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
MultiParamTypeClasses,
FlexibleInstances, FlexibleContexts,
DeriveDataTypeable, DeriveGeneric
#-}
module Insomnia.Types where
import Control.Applicative
import Control.Lens
import Control.Monad (liftM, zipWithM_)
import Data.Function (on)
import qualified Data.Map as M
import Data.List (sortBy)
import Data.Ord (comparing)
import Data.Typeable(Typeable)
import Data.Format (Format(..))
import GHC.Generics (Generic)
import Unbound.Generics.LocallyNameless
import qualified Unbound.Generics.LocallyNameless.Unsafe as UU
import Insomnia.Identifier
import Insomnia.Common.Literal
import {-# SOURCE #-} Insomnia.ModuleType (ModuleType)
import Insomnia.Unify (UVar, Unifiable(..),
HasUVars(..),
Partial(..),
MonadUnify(..),
MonadUnificationExcept(..),
UnificationFailure(..))
type TyVar = Name Type
type KindedTVar = (TyVar, Kind)
type Nat = Integer
data Rows = Rows -- TODO
data Kind = KType -- ^ the kind of types
-- | KROW -- ^ the kind ROW of rows. users can't write it directly
| KArr !Kind !Kind
deriving (Show, Typeable, Generic)
infixr 6 `KArr`
-- | A local type constructor name. These are similar to type variables, except they
-- are substituted by global type paths instead of by arbitrary types.
type TyConName = Name TypeConstructor
-- | A type path selects a type from a model named by field
data TypePath = TypePath Path Field
deriving (Show, Eq, Ord, Typeable, Generic)
-- | A type constructor is either local to the current model, or it is
-- global.
data TypeConstructor =
TCLocal TyConName
| TCGlobal TypePath
deriving (Show, Eq, Typeable, Generic)
instance Ord TypeConstructor where
compare tc1 tc2 =
case (tc1, tc2) of
(TCLocal n1, TCLocal n2) -> compare n1 n2
(TCLocal {}, TCGlobal {}) -> LT
(TCGlobal {}, TCLocal {}) -> GT
(TCGlobal p1, TCGlobal p2) -> compare p1 p2
-- | The types include type variables (which stand for types), unification
-- variables, type constructors, annotted kinds, type applications,
-- universally quantified types and record types.
data Type = TV TyVar
| TUVar (UVar Kind Type) -- invariant: unification variables should be fully applied -- XXX what does this mean? ak-20150825
| TC !TypeConstructor
| TAnn Type !Kind
| TApp Type Type
| TForall (Bind (TyVar, Kind) Type)
| TRecord Row
| TPack !ModuleType -- first class modules of the given module type
deriving (Show, Typeable, Generic)
infixl 6 `TApp`
-- | A label identifies a component of a row.
newtype Label = Label {labelName :: String}
deriving (Show, Eq, Ord, Typeable, Generic)
-- | Rows associate a set of types with a set of labels. For now this
-- is syntactically separate from other types and we don't have row
-- variables, so this is really just plain old non-extensible records.
data Row = Row [(Label, Type)]
deriving (Show, Typeable, Generic)
-- | iterate kind arrow construction
-- @kArrs [k1, ... kN] kcod = k1 `KArr` k2 `KArr` ... `KArr` kN `kArr` kcod@
kArrs :: [Kind] -> Kind -> Kind
kArrs [] kcod = kcod
kArrs (kdom:ks) kcod = kdom `KArr` kArrs ks kcod
-- | iterate type application
-- @tApps t0 [t1, ..., tN] = t0 `TApp` t1 `TApp` ... `TApp` tN
tApps :: Type -> [Type] -> Type
tApps t0 [] = t0
tApps t0 (t1:ts) = tApps (TApp t0 t1) ts
tForalls :: [(TyVar, Kind)] -> Type -> Type
tForalls [] = id
tForalls (tvk:tvks) = TForall . bind tvk . tForalls tvks
-- | Sort the labels of a row into a canonical order
canonicalOrderRowLabels :: [(Label, a)] -> [(Label, a)]
canonicalOrderRowLabels = sortBy (comparing fst)
-- Formatted output
instance Format Kind
instance Format Type
-- Alpha equivalence
instance Alpha Label
instance Alpha TypePath
instance Alpha TypeConstructor
instance Alpha Type
instance Alpha Kind
instance Alpha Row
instance Eq Type where
(==) = aeq
-- Substitution
-- Capture avoiding substitution of type variables in types and terms.
instance Subst Type Type where
isvar (TV v) = Just (SubstName v)
isvar _ = Nothing
instance Subst Type Row
instance Subst Type Label where
subst _ _ = id
substs _ = id
instance Subst Type TypePath where
subst _ _ = id
substs _ = id
instance Subst Type Literal where
subst _ _ = id
substs _ = id
instance Subst Type Path where
subst _ _ = id
substs _ = id
instance Subst Type TypeConstructor where
subst _ _ = id
substs _ = id
instance Subst Type Kind where
subst _ _ = id
substs _ = id
-- unification variables are opaque boxes that can't be substituted into.
instance Subst Type (UVar w a) where
subst _ _ = id
substs _ = id
instance Subst Type SigPath where
subst _ _ = id
substs _ = id
instance Subst SigPath Kind where
subst _ _ = id
substs _ = id
instance Subst Path Kind where
subst _ _ = id
substs _ = id
instance Subst Path Label where
subst _ _ = id
substs _ = id
instance Subst SigPath Type
instance Subst SigPath TypePath where
subst _ _ = id
substs _ = id
instance Subst SigPath Row
instance Subst SigPath Label where
subst _ _ = id
substs _ = id
instance Subst SigPath TypeConstructor
instance Subst SigPath (UVar w a) where
subst _ _ = id
substs _ = id
instance Subst Path TypePath
instance Subst Path TypeConstructor
instance Subst Path Type
instance Subst Path Row
instance Subst TypeConstructor TypeConstructor where
isvar (TCLocal c) = Just (SubstName c)
isvar _ = Nothing
instance Subst TypeConstructor TypePath where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor Path where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor SigPath where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor Literal where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor (UVar w a) where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor Label where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor Kind where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor Type
instance Subst TypeConstructor Row
-- Unification
instance Partial Kind Type where
_UVar = let
pick (TUVar u) = Just u
pick _ = Nothing
in prism' TUVar pick
instance HasUVars Type Type where
allUVars f t =
case t of
TV {} -> pure t
TUVar {} -> f t
TC {} -> pure t
TAnn t1 k -> TAnn <$> allUVars f t1 <*> pure k
TApp t1 t2 -> TApp <$> allUVars f t1 <*> allUVars f t2
TPack {} -> pure t
TForall bnd -> let
(vk, t1) = UU.unsafeUnbind bnd
in (TForall . bind vk) <$> allUVars f t1
TRecord row -> TRecord <$> allUVars f row
instance HasUVars Type Row where
allUVars f (Row ts) = Row <$> traverseOf (traverse . _2 . allUVars) f ts
-- | Make a fresh unification variable
freshUVarT :: MonadUnify e Kind Type m => Kind -> m Type
freshUVarT k = liftM TUVar (unconstrained k)
-- | Construct a fresh type expression composed of a unification var
-- of the given kind applied to sufficiently many ground arguments
-- such that the whole type expression has of kind ⋆.
--
-- @
-- ⌞⋆⌟ = u - u fresh
-- ⌞k1 → ⋯ → kN → ⋆⌟ = apply u (map ⌞·⌟ ks) - u fresh
-- @
-- for example: @⌞a -> (b -> ⋆)⌟ = (u·⌞a⌟)·⌞b⌟@
groundUnificationVar :: MonadUnify TypeUnificationError Kind Type m => Kind -> m Type
groundUnificationVar = \ k -> do
tu <- freshUVarT k
go k tu
where
go KType thead = return thead
go (KArr kdom kcod) thead = do
targ <- groundUnificationVar kdom
go kcod (thead `TApp` targ)
data TypeUnificationError =
SimplificationFail (M.Map (UVar Kind Type) Type) !Type !Type -- the two given types could not be simplified under the given constraints
| RowLabelsDifferFail !Row !Row -- the two given rows could not be unifified because they have different labels
| PackedModuleTypesDifferFail !ModuleType !ModuleType -- the two given module types are not equivalent
class MonadTypeAlias m where
expandTypeAlias :: TypeConstructor -> m (Maybe Type)
instance (MonadUnify TypeUnificationError Kind Type m,
MonadUnificationExcept TypeUnificationError Kind Type m,
MonadTypeAlias m,
LFresh m)
=> Unifiable Kind Type TypeUnificationError m Type where
t1 =?= t2 =
case (t1, t2) of
(TForall bnd1, TForall bnd2) ->
lunbind2 bnd1 bnd2 $ \opn ->
case opn of
Just ((_, _), t1', (_, _), t2') ->
t1' =?= t2'
Nothing -> do
constraintMap <- reflectCollectedConstraints
throwUnificationFailure
$ Unsimplifiable (SimplificationFail constraintMap t1 t2)
-- (TForall bnd1, _) ->
-- lunbind bnd1 $ \ ((v1, _), t1_) -> do
-- tu1 <- freshUVarT
-- let t1' = subst v1 tu1 t1_
-- t1' =?= t2
-- (_, TForall {}) -> t2 =?= t1
(TRecord row1, TRecord row2) -> row1 =?= row2
(TPack modTy1, TPack modTy2) ->
if aeq modTy1 modTy2
then return ()
else throwUnificationFailure $ Unsimplifiable (PackedModuleTypesDifferFail modTy1 modTy2)
(TUVar u1, TUVar u2) | u1 == u2 -> return ()
(TUVar u1, _) -> u1 -?= t2
(_, TUVar u2) -> u2 -?= t1
(TAnn t1' _, TAnn t2' _) -> t1' =?= t2'
(TAnn t1' _, _) -> t1' =?= t2
(_, TAnn t2' _) -> t1 =?= t2'
(TV v1, TV v2) | v1 == v2 -> return ()
(TC c1, TC c2) ->
if c1 == c2
then return ()
else do
mexp1 <- expandTypeAlias c1
mexp2 <- expandTypeAlias c2
case (mexp1, mexp2) of
(Just t1', Just t2') -> t1' =?= t2'
(Just t1', Nothing) -> t1' =?= t2
(Nothing, Just t2') -> t1 =?= t2'
(Nothing, Nothing) -> failedToUnify
(TC c1, _) -> do
mexp <- expandTypeAlias c1
case mexp of
Nothing -> failedToUnify
Just t1' -> t1' =?= t2
(_, TC _c2) -> t2 =?= t1
(TApp t11 t12, TApp t21 t22) -> do
t11 =?= t21
t12 =?= t22
_ -> failedToUnify
where
failedToUnify = do
constraintMap <- reflectCollectedConstraints
throwUnificationFailure
$ Unsimplifiable (SimplificationFail constraintMap t1 t2)
instance (MonadUnify TypeUnificationError Kind Type m,
MonadUnificationExcept TypeUnificationError Kind Type m,
MonadTypeAlias m,
LFresh m)
=> Unifiable Kind Type TypeUnificationError m Row where
r1@(Row ls1_) =?= r2@(Row ls2_) =
let ls1 = canonicalOrderRowLabels ls1_
ls2 = canonicalOrderRowLabels ls2_
in if map fst ls1 == map fst ls2
then zipWithM_ ((=?=) `on` snd) ls1 ls2
else throwUnificationFailure $ Unsimplifiable (RowLabelsDifferFail r1 r2)
instance Plated Type where
plate _ (t@TUVar {}) = pure t
plate _ (t@TV {}) = pure t
plate _ (t@TC {}) = pure t
plate f (TPack modTy) = TPack <$> traverseTypes f modTy
plate f (TForall bnd) =
let (tvk,t) = UU.unsafeUnbind bnd
in (TForall . bind tvk) <$> f t
plate f (TAnn t k) = TAnn <$> f t <*> pure k
plate f (TApp t1 t2) = TApp <$> f t1 <*> f t2
plate f (TRecord ts) = TRecord <$> traverseTypes f ts
-- | Traverse the types in the given container
class TraverseTypes s t where
traverseTypes :: Traversal s t Type Type
instance TraverseTypes Row Row where
traverseTypes f (Row ts) = Row <$> traverseOf (traverse . _2) f ts
instance TraverseTypes a b => TraverseTypes (Maybe a) (Maybe b) where
traverseTypes _ Nothing = pure Nothing
traverseTypes f (Just a) = Just <$> traverseTypes f a
instance TraverseTypes a b => TraverseTypes [a] [b] where
traverseTypes _ [] = pure []
traverseTypes f (x:xs) = (:) <$> traverseTypes f x <*> traverseTypes f xs
transformEveryTypeM :: (TraverseTypes a a, Plated a, Monad m) => (Type -> m Type) -> a -> m a
transformEveryTypeM f = transformM (transformMOn traverseTypes f)
|
lambdageek/insomnia
|
src/Insomnia/Types.hs
|
bsd-3-clause
| 12,161 | 0 | 19 | 3,174 | 3,676 | 1,897 | 1,779 | 307 | 2 |
{-# LANGUAGE ScopedTypeVariables
, ParallelListComp
#-}
{-| Parse UTF-8 JSON into native Haskell types.
-}
module Text.JSONb.Decode where
import Data.Char
import Data.Ratio ((%))
import Prelude hiding (length, null, last, takeWhile)
import Data.ByteString (length, append, empty, ByteString)
import Data.ByteString.Char8 (snoc, cons, pack)
import Control.Applicative hiding (empty)
import qualified Data.ByteString.UTF8 as UTF8
import qualified Data.Trie.Convenience as Trie
import Data.Attoparsec (eitherResult)
import Data.Attoparsec.Char8 ( choice, char, Parser, option, takeWhile1,
takeWhile, skipMany, satisfy, signed,
decimal )
import qualified Data.Attoparsec.Char8 as Attoparsec
import qualified Data.Attoparsec.Types as AttoparsecT
import Data.ByteString.Nums.Careless
import Text.JSONb.Simple
{-| Interpret a 'ByteString' as any JSON literal.
-}
decode :: ByteString -> Either String JSON
decode bytes = (eitherResult . Attoparsec.parse json) bytes
{-| Split out the first parseable JSON literal from the input, returning
the result of the attempt along with the remainder of the input or the
whole input if no parseable item was discovered.
-}
break :: ByteString -> (Either String JSON, ByteString)
break bytes = case Attoparsec.parse json bytes of
AttoparsecT.Done remainder result -> (Right result, remainder)
AttoparsecT.Fail _ _ s -> (Left s, bytes)
AttoparsecT.Partial _ -> (Left "Partial", bytes)
{-| Tries to parse any JSON literal.
-}
json :: Parser JSON
json = do
whitespace
choice [object, array, string, number, boolean, null]
{-| Parse a JSON object (dictionary).
-}
object :: Parser JSON
object = do
char '{'
whitespace
Object . Trie.fromListS <$> choice
[ whitespace >> char '}' >> return []
, properties []
]
where
properties acc = do
key <- string_literal
whitespace
char ':'
something <- json
whitespace
let
acc' = (key, something) : acc
choice
[ char ',' >> whitespace >> choice
[ char '}' >> return acc'
, properties acc'
]
, char '}' >> return acc'
]
{-| Parse a JSON array.
-}
array :: Parser JSON
array = do
char '['
Array <$> choice
[ whitespace >> char ']' >> return []
, elements []
]
where
elements acc = do
something <- json
whitespace
let
acc' = something : acc
finish = char ']' >> return (reverse acc')
choice
[ char ',' >> whitespace >> choice [finish, elements acc']
, finish
]
{-| Parses a string literal, unescaping as it goes.
-}
string :: Parser JSON
string = String <$> string_literal
{-| Parses a numeric literal to a @Rational@.
-}
number :: Parser JSON
number = Number <$> do
(sign :: Rational) <- (char '-' *> pure (-1)) <|> pure 1
i <- just_zero <|> positive_number
f <- option 0 fractional
e <- option 0 (exponentialE *> signed decimal)
return (sign * (i + f) * (10^^e))
where
exponentialE = char 'e' <|> char 'E'
fractional = do
c <- char '.'
digits <- takeWhile1 isDigit
return (int digits % (10^(length digits)))
just_zero = char '0' *> pure 0
positive_number = pure ((int .) . cons) <*> satisfy hi <*> takeWhile isDigit
where
hi d = d > '0' && d <= '9'
{-| Parse a JSON Boolean literal.
-}
boolean :: Parser JSON
boolean = Boolean <$> choice
[ s_as_b "true" >> pure True
, s_as_b "false" >> pure False
]
{-| Parse a JSON null literal.
-}
null :: Parser JSON
null = s_as_b "null" >> return Null
{-| Per RFC 4627, section 2 "JSON Grammar", only a limited set of whitespace
characters actually count as insignificant whitespace.
-}
whitespace :: Parser ()
whitespace = skipMany (satisfy w)
where
w ' ' = True -- ASCII space.
w '\n' = True -- Newline.
w '\r' = True -- Carriage return.
w '\t' = True -- Horizontal tab.
w _ = False -- Not a JSON space.
{-| Parse a JSON string literal and unescape it but don't wrap it in a string
constructor (we might wrap it as a dict key instead).
-}
string_literal :: Parser ByteString
string_literal = char '"' >> recurse empty
where
recurse acc = do
text <- takeWhile (not . (`elem` "\\\""))
choice
[ char '"' >> return (acc `append` text)
, do
char '\\'
c <- escape_sequence
recurse (acc `append` text `append` UTF8.fromString [c])
]
where
escape_sequence = do
choice [ c >> r | c <- fmap char "n/\"rfbt\\u"
| r <- fmap return "\n/\"\r\f\b\t\\" ++ [u] ]
where
u = do
(a,b,c,d) <- (,,,) <$> hex <*> hex <*> hex <*> hex
return . toEnum $ a * 0x1000
+ b * 0x100
+ c * 0x10
+ d * 0x1
where
hex = choice digits
where
prep (n, chars) = fmap (fmap ((+n) . ord) . char) chars
digits = concatMap prep [ (-48, ['0'..'9'])
, (-55, ['A'..'F'])
, (-87, ['a'..'f']) ]
s_as_b s = Attoparsec.string (pack s)
|
solidsnack/JSONb
|
Text/JSONb/Decode.hs
|
bsd-3-clause
| 6,427 | 1 | 21 | 2,709 | 1,528 | 802 | 726 | 120 | 5 |
{-- snippet modifyMVar_strict --}
{-# LANGUAGE BangPatterns #-}
import Control.Concurrent (MVar, putMVar, takeMVar)
import Control.Exception (block, catch, throw, unblock)
import Prelude hiding (catch) -- use Control.Exception's version
modifyMVar_strict :: MVar a -> (a -> IO a) -> IO ()
modifyMVar_strict m io = block $ do
a <- takeMVar m
!b <- unblock (io a) `catch` \e ->
putMVar m a >> throw e
putMVar m b
{-- /snippet modifyMVar_strict --}
|
binesiyu/ifl
|
examples/ch24/ModifyMVarStrict.hs
|
mit
| 462 | 0 | 12 | 87 | 152 | 80 | 72 | 10 | 1 |
{-# OPTIONS_GHC -fglasgow-exts #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Morphism.Histo
-- Copyright : (C) 2008 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable (rank-2 polymorphism)
--
-- Traditional operators, shown here to show how to roll your own
----------------------------------------------------------------------------
module Control.Morphism.Histo
( distHisto
, histo, g_histo
, prepro_histo, g_prepro_histo
) where
import Control.Functor.Algebra
import Control.Functor.Extras
import Control.Functor.Fix
import Control.Comonad
import Control.Comonad.Cofree
import Control.Morphism.Cata
import Control.Morphism.Prepro
distHisto :: (RunComonadCofree h w, Functor f) => Dist f h -> Dist f w
distHisto k = anaCofree (fmap extract) (k . fmap outCofree)
histo :: (RunComonadCofree f w) => GAlgebra f w a -> FixF f -> a
histo = g_cata (distHisto id)
g_histo :: (RunComonadCofree h w, Functor f) => Dist f h -> GAlgebra f w a -> FixF f -> a
g_histo k = g_cata (distHisto k)
-- A histomorphic prepromorphism
prepro_histo :: (RunComonadCofree f w) => GAlgebra f w a -> (f :~> f) -> FixF f -> a
prepro_histo = g_prepro (distHisto id)
-- A generalized histomorphic prepromorphism
g_prepro_histo :: (RunComonadCofree h w, Functor f) => Dist f h -> GAlgebra f w a -> (f :~> f) -> FixF f -> a
g_prepro_histo k = g_prepro (distHisto k)
|
urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav
|
Control/Morphism/Histo.hs
|
apache-2.0
| 1,548 | 4 | 10 | 252 | 399 | 216 | 183 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -Wall #-}
{-|
Defines the syntax of invariant annotations. See "Camfort.Specification.Hoare"
for a high-level overview.
In this module, the word \'primitive\' is used to refer to untyped expression
syntax (as opposed to the typed expression syntax defined in
"Language.Fortran.Model.Op").
-}
module Camfort.Specification.Hoare.Syntax where
import Data.Data
import Control.Lens
import qualified Language.Fortran.AST as F
import Language.Expression.Pretty
-- * Syntax Types
-- | A type of primitive logical operators.
data PrimLogic a
= PLAnd a a
| PLOr a a
| PLImpl a a
| PLEquiv a a
| PLNot a
| PLLit Bool
deriving (Typeable, Data, Show, Eq, Functor, Foldable, Traversable)
-- | Logical expressions over Fortran expressions.
data PrimFormula ann
= PFExpr (F.Expression ann)
| PFLogical (PrimLogic (PrimFormula ann))
deriving (Typeable, Data, Show, Eq, Functor)
-- | Labels for the keyword used in @static_assert@ annotations.
data SpecKind
= SpecPre
-- ^ @static_assert pre(...)@
| SpecPost
-- ^ @static_assert post(...)@
| SpecSeq
-- ^ @static_assert seq(...)@
| SpecInvariant
-- ^ @static_assert invariant(...)@
deriving (Show, Eq, Typeable, Data)
-- | A @static_assert@ annotation.
data Specification a =
Specification
{ _specType :: SpecKind
, _specFormula :: a
}
deriving (Typeable, Data, Eq, Functor)
-- | A @decl_aux@ annotation.
data AuxDecl ann =
AuxDecl
{ _adName :: F.Name
, _adTy :: F.TypeSpec ann
}
deriving (Typeable, Data, Show, Eq, Functor)
-- | A specification over untyped logical expressions.
type PrimSpec ann = Specification (PrimFormula ann)
-- | A @static_assert@ or @decl_aux@ annotation.
data SpecOrDecl ann =
SodSpec (PrimSpec ann)
| SodDecl (AuxDecl ann)
deriving (Typeable, Data, Show, Eq, Functor)
instance Show a => Pretty (PrimFormula a) where pretty = show
instance (Pretty a) => Show (Specification a) where
show Specification { _specType, _specFormula } =
"Specification { " ++
"_specType = " ++ show _specType ++ ", " ++
"_specFormula = " ++ pretty _specFormula ++
" }"
-- * Lenses
makeLenses ''Specification
makeLenses ''AuxDecl
makePrisms ''Specification
makePrisms ''SpecOrDecl
-- | Given a prism @p@ projecting a pair, @'refining' x p@ projects values from
-- the front left of the pair such that the right of the pair matches @x@.
--
-- >>> [1, 2, 3] ^? refining [] _Cons
-- Nothing
--
-- >>> [1] ^? refining [] _Cons
-- Just 1
--
refining :: (Eq r) => r -> APrism s t (a, r) (a, r) -> Prism s t a a
refining y p = clonePrism p . below (only y) . iso fst (, ())
-- | Match a @static_assert pre(...)@ annotation.
_SpecPre :: Prism' (Specification a) a
_SpecPre = refining SpecPre (_Specification . swapped)
-- | Match a @static_assert post(...)@ annotation.
_SpecPost :: Prism' (Specification a) a
_SpecPost = refining SpecPost (_Specification . swapped)
-- | Match a @static_assert seq(...)@ annotation.
_SpecSeq :: Prism' (Specification a) a
_SpecSeq = refining SpecSeq (_Specification . swapped)
-- | Match a @static_assert invariant(...)@ annotation.
_SpecInvariant :: Prism' (Specification a) a
_SpecInvariant = refining SpecInvariant (_Specification . swapped)
|
dorchard/camfort
|
src/Camfort/Specification/Hoare/Syntax.hs
|
apache-2.0
| 3,938 | 0 | 11 | 865 | 755 | 423 | 332 | 75 | 1 |
{-# LANGUAGE DeriveDataTypeable, TypeFamilies, TemplateHaskell #-}
module AudioDB where
import Data.Acid
import Data.Typeable
import Control.Monad.State
import Control.Monad.Reader
import Data.SafeCopy
import qualified Data.Map as Map
type AudioUID = String
type AudioVKID = String
data AudioIds = AudioIds !(Map.Map AudioUID AudioVKID)
deriving Typeable
$(deriveSafeCopy 0 'base ''AudioIds)
insertAudio :: AudioUID -> AudioVKID -> Update AudioIds ()
insertAudio uid vkid = do
AudioIds m <- get
put (AudioIds (Map.insert uid vkid m))
getAudio :: AudioUID -> Query AudioIds (Maybe AudioVKID)
getAudio uid = do
AudioIds m <- ask
return (Map.lookup uid m)
$(makeAcidic ''AudioIds ['insertAudio, 'getAudio])
|
hithroc/hsvkbot
|
src/AudioDB.hs
|
bsd-3-clause
| 730 | 0 | 12 | 119 | 232 | 122 | 110 | 24 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
import Prelude hiding (and, foldl, mapM, mapM_, sequence, sequence_)
import Control.Monad.Ref
import Reflex.Class
import Reflex.Dynamic
import Reflex.Host.Class
import qualified Reflex.Pure as P
import qualified Reflex.Spider.Internal as S
import qualified Reflex.Profiled as Prof
import Control.Arrow (second, (&&&))
import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
import Control.Monad.State.Strict hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
import Data.Dependent.Sum (DSum (..))
import Data.Foldable
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Data.Monoid
import Data.Traversable
import System.Exit
import System.Mem
mapToPureBehavior :: Map Int a -> Behavior PureReflexDomain a
mapToPureBehavior m = P.Behavior $ \t -> case Map.lookupLE t m of
Nothing -> error $ "mapToPureBehavior: no value for time " <> show t
Just (_, v) -> v
mapToPureEvent :: Map Int a -> Event PureReflexDomain a
mapToPureEvent m = P.Event $ flip Map.lookup m
relevantTestingTimes :: (Map Int a, Map Int b) -> [Int]
relevantTestingTimes (b, e) = case Set.minView &&& Set.maxView $ Map.keysSet b `Set.union` Map.keysSet e of
(Just (t0, _), Just (t1, _)) -> [t0..t1+1] -- We need to go to b+1 to see the result of the final event
_ -> [] -- Doesn't actually make much sense
type PureReflexDomain = P.Pure Int
type TimeM = (->) Int
testPure :: (t ~ PureReflexDomain, m ~ TimeM) => ((Behavior t a, Event t b) -> m (Behavior t c, Event t d)) -> (Map Int a, Map Int b) -> (Map Int c, Map Int d)
testPure builder (b, e) =
let (P.Behavior b', P.Event e') = ($ 0) $ builder (mapToPureBehavior b, mapToPureEvent e)
relevantTimes = relevantTestingTimes (b, e)
e'' = Map.mapMaybe id $ Map.fromList $ map (id &&& e') relevantTimes
b'' = Map.fromList $ map (id &&& b') relevantTimes
in (b'', e'')
class MapMSignals a a' t t' | a -> t, a' -> t', a t' -> a', a' t -> a where
mapMSignals :: Monad m => (forall b. Behavior t b -> m (Behavior t' b)) -> (forall b. Event t b -> m (Event t' b)) -> a -> m a'
instance MapMSignals (Behavior t a) (Behavior t' a) t t' where
mapMSignals fb _ = fb
instance MapMSignals (Event t a) (Event t' a) t t' where
mapMSignals _ fe = fe
instance (MapMSignals a a' t t', MapMSignals b b' t t') => MapMSignals (a, b) (a', b') t t' where
mapMSignals fb fe (a, b) = liftM2 (,) (mapMSignals fb fe a) (mapMSignals fb fe b)
testTimeline
:: (forall m t. TestCaseConstraint t m => (Behavior t a, Event t b) -> m (Behavior t c, Event t d))
-> (Map Int a, Map Int b)
-> (forall m t. (MonadReflexHost t m, MonadIO m, MonadRef m, Ref m ~ Ref IO, MonadSample t m) => m (Map Int c, Map Int d))
testTimeline builder (bMap, eMap) = do
(re, reTrigger) <- newEventWithTriggerRef
(rb, rbTrigger) <- newEventWithTriggerRef
b <- runHostFrame $ hold (error "testTimeline: No value for input behavior yet") rb
(b', e') <- runHostFrame $ builder (b, re)
e'Handle <- subscribeEvent e' --TODO: This should be unnecessary
let times = relevantTestingTimes (bMap, eMap)
liftIO performGC
outputs <- forM times $ \t -> do
forM_ (Map.lookup t bMap) $ \val -> mapM_ (\ rbt -> fireEvents [rbt :=> Identity val]) =<< readRef rbTrigger
bOutput <- sample b'
eOutput <- fmap join $ forM (Map.lookup t eMap) $ \val -> do
mret <- readRef reTrigger
let firing = case mret of
Just ret -> [ret :=> Identity val]
Nothing -> []
fireEventsAndRead firing $ sequence =<< readEvent e'Handle
liftIO performGC
return (t, (bOutput, eOutput))
return (Map.fromList $ map (second fst) outputs, Map.mapMaybe id $ Map.fromList $ map (second snd) outputs)
tracePerf :: Show a => a -> b -> b
tracePerf = flip const
testAgreement :: (Eq c, Eq d, Show c, Show d) => (forall m t. TestCaseConstraint t m => (Behavior t a, Event t b) -> m (Behavior t c, Event t d)) -> (Map Int a, Map Int b) -> IO Bool
testAgreement builder inputs = do
let identityResult = testPure builder inputs
tracePerf "---------" $ return ()
spiderResult <- S.runSpiderHost $ testTimeline builder inputs
tracePerf "---------" $ return ()
profiledResult <- S.runSpiderHost $ Prof.runProfiledM $ testTimeline builder inputs
tracePerf "---------" $ return ()
let resultsAgree = identityResult == spiderResult && identityResult == profiledResult
if resultsAgree
then do --putStrLn "Success:"
--print identityResult
return ()
else do putStrLn "Failure:"
putStrLn $ "Pure result: " <> show identityResult
putStrLn $ "Spider result: " <> show spiderResult
putStrLn $ "Profiled result: " <> show profiledResult
return resultsAgree
type TestCaseConstraint t m = (Reflex t, MonadSample t m, MonadHold t m, MonadFix m, MonadFix (PushM t))
data TestCase = forall a b c d. (Eq c, Eq d, Show c, Show d) => TestCase (Map Int a, Map Int b) (forall m t. TestCaseConstraint t m => (Behavior t a, Event t b) -> m (Behavior t c, Event t d))
testCases :: [(String, TestCase)]
testCases =
[ (,) "hold" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(_, e) -> do
b' <- hold "123" e
return (b', e)
, (,) "count" $ TestCase (Map.singleton 0 (), Map.fromList [(1, ()), (2, ()), (3, ())]) $ \(_, e) -> do
e' <- updated <$> count e
b' <- hold (0 :: Int) e'
return (b', e')
, (,) "headE-1" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
e' <- headE $ leftmost [e, e]
return (b, e')
, (,) "switch-1" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
let e' = fmap (const e) e
b' <- hold never e'
let e'' = switch b'
return (b, e'')
, (,) "switch-2" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
let e' = flip pushAlways e $ const $ do
let eab = splitRecombineEvent e
switch <$> hold eab never
e'' = coincidence e'
return (b, e'')
, (,) "switch-3" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
let e' = flip pushAlways e $ const $ do
let eab = splitRecombineEvent e
switch <$> hold eab (fmap (const e) e)
e'' = coincidence e'
return (b, e'')
, (,) "switch-4" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
let e' = leftmost [e, e]
e'' <- switch <$> hold e' (fmap (const e) e)
return (b, e'')
, (,) "switchHoldPromptly-1" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
let e' = fmap (const e) e
e'' <- switchHoldPromptly never e'
return (b, e'')
, (,) "switchHoldPromptly-2" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
let e' = fmap (const e) e
e'' <- switchHoldPromptly never $ leftmost [e', e']
return (b, e'')
, (,) "switchHoldPromptly-3" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
let e' = leftmost [e, e]
e'' <- switchHoldPromptly never (fmap (const e) e')
return (b, e'')
, (,) "switchHoldPromptly-4" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do
let e' = leftmost [e, e]
e'' <- switchHoldPromptly never (fmap (const e') e)
return (b, e'')
, (,) "switch-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
let e' = leftmost [e, e]
e'' <- switch <$> hold never (fmap (const e') e)
return (b, e'')
, (,) "switchHoldPromptly-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
let e' = flip push e $ \_ -> do
Just <$> headE e
e'' <- switchHoldPromptly never e'
return (b, e'')
, (,) "switchHoldPromptly-6" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
let e' = flip pushAlways e $ \_ -> do
switchHoldPromptly e never
e'' <- switchHoldPromptly never e'
return (b, e'')
, (,) "coincidence-1" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
let e' = flip pushAlways e $ \_ -> return e
e'' = coincidence e'
return (b, e'')
, (,) "coincidence-2" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
let e' = flip pushAlways e $ \_ -> return $ leftmost [e, e]
e'' = coincidence e'
return (b, e'')
, (,) "coincidence-3" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
let e' = flip pushAlways e $ \_ -> return $ coincidence $ fmap (const e) e
e'' = coincidence e'
return (b, e'')
, (,) "coincidence-4" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do
let e' = flip pushAlways e $ \_ -> headE e
e'' = coincidence e'
return (b, e'')
, (,) "coincidence-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer")]) $ \(b, e) -> do
let eChild = flip pushAlways e $ const $ do
let eNewValues = leftmost [e, e]
return $ coincidence $ fmap (const eNewValues) eNewValues
e' = coincidence eChild
return (b, e')
, (,) "coincidence-6" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer")]) $ \(b, e) -> do
let eChild = flip pushAlways e $ const $ do
let e' = coincidence $ fmap (const e) e
return $ leftmost [e', e']
e'' = coincidence eChild
return (b, e'')
, (,) "coincidence-7" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do
let e' = leftmost [e, e]
eCoincidences = coincidence $ fmap (const e') e
return (b, eCoincidences)
, (,) "holdWhileFiring" $ TestCase (Map.singleton 0 "zxc", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
eo <- headE e
bb <- hold b $ pushAlways (const $ hold "asdf" eo) eo
let b' = pull $ sample =<< sample bb
return (b', e)
, (,) "foldDynWhileFiring" $ TestCase (Map.singleton 0 "zxc", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(_, e) -> do
d <- foldDyn (:) [] $
pushAlways (\a -> foldDyn (:) [a] e) e
let b = current (join (fmap distributeListOverDynPure d))
return (b, e)
, (,) "joinDyn" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do
bb <- hold "b" e
bd <- hold never . fmap (const e) =<< headE e
eOuter <- pushAlways sample . fmap (const bb) <$> headE e
let eInner = switch bd
e' = leftmost [eOuter, eInner]
return (b, e')
, (,) "holdUniqDyn-laziness" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList (zip [1 :: Int ..] [1 :: Int, 2, 2, 3, 3, 3, 4, 4, 4, 4])) $ \(_, e :: Event t Int) -> do
rec result <- holdUniqDyn d
d <- holdDyn (0 :: Int) e
return (current result, updated result)
{-
, (,) "mergeIncrementalWithMove" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, PatchDMapWithMove.moveDMapKey LeftTag RightTag), (2, mempty)]) $ \(b, e :: Event t (PatchDMapWithMove (EitherTag () ()) (Const2 () ()))) -> do
x <- holdIncremental (DMap.singleton LeftTag $ void e) $ PatchDMapWithMove.mapPatchDMapWithMove (\(Const2 _) -> void e) <$> e
let e' = mergeIncrementalWithMove x :: Event t (DMap (EitherTag () ()) Identity)
return (b, e')
-}
]
splitRecombineEvent :: Reflex t => Event t a -> Event t String
splitRecombineEvent e =
let ea = "a" <$ e
eb = "b" <$ e
in leftmost [ea, eb]
main :: IO ()
main = do
results <- forM testCases $ \(name, TestCase inputs builder) -> do
putStrLn $ "Test: " <> name
testAgreement builder inputs
exitWith $ if and results
then ExitSuccess
else ExitFailure 1
|
reflex-frp/reflex
|
test/Reflex/Test/CrossImpl.hs
|
bsd-3-clause
| 12,834 | 0 | 25 | 3,144 | 5,604 | 2,946 | 2,658 | 235 | 2 |
module Database.Persist.Class.Extra where
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Trans.Reader (ReaderT)
import Database.Persist.Class
import Database.Persist.Types
import Prelude
-- Like insertBy, but only return the Key if the Entity exists, not the whole Entity
insertBy' :: (MonadIO m, PersistEntity val, PersistUnique backend, PersistEntityBackend val ~ backend)
=> val
-> ReaderT backend m (Key val)
insertBy' = fmap (either entityKey id) . insertBy
|
mitchellwrosen/dohaskell
|
src/Database/Persist/Class/Extra.hs
|
bsd-3-clause
| 503 | 0 | 9 | 85 | 122 | 70 | 52 | 10 | 1 |
{-# LANGUAGE CPP, OverloadedStrings #-}
-- | This module provides remote monitoring of a running process over
-- HTTP. It can be used to run an HTTP server that provides both a
-- web-based user interface and a machine-readable API (e.g. JSON.)
-- The former can be used by a human to get an overview of what the
-- program is doing and the latter can be used by automated monitoring
-- tools.
--
-- Typical usage is to start the monitoring server at program startup
--
-- > main = do
-- > forkServer "localhost" 8000
-- > ...
--
-- and then periodically check the stats using a web browser or a
-- command line tool (e.g. curl)
--
-- > $ curl -H "Accept: application/json" http://localhost:8000/
module System.Remote.Monitoring
(
-- * Required configuration
-- $configuration
-- * Security considerations
-- $security
-- * REST API
-- $api
-- * The monitoring server
Server
, serverThreadId
, serverMetricStore
, forkServer
, forkServerWith
-- * Defining metrics
-- $userdefined
, getCounter
, getGauge
, getLabel
, getDistribution
) where
import Control.Concurrent (ThreadId, myThreadId, throwTo)
import qualified Data.ByteString as S
import Data.Int (Int64)
import qualified Data.Text as T
import Data.Time.Clock.POSIX (getPOSIXTime)
import Prelude hiding (read)
import qualified System.Metrics as Metrics
import qualified System.Metrics.Counter as Counter
import qualified System.Metrics.Distribution as Distribution
import qualified System.Metrics.Gauge as Gauge
import qualified System.Metrics.Label as Label
import System.Remote.Snap
import Network.Socket (withSocketsDo)
#if __GLASGOW_HASKELL__ >= 706
import Control.Concurrent (forkFinally)
#else
import Control.Concurrent (forkIO)
import Control.Exception (SomeException, mask, try)
#endif
-- $configuration
--
-- To make full use out of this this module you must first enable GC
-- statistics collection in the run-time system. To enable GC
-- statistics collection, either run your program with
--
-- > +RTS -T
--
-- or compile it with
--
-- > -with-rtsopts=-T
--
-- The runtime overhead of @-T@ is very small so it's safe to always
-- leave it enabled.
-- $security
-- Be aware that if the server started by 'forkServer' is not bound to
-- \"localhost\" (or equivalent) anyone on the network can access the
-- monitoring server. Either make sure the network is secure or bind
-- the server to \"localhost\".
-- $api
-- To use the machine-readable REST API, send an HTTP GET request to
-- the host and port passed to 'forkServer'.
--
-- The API is versioned to allow for API evolution. This document is
-- for version 1. To ensure you're using this version, append @?v=1@
-- to your resource URLs. Omitting the version number will give you
-- the latest version of the API.
--
-- The following resources (i.e. URLs) are available:
--
-- [\/] JSON object containing all metrics. Metrics are stored as
-- nested objects, with one new object layer per \".\" in the metric
-- name (see example below.) Content types: \"text\/html\" (default),
-- \"application\/json\"
--
-- [\/\<namespace\>/\<metric\>] JSON object for a single metric. The
-- metric name is created by converting all \"\/\" to \".\". Example:
-- \"\/foo\/bar\" corresponds to the metric \"foo.bar\". Content
-- types: \"application\/json\"
--
-- Each metric is returned as an object containing a @type@ field. Available types
-- are:
--
-- * \"c\" - 'Counter.Counter'
--
-- * \"g\" - 'Gauge.Gauge'
--
-- * \"l\" - 'Label.Label'
--
-- * \"d\" - 'Distribution.Distribution'
--
-- In addition to the @type@ field, there are metric specific fields:
--
-- * Counters, gauges, and labels: the @val@ field contains the
-- actual value (i.e. an integer or a string).
--
-- * Distributions: the @mean@, @variance@, @count@, @sum@, @min@,
-- and @max@ fields contain their statistical equivalents.
--
-- Example of a response containing the metrics \"myapp.visitors\" and
-- \"myapp.args\":
--
-- > {
-- > "myapp": {
-- > "visitors": {
-- > "val": 10,
-- > "type": "c"
-- > },
-- > "args": {
-- > "val": "--a-flag",
-- > "type": "l"
-- > }
-- > }
-- > }
-- $userdefined
-- The monitoring server can store and serve integer-valued counters
-- and gauges, string-valued labels, and statistical distributions. A
-- counter is a monotonically increasing value (e.g. TCP connections
-- established since program start.) A gauge is a variable value (e.g.
-- the current number of concurrent connections.) A label is a
-- free-form string value (e.g. exporting the command line arguments
-- or host name.) A distribution is a statistic summary of events
-- (e.g. processing time per request.) Each metric is associated with
-- a name, which is used when it is displayed in the UI or returned in
-- a JSON object.
--
-- Metrics share the same namespace so it's not possible to create
-- e.g. a counter and a gauge with the same. Attempting to do so will
-- result in an 'error'.
--
-- To create and use a counter, simply call 'getCounter' to create it
-- and then call e.g. 'Counter.inc' or 'Counter.add' to modify its
-- value. Example:
--
-- > main = do
-- > handle <- forkServer "localhost" 8000
-- > counter <- getCounter "iterations" handle
-- > let loop n = do
-- > inc counter
-- > loop
-- > loop
--
-- To create a gauge, use 'getGauge' instead of 'getCounter' and then
-- call e.g. 'System.Remote.Gauge.set'. Similar for the other metric
-- types.
--
-- It's also possible to register metrics directly using the
-- @System.Metrics@ module in the ekg-core package. This gives you a
-- bit more control over how metric values are retrieved.
------------------------------------------------------------------------
-- * The monitoring server
-- | A handle that can be used to control the monitoring server.
-- Created by 'forkServer'.
data Server = Server {
-- | The thread ID of the server. You can kill the server by
-- killing this thread (i.e. by throwing it an asynchronous
-- exception.)
serverThreadId :: {-# UNPACK #-} !ThreadId
-- | The metric store associated with the server. If you want to
-- add metric to the default store created by 'forkServer' you
-- need to use this function to retrieve it.
, serverMetricStore :: {-# UNPACK #-} !Metrics.Store
}
-- | Like 'forkServerWith', but creates a default metric store with
-- some predefined metrics. The predefined metrics are those given in
-- 'System.Metrics.registerGcMetrics'.
forkServer :: S.ByteString -- ^ Host to listen on (e.g. \"localhost\")
-> Int -- ^ Port to listen on (e.g. 8000)
-> IO Server
forkServer host port = do
store <- Metrics.newStore
Metrics.registerGcMetrics store
forkServerWith store host port
-- | Start an HTTP server in a new thread. The server replies to GET
-- requests to the given host and port. The host argument can be
-- either a numeric network address (dotted quad for IPv4,
-- colon-separated hex for IPv6) or a hostname (e.g. \"localhost\".)
-- The client can control the Content-Type used in responses by
-- setting the Accept header. At the moment two content types are
-- available: \"application\/json\" and \"text\/html\".
--
-- Registers the following counter, used by the UI:
--
-- [@ekg.server_time_ms@] The server time when the sample was taken,
-- in milliseconds.
--
-- Note that this function, unlike 'forkServer', doesn't register any
-- other predefined metrics. This allows other libraries to create and
-- provide a metric store for use with this library. If the metric
-- store isn't created by you and the creator doesn't register the
-- metrics registered by 'forkServer', you might want to register them
-- yourself.
forkServerWith :: Metrics.Store -- ^ Metric store
-> S.ByteString -- ^ Host to listen on (e.g. \"localhost\")
-> Int -- ^ Port to listen on (e.g. 8000)
-> IO Server
forkServerWith store host port = do
Metrics.registerCounter "ekg.server_timestamp_ms" getTimeMs store
me <- myThreadId
tid <- withSocketsDo $ forkFinally (startServer store host port) $ \ r ->
case r of
Left e -> throwTo me e
Right _ -> return ()
return $! Server tid store
where
getTimeMs :: IO Int64
getTimeMs = (round . (* 1000)) `fmap` getPOSIXTime
------------------------------------------------------------------------
-- * Defining metrics
-- | Return a new, zero-initialized counter associated with the given
-- name and server. Multiple calls to 'getCounter' with the same
-- arguments will result in an 'error'.
getCounter :: T.Text -- ^ Counter name
-> Server -- ^ Server that will serve the counter
-> IO Counter.Counter
getCounter name server = Metrics.createCounter name (serverMetricStore server)
-- | Return a new, zero-initialized gauge associated with the given
-- name and server. Multiple calls to 'getGauge' with the same
-- arguments will result in an 'error'.
getGauge :: T.Text -- ^ Gauge name
-> Server -- ^ Server that will serve the gauge
-> IO Gauge.Gauge
getGauge name server = Metrics.createGauge name (serverMetricStore server)
-- | Return a new, empty label associated with the given name and
-- server. Multiple calls to 'getLabel' with the same arguments will
-- result in an 'error'.
getLabel :: T.Text -- ^ Label name
-> Server -- ^ Server that will serve the label
-> IO Label.Label
getLabel name server = Metrics.createLabel name (serverMetricStore server)
-- | Return a new distribution associated with the given name and
-- server. Multiple calls to 'getDistribution' with the same arguments
-- will result in an 'error'.
getDistribution :: T.Text -- ^ Distribution name
-> Server -- ^ Server that will serve the distribution
-> IO Distribution.Distribution
getDistribution name server =
Metrics.createDistribution name (serverMetricStore server)
------------------------------------------------------------------------
-- Backwards compatibility shims
#if __GLASGOW_HASKELL__ < 706
forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId
forkFinally action and_then =
mask $ \restore ->
forkIO $ try (restore action) >>= and_then
#endif
|
seanparsons/ekg
|
System/Remote/Monitoring.hs
|
bsd-3-clause
| 10,466 | 0 | 14 | 2,159 | 861 | 558 | 303 | 72 | 2 |
{-
(c) The University of Glasgow 2006
(c) The GRASP Project, Glasgow University, 1992-2000
Defines basic functions for printing error messages.
It's hard to put these functions anywhere else without causing
some unnecessary loops in the module dependency graph.
-}
{-# LANGUAGE CPP, ScopedTypeVariables, LambdaCase #-}
module Panic (
GhcException(..), showGhcException,
throwGhcException, throwGhcExceptionIO,
handleGhcException,
progName,
pgmError,
panic, sorry, assertPanic, trace,
panicDoc, sorryDoc, pgmErrorDoc,
Exception.Exception(..), showException, safeShowException,
try, tryMost, throwTo,
withSignalHandlers,
) where
#include "HsVersions.h"
import GhcPrelude
import {-# SOURCE #-} Outputable (SDoc, showSDocUnsafe)
import Config
import Exception
import Control.Monad.IO.Class
import Control.Concurrent
import Debug.Trace ( trace )
import System.IO.Unsafe
import System.Environment
#if !defined(mingw32_HOST_OS)
import System.Posix.Signals as S
#endif
#if defined(mingw32_HOST_OS)
import GHC.ConsoleHandler as S
#endif
import GHC.Stack
import System.Mem.Weak ( deRefWeak )
-- | GHC's own exception type
-- error messages all take the form:
--
-- @
-- <location>: <error>
-- @
--
-- If the location is on the command line, or in GHC itself, then
-- <location>="ghc". All of the error types below correspond to
-- a <location> of "ghc", except for ProgramError (where the string is
-- assumed to contain a location already, so we don't print one).
data GhcException
-- | Some other fatal signal (SIGHUP,SIGTERM)
= Signal Int
-- | Prints the short usage msg after the error
| UsageError String
-- | A problem with the command line arguments, but don't print usage.
| CmdLineError String
-- | The 'impossible' happened.
| Panic String
| PprPanic String SDoc
-- | The user tickled something that's known not to work yet,
-- but we're not counting it as a bug.
| Sorry String
| PprSorry String SDoc
-- | An installation problem.
| InstallationError String
-- | An error in the user's code, probably.
| ProgramError String
| PprProgramError String SDoc
instance Exception GhcException
instance Show GhcException where
showsPrec _ e@(ProgramError _) = showGhcException e
showsPrec _ e@(CmdLineError _) = showString "<command line>: " . showGhcException e
showsPrec _ e = showString progName . showString ": " . showGhcException e
-- | The name of this GHC.
progName :: String
progName = unsafePerformIO (getProgName)
{-# NOINLINE progName #-}
-- | Short usage information to display when we are given the wrong cmd line arguments.
short_usage :: String
short_usage = "Usage: For basic information, try the `--help' option."
-- | Show an exception as a string.
showException :: Exception e => e -> String
showException = show
-- | Show an exception which can possibly throw other exceptions.
-- Used when displaying exception thrown within TH code.
safeShowException :: Exception e => e -> IO String
safeShowException e = do
-- ensure the whole error message is evaluated inside try
r <- try (return $! forceList (showException e))
case r of
Right msg -> return msg
Left e' -> safeShowException (e' :: SomeException)
where
forceList [] = []
forceList xs@(x : xt) = x `seq` forceList xt `seq` xs
-- | Append a description of the given exception to this string.
--
-- Note that this uses 'DynFlags.unsafeGlobalDynFlags', which may have some
-- uninitialized fields if invoked before 'GHC.initGhcMonad' has been called.
-- If the error message to be printed includes a pretty-printer document
-- which forces one of these fields this call may bottom.
showGhcException :: GhcException -> ShowS
showGhcException exception
= case exception of
UsageError str
-> showString str . showChar '\n' . showString short_usage
CmdLineError str -> showString str
PprProgramError str sdoc ->
showString str . showString "\n\n" .
showString (showSDocUnsafe sdoc)
ProgramError str -> showString str
InstallationError str -> showString str
Signal n -> showString "signal: " . shows n
PprPanic s sdoc ->
panicMsg $ showString s . showString "\n\n"
. showString (showSDocUnsafe sdoc)
Panic s -> panicMsg (showString s)
PprSorry s sdoc ->
sorryMsg $ showString s . showString "\n\n"
. showString (showSDocUnsafe sdoc)
Sorry s -> sorryMsg (showString s)
where
sorryMsg :: ShowS -> ShowS
sorryMsg s =
showString "sorry! (unimplemented feature or known bug)\n"
. showString (" (GHC version " ++ cProjectVersion ++ " for " ++ TargetPlatform_NAME ++ "):\n\t")
. s . showString "\n"
panicMsg :: ShowS -> ShowS
panicMsg s =
showString "panic! (the 'impossible' happened)\n"
. showString (" (GHC version " ++ cProjectVersion ++ " for " ++ TargetPlatform_NAME ++ "):\n\t")
. s . showString "\n\n"
. showString "Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug\n"
throwGhcException :: GhcException -> a
throwGhcException = Exception.throw
throwGhcExceptionIO :: GhcException -> IO a
throwGhcExceptionIO = Exception.throwIO
handleGhcException :: ExceptionMonad m => (GhcException -> m a) -> m a -> m a
handleGhcException = ghandle
-- | Panics and asserts.
panic, sorry, pgmError :: String -> a
panic x = unsafeDupablePerformIO $ do
stack <- ccsToStrings =<< getCurrentCCS x
if null stack
then throwGhcException (Panic x)
else throwGhcException (Panic (x ++ '\n' : renderStack stack))
sorry x = throwGhcException (Sorry x)
pgmError x = throwGhcException (ProgramError x)
panicDoc, sorryDoc, pgmErrorDoc :: String -> SDoc -> a
panicDoc x doc = throwGhcException (PprPanic x doc)
sorryDoc x doc = throwGhcException (PprSorry x doc)
pgmErrorDoc x doc = throwGhcException (PprProgramError x doc)
-- | Throw a failed assertion exception for a given filename and line number.
assertPanic :: String -> Int -> a
assertPanic file line =
Exception.throw (Exception.AssertionFailed
("ASSERT failed! file " ++ file ++ ", line " ++ show line))
-- | Like try, but pass through UserInterrupt and Panic exceptions.
-- Used when we want soft failures when reading interface files, for example.
-- TODO: I'm not entirely sure if this is catching what we really want to catch
tryMost :: IO a -> IO (Either SomeException a)
tryMost action = do r <- try action
case r of
Left se ->
case fromException se of
-- Some GhcException's we rethrow,
Just (Signal _) -> throwIO se
Just (Panic _) -> throwIO se
-- others we return
Just _ -> return (Left se)
Nothing ->
case fromException se of
-- All IOExceptions are returned
Just (_ :: IOException) ->
return (Left se)
-- Anything else is rethrown
Nothing -> throwIO se
Right v -> return (Right v)
-- | We use reference counting for signal handlers
{-# NOINLINE signalHandlersRefCount #-}
#if !defined(mingw32_HOST_OS)
signalHandlersRefCount :: MVar (Word, Maybe (S.Handler,S.Handler
,S.Handler,S.Handler))
#else
signalHandlersRefCount :: MVar (Word, Maybe S.Handler)
#endif
signalHandlersRefCount = unsafePerformIO $ newMVar (0,Nothing)
-- | Temporarily install standard signal handlers for catching ^C, which just
-- throw an exception in the current thread.
withSignalHandlers :: (ExceptionMonad m, MonadIO m) => m a -> m a
withSignalHandlers act = do
main_thread <- liftIO myThreadId
wtid <- liftIO (mkWeakThreadId main_thread)
let
interrupt = do
r <- deRefWeak wtid
case r of
Nothing -> return ()
Just t -> throwTo t UserInterrupt
#if !defined(mingw32_HOST_OS)
let installHandlers = do
let installHandler' a b = installHandler a b Nothing
hdlQUIT <- installHandler' sigQUIT (Catch interrupt)
hdlINT <- installHandler' sigINT (Catch interrupt)
-- see #3656; in the future we should install these automatically for
-- all Haskell programs in the same way that we install a ^C handler.
let fatal_signal n = throwTo main_thread (Signal (fromIntegral n))
hdlHUP <- installHandler' sigHUP (Catch (fatal_signal sigHUP))
hdlTERM <- installHandler' sigTERM (Catch (fatal_signal sigTERM))
return (hdlQUIT,hdlINT,hdlHUP,hdlTERM)
let uninstallHandlers (hdlQUIT,hdlINT,hdlHUP,hdlTERM) = do
_ <- installHandler sigQUIT hdlQUIT Nothing
_ <- installHandler sigINT hdlINT Nothing
_ <- installHandler sigHUP hdlHUP Nothing
_ <- installHandler sigTERM hdlTERM Nothing
return ()
#else
-- GHC 6.3+ has support for console events on Windows
-- NOTE: running GHCi under a bash shell for some reason requires
-- you to press Ctrl-Break rather than Ctrl-C to provoke
-- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
-- why --SDM 17/12/2004
let sig_handler ControlC = interrupt
sig_handler Break = interrupt
sig_handler _ = return ()
let installHandlers = installHandler (Catch sig_handler)
let uninstallHandlers = installHandler -- directly install the old handler
#endif
-- install signal handlers if necessary
let mayInstallHandlers = liftIO $ modifyMVar_ signalHandlersRefCount $ \case
(0,Nothing) -> do
hdls <- installHandlers
return (1,Just hdls)
(c,oldHandlers) -> return (c+1,oldHandlers)
-- uninstall handlers if necessary
let mayUninstallHandlers = liftIO $ modifyMVar_ signalHandlersRefCount $ \case
(1,Just hdls) -> do
_ <- uninstallHandlers hdls
return (0,Nothing)
(c,oldHandlers) -> return (c-1,oldHandlers)
mayInstallHandlers
act `gfinally` mayUninstallHandlers
|
shlevy/ghc
|
compiler/utils/Panic.hs
|
bsd-3-clause
| 10,573 | 0 | 19 | 2,851 | 2,043 | 1,050 | 993 | 162 | 10 |
module PackageTests.CMain.Check
( checkBuild
) where
import Test.HUnit
import System.FilePath
import PackageTests.PackageTester
dir :: FilePath
dir = "PackageTests" </> "CMain"
checkBuild :: FilePath -> Test
checkBuild ghcPath = TestCase $ do
let spec = PackageSpec
{ directory = dir
, distPref = Nothing
, configOpts = []
}
buildResult <- cabal_build spec ghcPath
assertBuildSucceeded buildResult
|
DavidAlphaFox/ghc
|
libraries/Cabal/Cabal/tests/PackageTests/CMain/Check.hs
|
bsd-3-clause
| 475 | 0 | 13 | 132 | 111 | 61 | 50 | 15 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE TemplateHaskell #-}
module TH_overloaded_constraints_no_instance where
-- Test the error message when there is no instance
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
data NewType a
-- No instance for Quote NewType
quote2 :: NewType Exp
quote2 = [| 5 |]
|
sdiehl/ghc
|
testsuite/tests/th/overloaded/TH_overloaded_no_instance.hs
|
bsd-3-clause
| 326 | 0 | 5 | 47 | 41 | 29 | 12 | -1 | -1 |
module Niki () where
import Language.Haskell.Liquid.Prelude
incr x = x + 1
baz x = (x, incr x)
prop :: Bool
prop = chk $ baz n
where n = choose 100
chk (x, y) = liquidAssertB (x < y)
|
mightymoose/liquidhaskell
|
tests/pos/deppair0.hs
|
bsd-3-clause
| 190 | 0 | 7 | 47 | 94 | 52 | 42 | 8 | 1 |
module Type where
import Unbound.Generics.LocallyNameless (Alpha (..),Name)
import TyCon
data TType = VarTy
type TyName = Name TType
instance Alpha TType where
isTerm VarTy = False
|
ezyang/ghc
|
testsuite/tests/typecheck/T11824/Type.hs
|
bsd-3-clause
| 187 | 0 | 6 | 32 | 57 | 34 | 23 | 7 | 0 |
{-# LANGUAGE DataKinds #-}
module T7502 where
type S = [1,2]
|
ghc-android/ghc
|
testsuite/tests/polykinds/T7502.hs
|
bsd-3-clause
| 62 | 0 | 5 | 12 | 17 | 12 | 5 | 3 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE DeriveGeneric #-}
module Metadata(http) where
import Network.HTTP.Types
import Network.HTTP.Types.Header (hContentType)
import Network.Wai
import GHC.Generics
import Data.Text as T
import Data.Aeson
import Ledger
data Endpoint = Endpoint {
health :: Text
} deriving (Generic, Show)
instance ToJSON Endpoint
data Meta = Meta {
urls :: Endpoint,
scale :: Int,
precision :: Int
} deriving (Generic, Show)
instance ToJSON Meta
http ledger _ _ respond =
respond $
responseLBS
status200
[(hContentType, "application/json")]
(encode meta)
where
endpoint = Endpoint (T.concat [baseUri ledger, "/health"])
meta = Meta endpoint (amountScale ledger) (18 - amountScale ledger)
|
gip/cinq-cloches-ledger
|
src/Metadata.hs
|
mit
| 812 | 0 | 11 | 145 | 229 | 131 | 98 | 30 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module : Network.IRC.Client
-- Copyright : (c) 2016 Michael Walker
-- License : MIT
-- Maintainer : Michael Walker <[email protected]>
-- Stability : experimental
-- Portability : OverloadedStrings
--
-- A simple IRC client library. Typical usage will be of this form:
--
-- > run :: ByteString -> Int -> Text -> IO ()
-- > run host port nick = do
-- > let conn = plainConnection host port
-- > let cfg = defaultInstanceConfig nick & handlers %~ (yourCustomEventHandlers:)
-- > runClient conn cfg ()
--
-- You shouldn't really need to tweak anything other than the event
-- handlers, as everything has been designed to be as simple as
-- possible.
module Network.IRC.Client
( -- * Configuration
-- | The configuration is logically split into two parts: the
-- /connection/ configuration (the 'ConnectionConfig' type) and the
-- /instance/ configuration (the 'InstanceConfig' type).
--
-- - Connection configuration details how to connect to the IRC
-- server, and cannot be modified after the client has started
-- (although it can be read).
--
-- - Instance configuration is everything else: the client's
-- nick, and version, handlers for received messages, and so
-- on. It can be modified after the client has started.
-- ** Connection configuration
-- | The following values can be changed with the exported lenses:
--
-- - 'username' (default: \"irc-client\"). The username sent to
-- the server in the \"USER\" command.
--
-- - 'realname' (default: \"irc-client\"). The real name sent to
-- the server in the \"USER\" command.
--
-- - 'password' (default: @Nothing@). If set, the password sent to the
-- server in the \"PASS\" command.
--
-- - 'flood' (default: @1@). The minimum time between sending
-- messages, to avoid flooding.
--
-- - 'timeout' (default: @300@). The amount of time to wait for a
-- message from the server before locally timing out.
--
-- - 'onconnect' (default: 'defaultOnConnect'). The action to
-- perform after sending the \"USER\" and \"PASS\" commands.
--
-- - 'ondisconnect' (default: 'defaultOnDisconnect'). The action
-- to perform after disconnecting from the server
--
-- - 'logfunc' (default: 'noopLogger'). The function to log received
-- and sent messages.
ConnectionConfig
, plainConnection
, TLSConfig(..)
, tlsConnection
-- *** Logging
-- | The logging functions are told whether the message came from
-- the server or the client, and are given the raw bytestring.
, Origin(..)
, stdoutLogger
, fileLogger
, noopLogger
-- ** Instance configuration
-- | The following values can be changed with the exported lenses:
--
-- - 'nick'. The nick that 'defaultOnConnect' sends to the
-- server. This is also modified during runtime by the
-- 'welcomeNick' and 'nickMangler' default event handlers.
--
-- - 'channels' (default: @[]@). The channels that
-- 'joinOnWelcome' joins. This is also modified during runtime
-- by the 'joinHandler' default event handler.
--
-- - 'version' (default: \"irc-client-$VERSION\"). The
-- version that 'ctcpVersionHandler' sends.
--
-- - 'handlers' (default: 'defaultEventHandlers'). The list of
-- event handlers.
--
-- - 'ignore' (default: @[]@). The ignore list, events from
-- matching nicks are not handled.
, InstanceConfig
, defaultInstanceConfig
-- * Writing IRC clients
-- | With this library, IRC clients are mostly composed of event
-- handlers. Event handlers are monadic actions operating in the
-- 'IRC' monad.
, IRC
, send
, sendBS
, disconnect
, reconnect
-- ** From event handlers
, module Network.IRC.Client.Events
-- ** From the outside
-- | The 'ConnectionConfig', 'InstanceConfig', and some other stuff
-- are combined in the 'IRCState' type. This can be used to interact
-- with a client from the outside, by providing a way to run @IRC s
-- a@ actions.
, IRCState
, getIRCState
, runIRCAction
, ConnectionState(..)
, getConnectionState
-- * Execution
, runClient
-- | If an 'IRCState' is constructed with 'newIRCState' and a client
-- started with 'runClientWith', then 'runIRCAction' can be used to
-- interact with that client.
, newIRCState
, runClientWith
-- | If the client times out from the server, the 'Timeout'
-- exception will be thrown, killing it.
, Timeout(..)
-- * Concurrency
-- | A client can manage a collection of threads, which get thrown
-- the 'Disconnect' exception whenever the client disconnects for
-- any reason (including a call to 'reconnect'). These can be
-- created from event handlers to manage long-running tasks.
, U.fork
, Disconnect(..)
-- * Lenses
, module Network.IRC.Client.Lens
-- * Utilities
, module Network.IRC.Client.Utils
, C.rawMessage
, C.toByteString
) where
import Control.Concurrent.STM (newTVarIO)
import Control.Concurrent.STM.TBMChan (newTBMChanIO)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.ByteString (ByteString)
import qualified Data.Conduit.Network.TLS as TLS
import qualified Data.Set as S
import Data.Text (Text)
import qualified Data.Text as T
import Data.Version (showVersion)
import qualified Data.X509 as X
import qualified Data.X509.CertificateStore as X
import qualified Data.X509.Validation as X
import Network.Connection as TLS (TLSSettings(..))
import qualified Network.IRC.Conduit as C
import qualified Network.TLS as TLS
import Network.IRC.Client.Events
import Network.IRC.Client.Internal
import Network.IRC.Client.Lens
-- I think exporting 'fork' with 'Disconnect' gives better documentation.
import Network.IRC.Client.Utils hiding (fork)
import qualified Network.IRC.Client.Utils as U
import qualified Paths_irc_client as Paths
-------------------------------------------------------------------------------
-- Configuration
-- | Connect to a server without TLS.
plainConnection
:: ByteString
-- ^ The hostname
-> Int
-- ^ The port
-> ConnectionConfig s
plainConnection host port_ =
setupInternal (C.ircClient port_ host) defaultOnConnect defaultOnDisconnect noopLogger host port_
-- | How to connect to a server over TLS.
data TLSConfig
= WithDefaultConfig ByteString Int
-- ^ Use @<http://hackage.haskell.org/package/irc-conduit/docs/Network-IRC-Conduit.html#t:defaultTLSConfig Network.IRC.Conduit.defaultTLSConfig>@.
| WithClientConfig TLS.TLSClientConfig
-- ^ Use the given configuration. The hostname and port are stored
-- as fields of the 'TLS.TLSClientConfig'.
| WithVerifier ByteString Int (X.CertificateStore -> TLS.ValidationCache -> X.ServiceID -> X.CertificateChain -> IO [X.FailedReason])
-- ^ Use @<http://hackage.haskell.org/package/irc-conduit/docs/Network-IRC-Conduit.html#t:defaultTLSConfig Network.IRC.Conduit.defaultTLSConfig>@,
-- with the given certificate verifier. The certificate verifier is
-- a function which returns a list of reasons to reject the
-- certificate.
-- | Connect to a server with TLS.
tlsConnection
:: TLSConfig
-- ^ How to initiate the TLS connection
-> ConnectionConfig s
tlsConnection (WithDefaultConfig host port_) =
setupInternal (C.ircTLSClient port_ host) defaultOnConnect defaultOnDisconnect noopLogger host port_
tlsConnection (WithClientConfig cfg) =
setupInternal (C.ircTLSClient' cfg) defaultOnConnect defaultOnDisconnect noopLogger host port_
where
host = TLS.tlsClientHost cfg
port_ = TLS.tlsClientPort cfg
tlsConnection (WithVerifier host port_ verifier) =
setupInternal (C.ircTLSClient' cfg) defaultOnConnect defaultOnDisconnect noopLogger host port_
where
cfg =
let cfg0 = C.defaultTLSConfig port_ host
-- this is a partial pattern match, but because I'm the
-- author of irc-conduit I can do this.
TLS.TLSSettings cTLSSettings = TLS.tlsClientTLSSettings cfg0
cHooks = TLS.clientHooks cTLSSettings
in cfg0 { TLS.tlsClientTLSSettings = TLS.TLSSettings cTLSSettings
{ TLS.clientHooks = cHooks
{ TLS.onServerCertificate = verifier }
}
}
-- | Construct a default IRC configuration from a nick
defaultInstanceConfig
:: Text
-- ^ The nick
-> InstanceConfig s
defaultInstanceConfig n = InstanceConfig
{ _nick = n
, _channels = []
, _version = T.append "irc-client-" (T.pack $ showVersion Paths.version)
, _handlers = defaultEventHandlers
, _ignore = []
}
-------------------------------------------------------------------------------
-- Execution
-- | Connect to the IRC server and run the client: receiving messages
-- and handing them off to handlers as appropriate.
runClient :: MonadIO m
=> ConnectionConfig s
-> InstanceConfig s
-> s
-- ^ The initial value for the user state.
-> m ()
runClient cconf iconf ustate = newIRCState cconf iconf ustate >>= runClientWith
-- | Like 'runClient', but use the provided initial
-- 'IRCState'.
--
-- Multiple clients should not be run with the same 'IRCState'. The
-- utility of this is to be able to run @IRC s a@ actions in order to
-- interact with the client from the outside.
runClientWith :: MonadIO m => IRCState s -> m ()
runClientWith = runIRCAction runner
-------------------------------------------------------------------------------
-- State
-- | Construct a new IRC state
newIRCState :: MonadIO m
=> ConnectionConfig s
-> InstanceConfig s
-> s
-- ^ The initial value for the user state.
-> m (IRCState s)
newIRCState cconf iconf ustate = liftIO $ IRCState cconf
<$> newTVarIO ustate
<*> newTVarIO iconf
<*> (newTVarIO =<< newTBMChanIO 16)
<*> newTVarIO Disconnected
<*> newTVarIO S.empty
|
barrucadu/irc-client
|
Network/IRC/Client.hs
|
mit
| 10,246 | 0 | 15 | 2,345 | 1,097 | 685 | 412 | 111 | 1 |
{-|
Description: Implementation of Nix's base32 encoding.
-}
module System.Nix.Base32 where
import qualified Data.ByteString as BS
import qualified Data.Text as T
import qualified Data.Vector as V
-- | Encode a 'BS.ByteString' in Nix's base32 encoding
encode :: BS.ByteString -> T.Text
encode c = T.pack $ map char32 [nChar - 1, nChar - 2 .. 0]
where
digits32 = V.fromList "0123456789abcdfghijklmnpqrsvwxyz"
-- Each base32 character gives us 5 bits of information, while
-- each byte gives is 8. Because 'div' rounds down, we need to add
-- one extra character to the result, and because of that extra 1
-- we need to subtract one from the number of bits in the
-- bytestring to cover for the case where the number of bits is
-- already a factor of 5. Thus, the + 1 outside of the 'div' and
-- the - 1 inside of it.
nChar = fromIntegral $ ((BS.length c * 8 - 1) `div` 5) + 1
byte = BS.index c . fromIntegral
-- May need to switch to a more efficient calculation at some
-- point.
bAsInteger :: Integer
bAsInteger = sum [fromIntegral (byte j) * (256 ^ j)
| j <- [0 .. BS.length c - 1]
]
char32 :: Integer -> Char
char32 i = digits32 V.! digitInd
where
digitInd = fromIntegral $
bAsInteger
`div` (32^i)
`mod` 32
|
shlevy/hnix-store
|
hnix-store-core/src/System/Nix/Base32.hs
|
mit
| 1,425 | 0 | 15 | 439 | 267 | 155 | 112 | 18 | 1 |
module Run (run) where
import Control.Exception (finally)
import System.Exit
import System.IO (Handle)
import Util (ifM)
import Options (Mode(..))
import qualified Options
import qualified Lock
import Config (Config)
import qualified Action
import Cipher (Cipher)
run :: Config -> (FilePath -> Cipher) -> Handle -> [String] -> IO ()
run conf cipher h args = do
opts <- Options.get args
let c = cipher $ Options.databaseFile opts
runAction = Action.runAction (Action.mkEnv conf c h)
case Options.mode opts of
Help -> Options.printHelp
Add url -> withLock $ runAction $ Action.add url (Options.userName opts)
Query s -> runAction $ Action.query s (maybe 1 id $ Options.repeatCount opts) (Options.passwordOnly opts)
List p -> runAction $ Action.list p
Edit -> withLock $ Action.edit c
Dump -> runAction $ Action.dump
AcquireLock -> ifM Lock.acquire exitSuccess failOnLock
ReleaseLock -> ifM Lock.release exitSuccess exitFailure
where
withLock action = ifM Lock.acquire (action `finally` Lock.release) failOnLock
failOnLock = error "Acquiring lock failed!"
|
beni55/pwsafe
|
src/Run.hs
|
mit
| 1,273 | 0 | 15 | 371 | 396 | 204 | 192 | 27 | 8 |
-- | Http GET requests with exceptions handled in the preferred way.
module Shiva.Get (httpGet) where
import Shiva.Config (ShivaException (..))
import Control.Monad.Catch (throwM, try)
import Data.ByteString.Lazy (toStrict)
import Data.Text (Text, unpack)
import Data.Text.Encoding (decodeUtf8')
import Network.HTTP.Conduit (simpleHttp)
httpGet :: Text -> IO Text
httpGet url = do
mbs <- try . simpleHttp $ unpack url
bs <- either (throwM . NetworkException) pure mbs
either (throwM . TextException) pure $ decodeUtf8' (toStrict bs)
|
BlackBrane/shiva
|
src/Shiva/Get.hs
|
mit
| 570 | 0 | 10 | 109 | 173 | 96 | 77 | 12 | 1 |
{-|
Description : Cryptographic hashing interface for hnix-store, on top
of the cryptohash family of libraries.
-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExistentialQuantification #-}
module System.Nix.Internal.Hash where
import qualified Crypto.Hash.MD5 as MD5
import qualified Crypto.Hash.SHA1 as SHA1
import qualified Crypto.Hash.SHA256 as SHA256
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base16 as Base16
import Data.Bits (xor)
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Hashable as DataHashable
import Data.List (foldl')
import Data.Proxy (Proxy(Proxy))
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Word (Word8)
import GHC.TypeLits (Nat, KnownNat, natVal)
import qualified System.Nix.Base32 as Base32
-- | The universe of supported hash algorithms.
--
-- Currently only intended for use at the type level.
data HashAlgorithm
= MD5
| SHA1
| SHA256
| Truncated Nat HashAlgorithm
-- ^ The hash algorithm obtained by truncating the result of the
-- input 'HashAlgorithm' to the given number of bytes. See
-- 'truncateDigest' for a description of the truncation algorithm.
-- | The result of running a 'HashAlgorithm'.
newtype Digest (a :: HashAlgorithm) =
Digest BS.ByteString deriving (Show, Eq, Ord, DataHashable.Hashable)
-- | The primitive interface for incremental hashing for a given
-- 'HashAlgorithm'. Every 'HashAlgorithm' should have an instance.
class ValidAlgo (a :: HashAlgorithm) where
-- | The incremental state for constructing a hash.
type AlgoCtx a
-- | Start building a new hash.
initialize :: AlgoCtx a
-- | Append a 'BS.ByteString' to the overall contents to be hashed.
update :: AlgoCtx a -> BS.ByteString -> AlgoCtx a
-- | Finish hashing and generate the output.
finalize :: AlgoCtx a -> Digest a
-- | A 'HashAlgorithm' with a canonical name, for serialization
-- purposes (e.g. SRI hashes)
class NamedAlgo (a :: HashAlgorithm) where
algoName :: Text
instance NamedAlgo 'MD5 where
algoName = "md5"
instance NamedAlgo 'SHA1 where
algoName = "sha1"
instance NamedAlgo 'SHA256 where
algoName = "sha256"
-- | A digest whose 'NamedAlgo' is not known at compile time.
data SomeNamedDigest = forall a . NamedAlgo a => SomeDigest (Digest a)
-- | Hash an entire (strict) 'BS.ByteString' as a single call.
--
-- For example:
-- > let d = hash "Hello, sha-256!" :: Digest SHA256
-- or
-- > :set -XTypeApplications
-- > let d = hash @SHA256 "Hello, sha-256!"
hash :: forall a.ValidAlgo a => BS.ByteString -> Digest a
hash bs =
finalize $ update @a (initialize @a) bs
-- | Hash an entire (lazy) 'BSL.ByteString' as a single call.
--
-- Use is the same as for 'hash'. This runs in constant space, but
-- forces the entire bytestring.
hashLazy :: forall a.ValidAlgo a => BSL.ByteString -> Digest a
hashLazy bsl =
finalize $ foldl' (update @a) (initialize @a) (BSL.toChunks bsl)
-- | Encode a 'Digest' in the special Nix base-32 encoding.
encodeBase32 :: Digest a -> T.Text
encodeBase32 (Digest bs) = Base32.encode bs
-- | Encode a 'Digest' in hex.
encodeBase16 :: Digest a -> T.Text
encodeBase16 (Digest bs) = T.decodeUtf8 (Base16.encode bs)
-- | Uses "Crypto.Hash.MD5" from cryptohash-md5.
instance ValidAlgo 'MD5 where
type AlgoCtx 'MD5 = MD5.Ctx
initialize = MD5.init
update = MD5.update
finalize = Digest . MD5.finalize
-- | Uses "Crypto.Hash.SHA1" from cryptohash-sha1.
instance ValidAlgo 'SHA1 where
type AlgoCtx 'SHA1 = SHA1.Ctx
initialize = SHA1.init
update = SHA1.update
finalize = Digest . SHA1.finalize
-- | Uses "Crypto.Hash.SHA256" from cryptohash-sha256.
instance ValidAlgo 'SHA256 where
type AlgoCtx 'SHA256 = SHA256.Ctx
initialize = SHA256.init
update = SHA256.update
finalize = Digest . SHA256.finalize
-- | Reuses the underlying 'ValidAlgo' instance, but does a
-- 'truncateDigest' at the end.
instance (ValidAlgo a, KnownNat n) => ValidAlgo ('Truncated n a) where
type AlgoCtx ('Truncated n a) = AlgoCtx a
initialize = initialize @a
update = update @a
finalize = truncateDigest @n . finalize @a
-- | Bytewise truncation of a 'Digest'.
--
-- When truncation length is greater than the length of the bytestring
-- but less than twice the bytestring length, truncation splits the
-- bytestring into a head part (truncation length) and tail part
-- (leftover part), right-pads the leftovers with 0 to the truncation
-- length, and combines the two strings bytewise with 'xor'.
truncateDigest
:: forall n a.(KnownNat n) => Digest a -> Digest ('Truncated n a)
truncateDigest (Digest c) =
Digest $ BS.pack $ map truncOutputByte [0.. n-1]
where
n = fromIntegral $ natVal (Proxy @n)
truncOutputByte :: Int -> Word8
truncOutputByte i = foldl' (aux i) 0 [0 .. BS.length c - 1]
inputByte :: Int -> Word8
inputByte j = BS.index c (fromIntegral j)
aux :: Int -> Word8 -> Int -> Word8
aux i x j = if j `mod` fromIntegral n == fromIntegral i
then xor x (inputByte $ fromIntegral j)
else x
|
shlevy/hnix-store
|
hnix-store-core/src/System/Nix/Internal/Hash.hs
|
mit
| 5,575 | 0 | 11 | 1,238 | 1,107 | 627 | 480 | 89 | 2 |
type info = (id, position) -> string
(setq liquid-tip-info hdevtools-info)
(setq liquid-tip-info liquidhaskell-info)
hdevtoolsInfo :: info
liquidInfo :: info
|
UCSD-PL/230-web
|
static/foo.hs
|
mit
| 165 | 4 | 5 | 26 | 38 | 28 | 10 | -1 | -1 |
{-|
Module: Flaw.UI.VisualElement
Description: Adapter for Visual to use it as Element.
License: MIT
-}
module Flaw.UI.VisualElement
( VisualElement(..)
, newVisualElement
) where
import Control.Concurrent.STM
import Flaw.Math
import Flaw.UI
import Flaw.UI.Drawer
data VisualElement = VisualElement
{ visualElementVisual :: !SomeVisual
, visualElementSizeVar :: !(TVar Size)
}
newVisualElement :: Visual v => v -> STM VisualElement
newVisualElement visual = do
sizeVar <- newTVar $ Vec2 0 0
return VisualElement
{ visualElementVisual = SomeVisual visual
, visualElementSizeVar = sizeVar
}
instance Element VisualElement where
layoutElement VisualElement
{ visualElementSizeVar = sizeVar
} = writeTVar sizeVar
dabElement _ _ = return False
elementMouseCursor _ = return MouseCursorArrow
renderElement VisualElement
{ visualElementVisual = SomeVisual visual
, visualElementSizeVar = sizeVar
} drawer@Drawer
{ drawerStyles = DrawerStyles
{ drawerFlatStyleVariant = StyleVariant
{ styleVariantNormalStyle = style
}
}
} position = do
size <- readTVar sizeVar
renderVisual visual drawer position size style
processInputEvent _ _ _ = return False
|
quyse/flaw
|
flaw-ui/Flaw/UI/VisualElement.hs
|
mit
| 1,248 | 0 | 16 | 258 | 288 | 151 | 137 | 37 | 1 |
euler005 :: Int -> Int
euler005 n = foldr1 lcm [1..n]
main :: IO ()
main = print $ euler005 20
|
marknsikora/euler
|
euler005/euler005.hs
|
mit
| 96 | 0 | 6 | 22 | 50 | 25 | 25 | 4 | 1 |
-- Copyright (c) Microsoft. All rights reserved.
-- Licensed under the MIT license. See LICENSE file in the project root for full license information.
{-# LANGUAGE RecordWildCards #-}
module Tests.Codegen
( verifyCodegen
, verifyCppCodegen
, verifyCsCodegen
) where
import System.FilePath
import System.Environment (withArgs)
import Control.Monad
import Data.Monoid
import Prelude
import Data.Text.Lazy (Text, unpack)
import Test.HUnit
import Bond.Template.Util
import Bond.Template.Cpp.Reflection_h
import Bond.Template.Cpp.Types_h
import Bond.Template.Cpp.Apply_h
import Bond.Template.Cpp.Apply_cpp
import Bond.Template.Cpp.Enum_h
import Bond.Template.Cpp.Types_cpp
import Bond.Template.Cs.Types_cs
import Bond.Template.TypeMapping
import Bond.Template.CustomMapping
import Bond.Schema.Types (Bond(..), Import, Declaration)
import Bond.Parser
import Options
import Files
import Tests.Util
type Template = MappingContext -> String -> [Import] -> [Declaration] -> (String, Text)
verifyCppCodegen :: FilePath -> Assertion
verifyCppCodegen = verifyCodegen ["c++"]
verifyCsCodegen :: FilePath -> Assertion
verifyCsCodegen = verifyCodegen ["c#"]
verifyCodegen :: [String] -> FilePath -> Assertion
verifyCodegen args baseName = do
options <- withArgs args getOptions
case options of
Cpp {..} -> verifyCppFiles options baseName
Cs {..} -> verifyCsFiles options baseName
_ -> assert False
verifyCppFiles :: Options -> FilePath -> Assertion
verifyCppFiles options@Cpp {..} = do
let typeMapping = maybe cppTypeMapping cppCustomAllocTypeMapping allocator
verifyFiles options typeMapping $
[ reflection_h
, types_cpp
, types_h header enum_header allocator
, apply_h protocols apply_attribute
, apply_cpp protocols
]
where
protocols =
[ Protocol "CompactBinaryReader" "CompactBinaryWriter"
, Protocol "FastBinaryReader" "FastBinaryWriter"
, Protocol "SimpleBinaryReader" "SimpleBinaryWriter"
]
verifyCsFiles :: Options -> FilePath -> Assertion
verifyCsFiles options@Cs {..} = do
let typeMapping = if collection_interfaces then csInterfaceTypeMapping else csTypeMapping
verifyFiles options typeMapping
[ types_cs readonly_properties fields
]
verifyFiles :: Options -> TypeMapping -> [Template] -> FilePath -> Assertion
verifyFiles options typeMapping templates baseName = do
aliasMapping <- parseAliasMappings $ using options
namespaceMapping <- parseNamespaceMappings $ namespace options
(Bond imports namespaces declarations) <- parseBondFile [] $ "tests" </> "schema" </> baseName <.> "bond"
let mappingContext = MappingContext typeMapping aliasMapping namespaceMapping namespaces
forM_ templates $ \template -> do
let (suffix, code) = template mappingContext baseName imports declarations
let fileName = baseName ++ suffix
expected <- readFile $ "tests" </> "generated" </> fileName
let actual = unpack code
let msg = "Generated `" ++ fileName ++ "` doesn't match:\n\n" ++ stringDiff actual expected
assertBool msg (actual == expected)
|
innovimax/bond
|
compiler/tests/Tests/Codegen.hs
|
mit
| 3,182 | 0 | 16 | 603 | 764 | 407 | 357 | 70 | 3 |
module Main where
import Data.List
import Control.Monad
import Text.Parsec
import Text.Parsec.String (Parser)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import System.Environment
import System.Timeout
import Control.Monad
import Control.Exception
import Control.Concurrent
import Network.Socket
import qualified Network.Socket.ByteString as BS
import Network.URI
import Network.Mime
import qualified Filesystem as FS
import qualified Filesystem.Path as Path
import qualified Filesystem.Path.CurrentOS as Path
ignore :: Monad m => m ()
ignore = return ()
ofShow :: Show a => a -> Parser a
ofShow x = do
string (show x)
return x
newtype Uri = Uri String deriving (Show, Eq)
uri :: Parser URI
uri = do
s <- many1 (noneOf " ")
case parseRelativeReference s of
Nothing -> unexpected "Invalid URI."
Just uri -> return uri
data StdHttpMethod = OPTIONS
| GET
| HEAD
| POST
| PUT
| DELETE
| TRACE
| CONNECT
deriving (Show, Eq, Enum)
data HttpMethod = StandardMethod StdHttpMethod
| GenericMethod String
deriving (Show, Eq)
standardMethod :: Parser HttpMethod
standardMethod = do
m <- choice methods
return (StandardMethod m)
where
methods = map ofShow [OPTIONS .. CONNECT]
genericMethod :: Parser HttpMethod
genericMethod = do
m <- many1 (oneOf ['A'..'Z'])
return (GenericMethod m)
method :: Parser HttpMethod
method = standardMethod <|> genericMethod
data HttpHeader = GenericHttpHeader String String deriving (Show, Eq)
headerKeyChars :: [Char]
headerKeyChars = ['\32'..'\127'] \\ "()<>@,;:\\\"/[]?={} "
endl :: Parser ()
endl = do
optional (char '\r')
char '\n' >> ignore
genericHeader :: Parser HttpHeader
genericHeader = do
k <- many1 (oneOf headerKeyChars)
string ": "
v <- many1 (noneOf "\r\n")
endl
let h = GenericHttpHeader k v
return h
headers :: Parser [HttpHeader]
headers = many genericHeader
fromHeader :: HttpHeader -> String
fromHeader (GenericHttpHeader k v) = k ++ ": " ++ v ++ "\r\n"
fromHeaders :: [HttpHeader] -> String
fromHeaders hs = concat $ map fromHeader hs
data HttpRequest = HttpRequest { reqMethod :: HttpMethod
, reqURI :: URI
, reqVersion :: String
, reqHeaders :: [HttpHeader]
} deriving (Show)
version :: Parser String
version = string "HTTP/1.1"
request :: Parser HttpRequest
request = do
m <- method
space
u <- uri
space
v <- version
endl
hs <- headers
endl
let req = HttpRequest m u v hs
return req
data StatusCode = StatusCode Int String deriving (Show, Eq)
fromStatusCode :: StatusCode -> String
fromStatusCode (StatusCode i s) = show i ++ " " ++ s
data HttpResponse = HttpResponse { resVersion :: String
, resStatus :: StatusCode
, resHeaders :: [HttpHeader]
, resBody :: Maybe BS.ByteString
} deriving (Show)
sendResponse :: HttpResponse -> Socket -> IO ()
sendResponse res sock = do
BS.sendAll sock (BS8.pack responseHead)
case resBody res of
Nothing -> ignore
Just body -> BS.sendAll sock body
where
responseHead = resVersion res ++ " "
++ fromStatusCode (resStatus res) ++ "\r\n"
++ fromHeaders (resHeaders res) ++ "\r\n"
server sock addr = do
bind sock (addrAddress addr)
listen sock sOMAXCONN
tid <- forkOS $ forever $ do
(client, clientAddr) <- accept sock
putStrLn $ ("Client: " ++ show clientAddr)
forkIO $ do
msgM <- timeout 5000000 (recv client 4096)
handleMessage client msgM
close client
_ <- getLine
killThread tid
putStrLn "Bye."
where
handleMessage _ Nothing = putStrLn "Request timeout."
handleMessage _ (Just "") = putStrLn "Client left."
handleMessage client (Just msg) = do
res <-
case (parse request "stdin" msg) of
Left err -> badRequest err
Right req -> catch (process req) (ise req)
sendResponse res client
defaultHeaders = [GenericHttpHeader "Connection" "close"]
badRequest e = do
let err = show e
return $ HttpResponse "HTTP/1.1" (StatusCode 400 "Bad Request") defaultHeaders (Just $ BS8.pack err)
ise req (SomeException e) = do
let err = show e
return $ HttpResponse "HTTP/1.1" (StatusCode 500 "Internal Server Error") defaultHeaders (Just $ BS8.pack err)
process req = do
let path = Path.decodeString $ uriPath $ reqURI req
isDir <- FS.isDirectory path
if isDir then
dirList path
else
fileRes path
dirList path = do
entries <- FS.listDirectory path
let body = BS8.pack $ unlines $ map Path.encodeString entries
let hs = defaultHeaders
++ [GenericHttpHeader "Content-Type" "text/plain"]
++ [GenericHttpHeader "Content-Length" (show $ BS.length body)]
return $ HttpResponse "HTTP/1.1" (StatusCode 200 "OK") hs (Just body)
fileRes path = do
bytes <- FS.readFile path
let body = bytes
let mime = T.unpack $ T.decodeUtf8 $ defaultMimeLookup (T.pack $ Path.encodeString path)
let hs = defaultHeaders
++ [GenericHttpHeader "Content-Type" mime]
++ [GenericHttpHeader "Content-Length" (show $ BS.length body)]
return $ HttpResponse "HTTP/1.1" (StatusCode 200 "OK") hs (Just bytes)
main = do
[addr, portS] <- getArgs
let hints = defaultHints { addrFlags = [AI_ADDRCONFIG, AI_CANONNAME] }
addrs <- getAddrInfo (Just hints) (Just addr) (Just portS)
let addr = head addrs
putStrLn $ ("Addr: " ++ show addr)
sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
server sock addr
close sock
|
Garciat/SocketsToy
|
src/Main.hs
|
mit
| 6,121 | 0 | 18 | 1,744 | 1,937 | 965 | 972 | 172 | 5 |
{-# LANGUAGE DeriveGeneric #-}
module Development.Duplo.Types.AppInfo where
import Data.Aeson (FromJSON, ToJSON)
import Data.HashMap.Strict (HashMap, empty)
import GHC.Generics (Generic)
type Dependencies = HashMap String String
type Modes = HashMap String [String]
-- | App information extracted from `component.json`
data AppInfo = AppInfo
{ name :: String
, repo :: String
, version :: String
, dependencies :: Dependencies
, modes :: Maybe Modes
, images :: [String]
, scripts :: [String]
, styles :: [String]
, templates :: [String]
, fonts :: [String]
} deriving
( Show
, Generic
)
defaultAppInfo = AppInfo
{ name = ""
, repo = ""
, version = ""
, dependencies = empty
, modes = Nothing
, images = []
, scripts = []
, styles = []
, templates = []
, fonts = []
}
instance FromJSON AppInfo
instance ToJSON AppInfo
|
pixbi/duplo
|
src/Development/Duplo/Types/AppInfo.hs
|
mit
| 1,355 | 0 | 9 | 676 | 261 | 162 | 99 | 34 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Y2020.M11.D13.Solution where
{--
HI! So, we got it working! Yay! And we have the 'daters' in the 'datersbase.'
YAY!
So, now, let's represent these 'daters' visually.
Hello, Google Earth.
Google Earth is, like, the Earth, man.
(wow, that was amazing, that introduction to Google Earth, it was!)
Now, in Google Earth, then all you to share your stories, by zooming in to
particular points on the Earth, but you can also provide annotations, screen-
shots, and group these things into folders.
Perfect.
KML is an XML ... language? (extensible markup language-language? YES!) and
the documentation ... is there! And you can go to Google Earth and follow
the tutorials to create your own projects.
For us to create XML, we can use any XML library we so desire. I'm going
with my own-rolled one.
--}
import Data.Maybe (maybeToList)
import Data.XHTML hiding (P)
-- What XML are we creating? One such sample project I created by hand is HERE:
kmlDir :: FilePath
kmlDir = "Y2020/M11/D13/"
kmlSampleProject :: FilePath
kmlSampleProject = "airpowers-and-alliances.kml"
{--
But this has all the additional annotations that Google puts in there that
are very ... 'meaningful' (?) to ... somebody (?) but we don't have to
imitate, necessarily, ourselves.
So, what's the minimum we need to do to creat our own KML-file of airbases
and alliances?
Good question!
Today's #haskell problem.
Fortunately, the Internet exists (because I invented the thing), and has
some kind soul providing some bare-minimum examples of KML files:
http://dagik.org/kml_intro/E/folder.html
Let's take this story, implementing airbases and alliances, step-by-step
in a piecemeal approach to our finished result, eh?
step uno: Create a KML document that has two folders:
1. Countries by Alliance
2. Airbases by Country
write out this KML-document to a file. What does that document look like?
It looks something like this strawman:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.0">
<Document>
<open>1</open>
<Folder>
<open>1</open>
<name>New Folder</name>
<description>
This is a new folder. No, really. I'm not kidding. Oh, and go to
the <a href="http://logicaltypes.blogspot.com/">Haskell Problems page</a>.
</description>
<Placemark> <visibility>0</visibility>
<name> Near Oecho Nika.</name>
<description>The southern fields of a farm</description>
<Point>
<coordinates>135.2, 35.4, 0. </coordinates>
</Point></Placemark>
<Placemark>
<name>Nihonheso Park</name>
<description>Strolls and play in a popular family spot</description>
<Point>
<coordinates>135.0, 35.0, 0. </coordinates>
</Point></Placemark>
<Folder>
<name>A Folder in a Folder</name>
<description>
This is a folder, within a folder. Like a donut hole, in a donut's hole.
</description>
</Folder>
</Folder>
</Document>
</kml>
This file is archived at this directory as kml-playground.kml.
... but let's not do anything with Placemark at this juncture
--}
kmlPlayground :: FilePath
kmlPlayground = "kml-playground.kml"
type Description = String
data KML = KML [Key]
deriving Show
data Key = F Folder | P Placemark
deriving (Eq, Show)
data Folder = Folder Name (Maybe Description) [Key]
deriving (Eq, Show)
data Placemark = Placemark Name (Maybe Description) Point
deriving (Eq, Show)
data Point = Coord Latitude Longitude Height
deriving (Eq, Show)
type Latitude = Float
type Longitude = Float
type Height = Float
-- so that means we need an XML-representation of the above types
instance XML KML where
rep (KML content) =
Elt "kml" [Attrib "xmlns" "http://earth.google.com/kml/2.0"]
[E $ Elt "Document" [] (map (E . rep) content)]
kind = const "Keyhole Markup Language root"
instance XML Key where
rep (F folder) = rep folder
rep (P mark) = rep mark
kind (F f) = kind f
kind (P mark) = kind mark
instance XML Folder where
rep = enXMLification . F
kind = undefined
-- for Folder/Placemark enXMLification:
type Tag = String
data Thunk = Thunk Tag Name (Maybe Description) [PointOrKey]
data PointOrKey = Pt Point | K Key
instance XML PointOrKey where
rep (Pt p) = rep p
rep (K k) = rep k
kind = const "Thingie"
enThunkify :: Key -> Thunk
enThunkify (F (Folder n md ks)) = Thunk "Folder" n md (map K ks)
enThunkify (P (Placemark n md pt)) = Thunk "Placemark" n md ([Pt pt])
enXMLification :: Key -> Element
enXMLification = e' . enThunkify
e' :: Thunk -> Element
e' (Thunk tag n md as) =
Elt tag [] (map E ((mkElt "name" n):md1 ++ map rep as))
where md1 = maybeToList (Elt "Description" [] . return . S <$> md)
mkElt :: String -> String -> Element
mkElt tag content = Elt tag [] [S content]
-- You don't have to implement the below instance declarations:
instance XML Placemark where
rep = undefined
kind = undefined
instance XML Point where
rep = undefined
kind = undefined
-- but do implement the below:
skeletonKML :: FilePath -> KML -> IO ()
skeletonKML outfile = printXMLDoc . XDoc (PI "1.0")
-- what does this KML document look like as an XML file?
kmlSample :: KML
kmlSample = KML [F (Folder "Countries by Alliance" Nothing []),
F (Folder "Airbases by Country" Nothing [])]
{--
... and, in case anyone was wondering, the KML reference card is here:
https://developers.google.com/kml/documentation/kmlreference
We're going to add lines connecting same-country airbases, but this is a start.
--}
|
geophf/1HaskellADay
|
exercises/HAD/Y2020/M11/D13/Solution.hs
|
mit
| 5,521 | 0 | 13 | 1,049 | 862 | 458 | 404 | 66 | 1 |
-- typeclass type
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b -- x >> y = x >>= \_ -> y
fail :: String -> m a
fail msg = error msg
-- Maybe Monad
instance Monad Maybe where
return x = Just x
Nothing >>= f = Nothing
Just x >>= f = f x
fail _ = Nothing
-- e.g.
return "WHAT" :: Maybe String
-- Just "WHAT"
Just 9 >>= \x -> return (x*10)
-- Just 90
Nothing >>= \x -> return (x*10)
-- Nothing
(>>=) (Just 5) (\x -> Just (x * 2))
-- Just 10
Just 3 >>= (\x -> Just "!" >>= (\y -> Just (show x ++ y)))
-- Just "3!" stuff like chain
-- do notation
-- bind
foo :: Maybe String
foo = Just 3 >>= (\x ->
Just "!" >>= (\y ->
Just (show x ++ y)))
-- do
foo :: Maybe String
foo = do
x <- Just 3
y <- Just "!"
Just (show x ++ y)
-- pattern matching with do
sayH :: Maybe Char
sayH = do
(x:xs) <- Just "hello"
return x
-- If the matching falls through all the patterns for a given function, an error is thrown and our program crashes
|
djleonskennedy/learning-haskell
|
src/algebras/monad-def.hs
|
mit
| 1,091 | 3 | 14 | 350 | 448 | 226 | 222 | -1 | -1 |
module BufferTest where
import Test.HUnit
import Buffer
import qualified Data.Rope as R
import qualified Rope as R
tests :: Test
tests = test [tRenameBuffer,
tMkBufferName,
tMkBufferText,
tMove1,
tMove2,
tMove3,
tMove4,
tMovePrev1,
tMovePrev2,
tMovePrev3,
tMoveNext1,
tMoveNext2,
tMoveNext3,
tDeleteChar,
tInsertChar
]
tRenameBuffer :: Test
tRenameBuffer = "renameBuffer" ~: name (renameBuffer "new" (mkEmptyBuffer "t")) ~?= "new"
tMkBufferName :: Test
tMkBufferName = "mkBufferName" ~: name b ~?= "name"
where b = mkBuffer "name" "text"
tMkBufferText :: Test
tMkBufferText = "mkBufferText" ~: R.toString (text b) ~?= "text"
where b = mkBuffer "name" "text"
tMove1 :: Test
tMove1 = "tMove1" ~: point (move 1 b) ~?= 1
where b = mkBuffer "name" "text"
tMove2 :: Test
tMove2 = "tMove2" ~: point (move (-1) b) ~?= 0
where b = mkBuffer "name" "text"
tMove3 :: Test
tMove3 = "tMove3" ~: point (move 10 b) ~?= 3
where b = mkBuffer "name" "text"
tMove4 :: Test
tMove4 = "tMove4" ~: point (move (-1) (move 10 b)) ~?= 2
where b = mkBuffer "name" "text"
tMovePrev1 :: Test
tMovePrev1 = "tMovePrev1" ~: point (movePrevious (move 10 b)) ~?= 3
where b = mkBuffer "name" (unlines ["012345","012345"])
tMovePrev2 :: Test
tMovePrev2 = "tMovePrev2" ~: point (movePrevious (move 9 b)) ~?= 2
where b = mkBuffer "name" (unlines ["012345","012345"])
tMovePrev3 :: Test
tMovePrev3 = "tMovePrev3" ~: point (movePrevious (move 0 b)) ~?= 0
where b = mkBuffer "name" (unlines ["012345","012345"])
tMoveNext1 :: Test
tMoveNext1 = "tMoveNext1" ~: point (moveNext (move 10 b)) ~?= 13
where b = mkBuffer "name" (unlines ["012345","012345"])
tMoveNext2 :: Test
tMoveNext2 = "tMoveNext2" ~: point (moveNext (move 2 b)) ~?= 9
where b = mkBuffer "name" (unlines ["012345","012345"])
tMoveNext3 :: Test
tMoveNext3 = "tMoveNext3" ~: point (moveNext (move 0 b)) ~?= 7
where b = mkBuffer "name" (unlines ["012345","012345"])
tDeleteChar :: Test
tDeleteChar = "tDeleteChar" ~: R.toString (text (deleteChar 0 b)) ~?= "est"
where b = mkBuffer "name" "test"
tInsertChar :: Test
tInsertChar = "tInsertChar" ~: R.toString (text (insertChar 0 'a' b)) ~?= "atest"
where b = mkBuffer "name" "test"
|
awbraunstein/emonad
|
src/BufferTest.hs
|
mit
| 2,404 | 0 | 11 | 587 | 829 | 443 | 386 | 65 | 1 |
module Functions.BinaryOperation where
import Notes
import Logic.FirstOrderLogic.Macro
import Sets.Basics.Terms
import Functions.Basics.Macro
import Functions.Basics.Terms
import Functions.BinaryOperation.Macro
import Functions.BinaryOperation.Terms
binaryOperations :: Note
binaryOperations = section "Binary operations" $ do
todo "binary operations x ⨯ y -> z"
binaryOperationDefinition
associativeDefinition
todo "Left identity and right identity"
identityDefinition
identityUniqueTheorem
identityExamples
-- TODO(binary operation can go to other set than dom_
binaryOperationDefinition :: Note
binaryOperationDefinition = de $ do
lab binaryOperationDefinitionLabel
s ["A ", binaryOperation', " is a ", binaryFunction, " as follows"]
ma $ fun fun_ (dom_ ⨯ dom_) dom_
associativeDefinition :: Note
associativeDefinition = de $ do
lab associativeDefinitionLabel
s ["A ", binaryOperation, " ", m binop_ , " is called ", associative', " if ", quoted "placement of parentheses does not matter"]
ma $ fa (cs [a, b, c] ∈ dom_) ((pars $ a ★ b) ★ c) =: (a ★ (pars $ b ★ c))
exneeded
where
a = "a"
b = "b"
c = "c"
identityDefinition :: Note
identityDefinition = de $ do
let x = "X"
s ["Let", m x, "be a", set, and, m binop_, "a", binaryOperation, "on", m x]
s ["If", m x, "contains an", element, m bid_, "with the following property, that element is called an", identity']
let a = "a"
ma $ fa (a ∈ x) $ a ★ bid_ =: bid_ =: bid_ ★ a
identityUniqueTheorem :: Note
identityUniqueTheorem = thm $ do
lab identityUniqueTheoremLabel
let a = "A"
s ["If there exists an", identity, "for a", binaryOperation, m binop_, "in a", set, m a, "then it must be unique"]
proof $ do
let e = "e"
f = "f"
s ["Let", m e, and, m f, "be two", identities, "in", m a]
ma $ e =: e ★ f =: f
s ["Note that the first equation uses that", m f, "is an", identity, "and the second equation that", m e, "is an", identity]
identityExamples :: Note
identityExamples = do
exneeded
|
NorfairKing/the-notes
|
src/Functions/BinaryOperation.hs
|
gpl-2.0
| 2,197 | 7 | 15 | 556 | 649 | 340 | 309 | 52 | 1 |
{-# LANGUAGE OverloadedStrings #-}
----------------------------------------------------------------------
--
-- Module : Text.BibSpec
-- Copyright : 2015-2017 Mathias Schenner,
-- 2015-2016 Language Science Press.
-- License : GPL-3
-- Maintainer : [email protected]
--
-- Tests for the "Text.Bib" module.
----------------------------------------------------------------------
module Text.BibSpec
( tests
) where
import Data.List (intersperse)
import qualified Data.Map.Strict as M
import Data.Text (Text)
import qualified Data.Text as T
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit ((@?=))
import Text.Bib
import Text.Bib.Types
import Text.Bib.Reader.BibTeX.Reference (parseAgents, parseList)
import Text.Doc.Types
import Text.Doc.Reader.TeX (tex2inlines)
import Text.TeX (readTeX)
-------------------- tests
tests :: Test
tests = testGroup "Text.BibSpec"
[ testsNames
, testsLiteralList
, testsEntry
, testsNameConflicts
, testsMacro
, testsInheritanceXData
, testsInheritanceCrossref
, testsInheritance
, testsNormalize
, testsFormatter
]
testsNames :: Test
testsNames = testGroup "name lists"
[ testCase "First Last" $
parseAgents (readTeX "" "First Last")
@?=
[Agent [Str "First"] [] [Str "Last"] []]
, testCase "First von Last" $
parseAgents (readTeX "" "First von Last")
@?=
[Agent [Str "First"] [Str "von"] [Str "Last"] []]
, testCase "von Last" $
parseAgents (readTeX "" "von Last")
@?=
[Agent [] [Str "von"] [Str "Last"] []]
, testCase "von last" $
-- BibTeX warning: lower-case last name
parseAgents (readTeX "" "von last")
@?=
[Agent [] [Str "von"] [Str "last"] []]
, testCase "Last" $
parseAgents (readTeX "" "Last")
@?=
[Agent [] [] [Str "Last"] []]
, testCase "last" $
-- BibTeX warning: lower-case last name
parseAgents (readTeX "" "last")
@?=
[Agent [] [] [Str "last"] []]
, testCase "First von last" $
-- BibTeX warning: lower-case last name
parseAgents (readTeX "" "First von last")
@?=
[Agent [Str "First"] [Str "von"] [Str "last"] []]
, testCase "First von von last" $
-- BibTeX warning: lower-case last name
parseAgents (readTeX "" "First von von last")
@?=
[Agent [Str "First"] [Str "von", Space, Str "von"] [Str "last"] []]
, testCase "First von Last last Last" $
parseAgents (readTeX "" "First von Last last Last")
@?=
[Agent [Str "First"] [Str "von"]
[Str "Last", Space, Str "last", Space, Str "Last"] []]
, testCase "First First Last" $
parseAgents (readTeX "" "First First Last")
@?=
[Agent [Str "First", Space, Str "First"] [] [Str "Last"] []]
, testCase "Last Last, First" $
parseAgents (readTeX "" "Last Last, First")
@?=
[Agent [Str "First"] [] [Str "Last", Space, Str "Last"] []]
, testCase "{Last, last}" $
-- Comma at brace level 1 is invisible during name-breaking.
parseAgents (readTeX "" "{Last, last}")
@?=
[Agent [] [] [Str "Last,", Space, Str "last"] []]
, testCase "{Last{, }last}" $
-- Comma at brace level 2 is invisible during name-breaking.
parseAgents (readTeX "" "{Last{, }last}")
@?=
[Agent [] [] [Str "Last,", Space, Str "last"] []]
, testCase "last, First" $
-- BibTeX warning: lower-case last name
parseAgents (readTeX "" "last, First")
@?=
[Agent [Str "First"] [] [Str "last"] []]
, testCase "{von last}, First" $
-- BibTeX warning: lower-case last name
parseAgents (readTeX "" "{von last}, First")
@?=
[Agent [Str "First"] [] [Str "von", Space, Str "last"] []]
, testCase "von Last Last, First first" $
parseAgents (readTeX "" "von Last Last, First first")
@?=
[Agent [Str "First", Space, Str "first"] [Str "von"]
[Str "Last", Space, Str "Last"] []]
, testCase "von Last, Jr, First" $
parseAgents (readTeX "" "von Last, Jr, First")
@?=
[Agent [Str "First"] [Str "von"] [Str "Last"] [Str "Jr"]]
, testCase "von Last, Jr, First, First" $
-- BibTeX warning: too many commas
parseAgents (readTeX "" "von Last, Jr, First, First")
@?=
[Agent (intersperse Space (replicate 2 (Str "First")))
[Str "von"] [Str "Last"] [Str "Jr"]]
, testCase "von Last Last, Junior, First, First First, First" $
-- BibTeX warning: too many commas
parseAgents (readTeX ""
"von Last Last, Junior, First, First First, First")
@?=
[Agent (intersperse Space (replicate 4 (Str "First")))
[Str "von"] [Str "Last", Space, Str "Last"] [Str "Junior"]]
, testCase "First Last and von Last, Jr, First, First" $
-- BibTeX warning: too many commas
parseAgents (readTeX ""
"First Last and von Last, Jr, First, First")
@?=
[ Agent [Str "First"] [] [Str "Last"] []
, Agent (intersperse Space (replicate 2 (Str "First")))
[Str "von"] [Str "Last"] [Str "Jr"]]
, testCase "First Last and First Last" $
parseAgents (readTeX "" "First Last and First Last")
@?=
replicate 2 (Agent [Str "First"] [] [Str "Last"] [])
, testCase "First von Last and von Last, First" $
parseAgents (readTeX "" "First von Last and von Last, First")
@?=
replicate 2 (Agent [Str "First"] [Str "von"] [Str "Last"] [])
, testCase "one name, no commas, one 'von' part" $
parseAgents (readTeX "" "John von Neumann")
@?=
[Agent [Str "John"] [Str "von"] [Str "Neumann"] []]
, testCase "one name, one comma, one 'von' part" $
parseAgents (readTeX "" "von Neumann, John")
@?=
[Agent [Str "John"] [Str "von"] [Str "Neumann"] []]
, testCase "one name, one comma, two last names" $
parseAgents (readTeX "" "Brinch Hansen, Per")
@?=
[Agent [Str "Per"] [] [Str "Brinch", Space, Str "Hansen"] []]
, testCase "two names, no commas, no 'von' part" $
parseAgents (readTeX "" "Alfred North Whitehead and Bertrand Russell")
@?=
[ Agent [Str "Alfred", Space, Str "North"] [] [Str "Whitehead"] []
, Agent [Str "Bertrand"] [] [Str "Russell"] []]
, testCase "one name, no commas, no 'von' part, with precomposed umlaut char" $
parseAgents (readTeX "" "Kurt Gödel")
@?=
[Agent [Str "Kurt"] [] [Str "Gödel"] []]
, testCase "one name, no commas, no 'von' part, with redundant whitespace" $
parseAgents (readTeX "" " Kurt Gödel ")
@?=
[Agent [Str "Kurt"] [] [Str "Gödel"] []]
, testCase "one name, one comma, no 'von' part, with redundant whitespace in braces" $
parseAgents (readTeX "" "{ Gödel }, Kurt")
@?=
[Agent [Str "Kurt"] [] [Str "Gödel"] []]
, testCase "one name, one comma, no 'von' part, with TeX-escaped special char" $
parseAgents (readTeX "" "B{\\\"u}chner, Georg")
@?=
[Agent [Str "Georg"] [] [Str "Bu\x0308\&chner"] []]
, testCase "one company name containing hidden 'and' (at brace level 1)" $
parseAgents (readTeX "" "{Nobody and Sons, Inc.}")
@?=
[Agent [] [] (toInlines "{Nobody and Sons, Inc.}") []]
, testCase "two names, combining one visible and one hidden 'and'" $
parseAgents (readTeX "" "{National Aeronautics and Space Administration} and Doe, John")
@?=
[ Agent [] [] (toInlines "{National Aeronautics and Space Administration}") []
, Agent [Str "John"] [] [Str "Doe"] []]
, testCase "one name, no commas, multiple first, prefix and last names" $
parseAgents (readTeX "" "Charles Louis Xavier Joseph de la Vall\\'ee Poussin")
@?=
[Agent [Str "Charles", Space, Str "Louis", Space, Str "Xavier", Space, Str "Joseph"]
[Str "de", Space, Str "la"] [Str "Valle\x0301\&e", Space, Str "Poussin"] []]
, testCase "one name, no commas, with non-breaking spaces" $
parseAgents (readTeX "" "Charles Louis Xavier~Joseph de~la Vall\\'ee~Poussin")
@?=
[Agent [Str "Charles", Space, Str "Louis", Space, Str ("Xavier" ++ "\x00A0" ++ "Joseph")]
[Str ("de" ++ "\x00A0" ++ "la")] [Str ("Valle\x0301\&e" ++ "\x00A0" ++ "Poussin")] []]
]
testsLiteralList :: Test
testsLiteralList = testGroup "literal lists"
[ testCase "zero items" $
parseList (readTeX "" "")
@?=
[]
, testCase "one item" $
parseList (readTeX "" "one")
@?=
[toInlines "one"]
, testCase "two items" $
parseList (readTeX "" "one and two")
@?=
map toInlines ["one", "two"]
, testCase "three items" $
parseList (readTeX "" "one and two and three")
@?=
map toInlines ["one", "two", "three"]
, testCase "one item, with hidden 'and' in outer group" $
parseList (readTeX "" "{one and two}")
@?=
[toInlines "{one and two}"]
, testCase "one item, with hidden 'and' in inner group" $
parseList (readTeX "" "one {and} two")
@?=
[toInlines "one {and} two"]
, testCase "two items, combining visible and hidden 'and'" $
parseList (readTeX "" "{one and one} and two")
@?=
map toInlines ["{one and one}", "two"]
, testCase "delimiter 'and' must be surrounded by whitespace" $
parseList (readTeX "" "land and andy dandy")
@?=
map toInlines ["land", "andy dandy"]
, testCase "delimiter 'and' must be surrounded by whitespace" $
parseList (readTeX "" "{d}and{y}")
@?=
[toInlines "dandy"]
, testCase "delimiter 'and' must be surrounded by whitespace" $
parseList (readTeX "" "{d} and{y}")
@?=
[toInlines "{d} and{y}"]
, testCase "delimiter 'and' must be surrounded by whitespace" $
parseList (readTeX "" "{d}and {y}")
@?=
[toInlines "{d}and {y}"]
, testCase "delimiter 'and' must be surrounded by whitespace" $
parseList (readTeX "" "{d} and {y}")
@?=
map toInlines ["{d}", "{y}"]
, testCase "isolated 'and'" $
parseList (readTeX "" "and")
@?=
[]
, testCase "double isolated 'and'" $
parseList (readTeX "" "and and")
@?=
[]
, testCase "mixing visible and hidden 'and'" $
parseList (readTeX "" "and {and} and {and and} and {and}")
@?=
map toInlines ["{and}", "{and and}", "{and}"]
, testCase "empty left-hand side" $
parseList (readTeX "" "and one")
@?=
[toInlines "one"]
, testCase "empty right-hand side" $
parseList (readTeX "" "one and")
@?=
[toInlines "one"]
, testCase "white left-hand side" $
parseList (readTeX "" " and one")
@?=
[toInlines "one"]
, testCase "white right-hand side" $
parseList (readTeX "" "one and ")
@?=
[toInlines "one"]
, testCase "'others' on right-hand side" $
-- We do not (yet) treat 'others' in a special way.
parseList (readTeX "" "one and others")
@?=
map toInlines ["one", "others"]
]
testsEntry :: Test
testsEntry = testGroup "parse bib entry"
[ testCase "empty entry with braces" $
fromBibTeX "" "@book{b,}"
@?=
mkBibDB [mkBookEntry "b" []]
, testCase "empty entry with parens" $
fromBibTeX "" "@book(b,)"
@?=
mkBibDB [mkBookEntry "b" []]
, testCase "valid empty entries with mismatching delimiters" $
-- BibTeX warning: entry started with X but ends with Y
fromBibTeX "" "@book{b1,)@book(b2,}"
@?=
mkBibDB [mkBookEntry "b1" [], mkBookEntry "b2" []]
, testCase "simple entry" $
fromBibTeX "" bibFile01
@?=
mkBibDB [bibEntry01]
, testCase "simple entry with hash-separated subfields" $
fromBibTeX "" bibFile01a
@?=
mkBibDB [bibEntry01]
, testCase "entrykey (aka citekey) may start with a digit (unlike field names)" $
fromBibTeX "" "@book{4i , }"
@?=
mkBibDB [mkBookEntry "4i" []]
, testCase "entrykey (aka citekey) may be numeric (unlike field names)" $
fromBibTeX "" "@book{23,}"
@?=
mkBibDB [mkBookEntry "23" []]
, testCase "do not strip whitespace around inner group" $
fromBibTeX "" "@book{b, title = {a {b} c }}"
@?=
mkBibDB [mkBookEntry "b"
[("title", [ Str "a", Space, Str "b", Space, Str "c" ])]]
, testCase "do not add whitespace around inner group" $
fromBibTeX "" "@book{b, title = { a{b}c }}"
@?=
mkBibDB [mkBookEntry "b"
[("title", [ Str "abc" ])]]
, testCase "do not strip whitespace after inner group" $
fromBibTeX "" "@book{b, title = {a{b} c }}"
@?=
mkBibDB [mkBookEntry "b"
[("title", [ Str "ab", Space, Str "c" ])]]
, testCase "do not strip inner whitespace" $
fromBibTeX "" "@book{b, eq = 2 # { + } #2 # { } # \"= \" # {4}}"
@?=
mkBibDB [mkBookEntry "b"
[("eq", [ Str "2", Space, Str "+", Space, Str "2"
, Space, Str "=", Space, Str "4"])]]
, testCase "do not strip inner whitespace" $
fromBibTeX "" "@book{b, eq = 2#{ }#\"+\"# { } #2}"
@?=
mkBibDB [mkBookEntry "b"
[("eq", [Str "2", Space, Str "+", Space, Str "2"])]]
, testCase "conflate inner whitespace" $
fromBibTeX "" "@book{b, eq = 2 # { + } # { } # { } #2 }"
@?=
mkBibDB [mkBookEntry "b"
[("eq", [Str "2", Space, Str "+", Space, Str "2"])]]
, testCase "strip outer whitespace" $
fromBibTeX "" "@book{b, title = { } # { White } # { Space } # { } # { } }"
@?=
mkBibDB [mkBookEntry "b"
[("title", [Str "White", Space, Str "Space"])]]
, testCase "strip outer but not inner whitespace" $
fromBibTeX "" "@book{b,title = { ab } # 22 # \" cd \"}"
@?=
mkBibDB [mkBookEntry "b"
[("title", [Str "ab", Space, Str "22", Space, Str "cd"])]]
]
testsNameConflicts :: Test
testsNameConflicts = testGroup "citekey and fieldname conflicts"
[ testCase "duplicate citekeys: first one wins" $
-- BibTeX warning: duplicate entry key
fromBibTeX "" (T.concat
[ "@book{b, title={one}}"
, "@book{b, title={two}}"
, "@book{b, title={three}}"])
@?=
mkBibDB [mkBookEntry "b" [("title", [Str "one"])]]
, testCase "duplicate fieldnames: last one wins" $
-- Note: biber-2.2 does not warn about duplicate field names
fromBibTeX "" "@book{b,title={one},title={two},title={three}}"
@?=
mkBibDB [mkBookEntry "b" [("title", [Str "three"])]]
, testCase "citekeys are case-sensitive" $
fromBibTeX "" (T.concat
[ "@book{b, title={b-one}}"
, "@book{B, title={B-one}}"
, "@book{b, title={b-two}}"])
@?=
mkBibDB [ mkBookEntry "b" [("title", [Str "b-one"])]
, mkBookEntry "B" [("title", [Str "B-one"])]]
, testCase "fieldnames are case-insensitive" $
fromBibTeX "" "@book{b,title={one},TITLE={two},Title={three}}"
@?=
mkBibDB [mkBookEntry "b" [("title", [Str "three"])]]
, testCase "mixing duplicate citekeys and fieldnames" $
-- BibTeX warning: duplicate entry key
fromBibTeX "" (T.concat
[ "@book{b,title={1-1},title={1-2},title={1-3}}"
, "@book{b,title={2-1},title={2-2},title={2-3}}"
, "@book{b,title={3-1},title={3-2},title={3-3}}"])
@?=
mkBibDB [mkBookEntry "b" [("title", [Str "1-3"])]]
]
testsMacro :: Test
testsMacro = testGroup "resolve bibtex @string macros"
[ testCase "using built-in month macros" $
fromBibTeX "" "@book{b, month = aug, other=dec}"
@?=
mkBibDB [mkBookEntry "b" [("month", [Str "8"]), ("other", [Str "12"])]]
, testCase "simple macro use" $
fromBibTeX "" "@string{v={some text}}@book{b, k=v, i=v}"
@?=
let r = [Str "some", Space, Str "text"]
in mkBibDB [mkBookEntry "b" [("k", r), ("i", r)]]
, testCase "macro definition with subfields" $
fromBibTeX "" "@string{v = 2 # \"+\" #2#{=4}} @book{b, eq=v}"
@?=
mkBibDB [mkBookEntry "b" [("eq", [Str "2+2=4"])]]
, testCase "macro use with subfields" $
fromBibTeX "" "@string{v={ab}}@book{b, title = v #{-}# v #{.} }"
@?=
mkBibDB [mkBookEntry "b" [("title", [Str "ab-ab."])]]
, testCase "nested macro definition" $
fromBibTeX "" (T.concat
[ " @string{s1={a}} "
, " @string{s2=s1} "
, " @book{b, v=s2}"])
@?=
mkBibDB [mkBookEntry "b" [("v", [Str "a"])]]
, testCase "nested macro definition with subfields" $
fromBibTeX "" (T.concat
[ " @string{s1={a}} "
, " @string{s2 = s1 # s1# s1} "
, " @book{b, v=s2}"])
@?=
mkBibDB [mkBookEntry "b" [("v", [Str "aaa"])]]
, testCase "field names are not subject to expansion" $
fromBibTeX "" "@string{v={repl}}@book{b, v=v}"
@?=
mkBibDB [mkBookEntry "b" [("v", [Str "repl"])]]
, testCase "overwriting macro" $
-- BibTeX warning: overwritten macro
fromBibTeX "" (T.concat
[ "@string{s1 = {a}}"
, "@string{s1 = s1 # {b}}"
, "@string{s1 = s1 # {c}}"
, "@book{b, title = s1}"])
@?=
mkBibDB [mkBookEntry "b" [("title", [Str "abc"])]]
, testCase "overwriting built-in month macros" $
-- BibTeX warning: overwritten macro
fromBibTeX "" (T.concat
[ "@book{b1, month = feb}"
, "@string{feb = {Hornung}}"
, "@book{b2, month = feb}"])
@?=
mkBibDB [ mkBookEntry "b1" [("month", [Str "2"])]
, mkBookEntry "b2" [("month", [Str "Hornung"])]]
, testCase "no self-reference" $
-- BibTeX warning: undefined macro
fromBibTeX "" "@string{me=1#me}@book{b, v=me}"
@?=
mkBibDB [mkBookEntry "b" [("v", [Str "1"])]]
, testCase "numeric plain fields" $
fromBibTeX "" "@book{b, year = 2525, volume = 30}"
@?=
mkBibDB [mkBookEntry "b" [("year", [Str "2525"]), ("volume", [Str "30"])]]
, testCase "negative numeric plain field (treated as macro name)" $
-- BibTeX warning: undefined macro
fromBibTeX "" "@book{b, volume = -1}"
@?=
mkBibDB [mkBookEntry "b" [("volume", [])]]
, testCase "negative numeric braced field" $
fromBibTeX "" "@book{b, volume = {-1}}"
@?=
mkBibDB [mkBookEntry "b" [("volume", [Str "-1"])]]
, testCase "macro names (field names) must not start with a digit" $
-- BibTeX error: biber-2.2 throws syntax error.
-- By contrast, we simply drop any leading digits and continue.
fromBibTeX "" "@string{2={two}}@book{b,v=2}"
@?=
mkBibDB [mkBookEntry "b" [("v", [Str "2"])]]
, testCase "macro names (field names) may consist of symbols only" $
fromBibTeX "" (T.concat
[ "@string{*={star}}"
, "@string{+*+={+}}"
, "@book{b,stars=*#+*+#*}"])
@?=
mkBibDB [mkBookEntry "b" [("stars", [Str "star+star"])]]
, testCase "macro names (field names) are case-insensitive" $
fromBibTeX "" "@string{ab={aB}}@book{b,v= AB#aB#Ab#ab}"
@?=
mkBibDB [mkBookEntry "b" [("v", [Str "aBaBaBaB"])]]
, testCase "undefined macro" $
-- BibTeX warning: undefined macro
fromBibTeX "" "@book{b,v=ab#{-}#-#cd#4}"
@?=
mkBibDB [mkBookEntry "b" [("v", [Str "-4"])]]
]
testsInheritanceXData :: Test
testsInheritanceXData = testGroup "xdata inheritance"
[ testCase "remove xdata entries from bibdb" $
fromBibTeX "" "@xdata{x1, location = {here}}"
@?=
mkBibDB []
, testCase "simple xdata inheritance" $
fromBibTeX "" (T.concat
[ "@xdata{x1, title = {x1 title}, location = {Berlin}}"
, "@book{b1, author={b1-author}, xdata={x1}}"])
@?=
mkBibDB [mkEntry "b1" "book"
[ ("author", AgentList [Agent [] [] [Str "b1-author"] []])
, ("title", LiteralField [Str "x1", Space, Str "title"])
, ("location", LiteralList [[Str "Berlin"]])]]
, testCase "simple xdata inheritance, reversed entry order in source" $
fromBibTeX "" (T.concat
[ "@book{b1, author={b1-author}, xdata={x1}}"
, "@xdata{x1, title = {x1 title}, location = {Berlin}}"])
@?=
mkBibDB [mkEntry "b1" "book"
[ ("author", AgentList [Agent [] [] [Str "b1-author"] []])
, ("title", LiteralField [Str "x1", Space, Str "title"])
, ("location", LiteralList [[Str "Berlin"]])]]
, testCase "nested xdata inheritance" $
-- "b" --(xdata)-> "x1-0" --(xdata)-> "x1-1"
fromBibTeX "" (T.concat
[ "@xdata{x1-0, level1 = {x1-0}, xdata={x1-1}}"
, "@book{b, level0 = {b}, xdata={x1-0}}"
, "@xdata{x1-1, level2 = {x1-1}}"])
@?=
mkBibDB [mkBookEntry "b"
[ ("level0", [Str "b"])
, ("level1", [Str "x1-0"])
, ("level2", [Str "x1-1"])]]
, testCase "multiple xdata inheritance" $
-- "b" --(xdata)-> "x1"
-- "b" --(xdata)-> "x2"
-- Note: we assume that "xdata1" and "xdata2" have no internal meaning.
fromBibTeX "" (T.concat
[ "@xdata{x2, xdata2={x2}}"
, "@book{b, self = {b}, xdata={x1,x2}}"
, "@xdata{x1, xdata1 = {x1}}"])
@?=
mkBibDB [mkBookEntry "b"
[ ("self", [Str "b"])
, ("xdata1", [Str "x1"])
, ("xdata2", [Str "x2"])]]
, testCase "multiple nested xdata inheritance" $
-- "b" --(xdata)-> "x1" --(xdata)-> "x1-1"
-- "b" --(xdata)-> "x2" --(xdata)-> "x2-1"
fromBibTeX "" (T.concat
[ "@book{b, self = {b}, xdata={x1,x2}}"
, "@xdata{x1, xdata={x1-1}}"
, "@xdata{x1-1, first={x1-1}}"
, "@xdata{x2, xdata = {x2-1}}"
, "@xdata{x2-1, second = {x2-1}}"])
@?=
mkBibDB [mkBookEntry "b"
[ ("self", [Str "b"])
, ("first", [Str "x1-1"])
, ("second", [Str "x2-1"])]]
, testCase "name conflicts in xdata-inherited fields: right-biased resolution" $
fromBibTeX "" (T.concat
[ "@book{b1, xdata={x2,x1}}"
, "@book{b2, xdata={x1,x2}}"
, "@xdata{x1, title = {x1}}"
, "@xdata{x2, title = {x2}}"])
@?=
mkBibDB [ mkBookEntry "b1" [("title", [Str "x1"])]
, mkBookEntry "b2" [("title", [Str "x2"])]]
, testCase "inherited fields do not overwrite existing fields" $
fromBibTeX "" (T.concat
[ "@book{b1, xdata={x1,x2}, title = {self}}"
, "@book{b2, title = {self}, xdata={x1,x2}}"
, "@xdata{x1, title = {x1}}"
, "@xdata{x2, title = {x2}}"])
@?=
mkBibDB [ mkBookEntry "b1" [("title", [Str "self"])]
, mkBookEntry "b2" [("title", [Str "self"])]]
, testCase "xdata inheritance from non-xdata entries is possible" $
-- biber-2.2 allows this without warning
fromBibTeX "" (T.concat
[ "@book{x1, title = {x1}}"
, "@book{b1, author={b1-author}, xdata={x1}}"])
@?=
mkBibDB
[ mkEntry "x1" "book" -- an xdata entry in disguise
[ ("title", LiteralField [Str "x1"])]
, mkEntry "b1" "book"
[ ("author", AgentList [Agent [] [] [Str "b1-author"] []])
, ("title", LiteralField [Str "x1"])]]
, testCase "avoid direct reference cycles" $
-- biber-2.2 error: Circular XDATA inheritance
-- "x1" <--(xdata)--> "x1"
fromBibTeX "" (T.concat
[ "@xdata{x1, xdata={x1}}"
, "@book{b1, xdata={x1}}"])
@?=
mkBibDB [mkBookEntry "b1" []]
, testCase "avoid indirect reference cycles" $
-- biber-2.2 error: Circular XDATA inheritance
-- "x1" <--(xdata)--> "x2"
fromBibTeX "" (T.concat
[ "@xdata{x1, xdata={x2}}"
, "@xdata{x2, xdata={x1}}"
, "@book{b1, xdata={x1}}"])
@?=
mkBibDB [mkBookEntry "b1" []]
, testCase "avoid indirect reference cycles" $
-- biber-2.2 error: Circular XDATA inheritance
-- "x1" <--(xdata)--> "x3"
fromBibTeX "" (T.concat
[ "@xdata{x1, xdata={x2}}"
, "@xdata{x2, xdata={x3}}"
, "@xdata{x3, xdata={x1}}"
, "@book{b1, xdata={x1}}"])
@?=
mkBibDB [mkBookEntry "b1" []]
, testCase "avoid reference cycles" $
-- biber-2.2 error: Circular XDATA inheritance
-- "x1" <--(xdata)--> "x1" <--(xdata)--> "x2" <--(xdata)--> "x2"
fromBibTeX "" (T.concat
[ "@xdata{x1, xdata={x1,x2}}"
, "@xdata{x2, xdata={x1,x2}}"
, "@book{b1, xdata={x1,x2}}"])
@?=
mkBibDB [mkBookEntry "b1" []]
, testCase "xdata-inheritance does not rename fields" $
-- ... even if the referenced entry is not actually an xdata entry
fromBibTeX "" (T.concat
[ "@incollection{i1, xdata={c1}}"
, "@collection{c1, title={c1-title}}"])
@?=
mkBibDB
[ mkEntry "i1" "incollection"
[ ("title", LiteralField [Str "c1-title"]) ] -- not "booktitle"
, mkEntry "c1" "collection" -- an xdata entry in disguise
[ ("title", LiteralField [Str "c1-title"]) ]]
]
testsInheritanceCrossref :: Test
testsInheritanceCrossref = testGroup "crossref inheritance"
[ testCase "simple crossref inheritance" $
fromBibTeX "" (T.concat
[ "@InCollection{i1, title={i1 title}, crossref={c1}}"
, "@COLLECTION{c1, location={Berlin}}"])
@?=
mkBibDB
[ mkEntry "i1" "incollection"
[ ("title", LiteralField [Str "i1", Space, Str "title"])
, ("crossref", RawField "c1")
, ("location", LiteralList [[Str "Berlin"]]) ]
, mkEntry "c1" "collection"
[ ("location", LiteralList [[Str "Berlin"]]) ]]
, testCase "nested crossref inheritance" $
fromBibTeX "" (T.concat
[ "@incollection{i1, crossref={c1}, title={i1-title}}"
, "@collection{c1, booktitle={c1-booktitle}, crossref={c2}}"
, "@collection{c2, location={Berlin}}"])
@?=
mkBibDB
[ mkEntry "i1" "incollection"
[ ("title", LiteralField [Str "i1-title"])
, ("crossref", RawField "c1")
, ("booktitle", LiteralField [Str "c1-booktitle"])
, ("location", LiteralList [[Str "Berlin"]]) ]
, mkEntry "c1" "collection"
[ ("booktitle", LiteralField [Str "c1-booktitle"])
, ("crossref", RawField "c2")
, ("location", LiteralList [[Str "Berlin"]]) ]
, mkEntry "c2" "collection"
[ ("location", LiteralList [[Str "Berlin"]]) ]]
, testCase "rename selected fields" $
fromBibTeX "" (T.concat
[ "@incollection{i1, crossref={c1}, title={i1-title}}"
, "@collection{c1, title={c1-title}}"])
@?=
mkBibDB
[ mkEntry "i1" "incollection"
[ ("title", LiteralField [Str "i1-title"])
, ("crossref", RawField "c1")
, ("booktitle", LiteralField [Str "c1-title"]) ]
, mkEntry "c1" "collection"
[ ("title", LiteralField [Str "c1-title"]) ]]
, testCase "rename selected fields" $
fromBibTeX "" (T.concat
[ "@incollection{i1, crossref={c1}}"
, "@collection{c1, title={c1-title}}"])
@?=
mkBibDB
[ mkEntry "i1" "incollection"
[ ("booktitle", LiteralField [Str "c1-title"]) -- not "title"
, ("crossref", RawField "c1") ]
, mkEntry "c1" "collection"
[ ("title", LiteralField [Str "c1-title"]) ]]
, testCase "do not overwrite existing fields" $
fromBibTeX "" (T.concat
[ "@incollection{i1, booktitle={i1-booktitle},"
, " crossref={c1}, title={i1-title}}"
, "@collection{c1, title={c1-title}}"])
@?=
mkBibDB
[ mkEntry "i1" "incollection"
[ ("title", LiteralField [Str "i1-title"])
, ("crossref", RawField "c1")
, ("booktitle", LiteralField [Str "i1-booktitle"]) ]
, mkEntry "c1" "collection"
[ ("title", LiteralField [Str "c1-title"]) ]]
, testCase "do not inherit private fields" $
fromBibTeX "" (T.concat
[ "@incollection{i1, crossref={c1}, title={i1-title}}"
, "@collection{c1, title={c1-title}, label={c1-label}, xref={none}}"])
@?=
mkBibDB
[ mkEntry "i1" "incollection"
[ ("title", LiteralField [Str "i1-title"])
, ("crossref", RawField "c1")
, ("booktitle", LiteralField [Str "c1-title"]) ]
, mkEntry "c1" "collection"
[ ("title", LiteralField [Str "c1-title"])
, ("label", LiteralField [Str "c1-label"])
, ("xref", LiteralField [Str "none"]) ]]
, testCase "renamed fields overwrite existing fields in parent" $
-- with biber-2.2: if there are both "title" and "booktitle" fields in the parent,
-- then the child inherits the "title" field under the name of "booktitle".
fromBibTeX "" (T.concat
[ "@incollection{i1, crossref={c1}}"
, "@collection{c1, booktitle={c1-booktitle}, title={c1-title}}"])
@?=
mkBibDB
[ mkEntry "i1" "incollection"
[ ("crossref", RawField "c1")
, ("booktitle", LiteralField [Str "c1-title"]) ]
, mkEntry "c1" "collection"
[ ("booktitle", LiteralField [Str "c1-booktitle"])
, ("title", LiteralField [Str "c1-title"]) ]]
, testCase "renamed fields overwrite existing fields in parent" $
-- same as previous test but with reversed field order in source,
-- i.e. "title" before "booktitle".
fromBibTeX "" (T.concat
[ "@incollection{i1, crossref={c1}}"
, "@collection{c1, title={c1-title}, booktitle={c1-booktitle}}"])
@?=
mkBibDB
[ mkEntry "i1" "incollection"
[ ("crossref", RawField "c1")
, ("booktitle", LiteralField [Str "c1-title"]) ]
, mkEntry "c1" "collection"
[ ("booktitle", LiteralField [Str "c1-booktitle"])
, ("title", LiteralField [Str "c1-title"]) ]]
, testCase "parent booktitle field is inherited if it has no title field" $
fromBibTeX "" (T.concat
[ "@incollection{i1, crossref = {c1}}"
, "@collection{c1, booktitle = {c1-booktitle}}"])
@?=
mkBibDB
[ mkEntry "i1" "incollection"
[ ("crossref", RawField "c1")
, ("booktitle", LiteralField [Str "c1-booktitle"]) ]
, mkEntry "c1" "collection"
[ ("booktitle", LiteralField [Str "c1-booktitle"]) ]]
, testCase "renamed fields do not overwrite existing fields in child" $
fromBibTeX "" (T.concat
[ "@incollection{i1, booktitle={i1-booktitle}, crossref={c1}}"
, "@collection{c1, booktitle={c1-booktitle}, title={c1-title}}"])
@?=
mkBibDB
[ mkEntry "i1" "incollection"
[ ("crossref", RawField "c1")
, ("booktitle", LiteralField [Str "i1-booktitle"]) ]
, mkEntry "c1" "collection"
[ ("booktitle", LiteralField [Str "c1-booktitle"])
, ("title", LiteralField [Str "c1-title"]) ]]
, testCase "avoid direct reference cycles" $
-- biber-2.2 error: Circular inheritance
-- "i1" <--(crossref)--> "i1"
fromBibTeX "" "@incollection{i1, crossref={i1}}"
@?=
mkBibDB
[ mkEntry "i1" "incollection"
[("crossref", RawField "i1")]]
, testCase "avoid indirect reference cycles" $
-- biber-2.2 error: Circular inheritance
-- "i1" <--(crossref)--> "i2"
fromBibTeX "" (T.concat
[ "@incollection{i1, crossref={i2}}"
, "@incollection{i2, crossref={i1}}"])
@?=
mkBibDB
[ mkEntry "i1" "incollection"
[("crossref", RawField "i2")]
, mkEntry "i2" "incollection"
[("crossref", RawField "i1")]]
]
testsInheritance :: Test
testsInheritance = testGroup "xdata and crossref interaction"
[ testCase "xdata fields win over crossref fields" $
fromBibTeX "" (T.concat
[ "@xdata{x1, booktitle={x1-booktitle}}"
, "@incollection{i1, crossref={c1}, xdata={x1}}"
, "@collection{c1, title={c1-title}}"])
@?=
mkBibDB
[ mkEntry "i1" "incollection"
[ ("crossref", RawField "c1")
, ("booktitle", LiteralField [Str "x1-booktitle"]) ]
, mkEntry "c1" "collection"
[ ("title", LiteralField [Str "c1-title"]) ]]
, testCase "xdata fields win over crossref fields" $
-- same as previous test but with reversed field order in source,
-- i.e. "xdata" before "crossref".
fromBibTeX "" (T.concat
[ "@xdata{x1, booktitle={x1-booktitle}}"
, "@incollection{i1, xdata={x1}, crossref={c1}}"
, "@collection{c1, title={c1-title}}"])
@?=
mkBibDB
[ mkEntry "i1" "incollection"
[ ("crossref", RawField "c1")
, ("booktitle", LiteralField [Str "x1-booktitle"]) ]
, mkEntry "c1" "collection"
[ ("title", LiteralField [Str "c1-title"]) ]]
]
testsNormalize :: Test
testsNormalize = testGroup "normalize to biblatex model"
[ testCase "book with no author is a collection" $
fromBibTeX "" "@book{b, editor={Nobody}}"
@?=
mkBibDB [mkEntry "b" "collection"
[("editor", AgentList [Agent [] [] [Str "Nobody"] []])]]
, testCase "book with author and editor is still a book" $
fromBibTeX "" "@book{b, author={A}, editor={E}}"
@?=
mkBibDB [mkEntry "b" "book"
[ ("author", AgentList [Agent [] [] [Str "A"] []])
, ("editor", AgentList [Agent [] [] [Str "E"] []])]]
, testCase "field name \"address\" is renamed to \"location\"" $
fromBibTeX "" "@book{b, author={A}, address={Berlin}}"
@?=
mkBibDB [mkEntry "b" "book"
[ ("author", AgentList [Agent [] [] [Str "A"] []])
, ("location", LiteralList [[Str "Berlin"]])]]
, testCase "field name \"journal\" is renamed to \"journaltitle\"" $
fromBibTeX "" "@article{a, journal={NN}}"
@?=
mkBibDB [mkEntry "a" "article"
[("journaltitle", LiteralField [Str "NN"])]]
]
testsFormatter :: Test
testsFormatter = testGroup "bib formatter"
[ testCase "single cite author" $
getCiteAgents (snd bibEntry01)
@?=
[[Str "Büchner"]]
, testCase "single cite year" $
fmtCiteYear Nothing (snd bibEntry01)
@?=
[Str "1835"]
, testCase "simple full citation" $
fmtCiteFull Nothing (snd bibEntry01)
@?=
[ Str "Büchner", Str ",", Space, Str "Georg", Str ".", Space
, Str "1835", Str ".", Space, FontStyle Emph [Str "Lenz"], Str "."]
]
-------------------- helpers
-- Parse the content of a bibfield to a list of inlines.
toInlines :: String -> [Inline]
toInlines = tex2inlines . readTeX "bibfield"
-- Create a BibDB from entries, wrapped in Either,
-- as returned by 'fromBibTeX'.
mkBibDB :: [(CiteKey, BibEntry)] -> Either String BibDB
mkBibDB = return . M.fromList
-- Create a \@book entry from a citekey and a list of literal fields.
mkBookEntry :: CiteKey -> [(BibFieldName, [Inline])] -> (CiteKey, BibEntry)
mkBookEntry key fs = (key, BibEntry "book"
(M.fromList (map (fmap LiteralField) fs)))
-- Create a general entry from a citekey, an entry type name,
-- and a list of BibFields.
mkEntry :: CiteKey -> Text -> [(BibFieldName, BibFieldValue)] -> (CiteKey, BibEntry)
mkEntry key btype bfields = (key, BibEntry btype (M.fromList bfields))
-------------------- example data
bibFile01 :: Text
bibFile01 = "@book{büchner35, author = {Büchner, Georg}, title={Lenz}, year=1835}"
bibFile01a :: Text
bibFile01a = T.concat
[ "@book{büchner35,"
, " author = {Bü}#\"ch\" # {ner}#{,} #\n { Georg },"
, " title={Le} # {nz}, year=1835}"]
bibEntry01 :: (CiteKey, BibEntry)
bibEntry01 = ("büchner35", BibEntry "book" $ M.fromList
[ ("author", AgentList [Agent [Str "Georg"] [] [Str "Büchner"] []])
, ("title", LiteralField [Str "Lenz"])
, ("year", LiteralField [Str "1835"])])
|
synsem/texhs
|
test/Text/BibSpec.hs
|
gpl-3.0
| 34,334 | 0 | 17 | 8,002 | 8,823 | 4,621 | 4,202 | 805 | 1 |
{-# LANGUAGE RecordWildCards #-}
module Main
where
-------------------------------------------------------------------------------
import Data.Function (on)
import System.Environment (getArgs)
import Control.Arrow ((&&&))
import System.Random (randomRIO)
import Data.List ((\\), minimumBy)
import Data.Maybe (fromMaybe, isJust)
import Graph
import qualified Poslist as P
import Pheromones
import qualified Data.Text.Lazy.IO as T (readFile)
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar
import Control.Monad (forM)
import Process
-------------------------------------------------------------------------------
data Configuration = Configuration { graph :: !(Graph Int)
, pheromones :: !Pheromones
, path :: !Path
, pathLen :: !Int
, ants :: !Ants
, iterations :: !Iterations
, alpha :: !Alpha
, beta :: !Beta
, rho :: !Rho
}
type Ants = Int
type Iterations = Int
type Alpha = Double
type Beta = Double
type Rho = Double
type Visited = [Node]
type Unvisited = [Node]
type AntSolution = (Path, Int)
-------------------------------------------------------------------------------
-- basic processes
ant :: BasicProcess Configuration AntSolution
ant Configuration {..} = do
path <- runAnt graph pheromones [1] (nodes graph \\ [1])
return (path, pathLength' graph path)
where
runAnt :: Graph Int -> Pheromones -> Visited -> Unvisited -> IO Path
runAnt _ _ visited [] = return visited
runAnt g p visited unvisited = do
let tau = distance' p (last visited)
let eta = (1.0/) . fromIntegral . distance' g (last visited)
let probs = [tau u**alpha * eta u**beta | u <- unvisited]
rand <- randomRIO (0, sum probs)
let next = fst . head . dropWhile ((< rand) . snd) $ zip unvisited (scanl1 (+) probs)
runAnt g p (visited ++ [next]) (unvisited \\ [next])
combinePaths :: BasicProcess (Configuration, [AntSolution]) Configuration
combinePaths (conf@(Configuration {..}), ps) = return conf { pheromones = pheromones', path = path', pathLen = len' }
where
pheromones' = depositPheromones ps pheromones
(path', len') = minimumBy (compare `on` snd) ps
evaporations :: BasicProcess Configuration Configuration
evaporations (conf@Configuration {..}) = return conf { pheromones = evaporation rho pheromones }
decIter :: BasicProcess Configuration Configuration
decIter conf@Configuration {..} = return conf { iterations = iterations - 1 }
continueIter :: BasicProcess Configuration Bool
continueIter Configuration {..} = return (iterations > 0)
extractSolution :: BasicProcess Configuration AntSolution
extractSolution (Configuration {..}) = return (path, pathLen)
-------------------------------------------------------------------------------
--
antProcess :: Process Configuration AntSolution
antProcess = Basic ant
combinePathsProcess :: Process (Configuration, [AntSolution]) Configuration
combinePathsProcess = Basic combinePaths
evaporationProcess :: Process Configuration Configuration
evaporationProcess = Basic evaporations
decIterProcess :: Process Configuration Configuration
decIterProcess = Basic decIter
continueIterProcess :: Predicate Configuration
continueIterProcess = Basic continueIter
extractSolutionProcess :: Process Configuration AntSolution
extractSolutionProcess = Basic extractSolution
-------------------------------------------------------------------------------
main :: IO ()
main = do
args <- getArgs
case args of
[jsonFile, antNumber, iterNumber] -> do
fileContent <- T.readFile jsonFile
let mposlist = P.parse fileContent
mgraph = fmap P.convertToGraph mposlist
ants = read antNumber :: Int
iters = read iterNumber :: Int
case mgraph of
Nothing -> print "the file didn't look good..."
Just graph -> do
let conf = Configuration graph (mkPheromones graph 2) (nodes graph) (pathLength' graph $ nodes graph) ants iters 2 5 0.1
computation = interpret conf
solution <- runProcess computation conf
print solution
_ -> putStrLn "wrong args, give me one input file."
interpret :: Configuration -> Process Configuration AntSolution
interpret conf@Configuration {..} = do
let antRuns = Multilel (replicate ants antProcess) combinePathsProcess
innerProc = antRuns `Sequence` evaporationProcess `Sequence` decIterProcess
loop = Repetition continueIterProcess innerProc
Sequence loop extractSolutionProcess
|
chrisbloecker/Hive
|
tools/AntSystem.hs
|
gpl-3.0
| 5,120 | 0 | 23 | 1,435 | 1,288 | 689 | 599 | 112 | 3 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
-- import Generics.MultiRec (children) hiding (show)
-- import Generics.MultiRec.HFix (children)
import Annotations.MultiRec.Annotated (children)
-- import Annotations.MultiRec.Any (children)
-- import AST
-- import ASTTHUse
import ASTExpr
import Annotations.Bounds
import Annotations.MultiRec.Annotated (AnnFix,AnnFix1)
import Control.Applicative hiding (Const)
import Control.Monad.State.Strict
import Control.Monad.Identity
import Data.Monoid
import Generics.MultiRec.Base
import Generics.MultiRec.HFix
import Generics.MultiRec.HFunctor
import qualified Generics.MultiRec.Fold as F
import Generics.MultiRec.FoldAlg as FA
main = putStrLn "hello"
-- | Example expression
-- example :: Expr String
-- example = Let (Seq ["x" := Mul (Const 6) (Const 9), "z" := Const 1])
-- (Mul (EVar "z") (Add (EVar "x") (EVar "y")))
example :: Expr
example = undefined
{-
type family PF phi :: (* -> *) -> * -> *
type AnnFix x s = HFix (K x :*: PF s)
-- A fully annotated tree.
type AnnFix1 x s = PF s (AnnFix x s)
-- A functor with fully annotated children.
mkAnnFix :: x -> AnnFix1 x s ix -> AnnFix x s ix
-- Supply a tree with an annotation at the top level.
-}
-- type
-- foo :: AnnFix1 Bounds ExprF
-- foo :: AnnFix1 Bounds (AST (Expr x)) r
-- foo = Expr Expr (Const 11)
-- ff :: AST String r
-- ff = undefined
nullBounds :: Bounds
nullBounds = Bounds (0,0) (0,0)
-- type AnnotExpr = AnnFix Bounds (AST (Expr String))
-- annotConst :: AnnotExpr r
-- annotConst = AnnFix nullBounds (Const 1)
-- foo :: AnnFix1 Bounds (s a)
-- foo = undefined
-- type instance PF (AST a)
data Except e a = Failed e | OK a
deriving (Functor,Show)
instance Monoid e => Applicative (Except e) where
pure = OK
OK f <*> OK x = OK (f x)
OK _ <*> Failed e = Failed e
Failed e <*> OK _ = Failed e
Failed e1 <*> Failed e2 = Failed (e1 `mappend` e2)
type ErrorAlgebra f e a = f a -> Either e a
-- exprEval :: ErrorAlgebra ExprF String Int
-- exprEval = undefined
-- type ErrorAlgPF f e a = forall ix.f (K a ) ix -> Either e a
type ErrorAlgPF f e a r = forall ix.f (K a r) ix -> Either e a
-- type ErrorAlgPF f e a = forall ix.f (K a r) ix -> Either e a
-- (f (K a r) ix -> Either e a)
{-
errorCata1 :: (HFunctor phi f )
=>
ErrorAlgPF f e r
-> phi ix
-> HFix (K x :*: f ) ix
-> Except [(e, x)] r
errorCata1 = undefined
-}
-- type Foo f e a r = (forall ix.f (K a r) ix -> Either e a)
errorCata :: HFunctor phi f
=>
ErrorAlgPF f e a r
-> phi ix
-> HFix (K x :*: f) ix
-> Except [(e, x)] a
errorCata alg pf (HIn (K k :*: f )) =
case hmapA (\pg g -> K <$> errorCata alg pg g) pf f of
Failed xs -> Failed xs
OK expr' -> case alg expr' of
Left x' -> Failed [(x', k)]
Right v -> OK v
-- Page 57
type family ErrorAlg
(f :: (* -> *) -> * -> *) -- pattern functor
(e :: *) -- error type
(a :: *) -- result type
:: * -- resulting algebra type
type instance ErrorAlg U e a = Either e a
type instance ErrorAlg (K b :*: f ) e a = b -> ErrorAlg f e a
type instance ErrorAlg (I xi :*: f ) e a = a -> ErrorAlg f e a
type instance ErrorAlg (f :+: g) e a = (ErrorAlg f e a, ErrorAlg g e a)
type instance ErrorAlg (f :>: xi) e a = ErrorAlg f e a
infixr 5 :&:
-- Note: This is a type synonym, so normal tuple processing stuff will
-- still work
type (:&:) = (,)
type ExprErrorAlg e a
= (a -> a -> Either e a) -- EAdd
:&: (a -> a -> Either e a) -- EMul
:&: (a -> a -> Either e a) -- ETup
:&: (Int -> Either e a) -- EIntLit
:&: (a -> a -> Either e a) -- ETyped
type TypeErrorAlg e a
= ( Either e a) -- TyInt
:&: (a -> a -> Either e a) -- TyTup
-- -------------------------------------
class MkErrorAlg f where
mkErrorAlg :: ErrorAlg f e a -> ErrorAlgPF f e a r
instance MkErrorAlg U where
mkErrorAlg x U = x
instance MkErrorAlg f => MkErrorAlg (K a :*: f ) where
mkErrorAlg alg (K x :*: f ) = mkErrorAlg (alg x) f
instance MkErrorAlg f => MkErrorAlg (I xi :*: f ) where
mkErrorAlg alg (I (K x) :*: f ) = mkErrorAlg (alg x) f
instance MkErrorAlg f => MkErrorAlg (f :>: xi) where
mkErrorAlg alg (Tag f ) = mkErrorAlg alg f
instance (MkErrorAlg f , MkErrorAlg g) => MkErrorAlg (f :+: g) where
mkErrorAlg (algf ,_ ) (L x) = mkErrorAlg algf x
mkErrorAlg (_ , algg) (R y) = mkErrorAlg algg y
-- -------------------------------------
inferType :: ExprErrorAlg String Type :&: TypeErrorAlg String Type
inferType =
(equal "+" & -- EAdd
equal "*" & -- EMul
tup & -- ETup
const (Right TyInt) & -- EIntLit
equal "::" -- ETyped
)
&
(
Right TyInt & -- TyInt
tup -- TyTup
)
where
equal op ty1 ty2
| ty1 == ty2 = Right ty1
| otherwise = Left ("lhs and rhs of "
++ op ++ " must have equal types")
tup ty1 ty2 = Right (TyTup ty1 ty2)
-- >let expr1 = readExpr "(1, (2, 3))"
tt expr = errorCata (mkErrorAlg inferType) Expr expr
-- OK (TyTup TyInt (TyTup TyInt TyInt))
exprE :: Expr
exprE = ETup (EIntLit 1) (ETup (EIntLit 2) (EIntLit 3))
-- f must be PF s
-- expr1 :: HFix (K x :*: f) ix
expr1 :: AnnFix String Tuples r
-- expr1 f = HIn . (K "foo" r Expr :*: from Expr (EIntLit 1))
expr1 = undefined
zz = from Expr (EIntLit 1)
-- ---------------------------------------------------------------------
-- Section 6.6 p60
{-
type family PF phi :: (* -> *) -> * -> *
type AnnFix x s = HFix (K x :*: PF s)
-- A fully annotated tree.
data HFix h ix = HIn {hout :: h (HFix h) ix}
type AnnFix1 x s = PF s (AnnFix x s)
-- A functor with fully annotated children.
mkAnnFix :: x -> AnnFix1 x s ix -> AnnFix x s ix
-- Supply a tree with an annotation at the top level.
-}
-- mkAnnFix :: x -> AnnFix1 x s ix -> AnnFix x s ix
-- mkAnnFix x = HIn . (K x :*:)
class Monad m => MonadYield m where
type ΦYield m :: * -> *
type AnnType m :: *
yield :: ΦYield m ix -> AnnType m -> ix -> m ix
data AnyF φ f where
AnyF :: φ ix -> f ix -> AnyF φ f
type AnyAnnFix x φ = AnyF φ (AnnFix x φ)
newtype YieldT x φ m a = YieldT (StateT [AnyAnnFix x φ] m a)
deriving (Functor,Monad)
instance MonadTrans (YieldT x φ) where
lift = YieldT . lift
instance (Monad m, HFunctor φ (PF φ), EqS φ,Fam φ) => MonadYield (YieldT x φ m) where
type ΦYield (YieldT x φ m) = φ
type AnnType (YieldT x φ m) = x
yield = doYield
doYield :: (Monad m, HFunctor φ (PF φ), EqS φ,Fam φ)
=> φ ix -> x -> ix -> YieldT x φ m ix
doYield p bounds x = YieldT $ do
let pfx = from p x
let n = length (children p pfx)
stack <- get
if length stack < n
then error $ "structure mismatch: required "++ show n
++ " accumulated children but found only "
++ show (length stack)
else do
let (cs, cs') = splitAt n stack
let newChild = evalState (hmapM distribute p pfx) (reverse cs)
put (AnyF p (HIn (K bounds :*: newChild)) : cs')
return x
distribute :: EqS φ => φ ix -> I0 ix -> State [AnyAnnFix x φ] (AnnFix x φ ix)
distribute p1 _ = do
xs <- get
case xs of
[] -> error "structure mismatch: too few children"
AnyF p2 x : xs' ->
case eqS p1 p2 of
Nothing -> error "structure mismatch: incompatible child type"
Just Refl -> do put xs'; return x
{-
buildExpr :: MonadYield m => m (AnnFix1 Bounds Tuples r)
buildExpr =
do
n2 <- yield Expr (Bounds {leftMargin = (0, 0), rightMargin = (1, 2)}) (EIntLit 2)
n3 <- yield Expr (Bounds {leftMargin = (3, 4), rightMargin = (5, 5)}) (EIntLit 3)
n5 <- yield Expr (Bounds {leftMargin = (0, 0), rightMargin = (5, 5)}) (EAdd n2 n3)
return n5
-- yield :: Monad m => ix -> Bounds -> Expr -> m (AnnFix1 Bounds Tuples r)
-- yield = undefined
-}
|
alanz/annotations-play
|
src/annotAST.hs
|
unlicense
| 8,209 | 9 | 19 | 2,201 | 2,185 | 1,147 | 1,038 | 143 | 3 |
{-
Copyright 2015 Tristan Aubrey-Jones
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.
-}
{-|
Copyright : (c) Tristan Aubrey-Jones, 2015
License : Apache-2
Maintainer : [email protected]
Stability : experimental
For more information please see <http://www.flocc.net/>
-}
module Compiler.Back.StrTemplates where
import Data.Map.Strict (Map)
import Data.Text (Text, replace, pack, unpack)
import qualified Data.Text as Txt
import Data.List (isInfixOf)
import Debug.Trace (trace)
type StrTem = String
nl = "\n"
-- |containsNl str. Returns True if
-- |nl is in str.
containsNewline :: String -> Bool
containsNewline = isInfixOf nl
containsTemParam :: String -> String -> Bool
containsTemParam paramName = isInfixOf $ "<" ++ paramName ++ ">"
-- |indentString indent str. Returns str where
-- |indent has been added after every newline.
indentString :: String -> String -> String
indentString indent str = indent ++ str'
where str' = unpack $ replace (pack nl) (pack $ nl ++ indent) (pack str)
-- |Creates a new string template
createT :: String -> StrTem
createT str = str
-- |Expands a template with a single value mapping
applySingleT :: Text -> (String, String) -> Text
applySingleT str (name, val) = if containsTemParam name (unpack str) then
replace (pack ("<" ++ {-(trace ("applySingleT:" ++ name) $ name)-} name ++ ">"))
(pack $ if containsNewline val then indentString " " val else val) str
else str
-- |Expands a template with an environment of values
applyT :: StrTem -> [(String, String)] -> String
applyT tem env = unpack $ foldl applySingleT (pack tem) env
|
flocc-net/flocc
|
v0.1/Compiler/Back/StrTemplates.hs
|
apache-2.0
| 2,088 | 0 | 11 | 368 | 371 | 209 | 162 | 24 | 3 |
-- Thinking Functionall with Haskell
-- Chapter 05 Homework
-- Implement a new version of nub, which does not care about Order
-- the complexity of normal nub is O(n^2)
import Data.List
myNub :: (Ord a) => [a] -> [a]
myNub xs = nubOrder ys
where ys = sort xs
nubOrder [] = []
nubOrder [x] = [x]
nubOrder (x:y:zs) = if x==y
then nubOrder (y:zs)
else x: nubOrder (y:zs)
|
Oscarzhao/haskell
|
functional_program_design/ch05/nub.hs
|
apache-2.0
| 464 | 0 | 11 | 166 | 136 | 74 | 62 | 9 | 4 |
{- |
Module : Stats.Foldable
Description : Numerical statistics for Foldable containers
Copyright : (c) Daniel Lovasko, 2016
License : OtherLicense
Maintainer : Daniel Lovasko <[email protected]>
Stability : stable
Portability : portable
Stats.Foldable is a pure Haskell module that implements a safe interface
to a set of basic numerical statistics that only assume the Foldable
typeclass for the underlying container.
-}
module Stats.Foldable
( amean -- f a -> Maybe a
, min -- f a -> Maybe a
, max -- f a -> Maybe a
, var -- f a -> Maybe a
, stddev -- f a -> Maybe a
, covar -- f a -> f a -> Maybe a
, correl -- f a -> f a -> Maybe a
) where
import Prelude hiding (min, max)
import Control.Monad (guard)
import Data.List (genericLength)
import qualified Data.Foldable as F
-- | Determine if the Foldable object contains any elements.
isNonEmpty :: (F.Foldable f)
=> f a -- ^ container
-> Bool -- ^ decision
isNonEmpty = not . null . F.toList
-- | Number of elements in the Foldable container.
size :: (F.Foldable f, Num n)
=> f a -- ^ container
-> n -- ^ size
size = genericLength . F.toList
-- | Find the minimal value of a series.
min :: (F.Foldable f, Ord a)
=> f a -- ^ population
-> Maybe a -- ^ minimal value
min xs = guard (isNonEmpty xs) >> return (F.minimum xs)
-- | Find the maximal value of a population.
max :: (F.Foldable f, Ord a)
=> f a -- ^ population
-> Maybe a -- ^ maximal value
max xs = guard (isNonEmpty xs) >> return (F.maximum xs)
-- | Compute the arithmetic mean of a population.
amean :: (F.Foldable f, Floating a)
=> f a -- ^ population
-> Maybe a -- ^ arithmetic mean
amean xs = guard (isNonEmpty xs) >> return (F.sum xs / size xs)
-- | Compute the standard deviation of a population.
stddev :: (F.Foldable f, Floating a)
=> f a -- ^ population
-> Maybe a -- ^ standard deviation
stddev = fmap sqrt . var
-- | Compute the variance of a population.
var :: (F.Foldable f, Floating a)
=> f a -- ^ population
-> Maybe a -- ^ variance
var xs = do
mean <- amean xs
return $ F.foldr (\x v -> v + (x-mean) * (x-mean)) 0 xs / size xs
-- | Compute the covariance of two populations.
covar :: (F.Foldable f, Floating a)
=> f a -- ^ first population
-> f a -- ^ second population
-> Maybe a -- ^ covariance
covar xs ys = do
xmean <- amean xs
ymean <- amean ys
let xs' = map (subtract xmean) (F.toList xs)
let ys' = map (subtract ymean) (F.toList ys)
return $ F.sum (zipWith (*) xs' ys') / size xs
-- | Compute the correlation of two populations.
correl :: (F.Foldable f, Floating a)
=> f a -- ^ first population
-> f a -- ^ second population
-> Maybe a -- ^ correlation
correl xs ys = do
sdx <- stddev xs
sdy <- stddev ys
cv <- covar xs ys
return $ cv / sdx * sdy
|
lovasko/staf
|
src/Stats/Foldable.hs
|
bsd-2-clause
| 2,902 | 0 | 15 | 752 | 784 | 410 | 374 | 61 | 1 |
{-# LANGUAGE FlexibleInstances #-}
module DecisionProcedure.OrientedPoint
( module SpatioTemporalStructure.OrientedPoint
) where
-- standard modules
-- local modules
import Basics
import DecisionProcedure
import DecisionProcedure.OrientedPoint.AngleConsistency
import SpatioTemporalStructure.OrientedPoint
instance HasDecisionProcedure (ARel Otop) where
procedures _ =
[ DecisionProcedure { decProName = "TC"
, decProProc = triangleConsistency }
, DecisionProcedure { decProName = "TC WitUn"
, decProProc = triangleConsistencyWithWitness }
-- , DecisionProcedure { decProName = "TC WitSa"
-- , decProProc = triangleConsistencyWithWitnesses }
-- , DecisionProcedure { decProName = "TC WitUS"
-- , decProProc = triangleConsistencyWithWitnessAndWitnesses }
, DecisionProcedure { decProName = "AC"
, decProProc = angleConsistency }
, DecisionProcedure { decProName = "AC WitUn"
, decProProc = angleConsistencyWithWitness }
-- , DecisionProcedure { decProName = "AC WitSa"
-- , decProProc = angleConsistencyWithWitnesses }
-- , DecisionProcedure { decProName = "AC WitUS"
-- , decProProc = angleConsistencyWithWitnessAndWitnesses }
]
instance HasDecisionProcedure (GRel Otop) where
procedures _ = []
|
spatial-reasoning/zeno
|
src/DecisionProcedure/OrientedPoint.hs
|
bsd-2-clause
| 1,504 | 0 | 8 | 454 | 156 | 98 | 58 | 19 | 0 |
module Exercises911 where
-- 1.
zip' :: [a] -> [b] -> [(a, b)]
zip' [] y = []
zip' x [] = []
zip' (x:xs) (y:ys) = (x, y) : zip' xs ys
-- 2.
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' f (x:xs) (y:ys) = f x y : zipWith f xs ys
zipWith' _ _ _ = []
-- 3.
zip'' :: [a] -> [b] -> [(a, b)]
zip'' = zipWith' (,)
|
pdmurray/haskell-book-ex
|
src/ch9/Exercises9.11.hs
|
bsd-3-clause
| 321 | 0 | 8 | 85 | 234 | 130 | 104 | 10 | 1 |
{-# LANGUAGE CPP #-}
module App.Clock where
#ifdef darwin_HOST_OS
import Control.Applicative ( (<$>) )
import Data.Time.Clock.POSIX
getTime :: IO Double
getTime = realToFrac <$> getPOSIXTime
#else
import Control.Applicative ( (<$>) )
import qualified System.Clock as SysClk
getTime :: IO Double
getTime =
toSeconds <$> SysClk.getTime SysClk.Monotonic
where
toSeconds (SysClk.TimeSpec seconds nanos) =
fromIntegral seconds + fromIntegral nanos * 10**(-9)
#endif
data Clock = Clock { _frames :: [Double]
, _avgFPS :: Double
, _timeNow :: Double
, _timePrev :: Double
} deriving (Show, Eq, Ord)
emptyClock :: Clock
emptyClock = Clock (replicate 100 0) 0.0 0.0 0.0
tickClock :: Double -> Clock -> Clock
tickClock t clk =
let fs = _frames clk
prev = _timeNow clk
len = length fs
dt = t - prev
in Clock { _timePrev = prev
, _timeNow = t
, _frames = take len (dt:fs)
, _avgFPS = 1/(sum fs /fromIntegral len)
}
|
schell/blocks
|
src/App/Clock.hs
|
bsd-3-clause
| 1,138 | 0 | 12 | 385 | 241 | 137 | 104 | 26 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE RecordWildCards #-}
-- | A basic storage engine for @Raptr@ which stores commands in a flat file.
--
-- This modules exposes a simple Raft persistent log implementation which stores entries in binary
-- format in a flat file, with the following structure:
--
-- +----+----+----+----+
-- | 78 | 56 | 34 | 12 | 4 bytes MAGIC header
-- +----+----+----+----+
-- | length of entry | 4 bytes length of entry
-- +----+--------------+
-- | Vr.| CRC (0-2) | 1 byte version
-- +----+--------------+
-- |CRC | payload | 4 bytes CRC
-- +-------------------+
-- | payload | payload of len (length - 5)
-- | |
-- ...
-- | |
-- +-------------------+
-- | <next entry> |
-- ...
--
module System.IO.Storage
( -- * Types
FileLog(..), magic, version,
-- * Management
openLog,
-- * Raft Operations
insertEntry, getEntry, getLastEntry, truncateLogAtIndex,
-- * Other Operations
getAllData)
where
import Control.DeepSeq
import Control.Exception (throw)
import Control.Monad (when)
import qualified Data.Binary as B
import Data.Binary.Get
import Data.Binary.Put (putWord32be, putWord8, runPut)
import Data.ByteString (ByteString, hPut, length)
import qualified Data.ByteString.Lazy.Char8 as LBS8
import Data.Monoid ((<>))
import Network.Kontiki.Raft as Raft
import Network.Raptr.Types
import Prelude hiding (length)
import qualified Prelude as P
import System.Directory (doesDirectoryExist, doesFileExist)
import System.IO (IOMode (..), hClose, hFlush,
hSetFileSize, openBinaryFile,
withBinaryFile)
-- | Representation of Raft log on disk.
data FileLog = FileLog { logName :: FilePath }
-- | Magic header for raptr log files.
magic :: B.Word32
magic = 0x12345678
-- |Current version number
version :: B.Word8
version = 1
skipMagic :: Get ()
skipMagic = do
mag <- getWord32be
if mag /= magic
then fail "incorrect file format, cannot read magic marker at beginning of file"
else return ()
trace :: FileLog -> String -> IO ()
trace FileLog{..} s = putStrLn $ "[" <> logName <> "] - " <> s
-- | Open a @FileLog@ for use by a Raptr node
--
-- The log file is created if it does not exist as well as any intermediary directory as
-- given by 'path'.
--
-- Returns an initialized 'FileLog' or throw a 'UserError' if file cannot be created or is a
-- directory.
openLog :: FilePath -> IO FileLog
openLog path = do
exist <- doesFileExist path
isdir <- doesDirectoryExist path
when isdir $ throw $ userError ("log file " ++ path ++ " is a directory")
when (not exist) $ withBinaryFile path WriteMode $ \ h ->
hPut h $ LBS8.toStrict $ runPut $ putWord32be magic
let log = FileLog path
trace log "opened log"
return log
-- | Insert a new 'Entry' at end of given 'FileLog'
--
-- The entry's index is asssumed to be correctly set by caller.
insertEntry :: FileLog -> Entry Value -> IO ()
insertEntry log@FileLog{..} e = withBinaryFile logName AppendMode $ \ h -> do
trace log $ "inserting entry: " <> show e
let bs = LBS8.toStrict $ runPut $ B.put e
ln = LBS8.toStrict $ runPut $ putWord32be $ (fromIntegral $ length bs) + 5
hPut h ln -- Size of entry, excluding the 4 bytes of length
hPut h $ LBS8.toStrict
$ runPut $ putWord8 version -- version
hPut h $ LBS8.toStrict
$ runPut $ putWord32be 0 -- TODO compute real CRC
hPut h bs -- payload
trace log "inserted entry"
readSingleEntry :: Get (B.Word32, LBS8.ByteString)
readSingleEntry = do
ln <- getWord32be
v <- getWord8
crc <- getWord32be
bs <- getLazyByteString (fromIntegral ln - 5)
return (ln, bs)
readUntilEntry :: B.Word64 -> Integer -> Get Integer
readUntilEntry 0 pos = return pos
readUntilEntry idx pos = do
empty <- isEmpty
if empty
then return pos
else do
(ln, bs) <- readSingleEntry
readUntilEntry (idx - 1) (pos + fromIntegral ln + 4)
readTruncatePosition :: FilePath -> Index -> IO Integer
readTruncatePosition logName idx = withBinaryFile logName ReadWriteMode $ \ h -> do
bs <- LBS8.hGetContents h
let !pos = runGet (skipMagic >> readUntilEntry (unIndex idx) 0) bs
hClose h
return pos
-- | Truncate 'FileLog' to given number of entries.
-- If 'idx' is greater than or equal than number of entries, file is unchanged.
truncateLogAtIndex :: FileLog -> Index -> IO ()
truncateLogAtIndex log@FileLog{..} idx = do
trace log $ "truncating at index: " <> show idx
!truncateAt <- readTruncatePosition logName idx
trace log $ "truncating at actual position: " <> show truncateAt
h <- openBinaryFile logName ReadWriteMode
hSetFileSize h (truncateAt + 4)
hClose h
trace log $ "truncated log"
getEntryAt :: B.Word64 -> Get (Maybe (Entry Value))
getEntryAt 0 = return Nothing
getEntryAt 1 = do
empty <- isEmpty
if empty
then return Nothing
else (Just . B.decode . snd) <$> readSingleEntry
getEntryAt idx = do
empty <- isEmpty
if empty
then return Nothing
else getEntryAt (idx - 1)
-- | Tries to retrieve 'Entry' at given index.
--
-- Returns 'Just entry' if found, otherwise 'Nothing'
getEntry :: FileLog -> Index -> IO (Maybe (Entry Value))
getEntry log@FileLog{..} idx = withBinaryFile logName ReadMode $ \ h -> do
trace log $ "getting entry at index: " <> show idx
bs <- LBS8.hGetContents h
let e = runGet (skipMagic >> getEntryAt (unIndex idx)) bs
trace log $ "got entry " ++ show e
return e
getLastEntryFromFile :: Maybe (Entry Value) -> Get (Maybe (Entry Value))
getLastEntryFromFile last = do
empty <- isEmpty
if empty
then return last
else do
(Just . B.decode . snd) <$> readSingleEntry >>= getLastEntryFromFile
-- | Tries to retrieve last 'Entry'.
--
-- Returns 'Just entry' if log is not empty, 'Nothing' otherwise.
getLastEntry :: FileLog -> IO (Maybe (Entry Value))
getLastEntry log@FileLog{..} = withBinaryFile logName ReadMode $ \ h -> do
trace log "getting last entry"
bs <- LBS8.hGetContents h
let e = runGet (skipMagic >> getLastEntryFromFile Nothing) bs
trace log $ "got last entry: " ++ show e
return e
readAllData :: Get [ LBS8.ByteString ]
readAllData = do
empty <- isEmpty
if empty
then return []
else do
(_,bs) <- readSingleEntry
(eValue (B.decode bs):) <$> readAllData
-- | Returns a (lazy) list of (lazy) 'ByteString' of all data stored within
-- entries in this log file.
--
-- **Note**: It is probably a good idea to consume the returned list otherwise the underlying file
-- handle will be kept in so-called semi-closed state hence will return a lock which will prevent
-- subsequent write operations on this file to operate properly.
getAllData :: FileLog -> IO [ LBS8.ByteString ]
getAllData log@FileLog{..} = do
trace log $ "retrieving all data"
h <- openBinaryFile logName ReadMode
bs <- LBS8.hGetContents h
let pos = bs `deepseq` runGet (skipMagic >> readAllData) bs
pos `deepseq` hClose h
return pos
|
capital-match/raptr
|
src/System/IO/Storage.hs
|
bsd-3-clause
| 7,458 | 0 | 17 | 1,970 | 1,807 | 926 | 881 | 140 | 3 |
{-# OPTIONS_GHC -Wall -fwarn-tabs #-}
----------------------------------------------------------------
-- ~ 2011.02.12
-- |
-- Module : Data.Trie.Convenience
-- Copyright : Copyright (c) 2008--2015 wren gayle romano
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Additional convenience functions. In order to keep "Data.Trie"
-- concise, non-essential and uncommonly used functions have been
-- moved here. Most of these functions simplify the generic functions
-- from "Data.Trie", following after the interface for "Data.Map"
-- and "Data.IntMap".
----------------------------------------------------------------
module Data.Trie.Convenience
(
-- * Conversion functions ('fromList' variants)
-- $fromList
fromListL, fromListR, fromListS
, fromListWith, fromListWith'
, fromListWithL, fromListWithL'
-- * Query functions ('lookupBy' variants)
, lookupWithDefault
-- * Inserting values ('alterBy' variants)
, insertIfAbsent
, insertWith, insertWith'
, insertWithKey, insertWithKey'
-- * Updating and adjusting values ('alterBy' and 'adjustBy' variants)
, adjustWithKey
, update, updateWithKey
-- * Combining tries ('mergeBy' variants)
, disunion
, unionWith, unionWith'
) where
import Data.Trie
import Data.Trie.Internal (lookupBy_, adjustBy)
import Data.Trie.Errors (impossible)
import Data.ByteString (ByteString)
import Data.List (foldl', sortBy)
import Data.Ord (comparing)
----------------------------------------------------------------
----------------------------------------------------------------
-- $fromList
-- Just like 'fromList' all of these functions convert an association
-- list into a trie, with earlier values shadowing later ones when
-- keys conflict. Depending on the order of keys in the list, there
-- can be as much as 5x speed difference between the left and right
-- variants. Yet, performance is about the same when matching
-- best-case to best-case and worst-case to worst-case (which is
-- which is swapped when reversing the list or changing which
-- function is used).
-- | A left-fold version of 'fromList'. If you run into issues with
-- stack overflows when using 'fromList' or 'fromListR', then you
-- should use this function instead.
fromListL :: [(ByteString,a)] -> Trie a
{-# INLINE fromListL #-}
fromListL = foldl' (flip . uncurry $ insertIfAbsent) empty
-- | An explicitly right-fold variant of 'fromList'. It is a good
-- consumer for list fusion. Worst-case behavior is somewhat worse
-- than worst-case for 'fromListL'. The 'fromList' function is
-- currently just an alias for 'fromListR'.
fromListR :: [(ByteString,a)] -> Trie a
{-# INLINE fromListR #-}
fromListR = fromList -- == foldr (uncurry insert) empty
-- TODO: compare performance against a fromListL variant, adjusting the sort appropriately
--
-- | This variant sorts the list before folding over it. This adds
-- /O(n log n)/ overhead and requires the whole list be in memory
-- at once, but it ensures that the list is in best-case order. The
-- benefits generally outweigh the costs.
fromListS :: [(ByteString,a)] -> Trie a
{-# INLINE fromListS #-}
fromListS = fromListR . sortBy (comparing fst)
-- | A variant of 'fromListR' that takes a function for combining
-- values on conflict. The first argument to the combining function
-- is the ``new'' value from the initial portion of the list; the
-- second argument is the value that has been accumulated into the
-- trie from the tail of the list (just like the first argument to
-- 'foldr'). Thus, @fromList = fromListWith const@.
fromListWith :: (a -> a -> a) -> [(ByteString,a)] -> Trie a
{-# INLINE fromListWith #-}
fromListWith f = foldr (uncurry $ alterBy g) empty
where
g _ v Nothing = Just v
g _ v (Just w) = Just (f v w)
-- | A variant of 'fromListWith' which applies the combining
-- function strictly. This function is a good consumer for list
-- fusion. If you need list fusion and are running into stack
-- overflow problems with 'fromListWith', then this function may
-- solve the problem.
fromListWith' :: (a -> a -> a) -> [(ByteString,a)] -> Trie a
{-# INLINE fromListWith' #-}
fromListWith' f = foldr (uncurry $ alterBy g') empty
where
g' _ v Nothing = Just v
g' _ v (Just w) = Just $! f v w
-- | A left-fold variant of 'fromListWith'. Note that the arguments
-- to the combining function are swapped: the first is the value
-- in the trie which has been accumulated from the initial part of
-- the list; the second argument is the ``new'' value from the
-- remaining tail of the list (just like the first argument to
-- 'foldl'). Thus, @fromListL = fromListWithL const@.
fromListWithL :: (a -> a -> a) -> [(ByteString,a)] -> Trie a
{-# INLINE fromListWithL #-}
fromListWithL f = foldl' (flip . uncurry $ alterBy flipG) empty
where
flipG _ v Nothing = Just v
flipG _ v (Just w) = Just (f w v)
-- | A variant of 'fromListWithL' which applies the combining
-- function strictly.
fromListWithL' :: (a -> a -> a) -> [(ByteString,a)] -> Trie a
{-# INLINE fromListWithL' #-}
fromListWithL' f = foldl' (flip . uncurry $ alterBy flipG') empty
where
flipG' _ v Nothing = Just v
flipG' _ v (Just w) = Just $! f w v
----------------------------------------------------------------
-- | Lookup a key, returning a default value if it's not found.
lookupWithDefault :: a -> ByteString -> Trie a -> a
lookupWithDefault def = lookupBy_ f def (const def)
where
f Nothing _ = def
f (Just v) _ = v
----------------------------------------------------------------
-- | Insert a new key, retaining old value on conflict.
insertIfAbsent :: ByteString -> a -> Trie a -> Trie a
insertIfAbsent =
alterBy $ \_ x mv ->
case mv of
Nothing -> Just x
Just _ -> mv
-- | Insert a new key, with a function to resolve conflicts.
insertWith :: (a -> a -> a) -> ByteString -> a -> Trie a -> Trie a
insertWith f =
alterBy $ \_ x mv ->
case mv of
Nothing -> Just x
Just v -> Just (f x v)
-- | A variant of 'insertWith' which applies the combining function
-- strictly.
insertWith' :: (a -> a -> a) -> ByteString -> a -> Trie a -> Trie a
insertWith' f =
alterBy $ \_ x mv ->
case mv of
Nothing -> Just x
Just v -> Just $! f x v
-- | A variant of 'insertWith' which also provides the key to the
-- combining function.
insertWithKey :: (ByteString -> a -> a -> a) -> ByteString -> a -> Trie a -> Trie a
insertWithKey f =
alterBy $ \k x mv ->
case mv of
Nothing -> Just x
Just v -> Just (f k x v)
-- | A variant of 'insertWithKey' which applies the combining
-- function strictly.
insertWithKey' :: (ByteString -> a -> a -> a) -> ByteString -> a -> Trie a -> Trie a
insertWithKey' f =
alterBy $ \k x mv ->
case mv of
Nothing -> Just x
Just v -> Just $! f k x v
{- This is a tricky one...
insertLookupWithKey :: (ByteString -> a -> a -> a) -> ByteString -> a -> Trie a -> (Maybe a, Trie a)
-}
----------------------------------------------------------------
-- | Apply a function to change the value at a key.
adjustWithKey :: (ByteString -> a -> a) -> ByteString -> Trie a -> Trie a
adjustWithKey f q =
adjustBy (\k _ -> f k) q (impossible "Convenience.adjustWithKey")
-- TODO: benchmark vs the definition with alterBy/liftM
-- | Apply a function to the value at a key, possibly removing it.
update :: (a -> Maybe a) -> ByteString -> Trie a -> Trie a
update f q =
alterBy (\_ _ mx -> mx >>= f) q (impossible "Convenience.update")
-- | A variant of 'update' which also provides the key to the function.
updateWithKey :: (ByteString -> a -> Maybe a) -> ByteString -> Trie a -> Trie a
updateWithKey f q =
alterBy (\k _ mx -> mx >>= f k) q (impossible "Convenience.updateWithKey")
{-
updateLookupWithKey :: (ByteString -> a -> Maybe a) -> ByteString -> Trie a -> (Maybe a, Trie a)
-- Also tricky
-}
----------------------------------------------------------------
-- | Combine two tries, a la symmetric difference. If they define
-- the same key, it is removed; otherwise it is retained with the
-- value it has in whichever trie.
disunion :: Trie a -> Trie a -> Trie a
disunion = mergeBy (\_ _ -> Nothing)
-- | Combine two tries, using a function to resolve conflicts.
unionWith :: (a -> a -> a) -> Trie a -> Trie a -> Trie a
unionWith f = mergeBy (\x y -> Just (f x y))
-- | A variant of 'unionWith' which applies the combining function
-- strictly.
unionWith' :: (a -> a -> a) -> Trie a -> Trie a -> Trie a
unionWith' f = mergeBy (\x y -> Just $! f x y)
{- TODO: (efficiently)
difference, intersection
-}
----------------------------------------------------------------
----------------------------------------------------------- fin.
|
unhammer/bytestring-trie-0.2.4
|
src/Data/Trie/Convenience.hs
|
bsd-3-clause
| 9,000 | 0 | 12 | 1,903 | 1,667 | 904 | 763 | 98 | 2 |
{-# LANGUAGE PatternGuards, ViewPatterns #-}
module Hint.Util where
import HSE.All
import Util
-- | Generate a lambda, but prettier (if possible).
-- Generally no lambda is good, but removing just some arguments isn't so useful.
niceLambda :: [String] -> Exp_ -> Exp_
-- \xs -> (e) ==> \xs -> e
niceLambda xs (Paren _ x) = niceLambda xs x
-- \xs -> \v vs -> e ==> \xs v -> \vs -> e
-- \xs -> \ -> e ==> \xs -> e
niceLambda xs (Lambda _ ((view -> PVar_ v):vs) x) | v `notElem` xs = niceLambda (xs++[v]) (Lambda an vs x)
niceLambda xs (Lambda _ [] x) = niceLambda xs x
-- \ -> e ==> e
niceLambda [] x = x
-- \xs -> e xs ==> e
niceLambda xs (fromApps -> e) | map view xs2 == map Var_ xs, vars e2 `disjoint` xs, notNull e2 = apps e2
where (e2,xs2) = splitAt (length e - length xs) e
-- \x y -> x + y ==> (+)
niceLambda [x,y] (InfixApp _ (view -> Var_ x1) (opExp -> op) (view -> Var_ y1))
| x == x1, y == y1, vars op `disjoint` [x,y] = op
-- \x -> x + b ==> (+ b) [heuristic, b must be a single lexeme, or gets too complex]
niceLambda [x] (view -> App2 (expOp -> Just op) a b)
| isLexeme b, view a == Var_ x, x `notElem` vars b, allowRightSection (fromNamed op) = rebracket1 $ RightSection an op b
-- \x y -> f y x = flip f
niceLambda [x,y] (view -> App2 op (view -> Var_ y1) (view -> Var_ x1))
| x == x1, y == y1, vars op `disjoint` [x,y] = App an (toNamed "flip") op
-- \x -> f (b x) ==> f . b
-- \x -> f $ b x ==> f . b
niceLambda [x] y | Just z <- factor y, x `notElem` vars z = z
where
-- factor the expression with respect to x
factor y@App{} | (ini,lst) <- unsnoc $ fromApps y, view lst == Var_ x = Just $ apps ini
factor y@App{} | (ini,lst) <- unsnoc $ fromApps y, Just z <- factor lst = Just $ niceDotApp (apps ini) z
factor (InfixApp _ y op (factor -> Just z)) | isDol op = Just $ niceDotApp y z
factor (Paren _ y@App{}) = factor y
factor _ = Nothing
-- \x -> (x +) ==> (+)
niceLambda [x] (LeftSection _ (view -> Var_ x1) op) | x == x1 = opExp op
-- base case
niceLambda ps x = Lambda an (map toNamed ps) x
-- ($) . b ==> b
niceDotApp :: Exp_ -> Exp_ -> Exp_
niceDotApp a b | a ~= "$" = b
| otherwise = dotApp a b
-- | Convert expressions which have redundant junk in them away.
-- Mainly so that later stages can match on fewer alternatives.
simplifyExp :: Exp_ -> Exp_
simplifyExp (InfixApp _ x dol y) | isDol dol = App an x (paren y)
simplifyExp (Let _ (BDecls _ [PatBind _ (view -> PVar_ x) Nothing (UnGuardedRhs _ y) Nothing]) z)
| x `notElem` vars y && length [() | UnQual _ a <- universeS z, prettyPrint a == x] <= 1 = transform f z
where f (view -> Var_ x') | x == x' = paren y
f x = x
simplifyExp x = x
|
bergmark/hlint
|
src/Hint/Util.hs
|
bsd-3-clause
| 2,742 | 0 | 14 | 702 | 1,157 | 575 | 582 | 35 | 5 |
module Language.Haskell.Refact.Refactoring.Renaming
( rename
, compRename
) where
import qualified Data.Generics.Schemes as SYB
import qualified Data.Generics.Aliases as SYB
import qualified GHC.SYB.Utils as SYB
import qualified GHC
import qualified Name as GHC
import qualified RdrName as GHC
import Control.Monad
import Data.Maybe
import Data.List
import qualified Language.Haskell.GhcMod as GM (Options(..))
import Language.Haskell.Refact.API
import System.Directory
{-This refactoring renames an indentifier to a user-specified name.
Conditions:
a: the indentifier to be renamed should be defined in the current module.
b. the user provided name should be a valid name with regard to the name
space of the identifier.
c. the new name should not change the semantics of the program, and
should not cause any name clash/conflict/ambiguity problem in the
program.
Attention:
a. To select an identifier, stop the cursor at the beginning position of
any occurrence of the identifier.
b. Renaming a qualified name will not change the qualifier;
c. In current module, an unqualified name won't become qualified after
renaming; but, in client modules, an unqualified name might become
qualified after renaming to avoid ambiguity prolem. In case the new
name, say 'f', will cause ambiguous occurrence in the current module
(this is because the identifier 'f' is imported from other modules),
the user will be prompted to choose another new name or qualify the
use of 'f' before doing renaming.
-}
{-In the current implementation, we assume that module name is same as
the file name, but we should keep in mind that people also use unnamed
modules.
-}
-- | Rename the given identifier.
rename :: RefactSettings
-> GM.Options
-> FilePath
-> String
-> SimpPos
-> IO [FilePath]
rename settings opts fileName newName (row,col) = do
absFileName <- canonicalizePath fileName
runRefacSession settings opts (compRename absFileName newName (row,col))
-- | Body of the refactoring
compRename :: FilePath -> String -> SimpPos -> RefactGhc [ApplyRefacResult]
compRename fileName newName (row,col) = do
logm $ "Renaming.comp: (fileName,newName,(row,col))=" ++ show (fileName,newName,(row,col))
parseSourceFileGhc fileName
renamed <- getRefactRenamed
parsed <- getRefactParsed
modu <- getModule
targetModule <- getRefactTargetModule
let modName = maybe (GHC.mkModuleName "Main") fst $ getModuleName parsed
maybePn = locToName (row, col) renamed
logm $ "Renamed.comp:maybePn=" ++ showGhc maybePn -- ++AZ++
case maybePn of
Just pn@(GHC.L _ n) -> do
logm $ "Renaming:(n,modu)=" ++ showGhc (n,modu)
let (GHC.L _ rdrName) = gfromJust "Renaming.comp.2" $ locToRdrName (row, col) parsed
let rdrNameStr = GHC.occNameString $ GHC.rdrNameOcc rdrName
logm $ "Renaming: rdrName=" ++ SYB.showData SYB.Parser 0 rdrName
logm $ "Renaming: occname rdrName=" ++ show (GHC.occNameString $ GHC.rdrNameOcc rdrName)
unless (nameToString n /= newName) $ error "The new name is same as the old name"
unless (isValidNewName n rdrNameStr newName) $ error $ "Invalid new name:" ++ newName ++ "!"
logm $ "Renaming.comp: before GHC.nameModule,n=" ++ showGhc n
let defineMod = case GHC.nameModule_maybe n of
Just mn -> GHC.moduleName mn
Nothing -> modName
-- TODO: why do we have this restriction?
unless (defineMod == modName) . error $ mconcat [ "This identifier is defined in module "
, GHC.moduleNameString defineMod
, ", please do renaming in that module!"
]
logm $ "Renaming.comp:(isMainModule modu,pn)=" ++ showGhcQual (isMainModule modu,pn)
when (isMainModule modu && showGhcQual pn == "Main.main") $
error "The 'main' function defined in a 'Main' module should not be renamed!"
logm "Renaming.comp: not main module"
newNameGhc <- mkNewGhcName (Just modu) newName
(refactoredMod, nIsExported) <- applyRefac (doRenaming pn rdrNameStr newName newNameGhc modName)
RSAlreadyLoaded
logm $ "Renaming:nIsExported=" ++ show nIsExported
if nIsExported --no matter whether this pn is used or not.
then do clients <- clientModsAndFiles targetModule
logm ("Renaming: clients=" ++ show clients) -- ++AZ++ debug
refactoredClients <- mapM (renameInClientMod n newName newNameGhc) clients
return $ refactoredMod : concat refactoredClients
else return [refactoredMod]
Nothing -> error "Invalid cursor position!"
-- |Actually do the renaming, split into the various things that can
-- be renamed. Returns True if the name is exported
doRenaming :: GHC.Located GHC.Name -> String -> String -> GHC.Name -> GHC.ModuleName -> RefactGhc Bool
--------Rename a value variable name--------------------------------
doRenaming pn@(GHC.L _ oldn) rdrNameStr newNameStr newNameGhc modName = do
logm $ "doRenaming:(pn,rdrNameStr,newNameStr) = " ++ showGhc (pn,rdrNameStr,newNameStr)
renamed <- getRefactRenamed
void $ SYB.everywhereM (SYB.mkM renameInMod) renamed
logm "doRenaming done"
isExported oldn
where
-- 1. The name is declared in a module(top level name)
renameInMod :: GHC.RenamedSource -> RefactGhc GHC.RenamedSource
renameInMod ren = do
logm "renameInMod"
renameTopLevelVarName oldn newNameStr newNameGhc modName ren True True
renameTopLevelVarName :: GHC.Name -> String -> GHC.Name -> GHC.ModuleName -> GHC.RenamedSource
-> Bool -> Bool -> RefactGhc GHC.RenamedSource
renameTopLevelVarName oldPN newName newNameGhc modName renamed existChecking exportChecking = do
logm $ "renameTopLevelVarName:(existChecking, exportChecking)=" ++ show (existChecking, exportChecking)
causeAmbiguity <- causeAmbiguityInExports oldPN newNameGhc
-- f' contains names imported from other modules;
-- d' contains the top level names declared in this module;
(f', d') <- hsFDsFromInside renamed
--filter those qualified free variables in f'
-- let (f,d) = ((nub.map pNtoName.filter (not.isQualifiedPN)) f', (nub.map pNtoName) d')
let (f, d) = (map nameToString f', map nameToString d')
logm $ "renameTopLevelVarName:f=" ++ show f
logm $ "renameTopLevelVarName:d=" ++ show d
let newNameStr = nameToString newNameGhc
logm $ "renameTopLevelVarName:(newName,newNameStr)=" ++ show (newName, newNameStr)
scopeClashNames <- inScopeNames newName
logm $ "renameTopLevelVarName:(f')=" ++ showGhc f'
logm $ "renameTopLevelVarName:(scopeClashNames,intersection)=" ++
showGhc (scopeClashNames, scopeClashNames `intersect` f')
logm $ "renameTopLevelVarName:(oldPN,modName)=" ++ showGhc (oldPN,modName)
-- Another implementation option is to add the qualifier to newName automatically.
when (nonEmptyList $ intersect scopeClashNames f') .
error $ mconcat [ "The new name will cause an ambiguous occurrence problem, "
, "please select another new name or qualify the use of '"
, newName ++ "' before renaming!\n"]
when (existChecking && newNameStr `elem` d \\ [nameToString oldPN]) . -- only check the declared names here
--the same name has been declared in this module.
error $ mconcat ["Name '", newName, "' already exists in this module\n"]
when (exportChecking && causeNameClashInExports oldPN newNameGhc modName renamed) $
error "The new name will cause conflicting exports, please select another new name!"
when (exportChecking && causeAmbiguity) . -- causeAmbiguityInExports oldPN newNameGhc {- inscps -} renamed
error $ mconcat ["The new name will cause ambiguity in the exports of module '"
, show modName
, "' , please select another name!"]
-- get all of those declared names visible to oldPN at where oldPN is used.
logm "renameTopLevelVarName:basic tests done"
isInScopeUnqual <- isInScopeAndUnqualifiedGhc newName (Just newNameGhc)
logm "renameTopLevelVarName:after isInScopeUnqual"
logm $ "renameTopLevelVarName:oldPN=" ++ showGhc oldPN
ds <- hsVisibleNames oldPN renamed
logm $ "renameTopLevelVarName:ds computed=" ++ show ds
when (existChecking && newName `elem` nub (ds `union` f) \\ [nameToString oldPN]) .
error $ mconcat [ "Name '", newName, "' already exists, or renaming '", nameToString oldPN, "' to '"
, newName, "' will change the program's semantics!\n"]
logm "renameTopLevelVarName start..:should have qualified"
parsed <- renamePN oldPN newNameGhc (exportChecking && isInScopeUnqual) =<< getRefactParsed
putRefactParsed parsed mempty
logm "renameTopLevelVarName done:should have qualified"
getRefactRenamed
------------------------------------------------------------------------
renameInClientMod :: GHC.Name -> String -> GHC.Name -> TargetModule
-> RefactGhc [ApplyRefacResult]
renameInClientMod oldPN newName newNameGhc targetModule = do
logm $ "renameInClientMod:(oldPN,newNameGhc,targetModule)=" ++ showGhc (oldPN,newNameGhc,targetModule) -- ++AZ++
logm $ "renameInClientMod:(newNameGhc module)=" ++ showGhc (GHC.nameModule newNameGhc) -- ++AZ++
getTargetGhc targetModule
renamed <- getRefactRenamed
modName <- getRefactModuleName
-- We need to find the old name in the module, and get it as a
-- GHC.Name to know what to look for in the call to renamePN', as it
-- checks the GHC.nameUnique value.
-- gnames <- GHC.getNamesInScope
-- let clientModule = GHC.nameModule oldPN
-- let clientInscopes = filter (\n -> clientModule == GHC.nameModule n) gnames
-- logm $ "renameInClientMod:(clientInscopes)=" ++ showGhcQual (clientInscopes)
-- let newNames = filter (\n -> showGhcQual n == showGhcQual oldPN) clientInscopes
newNames <- equivalentNameInNewMod oldPN
logm $ "renameInClientMod:(newNames)=" ++ showGhcQual newNames
-- newNames <- inScopeNames (showGhcQual oldPN)
-- newNamesUnqual <- inScopeNames (showGhc oldPN)
-- logm $ "renameInClientMod:(newNamesUnqual,oldPN)=" ++ showGhcQual (newNamesUnqual,oldPN)
-- logm $ "renameInClientMod:(newNames,oldPN)=" ++ showGhcQual (newNames,oldPN)
-- logm $ "renameInClientMod:(uniques:newNames,oldPN)=" ++ showGhcQual (map GHC.nameUnique newNames,GHC.nameUnique oldPN)
case newNames of
[] -> return []
[oldName] | findPN oldName renamed -> doRenameInClientMod oldName modName renamed
| otherwise -> do
logm "renameInClientMod: name not present in module, returning"
return []
ns -> error $ "HaRe: renameInClientMod: could not find name to replace, got:" ++ showGhcQual ns
where
doRenameInClientMod oldNameGhc modName renamed = do
-- There are two different tests we need to do here
-- 1. Does the new name clash with some existing name in the
-- client mod, in which case it must be qualified
-- 2. Is the new name module imported qualified, and so needs to
-- be qualified in the replacement, according to the import
isInScopeUnqual <- isInScopeAndUnqualifiedGhc (nameToString oldPN) Nothing
isInScopeUnqualNew <- isInScopeAndUnqualifiedGhc newName Nothing
logm $ "renameInClientMod: (isInScopeAndUnqual,isInScopeUnqualNew)=" ++
show (isInScopeUnqual, isInScopeUnqualNew) -- ++AZ++
if isInScopeUnqualNew -- ++AZ++: should this be negated?
then do
(refactoredMod, _) <- applyRefac (refactRenameSimple oldNameGhc newName newNameGhc True)
RSAlreadyLoaded
return [refactoredMod]
else do
when (causeNameClashInExports oldPN newNameGhc modName renamed) .
error $ mconcat [ "The new name will cause conflicting exports in module"
, show newName, ", please select another name!"]
-- (refactoredMod,_) <- applyRefac (refactRenameComplex oldPN newName newNameGhc) RSAlreadyLoaded
(refactoredMod, _) <- applyRefac (refactRenameComplex oldNameGhc newName newNameGhc)
RSAlreadyLoaded
-- TODO: implement rest of this
return [refactoredMod]
refactRenameSimple :: GHC.Name -> String -> GHC.Name -> Bool -> RefactGhc ()
refactRenameSimple old newStr new useQual = do
logm $ "refactRenameSimple:(old,newStr,new,useQual)=" ++ showGhc (old, newStr, new, useQual)
qualifyTopLevelVar newStr
parsed <- renamePN old new useQual =<< getRefactParsed
putRefactParsed parsed mempty
return ()
refactRenameComplex :: GHC.Name -> String -> GHC.Name -> RefactGhc ()
refactRenameComplex old new newGhc = do
logm $ "refactRenameComplex:(old,new,newGhc)=" ++ showGhc (old, new, newGhc)
qualifyTopLevelVar new
worker old new newGhc
qualifyTopLevelVar :: String -> RefactGhc ()
qualifyTopLevelVar new = do
toQualify <- inScopeNames new
logm $ "renameInClientMod.qualifyTopLevelVar:new:toQualify=" ++ show new ++ ":" ++ showGhc toQualify
mapM_ qualifyToplevelName toQualify
return ()
worker :: GHC.Name -> String -> GHC.Name -> RefactGhc ()
worker oldPN' newName' newNameGhc' = do
logm $ "renameInClientMod.worker:(oldPN',newName',newNameGhc')=" ++
showGhc (oldPN', newName', newNameGhc')
isInScopeUnqualNew <- isInScopeAndUnqualifiedGhc newName' Nothing
vs <- hsVisibleNames oldPN' =<< getRefactRenamed -- Does this check names other than variable names?
logm $ "renameInClientMod.worker:(vs,oldPN',isInScopeUnqualNew)=" ++
showGhc (vs, oldPN', isInScopeUnqualNew)
parsed <- renamePN oldPN' newNameGhc'
(newName' `elem` (nub vs \\ [nameToString oldPN']) || isInScopeUnqualNew)
=<< getRefactParsed
putRefactParsed parsed mempty
return ()
causeAmbiguityInExports :: GHC.Name -> GHC.Name -> RefactGhc Bool
causeAmbiguityInExports old newName {- inscps -} = do
(GHC.L _ (GHC.HsModule _ exps _imps _decls _ _)) <- getRefactParsed
isInScopeUnqual <- isInScopeAndUnqualifiedGhc (nameToString old) Nothing
let usedUnqual = usedWithoutQualR newName exps
logm $ "causeAmbiguityInExports:(isInScopeUnqual,usedUnqual)" ++ show (isInScopeUnqual, usedUnqual)
return (isInScopeUnqual && usedUnqual)
isValidNewName :: GHC.Name -> String -> String -> Bool
isValidNewName oldName rdrNameStr newName = res
where
doTest :: Bool -> Bool -> String -> Bool
doTest isCategory isRightType errStr = not isCategory || isRightType || error errStr
tyconOk = doTest (GHC.isTyConName oldName) (isConId newName) "Invalid type constructor/class name!"
dataConOk = doTest (GHC.isDataConName oldName) (isConId newName) "Invalid data constructor name!"
tyVarOk = doTest (GHC.isTyVarName oldName) (isVarId newName) "Invalid type variable name!"
oldName' = rdrNameStr
matchNamesOk
| {- GHC.isValName oldName || -} GHC.isVarName oldName
= if isVarId oldName' && not (isVarId newName)
then error "The new name should be an identifier!"
else if isOperator oldName' && not (isOperator newName)
then error "The new name should be an operator!"
else (isVarId oldName' && isVarId newName)
|| (isOperator oldName' && isOperator newName)
|| (error $ "Invalid new name!" ++ show ( oldName', newName
, isVarId oldName'
, isVarId newName
, isOperator oldName'
, isOperator newName ))
| otherwise = True
res = tyconOk && dataConOk {- && fieldOk && instanceOk -} && tyVarOk && matchNamesOk
-- EOF
|
kmate/HaRe
|
src/Language/Haskell/Refact/Refactoring/Renaming.hs
|
bsd-3-clause
| 16,951 | 0 | 19 | 4,551 | 3,040 | 1,504 | 1,536 | 214 | 4 |
{-# LANGUAGE TemplateHaskell, DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
module SimpleBound(
Scope(..),
toScope,
(>>>=),
abstract,
instantiate,
Var(..)
) where
import Control.Monad
import Control.Monad.Trans
import Control.Applicative
import Data.Functor.Classes
import Data.Deriving (deriveShow1)
data Var a = B | F a
deriving (Eq, Show)
-- Fun, Fold, Trav
deriveShow1 ''Var
varbe :: b -> (a -> b) -> Var a -> b
varbe n _ B = n
varbe _ f (F x) = f x
instance Eq1 Var where
liftEq _ B B = True
liftEq f (F a) (F b) = f a b
liftEq _ _ _ = False
newtype Scope f a = Scope { fromScope :: f (Var a) }
-- deriving(Functor, Foldable, Traversable)
toScope :: f (Var a) -> Scope f a
toScope = Scope
instance (Monad f, Eq1 f, Eq a) => Eq (Scope f a) where (==) = eq1
instance (Show1 f, Show a) => Show (Scope f a) where showsPrec = showsPrec1
instance (Monad f, Eq1 f) => Eq1 (Scope f) where
liftEq f m n = liftEq (liftEq f) (fromScope m) (fromScope n)
instance (Show1 f) => Show1 (Scope f) where
liftShowsPrec f g d m = showsUnaryWith (liftShowsPrec f' g') "Scope" d (fromScope m) where
f' = liftShowsPrec f g
g' = liftShowList f g
instance Monad f => Applicative (Scope f) where
pure = Scope . return . F
(<*>) = ap
instance Monad f => Monad (Scope f) where
return = Scope . return . F
Scope m >>= f = Scope $ m >>= varbe (return B) (fromScope . f)
instance MonadTrans Scope where
lift = Scope . liftM F
abstract :: (Functor f, Eq a) => a -> f a -> Scope f a
abstract x xs = Scope (fmap go xs) where
go y = y <$ guard (x /= y)
instantiate :: Monad f => f a -> Scope f a -> f a
instantiate x (Scope xs) = xs >>= go where
go B = x
go (F y) = return y
(>>>=) :: (Monad f) => Scope f a -> (a -> f b) -> Scope f b
m >>>= f = m >>= lift . f
instance Applicative Var where
pure = F
(<*>) = ap
instance Monad Var where
return = pure
F a >>= f = f a
B >>= _ = B
instance Alternative Var where
empty = B
B <|> r = r
l <|> _ = l
--------------------------------------------------
-- could be derived
--------------------------------------------------------------------------------
instance Functor Var where
fmap _ B = B
fmap f (F a) = F (f a)
instance Foldable Var where
foldMap f (F a) = f a
foldMap _ _ = mempty
instance Traversable Var where
traverse f (F a) = F <$> f a
traverse _ B = pure B
instance Functor f => Functor (Scope f) where
fmap f (Scope a) = Scope (fmap (fmap f) a)
instance Foldable f => Foldable (Scope f) where
foldMap f (Scope a) = foldMap (foldMap f) a
instance Traversable f => Traversable (Scope f) where
traverse f (Scope a) = Scope <$> traverse (traverse f) a
---
|
esengie/fpl-exploration-tool
|
src/langGenerator/SimpleBound.hs
|
bsd-3-clause
| 2,718 | 0 | 10 | 653 | 1,237 | 633 | 604 | 77 | 2 |
module Bench.Lev.Reader.Dynamic where
import Data.Int
import Data.Word
import Lev.Reader.Dynamic
import Bench.Lev.Reader.Static as Static
{-# INLINE read12Int64PlusInt32 #-}
read12Int64PlusInt32 :: ( Cursor c ) => Reader c IO Int64
read12Int64PlusInt32 = readStatic Static.read12Int64PlusInt32
{-# INLINE getWord64N16Host #-}
getWord64N16Host :: (Cursor c) => Int -> Reader c IO Word64
getWord64N16Host = loop 0
where loop s n | s `seq` n `seq` False = undefined
loop s 0 = return s
loop s n = do
r <- readStatic Static.getWord64N16Host
loop r (n-16)
|
PROTEINE-INSAIDERS/lev-tolstoy
|
bench/Bench/Lev/Reader/Dynamic.hs
|
bsd-3-clause
| 596 | 0 | 11 | 126 | 179 | 97 | 82 | 16 | 3 |
{-# LANGUAGE TypeFamilies, TypeOperators, PatternSynonyms, TemplateHaskell, CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Units.SI
-- Copyright : (C) 2013 Richard Eisenberg
-- License : BSD-style (see LICENSE)
-- Maintainer : Richard Eisenberg ([email protected])
-- Stability : experimental
-- Portability : non-portable
--
-- This module exports unit definitions according to the SI system of units.
-- The definitions were taken from here: <http://www.bipm.org/en/si/>.
--
-- Some additional units were added based on
-- <http://www.bipm.org/en/si/si_brochure/chapter4/table6.html this link>:
-- "Non-SI units accepted for use with the SI,
-- and units based on fundamental constants".
--
-- There is one deviation from the definitions at that site: To work better
-- with prefixes, the unit of mass is 'Gram'.
--
-- This module exports both American spellings and British spellings of
-- units, using pattern synonyms to get the British spellings of data
-- constructors.
-----------------------------------------------------------------------------
module Data.Units.SI where
import Data.Metrology.Poly
import Data.Metrology.TH
import Data.Dimensions.SI
import Data.Units.SI.Prefixes ( Kilo, Centi )
import Data.Constants.Math (piR)
import Language.Haskell.TH ( Name )
declareCanonicalUnit "Meter" [t| Length |] (Just "m")
type Metre = Meter
#if __GLASGOW_HASKELL >= 710
pattern Metre :: Metre
#endif
pattern Metre = Meter
declareCanonicalUnit "Gram" [t| Mass |] (Just "g")
type Gramme = Gram
#if __GLASGOW_HASKELL__ >= 710
pattern Gramme :: Gramme
#endif
pattern Gramme = Gram
declareCanonicalUnit "Second" [t| Time |] (Just "s")
-- | Derived SI unit
declareDerivedUnit "Minute" [t| Second |] 60 (Just "min")
-- | Derived SI unit
declareDerivedUnit "Hour" [t| Minute |] 60 (Just "h")
declareCanonicalUnit "Ampere" [t| Current |] (Just "A")
declareCanonicalUnit "Kelvin" [t| Temperature |] (Just "K")
declareCanonicalUnit "Mole" [t| AmountOfSubstance |] (Just "mol")
declareCanonicalUnit "Candela" [t| LuminousIntensity |] (Just "cd")
-- | The two angular dimensions that must be fundamental dimensions.
declareCanonicalUnit "Radian" [t| PlaneAngle |] (Just "rad")
declareCanonicalUnit "Steradian" [t| SolidAngle |] (Just "sr")
declareDerivedUnit "Hertz" [t| Number :/ Second |] 1 (Just "Hz")
-- | This is not in the SI standard, but is used widely.
declareDerivedUnit "Liter" [t| (Centi :@ Meter) :^ Three |] 1000 (Just "L")
type Litre = Liter
#if __GLASGOW_HASKELL__ >= 710
pattern Litre :: Litre
#endif
pattern Litre = Liter
declareDerivedUnit "Newton" [t| Gram :* Meter :/ (Second :^ Two) |] 1000 (Just "N")
declareDerivedUnit "Pascal" [t| Newton :/ (Meter :^ Two) |] 1 (Just "Pa")
declareDerivedUnit "Joule" [t| Newton :* Meter |] 1 (Just "J")
declareDerivedUnit "Watt" [t| Joule :/ Second |] 1 (Just "W")
declareDerivedUnit "Coulomb" [t| Ampere :* Second |] 1 (Just "C")
declareDerivedUnit "Volt" [t| Watt :/ Ampere |] 1 (Just "V")
declareDerivedUnit "Farad" [t| Coulomb :/ Volt |] 1 (Just "F")
declareDerivedUnit "Ohm" [t| Volt :/ Ampere |] 1 (Just "Ω")
declareDerivedUnit "Siemens" [t| Ampere :/ Volt |] 1 (Just "S")
declareDerivedUnit "Weber" [t| Volt :* Second |] 1 (Just "Wb")
declareDerivedUnit "Tesla" [t| Weber :/ (Meter :^ Two) |] 1 (Just "T")
declareDerivedUnit "Henry" [t| Weber :/ Ampere |] 1 (Just "H")
declareDerivedUnit "Lumen" [t| Candela |] 1 (Just "lm")
declareDerivedUnit "Lux" [t| Lumen :/ (Meter :^ Two) |] 1 (Just "lx")
declareDerivedUnit "Becquerel" [t| Number :/ Second |] 1 (Just "Bq")
declareDerivedUnit "Gray" [t| (Meter :^ Two) :/ (Second :^ Two) |] 1 (Just "Gy")
declareDerivedUnit "Sievert" [t| (Meter :^ Two) :/ (Second :^ Two) |] 1 (Just "Sv")
declareDerivedUnit "Katal" [t| Mole :/ Second |] 1 (Just "kat")
-- Non-SI units accepted for use with SI
-- (https://en.wikipedia.org/wiki/International_System_of_Units#Non-SI_units_accepted_for_use_with_SI)
declareDerivedUnit "Degree" [t| Radian |] (piR / 180) (Just "deg")
-- This should be printed as /'/ but Text.Parse.Units.mkSymbolTable says that's illegal.
declareDerivedUnit "Arcminute" [t| Degree |] (1 / 60) (Just "arcminute")
-- This should be printed as /"/ but Text.Parse.Units.mkSymbolTable says that's illegal.
declareDerivedUnit "Arcsecond" [t| Arcminute |] (1 / 60) (Just "arcsecond")
-- | Derived SI unit
declareDerivedUnit "Hectare" [t| Meter :^ Two |] 10000 (Just "ha")
-- | Derived SI unit
declareDerivedUnit "Ton" [t| Kilo :@ Gram |] 1000 (Just "t")
type Tonne = Ton
#if __GLASGOW_HASKELL__ >= 710
pattern Tonne :: Tonne
#endif
pattern Tonne = Ton
-- | A list of the names of all unit types. Useful with
-- 'Data.Metrology.Parser.makeQuasiQuoter'.
siUnits :: [Name]
siUnits =
[ ''Meter, ''Gram, ''Second, ''Minute, ''Hour, ''Ampere
, ''Kelvin, ''Mole, ''Candela, ''Hertz, ''Liter, ''Newton, ''Pascal
, ''Joule, ''Watt, ''Coulomb, ''Volt, ''Farad, ''Ohm, ''Siemens
, ''Weber, ''Tesla, ''Henry, ''Lumen, ''Radian, ''Lux, ''Becquerel, ''Gray
, ''Sievert, ''Katal, ''Degree, ''Arcminute
, ''Arcsecond,''Hectare, ''Ton
]
|
goldfirere/units
|
units-defs/Data/Units/SI.hs
|
bsd-3-clause
| 5,920 | 0 | 7 | 1,551 | 1,174 | 682 | 492 | 60 | 1 |
{- |
This module defines an internal (generic) representation for XML
documents including their DTDs.
History:
The original module was derived by hand from the XML specification,
following the grammar precisely. Then we simplified the types,
removing layers of indirection and redundancy, and generally making
things easier to work with. Then we allowed PEReferences to be
ubiquitous, by removing them from the types and resolving all
PE references at parse-time. Finally, we added a per-document
symbol table for GEReferences, and a whitespace-significance flag
for plaintext.
-}
module Text.XML.HaXml.Types
(
-- * A simple symbol table mapping strings (references) to values.
SymTab
-- ** Symbol table operations
, emptyST
, addST
, lookupST
-- * XML Types
-- ** The top-level document container
, Document(..)
-- ** The main document content
, Element(..)
, ElemTag(..)
, Content(..)
, Attribute
, AttValue(..)
, info
-- ** Administrative parts of the document
, Prolog(..)
, XMLDecl(..)
, Misc(..)
, ProcessingInstruction
, SDDecl
, VersionInfo
, Comment
, PITarget
-- ** The DTD
-- *** content model
, DocTypeDecl(..)
, MarkupDecl(..)
, ExtSubset(..)
, ExtSubsetDecl(..)
, ElementDecl(..)
, ContentSpec(..)
, CP(..)
, Modifier(..)
, Mixed(..)
-- *** attribute model
, AttListDecl(..)
, AttDef(..)
, AttType(..)
, TokenizedType(..)
, EnumeratedType(..)
, NotationType
, Enumeration
, DefaultDecl(..)
, FIXED(..)
-- *** conditional sections
, ConditionalSect(..)
, IncludeSect
, IgnoreSect
, Ignore(..)
, IgnoreSectContents(..)
-- ** References
, Reference(..)
, EntityRef
, CharRef
, PEReference
-- ** Entities
, EntityDecl(..)
, GEDecl(..)
, PEDecl(..)
, EntityDef(..)
, PEDef(..)
, ExternalID(..)
, NDataDecl(..)
, TextDecl(..)
, ExtParsedEnt(..)
, ExtPE(..)
, NotationDecl(..)
, PublicID(..)
, EncodingDecl(..)
, EntityValue(..)
, EV(..)
, PubidLiteral(..)
, SystemLiteral(..)
-- ** Basic value types
, Name
, Names
, NmToken
, NmTokens
, CharData
, CDSect
) where
{- A simple symbol table for storing macros whilst parsing. -}
type SymTab a = [(String,a)]
emptyST :: SymTab a
emptyST = []
addST :: String -> a -> SymTab a -> SymTab a
addST n v = ((n,v):)
lookupST :: String -> SymTab a -> Maybe a
lookupST = lookup
{- XML types start here -}
-- | The symbol table stored in a document holds all its general entity
-- reference definitions.
data Document i = Document Prolog (SymTab EntityDef) (Element i) [Misc]
data Prolog = Prolog (Maybe XMLDecl) [Misc] (Maybe DocTypeDecl) [Misc]
data XMLDecl = XMLDecl VersionInfo (Maybe EncodingDecl) (Maybe SDDecl)
data Misc = Comment Comment
| PI ProcessingInstruction
type ProcessingInstruction = (PITarget,String)
type SDDecl = Bool
type VersionInfo = String
type Comment = String
type PITarget = String
data DocTypeDecl = DTD Name (Maybe ExternalID) [MarkupDecl]
data MarkupDecl = Element ElementDecl
| AttList AttListDecl
| Entity EntityDecl
| Notation NotationDecl
| MarkupMisc Misc
data ExtSubset = ExtSubset (Maybe TextDecl) [ExtSubsetDecl]
data ExtSubsetDecl = ExtMarkupDecl MarkupDecl
| ExtConditionalSect ConditionalSect
data Element i = Elem Name [Attribute] [Content i]
data ElemTag = ElemTag Name [Attribute] -- ^ intermediate for parsing
type Attribute = (Name, AttValue)
data Content i = CElem (Element i) i
| CString Bool CharData i
-- ^ bool is whether whitespace is significant
| CRef Reference i
| CMisc Misc i
info (CElem _ i) = i
info (CString _ _ i) = i
info (CRef _ i) = i
info (CMisc _ i) = i
instance Functor Document where
fmap f (Document p st e ms) = Document p st (fmap f e) ms
instance Functor Element where
fmap f (Elem t as cs) = Elem t as (map (fmap f) cs)
instance Functor Content where
fmap f (CElem e i) = CElem (fmap f e) (f i)
fmap f (CString b s i) = CString b s (f i)
fmap f (CRef r i) = CRef r (f i)
fmap f (CMisc m i) = CMisc m (f i)
data ElementDecl = ElementDecl Name ContentSpec
data ContentSpec = EMPTY
| ANY
| Mixed Mixed
| ContentSpec CP
data CP = TagName Name Modifier
| Choice [CP] Modifier
| Seq [CP] Modifier
data Modifier = None -- ^ Just One
| Query -- ^ Zero Or One
| Star -- ^ Zero Or More
| Plus -- ^ One Or More
data Mixed = PCDATA
| PCDATAplus [Name]
data AttListDecl = AttListDecl Name [AttDef]
data AttDef = AttDef Name AttType DefaultDecl
data AttType = StringType
| TokenizedType TokenizedType
| EnumeratedType EnumeratedType
data TokenizedType = ID
| IDREF
| IDREFS
| ENTITY
| ENTITIES
| NMTOKEN
| NMTOKENS
data EnumeratedType = NotationType NotationType
| Enumeration Enumeration
type NotationType = [Name] -- nonempty list
type Enumeration = [NmToken] -- nonempty list
data DefaultDecl = REQUIRED
| IMPLIED
| DefaultTo AttValue (Maybe FIXED)
data FIXED = FIXED
data ConditionalSect = IncludeSect IncludeSect
| IgnoreSect IgnoreSect
type IncludeSect = [ExtSubsetDecl]
type IgnoreSect = [IgnoreSectContents]
data Ignore = Ignore
data IgnoreSectContents = IgnoreSectContents Ignore [(IgnoreSectContents,Ignore)]
data Reference = RefEntity EntityRef
| RefChar CharRef
deriving (Eq, Show)
type EntityRef = Name
type CharRef = Int
type PEReference = Name
data EntityDecl = EntityGEDecl GEDecl
| EntityPEDecl PEDecl
data GEDecl = GEDecl Name EntityDef
data PEDecl = PEDecl Name PEDef
data EntityDef = DefEntityValue EntityValue
| DefExternalID ExternalID (Maybe NDataDecl)
data PEDef = PEDefEntityValue EntityValue
| PEDefExternalID ExternalID deriving (Show)
data ExternalID = SYSTEM SystemLiteral
| PUBLIC PubidLiteral SystemLiteral deriving (Show)
newtype NDataDecl = NDATA Name
data TextDecl = TextDecl (Maybe VersionInfo) EncodingDecl
data ExtParsedEnt i = ExtParsedEnt (Maybe TextDecl) (Content i)
data ExtPE = ExtPE (Maybe TextDecl) [ExtSubsetDecl]
data NotationDecl = NOTATION Name (Either ExternalID PublicID)
newtype PublicID = PUBLICID PubidLiteral
newtype EncodingDecl = EncodingDecl String
type Name = String -- non-empty string
type Names = [Name] -- non-empty list
type NmToken = String -- non-empty string
type NmTokens = [NmToken] -- non-empty list
data AttValue = AttValue [Either String Reference]
deriving Eq
data EntityValue = EntityValue [EV] deriving (Show)
data EV = EVString String
-- -- | EVPERef PEReference
| EVRef Reference deriving (Show)
newtype PubidLiteral = PubidLiteral String deriving (Show)
newtype SystemLiteral = SystemLiteral String deriving (Show)
type CharData = String
type CDSect = CharData
instance Eq ElemTag where
(ElemTag n _) == (ElemTag m _) = n==m
|
FranklinChen/hugs98-plus-Sep2006
|
packages/HaXml/src/Text/XML/HaXml/Types.hs
|
bsd-3-clause
| 7,522 | 0 | 10 | 2,130 | 1,841 | 1,100 | 741 | 195 | 1 |
module Main (main) where
import Distribution.Simple
import System.Cmd (system)
main :: IO ()
main = defaultMainWithHooks $ simpleUserHooks {runTests = runMyTests}
runMyTests a b pd lb = system "runhaskell ./UnitTest.hs" >> return ()
|
hnakamur/haskell-sandbox
|
sandbox-json/Setup.hs
|
bsd-3-clause
| 236 | 0 | 7 | 36 | 77 | 42 | 35 | 6 | 1 |
-- | Extract various archive files in a consistent manner.
{-# LANGUAGE OverloadedStrings #-}
module Control.Shell.Extract
( -- * Extracting archives
extract, extractWith, supportedExtensions, canExtract
-- * Extraction options
, ExtractOptions, separateDirectory, removeArchive
, defaultExtractOptions
) where
import Control.Shell
import qualified Data.ByteString.Char8 as BS
import qualified Data.Text as T
import Network.Mime
import System.IO.Unsafe
data ExtractOptions = ExtractOptions
{ -- | Extract archive into a separate directory. The name of the directory
-- will be the base name of the archive.
-- If the archive contains a single directory on the top-level, the
-- contents of that directory will be moved into the outer directory.
-- This ensures that tarbombs and non-tarbombs are treated consistently.
--
-- If this option is set to @False@, archives will be unpacked into the
-- current working directory.
--
-- Default: @True@
separateDirectory :: Bool
-- | Remove the archive after extraction?
--
-- Default: @False@
, removeArchive :: Bool
}
-- | Default extraction options. See 'ExtractOptions' for defaults.
defaultExtractOptions :: ExtractOptions
defaultExtractOptions = ExtractOptions
{ separateDirectory = True
, removeArchive = False
}
-- | The list of supported archive format file extensions.
-- On a typical Linux/OSX/Cygwin/MinGW system, .tar, .tar.gz, .tar.bz2,
-- .tar.xz, .tbz2, .tgz, .bz2, .gz and .xz should all be supported.
-- If the appropriate programs are installed, .zip, .rar and .7z should also
-- be supported.
supportedExtensions :: [String]
supportedExtensions = unsafePerformIO $ do
env <- shell_ $ getShellEnv
res <- runSh (env {envStdErr = envStdOut env}) $ do
tar <- (capture (run "tar" ["-?"]) >> pure tarExts) `orElse` pure []
z7 <- (capture (run "7z" []) >> pure [".7z"]) `orElse` pure []
rar <- (capture (run "unrar" []) >> pure [".rar"]) `orElse` pure []
z <- (capture (run "unzip" []) >> pure [".zip"]) `orElse` pure []
xz <- (capture (run "xz" ["--help"]) >> pure [".xz"]) `orElse` pure []
bz2 <- (capture (run "bunzip2" ["--help"]) >> pure [".bz2"]) `orElse` pure []
gz <- (capture (run "gunzip" ["--help"]) >> pure [".gz"]) `orElse` pure []
pure $ concat [tar, z7, rar, z, xz, bz2, gz]
case res of
Left _ -> pure []
Right xs -> pure xs
where
tarExts = [".tar.gz", ".tar.bz2", ".tar.xz", ".tbz2", ".tgz", ".tar"]
-- | Can the given file be extracted, as determined by comparing the file
-- extension to the list of supported extensions.
canExtract :: FilePath -> Bool
canExtract f =
any (and . zipWith (==) f') (map reverse supportedExtensions)
where
f' = reverse f
-- | Extract an archive with the default options. See 'ExtractOptions'
-- for details.
extract :: FilePath -> Shell ()
extract = extractWith defaultExtractOptions
-- | Extract an archive with the given extraction options.
extractWith :: ExtractOptions -> FilePath -> Shell ()
extractWith opts file = do
archivedir <- pwd
let archive = archivedir </> file
mkdir True outputDir
case extractCmd archive of
Just (cmd, args)
| canExtract file -> inDirectory outputDir $ do
void . capture $ run cmd (args ++ [archive])
moveOutputToWorkDir archive
when (separateDirectory opts) $ void $ try mergeOneLevelRoot
when (removeArchive opts) $ rm archive
| otherwise ->
supportFail cmd
Nothing ->
mimeFail
where
outputDir
| separateDirectory opts = takeBasestName file
| otherwise = "."
mimeFail = fail $ concat
[ "mime type does not seem to be an archive: "
, BS.unpack $ defaultMimeLookup (T.pack file)
]
supportFail cmd = fail $ concat
[ "unable to unpack archive, as the program `" ++ cmd ++ "' "
, "was not found"
]
-- | If the current working directory contains a single directory, move all
-- contents of that directory into the working directory, then remove the
-- directory.
mergeOneLevelRoot :: Shell ()
mergeOneLevelRoot = do
[dir] <- ls "."
guard $ isDirectory dir
inCustomTempDirectory "." $ do
mv (".." </> dir) ("." </> dir)
files <- ls dir
mapM_ (\f -> mv (dir </> f) (".." </> f)) files
-- | Command + arguments to extract an archive file.
-- Arguments must be followed immediately by the archive file name.
extractCmd :: FilePath -> Maybe (FilePath, [String])
extractCmd f =
case defaultMimeLookup (T.pack f) of
"application/x-7z-compressed" -> Just ("7z", ["x"])
"application/zip" -> Just ("unzip", ["-o"])
"application/x-rar-compressed" -> Just ("unrar", ["x"])
"application/x-tar" -> Just ("tar", ["-xf"])
"application/x-tgz" -> Just ("tar", ["-xzf"])
"application/x-bzip-compressed-tar" -> Just ("tar", ["-xjf"])
"application/x-bzip" -> Just ("bunzip2", ["-k"])
"application/x-gzip" -> Just ("gunzip", ["-k"])
"application/x-xz"
| "application/x-tar" <- defaultMimeLookup (T.pack $ dropExtension f)
-> Just ("tar", ["-xJf"])
| otherwise -> Just ("xz", ["-dk"])
_ -> Nothing
-- | Move the extracted file of the given archive into the current working
-- directory, if the archive is .gz, .bz2 or .xz. Workaround for bunzip,
-- gunzip2 and xz insisting on unpacking files to the same directory as the
-- archive instead of to the current working directory.
moveOutputToWorkDir :: FilePath -> Shell ()
moveOutputToWorkDir f = when needsWorkaround $ mv f' (takeFileName f')
where
f' = dropExtension f
needsWorkaround =
case defaultMimeLookup (T.pack f) of
"application/x-bzip" -> True
"application/x-gzip" -> True
"application/x-xz" ->
"application/x-tar" /= defaultMimeLookup (T.pack f')
_ -> False
-- | Iterate 'takeBaseName' until all extensions are gone.
takeBasestName :: FilePath -> FilePath
takeBasestName f
| f == f' = f
| unknownExt f = f
| otherwise = takeBasestName f'
where
f' = takeBaseName f
unknownExt f = defaultMimeLookup (T.pack f) == "application/octet-stream"
|
valderman/shellmate
|
shellmate-extras/Control/Shell/Extract.hs
|
bsd-3-clause
| 6,465 | 0 | 19 | 1,639 | 1,526 | 798 | 728 | 106 | 10 |
{-# LANGUAGE OverloadedStrings #-}
import Web.Scotty
main = scotty 3000 $ do
get "/" $ do
file "static/index.html"
get "/:filename" $ do
filename <- param "filename"
file $ "static/" ++ filename
post "/:filename" $ do
filename <- param "filename"
file $ "static/" ++ filename
|
szatkus/haffen
|
Haffen.hs
|
bsd-3-clause
| 292 | 0 | 12 | 60 | 97 | 42 | 55 | 11 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE PolyKinds #-}
module Data.LnFunctor.Pointed where
import Data.LnFunctor
import Type.Families (Rfl)
class (LnFunctor f, LnInitial f) => LnPointed (f :: ix -> ix -> * -> *) where
lreturn :: Init f i j => a -> f i j a
ireturn :: (LnPointed f, Rfl Init f i) => a -> f i i a
ireturn = lreturn
|
kylcarte/lnfunctors
|
src/Data/LnFunctor/Pointed.hs
|
bsd-3-clause
| 341 | 0 | 10 | 71 | 133 | 72 | 61 | -1 | -1 |
module Lib.HGit
( module Lib.HGit.Readers
, module Lib.HGit.Writers
, module Lib.HGit.Data
, module Lib.HGit.Batch
) where
import Lib.HGit.Readers
import Lib.HGit.Writers
import Lib.HGit.Data
import Lib.HGit.Batch
|
MarcusWalz/hgit
|
Lib/HGit.hs
|
bsd-3-clause
| 266 | 0 | 5 | 76 | 60 | 41 | 19 | 9 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
-- | Exports useful types for other modules.
module Network.BitTorrent.Types (
maxRequestsPerPeer
, PeerData(..)
, newPeer
, TorrentStatus(..)
, TorrentState(..)
, GlobalState(..)
, SharedMessage(..)
, Chunks
, defaultChunkSize
, chunksInPiece
, expectedPieceSize
, expectedChunkSize
, PieceId(..)
, ChunkId(..)
) where
import Control.Concurrent
import Control.Concurrent.STM.TVar
import Data.Binary
import Data.ByteString.Internal as BI
import Data.IntSet (IntSet)
import Data.Map.Strict (Map)
import Data.Sequence (Seq)
-- import Hexdump
import Network.BitTorrent.BitField (BitField)
import Network.BitTorrent.ChunkField as CF
import qualified Network.BitTorrent.DownloadProgress as DP
import qualified Network.BitTorrent.LinkSpeed as LP
import Network.BitTorrent.MemoryMap
import Network.BitTorrent.MetaInfo as Meta
-- import Network.BitTorrent.PieceSelection as PS
import Network.BitTorrent.Utility
import Network.Socket
import System.IO
-- | Describes the limit of requests in flight to a single peer.
maxRequestsPerPeer :: Word8
maxRequestsPerPeer = 64
-- | Stores information about a peer.
data PeerData = PeerData {
amChoking :: !Bool
, amInterested :: !Bool
, peerChoking :: !Bool
, peerInterested :: !Bool
, address :: SockAddr
, peerId :: !ByteString
, peerBitField :: !BitField
, requestsLive :: !Word8
, peerDataStopping :: !Bool
} deriving(Eq, Show)
data GlobalState = GlobalState {
globalStatePeerId :: ByteString
, globalStateListenPort :: Word16
, globalStateTorrents :: TVar (Seq TorrentState)
}
data TorrentStatus = Active | Paused | Stopped
data TorrentState = TorrentState {
torrentStateMetaInfo :: MetaInfo
, torrentStateBitField :: TVar BitField
, torrentStateRequestablePieces :: TVar IntSet
, torrentStateDownloadProgress :: DP.ProgressStorage
, torrentStateOutputHandles :: Seq (Word64, Word64, Handle)
, torrentStateOutputMMaps :: Seq (Word64, Word64, MemoryMap)
, torrentStateOutputLock :: MVar ()
, torrentStateSharedMessages :: Chan SharedMessage
, torrentStatePeerThreads :: TVar (Seq (ThreadId, ByteString))
, torrentStateStatus :: TVar TorrentStatus
, torrentStateDownloadSpeed :: TVar LP.Store
, torrentStateUploadSpeed :: TVar LP.Store
}
-- | Create a new 'PeerData' structure.
newPeer :: BitField -> SockAddr -> ByteString -> PeerData
newPeer bf addr peer =
PeerData True False True False addr peer bf 0 False
{-# INLINABLE newPeer #-}
-- | Describes shared messages that can be broadcasted to peer loops.
data SharedMessage = RequestPiece | Checkup | Exit deriving (Eq, Show)
-- | Stores download progress for pieces.
--
-- For each piece that is being downloaded, holds the 'ChunkField' and
-- the full buffer with data.
type Chunks = Map PieceId ChunkField
-- | Describes granularity of a request.
--
-- /2^14/ is the size recommended by the standard.
defaultChunkSize :: Word32
defaultChunkSize = 2 ^ (14 :: Word32)
-- | Calculates the number of chunks in a piece.
chunksInPiece :: Word32 -- ^ piece size
-> Word32 -- ^ chunk size
-> Word32
chunksInPiece = divideSize
{-# INLINABLE chunksInPiece #-}
-- | Calculates the piece size.
expectedPieceSize :: Word64 -- ^ total size of all pieces
-> Word32 -- ^ piece size
-> PieceId
-> Word32
expectedPieceSize totalSize pSize (PieceId pix) =
if pix >= pCount
then if totalSize `rem` pSize' == 0
then pSize
else fromIntegral $ totalSize `rem` pSize'
else pSize
where pCount = fromIntegral $ divideSize totalSize pSize' - 1
pSize' = fromIntegral pSize
{-# INLINABLE expectedPieceSize #-}
-- | Calculates the chunk size.
expectedChunkSize :: Word64 -- ^ total size of all pieces
-> Word32 -- ^ piece size
-> Word32 -- ^ default chunk size
-> PieceId -- ^ piece index
-> ChunkId -- ^ chunk index
-> Word32
expectedChunkSize totalSize pSize cSize piece (ChunkId cix) =
if (cix + 1) >= chunksCount
then if expectedPSize `rem` cSize == 0
then cSize
else expectedPSize `rem` cSize
else cSize
where expectedPSize = expectedPieceSize totalSize pSize piece
chunksCount = chunksInPiece expectedPSize cSize
{-# INLINABLE expectedChunkSize #-}
|
farnoy/torrent
|
src/Network/BitTorrent/Types.hs
|
bsd-3-clause
| 4,423 | 0 | 12 | 926 | 862 | 522 | 340 | 117 | 3 |
module Text.Tagset.Data
( Tagset (Tagset)
, Rule (Rule)
, TagView (NKJPView, MorphosView)
, Label
, tagView
, ruleDefs
, attrDefs
, rulePred
, attsFor
, allAtts
, attrValues
, Optional
, Attr
, AttrValue
) where
import Control.Monad (liftM3)
import qualified Data.Map as Map
import qualified Data.Text as T
import Data.List (intercalate)
import Data.Binary (Binary, get, put, putWord8, getWord8)
type Pred = [(Attr, AttrValue)]
type Action = [(Attr, Optional)]
data Rule = Rule Pred Action deriving (Show)
instance Binary Rule where
put (Rule pred action) = put (pred, action)
get = get >>= return . uncurry Rule
data TagView = NKJPView
| MorphosView
deriving (Eq, Show)
instance Binary TagView where
put NKJPView = putWord8 0
put MorphosView = putWord8 1
get = do
x <- getWord8
case x of
0 -> return NKJPView
1 -> return MorphosView
data Tagset = Tagset { attrDefs :: Map.Map Attr [AttrValue]
, ruleDefs :: [Rule]
, tagView :: TagView
} deriving (Show)
instance Binary Tagset where
put ts = put (attrDefs ts)
>> put (ruleDefs ts)
>> put (tagView ts)
get = liftM3 Tagset get get get
type Optional = Bool
type Attr = String
type AttrValue = String
-- attsFor :: Tagset -> Pos -> [(Attr, Optional)]
-- attsFor tagset pos = (posDefs tagset) Map.! pos
rulePred :: Rule -> Pred
rulePred (Rule pred _) = pred
attsFor :: Rule -> [(Attr, Optional)]
attsFor (Rule _ atts) = atts
attrValues :: Tagset -> Attr -> [AttrValue]
attrValues tagset attr = (attrDefs tagset) Map.! attr
allAtts :: Tagset -> [Attr]
allAtts tagset = Map.keys $ attrDefs tagset
-- [(Attr AttrValue)]; using T.Text for high speed.
type Label = [(T.Text, T.Text)]
|
kawu/tagger
|
src/Text/Tagset/Data.hs
|
bsd-3-clause
| 1,805 | 1 | 10 | 457 | 588 | 334 | 254 | 64 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.SES.ListIdentities
-- 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)
--
-- Returns a list containing all of the identities (email addresses and
-- domains) for a specific AWS Account, regardless of verification status.
--
-- This action is throttled at one request per second.
--
-- /See:/ <http://docs.aws.amazon.com/ses/latest/APIReference/API_ListIdentities.html AWS API Reference> for ListIdentities.
--
-- This operation returns paginated results.
module Network.AWS.SES.ListIdentities
(
-- * Creating a Request
listIdentities
, ListIdentities
-- * Request Lenses
, liIdentityType
, liNextToken
, liMaxItems
-- * Destructuring the Response
, listIdentitiesResponse
, ListIdentitiesResponse
-- * Response Lenses
, lirsNextToken
, lirsResponseStatus
, lirsIdentities
) where
import Network.AWS.Pager
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
import Network.AWS.SES.Types
import Network.AWS.SES.Types.Product
-- | Represents a request instructing the service to list all identities for
-- the AWS Account.
--
-- /See:/ 'listIdentities' smart constructor.
data ListIdentities = ListIdentities'
{ _liIdentityType :: !(Maybe IdentityType)
, _liNextToken :: !(Maybe Text)
, _liMaxItems :: !(Maybe Int)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListIdentities' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'liIdentityType'
--
-- * 'liNextToken'
--
-- * 'liMaxItems'
listIdentities
:: ListIdentities
listIdentities =
ListIdentities'
{ _liIdentityType = Nothing
, _liNextToken = Nothing
, _liMaxItems = Nothing
}
-- | The type of the identities to list. Possible values are \"EmailAddress\"
-- and \"Domain\". If this parameter is omitted, then all identities will
-- be listed.
liIdentityType :: Lens' ListIdentities (Maybe IdentityType)
liIdentityType = lens _liIdentityType (\ s a -> s{_liIdentityType = a});
-- | The token to use for pagination.
liNextToken :: Lens' ListIdentities (Maybe Text)
liNextToken = lens _liNextToken (\ s a -> s{_liNextToken = a});
-- | The maximum number of identities per page. Possible values are 1-1000
-- inclusive.
liMaxItems :: Lens' ListIdentities (Maybe Int)
liMaxItems = lens _liMaxItems (\ s a -> s{_liMaxItems = a});
instance AWSPager ListIdentities where
page rq rs
| stop (rs ^. lirsNextToken) = Nothing
| stop (rs ^. lirsIdentities) = Nothing
| otherwise =
Just $ rq & liNextToken .~ rs ^. lirsNextToken
instance AWSRequest ListIdentities where
type Rs ListIdentities = ListIdentitiesResponse
request = postQuery sES
response
= receiveXMLWrapper "ListIdentitiesResult"
(\ s h x ->
ListIdentitiesResponse' <$>
(x .@? "NextToken") <*> (pure (fromEnum s)) <*>
(x .@? "Identities" .!@ mempty >>=
parseXMLList "member"))
instance ToHeaders ListIdentities where
toHeaders = const mempty
instance ToPath ListIdentities where
toPath = const "/"
instance ToQuery ListIdentities where
toQuery ListIdentities'{..}
= mconcat
["Action" =: ("ListIdentities" :: ByteString),
"Version" =: ("2010-12-01" :: ByteString),
"IdentityType" =: _liIdentityType,
"NextToken" =: _liNextToken,
"MaxItems" =: _liMaxItems]
-- | Represents a list of all verified identities for the AWS Account.
--
-- /See:/ 'listIdentitiesResponse' smart constructor.
data ListIdentitiesResponse = ListIdentitiesResponse'
{ _lirsNextToken :: !(Maybe Text)
, _lirsResponseStatus :: !Int
, _lirsIdentities :: ![Text]
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListIdentitiesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lirsNextToken'
--
-- * 'lirsResponseStatus'
--
-- * 'lirsIdentities'
listIdentitiesResponse
:: Int -- ^ 'lirsResponseStatus'
-> ListIdentitiesResponse
listIdentitiesResponse pResponseStatus_ =
ListIdentitiesResponse'
{ _lirsNextToken = Nothing
, _lirsResponseStatus = pResponseStatus_
, _lirsIdentities = mempty
}
-- | The token used for pagination.
lirsNextToken :: Lens' ListIdentitiesResponse (Maybe Text)
lirsNextToken = lens _lirsNextToken (\ s a -> s{_lirsNextToken = a});
-- | The response status code.
lirsResponseStatus :: Lens' ListIdentitiesResponse Int
lirsResponseStatus = lens _lirsResponseStatus (\ s a -> s{_lirsResponseStatus = a});
-- | A list of identities.
lirsIdentities :: Lens' ListIdentitiesResponse [Text]
lirsIdentities = lens _lirsIdentities (\ s a -> s{_lirsIdentities = a}) . _Coerce;
|
fmapfmapfmap/amazonka
|
amazonka-ses/gen/Network/AWS/SES/ListIdentities.hs
|
mpl-2.0
| 5,641 | 0 | 14 | 1,248 | 894 | 526 | 368 | 103 | 1 |
{-
Copyright 2019 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
-- |
-- Module : Data.MultiMap
-- Copyright : (c) CodeWorld Authors 2017
-- License : Apache-2.0
--
-- Maintainer : Joachim Breitner <[email protected]>
--
-- A simple MultiMap.
--
-- This differs from the one in the @multimap@ package by using
-- 'Data.Sequence.Seq' for efficient insert-at-end and other improved speeds.
--
-- Also only supports the operations required by CodeWorld for now.
{-# LANGUAGE TupleSections #-}
module Data.MultiMap
( MultiMap
, empty
, null
, insertL
, insertR
, toList
, spanAntitone
, union
, keys
) where
import Data.Bifunctor
import Data.Coerce
import qualified Data.Foldable (toList)
import qualified Data.Map as M
import qualified Data.Sequence as S
import Prelude hiding (null)
newtype MultiMap k v =
MM (M.Map k (S.Seq v))
deriving (Show, Eq)
empty :: MultiMap k v
empty = MM M.empty
null :: MultiMap k v -> Bool
null (MM m) = M.null m
insertL :: Ord k => k -> v -> MultiMap k v -> MultiMap k v
insertL k v (MM m) = MM (M.alter (Just . maybe (S.singleton v) (v S.<|)) k m)
insertR :: Ord k => k -> v -> MultiMap k v -> MultiMap k v
insertR k v (MM m) = MM (M.alter (Just . maybe (S.singleton v) (S.|> v)) k m)
toList :: MultiMap k v -> [(k, v)]
toList (MM m) = [(k, v) | (k, vs) <- M.toList m, v <- Data.Foldable.toList vs]
-- TODO: replace with M.spanAntitone once containers is updated
mapSpanAntitone :: (k -> Bool) -> M.Map k a -> (M.Map k a, M.Map k a)
mapSpanAntitone p =
bimap M.fromDistinctAscList M.fromDistinctAscList .
span (p . fst) . M.toList
spanAntitone :: (k -> Bool) -> MultiMap k v -> (MultiMap k v, MultiMap k v)
spanAntitone p (MM m) = coerce (mapSpanAntitone p m)
union :: Ord k => MultiMap k v -> MultiMap k v -> MultiMap k v
union (MM m1) (MM m2) = MM (M.unionWith (S.><) m1 m2)
keys :: MultiMap k v -> [k]
keys (MM m) = M.keys m
|
alphalambda/codeworld
|
codeworld-prediction/src/Data/MultiMap.hs
|
apache-2.0
| 2,493 | 0 | 13 | 538 | 718 | 384 | 334 | 40 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStyleOptionToolBox.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:25
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QStyleOptionToolBox (
QqStyleOptionToolBox(..)
,QqStyleOptionToolBox_nf(..)
,qStyleOptionToolBox_delete
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqStyleOptionToolBox x1 where
qStyleOptionToolBox :: x1 -> IO (QStyleOptionToolBox ())
instance QqStyleOptionToolBox (()) where
qStyleOptionToolBox ()
= withQStyleOptionToolBoxResult $
qtc_QStyleOptionToolBox
foreign import ccall "qtc_QStyleOptionToolBox" qtc_QStyleOptionToolBox :: IO (Ptr (TQStyleOptionToolBox ()))
instance QqStyleOptionToolBox ((QStyleOptionToolBox t1)) where
qStyleOptionToolBox (x1)
= withQStyleOptionToolBoxResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionToolBox1 cobj_x1
foreign import ccall "qtc_QStyleOptionToolBox1" qtc_QStyleOptionToolBox1 :: Ptr (TQStyleOptionToolBox t1) -> IO (Ptr (TQStyleOptionToolBox ()))
class QqStyleOptionToolBox_nf x1 where
qStyleOptionToolBox_nf :: x1 -> IO (QStyleOptionToolBox ())
instance QqStyleOptionToolBox_nf (()) where
qStyleOptionToolBox_nf ()
= withObjectRefResult $
qtc_QStyleOptionToolBox
instance QqStyleOptionToolBox_nf ((QStyleOptionToolBox t1)) where
qStyleOptionToolBox_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionToolBox1 cobj_x1
instance Qicon (QStyleOptionToolBox a) (()) (IO (QIcon ())) where
icon x0 ()
= withQIconResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionToolBox_icon cobj_x0
foreign import ccall "qtc_QStyleOptionToolBox_icon" qtc_QStyleOptionToolBox_icon :: Ptr (TQStyleOptionToolBox a) -> IO (Ptr (TQIcon ()))
instance QsetIcon (QStyleOptionToolBox a) ((QIcon t1)) where
setIcon x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionToolBox_setIcon cobj_x0 cobj_x1
foreign import ccall "qtc_QStyleOptionToolBox_setIcon" qtc_QStyleOptionToolBox_setIcon :: Ptr (TQStyleOptionToolBox a) -> Ptr (TQIcon t1) -> IO ()
instance QsetText (QStyleOptionToolBox a) ((String)) where
setText x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QStyleOptionToolBox_setText cobj_x0 cstr_x1
foreign import ccall "qtc_QStyleOptionToolBox_setText" qtc_QStyleOptionToolBox_setText :: Ptr (TQStyleOptionToolBox a) -> CWString -> IO ()
instance Qtext (QStyleOptionToolBox a) (()) (IO (String)) where
text x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionToolBox_text cobj_x0
foreign import ccall "qtc_QStyleOptionToolBox_text" qtc_QStyleOptionToolBox_text :: Ptr (TQStyleOptionToolBox a) -> IO (Ptr (TQString ()))
qStyleOptionToolBox_delete :: QStyleOptionToolBox a -> IO ()
qStyleOptionToolBox_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionToolBox_delete cobj_x0
foreign import ccall "qtc_QStyleOptionToolBox_delete" qtc_QStyleOptionToolBox_delete :: Ptr (TQStyleOptionToolBox a) -> IO ()
|
keera-studios/hsQt
|
Qtc/Gui/QStyleOptionToolBox.hs
|
bsd-2-clause
| 3,503 | 0 | 12 | 498 | 854 | 445 | 409 | -1 | -1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
The Desugarer: turning HsSyn into Core.
-}
{-# LANGUAGE CPP #-}
module Desugar ( deSugar, deSugarExpr ) where
import DynFlags
import HscTypes
import HsSyn
import TcRnTypes
import TcRnMonad ( finalSafeMode, fixSafeInstances )
import MkIface
import Id
import Name
import Type
import FamInstEnv
import Coercion
import InstEnv
import Class
import Avail
import CoreSyn
import CoreFVs( exprsSomeFreeVars )
import CoreSubst
import PprCore
import DsMonad
import DsExpr
import DsBinds
import DsForeign
import Module
import NameSet
import NameEnv
import Rules
import TysPrim (eqReprPrimTyCon)
import TysWiredIn (coercibleTyCon )
import BasicTypes ( Activation(.. ), competesWith, pprRuleName )
import CoreMonad ( CoreToDo(..) )
import CoreLint ( endPassIO )
import MkCore
import VarSet
import FastString
import ErrUtils
import Outputable
import SrcLoc
import Coverage
import Util
import MonadUtils
import OrdList
import StaticPtrTable
import Data.List
import Data.IORef
import Control.Monad( when )
{-
************************************************************************
* *
* The main function: deSugar
* *
************************************************************************
-}
-- | Main entry point to the desugarer.
deSugar :: HscEnv -> ModLocation -> TcGblEnv -> IO (Messages, Maybe ModGuts)
-- Can modify PCS by faulting in more declarations
deSugar hsc_env
mod_loc
tcg_env@(TcGblEnv { tcg_mod = mod,
tcg_src = hsc_src,
tcg_type_env = type_env,
tcg_imports = imports,
tcg_exports = exports,
tcg_keep = keep_var,
tcg_th_splice_used = tc_splice_used,
tcg_rdr_env = rdr_env,
tcg_fix_env = fix_env,
tcg_inst_env = inst_env,
tcg_fam_inst_env = fam_inst_env,
tcg_warns = warns,
tcg_anns = anns,
tcg_binds = binds,
tcg_imp_specs = imp_specs,
tcg_dependent_files = dependent_files,
tcg_ev_binds = ev_binds,
tcg_fords = fords,
tcg_rules = rules,
tcg_vects = vects,
tcg_patsyns = patsyns,
tcg_tcs = tcs,
tcg_insts = insts,
tcg_fam_insts = fam_insts,
tcg_hpc = other_hpc_info})
= do { let dflags = hsc_dflags hsc_env
print_unqual = mkPrintUnqualified dflags rdr_env
; showPass dflags "Desugar"
-- Desugar the program
; let export_set = availsToNameSet exports
target = hscTarget dflags
hpcInfo = emptyHpcInfo other_hpc_info
; (binds_cvr, ds_hpc_info, modBreaks)
<- if not (isHsBoot hsc_src)
then addTicksToBinds dflags mod mod_loc export_set
(typeEnvTyCons type_env) binds
else return (binds, hpcInfo, emptyModBreaks)
; (msgs, mb_res) <- initDs hsc_env mod rdr_env type_env fam_inst_env $
do { ds_ev_binds <- dsEvBinds ev_binds
; core_prs <- dsTopLHsBinds binds_cvr
; (spec_prs, spec_rules) <- dsImpSpecs imp_specs
; (ds_fords, foreign_prs) <- dsForeigns fords
; ds_rules <- mapMaybeM dsRule rules
; ds_vects <- mapM dsVect vects
; stBinds <- dsGetStaticBindsVar >>=
liftIO . readIORef
; let hpc_init
| gopt Opt_Hpc dflags = hpcInitCode mod ds_hpc_info
| otherwise = empty
-- Stub to insert the static entries of the
-- module into the static pointer table
spt_init = sptInitCode mod stBinds
; return ( ds_ev_binds
, foreign_prs `appOL` core_prs `appOL` spec_prs
`appOL` toOL (map snd stBinds)
, spec_rules ++ ds_rules, ds_vects
, ds_fords `appendStubC` hpc_init
`appendStubC` spt_init) }
; case mb_res of {
Nothing -> return (msgs, Nothing) ;
Just (ds_ev_binds, all_prs, all_rules, vects0, ds_fords) -> do
do { -- Add export flags to bindings
keep_alive <- readIORef keep_var
; let (rules_for_locals, rules_for_imps) = partition isLocalRule all_rules
final_prs = addExportFlagsAndRules target export_set keep_alive
rules_for_locals (fromOL all_prs)
final_pgm = combineEvBinds ds_ev_binds final_prs
-- Notice that we put the whole lot in a big Rec, even the foreign binds
-- When compiling PrelFloat, which defines data Float = F# Float#
-- we want F# to be in scope in the foreign marshalling code!
-- You might think it doesn't matter, but the simplifier brings all top-level
-- things into the in-scope set before simplifying; so we get no unfolding for F#!
#ifdef DEBUG
-- Debug only as pre-simple-optimisation program may be really big
; endPassIO hsc_env print_unqual CoreDesugar final_pgm rules_for_imps
#endif
; (ds_binds, ds_rules_for_imps, ds_vects)
<- simpleOptPgm dflags mod final_pgm rules_for_imps vects0
-- The simpleOptPgm gets rid of type
-- bindings plus any stupid dead code
; endPassIO hsc_env print_unqual CoreDesugarOpt ds_binds ds_rules_for_imps
; let used_names = mkUsedNames tcg_env
; deps <- mkDependencies tcg_env
; used_th <- readIORef tc_splice_used
; dep_files <- readIORef dependent_files
; safe_mode <- finalSafeMode dflags tcg_env
; let mod_guts = ModGuts {
mg_module = mod,
mg_hsc_src = hsc_src,
mg_loc = mkFileSrcSpan mod_loc,
mg_exports = exports,
mg_deps = deps,
mg_used_names = used_names,
mg_used_th = used_th,
mg_dir_imps = imp_mods imports,
mg_rdr_env = rdr_env,
mg_fix_env = fix_env,
mg_warns = warns,
mg_anns = anns,
mg_tcs = tcs,
mg_insts = fixSafeInstances safe_mode insts,
mg_fam_insts = fam_insts,
mg_inst_env = inst_env,
mg_fam_inst_env = fam_inst_env,
mg_patsyns = patsyns,
mg_rules = ds_rules_for_imps,
mg_binds = ds_binds,
mg_foreign = ds_fords,
mg_hpc_info = ds_hpc_info,
mg_modBreaks = modBreaks,
mg_vect_decls = ds_vects,
mg_vect_info = noVectInfo,
mg_safe_haskell = safe_mode,
mg_trust_pkg = imp_trust_own_pkg imports,
mg_dependent_files = dep_files
}
; return (msgs, Just mod_guts)
}}}
mkFileSrcSpan :: ModLocation -> SrcSpan
mkFileSrcSpan mod_loc
= case ml_hs_file mod_loc of
Just file_path -> mkGeneralSrcSpan (mkFastString file_path)
Nothing -> interactiveSrcSpan -- Presumably
dsImpSpecs :: [LTcSpecPrag] -> DsM (OrdList (Id,CoreExpr), [CoreRule])
dsImpSpecs imp_specs
= do { spec_prs <- mapMaybeM (dsSpec Nothing) imp_specs
; let (spec_binds, spec_rules) = unzip spec_prs
; return (concatOL spec_binds, spec_rules) }
combineEvBinds :: [CoreBind] -> [(Id,CoreExpr)] -> [CoreBind]
-- Top-level bindings can include coercion bindings, but not via superclasses
-- See Note [Top-level evidence]
combineEvBinds [] val_prs
= [Rec val_prs]
combineEvBinds (NonRec b r : bs) val_prs
| isId b = combineEvBinds bs ((b,r):val_prs)
| otherwise = NonRec b r : combineEvBinds bs val_prs
combineEvBinds (Rec prs : bs) val_prs
= combineEvBinds bs (prs ++ val_prs)
{-
Note [Top-level evidence]
~~~~~~~~~~~~~~~~~~~~~~~~~
Top-level evidence bindings may be mutually recursive with the top-level value
bindings, so we must put those in a Rec. But we can't put them *all* in a Rec
because the occurrence analyser doesn't teke account of type/coercion variables
when computing dependencies.
So we pull out the type/coercion variables (which are in dependency order),
and Rec the rest.
-}
deSugarExpr :: HscEnv -> LHsExpr Id -> IO (Messages, Maybe CoreExpr)
deSugarExpr hsc_env tc_expr
= do { let dflags = hsc_dflags hsc_env
icntxt = hsc_IC hsc_env
rdr_env = ic_rn_gbl_env icntxt
type_env = mkTypeEnvWithImplicits (ic_tythings icntxt)
fam_insts = snd (ic_instances icntxt)
fam_inst_env = extendFamInstEnvList emptyFamInstEnv fam_insts
-- This stuff is a half baked version of TcRnDriver.setInteractiveContext
; showPass dflags "Desugar"
-- Do desugaring
; (msgs, mb_core_expr) <- initDs hsc_env (icInteractiveModule icntxt) rdr_env
type_env fam_inst_env $
dsLExpr tc_expr
; case mb_core_expr of
Nothing -> return ()
Just expr -> dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr expr)
; return (msgs, mb_core_expr) }
{-
************************************************************************
* *
* Add rules and export flags to binders
* *
************************************************************************
-}
addExportFlagsAndRules
:: HscTarget -> NameSet -> NameSet -> [CoreRule]
-> [(Id, t)] -> [(Id, t)]
addExportFlagsAndRules target exports keep_alive rules prs
= mapFst add_one prs
where
add_one bndr = add_rules name (add_export name bndr)
where
name = idName bndr
---------- Rules --------
-- See Note [Attach rules to local ids]
-- NB: the binder might have some existing rules,
-- arising from specialisation pragmas
add_rules name bndr
| Just rules <- lookupNameEnv rule_base name
= bndr `addIdSpecialisations` rules
| otherwise
= bndr
rule_base = extendRuleBaseList emptyRuleBase rules
---------- Export flag --------
-- See Note [Adding export flags]
add_export name bndr
| dont_discard name = setIdExported bndr
| otherwise = bndr
dont_discard :: Name -> Bool
dont_discard name = is_exported name
|| name `elemNameSet` keep_alive
-- In interactive mode, we don't want to discard any top-level
-- entities at all (eg. do not inline them away during
-- simplification), and retain them all in the TypeEnv so they are
-- available from the command line.
--
-- isExternalName separates the user-defined top-level names from those
-- introduced by the type checker.
is_exported :: Name -> Bool
is_exported | targetRetainsAllBindings target = isExternalName
| otherwise = (`elemNameSet` exports)
{-
Note [Adding export flags]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Set the no-discard flag if either
a) the Id is exported
b) it's mentioned in the RHS of an orphan rule
c) it's in the keep-alive set
It means that the binding won't be discarded EVEN if the binding
ends up being trivial (v = w) -- the simplifier would usually just
substitute w for v throughout, but we don't apply the substitution to
the rules (maybe we should?), so this substitution would make the rule
bogus.
You might wonder why exported Ids aren't already marked as such;
it's just because the type checker is rather busy already and
I didn't want to pass in yet another mapping.
Note [Attach rules to local ids]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Find the rules for locally-defined Ids; then we can attach them
to the binders in the top-level bindings
Reason
- It makes the rules easier to look up
- It means that transformation rules and specialisations for
locally defined Ids are handled uniformly
- It keeps alive things that are referred to only from a rule
(the occurrence analyser knows about rules attached to Ids)
- It makes sure that, when we apply a rule, the free vars
of the RHS are more likely to be in scope
- The imported rules are carried in the in-scope set
which is extended on each iteration by the new wave of
local binders; any rules which aren't on the binding will
thereby get dropped
************************************************************************
* *
* Desugaring transformation rules
* *
************************************************************************
-}
dsRule :: LRuleDecl Id -> DsM (Maybe CoreRule)
dsRule (L loc (HsRule name rule_act vars lhs _tv_lhs rhs _fv_rhs))
= putSrcSpanDs loc $
do { let bndrs' = [var | L _ (RuleBndr (L _ var)) <- vars]
; lhs' <- unsetGOptM Opt_EnableRewriteRules $
unsetWOptM Opt_WarnIdentities $
dsLExpr lhs -- Note [Desugaring RULE left hand sides]
; rhs' <- dsLExpr rhs
; this_mod <- getModule
; (bndrs'', lhs'', rhs'') <- unfold_coerce bndrs' lhs' rhs'
-- Substitute the dict bindings eagerly,
-- and take the body apart into a (f args) form
; case decomposeRuleLhs bndrs'' lhs'' of {
Left msg -> do { warnDs msg; return Nothing } ;
Right (final_bndrs, fn_id, args) -> do
{ let is_local = isLocalId fn_id
-- NB: isLocalId is False of implicit Ids. This is good because
-- we don't want to attach rules to the bindings of implicit Ids,
-- because they don't show up in the bindings until just before code gen
fn_name = idName fn_id
final_rhs = simpleOptExpr rhs'' -- De-crap it
rule_name = snd (unLoc name)
rule = mkRule this_mod False {- Not auto -} is_local
rule_name rule_act fn_name final_bndrs args
final_rhs
arg_ids = varSetElems (exprsSomeFreeVars isId args `delVarSetList` final_bndrs)
; dflags <- getDynFlags
; when (wopt Opt_WarnInlineRuleShadowing dflags) $
warnRuleShadowing rule_name rule_act fn_id arg_ids
; return (Just rule)
} } }
warnRuleShadowing :: RuleName -> Activation -> Id -> [Id] -> DsM ()
-- See Note [Rules and inlining/other rules]
warnRuleShadowing rule_name rule_act fn_id arg_ids
= do { check False fn_id -- We often have multiple rules for the same Id in a
-- module. Maybe we should check that they don't overlap
-- but currently we don't
; mapM_ (check True) arg_ids }
where
check check_rules_too lhs_id
| isLocalId lhs_id || canUnfold (idUnfolding lhs_id)
-- If imported with no unfolding, no worries
, idInlineActivation lhs_id `competesWith` rule_act
= warnDs (vcat [ hang (ptext (sLit "Rule") <+> pprRuleName rule_name
<+> ptext (sLit "may never fire"))
2 (ptext (sLit "because") <+> quotes (ppr lhs_id)
<+> ptext (sLit "might inline first"))
, ptext (sLit "Probable fix: add an INLINE[n] or NOINLINE[n] pragma for")
<+> quotes (ppr lhs_id)
, ifPprDebug (ppr (idInlineActivation lhs_id) $$ ppr rule_act) ])
| check_rules_too
, bad_rule : _ <- get_bad_rules lhs_id
= warnDs (vcat [ hang (ptext (sLit "Rule") <+> pprRuleName rule_name
<+> ptext (sLit "may never fire"))
2 (ptext (sLit "because rule") <+> pprRuleName (ruleName bad_rule)
<+> ptext (sLit "for")<+> quotes (ppr lhs_id)
<+> ptext (sLit "might fire first"))
, ptext (sLit "Probable fix: add phase [n] or [~n] to the competing rule")
, ifPprDebug (ppr bad_rule) ])
| otherwise
= return ()
get_bad_rules lhs_id
= [ rule | rule <- idCoreRules lhs_id
, ruleActivation rule `competesWith` rule_act ]
-- See Note [Desugaring coerce as cast]
unfold_coerce :: [Id] -> CoreExpr -> CoreExpr -> DsM ([Var], CoreExpr, CoreExpr)
unfold_coerce bndrs lhs rhs = do
(bndrs', wrap) <- go bndrs
return (bndrs', wrap lhs, wrap rhs)
where
go :: [Id] -> DsM ([Id], CoreExpr -> CoreExpr)
go [] = return ([], id)
go (v:vs)
| Just (tc, args) <- splitTyConApp_maybe (idType v)
, tc == coercibleTyCon = do
let ty' = mkTyConApp eqReprPrimTyCon args
v' <- mkDerivedLocalM mkRepEqOcc v ty'
(bndrs, wrap) <- go vs
return (v':bndrs, mkCoreLet (NonRec v (mkEqBox (mkCoVarCo v'))) . wrap)
| otherwise = do
(bndrs,wrap) <- go vs
return (v:bndrs, wrap)
{- Note [Desugaring RULE left hand sides]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For the LHS of a RULE we do *not* want to desugar
[x] to build (\cn. x `c` n)
We want to leave explicit lists simply as chains
of cons's. We can achieve that slightly indirectly by
switching off EnableRewriteRules. See DsExpr.dsExplicitList.
That keeps the desugaring of list comprehensions simple too.
Nor do we want to warn of conversion identities on the LHS;
the rule is precisly to optimise them:
{-# RULES "fromRational/id" fromRational = id :: Rational -> Rational #-}
Note [Desugaring coerce as cast]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We want the user to express a rule saying roughly “mapping a coercion over a
list can be replaced by a coercion”. But the cast operator of Core (▷) cannot
be written in Haskell. So we use `coerce` for that (#2110). The user writes
map coerce = coerce
as a RULE, and this optimizes any kind of mapped' casts aways, including `map
MkNewtype`.
For that we replace any forall'ed `c :: Coercible a b` value in a RULE by
corresponding `co :: a ~#R b` and wrap the LHS and the RHS in
`let c = MkCoercible co in ...`. This is later simplified to the desired form
by simpleOptExpr (for the LHS) resp. the simplifiers (for the RHS).
Note [Rules and inlining/other rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you have
f x = ...
g x = ...
{-# RULES "rule-for-f" forall x. f (g x) = ... #-}
then there's a good chance that in a potential rule redex
...f (g e)...
then 'f' or 'g' will inline befor the rule can fire. Solution: add an
INLINE [n] or NOINLINE [n] pragma to 'f' and 'g'.
Note that this applies to all the free variables on the LHS, both the
main function and things in its arguments.
We also check if there are Ids on the LHS that have competing RULES.
In the above example, suppose we had
{-# RULES "rule-for-g" forally. g [y] = ... #-}
Then "rule-for-f" and "rule-for-g" would compete. Better to add phase
control, so "rule-for-f" has a chance to fire before "rule-for-g" becomes
active; or perhpas after "rule-for-g" has become inactive. This is checked
by 'competesWith'
Class methods have a built-in RULE to select the method from the dictionary,
so you can't change the phase on this. That makes id very dubious to
match on class methods in RULE lhs's. See Trac #10595. I'm not happy
about this. For exmaple in Control.Arrow we have
{-# RULES "compose/arr" forall f g .
(arr f) . (arr g) = arr (f . g) #-}
and similar, which will elicit exactly these warnings, and risk never
firing. But it's not clear what to do instead. We could make the
class methocd rules inactive in phase 2, but that would delay when
subsequent transformations could fire.
************************************************************************
* *
* Desugaring vectorisation declarations
* *
************************************************************************
-}
dsVect :: LVectDecl Id -> DsM CoreVect
dsVect (L loc (HsVect _ (L _ v) rhs))
= putSrcSpanDs loc $
do { rhs' <- dsLExpr rhs
; return $ Vect v rhs'
}
dsVect (L _loc (HsNoVect _ (L _ v)))
= return $ NoVect v
dsVect (L _loc (HsVectTypeOut isScalar tycon rhs_tycon))
= return $ VectType isScalar tycon' rhs_tycon
where
tycon' | Just ty <- coreView $ mkTyConTy tycon
, (tycon', []) <- splitTyConApp ty = tycon'
| otherwise = tycon
dsVect vd@(L _ (HsVectTypeIn _ _ _ _))
= pprPanic "Desugar.dsVect: unexpected 'HsVectTypeIn'" (ppr vd)
dsVect (L _loc (HsVectClassOut cls))
= return $ VectClass (classTyCon cls)
dsVect vc@(L _ (HsVectClassIn _ _))
= pprPanic "Desugar.dsVect: unexpected 'HsVectClassIn'" (ppr vc)
dsVect (L _loc (HsVectInstOut inst))
= return $ VectInst (instanceDFunId inst)
dsVect vi@(L _ (HsVectInstIn _))
= pprPanic "Desugar.dsVect: unexpected 'HsVectInstIn'" (ppr vi)
|
ml9951/ghc
|
compiler/deSugar/Desugar.hs
|
bsd-3-clause
| 22,744 | 28 | 22 | 7,753 | 3,502 | 1,870 | 1,632 | 299 | 3 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
module Foundation.Check.Print
( propertyToResult
, PropertyResult(..)
, diffBlame
) where
import Foundation.Check.Property
import Foundation.Check.Types
import Basement.Imports
import Foundation.Collection
import Basement.Compat.Bifunctor (bimap)
import Foundation.Numerical
propertyToResult :: PropertyTestArg -> (PropertyResult, Bool)
propertyToResult propertyTestArg =
let args = propertyGetArgs propertyTestArg
checks = getChecks propertyTestArg
in if checkHasFailed checks
then printError args checks
else (PropertySuccess, not (null args))
where
printError args checks = (PropertyFailed (mconcat $ loop 1 args), False)
where
loop :: Word -> [String] -> [String]
loop _ [] = printChecks checks
loop !i (a:as) = "parameter " <> show i <> " : " <> a <> "\n" : loop (i+1) as
printChecks (PropertyBinaryOp True _ _ _) = []
printChecks (PropertyBinaryOp False n a b) =
[ "Property `a " <> n <> " b' failed where:\n"
, " a = " <> a <> "\n"
, " " <> bl1 <> "\n"
, " b = " <> b <> "\n"
, " " <> bl2 <> "\n"
]
where
(bl1, bl2) = diffBlame a b
printChecks (PropertyNamed True _) = []
printChecks (PropertyNamed False e) = ["Property " <> e <> " failed"]
printChecks (PropertyBoolean True) = []
printChecks (PropertyBoolean False) = ["Property failed"]
printChecks (PropertyFail _ e) = ["Property failed: " <> e]
printChecks (PropertyAnd True _ _) = []
printChecks (PropertyAnd False a1 a2) =
[ "Property `cond1 && cond2' failed where:\n"
, " cond1 = " <> h1 <> "\n"
]
<> ((<>) " " <$> hs1)
<>
[ " cond2 = " <> h2 <> "\n"
]
<> ((<>) " " <$> hs2)
where
(h1, hs1) = f a1
(h2, hs2) = f a2
f a = case printChecks a of
[] -> ("Succeed", [])
(x:xs) -> (x, xs)
propertyGetArgs (PropertyArg a p) = a : propertyGetArgs p
propertyGetArgs (PropertyEOA _) = []
getChecks (PropertyArg _ p) = getChecks p
getChecks (PropertyEOA c ) = c
diffBlame :: String -> String -> (String, String)
diffBlame a b = bimap fromList fromList $ go ([], []) (toList a) (toList b)
where
go (acc1, acc2) [] [] = (acc1, acc2)
go (acc1, acc2) l1 [] = (acc1 <> blaming (length l1), acc2)
go (acc1, acc2) [] l2 = (acc1 , acc2 <> blaming (length l2))
go (acc1, acc2) (x:xs) (y:ys)
| x == y = go (acc1 <> " ", acc2 <> " ") xs ys
| otherwise = go (acc1 <> "^", acc2 <> "^") xs ys
blaming n = replicate n '^'
|
vincenthz/hs-foundation
|
foundation/Foundation/Check/Print.hs
|
bsd-3-clause
| 3,176 | 0 | 14 | 1,147 | 1,015 | 539 | 476 | -1 | -1 |
module Shift.Computer where
-- -- $Id$
import Shift.Type
import Shift.Iterate
import Shift.Enum
import Data.FiniteMap
import Control.Monad ( guard, when, foldM )
import Random ( randomRIO )
import IO
import System
import Data.List (sort)
import Util.Zufall
import Util.Faktor
import Data.List ( group )
instance Show [Bool] where
show = map ( \ x -> if x then '+' else '-' )
smp :: Show a => [a] -> IO ()
smp = sequence_ . map print
--------------------------------------------------------------
next0 :: Int -> Pins -> [Bool] -> [Bool]
-- wegen effizienz wird maximum ps nicht immer ausgerechnet
next0 m ps xs =
let this = not $ and $ do p <- ps ; return $ xs !! (p - 1)
in this `seq` this : take (m-1) xs
next :: Pins -> [Bool] -> [Bool]
next ps = next0 (maximum $ 0 : ps) ps
strictly :: [[Bool]] -> [[Bool]]
-- das ist trivial wahr, erzwingt aber die auswertung der liste
strictly = takeWhile (( >= 0) . sum . map fromEnum )
zustands_folge :: Pins -> [[ Bool ]]
zustands_folge ps =
let m = maximum (0 : ps)
start = replicate m True
fun = next0 m ps
in tail
$ strictly
$ iterate_strict fun $ start
folge :: Pins -> [ Bool ]
folge = map head . zustands_folge
find :: Ord a => [a] -> (Int, Int)
-- findet Länge von Vorperiode und Periode
-- für eine unendliche schließlich periodische Folge
find xs =
let handle cache ((k,x) : rest) =
case lookupFM cache x of
Just i -> ( i, k-i )
Nothing -> handle ( addToFM cache x k ) rest
in handle emptyFM $ zip [0..] xs
-------------------------------------------------------------------
-------------------------------------------------------------------
-- ffind :: Eq a => (a -> a) -> a -> Int
ffind :: ([Bool] -> [Bool]) -> [Bool] -> Int
-- etwas more tricky:
-- vergleicht die folgen f x0, f f x0, ..., f^k x0
-- und f f x0, f f f f x0, ..., f^{2k} x0
ffind next x0 =
let slow = strictly $ iterate_strict next x0
fast = strictly $ iterate_strict (\ x -> next $! next $! x ) x0
-- c ist das kleinste c mit f^c x0 == f^{2c} x0
x = head $ do
( x ,y ) <- tail $ zip slow fast
guard $ x == y
return x
-- bestimme das erste vorkommen von x danach
-- (ergibt kleinste periodenlänge)
d = head $ do (i, y) <- tail $ zip [0..]
$ strictly $ iterate_strict next x
guard $ y == x
return i
in d
--------------------------------------------------------------------------
some :: Int -> IO Pins
some n = do
xfs <- mapM ( \ x -> do f <- randomRIO (1, n) ; return (x, f ) )
[ 1 .. n ]
return $ do (x, f) <- xfs ; guard $ f*f < n ; return x
somes :: Int -> Int -> IO Pins
somes n k = do
ps <- sequence $ do i <- [ 1 .. k ] ; return $ randomRIO (1, n)
return $ sort ps
suche :: Int -> Int -> IO ()
suche n k = do
putStrLn $ "optimiere q"
let handle top ( ps : rest ) = do
let s = maximum ( 0 : ps )
let p = ffind (next0 s ps) $ replicate s True
let q = -1
-- hiernach wird optimiert
let m = p
let sh = Shift { pins = ps, vorperiode = q, periode = p }
when ( m > top ) $ print (sh, primfaktoren $ fromIntegral p)
when ( m == top ) $ putStr " * "
handle ( max m top ) rest
handle 0 $ subsets k [1 .. n]
|
Erdwolf/autotool-bonn
|
src/Shift/Computer.hs
|
gpl-2.0
| 3,319 | 63 | 15 | 924 | 1,237 | 660 | 577 | 77 | 2 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE CPP #-}
-- | A module providing a means of creating multiple input forms, such as a
-- list of 0 or more recipients.
module Yesod.Form.MassInput
( inputList
, massDivs
, massTable
) where
import Yesod.Form.Types
import Yesod.Form.Functions
import Yesod.Form.Fields (checkBoxField)
import Yesod.Core
import Control.Monad.Trans.RWS (get, put, ask)
import Data.Maybe (fromMaybe)
import Data.Text.Read (decimal)
import Control.Monad (liftM)
import Data.Either (partitionEithers)
import Data.Traversable (sequenceA)
import qualified Data.Map as Map
import Data.Maybe (listToMaybe)
down :: Monad m => Int -> MForm m ()
down 0 = return ()
down i | i < 0 = error "called down with a negative number"
down i = do
is <- get
put $ IntCons 0 is
down $ i - 1
up :: Monad m => Int -> MForm m ()
up 0 = return ()
up i | i < 0 = error "called down with a negative number"
up i = do
is <- get
case is of
IntSingle _ -> error "up on IntSingle"
IntCons _ is' -> put is' >> newFormIdent >> return ()
up $ i - 1
-- | Generate a form that accepts 0 or more values from the user, allowing the
-- user to specify that a new row is necessary.
inputList :: (xml ~ WidgetFor site (), RenderMessage site FormMessage)
=> Html
-- ^ label for the form
-> ([[FieldView site]] -> xml)
-- ^ how to display the rows, usually either 'massDivs' or 'massTable'
-> (Maybe a -> AForm (HandlerFor site) a)
-- ^ display a single row of the form, where @Maybe a@ gives the
-- previously submitted value
-> Maybe [a]
-- ^ default initial values for the form
-> AForm (HandlerFor site) [a]
inputList label fixXml single mdef = formToAForm $ do
theId <- lift newIdent
down 1
countName <- newFormIdent
addName <- newFormIdent
(menv, _, _) <- ask
let readInt t =
case decimal t of
Right (i, "") -> Just i
_ -> Nothing
let vals =
case menv of
Nothing -> map Just $ fromMaybe [] mdef
Just (env, _) ->
let toAdd = maybe False (const True) $ Map.lookup addName env
count' = fromMaybe 0 $ Map.lookup countName env >>= listToMaybe >>= readInt
count = (if toAdd then 1 else 0) + count'
in replicate count Nothing
let count = length vals
(res, xmls, views) <- liftM fixme $ mapM (withDelete . single) vals
up 1
return (res, [FieldView
{ fvLabel = label
, fvTooltip = Nothing
, fvId = theId
, fvInput = [whamlet|
$newline never
^{fixXml views}
<p>
$forall xml <- xmls
^{xml}
<input .count type=hidden name=#{countName} value=#{count}>
<input type=checkbox name=#{addName}>
Add another row
|]
, fvErrors = Nothing
, fvRequired = False
}])
withDelete :: (xml ~ WidgetFor site (), RenderMessage site FormMessage)
=> AForm (HandlerFor site) a
-> MForm (HandlerFor site) (Either xml (FormResult a, [FieldView site]))
withDelete af = do
down 1
deleteName <- newFormIdent
(menv, _, _) <- ask
res <- case menv >>= Map.lookup deleteName . fst of
Just ("yes":_) -> return $ Left [whamlet|
$newline never
<input type=hidden name=#{deleteName} value=yes>
|]
_ -> do
(_, xml2) <- aFormToForm $ areq checkBoxField FieldSettings
{ fsLabel = SomeMessage MsgDelete
, fsTooltip = Nothing
, fsName = Just deleteName
, fsId = Nothing
, fsAttrs = []
} $ Just False
(res, xml) <- aFormToForm af
return $ Right (res, xml $ xml2 [])
up 1
return res
fixme :: [Either xml (FormResult a, [FieldView site])]
-> (FormResult [a], [xml], [[FieldView site]])
fixme eithers =
(res, xmls, map snd rest)
where
(xmls, rest) = partitionEithers eithers
res = Data.Traversable.sequenceA $ map fst rest
massDivs, massTable
:: [[FieldView site]]
-> WidgetFor site ()
massDivs viewss = [whamlet|
$newline never
$forall views <- viewss
<fieldset>
$forall view <- views
<div :fvRequired view:.required :not $ fvRequired view:.optional>
<label for=#{fvId view}>#{fvLabel view}
$maybe tt <- fvTooltip view
<div .tooltip>#{tt}
^{fvInput view}
$maybe err <- fvErrors view
<div .errors>#{err}
|]
massTable viewss = [whamlet|
$newline never
$forall views <- viewss
<fieldset>
<table>
$forall view <- views
<tr :fvRequired view:.required :not $ fvRequired view:.optional>
<td>
<label for=#{fvId view}>#{fvLabel view}
$maybe tt <- fvTooltip view
<div .tooltip>#{tt}
<td>^{fvInput view}
$maybe err <- fvErrors view
<td .errors>#{err}
|]
|
psibi/yesod
|
yesod-form/Yesod/Form/MassInput.hs
|
mit
| 5,293 | 0 | 22 | 1,741 | 1,287 | 673 | 614 | 103 | 4 |
--
-- Copyright (c) 2012 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
module Core.Types
(
URI (..)
, Text
, DBPath
, DBusValue (..)
, DBusKeyValue (..)
, PtRule (..)
, FileContents
, FileResource (..)
, DBEntry (..)
, DBSection (..)
, DBValue
, EnvFile (..)
, DomStoreFile (..)
, FilesystemType (..)
, filesystemFromStr
, filesystemStr
, parseURI
, strFileResource
, module Core.Uuid
) where
import Data.Text.Lazy (Text)
import Data.List
import Data.Char
import Data.Maybe
import System.FilePath
import Network.DBus (DBusValue)
import Core.Uuid
type FileContents = Text
data DBusKeyValue = DBusKeyValue String DBusValue
data URI = URI { uriScheme :: String, uriLocation :: String } deriving (Eq)
instance Show URI where
show (URI s l) = if null s then l else s ++ ":" ++ l
parseURI :: String -> Maybe URI
parseURI str
= maybe (Just $ URI "" str) Just $
safeHead . map fromJust . filter isJust $ [ prefix "ovf", prefix "http", prefix "https", prefix "file" ]
where
prefix p | (p++":") `isPrefixOf` str = Just (URI p (drop (length p + 1) str))
| otherwise = Nothing
safeHead [] = Nothing
safeHead (x:_) = Just x
data FileResource
= FileResource URI
deriving Eq
instance Show FileResource where show (FileResource uri) = show uri
strFileResource (FileResource uri) = show uri
data DBEntry
= DBEntry
{ dbeSection :: DBSection
, dbePath :: DBPath
, dbeValue :: DBValue }
deriving (Eq,Show)
type DBPath = String
type DBValue = String
data DBSection = DomStoreSection | VmSection
deriving (Eq,Show)
data EnvFile = EnvFile { efFile :: FileResource, efRelativePath :: FilePath } deriving (Eq, Show)
data DomStoreFile = DomStoreFile FileResource FilePath
deriving (Eq,Show)
data PtRule
= PtMatchID { ptClass :: Maybe Int
, ptVendorID :: Maybe Int
, ptDeviceID :: Maybe Int }
| PtMatchBDF { ptBDF :: String }
deriving (Eq, Show)
data FilesystemType = Ext2 | Ext3 | Ext4 | Minix | Ntfs | Swap deriving (Eq, Show)
filesystemStr Ext2 = "ext2"
filesystemStr Ext3 = "ext3"
filesystemStr Ext4 = "ext4"
filesystemStr Minix = "minix"
filesystemStr Ntfs = "ntfs"
filesystemStr Swap = "swap"
filesystemFromStr str = f str where
f "ext2" = Just Ext2
f "ext3" = Just Ext3
f "ext4" = Just Ext4
f "minix" = Just Minix
f "ntfs" = Just Ntfs
f "swap" = Just Swap
f _ = Nothing
|
jean-edouard/manager
|
apptool/Core/Types.hs
|
gpl-2.0
| 3,249 | 0 | 15 | 814 | 842 | 474 | 368 | 80 | 7 |
module WhereIn2 where
f = (y + z)
where
(x,y,z) = g 42
g x = (1,2,x)
|
kmate/HaRe
|
old/testing/simplifyExpr/WhereIn2_TokOut.hs
|
bsd-3-clause
| 101 | 0 | 7 | 49 | 53 | 31 | 22 | 4 | 1 |
--------------------------------------------------------------------------------
-- | This module exposes a function which can relativize URL's on a webpage.
--
-- This means that one can deploy the resulting site on
-- @http:\/\/example.com\/@, but also on @http:\/\/example.com\/some-folder\/@
-- without having to change anything (simply copy over the files).
--
-- To use it, you should use absolute URL's from the site root everywhere. For
-- example, use
--
-- > <img src="/images/lolcat.png" alt="Funny zomgroflcopter" />
--
-- in a blogpost. When running this through the relativize URL's module, this
-- will result in (suppose your blogpost is located at @\/posts\/foo.html@:
--
-- > <img src="../images/lolcat.png" alt="Funny zomgroflcopter" />
module Hakyll.Web.Html.RelativizeUrls
( relativizeUrls
, relativizeUrlsWith
) where
--------------------------------------------------------------------------------
import Data.List (isPrefixOf)
--------------------------------------------------------------------------------
import Hakyll.Core.Compiler
import Hakyll.Core.Item
import Hakyll.Web.Html
--------------------------------------------------------------------------------
-- | Compiler form of 'relativizeUrls' which automatically picks the right root
-- path
relativizeUrls :: Item String -> Compiler (Item String)
relativizeUrls item = do
route <- getRoute $ itemIdentifier item
return $ case route of
Nothing -> item
Just r -> fmap (relativizeUrlsWith $ toSiteRoot r) item
--------------------------------------------------------------------------------
-- | Relativize URL's in HTML
relativizeUrlsWith :: String -- ^ Path to the site root
-> String -- ^ HTML to relativize
-> String -- ^ Resulting HTML
relativizeUrlsWith root = withUrls rel
where
isRel x = "/" `isPrefixOf` x && not ("//" `isPrefixOf` x)
rel x = if isRel x then root ++ x else x
|
bergmark/hakyll
|
src/Hakyll/Web/Html/RelativizeUrls.hs
|
bsd-3-clause
| 2,016 | 0 | 14 | 381 | 233 | 136 | 97 | 19 | 2 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Int
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Signed integer types
--
-----------------------------------------------------------------------------
module Data.Int
(
-- * Signed integer types
Int,
Int8, Int16, Int32, Int64,
-- * Notes
-- $notes
) where
#ifdef __GLASGOW_HASKELL__
import GHC.Base ( Int )
import GHC.Int ( Int8, Int16, Int32, Int64 )
#endif
#ifdef __HUGS__
import Hugs.Int ( Int8, Int16, Int32, Int64 )
#endif
#ifdef __NHC__
import Prelude
import Prelude (Int)
import NHC.FFI (Int8, Int16, Int32, Int64)
import NHC.SizedTypes (Int8, Int16, Int32, Int64) -- instances of Bits
#endif
{- $notes
* All arithmetic is performed modulo 2^n, where @n@ is the number of
bits in the type.
* For coercing between any two integer types, use 'Prelude.fromIntegral',
which is specialized for all the common cases so should be fast
enough. Coercing word types (see "Data.Word") to and from integer
types preserves representation, not sign.
* The rules that hold for 'Prelude.Enum' instances over a
bounded type such as 'Int' (see the section of the
Haskell report dealing with arithmetic sequences) also hold for the
'Prelude.Enum' instances over the various
'Int' types defined here.
* Right and left shifts by amounts greater than or equal to the width
of the type result in either zero or -1, depending on the sign of
the value being shifted. This is contrary to the behaviour in C,
which is undefined; a common interpretation is to truncate the shift
count to the width of the type, for example @1 \<\< 32
== 1@ in some C implementations.
-}
|
beni55/haste-compiler
|
libraries/ghc-7.8/base/Data/Int.hs
|
bsd-3-clause
| 2,005 | 0 | 5 | 409 | 147 | 103 | 44 | 6 | 0 |
module Main where
import System.Environment
import Text.ParserCombinators.Parsec hiding (spaces)
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| String String
| Bool Bool
symbol :: Parser Char
symbol = oneOf "!#$%&|*+-/:<=>?@^_~"
spaces :: Parser ()
spaces = skipMany1 space
parseString :: Parser LispVal
parseString = do char '"'
x <- many (noneOf "\"")
char '"'
return $ String x
readExpr :: String -> String
readExpr input = case parse (spaces >> symbol) "lisp" input of
Left err -> "No match: " ++ show err
Right _ -> "Found value"
main :: IO ()
main = do args <- getArgs
putStrLn $ readExpr $ head args
|
fredmorcos/attic
|
snippets/haskell/Scheme/Main.hs
|
isc
| 814 | 0 | 10 | 272 | 244 | 124 | 120 | 25 | 2 |
-- Graphics!
import GameOfLife
import Graphics.Gloss ( Color
, Display(InWindow)
, Picture(Color, Pictures, Polygon, Translate)
, simulate
, black
, white )
import System.Random ( newStdGen )
main :: IO ()
main = do
let size = windowSize `div` round cellSize
gen <- newStdGen
simulate
(InWindow windowTitle (windowSize, windowSize) windowPosition)
backgroundColor
stepsPerSecond
(randomBoard size size gen)
renderBoard
(\_ _ b -> nextBoard b)
stepsPerSecond = 10 :: Int
windowTitle = "Game of Life"
windowSize = 700 :: Int
cellSize = 10 :: Float
windowPosition = (10, 10) :: (Int, Int)
backgroundColor = white
liveCellColor = black
renderBoard :: Board -> Picture
renderBoard board =
let offset = - fromIntegral windowSize / 2
in Translate offset offset
$ Pictures
$ map (renderPoint . fst)
$ filter ((== Alive) . snd)
$ cellsWithPositions board
renderPoint :: Point -> Picture
renderPoint (Point row col) =
let [(x1, x2), (y1, y2)] = [((fromIntegral n) * cellSize, (fromIntegral $ succ n) * cellSize) | n <- [col, row]]
in Color liveCellColor
$ Polygon [(x1, y1), (x1, y2), (x2, y2), (x2, y1)]
|
ktkonrad/game-of-life
|
src/MainGloss.hs
|
mit
| 1,337 | 2 | 14 | 418 | 446 | 249 | 197 | 39 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module GameStateIn where
import Text.JSON.Generic
import GameState
import qualified Data.Map as Map
magicFields = ["id", "name", "yahoo-rank", "playerName", "injured"]
data GameStateIn = GameStateIn {
n :: Int,
playerIndex :: Int,
history :: [(Int, [(String, String)])],
horizon :: Int,
preHistory :: [(Int, [(String, String)])],
sweep :: Int,
ignoreFirst :: [Int],
inventory :: [[(String, String)]],
players :: Int
} deriving (Eq, Show, Data, Typeable)
readGame :: String -> GameStateIn
readGame = decodeJSON
readPlayer :: [(String, String)] -> Player
readPlayer [] = Player Map.empty Map.empty
readPlayer ((key, value):rest)
| key `elem` magicFields =
player { playerData = Map.insert key value (playerData player) }
| otherwise =
player { playerNumeric = Map.insert key (read value) (playerNumeric player) } where
player = readPlayer rest
gameState_of :: GameStateIn -> GameState
gameState_of g =
GameState {
gsN = n g,
gsPlayerIndex = playerIndex g,
gsHistory = History [(index, readPlayer list) | (index, list) <- history g],
gsHorizon = 3,
gsPrehistory = History [(index, readPlayer list) | (index, list) <- preHistory g],
gsSweep = sw (sweep g),
gsIgnoreFirst = ignoreFirst g,
gsInventory = [readPlayer list | list <- inventory g],
gsPlayers = players g,
gsInventoryLimit = 15
} where
sw 1 = SweepRight
sw (-1) = SweepLeft
sw _ = error "illegal sweeping direction"
gameState_of_string :: String -> GameState
gameState_of_string st = gameState_of (readGame st)
|
golden-warning/giraffedraft-api
|
newHotness/gameStateIn.hs
|
mit
| 1,563 | 46 | 12 | 281 | 617 | 349 | 268 | 45 | 3 |
-- 麻布中学校 2008年 入試問題 算数 問4 解法
import Data.List
import Data.MultiMap
import System.Environment (getArgs)
-- 演算子
opToChar 0 = "+"
opToChar 1 = "*"
-- 最初のリストの先頭2個の数字に、演算子のリスト(0が加算、1が乗算)を適用する
apply (x:y:xs) (0:os) = x + apply (y:xs) os
apply (x:y:xs) (1:os) = apply ((x*y):xs) os
apply (x:xs) _ = x
makePair nums ops = (value, str)
where value = apply nums ops
str = concat $ concat $ transpose [Data.List.map show nums, Data.List.map opToChar ops ++ [""]]
allLists minNum maxNum = Data.List.map f opLists
where nums = [minNum..maxNum]
opLists = sequence (replicate (maxNum - minNum) [0,1])
f ops = makePair nums ops
allListMap minNum maxNum = Data.MultiMap.fromList $ allLists minNum maxNum
-- 問4-1
q1 = sort $ allLists 1 4
-- 問4-2
q2full leftMin leftMax rightMin rightMax =
[(snd p, snd q) | p <- (allLists leftMin leftMax), q <- (allLists rightMin rightMax), fst p == fst q]
q2map leftMin leftMax rightMin rightMax =
Data.List.concatMap f4 $ filter f3 $ Data.List.map f2 $ Data.List.map f1 (allLists leftMin leftMax)
where f1 l = (l, Data.MultiMap.lookup (fst l) (allListMap rightMin rightMax))
f2 (l,r) = (snd l, r)
f3 (l,r) = (not $ Data.List.null r)
f4 (l,r) = [(l, x) | x <-r]
q2 = q2full 1 5 2 6
paramSet (mode:lMin:lMax:rMin:rMax:xs) =
(True, mode, read lMin :: Int, read lMax :: Int, read rMin :: Int, read rMax :: Int)
paramSet _ = (False, "", 0, 0, 0, 0)
solveAll :: IO ()
solveAll = do
putStrLn $ show q1
putStrLn $ show q2
solve :: String -> Int -> Int -> Int -> Int -> IO ()
solve mode leftMin leftMax rightMin rightMax = do
putStrLn $ show $ f leftMin leftMax rightMin rightMax
where f = if (mode == "map") then q2map else q2full
main = do
args <- getArgs
let (fixed, mode, leftMin, leftMax, rightMin, rightMax) = paramSet args
case fixed of
False -> solveAll
True -> solve mode leftMin leftMax rightMin rightMax
|
zettsu-t/examQuestions
|
2008math4.hs
|
mit
| 2,089 | 6 | 11 | 478 | 918 | 470 | 448 | 43 | 2 |
module Main where
import System.Exit
import System.Environment
import Text.LineToPDF
import qualified Data.ByteString.Lazy.Char8 as L
main :: IO ()
main = do
args <- getArgs
(enc, input) <- case args of
[] -> do
putStrLn "Usage: line2pdf [-big5|-gbk|-shiftjis|-euc-jp|-euc-kr] input.txt > output.pdf"
putStrLn " (Form feed (^L) in input denotes a pagebreak.)"
exitWith ExitSuccess
("-big5":i:_) -> return (Big5, i)
("-gbk":i:_) -> return (GBK, i)
("-euc-jp":i:_) -> return (EUC_JP, i)
("-euc-kr":i:_) -> return (EUC_KR, i)
("-shiftjis":i:_) -> return (ShiftJIS, i)
(i:_) -> return (Latin, i)
src <- L.readFile input
lineToPDF $ defaultConfig enc src
|
audreyt/line2pdf
|
line2pdf.hs
|
mit
| 792 | 0 | 13 | 233 | 270 | 142 | 128 | 21 | 7 |
module Hasql.Private.PTI where
import Hasql.Private.Prelude hiding (bool)
import qualified Database.PostgreSQL.LibPQ as LibPQ
-- | A Postgresql type info
data PTI = PTI { ptiOID :: !OID, ptiArrayOID :: !(Maybe OID) }
-- | A Word32 and a LibPQ representation of an OID
data OID = OID { oidWord32 :: !Word32, oidPQ :: !LibPQ.Oid, oidFormat :: !LibPQ.Format }
mkOID :: LibPQ.Format -> Word32 -> OID
mkOID format x =
OID x ((LibPQ.Oid . fromIntegral) x) format
mkPTI :: LibPQ.Format -> Word32 -> Maybe Word32 -> PTI
mkPTI format oid arrayOID =
PTI (mkOID format oid) (fmap (mkOID format) arrayOID)
-- * Constants
-------------------------
abstime = mkPTI LibPQ.Binary 702 (Just 1023)
aclitem = mkPTI LibPQ.Binary 1033 (Just 1034)
bit = mkPTI LibPQ.Binary 1560 (Just 1561)
bool = mkPTI LibPQ.Binary 16 (Just 1000)
box = mkPTI LibPQ.Binary 603 (Just 1020)
bpchar = mkPTI LibPQ.Binary 1042 (Just 1014)
bytea = mkPTI LibPQ.Binary 17 (Just 1001)
char = mkPTI LibPQ.Binary 18 (Just 1002)
cid = mkPTI LibPQ.Binary 29 (Just 1012)
cidr = mkPTI LibPQ.Binary 650 (Just 651)
circle = mkPTI LibPQ.Binary 718 (Just 719)
cstring = mkPTI LibPQ.Binary 2275 (Just 1263)
date = mkPTI LibPQ.Binary 1082 (Just 1182)
daterange = mkPTI LibPQ.Binary 3912 (Just 3913)
float4 = mkPTI LibPQ.Binary 700 (Just 1021)
float8 = mkPTI LibPQ.Binary 701 (Just 1022)
gtsvector = mkPTI LibPQ.Binary 3642 (Just 3644)
inet = mkPTI LibPQ.Binary 869 (Just 1041)
int2 = mkPTI LibPQ.Binary 21 (Just 1005)
int2vector = mkPTI LibPQ.Binary 22 (Just 1006)
int4 = mkPTI LibPQ.Binary 23 (Just 1007)
int4range = mkPTI LibPQ.Binary 3904 (Just 3905)
int8 = mkPTI LibPQ.Binary 20 (Just 1016)
int8range = mkPTI LibPQ.Binary 3926 (Just 3927)
interval = mkPTI LibPQ.Binary 1186 (Just 1187)
json = mkPTI LibPQ.Binary 114 (Just 199)
jsonb = mkPTI LibPQ.Binary 3802 (Just 3807)
line = mkPTI LibPQ.Binary 628 (Just 629)
lseg = mkPTI LibPQ.Binary 601 (Just 1018)
macaddr = mkPTI LibPQ.Binary 829 (Just 1040)
money = mkPTI LibPQ.Binary 790 (Just 791)
name = mkPTI LibPQ.Binary 19 (Just 1003)
numeric = mkPTI LibPQ.Binary 1700 (Just 1231)
numrange = mkPTI LibPQ.Binary 3906 (Just 3907)
oid = mkPTI LibPQ.Binary 26 (Just 1028)
oidvector = mkPTI LibPQ.Binary 30 (Just 1013)
path = mkPTI LibPQ.Binary 602 (Just 1019)
point = mkPTI LibPQ.Binary 600 (Just 1017)
polygon = mkPTI LibPQ.Binary 604 (Just 1027)
record = mkPTI LibPQ.Binary 2249 (Just 2287)
refcursor = mkPTI LibPQ.Binary 1790 (Just 2201)
regclass = mkPTI LibPQ.Binary 2205 (Just 2210)
regconfig = mkPTI LibPQ.Binary 3734 (Just 3735)
regdictionary = mkPTI LibPQ.Binary 3769 (Just 3770)
regoper = mkPTI LibPQ.Binary 2203 (Just 2208)
regoperator = mkPTI LibPQ.Binary 2204 (Just 2209)
regproc = mkPTI LibPQ.Binary 24 (Just 1008)
regprocedure = mkPTI LibPQ.Binary 2202 (Just 2207)
regtype = mkPTI LibPQ.Binary 2206 (Just 2211)
reltime = mkPTI LibPQ.Binary 703 (Just 1024)
text = mkPTI LibPQ.Binary 25 (Just 1009)
tid = mkPTI LibPQ.Binary 27 (Just 1010)
time = mkPTI LibPQ.Binary 1083 (Just 1183)
timestamp = mkPTI LibPQ.Binary 1114 (Just 1115)
timestamptz = mkPTI LibPQ.Binary 1184 (Just 1185)
timetz = mkPTI LibPQ.Binary 1266 (Just 1270)
tinterval = mkPTI LibPQ.Binary 704 (Just 1025)
tsquery = mkPTI LibPQ.Binary 3615 (Just 3645)
tsrange = mkPTI LibPQ.Binary 3908 (Just 3909)
tstzrange = mkPTI LibPQ.Binary 3910 (Just 3911)
tsvector = mkPTI LibPQ.Binary 3614 (Just 3643)
txid_snapshot = mkPTI LibPQ.Binary 2970 (Just 2949)
unknown = mkPTI LibPQ.Text 705 (Just 705)
uuid = mkPTI LibPQ.Binary 2950 (Just 2951)
varbit = mkPTI LibPQ.Binary 1562 (Just 1563)
varchar = mkPTI LibPQ.Binary 1043 (Just 1015)
void = mkPTI LibPQ.Binary 2278 Nothing
xid = mkPTI LibPQ.Binary 28 (Just 1011)
xml = mkPTI LibPQ.Binary 142 (Just 143)
|
nikita-volkov/hasql
|
library/Hasql/Private/PTI.hs
|
mit
| 4,364 | 0 | 11 | 1,243 | 1,577 | 800 | 777 | 90 | 1 |
{-# LANGUAGE OverloadedStrings, TemplateHaskell, RankNTypes,
FunctionalDependencies, MultiParamTypeClasses, FlexibleInstances #-}
module Web.Slack.Types.Session where
import Control.Applicative
import Data.Aeson
import Web.Slack.Types.User
import Web.Slack.Types.Time
import Web.Slack.Types.Self
import Web.Slack.Types.Team
import Web.Slack.Types.Channel
import Web.Slack.Types.Group
import Web.Slack.Types.IM
import Web.Slack.Types.Bot
import Data.Text (Text)
import Control.Lens.TH
import Prelude
data SlackSession = SlackSession
{ _slackSelf :: Self
, _slackTeam :: Team
, _slackUsers :: [User]
, _slackLatestEventTs :: SlackTimeStamp
, _slackChannels :: [Channel]
, _slackGroups :: [Group]
, _slackIms :: [IM]
, _slackBots :: [Bot]
, _slackCacheVersion :: Text
} deriving Show
instance FromJSON SlackSession where
parseJSON = withObject "SlackSession"
(\o -> SlackSession <$> o .: "self" <*> o .: "team"
<*> o .: "users"
<*> o .: "latest_event_ts" <*> o .: "channels"
<*> o .: "groups" <*> o .: "ims"
<*> o .: "bots" <*> o .: "cache_version")
makeLenses ''SlackSession
|
madjar/slack-api
|
src/Web/Slack/Types/Session.hs
|
mit
| 1,411 | 0 | 26 | 469 | 281 | 171 | 110 | 35 | 0 |
module DataTypes where
import Data.Maybe
import Data.List
-------------------------------------------------------------------------
-- Type synonym for representation of a field cell
-- Nothing == unctouched cell,
-- Just True == hit cell
-- Just False == missed cell
type Cell = Maybe Bool
-- Type synonym for cell coordinates on a field
type Coord = (Int, Int)
-- Alignment of a boat on a filed
data Alignment = Vertical | Horizontal
deriving (Eq, Show)
-- 10x10 battle field
data Field = Field { rows :: [[Cell]] }
deriving ( Show )
-- Models of boats that could be placed on a field
data Model = AircraftCarrier | Battleship | Submarine | Destroyer | PatrolBoat
deriving ( Show, Eq )
-- A boat placed on a field is described by its model, starting coordinates
-- and alignment
data Boat = Boat { model :: Model,
start :: Coord,
alignment :: Alignment }
deriving (Eq, Show)
-- A list of boats that are used in one game
data Fleet = Fleet { boats :: [Boat] }
deriving ( Show )
-- Directions for shooting
data Direction = North | South | West | East
deriving (Enum, Eq, Show)
directions = [North, South, West, East] :: [Direction]
{-
data Player = Player {
field :: Field,
fleet :: Fleet,
shots :: [(Coord)]
}
deriving (Show) -}
-- A constant defining the size of a complete fleet
-- (sum of the sizes of all boats in a complete field)
sizeOfFleet = 19 ::Int
-------------------------------------------------------------------------
|
tdeekens/tda452-code
|
Lab-4/DataTypes.hs
|
mit
| 1,479 | 0 | 10 | 291 | 256 | 162 | 94 | 21 | 1 |
module SSeg.SSeg (ssegH, ssegU) where
import CLaSH.Prelude
import SSeg.HexToSSeg
type Hex = Unsigned 4
type Counter = Unsigned 20
hexMux :: Counter ->
(Hex, Hex, Hex, Hex, Hex, Hex, Hex, Hex) ->
(Unsigned 8, Hex)
hexMux counter (hex7, hex6, hex5, hex4, hex3, hex2, hex1, hex0) =
case counter `shiftR` 17 of -- TODO: a more direct way to access the bits?
0b000 -> (0b11111110, hex0)
0b001 -> (0b11111101, hex1)
0b010 -> (0b11111011, hex2)
0b011 -> (0b11110111, hex3)
0b100 -> (0b11101111, hex4)
0b101 -> (0b11011111, hex5)
0b110 -> (0b10111111, hex6)
_ -> (0b01111111, hex7)
-- dp is ignored
ssegH :: Signal (Hex, Hex, Hex, Hex, Hex, Hex, Hex, Hex) ->
Signal (Unsigned 8, BitVector 8)
ssegH h = (\(an, hex) -> (an, hexToSSegCA 0 hex)) <$> an_hex
where
an_hex = hexMux <$> counter <*> h
counter :: Signal Counter
counter = register 0 (counter + 1)
-- from Data.BitVector
(@@) :: (Integral a, Integral b, Bits a) => a -> (Int, Int) -> b
a @@ (j,i) = fromIntegral $ (a `shiftR` i) `mod` 2^m
where
m = j - i + 1 -- width
ssegU :: Signal (Unsigned 32) -> Signal (Unsigned 8, BitVector 8)
ssegU n = ssegH (split <$> n)
where
split x = let f = (x @@)
in (f (31, 28), f (27, 24), f (23, 20), f (19, 16),
f (15, 12), f (11, 8), f (7, 4), f (3, 0))
{-# ANN topEntity
(defTop
{ t_name = "sseg"
, t_inputs = []
, t_outputs = ["an", "seg"]
, t_extraIn = [("clk", 1), ("btnCpuReset", 1)]
, t_extraOut = []
, t_clocks = []
}) #-}
topEntity = ssegU
|
aufheben/Y86
|
SEQ/SSeg/SSeg.hs
|
mit
| 1,608 | 0 | 11 | 449 | 635 | 364 | 271 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
module Diagrams.Plots.Bar
( BarOpt
, barWidth
, barBaseLine
, barOrientation
, bars
) where
import Diagrams.Prelude
import Data.Default
import Control.Lens (makeLenses, (^.), both)
import Data.Maybe
import Diagrams.Plots.Types
data BarOpt = BarOpt
{ _barWidth :: Double -- ^ from 0 to 1
, _barBaseLine :: Maybe Double
, _barOrientation :: Char
}
makeLenses ''BarOpt
instance Default BarOpt where
def = BarOpt
{ _barWidth = 0.8
, _barBaseLine = Nothing
, _barOrientation = '^'
}
bars :: (PlotData m1 a1, PlotData m2 a2) => m1 a1 -> m2 a2 -> BarOpt -> PlotFn
bars xs ys opt m = case opt^.barOrientation of
'^' -> upBars xs ys opt m
'>' -> rightBars xs ys opt m
'V' -> downBars xs ys opt m
_ -> upBars xs ys opt m
upBars :: (PlotData m1 a1, PlotData m2 a2) => m1 a1 -> m2 a2 -> BarOpt -> PlotFn
{-# INLINE upBars #-}
upBars xs ys opt mapX mapY = map (uncurry moveTo) [ (x ^& ((y+bl)/2), rect w (y-bl)) | (x, y) <- xy ]
where
xy = mapMaybe (runMap pMap) $ zip (getValues xs) $ getValues ys
w = (opt^.barWidth) * gap'
gap' = (fromJust.runMap mapX) 2 - (fromJust.runMap mapX) 1
pMap = compose mapX mapY
bl = fromMaybe 0 $ do b <- opt^.barBaseLine
runMap mapY b
rightBars :: (PlotData m1 a1, PlotData m2 a2) => m1 a1 -> m2 a2 -> BarOpt -> PlotFn
rightBars xs ys opt mapX mapY = map (uncurry moveTo) [ ( ((x+bl)/2) ^& y, rect (x-bl) h) | (x, y) <- xy ]
where
xy = mapMaybe (runMap pMap) $ zip (getValues xs) $ getValues ys
h = (opt^.barWidth) * gap'
gap' = (fromJust.runMap mapY) 2 - (fromJust.runMap mapY) 1
pMap = compose mapX mapY
bl = fromMaybe 0 $ do b <- opt^.barBaseLine
runMap mapX b
{-# INLINE rightBars #-}
downBars :: (PlotData m1 a1, PlotData m2 a2) => m1 a1 -> m2 a2 -> BarOpt -> PlotFn
downBars xs ys opt mapX mapY = map (uncurry moveTo) [ (x ^& ((areaHeight+y-bl)/2), rect w (areaHeight-y-bl) ) | (x, y) <- xy ]
where
xy = mapMaybe (runMap pMap) $ zip (getValues xs) $ getValues ys
w = (opt^.barWidth) * gap'
gap' = (fromJust.runMap mapX) 2 - (fromJust.runMap mapX) 1
pMap = compose mapX mapY
areaHeight = l' + u'
(l', u') = both %~ fromJust . runMap mapY $ domain mapY
bl = fromMaybe 0 $ do b <- opt^.barBaseLine
runMap mapY b
{-# INLINE downBars #-}
|
kaizhang/haskell-plot
|
src/Diagrams/Plots/Bar.hs
|
mit
| 2,523 | 0 | 13 | 749 | 1,048 | 543 | 505 | -1 | -1 |
-- Ease the StockBroker
-- http://www.codewars.com/kata/54de3257f565801d96001200/
module Codewars.G964.Stockbroker where
import Data.Char (isDigit, isSpace)
import Data.Either (partitionEithers)
import Data.List (elemIndices, partition, groupBy)
import Data.List.Split (split, dropDelims, dropBlanks, oneOf)
balanceStatements "" = "Buy: 0 Sell: 0"
balanceStatements s = f correct ++ g malformed
where (malformed, correct) = partitionEithers . map validate . split (dropDelims $ oneOf ",") $ s
f = concat . (\(b, s) -> [("Buy: "++) . show . sum . map snd $ b , (" Sell: "++) . show . sum . map snd $ s]) . partition ((=="B") . fst)
g xs = if null xs then "" else concat . (\x -> [("; Badly formed "++) . (++": ") . show . length $ x, concat x]) . map ((++" ;") . dropWhile isSpace) $ xs
validAction "B" = True
validAction "S" = True
validAction _ = False
validInt :: String -> Bool
validInt = all isDigit
validDouble :: String -> Bool
validDouble = (\(ds, nds) -> ((>=2) . length $ ds) && ((==1) . length $ nds) && ((=='.') . head $ nds)) . partition isDigit
validate :: String -> Either String (String, Integer)
validate order | validOrder = Right (action, orderValue quantity price)
| otherwise = Left order
where validOrder = validInt quantity && validDouble price && validAction action
orderValue q p = round ((read q :: Double) * (read p :: Double))
(stock, quantity, price, action) = case split (dropDelims . dropBlanks $ oneOf " " ) order of
(a:b:c:d:[]) -> (a, b, c, d)
x -> ("", "", "", "E")
|
gafiatulin/codewars
|
src/6 kyu/Stockbroker.hs
|
mit
| 1,799 | 0 | 18 | 558 | 667 | 365 | 302 | 25 | 5 |
{-# LANGUAGE UndecidableInstances #-}
-- | Types relating to a nix binary cache.
module Nix.Cache.Types where
import qualified Data.Text as T
import Data.Attoparsec.ByteString.Lazy (Result(..), parse)
import Data.Aeson (ToJSON, FromJSON)
import Servant (MimeUnrender(..), OctetStream, Accept(..),
Proxy(..), MimeRender(..))
import Network.HTTP.Media ((//))
import Codec.Compression.GZip (compress, decompress)
import Data.KVMap
import Nix.Cache.Common
import Nix.StorePath (NixStoreDir(NixStoreDir))
-- | Represents binary data compressed with gzip.
data GZipped
-- | Content type for gzipped data.
instance Accept GZipped where
contentType _ = "application" // "x-gzip"
-- | Anything which can be put in an octet stream can be put in gzip.
instance MimeUnrender OctetStream t => MimeUnrender GZipped t where
mimeUnrender _ = mimeUnrender (Proxy :: Proxy OctetStream) . decompress
instance MimeRender OctetStream t => MimeRender GZipped t where
mimeRender _ obj = compress $ mimeRender (Proxy :: Proxy OctetStream) obj
-- | Information about a nix binary cache. This information is served
-- on the /nix-cache-info route.
data NixCacheInfo = NixCacheInfo {
storeDir :: NixStoreDir,
-- ^ On-disk location of the nix store.
wantMassQuery :: Bool,
-- ^ Not sure what this does.
priority :: Maybe Int
-- ^ Also not sure what this means.
} deriving (Show, Eq, Generic)
instance ToJSON NixCacheInfo
instance FromJSON NixCacheInfo
instance FromKVMap NixCacheInfo where
fromKVMap (KVMap kvm) = case lookup "StoreDir" kvm of
Nothing -> Left "No StoreDir key defined."
Just sdir -> return $ NixCacheInfo {
storeDir = NixStoreDir $ T.unpack sdir,
wantMassQuery = lookup "WantMassQuery" kvm == Just "1",
priority = lookup "Priority" kvm >>= readMay
}
-- | To parse something from an octet stream, first parse the
-- stream as a KVMap and then attempt to translate it.
instance MimeUnrender OctetStream NixCacheInfo where
mimeUnrender _ bstring = case parse parseKVMap bstring of
Done _ kvmap -> fromKVMap kvmap
Fail _ _ message -> Left message
|
adnelson/nix-binary-cache
|
src/Nix/Cache/Types.hs
|
mit
| 2,122 | 0 | 14 | 388 | 481 | 269 | 212 | -1 | -1 |
-- Copyright (c) Microsoft. All rights reserved.
-- Licensed under the MIT license. See LICENSE file in the project root for full license information.
{-# LANGUAGE QuasiQuotes, OverloadedStrings, RecordWildCards #-}
module Language.Bond.Codegen.Cs.Comm_cs (
comm_interface_cs,
comm_proxy_cs,
comm_service_cs)
where
import Data.Maybe
import Data.Monoid
import Data.List (nub)
import Prelude
import qualified Data.Text.Lazy as L
import Data.Text.Lazy.Builder
import Text.Shakespeare.Text
import Language.Bond.Syntax.Types
import Language.Bond.Util
import Language.Bond.Codegen.Util
import Language.Bond.Codegen.TypeMapping
import qualified Language.Bond.Codegen.Cs.Util as CS
getMessageTypeName :: MappingContext -> Maybe Type -> Builder
getMessageTypeName ctx t = maybe "global::Bond.Void" (getTypeName ctx) t
getMessageProxyInputParam :: MappingContext -> Maybe Type -> Builder
getMessageProxyInputParam ctx t = maybe "" constructParam t
where
constructParam x = getTypeName ctx x `mappend` fromText " param"
paramOrBondVoid :: Maybe Type -> String
paramOrBondVoid t = if isNothing t then "new global::Bond.Void()" else "param"
-- | Codegen template for generating code containing declarations of
-- of services including interfaces, proxies and services files.
comm_interface_cs :: MappingContext -> String -> [Import] -> [Declaration] -> (String, L.Text)
comm_interface_cs cs _ _ declarations = ("_interfaces.cs", [lt|
#{CS.disableCscWarnings}
#{CS.disableReSharperWarnings}
namespace #{csNamespace}
{
#{doubleLineSep 1 comm declarations}
} // #{csNamespace}
|])
where
csNamespace = sepBy "." toText $ getNamespace cs
comm s@Service{..} = [lt|#{CS.typeAttributes cs s}interface I#{declName}#{generics}
{
#{doubleLineSep 2 methodDeclaration serviceMethods}
}
|]
where
generics = angles $ sepBy ", " paramName declParams
methodDeclaration Function{..} = [lt|global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<#{getMessageResultTypeName}>> #{methodName}Async(global::Bond.Comm.IMessage<#{getMessageInputTypeName}> param, global::System.Threading.CancellationToken ct);|]
where
getMessageResultTypeName = getMessageTypeName cs methodResult
getMessageInputTypeName = getMessageTypeName cs methodInput
methodDeclaration Event{..} = [lt|void #{methodName}Async(global::Bond.Comm.IMessage<#{getMessageInputTypeName}> param);|]
where
getMessageInputTypeName = getMessageTypeName cs methodInput
comm _ = mempty
comm_proxy_cs :: MappingContext -> String -> [Import] -> [Declaration] -> (String, L.Text)
comm_proxy_cs cs _ _ declarations = ("_proxies.cs", [lt|
#{CS.disableCscWarnings}
#{CS.disableReSharperWarnings}
namespace #{csNamespace}
{
#{doubleLineSep 1 comm declarations}
} // #{csNamespace}
|])
where
csNamespace = sepBy "." toText $ getNamespace cs
idl = MappingContext idlTypeMapping [] [] []
comm s@Service{..} = [lt|#{CS.typeAttributes cs s}public class #{declName}Proxy<#{proxyGenerics}TConnection> : I#{declName}#{interfaceGenerics}#{connConstraint}
{
private readonly TConnection m_connection;
public #{declName}Proxy(TConnection connection)
{
m_connection = connection;
}
#{doubleLineSep 2 proxyMethod serviceMethods}
}|]
where
methodCapability Function {} = "global::Bond.Comm.IRequestResponseConnection"
methodCapability Event {} = "global::Bond.Comm.IEventConnection"
getCapabilities :: [Method] -> [String]
getCapabilities m = nub $ map methodCapability m
connConstraint = " where TConnection : " ++ sepBy ", " (\p -> p) (getCapabilities serviceMethods)
interfaceGenerics = angles $ sepBy "," paramName declParams -- of the form "<T1, T2, T3>"
proxyGenerics = sepEndBy ", " paramName declParams -- of the form "T1, T2, T3, "
proxyMethod Function{..} = [lt|public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<#{getMessageResultTypeName}>> #{methodName}Async(#{getMessageProxyInputParam cs methodInput})
{
var message = new global::Bond.Comm.Message<#{getMessageInputTypeName}>(#{paramOrBondVoid methodInput});
return #{methodName}Async(message, global::System.Threading.CancellationToken.None);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<#{getMessageResultTypeName}>> #{methodName}Async(global::Bond.Comm.IMessage<#{getMessageInputTypeName}> param, global::System.Threading.CancellationToken ct)
{
return m_connection.RequestResponseAsync<#{getMessageInputTypeName}, #{getMessageResultTypeName}>(
"#{getDeclTypeName idl s}.#{methodName}",
param,
ct);
}|]
where
getMessageResultTypeName = getMessageTypeName cs methodResult
getMessageInputTypeName = getMessageTypeName cs methodInput
proxyMethod Event{..} = [lt|public void #{methodName}Async(#{getMessageProxyInputParam cs methodInput})
{
var message = new global::Bond.Comm.Message<#{getMessageInputTypeName}>(#{paramOrBondVoid methodInput});
#{methodName}Async(message);
}
public void #{methodName}Async(global::Bond.Comm.IMessage<#{getMessageInputTypeName}> param)
{
m_connection.FireEventAsync<#{getMessageInputTypeName}>(
"#{getDeclTypeName idl s}.#{methodName}",
param);
}|]
where
getMessageInputTypeName = getMessageTypeName cs methodInput
comm _ = mempty
comm_service_cs :: MappingContext -> String -> [Import] -> [Declaration] -> (String, L.Text)
comm_service_cs cs _ _ declarations = ("_services.cs", [lt|
#{CS.disableCscWarnings}
#{CS.disableReSharperWarnings}
namespace #{csNamespace}
{
#{doubleLineSep 1 comm declarations}
} // #{csNamespace}
|])
where
csNamespace = sepBy "." toText $ getNamespace cs
idl = MappingContext idlTypeMapping [] [] []
comm s@Service{..} = [lt|#{CS.typeAttributes cs s}public abstract class #{declName}ServiceBase#{generics} : I#{declName}#{generics}, global::Bond.Comm.IService
{
public global::System.Collections.Generic.IEnumerable<global::Bond.Comm.ServiceMethodInfo> Methods
{
get
{
#{newlineSep 4 methodInfo serviceMethods}
}
}
#{doubleLineSep 2 methodAbstract serviceMethods}
#{doubleLineSep 2 methodGlue serviceMethods}
}
|]
where
generics = angles $ sepBy ", " paramName declParams
methodInfo Function{..} = [lt|yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="#{getDeclTypeName idl s}.#{methodName}", Callback = #{methodName}Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.RequestResponse};|]
methodInfo Event{..} = [lt|yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="#{getDeclTypeName idl s}.#{methodName}", Callback = #{methodName}Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.Event};|]
methodAbstract Function{..} = [lt|public abstract global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<#{getMessageResultTypeName}>> #{methodName}Async(global::Bond.Comm.IMessage<#{getMessageInputTypeName}> param, global::System.Threading.CancellationToken ct);|]
where
getMessageResultTypeName = getMessageTypeName cs methodResult
getMessageInputTypeName = getMessageTypeName cs methodInput
methodAbstract Event{..} = [lt|public abstract void #{methodName}Async(global::Bond.Comm.IMessage<#{getMessageInputTypeName}> param);|]
where
getMessageInputTypeName = getMessageTypeName cs methodInput
methodGlue Function{..} = [lt|private global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage> #{methodName}Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct)
{
return global::Bond.Comm.CodegenHelpers.Upcast<global::Bond.Comm.IMessage<#{getMessageResultTypeName}>,
global::Bond.Comm.IMessage>(
#{methodName}Async(param.Convert<#{getMessageInputTypeName}>(), ct));
}|]
where
getMessageResultTypeName = getMessageTypeName cs methodResult
getMessageInputTypeName = getMessageTypeName cs methodInput
methodGlue Event{..} = [lt|private global::System.Threading.Tasks.Task #{methodName}Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct)
{
#{methodName}Async(param.Convert<#{getMessageInputTypeName}>());
return global::Bond.Comm.CodegenHelpers.CompletedTask;
}|]
where
getMessageInputTypeName = getMessageTypeName cs methodInput
comm _ = mempty
|
ant0nsc/bond
|
compiler/src/Language/Bond/Codegen/Cs/Comm_cs.hs
|
mit
| 9,113 | 0 | 12 | 1,762 | 1,066 | 601 | 465 | 72 | 5 |
{-# LANGUAGE RecordWildCards, PatternSynonyms, BangPatterns, ViewPatterns #-}
module Main where
-----------------------------------------------------------------------------------
import Control.Monad
import System.Random
import Data.Vector as V (Vector(..), fromList)
import System.IO (hSetBuffering, stdout, BufferMode(..))
import System.Posix.Signals
import System.Exit
import Control.Concurrent
import Control.Monad.Random
import System.Random.Shuffle (shuffleM)
import Data.Map as M (Map(..))
import Data.Word (Word8(..))
import Control.Parallel.Strategies
-----------------------------------------------------------------------------------
import Genetic -- (genIndividual, genIndividuals)
import Crossover
import Player -- (play,playIO)
import Board.Utils -- (createBoardPositions)
import Board.Types
import SimpleLogger
-----------------------------------------------------------------------------------
-- Ideas:
--
-- * Coevolution - two different populations play vs each other (no crossover between the two of them) Island separated multi population scheme
-- * fitness is based on "turns lived" Done
-- * fitness counts real wins / invalidmove wins / losses from invalid moves Doesn't matter
-- * only play two games from empty board only Done
-- * invalid moves are not permitted (predefined in boardVector) (last resort)
-- Current issues:
-- * Inbreeding...
-- * TODO: Hash 827 board states - Hash all rotations and store all 9 in a (Map Hash [Hash])
-- real win = 1.0 count + 1
-- win through invalid move = 0 count stays same
-- turn = turns / 5 count + 5 for every game played (new count)
-- lose = 0.2 count + 1
-- loose through invalid move = 0 count + 1
-- Let gensize (100) Players play vs each other
-- crossover according to alpha
-- mutation according to delta + beta
-- CO + MU creates new children population
-- Children population is being evaluated
-- Sort the children population and parent population by fitness
-- Natural selection removed individuals according to tetha
-- Fill up the remaining spots
popsize = 1000 -- populationsize
stringlength = 827 -- possible boardstates
delta = 0.10 -- chance to mutate
beta = 0.05 -- percent of the string to mutate
tetha = 0.8 -- percent to be removed by natural selection
generations = 3900
-------------------------------------------------------------------------
-- | Main entry point
--
main :: IO ()
main = do
-- create board positions
rotMap <- createRotHashMap "lib/sortedCombos827.txt"
nextMMap <- createNextBoardStateMap "lib/sortedCombos827.txt"
vec <- V.fromList <$> createBoardStatesFrom "lib/sortedCombos827.txt"
-- set up logger
time <- getTime
fLog <- createFileLog ("log/" ++ time ++ "/") ""
stdLog <- createStdoutLog
let logger = mergeLogs [fLog, stdLog]
-- create initial population
let g = mkStdGen 13457398364872342
(g',_) = split g
population = flip evalRand g $ genIndividuals popsize stringlength
-- start the evolution
evolution rotMap nextMMap vec population generations g logger
-------------------------------------------------------------------------
-- | Automatic evolution dependent on 'generations'
--
evolution :: Map Int (Int, Rotation) -> Map Int [Board] -> Vector Board -> [Player] -> Int -> StdGen -> Logger -> IO ()
evolution rotMap nextMMap vec pop 0 _ log = mapM_ ((log <!>) . moves) (take 10 pop) >> closeLog log
evolution rotMap nextMMap vec pop n g log = do
log <!!> unwords ["Generation(s) left to live: ", show n, "\n"]
let strategy = parList rseq
npop = flip evalRand g $ do
let !parents = map (playSingle rotMap nextMMap) pop `using` strategy
--let !parents = populationPlay vec rotMap pop `using` strategy
children <- randomTacticCrossover uniformCrossover parents
mutants <- mutate delta beta children
let !children' = map (playSingle rotMap nextMMap) mutants `using` strategy
-- let !children' = populationPlay vec rotMap mutants `using` strategy
selected = naturalselection tetha (parents ++ children')
repopulate selected popsize stringlength
let (g',_) = split g
mapM_ (log <!>) (take 10 npop)
mapM_ ((log <!!>) . (>>= show) . moves) (take 3 npop)
evolution rotMap nextMMap vec npop (n-1) g' log
-----------------------------------------------------------------------------------
-- ## Tests ##
-- | Play vs a custom Chromosome for testing purposes
--
-- 0 - You start
-- 1 - AI starts
--
playAI :: Map Int (Int, Rotation) -> Player -> Int -> IO ()
playAI hmap player n = playAI' hmap emptyBoard player n
where
playAI' :: Map Int (Int, Rotation) -> Board -> Player -> Int -> IO ()
playAI' hmap board player n = do
print board
case (gameState board, n) of
(Ongoing, 0) -> do
putStr "My move: "
input <- getLine
case input of
"1" -> playAI' hmap (A1 `playOn` board) player 1
"2" -> playAI' hmap (A2 `playOn` board) player 1
"3" -> playAI' hmap (A3 `playOn` board) player 1
"4" -> playAI' hmap (B1 `playOn` board) player 1
"5" -> playAI' hmap (B2 `playOn` board) player 1
"6" -> playAI' hmap (B3 `playOn` board) player 1
"7" -> playAI' hmap (C1 `playOn` board) player 1
"8" -> playAI' hmap (C2 `playOn` board) player 1
"9" -> playAI' hmap (C3 `playOn` board) player 1
_ -> putStrLn "Noob l2p" >> playAI' hmap board player 0
(Ongoing, 1) -> case nextMove hmap player board of
(False, move, _) -> putStrLn ("Master wins, I tried to play " ++ show move)
(True , _ , board') -> playAI' hmap board' player 0
((Win r), _) -> putStrLn (show r ++ " won!")
(Tie , _) -> putStrLn "It's a tie"
crossoverTest :: IO ()
crossoverTest = do
let p1 = Player [0,0,0,0,0,0,0,0,0,0] 1 0 0 0 False 3
p2 = Player [1,1,1,1,1,1,1,1,1,1] 2 0 0 0 False 5
p3 = Player [2,2,2,2,2,2,2,2,2,2] 3 0 0 0 False 7
p4 = Player [3,3,3,3,3,3,3,3,3,3] 10 0 0 0 False 11
p5 = Player [4,4,4,4,4,4,4,4,4,4] 2 0 0 0 False 127
p6 = Player [5,5,5,5,5,5,5,5,5,5] 6 0 0 0 False 67
g = mkStdGen 311
l = flip evalRand g $ randomTacticCrossover uniformCrossover [p1,p2,p3,p4,p5,p6]
mapM_ print l
naturalselectionTest :: IO ()
naturalselectionTest = do
let p1 = Player [0,0,0,0,0,0,0,0,0,0] 31 0 0 0 False 7 -- 4.428
p2 = Player [1,1,1,1,1,1,1,1,1,1] 30 0 0 0 False 8 -- 3.75
p3 = Player [2,2,2,2,2,2,2,2,2,2] 35 0 0 0 False 9 -- 3.88
p4 = Player [3,3,3,3,3,3,3,3,3,3] 10 0 0 0 False 11 -- 0.9
p5 = Player [4,4,4,4,4,4,4,4,4,4] 114 0 0 0 False 10 -- 11.4
p6 = Player [5,5,5,5,5,5,5,5,5,5] 60 0 0 0 False 67 -- 0.89
popsize = 6
tetha = 0.7
stringlength = 10
l = naturalselection tetha [p1,p2,p3,p4,p5,p6]
g = mkStdGen 12345
l' = flip evalRand g $ repopulate l popsize stringlength
mapM_ print l'
shuffleTest :: IO ()
shuffleTest = do
let p1 = Player [0,0,0,0,0,0,0,0,0,0] 31 0 0 0 False 7 -- 4.428
p2 = Player [1,1,1,1,1,1,1,1,1,1] 30 0 0 0 False 8 -- 3.75
p3 = Player [2,2,2,2,2,2,2,2,2,2] 35 0 0 0 False 9 -- 3.88
p4 = Player [3,3,3,3,3,3,3,3,3,3] 10 0 0 0 False 11 -- 0.9
p5 = Player [4,4,4,4,4,4,4,4,4,4] 114 0 0 0 False 10 -- 11.4
p6 = Player [5,5,5,5,5,5,5,5,5,5] 60 0 0 0 False 67 -- 0.89
g = mkStdGen 123545
l' = flip evalRand g $ shuffleM [p1, p2, p3, p4, p5, p6]
mapM_ print l'
singlePlayerTest :: IO Player
singlePlayerTest = do
rotMap <- createRotHashMap "lib/sortedCombos827.txt"
nextMMap <- createNextBoardStateMap "lib/sortedCombos827.txt"
let g = mkStdGen 123123123
p1 = flip evalRand g $ genIndividual 827
return $ playSingle rotMap nextMMap p1
-- testPlay :: String -> Int -> IO ()
-- testPlay s i = do
-- let p = Player s 0 1
-- vec <- createBoardStatesFrom "lib/tictactoeCombos827.txt"
-- playAI vec p i
-----------------------------------------------------------------------------------
-- | User input for communication
--
{-
customEvolution :: V.Vector Board -> [Player] -> StdGen -> Logger -> IO ()
customEvolution vec population g log = do
log <!!> "Another round? (y/n) or (p)rint "
input <- getLine
log <!!> input
case input of
"y" -> do
let newpop = flip evalRand g $ do
let parents = populationPlay vec population
children <- rouletteCrossover uniformCrossover parents
mutants <- mutate delta beta children
let children' = populationPlay vec children
selected = naturalselection tetha (parents ++ children')
repopulate selected popsize stringlength
let (g',_) = split g
log <!> newpop
customEvolution vec newpop g' log
"p" -> mapM_ ((log <!>) . moves) (take 10 population) >> customEvolution vec population g log
_ -> mapM_ ( log <!>) (take 10 population)
-}
{-
safeExit :: [Player] -> V.Vector Board -> ThreadId -> IO ()
safeExit population vec tid = do
putStrLn ""
mapM_ print population
putStrLn $ "\n * <int> - from the range 0 - " ++ show (length population) ++ " prints the indiviual"
putStrLn " * exit/quit/q/:q - exits the program"
putStrLn " * play <int> [me|ki] - let's you play vs the individual at that index, second arg is who starts first"
putStr "Command: "
input <- getLine
loop population vec input
where
loop :: [Player] -> V.Vector Board -> String -> IO ()
loop population vec "exit" = killThread tid >> exitSuccess
loop population vec "quit" = killThread tid >> exitSuccess
loop population vec "q" = killThread tid >> exitSuccess
loop population vec ":q" = killThread tid >> exitSuccess
loop population vec ('p':'l':'a':'y':' ':xs)
| [(n, " me")] <- reads xs, n >= 0, n < length population = do
playAI vec (population !! n) 0
putStr "Command: "
input <- getLine
loop population vec input
| [(n, " ki")] <- reads xs, n >= 0, n < length population = do
playAI vec (population !! n) 1
putStr "Command: "
input <- getLine
loop population vec input
loop population vec (reads -> [(n, "")])
| n >= 0, n < length population = do
putStrLn ("Individual Nr." ++ show n)
let individual = population !! n
putStrLn ("Fitness in %, Wins + Ties, Total Games: " ++ show (ratio individual) ++ ", " ++ show (fitness individual) ++ ", " ++ show (games individual))
putStrLn ("Chromosome: " ++ moves individual)
putStr "Command: "
input <- getLine
loop population vec input
loop population vec _ = putStrLn "Sorry, something didn't work...try again" >> putStr "Command: " >> getLine >>= \input -> loop population vec input
-}
|
cirquit/genetic-tic-tac-toe
|
app/Main.hs
|
mit
| 12,213 | 0 | 19 | 3,900 | 2,551 | 1,429 | 1,122 | 124 | 14 |
module Bonlang.Lang.Numeric
( add
, subtract
, multiply
, divide
, modulo
, greaterThan
, greaterThanOrEquals
, lessThan
, lessThanOrEquals
) where
import Bonlang.Lang
import Prelude hiding (subtract)
binOp :: (a -> BonlangValue) -- A Constructor
-> (BonlangNum -> BonlangNum -> a) -- A binary operation
-> PrimFunc -- A primitive function
binOp c op xs = case xs of
[BonlangNumber x, BonlangNumber y] -> return $ c (x `op` y)
_ -> Left $ NumArgs (length xs) xs
binNumericOp :: (BonlangNum -> BonlangNum -> BonlangNum) -> PrimFunc
binNumericOp = binOp BonlangNumber
binBoolOp :: (BonlangNum -> BonlangNum -> Bool) -> PrimFunc
binBoolOp = binOp BonlangBool
add, subtract, multiply, divide, modulo :: PrimFunc
greaterThan, greaterThanOrEquals, lessThan, lessThanOrEquals :: PrimFunc
add = binNumericOp (+)
multiply = binNumericOp (*)
subtract = binNumericOp (-)
divide = binNumericOp (/)
modulo = binNumericOp mod
greaterThan = binBoolOp (>)
greaterThanOrEquals = binBoolOp (>=)
lessThan = binBoolOp (<)
lessThanOrEquals = binBoolOp (<=)
|
charlydagos/bonlang
|
src/Bonlang/Lang/Numeric.hs
|
mit
| 1,268 | 0 | 11 | 386 | 323 | 191 | 132 | 33 | 2 |
module Parser(parseExpression, parseProgram) where
import Grammar
data NonTerminal =Program
|Stat
|Block
|ForDef
|Print
|NegExpr
|BoolExpr
|AddExpr
|MulExpr
|Operand deriving (Show)
--check whether the correct tokentype is at the head of the tokenstream and return the token with the rest
consume::TokenType->[Token]->(Token,[Token])
consume a (x:xs)|a==(fst x) =(x,xs)
|otherwise =error ("parser error: expected "++(show a)++" but found "++(show x))
parseExpression::[Token]->TokenTree
parseExpression=fst.(parse NegExpr)
parseProgram::[Token]->TokenTree
parseProgram=fst.(parse Program)
parse::NonTerminal->[Token]->(TokenTree,[Token])
--Expression parsing
--Possible Operands(Bool, Int and nested expressions)
parse Operand (t@(Var,_):ts) =(TokenLeaf t,ts)
parse Operand (t@(Number,_):ts) =(TokenLeaf t,ts)
parse Operand (t@(BTrue,_):ts) =(TokenLeaf t,ts)
parse Operand (t@(BFalse,_):ts) =(TokenLeaf t,ts)
parse Operand (t@(POpen,_):ts) =(node,rest) where
(node,r1) =parse NegExpr ts
(_,rest) =consume PClose r1
--Layers of operations
parse MulExpr (t:ts) =(node,rest) where
(tl, r1) =parse Operand (t:ts)
(tr, r2) =parse MulExpr (tail r1)
(node,rest) =case r1 of
((Mul,_):xs) ->(TokenNode (head r1) tl tr,r2)
((Div,_):xs) ->(TokenNode (head r1) tl tr,r2)
_ ->(tl,r1)
parse AddExpr (t:ts) =(node,rest) where
(tl, r1) =parse MulExpr (t:ts)
(tr, r2) =parse AddExpr (tail r1)
(node, rest)=case r1 of
((Plus,_):xs) ->(TokenNode (head r1) tl tr,r2)
((Min,_):xs) ->(TokenNode (head r1) tl tr,r2)
_ ->(tl,r1)
parse BoolExpr (t:ts) =(node,rest) where
(tl, r1) =parse AddExpr (t:ts)
(tr, r2) =parse BoolExpr (tail r1)
(node, rest)=case r1 of
((OpBool,_):xs) ->(TokenNode (head r1) tl tr,r2)
_ ->(tl,r1)
parse NegExpr (t@(Not,_):ts) =((TokenNode t tl Nop),r) where
(tl,r) =parse BoolExpr ts
parse NegExpr t =parse BoolExpr t
--Statement parsing
parse Program [] =(Nop,[])
parse Program ts =(TokenNode (Semicolon,";") tl tr,r) where
(tl, r1) =parse Stat ts
(tr, r) =parse Program r1
parse Block (t@(BClose,_):ts) =(Nop,ts)
parse Block ts =(TokenNode (Semicolon,";") tl tr,r) where
(tl, r1) =parse Stat ts
(tr, r) =parse Block r1
parse Stat (t@(BOpen,_):ts) =(TokenNode t tl Nop,r) where
(tl, r) =parse Block ts
parse Stat (t@(Semicolon,_):ts) =parse Stat ts
parse Stat (t@(VarVar,_):ts) =(TokenNode t (TokenLeaf tv) tr ,r) where
(tv, r1) =consume Var ts
(tn, r2) =consume Assignment r1
(tr, r3) =parse NegExpr r2
(nt, r) =consume Semicolon r3
parse Stat (t@(ConstVar,_):ts) =(TokenNode t (TokenLeaf tv) tr ,r) where
(tv, r1) =consume Var ts
(tn, r2) =consume Assignment r1
(tr, r3) =parse NegExpr r2
(nt, r) =consume Semicolon r3
parse Stat (t@(Var,_):ts) =(TokenNode tn (TokenLeaf t) tr,r) where
(tn, r1) =consume Assignment ts
(tr, r2) =parse NegExpr r1
(nt, r) =consume Semicolon r2
parse Stat (t@(While,_):ts) =(TokenNode t tl (TokenNode (Semicolon,";") tr Nop), r) where
(tl, r1) =parse NegExpr ts
(tr, r) =parse Stat r1
--for typedef;booleanexpr;expr stat;
--For loops are rewritten to a while loop.
parse Stat (t@(For,_):ts) =
((TokenNode (BOpen,"{")
(TokenNode (Semicolon,";")
tll --typedef
(TokenNode (Semicolon, ";")
(TokenNode (While,"while")
tlr --booleanexpr goes into the while loop
(TokenNode (Semicolon,";")
trr --stat//content of the loop
(TokenNode (Semicolon,";")
(TokenNode (Assignment,"=") tvn trl)--implicit assignment of the exor to the typedef
Nop)
)
)
Nop
)
)
Nop
),r)where
(tll@(TokenNode _ tvn _), r1) =parse ForDef ts
(_, r2) =consume Semicolon r1
(tlr, r3) =parse NegExpr r2
(_, r4) =consume Semicolon r3
(trl, r5) =parse NegExpr r4
(trr, r) =parse Stat r5
parse Stat (t@(If,_):ts) =(TokenNode t tl (TokenNode tn (TokenNode (Semicolon,";") trl Nop) (TokenNode (Semicolon,";") trr Nop)), r) where
(tl, r1) =parse NegExpr ts
(tn, r2) =consume Then r1
(trl, r3) =parse Stat r2
(trr, r) =case r3 of
((Else,_):xs) ->parse Stat xs
_ ->(Nop,r3)
parse ForDef (t@(VarVar,_):ts) =(TokenNode t (TokenLeaf tv) tr ,r) where
(tv, r1) =consume Var ts
(tn, r2) =consume Assignment r1
(tr, r) =parse NegExpr r2
parse nt (t:ts) =error ("parser error: "++(show nt)++" on "++(show t)++" is not implemented")
parse nt [] =error ("parser error: "++(show nt)++" on empty is not implemented")
|
Oboema/FP-GO1
|
Parser.hs
|
mit
| 4,496 | 214 | 20 | 888 | 2,553 | 1,398 | 1,155 | 112 | 7 |
{-# LANGUAGE MultiParamTypeClasses, ScopedTypeVariables
, TypeSynonymInstances, FlexibleInstances #-}
{- |
Module : ./CspCASL/Logic_CspCASL.hs
Description : CspCASL instance of type class logic
Copyright : (c) Markus Roggenbach, Till Mossakowski and Uni Bremen 2003
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : non-portable(import Logic.Logic)
Here is the place where the class Logic is instantiated for CspCASL. A
CspCASL signature is a CASL signature with a set of named channels and
processes. Every process has a profile. Morphisms are supposed to allow
renaming of channels and processes, too. Also sublogics (as a superset of some
CASL sublogics) are still missing.
-}
module CspCASL.Logic_CspCASL
( GenCspCASL (..)
, CspCASLSemantics
, CspCASL
, cspCASL
, Trace (..)
, traceCspCASL
, Failure (..)
, failureCspCASL
) where
import Logic.Logic
import Logic.Prover
import Common.DocUtils
import CASL.Logic_CASL
import CASL.Parse_AS_Basic
import CASL.Morphism
import CASL.Sign
import CASL.ToDoc
import qualified CASL.MapSentence as MapSen
import qualified CASL.SimplifySen as SimpSen
import CspCASL.ATC_CspCASL ()
import CspCASL.CspCASL_Keywords
import CspCASL.Morphism as CspCASL_Morphism
import CspCASL.Parse_CspCASL ()
import CspCASL.Print_CspCASL ()
import qualified CspCASL.SignCSP as SignCSP
import qualified CspCASL.SimplifySen as SimplifySen
import CspCASL.StatAnaCSP
import CspCASL.SymbItems
import CspCASL.Symbol
import CspCASL.SymMapAna
import CspCASLProver.CspCASLProver (cspCASLProver)
-- | a generic logic id for CspCASL with different semantics
data GenCspCASL a = GenCspCASL a deriving Show
cspCASL :: GenCspCASL ()
cspCASL = GenCspCASL ()
-- | The top-level logic with the loosest semantics (and without provers)
type CspCASL = GenCspCASL ()
instance Show a => Language (GenCspCASL a) where
language_name (GenCspCASL a) = "CspCASL"
++ let s = show a in if s == "()" then "" else '_' : s
description _ =
"CspCASL - extension of CASL with the process algebra CSP\n" ++
"See http://www.cs.swan.ac.uk/~csmarkus/ProcessesAndData/"
-- | Instance of Sentences for CspCASL
instance Show a => Sentences (GenCspCASL a)
-- sentence
SignCSP.CspCASLSen
-- signature
SignCSP.CspCASLSign
-- morphism
CspCASL_Morphism.CspCASLMorphism
-- symbol
CspSymbol
where
map_sen (GenCspCASL _) m = return . MapSen.mapSen mapSen m
sym_name (GenCspCASL _) = cspSymName
symmap_of (GenCspCASL _) = cspMorphismToCspSymbMap
simplify_sen (GenCspCASL _) =
SimpSen.simplifySen (const return) SimplifySen.simplifySen
sym_of (GenCspCASL _) = symSets
symKind (GenCspCASL _) = show . pretty . cspSymbType
print_named (GenCspCASL _) = printTheoryFormula
-- | Syntax of CspCASL
instance Show a => Syntax (GenCspCASL a)
CspBasicSpec -- basic_spec
CspSymbol
CspSymbItems
CspSymbMapItems
where
parse_symb_items (GenCspCASL _) = Just cspSymbItems
parse_symb_map_items (GenCspCASL _) = Just cspSymbMapItems
parse_basic_spec (GenCspCASL _) = Just $ basicSpec startCspKeywords
-- lattices (for sublogics) missing
class Show a => CspCASLSemantics a where
cspProvers :: a
-> [Prover SignCSP.CspCASLSign SignCSP.CspCASLSen
CspCASL_Morphism.CspCASLMorphism () ()]
cspProvers _ = []
{- further dummy types for the trace of the failure semantics can be added
and made an instance of CspCASLSemantics.
"identity" Comorphisms between these different logics still need to be
defined.
-}
instance CspCASLSemantics ()
data Trace = Trace deriving Show
data Failure = Failure deriving Show
traceCspCASL :: GenCspCASL Trace
traceCspCASL = GenCspCASL Trace
failureCspCASL :: GenCspCASL Failure
failureCspCASL = GenCspCASL Failure
instance CspCASLSemantics Trace where
cspProvers _ = [cspCASLProver]
instance CspCASLSemantics Failure
-- | Instance of Logic for CspCASL
instance CspCASLSemantics a => Logic (GenCspCASL a)
-- Sublogics (missing)
()
-- basic_spec
CspBasicSpec
-- sentence
SignCSP.CspCASLSen
-- symb_items
CspSymbItems
-- symb_map_items
CspSymbMapItems
-- signature
SignCSP.CspCASLSign
-- morphism
CspCASL_Morphism.CspCASLMorphism
CspSymbol
CspRawSymbol
-- proof_tree (missing)
()
where
stability (GenCspCASL _) = Testing
data_logic (GenCspCASL _) = Just (Logic CASL)
empty_proof_tree _ = ()
provers (GenCspCASL _) = cspProvers (undefined :: a)
-- | Static Analysis for CspCASL
instance Show a => StaticAnalysis (GenCspCASL a)
-- basic_spec
CspBasicSpec
-- sentence
SignCSP.CspCASLSen
-- symb_items
CspSymbItems
-- symb_map_items
CspSymbMapItems
-- signature
SignCSP.CspCASLSign
-- morphism
CspCASL_Morphism.CspCASLMorphism
CspSymbol
CspRawSymbol
where
basic_analysis (GenCspCASL _) = Just basicAnalysisCspCASL
stat_symb_items (GenCspCASL _) = cspStatSymbItems
stat_symb_map_items (GenCspCASL _) = cspStatSymbMapItems
id_to_raw (GenCspCASL _) = idToCspRaw
symbol_to_raw (GenCspCASL _) = ACspSymbol
matches (GenCspCASL _) = cspMatches
empty_signature (GenCspCASL _) = SignCSP.emptyCspCASLSign
is_subsig (GenCspCASL _) = SignCSP.isCspCASLSubSig
subsig_inclusion (GenCspCASL _) = cspSubsigInclusion
signature_union (GenCspCASL _) = SignCSP.unionCspCASLSign
signatureDiff (GenCspCASL _) s = return . diffSig SignCSP.diffCspSig s
morphism_union (GenCspCASL _) =
morphismUnion CspCASL_Morphism.cspAddMorphismUnion
SignCSP.cspSignUnion
induced_from_morphism (GenCspCASL _) = cspInducedFromMorphism
induced_from_to_morphism (GenCspCASL _) = cspInducedFromToMorphism
cogenerated_sign (GenCspCASL _) = cspCogeneratedSign
generated_sign (GenCspCASL _) = cspGeneratedSign
|
spechub/Hets
|
CspCASL/Logic_CspCASL.hs
|
gpl-2.0
| 6,053 | 0 | 11 | 1,231 | 1,154 | 616 | 538 | 121 | 1 |
module MidiGen where
import Euterpea
right, wrong, delta, empty, x, y, xy, z, zx, zy, xyz :: Music Pitch
right = (line $ map ($en) [a 4, b 4, cs 5, d 5]) :+: e 5 hn
wrong = (line $ map ($en) [a 4, af 4, g 4, gf 4]) :+: f 4 hn
delta = line $ map ($en) [a 4, b 4, c 5, b 4, a 4, af 4, gf 4, af 4]
empty = a 2 en
x = b 2 en
y = c 3 en
xy = e 3 en
z = d 3 en
zx = f 3 en
zy = g 3 en
xyz = a 3 en
|
HMB-Entertainment/NZT
|
code/music/MidiGen.hs
|
gpl-2.0
| 404 | 0 | 10 | 129 | 289 | 156 | 133 | 14 | 1 |
-- Module Instances: basic functions and instances
-- Author: Abdul Rahim Nizamani, ITIT, Gothenburg University, Sweden
module Instances where
import Prelude hiding (catch)
import Control.Exception (catch, IOException)
import System.IO
import Data.Time
import Data.List
import Data.Function (on)
import Data.Maybe (isNothing,isJust,fromJust)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import System.Directory
import Debug.Trace
import Data.Ratio
import Data.Time.Calendar
combiner = "#" -- combiner is a special binary operator, with size = 0 and always considered a rewarded symbol
deepRule = ["▶","⊣⊢","=="]
shallowRule = ["▷","⊢","=>"]
negativeRule = ["⊬","▷̸","/>"]
itemPositive = "⊢"
itemNegative = "⊬"
class Size a where
size :: a -> Int
data Mode = Einstein | Popper deriving Eq
data Truth = Invalid | Satisfiable | Valid
deriving (Eq,Ord,Show)
data Oper = Oper String | OVar String deriving (Eq,Ord)
data Exp = Root String | Var String | Unary Oper Exp | Binary Oper Exp Exp
deriving (Eq,Ord)
data Item = Item {lhs :: Lhs, rhs :: Rhs, val :: Int}
data Items = Items {getItems :: [Item]}
type Width = Int
type Depth = Int
type Comments = String
type ID = Int
type Arity = Int
type Frequency = Int
type Viability = Double
type Rewarded = Int -- 0 for false, 1 for true. Indicates if a symbol appears in rhs
type FirstTime = UTCTime
type LastTime = UTCTime
type IsFact = Bool
type Substitution = Map String String -- Map variable constant
data Dir = Bi | Uni | Neg deriving (Eq,Ord)
isBi, isUni, isNeg :: Axiom -> Bool
isBi (Axiom (_,_,_,_,_,(_,Bi,_))) = True
isBi _ = False
isUni (Axiom (_,_,_,_,_,(_,Uni,_))) = True
isUni _ = False
isNeg (Axiom (_,_,_,_,_,(_,Neg,_))) = True
isNeg _ = False
instance Show Dir where
show Bi = head deepRule
show Uni = head shallowRule
show Neg = head negativeRule
type Axiom' = (Lhs,Dir,Rhs)
newtype Axiom = Axiom (Viability,Frequency,IsFact,FirstTime,LastTime,Axiom')
axiom' (Axiom (_,_,_,_,_,ax)) = ax
newtype Concept = C (Arity,Rewarded,Frequency,FirstTime,LastTime,Exp)
isUnitConcept (C (0,_,_,_,_,Root _)) = True
isUnitConcept _ = False
type Vars = Set String
newtype Edge = Edge (Exp,Exp,Truth,Set [String])
type Weight = (Truth,Set [String])
type Graph a = Map (a,a) Weight
newtype Rewarding = Rew (Arity,String) -- rewarding symbols, that appear in Rhs
deriving (Eq,Ord)
type WM = Exp
type Lhs = Exp
type Rhs = Exp
type Pattern = Exp
type IPFile = FilePath
type RecentlyRemoved = [Axiom]
type Redundancy = Bool
type Consistency = Bool
type Iterations = Int
type Fact = Axiom
data LTM = Ltm !(Set Fact) !(Set Axiom)
newLtm = Ltm Set.empty Set.empty
ltmAxioms (Ltm _ ax) = ax
ltmFacts (Ltm f _) = f
allAxioms (Ltm fc ax) = Set.union fc ax
biToUni :: LTM -> Exp -> Exp -> LTM
biToUni (Ltm f ax) t t' =
let fx = [(x, Axiom (a,b,c,d,e,(s,Uni,s'))) | x@(Axiom (a,b,c,d,e,(s,Bi,s'))) <- Set.toList f,
s == t', s' == t]
f' = Set.union (Set.fromList $ map snd fx) $ Set.difference f (Set.fromList $ map fst fx)
axx = [(x, Axiom (a,b,c,d,e,(s,Uni,s'))) | x@(Axiom (a,b,c,d,e,(s,Bi,s'))) <- Set.toList ax,
(Axiom (a,b,c,d,e,(t',Bi,t))) `isInstanceOf` x]
ax' = Set.union (Set.fromList $ map snd axx) $ Set.difference ax (Set.fromList $ map fst axx)
in Ltm f' ax'
makeLTM :: (Set Axiom) -> LTM
makeLTM axs =
let (ax,fc) = Set.partition containsVarAx axs
in Ltm fc ax
instance Eq LTM where
(==) (Ltm a b) (Ltm x y) = (a,b) == (x,y)
instance Size LTM where
size (Ltm a b) = Set.size a + Set.size b
ltmDifference :: LTM -> (Set Axiom) -> LTM
ltmDifference (Ltm facts axioms) axs =
let (axAxioms,axFacts) = Set.partition containsVarAx axs
facts' = Set.difference facts axFacts
axioms' = Set.difference axioms axAxioms
axFacts' = Set.fromList . map (\x -> (axLhs x,axRhs x)) $ Set.toList axFacts
in Ltm facts' axioms'
ltmDelete :: Axiom -> LTM -> LTM
ltmDelete ax (Ltm fc axs) =
if containsVarAx ax
then Ltm fc (Set.delete ax axs)
else Ltm (Set.delete ax fc) axs
ltmMember :: Axiom -> LTM -> Bool
ltmMember ax (Ltm fc axs) = if containsVarAx ax
then Set.member ax axs
else Set.member ax fc
ltmNotmember :: Axiom -> LTM -> Bool
ltmNotmember ax (Ltm fc axs) = if containsVarAx ax
then Set.notMember ax axs
else Set.notMember ax fc
insertInLTM :: LTM -> Axiom -> LTM
insertInLTM (Ltm fc ax) c@(Axiom (viab,freq,isfact,first,last,(lhs,dir,rhs))) | containsVarAx c =
let index' = Set.lookupIndex c ax
in if isNothing index'
then Ltm fc (Set.insert c ax)
else let index = fromJust index'
Axiom (_,_,_,first',_,_) = Set.elemAt index ax
in Ltm fc (Set.insert (Axiom (viab,freq,isfact,first',last,(lhs,dir,rhs))) ax) -- replace old axiom with new
insertInLTM (Ltm fc ax) c@(Axiom (viab,freq,isfact,first,last,(lhs,dir,rhs))) = -- c is fact
let index' = Set.lookupIndex c fc
in if isNothing index'
then let fc' = Set.insert c fc
in Ltm fc' ax
else let index = fromJust index'
Axiom (_,_,_,first',_,_) = Set.elemAt index fc
fc' = Set.insert (Axiom (viab,freq,isfact,first',last,(lhs,dir,rhs))) fc
in Ltm fc' ax -- replace old axiom with new
ltmUpdateViability time decay (Ltm fc ax)
= Ltm (Set.mapMonotonic (updateViability time decay) fc) (Set.mapMonotonic (updateViability time decay) ax)
type AgentParams = (Width, Depth, Int, (Redundancy, Consistency, Mode, Iterations))
type AgentMemory = (LTM,Set Concept,Graph Pattern,Set Pattern,Set Rewarding,RecentlyRemoved)
data Agent = Agent (FilePath,Comments) AgentParams AgentMemory deriving Eq
makeFalse :: Graph Pattern -> [(Bool,[Axiom])] -> Graph Pattern
makeFalse graph ax = undefined
type Length = Int
type StateD = (Exp,Maybe Axiom,Set Exp)
axV (Axiom (v,_,_,_,_,_)) = v
axFreq (Axiom (_,x,_,_,_,_)) = x
axIsFact (Axiom (_,_,x,_,_,_)) = x
axFirst (Axiom (_,_,_,x,_,_)) = x
axRecency (Axiom (_,_,_,_,x,_)) = x
axLast (Axiom (_,_,_,_,x,_)) = x
axLhs (Axiom (_,_,_,_,_,(l,_,_))) = l
axRhs (Axiom (_,_,_,_,_,(_,_,r))) = r
axPair (Axiom (_,_,_,_,_,(l,_,r))) = (l,r)
axIsBi (Axiom (_,_,_,_,_,(_,Bi,_))) = True
axIsBi _ = False
axIsUni (Axiom (_,_,_,_,_,(_,Uni,_))) = True
axIsUni _ = False
arity (C (a,_,_,_,_,_)) = a
cexp (C (_,_,_,_,_,a)) = a
isRoot (Root _) = True
isRoot _ = False
fromRoot (Root x) = x
agentMemory (Agent _ _ x) = x
getIterations (Agent _ (_,_,_,(_,_,_,x)) _) = x
setIterations (Agent a (b,c,d,(e,f,g,h)) i) iter = (Agent a (b,c,d,(e,f,g,iter)) i)
-------------------------------------------------------------------------------
---------------- CONSTRUCTORS -------- ----------------------------------------
-------------------------------------------------------------------------------
makeR :: String -> Exp
makeR = Root
makeV :: String -> Exp
makeV = Var
makeU :: String -> Exp -> Exp
makeU s e = Unary (Oper s) e
makeB :: String -> Exp -> Exp -> Exp
makeB s e f = Binary (Oper s) e f
makeGraph :: [((Exp,Exp),(Truth,Set [String]))] -> Graph Exp
makeGraph patterns = foldl' (\m (key,(b,set)) ->
let value = Map.lookup key m
in if isNothing value
then Map.insert key (b,set) m
else let (b',set') = fromJust value
in if b == Valid
then Map.insert key (Valid,set) m
else if b' == Valid
then Map.insert key (Valid,set') m
else if b==Invalid
then Map.insert key (b,set) m
else if b'==Invalid
then Map.insert key (b',set') m
else Map.insert key (Satisfiable,Set.union set set') m
) Map.empty patterns
-- Map.fromList . map (\(Edge (e1,e2,b,set)) -> ((e1,e2),(b,set)))
getEdges :: Graph Exp -> [Edge]
getEdges = map (\((e1,e2),(b,set)) -> Edge (e1,e2,b,set)) . Map.toList
-------------------------------------------------------------------------------
---------------- INSTANCE DECLARATIONS ----------------------------------------
-------------------------------------------------------------------------------
instance Eq Concept where
(==) = (==) `on` (\c -> (arity c,cexp c))
instance Ord Concept where
compare = compare `on` (\c -> (arity c,cexp c))
instance Show Oper where
show (Oper s) = s
show (OVar "x") = "x"
show (OVar "y") = "y"
show (OVar "z") = "z"
show (OVar s) = "\\" ++ s
instance Eq Axiom where
(Axiom (_,_,_,_,_,(l1,d1,r1))) == (Axiom (_,_,_,_,_,(l2,d2,r2))) = (d1,l1,r1) == (d2,l2,r2)
instance Ord Axiom where
compare (Axiom (_,_,_,_,_,(l1,d1,r1))) (Axiom (_,_,_,_,_,(l2,d2,r2))) = compare (d1,l1,r1) (d2,l2,r2)
instance Size Item where
size (Item x y _) = size x + size y
tsize :: Exp -> Int -- number of nodes in tree
tsize (Unary _ x) = 1 + tsize x
tsize (Binary _ x y) = 1 + tsize x + tsize y
tsize _ = 1
instance Size Exp where
size (Unary a x) = 1 + size x
size (Binary (Oper o) x y) | o == combiner = size x + size y
size (Binary a x y) = 1 + size x + size y
size _ = 1
instance Size Axiom where
size (Axiom (_,_,_,_,_,(x,_,y))) = size x + size y
instance Size [a] where
size xs = length xs
instance Size (Set a) where
size x = Set.size x
instance Size (Map a b) where
size x = Map.size x
instance Show Exp where
show (Root "x") = "(\\x)"
show (Root "y") = "(\\y)"
show (Root "z") = "(\\z)"
show (Root a) = "(" ++ a ++ ")"
show (Var "x") = "(x)"
show (Var "y") = "(y)"
show (Var "z") = "(z)"
show (Var v) = "(\\v " ++ v ++ ")"
show (Unary a e) = "(" ++ show a ++ " " ++ showexp e ++ ")"
show (Binary a e1 e2) = "(" ++ showexp e1 ++ " " ++ show a ++ " " ++ showexp e2 ++ ")"
showexp :: Exp -> String
showexp (Root "x") = "\\x"
showexp (Root "y") = "\\y"
showexp (Root "z") = "\\z"
showexp (Root a) = a
showexp (Var "x") = "x"
showexp (Var "y") = "y"
showexp (Var "z") = "z"
showexp e = show e
instance Show Item where
show (Item lhs rhs val) | val >= 0 = show lhs ++ "⊢" ++ show rhs
show (Item lhs rhs val) = show lhs ++ "⊬" ++ show rhs
instance Show Axiom where
show (Axiom (v,freq,isfact,start,last,(lhs,dir,rhs))) =
"(A," ++ show v
++ "," ++ show freq
++ "," ++ show isfact
++ "," ++ show start
++ "," ++ show last
++ "," ++ show lhs ++ show dir ++ show rhs
++ ")"
instance Show Concept where
show (C (arity,rew,freq,start,last,exp)) =
"(C," ++ show arity
++ "," ++ show rew
++ "," ++ show freq
++ "," ++ show start
++ "," ++ show last
++ "," ++ show exp
++ ")"
instance Show Edge where
show (Edge (e1,e2,b,set)) =
"(E," ++ show e1
++ "," ++ show e2
++ "," ++ show b
++ ",[" ++ concat (intersperse "," (map (\x -> "[" ++ concat (intersperse "," x) ++ "]") (Set.toList set)))
++ "])"
isLeft (Left _) = True
isLeft _ = False
getLeft (Left r) = r
isRight (Right _) = True
isRight _ = False
getRight (Right r) = r
updateViability :: UTCTime -> Double -> Axiom -> Axiom
updateViability now d ax@(Axiom (_,n',isfact,first,last,(lhs,dir,rhs))) | first == last
= let t_n' = abs (utcToDouble now - utcToDouble first)
t_n = if t_n' < 1 then 1 else t_n'
n = fromIntegral n'
viability = log (n / (1 - d)) - (d * log t_n)
in if isNaN viability || isInfinite viability
then error $ "\nbaseLevel: error computing base viability for first==last, tn'=" ++ show t_n' ++ ", "
else Axiom (viability,n',isfact,first,last,(lhs,dir,rhs))
updateViability now d ax@(Axiom (vprev,n',isfact,first,last,(lhs,dir,rhs)))
= let n = fromIntegral n'
t_n' = abs (utcToDouble now - utcToDouble first)
t_1' = abs (utcToDouble now - utcToDouble last)
t_n = if t_n' == 0 then 0.00001 else t_n'
t_1 = if t_n == t_1' then 0 else t_1'
term1 = if t_1 == 0.0 then 0.0 else t_1 ** (0 - d)
tnd = if t_n == 0.0 then 0.0 else t_n ** (1 - d)
t1d = if t_1 == 0.0 then 0.0 else t_1 ** (1 - d)
a = (n - 1) * (tnd - t1d)
b = (1.0 - d) * (t_n - t_1)
viability = log (term1 + (if b == 0.0 then 0 else a / b))
in if isNaN viability || isInfinite viability
then Axiom (viability,n',isfact,first,last,(lhs,dir,rhs)) -- error $ "\nbaseLevel: error computing base viability, tn=" ++ show t_n' ++ ", t1=" ++ show t_1'
else Axiom (vprev,n',isfact,first,last,(lhs,dir,rhs))
utcToDouble :: UTCTime -> Double
utcToDouble time =
let days = fromIntegral . toModifiedJulianDay . utctDay $ time
-- secs = read (init . show $ utctDayTime time) :: Double
secs = diffTimeToSeconds $ utctDayTime time
in days * 86400 + secs
diffTimeToSeconds :: DiffTime -> Double
diffTimeToSeconds d =
let r = toRational d
in fromIntegral (numerator r) / (fromIntegral (denominator r))
{-
data E12 = E12
deriving (Typeable)
instance HasResolution E12 where
resolution _ = 1000000000000
newtype Fixed a = MkFixed Integer -- ^ /Since: 4.7.0.0/
deriving (Eq,Ord,Typeable)
newtype DiffTime = MkDiffTime (Fixed E12)
diff = MkDiffTime (MkFixed Integer :: Fixed E12)
-}
findVarBinding :: Axiom -> Axiom -> Maybe [(String,Exp)]
findVarBinding (Axiom (_,_,_,_,_,(f,_,f'))) ax@(Axiom (_,_,_,_,_,(x,_,x'))) =
let bind1 = expVarBinding x f -- Maybe [(String,Exp)]
bind2 = expVarBinding x' f' -- Maybe [(String,Exp)]
in if isJust bind1 && isJust bind2
then let bind = fromJust bind1 ++ fromJust bind2 -- -- [(String,Exp)]
in if (length bind == countVars ax) && (null $ sameVarBinding bind)
then Just $ nubBy' fst bind
else Nothing
else Nothing
axiomVarBinding :: Axiom -> Axiom -> Maybe [(String,String)]
axiomVarBinding (Axiom (_,_,_,_,_,(f,_,f'))) ax@(Axiom (_,_,_,_,_,(x,_,x'))) =
let bind1 = expVarBinding x f -- Maybe [(String,Exp)]
bind2 = expVarBinding x' f' -- Maybe [(String,Exp)]
in if isJust bind1 && isJust bind2
then let bind = fromJust bind1 ++ fromJust bind2 -- -- [(String,Exp)]
in if length bind == countVars ax
&& (null $ sameVarBinding bind)
&& all isRoot (map snd bind)
then Just $ nubBy' fst $ [(a,b) | (a,Root b) <- bind]
else Nothing
else Nothing
isInstanceOf :: Axiom -> Axiom -> Bool
isInstanceOf (Axiom (_,_,_,_,_,(f,_,f'))) ax@(Axiom (_,_,_,_,_,(x,_,x'))) =
let bind1 = expVarBinding x f -- Maybe [(String,Exp)]
bind2 = expVarBinding x' f' -- Maybe [(String,Exp)]
in if isJust bind1 && isJust bind2
then let bind = fromJust bind1 ++ fromJust bind2 -- -- [(String,Exp)]
in length bind == countVars ax
&& (null $ sameVarBinding bind)
&& all isRoot (map snd bind)
else False
isInstance :: Axiom -> Axiom -> Bool
isInstance (Axiom (_,_,_,_,_,(f,_,f'))) ax@(Axiom (_,_,_,_,_,(x,_,x'))) =
let bind1 = expVarBinding x f -- Maybe [(String,Exp)]
bind2 = expVarBinding x' f' -- Maybe [(String,Exp)]
in if isJust bind1 && isJust bind2
then let bind = fromJust bind1 ++ fromJust bind2 -- -- [(String,Exp)]
in length bind == countVars ax
&& (null $ sameVarBinding bind)
else False
instance' :: Exp -> Exp -> [(String,Exp)]
instance' = undefined
isPure (Axiom (_,_,_,_,_,(t,_,t'))) =
let lhsvar = nub' $ getVars t
rhsvar = nub' $ getVars t'
in null (rhsvar \\ lhsvar)
-- stability of constants and variables: Every constant is unique
isStable ax@(Axiom (_,_,_,_,_,(t,_,t'))) = size t > 1 && t /= t' && isPure ax
isBasicFact :: Set Rewarding -> Axiom -> Bool
isBasicFact rew (Axiom (_,_,_,_,_,ax)) = func rew $ fst' ax
where
func rew (Unary (Oper op) (Root _)) | Set.member (Rew (1,op)) rew = True
func rew (Unary (Oper _) (Root _)) = False
func rew (Binary (Oper op) (Root _) (Root _)) | Set.member (Rew (2,op)) rew = True
func rew (Binary (Oper _) (Root _) (Root _)) = True
func _ _ = False
isSmallFact :: Axiom -> Bool
isSmallFact ax@(Axiom (_,_,_,_,_,(t,_,t'))) = isFact ax && size t <= 3
isFact :: Axiom -> Bool
isFact ax@(Axiom (_,_,_,_,_,(t,_,t')))
= (not . containsVarAx) ax
&& t /= t'
isAxiom :: Axiom -> Bool
isAxiom = containsVarAx
isMixedPlus :: Axiom -> Bool
isMixedPlus ax@(Axiom (_,_,_,_,_,(t,_,t')))
= (not . null $ lhsvar)
&& (isOne . nub' . getConstsAx $ ax)
&& ((sort . nub' $ lhsvar)
== (sort . nub' $ rhsvar))
&& size t > 1
&& t /= t'
where
lhsvar = getVars t
rhsvar = getVars t'
isMixed :: Axiom -> Bool
isMixed ax@(Axiom (_,_,_,_,_,(t,_,t')))
= isOne vars
&& isOne consts
&& notnull lhsvar
&& t /= t'
&& checkRhs t'
where
lhsvar = nub' $ getVars t
rhsvar = nub' $ getVars t'
vars = nub' (lhsvar ++ rhsvar)
consts = nub' . getConstsAx $ ax
checkRhs (Var _) = True
checkRhs (Root _) = True
checkRhs _ = False
isOne :: [a] -> Bool
isOne [x] = True
isOne _ = False
atMostOne :: [a] -> Bool
atMostOne [] = True
atMostOne [x] = True
atMostOne _ = False
getConstsAx :: Axiom -> [String]
getConstsAx (Axiom (_,_,_,_,_,(x,_,y))) = getConsts x ++ getConsts y
getConsts :: Exp -> [String]
getConsts e = case e of
Root r -> [r]
Unary _ e -> getConsts e
Binary _ e f -> getConsts e ++ getConsts f
_ -> []
getConstsSet :: Axiom -> Set String
getConstsSet (Axiom (_,_,_,_,_,(x,_,y))) = Set.union (getConstsSet' x) (getConstsSet' y)
getConstsSet' :: Exp -> Set String
getConstsSet' e = case e of
Root r -> Set.singleton r
Unary _ e -> getConstsSet' e
Binary _ e f -> Set.union (getConstsSet' e) (getConstsSet' f)
_ -> Set.empty
getVarsAx :: Axiom -> [String]
getVarsAx (Axiom (_,_,_,_,_,(x,_,y))) = getVars x ++ getVars y
getVars :: Exp -> [String]
getVars e = case e of
Var v -> [v]
Unary (OVar v) e -> v : getVars e
Unary _ e -> getVars e
Binary (OVar v) e f -> v : (getVars e ++ getVars f)
Binary _ e f -> getVars e ++ getVars f
_ -> []
getVarsSet :: Axiom -> Set String
getVarsSet (Axiom (_,_,_,_,_,(x,_,y))) = Set.union (getVarsSet' x) (getVarsSet' y)
getVarsSet' :: Exp -> Set String
getVarsSet' e = case e of
Root _ -> Set.empty
Var v -> Set.singleton v
Unary (OVar v) e' -> Set.insert v (getVarsSet' e')
Unary _ e -> getVarsSet' e
Binary (OVar v) e' f -> Set.insert v (Set.union (getVarsSet' e') (getVarsSet' f))
Binary _ e' f -> Set.union (getVarsSet' e') (getVarsSet' f)
getUnary :: Exp -> [String]
getUnary e = case e of
Root _ -> []
Var _ -> []
Unary (Oper u) e -> u : getUnary e
Unary _ e -> getUnary e
Binary _ e f -> getUnary e ++ getUnary f
getBinary :: Exp -> [String]
getBinary e = case e of
Root _ -> []
Var v -> []
Unary _ e -> getBinary e
Binary (Oper b) e f -> b : (getBinary e ++ getBinary f)
Binary _ e f -> (getBinary e ++ getBinary f)
getUnaryBinary :: Exp -> [(Arity,String)]
getUnaryBinary e = case e of
Root _ -> []
Var _ -> []
Unary (Oper u) e -> (1,u) : getUnaryBinary e
Unary _ e -> getUnaryBinary e
Binary (Oper b) e f -> (2,b) : (getUnaryBinary e ++ getUnaryBinary f)
Binary _ e f -> (getUnaryBinary e ++ getUnaryBinary f)
getSymbolsAx :: Axiom -> [(Arity,String)]
getSymbolsAx (Axiom (_,_,_,_,_,(x,_,y))) = getSymbols x ++ getSymbols y
getSymbols :: Exp -> [(Arity,String)]
getSymbols e = case e of
Root r -> [(0,r)]
Var v -> [] -- [(0,v)]
Unary (Oper u) e -> (1,u) : getSymbols e
Unary _ e -> getSymbols e
Binary (Oper b) e f -> (2,b) : (getSymbols e ++ getSymbols f)
Binary _ e f -> (getSymbols e ++ getSymbols f)
isUnary ax = isUnary' . fst' . axiom' $ ax
isUnary' (Unary _ _) = True
isUnary' _ = False
isUnary'' (Unary (Oper _) _) = True
isUnary'' _ = False
isAlgebraic :: Axiom -> Bool
isAlgebraic ax@(Axiom (_,_,_,_,_,(t,_,t')))
= not (containsConstAx ax)
&& (sort lhsvar == sort rhsvar)
&& (sort lhsunr == sort rhsunr)
&& (sort lhsbin == sort rhsbin)
&& size t > 1
&& size ax <= 7
&& t /= t'
where
lhsvar = nub' $ getVars t
rhsvar = nub' $ getVars t'
lhsunr = nub' $ getUnary t
rhsunr = nub' $ getUnary t'
lhsbin = nub' $ getBinary t
rhsbin = nub' $ getBinary t'
isAlgebraicAbs :: Axiom -> Bool
isAlgebraicAbs ax@(Axiom (_,_,_,_,_,(t,_,t')))
= not (containsConstAx ax)
&& (sort lhsvar == sort rhsvar)
&& size t > 1
&& t /= t'
where
lhsvar = nub' $ getVars t
rhsvar = nub' $ getVars t'
isConservative :: Axiom -> Bool
isConservative ax@(Axiom (_,_,_,_,_,(t,_,t')))
= isAxiom ax && isStable ax
&& and [v `elem` lhs' | v@(Var _) <- rhs']
&& and [e `elem` lhs' | e@(Root _) <- rhs']
&& and [u `elem` [u' | (Unary u' _) <- lhs'] | (Unary u _) <- rhs']
&& and [b `elem` [b' | (Binary b' _ _) <- lhs'] | (Binary b _ _) <- rhs']
where
lhs' = getSubExp t
rhs' = getSubExp t'
varConstBinding :: Exp -> Exp -> Maybe Substitution -- Map String (Root c)
varConstBinding (Root x) (Root y) | x == y = Just Map.empty
varConstBinding (Var v) (Root s) = Just $ Map.singleton v s
varConstBinding (Unary (OVar p) p') (Unary (Oper e) e') =
let result = varConstBinding p' e'
in if isNothing result
then Just $ (Map.singleton p e)
else Just $ Map.insert p e (fromJust result)
varConstBinding (Unary p p') (Unary e e') | p == e = varConstBinding p' e'
varConstBinding (Binary (OVar op1) p1 p2) (Binary (Oper op2) e1 e2) =
let result1 = varConstBinding p1 e1
result2 = varConstBinding p2 e2
in if (isNothing result1 || isNothing result2)
then Just $ (Map.singleton op1 op2)
else let result = mergeSubstitutions (fromJust result1) (fromJust result2)
in if isNothing result
then Just $ (Map.singleton op1 op2)
else mergeSubstitutions (Map.singleton op1 op2) (fromJust result)
varConstBinding (Binary op1 p1 p2) (Binary op2 e1 e2)
| op1 == op2 && isJust result1 && isJust result2
= mergeSubstitutions (fromJust result1) (fromJust result2)
where
result1 = varConstBinding p1 e1
result2 = varConstBinding p2 e2
varConstBinding _ _ = Nothing
mergeSubstitutions :: Substitution -> Substitution -> Maybe Substitution
mergeSubstitutions m1 m2 = merge' m1 (Map.toList m2)
where
merge' mp1 [] = Just mp1
merge' mp1 ((x,y):mp2) = let result = Map.lookup x mp1
in if isNothing result
then merge' (Map.insert x y mp1) mp2
else if (fromJust result == y)
then merge' mp1 mp2
else Nothing
-- Matches left Exp with right Exp
matchExpExp :: Exp -> Exp -> Bool
matchExpExp (Var v) _ = True
matchExpExp (Root x) (Root y) = x == y
matchExpExp (Unary (OVar p) p') (Unary e e') = matchExpExp p' e'
matchExpExp (Unary p p') (Unary e e') | p == e = matchExpExp p' e'
matchExpExp (Binary (OVar op1) p1 p2) (Binary op2 e1 e2) = matchExpExp p1 e1 && matchExpExp p2 e2
matchExpExp (Binary op1 p1 p2) (Binary op2 e1 e2)
| op1 == op2 = matchExpExp p1 e1 && matchExpExp p2 e2
matchExpExp _ _ = False
expVarBinding :: Exp -> Exp -> Maybe [(String,Exp)]
expVarBinding (Var v) arg = Just [(v,arg)]
expVarBinding (Root x) (Root y) | x == y = Just []
expVarBinding (Unary (OVar p) p') (Unary (Oper e) e') =
let result = expVarBinding p' e'
in if isNothing result
then Nothing
else Just $ (p,(Root e)) : (fromJust result)
expVarBinding (Unary p p') (Unary e e') | p == e = expVarBinding p' e'
-- expVarBinding (palm x hand) (Islamabad capital Pakistan)
expVarBinding (Binary (OVar op1) p1 p2) (Binary (Oper op2) e1 e2) =
let result1 = expVarBinding p1 e1
result2 = expVarBinding p2 e2
in if (isNothing result1 || isNothing result2)
then Nothing -- Just $ [(op1,Root op2)]
else Just $ (op1,Root op2) : ((fromJust result1) ++ (fromJust result2))
expVarBinding (Binary op1 p1 p2) (Binary op2 e1 e2) | op1 == op2 && isJust result1 && isJust result2
= Just (fromJust result1 ++ fromJust result2)
where
result1 = expVarBinding p1 e1
result2 = expVarBinding p2 e2
expVarBinding _ _ = Nothing
matchingAxiom func (Axiom (_,_,_,_,_,ax)) = matchExpExp (fst' ax) func
containsVarItem :: Item -> Bool
containsVarItem (Item lhs rhs _) = containsVar lhs || containsVar rhs
containsVar :: Exp -> Bool
containsVar e = case e of
Var _ -> True
Root _ -> False
Unary (OVar _) _ -> True
Unary _ e -> containsVar e
Binary (OVar _) _ _ -> True
Binary _ e f -> containsVar e || containsVar f
containsVarAx :: Axiom -> Bool
containsVarAx (Axiom (_,_,_,_,_,(x,_,y))) = containsVar x || containsVar y
containsConst :: Exp -> Bool
containsConst e = case e of
Var _ -> False
Root _ -> True
Unary _ e -> containsConst e
Binary _ e f -> containsConst e || containsConst f
containsConstAx :: Axiom -> Bool
containsConstAx (Axiom (_,_,_,_,_,(x,_,y))) = containsConst x || containsConst y
countVarsUnique :: Axiom -> Int
countVarsUnique ax = length $ nub' (getVarsAx ax)
countVars :: Axiom -> Int
countVars (Axiom (_,_,_,_,_,(p,_,q))) = mCountVars' p + mCountVars' q
mCountVars' = countVars' -- memoize countVars'
countVars' (Var _) = 1
countVars' (Root _) = 0
countVars' (Unary (OVar _) e) = 1 + mCountVars' e
countVars' (Unary _ e) = mCountVars' e
countVars' (Binary (OVar _) e1 e2) = 1 + mCountVars' e1 + mCountVars' e2
countVars' (Binary _ e1 e2) = mCountVars' e1 + mCountVars' e2
countConsts :: Axiom -> Int
countConsts (Axiom (_,_,_,_,_,(p,_,q))) = countConsts' p + countConsts' q
countConsts' (Var _) = 0
countConsts' (Root _) = 1
countConsts' (Unary _ e) = countConsts' e
countConsts' (Binary _ e1 e2) = countConsts' e1 + countConsts' e2
-- | Returns multiple bindings for the same variable, if any exist
sameVarBinding :: Eq a => [(String,a)] -> [(String,a)]
sameVarBinding [] = []
--sameVarBinding :: [(HsQName,HsExp)] -> [(HsQName,HsExp)]
sameVarBinding ((name,exp):xs) =
let xs'' = [(n,e) | (n,e) <- xs, n == name]
xs' = [(n,e) | (n,e) <- xs'', e /= exp]
in if null xs'
then sameVarBinding xs
else ((name,exp):xs') ++ sameVarBinding [(n,e) | (n,e) <- xs, n /= name]
getSubExpAx :: Axiom -> [Exp]
getSubExpAx (Axiom (_,_,_,_,_,(x,_,y))) = getSubExp x ++ getSubExp y
-- | returns a list of all subexpressions
getSubExp :: Exp -> [Exp]
getSubExp e = e : case e of
Unary _ x -> getSubExp x
Binary _ x y -> getSubExp x ++ getSubExp y
_ -> []
replaceConstsWithVars :: [Exp] -> Exp -> Exp
replaceConstsWithVars vars exp = fst $ func vars exp
where
func [] e = (e,[])
func vars e@(Var _) = (e,vars)
func (x:xs) e@(Root _) = (x,xs)
func vars (Unary f e) = let (e',vars') = func vars e
in (Unary f e',vars')
func vars (Binary b e f) = let (e',v') = func vars e
(f',vars') = func v' f
in (Binary b e' f',vars')
-- | Replaces an Exp (exp) with an Exp (arg) in the main expression (rhs)
-- replaceExpInExp :: Rhs -> Exp -> Exp -> Exp
-- replaceExpInExp rhs (Var var) arg = replaceAllSubExp rhs var arg
-- replaceExpInExp rhs (Unary s1 e1) (Unary s2 e2) = replaceExpInExp rhs e1 e2
-- replaceExpInExp rhs (Binary s1 p1 p2) (Binary s2 e1 e2)
-- = replaceExpInExp (replaceExpInExp rhs p1 e1) p2 e2
-- replaceExpInExp rhs _ _ = rhs
-- replaceAllSubExp :: Rhs -> String -> Exp -> Exp
-- replaceAllSubExp rhs v arg = case rhs of
-- Var v' -> v == v' ? arg $ rhs
-- Unary s e -> makeU s $ replaceAllSubExp e v arg
-- Binary s e1 e2 -> makeB s (replaceAllSubExp e1 v arg) (replaceAllSubExp e2 v arg)
-- _ -> rhs
replaceAllSubExp :: Rhs -> Map String Exp -> Exp
replaceAllSubExp rhs bind = case rhs of
Var v -> if Map.member v bind then bind Map.! v else rhs
Unary (OVar v) e -> let s = if Map.member v bind then bind Map.! v else rhs
in if isRoot s
then Unary (Oper (fromRoot s)) $ replaceAllSubExp e bind
else Unary (OVar v) $ replaceAllSubExp e bind
Unary s e -> Unary s $ replaceAllSubExp e bind
Binary (OVar v) e1 e2 ->
let s = if Map.member v bind then bind Map.! v else rhs
in if isRoot s
then Binary (Oper (fromRoot s)) (replaceAllSubExp e1 bind) (replaceAllSubExp e2 bind)
else Binary (OVar v) (replaceAllSubExp e1 bind) (replaceAllSubExp e2 bind)
Binary s e1 e2 -> Binary s (replaceAllSubExp e1 bind) (replaceAllSubExp e2 bind)
_ -> rhs
-- replaceAllSubExp2 y'@(Var "x") v@(Var "x") c@(Root "T")
-- replace all instances
replaceAllSubExp2 :: Exp -> Exp -> Exp -> Exp
-- replace every "v" with "arg" in "exp"
replaceAllSubExp2 exp v arg | exp == v = arg
replaceAllSubExp2 exp v arg = case exp of
-- Var v' -> v == exp ? arg $ exp
Unary s e -> let e' = replaceAllSubExp2 e v arg
in Unary s e'
Binary s e1 e2 ->
let e1' = (replaceAllSubExp2 e1 v arg)
e2' = (replaceAllSubExp2 e2 v arg)
in Binary s e1' e2'
_ -> exp
-- replace only one instance
replaceOneSubExp2 :: Exp -> Exp -> Exp -> Exp
replaceOneSubExp2 exp v arg | exp == arg = v
replaceOneSubExp2 exp v arg = case exp of
-- Var v' -> v == exp ? arg $ exp
Unary s e -> let e' = replaceOneSubExp2 e v arg
in Unary s e'
Binary s e1 e2 -> let e1' = (replaceOneSubExp2 e1 v arg)
in if e1' /= e1
then Binary s e1' e2
else
let e2' = (replaceOneSubExp2 e2 v arg)
in Binary s e1' e2'
_ -> exp
replaceLhsRhsWm :: Exp -> Exp -> Exp -> [Exp] -- replace lhs with rhs in wm
replaceLhsRhsWm lhs rhs wm | wm == lhs
= [rhs]
replaceLhsRhsWm lhs rhs (Unary u wm)
= map (Unary u) $ replaceLhsRhsWm lhs rhs wm
replaceLhsRhsWm lhs rhs (Binary b w1 w2)
= map (\x -> Binary b x w2) (replaceLhsRhsWm lhs rhs w1)
++ map (\x -> Binary b w1 x) (replaceLhsRhsWm lhs rhs w2)
replaceLhsRhsWm _ _ wm = [wm]
containsExp :: WM -> Exp -> Bool
containsExp wm exp | wm == exp = True
containsExp wm exp = case wm of
(Unary _ e) -> containsExp e exp
(Binary _ e f) -> containsExp e exp || containsExp f exp
_ -> False
notnull = not . null
wschars = " \t\r\n"
strip :: String -> String
strip = lstrip . rstrip
lstrip s = case s of
[] -> []
(x:xs) -> if elem x wschars
then lstrip xs
else s
rstrip = reverse . lstrip . reverse
-- Function to simulate if-then-else
if' :: Bool -> a -> a -> a
if' True x _ = x
if' False _ y = y
zipIf :: [Bool] -> [a] -> [a] -> [a]
zipIf = zipWith3 if'
infixr 1 ?
(?) :: Bool -> a -> a -> a
(?) = if'
readFileSafe :: FilePath -> TextEncoding -> IO String
readFileSafe f enc = readFileSafe' f enc
`catch`
(\e -> do putStrLn ("Error in reading file " ++ f)
putStrLn $ "Exception: " ++ show (e :: IOException)
return "")
-- | Read file after checking its existence and permissions
readFileSafe' :: FilePath -> TextEncoding -> IO String
readFileSafe' f enc = do
e <- doesFileExist f
if (not e)
then do
putStrLn $ "File " ++ f ++ " does not exist."
return ""
else do
p <- getPermissions f
if (not (readable p))
then do
putStrLn $ "Unable to read file " ++ f ++ "."
return ""
else do
h <- openFile f ReadMode
hSetEncoding h enc
text <- hGetContents h
putStrLn $ "Reading file " ++ show f ++ ", file length= " ++ show (length text)
hClose h
return text
nub' :: (Ord a) => [a] -> [a]
nub' = go Set.empty
where go _ [] = []
go s (x:xs) | Set.member x s = go s xs
| otherwise = x : go (Set.insert x s) xs
nubBy' :: (Ord b) => (a -> b) -> [a] -> [a]
nubBy' = go Set.empty
where go _ _ [] = []
go s f (x:xs) | Set.member x' s = go s f xs
| otherwise = x : go (Set.insert x' s) f xs
where x' = f x
unlines' [] = []
unlines' [l] = l
unlines' (l:ls) = l ++ '\n' : unlines' ls
printExp :: Exp -> String
printExp (Root s) = "(Root " ++ s ++ ")"
printExp (Var v) = "(Var " ++ v ++ ")"
printExp (Unary u e) = "(Unary " ++ show u ++ " " ++ show e ++ ")"
printExp (Binary b e1 e2) = "(Binary " ++ show b ++ " " ++ show e1 ++ " " ++ show e2 ++ ")"
fst' (x,_,_) = x
snd' (_,x,_) = x
thd' (_,_,x) = x
getUnaryOper (Unary (Oper f) _) = f
fromLeft (Left x) = x
fromRight (Right x) = x
boolToInt :: Bool -> Int
boolToInt True = 1
boolToInt False = 0
|
arnizamani/aiw
|
Instances.hs
|
gpl-2.0
| 36,046 | 0 | 20 | 11,587 | 14,645 | 7,732 | 6,913 | 764 | 11 |
{-# LANGUAGE FlexibleContexts, NoMonomorphismRestriction, GADTs, ScopedTypeVariables, TemplateHaskell, StandaloneDeriving #-}
{-# OPTIONS -Wall #-}
import Tetrahedron
import Blender
import Data.Function
import Data.Vect.Double
import SimplexLabels
import SimplicialComplex
import System.Exit
main :: IO ExitCode
main = testBlender .
defaultScene .
transformCoords rot $
(pseudomanifoldStyle
(setGluing "F" (vA,vB,vC) (vA,vB,vD) S3bac
(setGluing "G" (vA,vC,vD) (vB,vC,vD) S3cab
tet3d)))
--`disjointUnion` abnormalCurve
where
rot = withOrigin (Vec3 0.5 0.5 0.5) (rotate3 (pi*0.42) vec3Z)
|
DanielSchuessler/hstri
|
bin/labelsTest.hs
|
gpl-3.0
| 683 | 2 | 12 | 162 | 174 | 95 | 79 | 18 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
-- |
-- Module : Aura.Packages.AUR
-- Copyright : (c) Colin Woodbury, 2012 - 2020
-- License : GPL3
-- Maintainer: Colin Woodbury <[email protected]>
--
-- Module for connecting to the AUR servers, downloading PKGBUILDs and package
-- sources.
module Aura.Packages.AUR
( -- * Batch Querying
aurLookup
, aurRepo
-- * Single Querying
, aurInfo
, aurSearch
-- * Source Retrieval
, clone
, pkgUrl
) where
import Aura.Core
import Aura.Languages
import Aura.Pkgbuild.Fetch
import Aura.Settings
import Aura.Types
import Aura.Utils
import Control.Monad.Trans.Maybe
import Control.Scheduler (Comp(..), traverseConcurrently)
import Data.Versions (versioning)
import Linux.Arch.Aur
import Network.HTTP.Client (Manager)
import RIO
import RIO.Directory
import RIO.FilePath
import RIO.Lens (each, non)
import qualified RIO.List as L
import qualified RIO.Map as M
import qualified RIO.NonEmpty as NEL
import qualified RIO.Set as S
import qualified RIO.Text as T
import System.Process.Typed
---
-- | Attempt to retrieve info about a given `Set` of packages from the AUR.
aurLookup :: Manager -> NonEmpty PkgName -> IO (Maybe (Set PkgName, Set Buildable))
aurLookup m names = runMaybeT $ do
infos <- MaybeT . fmap hush . info m $ foldr (\(PkgName pn) acc -> pn : acc) [] names
badsgoods <- lift $ traverseConcurrently Par' (buildable m) infos
let (bads, goods) = partitionEithers badsgoods
goodNames = S.fromList $ goods ^.. each . to bName
pure (S.fromList bads <> S.fromList (NEL.toList names) S.\\ goodNames, S.fromList goods)
-- | Yield fully realized `Package`s from the AUR.
aurRepo :: IO Repository
aurRepo = do
tv <- newTVarIO mempty
-- TODO Use `data-or` here to offer `Or (NESet PkgName) (NESet Package)`?
-- Yes that sounds like a good idea :)
let f :: Settings -> NonEmpty PkgName -> IO (Maybe (Set PkgName, Set Package))
f ss ps = do
--- Retrieve cached Packages ---
cache <- readTVarIO tv
let (uncached, cached) = fmapEither (\p -> note p $ M.lookup p cache) $ toList ps
--- Lookup uncached Packages ---
case NEL.nonEmpty uncached of
Nothing -> pure $ Just (S.empty, S.fromList cached)
Just uncached' -> runMaybeT $ do
(bads, goods) <- MaybeT $ aurLookup (managerOf ss) uncached'
let !pkgs = map FromAUR $ S.toList goods
--- Update Cache ---
let m = M.fromList $ map (pname &&& id) pkgs
liftIO . atomically $ modifyTVar' tv (<> m)
pure (bads, S.fromList $ cached <> pkgs)
pure $ Repository tv f
buildable :: Manager -> AurInfo -> IO (Either PkgName Buildable)
buildable m ai = do
let !bse = PkgName $ pkgBaseOf ai
mver = hush . versioning $ aurVersionOf ai
mpb <- getPkgbuild m bse -- Using the package base ensures split packages work correctly.
case (,) <$> mpb <*> mver of
Nothing -> pure . Left . PkgName $ aurNameOf ai
Just (pb, ver) -> pure $ Right Buildable
{ bName = PkgName $ aurNameOf ai
, bVersion = ver
, bBase = bse
, bProvides = providesOf ai ^. to listToMaybe . non (aurNameOf ai) . to (Provides . PkgName)
-- TODO This is a potentially naughty mapMaybe, since deps that fail to
-- parse will be silently dropped. Unfortunately there isn't much to be
-- done - `aurLookup` and `aurRepo` which call this function only report
-- existence errors (i.e. "this package couldn't be found at all").
, bDeps = mapMaybe parseDep $ dependsOf ai ++ makeDepsOf ai
, bPkgbuild = pb
, bIsExplicit = False }
----------------
-- AUR PKGBUILDS
----------------
aurLink :: FilePath
aurLink = "https://aur.archlinux.org"
-- | A package's home URL on the AUR.
pkgUrl :: PkgName -> Text
pkgUrl (PkgName pkg) = T.pack $ aurLink </> "packages" </> T.unpack pkg
-------------------
-- SOURCES FROM GIT
-------------------
-- | Attempt to clone a package source from the AUR.
clone :: Buildable -> IO (Maybe FilePath)
clone b = do
ec <- runProcess . setStderr closed . setStdout closed
$ proc "git" [ "clone", "--depth", "1", url ]
case ec of
ExitFailure _ -> pure Nothing
ExitSuccess -> do
pwd <- getCurrentDirectory
pure . Just $ pwd </> pathy
where
pathy :: FilePath
pathy = T.unpack . pnName $ bBase b
url :: FilePath
url = aurLink </> pathy <.> "git"
------------
-- RPC CALLS
------------
sortAurInfo :: Maybe BuildSwitch -> [AurInfo] -> [AurInfo]
sortAurInfo bs ai = L.sortBy compare' ai
where compare' = case bs of
Just SortAlphabetically -> compare `on` aurNameOf
_ -> \x y -> compare (aurVotesOf y) (aurVotesOf x)
-- | Frontend to the `aur` library. For @-As@.
aurSearch :: Text -> RIO Env [AurInfo]
aurSearch regex = do
ss <- asks settings
res <- liftMaybeM (Failure connectFailure_1) . fmap hush . liftIO $ search (managerOf ss) regex
pure $ sortAurInfo (bool Nothing (Just SortAlphabetically) $ switch ss SortAlphabetically) res
-- | Frontend to the `aur` library. For @-Ai@.
aurInfo :: NonEmpty PkgName -> RIO Env [AurInfo]
aurInfo pkgs = do
logDebug $ "AUR: Looking up " <> display (length pkgs) <> " packages..."
m <- asks (managerOf . settings)
sortAurInfo (Just SortAlphabetically) . fold
<$> traverseConcurrently Par' (work m) (groupsOf 50 $ NEL.toList pkgs)
where
work :: Manager -> [PkgName] -> RIO Env [AurInfo]
work m ps = liftIO (info m $ map pnName ps) >>= \case
Left (NotFound _) -> throwM (Failure connectFailure_1)
Left BadJSON -> throwM (Failure miscAURFailure_3)
Left (OtherAurError e) -> do
let !resp = display $ decodeUtf8Lenient e
logDebug $ "Failed! Server said: " <> resp
throwM (Failure miscAURFailure_1)
Right res -> pure res
|
aurapm/aura
|
aura/lib/Aura/Packages/AUR.hs
|
gpl-3.0
| 6,061 | 0 | 24 | 1,550 | 1,700 | 872 | 828 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Network.Google.Gmail
-- 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)
--
-- The Gmail API lets you view and manage Gmail mailbox data like threads,
-- messages, and labels.
--
-- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference>
module Network.Google.Gmail
(
-- * Service Configuration
gmailService
-- * OAuth Scopes
, gmailSettingsBasicScope
, gmailAddonsCurrentMessageActionScope
, gmailAddonsCurrentMessageMetadataScope
, mailGoogleComScope
, gmailModifyScope
, gmailMetadataScope
, gmailLabelsScope
, gmailSettingsSharingScope
, gmailSendScope
, gmailAddonsCurrentMessageReadOnlyScope
, gmailAddonsCurrentActionComposeScope
, gmailInsertScope
, gmailComposeScope
, gmailReadOnlyScope
-- * API Declaration
, GmailAPI
-- * Resources
-- ** gmail.users.drafts.create
, module Network.Google.Resource.Gmail.Users.Drafts.Create
-- ** gmail.users.drafts.delete
, module Network.Google.Resource.Gmail.Users.Drafts.Delete
-- ** gmail.users.drafts.get
, module Network.Google.Resource.Gmail.Users.Drafts.Get
-- ** gmail.users.drafts.list
, module Network.Google.Resource.Gmail.Users.Drafts.List
-- ** gmail.users.drafts.send
, module Network.Google.Resource.Gmail.Users.Drafts.Send
-- ** gmail.users.drafts.update
, module Network.Google.Resource.Gmail.Users.Drafts.Update
-- ** gmail.users.getProfile
, module Network.Google.Resource.Gmail.Users.GetProFile
-- ** gmail.users.history.list
, module Network.Google.Resource.Gmail.Users.History.List
-- ** gmail.users.labels.create
, module Network.Google.Resource.Gmail.Users.Labels.Create
-- ** gmail.users.labels.delete
, module Network.Google.Resource.Gmail.Users.Labels.Delete
-- ** gmail.users.labels.get
, module Network.Google.Resource.Gmail.Users.Labels.Get
-- ** gmail.users.labels.list
, module Network.Google.Resource.Gmail.Users.Labels.List
-- ** gmail.users.labels.patch
, module Network.Google.Resource.Gmail.Users.Labels.Patch
-- ** gmail.users.labels.update
, module Network.Google.Resource.Gmail.Users.Labels.Update
-- ** gmail.users.messages.attachments.get
, module Network.Google.Resource.Gmail.Users.Messages.Attachments.Get
-- ** gmail.users.messages.batchDelete
, module Network.Google.Resource.Gmail.Users.Messages.BatchDelete
-- ** gmail.users.messages.batchModify
, module Network.Google.Resource.Gmail.Users.Messages.BatchModify
-- ** gmail.users.messages.delete
, module Network.Google.Resource.Gmail.Users.Messages.Delete
-- ** gmail.users.messages.get
, module Network.Google.Resource.Gmail.Users.Messages.Get
-- ** gmail.users.messages.import
, module Network.Google.Resource.Gmail.Users.Messages.Import
-- ** gmail.users.messages.insert
, module Network.Google.Resource.Gmail.Users.Messages.Insert
-- ** gmail.users.messages.list
, module Network.Google.Resource.Gmail.Users.Messages.List
-- ** gmail.users.messages.modify
, module Network.Google.Resource.Gmail.Users.Messages.Modify
-- ** gmail.users.messages.send
, module Network.Google.Resource.Gmail.Users.Messages.Send
-- ** gmail.users.messages.trash
, module Network.Google.Resource.Gmail.Users.Messages.Trash
-- ** gmail.users.messages.untrash
, module Network.Google.Resource.Gmail.Users.Messages.Untrash
-- ** gmail.users.settings.delegates.create
, module Network.Google.Resource.Gmail.Users.Settings.Delegates.Create
-- ** gmail.users.settings.delegates.delete
, module Network.Google.Resource.Gmail.Users.Settings.Delegates.Delete
-- ** gmail.users.settings.delegates.get
, module Network.Google.Resource.Gmail.Users.Settings.Delegates.Get
-- ** gmail.users.settings.delegates.list
, module Network.Google.Resource.Gmail.Users.Settings.Delegates.List
-- ** gmail.users.settings.filters.create
, module Network.Google.Resource.Gmail.Users.Settings.Filters.Create
-- ** gmail.users.settings.filters.delete
, module Network.Google.Resource.Gmail.Users.Settings.Filters.Delete
-- ** gmail.users.settings.filters.get
, module Network.Google.Resource.Gmail.Users.Settings.Filters.Get
-- ** gmail.users.settings.filters.list
, module Network.Google.Resource.Gmail.Users.Settings.Filters.List
-- ** gmail.users.settings.forwardingAddresses.create
, module Network.Google.Resource.Gmail.Users.Settings.ForwardingAddresses.Create
-- ** gmail.users.settings.forwardingAddresses.delete
, module Network.Google.Resource.Gmail.Users.Settings.ForwardingAddresses.Delete
-- ** gmail.users.settings.forwardingAddresses.get
, module Network.Google.Resource.Gmail.Users.Settings.ForwardingAddresses.Get
-- ** gmail.users.settings.forwardingAddresses.list
, module Network.Google.Resource.Gmail.Users.Settings.ForwardingAddresses.List
-- ** gmail.users.settings.getAutoForwarding
, module Network.Google.Resource.Gmail.Users.Settings.GetAutoForwarding
-- ** gmail.users.settings.getImap
, module Network.Google.Resource.Gmail.Users.Settings.GetImap
-- ** gmail.users.settings.getLanguage
, module Network.Google.Resource.Gmail.Users.Settings.GetLanguage
-- ** gmail.users.settings.getPop
, module Network.Google.Resource.Gmail.Users.Settings.GetPop
-- ** gmail.users.settings.getVacation
, module Network.Google.Resource.Gmail.Users.Settings.GetVacation
-- ** gmail.users.settings.sendAs.create
, module Network.Google.Resource.Gmail.Users.Settings.SendAs.Create
-- ** gmail.users.settings.sendAs.delete
, module Network.Google.Resource.Gmail.Users.Settings.SendAs.Delete
-- ** gmail.users.settings.sendAs.get
, module Network.Google.Resource.Gmail.Users.Settings.SendAs.Get
-- ** gmail.users.settings.sendAs.list
, module Network.Google.Resource.Gmail.Users.Settings.SendAs.List
-- ** gmail.users.settings.sendAs.patch
, module Network.Google.Resource.Gmail.Users.Settings.SendAs.Patch
-- ** gmail.users.settings.sendAs.smimeInfo.delete
, module Network.Google.Resource.Gmail.Users.Settings.SendAs.SmimeInfo.Delete
-- ** gmail.users.settings.sendAs.smimeInfo.get
, module Network.Google.Resource.Gmail.Users.Settings.SendAs.SmimeInfo.Get
-- ** gmail.users.settings.sendAs.smimeInfo.insert
, module Network.Google.Resource.Gmail.Users.Settings.SendAs.SmimeInfo.Insert
-- ** gmail.users.settings.sendAs.smimeInfo.list
, module Network.Google.Resource.Gmail.Users.Settings.SendAs.SmimeInfo.List
-- ** gmail.users.settings.sendAs.smimeInfo.setDefault
, module Network.Google.Resource.Gmail.Users.Settings.SendAs.SmimeInfo.SetDefault
-- ** gmail.users.settings.sendAs.update
, module Network.Google.Resource.Gmail.Users.Settings.SendAs.Update
-- ** gmail.users.settings.sendAs.verify
, module Network.Google.Resource.Gmail.Users.Settings.SendAs.Verify
-- ** gmail.users.settings.updateAutoForwarding
, module Network.Google.Resource.Gmail.Users.Settings.UpdateAutoForwarding
-- ** gmail.users.settings.updateImap
, module Network.Google.Resource.Gmail.Users.Settings.UpdateImap
-- ** gmail.users.settings.updateLanguage
, module Network.Google.Resource.Gmail.Users.Settings.UpdateLanguage
-- ** gmail.users.settings.updatePop
, module Network.Google.Resource.Gmail.Users.Settings.UpdatePop
-- ** gmail.users.settings.updateVacation
, module Network.Google.Resource.Gmail.Users.Settings.UpdateVacation
-- ** gmail.users.stop
, module Network.Google.Resource.Gmail.Users.Stop
-- ** gmail.users.threads.delete
, module Network.Google.Resource.Gmail.Users.Threads.Delete
-- ** gmail.users.threads.get
, module Network.Google.Resource.Gmail.Users.Threads.Get
-- ** gmail.users.threads.list
, module Network.Google.Resource.Gmail.Users.Threads.List
-- ** gmail.users.threads.modify
, module Network.Google.Resource.Gmail.Users.Threads.Modify
-- ** gmail.users.threads.trash
, module Network.Google.Resource.Gmail.Users.Threads.Trash
-- ** gmail.users.threads.untrash
, module Network.Google.Resource.Gmail.Users.Threads.Untrash
-- ** gmail.users.watch
, module Network.Google.Resource.Gmail.Users.Watch
-- * Types
-- ** BatchDeleteMessagesRequest
, BatchDeleteMessagesRequest
, batchDeleteMessagesRequest
, bdmrIds
-- ** FilterCriteriaSizeComparison
, FilterCriteriaSizeComparison (..)
-- ** Delegate
, Delegate
, delegate
, dVerificationStatus
, dDelegateEmail
-- ** UsersMessagesGetFormat
, UsersMessagesGetFormat (..)
-- ** ModifyThreadRequest
, ModifyThreadRequest
, modifyThreadRequest
, mtrRemoveLabelIds
, mtrAddLabelIds
-- ** ListFiltersResponse
, ListFiltersResponse
, listFiltersResponse
, lfrFilter
-- ** ModifyMessageRequest
, ModifyMessageRequest
, modifyMessageRequest
, mmrRemoveLabelIds
, mmrAddLabelIds
-- ** ListForwardingAddressesResponse
, ListForwardingAddressesResponse
, listForwardingAddressesResponse
, lfarForwardingAddresses
-- ** PopSettings
, PopSettings
, popSettings
, psAccessWindow
, psDisPosition
-- ** PopSettingsAccessWindow
, PopSettingsAccessWindow (..)
-- ** History
, History
, history
, hLabelsRemoved
, hMessagesDeleted
, hMessagesAdded
, hLabelsAdded
, hId
, hMessages
-- ** ListDelegatesResponse
, ListDelegatesResponse
, listDelegatesResponse
, ldrDelegates
-- ** ForwardingAddressVerificationStatus
, ForwardingAddressVerificationStatus (..)
-- ** LabelColor
, LabelColor
, labelColor
, lcBackgRoundColor
, lcTextColor
-- ** FilterCriteria
, FilterCriteria
, filterCriteria
, fcSizeComparison
, fcSubject
, fcSize
, fcExcludeChats
, fcTo
, fcFrom
, fcQuery
, fcNegatedQuery
, fcHasAttachment
-- ** ProFile
, ProFile
, proFile
, pfMessagesTotal
, pfThreadsTotal
, pfHistoryId
, pfEmailAddress
-- ** AutoForwardingDisPosition
, AutoForwardingDisPosition (..)
-- ** MessagePartHeader
, MessagePartHeader
, messagePartHeader
, mphValue
, mphName
-- ** UsersHistoryListHistoryTypes
, UsersHistoryListHistoryTypes (..)
-- ** SendAsVerificationStatus
, SendAsVerificationStatus (..)
-- ** ListHistoryResponse
, ListHistoryResponse
, listHistoryResponse
, lhrNextPageToken
, lhrHistory
, lhrHistoryId
-- ** SendAs
, SendAs
, sendAs
, saSignature
, saReplyToAddress
, saTreatAsAlias
, saSendAsEmail
, saDisplayName
, saVerificationStatus
, saSmtpMsa
, saIsPrimary
, saIsDefault
-- ** LabelType
, LabelType (..)
-- ** UsersDraftsGetFormat
, UsersDraftsGetFormat (..)
-- ** UsersMessagesImportInternalDateSource
, UsersMessagesImportInternalDateSource (..)
-- ** LabelMessageListVisibility
, LabelMessageListVisibility (..)
-- ** ListThreadsResponse
, ListThreadsResponse
, listThreadsResponse
, ltrNextPageToken
, ltrResultSizeEstimate
, ltrThreads
-- ** MessagePart
, MessagePart
, messagePart
, mpParts
, mpBody
, mpMimeType
, mpHeaders
, mpPartId
, mpFilename
-- ** HistoryLabelAdded
, HistoryLabelAdded
, historyLabelAdded
, hlaLabelIds
, hlaMessage
-- ** ListLabelsResponse
, ListLabelsResponse
, listLabelsResponse
, llrLabels
-- ** VacationSettings
, VacationSettings
, vacationSettings
, vsEnableAutoReply
, vsResponseBodyPlainText
, vsRestrictToDomain
, vsStartTime
, vsResponseBodyHTML
, vsRestrictToContacts
, vsResponseSubject
, vsEndTime
-- ** LabelLabelListVisibility
, LabelLabelListVisibility (..)
-- ** HistoryMessageDeleted
, HistoryMessageDeleted
, historyMessageDeleted
, hmdMessage
-- ** MessagePartBody
, MessagePartBody
, messagePartBody
, mpbSize
, mpbData
, mpbAttachmentId
-- ** AutoForwarding
, AutoForwarding
, autoForwarding
, afEnabled
, afDisPosition
, afEmailAddress
-- ** ListDraftsResponse
, ListDraftsResponse
, listDraftsResponse
, ldrNextPageToken
, ldrResultSizeEstimate
, ldrDrafts
-- ** ListSendAsResponse
, ListSendAsResponse
, listSendAsResponse
, lsarSendAs
-- ** LanguageSettings
, LanguageSettings
, languageSettings
, lsDisplayLanguage
-- ** WatchResponse
, WatchResponse
, watchResponse
, wrExpiration
, wrHistoryId
-- ** Xgafv
, Xgafv (..)
-- ** DelegateVerificationStatus
, DelegateVerificationStatus (..)
-- ** UsersThreadsGetFormat
, UsersThreadsGetFormat (..)
-- ** BatchModifyMessagesRequest
, BatchModifyMessagesRequest
, batchModifyMessagesRequest
, bmmrIds
, bmmrRemoveLabelIds
, bmmrAddLabelIds
-- ** Draft
, Draft
, draft
, dId
, dMessage
-- ** SmtpMsa
, SmtpMsa
, smtpMsa
, smSecurityMode
, smUsername
, smPassword
, smHost
, smPort
-- ** ForwardingAddress
, ForwardingAddress
, forwardingAddress
, faForwardingEmail
, faVerificationStatus
-- ** PopSettingsDisPosition
, PopSettingsDisPosition (..)
-- ** Filter
, Filter
, filter'
, fAction
, fId
, fCriteria
-- ** WatchRequest
, WatchRequest
, watchRequest
, wrLabelFilterAction
, wrTopicName
, wrLabelIds
-- ** WatchRequestLabelFilterAction
, WatchRequestLabelFilterAction (..)
-- ** ImapSettings
, ImapSettings
, imapSettings
, isEnabled
, isExpungeBehavior
, isAutoExpunge
, isMaxFolderSize
-- ** ImapSettingsExpungeBehavior
, ImapSettingsExpungeBehavior (..)
-- ** ListSmimeInfoResponse
, ListSmimeInfoResponse
, listSmimeInfoResponse
, lsirSmimeInfo
-- ** SmtpMsaSecurityMode
, SmtpMsaSecurityMode (..)
-- ** Message
, Message
, message
, mRaw
, mSnippet
, mSizeEstimate
, mPayload
, mHistoryId
, mId
, mLabelIds
, mThreadId
, mInternalDate
-- ** UsersMessagesInsertInternalDateSource
, UsersMessagesInsertInternalDateSource (..)
-- ** HistoryLabelRemoved
, HistoryLabelRemoved
, historyLabelRemoved
, hlrLabelIds
, hlrMessage
-- ** Thread
, Thread
, thread
, tSnippet
, tHistoryId
, tId
, tMessages
-- ** FilterAction
, FilterAction
, filterAction
, faForward
, faRemoveLabelIds
, faAddLabelIds
-- ** Label
, Label
, label
, lThreadsUnread
, lMessageListVisibility
, lMessagesTotal
, lColor
, lMessagesUnread
, lName
, lThreadsTotal
, lLabelListVisibility
, lId
, lType
-- ** SmimeInfo
, SmimeInfo
, smimeInfo
, siPem
, siExpiration
, siEncryptedKeyPassword
, siId
, siPkcs12
, siIssuerCn
, siIsDefault
-- ** ListMessagesResponse
, ListMessagesResponse
, listMessagesResponse
, lmrNextPageToken
, lmrResultSizeEstimate
, lmrMessages
-- ** HistoryMessageAdded
, HistoryMessageAdded
, historyMessageAdded
, hmaMessage
) where
import Network.Google.Prelude
import Network.Google.Gmail.Types
import Network.Google.Resource.Gmail.Users.Drafts.Create
import Network.Google.Resource.Gmail.Users.Drafts.Delete
import Network.Google.Resource.Gmail.Users.Drafts.Get
import Network.Google.Resource.Gmail.Users.Drafts.List
import Network.Google.Resource.Gmail.Users.Drafts.Send
import Network.Google.Resource.Gmail.Users.Drafts.Update
import Network.Google.Resource.Gmail.Users.GetProFile
import Network.Google.Resource.Gmail.Users.History.List
import Network.Google.Resource.Gmail.Users.Labels.Create
import Network.Google.Resource.Gmail.Users.Labels.Delete
import Network.Google.Resource.Gmail.Users.Labels.Get
import Network.Google.Resource.Gmail.Users.Labels.List
import Network.Google.Resource.Gmail.Users.Labels.Patch
import Network.Google.Resource.Gmail.Users.Labels.Update
import Network.Google.Resource.Gmail.Users.Messages.Attachments.Get
import Network.Google.Resource.Gmail.Users.Messages.BatchDelete
import Network.Google.Resource.Gmail.Users.Messages.BatchModify
import Network.Google.Resource.Gmail.Users.Messages.Delete
import Network.Google.Resource.Gmail.Users.Messages.Get
import Network.Google.Resource.Gmail.Users.Messages.Import
import Network.Google.Resource.Gmail.Users.Messages.Insert
import Network.Google.Resource.Gmail.Users.Messages.List
import Network.Google.Resource.Gmail.Users.Messages.Modify
import Network.Google.Resource.Gmail.Users.Messages.Send
import Network.Google.Resource.Gmail.Users.Messages.Trash
import Network.Google.Resource.Gmail.Users.Messages.Untrash
import Network.Google.Resource.Gmail.Users.Settings.Delegates.Create
import Network.Google.Resource.Gmail.Users.Settings.Delegates.Delete
import Network.Google.Resource.Gmail.Users.Settings.Delegates.Get
import Network.Google.Resource.Gmail.Users.Settings.Delegates.List
import Network.Google.Resource.Gmail.Users.Settings.Filters.Create
import Network.Google.Resource.Gmail.Users.Settings.Filters.Delete
import Network.Google.Resource.Gmail.Users.Settings.Filters.Get
import Network.Google.Resource.Gmail.Users.Settings.Filters.List
import Network.Google.Resource.Gmail.Users.Settings.ForwardingAddresses.Create
import Network.Google.Resource.Gmail.Users.Settings.ForwardingAddresses.Delete
import Network.Google.Resource.Gmail.Users.Settings.ForwardingAddresses.Get
import Network.Google.Resource.Gmail.Users.Settings.ForwardingAddresses.List
import Network.Google.Resource.Gmail.Users.Settings.GetAutoForwarding
import Network.Google.Resource.Gmail.Users.Settings.GetImap
import Network.Google.Resource.Gmail.Users.Settings.GetLanguage
import Network.Google.Resource.Gmail.Users.Settings.GetPop
import Network.Google.Resource.Gmail.Users.Settings.GetVacation
import Network.Google.Resource.Gmail.Users.Settings.SendAs.Create
import Network.Google.Resource.Gmail.Users.Settings.SendAs.Delete
import Network.Google.Resource.Gmail.Users.Settings.SendAs.Get
import Network.Google.Resource.Gmail.Users.Settings.SendAs.List
import Network.Google.Resource.Gmail.Users.Settings.SendAs.Patch
import Network.Google.Resource.Gmail.Users.Settings.SendAs.SmimeInfo.Delete
import Network.Google.Resource.Gmail.Users.Settings.SendAs.SmimeInfo.Get
import Network.Google.Resource.Gmail.Users.Settings.SendAs.SmimeInfo.Insert
import Network.Google.Resource.Gmail.Users.Settings.SendAs.SmimeInfo.List
import Network.Google.Resource.Gmail.Users.Settings.SendAs.SmimeInfo.SetDefault
import Network.Google.Resource.Gmail.Users.Settings.SendAs.Update
import Network.Google.Resource.Gmail.Users.Settings.SendAs.Verify
import Network.Google.Resource.Gmail.Users.Settings.UpdateAutoForwarding
import Network.Google.Resource.Gmail.Users.Settings.UpdateImap
import Network.Google.Resource.Gmail.Users.Settings.UpdateLanguage
import Network.Google.Resource.Gmail.Users.Settings.UpdatePop
import Network.Google.Resource.Gmail.Users.Settings.UpdateVacation
import Network.Google.Resource.Gmail.Users.Stop
import Network.Google.Resource.Gmail.Users.Threads.Delete
import Network.Google.Resource.Gmail.Users.Threads.Get
import Network.Google.Resource.Gmail.Users.Threads.List
import Network.Google.Resource.Gmail.Users.Threads.Modify
import Network.Google.Resource.Gmail.Users.Threads.Trash
import Network.Google.Resource.Gmail.Users.Threads.Untrash
import Network.Google.Resource.Gmail.Users.Watch
{- $resources
TODO
-}
-- | Represents the entirety of the methods and resources available for the Gmail API service.
type GmailAPI =
UsersHistoryListResource :<|>
UsersSettingsDelegatesListResource
:<|> UsersSettingsDelegatesGetResource
:<|> UsersSettingsDelegatesCreateResource
:<|> UsersSettingsDelegatesDeleteResource
:<|> UsersSettingsForwardingAddressesListResource
:<|> UsersSettingsForwardingAddressesGetResource
:<|> UsersSettingsForwardingAddressesCreateResource
:<|> UsersSettingsForwardingAddressesDeleteResource
:<|> UsersSettingsFiltersListResource
:<|> UsersSettingsFiltersGetResource
:<|> UsersSettingsFiltersCreateResource
:<|> UsersSettingsFiltersDeleteResource
:<|> UsersSettingsSendAsSmimeInfoInsertResource
:<|> UsersSettingsSendAsSmimeInfoListResource
:<|> UsersSettingsSendAsSmimeInfoGetResource
:<|> UsersSettingsSendAsSmimeInfoSetDefaultResource
:<|> UsersSettingsSendAsSmimeInfoDeleteResource
:<|> UsersSettingsSendAsVerifyResource
:<|> UsersSettingsSendAsListResource
:<|> UsersSettingsSendAsPatchResource
:<|> UsersSettingsSendAsGetResource
:<|> UsersSettingsSendAsCreateResource
:<|> UsersSettingsSendAsDeleteResource
:<|> UsersSettingsSendAsUpdateResource
:<|> UsersSettingsUpdateImapResource
:<|> UsersSettingsGetLanguageResource
:<|> UsersSettingsGetVacationResource
:<|> UsersSettingsGetAutoForwardingResource
:<|> UsersSettingsUpdateAutoForwardingResource
:<|> UsersSettingsUpdateVacationResource
:<|> UsersSettingsUpdateLanguageResource
:<|> UsersSettingsGetImapResource
:<|> UsersSettingsUpdatePopResource
:<|> UsersSettingsGetPopResource
:<|> UsersDraftsListResource
:<|> UsersDraftsGetResource
:<|> UsersDraftsCreateResource
:<|> UsersDraftsSendResource
:<|> UsersDraftsDeleteResource
:<|> UsersDraftsUpdateResource
:<|> UsersLabelsListResource
:<|> UsersLabelsPatchResource
:<|> UsersLabelsGetResource
:<|> UsersLabelsCreateResource
:<|> UsersLabelsDeleteResource
:<|> UsersLabelsUpdateResource
:<|> UsersThreadsListResource
:<|> UsersThreadsGetResource
:<|> UsersThreadsTrashResource
:<|> UsersThreadsUntrashResource
:<|> UsersThreadsModifyResource
:<|> UsersThreadsDeleteResource
:<|> UsersMessagesAttachmentsGetResource
:<|> UsersMessagesInsertResource
:<|> UsersMessagesListResource
:<|> UsersMessagesGetResource
:<|> UsersMessagesTrashResource
:<|> UsersMessagesSendResource
:<|> UsersMessagesBatchModifyResource
:<|> UsersMessagesUntrashResource
:<|> UsersMessagesImportResource
:<|> UsersMessagesBatchDeleteResource
:<|> UsersMessagesModifyResource
:<|> UsersMessagesDeleteResource
:<|> UsersGetProFileResource
:<|> UsersStopResource
:<|> UsersWatchResource
|
brendanhay/gogol
|
gogol-gmail/gen/Network/Google/Gmail.hs
|
mpl-2.0
| 23,441 | 0 | 71 | 4,079 | 2,808 | 2,108 | 700 | 479 | 0 |
module Example.Eg02 (eg02) where
import Graphics.Radian
import ExampleUtils
eg02 :: IO Html
eg02 = do
d <- readJSON "vic2012aoo.json" #+
M.fromList [ ("doy", [label.="Day of year", units.="d"])
, ("month", [label.="Month"])
, ("tmp", [label.="Temperature", units.="°C"])
, ("prc", [label.="Rainfall", units.="mm/day"]) ]
let plot = Plot [l1, l2] # [strokeWidth.=1.5]
l1 = Lines (d#^"date"#^"doy") (d#^"tmp") # [stroke.="red"]
l2 = Lines (d#^"date"#^"doy") (d#^"prc") # [stroke.="blue"]
source = exampleSource "Eg02.hs"
return [shamlet|
<h3>
Example 2 (basic plot; JSON data access)
^{plot}
^{source}
|]
|
openbrainsrc/hRadian
|
examples/Example/Eg02.hs
|
mpl-2.0
| 712 | 10 | 14 | 183 | 271 | 146 | 125 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DFAReporting.Cities.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a list of cities, possibly filtered.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ Campaign Manager 360 API Reference> for @dfareporting.cities.list@.
module Network.Google.Resource.DFAReporting.Cities.List
(
-- * REST Resource
CitiesListResource
-- * Creating a Request
, citiesList
, CitiesList
-- * Request Lenses
, citXgafv
, citUploadProtocol
, citRegionDartIds
, citAccessToken
, citUploadType
, citProFileId
, citNamePrefix
, citCountryDartIds
, citDartIds
, citCallback
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.cities.list@ method which the
-- 'CitiesList' request conforms to.
type CitiesListResource =
"dfareporting" :>
"v3.5" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"cities" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParams "regionDartIds" (Textual Int64) :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "namePrefix" Text :>
QueryParams "countryDartIds" (Textual Int64) :>
QueryParams "dartIds" (Textual Int64) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] CitiesListResponse
-- | Retrieves a list of cities, possibly filtered.
--
-- /See:/ 'citiesList' smart constructor.
data CitiesList =
CitiesList'
{ _citXgafv :: !(Maybe Xgafv)
, _citUploadProtocol :: !(Maybe Text)
, _citRegionDartIds :: !(Maybe [Textual Int64])
, _citAccessToken :: !(Maybe Text)
, _citUploadType :: !(Maybe Text)
, _citProFileId :: !(Textual Int64)
, _citNamePrefix :: !(Maybe Text)
, _citCountryDartIds :: !(Maybe [Textual Int64])
, _citDartIds :: !(Maybe [Textual Int64])
, _citCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CitiesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'citXgafv'
--
-- * 'citUploadProtocol'
--
-- * 'citRegionDartIds'
--
-- * 'citAccessToken'
--
-- * 'citUploadType'
--
-- * 'citProFileId'
--
-- * 'citNamePrefix'
--
-- * 'citCountryDartIds'
--
-- * 'citDartIds'
--
-- * 'citCallback'
citiesList
:: Int64 -- ^ 'citProFileId'
-> CitiesList
citiesList pCitProFileId_ =
CitiesList'
{ _citXgafv = Nothing
, _citUploadProtocol = Nothing
, _citRegionDartIds = Nothing
, _citAccessToken = Nothing
, _citUploadType = Nothing
, _citProFileId = _Coerce # pCitProFileId_
, _citNamePrefix = Nothing
, _citCountryDartIds = Nothing
, _citDartIds = Nothing
, _citCallback = Nothing
}
-- | V1 error format.
citXgafv :: Lens' CitiesList (Maybe Xgafv)
citXgafv = lens _citXgafv (\ s a -> s{_citXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
citUploadProtocol :: Lens' CitiesList (Maybe Text)
citUploadProtocol
= lens _citUploadProtocol
(\ s a -> s{_citUploadProtocol = a})
-- | Select only cities from these regions.
citRegionDartIds :: Lens' CitiesList [Int64]
citRegionDartIds
= lens _citRegionDartIds
(\ s a -> s{_citRegionDartIds = a})
. _Default
. _Coerce
-- | OAuth access token.
citAccessToken :: Lens' CitiesList (Maybe Text)
citAccessToken
= lens _citAccessToken
(\ s a -> s{_citAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
citUploadType :: Lens' CitiesList (Maybe Text)
citUploadType
= lens _citUploadType
(\ s a -> s{_citUploadType = a})
-- | User profile ID associated with this request.
citProFileId :: Lens' CitiesList Int64
citProFileId
= lens _citProFileId (\ s a -> s{_citProFileId = a})
. _Coerce
-- | Select only cities with names starting with this prefix.
citNamePrefix :: Lens' CitiesList (Maybe Text)
citNamePrefix
= lens _citNamePrefix
(\ s a -> s{_citNamePrefix = a})
-- | Select only cities from these countries.
citCountryDartIds :: Lens' CitiesList [Int64]
citCountryDartIds
= lens _citCountryDartIds
(\ s a -> s{_citCountryDartIds = a})
. _Default
. _Coerce
-- | Select only cities with these DART IDs.
citDartIds :: Lens' CitiesList [Int64]
citDartIds
= lens _citDartIds (\ s a -> s{_citDartIds = a}) .
_Default
. _Coerce
-- | JSONP
citCallback :: Lens' CitiesList (Maybe Text)
citCallback
= lens _citCallback (\ s a -> s{_citCallback = a})
instance GoogleRequest CitiesList where
type Rs CitiesList = CitiesListResponse
type Scopes CitiesList =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient CitiesList'{..}
= go _citProFileId _citXgafv _citUploadProtocol
(_citRegionDartIds ^. _Default)
_citAccessToken
_citUploadType
_citNamePrefix
(_citCountryDartIds ^. _Default)
(_citDartIds ^. _Default)
_citCallback
(Just AltJSON)
dFAReportingService
where go
= buildClient (Proxy :: Proxy CitiesListResource)
mempty
|
brendanhay/gogol
|
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/Cities/List.hs
|
mpl-2.0
| 6,297 | 0 | 22 | 1,625 | 1,118 | 640 | 478 | 154 | 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.Gmail.Users.Threads.List
-- 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)
--
-- Lists the threads in the user\'s mailbox.
--
-- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.threads.list@.
module Network.Google.Resource.Gmail.Users.Threads.List
(
-- * REST Resource
UsersThreadsListResource
-- * Creating a Request
, usersThreadsList
, UsersThreadsList
-- * Request Lenses
, utlXgafv
, utlUploadProtocol
, utlAccessToken
, utlUploadType
, utlQ
, utlUserId
, utlIncludeSpamTrash
, utlLabelIds
, utlPageToken
, utlMaxResults
, utlCallback
) where
import Network.Google.Gmail.Types
import Network.Google.Prelude
-- | A resource alias for @gmail.users.threads.list@ method which the
-- 'UsersThreadsList' request conforms to.
type UsersThreadsListResource =
"gmail" :>
"v1" :>
"users" :>
Capture "userId" Text :>
"threads" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "q" Text :>
QueryParam "includeSpamTrash" Bool :>
QueryParams "labelIds" Text :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListThreadsResponse
-- | Lists the threads in the user\'s mailbox.
--
-- /See:/ 'usersThreadsList' smart constructor.
data UsersThreadsList =
UsersThreadsList'
{ _utlXgafv :: !(Maybe Xgafv)
, _utlUploadProtocol :: !(Maybe Text)
, _utlAccessToken :: !(Maybe Text)
, _utlUploadType :: !(Maybe Text)
, _utlQ :: !(Maybe Text)
, _utlUserId :: !Text
, _utlIncludeSpamTrash :: !Bool
, _utlLabelIds :: !(Maybe [Text])
, _utlPageToken :: !(Maybe Text)
, _utlMaxResults :: !(Textual Word32)
, _utlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UsersThreadsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'utlXgafv'
--
-- * 'utlUploadProtocol'
--
-- * 'utlAccessToken'
--
-- * 'utlUploadType'
--
-- * 'utlQ'
--
-- * 'utlUserId'
--
-- * 'utlIncludeSpamTrash'
--
-- * 'utlLabelIds'
--
-- * 'utlPageToken'
--
-- * 'utlMaxResults'
--
-- * 'utlCallback'
usersThreadsList
:: UsersThreadsList
usersThreadsList =
UsersThreadsList'
{ _utlXgafv = Nothing
, _utlUploadProtocol = Nothing
, _utlAccessToken = Nothing
, _utlUploadType = Nothing
, _utlQ = Nothing
, _utlUserId = "me"
, _utlIncludeSpamTrash = False
, _utlLabelIds = Nothing
, _utlPageToken = Nothing
, _utlMaxResults = 100
, _utlCallback = Nothing
}
-- | V1 error format.
utlXgafv :: Lens' UsersThreadsList (Maybe Xgafv)
utlXgafv = lens _utlXgafv (\ s a -> s{_utlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
utlUploadProtocol :: Lens' UsersThreadsList (Maybe Text)
utlUploadProtocol
= lens _utlUploadProtocol
(\ s a -> s{_utlUploadProtocol = a})
-- | OAuth access token.
utlAccessToken :: Lens' UsersThreadsList (Maybe Text)
utlAccessToken
= lens _utlAccessToken
(\ s a -> s{_utlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
utlUploadType :: Lens' UsersThreadsList (Maybe Text)
utlUploadType
= lens _utlUploadType
(\ s a -> s{_utlUploadType = a})
-- | Only return threads matching the specified query. Supports the same
-- query format as the Gmail search box. For example,
-- \`\"from:someuser\'example.com rfc822msgid: is:unread\"\`. Parameter
-- cannot be used when accessing the api using the gmail.metadata scope.
utlQ :: Lens' UsersThreadsList (Maybe Text)
utlQ = lens _utlQ (\ s a -> s{_utlQ = a})
-- | The user\'s email address. The special value \`me\` can be used to
-- indicate the authenticated user.
utlUserId :: Lens' UsersThreadsList Text
utlUserId
= lens _utlUserId (\ s a -> s{_utlUserId = a})
-- | Include threads from \`SPAM\` and \`TRASH\` in the results.
utlIncludeSpamTrash :: Lens' UsersThreadsList Bool
utlIncludeSpamTrash
= lens _utlIncludeSpamTrash
(\ s a -> s{_utlIncludeSpamTrash = a})
-- | Only return threads with labels that match all of the specified label
-- IDs.
utlLabelIds :: Lens' UsersThreadsList [Text]
utlLabelIds
= lens _utlLabelIds (\ s a -> s{_utlLabelIds = a}) .
_Default
. _Coerce
-- | Page token to retrieve a specific page of results in the list.
utlPageToken :: Lens' UsersThreadsList (Maybe Text)
utlPageToken
= lens _utlPageToken (\ s a -> s{_utlPageToken = a})
-- | Maximum number of threads to return. This field defaults to 100. The
-- maximum allowed value for this field is 500.
utlMaxResults :: Lens' UsersThreadsList Word32
utlMaxResults
= lens _utlMaxResults
(\ s a -> s{_utlMaxResults = a})
. _Coerce
-- | JSONP
utlCallback :: Lens' UsersThreadsList (Maybe Text)
utlCallback
= lens _utlCallback (\ s a -> s{_utlCallback = a})
instance GoogleRequest UsersThreadsList where
type Rs UsersThreadsList = ListThreadsResponse
type Scopes UsersThreadsList =
'["https://mail.google.com/",
"https://www.googleapis.com/auth/gmail.metadata",
"https://www.googleapis.com/auth/gmail.modify",
"https://www.googleapis.com/auth/gmail.readonly"]
requestClient UsersThreadsList'{..}
= go _utlUserId _utlXgafv _utlUploadProtocol
_utlAccessToken
_utlUploadType
_utlQ
(Just _utlIncludeSpamTrash)
(_utlLabelIds ^. _Default)
_utlPageToken
(Just _utlMaxResults)
_utlCallback
(Just AltJSON)
gmailService
where go
= buildClient
(Proxy :: Proxy UsersThreadsListResource)
mempty
|
brendanhay/gogol
|
gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Threads/List.hs
|
mpl-2.0
| 7,020 | 0 | 23 | 1,811 | 1,133 | 656 | 477 | 161 | 1 |
import Tree
instance Functor Tree where
fmap f EmptyTree = EmptyTree
fmap f (Node a left right) = Node (f a) (fmap f left) (fmap f right)
{-
data Either a b = Left a | Right b
instance Functor (Either a) where
fmap f (Right x) = Right (f x)
fmap f (Left x) = Left x
-}
{-
instance Functor (Map k) where
fmap f (Map k v) = Map k (f v)
-}
|
alexliew/learn_you_a_haskell
|
code/functors.hs
|
unlicense
| 350 | 0 | 8 | 89 | 73 | 37 | 36 | 4 | 0 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QAbstractSpinBox_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:26
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QAbstractSpinBox_h where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QAbstractSpinBox
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QAbstractSpinBox ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractSpinBox_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QAbstractSpinBox_unSetUserMethod" qtc_QAbstractSpinBox_unSetUserMethod :: Ptr (TQAbstractSpinBox a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QAbstractSpinBoxSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractSpinBox_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QAbstractSpinBox ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractSpinBox_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QAbstractSpinBoxSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractSpinBox_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QAbstractSpinBox ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractSpinBox_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QAbstractSpinBoxSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractSpinBox_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QAbstractSpinBox ()) (QAbstractSpinBox x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QAbstractSpinBox setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QAbstractSpinBox_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractSpinBox_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractSpinBox_setUserMethod" qtc_QAbstractSpinBox_setUserMethod :: Ptr (TQAbstractSpinBox a) -> CInt -> Ptr (Ptr (TQAbstractSpinBox x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QAbstractSpinBox :: (Ptr (TQAbstractSpinBox x0) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractSpinBox x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QAbstractSpinBox_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QAbstractSpinBoxSc a) (QAbstractSpinBox x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QAbstractSpinBox setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QAbstractSpinBox_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractSpinBox_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QAbstractSpinBox ()) (QAbstractSpinBox x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QAbstractSpinBox setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QAbstractSpinBox_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractSpinBox_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractSpinBox_setUserMethodVariant" qtc_QAbstractSpinBox_setUserMethodVariant :: Ptr (TQAbstractSpinBox a) -> CInt -> Ptr (Ptr (TQAbstractSpinBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QAbstractSpinBox :: (Ptr (TQAbstractSpinBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQAbstractSpinBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QAbstractSpinBox_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QAbstractSpinBoxSc a) (QAbstractSpinBox x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QAbstractSpinBox setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QAbstractSpinBox_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractSpinBox_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QAbstractSpinBox ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QAbstractSpinBox_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QAbstractSpinBox_unSetHandler" qtc_QAbstractSpinBox_unSetHandler :: Ptr (TQAbstractSpinBox a) -> CWString -> IO (CBool)
instance QunSetHandler (QAbstractSpinBoxSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QAbstractSpinBox_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QAbstractSpinBox ()) (QAbstractSpinBox x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractSpinBoxFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractSpinBox_setHandler1" qtc_QAbstractSpinBox_setHandler1 :: Ptr (TQAbstractSpinBox a) -> CWString -> Ptr (Ptr (TQAbstractSpinBox x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox1 :: (Ptr (TQAbstractSpinBox x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractSpinBox x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractSpinBoxSc a) (QAbstractSpinBox x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractSpinBoxFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QchangeEvent_h (QAbstractSpinBox ()) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_changeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_changeEvent" qtc_QAbstractSpinBox_changeEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent_h (QAbstractSpinBoxSc a) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_changeEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractSpinBox ()) (QAbstractSpinBox x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- qAbstractSpinBoxFromPtr x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractSpinBox_setHandler2" qtc_QAbstractSpinBox_setHandler2 :: Ptr (TQAbstractSpinBox a) -> CWString -> Ptr (Ptr (TQAbstractSpinBox x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox2 :: (Ptr (TQAbstractSpinBox x0) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractSpinBox x0) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractSpinBoxSc a) (QAbstractSpinBox x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- qAbstractSpinBoxFromPtr x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qclear_h (QAbstractSpinBox ()) (()) where
clear_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_clear cobj_x0
foreign import ccall "qtc_QAbstractSpinBox_clear" qtc_QAbstractSpinBox_clear :: Ptr (TQAbstractSpinBox a) -> IO ()
instance Qclear_h (QAbstractSpinBoxSc a) (()) where
clear_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_clear cobj_x0
instance QcloseEvent_h (QAbstractSpinBox ()) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_closeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_closeEvent" qtc_QAbstractSpinBox_closeEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent_h (QAbstractSpinBoxSc a) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_closeEvent cobj_x0 cobj_x1
instance QcontextMenuEvent_h (QAbstractSpinBox ()) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_contextMenuEvent" qtc_QAbstractSpinBox_contextMenuEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QAbstractSpinBoxSc a) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_contextMenuEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractSpinBox ()) (QAbstractSpinBox x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractSpinBoxFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractSpinBox_setHandler3" qtc_QAbstractSpinBox_setHandler3 :: Ptr (TQAbstractSpinBox a) -> CWString -> Ptr (Ptr (TQAbstractSpinBox x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox3 :: (Ptr (TQAbstractSpinBox x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQAbstractSpinBox x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractSpinBoxSc a) (QAbstractSpinBox x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractSpinBoxFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QAbstractSpinBox ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_event cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_event" qtc_QAbstractSpinBox_event :: Ptr (TQAbstractSpinBox a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QAbstractSpinBoxSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_event cobj_x0 cobj_x1
instance QfocusInEvent_h (QAbstractSpinBox ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_focusInEvent" qtc_QAbstractSpinBox_focusInEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QAbstractSpinBoxSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QAbstractSpinBox ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_focusOutEvent" qtc_QAbstractSpinBox_focusOutEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QAbstractSpinBoxSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_focusOutEvent cobj_x0 cobj_x1
instance QhideEvent_h (QAbstractSpinBox ()) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_hideEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_hideEvent" qtc_QAbstractSpinBox_hideEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent_h (QAbstractSpinBoxSc a) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_hideEvent cobj_x0 cobj_x1
instance QkeyPressEvent_h (QAbstractSpinBox ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_keyPressEvent" qtc_QAbstractSpinBox_keyPressEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QAbstractSpinBoxSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_keyPressEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QAbstractSpinBox ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_keyReleaseEvent" qtc_QAbstractSpinBox_keyReleaseEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QAbstractSpinBoxSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_keyReleaseEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractSpinBox ()) (QAbstractSpinBox x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qAbstractSpinBoxFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractSpinBox_setHandler4" qtc_QAbstractSpinBox_setHandler4 :: Ptr (TQAbstractSpinBox a) -> CWString -> Ptr (Ptr (TQAbstractSpinBox x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox4 :: (Ptr (TQAbstractSpinBox x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQAbstractSpinBox x0) -> IO (Ptr (TQSize t0))))
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractSpinBoxSc a) (QAbstractSpinBox x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qAbstractSpinBoxFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqminimumSizeHint_h (QAbstractSpinBox ()) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_minimumSizeHint cobj_x0
foreign import ccall "qtc_QAbstractSpinBox_minimumSizeHint" qtc_QAbstractSpinBox_minimumSizeHint :: Ptr (TQAbstractSpinBox a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint_h (QAbstractSpinBoxSc a) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_minimumSizeHint cobj_x0
instance QminimumSizeHint_h (QAbstractSpinBox ()) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QAbstractSpinBox_minimumSizeHint_qth" qtc_QAbstractSpinBox_minimumSizeHint_qth :: Ptr (TQAbstractSpinBox a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint_h (QAbstractSpinBoxSc a) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QmouseMoveEvent_h (QAbstractSpinBox ()) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_mouseMoveEvent" qtc_QAbstractSpinBox_mouseMoveEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QAbstractSpinBoxSc a) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QAbstractSpinBox ()) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_mousePressEvent" qtc_QAbstractSpinBox_mousePressEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QAbstractSpinBoxSc a) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QAbstractSpinBox ()) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_mouseReleaseEvent" qtc_QAbstractSpinBox_mouseReleaseEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QAbstractSpinBoxSc a) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_mouseReleaseEvent cobj_x0 cobj_x1
instance QpaintEvent_h (QAbstractSpinBox ()) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_paintEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_paintEvent" qtc_QAbstractSpinBox_paintEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent_h (QAbstractSpinBoxSc a) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_paintEvent cobj_x0 cobj_x1
instance QresizeEvent_h (QAbstractSpinBox ()) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_resizeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_resizeEvent" qtc_QAbstractSpinBox_resizeEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent_h (QAbstractSpinBoxSc a) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_resizeEvent cobj_x0 cobj_x1
instance QshowEvent_h (QAbstractSpinBox ()) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_showEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_showEvent" qtc_QAbstractSpinBox_showEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent_h (QAbstractSpinBoxSc a) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_showEvent cobj_x0 cobj_x1
instance QqsizeHint_h (QAbstractSpinBox ()) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_sizeHint cobj_x0
foreign import ccall "qtc_QAbstractSpinBox_sizeHint" qtc_QAbstractSpinBox_sizeHint :: Ptr (TQAbstractSpinBox a) -> IO (Ptr (TQSize ()))
instance QqsizeHint_h (QAbstractSpinBoxSc a) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_sizeHint cobj_x0
instance QsizeHint_h (QAbstractSpinBox ()) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QAbstractSpinBox_sizeHint_qth" qtc_QAbstractSpinBox_sizeHint_qth :: Ptr (TQAbstractSpinBox a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint_h (QAbstractSpinBoxSc a) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QsetHandler (QAbstractSpinBox ()) (QAbstractSpinBox x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractSpinBoxFromPtr x0
let x1int = fromCInt x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractSpinBox_setHandler5" qtc_QAbstractSpinBox_setHandler5 :: Ptr (TQAbstractSpinBox a) -> CWString -> Ptr (Ptr (TQAbstractSpinBox x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox5 :: (Ptr (TQAbstractSpinBox x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQAbstractSpinBox x0) -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractSpinBoxSc a) (QAbstractSpinBox x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractSpinBoxFromPtr x0
let x1int = fromCInt x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QstepBy_h (QAbstractSpinBox ()) ((Int)) where
stepBy_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_stepBy cobj_x0 (toCInt x1)
foreign import ccall "qtc_QAbstractSpinBox_stepBy" qtc_QAbstractSpinBox_stepBy :: Ptr (TQAbstractSpinBox a) -> CInt -> IO ()
instance QstepBy_h (QAbstractSpinBoxSc a) ((Int)) where
stepBy_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_stepBy cobj_x0 (toCInt x1)
instance QwheelEvent_h (QAbstractSpinBox ()) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_wheelEvent" qtc_QAbstractSpinBox_wheelEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent_h (QAbstractSpinBoxSc a) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_wheelEvent cobj_x0 cobj_x1
instance QactionEvent_h (QAbstractSpinBox ()) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_actionEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_actionEvent" qtc_QAbstractSpinBox_actionEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent_h (QAbstractSpinBoxSc a) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_actionEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractSpinBox ()) (QAbstractSpinBox x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qAbstractSpinBoxFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractSpinBox_setHandler6" qtc_QAbstractSpinBox_setHandler6 :: Ptr (TQAbstractSpinBox a) -> CWString -> Ptr (Ptr (TQAbstractSpinBox x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox6 :: (Ptr (TQAbstractSpinBox x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQAbstractSpinBox x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractSpinBoxSc a) (QAbstractSpinBox x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qAbstractSpinBoxFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdevType_h (QAbstractSpinBox ()) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_devType cobj_x0
foreign import ccall "qtc_QAbstractSpinBox_devType" qtc_QAbstractSpinBox_devType :: Ptr (TQAbstractSpinBox a) -> IO CInt
instance QdevType_h (QAbstractSpinBoxSc a) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_devType cobj_x0
instance QdragEnterEvent_h (QAbstractSpinBox ()) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_dragEnterEvent" qtc_QAbstractSpinBox_dragEnterEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent_h (QAbstractSpinBoxSc a) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QAbstractSpinBox ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_dragLeaveEvent" qtc_QAbstractSpinBox_dragLeaveEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent_h (QAbstractSpinBoxSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QAbstractSpinBox ()) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_dragMoveEvent" qtc_QAbstractSpinBox_dragMoveEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent_h (QAbstractSpinBoxSc a) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QAbstractSpinBox ()) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_dropEvent" qtc_QAbstractSpinBox_dropEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent_h (QAbstractSpinBoxSc a) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_dropEvent cobj_x0 cobj_x1
instance QenterEvent_h (QAbstractSpinBox ()) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_enterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_enterEvent" qtc_QAbstractSpinBox_enterEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent_h (QAbstractSpinBoxSc a) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_enterEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractSpinBox ()) (QAbstractSpinBox x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractSpinBoxFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractSpinBox_setHandler7" qtc_QAbstractSpinBox_setHandler7 :: Ptr (TQAbstractSpinBox a) -> CWString -> Ptr (Ptr (TQAbstractSpinBox x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox7 :: (Ptr (TQAbstractSpinBox x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQAbstractSpinBox x0) -> CInt -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractSpinBoxSc a) (QAbstractSpinBox x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractSpinBoxFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QheightForWidth_h (QAbstractSpinBox ()) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_heightForWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QAbstractSpinBox_heightForWidth" qtc_QAbstractSpinBox_heightForWidth :: Ptr (TQAbstractSpinBox a) -> CInt -> IO CInt
instance QheightForWidth_h (QAbstractSpinBoxSc a) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_heightForWidth cobj_x0 (toCInt x1)
instance QsetHandler (QAbstractSpinBox ()) (QAbstractSpinBox x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qAbstractSpinBoxFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractSpinBox_setHandler8" qtc_QAbstractSpinBox_setHandler8 :: Ptr (TQAbstractSpinBox a) -> CWString -> Ptr (Ptr (TQAbstractSpinBox x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox8 :: (Ptr (TQAbstractSpinBox x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQAbstractSpinBox x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractSpinBoxSc a) (QAbstractSpinBox x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qAbstractSpinBoxFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinputMethodQuery_h (QAbstractSpinBox ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QAbstractSpinBox_inputMethodQuery" qtc_QAbstractSpinBox_inputMethodQuery :: Ptr (TQAbstractSpinBox a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QAbstractSpinBoxSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QleaveEvent_h (QAbstractSpinBox ()) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_leaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_leaveEvent" qtc_QAbstractSpinBox_leaveEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent_h (QAbstractSpinBoxSc a) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_leaveEvent cobj_x0 cobj_x1
instance QmouseDoubleClickEvent_h (QAbstractSpinBox ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_mouseDoubleClickEvent" qtc_QAbstractSpinBox_mouseDoubleClickEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QAbstractSpinBoxSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmoveEvent_h (QAbstractSpinBox ()) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_moveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_moveEvent" qtc_QAbstractSpinBox_moveEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent_h (QAbstractSpinBoxSc a) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_moveEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractSpinBox ()) (QAbstractSpinBox x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qAbstractSpinBoxFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractSpinBox_setHandler9" qtc_QAbstractSpinBox_setHandler9 :: Ptr (TQAbstractSpinBox a) -> CWString -> Ptr (Ptr (TQAbstractSpinBox x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox9 :: (Ptr (TQAbstractSpinBox x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQAbstractSpinBox x0) -> IO (Ptr (TQPaintEngine t0))))
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractSpinBoxSc a) (QAbstractSpinBox x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qAbstractSpinBoxFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QpaintEngine_h (QAbstractSpinBox ()) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_paintEngine cobj_x0
foreign import ccall "qtc_QAbstractSpinBox_paintEngine" qtc_QAbstractSpinBox_paintEngine :: Ptr (TQAbstractSpinBox a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine_h (QAbstractSpinBoxSc a) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_paintEngine cobj_x0
instance QsetHandler (QAbstractSpinBox ()) (QAbstractSpinBox x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractSpinBoxFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractSpinBox_setHandler10" qtc_QAbstractSpinBox_setHandler10 :: Ptr (TQAbstractSpinBox a) -> CWString -> Ptr (Ptr (TQAbstractSpinBox x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox10 :: (Ptr (TQAbstractSpinBox x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQAbstractSpinBox x0) -> CBool -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractSpinBoxSc a) (QAbstractSpinBox x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractSpinBoxFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetVisible_h (QAbstractSpinBox ()) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QAbstractSpinBox_setVisible" qtc_QAbstractSpinBox_setVisible :: Ptr (TQAbstractSpinBox a) -> CBool -> IO ()
instance QsetVisible_h (QAbstractSpinBoxSc a) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractSpinBox_setVisible cobj_x0 (toCBool x1)
instance QtabletEvent_h (QAbstractSpinBox ()) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_tabletEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractSpinBox_tabletEvent" qtc_QAbstractSpinBox_tabletEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent_h (QAbstractSpinBoxSc a) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractSpinBox_tabletEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractSpinBox ()) (QAbstractSpinBox x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractSpinBoxFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractSpinBox_setHandler11" qtc_QAbstractSpinBox_setHandler11 :: Ptr (TQAbstractSpinBox a) -> CWString -> Ptr (Ptr (TQAbstractSpinBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox11 :: (Ptr (TQAbstractSpinBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQAbstractSpinBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QAbstractSpinBox11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractSpinBoxSc a) (QAbstractSpinBox x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractSpinBox11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractSpinBox11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractSpinBox_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractSpinBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractSpinBoxFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QAbstractSpinBox ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QAbstractSpinBox_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QAbstractSpinBox_eventFilter" qtc_QAbstractSpinBox_eventFilter :: Ptr (TQAbstractSpinBox a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QAbstractSpinBoxSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QAbstractSpinBox_eventFilter cobj_x0 cobj_x1 cobj_x2
|
keera-studios/hsQt
|
Qtc/Gui/QAbstractSpinBox_h.hs
|
bsd-2-clause
| 66,949 | 0 | 18 | 13,785 | 21,070 | 10,147 | 10,923 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Src.Modules.BTCInfo (getBTCInfo
, getBTCProfit
, getBTCPrice
) where
import Network.HTTP
import Data.Aeson ((.:), (.:?), eitherDecode, FromJSON)
import Data.Aeson.Types
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero)
import qualified Data.ByteString.Lazy.Char8 as BS
data BTCInfo = BTCInfo { getHigh :: String
, getLow :: String
, getAvg :: String
, getLast :: String
} deriving (Eq, Show)
instance FromJSON BTCInfo where
parseJSON (Object v) = BTCInfo <$>
(((v .: "return") >>= (.: "high")) >>= (.: "value")) <*>
(((v .: "return") >>= (.: "low")) >>= (.: "value")) <*>
(((v .: "return") >>= (.: "avg")) >>= (.: "value")) <*>
(((v .: "return") >>= (.: "last")) >>= (.: "value"))
parseJSON _ = mzero
getJSON :: String -> IO String
getJSON u = do
answer <- simpleHTTP $ getRequest u
case answer of
Left _ -> return "Got a connection error"
Right result -> return $ rspBody result
decodeBTCInfo :: BS.ByteString -> Either String (Maybe BTCInfo)
decodeBTCInfo = eitherDecode
getBTCInfo :: String -> IO String
getBTCInfo currency = do
rawJSON <- getJSON $ "http://data.mtgox.com/api/1/BTC" ++ currency ++ "/ticker"
json <- return $ BS.pack rawJSON
btc <- return $ decodeBTCInfo json
case btc of
Left err -> return err
Right btcjson -> case btcjson of
Just btcinfo -> return $ getLast btcinfo
Nothing -> return "Couldn't find it :("
getBTCProfit :: IO String
getBTCProfit = do
curPrice <- getBTCInfo "EUR"
let priceInFloat = read curPrice
let profit = floor $ (priceInFloat - 56) * 5.30397956 * 7.45
return $ show profit ++ " DKK"
getBTCPrice :: IO String
getBTCPrice = do
curPriceInEuro <- getBTCInfo "EUR"
curPriceInUSD <- getBTCInfo "USD"
curPriceInDKK <- getBTCInfo "DKK"
let priceInEuro = show $ floor $ read curPriceInEuro
let priceInUSD = show $ floor $ read curPriceInUSD
let priceInDKK = show $ floor $ read curPriceInDKK
return $ "1btc: " ++ priceInEuro ++ "euro, $" ++ priceInUSD ++ ", " ++ priceInDKK ++ "DKK"
|
Tehnix/HsIRCb
|
Src/Modules/BTCInfo.hs
|
bsd-2-clause
| 2,332 | 0 | 15 | 666 | 729 | 383 | 346 | 55 | 3 |
-- | Support for the Obnam backup tool <http://obnam.org/>
module Propellor.Property.Obnam where
import Propellor.Base
import qualified Propellor.Property.Apt as Apt
import qualified Propellor.Property.Cron as Cron
import qualified Propellor.Property.Gpg as Gpg
import Data.List
type ObnamParam = String
-- | An obnam repository can be used by multiple clients. Obnam uses
-- locking to allow only one client to write at a time. Since stale lock
-- files can prevent backups from happening, it's more robust, if you know
-- a repository has only one client, to force the lock before starting a
-- backup. Using OnlyClient allows propellor to do so when running obnam.
data NumClients = OnlyClient | MultipleClients
deriving (Eq)
-- | Installs a cron job that causes a given directory to be backed
-- up, by running obnam with some parameters.
--
-- If the directory does not exist, or exists but is completely empty,
-- this Property will immediately restore it from an existing backup.
--
-- So, this property can be used to deploy a directory of content
-- to a host, while also ensuring any changes made to it get backed up.
-- For example:
--
-- > & Obnam.backup "/srv/git" "33 3 * * *"
-- > [ "--repository=sftp://[email protected]/~/mygitrepos.obnam"
-- > ] Obnam.OnlyClient
-- > `requires` Ssh.keyImported SshRsa "root" (Context hostname)
--
-- How awesome is that?
--
-- Note that this property does not make obnam encrypt the backup
-- repository.
--
-- Since obnam uses a fair amount of system resources, only one obnam
-- backup job will be run at a time. Other jobs will wait their turns to
-- run.
backup :: FilePath -> Cron.Times -> [ObnamParam] -> NumClients -> Property DebianLike
backup dir crontimes params numclients =
backup' dir crontimes params numclients
`requires` restored dir params
-- | Like backup, but the specified gpg key id is used to encrypt
-- the repository.
--
-- The gpg secret key will be automatically imported
-- into root's keyring using Propellor.Property.Gpg.keyImported
backupEncrypted :: FilePath -> Cron.Times -> [ObnamParam] -> NumClients -> Gpg.GpgKeyId -> Property (HasInfo + DebianLike)
backupEncrypted dir crontimes params numclients keyid =
backup dir crontimes params' numclients
`requires` Gpg.keyImported keyid (User "root")
where
params' = ("--encrypt-with=" ++ Gpg.getGpgKeyId keyid) : params
-- | Does a backup, but does not automatically restore.
backup' :: FilePath -> Cron.Times -> [ObnamParam] -> NumClients -> Property DebianLike
backup' dir crontimes params numclients = cronjob `describe` desc
where
desc = dir ++ " backed up by obnam"
cronjob = Cron.niceJob ("obnam_backup" ++ dir) crontimes (User "root") "/" $
"flock " ++ shellEscape lockfile ++ " sh -c " ++ shellEscape cmdline
lockfile = "/var/lock/propellor-obnam.lock"
cmdline = unwords $ catMaybes
[ if numclients == OnlyClient
-- forcelock fails if repo does not exist yet
then Just $ forcelockcmd ++ " 2>/dev/null ;"
else Nothing
, Just backupcmd
, if any isKeepParam params
then Just $ "&& " ++ forgetcmd
else Nothing
]
forcelockcmd = unwords $
[ "obnam"
, "force-lock"
] ++ map shellEscape params
backupcmd = unwords $
[ "obnam"
, "backup"
, shellEscape dir
] ++ map shellEscape params
forgetcmd = unwords $
[ "obnam"
, "forget"
] ++ map shellEscape params
-- | Restores a directory from an obnam backup.
--
-- Only does anything if the directory does not exist, or exists,
-- but is completely empty.
--
-- The restore is performed atomically; restoring to a temp directory
-- and then moving it to the directory.
restored :: FilePath -> [ObnamParam] -> Property DebianLike
restored dir params = go `requires` installed
where
desc = dir ++ " restored by obnam"
go :: Property DebianLike
go = property desc $ ifM (liftIO needsRestore)
( do
warningMessage $ dir ++ " is empty/missing; restoring from backup ..."
liftIO restore
, noChange
)
needsRestore = null <$> catchDefaultIO [] (dirContents dir)
restore = withTmpDirIn (takeDirectory dir) "obnam-restore" $ \tmpdir -> do
ok <- boolSystem "obnam" $
[ Param "restore"
, Param "--to"
, Param tmpdir
] ++ map Param params
let restoreddir = tmpdir ++ "/" ++ dir
ifM (pure ok <&&> doesDirectoryExist restoreddir)
( do
void $ tryIO $ removeDirectory dir
renameDirectory restoreddir dir
return MadeChange
, return FailedChange
)
-- | Policy for backup generations to keep. For example, KeepDays 30 will
-- keep the latest backup for each day when a backup was made, and keep the
-- last 30 such backups. When multiple KeepPolicies are combined together,
-- backups meeting any policy are kept. See obnam's man page for details.
data KeepPolicy
= KeepHours Int
| KeepDays Int
| KeepWeeks Int
| KeepMonths Int
| KeepYears Int
-- | Constructs an ObnamParam that specifies which old backup generations
-- to keep. By default, all generations are kept. However, when this parameter
-- is passed to the `backup` or `backupEncrypted` properties, they will run
-- obnam forget to clean out generations not specified here.
keepParam :: [KeepPolicy] -> ObnamParam
keepParam ps = "--keep=" ++ intercalate "," (map go ps)
where
go (KeepHours n) = mk n 'h'
go (KeepDays n) = mk n 'd'
go (KeepWeeks n) = mk n 'w'
go (KeepMonths n) = mk n 'm'
go (KeepYears n) = mk n 'y'
mk n c = val n ++ [c]
isKeepParam :: ObnamParam -> Bool
isKeepParam p = "--keep=" `isPrefixOf` p
installed :: Property DebianLike
installed = Apt.installed ["obnam"]
|
ArchiveTeam/glowing-computing-machine
|
src/Propellor/Property/Obnam.hs
|
bsd-2-clause
| 5,555 | 50 | 16 | 1,046 | 1,089 | 590 | 499 | -1 | -1 |
{-# LANGUAGE LambdaCase, NamedFieldPuns, RecordWildCards, TupleSections #-}
module Mote.Search
( transesInScope
, WrappedType(..)
, SyntacticFunc
-- DEBUG
, search
, showTrans
, traversables
, monads
, applicatives
) where
import Mote.GhcUtil (discardConstraints, splitPredTys)
import Mote.ReadType
import Mote.Refine (tcRnExprTc)
import Mote.Types
import Mote.Util
import Search.Graph
import Search.Types
import Control.Applicative
import Control.Arrow (first)
import Control.Monad.Error
import Data.Hashable
import qualified Data.List as List
import Data.Maybe
import qualified Data.Set as Set
import GHC
import InstEnv (ClsInst (..))
import Name
import Outputable
import qualified PrelNames
import RdrName
import Type (dropForAlls, splitFunTys)
import TypeRep
import UniqSet (elementOfUniqSet)
import Unique (getKey, getUnique)
{-
search stRef = do
FileData {typecheckedModule} <- getFileDataErr stRef
ahi@(AugmentedHoleInfo {holeInfo}) <- getCurrentHoleErr stRef
suggs <- getAndMemoizeSuggestions stRef ahi
(sug, startTy) <- headErr suggs
let goalTy = holeType holeInfo
return $ go _ startTy goalTy
where
go transes startTy goalTy =
let (startFs, _) = extractFunctors startTy
(goalFs, _) = extractFunctors goalTy
in
programsOfLengthAtMost transes 6 startFs goalFs
-}
-- Write a type t as (A1 * ... * An)F where
-- each Ai and F are functors over a variable x
-- Checks if the type can be thought of as being of the form
-- forall a. F a -> G a
-- perhaps after partially applying.
-- (Of course F and G could be constant functors...but we don't
-- consider that case now. Maybe later, I guess there's no reason
-- not to.)
-- So, we are looking for types of the form
-- forall a. _ -> ... -> _ -> F a -> _ -> ... -> G a
-- It's really not unique since we can view
-- forall a. F1 a -> F2 a -> G a as
-- F1 -> G
-- F2 -> G
-- (F1 * F2) -> G
--
-- either :: (a -> c) -> (b -> c) -> Either a b -> c
-- (^a * ^b) -> 1 (partially apply the Either argument)
-- (^a * ^b) -> ^(a + b) (don't partially apply the either argument
--
-- TODO: SyntacticFuncs should be bundled with the variables that they're
-- universally quantified over
type SyntacticFunc = (TyCon, [WrappedType])
data TransInterpretation = TransInterpretation
{ numArguments :: Int
, functorArgumentPosition :: Int
, name :: Name
, from :: [SyntacticFunc]
, to :: [SyntacticFunc]
}
showTrans :: Trans SyntacticFunc -> M String
showTrans (Trans {from, to, name}) = do
from' <- lift $ mapM showPprM from
to' <- lift $ mapM showPprM to
return (show $ Trans {from=from', to=to', name})
data CoarseType
= SomeVar
| Type WrappedType
deriving (Eq, Ord)
-- Heuristically ignore distinctions between all TyVars
-- since comparing types gets complicated with TyVars
type CoarseFunc = (TyCon, [CoarseType])
squint :: SyntacticFunc -> CoarseFunc
squint (tc, ts) = (tc, map squintTy ts) where
squintTy (WrappedType t) = case t of
TyVarTy _v -> SomeVar
_ -> Type (WrappedType t)
-- Filtering occurs here
transes :: Set.Set CoarseFunc -> (Name, Type) -> [Trans SyntacticFunc]
transes funcs b = mapMaybe toTrans (transInterpretations b)
where
toTrans :: TransInterpretation -> Maybe (Trans SyntacticFunc)
toTrans (TransInterpretation {..}) =
if any (\f -> not $ Set.member (squint f) funcs) from ||
any (\f -> not $ Set.member (squint f) funcs) to
then Nothing
else if from == to
then Nothing
else if numArguments > 3 then Nothing
else Just (Trans {from, to, name=AnnotatedTerm name' (numArguments - 1)})
where
ident = occNameString $ occName name
name' =
if numArguments == 1
then Simple ident
else if functorArgumentPosition == numArguments - 1
then Compound (ident ++ " " ++ underscores (numArguments - 1))
else Simple ("(\\x -> " ++ ident ++ " " ++ underscores functorArgumentPosition ++ " x " ++ underscores (numArguments - functorArgumentPosition - 1) ++ ")")
underscores n = unwords $ replicate n "_"
traversables :: GhcMonad m => m [SyntacticFunc]
traversables = instancesOneParamFunctorClass PrelNames.traversableClassName
monads :: GhcMonad m => m [SyntacticFunc]
monads = instancesOneParamFunctorClass PrelNames.monadClassName
applicatives :: GhcMonad m => m [SyntacticFunc]
applicatives = instancesOneParamFunctorClass PrelNames.applicativeClassName
functors :: GhcMonad m => m [SyntacticFunc]
functors = instancesOneParamFunctorClass PrelNames.functorClassName
instancesOneParamFunctorClass name =
getInfo False name >>| \case
Just (_,_,insts,_) -> mapMaybe (extractUnapplied . head . is_tys) insts
Nothing -> []
extractUnapplied :: Type -> Maybe SyntacticFunc
extractUnapplied t = case t of
TyConApp tc kots -> Just (tc, map WrappedType kots)
-- TODO: In the future, this should extract applications of type
-- variables
_ -> Nothing
-- TODO: This type is only for debug purposes
data WrappedTyCon = WrappedTyCon TyCon String
instance Eq WrappedTyCon where
WrappedTyCon tc _ == WrappedTyCon tc' _ = tc == tc'
instance Ord WrappedTyCon where
compare (WrappedTyCon x _) (WrappedTyCon y _) = compare x y
instance Hashable WrappedTyCon where
hashWithSalt s (WrappedTyCon tc _) = s `hashWithSalt` getKey (getUnique tc)
instance Show WrappedTyCon where
show (WrappedTyCon _ s) = show s
-- search :: [String] -> [String] -> Int -> M [NaturalGraph (Int, Int)]
search src trg n = do
let renderSyntacticFunc (tc, args) = (getKey (getUnique tc), hash args)
-- let showSyntacticFunc = showSDoc fs . ppr
-- let renderSyntacticFunc sf@(tc, args) = WrappedTyCon tc (showSyntacticFunc sf)
from <- fmap catMaybes $ mapM (fmap (fmap renderSyntacticFunc . extractUnapplied . dropForAlls) . readType) src
to <- fmap catMaybes $ mapM (fmap (fmap renderSyntacticFunc . extractUnapplied . dropForAlls) . readType) trg
transes <- fmap (fmap (fmap renderSyntacticFunc)) transesInScope
return $ graphsOfSizeAtMost transes n from to
transesInScope :: M [Trans SyntacticFunc]
transesInScope = do
namedTys <- fmap catMaybes . mapM typeName =<< lift getNamesInScope
ts <- lift traversables
as <- lift applicatives
ms <- lift monads
funcSet <- lift $ fmap (Set.fromList . map squint) functors
let joins = map (\m -> Trans { from = [m,m], to = [m], name = AnnotatedTerm (Simple "join") 0 }) ms
traverses = liftA2 (\t f -> Trans { from = [t,f], to = [f,t], name = AnnotatedTerm (Simple "sequenceA") 0 }) ts as
return $
concatMap (transes funcSet) namedTys ++ traverses ++ joins
where
typeName n = do
hsc_env <- lift getSession
(_errs, mayTy) <- liftIO $
runTcInteractive hsc_env . discardConstraints . tcRnExprTc . noLoc . HsVar . Exact $ n
return $ fmap (n,) mayTy
-- TODO: Turn SyntacticFunc into SyntacticFuncScheme
-- so runErrorT can work
extractFunctors :: Type -> ([SyntacticFunc], WrappedType)
extractFunctors t = case t of
TyVarTy _v -> ([], WrappedType t)
FunTy _ _ -> ([], WrappedType t)
ForAllTy _v t -> extractFunctors t
LitTy _ -> ([], WrappedType t)
AppTy t _t' -> ([], WrappedType t) -- TODO
TyConApp tc kots -> case splitLast kots of
Nothing -> ([], WrappedType t)
Just (args, arg) -> first ((tc, map WrappedType args) :) (extractFunctors arg)
where
splitLast' :: [a] -> ([a], a)
splitLast' [x] = ([], x)
splitLast' (x:xs) = first (x:) (splitLast' xs)
splitLast' _ = error "Mote.Search.splitLast': Impossible"
splitLast :: [a] -> Maybe ([a], a)
splitLast [] = Nothing
splitLast xs = Just (splitLast' xs)
-- TODO: This is, of course, a first approximation since
-- we assume all TyCons other than (->) are covariant in all
-- arguments.
occursStrictlyPositively :: TyVar -> Type -> Bool
occursStrictlyPositively v = not . bad where
bad t = case t of
AppTy t' t'' -> bad t' || bad t''
TyConApp _tc kots -> any bad kots
FunTy t' t'' -> occurs t' || bad t''
ForAllTy _ t' -> bad t'
LitTy _tl -> False
TyVarTy _v -> False
occurs t = case t of
AppTy t' t'' -> occurs t' || occurs t''
TyConApp _tc kots -> any occurs kots
FunTy t' t'' -> occurs t' || occurs t''
ForAllTy _v t' -> occurs t'
LitTy _tl -> False
TyVarTy v' -> v' == v
transInterpretations :: (Name, Type) -> [TransInterpretation]
transInterpretations (n, t0) =
case targInner of
WrappedType (TyVarTy polyVar) ->
if polyVar `elementOfUniqSet` forbiddenVars
then []
else if any (not . occursStrictlyPositively polyVar) args
then []
else catMaybes $ zipWith interp [0..] args
where
interp :: Int -> Type -> Maybe TransInterpretation
interp i argty =
if inner == targInner
then Just trans
else Nothing
where
(sfs, inner) = extractFunctors argty
trans = TransInterpretation
{ numArguments = numArguments
, functorArgumentPosition = i
, name = n
, from = sfs
, to = sfsTarg
}
_ -> []
where
(_polyVars, t1) = splitForAllTys t0
(predTys, t) = splitPredTys t1
forbiddenVars = tyVarsOfTypes predTys
(args, targ) = splitFunTys t
(sfsTarg, targInner) = extractFunctors targ
numArguments = length args
newtype WrappedType = WrappedType Type
instance Eq WrappedType where
(==) (WrappedType t) (WrappedType t') = eqTy t t'
instance Ord WrappedType where
compare (WrappedType t) (WrappedType t') = compareTy t t'
instance Outputable WrappedType where
ppr (WrappedType t) = ppr t
pprPrec r (WrappedType t) = pprPrec r t
-- Hacky syntactic equality for Type so that it can be used as the functor
-- parameter in all the Search types
eqTy :: Type -> Type -> Bool
eqTy x y = case (x, y) of
(AppTy t1 t2, AppTy t1' t2') -> eqTy t1 t1' && eqTy t2 t2'
(TyConApp tc kots, TyConApp tc' kots') -> tc == tc' && and (zipWith eqTy kots kots')
(FunTy t1 t2, FunTy t1' t2') -> eqTy t1 t1' && eqTy t2 t2'
(ForAllTy v t, ForAllTy v' t') -> v == v' && eqTy t t'
(LitTy tl, LitTy tl') -> tl == tl'
(TyVarTy v, TyVarTy v') -> v == v'
_ -> False
instance Hashable WrappedType where
hashWithSalt s (WrappedType t) = hashTypeWithSalt s t
hashTypeWithSalt :: Int -> Type -> Int
hashTypeWithSalt s t = case t of
TyVarTy v -> s `hashWithSalt` (0::Int) `hashWithSalt` getKey (getUnique v)
AppTy t t' -> s `hashWithSalt` ((1::Int) `hashTypeWithSalt` t) `hashTypeWithSalt` t'
TyConApp tc kots -> List.foldl' hashTypeWithSalt (s `hashWithSalt` (2::Int) `hashWithSalt` getKey (getUnique tc)) kots
FunTy t t' -> s `hashWithSalt` (3::Int) `hashTypeWithSalt` t `hashTypeWithSalt` t'
ForAllTy v t -> s `hashWithSalt` ((4::Int) `hashWithSalt` getKey (getUnique v)) `hashTypeWithSalt` t
LitTy tl -> s `hashWithSalt` (5::Int) `hashTyLitWithSalt` tl
hashTyLitWithSalt s tl = case tl of
NumTyLit n -> s `hashWithSalt` n
StrTyLit fs -> s `hashWithSalt` getKey (getUnique fs)
compareTy :: Type -> Type -> Ordering
compareTy = \x y -> case compare (conOrd x) (conOrd y) of
EQ ->
case (x, y) of
(AppTy t1 t2, AppTy t1' t2') ->
lex [compareTy t1 t1', compareTy t2 t2']
(TyConApp tc kots, TyConApp tc' kots') ->
lex (compare tc tc' : zipWith compareTy kots kots')
(FunTy t1 t2, FunTy t1' t2') ->
lex [compareTy t1 t1', compareTy t2 t2']
(ForAllTy v t, ForAllTy v' t') ->
lex [compare v v', compareTy t t']
(LitTy tl, LitTy tl') -> compare tl tl'
(TyVarTy v, TyVarTy v') -> compare v v'
_ -> error "Mote.Search.compareTy: Impossible"
o -> o
where
conOrd :: Type -> Int
conOrd x = case x of
TyVarTy {} -> 0
AppTy {} -> 1
TyConApp {} -> 2
FunTy {} -> 3
ForAllTy {} -> 4
LitTy {} -> 5
lex :: [Ordering] -> Ordering
lex = (\case { [] -> EQ; (o:_) -> o } ) . dropWhile (== EQ)
{-
TyConApp IO
[TyConApp Free
[ TyConApp "[]" []
, TyConApp Maybe [TyConApp Int]
]
]
-}
|
imeckler/mote
|
Mote/Search.hs
|
bsd-3-clause
| 12,741 | 0 | 18 | 3,401 | 3,748 | 1,971 | 1,777 | 239 | 14 |
module Algebra.Structures.Semigroup
( Semigroup(..)
) where
import Data.List
class Semigroup a where
(<+>) :: a -> a -> a
infixl 6 <+>
|
Alex128/abstract-math
|
src/Algebra/Structures/Semigroup.hs
|
bsd-3-clause
| 152 | 0 | 8 | 39 | 50 | 30 | 20 | 6 | 0 |
-- |
-- Module : Crypto.PubKey.RSA
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : Good
--
module Crypto.PubKey.RSA
( Error(..)
, PublicKey(..)
, PrivateKey(..)
, Blinder(..)
-- * Generation function
, generateWith
, generate
, generateBlinder
) where
import Crypto.Internal.Imports
import Crypto.Random.Types
import Crypto.Number.ModArithmetic (inverse, inverseCoprimes)
import Crypto.Number.Generate (generateMax)
import Crypto.Number.Prime (generatePrime)
import Crypto.PubKey.RSA.Types
{-
-- some bad implementation will not serialize ASN.1 integer properly, leading
-- to negative modulus.
-- TODO : Find a better place for this
toPositive :: Integer -> Integer
toPositive int
| int < 0 = uintOfBytes $ bytesOfInt int
| otherwise = int
where uintOfBytes = foldl (\acc n -> (acc `shiftL` 8) + fromIntegral n) 0
bytesOfInt :: Integer -> [Word8]
bytesOfInt n = if testBit (head nints) 7 then nints else 0xff : nints
where nints = reverse $ plusOne $ reverse $ map complement $ bytesOfUInt (abs n)
plusOne [] = [1]
plusOne (x:xs) = if x == 0xff then 0 : plusOne xs else (x+1) : xs
bytesOfUInt x = reverse (list x)
where list i = if i <= 0xff then [fromIntegral i] else (fromIntegral i .&. 0xff) : list (i `shiftR` 8)
-}
-- | Generate a key pair given p and q.
--
-- p and q need to be distinct prime numbers.
--
-- e need to be coprime to phi=(p-1)*(q-1). If that's not the
-- case, the function will not return a key pair.
-- A small hamming weight results in better performance.
--
-- * e=0x10001 is a popular choice
--
-- * e=3 is popular as well, but proven to not be as secure for some cases.
--
generateWith :: (Integer, Integer) -- ^ chosen distinct primes p and q
-> Int -- ^ size in bytes
-> Integer -- ^ RSA public exponant 'e'
-> Maybe (PublicKey, PrivateKey)
generateWith (p,q) size e =
case inverse e phi of
Nothing -> Nothing
Just d -> Just (pub,priv d)
where n = p*q
phi = (p-1)*(q-1)
-- q and p should be *distinct* *prime* numbers, hence always coprime
qinv = inverseCoprimes q p
pub = PublicKey { public_size = size
, public_n = n
, public_e = e
}
priv d = PrivateKey { private_pub = pub
, private_d = d
, private_p = p
, private_q = q
, private_dP = d `mod` (p-1)
, private_dQ = d `mod` (q-1)
, private_qinv = qinv
}
-- | generate a pair of (private, public) key of size in bytes.
generate :: MonadRandom m
=> Int -- ^ size in bytes
-> Integer -- ^ RSA public exponant 'e'
-> m (PublicKey, PrivateKey)
generate size e = loop
where
loop = do -- loop until we find a valid key pair given e
pq <- generatePQ
case generateWith pq size e of
Nothing -> loop
Just pp -> return pp
generatePQ = do
p <- generatePrime (8 * (size `div` 2))
q <- generateQ p
return (p,q)
generateQ p = do
q <- generatePrime (8 * (size - (size `div` 2)))
if p == q then generateQ p else return q
-- | Generate a blinder to use with decryption and signing operation
--
-- the unique parameter apart from the random number generator is the
-- public key value N.
generateBlinder :: MonadRandom m
=> Integer -- ^ RSA public N parameter.
-> m Blinder
generateBlinder n =
(\r -> Blinder r (inverseCoprimes r n)) <$> generateMax n
|
tekul/cryptonite
|
Crypto/PubKey/RSA.hs
|
bsd-3-clause
| 3,927 | 0 | 16 | 1,323 | 623 | 363 | 260 | 57 | 3 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module PeerTrader.P2PPicks.Account where
import Data.ByteString (ByteString)
import Data.Maybe (listToMaybe)
import Database.Groundhog (PersistBackend, select, (==.))
import Database.Groundhog.TH
import P2PPicks
import PeerTrader.Types (UserLogin)
data P2PPicksAccount = P2PPicksAccount
{ p2ppicksOwner :: UserLogin
, p2ppicksUser :: ByteString
, p2ppicksPass :: ByteString
, subscriberId :: SubscriberID
, p2ppicksIsActive :: Bool
}
mkPersist defaultCodegenConfig [groundhog|
entity: P2PPicksAccount
constructors:
- name: P2PPicksAccount
fields:
- name: p2ppicksOwner
type: text
reference:
table: snap_auth_user
columns: [login]
uniques:
- name: oneuserperp2ppicks
fields: [p2ppicksOwner]
|]
getP2PPicksAccount :: PersistBackend m => UserLogin -> m (Maybe P2PPicksAccount)
getP2PPicksAccount n = do
accts <- select $ P2ppicksOwnerField ==. n
return (listToMaybe accts)
|
WraithM/peertrader-backend
|
src/PeerTrader/P2PPicks/Account.hs
|
bsd-3-clause
| 1,286 | 0 | 9 | 354 | 181 | 107 | 74 | 24 | 1 |
-- 参考:http://d.hatena.ne.jp/haxis_fx/20110726/1311657175
{-# LANGUAGE Arrows #-}
{-# LANGUAGE RankNTypes #-}
module
Main
where
import qualified Control.Arrow.Machine as P
import Control.Applicative ((<$>), (<*>))
import qualified Control.Category as Cat
import Control.Arrow
import Control.Monad.State
import Control.Monad
import Control.Monad.Trans
import Debug.Trace
counter =
proc ev ->
do
rec output <- returnA -< (\reset -> if reset then 0 else next) <$> ev
next <- P.dHold 0 -< (+1) <$> output
returnA -< output
main = print $ P.run counter (map b "ffffffffttfftt")
where b 't' = True
b 'f' = False
|
as-capabl/machinecell
|
example/counter/Main.hs
|
bsd-3-clause
| 671 | 1 | 15 | 147 | 187 | 108 | 79 | 21 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.