code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, StandaloneDeriving,
MagicHash, UnboxedTuples #-}
{-# OPTIONS_HADDOCK hide #-}
#include "MachDeps.h"
#if SIZEOF_HSWORD == 4
#define DIGITS 9
#define BASE 1000000000
#elif SIZEOF_HSWORD == 8
#define DIGITS 18
#define BASE 1000000000000000000
#else
#error Please define DIGITS and BASE
-- DIGITS should be the largest integer such that
-- 10^DIGITS < 2^(SIZEOF_HSWORD * 8 - 1)
-- BASE should be 10^DIGITS. Note that ^ is not available yet.
#endif
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Show
-- Copyright : (c) The University of Glasgow, 1992-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- The 'Show' class, and related operations.
--
-----------------------------------------------------------------------------
module GHC.Show
(
Show(..), ShowS,
-- Instances for Show: (), [], Bool, Ordering, Int, Char
-- Show support code
shows, showChar, showString, showMultiLineString,
showParen, showList__, showSpace,
showLitChar, showLitString, protectEsc,
intToDigit, showSignedInt,
appPrec, appPrec1,
-- Character operations
asciiTab,
)
where
import GHC.Base
import GHC.List ((!!), foldr1, break)
import GHC.Num
-- | The @shows@ functions return a function that prepends the
-- output 'String' to an existing 'String'. This allows constant-time
-- concatenation of results using function composition.
type ShowS = String -> String
-- | Conversion of values to readable 'String's.
--
-- Derived instances of 'Show' have the following properties, which
-- are compatible with derived instances of 'Text.Read.Read':
--
-- * The result of 'show' is a syntactically correct Haskell
-- expression containing only constants, given the fixity
-- declarations in force at the point where the type is declared.
-- It contains only the constructor names defined in the data type,
-- parentheses, and spaces. When labelled constructor fields are
-- used, braces, commas, field names, and equal signs are also used.
--
-- * If the constructor is defined to be an infix operator, then
-- 'showsPrec' will produce infix applications of the constructor.
--
-- * the representation will be enclosed in parentheses if the
-- precedence of the top-level constructor in @x@ is less than @d@
-- (associativity is ignored). Thus, if @d@ is @0@ then the result
-- is never surrounded in parentheses; if @d@ is @11@ it is always
-- surrounded in parentheses, unless it is an atomic expression.
--
-- * If the constructor is defined using record syntax, then 'show'
-- will produce the record-syntax form, with the fields given in the
-- same order as the original declaration.
--
-- For example, given the declarations
--
-- > infixr 5 :^:
-- > data Tree a = Leaf a | Tree a :^: Tree a
--
-- the derived instance of 'Show' is equivalent to
--
-- > instance (Show a) => Show (Tree a) where
-- >
-- > showsPrec d (Leaf m) = showParen (d > app_prec) $
-- > showString "Leaf " . showsPrec (app_prec+1) m
-- > where app_prec = 10
-- >
-- > showsPrec d (u :^: v) = showParen (d > up_prec) $
-- > showsPrec (up_prec+1) u .
-- > showString " :^: " .
-- > showsPrec (up_prec+1) v
-- > where up_prec = 5
--
-- Note that right-associativity of @:^:@ is ignored. For example,
--
-- * @'show' (Leaf 1 :^: Leaf 2 :^: Leaf 3)@ produces the string
-- @\"Leaf 1 :^: (Leaf 2 :^: Leaf 3)\"@.
class Show a where
{-# MINIMAL showsPrec | show #-}
-- | Convert a value to a readable 'String'.
--
-- 'showsPrec' should satisfy the law
--
-- > showsPrec d x r ++ s == showsPrec d x (r ++ s)
--
-- Derived instances of 'Text.Read.Read' and 'Show' satisfy the following:
--
-- * @(x,\"\")@ is an element of
-- @('Text.Read.readsPrec' d ('showsPrec' d x \"\"))@.
--
-- That is, 'Text.Read.readsPrec' parses the string produced by
-- 'showsPrec', and delivers the value that 'showsPrec' started with.
showsPrec :: Int -- ^ the operator precedence of the enclosing
-- context (a number from @0@ to @11@).
-- Function application has precedence @10@.
-> a -- ^ the value to be converted to a 'String'
-> ShowS
-- | A specialised variant of 'showsPrec', using precedence context
-- zero, and returning an ordinary 'String'.
show :: a -> String
-- | The method 'showList' is provided to allow the programmer to
-- give a specialised way of showing lists of values.
-- For example, this is used by the predefined 'Show' instance of
-- the 'Char' type, where values of type 'String' should be shown
-- in double quotes, rather than between square brackets.
showList :: [a] -> ShowS
showsPrec _ x s = show x ++ s
show x = shows x ""
showList ls s = showList__ shows ls s
showList__ :: (a -> ShowS) -> [a] -> ShowS
showList__ _ [] s = "[]" ++ s
showList__ showx (x:xs) s = '[' : showx x (showl xs)
where
showl [] = ']' : s
showl (y:ys) = ',' : showx y (showl ys)
appPrec, appPrec1 :: Int
-- Use unboxed stuff because we don't have overloaded numerics yet
appPrec = I# 10# -- Precedence of application:
-- one more than the maximum operator precedence of 9
appPrec1 = I# 11# -- appPrec + 1
--------------------------------------------------------------
-- Simple Instances
--------------------------------------------------------------
deriving instance Show ()
instance Show a => Show [a] where
{-# SPECIALISE instance Show [String] #-}
{-# SPECIALISE instance Show [Char] #-}
{-# SPECIALISE instance Show [Int] #-}
showsPrec _ = showList
deriving instance Show Bool
deriving instance Show Ordering
instance Show Char where
showsPrec _ '\'' = showString "'\\''"
showsPrec _ c = showChar '\'' . showLitChar c . showChar '\''
showList cs = showChar '"' . showLitString cs . showChar '"'
instance Show Int where
showsPrec = showSignedInt
instance Show Word where
showsPrec _ (W# w) = showWord w
showWord :: Word# -> ShowS
showWord w# cs
| isTrue# (w# `ltWord#` 10##) = C# (chr# (ord# '0'# +# word2Int# w#)) : cs
| otherwise = case chr# (ord# '0'# +# word2Int# (w# `remWord#` 10##)) of
c# ->
showWord (w# `quotWord#` 10##) (C# c# : cs)
deriving instance Show a => Show (Maybe a)
instance Show TyCon where
showsPrec p (TyCon _ _ _ tc_name) = showsPrec p tc_name
instance Show TrName where
showsPrec _ (TrNameS s) = showString (unpackCString# s)
showsPrec _ (TrNameD s) = showString s
instance Show Module where
showsPrec _ (Module p m) = shows p . (':' :) . shows m
--------------------------------------------------------------
-- Show instances for the first few tuple
--------------------------------------------------------------
-- The explicit 's' parameters are important
-- Otherwise GHC thinks that "shows x" might take a lot of work to compute
-- and generates defns like
-- showsPrec _ (x,y) = let sx = shows x; sy = shows y in
-- \s -> showChar '(' (sx (showChar ',' (sy (showChar ')' s))))
instance (Show a, Show b) => Show (a,b) where
showsPrec _ (a,b) s = show_tuple [shows a, shows b] s
instance (Show a, Show b, Show c) => Show (a, b, c) where
showsPrec _ (a,b,c) s = show_tuple [shows a, shows b, shows c] s
instance (Show a, Show b, Show c, Show d) => Show (a, b, c, d) where
showsPrec _ (a,b,c,d) s = show_tuple [shows a, shows b, shows c, shows d] s
instance (Show a, Show b, Show c, Show d, Show e) => Show (a, b, c, d, e) where
showsPrec _ (a,b,c,d,e) s = show_tuple [shows a, shows b, shows c, shows d, shows e] s
instance (Show a, Show b, Show c, Show d, Show e, Show f) => Show (a,b,c,d,e,f) where
showsPrec _ (a,b,c,d,e,f) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f] s
instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g)
=> Show (a,b,c,d,e,f,g) where
showsPrec _ (a,b,c,d,e,f,g) s
= show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g] s
instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h)
=> Show (a,b,c,d,e,f,g,h) where
showsPrec _ (a,b,c,d,e,f,g,h) s
= show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h] s
instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i)
=> Show (a,b,c,d,e,f,g,h,i) where
showsPrec _ (a,b,c,d,e,f,g,h,i) s
= show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h,
shows i] s
instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j)
=> Show (a,b,c,d,e,f,g,h,i,j) where
showsPrec _ (a,b,c,d,e,f,g,h,i,j) s
= show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h,
shows i, shows j] s
instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k)
=> Show (a,b,c,d,e,f,g,h,i,j,k) where
showsPrec _ (a,b,c,d,e,f,g,h,i,j,k) s
= show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h,
shows i, shows j, shows k] s
instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k,
Show l)
=> Show (a,b,c,d,e,f,g,h,i,j,k,l) where
showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l) s
= show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h,
shows i, shows j, shows k, shows l] s
instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k,
Show l, Show m)
=> Show (a,b,c,d,e,f,g,h,i,j,k,l,m) where
showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l,m) s
= show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h,
shows i, shows j, shows k, shows l, shows m] s
instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k,
Show l, Show m, Show n)
=> Show (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where
showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l,m,n) s
= show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h,
shows i, shows j, shows k, shows l, shows m, shows n] s
instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k,
Show l, Show m, Show n, Show o)
=> Show (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where
showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) s
= show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h,
shows i, shows j, shows k, shows l, shows m, shows n, shows o] s
show_tuple :: [ShowS] -> ShowS
show_tuple ss = showChar '('
. foldr1 (\s r -> s . showChar ',' . r) ss
. showChar ')'
--------------------------------------------------------------
-- Support code for Show
--------------------------------------------------------------
-- | equivalent to 'showsPrec' with a precedence of 0.
shows :: (Show a) => a -> ShowS
shows = showsPrec 0
-- | utility function converting a 'Char' to a show function that
-- simply prepends the character unchanged.
showChar :: Char -> ShowS
showChar = (:)
-- | utility function converting a 'String' to a show function that
-- simply prepends the string unchanged.
showString :: String -> ShowS
showString = (++)
-- | utility function that surrounds the inner show function with
-- parentheses when the 'Bool' parameter is 'True'.
showParen :: Bool -> ShowS -> ShowS
showParen b p = if b then showChar '(' . p . showChar ')' else p
showSpace :: ShowS
showSpace = {-showChar ' '-} \ xs -> ' ' : xs
-- Code specific for characters
-- | Convert a character to a string using only printable characters,
-- using Haskell source-language escape conventions. For example:
--
-- > showLitChar '\n' s = "\\n" ++ s
--
showLitChar :: Char -> ShowS
showLitChar c s | c > '\DEL' = showChar '\\' (protectEsc isDec (shows (ord c)) s)
showLitChar '\DEL' s = showString "\\DEL" s
showLitChar '\\' s = showString "\\\\" s
showLitChar c s | c >= ' ' = showChar c s
showLitChar '\a' s = showString "\\a" s
showLitChar '\b' s = showString "\\b" s
showLitChar '\f' s = showString "\\f" s
showLitChar '\n' s = showString "\\n" s
showLitChar '\r' s = showString "\\r" s
showLitChar '\t' s = showString "\\t" s
showLitChar '\v' s = showString "\\v" s
showLitChar '\SO' s = protectEsc (== 'H') (showString "\\SO") s
showLitChar c s = showString ('\\' : asciiTab!!ord c) s
-- I've done manual eta-expansion here, because otherwise it's
-- impossible to stop (asciiTab!!ord) getting floated out as an MFE
showLitString :: String -> ShowS
-- | Same as 'showLitChar', but for strings
-- It converts the string to a string using Haskell escape conventions
-- for non-printable characters. Does not add double-quotes around the
-- whole thing; the caller should do that.
-- The main difference from showLitChar (apart from the fact that the
-- argument is a string not a list) is that we must escape double-quotes
showLitString [] s = s
showLitString ('"' : cs) s = showString "\\\"" (showLitString cs s)
showLitString (c : cs) s = showLitChar c (showLitString cs s)
-- Making 's' an explicit parameter makes it clear to GHC that
-- showLitString has arity 2, which avoids it allocating an extra lambda
-- The sticking point is the recursive call to (showLitString cs), which
-- it can't figure out would be ok with arity 2.
showMultiLineString :: String -> [String]
-- | Like 'showLitString' (expand escape characters using Haskell
-- escape conventions), but
-- * break the string into multiple lines
-- * wrap the entire thing in double quotes
-- Example: @showMultiLineString "hello\ngoodbye\nblah"@
-- returns @["\"hello\\n\\", "\\goodbye\n\\", "\\blah\""]@
showMultiLineString str
= go '\"' str
where
go ch s = case break (== '\n') s of
(l, _:s'@(_:_)) -> (ch : showLitString l "\\n\\") : go '\\' s'
(l, "\n") -> [ch : showLitString l "\\n\""]
(l, _) -> [ch : showLitString l "\""]
isDec :: Char -> Bool
isDec c = c >= '0' && c <= '9'
protectEsc :: (Char -> Bool) -> ShowS -> ShowS
protectEsc p f = f . cont
where cont s@(c:_) | p c = "\\&" ++ s
cont s = s
asciiTab :: [String]
asciiTab = -- Using an array drags in the array module. listArray ('\NUL', ' ')
["NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
"BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI",
"DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
"CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US",
"SP"]
-- Code specific for Ints.
-- | Convert an 'Int' in the range @0@..@15@ to the corresponding single
-- digit 'Char'. This function fails on other inputs, and generates
-- lower-case hexadecimal digits.
intToDigit :: Int -> Char
intToDigit (I# i)
| isTrue# (i >=# 0#) && isTrue# (i <=# 9#) = unsafeChr (ord '0' + I# i)
| isTrue# (i >=# 10#) && isTrue# (i <=# 15#) = unsafeChr (ord 'a' + I# i - 10)
| otherwise = error ("Char.intToDigit: not a digit " ++ show (I# i))
showSignedInt :: Int -> Int -> ShowS
showSignedInt (I# p) (I# n) r
| isTrue# (n <# 0#) && isTrue# (p ># 6#) = '(' : itos n (')' : r)
| otherwise = itos n r
itos :: Int# -> String -> String
itos n# cs
| isTrue# (n# <# 0#) =
let !(I# minInt#) = minInt in
if isTrue# (n# ==# minInt#)
-- negateInt# minInt overflows, so we can't do that:
then '-' : (case n# `quotRemInt#` 10# of
(# q, r #) ->
itos' (negateInt# q) (itos' (negateInt# r) cs))
else '-' : itos' (negateInt# n#) cs
| otherwise = itos' n# cs
where
itos' :: Int# -> String -> String
itos' x# cs'
| isTrue# (x# <# 10#) = C# (chr# (ord# '0'# +# x#)) : cs'
| otherwise = case x# `quotRemInt#` 10# of
(# q, r #) ->
case chr# (ord# '0'# +# r) of
c# ->
itos' q (C# c# : cs')
--------------------------------------------------------------
-- The Integer instances for Show
--------------------------------------------------------------
instance Show Integer where
showsPrec p n r
| p > 6 && n < 0 = '(' : integerToString n (')' : r)
-- Minor point: testing p first gives better code
-- in the not-uncommon case where the p argument
-- is a constant
| otherwise = integerToString n r
showList = showList__ (showsPrec 0)
-- Divide an conquer implementation of string conversion
integerToString :: Integer -> String -> String
integerToString n0 cs0
| n0 < 0 = '-' : integerToString' (- n0) cs0
| otherwise = integerToString' n0 cs0
where
integerToString' :: Integer -> String -> String
integerToString' n cs
| n < BASE = jhead (fromInteger n) cs
| otherwise = jprinth (jsplitf (BASE*BASE) n) cs
-- Split n into digits in base p. We first split n into digits
-- in base p*p and then split each of these digits into two.
-- Note that the first 'digit' modulo p*p may have a leading zero
-- in base p that we need to drop - this is what jsplith takes care of.
-- jsplitb the handles the remaining digits.
jsplitf :: Integer -> Integer -> [Integer]
jsplitf p n
| p > n = [n]
| otherwise = jsplith p (jsplitf (p*p) n)
jsplith :: Integer -> [Integer] -> [Integer]
jsplith p (n:ns) =
case n `quotRemInteger` p of
(# q, r #) ->
if q > 0 then q : r : jsplitb p ns
else r : jsplitb p ns
jsplith _ [] = error "jsplith: []"
jsplitb :: Integer -> [Integer] -> [Integer]
jsplitb _ [] = []
jsplitb p (n:ns) = case n `quotRemInteger` p of
(# q, r #) ->
q : r : jsplitb p ns
-- Convert a number that has been split into digits in base BASE^2
-- this includes a last splitting step and then conversion of digits
-- that all fit into a machine word.
jprinth :: [Integer] -> String -> String
jprinth (n:ns) cs =
case n `quotRemInteger` BASE of
(# q', r' #) ->
let q = fromInteger q'
r = fromInteger r'
in if q > 0 then jhead q $ jblock r $ jprintb ns cs
else jhead r $ jprintb ns cs
jprinth [] _ = error "jprinth []"
jprintb :: [Integer] -> String -> String
jprintb [] cs = cs
jprintb (n:ns) cs = case n `quotRemInteger` BASE of
(# q', r' #) ->
let q = fromInteger q'
r = fromInteger r'
in jblock q $ jblock r $ jprintb ns cs
-- Convert an integer that fits into a machine word. Again, we have two
-- functions, one that drops leading zeros (jhead) and one that doesn't
-- (jblock)
jhead :: Int -> String -> String
jhead n cs
| n < 10 = case unsafeChr (ord '0' + n) of
c@(C# _) -> c : cs
| otherwise = case unsafeChr (ord '0' + r) of
c@(C# _) -> jhead q (c : cs)
where
(q, r) = n `quotRemInt` 10
jblock = jblock' {- ' -} DIGITS
jblock' :: Int -> Int -> String -> String
jblock' d n cs
| d == 1 = case unsafeChr (ord '0' + n) of
c@(C# _) -> c : cs
| otherwise = case unsafeChr (ord '0' + r) of
c@(C# _) -> jblock' (d - 1) q (c : cs)
where
(q, r) = n `quotRemInt` 10
| AlexanderPankiv/ghc | libraries/base/GHC/Show.hs | bsd-3-clause | 20,666 | 0 | 18 | 5,875 | 5,956 | 3,221 | 2,735 | -1 | -1 |
{-# LANGUAGE CPP #-}
import System.Posix.Signals
#include "ghcconfig.h"
main = do
print (testMembers emptySignalSet)
print (testMembers emptyset)
print (testMembers fullSignalSet)
print (testMembers fullset)
fullset = internalAbort `addSignal`
realTimeAlarm `addSignal`
busError `addSignal`
processStatusChanged `addSignal`
continueProcess `addSignal`
floatingPointException `addSignal`
lostConnection `addSignal`
illegalInstruction `addSignal`
keyboardSignal `addSignal`
killProcess `addSignal`
openEndedPipe `addSignal`
keyboardTermination `addSignal`
segmentationViolation `addSignal`
softwareStop `addSignal`
softwareTermination `addSignal`
keyboardStop `addSignal`
backgroundRead `addSignal`
backgroundWrite `addSignal`
userDefinedSignal1 `addSignal`
userDefinedSignal2 `addSignal`
#if HAVE_SIGPOLL
pollableEvent `addSignal`
#endif
profilingTimerExpired `addSignal`
badSystemCall `addSignal`
breakpointTrap `addSignal`
urgentDataAvailable `addSignal`
virtualTimerExpired `addSignal`
cpuTimeLimitExceeded `addSignal`
fileSizeLimitExceeded `addSignal`
emptySignalSet
emptyset = internalAbort `deleteSignal`
realTimeAlarm `deleteSignal`
busError `deleteSignal`
processStatusChanged `deleteSignal`
continueProcess `deleteSignal`
floatingPointException `deleteSignal`
lostConnection `deleteSignal`
illegalInstruction `deleteSignal`
keyboardSignal `deleteSignal`
killProcess `deleteSignal`
openEndedPipe `deleteSignal`
keyboardTermination `deleteSignal`
segmentationViolation `deleteSignal`
softwareStop `deleteSignal`
softwareTermination `deleteSignal`
keyboardStop `deleteSignal`
backgroundRead `deleteSignal`
backgroundWrite `deleteSignal`
userDefinedSignal1 `deleteSignal`
userDefinedSignal2 `deleteSignal`
#if HAVE_SIGPOLL
pollableEvent `deleteSignal`
#endif
profilingTimerExpired `deleteSignal`
badSystemCall `deleteSignal`
breakpointTrap `deleteSignal`
urgentDataAvailable `deleteSignal`
virtualTimerExpired `deleteSignal`
cpuTimeLimitExceeded `deleteSignal`
fileSizeLimitExceeded `deleteSignal`
fullSignalSet
testMembers set = [
internalAbort `inSignalSet` set,
realTimeAlarm `inSignalSet` set,
busError `inSignalSet` set,
processStatusChanged `inSignalSet` set,
continueProcess `inSignalSet` set,
floatingPointException `inSignalSet` set,
lostConnection `inSignalSet` set,
illegalInstruction `inSignalSet` set,
keyboardSignal `inSignalSet` set,
killProcess `inSignalSet` set,
openEndedPipe `inSignalSet` set,
keyboardTermination `inSignalSet` set,
segmentationViolation `inSignalSet` set,
softwareStop `inSignalSet` set,
softwareTermination `inSignalSet` set,
keyboardStop `inSignalSet` set,
backgroundRead `inSignalSet` set,
backgroundWrite `inSignalSet` set,
userDefinedSignal1 `inSignalSet` set,
userDefinedSignal2 `inSignalSet` set,
#if HAVE_SIGPOLL
pollableEvent `inSignalSet` set,
#endif
profilingTimerExpired `inSignalSet` set,
badSystemCall `inSignalSet` set,
breakpointTrap `inSignalSet` set,
urgentDataAvailable `inSignalSet` set,
virtualTimerExpired `inSignalSet` set,
cpuTimeLimitExceeded `inSignalSet` set,
fileSizeLimitExceeded `inSignalSet` set
]
| jimenezrick/unix | tests/signals001.hs | bsd-3-clause | 3,342 | 168 | 32 | 511 | 842 | 521 | 321 | 91 | 1 |
module Data.List.Assoc
( at, match
) where
import Control.Applicative (Applicative)
import Control.Monad (guard)
import Control.Lens (LensLike')
import qualified Control.Lens as Lens
import qualified Data.List.Utils as List
at :: (Applicative f, Eq k) => k -> LensLike' f [(k, a)] a
at key = Lens.traverse . Lens.filtered ((== key) . fst) . Lens._2
match :: Eq k => (a -> b -> c) -> [(k, a)] -> [(k, b)] -> Maybe [(k, c)]
match f xs ys =
sequence =<< List.match matchItem xs ys
where
matchItem (k0, v0) (k1, v1) = do
guard $ k0 == k1
return (k0, f v0 v1)
| BrennonTWilliams/lamdu | bottlelib/Data/List/Assoc.hs | gpl-3.0 | 582 | 0 | 11 | 128 | 280 | 158 | 122 | 15 | 1 |
fac :: Integer -> Integer
fac 0 = 1
fac n = n * (fac (n - 1))
facList :: Integer -> [Integer]
facList n = map fac [0..n]
isEven :: Int -> Bool
isEven n = ((mod n 2) == 0)
retainEven :: [Int] -> [Int]
retainEven l = filter isEven l
retainEvenTuple, retainEvenTupleBetter :: [(Int, Int)] -> [Int]
retainEvenTuple l = [fst n | n <- l, isEven (snd n)]
retainEvenTupleBetter l = [x | (x,y) <- l, isEven y]
returnDiv :: Int -> [Int] -> [Int]
returnDiv 0 _ = error "div by zero"
returnDiv n l = [x | x <- l, (mod x n) == 0]
listTails :: [[Int]] -> [[Int]]
listTails l = [tail x | x <- l, (length x) > 0, (head x) > 5]
| fredmorcos/attic | snippets/haskell/scans.hs | isc | 618 | 0 | 9 | 140 | 363 | 193 | 170 | 17 | 1 |
import Test.DocTest
main = doctest ["Data/Breadcrumbs.hs"]
| Lysxia/breadcrumbs | doctest.hs | mit | 59 | 0 | 6 | 6 | 17 | 9 | 8 | 2 | 1 |
module Utils.Calendar where
import Import
import Data.Time.Clock
import Data.Time.Calendar
data Semester = Fall Integer | Spring Integer | Summer Integer deriving(Show,Eq)
date :: IO (Integer,Int,Int) -- :: (year,month,day)
date = getCurrentTime >>= return . toGregorian . utctDay
getCurrSem :: IO Semester
getCurrSem = do (year,month,_) <- date
return $ case () of
_ | 1 <= month && month <= 5 -> Spring year
| 6 <= month && month <= 8 -> Summer year
| 9 <= month && month <= 12 -> Fall year
| otherwise -> error "Nonsensical month at Utils/Calendar.hs line 13"
| dgonyeo/lambdollars | Utils/Calendar.hs | mit | 726 | 0 | 16 | 259 | 215 | 112 | 103 | 14 | 1 |
import Control.Monad.State
import Data.SyntaxIR
import Data.List.Utils (replace)
import IO
import Lisp.Runtime
import Lisp.StdLib
import System.Exit
import Text.Parser
import Text.PrettyPrint
main = repl stdLib ""
repl :: Environment -> String -> IO ()
repl state lastInput = do
putStr (if lastInput == "" then "\n λ: " else " | ")
hFlush stdout
input <- getLine
let allInput = lastInput ++ input
if allInput == "" then do
putStrLn " Ciao\n"
else if complete allInput then do
let (result, newState) = evaulate state allInput
prompt result
repl newState ""
else do
repl state (allInput ++ " ")
prompt output = do
putStrLn (" <| " ++ sanitized)
hFlush stdout
where
sanitized = replace "\n" "\n " output
-- TODO implement bracket check
complete xs = impl xs 0
where impl [] count = count == 0
impl (x:xs) count = case x of
'(' -> impl xs (count + 1)
')' -> impl xs (count - 1)
_ -> impl xs count
evaulate state input =
let repr = myParser input
myFunc = \x -> runState (evalSeq x) state
evaled = fmap myFunc repr
in case evaled of
Left err -> (show err, state)
Right (answer, newState) -> (prettyPrint answer, newState)
myParser = manyParser "repl"
| AKST/lisp.hs | src/Main.hs | mit | 1,353 | 1 | 14 | 410 | 469 | 234 | 235 | 42 | 4 |
{-# LANGUAGE CPP #-}
--------------------------------------------------
{-# LANGUAGE DataKinds, KindSignatures, GADTs, ConstraintKinds #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase, ScopedTypeVariables, TypeOperators, TupleSections #-}
--------------------------------------------------
--------------------------------------------------
{-| Type-Safe Bounded Intervals (Quick n Dirty).
See 'Between', 'clipBetween', 'isBetween', 'readBetween'.
-}
module Enumerate.Between where
--------------------------------------------------
#include <sboo-base-feature-macros.h>
--------------------------------------------------
--------------------------------------------------
import Enumerate.Types
--------------------------------------------------
-- Imports ---------------------------------------
--------------------------------------------------
import GHC.TypeLits
import Control.Exception
import Prelude (Enum(..))
import Prelude.Spiros
--------------------------------------------------
-- Imports: CPP ----------------------------------
--------------------------------------------------
-- #if HAS_BASE_Semigroup
-- import "base" Data.Semigroup (Semigroup(..))
-- #endif
--------------------------------------------------
{- $setup
@
for doctest:
@
>>> :set -XDataKinds
>>> import Data.Proxy (Proxy(..))
>>> pBetweenNegativeThreeAndPositiveSeven = Proxy :: Proxy (Between Negative 3 Positive 7)
-}
--------------------------------------------------
-- Types -----------------------------------------
--------------------------------------------------
----------------------------------------
-- data Modular i = Modular
----------------------------------------
{-
-- | kind
data Signed
= Positive
| Negative
-}
type KnownBetween (sin :: Sign) (min :: Nat) (sax :: Sign) (max :: Nat) =
( KnownInteger sin min
, KnownInteger sax max
)
type KnownInteger (sign :: Sign) (nat :: Nat) =
( KnownSign sign
, KnownNat nat
)
----------------------------------------
-- | kind
data Sign
= Positive
| Negative
-- | a hack since we can't distinguish @(Positive,0)@ from @(Negative,0)@
type Unsigned = Positive
class KnownSign (sign :: Sign) where
signVal :: proxy sign -> Integer
-- | @= +1@
instance KnownSign 'Positive where
signVal _ = 1
-- | @= -1@
instance KnownSign 'Negative where
signVal _ = -1
{-
-- | singleton
data Sign_ (sign :: Sign) where
Positive_ :: Sign_ 'Positive
Negative_ :: Sign_ 'Negative
sign2int :: Sign_ sign -> Integer
sign2int = \case
Positive_ -> -1
Negative_ -> 1
-}
{-|
>>> pNegative = Proxy :: Proxy Negative -- 'Negative'
>>> pThree = Proxy :: Proxy 3
>>> intVal pNegative pThree
-3
-}
intVal
:: forall (sign :: Sign) (nat :: Nat) proxy proxy'.
( KnownSign sign
, KnownNat nat
)
=> proxy sign
-> proxy' nat
-> Integer
intVal pSign pNat =
signVal pSign * natVal pNat
-- reifyINTEGER
-- :: forall (i :: INTEGER).
-- ( KnownINTEGER i
-- )
-- => proxy i
-- -> Integer
-- reifyINTEGER _
----------------------------------------
{-| An integer within an (inclusive) interval.
@
Between sin min sax max
@
* @sin@: sign for the minimum
* @sax@: sign for the maximum
* @min@: the minimum bound
* @max@: the maximum bound
e.g. to represent [-3..7]
@
Between 'Negative' 3 'Positive' 7
@
e.g. forall (s :: Sign) (n :: Nat)
@
Between s n s n
~
Singleton (intVal (Proxy @s) (Proxy @n))
@
-}
newtype Between
(sin :: Sign) (min :: Nat)
(sax :: Sign) (max :: Nat)
= UnsafeBetween Integer
----------------------------------------
#if HAS_EXTENSION_DerivingStrategies
deriving stock ( Show, Eq, Ord, Generic, Data )
deriving newtype ( NFData, Hashable )
#else
deriving ( Show,Eq,Ord,Generic,Data
, NFData,Hashable
)
#endif
----------------------------------------
-- | @[0 .. 7]@
type Octal = Base 8
-- | @[0 .. 9]@
type Decimal = Base 10 -- Between Unsigned 0 Positive 9
-- | @[0 .. 15]@
type Hexadecimal = Base 16
----------------------------------------
-- | @[0 .. 100]@
type Percentage = PositiveBelow 100
----------------------------------------
-- | @[-1, 0, +1]@
type PlusMinusOne = Absolute 1
----------------------------------------
-- | @[-n .. +n]@
type Absolute (n :: Nat) = Between Negative n Positive n
-- | @[0 .. (n-1)]@
type Base (n :: Nat) = PositiveBelow (n-1)
-- | @[-n .. 0]@
type NegativeBelow (n :: Nat) = Between Negative n Unsigned 0
-- | @[0 .. +n]@
type PositiveBelow (n :: Nat) = Between Unsigned 0 Positive n
----------------------------------------
-- | an out-of-bounds 'toEnum' is clipped (with 'clipBetween').
instance
( KnownBetween sin min sax max
) => Enum (Between sin min sax max) where
fromEnum (UnsafeBetween i) = fromInteger i
toEnum = clipBetween (Proxy :: Proxy (Between sin min sax max))
instance
( KnownInteger sin min
, KnownInteger sax max
) => Bounded (Between sin min sax max)
where
minBound = UnsafeBetween $
minBetween (Proxy :: Proxy (Between sin min sax max))
maxBound = UnsafeBetween $
maxBetween (Proxy :: Proxy (Between sin min sax max))
instance
( KnownInteger sin min
, KnownInteger sax max
) => Enumerable (Between sin min sax max)
where
enumerated = [minBound .. maxBound]
--instance (Integral i, KnownNat n) => Num (i `Mod` n) where
-- | all operations that overflow/underflow are clipped (with 'clipBetween').
instance
( KnownInteger sin min
, KnownInteger sax max
) => Num (Between sin min sax max)
where
fromInteger = fromInteger >>> idInteger >>> clipBetween'
where
idInteger :: Integer -> Integer
idInteger = id
UnsafeBetween i₁ + UnsafeBetween i₂ = clipBetween' $
i₁ + i₂
UnsafeBetween i₁ * UnsafeBetween i₂ = clipBetween' $
i₁ * i₂
abs (UnsafeBetween i) = clipBetween' $
abs i
signum (UnsafeBetween i) = clipBetween' $
signum i
negate (UnsafeBetween i) = clipBetween' $
negate i
-- | all operations that overflow/underflow are clipped (with 'clipBetween').
instance
( KnownInteger sin min
, KnownInteger sax max
) => Real (Between sin min sax max)
where
toRational (UnsafeBetween i) = toRational i
-- | all operations that overflow/underflow are clipped (with 'clipBetween').
instance
( KnownInteger sin min
, KnownInteger sax max
) => Integral (Between sin min sax max)
where
toInteger (UnsafeBetween i) = i
quotRem (UnsafeBetween i) (UnsafeBetween j) =
(clipBetween' *** clipBetween') (i `quotRem` j)
{-
quot :: a -> a -> a
integer division truncated toward zero
rem :: a -> a -> a
integer remainder
-}
-- | @read \@Integer@ and @'checkBetween'@
instance
( KnownBetween sin min sax max
) =>
Read (Between sin min sax max) where
readsPrec precedence string = results'
where
results' :: [((Between sin min sax max), String)]
results' = results & fmap go & catMaybes
-- fwiw, we don't short-circuit, we just keep the parses whose integers are in-bounds, but they're probably equivalent
go :: (Integer, String)
-> Maybe (Between sin min sax max, String)
go (i,s) = (,s) <$> either2maybe (isBetween' i)
results :: [(Integer, String)]
results = readsPrec precedence string
{-
*Main> :i readsPrec
class Read a where
readsPrec :: Int -> ReadS a
...
-- Defined in GHC.Read
*Main> :i ReadS
type ReadS a = String -> [(a, String)]
-- Defined in Text.ParserCombinators.ReadP
-}
--------------------------------------------------
-- Values ----------------------------------------
--------------------------------------------------
{-|
>>> minBetween pBetweenNegativeThreeAndPositiveSeven
-3
-}
minBetween
:: forall sin min sax max proxy.
( KnownInteger sin min
)
=> proxy (Between sin min sax max)
-> Integer
minBetween _proxy = intVal pSin pMin
where
pSin = Proxy :: Proxy sin
pMin = Proxy :: Proxy min
{-|
>>> maxBetween pBetweenNegativeThreeAndPositiveSeven
7
-}
maxBetween
:: forall sin min sax max proxy.
( KnownInteger sax max
)
=> proxy (Between sin min sax max)
-> Integer
maxBetween _proxy = intVal pSax pMax
where
pSax = Proxy :: Proxy sax
pMax = Proxy :: Proxy max
{-|
>>> rangeBetween pBetweenNegativeThreeAndPositiveSeven
10
-}
rangeBetween
:: forall sin min sax max proxy.
( KnownBetween sin min sax max
)
=> proxy (Between sin min sax max)
-> Natural
rangeBetween proxy
= maximum' - minimum'
& max 0
& fromInteger
where
maximum' = maxBetween proxy
minimum' = minBetween proxy
----------------------------------------
{- | the primary constructor. total via clipping (rounds up underflow and rounds down overflow).
i.e. 'id' on in-bounds inputs, and 'min' or 'max' for out-of-bounds inputs.
>>> clipBetween pBetweenNegativeThreeAndPositiveSeven (-9 :: Integer)
UnsafeBetween (-3)
>>> clipBetween pBetweenNegativeThreeAndPositiveSeven (9 :: Integer)
UnsafeBetween 7
>>> clipBetween pBetweenNegativeThreeAndPositiveSeven (0 :: Integer)
UnsafeBetween 0
-}
clipBetween
:: forall a sin min sax max proxy.
( Integral a -- Num a
, KnownBetween sin min sax max
)
=> proxy (Between sin min sax max)
-> a
-> Between sin min sax max
clipBetween proxy
= toInteger
>>> max (minBetween proxy)
>>> min (maxBetween proxy)
>>> UnsafeBetween
-- where
-- proxy = Proxy :: Proxy (Between sin min sax max)
-- | is 'clipBetween' without a proxy (it leans on inference).
clipBetween'
:: forall a sin min sax max.
( Integral a -- Num a
, KnownBetween sin min sax max
)
=> a
-> Between sin min sax max
clipBetween' = clipBetween Nothing
----------------------------------------
--TODO specializations
{-# SPECIALIZE clipBetween
:: Maybe (Between Unsigned 0 Positive 9)
-> Integer
-> (Between Unsigned 0 Positive 9)
#-}
{-# SPECIALIZE clipBetween
:: Proxy (Between Unsigned 0 Positive 9)
-> Integer
-> (Between Unsigned 0 Positive 9)
#-}
{-# SPECIALIZE clipBetween
:: Maybe (Between Unsigned 0 Positive 9)
-> Int
-> (Between Unsigned 0 Positive 9)
#-}
{-# SPECIALIZE clipBetween
:: Proxy (Between Unsigned 0 Positive 9)
-> Int
-> (Between Unsigned 0 Positive 9)
#-}
{-# SPECIALIZE clipBetween
:: Maybe (Between Unsigned 0 Positive 255)
-> Integer
-> (Between Unsigned 0 Positive 255)
#-}
{-# SPECIALIZE clipBetween
:: Proxy (Between Unsigned 0 Positive 255)
-> Integer
-> (Between Unsigned 0 Positive 255)
#-}
{-# SPECIALIZE clipBetween
:: Maybe (Between Unsigned 0 Positive 255)
-> Int
-> (Between Unsigned 0 Positive 255)
#-}
{-# SPECIALIZE clipBetween
:: Proxy (Between Unsigned 0 Positive 255)
-> Int
-> (Between Unsigned 0 Positive 255)
#-}
---------------------------------------
{- | a secondary constructor. partial (safely), via @Either 'NotBetween'@).
outputs:
* 'Right' on in-bounds inputs,
* 'NumberIsTooLow' or 'NumberIsTooHigh' for out-of-bounds inputs,
* 'IntervalIsEmpty' when the 'Between' itself is invalid.
>>> isBetween pBetweenNegativeThreeAndPositiveSeven (-9 :: Integer)
Left NumberIsTooLow
>>> isBetween pBetweenNegativeThreeAndPositiveSeven (9 :: Integer)
Left NumberIsTooHigh
>>> isBetween pBetweenNegativeThreeAndPositiveSeven (0 :: Integer)
Right (UnsafeBetween 0)
>>> import Prelude (undefined)
>>> pEmptyBetween = Proxy :: Proxy (Between Positive 1 Negative 1)
>>> isBetween pEmptyBetween undefined
Left IntervalIsEmpty
-}
isBetween
:: forall a sin min sax max proxy.
( Integral a -- Num a
, KnownBetween sin min sax max
)
=> proxy (Between sin min sax max)
-> a
-> Either NotBetween (Between sin min sax max)
isBetween proxy x =
if not (checkBetween proxy)
then Left IntervalIsEmpty
else if not (i >= minimum')
then Left NumberIsTooLow
else if not (i <= maximum')
then Left NumberIsTooHigh
else Right (UnsafeBetween i)
where
i = toInteger x
maximum' = maxBetween proxy
minimum' = minBetween proxy
-- | 'isBetween' with the type parameters being implicit (i.e. no @proxy@).
isBetween'
:: forall a sin min sax max.
( Integral a -- Num a
, KnownBetween sin min sax max
)
=> a
-> Either NotBetween (Between sin min sax max)
isBetween' = isBetween Nothing
----------------------------------------
data NotBetween
= NumberIsTooLow
| NumberIsTooHigh
| IntervalIsEmpty
deriving (Show,Read,Eq,Ord,Enum,Bounded,Generic)
instance Exception NotBetween
instance NFData NotBetween
instance Hashable NotBetween
instance Enumerable NotBetween
{- | 'False' if the interval itself ('Between') is invalid:
'minBetween' must be less than or equal to 'maxBetween'
>>> pSingularBetween = Proxy :: Proxy (Between Positive 1 Positive 1)
>>> checkBetween pSingularBetween
True
>>> checkBetween (Proxy :: Proxy (Between Positive 1 Positive 2))
True
>>> checkBetween (Proxy :: Proxy (Between Positive 1 Negative 1))
False
Can be checked at the type-level too.
-}
checkBetween
:: forall sin min sax max proxy.
( KnownBetween sin min sax max
)
=> proxy (Between sin min sax max)
-> Bool
checkBetween proxy = minimum' <= maximum'
where
minimum' = minBetween proxy
maximum' = maxBetween proxy
--NOTE uselessly uninferrable
-- -- | 'checkBetween' with the type parameters being implicit (i.e. no @proxy@).
-- checkBetween'
-- :: forall sin min sax max proxy.
-- ( KnownBetween sin min sax max
-- )
-- => Bool
-- checkBetween' = checkBetween Nothing
---------------------------------------
{-|
>>> readBetween pBetweenNegativeThreeAndPositiveSeven "11"
Left (BetweenValidationFailure NumberIsTooHigh)
>>> readBetween pBetweenNegativeThreeAndPositiveSeven "three"
Left (BetweenParsingFailure "three")
>>> readBetween pBetweenNegativeThreeAndPositiveSeven "-1"
Right (UnsafeBetween (-1))
-}
readBetween
:: forall sin min sax max proxy.
( KnownBetween sin min sax max
)
=> proxy (Between sin min sax max)
-> String
-> Either BetweenError (Between sin min sax max)
readBetween proxy s = do
i <- readInteger_BetweenError s
j <- isBetween_BetweenError i
return j
where
isBetween_BetweenError
= isBetween proxy
> first BetweenValidationFailure
readInteger_BetweenError
= readInteger
> maybe2either (BetweenParsingFailure s)
readInteger :: String -> Maybe Integer
readInteger = readMay
data BetweenError
= BetweenParsingFailure String
| BetweenValidationFailure NotBetween
deriving (Show,Read,Eq,Ord,Generic)
instance Exception BetweenError
instance NFData BetweenError
instance Hashable BetweenError
--instance Enumerable BetweenError
-- | 'readBetween' with the type parameters being implicit (i.e. no @proxy@).
readBetween'
:: forall sin min sax max.
( KnownBetween sin min sax max
)
=> String
-> Either BetweenError (Between sin min sax max)
readBetween' = readBetween Nothing
----------------------------------------
{-
data INTEGER
= Negative Nat
| Positive Nat
type family KnownINTEGER (i :: INTEGER) :: Constraint where
KnownINTEGER (Negative n) = (KnownNat n)
KnownINTEGER (Positive n) = (KnownNat n)
reifyINTEGER
:: forall (i :: INTEGER).
( KnownINTEGER i
)
=> proxy i
-> Integer
reifyINTEGER _
----------------------------------------
newtype Between (min :: INTEGER) (max :: INTEGER) = Between Integer
deriving (Show,Eq,Ord,Generic,NFData)
minBetween :: Between a => a -- Between
minBetween = -5
maxBetween :: Num a => a -- Between
maxBetween = 25
clipBetween :: Int -> Between
clipBetween = max minBetween > min maxBetween > Between
instance Enum Between where
fromEnum (Between i) = i
toEnum = clipBetween
instance Bounded Between where
minBound = minBetween
maxBound = maxBetween
instance Enumerable Between where
enumerated = [minBetween .. maxBetween]
--instance (Integral i, KnownNat n) => Num (i `Mod` n) where
instance Num Between where
fromInteger = fromInteger > clipBetween
Between i₁ + Between i₂ = clipBetween $ i₁ + i₂
Between i₁ * Between i₂ = clipBetween $ i₁ * i₂
abs (Between i) = clipBetween $ abs i
signum (Between i) = clipBetween $ signum i
negate (Between i) = clipBetween $ negate i
---------------------------------------
>>> readBetween' "11" :: Between Negative 10 Positive 10
Left (BetweenValidationFailure NumberIsTooHigh)
>>> readBetween' "eleven" :: Between Negative 10 Positive 10
Left (BetweenParsingFailure "eleven")
>>> readBetween' "-5" :: Between Negative 10 Positive 10
Right (UnsafeBetween 5)
----------------------------------------
{-|
-}
newtype Between i j a
= Between a
--minimumBetween
-- TODO @a@ is any @Ord@erable, @i@ and @j@ would require reflection
instance (KnownNat i, KnownNat j) => Bounded (Between i j) where
minBound = _
maxBound = _
-}
| sboosali/enumerate | enumerate/sources/Enumerate/Between.hs | mit | 17,336 | 14 | 11 | 3,726 | 2,422 | 1,352 | 1,070 | 259 | 4 |
module Morph where
import qualified Data.Text.Format as Lazy
import qualified Data.Text.Lazy as Lazy
import Grammar.IO.QueryStage
import Grammar.Greek.Morph.Types
import Grammar.Greek.Morph.Paradigm.Types
import Grammar.Greek.Morph.Paradigm.Maps (endingFormGroups)
import Grammar.Greek.Script.Word
showMorph :: Morph -> Lazy.Text
showMorph (Morph a b c d e f g)
= Lazy.intercalate ", "
. filter (not . Lazy.null)
$ [sh a, sh b, sh c, sh d, sh e, sh f, sh g]
where
sh Nothing = ""
sh (Just x) = Lazy.pack . show $ x
showAccent :: WordAccent -> Lazy.Text
showAccent (WordAccent av ap _ _) = Lazy.format "{} {}" (Lazy.Shown av, Lazy.Shown ap)
toTextFullParadigmForm :: ParadigmForm -> Lazy.Text
toTextFullParadigmForm (ParadigmForm k (ParadigmEnding (ParadigmExemplar et _) m acc _)) =
Lazy.format " {} -- {} -- {} -- {}" (Lazy.Shown k, Lazy.fromStrict et, showAccent acc, showMorph m)
showMorphForms :: QueryOptions -> IO ()
showMorphForms opt = showKeyValues opt (fmap (Lazy.toStrict . toTextFullParadigmForm)) endingFormGroups
| ancientlanguage/haskell-analysis | greek-morph/app/Morph.hs | mit | 1,047 | 0 | 11 | 164 | 381 | 205 | 176 | 22 | 2 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE CPP #-}
module Main
( main -- :: IO ()
) where
import Control.Monad
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import Crypto.Sign.Ed25519
import System.Environment (getArgs)
import Test.QuickCheck
import Test.QuickCheck.Property (morallyDubiousIOProperty)
import Text.Printf
--------------------------------------------------------------------------------
-- Orphans
instance Arbitrary ByteString where
arbitrary = S.pack `liftM` arbitrary
instance Arbitrary SecretKey where
arbitrary = SecretKey `liftM` arbitrary
instance Arbitrary PublicKey where
arbitrary = PublicKey `liftM` arbitrary
--------------------------------------------------------------------------------
-- Signatures
keypairProp :: ((PublicKey, SecretKey) -> Bool) -> Property
keypairProp k = morallyDubiousIOProperty $ k `liftM` createKeypair
roundtrip :: ByteString -> Property
roundtrip xs
= keypairProp $ \(pk,sk) -> verify pk (sign sk xs)
roundtrip' :: ByteString -> Property
roundtrip' xs
= keypairProp $ \(pk,sk) -> dverify pk xs (dsign sk xs)
-- Generally the signature format is '<signature><original message>'
-- and <signature> is of a fixed length (crypto_sign_BYTES), which in
-- ed25519's case is 64. @'dsign'@ drops the message appended at the
-- end, so we just make sure we have constant length signatures.
signLength :: (ByteString,ByteString) -> Property
signLength (xs,xs2)
= keypairProp $ \(_,sk) ->
let s1 = unSignature $ dsign sk xs
s2 = unSignature $ dsign sk xs2
in S.length s1 == S.length s2
-- ed25519 has a sig length of 64
signLength2 :: ByteString -> Property
signLength2 xs
= keypairProp $ \(_,sk) ->
(64 == S.length (unSignature $ dsign sk xs))
--------------------------------------------------------------------------------
-- Driver
main :: IO ()
main = do
args <- getArgs
let n = if null args then 100 else read (head args) :: Int
(results, passed) <- runTests n
printf "Passed %d tests!\n" (sum passed)
unless (and results) (fail "Not all tests passed!")
runTests :: Int -> IO ([Bool], [Int])
runTests ntests = fmap unzip . forM (tests ntests) $ \(s, a) ->
printf "%-40s: " s >> a
tests :: Int -> [(String, IO (Bool,Int))]
tests ntests =
[ ("Signature roundtrip", wrap roundtrip)
, ("Detached signature roundtrip", wrap roundtrip')
, ("Detached signature length", wrap signLength)
, ("Detached signature length (#2)", wrap signLength2)
]
where
wrap :: Testable prop => prop -> IO (Bool, Int)
wrap prop = do
r <- quickCheckWithResult stdArgs{maxSuccess=ntests} prop
case r of
Success n _ _ -> return (True, n)
GaveUp n _ _ -> return (True, n)
#if MIN_VERSION_QuickCheck(2,7,0)
Failure n _ _ _ _ _ _ _ _ _ -> return (False, n)
#elif MIN_VERSION_QuickCheck(2,6,0)
Failure n _ _ _ _ _ _ _ -> return (False, n)
#else
Failure n _ _ _ _ _ _ -> return (False, n)
#endif
_ -> return (False, 0)
| thoughtpolice/hs-ed25519 | tests/properties.hs | mit | 3,193 | 0 | 13 | 746 | 841 | 460 | 381 | 60 | 4 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
module Run where
import Control.Exception
import Control.Monad
import Development.GitRev
import System.Environment
import System.FileLock
import System.FilePath
import System.Process
import Tinc.Install
import Tinc.Facts
import Tinc.Types
import Tinc.Nix
import Tinc.RecentCheck
unsetEnvVars :: IO ()
unsetEnvVars = do
unsetEnv "CABAL_SANDBOX_CONFIG"
unsetEnv "CABAL_SANDBOX_PACKAGE_PATH"
unsetEnv "GHC_PACKAGE_PATH"
tinc :: [String] -> IO ()
tinc args = do
unsetEnvVars
facts@Facts{..} <- getExecutablePath >>= discoverFacts
case args of
[] -> do
withCacheLock factsCache $ do
installDependencies False facts
["--fast"] -> do
recent <- tincEnvCreationTime facts >>= isRecent
unless recent $ do
withCacheLock factsCache $ do
installDependencies False facts
["--dry-run"] -> withCacheLock factsCache $
installDependencies True facts
["--version"] -> putStrLn $(gitHash)
"exec" : name : rest -> callExec facts name rest
name : rest | Just plugin <- lookup name factsPlugins -> callPlugin plugin rest
_ -> throwIO (ErrorCall $ "unrecognized arguments: " ++ show args)
callExec :: Facts -> String -> [String] -> IO ()
callExec Facts{..} name args = do
pid <- if factsUseNix
then uncurry spawnProcess $ nixShell name args
else spawnProcess "cabal" ("exec" : "--" : name : args)
waitForProcess pid >>= throwIO
callPlugin :: String -> [String] -> IO ()
callPlugin name args = do
pid <- spawnProcess name args
waitForProcess pid >>= throwIO
withCacheLock :: Path CacheDir -> IO a -> IO a
withCacheLock cache action = do
putStrLn $ "Acquiring " ++ lock
withFileLock lock Exclusive $ \ _ -> action
where
lock = path cache </> "tinc.lock"
| robbinch/tinc | src/Run.hs | mit | 1,937 | 0 | 18 | 486 | 572 | 277 | 295 | 54 | 7 |
-- | This module exports the main functions of the package.
{-# LANGUAGE UnicodeSyntax #-}
module OnlineATPs
( getOnlineATPs
, getSystemATP
, onlineATPOk
, printListOnlineATPs
, getResponseSystemOnTPTP
) where
import OnlineATPs.Consult
( getOnlineATPs
, getSystemATP
, getResponseSystemOnTPTP
)
import OnlineATPs.Defaults ( defaultSystemATP )
import OnlineATPs.SystemATP
( onlineATPOk
, printListOnlineATPs
)
| jonaprieto/online-atps | src/OnlineATPs.hs | mit | 441 | 0 | 5 | 81 | 62 | 40 | 22 | 15 | 0 |
module Model where
import ClassyPrelude.Yesod
import Database.Persist.Quasi
import Models.ColumnTypes
-- You can define all of your database entities in the entities file.
-- You can find more information on persistent and how to declare entities
-- at:
-- http://www.yesodweb.com/book/persistent/
share [mkPersist sqlSettings { mpsGenerateLenses = True }, mkMigrate "migrateAll"]
$(persistFileWith lowerCaseSettings "config/models")
| darthdeus/reedink | Model.hs | mit | 440 | 0 | 9 | 58 | 61 | 35 | 26 | -1 | -1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
module Week5 where
import ExprT
import Parser
import qualified StackVM as S
import qualified Data.Map as M
eval :: ExprT -> Integer
eval (Lit x) = x
eval (Add x y) = eval x + eval y
eval (Mul x y) = eval x * eval y
evalStr = fmap eval . parseExp Lit Add Mul
class Expry a where
fromExpr :: Integer -> a
class Expr a where
lit :: Integer -> a
add :: a -> a -> a
mul :: a -> a -> a
instance Expr ExprT where
lit = Lit
add = Add
mul = Mul
instance Expr Integer where
lit = id
add x y = x + y
mul x y = x * y
instance Expr Bool where
lit = (> 0)
add = (||)
mul = (&&)
newtype MinMax = MinMax Integer deriving (Eq, Show)
newtype Mod7 = Mod7 Integer deriving (Eq, Show)
instance Expr MinMax where
lit = MinMax
add (MinMax x) (MinMax y) = MinMax $ min x y
mul (MinMax x) (MinMax y )= MinMax $ max x y
instance Expr Mod7 where
lit = Mod7
add (Mod7 x) (Mod7 y) = Mod7 $ (x + y) `mod` 7
mul (Mod7 x) (Mod7 y) = Mod7 $ (x * y) `mod` 7
instance Expr S.Program where
lit x = [S.PushI x]
add x y = x ++ y ++ [S.Add]
mul x y = x ++ y ++ [S.Mul]
compile :: String -> Maybe S.Program
compile = parseExp lit add mul
class HasVars a where
var :: String -> a
data VarExprT = VLit Integer
| VAdd VarExprT VarExprT
| VMult VarExprT VarExprT
| VVar String
deriving (Show, Eq)
instance Expr VarExprT where
lit = VLit
add = VAdd
mul = VMult
instance HasVars VarExprT where
var = VVar
instance HasVars (M.Map String Integer -> Maybe Integer) where
var = M.lookup
instance Expr (M.Map String Integer -> Maybe Integer) where
lit x = \_ -> Just x
add x y = \m -> pure (+) <*> x m <*> y m
mul x y = \m -> pure (*) <*> x m <*> y m
withVars :: [(String, Integer)]
-> (M.Map String Integer -> Maybe Integer)
-> Maybe Integer
withVars vs exp = exp $ M.fromList vs
| taylor1791/cis-194-spring | src/Week5.hs | mit | 1,943 | 0 | 10 | 540 | 873 | 460 | 413 | 68 | 1 |
module Data.SymbolTable where
-- TWO(!) solutions to the problem posted at http://lpaste.net/7204216668719939584
import Control.Monad
import Control.Monad.Trans.State -- every monad is Trans these days?
import Data.Array
import Data.Maybe
-- is that discriminatory against cis-monads?
-- or are monads by definition in motion and therefore must be trans?
-- ('bind' is, after all, a transitive verb)
import Data.BidirectionalMap (BidirectionalMap)
import qualified Data.BidirectionalMap as BDM
{-- Okay, like I said: cat, splice-n-dice, many ways. MEOW!
But I'm going with a symbol-table here where we store strings-to-enumerated
values (ints) in a bidirectional map for easy toEnum retrievals. You'll see.
Now, to get the 'next' value we use State monad. --}
data SymbolTable = SymT { table :: BidirectionalMap String Int, top :: Int }
deriving Show
-- our ground state:
empty :: SymbolTable
empty = SymT BDM.empty (negate 1) -- Haskell has to fix this, pronto!
{-- So what are we doing here?
instance Enum String where
toEnum num = undefined
fromEnum str = undefined
Choose one of them. Make strings enumerable. Output the enumeration for the
following strings:
a, b, ab, The quick, brown fox jumped over the lazy dog.
Then 'de-enumerify' those value back to strings. --}
-- Okay, toEnum/fromEnum are occurring in the context or in the domain of
-- the SymbolTable State monad. This is problematic for the raw functions,
-- so let's just lift these unit functions into the State domain
strVal :: SymbolTable -> Int -> String
strVal syms = fromJust . (`BDM.lookback` (table syms))
-- throws error if not there
-- lookback function does a bi-directional map lookup from the value to key
toEnumS :: Monad m => Int -> StateT SymbolTable m String
toEnumS idx = liftM (`strVal` idx) get
intVal :: SymbolTable -> String -> Int
intVal syms = fromJust . (`BDM.lookup` (table syms))
fromEnumS :: Monad m => String -> StateT SymbolTable m Int
fromEnumS str = get >>= \(SymT table top) ->
maybe (addSym str table (succ top)) return (BDM.lookup str table)
-- so ... the enumeration-typeclass is over State SymbolTable Int
-- adds a symbol to the symbol table if it's not there already
addSym :: Monad m => String -> BidirectionalMap String Int -> Int
-> StateT SymbolTable m Int
addSym str table n = put (SymT (BDM.insert str n table) n) >> return n
{-- So:
*Main> runState (fromEnumS "a") empty ~>
(0,SymT {table = BDMap fromList [("a",0)], top = 0})
and then ...
*Main> let status =
foldr (\str state -> runState (fromEnumS str) (snd state))
(runState (fromEnumS "a") empty)
["a", "b", "ab", "The quick, brown fox jumped over the lazy dog."] ~>
(0,SymT {table = BDMap fromList [("a",0),("ab",2),("b",3),
("The quick, brown fox jumped over the lazy dog.",1)]
top = 3})
And given that:
*Main> evalState (toEnumS 0) $ snd status ~> "a"
Strings are now enumerable. To wit:
*Main> map (\x -> evalState (toEnumS x) $ snd status) [0 .. 3] ~>
["a","The quick, brown fox jumped over the lazy dog.","ab","b"]
And strings yield enumerated values:
*Main> map (\x -> evalState (fromEnumS x) $ snd status) it ~> [0,1,2,3]
TA-DAH! --}
{-- Epilogue
This is one way to do it. Another way, if you know all your strings statically,
is to compile the strings into an algebraic type in a separate module and making
that type showable and enumerable, e.g.:
data EnumedString = S0 | S1 | S2 | S3
deriving (Eq, Ord, Enum, Bounded, Ix)
instance Show EnumedString where
show S0 = "a"
show S1 = "b"
show S2 = "ab"
show S3 = "The quick, brown fox jumped over the lazy dog."
since EnumedString is enumerable, fromEnum and toEnum work as expected, and
show gives you the string-representation you want. To wit:
*Main> S0 ~> a
*Main> S1 ~> b
*Main> S2 ~> ab
*Main> S3 ~> The quick, brown fox jumped over the lazy dog.
*Main> :t toEnum
toEnum :: Enum a => Int -> a
*Main> toEnum 3 :: EnumedString ~> The quick, brown fox jumped over the lazy dog.
*Main> fromEnum S2 ~> 2
This is using the haskell compiler to 'machine-encode' enumerated string. A wee-
bit more arcane, but automagic both in the String encoding and decoding (from/toEnum)
--}
| geophf/1HaskellADay | exercises/HAD/Data/SymbolTable.hs | mit | 4,266 | 0 | 11 | 862 | 395 | 220 | 175 | 23 | 1 |
-- It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
--
-- 9 = 7 + 2×1^2
-- 15 = 7 + 2×2^2
-- 21 = 3 + 2×3^2
-- 25 = 7 + 2×3^2
-- 27 = 19 + 2×2^2
-- 33 = 31 + 2×1^2
--
-- It turns out that the conjecture was false.
-- What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
import Utils.Primes
import Utils.List
isGoldbachNumber :: Int -> Bool
isGoldbachNumber x = do
let p = primesLessThan x
any (==x) $ [x + 2 * (y^2)| x <- p, y <- [1..54]]
calculate :: Int
calculate = do
let oddComposites = filter (\x -> isPrime(x) == False) [1,3..]
last $ takeWhileInclusive (isGoldbachNumber) oddComposites
main :: IO ()
main = print calculate | daniel-beard/projecteulerhaskell | Problems/p46.hs | mit | 791 | 0 | 15 | 184 | 185 | 101 | 84 | 12 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
module PostgREST.Workers
( connectionWorker
, reReadConfig
, listener
) where
import qualified Data.Aeson as JSON
import qualified Data.ByteString as BS
import qualified Hasql.Connection as C
import qualified Hasql.Notifications as N
import qualified Hasql.Pool as P
import qualified Hasql.Transaction.Sessions as HT
import Control.Retry (RetryStatus, capDelay, exponentialBackoff,
retrying, rsPreviousDelay)
import PostgREST.AppState (AppState)
import PostgREST.Config (AppConfig (..), readAppConfig)
import PostgREST.Config.Database (queryDbSettings, queryPgVersion)
import PostgREST.Config.PgVersion (PgVersion (..), minimumPgVersion)
import PostgREST.DbStructure (queryDbStructure)
import PostgREST.Error (PgError (PgError), checkIsFatal,
errorPayload)
import qualified PostgREST.AppState as AppState
import Protolude hiding (head, toS)
import Protolude.Conv (toS)
-- | Current database connection status data ConnectionStatus
data ConnectionStatus
= NotConnected
| Connected PgVersion
| FatalConnectionError Text
deriving (Eq)
-- | Schema cache status
data SCacheStatus
= SCLoaded
| SCOnRetry
| SCFatalFail
-- | The purpose of this worker is to obtain a healthy connection to pg and an
-- up-to-date schema cache(DbStructure). This method is meant to be called
-- multiple times by the same thread, but does nothing if the previous
-- invocation has not terminated. In all cases this method does not halt the
-- calling thread, the work is preformed in a separate thread.
--
-- Background thread that does the following :
-- 1. Tries to connect to pg server and will keep trying until success.
-- 2. Checks if the pg version is supported and if it's not it kills the main
-- program.
-- 3. Obtains the dbStructure. If this fails, it goes back to 1.
connectionWorker :: AppState -> IO ()
connectionWorker appState = do
isWorkerOn <- AppState.getIsWorkerOn appState
-- Prevents multiple workers to be running at the same time. Could happen on
-- too many SIGUSR1s.
unless isWorkerOn $ do
AppState.putIsWorkerOn appState True
void $ forkIO work
where
work = do
AppConfig{..} <- AppState.getConfig appState
AppState.logWithZTime appState "Attempting to connect to the database..."
connected <- connectionStatus appState
case connected of
FatalConnectionError reason ->
-- Fatal error when connecting
AppState.logWithZTime appState reason >> killThread (AppState.getMainThreadId appState)
NotConnected ->
-- Unreachable because connectionStatus will keep trying to connect
return ()
Connected actualPgVersion -> do
-- Procede with initialization
AppState.putPgVersion appState actualPgVersion
when configDbChannelEnabled $
AppState.signalListener appState
AppState.logWithZTime appState "Connection successful"
-- this could be fail because the connection drops, but the
-- loadSchemaCache will pick the error and retry again
when configDbConfig $ reReadConfig False appState
scStatus <- loadSchemaCache appState
case scStatus of
SCLoaded ->
-- do nothing and proceed if the load was successful
return ()
SCOnRetry ->
work
SCFatalFail ->
-- die if our schema cache query has an error
killThread $ AppState.getMainThreadId appState
AppState.putIsWorkerOn appState False
-- | Check if a connection from the pool allows access to the PostgreSQL
-- database. If not, the pool connections are released and a new connection is
-- tried. Releasing the pool is key for rapid recovery. Otherwise, the pool
-- timeout would have to be reached for new healthy connections to be acquired.
-- Which might not happen if the server is busy with requests. No idle
-- connection, no pool timeout.
--
-- The connection tries are capped, but if the connection times out no error is
-- thrown, just 'False' is returned.
connectionStatus :: AppState -> IO ConnectionStatus
connectionStatus appState =
retrying retrySettings shouldRetry $
const $ P.release pool >> getConnectionStatus
where
pool = AppState.getPool appState
retrySettings = capDelay delayMicroseconds $ exponentialBackoff backoffMicroseconds
delayMicroseconds = 32000000 -- 32 seconds
backoffMicroseconds = 1000000 -- 1 second
getConnectionStatus :: IO ConnectionStatus
getConnectionStatus = do
pgVersion <- P.use pool queryPgVersion
case pgVersion of
Left e -> do
let err = PgError False e
AppState.logWithZTime appState . toS $ errorPayload err
case checkIsFatal err of
Just reason ->
return $ FatalConnectionError reason
Nothing ->
return NotConnected
Right version ->
if version < minimumPgVersion then
return . FatalConnectionError $
"Cannot run in this PostgreSQL version, PostgREST needs at least "
<> pgvName minimumPgVersion
else
return . Connected $ version
shouldRetry :: RetryStatus -> ConnectionStatus -> IO Bool
shouldRetry rs isConnSucc = do
let
delay = fromMaybe 0 (rsPreviousDelay rs) `div` backoffMicroseconds
itShould = NotConnected == isConnSucc
when itShould . AppState.logWithZTime appState $
"Attempting to reconnect to the database in "
<> (show delay::Text)
<> " seconds..."
return itShould
-- | Load the DbStructure by using a connection from the pool.
loadSchemaCache :: AppState -> IO SCacheStatus
loadSchemaCache appState = do
AppConfig{..} <- AppState.getConfig appState
result <-
P.use (AppState.getPool appState) . HT.transaction HT.ReadCommitted HT.Read $
queryDbStructure (toList configDbSchemas) configDbExtraSearchPath configDbPreparedStatements
case result of
Left e -> do
let
err = PgError False e
putErr = AppState.logWithZTime appState . toS $ errorPayload err
case checkIsFatal err of
Just _ -> do
AppState.logWithZTime appState "A fatal error ocurred when loading the schema cache"
putErr
AppState.logWithZTime appState $
"This is probably a bug in PostgREST, please report it at "
<> "https://github.com/PostgREST/postgrest/issues"
return SCFatalFail
Nothing -> do
AppState.logWithZTime appState "An error ocurred when loading the schema cache"
putErr
return SCOnRetry
Right dbStructure -> do
AppState.putDbStructure appState dbStructure
when (isJust configDbRootSpec) $
AppState.putJsonDbS appState $ toS $ JSON.encode dbStructure
AppState.logWithZTime appState "Schema cache loaded"
return SCLoaded
-- | Starts a dedicated pg connection to LISTEN for notifications. When a
-- NOTIFY <db-channel> - with an empty payload - is done, it refills the schema
-- cache. It uses the connectionWorker in case the LISTEN connection dies.
listener :: AppState -> IO ()
listener appState = do
AppConfig{..} <- AppState.getConfig appState
let dbChannel = toS configDbChannel
-- The listener has to wait for a signal from the connectionWorker.
-- This is because when the connection to the db is lost, the listener also
-- tries to recover the connection, but not with the same pace as the connectionWorker.
-- Not waiting makes stderr quickly fill with connection retries messages from the listener.
AppState.waitListener appState
-- forkFinally allows to detect if the thread dies
void . flip forkFinally (handleFinally dbChannel) $ do
dbOrError <- C.acquire $ toS configDbUri
case dbOrError of
Right db -> do
AppState.logWithZTime appState $ "Listening for notifications on the " <> dbChannel <> " channel"
N.listen db $ N.toPgIdentifier dbChannel
N.waitForNotifications handleNotification db
_ ->
die $ "Could not listen for notifications on the " <> dbChannel <> " channel"
where
handleFinally dbChannel _ = do
-- if the thread dies, we try to recover
AppState.logWithZTime appState $ "Retrying listening for notifications on the " <> dbChannel <> " channel.."
-- assume the pool connection was also lost, call the connection worker
connectionWorker appState
-- retry the listener
listener appState
handleNotification _ msg
| BS.null msg = scLoader -- reload the schema cache
| msg == "reload schema" = scLoader -- reload the schema cache
| msg == "reload config" = reReadConfig False appState -- reload the config
| otherwise = pure () -- Do nothing if anything else than an empty message is sent
scLoader =
-- It's not necessary to check the loadSchemaCache success
-- here. If the connection drops, the thread will die and
-- proceed to recover.
void $ loadSchemaCache appState
-- | Re-reads the config plus config options from the db
reReadConfig :: Bool -> AppState -> IO ()
reReadConfig startingUp appState = do
AppConfig{..} <- AppState.getConfig appState
dbSettings <-
if configDbConfig then do
qDbSettings <- queryDbSettings $ AppState.getPool appState
case qDbSettings of
Left e -> do
AppState.logWithZTime appState $
"An error ocurred when trying to query database settings for the config parameters:\n"
<> show e
pure []
Right x -> pure x
else
pure mempty
readAppConfig dbSettings configFilePath (Just configDbUri) >>= \case
Left err ->
if startingUp then
panic err -- die on invalid config if the program is starting up
else
AppState.logWithZTime appState $ "Failed re-loading config: " <> err
Right newConf -> do
AppState.putConfig appState newConf
if startingUp then
pass
else
AppState.logWithZTime appState "Config re-loaded"
| steve-chavez/postgrest | src/PostgREST/Workers.hs | mit | 10,360 | 0 | 20 | 2,667 | 1,730 | 861 | 869 | 177 | 6 |
{-# LANGUAGE ForeignFunctionInterface #-}
module System.Say.FFI (csay, csetVolume) where
import Foreign.C
import Foreign.C.String
foreign import ccall safe "cTTS.h csay"
csay :: CString -> IO ()
foreign import ccall safe "cTTS.h csetVolume"
csetVolume :: CInt -> IO ()
| tcsavage/say | src/System/Say/FFI.hs | mit | 282 | 0 | 8 | 50 | 73 | 42 | 31 | 8 | 0 |
module Display where
import Control.Monad.Trans.Class
import Control.Monad.Trans.Reader
import Graphics.UI.GLUT
import Colors
import Drawable
import SData
type DisplayReaderCallback = ReaderT SData IO ()
display :: DisplayReaderCallback
display = do
boardVar <- asks board
lift $ do
b <- get boardVar
clearScreen
draw b 20 (Position 0 0)
flush
clearScreen :: IO ()
clearScreen = clearColor $= blackBG >> clear [ColorBuffer]
reshape :: ReshapeCallback
reshape size@(Size w_ h_) = do
let [w, h] = map fromIntegral [w_, h_]
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
ortho2D (-w / 2) (w / 2) (-h / 2) (h / 2)
postRedisplay Nothing
| mrlovre/LMTetrys | src/Display.hs | gpl-2.0 | 786 | 0 | 12 | 231 | 267 | 138 | 129 | 26 | 1 |
{- |
Module : $Header$
Description : Signature for propositional logic
Copyright : (c) Dominik Luecke, Uni Bremen 2007
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
Definition of signatures for propositional logic
-}
{-
Ref.
Till Mossakowski, Joseph Goguen, Razvan Diaconescu, Andrzej Tarlecki.
What is a Logic?.
In Jean-Yves Beziau (Ed.), Logica Universalis, pp. 113-@133. Birkhaeuser.
2005.
-}
module Temporal.Sign
(Sign (..) -- Propositional Signatures
,pretty -- pretty printing
,isLegalSignature -- is a signature ok?
,addToSig -- adds an id to the given Signature
,unite -- union of sigantures
,emptySig -- empty signature
,isSubSigOf -- is subsiganture?
,sigDiff -- Difference of Signatures
,sigUnion -- Union for Logic.Logic
) where
import qualified Data.Set as Set
import Common.Id
import Common.Result
import Common.Doc
import Common.DocUtils
-- | Datatype for propositional Signatures
-- Signatures are just sets
newtype Sign = Sign {items :: Set.Set Id} deriving (Eq, Ord, Show)
instance Pretty Sign where
pretty = printSign
-- | determines whether a signature is vaild
-- all sets are ok, so glued to true
isLegalSignature :: Sign -> Bool
isLegalSignature _ = True
-- | pretty printing for Signatures
printSign :: Sign -> Doc
printSign s =
hsep [text "prop", sepByCommas $ map pretty $ Set.toList $ items s]
-- | Adds an Id to the signature
addToSig :: Sign -> Id -> Sign
addToSig sig tok = Sign {items = Set.insert tok $ items sig}
-- | Union of signatures
unite :: Sign -> Sign -> Sign
unite sig1 sig2 = Sign {items = Set.union (items sig1) $ items sig2}
-- | The empty signature
emptySig :: Sign
emptySig = Sign {items = Set.empty}
-- | Determines if sig1 is subsignature of sig2
isSubSigOf :: Sign -> Sign -> Bool
isSubSigOf sig1 sig2 = Set.isSubsetOf (items sig1) $ items sig2
-- | difference of Signatures
sigDiff :: Sign -> Sign -> Sign
sigDiff sig1 sig2 = Sign{items = Set.difference (items sig1) $ items sig2}
-- | union of Signatures
-- or do I have to care about more things here?
sigUnion :: Sign -> Sign -> Result Sign
sigUnion s1 s2 = Result [Diag Debug "All fine sigUnion" nullRange]
$ Just $ unite s1 s2
| nevrenato/Hets_Fork | Temporal/Sign.hs | gpl-2.0 | 2,505 | 0 | 10 | 652 | 456 | 255 | 201 | 36 | 1 |
module SMCDEL.Examples.SallyAnne where
import Data.Map.Strict (fromList)
import SMCDEL.Language
import SMCDEL.Symbolic.K
import SMCDEL.Symbolic.S5 (boolBddOf)
pp, qq, tt :: Prp
pp = P 0
tt = P 1
qq = P 7 -- this number does not matter
sallyInit :: BelScene
sallyInit = (BlS [pp, tt] law obs, actual) where
law = boolBddOf $ Conj [PrpF pp, Neg (PrpF tt)]
obs = fromList [ ("Sally", totalRelBdd), ("Anne", totalRelBdd) ]
actual = [pp]
sallyPutsMarbleInBasket :: Event
sallyPutsMarbleInBasket = (Trf [] Top
(fromList [ (tt,boolBddOf Top) ])
(fromList [ (i,totalRelBdd) | i <- ["Anne","Sally"] ]), [])
sallyIntermediate1 :: BelScene
sallyIntermediate1 = sallyInit `update` sallyPutsMarbleInBasket
sallyLeaves :: Event
sallyLeaves = (Trf [] Top
(fromList [ (pp,boolBddOf Bot) ])
(fromList [ (i,totalRelBdd) | i <- ["Anne","Sally"] ]), [])
sallyIntermediate2 :: BelScene
sallyIntermediate2 = sallyIntermediate1 `update` sallyLeaves
annePutsMarbleInBox :: Event
annePutsMarbleInBox = (Trf [qq] Top
(fromList [ (tt,boolBddOf $ Conj [Neg (PrpF qq) `Impl` PrpF tt, PrpF qq `Impl` Bot]) ])
(fromList [ ("Anne", allsamebdd [qq]), ("Sally", cpBdd $ boolBddOf $ Neg (PrpF qq)) ]), [qq])
sallyIntermediate3 :: BelScene
sallyIntermediate3 = sallyIntermediate2 `update` annePutsMarbleInBox
sallyComesBack :: Event
sallyComesBack = (Trf [] Top
(fromList [ (pp,boolBddOf Top) ])
(fromList [ (i,totalRelBdd) | i <- ["Anne","Sally"] ]), [])
sallyIntermediate4 :: BelScene
sallyIntermediate4 = sallyIntermediate3 `update` sallyComesBack
sallyFinal :: BelScene
sallyFinal = sallyInit `updates`
[ sallyPutsMarbleInBasket
, sallyLeaves
, annePutsMarbleInBox
, sallyComesBack ]
sallyFinalCheck :: Bool
sallyFinalCheck = SMCDEL.Symbolic.K.evalViaBdd sallyFinal (K "Sally" (PrpF tt))
| jrclogic/SMCDEL | src/SMCDEL/Examples/SallyAnne.hs | gpl-2.0 | 1,807 | 0 | 17 | 285 | 655 | 379 | 276 | 46 | 1 |
module CompileTest where
import Test.HUnit
import Types
import Compile
------------------------------
-- Test Suite fo Compile.hs --
------------------------------
--
-- TODOs:
-- checkVars with inlineFunction and failing leftSide
compileTests = TestList [genTest simple_vars, genTest complex_vars, genTest simple_funcs]
genTest (n, f, l) = TestLabel n (TestList (map (\(a, b, c) -> (TestCase (assertEqual a b (f c)))) l))
simple_vars = ("simple variable check", checkVars, [
(
"f X -> X;",
Right [],
Function testEmptyPos (Operator testEmptyPos "f") [Variable testEmptyPos "X"] Wildcard (Variable testEmptyPos "X") []),
(
"add A B -> A + B;",
Right [],
Function testEmptyPos (Operator testEmptyPos "add") [Variable testEmptyPos "A",Variable testEmptyPos "B"] Wildcard (Application testEmptyPos (Operator testEmptyPos "+") [Variable testEmptyPos "A",Variable testEmptyPos "B"]) []),
(
"const A B -> A;",
Right [Variable testEmptyPos "B"],
Function testEmptyPos (Operator testEmptyPos "const") [Variable testEmptyPos "A",Variable testEmptyPos "B"] Wildcard (Variable testEmptyPos "A") []),
(
"map F (X:Xs) -> (F X) : (map F Xs);",
Right [],
Function testEmptyPos (Operator testEmptyPos "map") [Variable testEmptyPos "F",Application testEmptyPos (Operator testEmptyPos ":") [Variable testEmptyPos "X",Variable testEmptyPos "Xs"]] Wildcard (Application testEmptyPos (Operator testEmptyPos ":") [Application testEmptyPos (Variable testEmptyPos "F") [Variable testEmptyPos "X"],Application testEmptyPos (Operator testEmptyPos "map") [Variable testEmptyPos "F",Variable testEmptyPos "Xs"]]) []),
(
"f A A -> A;",
Right [],
Function testEmptyPos (Operator testEmptyPos "f") [Variable testEmptyPos "A",Variable testEmptyPos "A"] Wildcard (Variable testEmptyPos "A") []),
(
"fail A -> A + B;",
Left [CompileError "Variable unbound" testEmptyPos ""],
Function testEmptyPos (Operator testEmptyPos "fail") [Variable testEmptyPos "A"] Wildcard (Application testEmptyPos (Operator testEmptyPos "+") [Variable testEmptyPos "A",Variable testEmptyPos "B"]) [])
])
complex_vars = ("complex variable checks", checkVars, [
(
"f X -> X + y where y -> X + 2;",
Right [],
Function testEmptyPos (Operator testEmptyPos "f") [Variable testEmptyPos "X"] Wildcard (Application testEmptyPos (Operator testEmptyPos "+") [Variable testEmptyPos "X",Operator testEmptyPos "y"]) [Function testEmptyPos (Operator testEmptyPos "y") [] Wildcard (Application testEmptyPos (Operator testEmptyPos "+") [Variable testEmptyPos "X",Datatype testEmptyPos (Number 2)]) []]),
(
"f X -> X + y where y W -> X + 2;",
Right [Variable testEmptyPos "W"],
Function testEmptyPos (Operator testEmptyPos "f") [Variable testEmptyPos "X"] Wildcard (Application testEmptyPos (Operator testEmptyPos "+") [Variable testEmptyPos "X",Operator testEmptyPos "y"]) [Function testEmptyPos (Operator testEmptyPos "y") [Variable testEmptyPos "W"] Wildcard (Application testEmptyPos (Operator testEmptyPos "+") [Variable testEmptyPos "X",Datatype testEmptyPos (Number 2)]) []]),
(
"f X -> X + y where y W -> W + 2;",
Right [],
Function testEmptyPos (Operator testEmptyPos "f") [Variable testEmptyPos "X"] Wildcard (Application testEmptyPos (Operator testEmptyPos "+") [Variable testEmptyPos "X",Operator testEmptyPos "y"]) [Function testEmptyPos (Operator testEmptyPos "y") [Variable testEmptyPos "W"] Wildcard (Application testEmptyPos (Operator testEmptyPos "+") [Variable testEmptyPos "W",Datatype testEmptyPos (Number 2)]) []]),
(
"fail X -> X + y where y -> W + 2;",
Left [CompileError "Variable unbound" testEmptyPos ""],
Function testEmptyPos (Operator testEmptyPos "fail") [Variable testEmptyPos "X"] Wildcard (Application testEmptyPos (Operator testEmptyPos "+") [Variable testEmptyPos "X",Operator testEmptyPos "y"]) [Function testEmptyPos (Operator testEmptyPos "y") [] Wildcard (Application testEmptyPos (Operator testEmptyPos "+") [Variable testEmptyPos "W",Datatype testEmptyPos (Number 2)]) []]),
(
"f X Y -> a + b where (a -> X * 2; b -> Y *3;)",
Right [],
Function testEmptyPos (Operator testEmptyPos "f") [Variable testEmptyPos "X",Variable testEmptyPos "Y"] Wildcard (Application testEmptyPos (Operator testEmptyPos "+") [Operator testEmptyPos "a",Operator testEmptyPos "b"]) [Function testEmptyPos (Operator testEmptyPos "a") [] Wildcard (Application testEmptyPos (Operator testEmptyPos "*") [Variable testEmptyPos "X",Datatype testEmptyPos (Number 2)]) [],Function testEmptyPos (Operator testEmptyPos "b") [] Wildcard (Application testEmptyPos (Operator testEmptyPos "*") [Variable testEmptyPos "Y",Datatype testEmptyPos (Number 3)]) []]),
(
"F . G -> (\\Y -> F (G Y));",
Right [],
Function testEmptyPos (Operator testEmptyPos ".") [Variable testEmptyPos "F",Variable testEmptyPos "G"] Wildcard (Datatype testEmptyPos (Lambda [Variable testEmptyPos "Y"] (Application testEmptyPos (Variable testEmptyPos "F") [Application testEmptyPos (Variable testEmptyPos "G") [Variable testEmptyPos "Y"]]))) []),
(
"F . G -> (\\Y,X -> F (G Y));",
Right [Variable testEmptyPos "X"],
Function testEmptyPos (Operator testEmptyPos ".") [Variable testEmptyPos "F",Variable testEmptyPos "G"] Wildcard (Datatype testEmptyPos (Lambda [Variable testEmptyPos "Y", Variable testEmptyPos "X"] (Application testEmptyPos (Variable testEmptyPos "F") [Application testEmptyPos (Variable testEmptyPos "G") [Variable testEmptyPos "Y"]]))) []),
(
"fail X Y -> a + b where (a -> X * 2; b Y -> Y *3;)",
Left [CompileError "Conflicting Definitions" testEmptyPos ""],
Function testEmptyPos (Operator testEmptyPos "f") [Variable testEmptyPos "X",Variable testEmptyPos "Y"] Wildcard (Application testEmptyPos (Operator testEmptyPos "+") [Operator testEmptyPos "a",Operator testEmptyPos "b"]) [Function testEmptyPos (Operator testEmptyPos "a") [] Wildcard (Application testEmptyPos (Operator testEmptyPos "*") [Variable testEmptyPos "X",Datatype testEmptyPos (Number 2)]) [],Function testEmptyPos (Operator testEmptyPos "b") [Variable testEmptyPos "Y"] Wildcard (Application testEmptyPos (Operator testEmptyPos "*") [Variable testEmptyPos "Y",Datatype testEmptyPos (Number 3)]) []])
])
simple_funcs = ("simple functions check", checkFuncs, [
(
"f X -> X;",
Right [Operator testEmptyPos "f"],
[Function testEmptyPos (Operator testEmptyPos "f") [Variable testEmptyPos "X"] Wildcard (Variable testEmptyPos "X") []]),
(
"add A B -> A; alias A B -> add A B;",
Right [Operator testEmptyPos "alias"],
[Function testEmptyPos (Operator testEmptyPos "add") [Variable testEmptyPos "A",Variable testEmptyPos "B"] Wildcard (Variable testEmptyPos "A") [],
Function testEmptyPos (Operator testEmptyPos "alias") [Variable testEmptyPos "A",Variable testEmptyPos "B"] Wildcard (Application testEmptyPos (Operator testEmptyPos "add") [Variable testEmptyPos "A",Variable testEmptyPos "B"]) []])
])
----------------------------------
-- Tests for internal functions --
----------------------------------
| Jem777/deepthought | test/CompileTest.hs | gpl-3.0 | 7,378 | 0 | 18 | 1,313 | 2,253 | 1,160 | 1,093 | 74 | 1 |
module Inkvizitor.UI.Debtor
( showDebtorForm
)
where
import Control.Applicative
import Data.Bits
import Graphics.UI.WX
import Graphics.UI.WXCore
import Inkvizitor.Debtor
import Inkvizitor.UI.Gui
showDebtorForm :: Gui -> Debtor -> (Debtor -> IO ()) -> IO ()
showDebtorForm g debtor onResult = do
f <- frame [text := "Edit debtor"]
p <- panel f []
ok <- button p [text := "Ok"]
cancel <- button p [text := "Cancel"]
nameInput <- textEntry p [text := getName debtor]
phoneInput <- textEntry p [text := getPhoneNum debtor]
exNumInput <- textEntry p [text := getExecutionNum debtor]
amountInput <- spinCtrl p 0 maxBound [selection := getAmount debtor]
exTimeInput <- textEntry p [text := getExecutionTime debtor]
commentInput <- textCtrl p [text := getComment debtor]
addrList <- singleListBox p
[ style := wxLB_NEEDED_SB
, items := getAddresses debtor
]
addrAdd <- button p [text := "Add", tooltip := "Adds a new addres"]
addrRemove <- button p [text := "Remove", tooltip := "Removes selected address"]
addrText <- textCtrl p [enabled := False]
addrSet <- button p [text := "Set", tooltip := "Sets the address", enabled := False]
set addrAdd [on command := do
itemAppend addrList "New address..."
]
set addrRemove [on command := do
id <- get addrList selection
if id /= (-1)
then itemDelete addrList id
else return ()
]
set addrList [on select := do
id <- get addrList selection
if id /= (-1)
then do
address <- get addrList (item id)
set addrText [text := address , enabled := True]
set addrSet [enabled := True]
else do
set addrText [text := "", enabled := False]
set addrSet [enabled := False]
propagateEvent
]
set addrSet [on command := do
id <- get addrList selection
if id /= (-1)
then do
address <- get addrText text
set addrList [item id := address]
else
return ()
]
let
getResult :: IO Debtor
getResult = do
name <- get nameInput text
phone <- get phoneInput text
exNum <- get exNumInput text
addresses <- get addrList items
amount <- get amountInput selection
exTime <- get exTimeInput text
comment <- get commentInput text
return $ debtor
{ getName = name
, getPhoneNum = phone
, getExecutionNum = exNum
, getAddresses = addresses
, getAmount = amount
, getExecutionTime = exTime
, getComment = comment
}
set ok [on command := do
result <- getResult
onResult result
close f
]
set cancel [on command := close f]
set f
[ defaultButton := ok
, layout := container p $ margin 10 $ minsize (sz 400 100) $ column 5
[ grid 5 5
[ [alignLeft $ label "Name: ", hfill $ widget nameInput]
, [alignLeft $ label "Phone number: ", hfill $ widget phoneInput]
, [alignLeft $ label "Execution number: ", hfill $ widget exNumInput]
, [alignLeft $ label "Addresses: ", fill . minsize (sz (-1) 150) $ widget addrList]
, [glue, hfloatCenter $ row 5 [widget addrAdd, widget addrRemove]]
, [glue, fill $ widget addrText]
, [glue, hfloatRight $ widget addrSet]
, [alignLeft $ label "Amount: ", hfill $ widget amountInput]
, [alignLeft $ label "Execution time: ", hfill $ widget exTimeInput]
, [alignLeft $ label "Comment: ", hfill $ widget commentInput]
]
, hfloatRight $ row 5
[ widget ok, widget cancel ]
]
]
| honzasp/inkvizitor | Inkvizitor/UI/Debtor.hs | gpl-3.0 | 3,617 | 0 | 21 | 1,054 | 1,288 | 629 | 659 | 91 | 4 |
module Jelly.Jammit
( module Sound.Jammit.Base
) where
import Sound.Jammit.Base
| mtolly/jelly | src/Jelly/Jammit.hs | gpl-3.0 | 81 | 0 | 5 | 10 | 21 | 14 | 7 | 3 | 0 |
{-# LANGUAGE GeneralizedNewtypeDeriving, TypeSynonymInstances, FlexibleInstances #-}
module Modules.Database where
import Control.Applicative
import qualified Data.Map as Map
import Test.Framework
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck
import Data.List
import Control.Monad
import Database.Memory
boundedInt :: Int -> Int -> Gen Int
boundedInt lb ub = choose (lb,ub)
-- Very inefficient but deterministic running time
uniqueList :: Int -> Gen [String]
uniqueList n = unique n 0 []
where
unique n s ls | n <= 0 = return ls
| otherwise = do
el <- vector s
let next = nub $ permutations el
let n' = n - (length next)
unique n' (s+1) (ls ++ take n next)
instance Arbitrary Table where
arbitrary = do
n <- boundedInt 0 5
m <- boundedInt 0 20
headers <- uniqueList 5
recs <- foldM (f n) (Map.empty) [1..m]
return $ Table headers recs
where f size a k = do
recs <- vector size
return $ Map.insert k recs a
instance Arbitrary Database where
arbitrary = do
n <- boundedInt 0 10
foldM on Map.empty [1..n]
where
on d _ = do
t <- arbitrary
n <- arbitrary
return $ Map.insert n t d
prop_create_get :: Fields -> Table -> Bool
prop_create_get f t = Just f == getRecordById i t'
where (i,t') = createRecord f t
test_create_get :: Test
test_create_get = testProperty "createRecord . get should return the same record" prop_create_get
tests :: [Test]
tests = [ test_create_get
]
| cornell-pl/evolution | tests/Modules/Database.hs | gpl-3.0 | 1,650 | 0 | 15 | 481 | 533 | 265 | 268 | 45 | 1 |
module SymLens.Table where
import SymLens
import Database.Memory
import Data.Maybe (fromMaybe)
import qualified Data.Map as Map
import qualified Data.List as List
insertColumn :: Header -> Field -> SymLens Table Table
insertColumn h f =
SymLens Map.empty
(\(Table hs rs) m -> let insertFn m' k fs = case Map.lookup k m of
Just f' -> (m', f':fs)
Nothing -> (Map.insert k f m', f:fs) in
let (m', rs') = Map.mapAccumWithKey insertFn m rs in
(Table (h:hs) rs', m'))
(\(Table hs rs) _ -> case List.elemIndex h hs of
Just n -> let (_, hs') = extract n hs in
let (m, rs') = Map.mapAccumWithKey (extractIntoMap n) Map.empty rs in
(Table hs' rs', m)
Nothing -> (Table hs rs, Map.empty))
where extract n l = let (l1, x:l2) = List.splitAt n l in
(x, l1 ++ l2)
extractIntoMap n m i l = let (x, l') = extract n l in
(Map.insert i x m, l')
deleteColumn :: Header -> Field -> SymLens Table Table
deleteColumn h f = inv $ insertColumn h f
renameColumn :: Header -> Header -> SymLens Table Table
renameColumn h h' =
SymLens () fn fn
where fn (Table hs rs) _ = (Table (List.map rename hs) rs, ())
rename hd | hd == h = h'
| hd == h' = h
| otherwise = hd
swapColumn :: Header -> Header -> SymLens Table Table
swapColumn h1 h2 =
SymLens () fn fn
where fn (Table hs rs) _ =
case (List.elemIndex h1 hs, List.elemIndex h2 hs) of
(Just n1, Just n2) -> (Table (swapElem n1 n2 hs) (Map.map (swapElem n1 n2) rs), ())
_ -> (Table hs rs, ())
swapElem n1 n2 l | n1 == n2 = l
| n1 > n2 = swapElem n2 n1 l
| n1 < n2 = let (l1, a:l2) = splitAt n1 l in
let (l3, b:l4) = splitAt (n2 - n1 - 1) l2 in
l1 ++ b:l3 ++ a:l4
--deleteColumn :: Header -> Table -> Table
--deleteColumn h t@(Table hs rs) =
-- case elemIndex h hs of
-- Just n -> Table (delete n hs) $ Map.map (delete n) rs
-- Nothing -> t
-- where delete n fs = take n fs ++ drop (n+1) fs
--
--projectColumn :: Header -> Table -> [Field]
--projectColumn h t@(Table hs rs) =
-- case elemIndex h hs of
-- Just n -> map (!!n) (Map.elems rs)
-- Nothing -> []
--
| cornell-pl/evolution | SymLens/Table.hs | gpl-3.0 | 2,757 | 0 | 19 | 1,183 | 906 | 463 | 443 | 44 | 3 |
{- ============================================================================
| Copyright 2011 Matthew D. Steele <[email protected]> |
| |
| This file is part of Fallback. |
| |
| Fallback 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. |
| |
| Fallback 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 Fallback. If not, see <http://www.gnu.org/licenses/>. |
============================================================================ -}
module Fallback.View.Combat
(CombatAction(..), newCombatView)
where
import Control.Applicative ((<$>))
import Fallback.Constants (sidebarWidth)
import Fallback.Data.Color (Tint(Tint))
import Fallback.Data.Point
import qualified Fallback.Data.TotalMap as TM (get)
import Fallback.Draw
import Fallback.Event
import Fallback.State.Area
import Fallback.State.Camera (camTopleft)
import Fallback.State.Combat
import Fallback.State.Creature
import Fallback.State.Doodad (DoodadHeight(..), paintDoodads)
import Fallback.State.Item (wdRange)
import Fallback.State.Party
import Fallback.State.Resources (Resources, rsrcCharacterImages)
import Fallback.State.Simple (CharacterNumber)
import Fallback.State.Terrain
import Fallback.Utility (maybeM)
import Fallback.View.Abilities
import Fallback.View.Base
import Fallback.View.Camera
import Fallback.View.Hover
import Fallback.View.Inventory
import Fallback.View.Sidebar
-------------------------------------------------------------------------------
data CombatAction = CombatSidebar SidebarAction
| CombatAbilities AbilitiesAction
| CombatInventory InventoryAction
| CombatMove Direction
| CombatAttack Position
| CombatEndTurnEarly
| CombatTargetPosition Position
| CombatTargetCharacter CharacterNumber
| CombatEndTargeting
| CombatCancelAction
newCombatView :: (MonadDraw m) => Resources
-> m (View CombatState CombatAction)
newCombatView resources = newCursorView resources $ \cursorSink -> do
let mapRect _ (w, h) = Rect sidebarWidth 0 (w - sidebarWidth) h
let sidebarRect _ (_, h) = Rect 0 0 sidebarWidth h
let abilitiesFn cs =
case csPhase cs of
ChooseAbilityPhase cc -> Just AbilitiesState
{ abilsActiveCharacter = ccCharacterNumber cc,
abilsInCombat = True,
abilsMetaAbilityTag = Nothing,
abilsParty = arsParty cs }
MetaAbilityPhase cm -> Just AbilitiesState
{ abilsActiveCharacter = ccCharacterNumber (cmCommander cm),
abilsInCombat = True,
abilsMetaAbilityTag = Just (cmFeatTag cm),
abilsParty = arsParty cs }
_ -> Nothing
let inventoryFn cs =
case csPhase cs of
InventoryPhase cc mbItem ->
Just $ makeInventoryState cs (ccCharacterNumber cc) mbItem
_ -> Nothing
compoundViewM [
(subView sidebarRect . viewMap SidebarCombat CombatSidebar <$>
newSidebarView resources),
(subView mapRect <$> compoundViewM [
(newCombatMapView resources),
(newMaybeView inventoryFn =<< fmap CombatInventory <$>
newInventoryView resources cursorSink),
(newMaybeView abilitiesFn =<< fmap CombatAbilities <$>
newAbilitiesView resources cursorSink)])]
newCombatMapView :: (MonadDraw m) => Resources
-> m (View CombatState CombatAction)
newCombatMapView resources = do
let
paint cs = do
let acs = csCommon cs
let cameraTopleft = camTopleft (acsCamera acs)
paintTerrain acs
paintRemains acs
paintDoodads cameraTopleft LowDood (acsDoodads acs)
paintFields resources cameraTopleft (acsVisible acs)
(acsClock acs) (acsFields acs)
paintMonsters acs True
paintCharacters resources cameraTopleft cs
paintDoodads cameraTopleft MidDood (acsDoodads acs)
tintNonVisibleTiles acs
paintDoodads cameraTopleft HighDood (acsDoodads acs)
let paintRange cc = do
let charNum = ccCharacterNumber cc
paintWeaponRange cameraTopleft cs charNum
(wdRange $ chrEquippedWeaponData $
arsGetCharacter charNum cs)
case csPhase cs of
CommandPhase cc -> paintRange cc
TargetingPhase (CombatTargeting { ctCommander = cc,
ctTargeting = targeting }) -> do
mbMousePt <- getRelativeMousePos
paintTargeting cameraTopleft mbMousePt cs
(ccCharacterNumber cc) targeting (acsClock acs)
ExecutionPhase ce -> maybeM (ceCommander ce) paintRange
_ -> return ()
maybeM (acsMessage acs) (paintMessage resources)
handler _ EvTick =
maybe Ignore (Action . CombatMove) <$> getArrowKeysDirection
handler cs (EvMouseDown pt) = do
whenWithinCanvas pt $ do
let pt' = pt `pAdd` (camTopleft $ arsCamera cs)
let pos = pointPosition pt'
case csPhase cs of
WaitingPhase ->
case arsOccupant pos cs of
Just (Left charNum) ->
return $ Action $ CombatSidebar $ MakeCharacterActive charNum
_ -> return Suppress
CommandPhase cc ->
-- FIXME device interation
case arsOccupant pos cs of
Just (Left charNum) ->
return $ Action $ CombatSidebar $ MakeCharacterActive charNum
Just (Right _) -> return $ Action $ CombatAttack pos
Nothing -> do
let here = arsCharacterPosition (ccCharacterNumber cc) cs
if pos == here then return Suppress else do
return $ Action $ CombatMove $
if adjacent pos here then ipointDir (pos `pSub` here) else
ipointDir (pt' `pSub` positionCenter here)
ChooseAbilityPhase _ -> return Suppress
MetaAbilityPhase _ -> return Suppress
InventoryPhase _ _ -> return Suppress
TargetingPhase _ -> return $ Action $ CombatTargetPosition pos
ExecutionPhase _ -> return Suppress
handler cs (EvKeyDown key _ _) = do
case key of
KeyEscape -> return $ Action $ CombatCancelAction
KeySpace -> do
case csPhase cs of
WaitingPhase -> return Ignore
CommandPhase _ -> return $ Action $ CombatEndTurnEarly
ChooseAbilityPhase _ -> return Suppress
MetaAbilityPhase _ -> return Suppress
InventoryPhase _ _ -> return Suppress
TargetingPhase _ -> return $ Action $ CombatEndTargeting
ExecutionPhase _ -> return Suppress
_ ->
case keyCharacterNumber key of
Just charNum ->
case csPhase cs of
TargetingPhase _ ->
return $ Action $ CombatTargetCharacter charNum
_ -> return Ignore
Nothing -> return Ignore
handler _ _ = return Ignore
return $ View paint handler
-------------------------------------------------------------------------------
paintCharacters :: Resources -> IPoint -> CombatState -> Paint ()
paintCharacters resources cameraTopleft cs =
mapM_ paintChar [minBound .. maxBound] where
paintChar charNum = do
let char = arsGetCharacter charNum cs
if not (chrIsConscious char) then return () else do
let ccs = TM.get charNum $ csCharStates cs
let pos = ccsPosition ccs
let pose = ccsPose ccs
let sprite =
(case cpAnim pose of { AttackAnim _ -> ciAttack; _ -> ciStand })
(cpFaceDir pose)
(rsrcCharacterImages resources (chrClass char)
(chrAppearance char))
let offset = animOffset (cpAnim pose) pos
-- TODO draw an extra decoration for the active character
blitStretchTinted (Tint 255 255 255 (cpAlpha pose)) sprite $
positionRect pos `rectPlus` (offset `pSub` cameraTopleft)
let prect = makeRect pos (1, 1)
paintStatusDecorations resources cameraTopleft (arsClock cs) offset
prect pos (chrStatus char)
paintHealthBar cameraTopleft True prect offset (chrHealth char)
(chrMaxHealth (arsParty cs) char) Nothing
-------------------------------------------------------------------------------
| mdsteele/fallback | src/Fallback/View/Combat.hs | gpl-3.0 | 9,377 | 38 | 25 | 2,976 | 2,025 | 1,027 | 998 | -1 | -1 |
module Sites.GirlGenius
( girlGenius
) where
import Network.HTTP.Types.URI (decodePathSegments)
import Data.List (isInfixOf, isPrefixOf)
import qualified Data.List as DL
import Text.XML.HXT.Core
import qualified Data.Text as T
import qualified Data.ByteString.Lazy.UTF8 as UL
import qualified Data.ByteString.UTF8 as US
-- Local imports
import Types
import Sites.Util
--
-- Girl Genius
--
girlGenius = Comic
{ comicName = "Girl Genius"
, seedPage = "http://www.girlgeniusonline.com/comic.php?date=20021104"
, seedCache = Always
, pageParse = toPipeline girlGeniusPageParse
, cookies = []
}
girlGeniusPageParse :: ReplyType -> IO [FetchType]
girlGeniusPageParse (WebpageReply html) = do
let doc = readString [withParseHTML yes, withWarnings no] $ UL.toString html
next <- runX $ doc //> nextPage
img <- runX $ doc //> comic
vol <- concat `fmap` runX (whichVol doc)
-- Do we have any comic we want to store to disk?
putStrLn "Fetched Urls:"
mapM_ putStrLn img
mapM_ putStrLn next
return $ map (\a -> Webpage a Always) next ++ map (\a -> Image a $ comicFileName vol a) img
where
nextPage = hasName "td" >>> hasAttrValue "valign" (== "top") //> (hasName "a" </ (hasName "img" >>> hasAttrValue "alt" (== "The Next Comic"))) >>> getAttrValue "href"
comic =
hasName "td"
>>> hasAttrValue "valign" (== "middle")
//> hasName "img"
>>> hasAttr "src"
>>> getAttrValue "src"
>>. arr (filter (isPrefixOf "http"))
comicFileName vol url = ComicTag (T.pack "girl_genius") Nothing (Just $ UnitTag [StandAlone $ Digit (girlGeniusVol vol) Nothing Nothing Nothing] Nothing) Nothing (Just $ last $ decodePathSegments $ US.fromString url)
-- TODO: this returns a single string (cuz its concating all of this), we worked around this but this is very much non-ideal
-- For workaround see girlGeniusVol
whichVol doc =
(doc //>
hasName "form"
>>> hasAttrValue "name" (== "storyline")
//> (hasName "option" `notContaining` (getChildren >>> hasText (== "---\"ADVANCED CLASS\" BEGINS---")))
>>> (
(withDefault (getAttrValue0 "selected") "no" >>> arr (/= "no"))
&&&
(getChildren >>> getText)
)
>>. filter (\(a, b) -> a || ((("VOLUME" `isInfixOf` b) || ("Volume" `isInfixOf` b)) && not (("Final Page" `isPrefixOf` b) || ("Wallpaper" `isInfixOf` b))))
) >. takeWhile (not . fst)
>>> unlistA
>>> arr snd
-- ) >>> arr ((SL.split . SL.keepDelimsL . SL.whenElt) (isPrefixOf "Chapter")) -- TODO: this is for splitting things up
girlGeniusVol :: String -> Integer
girlGeniusVol a = wordToNumber (DL.reverse $ DL.head $ DL.words $ DL.drop 3 $ DL.reverse a)
| pharaun/hComicFetcher | src/Sites/GirlGenius.hs | gpl-3.0 | 2,823 | 0 | 22 | 680 | 802 | 431 | 371 | 49 | 1 |
{-
Copyright (C) 2014 Richard Larocque <[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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{-# LANGUAGE OverloadedStrings #-}
module Wiki.Latin.NounDecl(getNounInflections) where
import qualified Data.Text as T
import Data.Maybe
import Wiki.Types
import Wiki.PageParser
import Latin.Grammar
import Debug.Trace
getNounInflections :: [TemplateRef] -> Maybe (T.Text, [Inflection])
getNounInflections trefs = listToMaybe $ mapMaybe readNounInflectionTemplate trefs
readNounInflectionTemplate :: TemplateRef -> Maybe (T.Text, [Inflection])
readNounInflectionTemplate (TemplateRef []) = Nothing
readNounInflectionTemplate (TemplateRef [name])
| name == "la-decl-agnus" = Just (name, la_decl_agnus)
| name == "la-decl-bos" = Just (name, la_decl_bos)
| name == "la-decl-deus" = Just (name, la_decl_deus)
| name == "la-decl-domus" = Just (name, la_decl_domus)
| name == "la-decl-iesus" = Just (name, la_decl_iesus)
| name == "la-decl-sus" = Just (name, la_decl_sus)
| name == "la-decl-venum" = Just (name, la_decl_venum)
| name == "la-decl-vis" = Just (name, la_decl_vis)
| otherwise = Nothing
readNounInflectionTemplate (TemplateRef (name:params))
| name == "la-decl-1st" = wrapReadFunc la_decl_1st name params
| name == "la-decl-1st-abus" = wrapReadFunc la_decl_1st_abus name params
| name == "la-decl-1st-am" = wrapReadFunc la_decl_1st_am name params
| name == "la-decl-1st-Greek" = wrapReadFunc la_decl_1st_Greek name params
| name == "la-decl-1st-Greek-Ma" = wrapReadFunc la_decl_1st_Greek_Ma name params
| name == "la-decl-1st-Greek-Me" = wrapReadFunc la_decl_1st_Greek_Me name params
| name == "la-decl-1st-loc" = wrapReadFunc la_decl_1st_loc name params
| name == "la-decl-2nd" = wrapReadFunc la_decl_2nd name params
| name == "la-decl-2nd-er" = wrapReadFunc la_decl_2nd_er name params
| name == "la-decl-2nd-Greek" = wrapReadFunc la_decl_2nd_Greek name params
| name == "la-decl-2nd-ius" = wrapReadFunc la_decl_2nd_ius name params
| name == "la-decl-2nd-loc" = wrapReadFunc la_decl_2nd_loc name params
| name == "la-decl-2nd-N" = wrapReadFunc la_decl_2nd_N name params
| name == "la-decl-2nd-N-Greek" = wrapReadFunc la_decl_2nd_N_Greek name params
| name == "la-decl-2nd-N-loc" = wrapReadFunc la_decl_2nd_N_loc name params
| name == "la-decl-2nd-N-us" = wrapReadFunc la_decl_2nd_N_us name params
| name == "la-decl-3rd" = wrapReadFunc la_decl_3rd name params
| name == "la-decl-3rd-Greek-er" = wrapReadFunc la_decl_3rd_Greek_er name params
| name == "la-decl-3rd-I" = wrapReadFunc la_decl_3rd_I name params
| name == "la-decl-3rd-I-ignis" = wrapReadFunc la_decl_3rd_I_ignis name params
| name == "la-decl-3rd-I-loc" = wrapReadFunc la_decl_3rd_I_loc name params
| name == "la-decl-3rd-I-navis" = wrapReadFunc la_decl_3rd_I_navis name params
| name == "la-decl-3rd-loc" = wrapReadFunc la_decl_3rd_loc name params
| name == "la-decl-3rd-N" = wrapReadFunc la_decl_3rd_N name params
| name == "la-decl-3rd-N-a" = wrapReadFunc la_decl_3rd_N_a name params
| name == "la-decl-3rd-N-I" = wrapReadFunc la_decl_3rd_N_I name params
| name == "la-decl-3rd-N-I-pure" = wrapReadFunc la_decl_3rd_N_I_pure name params
| name == "la-decl-4th" = wrapReadFunc la_decl_4th name params
| name == "la-decl-4th-argo" = wrapReadFunc la_decl_4th_argo name params
| name == "la-decl-4th-N" = wrapReadFunc la_decl_4th_N name params
| name == "la-decl-4th-ubus" = wrapReadFunc la_decl_4th_ubus name params
| name == "la-decl-5th-CONS" = wrapReadFunc la_decl_5th_CONS name params
| name == "la-decl-5th-VOW" = wrapReadFunc la_decl_5th_VOW name params
| otherwise = Nothing
wrapReadFunc :: ([T.Text] -> Maybe [Inflection]) -> T.Text -> [T.Text] -> Maybe (T.Text, [Inflection])
wrapReadFunc f name (p:ps) = do
decls <- case T.stripPrefix (T.pack "num=") p of
Nothing -> f (p:ps)
Just n | n == (T.pack "sg") -> f ps >>= return.sgOnly
Just n | n == (T.pack "pl") -> f ps >>= return.plOnly
Just _ -> error $ "Unexpected num= parameter: " ++ (show p)
return (name, decls)
where
sgOnly ds = [ d | d@(Inflection _ Singular _) <- ds ]
plOnly ds = [ d | d@(Inflection _ Plural _) <- ds ]
wrapReadFunc f n xs = f xs >>= \x -> return (n, x)
withSuffix :: T.Text -> String -> T.Text
withSuffix a b = a `T.append` (T.pack b)
nom_sg, gen_sg, dat_sg, acc_sg, abl_sg, voc_sg, loc_sg, nom_pl, gen_pl, dat_pl, acc_pl, abl_pl, voc_pl, loc_pl :: T.Text -> Inflection
nom_sg = Inflection Nominative Singular
gen_sg = Inflection Genitive Singular
dat_sg = Inflection Dative Singular
acc_sg = Inflection Accusative Singular
abl_sg = Inflection Ablative Singular
voc_sg = Inflection Vocative Singular
loc_sg = Inflection Locative Singular
nom_pl = Inflection Nominative Plural
gen_pl = Inflection Genitive Plural
dat_pl = Inflection Dative Plural
acc_pl = Inflection Accusative Plural
abl_pl = Inflection Ablative Plural
voc_pl = Inflection Vocative Plural
loc_pl = Inflection Locative Plural
la_decl_1st, la_decl_1st_abus, la_decl_1st_am, la_decl_1st_Greek, la_decl_1st_Greek_Ma, la_decl_1st_Greek_Me, la_decl_1st_loc, la_decl_2nd, la_decl_2nd_er, la_decl_2nd_Greek, la_decl_2nd_N, la_decl_2nd_N_us, la_decl_2nd_N_Greek, la_decl_2nd_N_loc, la_decl_2nd_ius, la_decl_2nd_loc, la_decl_3rd, la_decl_3rd_Greek_er, la_decl_3rd_I, la_decl_3rd_I_ignis, la_decl_3rd_I_loc, la_decl_3rd_I_navis, la_decl_3rd_loc, la_decl_3rd_N, la_decl_3rd_N_a, la_decl_3rd_N_I, la_decl_3rd_N_I_pure, la_decl_4th, la_decl_4th_argo, la_decl_4th_N, la_decl_4th_ubus, la_decl_5th_CONS, la_decl_5th_VOW :: [T.Text] -> Maybe [Inflection]
la_decl_1st (stem:_) = Just [
nom_sg (stem `withSuffix` "a"),
gen_sg (stem `withSuffix` "ae"),
dat_sg (stem `withSuffix` "ae"),
acc_sg (stem `withSuffix` "am"),
abl_sg (stem `withSuffix` "ā"),
voc_sg (stem `withSuffix` "a"),
nom_pl (stem `withSuffix` "ae"),
gen_pl (stem `withSuffix` "ārum"),
dat_pl (stem `withSuffix` "īs"),
acc_pl (stem `withSuffix` "ās"),
abl_pl (stem `withSuffix` "īs"),
voc_pl (stem `withSuffix` "ae")]
la_decl_1st _ = Nothing
la_decl_1st_abus (stem:_) = Just [
nom_sg (stem `withSuffix` "a"),
gen_sg (stem `withSuffix` "ae"),
dat_sg (stem `withSuffix` "ae"),
acc_sg (stem `withSuffix` "am"),
abl_sg (stem `withSuffix` "ā"),
voc_sg (stem `withSuffix` "a"),
nom_pl (stem `withSuffix` "ae"),
gen_pl (stem `withSuffix` "ārum"),
dat_pl (stem `withSuffix` "ābus"),
acc_pl (stem `withSuffix` "ās"),
abl_pl (stem `withSuffix` "ābus"),
voc_pl (stem `withSuffix` "ae")]
la_decl_1st_abus _ = Nothing
la_decl_1st_am (stem:_) = Just [
nom_sg (stem `withSuffix` "am"),
gen_sg (stem `withSuffix` "ae"),
dat_sg (stem `withSuffix` "ae"),
acc_sg (stem `withSuffix` "am"),
abl_sg (stem `withSuffix` "ā"),
voc_sg (stem `withSuffix` "am"),
nom_pl (stem `withSuffix` "ae"),
gen_pl (stem `withSuffix` "ārum"),
dat_pl (stem `withSuffix` "īs"),
acc_pl (stem `withSuffix` "ās"),
abl_pl (stem `withSuffix` "īs"),
voc_pl (stem `withSuffix` "ae")]
la_decl_1st_am _ = Nothing
la_decl_1st_Greek (stem:_) = Just [
nom_sg (stem `withSuffix` "ē"),
gen_sg (stem `withSuffix` "ēs"),
dat_sg (stem `withSuffix` "ae"),
acc_sg (stem `withSuffix` "ēn"),
abl_sg (stem `withSuffix` "ē"),
voc_sg (stem `withSuffix` "ē"),
nom_pl (stem `withSuffix` "ae"),
gen_pl (stem `withSuffix` "ārum"),
dat_pl (stem `withSuffix` "īs"),
acc_pl (stem `withSuffix` "ās"),
abl_pl (stem `withSuffix` "īs"),
voc_pl (stem `withSuffix` "ae")]
la_decl_1st_Greek _ = Nothing
la_decl_1st_Greek_Ma (stem:_) = Just [
nom_sg (stem `withSuffix` "ās"),
gen_sg (stem `withSuffix` "ae"),
dat_sg (stem `withSuffix` "ae"),
acc_sg (stem `withSuffix` "ān"),
abl_sg (stem `withSuffix` "ā"),
voc_sg (stem `withSuffix` "a"),
nom_pl (stem `withSuffix` "ae"),
gen_pl (stem `withSuffix` "ārum"),
dat_pl (stem `withSuffix` "īs"),
acc_pl (stem `withSuffix` "ās"),
abl_pl (stem `withSuffix` "īs"),
voc_pl (stem `withSuffix` "ae")]
la_decl_1st_Greek_Ma _ = Nothing
la_decl_1st_Greek_Me (stem:_) = Just [
nom_sg (stem `withSuffix` "ēs"),
gen_sg (stem `withSuffix` "ae"),
dat_sg (stem `withSuffix` "ae"),
acc_sg (stem `withSuffix` "ēn"),
abl_sg (stem `withSuffix` "ē"),
voc_sg (stem `withSuffix` "ē"),
nom_pl (stem `withSuffix` "ae"),
gen_pl (stem `withSuffix` "ārum"),
dat_pl (stem `withSuffix` "īs"),
acc_pl (stem `withSuffix` "ās"),
abl_pl (stem `withSuffix` "īs"),
voc_pl (stem `withSuffix` "ae")]
la_decl_1st_Greek_Me _ = Nothing
la_decl_1st_loc (stem:_) = Just [
nom_sg (stem `withSuffix` "a"),
gen_sg (stem `withSuffix` "ae"),
dat_sg (stem `withSuffix` "ae"),
acc_sg (stem `withSuffix` "am"),
abl_sg (stem `withSuffix` "ā"),
voc_sg (stem `withSuffix` "a"),
loc_sg (stem `withSuffix` "ae"),
nom_pl (stem `withSuffix` "ae"),
gen_pl (stem `withSuffix` "ārum"),
dat_pl (stem `withSuffix` "īs"),
acc_pl (stem `withSuffix` "ās"),
abl_pl (stem `withSuffix` "īs"),
voc_pl (stem `withSuffix` "ae"),
loc_pl (stem `withSuffix` "īs")]
la_decl_1st_loc _ = Nothing
la_decl_2nd (stem:_) = Just [
nom_sg (stem `withSuffix` "us"),
gen_sg (stem `withSuffix` "ī"),
dat_sg (stem `withSuffix` "ō"),
acc_sg (stem `withSuffix` "um"),
abl_sg (stem `withSuffix` "ō"),
voc_sg (stem `withSuffix` "e"),
nom_pl (stem `withSuffix` "ī"),
gen_pl (stem `withSuffix` "ōrum"),
dat_pl (stem `withSuffix` "īs"),
acc_pl (stem `withSuffix` "ōs"),
abl_pl (stem `withSuffix` "īs"),
voc_pl (stem `withSuffix` "ī")]
la_decl_2nd _ = Nothing
la_decl_2nd_er (stem:_) = Just [
nom_sg stem,
gen_sg (stem `withSuffix` "ī"),
dat_sg (stem `withSuffix` "ō"),
acc_sg (stem `withSuffix` "um"),
abl_sg (stem `withSuffix` "ō"),
voc_sg stem,
nom_pl (stem `withSuffix` "ī"),
gen_pl (stem `withSuffix` "ōrum"),
dat_pl (stem `withSuffix` "īs"),
acc_pl (stem `withSuffix` "ōs"),
abl_pl (stem `withSuffix` "īs"),
voc_pl (stem `withSuffix` "ī")]
la_decl_2nd_er _ = Nothing
la_decl_2nd_Greek (stem:_) = Just [
nom_sg (stem `withSuffix` "os"),
gen_sg (stem `withSuffix` "ī"),
dat_sg (stem `withSuffix` "ō"),
acc_sg (stem `withSuffix` "on"),
abl_sg (stem `withSuffix` "ō"),
voc_sg (stem `withSuffix` "e"),
nom_pl (stem `withSuffix` "ī"),
gen_pl (stem `withSuffix` "ōrum"),
dat_pl (stem `withSuffix` "īs"),
acc_pl (stem `withSuffix` "ōs"),
abl_pl (stem `withSuffix` "īs"),
voc_pl (stem `withSuffix` "ī")]
la_decl_2nd_Greek _ = Nothing
la_decl_2nd_N (stem:_) = Just [
nom_sg (stem `withSuffix` "um"),
gen_sg (stem `withSuffix` "ī"),
dat_sg (stem `withSuffix` "ō"),
acc_sg (stem `withSuffix` "um"),
abl_sg (stem `withSuffix` "ō"),
voc_sg (stem `withSuffix` "um"),
nom_pl (stem `withSuffix` "a"),
gen_pl (stem `withSuffix` "ōrum"),
dat_pl (stem `withSuffix` "īs"),
acc_pl (stem `withSuffix` "a"),
abl_pl (stem `withSuffix` "īs"),
voc_pl (stem `withSuffix` "a")]
la_decl_2nd_N _ = Nothing
la_decl_2nd_N_us (stem:_) = Just [
nom_sg (stem `withSuffix` "us"),
gen_sg (stem `withSuffix` "ī"),
dat_sg (stem `withSuffix` "ō"),
acc_sg (stem `withSuffix` "us"),
abl_sg (stem `withSuffix` "ō"),
voc_sg (stem `withSuffix` "us")]
la_decl_2nd_N_us _ = Nothing
la_decl_2nd_N_Greek (stem:_) = Just [
nom_sg (stem `withSuffix` "on"),
gen_sg (stem `withSuffix` "ī"),
dat_sg (stem `withSuffix` "ō"),
acc_sg (stem `withSuffix` "on"),
abl_sg (stem `withSuffix` "ō"),
voc_sg (stem `withSuffix` "on"),
nom_pl (stem `withSuffix` "a"),
gen_pl (stem `withSuffix` "ōrum"),
dat_pl (stem `withSuffix` "īs"),
acc_pl (stem `withSuffix` "a"),
abl_pl (stem `withSuffix` "īs"),
voc_pl (stem `withSuffix` "a")]
la_decl_2nd_N_Greek _ = Nothing
la_decl_2nd_N_loc (stem:_) = Just [
nom_sg (stem `withSuffix` "um"),
gen_sg (stem `withSuffix` "ī"),
dat_sg (stem `withSuffix` "ō"),
acc_sg (stem `withSuffix` "um"),
abl_sg (stem `withSuffix` "ō"),
voc_sg (stem `withSuffix` "um"),
loc_sg (stem `withSuffix` "ī"),
nom_pl (stem `withSuffix` "a"),
gen_pl (stem `withSuffix` "ōrum"),
dat_pl (stem `withSuffix` "īs"),
acc_pl (stem `withSuffix` "a"),
abl_pl (stem `withSuffix` "īs"),
voc_pl (stem `withSuffix` "a"),
loc_pl (stem `withSuffix` "īs")]
la_decl_2nd_N_loc _ = Nothing
la_decl_2nd_ius (stem:_) = Just [
nom_sg (stem `withSuffix` "ius"),
gen_sg (stem `withSuffix` "iī"),
dat_sg (stem `withSuffix` "iō"),
acc_sg (stem `withSuffix` "ium"),
abl_sg (stem `withSuffix` "iō"),
voc_sg (stem `withSuffix` "i"),
nom_pl (stem `withSuffix` "iī"),
gen_pl (stem `withSuffix` "iōrum"),
dat_pl (stem `withSuffix` "iīs"),
acc_pl (stem `withSuffix` "iōs"),
abl_pl (stem `withSuffix` "iīs"),
voc_pl (stem `withSuffix` "iī")]
la_decl_2nd_ius _ = Nothing
la_decl_2nd_loc (stem:_) = Just [
nom_sg (stem `withSuffix` "us"),
gen_sg (stem `withSuffix` "ī"),
dat_sg (stem `withSuffix` "ō"),
acc_sg (stem `withSuffix` "um"),
abl_sg (stem `withSuffix` "ō"),
voc_sg (stem `withSuffix` "e"),
loc_sg (stem `withSuffix` "ī"),
nom_pl (stem `withSuffix` "ī"),
gen_pl (stem `withSuffix` "ōrum"),
dat_pl (stem `withSuffix` "īs"),
acc_pl (stem `withSuffix` "ōs"),
abl_pl (stem `withSuffix` "īs"),
voc_pl (stem `withSuffix` "ī"),
loc_pl (stem `withSuffix` "īs")]
la_decl_2nd_loc _ = Nothing
la_decl_3rd (nom:stem:_) = Just [
nom_sg nom,
gen_sg (stem `withSuffix` "is"),
dat_sg (stem `withSuffix` "ī"),
acc_sg (stem `withSuffix` "em"),
abl_sg (stem `withSuffix` "e"),
voc_sg nom,
nom_pl (stem `withSuffix` "ēs"),
gen_pl (stem `withSuffix` "um"),
dat_pl (stem `withSuffix` "ibus"),
acc_pl (stem `withSuffix` "ēs"),
abl_pl (stem `withSuffix` "ibus"),
voc_pl (stem `withSuffix` "ēs")]
la_decl_3rd _ = Nothing
la_decl_3rd_Greek_er (stem:_) = Just [
nom_sg (stem `withSuffix` "ēr"),
gen_sg (stem `withSuffix` "eris"),
dat_sg (stem `withSuffix` "erī"),
acc_sg (stem `withSuffix` "era"),
abl_sg (stem `withSuffix` "ere"),
voc_sg (stem `withSuffix` "ēr"),
nom_pl (stem `withSuffix` "erēs"),
gen_pl (stem `withSuffix` "erum"),
dat_pl (stem `withSuffix` "eribus"),
acc_pl (stem `withSuffix` "erēs"),
abl_pl (stem `withSuffix` "eribus"),
voc_pl (stem `withSuffix` "erēs")]
la_decl_3rd_Greek_er _ = Nothing
la_decl_3rd_I (nom:stem:_) = Just [
nom_sg nom,
gen_sg (stem `withSuffix` "is"),
dat_sg (stem `withSuffix` "ī"),
acc_sg (stem `withSuffix` "em"),
abl_sg (stem `withSuffix` "e"),
voc_sg nom,
nom_pl (stem `withSuffix` "ēs"),
gen_pl (stem `withSuffix` "ium"),
dat_pl (stem `withSuffix` "ibus"),
acc_pl (stem `withSuffix` "ēs"),
abl_pl (stem `withSuffix` "ibus"),
voc_pl (stem `withSuffix` "ēs")]
la_decl_3rd_I _ = Nothing
la_decl_3rd_I_ignis (nom:stem:_) = Just [
nom_sg nom,
gen_sg (stem `withSuffix` "is"),
dat_sg (stem `withSuffix` "ī"),
acc_sg (stem `withSuffix` "em"),
abl_sg (stem `withSuffix` "ī"),
voc_sg nom,
nom_pl (stem `withSuffix` "ēs"),
gen_pl (stem `withSuffix` "ium"),
dat_pl (stem `withSuffix` "ibus"),
acc_pl (stem `withSuffix` "īs"),
abl_pl (stem `withSuffix` "ibus"),
voc_pl (stem `withSuffix` "ēs")]
la_decl_3rd_I_ignis _ = Nothing
la_decl_3rd_I_loc (nom:stem:_) = Just [
nom_sg nom,
gen_sg (stem `withSuffix` "is"),
dat_sg (stem `withSuffix` "ī"),
acc_sg (stem `withSuffix` "em"),
abl_sg (stem `withSuffix` "e"),
voc_sg nom,
loc_sg (stem `withSuffix` "e"),
nom_pl (stem `withSuffix` "ēs"),
gen_pl (stem `withSuffix` "ium"),
dat_pl (stem `withSuffix` "ibus"),
acc_pl (stem `withSuffix` "ēs"),
abl_pl (stem `withSuffix` "ibus"),
voc_pl (stem `withSuffix` "ēs"),
loc_pl (stem `withSuffix` "ēs")]
la_decl_3rd_I_loc _ = Nothing
la_decl_3rd_I_navis (nom:stem:_) = Just [
nom_sg nom,
gen_sg (stem `withSuffix` "is"),
dat_sg (stem `withSuffix` "ī"),
acc_sg (stem `withSuffix` "im"),
abl_sg (stem `withSuffix` "ī"),
voc_sg nom,
nom_pl (stem `withSuffix` "ēs"),
gen_pl (stem `withSuffix` "ium"),
dat_pl (stem `withSuffix` "ibus"),
acc_pl (stem `withSuffix` "īs"),
abl_pl (stem `withSuffix` "ibus"),
voc_pl (stem `withSuffix` "ēs")]
la_decl_3rd_I_navis _ = Nothing
la_decl_3rd_loc (nom:stem:_) = Just [
nom_sg nom,
gen_sg (stem `withSuffix` "is"),
dat_sg (stem `withSuffix` "ī"),
acc_sg (stem `withSuffix` "em"),
abl_sg (stem `withSuffix` "e"),
voc_sg nom,
loc_sg (stem `withSuffix` "e"),
nom_pl (stem `withSuffix` "ēs"),
gen_pl (stem `withSuffix` "um"),
dat_pl (stem `withSuffix` "ibus"),
acc_pl (stem `withSuffix` "ēs"),
abl_pl (stem `withSuffix` "ibus"),
voc_pl (stem `withSuffix` "ēs"),
loc_pl (stem `withSuffix` "ēs")]
la_decl_3rd_loc _ = Nothing
la_decl_3rd_N (nom:stem:_) = Just [
nom_sg nom,
gen_sg (stem `withSuffix` "is"),
dat_sg (stem `withSuffix` "ī"),
acc_sg nom,
abl_sg (stem `withSuffix` "e"),
voc_sg nom,
nom_pl (stem `withSuffix` "a"),
gen_pl (stem `withSuffix` "um"),
dat_pl (stem `withSuffix` "ibus"),
acc_pl (stem `withSuffix` "a"),
abl_pl (stem `withSuffix` "ibus"),
voc_pl (stem `withSuffix` "a")]
la_decl_3rd_N _ = Nothing
-- TODO: This one actually has a 1st decl variant, too.
la_decl_3rd_N_a (stem:_) = Just [
nom_sg (stem `withSuffix` "a"),
gen_sg (stem `withSuffix` "atis"),
dat_sg (stem `withSuffix` "atī"),
acc_sg (stem `withSuffix` "a"),
abl_sg (stem `withSuffix` "ate"),
voc_sg (stem `withSuffix` "a"),
nom_pl (stem `withSuffix` "ata"),
gen_pl (stem `withSuffix` "atum"),
dat_pl (stem `withSuffix` "atibus"),
acc_pl (stem `withSuffix` "ata"),
abl_pl (stem `withSuffix` "atibus"),
voc_pl (stem `withSuffix` "ata")]
la_decl_3rd_N_a _ = Nothing
la_decl_3rd_N_I (nom:stem:_) = Just [
nom_sg nom,
gen_sg (stem `withSuffix` "is"),
dat_sg (stem `withSuffix` "ī"),
acc_sg nom,
abl_sg (stem `withSuffix` "e"),
voc_sg nom,
nom_pl (stem `withSuffix` "a"),
gen_pl (stem `withSuffix` "ium"),
dat_pl (stem `withSuffix` "ibus"),
acc_pl (stem `withSuffix` "a"),
abl_pl (stem `withSuffix` "ibus"),
voc_pl (stem `withSuffix` "a")]
la_decl_3rd_N_I _ = Nothing
la_decl_3rd_N_I_pure (nom:stem:_) = Just [
nom_sg nom,
gen_sg (stem `withSuffix` "is"),
dat_sg (stem `withSuffix` "ī"),
acc_sg nom,
abl_sg (stem `withSuffix` "e"),
voc_sg nom,
nom_pl (stem `withSuffix` "ia"),
gen_pl (stem `withSuffix` "ium"),
dat_pl (stem `withSuffix` "ibus"),
acc_pl (stem `withSuffix` "ia"),
abl_pl (stem `withSuffix` "ibus"),
voc_pl (stem `withSuffix` "a")]
la_decl_3rd_N_I_pure _ = Nothing
la_decl_4th (stem:_) = Just [
nom_sg (stem `withSuffix` "us"),
gen_sg (stem `withSuffix` "ūs"),
dat_sg (stem `withSuffix` "uī"),
acc_sg (stem `withSuffix` "um"),
abl_sg (stem `withSuffix` "ū"),
voc_sg (stem `withSuffix` "us"),
nom_pl (stem `withSuffix` "ūs"),
gen_pl (stem `withSuffix` "uum"),
dat_pl (stem `withSuffix` "ibus"),
acc_pl (stem `withSuffix` "ūs"),
abl_pl (stem `withSuffix` "ibus"),
voc_pl (stem `withSuffix` "ūs")]
la_decl_4th _ = Nothing
la_decl_4th_argo (stem:_) = Just [
nom_sg (stem `withSuffix` "ō"),
gen_sg (stem `withSuffix` "ūs"),
dat_sg (stem `withSuffix` "uī"),
acc_sg (stem `withSuffix` "ō"),
abl_sg (stem `withSuffix` "uī"),
voc_sg (stem `withSuffix` "ō")]
la_decl_4th_argo _ = Nothing
la_decl_4th_N (stem:_) = Just [
nom_sg (stem `withSuffix` "ū"),
gen_sg (stem `withSuffix` "ūs"),
dat_sg (stem `withSuffix` "uī"),
acc_sg (stem `withSuffix` "ū"),
abl_sg (stem `withSuffix` "ū"),
voc_sg (stem `withSuffix` "ū"),
nom_pl (stem `withSuffix` "ua"),
gen_pl (stem `withSuffix` "uum"),
dat_pl (stem `withSuffix` "ibus"),
acc_pl (stem `withSuffix` "ua"),
abl_pl (stem `withSuffix` "ibus"),
voc_pl (stem `withSuffix` "ua")]
la_decl_4th_N _ = Nothing
la_decl_4th_ubus (stem:_) = Just [
nom_sg (stem `withSuffix` "us"),
gen_sg (stem `withSuffix` "ūs"),
dat_sg (stem `withSuffix` "uī"),
acc_sg (stem `withSuffix` "um"),
abl_sg (stem `withSuffix` "ū"),
voc_sg (stem `withSuffix` "us"),
nom_pl (stem `withSuffix` "ūs"),
gen_pl (stem `withSuffix` "uum"),
dat_pl (stem `withSuffix` "ubus"),
acc_pl (stem `withSuffix` "ūs"),
abl_pl (stem `withSuffix` "ubus"),
voc_pl (stem `withSuffix` "ūs")]
la_decl_4th_ubus _ = Nothing
la_decl_5th_CONS (stem:_) = Just [
nom_sg (stem `withSuffix` "ēs"),
gen_sg (stem `withSuffix` "eī"),
dat_sg (stem `withSuffix` "eī"),
acc_sg (stem `withSuffix` "em"),
abl_sg (stem `withSuffix` "ē"),
voc_sg (stem `withSuffix` "ēs"),
nom_pl (stem `withSuffix` "ēs"),
gen_pl (stem `withSuffix` "ērum"),
dat_pl (stem `withSuffix` "ēbus"),
acc_pl (stem `withSuffix` "ēs"),
abl_pl (stem `withSuffix` "ēbus"),
voc_pl (stem `withSuffix` "ēs")]
la_decl_5th_CONS _ = Nothing
la_decl_5th_VOW (stem:_) = Just [
nom_sg (stem `withSuffix` "ēs"),
gen_sg (stem `withSuffix` "ēī"),
dat_sg (stem `withSuffix` "ēī"),
acc_sg (stem `withSuffix` "em"),
abl_sg (stem `withSuffix` "ē"),
voc_sg (stem `withSuffix` "ēs"),
nom_pl (stem `withSuffix` "ēs"),
gen_pl (stem `withSuffix` "ērum"),
dat_pl (stem `withSuffix` "ēbus"),
acc_pl (stem `withSuffix` "ēs"),
abl_pl (stem `withSuffix` "ēbus"),
voc_pl (stem `withSuffix` "ēs")]
la_decl_5th_VOW _ = Nothing
la_decl_agnus, la_decl_bos, la_decl_deus, la_decl_domus, la_decl_iesus, la_decl_sus, la_decl_venum, la_decl_vis :: [Inflection]
la_decl_agnus = [
nom_sg "agnus",
gen_sg "agnnī",
dat_sg "agnō",
acc_sg "agnum",
abl_sg "agnō",
voc_sg "agne",
nom_pl "agnī",
gen_pl "agnūs",
dat_pl "agnīs",
acc_pl "agnōs",
abl_pl "agnīs",
voc_pl "agnī" ]
la_decl_bos = [
nom_sg "bōs",
gen_sg "bovis",
dat_sg "bovī",
acc_sg "bovem",
abl_sg "bove",
voc_sg "bōs",
nom_pl "bovēs",
gen_pl "boum",
dat_pl "bōbus",
acc_pl "bovēs",
abl_pl "bōbus",
voc_pl "bovēs" ]
la_decl_deus = [
nom_sg "deus",
gen_sg "deī",
dat_sg "deō",
acc_sg "deum",
abl_sg "deō",
voc_sg "deus",
nom_pl "dī",
gen_pl "deorum",
dat_pl "dīs",
acc_pl "denōs",
abl_pl "dīs",
voc_pl "dī"]
la_decl_domus = [
nom_sg "domus",
gen_sg "domūs",
dat_sg "domuī",
acc_sg "domum",
abl_sg "domū",
voc_sg "domī",
nom_pl "domūs",
gen_pl "domuum",
dat_pl "domibus",
acc_pl "domūs",
abl_pl "domibus",
voc_pl "domīs"]
la_decl_iesus = [
nom_sg "Iēsus",
gen_sg "Iēsū",
dat_sg "Iēsū",
acc_sg "Iēsum",
abl_sg "Iēsū",
voc_sg "Iēsū"]
la_decl_sus = [
nom_sg "sūs",
gen_sg "sū",
dat_sg "sū",
acc_sg "sum",
abl_sg "sū",
voc_sg "sū"]
la_decl_venum = [
dat_sg "vēnuī",
acc_sg "vēnum"]
la_decl_vis = [
nom_sg "vīs",
gen_sg "vīs",
dat_sg "vī",
acc_sg "vim",
abl_sg "vī",
voc_sg "vīs",
nom_pl "vīrēs",
gen_pl "vīrium",
dat_pl "vīribus",
acc_pl "vīrēs",
abl_pl "vīribus",
voc_pl "vīrēs"]
| richardlarocque/latin-db-builder | Wiki/Latin/NounDecl.hs | gpl-3.0 | 23,126 | 936 | 17 | 3,444 | 9,682 | 5,435 | 4,247 | 629 | 4 |
module Main where
import Math.Cuba
myIntegrand :: Integrand
myIntegrand xs d | length xs /= 3 = undefined
| otherwise =
[x, (sin x) * (cos y) * (exp z), x, x**2, x**6 * y * z, s] where
[x, y, z] = xs
(s) = d
main :: IO()
main = do
let results = vegas 3 6 myIntegrand (1) 0.01 0
print results
| waterret/Cuba-haskell | src/Main.hs | gpl-3.0 | 342 | 0 | 11 | 115 | 178 | 93 | 85 | 12 | 1 |
{-# LANGUAGE QuasiQuotes, OverloadedStrings #-}
module Templates (indexTpl, notFoundTpl, doneTpl, infoTpl) where
import Text.Hamlet
import Data.Text.Lazy as T
import System.Locale (defaultTimeLocale, rfc822DateFormat)
import Data.Time.Format (formatTime)
import Data.Time.Clock (UTCTime)
import Data.Monoid
import Styles (mainCss)
base_ :: Html -> Text -> Text -> Html
base_ body title style = [shamlet|
$doctype 5
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<style>
#{style}
<title>hsUrlShort — #{title}
<body>
<div class="container">
#{body}
|]
base :: Html -> Text -> Html
base body title = base_ body title mainCss
indexTpl :: Html
indexTpl = base body "Main page"
where body = [shamlet|
<form class="form-urlshort" action="/" method="post">
<h2 class="form-shorturl-heading">Type your URL
<label for="inputUrl" class="sr-only">Url to short
<input name="url" type="url" id="inputUrl" class="form-control" placeholder="Url to short" required autofocus />
<button class="btn btn-lg btn-primary btn-block" type="submit">Shorten!
|]
notFoundTpl :: Html
notFoundTpl = base body "404 Not Found"
where body = [shamlet|
<h1>404 Not Found
<p>Sorry, but we can't find requested URL.
|]
doneTpl :: Text -> Html
doneTpl url = base body "Get your URL"
where body = [shamlet|
<h1>Get your shortened link
<p>http://localhost:3000/s/#{url}
|]
infoTpl :: UTCTime -> Int -> Text -> Text -> Html
infoTpl time clicks url key = base body ("Information about #" <> key)
where body = [shamlet|
<h2>Some information about shortened url
<ul>
<li>
<b>Real URL:
<a href="#{url}">#{url}
<li>
<b>Created:
#{formatTime defaultTimeLocale rfc822DateFormat time}
<li>
<b>Clicks:
#{show clicks}
|]
| nico-izo/hsUrlShort | src/Templates.hs | gpl-3.0 | 2,179 | 0 | 8 | 482 | 286 | 169 | 117 | 25 | 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.IAM.Projects.ServiceAccounts.Create
-- 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)
--
-- Creates a ServiceAccount and returns it.
--
-- /See:/ <https://cloud.google.com/iam/ Google Identity and Access Management (IAM) API Reference> for @iam.projects.serviceAccounts.create@.
module Network.Google.Resource.IAM.Projects.ServiceAccounts.Create
(
-- * REST Resource
ProjectsServiceAccountsCreateResource
-- * Creating a Request
, projectsServiceAccountsCreate
, ProjectsServiceAccountsCreate
-- * Request Lenses
, psacXgafv
, psacUploadProtocol
, psacPp
, psacAccessToken
, psacUploadType
, psacPayload
, psacBearerToken
, psacName
, psacCallback
) where
import Network.Google.IAM.Types
import Network.Google.Prelude
-- | A resource alias for @iam.projects.serviceAccounts.create@ method which the
-- 'ProjectsServiceAccountsCreate' request conforms to.
type ProjectsServiceAccountsCreateResource =
"v1" :>
Capture "name" Text :>
"serviceAccounts" :>
QueryParam "$.xgafv" Text :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] CreateServiceAccountRequest :>
Post '[JSON] ServiceAccount
-- | Creates a ServiceAccount and returns it.
--
-- /See:/ 'projectsServiceAccountsCreate' smart constructor.
data ProjectsServiceAccountsCreate = ProjectsServiceAccountsCreate'
{ _psacXgafv :: !(Maybe Text)
, _psacUploadProtocol :: !(Maybe Text)
, _psacPp :: !Bool
, _psacAccessToken :: !(Maybe Text)
, _psacUploadType :: !(Maybe Text)
, _psacPayload :: !CreateServiceAccountRequest
, _psacBearerToken :: !(Maybe Text)
, _psacName :: !Text
, _psacCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ProjectsServiceAccountsCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'psacXgafv'
--
-- * 'psacUploadProtocol'
--
-- * 'psacPp'
--
-- * 'psacAccessToken'
--
-- * 'psacUploadType'
--
-- * 'psacPayload'
--
-- * 'psacBearerToken'
--
-- * 'psacName'
--
-- * 'psacCallback'
projectsServiceAccountsCreate
:: CreateServiceAccountRequest -- ^ 'psacPayload'
-> Text -- ^ 'psacName'
-> ProjectsServiceAccountsCreate
projectsServiceAccountsCreate pPsacPayload_ pPsacName_ =
ProjectsServiceAccountsCreate'
{ _psacXgafv = Nothing
, _psacUploadProtocol = Nothing
, _psacPp = True
, _psacAccessToken = Nothing
, _psacUploadType = Nothing
, _psacPayload = pPsacPayload_
, _psacBearerToken = Nothing
, _psacName = pPsacName_
, _psacCallback = Nothing
}
-- | V1 error format.
psacXgafv :: Lens' ProjectsServiceAccountsCreate (Maybe Text)
psacXgafv
= lens _psacXgafv (\ s a -> s{_psacXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
psacUploadProtocol :: Lens' ProjectsServiceAccountsCreate (Maybe Text)
psacUploadProtocol
= lens _psacUploadProtocol
(\ s a -> s{_psacUploadProtocol = a})
-- | Pretty-print response.
psacPp :: Lens' ProjectsServiceAccountsCreate Bool
psacPp = lens _psacPp (\ s a -> s{_psacPp = a})
-- | OAuth access token.
psacAccessToken :: Lens' ProjectsServiceAccountsCreate (Maybe Text)
psacAccessToken
= lens _psacAccessToken
(\ s a -> s{_psacAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
psacUploadType :: Lens' ProjectsServiceAccountsCreate (Maybe Text)
psacUploadType
= lens _psacUploadType
(\ s a -> s{_psacUploadType = a})
-- | Multipart request metadata.
psacPayload :: Lens' ProjectsServiceAccountsCreate CreateServiceAccountRequest
psacPayload
= lens _psacPayload (\ s a -> s{_psacPayload = a})
-- | OAuth bearer token.
psacBearerToken :: Lens' ProjectsServiceAccountsCreate (Maybe Text)
psacBearerToken
= lens _psacBearerToken
(\ s a -> s{_psacBearerToken = a})
-- | Required. The resource name of the project associated with the service
-- accounts, such as \`projects\/my-project-123\`.
psacName :: Lens' ProjectsServiceAccountsCreate Text
psacName = lens _psacName (\ s a -> s{_psacName = a})
-- | JSONP
psacCallback :: Lens' ProjectsServiceAccountsCreate (Maybe Text)
psacCallback
= lens _psacCallback (\ s a -> s{_psacCallback = a})
instance GoogleRequest ProjectsServiceAccountsCreate
where
type Rs ProjectsServiceAccountsCreate =
ServiceAccount
type Scopes ProjectsServiceAccountsCreate =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsServiceAccountsCreate'{..}
= go _psacName _psacXgafv _psacUploadProtocol
(Just _psacPp)
_psacAccessToken
_psacUploadType
_psacBearerToken
_psacCallback
(Just AltJSON)
_psacPayload
iAMService
where go
= buildClient
(Proxy ::
Proxy ProjectsServiceAccountsCreateResource)
mempty
| rueshyna/gogol | gogol-iam/gen/Network/Google/Resource/IAM/Projects/ServiceAccounts/Create.hs | mpl-2.0 | 6,222 | 0 | 19 | 1,503 | 934 | 542 | 392 | 135 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-
Copyright 2020 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module ErrorSanitizer (rewriteErrors) where
import Data.List
import Data.Text (Text)
import RegexShim (replace)
rewriteStages :: [(Text, Text)]
rewriteStages =
[ ("\8216", ""),
("\8217", ""),
("warning: ([a-zA-Z,0-9 ]*)\\[-Wdefer[a-z-]*\\]", "error: \\1"),
(" \\[-W[a-z-]*\\]", ""),
("IO action main", "variable program"),
("main IO action", "variable"),
("exported by", "defined in"),
("bound at program[.]hs", "defined at program.hs"),
("module Main", "your code"),
("main\\:Main", "your code"),
("[ ]*\8226 Possible cause: [(].*[)] is applied to too many arguments\n", ""),
("[ ]*except perhaps to import instances from [A-Za-z0-9.]*\n", ""),
("[ ]*To import instances alone, use: import [A-Za-z0-9.]*[(][)]\n", ""),
( "^([ ]*(\8226 )?)(.*[Nn]ot in scope: .* :: Text)",
"\\1\\3\n\\1Perhaps you meant to put quotation marks around this text."
),
("is applied to too few arguments", "is missing arguments"),
("is applied to too many arguments", "is a value, but a function is needed here."),
( "Couldn't match expected type Text\\s*with actual type GHC.Types.Char",
"Text requires double quotes, rather than single."
),
("[ ]*Perhaps you intended to use TemplateHaskell or TemplateHaskellQuotes\n", ""),
( "(program.hs:[0-9]*:1:(.|\n )*) [(]possibly incorrect indentation or mismatched brackets[)]",
"\\1\n \8226 If this line continues the previous definition, indent it."
<> "\n \8226 Otherwise, are you missing a parenthesis on the previous line)?"
),
( " [(]possibly incorrect indentation or mismatched brackets[)]",
"\n \8226 Are you missing a parenthesis?"
),
( "In the Template Haskell quotation '.*'",
"Use double quotes around text values."
),
("[ ]+\8226 In ([^\n\8226]|\n )+\n", ""),
("(( |\n)*)base-[0-9.]*:GHC\\.Stack\\.Types\\.HasCallStack =>( |\n)*", " "),
( "When checking that:\\s*[^\n]*\\s*is more polymorphic than:\\s*[^\n]*(\n\\s*)?",
""
),
( "Perhaps you need a 'let' in a 'do' block[?][ \t\n]*e.g. '[^']*' instead of '[^']*'",
"An equation does not fit here. Is this line indented incorrectly?"
),
( "[pP]arse error on input import\n",
"Parse error\n Import statements belong at the beginning of your code.\n"
),
("\\[GHC\\.Types\\.Char\\] -> ", "\n"),
("base(-[0-9.]*)?\\:.*( |\n)*->( |\n)*", "\n"),
("integer-gmp(-[0-9\\.]*)?:(.|\n)*->( |\n)*", ""),
("GHC\\.[A-Za-z.]*(\\s|\n)*->( |\n)*", ""),
("at src/[A-Za-z0-9\\/.:]*", ""),
("\\[GHC\\.Types\\.Char\\]", ""),
("codeworld-base[-.:_A-Za-z0-9]*", "the standard library"),
("Main\\.", ""),
("main :: t", "program"),
("Prelude\\.", ""),
("\\bBool\\b", "Truth"),
("IO \\(\\)", "Program"),
("IO [a-z][a-zA-Z0-9_]*", "Program"),
("[ ]*Perhaps you intended to use TemplateHaskell\n", ""),
("imported from [^)\n]*", "defined in the standard library"),
("( |\n)*[(]and originally defined in [^)]*[)]", ""),
("the first argument", "the argument(s)"),
( "[ ]*The function [a-zA-Z0-9_]* is applied to [a-z0-9]* arguments,\n",
""
),
("[ ]*but its type .* has only .*\n", ""),
( "A data constructor of that name is in scope; did you mean DataKinds\\?",
"That name refers to a value, not a type."
),
("type constructor or class", "type"),
( "Illegal tuple section: use TupleSections",
"This tuple is missing a value, or has an extra comma."
),
("in string/character literal", "in text literal"),
( "lexical error in text literal at end of input",
"Missing the end quotation mark for a Text value."
),
( "lexical error in text literal at character '\\\\n'",
"Missing the end quotation mark for a Text value."
),
( "lexical error at character '\\\\822[01]'",
"Smart quotes are not allowed."
),
("[(]main[)]", "program"),
("\\bmain\\b", "program"),
("a pattern binding", "the definition"),
("Use -v to see a list of the files searched for\\.", ""),
("Could not load module", "Could not find module"),
("[ ]*It is a member of the hidden package [^\n]*\n", ""),
("[ ]*You can run :set [^\n]*\n", ""),
("[ ]*[(]Note: this unloads all the modules in the current scope[.][)]\n", ""),
("^ Where: [^\n]*rigid type variable[^\n]*\n( [^\n]*\n)*", ""),
(" \8226 Relevant bindings include\n( [^\n]*\n)*", ""),
(" \8226 Relevant bindings include [^\n]*\n", ""),
(" Valid hole fits include", " \8226 Valid hole fits include"),
("^[ ]+with [^\n]+@[^\n]+\n", ""),
("[(]Some hole fits suppressed; use -fmax-valid-hole-fits=N or -fno-max-valid-hole-fits[)]", "..."),
("CallStack \\(from HasCallStack\\):", "When evaluating:"),
(", called at program.hs:", ", used at program.hs:"),
( "module header, import declaration\n or top-level declaration expected.",
"An equation was expected here.\n Are you missing the equal sign?"
),
("forall( [a-z0-9]+)*[.] ", ""),
("^<<loop>>$", "Stuck because your code contains a circular definition."),
("\n\\s+\n", "\n")
]
rewriteErrors :: Text -> Text
rewriteErrors output = foldl' applyStage output rewriteStages
where
applyStage s (pattern, sub) = replace pattern sub s
| google/codeworld | codeworld-error-sanitizer/src/ErrorSanitizer.hs | apache-2.0 | 5,997 | 0 | 8 | 1,281 | 754 | 493 | 261 | 98 | 1 |
module Main where
import Control.Monad (forM_)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.MarkovChain (runMulti)
import Data.Serialize (decode)
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Text.Encoding (decodeUtf8)
import System.Random (getStdGen)
-- makeSomeStories :: [Text] -> IO ()
-- makeSomeStories storiesList = do
-- stdGen <- getStdGen
-- runMulti
makeSomeStories :: [(Int, ByteString)] -> IO ()
makeSomeStories storiesList = do
let byteStringTitles = fmap snd storiesList
stringTitles = fmap (Text.unpack . decodeUtf8) byteStringTitles
stdGen <- getStdGen
-- forM_ stringTitles print
forM_ (take 100 $ runMulti 5 stringTitles 0 stdGen) print
main :: IO ()
main = do
serializedList <- BS.getContents
let decodedList = decode serializedList
case decodedList of
Left err ->
putStrLn $
"ERROR: Failed to decode the input string with the " ++
"following error: " ++ err
Right storiesList -> makeSomeStories storiesList
| cdepillabout/hn-markov-headlines | src/CreateMain.hs | apache-2.0 | 1,131 | 0 | 13 | 273 | 270 | 146 | 124 | 26 | 2 |
{-
Copyright (c) Facebook, Inc. and its affiliates.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module BinaryTests where
import Test.QuickCheck
import Thrift.Protocol.Binary
import Util
main :: IO ()
main = aggregateResults
[ quickCheckResult $ propRoundTrip BinaryProtocol
, quickCheckResult $ propRoundTripMessage BinaryProtocol
]
| facebook/fbthrift | thrift/lib/hs/tests/BinaryTests.hs | apache-2.0 | 862 | 0 | 8 | 166 | 57 | 32 | 25 | 8 | 1 |
{-# LANGUAGE OverloadedStrings #-}
------------------------------------------------------------
-- Copyright : Erik de Castro Lopo <[email protected]>
-- License : BSD3
------------------------------------------------------------
module Test.HttpHttpsRewriteTest
( httpToHttpsRewriteTest
)
where
import Control.Concurrent (forkIO, killThread)
import Control.Monad (when)
import Control.Monad.IO.Class (liftIO)
import Data.ByteString (ByteString)
import qualified Network.HTTP.Conduit as HC
import qualified Network.HTTP.Types as HT
import Network.HTTP.Proxy
import Test.TestServer
import qualified Test.Util as U
debug :: Bool
debug = False
httpToHttpsRewriteTest :: IO ()
httpToHttpsRewriteTest = do
U.printTestMsgR "Rewrite HTTP to HTTPS test"
-- Don't need to do anything with these ThreadIds
t1 <- forkIO $ runTestServerTLS U.httpTestPort
t2 <- forkIO $ runProxySettings proxySettings
mapM_ (testSingleUrl debug) tests
U.printPassR
killThread t1
killThread t2
where
proxySettings = defaultSettings
{ proxyPort = U.testProxyPort
, proxyHost = "*6"
, proxyRequestModifier = Just httpsRedirector
}
tests =
[ ( HT.methodGet, "localhost", U.httpTestPort, "/", Nothing )
, ( HT.methodPost, "localhost", U.httpTestPort, "/", Nothing )
, ( HT.methodPost, "localhost", U.httpTestPort, "/", Just "Message\n" )
, ( HT.methodGet, "localhost", U.httpTestPort, "/forbidden", Nothing )
]
httpsRedirector :: Request -> IO Request
httpsRedirector _req = error "httpRedirector"
{-
| serverName req == "localhost" && not (isSecure req) = do
return $ req
{ isSecure = True
, serverPort = U.httpTestPort
}
| otherwise = return req
-}
--------------------------------------------------------------------------------
type TestRequest = ( HT.Method, String, Int, String, Maybe ByteString )
testSingleUrl :: Bool -> TestRequest -> IO ()
testSingleUrl dbg testreq = do
(dreq, preq) <- liftIO $ setupRequest testreq
when dbg $ liftIO $ do
U.dumpHttpConduitRequest dreq
U.dumpHttpConduitRequest preq
direct <- U.httpRun dreq
proxy <- U.httpRun $ HC.addProxy "localhost" U.testProxyPort preq
when dbg $ liftIO $ do
U.printResult direct
U.printResult proxy
U.compareResult direct proxy
setupRequest :: TestRequest -> IO (HC.Request, HC.Request)
setupRequest (method, host, port, path, reqBody) = do
req <- HC.parseUrl $ "http://" ++ host ++ ":" ++ show port ++ path
return
( req
{ HC.method = method
, HC.secure = True
, HC.port = if HC.port req == 443 then 443 else HC.port req
, HC.requestBody = case reqBody of
Just x -> HC.RequestBodyBS x
Nothing -> HC.requestBody req
-- In this test program we want to pass error pages back to the test
-- function so the error output can be compared.
, HC.checkStatus = \ _ _ _ -> Nothing
}
, req
{ HC.method = method
, HC.secure = False
, HC.port = if HC.port req == 80 then 80 else HC.port req
, HC.requestBody = case reqBody of
Just x -> HC.RequestBodyBS x
Nothing -> HC.requestBody req
-- In this test program we want to pass error pages back to the test
-- function so the error output can be compared.
, HC.checkStatus = \ _ _ _ -> Nothing
}
)
| olorin/http-proxy | Test/HttpHttpsRewriteTest.hs | bsd-2-clause | 3,739 | 0 | 15 | 1,115 | 823 | 447 | 376 | 67 | 5 |
module Main where
import ECC.Tester
import ECC.Types
import Data.Monoid
import qualified ECC.Code.BPSK as BPSK
import qualified ECC.Code.LDPC.Reference as Reference
import qualified ECC.Code.LDPC.ElimTanh as ElimTanh
import qualified ECC.Code.LDPC.Accelerate as Accelerate
codes :: Code
codes = BPSK.code <> Reference.code <> Accelerate.code
-- usage: ./Main 0 2 4 6 8 0 bpsk
-- or, to run the LDPC reference implementation, at a single EBNO = 2.2
-- ./Main 2.2 ldpc/reference/jpl.1K/20
main :: IO ()
main = eccMain codes eccPrinter
| ku-fpg/ecc-ldpc-accelerate | main/Main.hs | bsd-2-clause | 546 | 0 | 7 | 89 | 105 | 69 | 36 | 12 | 1 |
module Concurrent.Unamb where
import Concurrent.Unamb.Unsafe
unamb_ :: a -> b -> ()
unamb_ x y = unamb (seq x ()) (seq y ())
| ekmett/concurrent | src/Concurrent/Unamb.hs | bsd-2-clause | 127 | 0 | 8 | 25 | 62 | 33 | 29 | 4 | 1 |
module Test.LifeTest where
import Life.Type
import Life.CountAlive
import Test.HUnit
game1 = Lifegame { size = 3, board = []}
game2 = Lifegame { size = 3, board = [(1,1)]}
game3 = Lifegame { size = 3, board = [(1,1), (1,2), (2,1)]}
game4 = Lifegame { size = 3, board = [(1,1), (1,2), (2,1), (2,3)]}
game5 = Lifegame { size = 3, board = [(1,1), (1,2), (1,3), (2,1), (2,3)]}
game6 = Lifegame { size = 3, board = [(1,1), (1,2), (1,3), (2,1), (2,3), (3,1)]}
game7 = Lifegame { size = 3, board = [(1,1), (1,2), (1,3), (2,1), (2,3), (3,1), (3,2)]}
game8 = Lifegame { size = 3, board = [(1,1), (1,2), (1,3), (2,1), (2,3), (3,1), (3,2), (3,3)]}
test1 = TestCase(assertEqual "countAlive (2,2) game1," 0 (countAlive (2,2) game1))
test2 = TestCase(assertEqual "countAlive (2,2) game2," 1 (countAlive (2,2) game2))
test3 = TestCase(assertEqual "countAlive (2,2) game3," 3 (countAlive (2,2) game3))
test4 = TestCase(assertEqual "countAlive (2,2) game4," 4 (countAlive (2,2) game4))
test5 = TestCase(assertEqual "countAlive (2,2) game5," 5 (countAlive (2,2) game5))
test6 = TestCase(assertEqual "countAlive (2,2) game6," 6 (countAlive (2,2) game6))
test7 = TestCase(assertEqual "countAlive (2,2) game7," 7 (countAlive (2,2) game7))
test8 = TestCase(assertEqual "countAlive (2,2) game8," 8 (countAlive (2,2) game8))
tests = TestList[TestLabel "test1" test1,
TestLabel "test2" test2,
TestLabel "test3" test3,
TestLabel "test4" test4,
TestLabel "test5" test5,
TestLabel "test6" test6,
TestLabel "test7" test7,
TestLabel "test8" test8]
| nichiyoubi/lifegame | src/Test/LifeTest.hs | bsd-3-clause | 1,573 | 14 | 10 | 277 | 823 | 493 | 330 | 28 | 1 |
{-# LANGUAGE CPP, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- | Extra functions for "Control.Concurrent".
--
-- This module includes three new types of 'MVar', namely 'Lock' (no associated value),
-- 'Var' (never empty) and 'Barrier' (filled at most once). See
-- <http://neilmitchell.blogspot.co.uk/2012/06/flavours-of-mvar_04.html this blog post>
-- for examples and justification.
--
-- If you need greater control of exceptions and threads
-- see the <http://hackage.haskell.org/package/slave-thread slave-thread> package.
-- If you need elaborate relationships between threads
-- see the <http://hackage.haskell.org/package/async async> package.
module Control.Concurrent.Extra(
module Control.Concurrent,
getNumCapabilities, setNumCapabilities, withNumCapabilities,
forkFinally, once, onceFork,
-- * Lock
Lock, newLock, withLock, withLockTry,
-- * Var
Var, newVar, readVar, modifyVar, modifyVar_, withVar,
-- * Barrier
Barrier, newBarrier, signalBarrier, waitBarrier, waitBarrierMaybe,
) where
import Control.Concurrent
import Control.Exception.Extra
import Control.Monad.Extra
import Data.Maybe
-- | On GHC 7.6 and above with the @-threaded@ flag, brackets a call to 'setNumCapabilities'.
-- On lower versions (which lack 'setNumCapabilities') this function just runs the argument action.
withNumCapabilities :: Int -> IO a -> IO a
withNumCapabilities new act | rtsSupportsBoundThreads = do
old <- getNumCapabilities
if old == new then act else
bracket_ (setNumCapabilities new) (setNumCapabilities old) act
withNumCapabilities _ act = act
#if __GLASGOW_HASKELL__ < 702
-- | A version of 'getNumCapabilities' that works on all versions of GHC, but returns 1 before GHC 7.2.
getNumCapabilities :: IO Int
getNumCapabilities = return 1
#endif
#if __GLASGOW_HASKELL__ < 706
-- | A version of 'setNumCapabilities' that works on all versions of GHC, but has no effect before GHC 7.6.
setNumCapabilities :: Int -> IO ()
setNumCapabilities n = return ()
#endif
#if __GLASGOW_HASKELL__ < 706
-- | fork a thread and call the supplied function when the thread is about
-- to terminate, with an exception or a returned value. The function is
-- called with asynchronous exceptions masked.
--
-- @
-- forkFinally action and_then =
-- mask $ \restore ->
-- forkIO $ try (restore action) >>= and_then
-- @
--
-- This function is useful for informing the parent when a child
-- terminates, for example.
forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId
forkFinally action and_then =
mask $ \restore ->
forkIO $ try (restore action) >>= and_then
#endif
-- | Given an action, produce a wrapped action that runs at most once.
-- If the function raises an exception, the same exception will be reraised each time.
--
-- > let x ||| y = do t1 <- onceFork x; t2 <- onceFork y; t1; t2
-- > \(x :: IO Int) -> void (once x) == return ()
-- > \(x :: IO Int) -> join (once x) == x
-- > \(x :: IO Int) -> (do y <- once x; y; y) == x
-- > \(x :: IO Int) -> (do y <- once x; y ||| y) == x
once :: IO a -> IO (IO a)
once act = do
var <- newVar OncePending
let run = either throwIO return
return $ mask $ \unmask -> join $ modifyVar var $ \v -> case v of
OnceDone x -> return (v, unmask $ run x)
OnceRunning x -> return (v, unmask $ run =<< waitBarrier x)
OncePending -> do
b <- newBarrier
return $ (OnceRunning b,) $ do
res <- try_ $ unmask act
signalBarrier b res
modifyVar_ var $ \_ -> return $ OnceDone res
run res
data Once a = OncePending | OnceRunning (Barrier a) | OnceDone a
-- | Like 'once', but immediately starts running the computation on a background thread.
--
-- > \(x :: IO Int) -> join (onceFork x) == x
-- > \(x :: IO Int) -> (do a <- onceFork x; a; a) == x
onceFork :: IO a -> IO (IO a)
onceFork act = do
bar <- newBarrier
forkFinally act $ signalBarrier bar
return $ either throwIO return =<< waitBarrier bar
---------------------------------------------------------------------
-- LOCK
-- | Like an MVar, but has no value.
-- Used to guarantees single-threaded access, typically to some system resource.
-- As an example:
--
-- @
-- lock <- 'newLock'
-- let output = 'withLock' . putStrLn
-- forkIO $ do ...; output \"hello\"
-- forkIO $ do ...; output \"world\"
-- @
--
-- Here we are creating a lock to ensure that when writing output our messages
-- do not get interleaved. This use of MVar never blocks on a put. It is permissible,
-- but rare, that a withLock contains a withLock inside it - but if so,
-- watch out for deadlocks.
newtype Lock = Lock (MVar ())
-- | Create a new 'Lock'.
newLock :: IO Lock
newLock = fmap Lock $ newMVar ()
-- | Perform some operation while holding 'Lock'. Will prevent all other
-- operations from using the 'Lock' while the action is ongoing.
withLock :: Lock -> IO a -> IO a
withLock (Lock x) = withMVar x . const
-- | Like 'withLock' but will never block. If the operation cannot be executed
-- immediately it will return 'Nothing'.
withLockTry :: Lock -> IO a -> IO (Maybe a)
withLockTry (Lock m) act = bracket
(tryTakeMVar m)
(\v -> when (isJust v) $ putMVar m ())
(\v -> if isJust v then fmap Just act else return Nothing)
---------------------------------------------------------------------
-- VAR
-- | Like an MVar, but must always be full.
-- Used to on a mutable variable in a thread-safe way.
-- As an example:
--
-- @
-- hits <- 'newVar' 0
-- forkIO $ do ...; 'modifyVar_' hits (+1); ...
-- i <- 'readVar' hits
-- print ("HITS",i)
-- @
--
-- Here we have a variable which we modify atomically, so modifications are
-- not interleaved. This use of MVar never blocks on a put. No modifyVar
-- operation should ever block, and they should always complete in a reasonable
-- timeframe. A Var should not be used to protect some external resource, only
-- the variable contained within. Information from a readVar should not be subsequently
-- inserted back into the Var.
newtype Var a = Var (MVar a)
-- | Create a new 'Var' with a value.
newVar :: a -> IO (Var a)
newVar = fmap Var . newMVar
-- | Read the current value of the 'Var'.
readVar :: Var a -> IO a
readVar (Var x) = readMVar x
-- | Modify a 'Var' producing a new value and a return result.
modifyVar :: Var a -> (a -> IO (a, b)) -> IO b
modifyVar (Var x) f = modifyMVar x f
-- | Modify a 'Var', a restricted version of 'modifyVar'.
modifyVar_ :: Var a -> (a -> IO a) -> IO ()
modifyVar_ (Var x) f = modifyMVar_ x f
-- | Perform some operation using the value in the 'Var',
-- a restricted version of 'modifyVar'.
withVar :: Var a -> (a -> IO b) -> IO b
withVar (Var x) f = withMVar x f
---------------------------------------------------------------------
-- BARRIER
-- | Starts out empty, then is filled exactly once. As an example:
--
-- @
-- bar <- 'newBarrier'
-- forkIO $ do ...; val <- ...; 'signalBarrier' bar val
-- print =<< 'waitBarrier' bar
-- @
--
-- Here we create a barrier which will contain some computed value.
-- A thread is forked to fill the barrier, while the main thread waits
-- for it to complete. A barrier has similarities to a future or promise
-- from other languages, has been known as an IVar in other Haskell work,
-- and in some ways is like a manually managed thunk.
newtype Barrier a = Barrier (Var (Either (MVar ()) a))
-- Either a Left empty MVar you should wait or a Right result
-- With base 4.7 and above readMVar is atomic so you probably can implement Barrier directly on MVar a
-- | Create a new 'Barrier'.
newBarrier :: IO (Barrier a)
newBarrier = fmap Barrier $ newVar . Left =<< newEmptyMVar
-- | Write a value into the Barrier, releasing anyone at 'waitBarrier'.
-- Any subsequent attempts to signal the 'Barrier' will throw an exception.
signalBarrier :: Barrier a -> a -> IO ()
signalBarrier (Barrier var) v = mask_ $ do -- use mask so never in an inconsistent state
join $ modifyVar var $ \x -> case x of
Left bar -> return (Right v, putMVar bar ())
Right res -> error "Control.Concurrent.Extra.signalBarrier, attempt to signal a barrier that has already been signaled"
-- | Wait until a barrier has been signaled with 'signalBarrier'.
waitBarrier :: Barrier a -> IO a
waitBarrier (Barrier var) = do
x <- readVar var
case x of
Right res -> return res
Left bar -> do
readMVar bar
x <- readVar var
case x of
Right res -> return res
Left bar -> error "Cortex.Concurrent.Extra, internal invariant violated in Barrier"
-- | A version of 'waitBarrier' that never blocks, returning 'Nothing'
-- if the barrier has not yet been signaled.
waitBarrierMaybe :: Barrier a -> IO (Maybe a)
waitBarrierMaybe (Barrier bar) = fmap (either (const Nothing) Just) $ readVar bar
| mgmeier/extra | src/Control/Concurrent/Extra.hs | bsd-3-clause | 9,004 | 0 | 22 | 1,964 | 1,506 | 803 | 703 | 89 | 3 |
{-# LANGUAGE
DefaultSignatures
, ExplicitForAll
, FlexibleContexts
, ScopedTypeVariables
#-}
module Graphics.QML.MarshalObj where
import Graphics.QML.MarshalObj.Internal
import Control.Monad
import Data.Proxy
import GHC.Generics
import Graphics.QML
marshalObj :: MarshalObj t => t -> IO AnyObjRef
marshalObj = return.anyObjRef <=< (`newObject` ()) <=< newClass.marshalObj'
class MarshalObj t where
marshalObj' :: t -> [Member ()]
default marshalObj' :: (Generic t, GMarshalObj (Rep t)) => t -> [Member ()]
marshalObj' = gMarshalObj.from
| marcinmrotek/hsqml-marshal | src/Graphics/QML/MarshalObj.hs | bsd-3-clause | 564 | 0 | 12 | 93 | 152 | 85 | 67 | -1 | -1 |
import Text.Read
operators :: [(String, Integer -> Integer -> Integer)]
operators = [("+", (+)), ("-", (-)), ("*", (*)), ("/", div)]
polish :: [String] -> Maybe [Integer]
polish [] = Just []
polish (s : ss) = case lookup s operators of
Just o -> case polish ss of
Just (x : y : ns) -> Just $ x `o` y : ns
_ -> Nothing
Nothing -> case readMaybe s of
Just n -> fmap (n :) $ polish ss
Nothing -> Nothing
| YoshikuniJujo/funpaala | samples/15_fold/polish0.hs | bsd-3-clause | 413 | 0 | 14 | 95 | 230 | 126 | 104 | 12 | 4 |
{-# LANGUAGE RankNTypes, FlexibleContexts, NamedFieldPuns, ViewPatterns,OverloadedStrings #-}
{-|
-}
module Main where
import qualified Blaze.ByteString.Builder.Char.Utf8 as BZ
import System.Environment (getArgs)
import LivingFlame.Monad
import LivingFlame.Job
import LivingFlame.Trigger
main :: IO ()
main = do
[baseDir] <- getArgs
conf <- mkDefaultEnv baseDir
flip runLivingFlame conf $ do
putLog $ BZ.fromText "=========== Startup"
--
--
putLog $ BZ.fromText "=========== Terminate"
return ()
{-|
-}
| seagull-kamome/living-flame | src/Main.hs | bsd-3-clause | 553 | 0 | 12 | 111 | 124 | 67 | 57 | 15 | 1 |
module HJS.Parser.JavaScript where
class EmitHaskell a where
eHs :: a -> String
data Literal = LitInt Int
| LitString String
| LitNull
| LitBool Bool
deriving Show
data PrimExpr
= Literal Literal
| Ident String
| Brack Expr
| This
| Regex (String,String)
| Array ArrayLit
| Object [Either (PropName, AssignE) GetterPutter ]
| PEFuncDecl FuncDecl
deriving Show
data GetterPutter =
GetterPutter PropName FuncDecl | Putter FuncDecl deriving Show
data PropName = PropNameId String | PropNameStr String | PropNameInt Int
deriving Show
data ArrayLit = ArrSimple [AssignE]
deriving Show
data MemberExpr = MemPrimExpr PrimExpr
| ArrayExpr MemberExpr Expr
| MemberNew MemberExpr [AssignE]
| MemberCall MemberExpr String
| MemberCall2 MemberExpr MemberExpr
deriving Show
data CallExpr = CallPrim MemberExpr
| CallMember MemberExpr [AssignE]
| CallCall CallExpr [AssignE]
| CallSquare CallExpr Expr
| CallDot CallExpr String
deriving Show
data NewExpr = MemberExpr MemberExpr
| NewNewExpr NewExpr
deriving Show
data LeftExpr = NewExpr NewExpr
| CallExpr CallExpr
deriving Show
data PostFix = LeftExpr LeftExpr
| PostInc LeftExpr
| PostDec LeftExpr
deriving Show
data UExpr = PostFix PostFix
| Delete UExpr
| Void UExpr
| TypeOf UExpr
| DoublePlus UExpr
| DoubleMinus UExpr
| UnaryPlus UExpr
| UnaryMinus UExpr
| Not UExpr
| BitNot UExpr
deriving Show
{--
data MultExpr = UExpr UExpr
| Times MultExpr UExpr
| Div MultExpr UExpr
| Mod MultExpr UExpr deriving Show
data AddExpr = MultExpr MultExpr
| Plus AddExpr MultExpr
| Minus AddExpr MultExpr
deriving Show
data ShiftE = AddExpr AddExpr
| ShiftLeft ShiftE AddExpr
| ShiftRight ShiftE AddExpr
| ShiftRight2 ShiftE AddExpr
deriving Show
data RelE = ShiftE ShiftE
| LessThan RelE ShiftE
| GreaterThan RelE ShiftE
| LessEqual RelE ShiftE
| GreaterEqual RelE ShiftE
| InstanceOf RelE ShiftE
| InObject RelE ShiftE
deriving Show
data EqualE = RelE RelE
| Equal EqualE RelE
| NotEqual EqualE RelE
| Equal2 EqualE RelE
| NotEqual2 EqualE RelE
deriving Show
data BitAnd = EqualE EqualE
| BABitAnd BitAnd EqualE
deriving Show
data BitXOR = BitAnd BitAnd
| BXBitXOR BitXOR BitAnd
deriving Show
data BitOR = BitXOR BitXOR
| BOBitOR BitOR BitXOR
deriving Show
data LogAnd = BitOR BitOR
| LALogAnd LogAnd BitOR
deriving Show
data LogOr = LogAnd LogAnd
| LOLogOr LogOr LogAnd
deriving Show
--}
data AExpr = AEUExpr UExpr | AOp String AExpr AExpr deriving Show
data CondE = AExpr AExpr
| CondIf AExpr AssignE AssignE
deriving Show
data AssignOp = AssignNormal
| AssignOpMult
| AssignOpDiv
| AssignOpMod
| AssignOpPlus
| AssignOpMinus deriving Show
data AssignE = CondE CondE
| Assign LeftExpr AssignOp AssignE
| AEFuncDecl FuncDecl
deriving Show
data Expr = AssignE AssignE
deriving Show
data VarDecl = VarDecl String (Maybe AssignE) deriving Show
data IfStmt = IfElse Expr Stmt Stmt
| IfOnly Expr Stmt
| If2 Expr
| If3
deriving Show
data ItStmt = DoWhile Stmt Expr
| While Expr Stmt
| For (Maybe Expr) (Maybe Expr) (Maybe Expr) Stmt
| ForVar [VarDecl] (Maybe Expr) (Maybe Expr) Stmt
| ForIn LeftExpr Expr Stmt
| It2 Expr
deriving Show
data TryStmt = TryBC [Stmt] [Catch]
| TryBF [Stmt] [Stmt]
| TryBCF [Stmt] [Catch] [Stmt]
| TryTry [Stmt] [Catch] [Stmt]
deriving Show
data Catch = Catch String [Stmt] | CatchIf String [Stmt] Expr | CatchCatch String (Maybe Expr) [Stmt]
deriving Show
data Stmt = StmtPos (Int,Int) Stmt' deriving Show
data Stmt' = IfStmt IfStmt | EmptyStmt | ExprStmt Expr | ItStmt ItStmt | Block [Stmt]
| VarStmt [VarDecl ]
| TryStmt TryStmt
| ContStmt (Maybe String)
| BreakStmt (Maybe String)
| ReturnStmt (Maybe Expr)
| WithStmt Expr Stmt
| LabelledStmt String Stmt
| Switch Expr [CaseClause]
| ThrowExpr Expr
deriving Show
data Switch = SSwitch Expr [CaseClause]
deriving Show
data CaseBlock = CaseBlock [CaseClause]
deriving Show
data CaseClause = CaseClause Expr [Stmt] | DefaultClause [Stmt]
deriving Show
-- data DefaultClause = DefaultClause [Stmt]
-- deriving Show
data FuncDecl = FuncDecl (Maybe String) [TypeAnnotation] [String] [SourceElement]
deriving Show
data TypeAnnotation = TypeAnnotation String String
deriving Show
data SourceElement = Stmt Stmt | SEFuncDecl FuncDecl
deriving Show
data JSProgram = JSProgram [SourceElement]
deriving Show
| disnet/jscheck | src/HJS/Parser/JavaScript.hs | bsd-3-clause | 5,332 | 49 | 9 | 1,793 | 1,051 | 612 | 439 | 119 | 0 |
{-# LANGUAGE DeriveGeneric #-}
module Codex.Lib.Geo.Names (
Names (..),
parseMales,
parseFemales
) where
import Codex.Lib.List
(splitBy)
import System.IO
import Control.Monad
import Data.Aeson
import GHC.Generics
import qualified Data.Map as M
data Names = Male String | Female String deriving (Show, Read, Eq, Generic)
instance ToJSON Names
instance FromJSON Names
parseMales :: FilePath -> IO [Names]
parseMales name = parseToks name >>= \toks -> return $ concat $ mapM (\x -> return $ Male x) toks
parseFemales :: FilePath -> IO [Names]
parseFemales name = parseToks name >>= \toks -> return $ concat $ mapM (\x -> return $ Female x) toks
parseToks :: FilePath -> IO [String]
parseToks name = do
contents <- readFile name
let parsed = map (\l -> fstTok $ splitBy ' ' l) $ lines contents
return parsed
fstTok :: [String] -> String
fstTok (name:rest) = name
| adarqui/Codex | src/Codex/Lib/Geo/Names.hs | bsd-3-clause | 875 | 0 | 15 | 156 | 338 | 180 | 158 | 26 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Stack.Init
( initProject
, InitOpts (..)
) where
import Control.Exception (assert)
import Control.Exception.Safe (catchAny)
import Control.Monad
import Control.Monad.Catch (throwM)
import Control.Monad.IO.Class
import Control.Monad.Logger
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as L
import qualified Data.Foldable as F
import Data.Function (on)
import qualified Data.HashMap.Strict as HM
import qualified Data.IntMap as IntMap
import Data.List (intercalate, intersect,
maximumBy)
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NonEmpty
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Yaml as Yaml
import qualified Distribution.PackageDescription as C
import qualified Distribution.Text as C
import qualified Distribution.Version as C
import Path
import Path.Extra (toFilePathNoTrailingSep)
import Path.IO
import qualified Paths_stack as Meta
import Stack.BuildPlan
import Stack.Config (getSnapshots,
makeConcreteResolver)
import Stack.Constants
import Stack.Solver
import Stack.Types.Build
import Stack.Types.BuildPlan
import Stack.Types.Config
import Stack.Types.FlagName
import Stack.Types.PackageName
import Stack.Types.Resolver
import Stack.Types.StackT (StackM)
import Stack.Types.StringError
import Stack.Types.Version
import qualified System.FilePath as FP
-- | Generate stack.yaml
initProject
:: (StackM env m, HasConfig env, HasGHCVariant env)
=> WhichSolverCmd
-> Path Abs Dir
-> InitOpts
-> Maybe AbstractResolver
-> m ()
initProject whichCmd currDir initOpts mresolver = do
let dest = currDir </> stackDotYaml
reldest <- toFilePath `liftM` makeRelativeToCurrentDir dest
exists <- doesFileExist dest
when (not (forceOverwrite initOpts) && exists) $
throwString
("Error: Stack configuration file " <> reldest <>
" exists, use 'stack solver' to fix the existing config file or \
\'--force' to overwrite it.")
dirs <- mapM (resolveDir' . T.unpack) (searchDirs initOpts)
let noPkgMsg = "In order to init, you should have an existing .cabal \
\file. Please try \"stack new\" instead."
find = findCabalFiles (includeSubDirs initOpts)
dirs' = if null dirs then [currDir] else dirs
$logInfo "Looking for .cabal or package.yaml files to use to init the project."
cabalfps <- liftM concat $ mapM find dirs'
(bundle, dupPkgs) <- cabalPackagesCheck cabalfps noPkgMsg Nothing
(r, flags, extraDeps, rbundle) <- getDefaultResolver whichCmd dest initOpts
mresolver bundle
let ignored = Map.difference bundle rbundle
dupPkgMsg
| dupPkgs /= [] =
"Warning (added by new or init): Some packages were found to \
\have names conflicting with others and have been commented \
\out in the packages section.\n"
| otherwise = ""
missingPkgMsg
| Map.size ignored > 0 =
"Warning (added by new or init): Some packages were found to \
\be incompatible with the resolver and have been left commented \
\out in the packages section.\n"
| otherwise = ""
extraDepMsg
| Map.size extraDeps > 0 =
"Warning (added by new or init): Specified resolver could not \
\satisfy all dependencies. Some external packages have been \
\added as dependencies.\n"
| otherwise = ""
makeUserMsg msgs =
let msg = concat msgs
in if msg /= "" then
msg <> "You can suppress this message by removing it from \
\stack.yaml\n"
else ""
userMsg = makeUserMsg [dupPkgMsg, missingPkgMsg, extraDepMsg]
gpds = Map.elems $ fmap snd rbundle
p = Project
{ projectUserMsg = if userMsg == "" then Nothing else Just userMsg
, projectPackages = pkgs
, projectExtraDeps = extraDeps
, projectFlags = PackageFlags (removeSrcPkgDefaultFlags gpds flags)
, projectResolver = r
, projectCompiler = Nothing
, projectExtraPackageDBs = []
}
makeRelDir dir =
case stripDir currDir dir of
Nothing
| currDir == dir -> "."
| otherwise -> assert False $ toFilePathNoTrailingSep dir
Just rel -> toFilePathNoTrailingSep rel
makeRel = fmap toFilePath . makeRelativeToCurrentDir
pkgs = map toPkg $ Map.elems (fmap (parent . fst) rbundle)
toPkg dir = PackageEntry
{ peExtraDepMaybe = Nothing
, peLocation = PLFilePath $ makeRelDir dir
, peSubdirs = []
}
indent t = T.unlines $ fmap (" " <>) (T.lines t)
$logInfo $ "Initialising configuration using resolver: " <> resolverName r
$logInfo $ "Total number of user packages considered: "
<> T.pack (show (Map.size bundle + length dupPkgs))
when (dupPkgs /= []) $ do
$logWarn $ "Warning! Ignoring "
<> T.pack (show $ length dupPkgs)
<> " duplicate packages:"
rels <- mapM makeRel dupPkgs
$logWarn $ indent $ showItems rels
when (Map.size ignored > 0) $ do
$logWarn $ "Warning! Ignoring "
<> T.pack (show $ Map.size ignored)
<> " packages due to dependency conflicts:"
rels <- mapM makeRel (Map.elems (fmap fst ignored))
$logWarn $ indent $ showItems rels
when (Map.size extraDeps > 0) $ do
$logWarn $ "Warning! " <> T.pack (show $ Map.size extraDeps)
<> " external dependencies were added."
$logInfo $
(if exists then "Overwriting existing configuration file: "
else "Writing configuration to file: ")
<> T.pack reldest
liftIO $ L.writeFile (toFilePath dest)
$ B.toLazyByteString
$ renderStackYaml p
(Map.elems $ fmap (makeRelDir . parent . fst) ignored)
(map (makeRelDir . parent) dupPkgs)
$logInfo "All done."
-- | Render a stack.yaml file with comments, see:
-- https://github.com/commercialhaskell/stack/issues/226
renderStackYaml :: Project -> [FilePath] -> [FilePath] -> B.Builder
renderStackYaml p ignoredPackages dupPackages =
case Yaml.toJSON p of
Yaml.Object o -> renderObject o
_ -> assert False $ B.byteString $ Yaml.encode p
where
renderObject o =
B.byteString headerHelp
<> B.byteString "\n\n"
<> F.foldMap (goComment o) comments
<> goOthers (o `HM.difference` HM.fromList comments)
<> B.byteString footerHelp
goComment o (name, comment) =
case HM.lookup name o of
Nothing -> assert (name == "user-message") mempty
Just v ->
B.byteString comment <>
B.byteString "\n" <>
B.byteString (Yaml.encode $ Yaml.object [(name, v)]) <>
if name == "packages" then commentedPackages else "" <>
B.byteString "\n"
commentLine l | null l = "#"
| otherwise = "# " ++ l
commentHelp = BC.pack . intercalate "\n" . map commentLine
commentedPackages =
let ignoredComment = commentHelp
[ "The following packages have been ignored due to incompatibility with the"
, "resolver compiler, dependency conflicts with other packages"
, "or unsatisfied dependencies."
]
dupComment = commentHelp
[ "The following packages have been ignored due to package name conflict "
, "with other packages."
]
in commentPackages ignoredComment ignoredPackages
<> commentPackages dupComment dupPackages
commentPackages comment pkgs
| pkgs /= [] =
B.byteString comment
<> B.byteString "\n"
<> B.byteString (BC.pack $ concat
$ map (\x -> "#- " ++ x ++ "\n") pkgs ++ ["\n"])
| otherwise = ""
goOthers o
| HM.null o = mempty
| otherwise = assert False $ B.byteString $ Yaml.encode o
-- Per Section Help
comments =
[ ("user-message" , userMsgHelp)
, ("resolver" , resolverHelp)
, ("packages" , packageHelp)
, ("extra-deps" , "# Dependency packages to be pulled from upstream that are not in the resolver\n# (e.g., acme-missiles-0.3)")
, ("flags" , "# Override default flag values for local packages and extra-deps")
, ("extra-package-dbs", "# Extra package databases containing global packages")
]
-- Help strings
headerHelp = commentHelp
[ "This file was automatically generated by 'stack init'"
, ""
, "Some commonly used options have been documented as comments in this file."
, "For advanced use and comprehensive documentation of the format, please see:"
, "http://docs.haskellstack.org/en/stable/yaml_configuration/"
]
resolverHelp = commentHelp
[ "Resolver to choose a 'specific' stackage snapshot or a compiler version."
, "A snapshot resolver dictates the compiler version and the set of packages"
, "to be used for project dependencies. For example:"
, ""
, "resolver: lts-3.5"
, "resolver: nightly-2015-09-21"
, "resolver: ghc-7.10.2"
, "resolver: ghcjs-0.1.0_ghc-7.10.2"
, "resolver:"
, " name: custom-snapshot"
, " location: \"./custom-snapshot.yaml\""
]
userMsgHelp = commentHelp
[ "A warning or info to be displayed to the user on config load." ]
packageHelp = commentHelp
[ "User packages to be built."
, "Various formats can be used as shown in the example below."
, ""
, "packages:"
, "- some-directory"
, "- https://example.com/foo/bar/baz-0.0.2.tar.gz"
, "- location:"
, " git: https://github.com/commercialhaskell/stack.git"
, " commit: e7b331f14bcffb8367cd58fbfc8b40ec7642100a"
, "- location: https://github.com/commercialhaskell/stack/commit/e7b331f14bcffb8367cd58fbfc8b40ec7642100a"
, " extra-dep: true"
, " subdirs:"
, " - auto-update"
, " - wai"
, ""
, "A package marked 'extra-dep: true' will only be built if demanded by a"
, "non-dependency (i.e. a user package), and its test suites and benchmarks"
, "will not be run. This is useful for tweaking upstream packages."
]
footerHelp =
let major = toCabalVersion
$ toMajorVersion $ fromCabalVersion Meta.version
in commentHelp
[ "Control whether we use the GHC we find on the path"
, "system-ghc: true"
, ""
, "Require a specific version of stack, using version ranges"
, "require-stack-version: -any # Default"
, "require-stack-version: \""
++ C.display (C.orLaterVersion major) ++ "\""
, ""
, "Override the architecture used by stack, especially useful on Windows"
, "arch: i386"
, "arch: x86_64"
, ""
, "Extra directories used by stack for building"
, "extra-include-dirs: [/path/to/dir]"
, "extra-lib-dirs: [/path/to/dir]"
, ""
, "Allow a newer minor version of GHC than the snapshot specifies"
, "compiler-check: newer-minor"
]
getSnapshots' :: (StackM env m, HasConfig env)
=> m Snapshots
getSnapshots' = do
getSnapshots `catchAny` \e -> do
$logError $
"Unable to download snapshot list, and therefore could " <>
"not generate a stack.yaml file automatically"
$logError $
"This sometimes happens due to missing Certificate Authorities " <>
"on your system. For more information, see:"
$logError ""
$logError " https://github.com/commercialhaskell/stack/issues/234"
$logError ""
$logError "You can try again, or create your stack.yaml file by hand. See:"
$logError ""
$logError " http://docs.haskellstack.org/en/stable/yaml_configuration/"
$logError ""
$logError $ "Exception was: " <> T.pack (show e)
errorString ""
-- | Get the default resolver value
getDefaultResolver
:: (StackM env m, HasConfig env, HasGHCVariant env)
=> WhichSolverCmd
-> Path Abs File -- ^ stack.yaml
-> InitOpts
-> Maybe AbstractResolver
-> Map PackageName (Path Abs File, C.GenericPackageDescription)
-- ^ Src package name: cabal dir, cabal package description
-> m ( Resolver
, Map PackageName (Map FlagName Bool)
, Map PackageName Version
, Map PackageName (Path Abs File, C.GenericPackageDescription))
-- ^ ( Resolver
-- , Flags for src packages and extra deps
-- , Extra dependencies
-- , Src packages actually considered)
getDefaultResolver whichCmd stackYaml initOpts mresolver bundle =
maybe selectSnapResolver makeConcreteResolver mresolver
>>= getWorkingResolverPlan whichCmd stackYaml initOpts bundle
where
-- TODO support selecting best across regular and custom snapshots
selectSnapResolver = do
let gpds = Map.elems (fmap snd bundle)
snaps <- fmap getRecommendedSnapshots getSnapshots'
(s, r) <- selectBestSnapshot gpds snaps
case r of
BuildPlanCheckFail {} | not (omitPackages initOpts)
-> throwM (NoMatchingSnapshot whichCmd snaps)
_ -> return $ ResolverSnapshot s
getWorkingResolverPlan
:: (StackM env m, HasConfig env, HasGHCVariant env)
=> WhichSolverCmd
-> Path Abs File -- ^ stack.yaml
-> InitOpts
-> Map PackageName (Path Abs File, C.GenericPackageDescription)
-- ^ Src package name: cabal dir, cabal package description
-> Resolver
-> m ( Resolver
, Map PackageName (Map FlagName Bool)
, Map PackageName Version
, Map PackageName (Path Abs File, C.GenericPackageDescription))
-- ^ ( Resolver
-- , Flags for src packages and extra deps
-- , Extra dependencies
-- , Src packages actually considered)
getWorkingResolverPlan whichCmd stackYaml initOpts bundle resolver = do
$logInfo $ "Selected resolver: " <> resolverName resolver
go bundle
where
go info = do
eres <- checkBundleResolver whichCmd stackYaml initOpts info resolver
-- if some packages failed try again using the rest
case eres of
Right (f, edeps)-> return (resolver, f, edeps, info)
Left ignored
| Map.null available -> do
$logWarn "*** Could not find a working plan for any of \
\the user packages.\nProceeding to create a \
\config anyway."
return (resolver, Map.empty, Map.empty, Map.empty)
| otherwise -> do
when (Map.size available == Map.size info) $
error "Bug: No packages to ignore"
if length ignored > 1 then do
$logWarn "*** Ignoring packages:"
$logWarn $ indent $ showItems ignored
else
$logWarn $ "*** Ignoring package: "
<> T.pack (packageNameString (head ignored))
go available
where
indent t = T.unlines $ fmap (" " <>) (T.lines t)
isAvailable k _ = k `notElem` ignored
available = Map.filterWithKey isAvailable info
checkBundleResolver
:: (StackM env m, HasConfig env, HasGHCVariant env)
=> WhichSolverCmd
-> Path Abs File -- ^ stack.yaml
-> InitOpts
-> Map PackageName (Path Abs File, C.GenericPackageDescription)
-- ^ Src package name: cabal dir, cabal package description
-> Resolver
-> m (Either [PackageName] ( Map PackageName (Map FlagName Bool)
, Map PackageName Version))
checkBundleResolver whichCmd stackYaml initOpts bundle resolver = do
result <- checkResolverSpec gpds Nothing resolver
case result of
BuildPlanCheckOk f -> return $ Right (f, Map.empty)
BuildPlanCheckPartial f e
| needSolver resolver initOpts -> do
warnPartial result
solve f
| omitPackages initOpts -> do
warnPartial result
$logWarn "*** Omitting packages with unsatisfied dependencies"
return $ Left $ failedUserPkgs e
| otherwise -> throwM $ ResolverPartial whichCmd resolver (show result)
BuildPlanCheckFail _ e _
| omitPackages initOpts -> do
$logWarn $ "*** Resolver compiler mismatch: "
<> resolverName resolver
$logWarn $ indent $ T.pack $ show result
return $ Left $ failedUserPkgs e
| otherwise -> throwM $ ResolverMismatch whichCmd resolver (show result)
where
indent t = T.unlines $ fmap (" " <>) (T.lines t)
warnPartial res = do
$logWarn $ "*** Resolver " <> resolverName resolver
<> " will need external packages: "
$logWarn $ indent $ T.pack $ show res
failedUserPkgs e = Map.keys $ Map.unions (Map.elems (fmap deNeededBy e))
gpds = Map.elems (fmap snd bundle)
solve flags = do
let cabalDirs = map parent (Map.elems (fmap fst bundle))
srcConstraints = mergeConstraints (gpdPackages gpds) flags
eresult <- solveResolverSpec stackYaml cabalDirs
(resolver, srcConstraints, Map.empty)
case eresult of
Right (src, ext) ->
return $ Right (fmap snd (Map.union src ext), fmap fst ext)
Left packages
| omitPackages initOpts, srcpkgs /= []-> do
pkg <- findOneIndependent srcpkgs flags
return $ Left [pkg]
| otherwise -> throwM (SolverGiveUp giveUpMsg)
where srcpkgs = Map.keys bundle `intersect` packages
-- among a list of packages find one on which none among the rest of the
-- packages depend. This package is a good candidate to be removed from
-- the list of packages when there is conflict in dependencies among this
-- set of packages.
findOneIndependent packages flags = do
platform <- view platformL
(compiler, _) <- getResolverConstraints stackYaml resolver
let getGpd pkg = snd (fromJust (Map.lookup pkg bundle))
getFlags pkg = fromJust (Map.lookup pkg flags)
deps pkg = gpdPackageDeps (getGpd pkg) compiler platform
(getFlags pkg)
allDeps = concatMap (Map.keys . deps) packages
isIndependent pkg = pkg `notElem` allDeps
-- prefer to reject packages in deeper directories
path pkg = fst (fromJust (Map.lookup pkg bundle))
pathlen = length . FP.splitPath . toFilePath . path
maxPathlen = maximumBy (compare `on` pathlen)
return $ maxPathlen (filter isIndependent packages)
giveUpMsg = concat
[ " - Use '--omit-packages to exclude conflicting package(s).\n"
, " - Tweak the generated "
, toFilePath stackDotYaml <> " and then run 'stack solver':\n"
, " - Add any missing remote packages.\n"
, " - Add extra dependencies to guide solver.\n"
, " - Update external packages with 'stack update' and try again.\n"
]
needSolver _ InitOpts {useSolver = True} = True
needSolver (ResolverCompiler _) _ = True
needSolver _ _ = False
getRecommendedSnapshots :: Snapshots -> NonEmpty SnapName
getRecommendedSnapshots snapshots =
-- in order - Latest LTS, Latest Nightly, all LTS most recent first
case NonEmpty.nonEmpty ltss of
Just (mostRecent :| older)
-> mostRecent :| (nightly : older)
Nothing
-> nightly :| []
where
ltss = map (uncurry LTS) (IntMap.toDescList $ snapshotsLts snapshots)
nightly = Nightly (snapshotsNightly snapshots)
data InitOpts = InitOpts
{ searchDirs :: ![T.Text]
-- ^ List of sub directories to search for .cabal files
, useSolver :: Bool
-- ^ Use solver to determine required external dependencies
, omitPackages :: Bool
-- ^ Exclude conflicting or incompatible user packages
, forceOverwrite :: Bool
-- ^ Overwrite existing stack.yaml
, includeSubDirs :: Bool
-- ^ If True, include all .cabal files found in any sub directories
}
| Fuuzetsu/stack | src/Stack/Init.hs | bsd-3-clause | 22,523 | 0 | 21 | 7,743 | 4,398 | 2,244 | 2,154 | 422 | 6 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ScopedTypeVariables #-}
module MailboxTestFilters where
import Control.Distributed.Process
import Control.Distributed.Process.Platform.Execution.Mailbox (FilterResult(..))
import Control.Monad (forM)
#if ! MIN_VERSION_base(4,6,0)
import Prelude hiding (catch, drop)
#else
import Prelude hiding (drop)
#endif
import Data.Maybe (catMaybes)
import Control.Distributed.Process.Closure (remotable, mkClosure, mkStaticClosure)
filterInputs :: (String, Int, Bool) -> Message -> Process FilterResult
filterInputs (s, i, b) msg = do
rs <- forM [ \m -> handleMessageIf m (\s' -> s' == s) (\_ -> return Keep)
, \m -> handleMessageIf m (\i' -> i' == i) (\_ -> return Keep)
, \m -> handleMessageIf m (\b' -> b' == b) (\_ -> return Keep)
] $ \h -> h msg
if (length (catMaybes rs) > 0)
then return Keep
else return Skip
filterEvens :: Message -> Process FilterResult
filterEvens m = do
matched <- handleMessage m (\(i :: Int) -> do
if even i then return Keep else return Skip)
case matched of
Just fr -> return fr
_ -> return Skip
$(remotable ['filterInputs, 'filterEvens])
intFilter :: Closure (Message -> Process FilterResult)
intFilter = $(mkStaticClosure 'filterEvens)
myFilter :: (String, Int, Bool) -> Closure (Message -> Process FilterResult)
myFilter = $(mkClosure 'filterInputs)
| haskell-distributed/distributed-process-platform | tests/MailboxTestFilters.hs | bsd-3-clause | 1,432 | 0 | 15 | 303 | 484 | 266 | 218 | 30 | 3 |
{-# LANGUAGE Rank2Types, TypeOperators, TypeSynonymInstances,
PatternGuards, FlexibleInstances #-}
----------------------------------------------------------------------
-- |
-- Module : Interface.TV.Common
-- Copyright : (c) Conal Elliott 2006
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : Rank2Types
--
-- Some common interaction vocabulary
----------------------------------------------------------------------
module Interface.TV.Common
(
-- * Type class
CommonIns(..), readD, getReadF, CommonOuts(..), putShowC
, CInput, CInputI, COutput, CTV
-- * Inputs
, stringIn, boolIn, readIn -- , intIn
-- * Outputs
, stringOut, boolOut, showOut, interactLine, readShow, interactLineRS
) where
-- import Control.Arrow
-- import Control.Applicative
import Control.Compose (OI,Flip(..),ContraFunctor(..))
import Interface.TV.Input
import Interface.TV.Output
import Interface.TV.OFun (wrapO)
import Interface.TV.Tangible (TV)
-- import Interface.TV.Misc (readD)
-- | This class captures some useful operations available in some input
-- types, and allows definition of some \"'Common'\" 'Input's
class CommonIns src where
-- | Input a string (with default)
getString :: String -> src String
-- | Read-based input. Initial value is also used as a default for
-- failed parse. Define as 'getReadF' when @src@ is a 'Functor'.
-- Requires 'Show' as well as 'Read', for displaying the initial value.
getRead :: (Show a, Read a) => a -> src a
-- | Input a bool
getBool :: Bool -> src Bool
getBool = getRead
{-
-- | Input an int with default & bounds
-- TODO: add getDouble or generalize
getInt :: Int -- ^ default
-> (Int,Int) -- ^ bounds
-> src Int
-}
-- | Read with default value. If the input doesn't parse as a value of
-- the expected type, or it's ambiguous, yield the default value.
readD :: Read a => a -> String -> a
readD dflt str | [(a,"")] <- reads str = a
| otherwise = dflt
-- | 'getRead' for 'Functor's
getReadF :: (CommonIns src, Functor src, Show a, Read a) => a -> src a
getReadF dflt = fmap (readD dflt) (getString (show dflt))
instance CommonIns IO where { getString = const getLine; getRead = getReadF }
instance CommonOuts OI where { putString = Flip putStrLn; putShow = putShowC }
-- Hm. putStrLn vs putStr above?
-- | This class captures some useful operations available in some arrows
-- and allows definition of some \"'Common'\" 'Input's, 'Output's, and
-- TVs.
class CommonOuts snk where
-- | Output a string
putString :: snk String
-- | Shows based outout. Define as 'putShowC' when @snk@ is a
-- 'ContraFunctor'
putShow :: Show a => snk a
-- | Output a bool
putBool :: snk Bool
putBool = putShow
putShowC :: (CommonOuts snk, ContraFunctor snk, Show a) => snk a
putShowC = contraFmap show putString
-- | Inputs that work over all 'CommonInsOuts' typecons.
type CInput a = forall src. (CommonIns src) => Input src a
-- | 'CInput' with initial value
type CInputI a = a -> CInput a
-- | Outputs that work over all 'CommonOuts' typecons.
type COutput a =
forall src snk. (CommonIns src, CommonOuts snk) => Output src snk a
-- | Convenient type synonym for TVs that work over all 'CommonInsOuts' typecons.
type CTV a = forall src snk. (CommonIns src, CommonOuts snk) => TV src snk a
-- | String input with default
stringIn :: CInputI String
stringIn s = iPrim (getString s)
-- | Bool input with default
boolIn :: CInputI Bool
boolIn b = iPrim (getBool b)
-- -- | Int input, with default and bounds
-- intIn :: Int -> (Int,Int) -> CInput Int
-- intIn dflt bounds = iPrim (getInt dflt bounds)
-- | Input a readable value. Use default when read fails.
readIn :: (Read a, Show a) => CInputI a
readIn a = iPrim (getRead a)
-- | Output a string
stringOut :: COutput String
stringOut = oPrim putString
-- | Output a bool
boolOut :: COutput Bool
boolOut = oPrim putBool
-- | Output a showable value
showOut :: Show a => COutput a
showOut = oPrim putShow -- contraFmap show stringOut
-- | 'Output' version of 'interact'. Well, not quite, since the IO
-- version uses 'getLine' instead of 'getContents'. See also
-- 'Interface.TV.interactOut'
interactLine :: String -> COutput (String -> String)
interactLine s = oLambda (stringIn s) stringOut
-- | Handy Read+Show wrapper
readShow :: ( Read a, Show b, CommonIns src, CommonOuts snk
, Functor src, ContraFunctor snk )
=> Output src snk (String->String) -- ^ base output
-> a -- ^ default, when read fails
-> Output src snk (a -> b)
readShow o dflt = wrapO show (readD dflt) o
-- Tempting to give the following terse type spec:
--
-- readShow :: (Read a, Show b) =>
-- CFOutput (String->String) -> a -> CFOutput (a -> b)
--
-- However, the universality requirement on the first argument is too strong.
-- | Read+Show of 'interactLine'
interactLineRS :: ( Read a, Show a, Show b, CommonIns src, CommonOuts snk )
=> a -- ^ default, if read fails
-> Output src snk (a -> b)
interactLineRS dflt = oLambda (readIn dflt) showOut
-- This version requires Functor src & ContraFunctor snk
-- interactLineRS a = readShow (interactLine (show a)) a
| conal/TV | src/Interface/TV/Common.hs | bsd-3-clause | 5,375 | 0 | 10 | 1,186 | 997 | 566 | 431 | 61 | 1 |
module Main (main) where
import Control.Monad (forM_)
import Control.Monad.IO.Class (liftIO)
import Data.Default (def)
import System.Directory (doesFileExist)
import Test.Hspec
import qualified Control.Monad.Trans.Resource as R
import qualified Data.Conduit as C
import qualified Data.Conduit.Binary as CB
import qualified Graphics.ThumbnailPlus as TP
import qualified Graphics.ThumbnailPlus.ImageSize as TPIS
jpn_art :: FilePath
jpn_art = "tests/data/jpn_art.jpg"
main :: IO ()
main = hspec $ do
describe "sinkImageInfo" $ do
it "works for logo.png" $ check (Just (TP.Size 271 61, TP.PNG)) "tests/data/logo.png"
it "works for logo.jpg" $ check (Just (TP.Size 271 61, TP.JPG)) "tests/data/logo.jpg"
it "works for logo.gif" $ check (Just (TP.Size 271 61, TP.GIF)) "tests/data/logo.gif"
it "works for jpg_art.jpg" $ check (Just (TP.Size 1344 1352, TP.JPG)) jpn_art
it "rejects invalid file" $ check Nothing "tests/Main.hs"
describe "createThumbnails" $ do
let conf = def { TP.maxFileSize = 450239
, TP.maxImageSize = TP.Size 1344 1352
, TP.reencodeOriginal = TP.NewFileFormat TP.GIF
, TP.thumbnailSizes = [(TP.Size i i, Nothing) | i <- [3000, 512, 64]]
}
it "works for jpg_art.jpg" $ do
fps <- R.runResourceT $ do
TP.CreatedThumbnails thumbs _ <- TP.createThumbnails conf jpn_art
liftIO $ do
map TP.thumbSize thumbs `shouldBe` [TP.maxImageSize conf, TP.Size 508 512, TP.Size 63 64]
map TP.thumbFormat thumbs `shouldBe` [TP.GIF, TP.JPG, TP.JPG]
mapM_ checkThumbnail thumbs
return (map TP.thumbFp thumbs)
forM_ fps $ \fp -> doesFileExist fp `shouldReturn` False
it "rejects due to large file size" $ do
let conf' = conf { TP.maxFileSize = TP.maxFileSize conf - 1 }
R.runResourceT (TP.createThumbnails conf' jpn_art) `shouldReturn` TP.FileSizeTooLarge (TP.maxFileSize conf)
it "rejects due to large image width" $ do
-- I should use some lens :).
let conf' = conf { TP.maxImageSize = TP.Size 1343 9999 }
R.runResourceT (TP.createThumbnails conf' jpn_art) `shouldReturn` TP.ImageSizeTooLarge (TP.maxImageSize conf)
it "rejects due to large image height" $ do
-- I should use some lens :).
let conf' = conf { TP.maxImageSize = TP.Size 9999 1351 }
R.runResourceT (TP.createThumbnails conf' jpn_art) `shouldReturn` TP.ImageSizeTooLarge (TP.maxImageSize conf)
check :: Maybe (TP.Size, TP.FileFormat) -> FilePath -> Expectation
check ex fp = do
size <- R.runResourceT $ CB.sourceFile fp C.$$ TPIS.sinkImageInfo
size `shouldBe` ex
checkThumbnail :: TP.Thumbnail -> Expectation
checkThumbnail t = check (Just (TP.thumbSize t, TP.thumbFormat t)) (TP.thumbFp t)
| prowdsponsor/thumbnail-plus | tests/Main.hs | bsd-3-clause | 2,823 | 0 | 24 | 627 | 920 | 471 | 449 | 50 | 1 |
-- | Main entry point to osdkeys.
--
-- Show keys pressed with an on-screen display (Linux only)
module Main where
import Data.Maybe
import OSDKeys
import OSDKeys.Types
import System.Process
import System.Environment
import Text.Read
-- | Main entry point.
main :: IO ()
main =
do args <- getArgs
case args of
[mdevice] -> run mdevice Nothing
[mdevice,mmax] -> run mdevice (Just mmax)
_ -> error "Arguments: DEVICE-ID [<max-keys-on-screen>]\n\n\
\Use `xinput list' to get device ID."
-- | Run on the device and with the given max.
run :: String -> Maybe String -> IO ()
run mdevice mmax =
case readMaybe mdevice of
Nothing ->
do xinputOutput <- readProcess "xinput"
["list"]
""
error ("Need a device id. Here are the current devices: \n\n" ++
xinputOutput)
Just device ->
startOSDKeys (Device device)
(fromMaybe 64 (mmax >>= readMaybe))
| chrisdone/osdkeys | src/main/Main.hs | bsd-3-clause | 1,028 | 0 | 12 | 327 | 221 | 114 | 107 | 26 | 3 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE NamedFieldPuns, RecordWildCards, BangPatterns,
StandaloneDeriving, GeneralizedNewtypeDeriving #-}
module Distribution.Server.Features.EditCabalFiles (
initEditCabalFilesFeature
, diffCabalRevisions
, Change(..)
) where
import Distribution.Server.Framework
import Distribution.Server.Framework.Templating
import Distribution.Server.Features.Users
import Distribution.Server.Features.Core
import Distribution.Server.Packages.Types
import Distribution.Server.Features.Upload
import Distribution.Package
import Distribution.Text (display)
import Distribution.Version (intersectVersionRanges)
import Distribution.PackageDescription
import Distribution.PackageDescription.Parse
(parsePackageDescription, sourceRepoFieldDescrs)
import Distribution.PackageDescription.Check
import Distribution.ParseUtils
( ParseResult(..), locatedErrorMsg, showPWarning )
import Distribution.Server.Util.Parse (unpackUTF8)
import Distribution.ParseUtils (FieldDescr(..))
import Distribution.Text (Text(..))
import Distribution.Simple.LocalBuildInfo (ComponentName(..) ,showComponentName)
import Text.PrettyPrint as Doc
(nest, empty, isEmpty, (<+>), colon, (<>), text, vcat, ($+$), Doc)
import Text.StringTemplate (ToSElem(..))
import Data.List
import qualified Data.Char as Char
import Data.ByteString.Lazy (ByteString)
import qualified Data.Map as Map
import Control.Monad.Error (ErrorT, runErrorT)
import Control.Monad.Writer (MonadWriter(..), Writer, runWriter)
import Control.Applicative
import Data.Time (getCurrentTime)
import qualified Data.ByteString.Lazy.Char8 as BS -- TODO: Verify that we don't need to worry about UTF8
-- | A feature to allow editing cabal files without uploading new tarballs.
--
initEditCabalFilesFeature :: ServerEnv
-> IO (UserFeature
-> CoreFeature
-> UploadFeature
-> IO HackageFeature)
initEditCabalFilesFeature env@ServerEnv{ serverTemplatesDir,
serverTemplatesMode } = do
-- Page templates
templates <- loadTemplates serverTemplatesMode
[serverTemplatesDir, serverTemplatesDir </> "EditCabalFile"]
["cabalFileEditPage.html", "cabalFilePublished.html"]
return $ \user core upload -> do
let feature = editCabalFilesFeature env templates user core upload
return feature
editCabalFilesFeature :: ServerEnv -> Templates
-> UserFeature -> CoreFeature -> UploadFeature
-> HackageFeature
editCabalFilesFeature _env templates
UserFeature{guardAuthorised}
CoreFeature{..}
UploadFeature{maintainersGroup, trusteesGroup} =
(emptyHackageFeature "edit-cabal-files") {
featureResources =
[ editCabalFileResource
]
, featureState = []
, featureReloadFiles = reloadTemplates templates
}
where
CoreResource{..} = coreResource
editCabalFileResource =
(resourceAt "/package/:package/:cabal.cabal/edit") {
resourceDesc = [(GET, "Page to edit package metadata")
,(POST, "Modify the package metadata")],
resourceGet = [("html", serveEditCabalFileGet)],
resourcePost = [("html", serveEditCabalFilePost)]
}
serveEditCabalFileGet :: DynamicPath -> ServerPartE Response
serveEditCabalFileGet dpath = do
template <- getTemplate templates "cabalFileEditPage.html"
pkg <- packageInPath dpath >>= lookupPackageId
let pkgname = packageName pkg
pkgid = packageId pkg
-- check that the cabal name matches the package
guard (lookup "cabal" dpath == Just (display pkgname))
ok $ toResponse $ template
[ "pkgid" $= pkgid
, "cabalfile" $= insertRevisionField (pkgNumRevisions pkg)
(cabalFileByteString (pkgLatestCabalFileText pkg))
]
serveEditCabalFilePost :: DynamicPath -> ServerPartE Response
serveEditCabalFilePost dpath = do
template <- getTemplate templates "cabalFileEditPage.html"
pkg <- packageInPath dpath >>= lookupPackageId
let pkgname = packageName pkg
pkgid = packageId pkg
-- check that the cabal name matches the package
guard (lookup "cabal" dpath == Just (display pkgname))
uid <- guardAuthorised [ InGroup (maintainersGroup pkgname)
, InGroup trusteesGroup ]
let oldVersion = cabalFileByteString (pkgLatestCabalFileText pkg)
newRevision <- getCabalFile
shouldPublish <- getPublish
case diffCabalRevisions pkgid oldVersion newRevision of
Left errs ->
responseTemplate template pkgid newRevision
shouldPublish [errs] []
Right changes
| shouldPublish && not (null changes) -> do
template' <- getTemplate templates "cabalFilePublished.html"
time <- liftIO getCurrentTime
updateAddPackageRevision pkgid (CabalFileText newRevision)
(time, uid)
ok $ toResponse $ template'
[ "pkgid" $= pkgid
, "cabalfile" $= newRevision
, "changes" $= changes
]
| otherwise ->
responseTemplate template pkgid newRevision
shouldPublish [] changes
where
getCabalFile = body (lookBS "cabalfile")
getPublish = body $ (look "review" >> return False) `mplus`
(look "publish" >> return True)
responseTemplate :: ([TemplateAttr] -> Template) -> PackageId
-> ByteString -> Bool -> [String] -> [Change]
-> ServerPartE Response
responseTemplate template pkgid cabalFile publish errors changes =
ok $ toResponse $ template
[ "pkgid" $= pkgid
, "cabalfile" $= cabalFile
, "publish" $= publish
, "errors" $= errors
, "changes" $= changes
]
instance ToSElem Change where
toSElem (Change change from to) =
toSElem (Map.fromList [("what", change)
,("from", from)
,("to", to)])
newtype CheckM a = CheckM { unCheckM :: ErrorT String (Writer [Change]) a } deriving (Functor, Applicative)
runCheck :: CheckM () -> Either String [Change]
runCheck c = case runWriter . runErrorT . unCheckM $ c of
(Left err, _ ) -> Left err
(Right (), changes) -> Right changes
instance Monad CheckM where
return = CheckM . return
CheckM m >>= f = CheckM (m >>= unCheckM . f)
fail = CheckM . throwError
data Change = Change String String String -- what, from, to
deriving Show
logChange :: Change -> CheckM ()
logChange change = CheckM (tell [change])
type Check a = a -> a -> CheckM ()
diffCabalRevisions :: PackageId -> ByteString -> ByteString
-> Either String [Change]
diffCabalRevisions pkgid oldVersion newRevision =
runCheck $ checkCabalFileRevision pkgid oldVersion newRevision
checkCabalFileRevision :: PackageId -> Check ByteString
checkCabalFileRevision pkgid old new = do
(pkg, warns) <- parseCabalFile old
(pkg', warns') <- parseCabalFile new
checkGenericPackageDescription pkg pkg'
checkParserWarnings warns warns'
checkPackageChecks pkg pkg'
where
filename = display pkgid ++ ".cabal"
parseCabalFile fileContent =
case parsePackageDescription . unpackUTF8 $ fileContent of
ParseFailed err -> fail (formatErrorMsg (locatedErrorMsg err))
ParseOk warnings pkg -> return (pkg, warnings)
formatErrorMsg (Nothing, msg) = msg
formatErrorMsg (Just n, msg) = "Line " ++ show n ++ ": " ++ msg
checkParserWarnings warns warns' =
case warns' \\ warns of
[] -> return ()
newwarns -> fail $ "New parse warning: "
++ unlines (map (showPWarning filename) newwarns)
checkPackageChecks pkg pkg' =
let checks = checkPackage pkg Nothing
checks' = checkPackage pkg' Nothing
in case checks' \\ checks of
[] -> return ()
newchecks -> fail $ unlines (map explanation newchecks)
checkGenericPackageDescription :: Check GenericPackageDescription
checkGenericPackageDescription
(GenericPackageDescription descrA flagsA libsA exesA testsA benchsA)
(GenericPackageDescription descrB flagsB libsB exesB testsB benchsB) = do
checkPackageDescriptions descrA descrB
checkSame "Sorry, cannot edit the package flags"
flagsA flagsB
checkMaybe "Cannot add or remove library sections"
(checkCondTree checkLibrary)
(withComponentName' CLibName <$> libsA)
(withComponentName' CLibName <$> libsB)
checkListAssoc "Cannot add or remove executable sections"
(checkCondTree checkExecutable)
(withComponentName CExeName <$> exesA)
(withComponentName CExeName <$> exesB)
checkListAssoc "Cannot add or remove test-suite sections"
(checkCondTree checkTestSuite)
(withComponentName CTestName <$> testsA)
(withComponentName CTestName <$> testsB)
checkListAssoc "Cannot add or remove benchmark sections"
(checkCondTree checkBenchmark)
(withComponentName CBenchName <$> benchsA)
(withComponentName CBenchName <$> benchsB)
where
withComponentName f (name, condTree) = (name, (f name, condTree))
withComponentName' f condTree = (f, condTree)
checkPackageDescriptions :: Check PackageDescription
checkPackageDescriptions
(PackageDescription
packageIdA licenseA licenseFileA
copyrightA maintainerA authorA stabilityA testedWithA homepageA
pkgUrlA bugReportsA sourceReposA synopsisA descriptionA
categoryA customFieldsA _buildDependsA specVersionA buildTypeA
_libraryA _executablesA _testSuitesA _benchmarksA dataFilesA dataDirA
extraSrcFilesA extraTmpFilesA extraDocFilesA)
(PackageDescription
packageIdB licenseB licenseFileB
copyrightB maintainerB authorB stabilityB testedWithB homepageB
pkgUrlB bugReportsB sourceReposB synopsisB descriptionB
categoryB customFieldsB _buildDependsB specVersionB buildTypeB
_libraryB _executablesB _testSuitesB _benchmarksB dataFilesB dataDirB
extraSrcFilesB extraTmpFilesB extraDocFilesB)
= do
checkSame "Don't be silly! You can't change the package name!"
(packageName packageIdA) (packageName packageIdB)
checkSame "You can't change the package version!"
(packageVersion packageIdA) (packageVersion packageIdB)
checkSame "Cannot change the license"
(licenseA, licenseFileA) (licenseB, licenseFileB)
changesOk "copyright" id copyrightA copyrightB
changesOk "maintainer" id maintainerA maintainerB
changesOk "author" id authorA authorB
checkSame "The stability field is unused, don't bother changing it."
stabilityA stabilityB
checkSame "The tested-with field is unused, don't bother changing it."
testedWithA testedWithB
changesOk "homepage" id homepageA homepageB
checkSame "The package-url field is unused, don't bother changing it."
pkgUrlA pkgUrlB
changesOk "bug-reports" id bugReportsA bugReportsB
changesOkList changesOk "source-repository" (show . ppSourceRepo)
sourceReposA sourceReposB
changesOk "synopsis" id synopsisA synopsisB
changesOk "description" id descriptionA descriptionB
changesOk "category" id categoryA categoryB
checkSame "Cannot change the Cabal spec version"
specVersionA specVersionB
checkSame "Cannot change the build-type"
buildTypeA buildTypeB
checkSame "Cannot change the data files"
(dataFilesA, dataDirA) (dataFilesB, dataDirB)
checkSame "Changing extra-tmp-files is a bit pointless at this stage"
extraTmpFilesA extraTmpFilesB
checkSame "Changing extra-source-files would not make sense!"
extraSrcFilesA extraSrcFilesB
checkSame "You can't change the extra-doc-files."
extraDocFilesA extraDocFilesB
checkSame "Cannot change custom/extension fields"
(filter (\(f,_) -> f /= "x-revision") customFieldsA)
(filter (\(f,_) -> f /= "x-revision") customFieldsB)
checkRevision customFieldsA customFieldsB
checkRevision :: Check [(String, String)]
checkRevision customFieldsA customFieldsB =
checkSame ("The new x-revision must be " ++ show expectedRevision)
newRevision expectedRevision
where
oldRevision = getRevision customFieldsA
newRevision = getRevision customFieldsB
expectedRevision = oldRevision + 1
getRevision customFields =
case lookup "x-revision" customFields of
Just s | [(n,"")] <- reads s -> n :: Int
_ -> 0
checkCondTree :: Check a -> Check (ComponentName, CondTree ConfVar [Dependency] a)
checkCondTree checkElem (componentName, condNodeA)
(_ , condNodeB) =
checkCondNode condNodeA condNodeB
where
checkCondNode (CondNode dataA constraintsA componentsA)
(CondNode dataB constraintsB componentsB) = do
checkDependencies componentName constraintsA constraintsB
checkList "Cannot add or remove 'if' conditionals"
checkComponent componentsA componentsB
checkElem dataA dataB
checkComponent (condA, ifPartA, thenPartA)
(condB, ifPartB, thenPartB) = do
checkSame "Cannot change the 'if' condition expressions"
condA condB
checkCondNode ifPartA ifPartB
checkMaybe "Cannot add or remove the 'else' part in conditionals"
checkCondNode thenPartA thenPartB
checkDependencies :: ComponentName -> Check [Dependency]
-- Special case: there are some pretty weird broken packages out there, see
-- https://github.com/haskell/hackage-server/issues/303
checkDependencies _ [] [dep@(Dependency (PackageName "base") _)] =
logChange (Change ("added dependency on") (display dep) "")
checkDependencies componentName ds1 ds2 =
fmapCheck canonicaliseDeps
(checkList "Cannot add or remove dependencies, \
\just change the version constraints"
(checkDependency componentName))
ds1 ds2
where
-- Allow a limited degree of adding and removing deps: only when they
-- are additional constraints on an existing package.
canonicaliseDeps :: [Dependency] -> [Dependency]
canonicaliseDeps =
map (\(pkgname, verrange) -> Dependency pkgname verrange)
. Map.toList
. Map.fromListWith (flip intersectVersionRanges)
. map (\(Dependency pkgname verrange) -> (pkgname, verrange))
checkDependency :: ComponentName -> Check Dependency
checkDependency componentName (Dependency pkgA verA) (Dependency pkgB verB)
| pkgA == pkgB = changesOk ("the " ++ showComponentName componentName ++
" component's dependency on " ++ display pkgA)
display
verA verB
| otherwise = fail "Cannot change which packages are dependencies, \
\just their version constraints."
checkLibrary :: Check Library
checkLibrary (Library modulesA reexportedA requiredSigsA exposedSigsA
exposedA buildInfoA)
(Library modulesB reexportedB requiredSigsB exposedSigsB
exposedB buildInfoB) = do
checkSame "Cannot change the exposed modules" modulesA modulesB
checkSame "Cannot change the re-exported modules" reexportedA reexportedB
checkSame "Cannot change the required signatures" requiredSigsA requiredSigsB
checkSame "Cannot change the exposed signatures" exposedSigsA exposedSigsB
checkSame "Cannot change the package exposed status" exposedA exposedB
checkBuildInfo buildInfoA buildInfoB
checkExecutable :: Check Executable
checkExecutable (Executable _nameA pathA buildInfoA)
(Executable _nameB pathB buildInfoB) = do
checkSame "Cannot change build information" pathA pathB
checkBuildInfo buildInfoA buildInfoB
checkTestSuite :: Check TestSuite
checkTestSuite (TestSuite _nameA interfaceA buildInfoA _enabledA)
(TestSuite _nameB interfaceB buildInfoB _enabledB) = do
checkSame "Cannot change test-suite type" interfaceA interfaceB
checkBuildInfo buildInfoA buildInfoB
checkBenchmark :: Check Benchmark
checkBenchmark (Benchmark _nameA interfaceA buildInfoA _enabledA)
(Benchmark _nameB interfaceB buildInfoB _enabledB) = do
checkSame "Cannot change benchmark type" interfaceA interfaceB
checkBuildInfo buildInfoA buildInfoB
checkBuildInfo :: Check BuildInfo
checkBuildInfo biA biB =
checkSame "Cannot change build information \
\(just the dependency version constraints)"
(biA { targetBuildDepends = [] })
(biB { targetBuildDepends = [] })
changesOk :: Eq a => String -> (a -> String) -> Check a
changesOk what render a b
| a == b = return ()
| otherwise = logChange (Change what (render a) (render b))
changesOkList :: (String -> (a -> String) -> Check a)
-> String -> (a -> String) -> Check [a]
changesOkList changesOkElem what render = go
where
go [] [] = return ()
go (a:_) [] = logChange (Change ("added " ++ what) (render a) "")
go [] (b:_) = logChange (Change ("removed " ++ what) "" (render b))
go (a:as) (b:bs) = changesOkElem what render a b >> go as bs
checkSame :: Eq a => String -> Check a
checkSame msg x y | x == y = return ()
| otherwise = fail msg
checkList :: String -> Check a -> Check [a]
checkList _ _ [] [] = return ()
checkList msg checkElem (x:xs) (y:ys) = checkElem x y
>> checkList msg checkElem xs ys
checkList msg _ _ _ = fail msg
checkListAssoc :: Eq b => String -> Check a -> Check [(b,a)]
checkListAssoc _ _ [] [] = return ()
checkListAssoc msg checkElem ((kx,x):xs) ((ky,y):ys)
| kx == ky = checkElem x y
>> checkListAssoc msg checkElem xs ys
| otherwise = fail msg
checkListAssoc msg _ _ _ = fail msg
checkMaybe :: String -> Check a -> Check (Maybe a)
checkMaybe _ _ Nothing Nothing = return ()
checkMaybe _ check (Just x) (Just y) = check x y
checkMaybe msg _ _ _ = fail msg
fmapCheck :: (b -> a) -> Check a -> Check b
fmapCheck f check a b =
check (f a) (f b)
--TODO: export from Cabal
ppSourceRepo :: SourceRepo -> Doc
ppSourceRepo repo =
emptyLine $ text "source-repository" <+> disp (repoKind repo) $+$
(nest 4 (ppFields sourceRepoFieldDescrs' repo))
where
sourceRepoFieldDescrs' =
filter (\fd -> fieldName fd /= "kind") sourceRepoFieldDescrs
emptyLine :: Doc -> Doc
emptyLine d = text " " $+$ d
ppFields :: [FieldDescr a] -> a -> Doc
ppFields fields x =
vcat [ ppField name (getter x)
| FieldDescr name getter _ <- fields]
ppField :: String -> Doc -> Doc
ppField name fielddoc | isEmpty fielddoc = Doc.empty
| otherwise = text name <> colon <+> fielddoc
insertRevisionField :: Int -> ByteString -> ByteString
insertRevisionField rev
| rev == 1 = BS.unlines . insertAfterVersion . BS.lines
| otherwise = BS.unlines . replaceRevision . BS.lines
where
replaceRevision [] = []
replaceRevision (ln:lns)
| isField (BS.pack "x-revision") ln
= BS.pack ("x-revision: " ++ show rev) : lns
| otherwise
= ln : replaceRevision lns
insertAfterVersion [] = []
insertAfterVersion (ln:lns)
| isField (BS.pack "version") ln
= ln : BS.pack ("x-revision: " ++ show rev) : lns
| otherwise
= ln : insertAfterVersion lns
isField nm ln
| BS.isPrefixOf nm (BS.map Char.toLower ln)
, let (_, t) = BS.span (\c -> c == ' ' || c == '\t')
(BS.drop (BS.length nm) ln)
, Just (':',_) <- BS.uncons t
= True
| otherwise = False
| grayjay/hackage-server | Distribution/Server/Features/EditCabalFiles.hs | bsd-3-clause | 20,599 | 0 | 18 | 5,517 | 5,058 | 2,556 | 2,502 | 402 | 5 |
{-# OPTIONS_HADDOCK not-home #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.LXC.Internal.AttachOptions
-- Copyright : (c) Nickolay Kudasov 2014
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : [email protected]
--
-- Internal module to support options and structures to run
-- commands inside LXC containers.
-- Normally you should import @System.LXC@ module only.
--
-----------------------------------------------------------------------------
module System.LXC.Internal.AttachOptions where
import Bindings.LXC.AttachOptions
import Data.Int
import Data.Maybe
import Foreign
import Foreign.C
import System.LXC.Internal.Utils
import System.Posix.Types
-- | @exec@ function to use for 'System.LXC.Container.attach'.
--
-- See 'attachRunCommand' and 'attachRunShell'.
newtype AttachExecFn = AttachExecFn { getAttachExecFn :: C_lxc_attach_exec_t }
-- | LXC environment policy.
data AttachEnvPolicy
= AttachKeepEnv -- ^ Retain the environment.
| AttachClearEnv -- ^ Clear the environment.
deriving (Eq, Show)
-- | Convert 'AttachEnvPolicy' to internal representation.
fromAttachEnvPolicy :: Num a => AttachEnvPolicy -> a
fromAttachEnvPolicy AttachKeepEnv = c'LXC_ATTACH_KEEP_ENV
fromAttachEnvPolicy AttachClearEnv = c'LXC_ATTACH_CLEAR_ENV
-- | Flags for 'System.LXC.Container.attach'.
data AttachFlag
= AttachMoveToCGroup -- ^ Move to cgroup. On by default.
| AttachDropCapabilities -- ^ Drop capabilities. On by default.
| AttachSetPersonality -- ^ Set personality. On by default
| AttachLSMExec -- ^ Execute under a Linux Security Module. On by default.
| AttachRemountProcSys -- ^ Remount /proc filesystem. Off by default.
| AttachLSMNow -- ^ FIXME: unknown. Off by default.
| AttachDefault -- ^ Mask of flags to apply by default.
| AttachLSM -- ^ All Linux Security Module flags.
deriving (Eq, Show)
-- | Convert 'AttachFlag' to bit flag.
fromAttachFlag :: Num a => AttachFlag -> a
fromAttachFlag AttachMoveToCGroup = c'LXC_ATTACH_MOVE_TO_CGROUP
fromAttachFlag AttachDropCapabilities = c'LXC_ATTACH_DROP_CAPABILITIES
fromAttachFlag AttachSetPersonality = c'LXC_ATTACH_SET_PERSONALITY
fromAttachFlag AttachLSMExec = c'LXC_ATTACH_LSM_EXEC
fromAttachFlag AttachRemountProcSys = c'LXC_ATTACH_REMOUNT_PROC_SYS
fromAttachFlag AttachLSMNow = c'LXC_ATTACH_LSM_NOW
fromAttachFlag AttachDefault = c'LXC_ATTACH_DEFAULT
fromAttachFlag AttachLSM = c'LXC_ATTACH_LSM
-- | LXC attach options for 'System.LXC.Container.attach'.
--
-- * /NOTE:/ for @stdin@, @stdout@ and @stderr@ descriptors
-- @dup2()@ will be used before calling @exec_function@,
-- (assuming not @0@, @1@ and @2@ are specified) and the
-- original fds are closed before passing control
-- over. Any @O_CLOEXEC@ flag will be removed after that.
data AttachOptions = AttachOptions
{ attachFlags :: [AttachFlag] -- ^ Any combination of 'AttachFlag' flags.
, attachNamespaces :: Int -- ^ The namespaces to attach to (CLONE_NEW... flags).
-- | Initial personality (@Nothing@ to autodetect).
--
-- * This may be ignored if @lxc@ is compiled without personality support
, attachPersonality :: Maybe Int64
-- | Inital current directory, @Nothing@ to use @cwd@.
--
-- If the current directory does not exist in the container, the
-- root directory will be used instead because of kernel defaults.
, attachInitialCWD :: Maybe FilePath
-- | The user-id to run as.
--
-- * /NOTE:/ Set to @-1@ for default behaviour (init uid for userns
-- containers or @0@ (super-user) if detection fails).
, attachUID :: UserID
-- |The group-id to run as.
--
-- * /NOTE:/ Set to @-1@ for default behaviour (init gid for userns
-- containers or @0@ (super-user) if detection fails).
, attachGID :: GroupID
, attachEnvPolicy :: AttachEnvPolicy -- ^ Environment policy.
, attachExtraEnvVars :: [String] -- ^ Extra environment variables to set in the container environment.
, attachExtraKeepEnv :: [String] -- ^ Names of environment variables in existing environment to retain in container environment.
, attachStdinFD :: Fd -- ^ @stdin@ file descriptor.
, attachStdoutFD :: Fd -- ^ @stdout@ file descriptor.
, attachStderrFD :: Fd -- ^ @stderr@ file descriptor.
}
deriving (Show)
-- | Default attach options to use.
defaultAttachOptions :: AttachOptions
defaultAttachOptions = AttachOptions
{ attachFlags = [AttachDefault]
, attachNamespaces = -1
, attachPersonality = Nothing
, attachInitialCWD = Nothing
, attachUID = -1
, attachGID = -1
, attachEnvPolicy = AttachKeepEnv
, attachExtraEnvVars = []
, attachExtraKeepEnv = []
, attachStdinFD = 0
, attachStdoutFD = 1
, attachStderrFD = 2
}
-- | Representation of a command to run in a container.
data AttachCommand = AttachCommand
{ attachProgram :: FilePath -- ^ The program to run (passed to @execvp@).
, attachArgv :: [String] -- ^ The @argv@ of that program, including the program itself as the first element.
}
-- | Allocate @lxc_attach_options_t@ structure in a temporary storage.
withC'lxc_attach_options_t :: AttachOptions -> (Ptr C'lxc_attach_options_t -> IO a) -> IO a
withC'lxc_attach_options_t a f = do
alloca $ \ca ->
maybeWith withCString (attachInitialCWD a) $ \cinitialCWD ->
withMany withCString (attachExtraEnvVars a) $ \cextraEnvVars ->
withArray0 nullPtr cextraEnvVars $ \cextraEnvVars' ->
withMany withCString (attachExtraKeepEnv a) $ \cextraKeepEnv ->
withArray0 nullPtr cextraKeepEnv $ \cextraKeepEnv' -> do
poke (p'lxc_attach_options_t'attach_flags ca) (mkFlags fromAttachFlag . attachFlags $ a)
poke (p'lxc_attach_options_t'namespaces ca) (fromIntegral . attachNamespaces $ a)
poke (p'lxc_attach_options_t'personality ca) (fromIntegral . fromMaybe (-1) . attachPersonality $ a)
poke (p'lxc_attach_options_t'initial_cwd ca) cinitialCWD
poke (p'lxc_attach_options_t'uid ca) (fromIntegral . attachUID $ a)
poke (p'lxc_attach_options_t'gid ca) (fromIntegral . attachGID $ a)
poke (p'lxc_attach_options_t'env_policy ca) (fromAttachEnvPolicy . attachEnvPolicy $ a)
poke (p'lxc_attach_options_t'extra_env_vars ca) cextraEnvVars'
poke (p'lxc_attach_options_t'extra_keep_env ca) cextraKeepEnv'
poke (p'lxc_attach_options_t'stdin_fd ca) (fromIntegral . attachStdinFD $ a)
poke (p'lxc_attach_options_t'stdout_fd ca) (fromIntegral . attachStdoutFD $ a)
poke (p'lxc_attach_options_t'stderr_fd ca) (fromIntegral . attachStderrFD $ a)
f ca
-- | Allocate @lxc_attach_command_t@ structure in a temporary storage.
withC'lxc_attach_command_t :: AttachCommand -> (Ptr C'lxc_attach_command_t -> IO a) -> IO a
withC'lxc_attach_command_t a f = do
alloca $ \ca ->
withCString (attachProgram a) $ \cprogram ->
withMany withCString (attachArgv a) $ \cargv ->
withArray0 nullPtr cargv $ \cargv' -> do
poke (p'lxc_attach_command_t'program ca) cprogram
poke (p'lxc_attach_command_t'argv ca) cargv'
f ca
-- | Run a command in the container.
attachRunCommand :: AttachExecFn
attachRunCommand = AttachExecFn p'lxc_attach_run_command
-- | Run a shell command in the container.
attachRunShell :: AttachExecFn
attachRunShell = AttachExecFn p'lxc_attach_run_shell
| fizruk/lxc | src/System/LXC/Internal/AttachOptions.hs | bsd-3-clause | 7,969 | 0 | 28 | 1,878 | 1,113 | 625 | 488 | 101 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- This examples requires you to: cabal install cookie
-- and: cabal install blaze-html
import Control.Monad (forM_)
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.Encoding as T
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Blaze.ByteString.Builder as B
import qualified Text.Blaze.Html5 as H
import Text.Blaze.Html5.Attributes
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Web.Scotty
import Web.Cookie
makeCookie :: BS.ByteString -> BS.ByteString -> SetCookie
makeCookie n v = def { setCookieName = n, setCookieValue = v }
renderSetCookie' :: SetCookie -> Text
renderSetCookie' = T.decodeUtf8 . B.toLazyByteString . renderSetCookie
setCookie :: BS.ByteString -> BS.ByteString -> ActionM ()
setCookie n v = setHeader "Set-Cookie" (renderSetCookie' (makeCookie n v))
getCookies :: ActionM (Maybe CookiesText)
getCookies =
fmap (fmap (parseCookiesText . lazyToStrict . T.encodeUtf8)) $
reqHeader "Cookie"
where
lazyToStrict = BS.concat . BSL.toChunks
renderCookiesTable :: CookiesText -> H.Html
renderCookiesTable cs =
H.table $ do
H.tr $ do
H.th "name"
H.th "value"
forM_ cs $ \(name, val) -> do
H.tr $ do
H.td (H.toMarkup name)
H.td (H.toMarkup val)
main :: IO ()
main = scotty 3000 $ do
get "/" $ do
cookies <- getCookies
html $ renderHtml $ do
case cookies of
Just cs -> renderCookiesTable cs
Nothing -> return ()
H.form H.! method "post" H.! action "/set-a-cookie" $ do
H.input H.! type_ "text" H.! name "name"
H.input H.! type_ "text" H.! name "value"
H.input H.! type_ "submit" H.! value "set a cookie"
post "/set-a-cookie" $ do
name <- param "name"
value <- param "value"
setCookie name value
redirect "/"
| xich/scotty | examples/cookies.hs | bsd-3-clause | 2,044 | 0 | 19 | 533 | 623 | 319 | 304 | 51 | 2 |
module Codec.Binary.Proquint.QuickChecks
( prop_proquints_are_roundtrippable
, prop_magic_proquints_are_roundtrippable
)
where
import Data.Word
import Test.QuickCheck
import Test.QuickCheck.Arbitrary
import Codec.Binary.Proquint
prop_proquints_are_roundtrippable :: (Eq a, ToProquint a) => a -> Property
prop_proquints_are_roundtrippable x = property $ fromProquint (toProquint x) == x
prop_magic_proquints_are_roundtrippable :: (Eq a, ToProquint a) => a -> Property
prop_magic_proquints_are_roundtrippable x = property $ fromProquint (toProquintWithMagic x) == x
| hellertime/proquint | src/Codec/Binary/Proquint/QuickChecks.hs | bsd-3-clause | 582 | 0 | 9 | 74 | 136 | 75 | 61 | 11 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Dalvik.AccessFlags
( AccessFlag(..)
, AccessFlags
, AccessType(..)
, flagCode
, codeFlag
, flagString
, flagsString
, hasAccessFlag
) where
import Data.Bits
import Data.List
import Data.Monoid
import Data.String
import Data.Word
import Text.Printf
type AccessFlags = Word32
data AccessFlag
= ACC_PUBLIC
| ACC_PRIVATE
| ACC_PROTECTED
| ACC_STATIC
| ACC_FINAL
| ACC_SYNCHRONIZED
| ACC_VOLATILE
| ACC_BRIDGE
| ACC_TRANSIENT
| ACC_VARARGS
| ACC_NATIVE
| ACC_INTERFACE
| ACC_ABSTRACT
| ACC_STRICT
| ACC_SYNTHETIC
| ACC_ANNOTATION
| ACC_ENUM
| ACC_CONSTRUCTOR
| ACC_DECLARED_SYNCHRONIZED
deriving (Eq, Enum)
flagCode :: AccessFlag -> Word32
flagCode ACC_PUBLIC = 0x1
flagCode ACC_PRIVATE = 0x2
flagCode ACC_PROTECTED = 0x4
flagCode ACC_STATIC = 0x8
flagCode ACC_FINAL = 0x10
flagCode ACC_SYNCHRONIZED = 0x20
flagCode ACC_VOLATILE = 0x40
flagCode ACC_BRIDGE = 0x40
flagCode ACC_TRANSIENT = 0x80
flagCode ACC_VARARGS = 0x80
flagCode ACC_NATIVE = 0x100
flagCode ACC_INTERFACE = 0x200
flagCode ACC_ABSTRACT = 0x400
flagCode ACC_STRICT = 0x800
flagCode ACC_SYNTHETIC = 0x1000
flagCode ACC_ANNOTATION = 0x2000
flagCode ACC_ENUM = 0x4000
flagCode ACC_CONSTRUCTOR = 0x10000
flagCode ACC_DECLARED_SYNCHRONIZED = 0x20000
data AccessType = AClass | AField | AMethod deriving Eq
{-
tyString :: (IsString s) => AccessType -> s
tyString AClass = "class"
tyString AField = "field"
tyString AMethod = "method"
-}
codeFlag :: AccessType -> Word32 -> AccessFlag
codeFlag _ 0x00001 = ACC_PUBLIC
codeFlag _ 0x00002 = ACC_PRIVATE
codeFlag _ 0x00004 = ACC_PROTECTED
codeFlag _ 0x00008 = ACC_STATIC
codeFlag _ 0x00010 = ACC_FINAL
codeFlag AMethod 0x00020 = ACC_SYNCHRONIZED
codeFlag AField 0x00040 = ACC_VOLATILE
codeFlag AMethod 0x00040 = ACC_BRIDGE
codeFlag AField 0x00080 = ACC_TRANSIENT
codeFlag AMethod 0x00080 = ACC_VARARGS
codeFlag AMethod 0x00100 = ACC_NATIVE
codeFlag AClass 0x00200 = ACC_INTERFACE
codeFlag AClass 0x00400 = ACC_ABSTRACT
codeFlag AMethod 0x00400 = ACC_ABSTRACT
codeFlag AMethod 0x00800 = ACC_STRICT
codeFlag _ 0x01000 = ACC_SYNTHETIC
codeFlag AClass 0x02000 = ACC_ANNOTATION
codeFlag AClass 0x04000 = ACC_ENUM
codeFlag AField 0x04000 = ACC_ENUM
codeFlag AMethod 0x10000 = ACC_CONSTRUCTOR
codeFlag AMethod 0x20000 = ACC_DECLARED_SYNCHRONIZED
codeFlag _ bits = error $ printf "(unknown access flag %08x)" bits
flagString :: (IsString s) => AccessFlag -> s
flagString ACC_PUBLIC = "PUBLIC"
flagString ACC_PRIVATE = "PRIVATE"
flagString ACC_PROTECTED = "PROTECTED"
flagString ACC_STATIC = "STATIC"
flagString ACC_FINAL = "FINAL"
flagString ACC_SYNCHRONIZED = "SYNCHRONIZED"
flagString ACC_VOLATILE = "VOLATILE"
flagString ACC_BRIDGE = "BRIDGE"
flagString ACC_TRANSIENT = "TRANSIENT"
flagString ACC_VARARGS = "VARARGS"
flagString ACC_NATIVE = "NATIVE"
flagString ACC_INTERFACE = "INTERFACE"
flagString ACC_ABSTRACT = "ABSTRACT"
flagString ACC_STRICT = "STRICT"
flagString ACC_SYNTHETIC = "SYNTHETIC"
flagString ACC_ANNOTATION = "ANNOTATION"
flagString ACC_ENUM = "ENUM"
flagString ACC_CONSTRUCTOR = "CONSTRUCTOR"
flagString ACC_DECLARED_SYNCHRONIZED = "DECLARED_SYNCHRONIZED"
flagsString :: (IsString s, Monoid s) => AccessType -> Word32 -> s
flagsString ty w = mconcat $ intersperse " "
[ flagString (codeFlag ty c) | c <- allCodes, w .&. c /= 0 ]
where allCodes = [ 0x00001, 0x00002, 0x00004, 0x00008
, 0x00010, 0x00020, 0x00040, 0x00080
, 0x00100, 0x00200, 0x00400, 0x00800
, 0x01000, 0x02000, 0x04000
, 0x10000, 0x20000
]
andTrue :: Word32 -> Word32 -> Bool
andTrue w1 w2 = (w1 .&. w2) /= 0
hasAccessFlag :: AccessFlag -> Word32 -> Bool
hasAccessFlag f = andTrue (flagCode f)
| atomb/dalvik | Dalvik/AccessFlags.hs | bsd-3-clause | 3,840 | 0 | 10 | 721 | 942 | 507 | 435 | 114 | 1 |
{-# LANGUAGE DeriveDataTypeable, RecordWildCards, CPP, ForeignFunctionInterface, ScopedTypeVariables #-}
-- | Progress tracking
module B.Shake.Progress(
Progress(..),
progressSimple, progressDisplay, progressTitlebar,
progressDisplayTester -- INTERNAL FOR TESTING ONLY
) where
import Control.Arrow
import Control.Applicative
import Control.Concurrent
import Control.Exception
import Control.Monad
import System.Environment
import Data.Data
import Data.Maybe
import Data.Monoid
import qualified Data.ByteString.Char8 as BS
import System.IO.Unsafe
#ifdef mingw32_HOST_OS
import Foreign
import Foreign.C.Types
type LPCSTR = Ptr CChar
foreign import stdcall "Windows.h SetConsoleTitleA" c_setConsoleTitle :: LPCSTR -> IO Bool
#endif
---------------------------------------------------------------------
-- PROGRESS TYPES - exposed to the user
-- | Information about the current state of the build, obtained by passing a callback function
-- to 'Development.Shake.shakeProgress'. Typically a program will use 'progressDisplay' to poll this value and produce
-- status messages, which is implemented using this data type.
data Progress = Progress
{isRunning :: !Bool -- ^ Starts out 'True', becomes 'False' once the build has completed.
,isFailure :: !(Maybe String) -- ^ Starts out 'Nothing', becomes 'Just' if a rule fails.
,countSkipped :: {-# UNPACK #-} !Int -- ^ Number of rules which were required, but were already in a valid state.
,countBuilt :: {-# UNPACK #-} !Int -- ^ Number of rules which were have been built in this run.
,countUnknown :: {-# UNPACK #-} !Int -- ^ Number of rules which have been built previously, but are not yet known to be required.
,countTodo :: {-# UNPACK #-} !Int -- ^ Number of rules which are currently required (ignoring dependencies that do not change), but not built.
,timeSkipped :: {-# UNPACK #-} !Double -- ^ Time spent building 'countSkipped' rules in previous runs.
,timeBuilt :: {-# UNPACK #-} !Double -- ^ Time spent building 'countBuilt' rules.
,timeUnknown :: {-# UNPACK #-} !Double -- ^ Time spent building 'countUnknown' rules in previous runs.
,timeTodo :: {-# UNPACK #-} !(Double,Int) -- ^ Time spent building 'countTodo' rules in previous runs, plus the number which have no known time (have never been built before).
}
deriving (Eq,Ord,Show,Data,Typeable)
instance Monoid Progress where
mempty = Progress True Nothing 0 0 0 0 0 0 0 (0,0)
mappend a b = Progress
{isRunning = isRunning a && isRunning b
,isFailure = isFailure a `mappend` isFailure b
,countSkipped = countSkipped a + countSkipped b
,countBuilt = countBuilt a + countBuilt b
,countUnknown = countUnknown a + countUnknown b
,countTodo = countTodo a + countTodo b
,timeSkipped = timeSkipped a + timeSkipped b
,timeBuilt = timeBuilt a + timeBuilt b
,timeUnknown = timeUnknown a + timeUnknown b
,timeTodo = let (a1,a2) = timeTodo a; (b1,b2) = timeTodo b
x1 = a1 + b1; x2 = a2 + b2
in x1 `seq` x2 `seq` (x1,x2)
}
---------------------------------------------------------------------
-- STREAM TYPES - for writing the progress functions
-- | A stream of values
newtype Stream a b = Stream {runStream :: a -> (b, Stream a b)}
instance Functor (Stream a) where
fmap f (Stream op) = Stream $ (f *** fmap f) . op
instance Applicative (Stream a) where
pure x = Stream $ const (x, pure x)
Stream ff <*> Stream xx = Stream $ \a ->
let (f1,f2) = ff a
(x1,x2) = xx a
in (f1 x1, f2 <*> x2)
idStream :: Stream a a
idStream = Stream $ \a -> (a, idStream)
oldStream :: b -> Stream a b -> Stream a (b,b)
oldStream old (Stream f) = Stream $ \a ->
let (new, f2) = f a
in ((old,new), oldStream new f2)
iff :: Stream a Bool -> Stream a b -> Stream a b -> Stream a b
iff c t f = (\c t f -> if c then t else f) <$> c <*> t <*> f
foldStream :: (a -> b -> a) -> a -> Stream i b -> Stream i a
foldStream f z (Stream op) = Stream $ \a ->
let (o1,o2) = op a
z2 = f z o1
in (z2, foldStream f z2 o2)
posStream :: Stream a Int
posStream = foldStream (+) 0 $ pure 1
fromInt :: Int -> Double
fromInt = fromInteger . toInteger
-- decay'd division, compute a/b, with a decay of f
-- r' is the new result, r is the last result
-- r ~= a / b
-- r' = r*b + f*(a'-a)
-- -------------
-- b + f*(b'-b)
-- when f == 1, r == r'
decay :: Double -> Stream i Double -> Stream i Double -> Stream i Double
decay f a b = foldStream step 0 $ (,) <$> oldStream 0 a <*> oldStream 0 b
where step r ((a,a'),(b,b')) =((r*b) + f*(a'-a)) / (b + f*(b'-b))
latch :: Stream i (Bool, a) -> Stream i a
latch = f Nothing
where f old (Stream op) = Stream $ \x -> let ((b,v),s) = op x
v2 = if b then fromMaybe v old else v
in (v2, f (Just v2) s)
---------------------------------------------------------------------
-- MESSAGE GENERATOR
message :: Double -> Stream Progress Progress -> Stream Progress String
message sample progress = (\time perc -> time ++ " (" ++ perc ++ "%)") <$> time <*> perc
where
-- Number of seconds work completed
-- Ignores timeSkipped which would be more truthful, but it makes the % drop sharply
-- which isn't what users want
done = fmap timeBuilt progress
-- Predicted build time for a rule that has never been built before
-- The high decay means if a build goes in "phases" - lots of source files, then lots of compiling
-- we reach a reasonable number fairly quickly, without bouncing too much
guess = iff ((==) 0 <$> samples) (pure 0) $ decay 10 time $ fmap fromInt samples
where
time = flip fmap progress $ \Progress{..} -> timeBuilt + fst timeTodo
samples = flip fmap progress $ \Progress{..} -> countBuilt + countTodo - snd timeTodo
-- Number of seconds work remaining, ignoring multiple threads
todo = f <$> progress <*> guess
where f Progress{..} guess = fst timeTodo + (fromIntegral (snd timeTodo) * guess)
-- Number of seconds we have been going
step = fmap ((*) sample . fromInt) posStream
work = decay 1.2 done step
-- Work value to use, don't divide by 0 and don't update work if done doesn't change
realWork = iff ((==) 0 <$> done) (pure 1) $
latch $ (,) <$> (uncurry (==) <$> oldStream 0 done) <*> work
-- Display information
time = flip fmap ((/) <$> todo <*> realWork) $ \guess ->
let (mins,secs) = divMod (ceiling guess) (60 :: Int)
in (if mins == 0 then "" else show mins ++ "m" ++ ['0' | secs < 10]) ++ show secs ++ "s"
perc = iff ((==) 0 <$> done) (pure "0") $
(\done todo -> show (floor (100 * done / (done + todo)) :: Int)) <$> done <*> todo
---------------------------------------------------------------------
-- EXPOSED FUNCTIONS
-- | Given a sampling interval (in seconds) and a way to display the status message,
-- produce a function suitable for using as 'Development.Shake.shakeProgress'.
-- This function polls the progress information every /n/ seconds, produces a status
-- message and displays it using the display function.
--
-- Typical status messages will take the form of @1m25s (15%)@, indicating that the build
-- is predicted to complete in 1 minute 25 seconds (85 seconds total), and 15% of the necessary build time has elapsed.
-- This function uses past observations to predict future behaviour, and as such, is only
-- guessing. The time is likely to go up as well as down, and will be less accurate from a
-- clean build (as the system has fewer past observations).
--
-- The current implementation is to predict the time remaining (based on 'timeTodo') and the
-- work already done ('timeBuilt'). The percentage is then calculated as @remaining / (done + remaining)@,
-- while time left is calculated by scaling @remaining@ by the observed work rate in this build,
-- roughly @done / time_elapsed@.
progressDisplay :: Double -> (String -> IO ()) -> IO Progress -> IO ()
progressDisplay = progressDisplayer True
-- | Version of 'progressDisplay' that omits the sleep
progressDisplayTester :: Double -> (String -> IO ()) -> IO Progress -> IO ()
progressDisplayTester = progressDisplayer False
progressDisplayer :: Bool -> Double -> (String -> IO ()) -> IO Progress -> IO ()
progressDisplayer sleep sample disp prog = do
disp "Starting..." -- no useful info at this stage
loop $ message sample idStream
where
loop :: Stream Progress String -> IO ()
loop stream = do
when sleep $ threadDelay $ ceiling $ sample * 1000000
p <- prog
if not $ isRunning p then
disp "Finished"
else do
(msg, stream) <- return $ runStream stream p
disp $ msg ++ maybe "" (\err -> ", Failure! " ++ err) (isFailure p)
loop stream
{-# NOINLINE xterm #-}
xterm :: Bool
xterm = System.IO.Unsafe.unsafePerformIO $
Control.Exception.catch (fmap (== "xterm") $ getEnv "TERM") $
\(e :: SomeException) -> return False
-- | Set the title of the current console window to the given text. If the
-- environment variable @$TERM@ is set to @xterm@ this uses xterm escape sequences.
-- On Windows, if not detected as an xterm, this function uses the @SetConsoleTitle@ API.
progressTitlebar :: String -> IO ()
progressTitlebar x
| xterm = BS.putStr $ BS.pack $ "\ESC]0;" ++ x ++ "\BEL"
#ifdef mingw32_HOST_OS
| otherwise = BS.useAsCString (BS.pack x) $ \x -> c_setConsoleTitle x >> return ()
#else
| otherwise = return ()
#endif
-- | A simple method for displaying progress messages, suitable for using as
-- 'Development.Shake.shakeProgress'. This function writes the current progress to
-- the titlebar every five seconds. The function is defined as:
--
-- @
--progressSimple = 'progressDisplay' 5 'progressTitlebar'
-- @
progressSimple :: IO Progress -> IO ()
progressSimple = progressDisplay 5 progressTitlebar
| strager/b-shake | B/Shake/Progress.hs | bsd-3-clause | 10,274 | 0 | 18 | 2,502 | 2,445 | 1,314 | 1,131 | 127 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Binary.Defer
-- Copyright : Neil Mitchell
-- License : BSD3
--
-- Maintainer : Neil Mitchell <http://community.haskell.org/~ndm/>
-- Stability : unstable
-- Portability : portable to Hugs and GHC. Requires Control.Exception.catch
--
-- Binary serialisation of deferred values
--
-----------------------------------------------------------------------------
module Data.Binary.Defer(
BinaryDefer(..), put,
BinaryDeferStatic(..),
defer,
Defer(..),
unit, (<<), (<<~), (<<!)
) where
import Prelude hiding (catch)
import Control.Exception (catch, SomeException)
import System.IO
import System.IO.Unsafe (unsafePerformIO)
import Control.Monad
import Data.Binary.Defer.Internal
class BinaryDefer a where
-- take a data value
-- return a function to save that data value
-- and one to load it
bothDefer :: (Handle -> a -> IO [(Int, IO ())], Handle -> IO a)
bothDefer = (putDefer, get)
putDefer :: Handle -> a -> IO [(Int, IO ())]
putDefer = fst bothDefer
get :: Handle -> IO a
get = snd bothDefer
put :: BinaryDefer a => Handle -> a -> IO ()
put hndl x = putDefer hndl x >>= mapM_ f . reverse
where
f (pos,action) = do
i <- hGetPos hndl
hSetPos hndl pos
hPutInt hndl i
hSetPos hndl i
action
class BinaryDefer a => BinaryDeferStatic a where
-- | Must be a constant, must not examine first argument
getSize :: a -> Int
-- have you used any combinators of <<, <<~ or <<!
data PendingNone = PendingNone
data PendingSome = PendingSome
data Pending a b = Pending {psave :: Handle -> Int -> IO [(Int, IO ())], pload :: Handle -> IO a}
type Both a = (Handle -> a -> IO [(Int, IO ())], Handle -> IO a)
deferOne :: (a -> Pending a PendingSome) -> Both a
deferOne x = (save, load)
where
save hndl value = psave (x value) hndl (-1)
load hndl = pload (x undefined) hndl
defer :: [a -> Pending a PendingSome] -> Both a
defer [x] = deferOne x
defer xs = (save, load)
where
-- value `seq` is important to that a _|_ in value is
-- thrown before entering a Catch statement
-- may still not be safe if multiple levels of combinators
save hndl value = value `seq` f (zip [0::Int ..] xs)
where
f [] = error "unmatched item to save, or trying to save _|_"
f ((i,x):xs) = catch (psave (x value) hndl i) (\(e :: SomeException) -> f xs)
load hndl = do
i <- hGetInt hndl
pload ((xs !! i) undefined) hndl
instance BinaryDefer Int where
putDefer hndl x = hPutInt hndl x >> return []
get hndl = hGetInt hndl
instance BinaryDefer a => BinaryDefer [a] where
putDefer hndl xs = hPutInt hndl (length xs) >> concatMapM (putDefer hndl) xs
where concatMapM f = liftM concat . mapM f
get hndl = do i <- hGetInt hndl; replicateM i (get hndl)
instance BinaryDefer Char where
putDefer hndl x = hPutChar hndl x >> return []
get hndl = hGetChar hndl
instance BinaryDefer Bool where
putDefer hndl x = putDefer hndl (if x then '1' else '0')
get hndl = get hndl >>= return . (== '1')
instance BinaryDeferStatic Int where getSize _ = 4
instance BinaryDeferStatic Char where getSize _ = 1
instance BinaryDeferStatic Bool where getSize _ = 1
unit :: a -> Pending a PendingNone
unit f = Pending (\hndl i -> when (i /= -1) (hPutInt hndl i) >> return [])
(const $ return f)
(<<!) :: Pending a p -> a -> Pending a PendingSome
(<<!) (Pending save load) val = Pending (val `seq` save) load
(<<) :: BinaryDefer a => Pending (a -> b) p -> a -> Pending b PendingSome
(Pending save load) << x = Pending
(\hndl i -> x `seq` do lazy <- save hndl i; l <- s hndl x; return (l ++ lazy))
(\hndl -> do f <- load hndl; x2 <- l hndl; return (f x2))
where (s,l) = bothDefer
(<<~) :: BinaryDefer a => Pending (a -> b) p -> a -> Pending b PendingSome
(Pending save load) <<~ x = Pending
(\hndl i -> x `seq` do
lazy <- save hndl i
pos <- hGetPos hndl
hPutInt hndl 0
return ((pos,put hndl x):lazy))
(\hndl -> do
f <- load hndl
pos <- hGetInt hndl
return $ f $ lazyRead hndl pos)
where
lazyRead hndl pos = unsafePerformIO $ do
p <- hGetPos hndl
hSetPos hndl pos
res <- get hndl
hSetPos hndl p
return res
newtype Defer x = Defer {fromDefer :: x}
instance BinaryDefer a => BinaryDefer (Defer a) where
bothDefer = defer [\ ~(Defer a) -> unit Defer <<~ a]
instance Show a => Show (Defer a) where
show (Defer a) = "(Defer " ++ show a ++ ")"
instance BinaryDefer a => BinaryDeferStatic (Defer a) where
getSize _ = 4
| ndmitchell/binarydefer | Data/Binary/Defer.hs | bsd-3-clause | 4,946 | 0 | 15 | 1,369 | 1,763 | 910 | 853 | 97 | 2 |
import Prelude hiding (readFile)
import System.IO.Strict (readFile)
| YoshikuniJujo/funpaala | samples/40_lifegame/strict.hs | bsd-3-clause | 68 | 0 | 5 | 7 | 21 | 13 | 8 | 2 | 0 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Persist.Migration
( doMigrate
) where
import NejlaCommon.Persistence.Migration as M
migrations :: [Migration]
migrations =
[ Migration { expect = Nothing -- No migrations present
, to = "1"
, description = "Initial version"
, script = do
schemaEmptyP "public" >>= \case
True -> do -- Database not initialized at all
rawExecute $(sqlFile "src/Persist/migrations/01-initial.sql") []
False -> -- Database _was_ initialized, but schema
-- versionioning wasn't in use
return ()
}
, Migration { expect = Just "1"
, to = "2"
, description = "Case insenstivie email addresses"
, script = rawExecute
$(sqlFile "src/Persist/migrations/02-ci-emails.sql") []
}
, Migration { expect = Just "2"
, to = "3"
, description = "Add \"deactive\" field to \"user\" relation\""
, script = rawExecute
$(sqlFile "src/Persist/migrations/03-user-deactivation.sql") []
}
, Migration { expect = Just "3"
, to = "4"
, description = "Add audit_log table"
, script = rawExecute
$(sqlFile "src/Persist/migrations/04-add-audit-log.sql") []
}
, Migration { expect = Just "4"
, to = "5"
, description = "Add login_attempt table"
, script = rawExecute
$(sqlFile "src/Persist/migrations/05-login-attempt.sql") []
}
]
doMigrate :: M ()
doMigrate = M.migrate $(gitHash) migrations
| nejla/auth-service | service/src/Persist/Migration.hs | bsd-3-clause | 1,884 | 0 | 19 | 736 | 324 | 184 | 140 | 39 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GADTs #-}
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE DeriveGeneric #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2012-2015 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- Plücker coordinates for lines in 3d homogeneous space.
----------------------------------------------------------------------------
module Linear.Plucker
( Plucker(..)
, squaredError
, isotropic
, (><)
, plucker
, plucker3D
-- * Operations on lines
, parallel
, intersects
, LinePass(..)
, passes
, quadranceToOrigin
, closestToOrigin
, isLine
, coincides
, coincides'
-- * Basis elements
, p01, p02, p03
, p10, p12, p13
, p20, p21, p23
, p30, p31, p32
, e01, e02, e03, e12, e31, e23
) where
import Control.Applicative
import Control.DeepSeq (NFData(rnf))
import Control.Monad (liftM)
import Control.Monad.Fix
import Control.Monad.Zip
import Control.Lens hiding (index, (<.>))
import Data.Binary as Binary
import Data.Bytes.Serial
import Data.Distributive
import Data.Foldable as Foldable
import Data.Functor.Bind
import Data.Functor.Classes
import Data.Functor.Rep
import Data.Hashable
import Data.Semigroup
import Data.Semigroup.Foldable
import Data.Serialize as Cereal
import Foreign.Ptr (castPtr)
import Foreign.Storable (Storable(..))
import GHC.Arr (Ix(..))
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702
import GHC.Generics (Generic)
#endif
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 706
import GHC.Generics (Generic1)
#endif
import qualified Data.Vector.Generic.Mutable as M
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Unboxed.Base as U
import Linear.Epsilon
import Linear.Metric
import Linear.V2
import Linear.V3
import Linear.V4
import Linear.Vector
{-# ANN module "HLint: ignore Reduce duplication" #-}
-- | Plücker coordinates for lines in a 3-dimensional space.
data Plucker a = Plucker !a !a !a !a !a !a deriving (Eq,Ord,Show,Read
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702
,Generic
#endif
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 706
,Generic1
#endif
)
instance Functor Plucker where
fmap g (Plucker a b c d e f) = Plucker (g a) (g b) (g c) (g d) (g e) (g f)
{-# INLINE fmap #-}
instance Apply Plucker where
Plucker a b c d e f <.> Plucker g h i j k l =
Plucker (a g) (b h) (c i) (d j) (e k) (f l)
{-# INLINE (<.>) #-}
instance Applicative Plucker where
pure a = Plucker a a a a a a
{-# INLINE pure #-}
Plucker a b c d e f <*> Plucker g h i j k l =
Plucker (a g) (b h) (c i) (d j) (e k) (f l)
{-# INLINE (<*>) #-}
instance Additive Plucker where
zero = pure 0
{-# INLINE zero #-}
liftU2 = liftA2
{-# INLINE liftU2 #-}
liftI2 = liftA2
{-# INLINE liftI2 #-}
instance Bind Plucker where
Plucker a b c d e f >>- g = Plucker a' b' c' d' e' f' where
Plucker a' _ _ _ _ _ = g a
Plucker _ b' _ _ _ _ = g b
Plucker _ _ c' _ _ _ = g c
Plucker _ _ _ d' _ _ = g d
Plucker _ _ _ _ e' _ = g e
Plucker _ _ _ _ _ f' = g f
{-# INLINE (>>-) #-}
instance Monad Plucker where
return a = Plucker a a a a a a
{-# INLINE return #-}
Plucker a b c d e f >>= g = Plucker a' b' c' d' e' f' where
Plucker a' _ _ _ _ _ = g a
Plucker _ b' _ _ _ _ = g b
Plucker _ _ c' _ _ _ = g c
Plucker _ _ _ d' _ _ = g d
Plucker _ _ _ _ e' _ = g e
Plucker _ _ _ _ _ f' = g f
{-# INLINE (>>=) #-}
instance Distributive Plucker where
distribute f = Plucker (fmap (\(Plucker x _ _ _ _ _) -> x) f)
(fmap (\(Plucker _ x _ _ _ _) -> x) f)
(fmap (\(Plucker _ _ x _ _ _) -> x) f)
(fmap (\(Plucker _ _ _ x _ _) -> x) f)
(fmap (\(Plucker _ _ _ _ x _) -> x) f)
(fmap (\(Plucker _ _ _ _ _ x) -> x) f)
{-# INLINE distribute #-}
instance Representable Plucker where
type Rep Plucker = E Plucker
tabulate f = Plucker (f e01) (f e02) (f e03) (f e23) (f e31) (f e12)
{-# INLINE tabulate #-}
index xs (E l) = view l xs
{-# INLINE index #-}
instance Foldable Plucker where
foldMap g (Plucker a b c d e f) =
g a `mappend` g b `mappend` g c `mappend` g d `mappend` g e `mappend` g f
{-# INLINE foldMap #-}
instance Traversable Plucker where
traverse g (Plucker a b c d e f) =
Plucker <$> g a <*> g b <*> g c <*> g d <*> g e <*> g f
{-# INLINE traverse #-}
instance Foldable1 Plucker where
foldMap1 g (Plucker a b c d e f) =
g a <> g b <> g c <> g d <> g e <> g f
{-# INLINE foldMap1 #-}
instance Traversable1 Plucker where
traverse1 g (Plucker a b c d e f) =
Plucker <$> g a <.> g b <.> g c <.> g d <.> g e <.> g f
{-# INLINE traverse1 #-}
instance Ix a => Ix (Plucker a) where
range (Plucker l1 l2 l3 l4 l5 l6,Plucker u1 u2 u3 u4 u5 u6) =
[Plucker i1 i2 i3 i4 i5 i6 | i1 <- range (l1,u1)
, i2 <- range (l2,u2)
, i3 <- range (l3,u3)
, i4 <- range (l4,u4)
, i5 <- range (l5,u5)
, i6 <- range (l6,u6)
]
{-# INLINE range #-}
unsafeIndex (Plucker l1 l2 l3 l4 l5 l6,Plucker u1 u2 u3 u4 u5 u6) (Plucker i1 i2 i3 i4 i5 i6) =
unsafeIndex (l6,u6) i6 + unsafeRangeSize (l6,u6) * (
unsafeIndex (l5,u5) i5 + unsafeRangeSize (l5,u5) * (
unsafeIndex (l4,u4) i4 + unsafeRangeSize (l4,u4) * (
unsafeIndex (l3,u3) i3 + unsafeRangeSize (l3,u3) * (
unsafeIndex (l2,u2) i2 + unsafeRangeSize (l2,u2) *
unsafeIndex (l1,u1) i1))))
{-# INLINE unsafeIndex #-}
inRange (Plucker l1 l2 l3 l4 l5 l6,Plucker u1 u2 u3 u4 u5 u6) (Plucker i1 i2 i3 i4 i5 i6) =
inRange (l1,u1) i1 && inRange (l2,u2) i2 &&
inRange (l3,u3) i3 && inRange (l4,u4) i4 &&
inRange (l5,u5) i5 && inRange (l6,u6) i6
{-# INLINE inRange #-}
instance Num a => Num (Plucker a) where
(+) = liftA2 (+)
{-# INLINE (+) #-}
(-) = liftA2 (-)
{-# INLINE (-) #-}
(*) = liftA2 (*)
{-# INLINE (*) #-}
negate = fmap negate
{-# INLINE negate #-}
abs = fmap abs
{-# INLINE abs #-}
signum = fmap signum
{-# INLINE signum #-}
fromInteger = pure . fromInteger
{-# INLINE fromInteger #-}
instance Fractional a => Fractional (Plucker a) where
recip = fmap recip
{-# INLINE recip #-}
(/) = liftA2 (/)
{-# INLINE (/) #-}
fromRational = pure . fromRational
{-# INLINE fromRational #-}
instance Floating a => Floating (Plucker a) where
pi = pure pi
{-# INLINE pi #-}
exp = fmap exp
{-# INLINE exp #-}
sqrt = fmap sqrt
{-# INLINE sqrt #-}
log = fmap log
{-# INLINE log #-}
(**) = liftA2 (**)
{-# INLINE (**) #-}
logBase = liftA2 logBase
{-# INLINE logBase #-}
sin = fmap sin
{-# INLINE sin #-}
tan = fmap tan
{-# INLINE tan #-}
cos = fmap cos
{-# INLINE cos #-}
asin = fmap asin
{-# INLINE asin #-}
atan = fmap atan
{-# INLINE atan #-}
acos = fmap acos
{-# INLINE acos #-}
sinh = fmap sinh
{-# INLINE sinh #-}
tanh = fmap tanh
{-# INLINE tanh #-}
cosh = fmap cosh
{-# INLINE cosh #-}
asinh = fmap asinh
{-# INLINE asinh #-}
atanh = fmap atanh
{-# INLINE atanh #-}
acosh = fmap acosh
{-# INLINE acosh #-}
instance Hashable a => Hashable (Plucker a) where
hashWithSalt s (Plucker a b c d e f) = s `hashWithSalt` a `hashWithSalt` b `hashWithSalt` c `hashWithSalt` d `hashWithSalt` e `hashWithSalt` f
{-# INLINE hashWithSalt #-}
instance Storable a => Storable (Plucker a) where
sizeOf _ = 6 * sizeOf (undefined::a)
{-# INLINE sizeOf #-}
alignment _ = alignment (undefined::a)
{-# INLINE alignment #-}
poke ptr (Plucker a b c d e f) = do
poke ptr' a
pokeElemOff ptr' 1 b
pokeElemOff ptr' 2 c
pokeElemOff ptr' 3 d
pokeElemOff ptr' 4 e
pokeElemOff ptr' 5 f
where ptr' = castPtr ptr
{-# INLINE poke #-}
peek ptr = Plucker <$> peek ptr'
<*> peekElemOff ptr' 1
<*> peekElemOff ptr' 2
<*> peekElemOff ptr' 3
<*> peekElemOff ptr' 4
<*> peekElemOff ptr' 5
where ptr' = castPtr ptr
{-# INLINE peek #-}
instance Metric Plucker where
dot (Plucker a b c d e f) (Plucker g h i j k l) = a*g+b*h+c*i+d*j+e*k+f*l
{-# INLINE dot #-}
instance Epsilon a => Epsilon (Plucker a) where
nearZero = nearZero . quadrance
{-# INLINE nearZero #-}
-- | Given a pair of points represented by homogeneous coordinates
-- generate Plücker coordinates for the line through them, directed
-- from the second towards the first.
plucker :: Num a => V4 a -> V4 a -> Plucker a
plucker (V4 a b c d)
(V4 e f g h) =
Plucker (a*f-b*e)
(a*g-c*e)
(b*g-c*f)
(a*h-d*e)
(b*h-d*f)
(c*h-d*g)
{-# INLINE plucker #-}
-- | Given a pair of 3D points, generate Plücker coordinates for the
-- line through them, directed from the second towards the first.
plucker3D :: Num a => V3 a -> V3 a -> Plucker a
plucker3D p q = Plucker a b c d e f
where V3 a b c = p - q
V3 d e f = p `cross` q
-- | These elements form a basis for the Plücker space, or the Grassmanian manifold @Gr(2,V4)@.
--
-- @
-- 'p01' :: 'Lens'' ('Plucker' a) a
-- 'p02' :: 'Lens'' ('Plucker' a) a
-- 'p03' :: 'Lens'' ('Plucker' a) a
-- 'p23' :: 'Lens'' ('Plucker' a) a
-- 'p31' :: 'Lens'' ('Plucker' a) a
-- 'p12' :: 'Lens'' ('Plucker' a) a
-- @
p01, p02, p03, p23, p31, p12 :: Lens' (Plucker a) a
p01 g (Plucker a b c d e f) = (\a' -> Plucker a' b c d e f) <$> g a
p02 g (Plucker a b c d e f) = (\b' -> Plucker a b' c d e f) <$> g b
p03 g (Plucker a b c d e f) = (\c' -> Plucker a b c' d e f) <$> g c
p23 g (Plucker a b c d e f) = (\d' -> Plucker a b c d' e f) <$> g d
p31 g (Plucker a b c d e f) = (\e' -> Plucker a b c d e' f) <$> g e
p12 g (Plucker a b c d e f) = Plucker a b c d e <$> g f
{-# INLINE p01 #-}
{-# INLINE p02 #-}
{-# INLINE p03 #-}
{-# INLINE p23 #-}
{-# INLINE p31 #-}
{-# INLINE p12 #-}
-- | These elements form an alternate basis for the Plücker space, or the Grassmanian manifold @Gr(2,V4)@.
--
-- @
-- 'p10' :: 'Num' a => 'Lens'' ('Plucker' a) a
-- 'p20' :: 'Num' a => 'Lens'' ('Plucker' a) a
-- 'p30' :: 'Num' a => 'Lens'' ('Plucker' a) a
-- 'p32' :: 'Num' a => 'Lens'' ('Plucker' a) a
-- 'p13' :: 'Num' a => 'Lens'' ('Plucker' a) a
-- 'p21' :: 'Num' a => 'Lens'' ('Plucker' a) a
-- @
p10, p20, p30, p32, p13, p21 :: (Functor f, Num a) => (a -> f a) -> Plucker a -> f (Plucker a)
p10 = anti p01
p20 = anti p02
p30 = anti p03
p32 = anti p23
p13 = anti p31
p21 = anti p21
{-# INLINE p10 #-}
{-# INLINE p20 #-}
{-# INLINE p30 #-}
{-# INLINE p32 #-}
{-# INLINE p13 #-}
{-# INLINE p21 #-}
anti :: (Functor f, Num a) => ((a -> f a) -> r) -> (a -> f a) -> r
anti k f = k (fmap negate . f . negate)
e01, e02, e03, e23, e31, e12 :: E Plucker
e01 = E p01
e02 = E p02
e03 = E p03
e23 = E p23
e31 = E p31
e12 = E p12
instance FunctorWithIndex (E Plucker) Plucker where
imap f (Plucker a b c d e g) = Plucker (f e01 a) (f e02 b) (f e03 c) (f e23 d) (f e31 e) (f e12 g)
{-# INLINE imap #-}
instance FoldableWithIndex (E Plucker) Plucker where
ifoldMap f (Plucker a b c d e g) = f e01 a `mappend` f e02 b `mappend` f e03 c
`mappend` f e23 d `mappend` f e31 e `mappend` f e12 g
{-# INLINE ifoldMap #-}
instance TraversableWithIndex (E Plucker) Plucker where
itraverse f (Plucker a b c d e g) = Plucker <$> f e01 a <*> f e02 b <*> f e03 c
<*> f e23 d <*> f e31 e <*> f e12 g
{-# INLINE itraverse #-}
type instance Index (Plucker a) = E Plucker
type instance IxValue (Plucker a) = a
instance Ixed (Plucker a) where
ix = el
{-# INLINE ix #-}
instance Each (Plucker a) (Plucker b) a b where
each = traverse
{-# INLINE each #-}
-- | Valid Plücker coordinates @p@ will have @'squaredError' p '==' 0@
--
-- That said, floating point makes a mockery of this claim, so you may want to use 'nearZero'.
squaredError :: (Eq a, Num a) => Plucker a -> a
squaredError v = v >< v
{-# INLINE squaredError #-}
-- | This isn't th actual metric because this bilinear form gives rise to an isotropic quadratic space
infixl 5 ><
(><) :: Num a => Plucker a -> Plucker a -> a
Plucker a b c d e f >< Plucker g h i j k l = a*l-b*k+c*j+d*i-e*h+f*g
{-# INLINE (><) #-}
-- | Checks if the line is near-isotropic (isotropic vectors in this
-- quadratic space represent lines in real 3d space).
isotropic :: Epsilon a => Plucker a -> Bool
isotropic a = nearZero (a >< a)
{-# INLINE isotropic #-}
-- | Checks if two lines intersect (or nearly intersect).
intersects :: (Epsilon a, Ord a) => Plucker a -> Plucker a -> Bool
intersects a b = not (a `parallel` b) && passes a b == Coplanar
-- intersects :: Epsilon a => Plucker a -> Plucker a -> Bool
-- intersects a b = nearZero (a >< b)
{-# INLINE intersects #-}
-- | Describe how two lines pass each other.
data LinePass = Coplanar
-- ^ The lines are coplanar (parallel or intersecting).
| Clockwise
-- ^ The lines pass each other clockwise (right-handed
-- screw)
| Counterclockwise
-- ^ The lines pass each other counterclockwise
-- (left-handed screw).
deriving (Eq, Show
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702
,Generic
#endif
)
-- | Check how two lines pass each other. @passes l1 l2@ describes
-- @l2@ when looking down @l1@.
passes :: (Epsilon a, Num a, Ord a) => Plucker a -> Plucker a -> LinePass
passes a b
| nearZero s = Coplanar
| s > 0 = Counterclockwise
| otherwise = Clockwise
where s = (u1 `dot` v2) + (u2 `dot` v1)
V2 u1 v1 = toUV a
V2 u2 v2 = toUV b
{-# INLINE passes #-}
-- | Checks if two lines are parallel.
parallel :: Epsilon a => Plucker a -> Plucker a -> Bool
parallel a b = nearZero $ u1 `cross` u2
where V2 u1 _ = toUV a
V2 u2 _ = toUV b
{-# INLINE parallel #-}
-- | Represent a Plücker coordinate as a pair of 3-tuples, typically
-- denoted U and V.
toUV :: Plucker a -> V2 (V3 a)
toUV (Plucker a b c d e f) = V2 (V3 a b c) (V3 d e f)
-- | Checks if two lines coincide in space. In other words, undirected equality.
coincides :: (Epsilon a, Fractional a) => Plucker a -> Plucker a -> Bool
coincides p1 p2 = Foldable.all nearZero $ (s *^ p2) - p1
where s = maybe 1 getFirst . getOption . fold $ saveDiv <$> p1 <*> p2
saveDiv x y | nearZero y = Option Nothing
| otherwise = Option . Just $ First (x / y)
{-# INLINABLE coincides #-}
-- | Checks if two lines coincide in space, and have the same
-- orientation.
coincides' :: (Epsilon a, Fractional a, Ord a) => Plucker a -> Plucker a -> Bool
coincides' p1 p2 = Foldable.all nearZero ((s *^ p2) - p1) && s > 0
where s = maybe 1 getFirst . getOption . fold $ saveDiv <$> p1 <*> p2
saveDiv x y | nearZero y = Option Nothing
| otherwise = Option . Just $ First (x / y)
{-# INLINABLE coincides' #-}
-- | The minimum squared distance of a line from the origin.
quadranceToOrigin :: Fractional a => Plucker a -> a
quadranceToOrigin p = (v `dot` v) / (u `dot` u)
where V2 u v = toUV p
{-# INLINE quadranceToOrigin #-}
-- | The point where a line is closest to the origin.
closestToOrigin :: Fractional a => Plucker a -> V3 a
closestToOrigin p = normalizePoint $ V4 x y z (u `dot` u)
where V2 u v = toUV p
V3 x y z = v `cross` u
{-# INLINE closestToOrigin #-}
-- | Not all 6-dimensional points correspond to a line in 3D. This
-- predicate tests that a Plücker coordinate lies on the Grassmann
-- manifold, and does indeed represent a 3D line.
isLine :: Epsilon a => Plucker a -> Bool
isLine p = nearZero $ u `dot` v
where V2 u v = toUV p
{-# INLINE isLine #-}
-- TODO: drag some more stuff out of my thesis
data instance U.Vector (Plucker a) = V_Plucker !Int (U.Vector a)
data instance U.MVector s (Plucker a) = MV_Plucker !Int (U.MVector s a)
instance U.Unbox a => U.Unbox (Plucker a)
instance U.Unbox a => M.MVector U.MVector (Plucker a) where
basicLength (MV_Plucker n _) = n
basicUnsafeSlice m n (MV_Plucker _ v) = MV_Plucker n (M.basicUnsafeSlice (6*m) (6*n) v)
basicOverlaps (MV_Plucker _ v) (MV_Plucker _ u) = M.basicOverlaps v u
basicUnsafeNew n = liftM (MV_Plucker n) (M.basicUnsafeNew (6*n))
basicUnsafeRead (MV_Plucker _ a) i =
do let o = 6*i
x <- M.basicUnsafeRead a o
y <- M.basicUnsafeRead a (o+1)
z <- M.basicUnsafeRead a (o+2)
w <- M.basicUnsafeRead a (o+3)
v <- M.basicUnsafeRead a (o+4)
u <- M.basicUnsafeRead a (o+5)
return (Plucker x y z w v u)
basicUnsafeWrite (MV_Plucker _ a) i (Plucker x y z w v u) =
do let o = 6*i
M.basicUnsafeWrite a o x
M.basicUnsafeWrite a (o+1) y
M.basicUnsafeWrite a (o+2) z
M.basicUnsafeWrite a (o+3) w
M.basicUnsafeWrite a (o+4) v
M.basicUnsafeWrite a (o+5) u
instance U.Unbox a => G.Vector U.Vector (Plucker a) where
basicUnsafeFreeze (MV_Plucker n v) = liftM ( V_Plucker n) (G.basicUnsafeFreeze v)
basicUnsafeThaw ( V_Plucker n v) = liftM (MV_Plucker n) (G.basicUnsafeThaw v)
basicLength ( V_Plucker n _) = n
basicUnsafeSlice m n (V_Plucker _ v) = V_Plucker n (G.basicUnsafeSlice (6*m) (6*n) v)
basicUnsafeIndexM (V_Plucker _ a) i =
do let o = 6*i
x <- G.basicUnsafeIndexM a o
y <- G.basicUnsafeIndexM a (o+1)
z <- G.basicUnsafeIndexM a (o+2)
w <- G.basicUnsafeIndexM a (o+3)
v <- G.basicUnsafeIndexM a (o+4)
u <- G.basicUnsafeIndexM a (o+5)
return (Plucker x y z w v u)
instance MonadZip Plucker where
mzipWith = liftA2
instance MonadFix Plucker where
mfix f = Plucker (let Plucker a _ _ _ _ _ = f a in a)
(let Plucker _ a _ _ _ _ = f a in a)
(let Plucker _ _ a _ _ _ = f a in a)
(let Plucker _ _ _ a _ _ = f a in a)
(let Plucker _ _ _ _ a _ = f a in a)
(let Plucker _ _ _ _ _ a = f a in a)
instance NFData a => NFData (Plucker a) where
rnf (Plucker a b c d e f) = rnf a `seq` rnf b `seq` rnf c
`seq` rnf d `seq` rnf e `seq` rnf f
instance Serial1 Plucker where
serializeWith = traverse_
deserializeWith k = Plucker <$> k <*> k <*> k <*> k <*> k <*> k
instance Serial a => Serial (Plucker a) where
serialize = serializeWith serialize
deserialize = deserializeWith deserialize
instance Binary a => Binary (Plucker a) where
put = serializeWith Binary.put
get = deserializeWith Binary.get
instance Serialize a => Serialize (Plucker a) where
put = serializeWith Cereal.put
get = deserializeWith Cereal.get
instance Eq1 Plucker where eq1 = (==)
instance Ord1 Plucker where compare1 = compare
instance Show1 Plucker where showsPrec1 = showsPrec
instance Read1 Plucker where readsPrec1 = readsPrec
| phaazon/linear | src/Linear/Plucker.hs | bsd-3-clause | 19,599 | 0 | 17 | 5,379 | 6,969 | 3,611 | 3,358 | 447 | 1 |
module Day3 where
import Test.Hspec
import Data.List (sort, transpose)
import Data.List.Split (chunksOf)
parse :: String -> [[Integer]]
parse = chunksOf 3 . map read . words
-- Problem DSL
isTriangle l = (a + b) > c
where
[a, b, c] = sort l
-- utils
score = length . filter isTriangle
-- FIRST problem
day = score
-- SECOND problem
tr = chunksOf 3 . mconcat . transpose
day' = score . tr
-- tests and data
test = hspec $ do
describe "firstProblem" $ do
it "works" $ do
day <$> content `shouldReturn` 917
describe "secondProblem" $ do
it "works" $ do
day' <$> content `shouldReturn` 1649
fileContent = readFile "content/day3"
content = parse <$> fileContent
| guibou/AdventOfCode2016 | src/Day3.hs | bsd-3-clause | 701 | 0 | 15 | 162 | 245 | 131 | 114 | 21 | 1 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, TemplateHaskell #-}
module Data.Shapely.TH (
deriveShapely
) where
import Data.Shapely.Classes
import Language.Haskell.TH
-- TODO:
-- - GADT's? forall?
-- - support for inlining, which will be the story for:
-- data Free f a = Pure a | Free (f (Free f a))
-- ...and newtype wrappers. When the type to be inlined is a param (as
-- above), our instance must have a shapely f constraint, else we don't
-- require a Shapely instance for the type to inline; simply reify the type
-- and do all that in the background.
-- | Generate a 'Shapely' instance for the type passed as argument @nm@. Used
-- like:
--
-- > $(deriveShapely ''Tree) -- two single-quotes reference a TH "Name" and the splice is optional
--
-- The algorithm used here to generate the 'Normal' instance is most easily
-- described syntactically:
--
-- - Constructors are replaced with @()@, which terminate (rather than start)
-- a product
--
-- - Product terms are composed with nested tuples, e.g. @Foo a b c ==> (a,(b,(c,())))@
--
-- - The @|@ in multiconstructor ('Sum') type declarations is replaced
-- with @Either@, with a nesting like the above
--
-- Note that a 'Product' type in the @Right@ place terminates a composed
-- 'Sum', while a @()@ in the @snd@ place terminates the composed terms
-- of a @Product@.
deriveShapely :: Name -> Q [Dec]
deriveShapely n = do
i <- reify n
case i of
(TyConI d) -> return $ return $
case d of
(DataD _ nm bndings cnstrctrs _) ->
drvShapely (mkType nm bndings) cnstrctrs
(NewtypeD _ nm bndings cnstrctr _) ->
drvShapely (mkType nm bndings) [cnstrctr]
_ -> error "This is either impossible, or a user error"
(PrimTyConI _ _ _) -> error "We can't generate instances for primitive type constructors. Note that 'newtype' wrapped primitive types are also not allowed, as we don't consider newtypes structural"
_ -> error "Please pass the name of a type constructor"
drvShapely :: Type -> [Con] -> Dec
drvShapely t cnstrctrs =
InstanceD [] (AppT (ConT ''Shapely) ( t )) [
TySynInstD ''Normal [ t ] (tNorm bcnstrctrs)
, FunD 'from (toClauses id bcnstrctrs)
-- i.e. constructorsOf = \_-> (the type's constructor(s))
, ValD (VarP 'constructorsOf) (NormalB $ LamE [WildP] ( constrsOf bcnstrctrs)) []
]
where
bcnstrctrs :: [BasicCon]
bcnstrctrs = map basicCon cnstrctrs
-- ----
tNorm :: [BasicCon] -> Type
tNorm [c] = tNormProd c
tNorm (c:cs) = AppT (AppT (ConT ''Either) (tNormProd c)) (tNorm cs) -- i.e. Either (tNormProd c) (tNorm cs)
tNorm _ = error "Type has no constructors, so has no 'shape'."
tNormProd :: BasicCon -> Type
tNormProd = tNormProd' . snd where
tNormProd' = foldr (AppT . AppT (TupleT 2)) (TupleT 0) -- i.e. foldr (,) () constructors
-- ----
toClauses sumWrapper [c] = [toClauseProd sumWrapper c]
toClauses sumWrapper (c:cs) =
toClauseProd (sumWrapper . AppE (ConE 'Left)) c
: toClauses (sumWrapper . AppE (ConE 'Right)) cs
toClauses _ _ = error "Type has no constructors, so has no 'shape'."
toClauseProd :: (Exp -> Exp) -> BasicCon -> Clause
toClauseProd sumWrapper (n, ts) =
Clause [ConP n boundVars] (NormalB $ sumWrapper prodBody) [] -- e.g. from { (Fook a b) = Left (a,(b,())) }
where boundNames = map (mkName . ("a"++) . show) $ map fst $ zip [(0 :: Int)..] ts
boundVars :: [Pat]
boundVars = map VarP boundNames -- e.g. from (Fook { a0 a1 }) = ...
prodBody :: Exp
prodBody = tupleList $ map VarE boundNames
-- ----
constrsOf :: [BasicCon] -> Exp
constrsOf [] = error "Type has no constructors, so has no 'shape'."
constrsOf [(n,_)] = ConE n -- e.g. Foo :: *, or Foo :: * -> *, etc.
constrsOf cs = tupleList $ map (ConE . fst) cs -- e.g. (Foo, (Bar, (Baz,())))
tupleList :: [Exp] -> Exp
tupleList = foldr tupleUp (ConE '())
where tupleUp e0 e1 = TupE [e0,e1]
type BasicCon = (Name, [Type])
basicCon :: Con -> BasicCon
basicCon (NormalC n sts) = (n, map snd sts)
basicCon (RecC n vsts) = (n, map (\(_,_,t)-> t) vsts)
basicCon (InfixC (_,t0) n (_,t1)) = (n, [t0,t1])
basicCon (ForallC _ _ _) = error "forall not handled yet" -- not sure how/if this would work
mkType :: Name -> [TyVarBndr] -> Type
mkType nm = foldl (\c-> AppT c . VarT . varName) (ConT nm) -- i.e. data Foo a b = .. -> .. :: Foo a b
varName :: TyVarBndr -> Name
varName (PlainTV n) = n
varName (KindedTV n _) = n
| jberryman/shapely-data | src/Data/Shapely/TH.hs | bsd-3-clause | 4,826 | 0 | 16 | 1,325 | 1,144 | 620 | 524 | 64 | 7 |
module Network.HaskellNet.IMAP
( connectIMAP, connectIMAPPort, connectStream
-- * IMAP commands
-- ** any state commands
, noop, capability, logout
-- ** not authenticated state commands
, login, authenticate
-- ** autenticated state commands
, select, examine, create, delete, rename
, subscribe, unsubscribe
, list, lsub, status, append
-- ** selected state commands
, check, close, expunge
, search, store, copy
-- * fetch commands
, fetch, fetchHeader, fetchSize, fetchHeaderFields, fetchHeaderFieldsNot
, fetchFlags, fetchR, fetchByString, fetchByStringR
-- * other types
, Flag(..), Attribute(..), MailboxStatus(..)
, SearchQuery(..), FlagsQuery(..)
)
where
import Network
import Network.HaskellNet.BSStream
import Network.HaskellNet.IMAP.Connection
import Network.HaskellNet.IMAP.Types
import Network.HaskellNet.IMAP.Parsers
import qualified Network.HaskellNet.Auth as A
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS
import Control.Applicative ((<$>))
import Control.Monad
import System.Time
import Data.Maybe
import Data.List hiding (delete)
import Data.Char
import Text.Packrat.Parse (Result)
-- suffixed by `s'
data SearchQuery = ALLs
| FLAG Flag
| UNFLAG Flag
| BCCs String
| BEFOREs CalendarTime
| BODYs String
| CCs String
| FROMs String
| HEADERs String String
| LARGERs Integer
| NEWs
| NOTs SearchQuery
| OLDs
| ONs CalendarTime
| ORs SearchQuery SearchQuery
| SENTBEFOREs CalendarTime
| SENTONs CalendarTime
| SENTSINCEs CalendarTime
| SINCEs CalendarTime
| SMALLERs Integer
| SUBJECTs String
| TEXTs String
| TOs String
| UIDs [UID]
instance Show SearchQuery where
showsPrec d q = showParen (d>app_prec) $ showString $ showQuery q
where app_prec = 10
showQuery ALLs = "ALL"
showQuery (FLAG f) = showFlag f
showQuery (UNFLAG f) = "UN" ++ showFlag f
showQuery (BCCs addr) = "BCC " ++ addr
showQuery (BEFOREs t) = "BEFORE " ++ dateToStringIMAP t
showQuery (BODYs s) = "BODY " ++ s
showQuery (CCs addr) = "CC " ++ addr
showQuery (FROMs addr) = "FROM " ++ addr
showQuery (HEADERs f v) = "HEADER " ++ f ++ " " ++ v
showQuery (LARGERs siz) = "LARGER {" ++ show siz ++ "}"
showQuery NEWs = "NEW"
showQuery (NOTs qry) = "NOT " ++ show qry
showQuery OLDs = "OLD"
showQuery (ONs t) = "ON " ++ dateToStringIMAP t
showQuery (ORs q1 q2) = "OR " ++ show q1 ++ " " ++ show q2
showQuery (SENTBEFOREs t) = "SENTBEFORE " ++ dateToStringIMAP t
showQuery (SENTONs t) = "SENTON " ++ dateToStringIMAP t
showQuery (SENTSINCEs t) = "SENTSINCE " ++ dateToStringIMAP t
showQuery (SINCEs t) = "SINCE " ++ dateToStringIMAP t
showQuery (SMALLERs siz) = "SMALLER {" ++ show siz ++ "}"
showQuery (SUBJECTs s) = "SUBJECT " ++ s
showQuery (TEXTs s) = "TEXT " ++ s
showQuery (TOs addr) = "TO " ++ addr
showQuery (UIDs uids) = concat $ intersperse "," $
map show uids
showFlag Seen = "SEEN"
showFlag Answered = "ANSWERED"
showFlag Flagged = "FLAGGED"
showFlag Deleted = "DELETED"
showFlag Draft = "DRAFT"
showFlag Recent = "RECENT"
showFlag (Keyword s) = "KEYWORD " ++ s
data FlagsQuery = ReplaceFlags [Flag]
| PlusFlags [Flag]
| MinusFlags [Flag]
----------------------------------------------------------------------
-- establish connection
connectIMAPPort :: String -> PortNumber -> IO IMAPConnection
connectIMAPPort hostname port =
handleToStream <$> connectTo hostname (PortNumber port)
>>= connectStream
connectIMAP :: String -> IO IMAPConnection
connectIMAP hostname = connectIMAPPort hostname 143
connectStream :: BSStream -> IO IMAPConnection
connectStream s =
do msg <- bsGetLine s
unless (and $ BS.zipWith (==) msg (BS.pack "* OK")) $
fail "cannot connect to the server"
newConnection s
----------------------------------------------------------------------
-- normal send commands
sendCommand' :: IMAPConnection -> String -> IO (ByteString, Int)
sendCommand' c cmdstr = do
(_, num) <- withNextCommandNum c $ \num -> bsPutCrLf (stream c) $
BS.pack $ show6 num ++ " " ++ cmdstr
resp <- getResponse (stream c)
return (resp, num)
show6 :: (Ord a, Num a, Show a) => a -> String
show6 n | n > 100000 = show n
| n > 10000 = '0' : show n
| n > 1000 = "00" ++ show n
| n > 100 = "000" ++ show n
| n > 10 = "0000" ++ show n
| otherwise = "00000" ++ show n
sendCommand :: IMAPConnection -> String
-> (RespDerivs -> Result RespDerivs (ServerResponse, MboxUpdate, v))
-> IO v
sendCommand imapc cmdstr pFunc =
do (buf, num) <- sendCommand' imapc cmdstr
BS.putStrLn buf
let (resp, mboxUp, value) = eval pFunc (show6 num) buf
case resp of
OK _ _ -> do mboxUpdate imapc mboxUp
return value
NO _ msg -> fail ("NO: " ++ msg)
BAD _ msg -> fail ("BAD: " ++ msg)
PREAUTH _ msg -> fail ("preauth: " ++ msg)
getResponse :: BSStream -> IO ByteString
getResponse s = unlinesCRLF <$> getLs
where unlinesCRLF = BS.concat . concatMap (:[crlfStr])
getLs =
do l <- strip <$> bsGetLine s
case () of
_ | isLiteral l -> do l' <- getLiteral l (getLitLen l)
ls <- getLs
return (l' : ls)
| isTagged l -> (l:) <$> getLs
| otherwise -> return [l]
getLiteral l len =
do lit <- bsGet s len
l2 <- strip <$> bsGetLine s
let l' = BS.concat [l, crlfStr, lit, l2]
if isLiteral l2
then getLiteral l' (getLitLen l2)
else return l'
crlfStr = BS.pack "\r\n"
isLiteral l = BS.last l == '}' &&
BS.last (fst (BS.spanEnd isDigit (BS.init l))) == '{'
getLitLen = read . BS.unpack . snd . BS.spanEnd isDigit . BS.init
isTagged l = BS.head l == '*' && BS.head (BS.tail l) == ' '
mboxUpdate :: IMAPConnection -> MboxUpdate -> IO ()
mboxUpdate conn (MboxUpdate exists' recent') = do
when (isJust exists') $
modifyMailboxInfo conn $ \mbox -> mbox { _exists = fromJust exists' }
when (isJust recent') $
modifyMailboxInfo conn $ \mbox -> mbox { _recent = fromJust recent' }
----------------------------------------------------------------------
-- IMAP commands
--
noop :: IMAPConnection -> IO ()
noop conn = sendCommand conn "NOOP" pNone
capability :: IMAPConnection -> IO [String]
capability conn = sendCommand conn "CAPABILITY" pCapability
logout :: IMAPConnection -> IO ()
logout c = do bsPutCrLf (stream c) $ BS.pack "a0001 LOGOUT"
bsClose (stream c)
login :: IMAPConnection -> A.UserName -> A.Password -> IO ()
login conn username password = sendCommand conn ("LOGIN " ++ username ++ " " ++ password)
pNone
authenticate :: IMAPConnection -> A.AuthType
-> A.UserName -> A.Password -> IO ()
authenticate conn A.LOGIN username password =
do (_, num) <- sendCommand' conn "AUTHENTICATE LOGIN"
bsPutCrLf (stream conn) $ BS.pack userB64
bsGetLine (stream conn)
bsPutCrLf (stream conn) $ BS.pack passB64
buf <- getResponse $ stream conn
let (resp, mboxUp, value) = eval pNone (show6 num) buf
case resp of
OK _ _ -> do mboxUpdate conn $ mboxUp
return value
NO _ msg -> fail ("NO: " ++ msg)
BAD _ msg -> fail ("BAD: " ++ msg)
PREAUTH _ msg -> fail ("preauth: " ++ msg)
where (userB64, passB64) = A.login username password
authenticate conn at username password =
do (c, num) <- sendCommand' conn $ "AUTHENTICATE " ++ show at
let challenge =
if BS.take 2 c == BS.pack "+ "
then A.b64Decode $ BS.unpack $ head $
dropWhile (isSpace . BS.last) $ BS.inits $ BS.drop 2 c
else ""
bsPutCrLf (stream conn) $ BS.pack $
A.auth at challenge username password
buf <- getResponse $ stream conn
let (resp, mboxUp, value) = eval pNone (show6 num) buf
case resp of
OK _ _ -> do mboxUpdate conn $ mboxUp
return value
NO _ msg -> fail ("NO: " ++ msg)
BAD _ msg -> fail ("BAD: " ++ msg)
PREAUTH _ msg -> fail ("preauth: " ++ msg)
_select :: String -> IMAPConnection -> String -> IO ()
_select cmd conn mboxName =
do mbox' <- sendCommand conn (cmd ++ mboxName) pSelect
setMailboxInfo conn $ mbox' { _mailbox = mboxName }
select :: IMAPConnection -> MailboxName -> IO ()
select = _select "SELECT "
examine :: IMAPConnection -> MailboxName -> IO ()
examine = _select "EXAMINE "
create :: IMAPConnection -> MailboxName -> IO ()
create conn mboxname = sendCommand conn ("CREATE " ++ mboxname) pNone
delete :: IMAPConnection -> MailboxName -> IO ()
delete conn mboxname = sendCommand conn ("DELETE " ++ mboxname) pNone
rename :: IMAPConnection -> MailboxName -> MailboxName -> IO ()
rename conn mboxorg mboxnew =
sendCommand conn ("RENAME " ++ mboxorg ++ " " ++ mboxnew) pNone
subscribe :: IMAPConnection -> MailboxName -> IO ()
subscribe conn mboxname = sendCommand conn ("SUBSCRIBE " ++ mboxname) pNone
unsubscribe :: IMAPConnection -> MailboxName -> IO ()
unsubscribe conn mboxname = sendCommand conn ("UNSUBSCRIBE " ++ mboxname) pNone
list :: IMAPConnection -> IO [([Attribute], MailboxName)]
list conn = do
r <- listFull conn "\"\"" "*"
mapM_ (putStrLn.show) r
return $ (map (\(a, _, m) -> (a, m))) r
lsub :: IMAPConnection -> IO [([Attribute], MailboxName)]
lsub conn = (map (\(a, _, m) -> (a, m))) <$> lsubFull conn "\"\"" "*"
listFull :: IMAPConnection -> String -> String
-> IO [([Attribute], String, MailboxName)]
listFull conn ref pat = sendCommand conn (unwords ["LIST", ref, pat]) pList
lsubFull :: IMAPConnection -> String -> String
-> IO [([Attribute], String, MailboxName)]
lsubFull conn ref pat = sendCommand conn (unwords ["LSUB", ref, pat]) pLsub
status :: IMAPConnection -> MailboxName -> [MailboxStatus]
-> IO [(MailboxStatus, Integer)]
status conn mbox stats =
let cmd = "STATUS " ++ mbox ++ " (" ++ (unwords $ map show stats) ++ ")"
in sendCommand conn cmd pStatus
append :: IMAPConnection -> MailboxName -> ByteString -> IO ()
append conn mbox mailData = appendFull conn mbox mailData [] Nothing
appendFull :: IMAPConnection -> MailboxName -> ByteString
-> [Flag] -> Maybe CalendarTime -> IO ()
appendFull conn mbox mailData flags' time =
do (buf, num) <- sendCommand' conn
(unwords ["APPEND", mbox
, fstr, tstr, "{" ++ show len ++ "}"])
unless (BS.null buf || (BS.head buf /= '+')) $
fail "illegal server response"
mapM_ (bsPutCrLf $ stream conn) mailLines
buf2 <- getResponse $ stream conn
let (resp, mboxUp, ()) = eval pNone (show6 num) buf2
case resp of
OK _ _ -> mboxUpdate conn mboxUp
NO _ msg -> fail ("NO: "++msg)
BAD _ msg -> fail ("BAD: "++msg)
PREAUTH _ msg -> fail ("PREAUTH: "++msg)
where mailLines = BS.lines mailData
len = sum $ map ((2+) . BS.length) mailLines
tstr = maybe "" show time
fstr = unwords $ map show flags'
check :: IMAPConnection -> IO ()
check conn = sendCommand conn "CHECK" pNone
close :: IMAPConnection -> IO ()
close conn =
do sendCommand conn "CLOSE" pNone
setMailboxInfo conn emptyMboxInfo
expunge :: IMAPConnection -> IO [Integer]
expunge conn = sendCommand conn "EXPUNGE" pExpunge
search :: IMAPConnection -> [SearchQuery] -> IO [UID]
search conn queries = searchCharset conn "" queries
searchCharset :: IMAPConnection -> Charset -> [SearchQuery]
-> IO [UID]
searchCharset conn charset queries =
sendCommand conn ("UID SEARCH "
++ (if not . null $ charset
then charset ++ " "
else "")
++ unwords (map show queries)) pSearch
fetch :: IMAPConnection -> UID -> IO ByteString
fetch conn uid =
do lst <- fetchByString conn uid "BODY[]"
return $ maybe BS.empty BS.pack $ lookup "BODY[]" lst
fetchHeader :: IMAPConnection -> UID -> IO ByteString
fetchHeader conn uid =
do lst <- fetchByString conn uid "BODY[HEADER]"
return $ maybe BS.empty BS.pack $ lookup "BODY[HEADER]" lst
fetchSize :: IMAPConnection -> UID -> IO Int
fetchSize conn uid =
do lst <- fetchByString conn uid "RFC822.SIZE"
return $ maybe 0 read $ lookup "RFC822.SIZE" lst
fetchHeaderFields :: IMAPConnection
-> UID -> [String] -> IO ByteString
fetchHeaderFields conn uid hs =
do lst <- fetchByString conn uid ("BODY[HEADER.FIELDS "++unwords hs++"]")
return $ maybe BS.empty BS.pack $
lookup ("BODY[HEADER.FIELDS "++unwords hs++"]") lst
fetchHeaderFieldsNot :: IMAPConnection
-> UID -> [String] -> IO ByteString
fetchHeaderFieldsNot conn uid hs =
do let fetchCmd = "BODY[HEADER.FIELDS.NOT "++unwords hs++"]"
lst <- fetchByString conn uid fetchCmd
return $ maybe BS.empty BS.pack $ lookup fetchCmd lst
fetchFlags :: IMAPConnection -> UID -> IO [Flag]
fetchFlags conn uid =
do lst <- fetchByString conn uid "FLAGS"
return $ getFlags $ lookup "FLAGS" lst
where getFlags Nothing = []
getFlags (Just s) = eval' dvFlags "" s
fetchR :: IMAPConnection -> (UID, UID)
-> IO [(UID, ByteString)]
fetchR conn r =
do lst <- fetchByStringR conn r "BODY[]"
return $ map (\(uid, vs) -> (uid, maybe BS.empty BS.pack $
lookup "BODY[]" vs)) lst
fetchByString :: IMAPConnection -> UID -> String
-> IO [(String, String)]
fetchByString conn uid command =
do lst <- fetchCommand conn ("UID FETCH "++show uid++" "++command) id
return $ snd $ head lst
fetchByStringR :: IMAPConnection -> (UID, UID) -> String
-> IO [(UID, [(String, String)])]
fetchByStringR conn (s, e) command =
fetchCommand conn ("UID FETCH "++show s++":"++show e++" "++command) proc
where proc (n, ps) =
(maybe (toEnum (fromIntegral n)) read (lookup "UID" ps), ps)
fetchCommand :: IMAPConnection -> String
-> ((Integer, [(String, String)]) -> b) -> IO [b]
fetchCommand conn command proc =
(map proc) <$> sendCommand conn command pFetch
storeFull :: IMAPConnection -> String -> FlagsQuery -> Bool
-> IO [(UID, [Flag])]
storeFull conn uidstr query isSilent =
fetchCommand conn ("UID STORE " ++ uidstr ++ flgs query) procStore
where fstrs fs = "(" ++ (concat $ intersperse " " $ map show fs) ++ ")"
toFStr s fstrs' =
s ++ (if isSilent then ".SILENT" else "") ++ " " ++ fstrs'
flgs (ReplaceFlags fs) = toFStr "FLAGS" $ fstrs fs
flgs (PlusFlags fs) = toFStr "+FLAGS" $ fstrs fs
flgs (MinusFlags fs) = toFStr "-FLAGS" $ fstrs fs
procStore (n, ps) = (maybe (toEnum (fromIntegral n)) read
(lookup "UID" ps)
,maybe [] (eval' dvFlags "") (lookup "FLAG" ps))
store :: IMAPConnection -> UID -> FlagsQuery -> IO ()
store conn i q = storeFull conn (show i) q True >> return ()
copyFull :: IMAPConnection -> String -> String -> IO ()
copyFull conn uidStr mbox =
sendCommand conn ("UID COPY " ++ uidStr ++ " " ++ mbox) pNone
copy :: IMAPConnection -> UID -> MailboxName -> IO ()
copy conn uid mbox = copyFull conn (show uid) mbox
----------------------------------------------------------------------
-- auxialiary functions
dateToStringIMAP :: CalendarTime -> String
dateToStringIMAP date = concat $ intersperse "-" [show2 $ ctDay date
, showMonth $ ctMonth date
, show $ ctYear date]
where show2 n | n < 10 = '0' : show n
| otherwise = show n
showMonth January = "Jan"
showMonth February = "Feb"
showMonth March = "Mar"
showMonth April = "Apr"
showMonth May = "May"
showMonth June = "Jun"
showMonth July = "Jul"
showMonth August = "Aug"
showMonth September = "Sep"
showMonth October = "Oct"
showMonth November = "Nov"
showMonth December = "Dec"
strip :: ByteString -> ByteString
strip = fst . BS.spanEnd isSpace . BS.dropWhile isSpace
crlf :: BS.ByteString
crlf = BS.pack "\r\n"
bsPutCrLf :: BSStream -> ByteString -> IO ()
bsPutCrLf h s = bsPut h s >> bsPut h crlf >> bsFlush h
| danchoi/imapget | src/Network/HaskellNet/IMAP.hs | bsd-3-clause | 18,001 | 0 | 18 | 5,765 | 5,887 | 2,966 | 2,921 | 372 | 12 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Language.Fixpoint.Types.Errors (
-- * Concrete Location Type
SrcSpan (..)
, dummySpan
, sourcePosElts
-- * Result
, FixResult (..)
, colorResult
, resultDoc
-- * Abstract Error Type
, Error
-- * Constructor
, err
-- * Accessors
, errLoc
, errMsg
-- * Adding Insult to Injury
, catMessage
, catError
, catErrors
-- * Fatal Exit
, die
, exit
-- * Some popular errors
, errFreeVarInQual
) where
import Control.Exception
import qualified Control.Monad.Error as E
import Data.Serialize (Serialize (..))
import Data.Generics (Data)
import Data.Typeable
import Control.DeepSeq
-- import Data.Hashable
import qualified Data.Binary as B
import GHC.Generics (Generic)
import Language.Fixpoint.Types.PrettyPrint
import Language.Fixpoint.Types.Spans
import Language.Fixpoint.Misc
import Text.PrettyPrint.HughesPJ
import Text.Printf
-- import Debug.Trace
instance Serialize Error
instance Serialize (FixResult Error)
instance (B.Binary a) => B.Binary (FixResult a)
-----------------------------------------------------------------------
-- | A BareBones Error Type -------------------------------------------
-----------------------------------------------------------------------
data Error = Error { errLoc :: SrcSpan
, errMsg :: String }
deriving (Eq, Ord, Show, Data, Typeable, Generic)
instance PPrint Error where
pprint (Error l msg) = pprint l <> text (": Error: " ++ msg)
instance Fixpoint Error where
toFix = pprint
instance Exception Error
instance Exception (FixResult Error)
instance E.Error Error where
strMsg = Error dummySpan
---------------------------------------------------------------------
catMessage :: Error -> String -> Error
---------------------------------------------------------------------
catMessage e msg = e {errMsg = msg ++ errMsg e}
---------------------------------------------------------------------
catError :: Error -> Error -> Error
---------------------------------------------------------------------
catError e1 e2 = catMessage e1 $ show e2
---------------------------------------------------------------------
catErrors :: ListNE Error -> Error
---------------------------------------------------------------------
catErrors = foldr1 catError
---------------------------------------------------------------------
err :: SrcSpan -> String -> Error
---------------------------------------------------------------------
err = Error
---------------------------------------------------------------------
die :: Error -> a
---------------------------------------------------------------------
die = throw
---------------------------------------------------------------------
exit :: a -> IO a -> IO a
---------------------------------------------------------------------
exit def act = catch act $ \(e :: Error) -> do
putStrLn $ "Unexpected Error: " ++ showpp e
return def
---------------------------------------------------------------------
-- | Result ---------------------------------------------------------
---------------------------------------------------------------------
data FixResult a = Crash [a] String
| Safe
| Unsafe ![a]
deriving (Data, Typeable, Show, Generic)
instance (NFData a) => NFData (FixResult a)
instance Eq a => Eq (FixResult a) where
Crash xs _ == Crash ys _ = xs == ys
Unsafe xs == Unsafe ys = xs == ys
Safe == Safe = True
_ == _ = False
instance Monoid (FixResult a) where
mempty = Safe
mappend Safe x = x
mappend x Safe = x
mappend _ c@(Crash _ _) = c
mappend c@(Crash _ _) _ = c
mappend (Unsafe xs) (Unsafe ys) = Unsafe (xs ++ ys)
instance Functor FixResult where
fmap f (Crash xs msg) = Crash (f <$> xs) msg
fmap f (Unsafe xs) = Unsafe (f <$> xs)
fmap _ Safe = Safe
resultDoc :: (Fixpoint a) => FixResult a -> Doc
resultDoc Safe = text "Safe"
resultDoc (Crash xs msg) = vcat $ text ("Crash!: " ++ msg) : (((text "CRASH:" <+>) . toFix) <$> xs)
resultDoc (Unsafe xs) = vcat $ text "Unsafe:" : (((text "WARNING:" <+>) . toFix) <$> xs)
colorResult :: FixResult a -> Moods
colorResult (Safe) = Happy
colorResult (Unsafe _) = Angry
colorResult (_) = Sad
---------------------------------------------------------------------
-- | Catalogue of Errors --------------------------------------------
---------------------------------------------------------------------
errFreeVarInQual :: (Fixpoint a, Loc a) => a -> Error
errFreeVarInQual q = err sp $ printf "Qualifier with free vars : %s \n" (showFix q)
where
sp = srcSpan q
| gridaphobe/liquid-fixpoint | src/Language/Fixpoint/Types/Errors.hs | bsd-3-clause | 5,231 | 0 | 11 | 1,232 | 1,161 | 631 | 530 | 97 | 1 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Main
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Main (main) where
import Test.Tasty
import Test.AWS.CodeCommit
import Test.AWS.CodeCommit.Internal
main :: IO ()
main = defaultMain $ testGroup "CodeCommit"
[ testGroup "tests" tests
, testGroup "fixtures" fixtures
]
| fmapfmapfmap/amazonka | amazonka-codecommit/test/Main.hs | mpl-2.0 | 543 | 0 | 8 | 103 | 76 | 47 | 29 | 9 | 1 |
module Util where
takeUntil :: (a -> Bool) -> [a] -> [a]
takeUntil _ [] = []
takeUntil p (x:xs) | p x = [x]
| otherwise = x : takeUntil p xs
| guillaume-nargeot/hpc-coveralls-testing2 | src/Util.hs | bsd-3-clause | 161 | 0 | 8 | 53 | 91 | 47 | 44 | 5 | 1 |
a :: Int
a = 0
{-@ assume b :: { b : Int | a < b } @-}
b :: Int
b = 1
{-@
f :: a : Int -> { b : Int | a < b } -> ()
@-}
f :: Int -> Int -> ()
f _ _ = ()
g :: ()
g = f a b | ssaavedra/liquidhaskell | tests/crash/Assume1.hs | bsd-3-clause | 173 | 0 | 9 | 67 | 90 | 41 | 49 | 8 | 1 |
module Util where
import System.IO.Unsafe
-- Lazier version of 'Control.Monad.sequence'
--
sequence' :: [IO a] -> IO [a]
sequence' = foldr k (return [])
where k m ms = do { x <- m; xs <- unsafeInterleaveIO ms; return (x:xs) }
mapM' :: (a -> IO b) -> [a] -> IO [b]
mapM' f xs = sequence' $ map f xs
forM' :: [a] -> (a -> IO b) -> IO [b]
forM' = flip mapM'
| wilbowma/accelerate | accelerate-examples/src/Util.hs | bsd-3-clause | 363 | 0 | 11 | 84 | 188 | 99 | 89 | 9 | 1 |
{-# LANGUAGE GADTs #-}
{-# OPTIONS_GHC -fno-warn-warnings-deprecations -fno-warn-incomplete-patterns #-}
module CmmContFlowOpt
( runCmmContFlowOpts
, removeUnreachableBlocks, replaceBranches
)
where
import BlockId
import Cmm
import CmmUtils
import Digraph
import Maybes
import Outputable
import Compiler.Hoopl
import Control.Monad
import Prelude hiding (succ, unzip, zip)
-----------------------------------------------------------------------------
--
-- Control-flow optimisations
--
-----------------------------------------------------------------------------
runCmmContFlowOpts :: CmmGroup -> CmmGroup
runCmmContFlowOpts = map (optProc cmmCfgOpts)
cmmCfgOpts :: CmmGraph -> CmmGraph
cmmCfgOpts = removeUnreachableBlocks . blockConcat . branchChainElim
-- Here branchChainElim can ultimately be replaced
-- with a more exciting combination of optimisations
optProc :: (g -> g) -> GenCmmDecl d h g -> GenCmmDecl d h g
optProc opt (CmmProc info lbl g) = CmmProc info lbl (opt g)
optProc _ top = top
-----------------------------------------------------------------------------
--
-- Branch Chain Elimination
--
-----------------------------------------------------------------------------
-- | Remove any basic block of the form L: goto L', and replace L with
-- L' everywhere else, unless L is the successor of a call instruction
-- and L' is the entry block. You don't want to set the successor of a
-- function call to the entry block because there is no good way to
-- store both the infotables for the call and from the callee, while
-- putting the stack pointer in a consistent place.
--
-- JD isn't quite sure when it's safe to share continuations for different
-- function calls -- have to think about where the SP will be,
-- so we'll table that problem for now by leaving all call successors alone.
branchChainElim :: CmmGraph -> CmmGraph
branchChainElim g
| null lone_branch_blocks = g -- No blocks to remove
| otherwise = {- pprTrace "branchChainElim" (ppr forest) $ -}
replaceLabels (mapFromList edges) g
where
blocks = toBlockList g
lone_branch_blocks :: [(BlockId, BlockId)]
-- each (L,K) is a block of the form
-- L : goto K
lone_branch_blocks = mapCatMaybes isLoneBranch blocks
call_succs = foldl add emptyBlockSet blocks
where add :: BlockSet -> CmmBlock -> BlockSet
add succs b =
case lastNode b of
(CmmCall _ (Just k) _ _ _) -> setInsert k succs
(CmmForeignCall {succ=k}) -> setInsert k succs
_ -> succs
isLoneBranch :: CmmBlock -> Maybe (BlockId, BlockId)
isLoneBranch block
| (JustC (CmmEntry id), [], JustC (CmmBranch target)) <- blockToNodeList block
, not (setMember id call_succs)
= Just (id,target)
| otherwise
= Nothing
-- We build a graph from lone_branch_blocks (every node has only
-- one out edge). Then we
-- - topologically sort the graph: if from A we can reach B,
-- then A occurs before B in the result list.
-- - depth-first search starting from the nodes in this list.
-- This gives us a [[node]], in which each list is a dependency
-- chain.
-- - for each list [a1,a2,...an] replace branches to ai with an.
--
-- This approach nicely deals with cycles by ignoring them.
-- Branches in a cycle will be redirected to somewhere in the
-- cycle, but we don't really care where. A cycle should be dead code,
-- and so will be eliminated by removeUnreachableBlocks.
--
fromNode (b,_) = b
toNode a = (a,a)
all_block_ids :: LabelSet
all_block_ids = setFromList (map fst lone_branch_blocks)
`setUnion`
setFromList (map snd lone_branch_blocks)
forest = dfsTopSortG $ graphFromVerticesAndAdjacency nodes lone_branch_blocks
where nodes = map toNode $ setElems $ all_block_ids
edges = [ (fromNode y, fromNode x)
| (x:xs) <- map reverse forest, y <- xs ]
----------------------------------------------------------------
replaceLabels :: BlockEnv BlockId -> CmmGraph -> CmmGraph
replaceLabels env =
replace_eid . mapGraphNodes1 txnode
where
replace_eid g = g {g_entry = lookup (g_entry g)}
lookup id = mapLookup id env `orElse` id
txnode :: CmmNode e x -> CmmNode e x
txnode (CmmBranch bid) = CmmBranch (lookup bid)
txnode (CmmCondBranch p t f) = CmmCondBranch (exp p) (lookup t) (lookup f)
txnode (CmmSwitch e arms) = CmmSwitch (exp e) (map (liftM lookup) arms)
txnode (CmmCall t k a res r) = CmmCall (exp t) (liftM lookup k) a res r
txnode fc@CmmForeignCall{} = fc{ args = map exp (args fc)
, succ = lookup (succ fc) }
txnode other = mapExpDeep exp other
exp :: CmmExpr -> CmmExpr
exp (CmmLit (CmmBlock bid)) = CmmLit (CmmBlock (lookup bid))
exp (CmmStackSlot (CallArea (Young id)) i) = CmmStackSlot (CallArea (Young (lookup id))) i
exp e = e
replaceBranches :: BlockEnv BlockId -> CmmGraph -> CmmGraph
replaceBranches env g = mapGraphNodes (id, id, last) g
where
last :: CmmNode O C -> CmmNode O C
last (CmmBranch id) = CmmBranch (lookup id)
last (CmmCondBranch e ti fi) = CmmCondBranch e (lookup ti) (lookup fi)
last (CmmSwitch e tbl) = CmmSwitch e (map (fmap lookup) tbl)
last l@(CmmCall {}) = l
last l@(CmmForeignCall {}) = l
lookup id = fmap lookup (mapLookup id env) `orElse` id
-- XXX: this is a recursive lookup, it follows chains until the lookup
-- returns Nothing, at which point we return the last BlockId
----------------------------------------------------------------
-- Build a map from a block to its set of predecessors. Very useful.
predMap :: [CmmBlock] -> BlockEnv BlockSet
predMap blocks = foldr add_preds mapEmpty blocks -- find the back edges
where add_preds block env = foldl (add (entryLabel block)) env (successors block)
add bid env b' =
mapInsert b' (setInsert bid (mapLookup b' env `orElse` setEmpty)) env
-----------------------------------------------------------------------------
--
-- Block concatenation
--
-----------------------------------------------------------------------------
-- If a block B branches to a label L, L is not the entry block,
-- and L has no other predecessors,
-- then we can splice the block starting with L onto the end of B.
-- Order matters, so we work bottom up (reverse postorder DFS).
-- This optimization can be inhibited by unreachable blocks, but
-- the reverse postorder DFS returns only reachable blocks.
--
-- To ensure correctness, we have to make sure that the BlockId of the block
-- we are about to eliminate is not named in another instruction.
--
-- Note: This optimization does _not_ subsume branch chain elimination.
blockConcat :: CmmGraph -> CmmGraph
blockConcat g@(CmmGraph {g_entry=eid}) =
replaceLabels concatMap $ ofBlockMap (g_entry g) blocks'
where
blocks = postorderDfs g
(blocks', concatMap) =
foldr maybe_concat (toBlockMap g, mapEmpty) $ blocks
maybe_concat :: CmmBlock -> (LabelMap CmmBlock, LabelMap Label) -> (LabelMap CmmBlock, LabelMap Label)
maybe_concat b unchanged@(blocks', concatMap) =
let bid = entryLabel b
in case blockToNodeList b of
(JustC h, m, JustC (CmmBranch b')) ->
if canConcatWith b' then
(mapInsert bid (splice blocks' h m b') blocks',
mapInsert b' bid concatMap)
else unchanged
_ -> unchanged
num_preds bid = liftM setSize (mapLookup bid backEdges) `orElse` 0
canConcatWith b' = b' /= eid && num_preds b' == 1
backEdges = predMap blocks
splice :: forall map n e x.
IsMap map =>
map (Block n e x) -> n C O -> [n O O] -> KeyOf map -> Block n C x
splice blocks' h m bid' =
case mapLookup bid' blocks' of
Nothing -> panic "unknown successor block"
Just block | (_, m', l') <- blockToNodeList block
-> blockOfNodeList (JustC h, (m ++ m'), l')
-----------------------------------------------------------------------------
--
-- Removing unreachable blocks
--
-----------------------------------------------------------------------------
removeUnreachableBlocks :: CmmGraph -> CmmGraph
removeUnreachableBlocks g
| length blocks < mapSize (toBlockMap g) = ofBlockList (g_entry g) blocks
| otherwise = g
where blocks = postorderDfs g
| mcmaniac/ghc | compiler/cmm/CmmContFlowOpt.hs | bsd-3-clause | 8,803 | 0 | 16 | 2,223 | 1,949 | 1,023 | 926 | -1 | -1 |
{-# LANGUAGE CPP #-}
-- | This is where we define a mapping from Uniques to their associated
-- known-key Names for things associated with tuples and sums. We use this
-- mapping while deserializing known-key Names in interface file symbol tables,
-- which are encoded as their Unique. See Note [Symbol table representation of
-- names] for details.
--
module KnownUniques
( -- * Looking up known-key names
knownUniqueName
-- * Getting the 'Unique's of 'Name's
-- ** Anonymous sums
, mkSumTyConUnique
, mkSumDataConUnique
-- ** Tuples
-- *** Vanilla
, mkTupleTyConUnique
, mkTupleDataConUnique
-- *** Constraint
, mkCTupleTyConUnique
, mkCTupleDataConUnique
) where
#include "HsVersions.h"
import TysWiredIn
import TyCon
import DataCon
import Id
import BasicTypes
import Outputable
import Unique
import Name
import Util
import Data.Bits
import Data.Maybe
-- | Get the 'Name' associated with a known-key 'Unique'.
knownUniqueName :: Unique -> Maybe Name
knownUniqueName u =
case tag of
'z' -> Just $ getUnboxedSumName n
'4' -> Just $ getTupleTyConName Boxed n
'5' -> Just $ getTupleTyConName Unboxed n
'7' -> Just $ getTupleDataConName Boxed n
'8' -> Just $ getTupleDataConName Unboxed n
'k' -> Just $ getCTupleTyConName n
'm' -> Just $ getCTupleDataConUnique n
_ -> Nothing
where
(tag, n) = unpkUnique u
--------------------------------------------------
-- Anonymous sums
--
-- Sum arities start from 2. The encoding is a bit funny: we break up the
-- integral part into bitfields for the arity and alternative index (which is
-- taken to be 0xff in the case of the TyCon)
--
-- TyCon for sum of arity k:
-- 00000000 kkkkkkkk 11111111
-- DataCon for sum of arity k and alternative n (zero-based):
-- 00000000 kkkkkkkk nnnnnnnn
mkSumTyConUnique :: Arity -> Unique
mkSumTyConUnique arity =
ASSERT(arity < 0xff)
mkUnique 'z' (arity `shiftL` 8 .|. 0xff)
mkSumDataConUnique :: ConTagZ -> Arity -> Unique
mkSumDataConUnique alt arity
| alt >= arity
= panic ("mkSumDataConUnique: " ++ show alt ++ " >= " ++ show arity)
| otherwise
= mkUnique 'z' (arity `shiftL` 8 + alt) {- skip the tycon -}
getUnboxedSumName :: Int -> Name
getUnboxedSumName n =
case n .&. 0xff of
0xff -> tyConName $ sumTyCon arity
alt -> dataConName $ sumDataCon (alt + 1) arity
where arity = n `shiftR` 8
-- Note [Uniques for tuple type and data constructors]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- Wired-in type constructor keys occupy *two* slots:
-- * u: the TyCon itself
-- * u+1: the TyConRepName of the TyCon
--
-- Wired-in tuple data constructor keys occupy *three* slots:
-- * u: the DataCon itself
-- * u+1: its worker Id
-- * u+2: the TyConRepName of the promoted TyCon
--------------------------------------------------
-- Constraint tuples
mkCTupleTyConUnique :: Arity -> Unique
mkCTupleTyConUnique a = mkUnique 'k' (2*a)
mkCTupleDataConUnique :: Arity -> Unique
mkCTupleDataConUnique a = mkUnique 'm' (3*a)
getCTupleTyConName :: Int -> Name
getCTupleTyConName n =
case n `divMod` 2 of
(arity, 0) -> cTupleTyConName arity
(arity, 1) -> mkPrelTyConRepName $ cTupleTyConName arity
_ -> panic "getCTupleTyConName: impossible"
getCTupleDataConUnique :: Int -> Name
getCTupleDataConUnique n =
case n `divMod` 3 of
(arity, 0) -> cTupleDataConName arity
(_arity, 1) -> panic "getCTupleDataConName: no worker"
(arity, 2) -> mkPrelTyConRepName $ cTupleDataConName arity
_ -> panic "getCTupleDataConName: impossible"
--------------------------------------------------
-- Normal tuples
mkTupleDataConUnique :: Boxity -> Arity -> Unique
mkTupleDataConUnique Boxed a = mkUnique '7' (3*a) -- may be used in C labels
mkTupleDataConUnique Unboxed a = mkUnique '8' (3*a)
mkTupleTyConUnique :: Boxity -> Arity -> Unique
mkTupleTyConUnique Boxed a = mkUnique '4' (2*a)
mkTupleTyConUnique Unboxed a = mkUnique '5' (2*a)
getTupleTyConName :: Boxity -> Int -> Name
getTupleTyConName boxity n =
case n `divMod` 2 of
(arity, 0) -> tyConName $ tupleTyCon boxity arity
(arity, 1) -> fromMaybe (panic "getTupleTyConName")
$ tyConRepName_maybe $ tupleTyCon boxity arity
_ -> panic "getTupleTyConName: impossible"
getTupleDataConName :: Boxity -> Int -> Name
getTupleDataConName boxity n =
case n `divMod` 3 of
(arity, 0) -> dataConName $ tupleDataCon boxity arity
(arity, 1) -> idName $ dataConWorkId $ tupleDataCon boxity arity
(arity, 2) -> fromMaybe (panic "getTupleDataCon")
$ tyConRepName_maybe $ promotedTupleDataCon boxity arity
_ -> panic "getTupleDataConName: impossible"
| olsner/ghc | compiler/prelude/KnownUniques.hs | bsd-3-clause | 4,874 | 0 | 12 | 1,097 | 1,002 | 542 | 460 | 87 | 8 |
{-
Copyright (C) 2006-2015 John MacFarlane <[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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Writers.RTF
Copyright : Copyright (C) 2006-2015 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
Conversion of 'Pandoc' documents to RTF (rich text format).
-}
module Text.Pandoc.Writers.RTF ( writeRTF, writeRTFWithEmbeddedImages ) where
import Text.Pandoc.Definition
import Text.Pandoc.Options
import Text.Pandoc.Shared
import Text.Pandoc.Writers.Shared
import Text.Pandoc.Readers.TeXMath
import Text.Pandoc.Templates (renderTemplate')
import Text.Pandoc.Walk
import Data.List ( isSuffixOf, intercalate )
import Data.Char ( ord, chr, isDigit )
import qualified Data.ByteString as B
import qualified Data.Map as M
import Text.Printf ( printf )
import Text.Pandoc.ImageSize
-- | Convert Image inlines into a raw RTF embedded image, read from a file,
-- or a MediaBag, or the internet.
-- If file not found or filetype not jpeg or png, leave the inline unchanged.
rtfEmbedImage :: WriterOptions -> Inline -> IO Inline
rtfEmbedImage opts x@(Image attr _ (src,_)) = do
result <- fetchItem' (writerMediaBag opts) (writerSourceURL opts) src
case result of
Right (imgdata, Just mime)
| mime == "image/jpeg" || mime == "image/png" -> do
let bytes = map (printf "%02x") $ B.unpack imgdata
let filetype = case mime of
"image/jpeg" -> "\\jpegblip"
"image/png" -> "\\pngblip"
_ -> error "Unknown file type"
sizeSpec <- case imageSize imgdata of
Left msg -> do
warn $ "Could not determine image size in `" ++
src ++ "': " ++ msg
return ""
Right sz -> return $ "\\picw" ++ show xpx ++
"\\pich" ++ show ypx ++
"\\picwgoal" ++ show (floor (xpt * 20) :: Integer)
++ "\\pichgoal" ++ show (floor (ypt * 20) :: Integer)
-- twip = 1/1440in = 1/20pt
where (xpx, ypx) = sizeInPixels sz
(xpt, ypt) = desiredSizeInPoints opts attr sz
let raw = "{\\pict" ++ filetype ++ sizeSpec ++ "\\bin " ++
concat bytes ++ "}"
return $ if B.null imgdata
then x
else RawInline (Format "rtf") raw
_ -> return x
rtfEmbedImage _ x = return x
-- | Convert Pandoc to a string in rich text format, with
-- images embedded as encoded binary data.
writeRTFWithEmbeddedImages :: WriterOptions -> Pandoc -> IO String
writeRTFWithEmbeddedImages options doc =
writeRTF options `fmap` walkM (rtfEmbedImage options) doc
-- | Convert Pandoc to a string in rich text format.
writeRTF :: WriterOptions -> Pandoc -> String
writeRTF options (Pandoc meta@(Meta metamap) blocks) =
let spacer = not $ all null $ docTitle meta : docDate meta : docAuthors meta
toPlain (MetaBlocks [Para ils]) = MetaInlines ils
toPlain x = x
-- adjust title, author, date so we don't get para inside para
meta' = Meta $ M.adjust toPlain "title"
. M.adjust toPlain "author"
. M.adjust toPlain "date"
$ metamap
Just metadata = metaToJSON options
(Just . concatMap (blockToRTF 0 AlignDefault))
(Just . inlineListToRTF)
meta'
body = concatMap (blockToRTF 0 AlignDefault) blocks
isTOCHeader (Header lev _ _) = lev <= writerTOCDepth options
isTOCHeader _ = False
context = defField "body" body
$ defField "spacer" spacer
$ (if writerTableOfContents options
then defField "toc"
(tableOfContents $ filter isTOCHeader blocks)
else id)
$ metadata
in if writerStandalone options
then renderTemplate' (writerTemplate options) context
else case reverse body of
('\n':_) -> body
_ -> body ++ "\n"
-- | Construct table of contents from list of header blocks.
tableOfContents :: [Block] -> String
tableOfContents headers =
let contentsTree = hierarchicalize headers
in concatMap (blockToRTF 0 AlignDefault) $
[Header 1 nullAttr [Str "Contents"],
BulletList (map elementToListItem contentsTree)]
elementToListItem :: Element -> [Block]
elementToListItem (Blk _) = []
elementToListItem (Sec _ _ _ sectext subsecs) = [Plain sectext] ++
if null subsecs
then []
else [BulletList (map elementToListItem subsecs)]
-- | Convert unicode characters (> 127) into rich text format representation.
handleUnicode :: String -> String
handleUnicode [] = []
handleUnicode (c:cs) =
if ord c > 127
then if surrogate c
then let x = ord c - 0x10000
(q, r) = x `divMod` 0x400
upper = q + 0xd800
lower = r + 0xDC00
in enc (chr upper) ++ enc (chr lower) ++ handleUnicode cs
else enc c ++ handleUnicode cs
else c:(handleUnicode cs)
where
surrogate x = not ( (0x0000 <= ord x && ord x <= 0xd7ff)
|| (0xe000 <= ord x && ord x <= 0xffff) )
enc x = '\\':'u':(show (ord x)) ++ "?"
-- | Escape special characters.
escapeSpecial :: String -> String
escapeSpecial = escapeStringUsing $
[ ('\t',"\\tab ")
, ('\8216',"\\u8216'")
, ('\8217',"\\u8217'")
, ('\8220',"\\u8220\"")
, ('\8221',"\\u8221\"")
, ('\8211',"\\u8211-")
, ('\8212',"\\u8212-")
] ++ backslashEscapes "{\\}"
-- | Escape strings as needed for rich text format.
stringToRTF :: String -> String
stringToRTF = handleUnicode . escapeSpecial
-- | Escape things as needed for code block in RTF.
codeStringToRTF :: String -> String
codeStringToRTF str = intercalate "\\line\n" $ lines (stringToRTF str)
-- | Make a paragraph with first-line indent, block indent, and space after.
rtfParSpaced :: Int -- ^ space after (in twips)
-> Int -- ^ block indent (in twips)
-> Int -- ^ first line indent (relative to block) (in twips)
-> Alignment -- ^ alignment
-> String -- ^ string with content
-> String
rtfParSpaced spaceAfter indent firstLineIndent alignment content =
let alignString = case alignment of
AlignLeft -> "\\ql "
AlignRight -> "\\qr "
AlignCenter -> "\\qc "
AlignDefault -> "\\ql "
in "{\\pard " ++ alignString ++
"\\f0 \\sa" ++ (show spaceAfter) ++ " \\li" ++ (show indent) ++
" \\fi" ++ (show firstLineIndent) ++ " " ++ content ++ "\\par}\n"
-- | Default paragraph.
rtfPar :: Int -- ^ block indent (in twips)
-> Int -- ^ first line indent (relative to block) (in twips)
-> Alignment -- ^ alignment
-> String -- ^ string with content
-> String
rtfPar = rtfParSpaced 180
-- | Compact paragraph (e.g. for compact list items).
rtfCompact :: Int -- ^ block indent (in twips)
-> Int -- ^ first line indent (relative to block) (in twips)
-> Alignment -- ^ alignment
-> String -- ^ string with content
-> String
rtfCompact = rtfParSpaced 0
-- number of twips to indent
indentIncrement :: Int
indentIncrement = 720
listIncrement :: Int
listIncrement = 360
-- | Returns appropriate bullet list marker for indent level.
bulletMarker :: Int -> String
bulletMarker indent = case indent `mod` 720 of
0 -> "\\bullet "
_ -> "\\endash "
-- | Returns appropriate (list of) ordered list markers for indent level.
orderedMarkers :: Int -> ListAttributes -> [String]
orderedMarkers indent (start, style, delim) =
if style == DefaultStyle && delim == DefaultDelim
then case indent `mod` 720 of
0 -> orderedListMarkers (start, Decimal, Period)
_ -> orderedListMarkers (start, LowerAlpha, Period)
else orderedListMarkers (start, style, delim)
-- | Convert Pandoc block element to RTF.
blockToRTF :: Int -- ^ indent level
-> Alignment -- ^ alignment
-> Block -- ^ block to convert
-> String
blockToRTF _ _ Null = ""
blockToRTF indent alignment (Div _ bs) =
concatMap (blockToRTF indent alignment) bs
blockToRTF indent alignment (Plain lst) =
rtfCompact indent 0 alignment $ inlineListToRTF lst
blockToRTF indent alignment (Para lst) =
rtfPar indent 0 alignment $ inlineListToRTF lst
blockToRTF indent alignment (BlockQuote lst) =
concatMap (blockToRTF (indent + indentIncrement) alignment) lst
blockToRTF indent _ (CodeBlock _ str) =
rtfPar indent 0 AlignLeft ("\\f1 " ++ (codeStringToRTF str))
blockToRTF _ _ (RawBlock f str)
| f == Format "rtf" = str
| otherwise = ""
blockToRTF indent alignment (BulletList lst) = spaceAtEnd $
concatMap (listItemToRTF alignment indent (bulletMarker indent)) lst
blockToRTF indent alignment (OrderedList attribs lst) = spaceAtEnd $ concat $
zipWith (listItemToRTF alignment indent) (orderedMarkers indent attribs) lst
blockToRTF indent alignment (DefinitionList lst) = spaceAtEnd $
concatMap (definitionListItemToRTF alignment indent) lst
blockToRTF indent _ HorizontalRule =
rtfPar indent 0 AlignCenter "\\emdash\\emdash\\emdash\\emdash\\emdash"
blockToRTF indent alignment (Header level _ lst) = rtfPar indent 0 alignment $
"\\b \\fs" ++ (show (40 - (level * 4))) ++ " " ++ inlineListToRTF lst
blockToRTF indent alignment (Table caption aligns sizes headers rows) =
(if all null headers
then ""
else tableRowToRTF True indent aligns sizes headers) ++
concatMap (tableRowToRTF False indent aligns sizes) rows ++
rtfPar indent 0 alignment (inlineListToRTF caption)
tableRowToRTF :: Bool -> Int -> [Alignment] -> [Double] -> [[Block]] -> String
tableRowToRTF header indent aligns sizes' cols =
let totalTwips = 6 * 1440 -- 6 inches
sizes = if all (== 0) sizes'
then take (length cols) $ repeat (1.0 / fromIntegral (length cols))
else sizes'
columns = concat $ zipWith (tableItemToRTF indent) aligns cols
rightEdges = tail $ scanl (\sofar new -> sofar + floor (new * totalTwips))
(0 :: Integer) sizes
cellDefs = map (\edge -> (if header
then "\\clbrdrb\\brdrs"
else "") ++ "\\cellx" ++ show edge)
rightEdges
start = "{\n\\trowd \\trgaph120\n" ++ concat cellDefs ++ "\n" ++
"\\trkeep\\intbl\n{\n"
end = "}\n\\intbl\\row}\n"
in start ++ columns ++ end
tableItemToRTF :: Int -> Alignment -> [Block] -> String
tableItemToRTF indent alignment item =
let contents = concatMap (blockToRTF indent alignment) item
in "{" ++ substitute "\\pard" "\\pard\\intbl" contents ++ "\\cell}\n"
-- | Ensure that there's the same amount of space after compact
-- lists as after regular lists.
spaceAtEnd :: String -> String
spaceAtEnd str =
if isSuffixOf "\\par}\n" str
then (take ((length str) - 6) str) ++ "\\sa180\\par}\n"
else str
-- | Convert list item (list of blocks) to RTF.
listItemToRTF :: Alignment -- ^ alignment
-> Int -- ^ indent level
-> String -- ^ list start marker
-> [Block] -- ^ list item (list of blocks)
-> [Char]
listItemToRTF alignment indent marker [] =
rtfCompact (indent + listIncrement) (0 - listIncrement) alignment
(marker ++ "\\tx" ++ (show listIncrement) ++ "\\tab ")
listItemToRTF alignment indent marker list =
let (first:rest) = map (blockToRTF (indent + listIncrement) alignment) list
listMarker = "\\fi" ++ show (0 - listIncrement) ++ " " ++ marker ++ "\\tx" ++
show listIncrement ++ "\\tab"
insertListMarker ('\\':'f':'i':'-':d:xs) | isDigit d =
listMarker ++ dropWhile isDigit xs
insertListMarker ('\\':'f':'i':d:xs) | isDigit d =
listMarker ++ dropWhile isDigit xs
insertListMarker (x:xs) =
x : insertListMarker xs
insertListMarker [] = []
-- insert the list marker into the (processed) first block
in insertListMarker first ++ concat rest
-- | Convert definition list item (label, list of blocks) to RTF.
definitionListItemToRTF :: Alignment -- ^ alignment
-> Int -- ^ indent level
-> ([Inline],[[Block]]) -- ^ list item (list of blocks)
-> [Char]
definitionListItemToRTF alignment indent (label, defs) =
let labelText = blockToRTF indent alignment (Plain label)
itemsText = concatMap (blockToRTF (indent + listIncrement) alignment) $
concat defs
in labelText ++ itemsText
-- | Convert list of inline items to RTF.
inlineListToRTF :: [Inline] -- ^ list of inlines to convert
-> String
inlineListToRTF lst = concatMap inlineToRTF lst
-- | Convert inline item to RTF.
inlineToRTF :: Inline -- ^ inline to convert
-> String
inlineToRTF (Span _ lst) = inlineListToRTF lst
inlineToRTF (Emph lst) = "{\\i " ++ (inlineListToRTF lst) ++ "}"
inlineToRTF (Strong lst) = "{\\b " ++ (inlineListToRTF lst) ++ "}"
inlineToRTF (Strikeout lst) = "{\\strike " ++ (inlineListToRTF lst) ++ "}"
inlineToRTF (Superscript lst) = "{\\super " ++ (inlineListToRTF lst) ++ "}"
inlineToRTF (Subscript lst) = "{\\sub " ++ (inlineListToRTF lst) ++ "}"
inlineToRTF (SmallCaps lst) = "{\\scaps " ++ (inlineListToRTF lst) ++ "}"
inlineToRTF (Quoted SingleQuote lst) =
"\\u8216'" ++ (inlineListToRTF lst) ++ "\\u8217'"
inlineToRTF (Quoted DoubleQuote lst) =
"\\u8220\"" ++ (inlineListToRTF lst) ++ "\\u8221\""
inlineToRTF (Code _ str) = "{\\f1 " ++ (codeStringToRTF str) ++ "}"
inlineToRTF (Str str) = stringToRTF str
inlineToRTF (Math t str) = inlineListToRTF $ texMathToInlines t str
inlineToRTF (Cite _ lst) = inlineListToRTF lst
inlineToRTF (RawInline f str)
| f == Format "rtf" = str
| otherwise = ""
inlineToRTF (LineBreak) = "\\line "
inlineToRTF SoftBreak = " "
inlineToRTF Space = " "
inlineToRTF (Link _ text (src, _)) =
"{\\field{\\*\\fldinst{HYPERLINK \"" ++ (codeStringToRTF src) ++
"\"}}{\\fldrslt{\\ul\n" ++ (inlineListToRTF text) ++ "\n}}}\n"
inlineToRTF (Image _ _ (source, _)) =
"{\\cf1 [image: " ++ source ++ "]\\cf0}"
inlineToRTF (Note contents) =
"{\\super\\chftn}{\\*\\footnote\\chftn\\~\\plain\\pard " ++
(concatMap (blockToRTF 0 AlignDefault) contents) ++ "}"
| infotroph/pandoc | src/Text/Pandoc/Writers/RTF.hs | gpl-2.0 | 15,663 | 306 | 24 | 4,389 | 3,827 | 1,993 | 1,834 | 280 | 6 |
-- | Carries interesting info for debugging / profiling of the
-- graph coloring register allocator.
module RegAlloc.Graph.Stats (
RegAllocStats (..),
pprStats,
pprStatsSpills,
pprStatsLifetimes,
pprStatsConflict,
pprStatsLifeConflict,
countSRMs, addSRM
) where
#include "nativeGen/NCG.h"
import qualified GraphColor as Color
import RegAlloc.Liveness
import RegAlloc.Graph.Spill
import RegAlloc.Graph.SpillCost
import RegAlloc.Graph.TrivColorable
import Instruction
import RegClass
import Reg
import TargetReg
import PprCmm()
import Outputable
import UniqFM
import UniqSet
import State
import Data.List
-- | Holds interesting statistics from the register allocator.
data RegAllocStats statics instr
-- Information about the initial conflict graph.
= RegAllocStatsStart
{ -- | Initial code, with liveness.
raLiveCmm :: [LiveCmmDecl statics instr]
-- | The initial, uncolored graph.
, raGraph :: Color.Graph VirtualReg RegClass RealReg
-- | Information to help choose which regs to spill.
, raSpillCosts :: SpillCostInfo }
-- Information about an intermediate graph.
-- This is one that we couldn't color, so had to insert spill code
-- instruction stream.
| RegAllocStatsSpill
{ -- | Code we tried to allocate registers for.
raCode :: [LiveCmmDecl statics instr]
-- | Partially colored graph.
, raGraph :: Color.Graph VirtualReg RegClass RealReg
-- | The regs that were coaleced.
, raCoalesced :: UniqFM VirtualReg
-- | Spiller stats.
, raSpillStats :: SpillStats
-- | Number of instructions each reg lives for.
, raSpillCosts :: SpillCostInfo
-- | Code with spill instructions added.
, raSpilled :: [LiveCmmDecl statics instr] }
-- a successful coloring
| RegAllocStatsColored
{ -- | Code we tried to allocate registers for.
raCode :: [LiveCmmDecl statics instr]
-- | Uncolored graph.
, raGraph :: Color.Graph VirtualReg RegClass RealReg
-- | Coalesced and colored graph.
, raGraphColored :: Color.Graph VirtualReg RegClass RealReg
-- | Regs that were coaleced.
, raCoalesced :: UniqFM VirtualReg
-- | Code with coalescings applied.
, raCodeCoalesced :: [LiveCmmDecl statics instr]
-- | Code with vregs replaced by hregs.
, raPatched :: [LiveCmmDecl statics instr]
-- | Code with unneeded spill\/reloads cleaned out.
, raSpillClean :: [LiveCmmDecl statics instr]
-- | Final code.
, raFinal :: [NatCmmDecl statics instr]
-- | Spill\/reload\/reg-reg moves present in this code.
, raSRMs :: (Int, Int, Int) }
instance (Outputable statics, Outputable instr)
=> Outputable (RegAllocStats statics instr) where
ppr (s@RegAllocStatsStart{}) = sdocWithPlatform $ \platform ->
text "# Start"
$$ text "# Native code with liveness information."
$$ ppr (raLiveCmm s)
$$ text ""
$$ text "# Initial register conflict graph."
$$ Color.dotGraph
(targetRegDotColor platform)
(trivColorable platform
(targetVirtualRegSqueeze platform)
(targetRealRegSqueeze platform))
(raGraph s)
ppr (s@RegAllocStatsSpill{}) =
text "# Spill"
$$ text "# Code with liveness information."
$$ ppr (raCode s)
$$ text ""
$$ (if (not $ isNullUFM $ raCoalesced s)
then text "# Registers coalesced."
$$ (vcat $ map ppr $ ufmToList $ raCoalesced s)
$$ text ""
else empty)
$$ text "# Spills inserted."
$$ ppr (raSpillStats s)
$$ text ""
$$ text "# Code with spills inserted."
$$ ppr (raSpilled s)
ppr (s@RegAllocStatsColored { raSRMs = (spills, reloads, moves) })
= sdocWithPlatform $ \platform ->
text "# Colored"
$$ text "# Code with liveness information."
$$ ppr (raCode s)
$$ text ""
$$ text "# Register conflict graph (colored)."
$$ Color.dotGraph
(targetRegDotColor platform)
(trivColorable platform
(targetVirtualRegSqueeze platform)
(targetRealRegSqueeze platform))
(raGraphColored s)
$$ text ""
$$ (if (not $ isNullUFM $ raCoalesced s)
then text "# Registers coalesced."
$$ (vcat $ map ppr $ ufmToList $ raCoalesced s)
$$ text ""
else empty)
$$ text "# Native code after coalescings applied."
$$ ppr (raCodeCoalesced s)
$$ text ""
$$ text "# Native code after register allocation."
$$ ppr (raPatched s)
$$ text ""
$$ text "# Clean out unneeded spill/reloads."
$$ ppr (raSpillClean s)
$$ text ""
$$ text "# Final code, after rewriting spill/rewrite pseudo instrs."
$$ ppr (raFinal s)
$$ text ""
$$ text "# Score:"
$$ (text "# spills inserted: " <> int spills)
$$ (text "# reloads inserted: " <> int reloads)
$$ (text "# reg-reg moves remaining: " <> int moves)
$$ text ""
-- | Do all the different analysis on this list of RegAllocStats
pprStats
:: [RegAllocStats statics instr]
-> Color.Graph VirtualReg RegClass RealReg
-> SDoc
pprStats stats graph
= let outSpills = pprStatsSpills stats
outLife = pprStatsLifetimes stats
outConflict = pprStatsConflict stats
outScatter = pprStatsLifeConflict stats graph
in vcat [outSpills, outLife, outConflict, outScatter]
-- | Dump a table of how many spill loads \/ stores were inserted for each vreg.
pprStatsSpills
:: [RegAllocStats statics instr] -> SDoc
pprStatsSpills stats
= let
finals = [ s | s@RegAllocStatsColored{} <- stats]
-- sum up how many stores\/loads\/reg-reg-moves were left in the code
total = foldl' addSRM (0, 0, 0)
$ map raSRMs finals
in ( text "-- spills-added-total"
$$ text "-- (stores, loads, reg_reg_moves_remaining)"
$$ ppr total
$$ text "")
-- | Dump a table of how long vregs tend to live for in the initial code.
pprStatsLifetimes
:: [RegAllocStats statics instr] -> SDoc
pprStatsLifetimes stats
= let info = foldl' plusSpillCostInfo zeroSpillCostInfo
[ raSpillCosts s
| s@RegAllocStatsStart{} <- stats ]
lifeBins = binLifetimeCount $ lifeMapFromSpillCostInfo info
in ( text "-- vreg-population-lifetimes"
$$ text "-- (instruction_count, number_of_vregs_that_lived_that_long)"
$$ (vcat $ map ppr $ eltsUFM lifeBins)
$$ text "\n")
binLifetimeCount :: UniqFM (VirtualReg, Int) -> UniqFM (Int, Int)
binLifetimeCount fm
= let lifes = map (\l -> (l, (l, 1)))
$ map snd
$ eltsUFM fm
in addListToUFM_C
(\(l1, c1) (_, c2) -> (l1, c1 + c2))
emptyUFM
lifes
-- | Dump a table of how many conflicts vregs tend to have in the initial code.
pprStatsConflict
:: [RegAllocStats statics instr] -> SDoc
pprStatsConflict stats
= let confMap = foldl' (plusUFM_C (\(c1, n1) (_, n2) -> (c1, n1 + n2)))
emptyUFM
$ map Color.slurpNodeConflictCount
[ raGraph s | s@RegAllocStatsStart{} <- stats ]
in ( text "-- vreg-conflicts"
$$ text "-- (conflict_count, number_of_vregs_that_had_that_many_conflicts)"
$$ (vcat $ map ppr $ eltsUFM confMap)
$$ text "\n")
-- | For every vreg, dump it's how many conflicts it has and its lifetime
-- good for making a scatter plot.
pprStatsLifeConflict
:: [RegAllocStats statics instr]
-> Color.Graph VirtualReg RegClass RealReg -- ^ global register conflict graph
-> SDoc
pprStatsLifeConflict stats graph
= let lifeMap = lifeMapFromSpillCostInfo
$ foldl' plusSpillCostInfo zeroSpillCostInfo
$ [ raSpillCosts s | s@RegAllocStatsStart{} <- stats ]
scatter = map (\r -> let lifetime = case lookupUFM lifeMap r of
Just (_, l) -> l
Nothing -> 0
Just node = Color.lookupNode graph r
in parens $ hcat $ punctuate (text ", ")
[ doubleQuotes $ ppr $ Color.nodeId node
, ppr $ sizeUniqSet (Color.nodeConflicts node)
, ppr $ lifetime ])
$ map Color.nodeId
$ eltsUFM
$ Color.graphMap graph
in ( text "-- vreg-conflict-lifetime"
$$ text "-- (vreg, vreg_conflicts, vreg_lifetime)"
$$ (vcat scatter)
$$ text "\n")
-- | Count spill/reload/reg-reg moves.
-- Lets us see how well the register allocator has done.
countSRMs
:: Instruction instr
=> LiveCmmDecl statics instr -> (Int, Int, Int)
countSRMs cmm
= execState (mapBlockTopM countSRM_block cmm) (0, 0, 0)
countSRM_block
:: Instruction instr
=> GenBasicBlock (LiveInstr instr)
-> State (Int, Int, Int) (GenBasicBlock (LiveInstr instr))
countSRM_block (BasicBlock i instrs)
= do instrs' <- mapM countSRM_instr instrs
return $ BasicBlock i instrs'
countSRM_instr
:: Instruction instr
=> LiveInstr instr -> State (Int, Int, Int) (LiveInstr instr)
countSRM_instr li
| LiveInstr SPILL{} _ <- li
= do modify $ \(s, r, m) -> (s + 1, r, m)
return li
| LiveInstr RELOAD{} _ <- li
= do modify $ \(s, r, m) -> (s, r + 1, m)
return li
| LiveInstr instr _ <- li
, Just _ <- takeRegRegMoveInstr instr
= do modify $ \(s, r, m) -> (s, r, m + 1)
return li
| otherwise
= return li
-- sigh..
addSRM :: (Int, Int, Int) -> (Int, Int, Int) -> (Int, Int, Int)
addSRM (s1, r1, m1) (s2, r2, m2)
= let !s = s1 + s2
!r = r1 + r2
!m = m1 + m2
in (s, r, m)
| hferreiro/replay | compiler/nativeGen/RegAlloc/Graph/Stats.hs | bsd-3-clause | 11,096 | 0 | 34 | 4,090 | 2,437 | 1,274 | 1,163 | -1 | -1 |
module Fixme where
import Language.Haskell.Liquid.Prelude
{-@
data Splay a <l :: root:a -> a -> Bool, r :: root:a -> a -> Bool>
= Node (value :: a)
(left :: Splay <l, r> (a <l value>))
(right :: Splay <l, r> (a <r value>))
| Leaf
@-}
data Splay a = Leaf | Node a (Splay a) (Splay a) deriving Show
{-@ type OSplay a = Splay <{v:a | v < root}, {v:a | v > root}> a @-}
{-@ split :: Ord a => x:a -> OSplay a
-> (Bool, OSplay {v:a | v<x}, OSplay {v:a | v>x})
<{v:Splay {v:a | (~(fld) => (v!=x))} |0=0},{v:Splay a | 0=0} >
@-}
split :: Ord a => a -> Splay a -> (Bool, Splay a, Splay a)
split _ Leaf = (False,Leaf,Leaf)
split k (Node xk xl xr) = case compare k xk of
EQ -> (True, xl, xr)
GT -> case xr of
Leaf -> (False, Node xk xl Leaf, Leaf)
Node yk yl yr -> case compare k yk of
EQ -> (True, Node xk xl yl, yr) -- R :zig
GT -> let (b, lt, gt) = split k yr -- RR :zig zag
in (b, Node yk (Node xk xl yl) lt, gt)
LT -> let (b, lt, gt) = split k yl
in (b, Node xk xl lt, Node yk gt yr) -- RL :zig zig
LT -> case xl of
Leaf -> (False, Leaf, Node xk Leaf xr)
Node yk yl yr -> case compare k yk of
EQ -> (True, yl, Node xk yr xr) -- L :zig
GT -> let (b, lt, gt) = split k yr -- LR :zig zag
in (b, Node yk yl lt, Node xk gt xr)
LT -> let (b, lt, gt) = split k yl -- LL :zig zig
in (b, lt, Node yk gt (Node xk yr xr))
| ssaavedra/liquidhaskell | benchmarks/llrbtree-0.1.1/Data/Set/fixme.hs | bsd-3-clause | 1,657 | 0 | 19 | 664 | 531 | 282 | 249 | 23 | 9 |
{-# LANGUAGE TemplateHaskell #-}
module A where
a = [|3|]
| ezyang/ghc | testsuite/tests/th/should_compile/T8025/A.hs | bsd-3-clause | 58 | 0 | 4 | 10 | 13 | 10 | 3 | 3 | 1 |
module Main where
import Idris.Core.TT
import Idris.AbsSyntax
import Idris.ElabDecls
import Idris.REPL
import IRTS.Compiler
import IRTS.CodegenJavaScript
import System.Environment
import System.Exit
import Paths_idris
data Opts = Opts {
inputs :: [FilePath]
, output :: FilePath
}
showUsage = do putStrLn "A code generator which is intended to be called by the compiler, not by a user."
putStrLn "Usage: idris-codegen-javascript <ibc-files> [-o <output-file>]"
exitWith ExitSuccess
getOpts :: IO Opts
getOpts = do xs <- getArgs
return $ process (Opts [] "main.js") xs
where
process opts ("-o":o:xs) = process (opts { output = o }) xs
process opts (x:xs) = process (opts { inputs = x:inputs opts }) xs
process opts [] = opts
jsMain :: Opts -> Idris ()
jsMain opts = do elabPrims
loadInputs (inputs opts) Nothing
mainProg <- elabMain
ir <- compile (Via "javascript") (output opts) (Just mainProg)
runIO $ codegenJavaScript ir
main :: IO ()
main = do opts <- getOpts
if (null (inputs opts))
then showUsage
else runMain (jsMain opts)
| mrmonday/Idris-dev | codegen/idris-codegen-javascript/Main.hs | bsd-3-clause | 1,253 | 0 | 12 | 384 | 370 | 189 | 181 | 33 | 3 |
import Control.Exception
import Data.List
import System.FilePath
import System.Directory
import System.IO
-- Checks that openTempFile returns filenames with the right structure
main :: IO ()
main = do
fp0 <- otf ".no_prefix.hs"
print (".hs" `isSuffixOf` fp0)
print (".no_prefix" `isPrefixOf` takeFileName fp0)
fp1 <- otf "no_suffix"
print (not ('.' `elem` fp1))
print ("no_suffix" `isPrefixOf` takeFileName fp1)
fp2 <- otf "one_suffix.hs"
print (".hs" `isSuffixOf` fp2)
print ("one_suffix" `isPrefixOf` takeFileName fp2)
fp3 <- otf "two_suffixes.hs.blah"
print (".blah" `isSuffixOf` fp3)
print ("two_suffixes.hs" `isPrefixOf` takeFileName fp3)
otf :: FilePath -> IO FilePath
otf fp = do putStrLn fp
bracket (openTempFile "." fp)
(\(fp', h) -> do hClose h
removeFile fp')
(\(fp', _) -> case fp' of
'.' : '/' : fp'' -> return fp''
'.' : '\\' : fp'' -> return fp''
_ -> return fp')
| urbanslug/ghc | libraries/base/tests/tempfiles.hs | bsd-3-clause | 1,130 | 0 | 14 | 381 | 351 | 175 | 176 | 28 | 3 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.SVGFEConvolveMatrixElement
(pattern SVG_EDGEMODE_UNKNOWN, pattern SVG_EDGEMODE_DUPLICATE,
pattern SVG_EDGEMODE_WRAP, pattern SVG_EDGEMODE_NONE, getIn1,
getOrderX, getOrderY, getKernelMatrix, getDivisor, getBias,
getTargetX, getTargetY, getEdgeMode, getKernelUnitLengthX,
getKernelUnitLengthY, getPreserveAlpha,
SVGFEConvolveMatrixElement(..), gTypeSVGFEConvolveMatrixElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
pattern SVG_EDGEMODE_UNKNOWN = 0
pattern SVG_EDGEMODE_DUPLICATE = 1
pattern SVG_EDGEMODE_WRAP = 2
pattern SVG_EDGEMODE_NONE = 3
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEConvolveMatrixElement.in1 Mozilla SVGFEConvolveMatrixElement.in1 documentation>
getIn1 ::
(MonadDOM m) => SVGFEConvolveMatrixElement -> m SVGAnimatedString
getIn1 self = liftDOM ((self ^. js "in1") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEConvolveMatrixElement.orderX Mozilla SVGFEConvolveMatrixElement.orderX documentation>
getOrderX ::
(MonadDOM m) => SVGFEConvolveMatrixElement -> m SVGAnimatedInteger
getOrderX self
= liftDOM ((self ^. js "orderX") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEConvolveMatrixElement.orderY Mozilla SVGFEConvolveMatrixElement.orderY documentation>
getOrderY ::
(MonadDOM m) => SVGFEConvolveMatrixElement -> m SVGAnimatedInteger
getOrderY self
= liftDOM ((self ^. js "orderY") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEConvolveMatrixElement.kernelMatrix Mozilla SVGFEConvolveMatrixElement.kernelMatrix documentation>
getKernelMatrix ::
(MonadDOM m) =>
SVGFEConvolveMatrixElement -> m SVGAnimatedNumberList
getKernelMatrix self
= liftDOM ((self ^. js "kernelMatrix") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEConvolveMatrixElement.divisor Mozilla SVGFEConvolveMatrixElement.divisor documentation>
getDivisor ::
(MonadDOM m) => SVGFEConvolveMatrixElement -> m SVGAnimatedNumber
getDivisor self
= liftDOM ((self ^. js "divisor") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEConvolveMatrixElement.bias Mozilla SVGFEConvolveMatrixElement.bias documentation>
getBias ::
(MonadDOM m) => SVGFEConvolveMatrixElement -> m SVGAnimatedNumber
getBias self = liftDOM ((self ^. js "bias") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEConvolveMatrixElement.targetX Mozilla SVGFEConvolveMatrixElement.targetX documentation>
getTargetX ::
(MonadDOM m) => SVGFEConvolveMatrixElement -> m SVGAnimatedInteger
getTargetX self
= liftDOM ((self ^. js "targetX") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEConvolveMatrixElement.targetY Mozilla SVGFEConvolveMatrixElement.targetY documentation>
getTargetY ::
(MonadDOM m) => SVGFEConvolveMatrixElement -> m SVGAnimatedInteger
getTargetY self
= liftDOM ((self ^. js "targetY") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEConvolveMatrixElement.edgeMode Mozilla SVGFEConvolveMatrixElement.edgeMode documentation>
getEdgeMode ::
(MonadDOM m) =>
SVGFEConvolveMatrixElement -> m SVGAnimatedEnumeration
getEdgeMode self
= liftDOM ((self ^. js "edgeMode") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEConvolveMatrixElement.kernelUnitLengthX Mozilla SVGFEConvolveMatrixElement.kernelUnitLengthX documentation>
getKernelUnitLengthX ::
(MonadDOM m) => SVGFEConvolveMatrixElement -> m SVGAnimatedNumber
getKernelUnitLengthX self
= liftDOM ((self ^. js "kernelUnitLengthX") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEConvolveMatrixElement.kernelUnitLengthY Mozilla SVGFEConvolveMatrixElement.kernelUnitLengthY documentation>
getKernelUnitLengthY ::
(MonadDOM m) => SVGFEConvolveMatrixElement -> m SVGAnimatedNumber
getKernelUnitLengthY self
= liftDOM ((self ^. js "kernelUnitLengthY") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEConvolveMatrixElement.preserveAlpha Mozilla SVGFEConvolveMatrixElement.preserveAlpha documentation>
getPreserveAlpha ::
(MonadDOM m) => SVGFEConvolveMatrixElement -> m SVGAnimatedBoolean
getPreserveAlpha self
= liftDOM ((self ^. js "preserveAlpha") >>= fromJSValUnchecked)
| ghcjs/jsaddle-dom | src/JSDOM/Generated/SVGFEConvolveMatrixElement.hs | mit | 5,485 | 0 | 10 | 722 | 980 | 560 | 420 | 75 | 1 |
module ArmstrongNumbers (armstrong) where
import Data.List (unfoldr)
import Data.Tuple (swap)
armstrong :: Integral a => a -> Bool
armstrong num = (sum . map (^ exponent)) digits' == num
where
digits' = digits num
exponent = length digits'
digits :: Integral a => a -> [a]
digits = unfoldr tryExtractDigit
where
tryExtractDigit 0 = Nothing
tryExtractDigit n = (Just . swap . (`divMod` 10)) n | enolive/exercism | haskell/armstrong-numbers/src/ArmstrongNumbers.hs | mit | 414 | 0 | 10 | 87 | 157 | 85 | 72 | 11 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Forth
( ForthError(..)
, ForthState
, evalText
, formatStack
, empty
) where
import Data.Map (Map)
import Data.Text (Text)
import Data.Char (isSpace, isControl)
import qualified Data.Text as T
import qualified Data.Text.Read as R
import qualified Data.Map.Strict as M
import Control.Arrow (first)
type Value = Int
type Word = Text
data Term
= StartDefinition
| EndDefinition
| V Value
| W Word
deriving (Show, Ord, Eq)
data Definition
= Add
| Subtract
| Multiply
| Divide
| Dup
| Drop
| Swap
| Over
| User [Term]
deriving (Show, Eq)
data ForthState = ForthState
{ forthStack :: [Value]
, forthCode :: [Term]
, forthWords :: Map Word Definition
}
deriving (Show, Eq)
data ForthError
= DivisionByZero
| StackUnderflow
| InvalidWord
| UnknownWord Word
deriving (Show, Eq)
defaultWords :: Map Word Definition
defaultWords = M.fromList . map (first T.toCaseFold) $
[ ("+", Add)
, ("-", Subtract)
, ("*", Multiply)
, ("/", Divide)
, ("dup", Dup)
, ("drop", Drop)
, ("swap", Swap)
, ("over", Over)
]
empty :: ForthState
empty = ForthState
{ forthStack = []
, forthCode = []
, forthWords = defaultWords
}
parseText :: Text -> [Term]
parseText =
map toTerm . filter (not . T.null) . T.split (\c -> isSpace c || isControl c)
where
toTerm ":" = StartDefinition
toTerm ";" = EndDefinition
toTerm w = case R.signed R.decimal w of
Right (n, "") -> V n
_ -> W (T.toCaseFold w)
eval :: [Term] -> ForthState -> Either ForthError ForthState
eval code state = mapCode (++code) state >>= runInterpreter
runInterpreter :: ForthState -> Either ForthError ForthState
runInterpreter s = case forthCode s of
[] -> return s
(x:xs) -> step x s { forthCode = xs }
with2 :: (Value -> Value -> ForthState -> Either ForthError ForthState)
-> ForthState
-> Either ForthError ForthState
with2 f s = case forthStack s of
(a:b:xs) -> f b a s { forthStack = xs }
_ -> Left StackUnderflow
with1 :: (Value -> ForthState -> Either ForthError ForthState)
-> ForthState
-> Either ForthError ForthState
with1 f s = case forthStack s of
(x:xs) -> f x s { forthStack = xs }
_ -> Left StackUnderflow
step :: Term -> ForthState -> Either ForthError ForthState
step t s = case t of
StartDefinition -> case break (EndDefinition ==) (forthCode s) of
((W w:xs), (EndDefinition:ys)) ->
runInterpreter s { forthWords = M.insert w (User xs) (forthWords s)
, forthCode = ys
}
(_, (EndDefinition:_)) -> Left InvalidWord
_ -> return s { forthCode = t : forthCode s }
EndDefinition -> Left InvalidWord
V v -> push v s >>= runInterpreter
W w ->
maybe (Left (UnknownWord w)) (`stepWord` s) (M.lookup w (forthWords s)) >>=
runInterpreter
push :: Value -> ForthState -> Either ForthError ForthState
push = mapStack . ((:) $!)
mapStack :: ([Value] -> [Value]) -> ForthState -> Either ForthError ForthState
mapStack f s = return s { forthStack = f (forthStack s) }
mapCode :: ([Term] -> [Term]) -> ForthState -> Either ForthError ForthState
mapCode f s = return s { forthCode = f (forthCode s) }
safeDiv :: Value -> Value -> Either ForthError Value
safeDiv a b
| b /= 0 = return (a `div` b)
| otherwise = Left DivisionByZero
(.:) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
(.:) = (.) . (.)
stepWord :: Definition -> ForthState -> Either ForthError ForthState
stepWord Add = with2 (push .: (+))
stepWord Subtract = with2 (push .: (-))
stepWord Multiply = with2 (push .: (*))
stepWord Divide = with2 (either (const . Left) push .: safeDiv)
stepWord Dup = with1 (mapStack . (++) . replicate 2)
stepWord Drop = with1 (const return)
stepWord Swap = with2 (\a b -> mapStack ([a, b] ++))
stepWord Over = with2 (\a b -> mapStack ([a, b, a] ++))
stepWord (User xs) = mapCode (xs ++)
evalText :: Text -> ForthState -> Either ForthError ForthState
evalText = eval . parseText
formatStack :: ForthState -> Text
formatStack = T.pack . unwords . map show . reverse . forthStack
| pminten/xhaskell | forth/example.hs | mit | 4,312 | 0 | 16 | 1,147 | 1,668 | 907 | 761 | 124 | 6 |
module LinePrinter
( LinePrinter
, printLine
)
where
class Monad m => LinePrinter m
where printLine :: String -> m ()
| 72636c/correct-fizz-buzz | src/LinePrinter.hs | mit | 127 | 0 | 9 | 30 | 42 | 22 | 20 | 5 | 0 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.ProcessingInstruction (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.ProcessingInstruction
#else
module Graphics.UI.Gtk.WebKit.DOM.ProcessingInstruction
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.ProcessingInstruction
#else
import Graphics.UI.Gtk.WebKit.DOM.ProcessingInstruction
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/ProcessingInstruction.hs | mit | 490 | 0 | 5 | 39 | 33 | 26 | 7 | 4 | 0 |
-- Intermission: Exercises
-- 1. Using takeWhile and dropWhile, write a function that takes a string and
-- returns a list of strings, using spaces to separate the elements of the
-- string into words, as in the following sample:
-- *Main> myWords "all i wanna do is have some fun"
-- ["all","i","wanna","do","is","have","some","fun"]
--myWords :: String -> [String]
myWords x = reverse $ go x []
where go x acc =
let upTo = takeWhile (/= ' ') x
after = dropWhile (/= ' ') x
in if after == ""
then upTo : acc
else go (tail after) (upTo : acc)
-- 2. Next, write a function that takes a string and returns a list of strings,
-- using newline separators to break up the string as in the following (your job
-- is to fill in the undefined function):
-- module PoemLines where
firstSen = "Tyger Tyger, burning bright\n"
secondSen = "In the forests of the night\n"
thirdSen = "What immortal hand or eye\n"
fourthSen = "Could frame thy fearful symmetry?"
sentences = firstSen ++ secondSen ++ thirdSen ++ fourthSen
-- putStrLn sentences -- should print
-- Tyger Tyger, burning bright
-- In the forests of the night
-- What immortal hand or eye
-- Could frame thy fearful symmetry?
-- Implement this
myLines :: String -> [String]
myLines x = reverse $ go x []
where go x acc =
let upTo = takeWhile (/= '\n') x
after = dropWhile (/= '\n') x
in if after == ""
then upTo : acc
else go (tail after) (upTo : acc)
-- What we want 'myLines sentences' to equal
shouldEqual =
["Tyger Tyger, burning bright" ,
"In the forests of the night" ,
"What immortal hand or eye" ,
"Could frame thy fearful symmetry?"]
-- The main function here is a small test -- to ensure you've written your function -- correctly.
main :: IO ()
main = print $ "Are they equal? " ++ show (myLines sentences == shouldEqual)
-- 3. Now let’s look at what those two functions have in common. Try writing a
-- new function that parameterizes the character you’re breaking the string
-- argument on and rewrite myWords and myLines using it.
myLinesPar :: String -> Char -> [String]
myLinesPar x n = reverse $ go x []
where go x acc =
let upTo = takeWhile (/= n) x
after = dropWhile (/= n) x
in if after == ""
then upTo : acc
else go (tail after) (upTo : acc)
| diminishedprime/.org | reading-list/haskell_programming_from_first_principles/09_06.hs | mit | 2,442 | 0 | 12 | 647 | 440 | 242 | 198 | 35 | 2 |
{-
Nume: Dimcica Tudor
Grupa: 321CC
-}
module Regexp where
import Parser
import Data.Char (isLetter, isDigit)
data Reg = Nil
| Sym Char
| Alt Reg Reg
| Seq Reg Reg
| Rep Reg
| Opt Reg
deriving Show
{-
Parser pentru extragerea unei litere sau a unei expresii dintr-o paranteza
-}
atom = (((spot isLetter) `transform` (\x -> Sym x)) `alt` parenSeq)
where
parenSeq = (token '(' >*> fParser >*> token ')') `transform` f
where
f (_, (e, _)) = e
{-
Parser pentru litera/paranteza
litera/paranteza + star
litera/paranteza + plus
litera/paranteza + semnul intrebarii
litera/paranteza + acolade de cuantificare
-}
qnty0 = atom >*> token '{' >*> number >*> token '}'
qnty1 = atom >*> token '{' >*> number >*> token ',' >*> token '}'
qnty2 = atom >*> token '{' >*> number >*> token ',' >*> number >*> token '}'
operator = (makeStar `alt` makePlus `alt` makeOpt `alt` makeQ `alt` atom)
where
makeStar = (atom >*> token '*') `transform` (\(e, _) -> Rep e)
makePlus = (atom >*> token '+') `transform` (\(e, _) -> Seq e (Rep e))
makeOpt = (atom >*> token '?') `transform` (\(e, _) -> Opt e)
makeQ = (qnty0 `transform` f0) `alt` (qnty1 `transform` f1) `alt` (qnty2 `transform` f2)
where
f0 (c, (_, (n, _))) = toQty0 c n
f1 (c, (_, (n, (_, _)))) = toQty1 c n
f2 (c, (_, (n1, (_, (n2, _))))) = toQty2 c n1 n2
{-
Functiile de creere a formei intermediare pentru acolada
-}
number = (spotWhile1 isDigit) `transform` (\x -> read x :: Integer)
{-
Cazul {n}
-}
toQty0 :: Reg -> Integer -> Reg
toQty0 e 1 = e
toQty0 e n = Seq e (toQty0 e (n - 1))
{-
Cazul {n,}
-}
toQty1 :: Reg -> Integer -> Reg
toQty1 e 0 = Rep e
toQty1 e 1 = Seq e (Rep e)
toQty1 e n = Seq e (toQty1 e (n - 1))
{-
Cazul {n1,n2}
-}
toQty2 :: Reg -> Integer -> Integer -> Reg
toQty2 e 0 n2 = if(n2 == 0)
then (toQty0 (Opt e) 1)
else Seq (toQty2 e 0 (n2 - 1)) (Opt e)
toQty2 e n1 n2 = if (n1 == n2)
then (toQty0 e n1)
else Seq (toQty2 e n1 (n2 - 1)) (Opt e)
{-
Parser pentru expresii ce pot fi multiple
-}
group = (operator `alt` multiple)
where
multiple = (operator >*> group) `transform` toSeq
where
toSeq (a, b) = Seq a b
{-
Parser pentru expresii ce pot contine si pipe
-}
fParser = (group `alt` makePipe)
where
makePipe = (group >*> token '|' >*> fParser) `transform` (\(a , (_, b)) -> Alt a b)
{-
Functia pentru transformarea unei expresii regulate din string in tipul de data dorit (forma intermediara)
-}
makeRegEx :: String -> Reg
makeRegEx str = result fParser str
{-
Functie ce creeaza un parser asociat tipului de data Reg
-}
parseSym :: Char -> Parser Char String
parseSym x = (token x) `transform` (\x -> [x])
makeParser :: Reg -> Parser Char String
makeParser (Sym c) = parseSym c
makeParser (Opt o) = parseOpt (makeParser o)
makeParser (Rep r) = parseRep (makeParser r)
makeParser (Seq a b) = parseSeq (makeParser a) (makeParser b)
makeParser (Alt a1 a2) = parseAlt (makeParser a1) (makeParser a2)
{-
Creere parser dintr-o secventa de parsere
-}
parseSeq :: Parser Char String -> Parser Char String -> Parser Char String
parseSeq s1 s2 = (s1 >*> s2) `transform` (\(s1,s2) -> s1 ++ s2)
{-
Creere parser asociat unei repetari de elemente
-}
parseRep :: Parser Char String -> Parser Char String
parseRep x = (maxList x) `transform` concat
{-
Creere parser pentru gasirea unui element optional
-}
parseOpt :: Parser Char String -> Parser Char String
parseOpt x = (maxOptional x) `transform` (\x -> if (null x) then "" else head x)
{-
Creere parser pentru o alternare de parsere
-}
parseAlt :: Parser Char String -> Parser Char String -> Parser Char String
parseAlt x y = x `alt` y
{-
Functiile matches si getMatches ce returneaza potrivirile pentru expresia data
-}
matches :: String -> String -> [String]
matches expression input = getMatches (makeParser (makeRegEx expression)) input
getMatches :: Parser Char String -> String -> [String]
getMatches regExParser ""
| (regExParser "" == []) = []
| otherwise = [""]
{-
Pentru orice fel de potrivire (nula, vida sau string), potrivirea se salveaza
corespunzator si se trece la verificarea potrivirilor pentru ce a ramas de
parsat.
-}
getMatches regExParser input = f (regExParser input)
where
f [] = getMatches regExParser (tail input)
f [("", (x:xs))] = "" : getMatches regExParser xs
f [(x, y)] = x : (getMatches regExParser y)
| free2tedy/PP | Tema2PP/Regexp.hs | mit | 4,661 | 43 | 14 | 1,208 | 1,680 | 915 | 765 | 72 | 3 |
{-# LANGUAGE DeriveGeneric, OverloadedStrings, TypeApplications #-}
module Main
( main
) where
import Control.Exception
import Control.Monad.State.Strict
import Data.Aeson
import Data.Int
import Data.Text.Encoding (encodeUtf8)
import Data.Time.Clock.POSIX
import Data.Time.LocalTime
import Data.UnixTime
import Dhall
import Foreign.C.Types
import Hasql.Connection
import Hasql.Session
import Hasql.Statement
import PostgreSQL.Binary.Data
import System.Environment
import System.Posix.Types
import System.Random.TF
import System.Random.TF.Gen
import System.Random.TF.Instances
import qualified Hasql.Encoders as Encoders
import qualified Hasql.Decoders as Decoders
import qualified Data.ByteString as BS
import qualified Data.Text as T
data PsqlConfig
= PsqlConfig
{ host :: Text
, port :: Natural
, user :: Text
, password :: Text
, database :: Text
} deriving (Generic)
instance FromDhall PsqlConfig
testStatement :: Statement Int64 [Int64]
testStatement = Statement sql encoder decoder True
where
sql = "SELECT ((raw -> 'time') :: bigint) AS t FROM poi_recordsb ORDER BY t LIMIT $1"
encoder = Encoders.param (Encoders.nonNullable Encoders.int8)
decoder = Decoders.rowList (Decoders.column (Decoders.nonNullable Decoders.int8))
data TestJson
= TestJson
{ tjLength :: Int
, tjNums :: [Int]
, tjMeta :: Text
} deriving (Show, Generic)
instance ToJSON TestJson
data TestRow
= TestRow
{ trId :: Int64
, trTime :: LocalTime
, trV :: Int64
, trS :: Text
, trJ :: TestJson
} deriving Show
type M = StateT TFGen IO
genChar :: M Char
genChar = (xs !!) <$> state (randomR (0, length xs - 1))
where
xs = ['a'..'z'] <> ['A' .. 'Z'] <> ['0'..'9'] <> "_+=!?"
genText :: (Int, Int) -> M Text
genText range = do
l <- state (randomR range)
T.pack <$> replicateM l genChar
genTestJson :: M TestJson
genTestJson = do
l <- state (randomR (0, 5))
xs <- replicateM l (state (randomR (-10000,10000)))
meta <- genText (7,10)
pure $ TestJson l xs meta
genEpoch :: M CTime
genEpoch = CTime <$> state (randomR (lo, hi))
where
parse = toEpochTime . parseUnixTimeGMT "%Y-%m-%d %H:%M:%S"
CTime lo = parse "2020-01-01 00:00:00"
CTime hi = parse "2020-01-01 00:00:10"
epochToLocal :: EpochTime -> LocalTime
epochToLocal =
utcToLocalTime utc
. posixSecondsToUTCTime
. realToFrac @EpochTime @POSIXTime
genTimestamp :: M (Int64, LocalTime)
genTimestamp =
(\x@(CTime t) -> (t, epochToLocal x)) <$> genEpoch
genTestRow :: M TestRow
genTestRow = do
(tsId, tsT) <- genTimestamp
TestRow tsId tsT
<$> state (randomR (100000,999999))
<*> genText (10,12)
<*> genTestJson
{-
Create a test table on demand, the schema will look like:
- id: as primary key
- time: timestamp
- v: a random integer column
- s: a random string column
- j: a column holding json AST value
- {length: <length>, nums: <array of numbers>, meta: <some random string>}
-}
testTableCreationStatement :: Statement () ()
testTableCreationStatement =
Statement sql Encoders.noParams Decoders.noResult False
where
sql =
"CREATE TABLE IF NOT EXISTS test_table (\
\ id int8 PRIMARY KEY NOT NULL,\
\ time timestamp NOT NULL,\
\ v int8 NOT NULL,\
\ s text NOT NULL,\
\ j jsonb NOT NULL\
\)"
insertStatement :: Statement TestRow ()
insertStatement =
Statement sql encoder Decoders.noResult False
where
sql =
"INSERT INTO test_table (id, time, v, s, j)\
\ VALUES ($1, $2, $3, $4, $5)\
\ ON CONFLICT DO NOTHING"
nNulParam = Encoders.param . Encoders.nonNullable
encoder =
(trId >$< nNulParam Encoders.int8)
<> (trTime >$< nNulParam Encoders.timestamp)
<> (trV >$< nNulParam Encoders.int8)
<> (trS >$< nNulParam Encoders.text)
<> ((toJSON . trJ) >$< nNulParam Encoders.jsonb)
main :: IO ()
main = do
[configPath] <- getArgs
PsqlConfig hst pt u pw db <- inputFile auto configPath
let sqlSettings =
settings
(encodeUtf8 hst)
(fromIntegral pt)
(encodeUtf8 u)
(encodeUtf8 pw)
(encodeUtf8 db)
mConn <- acquire sqlSettings
case mConn of
Left e -> do
putStrLn "error while connecting to database."
print e
Right conn -> do
putStrLn "connection acquired successfully."
g <- newTFGen
rows <- evalStateT (replicateM 16 genTestRow) g
-- main logic after connection goes here.
let sess = statement () testTableCreationStatement
mResult <- run sess conn
case mResult of
Left qe -> do
putStrLn "query error"
print qe
Right rs -> print rs
forM_ rows $ \r -> do
let sess' = statement r insertStatement
mR <- run sess' conn
case mR of
Left e -> do
putStrLn $ "Error while inserting " <> show r
print e
Right _ -> pure ()
putStrLn "releasing connection ..."
release conn
| Javran/misc | psql-playground/src/Main.hs | mit | 5,000 | 0 | 22 | 1,215 | 1,370 | 715 | 655 | 143 | 4 |
-- |
-- Module : Control.Auto.Process
-- Description : 'Auto's useful for various commonly occurring processes.
-- Copyright : (c) Justin Le 2015
-- License : MIT
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : portable
--
-- Various 'Auto's describing relationships following common processes,
-- like 'sumFrom', whose output is the cumulative sum of the input.
--
-- Also has some 'Auto' constructors inspired from digital signal
-- processing signal transformation systems and statistical models.
--
-- Note that all of these can be turned into an equivalent version acting
-- on blip streams, with 'perBlip':
--
-- @
-- 'sumFrom' n :: 'Num' a => 'Auto' m a a
-- 'perBlip' ('sumFrom' n) :: 'Num' a => 'Auto' m ('Blip' a) ('Blip' a)
-- @
--
module Control.Auto.Process (
-- * Numerical
sumFrom
, sumFrom_
, sumFromD
, sumFromD_
, productFrom
, productFrom_
, deltas
, deltas_
-- ** Numerical signal transformations/systems
, movingAverage
, movingAverage_
, impulseResponse
, impulseResponse_
, autoRegression
, autoRegression_
, arma
, arma_
-- * Monoidal/Semigroup
, mappender
, mappender_
, mappendFrom
, mappendFrom_
) where
import Control.Auto.Core
import Control.Auto.Interval
import Data.Semigroup
import Data.Serialize
-- | The stream of outputs is the cumulative/running sum of the inputs so
-- far, starting with an initial count.
--
-- The first output takes into account the first input. See 'sumFromD' for
-- a version where the first output is the initial count itself.
--
-- prop> sumFrom x0 = accum (+) x0
sumFrom :: (Serialize a, Num a)
=> a -- ^ initial count
-> Auto m a a
sumFrom = accum (+)
-- | The non-resuming/non-serializing version of 'sumFrom'.
sumFrom_ :: Num a
=> a -- ^ initial count
-> Auto m a a
sumFrom_ = accum_ (+)
-- | Like 'sumFrom', except the first output is the starting count.
--
-- >>> let a = sumFromD 5
-- >>> let (y1, a') = stepAuto' a 10
-- >>> y1
-- 5
-- >>> let (y2, _ ) = stepAuto' a' 3
-- >>> y2
-- 10
--
-- >>> streamAuto' (sumFrom 0) [1..10]
-- [1,3,6,10,15,21,28,36,45,55]
-- >>> streamAuto' (sumFromD 0) [1..10]
-- [0,1,3,6,10,15,21,28,36,45]
--
-- It's 'sumFrom', but "delayed".
--
-- Useful for recursive bindings, where you need at least one value to be
-- able to produce its "first output" without depending on anything else.
--
-- prop> sumFromD x0 = sumFrom x0 . delay 0
-- prop> sumFromD x0 = delay x0 . sumFrom x0
sumFromD :: (Serialize a, Num a)
=> a -- ^ initial count
-> Auto m a a
sumFromD = accumD (+)
-- | The non-resuming/non-serializing version of 'sumFromD'.
sumFromD_ :: Num a
=> a -- ^ initial count
-> Auto m a a
sumFromD_ = accumD_ (+)
-- | The output is the running/cumulative product of all of the inputs so
-- far, starting from an initial product.
--
-- prop> productFrom x0 = accum (*) x0
productFrom :: (Serialize a, Num a)
=> a -- ^ initial product
-> Auto m a a
productFrom = accum (*)
-- | The non-resuming/non-serializing version of 'productFrom'.
productFrom_ :: Num a
=> a -- ^ initial product
-> Auto m a a
productFrom_ = accum_ (*)
-- | The output is the the difference between the input and the previously
-- received input.
--
-- First result is a 'Nothing', so you can use '<|!>' or 'fromInterval' or
-- 'fromMaybe' to get a "default first value".
--
-- >>> streamAuto' deltas [1,6,3,5,8]
-- >>> [Nothing, Just 5, Just (-3), Just 2, Just 3]
--
-- Usage with '<|!>':
--
-- >>> let a = deltas <|!> pure 100
-- >>> streamAuto' (deltas <|!> pure 100) [1,6,3,5,8]
-- [100, 5, -3, 2, 3]
--
-- Usage with 'fromMaybe':
--
-- >>> streamAuto' (fromMaybe 100 <$> deltas) [1,6,3,5,8]
-- [100, 5, -3, 2, 3]
--
deltas :: (Serialize a, Num a) => Interval m a a
deltas = mkState _deltasF Nothing
-- | The non-resuming/non-serializing version of 'deltas'.
deltas_ :: Num a => Interval m a a
deltas_ = mkState_ _deltasF Nothing
_deltasF :: Num a => a -> Maybe a -> (Maybe a, Maybe a)
_deltasF x s = case s of
Nothing -> (Nothing , Just x)
Just prev -> (Just (x - prev), Just x)
-- | The output is the running/cumulative 'mconcat' of all of the input
-- seen so far, starting with 'mempty'.
--
-- >>> streamauto' mappender . map Last $ [Just 4, Nothing, Just 2, Just 3]
-- [Last (Just 4), Last (Just 4), Last (Just 2), Last (Just 3)]
-- >>> streamAuto' mappender ["hello","world","good","bye"]
-- ["hello","helloworld","helloworldgood","helloworldgoodbye"]
--
-- prop> mappender = accum mappend mempty
mappender :: (Serialize a, Monoid a) => Auto m a a
mappender = accum mappend mempty
-- | The non-resuming/non-serializing version of 'mappender'.
mappender_ :: Monoid a => Auto m a a
mappender_ = accum_ mappend mempty
-- | The output is the running '<>'-sum ('mappend' for 'Semigroup') of all
-- of the input values so far, starting with a given starting value.
-- Basically like 'mappender', but with a starting value.
--
-- >>> streamAuto' (mappendFrom (Max 0)) [Max 4, Max (-2), Max 3, Max 10]
-- [Max 4, Max 4, Max 4, Max 10]
--
-- prop> mappendFrom m0 = accum (<>) m0
mappendFrom :: (Serialize a, Semigroup a)
=> a -- ^ initial value
-> Auto m a a
mappendFrom = accum (<>)
-- | The non-resuming/non-serializing version of 'mappender'.
mappendFrom_ :: Semigroup a
=> a -- ^ initial value
-> Auto m a a
mappendFrom_ = accum_ (<>)
-- | The output is the sum of the past inputs, multiplied by a moving
-- window of weights.
--
-- For example, if the last received inputs are @[1,2,3,4]@ (from most
-- recent to oldest), and the window of weights is @[2,0.5,4]@, then the
-- output will be @1*2 + 0.5*2 + 4*3@, or @15@. (The weights are assumed
-- to be zero past the end of the weight window)
--
-- The immediately received input is counted as a part of the history.
--
-- Mathematically,
-- @y_n = w_0 * x_(n-0) + w_1 + x_(n-1) + w_2 * x_(n-1) + ...@, for all
-- @w@s in the weight window, where the first item is @w_0@. @y_n@ is the
-- @n@th output, and @x_n@ is the @n@th input.
--
-- Note that this serializes the history of the input...or at least the
-- history as far back as the entire window of weights. (A weight list of
-- five items will serialize the past five received items) If your weight
-- window is very long (or infinite), then serializing is a bad idea!
--
-- The second parameter is a list of a "starting history", or initial
-- conditions, to be used when the actual input history isn't long enough.
-- If you want all your initial conditions/starting history to be @0@, just
-- pass in @[]@.
--
-- Minus serialization, you can implement 'sumFrom' as:
--
-- @
-- sumFrom n = movingAverage (repeat 1) [n]
-- @
--
-- And you can implement a version of 'deltas' as:
--
-- @
-- deltas = movingAverage [1,-1] []
-- @
--
-- It behaves the same, except the first step outputs the initially
-- received value. So it's realy a bit like
--
-- @
-- (movingAverage [1,-1] []) == (deltas <|!> id)
-- @
--
-- Where for the first step, the actual input is used instead of the delta.
--
-- Name comes from the statistical model.
--
movingAverage :: (Num a, Serialize a)
=> [a] -- ^ weights to apply to previous inputs,
-- from most recent
-> [a] -- ^ starting history/initial conditions
-> Auto m a a
movingAverage weights = mkState (_movingAverageF weights)
-- | The non-serializing/non-resuming version of 'movingAverage'.
movingAverage_ :: Num a
=> [a] -- ^ weights to apply to previous inputs,
-- from most recent
-> [a] -- ^ starting history/initial conditions
-> Auto m a a
movingAverage_ weights = mkState_ (_movingAverageF weights)
_movingAverageF :: Num a => [a] -> a -> [a] -> (a, [a])
_movingAverageF weights x hist = (sum (zipWith (*) weights hist'), hist')
where
hist' = zipWith const (x:hist) weights
-- | Any linear time independent stream transformation can be encoded by
-- the response of the transformation when given @[1,0,0,0...]@, or @1
-- : 'repeat' 0@. So, given an "LTI" 'Auto', if you feed it @1 : 'repeat'
-- 0@, the output is what is called an "impulse response function".
--
-- For any "LTI" 'Auto', we can reconstruct the behavior of the original
-- 'Auto' given its impulse response. Give 'impulseResponse' an impulse
-- response, and it will recreate/reconstruct the original 'Auto'.
--
-- >>> let getImpulseResponse a = streamAuto' a (1 : repeat 0)
-- >>> let sumFromImpulseResponse = getImpulseResponse (sumFrom 0)
-- >>> streamAuto' (sumFrom 0) [1..10]
-- [1,3,6,10,15,21,28,36,45,55]
-- >>> streamAuto' (impulseResponse sumFromImpulseResponse) [1..10]
-- [1,3,6,10,15,21,28,36,45,55]
--
-- Use this function to create an LTI system when you know its impulse
-- response.
--
-- >>> take 10 . streamAuto' (impulseResponse (map (2**) [0,-1..])) $ repeat 1
-- [1.0,1.5,1.75,1.875,1.9375,1.96875,1.984375,1.9921875,1.99609375,1.998046875]
--
-- All impulse response after the end of the given list is assumed to be
-- zero.
--
-- Mathematically,
-- @y_n = h_0 * x_(n-0) + h_1 + x_(n-1) + h_2 * x_(n-1) + ...@, for all
-- @h_n@ in the input response, where the first item is @h_0@.
--
-- Note that when this is serialized, it must serialize a number of input
-- elements equal to the length of the impulse response list...so if you give
-- an infinite impulse response, you might want to use 'impulseResponse_',
-- or not serialize.
--
-- By the way, @'impulseResponse' ir == 'movingAverage' ir []@.
--
impulseResponse :: (Num a, Serialize a)
=> [a] -- ^ the impulse response function
-> Auto m a a
impulseResponse weights = movingAverage weights []
-- | The non-serializing/non-resuming version of 'impulseResponse'.
impulseResponse_ :: Num a
=> [a] -- ^ the impulse response function
-> Auto m a a
impulseResponse_ weights = movingAverage_ weights []
-- | The output is the sum of the past outputs, multiplied by a moving
-- window of weights. Ignores all input.
--
-- For example, if the last outputs are @[1,2,3,4]@ (from most recent to
-- oldest), and the window of weights is @[2,0.5,4]@, then the output will
-- be @1*2 + 0.5*2 + 4*3@, or @15@. (The weights are assumed to be zero
-- past the end of the weight window)
--
-- Mathematically, @y_n = w_1 * y_(n-1) + w_2 * y_(n-2) + ...@, for all @w@
-- in the weight window, where the first item is @w_1@.
--
-- Note that this serializes the history of the outputs...or at least the
-- history as far back as the entire window of weights. (A weight list of
-- five items will serialize the past five outputted items) If your weight
-- window is very long (or infinite), then serializing is a bad idea!
--
-- The second parameter is a list of a "starting history", or initial
-- conditions, to be used when the actual output history isn't long enough.
-- If you want all your initial conditions/starting history to be @0@, just
-- pass in @[]@.
--
-- You can use this to implement any linear recurrence relationship, like
-- he fibonacci sequence:
--
-- >>> evalAutoN' 10 (autoRegression [1,1] [1,1]) ()
-- [2,3,5,8,13,21,34,55,89,144]
-- >>> evalAutoN' 10 (fromList [1,1] --> autoRegression [1,1] [1,1]) ()
-- [1,1,2,3,5,8,13,21,34,55]
--
-- Which is 1 times the previous value, plus one times the value before
-- that.
--
-- You can create a series that doubles by having it be just twice the
-- previous value:
--
-- >>> evalAutoN' 10 (autoRegression [2] [1]) ()
-- [2,,4,8,16,32,64,128,256,512,1024]
--
-- Name comes from the statistical model.
--
autoRegression :: (Num b, Serialize b)
=> [b] -- ^ weights to apply to previous outputs,
-- from most recent
-> [b] -- ^ starting history/initial conditions
-> Auto m a b
autoRegression weights = mkState (const (_autoRegressionF weights))
-- | The non-serializing/non-resuming version of 'autoRegression'.
autoRegression_ :: Num b
=> [b] -- ^ weights to apply to previous outputs,
-- from most recent
-> [b] -- ^ starting history/initial conditions
-> Auto m a b
autoRegression_ weights = mkState_ (const (_autoRegressionF weights))
_autoRegressionF :: Num b => [b] -> [b] -> (b, [b])
_autoRegressionF weights hist = (result, hist')
where
result = sum (zipWith (*) weights hist)
hist' = zipWith const (result:hist) weights
-- | A combination of 'autoRegression' and 'movingAverage'. Inspired by
-- the statistical model.
--
-- Mathematically:
--
-- @
-- y_n = wm_0 * x_(n-0) + wm_1 * x_(n-1) + wm_2 * x_(n-2) + ...
-- + wa_1 * y_(n-1) + wa_2 * y_(n-1) + ...
-- @
--
-- Where @wm_n@s are all of the "moving average" weights, where the first
-- weight is @wm_0@, and @wa_n@s are all of the "autoregression" weights,
-- where the first weight is @wa_1@.
arma :: (Num a, Serialize a)
=> [a] -- ^ weights for the "auto-regression" components
-> [a] -- ^ weights for the "moving average" components
-> [a] -- ^ an "initial history" of outputs, recents first
-> [a] -- ^ an "initial history" of inputs, recents first
-> Auto m a a
arma arWeights maWeights arHist maHist =
mkState (_armaF arWeights maWeights) (arHist, maHist)
-- | The non-serializing/non-resuming version of 'arma'.
arma_ :: Num a
=> [a] -- ^ weights for the "auto-regression" components
-> [a] -- ^ weights for the "moving average" components
-> [a] -- ^ an "initial history" of outputs, recents first
-> [a] -- ^ an "initial history" of inputs, recents first
-> Auto m a a
arma_ arWeights maWeights arHist maHist =
mkState_ (_armaF arWeights maWeights) (arHist, maHist)
_armaF :: Num a => [a] -> [a] -> a -> ([a], [a]) -> (a, ([a], [a]))
_armaF arWeights maWeights x (arHist, maHist) = (y, (arHist', maHist'))
where
maHist' = zipWith const (x:maHist) maWeights
ma = sum (zipWith (*) maWeights maHist')
ar = sum (zipWith (*) arWeights arHist)
y = ar + ma
arHist' = zipWith const (y:arHist) arWeights
| mstksg/auto | src/Control/Auto/Process.hs | mit | 14,546 | 0 | 12 | 3,423 | 1,740 | 1,058 | 682 | 127 | 2 |
module EasySDL.Draw where
import Data.StateVar
import qualified SDL.Video.Renderer as R
import GHC.Word
import Linear.V4
white :: V4 Word8
white = V4 0xFF 0xFF 0xFF 0xFF
red :: V4 Word8
red = V4 0xFF 0x00 0x00 0xFF
green :: V4 Word8
green = V4 0x00 0x80 0x00 0xFF
blue :: V4 Word8
blue = V4 0x00 0x00 0xFF 0xFF
yellow :: V4 Word8
yellow = V4 0xFF 0xFF 0x00 0xFF
black :: V4 Word8
black = V4 0x00 0x00 0x00 0xFF
pink :: V4 Word8
pink = V4 0xFF 0x3E 0x96 0xFF
cyan :: V4 Word8
cyan = V4 0x00 0xFF 0xFF 0xFF
darkBlue :: V4 Word8
darkBlue = V4 0x00 0x00 0xA0 0xFF
lightBlue :: V4 Word8
lightBlue = V4 0xAD 0xD8 0xE6 0xFF
purple :: V4 Word8
purple = V4 0x80 0x00 0x80 0xFF
magenta :: V4 Word8
magenta = V4 0xFF 0x00 0xFF 0xFF
silver :: V4 Word8
silver = V4 0xC0 0xC0 0xC0 0xFF
grey :: V4 Word8
grey = V4 0x80 0x80 0x80 0xFF
orange :: V4 Word8
orange = V4 0xFF 0xA5 0x00 0xFF
brown :: V4 Word8
brown = V4 0xA5 0x2A 0x2A 0xFF
maroon :: V4 Word8
maroon = V4 0x80 0x00 0x00 0xFF
lime :: V4 Word8
lime = V4 0x00 0xFF 0x00 0xFF
olive :: V4 Word8
olive = V4 0x80 0x80 0x00 0xFF
clearScreen :: R.Renderer -> IO ()
clearScreen renderer = do
setColor renderer white
R.clear renderer
setColor :: R.Renderer -> V4 Word8 -> IO ()
setColor r c = R.rendererDrawColor r $= c
withBlankScreen :: R.Renderer -> IO () -> IO ()
withBlankScreen r operation = do
clearScreen r
operation
R.present r
| ublubu/shapes | shapes-demo/src/EasySDL/Draw.hs | mit | 1,404 | 0 | 8 | 307 | 582 | 290 | 292 | 54 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module UserSpec where
import App
import Server
import User
import Util
import Data.Aeson hiding (json)
import qualified Data.ByteString.Char8 as BS
import qualified Data.Map as M
import Data.Maybe
import Data.Monoid
import Data.Text
import Network.Wai.Test
import Test.Hspec
import Test.Hspec.Wai
import Test.Hspec.Wai.JSON
import Test.QuickCheck
spec :: Spec
spec = do
with setup $
describe "server" $ do
it "should create a user" $
postJSON "/user" [json|{email:"[email protected]", password:"hunter2"}|] `shouldRespondWith` 201
it "should not allow malformed registrations" $
postJSON "/user" [json|[1,2,3]|] `shouldRespondWith` 400
it "should not allow duplicate emails" $ do
postJSON "/user" [json|{email:"[email protected]", password:"hunter2"}|] `shouldRespondWith` 201
postJSON "/user" [json|{email:"[email protected]", password:"hunter2"}|] `shouldRespondWith` 409
it "should allow users to login" $ do
postJSON "/user" [json|{email:"[email protected]", password:"hunter2"}|] `shouldRespondWith` 201
postJSONHeaders "/user/[email protected]/token" [("Authorization", "Simple hunter2")] "" `shouldRespondWith` 201
it "should prevent unauthenticated users from logging in" $ do
postJSON "/user" [json|{email:"[email protected]", password:"hunter2"}|] `shouldRespondWith` 201
postJSON "/user/[email protected]/token" "" `shouldRespondWith` 401
postJSONHeaders "/user/[email protected]/token" [("Authorization", "Simple hunter3")] "" `shouldRespondWith` 403
it "should update users" $ do
resp <- postJSON "/user" [json|{email:"[email protected]", password:"hunter2"}|]
let tokenJSON = simpleBody resp
token = BS.pack . fromMaybe ("dummy token" :: String) $ decode tokenJSON >>= M.lookup ("token" :: String)
pure resp `shouldRespondWith` 201
resp' <- putJSONHeaders "/user/[email protected]" [("Authorization", "Bearer " <> token)] [json|{age:23}|]
pure resp `shouldRespondWith` 201
describe "email" $ do
it "should convert between text and email" $
property $ \email@(Email local server) ->
not ("@" `isInfixOf` local) && not ("@" `isInfixOf` server) ==>
toEmail (fromEmail email) == Just email
it "should fail to convert non-emails" $ do
toEmail "" `shouldBe` Nothing
toEmail "@" `shouldBe` Nothing
toEmail "a@" `shouldBe` Nothing
toEmail "@a" `shouldBe` Nothing
toEmail "a" `shouldBe` Nothing
it "decodes JSON" $ do
decode "" `shouldBe` (Nothing :: Maybe Email)
decode "\"ben@test\"" `shouldBe` Just (Email "ben" "test")
decode "\"\"" `shouldBe` (Nothing :: Maybe Email)
decode "{\"email\":\"ben@test\"}" `shouldBe` (Nothing :: Maybe Email)
it "should show" $
property $ \email@(Email local server) ->
not ("@" `isInfixOf` local) && not ("@" `isInfixOf` server) ==>
show email == unpack local ++ "@" ++ unpack server
instance Arbitrary Email where
arbitrary = do
NonEmpty local <- arbitrary
NonEmpty server <- arbitrary
return $ Email (pack local) (pack server)
| benweitzman/PhoBuddies-Servant | test/UserSpec.hs | mit | 3,511 | 0 | 20 | 964 | 862 | 457 | 405 | 68 | 1 |
{-|
Module : Control.Monad.Bayes.Inference.SMC
Description : Sequential Monte Carlo (SMC)
Copyright : (c) Adam Scibior, 2015-2020
License : MIT
Maintainer : [email protected]
Stability : experimental
Portability : GHC
Sequential Monte Carlo (SMC) sampling.
Arnaud Doucet and Adam M. Johansen. 2011. A tutorial on particle filtering and smoothing: fifteen years later. In /The Oxford Handbook of Nonlinear Filtering/, Dan Crisan and Boris Rozovskii (Eds.). Oxford University Press, Chapter 8.
-}
module Control.Monad.Bayes.Inference.SMC (
sir,
smcMultinomial,
smcSystematic,
smcMultinomialPush,
smcSystematicPush
) where
import Control.Monad.Bayes.Class
import Control.Monad.Bayes.Population
import Control.Monad.Bayes.Sequential as Seq
-- | Sequential importance resampling.
-- Basically an SMC template that takes a custom resampler.
sir :: Monad m
=> (forall x. Population m x -> Population m x) -- ^ resampler
-> Int -- ^ number of timesteps
-> Int -- ^ population size
-> Sequential (Population m) a -- ^ model
-> Population m a
sir resampler k n = sis resampler k . Seq.hoistFirst (spawn n >>)
-- | Sequential Monte Carlo with multinomial resampling at each timestep.
-- Weights are not normalized.
smcMultinomial :: MonadSample m
=> Int -- ^ number of timesteps
-> Int -- ^ number of particles
-> Sequential (Population m) a -- ^ model
-> Population m a
smcMultinomial = sir resampleMultinomial
-- | Sequential Monte Carlo with systematic resampling at each timestep.
-- Weights are not normalized.
smcSystematic :: MonadSample m
=> Int -- ^ number of timesteps
-> Int -- ^ number of particles
-> Sequential (Population m) a -- ^ model
-> Population m a
smcSystematic = sir resampleSystematic
-- | Sequential Monte Carlo with multinomial resampling at each timestep.
-- Weights are normalized at each timestep and the total weight is pushed
-- as a score into the transformed monad.
smcMultinomialPush :: MonadInfer m
=> Int -- ^ number of timesteps
-> Int -- ^ number of particles
-> Sequential (Population m) a -- ^ model
-> Population m a
smcMultinomialPush = sir (pushEvidence . resampleMultinomial)
-- | Sequential Monte Carlo with systematic resampling at each timestep.
-- Weights are normalized at each timestep and the total weight is pushed
-- as a score into the transformed monad.
smcSystematicPush :: MonadInfer m
=> Int -- ^ number of timesteps
-> Int -- ^ number of particles
-> Sequential (Population m) a -- ^ model
-> Population m a
smcSystematicPush = sir (pushEvidence . resampleSystematic)
| adscib/monad-bayes | src/Control/Monad/Bayes/Inference/SMC.hs | mit | 2,852 | 0 | 12 | 720 | 383 | 212 | 171 | -1 | -1 |
module TestLabel (
prop_domination_reflexive,
prop_domination_antisymmetric,
prop_domination_transitive,
prop_noBetter,
prop_domination_total
) where
import Label
import Data.Set as Set
import Test.QuickCheck
import TestModel
-- LABELS
-- Labels are made to store a partial solution
-- to the problem
-- They contain the set of users allocated along
-- the current path
instance Arbitrary Label where
arbitrary = do
sc <- arbitrary
us <- arbitrary
return (Label sc us)
-- Checking that domination is an ordering relation
prop_domination_reflexive x = x `dominates` x
prop_domination_antisymmetric x y =
x /= y ==> x `dominates` y || y `dominates` x
-- x `dominates` y && y `dominates` x ==> x == y
prop_domination_transitive x y z = x `dominates` y && y `dominates` z ==> x `dominates` z
-- Also checking that domination is a total order
prop_domination_total x y = x `dominates` y || y `dominates` x
prop_noBetter :: Set Label -> Label -> Bool
prop_noBetter s l =
let b1 = not (any (\h -> h `dominates` l) s)
-- b2 = Set.null s || (l `dominates` (findMax s))
b2 = all (\h -> not (h `dominates` l)) s
in b1 == b2
-- Labels are a monoids because Floats are monoids under sum and
-- set are monoids under union
| Vetii/SCFDMA | test/TestLabel.hs | mit | 1,310 | 0 | 14 | 308 | 299 | 171 | 128 | 25 | 1 |
cutBrackets :: (Show a, Show b) => [(a, b)] -> String
cutBrackets (x:xs)
| null xs = show (fst x) ++ " " ++ show (snd x)
| otherwise = show (fst x) ++ " " ++ show (snd x) ++ "\n" ++ cutBrackets xs
func :: Floating a => a -> a
func x = x
dxList :: (Enum a, Floating a) => a -> a -> [a]
dxList dx xmax = [0.0, dx..xmax]
odeEulerWorker :: Floating a => (a -> a) -> a -> [a] -> [(a, a)]
odeEulerWorker f yn (x:xs)
| null xs = [(x, yn)]
| otherwise = (x, yn) : odeEulerWorker f (yn + dx * f yn) xs
where
dx = (head xs) - x
odeEuler :: (Enum a, Floating a) => (a -> a) -> a -> a -> a -> [(a, a)]
odeEuler f yinit dx xmax = odeEulerWorker f yinit $ dxList dx xmax
main = do
putStrLn $ cutBrackets $ odeEuler func 1.0 0.01 10.0
| mino2357/Hello_Haskell | test/ode.hs | mit | 749 | 0 | 12 | 195 | 445 | 228 | 217 | 17 | 1 |
#!/usr/bin/env runhaskell
{-# LANGUAGE OverloadedStrings #-}
import Turtle
main :: IO ()
main = do
stdout (runWatch $ findSrc)
findSrc :: Shell Text
findSrc = inproc "find" ["./src"] ""
runWatch :: Shell Text -> Shell Text
runWatch s = inproc "entr" ["cabal", "build"] s
| dzotokan/minions-api | scripts/watch.hs | mit | 278 | 0 | 9 | 51 | 93 | 48 | 45 | 9 | 1 |
-- Same as 035_delay_rec, but using combLoop instead.
module T where
import Tests.Basis
c = proc a ->
(| combLoop (\y ->
do x <- (| delayAC (falseA -< ()) (returnA -< y) |)
y <- orA -< (a, x)
returnA -< (x, y)) |)
c' = proc a ->
(| combLoop (\x ->
do x' <- (| delayAC (falseA -< ()) (orA -< (a, x)) |)
returnA -< (x', x')) |)
c'' = proc a ->
(| combLoop (\x ->
do x' <- (| delayAC (falseA -< ()) (orA -< (x, a)) |)
returnA -< (x', x')) |)
-- Constructivity is OK on this one.
c''' = proc () ->
(| combLoop (\x ->
do x' <- (| delayAC (falseA -< ()) (notA -< x) |)
returnA -< (x', x')) |)
test_constructive = isJust (isConstructive c)
test_constructive' = isJust (isConstructive c')
test_constructive'' = isJust (isConstructive c'')
test_constructive''' = isJust (isConstructive c''')
| peteg/ADHOC | Tests/02_SequentialCircuits/036_delay_combLoop.hs | gpl-2.0 | 936 | 20 | 17 | 305 | 410 | 218 | 192 | -1 | -1 |
module Access.System.Timeout
( module System.Timeout
, TimeoutAccess(..)
) where
import System.Timeout
import Access.Core
class Access io => TimeoutAccess io where
timeout' :: Int -> IO a -> io (Maybe a)
instance TimeoutAccess IO where
-- |Wrap an 'IO' computation to time out and return @Nothing@ in case no result
-- is available within @n@ microseconds (@1\/10^6@ seconds). In case a result
-- is available before the timeout expires, @Just a@ is returned. A negative
-- timeout interval means \"wait indefinitely\". When specifying long timeouts,
-- be careful not to exceed @maxBound :: Int@.
--
-- The design of this combinator was guided by the objective that @timeout n f@
-- should behave exactly the same as @f@ as long as @f@ doesn't time out. This
-- means that @f@ has the same 'myThreadId' it would have without the timeout
-- wrapper. Any exceptions @f@ might throw cancel the timeout and propagate
-- further up. It also possible for @f@ to receive exceptions thrown to it by
-- another thread.
--
-- A tricky implementation detail is the question of how to abort an @IO@
-- computation. This combinator relies on asynchronous exceptions internally.
-- The technique works very well for computations executing inside of the
-- Haskell runtime system, but it doesn't work at all for non-Haskell code.
-- Foreign function calls, for example, cannot be timed out with this
-- combinator simply because an arbitrary C function cannot receive
-- asynchronous exceptions. When @timeout@ is used to wrap an FFI call that
-- blocks, no timeout event can be delivered until the FFI call returns, which
-- pretty much negates the purpose of the combinator. In practice, however,
-- this limitation is less severe than it may sound. Standard I\/O functions
-- like 'System.IO.hGetBuf', 'System.IO.hPutBuf', Network.Socket.accept, or
-- 'System.IO.hWaitForInput' appear to be blocking, but they really don't
-- because the runtime system uses scheduling mechanisms like @select(2)@ to
-- perform asynchronous I\/O, so it is possible to interrupt standard socket
-- I\/O or file I\/O using this combinator.
timeout' = timeout
| bheklilr/base-io-access | Access/System/Timeout.hs | gpl-2.0 | 2,289 | 0 | 11 | 502 | 114 | 75 | 39 | 9 | 0 |
{- hpodder component
Copyright (C) 2006-2007 John Goerzen <[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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
module Commands.ImportIpodder(cmd, cmd_worker) where
import Utils
import System.Log.Logger
import DB
import Download
import FeedParser
import Types
import Text.Printf
import Config
import Database.HDBC
import Control.Monad
import Utils
import System.Console.GetOpt
import System.Console.GetOpt.Utils
import qualified Commands.Update
import System.FilePath
import Data.List
import Data.String.Utils
import System.Directory
import Control.Exception
d = debugM "import-ipodder"
i = infoM "import-ipodder"
w = warningM "import-ipodder"
cmd = simpleCmd "import-ipodder"
"Import feeds and history from ipodder or castpodder"
""
[Option "" ["from"] (ReqArg (stdRequired "from") "PATH")
"Location of ipodder data directory (default ~/.ipodder)"]
cmd_worker
cmd_worker gi (args, []) = lock $
do ipodderpath <- case lookup "from" args of
Nothing -> do getAppUserDataDirectory "ipodder"
Just x -> return x
i "Scanning ipodder podcast list and adding new podcasts to hpodder..."
pc <- newpodcasts ipodderpath gi
i $ printf "Added %d podcasts" (length pc)
i "Loading new feeds..."
Commands.Update.cmd_worker gi ([], map (show . castid) pc)
commit (gdbh gi)
i "Now importing iPodder history..."
history <- loadhistory ipodderpath
prochistory gi pc history
commit (gdbh gi)
i "Done."
cmd_worker _ _ =
fail "Unknown arg to import-ipodder; see hpodder import-ipodder --help"
prochistory _ [] _ = return ()
prochistory gi (pc:xs) history =
do episodes <- getEpisodes (gdbh gi) pc
-- Force episodes to be consumed before proceeding
evaluate (length episodes)
d $ printf "Considering %d episode(s) for podcast %d" (length episodes)
(castid pc)
mapM_ procep episodes
prochistory gi xs history
where procep ep =
if (snd . splitFileName . epurl $ ep) `elem` history
&& (epstatus ep) `elem` [Pending, Error]
then do d $ printf "Adjusting episode %d" (epid ep)
updateEpisode (gdbh gi) (ep {epstatus = Skipped})
return ()
else return ()
newpodcasts id gi =
do favorites <- readFile (id ++ "/favorites.txt")
let newurls = filter (not . isPrefixOf "#") . map strip . lines
$ favorites
existinglist <- getPodcasts (gdbh gi)
let existingurls = map feedurl existinglist
let urlstoadd = filter (\newurl -> not (newurl `elem` existingurls))
newurls
let podcaststoadd = map (\url -> Podcast {castid = 0,
castname = "",
feedurl = url,
pcenabled = PCEnabled,
lastupdate = Nothing,
lastattempt = Nothing,
failedattempts = 0}) urlstoadd
newpcs <- mapM (addPodcast (gdbh gi)) podcaststoadd
commit (gdbh gi)
return newpcs
loadhistory :: String -> IO [String]
loadhistory id =
do historyfile <- readFile (id ++ "/history.txt")
return $ filter (/= "") . map strip . lines $ historyfile
| jgoerzen/hpodder | Commands/ImportIpodder.hs | gpl-2.0 | 4,200 | 0 | 16 | 1,310 | 910 | 457 | 453 | 83 | 2 |
{-# LANGUAGE NoImplicitPrelude, DeriveGeneric, TemplateHaskell, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings #-}
module Graphics.UI.Bottle.Animation
( R, Size, Layer
, Image(..), iUnitImage, iRect
, Frame(..), frameImagesMap, unitImages
, draw, nextFrame, mapIdentities
, unitSquare, unitHStripedSquare, emptyRectangle
, backgroundColor
, translate, scale, layers
, unitIntoRect
, simpleFrame, sizedFrame
, module Graphics.UI.Bottle.Animation.Id
) where
import Prelude.Compat
import Control.Applicative (liftA2)
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Control.Lens.Tuple
import Control.Monad (void)
import qualified Data.ByteString.Char8 as SBS
import qualified Data.List as List
import Data.List.Utils (groupOn, sortOn)
import Data.Map (Map, (!))
import qualified Data.Map.Strict as Map
import Data.Maybe (isJust)
import Data.Vector.Vector2 (Vector2(..))
import qualified Data.Vector.Vector2 as Vector2
import GHC.Generics (Generic)
import Graphics.DrawingCombinators (R, (%%))
import qualified Graphics.DrawingCombinators as Draw
import qualified Graphics.DrawingCombinators.Utils as DrawUtils
import Graphics.UI.Bottle.Animation.Id
import Graphics.UI.Bottle.Rect (Rect(Rect))
import qualified Graphics.UI.Bottle.Rect as Rect
type Layer = Int
type Size = Vector2 R
data Image = Image
{ _iLayer :: Layer
, _iUnitImage :: Draw.Image ()
-- iUnitImage always occupies (0,0)..(1,1),
-- the translation/scaling occurs when drawing
, _iRect :: Rect
} deriving (Generic)
Lens.makeLenses ''Image
newtype Frame = Frame
{ _frameImagesMap :: Map AnimId [Image]
} deriving (Generic)
Lens.makeLenses ''Frame
{-# INLINE images #-}
images :: Lens.Traversal' Frame Image
images = frameImagesMap . Lens.traversed . Lens.traversed
{-# INLINE layers #-}
layers :: Lens.Traversal' Frame Layer
layers = images . iLayer
{-# INLINE unitImages #-}
unitImages :: Lens.Traversal' Frame (Draw.Image ())
unitImages = images . iUnitImage
simpleFrame :: AnimId -> Draw.Image () -> Frame
simpleFrame animId image =
Frame $ Map.singleton animId [Image 0 image (Rect 0 1)]
sizedFrame :: AnimId -> Size -> Draw.Image () -> Frame
sizedFrame animId size =
scale size .
simpleFrame animId .
(DrawUtils.scale (1 / size) %%)
instance Monoid Frame where
mempty = Frame mempty
mappend (Frame m0) (Frame m1) = Frame $ Map.unionWith (++) m0 m1
unitX :: Draw.Image ()
unitX = void $ mconcat
[ Draw.line (0, 0) (1, 1)
, Draw.line (1, 0) (0, 1)
]
red :: Draw.Color
red = Draw.Color 1 0 0 1
draw :: Frame -> Draw.Image ()
draw frame =
frame
^. frameImagesMap
& Map.elems
<&> markConflicts
& concat
<&> posImage
& sortOn (^. _1) <&> snd
& mconcat
where
redX = Draw.tint red unitX
markConflicts imgs@(_:_:_) =
imgs <&> iUnitImage %~ mappend redX
markConflicts imgs = imgs
posImage (Image layer img rect) =
( layer
, DrawUtils.translate (rect ^. Rect.topLeft) %%
DrawUtils.scale (rect ^. Rect.size) %%
img
)
prefixRects :: Map AnimId Image -> Map AnimId Rect
prefixRects src =
Map.fromList . filter (not . null . fst) . map perGroup $ groupOn fst $ sortOn fst prefixItems
where
perGroup xs =
(fst (head xs), List.foldl1' joinRects (map snd xs))
prefixItems = do
(key, img) <- Map.toList src
prefix <- List.inits key
return (prefix, img ^. iRect)
joinRects a b =
Rect {
Rect._topLeft = tl,
Rect._size = br - tl
}
where
tl =
liftA2 min (a ^. Rect.topLeft) (b ^. Rect.topLeft)
br =
liftA2 max (a ^. Rect.bottomRight) (b ^. Rect.bottomRight)
findPrefix :: Ord a => [a] -> Map [a] b -> Maybe [a]
findPrefix key dict =
List.find (`Map.member` dict) . reverse $ List.inits key
relocateSubRect :: Rect -> Rect -> Rect -> Rect
relocateSubRect srcSubRect srcSuperRect dstSuperRect =
Rect
{ Rect._topLeft =
dstSuperRect ^. Rect.topLeft +
sizeRatio *
(srcSubRect ^. Rect.topLeft -
srcSuperRect ^. Rect.topLeft)
, Rect._size = sizeRatio * srcSubRect ^. Rect.size
}
where
sizeRatio =
dstSuperRect ^. Rect.size /
fmap (max 1) (srcSuperRect ^. Rect.size)
isVirtuallySame :: Frame -> Frame -> Bool
isVirtuallySame (Frame a) (Frame b) =
Map.keysSet a == Map.keysSet b &&
diffRects < equalityThreshold
where
equalityThreshold = 0.2
diffRects =
maximum . Map.elems $
Map.intersectionWith subtractRect
(rectMap a) (rectMap b)
subtractRect ra rb =
Vector2.uncurry max $
liftA2 max
(abs (ra ^. Rect.topLeft - rb ^. Rect.topLeft))
(abs (ra ^. Rect.bottomRight - rb ^. Rect.bottomRight))
rectMap = Map.mapMaybe (^? Lens.traversed . iRect)
mapIdentities :: (AnimId -> AnimId) -> Frame -> Frame
mapIdentities f = frameImagesMap %~ Map.mapKeys f
nextFrame :: R -> Frame -> Frame -> Maybe Frame
nextFrame movement dest cur
| isVirtuallySame dest cur = Nothing
| otherwise = Just $ makeNextFrame movement dest cur
makeNextFrame :: R -> Frame -> Frame -> Frame
makeNextFrame movement (Frame dests) (Frame curs) =
Frame . Map.map (:[]) . Map.mapMaybe id $
mconcat
[ Map.mapWithKey add $ Map.difference dest cur
, Map.mapWithKey del $ Map.difference cur dest
, Map.intersectionWith modify dest cur
]
where
dest = Map.map head dests
cur = Map.map head curs
animSpeed = pure movement
curPrefixMap = prefixRects cur
destPrefixMap = prefixRects dest
add key destImg =
destImg & iRect .~ curRect & Just
where
destRect = destImg ^. iRect
curRect =
findPrefix key curPrefixMap
& maybe (Rect (destRect ^. Rect.center) 0) genRect
genRect prefix = relocateSubRect destRect (destPrefixMap ! prefix) (curPrefixMap ! prefix)
del key curImg
| isJust (findPrefix key destPrefixMap)
|| Vector2.sqrNorm (curImg ^. iRect . Rect.size) < 1 = Nothing
| otherwise =
curImg
& iRect . Rect.centeredSize *~ (1 - animSpeed)
& Just
modify destImg curImg =
destImg
& iRect .~
Rect
(animSpeed * destTopLeft + (1 - animSpeed) * curTopLeft)
(animSpeed * destSize + (1 - animSpeed) * curSize )
& Just
where
Rect destTopLeft destSize = destImg ^. iRect
Rect curTopLeft curSize = curImg ^. iRect
unitSquare :: AnimId -> Frame
unitSquare animId = simpleFrame animId DrawUtils.square
emptyRectangle :: Vector2 R -> Vector2 R -> AnimId -> Frame
emptyRectangle (Vector2 fX fY) totalSize@(Vector2 sX sY) animId =
mconcat
[ rect 0 (Vector2 sX fY)
, rect (Vector2 0 (sY - fY)) (Vector2 sX fY)
, rect (Vector2 0 fY) (Vector2 fX (sY - fY*2))
, rect (Vector2 (sX - fX) fY) (Vector2 fX (sY - fY*2))
]
& sizedFrame animId totalSize
where
rect origin size =
DrawUtils.square
& (DrawUtils.scale size %%)
& (DrawUtils.translate origin %%)
-- Size is 1. Built from multiple vertical rectangles
unitHStripedSquare :: Int -> AnimId -> Frame
unitHStripedSquare n animId =
mconcat
[ scale (Vector2 (1/hunits) 1) $
translate (Vector2 pos 0) $
square i
| (i, pos) <- zip [0..] [0,2..hunits-1]
]
where
hunits = fromIntegral n * 2 - 1 -- light/dark unit count
square i = unitSquare $ animId ++ [SBS.pack (show (i :: Int))]
backgroundColor :: AnimId -> Layer -> Draw.Color -> Vector2 R -> Frame -> Frame
backgroundColor animId layer color size frame =
unitSquare animId
& images . iUnitImage %~ Draw.tint color
& scale size
& layers +~ layer
& mappend frame
translate :: Vector2 R -> Frame -> Frame
translate pos = images . iRect . Rect.topLeft +~ pos
scale :: Vector2 R -> Frame -> Frame
scale factor = images . iRect . Rect.topLeftAndSize *~ factor
-- Scale/translate a Unit-sized frame into a given rect
unitIntoRect :: Rect -> Frame -> Frame
unitIntoRect r =
translate (r ^. Rect.topLeft) .
scale (r ^. Rect.size)
| rvion/lamdu | bottlelib/Graphics/UI/Bottle/Animation.hs | gpl-3.0 | 8,843 | 0 | 15 | 2,645 | 2,779 | 1,473 | 1,306 | -1 | -1 |
module Favorites where
import Graphics.UI.Gtk
import Data.IORef
import Network.Tremulous.Protocol
import qualified Data.ByteString as B
import Types
import GtkUtils
import ClanFetcher
import FindPlayers (playerLikeList)
import Constants
import Config
favlist = ["gt", "meisseli", ".gm"]
newFavorites:: Bundle -> SetCurrent -> IO VBox
newFavorites bundle@Bundle{..} setCurrent = do
favPlayers <- newIORef (map mk favlist)
favClans <- newIORef [1]
playersLabel <- labelNew (Just "Players")
labelSetAttributes playersLabel [AttrWeight 0 (-1) WeightBold]
set playersLabel [miscXalign := 0, miscXpad := spacingHalf]
gen@(GenFilterSort raw filtered sorted view) <- playerLikeList bundle setCurrent
scroll <- scrollIt view PolicyAutomatic PolicyAutomatic
clansx <- atomically $ readTMVar mclans
treeModelFilterSetVisibleFunc filtered $ \iter -> do
(item, GameServer{..}) <- treeModelGetRow raw iter
favP <- readIORef favPlayers
favC <- readIORef favClans
return $ any (\x -> cleanedCase x `B.isInfixOf` cleanedCase item) favP
|| any (matchClanByID clansx item) favC
box <- vBoxNew False 0
boxPackStart box playersLabel PackNatural spacingBig
boxPackStart box scroll PackGrow 0
return box
| Cadynum/Apelsin | src/Favorites.hs | gpl-3.0 | 1,222 | 4 | 17 | 189 | 404 | 201 | 203 | -1 | -1 |
module SpacialGameMsg.RunSGMsg where
import SpacialGameMsg.SGModelMsg
import qualified PureAgents2DDiscrete as Front
import qualified Graphics.Gloss as GLO
import Graphics.Gloss.Interface.IO.Simulate
import qualified PureAgentsConc as PA
import System.Random
import Data.Maybe
import Data.List
import Control.Monad.STM
winTitle = "Spacial Game Msg CON"
winSize = (1000, 1000)
runSGMsgWithRendering :: IO ()
runSGMsgWithRendering = do
--hSetBuffering stdin NoBuffering
let dt = 1.0
let dims = (99, 99)
let rngSeed = 42
let defectorsRatio = 0.0
let g = mkStdGen rngSeed
(as, g') <- atomically $ createRandomSGAgents g dims defectorsRatio
let asWithDefector = setDefector as (49, 49) dims
hdl <- PA.initStepSimulation asWithDefector ()
stepWithRendering dims hdl dt
runSGMsgStepsAndRender :: IO ()
runSGMsgStepsAndRender = do
let dt = 1.0
let dims = (99, 99)
let rngSeed = 42
let steps = 2 * 218
let defectorsRatio = 0.0
let g = mkStdGen rngSeed
(as, g') <- atomically $ createRandomSGAgents g dims defectorsRatio
let asWithDefector = setDefector as (49, 49) dims
as' <- PA.stepSimulation asWithDefector () dt steps
let observableAgentStates = map (sgAgentToRenderCell dims) as'
let frameRender = (Front.renderFrame observableAgentStates winSize dims)
GLO.display (Front.display winTitle winSize) GLO.white frameRender
return ()
setDefector :: [SGAgent] -> (Int, Int) -> (Int, Int) -> [SGAgent]
setDefector as pos cells
| isNothing mayAgentAtPos = as
| otherwise = infront ++ [defectedAgentAtPos] ++ (tail behind)
where
mayAgentAtPos = find (\a -> pos == (agentToCell a cells)) as
agentAtPos = (fromJust mayAgentAtPos)
agentAtPosId = PA.agentId agentAtPos
defectedAgentAtPos = PA.updateState agentAtPos (\s -> s { sgCurrState = Defector,
sgPrevState = Defector,
sgBestPayoff = (Defector, 0.0) } )
(infront, behind) = splitAt agentAtPosId as
stepWithRendering :: (Int, Int) -> SGSimHandle -> Double -> IO ()
stepWithRendering dims hdl dt = simulateIO (Front.display winTitle winSize)
GLO.white
2
hdl
(modelToPicture dims)
(stepIteration dt)
modelToPicture :: (Int, Int) -> SGSimHandle -> IO GLO.Picture
modelToPicture dims hdl = do
let as = PA.extractHdlAgents hdl
let cells = map (sgAgentToRenderCell dims) as
return (Front.renderFrame cells winSize dims)
stepIteration :: Double -> ViewPort -> Float -> SGSimHandle -> IO SGSimHandle
stepIteration fixedDt viewport dtRendering hdl = (PA.advanceSimulation hdl fixedDt)
sgAgentToRenderCell :: (Int, Int) -> SGAgent -> Front.RenderCell
sgAgentToRenderCell (xDim, yDim) a = Front.RenderCell { Front.renderCellCoord = (ax, ay),
Front.renderCellColor = ss }
where
id = PA.agentId a
s = PA.state a
ax = mod id yDim
ay = floor((fromIntegral id) / (fromIntegral xDim))
curr = sgCurrState s
prev = sgPrevState s
ss = sgAgentStateToColor prev curr
sgAgentStateToColor :: SGState -> SGState -> (Double, Double, Double)
sgAgentStateToColor Cooperator Cooperator = blueC
sgAgentStateToColor Defector Defector = redC
sgAgentStateToColor Defector Cooperator = greenC
sgAgentStateToColor Cooperator Defector = yellowC
blueC :: (Double, Double, Double)
blueC = (0.0, 0.0, 0.7)
greenC :: (Double, Double, Double)
greenC = (0.0, 0.4, 0.0)
redC :: (Double, Double, Double)
redC = (0.7, 0.0, 0.0)
yellowC :: (Double, Double, Double)
yellowC = (1.0, 0.9, 0.0) | thalerjonathan/phd | public/ArtIterating/code/haskell/PureAgentsConc/src/SpacialGameMsg/RunSGMsg.hs | gpl-3.0 | 4,493 | 0 | 12 | 1,668 | 1,170 | 621 | 549 | 86 | 1 |
module Lookups where
import Data.List (elemIndex)
import Control.Applicative (liftA2)
added :: Maybe Integer
added = (+3) <$> (lookup 3 $ zip [1,2,3] [4,5,6])
y :: Maybe Integer
y = lookup 3 $ zip [1,2,3] [4,5,6]
z :: Maybe Integer
z = lookup 2 $ zip [1,2,3] [4,5,6]
tupled :: Maybe (Integer, Integer)
tupled = (,) <$> y <*> z
x' :: Maybe Int
x' = elemIndex 3 [1,2,3,4,5]
y' :: Maybe Int
y' = elemIndex 4 [1,2,3,4,5]
max' :: Int -> Int -> Int
max' = max
maxed :: Maybe Int
maxed = max' <$> x' <*> y'
maxed' :: Maybe Int
maxed' = liftA2 max' x' y'
xs = [1,2,3]
ys = [4,5,6]
x'' :: Maybe Integer
x'' = lookup 3 $ zip xs ys
y'' :: Maybe Integer
y'' = lookup 2 $ zip xs ys
-- Matt likes this one, he's clearly wrong. Maor's wrong too. So much
-- wrong...
summed :: Maybe Integer
summed = sum <$> ((,) <$> x'' <*> y'')
-- Eric likes this one. He's clearly right.
summed' :: Maybe Integer
summed' = sum <$> (liftA2 (,) x'' y'')
| thewoolleyman/haskellbook | 17/05/haskell-club/Lookups.hs | unlicense | 938 | 0 | 9 | 202 | 461 | 258 | 203 | 31 | 1 |
module Main where
import Prelude hiding (any)
import Grammar
import Any
import Control.Applicative((<$>))
import Control.Monad(void)
import qualified System.Random as R
main :: IO ()
main = void ((genSome :: IO S) >>= print)
genSome :: Any a => IO a
genSome = runGen any <$> R.newStdGen
| versusvoid/grammar-generator | src/Main.hs | unlicense | 291 | 0 | 9 | 50 | 112 | 65 | 47 | 11 | 1 |
{-# LANGUAGE FlexibleContexts #-}
-- Liang Barsky Line Clipping Algorithm
-- https://en.wikipedia.org/wiki/Liang%E2%80%93Barsky_algorithm
module Data.Geometry.Clip.Internal.LineLiangBarsky (
clipLineLb
, clipLinesLb
) where
import qualified Data.Aeson as Aeson
import qualified Data.Foldable as Foldable
import qualified Data.Geospatial as Geospatial
import qualified Data.LineString as LineString
import qualified Data.Sequence as Sequence
import qualified Data.Validation as Validation
import Prelude hiding (lines)
import qualified Data.Geometry.Clip.Internal.Line as ClipLine
import qualified Data.Geometry.Types.Geography as TypesGeography
data Edge = LeftEdge | RightEdge | BottomEdge | TopEdge
deriving (Show, Eq, Enum)
clipLineLb :: TypesGeography.BoundingBox -> Geospatial.GeoLine -> Geospatial.GeoFeature Aeson.Value -> Sequence.Seq (Geospatial.GeoFeature Aeson.Value) -> Sequence.Seq (Geospatial.GeoFeature Aeson.Value)
clipLineLb bb line feature acc =
case LineString.fromSeq clippedLine of
Validation.Success res -> (Sequence.<|) (Geospatial.reWrapGeometry feature (Geospatial.Line (Geospatial.GeoLine res))) acc
Validation.Failure _ -> acc
where
clippedLine = ClipLine.lineToGeoPoint $ lineToClippedPoints bb line
clipLinesLb :: TypesGeography.BoundingBox -> Geospatial.GeoMultiLine -> Geospatial.GeoFeature Aeson.Value -> Sequence.Seq (Geospatial.GeoFeature Aeson.Value) -> Sequence.Seq (Geospatial.GeoFeature Aeson.Value)
clipLinesLb bb lines (Geospatial.GeoFeature bbox _ props fId) acc = checkLinesAndAdd
where
checkLinesAndAdd = if Sequence.null multiLine then acc else (Sequence.<|) reMakeFeature acc
reMakeFeature = Geospatial.GeoFeature bbox (Geospatial.MultiLine (Geospatial.GeoMultiLine multiLine)) props fId
multiLine = Foldable.foldl' maybeAddLine mempty (linesToClippedPoints bb (Geospatial.splitGeoMultiLine lines))
maybeAddLine :: Sequence.Seq
(LineString.LineString Geospatial.GeoPositionWithoutCRS)
-> Sequence.Seq TypesGeography.GeoStorableLine
-> Sequence.Seq
(LineString.LineString Geospatial.GeoPositionWithoutCRS)
maybeAddLine acc pp =
case clipLineToValidationLineString pp of
Validation.Success res -> (Sequence.<|) res acc
Validation.Failure _ -> acc
clipLineToValidationLineString :: Sequence.Seq TypesGeography.GeoStorableLine
-> Validation.Validation
LineString.SequenceToLineStringError (LineString.LineString Geospatial.GeoPositionWithoutCRS)
clipLineToValidationLineString lines = LineString.fromSeq (ClipLine.lineToGeoPoint lines)
lineToClippedPoints :: TypesGeography.BoundingBox -> Geospatial.GeoLine -> Sequence.Seq TypesGeography.GeoStorableLine
lineToClippedPoints bb geoLine = Foldable.foldr (clipOrDiscard bb) Sequence.empty (ClipLine.getLines geoLine)
linesToClippedPoints :: Functor f => TypesGeography.BoundingBox -> f Geospatial.GeoLine -> f (Sequence.Seq TypesGeography.GeoStorableLine)
linesToClippedPoints bb = fmap (lineToClippedPoints bb)
clipOrDiscard :: TypesGeography.BoundingBox -> TypesGeography.GeoStorableLine -> Sequence.Seq TypesGeography.GeoStorableLine -> Sequence.Seq TypesGeography.GeoStorableLine
clipOrDiscard bb line acc =
case foldLine bb line dXdY of
Nothing -> acc
Just pt -> (Sequence.<|) (recreateLine pt line dXdY) acc
where
dXdY = dXAndDyFromLine line
foldLine :: TypesGeography.BoundingBox -> TypesGeography.GeoStorableLine -> DxAndDy -> Maybe T1AndT2
foldLine bb line dXdY = Foldable.foldl' (\acc edge -> calcT1AndT2OrQuit (calcPAndQ bb line dXdY edge) acc) t1AndT2 (Sequence.fromList [LeftEdge, RightEdge, BottomEdge, TopEdge])
data DxAndDy = DxAndDy !Double !Double
data T1AndT2 = T1AndT2 !Double !Double
data PAndQ = PAndQ !Double !Double
dXAndDyFromLine :: TypesGeography.GeoStorableLine -> DxAndDy
dXAndDyFromLine (TypesGeography.GeoStorableLine (Geospatial.PointXY x1 y1) (Geospatial.PointXY x2 y2)) = DxAndDy (x2 - x1) (y2 - y1)
t1AndT2 :: Maybe T1AndT2
t1AndT2 = Just (T1AndT2 0.0 1.0)
recreateLine :: T1AndT2 -> TypesGeography.GeoStorableLine -> DxAndDy -> TypesGeography.GeoStorableLine
recreateLine (T1AndT2 t1 t2) (TypesGeography.GeoStorableLine (Geospatial.PointXY x1 y1) _) (DxAndDy dX dY) =
TypesGeography.GeoStorableLine
(Geospatial.PointXY (x1 + t1 * dX) (y1 + t1 * dY))
(Geospatial.PointXY (x1 + t2 * dX) (y1 + t2 * dY))
calcT1AndT2OrQuit :: PAndQ -> Maybe T1AndT2 -> Maybe T1AndT2
calcT1AndT2OrQuit (PAndQ p q) orig =
case orig of
Nothing -> Nothing
Just (T1AndT2 t1 t2) ->
case compare p 0 of
EQ | q < 0 -> Nothing
| otherwise -> orig
LT | r > t2 -> Nothing
| r > t1 -> Just (T1AndT2 r t2)
| otherwise -> orig
GT | r < t1 -> Nothing
| r < t2 -> Just (T1AndT2 t1 r)
| otherwise -> orig
where
r = q / p
calcPAndQ :: TypesGeography.BoundingBox -> TypesGeography.GeoStorableLine -> DxAndDy -> Edge -> PAndQ
calcPAndQ (TypesGeography.BoundingBox minX minY maxX maxY) (TypesGeography.GeoStorableLine (Geospatial.PointXY x1 y1) _) (DxAndDy dX dY) e =
case e of
LeftEdge -> PAndQ (-1 * dX) (x1 - minX)
RightEdge -> PAndQ dX (maxX - x1)
BottomEdge -> PAndQ (-1 * dY) (y1 - minY)
TopEdge -> PAndQ dY (maxY - y1)
| sitewisely/zellige | src/Data/Geometry/Clip/Internal/LineLiangBarsky.hs | apache-2.0 | 5,506 | 0 | 15 | 1,077 | 1,587 | 811 | 776 | 97 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.