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 RecordWildCards, NamedFieldPuns #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DataKinds, PolyKinds #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE StandaloneDeriving, GeneralizedNewtypeDeriving #-} module DAGIO where import Data.IORef import Data.Vinyl import Data.Vinyl.Functor import VinylUtils import Control.Monad import VarArgs import Data.Default import DefaultM import Numeric.AD --import qualified Algebra.Additive as Additive import Prelude hiding (curry, uncurry) data Some f where Some :: f a -> Some f deriving instance Num a => Num (Identity a) data Node (output :: *) where Node :: (Num output) => { forward :: HList inputs -> Identity output , inputs :: Rec Node inputs , output :: IORef (Identity output) , updated :: IORef Bool , backwards :: HList inputs -> Identity output -> HList inputs , gradOutput :: IORef (Identity output) } -> Node output makeSource :: (Num a) => a -> IO (Node a) makeSource a = do output' <- newIORef (Identity a) updated' <- newIORef True gradOutput' <- newIORef 0 return Node { forward = \RNil -> Identity a , inputs = RNil , output = output' , updated = updated' , backwards = \RNil _ -> RNil , gradOutput = gradOutput' } instance (Num a, Default a) => DefaultM IO (Node a) where defM = makeSource def -- these types are somewhat less general than would be ideal makeUnary :: (Floating a) => (forall b. Floating b => b -> b) -> Node a -> IO (Node a) makeUnary f = makeNode (uncurry1 f, \inputs output -> (output * uncurry1 (diff f) inputs) :& RNil) makeBinary :: (Num a) => (forall b. Num b => b -> b -> b) -> Node a -> Node a -> IO (Node a) makeBinary f = makeNode (uncurry2 f, g) where g (x :& y :& RNil) output = dx :& dy :& RNil where [dx, dy] = map (output *) $ grad (\[a, b] -> f a b) [x, y] makeNode :: (Num output) => Curry Node inputs (IO (Node output)) c => (HList inputs -> Identity output, HList inputs -> Identity output -> HList inputs) -> c makeNode (f, b) = curry g where g inputs' = do ins <- rtraverse readNode inputs' output' <- newIORef (f ins) updated' <- newIORef True gradOutput' <- newIORef 0 return Node { forward = f , inputs = inputs' , output = output' , updated = updated' , backwards = b , gradOutput = gradOutput' } readNode :: Node output -> IO (Identity output) readNode Node{output} = readIORef output resetNode :: Node output -> IO () resetNode Node{..} = do todo <- readIORef updated when todo $ do rtraverse_ (\n -> Const <$> resetNode n) inputs writeIORef gradOutput 0 writeIORef updated False evalNode' :: Node output -> IO (Identity output) evalNode' node@Node{..} = do done <- readIORef updated unless done $ do ins <- rtraverse evalNode' inputs unless (rnull ins) $ writeIORef output (forward ins) writeIORef updated True readIORef output evalNode node = getIdentity <$> evalNode' node type Tape = [Some Node] evalNodeTape :: IORef Tape -> Node output -> IO (Identity output) evalNodeTape tape node@Node{..} = do done <- readIORef updated unless done $ do ins <- rtraverse (evalNodeTape tape) inputs unless (rnull ins) $ writeIORef output (forward ins) modifyIORef tape (Some node :) writeIORef updated True readIORef output backprop tape = traverse f tape where writeGrad Node{gradOutput} grad = modifyIORef gradOutput (grad +) f (Some Node{..}) = do ins <- rtraverse readNode inputs out <- readIORef gradOutput let gradInputs = backwards ins out liftA2_ writeGrad inputs gradInputs setLearningRate rate Node{..} = writeIORef gradOutput (Identity rate) learn (Some Node{..}) = do grad <- readIORef gradOutput modifyIORef output (grad+) testGrad = do param <- makeSource 0 loss <- makeUnary id param tape <- newIORef [] resetNode loss error <- evalNodeTape tape loss print error print =<< length <$> readIORef tape setLearningRate (-0.1) loss backprop =<< readIORef tape g <- readIORef $ gradOutput param print g {- pull-based backprop scrapped in favor of tape version resetGrad :: Node output -> IO () resetGrad Node{gradUpdated} = do todo <- readIORef gradUpdated when todo $ do children' <- readIORef children rtraverse_ (\n -> Const <$> resetGrad n) children' writeIORef gradOutput 0 writeIORef gradUpdated False backprop :: Some Node -> IO () backprop (Some Node{..}) = do done <- readIORef gradUpdated unless done $ do children' <- readIORef children traverse backprop children ins <- rtraverse readNode inputs out <- readIORef gradOutput let gradInputs = backwards ins out rZipWith inputs gradInputs _ -}
vladfi1/hs-misc
DAGIO.hs
mit
4,849
0
14
1,093
1,566
776
790
-1
-1
{-# LANGUAGE Safe #-} -- | Dead Instruction Elimination -- -- This optimization pass removes assignment statements that are -- unreferenced by all later statements. Unlike the LLVM version, -- this version also moves each instruction as closely as possible to -- the first instruction that references it. -- -- How it works: -- -- When a definition (i.e. assignment) is parsed, we pull it out of the basic -- block until another statement references it. Then, for each statement, we -- lookup all definitions it uses and check for them in our list of -- unreferenced definitions. If we find one, we push the definition back -- into the basic block, just before the statement that references it. -- -- For example: -- -- Line Input PassState Output Comment -- ---- -------- --------- ------ ------- -- 1 %1 = 5 [%1 = 5] %1 may be unreferrenced -- 2 %2 = 7 [%1 = 5, %2 = 7] %1 & %2 may be unreferrenced -- 3 %3 = %1 [%2 = 7, %3 = %1] [%1 = 5] %1 is used -- 4 ret %3 [%2 = 7] [%3 = %1, ret %3] %3 is used, %2 is dropped -- -- Limitations: -- -- 1. If there is a chain of unreferenced definitions, this pass will only -- remove the first link in the chain. -- 2. Code size: A redundant definition can be pulled into branch if both -- sides reference the definition for the first time. -- -- Hindsight: -- -- This pass is probably more useful in improving spacial locality and -- reducing register pressure than removing dead instructions. -- module Transforms.DeadInstructionElimination where import Data.List ( delete ) import Control.Monad.Trans.State ( modify , get , put , StateT ) import Control.Lens.Plated ( universe ) import LlvmData -- | A list of unreferenced instructions. -- The String is a variable name, and -- the Expr is the value assigned to it. type PassState = [(String, Expr)] -- | The name of this optimization pass name :: String name = "die" -- | The initial state emptyState :: PassState emptyState = [] -- | Optimize a list of top-level entities chunk :: Monad m => Module -> StateT PassState m Module chunk = mapM toplevelEntity -- | Optimize a top-level entity toplevelEntity :: Monad m => ToplevelEntity -> StateT PassState m ToplevelEntity toplevelEntity (Function nm ret args as blk) = do put [] blk' <- mapM stat blk return $ Function nm ret args as (concat blk') toplevelEntity x = return x -- | Optimize a statement stat :: Monad m => Statement -> StateT PassState m Block stat (Assignment nm e) = do xss <- mapM popStatement (vars e) pushStatement nm e return $ concat xss stat s@(Return _ e) = do xss <- mapM popStatement (vars e) return $ concat xss ++ [s] stat Flush = do st <- get put [] return $ map (uncurry Assignment) st stat x = return [x] -- | Given an expression, return the variable names it references vars :: Expr -> [String] vars = concatMap vars' . universe -- | Given an expresion, if it is variable, return its name. Otherwise, return an empty list vars' :: Expr -> [String] vars' (ExprVar nm) = [nm] vars' _ = [] -- | Push a statement that may be dead pushStatement :: Monad m => String -> Expr -> StateT PassState m () pushStatement nm x = modify ((nm, x) :) -- | Lookup a statement that is now known to be undead. Remove it from the list of dead instructions. popStatement :: Monad m => String -> StateT PassState m [Statement] popStatement nm = do xs <- get case lookup nm xs of Just x -> do modify (delete (nm,x)) return [Assignment nm x] Nothing -> return []
garious/hopt
Transforms/DeadInstructionElimination.hs
mit
5,104
0
15
2,329
672
361
311
54
2
{-# LANGUAGE ExistentialQuantification, RankNTypes, FlexibleContexts #-} module Commands.Parse where import Commands.Text.Parsec import Commands.Generic import Data.Functor -- | a 'Parse'able type. -- -- 'parse' is vaguely like @readPrec@ but: -- -- * the input is a natural-language string, not a Haskell-code string -- * if it had laws, it might be like @parse . prettyPrint = id@, not @read . show = id@. -- -- -- parses an unusable\/unstructured 'Char'acter list, into a usable\/structured syntax tree. -- -- class Parse r where parse :: ParsingContext -> Parser Char r -- | existentially quantified constructor, without some scoped-over function. -- -- i.e. the result of the parser must be ignored. data ParsingContext = forall a. ParsingContext (Parser Char a) -- | the 'Default' 'ParsingContext' uses 'eof'. -- -- i.e. lets a "hungry rule" (e.g. "Commands.Rule.Type") "be satiated" by (i.e. parse successfully) the end of file stops it (successfully), by default, when there's no ending context. instance Default ParsingContext where def = ParsingContext eof -- | -- contextual :: Parser Char a -> ParsingContext contextual = ParsingContext -- | 'manyUntil' ignores the result of the second argument. -- -- i.e. 'undefined' is ignored -- manyUntil :: Parser Char a -> ParsingContext -> Parser Char [a] manyUntil parser (ParsingContext context) = parser `manyTill` ((try . lookAhead) context <|> (undefined <$ eof))
sboosali/Haskell-DragonNaturallySpeaking
sources/Commands/Parse.hs
mit
1,437
0
10
231
198
117
81
14
1
module GHCJS.DOM.SVGRectElement ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/SVGRectElement.hs
mit
44
0
3
7
10
7
3
1
0
module Data.Strict.Maybe (Maybe(..), maybe, isJust, isNothing, fromJust, fromMaybe, listToMaybe, maybeToList, catMaybes, mapMaybe) where import Control.DeepSeq import Prelude hiding (Maybe(..), maybe) data Maybe a = Nothing | Just !a deriving (Eq, Show) instance (NFData a) => NFData (Maybe a) where rnf Nothing = () rnf (Just something) = rnf something instance Monad Maybe where (>>=) Nothing actionB = Nothing (>>=) (Just resultA) actionB = actionB resultA return a = Just a maybe :: b -> (a -> b) -> Maybe a -> b maybe default' _ Nothing = default' maybe _ function (Just a) = function a isJust :: Maybe a -> Bool isJust Nothing = False isJust (Just _) = True isNothing :: Maybe a -> Bool isNothing Nothing = True isNothing (Just _) = False fromJust :: Maybe a -> a fromJust Nothing = error $ "fromJust: Nothing" fromJust (Just a) = a fromMaybe :: a -> Maybe a -> a fromMaybe default' Nothing = default' fromMaybe _ (Just a) = a listToMaybe :: [a] -> Maybe a listToMaybe [] = Nothing listToMaybe (a:_) = Just a maybeToList :: Maybe a -> [a] maybeToList Nothing = [] maybeToList (Just a) = [a] catMaybes :: [Maybe a] -> [a] catMaybes [] = [] catMaybes (Nothing:rest) = catMaybes rest catMaybes (Just a:rest) = a : catMaybes rest mapMaybe :: (a -> Maybe b) -> [a] -> [b] mapMaybe function input = catMaybes $ map function input
IreneKnapp/legal-emulator
BackEnd/Data/Strict/Maybe.hs
mit
1,627
0
8
532
605
319
286
51
1
{-# LANGUAGE OverloadedStrings #-} module MAL.API.Delete ( deleteAnime , deleteManga ) where import Control.Monad ( void ) import Network.Wreq hiding ( delete ) import MAL.Credentials import MAL.Types delete :: String -> Credentials -> Id -> IO () delete ty creds n = do let url = "http://myanimelist.net/api/" ++ ty ++ "list/delete/" ++ show n ++ ".xml" opts' = opts creds void $ getWith opts' url deleteAnime :: Credentials -> Id -> IO () deleteAnime = delete "anime" deleteManga :: Credentials -> Id -> IO () deleteManga = delete "manga"
nyorem/skemmtun
src/MAL/API/Delete.hs
mit
586
0
13
134
181
95
86
19
1
/*Owner & Copyrights: Vance King Saxbe. A.*//* Copyright (c) <2014> Author Vance King Saxbe. A, and contributors Power Dominion Enterprise, Precieux Consulting and other contributors. Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting and GoldSax Technologies email @vsaxbe@yahoo.com. Development teams from Power Dominion Enterprise, Precieux Consulting. Project sponsored by GoldSax Foundation, GoldSax Group and executed by GoldSax Manager.*/module GoldSaxMachineModule4.FunctorsFoldables where import GoldSaxMachineModule4.MinimumPrice import qualified Data.Map as M import qualified Data.Tree as T modifyTravelGuidePrice :: Double -> [TravelGuide] -> [TravelGuide] modifyTravelGuidePrice m = map (\tg -> tg { price = m * price tg }) modifyTravelGuidePriceMap :: Double -> M.Map a TravelGuide -> M.Map a TravelGuide modifyTravelGuidePriceMap m = M.map (\tg -> tg { price = m * price tg }) modifyTravelGuidePriceTree :: Double -> T.Tree TravelGuide -> T.Tree TravelGuide modifyTravelGuidePriceTree m = fmap (\tg -> tg { price = m * price tg }) modifyTravelGuidePrice' :: Functor f => Double -> f TravelGuide -> f TravelGuide modifyTravelGuidePrice' m = fmap (\tg -> tg { price = m * price tg }) {- instance Functor ((->) r) where fmap f g = f . g -}/*email to provide support at vancekingsaxbe@powerdominionenterprise.com, businessaffairs@powerdominionenterprise.com, For donations please write to fundraising@powerdominionenterprise.com*/
VanceKingSaxbeA/GoldSaxMachineStore
GoldSaxMachineModule4/src/Chapter4/FunctorsFoldables.hs
mit
1,500
21
16
214
509
260
249
12
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-iotanalyticsaction.html module Stratosphere.ResourceProperties.IoTTopicRuleIotAnalyticsAction where import Stratosphere.ResourceImports -- | Full data type definition for IoTTopicRuleIotAnalyticsAction. See -- 'ioTTopicRuleIotAnalyticsAction' for a more convenient constructor. data IoTTopicRuleIotAnalyticsAction = IoTTopicRuleIotAnalyticsAction { _ioTTopicRuleIotAnalyticsActionChannelName :: Val Text , _ioTTopicRuleIotAnalyticsActionRoleArn :: Val Text } deriving (Show, Eq) instance ToJSON IoTTopicRuleIotAnalyticsAction where toJSON IoTTopicRuleIotAnalyticsAction{..} = object $ catMaybes [ (Just . ("ChannelName",) . toJSON) _ioTTopicRuleIotAnalyticsActionChannelName , (Just . ("RoleArn",) . toJSON) _ioTTopicRuleIotAnalyticsActionRoleArn ] -- | Constructor for 'IoTTopicRuleIotAnalyticsAction' containing required -- fields as arguments. ioTTopicRuleIotAnalyticsAction :: Val Text -- ^ 'ittriaaChannelName' -> Val Text -- ^ 'ittriaaRoleArn' -> IoTTopicRuleIotAnalyticsAction ioTTopicRuleIotAnalyticsAction channelNamearg roleArnarg = IoTTopicRuleIotAnalyticsAction { _ioTTopicRuleIotAnalyticsActionChannelName = channelNamearg , _ioTTopicRuleIotAnalyticsActionRoleArn = roleArnarg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-iotanalyticsaction.html#cfn-iot-topicrule-iotanalyticsaction-channelname ittriaaChannelName :: Lens' IoTTopicRuleIotAnalyticsAction (Val Text) ittriaaChannelName = lens _ioTTopicRuleIotAnalyticsActionChannelName (\s a -> s { _ioTTopicRuleIotAnalyticsActionChannelName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-iotanalyticsaction.html#cfn-iot-topicrule-iotanalyticsaction-rolearn ittriaaRoleArn :: Lens' IoTTopicRuleIotAnalyticsAction (Val Text) ittriaaRoleArn = lens _ioTTopicRuleIotAnalyticsActionRoleArn (\s a -> s { _ioTTopicRuleIotAnalyticsActionRoleArn = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/IoTTopicRuleIotAnalyticsAction.hs
mit
2,190
0
13
220
265
151
114
29
1
-- -- -- ------------------ -- Exercise 12.23. ------------------ -- -- -- module E'12'23 where
pascal-knodel/haskell-craft
_/links/E'12'23.hs
mit
106
0
2
24
13
12
1
1
0
-- -*- mode: haskell -*- {-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-} module Pump.CF.Type where -- $Id$ import Autolib.Size import Autolib.Hash import Autolib.Reader import Autolib.ToDoc import Data.Typeable data Zerlegung = Zerlegung { u :: String, v :: String , x :: String, y :: String, z :: String } deriving (Eq, Ord, Typeable) $(derives [makeReader, makeToDoc] [''Zerlegung]) instance Hash Zerlegung where hash e = hash ( hash ( u e, v e ), x e , hash ( y e, z e ) )
Erdwolf/autotool-bonn
src/Pump/CF/Type.hs
gpl-2.0
519
2
10
120
175
99
76
14
0
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-warnings-deprecations #-} {-| Combines the construction of RPC server components and their Python stubs. -} {- Copyright (C) 2013 Google 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.THH.PyRPC ( genPyUDSRpcStub , genPyUDSRpcStubStr ) where import Control.Monad import Data.Char (toLower, toUpper) import Data.Functor import Data.Maybe (fromMaybe) import Language.Haskell.TH import Language.Haskell.TH.Syntax (liftString) import Text.PrettyPrint import Ganeti.THH.Types -- | The indentation step in generated Python files. pythonIndentStep :: Int pythonIndentStep = 2 -- | A helper function that nests a block of generated output by the default -- step (see 'pythonIndentStep'). nest' :: Doc -> Doc nest' = nest pythonIndentStep -- | The name of an abstract function to which all method in a Python stub -- are forwarded to. genericInvokeName :: String genericInvokeName = "_GenericInvoke" -- | The name of a function that returns the socket path for reaching the -- appropriate RPC client. socketPathName :: String socketPathName = "_GetSocketPath" -- | Create a Python expression that applies a given function to a list of -- given expressions apply :: String -> [Doc] -> Doc apply name as = text name <> parens (hcat $ punctuate (text ", ") as) -- | An empty line block. emptyLine :: Doc emptyLine = text "" -- apparently using 'empty' doesn't work lowerFirst :: String -> String lowerFirst (x:xs) = toLower x : xs lowerFirst [] = [] upperFirst :: String -> String upperFirst (x:xs) = toUpper x : xs upperFirst [] = [] -- | Creates a method declaration given a function name and a list of -- Haskell types corresponding to its arguments. toFunc :: String -> [Type] -> Q Doc toFunc fname as = do args <- zipWithM varName [1..] as let args' = text "self" : args callName = lowerFirst fname return $ (text "def" <+> apply fname args') <> colon $+$ nest' (text "return" <+> text "self." <> apply genericInvokeName (text (show callName) : args) ) where -- | Create a name for a method argument, given its index position -- and Haskell type. varName :: Int -> Type -> Q Doc varName _ (VarT n) = lowerFirstNameQ n varName _ (ConT n) = lowerFirstNameQ n varName idx (AppT ListT t) = listOf idx t varName idx (AppT (ConT n) t) | n == ''[] = listOf idx t | otherwise = kind1Of idx n t varName idx (AppT (AppT (TupleT 2) t) t') = pairOf idx t t' varName idx (AppT (AppT (ConT n) t) t') | n == ''(,) = pairOf idx t t' varName idx t = do report False $ "Don't know how to make a Python variable name from " ++ show t ++ "; using a numbered one." return $ text ('_' : show idx) -- | Create a name for a method argument, knowing that its a list of -- a given type. listOf :: Int -> Type -> Q Doc listOf idx t = (<> text "List") <$> varName idx t -- | Create a name for a method argument, knowing that its wrapped in -- a type of kind @* -> *@. kind1Of :: Int -> Name -> Type -> Q Doc kind1Of idx name t = (<> text (nameBase name)) <$> varName idx t -- | Create a name for a method argument, knowing that its a pair of -- the given types. pairOf :: Int -> Type -> Type -> Q Doc pairOf idx t t' = do tn <- varName idx t tn' <- varName idx t' return $ tn <> text "_" <> tn' <> text "_Pair" lowerFirstNameQ :: Name -> Q Doc lowerFirstNameQ = return . text . lowerFirst . nameBase -- | Creates a method declaration by inspecting (reifying) Haskell's function -- name. nameToFunc :: Name -> Q Doc nameToFunc name = do (as, _) <- funArgs `liftM` typeOfFun name -- If the function has just one argument, try if it isn't a tuple; -- if not, use the arguments as they are. let as' = fromMaybe as $ case as of [t] -> tupleArgs t -- TODO CHECK! _ -> Nothing toFunc (upperFirst $ nameBase name) as' -- | Generates a Python class stub, given a class name, the list of Haskell -- functions to expose as methods, and a optionally a piece of code to -- include. namesToClass :: String -- ^ the class name -> Doc -- ^ Python code to include in the class -> [Name] -- ^ the list of functions to include -> Q Doc namesToClass cname pycode fns = do fnsCode <- mapM (liftM ($+$ emptyLine) . nameToFunc) fns return $ vcat [ text "class" <+> apply cname [text "object"] <> colon , nest' ( pycode $+$ vcat fnsCode ) ] -- | Takes a list of function names and creates a RPC handler that delegates -- calls to them, as well as writes out the corresponding Python stub. -- -- See 'mkRpcM' for the requirements on the passed functions and the returned -- expression. genPyUDSRpcStub :: String -- ^ the name of the class to be generated -> String -- ^ the name of the constant from @constants.py@ holding -- the path to a UDS socket -> [Name] -- ^ names of functions to include -> Q Doc genPyUDSRpcStub className constName = liftM (header $+$) . namesToClass className stubCode where header = text "# This file is automatically generated, do not edit!" $+$ text "# pylint: disable-all" stubCode = abstrMethod genericInvokeName [ text "method", text "*args"] $+$ method socketPathName [] ( text "from ganeti import pathutils" $+$ text "return" <+> text "pathutils." <> text constName) method name args body = text "def" <+> apply name (text "self" : args) <> colon $+$ nest' body $+$ emptyLine abstrMethod name args = method name args $ text "raise" <+> apply "NotImplementedError" [] -- The same as 'genPyUDSRpcStub', but returns the result as a @String@ -- expression. genPyUDSRpcStubStr :: String -- ^ the name of the class to be generated -> String -- ^ the constant in @pathutils.py@ holding the socket path -> [Name] -- ^ functions to include -> Q Exp genPyUDSRpcStubStr className constName names = liftString . render =<< genPyUDSRpcStub className constName names
ribag/ganeti-experiments
src/Ganeti/THH/PyRPC.hs
gpl-2.0
7,157
0
16
1,958
1,426
732
694
110
7
{-# LANGUAGE OverloadedStrings #-} module Database.CourseVideoSeed (courseVideos, seedVideos) where import Data.Text (Text) import Database.Tables hiding (Text) import Database.Persist.Sqlite (runSqlite, updateWhere, (=.), (==.)) import Config (databasePath) courseVideos :: [(Text, [Text])] courseVideos = [ ("CSC240H1", ["static/videos/csc240.mp4"]), ("CSC336H1", ["static/videos/csc336.mp4"]), ("CSC436H1", ["static/videos/csc436.mp4"]), ("CSC438H1", ["static/videos/csc438.mp4"]), ("CSC456H1", ["static/videos/csc456.mp4"]), ("CSC463H1", ["static/videos/csc463.mp4"])] seedVideo (code, videos) = do updateWhere [CoursesCode ==. code] [CoursesVideoUrls =. videos] seedVideos :: IO () seedVideos = runSqlite databasePath $ do mapM_ seedVideo courseVideos
arkon/courseography
hs/Database/CourseVideoSeed.hs
gpl-3.0
787
0
9
99
228
140
88
20
1
{-| Module : Css.Constants Description : Defines the constants for the other CSS modules. -} module Css.Constants (-- * Colors theoryDark, coreDark, seDark, systemsDark, graphicsDark, dbwebDark, numDark, aiDark, hciDark, mathDark, introDark, titleColour, lightGrey, -- * Graph Styles nodeFontSize, hybridFontSize, boolFontSize, regionFontSize ) where import Data.Text as T import Prelude hiding ((**)) {- Colors -} -- |Defines the color of a grayish blue. theoryDark :: T.Text theoryDark = "#B1C8D1" -- |Defines the color of a light gray. coreDark :: T.Text coreDark = "#C9C9C9" -- |Defines the color of a soft red. seDark :: T.Text seDark = "#E68080" -- |Defines the color of a light violet. systemsDark :: T.Text systemsDark = "#C285FF" -- |Defines the color of a mostly desaturated dark lime green. graphicsDark :: T.Text graphicsDark = "#66A366" -- |Defines the color of a strong pink. dbwebDark :: T.Text dbwebDark = "#C42B97" -- |Defines the color of a very light green. numDark :: T.Text numDark = "#B8FF70" -- |Defines the color of a very light blue. aiDark :: T.Text aiDark = "#80B2FF" -- |Defines the color of a soft lime green. hciDark :: T.Text hciDark = "#91F27A" -- |Defines the color of a slightly desaturated violet. mathDark :: T.Text mathDark = "#8A67BE" -- |Defines the color of a moderate cyan. introDark :: T.Text introDark = "#5DD5B8" -- |Defines the color of a very dark blue. titleColour :: T.Text titleColour = "#072D68" -- |Defines the color of a light gray. lightGrey :: T.Text lightGrey = "#CCCCCC" {- Graph styles -} -- |Defines node font size, 12 in pixels. nodeFontSize :: Num a => a nodeFontSize = 12 -- |Defines hybrid font size, 7 in pixels. hybridFontSize :: Double hybridFontSize = 7 -- |Defines bool font size, 6 in pixels. boolFontSize :: Num a => a boolFontSize = 6 -- |Defines region font size, 14 in pixels. regionFontSize :: Num a => a regionFontSize = 13
Courseography/courseography
app/Css/Constants.hs
gpl-3.0
2,032
0
6
447
316
198
118
55
1
module Amoeba.AI.Facade where
graninas/The-Amoeba-World
src/Amoeba/AI/Facade.hs
gpl-3.0
30
0
3
3
7
5
2
1
0
{-# LANGUAGE OverloadedStrings #-} {-| Module : Network.Gopher Stability : experimental Portability : POSIX = Overview This is the main module of the spacecookie library. It allows to write gopher applications by taking care of handling gopher requests while leaving the application logic to a user-supplied function. For a small tutorial an example of a trivial pure gopher application: @ {-# LANGUAGE OverloadedStrings #-} import Network.Gopher import Network.Gopher.Util main = do 'runGopherPure' ('GopherConfig' "localhost" 7000 Nothing) (\\req -> 'FileResponse' ('uEncode' req)) @ This server just returns the request string as a file. There are three possibilities for a 'GopherResponse': * 'FileResponse': file type agnostic file response, takes a 'ByteString' to support both text and binary files * 'MenuResponse': a gopher menu (“directory listing”) consisting of a list of 'GopherMenuItem's * 'ErrorResponse': gopher way to show an error (e. g. if a file is not found). A 'ErrorResponse' results in a menu response with a single entry. If you use 'runGopher', it is the same story like in the example above, but you can do 'IO' effects. To see a more elaborate example, have a look at the server code in this package. Note: In practice it is probably best to use record update syntax on 'defaultConfig' which won't break your application every time the config record fields are changed. -} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Network.Gopher ( -- * Main API runGopher , runGopherPure , runGopherManual , GopherConfig (..) , defaultConfig -- * Helper Functions , gophermapToDirectoryResponse , setupGopherSocket -- * Representations -- ** Responses , GopherResponse (..) , GopherMenuItem (..) , GopherFileType (..) -- ** Gophermaps , GophermapEntry (..) , Gophermap (..) ) where import Prelude hiding (log) import Network.Gopher.Log import Network.Gopher.Types import Network.Gopher.Util import Network.Gopher.Util.Gophermap import Control.Applicative ((<$>), (<*>), Applicative (..)) import Control.Concurrent (forkIO, ThreadId ()) import Control.Exception (bracket, catch, IOException (..)) import Control.Monad (forever, when) import Control.Monad.IO.Class (liftIO, MonadIO (..)) import Control.Monad.Reader (ask, runReaderT, MonadReader (..), ReaderT (..)) import Control.Monad.Error.Class (MonadError (..)) import Data.ByteString (ByteString ()) import qualified Data.ByteString as B import Data.Maybe (isJust, fromJust, fromMaybe) import Data.Monoid ((<>)) import qualified Data.String.UTF8 as U import System.IO import System.Log.FastLogger import System.Log.FastLogger.Date import System.Socket hiding (Error (..)) import System.Socket.Family.Inet6 import System.Socket.Type.Stream import System.Socket.Protocol.TCP import System.Posix.User -- | necessary information to handle gopher requests data GopherConfig = GopherConfig { cServerName :: ByteString -- ^ “name” of the server (either ip address or dns name) , cServerPort :: Integer -- ^ port to listen on , cRunUserName :: Maybe String -- ^ user to run the process as , cLogConfig :: Maybe GopherLogConfig -- ^ Can be used to customize the log output. -- If 'Nothing', logging is disabled. } -- | Default 'GopherConfig' describing a server on @localhost:70@ with logging enabled. defaultConfig :: GopherConfig defaultConfig = GopherConfig "localhost" 70 Nothing (Just defaultLogConfig) data Env = Env { serverConfig :: GopherConfig , serverSocket :: Socket Inet6 Stream TCP , serverFun :: (String -> IO GopherResponse) , logger :: Maybe (TimedFastLogger, IO ()) -- ^ TimedFastLogger and clean up action } -- aliases for old accessors serverName = cServerName . serverConfig serverPort = cServerPort . serverConfig initEnv :: Socket Inet6 Stream TCP -> (String -> IO GopherResponse) -> GopherConfig -> IO Env initEnv sock fun cfg = do timeCache <- newTimeCache simpleTimeFormat logger <- if isJust (cLogConfig cfg) then Just <$> newTimedFastLogger timeCache (LogStderr 128) else pure Nothing pure $ Env cfg sock fun logger newtype GopherM a = GopherM { runGopherM :: ReaderT Env IO a } deriving ( Functor, Applicative, Monad , MonadIO, MonadReader Env, MonadError IOException) gopherM env action = (runReaderT . runGopherM) action env -- This action has become a bit obfuscated. Essentially -- we initially get the log config and the logger out -- of Env. Both those values may be Nothing, so we -- figure out in the Maybe monad: -- -- * if we have a logger -- * if we have a log config -- * if the configured log handler returns a LogStr -- for the given LogMessage -- -- If all of those things hold we perform the log -- action in the IO Monad and get rid of the intermediate -- Maybe layer. log :: LogMessage -> GopherM () log logMsg = do c <- fmap (cLogConfig . serverConfig) ask mLogger <- fmap logger ask liftIO . fromMaybe (pure ()) $ do cfg <- c (tlogger, _) <- mLogger renderedMsg <- glcLogHandler cfg logMsg pure . tlogger $ (\t -> let tStr = if glcLogTimed cfg then "[" <> toLogStr t <> "]" else "" in tStr <> renderedMsg <> "\n") receiveRequest :: Socket Inet6 Stream TCP -> IO ByteString receiveRequest sock = receiveRequest' sock mempty where lengthLimit = 1024 receiveRequest' sock acc = do bs <- liftIO $ receive sock lengthLimit mempty case (B.elemIndex (asciiOrd '\n') bs) of Just i -> return (acc `B.append` (B.take (i + 1) bs)) Nothing -> if B.length bs < lengthLimit then return (acc `B.append` bs) else receiveRequest' sock (acc `B.append` bs) dropPrivileges :: String -> IO Bool dropPrivileges username = do uid <- getRealUserID if (uid /= 0) then return False else do user <- getUserEntryForName username setGroupID $ userGroupID user setUserID $ userID user return True -- | Auxiliary function that sets up the listening socket for -- 'runGopherManual' correctly and starts to listen. setupGopherSocket :: GopherConfig -> IO (Socket Inet6 Stream TCP) setupGopherSocket cfg = do sock <- (socket :: IO (Socket Inet6 Stream TCP)) setSocketOption sock (ReuseAddress True) setSocketOption sock (V6Only False) bind sock (SocketAddressInet6 inet6Any (fromInteger (cServerPort cfg)) 0 0) listen sock 5 pure sock -- | Run a gopher application that may cause effects in 'IO'. -- The application function is given the gopher request (path) -- and required to produce a GopherResponse. runGopher :: GopherConfig -> (String -> IO GopherResponse) -> IO () runGopher cfg f = runGopherManual (setupGopherSocket cfg) (pure ()) close cfg f -- | Same as 'runGopher', but allows you to setup the 'Socket' manually -- and calls an action of type @IO ()@ as soon as the server is ready -- to accept requests. When the server terminates, it calls the action -- of type @Socket Inet6 Stream TCP -> IO ()@ to clean up the socket. -- -- Spacecookie assumes the 'Socket' is properly set up to listen on the -- port and host specified in the 'GopherConfig' (i. e. 'bind' and -- 'listen' have been called). This can be achieved using 'setupGopherSocket'. -- -- This is intended for supporting systemd socket activation and storage. -- Only use, if you know what you are doing. runGopherManual :: IO (Socket Inet6 Stream TCP) -> IO () -> (Socket Inet6 Stream TCP -> IO ()) -> GopherConfig -> (String -> IO GopherResponse) -> IO () runGopherManual sock ready term cfg f = bracket sock term (\sock -> do env <- initEnv sock f cfg gopherM env $ do addr <- liftIO $ getAddress sock log $ LogInfoListeningOn addr -- Change UID and GID if necessary when (isJust (cRunUserName cfg)) $ do success <- liftIO . dropPrivileges . fromJust $ cRunUserName cfg if success then log . LogInfoChangedUser . fromJust $ cRunUserName cfg else log . LogErrorCantChangeUid . fromJust $ cRunUserName cfg liftIO $ ready (forever (acceptAndHandle sock) `catchError` (\e -> do log . LogErrorAccept $ e maybe (pure ()) snd . logger <$> ask >>= liftIO))) forkGopherM :: GopherM () -> GopherM ThreadId forkGopherM action = ask >>= liftIO . forkIO . (flip gopherM) action handleIncoming :: Socket Inet6 Stream TCP -> SocketAddress Inet6 -> GopherM () handleIncoming clientSock addr = do req <- liftIO $ uDecode . stripNewline <$> receiveRequest clientSock log $ LogInfoRequest req addr fun <- serverFun <$> ask res <- liftIO (fun req) >>= response liftIO $ sendAll clientSock res msgNoSignal liftIO $ close clientSock log $ LogInfoClosedConnection addr acceptAndHandle :: Socket Inet6 Stream TCP -> GopherM () acceptAndHandle sock = do (clientSock, addr) <- liftIO $ accept sock log $ LogInfoNewConnection addr forkGopherM $ handleIncoming clientSock addr `catchError` (\e -> do liftIO (close clientSock `catchError` const (pure ())) log $ LogErrorClosedConnection addr e) return () -- | Run a gopher application that may not cause effects in 'IO'. runGopherPure :: GopherConfig -> (String -> GopherResponse) -> IO () runGopherPure cfg f = runGopher cfg (fmap pure f) response :: GopherResponse -> GopherM ByteString response (MenuResponse items) = do env <- ask pure $ foldl (\acc (Item fileType title path host port) -> B.append acc $ fileTypeToChar fileType `B.cons` B.concat [ title, uEncode "\t", uEncode path, uEncode "\t", fromMaybe (serverName env) host, uEncode "\t", uEncode . show $ fromMaybe (serverPort env) port, uEncode "\r\n" ]) B.empty items response (FileResponse str) = pure str response (ErrorResponse reason) = response . MenuResponse $ [ Item Error (uEncode reason) "Err" Nothing Nothing ]
lukasepple/spacecookie
src/Network/Gopher.hs
gpl-3.0
10,224
0
25
2,312
2,275
1,201
1,074
159
3
{-# 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.S3.ListParts -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists the parts that have been uploaded for a specific multipart upload. -- -- /See:/ <http://docs.aws.amazon.com/AmazonS3/latest/API/ListParts.html AWS API Reference> for ListParts. -- -- This operation returns paginated results. module Network.AWS.S3.ListParts ( -- * Creating a Request listParts , ListParts -- * Request Lenses , lpMaxParts , lpRequestPayer , lpPartNumberMarker , lpBucket , lpKey , lpUploadId -- * Destructuring the Response , listPartsResponse , ListPartsResponse -- * Response Lenses , lprsParts , lprsRequestCharged , lprsMaxParts , lprsInitiator , lprsBucket , lprsNextPartNumberMarker , lprsOwner , lprsKey , lprsStorageClass , lprsIsTruncated , lprsPartNumberMarker , lprsUploadId , lprsResponseStatus ) where import Network.AWS.Pager import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.S3.Types import Network.AWS.S3.Types.Product -- | /See:/ 'listParts' smart constructor. data ListParts = ListParts' { _lpMaxParts :: !(Maybe Int) , _lpRequestPayer :: !(Maybe RequestPayer) , _lpPartNumberMarker :: !(Maybe Int) , _lpBucket :: !BucketName , _lpKey :: !ObjectKey , _lpUploadId :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListParts' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lpMaxParts' -- -- * 'lpRequestPayer' -- -- * 'lpPartNumberMarker' -- -- * 'lpBucket' -- -- * 'lpKey' -- -- * 'lpUploadId' listParts :: BucketName -- ^ 'lpBucket' -> ObjectKey -- ^ 'lpKey' -> Text -- ^ 'lpUploadId' -> ListParts listParts pBucket_ pKey_ pUploadId_ = ListParts' { _lpMaxParts = Nothing , _lpRequestPayer = Nothing , _lpPartNumberMarker = Nothing , _lpBucket = pBucket_ , _lpKey = pKey_ , _lpUploadId = pUploadId_ } -- | Sets the maximum number of parts to return. lpMaxParts :: Lens' ListParts (Maybe Int) lpMaxParts = lens _lpMaxParts (\ s a -> s{_lpMaxParts = a}); -- | Undocumented member. lpRequestPayer :: Lens' ListParts (Maybe RequestPayer) lpRequestPayer = lens _lpRequestPayer (\ s a -> s{_lpRequestPayer = a}); -- | Specifies the part after which listing should begin. Only parts with -- higher part numbers will be listed. lpPartNumberMarker :: Lens' ListParts (Maybe Int) lpPartNumberMarker = lens _lpPartNumberMarker (\ s a -> s{_lpPartNumberMarker = a}); -- | Undocumented member. lpBucket :: Lens' ListParts BucketName lpBucket = lens _lpBucket (\ s a -> s{_lpBucket = a}); -- | Undocumented member. lpKey :: Lens' ListParts ObjectKey lpKey = lens _lpKey (\ s a -> s{_lpKey = a}); -- | Upload ID identifying the multipart upload whose parts are being listed. lpUploadId :: Lens' ListParts Text lpUploadId = lens _lpUploadId (\ s a -> s{_lpUploadId = a}); instance AWSPager ListParts where page rq rs | stop (rs ^. lprsNextPartNumberMarker) = Nothing | stop (rs ^. lprsParts) = Nothing | otherwise = Just $ rq & lpPartNumberMarker .~ rs ^. lprsNextPartNumberMarker instance AWSRequest ListParts where type Rs ListParts = ListPartsResponse request = get s3 response = receiveXML (\ s h x -> ListPartsResponse' <$> (may (parseXMLList "Part") x) <*> (h .#? "x-amz-request-charged") <*> (x .@? "MaxParts") <*> (x .@? "Initiator") <*> (x .@? "Bucket") <*> (x .@? "NextPartNumberMarker") <*> (x .@? "Owner") <*> (x .@? "Key") <*> (x .@? "StorageClass") <*> (x .@? "IsTruncated") <*> (x .@? "PartNumberMarker") <*> (x .@? "UploadId") <*> (pure (fromEnum s))) instance ToHeaders ListParts where toHeaders ListParts'{..} = mconcat ["x-amz-request-payer" =# _lpRequestPayer] instance ToPath ListParts where toPath ListParts'{..} = mconcat ["/", toBS _lpBucket, "/", toBS _lpKey] instance ToQuery ListParts where toQuery ListParts'{..} = mconcat ["max-parts" =: _lpMaxParts, "part-number-marker" =: _lpPartNumberMarker, "uploadId" =: _lpUploadId] -- | /See:/ 'listPartsResponse' smart constructor. data ListPartsResponse = ListPartsResponse' { _lprsParts :: !(Maybe [Part]) , _lprsRequestCharged :: !(Maybe RequestCharged) , _lprsMaxParts :: !(Maybe Int) , _lprsInitiator :: !(Maybe Initiator) , _lprsBucket :: !(Maybe BucketName) , _lprsNextPartNumberMarker :: !(Maybe Int) , _lprsOwner :: !(Maybe Owner) , _lprsKey :: !(Maybe ObjectKey) , _lprsStorageClass :: !(Maybe StorageClass) , _lprsIsTruncated :: !(Maybe Bool) , _lprsPartNumberMarker :: !(Maybe Int) , _lprsUploadId :: !(Maybe Text) , _lprsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListPartsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lprsParts' -- -- * 'lprsRequestCharged' -- -- * 'lprsMaxParts' -- -- * 'lprsInitiator' -- -- * 'lprsBucket' -- -- * 'lprsNextPartNumberMarker' -- -- * 'lprsOwner' -- -- * 'lprsKey' -- -- * 'lprsStorageClass' -- -- * 'lprsIsTruncated' -- -- * 'lprsPartNumberMarker' -- -- * 'lprsUploadId' -- -- * 'lprsResponseStatus' listPartsResponse :: Int -- ^ 'lprsResponseStatus' -> ListPartsResponse listPartsResponse pResponseStatus_ = ListPartsResponse' { _lprsParts = Nothing , _lprsRequestCharged = Nothing , _lprsMaxParts = Nothing , _lprsInitiator = Nothing , _lprsBucket = Nothing , _lprsNextPartNumberMarker = Nothing , _lprsOwner = Nothing , _lprsKey = Nothing , _lprsStorageClass = Nothing , _lprsIsTruncated = Nothing , _lprsPartNumberMarker = Nothing , _lprsUploadId = Nothing , _lprsResponseStatus = pResponseStatus_ } -- | Undocumented member. lprsParts :: Lens' ListPartsResponse [Part] lprsParts = lens _lprsParts (\ s a -> s{_lprsParts = a}) . _Default . _Coerce; -- | Undocumented member. lprsRequestCharged :: Lens' ListPartsResponse (Maybe RequestCharged) lprsRequestCharged = lens _lprsRequestCharged (\ s a -> s{_lprsRequestCharged = a}); -- | Maximum number of parts that were allowed in the response. lprsMaxParts :: Lens' ListPartsResponse (Maybe Int) lprsMaxParts = lens _lprsMaxParts (\ s a -> s{_lprsMaxParts = a}); -- | Identifies who initiated the multipart upload. lprsInitiator :: Lens' ListPartsResponse (Maybe Initiator) lprsInitiator = lens _lprsInitiator (\ s a -> s{_lprsInitiator = a}); -- | Name of the bucket to which the multipart upload was initiated. lprsBucket :: Lens' ListPartsResponse (Maybe BucketName) lprsBucket = lens _lprsBucket (\ s a -> s{_lprsBucket = a}); -- | When a list is truncated, this element specifies the last part in the -- list, as well as the value to use for the part-number-marker request -- parameter in a subsequent request. lprsNextPartNumberMarker :: Lens' ListPartsResponse (Maybe Int) lprsNextPartNumberMarker = lens _lprsNextPartNumberMarker (\ s a -> s{_lprsNextPartNumberMarker = a}); -- | Undocumented member. lprsOwner :: Lens' ListPartsResponse (Maybe Owner) lprsOwner = lens _lprsOwner (\ s a -> s{_lprsOwner = a}); -- | Object key for which the multipart upload was initiated. lprsKey :: Lens' ListPartsResponse (Maybe ObjectKey) lprsKey = lens _lprsKey (\ s a -> s{_lprsKey = a}); -- | The class of storage used to store the object. lprsStorageClass :: Lens' ListPartsResponse (Maybe StorageClass) lprsStorageClass = lens _lprsStorageClass (\ s a -> s{_lprsStorageClass = a}); -- | Indicates whether the returned list of parts is truncated. lprsIsTruncated :: Lens' ListPartsResponse (Maybe Bool) lprsIsTruncated = lens _lprsIsTruncated (\ s a -> s{_lprsIsTruncated = a}); -- | Part number after which listing begins. lprsPartNumberMarker :: Lens' ListPartsResponse (Maybe Int) lprsPartNumberMarker = lens _lprsPartNumberMarker (\ s a -> s{_lprsPartNumberMarker = a}); -- | Upload ID identifying the multipart upload whose parts are being listed. lprsUploadId :: Lens' ListPartsResponse (Maybe Text) lprsUploadId = lens _lprsUploadId (\ s a -> s{_lprsUploadId = a}); -- | The response status code. lprsResponseStatus :: Lens' ListPartsResponse Int lprsResponseStatus = lens _lprsResponseStatus (\ s a -> s{_lprsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-s3/gen/Network/AWS/S3/ListParts.hs
mpl-2.0
9,698
0
25
2,334
1,913
1,113
800
208
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.DLP.Organizations.Locations.DeidentifyTemplates.Create -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a DeidentifyTemplate for re-using frequently used configuration -- for de-identifying content, images, and storage. See -- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates-deid to learn -- more. -- -- /See:/ <https://cloud.google.com/dlp/docs/ Cloud Data Loss Prevention (DLP) API Reference> for @dlp.organizations.locations.deidentifyTemplates.create@. module Network.Google.Resource.DLP.Organizations.Locations.DeidentifyTemplates.Create ( -- * REST Resource OrganizationsLocationsDeidentifyTemplatesCreateResource -- * Creating a Request , organizationsLocationsDeidentifyTemplatesCreate , OrganizationsLocationsDeidentifyTemplatesCreate -- * Request Lenses , oldtcParent , oldtcXgafv , oldtcUploadProtocol , oldtcAccessToken , oldtcUploadType , oldtcPayload , oldtcCallback ) where import Network.Google.DLP.Types import Network.Google.Prelude -- | A resource alias for @dlp.organizations.locations.deidentifyTemplates.create@ method which the -- 'OrganizationsLocationsDeidentifyTemplatesCreate' request conforms to. type OrganizationsLocationsDeidentifyTemplatesCreateResource = "v2" :> Capture "parent" Text :> "deidentifyTemplates" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] GooglePrivacyDlpV2CreateDeidentifyTemplateRequest :> Post '[JSON] GooglePrivacyDlpV2DeidentifyTemplate -- | Creates a DeidentifyTemplate for re-using frequently used configuration -- for de-identifying content, images, and storage. See -- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates-deid to learn -- more. -- -- /See:/ 'organizationsLocationsDeidentifyTemplatesCreate' smart constructor. data OrganizationsLocationsDeidentifyTemplatesCreate = OrganizationsLocationsDeidentifyTemplatesCreate' { _oldtcParent :: !Text , _oldtcXgafv :: !(Maybe Xgafv) , _oldtcUploadProtocol :: !(Maybe Text) , _oldtcAccessToken :: !(Maybe Text) , _oldtcUploadType :: !(Maybe Text) , _oldtcPayload :: !GooglePrivacyDlpV2CreateDeidentifyTemplateRequest , _oldtcCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OrganizationsLocationsDeidentifyTemplatesCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oldtcParent' -- -- * 'oldtcXgafv' -- -- * 'oldtcUploadProtocol' -- -- * 'oldtcAccessToken' -- -- * 'oldtcUploadType' -- -- * 'oldtcPayload' -- -- * 'oldtcCallback' organizationsLocationsDeidentifyTemplatesCreate :: Text -- ^ 'oldtcParent' -> GooglePrivacyDlpV2CreateDeidentifyTemplateRequest -- ^ 'oldtcPayload' -> OrganizationsLocationsDeidentifyTemplatesCreate organizationsLocationsDeidentifyTemplatesCreate pOldtcParent_ pOldtcPayload_ = OrganizationsLocationsDeidentifyTemplatesCreate' { _oldtcParent = pOldtcParent_ , _oldtcXgafv = Nothing , _oldtcUploadProtocol = Nothing , _oldtcAccessToken = Nothing , _oldtcUploadType = Nothing , _oldtcPayload = pOldtcPayload_ , _oldtcCallback = Nothing } -- | Required. Parent resource name. The format of this value varies -- depending on the scope of the request (project or organization) and -- whether you have [specified a processing -- location](https:\/\/cloud.google.com\/dlp\/docs\/specifying-location): + -- Projects scope, location specified: -- \`projects\/\`PROJECT_ID\`\/locations\/\`LOCATION_ID + Projects scope, -- no location specified (defaults to global): \`projects\/\`PROJECT_ID + -- Organizations scope, location specified: -- \`organizations\/\`ORG_ID\`\/locations\/\`LOCATION_ID + Organizations -- scope, no location specified (defaults to global): -- \`organizations\/\`ORG_ID The following example \`parent\` string -- specifies a parent project with the identifier \`example-project\`, and -- specifies the \`europe-west3\` location for processing data: -- parent=projects\/example-project\/locations\/europe-west3 oldtcParent :: Lens' OrganizationsLocationsDeidentifyTemplatesCreate Text oldtcParent = lens _oldtcParent (\ s a -> s{_oldtcParent = a}) -- | V1 error format. oldtcXgafv :: Lens' OrganizationsLocationsDeidentifyTemplatesCreate (Maybe Xgafv) oldtcXgafv = lens _oldtcXgafv (\ s a -> s{_oldtcXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). oldtcUploadProtocol :: Lens' OrganizationsLocationsDeidentifyTemplatesCreate (Maybe Text) oldtcUploadProtocol = lens _oldtcUploadProtocol (\ s a -> s{_oldtcUploadProtocol = a}) -- | OAuth access token. oldtcAccessToken :: Lens' OrganizationsLocationsDeidentifyTemplatesCreate (Maybe Text) oldtcAccessToken = lens _oldtcAccessToken (\ s a -> s{_oldtcAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). oldtcUploadType :: Lens' OrganizationsLocationsDeidentifyTemplatesCreate (Maybe Text) oldtcUploadType = lens _oldtcUploadType (\ s a -> s{_oldtcUploadType = a}) -- | Multipart request metadata. oldtcPayload :: Lens' OrganizationsLocationsDeidentifyTemplatesCreate GooglePrivacyDlpV2CreateDeidentifyTemplateRequest oldtcPayload = lens _oldtcPayload (\ s a -> s{_oldtcPayload = a}) -- | JSONP oldtcCallback :: Lens' OrganizationsLocationsDeidentifyTemplatesCreate (Maybe Text) oldtcCallback = lens _oldtcCallback (\ s a -> s{_oldtcCallback = a}) instance GoogleRequest OrganizationsLocationsDeidentifyTemplatesCreate where type Rs OrganizationsLocationsDeidentifyTemplatesCreate = GooglePrivacyDlpV2DeidentifyTemplate type Scopes OrganizationsLocationsDeidentifyTemplatesCreate = '["https://www.googleapis.com/auth/cloud-platform"] requestClient OrganizationsLocationsDeidentifyTemplatesCreate'{..} = go _oldtcParent _oldtcXgafv _oldtcUploadProtocol _oldtcAccessToken _oldtcUploadType _oldtcCallback (Just AltJSON) _oldtcPayload dLPService where go = buildClient (Proxy :: Proxy OrganizationsLocationsDeidentifyTemplatesCreateResource) mempty
brendanhay/gogol
gogol-dlp/gen/Network/Google/Resource/DLP/Organizations/Locations/DeidentifyTemplates/Create.hs
mpl-2.0
7,454
0
17
1,463
799
474
325
124
1
module CSC322a2TestData where tests :: [(Integer, [Int], Bool)] tests = [(1, [5, 3, 1, 6, 8, 2, 4, 7], True), (2, [3, 6, 2, 5, 8, 1, 7, 4], True), (3, [2, 5, 11, 4, 1, 1, 10, 3], False), (4, [6, 6, 1, 4, 7, 5], False), (5, [5, 3, 1, 7, 2, 8, 6, 4], True), (6, [1, 2, 2, 1, 6], False), (7, [3, 6, 2, 5, 8, 1, 7, 4], True), (8, [7, 5, 3, 1, 6, 8, 2, 4], True), (9, [1, 5, 2, 3, 3], False), (10, [3, 5, 5, 11, 9, 4, 8, 4], False), (11, [6, 4, 1, 5, 8, 2, 7, 3], True), (12, [8, 6, 5, 3, 1, 4], False), (13, [5, 6, 2, 2, 1], False), (14, [6, 1, 8, 7, 3, 8, 1], False), (15, [3, 6, 7, 2, 1, 4, 7], False), (16, [6, 4, 7, 1, 3, 5, 2, 8], True), (17, [3, 8, 9, 8, 4, 4, 9], False), (18, [2, 4, 6, 1, 3, 5], True), (19, [5, 8, 4, 1, 7, 2, 6, 3], True), (20, [6, 1, 8, 4, 9, 9, 6], False), (21, [2, 5, 7, 2, 2, 7], False), (22, [3, 5, 8, 4, 1, 7, 2, 6], True), (23, [4, 3, 9, 4, 6, 3, 2], False), (24, [3, 2, 6, 6, 7, 6, 3], False), (25, [7, 3, 6, 2, 5, 1, 4], True), (26, [2, 4, 6, 1, 3, 5, 7], True), (27, [5, 4, 9, 11, 1, 3, 11, 3], False), (28, [2, 6, 3, 7, 4, 1, 5], True), (29, [5, 2, 4, 7, 3, 8, 6, 1], True), (30, [4, 5, 3, 4, 2], False), (31, [4, 2, 7, 5, 1, 8, 6, 3], True), (32, [1, 7, 4, 6, 8, 2, 5, 3], True), (33, [6, 3, 1, 4, 7, 5, 2], True), (34, [6, 11, 2, 7, 6, 4, 4, 10], False), (35, [1, 7, 5, 7, 3, 7], False), (36, [2, 6, 6, 2, 6], False), (37, [6, 1, 6, 6, 2], False), (38, [3, 6, 8, 1, 5, 7, 2, 4], True), (39, [6, 2, 5, 1, 4, 7, 3], True), (40, [6, 1, 1, 3, 5, 2], False), (41, [7, 8, 6, 8, 4, 7, 1], False), (42, [7, 4, 2, 8, 6, 1, 3, 5], True), (43, [2, 1, 7, 2, 6, 1], False), (44, [3, 1, 7, 5, 8, 2, 4, 6], True), (45, [1, 5, 6, 1, 8, 5], False), (46, [2, 3, 2, 1, 4, 4, 8], False), (47, [6, 4, 1, 3, 2], False), (48, [9, 4, 1, 8, 8, 8, 7], False), (49, [4, 6, 1, 5, 2, 8, 3, 7], True), (50, [3, 11, 9, 5, 9, 10, 9, 2], False), (51, [4, 2, 5, 3, 1], True), (52, [1, 1, 1, 2, 6], False), (53, [7, 2, 4, 6, 1, 3, 5], True), (54, [9, 9, 7, 1, 5, 7, 8, 2], False), (55, [8, 2, 4, 1, 7, 5, 3, 6], True), (56, [5, 3, 1, 7, 2, 8, 6, 4], True), (57, [4, 5, 3, 5, 3], False), (58, [8, 6, 4, 4, 7, 3], False), (59, [6, 4, 4, 5, 4, 1], False), (60, [5, 5, 4, 11, 8, 8, 3, 9], False), (61, [2, 4, 1, 4, 4], False), (62, [3, 5, 7, 2, 4, 6, 4], False), (63, [7, 6, 2, 7, 8, 9, 2, 4], False), (64, [6, 8, 2, 4, 1, 7, 5, 3], True), (65, [7, 4, 2, 8, 6, 1, 3, 5], True), (66, [9, 7, 3, 8, 1, 1, 8], False), (67, [3, 5, 2, 2, 1], False), (68, [6, 4, 2, 8, 5, 7, 1, 3], True), (69, [7, 3, 1, 6, 8, 5, 2, 4], True), (70, [4, 7, 5, 3, 1, 6, 8, 2], True), (71, [5, 7, 1, 4, 2, 8, 6, 3], True), (72, [5, 9, 2, 3, 9, 5, 3, 3], False), (73, [2, 4, 6, 1, 3, 5], True), (74, [7, 3, 1, 6, 8, 5, 2, 4], True), (75, [3, 6, 8, 1, 5, 7, 2, 4], True), (76, [2, 5, 3, 3, 4], False), (77, [1, 4, 2, 5, 3], True), (78, [4, 6, 5, 5, 2], False), (79, [2, 1, 3, 1, 3, 1, 1], False), (80, [7, 5, 3, 1, 6, 4, 2], True), (81, [1, 4, 8, 3, 5, 1], False), (82, [3, 6, 8, 1, 4, 7, 5, 2], True), (83, [7, 4, 2, 5, 8, 1, 3, 6], True), (84, [3, 5, 7, 2, 4, 6, 1], True), (85, [6, 4, 2, 8, 5, 7, 1, 3], True), (86, [4, 2, 7, 5, 3, 1, 6], True), (87, [4, 6, 8, 2, 7, 1, 3, 5], True), (88, [2, 7, 11, 2, 1, 3, 6, 9], False), (89, [7, 6, 1, 8, 9, 9, 4], False), (90, [8, 8, 7, 1, 2, 2, 6], False), (91, [6, 8, 2, 4, 1, 7, 5, 3], True), (92, [3, 5, 2, 4, 1], True), (93, [6, 4, 7, 1, 3, 5, 2], True), (94, [2, 7, 5, 8, 1, 4, 6, 3], True), (95, [7, 10, 2, 5, 11, 7, 5, 2], False), (96, [3, 6, 6, 4, 3], False), (97, [5, 6, 8, 7, 7, 8, 4], False), (98, [7, 3, 6, 2, 5, 1, 4], True), (99, [1, 4, 7, 3, 6, 2, 5], True), (100, [3, 1, 4, 2], True)]
cwlmyjm/haskell
Learning/400/CSC322a2TestData.hs
mpl-2.0
4,502
0
7
1,796
3,311
2,207
1,104
102
1
{-| Module : TypedFlow.Layers.RNN.Base Description : RNN cells, layers and combinators. Copyright : (c) Jean-Philippe Bernardy, 2017 License : LGPL-3 Maintainer : jean-philippe.bernardy@gu.se Stability : experimental -} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE TypeInType #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-} {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE PatternSynonyms #-} module TypedFlow.Layers.RNN.Base ( -- * Cell Combinators RnnCell, simpleRnn, runCell, mkCell, stackRnnCells, (.-.), bothRnnCells, (.|.), withBypass, withFeedback, onStates, -- * Rnn Combinators Rnn, runRnn, stackRnns, (.--.), bothRnns,(.++.), -- * RNN unfolding functions timeDistribute, iterateCell, iterateCellBackward, iterateWithCull, -- * Monad-like interface for cell construction Component(..), bindC, returnC, -- rnnBackwardsWithCull, ) where import Prelude hiding (tanh,Num(..),Floating(..),floor) import GHC.TypeLits import TypedFlow.TF import TypedFlow.Types import TypedFlow.Types.Proofs -- import Data.Type.Equality -- import Data.Kind (Type,Constraint) -- | The RNN Component generalized monad. This can be used to build -- RNNs cells which do not follow the simple and usual "stacking" -- pattern. This is not a simple monad, because the indexing over -- states is non-uniform; see 'BindC'. newtype Component t (states::[Shape]) a = C {runC :: HTV t states -> (HTV t states , a)} -- Note: states are tensors only, because we need to index into them -- in the time dimension in iterateWithCull instance Functor (Component t states) where fmap = mapC mapC :: (a -> b) -> Component t s a -> Component t s b mapC f c = C $ \s -> let (s',x) = runC c s in (s', f x) -- | Unit of the Component monad. returnC :: a -> Component t '[] a returnC x = C $ \Unit -> (Unit,x) -- | Bind operation for Components. States are accumulated. bindC :: forall t s0 s1 a b. KnownLen s1 => Component t s0 a -> (a -> Component t s1 b) -> Component t (s1++s0) b bindC f g = C $ \(hsplit @s1 -> (s1,s0)) -> let (s0',x) = runC f s0 (s1',y) = runC (g x) s1 in (happ s1' s0',y) -- | A cell (one time-step) in an rnn. @state@ is the state propagated through time. type RnnCell t states input output = input -> Component t states output -- | An rnn. @n@ is the length of the time sequence. @state@ is the state propagated through time. type Rnn n b state input output = RnnCell b state (V n input) (V n output) -- | Run a cell runCell :: RnnCell t states input output -> (HTV t states,input) -> (HTV t states, output) runCell cell = uncurry (flip (runC . cell)) -- | Run an RNN, using a tensor as input. @n@ is the length of the time sequence. runRnn :: (KnownNat n,KnownShape s0, KnownShape s1, KnownTyp t1) => Rnn n t2 states (T s1 t1) (T s0 t0) -> (HTV t2 states, Tensor (n ': s1) t1) -> (HTV t2 states, Tensor (n ': s0) t0) runRnn l (s,x) = let x' = unstack0 x (s',y) = runCell l (s,x') in (s',stack0 y) -- | Run an RNN composed of a single RNN cell. simpleRnn :: KnownTyp t1 => KnownShape s1 => KnownShape s0 => KnownNat n => RnnCell t2 states (T s1 t1) (T s0 t0) -> (HTV t2 states, Tensor (n : s1) t1) -> (HTV t2 states, Tensor (n : s0) t0) simpleRnn = runRnn . iterateCell -- | Construct a cell from an arbitrary stateful function mkCell :: ((HTV t states,input) -> (HTV t states, output)) -> RnnCell t states input output mkCell cell = C . flip (curry cell) ---------------------- -- Lifting functions -- | Convert a pure function (feed-forward layer) to an RNN cell by -- ignoring the RNN state. timeDistribute :: (a -> b) -> RnnCell t '[] a b timeDistribute = constantOverSteps -- | Convert a pure function (feed-forward layer) to an RNN cell by -- ignoring the RNN state. constantOverSteps :: (a -> b) -> RnnCell t '[] a b constantOverSteps stateLess a = returnC (stateLess a) -------------------------------------- -- Combinators -- | Compose two rnn layers. This is useful for example to combine -- forward and backward layers. (.--.),stackRnns :: forall s1 s2 a b c n bits. KnownLen s2 => Rnn n bits s1 a b -> Rnn n bits s2 b c -> Rnn n bits (s2 ++ s1) a c stackRnns = stackRnnCells infixr .--. (.--.) = stackRnns -- | Compose two rnn layers in parallel. bothRnns,(.++.) :: forall s1 s2 a b c n bits t. KnownTyp t => KnownLen s1 => KnownLen s2 => KnownNat n => KnownNat b => KnownNat c => Rnn n bits s1 a (T '[b] t) -> Rnn n bits s2 a (T '[c] t) -> Rnn n bits (s2 ++ s1) a (T ('[b+c]) t) bothRnns f g x = f x `bindC` \y -> g x `bindC` \z -> returnC (concat0 <$> y <*> z) infixr .++. (.++.) = bothRnns -- | Apply a function on the cell state(s) before running the cell itself. onStates :: (HTV t xs -> HTV t xs) -> RnnCell t xs a b -> RnnCell t xs a b onStates f cell x = C $ \h -> do runC (cell x) (f h) -- | Stack two RNN cells (LHS is run first) stackRnnCells, (.-.) :: forall s0 s1 a b c t. KnownLen s1 => RnnCell t s0 a b -> RnnCell t s1 b c -> RnnCell t (s1 ++ s0) a c stackRnnCells l1 l2 x = l1 x `bindC` l2 (.-.) = stackRnnCells -- | Compose two rnn cells in parallel. bothRnnCells, (.|.) :: forall s0 s1 a b c t bits. KnownLen s0 => KnownLen s1 => KnownBits bits => KnownNat b => KnownNat c => RnnCell t s0 a (T '[b] (Flt bits)) -> RnnCell t s1 a (T '[c] (Flt bits)) -> RnnCell t (s1 ++ s0) a (T '[b+c] (Flt bits)) bothRnnCells l1 l2 x = l1 x `bindC` \y -> l2 x `bindC` \z -> returnC (concat0 y z) (.|.) = bothRnnCells -- | Run the cell, and forward the input to the output, by -- concatenation with the output of the cell. This bypass is sometimes -- called a 'highway' in the literature. withBypass :: forall x y t b s0. KnownNat x => KnownNat y => KnownLen s0 => KnownTyp t => RnnCell b s0 (T '[x] t) (T '[y] t) -> RnnCell b s0 (T '[x] t) (T '[x+y] t) withBypass cell x = appRUnit @s0 #> cell x `bindC` \y -> returnC (concat0 x y) -- | Run the cell, and feeds its output as input to the next time-step withFeedback :: forall outputSize inputSize (w :: Typ) ss. KnownTyp w => KnownNat outputSize => KnownNat inputSize => RnnCell w ss (T '[inputSize+outputSize] w) (T '[outputSize] w) -> RnnCell w ('[outputSize] ': ss) (T '[inputSize ] w) (T '[outputSize] w) withFeedback cell x = C $ \(F prevoutputnVector :* s) -> let (s',y) = runC (cell (concat0 x prevoutputnVector)) s in (F y :* s',y) --------------------------------------------------------- -- RNN unfolding -- | Build a RNN by repeating a cell @n@ times. iterateCell :: ∀ n state input output b. (KnownNat n) => RnnCell b state input output -> Rnn n b state input output iterateCell c x = C $ \s -> chainForward (\(t,y) -> runC (c y) t) (s,x) -- | Build a RNN by repeating a cell @n@ times. However the state is -- propagated in the right-to-left direction (decreasing indices in -- the time dimension of the input and output tensors) iterateCellBackward :: ∀ n state input output b. (KnownNat n) => RnnCell b state input output -> Rnn n b state input output iterateCellBackward c x = C $ \s -> chainBackward (\(t,y) -> runC (c y) t) (s,x) -- | RNN helper chainForward :: ∀ state a b n. ((state , a) -> (state , b)) → (state , V n a) -> (state , V n b) chainForward _ (s0 , VUnit) = (s0 , VUnit) chainForward f (s0 , x :** xs) = let (s1,x') = f (s0 , x) (sFin,xs') = chainForward f (s1 , xs) in (sFin,(x':**xs')) -- | RNN helper chainBackward :: ∀ state a b n. ((state , a) -> (state , b)) → (state , V n a) -> (state , V n b) chainBackward _ (s0 , VUnit) = (s0 , VUnit) chainBackward f (s0 , (x:**xs)) = let (s1,xs') = chainBackward f (s0,xs) (sFin, x') = f (s1,x) in (sFin,(x':**xs')) -- | RNN helper chainForwardWithState :: ∀ state a b n. ((state , a) -> (state , b)) → (state , V n a) -> (V n b, V n state) chainForwardWithState _ (_s0 , VUnit) = (VUnit, VUnit) chainForwardWithState f (s0 , (x:**xs)) = let (s1,x') = f (s0 , x) (xs',ss) = chainForwardWithState f (s1 , xs) in ((x':**xs'), (s1:**ss) ) -- -- | RNN helper -- chainBackwardWithState :: -- ∀ state a b n. ((state , a) -> (state , b)) → (state , V n a) -> (state , V n b, V n state) -- chainBackwardWithState _ (s0 , VUnit) = return (s0 , VUnit, VUnit) -- chainBackwardWithState f (s0 , (x:**xs)) = do -- (s1,xs',ss') <- chainBackwardWithState f (s0,xs) -- (sFin, x') <- f (s1,x) -- return (sFin,(x':**xs'),(sFin:**ss')) -- | RNN helper transposeV :: forall n xs t. All KnownShape xs => KnownNat n => SList xs -> V n (HTV t xs) -> HTV t (Ap (FMap (Cons n)) xs) transposeV Unit _ = Unit transposeV (_ :* n) xxs = F ys' :* yys' where (ys,yys) = help @(Tail xs) xxs ys' = stack0 ys yys' = transposeV n yys help :: forall ys x tt. V n (HTV tt (x ': ys)) -> (V n (T x tt) , V n (HTV tt ys)) help (xs) = ((fmap (fromF . hhead) xs),(fmap htail xs)) -- | @(gatherFinalStates dynLen states)[i] = states[dynLen[i]-1]@ gatherFinalStates :: KnownShape x => KnownNat n => T '[] Int32 -> T (n ': x) t -> T x t gatherFinalStates dynLen states = gather states (dynLen ⊝ constant 1) gathers :: forall n xs t. All KnownShape xs => KnownNat n => SList xs -> T '[] Int32 -> HTV t (Ap (FMap (Cons n)) xs) -> HTV t xs gathers Unit _ Unit = Unit gathers (_ :* n) ixs (F x :* xs) = F (gatherFinalStates ixs x) :* gathers @n n ixs xs -- | @rnnWithCull dynLen@ constructs an RNN as normal, but returns the -- state after step @dynLen@ only. iterateWithCull :: forall n x y ls b. KnownLen ls => KnownNat n => All KnownShape ls => T '[] Int32 -- ^ dynamic length -> RnnCell b ls x y -> Rnn n b ls x y iterateWithCull dynLen cell xs = C $ \s0 -> let (us,ss) = chainForwardWithState (uncurry (flip (runC . cell))) (s0,xs) sss = transposeV @n (typeSList @ls) ss in (gathers @n (typeSList @ls) dynLen sss,us) -- -- | Like @rnnWithCull@, but states are threaded backwards. -- rnnBackwardsWithCull :: forall n bs x y ls b. -- KnownLen ls => KnownNat n => All KnownLen ls => All (LastEqual bs) ls => -- T '[bs] Int32 -> RnnCell b ls x y -> RNN n b ls x y -- rnnBackwardsWithCull dynLen cell (s0, t) = do -- (us,ss) <- chainBackwardWithState cell (s0,xs) -- let sss = transposeV @n (shapeSList @ls) ss -- return (gathers @n (shapeSList @ls) (n - dynLen) sss,us)
GU-CLASP/TypedFlow
TypedFlow/Layers/RNN/Base.hs
lgpl-3.0
11,022
0
20
2,420
3,660
2,011
1,649
180
1
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RecordWildCards #-} import Data.Char data Client = GovOrg String | Company String Integer Person String | Individual Person Bool deriving Show data Person = Person String String Gender deriving Show data Gender = Male | Female | Unknown deriving Show --Simple Pattern Marching clientName :: Client -> String clientName client = case client of GovOrg name -> name Company name id person resp -> name Individual person _ -> case person of Person fName lName gender -> fName ++ " " ++ lName clientNamev2 :: Client -> String clientNamev2 client = case client of GovOrg name -> name Company name _ _ _ -> name Individual (Person fname lname _) _ -> fname ++ " " ++ lname companyName :: Client -> Maybe String companyName client = case client of Company name _ _ _ -> Just name _ -> Nothing --mathematical functions writing way clientNamev3 :: Client -> String clientNamev3 (GovOrg name) = name clientNamev3 (Company name _ _ _) = name clientNamev3 (Individual (Person fname lname _) _) = fname ++ " " ++ lname fibonacci 0 = 0 fibonacci 1 = 1 fibonacci n = fibonacci (n-1) + fibonacci (n-2) sortedv1 :: Ord a => [a] -> Bool sortedv1 [] = True sortedv1 [_] = True sortedv1 (x:y:ys) = x < y && sortedv1 (y:ys) --using 'as pattern' sortedv2 :: Ord a => [a] -> Bool sortedv2 [] = True sortedv2 [_] = True sortedv2 (x:r@(y:_)) = x < y && sortedv2 r --binomialCoefficient :: Int Int -> Int binomialCoefficient _ 0 = 1 binomialCoefficient x y | x==y = 1 binomialCoefficient n k = binomialCoefficient (n-1) (k-1) + binomialCoefficient (n-1) k ackermann 0 n = n + 1 ackermann m 0 = ackermann (m-1) 1 ackermann m n = ackermann (m-1) (ackermann m (n-1)) --view pattern {-# LANGUAGE ViewPatterns #-} specialClient :: Client -> Bool specialClient (clientNamev3 -> "wang yixiang") = True specialClient _ = False data ClientR = GovOrgR { clientRName :: String} | CompanyR { clientRName :: String , companyId :: Integer , person :: PersonR , duty :: String } | IndividualR { person :: PersonR } deriving Show data PersonR = PersonR { firstName :: String ,lastName :: String } deriving Show greetv1 :: ClientR -> String greetv1 GovOrgR { clientRName = c } = "Welcome" greetv1 CompanyR { clientRName = c } = "Hello " ++ c greetv1 IndividualR { person = PersonR { firstName = c}} = "Hi " ++ c -- record puns {-# LANGUAGE NamedFieldPuns #-} greetv2 :: ClientR -> String greetv2 GovOrgR { clientRName } = "Welcome" greetv2 CompanyR { clientRName } = "Hello " ++ clientRName greetv2 IndividualR { person = PersonR { firstName}} = "Hi " ++ firstName -- two dots {-# LANGUAGE RecordWildCards #-} greetv3 :: ClientR -> String greetv3 GovOrgR { .. } = "Welcome" greetv3 CompanyR { .. } = "Hello " ++ clientRName greetv3 IndividualR { person = PersonR {..}} = "Hi " ++ firstName -- recording updating -- 很明显,下面的pattern matching 是一个非穷尽的 nameInCapitals :: PersonR -> PersonR nameInCapitals p@(PersonR { firstName = initial:rest }) = let newName = (toUpper initial):rest in p { firstName = newName}
wangyixiang/beginninghaskell
chapter2/src/Chapter2/DataTypes.hs
unlicense
3,154
18
12
623
1,122
593
529
-1
-1
{-# LANGUAGE RankNTypes #-} module Lib( patternCount, freqWords, revComp, clumps, indexes ) where import Prelude hiding (tail, length, take, drop) import Data.ByteString.Char8 (ByteString, tail, length, isPrefixOf, take, pack, unpack) import Data.ByteString.Char8 as BS hiding (head, map, takeWhile, reverse) import Data.List (sortBy) import Data.Maybe (fromMaybe) import Data.Set (Set) import Data.Set as Set hiding (map) import Data.HashTable.Class as H import Data.HashTable.ST.Basic as HT import Data.STRef (STRef, newSTRef, modifySTRef, readSTRef) import Control.Monad.ST (ST, runST) type Counts s = HT.HashTable s ByteString Int type CountsST s = ST s (Counts s) patternCount :: ByteString -> ByteString -> Int patternCount text pattern = let patLen = length pattern loop :: Int -> ByteString -> Int loop count text' | length text' < patLen = count | otherwise = loop (count + fromEnum (isPrefixOf pattern text')) (tail text') in loop 0 text freqWords :: ByteString -> Int -> [ByteString] freqWords text k = mostFreq $ Lib.toList (H.new >>= countAll text k) countAll :: ByteString -> Int -> Counts s -> CountsST s countAll text k counts | length text < k = return counts | otherwise = inc counts (take k text) >>= countAll (tail text) k inc :: Counts s -> ByteString -> CountsST s inc counts str = do curr <- fmap (fromMaybe 0) (H.lookup counts str) H.insert counts str (curr + 1) return counts toList :: (forall s. CountsST s) -> [(ByteString, Int)] toList counts = runST $ counts >>= H.toList mostFreq :: [(ByteString, Int)] -> [ByteString] mostFreq [] = [] mostFreq xs = let sorted = sortBy (\(_, x) (_, y) -> y `compare` x) xs highest = snd (head sorted) in map fst $ takeWhile (\x -> (snd x) == highest) sorted comp :: Char -> Char comp 'A' = 'T' comp 'T' = 'A' comp 'C' = 'G' comp 'G' = 'C' revComp :: ByteString -> ByteString revComp = pack . BS.foldl (\str c -> (comp c):str) [] indexes :: ByteString -> ByteString -> [Integer] indexes pat text = reverse $ loop 0 text [] where lenPat = length pat loop :: Integer -> ByteString -> [Integer] -> [Integer] loop x text' idxs | length text' < lenPat = idxs | otherwise = loop (x+1) (tail text') (if isPrefixOf pat text' then x:idxs else idxs) type ClumpSet s = STRef s (Set ByteString) clumps :: Int -> Int -> Int -> ByteString -> Set ByteString clumps k window times text = runST $ do counts <- H.new found <- newSTRef Set.empty init counts found 0 scan counts found text readSTRef found where toCurr = window - k init :: Counts s -> ClumpSet s -> Int -> ST s () init counts found t = do incAndMark counts found (take k . drop t $ text) if t + k == window then return () else init counts found (t+1) scan :: Counts s -> ClumpSet s -> ByteString -> ST s () scan counts found text = do dec counts (take k text) incAndMark counts found (take k . drop toCurr $ text) if length text == window then return () else scan counts found (tail text) incAndMark :: Counts s -> ClumpSet s -> ByteString -> ST s () incAndMark counts found str = do curr <- fmap (fromMaybe 0) (H.lookup counts str) let next = curr + 1 H.insert counts str next if next == times then modifySTRef found (Set.insert str) else return () dec :: Counts s -> ByteString -> ST s () dec counts str = do curr <- fmap (fromMaybe (error ("dec " ++ unpack str ++ " not there"))) (H.lookup counts str) H.insert counts str (curr - 1)
adambaker/bioinformatics
src/Lib.hs
unlicense
3,551
0
16
810
1,538
787
751
91
4
import System.Console.HsOptions import qualified Greeter as Greeter userIdFlag :: Flag Int userIdFlag = make ("user_id", "the user id of the app", [parser intParser, aliasIs ["u"]]) description :: String description = "Complex Haskell program\n" ++ "Just prints a simple message based on the input flags" database :: Flag (Maybe String) database = make ("database", "database connection string. required if user_id == -1", [maybeParser stringParser, aliasIs ["db"], requiredIf (\ fr -> get fr userIdFlag == -1)]) tellJoke :: Flag Bool tellJoke = make ("tell_joke", "tells a joke", boolFlag) profileMemory :: Flag Bool profileMemory = make ("profile_memory", "profiles the memory of the app", boolFlag) profileDisk :: Flag Bool profileDisk = make ("profile_disk", "profiles the disk usage of the app", boolFlag) flagData :: FlagData flagData = combine [ combine [ flagToData userIdFlag, flagToData database, flagToData tellJoke, flagToData profileMemory, flagToData profileDisk], Greeter.flagData, -- Global validation validate (\fr -> if get fr profileMemory && get fr profileDisk then Just "'--profile_memory' and '--profile_disk' can't be on at the same time" else Nothing) ] main_success :: ProcessResults -> IO () main_success (flags, argsResults) = do let userId = flags `get` userIdFlag -- get userId db = flags `get` database -- get database putStrLn $ "Main.hs: Args: " ++ show argsResults putStrLn $ "Main.hs: User id: " ++ show userId putStrLn $ "Main.hs: Database: " ++ show db -- Call other modules Greeter.sayHello flags putStrLn $ if flags `get` tellJoke then "I never make mistakes…I thought I did once; but I was wrong." else "Not a time for jokes." main :: IO () main = processMain description flagData main_success defaultDisplayErrors defaultDisplayHelp
josercruz01/hsoptions
examples/ComplexFlag.hs
apache-2.0
2,244
0
12
731
461
247
214
47
2
module CochleaPlus where -- CLaSH import CLaSH.Prelude as C -- Haskell import qualified Data.List as L replaceL xs i x = as L.++ [x] L.++ bs where (as,b:bs) = L.splitAt i xs True % t = 1 False % t = t -- Haskell upd hist t = replaceL hist t (hist L.!! t + 1) -- CLaSH c_upd hist t = replace hist t (hist !! t + 1) -- Haskell upd' hist (True,t) = upd hist t upd' hist (False,t) = hist -- CLaSH c_upd' hist (True,t) = c_upd hist t c_upd' hist (False,t) = hist -- Haskell frm (ws,ts,hist) vs = ((ws',ts',hist') , y) where zcs = L.zipWith (/=) (L.map (>=0) ws) (L.map (>=0) vs) ts' = L.zipWith (%) zcs (L.map (+1) ts) -- zts = map snd $ filter fst $ zip zcs ts zts = L.zip zcs ts hist' = L.foldl upd' hist zts ws' = vs y = hist' -- CLaSH c_frm (ws,ts,hist) vs = ((ws',ts',hist'),y) where zcs = zipWith (/=) (map (>=0) ws) (map (>=0) vs) ts' = zipWith (%) zcs (map (+1) ts) zts = zip zcs ts hist' = foldl c_upd' hist zts ws' = vs y = hist' topEntity :: Signal (Vec 6 Integer) -> Signal (Vec 12 Integer) topEntity = c_frm `mealy` (c_ws0,c_ts0,c_hist0) -- Haskell sim f s [] = [] sim f s (x:xs) = y : sim f s' xs where (s',y) = f s x -- CLaSH c_sim f i = L.take (L.length i) $ simulate f c_vss c_outp = c_sim topEntity c_vss -- =============================================== -- Haskell vss = [ [ 1 :: Int,-1,-1,-1, 1,-1 ] , [ 1, 1,-1,-1, 1, 1 ] , [ 1, 1, 1,-1, 1, 1 ] , [ 1, 1, 1, 1,-1, 1 ] , [ 1, 1, 1, 1,-1,-1 ] , [ -1, 1, 1, 1,-1,-1 ] , [ -1,-1, 1, 1, 1,-1 ] , [ -1,-1,-1, 1, 1, 1 ] , [ -1,-1,-1,-1, 1, 1 ] , [ -1,-1,-1,-1,-1, 1 ] , [ 1,-1,-1,-1,-1,-1 ] , [ 1, 1,-1,-1,-1,-1 ] , [ 1, 1, 1,-1, 1,-1 ] , [ 1, 1, 1, 1, 1, 1 ] , [ 1, 1, 1, 1, 1, 1 ] , [ -1, 1, 1, 1,-1, 1 ] , [ -1,-1, 1, 1,-1,-1 ] , [ -1,-1,-1, 1,-1,-1 ] , [ -1,-1,-1,-1, 1,-1 ] , [ -1,-1,-1,-1, 1, 1 ] ] -- CLaSH c_vss = [ $(v [ 1 :: Int,-1,-1,-1, 1,-1 ]) , $(v [ 1 :: Int, 1,-1,-1, 1, 1 ]) , $(v [ 1 :: Int, 1, 1,-1, 1, 1 ]) , $(v [ 1 :: Int, 1, 1, 1,-1, 1 ]) , $(v [ 1 :: Int, 1, 1, 1,-1,-1 ]) , $(v [ -1 :: Int, 1, 1, 1,-1,-1 ]) , $(v [ -1 :: Int,-1, 1, 1, 1,-1 ]) , $(v [ -1 :: Int,-1,-1, 1, 1, 1 ]) , $(v [ -1 :: Int,-1,-1,-1, 1, 1 ]) , $(v [ -1 :: Int,-1,-1,-1,-1, 1 ]) , $(v [ 1 :: Int,-1,-1,-1,-1,-1 ]) , $(v [ 1 :: Int, 1,-1,-1,-1,-1 ]) , $(v [ 1 :: Int, 1, 1,-1, 1,-1 ]) , $(v [ 1 :: Int, 1, 1, 1, 1, 1 ]) , $(v [ 1 :: Int, 1, 1, 1, 1, 1 ]) , $(v [ -1 :: Int, 1, 1, 1,-1, 1 ]) , $(v [ -1 :: Int,-1, 1, 1,-1,-1 ]) , $(v [ -1 :: Int,-1,-1, 1,-1,-1 ]) , $(v [ -1 :: Int,-1,-1,-1, 1,-1 ]) , $(v [ -1 :: Int,-1,-1,-1, 1, 1 ]) ] -- Haskell ws0 = [0 :: Int,-1,-1,-1,0,-1] ts0 = [0 :: Int,0,0,0,0,0] hist0 = [0 :: Int,0,0,0,0,0,0,0,0,0,0,0] -- CLaSH c_ws0 = $(v [0 :: Int,-1,-1,-1,0,-1]) c_ts0 = $(v [0 :: Int,0,0,0,0,0]) c_hist0 = $(v [0 :: Int,0,0,0,0,0,0,0,0,0,0,0])
christiaanb/clash-compiler
examples/CochleaPlus.hs
bsd-2-clause
3,246
0
10
1,143
2,195
1,305
890
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE Unsafe #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_HADDOCK not-home #-} ----------------------------------------------------------------------------- -- | -- Copyright : (C) 2015 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : non-portable -- ----------------------------------------------------------------------------- module Data.Struct.Internal where import Control.Exception import Control.Monad.Primitive import Control.Monad.ST import Data.Primitive import Data.Coerce import GHC.Exts import GHC.ST #ifdef HLINT {-# ANN module "HLint: ignore Eta reduce" #-} {-# ANN module "HLint: ignore Unused LANGUAGE pragma" #-} #endif data NullPointerException = NullPointerException deriving (Show, Exception) data Dict p where Dict :: p => Dict p -- | Run an ST calculation inside of a PrimMonad. This lets us avoid dispatching everything through the 'PrimMonad' dictionary. st :: PrimMonad m => ST (PrimState m) a -> m a st (ST f) = primitive f {-# INLINE[0] st #-} {-# RULES "st/id" st = id #-} class Struct t where struct :: p t -> Dict (Coercible (t s) (Object s)) data Object s = Object { runObject :: SmallMutableArray# s Any } instance Struct Object where struct _ = Dict -- TODO: get these to dispatch fast through 'coerce' using struct as a witness destruct :: Struct t => t s -> SmallMutableArray# s Any destruct x = runObject (unsafeCoerce# x) construct :: Struct t => SmallMutableArray# s Any -> t s construct x = unsafeCoerce# (Object x) unsafeCoerceStruct :: (Struct x, Struct y) => x s -> y s unsafeCoerceStruct x = unsafeCoerce# x eqStruct :: Struct t => t s -> t s -> Bool eqStruct x y = isTrue# (destruct x `sameSmallMutableArray#` destruct y) {-# INLINE eqStruct #-} instance Eq (Object s) where (==) = eqStruct -- instance Struct Object s where -- construct = Object -- destruct = runObject #ifndef HLINT pattern Struct :: () => Struct t => SmallMutableArray# s Any -> t s pattern Struct x <- (destruct -> x) where Struct x = construct x #endif -- | Allocate a structure made out of `n` slots. Initialize the structure before proceeding! alloc :: (PrimMonad m, Struct t) => Int -> m (t (PrimState m)) alloc (I# n#) = primitive $ \s -> case newSmallArray# n# undefined s of (# s', b #) -> (# s', construct b #) -------------------------------------------------------------------------------- -- * Tony Hoare's billion dollar mistake -------------------------------------------------------------------------------- data Box = Box !Null data Null = Null isNil :: Struct t => t s -> Bool isNil t = isTrue# (unsafeCoerce# reallyUnsafePtrEquality# (destruct t) Null) {-# INLINE isNil #-} #ifndef HLINT -- | Truly imperative. pattern Nil :: forall t s. () => Struct t => t s pattern Nil <- (isNil -> True) where Nil = unsafeCoerce# Box Null #endif -------------------------------------------------------------------------------- -- * Faking SmallMutableArrayArray#s -------------------------------------------------------------------------------- writeSmallMutableArraySmallArray# :: SmallMutableArray# s Any -> Int# -> SmallMutableArray# s Any -> State# s -> State# s writeSmallMutableArraySmallArray# m i a s = unsafeCoerce# writeSmallArray# m i a s {-# INLINE writeSmallMutableArraySmallArray# #-} readSmallMutableArraySmallArray# :: SmallMutableArray# s Any -> Int# -> State# s -> (# State# s, SmallMutableArray# s Any #) readSmallMutableArraySmallArray# m i s = unsafeCoerce# readSmallArray# m i s {-# INLINE readSmallMutableArraySmallArray# #-} writeMutableByteArraySmallArray# :: SmallMutableArray# s Any -> Int# -> MutableByteArray# s -> State# s -> State# s writeMutableByteArraySmallArray# m i a s = unsafeCoerce# writeSmallArray# m i a s {-# INLINE writeMutableByteArraySmallArray# #-} readMutableByteArraySmallArray# :: SmallMutableArray# s Any -> Int# -> State# s -> (# State# s, MutableByteArray# s #) readMutableByteArraySmallArray# m i s = unsafeCoerce# readSmallArray# m i s {-# INLINE readMutableByteArraySmallArray# #-} -------------------------------------------------------------------------------- -- * Field Accessors -------------------------------------------------------------------------------- -- | A "Slot" is a reference to another unboxed mutable object. data Slot x y = Slot (forall s. SmallMutableArray# s Any -> State# s -> (# State# s, SmallMutableArray# s Any #)) (forall s. SmallMutableArray# s Any -> SmallMutableArray# s Any -> State# s -> State# s) -- | We can compose slots to get a nested slot or field accessor class Precomposable t where ( # ) :: Slot x y -> t y z -> t x z instance Precomposable Slot where Slot gxy _ # Slot gyz syz = Slot (\x s -> case gxy x s of (# s', y #) -> gyz y s') (\x z s -> case gxy x s of (# s', y #) -> syz y z s') slot :: Int -> Slot s t slot (I# i) = Slot (\m s -> readSmallMutableArraySmallArray# m i s) (\m a s -> writeSmallMutableArraySmallArray# m i a s) -- | Get the value from a 'Slot' get :: (PrimMonad m, Struct x, Struct y) => Slot x y -> x (PrimState m) -> m (y (PrimState m)) get (Slot go _) x = primitive $ \s -> case go (destruct x) s of (# s', y #) -> (# s', construct y #) {-# INLINE get #-} -- | Set the value of a 'Slot' set :: (PrimMonad m, Struct x, Struct y) => Slot x y -> x (PrimState m) -> y (PrimState m) -> m () set (Slot _ go) x y = primitive_ (go (destruct x) (destruct y)) {-# INLINE set #-} -- | A "Field" is a reference from a struct to a normal Haskell data type. data Field x a = Field (forall s. SmallMutableArray# s Any -> State# s -> (# State# s, a #)) (forall s. SmallMutableArray# s Any -> a -> State# s -> State# s) instance Precomposable Field where Slot gxy _ # Field gyz syz = Field (\x s -> case gxy x s of (# s', y #) -> gyz y s') (\x z s -> case gxy x s of (# s', y #) -> syz y z s') -- | Store the reference to the Haskell data type in a normal field field :: Int -> Field s a field (I# i) = Field (\m s -> unsafeCoerce# readSmallArray# m i s) (\m a s -> unsafeCoerce# writeSmallArray# m i a s) {-# INLINE field #-} -- | Store the reference in the nth slot of the nth argument, treated as a MutableByteArray unboxedField :: Prim a => Int -> Int -> Field s a unboxedField (I# i) (I# j) = Field (\m s -> case readMutableByteArraySmallArray# m i s of (# s', mba #) -> readByteArray# mba j s') (\m a s -> case readMutableByteArraySmallArray# m i s of (# s', mba #) -> writeByteArray# mba j a s') {-# INLINE unboxedField #-} -- | Get the value of a field in a struct getField :: (PrimMonad m, Struct x) => Field x a -> x (PrimState m) -> m a getField (Field go _) x = primitive (go (destruct x)) {-# INLINE getField #-} -- | Set the value of a field in a struct setField :: (PrimMonad m, Struct x) => Field x a -> x (PrimState m) -> a -> m () setField (Field _ go) x y = primitive_ (go (destruct x) y) {-# INLINE setField #-}
bitemyapp/structs
src/Data/Struct/Internal.hs
bsd-2-clause
7,377
0
12
1,341
2,080
1,072
1,008
119
1
-- http://www.codewars.com/kata/5464cbfb1e0c08e9b3000b3e module IsHappy where import Control.Arrow isHappy :: Integer -> Bool isHappy x = findCycle x == 1 where findCycle = fst . head . dropWhile (\(a,b) -> a/=b) . iterate (step . step *** step) . (step . step &&& step) step = sum . map ((^2) . (`mod`10)) . takeWhile (>0) . iterate (`div`10)
Bodigrim/katas
src/haskell/B-Happy-numbers.hs
bsd-2-clause
355
0
13
68
156
88
68
-1
-1
{-# LANGUAGE TypeOperators, GADTs, ScopedTypeVariables #-} ----------------------------------------------------------------------------- -- | -- Module : Application.HXournal.Accessor -- Copyright : (c) 2011, 2012 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <ianwookim@gmail.com> -- Stability : experimental -- Portability : GHC -- ----------------------------------------------------------------------------- module Application.HXournal.Accessor where import Application.HXournal.Type import Control.Applicative import Control.Monad hiding (mapM_) import qualified Control.Monad.State as St hiding (mapM_) import Control.Monad.Trans import Control.Category import qualified Data.IntMap as M import Data.Label import Graphics.UI.Gtk hiding (get,set) import qualified Graphics.UI.Gtk as Gtk (set) import Data.Foldable import Data.Monoid import Data.Xournal.BBox import Data.Xournal.Generic import Application.HXournal.ModelAction.Layer import Application.HXournal.Type.Alias import Application.HXournal.Type.PageArrangement import Application.HXournal.View.Coordinate import Prelude hiding ((.),id,mapM_) -- | get HXournalState getSt :: MainCoroutine HXournalState getSt = lift St.get -- | put HXournalState putSt :: HXournalState -> MainCoroutine () putSt = lift . St.put -- | update state updateXState :: (HXournalState -> MainCoroutine HXournalState) -> MainCoroutine () updateXState action = putSt =<< action =<< getSt -- | getPenType :: MainCoroutine PenType getPenType = get (penType.penInfo) <$> lift (St.get) -- | getCurrentPageCurr :: MainCoroutine (Page EditMode) getCurrentPageCurr = do xstate <- getSt let xojstate = get xournalstate xstate cinfobox = get currentCanvasInfo xstate case cinfobox of CanvasInfoBox cinfo -> return (getCurrentPageFromXojState cinfo xojstate) -- | getCurrentPageCvsId :: CanvasId -> MainCoroutine (Page EditMode) getCurrentPageCvsId cid = do xstate <- getSt let xojstate = get xournalstate xstate cinfobox = getCanvasInfo cid xstate case cinfobox of CanvasInfoBox cinfo -> return (getCurrentPageFromXojState cinfo xojstate) -- | getCurrentPageEitherFromXojState :: (ViewMode a) => CanvasInfo a -> XournalState -> Either (Page EditMode) (Page SelectMode) getCurrentPageEitherFromXojState cinfo xojstate = let cpn = get currentPageNum cinfo page = getCurrentPageFromXojState cinfo xojstate in case xojstate of ViewAppendState _xoj -> Left page SelectState txoj -> case get g_selectSelected txoj of Nothing -> Left page Just (n,tpage) -> if cpn == n then Right tpage else Left page -- | getAllStrokeBBoxInCurrentPage :: MainCoroutine [StrokeBBox] getAllStrokeBBoxInCurrentPage = do page <- getCurrentPageCurr return [s| l <- gToList (get g_layers page), s <- get g_bstrokes l ] -- | getAllStrokeBBoxInCurrentLayer :: MainCoroutine [StrokeBBox] getAllStrokeBBoxInCurrentLayer = do page <- getCurrentPageCurr let (mcurrlayer, _currpage) = getCurrentLayerOrSet page currlayer = maybe (error "getAllStrokeBBoxInCurrentLayer") id mcurrlayer return (get g_bstrokes currlayer) -- | otherCanvas :: HXournalState -> [Int] otherCanvas = M.keys . getCanvasInfoMap -- | changeCurrentCanvasId :: CanvasId -> MainCoroutine HXournalState changeCurrentCanvasId cid = do xstate1 <- getSt maybe (return xstate1) (\xst -> do putSt xst return xst) (setCurrentCanvasId cid xstate1) xst <- getSt let cinfo = get currentCanvasInfo xst ui = get gtkUIManager xst reflectUI ui cinfo return xst -- | reflect UI for current canvas info reflectUI :: UIManager -> CanvasInfoBox -> MainCoroutine () reflectUI ui cinfobox = do xstate <- getSt let mconnid = get pageModeSignal xstate liftIO $ maybe (return ()) signalBlock mconnid agr <- liftIO $ uiManagerGetActionGroups ui Just ra1 <- liftIO $ actionGroupGetAction (head agr) "ONEPAGEA" selectBoxAction (fsingle ra1) (fcont ra1) cinfobox liftIO $ maybe (return ()) signalUnblock mconnid return () where fsingle ra1 _cinfo = do let wra1 = castToRadioAction ra1 liftIO $ Gtk.set wra1 [radioActionCurrentValue := 1 ] fcont ra1 _cinfo = do liftIO $ Gtk.set (castToRadioAction ra1) [radioActionCurrentValue := 0 ] -- | printViewPortBBox :: CanvasId -> MainCoroutine () printViewPortBBox cid = do cvsInfo <- return . getCanvasInfo cid =<< getSt liftIO $ putStrLn $ show (unboxGet (viewPortBBox.pageArrangement.viewInfo) cvsInfo) -- | printViewPortBBoxAll :: MainCoroutine () printViewPortBBoxAll = do xstate <- getSt let cmap = getCanvasInfoMap xstate cids = M.keys cmap mapM_ printViewPortBBox cids -- | printViewPortBBoxCurr :: MainCoroutine () printViewPortBBoxCurr = do cvsInfo <- return . get currentCanvasInfo =<< getSt liftIO $ putStrLn $ show (unboxGet (viewPortBBox.pageArrangement.viewInfo) cvsInfo) -- | printModes :: CanvasId -> MainCoroutine () printModes cid = do cvsInfo <- return . getCanvasInfo cid =<< getSt liftIO $ printCanvasMode cid cvsInfo -- | printCanvasMode :: CanvasId -> CanvasInfoBox -> IO () printCanvasMode cid cvsInfo = do let zmode = unboxGet (zoomMode.viewInfo) cvsInfo f :: PageArrangement a -> String f (SingleArrangement _ _ _) = "SingleArrangement" f (ContinuousSingleArrangement _ _ _ _) = "ContinuousSingleArrangement" g :: CanvasInfo a -> String g cinfo = f . get (pageArrangement.viewInfo) $ cinfo arrmode :: String arrmode = boxAction g cvsInfo incid = unboxGet canvasId cvsInfo putStrLn $ show (cid,incid,zmode,arrmode) -- | printModesAll :: MainCoroutine () printModesAll = do xstate <- getSt let cmap = getCanvasInfoMap xstate cids = M.keys cmap mapM_ printModes cids -- | getCanvasGeometryCvsId :: CanvasId -> HXournalState -> IO CanvasGeometry getCanvasGeometryCvsId cid xstate = do let cinfobox = getCanvasInfo cid xstate cpn = PageNum . unboxGet currentPageNum $ cinfobox canvas = unboxGet drawArea cinfobox fsingle :: (ViewMode a) => CanvasInfo a -> IO CanvasGeometry fsingle = flip (makeCanvasGeometry cpn) canvas . get (pageArrangement.viewInfo) boxAction fsingle cinfobox -- | getGeometry4CurrCvs :: HXournalState -> IO CanvasGeometry getGeometry4CurrCvs xstate = do let cinfobox = get currentCanvasInfo xstate cpn = PageNum . unboxGet currentPageNum $ cinfobox canvas = unboxGet drawArea cinfobox fsingle :: (ViewMode a) => CanvasInfo a -> IO CanvasGeometry fsingle = flip (makeCanvasGeometry cpn) canvas . get (pageArrangement.viewInfo) boxAction fsingle cinfobox -- | bbox4AllStrokes :: (Foldable t, Functor t) => t StrokeBBox -> ULMaybe BBox bbox4AllStrokes = unUnion . fold . fmap (Union . Middle . strokebbox_bbox)
wavewave/hxournal
lib/Application/HXournal/Accessor.hs
bsd-2-clause
7,251
2
14
1,657
1,891
962
929
152
4
module Main where import qualified Lib as L main :: IO () main = L.printHello
taskell/helloworld
app/Main.hs
bsd-3-clause
81
0
6
18
27
17
10
4
1
{-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} module Synth.Synth where import Synth.SGD import Synth.RTypeFilterGuess import Synth.StructuralRefinement import Analysis.FilterDistance import Types.Common import Types.Filter import Types.DSPNode import Types.SCCode import qualified Settings as S import Utils import Control.Monad import qualified Codec.Wav as W import qualified Data.HashMap.Strict as H import qualified Data.Map as M import System.Random import System.FilePath -- | The main runner for DSP-PBE -- this is a wrapper that handles the file io for runSynth synthCode :: S.Options -> IO (Filter, Double, Int) synthCode settings@S.SynthesisOptions{..} = do S.checkOptions settings fileActions <- mapM W.importFile [inputExample,outputExample] :: IO [Either String (AudioFormat)] (solutionProgram, score, structureAttempts) <- case sequence fileActions of Right fs -> do runSynth settings (head fs) (head $ tail fs) Left e -> error e debugPrint $ toSCCode solutionProgram if targetAudioPath /= "" then runFilter resultantAudioPath targetAudioPath (toVivid solutionProgram) 10 >> return () else runFilter ("final/"++(takeBaseName outputExample)++"-synth.wav") inputExample (toVivid solutionProgram) 10 >> return () return (solutionProgram, score, structureAttempts) -- | Kicks off synthesis by using the user-provided refinements to select an initFilter -- then enters the synthesis loop runSynth :: S.Options -> AudioFormat -> AudioFormat -> IO (Filter, Double, Int) runSynth settings@S.SynthesisOptions{..} in_audio out_audio = do initFilter <- guessInitFilter (inputExample,in_audio) (outputExample,out_audio) debugPrint "Starting with best filter as:" debugPrint $ show initFilter synthLoop settings out_audio M.empty initFilter -- | If we scored below the user provided threshold, we are done -- If not we dervive new constraints on synthesis and try again synthLoop :: S.Options -> AudioFormat -> FilterLog -> Filter -> IO (Filter, Double, Int) synthLoop settings@S.SynthesisOptions{..} out_audio prevFLog prevFilter = do debugPrint "Initiating strucutral synthesis..." initFilter <- if prevFLog == M.empty --special case to catch the first time through the loop then return $ prevFilter else structuralRefinement settings out_audio prevFLog debugPrint "Found a program structure:" debugPrint $ show initFilter debugPrint "Initiating metrical synthesis..." debugPrint $ show $ M.size prevFLog (synthedFilter, score, fLog) <- parameterTuning settings inputExample (outputExample,out_audio) initFilter debugPrint $ show $ M.size fLog --let newFLog = M.union fLog prevFLog let newFLog = M.insert synthedFilter score prevFLog if score < epsilon || M.size newFLog > filterLogSizeTimeout || abs (score - (snd $ findMinByVal (M.union (M.fromList [(synthedFilter,99999)]) prevFLog))) < converganceGoal then do debugPrint $ ("Finished synthesis with score: "++ (show $ snd $ findMinByVal newFLog)) return (fst $ findMinByVal newFLog, snd $ findMinByVal newFLog, M.size newFLog) else do synthLoop settings out_audio newFLog synthedFilter -- | This uses stochastic gradient descent to find a minimal cost theta -- SGD is problematic since we cannot analytically calculate a derivative of the cost function as the cost function is in IO -- TODO Another option might be to use http://www.jhuapl.edu/SPSA/ which does not require the derivative -- TODO many options here https://www.reddit.com/r/MachineLearning/comments/2e8797/gradient_descent_without_a_derivative/ parameterTuning :: S.Options -> FilePath -> (FilePath, AudioFormat) -> Filter -> IO (Filter, Double, FilterLog) parameterTuning settings in_audio_fp (out_fp, out_audio) initF = do let costFxn = testFilter in_audio_fp (out_fp, out_audio) let rGen = mkStdGen 0 debugPrint $ show initF initCost <- costFxn initF solution <- multiVarSGD settings costFxn rGen (M.singleton initF initCost) (extractThetaUpdaters initF) initF return solution
aedanlombardo/HaskellPS
DSP-PBE/src/Synth/Synth.hs
bsd-3-clause
4,172
0
21
701
994
513
481
72
3
{-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE NoImplicitPrelude #-} module Language.Fay.JQuery where import Language.Fay.Prelude import Language.Fay.FFI data JQuery instance Foreign JQuery instance Show JQuery ready :: Fay () -> Fay () ready = ffi "window['jQuery'](%1)"
jhickner/fay-three
Language/Fay/JQuery.hs
bsd-3-clause
275
0
7
39
65
36
29
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Text.XmlHtml.XML.Render where import Blaze.ByteString.Builder import Data.Char import Data.Maybe import Data.Monoid import Text.XmlHtml.Common import Data.Text (Text) import qualified Data.Text as T ------------------------------------------------------------------------------ render :: Encoding -> Maybe DocType -> [Node] -> Builder render e dt ns = byteOrder `mappend` xmlDecl e `mappend` docTypeDecl e dt `mappend` nodes where byteOrder | isUTF16 e = fromText e "\xFEFF" -- byte order mark | otherwise = mempty nodes | null ns = mempty | otherwise = node e (head ns) `mappend` (mconcat $ map (node e) (tail ns)) ------------------------------------------------------------------------------ -- | Function for rendering XML nodes without the overhead of creating a -- Document structure. renderXmlFragment :: Encoding -> [Node] -> Builder renderXmlFragment _ [] = mempty renderXmlFragment e (n:ns) = node e n `mappend` (mconcat $ map (node e) ns) ------------------------------------------------------------------------------ xmlDecl :: Encoding -> Builder xmlDecl e = fromText e "<?xml version=\"1.0\" encoding=\"" `mappend` fromText e (encodingName e) `mappend` fromText e "\"?>\n" ------------------------------------------------------------------------------ docTypeDecl :: Encoding -> Maybe DocType -> Builder docTypeDecl _ Nothing = mempty docTypeDecl e (Just (DocType tag ext int)) = fromText e "<!DOCTYPE " `mappend` fromText e tag `mappend` externalID e ext `mappend` internalSubset e int `mappend` fromText e ">\n" ------------------------------------------------------------------------------ externalID :: Encoding -> ExternalID -> Builder externalID _ NoExternalID = mempty externalID e (System sid) = fromText e " SYSTEM " `mappend` sysID e sid externalID e (Public pid sid) = fromText e " PUBLIC " `mappend` pubID e pid `mappend` fromText e " " `mappend` sysID e sid ------------------------------------------------------------------------------ internalSubset :: Encoding -> InternalSubset -> Builder internalSubset _ NoInternalSubset = mempty internalSubset e (InternalText t) = fromText e " " `mappend` fromText e t ------------------------------------------------------------------------------ sysID :: Encoding -> Text -> Builder sysID e sid | not ("\'" `T.isInfixOf` sid) = fromText e "\'" `mappend` fromText e sid `mappend` fromText e "\'" | not ("\"" `T.isInfixOf` sid) = fromText e "\"" `mappend` fromText e sid `mappend` fromText e "\"" | otherwise = error "SYSTEM id is invalid" ------------------------------------------------------------------------------ pubID :: Encoding -> Text -> Builder pubID e sid | not ("\"" `T.isInfixOf` sid) = fromText e "\"" `mappend` fromText e sid `mappend` fromText e "\"" | otherwise = error "PUBLIC id is invalid" ------------------------------------------------------------------------------ node :: Encoding -> Node -> Builder node e (TextNode t) = escaped "<>&" e t node e (Comment t) | "--" `T.isInfixOf` t = error "Invalid comment" | "-" `T.isSuffixOf` t = error "Invalid comment" | otherwise = fromText e "<!--" `mappend` fromText e t `mappend` fromText e "-->" node e (Element t a c) = element e t a c ------------------------------------------------------------------------------ -- | Process the first node differently to encode leading whitespace. This -- lets us be sure that @parseXML@ is a left inverse to @render@. firstNode :: Encoding -> Node -> Builder firstNode e (Comment t) = node e (Comment t) firstNode e (Element t a c) = node e (Element t a c) firstNode _ (TextNode "") = mempty firstNode e (TextNode t) = let (c,t') = fromJust $ T.uncons t in escaped "<>& \t\r\n" e (T.singleton c) `mappend` node e (TextNode t') ------------------------------------------------------------------------------ escaped :: [Char] -> Encoding -> Text -> Builder escaped _ _ "" = mempty escaped bad e t = let (p,s) = T.break (`elem` bad) t r = T.uncons s in fromText e p `mappend` case r of Nothing -> mempty Just (c,ss) -> entity e c `mappend` escaped bad e ss ------------------------------------------------------------------------------ entity :: Encoding -> Char -> Builder entity e '&' = fromText e "&amp;" entity e '<' = fromText e "&lt;" entity e '>' = fromText e "&gt;" entity e '\"' = fromText e "&quot;" entity e c = fromText e "&#" `mappend` fromText e (T.pack (show (ord c))) `mappend` fromText e ";" ------------------------------------------------------------------------------ element :: Encoding -> Text -> [(Text, Text)] -> [Node] -> Builder element e t a [] = fromText e "<" `mappend` fromText e t `mappend` (mconcat $ map (attribute e) a) `mappend` fromText e "/>" element e t a c = fromText e "<" `mappend` fromText e t `mappend` (mconcat $ map (attribute e) a) `mappend` fromText e ">" `mappend` (mconcat $ map (node e) c) `mappend` fromText e "</" `mappend` fromText e t `mappend` fromText e ">" ------------------------------------------------------------------------------ attribute :: Encoding -> (Text, Text) -> Builder attribute e (n,v) | not ("\'" `T.isInfixOf` v) = fromText e " " `mappend` fromText e n `mappend` fromText e "=\'" `mappend` escaped "<&" e v `mappend` fromText e "\'" | otherwise = fromText e " " `mappend` fromText e n `mappend` fromText e "=\"" `mappend` escaped "<&\"" e v `mappend` fromText e "\""
silkapp/xmlhtml
src/Text/XmlHtml/XML/Render.hs
bsd-3-clause
7,033
0
15
2,437
1,810
944
866
112
2
{-# OPTIONS_GHC -fdefer-typed-holes #-} -- Imports module Lib where import Control.Monad.Omega import Data.Foldable (asum, toList) import Data.List (group, sortBy) import Data.Map (Map) import qualified Data.Map as M import Data.Monoid ((<>)) import Control.Monad.State import Control.Monad.Writer -- Definitions and functions for BinTree data BinTree = Leaf | Branch BinTree BinTree deriving (Show, Eq) generationOrder :: BinTree -> BinTree -> Ordering generationOrder Leaf Leaf = EQ generationOrder Leaf (Branch _ _) = LT generationOrder (Branch _ _) Leaf = GT generationOrder b1@(Branch b11 b12) b2@(Branch b21 b22) = compare (depth b1) (depth b2) <> generationOrder b11 b21 <> generationOrder b12 b22 depth :: BinTree -> Int depth Leaf = 0 depth (Branch b1 b2) = 1 + max (depth b1) (depth b2) allBinTrees :: Omega BinTree allBinTrees = asum [pure Leaf, Branch <$> allBinTrees <*> allBinTrees] sufficientBinTrees :: Int -> [BinTree] sufficientBinTrees n = take n . uniq . take (4*n) $ runOmega allBinTrees uniq :: [BinTree] -> [BinTree] uniq = map head . group . sortBy generationOrder -- Le mappe di traduzione T ed S data TwoMaps = TwoMaps { t :: Map BinTree Int , s :: Map Int Int } deriving (Show) type M a = WriterT [String] (StateT TwoMaps []) a computation :: M a computation = undefined equation :: BinTree -> BinTree -> BinTree -> M a equation b1 b2 b3 = do twoMaps <- get tell ["Checking for b1 in the state"] tB1 <- if M.member b1 (t twoMaps) then lift . lift . toList $ M.lookup b1 (t twoMaps) else _where return _what
meditans/generalCompilator2
src/Lib.hs
bsd-3-clause
1,825
0
12
548
587
312
275
42
2
-- | A data references URL. module Data.ByteString.IsoBaseFileFormat.Boxes.DataEntryUrl ( DataEntryUrl (), localMediaDataEntryUrl, dataEntryUrl, ) where import Data.ByteString.IsoBaseFileFormat.Box import Data.ByteString.IsoBaseFileFormat.ReExports import Data.ByteString.IsoBaseFileFormat.Util.BoxContent import Data.ByteString.IsoBaseFileFormat.Util.FullBox import qualified Data.Text as T -- | A container for a URL or an indicator for local only media newtype DataEntryUrl = DataEntryUrl (Maybe T.Text) deriving (Default, IsBoxContent) -- | Create a 'DataEntryUrl' box for local media entry with the flag set and -- empty content. localMediaDataEntryUrl :: Box (FullBox DataEntryUrl 0) localMediaDataEntryUrl = dataEntryUrl True Nothing -- | Create a 'DataEntryUrl' box. The flag determines if the url is local, i.e. -- the media data is in the same file. dataEntryUrl :: Bool -> Maybe T.Text -> Box (FullBox DataEntryUrl 0) dataEntryUrl isLocal Nothing = Box (FullBox (fromIntegral $ fromEnum isLocal) $ DataEntryUrl Nothing) dataEntryUrl isLocal murl = Box (FullBox (fromIntegral $ fromEnum isLocal) $ DataEntryUrl murl) instance IsBox DataEntryUrl type instance BoxTypeSymbol DataEntryUrl = "url "
sheyll/isobmff-builder
src/Data/ByteString/IsoBaseFileFormat/Boxes/DataEntryUrl.hs
bsd-3-clause
1,231
0
11
177
239
136
103
-1
-1
{-# LANGUAGE PackageImports #-} {-# LANGUAGE UnicodeSyntax #-} module Test.Complexity.Sensors ( -- *Sensors Sensor , criterionSensor ) where ------------------------------------------------------------------------------- -- Imports ------------------------------------------------------------------------------- import "this" Test.Complexity.Types ( Action ) import "criterion" Criterion ( Benchmarkable, runBenchmark ) import "criterion" Criterion.Config ( Config ) import "criterion" Criterion.Monad ( withConfig ) import "criterion" Criterion.Environment ( Environment ) import "vector" Data.Vector.Unboxed ( Vector ) ------------------------------------------------------------------------------- -- Sensors ------------------------------------------------------------------------------- -- |Function that measures some aspect of the execution of an action. type Sensor α β = Action α β → α → IO (Vector Double) criterionSensor ∷ (Benchmarkable β) ⇒ Environment → Config → Sensor α β criterionSensor env conf action x = withConfig conf $ runBenchmark env $ action x
roelvandijk/complexity
Test/Complexity/Sensors.hs
bsd-3-clause
1,116
0
9
141
182
109
73
15
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE KindSignatures #-} -- | An attempt at modeling observables in Haskell. module Observable where import Prelude hiding (initMutable) import Data.IORef import Control.Monad import Control.Monad.ST import Data.STRef import Test.Hspec import GHC.Types import qualified Data.IntMap.Strict as Map class (Monad m) => Stateful m where initMutable :: state -> m (MutableRef m state) class Mutable ref where get :: ref m state -> m state set :: ref m state -> state -> m () data MutableRef m state = MkMutableRef { getter :: m state, setter :: state -> m () } instance Mutable MutableRef where get (MkMutableRef getter _) = getter set (MkMutableRef _ setter) = setter instance Stateful IO where initMutable :: forall state. state -> IO (MutableRef IO state) initMutable s = do ref <- newIORef s let getter = readIORef ref setter = writeIORef ref return $ MkMutableRef getter setter instance Stateful (ST t) where initMutable :: state -> (ST t) (MutableRef (ST t) state) initMutable s = do ref <- newSTRef s let get = readSTRef ref set = writeSTRef ref return $ MkMutableRef get set -- | Take 1: -- -- An observable is mutable, mutable reference, in which the setter is mutated. -- -- Issues: -- - Cannot deregister callbacks -- - Unwieldy (to get value, one must (get >=> get)) registerTake1 :: forall (m :: Type -> Type) (state :: Type). (Stateful m) => MutableRef m (MutableRef m state) -> (state -> m ()) -> m () registerTake1 refref cb = do let MkMutableRef getRef setRef = refref MkMutableRef oldGet oldSet <- getRef setRef $ MkMutableRef oldGet (\state -> oldSet state >> cb state) -- | Take 2: -- -- An observable is mutable reference of some state, along with some mutable reference of a collection of callbacks. -- -- Issues: -- - Memory leaks data ObservableRef m state = MkObservableRef { getter :: m state, setter :: state -> m (), registerer :: (state -> m ()) -> m (m ()) } class Mutable ref => Observable ref where register :: ref m state -> (state -> m ()) -> m (m ()) makeObservable :: forall m state. Stateful m => MutableRef m state -> m (ObservableRef m state) makeObservable (MkMutableRef originalGetter originalSetter) = do idRef <- initMutable (0 :: Int) let freshId :: m Int freshId = do newId <- get idRef set idRef (newId + 1) return newId callbacksRef <- initMutable (Map.fromList [] :: Map.IntMap (state -> m ())) let newSetter :: state -> m () newSetter state = do originalSetter state callbacks <- get callbacksRef mapM_ ($state) $ fmap snd $ Map.toList callbacks register :: (state -> m ()) -> m (m ()) register cb = do callbacks <- get callbacksRef id <- freshId set callbacksRef (Map.insert id cb callbacks) let deregister = do callbacks <- get callbacksRef set callbacksRef (Map.delete id callbacks) return deregister return $ MkObservableRef originalGetter newSetter register instance Mutable ObservableRef where get (MkObservableRef getter _ _) = getter set (MkObservableRef _ setter _) = setter instance Observable ObservableRef where register (MkObservableRef _ _ register) = register runTest :: forall a. (Eq a, Show a) => (forall m. (Stateful m) => m a) -> a -> Spec runTest test expectedResult = do it "works for ST" $ do let result = runST test result `shouldBe` expectedResult it "works for IO" $ do result <- test result `shouldBe` expectedResult spec :: Spec spec = do describe "Stateful" $ do let test :: (Stateful m) => m Bool test = do ref <- initMutable False set ref True get ref runTest test True describe "Observable: Take 1" $ do context "doesn't trigger cb when not supposed to" $ do let test :: forall m. (Stateful m) => m Bool test = do refref <- initMutable =<< initMutable "hello" isModifiedRef <- initMutable False registerTake1 refref $ const $ set isModifiedRef True get isModifiedRef runTest test False context "triggers cb when supposed to" $ do let test :: forall m. (Stateful m) => m Bool test = do refref <- return "hello" >>= initMutable >>= initMutable isModifiedRef <- initMutable False registerTake1 refref $ const $ set isModifiedRef True (get refref) >>= flip set "asdf" get isModifiedRef runTest test True describe "Observable: Take 2" $ do context "doesn't trigger cb when not supposed to" $ do let test :: forall m. (Stateful m) => m Bool test = do ref <- return "hello" >>= initMutable >>= makeObservable isModifiedRef <- initMutable False _ <- register ref (const $ set isModifiedRef True) get isModifiedRef runTest test False context "can trigger cb when supposed to" $ do let test :: forall m. (Stateful m) => m Bool test = do ref <- return "hello" >>= initMutable >>= makeObservable isModifiedRef <- initMutable False _ <- register ref (const $ set isModifiedRef True) set ref "world" get isModifiedRef runTest test True context "can trigger multiple cb's when supposed to" $ do let test :: forall m. (Stateful m) => m Bool test = do ref <- return "hello" >>= initMutable >>= makeObservable isModifiedRef1 <- initMutable False _ <- register ref (const $ set isModifiedRef1 True) isModifiedRef2 <- initMutable False _ <- register ref (const $ set isModifiedRef2 True) set ref "world" (&&) <$> get isModifiedRef1 <*> get isModifiedRef2 runTest test True context "can trigger cb's multiple times" $ do let test :: forall m. (Stateful m) => m Int test = do ref <- return () >>= initMutable >>= makeObservable counter <- initMutable (0 :: Int) let incr = get counter >>= \i -> set counter (i + 1) _ <- register ref $ const incr set ref () set ref () set ref () set ref () set ref () get counter runTest test 5 context "can deregister cb" $ do let test :: forall m. (Stateful m) => m Bool test = do ref <- return "hello" >>= initMutable >>= makeObservable isModifiedRef <- initMutable False deregister <- register ref (const $ set isModifiedRef True) deregister set ref "world" get isModifiedRef runTest test False
sleexyz/haskell-fun
Observable.hs
bsd-3-clause
7,334
0
25
2,301
2,242
1,065
1,177
-1
-1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. ----------------------------------------------------------------- -- Auto-generated by regenClassifiers -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated ----------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} module Duckling.Ranking.Classifiers.VI (classifiers) where import Prelude import Duckling.Ranking.Types import qualified Data.HashMap.Strict as HashMap import Data.String classifiers :: Classifiers classifiers = HashMap.fromList [("<time> timezone", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("<time-of-day> am|pm", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("integer (numeric)", Classifier{okData = ClassData{prior = -0.4986303506721723, unseen = -4.61512051684126, likelihoods = HashMap.fromList [("", 0.0)], n = 99}, koData = ClassData{prior = -0.9348671174470905, unseen = -4.189654742026425, likelihoods = HashMap.fromList [("", 0.0)], n = 64}}), ("exactly <time-of-day>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("time-of-day gi\7901", -1.6094379124341003), ("<time-of-day> s\225ng|chi\7873u|t\7889i", -1.6094379124341003), ("time-of-day (latent)", -1.6094379124341003), ("hour", -0.916290731874155)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("ng\224y h\244m qua", Classifier{okData = ClassData{prior = -0.5596157879354228, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}, koData = ClassData{prior = -0.8472978603872037, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}}), ("lunch", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("ng\224y dd/mm", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("dd/mm", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}, koData = ClassData{prior = -0.6931471805599453, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}}), ("<part-of-day> <time>", Classifier{okData = ClassData{prior = -0.7884573603642702, unseen = -3.5553480614894135, likelihoods = HashMap.fromList [("hourday", -1.128465251817791), ("noonh\244m nay", -2.833213344056216), ("lunchng\224y mai", -2.4277482359480516), ("morningnamed-day", -2.833213344056216), ("noonng\224y h\244m qua", -2.4277482359480516), ("noonng\224y mai", -2.4277482359480516), ("afternoonng\224y dd/mm", -2.833213344056216), ("afternoonng\224y mai", -2.833213344056216)], n = 10}, koData = ClassData{prior = -0.6061358035703156, unseen = -3.6635616461296463, likelihoods = HashMap.fromList [("hourday", -1.072636802264849), ("afternoon<day-of-month> (numeric with day symbol) <named-month>", -2.538973871058276), ("afternoongi\225ng sinh", -1.845826690498331), ("afternoonng\224y dd/mm/yyyy", -2.9444389791664407), ("noongi\225ng sinh", -2.9444389791664407), ("afternoonng\224y dd/mm", -2.9444389791664407), ("lunchgi\225ng sinh", -2.9444389791664407), ("afternoonintersect", -2.9444389791664407)], n = 12}}), ("tonight", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("integer (0..19)", Classifier{okData = ClassData{prior = -1.452252328911688, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("", 0.0)], n = 11}, koData = ClassData{prior = -0.2666286632539486, unseen = -3.6375861597263857, likelihoods = HashMap.fromList [("", 0.0)], n = 36}}), ("<day-of-week> t\7899i", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("day", -0.6931471805599453), ("named-day", -0.6931471805599453)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("month (grain)", Classifier{okData = ClassData{prior = -1.4271163556401458, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -0.2744368457017603, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("", 0.0)], n = 19}}), ("ng\224y h\244m kia", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("gi\225ng sinh", Classifier{okData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -3.4657359027997265, likelihoods = HashMap.fromList [("", 0.0)], n = 30}}), ("hour (grain)", Classifier{okData = ClassData{prior = -1.791759469228055, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}, koData = ClassData{prior = -0.1823215567939546, unseen = -3.0910424533583156, likelihoods = HashMap.fromList [("", 0.0)], n = 20}}), ("intersect", Classifier{okData = ClassData{prior = -0.5070449009260846, unseen = -5.0106352940962555, likelihoods = HashMap.fromList [("<time-of-day> s\225ng|chi\7873u|t\7889ing\224y dd/mm", -3.6176519448255684), ("hourday", -3.6176519448255684), ("dayhour", -4.310799125385514), ("h\244m nay<time-of-day> s\225ng|chi\7873u|t\7889i", -4.310799125385514), ("monthyear", -3.3945083935113587), ("time-of-day gi\7901<part-of-day> <time>", -4.310799125385514), ("time-of-day gi\7901<time> n\224y", -4.310799125385514), ("month (numeric with month symbol)year (numeric with year symbol)", -3.6176519448255684), ("dayday", -2.6060510331470885), ("named-monthyear (numeric with year symbol)", -4.310799125385514), ("hourhour", -3.3945083935113587), ("named-day<day-of-month> (numeric with day symbol) <named-month>", -2.7013612129514133), ("intersectyear (numeric with year symbol)", -3.6176519448255684), ("dayyear", -2.4389969484839225), ("<ordinal> <cycle> of <time>year (numeric with year symbol)", -4.310799125385514), ("minutehour", -3.9053340172773496), ("<time-of-day> s\225ng|chi\7873u|t\7889iintersect", -3.9053340172773496), ("time-of-day gi\7901<part-of-day> (h\244m )?nay", -4.310799125385514), ("<day-of-month> (numeric with day symbol) <named-month>year (numeric with year symbol)", -3.2121868367174042), ("named-daynext <cycle>", -3.6176519448255684), ("named-dayintersect", -4.310799125385514), ("<time-of-day> s\225ng|chi\7873u|t\7889i<day-of-month> (numeric with day symbol) <named-month>", -3.3945083935113587), ("time-of-day gi\7901tonight", -4.310799125385514), ("minuteday", -2.8067217286092396), ("hh:mm<part-of-day> <time>", -4.310799125385514), ("<day-of-month> <named-month>year (numeric with year symbol)", -3.2121868367174042), ("at hh:mm<part-of-day> <time>", -4.310799125385514), ("dayweek", -3.0580361568901457), ("weekyear", -4.310799125385514), ("<time-of-day> s\225ng|chi\7873u|t\7889ing\224y dd/mm/yyyy", -4.310799125385514), ("<time-of-day> s\225ng|chi\7873u|t\7889ing\224y mai", -4.310799125385514), ("named-daythis <cycle>", -3.6176519448255684), ("seasonthis <cycle>", -4.310799125385514), ("minuteyear", -3.9053340172773496)], n = 53}, koData = ClassData{prior = -0.9219887529887928, unseen = -4.736198448394496, likelihoods = HashMap.fromList [("<time-of-day> s\225ng|chi\7873u|t\7889ing\224y dd/mm", -4.034240638152395), ("hourday", -2.2424811689243405), ("dayhour", -4.034240638152395), ("monthyear", -2.7814776696570274), ("noonh\244m nay", -4.034240638152395), ("houryear", -4.034240638152395), ("month (numeric with month symbol)year (numeric with year symbol)", -2.7814776696570274), ("dayday", -2.5301632413761213), ("dayyear", -4.034240638152395), ("h\244m naytime-of-day gi\7901", -4.034240638152395), ("minutehour", -3.628775530044231), ("<part-of-day> <time>year (numeric with year symbol)", -4.034240638152395), ("<time-of-day> s\225ng|chi\7873u|t\7889igi\225ng sinh", -2.424802725718295), ("noonng\224y h\244m qua", -3.628775530044231), ("noongi\225ng sinh", -4.034240638152395), ("minuteday", -2.9356283494842854), ("hh:mm<part-of-day> <time>", -4.034240638152395), ("noonng\224y mai", -3.628775530044231), ("<day-of-month> <named-month>year (numeric with year symbol)", -4.034240638152395), ("named-daygi\225ng sinh", -2.5301632413761213), ("at hh:mm<part-of-day> <time>", -4.034240638152395)], n = 35}}), ("time-of-day gi\7901", Classifier{okData = ClassData{prior = -6.453852113757118e-2, unseen = -4.174387269895637, likelihoods = HashMap.fromList [("exactly <time-of-day>", -3.4657359027997265), ("about <time-of-day>", -3.0602707946915624), ("time-of-day (latent)", -0.8266785731844679), ("hour", -0.7248958788745256)], n = 30}, koData = ClassData{prior = -2.772588722239781, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("time-of-day (latent)", -0.9808292530117262), ("hour", -0.9808292530117262)], n = 2}}), ("<ordinal> <cycle> of <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.833213344056216, likelihoods = HashMap.fromList [("daymonth", -1.3862943611198906), ("day (grain)ordinalsnamed-month", -2.0794415416798357), ("day (grain)ordinalsmonth (numeric with month symbol)", -1.6739764335716716), ("week (grain)ordinalsintersect", -2.0794415416798357), ("weekmonth", -1.6739764335716716), ("week (grain)ordinalsmonth (numeric with month symbol)", -2.0794415416798357)], n = 5}, koData = ClassData{prior = -infinity, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [], n = 0}}), ("season", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("year (grain)", Classifier{okData = ClassData{prior = -0.5389965007326869, unseen = -2.772588722239781, likelihoods = HashMap.fromList [("", 0.0)], n = 14}, koData = ClassData{prior = -0.8754687373538999, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("", 0.0)], n = 10}}), ("quarter <number>", Classifier{okData = ClassData{prior = -0.40546510810816444, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("quarter (grain)integer (numeric)", -1.2992829841302609), ("quarter (grain)integer (0..19)", -1.2992829841302609), ("quarter", -0.7884573603642702)], n = 4}, koData = ClassData{prior = -1.0986122886681098, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("quarter (grain)integer (numeric)", -0.8472978603872037), ("quarter", -0.8472978603872037)], n = 2}}), ("next <cycle>", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -3.7612001156935624, likelihoods = HashMap.fromList [("week", -1.9459101490553135), ("month (grain)", -3.044522437723423), ("year (grain)", -2.128231705849268), ("week (grain)", -1.9459101490553135), ("quarter", -2.3513752571634776), ("year", -2.128231705849268), ("month", -3.044522437723423), ("quarter (grain)", -2.3513752571634776)], n = 13}, koData = ClassData{prior = -0.6931471805599453, unseen = -3.7612001156935624, likelihoods = HashMap.fromList [("month (grain)", -2.639057329615259), ("hour (grain)", -2.639057329615259), ("year (grain)", -2.639057329615259), ("second", -2.3513752571634776), ("day", -2.639057329615259), ("minute (grain)", -2.639057329615259), ("year", -2.639057329615259), ("second (grain)", -2.3513752571634776), ("hour", -2.639057329615259), ("month", -2.639057329615259), ("minute", -2.639057329615259), ("day (grain)", -2.639057329615259)], n = 13}}), ("ng\224y mai", Classifier{okData = ClassData{prior = 0.0, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("quarter <number> <year>", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("quarteryear", -1.0986122886681098), ("quarter (grain)integer (numeric)year (numeric with year symbol)", -1.0986122886681098)], n = 1}, koData = ClassData{prior = -0.6931471805599453, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("quarterhour", -1.0986122886681098), ("quarter (grain)integer (numeric)time-of-day (latent)", -1.0986122886681098)], n = 1}}), ("dd/mm/yyyy", Classifier{okData = ClassData{prior = -0.15415067982725836, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -1.9459101490553135, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("after lunch", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("hh:mm:ss", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<time> tr\432\7899c", Classifier{okData = ClassData{prior = -1.9459101490553135, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("day", -1.5040773967762742), ("named-day", -1.5040773967762742)], n = 1}, koData = ClassData{prior = -0.15415067982725836, unseen = -2.995732273553991, likelihoods = HashMap.fromList [("gi\225ng sinh", -2.2512917986064953), ("<hour-of-day> <integer>", -2.2512917986064953), ("day", -2.2512917986064953), ("time-of-day (latent)", -1.3350010667323402), ("hour", -1.3350010667323402), ("minute", -2.2512917986064953)], n = 6}}), ("ng\224y dd/mm/yyyy", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<time> n\224y", Classifier{okData = ClassData{prior = -0.6061358035703156, unseen = -2.995732273553991, likelihoods = HashMap.fromList [("season", -1.845826690498331), ("<time-of-day> s\225ng|chi\7873u|t\7889i", -2.2512917986064953), ("day", -1.845826690498331), ("noon", -1.845826690498331), ("hour", -1.3350010667323402), ("morning", -2.2512917986064953)], n = 6}, koData = ClassData{prior = -0.7884573603642702, unseen = -2.890371757896165, likelihoods = HashMap.fromList [("time-of-day (latent)", -1.4469189829363254), ("noon", -1.7346010553881064), ("hour", -1.041453874828161)], n = 5}}), ("b\226y gi\7901", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<hour-of-day> <integer>", Classifier{okData = ClassData{prior = -1.4469189829363254, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("hour", -0.7884573603642702), ("time-of-day gi\7901integer (numeric)", -0.7884573603642702)], n = 4}, koData = ClassData{prior = -0.2682639865946794, unseen = -3.4011973816621555, likelihoods = HashMap.fromList [("time-of-day (latent)integer (0..19)", -0.7282385003712154), ("hour", -0.7282385003712154)], n = 13}}), ("<time> t\7899i", Classifier{okData = ClassData{prior = -0.4700036292457356, unseen = -2.995732273553991, likelihoods = HashMap.fromList [("month (numeric with month symbol)", -2.2512917986064953), ("day", -1.3350010667323402), ("named-day", -1.3350010667323402), ("month", -2.2512917986064953)], n = 5}, koData = ClassData{prior = -0.9808292530117262, unseen = -2.772588722239781, likelihoods = HashMap.fromList [("gi\225ng sinh", -2.0149030205422647), ("time-of-day gi\7901", -2.0149030205422647), ("<hour-of-day> <integer>", -2.0149030205422647), ("day", -2.0149030205422647), ("hour", -2.0149030205422647), ("minute", -2.0149030205422647)], n = 3}}), ("<time-of-day> s\225ng|chi\7873u|t\7889i", Classifier{okData = ClassData{prior = -5.129329438755058e-2, unseen = -4.465908118654584, likelihoods = HashMap.fromList [("exactly <time-of-day>", -3.7612001156935624), ("time-of-day gi\7901", -1.318853080324358), ("<hour-of-day> <integer>", -3.355735007585398), ("about <time-of-day>", -3.355735007585398), ("at hh:mm", -3.068052935133617), ("(hour-of-day) half", -3.355735007585398), ("hh:mm", -2.5084371471981943), ("hour", -1.1962507582320256), ("minute", -1.8152899666382492)], n = 38}, koData = ClassData{prior = -2.995732273553991, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("time-of-day (latent)", -1.540445040947149), ("hour", -1.540445040947149)], n = 2}}), ("named-month", Classifier{okData = ClassData{prior = 0.0, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("month (numeric with month symbol)", Classifier{okData = ClassData{prior = 0.0, unseen = -3.4339872044851463, likelihoods = HashMap.fromList [("integer (numeric)", -0.2231435513142097), ("integer (0..19)", -1.6094379124341003)], n = 28}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("week (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("", 0.0)], n = 13}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("year (numeric with year symbol)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 11}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("quarter <number> of <year>", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("quarteryear", -1.0986122886681098), ("quarter (grain)integer (numeric)year (numeric with year symbol)", -1.0986122886681098)], n = 1}, koData = ClassData{prior = -0.6931471805599453, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("quarterhour", -1.0986122886681098), ("quarter (grain)integer (numeric)time-of-day (latent)", -1.0986122886681098)], n = 1}}), ("afternoon", Classifier{okData = ClassData{prior = -0.916290731874155, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -0.5108256237659907, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}}), ("this <cycle>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.6109179126442243, likelihoods = HashMap.fromList [("week", -1.6376087894007967), ("year (grain)", -2.1972245773362196), ("week (grain)", -1.6376087894007967), ("day", -2.890371757896165), ("quarter", -1.9740810260220096), ("year", -2.1972245773362196), ("quarter (grain)", -1.9740810260220096), ("day (grain)", -2.890371757896165)], n = 14}, koData = ClassData{prior = -infinity, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [], n = 0}}), ("minute (grain)", Classifier{okData = ClassData{prior = -0.2876820724517809, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -1.3862943611198906, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("about <time-of-day>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.833213344056216, likelihoods = HashMap.fromList [("time-of-day gi\7901", -1.6739764335716716), ("<time-of-day> s\225ng|chi\7873u|t\7889i", -1.6739764335716716), ("time-of-day (latent)", -1.6739764335716716), ("hour", -0.8266785731844679)], n = 6}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("time-of-day (latent)", Classifier{okData = ClassData{prior = -0.6567795363890705, unseen = -3.4339872044851463, likelihoods = HashMap.fromList [("integer (numeric)", -0.10536051565782628), ("integer (0..19)", -2.3025850929940455)], n = 28}, koData = ClassData{prior = -0.7308875085427924, unseen = -3.367295829986474, likelihoods = HashMap.fromList [("integer (numeric)", -0.4989911661189879), ("integer (0..19)", -0.9343092373768334)], n = 26}}), ("at hh:mm", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("(hour-of-day) half", Classifier{okData = ClassData{prior = 0.0, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("time-of-day gi\7901", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("<integer> <unit-of-duration>", Classifier{okData = ClassData{prior = -infinity, unseen = -2.995732273553991, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -5.225746673713201, likelihoods = HashMap.fromList [("week", -3.42859635585027), ("integer (0..19)year (grain)", -4.527208644518379), ("integer (numeric)day (grain)", -3.0231312477421053), ("integer (0..19)hour (grain)", -3.834061463958434), ("second", -3.6109179126442243), ("integer (numeric)second (grain)", -3.6109179126442243), ("integer (numeric)year (grain)", -2.655406467616788), ("day", -2.822460552279954), ("year", -2.581298495463066), ("integer (numeric)week (grain)", -4.121743536410215), ("integer (0..19)month (grain)", -4.527208644518379), ("hour", -2.001480000210124), ("month", -2.042301994730379), ("integer (numeric)minute (grain)", -3.6109179126442243), ("integer (numeric)month (grain)", -2.084861609149175), ("minute", -3.6109179126442243), ("integer (numeric)hour (grain)", -2.129313371720009), ("integer (0..19)day (grain)", -4.121743536410215), ("integer (0..19)week (grain)", -3.834061463958434)], n = 83}}), ("<time-of-day> am|pm", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("time-of-day (latent)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("h\244m nay", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("hh:mm", Classifier{okData = ClassData{prior = -8.701137698962981e-2, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("", 0.0)], n = 11}, koData = ClassData{prior = -2.4849066497880004, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("named-day", Classifier{okData = ClassData{prior = 0.0, unseen = -3.4339872044851463, likelihoods = HashMap.fromList [("", 0.0)], n = 29}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("second (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("intersect by \"of\", \"from\", \"'s\"", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("named-daynext <cycle>", -1.5040773967762742), ("dayweek", -0.8109302162163288), ("named-daythis <cycle>", -1.0986122886681098)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("<hour-of-day> <integer> ph\250t", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("hour", -0.6931471805599453), ("time-of-day gi\7901integer (numeric)", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("noon", Classifier{okData = ClassData{prior = -0.7621400520468967, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("", 0.0)], n = 7}, koData = ClassData{prior = -0.6286086594223742, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("", 0.0)], n = 8}}), ("ordinals", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("(hour-of-day) quarter", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("hour", -0.6931471805599453), ("time-of-day gi\7901integer (numeric)", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("last <cycle>", Classifier{okData = ClassData{prior = -0.7731898882334817, unseen = -3.295836866004329, likelihoods = HashMap.fromList [("week", -2.5649493574615367), ("month (grain)", -2.5649493574615367), ("year (grain)", -1.6486586255873816), ("week (grain)", -2.5649493574615367), ("year", -1.6486586255873816), ("month", -2.5649493574615367)], n = 6}, koData = ClassData{prior = -0.6190392084062235, unseen = -3.367295829986474, likelihoods = HashMap.fromList [("month (grain)", -2.2335922215070942), ("hour (grain)", -2.639057329615259), ("year (grain)", -2.639057329615259), ("second", -2.639057329615259), ("day", -2.639057329615259), ("minute (grain)", -2.639057329615259), ("year", -2.639057329615259), ("second (grain)", -2.639057329615259), ("hour", -2.639057329615259), ("month", -2.2335922215070942), ("minute", -2.639057329615259), ("day (grain)", -2.639057329615259)], n = 7}}), ("next n <cycle>", Classifier{okData = ClassData{prior = -0.1431008436406733, unseen = -3.7612001156935624, likelihoods = HashMap.fromList [("integer (numeric)day (grain)", -2.639057329615259), ("second", -2.3513752571634776), ("integer (numeric)second (grain)", -2.3513752571634776), ("integer (numeric)year (grain)", -2.639057329615259), ("day", -2.639057329615259), ("year", -2.639057329615259), ("integer (0..19)month (grain)", -3.044522437723423), ("hour", -2.639057329615259), ("month", -2.639057329615259), ("integer (numeric)minute (grain)", -2.639057329615259), ("integer (numeric)month (grain)", -3.044522437723423), ("minute", -2.639057329615259), ("integer (numeric)hour (grain)", -2.639057329615259)], n = 13}, koData = ClassData{prior = -2.0149030205422647, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("week", -1.8971199848858813), ("integer (numeric)week (grain)", -2.3025850929940455), ("integer (0..19)week (grain)", -2.3025850929940455)], n = 2}}), ("<day-of-month> <named-month>", Classifier{okData = ClassData{prior = -0.10008345855698253, unseen = -3.7376696182833684, likelihoods = HashMap.fromList [("integer (numeric)month (numeric with month symbol)", -0.8232003088081431), ("integer (numeric)named-month", -2.6149597780361984), ("month", -0.7178397931503169)], n = 19}, koData = ClassData{prior = -2.3513752571634776, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("integer (numeric)month (numeric with month symbol)", -0.8472978603872037), ("month", -0.8472978603872037)], n = 2}}), ("last n <cycle>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.4657359027997265, likelihoods = HashMap.fromList [("integer (numeric)day (grain)", -2.3353749158170367), ("integer (0..19)hour (grain)", -2.740840023925201), ("second", -2.740840023925201), ("integer (numeric)second (grain)", -2.740840023925201), ("integer (numeric)year (grain)", -2.740840023925201), ("day", -2.3353749158170367), ("year", -2.740840023925201), ("hour", -2.3353749158170367), ("month", -2.3353749158170367), ("integer (numeric)minute (grain)", -2.740840023925201), ("integer (numeric)month (grain)", -2.3353749158170367), ("minute", -2.740840023925201), ("integer (numeric)hour (grain)", -2.740840023925201)], n = 9}, koData = ClassData{prior = -infinity, unseen = -2.639057329615259, likelihoods = HashMap.fromList [], n = 0}}), ("quarter (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("", 0.0)], n = 13}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("morning", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("day (grain)", Classifier{okData = ClassData{prior = -0.6190392084062235, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("", 0.0)], n = 7}, koData = ClassData{prior = -0.7731898882334817, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}}), ("<part-of-day> (h\244m )?nay", Classifier{okData = ClassData{prior = 0.0, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("noon", -1.0116009116784799), ("hour", -0.7884573603642702), ("morning", -1.7047480922384253)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("<day-of-month> (numeric with day symbol) <named-month>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.784189633918261, likelihoods = HashMap.fromList [("integer (numeric)month (numeric with month symbol)", -0.8167611365271219), ("integer (numeric)named-month", -2.662587827025453), ("month", -0.7166776779701395)], n = 20}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}})]
rfranek/duckling
Duckling/Ranking/Classifiers/VI.hs
bsd-3-clause
54,500
0
15
26,736
9,617
5,994
3,623
892
1
module Web.Heroku.Internal ( dbConnParams' , parseDatabaseUrl' ) where import System.Environment import Network.URI import Data.Text import Prelude -- | read the DATABASE_URL environment variable -- and return an alist of connection parameters with the following keys: -- user, password, host, port, dbname -- -- warning: just calls error if it can't parse correctly dbConnParams' :: String -> (String -> [(Text, Text)]) -> IO [(Text, Text)] dbConnParams' envVar parse = getEnv envVar >>= return . parse parseDatabaseUrl' :: String -> String -> [(Text, Text)] parseDatabaseUrl' scheme durl = let muri = parseAbsoluteURI durl (auth, path) = case muri of Nothing -> error "couldn't parse absolute uri" Just uri -> if uriScheme uri /= scheme then schemeError uri else case uriAuthority uri of Nothing -> invalid Just a -> (a, uriPath uri) (user,password) = userAndPassword auth in [ (pack "user", user) -- tail not safe, but should be there on Heroku ,(pack "password", Data.Text.tail password) ,(pack "host", pack $ uriRegName auth) ,(pack "port", Data.Text.tail $ pack $ uriPort auth) -- tail not safe but path should always be there ,(pack "dbname", pack $ Prelude.tail $ path) ] where -- init is not safe, but should be there on Heroku userAndPassword :: URIAuth -> (Text, Text) userAndPassword = (breakOn $ pack ":") . pack . Prelude.init . uriUserInfo schemeError uri = error $ "was expecting a postgres scheme, not: " ++ (uriScheme uri) ++ "\n" ++ (show uri) -- should be an error invalid = error "could not parse heroku DATABASE_URL"
thoughtbot/haskell-heroku
Web/Heroku/Internal.hs
bsd-3-clause
1,893
0
17
601
435
237
198
30
4
{- - Hacq (c) 2013 NEC Laboratories America, Inc. All rights reserved. - - This file is part of Hacq. - Hacq is distributed under the 3-clause BSD license. - See the LICENSE file for more details. -} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} module Data.Quantum.Circuit.Invert (IsCircuitInvert(..), CircuitInvert, runCircuitInvert) where import Control.Applicative (Applicative, liftA2) import Control.Monad.Reader (Reader, reader, runReader) import qualified Control.Monad.Reader as Reader import Data.Quantum.Circuit.Class class IsCircuit g w c => IsCircuitInvert g w c | c -> g, c -> w where invert :: c -> c newtype CircuitInvert a = CircuitInvert { _unwrapCircuitInvert :: Reader Bool a } deriving (Functor, Applicative, Monad) runCircuitInvert :: CircuitInvert a -> a runCircuitInvert (CircuitInvert m) = runReader m False instance IsCircuit g w c => IsCircuit g w (CircuitInvert c) where empty = return empty {-# INLINABLE empty #-} singleton g = CircuitInvert $ reader $ \inv -> singleton $ if inv then invertGate g else g {-# INLINABLE singleton #-} newWire w inv = CircuitInvert $ reader $ \inv' -> newWire w (inv /= inv') {-# INLINABLE newWire #-} ancilla w inv = CircuitInvert $ reader $ \inv' -> ancilla w (inv /= inv') {-# INLINABLE ancilla #-} sequential (CircuitInvert m1) (CircuitInvert m2) = CircuitInvert $ do inv <- Reader.ask if inv then liftA2 sequential m2 m1 else liftA2 sequential m1 m2 {-# INLINABLE sequential #-} parallel (CircuitInvert m1) (CircuitInvert m2) = CircuitInvert $ liftA2 parallel m1 m2 {-# INLINABLE parallel #-} instance IsCircuit g w c => IsCircuitInvert g w (CircuitInvert c) where invert (CircuitInvert m) = CircuitInvert $ reader $ \inv -> runReader m $! not inv {-# INLINABLE invert #-}
ti1024/hacq
src/Data/Quantum/Circuit/Invert.hs
bsd-3-clause
2,010
0
10
408
493
269
224
36
1
{-# LANGUAGE ConstraintKinds , FlexibleInstances , MultiParamTypeClasses , GeneralizedNewtypeDeriving , TemplateHaskell , TypeFamilies , UndecidableInstances #-} module Data.CRDT.Set where import Data.CRDT.Classes import Data.CRDT.Counter import Data.CRDT.User (UserIx) import Data.CRDT.Utils import Prelude hiding (null) import Control.Applicative ((<$>)) import Control.Arrow ((***)) import Data.Label import Data.Maybe (fromMaybe) import qualified Data.Map as M import qualified Data.Set as S import qualified Data.Vector.Storable as V -- Classes --TODO: reducers? -- "G set" - growable set newtype GSet a = GSet (S.Set a) deriving ( Eq, Read, Show , Size, Update , Monoid, Semigroup , JoinSemiLattice, BoundedJoinSemiLattice, PartialOrd ) instance Ord a => Function (GSet a) where type Domain (GSet a) = a type Codomain (GSet a) = Bool value (GSet s) = value s $(mkNewType ''GSet) -- "2P set" - set with deletions where new need to have never been in the set. newtype Set2P a = Set2P (a, a) deriving ( Eq, Read, Show , Monoid, Semigroup , JoinSemiLattice, BoundedJoinSemiLattice, PartialOrd ) $(mkNewType ''Set2P) instance (Function a, Codomain a ~ Bool) => Function (Set2P a) where type Domain (Set2P a) = Domain a type Codomain (Set2P a) = Bool value (Set2P (s, d)) x = member x s && notMember x d instance (Update a, Function a, Codomain a ~ Bool) => Update (Set2P a) where update k = over Set2P . first . update k instance (Zero a, JoinSemiLattice a) => Zero (Set2P a) where zero = Set2P zero clear (Set2P (s, d)) = Set2P (s, s `join` d) instance Size a => Size (Set2P a) where size (Set2P (s, d)) = size s - size d instance Lattice a => MeetSemiLattice (Set2P a) where meet (Set2P (s, d)) (Set2P (s', d')) = Set2P (s `meet` s', d `join` d') instance BoundedLattice a => BoundedMeetSemiLattice (Set2P a) where top = Set2P (top, bottom) instance DiffLattice a => DiffLattice (Set2P a) where diff (Set2P (s, d)) (Set2P (s', d')) = Set2P (s \\ s', s' \\ s `join` d `join` d') instance (DiffLattice a, Monoid a) => ResiduatedLattice (Set2P a) where residualL = diff residualR = diff instance Lattice a => Lattice (Set2P a) instance BoundedLattice a => BoundedLattice (Set2P a) -- Set2P variant, represented as (members, deleted) instead of (seen, deleted). data RemSet a = RemSet (a, a) deriving ( Eq, Read, Show ) $(mkNewType ''RemSet) instance (Function a, Codomain a ~ Bool) => Function (RemSet a) where type Domain (RemSet a) = Domain a type Codomain (RemSet a) = Bool value (RemSet (a, _)) = value a instance (Update a, Function a, Codomain a ~ Bool) => Update (RemSet a) where update x True s@(RemSet (a, d)) | x `notMember` d = RemSet (update x True a, d) | otherwise = s update x False (RemSet (a, d)) = RemSet (update x False a, update x True d) instance (Zero a, BoundedJoinSemiLattice a) => Zero (RemSet a) where zero = RemSet (zero, zero) null = null . fst . unpack clear (RemSet (a, d)) = RemSet (bottom, a `join` d) instance Size a => Size (RemSet a) where size = size . fst . unpack instance (PartialOrd a) => PartialOrd (RemSet a) where leq (RemSet (a, d)) (RemSet (a', d')) = (a `leq` a') && (d `leq` d) instance DiffLattice a => JoinSemiLattice (RemSet a) where join (RemSet (a, d)) (RemSet (a', d')) = RemSet ( (a \\ d') `join` (a' \\ d), d `join` d') instance DiffLattice a => MeetSemiLattice (RemSet a) where meet (RemSet (a, d)) (RemSet (a', d')) = RemSet ( a `meet` a', joins [d, d', a \\ a', a' \\ a] ) instance (DiffLattice a, BoundedJoinSemiLattice a) => BoundedJoinSemiLattice (RemSet a) where bottom = RemSet (bottom, bottom) instance (DiffLattice a, BoundedLattice a) => BoundedMeetSemiLattice (RemSet a) where top = RemSet (top, bottom) instance DiffLattice a => DiffLattice (RemSet a) where diff (RemSet (a, d)) (RemSet (a', d')) = RemSet (a `diff` a', d `join` d' `join` (a' \\ a)) instance DiffLattice a => ResiduatedLattice (RemSet a) where residualL = diff residualR = diff instance DiffLattice a => Lattice (RemSet a) where instance DiffLattice a => BoundedLattice (RemSet a) where instance DiffLattice a => Semigroup (RemSet a) where (<>) = join instance DiffLattice a => Monoid (RemSet a) where mappend = join mempty = bottom -- Observed-delete Set newtype ORSet t a = ORSet (M.Map a (RemSet (S.Set t))) deriving ( Eq, Read, Show , JoinSemiLattice, BoundedJoinSemiLattice , MeetSemiLattice, BoundedMeetSemiLattice , Lattice, BoundedLattice , ResiduatedLattice, DiffLattice ) instance (Ord a, Ord t, Enumerable t) => Monoid (ORSet t a) where mappend (ORSet a) (ORSet b) = ORSet $ join a b $(mkNewType ''ORSet) instance (Ord t, Ord a) => Function (ORSet t a) where type Domain (ORSet t a) = a type Codomain (ORSet t a) = Bool value (ORSet m) = maybe False (not . null) . value m instance (Ord t, Ord a) => Zero (ORSet t a) where zero = ORSet zero null = all null . M.elems . unpack clear = over ORSet $ M.map clear instance Ord a => Size (ORSet t a) where size (ORSet m) = sum . map size $ M.elems m {- -- TODO: operational USet -- Sets that provide preferential ordering to operations: Last-Writer-Wins newtype LWWSet t a = LWWSet (M.Map a t, M.Map a t) deriving ( Eq, Read, Show, JoinSemiLattice, BoundedJoinSemiLattice, PartialOrd ) $(mkNewType ''LWWSet) instance Ord a => LWWSet a where member = uncurry (helper `on` M.lookup x) . unpack where helper (Just _) Nothing = True helper (Just t) (Just t') = t' < t helper _ _ = False update --TODO: consider take a "Tagged"? insertLWWSet :: Ord a => t -> a -> LWWSet t a -> LWWSet t a insertLWWSet t x = LWWSet `over` first (M.update x t) deleteLWWSet :: Ord a => t -> a -> LWWSet t a -> LWWSet t a deleteLWWSet t x = LWWSet `over` second (M.update x t) -- TODO: multi-register can be generalized to this as well. is it useful? -- PNSet - positive / negative set newtype PNSet t a = PNSet (M.Map a (V.Vector (Counter t))) deriving ( Eq, Read, Show, JoinSemiLattice, BoundedJoinSemiLattice, PartialOrd ) $(mkNewType ''PNSet) instance Ord a => SetLike (GSet a) where type Element (GSet a) = a member x = maybe False ((> 0) . get count) . M.lookup x . unpack alterPNSet :: (Counter t -> Counter t) -> UserIx -> a -> PNSet t a -> PNSet t a alterPNSet f u x = PNSet `over` M.alter (maybe (f bottom) $ modify (atIndex u) f) x insertPNSet, deletePNSet :: Enum t => UserIx -> a -> PNSet t a -> PNSet t a insertPNSet = alterPN succ deletePNSet = alterPN pred -}
mgsloan/crdt
src/Data/CRDT/Set.hs
bsd-3-clause
6,663
0
12
1,436
2,245
1,193
1,052
125
0
module Module4.Task14 where data Coord a = Coord a a distance :: Coord Double -> Coord Double -> Double distance (Coord x1 y1) (Coord x2 y2) = sqrt $ (x1 - x2)^2 + (y1 - y2)^2 manhDistance :: Coord Int -> Coord Int -> Int manhDistance (Coord x1 y1) (Coord x2 y2) = abs (x1 - x2) + abs (y1 - y2)
dstarcev/stepic-haskell
src/Module4/Task14.hs
bsd-3-clause
313
0
10
80
162
83
79
8
1
----------------------------------------------------------------------------- -- -- GHC Interactive support for inspecting arbitrary closures at runtime -- -- Pepe Iborra (supported by Google SoC) 2006 -- ----------------------------------------------------------------------------- {-# OPTIONS -fno-warn-tabs #-} -- The above warning supression flag is a temporary kludge. -- While working on this module you are encouraged to remove it and -- detab the module (please do the detabbing in a separate patch). See -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces -- for details module RtClosureInspect( cvObtainTerm, -- :: HscEnv -> Int -> Bool -> Maybe Type -> HValue -> IO Term cvReconstructType, improveRTTIType, Term(..), isTerm, isSuspension, isPrim, isFun, isFunLike, isNewtypeWrap, isFullyEvaluated, isFullyEvaluatedTerm, termType, mapTermType, termTyVars, foldTerm, TermFold(..), foldTermM, TermFoldM(..), idTermFold, pprTerm, cPprTerm, cPprTermBase, CustomTermPrinter, -- unsafeDeepSeq, Closure(..), getClosureData, ClosureType(..), isConstr, isIndirection ) where #include "HsVersions.h" import DebuggerUtils import ByteCodeItbls ( StgInfoTable, peekItbl ) import qualified ByteCodeItbls as BCI( StgInfoTable(..) ) import BasicTypes ( HValue ) import HscTypes import DataCon import Type import qualified Unify as U import Var import TcRnMonad import TcType import TcMType import TcHsSyn ( zonkTcTypeToType, mkEmptyZonkEnv ) import TcUnify import TcEnv import TyCon import Name import VarEnv import Util import VarSet import BasicTypes ( TupleSort(UnboxedTuple) ) import TysPrim import PrelNames import TysWiredIn import DynFlags import Outputable as Ppr import GHC.Arr ( Array(..) ) import GHC.Exts import GHC.IO ( IO(..) ) import StaticFlags( opt_PprStyle_Debug ) import Control.Monad import Data.Maybe import Data.Array.Base import Data.Ix import Data.List import qualified Data.Sequence as Seq import Data.Monoid (mappend) import Data.Sequence (viewl, ViewL(..)) import Foreign.Safe import System.IO.Unsafe --------------------------------------------- -- * A representation of semi evaluated Terms --------------------------------------------- data Term = Term { ty :: RttiType , dc :: Either String DataCon -- Carries a text representation if the datacon is -- not exported by the .hi file, which is the case -- for private constructors in -O0 compiled libraries , val :: HValue , subTerms :: [Term] } | Prim { ty :: RttiType , value :: [Word] } | Suspension { ctype :: ClosureType , ty :: RttiType , val :: HValue , bound_to :: Maybe Name -- Useful for printing } | NewtypeWrap{ -- At runtime there are no newtypes, and hence no -- newtype constructors. A NewtypeWrap is just a -- made-up tag saying "heads up, there used to be -- a newtype constructor here". ty :: RttiType , dc :: Either String DataCon , wrapped_term :: Term } | RefWrap { -- The contents of a reference ty :: RttiType , wrapped_term :: Term } isTerm, isSuspension, isPrim, isFun, isFunLike, isNewtypeWrap :: Term -> Bool isTerm Term{} = True isTerm _ = False isSuspension Suspension{} = True isSuspension _ = False isPrim Prim{} = True isPrim _ = False isNewtypeWrap NewtypeWrap{} = True isNewtypeWrap _ = False isFun Suspension{ctype=Fun} = True isFun _ = False isFunLike s@Suspension{ty=ty} = isFun s || isFunTy ty isFunLike _ = False termType :: Term -> RttiType termType t = ty t isFullyEvaluatedTerm :: Term -> Bool isFullyEvaluatedTerm Term {subTerms=tt} = all isFullyEvaluatedTerm tt isFullyEvaluatedTerm Prim {} = True isFullyEvaluatedTerm NewtypeWrap{wrapped_term=t} = isFullyEvaluatedTerm t isFullyEvaluatedTerm RefWrap{wrapped_term=t} = isFullyEvaluatedTerm t isFullyEvaluatedTerm _ = False instance Outputable (Term) where ppr t | Just doc <- cPprTerm cPprTermBase t = doc | otherwise = panic "Outputable Term instance" ------------------------------------------------------------------------- -- Runtime Closure Datatype and functions for retrieving closure related stuff ------------------------------------------------------------------------- data ClosureType = Constr | Fun | Thunk Int | ThunkSelector | Blackhole | AP | PAP | Indirection Int | MutVar Int | MVar Int | Other Int deriving (Show, Eq) data Closure = Closure { tipe :: ClosureType , infoPtr :: Ptr () , infoTable :: StgInfoTable , ptrs :: Array Int HValue , nonPtrs :: [Word] } instance Outputable ClosureType where ppr = text . show #include "../includes/rts/storage/ClosureTypes.h" aP_CODE, pAP_CODE :: Int aP_CODE = AP pAP_CODE = PAP #undef AP #undef PAP getClosureData :: DynFlags -> a -> IO Closure getClosureData dflags a = case unpackClosure# a of (# iptr, ptrs, nptrs #) -> do let iptr' | ghciTablesNextToCode = Ptr iptr | otherwise = -- the info pointer we get back from unpackClosure# -- is to the beginning of the standard info table, -- but the Storable instance for info tables takes -- into account the extra entry pointer when -- !ghciTablesNextToCode, so we must adjust here: Ptr iptr `plusPtr` negate (wORD_SIZE dflags) itbl <- peekItbl dflags iptr' let tipe = readCType (BCI.tipe itbl) elems = fromIntegral (BCI.ptrs itbl) ptrsList = Array 0 (elems - 1) elems ptrs nptrs_data = [W# (indexWordArray# nptrs i) | I# i <- [0.. fromIntegral (BCI.nptrs itbl)-1] ] ASSERT(elems >= 0) return () ptrsList `seq` return (Closure tipe (Ptr iptr) itbl ptrsList nptrs_data) readCType :: Integral a => a -> ClosureType readCType i | i >= CONSTR && i <= CONSTR_NOCAF_STATIC = Constr | i >= FUN && i <= FUN_STATIC = Fun | i >= THUNK && i < THUNK_SELECTOR = Thunk i' | i == THUNK_SELECTOR = ThunkSelector | i == BLACKHOLE = Blackhole | i >= IND && i <= IND_STATIC = Indirection i' | i' == aP_CODE = AP | i == AP_STACK = AP | i' == pAP_CODE = PAP | i == MUT_VAR_CLEAN || i == MUT_VAR_DIRTY= MutVar i' | i == MVAR_CLEAN || i == MVAR_DIRTY = MVar i' | otherwise = Other i' where i' = fromIntegral i isConstr, isIndirection, isThunk :: ClosureType -> Bool isConstr Constr = True isConstr _ = False isIndirection (Indirection _) = True isIndirection _ = False isThunk (Thunk _) = True isThunk ThunkSelector = True isThunk AP = True isThunk _ = False isFullyEvaluated :: DynFlags -> a -> IO Bool isFullyEvaluated dflags a = do closure <- getClosureData dflags a case tipe closure of Constr -> do are_subs_evaluated <- amapM (isFullyEvaluated dflags) (ptrs closure) return$ and are_subs_evaluated _ -> return False where amapM f = sequence . amap' f -- TODO: Fix it. Probably the otherwise case is failing, trace/debug it {- unsafeDeepSeq :: a -> b -> b unsafeDeepSeq = unsafeDeepSeq1 2 where unsafeDeepSeq1 0 a b = seq a $! b unsafeDeepSeq1 i a b -- 1st case avoids infinite loops for non reducible thunks | not (isConstr tipe) = seq a $! unsafeDeepSeq1 (i-1) a b -- | unsafePerformIO (isFullyEvaluated a) = b | otherwise = case unsafePerformIO (getClosureData a) of closure -> foldl' (flip unsafeDeepSeq) b (ptrs closure) where tipe = unsafePerformIO (getClosureType a) -} ----------------------------------- -- * Traversals for Terms ----------------------------------- type TermProcessor a b = RttiType -> Either String DataCon -> HValue -> [a] -> b data TermFold a = TermFold { fTerm :: TermProcessor a a , fPrim :: RttiType -> [Word] -> a , fSuspension :: ClosureType -> RttiType -> HValue -> Maybe Name -> a , fNewtypeWrap :: RttiType -> Either String DataCon -> a -> a , fRefWrap :: RttiType -> a -> a } data TermFoldM m a = TermFoldM {fTermM :: TermProcessor a (m a) , fPrimM :: RttiType -> [Word] -> m a , fSuspensionM :: ClosureType -> RttiType -> HValue -> Maybe Name -> m a , fNewtypeWrapM :: RttiType -> Either String DataCon -> a -> m a , fRefWrapM :: RttiType -> a -> m a } foldTerm :: TermFold a -> Term -> a foldTerm tf (Term ty dc v tt) = fTerm tf ty dc v (map (foldTerm tf) tt) foldTerm tf (Prim ty v ) = fPrim tf ty v foldTerm tf (Suspension ct ty v b) = fSuspension tf ct ty v b foldTerm tf (NewtypeWrap ty dc t) = fNewtypeWrap tf ty dc (foldTerm tf t) foldTerm tf (RefWrap ty t) = fRefWrap tf ty (foldTerm tf t) foldTermM :: Monad m => TermFoldM m a -> Term -> m a foldTermM tf (Term ty dc v tt) = mapM (foldTermM tf) tt >>= fTermM tf ty dc v foldTermM tf (Prim ty v ) = fPrimM tf ty v foldTermM tf (Suspension ct ty v b) = fSuspensionM tf ct ty v b foldTermM tf (NewtypeWrap ty dc t) = foldTermM tf t >>= fNewtypeWrapM tf ty dc foldTermM tf (RefWrap ty t) = foldTermM tf t >>= fRefWrapM tf ty idTermFold :: TermFold Term idTermFold = TermFold { fTerm = Term, fPrim = Prim, fSuspension = Suspension, fNewtypeWrap = NewtypeWrap, fRefWrap = RefWrap } mapTermType :: (RttiType -> Type) -> Term -> Term mapTermType f = foldTerm idTermFold { fTerm = \ty dc hval tt -> Term (f ty) dc hval tt, fSuspension = \ct ty hval n -> Suspension ct (f ty) hval n, fNewtypeWrap= \ty dc t -> NewtypeWrap (f ty) dc t, fRefWrap = \ty t -> RefWrap (f ty) t} mapTermTypeM :: Monad m => (RttiType -> m Type) -> Term -> m Term mapTermTypeM f = foldTermM TermFoldM { fTermM = \ty dc hval tt -> f ty >>= \ty' -> return $ Term ty' dc hval tt, fPrimM = (return.) . Prim, fSuspensionM = \ct ty hval n -> f ty >>= \ty' -> return $ Suspension ct ty' hval n, fNewtypeWrapM= \ty dc t -> f ty >>= \ty' -> return $ NewtypeWrap ty' dc t, fRefWrapM = \ty t -> f ty >>= \ty' -> return $ RefWrap ty' t} termTyVars :: Term -> TyVarSet termTyVars = foldTerm TermFold { fTerm = \ty _ _ tt -> tyVarsOfType ty `plusVarEnv` concatVarEnv tt, fSuspension = \_ ty _ _ -> tyVarsOfType ty, fPrim = \ _ _ -> emptyVarEnv, fNewtypeWrap= \ty _ t -> tyVarsOfType ty `plusVarEnv` t, fRefWrap = \ty t -> tyVarsOfType ty `plusVarEnv` t} where concatVarEnv = foldr plusVarEnv emptyVarEnv ---------------------------------- -- Pretty printing of terms ---------------------------------- type Precedence = Int type TermPrinter = Precedence -> Term -> SDoc type TermPrinterM m = Precedence -> Term -> m SDoc app_prec,cons_prec, max_prec ::Int max_prec = 10 app_prec = max_prec cons_prec = 5 -- TODO Extract this info from GHC itself pprTerm :: TermPrinter -> TermPrinter pprTerm y p t | Just doc <- pprTermM (\p -> Just . y p) p t = doc pprTerm _ _ _ = panic "pprTerm" pprTermM, ppr_termM, pprNewtypeWrap :: Monad m => TermPrinterM m -> TermPrinterM m pprTermM y p t = pprDeeper `liftM` ppr_termM y p t ppr_termM y p Term{dc=Left dc_tag, subTerms=tt} = do tt_docs <- mapM (y app_prec) tt return $ cparen (not (null tt) && p >= app_prec) (text dc_tag <+> pprDeeperList fsep tt_docs) ppr_termM y p Term{dc=Right dc, subTerms=tt} {- | dataConIsInfix dc, (t1:t2:tt') <- tt --TODO fixity = parens (ppr_term1 True t1 <+> ppr dc <+> ppr_term1 True ppr t2) <+> hsep (map (ppr_term1 True) tt) -} -- TODO Printing infix constructors properly | null sub_terms_to_show = return (ppr dc) | otherwise = do { tt_docs <- mapM (y app_prec) sub_terms_to_show ; return $ cparen (p >= app_prec) $ sep [ppr dc, nest 2 (pprDeeperList fsep tt_docs)] } where sub_terms_to_show -- Don't show the dictionary arguments to -- constructors unless -dppr-debug is on | opt_PprStyle_Debug = tt | otherwise = dropList (dataConTheta dc) tt ppr_termM y p t@NewtypeWrap{} = pprNewtypeWrap y p t ppr_termM y p RefWrap{wrapped_term=t} = do contents <- y app_prec t return$ cparen (p >= app_prec) (text "GHC.Prim.MutVar#" <+> contents) -- The constructor name is wired in here ^^^ for the sake of simplicity. -- I don't think mutvars are going to change in a near future. -- In any case this is solely a presentation matter: MutVar# is -- a datatype with no constructors, implemented by the RTS -- (hence there is no way to obtain a datacon and print it). ppr_termM _ _ t = ppr_termM1 t ppr_termM1 :: Monad m => Term -> m SDoc ppr_termM1 Prim{value=words, ty=ty} = return $ repPrim (tyConAppTyCon ty) words ppr_termM1 Suspension{ty=ty, bound_to=Nothing} = return (char '_' <+> ifPprDebug (text "::" <> ppr ty)) ppr_termM1 Suspension{ty=ty, bound_to=Just n} -- | Just _ <- splitFunTy_maybe ty = return$ ptext (sLit("<function>") | otherwise = return$ parens$ ppr n <> text "::" <> ppr ty ppr_termM1 Term{} = panic "ppr_termM1 - Term" ppr_termM1 RefWrap{} = panic "ppr_termM1 - RefWrap" ppr_termM1 NewtypeWrap{} = panic "ppr_termM1 - NewtypeWrap" pprNewtypeWrap y p NewtypeWrap{ty=ty, wrapped_term=t} | Just (tc,_) <- tcSplitTyConApp_maybe ty , ASSERT(isNewTyCon tc) True , Just new_dc <- tyConSingleDataCon_maybe tc = do real_term <- y max_prec t return $ cparen (p >= app_prec) (ppr new_dc <+> real_term) pprNewtypeWrap _ _ _ = panic "pprNewtypeWrap" ------------------------------------------------------- -- Custom Term Pretty Printers ------------------------------------------------------- -- We can want to customize the representation of a -- term depending on its type. -- However, note that custom printers have to work with -- type representations, instead of directly with types. -- We cannot use type classes here, unless we employ some -- typerep trickery (e.g. Weirich's RepLib tricks), -- which I didn't. Therefore, this code replicates a lot -- of what type classes provide for free. type CustomTermPrinter m = TermPrinterM m -> [Precedence -> Term -> (m (Maybe SDoc))] -- | Takes a list of custom printers with a explicit recursion knot and a term, -- and returns the output of the first succesful printer, or the default printer cPprTerm :: Monad m => CustomTermPrinter m -> Term -> m SDoc cPprTerm printers_ = go 0 where printers = printers_ go go prec t = do let default_ = Just `liftM` pprTermM go prec t mb_customDocs = [pp prec t | pp <- printers] ++ [default_] Just doc <- firstJustM mb_customDocs return$ cparen (prec>app_prec+1) doc firstJustM (mb:mbs) = mb >>= maybe (firstJustM mbs) (return . Just) firstJustM [] = return Nothing -- Default set of custom printers. Note that the recursion knot is explicit cPprTermBase :: forall m. Monad m => CustomTermPrinter m cPprTermBase y = [ ifTerm (isTupleTy.ty) (\_p -> liftM (parens . hcat . punctuate comma) . mapM (y (-1)) . subTerms) , ifTerm (\t -> isTyCon listTyCon (ty t) && subTerms t `lengthIs` 2) ppr_list , ifTerm (isTyCon intTyCon . ty) ppr_int , ifTerm (isTyCon charTyCon . ty) ppr_char , ifTerm (isTyCon floatTyCon . ty) ppr_float , ifTerm (isTyCon doubleTyCon . ty) ppr_double , ifTerm (isIntegerTy . ty) ppr_integer ] where ifTerm :: (Term -> Bool) -> (Precedence -> Term -> m SDoc) -> Precedence -> Term -> m (Maybe SDoc) ifTerm pred f prec t@Term{} | pred t = Just `liftM` f prec t ifTerm _ _ _ _ = return Nothing isTupleTy ty = fromMaybe False $ do (tc,_) <- tcSplitTyConApp_maybe ty return (isBoxedTupleTyCon tc) isTyCon a_tc ty = fromMaybe False $ do (tc,_) <- tcSplitTyConApp_maybe ty return (a_tc == tc) isIntegerTy ty = fromMaybe False $ do (tc,_) <- tcSplitTyConApp_maybe ty return (tyConName tc == integerTyConName) ppr_int, ppr_char, ppr_float, ppr_double, ppr_integer :: Precedence -> Term -> m SDoc ppr_int _ v = return (Ppr.int (unsafeCoerce# (val v))) ppr_char _ v = return (Ppr.char '\'' <> Ppr.char (unsafeCoerce# (val v)) <> Ppr.char '\'') ppr_float _ v = return (Ppr.float (unsafeCoerce# (val v))) ppr_double _ v = return (Ppr.double (unsafeCoerce# (val v))) ppr_integer _ v = return (Ppr.integer (unsafeCoerce# (val v))) --Note pprinting of list terms is not lazy ppr_list :: Precedence -> Term -> m SDoc ppr_list p (Term{subTerms=[h,t]}) = do let elems = h : getListTerms t isConsLast = not(termType(last elems) `eqType` termType h) is_string = all (isCharTy . ty) elems print_elems <- mapM (y cons_prec) elems if is_string then return (Ppr.doubleQuotes (Ppr.text (unsafeCoerce# (map val elems)))) else if isConsLast then return $ cparen (p >= cons_prec) $ pprDeeperList fsep $ punctuate (space<>colon) print_elems else return $ brackets $ pprDeeperList fcat $ punctuate comma print_elems where getListTerms Term{subTerms=[h,t]} = h : getListTerms t getListTerms Term{subTerms=[]} = [] getListTerms t@Suspension{} = [t] getListTerms t = pprPanic "getListTerms" (ppr t) ppr_list _ _ = panic "doList" repPrim :: TyCon -> [Word] -> SDoc repPrim t = rep where rep x | t == charPrimTyCon = text $ show (build x :: Char) | t == intPrimTyCon = text $ show (build x :: Int) | t == wordPrimTyCon = text $ show (build x :: Word) | t == floatPrimTyCon = text $ show (build x :: Float) | t == doublePrimTyCon = text $ show (build x :: Double) | t == int32PrimTyCon = text $ show (build x :: Int32) | t == word32PrimTyCon = text $ show (build x :: Word32) | t == int64PrimTyCon = text $ show (build x :: Int64) | t == word64PrimTyCon = text $ show (build x :: Word64) | t == addrPrimTyCon = text $ show (nullPtr `plusPtr` build x) | t == stablePtrPrimTyCon = text "<stablePtr>" | t == stableNamePrimTyCon = text "<stableName>" | t == statePrimTyCon = text "<statethread>" | t == proxyPrimTyCon = text "<proxy>" | t == realWorldTyCon = text "<realworld>" | t == threadIdPrimTyCon = text "<ThreadId>" | t == weakPrimTyCon = text "<Weak>" | t == arrayPrimTyCon = text "<array>" | t == byteArrayPrimTyCon = text "<bytearray>" | t == mutableArrayPrimTyCon = text "<mutableArray>" | t == mutableByteArrayPrimTyCon = text "<mutableByteArray>" | t == mutVarPrimTyCon = text "<mutVar>" | t == mVarPrimTyCon = text "<mVar>" | t == tVarPrimTyCon = text "<tVar>" | otherwise = char '<' <> ppr t <> char '>' where build ww = unsafePerformIO $ withArray ww (peek . castPtr) -- This ^^^ relies on the representation of Haskell heap values being -- the same as in a C array. ----------------------------------- -- Type Reconstruction ----------------------------------- {- Type Reconstruction is type inference done on heap closures. The algorithm walks the heap generating a set of equations, which are solved with syntactic unification. A type reconstruction equation looks like: <datacon reptype> = <actual heap contents> The full equation set is generated by traversing all the subterms, starting from a given term. The only difficult part is that newtypes are only found in the lhs of equations. Right hand sides are missing them. We can either (a) drop them from the lhs, or (b) reconstruct them in the rhs when possible. The function congruenceNewtypes takes a shot at (b) -} -- A (non-mutable) tau type containing -- existentially quantified tyvars. -- (since GHC type language currently does not support -- existentials, we leave these variables unquantified) type RttiType = Type -- An incomplete type as stored in GHCi: -- no polymorphism: no quantifiers & all tyvars are skolem. type GhciType = Type -- The Type Reconstruction monad -------------------------------- type TR a = TcM a runTR :: HscEnv -> TR a -> IO a runTR hsc_env thing = do mb_val <- runTR_maybe hsc_env thing case mb_val of Nothing -> error "unable to :print the term" Just x -> return x runTR_maybe :: HscEnv -> TR a -> IO (Maybe a) runTR_maybe hsc_env = fmap snd . initTc hsc_env HsSrcFile False iNTERACTIVE traceTR :: SDoc -> TR () traceTR = liftTcM . traceOptTcRn Opt_D_dump_rtti -- Semantically different to recoverM in TcRnMonad -- recoverM retains the errors in the first action, -- whereas recoverTc here does not recoverTR :: TR a -> TR a -> TR a recoverTR recover thing = do (_,mb_res) <- tryTcErrs thing case mb_res of Nothing -> recover Just res -> return res trIO :: IO a -> TR a trIO = liftTcM . liftIO liftTcM :: TcM a -> TR a liftTcM = id newVar :: Kind -> TR TcType newVar = liftTcM . newFlexiTyVarTy instTyVars :: [TyVar] -> TR ([TcTyVar], [TcType], TvSubst) -- Instantiate fresh mutable type variables from some TyVars -- This function preserves the print-name, which helps error messages instTyVars = liftTcM . tcInstTyVars type RttiInstantiation = [(TcTyVar, TyVar)] -- Associates the typechecker-world meta type variables -- (which are mutable and may be refined), to their -- debugger-world RuntimeUnk counterparts. -- If the TcTyVar has not been refined by the runtime type -- elaboration, then we want to turn it back into the -- original RuntimeUnk -- | Returns the instantiated type scheme ty', and the -- mapping from new (instantiated) -to- old (skolem) type variables instScheme :: QuantifiedType -> TR (TcType, RttiInstantiation) instScheme (tvs, ty) = liftTcM $ do { (tvs', _, subst) <- tcInstTyVars tvs ; let rtti_inst = [(tv',tv) | (tv',tv) <- tvs' `zip` tvs] ; return (substTy subst ty, rtti_inst) } applyRevSubst :: RttiInstantiation -> TR () -- Apply the *reverse* substitution in-place to any un-filled-in -- meta tyvars. This recovers the original debugger-world variable -- unless it has been refined by new information from the heap applyRevSubst pairs = liftTcM (mapM_ do_pair pairs) where do_pair (tc_tv, rtti_tv) = do { tc_ty <- zonkTcTyVar tc_tv ; case tcGetTyVar_maybe tc_ty of Just tv | isMetaTyVar tv -> writeMetaTyVar tv (mkTyVarTy rtti_tv) _ -> return () } -- Adds a constraint of the form t1 == t2 -- t1 is expected to come from walking the heap -- t2 is expected to come from a datacon signature -- Before unification, congruenceNewtypes needs to -- do its magic. addConstraint :: TcType -> TcType -> TR () addConstraint actual expected = do traceTR (text "add constraint:" <+> fsep [ppr actual, equals, ppr expected]) recoverTR (traceTR $ fsep [text "Failed to unify", ppr actual, text "with", ppr expected]) $ do { (ty1, ty2) <- congruenceNewtypes actual expected ; _ <- captureConstraints $ unifyType ty1 ty2 ; return () } -- TOMDO: what about the coercion? -- we should consider family instances -- Type & Term reconstruction ------------------------------ cvObtainTerm :: HscEnv -> Int -> Bool -> RttiType -> HValue -> IO Term cvObtainTerm hsc_env max_depth force old_ty hval = runTR hsc_env $ do -- we quantify existential tyvars as universal, -- as this is needed to be able to manipulate -- them properly let quant_old_ty@(old_tvs, old_tau) = quantifyType old_ty sigma_old_ty = mkForAllTys old_tvs old_tau traceTR (text "Term reconstruction started with initial type " <> ppr old_ty) term <- if null old_tvs then do term <- go max_depth sigma_old_ty sigma_old_ty hval term' <- zonkTerm term return $ fixFunDictionaries $ expandNewtypes term' else do (old_ty', rev_subst) <- instScheme quant_old_ty my_ty <- newVar openTypeKind when (check1 quant_old_ty) (traceTR (text "check1 passed") >> addConstraint my_ty old_ty') term <- go max_depth my_ty sigma_old_ty hval new_ty <- zonkTcType (termType term) if isMonomorphic new_ty || check2 (quantifyType new_ty) quant_old_ty then do traceTR (text "check2 passed") addConstraint new_ty old_ty' applyRevSubst rev_subst zterm' <- zonkTerm term return ((fixFunDictionaries . expandNewtypes) zterm') else do traceTR (text "check2 failed" <+> parens (ppr term <+> text "::" <+> ppr new_ty)) -- we have unsound types. Replace constructor types in -- subterms with tyvars zterm' <- mapTermTypeM (\ty -> case tcSplitTyConApp_maybe ty of Just (tc, _:_) | tc /= funTyCon -> newVar openTypeKind _ -> return ty) term zonkTerm zterm' traceTR (text "Term reconstruction completed." $$ text "Term obtained: " <> ppr term $$ text "Type obtained: " <> ppr (termType term)) return term where dflags = hsc_dflags hsc_env go :: Int -> Type -> Type -> HValue -> TcM Term -- [SPJ May 11] I don't understand the difference between my_ty and old_ty go max_depth _ _ _ | seq max_depth False = undefined go 0 my_ty _old_ty a = do traceTR (text "Gave up reconstructing a term after" <> int max_depth <> text " steps") clos <- trIO $ getClosureData dflags a return (Suspension (tipe clos) my_ty a Nothing) go max_depth my_ty old_ty a = do let monomorphic = not(isTyVarTy my_ty) -- This ^^^ is a convention. The ancestor tests for -- monomorphism and passes a type instead of a tv clos <- trIO $ getClosureData dflags a case tipe clos of -- Thunks we may want to force t | isThunk t && force -> traceTR (text "Forcing a " <> text (show t)) >> seq a (go (pred max_depth) my_ty old_ty a) -- Blackholes are indirections iff the payload is not TSO or BLOCKING_QUEUE. So we -- treat them like indirections; if the payload is TSO or BLOCKING_QUEUE, we'll end up -- showing '_' which is what we want. Blackhole -> do traceTR (text "Following a BLACKHOLE") appArr (go max_depth my_ty old_ty) (ptrs clos) 0 -- We always follow indirections Indirection i -> do traceTR (text "Following an indirection" <> parens (int i) ) go max_depth my_ty old_ty $! (ptrs clos ! 0) -- We also follow references MutVar _ | Just (tycon,[world,contents_ty]) <- tcSplitTyConApp_maybe old_ty -> do -- Deal with the MutVar# primitive -- It does not have a constructor at all, -- so we simulate the following one -- MutVar# :: contents_ty -> MutVar# s contents_ty traceTR (text "Following a MutVar") contents_tv <- newVar liftedTypeKind contents <- trIO$ IO$ \w -> readMutVar# (unsafeCoerce# a) w ASSERT(isUnliftedTypeKind $ typeKind my_ty) return () (mutvar_ty,_) <- instScheme $ quantifyType $ mkFunTy contents_ty (mkTyConApp tycon [world,contents_ty]) addConstraint (mkFunTy contents_tv my_ty) mutvar_ty x <- go (pred max_depth) contents_tv contents_ty contents return (RefWrap my_ty x) -- The interesting case Constr -> do traceTR (text "entering a constructor " <> if monomorphic then parens (text "already monomorphic: " <> ppr my_ty) else Ppr.empty) Right dcname <- dataConInfoPtrToName (infoPtr clos) (_,mb_dc) <- tryTcErrs (tcLookupDataCon dcname) case mb_dc of Nothing -> do -- This can happen for private constructors compiled -O0 -- where the .hi descriptor does not export them -- In such case, we return a best approximation: -- ignore the unpointed args, and recover the pointeds -- This preserves laziness, and should be safe. traceTR (text "Not constructor" <+> ppr dcname) let dflags = hsc_dflags hsc_env tag = showPpr dflags dcname vars <- replicateM (length$ elems$ ptrs clos) (newVar liftedTypeKind) subTerms <- sequence [appArr (go (pred max_depth) tv tv) (ptrs clos) i | (i, tv) <- zip [0..] vars] return (Term my_ty (Left ('<' : tag ++ ">")) a subTerms) Just dc -> do traceTR (text "Is constructor" <+> (ppr dc $$ ppr my_ty)) subTtypes <- getDataConArgTys dc my_ty subTerms <- extractSubTerms (\ty -> go (pred max_depth) ty ty) clos subTtypes return (Term my_ty (Right dc) a subTerms) -- The otherwise case: can be a Thunk,AP,PAP,etc. tipe_clos -> return (Suspension tipe_clos my_ty a Nothing) -- insert NewtypeWraps around newtypes expandNewtypes = foldTerm idTermFold { fTerm = worker } where worker ty dc hval tt | Just (tc, args) <- tcSplitTyConApp_maybe ty , isNewTyCon tc , wrapped_type <- newTyConInstRhs tc args , Just dc' <- tyConSingleDataCon_maybe tc , t' <- worker wrapped_type dc hval tt = NewtypeWrap ty (Right dc') t' | otherwise = Term ty dc hval tt -- Avoid returning types where predicates have been expanded to dictionaries. fixFunDictionaries = foldTerm idTermFold {fSuspension = worker} where worker ct ty hval n | isFunTy ty = Suspension ct (dictsView ty) hval n | otherwise = Suspension ct ty hval n extractSubTerms :: (Type -> HValue -> TcM Term) -> Closure -> [Type] -> TcM [Term] extractSubTerms recurse clos = liftM thirdOf3 . go 0 (nonPtrs clos) where go ptr_i ws [] = return (ptr_i, ws, []) go ptr_i ws (ty:tys) | Just (tc, elem_tys) <- tcSplitTyConApp_maybe ty , isUnboxedTupleTyCon tc = do (ptr_i, ws, terms0) <- go ptr_i ws elem_tys (ptr_i, ws, terms1) <- go ptr_i ws tys return (ptr_i, ws, unboxedTupleTerm ty terms0 : terms1) | otherwise = case repType ty of UnaryRep rep_ty -> do (ptr_i, ws, term0) <- go_rep ptr_i ws ty (typePrimRep rep_ty) (ptr_i, ws, terms1) <- go ptr_i ws tys return (ptr_i, ws, term0 : terms1) UbxTupleRep rep_tys -> do (ptr_i, ws, terms0) <- go_unary_types ptr_i ws rep_tys (ptr_i, ws, terms1) <- go ptr_i ws tys return (ptr_i, ws, unboxedTupleTerm ty terms0 : terms1) go_unary_types ptr_i ws [] = return (ptr_i, ws, []) go_unary_types ptr_i ws (rep_ty:rep_tys) = do tv <- newVar liftedTypeKind (ptr_i, ws, term0) <- go_rep ptr_i ws tv (typePrimRep rep_ty) (ptr_i, ws, terms1) <- go_unary_types ptr_i ws rep_tys return (ptr_i, ws, term0 : terms1) go_rep ptr_i ws ty rep = case rep of PtrRep -> do t <- appArr (recurse ty) (ptrs clos) ptr_i return (ptr_i + 1, ws, t) _ -> do dflags <- getDynFlags let (ws0, ws1) = splitAt (primRepSizeW dflags rep) ws return (ptr_i, ws1, Prim ty ws0) unboxedTupleTerm ty terms = Term ty (Right (tupleCon UnboxedTuple (length terms))) (error "unboxedTupleTerm: no HValue for unboxed tuple") terms -- Fast, breadth-first Type reconstruction ------------------------------------------ cvReconstructType :: HscEnv -> Int -> GhciType -> HValue -> IO (Maybe Type) cvReconstructType hsc_env max_depth old_ty hval = runTR_maybe hsc_env $ do traceTR (text "RTTI started with initial type " <> ppr old_ty) let sigma_old_ty@(old_tvs, _) = quantifyType old_ty new_ty <- if null old_tvs then return old_ty else do (old_ty', rev_subst) <- instScheme sigma_old_ty my_ty <- newVar openTypeKind when (check1 sigma_old_ty) (traceTR (text "check1 passed") >> addConstraint my_ty old_ty') search (isMonomorphic `fmap` zonkTcType my_ty) (\(ty,a) -> go ty a) (Seq.singleton (my_ty, hval)) max_depth new_ty <- zonkTcType my_ty if isMonomorphic new_ty || check2 (quantifyType new_ty) sigma_old_ty then do traceTR (text "check2 passed" <+> ppr old_ty $$ ppr new_ty) addConstraint my_ty old_ty' applyRevSubst rev_subst zonkRttiType new_ty else traceTR (text "check2 failed" <+> parens (ppr new_ty)) >> return old_ty traceTR (text "RTTI completed. Type obtained:" <+> ppr new_ty) return new_ty where dflags = hsc_dflags hsc_env -- search :: m Bool -> ([a] -> [a] -> [a]) -> [a] -> m () search _ _ _ 0 = traceTR (text "Failed to reconstruct a type after " <> int max_depth <> text " steps") search stop expand l d = case viewl l of EmptyL -> return () x :< xx -> unlessM stop $ do new <- expand x search stop expand (xx `mappend` Seq.fromList new) $! (pred d) -- returns unification tasks,since we are going to want a breadth-first search go :: Type -> HValue -> TR [(Type, HValue)] go my_ty a = do traceTR (text "go" <+> ppr my_ty) clos <- trIO $ getClosureData dflags a case tipe clos of Blackhole -> appArr (go my_ty) (ptrs clos) 0 -- carefully, don't eval the TSO Indirection _ -> go my_ty $! (ptrs clos ! 0) MutVar _ -> do contents <- trIO$ IO$ \w -> readMutVar# (unsafeCoerce# a) w tv' <- newVar liftedTypeKind world <- newVar liftedTypeKind addConstraint my_ty (mkTyConApp mutVarPrimTyCon [world,tv']) return [(tv', contents)] Constr -> do Right dcname <- dataConInfoPtrToName (infoPtr clos) traceTR (text "Constr1" <+> ppr dcname) (_,mb_dc) <- tryTcErrs (tcLookupDataCon dcname) case mb_dc of Nothing-> do -- TODO: Check this case forM [0..length (elems $ ptrs clos)] $ \i -> do tv <- newVar liftedTypeKind return$ appArr (\e->(tv,e)) (ptrs clos) i Just dc -> do arg_tys <- getDataConArgTys dc my_ty (_, itys) <- findPtrTyss 0 arg_tys traceTR (text "Constr2" <+> ppr dcname <+> ppr arg_tys) return $ [ appArr (\e-> (ty,e)) (ptrs clos) i | (i,ty) <- itys] _ -> return [] findPtrTys :: Int -- Current pointer index -> Type -- Type -> TR (Int, [(Int, Type)]) findPtrTys i ty | Just (tc, elem_tys) <- tcSplitTyConApp_maybe ty , isUnboxedTupleTyCon tc = findPtrTyss i elem_tys | otherwise = case repType ty of UnaryRep rep_ty | typePrimRep rep_ty == PtrRep -> return (i + 1, [(i, ty)]) | otherwise -> return (i, []) UbxTupleRep rep_tys -> foldM (\(i, extras) rep_ty -> if typePrimRep rep_ty == PtrRep then newVar liftedTypeKind >>= \tv -> return (i + 1, extras ++ [(i, tv)]) else return (i, extras)) (i, []) rep_tys findPtrTyss :: Int -> [Type] -> TR (Int, [(Int, Type)]) findPtrTyss i tys = foldM step (i, []) tys where step (i, discovered) elem_ty = findPtrTys i elem_ty >>= \(i, extras) -> return (i, discovered ++ extras) -- Compute the difference between a base type and the type found by RTTI -- improveType <base_type> <rtti_type> -- The types can contain skolem type variables, which need to be treated as normal vars. -- In particular, we want them to unify with things. improveRTTIType :: HscEnv -> RttiType -> RttiType -> Maybe TvSubst improveRTTIType _ base_ty new_ty = U.tcUnifyTys (const U.BindMe) [base_ty] [new_ty] getDataConArgTys :: DataCon -> Type -> TR [Type] -- Given the result type ty of a constructor application (D a b c :: ty) -- return the types of the arguments. This is RTTI-land, so 'ty' might -- not be fully known. Moreover, the arg types might involve existentials; -- if so, make up fresh RTTI type variables for them getDataConArgTys dc con_app_ty = do { (_, ex_tys, ex_subst) <- instTyVars ex_tvs ; let UnaryRep rep_con_app_ty = repType con_app_ty ; traceTR (text "getDataConArgTys 1" <+> (ppr con_app_ty $$ ppr rep_con_app_ty)) ; ty_args <- case tcSplitTyConApp_maybe rep_con_app_ty of Just (tc, ty_args) | dataConTyCon dc == tc -> ASSERT( univ_tvs `equalLength` ty_args) return ty_args _ -> do { (_, ty_args, univ_subst) <- instTyVars univ_tvs ; let res_ty = substTy ex_subst (substTy univ_subst (dataConOrigResTy dc)) -- See Note [Constructor arg types] ; addConstraint rep_con_app_ty res_ty ; return ty_args } -- It is necessary to check dataConTyCon dc == tc -- because it may be the case that tc is a recursive -- newtype and tcSplitTyConApp has not removed it. In -- that case, we happily give up and don't match ; let subst = zipTopTvSubst (univ_tvs ++ ex_tvs) (ty_args ++ ex_tys) ; traceTR (text "getDataConArgTys 2" <+> (ppr rep_con_app_ty $$ ppr ty_args $$ ppr subst)) ; return (substTys subst (dataConRepArgTys dc)) } where univ_tvs = dataConUnivTyVars dc ex_tvs = dataConExTyVars dc {- Note [Constructor arg types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider a GADT (cf Trac #7386) data family D a b data instance D [a] b where MkT :: b -> D [a] (Maybe b) In getDataConArgTys * con_app_ty is the known type (from outside) of the constructor application, say D [Int] Bool * The data constructor MkT has a (representation) dataConTyCon = DList, say where data DList a b where MkT :: b -> DList a (Maybe b) So the dataConTyCon of the data constructor, DList, differs from the "outside" type, D. So we can't straightforwardly decompose the "outside" type, and we end up in the "_" branch of the case. Then we match the dataConOrigResTy of the data constructor against the outside type, hoping to get a substitution that tells how to instantiate the *representation* type constructor. This looks a bit delicate to me, but it seems to work. -} -- Soundness checks -------------------- {- This is not formalized anywhere, so hold to your seats! RTTI in the presence of newtypes can be a tricky and unsound business. Example: ~~~~~~~~~ Suppose we are doing RTTI for a partially evaluated closure t, the real type of which is t :: MkT Int, for newtype MkT a = MkT [Maybe a] The table below shows the results of RTTI and the improvement calculated for different combinations of evaluatedness and :type t. Regard the two first columns as input and the next two as output. # | t | :type t | rtti(t) | improv. | result ------------------------------------------------------------ 1 | _ | t b | a | none | OK 2 | _ | MkT b | a | none | OK 3 | _ | t Int | a | none | OK If t is not evaluated at *all*, we are safe. 4 | (_ : _) | t b | [a] | t = [] | UNSOUND 5 | (_ : _) | MkT b | MkT a | none | OK (compensating for the missing newtype) 6 | (_ : _) | t Int | [Int] | t = [] | UNSOUND If a is a minimal whnf, we run into trouble. Note that row 5 above does newtype enrichment on the ty_rtty parameter. 7 | (Just _:_)| t b |[Maybe a] | t = [], | UNSOUND | | | b = Maybe a| 8 | (Just _:_)| MkT b | MkT a | none | OK 9 | (Just _:_)| t Int | FAIL | none | OK And if t is any more evaluated than whnf, we are still in trouble. Because constraints are solved in top-down order, when we reach the Maybe subterm what we got is already unsound. This explains why the row 9 fails to complete. 10 | (Just _:_)| t Int | [Maybe a] | FAIL | OK 11 | (Just 1:_)| t Int | [Maybe Int] | FAIL | OK We can undo the failure in row 9 by leaving out the constraint coming from the type signature of t (i.e., the 2nd column). Note that this type information is still used to calculate the improvement. But we fail when trying to calculate the improvement, as there is no unifier for t Int = [Maybe a] or t Int = [Maybe Int]. Another set of examples with t :: [MkT (Maybe Int)] \equiv [[Maybe (Maybe Int)]] # | t | :type t | rtti(t) | improvement | result --------------------------------------------------------------------- 1 |(Just _:_) | [t (Maybe a)] | [[Maybe b]] | t = [] | | | | | b = Maybe a | The checks: ~~~~~~~~~~~ Consider a function obtainType that takes a value and a type and produces the Term representation and a substitution (the improvement). Assume an auxiliar rtti' function which does the actual job if recovering the type, but which may produce a false type. In pseudocode: rtti' :: a -> IO Type -- Does not use the static type information obtainType :: a -> Type -> IO (Maybe (Term, Improvement)) obtainType v old_ty = do rtti_ty <- rtti' v if monomorphic rtti_ty || (check rtti_ty old_ty) then ... else return Nothing where check rtti_ty old_ty = check1 rtti_ty && check2 rtti_ty old_ty check1 :: Type -> Bool check2 :: Type -> Type -> Bool Now, if rtti' returns a monomorphic type, we are safe. If that is not the case, then we consider two conditions. 1. To prevent the class of unsoundness displayed by rows 4 and 7 in the example: no higher kind tyvars accepted. check1 (t a) = NO check1 (t Int) = NO check1 ([] a) = YES 2. To prevent the class of unsoundness shown by row 6, the rtti type should be structurally more defined than the old type we are comparing it to. check2 :: NewType -> OldType -> Bool check2 a _ = True check2 [a] a = True check2 [a] (t Int) = False check2 [a] (t a) = False -- By check1 we never reach this equation check2 [Int] a = True check2 [Int] (t Int) = True check2 [Maybe a] (t Int) = False check2 [Maybe Int] (t Int) = True check2 (Maybe [a]) (m [Int]) = False check2 (Maybe [Int]) (m [Int]) = True -} check1 :: QuantifiedType -> Bool check1 (tvs, _) = not $ any isHigherKind (map tyVarKind tvs) where isHigherKind = not . null . fst . splitKindFunTys check2 :: QuantifiedType -> QuantifiedType -> Bool check2 (_, rtti_ty) (_, old_ty) | Just (_, rttis) <- tcSplitTyConApp_maybe rtti_ty = case () of _ | Just (_,olds) <- tcSplitTyConApp_maybe old_ty -> and$ zipWith check2 (map quantifyType rttis) (map quantifyType olds) _ | Just _ <- splitAppTy_maybe old_ty -> isMonomorphicOnNonPhantomArgs rtti_ty _ -> True | otherwise = True -- Dealing with newtypes -------------------------- {- congruenceNewtypes does a parallel fold over two Type values, compensating for missing newtypes on both sides. This is necessary because newtypes are not present in runtime, but sometimes there is evidence available. Evidence can come from DataCon signatures or from compile-time type inference. What we are doing here is an approximation of unification modulo a set of equations derived from newtype definitions. These equations should be the same as the equality coercions generated for newtypes in System Fc. The idea is to perform a sort of rewriting, taking those equations as rules, before launching unification. The caller must ensure the following. The 1st type (lhs) comes from the heap structure of ptrs,nptrs. The 2nd type (rhs) comes from a DataCon type signature. Rewriting (i.e. adding/removing a newtype wrapper) can happen in both types, but in the rhs it is restricted to the result type. Note that it is very tricky to make this 'rewriting' work with the unification implemented by TcM, where substitutions are operationally inlined. The order in which constraints are unified is vital as we cannot modify anything that has been touched by a previous unification step. Therefore, congruenceNewtypes is sound only if the types recovered by the RTTI mechanism are unified Top-Down. -} congruenceNewtypes :: TcType -> TcType -> TR (TcType,TcType) congruenceNewtypes lhs rhs = go lhs rhs >>= \rhs' -> return (lhs,rhs') where go l r -- TyVar lhs inductive case | Just tv <- getTyVar_maybe l , isTcTyVar tv , isMetaTyVar tv = recoverTR (return r) $ do Indirect ty_v <- readMetaTyVar tv traceTR $ fsep [text "(congruence) Following indirect tyvar:", ppr tv, equals, ppr ty_v] go ty_v r -- FunTy inductive case | Just (l1,l2) <- splitFunTy_maybe l , Just (r1,r2) <- splitFunTy_maybe r = do r2' <- go l2 r2 r1' <- go l1 r1 return (mkFunTy r1' r2') -- TyconApp Inductive case; this is the interesting bit. | Just (tycon_l, _) <- tcSplitTyConApp_maybe lhs , Just (tycon_r, _) <- tcSplitTyConApp_maybe rhs , tycon_l /= tycon_r = upgrade tycon_l r | otherwise = return r where upgrade :: TyCon -> Type -> TR Type upgrade new_tycon ty | not (isNewTyCon new_tycon) = do traceTR (text "(Upgrade) Not matching newtype evidence: " <> ppr new_tycon <> text " for " <> ppr ty) return ty | otherwise = do traceTR (text "(Upgrade) upgraded " <> ppr ty <> text " in presence of newtype evidence " <> ppr new_tycon) (_, vars, _) <- instTyVars (tyConTyVars new_tycon) let ty' = mkTyConApp new_tycon vars UnaryRep rep_ty = repType ty' _ <- liftTcM (unifyType ty rep_ty) -- assumes that reptype doesn't ^^^^ touch tyconApp args return ty' zonkTerm :: Term -> TcM Term zonkTerm = foldTermM (TermFoldM { fTermM = \ty dc v tt -> zonkRttiType ty >>= \ty' -> return (Term ty' dc v tt) , fSuspensionM = \ct ty v b -> zonkRttiType ty >>= \ty -> return (Suspension ct ty v b) , fNewtypeWrapM = \ty dc t -> zonkRttiType ty >>= \ty' -> return$ NewtypeWrap ty' dc t , fRefWrapM = \ty t -> return RefWrap `ap` zonkRttiType ty `ap` return t , fPrimM = (return.) . Prim }) zonkRttiType :: TcType -> TcM Type -- Zonk the type, replacing any unbound Meta tyvars -- by skolems, safely out of Meta-tyvar-land zonkRttiType = zonkTcTypeToType (mkEmptyZonkEnv zonk_unbound_meta) where zonk_unbound_meta tv = ASSERT( isTcTyVar tv ) do { tv' <- skolemiseUnboundMetaTyVar tv RuntimeUnk -- This is where RuntimeUnks are born: -- otherwise-unconstrained unification variables are -- turned into RuntimeUnks as they leave the -- typechecker's monad ; return (mkTyVarTy tv') } -------------------------------------------------------------------------------- -- Restore Class predicates out of a representation type dictsView :: Type -> Type dictsView ty = ty -- Use only for RTTI types isMonomorphic :: RttiType -> Bool isMonomorphic ty = noExistentials && noUniversals where (tvs, _, ty') = tcSplitSigmaTy ty noExistentials = isEmptyVarSet (tyVarsOfType ty') noUniversals = null tvs -- Use only for RTTI types isMonomorphicOnNonPhantomArgs :: RttiType -> Bool isMonomorphicOnNonPhantomArgs ty | UnaryRep rep_ty <- repType ty , Just (tc, all_args) <- tcSplitTyConApp_maybe rep_ty , phantom_vars <- tyConPhantomTyVars tc , concrete_args <- [ arg | (tyv,arg) <- tyConTyVars tc `zip` all_args , tyv `notElem` phantom_vars] = all isMonomorphicOnNonPhantomArgs concrete_args | Just (ty1, ty2) <- splitFunTy_maybe ty = all isMonomorphicOnNonPhantomArgs [ty1,ty2] | otherwise = isMonomorphic ty tyConPhantomTyVars :: TyCon -> [TyVar] tyConPhantomTyVars tc | isAlgTyCon tc , Just dcs <- tyConDataCons_maybe tc , dc_vars <- concatMap dataConUnivTyVars dcs = tyConTyVars tc \\ dc_vars tyConPhantomTyVars _ = [] type QuantifiedType = ([TyVar], Type) -- Make the free type variables explicit quantifyType :: Type -> QuantifiedType -- Generalize the type: find all free tyvars and wrap in the appropiate ForAll. quantifyType ty = (varSetElems (tyVarsOfType ty), ty) unlessM :: Monad m => m Bool -> m () -> m () unlessM condM acc = condM >>= \c -> unless c acc -- Strict application of f at index i appArr :: Ix i => (e -> a) -> Array i e -> Int -> a appArr f a@(Array _ _ _ ptrs#) i@(I# i#) = ASSERT2(i < length(elems a), ppr(length$ elems a, i)) case indexArray# ptrs# i# of (# e #) -> f e amap' :: (t -> b) -> Array Int t -> [b] amap' f (Array i0 i _ arr#) = map g [0 .. i - i0] where g (I# i#) = case indexArray# arr# i# of (# e #) -> f e
ekmett/ghc
compiler/ghci/RtClosureInspect.hs
bsd-3-clause
52,534
249
24
16,143
11,644
6,133
5,511
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Model where import Data.ByteString (ByteString) import Data.Text (Text) import Database.Persist.Quasi import Yesod import Data.Typeable (Typeable) share [mkPersist sqlSettings, mkMigrate "migrateAll"] $(persistFileWith lowerCaseSettings "config/models")
mikesteele81/soh-file-server-tutorial-project
src/Model.hs
bsd-3-clause
467
0
8
55
78
46
32
14
0
{-# LANGUAGE CPP #-} {- arch-tag: Syslog handler Copyright (C) 2004-2006 John Goerzen <jgoerzen@complete.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -} {- | Module : System.Log.Handler.Syslog Copyright : Copyright (C) 2004-2006 John Goerzen License : GNU LGPL, version 2.1 or above Maintainer : John Goerzen <jgoerzen@complete.org> Stability : provisional Portability: portable Syslog handler for the Haskell Logging Framework Written by John Goerzen, jgoerzen\@complete.org This module implements an interface to the Syslog service commonly found in Unix\/Linux systems. This interface is primarily of interest to developers of servers, as Syslog does not typically display messages in an interactive fashion. This module is written in pure Haskell and is capable of logging to a local or remote machine using the Syslog protocol. You can create a new Syslog 'LogHandler' by calling 'openlog'. More information on the Haskell Logging Framework can be found at "System.Log.Logger". This module can also be used outside of the rest of that framework for those interested in that. -} module System.Log.Handler.Syslog( -- * Handler Initialization openlog, -- * Advanced handler initialization #ifndef mingw32_HOST_OS openlog_local, #endif openlog_remote, openlog_generic, -- * Data Types Facility(..), Option(..) ) where import System.Log import System.Log.Handler import Data.Bits import Network.Socket import Network.BSD import Data.List #ifndef mingw32_HOST_OS import System.Posix.Process(getProcessID) #endif import System.IO code_of_pri :: Priority -> Int code_of_pri p = case p of EMERGENCY -> 0 ALERT -> 1 CRITICAL -> 2 ERROR -> 3 WARNING -> 4 NOTICE -> 5 INFO -> 6 DEBUG -> 7 {- | Facilities are used by the system to determine where messages are sent. -} data Facility = KERN -- ^ Kernel messages; you should likely never use this in your programs | USER -- ^ General userland messages. Use this if nothing else is appropriate | MAIL -- ^ E-Mail system | DAEMON -- ^ Daemon (server process) messages | AUTH -- ^ Authentication or security messages | SYSLOG -- ^ Internal syslog messages; you should likely never use this in your programs | LPR -- ^ Printer messages | NEWS -- ^ Usenet news | UUCP -- ^ UUCP messages | CRON -- ^ Cron messages | AUTHPRIV -- ^ Private authentication messages | FTP -- ^ FTP messages | LOCAL0 -- ^ LOCAL0 through LOCAL7 are reserved for you to customize as you wish | LOCAL1 | LOCAL2 | LOCAL3 | LOCAL4 | LOCAL5 | LOCAL6 | LOCAL7 deriving (Eq, Show, Read) code_of_fac :: Facility -> Int code_of_fac f = case f of KERN -> 0 USER -> 1 MAIL -> 2 DAEMON -> 3 AUTH -> 4 SYSLOG -> 5 LPR -> 6 NEWS -> 7 UUCP -> 8 CRON -> 9 AUTHPRIV -> 10 FTP -> 11 LOCAL0 -> 16 LOCAL1 -> 17 LOCAL2 -> 18 LOCAL3 -> 19 LOCAL4 -> 20 LOCAL5 -> 21 LOCAL6 -> 22 LOCAL7 -> 23 makeCode :: Facility -> Priority -> Int makeCode fac pri = let faccode = code_of_fac fac pricode = code_of_pri pri in (faccode `shiftL` 3) .|. pricode {- | Options for 'openlog'. -} data Option = PID -- ^ Automatically log process ID (PID) with each message | PERROR -- ^ Send a copy of each message to stderr deriving (Eq,Show,Read) data SyslogHandler = SyslogHandler {options :: [Option], facility :: Facility, identity :: String, logsocket :: Socket, address :: SockAddr, priority :: Priority} {- | Initialize the Syslog system using the local system's default interface, \/dev\/log. Will return a new 'System.Log.Handler.LogHandler'. On Windows, instead of using \/dev\/log, this will attempt to send UDP messages to something listening on the syslog port (514) on localhost. Use 'openlog_remote' if you need more control. -} openlog :: String -- ^ The name of this program -- will be prepended to every log message -> [Option] -- ^ A list of 'Option's. The list [] is perfectly valid. ['PID'] is probably most common here. -> Facility -- ^ The 'Facility' value to pass to the syslog system for every message logged -> Priority -- ^ Messages logged below this priority will be ignored. To include every message, set this to 'DEBUG'. -> IO SyslogHandler -- ^ Returns the new handler #ifdef mingw32_HOST_OS openlog = openlog_remote AF_INET "localhost" 514 #else openlog = openlog_local "/dev/log" #endif {- | Initialize the Syslog system using an arbitrary Unix socket (FIFO). Not supported under Windows. -} #ifndef mingw32_HOST_OS openlog_local :: String -- ^ Path to FIFO -> String -- ^ Program name -> [Option] -- ^ 'Option's -> Facility -- ^ Facility value -> Priority -- ^ Priority limit -> IO SyslogHandler openlog_local fifopath ident options fac pri = do s <- socket AF_UNIX Datagram 0 openlog_generic s (SockAddrUnix "/dev/log") ident options fac pri #endif {- | Log to a remote server via UDP. -} openlog_remote :: Family -- ^ Usually AF_INET or AF_INET6; see Network.Socket -> HostName -- ^ Remote hostname. Some use @localhost@ -> PortNumber -- ^ 514 is the default for syslog -> String -- ^ Program name -> [Option] -- ^ 'Option's -> Facility -- ^ Facility value -> Priority -- ^ Priority limit -> IO SyslogHandler openlog_remote fam hostname port ident options fac pri = do he <- getHostByName hostname s <- socket fam Datagram 0 let addr = SockAddrInet port (head (hostAddresses he)) openlog_generic s addr ident options fac pri {- | The most powerful initialization mechanism. Takes an open datagram socket. -} openlog_generic :: Socket -- ^ A datagram socket -> SockAddr -- ^ Address for transmissions -> String -- ^ Program name -> [Option] -- ^ 'Option's -> Facility -- ^ Facility value -> Priority -- ^ Priority limit -> IO SyslogHandler openlog_generic sock addr ident opt fac pri = return (SyslogHandler {options = opt, facility = fac, identity = ident, logsocket = sock, address = addr, priority = pri}) instance LogHandler SyslogHandler where setLevel sh p = sh{priority = p} getLevel sh = priority sh emit sh (p, msg) loggername = let code = makeCode (facility sh) p getpid :: IO String getpid = if (elem PID (options sh)) then do #ifndef mingw32_HOST_OS pid <- getProcessID #else let pid = "windows" #endif return ("[" ++ show pid ++ "]") else return "" sendstr :: String -> IO String sendstr [] = return [] sendstr omsg = do sent <- sendTo (logsocket sh) omsg (address sh) sendstr (genericDrop sent omsg) in do pidstr <- getpid let outstr = "<" ++ (show code) ++ ">" ++ (identity sh) ++ pidstr ++ ": " ++ "[" ++ loggername ++ "/" ++ (show p) ++ "] " ++ msg if (elem PERROR (options sh)) then hPutStrLn stderr outstr else return () sendstr (outstr ++ "\0") return () close sh = sClose (logsocket sh)
abuiles/turbinado-blog
tmp/dependencies/hslogger-1.0.6/src/System/Log/Handler/Syslog.hs
bsd-3-clause
10,341
0
25
4,391
1,277
699
578
155
20
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TemplateHaskellQuotes #-} module Data.Aeson.Key ( Key, fromString, toString, toText, fromText, coercionToText, toShortText, fromShortText, ) where import Prelude (Eq, Ord, (.), Show (..), String, Maybe (..)) import Control.Applicative ((<$>)) import Control.DeepSeq (NFData(..)) import Data.Data (Data) import Data.Hashable (Hashable(..)) import Data.Monoid (Monoid(mempty, mappend)) import Data.Semigroup (Semigroup((<>))) import Data.Text (Text) import Data.Type.Coercion (Coercion (..)) import Data.Typeable (Typeable) import Text.Read (Read (..)) import qualified Data.String import qualified Data.Text as T import qualified Data.Text.Short as ST import qualified Language.Haskell.TH.Syntax as TH newtype Key = Key { unKey :: Text } deriving (Eq, Ord, Typeable, Data) fromString :: String -> Key fromString = Key . T.pack toString :: Key -> String toString (Key k) = T.unpack k fromText :: Text -> Key fromText = Key toText :: Key -> Text toText = unKey -- | @'coercing r1 r2'@ will evaluate to @r1@ if 'Key' is 'Coercible' to 'Text', -- and to @r2@ otherwise. -- -- Using 'coercing' we can make more efficient implementations -- when 'Key' is backed up by 'Text' without exposing internals. -- coercionToText :: Maybe (Coercion Key Text) coercionToText = Just Coercion {-# INLINE coercionToText #-} -- | @since 2.0.2.0 toShortText :: Key -> ST.ShortText toShortText = ST.fromText . unKey -- | @since 2.0.2.0 fromShortText :: ST.ShortText -> Key fromShortText = Key . ST.toText ------------------------------------------------------------------------------- -- instances ------------------------------------------------------------------------------- instance Read Key where readPrec = fromString <$> readPrec instance Show Key where showsPrec d (Key k) = showsPrec d k instance Data.String.IsString Key where fromString = fromString instance Hashable Key where hashWithSalt salt (Key k) = hashWithSalt salt k instance NFData Key where rnf (Key k) = rnf k instance Semigroup Key where Key x <> Key y = Key (x <> y) instance Monoid Key where mempty = Key mempty mappend = (<>) instance TH.Lift Key where #if MIN_VERSION_text(1,2,4) lift (Key k) = [| Key k |] #else lift k = [| fromString k' |] where k' = toString k #endif #if MIN_VERSION_template_haskell(2,17,0) liftTyped = TH.unsafeCodeCoerce . TH.lift #elif MIN_VERSION_template_haskell(2,16,0) liftTyped = TH.unsafeTExpCoerce . TH.lift #endif
dmjio/aeson
src/Data/Aeson/Key.hs
bsd-3-clause
2,601
0
8
454
643
383
260
-1
-1
{-| Module : Network.Kademlia.Protocol.Parsing Description : Implementation of the protocol parsing Network.Kademlia.Protocol.Parsing implements the actual protocol parsing. It made sense to split it off Network.Kademlia.Protocol as it made both cleaner and more readable. -} module Network.Kademlia.Protocol.Parsing where import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as C import Control.Monad (liftM, liftM2) import Control.Monad.Trans (lift) import Control.Monad.State import Control.Monad.Trans.Except import Text.Read (readMaybe) import Data.Word (Word8, Word16) import Data.Bits (shiftL) import Network.Kademlia.Types type Parse = ExceptT String (State B.ByteString) -- | Parse a signal from a ByteString -- -- (This needs to be supplied a Peer, to be able to create a complete Signal) parse :: (Serialize i, Serialize a) => Peer -> B.ByteString -> Either String (Signal i a) parse peer = evalState (runExceptT $ parseSignal peer) -- | Parses the parsable parts of a signal parseSignal :: (Serialize i, Serialize a) => Peer -> Parse (Signal i a) parseSignal peer = do cId <- parseCommandId id <- parseSerialize cmd <- parseCommand cId let node = Node peer id return $ Signal node cmd -- | Parses a Serialize parseSerialize :: (Serialize a) => Parse a parseSerialize = do bs <- lift get case fromBS bs of Left err -> throwE err Right (id, rest) -> do lift . put $ rest return id -- | Parses a CommandId parseCommandId :: Parse Int parseCommandId = do bs <- lift get case B.uncons bs of Nothing -> throwE "uncons returned Nothing" Just (id, rest) -> do lift . put $ rest return $ fromIntegral id -- | Splits after a certain character parseSplit :: Char -> Parse B.ByteString parseSplit c = do bs <- lift get if B.null bs then throwE "ByteString empty" else do let (result, rest) = C.span (/=c) bs lift . put $ rest return result -- | Skips one character skipCharacter :: Parse () skipCharacter = do bs <- lift get if B.null bs then throwE "ByteString empty" else lift . put $ B.drop 1 bs -- | Parses an Int parseInt :: Parse Int parseInt = do bs <- lift get case C.readInt bs of Nothing -> throwE "Failed to parse an Int" Just (n, rest) -> do lift . put $ rest return n -- | Parses two Word8s from a ByteString into one Word16 parseWord16 :: Parse Word16 parseWord16 = do bs <- lift get if B.length bs < 2 then throwE "ByteString to short" else do let (words, rest) = B.splitAt 2 bs lift . put $ rest return . joinWords . B.unpack $ words where joinWords [a, b] = (toWord16 a `shiftL` 8) + toWord16 b toWord16 :: Word8 -> Word16 toWord16 = fromIntegral -- | Parses a Node's info parseNode :: (Serialize i) => Parse (Node i) parseNode = do id <- parseSerialize host <- parseSplit ' ' skipCharacter port <- parseWord16 let peer = Peer (C.unpack host) (fromIntegral port) return $ Node peer id -- | Parses a trailing k-bucket parseKBucket :: (Serialize i) => Parse [Node i] parseKBucket = liftM2 (:) parseNode parseKBucket `catchE` \_ -> return [] -- | Parses the rest of a command corresponding to an id parseCommand :: (Serialize i, Serialize a) => Int -> Parse (Command i a) parseCommand 0 = return PING parseCommand 1 = return PONG parseCommand 2 = liftM2 STORE parseSerialize parseSerialize parseCommand 3 = FIND_NODE `liftM` parseSerialize parseCommand 4 = liftM2 RETURN_NODES parseSerialize parseKBucket parseCommand 5 = FIND_VALUE `liftM` parseSerialize parseCommand 6 = liftM2 RETURN_VALUE parseSerialize parseSerialize parseCommand _ = throwE "Invalid id"
froozen/kademlia
src/Network/Kademlia/Protocol/Parsing.hs
bsd-3-clause
3,912
0
14
996
1,122
567
555
92
2
module Insomnia.Typecheck ( Insomnia.Typecheck.Env.runTC , Insomnia.Typecheck.Toplevel.checkToplevel ) where import Insomnia.Typecheck.Env import Insomnia.Typecheck.Toplevel
lambdageek/insomnia
src/Insomnia/Typecheck.hs
bsd-3-clause
227
0
5
65
34
23
11
4
0
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.Url.Tests ( tests ) where import Data.String import Prelude import Test.Tasty import Test.Tasty.HUnit import Duckling.Dimensions.Types import Duckling.Testing.Asserts import Duckling.Testing.Types import Duckling.Url.Corpus import Duckling.Url.Types tests :: TestTree tests = testGroup "Url Tests" [ makeCorpusTest [Seal Url] corpus , makeNegativeCorpusTest [Seal Url] negativeCorpus , surroundTests ] surroundTests :: TestTree surroundTests = testCase "Surround Tests" $ mapM_ (analyzedFirstTest testContext testOptions . withTargets [Seal Url]) xs where xs = examples (UrlData "www.lets-try-this-one.co.uk/episode-7" "lets-try-this-one.co.uk") [ "phishing link: www.lets-try-this-one.co.uk/episode-7 If you want my job" ]
facebookincubator/duckling
tests/Duckling/Url/Tests.hs
bsd-3-clause
1,044
0
11
183
179
103
76
22
1
module TupleSort where gt :: (a -> a -> Ordering) -> a -> a -> Bool gt cmp a b = a `cmp` b == GT lt :: (a -> a -> Ordering) -> a -> a -> Bool lt cmp a b = a `cmp` b == LT gte :: (a -> a -> Ordering) -> a -> a -> Bool gte cmp a b = c == GT || c == EQ where c = cmp a b tuple5SortBy :: (a -> a -> Ordering) -> (a,a,a,a,a) -> (a,a,a,a,a) tuple5SortBy cmp = step4 . step3 . step2 . step1 where step1 (a,b,c,d,e) | gt cmp a b = (b,a,c,d,e) | otherwise = (a,b,c,d,e) step2 (a,b,c,d,e) | gt cmp c d = (a,b,d,c,e) | otherwise = (a,b,c,d,e) step3 (a,b,c,d,e) | gt cmp b d = (c,d,a,b,e) | otherwise = (a,b,c,d,e) step4 (a,b,c,d,e) | gte cmp e b = step5 (a,b,c,d,e) -- e >= b | otherwise = step6 (a,b,c,d,e) -- e < b step5 (a,b,c,d,e) | lt cmp e d = step7 (a,b,c,d,e) -- e < d | otherwise = step8 (a,b,c,d,e) -- e >= d step6 (a,b,c,d,e) | lt cmp e a = step12 (a,b,c,d,e) | otherwise = step13 (a,b,c,d,e) step7 (a,b,c,d,e) | gte cmp c b = step9 (a,b,c,d,e) -- complete | otherwise = step10 (a,b,c,d,e) -- complete step8 (a,b,c,d,e) | gte cmp c b = (a,b,c,d,e) -- complete | otherwise = step11 (a,b,c,d,e) -- complete step9 (a,b,c,d,e) | lt cmp c e = (a,b,c,e,d) -- complete | otherwise = (a,b,e,c,d) -- complete step10 (a,b,c,d,e) | lt cmp c a = (c,a,b,e,d) -- complete | otherwise = (a,c,b,e,d) -- complete step11 (a,b,c,d,e) | lt cmp c a = (c,a,b,d,e) -- Complete | otherwise = (a,c,b,d,e) -- Complete step12 (a,b,c,d,e) | gte cmp c a = step14 (a,b,c,d,e) -- complete | otherwise = step15 (a,b,c,d,e) -- complete step13 (a,b,c,d,e) | gte cmp c e = step16 (a,b,c,d,e) | otherwise = step17 (a,b,c,d,e) step14 (a,b,c,d,e) | lt cmp c b = (e,a,c,b,d) -- complete | otherwise = (e,a,b,c,d) -- complete step15 (a,b,c,d,e) | lt cmp c e = (c,e,a,b,d) -- complete | otherwise = (e,c,a,b,d) -- complete step16 (a,b,c,d,e) | lt cmp c b = (a,e,c,b,d) | otherwise = (a,e,b,c,d) step17 (a,b,c,d,e) | lt cmp c a = (c,a,e,b,d) | otherwise = (a,c,e,b,d)
fffej/HS-Poker
TupleSort.hs
bsd-3-clause
3,085
0
10
1,543
1,578
898
680
44
1
---------------------------------------------------------------------------- -- | -- Module : ModuleWithImportsThatHaveModuleReexports -- Copyright : (c) Sergey Vinokurov 2015 -- License : BSD3-style (see LICENSE) -- Maintainer : serg.foo@gmail.com ---------------------------------------------------------------------------- module ModuleWithImportsThatHaveModuleReexports where import ModuleWithModuleReexport import ModuleWithModuleReexportViaAlias -- this brings in no new names because that's what GHC does import ModuleWithQualifiedModuleReexport
sergv/tags-server
test-data/0008module_reexport/ModuleWithImportsThatHaveModuleReexports.hs
bsd-3-clause
572
0
3
65
21
17
4
4
0
module Main where import Control.Concurrent import Control.Monad import Network.Curl.Download import System.Exit import System.Process import System.Environment (getArgs) main :: IO () main = do args <- getArgs foreverPing (args !! 0) foreverPing :: String -> IO () foreverPing address = forever $ do ping address >>= notify address threadDelay (10*1000000) ping :: String -> IO (Either String String) ping = openURIString notify :: String -> (Either String String) -> IO () notify address (Right _) = system (notifyCmd address) >> exitWith ExitSuccess notify _ _ = return () notifyCmd addr = "growlnotify -s -m '"++addr++" is now online.' `date \"+%Y-%m-%d %H:%M:%S\"`"
ptek/isupyet
src/IsUpYet.hs
bsd-3-clause
698
0
10
127
241
122
119
21
1
{-# LANGUAGE PatternSynonyms #-} {-# OPTIONS_GHC -Wwarn #-} module Main where import Prelude hiding (pi, abs) import Control.Monad.Trans.Class import Control.Monad.State --import Data.Sequence (Seq, (|>)) --import qualified Data.Sequence as Seq import Data.Set (Set) --import qualified Data.Set as Set --import Data.Map (Map) --import qualified Data.Map as Map import System.IO import Text.PrettyPrint.ANSI.Leijen hiding ((<$>)) import Lang.LF import Lang.LF.ChangeT import Lang.LF.Tree hiding (M) import qualified Lang.LF.Tree as Tree --import qualified Debug.Trace as Debug type LF = Tree.LFTree String String type Sig = Tree.Signature String String type M = Tree.M String String type H = Hyps LF sig :: Sig sig = buildSignature [ -- STLC type formers "tp" ::. lf_type , "arrow" :. tp ==> tp ==> tp , "nat" :. tp , "unit" :. tp -- STLC term formers , "tm" ::. tp ==> lf_type , "zero" :. tm nat , "suc" :. tm nat ==> tm nat , "app" :. pi "a" tp $ \a -> pi "b" tp $ \b -> tm (arrow (var a) (var b)) ==> tm (var a) ==> tm (var b) , "lam" :. pi "a" tp $ \a -> pi "b" tp $ \b -> (tm (var a) ==> tm (var b)) ==> tm (arrow (var a) (var b)) , "nat_elim" :. pi "a" tp $ \a -> tm (var a) ==> tm (arrow (var a) (var a)) ==> tm nat ==> tm (var a) , "tt" :. tm unit -- STLC value judgements , "is_value" ::. pi "a" tp $ \a -> tm (var a) ==> lf_type , "value_tt" :. is_value unit tt , "value_zero" :. is_value nat zero , "value_suc" :. pi "n" (tm nat) $ \n -> is_value nat (var n) ==> is_value nat (suc (var n)) , "value_lam" :. pi "a" tp $ \a -> pi "b" tp $ \b -> pi "f" (tm (var a) ==> tm (var b)) $ \f -> is_value (arrow (var a) (var b)) (lam (var a) (var b) "x" (\x -> var f @@ var x)) -- STLC small-step CBV semantics , "step" ::. pi "a" tp $ \a -> tm (var a) ==> tm (var a) ==> lf_type , "step_app1" :. pi "a" tp $ \a -> pi "b" tp $ \b -> pi "e₁" (tm (arrow (var a) (var b))) $ \e1 -> pi "e₂" (tm (var a)) $ \e2 -> pi "e₁'" (tm (arrow (var a) (var b))) $ \e1' -> step (arrow (var a) (var b)) (var e1) (var e1') ==> step (var b) (app (var a) (var b) (var e1) (var e2)) (app (var a) (var b) (var e1') (var e2)) , "step_app2" :. pi "a" tp $ \a -> pi "b" tp $ \b -> pi "e₁" (tm (arrow (var a) (var b))) $ \e1 -> pi "e₂" (tm (var a)) $ \e2 -> pi "e₂'" (tm (var a)) $ \e2' -> is_value (arrow (var a) (var b)) (var e1) ==> step (var a) (var e2) (var e2') ==> step (var b) (app (var a) (var b) (var e1) (var e2)) (app (var a) (var b) (var e1) (var e2')) , "step_beta" :. pi "a" tp $ \a -> pi "b" tp $ \b -> pi "e₂" (tm (var a)) $ \e2 -> pi "f" (tm (var a) ==> tm (var b)) $ \f -> is_value (var a) (var e2) ==> step (var b) (app (var a) (var b) (lam (var a) (var b) "x" (\x -> var f @@ var x)) (var e2)) (var f @@ var e2) , "step_nat_zero" :. pi "a" tp $ \a -> pi "z" (tm (var a)) $ \z -> pi "s" (tm (arrow (var a) (var a))) $ \s -> step (var a) (nat_elim (var a) (var z) (var s) zero) (var z) , "step_nat_succ" :. pi "a" tp $ \a -> pi "z" (tm (var a)) $ \z -> pi "s" (tm (arrow (var a) (var a))) $ \s -> pi "n" (tm nat) $ \n -> step (var a) (nat_elim (var a) (var z) (var s) (suc (var n))) (app (var a) (var a) (var s) (nat_elim (var a) (var z) (var s) (var n))) , "F" :. tm (arrow unit unit) ] tp :: LiftClosed γ => M (LF γ TYPE) tp = tyConst "tp" unit :: LiftClosed γ => M (LF γ TERM) unit = tmConst "unit" nat :: LiftClosed γ => M (LF γ TERM) nat = tmConst "nat" arrow :: LiftClosed γ => M (LF γ TERM) -> M (LF γ TERM) -> M (LF γ TERM) arrow x y = tmConst "arrow" @@ x @@ y tm :: LiftClosed γ => M (LF γ TERM) -> M (LF γ TYPE) tm a = tyConst "tm" @@ a tt :: LiftClosed γ => M (LF γ TERM) tt = tmConst "tt" zero :: LiftClosed γ => M (LF γ TERM) zero = tmConst "zero" suc :: LiftClosed γ => M (LF γ TERM) -> M (LF γ TERM) suc x = tmConst "suc" @@ x infixl 5 `app` app :: LiftClosed γ => M (LF γ TERM) -> M (LF γ TERM) -> M (LF γ TERM) -> M (LF γ TERM) -> M (LF γ TERM) app a b x y = tmConst "app" @@ a @@ b @@ x @@ y lam :: ( LiftClosed γ , ?nms :: Set String , ?hyps :: Hyps LF γ ) => M (LF γ TERM) -> M (LF γ TERM) -> String -> (forall b. ( ?nms :: Set String , ?hyps :: Hyps LF (γ::>b) ) => Var (γ::>b) -> M (LF (γ::>b) TERM)) -> M (LF γ TERM) lam a b nm f = tmConst "lam" @@ a @@ b @@ (λ nm (tm a) f) nat_elim :: LiftClosed γ => M (LF γ TERM) -> M (LF γ TERM) -> M (LF γ TERM) -> M (LF γ TERM) -> M (LF γ TERM) nat_elim a z s n = tmConst "nat_elim" @@ a @@ z @@ s @@ n typeof :: LiftClosed γ => M (LF γ TERM) -> M (LF γ TERM) -> M (LF γ TERM) -> M (LF γ TYPE) typeof a t p = tyConst "typeof" @@ a @@ t @@ p is_value :: LiftClosed γ => M (LF γ TERM) -> M (LF γ TERM) -> M (LF γ TYPE) is_value a v = tyConst "is_value" @@ a @@ v step :: LiftClosed γ => M (LF γ TERM) -> M (LF γ TERM) -> M (LF γ TERM) -> M (LF γ TYPE) step a x x' = tyConst "step" @@ a @@ x @@ x' pattern VarP v <- (termView -> VVar v []) pattern AppP a b m1 m2 <- (termView -> VConst "app" [a, b, m1, m2]) pattern LamP a b m <- (termView -> VConst "lam" [a, b, m]) pattern NatElimP a z s n <- (termView -> VConst "nat_elim" [a,z,s,n]) pattern ZeroP <- (termView -> VConst "zero" []) pattern SucP n <- (termView -> VConst "suc" [n]) pattern ArrowP t1 t2 <- (termView -> VConst "arrow" [t1,t2]) addConstraint :: M (LF E CON) -> StateT [LF E CON] M () addConstraint c = do x <- lift c modify (x:) {- cps_type :: ( LiftClosed γ, ?soln :: LFSoln LF , ?nms :: Set String, ?hyps :: H γ ) => LF E TERM -> LF γ TERM -> M (LF γ TERM) cps_type ans_ty (ArrowP t1 t2) = do t1' <- cps_type ans_ty t1 t2' <- cps_type ans_ty t2 arrow (return t1') (arrow (arrow (return t2') (return (liftClosed ans_ty))) (return (liftClosed ans_ty))) cps_type _ x = return x -- Given a term compute a CPS conversion of it. cps, docps :: ( LiftClosed γ, ?soln :: LFSoln LF , ?nms :: Set String, ?hyps :: H γ ) => LF E TERM -> LF γ TERM -> LF γ TERM -> M (LF γ TERM) cps ans_ty ty m = do x <- docps ans_ty ty m str_m <- displayLF m str <- displayLF x Debug.trace (unlines ["Before:",str_m,"After:",str]) $ do _ <- inferType x return x docps ans_ty ty (LamP a b body) = do ty' <- cps_type ans_ty ty k_arg <- tm (return ty') ==> tm (return $ liftClosed ans_ty) λ "k" (return k_arg) $ \k0 -> var k0 @@ (extendCtx "k" QLam k_arg $ (lam (return $ weaken a) (arrow (arrow (return $ weaken b) (return $ liftClosed $ ans_ty)) (return $ liftClosed $ ans_ty)) "x" $ \x -> do x_arg <- tm (return $ weaken a) extendCtx "x" QLam x_arg $ lam (arrow (return $ weaken $ weaken $ b) (return $ liftClosed $ ans_ty)) (return $ liftClosed $ ans_ty) "k" $ \k -> do k_arg <- tm (arrow (return $ weaken $ weaken $ b) (return $ liftClosed $ ans_ty)) extendCtx "k" QLam k_arg $ (cps ans_ty (weaken $ weaken $ weaken b) =<< ((return $ weaken $ weaken $ weaken body) @@ (weaken <$> var x))) @@ (λ "m" (tm (return $ weaken $ weaken $ weaken b)) $ \m -> app (return $ weaken $ weaken $ weaken $ weaken b) (return $ liftClosed $ ans_ty) (weaken <$> var k) (var m)))) docps ans_ty _ (AppP a b x y) = do a' <- cps_type ans_ty a b' <- cps_type ans_ty b k_arg <- (tm (return b) ==> tm (return $ liftClosed ans_ty)) λ "k" (return k_arg) $ \k -> extendCtx "k" QLam k_arg $ do arr <- arrow (return $ weaken a) (return $ weaken b) (cps ans_ty arr (weaken x)) @@ (do arr' <- cps_type ans_ty arr m_arg <- tm (return arr') λ "m" (return m_arg) $ \m -> extendCtx "m" QLam m_arg $ (cps ans_ty (weaken $ weaken a) (weaken $ weaken y)) @@ (do n_arg <- tm (return $ weaken $ weaken a) λ "n" (return n_arg) $ \n -> extendCtx "n" QLam n_arg $ app (arrow (return $ weaken $ weaken $ weaken b') (return $ liftClosed ans_ty)) (return $ liftClosed ans_ty) (app (return $ weaken $ weaken $ weaken a') (arrow (arrow (return $ weaken $ weaken $ weaken b') (return $ liftClosed ans_ty)) (return $ liftClosed ans_ty)) (weaken <$> var m) (var n)) (lam (return $ weaken $ weaken $ weaken b') (return $ liftClosed ans_ty) "q" $ \q -> (weaken <$> weaken <$> weaken <$> var k) @@ var q))) docps ans_ty n_ty (SucP n) = λ "k" (tm nat ==> tm (return $ liftClosed ans_ty)) $ \k -> do t <- tm nat extendCtx "k" QLam t $ (cps ans_ty (weaken n_ty) (weaken n)) @@ (λ "q" (tm nat) $ \q -> (weaken <$> var k) @@ (suc (var q))) docps ans_ty ty x = λ "k" (tm (return $ ty) ==> tm (return $ liftClosed ans_ty)) $ \k -> var k @@ return (weaken x) -} -- CBV reduction to head-normal form eval :: (?nms :: Set String, ?hyps :: H γ, LiftClosed γ, ?soln :: LFSoln LF) => LF γ TERM -> ChangeT M (LF γ TERM) -- β reduction eval (AppP _ _ (LamP _ _ body) arg) = do arg' <- eval arg eval =<< Changed (return body @@ return arg') -- structural evaluation under application eval tm@(AppP a b m1 m2) = do case eval m1 of Unchanged _ -> case eval m2 of Unchanged _ -> Unchanged tm Changed m2' -> eval =<< Changed (app (return a) (return b) (return m1) m2') Changed m1' -> eval =<< Changed (app (return a) (return b) m1' (return m2)) -- evaluation under lambdas eval tm@(LamP a b (termView -> VLam nm var tp body)) = do case eval body of Changed body' -> do Changed (tmConst "lam" @@ return a @@ return b @@ (mkLam nm var tp =<< body')) _ -> Unchanged tm -- nat recursor: zero case eval (NatElimP _a z _s ZeroP) = Changed (return z) -- nat recursor: successor case eval (NatElimP a z s (SucP n)) = eval =<< Changed (app (return a) (return a) (return s) (nat_elim (return a) (return z) (return s) (return n))) eval t = Unchanged t five :: M (LF E TERM) five = suc $ suc $ suc $ suc $ suc $ zero three :: M (LF E TERM) three = suc $ suc $ suc $ zero add :: M (LF E TERM) add = inEmptyCtx $ lam nat (arrow nat nat) "x" $ \x -> lam nat nat "y" $ \y -> nat_elim nat (var x) (lam nat nat "n" $ \n -> suc (var n)) (var y) composeN :: M (LF E TERM) -> M (LF E TERM) composeN a = inEmptyCtx $ do lam (arrow a a) (arrow nat (arrow a a)) "f" $ \f -> lam nat (autoweaken <$> (arrow a a)) "n" $ \n -> nat_elim (autoweaken <$> (arrow a a)) (lam (autoweaken <$> a) (autoweaken <$> a) "q" $ \q -> var q) (lam (autoweaken <$> (arrow a a)) (autoweaken <$> (arrow a a)) "g" $ \g -> lam (autoweaken <$> a) (autoweaken <$> a) "q" $ \q -> app (autoweaken <$> a) (autoweaken <$> a) (var f) (app (autoweaken <$> a) (autoweaken <$> a) (var g) (var q))) (var n) testTerm :: LF E TERM testTerm = mkTerm sig $ app nat nat (app nat (arrow nat nat) add three) five -- mkTerm sig $ -- app unit unit -- (app nat (arrow unit unit) -- (app (arrow unit unit) (arrow nat (arrow unit unit)) -- (composeN unit) -- (lam unit unit "q" $ \q -> app unit unit (tmConst "F") (var q))) -- three) -- tt evalTerm :: LF E TERM evalTerm = inEmptyCtx $ mkTerm sig $ runChangeT $ eval testTerm {- cpsTerm :: LF E TERM cpsTerm = inEmptyCtx $ mkTerm sig $ do u <- unit t <- nat x <- (cps u t testTerm) @@ (λ "q" (tm nat) $ \_q -> tt) str <- displayLF x Debug.trace (unlines ["Final:", str]) $ return x -} main = inEmptyCtx $ do let x :: LF E TERM x = evalTerm displayIO stdout $ renderSmart 0.7 80 $ runM sig $ ppLF TopPrec WeakRefl x putStrLn "" displayIO stdout $ renderSmart 0.7 80 $ runM sig $ (ppLF TopPrec WeakRefl =<< inferType WeakRefl x) putStrLn ""
robdockins/canonical-lf
Main.hs
bsd-3-clause
12,997
0
24
4,343
4,530
2,266
2,264
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Database.Persist.TH.MigrationOnlySpec where import TemplateTestImports import Data.Text (Text) import Database.Persist.ImplicitIdDef import Database.Persist.ImplicitIdDef.Internal (fieldTypeFromTypeable) import Database.Persist.Types mkPersist sqlSettings [persistLowerCase| HasMigrationOnly name String blargh Int MigrationOnly deriving Eq Show |] pass :: IO () pass = pure () asIO :: IO a -> IO a asIO = id spec :: Spec spec = describe "MigrationOnlySpec" $ do describe "HasMigrationOnly" $ do let edef = entityDef $ Proxy @HasMigrationOnly describe "getEntityFields" $ do it "has one field" $ do length (getEntityFields edef) `shouldBe` 1 describe "getEntityFieldsDatabase" $ do it "has two fields" $ do length (getEntityFieldsDatabase edef) `shouldBe` 2 describe "toPersistFields" $ do it "should have one field" $ do map toPersistValue (toPersistFields (HasMigrationOnly "asdf")) `shouldBe` map toPersistValue [SomePersistField ("asdf" :: Text)] describe "fromPersistValues" $ do it "should work with only item in list" $ do fromPersistValues [PersistText "Hello"] `shouldBe` Right (HasMigrationOnly "Hello")
yesodweb/persistent
persistent/test/Database/Persist/TH/MigrationOnlySpec.hs
mit
1,916
0
22
528
341
176
165
48
1
{- | Module : ./TPTP/Prover/Vampire/ProofParser.hs Description : Parses a Vampire proof. Copyright : (c) Eugen Kuksa University of Magdeburg 2017 License : GPLv2 or higher, see LICENSE.txt Maintainer : Eugen Kuksa <kuksa@iks.cs.ovgu.de> Stability : provisional Portability : non-portable (imports Logic) -} module TPTP.Prover.Vampire.ProofParser ( parseStatus , parseTimeUsed , filterProofLines ) where import Common.Utils import Data.Char import Data.List hiding (lines) import Data.Maybe import Data.Time (TimeOfDay (..), midnight) import Prelude hiding (lines) parseStatus :: [String] -> String parseStatus = fromMaybe "Unknown" . foldr parseStatusIfStatusline Nothing where parseStatusIfStatusline :: String -> Maybe String -> Maybe String parseStatusIfStatusline line mStatus = case mStatus of Nothing -> case () of _ | isPrefixOf "Termination reason: Time limit" line -> Just "Timeout" _ | isPrefixOf "Termination reason: Memory limit" line -> Just "MemoryOut" _ | isPrefixOf "Termination reason: Refutation not found" line -> Just "GaveUp" _ | isPrefixOf "Termination reason: Refutation" line -> Just "Theorem" _ | isPrefixOf "Termination reason: Satisfiable" line -> Just "CounterSatisfiable" -- this is a model _ | isPrefixOf "Termination reason: Unknown" line -> Just "Unknown" _ -> mStatus _ -> mStatus parseTimeUsed :: [String] -> TimeOfDay parseTimeUsed = fromMaybe midnight . foldr parseTimeUsedIfTimeLine Nothing where parseTimeUsedIfTimeLine :: String -> Maybe TimeOfDay -> Maybe TimeOfDay parseTimeUsedIfTimeLine line mTime = case mTime of Just _ -> mTime Nothing -> case stripPrefix "Time elapsed: " line of Just s -> Just $ parseTimeOfDay $ takeWhile (\ c -> isDigit c || c == '.') $ trimLeft s Nothing -> mTime parseTimeOfDay :: String -> TimeOfDay parseTimeOfDay s = TimeOfDay { todHour = 0 , todMin = 0 , todSec = realToFrac (read s :: Double) } data FilterState = Version | Separator | Proof deriving Show -- filters the lines of the proof -- The first line does not belong to the proof. The next lines before the -- "------------------------------" belong to the proof. -- Right after that separator, the version indicator appears. filterProofLines :: [String] -> [String] filterProofLines lines = fst $ foldr addIfInProof ([], Version) $ tail lines where addIfInProof :: String -> ([String], FilterState) -> ([String], FilterState) addIfInProof line (addedLines, state) = -- @state@ tells if the line is between "SZS output start/end". -- Since the lines are in reverse order (by foldr), we need to parse after -- the separator ("------------------------------"). case state of Version -> if isPrefixOf "Version: " line then (addedLines, Separator) else (addedLines, state) Separator -> if isPrefixOf "------------------------------" line then (addedLines, Proof) else (addedLines, state) Proof -> (line : addedLines, state)
spechub/Hets
TPTP/Prover/Vampire/ProofParser.hs
gpl-2.0
3,273
0
20
838
671
354
317
51
8
import Data.List import Data.Char import Data.String.Utils readNamesFromFile :: String -> IO [String] readNamesFromFile fileName = do fileContent <- readFile fileName return (listOfNames fileContent) where listOfNames :: String -> [String] listOfNames fileContent = split "," $ replace "\"" "" fileContent findNamesScores :: [String] -> [Int] findNamesScores namesList = map nameScore $ zip (sort namesList) [1..] where nameScore (name, index) = (alphabeticalScore name) * index alphabeticalScore :: String -> Int alphabeticalScore name = sum $ map letterIndex name where letterIndex char = ord char - letterAindex + 1 letterAindex = ord 'A' main = do namesList <- readNamesFromFile "names.txt" let nameScores = findNamesScores namesList return (sum nameScores)
nothiphop/project-euler
022/solution.hs
apache-2.0
802
3
10
145
294
134
160
20
1
-- (c) 2000 - 2005 by Martin Erwig [see file COPYRIGHT] -- | Depth-First Search module Data.Graph.Inductive.Query.DFS( CFun, dfs,dfs',dff,dff', dfsWith, dfsWith',dffWith,dffWith', -- * Undirected DFS udfs,udfs',udff,udff', -- * Reverse DFS rdff,rdff',rdfs,rdfs', -- * Applications of DFS\/DFF topsort,topsort',scc,reachable, -- * Applications of UDFS\/UDFF components,noComponents,isConnected ) where import Data.Tree import Data.Graph.Inductive.Graph import Data.Graph.Inductive.Basic ---------------------------------------------------------------------- -- DFS AND FRIENDS ---------------------------------------------------------------------- {- Classification of all 32 dfs functions: dfs-function ::= [direction]"df"structure["With"]["'"] direction --> "x" | "u" | "r" structure --> "s" | "f" | structure direction | "s" "f" ------------------------ + optional With + optional ' "x" | xdfs xdff " " | dfs dff "u" | udfs udff "r" | rdfs rdff ------------------------ Direction Parameter ------------------- x : parameterized by a function that specifies which nodes to be visited next " ": the "normal case: just follow successors u : undirected, ie, follow predecesors and successors r : reverse, ie, follow predecesors Structure Parameter ------------------- s : result is a list of (a) objects computed from visited contexts ("With"-version) (b) nodes (normal version) f : result is a tree/forest of (a) objects computed from visited contexts ("With"-version) (b) nodes (normal version) Optional Suffixes ----------------- With : objects to be put into list/tree are given by a function on contexts, default for non-"With" versions: nodes ' : parameter node list is given implicitly by the nodes of the graph to be traversed, default for non-"'" versions: nodes must be provided explicitly Defined are only the following 18 most important function versions: xdfsWith dfsWith,dfsWith',dfs,dfs' udfs,udfs' rdfs,rdfs' xdffWith dffWith,dffWith',dff,dff' udff,udff' rdff,rdff' Others can be added quite easily if needed. -} -- fixNodes fixes the nodes of the graph as a parameter -- fixNodes :: Graph gr => ([Node] -> gr a b -> c) -> gr a b -> c fixNodes f g = f (nodes g) g -- generalized depth-first search -- (could also be simply defined as applying preorderF to the -- result of xdffWith) -- type CFun a b c = Context a b -> c xdfsWith :: Graph gr => CFun a b [Node] -> CFun a b c -> [Node] -> gr a b -> [c] xdfsWith _ _ [] _ = [] xdfsWith _ _ _ g | isEmpty g = [] xdfsWith d f (v:vs) g = case match v g of (Just c,g') -> f c:xdfsWith d f (d c++vs) g' (Nothing,g') -> xdfsWith d f vs g' -- dfs -- dfsWith :: Graph gr => CFun a b c -> [Node] -> gr a b -> [c] dfsWith = xdfsWith suc' dfsWith' :: Graph gr => CFun a b c -> gr a b -> [c] dfsWith' f = fixNodes (dfsWith f) dfs :: Graph gr => [Node] -> gr a b -> [Node] dfs = dfsWith node' dfs' :: Graph gr => gr a b -> [Node] dfs' = dfsWith' node' -- undirected dfs, ie, ignore edge directions -- udfs :: Graph gr => [Node] -> gr a b -> [Node] udfs = xdfsWith neighbors' node' udfs' :: Graph gr => gr a b -> [Node] udfs' = fixNodes udfs -- reverse dfs, ie, follow predecessors -- rdfs :: Graph gr => [Node] -> gr a b -> [Node] rdfs = xdfsWith pre' node' rdfs' :: Graph gr => gr a b -> [Node] rdfs' = fixNodes rdfs -- generalized depth-first forest -- xdfWith :: Graph gr => CFun a b [Node] -> CFun a b c -> [Node] -> gr a b -> ([Tree c],gr a b) xdfWith _ _ [] g = ([],g) xdfWith _ _ _ g | isEmpty g = ([],g) xdfWith d f (v:vs) g = case match v g of (Nothing,g1) -> xdfWith d f vs g1 (Just c,g1) -> (Node (f c) ts:ts',g3) where (ts,g2) = xdfWith d f (d c) g1 (ts',g3) = xdfWith d f vs g2 xdffWith :: Graph gr => CFun a b [Node] -> CFun a b c -> [Node] -> gr a b -> [Tree c] xdffWith d f vs g = fst (xdfWith d f vs g) -- dff -- dffWith :: Graph gr => CFun a b c -> [Node] -> gr a b -> [Tree c] dffWith = xdffWith suc' dffWith' :: Graph gr => CFun a b c -> gr a b -> [Tree c] dffWith' f = fixNodes (dffWith f) dff :: Graph gr => [Node] -> gr a b -> [Tree Node] dff = dffWith node' dff' :: Graph gr => gr a b -> [Tree Node] dff' = dffWith' node' -- undirected dff -- udff :: Graph gr => [Node] -> gr a b -> [Tree Node] udff = xdffWith neighbors' node' udff' :: Graph gr => gr a b -> [Tree Node] udff' = fixNodes udff -- reverse dff, ie, following predecessors -- rdff :: Graph gr => [Node] -> gr a b -> [Tree Node] rdff = xdffWith pre' node' rdff' :: Graph gr => gr a b -> [Tree Node] rdff' = fixNodes rdff ---------------------------------------------------------------------- -- ALGORITHMS BASED ON DFS ---------------------------------------------------------------------- components :: Graph gr => gr a b -> [[Node]] components = (map preorder) . udff' noComponents :: Graph gr => gr a b -> Int noComponents = length . components isConnected :: Graph gr => gr a b -> Bool isConnected = (==1) . noComponents postflatten :: Tree a -> [a] postflatten (Node v ts) = postflattenF ts ++ [v] postflattenF :: [Tree a] -> [a] postflattenF = concatMap postflatten topsort :: Graph gr => gr a b -> [Node] topsort = reverse . postflattenF . dff' topsort' :: Graph gr => gr a b -> [a] topsort' = reverse . postorderF . (dffWith' lab') scc :: Graph gr => gr a b -> [[Node]] scc g = map preorder (rdff (topsort g) g) -- optimized, using rdff -- sccOrig g = map preorder (dff (topsort g) (grev g)) -- original by Sharir reachable :: Graph gr => Node -> gr a b -> [Node] reachable v g = preorderF (dff [v] g)
FranklinChen/hugs98-plus-Sep2006
packages/fgl/Data/Graph/Inductive/Query/DFS.hs
bsd-3-clause
6,129
0
12
1,686
1,782
930
852
80
2
{-# LANGUAGE QuasiQuotes #-} import LiquidHaskell import Language.Haskell.Liquid.Prelude import qualified Data.Map import Data.List (foldl') ---------------------------------------------------------------- --- Step 1: Map each element into key-value list (concatMap) --- ---------------------------------------------------------------- expand :: (a -> [(k,v)]) -> [a] -> [(k, v)] expand f [] = [] expand f (x:xs) = (f x) ++ (expand f xs) ---------------------------------------------------------------- --- Step 2: Group By Key --------------------------------------- ---------------------------------------------------------------- group :: (Ord k) => [(k, v)] -> Data.Map.Map k [v] group = foldl' addKV Data.Map.empty addKV m (k, v) = Data.Map.insert k vs' m where vs' = v : (Data.Map.findWithDefault [] k m) -------------------------------------------------------------------- --- Step 3: Group By Key ------------------------------------------- -------------------------------------------------------------------- collapse f = Data.Map.foldrWithKey reduceKV [] where reduceKV k (v:vs) acc = let b = liquidAssertB False in (k, foldl' f v vs) : acc reduceKV k [] _ = crash False --error $ show (liquidAssertB False) -------------------------------------------------------------------- --- Putting it All Together ---------------------------------------- -------------------------------------------------------------------- mapReduce mapper reducer = collapse reducer . group . expand mapper -------------------------------------------------------------------- --- "Word Count" --------------------------------------------------- -------------------------------------------------------------------- wordCount = mapReduce fm plus where fm = \doc -> [ (w,1) | w <- words doc] main = putStrLn $ show $ wordCount docs where docs = [ "this is the end" , "go to the end" , "the end is the beginning"]
spinda/liquidhaskell
tests/gsoc15/working/pos/mapreduce.hs
bsd-3-clause
2,012
15
10
326
472
238
234
22
2
-- {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, UndecidableInstances #-} -- Compilation loops in GHC 6.2! -- While LoopOfTheDay1.hs did compile and work, -- this one loops during compilation, even though -- there is only an innocent difference regarding T1, -- i.e., an additional, non-recursive constructor component. module ShouldCompile where data T1 = T1a Int | T1b T1 class C0 x where foo :: x -> (); foo = undefined -- foo :: C0 x => x -> () class C1 x y class C1 x y => C2 x y instance C0 Int => C1 () Int -- I1 instance C0 T1 => C1 () T1 -- I2 instance (C1 x T1, C1 x Int) => C2 x T1 -- I3 instance C1 x Int => C2 x Int -- I4 instance C2 () T1 => C0 T1 -- I5 instance C2 () Int => C0 Int -- I6 baz = foo (T1b (T1a 3)) {- Need C0 T1 -->(I5) C2 () T1 -->(I3) C1 () T1, C1 () Int -->(I1,I2) C0 T1, C0 Int -->(recusive) C0 Int -->(I6) C2 () Int -->(I4) C1 () Int -->(recursive) {} -}
rahulmutt/ghcvm
tests/suite/typecheck/compile/LoopOfTheDay2.hs
bsd-3-clause
1,121
0
9
362
224
116
108
-1
-1
module Beer (song) where song :: String song = "99 bottles of beer on the wall, 99 bottles of beer.\n\ \Take one down and pass it around, 98 bottles of beer on the wall.\n\ \\n\ \98 bottles of beer on the wall, 98 bottles of beer.\n\ \Take one down and pass it around, 97 bottles of beer on the wall.\n\ \\n\ \97 bottles of beer on the wall, 97 bottles of beer.\n\ \Take one down and pass it around, 96 bottles of beer on the wall.\n\ \\n\ \96 bottles of beer on the wall, 96 bottles of beer.\n\ \Take one down and pass it around, 95 bottles of beer on the wall.\n\ \\n\ \95 bottles of beer on the wall, 95 bottles of beer.\n\ \Take one down and pass it around, 94 bottles of beer on the wall.\n\ \\n\ \94 bottles of beer on the wall, 94 bottles of beer.\n\ \Take one down and pass it around, 93 bottles of beer on the wall.\n\ \\n\ \93 bottles of beer on the wall, 93 bottles of beer.\n\ \Take one down and pass it around, 92 bottles of beer on the wall.\n\ \\n\ \92 bottles of beer on the wall, 92 bottles of beer.\n\ \Take one down and pass it around, 91 bottles of beer on the wall.\n\ \\n\ \91 bottles of beer on the wall, 91 bottles of beer.\n\ \Take one down and pass it around, 90 bottles of beer on the wall.\n\ \\n\ \90 bottles of beer on the wall, 90 bottles of beer.\n\ \Take one down and pass it around, 89 bottles of beer on the wall.\n\ \\n\ \89 bottles of beer on the wall, 89 bottles of beer.\n\ \Take one down and pass it around, 88 bottles of beer on the wall.\n\ \\n\ \88 bottles of beer on the wall, 88 bottles of beer.\n\ \Take one down and pass it around, 87 bottles of beer on the wall.\n\ \\n\ \87 bottles of beer on the wall, 87 bottles of beer.\n\ \Take one down and pass it around, 86 bottles of beer on the wall.\n\ \\n\ \86 bottles of beer on the wall, 86 bottles of beer.\n\ \Take one down and pass it around, 85 bottles of beer on the wall.\n\ \\n\ \85 bottles of beer on the wall, 85 bottles of beer.\n\ \Take one down and pass it around, 84 bottles of beer on the wall.\n\ \\n\ \84 bottles of beer on the wall, 84 bottles of beer.\n\ \Take one down and pass it around, 83 bottles of beer on the wall.\n\ \\n\ \83 bottles of beer on the wall, 83 bottles of beer.\n\ \Take one down and pass it around, 82 bottles of beer on the wall.\n\ \\n\ \82 bottles of beer on the wall, 82 bottles of beer.\n\ \Take one down and pass it around, 81 bottles of beer on the wall.\n\ \\n\ \81 bottles of beer on the wall, 81 bottles of beer.\n\ \Take one down and pass it around, 80 bottles of beer on the wall.\n\ \\n\ \80 bottles of beer on the wall, 80 bottles of beer.\n\ \Take one down and pass it around, 79 bottles of beer on the wall.\n\ \\n\ \79 bottles of beer on the wall, 79 bottles of beer.\n\ \Take one down and pass it around, 78 bottles of beer on the wall.\n\ \\n\ \78 bottles of beer on the wall, 78 bottles of beer.\n\ \Take one down and pass it around, 77 bottles of beer on the wall.\n\ \\n\ \77 bottles of beer on the wall, 77 bottles of beer.\n\ \Take one down and pass it around, 76 bottles of beer on the wall.\n\ \\n\ \76 bottles of beer on the wall, 76 bottles of beer.\n\ \Take one down and pass it around, 75 bottles of beer on the wall.\n\ \\n\ \75 bottles of beer on the wall, 75 bottles of beer.\n\ \Take one down and pass it around, 74 bottles of beer on the wall.\n\ \\n\ \74 bottles of beer on the wall, 74 bottles of beer.\n\ \Take one down and pass it around, 73 bottles of beer on the wall.\n\ \\n\ \73 bottles of beer on the wall, 73 bottles of beer.\n\ \Take one down and pass it around, 72 bottles of beer on the wall.\n\ \\n\ \72 bottles of beer on the wall, 72 bottles of beer.\n\ \Take one down and pass it around, 71 bottles of beer on the wall.\n\ \\n\ \71 bottles of beer on the wall, 71 bottles of beer.\n\ \Take one down and pass it around, 70 bottles of beer on the wall.\n\ \\n\ \70 bottles of beer on the wall, 70 bottles of beer.\n\ \Take one down and pass it around, 69 bottles of beer on the wall.\n\ \\n\ \69 bottles of beer on the wall, 69 bottles of beer.\n\ \Take one down and pass it around, 68 bottles of beer on the wall.\n\ \\n\ \68 bottles of beer on the wall, 68 bottles of beer.\n\ \Take one down and pass it around, 67 bottles of beer on the wall.\n\ \\n\ \67 bottles of beer on the wall, 67 bottles of beer.\n\ \Take one down and pass it around, 66 bottles of beer on the wall.\n\ \\n\ \66 bottles of beer on the wall, 66 bottles of beer.\n\ \Take one down and pass it around, 65 bottles of beer on the wall.\n\ \\n\ \65 bottles of beer on the wall, 65 bottles of beer.\n\ \Take one down and pass it around, 64 bottles of beer on the wall.\n\ \\n\ \64 bottles of beer on the wall, 64 bottles of beer.\n\ \Take one down and pass it around, 63 bottles of beer on the wall.\n\ \\n\ \63 bottles of beer on the wall, 63 bottles of beer.\n\ \Take one down and pass it around, 62 bottles of beer on the wall.\n\ \\n\ \62 bottles of beer on the wall, 62 bottles of beer.\n\ \Take one down and pass it around, 61 bottles of beer on the wall.\n\ \\n\ \61 bottles of beer on the wall, 61 bottles of beer.\n\ \Take one down and pass it around, 60 bottles of beer on the wall.\n\ \\n\ \60 bottles of beer on the wall, 60 bottles of beer.\n\ \Take one down and pass it around, 59 bottles of beer on the wall.\n\ \\n\ \59 bottles of beer on the wall, 59 bottles of beer.\n\ \Take one down and pass it around, 58 bottles of beer on the wall.\n\ \\n\ \58 bottles of beer on the wall, 58 bottles of beer.\n\ \Take one down and pass it around, 57 bottles of beer on the wall.\n\ \\n\ \57 bottles of beer on the wall, 57 bottles of beer.\n\ \Take one down and pass it around, 56 bottles of beer on the wall.\n\ \\n\ \56 bottles of beer on the wall, 56 bottles of beer.\n\ \Take one down and pass it around, 55 bottles of beer on the wall.\n\ \\n\ \55 bottles of beer on the wall, 55 bottles of beer.\n\ \Take one down and pass it around, 54 bottles of beer on the wall.\n\ \\n\ \54 bottles of beer on the wall, 54 bottles of beer.\n\ \Take one down and pass it around, 53 bottles of beer on the wall.\n\ \\n\ \53 bottles of beer on the wall, 53 bottles of beer.\n\ \Take one down and pass it around, 52 bottles of beer on the wall.\n\ \\n\ \52 bottles of beer on the wall, 52 bottles of beer.\n\ \Take one down and pass it around, 51 bottles of beer on the wall.\n\ \\n\ \51 bottles of beer on the wall, 51 bottles of beer.\n\ \Take one down and pass it around, 50 bottles of beer on the wall.\n\ \\n\ \50 bottles of beer on the wall, 50 bottles of beer.\n\ \Take one down and pass it around, 49 bottles of beer on the wall.\n\ \\n\ \49 bottles of beer on the wall, 49 bottles of beer.\n\ \Take one down and pass it around, 48 bottles of beer on the wall.\n\ \\n\ \48 bottles of beer on the wall, 48 bottles of beer.\n\ \Take one down and pass it around, 47 bottles of beer on the wall.\n\ \\n\ \47 bottles of beer on the wall, 47 bottles of beer.\n\ \Take one down and pass it around, 46 bottles of beer on the wall.\n\ \\n\ \46 bottles of beer on the wall, 46 bottles of beer.\n\ \Take one down and pass it around, 45 bottles of beer on the wall.\n\ \\n\ \45 bottles of beer on the wall, 45 bottles of beer.\n\ \Take one down and pass it around, 44 bottles of beer on the wall.\n\ \\n\ \44 bottles of beer on the wall, 44 bottles of beer.\n\ \Take one down and pass it around, 43 bottles of beer on the wall.\n\ \\n\ \43 bottles of beer on the wall, 43 bottles of beer.\n\ \Take one down and pass it around, 42 bottles of beer on the wall.\n\ \\n\ \42 bottles of beer on the wall, 42 bottles of beer.\n\ \Take one down and pass it around, 41 bottles of beer on the wall.\n\ \\n\ \41 bottles of beer on the wall, 41 bottles of beer.\n\ \Take one down and pass it around, 40 bottles of beer on the wall.\n\ \\n\ \40 bottles of beer on the wall, 40 bottles of beer.\n\ \Take one down and pass it around, 39 bottles of beer on the wall.\n\ \\n\ \39 bottles of beer on the wall, 39 bottles of beer.\n\ \Take one down and pass it around, 38 bottles of beer on the wall.\n\ \\n\ \38 bottles of beer on the wall, 38 bottles of beer.\n\ \Take one down and pass it around, 37 bottles of beer on the wall.\n\ \\n\ \37 bottles of beer on the wall, 37 bottles of beer.\n\ \Take one down and pass it around, 36 bottles of beer on the wall.\n\ \\n\ \36 bottles of beer on the wall, 36 bottles of beer.\n\ \Take one down and pass it around, 35 bottles of beer on the wall.\n\ \\n\ \35 bottles of beer on the wall, 35 bottles of beer.\n\ \Take one down and pass it around, 34 bottles of beer on the wall.\n\ \\n\ \34 bottles of beer on the wall, 34 bottles of beer.\n\ \Take one down and pass it around, 33 bottles of beer on the wall.\n\ \\n\ \33 bottles of beer on the wall, 33 bottles of beer.\n\ \Take one down and pass it around, 32 bottles of beer on the wall.\n\ \\n\ \32 bottles of beer on the wall, 32 bottles of beer.\n\ \Take one down and pass it around, 31 bottles of beer on the wall.\n\ \\n\ \31 bottles of beer on the wall, 31 bottles of beer.\n\ \Take one down and pass it around, 30 bottles of beer on the wall.\n\ \\n\ \30 bottles of beer on the wall, 30 bottles of beer.\n\ \Take one down and pass it around, 29 bottles of beer on the wall.\n\ \\n\ \29 bottles of beer on the wall, 29 bottles of beer.\n\ \Take one down and pass it around, 28 bottles of beer on the wall.\n\ \\n\ \28 bottles of beer on the wall, 28 bottles of beer.\n\ \Take one down and pass it around, 27 bottles of beer on the wall.\n\ \\n\ \27 bottles of beer on the wall, 27 bottles of beer.\n\ \Take one down and pass it around, 26 bottles of beer on the wall.\n\ \\n\ \26 bottles of beer on the wall, 26 bottles of beer.\n\ \Take one down and pass it around, 25 bottles of beer on the wall.\n\ \\n\ \25 bottles of beer on the wall, 25 bottles of beer.\n\ \Take one down and pass it around, 24 bottles of beer on the wall.\n\ \\n\ \24 bottles of beer on the wall, 24 bottles of beer.\n\ \Take one down and pass it around, 23 bottles of beer on the wall.\n\ \\n\ \23 bottles of beer on the wall, 23 bottles of beer.\n\ \Take one down and pass it around, 22 bottles of beer on the wall.\n\ \\n\ \22 bottles of beer on the wall, 22 bottles of beer.\n\ \Take one down and pass it around, 21 bottles of beer on the wall.\n\ \\n\ \21 bottles of beer on the wall, 21 bottles of beer.\n\ \Take one down and pass it around, 20 bottles of beer on the wall.\n\ \\n\ \20 bottles of beer on the wall, 20 bottles of beer.\n\ \Take one down and pass it around, 19 bottles of beer on the wall.\n\ \\n\ \19 bottles of beer on the wall, 19 bottles of beer.\n\ \Take one down and pass it around, 18 bottles of beer on the wall.\n\ \\n\ \18 bottles of beer on the wall, 18 bottles of beer.\n\ \Take one down and pass it around, 17 bottles of beer on the wall.\n\ \\n\ \17 bottles of beer on the wall, 17 bottles of beer.\n\ \Take one down and pass it around, 16 bottles of beer on the wall.\n\ \\n\ \16 bottles of beer on the wall, 16 bottles of beer.\n\ \Take one down and pass it around, 15 bottles of beer on the wall.\n\ \\n\ \15 bottles of beer on the wall, 15 bottles of beer.\n\ \Take one down and pass it around, 14 bottles of beer on the wall.\n\ \\n\ \14 bottles of beer on the wall, 14 bottles of beer.\n\ \Take one down and pass it around, 13 bottles of beer on the wall.\n\ \\n\ \13 bottles of beer on the wall, 13 bottles of beer.\n\ \Take one down and pass it around, 12 bottles of beer on the wall.\n\ \\n\ \12 bottles of beer on the wall, 12 bottles of beer.\n\ \Take one down and pass it around, 11 bottles of beer on the wall.\n\ \\n\ \11 bottles of beer on the wall, 11 bottles of beer.\n\ \Take one down and pass it around, 10 bottles of beer on the wall.\n\ \\n\ \10 bottles of beer on the wall, 10 bottles of beer.\n\ \Take one down and pass it around, 9 bottles of beer on the wall.\n\ \\n\ \9 bottles of beer on the wall, 9 bottles of beer.\n\ \Take one down and pass it around, 8 bottles of beer on the wall.\n\ \\n\ \8 bottles of beer on the wall, 8 bottles of beer.\n\ \Take one down and pass it around, 7 bottles of beer on the wall.\n\ \\n\ \7 bottles of beer on the wall, 7 bottles of beer.\n\ \Take one down and pass it around, 6 bottles of beer on the wall.\n\ \\n\ \6 bottles of beer on the wall, 6 bottles of beer.\n\ \Take one down and pass it around, 5 bottles of beer on the wall.\n\ \\n\ \5 bottles of beer on the wall, 5 bottles of beer.\n\ \Take one down and pass it around, 4 bottles of beer on the wall.\n\ \\n\ \4 bottles of beer on the wall, 4 bottles of beer.\n\ \Take one down and pass it around, 3 bottles of beer on the wall.\n\ \\n\ \3 bottles of beer on the wall, 3 bottles of beer.\n\ \Take one down and pass it around, 2 bottles of beer on the wall.\n\ \\n\ \2 bottles of beer on the wall, 2 bottles of beer.\n\ \Take one down and pass it around, 1 bottle of beer on the wall.\n\ \\n\ \1 bottle of beer on the wall, 1 bottle of beer.\n\ \Take it down and pass it around, no more bottles of beer on the wall.\n\ \\n\ \No more bottles of beer on the wall, no more bottles of beer.\n\ \Go to the store and buy some more, 99 bottles of beer on the wall.\n"
sandimetz/99bottles-polyglot
haskell/Beer.hs
mit
15,215
0
4
4,700
19
12
7
3
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ru-RU"> <title>Тестер регулярных выражений </title> <maps> <homeID>regextester</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Содержание</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Индекс</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Поиск</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Избранное</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/regextester/src/main/javahelp/help_ru_RU/helpset_ru_RU.hs
apache-2.0
1,038
102
29
158
531
258
273
-1
-1
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses #-} module ShouldFail where import Data.Kind (Type) -- must fail: defaults have no patterns class C2 a b where type S2 a :: Type type S2 Int = Char
sdiehl/ghc
testsuite/tests/indexed-types/should_fail/SimpleFail4.hs
bsd-3-clause
204
0
6
40
43
26
17
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ur-PK"> <title>Bug Tracker</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/bugtracker/src/main/javahelp/org/zaproxy/zap/extension/bugtracker/resources/help_ur_PK/helpset_ur_PK.hs
apache-2.0
956
103
29
156
389
209
180
-1
-1
{-# LANGUAGE CPP #-} {- | Compatibility helper module. This module holds definitions that help with supporting multiple library versions or transitions between versions. -} {- Copyright (C) 2011, 2012 Google 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.Compat ( rwhnf , Control.Parallel.Strategies.parMap ) where import qualified Control.Parallel.Strategies -- | Wrapper over the function exported from -- "Control.Parallel.Strategies". -- -- This wraps either the old or the new name of the function, -- depending on the detected library version. rwhnf :: Control.Parallel.Strategies.Strategy a #ifdef PARALLEL3 rwhnf = Control.Parallel.Strategies.rseq #else rwhnf = Control.Parallel.Strategies.rwhnf #endif
damoxc/ganeti
src/Ganeti/Compat.hs
gpl-2.0
1,383
0
6
221
57
41
16
7
1
{-# LANGUAGE CPP, KindSignatures #-} -- The record update triggered a kind error in GHC 6.2 module Foo where import Data.Kind (Type) data HT (ref :: Type -> Type) = HT { kcount :: Int } set_kcount :: Int -> HT s -> HT s set_kcount kc ht = ht{kcount=kc}
sdiehl/ghc
testsuite/tests/typecheck/should_compile/tc190.hs
bsd-3-clause
260
0
8
57
79
46
33
-1
-1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} module PersistTestPetCollarType where import GHC.Generics import Data.Aeson import Database.Persist.TH import Data.Text (Text) data PetCollar = PetCollar {tag :: Text, bell :: Bool} deriving (Generic, Eq, Show) instance ToJSON PetCollar instance FromJSON PetCollar derivePersistFieldJSON "PetCollar"
plow-technologies/persistent
persistent-test/src/PersistTestPetCollarType.hs
mit
371
0
8
49
88
50
38
12
0
module ConstructorFields where data Foo = Bar Int String -- ^ doc on `Bar` constructor | Baz -- ^ doc on the `Baz` constructor Int -- ^ doc on the `Int` field of `Baz` String -- ^ doc on the `String` field of `Baz` | Int :+ String -- ^ doc on the `:+` constructor | Int -- ^ doc on the `Int` field of the `:*` constructor :* -- ^ doc on the `:*` constructor String -- ^ doc on the `String` field of the `:*` constructor | Boo { x :: () } -- ^ doc on the `Boo` record constructor | Boa -- ^ doc on the `Boa` record constructor { y :: () }
shlevy/ghc
testsuite/tests/haddock/should_compile_noflag_haddock/haddockC036.hs
bsd-3-clause
660
0
9
240
72
47
25
13
0
module T10819_Lib where import Language.Haskell.TH.Syntax doSomeTH s tp drv = return [NewtypeD [] n [] Nothing (NormalC n [(Bang NoSourceUnpackedness NoSourceStrictness, ConT tp)]) drv] where n = mkName s
ezyang/ghc
testsuite/tests/th/T10819_Lib.hs
bsd-3-clause
213
0
12
37
81
43
38
5
1
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.DOMImplementation (createDocumentType, createDocumentType_, createDocument, createDocument_, createHTMLDocument, createHTMLDocument_, hasFeature, hasFeature_, DOMImplementation(..), gTypeDOMImplementation) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation.createDocumentType Mozilla DOMImplementation.createDocumentType documentation> createDocumentType :: (MonadDOM m, ToJSString qualifiedName, ToJSString publicId, ToJSString systemId) => DOMImplementation -> qualifiedName -> publicId -> systemId -> m DocumentType createDocumentType self qualifiedName publicId systemId = liftDOM ((self ^. jsf "createDocumentType" [toJSVal qualifiedName, toJSVal publicId, toJSVal systemId]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation.createDocumentType Mozilla DOMImplementation.createDocumentType documentation> createDocumentType_ :: (MonadDOM m, ToJSString qualifiedName, ToJSString publicId, ToJSString systemId) => DOMImplementation -> qualifiedName -> publicId -> systemId -> m () createDocumentType_ self qualifiedName publicId systemId = liftDOM (void (self ^. jsf "createDocumentType" [toJSVal qualifiedName, toJSVal publicId, toJSVal systemId])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation.createDocument Mozilla DOMImplementation.createDocument documentation> createDocument :: (MonadDOM m, ToJSString namespaceURI, ToJSString qualifiedName) => DOMImplementation -> Maybe namespaceURI -> qualifiedName -> Maybe DocumentType -> m XMLDocument createDocument self namespaceURI qualifiedName doctype = liftDOM ((self ^. jsf "createDocument" [toJSVal namespaceURI, toJSVal qualifiedName, toJSVal doctype]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation.createDocument Mozilla DOMImplementation.createDocument documentation> createDocument_ :: (MonadDOM m, ToJSString namespaceURI, ToJSString qualifiedName) => DOMImplementation -> Maybe namespaceURI -> qualifiedName -> Maybe DocumentType -> m () createDocument_ self namespaceURI qualifiedName doctype = liftDOM (void (self ^. jsf "createDocument" [toJSVal namespaceURI, toJSVal qualifiedName, toJSVal doctype])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation.createHTMLDocument Mozilla DOMImplementation.createHTMLDocument documentation> createHTMLDocument :: (MonadDOM m, ToJSString title) => DOMImplementation -> Maybe title -> m HTMLDocument createHTMLDocument self title = liftDOM ((self ^. jsf "createHTMLDocument" [toJSVal title]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation.createHTMLDocument Mozilla DOMImplementation.createHTMLDocument documentation> createHTMLDocument_ :: (MonadDOM m, ToJSString title) => DOMImplementation -> Maybe title -> m () createHTMLDocument_ self title = liftDOM (void (self ^. jsf "createHTMLDocument" [toJSVal title])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation.hasFeature Mozilla DOMImplementation.hasFeature documentation> hasFeature :: (MonadDOM m) => DOMImplementation -> m Bool hasFeature self = liftDOM ((self ^. jsf "hasFeature" ()) >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation.hasFeature Mozilla DOMImplementation.hasFeature documentation> hasFeature_ :: (MonadDOM m) => DOMImplementation -> m () hasFeature_ self = liftDOM (void (self ^. jsf "hasFeature" ()))
ghcjs/jsaddle-dom
src/JSDOM/Generated/DOMImplementation.hs
mit
4,946
0
12
948
998
556
442
76
1
{-# LANGUAGE CPP #-} module GHCJS.DOM.StorageErrorCallback ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.StorageErrorCallback #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.StorageErrorCallback #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/StorageErrorCallback.hs
mit
373
0
5
33
33
26
7
4
0
{-# LANGUAGE JavaScriptFFI #-} -- | An implementation of the NodeJS signature verification API, as documented -- <https://nodejs.org/api/crypto.html#crypto_class_verify here>. module GHCJS.Node.Crypto.Verify ( module GHCJS.Node.Crypto.Verify -- FIXME: specific export list ) where import GHCJS.Array import GHCJS.Foreign.Callback import GHCJS.Types -- FIXME: implement crypto.createVerify -- FIXME: implement <Verify>.verify -- FIXME: implement <Verify>.update
taktoa/ghcjs-electron
src/GHCJS/Node/Crypto/Verify.hs
mit
500
0
5
88
41
30
11
6
0
{-| Module : Language.GoLite.Parser.Stmt Description : Parsers for statements Copyright : (c) Jacob Errington and Frederic Lafrance, 2016 License : MIT Maintainer : goto@mail.jerrington.me Stability : experimental -} {-# LANGUAGE ViewPatterns #-} module Language.GoLite.Parser.Stmt ( stmt , expr , blockStmt , blockP -- used in function declarations , printStmtP , returnStmtP , ifStmtP , switchStmtP , fallthroughStmtP , forStmtP , breakStmtP , continueStmtP ) where import Language.GoLite.Parser.Core import Language.GoLite.Parser.SimpleStmts import Language.GoLite.Parser.Decl import Control.Monad ( void ) -- | Parses a statement. -- -- Some statement parsers produce several statements at once (specifically, -- distributed @type@ and @var@ declarations), so this parser takes care of -- wrapping the simpler statement parsers into singleton lists. stmt :: Parser [SrcAnnStatement] stmt = varDeclP <|> typeDeclP <|> choice (map (fmap pure) [ printStmtP , returnStmtP , ifStmtP , switchStmtP , fallthroughStmtP , forStmtP , breakStmtP , continueStmtP , blockStmt , simpleStmt >>= requireSemiP ] ) -- | Parses a print statement. -- -- @println@ is internally represented as a @print@ statement in which a -- synthetic @"\n"@ is appended to the expression list to print. printStmtP :: Parser SrcAnnStatement printStmtP = do (Ann l (runIdentity -> hasLn)) <- withSrcAnnId $ (try $ (kwPrintLn >>= noSemiP) *> pure True) <|> ((kwPrint >>= noSemiP) *> pure False) (Ann r exprs) <- withSrcAnnF $ parens (expr `sepBy` comma) >>= requireSemiP exprs' <- mapM noSemiP exprs let a = SrcSpan (srcStart l) (srcEnd r) pure $ Fix $ Ann a $ PrintStmt $ case hasLn of True -> exprs' ++ [Fix (Ann l (Literal (Ann l (StringLit "\n"))))] False -> exprs' -- | Parses a return statement. returnStmtP :: Parser SrcAnnStatement returnStmtP = do (Ann l s) <- withSrcAnnF kwReturn se <- optional expr requireSemiP $ case se of Nothing -> do s pure $ Fix $ Ann l $ ReturnStmt Nothing Just e -> do s *> noSemi e' <- e let a = SrcSpan (srcStart l) (srcEnd (topAnn e')) pure $ Fix $ Ann a $ ReturnStmt $ Just e' -- | Parses an if statement. It consists of the keyword if, followed by an -- optional simple statement, then an expression, then a block, followed by -- an optional else part. Note that unlike some other languages, the body of the -- statement must be a block (i.e. enclosed in braces). It cannot be a naked -- statement. -- -- If the optional initializer is present, it must have a semicolon. There -- cannot be a semicolon between the expression and the block. ifStmtP :: Parser SrcAnnStatement ifStmtP = do (Ann l _) <- withSrcAnnConst $ kwIf (initializer, cond) <- choice [ try $ (,) <$> pure Nothing <*> (expr <* lookAhead openBrace >>= noSemiP) , (,) <$> (fmap Just $ simpleStmt >>= requireSemiP) <*> (expr >>= noSemiP) ] -- The try here is OK, because if we fail in somewhere in the block, we'll -- attempt parsing it again right away. thens <- try (blockP <* (notFollowedBy kwElse) >>= requireSemiP) <|> (blockP >>= noSemiP) (Ann r elses) <- withSrcAnnF $ optional else_ let a = SrcSpan (srcStart l) (srcEnd r) pure $ do Fix $ Ann a $ IfStmt initializer cond thens elses -- | Parses the else part of an if statement. It's the \"else\" keyword followed -- either by a block or another if statement. else_ :: Parser [SrcAnnStatement] else_ = (kwElse >>= noSemiP) >> (blockP >>= requireSemiP) <|> fmap (:[]) ifStmtP -- | Parses a switch statement. It consists of the \"switch\" keyword, followed -- by an optional initializer simple statement, an optional expression, then a -- potentially empty list of case clauses enclosed in brackets. switchStmtP :: Parser SrcAnnStatement switchStmtP = do (Ann l _) <- withSrcAnnConst kwSwitch initializer <- optional (try $ simpleStmt >>= requireSemiP) e <- optional (expr >>= noSemiP) (Ann r clauses) <- withSrcAnnF $ (braces $ many caseClause) >>= requireSemiP let a = SrcSpan (srcStart l) (srcEnd r) pure $ Fix $ Ann a $ SwitchStmt initializer e clauses -- | Parses a case clause. It is a case head and a block separated by a colon. caseClause :: Parser (SrcAnnCaseHead, [SrcAnnStatement]) caseClause = do head_ <- caseHead <* colon stmts <- stmt `manyTill` lookAhead (try $ void caseHead <|> void closeBrace) pure $ (head_, concat stmts) -- Each statement parser may produce multiple statements, so use concat. -- | Parses a case head. It is either the keyword \"default\", or the keyword -- \"case\" followed by a comma-separated list of expressions. caseHead :: Parser SrcAnnCaseHead caseHead = default_ <|> case_ where default_ = (kwDefault >>= noSemiP) *> pure CaseDefault case_ = do kwCase >>= noSemiP exprs <- (expr >>= noSemiP) `sepBy1` comma pure $ CaseExpr exprs -- | Parses a for statement. It starts with the \"for\" keyword, then the for -- head, then a block. The for head has three forms: nothing, an expression, or -- an initializer simple statement followed by an expression and another simple -- statement. In this last case, all the components are optional, and the -- initializer and expression must end with a semicolon. forStmtP :: Parser SrcAnnStatement forStmtP = do (Ann l _) <- withSrcAnnConst kwFor (Fix (Ann r s)) <- infiniteFor <|> simpleFor <|> fullFor let a = SrcSpan (srcStart l) (srcEnd r) pure $ Fix $ Ann a s -- | Parses an infinite for loop, which does not contain anything in its head. -- This parser may be backtracked out of before reaching the beginning of a -- block. infiniteFor :: Parser SrcAnnStatement infiniteFor = do (try . lookAhead . symbol_) "{" (Ann a b) <- withSrcAnnF (blockP >>= unSemiP) pure $ Fix $ Ann a $ ForStmt Nothing Nothing Nothing b -- | Parses a full for loop, which may contain an initializer simple statement, -- an expression and a post-iteration simple statement. All those components -- are optional. The initializer and expression must end with a semicolon, -- the post-iteration must not. The post-iteration statement cannot be a -- variable declaration. fullFor :: Parser SrcAnnStatement fullFor = do (Ann l (runIdentity -> (initializer, cond, post))) <- withSrcAnnId $ (,,) <$> optional (simpleStmt >>= requireSemiP) -- This looks funky but it's an easy way to encode that there's -- either an expression, or just a semicolon. <*> (emptyStmtP $> Nothing <|> fmap Just (expr >>= requireSemiP)) <*> optional (simpleStmt >>= noSemiP) case post of (Just (Fix (Ann _ (ShortVarDecl _ _)))) -> failure [Message "Illegal short variable declaration in post-loop statement."] _ -> pure () (Ann r b) <- withSrcAnnF (blockP >>= requireSemiP) let a = SrcSpan (srcStart l) (srcEnd r) pure $ Fix $ Ann a $ ForStmt initializer cond post b -- | Parses a for loop that only has a condition in its head. This parser can be -- backtracked out of until reaching the beginning of a block. simpleFor :: Parser SrcAnnStatement simpleFor = do e <- try $ do e <- expr >>= noSemiP lookAhead $ symbol_ "{" -- Make sure a block begins next. pure e (Ann a b) <- withSrcAnnF (blockP >>= requireSemiP) pure $ Fix $ Ann a $ ForStmt Nothing (Just e) Nothing b -- | Parses a block, which is a potentially empty list of statements enclosed in -- braces. blockP :: Parser (Semi [SrcAnnStatement]) blockP = do symbol "{" stmts <- many stmt -- All blocks require a semi, EXCEPT the block for ifs, which does not -- require a semi if there is an else[-if] part to the statement. Therefore -- we must keep track of semis on blocks. b <- closeBrace -- Each statement parser may produce multiple statements. pure $ do _ <- b -- force semi evaluation on the brace. pure $ concat stmts -- | Parses a block, wrapped as a statement. blockStmt :: Parser SrcAnnStatement blockStmt = do (Ann a b) <- withSrcAnnF (blockP >>= requireSemiP) pure $ Fix $ Ann a $ Block b -- | Parses a break statement, which consists of the \"break\" keyword. breakStmtP :: Parser SrcAnnStatement breakStmtP = do (Ann a _) <- withSrcAnnConst $ kwBreak >>= requireSemiP pure $ Fix $ Ann a $ BreakStmt -- | Parses a fallthrough statement, which consists of the \"fallthrough\" -- keyword. This parser always fails, since this keyword is unsupported in -- GoLite. fallthroughStmtP :: Parser SrcAnnStatement fallthroughStmtP = do withSrcAnnConst $ kwFallthrough >>= requireSemiP failure [Message "fallthrough is not supported in GoLite"] -- | Parses a continue statement, which consists of the \"continue\" keyword. continueStmtP :: Parser SrcAnnStatement continueStmtP = do (Ann a _) <- withSrcAnnConst $ kwContinue >>= requireSemiP pure $ Fix $ Ann a $ ContinueStmt
djeik/goto
libgoto/Language/GoLite/Parser/Stmt.hs
mit
9,256
0
21
2,191
2,016
1,029
987
150
2
module Sing where fstString :: [Char] -> [Char] fstString x = x ++ " in the rain" sndString :: [Char] -> [Char] sndString x = x ++ " over the rainbow" sing = if (x < y) then fstString x else sndString y where x = "Singin" y = "Somewhere"
mikegehard/haskellBookExercises
chapter5/sing.hs
mit
268
0
7
80
96
54
42
8
2
module Network.XMLHttpRequest where import Data.Foreign -- Access to the outside world. import Control.Monad.Eff import Data.Maybe import Data.Either -- Effects foreign import data XHR :: * foreign import data XHRReq :: ! type URI = String -- Stolen from Network.HTTP <3 -- TODO make Network.HTTP live again. data Verb = DELETE | GET | HEAD | OPTIONS | PATCH | POST | PUT instance showHTTPVerb :: Show Verb where show DELETE = "DELETE" show GET = "GET" show HEAD = "HEAD" show OPTIONS = "OPTIONS" show PATCH = "PATCH" show POST = "POST" show PUT = "PUT" data XHRResponse = XHRResponse { readyState :: Number , status :: Number , statusText :: String , response :: String , responseText :: String , responseType :: String } instance readXHRResponse :: ReadForeign XHRResponse where read = do redySt <- prop "readyState" st <- prop "status" stT <- prop "statusText" rs <- prop "response" rsTe <- prop "responseText" rsTy <- prop "responseType" return $ XHRResponse { readyState: redySt , status: st , statusText: stT , response: rs , responseText: rsTe , responseType: rsTy } ------------------------------ -- Foreign Import Functions -- ------------------------------ foreign import startXHR "function startXHR() {\ \ return new XMLHttpRequest(); \ \};" :: forall a. Eff (x :: XHRReq | a) XHR foreign import assignOnStateChange "function assignOnStateChange(xhr) {\ \ return function(f) {\ \ return function() {\ \ xhr.onreadystatechange = function() { f(xhr); }; \ \ return xhr; \ \ }; \ \ }; \ \};" :: forall eff a b. XHR -> (XHR -> a) -> Eff (x :: XHRReq | b) XHR foreign import open "function open(xhr) {\ \ return function(type) {\ \ return function(url) {\ \ return function() {\ \ xhr.open(type, url, true); \ \ return xhr; \ \ }; \ \ }; \ \ }; \ \};" :: forall a. XHR -> String -> URI -> Eff (x :: XHRReq | a) XHR foreign import sendEmpty "function sendEmpty(xhr) {\ \ return function() {\ \ xhr.send(null); \ \ return xhr; \ \ }; \ \};" :: forall eff. XHR -> Eff (x :: XHRReq | eff) XHR foreign import sendPayload "function sendPayload(xhr) {\ \ return function(payload) {\ \ return function() {\ \ xhr.send(payload); \ \ return x; \ \ }; \ \ }; \ \};" :: forall eff a. XHR -> a -> Eff (x :: XHRReq | eff) XHR foreign import maybeXhr "function maybeXhr(req) {\ \ console.log(req != undefined); \ \ if (req != undefined) {\ \ return PS.Data_Maybe.Just(req.valueOf()); \ \ } \ \ else {\ \ return PS.Data_Maybe.Nothing; \ \ }\ \};" :: XHR -> Maybe Foreign maybeResponse :: XHR -> Either String XHRResponse maybeResponse x = case maybeXhr x of Just r -> parseForeign (read) r Nothing -> Left ("Error Parsing XHR Target")
mankyKitty/purescript-xmlhttp
src/Network/XMLHttpRequest/XMLHttpRequest.purs.hs
mit
3,306
47
10
1,136
590
322
268
-1
-1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SVGPaint (js_setUri, setUri, js_setPaint, setPaint, pattern SVG_PAINTTYPE_UNKNOWN, pattern SVG_PAINTTYPE_RGBCOLOR, pattern SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR, pattern SVG_PAINTTYPE_NONE, pattern SVG_PAINTTYPE_CURRENTCOLOR, pattern SVG_PAINTTYPE_URI_NONE, pattern SVG_PAINTTYPE_URI_CURRENTCOLOR, pattern SVG_PAINTTYPE_URI_RGBCOLOR, pattern SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR, pattern SVG_PAINTTYPE_URI, js_getPaintType, getPaintType, js_getUri, getUri, SVGPaint, castToSVGPaint, gTypeSVGPaint) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"setUri\"]($2)" js_setUri :: SVGPaint -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPaint.setUri Mozilla SVGPaint.setUri documentation> setUri :: (MonadIO m, ToJSString uri) => SVGPaint -> uri -> m () setUri self uri = liftIO (js_setUri (self) (toJSString uri)) foreign import javascript unsafe "$1[\"setPaint\"]($2, $3, $4, $5)" js_setPaint :: SVGPaint -> Word -> JSString -> JSString -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPaint.setPaint Mozilla SVGPaint.setPaint documentation> setPaint :: (MonadIO m, ToJSString uri, ToJSString rgbColor, ToJSString iccColor) => SVGPaint -> Word -> uri -> rgbColor -> iccColor -> m () setPaint self paintType uri rgbColor iccColor = liftIO (js_setPaint (self) paintType (toJSString uri) (toJSString rgbColor) (toJSString iccColor)) pattern SVG_PAINTTYPE_UNKNOWN = 0 pattern SVG_PAINTTYPE_RGBCOLOR = 1 pattern SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR = 2 pattern SVG_PAINTTYPE_NONE = 101 pattern SVG_PAINTTYPE_CURRENTCOLOR = 102 pattern SVG_PAINTTYPE_URI_NONE = 103 pattern SVG_PAINTTYPE_URI_CURRENTCOLOR = 104 pattern SVG_PAINTTYPE_URI_RGBCOLOR = 105 pattern SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR = 106 pattern SVG_PAINTTYPE_URI = 107 foreign import javascript unsafe "$1[\"paintType\"]" js_getPaintType :: SVGPaint -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPaint.paintType Mozilla SVGPaint.paintType documentation> getPaintType :: (MonadIO m) => SVGPaint -> m Word getPaintType self = liftIO (js_getPaintType (self)) foreign import javascript unsafe "$1[\"uri\"]" js_getUri :: SVGPaint -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPaint.uri Mozilla SVGPaint.uri documentation> getUri :: (MonadIO m, FromJSString result) => SVGPaint -> m result getUri self = liftIO (fromJSString <$> (js_getUri (self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SVGPaint.hs
mit
3,445
34
10
522
821
472
349
60
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeSynonymInstances #-} module Physics.Demo.IOWorld where import Control.Lens (makeLenses, view, (%~), (&), (.~), (^.), _1) import Control.Monad import Control.Monad.IO.Class import Control.Monad.Reader import Control.Monad.ST import Control.Monad.State.Strict import Data.Maybe import qualified Data.Vector.Unboxed as V import Linear.Matrix (M33) import Linear.V2 import EasySDL.Draw import GameLoop import qualified SDL.Event as E import qualified SDL.Input.Keyboard as K import qualified SDL.Input.Keyboard.Codes as KC import qualified SDL.Time as T import qualified SDL.Video.Renderer as R import qualified Physics.Broadphase.Aabb as B import qualified Physics.Broadphase.Grid as G import Physics.Contact import Physics.Contact.ConvexHull import Physics.Contact.Types (ContactBehavior (..)) import qualified Physics.Contact.Types as C import Physics.Demo.Scenes import Physics.Draw import Physics.Draw.Canonical import qualified Physics.Draw.Opt as D import Physics.Engine import qualified Physics.Engine.Main as OM import Physics.Scenes.Scene import qualified Physics.Solvers.Contact as S import Physics.World import Utils.Descending import Utils.Utils type DemoM = ReaderT OM.EngineConfig (StateT (OM.EngineState () RealWorld) IO) convertEngineT :: OM.EngineST () RealWorld a -> DemoM a convertEngineT action = ReaderT (\config -> StateT (stToIO . runStateT (runReaderT action config))) runDemo :: Scene RealWorld () -> DemoM a -> IO a runDemo scene@Scene{..} action = do eState <- liftIO . stToIO $ OM.initEngine scene evalStateT (runReaderT action eConfig) eState where eConfig = OM.EngineConfig 0.01 _scContactBeh resetEngine :: Scene RealWorld () -> DemoM () resetEngine scene = convertEngineT $ OM.changeScene scene drawWorld :: R.Renderer -> M33 Double -> DemoM () drawWorld r vt = do world <- demoWorld liftIO $ D.drawWorld r vt world demoWorld :: DemoM (World RealWorld ()) demoWorld = view _1 <$> get worldContacts :: DemoM [Contact] worldContacts = do world <- demoWorld keys <- lifty $ G.culledKeys <$> G.toGrid OM.gridAxes world contacts_ <- lifty $ S.prepareFrame keys world let contacts :: Descending C.Contact contacts = fmap (flipExtractUnsafe . snd) contacts_ return . _descList $ toCanonical <$> contacts lifty :: (MonadIO m) => ST RealWorld a -> m a lifty = liftIO . stToIO worldAabbs :: DemoM [Aabb] worldAabbs = do world <- demoWorld aabbs <- lifty $ B.toAabbs world return $ toCanonical . snd <$> V.toList aabbs debugEngineState :: DemoM String debugEngineState = return "<insert debug trace here>" updateWorld :: DemoM () updateWorld = void . convertEngineT $ OM.updateWorld data DemoState = DemoState { _demoFinished :: Bool , _demoSceneIndex :: Int , _demoDrawDebug :: Bool , _demoPrintDebug :: Bool , _demoViewTransform :: M33 Double } makeLenses ''DemoState getViewTransform :: V2 Double -> V2 Double -> M33 Double getViewTransform window scale = fst $ viewTransform window scale (V2 0 0) initialState :: Int -> M33 Double -> DemoState initialState i = DemoState False i True False nextInitialState :: DemoState -> Int -> DemoM DemoState nextInitialState DemoState{..} i = do scene <- lifty $ scenes i resetEngine scene return $ initialState i _demoViewTransform & demoDrawDebug .~ _demoDrawDebug & demoPrintDebug .~ _demoPrintDebug timeStep :: Num a => a timeStep = 10 renderWorld :: R.Renderer -> DemoState -> DemoM () renderWorld r DemoState{..} = do liftIO $ setColor r black drawWorld r _demoViewTransform renderContacts :: R.Renderer -> DemoState -> DemoM () renderContacts r DemoState{..} = do liftIO $ setColor r pink contacts <- worldContacts liftIO $ mapM_ (drawContact r . transform _demoViewTransform) contacts renderAabbs :: R.Renderer -> DemoState -> DemoM () renderAabbs r DemoState{..} = do liftIO $ setColor r silver aabbs <- worldAabbs liftIO $ mapM_ (drawAabb r . transform _demoViewTransform) aabbs demoStep :: R.Renderer -> DemoState -> DemoM DemoState demoStep r s0@DemoState {..} = do events <- liftIO E.pollEvents liftIO $ clearScreen r renderWorld r s0 when (s0 ^. demoDrawDebug) $ do renderContacts r s0 renderAabbs r s0 when (s0 ^. demoPrintDebug) $ do debug <- debugEngineState liftIO $ print debug s1 <- foldM handleEvent s0 events updateWorld liftIO $ R.present r return s1 handleEvent :: DemoState -> E.Event -> DemoM DemoState handleEvent s0 (E.Event _ E.QuitEvent) = return s0 { _demoFinished = True } handleEvent s0 (E.Event _ (E.KeyboardEvent (E.KeyboardEventData _ motion _ key))) | motion == E.Pressed = handleKeypress s0 (K.keysymScancode key) (K.keysymModifier key) | otherwise = return s0 handleEvent s0 _ = return s0 handleKeypress :: DemoState -> K.Scancode -> K.KeyModifier -> DemoM DemoState handleKeypress state KC.ScancodeR _ = nextInitialState state (state ^. demoSceneIndex) handleKeypress state KC.ScancodeN km | K.keyModifierLeftShift km || K.keyModifierRightShift km = nextInitialState state $ (state ^. demoSceneIndex - 1) `posMod` sceneCount | otherwise = nextInitialState state $ (state ^. demoSceneIndex + 1) `mod` sceneCount handleKeypress state KC.ScancodeD _ = return $ state & demoDrawDebug %~ not handleKeypress state KC.ScancodeP _ = return $ state & demoPrintDebug %~ not handleKeypress state _ _ = return state demoMain :: V2 Double -> V2 Double -> R.Renderer -> IO () demoMain window scale r = do t0 <- T.ticks let demo = timedRunUntil t0 timeStep (initialState 0 $ getViewTransform window scale) _demoFinished (\s _ -> demoStep r s) scene <- lifty $ scenes 0 runDemo scene demo
ublubu/shapes
shapes-demo/src/Physics/Demo/IOWorld.hs
mit
6,371
0
13
1,521
1,947
998
949
162
1
----------------------------------------------------------------------------- -- -- Module : Builder -- Copyright : -- License : BSD3 -- -- Maintainer : agocorona@gmail.com -- Stability : experimental -- Portability : -- -- | Monad and Monoid instances for a builder that hang DOM elements from the -- current parent element. It uses Haste.DOM from the haste-compiler -- ----------------------------------------------------------------------------- {-#LANGUAGE CPP, ForeignFunctionInterface, TypeSynonymInstances, FlexibleInstances , DeriveDataTypeable, UndecidableInstances , OverlappingInstances #-} module Haste.Perch.Client where import Data.Typeable import Haste.App import Haste.Foreign import Data.Maybe import Data.Monoid import Unsafe.Coerce import Data.String import Control.Monad.IO.Class import Control.Applicative newtype PerchM a= Perch{build :: Elem -> Client Elem} deriving Typeable type Perch = PerchM () instance Monoid (PerchM a) where mappend mx my= Perch $ \e -> do build mx e build my e return e mempty = Perch return instance Functor PerchM instance Applicative PerchM instance Monad PerchM where (>>) x y= mappend (unsafeCoerce x) y (>>=) = error "bind (>>=) invocation in the Perch monad creating DOM elements" return = mempty instance MonadIO PerchM where liftIO mx= Perch $ \e -> liftIO mx >> return e instance IsString Perch where fromString= toElem class ToElem a where toElem :: a -> Perch instance ToElem String where toElem s= Perch $ \e -> do e' <- newTextElem s addChild e' e return e' instance Show a => ToElem a where toElem = toElem . show instance ToElem (PerchM a) where toElem e = unsafeCoerce e attr tag (n, v)=Perch $ \e -> do tag' <- build tag e setAttr tag' n v return tag' nelem :: String -> Perch nelem s= Perch $ \e ->do e' <- newElem s addChild e' e return e' child :: ToElem a => Perch -> a -> Perch child me ch= Perch $ \e' -> do e <- build me e' let t = toElem ch r <- build t e return e setHtml :: Perch -> String -> Perch setHtml me text= Perch $ \e' -> do e <- build me e' inner e text return e' where inner :: Elem -> String -> Client () inner e txt = setProp e "innerHTML" txt -- | create an element and add a Haste event handler to it. addEvent :: ClientCallback a => Perch -> Event Client a -> a -> Perch addEvent be event action= Perch $ \e -> do e' <- build be e let atr= evtName event has <- getAttr e' atr case has of "true" -> return e' _ -> do onEvent e' event action setAttr e' atr "true" return e' instance JSType JSString where toJSString x= x fromJSString x= Just x -- Leaf DOM nodes -- area = nelem "area" base = nelem "base" br = nelem "br" col = nelem "col" embed = nelem "embed" hr = nelem "hr" img = nelem "img" input = nelem "input" keygen = nelem "keygen" link = nelem "link" menuitem = nelem "menuitem" meta = nelem "meta" param = nelem "param" source = nelem "source" track = nelem "track" wbr = nelem "wbr" -- Parent DOM nodes -- a cont = nelem "a" `child` cont abbr cont = nelem "abbr" `child` cont address cont = nelem "address" `child` cont article cont = nelem "article" `child` cont aside cont = nelem "aside" `child` cont audClient cont = nelem "audio" `child` cont b cont = nelem "b" `child` cont bdo cont = nelem "bdo" `child` cont blockquote cont = nelem "blockquote" `child` cont body cont = nelem "body" `child` cont button cont = nelem "button" `child` cont canvas cont = nelem "canvas" `child` cont caption cont = nelem "caption" `child` cont cite cont = nelem "cite" `child` cont code cont = nelem "code" `child` cont colgroup cont = nelem "colgroup" `child` cont command cont = nelem "command" `child` cont datalist cont = nelem "datalist" `child` cont dd cont = nelem "dd" `child` cont del cont = nelem "del" `child` cont details cont = nelem "details" `child` cont dfn cont = nelem "dfn" `child` cont div cont = nelem "div" `child` cont dl cont = nelem "dl" `child` cont dt cont = nelem "dt" `child` cont em cont = nelem "em" `child` cont fieldset cont = nelem "fieldset" `child` cont figcaption cont = nelem "figcaption" `child` cont figure cont = nelem "figure" `child` cont footer cont = nelem "footer" `child` cont form cont = nelem "form" `child` cont h1 cont = nelem "h1" `child` cont h2 cont = nelem "h2" `child` cont h3 cont = nelem "h3" `child` cont h4 cont = nelem "h4" `child` cont h5 cont = nelem "h5" `child` cont h6 cont = nelem "h6" `child` cont head cont = nelem "head" `child` cont header cont = nelem "header" `child` cont hgroup cont = nelem "hgroup" `child` cont html cont = nelem "html" `child` cont i cont = nelem "i" `child` cont iframe cont = nelem "iframe" `child` cont ins cont = nelem "ins" `child` cont kbd cont = nelem "kbd" `child` cont label cont = nelem "label" `child` cont legend cont = nelem "legend" `child` cont li cont = nelem "li" `child` cont map cont = nelem "map" `child` cont mark cont = nelem "mark" `child` cont menu cont = nelem "menu" `child` cont meter cont = nelem "meter" `child` cont nav cont = nelem "nav" `child` cont noscript cont = nelem "noscript" `child` cont object cont = nelem "object" `child` cont ol cont = nelem "ol" `child` cont optgroup cont = nelem "optgroup" `child` cont option cont = nelem "option" `child` cont output cont = nelem "output" `child` cont p cont = nelem "p" `child` cont pre cont = nelem "pre" `child` cont progress cont = nelem "progress" `child` cont q cont = nelem "q" `child` cont rp cont = nelem "rp" `child` cont rt cont = nelem "rt" `child` cont ruby cont = nelem "ruby" `child` cont samp cont = nelem "samp" `child` cont script cont = nelem "script" `child` cont section cont = nelem "section" `child` cont select cont = nelem "select" `child` cont small cont = nelem "small" `child` cont span cont = nelem "span" `child` cont strong cont = nelem "strong" `child` cont {-style cont = nelem "style" `child` cont-} sub cont = nelem "sub" `child` cont summary cont = nelem "summary" `child` cont sup cont = nelem "sup" `child` cont table cont = nelem "table" `child` cont tbody cont = nelem "tbody" `child` cont td cont = nelem "td" `child` cont textarea cont = nelem "textarea" `child` cont tfoot cont = nelem "tfoot" `child` cont th cont = nelem "th" `child` cont thead cont = nelem "thead" `child` cont time cont = nelem "time" `child` cont title cont = nelem "title" `child` cont tr cont = nelem "tr" `child` cont ul cont = nelem "ul" `child` cont var cont = nelem "var" `child` cont video cont = nelem "video" `child` cont ctag tag cont= nelem tag `child` cont -- HTML4 support center cont= nelem "center" `child` cont noHtml= mempty :: Perch type Attribute = (String,String) class Attributable h where (!) :: h -> Attribute -> h instance ToElem a => Attributable (a -> Perch) where (!) pe atrib = \e -> pe e `attr` atrib instance Attributable Perch where (!) = attr atr n v= (n,v) style= atr "style" id = atr "id" width= atr "width" height= atr "height" href= atr "href" src= atr "src" ---------------- DOM Tree navigation -- | return the current node this :: Perch this= Perch $ \e -> return e -- | goes to the parent node of the first and execute the second goParent :: Perch -> Perch -> Perch goParent pe pe'= Perch $ \e' -> do e <- build pe e' p <- liftIO $ parent e e2 <- build pe' p return e2 -- | delete the current node. Return the parent delete :: Perch delete= Perch $ \e -> do p <- liftIO $ parent e removeChild e p return p -- | delete the children of the current node. clear :: Perch clear= Perch $ \e -> clearChildren e >> return e parent :: Elem -> IO Elem parent= ffi $ toJSString "(function(e){return e.parentNode;})" getBody :: IO Elem getBody= ffi $ toJSString "(function(){return document.body;})" getDocument :: IO Elem getDocument= ffi $ toJSString "(function(){return document;})" -- ! JQuery-like DOM manipulation: using a selector for querySelectorAll, -- it apply the Perch DOM manipulation of the second parameter for each of the matches -- -- Example -- -- > main= do -- > body <- getBody -- > (flip build) body $ pre $ do -- > div ! atr "class" "modify" $ "click" -- > div $ "not changed" -- > div ! atr "class" "modify" $ "here" -- > -- > addEvent this OnClick $ \_ _ -> do -- > forElems' ".modify" $ this ! style "color:red" forElems' :: String -> Perch -> Client () forElems' for doit= do (flip build) undefined (forElems for doit) return () -- ! JQuery-like DOM manipulation: using a selector for querySelectorAll, -- it apply the Perch DOM manipulation of the second parameter for each of the matches forElems :: String -> Perch -> Perch forElems selectors dosomething= Perch $ \e -> do es <- liftIO $ queryAll selectors mapM (build dosomething) es return e where queryAll :: String -> IO [Elem] queryAll = ffi $ toJSString "(function(sel){return document.querySelectorAll(sel);})"
ababkin/railoscopy
src/Haste/Perch/Client.hs
mit
9,259
0
14
2,099
3,098
1,607
1,491
230
2
-- | Utilities related to representation of versions. -- Adapted from @Apia.Utils.Version@ {-# LANGUAGE CPP #-} {-# LANGUAGE UnicodeSyntax #-} module OnlineATPs.Utils.Version ( progNameVersion ) where import Data.Char ( toUpper ) import Data.Version ( showVersion ) import Paths_online_atps ( version ) import System.Environment ( getProgName ) toUpperFirst ∷ String → String toUpperFirst [] = [] toUpperFirst (x : xs) = toUpper x : xs -- Uncomment this in order to use ghcid with Main.hs --progNameVersion ∷ IO String --progNameVersion = return "dev" -- | Return program name and version information. progNameVersion ∷ IO String progNameVersion = do progName ← getProgName return $ toUpperFirst progName ++ " version " ++ showVersion version
jonaprieto/online-atps
src/OnlineATPs/Utils/Version.hs
mit
798
0
10
155
142
80
62
14
1
-- Branching model from Anglican (https://bitbucket.org/probprog/anglican-white-paper) module Branching where import Control.Monad.Bayes.Simple fib :: Int -> Int fib n = run 1 1 0 where run a b m = if n == m then a else run b (a + b) (m+1) branching :: (MonadBayes m, CustomReal m ~ Double) => m Int branching = do let count_prior = discrete $ replicate 10 0.1 -- TODO: change to poisson 4 r <- count_prior l <- if (4 < r) then return 6 else fmap (+ fib (3*r)) count_prior observe (discreteDist $ replicate 10 0.1) 6 -- TODO: change to poisson l return r
adscib/monad-bayes
models/Branching.hs
mit
596
0
13
144
213
110
103
14
2
{-# LANGUAGE OverloadedStrings, GADTs, StandaloneDeriving, DataKinds, FlexibleInstances, KindSignatures #-} module Nginx.Main(main) where import Data.Text(Text) import qualified Data.Text as Text import qualified Data.Text.IO as Text import Data.Attoparsec.Text import Control.Applicative import Control.Monad import Data.Monoid ((<>)) import qualified Data.ByteString.Lazy.Char8 as BS import Text.Parser.Combinators (endBy) import Nginx.Types (Context(..),Serializable,serialize) import Nginx.Events (EventsDirective,events) import Nginx.Utils import Nginx.Http.Core (http,HttpDirective) data MainDirective (a :: Context) where UserDirective :: Text -> MainDirective MainContext WorkerProcessesDirective :: Integer -> MainDirective MainContext TimerResolutionDirective :: Text -> MainDirective MainContext PidDirective :: Text -> MainDirective MainContext EventsDirective :: [EventsDirective 'EventsContext] -> MainDirective MainContext HttpDirective :: [HttpDirective 'HttpContext] -> MainDirective MainContext deriving instance Show (MainDirective a) main = mainDirective `sepBy` directiveSeparator mainDirective = user <|> workerProcesses <|> pid <|> eventsD <|> timerResolution <|> httpD user = UserDirective <$> textValueDirective "user" workerProcesses = WorkerProcessesDirective <$> intValueDirective "worker_processes" pid = PidDirective <$> textValueDirective "pid" eventsD = EventsDirective <$> (string "events" *> skipSpace *> char '{' *> skipSpace *> many events <* skipSpace <* char '}') timerResolution = TimerResolutionDirective <$> textValueDirective "timer_resolution" httpD = HttpDirective <$> (string "http" *> skipSpace *> char '{' *> skipSpace *> many directiveSeparator *> http <* many directiveSeparator <* skipSpace <* char '}') instance Serializable (MainDirective a) where serialize (UserDirective user) = "user " <> user serialize (WorkerProcessesDirective workers) = "worker_processes " <> (Text.pack $ show workers) serialize (TimerResolutionDirective tr) = "timer_resolution " <> tr serialize (PidDirective pid) = "pid " <> pid serialize (EventsDirective block) = "events {\n" <> (Text.concat $ map serialize block) <> "}\n" --serialize (HttpDirective block) = undefined -- "http {\n" <> (Text.concat serialize _ = error "not implemented yet"
polachok/hs-nginx
src/Nginx/Main.hs
mit
2,333
0
15
320
590
320
270
38
1
module Main ( main ) where import Criterion.Main (defaultMain, bgroup, bench, whnfIO) import Dusky (getLightTimes) import qualified LightTimes import Data.Time.LocalTime main = do timeZone <- getCurrentTimeZone defaultMain [ bgroup "getLightTimes" [ bench "nyc" $ whnfIO $ getLightTimes (40.7127, 74.0059) timeZone LightTimes.sunriseTimes ] ]
cmwilhelm/dusky
benchmark/Main.hs
mit
389
0
13
89
101
57
44
12
1
example1 :: Maybe Int example1 = do a <- Just 3 b <- Just 4 return $ a + b -- Just 7 example2 :: Maybe Int example2 = do a <- Just 3 b <- Nothing return $ a + b -- Nothing
riwsky/wiwinwlh
src/maybe.hs
mit
185
0
8
57
88
41
47
10
1
module Player.Resources.Dom where import Rules import Common.CssClass import Player.Resources.Style import Common.DomUtil import Reflex.Dom import Data.Monoid ((<>)) import Data.Text as T import Control.Monad (replicateM_, forM_) drawResourcesDyn :: MonadWidget t m => Dynamic t Resources -> m () drawResourcesDyn res = do uniqRes <- holdUniqDyn res dyn_ $ drawResources <$> uniqRes drawResources :: MonadWidget t m => Resources -> m () drawResources res = divAttributeLike resourceHolderClass $ forM_ resourceTypes $ \(func, cls) -> drawResource res func cls drawResource :: MonadWidget t m => Resources -> (Resources -> Int) -> CssClass -> m () drawResource res func cls = do let number = func res if number == 0 then return () else divAttributeLike resourceLineClass $ if number > 3 then do divAttributeLike (cls <> resourceIconClass) $ return () text $ T.pack $ show number else do replicateM_ number $ divAttributeLike (cls <> resourceIconClass) $ return () resourceTypes :: [(Resources -> Int, CssClass)] resourceTypes = [(getWoodAmount, woodIconClass), (getStoneAmount, stoneIconClass), (getGoldAmount, goldIconClass), (getIronAmount, ironIconClass), (getWheatAmount, wheatIconClass), (getPotatoAmount, potatoIconClass), (getMoneyAmount, moneyIconClass), (getFoodAmount, foodIconClass)]
martin-kolinek/some-board-game
src/Player/Resources/Dom.hs
mit
1,462
0
16
336
446
240
206
36
3
---------------------------------------------------------------------- -- -- Proc.hs -- Programming Languages -- Fall 2015 -- -- An implementation of Proc -- [Nielson and Nielson, Semantics with Applications] -- -- Author: Pablo López --- ------------------------------------------------------------------- -- ------------------------------------------------------------------- -- Abstract syntax -- ------------------------------------------------------------------- module Proc where type Var = String type Pname = String data Aexp = N Integer | V Var | Add Aexp Aexp | Mult Aexp Aexp | Sub Aexp Aexp deriving (Show, Eq) data Bexp = TRUE | FALSE | Eq Aexp Aexp | Le Aexp Aexp | Neg Bexp | And Bexp Bexp deriving (Show, Eq) data DecVar = Dec Var Aexp DecVar | EndDec deriving Show data DecProc = Proc Pname Stm DecProc | EndProc deriving Show data Stm = Ass Var Aexp | Skip | Comp Stm Stm | If Bexp Stm Stm | While Bexp Stm | Block DecVar DecProc Stm | Call Pname | For Var Aexp Aexp Stm -- For x:= a1 to a2 do S | Repeat Stm Bexp -- Repeat S until b deriving Show -- Example B.1 factorial :: Stm factorial = Block (Dec "x" (N 5) (Dec "y" (N 1) EndDec)) EndProc (While (Neg (Eq (V "x") (N 1))) (Comp (Ass "y" (Mult (V "y") (V "x"))) (Ass "x" (Sub (V "x") (N 1))))) -- End Example B.1 --------------------------------------------------------------------- -- Evaluation of expressions --------------------------------------------------------------------- type Z = Integer type T = Bool type State = Var -> Z -- Example B.3 sInit :: State sInit "x" = 3 sInit _ = 0 -- End Example B.3 aVal :: Aexp -> State -> Z aVal (N n) _ = n aVal (V x) s = s x aVal (Add a1 a2) s = aVal a1 s + aVal a2 s aVal (Mult a1 a2) s = aVal a1 s * aVal a2 s aVal (Sub a1 a2) s = aVal a1 s - aVal a2 s bVal :: Bexp -> State -> T bVal TRUE _ = True bVal FALSE _ = False bVal (Eq a1 a2) s = aVal a1 s == aVal a2 s -- equivalent but smaller bVal (Le a1 a2) s = aVal a1 s <= aVal a2 s -- equivalent but smaller bVal (Neg b) s = not(bVal b s) -- equivalent but smaller bVal (And b1 b2) s = bVal b1 s && bVal b2 s -- equivalent but smaller
HaritzPuerto/SemanticsforWhileLanguage
Proc/Proc.hs
mit
2,662
14
15
947
750
404
346
59
1
{-# LANGUAGE OverloadedStrings #-} module Text.CSS.Shorthand.Background ( Background (..) , Repeat (..) , Attachment (..) , parseBackground , backgroundParser ) where import Text.CSS.Shorthand.Utility import Data.Attoparsec.Text import qualified Data.Attoparsec.Text.Lazy as AL import Prelude hiding (takeWhile) import Control.Applicative import Data.Char import Data.Text (unpack) import Data.Text.Lazy as L (Text) import Data.Text as T (Text, length) import Data.Foldable data Background = Background {getColor :: Maybe Color, getImage :: Maybe Image, getRepeat :: Maybe Repeat, getAttachment :: Maybe Attachment, getPosition :: Maybe Position} | InheritBackground deriving (Eq, Show, Ord) data Repeat = Repeat | RepeatX | RepeatY | NoRepeat | InheritRepeat deriving (Eq, Show, Ord) data Attachment = Scroll | Fixed | InheritAttachment deriving (Eq, Show, Ord) instance Value Repeat instance Value Attachment parseBackground :: L.Text -> Maybe Background parseBackground s = AL.maybeResult $ AL.parse backgroundParser s backgroundParser :: Parser Background backgroundParser = inherit <|> longhand where inherit = do symbol "inherit" endOfInput return InheritBackground longhand = do color' <- maybeTry color skipSpace image <- maybeTry bgImage skipSpace repeat' <- maybeTry bgRepeat skipSpace attachment <- maybeTry bgAttachment skipSpace position <- maybeTry bgPosition return $ Background color' image repeat' attachment position -- -- Images -- bgImage :: Parser Image bgImage = imageUrl <|> symbols [("none", NoneImage), ("inherit", InheritImage)] -- -- Repeat -- bgRepeat :: Parser Repeat bgRepeat = symbols [ ("repeat-x", RepeatX) , ("repeat-y", RepeatY) , ("no-repeat", NoRepeat) , ("repeat", Repeat) , ("inherit", InheritRepeat)] -- -- Attachment -- bgAttachment :: Parser Attachment bgAttachment = symbols [ ("scroll", Scroll) , ("fixed", Fixed) , ("inherit", InheritAttachment)] -- -- Position -- bgPosition :: Parser Position bgPosition = points <|> inherit where points = do h <- asum $ (literalMap <$> hKeywords) ++ [percentParser' HPercent, lengthParser' HLength] v <- maybeTry . asum $ (literalMap <$> vKeywords) ++ [percentParser' VPercent, lengthParser' VLength] return $ Position (h, v) inherit = literalMap ("inherit", InheritPosition) percentParser' t = t <$> percentParser lengthParser' t = t <$> lengthParser hKeywords = [ ("left", LeftPoint) , ("right", RightPoint) , ("center", HCenterPoint)] vKeywords = [ ("top", TopPoint) , ("bottom", BottomPoint) , ("center", VCenterPoint)]
zmoazeni/csscss-haskell
src/Text/CSS/Shorthand/Background.hs
mit
3,065
0
13
894
798
453
345
75
1
module Presenter.Source ( SourceCommand(..) ) where import Model.SourceInfo data SourceCommand = SetMainSource SourceInfo deriving Show
jvilar/hrows
lib/Presenter/Source.hs
gpl-2.0
165
0
6
44
32
20
12
5
0
-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca) -- Copyright (C) 2014, 2015 Julia Longtin (julial@turinglace.com) -- Released under the GNU GPL, see LICENSE {-# LANGUAGE OverloadedStrings #-} module Graphics.Implicit.Export.TriangleMeshFormats where import Graphics.Implicit.Definitions import Graphics.Implicit.Export.TextBuilderUtils import Blaze.ByteString.Builder hiding (Builder) import Data.ByteString (replicate) import Data.ByteString.Lazy (ByteString) import Data.Storable.Endian import Prelude hiding (replicate) import Data.VectorSpace import Data.Cross hiding (normal) normal :: (ℝ3,ℝ3,ℝ3) -> ℝ3 normal (a,b,c) = normalized $ (b + negateV a) `cross3` (c + negateV a) stl :: [Triangle] -> Text stl triangles = toLazyText $ stlHeader <> mconcat (map triangle triangles) <> stlFooter where stlHeader = "solid ImplictCADExport\n" stlFooter = "endsolid ImplictCADExport\n" vector :: ℝ3 -> Builder vector (x,y,z) = bf x <> " " <> bf y <> " " <> bf z vertex :: ℝ3 -> Builder vertex v = "vertex " <> vector v triangle :: (ℝ3, ℝ3, ℝ3) -> Builder triangle (a,b,c) = "facet normal " <> vector (normal (a,b,c)) <> "\n" <> "outer loop\n" <> vertex a <> "\n" <> vertex b <> "\n" <> vertex c <> "\nendloop\nendfacet\n" -- Write a 32-bit little-endian float to a buffer. -- convert Floats and Doubles to Float. toFloat = realToFrac :: (Real a) => a -> Float float32LE :: Float -> Write float32LE = writeStorable . LE binaryStl :: [Triangle] -> ByteString binaryStl triangles = toLazyByteString $ header <> lengthField <> mconcat (map triangle triangles) where header = fromByteString $ replicate 80 0 lengthField = fromWord32le $ toEnum $ length triangles triangle (a,b,c) = normalV (a,b,c) <> point a <> point b <> point c <> fromWord16le 0 point (x,y,z) = fromWrite $ float32LE (toFloat x) <> float32LE (toFloat y) <> float32LE (toFloat z) normalV ps = let (x,y,z) = normal ps in fromWrite $ float32LE (toFloat x) <> float32LE (toFloat y) <> float32LE (toFloat z) jsTHREE :: TriangleMesh -> Text jsTHREE triangles = toLazyText $ header <> vertcode <> facecode <> footer where -- some dense JS. Let's make helper functions so that we don't repeat code each line header = mconcat [ "var Shape = function(){\n" ,"var s = this;\n" ,"THREE.Geometry.call(this);\n" ,"function vec(x,y,z){return new THREE.Vector3(x,y,z);}\n" ,"function v(x,y,z){s.vertices.push(vec(x,y,z));}\n" ,"function f(a,b,c){" ,"s.faces.push(new THREE.Face3(a,b,c));" ,"}\n" ] footer = mconcat [ "}\n" ,"Shape.prototype = new THREE.Geometry();\n" ,"Shape.prototype.constructor = Shape;\n" ] -- A vertex line; v (0.0, 0.0, 1.0) = "v(0.0,0.0,1.0);\n" v :: ℝ3 -> Builder v (x,y,z) = "v(" <> bf x <> "," <> bf y <> "," <> bf z <> ");\n" -- A face line f :: Int -> Int -> Int -> Builder f posa posb posc = "f(" <> buildInt posa <> "," <> buildInt posb <> "," <> buildInt posc <> ");" verts = do -- extract the vertices for each triangle -- recall that a normed triangle is of the form ((vert, norm), ...) (a,b,c) <- triangles -- The vertices from each triangle take up 3 position in the resulting list [a,b,c] vertcode = mconcat $ map v verts facecode = mconcat $ do (n,_) <- zip [0, 3 ..] triangles let (posa, posb, posc) = (n, n+1, n+2) return $ f posa posb posc
silky/ImplicitCAD
Graphics/Implicit/Export/TriangleMeshFormats.hs
gpl-2.0
4,241
0
19
1,489
1,024
554
470
70
1
-- | Formats Haskell source code using mIRC codes. -- (see http:\/\/irssi.org\/documentation\/formats) module Language.Haskell.HsColour.MIRC (hscolour) where {-@ LIQUID "--totality" @-} import Language.Haskell.HsColour.Classify as Classify import Language.Haskell.HsColour.Colourise import Data.Char(isAlphaNum) -- | Formats Haskell source code using mIRC codes. hscolour :: ColourPrefs -- ^ Colour preferences. -> String -- ^ Haskell source code. -> String -- ^ Coloured Haskell source code. hscolour pref = concatMap (renderToken pref) . tokenise renderToken :: ColourPrefs -> (TokenType,String) -> String renderToken pref (t,s) = fontify (colourise pref t) s -- mIRC stuff fontify hs = mircColours (joinColours hs) . highlight (filterElts [Normal,Bold,Underscore,ReverseVideo] hs) where highlight [] s = s highlight (h:hs) s = font h (highlight hs s) font Normal s = s font Bold s = '\^B':s++"\^B" font Underscore s = '\^_':s++"\^_" font ReverseVideo s = '\^V':s++"\^V" {-@ qualif IsFont(v: Highlight): (isFont v) @-} {-@ measure isFont :: Highlight -> Prop isFont(Normal) = true isFont(Bold) = true isFont(Underscore) = true isFont(ReverseVideo) = true isFont(Dim) = false isFont(Blink) = false isFont(Italic) = false isFont(Concealed) = false isFont(Background x) = false isFont(Foreground x) = false @-} {-@ filterElts :: forall <p :: a -> Prop>. Eq a => [a<p>] -> [a] -> [a<p>] @-} filterElts :: Eq a => [a] -> [a] -> [a] filterElts xs ys = go xs xs ys {-@ go :: forall <p :: a -> Prop>. Eq a => xs:[a<p>] -> ws:[a<p>] -> zs:[a] -> [a<p>] /[(len zs), (len ws)] @-} go :: Eq a => [a] -> [a] -> [a] -> [a] go xs (w:ws) (z:zs) | w == z = z : go xs xs zs | otherwise = go xs ws (z:zs) go xs [] (z:zs) = go xs xs zs go xs ws [] = [] -- mIRC combines colour codes in a non-modular way data MircColour = Mirc { fg::Colour, dim::Bool, bg::Maybe Colour, blink::Bool} joinColours :: [Highlight] -> MircColour joinColours = foldr join (Mirc {fg=Black, dim=False, bg=Nothing, blink=False}) where join Blink mirc = mirc {blink=True} join Dim mirc = mirc {dim=True} join (Foreground fg) mirc = mirc {fg=fg} join (Background bg) mirc = mirc {bg=Just bg} join Concealed mirc = mirc {fg=Black, bg=Just Black} join _ mirc = mirc mircColours :: MircColour -> String -> String mircColours (Mirc fg dim Nothing blink) s = '\^C': code fg dim++s++"\^O" mircColours (Mirc fg dim (Just bg) blink) s = '\^C': code fg dim++',' : code bg blink++s++"\^O" {-@ code :: c:Colour -> Bool -> String / [ 1 - (isBasic c)] @-} code :: Colour -> Bool -> String code Black False = "1" code Red False = "5" code Green False = "3" code Yellow False = "7" code Blue False = "2" code Magenta False = "6" code Cyan False = "10" code White False = "0" code Black True = "14" code Red True = "4" code Green True = "9" code Yellow True = "8" code Blue True = "12" code Magenta True = "13" code Cyan True = "11" code White True = "15" code c@(Rgb _ _ _) b = code (projectToBasicColour8 c) b
nikivazou/hscolour
Language/Haskell/HsColour/MIRC.hs
gpl-2.0
3,324
0
10
885
1,013
540
473
57
6
{- Copyright 2010 John Morrice This source file is part of The Obelisk Programming Language and is distributed under the terms of the GNU General Public License This file is part of The Obelisk Programming Language. The Obelisk Programming Language is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. The Obelisk Programming Language 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 The Obelisk Programming Language. If not, see <http://www.gnu.org/licenses/> -} -- | Perform lexical analysis on Obelisk source module Language.Obelisk.Lexer where import Language.Obelisk.AST.Simple import Language.Obelisk.Parser.Monad import Language.Obelisk.Lexer.Token import Error.Report import Text.Parsec.Token as T import Text.Parsec.Language import Text.Parsec.String import Text.Parsec import Data.Either import Data.Char import Debug.Trace -- | Obelisk language definition obdef :: LanguageDef st obdef = LanguageDef {commentStart = "/*" ,commentEnd = "*/" ,commentLine = "//" ,nestedComments = False ,identStart = lower ,identLetter = alphaNum <|> oneOf "_?" ,opStart = oneOf ":!#$%&*+/<=>@\\^|-~" ,opLetter = oneOf ":!#$%&*+/<=>@\\^|-~" ,reservedNames = ["def", "if", "true", "false", "where", "let"] ,reservedOpNames = ["->"] ,caseSensitive = True} -- | Obelisk token parser obtok :: TokenParser st obtok = makeTokenParser obdef -- | Parse a class name class_name :: Parser Token class_name = do fst <- upper rst <- many alphaNum return $ TClassName $ fst : rst -- | Parse the close brace bra_close :: Parser Token bra_close = char '}' >> return TBraceClose -- Ooo err matron -- | Parse the open brace bra_open :: Parser Token bra_open = char '{' >> return TBraceOpen -- | Parse the open parenthesis par_open :: Parser Token par_open = do char '(' return TParOpen -- | Parse the close parenthesis par_close :: Parser Token par_close = do char ')' return TParClose -- | A period period :: Parser Token period = do char '.' return TPeriod chomp :: String -> String chomp = reverse . chomp_front . reverse . chomp_front where chomp_front = dropWhile isSpace -- | Take obelisk source and return a list of tokens or an error. ob_lex :: FilePath -> String -> Either ParseError [Token] ob_lex fp str = parse plex fp $ chomp str where plex = do ts <- many $ T.whiteSpace obtok >> tlex T.whiteSpace obtok eof return $ ts ++ [TEOF] -- | There was a lexical error lexical_error :: CodeFragment -> String -> String lexical_error fr s = '\n' : show fr ++ "\n\tThere was a lexical error near: " ++ show s -- | Lexical analyzer for parsers generated by Happy lex :: (Token -> OParser a) -> OParser a lex cont = OParser $ \i report -> either (\err -> either (const $ ParseFail $ lexical_error report $ takeWhile (not . isSpace) $ dropWhile isSpace i) (const $ continue TEOF i report) (parse (T.whiteSpace obtok >> eof) "" i)) (\(t, f, r) -> continue t r f) (parse (ilex $ pos report) "" i) where continue t r p = let OParser crf = cont t in crf r p ilex s = do setPosition s T.whiteSpace obtok cod <- fmap (unlines . take 1 . lines) getInput t <- tlex p <- getPosition i <- getInput return $ (t, CodeFragment p cod, i) -- | Parse a token with parsec tlex :: Parser Token tlex = try (fmap TInt (T.decimal obtok)) <|> try (T.reserved obtok "true" >> return TTrue) <|> try (T.reserved obtok "false" >> return TFalse) <|> try (T.reserved obtok "def" >> return TDef) <|> try (T.reserved obtok "if" >> return TIf) <|> try (T.reserved obtok "where" >> return TWhere) <|> try (T.reserved obtok "let" >> return TConstant) <|> try (T.reservedOp obtok "->" >> return TArrow) <|> try class_name <|> try par_open <|> try par_close <|> try bra_open <|> try bra_close <|> try (fmap TVar (T.identifier obtok)) <|> try (fmap TOp (T.operator obtok)) <|> try period <|> fmap TChar (T.charLiteral obtok)
elginer/Obelisk
Language/Obelisk/Lexer.hs
gpl-3.0
4,573
0
26
1,096
1,169
593
576
101
1
module Haskore.Interface.Braille.Utilities (makeDotsType) where import Data.Bits (testBit) import Language.Haskell.TH (Q, Dec(DataD), Con(NormalC), mkName) ctorNames :: [String] ctorNames = "NoDots" : map ctorName [1..255] where ctorName :: Int -> String ctorName = (++) "Dot" . concatMap (show . succ) . flip filter [0..7] . testBit makeDotsType :: String -> Q [Dec] makeDotsType n = do let ctors = map (flip NormalC [] . mkName) (take 64 ctorNames) let instances = map mkName ["Bounded", "Enum", "Eq", "Read", "Show"] return [DataD [] (mkName n) [] ctors instances]
mlang/haskore-braille
src/Haskore/Interface/Braille/Utilities.hs
gpl-3.0
581
0
14
97
249
136
113
12
1
module Leaf.String ( strip ) where import Data.List (dropWhileEnd) strip :: String -> String strip = dropWhile pred . dropWhileEnd pred where pred = (==' ')
phaazon/leaf
src/Leaf/String.hs
gpl-3.0
165
0
7
34
56
32
24
6
1
{- Perceptron 1. For every input, multiply that input by its weight. 2. Sum all of the weighted inputs. 3. Comput the output of the perceptron based on that sum passed through an activation function. -} {-# LANGUAGE GADTs #-} {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE RankNTypes #-} import System.Random data PerceptronF i w o where PerceptronF :: { weighInput :: i -> w -> wi -- function that applies to an input and a weight , sumInputs :: [b] -> c -- function that aggregates all weighted inputs , activation :: c -> o -- function that turns the summed inputs into the output } -> PerceptronF i w o data Perceptron i w o = Perceptron (PerceptronF i w o) [w] type BasicPerceptronF a = Num a => PerceptronF a a a type BasicPerceptron a = Num a => Perceptron a a a basicPerceptronF :: BasicPerceptronF a basicPerceptronF = PerceptronF { weighInput = (*) , sumInputs = sum , activation = signum } basicPerceptronFromWeights :: [a] -> BasicPerceptron a basicPerceptronFromWeights = Perceptron basicPerceptronF randomWeights :: Random w => (w, w) -> IO [w] randomWeights range = randomRs range <$> getStdGen randomPerceptron :: Random w => (w, w) -> PerceptronF i w o -> IO (Perceptron i w o) randomPerceptron range perceptronF = Perceptron perceptronF <$> randomWeights range -- FIXME: Not working. Impredicative types. randomBasicPerceptron :: Random a => IO (BasicPerceptron a) randomBasicPerceptron = basicPerceptronFromWeights <$> randomWeights (-1, 1)
KenetJervet/mapensee
haskell/neural-network/Perceptron.hs
gpl-3.0
1,658
0
10
436
350
194
156
24
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.YouTube.PlayListItems.Update -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Modifies a playlist item. For example, you could update the item\'s -- position in the playlist. -- -- /See:/ <https://developers.google.com/youtube/v3 YouTube Data API Reference> for @youtube.playlistItems.update@. module Network.Google.Resource.YouTube.PlayListItems.Update ( -- * REST Resource PlayListItemsUpdateResource -- * Creating a Request , playListItemsUpdate , PlayListItemsUpdate -- * Request Lenses , pliuPart , pliuPayload , pliuOnBehalfOfContentOwner ) where import Network.Google.Prelude import Network.Google.YouTube.Types -- | A resource alias for @youtube.playlistItems.update@ method which the -- 'PlayListItemsUpdate' request conforms to. type PlayListItemsUpdateResource = "youtube" :> "v3" :> "playlistItems" :> QueryParam "part" Text :> QueryParam "onBehalfOfContentOwner" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] PlayListItem :> Put '[JSON] PlayListItem -- | Modifies a playlist item. For example, you could update the item\'s -- position in the playlist. -- -- /See:/ 'playListItemsUpdate' smart constructor. data PlayListItemsUpdate = PlayListItemsUpdate' { _pliuPart :: !Text , _pliuPayload :: !PlayListItem , _pliuOnBehalfOfContentOwner :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'PlayListItemsUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pliuPart' -- -- * 'pliuPayload' -- -- * 'pliuOnBehalfOfContentOwner' playListItemsUpdate :: Text -- ^ 'pliuPart' -> PlayListItem -- ^ 'pliuPayload' -> PlayListItemsUpdate playListItemsUpdate pPliuPart_ pPliuPayload_ = PlayListItemsUpdate' { _pliuPart = pPliuPart_ , _pliuPayload = pPliuPayload_ , _pliuOnBehalfOfContentOwner = Nothing } -- | The part parameter serves two purposes in this operation. It identifies -- the properties that the write operation will set as well as the -- properties that the API response will include. Note that this method -- will override the existing values for all of the mutable properties that -- are contained in any parts that the parameter value specifies. For -- example, a playlist item can specify a start time and end time, which -- identify the times portion of the video that should play when users -- watch the video in the playlist. If your request is updating a playlist -- item that sets these values, and the request\'s part parameter value -- includes the contentDetails part, the playlist item\'s start and end -- times will be updated to whatever value the request body specifies. If -- the request body does not specify values, the existing start and end -- times will be removed and replaced with the default settings. pliuPart :: Lens' PlayListItemsUpdate Text pliuPart = lens _pliuPart (\ s a -> s{_pliuPart = a}) -- | Multipart request metadata. pliuPayload :: Lens' PlayListItemsUpdate PlayListItem pliuPayload = lens _pliuPayload (\ s a -> s{_pliuPayload = a}) -- | Note: This parameter is intended exclusively for YouTube content -- partners. The onBehalfOfContentOwner parameter indicates that the -- request\'s authorization credentials identify a YouTube CMS user who is -- acting on behalf of the content owner specified in the parameter value. -- This parameter is intended for YouTube content partners that own and -- manage many different YouTube channels. It allows content owners to -- authenticate once and get access to all their video and channel data, -- without having to provide authentication credentials for each individual -- channel. The CMS account that the user authenticates with must be linked -- to the specified YouTube content owner. pliuOnBehalfOfContentOwner :: Lens' PlayListItemsUpdate (Maybe Text) pliuOnBehalfOfContentOwner = lens _pliuOnBehalfOfContentOwner (\ s a -> s{_pliuOnBehalfOfContentOwner = a}) instance GoogleRequest PlayListItemsUpdate where type Rs PlayListItemsUpdate = PlayListItem type Scopes PlayListItemsUpdate = '["https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtubepartner"] requestClient PlayListItemsUpdate'{..} = go (Just _pliuPart) _pliuOnBehalfOfContentOwner (Just AltJSON) _pliuPayload youTubeService where go = buildClient (Proxy :: Proxy PlayListItemsUpdateResource) mempty
rueshyna/gogol
gogol-youtube/gen/Network/Google/Resource/YouTube/PlayListItems/Update.hs
mpl-2.0
5,527
0
14
1,178
497
305
192
75
1
{- | Module : Data.Convertible.Instances.Num Copyright : Copyright (C) 2009 John Goerzen License : LGPL Maintainer : John Goerzen <jgoerzen@complete.org> Stability : provisional Portability: portable Numeric instances for Convertible. Copyright (C) 2009 John Goerzen <jgoerzen@complete.org> All rights reserved. For license and copyright information, see the file COPYRIGHT These instances perform conversion between numeric types such as Double, Int, Integer, Rational, and the like. Here are some notes about the conversion process: Conversions from floating-point types such as Double to integral types are dune via the 'truncate' function. This is a somewhat arbitrary decision; if you need different behavior, you will have to write your own instance or manually perform the conversion. All conversions perform bounds checking. If a value is too large for its destination type, you will get a 'ConvertError' informing you of this. Note that this behavior differs from functions in the Haskell standard libraries, which will perform the conversion without error, but give you garbage in the end. Conversions do not perform precision checking; loss of precision is implied with certain conversions (for instance, Double to Float) and this is not an error. -} module Data.Convertible.Instances.Num() where import Data.Convertible.Base import Data.Convertible.Utils import Data.Int import Data.Word ------------------------------------------------------------ instance ConvertSuccess Integer Integer where convertSuccess = id instance ConvertAttempt Integer Integer where convertAttempt = return instance ConvertSuccess Char Integer where convertSuccess = fromIntegral . fromEnum instance ConvertAttempt Char Integer where convertAttempt = return . convertSuccess {- The following instances generated by util/genNumInstances.hs -} instance ConvertAttempt Integer Int where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int Integer where convertAttempt = return . fromIntegral instance ConvertSuccess Int Integer where convertSuccess = fromIntegral instance ConvertAttempt Integer Int8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int8 Integer where convertAttempt = return . fromIntegral instance ConvertSuccess Int8 Integer where convertSuccess = fromIntegral instance ConvertAttempt Integer Int16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int16 Integer where convertAttempt = return . fromIntegral instance ConvertSuccess Int16 Integer where convertSuccess = fromIntegral instance ConvertAttempt Integer Int32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int32 Integer where convertAttempt = return . fromIntegral instance ConvertSuccess Int32 Integer where convertSuccess = fromIntegral instance ConvertAttempt Integer Int64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int64 Integer where convertAttempt = return . fromIntegral instance ConvertSuccess Int64 Integer where convertSuccess = fromIntegral instance ConvertAttempt Integer Word where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word Integer where convertAttempt = return . fromIntegral instance ConvertSuccess Word Integer where convertSuccess = fromIntegral instance ConvertAttempt Integer Word8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word8 Integer where convertAttempt = return . fromIntegral instance ConvertSuccess Word8 Integer where convertSuccess = fromIntegral instance ConvertAttempt Integer Word16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word16 Integer where convertAttempt = return . fromIntegral instance ConvertSuccess Word16 Integer where convertSuccess = fromIntegral instance ConvertAttempt Integer Word32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word32 Integer where convertAttempt = return . fromIntegral instance ConvertSuccess Word32 Integer where convertSuccess = fromIntegral instance ConvertAttempt Integer Word64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word64 Integer where convertAttempt = return . fromIntegral instance ConvertSuccess Word64 Integer where convertSuccess = fromIntegral instance ConvertAttempt Int Int8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int Int16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int Int32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int Int64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int Word where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int Word8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int Word16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int Word32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int Word64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int8 Int where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int8 Int16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int8 Int32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int8 Int64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int8 Word where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int8 Word8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int8 Word16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int8 Word32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int8 Word64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int16 Int where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int16 Int8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int16 Int32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int16 Int64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int16 Word where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int16 Word8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int16 Word16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int16 Word32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int16 Word64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int32 Int where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int32 Int8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int32 Int16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int32 Int64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int32 Word where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int32 Word8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int32 Word16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int32 Word32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int32 Word64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int64 Int where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int64 Int8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int64 Int16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int64 Int32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int64 Word where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int64 Word8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int64 Word16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int64 Word32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Int64 Word64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word Int where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word Int8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word Int16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word Int32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word Int64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word Word8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word Word16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word Word32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word Word64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word8 Int where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word8 Int8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word8 Int16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word8 Int32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word8 Int64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word8 Word where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word8 Word16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word8 Word32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word8 Word64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word16 Int where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word16 Int8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word16 Int16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word16 Int32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word16 Int64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word16 Word where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word16 Word8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word16 Word32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word16 Word64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word32 Int where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word32 Int8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word32 Int16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word32 Int32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word32 Int64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word32 Word where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word32 Word8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word32 Word16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word32 Word64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word64 Int where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word64 Int8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word64 Int16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word64 Int32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word64 Int64 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word64 Word where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word64 Word8 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word64 Word16 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertAttempt Word64 Word32 where convertAttempt = boundedConversion (return . fromIntegral) instance ConvertSuccess Integer Double where convertSuccess = fromIntegral instance ConvertAttempt Integer Double where convertAttempt = return . fromIntegral instance ConvertSuccess Double Integer where convertSuccess = truncate instance ConvertAttempt Double Integer where convertAttempt = return . truncate instance ConvertSuccess Integer Float where convertSuccess = fromIntegral instance ConvertAttempt Integer Float where convertAttempt = return . fromIntegral instance ConvertSuccess Float Integer where convertSuccess = truncate instance ConvertAttempt Float Integer where convertAttempt = return . truncate instance ConvertSuccess Integer Rational where convertSuccess = fromIntegral instance ConvertAttempt Integer Rational where convertAttempt = return . fromIntegral instance ConvertSuccess Rational Integer where convertSuccess = truncate instance ConvertAttempt Rational Integer where convertAttempt = return . truncate instance ConvertAttempt Double Int where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Int Double where convertSuccess = fromIntegral instance ConvertAttempt Int Double where convertAttempt = return . fromIntegral instance ConvertAttempt Double Int8 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Int8 Double where convertSuccess = fromIntegral instance ConvertAttempt Int8 Double where convertAttempt = return . fromIntegral instance ConvertAttempt Double Int16 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Int16 Double where convertSuccess = fromIntegral instance ConvertAttempt Int16 Double where convertAttempt = return . fromIntegral instance ConvertAttempt Double Int32 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Int32 Double where convertSuccess = fromIntegral instance ConvertAttempt Int32 Double where convertAttempt = return . fromIntegral instance ConvertAttempt Double Int64 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Int64 Double where convertSuccess = fromIntegral instance ConvertAttempt Int64 Double where convertAttempt = return . fromIntegral instance ConvertAttempt Double Word where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Word Double where convertSuccess = fromIntegral instance ConvertAttempt Word Double where convertAttempt = return . fromIntegral instance ConvertAttempt Double Word8 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Word8 Double where convertSuccess = fromIntegral instance ConvertAttempt Word8 Double where convertAttempt = return . fromIntegral instance ConvertAttempt Double Word16 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Word16 Double where convertSuccess = fromIntegral instance ConvertAttempt Word16 Double where convertAttempt = return . fromIntegral instance ConvertAttempt Double Word32 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Word32 Double where convertSuccess = fromIntegral instance ConvertAttempt Word32 Double where convertAttempt = return . fromIntegral instance ConvertAttempt Double Word64 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Word64 Double where convertSuccess = fromIntegral instance ConvertAttempt Word64 Double where convertAttempt = return . fromIntegral instance ConvertAttempt Float Int where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Int Float where convertSuccess = fromIntegral instance ConvertAttempt Int Float where convertAttempt = return . fromIntegral instance ConvertAttempt Float Int8 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Int8 Float where convertSuccess = fromIntegral instance ConvertAttempt Int8 Float where convertAttempt = return . fromIntegral instance ConvertAttempt Float Int16 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Int16 Float where convertSuccess = fromIntegral instance ConvertAttempt Int16 Float where convertAttempt = return . fromIntegral instance ConvertAttempt Float Int32 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Int32 Float where convertSuccess = fromIntegral instance ConvertAttempt Int32 Float where convertAttempt = return . fromIntegral instance ConvertAttempt Float Int64 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Int64 Float where convertSuccess = fromIntegral instance ConvertAttempt Int64 Float where convertAttempt = return . fromIntegral instance ConvertAttempt Float Word where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Word Float where convertSuccess = fromIntegral instance ConvertAttempt Word Float where convertAttempt = return . fromIntegral instance ConvertAttempt Float Word8 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Word8 Float where convertSuccess = fromIntegral instance ConvertAttempt Word8 Float where convertAttempt = return . fromIntegral instance ConvertAttempt Float Word16 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Word16 Float where convertSuccess = fromIntegral instance ConvertAttempt Word16 Float where convertAttempt = return . fromIntegral instance ConvertAttempt Float Word32 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Word32 Float where convertSuccess = fromIntegral instance ConvertAttempt Word32 Float where convertAttempt = return . fromIntegral instance ConvertAttempt Float Word64 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Word64 Float where convertSuccess = fromIntegral instance ConvertAttempt Word64 Float where convertAttempt = return . fromIntegral instance ConvertAttempt Rational Int where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Int Rational where convertSuccess = fromIntegral instance ConvertAttempt Int Rational where convertAttempt = return . fromIntegral instance ConvertAttempt Rational Int8 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Int8 Rational where convertSuccess = fromIntegral instance ConvertAttempt Int8 Rational where convertAttempt = return . fromIntegral instance ConvertAttempt Rational Int16 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Int16 Rational where convertSuccess = fromIntegral instance ConvertAttempt Int16 Rational where convertAttempt = return . fromIntegral instance ConvertAttempt Rational Int32 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Int32 Rational where convertSuccess = fromIntegral instance ConvertAttempt Int32 Rational where convertAttempt = return . fromIntegral instance ConvertAttempt Rational Int64 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Int64 Rational where convertSuccess = fromIntegral instance ConvertAttempt Int64 Rational where convertAttempt = return . fromIntegral instance ConvertAttempt Rational Word where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Word Rational where convertSuccess = fromIntegral instance ConvertAttempt Word Rational where convertAttempt = return . fromIntegral instance ConvertAttempt Rational Word8 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Word8 Rational where convertSuccess = fromIntegral instance ConvertAttempt Word8 Rational where convertAttempt = return . fromIntegral instance ConvertAttempt Rational Word16 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Word16 Rational where convertSuccess = fromIntegral instance ConvertAttempt Word16 Rational where convertAttempt = return . fromIntegral instance ConvertAttempt Rational Word32 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Word32 Rational where convertSuccess = fromIntegral instance ConvertAttempt Word32 Rational where convertAttempt = return . fromIntegral instance ConvertAttempt Rational Word64 where convertAttempt = boundedConversion (return . truncate) instance ConvertSuccess Word64 Rational where convertSuccess = fromIntegral instance ConvertAttempt Word64 Rational where convertAttempt = return . fromIntegral instance ConvertSuccess Double Float where convertSuccess = realToFrac instance ConvertAttempt Double Float where convertAttempt = return . realToFrac instance ConvertSuccess Double Rational where convertSuccess = toRational instance ConvertAttempt Double Rational where convertAttempt = return . toRational instance ConvertSuccess Float Double where convertSuccess = realToFrac instance ConvertAttempt Float Double where convertAttempt = return . realToFrac instance ConvertSuccess Float Rational where convertSuccess = toRational instance ConvertAttempt Float Rational where convertAttempt = return . toRational instance ConvertSuccess Rational Double where convertSuccess = realToFrac instance ConvertAttempt Rational Double where convertAttempt = return . realToFrac instance ConvertSuccess Rational Float where convertSuccess = realToFrac instance ConvertAttempt Rational Float where convertAttempt = return . realToFrac instance ConvertAttempt Char Int where convertAttempt = boundedConversion (return . fromIntegral . fromEnum) instance ConvertAttempt Int Char where convertAttempt = boundedConversion (return . toEnum . fromIntegral) instance ConvertAttempt Char Int8 where convertAttempt = boundedConversion (return . fromIntegral . fromEnum) instance ConvertAttempt Int8 Char where convertAttempt = boundedConversion (return . toEnum . fromIntegral) instance ConvertAttempt Char Int16 where convertAttempt = boundedConversion (return . fromIntegral . fromEnum) instance ConvertAttempt Int16 Char where convertAttempt = boundedConversion (return . toEnum . fromIntegral) instance ConvertAttempt Char Int32 where convertAttempt = boundedConversion (return . fromIntegral . fromEnum) instance ConvertAttempt Int32 Char where convertAttempt = boundedConversion (return . toEnum . fromIntegral) instance ConvertAttempt Char Int64 where convertAttempt = boundedConversion (return . fromIntegral . fromEnum) instance ConvertAttempt Int64 Char where convertAttempt = boundedConversion (return . toEnum . fromIntegral) instance ConvertAttempt Char Word where convertAttempt = boundedConversion (return . fromIntegral . fromEnum) instance ConvertAttempt Word Char where convertAttempt = boundedConversion (return . toEnum . fromIntegral) instance ConvertAttempt Char Word8 where convertAttempt = boundedConversion (return . fromIntegral . fromEnum) instance ConvertAttempt Word8 Char where convertAttempt = boundedConversion (return . toEnum . fromIntegral) instance ConvertAttempt Char Word16 where convertAttempt = boundedConversion (return . fromIntegral . fromEnum) instance ConvertAttempt Word16 Char where convertAttempt = boundedConversion (return . toEnum . fromIntegral) instance ConvertAttempt Char Word32 where convertAttempt = boundedConversion (return . fromIntegral . fromEnum) instance ConvertAttempt Word32 Char where convertAttempt = boundedConversion (return . toEnum . fromIntegral) instance ConvertAttempt Char Word64 where convertAttempt = boundedConversion (return . fromIntegral . fromEnum) instance ConvertAttempt Word64 Char where convertAttempt = boundedConversion (return . toEnum . fromIntegral)
snoyberg/convertible
Data/Convertible/Instances/Num.hs
lgpl-2.1
26,399
0
9
4,098
5,702
2,987
2,715
-1
-1
{-# LANGUAGE UnicodeSyntax #-} module TestCommon ( xml , json , def , documentRoot , parseLBS ) where import Language.Haskell.TH.Quote import Text.RawString.QQ import Text.XML.Lens (documentRoot) import Text.HTML.DOM import Data.Aeson.QQ import Data.Default -- renames for vim xml, json ∷ QuasiQuoter xml = r json = aesonQQ
myfreeweb/microformats2-parser
test-suite/TestCommon.hs
unlicense
391
0
5
110
81
54
27
16
1
fibNextPair :: (Integer, Integer) -> (Integer, Integer) fibNextPair (x, y) = (y, x + y) fibNthPair :: Integer -> (Integer, Integer) fibNthPair 1 = (1, 1) fibNthPair n = fibNextPair (fibNthPair (n - 1)) fib :: Integer -> Integer fib = fst . fibNthPair
fbartnitzek/notes
7_languages/Haskell/fib_pair.hs
apache-2.0
252
0
9
45
117
66
51
7
1
module Braxton.A282167Spec (main, spec) where import Test.Hspec import Braxton.A282167 (a282167) main :: IO () main = hspec spec spec :: Spec spec = describe "A282167" $ it "correctly computes the first 5 elements" $ take 5 (map a282167 [1..]) `shouldBe` expectedValue where expectedValue = [1,3,6,7,11]
peterokagey/haskellOEIS
test/Braxton/A282167Spec.hs
apache-2.0
318
0
10
59
115
65
50
10
1
module Language.K3.Codegen.CPP.Simplification ( simplifyCPP, ) where import Control.Applicative import Control.Monad.Identity import Control.Monad.State import Language.K3.Codegen.CPP.Representation type SimplificationS = () type SimplificationM = StateT SimplificationS Identity runSimplificationM :: SimplificationM a -> SimplificationS -> (a, SimplificationS) runSimplificationM s t = runIdentity $ runStateT s t simplifyCPP :: [Definition] -> [Definition] simplifyCPP ds = fst $ runSimplificationM (mapM simplifyCPPDefinition ds) () simplifyCPPExpression :: Expression -> SimplificationM Expression simplifyCPPExpression expr = case expr of Binary i x y -> Binary i <$> simplifyCPPExpression x <*> simplifyCPPExpression y Bind f vs 0 -> simplifyCPPExpression (Call f vs) Bind f vs n -> do f' <- simplifyCPPExpression f vs' <- mapM simplifyCPPExpression vs case f' of Bind f'' vs'' n' -> return (Bind f'' (vs'' ++ vs') n) _ -> return (Bind f' vs' n) Call f vs -> do f' <- simplifyCPPExpression f vs' <- mapM simplifyCPPExpression vs case f' of Bind f'' vs'' n | n == length vs' -> return (Call f'' (vs'' ++ vs')) _ -> return (Call f' vs') Dereference e -> Dereference <$> simplifyCPPExpression e TakeReference e -> TakeReference <$> simplifyCPPExpression e Initialization t es -> Initialization t <$> mapM simplifyCPPExpression es Lambda cs as m mrt bd -> Lambda cs as m mrt <$> mapM simplifyCPPStatement bd Literal lt -> return (Literal lt) Project e n -> Project <$> simplifyCPPExpression e <*> return n Subscript a x -> Subscript <$> simplifyCPPExpression a <*> simplifyCPPExpression x Unary i e -> Unary i <$> simplifyCPPExpression e Variable n -> return (Variable n) simplifyCPPDeclaration :: Declaration -> SimplificationM Declaration simplifyCPPDeclaration decl = case decl of ScalarDecl n Inferred (Just (Literal (LString s))) -> return $ ScalarDecl n Inferred (Just $ Initialization (Named $ Qualified (Name "K3") (Name "base_string")) [Literal $ LString s]) ScalarDecl n t (Just e) -> ScalarDecl n t . Just <$> simplifyCPPExpression e _ -> return decl simplifyCPPStatement :: Statement -> SimplificationM Statement simplifyCPPStatement stmt = case stmt of Assignment x y -> Assignment <$> simplifyCPPExpression x <*> simplifyCPPExpression y Block ss -> Block <$> mapM simplifyCPPStatement ss ForEach i t e s -> ForEach i t <$> simplifyCPPExpression e <*> simplifyCPPStatement s Forward d -> Forward <$> simplifyCPPDeclaration d IfThenElse p ts es -> IfThenElse <$> simplifyCPPExpression p <*> mapM simplifyCPPStatement ts <*> mapM simplifyCPPStatement es Ignore e -> Ignore <$> simplifyCPPExpression e Pragma s -> return (Pragma s) Return e -> Return <$> simplifyCPPExpression e simplifyCPPDefinition :: Definition -> SimplificationM Definition simplifyCPPDefinition defn = case defn of ClassDefn cn ts ps publics privates protecteds -> ClassDefn cn ts ps <$> mapM simplifyCPPDefinition publics <*> mapM simplifyCPPDefinition privates <*> mapM simplifyCPPDefinition protecteds FunctionDefn fn as mrt is c bd -> FunctionDefn fn as mrt is c <$> mapM simplifyCPPStatement bd GlobalDefn s -> GlobalDefn <$> simplifyCPPStatement s GuardedDefn i d -> GuardedDefn i <$> simplifyCPPDefinition d IncludeDefn i -> return (IncludeDefn i) NamespaceDefn i ds -> NamespaceDefn i <$> mapM simplifyCPPDefinition ds TemplateDefn is d -> TemplateDefn is <$> simplifyCPPDefinition d TypeDefn t i -> return $ TypeDefn t i
yliu120/K3
src/Language/K3/Codegen/CPP/Simplification.hs
apache-2.0
3,901
0
18
987
1,208
566
642
71
15
module Main where -- Libraries for hermit conversion import Life.Types import Life.Scenes import Life.Formations import Life.Reader import Life.Engine.HERMIT.HuttonA -- Target module for hermit -- Libraries for testing import Criterion.Main -- For performance tests import qualified Data.Array.Accelerate.CUDA as C -- Runs the Life (without display) for the specified number of generations life :: Int -> Config -> [Pos] -> Board life x c = (runLife x) . (scene c) -- QuickCheck test of source code engine vs. hermit converted engine --testHermit x c b = alive (life x c b) == alive (lifeAcc x c b) -- Tests conversion against original for correctness and performance main :: IO () main = do b <- parseLife "Life/test.txt" --print $ life 100 ((50,50),False) b defaultMain [ bench "Test" $ nf (board . life 100 ((50,50),False)) b]
ku-fpg/better-life
examples/HERMIT/HuttonEngineA.hs
bsd-2-clause
862
0
15
165
171
99
72
13
1
{-| Implementation of the iallocator interface. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.HTools.Backend.IAlloc ( readRequest , runIAllocator , processRelocate , loadData ) where import Data.Either () import Data.Maybe (fromMaybe, isJust, fromJust) import Data.List import Control.Monad import System.Time import Text.JSON (JSObject, JSValue(JSArray), makeObj, encodeStrict, decodeStrict, fromJSObject, showJSON) import Ganeti.BasicTypes import qualified Ganeti.HTools.Cluster as Cluster import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Group as Group import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Nic as Nic import qualified Ganeti.Constants as C import Ganeti.HTools.AlgorithmParams (AlgorithmOptions) import Ganeti.HTools.CLI import Ganeti.HTools.Loader import Ganeti.HTools.Types import Ganeti.JSON import Ganeti.Types (EvacMode(ChangePrimary, ChangeSecondary)) import Ganeti.Utils {-# ANN module "HLint: ignore Eta reduce" #-} -- | Type alias for the result of an IAllocator call. type IAllocResult = (String, JSValue, Node.List, Instance.List) -- | Parse a NIC within an instance (in a creation request) parseNic :: String -> JSRecord -> Result Nic.Nic parseNic n a = do mac <- maybeFromObj a "mac" ip <- maybeFromObj a "ip" mode <- maybeFromObj a "mode" >>= \m -> case m of Just "bridged" -> Ok $ Just Nic.Bridged Just "routed" -> Ok $ Just Nic.Routed Just "openvswitch" -> Ok $ Just Nic.OpenVSwitch Nothing -> Ok Nothing _ -> Bad $ "invalid NIC mode in instance " ++ n link <- maybeFromObj a "link" bridge <- maybeFromObj a "bridge" network <- maybeFromObj a "network" return (Nic.create mac ip mode link bridge network) -- | Parse the basic specifications of an instance. -- -- Instances in the cluster instance list and the instance in an -- 'Allocate' request share some common properties, which are read by -- this function. parseBaseInstance :: String -> JSRecord -> Result (String, Instance.Instance) parseBaseInstance n a = do let errorMessage = "invalid data for instance '" ++ n ++ "'" let extract x = tryFromObj errorMessage a x disk <- extract "disk_space_total" jsdisks <- extract "disks" >>= toArray >>= asObjectList dsizes <- mapM (flip (tryFromObj errorMessage) "size" . fromJSObject) jsdisks dspindles <- mapM (annotateResult errorMessage . flip maybeFromObj "spindles" . fromJSObject) jsdisks let disks = zipWith Instance.Disk dsizes dspindles mem <- extract "memory" vcpus <- extract "vcpus" tags <- extract "tags" dt <- extract "disk_template" su <- extract "spindle_use" nics <- extract "nics" >>= toArray >>= asObjectList >>= mapM (parseNic n . fromJSObject) return (n, Instance.create n mem disk disks vcpus Running tags True 0 0 dt su nics) -- | Parses an instance as found in the cluster instance list. parseInstance :: NameAssoc -- ^ The node name-to-index association list -> String -- ^ The name of the instance -> JSRecord -- ^ The JSON object -> Result (String, Instance.Instance) parseInstance ktn n a = do base <- parseBaseInstance n a nodes <- fromObj a "nodes" (pnode, snodes) <- case nodes of [] -> Bad $ "empty node list for instance " ++ n x:xs -> readEitherString x >>= \x' -> return (x', xs) pidx <- lookupNode ktn n pnode sidx <- case snodes of [] -> return Node.noSecondary x:_ -> readEitherString x >>= lookupNode ktn n return (n, Instance.setBoth (snd base) pidx sidx) -- | Parses a node as found in the cluster node list. parseNode :: NameAssoc -- ^ The group association -> String -- ^ The node's name -> JSRecord -- ^ The JSON object -> Result (String, Node.Node) parseNode ktg n a = do let desc = "invalid data for node '" ++ n ++ "'" extract x = tryFromObj desc a x offline <- extract "offline" drained <- extract "drained" guuid <- extract "group" vm_capable <- annotateResult desc $ maybeFromObj a "vm_capable" let vm_capable' = fromMaybe True vm_capable gidx <- lookupGroup ktg n guuid ndparams <- extract "ndparams" >>= asJSObject excl_stor <- tryFromObj desc (fromJSObject ndparams) "exclusive_storage" let live = not offline && vm_capable' lvextract def = eitherLive live def . extract sptotal <- if excl_stor then lvextract 0 "total_spindles" else tryFromObj desc (fromJSObject ndparams) "spindle_count" spfree <- lvextract 0 "free_spindles" mtotal <- lvextract 0.0 "total_memory" mnode <- lvextract 0 "reserved_memory" mfree <- lvextract 0 "free_memory" dtotal <- lvextract 0.0 "total_disk" dfree <- lvextract 0 "free_disk" ctotal <- lvextract 0.0 "total_cpus" cnos <- lvextract 0 "reserved_cpus" let node = Node.create n mtotal mnode mfree dtotal dfree ctotal cnos (not live || drained) sptotal spfree gidx excl_stor return (n, node) -- | Parses a group as found in the cluster group list. parseGroup :: String -- ^ The group UUID -> JSRecord -- ^ The JSON object -> Result (String, Group.Group) parseGroup u a = do let extract x = tryFromObj ("invalid data for group '" ++ u ++ "'") a x name <- extract "name" apol <- extract "alloc_policy" nets <- extract "networks" ipol <- extract "ipolicy" tags <- extract "tags" return (u, Group.create name u apol nets ipol tags) -- | Top-level parser. -- -- The result is a tuple of eventual warning messages and the parsed -- request; if parsing the input data fails, we'll return a 'Bad' -- value. parseData :: ClockTime -- ^ The current time -> String -- ^ The JSON message as received from Ganeti -> Result ([String], Request) -- ^ Result tuple parseData now body = do decoded <- fromJResult "Parsing input IAllocator message" (decodeStrict body) let obj = fromJSObject decoded extrObj x = tryFromObj "invalid iallocator message" obj x -- request parser request <- liftM fromJSObject (extrObj "request") let extrFromReq r x = tryFromObj "invalid request dict" r x let extrReq x = extrFromReq request x -- existing group parsing glist <- liftM fromJSObject (extrObj "nodegroups") gobj <- mapM (\(x, y) -> asJSObject y >>= parseGroup x . fromJSObject) glist let (ktg, gl) = assignIndices gobj -- existing node parsing nlist <- liftM fromJSObject (extrObj "nodes") nobj <- mapM (\(x,y) -> asJSObject y >>= parseNode ktg x . fromJSObject) nlist let (ktn, nl) = assignIndices nobj -- existing instance parsing ilist <- extrObj "instances" let idata = fromJSObject ilist iobj <- mapM (\(x,y) -> asJSObject y >>= parseInstance ktn x . fromJSObject) idata let (kti, il) = assignIndices iobj -- cluster tags ctags <- extrObj "cluster_tags" cdata1 <- mergeData [] [] [] [] now (ClusterData gl nl il ctags defIPolicy) let (msgs, fix_nl) = checkData (cdNodes cdata1) (cdInstances cdata1) cdata = cdata1 { cdNodes = fix_nl } map_n = cdNodes cdata map_i = cdInstances cdata map_g = cdGroups cdata optype <- extrReq "type" rqtype <- case () of _ | optype == C.iallocatorModeAlloc -> do rname <- extrReq "name" rgn <- maybeFromObj request "group_name" req_nodes <- extrReq "required_nodes" inew <- parseBaseInstance rname request let io = updateExclTags (extractExTags ctags) $ snd inew return $ Allocate io (Cluster.AllocDetails req_nodes rgn) | optype == C.iallocatorModeReloc -> do rname <- extrReq "name" ridx <- lookupInstance kti rname req_nodes <- extrReq "required_nodes" ex_nodes <- extrReq "relocate_from" ex_idex <- mapM (Container.findByName map_n) ex_nodes return $ Relocate ridx req_nodes (map Node.idx ex_idex) | optype == C.iallocatorModeChgGroup -> do rl_names <- extrReq "instances" rl_insts <- mapM (liftM Instance.idx . Container.findByName map_i) rl_names gr_uuids <- extrReq "target_groups" gr_idxes <- mapM (liftM Group.idx . Container.findByName map_g) gr_uuids return $ ChangeGroup rl_insts gr_idxes | optype == C.iallocatorModeNodeEvac -> do rl_names <- extrReq "instances" rl_insts <- mapM (Container.findByName map_i) rl_names let rl_idx = map Instance.idx rl_insts rl_mode <- extrReq "evac_mode" return $ NodeEvacuate rl_idx rl_mode | optype == C.iallocatorModeMultiAlloc -> do arry <- extrReq "instances" :: Result [JSObject JSValue] let inst_reqs = map fromJSObject arry prqs <- forM inst_reqs (\r -> do rname <- extrFromReq r "name" rgn <- maybeFromObj request "group_name" req_nodes <- extrFromReq r "required_nodes" inew <- parseBaseInstance rname r let io = updateExclTags (extractExTags ctags) $ snd inew return (io, Cluster.AllocDetails req_nodes rgn)) return $ MultiAllocate prqs | otherwise -> fail ("Invalid request type '" ++ optype ++ "'") return (msgs, Request rqtype cdata) -- | Formats the result into a valid IAllocator response message. formatResponse :: Bool -- ^ Whether the request was successful -> String -- ^ Information text -> JSValue -- ^ The JSON encoded result -> String -- ^ The full JSON-formatted message formatResponse success info result = let e_success = ("success", showJSON success) e_info = ("info", showJSON info) e_result = ("result", result) in encodeStrict $ makeObj [e_success, e_info, e_result] -- | Flatten the log of a solution into a string. describeSolution :: Cluster.AllocSolution -> String describeSolution = intercalate ", " . Cluster.asLog -- | Convert allocation/relocation results into the result format. formatAllocate :: Instance.List -> Cluster.AllocSolution -> Result IAllocResult formatAllocate il as = do let info = describeSolution as case Cluster.asSolution as of Nothing -> fail info Just (nl, inst, nodes, _) -> do let il' = Container.add (Instance.idx inst) inst il return (info, showJSON $ map Node.name nodes, nl, il') -- | Convert multi allocation results into the result format. formatMultiAlloc :: (Node.List, Instance.List, Cluster.AllocSolutionList) -> Result IAllocResult formatMultiAlloc (fin_nl, fin_il, ars) = let rars = reverse ars (allocated, failed) = partition (isJust . Cluster.asSolution . snd) rars aars = map (\(_, ar) -> let (_, inst, nodes, _) = fromJust $ Cluster.asSolution ar iname = Instance.name inst nnames = map Node.name nodes in (iname, nnames)) allocated fars = map (\(inst, ar) -> let iname = Instance.name inst in (iname, describeSolution ar)) failed info = show (length failed) ++ " instances failed to allocate and " ++ show (length allocated) ++ " were allocated successfully" in return (info, showJSON (aars, fars), fin_nl, fin_il) -- | Convert a node-evacuation/change group result. formatNodeEvac :: Group.List -> Node.List -> Instance.List -> (Node.List, Instance.List, Cluster.EvacSolution) -> Result IAllocResult formatNodeEvac gl nl il (fin_nl, fin_il, es) = let iname = Instance.name . flip Container.find il nname = Node.name . flip Container.find nl gname = Group.name . flip Container.find gl fes = map (\(idx, msg) -> (iname idx, msg)) $ Cluster.esFailed es mes = map (\(idx, gdx, ndxs) -> (iname idx, gname gdx, map nname ndxs)) $ Cluster.esMoved es failed = length fes moved = length mes info = show failed ++ " instances failed to move and " ++ show moved ++ " were moved successfully" in Ok (info, showJSON (mes, fes, Cluster.esOpCodes es), fin_nl, fin_il) -- | Runs relocate for a single instance. -- -- This is wrapper over the 'Cluster.tryNodeEvac' function that is run -- with a single instance (ours), and further it checks that the -- result it got (in the nodes field) is actually consistent, as -- tryNodeEvac is designed to output primarily an opcode list, not a -- node list. processRelocate :: AlgorithmOptions -> Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Idx -- ^ The index of the instance to move -> Int -- ^ The number of nodes required -> [Ndx] -- ^ Nodes which should not be used -> Result (Node.List, Instance.List, [Ndx]) -- ^ Solution list processRelocate opts gl nl il idx 1 exndx = do let orig = Container.find idx il sorig = Instance.sNode orig porig = Instance.pNode orig mir_type = Instance.mirrorType orig (exp_node, node_type, reloc_type) <- case mir_type of MirrorNone -> fail "Can't relocate non-mirrored instances" MirrorInternal -> return (sorig, "secondary", ChangeSecondary) MirrorExternal -> return (porig, "primary", ChangePrimary) when (exndx /= [exp_node]) . -- FIXME: we can't use the excluded nodes here; the logic is -- already _but only partially_ implemented in tryNodeEvac... fail $ "Unsupported request: excluded nodes not equal to\ \ instance's " ++ node_type ++ "(" ++ show exp_node ++ " versus " ++ show exndx ++ ")" (nl', il', esol) <- Cluster.tryNodeEvac opts gl nl il reloc_type [idx] nodes <- case lookup idx (Cluster.esFailed esol) of Just msg -> fail msg Nothing -> case lookup idx (map (\(a, _, b) -> (a, b)) (Cluster.esMoved esol)) of Nothing -> fail "Internal error: lost instance idx during move" Just n -> return n let inst = Container.find idx il' pnode = Instance.pNode inst snode = Instance.sNode inst nodes' <- case mir_type of MirrorNone -> fail "Internal error: mirror type none after relocation?!" MirrorInternal -> do when (snode == sorig) $ fail "Internal error: instance didn't change secondary node?!" when (snode == pnode) $ fail "Internal error: selected primary as new secondary?!" if nodes == [pnode, snode] then return [snode] -- only the new secondary is needed else fail $ "Internal error: inconsistent node list (" ++ show nodes ++ ") versus instance nodes (" ++ show pnode ++ "," ++ show snode ++ ")" MirrorExternal -> do when (pnode == porig) $ fail "Internal error: instance didn't change primary node?!" if nodes == [pnode] then return nodes else fail $ "Internal error: inconsistent node list (" ++ show nodes ++ ") versus instance node (" ++ show pnode ++ ")" return (nl', il', nodes') processRelocate _ _ _ _ _ reqn _ = fail $ "Exchange " ++ show reqn ++ " nodes mode is not implemented" formatRelocate :: (Node.List, Instance.List, [Ndx]) -> Result IAllocResult formatRelocate (nl, il, ndxs) = let nodes = map (`Container.find` nl) ndxs names = map Node.name nodes in Ok ("success", showJSON names, nl, il) -- | Process a request and return new node lists. processRequest :: AlgorithmOptions -> Request -> Result IAllocResult processRequest opts request = let Request rqtype (ClusterData gl nl il _ _) = request in case rqtype of Allocate xi (Cluster.AllocDetails reqn Nothing) -> Cluster.tryMGAlloc gl nl il xi reqn >>= formatAllocate il Allocate xi (Cluster.AllocDetails reqn (Just gn)) -> Cluster.tryGroupAlloc gl nl il gn xi reqn >>= formatAllocate il Relocate idx reqn exnodes -> processRelocate opts gl nl il idx reqn exnodes >>= formatRelocate ChangeGroup gdxs idxs -> Cluster.tryChangeGroup gl nl il idxs gdxs >>= formatNodeEvac gl nl il NodeEvacuate xi mode -> Cluster.tryNodeEvac opts gl nl il mode xi >>= formatNodeEvac gl nl il MultiAllocate xies -> Cluster.allocList gl nl il xies [] >>= formatMultiAlloc -- | Reads the request from the data file(s). readRequest :: FilePath -> IO Request readRequest fp = do now <- getClockTime input_data <- case fp of "-" -> getContents _ -> readFile fp case parseData now input_data of Bad err -> exitErr err Ok (fix_msgs, rq) -> maybeShowWarnings fix_msgs >> return rq -- | Main iallocator pipeline. runIAllocator :: AlgorithmOptions -> Request -> (Maybe (Node.List, Instance.List), String) runIAllocator opts request = let (ok, info, result, cdata) = case processRequest opts request of Ok (msg, r, nl, il) -> (True, "Request successful: " ++ msg, r, Just (nl, il)) Bad msg -> (False, "Request failed: " ++ msg, JSArray [], Nothing) rstring = formatResponse ok info result in (cdata, rstring) -- | Load the data from an iallocation request file loadData :: FilePath -- ^ The path to the file -> IO (Result ClusterData) loadData fp = do Request _ cdata <- readRequest fp return $ Ok cdata
ganeti-github-testing/ganeti-test-1
src/Ganeti/HTools/Backend/IAlloc.hs
bsd-2-clause
19,821
0
26
5,621
4,923
2,451
2,472
364
9
{-# LANGUAGE KindSignatures, RankNTypes, GADTs, OverloadedStrings #-} module SneathLane.BasicWidgets where import Control.Applicative (Applicative(..), liftA2) import Control.Monad (mplus, when) import Data.Monoid ((<>)) import Data.Functor ((<$)) import Data.Maybe (fromMaybe) import Control.Arrow ((***)) import SneathLane.Graphics import SneathLane.Widget import System.IO.Unsafe (unsafePerformIO) import Haste (writeLog, catJSStr, toJSString, fromJSStr) logging x y = unsafePerformIO (writeLog (show x) >> return y) rectPath ps w h r = QuadraticPath ps (0,r) [((0,0),(r,0)), ((w-r,0),(w-r,0)), ((w,0),(w,r)), ((w,h-r),(w,h-r)), ((w,h),(w-r,h)), ((r,h),(r,h)), ((0,h),(0,h-r)), ((0,r),(0,r))] button textStyle label = blur where blur = Continue (output (RGBA 0 0 0 1)) Nothing Nothing (Focusable focus focus) focus = Continue (output (RGBA 0 1 0 1)) Nothing Nothing (Focused blur (blur, False) (blur, False) (\key -> case key of EvKeyDown 13 _ -> Finish () -- enter _ -> focus)) output clr = handler <$ graphicList [rectPath (PathStyle (Just (clr, 2)) Nothing) (labelWidth + 10) 30 5, Text textStyle (5,5) label] handler (EvMouseDown _ LeftButton) = (Nothing, Finish ()) handler _ = (Nothing, blur) labelWidth = measureText textStyle label tabs textStyle ts n = let buttons = zipWith (\(label,_) n' -> button textStyle label >> return (Left n')) ts [0..] curr = fmap Right $ nextFrame $ snd $ ts !! n in do ret <- balancedFold beside buttons `above` curr case ret of Right (Finish z) -> Finish z Right w' -> tabs textStyle (zipWith (\(label,w) n' -> if n' == n then (label, w') else (label, w)) ts [0..]) n Left n' -> let (Continue out _ _ _) = curr (Rect _ _ _ h) = graphicTreeBounds out in tabs textStyle (zipWith (\(label,w) n -> (label, if n == n' then slideToHeight h 0.2 w else w)) ts [0..]) n' slideToHeight initialHeight duration (Finish z) = Finish z slideToHeight initialHeight duration (Continue out mouseOut anim foc) = let (Rect x y w h) = graphicTreeBounds out anim' = fromMaybe (\tm -> Continue out mouseOut Nothing foc) anim anim'' tm = let w' = anim' tm in if tm > duration then w' else slideToHeight (initialHeight + (tm/duration)*(h - initialHeight)) (duration - tm) w' out' = Clip (Rect x y w initialHeight) out mouseOut' = fmap (slideToHeight initialHeight duration) mouseOut foc' = mapWidgetFocus (slideToHeight initialHeight duration) foc in Continue out' mouseOut' (Just anim'') foc' nextFrame widget = case widget of Finish z -> Finish (Finish z) Continue out mouseOut anim foc -> let out' = (fmap . fmap) (\(murl, w) -> (murl, Finish w)) out mouseOut' = fmap Finish mouseOut anim' = (fmap . fmap) Finish anim foc' = mapWidgetFocus Finish foc in Continue out' mouseOut' anim' foc' textInput ww ts txt focused = Continue out Nothing Nothing foc where out = const (Nothing, textInput ww ts txt True) <$ graphicList [ rectPath (PathStyle (Just (if focused then RGBA 0 0 1 1 else RGBA 0 0 0 1, 1)) Nothing) ww (fromIntegral $ ts_lineHeight ts + 6) 5, Text ts (5,3) txt ] foc = if focused then Focused blur (blur, False) (blur, False) keys else Focusable focus focus keys = (\key -> case key of EvKeyDown 8 _ -> Finish (toJSString $ reverse $ drop 1 $ reverse $ fromJSStr txt, False) EvKeyDown 13 _ -> Finish (txt, True) EvKeyInput str -> Finish (catJSStr "" [txt, str], False) _ -> textInput ww ts txt focused) blur = textInput ww ts txt False focus = textInput ww ts txt True autoComplete ts fcomps txt focused = let comps = fcomps txt ww = maximum $ map (measureText ts) (txt:map fst comps) ti = textInput (ww + 10) ts txt focused wi = balancedFold above (ti : map showComp comps) showComp comp = graphicWidget Nothing (graphicList [ rectPath (PathStyle (Just (RGBA 0.4 0.4 0.4 1, 1)) (Just $ RGBA 0.9 0.9 0.9 1)) (ww + 10) (fromIntegral $ ts_lineHeight ts) 0, Text ts (5,0) (fst comp)]) in do (txt', finish) <- wi case finish of True -> if null comps then autoComplete ts fcomps txt True else return (snd $ head comps) False -> if txt' /= "" && null (fcomps txt') then autoComplete ts fcomps txt True else autoComplete ts fcomps txt' True simpleFocus fw keys = focus where focus = fw $ Focused blur (blur, False) (blur, False) keys blur = fw $ Focusable focus focus
jhp/sneathlane-haste
SneathLane/BasicWidgets.hs
bsd-2-clause
5,340
0
21
1,851
2,051
1,088
963
98
6
{-| Copyright : (C) 2012-2016, University of Twente License : BSD2 (see the file LICENSE) Maintainer : Christiaan Baaij <christiaan.baaij@gmail.com> Utility functions used by the normalisation transformations -} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE TemplateHaskell #-} module CLaSH.Normalize.Util where import Control.Lens ((%=)) import qualified Control.Lens as Lens import Data.Function (on) import qualified Data.Graph as Graph import Data.Graph.Inductive (Gr,LNode,lsuc,mkGraph,iDom) import Data.HashMap.Lazy (HashMap) import qualified Data.HashMap.Lazy as HashMap import qualified Data.List as List import qualified Data.Maybe as Maybe import qualified Data.Set as Set import qualified Data.Set.Lens as Lens import Unbound.Generics.LocallyNameless (Fresh, bind, embed, rec) import CLaSH.Core.FreeVars (termFreeIds) import CLaSH.Core.Var (Var (Id)) import CLaSH.Core.Term (Term (..), TmName) import CLaSH.Core.Type (Type) import CLaSH.Core.TyCon (TyCon, TyConName) import CLaSH.Core.Util (collectArgs, isPolyFun) import CLaSH.Normalize.Types import CLaSH.Rewrite.Types (bindings,extra) import CLaSH.Rewrite.Util (specialise) import CLaSH.Util (curLoc) -- | Determine if a function is already inlined in the context of the 'NetlistMonad' alreadyInlined :: TmName -- ^ Function we want to inline -> TmName -- ^ Function in which we want to perform the inlining -> NormalizeMonad (Maybe Int) alreadyInlined f cf = do inlinedHM <- Lens.use inlineHistory case HashMap.lookup cf inlinedHM of Nothing -> return Nothing Just inlined' -> return (HashMap.lookup f inlined') addNewInline :: TmName -- ^ Function we want to inline -> TmName -- ^ Function in which we want to perform the inlining -> NormalizeMonad () addNewInline f cf = inlineHistory %= HashMap.insertWith (\_ hm -> HashMap.insertWith (+) f 1 hm) cf (HashMap.singleton f 1) -- | Specialize under the Normalization Monad specializeNorm :: NormRewrite specializeNorm = specialise specialisationCache specialisationHistory specialisationLimit -- | Determine if a term is closed isClosed :: (Functor m, Fresh m) => HashMap TyConName TyCon -> Term -> m Bool isClosed tcm = fmap not . isPolyFun tcm -- | Determine if a term represents a constant isConstant :: Term -> Bool isConstant e = case collectArgs e of (Data _, args) -> all (either isConstant (const True)) args (Prim _ _, args) -> all (either isConstant (const True)) args (Literal _,_) -> True _ -> False isRecursiveBndr :: TmName -> NormalizeSession Bool isRecursiveBndr f = do cg <- Lens.use (extra.recursiveComponents) case HashMap.lookup f cg of Just isR -> return isR Nothing -> do bndrs <- Lens.use bindings let cg' = callGraph [] bndrs f rcs = concat $ mkRecursiveComponents cg' isR = f `elem` rcs cg'' = HashMap.fromList $ map (\(t,_) -> (t,t `elem` rcs)) cg' (extra.recursiveComponents) %= HashMap.union cg'' return isR -- | Create a call graph for a set of global binders, given a root callGraph :: [TmName] -- ^ List of functions that should not be inspected -> HashMap TmName (Type,Term) -- ^ Global binders -> TmName -- ^ Root of the call graph -> [(TmName,[TmName])] callGraph visited bindingMap root = node:other where rootTm = Maybe.fromMaybe (error $ show root ++ " is not a global binder") $ HashMap.lookup root bindingMap used = Set.toList $ Lens.setOf termFreeIds (snd rootTm) node = (root,used) other = concatMap (callGraph (root:visited) bindingMap) (filter (`notElem` visited) used) -- | Determine the sets of recursive components given the edges of a callgraph mkRecursiveComponents :: [(TmName,[TmName])] -- ^ [(calling function,[called function])] -> [[TmName]] mkRecursiveComponents cg = map (List.sortBy (compare `on` (`List.elemIndex` fs))) . Maybe.catMaybes . map (\case {Graph.CyclicSCC vs -> Just vs; _ -> Nothing}) . Graph.stronglyConnComp $ map (\(n,es) -> (n,n,es)) cg where fs = map fst cg lambdaDropPrep :: HashMap TmName (Type,Term) -> TmName -> HashMap TmName (Type,Term) lambdaDropPrep bndrs topEntity = bndrs' where depGraph = callGraph [] bndrs topEntity used = HashMap.fromList depGraph rcs = mkRecursiveComponents depGraph dropped = map (lambdaDrop bndrs used) rcs bndrs' = foldr (\(k,v) b -> HashMap.insert k v b) bndrs dropped lambdaDrop :: HashMap TmName (Type,Term) -- ^ Original Binders -> HashMap TmName [TmName] -- ^ Dependency Graph -> [TmName] -- ^ Recursive block -> (TmName,(Type,Term)) -- ^ Lambda-dropped Binders lambdaDrop bndrs depGraph cyc@(root:_) = block where doms = dominator depGraph cyc block = blockSink bndrs doms (0,root) lambdaDrop _ _ [] = error $ $(curLoc) ++ "Can't lambdadrop empty cycle" dominator :: HashMap TmName [TmName] -- ^ Dependency Graph -> [TmName] -- ^ Recursive block -> Gr TmName TmName -- ^ Recursive block dominator dominator cfg cyc = mkGraph nodes (map (\(e,b) -> (b,e,nodesM HashMap.! e)) doms) where nodes = zip [0..] cyc nodesM = HashMap.fromList nodes nodesI = HashMap.fromList $ zip cyc [0..] cycEdges = HashMap.map ( map (nodesI HashMap.!) . filter (`elem` cyc) ) $ HashMap.filterWithKey (\k _ -> k `elem` cyc) cfg edges = concatMap (\(i,n) -> zip3 (repeat i) (cycEdges HashMap.! n) (repeat ()) ) nodes graph = mkGraph nodes edges :: Gr TmName () doms = iDom graph 0 blockSink :: HashMap TmName (Type,Term) -- ^ Original Binders -> Gr TmName TmName -- ^ Recursive block dominator -> LNode TmName -- ^ Recursive block dominator root -> (TmName,(Type,Term)) -- ^ Block sank binder blockSink bndrs doms (nId,tmName) = (tmName,(ty,newTm)) where (ty,tm) = bndrs HashMap.! tmName sucTm = lsuc doms nId tmS = map (blockSink bndrs doms) sucTm bnds = map (\(tN,(ty',tm')) -> (Id tN (embed ty'),embed tm')) tmS newTm = case sucTm of [] -> tm _ -> Letrec (bind (rec bnds) tm)
ggreif/clash-compiler
clash-lib/src/CLaSH/Normalize/Util.hs
bsd-2-clause
6,945
0
20
2,116
1,903
1,053
850
128
4
module Hack2.Contrib.Middleware.Cascade (cascade) where import Prelude () import Air.Env hiding (Default, def) import Hack2 import Data.Default cascade :: [Application] -> Application cascade [] = const - return def { status = 404 } cascade (x:xs) = \env -> do r <- x env if r.status == 404 then cascade xs env else return r
nfjinjing/hack2-contrib
src/Hack2/Contrib/Middleware/Cascade.hs
bsd-3-clause
350
0
10
79
133
74
59
12
2