code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Deriving.Traverse(deriveFunctor,deriveFoldable,deriveTraversable) where import Deriving.Type import Deriving.Util import FrontEnd.HsSyn import FrontEnd.Syn.Q import FrontEnd.Syn.Traverse() import FrontEnd.Warning import Name.Names import Support.FreeVars import Util.Std import qualified Data.Set as Set isRight Right {} = True isRight _ = False deriveFunctor :: Derive -> Module -> Data -> Q HsDecl deriveFunctor der@Derive {..} mod d@D { vars = [], .. } = do warn deriveSrcLoc InvalidDecl "Attempt to derive Functor for type without parameters" mkInstN 1 der mod d undefined [] deriveFunctor der@Derive {..} mod d@D { body = [], .. } = do (HsVar -> fe,fp) <- newVarN "x" Nothing let hsMatchSrcLoc = deriveSrcLoc hsMatchPats = [HsPWildCard,fp] hsMatchRhs = HsUnGuardedRhs fe f hsMatchName = HsMatch { .. } hsMatchDecls = [] mkInstN 1 der mod d class_Functor [HsFunBind [f v_fmap],HsFunBind [f v_fmap_const]] deriveFunctor der@Derive {..} mod d@D { vars = reverse -> ~(fv:_), .. } = do let mkMatch func b@Body { .. } = do (HsVar -> fe,fp) <- newVarN "f" Nothing (pa,es) <- mkPat mod b let dt (e,HsTyVar t) | t == fv, func == v_fmap = return $ HsApp fe e dt (e,HsTyVar t) | t == fv = return fe dt (e,HsTyApp x (HsTyVar t)) | t == fv, fv `Set.notMember` freeVars x = return $ app2 (HsVar func) fe e dt (e,t) | fv `Set.notMember` freeVars t = return e dt (e,t) = do warn deriveSrcLoc InvalidDecl "Cannot Derive Functor class for type" return e as <- mapM dt (zip es $ map hsBangType types) let hsMatchRhs | null types = HsUnGuardedRhs (HsCon constructor) | otherwise = HsUnGuardedRhs $ foldl1 HsApp (HsCon constructor:as) hsMatchName = func hsMatchDecls = [] return HsMatch { hsMatchPats = [fp,pa], .. } hsMatchSrcLoc = deriveSrcLoc bs <- mapM (mkMatch v_fmap) body bsc <- mapM (mkMatch v_fmap_const) body mkInstN 1 der mod d class_Functor [HsFunBind bs,HsFunBind bsc] deriveFoldable :: Derive -> Module -> Data -> Q HsDecl deriveFoldable der@Derive {..} mod d@D { vars = [], .. } = do warn deriveSrcLoc InvalidDecl "Attempt to derive Foldable for type without parameters" mkInstN 1 der mod d undefined [] deriveFoldable der@Derive {..} mod d@D { body = [], .. } = do -- (HsVar -> fe,fp) <- newVarN "x" Nothing let hsMatchSrcLoc = deriveSrcLoc hsMatchPats = [HsPWildCard,HsPWildCard] hsMatchRhs = HsUnGuardedRhs $HsVar v_mempty hsMatchName = v_foldMap fun = HsMatch { .. } hsMatchDecls = [] mkInstN 1 der mod d class_Functor [HsFunBind [fun]] deriveFoldable der@Derive {..} mod d@D { vars = reverse -> ~(fv:_), .. } = do let mkMatch func b@Body { .. } = do (HsVar -> fe,fp) <- newVarN "f" Nothing (pa,es) <- mkPat mod b let dt (e,HsTyVar t) | t == fv, func == v_foldMap = return [HsApp fe e] dt (e,HsTyVar t) | t == fv = return [e] dt (e,HsTyApp x (HsTyVar t)) | t == fv, fv `Set.notMember` freeVars x = if func == v_foldMap then return [ app2 (HsVar func) fe e] else return [ HsApp (HsVar func) e] dt (e,t) | fv `Set.notMember` freeVars t = return [] dt (e,t) = do warn deriveSrcLoc InvalidDecl "Cannot Derive Foldable class for type" return [e] as <- concat <$> mapM dt (zip es $ map hsBangType types) let hsMatchRhs | null as = HsUnGuardedRhs (HsVar v_mempty) | otherwise = HsUnGuardedRhs $ foldr1 (app2 (HsVar v_mappend)) as hsMatchName = func hsMatchDecls = [] return HsMatch { hsMatchPats = if func == v_foldMap then [fp,pa] else [pa], .. } hsMatchSrcLoc = deriveSrcLoc bs <- mapM (mkMatch v_foldMap) body bsc <- mapM (mkMatch v_fold) body mkInstN 1 der mod d class_Functor [HsFunBind bs,HsFunBind bsc] deriveTraversable :: Derive -> Module -> Data -> Q HsDecl deriveTraversable der@Derive {..} mod d@D { vars = [], .. } = do warn deriveSrcLoc InvalidDecl "Attempt to derive Traversable for type without parameters" mkInstN 1 der mod d undefined [] deriveTraversable der@Derive {..} mod d@D { body = [], .. } = do -- (HsVar -> fe,fp) <- newVarN "x" Nothing let hsMatchSrcLoc = deriveSrcLoc hsMatchPats = [HsPWildCard,HsPWildCard] hsMatchRhs = HsUnGuardedRhs $HsVar v_mempty hsMatchName = v_foldMap fun = HsMatch { .. } hsMatchDecls = [] mkInstN 1 der mod d class_Functor [HsFunBind [fun]] deriveTraversable der@Derive {..} mod d@D { vars = reverse -> (fv:_), .. } = do let mkMatch func b@Body { .. } = do (HsVar -> fe,fp) <- newVarN "f" Nothing (pa,es) <- mkPat mod b let dt (e,HsTyVar t) | t == fv, func == v_traverse = return $ Right (HsApp fe e) dt (e,HsTyVar t) | t == fv = return $ Right e dt (e,HsTyApp x (HsTyVar t)) | t == fv, fv `Set.notMember` freeVars x = return . Right $ if func == v_traverse then (app2 (HsVar func) fe e) else (HsApp (HsVar func) e) dt (e,t) | fv `Set.notMember` freeVars t = return $ Left e dt (e,t) = do warn deriveSrcLoc InvalidDecl "Cannot Derive Traversable class for type" return $ Left e as <- mapM dt (zip es $ map hsBangType types) let pullLeft as = f as [] where f (Left x:xs) rs = f xs (x:rs) f xs rs = (reverse rs,xs) (rs',xs') = pullLeft as bval = foldl1 HsApp (HsCon constructor:rs') lstar = HsVar v_lstar hsMatchPats = if func == v_traverse then [fp,pa] else [pa] hsMatchName = func appxs bv = foldl1 (app2 lstar) (app2 (HsVar v_fmap) bv x:[ x | Right x <- xs]) where (Right x:xs) = xs' let scont rhs = return ans where ans = HsMatch { .. } hsMatchRhs = HsUnGuardedRhs rhs hsMatchDecls = [] case () of () | null xs' -> scont $ HsApp (HsVar v_pure) bval | all isRight xs' -> scont $ appxs bval | otherwise -> do (gname,ge) <- newVarN "g" Nothing vs <- replicateM (length xs') (newVarN "v" Nothing) let hsMatchRhs = HsUnGuardedRhs $ appxs ge hsMatchDecls = [HsFunBind [HsMatch { .. }]] where hsMatchName = gname hsMatchDecls = [] hsMatchPats = [ p | ((_,p),Right _) <- zip vs xs' ] hsMatchRhs = HsUnGuardedRhs $ foldl1 HsApp (bval:zipWith f vs xs') where f (_,_) (Left e) = e f (n,_) Right {} = HsVar n return HsMatch { .. } hsMatchSrcLoc = deriveSrcLoc bs <- mapM (mkMatch v_traverse) body bsc <- mapM (mkMatch v_sequenceA) body mkInstN 1 der mod d class_Functor [HsFunBind bs,HsFunBind bsc] deriveTraversable der@Derive {..} mod d@D { .. } = do mkInstN 1 der mod d undefined []
hvr/jhc
src/Deriving/Traverse.hs
mit
7,650
8
21
2,675
2,865
1,442
1,423
-1
-1
{-# OPTIONS_GHC -fexcess-precision #-} -- -- The Computer Language Shootout -- http://shootout.alioth.debian.org/ -- -- Contributed by Olof Kraigher, with help from Don Stewart. -- -- Compile with: -- -- -funbox-strict-fields -fglasgow-exts -fbang-patterns -O3 -- -optc-O3 -optc-mfpmath=sse -optc-msse2 -optc-march=pentium4 -- import Foreign import Foreign.Storable import Foreign.Marshal.Alloc import Data.IORef import Control.Monad import System import Text.Printf main = do n <- getArgs >>= readIO.head initialize offset_momentum energy 0 planets >>= printf "%.9f\n" replicateM_ n (advance planets) energy 0 planets >>= printf "%.9f\n" return () offset_momentum = do m <- foldr (.+.) (Vec 0 0 0) `fmap` (mapM momentum . take (nbodies - 1) . iterate next $ next planets) setVec (vel planets) $ (-1/solar_mass) *. m where momentum p = p `seq` liftM2 (*.) (mass p) (getVec (vel p)) energy :: Double -> Ptr Double -> IO Double energy e p | e `seq` p `seq` False = undefined | p == end = return e | otherwise = do p1 <- getVec (pos p) v1 <- getVec (vel p) m1 <- mass p e <- energy2 p1 m1 e p2 energy (e + 0.5 * m1 * magnitude2 v1) p2 where p2 = next p energy2 p1 m1 e p | p1 `seq` m1 `seq` e `seq` p `seq` False = undefined | p == end = return e | otherwise = do p2 <- getVec (pos p) v2 <- getVec (vel p) m2 <- mass p let distance = sqrt . magnitude2 $ p1 .-. p2 energy2 p1 m1 (e - m1 * m2 / distance) (next p) advance :: Ptr Double -> IO () advance p1 | p1 `seq` False = undefined advance p1 = when (p1 /= end) $ do pos1 <- getVec $ pos p1 m1 <- mass p1 let go p2 | p2 `seq` False = undefined | p2 /= end = do pos2 <- getVec (pos p2) m2 <- mass p2 let vel2 = vel p2 difference = pos1 .-. pos2 distance2 = magnitude2 difference distance = sqrt distance2 magnitude = delta_t / (distance2 * distance) mass_magn = magnitude *. difference vel1 -= m2 *. mass_magn vel2 += m1 *. mass_magn go (next p2) | otherwise = do v1 <- getVec vel1 p1 += delta_t *. v1 go p2 advance p2 where vel1 = vel p1 p2 = next p1 ------------------------------------------------------------------------ planets :: Ptr Double planets = unsafePerformIO $ mallocBytes (7 * nbodies * 8) -- sizeOf double = 8 nbodies :: Int nbodies = 5 solar_mass, delta_t, days_per_year :: Double days_per_year = 365.24 solar_mass = 4 * pi ** 2; delta_t = 0.01 initialize = mapM_ newPlanet planets where dp = days_per_year planets = [0, 0, 0, 0, 0, 0, 1 * solar_mass, 4.84143144246472090e+00, (-1.16032004402742839e+00), (-1.03622044471123109e-01), 1.66007664274403694e-03*dp, 7.69901118419740425e-03*dp, (-6.90460016972063023e-05)*dp, 9.54791938424326609e-04 * solar_mass, 8.34336671824457987e+00, 4.12479856412430479e+00, (-4.03523417114321381e-01), (-2.76742510726862411e-03)*dp, 4.99852801234917238e-03*dp, 2.30417297573763929e-05*dp, 2.85885980666130812e-04 * solar_mass, 1.28943695621391310e+01, (-1.51111514016986312e+01), (-2.23307578892655734e-01), 2.96460137564761618e-03*dp, 2.37847173959480950e-03*dp, (-2.96589568540237556e-05)*dp, 4.36624404335156298e-05 * solar_mass, 1.53796971148509165e+01, (-2.59193146099879641e+01), 1.79258772950371181e-01, 2.68067772490389322e-03*dp, 1.62824170038242295e-03*dp, (-9.51592254519715870e-05)*dp, 5.15138902046611451e-05 * solar_mass ] ------------------------------------------------------------------------ -- Support for 3 dimensional mutable vectors data Vector3 = Vec !Double !Double !Double cursor :: IORef (Ptr Double) cursor = unsafePerformIO $ newIORef planets end :: Ptr Double end = inc planets (nbodies * 7) next :: Ptr Double -> Ptr Double next = flip inc 7 inc :: Ptr Double -> Int -> Ptr Double inc ptr n = ptr `seq` n `seq` plusPtr ptr (n * 8) newPlanet :: Double -> IO () newPlanet d = d `seq` do ptr <- readIORef cursor pokeElemOff ptr 0 d writeIORef cursor (inc ptr 1) pos :: Ptr Double -> Ptr Double pos ptr = ptr vel :: Ptr Double -> Ptr Double vel ptr = inc ptr 3 mass :: Ptr Double -> IO Double mass = flip peekElemOff 6 ------------------------------------------------------------------------ (Vec x y z) .+. (Vec u v w) = Vec (x+u) (y+v) (z+w) (Vec x y z) .-. (Vec u v w) = Vec (x-u) (y-v) (z-w) k *. (Vec x y z) = Vec (k*x) (k*y) (k*z) -- allocates magnitude2 (Vec x y z) = x*x + y*y + z*z ------------------------------------------------------------------------ getVec p = p `seq` liftM3 Vec (peek p) (f 1) (f 2) where f = peekElemOff p setVec p (Vec x y z)= do poke p x pokeElemOff p 1 y pokeElemOff p 2 z infix 4 += infix 4 -= v1 += (Vec u v w) = do x <- peek v1; poke v1 (x+u) y <- peekElemOff v1 1; pokeElemOff v1 1 (y+v) z <- peekElemOff v1 2; pokeElemOff v1 2 (z+w) v1 -= (Vec u v w) = do x <- peek v1; poke v1 (x-u) y <- peekElemOff v1 1; pokeElemOff v1 1 (y-v) z <- peekElemOff v1 2; pokeElemOff v1 2 (z-w)
hvr/jhc
regress/tests/8_shootout/nbody.hs
mit
5,545
0
19
1,583
2,034
1,025
1,009
141
1
module Util.Happstack (createJSONResponse) where import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy.Char8 as BSL import Happstack.Server import Data.Aeson (ToJSON, encode) -- | Creates a JSON response. createJSONResponse :: ToJSON a => a -> Response createJSONResponse x = toResponseBS (BS.pack "application/json") (encodeJSON x) where encodeJSON :: ToJSON a => a -> BSL.ByteString encodeJSON = BSL.filter (/= '\\') . encode
tamaralipowski/courseography
hs/Util/Happstack.hs
gpl-3.0
483
0
9
84
130
75
55
10
1
module SortingSpec ( main , spec ) where import qualified Data.Vector.Unboxed as VU import MLUtil import Test.Hspec spec :: Spec spec = do describe "argSort" $ do it "should return ordered indices" $ argSort (vector [40.0, 30.0, 10.0, 11.0]) `shouldBe` VU.fromList [2, 3, 1, 0] main :: IO () main = hspec spec
rcook/mlutil
mlutil/spec/SortingSpec.hs
mit
369
0
15
112
121
69
52
13
1
{-# LANGUAGE TemplateHaskell #-} -- | Test data. module Test.Orchid.Data ( factorial_ioSource , classSource , errorSource , global_varSource , type_errorSource , rectangleSource , private_var_insideSource , private_var_outsideSource , class_method_insideSource , private_method_insideSource , private_method_outsideSource , inheritanceSource , pointerSource , shapeSource , virtualSource , newSource , new_classSource , fibSource , factorialSource , mutually_recursiveSource , factorial_hugeSource ) where import Data.FileEmbed (embedStringFile) import Data.String (IsString) import Test.Orchid.Util (testPath) factorial_ioSource :: IsString s => s factorial_ioSource = $(embedStringFile $ testPath "factorial_io.orc") classSource :: IsString s => s classSource = $(embedStringFile $ testPath "class.orc") errorSource :: IsString s => s errorSource = $(embedStringFile $ testPath "error.orc") global_varSource :: IsString s => s global_varSource = $(embedStringFile $ testPath "global_var.orc") type_errorSource :: IsString s => s type_errorSource = $(embedStringFile $ testPath "type_error.orc") rectangleSource :: IsString s => s rectangleSource = $(embedStringFile $ testPath "rectangle.orc") private_var_insideSource :: IsString s => s private_var_insideSource = $(embedStringFile $ testPath "private_var_inside.orc") private_var_outsideSource :: IsString s => s private_var_outsideSource = $(embedStringFile $ testPath "private_var_outside.orc") class_method_insideSource :: IsString s => s class_method_insideSource = $(embedStringFile $ testPath "class_method_inside.orc") private_method_insideSource :: IsString s => s private_method_insideSource = $(embedStringFile $ testPath "private_method_inside.orc") private_method_outsideSource :: IsString s => s private_method_outsideSource = $(embedStringFile $ testPath "private_method_outside.orc") inheritanceSource :: IsString s => s inheritanceSource = $(embedStringFile $ testPath "inheritance.orc") pointerSource :: IsString s => s pointerSource = $(embedStringFile $ testPath "pointer.orc") shapeSource :: IsString s => s shapeSource = $(embedStringFile $ testPath "shape.orc") virtualSource :: IsString s => s virtualSource = $(embedStringFile $ testPath "virtual.orc") newSource :: IsString s => s newSource = $(embedStringFile $ testPath "new.orc") new_classSource :: IsString s => s new_classSource = $(embedStringFile $ testPath "new_class.orc") fibSource :: IsString s => s fibSource = $(embedStringFile $ testPath "fib.orc") factorialSource :: IsString s => s factorialSource = $(embedStringFile $ testPath "factorial.orc") mutually_recursiveSource :: IsString s => s mutually_recursiveSource = $(embedStringFile $ testPath "mutually_recursive.orc") factorial_hugeSource :: IsString s => s factorial_hugeSource = $(embedStringFile $ testPath "factorial_huge.orc")
gromakovsky/Orchid
test/Test/Orchid/Data.hs
mit
3,215
0
8
699
693
363
330
110
1
module Y2018.M12.D18.Solution where {-- Read in 'diffs.txt' in this directory, then compute the final value after applying all these values from a starting value of 0. --} exDir, diffs :: FilePath exDir = "Y2018/M12/D18/" diffs = "diffs.txt" result :: FilePath -> IO Integer result = fmap (sum . map readNum . words) . readFile readNum :: String -> Integer readNum (s:n) = (if s == '-' then negate else id) (read n)
geophf/1HaskellADay
exercises/HAD/Y2018/M12/D18/Solution.hs
mit
421
0
10
77
112
63
49
8
2
-- Ref -- Terms: ref(ref create) / !(deref) / :=(assignment) / l(ref pos) (13.2) -- Types: Ref type / Storage type -- Change storage ===> Change environment (13.3) -- Exception -- Terms: Γ⊢undefined : T / try .. with ... / raise t -- Subtyping (λc) -- Types: Top (T <: Top) / Bottom (Bot <: T) -- Rules: width / depth / permutation -- Recursive type -- NatList = \mu X. <nil : Unit, cons : {Nat, X}> -- \mu X.T: 满足 X = [X -> \mu X.T]T 的无穷类型 -- equi-recursive -- iso-recursive -- Fold [\mu X.T] -> \mu X.T -> [X -> \mu X.T]T -- U = \mu X.T \Gamma |- t : [X -> U] T -- --------------------------------------- -- \Gamma |- fold [U] t : U -- NLBody = <nil : Unit, cons : {Nat, NatList}> -- nil = fold [NatList] (<nil = Unit> as NLBody) -- cons = \n : Nat -> \l: NatList -> fold [NatList] <cons = {n, l}> as NLBody -- Unfold [\mu X.T] -> [X -> \mu X.T] T -> \mu X.T -- U = \mu X.T \Gamma |- t : U -- --------------------------------------- -- \Gamma |- unfold [U] t : [X -> U]T -- Polymorphism -- In general, the context now associates each free variable with a type scheme, not just a type. -- \Gamma |- t : S | C -- (\sigma, T) ==> \sigma satisfy C and \sigma S = T -- unificaiton -- principle types -- let polymorphism -- 1. We use the constraint typing rules to calculate a type S1 and a set C1 of associated constraints for the right-hand side t1. -- 2. We use unification to find a most general solution σ to the constraints C1 and apply σ to S1 (and Γ) to obtain t1’s principal type T1. -- 3. We generalize any variables remaining in T1. If X1. . .Xn are the remaining variables, we write ∀X1...Xn.T1 for the principal type scheme of t1 -- 4. We extend the context to record the type scheme ∀X1...Xn.T1 for the bound variable x, and start typechecking the body t2. In general, the context now associates each free variable with a type scheme, not just a type. -- 5. Each time we encounter an occurrence of x in t2, we look up its type scheme ∀X1...Xn.T1. We now generate fresh type variables Y1...Yn and use them to instantiate the type scheme, yielding [X1 , Y1, ..., Xn , Yn]T1, which we use as the type of x. -- System F -- \lambda X.t t[T] type abstraction -- Universal type -- Existential type -- {*S, t} as {\exists X, {t : X}} S satisfy X -- {\exists X, T} === \forall Y. (\forall X. T -> Y) -> Y -- {*S, t} as {\exists X, T} === \lambda Y. \lambda f : (\forall X. T -> Y). f[S] t -- let {X, x} = t1 in t2 === t1 [T2] (\lambda X. \lambda x : T11. t2) -- counterADT = {*Nat, {new = 1, get = \i:Nat i, inc = \i:Nat, succ(i)}} -- counterADT : {\exists Counter, {new:Counter, get:Counter->Nat}, ...} -- let {Counter, counter} = counterADT in .... -- Counter is ADT, counterADT is OOP -- System F_{<:} -- \lambda X <: T. t -- \forall X <: T. T -- \Gamma, X <: T -- System F_{\omega} -- X: Kind -- \lambda X::K.T -- \Gamma, X::K -- * / K -> K -- \forall X :: K. T ===>(K == *) \forall X . T -- |\exists X :: K, T| ===>(K == *) |\exists X, T| -- Lambda Cube -- ref: https://cs.stackexchange.com/questions/49189/what-terms-type-systems-exclude/49381#49381 -- ref: https://cstheory.stackexchange.com/questions/36054/how-do-you-get-the-calculus-of-constructions-from-the-other-points-in-the-lambda/36058#36058 -- ref: https://stackoverflow.com/questions/21219773/are-ghcs-type-famlies-an-example-of-system-f-omega -- terms depend on terms (normal functional programming) \x -> x -- terms depend on types (polymorphism) Head : [X] -> X -- types depend on types (type operator / type families) List<T> : X -> [X] K1 -> K2 -- types depend on terms (dependent types) Array<U, N> : N -> U^N -- λ→ (Simply-typed lambda calculus) -- λω_ (STLC + higher-kinded type operators) -- \lambda a : K. t -- λ2 (System F: STLC + poly) -- ∀a:k. A -- Λa:k. e + e [A] -- can represent \x. x x -- λω (System F-omega: STLC + poly(parametric) + type operator) -- λP (LF: STLC + dependent type) -- Πx:A. B(x) (arugment in return type) -- λP2 (no special name: + dt + poly) -- λPω_ (no special name: + dt + type operator) -- λPω (the Calculus of Constructions: all) -- what's not include is subtyping (X <: Y) -- HM is part of System F -- System F^{\omega}_{<:}
Airtnp/Freshman_Simple_Haskell_Lib
Intro/TAPL/miscs.hs
mit
4,605
0
2
1,197
86
85
1
1
0
{-| - Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: - - 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... - - By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. - -} sumEvenFibLessThan :: Integer -> Integer sumEvenFibLessThan = sum . filter even . fibsLessThan fibsLessThan n = takeWhile (< n) fibs fibs = 1:1:zipWith (+) fibs (tail fibs) -- sumEvenFibLessThan 4000000
MakerBar/haskell-euler
2/2.hs
mit
562
2
9
127
77
39
38
4
1
#!/usr/local/bin/runghc -i/home/martyn/bin/hlib -- base -------------------------------- import qualified System.Environment as SysEnv import Control.Exception ( tryJust ) import Control.Monad ( guard ) import System.Exit ( ExitCode( ExitFailure ) , exitSuccess, exitWith ) import System.IO.Error ( isDoesNotExistError ) import System.IO.Unsafe ( unsafePerformIO ) -- rainbow ----------------------------- import Rainbow ( back, chunk, fore, red, white ) -- this package -------------------------------------------- import Test.TAP ( diag, explain, is, like, okay, test_ ) -------------------------------------------------------------------------------- -- exit ------------------------------------------------------------------------ -- | akin to C's _exit(int); exit process with a given value exit :: Int -> IO a exit 0 = exitSuccess exit e = _exit e _exit :: Int -> IO a _exit = exitWith . ExitFailure -- getenv ------------------------------ getEnv :: String -> Maybe String getEnv e = unsafePerformIO $ do en <- tryJust (guard . isDoesNotExistError) $ SysEnv.getEnv e either (\ _ -> return Nothing) (return . Just) en -- main -------------------------------- main :: IO() main = do -- prove/TAP doesn't likes the plan to be the very first thing it sees; even -- before any diagnostic case getEnv "PROVE" of Nothing -> diag "before the rain" Just "1" -> return () _ -> diag "before the rain" ex <- test_ [ okay True "-ok test-" ["some diag"] , okay False "-not ok test-" ["some more diag"] , okay undefined "-explode-" ["bang"] , diag "" , diag "this is a diagnostic string" , diag [ chunk "this is a " , fore red $ back white $ chunk "red" , chunk " word" ] , diag ["some", "lines"] , is "foo" "foo" "-is test-" -- show diff strings! , is "foo" "baroo" "-is not test-" , like ([1,2,3] :: [Int]) [1,2,3] "-like-" , like ([1,2,3,6] :: [Int]) [5,1,4,3] "-not like-" ] explain "after the deluge" ([1,2,3] :: [Int]) exit ex
sixears/test-tap
t/Test.hs
mit
2,322
0
14
690
558
309
249
39
3
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module Bio.Data.Fasta ( FastaLike(..) , fastaReader ) where import Bio.Motif import Bio.Seq import qualified Data.ByteString.Char8 as B import Conduit class FastaLike f where -- | Convert a FASTA record, consisting of a record header and a record body, -- to a specific data type fromFastaRecord :: (B.ByteString, [B.ByteString]) -> f readFasta :: FilePath -> ConduitT i f (ResourceT IO) () readFasta fl = fastaReader fl .| mapC fromFastaRecord -- | non-stream version, read whole file in memory readFasta' :: FilePath -> IO [f] readFasta' fl = runResourceT $ runConduit $ readFasta fl .| sinkList {-# MINIMAL fromFastaRecord #-} instance BioSeq s a => FastaLike (s a) where fromFastaRecord (_, xs) = case fromBS (B.concat xs) of Left err -> error err Right x -> x {-# INLINE fromFastaRecord #-} instance FastaLike Motif where fromFastaRecord (name, mat) = Motif name (toPWM mat) {-# INLINE fromFastaRecord #-} fastaReader :: FilePath -> ConduitT i (B.ByteString, [B.ByteString]) (ResourceT IO) () fastaReader fl = sourceFile fl .| linesUnboundedAsciiC .| loop [] where loop acc = do x <- await case x of Just l -> case () of _ | B.null l -> loop acc -- empty line, go to next line | B.head l == '>' -> output (reverse acc) >> loop [B.tail l] | otherwise -> loop (l:acc) Nothing -> output $ reverse acc output (x:xs) = yield (x, xs) output _ = return () {-# INLINE fastaReader #-}
kaizhang/bioinformatics-toolkit
bioinformatics-toolkit/src/Bio/Data/Fasta.hs
mit
1,661
0
20
451
503
258
245
38
3
-- mktwit.hs: Cuts a set of text down to chunks of no more than 140 characters suitable for tweeting. {-# LANGUAGE DeriveDataTypeable, OverloadedStrings, BangPatterns #-} import qualified Data.ByteString.Lazy.Char8 as L import Data.Int(Int64) import Control.Monad import System.Console.CmdLib data Main = Main { infile :: String , outfile :: String } deriving(Typeable, Data, Eq) instance Attributes Main where attributes _ = group "Options" [ infile %> [ Help "File to be converted to tweets", ArgHelp "FILENAME", Short ['i'] ], outfile %> [ Help "File name for output, defaults to tweets.txt", ArgHelp "FILENAME", Short ['o'], Long ["out","output"] ] ] instance RecordCommand Main where mode_summary _ = "Cuts a set of text down to chunks of no more than 140 characters suitable for tweeting." main = getArgs >>= executeR Main {} >>= \opts -> do text <- L.readFile $ infile opts tweets <- return $ genTweets text L.writeFile (out opts) tweets where out opts | null $ outfile opts = "tweets.txt" | otherwise = outfile opts genTweets :: L.ByteString -> L.ByteString genTweets text | L.null text = "" | otherwise = L.intercalate "\n" $ genTweets' $ L.words text where genTweets' :: [L.ByteString] -> [L.ByteString] genTweets' [] = [] genTweets' [w] = [w] genTweets' (w:ws) = go (L.length w, w) ws go :: (Int64,L.ByteString) -> [L.ByteString] -> [L.ByteString] go (_len, !tweet) [] = [tweet] go (!len, !tweet) (w:ws) | wlen + len <= 139 = go (len + wlen + 1,w') ws | otherwise = tweet : go (wlen, w) ws where wlen = L.length w w' = tweet `L.append` " " `L.append` w
Hrothen/scripts
src/mktwit/mktwit.hs
mit
1,888
0
11
583
587
307
280
39
4
module SendMoreMoney (sendMoreMoney) where import Control.Monad (guard) import FD sendMoreMoney = runFD $ do vars@[s, e, n, d, m, o, r, y] <- news 8 (0, 9) s #\= 0 m #\= 0 allDifferent vars 1000 * s + 100 * e + 10 * n + d + 1000 * m + 100 * o + 10 * r + e #== 10000 * m + 1000 * o + 100 * n + 10 * e + y labelling vars bruteForce :: [[Int]] bruteForce = do s <- [1..9] e <- [0..9] n <- [0..9] d <- [0..9] let m = 1 o <- [0..9] r <- [0..9] y <- [0..9] guard (s /= e) guard (s /= n) guard (s /= d) guard (s /= m) guard (s /= o) guard (s /= r) guard (s /= y) guard (e /= n) guard (e /= d) guard (e /= m) guard (e /= o) guard (e /= r) guard (e /= y) guard (n /= d) guard (n /= m) guard (n /= o) guard (n /= r) guard (n /= y) guard (d /= m) guard (d /= o) guard (d /= r) guard (d /= y) guard (m /= o) guard (m /= r) guard (m /= y) guard (o /= r) guard (o /= y) guard (r /= y) guard (1000*s + 100*e + 10*n + d + 1000*m + 100*o + 10*r + e == 10000*m + 1000*o + 100*n + 10*e + y) return [s,e,n,d,m,o,r,y]
dmoverton/finite-domain
src/SendMoreMoney.hs
mit
1,200
0
30
456
793
391
402
53
1
-- ~~~~~~~~~~ Monadic FRW, lazy non path-tracking module Main where import Nilsson import Data.Array import System.Environment import Control.Monad.ST import Data.Array.ST type MyA s = STArray s (Int,Int) [(Capacity,Length)] frw n xs = runST $ do { xa <- nLA ((1,1),(n,n)) xs; xb <- nLA ((1,1),(n,n)) []; let loop(k,i,j) = if k > n then return () else if i > (n-1) then do transfer xb xa n 1 2 loop(k+1,1,2) else if j > n then loop (k,i+1,i+2) else do compute xa xb k i j loop(k,i,j+1) in loop(1,1,2); getElems xa } compute :: MyA s -> MyA s -> Int -> Int -> Int -> ST s () compute xa xb k i j = do ij <- readArray xa (i,j) ik <- readArray xa (i,k) kj <- readArray xa (k,j) -- ~~~~~~~~~~ Lazy non path tracking version ~~~~~ writeArray xb (i,j) (nch ij (njn ik kj)) -- ~~~~~~~~~~ Auxiliary functions nLA :: (Ix i) => (i,i) -> [e] -> ST s ((STArray s) i e) nLA = newListArray transfer :: MyA s -> MyA s -> Int -> Int -> Int -> ST s () transfer xb xa n i j = if i>(n-1) then return () else if j>n then transfer xb xa n (i+1) (i+2) else do tba xb xa i j transfer xb xa n i (j+1) tba :: MyA s -> MyA s -> Int -> Int -> ST s () tba xb xa i j = do ij <- readArray xb (i,j) writeArray xa (i,j) ij
jcsaenzcarrasco/MPhil-thesis
frwM.hs
mit
1,546
0
19
609
745
392
353
48
4
module LLVM.Codegen.GC ( sizeof, gcinit, gcmalloc, gccollect, gcdisable, gcdiagnostic, ) where import LLVM.General.AST import LLVM.Codegen.Types import LLVM.Codegen.Utils import LLVM.Codegen.Instructions import LLVM.Codegen.Builder import qualified LLVM.General.AST.Constant as C -- | Return the constant sizeof of a given type. sizeof :: Type -> Codegen Operand sizeof ty = return $ ConstantOperand $ C.PtrToInt (C.GetElementPtr True nullty off) ptr where off = [C.Int 32 1] nullty = C.Null $ pointer ty ptr = IntegerType $ fromIntegral bitsize gcinit :: Codegen Operand gcinit = ccall "GC_init" [] gcmalloc :: [Operand] -> Codegen Operand gcmalloc = ccall "GC_malloc" gccollect :: Codegen Operand gccollect = ccall "GC_gcollect" [] gcdisable :: Codegen Operand gcdisable = ccall "GC_disable" [] gcdiagnostic :: Codegen () gcdiagnostic = do heap <- ccall "GC_get_heap_size" [] free <- ccall "GC_get_free_bytes" [] total <- ccall "GC_get_free_bytes" [] -- debug "Heap: %d" heap -- debug "Free: %d" free -- debug "Total %d" total return ()
sdiehl/llvm-codegen
src/LLVM/Codegen/GC.hs
mit
1,099
0
9
209
310
167
143
33
1
{------------------------------------------------------------------------------- Let (a, b, c) represent the three sides of a right angle triangle with integral length sides. It is possible to place four such triangles together to form a square with length c. For example, (3, 4, 5) triangles can be placed together to form a 5 by 5 square with a 1 by 1 hole in the middle and it can be seen that the 5 by 5 square can be tiled with twenty-five 1 by 1 squares. However, if (5, 12, 13) triangles were used then the hole would measure 7 by 7 and these could not be used to tile the 13 by 13 square. Given that the perimeter of the right triangle is less than one-hundred million, how many Pythagorean triangles would allow such a tiling to take place? -------------------------------------------------------------------------------- Notation and definition: - Given a triangle T, let's (s, m, h) be the associated Pythagorean triple with s < m and s²+m²=h², i.e s is the length of the small, medium and hypotenuse side respectively. - A triangle is said to be 'valid' if it fulfils the condition. - By extension, a Pythagorean triple (s, m, h) is valid if the corresponding triangle is valid Given T(s, m, h), the length of the internal hole square side is m-s. Such a square allows covering the external square iif m-s | h. Note that it is enough to consider the primitive triples since, if a triple is valid, then km-ks | kh => m-s | h and thus the corresponding primitive is also valid. Let a = p²-q², b = 2pq and c = p²+q²; (s,m) = (a,b) if a<b or (b,a) if b<a. The perimeter P = a + b + c = 2 p² + 2 pq = 2p(p+q) ≤ 2*p(p-1) -------------------------------------------------------------------------------} import Data.List euler limit = foldl' (\acc p -> acc + quot limit p) 0 perimeters where -- Perimeters is the list of perimeters from primitive triangles that fulfil -- the criterion. perimeters = [ perim | p <- takeWhile (\p -> 2*p*(p-1) < limit) [1 ..] , q <- [p-1, p-3 .. 1] , 1 == gcd p q , let p² = p*p , let q² = q*q , let a = p² - q² , let b = 2*p*q , let h = p² + q² , rem h (abs (b-a)) == 0 , let perim = a + b + h , perim < limit ] main = do putStrLn $ concat $ ["Euler 139: ", show $ euler (10^8)]
dpieroux/euler
0139.hs
mit
2,493
16
18
684
305
160
145
16
1
module Y2018.M04.D05.Solution where {-- We're basically rewriting Store.SQL.Connection. Good module, if you only have one database to manage, but now I have multiple SQL databases, so I have to make all these functions confirgurable. --} import Database.PostgreSQL.Simple import System.Environment -- let's codify which databases we're talking about here: data Database = WPJ | PILOT -- ... and we just add as we grow our scope deriving (Eq, Show) -- these functions get your database's information from the environment dbUserName, dbPassword, dbmsServer, dbName :: Database -> IO String dbUserName = ge "USERNAME" dbPassword = ge "PASSWORD" dbmsServer = ge "SERVER_URL" dbName = ge "DB_NAME" ge :: String -> Database -> IO String ge str dbname = getEnv ("SQL_DAAS_" ++ str ++ ('_':show dbname)) dbPort :: Database -> IO Int dbPort = fmap read . ge "SERVER_PORT" -- and with those we can do this: connectInfo :: Database -> IO ConnectInfo connectInfo dbname = ConnectInfo <$> dbmsServer dbname <*> (fromIntegral <$> dbPort dbname) <*> dbUserName dbname <*> dbPassword dbname <*> dbName dbname -- and with that we can do this: withConnection :: Database -> (Connection -> IO a) -> IO () withConnection db fn = connectInfo db >>= connect >>= \conn -> fn conn >> close conn -- with all that now connect to your database and do something cutesies -- ('cutesies' is a technical term) -- this module will replace Store.SQL.Connection
geophf/1HaskellADay
exercises/HAD/Y2018/M04/D05/Solution.hs
mit
1,526
0
11
328
302
160
142
22
1
module P006 where import Euler solution :: EulerType solution = Left $ (sumN1 100) ^ 2 - sumN2 100 main = printEuler solution
Undeterminant/euler-haskell
P006.hs
cc0-1.0
126
0
9
23
46
25
21
5
1
-- An artificial bee colony algorithm for the maximally diverse grouping problem -- Francisco J. Rodriguez, M. Lozano, C. Garcia-martinez, -- Jonathan D. Gonzalez-Barrera -- January 2013 import System.Random import System.Environment import Data.Ord import Data.List import qualified Data.Map as Map import qualified Data.Set as Set import Data.Maybe import Data.IORef import System.Timeout import Debug.Trace (trace) import System.Directory import Control.Monad mkset :: Ord a => a -> a -> Set.Set a mkset x y = Set.fromList [x, y] type Distances = Map.Map (Set.Set Element) Double type Element = String type Elements = [Element] data Group = MkGroup {ag::Integer, bg::Integer, members::Elements} deriving (Show, Eq) type Groups = [Group] type Solution = [Group] main :: IO () main = do home <- getHomeDirectory geo <- getDirectoryContents $ home ++ "/mdgplib/Geo/" let geoN = sort $ filter (\s -> (isInfixOf "_01." s) && ((isInfixOf "120" s) || (isInfixOf "240" s) || (isInfixOf "480" s))) geo let geoM = map ((home ++ "/mdgplib/Geo/") ++) geoN runlimitndp 20 0 [no1] geoM runlimitndp :: Integer -> Double -> [(Distances -> Solution -> Integer -> StdGen -> (Solution, StdGen))] -> [FilePath] -> IO () runlimitndp _ _ _ _ | trace ("rlndp") False = undefined runlimitndp np pls nos (filename:fs) | isInfixOf "120" filename = do makeAndPrint 120 runlimitndp np pls nos fs | isInfixOf "240" filename = do makeAndPrint 240 runlimitndp np pls nos fs | isInfixOf "480" filename = do makeAndPrint 240 runlimitndp np pls nos fs where printem n [] = do return () printem n ((limit,ndp,sol):rest) = do theSol <- sol print $ show n ++ "--" ++ show limit ++ "--" ++ show ndp ++ ": " ++ show theSol printem n rest makeAndPrint n = printem n [(limit, ndp, runOnce limit np ndp pls nos 3 filename) | limit <- [(quot n 10), (quot n 5)..(quot n 2)], ndp <- [(quot n 2), n, 2*n]] runOnce :: Integer -> Integer -> Integer -> Double -> [(Distances -> Solution -> Integer -> StdGen -> (Solution, StdGen))] -> Integer -> String -> IO Double runOnce limit np ndp pls nos tmax_s filename = do file <- readFile filename let (header:dists) = lines file let (nstring:(mstring:(grouptypestring:grouplimitstrings))) = words header let n = read nstring :: Integer let m = read mstring :: Integer let grouplimits = map (\x -> read x :: Integer) grouplimitstrings let groups = groups_from_limits grouplimits let distances = map_from_list dists let elems = nub $ concatMap (\x -> take 2 $ words x) dists best_solution <- abc distances elems groups limit np ndp pls nos (fromInteger (1000000*tmax_s)) bs <- readIORef best_solution return (fitness distances bs) groups_from_limits :: [Integer] -> Groups groups_from_limits [] = [] groups_from_limits (ag:(bg:limits)) = (MkGroup ag bg []):(groups_from_limits limits) map_from_list :: [String] -> Distances map_from_list [] = Map.empty map_from_list (pair:pairs) = Map.insert key value (map_from_list pairs) where [elem1, elem2, diststring] = words pair key = mkset elem1 elem2 value = read diststring :: Double abc :: Distances -> Elements -> Groups -> Integer -> Integer -> Integer -> Double -> [(Distances -> Solution -> Integer -> StdGen -> (Solution, StdGen))] -> Int -> IO (IORef Solution) -- Initialization phase abc distances elems groups limit np ndp pls nos tmax = do --print "abc" best_sol <- newIORef (best_solution_found distances initial_sols) timeout tmax (seq initial_sols $ abc_ distances elems groups limit ndp pls nos iterations initial_sols nrng best_sol) return best_sol where rng = mkStdGen 123 (nrng, initial_sols) = init_solutions distances elems groups np pls rng iterations = zipWith const [0..] initial_sols abc_ :: Distances -> Elements -> Groups -> Integer -> Integer -> Double -> [(Distances -> Solution -> Integer -> StdGen -> (Solution, StdGen))] -> [Integer] -> [Solution] -> StdGen -> IORef Solution -> IO () abc_ distances elems groups limit ndp pls nos iterations sols rng best_sol = do --print "abc_" --print sols --print $ best_solution_found distances sols modifyIORef' best_sol ((best_solution_found distances) . (flip (:) nsols)) --print niterations abc_ distances elems groups limit ndp pls nos (map (+1) niterations) nsols nrng best_sol where (nsols, niterations, nrng) = abc__ distances elems groups limit ndp pls nos iterations sols rng abc__ :: Distances -> Elements -> Groups -> Integer -> Integer -> Double -> [(Distances -> Solution -> Integer -> StdGen -> (Solution, StdGen))] -> [Integer] -> [Solution] -> StdGen -> ([Solution], [Integer], StdGen) abc__ distances elems groups limit ndp pls nos iterations sols rng = (uncurry scouting) $ (uncurry onlooking) $ (employing sols rng) where employing = employed distances ndp pls nos onlooking = onlooker distances ndp pls nos scouting = scout distances elems groups pls limit iterations employed :: Distances -> Integer -> Double -> [(Distances -> Solution -> Integer -> StdGen -> (Solution, StdGen))] -> [Solution] -> StdGen -> ([Solution], StdGen) employed distances ndp pls nos cur_sols rng = (map (\sol -> let (neighbour_sol, trng) = generate_neighbouring distances sol ndp nos rng (imp_sol, ttrng) = local_improvement distances pls neighbour_sol trng in if fitness distances imp_sol > fitness distances sol then imp_sol else sol) cur_sols, refresh rng rn) where (rn, _) = randomR (1, 1000) rng onlooker :: Distances -> Integer -> Double -> [(Distances -> Solution -> Integer -> StdGen -> (Solution, StdGen))] -> [Solution] -> StdGen -> ([Solution], StdGen) onlooker distances ndp pls nos cur_sols rng = onlooker_ distances cur_sols ndp pls nos rng (toInteger $ length cur_sols) onlooker_ :: Distances -> [Solution] -> Integer -> Double -> [(Distances -> Solution -> Integer -> StdGen -> (Solution, StdGen))] -> StdGen -> Integer -> ([Solution], StdGen) onlooker_ distances cur_sols ndp pls nos rng 0 = (cur_sols, rng) onlooker_ distances cur_sols ndp pls nos rng count = if fitness distances imp_sol > fitness distances sol then onlooker_ distances (imp_sol:(delete sol cur_sols)) ndp pls nos ttrng (count-1) else onlooker_ distances cur_sols ndp pls nos ttrng (count-1) where (sol, trng) = binary_tournament distances cur_sols rng (neighbour_sol, ttrng) = generate_neighbouring distances sol ndp nos trng (imp_sol, tttrng) = local_improvement distances pls neighbour_sol ttrng scout :: Distances -> Elements -> Groups -> Double -> Integer -> [Integer] -> [Solution] -> StdGen -> ([Solution], [Integer], StdGen) scout distances elems groups pls limit iterations cur_sols rng = (sols ++ nsols, orig_iters ++ niters, nrng) where (sols, orig_iters) = unzip $ filter (\(s, iters) -> iters < limit) (zip cur_sols iterations) (nrng, nsols) = init_solutions distances elems groups (toInteger $ length cur_sols - length sols) pls rng niters = take (length cur_sols - length sols) [0..] refresh :: StdGen -> Integer -> StdGen refresh rng 0 = rng refresh rng n = refresh nrng (n-1) where (_, nrng) = random rng :: (Double, StdGen) init_solutions :: Distances -> Elements -> Groups -> Integer -> Double -> StdGen -> (StdGen, [Solution]) init_solutions distances elems groups 0 _ rng = (rng,[]) init_solutions distances elems groups np pls rng = (nrng, map (\s -> fst $ local_improvement distances pls s nrng) (sol:sols)) where (trng, sol) = construct_solution distances elems groups rng (nrng, sols) = init_solutions distances elems groups (np - 1) pls trng construct_solution :: Distances -> Elements -> Groups -> StdGen -> (StdGen, Solution) construct_solution distances elems groups rng = {- trace (show "cs: " ++ show elems ++ "\n" ++ show ngroups)-} (nrng, ngroups) where ([], ngroups, nrng) = if (1 == length groups_m) then error "consol" else fill distances elems_m groups_m rng_m (elems_m, groups_m, rng_m) = choose_m distances elems groups rng -- Wijs elk element in elements toe aan een groep uit groups fill :: Distances -> Elements -> Groups -> StdGen -> (Elements, Groups, StdGen) --fill _ es gs _ | trace (show es ++ "\n" ++ show gs ++ "\n") False = undefined fill _ es [g] _ = error $ (show es) ++ (show g) fill distances [] groups rng = ([], groups, rng) fill distances elems groups rng = fill distances nelems (nrgroup:restGroups) nrng where -- Als alle groepen in gs nog niet tot aan ag gevuld zijn vul tot ag -- anders vul tot bg gfilter gs | (smaller ag) gs /= [] = (smaller ag) gs | otherwise = (smaller bg) gs smaller boundFun = filter (\g -> length (members g) < (fromInteger $ boundFun g)) -- Kies een random element uit de nog niet genoeg gevulde groepen (rgroup, restG, nrng) = if not $ null $ gfilter groups then randomElem (gfilter groups) rng else error $ show groups ++ show (gfilter groups) restGroups = delete rgroup groups -- Kies het element dat het meeste diversiteit toevoegt nelem = maximumBy (comparing (\el -> diversity distances el $ members rgroup)) elems nelems = delete nelem elems nrgroup = ginsert rgroup nelem randomElem :: Eq a => [a] -> StdGen -> (a, [a], StdGen) randomElem [] _ = error "randomElem" randomElem [g] rng = (g, [], rng) randomElem gs rng = (rg, restgs, nrng) where (rindex, nrng) = randomR (0, (length gs) - 1) rng rg = gs!!rindex restgs = delete rg gs choose_m :: Distances -> Elements -> Groups -> StdGen -> (Elements, Groups, StdGen) choose_m distances elems [] rng = (elems, [], rng) choose_m distances elems (group:groups) rng = (nelems, ngroup:ngroups, nrng) where (relem, telems, trng) = randomElem elems rng ngroup = ginsert group relem (nelems, ngroups, nrng) = choose_m distances telems groups trng ginsert :: Group -> Element -> Group ginsert group el = group {members = el:(members group)} diversity :: Distances -> Element -> Elements -> Double diversity distances el group = sum $ map (fromJust . lu) group where lu e | e == el = Just 0 | otherwise = Map.lookup (mkset el e) distances fitness :: Distances -> Solution -> Double fitness distances = sum . map ((fitness_group distances) . members) fitness_group :: Distances -> Elements -> Double fitness_group distances [] = 0 fitness_group distances (el:rest_el) = diversity distances el rest_el + fitness_group distances rest_el local_improvement :: Distances -> Double -> Solution -> StdGen -> (Solution, StdGen) --local_improvement _ _ s_in _ = error $ show s_in local_improvement distances pls s_in rng | u < pls = (li_swap distances s_move s_move (members $ safehead s_move "locimp"), nrng) | otherwise = (s_in, rng) where (u, trng) = random rng :: (Double, StdGen) elems = sort $ Set.toList (Set.unions $ Map.keys distances) (s_move, nrng) = li_move distances pls s_in elems trng safehead :: [a] -> String -> a safehead [] s = error $ show s safehead (e:el) _ = e li_move :: Distances -> Double -> Solution -> Elements -> StdGen -> (Solution, StdGen) --li_move distances pls s_in els rng | -- trace ("lm: " ++ show els ++ "\n" ++ show s_in ++ "\n") False = undefined li_move distances pls s_in [] rng = (s_in, rng) li_move distances pls s_in (el:elems) rng | first_improv_index == Nothing = li_move distances pls s_in elems rng | otherwise = li_move distances pls (apply_transform s_in elgroup figroup $ move el elgroup figroup) all_elems rng where all_elems = sort $ Set.toList (Set.unions $ Map.keys distances) -- Groep waar el vandaan komt elgroup = safehead (filter (elem el . members) s_in) (show s_in) -- Lijst van toegevoegde fitnesses per groep als we el daar in zouden steken fs = map (\g -> - (diversity distances el $ members elgroup) + (diversity distances el $ members (snd $ move el elgroup g))) (filter (\g -> (toInteger . length . members $ g) < (bg g)) $ delete elgroup s_in) -- Eerste groep waarvoor we meer fitness krijgen door daarnaar te moven first_improv_index = if (toInteger . length $ members elgroup) <= (ag elgroup) then Nothing else findIndex (> 0) fs figroup = (s_in!!(fromJust first_improv_index)) move :: Element -> Group -> Group -> (Group, Group) -- move el og ng | -- trace ("move: " ++ show el ++ " " ++ show og ++ " " ++ show ng ++ "\n") False = undefined move el og ng = (og {members = (delete el $ members og)}, ng {members = el:(members ng)}) li_swap :: Distances -> Solution -> Groups -> Elements -> Solution li_swap distances s_in [g] elems = s_in li_swap distances s_in (group:groups) [] = li_swap distances s_in groups (members $ safehead groups "liswap-[]") li_swap distances s_in (group:groups) (el:elems) | first_improv_group_index == Nothing = li_swap distances s_in (group:groups) elems | otherwise = li_swap distances s_new s_new (members $ safehead s_new "liswap-other") where fs = map (\g -> map (\el2 -> let (ngroup, ng) = swap el el2 group g in - (diversity distances el $ members group) - (diversity distances el2 $ members g) + (diversity distances el $ members ng) + (diversity distances el2 $ members ngroup)) (members g)) groups first_improv_group_index = findIndex (isJust . findIndex (> 0)) fs first_improv_group = (groups!!(fromJust first_improv_group_index)) first_improv_index = findIndex (> 0) (fs!!(fromJust first_improv_group_index)) first_improv_elem = (members first_improv_group)!!(fromJust first_improv_index) s_new = apply_transform s_in group first_improv_group (swap el first_improv_elem group first_improv_group) swap :: Element -> Element -> Group -> Group -> (Group, Group) swap el1 el2 g1 g2 = (uncurry $ flip (move el2)) $ move el1 g1 g2 apply_transform :: Solution -> Group -> Group -> (Group, Group) -> Solution apply_transform s_in g1 g2 (ng1, ng2) = ng1:(ng2:(delete g1 (delete g2 s_in))) generate_neighbouring :: Distances -> Solution -> Integer -> [(Distances -> Solution -> Integer -> StdGen -> (Solution, StdGen))] -> StdGen -> (Solution, StdGen) generate_neighbouring distances s_in ndp nos rng = (s_out, nrng) where (rindex, trng) = randomR (0, length nos - 1) rng rno = nos!!rindex (s_out, nrng) = rno distances s_in ndp trng no1 :: Distances -> Solution -> Integer -> StdGen -> (Solution, StdGen) no1 distances s_in nd rng = (s_out, nrng) where (rn, trng) = randomR (1, nd) rng (groups, elems, ttrng) = no1_ distances s_in [] rn trng ([], s_out, nrng) = if (1 == length groups) then error "no1" else fill distances elems groups ttrng no1_ :: Distances -> Groups -> Elements -> Integer -> StdGen -> (Groups, Elements, StdGen) no1_ distances s_in elems 0 rng = (s_in, elems, rng) no1_ distances s_in elems n rng = no1_ distances (nrgroup:restGroups) (nelem:elems) (n-1) nrng where nemptygroups = filter (\g -> not $ null $ members g) s_in (rgroup, restG, trng) = randomElem nemptygroups rng restGroups = delete rgroup s_in (nelem, restElems, nrng) = randomElem (members rgroup) trng nrgroup = rgroup {members = restElems} no2 :: Distances -> Solution -> Integer -> StdGen -> (Solution, StdGen) no2 distances s_in nd rng = (s_out, nrng) where (rn, trng) = randomR (1, nd) rng (groups, elems) = no2_ distances s_in [] rn ([], s_out, nrng) = if (1 == length groups) then error "no2" else fill distances elems groups trng no2_ :: Distances -> Groups -> Elements -> Integer -> (Groups, Elements) no2_ distances groups elems 0 = (groups, elems) no2_ distances groups elems n = no2_ distances tgroups (nelem:elems) (n-1) where (tgroups, nelem) = least_diverse distances groups least_diverse :: Distances -> Groups -> (Groups, Element) least_diverse distances groups = (ngroups, nelem) where nelem = minimumBy (comparing (\el -> let containing_group = (safehead (filter ((elem el) . members) groups) "leadiv") in diversity distances el (delete el $ members containing_group))) (least_diverse_ distances groups) ngroups = map (\g -> if elem nelem $ members g then g {members = delete nelem $ members g} else g) groups least_diverse_ :: Distances -> Groups -> Elements least_diverse_ distances [] = [] least_diverse_ distances (group:groups) = (least_diverse__ distances group):(least_diverse_ distances groups) least_diverse__ :: Distances -> Group -> Element least_diverse__ distances group = minimumBy (comparing (\el -> diversity distances el (delete el $ members group))) (members group) no3 :: Distances -> Solution -> Integer -> StdGen -> (Solution, StdGen) no3 distances s_in p rng = no3_ distances s_in rp trng where (rp, trng) = randomR (1, p) rng no3_ :: Distances -> Groups -> Integer -> StdGen -> (Solution, StdGen) no3_ distances groups 0 rng = (groups, rng) no3_ distances groups q rng = no3_ distances ngroups (q-1) nrng where (rindex1, trng) = randomR (0, length groups - 1) rng rgroup1 = groups!!rindex1 (rindex2, ttrng) = randomR (0, length (delete rgroup1 groups) - 1) trng rgroup2 = (delete rgroup1 groups)!!rindex2 (rindex11, tttrng) = randomR (0, (length $ members rgroup1) - 1) ttrng relem1 = (members rgroup1)!!rindex11 (rindex21, nrng) = randomR (0, (length $ members rgroup2) - 1) tttrng relem2 = (members rgroup2)!!rindex21 ngroups = (rgroup1 {members = relem2:(delete relem1 (members rgroup1))}) :((rgroup2 {members = relem1:(delete relem2 (members rgroup2))}) :(delete rgroup1 (delete rgroup2 groups))) binary_tournament :: Distances -> [Solution] -> StdGen -> (Solution, StdGen) binary_tournament distances sols rng = (best_solution_found distances [rsol1, rsol2], nrng) where (rindex1, trng) = randomR (0, length sols - 1) rng rsol1 = sols!!rindex1 (rindex2, nrng) = randomR (0, length (delete rsol1 sols) - 1) trng rsol2 = (delete rsol1 sols)!!rindex2 best_solution_found :: Distances -> [Solution] -> Solution --best_solution_found distances = head best_solution_found distances = maximumBy (comparing (fitness distances))
jorenverspeurt/portfolio
Haskell/abc.hs
gpl-2.0
20,928
0
23
6,328
6,917
3,626
3,291
389
2
module HLinear.Test.Matrix.Basic where import HLinear.Utility.Prelude import Control.Applicative ( (<$>), (<*>), (<|>) ) import Math.Structure.Tasty import Test.Tasty import qualified Data.Vector as V import HLinear.Utility.NmbRowColumn import HLinear.Matrix ( Matrix ) import qualified HLinear.Matrix as M import HLinear.Matrix.Sized ( MatrixSized ) properties :: TestTree properties = testGroup "Basic properties" [ testPropertyQSnC 2 "m == m" $ \m -> (m :: Matrix Int) == m , testPropertyQSC "isZero (zero * v)" $ \v -> isZero $ (zero :: MatrixSized 3 3 FMPZ) *. (v :: MatrixSized 3 1 FMPZ) , testPropertyQSC "nmbRows/Cols .: zeroMatrix" $ \nrs ncs -> ( let m = M.zero nrs ncs :: Matrix Int in nrs < 0 || ncs < 0 || ( nmbRows m == nrs && nmbCols m == ncs ) ) , testPropertyQSC "nmbRows/Cols .: identityMatrix" $ \nrs -> ( let m = M.one nrs :: Matrix Int in nrs < 0 || ( nmbRows m == max 0 nrs && nmbCols m == max 0 nrs ) ) , testPropertyQSnC 2 "diagonalMatrix . * == * . diagonalMatrix" $ \abs -> ( let (as,bs) = V.unzip (abs :: Vector (Int,Int)) in (M.diagonal as) * (M.diagonal bs) == M.diagonal (V.map (uncurry (*)) abs) ) ]
martinra/hlinear
test/HLinear/Test/Matrix/Basic.hs
gpl-3.0
1,404
0
17
472
449
245
204
-1
-1
{- Math.Geom.Delaunay - Delaunay algorithm implementation. Copyright 2013 Alan Manuel K. Gloria This file is part of Merchant's Race. Merchant's Race is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Merchant's Race is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Merchant's Race. If not, see <http://www.gnu.org/licenses/>. -} {- Delaunay divide-and-conquer algorithm, from Guibas and Stolfi. -} {- NOTE: Will FAIL if using Double! Use Rational instead; inexact math (Double) does not give enough bits of precision. Supposedly, alternating the partition between horizontal and vertical will make it far more likely to succeed using inexact math, but that's beyond my capability. -} module Math.Geom.Delaunay ( delaunay ) where import Math.Geom.QuadEdge import Control.Monad import Control.Monad.ST import Data.List connect :: QE s (r,r) -> EdgeRef -> EdgeRef -> ST s EdgeRef connect qeds a b = do e <- makeEdge qeds putData qeds e =<< getData qeds (sym a) putData qeds (sym e) =<< getData qeds b lnext_a <- lnext qeds a splice qeds e lnext_a splice qeds (sym e) b return e delaunay :: (Ord r, Num r) => [(r,r)] -> ST s (QE s (r,r), EdgeRef, EdgeRef) delaunay points = do let sortedPoints = nub $ sortBy xycompare points qeds <- newQE (ledge, redge) <- delaunay1 qeds sortedPoints return (qeds, ledge, redge) where delaunay1 qeds = loop where loop [] = fail "Math.Geom.Delaunay.delaunay: pointless graph." loop [a] = fail "Math.Geom.Delaunay.delaunay: graph has one point." -- two-point case loop [a,b] = do e <- makeEdge qeds putData qeds e a putData qeds (sym e) b return (e, sym e) -- three-point case loop [a,b,c] = do -- Build the first two edges: {- . b e1 / \ e2 / \ a . . c -} e1 <- makeEdge qeds e2 <- makeEdge qeds splice qeds (sym e1) e2 putData qeds e1 a putData qeds (sym e1) b putData qeds e2 b putData qeds (sym e2) c -- Close the triangle let action | ccw a b c = do e3 <- connect qeds e2 e1 return (e1, sym e2) | ccw a c b = do e3 <- connect qeds e2 e1 return (sym e3, e3) | otherwise = do -- collinear return (e1, sym e2) action -- recursive case loop s = do let getOrgDst e = do org <- getData qeds e dst <- getData qeds (sym e) return (org, dst) -- Let l and r be the left and right halves of s. let (l, r) = splitList s (ldo, ldi) <- loop l; (rdi, rdo) <- loop r -- compute the lower common tangent of l and r: let lowerTangent ldi rdi = do (org_rdi, dst_rdi) <- getOrgDst rdi (org_ldi, dst_ldi) <- getOrgDst ldi let action | ccw org_rdi org_ldi dst_ldi = do lnext_ldi <- lnext qeds ldi lowerTangent lnext_ldi rdi | ccw org_ldi dst_rdi org_rdi = do rprev_rdi <- rprev qeds rdi lowerTangent ldi rprev_rdi | otherwise = do return (ldi, rdi) action (ldi, rdi) <- lowerTangent ldi rdi -- create a first cross edge base1 from rdi.Org to ldi.Org base1 <- connect qeds (sym rdi) ldi (ldo, rdo) <- do (org_rdi, _) <- getOrgDst rdi (org_ldi, _) <- getOrgDst ldi (org_rdo, _) <- getOrgDst rdo (org_ldo, _) <- getOrgDst ldo return ( if org_ldi == org_ldo then sym base1 else ldo , if org_rdi == org_rdo then base1 else rdo ) let merge base1 = do -- This is the merge loop (org_base1, dst_base1) <- getOrgDst base1 let valid e = do dst_e <- getData qeds (sym e) return $ ccw dst_e dst_base1 org_base1 -- Locate the first L point (lcand.Dest) to be -- encountered by the rising bubble, and delete -- L edges out of base1.dest that fail the -- circle test. initial_lcand <- onext qeds (sym base1) valid_initial_lcand <- valid initial_lcand lcand <- if (not valid_initial_lcand) then return initial_lcand else do let while lcand = do onext_lcand <- onext qeds lcand (_, dst_lcand) <- getOrgDst lcand (_, dst_onext_lcand) <- getOrgDst onext_lcand if inCircle dst_base1 org_base1 dst_lcand dst_onext_lcand then do deleteEdge qeds lcand; while onext_lcand else return lcand while initial_lcand -- Symmetrically, locate the first R point to -- be hit, and delete R edges initial_rcand <- oprev qeds base1 valid_initial_rcand <- valid initial_rcand rcand <- if (not valid_initial_rcand) then return initial_rcand else do let while rcand = do oprev_rcand <- oprev qeds rcand (_, dst_rcand) <- getOrgDst rcand (_, dst_oprev_rcand) <- getOrgDst oprev_rcand if inCircle dst_base1 org_base1 dst_rcand dst_oprev_rcand then do deleteEdge qeds rcand; while oprev_rcand else return rcand while initial_rcand valid_lcand <- valid lcand valid_rcand <- valid rcand (org_lcand, dst_lcand) <- getOrgDst lcand (org_rcand, dst_rcand) <- getOrgDst rcand let action -- if both lcand and rcand are invalid, then -- base1 is the upper common tangent. | not valid_lcand && not valid_rcand = return () -- the next cross edge is to be connected to -- either lcand.Dest or rcand.Dest. -- if both are valid, then choose the -- appropriate one using the inCircle -- test | not valid_lcand || (valid_rcand && inCircle dst_lcand org_lcand org_rcand dst_rcand) = do next_base1 <- connect qeds rcand (sym base1) merge next_base1 | otherwise = do next_base1 <- connect qeds (sym base1) (sym lcand) merge next_base1 action merge base1 return (ldo, rdo) splitList :: [a] -> ([a], [a]) splitList a = loop a a where -- The first argument is the fast pointer, the -- second argument is the slow pointer. loop [] slow = ([], slow) loop (_:[]) slow = ([], slow) loop (_:_:fast) (a:slow) = let res = loop fast slow in (a:fst res, snd res) xycompare :: Ord r => (r, r) -> (r, r) -> Ordering xycompare (xa, ya) (xb, yb) = case compare xa xb of EQ -> compare ya yb res -> res -- Geometric tests -- Determine if point d is inside the circle -- defined by points abc. inCircle :: (Ord r, Num r) => (r, r) -> (r, r) -> (r, r) -> (r, r) -> Bool inCircle (xa, ya) (xb, yb) (xc, yc) (xd, yd) = {- Determine the sign of the determinant of the matrix: | xa ya (xa*xa + ya*ya) 1 | | xb yb (xb*xb + yb*yb) 1 | | xc yc (xc*xc + yc*yc) 1 | | xd yd (xd*xd + yd*yd) 1 | -} let za = xa * xa + ya * ya zb = xb * xb + yb * yb zc = xc * xc + yc * yc zd = xd * xd + yd * yd determinant = det4 (xa, ya, za, 1) (xb, yb, zb, 1) (xc, yc, zc, 1) (xd, yd, zd, 1) in determinant > 0 -- Determine if the triangle formed by -- points abc is clockwise ccw :: (Ord r, Num r) => (r,r) -> (r,r) -> (r,r) -> Bool ccw (xa, ya) (xb, yb) (xc, yc) = {- Determine the sign of the determinant of the matrix: | xa ya 1 | | xb yb 1 | | xc yc 1 | -} let determinant = det3 (xa, ya, 1) (xb, yb, 1) (xc, yc, 1) in determinant > 0 -- determinant computation det4 :: Num r => (r,r,r,r) -> (r,r,r,r) -> (r,r,r,r) -> (r,r,r,r) -> r det4 (a0, a1, a2, a3) (b0, b1, b2, b3) (c0, c1, c2, c3) (d0, d1, d2, d3) = a0 * det3 (b1, b2, b3) (c1, c2, c3) (d1, d2, d3) - a1 * det3 (b0, b2, b3) (c0, c2, c3) (d0, d2, d3) + a2 * det3 (b0, b1, b3) (c0, c1, c3) (d0, d1, d3) - a3 * det3 (b0, b1, b2) (c0, c1, c2) (d0, d1, d2) det3 :: Num r => (r,r,r) -> (r,r,r) -> (r,r,r) -> r det3 (a0, a1, a2) (b0, b1, b2) (c0, c1, c2) = a0 * det2 (b1, b2) (c1, c2) - a1 * det2 (b0, b2) (c0, c2) + a2 * det2 (b0, b1) (c0, c1) det2 :: Num r => (r,r) -> (r,r) -> r det2 (a0, a1) (b0, b1) = a0 * b1 - b0 * a1
AmkG/merchants-race
Math/Geom/Delaunay.hs
gpl-3.0
9,656
0
28
3,651
2,783
1,439
1,344
185
11
-- | -- Copyright : © 2009 CNRS - École Polytechnique - INRIA -- License : GPL -- -- Interface for all code generators. module Dedukti.CodeGen where import Dedukti.Core import Dedukti.Module import Data.ByteString.Lazy.Char8 (ByteString) class CodeGen o where data Bundle o -- | Emit code corresponding to an individual rule set. emit :: RuleSet (Id o) (A o) -> o -- | Combine code from a number of rule sets, typically forming a module, -- into a bundle. coalesce :: [o] -> Bundle o -- | Produce the byte sequence to write to a file, given the code -- for all the rule sets. serialize :: MName -- ^ The module name -> [MName] -- ^ Dependencies -> Bundle o -- ^ Code -> ByteString
mboes/dedukti
Dedukti/CodeGen.hs
gpl-3.0
772
0
10
214
118
71
47
-1
-1
(++) <$> ["ha","heh","hmm"] <*> ["?","!","."] newtype CharList = CharList { getCharList :: [Char] } deriving (Eq, Show) <> <$> <+> <*> <|> >>= -- infixl 4 <$> (<$>) :: Functor f => (a -> b) -> f a -> f b -- infixl 4 <*> (<*>) :: Applicative f => f (a -> b) -> f a -> f b -- infixl 1 >>= (>>=) :: Monad m => m a -> (a -> m b) -> m b -- infixl 1 >> (>>) :: Monad m => m a -> m b -> m b --
YPBlib/NaiveFunGame_hs
draftmd.hs
gpl-3.0
391
4
10
101
233
130
103
-1
-1
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} -- | This module defines types for describing formats module Format.Base where import Data.Proxy import GHC.TypeLits -- Sequence data a :*: b = a :*: b -- Alternative data a :+: b = L a | R b -- Zero or more data Many a = Many [a] -- One or more data Some a = Some a [a] -- | Context sensitive decoding -- The parser of b depends on the value a. -- The user is required to write an instance for DecodeWith i a b -- that specifies how the value a is used to produce a parser for b. data a :~>: b = a :~>: b -- | Match any character except those included in s data NoneOf (s :: Symbol) = NoneOf (Proxy s) Char -- Exactly n -- type a :^: (n :: Nat) = Vector a n --data Vector (a :: *) (n :: Nat) where -- Nil :: Vector a 0 -- Cons :: a -> Vector a n -> Vector a (n + 1)
marco-vassena/svc
src/Format/Base.hs
gpl-3.0
884
0
8
213
131
85
46
13
0
module BarTender.Process ( forkChild , forkChildFinally , killChildren , waitForChildren ) where import Control.Applicative import Control.Concurrent import Control.Concurrent.STM.TMVar import Control.Exception.Base import Control.Monad import Control.Monad.STM import Data.Maybe import System.IO.Unsafe -- List of child semaphores to check when waiting childListVar :: TMVar [(ThreadId, TMVar ())] childListVar = unsafePerformIO $ newTMVarIO [] -- | Create a child thread that can be waited on by 'waitForChildren'. See -- "Control.Concurrent.forkIO". forkChild :: IO () -> IO ThreadId forkChild action = forkChildFinally action $ \_ -> return () -- | Create a child thread that can be waited on by 'waitForChildren', and call -- the supplied function when the thread is about to terminate. See -- "Control.Concurrent.forkFinally". forkChildFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId forkChildFinally action handler = do childVar <- newEmptyTMVarIO tid <- forkFinally action $ \e -> do handler e atomically $ putTMVar childVar () atomically $ do childList <- takeTMVar childListVar putTMVar childListVar $ (tid, childVar) : childList return tid -- | Kill all the child threads spawned by forkChild*. killChildren :: IO () killChildren = do childList <- atomically $ swapTMVar childListVar [] forM_ childList $ killThread . fst -- | Wait on all the child threads spawned by forkChild*. waitForChildren :: IO () waitForChildren = atomically $ waitForChildrenSTM where waitForChildrenSTM :: STM () waitForChildrenSTM = do childList <- takeTMVar childListVar -- If there are no child processes, get out guard $ (childList /= []) -- Get the first child from the list let ((_, childVar) : remList) = childList readTMVar childVar putTMVar childListVar remList waitForChildrenSTM
chrisbouchard/bartender
src/BarTender/Process.hs
gpl-3.0
2,009
0
14
472
437
223
214
41
1
-- | Nonderministic Finite Automata module NFA ( matches ) where import Control.Monad.State (State, evalState, get, put) import Data.List (foldl') import Data.Maybe (isNothing) import Regx type SID = Int data NFA = NFA { rules :: [Rule] , currentStates :: [SID] , acceptStates :: [SID] } deriving Show data Rule = Rule { fromState :: SID , inputChar :: Maybe Char , nextStates :: [SID] } deriving Show accepts :: NFA -> String -> Bool accepts nfa = accepted . foldl' process nfaTemp where accepted nfa' = any (`elem` acceptStates nfa') (currentStates nfa') nfaTemp = nfa { currentStates = stateClosure (rules nfa) (currentStates nfa)} process :: NFA -> Char -> NFA process nfa c = case findRules c nfa of [] -> nfa { acceptStates = [] } rs -> let directStates = followRules rs in nfa { currentStates = stateClosure (rules nfa) directStates } followRules :: [Rule] -> [SID] followRules = concatMap nextStates findRules :: Char -> NFA -> [Rule] findRules c nfa = filter (ruleApplies c nfa) $ rules nfa ruleApplies :: Char -> NFA -> Rule -> Bool ruleApplies c nfa r = maybe False (c ==) (inputChar r) && fromState r `elem` currentStates nfa stateClosure :: [Rule] -> [SID] -> [SID] stateClosure r cs = cs ++ go [] cs where go acc [] = acc go acc ss = let ss1 = followRules $ freeMoves r ss ss' = filter (`notElem` acc) ss1 in go (acc ++ ss') ss' freeMoves :: [Rule] -> [SID] -> [Rule] freeMoves rs ss = filter (\r -> (fromState r `elem` ss) && isNothing (inputChar r)) rs type SIDPool a = State [SID] a nextID :: SIDPool SID nextID = do (x:xs) <- get put xs return x toNFA :: Pattern -> NFA toNFA p = evalState (buildNFA p) [1..] buildNFA :: Pattern -> SIDPool NFA buildNFA p = do s1 <- nextID case p of EmptyR -> return $ NFA [] [s1] [s1] Literal c -> do s2 <- nextID return $ NFA [Rule s1 (Just c) [s2]] [s1] [s2] Concat p1 p2 -> do nfa1 <- buildNFA p1 nfa2 <- buildNFA p2 let lambdaMoves = map (freeMoveTo nfa2) (acceptStates nfa1) return $ NFA (rules nfa1 ++ lambdaMoves ++ rules nfa2) (currentStates nfa1) (acceptStates nfa2) Choose p1 p2 -> do s2 <- nextID nfa1 <- buildNFA p1 nfa2 <- buildNFA p2 let lambdaMoves = [ freeMoveTo nfa1 s2 , freeMoveTo nfa2 s2 ] return $ NFA (lambdaMoves ++ rules nfa1 ++ rules nfa2) [s2] (acceptStates nfa1 ++ acceptStates nfa2) Repeat p' -> do s2 <- nextID nfa <- buildNFA p' let initMove = freeMoveTo nfa s2 lambdaMoves = map (freeMoveTo nfa) (acceptStates nfa) return $ NFA (initMove : rules nfa ++ lambdaMoves) [s2] (s2 : acceptStates nfa) OneMore p' -> buildNFA (Concat p' (Repeat p')) ZeroOne p' -> buildNFA (Choose EmptyR p') where freeMoveTo nfa s = Rule s Nothing (currentStates nfa) matches :: String -> String -> Bool matches s = (`accepts` s) . toNFA . parseRegx
bixuanzju/Simple-Regex
src/NFA.hs
gpl-3.0
3,680
0
17
1,470
1,245
637
608
84
7
module Experiment.Battlefield.Soldier ( soldierWire , swordsmanClass , archerClass , axemanClass , longbowmanClass , horsemanClass , horsearcherClass , allClasses , classStats , classWorth , normedClassWorths ) where -- import Control.Wire.Unsafe.Event -- import Data.Fixed (mod') -- import Data.Foldable (fold) -- import Data.Traversable (mapAccumL) -- import Utils.Helpers (rotationDir) -- import Utils.Wire.Wrapped import Control.Monad import Control.Monad.Fix import Control.Wire as W import Data.List (minimumBy) import Data.Maybe (mapMaybe, fromMaybe) import Data.Ord (comparing) import Experiment.Battlefield.Attack import Experiment.Battlefield.Stats import Experiment.Battlefield.Types import FRP.Netwire.Move import FRP.Netwire.Noise import Linear import Prelude hiding ((.),id) import System.Random import Utils.Wire.Misc import Utils.Wire.Noise import qualified Data.Map.Strict as M type SoldierWireIn k = ((M.Map k Soldier,[Base]), SoldierInEvents) type SoldierWireOut k = (Soldier, SoldierOutEvents) type SoldierWire s e m k = Wire s e m (SoldierWireIn k) (SoldierWireOut k) soldierWire :: forall s e m k. (MonadFix m, HasTime Double s, Monoid e, Ord k) => SoldierData -> SoldierWire s e m k soldierWire (SoldierData x0 fl cls@(SoldierClass bod weap mnt) gen) = proc ((targets,targetBases),mess) -> do -- it's good to be alive! age <- integral 0 -< 1 -- calculate damage from hits let hit = sum . map fst <$> attackeds attackeds = mapMaybe maybeAttacked <$> mess gotKill = sum . mapMaybe (fmap (const 1) . maybeGotKill) <$> mess damage <- hold . accumE (+) 0 <|> pure 0 -< hit -- calculate health, plus recovery recov <- integralWith (\d a -> min d a) 0 -< (recovery, damage) let health = maxHealth + recov - damage alive = health > 0 (posAng,newD) <- moveAndAttack maaGen -< (targets,targetBases,attackeds,alive) -- shoot! shot <- shoot -< newD killCount <- hold . accumE (+) 0 <|> 0 -< gotKill let -- hasAtks = not (null atks) wouldKill = (>= health) . attackDamage funcs = SoldierFuncs wouldKill score = SoldierScore killCount age soldier = Soldier posAng (health / maxHealth) fl score funcs bod weap mnt -- inhibit when dead W.when id -< alive -- outE <- never -< () returnA -< (soldier, map AttackEvent <$> shot) where SoldierStats _ maxHealth baseDamage speed coolDown range' classAcc = classStats cls (gen',accGen') = split gen (dmgGen,maaGen) = split gen' (firstAcc,accGen) = randomR (-accLimit,accLimit) accGen' accLimit = atan $ (hitRadius * 1.1 / classAcc / 2) / range range = fromMaybe 7.5 range' isRanged = weaponRanged weap -- angSpeed = 2 * pi * 2.5 accuracy | isRanged = Just <$> (hold . noiseR coolDown (-accLimit,accLimit) accGen <|> pure firstAcc) | otherwise = pure Nothing newAtk :: V3 Double -> Maybe Double -> (Double, V3 Double) -> Maybe (Double -> AttackData) newAtk p acc (tDist, tDir) | tDist > range = Nothing | otherwise = Just $ AttackData aX0 tDir' . flip (Attack weap) aX0 where tDir' = case acc of Just a -> (rot2 a) !* tDir Nothing -> tDir aX0 = p ^+^ (tDir' ^* 7.5) rot2 ang = V3 (V3 (cos ang) (-1 * (sin ang)) 0) (V3 (sin ang) (cos ang) 0) (V3 0 0 1) recovery = maxHealth / recoveryFactor findClosest :: [V3 Double] -> V3 Double -> Maybe ((Double, V3 Double),V3 Double) findClosest [] _ = Nothing findClosest others pos = Just $ minimumBy (comparing fst) otherPs where otherPs = map f others f v = ((d,u),v) where dv = v ^-^ pos d = norm dv u = dv ^/ d findAttacker :: [V3 Double] -> V3 Double -> Maybe (V3 Double) findAttacker others pos = snd <$> mfilter ((< 9) . fst . fst) (findClosest others pos) seek others = (fst <$>) . findClosest others shoot = fmap applyRandom <$> coupleRandom . oneShot where oneShot = (proc newA -> do case newA of Nothing -> never -< () Just a -> do shot <- W.for coolDown . now -< a returnA -< shot ) --> oneShot coupleRandom = couple (noisePrimR (1/damageVariance,damageVariance) dmgGen) applyRandom (atk,r) = [atk (r * baseDamage)] moveAndAttack g = proc (targets,targetBases,attackeds,alive) -> do favoriteSpot <- arr (^* (baseRadius * 0.25)) . noiseDisc 1 0 g -< () let targetsPos = map getPos (M.elems targets) basesPos = map ((^+^ favoriteSpot) . basePos) targetBases attackers <- curated -< (map snd <$> attackeds, findAttacker targetsPos) -- seeking and movement acc <- accuracy -< () rec let zone | null basesPos = Nothing | otherwise = fst <$> findClosest basesPos pos zone' = (first ((if noAttackers then id else const True) . (< (range + baseRadius * 0.5)))) <$> zone noAttackers = null attackers inZone = fromMaybe True $ fst <$> zone' -- inZone = -- case zone of -- Just ((zDist,_),_) -- | zDist < baseRadius * 0.85 -> True -- | otherwise -> False -- Nothing -> False -- find the target and the direction to face -- targetPool = -- case (attackers,targetBases,isRanged) of -- ([],[],False) -> targetsPos -- ([],[],True) -> targetsPos -- (_,[],False) -> targetsPos -- (_,[],True) -> attackers -- ([],_,False) -> basesPos -- ([],_,True) -> basesPos -- (_,_,False) -> attackers ++ basesPos -- (_,_,True) -> attackers targetPool | noAttackers || not isRanged = targetsPos | otherwise = attackers target = guard inZone >> seek targetPool pos target' = (first (> range)) <$> target newD | alive = target >>= newAtk pos acc | otherwise = Nothing -- move to target? (dir,vel) = case (target',zone') of (Just (True, tDir),_) -> (Just tDir, tDir ^* speed) (_,Just (False, bDir)) -> (Just bDir, bDir ^* speed) _ -> (Nothing, zero) pos <- integral x0 -< vel -- calculate last direction facing. holdJust breaks FRP. (V3 vx vy _) <- holdJust zero -< dir returnA -< (PosAng pos (atan2 vy vx),newD) swordsmanClass :: SoldierClass archerClass :: SoldierClass axemanClass :: SoldierClass longbowmanClass :: SoldierClass horsemanClass :: SoldierClass horsearcherClass :: SoldierClass swordsmanClass = SoldierClass MeleeBody Sword Foot archerClass = SoldierClass RangedBody Bow Foot axemanClass = SoldierClass TankBody Axe Foot longbowmanClass = SoldierClass RangedBody Longbow Foot horsemanClass = SoldierClass MeleeBody Sword Horse horsearcherClass = SoldierClass RangedBody Bow Horse allClasses :: [SoldierClass] allClasses = [ swordsmanClass, archerClass, axemanClass , longbowmanClass, horsemanClass, horsearcherClass] classStats :: SoldierClass -> SoldierStats classStats (SoldierClass bod weap mnt) = SoldierStats dps hlt dmg spd cld rng acc where dps = weaponDPS weap * mountDamageMod mnt / acc hlt = bodyHealth bod * mountHealthMod mnt dmg = dps * cld spd = mountSpeed mnt * bodySpeedMod bod cld = weaponCooldown weap rng = weaponRange weap acc = fromMaybe 1 (rangedAccuracy <$ rng) classWorth :: SoldierClass -> Double classWorth = statsWorth . classStats where statsWorth (SoldierStats dps hlt dmg spd _ rng _) = sum statZipped - shunter where shunter = 2.5 statArr = [ dps , hlt , spd , dmg , fromMaybe 0 rng ] statNorm = [ 5 , 25 , 33 , 5 , 25 ] statWeight = [ 1.85, 1.67, 0.75, 0.5 , 1.5 ] statZipped = zipWith3 mul3 statArr statNorm statWeight mul3 a n z = (a/n)*z normedClassWorths :: M.Map SoldierClass Double normedClassWorths = M.fromList $ zip allClasses normed where worths = map classWorth allClasses worthsum = sum worths normed = map (/ worthsum) worths
mstksg/netwire-experiments
src/Experiment/Battlefield/Soldier.hs
gpl-3.0
8,797
3
23
2,796
2,531
1,350
1,181
-1
-1
{-# LANGUAGE DeriveGeneric #-} module System.DevUtils.Redis.Helpers.CommandStats.Include ( CommandStat(..), CommandStats(..) ) where import GHC.Generics (Generic) --data CommandStats = CommandStats [CommandStat] deriving (Show, Read, Eq, Generic) type CommandStats = [CommandStat] data CommandStat = CommandStat { _type :: String, _numCalls :: Integer, _totalCpu :: Integer, _avgCpu :: Double } deriving (Show, Read, Eq, Generic)
adarqui/DevUtils-Redis
src/System/DevUtils/Redis/Helpers/CommandStats/Include.hs
gpl-3.0
439
0
8
60
99
64
35
12
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ExtendedDefaultRules #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} import Shelly import Data.Text as T import System.Directory (removeFile) import System.Environment (getArgs) import System.IO.Error default (T.Text) cleanTmp :: IO () cleanTmp = do r <- tryIOError $ removeFile "./tmp.png" case r of Left err -> putStrLn $ "error: " ++ show err Right err -> putStrLn "error: tmp.png does not exist, continuing as normal, this is to be expected" handleArgs :: [String] -> IO () handleArgs ["window"] = shelly $ verbosely $ do liftIO $ cleanTmp cmd "maim" ["./tmp.png"] cmd "shoot" ["./tmp.png"] >>= cmd "xclip" ["-selection", "c"] handleArgs [] = shelly $ verbosely $ do liftIO $ cleanTmp cmd "maim" ["-s", "./tmp.png"] cmd "shoot" ["./tmp.png"] >>= cmd "xclip" ["-selection", "c"] handleArgs [x] = putStrLn $ "Unknown argument: " ++ x handleArgs (x:xs) = do putStrLn $ "Unknown argument: " ++ x; handleArgs xs main = getArgs >>= handleArgs
zackp30/dotfiles
home/bin/scrot2.hs
gpl-3.0
1,028
0
11
189
322
165
157
27
2
module Hadolint.Rule.DL3059 (rule) where import Hadolint.Rule import Language.Docker.Syntax data Acc = Acc RunFlags | Empty deriving (Eq, Show) rule :: Rule args rule = customRule check (emptyState Empty) where code = "DL3059" severity = DLInfoC message = "Multiple consecutive `RUN` instructions. Consider consolidation." check line st (Run (RunArgs _ flags)) | state st == Acc flags = st |> addFail CheckFailure {..} | otherwise = st |> modify (remember flags) check _ st _ = st |> modify reset {-# INLINEABLE rule #-} remember :: RunFlags -> Acc -> Acc remember flags _ = Acc flags reset :: Acc -> Acc reset _ = Empty
lukasmartinelli/hadolint
src/Hadolint/Rule/DL3059.hs
gpl-3.0
668
0
11
152
226
117
109
-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.AndroidEnterprise.ServiceAccountkeys.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Removes and invalidates the specified credentials for the service -- account associated with this enterprise. The calling service account -- must have been retrieved by calling Enterprises.GetServiceAccount and -- must have been set as the enterprise service account by calling -- Enterprises.SetAccount. -- -- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.serviceaccountkeys.delete@. module Network.Google.Resource.AndroidEnterprise.ServiceAccountkeys.Delete ( -- * REST Resource ServiceAccountkeysDeleteResource -- * Creating a Request , serviceAccountkeysDelete , ServiceAccountkeysDelete -- * Request Lenses , sadKeyId , sadEnterpriseId ) where import Network.Google.AndroidEnterprise.Types import Network.Google.Prelude -- | A resource alias for @androidenterprise.serviceaccountkeys.delete@ method which the -- 'ServiceAccountkeysDelete' request conforms to. type ServiceAccountkeysDeleteResource = "androidenterprise" :> "v1" :> "enterprises" :> Capture "enterpriseId" Text :> "serviceAccountKeys" :> Capture "keyId" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] () -- | Removes and invalidates the specified credentials for the service -- account associated with this enterprise. The calling service account -- must have been retrieved by calling Enterprises.GetServiceAccount and -- must have been set as the enterprise service account by calling -- Enterprises.SetAccount. -- -- /See:/ 'serviceAccountkeysDelete' smart constructor. data ServiceAccountkeysDelete = ServiceAccountkeysDelete' { _sadKeyId :: !Text , _sadEnterpriseId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ServiceAccountkeysDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sadKeyId' -- -- * 'sadEnterpriseId' serviceAccountkeysDelete :: Text -- ^ 'sadKeyId' -> Text -- ^ 'sadEnterpriseId' -> ServiceAccountkeysDelete serviceAccountkeysDelete pSadKeyId_ pSadEnterpriseId_ = ServiceAccountkeysDelete' { _sadKeyId = pSadKeyId_ , _sadEnterpriseId = pSadEnterpriseId_ } -- | The ID of the key. sadKeyId :: Lens' ServiceAccountkeysDelete Text sadKeyId = lens _sadKeyId (\ s a -> s{_sadKeyId = a}) -- | The ID of the enterprise. sadEnterpriseId :: Lens' ServiceAccountkeysDelete Text sadEnterpriseId = lens _sadEnterpriseId (\ s a -> s{_sadEnterpriseId = a}) instance GoogleRequest ServiceAccountkeysDelete where type Rs ServiceAccountkeysDelete = () type Scopes ServiceAccountkeysDelete = '["https://www.googleapis.com/auth/androidenterprise"] requestClient ServiceAccountkeysDelete'{..} = go _sadEnterpriseId _sadKeyId (Just AltJSON) androidEnterpriseService where go = buildClient (Proxy :: Proxy ServiceAccountkeysDeleteResource) mempty
rueshyna/gogol
gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/ServiceAccountkeys/Delete.hs
mpl-2.0
3,943
0
14
811
393
239
154
62
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.ConsentStores.Consents.Activate -- 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) -- -- Activates the latest revision of the specified Consent by committing a -- new revision with \`state\` updated to \`ACTIVE\`. If the latest -- revision of the specified Consent is in the \`ACTIVE\` state, no new -- revision is committed. A FAILED_PRECONDITION error occurs if the latest -- revision of the specified Consent is in the \`REJECTED\` or \`REVOKED\` -- state. -- -- /See:/ <https://cloud.google.com/healthcare Cloud Healthcare API Reference> for @healthcare.projects.locations.datasets.consentStores.consents.activate@. module Network.Google.Resource.Healthcare.Projects.Locations.DataSets.ConsentStores.Consents.Activate ( -- * REST Resource ProjectsLocationsDataSetsConsentStoresConsentsActivateResource -- * Creating a Request , projectsLocationsDataSetsConsentStoresConsentsActivate , ProjectsLocationsDataSetsConsentStoresConsentsActivate -- * Request Lenses , pldscscaXgafv , pldscscaUploadProtocol , pldscscaAccessToken , pldscscaUploadType , pldscscaPayload , pldscscaName , pldscscaCallback ) where import Network.Google.Healthcare.Types import Network.Google.Prelude -- | A resource alias for @healthcare.projects.locations.datasets.consentStores.consents.activate@ method which the -- 'ProjectsLocationsDataSetsConsentStoresConsentsActivate' request conforms to. type ProjectsLocationsDataSetsConsentStoresConsentsActivateResource = "v1" :> CaptureMode "name" "activate" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] ActivateConsentRequest :> Post '[JSON] Consent -- | Activates the latest revision of the specified Consent by committing a -- new revision with \`state\` updated to \`ACTIVE\`. If the latest -- revision of the specified Consent is in the \`ACTIVE\` state, no new -- revision is committed. A FAILED_PRECONDITION error occurs if the latest -- revision of the specified Consent is in the \`REJECTED\` or \`REVOKED\` -- state. -- -- /See:/ 'projectsLocationsDataSetsConsentStoresConsentsActivate' smart constructor. data ProjectsLocationsDataSetsConsentStoresConsentsActivate = ProjectsLocationsDataSetsConsentStoresConsentsActivate' { _pldscscaXgafv :: !(Maybe Xgafv) , _pldscscaUploadProtocol :: !(Maybe Text) , _pldscscaAccessToken :: !(Maybe Text) , _pldscscaUploadType :: !(Maybe Text) , _pldscscaPayload :: !ActivateConsentRequest , _pldscscaName :: !Text , _pldscscaCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsDataSetsConsentStoresConsentsActivate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pldscscaXgafv' -- -- * 'pldscscaUploadProtocol' -- -- * 'pldscscaAccessToken' -- -- * 'pldscscaUploadType' -- -- * 'pldscscaPayload' -- -- * 'pldscscaName' -- -- * 'pldscscaCallback' projectsLocationsDataSetsConsentStoresConsentsActivate :: ActivateConsentRequest -- ^ 'pldscscaPayload' -> Text -- ^ 'pldscscaName' -> ProjectsLocationsDataSetsConsentStoresConsentsActivate projectsLocationsDataSetsConsentStoresConsentsActivate pPldscscaPayload_ pPldscscaName_ = ProjectsLocationsDataSetsConsentStoresConsentsActivate' { _pldscscaXgafv = Nothing , _pldscscaUploadProtocol = Nothing , _pldscscaAccessToken = Nothing , _pldscscaUploadType = Nothing , _pldscscaPayload = pPldscscaPayload_ , _pldscscaName = pPldscscaName_ , _pldscscaCallback = Nothing } -- | V1 error format. pldscscaXgafv :: Lens' ProjectsLocationsDataSetsConsentStoresConsentsActivate (Maybe Xgafv) pldscscaXgafv = lens _pldscscaXgafv (\ s a -> s{_pldscscaXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pldscscaUploadProtocol :: Lens' ProjectsLocationsDataSetsConsentStoresConsentsActivate (Maybe Text) pldscscaUploadProtocol = lens _pldscscaUploadProtocol (\ s a -> s{_pldscscaUploadProtocol = a}) -- | OAuth access token. pldscscaAccessToken :: Lens' ProjectsLocationsDataSetsConsentStoresConsentsActivate (Maybe Text) pldscscaAccessToken = lens _pldscscaAccessToken (\ s a -> s{_pldscscaAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pldscscaUploadType :: Lens' ProjectsLocationsDataSetsConsentStoresConsentsActivate (Maybe Text) pldscscaUploadType = lens _pldscscaUploadType (\ s a -> s{_pldscscaUploadType = a}) -- | Multipart request metadata. pldscscaPayload :: Lens' ProjectsLocationsDataSetsConsentStoresConsentsActivate ActivateConsentRequest pldscscaPayload = lens _pldscscaPayload (\ s a -> s{_pldscscaPayload = a}) -- | Required. The resource name of the Consent to activate, of the form -- \`projects\/{project_id}\/locations\/{location_id}\/datasets\/{dataset_id}\/consentStores\/{consent_store_id}\/consents\/{consent_id}\`. -- An INVALID_ARGUMENT error occurs if \`revision_id\` is specified in the -- name. pldscscaName :: Lens' ProjectsLocationsDataSetsConsentStoresConsentsActivate Text pldscscaName = lens _pldscscaName (\ s a -> s{_pldscscaName = a}) -- | JSONP pldscscaCallback :: Lens' ProjectsLocationsDataSetsConsentStoresConsentsActivate (Maybe Text) pldscscaCallback = lens _pldscscaCallback (\ s a -> s{_pldscscaCallback = a}) instance GoogleRequest ProjectsLocationsDataSetsConsentStoresConsentsActivate where type Rs ProjectsLocationsDataSetsConsentStoresConsentsActivate = Consent type Scopes ProjectsLocationsDataSetsConsentStoresConsentsActivate = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsLocationsDataSetsConsentStoresConsentsActivate'{..} = go _pldscscaName _pldscscaXgafv _pldscscaUploadProtocol _pldscscaAccessToken _pldscscaUploadType _pldscscaCallback (Just AltJSON) _pldscscaPayload healthcareService where go = buildClient (Proxy :: Proxy ProjectsLocationsDataSetsConsentStoresConsentsActivateResource) mempty
brendanhay/gogol
gogol-healthcare/gen/Network/Google/Resource/Healthcare/Projects/Locations/DataSets/ConsentStores/Consents/Activate.hs
mpl-2.0
7,401
0
16
1,443
793
469
324
125
1
module GameTree ( GameTree(..) , isGameTreePuttingAllowed , selectGameTreeFields , emptyGameTree , buildGameTree , putGameTreePlayersPoint , putGameTreePoint , gameTreeBack , gameTreeIsEmpty , gameTreeIsOver , gameTreeWidth , gameTreeHeight ) where import Data.List import Data.Maybe import Data.Tree import Player import Field data GameTree = GameTree { gtCurPlayer :: Player , gtFields :: [Field] , gtTree :: Tree Field } isGameTreePuttingAllowed :: GameTree -> Pos -> Bool isGameTreePuttingAllowed = isPuttingAllowed . head . gtFields findByLastMove :: (Pos, Player) -> Forest Field -> Maybe (Tree Field) findByLastMove move = find (\(Node field _) -> head (moves field) == move) filterByLastMove :: (Pos, Player) -> Forest Field -> Forest Field filterByLastMove move = filter (\(Node field _) -> head (moves field) /= move) selectGameTreeFields :: Tree Field -> [(Pos, Player)] -> [Field] selectGameTreeFields (Node field _) [] = [field] selectGameTreeFields (Node field children) (h : t) = case findByLastMove h children of Just child -> field : selectGameTreeFields child t Nothing -> [field] emptyGameTree :: Int -> Int -> GameTree emptyGameTree width height = let field = emptyField width height in GameTree { gtCurPlayer = Red , gtFields = [field] , gtTree = Node field [] } unfoldFunction :: [Field] -> (Field, [[Field]]) unfoldFunction [] = error "unfoldFunction: can't unfold empty list of fields." unfoldFunction [field] = (field, []) unfoldFunction (field : t) = (field, [t]) buildGameTree :: [Field] -> GameTree buildGameTree fields = let curPlayer = maybe Red (nextPlayer . snd) $ listToMaybe $ moves $ head fields in GameTree { gtCurPlayer = curPlayer , gtFields = fields , gtTree = unfoldTree unfoldFunction (reverse fields) } updateGameTree :: [Field] -> Tree Field -> Tree Field updateGameTree [] tree = tree updateGameTree (h : t) (Node field children) = let move = head (moves h) in case findByLastMove move children of Just child -> Node field $ updateGameTree t child : filterByLastMove move children Nothing -> Node field $ updateGameTree t (Node h []) : children putGameTreePlayersPoint :: Pos -> Player -> GameTree -> GameTree putGameTreePlayersPoint pos player gameTree = let fields = gtFields gameTree newFields = putPoint pos player (head fields) : fields in gameTree { gtCurPlayer = nextPlayer player , gtFields = newFields , gtTree = updateGameTree (tail $ reverse newFields) (gtTree gameTree) } putGameTreePoint :: Pos -> GameTree -> GameTree putGameTreePoint pos gameTree = putGameTreePlayersPoint pos (gtCurPlayer gameTree) gameTree gameTreeBack :: GameTree -> GameTree gameTreeBack gameTree = gameTree { gtCurPlayer = snd $ head $ moves $ head $ gtFields gameTree , gtFields = tail $ gtFields gameTree } gameTreeIsEmpty :: GameTree -> Bool gameTreeIsEmpty = null . subForest . gtTree gameTreeIsOver :: GameTree -> Bool gameTreeIsOver = fieldIsFull . head . gtFields gameTreeWidth :: GameTree -> Int gameTreeWidth = fieldWidth . head . gtFields gameTreeHeight :: GameTree -> Int gameTreeHeight = fieldHeight . head . gtFields
kurnevsky/missile
src/GameTree.hs
agpl-3.0
3,541
0
15
944
1,052
558
494
76
2
{-# LANGUAGE OverloadedStrings #-} module Misc.MarkdownSpec where import Misc.Markdown import SpecHelper spec :: Spec spec = describe "Core.MarkdownSpec" $ do context "Simple Text" $ do it "parses simple string" $ do parse "#### Hello\r\n\r\n" `shouldBe` Just (Markdown [H4 "Hello"]) parse "! hi-hihi; /img/img.png\r\n\r\n" `shouldBe` Just (Markdown [Img "hi-hihi" "/img/img.png"]) parse "Hello\r\n\r\nHihi\r\n" `shouldBe` Just (Markdown [Paragraph "Hello", Paragraph "Hihi"]) it "parses simple enippet" $ parse "Hello\r\n```rust\r\nHELLO\r\n```\r\n" `shouldBe` Just (Markdown [Paragraph "Hello", Snippet "rust" ["HELLO"]]) context "To Html" $ do it "generate h4 string" $ toHtml (Markdown [Paragraph "HI"]) `shouldBe` "<p>HI</p>" it "generate img tag" $ toHtml (Markdown [Img "hi-hi" "/img/img.png"]) `shouldBe` "<img class='content-img' alt='hi-hi' src='/img/img.png'>" it "generate paragraphs" $ toHtml (Markdown [Paragraph "HI", Paragraph "Hello"]) `shouldBe` "<p>HI</p><p>Hello</p>" main :: IO () main = hspec spec
inq/manicure
spec/Misc/MarkdownSpec.hs
agpl-3.0
1,189
0
19
293
315
154
161
30
1
module Arith3Broken where main :: IO () main = do print (1 + 2) putStrLn (show 10) print (negate (-1)) let blah = negate 1 in print ((+) 0 blah)
thewoolleyman/haskellbook
05/09/maor/arith3broken.hs
unlicense
162
0
11
47
91
44
47
7
1
import System.Random -- Sieve implementations ------------------------ -- This sieve uses mod. It's not the sieve of eratosthenes. sievem :: Integral a => [a] -> [a] sievem [] = [] sievem (p:z) = p : sievem [x | x <- z, mod x p > 0] -- The real sieve of eratosthenes only uses the plus (+) operation :-) -- assumes that the list of numbers ns starts with the digit 2 sieve :: Int -> Int -> [Int] -> [Int] sieve n m ns | m <= (length ns + 2) = sieve n (m+n) (map map_fn ns) | m > (length ns + 2) && n < (length ns + 2) = sieve (n+1) (n+n+2) (map map_fn ns) | otherwise = ns where map_fn x | x==m = 0 | otherwise = x prims :: [Int] -> [Int] prims [] = [] prims (x:xs) = filter (/=0) (sieve x (x+x) (x:xs)) -- given a list of prime numbers -- calculate the distance between two pairs of primes distance :: [Int] -> [Int] distance ps = [ y-x | (x,y) <- zip ps (tail ps) ] -- given a list of numbers returns the max number max' :: [Int] -> Int max' xs = foldl max (head xs) (tail xs) -- given a sequence of numbers calculate the max distance -- between two pairs of prime numbers 2..r maxdist :: [Int] -> [Int] maxdist rs = [max' (distance (sievem [2..x])) | x <- rs] -- Primality tests ------------------ -- given a number n check if it is prime -- using the trial division method trialDiv :: Int -> Bool trialDiv n = null [y | y<-[2..floor (sqrt (fromIntegral n))], mod n y == 0] -- given a number n check if it is a fermat pseudoprime fermat :: Int -> Bool fermat n = and [fermat_theorem n a | a <- rnd 1 (n - 1)] where fermat_theorem :: Int -> Int -> Bool fermat_theorem n a = mod (fromIntegral a ^ (n - 1)) (fromIntegral n) == 1 -- given the limits a and b of a range [a..b] -- compute a random number in this range rnd :: Int -> Int -> [Int] rnd a b = take (if (b - 1) > 5 then 5 else b - 1) (randomRs (a, b) g) where g = mkStdGen 42
maltindal/algorithms
basics/eratos.hs
apache-2.0
1,889
0
14
445
765
403
362
30
2
module AST where type AST = [TopDef] data TopDef = Def Def | Struct Symbol Tsyms data Def = FuncDef Symbol Tsyms Type Expr | VarDef Tsym Expr deriving (Show) data Symbol = Symbol String deriving (Show, Eq) instance Ord Symbol where (Symbol sym1) `compare` (Symbol sym2) = sym1 `compare` sym2 data Expr = Literal Float Unit | Attr Expr Symbol | Tuple [Expr] | List [Expr] | BinaryOp BinOp Expr Expr | UnaryOp UnOp Expr | Func Expr [Expr] | Var Symbol Int | Lambda Tsyms Type Expr | LetExp [Def] Expr | Cond Expr Expr Expr | Str [Char] deriving (Show) type Unit = String data BinOp = Plus | Minus | Divide | Multiply | LessThan | GreaterThan | LessThanEq | GreaterThanEq | Eq | And | Or deriving (Show, Eq) data UnOp = Negate deriving (Show, Eq) type Tsyms = [Tsym] data Tsym = Tsym Type Symbol deriving (Show, Eq) data Type = Type Symbol | ListType Type | TupleType [Type] | FuncType [Type] Type deriving (Show, Eq) instance Ord Type where (Type sym1) <= (Type sym2) = sym1 <= sym2 (Type _) <= _ = True (ListType t1) <= (ListType t2) = t1 <= t2 (ListType _) <= _ = True (TupleType ts1) <= (TupleType ts2) = ts1 <= ts2 (TupleType _) <= _ = True (FuncType ts1 t1) <= (FuncType ts2 t2) = (t1:ts1) <= (t2:ts2) (FuncType _ _) <= _ = True
rbtying/parsel
src/AST.hs
apache-2.0
1,906
0
8
913
577
316
261
60
0
{-# LANGUAGE OverloadedStrings #-} import Control.Monad import Control.Concurrent import Data.List import Control.Exception (finally) import Data.Maybe (fromJust) import qualified Network.WebSockets as WS import qualified Data.Text as T import qualified Data.ByteString as BS import qualified Data.Map as Map import Data.Aeson type ConnectionID = Integer type ChannelName = BS.ByteString data Message = Welcome [Connection] Connection | PeerMessage Connection T.Text | Join Connection | Disconnect Connection instance ToJSON Message where toJSON (Welcome members newCon) = object [ "type" .= ("welcome" :: T.Text) , "members" .= members , "yourid" .= newCon ] toJSON (PeerMessage connection message) = object [ "type" .= ("peermessage" :: T.Text) , "message" .= message , "from" .= connection ] toJSON (Join connection) = object [ "type" .= ("join" :: T.Text) , "id" .= connection ] toJSON (Disconnect connection) = object [ "type" .= ("disconnect" :: T.Text) , "id" .= connection ] instance ToJSON Connection where toJSON Connection { conID = c } = toJSON c data Connection = Connection { conHandle :: WS.Connection, conID :: ConnectionID } instance Eq Connection where Connection {conID = a} == Connection {conID = b} = a == b data Channel = Channel { nextID :: Integer, connections :: [Connection] } data ServerState = ServerState { channels :: Map.Map BS.ByteString Channel } newServerState :: ServerState newServerState = ServerState {channels=Map.empty} newChannel :: Channel newChannel = Channel {nextID=1, connections=[]} getChannelByName :: ChannelName -> ServerState -> Channel getChannelByName channelName state = fromJust $ Map.lookup channelName $ channels state addConnection :: Channel -> Connection -> Channel addConnection channel connection = channel { nextID=nextID channel + 1, connections=connection : connections channel } removeConnection :: ServerState -> ChannelName -> Connection -> ServerState removeConnection state channelName connection = state { channels=if null $ connections channel' then Map.delete channelName allChannels else Map.insert channelName channel' allChannels } where allChannels = channels state channel = getChannelByName channelName state channel' = channel { connections=delete connection $ connections channel } acceptConnection :: MVar ServerState -> WS.ServerApp acceptConnection serverState pending = do print $ WS.pendingRequest pending let channelName = WS.requestPath $ WS.pendingRequest pending handle <- WS.acceptRequest pending connection <- modifyMVar serverState (\state -> let channel = Map.findWithDefault newChannel channelName (channels state) connection = Connection {conHandle=handle, conID=nextID channel} channel' = addConnection channel connection in return (state {channels=Map.insert channelName channel' (channels state)}, connection)) application serverState channelName connection application :: MVar ServerState -> ChannelName -> Connection -> IO () application serverState channelName connection = do withMVar serverState (\state -> let channel = getChannelByName channelName state in sendMessage connection $ Welcome (connections channel) connection) broadcast $ Join connection forever (talk serverState connection broadcast) `finally` disconnect where handle = conHandle connection sendMessage con message = WS.sendTextData (conHandle con) $ encode message broadcast message = do withMVar serverState (\state -> let channel = getChannelByName channelName state in forM_ (connections channel) (\c -> when (c /= connection) $ sendMessage c message)) disconnect = do broadcast $ Disconnect connection modifyMVar_ serverState (\state -> return $ removeConnection state channelName connection) talk :: MVar ServerState -> Connection -> (Message -> IO ()) -> IO () talk serverState myConnection broadcast = do packet <- WS.receiveData handle broadcast $ PeerMessage myConnection packet where handle = conHandle myConnection main :: IO () main = do serverState <- newMVar newServerState WS.runServer "0.0.0.0" 12345 $ acceptConnection serverState
gavinwahl/websocket-channel-server
Main.hs
bsd-2-clause
4,411
0
20
923
1,280
665
615
99
2
{-# LANGUAGE TypeFamilies #-} module Control.Monad.Trans.Abort.Instances.MonadsTF where import Control.Monad.Cont.Class (MonadCont(..)) import Control.Monad.Error.Class (MonadError(..)) import Control.Monad.RWS.Class (MonadRWS(..)) import Control.Monad.Reader.Class (MonadReader(..)) import Control.Monad.Trans (lift) import Control.Monad.Trans.Abort import Control.Monad.State.Class (MonadState(..)) import Control.Monad.Writer.Class (MonadWriter(..)) instance MonadCont m => MonadCont (AbortT r m) where callCC = liftCallCC callCC instance MonadError m => MonadError (AbortT r m) where type ErrorType (AbortT r m) = ErrorType m throwError = lift . throwError catchError = liftCatch catchError instance MonadReader m => MonadReader (AbortT r m) where type EnvType (AbortT r m) = EnvType m ask = lift ask local f = AbortT . local f . unwrapAbortT instance MonadWriter m => MonadWriter (AbortT r m) where type WriterType (AbortT r m) = WriterType m tell = lift . tell listen = liftListen listen pass = liftPass pass instance MonadState m => MonadState (AbortT r m) where type StateType (AbortT r m) = StateType m get = lift get put = lift . put instance MonadRWS m => MonadRWS (AbortT r m)
gcross/AbortT-monadstf
Control/Monad/Trans/Abort/Instances/MonadsTF.hs
bsd-2-clause
1,259
0
8
233
436
240
196
30
0
{-# OPTIONS -Wall -fwarn-tabs -fno-warn-type-defaults #-} module GameLogic where import qualified Data.Set as Set import Data.Map (Map) import qualified Data.Map as Map import Data.List import Data.Maybe import Control.Monad import Text.ParserCombinators.Parsec hiding (Line) type Point = (Int, Int) data Line = VL -- "void" (fake) line, used to indicating initial marks | L { getPoint :: Point , getOrientation :: Orientation , getDirection :: Direction } deriving (Ord) data Orientation = H -- horizontal | V -- vertical | A -- ascending | D -- descending deriving (Eq, Ord, Enum, Bounded) data Direction = Positive | Negative deriving (Eq, Ord, Enum, Bounded) data Board = B { lineState :: [Line] , pointState :: Map Point [Line] } deriving (Show, Eq) instance Show Line where show VL = "VL" show (L point orientation direction) = unwords [show point, show orientation, show direction] instance Show Orientation where show H = "-" show V = "|" show A = "/" show D = "\\" instance Show Direction where show Positive = "+" show Negative = "-" instance Eq Line where (==) VL VL = True (==) VL _ = False (==) _ VL = False (==) l1 l2 = Set.fromList (linePoints l1) == Set.fromList (linePoints l2) lineLength :: Int lineLength = 5 orientationMultiplier :: Orientation -> (Int, Int) orientationMultiplier H = (0, 1) orientationMultiplier V = (1, 0) orientationMultiplier A = (-1, 1) orientationMultiplier D = (1, 1) directionMultiplier :: Direction -> Int directionMultiplier Positive = 1 directionMultiplier Negative = -1 game5 :: [Point] game5 = [ (0,3),(0,4),(0,5),(0,6), (1,3), (1,6), (2,3), (2,6), (3,0),(3,1),(3,2),(3,3), (3,6),(3,7),(3,8),(3,9), (4,0), (4,9), (5,0), (5,9), (6,0),(6,1),(6,2),(6,3), (6,6),(6,7),(6,8),(6,9), (7,3), (7,6), (8,3), (8,6), (9,3),(9,4),(9,5),(9,6) ] makeBoard :: [Point] -> Board makeBoard points = B [] (Map.fromList $ map (\p -> (p, [VL])) points) played :: Board -> Point -> Bool played board point = Map.member point (pointState board) playable :: Board -> Bool playable b = length (validMoves b) > 0 score :: Board -> Int score board = length (Map.keys (pointState board)) - length game5 validLines :: Board -> Point -> [Line] validLines board p = do orientation <- [minBound..] let behindPoints = adjacentPoints board p orientation Negative let aheadPoints = adjacentPoints board p orientation Positive offset <- [lineLength - 1 - aheadPoints..behindPoints] let p' = movePoint offset p orientation Negative return $ L p' orientation Positive adjacentPoints :: Board -> Point -> Orientation -> Direction -> Int adjacentPoints board point orientation direction = aux 0 where aux i = let newPoint = (movePoint (i + 1) point orientation direction) in case () of _ | i >= lineLength - 1 -> i | played board newPoint -> if overlapped newPoint then i + 1 else aux (i + 1) | otherwise -> i overlapped :: Point -> Bool overlapped point' = case Map.lookup point' (pointState board) of Just x -> orientation `elem` (map getOrientation (filter (/= VL) x)) Nothing -> undefined movePoint :: Int -> Point -> Orientation -> Direction -> Point movePoint n (x, y) orientation direction = (x + dx * n, y + dy * n) where dirMul = directionMultiplier direction (oriMulX, oriMulY) = orientationMultiplier orientation (dx, dy) = (dirMul * oriMulX, dirMul * oriMulY) possibleMovePoints :: Board -> [Point] possibleMovePoints board = do x <- [x1..x2] y <- [y1..y2] guard $ not $ Map.member (x, y) (pointState board) return (x, y) where points = Map.keys $ pointState board xs = map fst points ys = map snd points x1 = minimum xs - 1 x2 = maximum xs + 1 y1 = minimum ys - 1 y2 = maximum ys + 1 validMoves :: Board -> [Line] validMoves board = concat [ validLines board point | point <- possibleMovePoints board ] validMovePoints :: Board -> [Point] validMovePoints board = filter (not.null.(validLines board)) (possibleMovePoints board) makeMove :: Board -> Line -> Maybe Board makeMove board line = do guard $ line `elem` (validMoves board) Just $ insertPoints (insertLine board) (linePoints line) where insertLine b = b { lineState = line : lineState b } insertPoints b points = do case points of (p:ps) -> insertPoints (b { pointState = newPointState b p }) ps _ -> b where newPointState b' p = Map.insertWith (++) p [line] (pointState b') undoMove :: Board -> Maybe Board undoMove board = do case lineState board of (l:ls) -> return $ removePoint l (board { lineState = ls }) _ -> Nothing where removePoint l b = b { pointState = cleanEmpty (foldr (removeLineFromMap l) (pointState b) (linePoints l)) } removeLineFromMap l p m = Map.adjust (filter (/= l)) p m cleanEmpty = Map.filter (not.null) tryMakeFirstMove :: Board -> Board tryMakeFirstMove board = case validMoves board of (l:_) -> fromMaybe board (makeMove board l) _ -> board tryMakeMove :: Board -> Line -> Board tryMakeMove board l = fromMaybe board (makeMove board l) tryUndoMove :: Board -> Board tryUndoMove board = case lineState board of (_:_) -> fromMaybe board (undoMove board) _ -> board validBoardLineOverlap :: Board -> Bool validBoardLineOverlap b = and $ map (\p -> overlap p <= 1) pairs where pairs = [ (l1, l2) | l1 <- lineState b, l2 <- lineState b, l1 /= l2 ] overlap (l1, l2) = length $ linePoints l1 `intersect` linePoints l2 validBoard :: Board -> Bool validBoard board = replayLines (makeBoard game5) (lineState board) where replayLines _ [] = True replayLines b ls = case playableLine b ls of Just l -> replayLines (tryMakeMove b l) (filter (/= l) ls) Nothing -> False playableLine b ls = find (\l -> l `elem` validMoves b) ls linePoints :: Line -> [Point] linePoints l = aux 0 [] where aux i acc | i == lineLength = acc | otherwise = aux (i + 1) (newPoint:acc) where newPoint = movePoint i (getPoint l) (getOrientation l) (getDirection l) intP :: GenParser Char st Int intP = do n <- string "-" <|> return [] s <- many1 digit return $ (read (n ++ s) :: Int) eolP :: GenParser Char st String eolP = try (string "\r\n") <|> string "\n" <|> string "\r" pointP :: GenParser Char st Point pointP = do _ <- char '(' x <- intP _ <- char ',' y <- intP _ <- char ')' return (x, y) orientationP :: GenParser Char st Orientation orientationP = do c <- oneOf "-|/\\" case c of '-' -> return H '|' -> return V '/' -> return A '\\' -> return D _ -> unexpected "Unknown orientation" directionP :: GenParser Char st Direction directionP = do c <- oneOf "+-" case c of '+' -> return Positive '-' -> return Negative _ -> unexpected "Unknown direction" lineP :: GenParser Char st Line lineP = do point <- pointP spaces orientation <- orientationP spaces direction <- directionP eof <|> skipMany eolP return $ L point orientation direction linesP :: GenParser Char st [Line] linesP = do line <- many lineP eof return line loadBoard :: String -> Either String Board loadBoard input = case parse linesP "Data Format Error" input of Left err -> Left $ show err Right ls -> replay ls replay :: [Line] -> Either String Board replay previousLines = playNext (makeBoard game5) previousLines where playNext b [] = Right b playNext b (l:ls) = case makeMove b l of Just b' -> playNext b' ls Nothing -> Left $ "Invalid Move: " ++ show l serializeBoard :: Board -> String serializeBoard b = foldr appendLine "" (lineState b) where appendLine l s = s ++ show l ++ "\n"
siyusong/Morphy
GameLogic.hs
bsd-3-clause
8,227
1
16
2,242
3,272
1,717
1,555
223
5
module Tct.Hoca.Config where import Tct.Core import Tct.Core.Common.Error (catchError) import Tct.Trs (TrsStrategy, runtime) import qualified Tct.Hoca.Strategies as S import Tct.Hoca.Types hocaDeclarations :: Declared TrsProblem TrsProblem => [StrategyDeclaration ML ML] hocaDeclarations = [ hocaDefault, hocaDefunctionalize ] fun :: Argument 'Optional (Maybe String) fun = some (string "call" ["The analysed ML expression.", "It defaults to the last defined function."]) `optional` Nothing tctStrategy :: Declared TrsProblem TrsProblem => Argument 'Required TrsStrategy tctStrategy = strat "tct-strategy" ["The TRS strategy to apply after a successfull transformation."] hocaDefault :: Declared TrsProblem TrsProblem => StrategyDeclaration ML ML hocaDefault = SD $ strategy "hoca" (fun, tctStrategy) $ \ mn solve -> S.hoca mn .>>> solve .>>> abort hocaDefunctionalize :: Declared TrsProblem TrsProblem => StrategyDeclaration ML ML hocaDefunctionalize = SD $ strategy "defunctionalize" (fun, tctStrategy) $ \ mn solve -> S.hocaDefunctionalize mn .>>> solve .>>> abort hocaConfig :: TctConfig ML hocaConfig = (defaultTctConfig parser) { defaultStrategy = S.hoca Nothing .>>> runtime .>>> abort } where parser fn = (Right <$> ML fn <$> readFile fn) `catchError` (return . Left . show)
ComputationWithBoundedResources/tct-hoca
src/Tct/Hoca/Config.hs
bsd-3-clause
1,363
0
11
251
375
203
172
-1
-1
module BowlingKata.Day11Spec (spec) where import Test.Hspec import BowlingKata.Day11 (score) spec :: Spec spec = do it "is a gutter game" ((score . rollMany 20 $ 0) == 0) it "rolls all ones" ((score . rollMany 20 $ 1) == 20) it "rolls one spare" ((score $ rollSpare()++3:(rollMany 17 $ 0)) == 16) it "rolls one strike" ((score $ rollStrike():4:3:(rollMany 16 $ 0)) == 24) it "is a perfect game" ((score . rollMany 12 $ 10) == 300) rollMany :: Int -> Int -> [Int] rollMany times pins = replicate times pins rollSpare :: () -> [Int] rollSpare () = [5,5] rollStrike :: () -> Int rollStrike () = 10
Alex-Diez/haskell-tdd-kata
old-katas/test/BowlingKata/Day11Spec.hs
bsd-3-clause
742
0
16
256
299
154
145
21
1
module Main where import Control.Applicative ((<$>)) import Control.Monad (liftM2) import Data.List (subsequences) import Data.Monoid ((<>)) import System.Exit (exitFailure, exitSuccess) import System.Directory (getDirectoryContents) import System.IO (hPutStrLn, stderr) import Utils.Katt.SourceHandler import Utils.Katt.Utils main :: IO () main = do res <- verifyLanguages if res then exitSuccess else exitFailure -- Given a set of source files, categorized into folders corresponding to all supported languages. -- Test the following things: -- (1) That the corresponding languages are actually identified correctly, also when intermixed. -- (2) That all main method classes are identified correctly in the case of java and python languages :: [(KattisLanguage, String)] languages = [(LangCplusplus, "c++"), (LangC, "c"), (LangJava, "java")] testDir :: String testDir = "katt-tests/data/sample_submissions/" verifyLanguages :: IO Bool verifyLanguages = and <$> mapM (\lang -> liftM2 (&&) (verifyLanguage lang) (verifyMain lang)) languages where verifyMain info@(LangJava, folder) = do tests <- getFileNamesSimple $ testDir <> folder res <- mapM (\test -> findMainClass ([test], fst info)) tests if Nothing `notElem` res then return True else do hPutStrLn stderr $ "Failed to verify SourceHandler: main class for language " <> show (fst info) return False verifyMain _ = return True verifyLanguage (identifier, folder)= do tests <- getFileNames $ testDir <> folder let res = map determineLanguage tests if Nothing `notElem` res then return True else do hPutStrLn stderr $ "Failed to verify SourceHandler: language " <> show identifier return False filterNonFiles = filter (`notElem` [".", ".."]) addFolder folder = map ((folder <> "/") <>) getFileNames folder = map (addFolder folder) <$> files where files = map filterNonFiles . drop 1 . subsequences <$> getDirectoryContents folder getFileNamesSimple folder = addFolder folder <$> files where files = filterNonFiles <$> getDirectoryContents folder
davnils/katt
katt-tests/src/TestSourceHandler.hs
bsd-3-clause
2,204
0
15
479
575
312
263
40
4
{-# OPTIONS -cpp #-} module Main where import Control.Concurrent (forkIO, threadDelay) import Control.Concurrent.MVar (putMVar, takeMVar, newEmptyMVar) import Control.Monad import Control.Exception import Data.Maybe (isNothing) import System.Environment (getArgs) import System.Exit import System.IO (hPutStrLn, stderr) #if !defined(mingw32_HOST_OS) import System.Posix hiding (killProcess) import System.IO.Error hiding (try,catch) #endif #if defined(mingw32_HOST_OS) import System.Process import WinCBindings import Foreign import System.Win32.DebugApi import System.Win32.Types #endif main :: IO () main = do args <- getArgs case args of [secs,cmd] -> case reads secs of [(secs', "")] -> run secs' cmd _ -> die ("Can't parse " ++ show secs ++ " as a number of seconds") _ -> die ("Bad arguments " ++ show args) run :: Int -> String -> IO () #if !defined(mingw32_HOST_OS) run secs cmd = do m <- newEmptyMVar mp <- newEmptyMVar installHandler sigINT (Catch (putMVar m Nothing)) Nothing forkIO $ do threadDelay (secs * 1000000) putMVar m Nothing forkIO $ do ei <- try $ do pid <- systemSession cmd return pid putMVar mp ei case ei of Left _ -> return () Right pid -> do r <- getProcessStatus True False pid putMVar m r ei_pid_ph <- takeMVar mp case ei_pid_ph of Left e -> do hPutStrLn stderr ("Timeout:\n" ++ show (e :: IOException)) exitWith (ExitFailure 98) Right pid -> do r <- takeMVar m case r of Nothing -> do killProcess pid exitWith (ExitFailure 99) Just (Exited r) -> exitWith r Just (Terminated s) -> raiseSignal s Just _ -> exitWith (ExitFailure 1) systemSession cmd = forkProcess $ do createSession executeFile "/bin/sh" False ["-c", cmd] Nothing -- need to use exec() directly here, rather than something like -- System.Process.system, because we are in a forked child and some -- pthread libraries get all upset if you start doing certain -- things in a forked child of a pthread process, such as forking -- more threads. killProcess pid = do ignoreIOExceptions (signalProcessGroup sigTERM pid) checkReallyDead 10 where checkReallyDead 0 = hPutStrLn stderr "checkReallyDead: Giving up" checkReallyDead (n+1) = do threadDelay (3*100000) -- 3/10 sec m <- tryJust (guard . isDoesNotExistError) $ getProcessStatus False False pid case m of Right Nothing -> return () Left _ -> return () _ -> do ignoreIOExceptions (signalProcessGroup sigKILL pid) checkReallyDead n ignoreIOExceptions :: IO () -> IO () ignoreIOExceptions io = io `catch` ((\_ -> return ()) :: IOException -> IO ()) #else run secs cmd = let escape '\\' = "\\\\" escape '"' = "\\\"" escape c = [c] cmd' = "sh -c \"" ++ concatMap escape cmd ++ "\"" in alloca $ \p_startupinfo -> alloca $ \p_pi -> withTString cmd' $ \cmd'' -> do job <- createJobObjectW nullPtr nullPtr b_info <- setJobParameters job unless b_info $ errorWin "setJobParameters" ioPort <- createCompletionPort job when (ioPort == nullPtr) $ errorWin "createCompletionPort, cannot continue." let creationflags = cCREATE_SUSPENDED b <- createProcessW nullPtr cmd'' nullPtr nullPtr True creationflags nullPtr nullPtr p_startupinfo p_pi unless b $ errorWin "createProcessW" pi <- peek p_pi b_assign <- assignProcessToJobObject job (piProcess pi) unless b_assign $ errorWin "assignProcessToJobObject, cannot continue." let handleInterrupt action = action `onException` terminateJobObject job 99 handleInterrupt $ do resumeThread (piThread pi) -- The program is now running let handle = piProcess pi let millisecs = secs * 1000 rc <- waitForJobCompletion job ioPort (fromIntegral millisecs) closeHandle ioPort if not rc then do terminateJobObject job 99 closeHandle job exitWith (ExitFailure 99) else alloca $ \p_exitCode -> do terminateJobObject job 0 -- Ensure it's all really dead. closeHandle job r <- getExitCodeProcess handle p_exitCode if r then do ec <- peek p_exitCode let ec' = if ec == 0 then ExitSuccess else ExitFailure $ fromIntegral ec exitWith ec' else errorWin "getExitCodeProcess" #endif
mettekou/ghc
testsuite/timeout/timeout.hs
bsd-3-clause
5,252
1
19
1,913
865
427
438
-1
-1
{-# LANGUAGE ViewPatterns #-} import Data.Profunctor foo :: Int -> Int foo@(lmap foo -> bar) = (+1)
sleexyz/haskell-fun
MultiBind.hs
bsd-3-clause
103
0
8
20
39
22
17
4
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleInstances #-} -- *** TODO *** -- -- GHC 8.0.1 complains about the definition of atomic: -- -- • Cannot instantiate unification variable ‘a0’ -- with a type involving foralls: (forall c. Atomic c a) -> AUTOSAR a -- GHC doesn't yet support impredicative polymorphism -- • In the expression: undefined -- In an equation for ‘atomic’: atomic = undefined -- module Speculation3 where import Unsafe.Coerce newtype DataElement c = DE' Int newtype DataElem = DE Int data Atomic c a instance Functor (Atomic c) where fmap = undefined instance Applicative (Atomic c) where pure = undefined; (<*>) = undefined instance Monad (Atomic c) where (>>=) = undefined data AUTOSAR a instance Functor AUTOSAR where fmap = undefined instance Applicative AUTOSAR where pure = undefined; (<*>) = undefined instance Monad AUTOSAR where (>>=) = undefined delem :: Atomic c (DataElement c) delem = undefined connect :: DataElem -> DataElem -> AUTOSAR () connect = undefined atomic :: (forall c . Atomic c a) -> AUTOSAR a atomic = undefined -------------------- type family Seal a where Seal (DataElement c) = DataElem Seal [a] = [Seal a] Seal (a,b) = (Seal a, Seal b) Seal (m a) = m (Seal a) Seal a = a class Interface a where seal :: a -> Seal a seal = Unsafe.Coerce.unsafeCoerce instance Interface a type family Unseal a where Unseal (a->b) = Seal a -> Unseal b Unseal a = a class Sealer a where sealBy :: Unseal a -> a sealBy = undefined instance (Interface a, Sealer b) => Sealer (a -> b) where sealBy f a = sealBy (f (seal a)) instance {-# OVERLAPPABLE #-} (Unseal a ~ a) => Sealer a where sealBy = id ---------------------- -- MyPort :: DataElem -> [DataElem] -> MyPort -- -- instance Sealer (DataElement c1 -> [DataElement c2] -> MyPort) where -- sealBy :: Unseal (DataElement c1 -> [DataElement c2] -> MyPort) -> -- (DataElement c1 -> [DataElement c2] -> MyPort) -- ~ (Seal (DataElement c1) -> Unseal ([DataElement c2] -> Unseal MyPort)) -> -- (DataElement c1 -> [DataElement c2] -> MyPort) -- ~ (Seal (DataElement c1) -> Seal [DataElement c2] -> Unseal MyPort) -> -- (DataElement c1 -> [DataElement c2] -> MyPort) -- ~ (DataElem -> [Seal (DataElement c2)] -> MyPort) -> -- (DataElement c1 -> [DataElement c2] -> MyPort) -- ~ (DataElem -> [DataElem] -> MyPort) -> -- DataElement c1 -> [DataElement c2] -> MyPort data MyPort = MyPort { e1 :: DataElem, e2 :: [DataElem] } --comp1 :: t -> AUTOSAR (MyPort, DataElem, Maybe Char) comp1 x = atomic $ do a <- delem b <- delem x <- delem return $ (sealBy MyPort a [b,x], seal x, Nothing) comp2 x = do (MyPort a (b:_), x, _) <- comp1 () connect a b return False
josefs/autosar
ARSim/arsim/Speculation3.hs
bsd-3-clause
3,074
0
11
870
678
377
301
-1
-1
module Main where import Data.GraphQL.XXX.Schema import System.Environment import Text.ParserCombinators.Parsec main :: IO () main = do (expr:_) <- getArgs putStrLn (readSchema expr) readSchema :: String -> String readSchema input = case parse graphQLStatements "GraphQL Schema" input of Left err -> "Error: " ++ show err Right val -> graphQLPretty val
uebayasi/haskell-graphql-schema
app/Main.hs
bsd-3-clause
395
0
9
92
119
61
58
12
2
module ElmFormat.Filesystem where import System.FilePath.Find (find, fileName, (/=?), (==?), extension) findAllElmFiles :: FilePath -> IO [FilePath] findAllElmFiles inputFile = find (fileName /=? "elm-stuff") -- TODO: not tested (extension ==? ".elm") inputFile
fredcy/elm-format
src/ElmFormat/Filesystem.hs
bsd-3-clause
293
0
7
62
78
47
31
8
1
{-# LANGUAGE DeriveGeneric #-} module ZM.Type.Tuples ( Tuple2(..), Tuple3(..), Tuple4(..), Tuple5(..), Tuple6(..), Tuple7(..), Tuple8(..), Tuple9(..) ) where import Data.Model data Tuple2 a b = Tuple2 a b deriving (Eq, Ord, Show, Generic) instance (Model a,Model b) => Model (Tuple2 a b) data Tuple3 a b c = Tuple3 a b c deriving (Eq, Ord, Show, Generic) instance (Model a,Model b,Model c) => Model (Tuple3 a b c) data Tuple4 a b c d = Tuple4 a b c d deriving (Eq, Ord, Show, Generic) instance (Model a,Model b,Model c,Model d) => Model (Tuple4 a b c d) data Tuple5 a1 a2 a3 a4 a5 = Tuple5 a1 a2 a3 a4 a5 deriving (Eq, Ord, Show, Generic) instance (Model a1,Model a2,Model a3,Model a4,Model a5) => Model (Tuple5 a1 a2 a3 a4 a5) data Tuple6 a1 a2 a3 a4 a5 a6 = Tuple6 a1 a2 a3 a4 a5 a6 deriving (Eq, Ord, Show, Generic) instance (Model a1,Model a2,Model a3,Model a4,Model a5,Model a6) => Model (Tuple6 a1 a2 a3 a4 a5 a6) data Tuple7 a1 a2 a3 a4 a5 a6 a7= Tuple7 a1 a2 a3 a4 a5 a6 a7 deriving (Eq, Ord, Show, Generic) instance (Model a1,Model a2,Model a3,Model a4,Model a5,Model a6,Model a7) => Model (Tuple7 a1 a2 a3 a4 a5 a6 a7) data Tuple8 a1 a2 a3 a4 a5 a6 a7 a8 = Tuple8 a1 a2 a3 a4 a5 a6 a7 a8 deriving (Eq, Ord, Show, Generic) instance (Model a1,Model a2,Model a3,Model a4,Model a5,Model a6,Model a7,Model a8) => Model (Tuple8 a1 a2 a3 a4 a5 a6 a7 a8) data Tuple9 a1 a2 a3 a4 a5 a6 a7 a8 a9 = Tuple9 a1 a2 a3 a4 a5 a6 a7 a8 a9 deriving (Eq, Ord, Show, Generic) instance (Model a1,Model a2,Model a3,Model a4,Model a5,Model a6,Model a7,Model a8,Model a9) => Model (Tuple9 a1 a2 a3 a4 a5 a6 a7 a8 a9)
tittoassini/typed
src/ZM/Type/Tuples.hs
bsd-3-clause
1,662
0
7
365
875
482
393
27
0
{-# LANGUAGE ExistentialQuantification, FlexibleInstances, GeneralizedNewtypeDeriving, MultiParamTypeClasses, TypeSynonymInstances, DeriveDataTypeable, LambdaCase, NamedFieldPuns, DeriveTraversable #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Core -- Copyright : (c) Spencer Janssen 2007 -- License : BSD3-style (see LICENSE) -- -- Maintainer : [email protected] -- Stability : unstable -- Portability : not portable, uses cunning newtype deriving -- -- The 'X' monad, a state monad transformer over 'IO', for the window -- manager state, and support routines. -- ----------------------------------------------------------------------------- module XMonad.Core ( X, WindowSet, WindowSpace, WorkspaceId, ScreenId(..), ScreenDetail(..), XState(..), XConf(..), XConfig(..), LayoutClass(..), Layout(..), readsLayout, Typeable, Message, SomeMessage(..), fromMessage, LayoutMessages(..), StateExtension(..), ExtensionClass(..), ConfExtension(..), runX, catchX, userCode, userCodeDef, io, catchIO, installSignalHandlers, uninstallSignalHandlers, withDisplay, withWindowSet, isRoot, runOnWorkspaces, getAtom, spawn, spawnPID, xfork, xmessage, recompile, trace, whenJust, whenX, getXMonadDir, getXMonadCacheDir, getXMonadDataDir, stateFileName, binFileName, atom_WM_STATE, atom_WM_PROTOCOLS, atom_WM_DELETE_WINDOW, atom_WM_TAKE_FOCUS, withWindowAttributes, ManageHook, Query(..), runQuery, Directories'(..), Directories, getDirectories, ) where import XMonad.StackSet hiding (modify) import Prelude import Control.Exception (fromException, try, bracket, bracket_, throw, finally, SomeException(..)) import qualified Control.Exception as E import Control.Applicative ((<|>), empty) import Control.Monad.Fail import Control.Monad.State import Control.Monad.Reader import Data.Semigroup import Data.Traversable (for) import Data.Time.Clock (UTCTime) import Data.Default.Class import Data.List (isInfixOf) import System.FilePath import System.IO import System.Info import System.Posix.Env (getEnv) import System.Posix.Process (executeFile, forkProcess, getAnyProcessStatus, createSession) import System.Posix.Signals import System.Posix.IO import System.Posix.Types (ProcessID) import System.Process import System.Directory import System.Exit import Graphics.X11.Xlib import Graphics.X11.Xlib.Extras (getWindowAttributes, WindowAttributes, Event) import Data.Typeable import Data.List ((\\)) import Data.Maybe (isJust,fromMaybe) import qualified Data.Map as M import qualified Data.Set as S -- | XState, the (mutable) window manager state. data XState = XState { windowset :: !WindowSet -- ^ workspace list , mapped :: !(S.Set Window) -- ^ the Set of mapped windows , waitingUnmap :: !(M.Map Window Int) -- ^ the number of expected UnmapEvents , dragging :: !(Maybe (Position -> Position -> X (), X ())) , numberlockMask :: !KeyMask -- ^ The numlock modifier , extensibleState :: !(M.Map String (Either String StateExtension)) -- ^ stores custom state information. -- -- The module "XMonad.Util.ExtensibleState" in xmonad-contrib -- provides additional information and a simple interface for using this. } -- | XConf, the (read-only) window manager configuration. data XConf = XConf { display :: Display -- ^ the X11 display , config :: !(XConfig Layout) -- ^ initial user configuration , theRoot :: !Window -- ^ the root window , normalBorder :: !Pixel -- ^ border color of unfocused windows , focusedBorder :: !Pixel -- ^ border color of the focused window , keyActions :: !(M.Map (KeyMask, KeySym) (X ())) -- ^ a mapping of key presses to actions , buttonActions :: !(M.Map (KeyMask, Button) (Window -> X ())) -- ^ a mapping of button presses to actions , mouseFocused :: !Bool -- ^ was refocus caused by mouse action? , mousePosition :: !(Maybe (Position, Position)) -- ^ position of the mouse according to -- the event currently being processed , currentEvent :: !(Maybe Event) -- ^ event currently being processed , directories :: !Directories -- ^ directories to use } -- todo, better name data XConfig l = XConfig { normalBorderColor :: !String -- ^ Non focused windows border color. Default: \"#dddddd\" , focusedBorderColor :: !String -- ^ Focused windows border color. Default: \"#ff0000\" , terminal :: !String -- ^ The preferred terminal application. Default: \"xterm\" , layoutHook :: !(l Window) -- ^ The available layouts , manageHook :: !ManageHook -- ^ The action to run when a new window is opened , handleEventHook :: !(Event -> X All) -- ^ Handle an X event, returns (All True) if the default handler -- should also be run afterwards. mappend should be used for combining -- event hooks in most cases. , workspaces :: ![String] -- ^ The list of workspaces' names , modMask :: !KeyMask -- ^ the mod modifier , keys :: !(XConfig Layout -> M.Map (ButtonMask,KeySym) (X ())) -- ^ The key binding: a map from key presses and actions , mouseBindings :: !(XConfig Layout -> M.Map (ButtonMask, Button) (Window -> X ())) -- ^ The mouse bindings , borderWidth :: !Dimension -- ^ The border width , logHook :: !(X ()) -- ^ The action to perform when the windows set is changed , startupHook :: !(X ()) -- ^ The action to perform on startup , focusFollowsMouse :: !Bool -- ^ Whether window entry events can change focus , clickJustFocuses :: !Bool -- ^ False to make a click which changes focus to be additionally passed to the window , clientMask :: !EventMask -- ^ The client events that xmonad is interested in , rootMask :: !EventMask -- ^ The root events that xmonad is interested in , handleExtraArgs :: !([String] -> XConfig Layout -> IO (XConfig Layout)) -- ^ Modify the configuration, complain about extra arguments etc. with arguments that are not handled by default , extensibleConf :: !(M.Map TypeRep ConfExtension) -- ^ Stores custom config information. -- -- The module "XMonad.Util.ExtensibleConf" in xmonad-contrib -- provides additional information and a simple interface for using this. } type WindowSet = StackSet WorkspaceId (Layout Window) Window ScreenId ScreenDetail type WindowSpace = Workspace WorkspaceId (Layout Window) Window -- | Virtual workspace indices type WorkspaceId = String -- | Physical screen indices newtype ScreenId = S Int deriving (Eq,Ord,Show,Read,Enum,Num,Integral,Real) -- | The 'Rectangle' with screen dimensions newtype ScreenDetail = SD { screenRect :: Rectangle } deriving (Eq,Show, Read) ------------------------------------------------------------------------ -- | The X monad, 'ReaderT' and 'StateT' transformers over 'IO' -- encapsulating the window manager configuration and state, -- respectively. -- -- Dynamic components may be retrieved with 'get', static components -- with 'ask'. With newtype deriving we get readers and state monads -- instantiated on 'XConf' and 'XState' automatically. -- newtype X a = X (ReaderT XConf (StateT XState IO) a) deriving (Functor, Applicative, Monad, MonadFail, MonadIO, MonadState XState, MonadReader XConf) instance Semigroup a => Semigroup (X a) where (<>) = liftM2 (<>) instance (Monoid a) => Monoid (X a) where mempty = pure mempty instance Default a => Default (X a) where def = return def type ManageHook = Query (Endo WindowSet) newtype Query a = Query (ReaderT Window X a) deriving (Functor, Applicative, Monad, MonadReader Window, MonadIO) runQuery :: Query a -> Window -> X a runQuery (Query m) w = runReaderT m w instance Semigroup a => Semigroup (Query a) where (<>) = liftM2 (<>) instance Monoid a => Monoid (Query a) where mempty = pure mempty instance Default a => Default (Query a) where def = return def -- | Run the 'X' monad, given a chunk of 'X' monad code, and an initial state -- Return the result, and final state runX :: XConf -> XState -> X a -> IO (a, XState) runX c st (X a) = runStateT (runReaderT a c) st -- | Run in the 'X' monad, and in case of exception, and catch it and log it -- to stderr, and run the error case. catchX :: X a -> X a -> X a catchX job errcase = do st <- get c <- ask (a, s') <- io $ runX c st job `E.catch` \e -> case fromException e of Just x -> throw e `const` (x `asTypeOf` ExitSuccess) _ -> do hPrint stderr e; runX c st errcase put s' return a -- | Execute the argument, catching all exceptions. Either this function or -- 'catchX' should be used at all callsites of user customized code. userCode :: X a -> X (Maybe a) userCode a = catchX (Just `liftM` a) (return Nothing) -- | Same as userCode but with a default argument to return instead of using -- Maybe, provided for convenience. userCodeDef :: a -> X a -> X a userCodeDef defValue a = fromMaybe defValue `liftM` userCode a -- --------------------------------------------------------------------- -- Convenient wrappers to state -- | Run a monad action with the current display settings withDisplay :: (Display -> X a) -> X a withDisplay f = asks display >>= f -- | Run a monadic action with the current stack set withWindowSet :: (WindowSet -> X a) -> X a withWindowSet f = gets windowset >>= f -- | Safely access window attributes. withWindowAttributes :: Display -> Window -> (WindowAttributes -> X ()) -> X () withWindowAttributes dpy win f = do wa <- userCode (io $ getWindowAttributes dpy win) catchX (whenJust wa f) (return ()) -- | True if the given window is the root window isRoot :: Window -> X Bool isRoot w = (w==) <$> asks theRoot -- | Wrapper for the common case of atom internment getAtom :: String -> X Atom getAtom str = withDisplay $ \dpy -> io $ internAtom dpy str False -- | Common non-predefined atoms atom_WM_PROTOCOLS, atom_WM_DELETE_WINDOW, atom_WM_STATE, atom_WM_TAKE_FOCUS :: X Atom atom_WM_PROTOCOLS = getAtom "WM_PROTOCOLS" atom_WM_DELETE_WINDOW = getAtom "WM_DELETE_WINDOW" atom_WM_STATE = getAtom "WM_STATE" atom_WM_TAKE_FOCUS = getAtom "WM_TAKE_FOCUS" ------------------------------------------------------------------------ -- LayoutClass handling. See particular instances in Operations.hs -- | An existential type that can hold any object that is in 'Read' -- and 'LayoutClass'. data Layout a = forall l. (LayoutClass l a, Read (l a)) => Layout (l a) -- | Using the 'Layout' as a witness, parse existentially wrapped windows -- from a 'String'. readsLayout :: Layout a -> String -> [(Layout a, String)] readsLayout (Layout l) s = [(Layout (asTypeOf x l), rs) | (x, rs) <- reads s] -- | Every layout must be an instance of 'LayoutClass', which defines -- the basic layout operations along with a sensible default for each. -- -- All of the methods have default implementations, so there is no -- minimal complete definition. They do, however, have a dependency -- structure by default; this is something to be aware of should you -- choose to implement one of these methods. Here is how a minimal -- complete definition would look like if we did not provide any default -- implementations: -- -- * 'runLayout' || (('doLayout' || 'pureLayout') && 'emptyLayout') -- -- * 'handleMessage' || 'pureMessage' -- -- * 'description' -- -- Note that any code which /uses/ 'LayoutClass' methods should only -- ever call 'runLayout', 'handleMessage', and 'description'! In -- other words, the only calls to 'doLayout', 'pureMessage', and other -- such methods should be from the default implementations of -- 'runLayout', 'handleMessage', and so on. This ensures that the -- proper methods will be used, regardless of the particular methods -- that any 'LayoutClass' instance chooses to define. class (Show (layout a), Typeable layout) => LayoutClass layout a where -- | By default, 'runLayout' calls 'doLayout' if there are any -- windows to be laid out, and 'emptyLayout' otherwise. Most -- instances of 'LayoutClass' probably do not need to implement -- 'runLayout'; it is only useful for layouts which wish to make -- use of more of the 'Workspace' information (for example, -- "XMonad.Layout.PerWorkspace"). runLayout :: Workspace WorkspaceId (layout a) a -> Rectangle -> X ([(a, Rectangle)], Maybe (layout a)) runLayout (Workspace _ l ms) r = maybe (emptyLayout l r) (doLayout l r) ms -- | Given a 'Rectangle' in which to place the windows, and a 'Stack' -- of windows, return a list of windows and their corresponding -- Rectangles. If an element is not given a Rectangle by -- 'doLayout', then it is not shown on screen. The order of -- windows in this list should be the desired stacking order. -- -- Also possibly return a modified layout (by returning @Just -- newLayout@), if this layout needs to be modified (e.g. if it -- keeps track of some sort of state). Return @Nothing@ if the -- layout does not need to be modified. -- -- Layouts which do not need access to the 'X' monad ('IO', window -- manager state, or configuration) and do not keep track of their -- own state should implement 'pureLayout' instead of 'doLayout'. doLayout :: layout a -> Rectangle -> Stack a -> X ([(a, Rectangle)], Maybe (layout a)) doLayout l r s = return (pureLayout l r s, Nothing) -- | This is a pure version of 'doLayout', for cases where we -- don't need access to the 'X' monad to determine how to lay out -- the windows, and we don't need to modify the layout itself. pureLayout :: layout a -> Rectangle -> Stack a -> [(a, Rectangle)] pureLayout _ r s = [(focus s, r)] -- | 'emptyLayout' is called when there are no windows. emptyLayout :: layout a -> Rectangle -> X ([(a, Rectangle)], Maybe (layout a)) emptyLayout _ _ = return ([], Nothing) -- | 'handleMessage' performs message handling. If -- 'handleMessage' returns @Nothing@, then the layout did not -- respond to the message and the screen is not refreshed. -- Otherwise, 'handleMessage' returns an updated layout and the -- screen is refreshed. -- -- Layouts which do not need access to the 'X' monad to decide how -- to handle messages should implement 'pureMessage' instead of -- 'handleMessage' (this restricts the risk of error, and makes -- testing much easier). handleMessage :: layout a -> SomeMessage -> X (Maybe (layout a)) handleMessage l = return . pureMessage l -- | Respond to a message by (possibly) changing our layout, but -- taking no other action. If the layout changes, the screen will -- be refreshed. pureMessage :: layout a -> SomeMessage -> Maybe (layout a) pureMessage _ _ = Nothing -- | This should be a human-readable string that is used when -- selecting layouts by name. The default implementation is -- 'show', which is in some cases a poor default. description :: layout a -> String description = show instance LayoutClass Layout Window where runLayout (Workspace i (Layout l) ms) r = fmap (fmap Layout) `fmap` runLayout (Workspace i l ms) r doLayout (Layout l) r s = fmap (fmap Layout) `fmap` doLayout l r s emptyLayout (Layout l) r = fmap (fmap Layout) `fmap` emptyLayout l r handleMessage (Layout l) = fmap (fmap Layout) . handleMessage l description (Layout l) = description l instance Show (Layout a) where show (Layout l) = show l -- | Based on ideas in /An Extensible Dynamically-Typed Hierarchy of -- Exceptions/, Simon Marlow, 2006. Use extensible messages to the -- 'handleMessage' handler. -- -- User-extensible messages must be a member of this class. -- class Typeable a => Message a -- | -- A wrapped value of some type in the 'Message' class. -- data SomeMessage = forall a. Message a => SomeMessage a -- | -- And now, unwrap a given, unknown 'Message' type, performing a (dynamic) -- type check on the result. -- fromMessage :: Message m => SomeMessage -> Maybe m fromMessage (SomeMessage m) = cast m -- X Events are valid Messages. instance Message Event -- | 'LayoutMessages' are core messages that all layouts (especially stateful -- layouts) should consider handling. data LayoutMessages = Hide -- ^ sent when a layout becomes non-visible | ReleaseResources -- ^ sent when xmonad is exiting or restarting deriving Eq instance Message LayoutMessages -- --------------------------------------------------------------------- -- Extensible state/config -- -- | Every module must make the data it wants to store -- an instance of this class. -- -- Minimal complete definition: initialValue class Typeable a => ExtensionClass a where {-# MINIMAL initialValue #-} -- | Defines an initial value for the state extension initialValue :: a -- | Specifies whether the state extension should be -- persistent. Setting this method to 'PersistentExtension' -- will make the stored data survive restarts, but -- requires a to be an instance of Read and Show. -- -- It defaults to 'StateExtension', i.e. no persistence. extensionType :: a -> StateExtension extensionType = StateExtension -- | Existential type to store a state extension. data StateExtension = forall a. ExtensionClass a => StateExtension a -- ^ Non-persistent state extension | forall a. (Read a, Show a, ExtensionClass a) => PersistentExtension a -- ^ Persistent extension -- | Existential type to store a config extension. data ConfExtension = forall a. Typeable a => ConfExtension a -- --------------------------------------------------------------------- -- | General utilities -- -- Lift an 'IO' action into the 'X' monad io :: MonadIO m => IO a -> m a io = liftIO -- | Lift an 'IO' action into the 'X' monad. If the action results in an 'IO' -- exception, log the exception to stderr and continue normal execution. catchIO :: MonadIO m => IO () -> m () catchIO f = io (f `E.catch` \(SomeException e) -> hPrint stderr e >> hFlush stderr) -- | spawn. Launch an external application. Specifically, it double-forks and -- runs the 'String' you pass as a command to \/bin\/sh. -- -- Note this function assumes your locale uses utf8. spawn :: MonadIO m => String -> m () spawn x = spawnPID x >> return () -- | Like 'spawn', but returns the 'ProcessID' of the launched application spawnPID :: MonadIO m => String -> m ProcessID spawnPID x = xfork $ executeFile "/bin/sh" False ["-c", x] Nothing -- | A replacement for 'forkProcess' which resets default signal handlers. xfork :: MonadIO m => IO () -> m ProcessID xfork x = io . forkProcess . finally nullStdin $ do uninstallSignalHandlers createSession x where nullStdin = do fd <- openFd "/dev/null" ReadOnly Nothing defaultFileFlags dupTo fd stdInput closeFd fd -- | Use @xmessage@ to show information to the user. xmessage :: MonadIO m => String -> m () xmessage msg = void . xfork $ do executeFile "xmessage" True [ "-default", "okay" , "-xrm", "*international:true" , "-xrm", "*fontSet:-*-fixed-medium-r-normal-*-18-*-*-*-*-*-*-*,-*-fixed-*-*-*-*-18-*-*-*-*-*-*-*,-*-*-*-*-*-*-18-*-*-*-*-*-*-*" , msg ] Nothing -- | This is basically a map function, running a function in the 'X' monad on -- each workspace with the output of that function being the modified workspace. runOnWorkspaces :: (WindowSpace -> X WindowSpace) -> X () runOnWorkspaces job = do ws <- gets windowset h <- mapM job $ hidden ws c:v <- mapM (\s -> (\w -> s { workspace = w}) <$> job (workspace s)) $ current ws : visible ws modify $ \s -> s { windowset = ws { current = c, visible = v, hidden = h } } -- | All the directories that xmonad will use. They will be used for -- the following purposes: -- -- * @dataDir@: This directory is used by XMonad to store data files -- such as the run-time state file. -- -- * @cfgDir@: This directory is where user configuration files are -- stored (e.g, the xmonad.hs file). You may also create a @lib@ -- subdirectory in the configuration directory and the default recompile -- command will add it to the GHC include path. -- -- * @cacheDir@: This directory is used to store temporary files that -- can easily be recreated such as the configuration binary and any -- intermediate object files generated by GHC. -- Also, the XPrompt history file goes here. -- -- For how these directories are chosen, see 'getDirectories'. -- data Directories' a = Directories { dataDir :: !a , cfgDir :: !a , cacheDir :: !a } deriving (Show, Functor, Foldable, Traversable) -- | Convenient type alias for the most common case in which one might -- want to use the 'Directories' type. type Directories = Directories' FilePath -- | Build up the 'Dirs' that xmonad will use. They are chosen as -- follows: -- -- 1. If all three of xmonad's environment variables (@XMONAD_DATA_DIR@, -- @XMONAD_CONFIG_DIR@, and @XMONAD_CACHE_DIR@) are set, use them. -- 2. If there is a build script called @build@ or configuration -- @xmonad.hs@ in @~\/.xmonad@, set all three directories to -- @~\/.xmonad@. -- 3. Otherwise, use the @xmonad@ directory in @XDG_DATA_HOME@, -- @XDG_CONFIG_HOME@, and @XDG_CACHE_HOME@ (or their respective -- fallbacks). These directories are created if necessary. -- -- The xmonad configuration file (or the build script, if present) is -- always assumed to be in @cfgDir@. -- getDirectories :: IO Directories getDirectories = xmEnvDirs <|> xmDirs <|> xdgDirs where -- | Check for xmonad's environment variables first xmEnvDirs :: IO Directories xmEnvDirs = do let xmEnvs = Directories{ dataDir = "XMONAD_DATA_DIR" , cfgDir = "XMONAD_CONFIG_DIR" , cacheDir = "XMONAD_CACHE_DIR" } maybe empty pure . sequenceA =<< traverse getEnv xmEnvs -- | Check whether the config file or a build script is in the -- @~\/.xmonad@ directory xmDirs :: IO Directories xmDirs = do xmDir <- getAppUserDataDirectory "xmonad" conf <- doesFileExist $ xmDir </> "xmonad.hs" build <- doesFileExist $ xmDir </> "build" -- Place *everything* in ~/.xmonad if yes guard $ conf || build pure Directories{ dataDir = xmDir, cfgDir = xmDir, cacheDir = xmDir } -- | Use XDG directories as a fallback xdgDirs :: IO Directories xdgDirs = for Directories{ dataDir = XdgData, cfgDir = XdgConfig, cacheDir = XdgCache } $ \dir -> do d <- getXdgDirectory dir "xmonad" d <$ createDirectoryIfMissing True d -- | Return the path to the xmonad configuration directory. getXMonadDir :: X String getXMonadDir = asks (cfgDir . directories) {-# DEPRECATED getXMonadDir "Use `asks (cfgDir . directories)' instead." #-} -- | Return the path to the xmonad cache directory. getXMonadCacheDir :: X String getXMonadCacheDir = asks (cacheDir . directories) {-# DEPRECATED getXMonadCacheDir "Use `asks (cacheDir . directories)' instead." #-} -- | Return the path to the xmonad data directory. getXMonadDataDir :: X String getXMonadDataDir = asks (dataDir . directories) {-# DEPRECATED getXMonadDataDir "Use `asks (dataDir . directories)' instead." #-} binFileName, buildDirName :: Directories -> FilePath binFileName Directories{ cacheDir } = cacheDir </> "xmonad-" <> arch <> "-" <> os buildDirName Directories{ cacheDir } = cacheDir </> "build-" <> arch <> "-" <> os errFileName, stateFileName :: Directories -> FilePath errFileName Directories{ dataDir } = dataDir </> "xmonad.errors" stateFileName Directories{ dataDir } = dataDir </> "xmonad.state" srcFileName, libFileName :: Directories -> FilePath srcFileName Directories{ cfgDir } = cfgDir </> "xmonad.hs" libFileName Directories{ cfgDir } = cfgDir </> "lib" buildScriptFileName, stackYamlFileName :: Directories -> FilePath buildScriptFileName Directories{ cfgDir } = cfgDir </> "build" stackYamlFileName Directories{ cfgDir } = cfgDir </> "stack.yaml" -- | Compilation method for xmonad configuration. data Compile = CompileGhc | CompileStackGhc FilePath | CompileScript FilePath deriving (Show) -- | Detect compilation method by looking for known file names in xmonad -- configuration directory. detectCompile :: Directories -> IO Compile detectCompile dirs = tryScript <|> tryStack <|> useGhc where buildScript = buildScriptFileName dirs stackYaml = stackYamlFileName dirs tryScript = do guard =<< doesFileExist buildScript isExe <- isExecutable buildScript if isExe then do trace $ "XMonad will use build script at " <> show buildScript <> " to recompile." pure $ CompileScript buildScript else do trace $ "XMonad will not use build script, because " <> show buildScript <> " is not executable." trace $ "Suggested resolution to use it: chmod u+x " <> show buildScript empty tryStack = do guard =<< doesFileExist stackYaml canonStackYaml <- canonicalizePath stackYaml trace $ "XMonad will use stack ghc --stack-yaml " <> show canonStackYaml <> " to recompile." pure $ CompileStackGhc canonStackYaml useGhc = do trace $ "XMonad will use ghc to recompile, because neither " <> show buildScript <> " nor " <> show stackYaml <> " exists." pure CompileGhc isExecutable f = E.catch (executable <$> getPermissions f) (\(SomeException _) -> return False) -- | Should we recompile xmonad configuration? Is it newer than the compiled -- binary? shouldCompile :: Directories -> Compile -> IO Bool shouldCompile dirs CompileGhc = do libTs <- mapM getModTime . Prelude.filter isSource =<< allFiles (libFileName dirs) srcT <- getModTime (srcFileName dirs) binT <- getModTime (binFileName dirs) if any (binT <) (srcT : libTs) then True <$ trace "XMonad recompiling because some files have changed." else False <$ trace "XMonad skipping recompile because it is not forced (e.g. via --recompile), and neither xmonad.hs nor any *.hs / *.lhs / *.hsc files in lib/ have been changed." where isSource = flip elem [".hs",".lhs",".hsc"] . takeExtension allFiles t = do let prep = map (t</>) . Prelude.filter (`notElem` [".",".."]) cs <- prep <$> E.catch (getDirectoryContents t) (\(SomeException _) -> return []) ds <- filterM doesDirectoryExist cs concat . ((cs \\ ds):) <$> mapM allFiles ds shouldCompile dirs CompileStackGhc{} = do stackYamlT <- getModTime (stackYamlFileName dirs) binT <- getModTime (binFileName dirs) if binT < stackYamlT then True <$ trace "XMonad recompiling because some files have changed." else shouldCompile dirs CompileGhc shouldCompile _dirs CompileScript{} = True <$ trace "XMonad recompiling because a custom build script is being used." getModTime :: FilePath -> IO (Maybe UTCTime) getModTime f = E.catch (Just <$> getModificationTime f) (\(SomeException _) -> return Nothing) -- | Compile the configuration. compile :: Directories -> Compile -> IO ExitCode compile dirs method = bracket_ uninstallSignalHandlers installSignalHandlers $ bracket (openFile (errFileName dirs) WriteMode) hClose $ \err -> do let run = runProc (cfgDir dirs) err case method of CompileGhc -> run "ghc" ghcArgs CompileStackGhc stackYaml -> run "stack" ["build", "--silent", "--stack-yaml", stackYaml] .&&. run "stack" ("ghc" : "--stack-yaml" : stackYaml : "--" : ghcArgs) CompileScript script -> run script [binFileName dirs] where ghcArgs = [ "--make" , "xmonad.hs" , "-i" -- only look in @lib@ , "-ilib" , "-fforce-recomp" , "-main-is", "main" , "-v0" , "-outputdir", buildDirName dirs , "-o", binFileName dirs ] -- waitForProcess =<< System.Process.runProcess, but without closing the err handle runProc cwd err exe args = do hPutStrLn err $ unwords $ "$" : exe : args hFlush err (_, _, _, h) <- createProcess_ "runProc" (proc exe args){ cwd = Just cwd, std_err = UseHandle err } waitForProcess h cmd1 .&&. cmd2 = cmd1 >>= \case ExitSuccess -> cmd2 e -> pure e -- | Check GHC output for deprecation warnings and notify the user if there -- were any. Report success otherwise. checkCompileWarnings :: Directories -> IO () checkCompileWarnings dirs = do ghcErr <- readFile (errFileName dirs) if "-Wdeprecations" `isInfixOf` ghcErr then do let msg = unlines $ ["Deprecations detected while compiling xmonad config: " <> srcFileName dirs] ++ lines ghcErr ++ ["","Please correct them or silence using {-# OPTIONS_GHC -Wno-deprecations #-}."] trace msg xmessage msg else trace "XMonad recompilation process exited with success!" -- | Notify the user that compilation failed and what was wrong. compileFailed :: Directories -> ExitCode -> IO () compileFailed dirs status = do ghcErr <- readFile (errFileName dirs) let msg = unlines $ ["Errors detected while compiling xmonad config: " <> srcFileName dirs] ++ lines (if null ghcErr then show status else ghcErr) ++ ["","Please check the file for errors."] -- nb, the ordering of printing, then forking, is crucial due to -- lazy evaluation trace msg xmessage msg -- | Recompile the xmonad configuration file when any of the following apply: -- -- * force is 'True' -- -- * the xmonad executable does not exist -- -- * the xmonad executable is older than @xmonad.hs@ or any file in -- the @lib@ directory (under the configuration directory) -- -- * custom @build@ script is being used -- -- The -i flag is used to restrict recompilation to the xmonad.hs file only, -- and any files in the aforementioned @lib@ directory. -- -- Compilation errors (if any) are logged to the @xmonad.errors@ file -- in the xmonad data directory. If GHC indicates failure with a -- non-zero exit code, an xmessage displaying that file is spawned. -- -- 'False' is returned if there are compilation errors. -- recompile :: MonadIO m => Directories -> Bool -> m Bool recompile dirs force = io $ do method <- detectCompile dirs willCompile <- if force then True <$ trace "XMonad recompiling (forced)." else shouldCompile dirs method if willCompile then do status <- compile dirs method if status == ExitSuccess then checkCompileWarnings dirs else compileFailed dirs status pure $ status == ExitSuccess else pure True -- | Conditionally run an action, using a @Maybe a@ to decide. whenJust :: Monad m => Maybe a -> (a -> m ()) -> m () whenJust mg f = maybe (return ()) f mg -- | Conditionally run an action, using a 'X' event to decide whenX :: X Bool -> X () -> X () whenX a f = a >>= \b -> when b f -- | A 'trace' for the 'X' monad. Logs a string to stderr. The result may -- be found in your .xsession-errors file trace :: MonadIO m => String -> m () trace = io . hPutStrLn stderr -- | Ignore SIGPIPE to avoid termination when a pipe is full, and SIGCHLD to -- avoid zombie processes, and clean up any extant zombie processes. installSignalHandlers :: MonadIO m => m () installSignalHandlers = io $ do installHandler openEndedPipe Ignore Nothing installHandler sigCHLD Ignore Nothing (try :: IO a -> IO (Either SomeException a)) $ fix $ \more -> do x <- getAnyProcessStatus False False when (isJust x) more return () uninstallSignalHandlers :: MonadIO m => m () uninstallSignalHandlers = io $ do installHandler openEndedPipe Default Nothing installHandler sigCHLD Default Nothing return ()
xmonad/xmonad
src/XMonad/Core.hs
bsd-3-clause
33,424
2
18
8,169
6,268
3,394
2,874
-1
-1
{-# LANGUAGE OverloadedStrings, Rank2Types #-} module MOO.Builtins.Values (builtins) where import Control.Applicative ((<$>), (<*>), (<|>)) import Control.Monad (unless, (<=<)) import Data.ByteString (ByteString) import Data.Char (isDigit, digitToInt) import Data.Monoid ((<>), mconcat) import Data.Text (Text) import Data.Text.Encoding (encodeUtf8) import Data.Word (Word8) import Database.VCache (vref') import Text.Printf (printf) import qualified Data.ByteString as BS import MOO.Builtins.Common import MOO.Builtins.Crypt import MOO.Builtins.Hash import MOO.Builtins.Match import MOO.Parser (parseNum, parseObj) import MOO.Task import MOO.Types import MOO.Util import qualified MOO.List as Lst import qualified MOO.String as Str {-# ANN module ("HLint: ignore Use camelCase" :: String) #-} -- | § 4.4.2 Manipulating MOO Values builtins :: [Builtin] builtins = [ -- § 4.4.2.1 General Operations Applicable to all Values bf_typeof , bf_tostr , bf_toliteral , bf_toint , bf_tonum , bf_toobj , bf_tofloat , bf_equal , bf_value_bytes , bf_value_hash -- § 4.4.2.2 Operations on Numbers , bf_random , bf_min , bf_max , bf_abs , bf_floatstr , bf_sqrt , bf_sin , bf_cos , bf_tan , bf_asin , bf_acos , bf_atan , bf_sinh , bf_cosh , bf_tanh , bf_exp , bf_log , bf_log10 , bf_ceil , bf_floor , bf_trunc -- § 4.4.2.3 Operations on Strings , bf_length , bf_strsub , bf_index , bf_rindex , bf_strcmp , bf_decode_binary , bf_encode_binary , bf_match , bf_rmatch , bf_substitute , bf_crypt , bf_string_hash , bf_binary_hash -- § 4.4.2.4 Operations on Lists , bf_is_member , bf_listinsert , bf_listappend , bf_listdelete , bf_listset , bf_setadd , bf_setremove ] -- § 4.4.2.1 General Operations Applicable to all Values bf_typeof = Builtin "typeof" 1 (Just 1) [TAny] TInt $ \[value] -> return $ Int $ typeCode $ typeOf value bf_tostr = Builtin "tostr" 0 Nothing [] TStr $ return . Str . Str.fromText . builder2text . mconcat . map toBuilder bf_toliteral = Builtin "toliteral" 1 (Just 1) [TAny] TStr $ \[value] -> return $ Str $ Str.fromText $ toLiteral value -- XXX toint(" - 34 ") does not parse as -34 bf_toint = Builtin "toint" 1 (Just 1) [TAny] TInt $ \[value] -> toint value where toint value = case value of Int _ -> return value Flt x | x < fromIntegral (minBound :: IntT) || x > fromIntegral (maxBound :: IntT) -> raise E_FLOAT | otherwise -> return (Int $ truncate x) Obj x -> return (Int $ fromIntegral x) Str x -> maybe (return $ Int 0) toint (parseNum $ Str.toText x) Err x -> return (Int $ fromIntegral $ fromEnum x) _ -> raise E_TYPE bf_tonum = bf_toint { builtinName = "tonum" } bf_toobj = Builtin "toobj" 1 (Just 1) [TAny] TObj $ \[value] -> toobj value where toobj value = case value of Int x -> return (Obj $ fromIntegral x) Flt x | x < fromIntegral (minBound :: ObjT) || x > fromIntegral (maxBound :: ObjT) -> raise E_FLOAT | otherwise -> return (Obj $ truncate x) Obj _ -> return value Str x -> maybe (return $ Obj 0) toobj $ parseNum (Str.toText x) <|> parseObj (Str.toText x) Err x -> return (Obj $ fromIntegral $ fromEnum x) _ -> raise E_TYPE bf_tofloat = Builtin "tofloat" 1 (Just 1) [TAny] TFlt $ \[value] -> tofloat value where tofloat value = case value of Int x -> return (Flt $ fromIntegral x) Flt _ -> return value Obj x -> return (Flt $ fromIntegral x) Str x -> maybe (return $ Flt 0) tofloat (parseNum $ Str.toText x) Err x -> return (Flt $ fromIntegral $ fromEnum x) _ -> raise E_TYPE bf_equal = Builtin "equal" 2 (Just 2) [TAny, TAny] TInt $ \[value1, value2] -> return $ truthValue (value1 `equal` value2) bf_value_bytes = Builtin "value_bytes" 1 (Just 1) [TAny] TInt $ \[value] -> do vspace <- getVSpace bytes <- unsafeIOtoMOO $ storageBytes (vref' vspace value) return (Int $ fromIntegral bytes) bf_value_hash = Builtin "value_hash" 1 (Just 3) [TAny, TStr, TAny] TStr $ \(value : optional) -> builtinFunction bf_toliteral [value] >>= builtinFunction bf_string_hash . (: optional) -- § 4.4.2.2 Operations on Numbers bf_random = Builtin "random" 0 (Just 1) [TInt] TInt $ \optional -> let [Int mod] = defaults optional [Int maxBound] in if mod < 1 then raise E_INVARG else Int <$> random (1, mod) imumBuiltin :: Id -> (forall a. Ord a => [a] -> a) -> Builtin imumBuiltin name f = Builtin name 1 Nothing [TNum] TNum $ \args -> case args of Int x:vs -> Int . f . (x :) <$> getValues intValue vs Flt x:vs -> Flt . f . (x :) <$> getValues fltValue vs where getValues :: (Value -> Maybe a) -> [Value] -> MOO [a] getValues f = maybe (raise E_TYPE) return . mapM f bf_min = imumBuiltin "min" minimum bf_max = imumBuiltin "max" maximum bf_abs = Builtin "abs" 1 (Just 1) [TNum] TNum $ \[arg] -> case arg of Int x -> return (Int $ abs x) Flt x -> return (Flt $ abs x) bf_floatstr = Builtin "floatstr" 2 (Just 3) [TFlt, TInt, TAny] TStr $ \(Flt x : Int precision : optional) -> let [scientific] = booleanDefaults optional [False] prec = min precision 19 format = printf "%%.%d%c" prec $ if scientific then 'e' else 'f' in if precision < 0 then raise E_INVARG else return $ Str $ Str.fromString $ printf format x floatBuiltin :: Id -> (FltT -> FltT) -> Builtin floatBuiltin name f = Builtin name 1 (Just 1) [TFlt] TFlt $ \[Flt x] -> checkFloat (f x) bf_sqrt = floatBuiltin "sqrt" sqrt bf_sin = floatBuiltin "sin" sin bf_cos = floatBuiltin "cos" cos bf_tan = floatBuiltin "tan" tan bf_asin = floatBuiltin "asin" asin bf_acos = floatBuiltin "acos" acos bf_atan = Builtin "atan" 1 (Just 2) [TFlt, TFlt] TFlt $ \args -> checkFloat $ case args of [Flt y] -> atan y [Flt y, Flt x] -> atan2 y x bf_sinh = floatBuiltin "sinh" sinh bf_cosh = floatBuiltin "cosh" cosh bf_tanh = floatBuiltin "tanh" tanh bf_exp = floatBuiltin "exp" exp bf_log = floatBuiltin "log" log bf_log10 = floatBuiltin "log10" (logBase 10) bf_ceil = floatBuiltin "ceil" $ fromInteger . ceiling bf_floor = floatBuiltin "floor" $ fromInteger . floor bf_trunc = floatBuiltin "trunc" $ fromInteger . truncate -- § 4.4.2.3 Operations on Strings bf_length = Builtin "length" 1 (Just 1) [TAny] TInt $ \[arg] -> case arg of Str string -> return $ Int $ fromIntegral $ Str.length string Lst list -> return $ Int $ fromIntegral $ Lst.length list _ -> raise E_TYPE caseFold' :: Bool -> StrT -> StrT caseFold' caseMatters | caseMatters = id | otherwise = Str.fromText . Str.toCaseFold -- XXX this won't work for Unicode in general bf_strsub = Builtin "strsub" 3 (Just 4) [TStr, TStr, TStr, TAny] TStr $ \(Str subject : Str what : Str with : optional) -> let [case_matters] = booleanDefaults optional [False] caseFold = caseFold' case_matters :: StrT -> StrT what' = caseFold what :: StrT subs :: StrT -> [StrT] subs "" = [] subs subject = case Str.breakOn what' (caseFold subject) of (_, "") -> [subject] (prefix, _) -> let (s, r) = Str.splitAt (Str.length prefix) subject in s : with : subs (Str.drop whatLen r) whatLen :: Int whatLen = Str.length what in if Str.null what then raise E_INVARG else return $ Str $ Str.concat $ subs subject indexBuiltin :: Id -> (StrT -> IntT) -> (StrT -> StrT -> IntT) -> Builtin indexBuiltin name nullCase mainCase = Builtin name 2 (Just 3) [TStr, TStr, TAny] TInt $ \(Str str1 : Str str2 : optional) -> let [case_matters] = booleanDefaults optional [False] caseFold = caseFold' case_matters :: StrT -> StrT in return $ Int $ if Str.null str2 then nullCase str1 else mainCase (caseFold str2) (caseFold str1) bf_index = indexBuiltin "index" nullCase mainCase where nullCase = const 1 mainCase needle haystack = case Str.breakOn needle haystack of (_, "") -> 0 (prefix, _) -> fromIntegral $ 1 + Str.length prefix bf_rindex = indexBuiltin "rindex" nullCase mainCase where nullCase haystack = fromIntegral $ Str.length haystack + 1 mainCase needle haystack = case Str.breakOnEnd needle haystack of ("", _) -> 0 (prefix, _) -> fromIntegral $ 1 + Str.length prefix - Str.length needle bf_strcmp = Builtin "strcmp" 2 (Just 2) [TStr, TStr] TInt $ \[Str str1, Str str2] -> return $ Int $ case Str.toText str1 `compare` Str.toText str2 of LT -> -1 EQ -> 0 GT -> 1 bf_decode_binary = Builtin "decode_binary" 1 (Just 2) [TStr, TAny] TLst $ \(Str bin_string : optional) -> let [fully] = booleanDefaults optional [False] in fromList . pushString . BS.foldr (decode fully) ([], "") <$> binaryString bin_string where decode :: Bool -> Word8 -> ([Value], String) -> ([Value], String) decode fully b accum | not fully && Str.validChar c = (c :) <$> accum | otherwise = (Int n : pushString accum, "") where c = toEnum (fromIntegral b) :: Char n = fromIntegral b :: IntT pushString :: ([Value], String) -> [Value] pushString (vs, "") = vs pushString (vs, s) = Str (Str.fromString s) : vs bf_encode_binary = Builtin "encode_binary" 0 Nothing [] TStr $ let mkResult = return . Str . Str.fromBinary . BS.pack in maybe (raise E_INVARG) mkResult . encode where encode :: [Value] -> Maybe [Word8] encode (Int n : rest) | n >= 0 && n <= 255 = (fromIntegral n :) <$> encode rest encode (Str s : rest) = (++) <$> encodeStr s <*> encode rest encode (Lst v : rest) = (++) <$> encode (Lst.toList v) <*> encode rest encode (_ : _ ) = Nothing encode [] = Just [] encodeStr :: StrT -> Maybe [Word8] encodeStr = mapM encodeChar . Str.toString encodeChar :: Char -> Maybe Word8 encodeChar c | n <= 255 = Just (fromIntegral n) | otherwise = Nothing where n = fromEnum c :: Int matchBuiltin :: Id -> (Regexp -> Text -> MatchResult) -> Builtin matchBuiltin name matchFunc = Builtin name 2 (Just 3) [TStr, TStr, TAny] TLst $ \(Str subject : Str pattern : optional) -> let [case_matters] = booleanDefaults optional [False] in runMatch matchFunc subject pattern case_matters bf_match = matchBuiltin "match" match bf_rmatch = matchBuiltin "rmatch" rmatch runMatch :: (Regexp -> Text -> MatchResult) -> StrT -> StrT -> Bool -> MOO Value runMatch match subject pattern caseMatters = case Str.toRegexp caseMatters pattern of Right regexp -> case regexp `match` Str.toText subject of MatchSucceeded offsets -> let (m : offs) = offsets (start, end) = convert m replacements = repls 9 offs in return $ fromList [Int start, Int end, fromList replacements, Str subject] MatchFailed -> return emptyList MatchAborted -> raise E_QUOTA Left err -> let message = Str.fromString $ "Invalid pattern: " ++ err in raiseException (Err E_INVARG) message zero where convert :: (Int, Int) -> (IntT, IntT) convert (s, e) = (1 + fromIntegral s, fromIntegral e) -- convert from 0-based open interval to 1-based closed one repls :: Int -> [(Int, Int)] -> [Value] repls n (r:rs) = let (s,e) = convert r in fromList [Int s, Int e] : repls (n - 1) rs repls n [] = replicate n $ fromList [Int 0, Int (-1)] bf_substitute = Builtin "substitute" 2 (Just 2) [TStr, TLst] TStr $ \[Str template, Lst subs] -> case Lst.toList subs of [Int start', Int end', Lst replacements', Str subject'] -> do let start = fromIntegral start' :: Int end = fromIntegral end' :: Int subject = Str.toString subject' :: String subjectLen = Str.length subject' :: Int valid :: Int -> Int -> Bool valid s e = (s == 0 && e == -1) || (s > 0 && e >= s - 1 && e <= subjectLen) substr :: Int -> Int -> String substr start end = let len = end - start + 1 in take len $ drop (start - 1) subject substitution :: Value -> MOO String substitution (Lst sub) = case Lst.toList sub of [Int start', Int end'] -> do let start = fromIntegral start' end = fromIntegral end' unless (valid start end) $ raise E_INVARG return $ substr start end _ -> raise E_INVARG substitution _ = raise E_INVARG unless (valid start end && Lst.length replacements' == 9) $ raise E_INVARG replacements <- (substr start end :) <$> mapM substitution (Lst.toList replacements') let walk :: String -> MOO String walk ('%':c:cs) | isDigit c = (replacements !! digitToInt c ++) <$> walk cs | c == '%' = (c :) <$> walk cs | otherwise = raise E_INVARG walk (c:cs) = (c :) <$> walk cs walk [] = return [] Str . Str.fromString <$> walk (Str.toString template) _ -> raise E_INVARG bf_crypt = Builtin "crypt" 1 (Just 2) [TStr, TStr] TStr $ \(Str text : optional) -> let (salt : _) = maybeDefaults optional in saltString salt >>= unsafeIOtoMOO . crypt (Str.toString text) >>= maybe (raise E_INVARG) (return . Str . Str.fromString) where saltString :: Maybe Value -> MOO String saltString (Just (Str salt)) | salt `Str.compareLength` 2 /= LT = return (Str.toString salt) saltString _ = randSaltChar >>= \c1 -> randSaltChar >>= \c2 -> return [c1, c2] randSaltChar :: MOO Char randSaltChar = (saltChars !!) <$> random (0, length saltChars - 1) saltChars :: String saltChars = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ "./" hashBuiltin :: Id -> ((ByteString -> MOO Value) -> StrT -> MOO Value) -> Builtin hashBuiltin name f = Builtin name 1 (Just 3) [TStr, TStr, TAny] TStr $ \(Str input : optional) -> let (Str algorithm : optional') = defaults optional [Str "MD5"] [wantBinary] = booleanDefaults optional' [False] in f (hash algorithm wantBinary) input where hash :: StrT -> Bool -> ByteString -> MOO Value hash alg wantBinary = maybe unknown (return . Str) . hashBytesUsing (toId alg) wantBinary where unknown = let message = "Unknown hash algorithm: " <> alg in raiseException (Err E_INVARG) message (Str alg) bf_string_hash = hashBuiltin "string_hash" $ \hash -> hash . encodeUtf8 . Str.toText -- XXX Unicode bf_binary_hash = hashBuiltin "binary_hash" (<=< binaryString) -- § 4.4.2.4 Operations on Lists -- bf_length already defined above bf_is_member = Builtin "is_member" 2 (Just 2) [TAny, TLst] TInt $ \[value, Lst list] -> return $ Int $ maybe 0 (fromIntegral . succ) $ Lst.findIndex (`equal` value) list bf_listinsert = Builtin "listinsert" 2 (Just 3) [TLst, TAny, TInt] TLst $ \(Lst list : value : optional) -> let [Int index] = defaults optional [Int 1] in return $ Lst $ Lst.insert list (fromIntegral index - 1) value bf_listappend = Builtin "listappend" 2 (Just 3) [TLst, TAny, TInt] TLst $ \(Lst list : value : optional) -> let [Int index] = defaults optional [Int $ fromIntegral $ Lst.length list] in return $ Lst $ Lst.insert list (fromIntegral index) value listFunc :: LstT -> Value -> Maybe Value -> MOO Value listFunc list index newValue = case index of Int i | i' < 1 || i' > Lst.length list -> raise E_RANGE | otherwise -> return $ Lst $ maybe (Lst.delete list) (Lst.set list) newValue (pred i') where i' = fromIntegral i Str key -> case Lst.assocLens key list of Just (_, change) -> return (Lst $ change newValue) Nothing -> raise E_INVIND _ -> raise E_TYPE bf_listdelete = Builtin "listdelete" 2 (Just 2) [TLst, TAny] TLst $ \[Lst list, index] -> listFunc list index Nothing bf_listset = Builtin "listset" 3 (Just 3) [TLst, TAny, TAny] TLst $ \[Lst list, value, index] -> listFunc list index (Just value) bf_setadd = Builtin "setadd" 2 (Just 2) [TLst, TAny] TLst $ \[Lst list, value] -> return $ Lst $ if value `Lst.elem` list then list else Lst.snoc list value bf_setremove = Builtin "setremove" 2 (Just 2) [TLst, TAny] TLst $ \[Lst list, value] -> return $ Lst $ maybe list (Lst.delete list) $ value `Lst.elemIndex` list
verement/etamoo
src/MOO/Builtins/Values.hs
bsd-3-clause
17,268
178
21
4,962
6,294
3,280
3,014
372
6
-- Copyright : (C) 2009 Corey O'Connor -- License : BSD-style (see the file LICENSE) module Bind.Marshal.Prelude ( module Bind.Marshal.Prelude , module Bind.Marshal.TypePrelude , module Prelude , module Bind.Marshal.Control.Monad.Parameterized , module Data.Bool , module Data.Bits , module Data.Char , module Data.Eq , module Data.Functor , module Data.List , module Data.Int , module Data.String , module Data.Word , module NumericPrelude.Numeric , module System.IO ) where import Bind.Marshal.TypePrelude import Bind.Marshal.Control.Monad.Parameterized import Prelude ( ($) , ($!) , (.) , undefined , snd , id , const , toEnum , fromEnum , Enum(..) , Show(..) , Ord(..) ) import Data.Bits import Data.Bool import Data.Char import Data.Eq import Data.Functor import Data.List hiding ( product, sum ) import Data.Int import Data.String import Data.Word import NumericPrelude.Numeric import Foreign.C.Types ( CSize(..) ) import Foreign.Ptr import System.IO -- use the standard ifThenElse for now. -- XXX: Add a version that handles static actions more optimaly. ifThenElse True e1 _e2 = e1 ifThenElse False _e1 e2 = e2 -- | Type for size in bytes. -- -- Just an alias of Int. Which does limit the size below the actual max size that a system could -- represent. Not enough of a limitation to care right now. type Size = Int -- | Buffer regions use a BytePtr to represent the start of the region. type BytePtr = Ptr Word8
coreyoconnor/bind-marshal
src/Bind/Marshal/Prelude.hs
bsd-3-clause
2,049
0
6
849
307
204
103
46
1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} module Wigner.ExpressionHelpers( makeExpr, mapTerms, mapOpFactors, mapFuncGroups, mapFuncFactors ) where import Wigner.Expression import Wigner.Complex mapTerms :: (Term -> Expr) -> Expr -> Expr mapTerms f (Expr s) = sum (map (\(c, t) -> makeExpr c * f t) (terms s)) mapOpFactors :: (OpFactor -> Expr) -> Expr -> Expr mapOpFactors f = mapTerms processTerm where processTerm (Term Nothing fs) = makeExpr fs processTerm (Term (Just opf) fs) = makeExpr fs * f opf mapFuncGroups :: (FuncGroup -> Expr) -> Expr -> Expr mapFuncGroups f = mapTerms processTerm where processTerm (Term opf fs) = product (map f fs) * makeExpr opf mapFuncFactors :: (FuncFactor -> Expr) -> Expr -> Expr mapFuncFactors f = mapFuncGroups processGroup where processGroup (FuncProduct ffs) = product (map f (factorsExpanded ffs)) processGroup x = makeExpr x exprFromTerm t = Expr (fromTerms [(1 :: Coefficient, t)]) productFromFactor f = fromFactors [(f, 1)] class Expressable a where makeExpr :: a -> Expr instance Expressable a => Expressable [a] where makeExpr xs = product (map makeExpr xs) instance Expressable Integer where makeExpr x = fromInteger x :: Expr instance Expressable Int where makeExpr x = makeExpr (fromIntegral x :: Integer) instance Expressable Rational where makeExpr x = fromRational x :: Expr instance Expressable (Complex Rational) where makeExpr x = fromComplexRational x :: Expr instance Expressable Coefficient where makeExpr x = Expr (fromCoeff x) instance Expressable Differential where makeExpr x = exprFromTerm term where term = Term Nothing [diff_product] diff_product = DiffProduct (productFromFactor x) instance Expressable Function where makeExpr x = exprFromTerm term where term = Term Nothing [func_product] func_product = FuncProduct (productFromFactor (Factor x)) instance Expressable Operator where makeExpr x = exprFromTerm term where term = Term (Just op_product) [] op_product = NormalProduct (productFromFactor x) instance Expressable Matrix where makeExpr x = exprFromTerm term where term = Term (Just mat_product) [] mat_product = MatProduct (productFromFactor x) instance Expressable OpFactor where makeExpr x = exprFromTerm (Term (Just x) []) instance Expressable (Maybe OpFactor) where makeExpr Nothing = exprFromTerm identityTerm makeExpr (Just x) = makeExpr x instance Expressable FuncGroup where makeExpr x = exprFromTerm (Term Nothing [x]) instance Expressable Term where makeExpr = exprFromTerm instance Expressable FuncFactor where makeExpr x = exprFromTerm (Term Nothing [FuncProduct (productFromFactor x)])
fjarri/wigner
src/Wigner/ExpressionHelpers.hs
bsd-3-clause
2,749
1
14
526
934
470
464
57
2
module Data.Phonology.Representations ( FValue(..) , FMatrix(..) , Segment , RuleState , (|>|) , (|?|) , flipFValue , fMatrix , readIPA , readableIPA , readFMatrix , ipaSegment , ipaDiacritics , segmentFromFeatures , includeFts , toFMatrixPairs , diacriticFunctions , defFeatures , defSegments , defMacros , defDiacritics , defState , mkRuleState ) where import Data.Maybe (fromJust) import Data.Map (Map) import qualified Data.Map as Map import Data.List (intercalate, sortBy) import Data.Ord (comparing) import Debug.Trace (trace) import Control.Monad (foldM) import Text.ParserCombinators.Parsec import Generics.Pointless.Combinators ((><)) data FValue = Plus | Minus | Unspec | Var String deriving (Eq, Ord) instance Show FValue where show Plus = "+" show Minus = "-" show Unspec = "0" show (Var s) = s instance Read FValue where readsPrec _ value = tryParse ([('+', Plus), ('-', Minus), ('0',Unspec)] ++ [(s, Var ([s])) | s <- ['α'..'ω']]) where tryParse [] = [] tryParse ((attempt, result):xs) = if head value == attempt then [(result, tail value)] else tryParse xs data FMatrix = FMatrix (Map String FValue) deriving (Eq, Ord) instance Show FMatrix where show (FMatrix fm) = (\x -> "[" ++ x ++ "]") $ intercalate "," $ map (\(k,v) -> show v ++ k) $ Map.toAscList fm fmapFM f (FMatrix fm) = FMatrix $ f fm fromFM (FMatrix fm) = fm type Segment = (String, FMatrix) type RuleState = ([Segment], [Segment], [(String, FMatrix -> FMatrix)]) --infixr 5 |>| --infixr 5 |?| -- | Updates an FMatrix. @a |>| b@ returns an 'FMatrix' identical to -- @a@ except for feature specifications where @a@ disagrees with @b@, -- which are returned as in @b@. (|>|) :: FMatrix -> FMatrix -> FMatrix FMatrix fm2 |>| FMatrix fm1 = FMatrix $ Map.union fm1 fm2 -- | Checks for matches between feature matrices. @a |?| b@ returns -- true iff, for all feature specifications in @b@, matching feature -- specifications are found in @a@. (|?|) :: FMatrix -> FMatrix -> Bool FMatrix comparandum |?| FMatrix comparator = Map.foldrWithKey (\k v acc -> Map.findWithDefault (flipFValue v) k comparandum `elem` [Unspec, v] && acc) True comparator flipFValue :: FValue -> FValue flipFValue Plus = Minus flipFValue Minus = Plus flipFValue _ = Unspec readFMatrix :: String -> FMatrix readFMatrix input = case parse fMatrix "feature matrix" input of Right fm -> fm Left e -> error $ show e fMatrix :: GenParser Char st FMatrix fMatrix = char '[' >> spaces >> sepBy feature (char ',') >>= \fm -> spaces >> char ']' >> return (FMatrix $ Map.fromList fm) fName :: GenParser Char st String fName = many (oneOf ['a'..'z']) fValue :: GenParser Char st FValue fValue = oneOf ("+-0" ++ ['α'..'ω']) >>= return . read . (:[]) feature :: GenParser Char st (String, FValue) feature = spaces >> fValue >>= \v -> (fName >>= \k -> spaces >> return (k, v)) -- | Give a 'RuleState' and a transcription as a 'String', returns the -- representation as a list of 'Segment's. readIPA :: RuleState -> String -> [Segment] readIPA (segs, macs, dias) input = case runParser ipaString (segs, macs, dias) "feature matrix" input of Right fm -> fm Left e -> error $ show e readableIPA :: RuleState -> String -> Bool readableIPA (segs, macs, dias) input = case runParser ipaString (segs, macs, dias) "feature matrix" input of Right fm -> True Left e -> False ipaString :: GenParser Char RuleState [Segment] ipaString = many (ipaSegment >>= ipaDiacritics) ipaSegment :: GenParser Char RuleState (String, FMatrix) ipaSegment = getState >>= \(segs, _, _) -> (char '#' >> return ("#", FMatrix Map.empty)) <|> choice (map (\(l,fs) -> try $ string l >> return (l, fs)) segs) ipaDiacritics :: (String, FMatrix) -> GenParser Char RuleState (String, FMatrix) ipaDiacritics (seg, fm) = getState >>= \(_, _, dias) -> (many (choice (map (\(d, f) -> try $ string d >> return (d, f)) dias)) >>= return . foldr (\(d, f) (seg', fm') -> (seg' ++ d, f fm')) (seg, fm)) toFMatrixPairs :: [(String, String)] -> [(String, FMatrix)] toFMatrixPairs segs = reverse $ sortBy (comparing (length . fst)) [(seg, readFMatrix fs) | (seg, fs) <- segs] diacriticFunctions :: [(String, String)] -> [(String, FMatrix -> FMatrix)] diacriticFunctions dias = [(dia, \fm -> fm |>| readFMatrix fts) | (dia, fts) <- dias] includeFts :: [String] -> (String, FMatrix) -> (String, FMatrix) includeFts fts = id >< fmapFM (Map.filterWithKey (\k _ -> k `elem` fts)) bestSegmentMatch :: [Segment] -> FMatrix -> Segment bestSegmentMatch segs fm = snd $ head $ sortBy (comparing fst) [(fmEditDistance fm fm', (s', fm')) | (s', fm') <- segs] segmentFromFeatures :: [Segment] -> [(String, FMatrix -> FMatrix)] -> FMatrix -> Segment segmentFromFeatures segs dias fm = segmentFromFeatures' segs' bestSeg bestDist where bestSeg = bestSegmentMatch segs fm segs' = applyDiacritics defDiacritics bestSeg bestDist = fmEditDistance fm (snd bestSeg) segmentFromFeatures' :: [Segment] -> Segment -> Int -> Segment segmentFromFeatures' segs'' seg dist | dist == 0 = seg | dist <= dist' = seg | otherwise = segmentFromFeatures' segs''' bestSeg' dist' where bestSeg' = bestSegmentMatch segs'' fm dist' = fmEditDistance fm (snd bestSeg') segs''' = applyDiacritics defDiacritics bestSeg' fmEditDistance :: FMatrix -> FMatrix -> Int fmEditDistance (FMatrix fm1) (FMatrix fm2) = Map.size $ Map.union (difference fm1 fm2) (difference fm2 fm1) where difference = Map.differenceWithKey (\_ a' b' -> if a' /= b' then Just a' else Nothing) applyDiacritics :: [(String, FMatrix -> FMatrix)] -> Segment -> [Segment] applyDiacritics dias (s, fm) = map (\(dia, f) -> (s++dia, f fm)) dias -- | Default feature names. defFeatures :: [String] defFeatures = ["syl","son","cons","cont","delrel","lat","nas","voi","cg","sg","ant","cor","distr","hi","lo","back","round","tense"] defSegments = map (includeFts defFeatures) $ toFMatrixPairs segments defMacros = map (includeFts defFeatures) $ toFMatrixPairs macros defDiacritics = diacriticFunctions diacritics -- | Default 'RuleState' to be passed to parsers. defState :: RuleState defState = (defSegments, defMacros, defDiacritics) -- | Given segment, macro, and diacritic definitions as lists of -- ('String', 'String')s, and a list of active features as 'String's, -- returns a 'RuleState' that can be passed to rule and transcription -- parsers. mkRuleState :: [(String, String)] -> [(String, String)] -> [(String, String)] -> [String] -> RuleState mkRuleState segs macs dias fts = ( map (includeFts fts) $ toFMatrixPairs segs , map (includeFts fts) $ toFMatrixPairs macs , diacriticFunctions diacritics ) getDefMacro :: Char -> FMatrix getDefMacro m = fromJust $ lookup (m:[]) defMacros diacritics = [ ("ʷ", "[+back,+round]") , ("ʲ", "[+hi]") , ("ˤ", "[+low,+back]") , ("ˠ", "[+hi,+back]") , ("ʰ", "[-voi,-cg,+sg]") , ("ʼ", "[-voi,+cg,-sg]") , ("̤", "[+voi,-cg,+sg]") , ("̰", "[+voi,+cg,-sg]") , ("̃", "[+nas]") , ("̥", "[-voi]") , ("̩", "[+syl]") , ("ː", "[+long]") ] macros = [ ("C", "[-syl]") , ("V", "[+syl]") , ("N", "[-syl,+nas]") , ("X", "[]") ] segments = [ ("p","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,-voi,-cg,-sg,+ant,+lab,-cor,0distr,-hi,-lo,-back,-round,0tense,-long]") , ("p͡f","[-syl,-son,+cons,-cont,+delrel,-lat,-nas,-voi,-cg,-sg,+ant,+lab,-cor,0distr,-hi,-lo,-back,-round,0tense,-long]") , ("t","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,-voi,-cg,-sg,+ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("t̪","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,-voi,-cg,-sg,+ant,-lab,+cor,+distr,-hi,-lo,-back,-round,0tense,-long]") , ("t͡s","[-syl,-son,+cons,-cont,+delrel,-lat,-nas,-voi,-cg,-sg,+ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("t͡ʃ","[-syl,-son,+cons,-cont,+delrel,-lat,-nas,-voi,-cg,-sg,-ant,-lab,+cor,+distr,-hi,-lo,-back,-round,0tense,-long]") , ("ʈ","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,-voi,-cg,-sg,-ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("c","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,-voi,-cg,-sg,-ant,-lab,-cor,0distr,+hi,-lo,-back,-round,0tense,-long]") , ("k","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,-voi,-cg,-sg,-ant,-lab,-cor,0distr,+hi,-lo,+back,-round,0tense,-long]") , ("q","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,-voi,-cg,-sg,-ant,+lab,-cor,0distr,-hi,-lo,+back,-round,0tense,-long]") , ("b","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,+voi,-cg,-sg,+ant,+lab,-cor,0distr,-hi,-lo,-back,-round,0tense,-long]") , ("bv","[-syl,-son,+cons,-cont,+delrel,-lat,-nas,+voi,-cg,-sg,+ant,+lab,-cor,0distr,-hi,-lo,-back,-round,0tense,-long]") , ("d","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,+voi,-cg,-sg,+ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("d̪","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,+voi,-cg,-sg,+ant,-lab,+cor,+distr,-hi,-lo,-back,-round,0tense,-long]") , ("d͡z","[-syl,-son,+cons,-cont,+delrel,-lat,-nas,+voi,-cg,-sg,+ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("d͡ʒ","[-syl,-son,+cons,-cont,+delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,+cor,+distr,-hi,-lo,-back,-round,0tense,-long]") , ("ɖ","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("ɟ","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,0distr,+hi,-lo,-back,-round,0tense,-long]") , ("g","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,0distr,+hi,-lo,+back,-round,0tense,-long]") , ("ɢ","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,0distr,-hi,-lo,+back,-round,0tense,-long]") , ("ɓ","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,+voi,+cg,-sg,+ant,+lab,-cor,0distr,-hi,-lo,-back,-round,0tense,-long]") , ("ɗ","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,+voi,+cg,-sg,+ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("ʄ","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,+voi,+cg,-sg,-ant,-lab,-cor,0distr,+hi,-lo,-back,-round,0tense,-long]") , ("ɠ","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,+voi,+cg,-sg,-ant,-lab,-cor,0distr,+hi,-lo,+back,-round,0tense,-long]") , ("ʛ","[-syl,-son,+cons,-cont,-delrel,-lat,-nas,+voi,+cg,-sg,-ant,-lab,-cor,0distr,-hi,-lo,+back,-round,0tense,-long]") , ("ɸ","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,-voi,-cg,-sg,+ant,+lab,-cor,0distr,-hi,-lo,-back,-round,0tense,-long]") , ("β","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,+ant,+lab,-cor,0distr,-hi,-lo,-back,-round,0tense,-long]") , ("f","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,-voi,-cg,-sg,+ant,+lab,-cor,0distr,-hi,-lo,-back,-round,0tense,-long]") , ("v","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,+ant,+lab,-cor,0distr,-hi,-lo,-back,-round,0tense,-long]") , ("θ","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,-voi,-cg,-sg,+ant,-lab,+cor,+distr,-hi,-lo,-back,-round,0tense,-long]") , ("ð","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,+ant,-lab,+cor,+distr,-hi,-lo,-back,-round,0tense,-long]") , ("s","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,-voi,-cg,-sg,+ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("s̪","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,-voi,-cg,-sg,+ant,-lab,+cor,+distr,-hi,-lo,-back,-round,0tense,-long]") , ("z","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,+ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("ʃ","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,-voi,-cg,-sg,-ant,-lab,+cor,+distr,-hi,-lo,-back,-round,0tense,-long]") , ("ʒ","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,+cor,+distr,-hi,-lo,-back,-round,0tense,-long]") , ("ʂ","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,-voi,-cg,-sg,-ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("ʐ","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("ç","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,-voi,-cg,-sg,-ant,-lab,-cor,0distr,+hi,-lo,-back,-round,0tense,-long]") , ("ʝ","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,0distr,+hi,-lo,-back,-round,0tense,-long]") , ("x","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,-voi,-cg,-sg,-ant,-lab,-cor,0distr,+hi,-lo,+back,-round,0tense,-long]") , ("ɣ","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,0distr,+hi,-lo,+back,-round,0tense,-long]") , ("χ","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,-voi,-cg,-sg,-ant,-lab,-cor,0distr,-hi,-lo,+back,-round,0tense,-long]") , ("ʁ","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,0distr,-hi,-lo,+back,-round,0tense,-long]") , ("ħ","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,-voi,-cg,-sg,-ant,-lab,-cor,0distr,-hi,+lo,+back,-round,0tense,-long]") , ("ʕ","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,0distr,-hi,+lo,+back,-round,0tense,-long]") , ("h","[-syl,-son,+cons,+cont,-delrel,-lat,-nas,-voi,-cg,+sg,-ant,-lab,-cor,0distr,-hi,-lo,-back,-round,0tense,-long]") , ("ɦ","[-syl,-son,+cons,+cont,-delrel,-lat,+nas,-voi,-cg,+sg,-ant,-lab,-cor,0distr,-hi,-lo,-back,-round,0tense,-long]") , ("m","[-syl,+son,+cons,-cont,-delrel,-lat,+nas,+voi,-cg,-sg,+ant,+lab,-cor,0distr,-hi,-lo,-back,-round,0tense,-long]") , ("n","[-syl,+son,+cons,-cont,-delrel,-lat,+nas,+voi,-cg,-sg,+ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("n̪","[-syl,+son,+cons,-cont,-delrel,-lat,+nas,+voi,-cg,-sg,+ant,-lab,+cor,+distr,-hi,-lo,-back,-round,0tense,-long]") , ("ɲ","[-syl,+son,+cons,-cont,-delrel,-lat,+nas,+voi,-cg,-sg,+ant,-lab,-cor,0distr,+hi,-lo,-back,-round,0tense,-long]") , ("ɳ","[-syl,+son,+cons,-cont,-delrel,-lat,+nas,+voi,-cg,-sg,-ant,-lab,+cor,0distr,-hi,-lo,-back,-round,0tense,-long]") , ("ŋ","[-syl,+son,+cons,-cont,-delrel,-lat,+nas,+voi,-cg,-sg,-ant,-lab,-cor,0distr,+hi,-lo,+back,-round,0tense,-long]") , ("ɴ","[-syl,+son,+cons,-cont,-delrel,-lat,+nas,+voi,-cg,-sg,-ant,-lab,-cor,0distr,-hi,-lo,+back,-round,0tense,-long]") , ("ɹ","[-syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,+cor,-distr,+hi,-lo,+back,+round,0tense,-long]") , ("r","[-syl,+son,+cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,+cor,-distr,+hi,-lo,+back,+round,0tense,-long]") , ("ɻ","[-syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("l","[-syl,+son,+cons,+cont,-delrel,+lat,-nas,+voi,-cg,-sg,+ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("l̪","[-syl,+son,+cons,+cont,-delrel,+lat,-nas,+voi,-cg,-sg,+ant,-lab,+cor,+distr,-hi,-lo,-back,-round,0tense,-long]") , ("j","[-syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,0distr,+hi,-lo,-back,-round,0tense,-long]") , ("w","[-syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,+lab,-cor,0distr,+hi,-lo,+back,+round,0tense,-long]") , ("t͡l","[-syl,+son,+cons,+cont,+delrel,+lat,-nas,-voi,-cg,-sg,+ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("d͡l","[-syl,+son,+cons,+cont,+delrel,+lat,-nas,+voi,-cg,-sg,+ant,-lab,+cor,-distr,-hi,-lo,-back,-round,0tense,-long]") , ("ʔ","[-syl,+son,-cons,-cont,-delrel,-lat,-nas,-voi,+cg,-sg,-ant,-lab,-cor,0distr,-hi,-lo,-back,-round,0tense,-long]") , ("i","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,+hi,-lo,-back,-round,+tense,-long]") , ("y","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,+lab,-cor,-distr,+hi,-lo,-back,+round,+tense,-long]") , ("ɨ","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,+hi,-lo,+back,-round,+tense,-long]") , ("u","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,+lab,-cor,-distr,+hi,-lo,+back,+round,+tense,-long]") , ("e","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,-hi,-lo,-back,-round,+tense,-long]") , ("ø","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,-hi,-lo,-back,+round,+tense,-long]") , ("ʌ","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,-hi,-lo,+back,-round,+tense,-long]") , ("o","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,-hi,-lo,+back,+round,+tense,-long]") , ("æ","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,-hi,+lo,-back,-round,+tense,-long]") , ("ɶ","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,-hi,+lo,-back,+round,+tense,-long]") , ("a","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,-hi,+lo,+back,-round,+tense,-long]") , ("ɑ","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,-hi,+lo,+back,-round,+tense,-long]") , ("ɒ","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,-hi,+lo,+back,+round,+tense,-long]") , ("ɪ","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,+hi,-lo,-back,-round,-tense,-long]") , ("ʏ","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,+hi,-lo,-back,+round,-tense,-long]") , ("ɯ","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,+hi,-lo,+back,-round,-tense,-long]") , ("ʊ","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,+hi,-lo,+back,+round,-tense,-long]") , ("ɛ","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,-hi,-lo,-back,-round,-tense,-long]") , ("œ","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,-hi,-lo,-back,+round,-tense,-long]") , ("ə","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,-hi,-lo,+back,-round,-tense,-long]") , ("ɔ","[+syl,+son,-cons,+cont,-delrel,-lat,-nas,+voi,-cg,-sg,-ant,-lab,-cor,-distr,-hi,-lo,+back,+round,-tense,-long]") ]
dmort27/HsSPE
Data/Phonology/Representations.hs
bsd-3-clause
20,312
0
19
4,096
3,405
1,985
1,420
239
2
module Data.Vector.Split ( chunksOf , splitPlaces , splitPlacesBlanks , chop , divvy , module Data.Vector.Split.Internal ) where import Data.Vector.Generic (Vector) import qualified Data.Vector.Generic as V import Data.List (unfoldr) import Data.Vector.Split.Internal -- | @'chunksOf' n@ splits a vector into length-n pieces. The last -- piece will be shorter if @n@ does not evenly divide the length of -- the vector. If @n <= 0@, @'chunksOf' n l@ returns an infinite list -- of empty vectors. For example: -- -- Note that @'chunksOf' n []@ is @[]@, not @[[]]@. This is -- intentional, and is consistent with a recursive definition of -- 'chunksOf'; it satisfies the property that -- -- @chunksOf n xs ++ chunksOf n ys == chunksOf n (xs ++ ys)@ -- -- whenever @n@ evenly divides the length of @xs@. chunksOf :: Vector v a => Int -> v a -> [v a] chunksOf i = unfoldr go where go v | V.null v = Nothing | otherwise = Just (V.splitAt i v) -- | Split a vector into chunks of the given lengths. For example: -- -- > splitPlaces [2,3,4] [1..20] == [[1,2],[3,4,5],[6,7,8,9]] -- > splitPlaces [4,9] [1..10] == [[1,2,3,4],[5,6,7,8,9,10]] -- > splitPlaces [4,9,3] [1..10] == [[1,2,3,4],[5,6,7,8,9,10]] -- -- If the input vector is longer than the total of the given lengths, -- then the remaining elements are dropped. If the vector is shorter -- than the total of the given lengths, then the result may contain -- fewer chunks than requested, and the last chunk may be shorter -- than requested. splitPlaces :: Vector v a => [Int] -> v a -> [v a] splitPlaces is v = unfoldr go (is,v) where go ([],_) = Nothing go (x:xs,y) | V.null y = Nothing | otherwise = let (l,r) = V.splitAt x y in Just (l,(xs,r)) -- | Split a vector into chunks of the given lengths. Unlike -- 'splitPlaces', the output list will always be the same length as -- the first input argument. If the input vector is longer than the -- total of the given lengths, then the remaining elements are -- dropped. If the vector is shorter than the total of the given -- lengths, then the last several chunks will be shorter than -- requested or empty. For example: -- -- > splitPlacesBlanks [2,3,4] [1..20] == [[1,2],[3,4,5],[6,7,8,9]] -- > splitPlacesBlanks [4,9] [1..10] == [[1,2,3,4],[5,6,7,8,9,10]] -- > splitPlacesBlanks [4,9,3] [1..10] == [[1,2,3,4],[5,6,7,8,9,10],[]] -- -- Notice the empty list in the output of the third example, which -- differs from the behavior of 'splitPlaces'. splitPlacesBlanks :: Vector v a => [Int] -> v a -> [v a] splitPlacesBlanks is v = unfoldr go (is,v) where go ([],_) = Nothing go (x:xs,y) = let (l,r) = V.splitAt x y in Just (l,(xs,r)) -- | A useful recursion pattern for processing a list to produce a new -- list, often used for \"chopping\" up the input list. Typically -- chop is called with some function that will consume an initial -- prefix of the list and produce a value and the rest of the list. -- -- For example, many common Prelude functions can be implemented in -- terms of @chop@: -- -- > group :: (Eq a) => [a] -> [[a]] -- > group = chop (\ xs@(x:_) -> span (==x) xs) -- > -- > words :: String -> [String] -- > words = filter (not . null) . chop (span (not . isSpace) . dropWhile isSpace) chop :: Vector v a => (v a -> (b, v a)) -> v a -> [b] chop f v | V.null v = [] | otherwise = b : chop f v' where (b, v') = f v -- | Divides up an input vector into a set of subvectors, according to 'n' and 'm' -- input specifications you provide. Each subvector will have 'n' items, and the -- start of each subvector will be offset by 'm' items from the previous one. -- -- > divvy 5 5 [1..20] == [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]] -- -- In the case where a source vector's trailing elements do no fill an entire -- subvector, those trailing elements will be dropped. -- -- > divvy 5 2 [1..10] == [[1,2,3,4,5],[3,4,5,6,7],[5,6,7,8,9]] -- -- As an example, you can generate a moving average over a vector of prices: -- -- > type Prices = [Float] -- > type AveragePrices = [Float] -- > -- > average :: [Float] -> Float -- > average xs = sum xs / (fromIntegral $ length xs) -- > -- > simpleMovingAverage :: Prices -> AveragePrices -- > simpleMovingAverage priceList = -- > map average divvyedPrices -- > where divvyedPrices = divvy 20 1 priceList divvy :: Vector v a => Int -> Int -> v a -> [v a] divvy n m v | V.null v = [] | otherwise = filter (\ws -> n == V.length ws) . chop (\xs -> (V.take n xs, V.drop m xs)) $ v
fhaust/vector-split
src/Data/Vector/Split.hs
bsd-3-clause
4,721
0
13
1,100
742
418
324
33
2
{-# OPTIONS_GHC -W #-} module Parse.Helpers where import Prelude hiding (until) import Control.Applicative ((<$>),(<*>)) import Control.Monad import Control.Monad.State import Data.Char (isUpper) import qualified Data.Set as Set import qualified Data.Map as Map import Text.Parsec hiding (newline,spaces,State) import Text.Parsec.Indent import qualified Text.Parsec.Token as T import SourceSyntax.Annotation as Annotation import SourceSyntax.Declaration (Assoc) import SourceSyntax.Expression import SourceSyntax.Helpers as Help import SourceSyntax.PrettyPrint import SourceSyntax.Variable as Variable reserveds = [ "if", "then", "else" , "case", "of" , "let", "in" , "data", "type" , "module", "where" , "import", "as", "hiding", "open" , "export", "foreign" , "deriving", "port" ] jsReserveds :: Set.Set String jsReserveds = Set.fromList [ "null", "undefined", "Nan", "Infinity", "true", "false", "eval" , "arguments", "int", "byte", "char", "goto", "long", "final", "float" , "short", "double", "native", "throws", "boolean", "abstract", "volatile" , "transient", "synchronized", "function", "break", "case", "catch" , "continue", "debugger", "default", "delete", "do", "else", "finally" , "for", "function", "if", "in", "instanceof", "new", "return", "switch" , "this", "throw", "try", "typeof", "var", "void", "while", "with", "class" , "const", "enum", "export", "extends", "import", "super", "implements" , "interface", "let", "package", "private", "protected", "public" , "static", "yield" -- reserved by the Elm runtime system , "Elm", "ElmRuntime" , "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9" , "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9" ] expecting = flip (<?>) type OpTable = Map.Map String (Int, Assoc) type SourceM = State SourcePos type IParser a = ParsecT String OpTable SourceM a iParse :: IParser a -> String -> Either ParseError a iParse = iParseWithTable "" Map.empty iParseWithTable :: SourceName -> OpTable -> IParser a -> String -> Either ParseError a iParseWithTable sourceName table aParser input = runIndent sourceName $ runParserT aParser table sourceName input var :: IParser String var = makeVar (letter <|> char '_' <?> "variable") lowVar :: IParser String lowVar = makeVar (lower <?> "lower case variable") capVar :: IParser String capVar = makeVar (upper <?> "upper case variable") qualifiedVar :: IParser String qualifiedVar = do vars <- many ((++) <$> capVar <*> string ".") (++) (concat vars) <$> lowVar rLabel :: IParser String rLabel = lowVar innerVarChar :: IParser Char innerVarChar = alphaNum <|> char '_' <|> char '\'' <?> "" makeVar :: IParser Char -> IParser String makeVar p = do v <- (:) <$> p <*> many innerVarChar if v `elem` reserveds then fail $ "unexpected keyword '" ++ v ++ "', variables cannot be keywords" else return v reserved :: String -> IParser String reserved word = try (string word >> notFollowedBy innerVarChar) >> return word <?> "reserved word '" ++ word ++ "'" anyOp :: IParser String anyOp = betwixt '`' '`' qualifiedVar <|> symOp <?> "infix operator (e.g. +, *, ||)" symOp :: IParser String symOp = do op <- many1 (satisfy Help.isSymbol) guard (op `notElem` [ "=", "..", "->", "--", "|", "\8594", ":" ]) case op of "." -> notFollowedBy lower >> return op "\8728" -> return "." _ -> return op padded :: IParser a -> IParser a padded p = do whitespace out <- p whitespace return out equals :: IParser String equals = string "=" arrow :: IParser String arrow = string "->" <|> string "\8594" <?> "arrow (->)" hasType :: IParser String hasType = string ":" <?> "':' (a type annotation)'" commitIf check p = commit <|> try p where commit = do (try $ lookAhead check) >> p spaceySepBy1 :: IParser b -> IParser a -> IParser [a] spaceySepBy1 sep p = do a <- p (a:) <$> many (commitIf (whitespace >> sep) (padded sep >> p)) commaSep1 :: IParser a -> IParser [a] commaSep1 = spaceySepBy1 (char ',' <?> "comma ','") commaSep :: IParser a -> IParser [a] commaSep = option [] . commaSep1 semiSep1 :: IParser a -> IParser [a] semiSep1 = spaceySepBy1 (char ';' <?> "semicolon ';'") pipeSep1 :: IParser a -> IParser [a] pipeSep1 = spaceySepBy1 (char '|' <?> "type divider '|'") consSep1 :: IParser a -> IParser [a] consSep1 = spaceySepBy1 (string "::" <?> "cons operator '::'") dotSep1 :: IParser a -> IParser [a] dotSep1 p = (:) <$> p <*> many (try (char '.') >> p) spaceSep1 :: IParser a -> IParser [a] spaceSep1 p = (:) <$> p <*> spacePrefix p spacePrefix p = constrainedSpacePrefix p (\_ -> return ()) constrainedSpacePrefix p constraint = many $ choice [ try (spacing >> lookAhead (oneOf "[({")) >> p , try (spacing >> p) ] where spacing = do n <- whitespace constraint n indented failure msg = do inp <- getInput setInput ('x':inp) anyToken fail msg followedBy a b = do x <- a ; b ; return x betwixt a b c = do char a ; out <- c char b <?> "closing '" ++ [b] ++ "'" ; return out surround a z name p = do char a v <- padded p char z <?> unwords ["closing", name, show z] return v braces :: IParser a -> IParser a braces = surround '[' ']' "brace" parens :: IParser a -> IParser a parens = surround '(' ')' "paren" brackets :: IParser a -> IParser a brackets = surround '{' '}' "bracket" addLocation :: (Pretty a) => IParser a -> IParser (Annotation.Located a) addLocation expr = do (start, e, end) <- located expr return (Annotation.at start end e) located :: IParser a -> IParser (SourcePos, a, SourcePos) located p = do start <- getPosition e <- p end <- getPosition return (start, e, end) accessible :: IParser ParseExpr -> IParser ParseExpr accessible expr = do start <- getPosition ce@(A _ e) <- expr let rest f = do let dot = char '.' >> notFollowedBy (char '.') access <- optionMaybe (try dot <?> "field access (e.g. List.map)") case access of Nothing -> return ce Just _ -> accessible $ do v <- var <?> "field access (e.g. List.map)" end <- getPosition return (Annotation.at start end (f v)) case e of Var (Variable.Raw (c:cs)) | isUpper c -> rest (\v -> rawVar (c:cs ++ '.':v)) | otherwise -> rest (Access ce) _ -> rest (Access ce) spaces :: IParser String spaces = concat <$> many1 (multiComment <|> string " ") <?> "spaces" forcedWS :: IParser String forcedWS = choice [ try $ (++) <$> spaces <*> (concat <$> many nl_space) , try $ concat <$> many1 nl_space ] where nl_space = try ((++) <$> (concat <$> many1 newline) <*> spaces) -- Just eats whitespace until the next meaningful character. dumbWhitespace :: IParser String dumbWhitespace = concat <$> many (spaces <|> newline) whitespace :: IParser String whitespace = option "" forcedWS <?> "whitespace" freshLine :: IParser [[String]] freshLine = try (many1 newline >> many space_nl) <|> try (many1 space_nl) <?> "" where space_nl = try $ spaces >> many1 newline newline :: IParser String newline = simpleNewline <|> lineComment <?> "newline" simpleNewline :: IParser String simpleNewline = try (string "\r\n") <|> string "\n" lineComment :: IParser String lineComment = do try (string "--") comment <- anyUntil $ simpleNewline <|> (eof >> return "\n") return ("--" ++ comment) multiComment :: IParser String multiComment = (++) <$> try (string "{-") <*> closeComment closeComment :: IParser String closeComment = anyUntil . choice $ [ try (string "-}") <?> "close comment" , concat <$> sequence [ try (string "{-"), closeComment, closeComment ] ] until :: IParser a -> IParser b -> IParser b until p end = go where go = end <|> (p >> go) anyUntil :: IParser String -> IParser String anyUntil end = go where go = end <|> (:) <$> anyChar <*> go ignoreUntil :: IParser a -> IParser (Maybe a) ignoreUntil end = go where ignore p = const () <$> p filler = choice [ try (ignore chr) <|> ignore str , ignore multiComment , ignore (markdown (\_ -> mzero)) , ignore anyChar ] go = choice [ Just <$> end , filler `until` choice [ const Nothing <$> eof, newline >> go ] ] onFreshLines :: (a -> b -> b) -> b -> IParser a -> IParser b onFreshLines insert init thing = go init where go values = do optionValue <- ignoreUntil thing case optionValue of Nothing -> return values Just v -> go (insert v values) withSource :: IParser a -> IParser (String, a) withSource p = do start <- getParserState result <- p endPos <- getPosition setParserState start raw <- anyUntilPos endPos return (raw, result) anyUntilPos :: SourcePos -> IParser String anyUntilPos pos = go where go = do currentPos <- getPosition case currentPos == pos of True -> return [] False -> (:) <$> anyChar <*> go markdown :: ([a] -> IParser (String, [a])) -> IParser (String, [a]) markdown interpolation = try (string "[markdown|") >> closeMarkdown (++ "") [] where closeMarkdown md stuff = choice [ do try (string "|]") return (md "", stuff) , (\(m,s) -> closeMarkdown (md . (m ++)) s) =<< interpolation stuff , do c <- anyChar closeMarkdown (md . ([c]++)) stuff ] --str :: IParser String str = expecting "String" $ do s <- choice [ multiStr, singleStr ] processAs T.stringLiteral . sandwich '\"' $ concat s where rawString quote insides = quote >> manyTill insides quote multiStr = rawString (try (string "\"\"\"")) multilineStringChar singleStr = rawString (char '"') stringChar stringChar :: IParser String stringChar = choice [ newlineChar, escaped '\"', (:[]) <$> satisfy (/= '\"') ] multilineStringChar :: IParser String multilineStringChar = do noEnd choice [ newlineChar, escaped '\"', expandQuote <$> anyChar ] where noEnd = notFollowedBy (string "\"\"\"") expandQuote c = if c == '\"' then "\\\"" else [c] newlineChar :: IParser String newlineChar = choice [ char '\n' >> return "\\n" , char '\r' >> return "\\r" ] sandwich :: Char -> String -> String sandwich delim s = delim : s ++ [delim] escaped :: Char -> IParser String escaped delim = try $ do char '\\' c <- char '\\' <|> char delim return ['\\', c] chr :: IParser Char chr = betwixt '\'' '\'' character <?> "character" where nonQuote = satisfy (/='\'') character = do c <- choice [ escaped '\'' , (:) <$> char '\\' <*> many1 nonQuote , (:[]) <$> nonQuote ] processAs T.charLiteral $ sandwich '\'' c processAs :: (T.GenTokenParser String u SourceM -> IParser a) -> String -> IParser a processAs processor s = calloutParser s (processor lexer) where calloutParser :: String -> IParser a -> IParser a calloutParser inp p = either (fail . show) return (iParse p inp) lexer :: T.GenTokenParser String u SourceM lexer = T.makeTokenParser elmDef -- I don't know how many of these are necessary for charLiteral/stringLiteral elmDef :: T.GenLanguageDef String u SourceM elmDef = T.LanguageDef { T.commentStart = "{-" , T.commentEnd = "-}" , T.commentLine = "--" , T.nestedComments = True , T.identStart = undefined , T.identLetter = undefined , T.opStart = undefined , T.opLetter = undefined , T.reservedNames = reserveds , T.reservedOpNames = [":", "->", "<-", "|"] , T.caseSensitive = True }
deadfoxygrandpa/Elm
compiler/Parse/Helpers.hs
bsd-3-clause
12,328
0
22
3,392
4,234
2,192
2,042
295
3
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE OverloadedStrings #-} module Develop.StaticFiles.Build ( readAsset , compile ) where import Control.Monad (void) import qualified Data.ByteString as BS import qualified System.Directory as Dir import System.FilePath ((</>)) import qualified Elm.Project as Project import qualified Reporting.Task as Task import qualified Reporting.Progress.Terminal as Terminal -- ASSETS readAsset :: FilePath -> IO BS.ByteString readAsset path = BS.readFile ("ui" </> "assets" </> path) -- COMPILE compile :: IO BS.ByteString compile = return "" {- do Dir.setCurrentDirectory "ui" reporter <- Terminal.create void $ Task.run reporter $ do summary <- Project.getRoot Project.compile summary rootPaths result <- BS.readFile "elm.js" seq (BS.length result) (Dir.removeFile "elm.js") Dir.setCurrentDirectory ".." return result -} rootPaths :: [FilePath] rootPaths = [ "src" </> "Errors.elm" , "src" </> "Index.elm" , "src" </> "Start.elm" , "src" </> "NotFound.elm" ]
evancz/cli
src/Develop/StaticFiles/Build.hs
bsd-3-clause
1,089
0
8
231
180
112
68
24
1
{-# LANGUAGE CPP,TemplateHaskell,DeriveDataTypeable #-} module Data.Encoding.ISO885914 (ISO885914(..)) where import Data.Array ((!),Array) import Data.Word (Word8) import Data.Map (Map,lookup,member) import Data.Encoding.Base import Prelude hiding (lookup) import Control.OldException (throwDyn) import Data.Typeable data ISO885914 = ISO885914 deriving (Eq,Show,Typeable) enc :: Char -> Word8 enc c = case lookup c encodeMap of Just v -> v Nothing -> throwDyn (HasNoRepresentation c) instance Encoding ISO885914 where encode _ = encodeSinglebyte enc encodeLazy _ = encodeSinglebyteLazy enc encodable _ c = member c encodeMap decode _ = decodeSinglebyte (decodeArr!) decodeArr :: Array Word8 Char #ifndef __HADDOCK__ decodeArr = $(decodingArray "8859-14.TXT") #endif encodeMap :: Map Char Word8 #ifndef __HADDOCK__ encodeMap = $(encodingMap "8859-14.TXT") #endif
abuiles/turbinado-blog
tmp/dependencies/encoding-0.4.1/Data/Encoding/ISO885914.hs
bsd-3-clause
876
2
10
120
270
149
121
24
2
module Network.DNS.Cache.Types ( Key , Prio , Value(..) , Entry , Result(..) , HostAddress , Domain , DNSError(..) ) where import Data.Array.Unboxed (UArray) import Data.ByteString.Short (ShortByteString) import Data.IORef (IORef) import Data.Time (UTCTime) import Network.DNS (Domain, DNSError(..)) import Network.Socket (HostAddress) type Key = ShortByteString -- avoiding memory fragmentation type Prio = UTCTime -- fixme: if UArray causes memory fragments, -- we should use real-time queue instaed. data Value = Value (UArray Int HostAddress) (IORef Int) instance Show Value where show (Value a _) = show a -- | Information of positive result. data Result = -- | An address obtained from the cache. Hit HostAddress -- | An address resolved from cache DNS servers. | Resolved HostAddress -- | Specified domain is IP address. So, it is converted into a numeric address. | Numeric HostAddress deriving (Eq,Show) type Entry = Either DNSError Value
kazu-yamamoto/concurrent-dns-cache
Network/DNS/Cache/Types.hs
bsd-3-clause
1,001
0
8
195
227
139
88
26
0
{-# LANGUAGE QuasiQuotes #-} module Widgets where import Graphics.UI.Threepenny.Core import qualified Graphics.UI.Threepenny as UI import Control.Monad (mapM, zipWithM_) import qualified NeatInterpolation as N import qualified Data.Text as T 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 -> if showing then do element collapsingSection # set style [("display", "none")] element toggle # set text "+" else do element collapsingSection # set style [("display", "block")] 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 :: Int -> [a] -> [a] deleteIndex _ [] = [] deleteIndex 0 (_:xs) = xs deleteIndex n xs'@(x:xs) | n < 0 = xs' | otherwise = x : deleteIndex (n-1) xs infixl 8 ## (##) :: UI Element -> String -> UI Element e ## ident = e # set UI.id_ ident uploadButton :: UI (Element, (String -> UI a) -> UI ()) uploadButton = do fileIn <- UI.input # set UI.id_ "file" # set UI.type_ "file" bIn <- stepper "Starting from NULL" $ UI.valueChange fileIn let installHandler h = do w <- UI.askWindow handler <- UI.ffiExport (\s -> runUI w $ do h s return () ) UI.runFunction (ffi onloadJS handler) return (fileIn, installHandler) onloadJS = T.unpack [N.text| document.querySelector('#file').addEventListener('change', function() { var reader = new FileReader(); reader.addEventListener('load', function() { %1(reader.result) }); reader.readAsBinaryString(this.files[0]); });|]
Chaddai/CurveProject
high-school-plotting/uiSrc/Widgets.hs
bsd-3-clause
3,271
0
20
926
1,087
544
543
65
2
module Transf.AntiPattern where -- todo: -- - for assignables-go-right -- - support more BinOp's with "<=" -> ">=" etc -- - support joined conditionals on "&&", "||", etc -- - more anti-pattern correctors import Lang.Php import TransfUtil import Util import qualified Data.Intercal as IC transfs :: [Transf] transfs = [ "assignables-go-right" -:- ftype -?- "\"if ($x == true)\" -> \"if (true == $x)\" etc" -=- (\ [] -> lexPass assignablesGoRight), "kill-split" -:- ftype -?- "split() becomes preg_split()" -- TODO: detect non-regex case and go to explode() instead of preg_split()? -=- (\ [] -> lexPass killSplit), "preg-split-non-regex" -:- ftype -?- "preg_split('/a/', ..) becomes explode('a', ..)" -=- (\ [] -> lexPass pregSplitNonRegex) ] assignablesGoRight :: Ast -> Transformed Ast assignablesGoRight = modAll . modIfBlockExpr $ modWSCap2 exprLRValToRight exprLRValToRight :: Expr -> Transformed Expr exprLRValToRight (ExprBinOp op e1 w e2) | op `elem` [BEQ, BNE, BID, BNI] = swapIfGood op | op == BLT = swapIfGood BGT | op == BGT = swapIfGood BLT | op == BLE = swapIfGood BGE | op == BGE = swapIfGood BLE | otherwise = transfNothing where swapIfGood op' = if exprIsLRVal e1 && not (exprIsLRVal e2) then pure $ ExprBinOp op' e2 w e1 else transfNothing exprLRValToRight _ = transfNothing exprIsLRVal :: Expr -> Bool exprIsLRVal (ExprRVal (RValLRVal _)) = True exprIsLRVal _ = False killSplit :: Ast -> Transformed Ast killSplit = modAll $ \ a -> case a of ROnlyValFunc _c@(Right (Const [] "split")) w (Right (arg0:args)) -> case arg0 of WSCap w1 (Left (ExprStrLit (StrLit s))) w2 -> pure . ROnlyValFunc c' w $ Right (arg0':args) where c' = Right (Const [] "preg_split") arg0' = WSCap w1 (strToArg s') w2 s' = onTail (onInit $ delimify '/' '\\') s _ -> transfNothing _ -> transfNothing delimify :: (Eq a) => a -> a -> [a] -> [a] delimify delim esc s = [delim] ++ concatMap doEsc s ++ [delim] where doEsc c = if c == delim then [esc, c] else [c] onTail :: ([a] -> [a]) -> [a] -> [a] onTail f (x:l) = x : f l onTail _f l = l onInit :: ([a] -> [a]) -> [a] -> [a] onInit = reversify . onTail . reversify pregSplitNonRegex :: Ast -> Transformed Ast pregSplitNonRegex = modAll $ \ a -> case a of ROnlyValFunc _c@(Right (Const [] "preg_split")) w (Right (arg0:args)) -> if length args `elem` [1, 2] then case arg0 of WSCap w1 (Left (ExprStrLit (StrLit s))) w2 -> if null sRegexPost then if null sRegexUnits then if length args == 1 then pure . ROnlyValFunc cStrSplit w $ Right argsAlone else transfNothing else if any regexUnitIsMeta sRegexUnits then transfNothing else pure . ROnlyValFunc cExplode w $ Right (arg0':args) else transfNothing where (sIsDub, sUnits) = strToUnits s (_, (sRegexUnits, sRegexPost)) = regexUnits $ map normalizeStrUnit sUnits cExplode = Right (Const [] "explode") cStrSplit = Right (Const [] "str_split") arg0' = WSCap w1 (strToArg s') w2 s' = strUnitsToStr (sIsDub, map last sRegexUnits) argsAlone = onHead (onWSCap1 $ wsStartTransfer w1) args _ -> transfNothing else transfNothing _ -> transfNothing regexUnitIsMeta :: [String] -> Bool regexUnitIsMeta [c] = normedStrUnitIsRegexMeta c regexUnitIsMeta ["\\\\", c] = isAlphaNum . chr $ phpOrd c -- note that "." and "\x2E" in a PHP str both count as any-char for -- preg stuff normedStrUnitIsRegexMeta :: String -> Bool normedStrUnitIsRegexMeta u = any (== chr (phpOrd u)) "|^$*+?.()[{" strToArg :: String -> Either Expr b strToArg = Left . ExprStrLit . StrLit
facebookarchive/lex-pass
src/Transf/AntiPattern.hs
bsd-3-clause
3,940
0
20
1,080
1,276
669
607
85
8
-- | -- Module: Math.NumberTheory.Logarithms.Internal -- Copyright: (c) 2011 Daniel Fischer -- Licence: MIT -- Maintainer: Daniel Fischer <[email protected]> -- Stability: Provisional -- Portability: Non-portable (GHC extensions) -- -- Low level stuff for integer logarithms. {-# LANGUAGE CPP, MagicHash, UnboxedTuples #-} {-# OPTIONS_HADDOCK hide #-} module Math.NumberTheory.Logarithms.Internal ( -- * Functions integerLog2# , wordLog2# ) where #if __GLASGOW_HASKELL__ >= 702 -- Stuff is already there import GHC.Integer.Logarithms #else -- We have to define it here #include "MachDeps.h" import GHC.Base import GHC.Integer.GMP.Internals #if (WORD_SIZE_IN_BITS != 32) && (WORD_SIZE_IN_BITS != 64) #error Only word sizes 32 and 64 are supported. #endif #if WORD_SIZE_IN_BITS == 32 #define WSHIFT 5 #define MMASK 31 #else #define WSHIFT 6 #define MMASK 63 #endif {- Reference implementation only, the algorithm in M.NT.Logarithms is better. -- | Calculate the integer logarithm for an arbitrary base. -- The base must be greater than 1, the second argument, the number -- whose logarithm is sought; should be positive, otherwise the -- result is meaningless. -- -- > base ^ integerLogBase# base m <= m < base ^ (integerLogBase# base m + 1) -- -- for @base > 1@ and @m > 0@. integerLogBase# :: Integer -> Integer -> Int# integerLogBase# b m = case step b of (# _, e #) -> e where step pw = if m `ltInteger` pw then (# m, 0# #) else case step (pw `timesInteger` pw) of (# q, e #) -> if q `ltInteger` pw then (# q, 2# *# e #) else (# q `quotInteger` pw, 2# *# e +# 1# #) -} -- | Calculate the integer base 2 logarithm of an 'Integer'. -- The calculation is much more efficient than for the general case. -- -- The argument must be strictly positive, that condition is /not/ checked. integerLog2# :: Integer -> Int# integerLog2# (S# i) = wordLog2# (int2Word# i) integerLog2# (J# s ba) = check (s -# 1#) where check i = case indexWordArray# ba i of 0## -> check (i -# 1#) w -> wordLog2# w +# (uncheckedIShiftL# i WSHIFT#) -- | This function calculates the integer base 2 logarithm of a 'Word#'. -- @'wordLog2#' 0## = -1#@. {-# INLINE wordLog2# #-} wordLog2# :: Word# -> Int# wordLog2# w = case leadingZeros of BA lz -> let zeros u = indexInt8Array# lz (word2Int# u) in #if WORD_SIZE_IN_BITS == 64 case uncheckedShiftRL# w 56# of a -> if a `neWord#` 0## then 64# -# zeros a else case uncheckedShiftRL# w 48# of b -> if b `neWord#` 0## then 56# -# zeros b else case uncheckedShiftRL# w 40# of c -> if c `neWord#` 0## then 48# -# zeros c else case uncheckedShiftRL# w 32# of d -> if d `neWord#` 0## then 40# -# zeros d else #endif case uncheckedShiftRL# w 24# of e -> if e `neWord#` 0## then 32# -# zeros e else case uncheckedShiftRL# w 16# of f -> if f `neWord#` 0## then 24# -# zeros f else case uncheckedShiftRL# w 8# of g -> if g `neWord#` 0## then 16# -# zeros g else 8# -# zeros w -- Lookup table data BA = BA ByteArray# leadingZeros :: BA leadingZeros = let mkArr s = case newByteArray# 256# s of (# s1, mba #) -> case writeInt8Array# mba 0# 9# s1 of s2 -> let fillA lim val idx st = if idx ==# 256# then st else if idx <# lim then case writeInt8Array# mba idx val st of nx -> fillA lim val (idx +# 1#) nx else fillA (2# *# lim) (val -# 1#) idx st in case fillA 2# 8# 1# s2 of s3 -> case unsafeFreezeByteArray# mba s3 of (# _, ba #) -> ba in case mkArr realWorld# of b -> BA b #endif
shlevy/arithmoi
Math/NumberTheory/Logarithms/Internal.hs
mit
4,592
1
40
1,820
713
378
335
-1
-1
{-# OPTIONS_GHC -fglasgow-exts #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Morphism.Synchro -- Copyright : (C) 2008 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : non-portable (rank-2 polymorphism) -- -- Martin Erwig's synchromorphisms. ---------------------------------------------------------------------------- module Control.Morphism.Synchro where import Control.Category.Cartesian ((&&&)) import Control.Category.Hask import Control.Functor import Control.Functor.Algebra -- | @synchro d' f d g1 g2 d''@ is Martin Erwig's @d,d''-synchromorphism to d'@. Mostly useful for graph algorithms. synchro :: QFunctor h Hask Hask => Bialgebra m n c -> (h x (Either a c) -> m c) -> Trialgebra (f x) (g x) (h x) a -> ((h x a, b) -> k x b) -> ((h x a, j x b) -> h x (Either a (g x a, b))) -> Bialgebra (k x) (j x) b -> (g x a, b) -> c -- g1 -- h = D' <- D <-> D'' -- f g2 -- dfs = List <- Graph <-> Stack -- depth-first search -- bfs = List <- Graph <-> Queue -- breadth-first search synchro d' f d g1 g2 d'' = h where h = fst d' . f . second (second h) . g2 . (fst &&& (snd d'' . fst d'' . g1)) . first (snd d) -- (g x a, b) >- first (snd d) -> -- (h x a, b) >- (fst &&& g1) -> -- (h x a, k x b) >- second (fst d'') -> -- (h x a, b) >- second (snd d'') -> -- (h x a, j x b) >- g2 -> -- (h x (Either a (g x a, b)) >- second (second h) -> -- (h x (Either a c)) >- f -> -- m c >- fst d' -- c
urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav
Control/Morphism/Synchro.hs
apache-2.0
1,645
16
17
394
372
205
167
-1
-1
module Yesod.Helpers.Acid ( module Yesod.Helpers.Acid , AcidState , skipAuthenticationCheck, skipAuthenticationPerform , sharedSecretCheck, sharedSecretPerform ) where import Prelude import Data.Acid import Data.Acid.Remote import Data.Acid.Memory (openMemoryState) import Data.SafeCopy (SafeCopy) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Concurrent (forkIO) #if !MIN_VERSION_base(4,8,0) import Control.Applicative ((<$>), (<*>)) #endif import Control.Monad import Control.Monad.Logger (MonadLogger, logError) import Control.Exception (try) import Control.Concurrent (threadDelay) import Control.Arrow ((&&&)) import Data.Monoid ((<>)) import Data.String (fromString) import System.Timeout (timeout) import Network (HostName, PortID) import Data.Aeson (withObject, FromJSON, parseJSON , (.:), (.:?), (.!=) ) import Data.Streaming.Network (HostPreference, bindPortTCP) import Data.Time (getCurrentTime, UTCTime) #if !MIN_VERSION_base(4,8,0) import Data.Traversable (traverse) #endif import Yesod.Helpers.Aeson import Yesod.Helpers.Parsec acidCached :: ( MonadIO m , QueryEvent eventq, UpdateEvent eventu , EventResult eventq ~ Maybe r , st ~ EventState eventq , st ~ EventState eventu ) => eventq -> (r -> eventu) -> m r -> AcidState st -> m r acidCached q u f acid = do mr <- liftIO $ query acid q case mr of Just x -> return x Nothing -> do new_r <- f _ <- liftIO $ forkIO $ void $ update acid (u new_r) return new_r class AcidCacheArm st f a where acidCacheArmed :: a -> f -> AcidState st -> f -- | This instance says: -- use a pair of Query and Update to wrap a function, -- cache its result in acid. -- retrieve the result from cache if cache is still considered fresh, -- otherwise call the original function to get fresh result. instance ( MonadIO m , QueryEvent eventq, UpdateEvent eventu , EventResult eventq ~ Maybe r , st ~ EventState eventq , st ~ EventState eventu ) => AcidCacheArm st (m r) (eventq, r -> eventu) where acidCacheArmed (q, u) func acid = acidCached q u func acid instance ( MonadIO m , QueryEvent eventq, UpdateEvent eventu , EventResult eventq ~ Maybe r , st ~ EventState eventq , st ~ EventState eventu ) => AcidCacheArm st (m (Maybe r)) (eventq, r -> eventu) where acidCacheArmed (q, u) func acid = do mr <- liftIO $ query acid q case mr of Just x -> return $ Just x Nothing -> do new_mr <- func case new_mr of Nothing -> return Nothing Just new_r -> do _ <- liftIO $ forkIO $ void $ update acid (u new_r) return $ Just new_r instance AcidCacheArm st f a => AcidCacheArm st (a1 -> f) (a1 -> a) where acidCacheArmed x func acid = \x1 -> acidCacheArmed (x x1) (func x1) acid -- | simple helper: usually we need to provide current time to -- construct the Query and Update. acidCacheArmedTTL :: ( AcidCacheArm st (m r) (c, c'), MonadIO m) => (UTCTime -> c) -> (UTCTime -> c') -> m r -- ^ the function to wrap -> AcidState st -> m r acidCacheArmedTTL q u f acid = do now <- liftIO getCurrentTime acidCacheArmed (q &&& u $ now) f acid -- | openRemoteState with timeout and log openRemoteStateTL :: (IsAcidic st, MonadIO m, MonadLogger m) => Int -> HostName -> PortID -> m (Maybe (AcidState st)) openRemoteStateTL ms hostname port = do m_acid <- liftIO $ timeout ms $ try $ openRemoteState skipAuthenticationPerform hostname port case m_acid of Nothing -> do $(logError) $ "cannot open remote acid-state server: timed-out in " <> fromString (show ms) <> " microseconds" return Nothing Just (Left err) -> do $(logError) $ "cannot open remote acid-state server, got exception: " <> (fromString $ show (err :: IOError)) return Nothing Just (Right x) -> return $ Just x -- | configuration for acid-state data AcidStateConfig = AcidStateConfig { acidConfigConnect :: Either FilePath ConnectPath -- ^ open local or connect to remote acid , acidConfigServeHost :: HostPreference -- ^ serve acid state at host , acidConfigPort :: Maybe Int -- ^ serve acid state at this port -- if it is Nothing, no server will be started } deriving (Show) instance FromJSON AcidStateConfig where parseJSON = withObject "AcidStateConfig" $ \obj -> do AcidStateConfig <$> ( obj .: "connect" >>= parseTextByParsec parseFileOrConnectPath ) <*> ( fmap fromString $ obj .:? "serve-host" .!= "*4" ) <*> ( obj .:? "serve-port" >>= return . nullTextToNothing >>= traverse (parseIntWithTextparsec simpleParser)) -- | if acid state configurated to use local file system acidStateConfigLocal :: AcidStateConfig -> Bool acidStateConfigLocal conf = case acidConfigConnect conf of Left _ -> True Right _ -> False acidStateConfigMemory :: AcidStateConfig -> Bool acidStateConfigMemory conf = case acidConfigConnect conf of Left "memory" -> True _ -> False acidStateConfigLocalPath :: AcidStateConfig -> Maybe FilePath acidStateConfigLocalPath conf = case acidConfigConnect conf of Left fp | fp /= "memory" -> Just fp _ -> Nothing acidServeOn :: (SafeCopy st) => (CommChannel -> IO Bool) -> Int -> HostPreference -> AcidState st -> IO () acidServeOn auth port host acid = do socket <- bindPortTCP port host acidServer' auth socket acid acidFlushRepeatly :: Int -> AcidState st -> IO () acidFlushRepeatly ms acid = forever $ do threadDelay ms createCheckpoint acid acidServerByConfig :: (SafeCopy st) => AcidStateConfig -> Maybe ((CommChannel -> IO Bool) -> AcidState st -> IO ()) -- ^ return the IO action if server should be started acidServerByConfig config = fmap (\x auth acid-> acidServeOn auth x host acid) $ acidConfigPort config where host = acidConfigServeHost config -- | open acid state according to AcidStateConfig acidOpenByConfig :: (IsAcidic st, MonadLogger m, MonadIO m) => st -> AcidStateConfig -> Int -> m (Maybe (AcidState st)) acidOpenByConfig s config ms = do case acidConfigConnect config of Right cp -> acidOpenConnectPath ms cp Left "memory" -> liftIO $ fmap Just $ openMemoryState s Left fp -> liftIO $ fmap Just $ openLocalStateFrom fp s acidOpenConnectPath :: (IsAcidic st, MonadLogger m, MonadIO m) => Int -> ConnectPath -> m (Maybe (AcidState st)) acidOpenConnectPath ms (host, port) = openRemoteStateTL ms host port checkInitAcid :: ( MonadIO m , QueryEvent qevent, UpdateEvent uevent , EventResult qevent ~ Bool , st ~ EventState qevent , st ~ EventState uevent ) => AcidState st -> qevent -> (t -> uevent) -> m t -> m () checkInitAcid acid q u f = do b <- liftIO $ query acid q when b $ do r <- f _ <- liftIO $ update acid $ u r return ()
yoo-e/yesod-helpers
Yesod/Helpers/Acid.hs
bsd-3-clause
8,353
0
22
3,009
2,160
1,098
1,062
-1
-1
#!/usr/bin/env runhaskell module Main where import Control.Monad.Reader import qualified Control.Monad.State as State import Control.Monad.Trans(liftIO) import Data.ByteString.Char8 as ByteString(ByteString, empty, hGet, pack, unpack) import Data.List(intersperse) import Graphics.UI.Gtk import Graphics.UI.Gtk.Glade import Graphics.UI.Gtk.SourceView import Numeric import System.Environment(getArgs) import System.Glib.MainLoop import System.Glib.Types import Data.IORef import Data.List import Data.Maybe import qualified Data.Map as Map import qualified Data.Set as Set import Data.Tree import Resolver.Log import Resolver.PrettyPrint import Resolver.Types import Resolver.Util import System.IO import System.Time import Text.Printf import DotRender import Types xmlFilename = "resolver-visualize.glade" data MainLoopContext = MainLoopContext { mainLoop :: MainLoop, numMainWindows :: IORef Integer } type MainM = ReaderT MainLoopContext IO runMain :: (MainM a) -> MainLoopContext -> IO a runMain = runReaderT mainWindowClosed :: MainM () mainWindowClosed = do ctx <- ask liftIO $ do modifyIORef (numMainWindows ctx) (+(-1)) num <- readIORef (numMainWindows ctx) when (num == 0) (mainLoopQuit (mainLoop ctx)) mainWindowOpened :: MainM () mainWindowOpened = do ctx <- ask liftIO $ modifyIORef (numMainWindows ctx) (+1) -- | Information about a loaded log file. data LoadedLogFile = LoadedLogFile { logFile :: LogFile } data TextColumnInfo = TextColumnInfo { textColumn :: TreeViewColumn, textRenderer :: CellRendererText } textColumnNew :: String -> IO TextColumnInfo textColumnNew name = do col <- treeViewColumnNew treeViewColumnSetTitle col name renderer <- cellRendererTextNew cellLayoutPackEnd col renderer True return TextColumnInfo { textColumn = col, textRenderer = renderer } -- | Information about the columns and renderers of the tree display. data TreeViewColumnInfo = TreeViewColumnInfo { treeViewText :: TextColumnInfo, treeViewNumChoices :: TextColumnInfo, treeViewBrokenDeps :: TextColumnInfo, treeViewStepNum :: TextColumnInfo, treeViewChildren :: TextColumnInfo, treeViewHeight :: TextColumnInfo, treeViewSubtreeSize :: TextColumnInfo, treeViewTier :: TextColumnInfo, treeViewScore :: TextColumnInfo, treeViewDep :: TextColumnInfo } treeViewColumnInfoRenderers :: TreeViewColumnInfo -> [CellRenderer] treeViewColumnInfoRenderers inf = [ toCellRenderer $ textRenderer $ treeViewText inf, toCellRenderer $ textRenderer $ treeViewNumChoices inf, toCellRenderer $ textRenderer $ treeViewBrokenDeps inf, toCellRenderer $ textRenderer $ treeViewStepNum inf, toCellRenderer $ textRenderer $ treeViewChildren inf, toCellRenderer $ textRenderer $ treeViewHeight inf, toCellRenderer $ textRenderer $ treeViewSubtreeSize inf, toCellRenderer $ textRenderer $ treeViewTier inf, toCellRenderer $ textRenderer $ treeViewScore inf, toCellRenderer $ textRenderer $ treeViewDep inf ] treeViewColumnInfoColumns :: TreeViewColumnInfo -> [TreeViewColumn] treeViewColumnInfoColumns inf = [ textColumn $ treeViewText inf, textColumn $ treeViewNumChoices inf, textColumn $ treeViewBrokenDeps inf, textColumn $ treeViewStepNum inf, textColumn $ treeViewChildren inf, textColumn $ treeViewHeight inf, textColumn $ treeViewSubtreeSize inf, textColumn $ treeViewTier inf, textColumn $ treeViewScore inf, textColumn $ treeViewDep inf ] -- | Discard attribute bindings for the tree view. treeViewColumnInfoClear :: TreeViewColumnInfo -> IO () treeViewColumnInfoClear inf = let cols = treeViewColumnInfoColumns inf in mapM_ cellLayoutClear cols newTreeViewColumns :: IO TreeViewColumnInfo newTreeViewColumns = do text <- textColumnNew "Description" numChoices <- textColumnNew "Choices" brokenDeps <- textColumnNew "Broken Deps" stepNum <- textColumnNew "Order" children <- textColumnNew "Children" height <- textColumnNew "Height" subtreeSize <- textColumnNew "Size" tier <- textColumnNew "Tier" score <- textColumnNew "Score" dep <- textColumnNew "Dep" return TreeViewColumnInfo { treeViewText = text, treeViewNumChoices = numChoices, treeViewBrokenDeps = brokenDeps, treeViewStepNum = stepNum, treeViewChildren = children, treeViewHeight = height, treeViewSubtreeSize = subtreeSize, treeViewTier = tier, treeViewScore = score, treeViewDep = dep } -- | Information about the columns and renderers of the chronological -- display. data ChronologicalViewColumnInfo = ChronologicalViewColumnInfo { chronViewNumChoices :: TextColumnInfo, chronViewBrokenDeps :: TextColumnInfo, chronViewStepNum :: TextColumnInfo, chronViewChildren :: TextColumnInfo, chronViewHeight :: TextColumnInfo, chronViewSubtreeSize :: TextColumnInfo, chronViewTier :: TextColumnInfo, chronViewScore :: TextColumnInfo, chronViewParent :: TextColumnInfo, chronViewChoice :: TextColumnInfo, chronViewDep :: TextColumnInfo } chronViewColumnInfoRenderers :: ChronologicalViewColumnInfo -> [CellRenderer] chronViewColumnInfoRenderers inf = [ toCellRenderer $ textRenderer $ chronViewNumChoices inf, toCellRenderer $ textRenderer $ chronViewBrokenDeps inf, toCellRenderer $ textRenderer $ chronViewStepNum inf, toCellRenderer $ textRenderer $ chronViewChildren inf, toCellRenderer $ textRenderer $ chronViewHeight inf, toCellRenderer $ textRenderer $ chronViewSubtreeSize inf, toCellRenderer $ textRenderer $ chronViewTier inf, toCellRenderer $ textRenderer $ chronViewScore inf, toCellRenderer $ textRenderer $ chronViewParent inf, toCellRenderer $ textRenderer $ chronViewChoice inf, toCellRenderer $ textRenderer $ chronViewDep inf ] chronViewColumnInfoColumns :: ChronologicalViewColumnInfo -> [TreeViewColumn] chronViewColumnInfoColumns inf = [ textColumn $ chronViewNumChoices inf, textColumn $ chronViewBrokenDeps inf, textColumn $ chronViewStepNum inf, textColumn $ chronViewChildren inf, textColumn $ chronViewHeight inf, textColumn $ chronViewSubtreeSize inf, textColumn $ chronViewTier inf, textColumn $ chronViewScore inf, textColumn $ chronViewParent inf, textColumn $ chronViewChoice inf, textColumn $ chronViewDep inf ] -- | Discard attribute bindings for the chronological view. chronViewColumnInfoClear :: ChronologicalViewColumnInfo -> IO () chronViewColumnInfoClear inf = let cols = chronViewColumnInfoColumns inf in mapM_ cellLayoutClear cols newChronViewColumns :: IO ChronologicalViewColumnInfo newChronViewColumns = do numChoices <- textColumnNew "Choices" brokenDeps <- textColumnNew "Broken Deps" stepNum <- textColumnNew "Order" children <- textColumnNew "Children" height <- textColumnNew "Height" subtreeSize <- textColumnNew "Size" tier <- textColumnNew "Tier" score <- textColumnNew "Score" parent <- textColumnNew "Parent" dep <- textColumnNew "Dep" choice <- textColumnNew "Step" return ChronologicalViewColumnInfo { chronViewNumChoices = numChoices, chronViewBrokenDeps = brokenDeps, chronViewStepNum = stepNum, chronViewChildren = children, chronViewHeight = height, chronViewSubtreeSize = subtreeSize, chronViewTier = tier, chronViewScore = score, chronViewParent = parent, chronViewDep = dep, chronViewChoice = choice } -- | Information about the columns and renderers of the run list. data RunListColumnInfo = RunListColumnInfo { runListNumber :: TextColumnInfo, runListLength :: TextColumnInfo } runListInfoRenderers :: RunListColumnInfo -> [CellRenderer] runListInfoRenderers inf = [ toCellRenderer $ textRenderer $ runListNumber inf, toCellRenderer $ textRenderer $ runListLength inf ] runListInfoColumns :: RunListColumnInfo -> [TreeViewColumn] runListInfoColumns inf = [ textColumn $ runListNumber inf, textColumn $ runListLength inf ] -- | Discard attribute bindings for the run list. runListColumnInfoClear :: RunListColumnInfo -> IO () runListColumnInfoClear inf = let cols = runListInfoColumns inf in mapM_ cellLayoutClear cols newRunListColumns :: IO RunListColumnInfo newRunListColumns = do number <- textColumnNew "Run Number" len <- textColumnNew "Run Length" return RunListColumnInfo { runListNumber = number, runListLength = len } type TreeViewStore = TreeStore TreeViewEntry type ChronViewStore = ListStore ChronViewEntry type RunListStore = ListStore (Integer, [ProcessingStep]) -- | Shared context for the visualizer. data VisualizeContext = VisualizeContext { treeView :: TreeView, treeViewColumnInfo :: TreeViewColumnInfo, treeViewStore :: TreeViewStore, chronologicalView :: TreeView, chronologicalViewColumnInfo :: ChronologicalViewColumnInfo, chronologicalViewStore :: ChronViewStore, runList :: TreeView, runListColumnInfo :: RunListColumnInfo, runListStore :: RunListStore, logView :: SourceView, statusbar :: Statusbar, mainStatusCtx :: ContextId, -- ^ The context ID used for the "main" messages. mainWindow :: Window, mainContext :: MainLoopContext, params :: Params, loadedFile :: IORef (Maybe LoadedLogFile), activeRun :: IORef (Maybe (Integer, [ProcessingStep])) } -- | State monad for the visualizer. type VisM = ReaderT VisualizeContext IO -- Accessors for state. runVis :: (VisM a) -> VisualizeContext -> IO a runVis = runReaderT getTreeView :: VisM TreeView getTreeView = do ctx <- ask; return $ treeView ctx getTreeViewStore :: VisM TreeViewStore getTreeViewStore = do ctx <- ask; return $ treeViewStore ctx getTreeViewColumnInfo :: VisM TreeViewColumnInfo getTreeViewColumnInfo = do ctx <- ask; return $ treeViewColumnInfo ctx getChronologicalView :: VisM TreeView getChronologicalView = do ctx <- ask; return $ chronologicalView ctx getChronologicalViewColumnInfo :: VisM ChronologicalViewColumnInfo getChronologicalViewColumnInfo = do ctx <- ask; return $ chronologicalViewColumnInfo ctx getChronologicalViewStore :: VisM ChronViewStore getChronologicalViewStore = do ctx <- ask; return $ chronologicalViewStore ctx getRunList :: VisM TreeView getRunList = do ctx <- ask; return $ runList ctx getRunListColumnInfo :: VisM RunListColumnInfo getRunListColumnInfo = do ctx <- ask; return $ runListColumnInfo ctx getRunListStore :: VisM RunListStore getRunListStore = do ctx <- ask; return $ runListStore ctx getLogView :: VisM SourceView getLogView = do ctx <- ask; return $ logView ctx getStatusbar :: VisM Statusbar getStatusbar = do ctx <- ask; return $ statusbar ctx getMainStatusCtx :: VisM ContextId getMainStatusCtx = do ctx <- ask; return $ mainStatusCtx ctx getMainWindow :: VisM Window getMainWindow = do ctx <- ask; return $ mainWindow ctx getMainCtx :: VisM MainLoopContext getMainCtx = do ctx <- ask; return $ mainContext ctx getParams :: VisM Params getParams = do ctx <- ask; return $ params ctx getLog :: VisM (Maybe LogFile) getLog = do ctx <- ask maybeInf <- liftIO $ readIORef $ loadedFile ctx return $ fmap logFile maybeInf getRunNumber :: VisM (Maybe Integer) getRunNumber = do ctx <- ask runInf <- liftIO $ readIORef $ activeRun ctx return $ fmap fst runInf getActiveRun :: VisM (Maybe [ProcessingStep]) getActiveRun = do ctx <- ask runInf <- liftIO $ readIORef $ activeRun ctx return $ fmap snd runInf isActiveRun :: Integer -> VisM Bool isActiveRun n = do current <- getRunNumber case current of Nothing -> return False (Just n') -> return (n == n') --getTreeViewStore :: VisM (Maybe (TreeStore TreeViewEntry)) --getTreeViewStore = do ctx <- ask -- maybeInf <- liftIO $ readIORef $ loadedFile ctx -- return $ fmap treeViewStore maybeInf -- | Stores tree-structure information about an entry. data EntryTreeInfo = EntryTreeInfo { treeInfoChildren :: Integer, treeInfoHeight :: Integer, treeInfoSubtreeSize :: Integer } deriving(Ord, Eq, Show) getTreeInfo :: ProcessingStep -> EntryTreeInfo getTreeInfo (ProcessingStep { stepSuccessors = steps, stepDepth = height, stepBranchSize = branchSize }) = EntryTreeInfo { treeInfoChildren = toInteger $ length steps, treeInfoHeight = height, treeInfoSubtreeSize = branchSize } -- Each row in the tree display is either the root of the search, a -- processing step (possibly with no parent!), a solution that was -- enqueued but never visited, or a note about a problem rendering the -- tree. data TreeViewEntry = Root { entryStep :: ProcessingStep, entryNumChoices :: Integer, entryBrokenDeps :: Integer, entryStepNum :: Integer, entryTreeInfo :: EntryTreeInfo } | Step { entryStep :: ProcessingStep, entryChoice :: LinkChoice, entryNumChoices :: Integer, entryBrokenDeps :: Integer, entryStepNum :: Integer, entryTreeInfo :: EntryTreeInfo } -- | The maximum number of search nodes was rendered. | Horizon { entryChoice :: LinkChoice, entryStepNum :: Integer, entryTreeInfo :: EntryTreeInfo } -- | A Step node would have been produced, but the -- same solution was already generated as a Step -- node. The attached Solution node could be used -- to, e.g., look up the tree node associated with -- the link. | AlreadyGeneratedStep { entrySol :: Solution, entryChoice :: LinkChoice, entryNumChoices :: Integer, entryStepNum :: Integer, entryBrokenDeps :: Integer, entryTextStart :: Integer, entryTextLength :: Integer } | NoStep { entrySol :: Solution, entryChoice :: LinkChoice, entryBrokenDeps :: Integer, entryNumChoices :: Integer } | Error { entryErrorText :: String, entryStepNum :: Integer } forceList :: [a] -> [a] forceList = foldr (\a b -> a `seq` (a:b)) [] -- Each node in the tree refers either to a node's successor or to a -- number of nodes below that node (precomputed). data SuccessorOrHorizon = NodeSuccessor Successor | NodeHorizon TreeViewEntry -- | The tree-view building monad contains local state remembering -- which nodes have already been incorporated into the tree, so we -- don't display them more than once. type BuildTreeView = State.State (Set.Set Solution) unfoldSuccessor :: Params -> SuccessorOrHorizon -> BuildTreeView (TreeViewEntry, [SuccessorOrHorizon]) unfoldSuccessor params (NodeHorizon entry) = return (entry, []) unfoldSuccessor params (NodeSuccessor (Successor step choice forced)) = do seen <- State.get let sol = stepSol step stepNum = stepOrder step case undefined of _ | maybe False (stepNum>=) (maxSteps params) -> let numChoices = toInteger $ Map.size $ solChoices $ stepSol step brokenDeps = toInteger $ Set.size $ solBrokenDeps $ stepSol step treeInfo = getTreeInfo step horizon = Horizon { entryChoice = choice, entryStepNum = stepNum, entryTreeInfo = treeInfo } in step `seq` choice `seq` stepNum `seq` treeInfo `seq` do return (Step { entryStep = step, entryChoice = choice, entryStepNum = stepNum, entryNumChoices = numChoices, entryBrokenDeps = brokenDeps, entryTreeInfo = treeInfo }, [NodeHorizon horizon]) | sol `Set.member` seen -> let numChoices = toInteger $ Map.size $ solChoices sol brokenDeps = toInteger $ Set.size $ solBrokenDeps sol textStart = stepTextStart step textLength = stepTextLength step in return $ sol `seq` choice `seq` stepNum `seq` textStart `seq` textLength `seq` numChoices `seq` brokenDeps `seq` (AlreadyGeneratedStep { entrySol = sol, entryChoice = choice, entryStepNum = stepNum, entryNumChoices = numChoices, entryBrokenDeps = brokenDeps, entryTextStart = textStart, entryTextLength = textLength }, []) | otherwise -> let newState = Set.insert sol seen numChoices = toInteger $ Map.size $ solChoices $ stepSol step brokenDeps = toInteger $ Set.size $ solBrokenDeps $ stepSol step treeInfo = getTreeInfo step in step `seq` choice `seq` stepNum `seq` newState `seq` numChoices `seq` brokenDeps `seq` treeInfo `seq` do State.put newState return (Step { entryStep = step, entryChoice = choice, entryStepNum = stepNum, entryNumChoices = numChoices, entryBrokenDeps = brokenDeps, entryTreeInfo = treeInfo }, forceList $ map NodeSuccessor $ stepSuccessors step) unfoldSuccessor _ (NodeSuccessor (Unprocessed sol choice forced)) = let brokenDeps = toInteger $ Set.size $ solBrokenDeps sol numChoices = toInteger $ Map.size $ solChoices sol in sol `seq` choice `seq` brokenDeps `seq` numChoices `seq` return (NoStep { entrySol = sol, entryChoice = choice, entryBrokenDeps = brokenDeps, entryNumChoices = numChoices }, []) runToForest :: Params -> [ProcessingStep] -> Forest TreeViewEntry runToForest params steps = case steps of [] -> [Node (Error { entryErrorText = "No steps in this run.", entryStepNum = 0 }) []] (first:rest) -> let hasRoot = maybe False (==0) (firstStep params) root = if hasRoot then Just first else Nothing droppedSteps = maybe steps (\n -> genericDrop n steps) (firstStep params) droppedRest = if hasRoot then drop 1 droppedSteps else droppedSteps truncatedRest = maybe droppedRest (\n -> genericTake n droppedRest) (maxSteps params) in State.evalState (makeWholeTree root truncatedRest) Set.empty where makeTree :: (ProcessingStep -> TreeViewEntry) -> ProcessingStep -> BuildTreeView (Maybe (Tree TreeViewEntry)) makeTree f root = do seen <- State.get let rootSol = stepSol root (if rootSol `Set.member` seen then return $ Nothing else do State.put $ Set.insert rootSol seen let rootSucc = stepSuccessors root succ <- unfoldForestM (unfoldSuccessor params) (map NodeSuccessor rootSucc) return $ f `seq` root `seq` forceList succ `seq` Just $ Node (f root) succ) makeWholeTree :: Maybe ProcessingStep -> [ProcessingStep] -> BuildTreeView (Forest TreeViewEntry) makeWholeTree root rest = do first <- maybe (return Nothing) (makeTree makeRootTree) root rest' <- sequence $ map (makeTree makeOrphanedTree) rest return $ catMaybes (first:rest') makeRootTree root = let numChoices = toInteger $ Map.size $ solChoices $ stepSol root brokenDeps = toInteger $ Set.size $ solBrokenDeps $ stepSol root stepNum = stepOrder root treeInfo = getTreeInfo root in root `seq` numChoices `seq` brokenDeps `seq` stepNum `seq` treeInfo `seq` Root { entryStep = root, entryNumChoices = numChoices, entryBrokenDeps = brokenDeps, entryStepNum = stepOrder root, entryTreeInfo = getTreeInfo root } makeOrphanedTree root = let numChoices = toInteger $ Map.size $ solChoices $ stepSol root brokenDeps = toInteger $ Set.size $ solBrokenDeps $ stepSol root stepNum = stepOrder root treeInfo = getTreeInfo root in root `seq` numChoices `seq` brokenDeps `seq` stepNum `seq` treeInfo `seq` Step { entryStep = root, entryChoice = Unknown, entryNumChoices = numChoices, entryBrokenDeps = brokenDeps, entryStepNum = stepNum, entryTreeInfo = treeInfo } choiceText :: LinkChoice -> String choiceText (LinkChoice c) = pp c choiceText Unknown = "(...)" -- Column definitions for tree view entries. entryColumnText :: TreeViewEntry -> String entryColumnText (Root {}) = "Root" entryColumnText (Step { entryChoice = choice}) = choiceText choice entryColumnText (Horizon { entryTreeInfo = inf }) = (show $ treeInfoChildren inf) ++ " search nodes..." entryColumnText (AlreadyGeneratedStep { entryChoice = choice }) = "Already seen: " ++ choiceText choice entryColumnText (NoStep { entryChoice = choice }) = "Never visited: " ++ choiceText choice entryColumnText (Error { entryErrorText = err }) = err entryColumnNumChoices :: TreeViewEntry -> String entryColumnNumChoices (Root { entryNumChoices = n }) = show n entryColumnNumChoices (Step { entryNumChoices = n }) = show n entryColumnNumChoices (Horizon {}) = "" entryColumnNumChoices (AlreadyGeneratedStep { entryNumChoices = n }) = show n entryColumnNumChoices (NoStep { entryNumChoices = n }) = show n entryColumnNumChoices (Error {}) = "" entryColumnBrokenDeps :: TreeViewEntry -> String entryColumnBrokenDeps (Root { entryBrokenDeps = n }) = show n entryColumnBrokenDeps (Step { entryBrokenDeps = n }) = show n entryColumnBrokenDeps (Horizon {}) = "" entryColumnBrokenDeps (AlreadyGeneratedStep { entryBrokenDeps = n }) = show n entryColumnBrokenDeps (NoStep { entryBrokenDeps = n }) = show n entryColumnBrokenDeps (Error {}) = "" entryColumnStepNum :: TreeViewEntry -> String entryColumnStepNum (Root { entryStepNum = n }) = show n entryColumnStepNum (Step { entryStepNum = n }) = show n entryColumnStepNum (Horizon { entryStepNum = n }) = show n entryColumnStepNum (AlreadyGeneratedStep { entryStepNum = n }) = show n entryColumnStepNum (NoStep {}) = "" entryColumnStepNum (Error {}) = "" entryColumnChildren :: TreeViewEntry -> String entryColumnChildren (Root { entryTreeInfo = inf }) = show $ treeInfoChildren inf entryColumnChildren (Step { entryTreeInfo = inf }) = show $ treeInfoChildren inf entryColumnChildren (Horizon { entryTreeInfo = inf }) = show $ treeInfoChildren inf entryColumnChildren (AlreadyGeneratedStep {}) = "" entryColumnChildren (NoStep { }) = "" entryColumnChildren (Error {}) = "" entryColumnHeight :: TreeViewEntry -> String entryColumnHeight (Root { entryTreeInfo = inf }) = show $ treeInfoHeight inf entryColumnHeight (Step { entryTreeInfo = inf }) = show $ treeInfoHeight inf entryColumnHeight (Horizon { entryTreeInfo = inf }) = show $ treeInfoHeight inf entryColumnHeight (AlreadyGeneratedStep { }) = "" entryColumnHeight (NoStep { }) = "" entryColumnHeight (Error {}) = "" entryColumnSubtreeSize :: TreeViewEntry -> String entryColumnSubtreeSize (Root { entryTreeInfo = inf }) = show $ treeInfoSubtreeSize inf entryColumnSubtreeSize (Step { entryTreeInfo = inf }) = show $ treeInfoSubtreeSize inf entryColumnSubtreeSize (Horizon { entryTreeInfo = inf }) = show $ treeInfoSubtreeSize inf entryColumnSubtreeSize (AlreadyGeneratedStep { }) = "" entryColumnSubtreeSize (NoStep { }) = "" entryColumnSubtreeSize (Error {}) = "" entryColumnTier :: TreeViewEntry -> String entryColumnTier (Root { entryStep = step }) = show $ solTier $ stepSol step entryColumnTier (Step { entryStep = step }) = show $ solTier $ stepSol step entryColumnTier (Horizon {}) = "" entryColumnTier (AlreadyGeneratedStep { entrySol = sol }) = show $ solTier sol entryColumnTier (NoStep { entrySol = sol }) = show $ solTier sol entryColumnTier (Error {}) = "" entryColumnScore :: TreeViewEntry -> String entryColumnScore (Root { entryStep = step }) = show $ solScore $ stepSol step entryColumnScore (Step { entryStep = step }) = show $ solScore $ stepSol step entryColumnScore (Horizon {}) = "" entryColumnScore (AlreadyGeneratedStep { entrySol = sol }) = show $ solScore sol entryColumnScore (NoStep { entrySol = sol }) = show $ solScore sol entryColumnScore (Error {}) = "" linkChoiceDepText :: LinkChoice -> String linkChoiceDepText (LinkChoice (InstallVersion { choiceVerDepInfo = Just di })) = pp (depInfoDep di) linkChoiceDepText _ = "" entryColumnDep :: TreeViewEntry -> String entryColumnDep (Root {}) = "" entryColumnDep (Step { entryChoice = choice }) = linkChoiceDepText choice entryColumnDep (Horizon { }) = "" entryColumnDep (AlreadyGeneratedStep { entryChoice = choice }) = linkChoiceDepText choice entryColumnDep (NoStep { entryChoice = choice }) = linkChoiceDepText choice entryColumnDep (Error { entryErrorText = err }) = "" renderTreeView :: Params -> [ProcessingStep] -> TreeViewStore -> IO () renderTreeView params steps model = do let forest = runToForest params steps taggedForest = zip [0..] forest treeStoreClear model mapM_ (\(n, tree) -> treeStoreInsertTree model [] n tree) taggedForest data ChronViewEntry = ChronStep { chronNumChoices :: Integer, chronBrokenDeps :: Integer, chronStepNum :: Integer, chronChildren :: Integer, chronHeight :: Integer, chronSubtreeSize :: Integer, chronTier :: Tier, chronScore :: Integer, chronParent :: Maybe Integer, chronDep :: Maybe Dep, chronChoice :: Maybe Choice, chronStep :: ProcessingStep } makeChronStep :: ProcessingStep -> ChronViewEntry makeChronStep step = let numChoices = toInteger $ Map.size $ solChoices $ stepSol step brokenDeps = toInteger $ Set.size $ solBrokenDeps $ stepSol step stepNum = stepOrder step children = toInteger $ length $ stepSuccessors step height = stepDepth step subtreeSize = stepBranchSize step tier = solTier $ stepSol step score = solScore $ stepSol step parent = fmap (stepOrder . parentLinkParent) $ stepPredecessor step choice = case stepPredecessor step of Just (ParentLink { parentLinkAction = LinkChoice c }) -> Just c _ -> Nothing dep = case choice of Just (InstallVersion { choiceVerDepInfo = maybeDi }) -> fmap depInfoDep maybeDi _ -> Nothing in numChoices `seq` brokenDeps `seq` stepNum `seq` children `seq` height `seq` subtreeSize `seq` step `seq` tier `seq` score `seq` choice `seq` parent `seq` dep `seq` ChronStep { chronNumChoices = numChoices, chronBrokenDeps = brokenDeps, chronStepNum = stepNum, chronChildren = children, chronHeight = height, chronSubtreeSize = subtreeSize, chronStep = step, chronTier = tier, chronScore = score, chronParent = parent, chronDep = dep, chronChoice = choice } renderChronView :: Params -> [ProcessingStep] -> ChronViewStore -> IO () renderChronView params steps model = do let stepsAdvanced = maybe steps (\n -> genericDrop n steps) (firstStep params) stepsTruncated = maybe stepsAdvanced (\n -> genericTake n stepsAdvanced) (maxSteps params) list = [ makeChronStep step | step <- stepsTruncated ] listStoreClear model mapM_ (listStoreAppend model) list showText :: Integer -> Integer -> VisM () showText start len = do log <- getLog logView <- getLogView liftIO $ do logBuffer <- textViewGetBuffer logView (case log of Nothing -> textBufferSetText logBuffer "" Just f -> do let h = logFileH f hSeek h AbsoluteSeek start s <- ByteString.hGet h (fromInteger len) textBufferSetText logBuffer $ unpack s) stepSelected :: Maybe ProcessingStep -> VisM () stepSelected Nothing = return () -- Clear the log view? stepSelected (Just step) = showText (stepTextStart step) (stepTextLength step) setupTextColumn inf model ops = cellLayoutSetAttributes (textColumn inf) (textRenderer inf) model ops -- Returns the number of *actual* solutions (search nodes with no -- broken dependencies). numSolutions :: [ProcessingStep] -> Integer numSolutions steps = genericLength [ step | step <- steps, Set.null $ solBrokenDeps $ stepSol step ] maxTier :: [ProcessingStep] -> Tier maxTier = maximum . map (solTier . stepSol) setRun :: Maybe (Integer, [ProcessingStep]) -> VisM () setRun Nothing = do treeView <- getTreeView chronView <- getChronologicalView treeStore <- getTreeViewStore chronStore <- getChronologicalViewStore treeViewColInfo <- getTreeViewColumnInfo chronViewColInfo <- getChronologicalViewColumnInfo ctx <- ask statusbar <- getStatusbar statusCtx <- getMainStatusCtx log <- getLog liftIO $ do statusbarPop statusbar statusCtx (case log of Nothing -> statusbarPush statusbar statusCtx "No file loaded." Just lf -> let sourceName = logFilename lf numRuns = length $ runs lf in statusbarPush statusbar statusCtx $ printf "%s: %d runs." sourceName numRuns) treeStoreClear treeStore listStoreClear chronStore writeIORef (activeRun ctx) Nothing setRun (Just (n, steps)) = do isActive <- isActiveRun n unless isActive $ do ctx <- ask treeView <- getTreeView chronView <- getChronologicalView treeStore <- getTreeViewStore chronStore <- getChronologicalViewStore treeViewColInfo <- getTreeViewColumnInfo chronViewColInfo <- getChronologicalViewColumnInfo params <- getParams statusbar <- getStatusbar statusCtx <- getMainStatusCtx log <- getLog logView <- getLogView liftIO $ do -- Update the UI for the new log file. statusbarPop statusbar statusCtx (case log of Nothing -> statusbarPush statusbar statusCtx "Error: bad state" Just lf -> let sourceName = logFilename lf numRuns = length $ runs lf numSteps = length steps numSols = numSolutions steps in statusbarPush statusbar statusCtx $ printf "%s: run %d/%d; %d %s, %d %s, maximum tier %s." sourceName n numRuns numSteps (if numSteps == 1 then "step" else "steps") numSols (if numSols == 1 then "solution" else "solutions") (show $ maxTier steps)) rawLogViewBuffer <- textViewGetBuffer logView textBufferSetText rawLogViewBuffer "" renderTreeView params steps treeStore renderChronView params steps chronStore writeIORef (activeRun ctx) (Just (n, steps)) setLog :: LogFile -> VisM () setLog lf = do runModel <- getRunListStore runView <- getRunList ctx <- ask mainWindow <- getMainWindow statusbar <- getStatusbar statusCtx <- getMainStatusCtx liftIO $ do windowSetTitle mainWindow $ printf "resolver-visualize: %s" (logFilename lf) let sourceName = logFilename lf numRuns = length $ runs lf statusbarPop statusbar statusCtx statusbarPush statusbar statusCtx $ printf "%s: %d runs." sourceName numRuns writeIORef (loadedFile ctx) $ Just LoadedLogFile { logFile = lf } listStoreClear runModel mapM_ (listStoreAppend runModel) $ (zip [1..] $ runs lf) -- Make sure the first iterator is selected. firstIter <- treeModelGetIterFirst runModel selection <- treeViewGetSelection runView (case firstIter of Nothing -> return () Just i -> treeSelectionSelectIter selection i) return () -- | Load a widget from the Glade file by name. loadXmlWidget :: WidgetClass a => String -> (GObject -> a) -> IO (GladeXML, a) loadXmlWidget widgetName cast = do x <- xmlNewWithRootAndDomain xmlFilename (Just widgetName) Nothing case x of Nothing -> error ("Can't load " ++ (show xmlFilename)) Just xml -> do w <- xmlGetWidget xml cast widgetName return (xml, w) -- | Load the main window from the Glade file. loadMainWindowXML :: IO (GladeXML, Window) loadMainWindowXML = loadXmlWidget "main_window" castToWindow -- | Load the About box from the Glade file. loadAboutBoxXML :: IO (GladeXML, AboutDialog) loadAboutBoxXML = loadXmlWidget "about_box" castToAboutDialog -- | Load the loading progress window from the Glade file. loadLoadingProgressXML :: IO (GladeXML, Window) loadLoadingProgressXML = loadXmlWidget "window_load_progress" castToWindow -- | Load the export params dialog from the Glade file. loadParamsDialogXML :: IO (GladeXML, Dialog) loadParamsDialogXML = loadXmlWidget "params_dialog" castToDialog setupMainWindow :: GladeXML -> IO SourceView setupMainWindow xml = do sourceViewHolder <- xmlGetWidget xml castToScrolledWindow "scrolledwindow_sourceview" sourceView <- sourceViewNew sourceViewSetShowLineNumbers sourceView True textViewSetEditable sourceView False containerAdd sourceViewHolder sourceView return sourceView createMainWindowColumns :: GladeXML -> MainM (TreeViewColumnInfo, ChronologicalViewColumnInfo, RunListColumnInfo) createMainWindowColumns xml = liftIO $ do treeViewCols <- newTreeViewColumns chronViewCols <- newChronViewColumns runListCols <- newRunListColumns return (treeViewCols, chronViewCols, runListCols) createMainWindowStores :: TreeViewColumnInfo -> ChronologicalViewColumnInfo -> RunListColumnInfo -> IO (TreeViewStore, ChronViewStore, RunListStore) createMainWindowStores treeViewInf chronViewInf runListInf = do treeModel <- treeStoreNew [] chronModel <- listStoreNew [] runModel <- listStoreNew [] -- Set up column bindings. let makeCol info model (getCol, getText) = setupTextColumn (getCol info) model (\row -> [cellText := getText row]) treeCols = [(treeViewText, entryColumnText), (treeViewNumChoices, entryColumnNumChoices), (treeViewBrokenDeps, entryColumnBrokenDeps), (treeViewStepNum, entryColumnStepNum), (treeViewChildren, entryColumnChildren), (treeViewHeight, entryColumnHeight), (treeViewSubtreeSize, entryColumnSubtreeSize), (treeViewTier, entryColumnTier), (treeViewScore, entryColumnScore), (treeViewDep, entryColumnDep)] chronCols = [(chronViewNumChoices, show . chronNumChoices), (chronViewBrokenDeps, show . chronBrokenDeps), (chronViewStepNum, show . chronStepNum), (chronViewChildren, show . chronChildren), (chronViewHeight, show . chronHeight), (chronViewSubtreeSize, show . chronSubtreeSize), (chronViewTier, show . chronTier), (chronViewScore, show . chronScore), (chronViewDep, maybe "" pp . chronDep), (chronViewParent, maybe "" show . chronParent), (chronViewChoice, maybe "" pp . chronChoice)] runCols = [(runListNumber, show . fst), (runListLength, show . length . snd)] mapM_ (makeCol treeViewInf treeModel) treeCols mapM_ (makeCol chronViewInf chronModel) chronCols mapM_ (makeCol runListInf runModel) runCols return (treeModel, chronModel, runModel) treeSelectionChanged :: VisualizeContext -> TreeSelection -> TreeViewStore -> IO () treeSelectionChanged ctx selection model = do num <- treeSelectionCountSelectedRows selection (if num /= 1 then runVis (stepSelected Nothing) ctx else do (Just selected) <- treeSelectionGetSelected selection path <- treeModelGetPath model selected node <- treeStoreLookup model path (case node of Nothing -> runVis (stepSelected Nothing) ctx Just (Node {rootLabel = Root {entryStep = step}}) -> runVis (stepSelected (Just step)) ctx Just (Node {rootLabel = Step {entryStep = step}}) -> runVis (stepSelected (Just step)) ctx Just (Node {rootLabel = AlreadyGeneratedStep { entryTextStart = start, entryTextLength = len }}) -> runVis (showText start len) ctx _ -> runVis (stepSelected Nothing) ctx)) chronSelectionChanged :: VisualizeContext -> TreeSelection -> ChronViewStore -> IO () chronSelectionChanged ctx selection model = do num <- treeSelectionCountSelectedRows selection (if num /= 1 then runVis (stepSelected Nothing) ctx else do (Just selected) <- treeSelectionGetSelected selection (i:_) <- treeModelGetPath model selected entry <- listStoreGetValue model i runVis (stepSelected $ Just $ chronStep entry) ctx) runSelectionChanged :: VisualizeContext -> TreeSelection -> RunListStore -> IO () runSelectionChanged ctx selection model = do num <- treeSelectionCountSelectedRows selection (if num /= 1 then runVis (setRun Nothing) ctx else do (Just selected) <- treeSelectionGetSelected selection (i:_) <- treeModelGetPath model selected run <- listStoreGetValue model i runVis (setRun (Just run)) ctx) setupMenus :: GladeXML -> Params -> VisualizeContext -> IO () setupMenus xml params ctx = do mainWin <- liftIO $ xmlGetWidget xml castToWindow "main_window" menuItemGraphviz <- liftIO $ xmlGetWidget xml castToMenuItem "menuitem_export_graphviz" menuItemQuit <- liftIO $ xmlGetWidget xml castToMenuItem "menuitem_quit" afterActivateLeaf menuItemGraphviz $ runVis (doExport mainWin) ctx afterActivateLeaf menuItemQuit $ do mainLoopQuit $ mainLoop $ mainContext ctx return () where doExport mainWin = do activeRun <- getActiveRun liftIO $ (case activeRun of Nothing -> return () Just steps -> do dlg <- makeParamsDialog params steps (doExport' mainWin steps) windowSetTransientFor (paramsDialog dlg) mainWin return ()) return () doExport' mainWin steps params = do dlg <- fileChooserDialogNew Nothing (Just mainWin) FileChooserActionOpen [(stockCancel, ResponseCancel), (stockSave, ResponseOk)] afterResponse dlg (\response -> do (if response /= ResponseOk then return () else do maybeFilename <- fileChooserGetFilename dlg case maybeFilename of (Just filename) -> writeDotRun params steps filename Nothing -> return ()) widgetDestroy dlg) widgetShow dlg newCtx :: GladeXML -> Params -> MainM VisualizeContext newCtx xml params = do mainCtx <- ask (treeViewColInf, chronViewColumnInf, runListColumnInf) <- createMainWindowColumns xml liftIO $ do sourceView <- setupMainWindow xml treeView <- xmlGetWidget xml castToTreeView "tree_view_search_tree" chronView <- xmlGetWidget xml castToTreeView "tree_view_search_history" runView <- xmlGetWidget xml castToTreeView "tree_view_run_list" mapM_ (treeViewAppendColumn treeView) (treeViewColumnInfoColumns treeViewColInf) mapM_ (treeViewAppendColumn chronView) (chronViewColumnInfoColumns chronViewColumnInf) mapM_ (treeViewAppendColumn runView) (runListInfoColumns runListColumnInf) (treeModel, chronModel, runModel) <- createMainWindowStores treeViewColInf chronViewColumnInf runListColumnInf statusbar <- xmlGetWidget xml castToStatusbar "main_statusbar" mainWindow <- xmlGetWidget xml castToWindow "main_window" mainStatusCtx <- statusbarGetContextId statusbar "Status" lf <- newIORef Nothing runRef <- newIORef Nothing let ctx = VisualizeContext { treeView = treeView, treeViewColumnInfo = treeViewColInf, treeViewStore = treeModel, chronologicalView = chronView, chronologicalViewColumnInfo = chronViewColumnInf, chronologicalViewStore = chronModel, runList = runView, runListColumnInfo = runListColumnInf, runListStore = runModel, logView = sourceView, statusbar = statusbar, mainStatusCtx = mainStatusCtx, mainWindow= mainWindow, loadedFile = lf, params = params, activeRun = runRef, mainContext = mainCtx } treeSelection <- treeViewGetSelection treeView treeSelectionSetMode treeSelection SelectionSingle afterSelectionChanged treeSelection (treeSelectionChanged ctx treeSelection treeModel) chronSelection <- treeViewGetSelection chronView treeSelectionSetMode chronSelection SelectionSingle afterSelectionChanged chronSelection (chronSelectionChanged ctx chronSelection chronModel) runSelection <- treeViewGetSelection runView treeSelectionSetMode runSelection SelectionSingle afterSelectionChanged runSelection (runSelectionChanged ctx runSelection runModel) treeViewSetModel treeView treeModel treeViewSetModel chronView chronModel treeViewSetModel runView runModel setupMenus xml params ctx windowSetTitle mainWindow "resolver-visualize" return ctx newMainWindow :: Params -> MainM (GladeXML, VisualizeContext) newMainWindow params = do mainContext <- ask (xml, mainWindow) <- liftIO $ loadMainWindowXML ctx <- newCtx xml params mainWindowOpened liftIO $ on mainWindow deleteEvent (liftIO $ doMainWindowClosed mainContext) return (xml, ctx) where doMainWindowClosed mainContext = do runMain mainWindowClosed mainContext return True milliToPicoseconds n = n * 1000000000 -- | Load the given log file in a background thread, displaying the -- progress in the foreground thread. When it's done, pop up a new -- main window. -- -- TODO: support displaying in an existing main window. load :: Params -> FilePath -> MainM () load params fn = do loadedFile <- liftIO $ do (xml, win) <- loadLoadingProgressXML title <- xmlGetWidget xml castToLabel "label_title" progressBar <- xmlGetWidget xml castToProgressBar "load_progress" status <- xmlGetWidget xml castToLabel "label_statistics" -- Should be done in a separate thread but GHC/Gtk2HS -- suck for threaded GUI programming. See -- -- http://haskell.org/gtk2hs/archives/2005/07/24/writing-multi-threaded-guis/1/ -- -- for (very gory) details. labelSetText title ("Loading " ++ fn ++ "...") widgetShow win h <- openFile fn ReadMode lastTime <- newIORef Nothing log <- loadLogFile h fn (showProgress progressBar lastTime) widgetDestroy win return log (xml, ctx) <- newMainWindow params liftIO $ runVis (setLog loadedFile) ctx liftIO $ xmlGetWidget xml castToWindow "main_window" >>= widgetShowAll return () where showProgress :: ProgressBar -> IORef (Maybe ClockTime) -> Integer -> Integer -> IO () showProgress pb lastTime cur max = do oldf <- progressBarGetFraction pb currTime <- getClockTime last <- readIORef lastTime writeIORef lastTime (Just currTime) let updateInterval = TimeDiff { tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0, tdSec = 0, tdPicosec = milliToPicoseconds 100 } newf = if max == 0 then 0 else ((fromInteger cur) / (fromInteger max)) longUpdate = case last of Nothing -> True Just time -> diffClockTimes currTime time >= updateInterval shouldUpdate = longUpdate || newf == 1 when shouldUpdate (do progressBarSetFraction pb newf progressBarSetText pb (showFFloat (Just 1) (100 * newf) "" ++ "%") while (mainContextIteration mainContextDefault False) (return ()) () return ()) filterUserParams :: [String] -> Params -> ([String], Params) filterUserParams [] params = ([], params) filterUserParams ("--max-steps":(n:args)) params = let params' = params { maxSteps = Just $ read n } in filterUserParams args params' filterUserParams ("--first-step":(n:args)) params = let params' = params { firstStep = Just $ read n } in filterUserParams args params' filterUserParams ("--show-promotions":args) params = let params' = params { showPromotions = True } in filterUserParams args params' filterUserParams ("--dot-output":(fn:args)) params = let params' = params { dotOutput = Just $ fn } in filterUserParams args params' filterUserParams ("--target-format":(fmt:args)) params = case reads fmt of [] -> error (printf "Unknown target format %s" (show fmt)) ((fmt', _):_) -> let params' = params { targetFormat = Just fmt' } in filterUserParams args params' filterUserParams (arg:args) params = let (args', params') = filterUserParams args params in (arg:args', params') textProgress :: IORef Integer -> Integer -> Integer -> IO () textProgress ref cur max = do lastPercent <- readIORef ref (if cur >= (max * (lastPercent + 10) `div` 100) then do let newPercent = lastPercent + 10 print newPercent writeIORef ref newPercent else return ()) makeTextProgress :: IO (Integer -> Integer -> IO ()) makeTextProgress = do ref <- newIORef 0 return $ textProgress ref writeDotOutput params logFile outputFile = -- TODO: show progress better. do progress <- makeTextProgress withFile logFile ReadMode $ \h -> do log <- loadLogFile h logFile progress (if null $ runs log then return () else if (null (drop 1 $ runs log)) then writeDotRun params (head $ runs log) outputFile else sequence_ [ writeDotRun params steps (printf "%s-%d" outputFile n) | (steps, n) <- zip (runs log) ([1..] :: [Integer]) ]) data MaybeNumberEntry = MaybeNumberEntry { mnCheckbox :: CheckButton, mnSpinner :: SpinButton } setMaybeNumberEntry :: MaybeNumberEntry -> Maybe Integer -> IO () setMaybeNumberEntry (MaybeNumberEntry { mnCheckbox = cb, mnSpinner = sb }) val = do (case val of Nothing -> toggleButtonSetActive cb False Just n -> do toggleButtonSetActive cb True spinButtonSetValue sb $ fromIntegral n) widgetSetSensitive sb (isJust val) getMaybeNumberEntry :: MaybeNumberEntry -> IO (Maybe Integer) getMaybeNumberEntry entry = do cbActive <- toggleButtonGetActive (mnCheckbox entry) spinButtonValue <- spinButtonGetValueAsInt (mnSpinner entry) (if cbActive then return $ Just $ toInteger spinButtonValue else return Nothing) makeMaybeNumberEntry :: CheckButton -> SpinButton -> Maybe Integer -> (Integer, Integer) -> IO MaybeNumberEntry makeMaybeNumberEntry cb sb val (min, max) = do let rval = MaybeNumberEntry { mnCheckbox = cb, mnSpinner = sb } spinButtonSetRange sb (fromIntegral min) (fromIntegral max) setMaybeNumberEntry rval val -- Update the sensitivity of the spin-box based on whether the -- check-button is set. afterToggled cb $ do cbActive <- toggleButtonGetActive cb widgetSetSensitive sb cbActive return rval data ParamsDialog = ParamsDialog { paramsDialog :: Dialog, paramsHboxTruncateRun :: HBox, paramsTruncateRunNumberEntry :: MaybeNumberEntry, paramsLabelTruncateRunMaxSteps :: Label, paramsHboxSkipSteps :: HBox, paramsSkipStepsNumberEntry :: MaybeNumberEntry, paramsLabelSkipStepsMaxSteps :: Label, paramsCheckboxShowPromotions :: CheckButton, paramsOkButton :: Button, paramsCancelButton :: Button } -- Should we ever say "out of %d step"? I think the plural is always -- right here? stepLimitLabelText n = printf " out of %d steps" n getTruncateEntryLimit :: Maybe Integer -> Integer -> Integer getTruncateEntryLimit firstStep numSteps = max 0 $ numSteps - maybe 0 id firstStep skipStepsLabelText :: Integer -> String skipStepsLabelText numSteps = stepLimitLabelText numSteps makeParamsDialog :: Params -> [ProcessingStep] -> (Params -> IO ()) -> IO ParamsDialog makeParamsDialog params steps callback = do (xml, dialog) <- loadParamsDialogXML hboxTruncate <- xmlGetWidget xml castToHBox "hbox_truncate_run" cbTruncateRun <- xmlGetWidget xml castToCheckButton "checkbutton_do_truncate_run" sbTruncateRun <- xmlGetWidget xml castToSpinButton "spinbutton_truncate_run" labelTruncateRun <- xmlGetWidget xml castToLabel "label_truncate_run_max_steps" hboxSkip <- xmlGetWidget xml castToHBox "hbox_skip_first_steps" cbSkip <- xmlGetWidget xml castToCheckButton "checkbutton_do_skip_steps" sbSkip <- xmlGetWidget xml castToSpinButton "spinbutton_skip_steps" labelSkip <- xmlGetWidget xml castToLabel "label_skip_max_steps" cbShowPromotions <- xmlGetWidget xml castToCheckButton "checkbutton_show_promotions" ok <- xmlGetWidget xml castToButton "params_ok" cancel <- xmlGetWidget xml castToButton "params_cancel" -- Set some initial parameters. let numSteps = genericLength steps initialTruncateLimit = getTruncateEntryLimit (firstStep params) numSteps truncateRunEntry <- makeMaybeNumberEntry cbTruncateRun sbTruncateRun (maxSteps params) (0, initialTruncateLimit) skipEntry <- makeMaybeNumberEntry cbSkip sbSkip (firstStep params) (0, numSteps) labelSetText labelTruncateRun (stepLimitLabelText initialTruncateLimit) labelSetText labelSkip (skipStepsLabelText $ numSteps) toggleButtonSetActive cbShowPromotions (showPromotions params) -- When the number of skipped steps is changed, we have to -- update the range and text of the max-steps box. afterValueSpinned sbSkip (do firstStep <- getMaybeNumberEntry skipEntry let truncateLimit = getTruncateEntryLimit firstStep numSteps labelSetText labelTruncateRun (stepLimitLabelText truncateLimit) spinButtonSetRange sbTruncateRun 0 (fromIntegral truncateLimit)) -- TODO: should pass in the ParamsDialog if we add any more -- widgets, rather than just tacking on parameters. afterResponse dialog (handleResponse dialog truncateRunEntry skipEntry cbShowPromotions) widgetShow dialog return $ ParamsDialog { paramsDialog = dialog, paramsHboxTruncateRun = hboxTruncate, paramsTruncateRunNumberEntry = truncateRunEntry, paramsLabelTruncateRunMaxSteps = labelTruncateRun, paramsHboxSkipSteps = hboxSkip, paramsSkipStepsNumberEntry = skipEntry, paramsLabelSkipStepsMaxSteps = labelSkip, paramsCheckboxShowPromotions = cbShowPromotions, paramsOkButton = ok, paramsCancelButton = cancel } where handleResponse dialog truncateRunEntry skipEntry showPromotionsButton ResponseOk = do maxSteps <- getMaybeNumberEntry truncateRunEntry firstStep <- getMaybeNumberEntry skipEntry showPromotions <- toggleButtonGetActive showPromotionsButton let params' = params { maxSteps = maxSteps, firstStep = firstStep, showPromotions = showPromotions } callback params' widgetDestroy dialog return () handleResponse dialog _ _ _ _ = do widgetDestroy dialog return () main :: IO () main = do -- Gtk2Hs whines loudly if it gets loaded into a threaded -- runtime, but runhaskell always loads a threaded runtime, -- so we have to call this to be a script: unsafeInitGUIForThreadedRTS mainWindows <- newIORef 0 mainLoop <- mainLoopNew Nothing False let mainLoopContext = MainLoopContext { numMainWindows = mainWindows, mainLoop = mainLoop } args <- getArgs let (args', params) = filterUserParams args defaultParams case args' of [] -> do (xml, ctx) <- runMain (newMainWindow params) mainLoopContext mainWin <- xmlGetWidget xml castToWindow "main_window" widgetShow (toWidget mainWin) mainLoopRun mainLoop [filename] -> case params of Params { dotOutput = Just output } -> writeDotOutput params filename output _ -> runMain (load params filename) mainLoopContext >> mainLoopRun mainLoop otherwise -> error "Too many arguments; expected at most one (the log file to load)."
dankamongmen/raptitude
tools/resolver-visualize/Main.hs
gpl-2.0
63,363
55
28
23,006
13,360
6,845
6,515
1,041
6
{-| Module : Idris.Elab.RunElab Description : Code to run the elaborator process. Copyright : License : BSD3 Maintainer : The Idris Community. -} module Idris.Elab.RunElab (elabRunElab) where import Idris.Elab.Term import Idris.Elab.Value (elabVal) import Idris.AbsSyntax import Idris.Error import Idris.Core.Elaborate hiding (Tactic (..)) import Idris.Core.Evaluate import Idris.Core.Execute import Idris.Core.TT import Idris.Core.Typecheck import Idris.Output (iputStrLn, pshow, iWarn, sendHighlighting) elabScriptTy :: Type elabScriptTy = App Complete (P Ref (sNS (sUN "Elab") ["Elab", "Reflection", "Language"]) Erased) (P Ref unitTy Erased) mustBeElabScript :: Type -> Idris () mustBeElabScript ty = do ctxt <- getContext case converts ctxt [] ty elabScriptTy of OK _ -> return () Error e -> ierror e elabRunElab :: ElabInfo -> FC -> PTerm -> [String] -> Idris () elabRunElab info fc script' ns = do -- First elaborate the script itself (script, scriptTy) <- elabVal info ERHS script' mustBeElabScript scriptTy ist <- getIState ctxt <- getContext (ElabResult tyT' defer is ctxt' newDecls highlights newGName, log) <- tclift $ elaborate (constraintNS info) ctxt (idris_datatypes ist) (idris_name ist) (sMN 0 "toplLevelElab") elabScriptTy initEState (transformErr RunningElabScript (erun fc (do tm <- runElabAction info ist fc [] script ns EState is _ impls highlights _ _ <- getAux ctxt <- get_context let ds = [] -- todo log <- getLog newGName <- get_global_nextname return (ElabResult tm ds (map snd is) ctxt impls highlights newGName)))) setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights updateIState $ \i -> i { idris_name = newGName }
ozgurakgun/Idris-dev
src/Idris/Elab/RunElab.hs
bsd-3-clause
2,034
0
21
598
557
285
272
41
2
module TestLib where
sdiehl/ghc
testsuite/tests/cabal/cabal10/src/TestLib.hs
bsd-3-clause
21
0
2
3
4
3
1
1
0
{-# LANGUAGE CPP #-} {-# LANGUAGE ScopedTypeVariables #-} import qualified PersistentTest import qualified RenameTest import qualified DataTypeTest import qualified EmptyEntityTest import qualified HtmlTest import qualified EmbedTest import qualified EmbedOrderTest import qualified LargeNumberTest import qualified MaxLenTest import qualified Recursive import qualified SumTypeTest import qualified UniqueTest import qualified MigrationTest import qualified MigrationOnlyTest import qualified PersistUniqueTest import qualified CompositeTest import qualified PrimaryTest import qualified CustomPersistFieldTest import qualified CustomPrimaryKeyReferenceTest import Test.Hspec (hspec) import Test.Hspec.Runner import Init import System.Exit import Control.Monad (unless, when) import Filesystem (isFile, removeFile) import Filesystem.Path.CurrentOS (fromText) import Control.Monad.Trans.Resource (runResourceT) import Control.Exception (handle, IOException) #ifdef WITH_NOSQL #else import Database.Persist.Sql (printMigration, runMigrationUnsafe) setup migration = do printMigration migration runMigrationUnsafe migration #endif toExitCode :: Bool -> ExitCode toExitCode True = ExitSuccess toExitCode False = ExitFailure 1 main :: IO () main = do #ifndef WITH_NOSQL handle (\(_ :: IOException) -> return ()) $ removeFile $ fromText sqlite_database runConn $ do mapM_ setup [ PersistentTest.testMigrate , PersistentTest.noPrefixMigrate , EmbedTest.embedMigrate , EmbedOrderTest.embedOrderMigrate , LargeNumberTest.numberMigrate , UniqueTest.uniqueMigrate , MaxLenTest.maxlenMigrate , Recursive.recursiveMigrate , CompositeTest.compositeMigrate , MigrationTest.migrationMigrate , PersistUniqueTest.migration , RenameTest.migration , CustomPersistFieldTest.customFieldMigrate # ifndef WITH_MYSQL , PrimaryTest.migration # endif , CustomPrimaryKeyReferenceTest.migration ] PersistentTest.cleanDB #endif hspec $ do RenameTest.specs DataTypeTest.specs HtmlTest.specs EmbedTest.specs EmbedOrderTest.specs LargeNumberTest.specs UniqueTest.specs MaxLenTest.specs Recursive.specs SumTypeTest.specs MigrationOnlyTest.specs PersistentTest.specs EmptyEntityTest.specs CompositeTest.specs PersistUniqueTest.specs PrimaryTest.specs CustomPersistFieldTest.specs CustomPrimaryKeyReferenceTest.specs #ifndef WITH_NOSQL MigrationTest.specs #endif
nakaji-dayo/persistent
persistent-test/test/main.hs
mit
2,534
0
13
417
449
255
194
79
1
module Foo () where {-@ choo :: [a] -> {v: Int | v > 0 } @-} choo = poo poo :: [a] -> Int poo (x:xs) = poo xs poo [] = 0
ssaavedra/liquidhaskell
tests/neg/grty3.hs
bsd-3-clause
130
0
7
43
53
30
23
5
1
{-# LANGUAGE TypeFamilies #-} module T8002 where import T8002a
urbanslug/ghc
testsuite/tests/indexed-types/should_compile/T8002.hs
bsd-3-clause
64
0
3
10
8
6
2
3
0
{-# LANGUAGE OverloadedStrings #-} -- Whatever, it's just an example module Application where import Network.Wai import Network.HTTP.Types (ok200, notFound404) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.ByteString.Lazy as LZ import Data.Monoid (mappend) textToUTF8 txt = LZ.fromChunks [T.encodeUtf8 txt] showUTF8 :: (Show a) => a -> LZ.ByteString showUTF8 = textToUTF8 . T.pack . show on404 _ = return $ responseLBS notFound404 [("Content-Type", "text/plain")] "Not Found" home _ _ = return $ responseLBS ok200 [("Content-Type", "text/plain")] "Hello World" test _ val _ = return $ responseLBS ok200 [("Content-Type", "text/plain")] (textToUTF8 val) test2 :: String -> Integer -> Application test2 _ val _ = return $ responseLBS ok200 [("Content-Type", "text/plain")] (showUTF8 val) test3 :: String -> T.Text -> [String] -> Application test3 some val multi env = return $ responseLBS ok200 [("Content-Type", "text/plain")] (textToUTF8 val `mappend` "\n\n" `mappend` showUTF8 multi `mappend` "\n\n" `mappend` showUTF8 (pathInfo env) `mappend` "\n\n" `mappend` showUTF8 some)
singpolyma/route-generator
example/Application.hs
isc
1,161
0
14
167
387
219
168
19
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} data Nat = Z | S Nat deriving (Eq, Show) type Zero = Z type One = S Zero type Two = S One type Three = S Two type Four = S Three type Five = S Four data Vec :: Nat -> * -> * where Nil :: Vec Z a Cons :: a -> Vec n a -> Vec (S n) a instance Show a => Show (Vec n a) where show Nil = "Nil" show (Cons x xs) = "Cons " ++ show x ++ " (" ++ show xs ++ ")" class FromList n where fromList :: [a] -> Vec n a instance FromList Z where fromList [] = Nil instance FromList n => FromList (S n) where fromList (x:xs) = Cons x $ fromList xs lengthVec :: Vec n a -> Nat lengthVec Nil = Z lengthVec (Cons x xs) = S (lengthVec xs) zipVec :: Vec n a -> Vec n b -> Vec n (a,b) zipVec Nil Nil = Nil zipVec (Cons x xs) (Cons y ys) = Cons (x,y) (zipVec xs ys) vec4 :: Vec Four Int vec4 = fromList [0, 1, 2, 3] vec5 :: Vec Five Int vec5 = fromList [0, 1, 2, 3, 4] example1 :: Nat example1 = lengthVec vec4 -- S (S (S (S Z))) example2 :: Vec Four (Int, Int) example2 = zipVec vec4 vec4 -- Cons (0,0) (Cons (1,1) (Cons (2,2) (Cons (3,3) (Nil)))) example2 = zipVec vec4 vec5 -- Couldn't match type 'S 'Z with 'Z -- Expected type: Vec Four Int -- Actual type: Vec Five Int -- The same technique we can use to create a container which is statically indexed by an empty or non-empty flag, such that if we try to take the head of an empty list we'll get a compile-time error, or stated equivalently we have an obligation to prove to the compiler that the argument we hand to the head function is non-empty. {-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} data Size = Empty | NonEmpty data List a b where Nil :: List Empty a Cons :: a -> List b a -> List NonEmpty a head' :: List NonEmpty a -> a head' (Cons x _) = x example1 :: Int example1 = head' (1 `Cons` (2 `Cons` Nil)) -- Cannot match type Empty with NonEmpty example2 :: Int example2 = head' Nil -- Couldn't match type None with Many -- Expected type: List NonEmpty Int -- Actual type: List Empty Int
Airtnp/Freshman_Simple_Haskell_Lib
Intro/WIW/Promoted/SizedVec.hs
mit
2,246
0
10
514
679
365
314
-1
-1
{-# LANGUAGE FlexibleContexts, FlexibleInstances, UndecidableInstances #-} {-# LANGUAGE RankNTypes, ScopedTypeVariables #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Utils where import Data.Vinyl hiding (Dict (..)) import Generics.SOP.NP import Generics.SOP.NS import Generics.SOP.BasicFunctors import Generics.SOP.Sing import Generics.SOP.Constraint import Constraints import Data.Proxy import Data.Default --import Constraints import Data.List (intercalate) showAsList :: [String] -> String showAsList strs = "[" ++ intercalate ", " strs ++ "]" -- utilites for conversion between Vinyl and SOP rec2np :: Rec f xs -> NP f xs rec2np RNil = Nil rec2np (fx :& fxs) = fx :* rec2np fxs np2rec :: NP f xs -> Rec f xs np2rec Nil = RNil np2rec (fx :* fxs) = fx :& np2rec fxs -- like liftA_NP but without the constraints liftA_NP' :: (forall a. f a -> g a) -> NP f xs -> NP g xs liftA_NP' _ Nil = Nil liftA_NP' f (fx :* fxs) = f fx :* liftA_NP' f fxs -- like liftA2_NS but without the constrains liftA_NS' :: (forall a. f a -> g a) -> NS f xs -> NS g xs liftA_NS' f (Z fx) = Z (f fx) liftA_NS' f (S fxs) = S (liftA_NS' f fxs) -- like liftA_SOP but without the constraints liftA_SOP' :: (forall a. f a -> g a) -> SOP f xss -> SOP g xss liftA_SOP' f (SOP sop) = SOP (liftA_NS' (liftA_NP' f) sop) -- like liftA_POP but without the constraints liftA_POP' :: (forall a. f a -> g a) -> POP f xss -> POP g xss liftA_POP' f (POP pop) = POP (liftA_NP' (liftA_NP' f) pop) -- like liftA2_NP but without the constraints liftA2_NP' :: (forall a. f a -> g a -> h a) -> NP f xs -> NP g xs -> NP h xs liftA2_NP' _ Nil Nil = Nil liftA2_NP' f (x :* xs) (y :* ys) = f x y :* liftA2_NP' f xs ys -- like liftA2_NS but without the constraint liftA2_NS' :: forall f g h xs. (forall a. f a -> g a -> h a) -> NP f xs -> NS g xs -> NS h xs liftA2_NS' f (fx :* _) (Z gx) = Z (f fx gx) liftA2_NS' f (_ :* fxs) (S gxs) = S (liftA2_NS' f fxs gxs) liftA2_SOP'' :: forall f g h xs. (forall a. f a -> g a -> h a) -> NP (NP f) xs -> NS (NP g) xs -> NS (NP h) xs liftA2_SOP'' f (fxs :* _) (Z gxs) = Z (liftA2_NP' f fxs gxs) liftA2_SOP'' f (_ :* fxss) (S gxss) = S (liftA2_SOP'' f fxss gxss) -- like liftA2_SOP but without the constraints liftA2_SOP' :: forall f g h xss. (forall a. f a -> g a -> h a) -> POP f xss -> SOP g xss -> SOP h xss liftA2_SOP' f (POP pop) (SOP sop) = SOP $ liftA2_SOP'' f pop sop collapse_SOP' :: SOP (K a) xs -> [a] collapse_SOP' (SOP sop) = collapse_NS $ liftA_NS' (K . collapse_NP) sop collapse_POP' :: POP (K a) xs -> [a] collapse_POP' (POP pop) = concat . collapse_NP $ liftA_NP' (K . collapse_NP) pop sequence_SOP' :: Applicative f => SOP (f :.: g) xss -> f (SOP g xss) sequence_SOP' (SOP (Z fgxs)) = SOP . Z <$> sequence'_NP fgxs sequence_SOP' (SOP (S ns)) = SOP . S . unSOP <$> sequence_SOP' (SOP ns) np2ns :: NP f xs -> [NS f xs] np2ns Nil = [] np2ns (fx :* fxs) = Z fx : map S (np2ns fxs) ns2int :: NS f xs -> Int ns2int (Z _) = 0 ns2int (S xs) = succ (ns2int xs) newtype FK f b a = FK (f a) newtype Flip f a b = Flip { runFlip :: f b a } deriving (Default) instance Show (f b a) => Show (Flip f a b) where show = show . runFlip showFlip :: forall f a b. ForallC1 Show (Flip f a) => Flip f a b -> String showFlip = case forallC of Forall (Dict :: Dict (CompC Show (Flip f a) b)) -> show fmapFlip :: forall f a a' b. (ForallC1 Functor f) => (a -> a') -> Flip f a b -> Flip f a' b fmapFlip f = case forallC of Forall (Dict :: Dict (CompC Functor f b)) -> Flip . (fmap f) . runFlip foldrFlip :: forall f a a' b. ForallC1 Foldable f => (a -> a' -> a') -> a' -> Flip f a b -> a' foldrFlip f a' (Flip fba) = case forallC of Forall (Dict :: Dict (CompC Foldable f b)) -> foldr f a' fba foldlFlip :: forall f a a' b. ForallC1 Foldable f => (a' -> a -> a') -> a' -> Flip f a b -> a' foldlFlip f a' (Flip fba) = case forallC of Forall (Dict :: Dict (CompC Foldable f b)) -> foldl f a' fba sequenceAFlip :: forall f a b t. (ForallC1 Traversable t, Applicative f) => Flip t (f a) b -> f (Flip t a b) sequenceAFlip (Flip fba) = case forallC of Forall (Dict :: Dict (CompC Traversable t b)) -> Flip <$> sequenceA fba newtype FlipNP f bs a = FlipNP { runFlipNP :: NP (Flip f a) bs } liftA_FNP :: (forall b. f b a -> g b a) -> FlipNP f bs a -> FlipNP g bs a liftA_FNP f = FlipNP . liftA_NP' (Flip . f . runFlip) . runFlipNP liftA2_FNP :: forall f g h a bs. (forall b. f b a -> g b a -> h b a) -> FlipNP f bs a -> FlipNP g bs a -> FlipNP h bs a liftA2_FNP f (FlipNP xs) (FlipNP ys) = FlipNP $ liftA2_NP' f' xs ys where f' :: forall b. Flip f a b -> Flip g a b -> Flip h a b f' (Flip x) (Flip y) = Flip $ f x y collapse_FNP :: FlipNP (FK f) bs a -> [f a] collapse_FNP (FlipNP np) = collapse_NP $ liftA_NP' f np where f (Flip (FK fa)) = K fa instance (SListI bs, All (CompC Show (Flip f a)) bs) => Show (FlipNP f bs a) where show (FlipNP np) = showAsList $ collapse_NP $ cliftA_NP (Proxy::Proxy (CompC Show (Flip f a))) (K . show) np instance ForallC1 Functor f => Functor (FlipNP f bs) where fmap f = FlipNP . liftA_NP' (fmapFlip f) . runFlipNP instance ForallC1 Foldable f => Foldable (FlipNP f bs) where foldr f a' (FlipNP Nil) = a' foldr f a' (FlipNP (x :* xs)) = foldrFlip f (foldr f a' (FlipNP xs)) x foldl f a' (FlipNP Nil) = a' foldl f a' (FlipNP (x :* xs)) = foldl f (foldlFlip f a' x) (FlipNP xs) instance (ForallC1 Functor t, ForallC1 Foldable t, ForallC1 Traversable t) => Traversable (FlipNP t bs) where sequenceA (FlipNP np) = fmap FlipNP $ sequence'_NP $ liftA_NP' (Comp . sequenceAFlip) np newtype FlipNS f bs a = FlipNS { runFlipNS :: NS (Flip f a) bs } liftA_FNS :: (forall b. f b a -> g b a) -> FlipNS f bs a -> FlipNS g bs a liftA_FNS f = FlipNS . liftA_NS' (Flip . f . runFlip) . runFlipNS liftA2_FNS :: forall f g h a bs. (forall b. f b a -> g b a -> h b a) -> FlipNP f bs a -> FlipNS g bs a -> FlipNS h bs a liftA2_FNS f (FlipNP xs) (FlipNS ys) = FlipNS $ liftA2_NS' f' xs ys where f' :: forall b. Flip f a b -> Flip g a b -> Flip h a b f' (Flip x) (Flip y) = Flip $ f x y collapse_FNS :: FlipNS (FK f) bs a -> f a collapse_FNS (FlipNS ns) = collapse_NS $ liftA_NS' f ns where f (Flip (FK fa)) = K fa instance (ForallC1 Show (Flip f a)) => Show (FlipNS f bs a) where show (FlipNS (Z x)) = showFlip x show (FlipNS (S xs)) = show (FlipNS xs) instance ForallC1 Functor f => Functor (FlipNS f bs) where fmap f = FlipNS . liftA_NS' (fmapFlip f) . runFlipNS instance ForallC1 Foldable f => Foldable (FlipNS f bs) where foldr f a' (FlipNS (S xs)) = foldr f a' (FlipNS xs) foldr f a' (FlipNS (Z x)) = foldrFlip f a' x foldl f a' (FlipNS (S xs)) = foldl f a' (FlipNS xs) foldl f a' (FlipNS (Z x)) = foldlFlip f a' x instance (ForallC1 Functor t, ForallC1 Foldable t, ForallC1 Traversable t) => Traversable (FlipNS t bs) where sequenceA (FlipNS ns) = fmap FlipNS $ sequence'_NS $ liftA_NS' (Comp . sequenceAFlip) ns newtype FlipSOP f bss a = FlipSOP { runFlipSOP :: FlipNS (FlipNP f) bss a } --newtype FlipSOP f bss a = FlipSOP { runFlipSOP :: SOP (Flip f a) bss } liftA_FSOP :: (forall b. f b a -> g b a) -> FlipSOP f bss a -> FlipSOP g bss a liftA_FSOP f (FlipSOP sop) = FlipSOP (liftA_FNS (liftA_FNP f) sop) collapse_FSOP :: FlipSOP (FK f) bs a -> [f a] collapse_FSOP (FlipSOP sop) = unComp . collapse_FNS $ liftA_FNS (FK . Comp . collapse_FNP) sop
vladfi1/hs-misc
Utils.hs
mit
7,460
0
15
1,688
3,692
1,871
1,821
130
1
module InstCtx where class C a where f :: a data T = K instance C T where f = K instance C a => C [a] where f = [ f ]
antalsz/hs-to-coq
examples/tests/InstCtx.hs
mit
128
0
6
43
64
35
29
8
0
module Platform (initPlatform) where import GHC.IO.Encoding import System.Win32.Console initPlatform :: IO () initPlatform = do setLocaleEncoding utf8 setConsoleOutputCP 65001
HairyDude/pdxparse
os/win32/Platform.hs
mit
186
0
7
29
48
26
22
7
1
module Hexadecimal ( hexToInt ) where import Data.Char (isHexDigit, toLower) import Data.List (foldl') hexToInt :: String -> Int hexToInt string | any (not . isHexDigit) string = 0 | otherwise = convert fromHex 16 string' where fromHex digit = fromEnum digit - offset digit offset digit = if digit <= '9' then fromEnum '0' else fromEnum 'a' - 10 string' = map toLower string convert :: (Char -> Int) -> Int -> String -> Int convert fromBase radix string = foldl' accumulate 0 values where values = map fromBase string accumulate number digit = number * radix + digit
tfausak/exercism-solutions
haskell/hexadecimal/Hexadecimal.hs
mit
640
0
10
172
216
110
106
18
2
module Main (main) where import Criterion.Main (bench, bgroup, defaultMain) import qualified Y2015.Bench import qualified Y2016.Bench main :: IO () main = defaultMain [ Y2015.Bench.benchmarks , Y2016.Bench.benchmarks ]
tylerjl/adventofcode
benchmark/Bench.hs
mit
243
0
7
51
67
41
26
8
1
{- Copyright (c) 2010-2012, Benedict R. Gaster All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Short Description: Distributed Linda implementation for Haskell Description : An implementation of distributed Linda-style tuple spaces, based on the CML implementation by John Reppy; from his book Concurrent Programming in ML. The implementation is built on STM and has a number of things that could be done better! It is worth noting that while it would have been possible to build an abstraction on top of STM channels to support CML style events the implementation passes channels explicitly. This has the disadvantage of having to explictly read/write from these channels in interfaces that could simply sync on an event in Reppy's implementation. The advantage is that we can use STM channels directly without an additonal layer of abstraction. It would be nice to see an event abstraction provided as part of STM, not simply in the CML package, but as a first class part of the STM implementation. -} module Linda ( TupleSpace, joinTupleSpace, inLinda, rdLinda, outLinda, AtomicVal(..), AtomicPat(..), TupleRep(..), Tuple, Template ) where import System.IO import System.IO.Error (isEOFError) import Control.Concurrent import Control.Concurrent.STM import Control.Concurrent.STM.TChan import Control.Concurrent.MVar -------------------------------------------------------------------------------- import TupleType import NetworkTuple import TupleServer import TupleStore import OutputServer -------------------------------------------------------------------------------- data TupleSpace = TupleSpace (TupleServerMsg -> IO ()) (Tuple -> IO ()) joinTupleSpace :: Maybe Port -> [(String, Port)] -> IO TupleSpace joinTupleSpace localPort remoteHosts = do reqChan <- atomically newTChan tsReqChan <- atomically newTChan let out tuple = atomically $ writeTChan tsReqChan (NetOutTuple tuple) (output, addTS) <- createOutputServer out logChan <- atomically $ dupTChan reqChan getInReqLog <- createLogServer logChan (netID, servers) <- initNetwork localPort remoteHosts tsReqChan (newRemoteTS reqChan addTS getInReqLog) port <- atomically $ dupTChan reqChan createTupleServer netID tsReqChan port mapM (newRemoteTS reqChan addTS getInReqLog) servers return $ TupleSpace (\msg -> atomically $ writeTChan reqChan msg ) output where newRemoteTS reqChan addTS getInReqLog (name, netID, conn) = do (port, initInReqs) <- getInReqLog () addTS (sendOutTupleNet conn) chan <- atomically $ dupTChan reqChan createProxyServer netID conn chan initInReqs --port initInReqs doInputOp tid (TupleSpace request _) template removeFlg nack = do replyChan <- atomically $ newTChan forkIO $ transactionMngr replyChan return replyChan where handleReply replyChan (msg,tsID) tid = do r <- atomically $ (Left `fmap` readTChan nack) `orElse`(Right `fmap` writeTChan replyChan msg) case r of Left _ -> request $ TSMsgCancel tid Right _ -> request $ TSMsgAccept tid tsID transactionMngr replyChan = do replyMB <- atomically $ newTChan request $ TSMsgIn tid removeFlg template (\x y -> atomically $ writeTChan replyMB (x,y)) r <- atomically $ (Left `fmap` readTChan nack) `orElse`(Right `fmap` readTChan replyMB) case r of Left _ -> request $ TSMsgCancel tid ; Right msg -> handleReply replyChan msg tid inLinda tid ts template = do nack <- atomically $ newTChan replyChan <- doInputOp tid ts template True nack tuple <- atomically $ readTChan replyChan return tuple rdLinda tid ts template = do nack <- atomically $ newTChan replyChan <- doInputOp tid ts template False nack binds <- atomically $ readTChan replyChan return binds outLinda (TupleSpace _ output) tuple = output tuple --------------------------------------------------------------------------------
bgaster/hlinda
Linda.hs
mit
6,067
0
15
1,666
891
448
443
78
3
module Bindings.Pkcs11.Attribs where import Bindings.Pkcs11 import Bindings.Pkcs11.Shared import Data.Bits import qualified Data.ByteString as BS import qualified Data.ByteString.UTF8 as BU8 import Data.ByteString.Unsafe import Data.List import Data.Word import Foreign.C.Types import Foreign.Marshal.Alloc import Foreign.Marshal.Array import Foreign.Marshal.Utils import Foreign.Ptr import Foreign.Storable import Control.Monad (when) -- | Represents an attribute of an object data Attribute = Class ClassType -- ^ class of an object, e.g. 'PrivateKey', 'SecretKey' | KeyType KeyTypeValue -- ^ e.g. 'RSA' or 'AES' | Label String -- ^ object's label | Id BS.ByteString -- ^ object's identifier | Token Bool -- ^ whether object is stored on the token or is a temporary session object | Local Bool -- ^ whether key was generated on the token or not | Private Bool -- ^ whether object is a private object or not | Application String -- ^ can be used to specify an application that manages object | Encrypt Bool -- ^ allow/deny encryption function for an object | Decrypt Bool -- ^ allow/deny decryption function for an object | Sign Bool -- ^ allow/deny signing function for an object | SignRecover Bool -- ^ allow/deny sign recover function for an object | Derive Bool -- ^ allow/deny key derivation functionality | SecondaryAuth Bool -- ^ if true secondary authentication would be required before key can be used | AlwaysAuthenticate Bool -- ^ if true user would have to supply PIN for each key use | ModulusBits CULong -- ^ number of bits used by modulus, for example in RSA public key | Modulus Integer -- ^ modulus value, used by RSA keys | PublicExponent Integer -- ^ value of public exponent, used by RSA public keys | PrimeBits CULong -- ^ number of bits used by prime in classic Diffie-Hellman | Prime Integer -- ^ value of prime modulus, used in classic Diffie-Hellman | Base Integer -- ^ value of generator, used in classic Diffie-Hellman | ValueLen CULong -- ^ length in bytes of the corresponding 'Value' attribute | Value BS.ByteString -- ^ object's value attribute, for example it is a DER encoded certificate for certificate objects | Extractable Bool -- ^ allows or denys extraction of certain attributes of private keys | NeverExtractable Bool -- ^ if true key never had been extractable | AlwaysSensitive Bool -- ^ if true key always had sensitive flag on | Modifiable Bool -- ^ allows or denys modification of object's attributes | EcParams BS.ByteString -- ^ DER encoded ANSI X9.62 parameters value for elliptic-curve algorithm | EcdsaParams BS.ByteString -- ^ DER encoded ANSI X9.62 parameters value for elliptic-curve algorithm | EcPoint BS.ByteString -- ^ DER encoded ANSI X9.62 point for elliptic-curve algorithm | CheckValue BS.ByteString -- ^ key checksum | KeyGenMechanism MechType -- ^ the mechanism used to generate the key | WrapWithTrusted Bool -- ^ if true key can only be wrapped with wrapping key that has trusted flag set | UnwrapTemplate [Attribute] -- ^ specifies attributes applied to keys unwrapped using this key | DeriveTemplate [Attribute] -- ^ specifies attributes applied to keys derived using this key | StartDate Date | EndDate Date deriving (Show, Eq) data MarshalAttr = BoolAttr Bool | ClassTypeAttr ClassType | KeyTypeAttr KeyTypeValue | StringAttr String | BigIntAttr Integer | ULongAttr CULong | ByteStringAttr BS.ByteString | AttrListAttr [Attribute] -- from http://hackage.haskell.org/package/binary-0.5.0.2/docs/src/Data-Binary.html#unroll unroll :: Integer -> [Word8] unroll = unfoldr step where step 0 = Nothing step i = Just (fromIntegral i, i `shiftR` 8) _bigIntLen i = length $ unroll i _pokeBigInt i ptr = pokeArray ptr (unroll i) _attrType :: Attribute -> AttributeType _attrType (Class _) = ClassType _attrType (KeyType _) = KeyTypeType _attrType (Label _) = LabelType _attrType (ModulusBits _) = ModulusBitsType _attrType (PrimeBits _) = PrimeBitsType _attrType (Token _) = TokenType _attrType (ValueLen _) = ValueLenType _attrType (Extractable _) = ExtractableType _attrType (Modifiable _) = ModifiableType _attrType (Decrypt _) = DecryptType _attrType (Encrypt _) = EncryptType _attrType (SignRecover _) = SignRecoverType _attrType (Value _) = ValueType _attrType (Prime _) = PrimeType _attrType (Base _) = BaseType _attrType (EcParams _) = EcParamsType _attrType (EcPoint _) = EcPointType _attrType (UnwrapTemplate _) = UnwrapTemplateType _attrToMarshal :: Attribute -> MarshalAttr _attrToMarshal (Class v) = ClassTypeAttr v _attrToMarshal (KeyType v) = KeyTypeAttr v _attrToMarshal (Label v) = StringAttr v _attrToMarshal (ModulusBits v) = ULongAttr v _attrToMarshal (PrimeBits v) = ULongAttr v _attrToMarshal (ValueLen v) = ULongAttr v _attrToMarshal (Token v) = BoolAttr v _attrToMarshal (Extractable v) = BoolAttr v _attrToMarshal (Modifiable v) = BoolAttr v _attrToMarshal (Decrypt v) = BoolAttr v _attrToMarshal (Encrypt v) = BoolAttr v _attrToMarshal (SignRecover v) = BoolAttr v _attrToMarshal (Value v) = ByteStringAttr v _attrToMarshal (Prime v) = BigIntAttr v _attrToMarshal (Base v) = BigIntAttr v _attrToMarshal (EcParams v) = ByteStringAttr v _attrToMarshal (EcPoint v) = ByteStringAttr v _attrToMarshal (UnwrapTemplate v) = AttrListAttr v _attrListSize l = sizeOf (LlAttribute ClassType nullPtr 0) * length l + _valuesSize l _pokeAttrList l ptr = do let valuesPtr = ptr `plusPtr` (sizeOf (LlAttribute ClassType nullPtr 0) * length l) pokeArray (castPtr ptr) (_makeLowLevelAttrs l valuesPtr) _pokeValues l valuesPtr _valueSize :: MarshalAttr -> Int _valueSize (ClassTypeAttr _) = sizeOf (0 :: CK_OBJECT_CLASS) _valueSize (KeyTypeAttr _) = sizeOf (0 :: CK_KEY_TYPE) _valueSize (StringAttr l) = BU8.length $ BU8.fromString l _valueSize (ULongAttr _) = sizeOf (0 :: CULong) _valueSize (BoolAttr _) = sizeOf (0 :: CK_BBOOL) _valueSize (ByteStringAttr bs) = BS.length bs _valueSize (AttrListAttr l) = _attrListSize l _pokeValue :: MarshalAttr -> Ptr () -> IO () _pokeValue (ClassTypeAttr c) ptr = poke (castPtr ptr :: Ptr CK_OBJECT_CLASS) (fromIntegral $ fromEnum c) _pokeValue (KeyTypeAttr k) ptr = poke (castPtr ptr :: Ptr CK_KEY_TYPE) (fromIntegral $ fromEnum k) _pokeValue (StringAttr s) ptr = unsafeUseAsCStringLen (BU8.fromString s) $ \(src, len) -> copyBytes ptr (castPtr src :: Ptr ()) len _pokeValue (ULongAttr l) ptr = poke (castPtr ptr :: Ptr CULong) (fromIntegral l) _pokeValue (BoolAttr b) ptr = poke (castPtr ptr :: Ptr CK_BBOOL) (fromBool b :: CK_BBOOL) _pokeValue (ByteStringAttr bs) ptr = unsafeUseAsCStringLen bs $ \(src, len) -> copyBytes ptr (castPtr src :: Ptr ()) len _pokeValue (BigIntAttr p) ptr = _pokeBigInt p (castPtr ptr) _pokeValue (AttrListAttr l) ptr = _pokeAttrList l ptr _pokeValues :: [Attribute] -> Ptr () -> IO () _pokeValues [] p = return () _pokeValues (a:rem) p = do _pokeValue (_attrToMarshal a) p _pokeValues rem (p `plusPtr` _valueSize (_attrToMarshal a)) _valuesSize :: [Attribute] -> Int _valuesSize = foldr ((+) . (_valueSize . _attrToMarshal)) 0 _makeLowLevelAttrs :: [Attribute] -> Ptr () -> [LlAttribute] _makeLowLevelAttrs [] valuePtr = [] _makeLowLevelAttrs (a:rem) valuePtr = let valuePtr' = valuePtr `plusPtr` _valueSize (_attrToMarshal a) llAttr = LlAttribute {attributeType = _attrType a, attributeValuePtr = valuePtr, attributeSize = fromIntegral $ _valueSize (_attrToMarshal a)} in llAttr : _makeLowLevelAttrs rem valuePtr' _withAttribs :: [Attribute] -> (Ptr LlAttribute -> IO a) -> IO a _withAttribs attribs f = allocaBytes (_attrListSize attribs) $ \ptr -> do _pokeAttrList attribs ptr f (castPtr ptr) _peekBigInt ptr len constr = do arr <- peekArray (fromIntegral len) (castPtr ptr :: Ptr Word8) return $ constr $ foldl (\acc v -> fromIntegral v + (acc * 256)) 0 arr _peekBool ptr len constr = do val <- peek (castPtr ptr :: Ptr CK_BBOOL) return $ constr (val /= 0) _peekByteString ptr len constr = do val <- BS.packCStringLen (castPtr ptr, fromIntegral len) return $ constr val _peekU2F8String :: Ptr () -> CULong -> (String -> Attribute) -> IO Attribute _peekU2F8String ptr len constr = do val <- BS.packCStringLen (castPtr ptr, fromIntegral len) return $ constr $ BU8.toString val _peekAttrList :: Ptr () -> CULong -> ([Attribute] -> Attribute) -> IO Attribute _peekAttrList ptr len constr = do let num = fromIntegral len `div` sizeOf (LlAttribute ClassType nullPtr 0) llArr <- peekArray num (castPtr ptr) attrArr <- mapM _llAttrToAttr llArr return $ constr attrArr _peekDate :: Ptr () -> CULong -> (Date -> Attribute) -> IO Attribute _peekDate ptr len constr = do val <- peek (castPtr ptr :: Ptr Date) return $ constr val _llAttrToAttr :: LlAttribute -> IO Attribute _llAttrToAttr (LlAttribute ClassType ptr len) = do val <- peek (castPtr ptr :: Ptr CK_OBJECT_CLASS) return (Class $ toEnum $ fromIntegral val) _llAttrToAttr (LlAttribute KeyTypeType ptr len) = do val <- peek (castPtr ptr :: Ptr CK_KEY_TYPE) return (KeyType $ toEnum $ fromIntegral val) _llAttrToAttr (LlAttribute KeyGenMechanismType ptr len) = do val <- peek (castPtr ptr :: Ptr CK_MECHANISM_TYPE) return (KeyGenMechanism $ toEnum $ fromIntegral val) _llAttrToAttr (LlAttribute PrivateType ptr len) = _peekBool ptr len Private _llAttrToAttr (LlAttribute ModulusType ptr len) = _peekBigInt ptr len Modulus _llAttrToAttr (LlAttribute PublicExponentType ptr len) = _peekBigInt ptr len PublicExponent _llAttrToAttr (LlAttribute PrimeType ptr len) = _peekBigInt ptr len Prime _llAttrToAttr (LlAttribute BaseType ptr len) = _peekBigInt ptr len Base _llAttrToAttr (LlAttribute DecryptType ptr len) = _peekBool ptr len Decrypt _llAttrToAttr (LlAttribute SignType ptr len) = _peekBool ptr len Sign _llAttrToAttr (LlAttribute SignRecoverType ptr len) = _peekBool ptr len SignRecover _llAttrToAttr (LlAttribute ExtractableType ptr len) = _peekBool ptr len Extractable _llAttrToAttr (LlAttribute ModifiableType ptr len) = _peekBool ptr len Modifiable _llAttrToAttr (LlAttribute EcParamsType ptr len) = _peekByteString ptr len EcParams _llAttrToAttr (LlAttribute EcdsaParamsType ptr len) = _peekByteString ptr len EcdsaParams _llAttrToAttr (LlAttribute EcPointType ptr len) = _peekByteString ptr len EcPoint _llAttrToAttr (LlAttribute LabelType ptr len) = _peekU2F8String ptr len Label _llAttrToAttr (LlAttribute ApplicationType ptr len) = _peekU2F8String ptr len Application _llAttrToAttr (LlAttribute ValueType ptr len) = _peekByteString ptr len Value _llAttrToAttr (LlAttribute CheckValueType ptr len) = _peekByteString ptr len CheckValue _llAttrToAttr (LlAttribute DeriveType ptr len) = _peekBool ptr len Derive _llAttrToAttr (LlAttribute LocalType ptr len) = _peekBool ptr len Local _llAttrToAttr (LlAttribute NeverExtractableType ptr len) = _peekBool ptr len NeverExtractable _llAttrToAttr (LlAttribute AlwaysSensitiveType ptr len) = _peekBool ptr len AlwaysSensitive _llAttrToAttr (LlAttribute SecondaryAuthType ptr len) = _peekBool ptr len SecondaryAuth _llAttrToAttr (LlAttribute AlwaysAuthenticateType ptr len) = _peekBool ptr len AlwaysAuthenticate _llAttrToAttr (LlAttribute WrapWithTrustedType ptr len) = _peekBool ptr len WrapWithTrusted _llAttrToAttr (LlAttribute UnwrapTemplateType ptr len) = _peekAttrList ptr len UnwrapTemplate _llAttrToAttr (LlAttribute DeriveTemplateType ptr len) = _peekAttrList ptr len DeriveTemplate _llAttrToAttr (LlAttribute IdType ptr len) = _peekByteString ptr len Id _llAttrToAttr (LlAttribute StartDateType ptr len) = _peekDate ptr len StartDate _llAttrToAttr (LlAttribute EndDateType ptr len) = _peekDate ptr len EndDate _llAttrToAttr (LlAttribute typ _ _) = error ("_llAttrToAttr needs to be implemented for " ++ show typ) _getAttr :: FunctionListPtr -> SessionHandle -> ObjectHandle -> AttributeType -> Ptr x -> IO () _getAttr functionListPtr sessionHandle objHandle attrType valPtr = alloca $ \attrPtr -> do poke attrPtr (LlAttribute attrType (castPtr valPtr) (fromIntegral $ sizeOf valPtr)) rv <- getAttributeValue' functionListPtr sessionHandle objHandle attrPtr 1 when (rv /= 0) $ fail $ "failed to get attribute: " ++ rvToStr rv getObjectAttr' :: FunctionListPtr -> SessionHandle -> ObjectHandle -> AttributeType -> IO Attribute getObjectAttr' functionListPtr sessionHandle objHandle attrType = alloca $ \attrPtr -> do poke attrPtr (LlAttribute attrType nullPtr 0) rv <- getAttributeValue' functionListPtr sessionHandle objHandle attrPtr 1 attrWithLen <- peek attrPtr allocaBytes (fromIntegral $ attributeSize attrWithLen) $ \attrVal -> do poke attrPtr (LlAttribute attrType attrVal (attributeSize attrWithLen)) rv <- getAttributeValue' functionListPtr sessionHandle objHandle attrPtr 1 if rv /= 0 then fail $ "failed to get attribute: " ++ rvToStr rv else do llAttr <- peek attrPtr _llAttrToAttr llAttr getBoolAttr :: AttributeType -> Object -> IO Bool getBoolAttr attrType (Object funcListPtr sessHandle objHandle) = alloca $ \valuePtr -> do _getAttr funcListPtr sessHandle objHandle attrType (valuePtr :: Ptr CK_BBOOL) val <- peek valuePtr return $ toBool val
denisenkom/hspkcs11
src/Bindings/Pkcs11/Attribs.hs
mit
13,312
0
17
2,278
3,887
1,950
1,937
239
2
module Game.Text where import Control.Monad.Trans import Control.Monad.Trans.State import Data.Char import Game.Graphics import Game.State import Settings -- |Sets font and background color -- setFontColor :: (GameColor, GameColor) -> StateT GameState IO () setFontColor (fc, bc) = do gameState <- get put $ gameState { fontColor = fc, backColor = bc } return () -- |Sets position for text output -- setTextPos :: Point -> StateT GameState IO () setTextPos (Point px py) = modify (\s -> s { printX = px , printY = py }) -- |Returns text position -- getTextPos :: StateT GameState IO Point getTextPos = do gstate <- get return (Point (printX gstate) (printY gstate)) -- |Prints a string in the current window. Newlines are supported -- usPrint :: String -> StateT GameState IO () usPrint str = do gstate <- get printOne $ lines str where printOne [] = return () printOne (s:ss) = do (Point px py) <- getTextPos vwDrawPropString px py s (w, h) <- vwlMeasureString s liftIO $ print $ "W: " ++ (show w) liftIO $ print $ "H: " ++ (show h) liftIO $ print s modify (\s -> s { printX = windowX s , printY = printY s + h }) printOne ss -- | Prints a string in the current window. -- Newlines are supported -- usCPrint :: String -> StateT GameState IO () usCPrint s = (mapM_ usCPrintLine $ lines s) >> updateScreen -- | Prints a string centered on the current line -- Newlines are not supported -- usCPrintLine :: String -> StateT GameState IO () usCPrintLine s = do gstate <- get (w, h) <- vwlMeasureString s if w > (windowW gstate) then error "usCPrintLine: string exceeds width" else return () let px = round $ fromIntegral ((windowX gstate) + (windowW gstate - w)) / 2 py = printY gstate vwDrawPropString px py s put $ gstate { printY = printY gstate + h }
vTurbine/w3dhs
src/Game/Text.hs
mit
2,026
0
17
595
650
333
317
48
2
{-# LANGUAGE RankNTypes, GADTs, ScopedTypeVariables #-} -- This module defines a compilers for converting between dynamic -- programs to static programs omitting as many dynamic checks as possible. module Compiler where import Data.Map as Map import qualified Common as C import StaticLang import PrettyPrint import qualified Lang as DL import DataDynamic import qualified DataTypeable as TR import DataTypeable -- ======================================================================================= data ArrowRep t where ArrowRep :: TypeRep t1 -> TypeRep t2 -> ArrowRep (t1 -> t2) -- | Attempt to turn a TypeRep (->), into an ArrowRep. -- | tra should look as follows: -- (((tr) tra1) tra2) -- <= tra ==========> -- <= tra' ==> -- Where tr is -(>) arrowUnify :: TypeRep a -> Maybe (ArrowRep a) arrowUnify tra = do (TR.App tra' tra2) <- splitApp tra (TR.App tr tra1) <- splitApp tra' Refl <- eqT tr (typeRep :: TypeRep (->)) return $ ArrowRep tra1 tra2 -- ======================================================================================= -- | Take a TypeRep 'tr' and a StaticExp Dynamic 'he' and check whether 'tr' is an -- | ArrorRep of the -- | Updated compiler. We use information about the current context to infer the types -- | and we percolate this information down though an additional TypeRep parameter. -- | TODO: We can define an ADT which holds the different types of errors we expect to -- | have. Then we can change the return value to Either (Static t) (MyErrors) -- | Then we can return an error and unit test to ensure things that shouldn't -- | compile, don't. compile :: TypeRep t -> DL.Exp -> StaticExp t compile tr (DL.Lam str e) = case arrowUnify tr of -- Ensure that we expect a function from our contex. Just (ArrowRep t1 t2) -> -- Our first argument must be a Dynamic. For now... case eqT t1 C.trDynamic of Just Refl -> Lam str (compile t2 e) -- Type of exp must be of t2. Nothing -> error "Lam: First argument of arrow should be dynamic." Nothing -> -- Not a function, maybe a dynamic type? cast. case eqT tr C.trDynamic of Just Refl -> To (Lam str (compile C.trDynamic e)) Nothing -> error "Lam: Type is not arrow or dynamic." compile tr (f DL.:@ e) = let trArrow = mkTyApp (mkTyApp (typeRep :: TypeRep (->)) C.trDynamic) tr in (compile trArrow f) :@ (compile C.trDynamic e) -- Equality is hard... We should pass information up the tree as well as down. -- TODO : This way, we can recurse until we know a type to type this expressions. compile tr (DL.Bin C.Eq e1 e2) = checkTr tr $ BinEq (compile C.trDynamic e1) (compile C.trDynamic e2) compile tr (DL.Uni C.Not e) = checkTr tr $ UniNot (compile trBool e) -- We hit a binary expression. Based on the operator we can check if the types are -- correct and infer the type of our subexpressions from those. We then check if -- our results matches our passed tr. compile tr (DL.Bin op e1 e2) = if intIntOperands op then checkTr tr $ BinInt (opToInt op) e1I' e2I' else if intBoolOperands op then checkTr tr $ BinIntBool (opIntToBool op) e1I' e2I' else if boolOperands op then checkTr tr $ BinBool (opToBool op) (compile trBool e1) (compile trBool e2) else error $ show op ++ ": Unimplemented Bin operator." where e1I' = compile trInte e1 e2I' = compile trInte e2 -- checkTr tr $ Bin op (compile trInt e1) (compile trInt e2) compile tr (DL.Lit n) = checkTr tr (Lit n) compile tr (DL.Var var) = checkTr tr (Var var) compile tr (DL.If cond e1 e2) = If (compile trBool cond) (compile tr e1) (compile tr e2) -- ======================================================================================= -- | These function are used in `compile`. When we get a tr which is a trBool -- | we don't know whether the subexpressions should be integers or bools, we can figure -- | it out based on the operator though. Except in the case of Eq and Neq... boolOperands :: C.BinOp -> Bool boolOperands C.Or = True boolOperands C.And = True boolOperands _ = False intIntOperands :: C.BinOp -> Bool intIntOperands C.Plus = True intIntOperands C.Minus = True intIntOperands C.Mult = True intIntOperands _ = False intBoolOperands :: C.BinOp -> Bool intBoolOperands C.Lte = True intBoolOperands C.Gte = True intBoolOperands C.Lt = True intBoolOperands C.Gt = True intBoolOperands _ = False -- ======================================================================================= errorMessageTo = " is the wrong operator for this function." opToInt :: C.BinOp -> IntIntOp opToInt C.Plus = Plus opToInt C.Minus = Minus opToInt C.Mult = Mult opToInt op = error $ show op ++ errorMessageTo opToBool :: C.BinOp -> BoolBoolOp opToBool C.And = And opToBool C.Or = Or opToBool op = error $ show op ++ errorMessageTo opIntToBool :: C.BinOp -> IntBoolOp opIntToBool C.Lte = Lte opIntToBool C.Gte = Gte opIntToBool C.Lt = Lt opIntToBool C.Gt = Gt opIntToBool op = error $ show op ++ errorMessageTo -- ======================================================================================= -- | Given a type representation and an expression, check that the expression is -- | of the type specified by the type represenation. Else it may be the case -- | that we want a dynamic or we have a dynamic, then cast respectively. checkTr :: forall a b. (Typeable b) => TypeRep a -> StaticExp b -> StaticExp a checkTr tra exp = -- tra and trb are equal. Easy casting to a StaticExp a. case eqT tra trb of Just Refl -> exp :: StaticExp a -- We expected a Dynamic, but our term isn't so. So we cast it to one. Nothing -> case eqT C.trDynamic tra of Just Refl -> To exp -- Our argument is Dynamic, cast it to the type it should be. We rely on -- withTypeable to do the work. Why? Nothing -> case eqT C.trDynamic trb of Just Refl -> withTypeable tra (From exp) Nothing -> error $ "checkTr: Type mismatch error.\n Expected: " ++ show tra ++ "\n Actual: " ++ show trb where trb = typeRep :: TypeRep b
plclub/cis670-16fa
projects/DynamicLang/src/Compiler.hs
mit
6,116
0
17
1,276
1,345
689
656
91
7
import Data.Numbers.Primes main = print( sum( takeWhile(<=2000000) primes ) )
emilkloeden/21-days-of-Euler
Haskell/10.hs
mit
77
1
10
9
36
18
18
2
1
{-# LANGUAGE CPP #-} {-# LANGUAGE PatternGuards #-} -- | Manage GHC package databases module PackageDBs ( PackageDBs (..) , ArgStyle (..) , dbArgs , buildArgStyle , getPackageDBsFromEnv , getPackageDBArgs ) where import System.Environment (getEnvironment) import System.FilePath (splitSearchPath, searchPathSeparator) -- | Full stack of GHC package databases data PackageDBs = PackageDBs { includeUser :: Bool -- | Unsupported on GHC < 7.6 , includeGlobal :: Bool , extraDBs :: [FilePath] } deriving (Show, Eq) -- | Package database handling switched between GHC 7.4 and 7.6 data ArgStyle = Pre76 | Post76 deriving (Show, Eq) -- | Determine command line arguments to be passed to GHC to set databases correctly -- -- >>> dbArgs Post76 (PackageDBs False True []) -- ["-no-user-package-db"] -- -- >>> dbArgs Pre76 (PackageDBs True True ["somedb"]) -- ["-package-conf","somedb"] dbArgs :: ArgStyle -> PackageDBs -> [String] dbArgs Post76 (PackageDBs user global extras) = (if user then id else ("-no-user-package-db":)) $ (if global then id else ("-no-global-package-db":)) $ concatMap (\extra -> ["-package-db", extra]) extras dbArgs Pre76 (PackageDBs _ False _) = error "Global package database must be included with GHC < 7.6" dbArgs Pre76 (PackageDBs user True extras) = (if user then id else ("-no-user-package-conf":)) $ concatMap (\extra -> ["-package-conf", extra]) extras -- | The argument style to be used with the current GHC version buildArgStyle :: ArgStyle #if __GLASGOW_HASKELL__ >= 706 buildArgStyle = Post76 #else buildArgStyle = Pre76 #endif -- | Determine the PackageDBs based on the environment. getPackageDBsFromEnv :: IO PackageDBs getPackageDBsFromEnv = do env <- getEnvironment return $ case () of () | Just packageDBs <- lookup "GHC_PACKAGE_PATH" env -> fromEnvMulti packageDBs | otherwise -> PackageDBs True True [] where fromEnvMulti s = PackageDBs { includeUser = False , includeGlobal = global , extraDBs = splitSearchPath s' } where (s', global) = case reverse s of c:rest | c == searchPathSeparator -> (reverse rest, True) _ -> (s, False) -- | Get the package DB flags for the current GHC version and from the -- environment. getPackageDBArgs :: IO [String] getPackageDBArgs = do dbs <- getPackageDBsFromEnv return $ dbArgs buildArgStyle dbs
sol/doctest
src/PackageDBs.hs
mit
2,537
0
15
612
531
301
230
51
4
import Data.Maybe (fromJust) import qualified Data.Vector as V import Algorithms.MDP.Examples.Ex_3_1 hiding (mdp, cost) import Algorithms.MDP.Examples.Ex_3_2 import Algorithms.MDP import Algorithms.MDP.ValueIteration iterations = undiscountedRelativeValueIteration mdp pairs = zip iterations (tail iterations) -- | Takes elements from a list while each adjacent pair of elements -- satisfies the given predicate. takeWhile2 :: (a -> a -> Bool) -> [a] -> [a] takeWhile2 _ [] = [] takeWhile2 p as = map fst $ takeWhile (uncurry p) (zip as (tail as)) distinguished = A showAll (CFBounds h lb ub) = unwords [show h, show lb, show ub] main = do mapM_ (putStrLn . showAll) $ take 11 iterations
prsteele/mdp
src/run-ex-3-2.hs
mit
697
2
10
113
243
128
115
15
1
{-# htermination show :: (Show a, Show k) => (a,k) -> String #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_show_9.hs
mit
65
0
2
13
3
2
1
1
0
-- | Commands for the Ultrasonic I2C distance sensor module NXT.Ultrasonic where import NXT.Codes import NXT.Commands import NXT.Comm import Data.Word import qualified Data.ByteString as B -- I2C device ID of the sensor i2c_dev = 0x02::Word8 ------------------------------------------------------------------------------ -- I2C Ultrasonic Sensor Commands ------------------------------------------------------------------------------ data I2CCommand = I2CC { i2cmessage :: Message, -- ^ I2C Address, followed by Commands i2rx ::Word8 -- ^ RX length (expected return length) } -- first value is the i2c address, second value is the expected number of bytes returned read_version = I2CC (B.singleton 0x00) 8 read_product_id = I2CC (B.singleton 0x08) 8 read_sensor_type = I2CC (B.singleton 0x10) 8 read_factory_zero = I2CC (B.singleton 0x11) 1 read_factory_scale_factor = I2CC (B.singleton 0x12) 1 read_factory_scale_divisor = I2CC (B.singleton 0x13) 1 read_measurement_units = I2CC (B.singleton 0x14) 7 -- value is the i2c address (all of these ops always expect to return 1 byte) read_continuous_measurements_interval = I2CC (B.singleton 0x40) 1 read_command_state = I2CC (B.singleton 0x41) 1 read_measurement_byte_0 = I2CC (B.singleton 0x42) 1 read_measurement_byte_1 = I2CC (B.singleton 0x43) 1 read_measurement_byte_2 = I2CC (B.singleton 0x44) 1 read_measurement_byte_3 = I2CC (B.singleton 0x45) 1 read_measurement_byte_4 = I2CC (B.singleton 0x46) 1 read_measurement_byte_5 = I2CC (B.singleton 0x47) 1 read_measurement_byte_6 = I2CC (B.singleton 0x48) 1 read_measurement_byte_7 = I2CC (B.singleton 0x49) 1 read_actual_zero = I2CC (B.singleton 0x50) 1 read_actual_scale_factor = I2CC (B.singleton 0x51) 1 read_actual_scale_divisor = I2CC (B.singleton 0x52) 1 -- first value is the i2c address, second value is the command off_command = I2CC (B.pack [0x41, 0x00]) 0 single_shot_command = I2CC (B.pack [0x41, 0x01]) 0 continuous_measurement_command = I2CC (B.pack [0x41, 0x02]) 0 event_capture_command = I2CC (B.pack [0x41, 0x03]) 0 request_warm_reset = I2CC (B.pack [0x41, 0x04]) 0 set_continuous_measurement_interval = I2CC (B.singleton 0x40 ) 0 set_actual_zero = I2CC (B.singleton 0x50 ) 0 set_actual_scale_factor = I2CC (B.singleton 0x51 ) 0 set_actual_scale_divisor = I2CC (B.singleton 0x52 ) 0 -- | Wrapper around 'NXT.Commands.lswrite' that accepts a 'I2CCommand' instead -- of seperate arguments for command and Rx. Also prepends the correct I2C -- device ID to the message. i2cwrite :: NXTHandle -> InputPort -> I2CCommand -> IO () i2cwrite h port (I2CC msg rx) = lswrite h port (i2c_dev +++ msg) rx
janv/haskell-nxt
src/NXT/Ultrasonic.hs
mit
2,975
4
9
714
690
365
325
41
1
module Drync.Sync ( sync , syncFile , syncDirectory ) where import Drync.Missing import Drync.Options import Drync.System import Drync.Transfer import Control.Monad (forM_, when) import Data.List (partition) import Data.Time (UTCTime, diffUTCTime) import Network.Google.Drive import System.Directory (getModificationTime) import System.FilePath ((</>)) import System.FilePath.Glob (match) sync :: Options -> FilePath -> File -> Api () sync options parent file = do let local = parent </> localPath file if isFolder file then syncDirectory options local file else syncFile options local file syncFile :: Options -> FilePath -> File -> Api () syncFile options fp file = do modified <- liftIO $ getModificationTime fp let rmodified = fileModified $ fileData file when (different modified rmodified) $ if modified > rmodified then upload options fp $ setModified modified file else download options file fp where -- Downloading or uploading results in a small difference in modification -- times. We should ignore such differences so as to not continually -- re-sync files back and forth. different :: UTCTime -> UTCTime -> Bool different x = (> 30) . abs . diffUTCTime x setModified :: UTCTime -> File -> File setModified t f@(File _ fd) = f { fileData = fd { fileModified = t } } syncDirectory :: Options -> FilePath -> File -> Api () syncDirectory options fp file = do files <- listVisibleContents file paths <- liftIO $ getVisibleDirectoryContents fp let (locals, both, remotes) = categorize paths files forM_ (filter include locals) $ missingRemote options file . (fp </>) forM_ (filter (include . localPath) remotes) $ missingLocal options fp forM_ (filter (include . localPath) both) $ sync options fp where include :: FilePath -> Bool include path = not $ any (`match` path) $ oExcludes options categorize :: [FilePath] -> [File] -> ([FilePath], [File], [File]) categorize paths files = (paths', both, files') where paths' = filter (`notElem` (map localPath both)) paths (both, files') = partition ((`elem` paths) . localPath) files
pbrisbin/drync
src/Drync/Sync.hs
mit
2,208
0
12
485
720
382
338
47
2
{- | Module : Text.Highlighting.Kate.Format.Blaze Copyright : Copyright (C) 2008 John MacFarlane, 2011 Antoine Latter License : GNU GPL, version 2 or above Maintainer : Antoine Latter <[email protected]> Stability : alpha Portability : portable Formatters that convert a list of annotated source lines to various output formats. -} module Text.Highlighting.Kate.Format.Blaze ( formatAsHtml, FormatOption (..), defaultHighlightingCss ) where import Text.Highlighting.Kate.Format ( FormatOption(..), defaultHighlightingCss) import Text.Highlighting.Kate.Definitions import Text.Blaze.Html5 (toHtml, toValue, Html, (!)) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Data.List (intersperse) import Data.Monoid (mconcat) -- | Format a list of highlighted @SourceLine@s as Html. formatAsHtml :: [FormatOption] -- ^ Options -> String -- ^ Language -> [SourceLine] -- ^ Source lines to format -> Html formatAsHtml opts lang lines = let startNum = getStartNum opts numberOfLines = length lines code = H.code ! A.class_ (toValue $ unwords ["sourceCode", lang]) $ mconcat $ intersperse H.br (map (sourceLineToHtml opts) lines) in if OptInline `elem` opts then code else if OptNumberLines `elem` opts then let onClick = "with (this.firstChild.style) { display = (display == '') ? 'none' : '' }" nums = H.td ! A.class_ (toValue "lineNumbers") ! A.title (toValue "Click to toggle line numbers") ! A.onclick (toValue onClick) $ H.pre $ mconcat $ intersperse H.br (map lineNum [startNum..(startNum + numberOfLines - 1)]) lineNum n = if OptLineAnchors `elem` opts then H.a ! A.id (toValue $ show n) $ toHtml (show n) else toHtml $ show n sourceCode = H.td ! A.class_ (toValue "sourceCode") $ H.pre ! A.class_ (toValue "sourceCode") $ code in H.table ! A.class_ (toValue "sourceCode") $ H.tr $ mconcat [nums, sourceCode] else H.pre ! A.class_ (toValue "sourceCode") $ code applyAtts elem [] = elem applyAtts elem (x:xs) = (elem ! x) `applyAtts` xs labeledSourceToHtml :: [FormatOption] -> LabeledSource -> Html labeledSourceToHtml _ ([], txt) = toHtml txt labeledSourceToHtml opts (labs, txt) = if null attribs then toHtml txt else H.span `applyAtts` attribs $ toHtml txt where classes = unwords $ if OptDetailed `elem` opts then map removeSpaces labs else drop 1 labs -- first is specific attribs = [A.class_ (toValue classes) | not (null classes)] ++ [A.title (toValue classes) | OptTitleAttributes `elem` opts] sourceLineToHtml :: [FormatOption] -> SourceLine -> Html sourceLineToHtml opts contents = mconcat $ map (labeledSourceToHtml opts) contents removeSpaces :: String -> String removeSpaces = filter (/= ' ') getStartNum :: [FormatOption] -> Int getStartNum [] = 1 getStartNum (OptNumberFrom n : _) = n getStartNum (_:xs) = getStartNum xs
aslatter/kate-blaze
src/Text/Highlighting/Kate/Format/Blaze.hs
gpl-2.0
3,591
0
21
1,214
877
477
400
62
4
{- Copyright (C) 2017 WATANABE Yuki <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. -} module Flesh.Language.Parser.BufferSpec (spec) where import Control.Monad (replicateM, replicateM_) import Control.Monad.State.Strict (evalState, execState) import Flesh.Language.Parser.Buffer import Flesh.Source.Position import Flesh.Source.PositionTestUtil () import Test.Hspec (Spec, describe, parallel) import Test.Hspec.QuickCheck (prop) import Test.QuickCheck ((===)) spec :: Spec spec = parallel $ do describe "MonadBuffer (RecordT m)" $ do describe "popChar" $ do prop "returns popped character" $ \s n -> let _ = s :: PositionedString r1 = flip evalState s $ runPositionedStringT $ evalRecordT $ replicateM n popChar r2 = flip evalState s $ runPositionedStringT $ replicateM n popChar in r1 === r2 describe "lookahead" $ do prop "applies lookahead to inner monad" $ \s n -> let _ = s :: PositionedString r1 = flip execState s $ runPositionedStringT $ evalRecordT $ lookahead $ replicateM_ n popChar r2 = flip execState s $ runPositionedStringT $ evalRecordT $ return () in r1 === r2 prop "does not record consumed characters" $ \s n -> let _ = s :: PositionedString r1 = flip evalState s $ runPositionedStringT $ evalRecordT $ do lookahead $ replicateM_ n popChar reverseConsumedChars r2 = flip evalState s $ runPositionedStringT $ evalRecordT $ reverseConsumedChars in r1 === r2 describe "MonadRecord (RecordT m)" $ do describe "reverseConsumedChars" $ do prop "returns consumed characters" $ \s n -> let _ = s :: PositionedString r = flip evalState s $ runPositionedStringT $ evalRecordT $ do replicateM_ n popChar reverseConsumedChars in reverse r === take n (unposition s) -- vim: set et sw=2 sts=2 tw=78:
magicant/flesh
hspec-src/Flesh/Language/Parser/BufferSpec.hs
gpl-2.0
2,622
0
32
680
526
266
260
44
1
-- Aufgabe 12.17 data Person = PER Name Geschlecht Kinder deriving Show type Name = String type Kinder = [Person] -- a) benenne_um :: Person -> Name -> Person benenne_um (PER _ geschlecht kinder) name = (PER name geschlecht kinder) -- b) data Geschlecht = Weiblich | Maennlich deriving Show weiblich :: Person -> Bool weiblich (PER _ Weiblich _) = True weiblich (PER _ Maennlich _) = False {- In the solution, it is written, the "==" operator can only be used, - if "deriving (Show, Eq)" is written in the algebraic data type -} -- c) nehme :: (Person -> Bool) -> [Person] -> [Person] nehme _ [] = [] nehme person (x:xs) | (person x) = [x] ++ (nehme person xs) | otherwise = nehme person xs -- The solution uses an if-then-else construct toechter :: Person -> [Person] toechter (PER x y kinder) = nehme weiblich kinder -- d) addiere :: [Int] -> Int addiere [] = 1 addiere (x:xs) = x + (addiere xs) nachfahren :: Person -> Int nachfahren (PER x y kinder) = addiere (map nachfahren kinder)
KaliszAd/programmierung2012
aufgabe12_17.hs
gpl-2.0
1,003
0
9
199
358
191
167
21
1
module Main where import Primes (primeSequence, prime) import Util (concatInts, asList, removeDuplicates) import Data.List (elem, sort, groupBy) primePair a b = prime x && prime y where x = concatInts [a,b] y = concatInts [b,a] primesUntil step = takeWhile (\x -> x <= step) primeSequence getPairs xs = map (prefix++) $ results where prefix = init $ head xs ys = map last xs results = [[a,b] | a <- ys, b <- takeWhile (<a) ys, primePair a b] target = 5 grouping a b = init a == init b performPass n groups = groupBy grouping $ concat results where sieve n group = length group >= target - n filtered = filter (sieve n) groups results = map getPairs groups main :: IO () main = let upper = sum [8389,6733,5701,5197,13, -3, -7, -11, -13] -- upper = 10000 primes = map asList $ primesUntil upper pairs = getPairs primes grouped = groupBy grouping pairs chewAway groups = foldl (\x n -> performPass n x) groups passes where passes = [1..target-2] -- 2 = size of a pair, which we started with results = chewAway grouped format = minimum.(map sum).concat in print $ format results
liefswanson/projectEuler
app/p2/q60/Main.hs
gpl-2.0
1,323
1
12
445
482
255
227
32
1
import Data.Char (chr, ord) import System.IO import Debug.Trace import System.Environment import Control.Monad data BFCommand = GoRight | GoLeft | Increment | Decrement | Print | Read | While | Wend | Loop BFSource | IncrementN Int | GoRightN Int | GoLeftN Int | SetZero deriving (Eq, Show) type BFSource = [BFCommand] mapMaybes :: (a -> Maybe b) -> [a] -> [b] mapMaybes _ [] = [] mapMaybes f (x: xs) = let rs = mapMaybes f xs in case f x of Just e -> e: rs Nothing -> rs parseBrainfuck :: String -> BFSource parseBrainfuck = mapMaybes charToBF where charToBF c = case c of '>' -> Just GoRight '<' -> Just GoLeft '+' -> Just Increment '-' -> Just Decrement '.' -> Just Print ',' -> Just Read '[' -> Just While ']' -> Just Wend _ -> Nothing outputBrainfuck :: BFSource -> String outputBrainfuck [] = [] outputBrainfuck (c: cs) = case c of GoRight -> '>': outputBrainfuck cs GoLeft -> '<': outputBrainfuck cs Increment -> '+': outputBrainfuck cs Decrement -> '-': outputBrainfuck cs Print -> '.': outputBrainfuck cs Read -> ',': outputBrainfuck cs While -> '[': outputBrainfuck cs Wend -> ']': outputBrainfuck cs IncrementN i -> show (abs i) ++ ((if i > 0 then '+' else '-'): outputBrainfuck cs) GoRightN i -> show i ++ ('>': outputBrainfuck cs) GoLeftN i -> show i ++ ('<': outputBrainfuck cs) SetZero -> '=':'0': outputBrainfuck cs Loop cs' -> ('{' : outputBrainfuck cs') ++ "}" ++ outputBrainfuck cs data Tape a = Tape [a] a [a] emptyTape :: Tape Int emptyTape = Tape zeros 0 zeros where zeros = repeat 0 moveRight :: Tape a -> Tape a moveRight (Tape ls p (r: rs)) = Tape (p: ls) r rs moveRight (Tape _ _ []) = error "Nothing on the right hand side" moveRightN :: Int -> Tape a -> Tape a moveRightN 0 t = t moveRightN i t = moveRightN (i - 1) (moveRight t) moveLeft :: Tape a -> Tape a moveLeft (Tape (l: ls) p rs) = Tape ls l (p: rs) moveLeft (Tape [] _ _) = error "Nothing on the left hand side" moveLeftN :: Int -> Tape a -> Tape a moveLeftN 0 t = t moveLeftN i t = moveLeftN (i - 1) (moveLeft t) runBrainfuck :: Bool -> BFSource -> IO () runBrainfuck debug bfs = run emptyTape (transformBrainfuck debug bfs) >> return () runBrainfuckInteract :: Bool -> BFSource -> String -> (String, Tape Int, String) runBrainfuckInteract debug bfs input = runI emptyTape (transformBrainfuck debug bfs) input transformBrainfuck :: Bool -> BFSource -> BFSource transformBrainfuck debug bfs = let tbfs = gatherLoops bfs in if debug then trace (outputBrainfuck tbfs) tbfs else tbfs gatherLoops :: BFSource -> BFSource gatherLoops [] = [] gatherLoops (c: cs) = case c of While -> let (loop, rest) = takeWhileIsSameLoop cs in Loop (gatherLoops loop): gatherLoops rest Wend -> error "Unexpected closing bracket" _ -> c: gatherLoops cs takeWhileIsSameLoop :: BFSource -> (BFSource, BFSource) takeWhileIsSameLoop cs = inner 0 cs where inner :: Int -> BFSource -> (BFSource, BFSource) inner _ [] = error "Missing closing braket" inner 0 (Wend: cs') = ([], cs') inner b (c: cs') = let { (loop, rest) = inner (case c of While -> b + 1 Wend -> b - 1 _ -> b) cs' } in (c: loop, rest) optimize :: BFSource -> BFSource optimize (Increment:Increment: cs) = optimizeHelper IncrementN Increment cs optimize (Decrement:Decrement: cs) = optimizeHelper (\i -> IncrementN (-i)) Decrement cs optimize (GoRight:GoRight: cs) = optimizeHelper GoRightN GoRight cs optimize (GoLeft:GoLeft: cs) = optimizeHelper GoLeftN GoLeft cs optimize (While:Decrement:Wend: cs) = SetZero: optimize cs optimize (c: cs) = c: optimize cs optimize [] = [] optimizeHelper :: (Int -> BFCommand) -> BFCommand -> BFSource -> BFSource optimizeHelper commandN cmd cs = commandN (2 + length (takeWhile (== cmd) cs)): optimize (dropWhile (== cmd) cs) run :: Tape Int -> BFSource -> IO (Tape Int) run t [] = return t run dataT@(Tape _ p _) (Print: rest) = putChar (chr p) >> run dataT rest run (Tape l p r) (Read: rest) = do maybeC <- catch (liftM Just getChar) (const $ return $ Nothing) run (Tape l (case maybeC of Just c -> ord c; Nothing -> p) r) rest run dataT@(Tape _ p _) source@((Loop loop): rest) | p == 0 = run dataT rest -- skip the loop | otherwise = do dataT' <- run dataT loop run dataT' source run dataT@(Tape l p r) (c: rest) = run (case c of GoRight -> moveRight dataT GoRightN i -> moveRightN i dataT GoLeft -> moveLeft dataT GoLeftN i -> moveLeftN i dataT Increment -> Tape l (p + 1) r Decrement -> Tape l (p - 1) r IncrementN i -> Tape l (p + i) r SetZero -> Tape l 0 r While -> error "While found" Wend -> error "Wend found" _ -> error "logic error in run" ) rest runI :: Tape Int -> BFSource -> String -> (String, Tape Int, String) runI t [] i = ([], t, i) runI dataT@(Tape _ p _) (Print: rest) input = let (nextOutput, nextTape, nextInput) = runI dataT rest input in (chr p: nextOutput, nextTape, nextInput) runI dataT@(Tape l _ r) (Read: rest) input = case input of [] -> runI dataT rest [] (c: cs) -> runI (Tape l (ord c) r) rest cs runI dataT@(Tape _ p _) source@((Loop loop): rest) input | p == 0 = runI dataT rest input | otherwise = let (loopOutput, loopTape, loopInput) = runI dataT loop input (nextOutput, nextTape, nextInput) = runI loopTape source loopInput in (loopOutput ++ nextOutput, nextTape, nextInput) runI dataT@(Tape l p r) (c: rest) input = runI (case c of GoRight -> moveRight dataT GoRightN i -> moveRightN i dataT GoLeft -> moveLeft dataT GoLeftN i -> moveLeftN i dataT Increment -> Tape l (p + 1) r Decrement -> Tape l (p - 1) r IncrementN i -> Tape l (p + i) r SetZero -> Tape l 0 r While -> error "While found" Wend -> error "Wend found" _ -> error "logic error in run" ) rest input getOutput :: (String -> (String, Tape a, String)) -> String -> String getOutput f i = let (o, _, _) = f i in o main :: IO () main = do hSetBuffering stdout NoBuffering args <- getArgs readFile (case args of [] -> error "Usage: bf2 <program.bf> [-O]" (filename: _) -> filename ) >>= (if "-i" `elem` args then runBFI args else runBF args) where debug args = "-d" `elem` args optimize' args = if "-O" `elem` args then optimize else id runBF args = runBrainfuck (debug args) . (optimize' args) . parseBrainfuck runBFI args source = interact $ getOutput $ (runBrainfuckInteract (debug args) . (optimize' args) . parseBrainfuck) source
dforgeas/lazyk
bf/bf.hs
gpl-2.0
6,380
26
16
1,327
2,952
1,484
1,468
163
14
module Language.Erlang.BEAM.Opcodes where opcodeInfo :: Int -> (String, Int) opcodeInfo 1 = ("label", 1) opcodeInfo 2 = ("func_info", 3) opcodeInfo 3 = ("int_code_end", 0) opcodeInfo 4 = ("call", 2) opcodeInfo 5 = ("call_last", 3) opcodeInfo 6 = ("call_only", 2) opcodeInfo 7 = ("call_ext", 2) opcodeInfo 8 = ("call_ext_last", 3) opcodeInfo 9 = ("bif0", 2) opcodeInfo 10 = ("bif1", 4) opcodeInfo 11 = ("bif2", 5) opcodeInfo 12 = ("allocate", 2) opcodeInfo 13 = ("allocate_heap", 3) opcodeInfo 14 = ("allocate_zero", 2) opcodeInfo 15 = ("allocate_heap_zero", 3) opcodeInfo 16 = ("test_heap", 2) opcodeInfo 17 = ("init", 1) opcodeInfo 18 = ("deallocate", 1) opcodeInfo 19 = ("return", 0) opcodeInfo 20 = ("send", 0) opcodeInfo 21 = ("remove_message", 0) opcodeInfo 22 = ("timeout", 0) opcodeInfo 23 = ("loop_rec", 2) opcodeInfo 24 = ("loop_rec_end", 1) opcodeInfo 25 = ("wait", 1) opcodeInfo 26 = ("wait_timeout", 2) opcodeInfo 27 = ("m_plus", 4) opcodeInfo 28 = ("m_minus", 4) opcodeInfo 29 = ("m_times", 4) opcodeInfo 30 = ("m_div", 4) opcodeInfo 31 = ("int_div", 4) opcodeInfo 32 = ("int_rem", 4) opcodeInfo 33 = ("int_band", 4) opcodeInfo 34 = ("int_bor", 4) opcodeInfo 35 = ("int_bxor", 4) opcodeInfo 36 = ("int_bsl", 4) opcodeInfo 37 = ("int_bsr", 4) opcodeInfo 38 = ("int_bnot", 3) opcodeInfo 39 = ("is_lt", 3) opcodeInfo 40 = ("is_ge", 3) opcodeInfo 41 = ("is_eq", 3) opcodeInfo 42 = ("is_ne", 3) opcodeInfo 43 = ("is_eq_exact", 3) opcodeInfo 44 = ("is_ne_exact", 3) opcodeInfo 45 = ("is_integer", 2) opcodeInfo 46 = ("is_float", 2) opcodeInfo 47 = ("is_number", 2) opcodeInfo 48 = ("is_atom", 2) opcodeInfo 49 = ("is_pid", 2) opcodeInfo 50 = ("is_reference", 2) opcodeInfo 51 = ("is_port", 2) opcodeInfo 52 = ("is_nil", 2) opcodeInfo 53 = ("is_binary", 2) opcodeInfo 54 = ("is_constant", 2) opcodeInfo 55 = ("is_list", 2) opcodeInfo 56 = ("is_nonempty_list", 2) opcodeInfo 57 = ("is_tuple", 2) opcodeInfo 58 = ("test_arity", 3) opcodeInfo 59 = ("select_val", 3) opcodeInfo 60 = ("select_tuple_arity", 3) opcodeInfo 61 = ("jump", 1) opcodeInfo 62 = ("catch", 2) opcodeInfo 63 = ("catch_end", 1) opcodeInfo 64 = ("move", 2) opcodeInfo 65 = ("get_list", 3) opcodeInfo 66 = ("get_tuple_element", 3) opcodeInfo 67 = ("set_tuple_element", 3) opcodeInfo 68 = ("put_string", 3) opcodeInfo 69 = ("put_list", 3) opcodeInfo 70 = ("put_tuple", 2) opcodeInfo 71 = ("put", 1) opcodeInfo 72 = ("badmatch", 1) opcodeInfo 73 = ("if_end", 0) opcodeInfo 74 = ("case_end", 1) opcodeInfo 75 = ("call_fun", 1) opcodeInfo 76 = ("make_fun", 3) opcodeInfo 77 = ("is_function", 2) opcodeInfo 78 = ("call_ext_only", 2) opcodeInfo 79 = ("bs_start_match", 2) opcodeInfo 80 = ("bs_get_integer", 5) opcodeInfo 81 = ("bs_get_float", 5) opcodeInfo 82 = ("bs_get_binary", 5) opcodeInfo 83 = ("bs_skip_bits", 4) opcodeInfo 84 = ("bs_test_tail", 2) opcodeInfo 85 = ("bs_save", 1) opcodeInfo 86 = ("bs_restore", 1) opcodeInfo 87 = ("bs_init", 2) opcodeInfo 88 = ("bs_final", 2) opcodeInfo 89 = ("bs_put_integer", 5) opcodeInfo 90 = ("bs_put_binary", 5) opcodeInfo 91 = ("bs_put_float", 5) opcodeInfo 92 = ("bs_put_string", 2) opcodeInfo 93 = ("bs_need_buf", 1) opcodeInfo 94 = ("fclearerror", 0) opcodeInfo 95 = ("fcheckerror", 1) opcodeInfo 96 = ("fmove", 2) opcodeInfo 97 = ("fconv", 2) opcodeInfo 98 = ("fadd", 4) opcodeInfo 99 = ("fsub", 4) opcodeInfo 100 = ("fmul", 4) opcodeInfo 101 = ("fdiv", 4) opcodeInfo 102 = ("fnegate", 3) opcodeInfo 103 = ("make_fun2", 1) opcodeInfo 104 = ("try", 2) opcodeInfo 105 = ("try_end", 1) opcodeInfo 106 = ("try_case", 1) opcodeInfo 107 = ("try_case_end", 1) opcodeInfo 108 = ("raise", 2) opcodeInfo 109 = ("bs_init2", 6) opcodeInfo 110 = ("bs_bits_to_bytes", 3) opcodeInfo 111 = ("bs_add", 5) opcodeInfo 112 = ("apply", 1) opcodeInfo 113 = ("apply_last", 2) opcodeInfo 114 = ("is_boolean", 2) opcodeInfo 115 = ("is_function2", 3) opcodeInfo 116 = ("bs_start_match2", 5) opcodeInfo 117 = ("bs_get_integer2", 7) opcodeInfo 118 = ("bs_get_float2", 7) opcodeInfo 119 = ("bs_get_binary2", 7) opcodeInfo 120 = ("bs_skip_bits2", 5) opcodeInfo 121 = ("bs_test_tail2", 3) opcodeInfo 122 = ("bs_save2", 2) opcodeInfo 123 = ("bs_restore2", 2) opcodeInfo 124 = ("gc_bif1", 5) opcodeInfo 125 = ("gc_bif2", 6) opcodeInfo 126 = ("bs_final2", 2) opcodeInfo 127 = ("bs_bits_to_bytes2", 2) opcodeInfo 128 = ("put_literal", 2) opcodeInfo 129 = ("is_bitstr", 2) opcodeInfo 130 = ("bs_context_to_binary", 1) opcodeInfo 131 = ("bs_test_unit", 3) opcodeInfo 132 = ("bs_match_string", 4) opcodeInfo 133 = ("bs_init_writable", 0) opcodeInfo 134 = ("bs_append", 8) opcodeInfo 135 = ("bs_private_append", 6) opcodeInfo 136 = ("trim", 2) opcodeInfo 137 = ("bs_init_bits", 6) opcodeInfo 138 = ("bs_get_utf8", 5) opcodeInfo 139 = ("bs_skip_utf8", 4) opcodeInfo 140 = ("bs_get_utf16", 5) opcodeInfo 141 = ("bs_skip_utf16", 4) opcodeInfo 142 = ("bs_get_utf32", 5) opcodeInfo 143 = ("bs_skip_utf32", 4) opcodeInfo 144 = ("bs_utf8_size", 3) opcodeInfo 145 = ("bs_put_utf8", 3) opcodeInfo 146 = ("bs_utf16_size", 3) opcodeInfo 147 = ("bs_put_utf16", 3) opcodeInfo 148 = ("bs_put_utf32", 3) opcodeInfo 149 = ("on_load", 0) opcodeInfo 150 = ("recv_mark", 1) opcodeInfo 151 = ("recv_set", 1) opcodeInfo 152 = ("gc_bif3", 7) opcodeInfo n = error $ "no such opcode " ++ show n maxOpcode :: Integer maxOpcode = 152
mbrock/HBEAM
src/Language/Erlang/BEAM/Opcodes.hs
gpl-3.0
5,287
0
6
789
2,180
1,246
934
157
1
{-# language StandaloneDeriving , UndecidableInstances #-} {-| Copyright : (c) Quivade, 2017 License : GPL-3 Maintainer : Jakub Kopański <[email protected]> Stability : experimental Portability : POSIX This module provides basic recursion schemes. Written for exercise, could possibly be replaced by [recursion-schemes](https://hackage.haskell.org/package/recursion-schemes). |-} module Language.FIRRTL.Recursion ( Fix (..) , unfix , ana , cata , hmap , ymap , anaM , cataM , hmapM , ymapM , Algebra , Coalgebra -- , TFix (..) ) where import Control.Monad ((<=<), liftM) newtype Fix f = Fix (f (Fix f)) deriving instance Show (f (Fix f)) => Show (Fix f) deriving instance Eq (f (Fix f)) => Eq (Fix f) unfix :: Fix f -> f (Fix f) unfix (Fix f) = f hmap :: (Functor f, Functor g) => (forall a. f a -> g a) -> Fix f -> Fix g hmap eps = ana (eps . unfix) hmapM :: (Functor f, Traversable t, Monad m) => (forall a. f a -> m (t a)) -> Fix f -> m (Fix t) hmapM eps = anaM (eps . unfix) ymap :: Functor f => (Fix f -> Fix f) -> Fix f -> Fix f ymap f = Fix . fmap f . unfix ymapM :: (Traversable f, Monad m) => (Fix f -> m (Fix f)) -> Fix f -> m (Fix f) ymapM f = liftM Fix . mapM f . unfix type Algebra f a = f a -> a type Coalgebra f a = a -> f a -- * catamorphism cata :: Functor f => Algebra f a -> Fix f -> a cata f = f . fmap (cata f) . unfix cataM :: (Traversable f, Monad m) => (f a -> m a) -> Fix f -> m a cataM f = self where self = f <=< (mapM self . unfix) -- * anamorphism ana :: Functor f => Coalgebra f a -> a -> Fix f ana psi = Fix . fmap (ana psi) . psi anaM :: (Traversable f, Monad m) => (a -> m (f a)) -> (a -> m (Fix f)) anaM psiM = self where self = (fmap Fix . mapM self) <=< psiM -- don't know why frank need this -- type TFix -- (t :: (* -> *) -> (* -> *)) -- (f :: ((* -> *) -> (* -> *)) -> * -> *) -- = Fix (t (f t))
quivade/screwdriver
src/Language/FIRRTL/Recursion.hs
gpl-3.0
1,920
0
12
490
793
410
383
-1
-1
module Server where import Control.Concurrent import Control.Concurrent.Chan import qualified Data.ByteString as BStr import System.IO import Network.Socket import Config data ProcStream = ProcStream { procThread :: ThreadId, procResult :: Chan BStr.ByteString } forkStream :: (Chan BStr.ByteString -> IO ()) -> IO ProcStream forkStream handler = do chan <- newChan pid <- forkIO (handler chan) return $ ProcStream pid chan -- a set of open connections data SocketSet = SocketSet { socketHandles :: [ProcStream] } -- socket to listen on a port openSocket :: PortNumber -> IO Socket openSocket port = do sock <- socket AF_INET Stream 0 setSocketOption sock ReuseAddr 1 bind sock (SockAddrInet port iNADDR_ANY) listen sock 5 return sock mainLoop :: (Handle -> IO ()) -> Socket -> IO () mainLoop handler sock = do putStrLn "Wait for connection..." connection <- accept sock forkIO (respond handler connection) mainLoop handler sock respond :: (Handle -> IO ()) -> (Socket, SockAddr) -> IO () respond handler (sock, _) = do hdl <- socketToHandle sock ReadWriteMode hSetBuffering hdl NoBuffering handler hdl hClose hdl respond2 :: (Socket, SockAddr) -> IO () respond2 (sock, _) = do send sock "Hello!\n" close sock -- opens port 8080 and applies handler to recieved connections acceptLoop :: (Handle -> IO ()) -> PortNumber -> IO () acceptLoop handler port = do sock <- openSocket port mainLoop handler sock
Jon0/status
src/Server.hs
gpl-3.0
1,508
0
10
326
497
244
253
43
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GADTs #-} import Control.Applicative import Control.Monad import Control.Monad.Trans (liftIO, lift) import Control.Monad.Trans.Either (EitherT(..)) import Control.Monad.Trans.Maybe import Control.Monad.Trans.Reader -- import Data.Attoparsec.Lazy import qualified Data.Aeson.Generic as G import qualified Data.ByteString.Lazy.Char8 as LB import Data.Data import Data.Either (lefts,rights) import Data.Foldable (foldrM) import Data.Maybe import qualified Data.Map as M import Data.Monoid ((<>)) import System.Environment import System.IO -- import HEP.Storage.WebDAV.CURL import HEP.Storage.WebDAV.Type -- import HEP.Storage.WebDAV.Util import HEP.Util.Either -- import HEP.Physics.Analysis.ATLAS.Common import HEP.Physics.Analysis.ATLAS.SUSY.SUSY_0L2to6JMET_8TeV import HEP.Physics.Analysis.Common.XSecNTotNum import HEP.Physics.Analysis.Common.Prospino import HEP.Util.Work -- import KFactor import Util import Debug.Trace newtype SetNum = SetNum { unSetNum :: Int } deriving (Show,Eq,Ord) -- models data QLDNeutLOSP = QLDNeutLOSP data QLDSquarkLOSP = QLDSquarkLOSP data UDDNeutLOSP = UDDNeutLOSP data UDDSquarkLOSP = UDDSquarkLOSP data Sim0 = Sim0 data Sim1q = Sim1q data Sim1g = Sim1g data Param a where QLDNeutLOSPParam :: Int -> Int -> Int -> Param QLDNeutLOSP Sim0Param :: Int -> Int -> Int -> Param Sim0 mkQLDNeut :: Int -> Int -> Int -> Param QLDNeutLOSP mkQLDNeut = QLDNeutLOSPParam mkSim0 :: Int -> Int -> Int -> Param Sim0 mkSim0 = Sim0Param data family Proc a :: * data instance Proc QLDNeutLOSP = QLDNeutLOSPProc_2SG | QLDNeutLOSPProc_SQSG | QLDNeutLOSPProc_2SQ data instance Proc Sim0 = Sim0Proc_2SG | Sim0Proc_SQSG | Sim0Proc_2SQ deriving instance Show (Proc QLDNeutLOSP) deriving instance Show (Proc Sim0) class MGluino p where mgluino :: p -> Int class MSquark p where msquark :: p -> Int class MNeut p where mneut :: p -> Int instance MGluino (Param QLDNeutLOSP) where mgluino (QLDNeutLOSPParam x _ _) = x instance MGluino (Param Sim0) where mgluino (Sim0Param x _ _) = x instance MSquark (Param QLDNeutLOSP) where msquark (QLDNeutLOSPParam _ x _) = x instance MSquark (Param Sim0) where msquark (Sim0Param _ x _) = x instance MNeut (Param QLDNeutLOSP) where mneut (QLDNeutLOSPParam _ _ x) = x instance MNeut (Param Sim0) where mneut (Sim0Param _ _ x) = x instance Show (Param QLDNeutLOSP) where show p = "(gluino=" ++ show (mgluino p) ++ ",squark=" ++ show (msquark p) ++ ",neut=" ++ show (mneut p) ++ ")" instance Show (Param Sim0) where show p = "(gluino=" ++ show (mgluino p) ++ ",squark=" ++ show (msquark p) ++ ",neut=" ++ show (mneut p) ++ ")" class ProcessName a where processName :: Proc a -> String instance ProcessName QLDNeutLOSP where processName QLDNeutLOSPProc_2SG = "2sg_2l8j2x" processName QLDNeutLOSPProc_SQSG = "sqsg_2l7j2x" processName QLDNeutLOSPProc_2SQ = "2sq_2l6j2x" instance ProcessName Sim0 where processName Sim0Proc_2SG = "2sg_4j2n" processName Sim0Proc_SQSG = "sqsg_3j2n" processName Sim0Proc_2SQ = "2sq_2j2n" data SQCDProcess = GluinoGluino | GluinoSquark | SquarkSquark class SQCDProcessable a where sqcdProcess :: Proc a -> SQCDProcess instance SQCDProcessable QLDNeutLOSP where sqcdProcess QLDNeutLOSPProc_2SG = GluinoGluino sqcdProcess QLDNeutLOSPProc_SQSG = GluinoSquark sqcdProcess QLDNeutLOSPProc_2SQ = SquarkSquark instance SQCDProcessable Sim0 where sqcdProcess Sim0Proc_2SG = GluinoGluino sqcdProcess Sim0Proc_SQSG = GluinoSquark sqcdProcess Sim0Proc_2SQ = SquarkSquark -- data Param = P_QLDNeut QLDNeutLOSPParam data ProcSet a b = ProcSet { procsetProcess :: Proc a , procsetData :: b } deriving instance (Show (Param a), Show (Proc a), Show b) => Show (ProcSet a b) deriving instance Functor (ProcSet a) data ParamSet a b = ParamSet (Param a) [ProcSet a b] deriving instance (Show (Param a), Show (Proc a), Show b) => Show (ParamSet a b) deriving instance Functor (ParamSet a) data PreResultSet = PreResult { preresultHist :: HistEType , preresultXsec :: CrossSectionAndCount , preresultKFactor :: Double } deriving (Show) data ResultSet a = Result { resultXsecNLO :: Double , resultNumEvent :: Double , resultNormHist :: a } deriving (Show) class CreateRdirBName a where createRdirBName :: (Param a, Proc a, SetNum) -> (WebDAVRemoteDir,String) instance CreateRdirBName QLDNeutLOSP where -- createRdirBName :: (Param QLDNeutLOSP, Proc QLDNeutLOSP, SetNum) -> (WebDAVRemoteDir,String) createRdirBName (param,proc,SetNum sn) = let procname = processName proc (mg,mq,mn) :: (Double,Double,Double) = ((,,) <$> (fromIntegral.mgluino) <*> (fromIntegral.msquark) <*> (fromIntegral.mneut)) param wdavrdir = WebDAVRemoteDir ("montecarlo/admproject/XQLDdegen/8TeV/neutLOSP/scan_" ++ procname) basename = "ADMXQLD111degenMG"++ show mg ++ "MQ" ++ show mq ++ "ML50000.0MN" ++ show mn ++ "_" ++ procname ++ "_LHC8ATLAS_NoMatch_NoCut_AntiKT0.4_NoTau_Set" ++ show sn in (wdavrdir,basename) instance CreateRdirBName Sim0 where -- createRdirBName :: (Param Sim0, Proc Sim0, SetNum) -> (WebDAVRemoteDir,String) createRdirBName (param,proc,SetNum sn) = let procname = processName proc (mg,mq,mn) :: (Double,Double,Double) = ((,,) <$> (fromIntegral.mgluino) <*> (fromIntegral.msquark) <*> (fromIntegral.mneut)) param wdavrdir = WebDAVRemoteDir ("montecarlo/admproject/SimplifiedSUSY/8TeV/scan_" ++ procname) basename = "SimplifiedSUSYMN" ++ show mn ++ "MG"++show mg++ "MSQ" ++ show mq ++ "_" ++ procname ++ "_LHC8ATLAS_NoMatch_NoCut_AntiKT0.4_NoTau_Set" ++ show sn in (wdavrdir,basename) getKFactor :: (SQCDProcessable a, MGluino (Param a), MSquark (Param a)) => KFactorMap -> (Param a, Proc a) -> Maybe Double getKFactor kfacmap (param,proc) = let mg = mgluino param mq = msquark param m = case sqcdProcess proc of GluinoGluino -> kFactor_2sg kfacmap GluinoSquark -> kFactor_sqsg kfacmap SquarkSquark -> kFactor_2sq kfacmap in M.lookup (mg,mq) m countFor1Set :: (CreateRdirBName a, Show (Param a) ) => (Param a, Proc a) -> SetNum -> EitherT String (ReaderT WebDAVConfig IO) () countFor1Set (param,proc) sn = do let (wdavrdir,bname) = createRdirBName (param,proc,sn) wdavcfg <- lift ask liftIO (getXSecNCount XSecLHE wdavcfg wdavrdir bname) >>= liftIO . getJSONFileAndUpload wdavcfg wdavrdir bname liftIO (atlas_8TeV_0L2to6J_bkgtest ([0],[0]) wdavcfg wdavrdir bname) return () countParamSet :: (CreateRdirBName a, Show (Param a) ) => ParamSet a [SetNum] -> EitherT String (ReaderT WebDAVConfig IO) () countParamSet (ParamSet param procsets) = do let countProcSet (ProcSet proc ns) = mapM_ (countFor1Set (param,proc)) ns mapM_ countProcSet procsets -- | checkFor1Set :: (CreateRdirBName a, Show (Param a) ) => (Param a, Proc a) -> SetNum -> EitherT String (ReaderT WebDAVConfig IO) () checkFor1Set (param,proc) sn = do let (wdavrdir,bname) = createRdirBName (param,proc,sn) zerolepfile = bname ++ "_ATLAS8TeV0L2to6JBkgTest.json" totalcountfile = bname ++ "_total_count.json" wdavcfg <- lift ask guardEitherM (show param ++ " not complete") $ (&&) <$> liftIO (doesFileExistInDAV wdavcfg wdavrdir zerolepfile) <*> liftIO (doesFileExistInDAV wdavcfg wdavrdir totalcountfile) checkParamSet :: (CreateRdirBName a, Show (Param a) ) => ParamSet a [SetNum] -> EitherT String (ReaderT WebDAVConfig IO) () checkParamSet (ParamSet param procsets) = do let checkProcSet (ProcSet proc ns) = mapM_ (checkFor1Set (param,proc)) ns mapM_ checkProcSet procsets -- | prepareFilesForSingleSet :: (CreateRdirBName a, MGluino (Param a), MSquark (Param a), SQCDProcessable a , Show (Param a) ) => KFactorMap -> (Param a, Proc a) -> SetNum -> EitherT String (ReaderT WebDAVConfig IO) PreResultSet prepareFilesForSingleSet kFacMap (param,proc) sn = do let (wdavrdir,bname) = createRdirBName (param,proc,sn) zerolepfile = bname ++ "_ATLAS8TeV0L2to6JBkgTest.json" totalcountfile = bname ++ "_total_count.json" (hist' :: [(JESParam, HistEType)]) <- downloadAndDecodeJSON wdavrdir zerolepfile let hist = (snd.head) hist' (xsec :: CrossSectionAndCount) <- downloadAndDecodeJSON wdavrdir totalcountfile (kfactor :: Double) <- (EitherT . return . maybeToEither ("no K Factor for " ++ show param) ) (getKFactor kFacMap (param,proc)) return (PreResult hist xsec kfactor) prepareFiles :: ( CreateRdirBName a, MGluino (Param a), MSquark (Param a), SQCDProcessable a , Show (Param a) ) => KFactorMap -> ParamSet a [SetNum] -> EitherT String (ReaderT WebDAVConfig IO) (ParamSet a [PreResultSet]) prepareFiles kfacmap (ParamSet param procsets) = do let mkResultProcSet (ProcSet proc ns) = do rs <- mapM (prepareFilesForSingleSet kfacmap (param,proc)) ns return (ProcSet proc rs) r_procsets <- mapM mkResultProcSet procsets return (ParamSet param r_procsets) getResultFromPreResult :: PreResultSet -> ResultSet [(EType,Double)] getResultFromPreResult PreResult {..} = let luminosity = 20300 xsecNLO = crossSectionInPb preresultXsec * preresultKFactor nev = (fromIntegral.numberOfEvent) preresultXsec weight = xsecNLO * luminosity / nev normhist = map (\(x,y) -> (x,fromIntegral y * weight)) preresultHist in Result xsecNLO nev normhist combineResultSets :: [ResultSet [(EType,Double)]] -> ResultSet (TotalSR Double) combineResultSets rs = let ws = map ((*) <$> resultXsecNLO <*> resultNumEvent) rs sumw = sum ws ws_norm = map (/ sumw) ws apply_weight w Result {..} = let hist' = map (\(x,y) -> (x,y*w)) resultNormHist in Result (resultXsecNLO*w) (resultNumEvent*w) hist' rs' = zipWith apply_weight ws_norm rs in Result (sum (map resultXsecNLO rs')) (sum (map resultNumEvent rs')) (mkTotalSR (map resultNormHist rs')) -- | getResult :: ParamSet a [PreResultSet] -> ParamSet a [ResultSet [(EType,Double)]] getResult = fmap (fmap getResultFromPreResult) -- | combineMultiSets :: ParamSet a [ResultSet [(EType,Double)]] -> ParamSet a (ResultSet (TotalSR Double)) combineMultiSets = fmap combineResultSets -- | combineMultiProcess :: ParamSet a (ResultSet (TotalSR Double)) -> (Param a, TotalSR Double) combineMultiProcess (ParamSet param rs) = (param, (sum . map (resultNormHist . procsetData)) rs) processParamSet :: (CreateRdirBName a, MGluino (Param a), MSquark (Param a), SQCDProcessable a , Show (Param a) ) => KFactorMap -> ParamSet a [SetNum] -> EitherT String (ReaderT WebDAVConfig IO) (Param a, Double) processParamSet kfacmap p = ((,) <$> fst <*> getRFromSR . snd) . combineMultiProcess . combineMultiSets . getResult <$> prepareFiles kfacmap p printFormatter :: (MGluino (Param a), MSquark (Param a)) => (Param a, Double) -> String printFormatter (p,x) = (showdbl . mgluino) p ++ ", " ++ (showdbl . msquark) p ++ ", " ++ show x where showdbl = show . fromIntegral ---------- -- TEST -- ---------- param_qldneutlosp_100 :: [ [ParamSet QLDNeutLOSP [SetNum]] ] param_qldneutlosp_100 = map (map (\x->ParamSet x procset)) qparams where qparams = [ [ mkQLDNeut g q 100 | q <- [500,600..3000] ] | g <- [500,600..3000] ] procset = [ ProcSet QLDNeutLOSPProc_2SG [SetNum 1] , ProcSet QLDNeutLOSPProc_SQSG [SetNum 1] , ProcSet QLDNeutLOSPProc_2SQ [SetNum 1] ] n_param_qldneutlosp_100 :: [ [ParamSet QLDNeutLOSP [SetNum]] ] n_param_qldneutlosp_100 = [ [ ParamSet (mkQLDNeut g q 100) y | q <- [500,600..3000], let y = if q <= 1000 then procset12 else procset1 ] | g <- [500,600..3000] ] where procset1 = [ ProcSet QLDNeutLOSPProc_2SG [SetNum 1] , ProcSet QLDNeutLOSPProc_SQSG [SetNum 1] , ProcSet QLDNeutLOSPProc_2SQ [SetNum 1] ] procset12 = [ ProcSet QLDNeutLOSPProc_2SG [SetNum 1, SetNum 2, SetNum 3] , ProcSet QLDNeutLOSPProc_SQSG [SetNum 1, SetNum 2, SetNum 3] , ProcSet QLDNeutLOSPProc_2SQ [SetNum 1, SetNum 2, SetNum 3] ] param_sim0_100 :: [ [ParamSet Sim0 [SetNum]] ] param_sim0_100 = map (map (\x->ParamSet x procset)) qparams where qparams = [ [ mkSim0 g q 100 | q <- [500,600..3000] ] | g <- [500,600..3000] ] procset = [ ProcSet Sim0Proc_2SG [SetNum 1] , ProcSet Sim0Proc_SQSG [SetNum 1] , ProcSet Sim0Proc_2SQ [SetNum 1] ] param_sim0_10 :: [ [ParamSet Sim0 [SetNum]] ] param_sim0_10 = map (map (\x->ParamSet x procset)) qparams where qparams = [ [ mkSim0 g q 10 | q <- [200,300..3000] ] | g <- [200,300..3000] ] procset = [ ProcSet Sim0Proc_2SG [SetNum 1] , ProcSet Sim0Proc_SQSG [SetNum 1] , ProcSet Sim0Proc_2SQ [SetNum 1] ] --------------- -- NEW COUNT -- --------------- nc_param_qldneutlosp_100 :: [ParamSet QLDNeutLOSP [SetNum]] nc_param_qldneutlosp_100 = map (\x->ParamSet x procset) qparams where qparams = [ mkQLDNeut g q 100 | g <- [500,600..3000], q <- [500,600..1000] ] procset = [ ProcSet QLDNeutLOSPProc_2SG [SetNum 2] , ProcSet QLDNeutLOSPProc_SQSG [SetNum 2] , ProcSet QLDNeutLOSPProc_2SQ [SetNum 2] ] nc3_param_qldneutlosp_100 :: [ParamSet QLDNeutLOSP [SetNum]] nc3_param_qldneutlosp_100 = map (\x->ParamSet x procset) qparams where qparams = [ mkQLDNeut g q 100 | g <- [500,600..3000] , q <- [500,600..1000] ] procset = [ ProcSet QLDNeutLOSPProc_2SG [SetNum 3] , ProcSet QLDNeutLOSPProc_SQSG [SetNum 3] , ProcSet QLDNeutLOSPProc_2SQ [SetNum 3] ] main' :: IO () main' = do putStrLn "prepare for KFactor map" kfacmap <- mkKFactorMap h <- openFile "xqld_neutLOSP100_sqsg_8TeV_0lep_NLO.dat" WriteMode -- openFile "sim0_neut10_sqsg_8TeV_0lep_NLO.dat" WriteMode emsg <- withDAVConfig "config1.txt" $ do let pass1glu x = do rs <- mapM (processParamSet kfacmap) x liftIO $ mapM_ (hPutStrLn h) (map printFormatter rs) mapM_ (\x->pass1glu x >> liftIO (hPutStr h "\n")) n_param_qldneutlosp_100 -- param_sim0_10 print emsg hClose h return () main'' :: IO () main'' = do emsg <- withDAVConfig "config1.txt" $ do mapM_ countParamSet nc3_param_qldneutlosp_100 print emsg main :: IO () main = do emsg <- mapM (\x->withDAVConfig "config1.txt" (checkParamSet x)) nc3_param_qldneutlosp_100 mapM_ print (lefts emsg)
wavewave/lhc-analysis-collection
analysis/ATLAS0L2to6JMET8TeV.hs
gpl-3.0
15,799
0
19
3,856
4,971
2,610
2,361
305
3
{-# 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.Dataproc.Projects.Regions.AutoscalingPolicies.TestIAMPermissions -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns permissions that a caller has on the specified resource. If the -- resource does not exist, this will return an empty set of permissions, -- not a NOT_FOUND error.Note: This operation is designed to be used for -- building permission-aware UIs and command-line tools, not for -- authorization checking. This operation may \"fail open\" without -- warning. -- -- /See:/ <https://cloud.google.com/dataproc/ Cloud Dataproc API Reference> for @dataproc.projects.regions.autoscalingPolicies.testIamPermissions@. module Network.Google.Resource.Dataproc.Projects.Regions.AutoscalingPolicies.TestIAMPermissions ( -- * REST Resource ProjectsRegionsAutoscalingPoliciesTestIAMPermissionsResource -- * Creating a Request , projectsRegionsAutoscalingPoliciesTestIAMPermissions , ProjectsRegionsAutoscalingPoliciesTestIAMPermissions -- * Request Lenses , praptipXgafv , praptipUploadProtocol , praptipAccessToken , praptipUploadType , praptipPayload , praptipResource , praptipCallback ) where import Network.Google.Dataproc.Types import Network.Google.Prelude -- | A resource alias for @dataproc.projects.regions.autoscalingPolicies.testIamPermissions@ method which the -- 'ProjectsRegionsAutoscalingPoliciesTestIAMPermissions' request conforms to. type ProjectsRegionsAutoscalingPoliciesTestIAMPermissionsResource = "v1" :> CaptureMode "resource" "testIamPermissions" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] TestIAMPermissionsRequest :> Post '[JSON] TestIAMPermissionsResponse -- | Returns permissions that a caller has on the specified resource. If the -- resource does not exist, this will return an empty set of permissions, -- not a NOT_FOUND error.Note: This operation is designed to be used for -- building permission-aware UIs and command-line tools, not for -- authorization checking. This operation may \"fail open\" without -- warning. -- -- /See:/ 'projectsRegionsAutoscalingPoliciesTestIAMPermissions' smart constructor. data ProjectsRegionsAutoscalingPoliciesTestIAMPermissions = ProjectsRegionsAutoscalingPoliciesTestIAMPermissions' { _praptipXgafv :: !(Maybe Xgafv) , _praptipUploadProtocol :: !(Maybe Text) , _praptipAccessToken :: !(Maybe Text) , _praptipUploadType :: !(Maybe Text) , _praptipPayload :: !TestIAMPermissionsRequest , _praptipResource :: !Text , _praptipCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsRegionsAutoscalingPoliciesTestIAMPermissions' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'praptipXgafv' -- -- * 'praptipUploadProtocol' -- -- * 'praptipAccessToken' -- -- * 'praptipUploadType' -- -- * 'praptipPayload' -- -- * 'praptipResource' -- -- * 'praptipCallback' projectsRegionsAutoscalingPoliciesTestIAMPermissions :: TestIAMPermissionsRequest -- ^ 'praptipPayload' -> Text -- ^ 'praptipResource' -> ProjectsRegionsAutoscalingPoliciesTestIAMPermissions projectsRegionsAutoscalingPoliciesTestIAMPermissions pPraptipPayload_ pPraptipResource_ = ProjectsRegionsAutoscalingPoliciesTestIAMPermissions' { _praptipXgafv = Nothing , _praptipUploadProtocol = Nothing , _praptipAccessToken = Nothing , _praptipUploadType = Nothing , _praptipPayload = pPraptipPayload_ , _praptipResource = pPraptipResource_ , _praptipCallback = Nothing } -- | V1 error format. praptipXgafv :: Lens' ProjectsRegionsAutoscalingPoliciesTestIAMPermissions (Maybe Xgafv) praptipXgafv = lens _praptipXgafv (\ s a -> s{_praptipXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). praptipUploadProtocol :: Lens' ProjectsRegionsAutoscalingPoliciesTestIAMPermissions (Maybe Text) praptipUploadProtocol = lens _praptipUploadProtocol (\ s a -> s{_praptipUploadProtocol = a}) -- | OAuth access token. praptipAccessToken :: Lens' ProjectsRegionsAutoscalingPoliciesTestIAMPermissions (Maybe Text) praptipAccessToken = lens _praptipAccessToken (\ s a -> s{_praptipAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). praptipUploadType :: Lens' ProjectsRegionsAutoscalingPoliciesTestIAMPermissions (Maybe Text) praptipUploadType = lens _praptipUploadType (\ s a -> s{_praptipUploadType = a}) -- | Multipart request metadata. praptipPayload :: Lens' ProjectsRegionsAutoscalingPoliciesTestIAMPermissions TestIAMPermissionsRequest praptipPayload = lens _praptipPayload (\ s a -> s{_praptipPayload = a}) -- | REQUIRED: The resource for which the policy detail is being requested. -- See the operation documentation for the appropriate value for this -- field. praptipResource :: Lens' ProjectsRegionsAutoscalingPoliciesTestIAMPermissions Text praptipResource = lens _praptipResource (\ s a -> s{_praptipResource = a}) -- | JSONP praptipCallback :: Lens' ProjectsRegionsAutoscalingPoliciesTestIAMPermissions (Maybe Text) praptipCallback = lens _praptipCallback (\ s a -> s{_praptipCallback = a}) instance GoogleRequest ProjectsRegionsAutoscalingPoliciesTestIAMPermissions where type Rs ProjectsRegionsAutoscalingPoliciesTestIAMPermissions = TestIAMPermissionsResponse type Scopes ProjectsRegionsAutoscalingPoliciesTestIAMPermissions = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsRegionsAutoscalingPoliciesTestIAMPermissions'{..} = go _praptipResource _praptipXgafv _praptipUploadProtocol _praptipAccessToken _praptipUploadType _praptipCallback (Just AltJSON) _praptipPayload dataprocService where go = buildClient (Proxy :: Proxy ProjectsRegionsAutoscalingPoliciesTestIAMPermissionsResource) mempty
brendanhay/gogol
gogol-dataproc/gen/Network/Google/Resource/Dataproc/Projects/Regions/AutoscalingPolicies/TestIAMPermissions.hs
mpl-2.0
7,208
0
16
1,436
790
466
324
125
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Content.Buyongoogleprograms.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves a status of the BoG program for your Merchant Center account. -- -- /See:/ <https://developers.google.com/shopping-content/v2/ Content API for Shopping Reference> for @content.buyongoogleprograms.get@. module Network.Google.Resource.Content.Buyongoogleprograms.Get ( -- * REST Resource BuyongoogleprogramsGetResource -- * Creating a Request , buyongoogleprogramsGet , BuyongoogleprogramsGet -- * Request Lenses , bgXgafv , bgMerchantId , bgUploadProtocol , bgRegionCode , bgAccessToken , bgUploadType , bgCallback ) where import Network.Google.Prelude import Network.Google.ShoppingContent.Types -- | A resource alias for @content.buyongoogleprograms.get@ method which the -- 'BuyongoogleprogramsGet' request conforms to. type BuyongoogleprogramsGetResource = "content" :> "v2.1" :> Capture "merchantId" (Textual Int64) :> "buyongoogleprograms" :> Capture "regionCode" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] BuyOnGoogleProgramStatus -- | Retrieves a status of the BoG program for your Merchant Center account. -- -- /See:/ 'buyongoogleprogramsGet' smart constructor. data BuyongoogleprogramsGet = BuyongoogleprogramsGet' { _bgXgafv :: !(Maybe Xgafv) , _bgMerchantId :: !(Textual Int64) , _bgUploadProtocol :: !(Maybe Text) , _bgRegionCode :: !Text , _bgAccessToken :: !(Maybe Text) , _bgUploadType :: !(Maybe Text) , _bgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BuyongoogleprogramsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bgXgafv' -- -- * 'bgMerchantId' -- -- * 'bgUploadProtocol' -- -- * 'bgRegionCode' -- -- * 'bgAccessToken' -- -- * 'bgUploadType' -- -- * 'bgCallback' buyongoogleprogramsGet :: Int64 -- ^ 'bgMerchantId' -> Text -- ^ 'bgRegionCode' -> BuyongoogleprogramsGet buyongoogleprogramsGet pBgMerchantId_ pBgRegionCode_ = BuyongoogleprogramsGet' { _bgXgafv = Nothing , _bgMerchantId = _Coerce # pBgMerchantId_ , _bgUploadProtocol = Nothing , _bgRegionCode = pBgRegionCode_ , _bgAccessToken = Nothing , _bgUploadType = Nothing , _bgCallback = Nothing } -- | V1 error format. bgXgafv :: Lens' BuyongoogleprogramsGet (Maybe Xgafv) bgXgafv = lens _bgXgafv (\ s a -> s{_bgXgafv = a}) -- | Required. The ID of the account. bgMerchantId :: Lens' BuyongoogleprogramsGet Int64 bgMerchantId = lens _bgMerchantId (\ s a -> s{_bgMerchantId = a}) . _Coerce -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). bgUploadProtocol :: Lens' BuyongoogleprogramsGet (Maybe Text) bgUploadProtocol = lens _bgUploadProtocol (\ s a -> s{_bgUploadProtocol = a}) -- | The Program region code [ISO 3166-1 -- alpha-2](https:\/\/en.wikipedia.org\/wiki\/ISO_3166-1_alpha-2). -- Currently only US is available. bgRegionCode :: Lens' BuyongoogleprogramsGet Text bgRegionCode = lens _bgRegionCode (\ s a -> s{_bgRegionCode = a}) -- | OAuth access token. bgAccessToken :: Lens' BuyongoogleprogramsGet (Maybe Text) bgAccessToken = lens _bgAccessToken (\ s a -> s{_bgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). bgUploadType :: Lens' BuyongoogleprogramsGet (Maybe Text) bgUploadType = lens _bgUploadType (\ s a -> s{_bgUploadType = a}) -- | JSONP bgCallback :: Lens' BuyongoogleprogramsGet (Maybe Text) bgCallback = lens _bgCallback (\ s a -> s{_bgCallback = a}) instance GoogleRequest BuyongoogleprogramsGet where type Rs BuyongoogleprogramsGet = BuyOnGoogleProgramStatus type Scopes BuyongoogleprogramsGet = '["https://www.googleapis.com/auth/content"] requestClient BuyongoogleprogramsGet'{..} = go _bgMerchantId _bgRegionCode _bgXgafv _bgUploadProtocol _bgAccessToken _bgUploadType _bgCallback (Just AltJSON) shoppingContentService where go = buildClient (Proxy :: Proxy BuyongoogleprogramsGetResource) mempty
brendanhay/gogol
gogol-shopping-content/gen/Network/Google/Resource/Content/Buyongoogleprograms/Get.hs
mpl-2.0
5,356
0
18
1,248
799
464
335
116
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.ServiceManagement.Services.Consumers.GetIAMPolicy -- 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) -- -- Gets the access control policy for a resource. Returns an empty policy -- if the resource exists and does not have a policy set. -- -- /See:/ <https://cloud.google.com/service-management/ Service Management API Reference> for @servicemanagement.services.consumers.getIamPolicy@. module Network.Google.Resource.ServiceManagement.Services.Consumers.GetIAMPolicy ( -- * REST Resource ServicesConsumersGetIAMPolicyResource -- * Creating a Request , servicesConsumersGetIAMPolicy , ServicesConsumersGetIAMPolicy -- * Request Lenses , scgipXgafv , scgipUploadProtocol , scgipAccessToken , scgipUploadType , scgipPayload , scgipResource , scgipCallback ) where import Network.Google.Prelude import Network.Google.ServiceManagement.Types -- | A resource alias for @servicemanagement.services.consumers.getIamPolicy@ method which the -- 'ServicesConsumersGetIAMPolicy' request conforms to. type ServicesConsumersGetIAMPolicyResource = "v1" :> CaptureMode "resource" "getIamPolicy" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] GetIAMPolicyRequest :> Post '[JSON] Policy -- | Gets the access control policy for a resource. Returns an empty policy -- if the resource exists and does not have a policy set. -- -- /See:/ 'servicesConsumersGetIAMPolicy' smart constructor. data ServicesConsumersGetIAMPolicy = ServicesConsumersGetIAMPolicy' { _scgipXgafv :: !(Maybe Xgafv) , _scgipUploadProtocol :: !(Maybe Text) , _scgipAccessToken :: !(Maybe Text) , _scgipUploadType :: !(Maybe Text) , _scgipPayload :: !GetIAMPolicyRequest , _scgipResource :: !Text , _scgipCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ServicesConsumersGetIAMPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'scgipXgafv' -- -- * 'scgipUploadProtocol' -- -- * 'scgipAccessToken' -- -- * 'scgipUploadType' -- -- * 'scgipPayload' -- -- * 'scgipResource' -- -- * 'scgipCallback' servicesConsumersGetIAMPolicy :: GetIAMPolicyRequest -- ^ 'scgipPayload' -> Text -- ^ 'scgipResource' -> ServicesConsumersGetIAMPolicy servicesConsumersGetIAMPolicy pScgipPayload_ pScgipResource_ = ServicesConsumersGetIAMPolicy' { _scgipXgafv = Nothing , _scgipUploadProtocol = Nothing , _scgipAccessToken = Nothing , _scgipUploadType = Nothing , _scgipPayload = pScgipPayload_ , _scgipResource = pScgipResource_ , _scgipCallback = Nothing } -- | V1 error format. scgipXgafv :: Lens' ServicesConsumersGetIAMPolicy (Maybe Xgafv) scgipXgafv = lens _scgipXgafv (\ s a -> s{_scgipXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). scgipUploadProtocol :: Lens' ServicesConsumersGetIAMPolicy (Maybe Text) scgipUploadProtocol = lens _scgipUploadProtocol (\ s a -> s{_scgipUploadProtocol = a}) -- | OAuth access token. scgipAccessToken :: Lens' ServicesConsumersGetIAMPolicy (Maybe Text) scgipAccessToken = lens _scgipAccessToken (\ s a -> s{_scgipAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). scgipUploadType :: Lens' ServicesConsumersGetIAMPolicy (Maybe Text) scgipUploadType = lens _scgipUploadType (\ s a -> s{_scgipUploadType = a}) -- | Multipart request metadata. scgipPayload :: Lens' ServicesConsumersGetIAMPolicy GetIAMPolicyRequest scgipPayload = lens _scgipPayload (\ s a -> s{_scgipPayload = a}) -- | REQUIRED: The resource for which the policy is being requested. See the -- operation documentation for the appropriate value for this field. scgipResource :: Lens' ServicesConsumersGetIAMPolicy Text scgipResource = lens _scgipResource (\ s a -> s{_scgipResource = a}) -- | JSONP scgipCallback :: Lens' ServicesConsumersGetIAMPolicy (Maybe Text) scgipCallback = lens _scgipCallback (\ s a -> s{_scgipCallback = a}) instance GoogleRequest ServicesConsumersGetIAMPolicy where type Rs ServicesConsumersGetIAMPolicy = Policy type Scopes ServicesConsumersGetIAMPolicy = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only", "https://www.googleapis.com/auth/service.management", "https://www.googleapis.com/auth/service.management.readonly"] requestClient ServicesConsumersGetIAMPolicy'{..} = go _scgipResource _scgipXgafv _scgipUploadProtocol _scgipAccessToken _scgipUploadType _scgipCallback (Just AltJSON) _scgipPayload serviceManagementService where go = buildClient (Proxy :: Proxy ServicesConsumersGetIAMPolicyResource) mempty
brendanhay/gogol
gogol-servicemanagement/gen/Network/Google/Resource/ServiceManagement/Services/Consumers/GetIAMPolicy.hs
mpl-2.0
6,023
0
16
1,298
789
462
327
120
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.CloudKMS.Projects.Locations.KeyRings.CryptoKeys.UpdatePrimaryVersion -- 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) -- -- Update the version of a CryptoKey that will be used in Encrypt. Returns -- an error if called on a key whose purpose is not ENCRYPT_DECRYPT. -- -- /See:/ <https://cloud.google.com/kms/ Cloud Key Management Service (KMS) API Reference> for @cloudkms.projects.locations.keyRings.cryptoKeys.updatePrimaryVersion@. module Network.Google.Resource.CloudKMS.Projects.Locations.KeyRings.CryptoKeys.UpdatePrimaryVersion ( -- * REST Resource ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersionResource -- * Creating a Request , projectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion , ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion -- * Request Lenses , plkrckupvXgafv , plkrckupvUploadProtocol , plkrckupvAccessToken , plkrckupvUploadType , plkrckupvPayload , plkrckupvName , plkrckupvCallback ) where import Network.Google.CloudKMS.Types import Network.Google.Prelude -- | A resource alias for @cloudkms.projects.locations.keyRings.cryptoKeys.updatePrimaryVersion@ method which the -- 'ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion' request conforms to. type ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersionResource = "v1" :> CaptureMode "name" "updatePrimaryVersion" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] UpdateCryptoKeyPrimaryVersionRequest :> Post '[JSON] CryptoKey -- | Update the version of a CryptoKey that will be used in Encrypt. Returns -- an error if called on a key whose purpose is not ENCRYPT_DECRYPT. -- -- /See:/ 'projectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion' smart constructor. data ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion = ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion' { _plkrckupvXgafv :: !(Maybe Xgafv) , _plkrckupvUploadProtocol :: !(Maybe Text) , _plkrckupvAccessToken :: !(Maybe Text) , _plkrckupvUploadType :: !(Maybe Text) , _plkrckupvPayload :: !UpdateCryptoKeyPrimaryVersionRequest , _plkrckupvName :: !Text , _plkrckupvCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plkrckupvXgafv' -- -- * 'plkrckupvUploadProtocol' -- -- * 'plkrckupvAccessToken' -- -- * 'plkrckupvUploadType' -- -- * 'plkrckupvPayload' -- -- * 'plkrckupvName' -- -- * 'plkrckupvCallback' projectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion :: UpdateCryptoKeyPrimaryVersionRequest -- ^ 'plkrckupvPayload' -> Text -- ^ 'plkrckupvName' -> ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion projectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion pPlkrckupvPayload_ pPlkrckupvName_ = ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion' { _plkrckupvXgafv = Nothing , _plkrckupvUploadProtocol = Nothing , _plkrckupvAccessToken = Nothing , _plkrckupvUploadType = Nothing , _plkrckupvPayload = pPlkrckupvPayload_ , _plkrckupvName = pPlkrckupvName_ , _plkrckupvCallback = Nothing } -- | V1 error format. plkrckupvXgafv :: Lens' ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion (Maybe Xgafv) plkrckupvXgafv = lens _plkrckupvXgafv (\ s a -> s{_plkrckupvXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). plkrckupvUploadProtocol :: Lens' ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion (Maybe Text) plkrckupvUploadProtocol = lens _plkrckupvUploadProtocol (\ s a -> s{_plkrckupvUploadProtocol = a}) -- | OAuth access token. plkrckupvAccessToken :: Lens' ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion (Maybe Text) plkrckupvAccessToken = lens _plkrckupvAccessToken (\ s a -> s{_plkrckupvAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). plkrckupvUploadType :: Lens' ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion (Maybe Text) plkrckupvUploadType = lens _plkrckupvUploadType (\ s a -> s{_plkrckupvUploadType = a}) -- | Multipart request metadata. plkrckupvPayload :: Lens' ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion UpdateCryptoKeyPrimaryVersionRequest plkrckupvPayload = lens _plkrckupvPayload (\ s a -> s{_plkrckupvPayload = a}) -- | Required. The resource name of the CryptoKey to update. plkrckupvName :: Lens' ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion Text plkrckupvName = lens _plkrckupvName (\ s a -> s{_plkrckupvName = a}) -- | JSONP plkrckupvCallback :: Lens' ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion (Maybe Text) plkrckupvCallback = lens _plkrckupvCallback (\ s a -> s{_plkrckupvCallback = a}) instance GoogleRequest ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion where type Rs ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion = CryptoKey type Scopes ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloudkms"] requestClient ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersion'{..} = go _plkrckupvName _plkrckupvXgafv _plkrckupvUploadProtocol _plkrckupvAccessToken _plkrckupvUploadType _plkrckupvCallback (Just AltJSON) _plkrckupvPayload cloudKMSService where go = buildClient (Proxy :: Proxy ProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersionResource) mempty
brendanhay/gogol
gogol-cloudkms/gen/Network/Google/Resource/CloudKMS/Projects/Locations/KeyRings/CryptoKeys/UpdatePrimaryVersion.hs
mpl-2.0
6,949
0
16
1,395
784
459
325
127
1
{-| Module : Codec.Picture.Png.Streaming.Info Copyright : (c) Bradley Hardy 2016 License: LGPL3 Maintainer: [email protected] Stability: experimental Portability: non-portable -} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-} module Codec.Picture.Png.Streaming.Info where import qualified Data.ByteString as B import Data.Int (Int16) import Data.Word (Word16, Word32, Word8) -- | A chunk type, represented as a 'B.ByteString' of length 4. type ChunkType = B.ByteString -- | A chunk length. type ChunkLength = Word32 -- | A colour type. type ColourType = Word8 -- | A bit depth. type BitDepth = Word8 -- | A PNG compression method (distinct from the type in 'Streaming.Zlib' of the -- same name). type CompressionMethod = Word8 -- | A PNG filtering method. type FilterMethod = Word8 -- | A PNG interlacing method. type InterlaceMethod = Word8 -- | A PNG filter type, for filter method 0. type FilterType = Word8 -- | The 4-byte identifier for a PNG header chunk. ctIHDR :: ChunkType ctIHDR = "IHDR" -- | The 4-byte identifier for a PNG data chunk. ctIDAT :: ChunkType ctIDAT = "IDAT" -- | The 4-byte identifier for a PNG ending chunk. ctIEND :: ChunkType ctIEND = "IEND" -- | The 8-byte signature for a PNG file. pngSignature :: B.ByteString pngSignature = "\137PNG\r\n\26\n" -- | The length of the header chunk. ihdrLength :: ChunkLength ihdrLength = 13 -- | From a bit depth and colour type, return the number of bits in each pixel, -- checking also that the bit depth provided is allowed for the given colour -- type. getBitsPerPixel :: BitDepth -> ColourType -> Maybe Word8 getBitsPerPixel bitDepth colourType -- greyscale | colourType == 0 && bitDepth `elem` [1, 2, 4, 8, 16] = Just bitDepth -- indexed colour | colourType == 3 && bitDepth `elem` [1, 2, 4, 8] = Just bitDepth -- truecolour | colourType == 2 && bitDepth == 8 || bitDepth == 16 = Just (bitDepth * 3) -- greyscale with alpha | colourType == 4 && bitDepth == 8 || bitDepth == 16 = Just (bitDepth * 2) -- truecolour with alpha | colourType == 6 && bitDepth == 8 || bitDepth == 16 = Just (bitDepth * 4) -- unknown | otherwise = Nothing -- | The Paeth predictor function due to Alan W. Paeth. paethPredictor :: Word8 -> Word8 -> Word8 -> Word8 paethPredictor a b c = -- It is important to convert the bytes to signed integers before doing the -- calculations, because the Paeth predictor relies on signed arithmetic. let ia = fromIntegral a :: Int16 ib = fromIntegral b ic = fromIntegral c p = ia + ib - ic pa = abs (p - ia) pb = abs (p - ib) pc = abs (p - ic) in if | pa <= pb && pa <= pc -> a | pb <= pc -> b | otherwise -> c -- | Average filter a byte. filterAverage :: Word8 -> Word8 -> Word8 -> Word8 filterAverage a b x = x - fromIntegral ((fromIntegral a + fromIntegral b) `div` (2 :: Word16)) {-# INLINE filterAverage #-} -- | Paeth filter a byte. filterPaeth :: Word8 -> Word8 -> Word8 -> Word8 -> Word8 filterPaeth a b c x = x - paethPredictor a b c {-# INLINE filterPaeth #-} -- | Reconstruct an average filtered byte. reconAverage :: Word8 -> Word8 -> Word8 -> Word8 reconAverage a b x = x + fromIntegral ((fromIntegral a + fromIntegral b) `div` (2 :: Word16)) {-# INLINE reconAverage #-} -- | Reconstruct a Paeth filtered byte. reconPaeth :: Word8 -> Word8 -> Word8 -> Word8 -> Word8 reconPaeth a b c x = x + paethPredictor a b c {-# INLINE reconPaeth #-} -- {- | -- Given a filter type, return the reconstruction function for a single byte, if -- the filter type is valid. If @f@ is a function returned by 'getReconFunction', -- the correct argument order is @f a b c x@, where those variable names match the -- ones used in the <http://www.w3.org/TR/PNG/#9Filter-types PNG specification, -- section 9.2>. -- -} -- getReconFunction :: FilterType -> Maybe (Word8 -> Word8 -> Word8 -> Word8 -> Word8) -- getReconFunction filterType = -- let ftInt = fromIntegral filterType -- funs = [ reconNone -- , reconSub -- , reconUp -- , reconAverage -- , reconPaeth ] -- in if ftInt < length funs -- then Just (funs !! ftInt) -- else Nothing
bch29/streaming-png
src/Codec/Picture/Png/Streaming/Info.hs
lgpl-3.0
4,268
0
13
974
811
460
351
56
3