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
import Data.Maybe import Data.Fixed import Data.List (foldl') import System.Environment fastFindIndex cond xs prev now | prev==now && matchNow = Just now | prev==now && not matchNow = Nothing | not matchNow && not matchPrev = fastFindIndex cond xs now (now+(now-prev)*2) | not matchNow && matchPrev = fastFindIndex cond xs now (now-(now-prev)`div`2) | matchNow && not matchPrev = fastFindIndex cond xs now (now-(now-prev)`div`2) | matchNow && matchPrev = fastFindIndex cond xs now (now+(now-prev)`div`2) where matchNow = cond(xs now) == True matchPrev = cond(xs prev) == True fib :: Int -> BigN fib i = (phi^i) / sqrt5 phi :: BigN phi = (1+sqrt5) / 2 sqrt5 :: BigN sqrt5=2.2360679774997896964091736687312762354406183596115257242708972454105209256378048994144144083787822749695081761507737835042532677244470738635863601215334527088667781731918791658112766453226398565805357613504175337850034233924140644420864325390972525926272288762995174024406816117759089094984923713907297288984820886415426898940991316935770197486788844250897541329561831769214999774248015304341150359576683325124988151781394080005624208552435422355561063063428202340933319829339597463522712013417496142026359047378855043896870611356600457571399565955669569175645782219525000605392312340050092867648755297220567662536660744858535052623306784946334222423176372770266324076801044433158257335058930981362263431986864719469899701808189524264459620345221411922329125981963258111041704958070481204034559949435068555518555725123886416550102624363125710244496187894246829034044747161154557232017376765904609185295756035779843980541553807790643936397230287560629994822138521773485924535 data E1001=E1001 instance HasResolution E1001 where resolution _ = 10 ^ 1001 type BigN= Fixed E1001 main = do args <- getArgs let t = read (head args) print $ answer $ 10^t answer x = fastFindIndex (\y->y>x) fib 0 1 -- fib n = (power fn n - power fn (-n)) / sqrt(5) -- where fn = (1+sqrt(5)) / 2 power :: (Integral a, Floating b) => a -> b power x y | y>0 = x * power x (y-1) | y<0 = 1 / power x (y+1) | otherwise = 1
yuto-matsum/contest-util-hs
src/Euler/025.hs
mit
2,157
1
12
294
570
289
281
32
1
fib :: Int -> Int fib 0 = 1 fib 1 = 1 fib x | x > 1 = fib (x - 2) + fib (x - 1) main = do print (sum [fib x | x <- [1..32], even (fib x)])
jamesbarnett/boring-attempts-to-learn-something-of-dubious-economic-value
haskell/problem002.hs
mit
144
0
14
48
117
57
60
6
1
module MinesImage where import Codec.Picture import Control.Arrow ((&&&)) import Data.Function import Data.List import Data.Maybe import Data.Ord import Data.Word import Debug.Trace import Logic type Img = Image PixelRGB8 type CellCoords = ([Int], [Int], Int) findTopLeftCorner :: Img -> (Int,Int) findTopLeftCorner img = trace (show (matchCoord,matchPix)) topLeftCoord where w = imageWidth img h = imageHeight img (cx,cy) = (w `div` 2, h `div` 2) diagCoords = reverse (zip [cx,cx-1..0] [cy,cy-1..0]) pixAtCoord = pixelToTuple . uncurry (pixelAt img) diagPixels = map pixAtCoord diagCoords (match:_) = locateSubstring targetBlock diagPixels matchCoord = diagCoords !! (match+2) matchPix = pixAtCoord matchCoord abovePix = pixAtCoord (above matchCoord) leftPix = pixAtCoord (left matchCoord) direction = case (abovePix == topLeftEdgePixel, leftPix == topLeftEdgePixel) of (True, True) -> error "!" (False, True) -> left (True, False) -> above (False, False) -> above topLeftCoord = last (takeWhile (pixAtIsEdge img) (iterate direction matchCoord)) cellCoords :: Img -> (Int,Int) -> CellCoords cellCoords img topLeftCoord = (xcentres, ycentres, cellMinLength) where h = imageHeight img w = imageWidth img coords = iterate belowRight topLeftCoord afterEdge = dropWhile (pixAtIsEdge img) coords topLeftNonEdge = head afterEdge nextOne = belowRight topLeftNonEdge row = map (\c -> (c, pixAt img c)) (takeWhile ((<w) . fst) (iterate right nextOne)) grow = map (head &&& length) . groupBy ((==) `on` snd) $ row cellMinLength = round (0.8 * fromIntegral (snd (head grow))) cellMaxLength = round (1.2 * fromIntegral (snd (head grow))) rowcells = filter (\ (_,l) -> cellMinLength <= l) (takeWhile ((<= cellMaxLength) . snd) grow) xcentres = map (\ (((x,_),_p), l) -> x + (l `div` 2)) rowcells col = map (\c -> (c, pixAt img c)) (takeWhile ((<h) . snd) (iterate below nextOne)) gcol = map (head &&& length) . groupBy ((==) `on` snd) $ col colcells = filter (\ (_,l) -> cellMinLength <= l) (takeWhile ((<= cellMaxLength) . snd) gcol) ycentres = map (\ (((_,y),_p), l) -> y + (l `div` 2)) colcells pixAt img = pixelToTuple . uncurry (pixelAt img) pixAtIsEdge img c = pixAt img c == topLeftEdgePixel above (x,y) = (x,y-1) left (x,y) = (x-1,y) right (x,y) = (x+1,y) belowRight (x,y) = (x+1,y+1) below (x,y) = (x,y+1) pixelToTuple (PixelRGB8 r b g) = (r,b,g) backgroundPixel = (220, 218, 213) unknownPixel = backgroundPixel topLeftEdgePixel = (147, 145, 142) revealedPixel = (209,207,203) targetBlock = replicate 2 backgroundPixel ++ replicate 2 topLeftEdgePixel isBright (r,g,b) = r+g+b >= 500 locateSubstring :: Eq a => [a] -> [a] -> [Int] locateSubstring needle haystack = map fst $ filter (\(i,s) -> needle `isPrefixOf` s) indexedTails where indexedTails = zip [0..] (tails haystack) cellContents :: Img -> CellCoords -> (Int,Int) -> [ ((Word8,Word8,Word8), Int) ] cellContents img (xcs, ycs, l) (x,y) = reverse . sortBy (comparing snd) . map (head &&& length) . group $ sortedPixels where (ccx, ccy) = (xcs !! x, ycs !! y) range = [-l `div` 2 .. l `div` 2] coords = [ (ccx + i, ccy + j) | i <- range, j <- range ] pixels = map (pixAt img) coords sortedPixels = sort pixels colours :: [ ((Word8,Word8,Word8), Int) ] colours = [ ((0,0,255), 1) , ((0,128,0), 2) , ((255,0,0), 3) , ((0,0,128), 4) , ((128,0,0), 5) , ((0,128,128), 6) , ((0,0,0), 7) , (backgroundPixel, -1) ] cellIdentify :: Img -> CellCoords -> (Int,Int) -> Cell cellIdentify img ccs coord = result where conts = cellContents img ccs coord mainColours = catMaybes (map (\p -> lookup (fst p) colours) conts) result = case mainColours of (-1:3:7:_) -> Flagged (-1:7:3:_) -> Flagged (-1:_) -> Unknown (n:_) -> Revealed n _ -> Revealed 0
cmears/mines-solver
MinesImage.hs
mit
4,161
0
14
1,063
1,890
1,068
822
94
5
import System.IO main = do gen <- getStdGen let (randNumber, _) = randomR (1,length $ lines contents) gen :: (Int, StdGen) handle <- openFile "przemyslenia 2016-05-10.txt" ReadMode contents <- hGetContents handle let firstLine = head $ lines contents putStrLn firstLine putStrLn $ show randNumber hClose handle
RAFIRAF/HASKELL
randomQuote.hs
mit
328
0
13
63
121
56
65
10
1
{- ** ********************************************************************* * * * This software is part of the pads package * * Copyright (c) 2005-2011 AT&T Knowledge Ventures * * and is licensed under the * * Common Public License * * by AT&T Knowledge Ventures * * * * A copy of the License is available at * * www.padsproj.org/License.html * * * * This program contains certain software code or other information * * ("AT&T Software") proprietary to AT&T Corp. ("AT&T"). The AT&T * * Software is provided to you "AS IS". YOU ASSUME TOTAL RESPONSIBILITY* * AND RISK FOR USE OF THE AT&T SOFTWARE. AT&T DOES NOT MAKE, AND * * EXPRESSLY DISCLAIMS, ANY EXPRESS OR IMPLIED WARRANTIES OF ANY KIND * * WHATSOEVER, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF* * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, WARRANTIES OF * * TITLE OR NON-INFRINGEMENT. (c) AT&T Corp. All rights * * reserved. AT&T is a registered trademark of AT&T Corp. * * * * Network Services Research Center * * AT&T Labs Research * * Florham Park NJ * * * * Kathleen Fisher <[email protected]> * * * ************************************************************************ -} module Language.Forest.Quote (forest) where import Prelude hiding (exp, init) import Foreign (unsafePerformIO) import Language.Haskell.TH import Language.Haskell.TH.Quote (QuasiQuoter(..)) import Language.Forest.CodeGen import qualified Language.Forest.Parser as P parse :: Monad m => Loc -> P.Parser a -> String -> m a parse loc p input = let fileName = loc_filename loc (line,column) = loc_start loc in case P.parse p fileName line column input of Left err -> unsafePerformIO $ fail $ show err Right x -> return x fparse1 p pToQ s = do loc <- location x <- Language.Forest.Quote.parse loc p s pToQ x fquasiquote1 p = QuasiQuoter (error "parse expression") (error "parse pattern") (error "parse type") (fparse1 p make_forest_declarations) forest :: QuasiQuoter forest = fquasiquote1 P.forestDecls
elitak/forest
Language/Forest/Quote.hs
epl-1.0
3,003
0
11
1,340
293
154
139
30
2
module MegaHAL ( initialize , greeting , learnAndReply , learn , cleanup , MegaHal() ) where import Prelude hiding (log) import Foreign.C.Types import Foreign.C.String import Foreign.Marshal.Alloc (free) import qualified Data.ByteString as BS import MegaHAL.CBits data MegaHal = MegaHal MHContext [CString] initialize :: FilePath -> FilePath -> FilePath -> IO MegaHal initialize brainDir errorFile statusFile = do -- Setup the logfile and brain and register the CString to be dealloc err <- newCString errorFile st <- newCString statusFile dir <- newCString brainDir -- Actually init megahal cxt <- m_initialize err st dir return $ MegaHal cxt [err, st, dir] -- TODO: uncertain if we need to free the returned string or what greeting :: MegaHal -> IO BS.ByteString greeting (MegaHal cxt _) = BS.packCString =<< m_initial_greeting cxt -- TODO: uncertain if we need to free the returned string or what learnAndReply :: MegaHal -> BS.ByteString -> Bool -> IO BS.ByteString learnAndReply (MegaHal cxt _) str log = BS.useAsCString str (flip (m_do_reply cxt) (boolToCInt log)) >>= BS.packCString learn :: MegaHal -> BS.ByteString -> Bool -> IO () learn (MegaHal cxt _) str log = BS.useAsCString str (flip (m_learn_no_reply cxt) (boolToCInt log)) cleanup :: MegaHal -> IO () cleanup (MegaHal cxt xs) = do -- Cleanup MegaHal m_cleanup cxt -- Dealloc the CStrings mapM_ free xs boolToCInt :: Bool -> CInt boolToCInt False = 0 boolToCInt True = 1
pharaun/MegaHAL
src/MegaHAL.hs
gpl-2.0
1,531
0
10
320
445
232
213
36
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.S3.ListParts -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Lists the parts that have been uploaded for a specific multipart upload. -- -- <http://docs.aws.amazon.com/AmazonS3/latest/API/ListParts.html> module Network.AWS.S3.ListParts ( -- * Request ListParts -- ** Request constructor , listParts -- ** Request lenses , lpBucket , lpKey , lpMaxParts , lpPartNumberMarker , lpUploadId -- * Response , ListPartsResponse -- ** Response constructor , listPartsResponse -- ** Response lenses , lprBucket , lprInitiator , lprIsTruncated , lprKey , lprMaxParts , lprNextPartNumberMarker , lprOwner , lprPartNumberMarker , lprParts , lprStorageClass , lprUploadId ) where import Network.AWS.Prelude import Network.AWS.Request.S3 import Network.AWS.S3.Types import qualified GHC.Exts data ListParts = ListParts { _lpBucket :: Text , _lpKey :: Text , _lpMaxParts :: Maybe Int , _lpPartNumberMarker :: Maybe Int , _lpUploadId :: Text } deriving (Eq, Ord, Read, Show) -- | 'ListParts' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lpBucket' @::@ 'Text' -- -- * 'lpKey' @::@ 'Text' -- -- * 'lpMaxParts' @::@ 'Maybe' 'Int' -- -- * 'lpPartNumberMarker' @::@ 'Maybe' 'Int' -- -- * 'lpUploadId' @::@ 'Text' -- listParts :: Text -- ^ 'lpBucket' -> Text -- ^ 'lpKey' -> Text -- ^ 'lpUploadId' -> ListParts listParts p1 p2 p3 = ListParts { _lpBucket = p1 , _lpKey = p2 , _lpUploadId = p3 , _lpMaxParts = Nothing , _lpPartNumberMarker = Nothing } lpBucket :: Lens' ListParts Text lpBucket = lens _lpBucket (\s a -> s { _lpBucket = a }) lpKey :: Lens' ListParts Text lpKey = lens _lpKey (\s a -> s { _lpKey = a }) -- | Sets the maximum number of parts to return. lpMaxParts :: Lens' ListParts (Maybe Int) lpMaxParts = lens _lpMaxParts (\s a -> s { _lpMaxParts = 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 }) -- | Upload ID identifying the multipart upload whose parts are being listed. lpUploadId :: Lens' ListParts Text lpUploadId = lens _lpUploadId (\s a -> s { _lpUploadId = a }) data ListPartsResponse = ListPartsResponse { _lprBucket :: Maybe Text , _lprInitiator :: Maybe Initiator , _lprIsTruncated :: Maybe Bool , _lprKey :: Maybe Text , _lprMaxParts :: Maybe Int , _lprNextPartNumberMarker :: Maybe Int , _lprOwner :: Maybe Owner , _lprPartNumberMarker :: Maybe Int , _lprParts :: List "Part" Part , _lprStorageClass :: Maybe StorageClass , _lprUploadId :: Maybe Text } deriving (Eq, Read, Show) -- | 'ListPartsResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lprBucket' @::@ 'Maybe' 'Text' -- -- * 'lprInitiator' @::@ 'Maybe' 'Initiator' -- -- * 'lprIsTruncated' @::@ 'Maybe' 'Bool' -- -- * 'lprKey' @::@ 'Maybe' 'Text' -- -- * 'lprMaxParts' @::@ 'Maybe' 'Int' -- -- * 'lprNextPartNumberMarker' @::@ 'Maybe' 'Int' -- -- * 'lprOwner' @::@ 'Maybe' 'Owner' -- -- * 'lprPartNumberMarker' @::@ 'Maybe' 'Int' -- -- * 'lprParts' @::@ ['Part'] -- -- * 'lprStorageClass' @::@ 'Maybe' 'StorageClass' -- -- * 'lprUploadId' @::@ 'Maybe' 'Text' -- listPartsResponse :: ListPartsResponse listPartsResponse = ListPartsResponse { _lprBucket = Nothing , _lprKey = Nothing , _lprUploadId = Nothing , _lprPartNumberMarker = Nothing , _lprNextPartNumberMarker = Nothing , _lprMaxParts = Nothing , _lprIsTruncated = Nothing , _lprParts = mempty , _lprInitiator = Nothing , _lprOwner = Nothing , _lprStorageClass = Nothing } -- | Name of the bucket to which the multipart upload was initiated. lprBucket :: Lens' ListPartsResponse (Maybe Text) lprBucket = lens _lprBucket (\s a -> s { _lprBucket = a }) -- | Identifies who initiated the multipart upload. lprInitiator :: Lens' ListPartsResponse (Maybe Initiator) lprInitiator = lens _lprInitiator (\s a -> s { _lprInitiator = a }) -- | Indicates whether the returned list of parts is truncated. lprIsTruncated :: Lens' ListPartsResponse (Maybe Bool) lprIsTruncated = lens _lprIsTruncated (\s a -> s { _lprIsTruncated = a }) -- | Object key for which the multipart upload was initiated. lprKey :: Lens' ListPartsResponse (Maybe Text) lprKey = lens _lprKey (\s a -> s { _lprKey = a }) -- | Maximum number of parts that were allowed in the response. lprMaxParts :: Lens' ListPartsResponse (Maybe Int) lprMaxParts = lens _lprMaxParts (\s a -> s { _lprMaxParts = 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. lprNextPartNumberMarker :: Lens' ListPartsResponse (Maybe Int) lprNextPartNumberMarker = lens _lprNextPartNumberMarker (\s a -> s { _lprNextPartNumberMarker = a }) lprOwner :: Lens' ListPartsResponse (Maybe Owner) lprOwner = lens _lprOwner (\s a -> s { _lprOwner = a }) -- | Part number after which listing begins. lprPartNumberMarker :: Lens' ListPartsResponse (Maybe Int) lprPartNumberMarker = lens _lprPartNumberMarker (\s a -> s { _lprPartNumberMarker = a }) lprParts :: Lens' ListPartsResponse [Part] lprParts = lens _lprParts (\s a -> s { _lprParts = a }) . _List -- | The class of storage used to store the object. lprStorageClass :: Lens' ListPartsResponse (Maybe StorageClass) lprStorageClass = lens _lprStorageClass (\s a -> s { _lprStorageClass = a }) -- | Upload ID identifying the multipart upload whose parts are being listed. lprUploadId :: Lens' ListPartsResponse (Maybe Text) lprUploadId = lens _lprUploadId (\s a -> s { _lprUploadId = a }) instance ToPath ListParts where toPath ListParts{..} = mconcat [ "/" , toText _lpBucket , "/" , toText _lpKey ] instance ToQuery ListParts where toQuery ListParts{..} = mconcat [ "max-parts" =? _lpMaxParts , "part-number-marker" =? _lpPartNumberMarker , "uploadId" =? _lpUploadId ] instance ToHeaders ListParts instance ToXMLRoot ListParts where toXMLRoot = const (namespaced ns "ListParts" []) instance ToXML ListParts instance AWSRequest ListParts where type Sv ListParts = S3 type Rs ListParts = ListPartsResponse request = get response = xmlResponse instance FromXML ListPartsResponse where parseXML x = ListPartsResponse <$> x .@? "Bucket" <*> x .@? "Initiator" <*> x .@? "IsTruncated" <*> x .@? "Key" <*> x .@? "MaxParts" <*> x .@? "NextPartNumberMarker" <*> x .@? "Owner" <*> x .@? "PartNumberMarker" <*> parseXML x <*> x .@? "StorageClass" <*> x .@? "UploadId" instance AWSPager ListParts where page rq rs | stop (rs ^. lprIsTruncated) = Nothing | otherwise = Just $ rq & lpPartNumberMarker .~ rs ^. lprNextPartNumberMarker
dysinger/amazonka
amazonka-s3/gen/Network/AWS/S3/ListParts.hs
mpl-2.0
8,503
0
26
2,214
1,528
887
641
152
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.StorageGateway.UpdateMaintenanceStartTime -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- This operation updates a gateway\'s weekly maintenance start time -- information, including day and time of the week. The maintenance time is -- the time in your gateway\'s time zone. -- -- /See:/ <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateMaintenanceStartTime.html AWS API Reference> for UpdateMaintenanceStartTime. module Network.AWS.StorageGateway.UpdateMaintenanceStartTime ( -- * Creating a Request updateMaintenanceStartTime , UpdateMaintenanceStartTime -- * Request Lenses , umstGatewayARN , umstHourOfDay , umstMinuteOfHour , umstDayOfWeek -- * Destructuring the Response , updateMaintenanceStartTimeResponse , UpdateMaintenanceStartTimeResponse -- * Response Lenses , umstrsGatewayARN , umstrsResponseStatus ) where import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.StorageGateway.Types import Network.AWS.StorageGateway.Types.Product -- | A JSON object containing the following fields: -- -- - UpdateMaintenanceStartTimeInput$DayOfWeek -- - UpdateMaintenanceStartTimeInput$HourOfDay -- - UpdateMaintenanceStartTimeInput$MinuteOfHour -- -- /See:/ 'updateMaintenanceStartTime' smart constructor. data UpdateMaintenanceStartTime = UpdateMaintenanceStartTime' { _umstGatewayARN :: !Text , _umstHourOfDay :: !Nat , _umstMinuteOfHour :: !Nat , _umstDayOfWeek :: !Nat } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UpdateMaintenanceStartTime' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'umstGatewayARN' -- -- * 'umstHourOfDay' -- -- * 'umstMinuteOfHour' -- -- * 'umstDayOfWeek' updateMaintenanceStartTime :: Text -- ^ 'umstGatewayARN' -> Natural -- ^ 'umstHourOfDay' -> Natural -- ^ 'umstMinuteOfHour' -> Natural -- ^ 'umstDayOfWeek' -> UpdateMaintenanceStartTime updateMaintenanceStartTime pGatewayARN_ pHourOfDay_ pMinuteOfHour_ pDayOfWeek_ = UpdateMaintenanceStartTime' { _umstGatewayARN = pGatewayARN_ , _umstHourOfDay = _Nat # pHourOfDay_ , _umstMinuteOfHour = _Nat # pMinuteOfHour_ , _umstDayOfWeek = _Nat # pDayOfWeek_ } -- | Undocumented member. umstGatewayARN :: Lens' UpdateMaintenanceStartTime Text umstGatewayARN = lens _umstGatewayARN (\ s a -> s{_umstGatewayARN = a}); -- | The hour component of the maintenance start time represented as hh, -- where /hh/ is the hour (00 to 23). The hour of the day is in the time -- zone of the gateway. umstHourOfDay :: Lens' UpdateMaintenanceStartTime Natural umstHourOfDay = lens _umstHourOfDay (\ s a -> s{_umstHourOfDay = a}) . _Nat; -- | The minute component of the maintenance start time represented as /mm/, -- where /mm/ is the minute (00 to 59). The minute of the hour is in the -- time zone of the gateway. umstMinuteOfHour :: Lens' UpdateMaintenanceStartTime Natural umstMinuteOfHour = lens _umstMinuteOfHour (\ s a -> s{_umstMinuteOfHour = a}) . _Nat; -- | The maintenance start time day of the week. umstDayOfWeek :: Lens' UpdateMaintenanceStartTime Natural umstDayOfWeek = lens _umstDayOfWeek (\ s a -> s{_umstDayOfWeek = a}) . _Nat; instance AWSRequest UpdateMaintenanceStartTime where type Rs UpdateMaintenanceStartTime = UpdateMaintenanceStartTimeResponse request = postJSON storageGateway response = receiveJSON (\ s h x -> UpdateMaintenanceStartTimeResponse' <$> (x .?> "GatewayARN") <*> (pure (fromEnum s))) instance ToHeaders UpdateMaintenanceStartTime where toHeaders = const (mconcat ["X-Amz-Target" =# ("StorageGateway_20130630.UpdateMaintenanceStartTime" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON UpdateMaintenanceStartTime where toJSON UpdateMaintenanceStartTime'{..} = object (catMaybes [Just ("GatewayARN" .= _umstGatewayARN), Just ("HourOfDay" .= _umstHourOfDay), Just ("MinuteOfHour" .= _umstMinuteOfHour), Just ("DayOfWeek" .= _umstDayOfWeek)]) instance ToPath UpdateMaintenanceStartTime where toPath = const "/" instance ToQuery UpdateMaintenanceStartTime where toQuery = const mempty -- | A JSON object containing the of the gateway whose maintenance start time -- is updated. -- -- /See:/ 'updateMaintenanceStartTimeResponse' smart constructor. data UpdateMaintenanceStartTimeResponse = UpdateMaintenanceStartTimeResponse' { _umstrsGatewayARN :: !(Maybe Text) , _umstrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UpdateMaintenanceStartTimeResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'umstrsGatewayARN' -- -- * 'umstrsResponseStatus' updateMaintenanceStartTimeResponse :: Int -- ^ 'umstrsResponseStatus' -> UpdateMaintenanceStartTimeResponse updateMaintenanceStartTimeResponse pResponseStatus_ = UpdateMaintenanceStartTimeResponse' { _umstrsGatewayARN = Nothing , _umstrsResponseStatus = pResponseStatus_ } -- | Undocumented member. umstrsGatewayARN :: Lens' UpdateMaintenanceStartTimeResponse (Maybe Text) umstrsGatewayARN = lens _umstrsGatewayARN (\ s a -> s{_umstrsGatewayARN = a}); -- | The response status code. umstrsResponseStatus :: Lens' UpdateMaintenanceStartTimeResponse Int umstrsResponseStatus = lens _umstrsResponseStatus (\ s a -> s{_umstrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-storagegateway/gen/Network/AWS/StorageGateway/UpdateMaintenanceStartTime.hs
mpl-2.0
6,558
0
13
1,336
854
509
345
108
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Gmail.Users.Settings.Delegates.Create -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Adds a delegate with its verification status set directly to -- \`accepted\`, without sending any verification email. The delegate user -- must be a member of the same G Suite organization as the delegator user. -- Gmail imposes limitations on the number of delegates and delegators each -- user in a G Suite organization can have. These limits depend on your -- organization, but in general each user can have up to 25 delegates and -- up to 10 delegators. Note that a delegate user must be referred to by -- their primary email address, and not an email alias. Also note that when -- a new delegate is created, there may be up to a one minute delay before -- the new delegate is available for use. This method is only available to -- service account clients that have been delegated domain-wide authority. -- -- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.settings.delegates.create@. module Network.Google.Resource.Gmail.Users.Settings.Delegates.Create ( -- * REST Resource UsersSettingsDelegatesCreateResource -- * Creating a Request , usersSettingsDelegatesCreate , UsersSettingsDelegatesCreate -- * Request Lenses , usdcXgafv , usdcUploadProtocol , usdcAccessToken , usdcUploadType , usdcPayload , usdcUserId , usdcCallback ) where import Network.Google.Gmail.Types import Network.Google.Prelude -- | A resource alias for @gmail.users.settings.delegates.create@ method which the -- 'UsersSettingsDelegatesCreate' request conforms to. type UsersSettingsDelegatesCreateResource = "gmail" :> "v1" :> "users" :> Capture "userId" Text :> "settings" :> "delegates" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Delegate :> Post '[JSON] Delegate -- | Adds a delegate with its verification status set directly to -- \`accepted\`, without sending any verification email. The delegate user -- must be a member of the same G Suite organization as the delegator user. -- Gmail imposes limitations on the number of delegates and delegators each -- user in a G Suite organization can have. These limits depend on your -- organization, but in general each user can have up to 25 delegates and -- up to 10 delegators. Note that a delegate user must be referred to by -- their primary email address, and not an email alias. Also note that when -- a new delegate is created, there may be up to a one minute delay before -- the new delegate is available for use. This method is only available to -- service account clients that have been delegated domain-wide authority. -- -- /See:/ 'usersSettingsDelegatesCreate' smart constructor. data UsersSettingsDelegatesCreate = UsersSettingsDelegatesCreate' { _usdcXgafv :: !(Maybe Xgafv) , _usdcUploadProtocol :: !(Maybe Text) , _usdcAccessToken :: !(Maybe Text) , _usdcUploadType :: !(Maybe Text) , _usdcPayload :: !Delegate , _usdcUserId :: !Text , _usdcCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UsersSettingsDelegatesCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'usdcXgafv' -- -- * 'usdcUploadProtocol' -- -- * 'usdcAccessToken' -- -- * 'usdcUploadType' -- -- * 'usdcPayload' -- -- * 'usdcUserId' -- -- * 'usdcCallback' usersSettingsDelegatesCreate :: Delegate -- ^ 'usdcPayload' -> UsersSettingsDelegatesCreate usersSettingsDelegatesCreate pUsdcPayload_ = UsersSettingsDelegatesCreate' { _usdcXgafv = Nothing , _usdcUploadProtocol = Nothing , _usdcAccessToken = Nothing , _usdcUploadType = Nothing , _usdcPayload = pUsdcPayload_ , _usdcUserId = "me" , _usdcCallback = Nothing } -- | V1 error format. usdcXgafv :: Lens' UsersSettingsDelegatesCreate (Maybe Xgafv) usdcXgafv = lens _usdcXgafv (\ s a -> s{_usdcXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). usdcUploadProtocol :: Lens' UsersSettingsDelegatesCreate (Maybe Text) usdcUploadProtocol = lens _usdcUploadProtocol (\ s a -> s{_usdcUploadProtocol = a}) -- | OAuth access token. usdcAccessToken :: Lens' UsersSettingsDelegatesCreate (Maybe Text) usdcAccessToken = lens _usdcAccessToken (\ s a -> s{_usdcAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). usdcUploadType :: Lens' UsersSettingsDelegatesCreate (Maybe Text) usdcUploadType = lens _usdcUploadType (\ s a -> s{_usdcUploadType = a}) -- | Multipart request metadata. usdcPayload :: Lens' UsersSettingsDelegatesCreate Delegate usdcPayload = lens _usdcPayload (\ s a -> s{_usdcPayload = a}) -- | User\'s email address. The special value \"me\" can be used to indicate -- the authenticated user. usdcUserId :: Lens' UsersSettingsDelegatesCreate Text usdcUserId = lens _usdcUserId (\ s a -> s{_usdcUserId = a}) -- | JSONP usdcCallback :: Lens' UsersSettingsDelegatesCreate (Maybe Text) usdcCallback = lens _usdcCallback (\ s a -> s{_usdcCallback = a}) instance GoogleRequest UsersSettingsDelegatesCreate where type Rs UsersSettingsDelegatesCreate = Delegate type Scopes UsersSettingsDelegatesCreate = '["https://www.googleapis.com/auth/gmail.settings.sharing"] requestClient UsersSettingsDelegatesCreate'{..} = go _usdcUserId _usdcXgafv _usdcUploadProtocol _usdcAccessToken _usdcUploadType _usdcCallback (Just AltJSON) _usdcPayload gmailService where go = buildClient (Proxy :: Proxy UsersSettingsDelegatesCreateResource) mempty
brendanhay/gogol
gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Settings/Delegates/Create.hs
mpl-2.0
6,901
0
20
1,524
806
478
328
116
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Ml.Projects.Models.GetIAMPolicy -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets the access control policy for a resource. Returns an empty policy -- if the resource exists and does not have a policy set. -- -- /See:/ <https://cloud.google.com/ml/ AI Platform Training & Prediction API Reference> for @ml.projects.models.getIamPolicy@. module Network.Google.Resource.Ml.Projects.Models.GetIAMPolicy ( -- * REST Resource ProjectsModelsGetIAMPolicyResource -- * Creating a Request , projectsModelsGetIAMPolicy , ProjectsModelsGetIAMPolicy -- * Request Lenses , pmgipOptionsRequestedPolicyVersion , pmgipXgafv , pmgipUploadProtocol , pmgipAccessToken , pmgipUploadType , pmgipResource , pmgipCallback ) where import Network.Google.MachineLearning.Types import Network.Google.Prelude -- | A resource alias for @ml.projects.models.getIamPolicy@ method which the -- 'ProjectsModelsGetIAMPolicy' request conforms to. type ProjectsModelsGetIAMPolicyResource = "v1" :> CaptureMode "resource" "getIamPolicy" Text :> QueryParam "options.requestedPolicyVersion" (Textual Int32) :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] GoogleIAMV1__Policy -- | Gets the access control policy for a resource. Returns an empty policy -- if the resource exists and does not have a policy set. -- -- /See:/ 'projectsModelsGetIAMPolicy' smart constructor. data ProjectsModelsGetIAMPolicy = ProjectsModelsGetIAMPolicy' { _pmgipOptionsRequestedPolicyVersion :: !(Maybe (Textual Int32)) , _pmgipXgafv :: !(Maybe Xgafv) , _pmgipUploadProtocol :: !(Maybe Text) , _pmgipAccessToken :: !(Maybe Text) , _pmgipUploadType :: !(Maybe Text) , _pmgipResource :: !Text , _pmgipCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsModelsGetIAMPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pmgipOptionsRequestedPolicyVersion' -- -- * 'pmgipXgafv' -- -- * 'pmgipUploadProtocol' -- -- * 'pmgipAccessToken' -- -- * 'pmgipUploadType' -- -- * 'pmgipResource' -- -- * 'pmgipCallback' projectsModelsGetIAMPolicy :: Text -- ^ 'pmgipResource' -> ProjectsModelsGetIAMPolicy projectsModelsGetIAMPolicy pPmgipResource_ = ProjectsModelsGetIAMPolicy' { _pmgipOptionsRequestedPolicyVersion = Nothing , _pmgipXgafv = Nothing , _pmgipUploadProtocol = Nothing , _pmgipAccessToken = Nothing , _pmgipUploadType = Nothing , _pmgipResource = pPmgipResource_ , _pmgipCallback = Nothing } -- | Optional. The policy format version to be returned. Valid values are 0, -- 1, and 3. Requests specifying an invalid value will be rejected. -- Requests for policies with any conditional bindings must specify version -- 3. Policies without any conditional bindings may specify any valid value -- or leave the field unset. To learn which resources support conditions in -- their IAM policies, see the [IAM -- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies). pmgipOptionsRequestedPolicyVersion :: Lens' ProjectsModelsGetIAMPolicy (Maybe Int32) pmgipOptionsRequestedPolicyVersion = lens _pmgipOptionsRequestedPolicyVersion (\ s a -> s{_pmgipOptionsRequestedPolicyVersion = a}) . mapping _Coerce -- | V1 error format. pmgipXgafv :: Lens' ProjectsModelsGetIAMPolicy (Maybe Xgafv) pmgipXgafv = lens _pmgipXgafv (\ s a -> s{_pmgipXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pmgipUploadProtocol :: Lens' ProjectsModelsGetIAMPolicy (Maybe Text) pmgipUploadProtocol = lens _pmgipUploadProtocol (\ s a -> s{_pmgipUploadProtocol = a}) -- | OAuth access token. pmgipAccessToken :: Lens' ProjectsModelsGetIAMPolicy (Maybe Text) pmgipAccessToken = lens _pmgipAccessToken (\ s a -> s{_pmgipAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pmgipUploadType :: Lens' ProjectsModelsGetIAMPolicy (Maybe Text) pmgipUploadType = lens _pmgipUploadType (\ s a -> s{_pmgipUploadType = a}) -- | REQUIRED: The resource for which the policy is being requested. See the -- operation documentation for the appropriate value for this field. pmgipResource :: Lens' ProjectsModelsGetIAMPolicy Text pmgipResource = lens _pmgipResource (\ s a -> s{_pmgipResource = a}) -- | JSONP pmgipCallback :: Lens' ProjectsModelsGetIAMPolicy (Maybe Text) pmgipCallback = lens _pmgipCallback (\ s a -> s{_pmgipCallback = a}) instance GoogleRequest ProjectsModelsGetIAMPolicy where type Rs ProjectsModelsGetIAMPolicy = GoogleIAMV1__Policy type Scopes ProjectsModelsGetIAMPolicy = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsModelsGetIAMPolicy'{..} = go _pmgipResource _pmgipOptionsRequestedPolicyVersion _pmgipXgafv _pmgipUploadProtocol _pmgipAccessToken _pmgipUploadType _pmgipCallback (Just AltJSON) machineLearningService where go = buildClient (Proxy :: Proxy ProjectsModelsGetIAMPolicyResource) mempty
brendanhay/gogol
gogol-ml/gen/Network/Google/Resource/Ml/Projects/Models/GetIAMPolicy.hs
mpl-2.0
6,358
0
16
1,366
805
470
335
122
1
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-} module HLol.Data.LolStaticData where import Control.Applicative import Control.Lens import Control.Monad import Data.Aeson import qualified Data.Map as M import qualified Data.Vector as V data BlockItemDto = BlockItemDto { _count :: Int, _blockItemId :: Int } deriving (Eq, Show) makeLenses ''BlockItemDto instance FromJSON BlockItemDto where parseJSON (Object v) = BlockItemDto <$> v .: "count"<*> v .: "id" parseJSON _ = mzero data BlockDto = BlockDto { _items :: Maybe [BlockItemDto], _recMath :: Maybe Bool, _blockType :: Maybe String } deriving (Eq, Show) makeLenses ''BlockDto instance FromJSON BlockDto where parseJSON (Object v) = BlockDto <$> v .:? "items"<*> v .:? "recMath"<*> v .:? "type" parseJSON _ = mzero data SpellVarsDto = SpellVarsDto { _coeff :: [Double], _dyn :: Maybe String, _spellKey :: String, _link :: String, _ranksWith :: Maybe String } deriving (Eq, Show) makeLenses ''SpellVarsDto instance FromJSON SpellVarsDto where parseJSON (Object v) = SpellVarsDto <$> v .: "coeff"<*> v .:? "dyn"<*> v .: "key"<*> v .: "link"<*> v .:? "ranksWith" parseJSON _ = mzero data LevelTipDto = LevelTipDto { _tipEffect :: [String], _tipLabel :: [String] } deriving (Eq, Show) makeLenses ''LevelTipDto instance FromJSON LevelTipDto where parseJSON (Object v) = LevelTipDto <$> v .: "effect"<*> v .: "label" parseJSON _ = mzero data StatsDto = StatsDto { _armor :: Double, _armorperlevel :: Double, _attackdamage :: Double, _attackdamageperlevel :: Double, _attackrange :: Double, _attackspeedoffset :: Double, _attackspeedperlevel :: Double, _crit :: Double, _critperlevel :: Double, _hp :: Double, _hpperlevel :: Double, _hpregen :: Double, _hpregenperlevel :: Double, _movespeed :: Double, _mp :: Double, _mpperlevel :: Double, _mpregen :: Double, _mpregenperlevel :: Double, _spellblock :: Double, _spellblockperlevel :: Double } deriving (Eq, Show) makeLenses ''StatsDto instance FromJSON StatsDto where parseJSON (Object v) = StatsDto <$> v .: "armor"<*> v .: "armorperlevel"<*> v .: "attackdamage"<*> v .: "attackdamageperlevel"<*> v .: "attackrange"<*> v .: "attackspeedoffset"<*> v .: "attackspeedperlevel"<*> v .: "crit"<*> v .: "critperlevel"<*> v .: "hp"<*> v .: "hpperlevel"<*> v .: "hpregen"<*> v .: "hpregenperlevel"<*> v .: "movespeed"<*> v .: "mp"<*> v .: "mpperlevel"<*> v .: "mpregen"<*> v .: "mpregenperlevel"<*> v .: "spellblock"<*> v .: "spellblockperlevel" parseJSON _ = mzero data SkinDto = SkinDto { _id :: Maybe Int, _skinName :: String, _num :: Int } deriving (Eq, Show) makeLenses ''SkinDto instance FromJSON SkinDto where parseJSON (Object v) = SkinDto <$> v .: "id"<*> v .: "name"<*> v .: "num" parseJSON _ = mzero data RecommendedDto = RecommendedDto { _blocks :: [BlockDto], _champion :: String, _map :: String, _mode :: String, _priority :: Bool, _title :: String, _type :: String } deriving (Eq, Show) makeLenses ''RecommendedDto instance FromJSON RecommendedDto where parseJSON (Object v) = RecommendedDto <$> v .: "blocks"<*> v .: "champion"<*> v .: "map"<*> v .: "mode"<*> v .: "priority"<*> v .: "title"<*> v .: "type" parseJSON _ = mzero data InfoDto = InfoDto { _attack :: Int, _defense :: Int, _difficulty :: Int, _magic :: Int } deriving (Eq, Show) makeLenses ''InfoDto instance FromJSON InfoDto where parseJSON (Object v) = InfoDto <$> v .: "attack"<*> v .: "defense"<*> v .: "difficulty"<*> v .: "magic" parseJSON _ = mzero data ImageDto = ImageDto { _full :: String, _group :: String, _h :: Int, _sprite :: String, _w :: Int, _x :: Int, _y :: Int } deriving (Eq, Show) makeLenses ''ImageDto instance FromJSON ImageDto where parseJSON (Object v) = ImageDto <$> v .: "full"<*> v .: "group"<*> v .: "h"<*> v .: "sprite"<*> v .: "w"<*> v .: "x"<*> v .: "y" parseJSON _ = mzero data PassiveDto = PassiveDto { _passiveDescription :: String, _passiveImage :: ImageDto, _passiveName :: String, _passiveSanitizedDescription :: String } deriving (Eq, Show) makeLenses ''PassiveDto instance FromJSON PassiveDto where parseJSON (Object v) = PassiveDto <$> v .: "description"<*> v .: "image"<*> v .: "name"<*> v .: "sanitizedDescription" parseJSON _ = mzero data SpellRange = Self | Range [Int] deriving (Show, Eq) instance FromJSON SpellRange where parseJSON (String "self") = return Self parseJSON (Array vs) = do parsedVs <- mapM parseJSON $ V.toList vs return $ Range parsedVs parseJSON _ = mzero data ChampionSpellDto = ChampionSpellDto { _altimages :: Maybe [ImageDto], _cooldown :: [Double], _cooldownBurn :: String, _cost :: [Int], _costBurn :: String, _costType :: String, _description :: String, _effect :: [Maybe [Double]], _effectBurn :: [String], _image :: ImageDto, _key :: String, _leveltip :: LevelTipDto, _maxrank :: Int, _name :: String, _range :: SpellRange, _rangeBurn :: String, _resource :: Maybe String, _sanitizedDescription :: String, _sanitizedTooltip :: String, _tooltip :: String, _vars :: Maybe [SpellVarsDto] } deriving (Eq, Show) makeLenses ''ChampionSpellDto instance FromJSON ChampionSpellDto where parseJSON (Object v) = ChampionSpellDto <$> v .:? "altimages"<*> v .: "cooldown"<*> v .: "cooldownBurn"<*> v .: "cost"<*> v .: "costBurn"<*> v .: "costType"<*> v .: "description"<*> v .: "effect"<*> v .: "effectBurn"<*> v .: "image"<*> v .: "key"<*> v .: "leveltip"<*> v .: "maxrank"<*> v .: "name"<*> v .: "range"<*> v .: "rangeBurn"<*> v .:? "resource"<*> v .: "sanitizedDescription"<*> v .: "sanitizedTooltip"<*> v .: "tooltip"<*> v .:? "vars" parseJSON _ = mzero data ChampionDto = ChampionDto { _championAllytips :: [String], _championBlurb :: String, _championEnemytips :: [String], _championId :: Int, _championImage :: ImageDto, _championInfo :: InfoDto, _championKey :: String, _championLore :: String, _championName :: String, _championPartype :: String, _championPassive :: PassiveDto, _championRecommended :: [RecommendedDto], _championSkins :: [SkinDto], _championSpells :: [ChampionSpellDto], _championStats :: StatsDto, _championTags :: [String], _championTitle :: String } deriving (Eq, Show) makeLenses ''ChampionDto instance FromJSON ChampionDto where parseJSON (Object v) = ChampionDto <$> v .: "allytips"<*> v .: "blurb"<*> v .: "enemytips"<*> v .: "id"<*> v .: "image"<*> v .: "info"<*> v .: "key"<*> v .: "lore"<*> v .: "name"<*> v .: "partype"<*> v .: "passive"<*> v .: "recommended"<*> v .: "skins"<*> v .: "spells"<*> v .: "stats"<*> v .: "tags"<*> v .: "title" parseJSON _ = mzero data ChampionListDto = ChampionListDto { _data :: M.Map String ChampionDto, _format :: String, _keys :: M.Map String String, _listType :: String, _version :: String } deriving (Eq, Show) makeLenses ''ChampionListDto instance FromJSON ChampionListDto where parseJSON (Object v) = ChampionListDto <$> v .: "data"<*> v .: "format"<*> v .: "keys"<*> v .: "type"<*> v .: "version" parseJSON _ = mzero data MetaDataDto = MetaDataDto { _isRune :: Bool, _tier :: String, _metaDataType :: String } deriving (Eq, Show) makeLenses ''MetaDataDto instance FromJSON MetaDataDto where parseJSON (Object v) = MetaDataDto <$> v .: "isRune"<*> v .: "tier"<*> v .: "type" parseJSON _ = mzero data GoldDto = GoldDto { _base :: Int, _purchasable :: Bool, _sell :: Int, _total :: Int } deriving (Eq, Show) makeLenses ''GoldDto instance FromJSON GoldDto where parseJSON (Object v) = GoldDto <$> v .: "base"<*> v .: "purchasable"<*> v .: "sell"<*> v .: "total" parseJSON _ = mzero type BasicDataStatsDto = M.Map String Double data ItemTreeDto = ItemTreeDto { _header :: String, _tags :: [String] } deriving (Eq, Show) makeLenses ''ItemTreeDto instance FromJSON ItemTreeDto where parseJSON (Object v) = ItemTreeDto <$> v .: "header"<*> v .: "tags" parseJSON _ = mzero data ItemDto = ItemDto { _colloq :: Maybe String, _consumeOnFull :: Maybe Bool, _consumed :: Maybe Bool, _depth :: Maybe Int, _itemDescription :: String, _itemEffect :: Maybe (M.Map String String), _from :: Maybe [String], _gold :: GoldDto, _itemGroup :: Maybe String, _hideFromAll :: Maybe Bool, _itemId :: Int, _itemImage :: ImageDto, _inStore :: Maybe Bool, _into :: Maybe [String], _maps :: Maybe (M.Map String Bool), _itemName :: String, _plaintext :: Maybe String, _requiredChampion :: Maybe String, _rune :: Maybe MetaDataDto, _itemSanitizedDescription :: String, _specialRecipe :: Maybe Int, _stacks :: Maybe Int, _stats :: BasicDataStatsDto, _itemTags :: Maybe [String] } deriving (Eq, Show) makeLenses ''ItemDto instance FromJSON ItemDto where parseJSON (Object v) = ItemDto <$> v .:? "colloq"<*> v .:? "consumeOnFull"<*> v .:? "consumed"<*> v .:? "depth"<*> v .: "description"<*> v .:? "effect"<*> v .:? "from"<*> v .: "gold"<*> v .:? "group"<*> v .:? "hideFromAll"<*> v .: "id"<*> v .: "image"<*> v .:? "inStore"<*> v .:? "into"<*> v .:? "maps"<*> v .: "name"<*> v .:? "plaintext"<*> v .:? "requiredChampion"<*> v .:? "rune"<*> v .: "sanitizedDescription"<*> v .:? "specialRecipe"<*> v .:? "stacks"<*> v .: "stats"<*> v .:? "tags" parseJSON _ = mzero data GroupDto = GroupDto { _MaxGroupOwnable :: Maybe String, _groupKey :: String } deriving (Eq, Show) makeLenses ''GroupDto instance FromJSON GroupDto where parseJSON (Object v) = GroupDto <$> v .:? "MaxGroupOwnable"<*> v .: "key" parseJSON _ = mzero data BasicDataDto = BasicDataDto { _bdataColloq :: Maybe String, _bdataConsumeOnFull :: Bool, _bdataConsumed :: Bool, _bdataDepth :: Int, _bdataDescription :: Maybe String, _bdataFrom :: Maybe [String], _bdataGold :: GoldDto, _bdataGroup :: Maybe String, _bdataHideFromAll :: Bool, _bdataId :: Int, _bdataImage :: Maybe ImageDto, _bdataInStore :: Bool, _bdataInto :: Maybe [String], _bdataMaps :: M.Map String Bool, _bdataName :: Maybe String, _bataPlaintext :: Maybe String, _bdataRequiredChampion :: Maybe String, _bdataRune :: MetaDataDto, _bdataSanitizedDescription :: Maybe String, _bdataSpecialRecipe :: Int, _bdataStacks :: Int, _bdataStats :: BasicDataStatsDto, _bdataTags :: Maybe [String] } deriving (Eq, Show) makeLenses ''BasicDataDto instance FromJSON BasicDataDto where parseJSON (Object v) = BasicDataDto <$> v .:? "colloq"<*> v .: "consumeOnFull"<*> v .: "consumed"<*> v .: "depth"<*> v .:? "description"<*> v .:? "from"<*> v .: "gold"<*> v .:? "group"<*> v .: "hideFromAll"<*> v .: "id"<*> v .:? "image"<*> v .: "inStore"<*> v .:? "into"<*> v .: "maps"<*> v .:? "name"<*> v .:? "plaintext"<*> v .:? "requiredChampion"<*> v .: "rune"<*> v .:? "sanitizedDescription"<*> v .: "specialRecipe"<*> v .: "stacks"<*> v .: "stats"<*> v .:? "tags" parseJSON _ = mzero data ItemListDto = ItemListDto { _basic :: BasicDataDto, _itemListData :: M.Map String ItemDto, _groups :: [GroupDto], _tree :: [ItemTreeDto], _itemListType :: String, _itemListVersion :: String } deriving (Eq, Show) makeLenses ''ItemListDto instance FromJSON ItemListDto where parseJSON (Object v) = ItemListDto <$> v .: "basic"<*> v .: "data"<*> v .: "groups"<*> v .: "tree"<*> v .: "type"<*> v .: "version" parseJSON _ = mzero data MasteryTreeItemDto = MasteryTreeItemDto { _masteryTreeItemId :: Int, _masteryTreeItemPrereq :: String } deriving (Eq, Show) makeLenses ''MasteryTreeItemDto instance FromJSON MasteryTreeItemDto where parseJSON (Object v) = MasteryTreeItemDto <$> v .: "masteryId"<*> v .: "prereq" parseJSON _ = mzero data MasteryTreeListDto = MasteryTreeListDto { _masteryTreeItems :: [Maybe MasteryTreeItemDto] } deriving (Eq, Show) makeLenses ''MasteryTreeListDto instance FromJSON MasteryTreeListDto where parseJSON (Object v) = MasteryTreeListDto <$> v .: "masteryTreeItems" parseJSON _ = mzero data MasteryTreeDto = MasteryTreeDto { _masteryTreeDefense :: [MasteryTreeListDto], _masteryTreeOffense :: [MasteryTreeListDto], _masteryTreeUtility :: [MasteryTreeListDto] } deriving (Eq, Show) makeLenses ''MasteryTreeDto instance FromJSON MasteryTreeDto where parseJSON (Object v) = MasteryTreeDto <$> v .: "Defense"<*> v .: "Offense"<*> v .: "Utility" parseJSON _ = mzero data MasteryDto = MasteryDto { _masteryId :: Int, _masteryRank :: Maybe Int } deriving (Eq, Show) makeLenses ''MasteryDto instance FromJSON MasteryDto where parseJSON (Object v) = MasteryDto <$> v .: "id"<*> v .:? "rank" parseJSON _ = mzero data MasteryListDto = MasteryListDto { _masteryListData :: M.Map String MasteryDto, _masteryListTree :: MasteryTreeDto, _masteryListType :: String, _masteryListVersion :: String } deriving (Eq, Show) makeLenses ''MasteryListDto instance FromJSON MasteryListDto where parseJSON (Object v) = MasteryListDto <$> v .: "data"<*> v .: "tree"<*> v .: "type"<*> v .: "version" parseJSON _ = mzero data RealmDto = RealmDto { _cdn :: String, _css :: String, _dd :: String, _l :: String, _lg :: String, _n :: M.Map String String, _profileiconmax :: Int, _store :: Maybe String, _v :: String } deriving (Eq, Show) makeLenses ''RealmDto instance FromJSON RealmDto where parseJSON (Object o) = RealmDto <$> o .: "cdn"<*> o .: "css"<*> o .: "dd"<*> o .: "l"<*> o .: "lg"<*> o .: "n"<*> o .: "profileiconmax"<*> o .:? "store"<*> o .: "v" parseJSON _ = mzero data RuneDto = RuneDto { _runeDescription :: String, _runeId :: Int, _runeName :: String, _runeMeta :: MetaDataDto } deriving (Eq, Show) makeLenses ''RuneDto instance FromJSON RuneDto where parseJSON (Object o) = RuneDto <$> o .: "description"<*> o .: "id"<*> o .: "name"<*> o .: "rune" parseJSON _ = mzero data RuneListDto = RuneListDto { _runeListBasic :: BasicDataDto, _runeListData :: M.Map String RuneDto, _runeListType :: String, _runeListVersion :: String } deriving (Eq, Show) makeLenses ''RuneListDto instance FromJSON RuneListDto where parseJSON (Object o) = RuneListDto <$> o .: "basic"<*> o .: "data"<*> o .: "type"<*> o .: "version" parseJSON _ = mzero data SummonerSpellDto = SummonerSpellDto { _summonerSpellDescription :: String, _summonerSpellId :: Int, _summonerSpellKey :: String, _summonerSpellName :: String, _summonerSpellSummonerLevel :: Int } deriving (Eq, Show) makeLenses ''SummonerSpellDto instance FromJSON SummonerSpellDto where parseJSON (Object o) = SummonerSpellDto <$> o .: "description"<*> o .: "id"<*> o .: "key"<*> o .: "name"<*> o .: "summonerLevel" parseJSON _ = mzero data SummonerSpellListDto = SummonerSpellListDto { _summonerSpellListData :: M.Map String SummonerSpellDto, _summonerSpellListType :: String, _summonerSpellListVersion :: String } deriving (Eq, Show) makeLenses ''SummonerSpellListDto instance FromJSON SummonerSpellListDto where parseJSON (Object o) = SummonerSpellListDto <$> o .: "data"<*> o .: "type"<*> o .: "version" parseJSON _ = mzero
tetigi/hlol
src/HLol/Data/LolStaticData.hs
agpl-3.0
17,202
0
53
4,854
5,008
2,703
2,305
597
0
module Data.Vector.DynamicTimeWarping where import Control.Monad (forM_) import qualified Data.Vector.Generic as V import qualified Data.Array.ST as ST import qualified Data.Array.MArray as MArray import qualified Data.Array.Base as Arr -- | Calculate the modification distance of two vectors. -- -- The sequences don't need to be of equal length, multiple points of one -- sequence can be matched to the same point of the other sequence. The matches -- must be in order though. distanceBy :: V.Vector v a => (a -> a -> Float) -> v a -> v a -> Float distanceBy d left right | V.null left || V.null right = 1/0 | otherwise = -- The algorithm is extremely simple in an imperative framework unless we -- carefully craft the memoization. Even then the mutable array is way -- faster. let lenl = V.length left lenr = V.length right def = 1/0 tabl = ST.runSTUArray $ do table <- MArray.newArray_ ((0,0), (lenl, lenr)) let write = MArray.writeArray table read_ = MArray.readArray table write (0,0) 0 forM_ [1..lenl] $ \i -> write (i, 0) def forM_ [1..lenr] $ \j -> write (0, j) def forM_ [1..lenl] $ \i -> forM_ [1..lenr] $ \j -> do ins <- read_ (i-1,j) del <- read_ (i,j-1) mat <- read_ (i-1,j-1) let cost = d (left V.! (i-1)) (right V.! (j-1)) rec = ins `min` del `min` mat write (i,j) $ cost + rec return table in tabl Arr.! (lenl, lenr)
zombiecalypse/DynamicTimeWarp
src/Data/Vector/DynamicTimeWarping.hs
lgpl-3.0
1,567
0
26
470
529
284
245
30
1
module Main where import qualified MAlonzo.Code.Qgetline as Q main :: IO () main = Q.main
haroldcarr/learn-haskell-coq-ml-etc
agda/examples-that-run/getline/app/Main.hs
unlicense
92
0
6
17
30
19
11
4
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} module Foundation where import Import.NoFoundation import Database.Persist.Sql (ConnectionPool, runSqlPool) import Text.Hamlet (hamletFile) import Text.Jasmine (minifym) -- Used only when in "auth-dummy-login" setting is enabled. import Yesod.Auth.Dummy import Yesod.Auth.OpenId (authOpenId, IdentifierType (Claimed)) import Yesod.Default.Util (addStaticContentExternal) import Yesod.Core.Types (Logger) import qualified Yesod.Core.Unsafe as Unsafe import qualified Data.CaseInsensitive as CI import qualified Data.Text.Encoding as TE -- | The foundation datatype for your application. This can be a good place to -- keep settings and values requiring initialization before your application -- starts running, such as database connections. Every handler will have -- access to the data present here. data App = App { appSettings :: AppSettings , appStatic :: Static -- ^ Settings for static file serving. , appConnPool :: ConnectionPool -- ^ Database connection pool. , appHttpManager :: Manager , appLogger :: Logger } data MenuItem = MenuItem { menuItemLabel :: Text , menuItemRoute :: Route App , menuItemAccessCallback :: Bool } data MenuTypes = NavbarLeft MenuItem | NavbarRight MenuItem -- This is where we define all of the routes in our application. For a full -- explanation of the syntax, please see: -- http://www.yesodweb.com/book/routing-and-handlers -- -- Note that this is really half the story; in Application.hs, mkYesodDispatch -- generates the rest of the code. Please see the following documentation -- for an explanation for this split: -- http://www.yesodweb.com/book/scaffolding-and-the-site-template#scaffolding-and-the-site-template_foundation_and_application_modules -- -- This function also generates the following type synonyms: -- type Handler = HandlerT App IO -- type Widget = WidgetT App IO () mkYesodData "App" $(parseRoutesFile "config/routes") -- | A convenient synonym for creating forms. type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget) -- Please see the documentation for the Yesod typeclass. There are a number -- of settings which can be configured by overriding methods here. instance Yesod App where -- Controls the base of generated URLs. For more information on modifying, -- see: https://github.com/yesodweb/yesod/wiki/Overriding-approot approot = ApprootRequest $ \app req -> case appRoot $ appSettings app of Nothing -> getApprootText guessApproot app req Just root -> root -- Store session data on the client in encrypted cookies, -- default session idle timeout is 120 minutes makeSessionBackend _ = Just <$> defaultClientSessionBackend 120 -- timeout in minutes "config/client_session_key.aes" -- Yesod Middleware allows you to run code before and after each handler function. -- The defaultYesodMiddleware adds the response header "Vary: Accept, Accept-Language" and performs authorization checks. -- Some users may also want to add the defaultCsrfMiddleware, which: -- a) Sets a cookie with a CSRF token in it. -- b) Validates that incoming write requests include that token in either a header or POST parameter. -- To add it, chain it together with the defaultMiddleware: yesodMiddleware = defaultYesodMiddleware . defaultCsrfMiddleware -- For details, see the CSRF documentation in the Yesod.Core.Handler module of the yesod-core package. yesodMiddleware = defaultYesodMiddleware defaultLayout widget = do master <- getYesod mmsg <- getMessage muser <- maybeAuthPair mcurrentRoute <- getCurrentRoute -- Get the breadcrumbs, as defined in the YesodBreadcrumbs instance. (title, parents) <- breadcrumbs -- Define the menu items of the header. let menuItems = [ NavbarLeft $ MenuItem { menuItemLabel = "Home" , menuItemRoute = HomeR , menuItemAccessCallback = True } , NavbarLeft $ MenuItem { menuItemLabel = "Profile" , menuItemRoute = ProfileR , menuItemAccessCallback = isJust muser } , NavbarRight $ MenuItem { menuItemLabel = "Login" , menuItemRoute = AuthR LoginR , menuItemAccessCallback = isNothing muser } , NavbarRight $ MenuItem { menuItemLabel = "Logout" , menuItemRoute = AuthR LogoutR , menuItemAccessCallback = isJust muser } ] let navbarLeftMenuItems = [x | NavbarLeft x <- menuItems] let navbarRightMenuItems = [x | NavbarRight x <- menuItems] let navbarLeftFilteredMenuItems = [x | x <- navbarLeftMenuItems, menuItemAccessCallback x] let navbarRightFilteredMenuItems = [x | x <- navbarRightMenuItems, menuItemAccessCallback x] -- We break up the default layout into two components: -- default-layout is the contents of the body tag, and -- default-layout-wrapper is the entire page. Since the final -- value passed to hamletToRepHtml cannot be a widget, this allows -- you to use normal widget features in default-layout. pc <- widgetToPageContent $ do addStylesheet $ StaticR css_bootstrap_css $(widgetFile "default-layout") withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet") -- The page to be redirected to when authentication is required. authRoute _ = Just $ AuthR LoginR -- Routes not requiring authentication. isAuthorized (AuthR _) _ = return Authorized isAuthorized CommentR _ = return Authorized isAuthorized HomeR _ = return Authorized isAuthorized FaviconR _ = return Authorized isAuthorized RobotsR _ = return Authorized isAuthorized (StaticR _) _ = return Authorized isAuthorized BowlR _ = return Authorized isAuthorized ProfileR _ = isAuthenticated -- This function creates static content files in the static folder -- and names them based on a hash of their content. This allows -- expiration dates to be set far in the future without worry of -- users receiving stale content. addStaticContent ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . flip StaticRoute []) ext mime content where -- Generate a unique filename based on the content itself genFileName lbs = "autogen-" ++ base64md5 lbs -- What messages should be logged. The following includes all messages when -- in development, and warnings and errors in production. shouldLog app _source level = appShouldLogAll (appSettings app) || level == LevelWarn || level == LevelError makeLogger = return . appLogger -- Define breadcrumbs. instance YesodBreadcrumbs App where breadcrumb HomeR = return ("Home", Nothing) breadcrumb (AuthR _) = return ("Login", Just HomeR) breadcrumb ProfileR = return ("Profile", Just HomeR) breadcrumb _ = return ("home", Nothing) -- How to run database actions. instance YesodPersist App where type YesodPersistBackend App = SqlBackend runDB action = do master <- getYesod runSqlPool action $ appConnPool master instance YesodPersistRunner App where getDBRunner = defaultGetDBRunner appConnPool instance YesodAuth App where type AuthId App = UserId -- Where to send a user after successful login loginDest _ = HomeR -- Where to send a user after logout logoutDest _ = HomeR -- Override the above two destinations when a Referer: header is present redirectToReferer _ = True authenticate creds = runDB $ do x <- getBy $ UniqueUser $ credsIdent creds case x of Just (Entity uid _) -> return $ Authenticated uid Nothing -> Authenticated <$> insert User { userIdent = credsIdent creds , userPassword = Nothing } -- You can add other plugins like Google Email, email or OAuth here authPlugins app = [authOpenId Claimed []] ++ extraAuthPlugins -- Enable authDummy login if enabled. where extraAuthPlugins = [authDummy | appAuthDummyLogin $ appSettings app] authHttpManager = getHttpManager -- | Access function to determine if a user is logged in. isAuthenticated :: Handler AuthResult isAuthenticated = do muid <- maybeAuthId return $ case muid of Nothing -> Unauthorized "You must login to access this page" Just _ -> Authorized instance YesodAuthPersist App -- This instance is required to use forms. You can modify renderMessage to -- achieve customized and internationalized form validation messages. instance RenderMessage App FormMessage where renderMessage _ _ = defaultFormMessage -- Useful when writing code that is re-usable outside of the Handler context. -- An example is background jobs that send email. -- This can also be useful for writing code that works across multiple Yesod applications. instance HasHttpManager App where getHttpManager = appHttpManager unsafeHandler :: App -> Handler a -> IO a unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger -- Note: Some functionality previously present in the scaffolding has been -- moved to documentation in the Wiki. Following are some hopefully helpful -- links: -- -- https://github.com/yesodweb/yesod/wiki/Sending-email -- https://github.com/yesodweb/yesod/wiki/Serve-static-files-from-a-separate-domain -- https://github.com/yesodweb/yesod/wiki/i18n-messages-in-the-scaffolding
SaintOlga/FruitHools
src/Foundation.hs
apache-2.0
10,243
0
16
2,548
1,431
776
655
139
2
-- | Exporting records. module Bug6( A(A), B(B), b, C(C,c1,c2), D(D,d1), E(E) ) where -- | -- This record is exported without its field data A = A { a :: Int } -- | -- .. with its field, but the field is named separately in the export list -- (should still be visible as a field name) data B = B { b :: Int } -- | -- .. with fields names as subordinate names in the export data C = C { c1 :: Int, c2 :: Int } -- | -- .. with only some of the fields exported (we can't handle this one - -- how do we render the declaration?) data D = D { d1 :: Int, d2 :: Int } -- | a newtype with a field newtype E = E { e :: Int }
nominolo/haddock2
examples/Bug6.hs
bsd-2-clause
620
0
8
150
147
102
45
16
0
module Handler.Item where import Import import Yesod.Form import qualified Data.Text as T import Lol.Items import Widget data ItemParams = ItemParams { ipItem :: Item } itemChoices :: [(Text, Item)] itemChoices = let itemList = [Empty ..] in zip (map (T.pack . show) itemList) itemList itemForm :: AForm LollerSite LollerSite ItemParams itemForm = ItemParams <$> areq (selectField itemChoices) "Item" (Just RubyCrystal) getItemR :: Handler RepHtml getItemR = do ((results, form), enctype) <- runFormGet $ renderDivs itemForm defaultLayout $ do setTitle "Lollerskates ~ Item Statistics" item <- case results of FormSuccess ip -> return $ ipItem ip _ -> return RubyCrystal $(widgetFile "item")
MostAwesomeDude/lollerskates
Handler/Item.hs
bsd-2-clause
764
0
15
173
239
126
113
-1
-1
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} -- | Generic methods for CouchDB documents. Unlike explicit, generic methods -- uses "Data.Generic". -- -- > {-# LANGUAGE DeriveDataTypeable #-} -- > {-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} -- > -- > import Control.Monad.IO.Class (liftIO) -- > import Data.Generic (Data, Typeable) -- > import Database.CouchDB.Conduit -- > import Database.CouchDB.Conduit.Generic -- > -- > -- | Our doc with instances -- > data D = D { f1 :: Int, f2 :: String } deriving (Show, Data, Typeable) -- > -- > runCouch def $ do -- > -- Put new doc and update it -- > rev1 <- couchPut "mydb" "my-doc1" "" [] $ D 123 "str" -- > rev2 <- couchPut "mydb" "my-doc1" rev1 [] $ D 1234 "another" -- > -- > -- get it and print -- > (rev3, d1 :: D) <- couchGet "mydb" "my-doc1" [] -- > liftIO $ print d1 -- > -- > -- update it in brute-force manner -- > couchPut' "mydb" "my-doc1" [] $ D 12345 "third" -- notice - no rev -- > -- > -- get revision and delete -- > rev3 <- couchRev "mydb" "my-doc1" -- > couchDelete "mydb" "my-doc1" rev3 -- -- The main advantage of this approach in the absence of tonns of -- boilerplate code. The main disadvantage is inability to influence the -- process of translation to and from JSON. -- -- For details of types see "Data.Aeson.Generic". To work with documents in -- explicit manner, look at "Database.CouchDB.Conduit.Explicit". module Database.CouchDB.Conduit.Generic ( -- * Accessing documents couchGet, -- * Manipulating documents couchPut, couchPut_, couchPut', -- * Working with views #view# toType ) where import Data.Generics (Data) import qualified Data.Aeson as A import qualified Data.Aeson.Generic as AG import Data.Conduit (Conduit, MonadResource) import Network.HTTP.Types (Query) import Database.CouchDB.Conduit.Internal.Connection (MonadCouch(..), Path, mkPath, Revision) import Database.CouchDB.Conduit.Internal.Doc (couchGetWith, couchPutWith, couchPutWith_, couchPutWith') import Database.CouchDB.Conduit.Internal.View (toTypeWith) -- | Load a single object from couch DB. couchGet :: (MonadCouch m, Data a) => Path -- ^ Database -> Path -- ^ Document path -> Query -- ^ Query -> m (Revision, a) couchGet db p = couchGetWith AG.fromJSON (mkPath [db, p]) -- | Put an object in Couch DB with revision, returning the new Revision. couchPut :: (MonadCouch m, Data a) => Path -- ^ Database -> Path -- ^ Document path -> Revision -- ^ Document revision. For new docs provide empty string. -> Query -- ^ Query arguments. -> a -- ^ The object to store. -> m Revision couchPut db p = couchPutWith AG.encode (mkPath [db, p]) -- | \"Don't care\" version of 'couchPut'. Creates document only in its -- absence. couchPut_ :: (MonadCouch m, Data a) => Path -- ^ Database -> Path -- ^ Document path -> Query -- ^ Query arguments. -> a -- ^ The object to store. -> m Revision couchPut_ db p = couchPutWith_ AG.encode (mkPath [db, p]) -- | Brute force version of 'couchPut'. Creates a document regardless of -- presence. couchPut' :: (MonadCouch m, Data a) => Path -- ^ Database -> Path -- ^ Document path -> Query -- ^ Query arguments. -> a -- ^ The object to store. -> m Revision couchPut' db p = couchPutWith' AG.encode (mkPath [db, p]) ------------------------------------------------------------------------------ -- View conduit ------------------------------------------------------------------------------ -- | Convert CouchDB view row or row value from 'Database.CouchDB.Conduit.View' -- to concrete type. -- -- > res <- couchView "mydesign" "myview" [] $ rowValue =$= toType =$ consume toType :: (MonadResource m, Data a) => Conduit A.Value m a toType = toTypeWith AG.fromJSON
lostbean/neo4j-conduit
src/Database/CouchDB/Conduit/Generic.hs
bsd-2-clause
4,173
0
11
1,096
523
326
197
47
1
{-| Implementation of the Ganeti network objects. This is does not (yet) cover all methods that are provided in the corresponding python implementation (network.py). -} {- Copyright (C) 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.Network ( AddressPool(..) , createAddressPool , bitStringToBitVector , allReservations , getReservedCount , getFreeCount , isFull , getMap , networkIsValid ) where import qualified Data.Vector.Unboxed as V import Ganeti.Objects import Ganeti.Utils (b64StringToBitString) -- | An address pool, holding a network plus internal and external -- reservations. data AddressPool = AddressPool { network :: Network, reservations :: V.Vector Bool, extReservations :: V.Vector Bool } deriving (Show) -- | Create an address pool from a network. createAddressPool :: Network -> Maybe AddressPool createAddressPool n | networkIsValid n = let res = maybeStr2BitVec $ networkReservations n ext_res = maybeStr2BitVec $ networkExtReservations n in Just AddressPool { reservations = res , extReservations = ext_res , network = n } | otherwise = Nothing -- | Checks the consistency of the network object. So far, only checks the -- length of the reservation strings. networkIsValid :: Network -> Bool networkIsValid n = sameLength (networkReservations n) (networkExtReservations n) -- | Checks if two maybe strings are both nothing or of equal length. sameLength :: Maybe String -> Maybe String -> Bool sameLength Nothing Nothing = True sameLength (Just s1) (Just s2) = length s1 == length s2 sameLength _ _ = False -- | Converts a maybe bit string to a bit vector. Returns an empty bit vector on -- nothing. maybeStr2BitVec :: Maybe String -> V.Vector Bool maybeStr2BitVec (Just s) = bitStringToBitVector $ b64StringToBitString s maybeStr2BitVec Nothing = V.fromList ([]::[Bool]) -- | Converts a string to a bit vector. The character '0' is interpreted -- as 'False', all others as 'True'. bitStringToBitVector :: String -> V.Vector Bool bitStringToBitVector = V.fromList . map (/= '0') -- | Get a bit vector of all reservations (internal and external) combined. allReservations :: AddressPool -> V.Vector Bool allReservations a = V.zipWith (||) (reservations a) (extReservations a) -- | Get the count of reserved addresses. getReservedCount :: AddressPool -> Int getReservedCount = V.length . V.filter (== True) . allReservations -- | Get the count of free addresses. getFreeCount :: AddressPool -> Int getFreeCount = V.length . V.filter (== False) . allReservations -- | Check whether the network is full. isFull :: AddressPool -> Bool isFull = V.and . allReservations -- | Return a textual representation of the network's occupation status. getMap :: AddressPool -> String getMap = V.toList . V.map mapPixel . allReservations where mapPixel c = if c then 'X' else '.'
apyrgio/snf-ganeti
src/Ganeti/Network.hs
bsd-2-clause
4,266
0
11
842
592
323
269
49
2
{-# Language GADTs, FlexibleContexts #-} {- TODO: - Correctly get number of threads, lengths (Cheating with this all over). - Support kernels that takes other arrays than just Arrays of int. - Output to the intermediate CoordC language instead of to strings. - GlobalArrays as they are now, just an identifier, or something like GlobalArray Name Size Type Etc - Give functions proper function-head - How to call the resulting coordinations function from Haskell - input is not fetched from the correct place if id is used as input transform - Figure out what parameters the coordination function should take for good flexibility (The generated C function that calls kernels) - What information are useful in the coordination layer. # number of elements a Kernel operates on is more useful than number of threads. - But a kernel might take many input arrays and those may be of different length. (for example a kernel taking a 256 elements array and an 128 element array) -- TODO: Something like this ? (Ok ?) runKC :: (GlobalArray a -> KC (GlobalArray b)) -> SomeKindOfHaskellArray a -> SomeKindOfHaskellArray -- TODO: Look at all of this again, with the new "GlobalArrays" from Obsidian.GCDObsidian.Arrays in mind. -- TODO: ALSO! see if the new version of Foreign.CUDA works properly on never CUDA versions. If it does se if it can be used to launch Obsidian kernels somehow. -} module Obsidian.Coordination.Array where import Obsidian.Coordination.CoordC -- future im representation import Obsidian.GCDObsidian.Exp import Obsidian.GCDObsidian.Kernel import Obsidian.GCDObsidian.Array import qualified Obsidian.GCDObsidian.Library as Lib import Obsidian.GCDObsidian.Sync import Obsidian.GCDObsidian.Program import Obsidian.GCDObsidian.Library import qualified Obsidian.GCDObsidian.CodeGen.CUDA as CUDA import qualified Obsidian.GCDObsidian.CodeGen.InOut as InOut import Obsidian.GCDObsidian.Types import Obsidian.GCDObsidian.Globs import Control.Monad.Writer import Data.Word import qualified Data.Map as Map import Prelude hiding (zipWith) import Control.Monad.State import Control.Monad.Writer bid :: Exp Word32 bid = variable "bid" bwd :: Exp Word32 bwd = variable "blockDim.x" gwd :: Exp Word32 gwd = variable "gridDim.x" standardInput :: Array (Exp Int) standardInput = Array (\tix-> index "input" ((bid*bwd)+tix)) 256 revblocks :: Array a -> Array a revblocks (Array ixf n) = Array (\tix -> ixf (((gwd - bid - 1)*(fromIntegral n)) + tix)) n stdIn :: Word32 -> Exp Word32 -> Exp Word32 stdIn n tix = (bid*(fromIntegral n)) + tix stdOut :: Word32 -> Exp Word32 -> Exp Word32 stdOut n tix = (bid *(fromIntegral n)) + tix ---------------------------------------------------------------------------- -- myKern :: Array (Exp Int) -> Kernel (Array (Exp Int)) myKern = pure Lib.rev ->- sync ->- sync ->- sync ---------------------------------------------------------------------------- -- newtype GlobalArray a = GlobalArray Int -- Just an identifier -- data GlobalArray a = GlobalArray Name Size Type Etc idOf (GlobalArray i) = i data KC a where Input :: GlobalArray a -> KC (GlobalArray a) -- Map a single input array - single output array kernel over a global array LaunchUn :: (Scalar a, Scalar b) => Int -- number of blocks (Could be a runtime value, perhaps) -> Int -- number of Elements that this kernel process -> (Exp Word32 -> Exp Word32) -- Transform array on input -> (Array (Exp a) -> Kernel (Array (Exp b))) -- kernel to apply -> (Exp Word32 -> Exp Word32) -- Transform array on output -> KC (GlobalArray (Exp a)) -- Input array -> KC (GlobalArray (Exp b)) -- Result array WriteResult :: Int -> Int -> KC (GlobalArray a) -> KC () {- TODO: This seems very hard to expand upon. Just adding a "LaunchBin" turns complicated. Some other way of taking care of the in and out transformations are needed. Would be cool if the transformation could be "attached" to the GlobalArrays in some way. The problem is that the code that implements the transformation must be internalized into the kernel (That is why they are now specified like this). -} ---------------------------------------------------------------------------- -- Kernel code to Kernel code map ... awful right ? type KernelMap = Map.Map String (String, String, Word32, Word32) -- code name threads shared ---------------------------------------------------------------------------- -- generate coordination code + kernels run :: (GlobalArray (Exp Int) -> KC ()) -> (KernelMap,String) run coord = (km,head ++ body ++ end ) where ((_,_,km),body) = runKCM (coord (GlobalArray undefined)) (0,0) (Map.empty) head = "void coord(int *input0, int input0size,int *output0, int output0size){\n" end = "\n}" run_ k = "/* Kernels */\n" ++ concat kernels ++ "/* Coordination */\n" ++ prg where kernels = map (\(x,_,_,_) -> x) (Map.elems km) -- (km,prg) = run k run' k = do putStrLn "/* Kernels */" sequence_$ map putStrLn kernels putStrLn "/* Coordination */" putStrLn prg where kernels = map (\(x,_,_,_) -> x) (Map.elems km) -- ((_,_,km),prg) = runKCM k (0,0) (Map.empty) -- will only work for integers right now... (fix , how ) runKCM :: KC a -> (Int,Int) -> KernelMap -> ((a,(Int,Int),KernelMap) ,String) runKCM (Input arr) (ai,ki) km = ((GlobalArray ai,(ai+1,ki),km) ,allocate ++ copy) where allocate = allocInput (GlobalArray ai) copy = copyInput (GlobalArray ai) runKCM (WriteResult blocks elems arr) ids km = (((),ids',km'),prg ++ (writeResult res blocks elems)) -- CHEATING where ((res,ids',km'),prg) = runKCM arr ids km runKCM (LaunchUn blocks elems inf k outf i) ids km = result where -- Generate kernel for lookup purposese kern = ((pure inputTransform ->- k ->- pOutput outf) (Array (\ix -> index "input0" ix) (fromIntegral elems))) inputTransform = \arr -> Array (\ix -> arr ! (inf ix)) (len arr) ((outArr,_),_) = runKernel kern (kernel,_,_) = CUDA.genKernel_ "gen" kern [("input0",Int)] -- type ?? [("output0",Int)] (newids,newkm,newprg) = -- Has Kernel already been generated ? case Map.lookup kernel km' of Nothing -> let id = snd ids' -- Generate kernel again. with different name, for insertion. -- (This should be improved upon) kernelIns' = CUDA.genKernel_ ("gen" ++ show id) kern [("input0",Pointer Int)] -- type ?? [("output0",Pointer Int)] (str,threads,sm) = kernelIns' kernelIns = (str,"gen" ++ show id,threads, sm) -- TODO CLEANUP in ((fst ids',id+1),Map.insert kernel kernelIns km', call ("gen" ++ show id) blocks threads sm (idOf res) (idOf newImm) ) --add one kernel (Just (_,kernNom,threads,sm)) -> (ids',km',call kernNom blocks threads sm (idOf res) (idOf newImm)) --return excisting -- Generate the input to this stage ((res,ids', km'),prg) = runKCM i ids km newImm = GlobalArray (fst newids) allocprg = allocImm newImm (fromIntegral (len outArr)*blocks) result = ((newImm ,(fst newids +1,snd newids),newkm),allocprg ++ "\n"++ prg ++ " \n" ++ newprg ++ "\n") allocInput (GlobalArray id) = " int* dinput"++ show id ++ ";\n" ++ " cudaMalloc((void**)&dinput" ++ show id ++ ", sizeof(int) * input" ++ show id ++ "size );\n" copyInput (GlobalArray id) = " cudaMemcpy(dinput"++ sid ++ ",input" ++ sid ++", sizeof(int) * input"++sid++"size, cudaMemcpyHostToDevice);\n" where sid = show id allocImm (GlobalArray id) s= " int* dinput"++ show id ++ ";\n" ++ " cudaMalloc((void**)&dinput" ++ show id ++ ", sizeof(int) * "++ show s ++ ");\n" -- Shared memory usage also needed call name blocks threads sm input output = " " ++ name ++ "<<<"++ show blocks ++", " ++ show threads ++" ," ++show sm++ " >>>((int*)dinput" ++ show input ++ ",(int*)dinput" ++ show output ++ ");\n" writeResult (GlobalArray id) blocks elems = " cudaMemcpy(output0, dinput"++show id++", sizeof(int) * "++ show (elems * blocks) ++" , cudaMemcpyDeviceToHost);\n" ---------------------------------------------------------------------------- -- pOutput :: Scalar a => (Exp Word32 -> Exp Word32) -> Array (Exp a) -> Kernel (Array (Exp a)) pOutput outf arr = do let name = "output0" let p = pushApp parr (globalTarget name (fromIntegral (len arr))) tell p return (Array (index name) (len arr)) where es = fromIntegral$ sizeOf (arr ! 0) t = Pointer$ Local$ typeOf (arr ! 0) parr = push arr globalTarget :: Scalar a => Name -> Exp Word32 -> (Exp Word32, Exp a) -> Program () globalTarget n blockSize (i,a) = Assign n (outf i) a ---------------------------------------------------------------------------- -- tests. test :: GlobalArray (Exp Int) -> KC () test arr = let arr' = Input arr imm = LaunchUn 10 256 (stdIn 256) myKern (stdOut 256) arr' imm2 = LaunchUn 10 256 (stdIn 256) myKern (stdOut 256) imm in WriteResult 10 256 imm2 {- launchUn :: (Scalar a, Scalar b) => Int -> Int -> (Exp Word32 -> Exp Word32) -- Maybe should be something else ? (bid tid etc ?) -> (Array (Exp a) -> Kernel (Array (Exp b))) -> (Exp Word32 -> Exp Word32) -> KC (GlobalArray (Exp a)) -> KC (GlobalArray (Exp b)) launchUn blocks threads inf kern outf input = LaunchUn blocks threads id (pure inf ->- kern ->- pure outf) id input test2 :: GlobalArray (Exp Int) -> KC () test2 arr = let arr' = Input arr imm = launchUn 10 256 stdIn myKern id arr' imm2 = launchUn 10 256 revblocks myKern id imm in WriteResult 10 256 imm2 -} ---------------------------------------------------------------------------- -- ReductionTest -- general reductions reduce :: Syncable Array a => (a -> a -> a) -> Array a -> Kernel (Array a) reduce op arr | len arr == 1 = return arr | otherwise = (pure ((uncurry (zipWith op)) . halve) ->- sync ->- reduce op) arr -- reduction kernel for integers. reduceAddInt :: Array (Exp Int) -> Kernel (Array (Exp Int)) reduceAddInt = reduce (+) -- Coordination code. reduceLarge :: GlobalArray (Exp Int) -> KC () reduceLarge arr = let arr' = Input arr imm = LaunchUn 256 256 (stdIn 256) reduceAddInt (stdOut 1) arr' imm2 = LaunchUn 1 256 (stdIn 256) reduceAddInt (stdOut 1) imm in WriteResult 1 1 imm2 -- output cuda as a string getReduceLarge = putStrLn$ run_ reduceLarge ---------------------------------------------------------------------------- -- Experiment2 data CPUArray a = CPUArray {cpuArrayName :: String, cpuArrayType :: Type, cpuArraySize :: Exp Word32} data GPUArray a = GPUArray {gpuArrayName :: String, gpuArrayType :: Type, gpuArraySize :: Exp Word32, gpuArrayPerm :: (Exp Word32 -> Exp Word32)} data M a = M a instance Monad M where return a = M a (>>=) (M a) f = f a data CoordState = CoordState {kernelMap :: KernelMap, nextId :: Integer} --Why do I always fall into doing things this way ? type Coord a = StateT CoordState (Writer CoordC) a newId :: Coord Integer newId = do s <- get let i = nextId s put (s {nextId = i+1}) return i -- (String, String, Word32, Word32) -- code name threads shared -- code code name name insertKernel :: String -> (String,String,Word32,Word32) -> Coord () insertKernel prot cand = do s <- get let km = kernelMap s km' = Map.insert prot cand km put (s {kernelMap = km'}) lookupKernel :: String -> Coord (Maybe (String,String,Word32,Word32)) lookupKernel prot = do s <- get let km = kernelMap s return (Map.lookup prot km) copyIn :: GPUArray e -> CPUArray e -> Coord () copyIn gpuArr cpuArr = do let gpuV = (CVar (gpuArrayName gpuArr) (gpuArrayType gpuArr)) cpuV = (CVar (cpuArrayName cpuArr) (cpuArrayType cpuArr)) code = MemCpy gpuV cpuV (gpuArraySize gpuArr) tell code copyOut :: CPUArray e -> GPUArray e -> Coord () copyOut cpuArr gpuArr = do let gpuV = (CVar (gpuArrayName gpuArr) (gpuArrayType gpuArr)) cpuV = (CVar (cpuArrayName cpuArr) (cpuArrayType cpuArr)) code = MemCpy cpuV gpuV (cpuArraySize cpuArr) tell code newArr :: Type -> Exp Word32 -> Coord (GPUArray e) newArr t bytes = do ident <- newId let gpuV = (CVar ("imm"++show ident) t) tell $ Malloc gpuV bytes return (GPUArray ("imm"++show ident) t bytes id) launch :: Word32 -> Word32 -> (Array (Exp a) -> Kernel (Array (Exp b))) -> GPUArray a -> GPUArray b -> Coord () launch = undefined permute :: (Exp Word32 -> Exp Word32) -> GPUArray e -> Coord (GPUArray e) permute = undefined silly1 arr out = do arr' <- newArr (cpuArrayType arr) (10*256*4) copyIn arr' arr imm <- newArr Int (10*256*4) -- Array with type of return type of kernel imm2 <- newArr Int (10*256*4) launch 10 256 (sync) arr' imm imm' <- permute (\ix -> 10*256 - 1 - ix) imm launch 10 256 (sync) imm' imm2 copyOut out imm2 reduceLarge2 arr out = do arr' <- newArr (cpuArrayType arr) (256*256*4) copyIn arr' arr imm <- newArr Int (256*4) imm2 <- newArr Int (1*4) launch 256 256 reduceAddInt arr' imm launch 1 256 reduceAddInt imm imm2 copyOut out imm2
svenssonjoel/GCDObsidian
Obsidian/Coordination/Array.hs
bsd-3-clause
15,358
0
17
4,884
3,927
2,044
1,883
230
2
module DataAnalysis05 where import Data.List (genericLength) import Math.Combinatorics.Exact.Binomial (choose) import DataAnalysis02 (average) probabilityMassFunction :: Integral a => a -> a -> Double -> Double probabilityMassFunction k n p = fromIntegral (n `choose` k) * p^k * (1-p)^(n-k) standardDeviation :: [Double] -> Double standardDeviation values = (sqrt . sum $ map (\x -> (x-mu)*(x-mu)) values) / sqrt_nm1 where mu = average values sqrt_nm1 = sqrt (genericLength values - 1)
mrordinaire/data-analysis
src/DataAnalysis05.hs
bsd-3-clause
502
0
13
84
206
113
93
11
1
module Main where import Data.Text import Test.QuickCheck data Thingy = Thingy { name :: Text , number :: Int } deriving (Show) instance Arbitrary Thingy where arbitrary = Thingy <$> arbitraryText <*> arbitrary arbitraryText :: Gen Text arbitraryText = elements [ "hello" , "no way" , "whatever" , "ok" ] main :: IO () main = arbitraryThing >>= print arbitraryThing :: IO Thingy arbitraryThing = generate arbitrary
toddmohney/concurrency-example
arbitrary/Main.hs
bsd-3-clause
457
0
8
109
126
71
55
19
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. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Duration.SV.Rules ( rules ) where import Control.Monad (join) import qualified Data.Text as Text import Prelude import Data.String import Duckling.Dimensions.Types import Duckling.Duration.Helpers import Duckling.Numeral.Helpers (parseInt) import Duckling.Numeral.Types (NumeralData(..)) import qualified Duckling.Numeral.Types as TNumeral import Duckling.Regex.Types import qualified Duckling.TimeGrain.Types as TG import Duckling.Types ruleHalfAnHour :: Rule ruleHalfAnHour = Rule { name = "half an hour" , pattern = [ regex "(1/2|en halv) timme" ] , prod = \_ -> Just . Token Duration $ duration TG.Minute 30 } ruleIntegerMoreUnitofduration :: Rule ruleIntegerMoreUnitofduration = Rule { name = "<integer> more <unit-of-duration>" , pattern = [ Predicate isNatural , dimension TimeGrain , regex "fler|mer" ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v}): Token TimeGrain grain: _) -> Just . Token Duration . duration grain $ floor v _ -> Nothing } ruleNumeralnumberHours :: Rule ruleNumeralnumberHours = Rule { name = "number.number hours" , pattern = [ regex "(\\d+)\\,(\\d+)" , regex "timm(e|ar)?" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (h:d:_)):_) -> do hh <- parseInt h dec <- parseInt d let divisor = floor $ (fromIntegral (10 :: Integer) :: Float) ** fromIntegral (Text.length d - 1) numerator = fromIntegral $ 6 * dec Just . Token Duration . duration TG.Minute $ 60 * hh + quot numerator divisor _ -> Nothing } ruleIntegerAndAnHalfHours :: Rule ruleIntegerAndAnHalfHours = Rule { name = "<integer> and an half hours" , pattern = [ Predicate isNatural , regex "och (en )?halv timme?" ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v}):_) -> Just . Token Duration . duration TG.Minute $ 30 + 60 * floor v _ -> Nothing } ruleAUnitofduration :: Rule ruleAUnitofduration = Rule { name = "a <unit-of-duration>" , pattern = [ regex "en|ett?" , dimension TimeGrain ] , prod = \tokens -> case tokens of (_:Token TimeGrain grain:_) -> Just . Token Duration $ duration grain 1 _ -> Nothing } ruleAboutDuration :: Rule ruleAboutDuration = Rule { name = "about <duration>" , pattern = [ regex "(omkring|cirka|ca.|ca|runt)" , dimension Duration ] , prod = \tokens -> case tokens of (_:token:_) -> Just token _ -> Nothing } ruleExactlyDuration :: Rule ruleExactlyDuration = Rule { name = "exactly <duration>" , pattern = [ regex "(precis|exakt)" , dimension Duration ] , prod = \tokens -> case tokens of (_:token:_) -> Just token _ -> Nothing } rules :: [Rule] rules = [ ruleAUnitofduration , ruleAboutDuration , ruleExactlyDuration , ruleHalfAnHour , ruleIntegerAndAnHalfHours , ruleIntegerMoreUnitofduration , ruleNumeralnumberHours ]
rfranek/duckling
Duckling/Duration/SV/Rules.hs
bsd-3-clause
3,461
0
21
832
909
508
401
97
2
{-# LANGUAGE RecordWildCards #-} module Yesod.Worker.Util ( enqueue , enqueueAt , enqueueIn ) where import qualified Keenser as K import Yesod import Yesod.Worker.Types import Control.Concurrent (readMVar) import Data.Thyme.Clock (UTCTime) enqueue :: (ToJSON a, YesodWorker master) => K.Worker (HandlerT master IO) a -> a -> HandlerT master IO () enqueue job args = do manager <- getManager K.enqueue manager job args enqueueAt :: (ToJSON a, YesodWorker master) => UTCTime -> K.Worker (HandlerT master IO) a -> a -> HandlerT master IO () enqueueAt time job args = do manager <- getManager K.enqueueAt time manager job args enqueueIn :: (ToJSON a, YesodWorker master) => Rational -> K.Worker (HandlerT master IO) a -> a -> HandlerT master IO () enqueueIn snds job args = do manager <- getManager K.enqueueIn snds manager job args getManager :: YesodWorker master => HandlerT master IO K.Manager getManager = do Workers{..} <- workers <$> getYesod liftIO $ do m <- readMVar wManager return $! m
jamesdabbs/yesod-worker
src/Yesod/Worker/Util.hs
bsd-3-clause
1,033
0
11
197
381
193
188
28
1
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable -} module Fragment.TyArr.Ast ( module X ) where import Fragment.TyArr.Ast.Type as X import Fragment.TyArr.Ast.Error as X
dalaing/type-systems
src/Fragment/TyArr/Ast.hs
bsd-3-clause
278
0
4
51
32
24
8
4
0
module Program.Bottles where import Syntax true = C "true" [] six = ofInt 6 four = ofInt 4 nine = ofInt 9 seven = ofInt 7 ofInt 0 = C "o" [] ofInt n = C "s" [ofInt $ n - 1] query = Program bottles $ fresh ["a", "b", "c"] (call "checkAnswer" [V "a", V "b", V "c", true]) query' = Program definition $ fresh ["q", "res"] (call "query" [V "q", V "res"]) queryEq = Program fancyEq $ fresh ["x", "y"] (call "fancyEq" [V "x", V "y", true]) definition :: [Def] definition = definitionDef : bottles definitionDef :: Def definitionDef = Def "query" ["q", "res"] ( call "capacities1" [V "q"] &&& call "checkAnswer" [V "res", V "q", seven, true]) add :: [Def] add = [addDef] -- addDef :: Def -- addDef = -- Def "add" ["a", "b", "q113"] ( -- ((V "a" === C "o" []) &&& -- (V "b" === V "q113")) ||| -- (fresh ["x"] ( -- (V "a" === C "s" [V "x"]) &&& -- (call "add" [V "x", C "s" [V "b"], V "q113"]))) -- ) addDef :: Def addDef = ( Def "add" ["x", "y", "z"] ( x === C "o" [] &&& z === y ||| fresh ["x'", "z'"] (x === C "s" [x'] &&& z === C "s" [z'] &&& call "add" [x', y, z']) ) ) where [x, y, z, x', z'] = map V ["x", "y", "z", "x'", "z'"] greater :: [Def] greater = [greaterDef] greaterDef :: Def greaterDef = Def "greater" ["a", "b", "q109"] ( ((V "a" === C "o" []) &&& (V "q109" === C "false" [])) ||| (fresh ["x"] ( (V "a" === C "s" [V "x"]) &&& (((V "b" === C "o" []) &&& (V "q109" === C "true" [])) ||| (fresh ["y"] ( (V "b" === C "s" [V "y"]) &&& (call "greater" [V "x", V "y", V "q109"])))))) ) sub :: [Def] sub = [subDef] subDef :: Def subDef = Def "sub" ["a", "b", "q105"] ( ((V "b" === C "o" []) &&& (V "a" === V "q105")) ||| (fresh ["y"] ( (V "b" === C "s" [V "y"]) &&& (((V "a" === C "o" []) &&& (V "q105" === C "o" [])) ||| (fresh ["x"] ( (V "a" === C "s" [V "x"]) &&& (call "sub" [V "x", V "y", V "q105"])))))) ) anotherBottle :: [Def] anotherBottle = [anotherBottleDef] anotherBottleDef :: Def anotherBottleDef = Def "anotherBottle" ["b", "q102"] ( ((V "b" === C "fst" []) &&& (V "q102" === C "snd" [])) ||| ((V "b" === C "snd" []) &&& (V "q102" === C "fst" [])) ) createEnv :: [Def] createEnv = [createEnvDef] createEnvDef :: Def createEnvDef = Def "createEnv" ["bottle", "lvl1", "lvl2", "q99"] ( ((V "bottle" === C "fst" []) &&& (V "q99" === C "pair" [V "lvl1", V "lvl2"])) ||| ((V "bottle" === C "snd" []) &&& (V "q99" === C "pair" [V "lvl2", V "lvl1"])) ) fst' :: [Def] fst' = [fst'Def] fst'Def :: Def fst'Def = Def "fst'" ["x", "q96"] ( fresh ["a", "q97"] ( (V "x" === C "pair" [V "a", V "q97"]) &&& (V "a" === V "q96")) ) snd' :: [Def] snd' = [snd'Def] snd'Def :: Def snd'Def = Def "snd'" ["x", "q93"] ( fresh ["q94", "a"] ( (V "x" === C "pair" [V "q94", V "a"]) &&& (V "a" === V "q93")) ) getCapacity :: [Def] getCapacity = getCapacityDef : fst' ++ snd' getCapacityDef :: Def getCapacityDef = Def "get_capacity" ["capacities", "bottle", "q92"] ( ((V "bottle" === C "fst" []) &&& (call "fst'" [V "capacities", V "q92"])) ||| ((V "bottle" === C "snd" []) &&& (call "snd'" [V "capacities", V "q92"])) ) fancyEq :: [Def] fancyEq = [fancyEqDef] fancyEqDef :: Def fancyEqDef = Def "fancyEq" ["a", "b", "q85"] ( ((V "a" === C "o" []) &&& (((V "b" === C "o" []) &&& (V "q85" === C "true" [])) ||| (fresh ["q88"] ( (V "b" === C "s" [V "q88"]) &&& (V "q85" === C "false" []))))) ||| (fresh ["x"] ( (V "a" === C "s" [V "x"]) &&& (((V "b" === C "o" []) &&& (V "q85" === C "false" [])) ||| (fresh ["y"] ( (V "b" === C "s" [V "y"]) &&& (call "fancyEq" [V "x", V "y", V "q85"])))))) ) checkStep :: [Def] checkStep = checkStepDef : fancyEq ++ getCapacity ++ anotherBottle checkStepDef :: Def checkStepDef = Def "checkStep" ["Env0", "step0", "capacities", "q48"] ( fresh ["f", "s"] ( (V "Env0" === C "pair" [V "f", V "s"]) &&& (fresh ["t", "b"] ( (V "step0" === C "pair" [V "t", V "b"]) &&& (((V "t" === C "fill" []) &&& (fresh ["q51"] ( (((V "b" === C "fst" []) &&& (V "f" === V "q51")) ||| ((V "b" === C "snd" []) &&& (V "s" === V "q51"))) &&& (call "fancyEq" [V "q51", C "o" [], V "q48"])))) ||| ((V "t" === C "empty" []) &&& (fresh ["q56", "q57"] ( (((V "b" === C "fst" []) &&& (V "f" === V "q56")) ||| ((V "b" === C "snd" []) &&& (V "s" === V "q56"))) &&& (call "get_capacity" [V "capacities", V "b", V "q57"]) &&& (call "fancyEq" [V "q56", V "q57", V "q48"])))) ||| ((V "t" === C "pour" []) &&& (fresh ["q62"] ( (fresh ["q66", "q67"] ( (fresh ["q72"] ( (((V "b" === C "fst" []) &&& (V "f" === V "q72")) ||| ((V "b" === C "snd" []) &&& (V "s" === V "q72"))) &&& (call "fancyEq" [V "q72", C "o" [], V "q66"]))) &&& (fresh ["q77", "q78"] ( (((V "b" === C "fst" []) &&& (V "s" === V "q77")) ||| ((V "b" === C "snd" []) &&& (V "f" === V "q77"))) &&& (fresh ["q83"] ( (call "anotherBottle" [V "b", V "q83"]) &&& (call "get_capacity" [V "capacities", V "q83", V "q78"]))) &&& (call "fancyEq" [V "q77", V "q78", V "q67"]))) &&& (((V "q66" === C "true" []) &&& (V "q62" === C "true" [])) ||| ((V "q66" === C "false" []) &&& (V "q62" === V "q67"))))) &&& (((V "q62" === C "true" []) &&& (V "q48" === C "false" [])) ||| ((V "q62" === C "false" []) &&& (V "q48" === C "true" [])))))))))) ) doStep :: [Def] doStep = doStepDef : getCapacity ++ createEnv ++ add ++ anotherBottle ++ greater doStepDef :: Def doStepDef = Def "doStep" ["Env0", "step0", "capacities", "q15"] ( fresh ["f", "s"] ( (V "Env0" === C "pair" [V "f", V "s"]) &&& (fresh ["t", "b"] ( (V "step0" === C "pair" [V "t", V "b"]) &&& (((V "t" === C "fill" []) &&& (fresh ["q18", "q19"] ( (call "get_capacity" [V "capacities", V "b", V "q18"]) &&& (((V "b" === C "fst" []) &&& (V "s" === V "q19")) ||| ((V "b" === C "snd" []) &&& (V "f" === V "q19"))) &&& (call "createEnv" [V "b", V "q18", V "q19", V "q15"])))) ||| ((V "t" === C "empty" []) &&& (fresh ["q24"] ( (((V "b" === C "fst" []) &&& (V "s" === V "q24")) ||| ((V "b" === C "snd" []) &&& (V "f" === V "q24"))) &&& (call "createEnv" [V "b", C "o" [], V "q24", V "q15"])))) ||| ((V "t" === C "pour" []) &&& (fresh ["q30"] ( (fresh ["q43", "q44"] ( (call "add" [V "f", V "s", V "q43"]) &&& (fresh ["q46"] ( (call "anotherBottle" [V "b", V "q46"]) &&& (call "get_capacity" [V "capacities", V "q46", V "q44"]))) &&& (call "greater" [V "q43", V "q44", V "q30"]))) &&& (((V "q30" === C "true" []) &&& (fresh ["q31", "q32"] ( (fresh ["q34", "q35"] ( (call "add" [V "f", V "s", V "q34"]) &&& (fresh ["q37"] ( (call "anotherBottle" [V "b", V "q37"]) &&& (call "get_capacity" [V "capacities", V "q37", V "q35"]))) &&& (call "sub" [V "q34", V "q35", V "q31"]))) &&& (fresh ["q39"] ( (call "anotherBottle" [V "b", V "q39"]) &&& (call "get_capacity" [V "capacities", V "q39", V "q32"]))) &&& (call "createEnv" [V "b", V "q31", V "q32", V "q15"])))) ||| ((V "q30" === C "false" []) &&& (fresh ["q41"] ( (call "add" [V "f", V "s", V "q41"]) &&& (call "createEnv" [V "b", C "o" [], V "q41", V "q15"])))))))))))) ) isFinishEnv :: [Def] isFinishEnv = isFinishEnvDef : fancyEq isFinishEnvDef :: Def isFinishEnvDef = Def "isFinishEnv" ["Env0", "reqLvl", "q8"] ( fresh ["f", "s"] ( (V "Env0" === C "pair" [V "f", V "s"]) &&& (fresh ["q9", "q10"] ( (call "fancyEq" [V "f", V "reqLvl", V "q9"]) &&& (call "fancyEq" [V "s", V "reqLvl", V "q10"]) &&& (((V "q9" === C "true" []) &&& (V "q8" === C "true" [])) ||| ((V "q9" === C "false" []) &&& (V "q8" === V "q10")))))) ) checkAnswer' :: [Def] checkAnswer' = checkAnswer'Def : isFinishEnv ++ checkStep ++ doStep checkAnswer'Def :: Def checkAnswer'Def = Def "checkAnswer'" ["Env0", "answer", "capacities", "reqLvl", "q1"] ( ((V "answer" === C "nil" []) &&& (call "isFinishEnv" [V "Env0", V "reqLvl", V "q1"])) ||| (fresh ["x", "xs"] ( (V "answer" === C "%" [V "x", V "xs"]) &&& (fresh ["q3"] ( (call "checkStep" [V "Env0", V "x", V "capacities", V "q3"]) &&& (((V "q3" === C "true" []) &&& (fresh ["q4"] ( (call "doStep" [V "Env0", V "x", V "capacities", V "q4"]) &&& (call "checkAnswer'" [V "q4", V "xs", V "capacities", V "reqLvl", V "q1"])))) ||| ((V "q3" === C "false" []) &&& (V "q1" === C "false" []))))))) ) checkAnswer :: [Def] checkAnswer = checkAnswerDef : checkAnswer' checkAnswerDef :: Def checkAnswerDef = Def "checkAnswer" ["answer", "capacities", "reqLvl", "q7"] ( call "checkAnswer'" [C "pair" [C "o" [], C "o" []], V "answer", V "capacities", V "reqLvl", V "q7"] ) capacities1 :: [Def] capacities1 = [capacities1Def] capacities1Def :: Def capacities1Def = Def "capacities1" ["q0"] ( V "q0" === C "pair" [four, nine] ) bottles :: [Def] bottles = [ addDef , greaterDef , subDef , anotherBottleDef , createEnvDef , fst'Def , snd'Def , getCapacityDef , fancyEqDef , checkStepDef , doStepDef , isFinishEnvDef , checkAnswerDef , checkAnswer'Def , capacities1Def ] env :: String env = "open MiniKanren\nopen MiniKanrenStd\ntype bottle =\n | Fst \n | Snd \nlet fst () = !! Fst\nlet snd () = !! Snd\ntype stepType =\n | Fill \n | Empty \n | Pour \nlet fill () = !! Fill\nlet empty () = !! Empty\nlet pour () = !! Pour\ntype 'a0 gnat =\n | O \n | S of 'a0 \nlet rec fmap fa0 = function | O -> O | S a0 -> S (fa0 a0)\nmodule For_gnat =\n (Fmap)(struct\n let rec fmap fa0 = function | O -> O | S a0 -> S (fa0 a0)\n type 'a0 t = 'a0 gnat\n end)\nlet rec o () = inj (For_gnat.distrib O)\nand s x__0 = inj (For_gnat.distrib (S x__0))"
kajigor/uKanren_transformations
test/resources/Program/Bottles.hs
bsd-3-clause
11,403
0
43
4,008
4,947
2,592
2,355
279
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} module Onedrive.Types.OauthTokenResponse where import Control.Lens (makeLensesWith, camelCaseFields) import Data.Aeson (FromJSON(parseJSON), (.:), (.:?), Value(String, Object)) import Data.Aeson.Types (typeMismatch) import qualified Data.Text as T data OauthTokenType = Bearer deriving (Eq, Show) data OauthTokenResponse = OauthTokenResponse { oauthTokenResponseTokenType :: OauthTokenType , oauthTokenResponseExpiresIn :: Int , oauthTokenResponseScope :: T.Text , oauthTokenResponseAccessToken :: T.Text , oauthTokenResponseRefreshToken :: Maybe T.Text } deriving (Eq, Show) instance FromJSON OauthTokenType where parseJSON (String "bearer") = return Bearer parseJSON invalid = typeMismatch "OauthTokenType" invalid instance FromJSON OauthTokenResponse where parseJSON (Object o) = OauthTokenResponse <$> o .: "token_type" <*> o .: "expires_in" <*> o .: "scope" <*> o .: "access_token" <*> o .:? "refresh_token" parseJSON invalid = typeMismatch "OauthTokenResponse" invalid makeLensesWith camelCaseFields ''OauthTokenResponse
asvyazin/hs-onedrive
src/Onedrive/Types/OauthTokenResponse.hs
bsd-3-clause
1,291
0
15
214
277
159
118
36
0
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Util.UDP -- Copyright : (c) Einar Karttunen -- License : BSD-style -- -- Maintainer : [email protected] -- Stability : alpha -- Portability : network -- -- Basic UDP connectivity. Currently inefficient - GHC 6.4 should provide -- the primitives directly. Supports fast ops with CVS GHC. -- ----------------------------------------------------------------------------- module HSNTP.Util.UDP (connectUDP, listenUDP, recvBufFrom, sendBufTo, sockAddr, newSock, sClose ) where import Data.Char import Network.BSD import Network.Socket #if (__GLASGOW_HASKELL__ < 603) import Data.Word import Foreign.C.String import Foreign.Marshal.Array import Foreign.Ptr -- | Receive a buffer of bytes. recvBufFrom :: Socket -> Ptr Word8 -> Int -> IO (Int, SockAddr) recvBufFrom sock ptr n = do (str,len,sa) <- recvFrom sock n pokeArray ptr ((map (fromIntegral . ord) str) :: [Word8]) return (len,sa) -- | Send a buffer of bytes. sendBufTo :: Socket -> Ptr Word8 -> Int -> SockAddr -> IO Int sendBufTo sock ptr len sa = do str <- peekArray len ptr sendTo sock (map (chr . fromIntegral) str) sa #endif -- | Connect to an UDP-port. connectUDP :: String -> Int -> IO Socket connectUDP host port = do sock <- socket AF_INET Datagram 0 addr <- getHostByName host connect sock $ SockAddrInet (toEnum port) $ hostAddress addr --socketToHandle sock ReadWriteMode return sock sockAddr :: String -> Int -> IO SockAddr sockAddr host port = do ha <- getHostByName host return $ SockAddrInet (toEnum port) (hostAddress ha) newSock :: IO Socket newSock = socket AF_INET Datagram 0 -- | Listen UDP listenUDP :: Int -> IO Socket listenUDP port = do sock <- socket AF_INET Datagram 0 bindSocket sock $ SockAddrInet (toEnum port) iNADDR_ANY return sock
creswick/hsntp
HSNTP/Util/UDP.hs
bsd-3-clause
2,177
0
12
615
496
258
238
32
1
{-# LANGUAGE DeriveDataTypeable #-} {-| Module : Numeric.AERN.Basics.Exception Description : exception type to signal AERN specific errors Copyright : (c) Michal Konecny License : BSD3 Maintainer : [email protected] Stability : experimental Portability : portable An exception type to be thrown on various arithmetic exceptions whose proper pure handling would be inefficient. 'Control.Exception.ArithmeticException' is not flexible enough, eg because often we will not be checking overflows but DomViolations instead. The default exeception policy is: * no operation should ever return DomViolation; when a DomViolation represents "any value"/bottom (eg with 0/0 or &infin - &infin), it should be rounded up to +&infin; or down to -&infin;; when a DomViolation represent an illegal argument exception (eg with log(-1)), an AERN DomViolation exception should be thrown with an appropriate message * intervals support infinite endpoints * polynomial coefficients must be finite, overflows of coefficients detected and result in a special polynomial denoting the constant function +&infin; or -&infin; -} module Numeric.AERN.Basics.Exception where import Prelude hiding (catch) import Control.Exception import Data.Typeable import System.IO.Unsafe data AERNException = AERNException String | AERNIllegalValue String | AERNDomViolationException String | AERNMaybeDomViolationException String deriving (Show, Typeable) instance Exception AERNException evalCatchAERNExceptions :: String -> t -> Either AERNException t evalCatchAERNExceptions contextDescription a = unsafePerformIO $ catch (evaluateEmbed a) handler where handler e@(AERNException msg) = do putStrLn $ "caught AERN exception: " ++ msg return (Left e) handler e@(AERNIllegalValue msg) = do putStrLn $ "caught AERN illegal value exception: " ++ msg return (Left e) handler e@(AERNDomViolationException msg) = do putStrLn $ "caught AERN operation domain violation exception: " ++ msg return (Left e) handler e@(AERNMaybeDomViolationException msg) = do putStrLn $ "caught AERN potential operation domain violation exception: " ++ msg return (Left e) evaluateEmbed a = do aa <- evaluate a return $ Right aa evalCatchDomViolationExceptions :: String -> t -> Either AERNException t evalCatchDomViolationExceptions contextDescription a = case evalCatchAERNExceptions contextDescription a of Left e@(AERNDomViolationException _) -> Left e Left e@(AERNMaybeDomViolationException _) -> Left e Left e -> unsafePerformIO $ do putStrLn $ contextDescription ++ ": rethrowing" throw e r -> r raisesAERNException :: String -> t -> Bool raisesAERNException contextDescription a = case (evalCatchAERNExceptions contextDescription a) of (Left _) -> True _ -> False raisesDomViolationException :: String -> t -> Bool raisesDomViolationException contextDescription a = case (evalCatchDomViolationExceptions contextDescription a) of (Left _) -> True _ -> False class HasLegalValues t where maybeGetProblem :: t -> Maybe String detectIllegalValues :: (HasLegalValues t) => String -> t -> t detectIllegalValues contextDescription value = case maybeGetProblem value of Nothing -> value Just problemDescription -> throw $ AERNIllegalValue $ contextDescription ++ ": " ++ problemDescription
michalkonecny/aern
aern-order/src/Numeric/AERN/Basics/Exception.hs
bsd-3-clause
3,732
0
12
936
622
310
312
66
4
-- | Provides file tools used for outputting and converting JSON plan -- files. module Database.Algebra.SQL.File where import Control.Monad.Error.Class import Data.Aeson import qualified Data.ByteString.Lazy.Char8 as BL import System.FilePath import System.Process import qualified Database.Algebra.Dag as D import Database.Algebra.Table.Render.Dot import qualified Database.Algebra.SQL.Tile as T readDagFromFile :: FilePath -> IO (Either String T.TADag) readDagFromFile filename = case takeExtension filename of ".plan" -> do -- FIXME This function is a mess, does an unchecked fromJust, which -- easily fails. Just dag <- decode <$> BL.readFile filename return $ return dag format -> return $ throwError $ "unkown file format '" ++ format ++ "'" outputDot :: FilePath -> T.TADag -> IO () outputDot filename dag = do writeFile filename result putStrLn $ "Writing dot file to '" ++ filename ++ "'" where result = renderTADot (D.rootNodes dag) (D.nodeMap dag) renderDot :: FilePath -> FilePath -> IO () renderDot dotPath pdfPath = do putStrLn $ "Rendering dot file to '" ++ pdfPath ++ "'" _ <- rawSystem "dot" ["-Tpdf", "-o", pdfPath, dotPath] return ()
ulricha/algebra-sql
src/Database/Algebra/SQL/File.hs
bsd-3-clause
1,310
0
13
326
321
173
148
26
2
-- | -- Module: $HEADER$ -- Description: Commonly used generators of input alphabet. -- Copyright: (c) 2013 Peter Trsko -- License: BSD3 -- -- Maintainer: [email protected] -- Stability: experimental -- Portability: portable -- -- Commonly used generators of input alphabet. module Text.Pwgen.Common ( -- * Generators numbers , uppers , lowers , symbols , ambiguous -- ** Hexadecimal Numbers , lowerHexNumbers , upperHexNumbers , hexNumbers -- ** Vowels and Consonants , lowerVowels , lowerVowelsY , upperVowels , upperVowelsY , lowerConsonants , lowerConsonantsY , upperConsonants , upperConsonantsY -- ** Utility functions , construct -- * Predicates , is -- , isNumber -- , isUpper -- , isLower -- , isSymbol -- , isAmbiguous -- , isHexNumber -- ** Vowels and Consonants , isLowerVowel , isLowerVowelY , isUpperVowel , isUpperVowelY , isVowel , isVowelY -- , isLowerConsonant -- , isLowerConsonantY -- , isUpperConsonant -- , isUpperConsonantY -- , isConsonant -- , isConsonantY ) where import Data.Word (Word8) import Control.Applicative.Predicate ((<||>)) import Text.Pwgen.FromAscii -- {{{ Generators ------------------------------------------------------------- -- | Helper function that constructs generator from list of ASCII values. construct :: FromAscii a => [Word8] -> (a -> t -> t) -> t -> t construct ws cons = foldl (\ f -> (f .) . cons . fromAscii) id ws {-# INLINE construct #-} -- | Numbers @\'0\', \'1\', ... \'9\'@. numbers :: FromAscii a => (a -> t -> t) -> t -> t numbers = construct [48..57] {-# INLINEABLE numbers #-} -- | Upper characters @\'A\', \'B\', ... \'Z\'@. uppers :: FromAscii a => (a -> t -> t) -> t -> t uppers = construct [65..90] {-# INLINEABLE uppers #-} -- | Lower characters @\'a\', \'b\', ... \'z\'@. lowers :: FromAscii a => (a -> t -> t) -> t -> t lowers = construct [97..122] {-# INLINEABLE lowers #-} -- | ASCII symbols. symbols :: FromAscii a => (a -> t -> t) -> t -> t symbols = construct $ concat [ [33..47] -- "!\"#$%&'()*+,-./" , [58..64] -- ":;<=>?@" , [133..96] -- "[\\]^_`" , [123..126] -- "{|}~" ] {-# INLINEABLE symbols #-} -- | Ambiguous characters, like @8@ and @B@. ambiguous :: FromAscii a => (a -> t -> t) -> t -> t ambiguous = construct [ 56, 66 -- 8, B , 54, 71 -- 6, G , 49, 73, 108 -- 1, I, l , 48, 68, 79, 81 -- 0, O, Q, D , 83, 53 -- S, 5 , 90, 50 -- Z, 2 ] {-# INLINEABLE ambiguous #-} -- | Hexadecimal numbers @\'0\', \'1\', ... \'9\', \'a\', \'b\', ... \'f\'@ lowerHexNumbers :: FromAscii a => (a -> t -> t) -> t -> t lowerHexNumbers cons = numbers cons . construct [97..102] cons {-# INLINEABLE lowerHexNumbers #-} -- | Hexadecimal numbers @\'0\', \'1\', ... \'9\', \'A\', \'B\', ... \'F\'@ upperHexNumbers :: FromAscii a => (a -> t -> t) -> t -> t upperHexNumbers cons = numbers cons . construct [65..70] cons {-# INLINEABLE upperHexNumbers #-} -- | Hexadecimal numbers @\'0\', \'1\', ... \'9\', \'A\', \'B\', ... \'F\', -- \'a\', \'b\', ... \'f\'@ hexNumbers :: FromAscii a => (a -> t -> t) -> t -> t hexNumbers cons = numbers cons . construct [65..70] cons . construct [97..102] cons {-# INLINEABLE hexNumbers #-} -- | Lower vowels @\'a\', \'e\', \'i\', \'o\', \'u\'@. lowerVowels :: FromAscii a => (a -> t -> t) -> t -> t lowerVowels = construct [ 97, 101, 105 -- 'a', 'e', 'i' , 111, 117 -- 'o', 'u' ] {-# INLINEABLE lowerVowels #-} -- | Lower vowels including @\'y\'@. lowerVowelsY :: FromAscii a => (a -> t -> t) -> t -> t lowerVowelsY cons = lowerVowels cons . cons (fromAscii 121 {- 'y' -}) {-# INLINEABLE lowerVowelsY #-} -- | Upper vowels @\'A\', \'E\', \'I\', \'O\', \'U\'@. upperVowels :: FromAscii a => (a -> t -> t) -> t -> t upperVowels = construct [ 65, 69, 73 -- 'A', 'E', 'I' , 79, 85 -- 'O', 'U' ] {-# INLINEABLE upperVowels #-} -- | Upper vowels including @\'Y\'@. upperVowelsY :: FromAscii a => (a -> t -> t) -> t -> t upperVowelsY cons = upperVowels cons . cons (fromAscii 89 {- 'Y' -}) {-# INLINEABLE upperVowelsY #-} lowerConsonants :: FromAscii a => (a -> t -> t) -> t -> t lowerConsonants = construct [ 98, 99, 100 -- 'b', 'c', 'd' , 102, 103, 104 -- 'f', 'g', 'h' , 106, 107, 108 -- 'j', 'k', 'l' , 109, 110, 112 -- 'm', 'n', 'p' , 113, 114, 116 -- 'q', 'r', 's' , 116, 118, 119 -- 't', 'v', 'w' , 122 -- 'z' ] {-# INLINEABLE lowerConsonants #-} -- | Lower consonants including @\'y\'@. lowerConsonantsY :: FromAscii a => (a -> t -> t) -> t -> t lowerConsonantsY cons = lowerConsonants cons . cons (fromAscii 121 {- 'y' -}) {-# INLINEABLE lowerConsonantsY #-} upperConsonants :: FromAscii a => (a -> t -> t) -> t -> t upperConsonants = construct [ 66, 67, 68 -- 'B', 'C', 'D' , 70, 71, 72 -- 'F', 'G', 'H' , 74, 75, 76 -- 'J', 'K', 'L' , 77, 78, 80 -- 'M', 'N', 'P' , 81, 82, 83 -- 'Q', 'R', 'S' , 84, 85, 87 -- 'T', 'V', 'W' , 90 -- 'Z' ] {-# INLINEABLE upperConsonants #-} -- | Upper consonants including @\'Y\'@. upperConsonantsY :: FromAscii a => (a -> t -> t) -> t -> t upperConsonantsY cons = upperConsonants cons . cons (fromAscii 89 {- 'Y' -}) {-# INLINEABLE upperConsonantsY #-} -- }}} Generators ------------------------------------------------------------- -- {{{ Predicates ------------------------------------------------------------- is :: (FromAscii a, Eq a) => Word8 -> a -> Bool is = (==) . fromAscii {-# INLINE is #-} -- | Check if argument is one of @\'a\', \'e\', \'i\', \'o\', \'u\'@. isLowerVowel :: (FromAscii a, Eq a) => a -> Bool isLowerVowel = is 97 <||> is 101 <||> is 105 <||> is 111 <||> is 117 {-# INLINE isLowerVowel #-} -- | Check if argument is one of @\'a\', \'e\', \'i\', \'o\', \'u\', \'y\'@. isLowerVowelY :: (FromAscii a, Eq a) => a -> Bool isLowerVowelY = isLowerVowel <||> is 121 {-# INLINE isLowerVowelY #-} -- | Check if argument is one of @\'A\', \'E\', \'I\', \'O\', \'U\'@. isUpperVowel :: (FromAscii a, Eq a) => a -> Bool isUpperVowel = is 65 <||> is 69 <||> is 73 <||> is 79 <||> is 85 {-# INLINE isUpperVowel #-} -- | Check if argument is one of @\'A\', \'E\', \'I\', \'O\', \'U\', \'Y\'@. isUpperVowelY :: (FromAscii a, Eq a) => a -> Bool isUpperVowelY = isUpperVowel <||> is 89 {-# INLINE isUpperVowelY #-} -- | Check if argument is one of @\'a\', \'e\', \'i\', \'o\', \'u\', \'A\', -- \'E\', \'I\', \'O\', \'U\'@. isVowel :: (FromAscii a, Eq a) => a -> Bool isVowel = isLowerVowel <||> isUpperVowel {-# INLINE isVowel #-} -- | Check if argument is one of @\'a\', \'e\', \'i\', \'o\', \'u\', \'y\', -- \'A\', \'E\', \'I\', \'O\', \'U\', \'Y\'@. isVowelY :: (FromAscii a, Eq a) => a -> Bool isVowelY = isLowerVowelY <||> isUpperVowelY {-# INLINE isVowelY #-} -- }}} Predicates -------------------------------------------------------------
trskop/hpwgen
src/Text/Pwgen/Common.hs
bsd-3-clause
7,155
0
10
1,753
1,588
916
672
114
1
{-# LANGUAGE Unsafe #-} {-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples #-} {-# OPTIONS_GHC -funbox-strict-fields #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.MVar -- Copyright : (c) The University of Glasgow 2008 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- The MVar type -- ----------------------------------------------------------------------------- module GHC.MVar ( -- * MVars MVar(..) , newMVar -- :: a -> IO (MVar a) , newEmptyMVar -- :: IO (MVar a) , takeMVar -- :: MVar a -> IO a , putMVar -- :: MVar a -> a -> IO () , tryTakeMVar -- :: MVar a -> IO (Maybe a) , tryPutMVar -- :: MVar a -> a -> IO Bool , isEmptyMVar -- :: MVar a -> IO Bool , addMVarFinalizer -- :: MVar a -> IO () -> IO () ) where import GHC.Base import Data.Maybe data MVar a = MVar (MVar# RealWorld a) {- ^ An 'MVar' (pronounced \"em-var\") is a synchronising variable, used for communication between concurrent threads. It can be thought of as a a box, which may be empty or full. -} -- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module instance Eq (MVar a) where (MVar mvar1#) == (MVar mvar2#) = sameMVar# mvar1# mvar2# {- M-Vars are rendezvous points for concurrent threads. They begin empty, and any attempt to read an empty M-Var blocks. When an M-Var is written, a single blocked thread may be freed. Reading an M-Var toggles its state from full back to empty. Therefore, any value written to an M-Var may only be read once. Multiple reads and writes are allowed, but there must be at least one read between any two writes. -} --Defined in IOBase to avoid cycle: data MVar a = MVar (SynchVar# RealWorld a) -- |Create an 'MVar' which is initially empty. newEmptyMVar :: IO (MVar a) newEmptyMVar = IO $ \ s# -> case newMVar# s# of (# s2#, svar# #) -> (# s2#, MVar svar# #) -- |Create an 'MVar' which contains the supplied value. newMVar :: a -> IO (MVar a) newMVar value = newEmptyMVar >>= \ mvar -> putMVar mvar value >> return mvar -- |Return the contents of the 'MVar'. If the 'MVar' is currently -- empty, 'takeMVar' will wait until it is full. After a 'takeMVar', -- the 'MVar' is left empty. -- -- There are two further important properties of 'takeMVar': -- -- * 'takeMVar' is single-wakeup. That is, if there are multiple -- threads blocked in 'takeMVar', and the 'MVar' becomes full, -- only one thread will be woken up. The runtime guarantees that -- the woken thread completes its 'takeMVar' operation. -- -- * When multiple threads are blocked on an 'MVar', they are -- woken up in FIFO order. This is useful for providing -- fairness properties of abstractions built using 'MVar's. -- takeMVar :: MVar a -> IO a takeMVar (MVar mvar#) = IO $ \ s# -> takeMVar# mvar# s# -- |Put a value into an 'MVar'. If the 'MVar' is currently full, -- 'putMVar' will wait until it becomes empty. -- -- There are two further important properties of 'putMVar': -- -- * 'putMVar' is single-wakeup. That is, if there are multiple -- threads blocked in 'putMVar', and the 'MVar' becomes empty, -- only one thread will be woken up. The runtime guarantees that -- the woken thread completes its 'putMVar' operation. -- -- * When multiple threads are blocked on an 'MVar', they are -- woken up in FIFO order. This is useful for providing -- fairness properties of abstractions built using 'MVar's. -- putMVar :: MVar a -> a -> IO () putMVar (MVar mvar#) x = IO $ \ s# -> case putMVar# mvar# x s# of s2# -> (# s2#, () #) -- |A non-blocking version of 'takeMVar'. The 'tryTakeMVar' function -- returns immediately, with 'Nothing' if the 'MVar' was empty, or -- @'Just' a@ if the 'MVar' was full with contents @a@. After 'tryTakeMVar', -- the 'MVar' is left empty. tryTakeMVar :: MVar a -> IO (Maybe a) tryTakeMVar (MVar m) = IO $ \ s -> case tryTakeMVar# m s of (# s', 0#, _ #) -> (# s', Nothing #) -- MVar is empty (# s', _, a #) -> (# s', Just a #) -- MVar is full -- |A non-blocking version of 'putMVar'. The 'tryPutMVar' function -- attempts to put the value @a@ into the 'MVar', returning 'True' if -- it was successful, or 'False' otherwise. tryPutMVar :: MVar a -> a -> IO Bool tryPutMVar (MVar mvar#) x = IO $ \ s# -> case tryPutMVar# mvar# x s# of (# s, 0# #) -> (# s, False #) (# s, _ #) -> (# s, True #) -- |Check whether a given 'MVar' is empty. -- -- Notice that the boolean value returned is just a snapshot of -- the state of the MVar. By the time you get to react on its result, -- the MVar may have been filled (or emptied) - so be extremely -- careful when using this operation. Use 'tryTakeMVar' instead if possible. isEmptyMVar :: MVar a -> IO Bool isEmptyMVar (MVar mv#) = IO $ \ s# -> case isEmptyMVar# mv# s# of (# s2#, flg #) -> (# s2#, not (flg ==# 0#) #) -- |Add a finalizer to an 'MVar' (GHC only). See "Foreign.ForeignPtr" and -- "System.Mem.Weak" for more about finalizers. addMVarFinalizer :: MVar a -> IO () -> IO () addMVarFinalizer (MVar m) finalizer = IO $ \s -> case mkWeak# m () finalizer s of { (# s1, _ #) -> (# s1, () #) }
joelburget/haste-compiler
libraries/base-ghc-7.6/GHC/MVar.hs
bsd-3-clause
5,504
0
13
1,294
741
422
319
51
2
-- 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 GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Quantity.KM.Rules ( rules ) where import Data.HashMap.Strict (HashMap) import Data.Text (Text, toLower) import Data.String import Prelude import qualified Data.HashMap.Strict as HashMap import qualified Data.Text as Text import Duckling.Dimensions.Types import Duckling.Numeral.Helpers import Duckling.Quantity.Helpers import Duckling.Regex.Types import Duckling.Types import Duckling.Numeral.Types (NumeralData (..)) import Duckling.Quantity.Types (QuantityData(..)) import qualified Duckling.Numeral.Types as TNumeral import qualified Duckling.Quantity.Types as TQuantity ruleQuantityOfProduct :: Rule ruleQuantityOfProduct = Rule { name = "<quantity> of product" , pattern = [ regex "(មនុស្ស|បងប្អូន|សត្វ|ឆ្កែ|ឆ្មា|ដើមឈើ|ផ្កា|កុលាប|ផ្ទះ)" , dimension Quantity ] , prod = \case (Token RegexMatch (GroupMatch (match:_)): Token Quantity qd: _) -> Just . Token Quantity $ withProduct match qd _ -> Nothing } unitsMap :: HashMap Text TQuantity.Unit unitsMap = HashMap.fromList [ ("ចាន", TQuantity.Bowl) , ("ពែង", TQuantity.Cup) , ("កែវ", TQuantity.Cup) , ("ថូ", TQuantity.Pint) , ("ស្លាបព្រា", TQuantity.Tablespoon) , ("ស្លាបព្រាបាយ", TQuantity.Tablespoon) , ("ស្លាបព្រាកាហ្វេ", TQuantity.Teaspoon) , ("នាក់", TQuantity.Custom "For Persons") , ("ក្បាល", TQuantity.Custom "For Animals") , ("ដើម", TQuantity.Custom "For Trees") , ("ទង", TQuantity.Custom "For Flowers") , ("ខ្នង", TQuantity.Custom "For Buildings") , ("គ្រឿង", TQuantity.Custom "For Vehicles/Devices") , ("កញ្ចប់", TQuantity.Custom "For Packages") , ("ឈុត", TQuantity.Custom "Sets") ] ruleNumeralUnits :: Rule ruleNumeralUnits = Rule { name = "<number><units>" , pattern = [ dimension Numeral , regex "(ចាន|ពែង|កែវ|ថូ|ស្លាបព្រា|ស្លាបព្រាបាយ|ស្លាបព្រាកាហ្វេ|នាក់|ក្បាល|ដើម|ទង|ខ្នង|គ្រឿង|កញ្ចប់|ឈុត)" ] , prod = \case (Token Numeral NumeralData{TNumeral.value = v}: Token RegexMatch (GroupMatch (match:_)): _) -> do unit <- HashMap.lookup match unitsMap Just . Token Quantity $ quantity unit v _ -> Nothing } quantities :: [(Text, String, TQuantity.Unit)] quantities = [ ("<quantity> grams", "((មីលី|គីឡូ)?ក្រាម)", TQuantity.Gram) ] opsMap :: HashMap Text (Double -> Double) opsMap = HashMap.fromList [ ( "មីលីក្រាម" , (/ 1000)) , ( "គីឡូក្រាម" , (* 1000)) ] ruleNumeralUnits2 :: [Rule] ruleNumeralUnits2 = map go quantities where go :: (Text, String, TQuantity.Unit) -> Rule go (name, regexPattern, u) = Rule { name = name , pattern = [dimension Numeral, regex regexPattern] , prod = \case (Token Numeral nd: Token RegexMatch (GroupMatch (match:_)): _) -> Just . Token Quantity $ quantity u value where value = getValue opsMap match $ TNumeral.value nd _ -> Nothing } rulePrecision :: Rule rulePrecision = Rule { name = "about|exactly <quantity>" , pattern = [ regex "\\~|ប្រហែល" , dimension Quantity ] , prod = \case (_:token:_) -> Just token _ -> Nothing } ruleIntervalBetweenNumeral :: Rule ruleIntervalBetweenNumeral = Rule { name = "between|from <numeral> and|to <quantity>" , pattern = [ regex "ចន្លោះ(ពី)?|ចាប់ពី" , Predicate isPositive , regex "និង|ដល់" , Predicate isSimpleQuantity ] , prod = \case (_: Token Numeral NumeralData{TNumeral.value = from}: _: Token Quantity QuantityData{TQuantity.value = Just to , TQuantity.unit = Just u , TQuantity.aproduct = Nothing}: _) | from < to -> Just . Token Quantity . withInterval (from, to) $ unitOnly u _ -> Nothing } ruleIntervalBetween :: Rule ruleIntervalBetween = Rule { name = "between|from <quantity> to|and <quantity>" , pattern = [ regex "ចន្លោះ(ពី)?|ចាប់ពី" , Predicate isSimpleQuantity , regex "និង|ដល់" , Predicate isSimpleQuantity ] , prod = \case (_: Token Quantity QuantityData{TQuantity.value = Just from , TQuantity.unit = Just u1 , TQuantity.aproduct = Nothing}: _: Token Quantity QuantityData{TQuantity.value = Just to , TQuantity.unit = Just u2 , TQuantity.aproduct = Nothing}: _) | from < to && u1 == u2 -> Just . Token Quantity . withInterval (from, to) $ unitOnly u1 _ -> Nothing } ruleIntervalNumeralDash :: Rule ruleIntervalNumeralDash = Rule { name = "<numeral> - <quantity>" , pattern = [ Predicate isPositive , regex "\\-" , Predicate isSimpleQuantity ] , prod = \case (Token Numeral NumeralData{TNumeral.value = from}: _: Token Quantity QuantityData{TQuantity.value = Just to , TQuantity.unit = Just u , TQuantity.aproduct = Nothing}: _) | from < to -> Just . Token Quantity . withInterval (from, to) $ unitOnly u _ -> Nothing } ruleIntervalDash :: Rule ruleIntervalDash = Rule { name = "<quantity> - <quantity>" , pattern = [ Predicate isSimpleQuantity , regex "\\-" , Predicate isSimpleQuantity ] , prod = \case (Token Quantity QuantityData{TQuantity.value = Just from , TQuantity.unit = Just u1 , TQuantity.aproduct = Nothing}: _: Token Quantity QuantityData{TQuantity.value = Just to , TQuantity.unit = Just u2 , TQuantity.aproduct = Nothing}: _) | from < to && u1 == u2 -> Just . Token Quantity . withInterval (from, to) $ unitOnly u1 _ -> Nothing } ruleIntervalMax :: Rule ruleIntervalMax = Rule { name = "Max Rule" , pattern = [ regex "ក្រោម|តិចជាង|មិនដល់|យ៉ាងច្រើន|មិនលើស" , Predicate isSimpleQuantity ] , prod = \case (_: Token Quantity QuantityData{TQuantity.value = Just to , TQuantity.unit = Just u , TQuantity.aproduct = Nothing}: _) -> Just . Token Quantity . withMax to $ unitOnly u _ -> Nothing } ruleIntervalMin :: Rule ruleIntervalMin = Rule { name = "Min Rule" , pattern = [ regex "លើស(ពី)?|មិនតិចជាង|លើ|ច្រើនជាង|យ៉ាងតិច|យ៉ាងហោច" , Predicate isSimpleQuantity ] , prod = \case (_: Token Quantity QuantityData{TQuantity.value = Just from , TQuantity.unit = Just u , TQuantity.aproduct = Nothing}: _) -> Just . Token Quantity . withMin from $ unitOnly u _ -> Nothing } rules :: [Rule] rules = [ ruleNumeralUnits , ruleQuantityOfProduct , rulePrecision , ruleIntervalBetweenNumeral , ruleIntervalBetween , ruleIntervalNumeralDash , ruleIntervalDash , ruleIntervalMax , ruleIntervalMin ] ++ruleNumeralUnits2
facebookincubator/duckling
Duckling/Quantity/KM/Rules.hs
bsd-3-clause
8,305
0
19
2,305
1,981
1,096
885
199
2
{-# LANGUAGE CPP, OverloadedStrings, PatternGuards, TupleSections, Rank2Types #-} module HTIG.TwitterAPI ( Timeline , Status(..) , TwitterUser(..) , getHomeTimeline , getMentions , getFriends , getLastStatus , updateStatus , followScreenName , unFollowScreenName , retweet , getUserTimeline , getRateLimit , userStreamIter , doOAuth -- re-export for convention , Result(Ok, Error) , Token ) where import Control.Applicative ((<$>), (<*>), (<|>)) import Control.Monad (forM_) import Control.Monad.Trans (MonadIO, liftIO) import Data.Function (on) import Data.List (sortBy) import Data.Maybe (catMaybes, fromJust, maybeToList) import Data.Time (UTCTime, parseTime) import Network.OAuth.Consumer (Application, Token(application), SigMethod(HMACSHA1), OAuthMonadT, oauthParams, runOAuthM, fromApplication, signRq2, oauthRequest, getToken, putToken, serviceRequest, injectOAuthVerifier) import HTIG.EnumHttpClient (EnumHttpClient(EnumHttpClient, EnumHttpClientWithIter), EnumResponseHandler) import Network.OAuth.Http.Request (Request(method, pathComps, qString), Method(GET, POST), findWithDefault, parseURL, fromList, union) import Network.OAuth.Http.Response (Response(status, reason, rspPayload)) import Network.OAuth.Http.Util (splitBy) import System.Locale (defaultTimeLocale) import Text.JSON (JSValue(JSObject, JSNull), Result(Ok, Error), JSON, JSObject, decode, readJSON, valFromObj) import qualified Data.ByteString.Lazy.UTF8 as BU import qualified Data.ByteString.UTF8 as BSU import Network.HTTP.Enumerator (Response(Response, responseBody)) import qualified Network.HTTP.Types as W import Data.Enumerator ((=$)) import qualified Data.Enumerator as E import qualified Data.Enumerator.Binary as EB import qualified Data.Enumerator.List as EL #include "../debug.hs" -- -- | Twitter API types -- twitterAPIURL :: String twitterAPIURL = "https://api.twitter.com/" twitterAPIVersion :: Int twitterAPIVersion = 1 twitterStreamAPIURL :: String twitterStreamAPIURL = "https://userstream.twitter.com/" twitterStreamAPIVersion :: Int twitterStreamAPIVersion = 2 type Timeline = [Status] data Status = Status { stCreatedAt :: UTCTime , stId :: Integer , stText :: String , stSource :: String , stTruncated :: Bool , stInReplyToStatusId :: Maybe Integer , stInReplyToUserId :: Maybe Integer , stFavorited :: Bool , stInReplyToScreenName :: Maybe String , stUser :: TwitterUser --, stEntities :: Entities , stRetweetedStatus :: Maybe Status } deriving (Show, Read, Eq) data TwitterUser = TwitterUser { usId :: Integer , usName :: String , usScreenName :: String -- TODO: other user attributes } | TwitterUserId { usId :: Integer } deriving (Show, Read, Eq, Ord) data Entities = Entities { enUrls :: [UrlEntity] -- TODO: --, enMedia :: [MediaEntity] --, enUserMentions :: [UserMentionEntity] --, enHashtags :: [HashtagEntiry] } deriving (Show, Read, Eq) data UrlEntity = UrlEntity { ueUrl :: String , ueDisplayUrl :: Maybe String , ueExpandedUrl :: Maybe String , ueIndices :: (Int, Int) } deriving (Show, Read, Eq) decodeTimeline :: JSValue -> Result Timeline decodeTimeline input = readJSON input >>= mapM decodeStatus >>= return . sortBy (compare `on` stId) decodeStatus :: JSValue -> Result Status decodeStatus v@(JSObject obj) = do st <- decodeStatus' v case decodeEntities =<< valFromObj "entities" obj of Ok Entities { enUrls = ues } -> return st { stText = expandUrls ues $ stText st } _ -> return st decodeStatus j = Error $ "invalid JSValue" ++ show j decodeStatus' :: JSValue -> Result Status decodeStatus' (JSObject obj) = Status <$> (maybeToResult . parseTime' =<< valFromObj "created_at" obj) <*> valFromObj "id" obj <*> valFromObj "text" obj <*> valFromObj "source" obj <*> valFromObj "truncated" obj <*> valMayFromObj "in_reply_to_status_id" obj <*> valMayFromObj "in_reply_to_user_id" obj <*> valFromObj "favorited" obj <*> valMayFromObj "in_reply_to_screen_name" obj <*> (decodeUser =<< valFromObj "user" obj) <*> getRetweetedStatus obj decodeStatus' j = Error $ "invalid JSValue" ++ show j getRetweetedStatus :: JSObject JSValue -> Result (Maybe Status) getRetweetedStatus obj = case valFromObj "retweeted_status" obj of Ok j -> Just <$> decodeStatus j Error _ -> Ok Nothing -- | Nothing if value is null valMayFromObj :: JSON a => String -> JSObject JSValue -> Result (Maybe a) valMayFromObj cs obj = valFromObj cs obj >>= toMaybe where toMaybe JSNull = return Nothing toMaybe jv = Just <$> readJSON jv decodeUser :: JSValue -> Result TwitterUser decodeUser (JSObject obj) = TwitterUser <$> valFromObj "id" obj <*> valFromObj "name" obj <*> valFromObj "screen_name" obj <|> TwitterUserId <$> valFromObj "id" obj decodeUser j = Error $ "invalid JSValue" ++ show j decodeEntities :: JSValue -> Result Entities decodeEntities (JSObject obj) = Entities <$> (valFromObj "urls" obj >>= mapM decodeUrlEntity) decodeEntities j = Error $ "invalid JSValue" ++ show j decodeUrlEntity :: JSValue -> Result UrlEntity decodeUrlEntity (JSObject obj) = UrlEntity <$> valFromObj "url" obj <*> valMayFromObj "display_url" obj <*> valMayFromObj "expanded_url" obj <*> (valFromObj "indices" obj >>= l2t) where l2t [i, j] = Ok (i, j) l2t xs = Error $ "not a [i, j], but" ++ show xs decodeUrlEntity j = Error $ "invalid JSValue" ++ show j expandUrls :: [UrlEntity] -> String -> String expandUrls [] text = text expandUrls (ue@(UrlEntity { ueExpandedUrl = Just eurl, ueIndices = (start, end) }):ues) text = expandUrls ues $ take start text ++ eurl ++ drop end text expandUrls (_:ues) text = expandUrls ues text parseTime' :: String -> Maybe UTCTime parseTime' = parseTime defaultTimeLocale "%c" maybeToResult :: Maybe a -> Result a maybeToResult (Just a) = Ok a maybeToResult Nothing = Error "Nothing" -- | get home timeline getHomeTimeline :: Token -> Maybe Integer -- ^ Returns results with an ID greater than this ID -> IO (Result Timeline) getHomeTimeline tok mLastId = do let query = ("count", "20") : ("include_entities", "1") : (maybeToList $ (("since_id", ) . show) <$> mLastId) json <- callAPI GET tok "statuses/home_timeline" query return $ json >>= decodeTimeline -- | get home mentions getMentions :: Token -> Maybe Integer -- ^ Returns results with an ID greater than this ID -> IO (Result Timeline) getMentions tok mLastId = do let query = ("count", "20") : ("include_entities", "1") : (maybeToList $ (("since_id", ) . show) <$> mLastId) json <- callAPI GET tok "statuses/mentions" query return $ json >>= decodeTimeline -- | get friends from screen_name getFriends :: Token -> String -- ^ screen name -> IO (Result [TwitterUser]) getFriends tok screen_name = getFriends' tok screen_name (-1) getFriends' :: Token -> String -- ^ screen name -> Integer -- ^ cursor -> IO (Result [TwitterUser]) getFriends' tok screen_name cur = do json <- callAPI GET tok "statuses/friends" [ ("screen_name", screen_name) , ("cursor", show cur)] case json >>= decodeFriendsWithCursor of Ok (prev, next, users) -> if next /= 0 then do users' <- getFriends' tok screen_name next return $ (users ++) <$> users' else return $ Ok users Error e -> return $ Error e decodeFriendsWithCursor :: JSValue -> Result (Integer, Integer, [TwitterUser]) decodeFriendsWithCursor (JSObject obj) = do previous_cursor <- valFromObj "previous_cursor" obj next_cursor <- valFromObj "next_cursor" obj users <- valFromObj "users" obj >>= mapM decodeUser return (previous_cursor, next_cursor, users) decodeFriendsWithCursor j = Error $ "invalid JSValue" ++ show j -- | get authenticated user's last status getLastStatus :: Token -> IO (Result Status) getLastStatus tok = do -- if last status is official RT, count=1 return empty list -- so use count=5 json <- callAPI GET tok "statuses/user_timeline" [("count", "5"), ("include_entities", "1")] -- FIXME: crash when returned empty array return $ json >>= readJSON >>= decodeStatus . head -- | update twitter status updateStatus :: Token -> Maybe Integer -- ^ status id to reply -> String -- ^ status message -> IO (Result Status) updateStatus tok mRepId msg = do json <- callAPI POST tok "statuses/update" $ catMaybes [Just ("status", msg) , ("in_reply_to_status_id", ) . show <$> mRepId] return $ json >>= decodeStatus -- | follow screen_name followScreenName :: Token -> String -- ^ screen name to follow -> IO (Result TwitterUser) followScreenName tok sname = do ret <- callAPI POST tok "friendships/create" [("screen_name", sname), ("follow", "true")] return $ ret >>= decodeUser -- | unfollow screen_name unFollowScreenName :: Token -> String -- ^ screen name to unfollow -> IO (Result ()) unFollowScreenName tok sname = do -- XXX: is friendships/destroy return valid JSON string? ret <- callAPI POST tok "friendships/destroy" [("screen_name", sname)] return $ (const ()) <$> ret -- | retweet status retweet :: Token -> Integer -- ^ status id to retweet -> IO (Result Status) retweet tok stid = do ret <- callAPI POST tok ("statuses/retweet/" ++ show stid) [] return $ ret >>= decodeStatus -- | get some user's recent statuses getUserTimeline :: Token -> String -- ^ screen_name -> Maybe Int -- ^ number of record to retrieve -> IO (Result Timeline) getUserTimeline tok sname mnum = do json <- callAPI GET tok "statuses/user_timeline" $ catMaybes [Just ("screen_name", sname) ,Just ("include_entities", "1") , ("count", ) . show <$> mnum] return $ json >>= decodeTimeline -- | get rate limit status -- return value is tuple of -- (remaining_hits, hourly_limit) getRateLimit :: Token -> IO (Result (Int, Int)) getRateLimit tok = do json <- callAPI GET tok "account/rate_limit_status" [] return $ case json of Ok (JSObject obj) -> (, ) <$> valFromObj "remaining_hits" obj <*> valFromObj "hourly_limit" obj Ok j -> Error $ "invalid JSValue: " ++ show j -- to convert (Result JSValue) to (Result (Int, Int)), -- extract error message and re-wrap with Error. Error e -> Error e -- | call twitter API -- callAPI GET tok "statuses/home_timeline" [] callAPI :: Method -> Token -> String -- ^ path component of target API -> [(String, String)] -- ^ query parameters -> IO (Result JSValue) callAPI m tok path query = callAPI' tok req EnumHttpClient where req = mkAPIRequest m (path ++ ".json") query callAPI' :: Token -> Request -> EnumHttpClient -> IO (Result JSValue) callAPI' tok req client = (runOAuthM tok $ do putToken tok debug req resp <- signRq2 HMACSHA1 Nothing req >>= serviceRequest client --debug resp case status resp of 200 -> return $ decode $ BU.toString $ rspPayload resp -- maybe connection error 0 -> return $ Error "unknown error" _ -> return $ Error $ show (status resp) ++ " " ++ show (reason resp)) `catch` (\e -> return $ Error $ show e) mkAPIRequest :: Method -> String -> [(String, String)] -> Request mkAPIRequest = mkAPIRequest' twitterAPIURL twitterAPIVersion mkAPIRequest' :: String -- API URL -> Int -- API Version -> Method -> String -> [(String, String)] -> Request mkAPIRequest' url ver m path query = req where rawReq = fromJust $ parseURL url req = rawReq { method = m , pathComps = "" : show ver : splitBy (== '/') path , qString = fromList query `union` qString rawReq } -- -- | User Stream API -- userStreamIter :: Token -> (Status -> IO a) -> IO (Result ()) userStreamIter tok f = callStreamAPI handler GET tok "user" [] where handler (W.Status sc _) hs = do splitStreamE =$ do -- drop initial stream, friends list EL.head E.continue go return (Response sc hs "") go (E.Chunks css) = do forM_ css $ \cs -> case decode cs >>= decodeStatus of Ok st -> liftIO (f st) >> return () Error e -> debug e E.continue go go E.EOF = E.yield () E.EOF -- | call twitter API -- callStreamAPI handler GET tok "user" [] callStreamAPI :: EnumResponseHandler -> Method -> Token -> String -- ^ path component of target API -> [(String, String)] -- ^ query parameters -> IO (Result ()) callStreamAPI iter m tok path query = do resp <- callAPI' tok req $ EnumHttpClientWithIter $ \s hs -> do resp <- iter s hs -- to always return JSNull return $ resp { responseBody = "null" } debug resp case resp of Ok JSNull -> return $ Ok () Error e -> return $ Error e where req = mkStreamAPIRequest m (path ++ ".json") query mkStreamAPIRequest :: Method -> String -> [(String, String)] -> Request mkStreamAPIRequest = mkAPIRequest' twitterStreamAPIURL twitterStreamAPIVersion splitStreamE :: Monad m => E.Enumeratee BSU.ByteString String m b splitStreamE iter = EB.splitWhen (==13 {- '\r' -}) =$ EL.map BSU.toString =$ EL.map removeInitialNewline =$ EL.filter (/="") iter where removeInitialNewline ('\n':cs) = cs removeInitialNewline cs = cs -- -- | Twitter OAuth handler -- reqURL, accURL, authURL :: String reqURL = "https://twitter.com/oauth/request_token" accURL = "https://twitter.com/oauth/access_token" authURL = "https://twitter.com/oauth/authorize" toAuthURL :: Token -> String toAuthURL = ((authURL ++ "?oauth_token=") ++) . findWithDefault ("oauth_token", "") . oauthParams doOAuth :: Application -> (String -> IO String) -- ^ IO action to display auth URL and ask verifier -> IO Token doOAuth app asker = runOAuthM (fromApplication app) $ do -- get request token signRq2 HMACSHA1 Nothing (fromJust . parseURL $ reqURL) >>= oauthRequest EnumHttpClient -- display authorization URL to user, get verifier from user askAuthorizationBy toAuthURL asker -- get access token signRq2 HMACSHA1 Nothing (fromJust . parseURL $ accURL) >>= oauthRequest EnumHttpClient getToken askAuthorizationBy :: MonadIO m => (Token -> String) -> (String -> IO String) -> OAuthMonadT m () askAuthorizationBy toURL asker = do token <- getToken ans <- liftIO $ asker (toURL token) putToken $ injectOAuthVerifier ans token
nakamuray/htig
HTIG/TwitterAPI.hs
bsd-3-clause
16,046
0
18
4,571
4,218
2,239
1,979
314
3
module PackageManagement ( Transplantable(..) , parseVersion , parsePkgInfo , insideGhcPkg , outsideGhcPkg , getHighestVersion , GhcPkg ) where import Distribution.Package (PackageIdentifier(..), PackageName(..)) import Distribution.Version (Version(..)) import Control.Monad (unless) import Types import HsenvMonad import Process (outsideProcess, insideProcess) import Util.Cabal (prettyPkgInfo, prettyVersion) import qualified Util.Cabal (parseVersion, parsePkgInfo) type GhcPkg = [String] -> Maybe String -> Hsenv String outsideGhcPkg :: GhcPkg outsideGhcPkg = outsideProcess "ghc-pkg" insideGhcPkg :: GhcPkg insideGhcPkg = insideProcess "ghc-pkg" parseVersion :: String -> Hsenv Version parseVersion s = case Util.Cabal.parseVersion s of Nothing -> throwError $ HsenvException $ "Couldn't parse " ++ s ++ " as a package version" Just version -> return version parsePkgInfo :: String -> Hsenv PackageIdentifier parsePkgInfo s = case Util.Cabal.parsePkgInfo s of Nothing -> throwError $ HsenvException $ "Couldn't parse package identifier " ++ s Just pkgInfo -> return pkgInfo getDeps :: PackageIdentifier -> Hsenv [PackageIdentifier] getDeps pkgInfo = do let prettyPkg = prettyPkgInfo pkgInfo debug $ "Extracting dependencies of " ++ prettyPkg out <- indentMessages $ outsideGhcPkg ["field", prettyPkg, "depends"] Nothing -- example output: -- depends: ghc-prim-0.2.0.0-3fbcc20c802efcd7c82089ec77d92990 -- integer-gmp-0.2.0.0-fa82a0df93dc30b4a7c5654dd7c68cf4 builtin_rts case words out of [] -> throwError $ HsenvException $ "Couldn't parse ghc-pkg output to find dependencies of " ++ prettyPkg _:depStrings -> do -- skip 'depends:' indentMessages $ trace $ "Found dependency strings: " ++ unwords depStrings mapM parsePkgInfo depStrings -- things that can be copied from system's GHC pkg database -- to GHC pkg database inside virtual environment class Transplantable a where transplantPackage :: a -> Hsenv () getHighestVersion :: PackageName -> GhcPkg -> Hsenv Version getHighestVersion (PackageName packageName) ghcPkg = do debug $ "Checking the highest installed version of package " ++ packageName out <- indentMessages $ ghcPkg ["field", packageName, "version"] Nothing -- example output: -- version: 1.1.4 -- version: 1.2.0.3 let extractVersionString :: String -> Hsenv String extractVersionString line = case words line of [_, x] -> return x _ -> throwError $ HsenvException $ "Couldn't extract version string from: " ++ line versionStrings <- mapM extractVersionString $ lines out indentMessages $ trace $ "Found version strings: " ++ unwords versionStrings versions <- mapM parseVersion versionStrings case versions of [] -> throwError $ HsenvException $ "No versions of package " ++ packageName ++ " found" (v:vs) -> do indentMessages $ debug $ "Found: " ++ unwords (map prettyVersion versions) return $ foldr max v vs -- choose the highest installed version of package with this name instance Transplantable PackageName where transplantPackage pkg@(PackageName packageName) = do debug $ "Copying package " ++ packageName ++ " to Virtual Haskell Environment." indentMessages $ do highestVersion <- getHighestVersion pkg outsideGhcPkg debug $ "Using version: " ++ prettyVersion highestVersion let pkgInfo = PackageIdentifier (PackageName packageName) highestVersion transplantPackage pkgInfo -- check if this package is already installed in Virtual Haskell Environment checkIfInstalled :: PackageIdentifier -> Hsenv Bool checkIfInstalled pkgInfo = do let package = prettyPkgInfo pkgInfo debug $ "Checking if " ++ package ++ " is already installed." (do _ <- indentMessages $ insideGhcPkg ["describe", package] Nothing indentMessages $ debug "It is." return True) `catchError` handler where handler _ = do debug "It's not." return False instance Transplantable PackageIdentifier where transplantPackage pkgInfo = do let prettyPkg = prettyPkgInfo pkgInfo debug $ "Copying package " ++ prettyPkg ++ " to Virtual Haskell Environment." indentMessages $ do flag <- checkIfInstalled pkgInfo unless flag $ do deps <- getDeps pkgInfo debug $ "Found: " ++ unwords (map prettyPkgInfo deps) mapM_ transplantPackage deps movePackage pkgInfo -- copy single package that already has all deps satisfied movePackage :: PackageIdentifier -> Hsenv () movePackage pkgInfo = do let prettyPkg = prettyPkgInfo pkgInfo debug $ "Moving package " ++ prettyPkg ++ " to Virtual Haskell Environment." out <- outsideGhcPkg ["describe", prettyPkg] Nothing _ <- insideGhcPkg ["register", "-"] (Just out) return ()
Paczesiowa/hsenv
src/PackageManagement.hs
bsd-3-clause
5,095
0
17
1,217
1,161
574
587
94
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-| This snaplet makes it simple to use a SQLite database from your Snap application and is based on the sqlite-simple library (<http://hackage.haskell.org/package/sqlite-simple>). Now, adding a database to your web app takes just two simple steps. First, include this snaplet in your application's state. > data App = App > { ... -- Other state needed in your app > , _db :: Snaplet Sqlite > } Next, call the sqliteInit from your application's initializer. > appInit = makeSnaplet ... $ do > ... > d <- nestSnaplet "db" db sqliteInit > return $ App ... d Now you can use any of the sqlite-simple wrapper functions defined in this module anywhere in your application handlers. For instance: > postHandler :: Handler App App () > postHandler = do > posts <- with db $ query_ "select * from blog_post" > ... Optionally, if you find yourself doing many database queries, you can eliminate some of the boilerplate by defining a HasSqlite instance for your application. > instance HasSqlite (Handler b App) where > getSqliteState = with db get With this code, our postHandler example no longer requires the 'with' function: > postHandler :: Handler App App () > postHandler = do > posts <- query_ "select * from blog_post" > ... The first time you run an application with the sqlite-simple snaplet, a configuration file @devel.cfg@ is created in the @snaplets/sqlite-simple@ directory underneath your project root. It specifies how to connect to your Sqlite database. Edit this file and modify the values appropriately and you'll be off and running. If you want to have out-of-the-box authentication, look at the documentation for the "Snap.Snaplet.Auth.Backends.Sqlite" module. -} module Snap.Snaplet.SqliteSimple ( -- * The Snaplet Sqlite(..) , HasSqlite(..) , sqliteInit , withSqlite -- * Wrappers and re-exports , query , query_ , execute , execute_ -- Re-exported from sqlite-simple , S.Connection , S.Query , S.Only(..) , S.FormatError(..) , S.ResultError(..) , (S.:.)(..) , ToRow(..) , FromRow(..) , field ) where import Prelude hiding (catch) import Control.Concurrent import Control.Lens import Control.Monad.Base import Control.Monad.IO.Class import Control.Monad.State import Control.Monad.Trans.Reader import Control.Monad.Trans.Writer import qualified Data.Configurator as C import Data.List import Data.Maybe import qualified Data.Text as T import Database.SQLite.Simple.ToRow import Database.SQLite.Simple.FromRow import qualified Database.SQLite.Simple as S import Snap import Paths_snaplet_sqlite_simple ------------------------------------------------------------------------------ -- | The state for the sqlite-simple snaplet. To use it in your app -- include this in your application state and use 'sqliteInit' to initialize it. data Sqlite = Sqlite { sqliteConn :: MVar S.Connection -- ^ Function for retrieving the database connection } ------------------------------------------------------------------------------ -- | Instantiate this typeclass on 'Handler b YourAppState' so this snaplet -- can find the connection source. If you need to have multiple instances of -- the sqlite snaplet in your application, then don't provide this instance -- and leverage the default instance by using \"@with dbLens@\" in front of calls -- to snaplet-sqlite-simple functions. class (MonadBase IO m) => HasSqlite m where getSqliteState :: m Sqlite ------------------------------------------------------------------------------ -- | Default instance instance HasSqlite (Handler b Sqlite) where getSqliteState = get ------------------------------------------------------------------------------ -- | A convenience instance to make it easier to use this snaplet in the -- Initializer monad like this: -- -- > d <- nestSnaplet "db" db sqliteInit -- > count <- liftIO $ runReaderT (execute "INSERT ..." params) d instance (MonadBase IO m) => HasSqlite (ReaderT (Snaplet Sqlite) m) where getSqliteState = asks (\sqlsnaplet -> sqlsnaplet ^# snapletValue) ------------------------------------------------------------------------------ -- | A convenience instance to make it easier to use functions written for -- this snaplet in non-snaplet contexts. instance (MonadBase IO m) => HasSqlite (ReaderT Sqlite m) where getSqliteState = ask ------------------------------------------------------------------------------ -- | Convenience function allowing easy collection of config file errors. logErr :: MonadIO m => t -> IO (Maybe a) -> WriterT [t] m (Maybe a) logErr err m = do res <- liftIO m when (isNothing res) (tell [err]) return res ------------------------------------------------------------------------------ -- | Initialize the snaplet sqliteInit :: SnapletInit b Sqlite sqliteInit = makeSnaplet "sqlite-simple" description datadir $ do config <- getSnapletUserConfig (mci,errs) <- runWriterT $ logErr "Must specify db filename" $ C.lookup config "db" let ci = fromMaybe (error $ intercalate "\n" errs) mci tracing <- liftIO $ C.lookupDefault False config "enableSqlTracing" conn <- liftIO (S.open ci >>= setTracing tracing >>= newMVar) return $ Sqlite conn where description = "Sqlite abstraction" datadir = Just $ liftM (++"/resources/db") getDataDir setTracing tracing conn = do when tracing (S.setTrace conn (Just (putStrLn . T.unpack))) return conn ------------------------------------------------------------------------------ -- | Convenience function for executing a function that needs a database -- connection. -- -- /Multi-threading considerations/: The database connection is mutexed -- such that only a single thread can read or write at any given time. -- This means we lose database access parallelism. Please see -- <https://github.com/nurpax/snaplet-sqlite-simple/issues/5> for more -- information. withSqlite :: (HasSqlite m) => (S.Connection -> IO b) -> m b withSqlite f = do s <- getSqliteState let conn = sqliteConn s liftBase $ withMVar conn f ------------------------------------------------------------------------------ -- | See 'S.query' -- -- See also 'withSqlite' for notes on concurrent access. query :: (HasSqlite m, ToRow q, FromRow r) => S.Query -> q -> m [r] query q params = withSqlite (\c -> S.query c q params) ------------------------------------------------------------------------------ -- | See 'S.query_' -- -- See also 'withSqlite' for notes on concurrent access. query_ :: (HasSqlite m, FromRow r) => S.Query -> m [r] query_ q = withSqlite (`S.query_` q) ------------------------------------------------------------------------------ -- | -- -- See also 'withSqlite' for notes on concurrent access. execute :: (HasSqlite m, ToRow q) => S.Query -> q -> m () execute template qs = withSqlite (\c -> S.execute c template qs) ------------------------------------------------------------------------------ -- | -- -- See also 'withSqlite' for notes on concurrent access. execute_ :: (HasSqlite m) => S.Query -> m () execute_ template = withSqlite (`S.execute_` template)
nurpax/snaplet-sqlite-simple
src/Snap/Snaplet/SqliteSimple.hs
bsd-3-clause
7,445
0
16
1,395
1,045
590
455
85
1
{-# LANGUAGE MagicHash, UnboxedTuples #-} module CoreFoundation.Types.Array.Internal where import GHC.Exts(touch#) import GHC.IO(IO(..)) import qualified Data.Vector as V import qualified Data.Vector.Storable as S import qualified Data.Vector.Storable.Mutable as SM import CoreFoundation.Types.Base import Foreign import Control.Exception withVector :: CF a => V.Vector a -> (Ptr (Ptr (Repr a)) -> Int -> IO b) -> IO b withVector v f = (S.unsafeWith (V.convert (V.map extractPtr v)) $ \buf -> f buf (V.length v)) `finally` touch v buildVector :: CF a => Int -> (Ptr (Ptr (Repr a)) -> IO b) -> IO (V.Vector a, b) buildVector len f = do mvec <- SM.new (fromIntegral len) res <- SM.unsafeWith mvec $ \ptr -> f ptr vec <- S.unsafeFreeze mvec vec' <- V.mapM (get . return) $ S.convert vec return (vec', res) touch :: a -> IO () touch a = IO (\s -> (# touch# a s, () #))
reinerp/CoreFoundation
CoreFoundation/Types/Array/Internal.hs
bsd-3-clause
887
0
14
166
406
213
193
23
1
module Render.Atom where import Prettyprinter import Polysemy import Polysemy.Input import Relude hiding ( Handle , lift ) import Foreign.Storable import Numeric import Text.Show import Error import Haskell as H import Render.Element import Spec.Parse renderAtom :: (HasErr r, HasRenderParams r) => Atom -> Sem r RenderElement renderAtom Atom {..} = context (unCName atName) $ do RenderParams {..} <- input genRe ("atom " <> unCName atName) $ do let n = mkTyName atName let t = ConT ''Word64 c = mkConName atName atName tDoc <- renderTypeHighPrec t tellDataExport n tellImport (TyConName "Zero") tellImport ''Storable tellImport 'showHex tellImport 'showParen tellDocWithHaddock $ \getDoc -> vsep $ [ getDoc (TopLevel atName) , "newtype" <+> pretty n <+> "=" <+> pretty c <+> tDoc , indent 2 "deriving newtype (Eq, Ord, Storable, Zero)" ] <> [ "instance Show" <+> pretty n <+> "where" <> line <> indent 2 ( "showsPrec p" <+> parens (pretty c <+> "x") <+> "= showParen (p >= 11)" <+> parens ( "showString" <+> viaShow (unName c <> " 0x") <+> ". showHex x" ) ) ]
expipiplus1/vulkan
generate-new/src/Render/Atom.hs
bsd-3-clause
1,603
0
26
717
382
190
192
-1
-1
{-#LANGUAGE FlexibleInstances #-} {-#LANGUAGE TypeSynonymInstances #-} module Twilio.Types.Capability where import Control.Monad import Data.Aeson import qualified Data.HashMap.Strict as HashMap import Data.Set (Set) import qualified Data.Set as Set import qualified Data.Text as T type Capabilities = Set Capability data Capability = Voice | SMS | MMS deriving (Bounded, Enum, Eq, Ord, Read, Show) instance FromJSON Capabilities where parseJSON (Object map) = let map' = fmap (\value -> case value of Bool bool -> bool _ -> False) map in return $ foldr (\capability set -> if HashMap.lookupDefault False (T.pack $ show capability) map' then Set.insert capability set else set ) Set.empty [Voice, SMS, MMS] parseJSON _ = mzero
seagreen/twilio-haskell
src/Twilio/Types/Capability.hs
bsd-3-clause
870
0
16
249
244
137
107
26
0
module Singletons.Fixity where import Data.Singletons import Data.Singletons.TH import Language.Haskell.TH.Desugar import Prelude.Singletons $(singletons [d| class MyOrd a where (<=>) :: a -> a -> Ordering infix 4 <=> (====) :: a -> a -> a a ==== _ = a infix 4 ==== |])
goldfirere/singletons
singletons-base/tests/compile-and-dump/Singletons/Fixity.hs
bsd-3-clause
290
0
7
63
43
27
16
-1
-1
-- | -- Module : Crypto.Hash.Blake2 -- License : BSD-style -- Maintainer : Nicolas Di Prima <[email protected]> -- Stability : experimental -- Portability : unknown -- -- Module containing the binding functions to work with the -- Blake2 -- -- Implementation based from [RFC7693](https://tools.ietf.org/html/rfc7693) -- -- Please consider the following when chosing a hash: -- -- Algorithm | Target | Collision | Digest Size | -- Identifier | Arch | Security | in bytes | -- ---------------+--------+-----------+-------------+ -- id-blake2b160 | 64-bit | 2**80 | 20 | -- id-blake2b256 | 64-bit | 2**128 | 32 | -- id-blake2b384 | 64-bit | 2**192 | 48 | -- id-blake2b512 | 64-bit | 2**256 | 64 | -- ---------------+--------+-----------+-------------+ -- id-blake2s128 | 32-bit | 2**64 | 16 | -- id-blake2s160 | 32-bit | 2**80 | 20 | -- id-blake2s224 | 32-bit | 2**112 | 28 | -- id-blake2s256 | 32-bit | 2**128 | 32 | -- ---------------+--------+-----------+-------------+ -- {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} module Crypto.Hash.Blake2 ( Blake2s(..) , Blake2sp(..) , Blake2b(..) , Blake2bp(..) ) where import Crypto.Hash.Types import Foreign.Ptr (Ptr) import Data.Data import Data.Typeable import Data.Word (Word8, Word32) import GHC.TypeLits (Nat, KnownNat, natVal) import Crypto.Internal.Nat -- | Fast and secure alternative to SHA1 and HMAC-SHA1 -- -- It is espacially known to target 32bits architectures. -- -- Known supported digest sizes: -- -- * Blake2s 160 -- * Blake2s 224 -- * Blake2s 256 -- data Blake2s (bitlen :: Nat) = Blake2s deriving (Show, Typeable) instance (IsDivisibleBy8 bitlen, KnownNat bitlen, IsAtLeast bitlen 8, IsAtMost bitlen 256) => HashAlgorithm (Blake2s bitlen) where type HashBlockSize (Blake2s bitlen) = 64 type HashDigestSize (Blake2s bitlen) = Div8 bitlen type HashInternalContextSize (Blake2s bitlen) = 136 hashBlockSize _ = 64 hashDigestSize _ = byteLen (Proxy :: Proxy bitlen) hashInternalContextSize _ = 136 hashInternalInit p = c_blake2s_init p (integralNatVal (Proxy :: Proxy bitlen)) hashInternalUpdate = c_blake2s_update hashInternalFinalize p = c_blake2s_finalize p (integralNatVal (Proxy :: Proxy bitlen)) foreign import ccall unsafe "cryptonite_blake2s_init" c_blake2s_init :: Ptr (Context a) -> Word32 -> IO () foreign import ccall "cryptonite_blake2s_update" c_blake2s_update :: Ptr (Context a) -> Ptr Word8 -> Word32 -> IO () foreign import ccall unsafe "cryptonite_blake2s_finalize" c_blake2s_finalize :: Ptr (Context a) -> Word32 -> Ptr (Digest a) -> IO () -- | Fast cryptographic hash. -- -- It is especially known to target 64bits architectures. -- -- Known supported digest sizes: -- -- * Blake2b 160 -- * Blake2b 224 -- * Blake2b 256 -- * Blake2b 384 -- * Blake2b 512 -- data Blake2b (bitlen :: Nat) = Blake2b deriving (Show, Typeable) instance (IsDivisibleBy8 bitlen, KnownNat bitlen, IsAtLeast bitlen 8, IsAtMost bitlen 512) => HashAlgorithm (Blake2b bitlen) where type HashBlockSize (Blake2b bitlen) = 128 type HashDigestSize (Blake2b bitlen) = Div8 bitlen type HashInternalContextSize (Blake2b bitlen) = 248 hashBlockSize _ = 128 hashDigestSize _ = byteLen (Proxy :: Proxy bitlen) hashInternalContextSize _ = 248 hashInternalInit p = c_blake2b_init p (integralNatVal (Proxy :: Proxy bitlen)) hashInternalUpdate = c_blake2b_update hashInternalFinalize p = c_blake2b_finalize p (integralNatVal (Proxy :: Proxy bitlen)) foreign import ccall unsafe "cryptonite_blake2b_init" c_blake2b_init :: Ptr (Context a) -> Word32 -> IO () foreign import ccall "cryptonite_blake2b_update" c_blake2b_update :: Ptr (Context a) -> Ptr Word8 -> Word32 -> IO () foreign import ccall unsafe "cryptonite_blake2b_finalize" c_blake2b_finalize :: Ptr (Context a) -> Word32 -> Ptr (Digest a) -> IO () data Blake2sp (bitlen :: Nat) = Blake2sp deriving (Show, Typeable) instance (IsDivisibleBy8 bitlen, KnownNat bitlen, IsAtLeast bitlen 8, IsAtMost bitlen 256) => HashAlgorithm (Blake2sp bitlen) where type HashBlockSize (Blake2sp bitlen) = 64 type HashDigestSize (Blake2sp bitlen) = Div8 bitlen type HashInternalContextSize (Blake2sp bitlen) = 2185 hashBlockSize _ = 64 hashDigestSize _ = byteLen (Proxy :: Proxy bitlen) hashInternalContextSize _ = 2185 hashInternalInit p = c_blake2sp_init p (integralNatVal (Proxy :: Proxy bitlen)) hashInternalUpdate = c_blake2sp_update hashInternalFinalize p = c_blake2sp_finalize p (integralNatVal (Proxy :: Proxy bitlen)) foreign import ccall unsafe "cryptonite_blake2sp_init" c_blake2sp_init :: Ptr (Context a) -> Word32 -> IO () foreign import ccall "cryptonite_blake2sp_update" c_blake2sp_update :: Ptr (Context a) -> Ptr Word8 -> Word32 -> IO () foreign import ccall unsafe "cryptonite_blake2sp_finalize" c_blake2sp_finalize :: Ptr (Context a) -> Word32 -> Ptr (Digest a) -> IO () data Blake2bp (bitlen :: Nat) = Blake2bp deriving (Show, Typeable) instance (IsDivisibleBy8 bitlen, KnownNat bitlen, IsAtLeast bitlen 8, IsAtMost bitlen 512) => HashAlgorithm (Blake2bp bitlen) where type HashBlockSize (Blake2bp bitlen) = 128 type HashDigestSize (Blake2bp bitlen) = Div8 bitlen type HashInternalContextSize (Blake2bp bitlen) = 2325 hashBlockSize _ = 128 hashDigestSize _ = byteLen (Proxy :: Proxy bitlen) hashInternalContextSize _ = 2325 hashInternalInit p = c_blake2bp_init p (integralNatVal (Proxy :: Proxy bitlen)) hashInternalUpdate = c_blake2bp_update hashInternalFinalize p = c_blake2bp_finalize p (integralNatVal (Proxy :: Proxy bitlen)) foreign import ccall unsafe "cryptonite_blake2bp_init" c_blake2bp_init :: Ptr (Context a) -> Word32 -> IO () foreign import ccall "cryptonite_blake2bp_update" c_blake2bp_update :: Ptr (Context a) -> Ptr Word8 -> Word32 -> IO () foreign import ccall unsafe "cryptonite_blake2bp_finalize" c_blake2bp_finalize :: Ptr (Context a) -> Word32 -> Ptr (Digest a) -> IO ()
tekul/cryptonite
Crypto/Hash/Blake2.hs
bsd-3-clause
6,710
0
11
1,591
1,518
816
702
-1
-1
-- | Data.Algorithm.Diff-like API module Data.Snakes.DiffLike ( Diff (..) , getDiff ) where import Data.Functor.Identity import Data.Snakes getDiff :: Eq t => [t] -> [t] -> [Diff t] getDiff l r = case runIdentity $ diffStream Straight Nothing l r of Just s -> runIdentity $ streamToList s Nothing -> error "Data.Snakes.DiffLike.getDiff: unbounded search does not yield any result." {-# INLINE getDiff #-}
schernichkin/snakes
src/Data/Snakes/DiffLike.hs
bsd-3-clause
418
0
9
76
116
63
53
10
2
op :: Op -> Val -> Maybe Val op Add1 (LitV (I n)) = Just $ LitV $ I $ n+1 op Sub1 (LitV (I n)) = Just $ LitV $ I $ n-1 op IsNonNeg (LitV (I n)) | n >= 0 = Just $ LitV $ B True | otherwise = Just $ LitV $ B False op _ _ = Nothing
davdar/quals
writeup-old/sections/03AAMByExample/01Concrete/01Op.hs
bsd-3-clause
254
0
9
89
166
80
86
6
1
module HPack.System ( module X ) where import HPack.System.PkgDB as X
markflorisson/hpack
src/HPack/System.hs
bsd-3-clause
71
0
4
12
20
14
6
3
0
module PermutationStatistics where import Tree import Permutation(allPermutations, inverse) ignoresInverse :: (Eq a) => ([Int] -> a) -> Int -> Bool ignoresInverse f = all g . allPermutations where g p = f p == f (inverse p) descents [] = [] descents (p:ps) = zipWith (<) ps (p:ps) des :: [Int] -> Int des = length . filter id . descents
cullina/Extractor
src/PermutationStatistics.hs
bsd-3-clause
360
0
10
84
162
87
75
10
1
module Snaplet.Authentication.Queries ( lookupByEmail , hashFor , resetUidpwdUserPassword , createUidpwdUser , getGithubAccessToken , handleSql , HashedPassword ) where import Control.Exception (throw) import Control.Monad.IO.Class import Crypto.BCrypt import Data.Text (Text) import Data.Text.Encoding import Data.Time import Database.Esqueleto import Kashmir.Email import Kashmir.Github.Types import Kashmir.UUID import Snap import Snaplet.Authentication.Common import Snaplet.Authentication.Exception import Snaplet.Authentication.Schema lookupByEmail :: Email -> SqlPersistM (Maybe (Account, AccountUidpwd)) lookupByEmail email = onlyOne . fmap unwrap <$> (select . from $ \(account `InnerJoin` accountUidpwd) -> do on $ account ^. AccountAccountId ==. accountUidpwd ^. AccountUidpwdAccountId where_ (accountUidpwd ^. AccountUidpwdEmail ==. val email) return (account, accountUidpwd)) unwrap :: (Entity a, Entity b) -> (a, b) unwrap (e, f) = (entityVal e, entityVal f) onlyOne :: [a] -> Maybe a onlyOne xs = case xs of [] -> Nothing [x] -> Just x _ -> throw DuplicateAccount data HashedPassword = HashedPassword { hash :: Text } hashFor :: Text -> IO (Maybe HashedPassword) hashFor password = do hashed <- hashPasswordUsingPolicy fastBcryptHashingPolicy $ encodeUtf8 password return (HashedPassword . decodeUtf8 <$> hashed) createUidpwdUser :: UUID -> UTCTime -> Email -> HashedPassword -> SqlPersistM (Key Account) createUidpwdUser uuid created email hashedPassword = do accountKey <- insert $ Account uuid created _ <- insert AccountUidpwd { accountUidpwdAccountId = unAccountKey accountKey , accountUidpwdEmail = email , accountUidpwdPassword = hash hashedPassword } return accountKey resetUidpwdUserPassword :: UUID -> HashedPassword -> SqlPersistM (Maybe Account) resetUidpwdUserPassword userId hashedPassword = do updatedRows <- updateCount $ \accountUidpwd -> do set accountUidpwd [AccountUidpwdPassword =. val (hash hashedPassword)] where_ ((accountUidpwd ^. AccountUidpwdAccountId) ==. val userId) case updatedRows of 0 -> return Nothing 1 -> get (AccountKey userId) getGithubAccessToken :: Key Account -> SqlPersistM (Maybe AccessToken) getGithubAccessToken key = onlyOne . fmap unValue <$> (select . from $ \accountGithub -> do where_ (accountGithub ^. AccountGithubAccountId ==. val key) return (accountGithub ^. AccountGithubAccessToken)) ------------------------------------------------------------ handleSql :: SqlPersistM a -> Handler b (Authentication b) a handleSql sql = do connection <- getConnection liftIO $ runSqlPersistMPool sql connection
krisajenkins/snaplet-auth
src/Snaplet/Authentication/Queries.hs
bsd-3-clause
2,800
0
17
549
788
407
381
78
3
{-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE InstanceSigs #-} module PFDS.Sec9.Ex14 where import qualified PFDS.Commons.QueueFamily as Q import qualified PFDS.Commons.RandomAccessList as L import PFDS.Commons.SkewBinaryRandomAccessList import Prelude hiding (head, tail, lookup) type instance Q.Elem (Queue a) = a data RotationState a = Idle | Reversing Int (RList a) (RList a) (RList a) (RList a) | Appending Int (RList a) (RList a) | Done (RList a) data Queue a = Q Int (RList a) (RotationState a) Int (RList a) exec :: RotationState a -> RotationState a exec (Reversing ok f f' r r') = if L.isEmpty f then Appending ok f' (L.head r `L.cons` r') else Reversing (ok + 1) (L.tail f) (L.head f `L.cons` f') r (L.head r `L.cons` r') exec (Appending 0 f' r') = Done r' exec (Appending ok f' r') = if L.isEmpty f' then Appending (ok - 1) (L.tail f') (L.head f' `L.cons` r') else Appending ok f' r' exec state = state invalidate :: RotationState a -> RotationState a invalidate (Reversing ok f f' r r') = Reversing (ok - 1) f f' r r' invalidate (Appending 0 f' r') = Done (L.tail r') invalidate (Appending ok f' r') = Appending (ok - 1) f' r' invalidate state = state exec2 :: Queue a -> Queue a exec2 (Q lenf f state lenr r) = case exec (exec state) of Done newf -> Q lenf newf Idle lenr r newstate -> Q lenf f newstate lenr r check :: Queue a -> Queue a check q@(Q lenf f state lenr r) = if lenr <= lenf then exec2 q else exec2 (Q (lenf+lenr) f newstate 0 L.empty) where newstate = Reversing 0 f L.empty r L.empty instance Q.Queue (Queue a) where empty :: Queue a empty = Q 0 L.empty Idle 0 L.empty isEmpty :: Queue a -> Bool isEmpty (Q lenf _ _ _ _) = lenf == 0 snoc :: Queue a -> a -> Queue a snoc (Q lenf f state lenr r) x = check (Q lenf f state (lenr + 1) (x `L.cons` r)) head :: Queue a -> a head (Q _ [] _ _ _) = error "empty" head (Q _ xs _ _ _) = L.head xs tail :: Queue a -> Queue a tail (Q _ [] _ _ _) = error "empty" tail (Q lenf f state lenr r) = check (Q (lenf - 1) (L.tail f) (invalidate state) lenr r) lookup :: Int -> Queue a -> a lookup i (Q lenf f _ lenr r) = if i < lenf then L.lookup i f else L.lookup (lenr - (i - lenf) - 1) r update :: Int -> a -> Queue a -> Queue a update i x (Q lenf f state lenr r) = if i < lenf then let f' = L.update i x f in Q lenf f' state lenr r else let r' = L.update (lenr - (i - lenf) - 1) x r in Q lenf f state lenr r' -- state の中身は…?
matonix/pfds
src/PFDS/Sec9/Ex14.hs
bsd-3-clause
2,544
0
15
588
1,285
658
627
60
3
{-# LANGUAGE ScopedTypeVariables #-} module Test.Hspec.Expectations.FloatingSpec (spec) where import Test.Hspec.Meta import Test.QuickCheck import Control.Exception import Control.Monad import Data.List import Data.Proxy import GHC.Fingerprint (fingerprint0) import Data.Bits.Floating import Test.Hspec.Expectations.Floating infinity :: (Read a, RealFloat a) => a infinity = read "Infinity" nan :: (Read a, RealFloat a) => a nan = read "NaN" maxValue :: (Read a, RealFloat a, FloatingBits a b) => a maxValue = nextDown infinity times :: Integer -> (a -> a) -> a -> a times n = foldr (.) id . genericReplicate n spec :: Spec spec = do describe "approximatelyEqual" $ do let compareWith :: Integer -> Float -> Float -> Bool compareWith = approximatelyEqual equals :: HasCallStack => Float -> Float -> Spec equals a b = do it ("returns True when comparing " ++ show a ++ " and " ++ show b) $ do approximatelyEqual 0 a b `shouldBe` True notEquals :: HasCallStack => Float -> Float -> Spec notEquals a b = do it ("returns False when comparing " ++ show a ++ " and " ++ show b) $ do approximatelyEqual 0 a b `shouldBe` False 0 `equals` 0 0 `equals` negate 0 1 `equals` 1 1 `notEquals` negate 1 infinity `equals` infinity infinity `notEquals` negate infinity nan `equals` nan nan `equals` negate nan context "when ULP distance is within the specified threshold" $ do it "returns True" $ do property $ \ (NonNegative distance) n -> do compareWith distance (times distance nextUp n) n `shouldBe` True compareWith distance (times distance nextDown n) n `shouldBe` True context "when ULP distance is greater than the specified threshold" $ do it "returns False" $ do property $ \ (NonNegative distance) n -> do compareWith distance (times (succ distance) nextUp n) n `shouldBe` False compareWith distance (times (succ distance) nextDown n) n `shouldBe` False describe "ulpDistance" $ do context "with Float" $ do it "calculates the difference in discrete ULP steps" $ do property $ \ (NonNegative n) (a :: Float) -> do ulpDistance a (times n nextUp a) `shouldBe` n ulpDistance a (times n nextDown a) `shouldBe` n context "with Double" $ do it "calculates the difference in discrete ULP steps" $ do property $ \ (NonNegative n) (a :: Double) -> do ulpDistance a (times n nextUp a) `shouldBe` n ulpDistance a (times n nextDown a) `shouldBe` n describe "floatingToWord64" $ do context "with Float" $ do floatingToWord64WorksFor (Proxy :: Proxy Float) context "with Double" $ do floatingToWord64WorksFor (Proxy :: Proxy Double) context "with a datatype that is larger than Word64" $ do it "throws an exception" $ do evaluate (floatingToWord64 fingerprint0) `shouldThrow` errorCall "operand too large (8 < 16)" where floatingToWord64WorksFor proxy = do forM_ [0, 1, maxValue, infinity, nan] $ \ n -> do forM_ [n, negate n] $ \ m -> do it ("works for " ++ show m) $ do shouldWorkFor (m `asProxyTypeOf` proxy) it "works for arbitrary numbers" $ do property shouldWorkFor where shouldWorkFor n = floatingToWord64 n `shouldBe` referenceImplementation n referenceImplementation = fromIntegral . coerceToWord
sol/hspec-expectations
test/Test/Hspec/Expectations/FloatingSpec.hs
mit
3,581
0
24
993
1,131
563
568
-1
-1
module Sound.Tidal.SimpleSynth where import Sound.Tidal.Stream (makeI, makeF) import Sound.Tidal.MIDI.Control keys :: ControllerShape keys = ControllerShape {params = [ mCC "modwheel" 1, mCC "balance" 10, mCC "expression" 11, mCC "sustainpedal" 64 ], duration = ("dur", 0.05), velocity = ("vel", 0.5), latency = 0.1} oscKeys = toOscShape keys note = makeI oscKeys "note" dur = makeF oscKeys "dur" vel = makeF oscKeys "vel" modwheel = makeF oscKeys "modwheel" balance = makeF oscKeys "balance" expression = makeF oscKeys "expression" sustainpedal = makeF oscKeys "sustainpedal"
lennart/tidal-midi
Sound/Tidal/SimpleSynth.hs
gpl-3.0
823
0
8
327
186
105
81
20
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.EC2.CreateVpnConnection -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Creates a VPN connection between an existing virtual private gateway and a -- VPN customer gateway. The only supported connection type is 'ipsec.1'. -- -- The response includes information that you need to give to your network -- administrator to configure your customer gateway. -- -- We strongly recommend that you use HTTPS when calling this operation -- because the response contains sensitive cryptographic information for -- configuring your customer gateway. -- -- If you decide to shut down your VPN connection for any reason and later -- create a new VPN connection, you must reconfigure your customer gateway with -- the new information returned from this call. -- -- For more information about VPN connections, see <http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_VPN.html Adding a Hardware VirtualPrivate Gateway to Your VPC> in the /Amazon Virtual Private Cloud User Guide/. -- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVpnConnection.html> module Network.AWS.EC2.CreateVpnConnection ( -- * Request CreateVpnConnection -- ** Request constructor , createVpnConnection -- ** Request lenses , cvcCustomerGatewayId , cvcDryRun , cvcOptions , cvcType , cvcVpnGatewayId -- * Response , CreateVpnConnectionResponse -- ** Response constructor , createVpnConnectionResponse -- ** Response lenses , cvcrVpnConnection ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.EC2.Types import qualified GHC.Exts data CreateVpnConnection = CreateVpnConnection { _cvcCustomerGatewayId :: Text , _cvcDryRun :: Maybe Bool , _cvcOptions :: Maybe VpnConnectionOptionsSpecification , _cvcType :: Text , _cvcVpnGatewayId :: Text } deriving (Eq, Read, Show) -- | 'CreateVpnConnection' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'cvcCustomerGatewayId' @::@ 'Text' -- -- * 'cvcDryRun' @::@ 'Maybe' 'Bool' -- -- * 'cvcOptions' @::@ 'Maybe' 'VpnConnectionOptionsSpecification' -- -- * 'cvcType' @::@ 'Text' -- -- * 'cvcVpnGatewayId' @::@ 'Text' -- createVpnConnection :: Text -- ^ 'cvcType' -> Text -- ^ 'cvcCustomerGatewayId' -> Text -- ^ 'cvcVpnGatewayId' -> CreateVpnConnection createVpnConnection p1 p2 p3 = CreateVpnConnection { _cvcType = p1 , _cvcCustomerGatewayId = p2 , _cvcVpnGatewayId = p3 , _cvcDryRun = Nothing , _cvcOptions = Nothing } -- | The ID of the customer gateway. cvcCustomerGatewayId :: Lens' CreateVpnConnection Text cvcCustomerGatewayId = lens _cvcCustomerGatewayId (\s a -> s { _cvcCustomerGatewayId = a }) cvcDryRun :: Lens' CreateVpnConnection (Maybe Bool) cvcDryRun = lens _cvcDryRun (\s a -> s { _cvcDryRun = a }) -- | Indicates whether the VPN connection requires static routes. If you are -- creating a VPN connection for a device that does not support BGP, you must -- specify 'true'. -- -- Default: 'false' cvcOptions :: Lens' CreateVpnConnection (Maybe VpnConnectionOptionsSpecification) cvcOptions = lens _cvcOptions (\s a -> s { _cvcOptions = a }) -- | The type of VPN connection ('ipsec.1'). cvcType :: Lens' CreateVpnConnection Text cvcType = lens _cvcType (\s a -> s { _cvcType = a }) -- | The ID of the virtual private gateway. cvcVpnGatewayId :: Lens' CreateVpnConnection Text cvcVpnGatewayId = lens _cvcVpnGatewayId (\s a -> s { _cvcVpnGatewayId = a }) newtype CreateVpnConnectionResponse = CreateVpnConnectionResponse { _cvcrVpnConnection :: Maybe VpnConnection } deriving (Eq, Read, Show) -- | 'CreateVpnConnectionResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'cvcrVpnConnection' @::@ 'Maybe' 'VpnConnection' -- createVpnConnectionResponse :: CreateVpnConnectionResponse createVpnConnectionResponse = CreateVpnConnectionResponse { _cvcrVpnConnection = Nothing } -- | Information about the VPN connection. cvcrVpnConnection :: Lens' CreateVpnConnectionResponse (Maybe VpnConnection) cvcrVpnConnection = lens _cvcrVpnConnection (\s a -> s { _cvcrVpnConnection = a }) instance ToPath CreateVpnConnection where toPath = const "/" instance ToQuery CreateVpnConnection where toQuery CreateVpnConnection{..} = mconcat [ "CustomerGatewayId" =? _cvcCustomerGatewayId , "DryRun" =? _cvcDryRun , "Options" =? _cvcOptions , "Type" =? _cvcType , "VpnGatewayId" =? _cvcVpnGatewayId ] instance ToHeaders CreateVpnConnection instance AWSRequest CreateVpnConnection where type Sv CreateVpnConnection = EC2 type Rs CreateVpnConnection = CreateVpnConnectionResponse request = post "CreateVpnConnection" response = xmlResponse instance FromXML CreateVpnConnectionResponse where parseXML x = CreateVpnConnectionResponse <$> x .@? "vpnConnection"
kim/amazonka
amazonka-ec2/gen/Network/AWS/EC2/CreateVpnConnection.hs
mpl-2.0
6,093
0
9
1,325
704
432
272
81
1
-- -*- Mode: Haskell; -*- -- -- QuickCheck tests for Megaparsec, utility functions for parser testing. -- -- Copyright © 2015 Megaparsec contributors -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are -- met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- This software is provided by the copyright holders "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 holders 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 Util ( checkParser , simpleParse , checkChar , checkString , (/=\) , abcRow , abcRow' , posErr , uneCh , uneStr , uneSpec , uneEof , exCh , exStr , exSpec , exEof , msg , showToken ) where import Data.Maybe (maybeToList) import Test.QuickCheck import Text.Megaparsec.Error import Text.Megaparsec.Pos import Text.Megaparsec.Prim import Text.Megaparsec.ShowToken import Text.Megaparsec.String -- | @checkParser p r s@ tries to run parser @p@ on input @s@ to parse -- entire @s@. Result of the parsing is compared with expected result @r@, -- it should match, otherwise the property doesn't hold and the test fails. checkParser :: (Eq a, Show a) => Parser a -> Either ParseError a -> String -> Property checkParser p r s = simpleParse p s === r -- | @simpleParse p s@ runs parser @p@ on input @s@ and returns corresponding -- result of type @Either ParseError a@, where @a@ is type of parsed -- value. This parser tries to parser end of file too and name of input file -- is always empty string. simpleParse :: Parser a -> String -> Either ParseError a simpleParse p = parse (p <* eof) "" -- | @checkChar p test label s@ runs parser @p@ on input @s@ and checks if -- the parser correctly parses single character that satisfies @test@. The -- character may be labelled, in this case @label@ is used to check quality -- of error messages. checkChar :: Parser Char -> (Char -> Bool) -> Maybe String -> String -> Property checkChar p f l' s = checkParser p r s where h = head s l = exSpec <$> maybeToList l' r | null s = posErr 0 s (uneEof : l) | length s == 1 && f h = Right h | not (f h) = posErr 0 s (uneCh h : l) | otherwise = posErr 1 s [uneCh (s !! 1), exEof] -- | @checkString p a test label s@ runs parser @p@ on input @s@ and checks if -- the result is equal to @a@ and also quality of error messages. @test@ is -- used to compare tokens. @label@ is used as expected representation of -- parser's result in error messages. checkString :: Parser String -> String -> (Char -> Char -> Bool) -> String -> String -> Property checkString p a' test l s' = checkParser p (w a' 0 s') s' where w [] _ [] = Right a' w [] i (s:_) = posErr i s' [uneCh s, exEof] w _ 0 [] = posErr 0 s' [uneEof, exSpec l] w _ i [] = posErr 0 s' [uneStr (take i s'), exSpec l] w (a:as) i (s:ss) | test a s = w as i' ss | otherwise = posErr 0 s' [uneStr (take i' s'), exSpec l] where i' = succ i infix 4 /=\ -- | @p /=\\ x@ runs parser @p@ on empty input and compares its result -- (which should be successful) with @x@. Succeeds when the result is equal -- to @x@, prints counterexample on failure. (/=\) :: (Eq a, Show a) => Parser a -> a -> Property p /=\ x = simpleParse p "" === Right x -- | @abcRow a b c@ generates string consisting of character “a” repeated -- @a@ times, character “b” repeated @b@ times, and finally character “c” -- repeated @c@ times. abcRow :: Int -> Int -> Int -> String abcRow a b c = replicate a 'a' ++ replicate b 'b' ++ replicate c 'c' -- | @abcRow' a b c@ generates string that includes character “a” if @a@ is -- 'True', then optionally character “b” if @b@ is 'True', then character -- “c” if @c@ is 'True'. abcRow' :: Bool -> Bool -> Bool -> String abcRow' a b c = abcRow (fromEnum a) (fromEnum b) (fromEnum c) -- | @posErr pos s ms@ is an easy way to model result of parser that -- fails. @pos@ is how many tokens (characters) has been consumed before -- failure. @s@ is input of the parser. @ms@ is a list, collection of -- 'Message's. See 'uneStr', 'uneCh', 'uneSpec', 'exStr', 'exCh', and -- 'exSpec' for easy ways to create error messages. posErr :: Int -> String -> [Message] -> Either ParseError a posErr pos s = Left . foldr addErrorMessage (newErrorUnknown errPos) where errPos = updatePosString (initialPos "") (take pos s) -- | @uneCh s@ returns message created with 'Unexpected' constructor that -- tells the system that char @s@ is unexpected. uneCh :: Char -> Message uneCh s = Unexpected $ showToken s -- | @uneStr s@ returns message created with 'Unexpected' constructor that -- tells the system that string @s@ is unexpected. uneStr :: String -> Message uneStr s = Unexpected $ showToken s -- | @uneSpec s@ returns message created with 'Unexpected' constructor that -- tells the system that @s@ is unexpected. This is different from 'uneStr' -- in that it doesn't use 'showToken' but rather pass its argument unaltered -- allowing for “special” labels. uneSpec :: String -> Message uneSpec = Unexpected -- | @uneEof@ represents message “unexpected end of input”. uneEof :: Message uneEof = Unexpected "end of input" -- | @exCh s@ returns message created with 'Expected' constructor that tells -- the system that character @s@ is expected. exCh :: Char -> Message exCh s = Expected $ showToken s -- | @exStr s@ returns message created with 'Expected' constructor that tells -- the system that string @s@ is expected. exStr :: String -> Message exStr s = Expected $ showToken s -- | @exSpec s@ returns message created with 'Expected' constructor that tells -- the system that @s@ is expected. This is different from 'exStr' in that -- it doesn't use 'showToken' but rather pass its argument unaltered -- allowing for “special” labels. exSpec :: String -> Message exSpec = Expected -- | @exEof@ represents message “expecting end of input”. exEof :: Message exEof = Expected "end of input" -- | @msg s@ return message created with 'Message' constructor. msg :: String -> Message msg = Message
tulcod/megaparsec
tests/Util.hs
bsd-2-clause
7,133
0
12
1,494
1,181
641
540
79
5
{- | Module : $Header$ Description : Goal management GUI. Copyright : (c) Rene Wagner, Klaus Luettich, Uni Bremen 2005 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : needs POSIX Goal management GUI for the structured level similar to how 'SPASS.Prove' works for SPASS. -} module GUI.HTkProverGUI (proofManagementGUI, GUIMVar) where import Common.AS_Annotation as AS_Anno import qualified Common.Doc as Pretty import Common.Result as Result import qualified Data.Map as Map import Common.ExtSign import Common.Utils import Data.List import qualified Control.Concurrent as Conc import HTk.Toolkit.Separator import HTk.Widgets.Space import HTk.Devices.XSelection import GUI.Utils import GUI.HTkUtils hiding (createTextSaveDisplay, displayTheoryWithWarning) import GUI.HTkProofDetails import Proofs.AbstractState import Logic.Comorphism import Logic.Logic import Logic.Prover import qualified Comorphisms.KnownProvers as KnownProvers import Static.GTheory -- * Proof Management GUI -- ** Defining the view {- | Colors used by the GUI to indicate the status of a goal. -} data ProverStatusColour -- | Not running = Black -- | Running | Blue deriving (Bounded, Enum, Show) data SelButtonFrame = SBF { selAllEv :: Event () , deselAllEv :: Event () , sbfBtns :: [Button] , sbfBtnFrame :: Frame} data SelAllListbox = SAL SelButtonFrame (ListBox String) {- | Generates a ('ProverStatusColour', 'String') tuple. -} statusNotRunning :: (ProverStatusColour, String) statusNotRunning = (Black, "No Prover Running") {- | Generates a ('ProverStatusColour', 'String') tuple. -} statusRunning :: (ProverStatusColour, String) statusRunning = (Blue, "Waiting for Prover") {- | Converts a 'ProofState' into a ('ProverStatusColour', 'String') tuple to be displayed by the GUI. -} toGuiStatus :: ProofState -> (ProverStatusColour, String) toGuiStatus st = if proverRunning st then statusRunning else statusNotRunning {- | Generates a list of 'GUI.HTkUtils.LBGoalView' representations of all goals from a 'SPASS.Prove.State'. Uses a status indicator internally. -} goalsView :: ProofState -- ^ current global state -> [LBGoalView] -- ^ resulting ['LBGoalView'] list goalsView = map toStatus . getGoals where toStatus (l, st) = let si = maybe LBIndicatorOpen indicatorFromBasicProof st in LBGoalView { statIndicator = si , goalDescription = l} -- ** GUI Implementation -- *** Utility Functions {- | Populates the "Pick Theorem Prover" 'ListBox' with prover names (or possibly paths to provers). -} populatePathsListBox :: ListBox String -> KnownProvers.KnownProversMap -> IO () populatePathsListBox lb prvs = do lb # value (Map.keys prvs) return () populateAxiomsList :: ListBox String -> ProofState -> IO () populateAxiomsList lbAxs s = do lbAxs # value (toAxioms s) return () setSelectedProver :: ListBox String -> ProofState -> IO () setSelectedProver lb st = do let ind = case selectedProver st of Just sp -> elemIndex sp $ Map.keys (proversMap st) Nothing -> Nothing maybe (return ()) (\ i -> selection i lb >> return ()) ind -- *** Callbacks {- | Updates the display of the status of the selected goals. -} updateDisplay :: ProofState -- ^ current global state -> Bool -- ^ set to 'True' if you want the 'ListBox' to be updated -> ListBox String -- ^ 'ListBox' displaying the status of all goals (see 'goalsView') -> ListBox String -- ^ 'ListBox' displaying possible morphism paths to prover logics -> Label -- ^ 'Label' displaying the status of the currently selected goal(s) -> IO () updateDisplay st updateLb goalsLb pathsLb statusLabel = do -- update goals listbox when updateLb (do (offScreen, _) <- view Vertical goalsLb populateGoalsListBox goalsLb (goalsView st) moveto Vertical goalsLb offScreen) setSelectedProver pathsLb st -- update status label let (color, label) = toGuiStatus st statusLabel # text label statusLabel # foreground (show color) return () toGoals :: ProofState -> [String] toGoals = map fst . getGoals updateStateGetSelectedGoals :: ProofState -> ListBox String -> IO ProofState updateStateGetSelectedGoals s lb = do sel <- getSelection lb :: IO (Maybe [Int]) return s {selectedGoals = maybe [] (map (toGoals s !!)) sel} updateStateGetSelectedSens :: ProofState -> ListBox String -- ^ axioms listbox -> ListBox String -- ^ theorems listbox -> IO ProofState updateStateGetSelectedSens s lbAxs lbThs = do selA <- getSelection lbAxs :: IO (Maybe [Int]) selT <- getSelection lbThs :: IO (Maybe [Int]) return (s { includedAxioms = maybe [] (fil $ toAxioms s) selA , includedTheorems = maybe [] (fil $ toGoals s) selT }) where fil = map . (!!) {- | Depending on the first argument all entries in a ListBox are selected or deselected -} doSelectAllEntries :: Bool {- ^ indicates wether all entries should be selected or deselected -} -> ListBox a -> IO () doSelectAllEntries selectAll lb = if selectAll then selectionRange (0 :: Int) EndOfText lb >> return () else clearSelection lb {- | Called whenever the button "Display" is clicked. -} doDisplayGoals :: ProofState -> IO () doDisplayGoals s = case currentTheory s of G_theory lid1 _ (ExtSign sig1 _) _ sens1 _ -> do let thName = theoryName s goalsText = show . Pretty.vsep . map (print_named lid1 . AS_Anno.mapNamed (simplify_sen lid1 sig1)) . toNamedList $ filterMapWithList (selectedGoals s) sens1 createTextSaveDisplay ("Selected Goals from Theory " ++ thName) (thName ++ "-goals.txt") goalsText {- | Called whenever a prover is selected from the "Pick Theorem Prover" ListBox. -} doSelectProverPath :: ProofState -> ListBox String -> IO ProofState doSelectProverPath s lb = do selected <- getSelection lb :: IO (Maybe [Int]) return s {selectedProver = maybe Nothing (\ (index : _) -> Just (Map.keys (proversMap s) !! index)) selected } newSelectButtonsFrame :: (Container par) => par -> IO SelButtonFrame newSelectButtonsFrame b3 = do selFrame <- newFrame b3 [] pack selFrame [Expand Off, Fill None, Side AtLeft, Anchor SouthWest] selHBox <- newHBox selFrame [] pack selHBox [Expand Off, Fill None, Anchor West] selectAllButton <- newButton selHBox [text "Select all"] pack selectAllButton [Expand Off, Fill None] deselectAllButton <- newButton selHBox [text "Deselect all"] pack deselectAllButton [Expand Off, Fill None] -- events selectAll <- clicked selectAllButton deselectAll <- clicked deselectAllButton return SBF { selAllEv = selectAll , deselAllEv = deselectAll , sbfBtns = [deselectAllButton, selectAllButton] , sbfBtnFrame = selFrame } newExtSelListBoxFrame :: (Container par) => par -> String -> Distance -> IO SelAllListbox newExtSelListBoxFrame b2 title hValue = do left <- newFrame b2 [] pack left [Expand On, Fill Both] b3 <- newVBox left [] pack b3 [Expand On, Fill Both] l0 <- newLabel b3 [text title] pack l0 [Anchor NorthWest] lbFrame <- newFrame b3 [] pack lbFrame [Expand On, Fill Both, Anchor NorthWest] lb <- newListBox lbFrame [bg "white", exportSelection False, selectMode Multiple, height hValue] :: IO (ListBox String) pack lb [Expand On, Side AtLeft, Fill Both] sb <- newScrollBar lbFrame [] pack sb [Expand On, Side AtRight, Fill Y, Anchor West] lb # scrollbar Vertical sb -- buttons for goal selection sbf <- newSelectButtonsFrame b3 return (SAL sbf lb) -- *** Main GUI -- | Invokes the GUI. proofManagementGUI :: ProofActions -- ^ record of possible GUI actions -> String -- ^ theory name -> String -- ^ warning information -> G_theory -- ^ theory -> KnownProvers.KnownProversMap -- ^ map of known provers -> [(G_prover, AnyComorphism)] {- ^ list of suitable comorphisms to provers for sublogic of G_theory -} -> GUIMVar {- ^ allows only one Proof window per graph; must be filled with Nothing and is filled with Nothing after closing the window; while the window is open it is filled with the Toplevel -} -> IO (Result.Result G_theory) proofManagementGUI prGuiAcs thName warningTxt th knownProvers comorphList guiMVar = do {- KnownProvers.showKnownProvers knownProvers initial backing data structure -} initState <- recalculateSublogicF prGuiAcs (initialState thName th knownProvers) { comorphismsToProvers = comorphList } stateMVar <- Conc.newMVar initState lockMVar <- Conc.newMVar () -- main window main <- createToplevel [text $ thName ++ " - Select Goal(s) and Prove"] Conc.tryTakeMVar guiMVar >>= let err s = fail $ "ProofManagementGUI: (" ++ s ++ ") MVar must be " ++ "filled with Nothing when entering proofManagementGUI" in maybe (err "not filled") (maybe (Conc.putMVar guiMVar $ Just main) (const $ err "filled with (Just x)")) -- VBox for the whole window b <- newVBox main [] pack b [Expand On, Fill Both] -- HBox for the upper part (goals on the left, options/results on the right) b2 <- newHBox b [] pack b2 [Expand On, Fill Both] -- ListBox for goal selection (SAL (SBF { selAllEv = selectAllGoals , deselAllEv = deselectAllGoals , sbfBtns = goalBtns , sbfBtnFrame = goalsBtnFrame}) lb) <- newExtSelListBoxFrame b2 "Goals:" 14 -- button to select only the open goals selectOpenGoalsButton <- newButton goalsBtnFrame [text "Select open goals"] pack selectOpenGoalsButton [Expand Off, Fill None, Side AtLeft] -- right frame (options/results) right <- newFrame b2 [] pack right [Expand On, Fill Both, Anchor NorthWest] let hindent = " " let vspacing = cm 0.2 rvb <- newVBox right [] pack rvb [Expand On, Fill Both] l1 <- newLabel rvb [text "Selected Goal(s):"] pack l1 [Anchor NorthWest] rhb1 <- newHBox rvb [] pack rhb1 [Expand On, Fill Both] hsp1 <- newLabel rhb1 [text hindent] pack hsp1 [] displayGoalsButton <- newButton rhb1 [text "Display"] pack displayGoalsButton [] proveButton <- newButton rhb1 [text "Prove"] pack proveButton [] proofDetailsButton <- newButton rhb1 [text "Show proof details"] pack proofDetailsButton [] vsp1 <- newSpace rvb vspacing [] pack vsp1 [] l2 <- newLabel rvb [text "Status:"] pack l2 [Anchor NorthWest] rhb2 <- newHBox rvb [] pack rhb2 [Expand On, Fill Both] hsp2 <- newLabel rhb2 [text hindent] pack hsp2 [] statusLabel <- newLabel rhb2 [text (snd statusNotRunning)] pack statusLabel [] vsp2 <- newSpace rvb vspacing [] pack vsp2 [] l3 <- newLabel rvb [text "Sublogic of Currently Selected Theory:"] pack l3 [Anchor NorthWest] rhb3 <- newHBox rvb [] pack rhb3 [Expand On, Fill Both] hsp3 <- newLabel rhb3 [text hindent] pack hsp3 [] sublogicLabel <- newLabel rhb3 [text (show $ sublogicOfTheory initState)] pack sublogicLabel [] vsp3 <- newSpace rvb vspacing [] pack vsp3 [] l4 <- newLabel rvb [text "Pick Theorem Prover:"] pack l4 [Anchor NorthWest] rhb4 <- newHBox rvb [] pack rhb4 [Expand On, Fill Both] hsp4 <- newLabel rhb4 [text hindent] pack hsp4 [] pathsFrame <- newFrame rhb4 [] pack pathsFrame [] pathsLb <- newListBox pathsFrame [value ([] :: [String]), bg "white", selectMode Single, exportSelection False, height 4, width 28] :: IO (ListBox String) pack pathsLb [Expand On, Side AtLeft, Fill Both] pathsSb <- newScrollBar pathsFrame [] pack pathsSb [Expand On, Side AtRight, Fill Y] pathsLb # scrollbar Vertical pathsSb moreButton <- newButton rvb [text "More fine grained selection..."] pack moreButton [Anchor SouthEast] -- separator sp1 <- newSpace b (cm 0.15) [] pack sp1 [Expand Off, Fill X, Side AtBottom] newHSeparator b sp2 <- newSpace b (cm 0.15) [] pack sp2 [Expand Off, Fill X, Side AtBottom] -- theory composer frame (toggled with button) composer <- newFrame b [] pack composer [Expand On, Fill Both] compBox <- newVBox composer [] pack compBox [Expand On, Fill Both] newLabel compBox [text "Fine grained composition of theory:"] >>= flip pack [] icomp <- newFrame compBox [] pack icomp [Expand On, Fill Both] icBox <- newHBox icomp [] pack icBox [Expand On, Fill Both] (SAL (SBF { selAllEv = selectAllAxs , deselAllEv = deselectAllAxs , sbfBtns = axsBtns , sbfBtnFrame = axiomsBtnFrame}) lbAxs) <- newExtSelListBoxFrame icBox "Axioms to include:" 10 -- button to deselect axioms that are former theorems deselectFormerTheoremsButton <- newButton axiomsBtnFrame [text "Deselect former theorems"] pack deselectFormerTheoremsButton [Expand Off, Fill None, Side AtLeft] (SAL (SBF { selAllEv = selectAllThs , deselAllEv = deselectAllThs , sbfBtns = thsBtns}) lbThs) <- newExtSelListBoxFrame icBox "Theorems to include if proven:" 10 -- separator spac1 <- newSpace b (cm 0.15) [] pack spac1 [Expand Off, Fill X, Side AtBottom] newHSeparator b spac2 <- newSpace b (cm 0.15) [] pack spac2 [Expand Off, Fill X, Side AtBottom] -- bottom frame (close button) bottom <- newFrame b [] pack bottom [Expand Off, Fill Both] bottomThFrame <- newFrame bottom [] pack bottomThFrame [Expand Off, Fill Both, Side AtLeft] showThButton <- newButton bottomThFrame [text "Show theory"] pack showThButton [Expand Off, Fill None, Side AtLeft] showSelThButton <- newButton bottomThFrame [text "Show selected theory"] pack showSelThButton [Expand Off, Fill None, Side AtRight] closeButton <- newButton bottom [text "Close"] pack closeButton [Expand Off, Fill None, Side AtRight, PadX (pp 13)] -- put the labels in the listboxes populateGoalsListBox lb (goalsView initState) populateAxiomsList lbAxs initState populatePathsListBox pathsLb (proversMap initState) lbThs # value (toGoals initState) doSelectAllEntries True lb doSelectAllEntries True lbAxs doSelectAllEntries True lbThs updateDisplay initState False lb pathsLb statusLabel let goalSpecificWids = map EnW [displayGoalsButton, proveButton, proofDetailsButton, moreButton] wids = [EnW pathsLb, EnW lbThs, EnW lb, EnW lbAxs] ++ map EnW (selectOpenGoalsButton : closeButton : showThButton : showSelThButton : deselectFormerTheoremsButton : axsBtns ++ goalBtns ++ thsBtns) ++ goalSpecificWids enableWids goalSpecificWids pack main [Expand On, Fill Both] putWinOnTop main let updateStatusSublogic s = do sWithSel <- updateStateGetSelectedSens s lbAxs lbThs >>= flip updateStateGetSelectedGoals lb s' <- recalculateSublogicF prGuiAcs sWithSel {proversMap = knownProvers} let newSublogicText = show $ sublogicOfTheory s' sublogicText <- getText sublogicLabel when (sublogicText /= newSublogicText) (sublogicLabel # text newSublogicText >> return ()) when (Map.keys (proversMap s) /= Map.keys (proversMap s')) $ do populatePathsListBox pathsLb (proversMap s') setSelectedProver pathsLb s' return s' { selectedProver = maybe Nothing (\ sp -> find (== sp) $ Map.keys (proversMap s')) (selectedProver s')} -- events (selectProverPath, _) <- bindSimple pathsLb (ButtonPress (Just 1)) (selectGoals, _) <- bindSimple lb (ButtonPress (Just 1)) (selectAxioms, _) <- bindSimple lbAxs (ButtonPress (Just 1)) (selectTheorems, _) <- bindSimple lbThs (ButtonPress (Just 1)) selectOpenGoals <- clicked selectOpenGoalsButton deselectFormerTheorems <- clicked deselectFormerTheoremsButton displayGoals <- clicked displayGoalsButton moreProverPaths <- clicked moreButton doProve <- clicked proveButton showProofDetails <- clicked proofDetailsButton close <- clicked closeButton showTh <- clicked showThButton showSelTh <- clicked showSelThButton (closeWindow, _) <- bindSimple main Destroy -- event handlers _ <- spawnEvent $ forever $ selectGoals >>> do Conc.modifyMVar_ stateMVar updateStatusSublogic enableWidsUponSelection lb goalSpecificWids done +> selectAxioms >>> do Conc.modifyMVar_ stateMVar updateStatusSublogic done +> selectTheorems >>> do Conc.modifyMVar_ stateMVar updateStatusSublogic done +> selectOpenGoals >>> do s <- Conc.takeMVar stateMVar clearSelection lb let isOpen = maybe True (\ bp -> case bp of BasicProof _ pst -> isOpenGoal $ goalStatus pst _ -> False) mapM_ (`selection` lb) (findIndices (isOpen . snd) $ getGoals s) enableWidsUponSelection lb goalSpecificWids s' <- updateStatusSublogic s Conc.putMVar stateMVar s' done +> deselectFormerTheorems >>> do s <- Conc.takeMVar stateMVar let axiomList = getAxioms s sel <- getSelection lbAxs :: IO (Maybe [Int]) clearSelection lbAxs mapM_ (`selection` lbAxs) $ maybe [] (filter (not . snd . (!!) axiomList)) sel s' <- updateStatusSublogic s Conc.putMVar stateMVar s' done +> deselectAllGoals >>> do doSelectAllEntries False lb enableWids goalSpecificWids Conc.modifyMVar_ stateMVar updateStatusSublogic done +> selectAllGoals >>> do doSelectAllEntries True lb enableWids goalSpecificWids Conc.modifyMVar_ stateMVar updateStatusSublogic done +> selectAllAxs >>> do doSelectAllEntries True lbAxs Conc.modifyMVar_ stateMVar updateStatusSublogic done +> selectAllThs >>> do doSelectAllEntries True lbThs Conc.modifyMVar_ stateMVar updateStatusSublogic done +> deselectAllAxs >>> do doSelectAllEntries False lbAxs Conc.modifyMVar_ stateMVar updateStatusSublogic done +> deselectAllThs >>> do doSelectAllEntries False lbThs Conc.modifyMVar_ stateMVar updateStatusSublogic done +> displayGoals >>> do s <- Conc.readMVar stateMVar s' <- updateStateGetSelectedGoals s lb doDisplayGoals s' done +> selectProverPath >>> do Conc.modifyMVar_ stateMVar (`doSelectProverPath` pathsLb) done +> moreProverPaths >>> do s <- Conc.readMVar stateMVar let s' = s {proverRunning = True} updateDisplay s' True lb pathsLb statusLabel disableWids wids prState <- updateStatusSublogic s' Result.Result ds ms'' <- fineGrainedSelectionF prGuiAcs prState s'' <- case ms'' of Nothing -> do when (null ds || diagString (head ds) /= "Proofs.Proofs: selection") $ errorDialog "Error" (showRelDiags 2 ds) return s' Just res -> return res let s''' = s'' { proverRunning = False , accDiags = accDiags s'' ++ ds } enableWids wids updateDisplay s''' True lb pathsLb statusLabel putWinOnTop main Conc.tryTakeMVar stateMVar -- ensure that MVar is empty Conc.putMVar stateMVar s''' done +> doProve >>> do s <- Conc.takeMVar stateMVar let s' = s {proverRunning = True} updateDisplay s' True lb pathsLb statusLabel disableWids wids prState <- updateStatusSublogic s' Result.Result ds ms'' <- proveF prGuiAcs prState s'' <- case ms'' of Nothing -> do errorDialog "Error" (showRelDiags 2 ds) return s' Just res -> return res let s''' = s'' {proverRunning = False, accDiags = accDiags s'' ++ ds} Conc.putMVar stateMVar s''' mv <- Conc.tryTakeMVar lockMVar case mv of Nothing -> done Just _ -> do enable lb updateDisplay s''' True lb pathsLb statusLabel enableWids wids putWinOnTop main Conc.tryPutMVar lockMVar () done +> showProofDetails >>> do s <- Conc.readMVar stateMVar s' <- updateStateGetSelectedGoals s lb doShowProofDetails s' done +> showTh >>> do displayTheoryWithWarning "Theory" thName warningTxt th done +> showSelTh >>> do s <- Conc.readMVar stateMVar displayTheoryWithWarning "Selected Theory" thName warningTxt (selectedTheory s) done sync $ close >>> destroy main +> closeWindow >>> Conc.takeMVar lockMVar -- clean up locking of window Conc.tryTakeMVar guiMVar >>= let err s = fail $ "ProofManagementGUI: (" ++ s ++ ") MVar must be " ++ "filled with Nothing when entering proofManagementGUI" in maybe (err "not filled") (maybe (err "filled with Nothing") (const $ Conc.putMVar guiMVar Nothing)) -- read the global state back in s <- Conc.takeMVar stateMVar return . Result.Result (accDiags s) . Just $ currentTheory s
keithodulaigh/Hets
GUI/HTkProverGUI.hs
gpl-2.0
22,843
0
49
6,693
6,113
2,892
3,221
484
5
{-# LANGUAGE DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Hooks.DynamicBars -- Copyright : (c) Ben Boeckel 2012 -- License : BSD-style (as xmonad) -- -- Maintainer : [email protected] -- Stability : unstable -- Portability : unportable -- -- Manage per-screen status bars. -- ----------------------------------------------------------------------------- module XMonad.Hooks.DynamicBars ( -- * Usage -- $usage DynamicStatusBar , DynamicStatusBarCleanup , DynamicStatusBarPartialCleanup , dynStatusBarStartup , dynStatusBarStartup' , dynStatusBarEventHook , dynStatusBarEventHook' , multiPP , multiPPFormat ) where import Prelude import Control.Monad import Control.Monad.Trans (lift) import Control.Monad.Writer (WriterT, execWriterT, tell) import Data.List import Data.Maybe import Data.Monoid import Data.Foldable (traverse_) import Graphics.X11.Xinerama import Graphics.X11.Xlib import Graphics.X11.Xlib.Extras import Graphics.X11.Xrandr import System.IO import XMonad import qualified XMonad.StackSet as W import XMonad.Hooks.DynamicLog import qualified XMonad.Util.ExtensibleState as XS -- $usage -- Provides a few helper functions to manage per-screen status bars while -- dynamically responding to screen changes. A startup action, event hook, and -- a way to separate PP styles based on the screen's focus are provided: -- -- * The 'dynStatusBarStartup' hook which initializes the status bars. The -- first argument is an `ScreenId -> IO Handle` which spawns a status bar on the -- given screen and returns the pipe which the string should be written to. -- The second argument is a `IO ()` to shut down all status bars. This should -- be placed in your `startupHook`. -- -- * The 'dynStatusBarEventHook' hook which respawns status bars when the -- number of screens changes. The arguments are the same as for the -- `dynStatusBarStartup` function. This should be placed in your -- `handleEventHook`. -- -- * Each of the above functions have an alternate form -- (`dynStatusBarStartup'` and `dynStatusBarEventHook'`) which use a cleanup -- function which takes an additional `ScreenId` argument which allows for -- more fine-grained control for shutting down a specific screen's status bar. -- -- * The 'multiPP' function which allows for different output based on whether -- the screen for the status bar has focus (the first argument) or not (the -- second argument). This is for use in your `logHook`. -- -- * The 'multiPPFormat' function is the same as the 'multiPP' function, but it -- also takes in a function that can customize the output to status bars. -- -- The hooks take a 'DynamicStatusBar' function which is given the id of the -- screen to start up and returns the 'Handle' to the pipe to write to. The -- 'DynamicStatusBarCleanup' argument should tear down previous instances. It -- is called when the number of screens changes and on startup. -- data DynStatusBarInfo = DynStatusBarInfo { dsbInfo :: [(ScreenId, Handle)] } deriving (Typeable) instance ExtensionClass DynStatusBarInfo where initialValue = DynStatusBarInfo [] type DynamicStatusBar = ScreenId -> IO Handle type DynamicStatusBarCleanup = IO () type DynamicStatusBarPartialCleanup = ScreenId -> IO () dynStatusBarSetup :: X () dynStatusBarSetup = do dpy <- asks display root <- asks theRoot io $ xrrSelectInput dpy root rrScreenChangeNotifyMask dynStatusBarStartup :: DynamicStatusBar -> DynamicStatusBarCleanup -> X () dynStatusBarStartup sb cleanup = do dynStatusBarSetup updateStatusBars sb cleanup dynStatusBarStartup' :: DynamicStatusBar -> DynamicStatusBarPartialCleanup -> X () dynStatusBarStartup' sb cleanup = do dynStatusBarSetup updateStatusBars' sb cleanup dynStatusBarEventHook :: DynamicStatusBar -> DynamicStatusBarCleanup -> Event -> X All dynStatusBarEventHook sb cleanup = dynStatusBarRun (updateStatusBars sb cleanup) dynStatusBarEventHook' :: DynamicStatusBar -> DynamicStatusBarPartialCleanup -> Event -> X All dynStatusBarEventHook' sb cleanup = dynStatusBarRun (updateStatusBars' sb cleanup) dynStatusBarRun :: X () -> Event -> X All dynStatusBarRun action (RRScreenChangeNotifyEvent {}) = action >> return (All True) dynStatusBarRun _ _ = return (All True) updateStatusBars :: DynamicStatusBar -> DynamicStatusBarCleanup -> X () updateStatusBars sb cleanup = do (dsbInfoScreens, dsbInfoHandles) <- XS.get >>= return . unzip . dsbInfo screens <- getScreens when (screens /= dsbInfoScreens) $ do newHandles <- liftIO $ do hClose `mapM_` dsbInfoHandles cleanup mapM sb screens XS.put $ DynStatusBarInfo (zip screens newHandles) updateStatusBars' :: DynamicStatusBar -> DynamicStatusBarPartialCleanup -> X () updateStatusBars' sb cleanup = do (dsbInfoScreens, dsbInfoHandles) <- XS.get >>= return . unzip . dsbInfo screens <- getScreens when (screens /= dsbInfoScreens) $ do let oldInfo = zip dsbInfoScreens dsbInfoHandles let (infoToKeep, infoToClose) = partition (flip elem screens . fst) oldInfo newInfo <- liftIO $ do mapM_ hClose $ map snd infoToClose mapM_ cleanup $ map fst infoToClose let newScreens = screens \\ dsbInfoScreens newHandles <- mapM sb newScreens return $ zip newScreens newHandles XS.put . DynStatusBarInfo $ infoToKeep ++ newInfo ----------------------------------------------------------------------------- -- The following code is from adamvo's xmonad.hs file. -- http://www.haskell.org/haskellwiki/Xmonad/Config_archive/adamvo%27s_xmonad.hs multiPP :: PP -- ^ The PP to use if the screen is focused -> PP -- ^ The PP to use otherwise -> X () multiPP = multiPPFormat dynamicLogString multiPPFormat :: (PP -> X String) -> PP -> PP -> X () multiPPFormat dynlStr focusPP unfocusPP = do (_, dsbInfoHandles) <- XS.get >>= return . unzip . dsbInfo multiPP' dynlStr focusPP unfocusPP dsbInfoHandles multiPP' :: (PP -> X String) -> PP -> PP -> [Handle] -> X () multiPP' dynlStr focusPP unfocusPP handles = do st <- get let pickPP :: WorkspaceId -> WriterT (Last XState) X String pickPP ws = do let isFoc = (ws ==) . W.tag . W.workspace . W.current $ windowset st put st{ windowset = W.view ws $ windowset st } out <- lift $ dynlStr $ if isFoc then focusPP else unfocusPP when isFoc $ get >>= tell . Last . Just return out traverse_ put . getLast =<< execWriterT . (io . zipWithM_ hPutStrLn handles <=< mapM pickPP) . catMaybes =<< mapM screenWorkspace (zipWith const [0 .. ] handles) getScreens :: MonadIO m => m [ScreenId] getScreens = liftIO $ do screens <- do dpy <- openDisplay "" rects <- getScreenInfo dpy closeDisplay dpy return rects let ids = zip [0 .. ] screens return $ map fst ids
f1u77y/xmonad-contrib
XMonad/Hooks/DynamicBars.hs
bsd-3-clause
6,953
0
19
1,299
1,403
729
674
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Network.Wai.Middleware.ForceSSLSpec ( main , spec ) where import Test.Hspec import Network.Wai.Middleware.ForceSSL import Control.Monad import Data.ByteString (ByteString) import Data.Monoid ((<>)) import Network.HTTP.Types (methodPost, status200, status301, status307) import Network.Wai import Network.Wai.Test main :: IO () main = hspec spec spec :: Spec spec = describe "forceSSL" (forM_ hosts $ \host -> hostSpec host) where hosts = ["example.com", "example.com:80", "example.com:8080"] hostSpec :: ByteString -> Spec hostSpec host = describe ("forceSSL on host " <> show host <> "") $ do it "redirects non-https requests to https" $ do resp <- runApp host forceSSL defaultRequest simpleStatus resp `shouldBe` status301 simpleHeaders resp `shouldBe` [("Location", "https://" <> host)] it "redirects with 307 in the case of a non-GET request" $ do resp <- runApp host forceSSL defaultRequest { requestMethod = methodPost } simpleStatus resp `shouldBe` status307 simpleHeaders resp `shouldBe` [("Location", "https://" <> host)] it "does not redirect already-secure requests" $ do resp <- runApp host forceSSL defaultRequest { isSecure = True } simpleStatus resp `shouldBe` status200 it "preserves the original host, path, and query string" $ do resp <- runApp host forceSSL defaultRequest { rawPathInfo = "/foo/bar" , rawQueryString = "?baz=bat" } simpleHeaders resp `shouldBe` [("Location", "https://" <> host <> "/foo/bar?baz=bat")] runApp :: ByteString -> Middleware -> Request -> IO SResponse runApp host mw req = runSession (request req { requestHeaderHost = Just host }) $ mw app where app _ respond = respond $ responseLBS status200 [] ""
sordina/wai
wai-extra/test/Network/Wai/Middleware/ForceSSLSpec.hs
bsd-2-clause
1,890
0
15
437
517
274
243
41
1
module Fibonacci.Plugin (fibonacci) where import Neovim -- | Neovim is not really good with big numbers, so we return a 'String' here. fibonacci :: Int -> Neovim' String fibonacci n = return . show $ fibs !! n where fibs :: [Integer] fibs = 0:1:scanl1 (+) fibs
saep/nvim-hs-config-example
lib/Fibonacci/Plugin.hs
mit
274
0
8
60
77
43
34
6
1
{-# LANGUAGE FlexibleContexts #-} module CommandLine.Helpers where import Control.Monad.Error.Class (MonadError) import Control.Monad.Trans (MonadIO, liftIO) import System.Directory import System.IO import qualified Elm.Utils as Utils yesOrNo :: IO Bool yesOrNo = do hFlush stdout input <- getLine case input of "y" -> return True "n" -> return False _ -> do putStr "Must type 'y' for yes or 'n' for no: " yesOrNo inDir :: (MonadError String m, MonadIO m) => FilePath -> m a -> m a inDir dir doStuff = do here <- liftIO $ getCurrentDirectory liftIO $ createDirectoryIfMissing True dir liftIO $ setCurrentDirectory dir result <- doStuff liftIO $ setCurrentDirectory here return result git :: (MonadError String m, MonadIO m) => [String] -> m String git = run "git" run :: (MonadError String m, MonadIO m) => String -> [String] -> m String run = Utils.run out :: (MonadIO m) => String -> m () out string = liftIO $ hPutStrLn stdout string' where string' = if not (null string) && last string == '\n' then init string else string
laszlopandy/elm-package
src/CommandLine/Helpers.hs
bsd-3-clause
1,150
0
12
294
380
192
188
33
3
{-# OPTIONS_GHC -Wall #-} module Reporting.Error.Docs where import qualified Reporting.Error.Helpers as Help import qualified Reporting.Report as Report data Error = NoDocs | OnlyInDocs String [String] | OnlyInExports [String] | NoComment String | NoType String -- TO REPORT toReport :: Error -> Report.Report toReport err = case err of NoDocs -> Report.simple "DOCUMENTATION ERROR" ( "You must have a documentation comment between the module declaration and the\n" ++ "imports." ) "Learn how at <http://package.elm-lang.org/help/documentation-format>" OnlyInDocs name suggestions -> Report.simple "DOCUMENTATION ERROR" ("Your module documentation includes `" ++ name ++ "` which is not exported.") ("Is it misspelled? Should it be exported? " ++ Help.maybeYouWant suggestions) OnlyInExports names -> Report.simple "DOCUMENTATION ERROR" ( "The following exports do not appear in your module documentation:\n" ++ concatMap ("\n " ++) names ) ( "All exports must be listed in the module documentation after a @docs keyword.\n" ++ "Learn how at <http://package.elm-lang.org/help/documentation-format>" ) NoComment name -> Report.simple "DOCUMENTATION ERROR" ("The value `" ++ name ++ "` does not have a documentation comment.") ( "Documentation comments start with {-| and end with -}. They should provide a\n" ++ "clear description of how they work, and ideally a small code example. This is\n" ++ "extremely valuable for users checking out your package!\n\n" ++ "If you think the docs are clearer without any words, you can use an empty\n" ++ "comment {-|-} which should be used sparingly. Maybe you have a section of 20\n" ++ "values all with the exact same type. The docs may read better if they are all\n" ++ "described in one place.\n\n" ++ "Learn more at <http://package.elm-lang.org/help/documentation-format>" ) NoType name -> Report.simple "MISSING ANNOTATION" ("The value `" ++ name ++ "` does not have a type annotation.") ( "Adding type annotations is best practice and it gives you a chance to name\n" ++ "types and type variables so they are as easy as possible to understand!" )
Axure/elm-compiler
src/Reporting/Error/Docs.hs
bsd-3-clause
2,479
0
16
700
286
154
132
45
5
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 HsImpExp: Abstract syntax: imports, exports, interfaces -} {-# LANGUAGE DeriveDataTypeable #-} module HsImpExp where import Module ( ModuleName ) import HsDoc ( HsDocString ) import OccName ( HasOccName(..), isTcOcc, isSymOcc ) import BasicTypes ( SourceText, StringLiteral(..) ) import FieldLabel ( FieldLbl(..) ) import Outputable import FastString import SrcLoc import Data.Data {- ************************************************************************ * * \subsection{Import and export declaration lists} * * ************************************************************************ One per \tr{import} declaration in a module. -} type LImportDecl name = Located (ImportDecl name) -- ^ When in a list this may have -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' -- For details on above see note [Api annotations] in ApiAnnotation -- | A single Haskell @import@ declaration. data ImportDecl name = ImportDecl { ideclSourceSrc :: Maybe SourceText, -- Note [Pragma source text] in BasicTypes ideclName :: Located ModuleName, -- ^ Module name. ideclPkgQual :: Maybe StringLiteral, -- ^ Package qualifier. ideclSource :: Bool, -- ^ True <=> {-\# SOURCE \#-} import ideclSafe :: Bool, -- ^ True => safe import ideclQualified :: Bool, -- ^ True => qualified ideclImplicit :: Bool, -- ^ True => implicit import (of Prelude) ideclAs :: Maybe ModuleName, -- ^ as Module ideclHiding :: Maybe (Bool, Located [LIE name]) -- ^ (True => hiding, names) } -- ^ -- 'ApiAnnotation.AnnKeywordId's -- -- - 'ApiAnnotation.AnnImport' -- -- - 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnClose' for ideclSource -- -- - 'ApiAnnotation.AnnSafe','ApiAnnotation.AnnQualified', -- 'ApiAnnotation.AnnPackageName','ApiAnnotation.AnnAs', -- 'ApiAnnotation.AnnVal' -- -- - 'ApiAnnotation.AnnHiding','ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' attached -- to location in ideclHiding -- For details on above see note [Api annotations] in ApiAnnotation deriving (Data, Typeable) simpleImportDecl :: ModuleName -> ImportDecl name simpleImportDecl mn = ImportDecl { ideclSourceSrc = Nothing, ideclName = noLoc mn, ideclPkgQual = Nothing, ideclSource = False, ideclSafe = False, ideclImplicit = False, ideclQualified = False, ideclAs = Nothing, ideclHiding = Nothing } instance (OutputableBndr name, HasOccName name) => Outputable (ImportDecl name) where ppr (ImportDecl { ideclName = mod', ideclPkgQual = pkg , ideclSource = from, ideclSafe = safe , ideclQualified = qual, ideclImplicit = implicit , ideclAs = as, ideclHiding = spec }) = hang (hsep [text "import", ppr_imp from, pp_implicit implicit, pp_safe safe, pp_qual qual, pp_pkg pkg, ppr mod', pp_as as]) 4 (pp_spec spec) where pp_implicit False = empty pp_implicit True = ptext (sLit ("(implicit)")) pp_pkg Nothing = empty pp_pkg (Just (StringLiteral _ p)) = doubleQuotes (ftext p) pp_qual False = empty pp_qual True = text "qualified" pp_safe False = empty pp_safe True = text "safe" pp_as Nothing = empty pp_as (Just a) = text "as" <+> ppr a ppr_imp True = text "{-# SOURCE #-}" ppr_imp False = empty pp_spec Nothing = empty pp_spec (Just (False, (L _ ies))) = ppr_ies ies pp_spec (Just (True, (L _ ies))) = text "hiding" <+> ppr_ies ies ppr_ies [] = text "()" ppr_ies ies = char '(' <+> interpp'SP ies <+> char ')' {- ************************************************************************ * * \subsection{Imported and exported entities} * * ************************************************************************ -} type LIE name = Located (IE name) -- ^ When in a list this may have -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' -- For details on above see note [Api annotations] in ApiAnnotation -- | Imported or exported entity. data IE name = IEVar (Located name) -- ^ - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnPattern', -- 'ApiAnnotation.AnnType' -- For details on above see note [Api annotations] in ApiAnnotation -- See Note [Located RdrNames] in HsExpr | IEThingAbs (Located name) -- ^ Class/Type (can't tell) -- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnPattern', -- 'ApiAnnotation.AnnType','ApiAnnotation.AnnVal' -- For details on above see note [Api annotations] in ApiAnnotation -- See Note [Located RdrNames] in HsExpr | IEThingAll (Located name) -- ^ Class/Type plus all methods/constructors -- -- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose', -- 'ApiAnnotation.AnnType' -- For details on above see note [Api annotations] in ApiAnnotation -- See Note [Located RdrNames] in HsExpr | IEThingWith (Located name) IEWildcard [Located name] [Located (FieldLbl name)] -- ^ Class/Type plus some methods/constructors -- and record fields; see Note [IEThingWith] -- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose', -- 'ApiAnnotation.AnnComma', -- 'ApiAnnotation.AnnType' -- For details on above see note [Api annotations] in ApiAnnotation | IEModuleContents (Located ModuleName) -- ^ (Export Only) -- -- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnModule' -- For details on above see note [Api annotations] in ApiAnnotation | IEGroup Int HsDocString -- ^ Doc section heading | IEDoc HsDocString -- ^ Some documentation | IEDocNamed String -- ^ Reference to named doc deriving (Eq, Data, Typeable) data IEWildcard = NoIEWildcard | IEWildcard Int deriving (Eq, Data, Typeable) {- Note [IEThingWith] ~~~~~~~~~~~~~~~~~~ A definition like module M ( T(MkT, x) ) where data T = MkT { x :: Int } gives rise to IEThingWith T [MkT] [FieldLabel "x" False x)] (without DuplicateRecordFields) IEThingWith T [MkT] [FieldLabel "x" True $sel:x:MkT)] (with DuplicateRecordFields) See Note [Representing fields in AvailInfo] in Avail for more details. -} ieName :: IE name -> name ieName (IEVar (L _ n)) = n ieName (IEThingAbs (L _ n)) = n ieName (IEThingWith (L _ n) _ _ _) = n ieName (IEThingAll (L _ n)) = n ieName _ = panic "ieName failed pattern match!" ieNames :: IE a -> [a] ieNames (IEVar (L _ n) ) = [n] ieNames (IEThingAbs (L _ n) ) = [n] ieNames (IEThingAll (L _ n) ) = [n] ieNames (IEThingWith (L _ n) _ ns _) = n : map unLoc ns ieNames (IEModuleContents _ ) = [] ieNames (IEGroup _ _ ) = [] ieNames (IEDoc _ ) = [] ieNames (IEDocNamed _ ) = [] pprImpExp :: (HasOccName name, OutputableBndr name) => name -> SDoc pprImpExp name = type_pref <+> pprPrefixOcc name where occ = occName name type_pref | isTcOcc occ && isSymOcc occ = text "type" | otherwise = empty instance (HasOccName name, OutputableBndr name) => Outputable (IE name) where ppr (IEVar var) = pprPrefixOcc (unLoc var) ppr (IEThingAbs thing) = pprImpExp (unLoc thing) ppr (IEThingAll thing) = hcat [pprImpExp (unLoc thing), text "(..)"] ppr (IEThingWith thing wc withs flds) = pprImpExp (unLoc thing) <> parens (fsep (punctuate comma ppWiths ++ map (ppr . flLabel . unLoc) flds)) where ppWiths = case wc of NoIEWildcard -> map (pprImpExp . unLoc) withs IEWildcard pos -> let (bs, as) = splitAt pos (map (pprImpExp . unLoc) withs) in bs ++ [text ".."] ++ as ppr (IEModuleContents mod') = text "module" <+> ppr mod' ppr (IEGroup n _) = text ("<IEGroup: " ++ show n ++ ">") ppr (IEDoc doc) = ppr doc ppr (IEDocNamed string) = text ("<IEDocNamed: " ++ string ++ ">")
tjakway/ghcjvm
compiler/hsSyn/HsImpExp.hs
bsd-3-clause
9,409
0
19
3,161
1,702
922
780
115
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="id-ID"> <title>Call Graph</title> <maps> <homeID>callgraph</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>
thc202/zap-extensions
addOns/callgraph/src/main/javahelp/help_id_ID/helpset_id_ID.hs
apache-2.0
961
77
66
156
407
206
201
-1
-1
import Communication.IVC(InOutChannel) import qualified Communication.IVC as IVC import Communication.Rendezvous import Control.Monad import Data.Binary import Data.Binary.Get import Data.ByteString.Lazy(unpack) import Data.Char import Hypervisor.Console import Hypervisor.Debug import Hypervisor.XenStore import Prelude hiding (getLine) newtype Msg = Msg String instance Binary Msg where get = (Msg . map chr . map fromIntegral . unpack) `fmap` getLazyByteStringNul put (Msg s) = mapM_ put (map word8ify s) >> putWord8 0 where word8ify :: Char -> Word8 word8ify = fromIntegral . ord accept :: XenStore -> IO (InOutChannel Msg Msg) (_, accept) = peerConnection "rot13" (0.5, 1) main :: IO () main = do writeDebugConsole "'Terminal' starting.\n" con <- initXenConsole xs <- initXenStore writeDebugConsole "Building connection.\n" ch <- accept xs writeDebugConsole "Connection established.\n" writeConsole con "Hello! This is your fabulous ROT13 terminal.\n" writeConsole con " - Type a message, and it will be encrypted for you.\n" writeConsole con " - Finish by entering a blank line.\n" runPrompt con ch runPrompt :: Console -> InOutChannel Msg Msg -> IO () runPrompt con ch = do writeConsole con "> " msg <- getLine con IVC.put ch (Msg msg) unless (all isSpace msg) $ do Msg rsp <- IVC.get ch writeConsole con ("Encoded result: " ++ rsp ++ "\n") runPrompt con ch getLine :: Console -> IO String getLine con = do nextC <- readConsole con 1 writeConsole con nextC case nextC of "\r" -> writeConsole con "\n" >> return "" [x] -> (x:) `fmap` getLine con _ -> fail "More than one character back?"
thumphries/HaLVM
examples/IVC/ROT13/Terminal.hs
bsd-3-clause
1,681
0
13
331
537
264
273
49
3
module Main where import Data.Char (toLower) palindrome s = lowered == reverse lowered where lowered = map toLower s main = do if palindrome "Tacocat" then putStrLn "tacocat is a palindrome" else putStrLn "tacocat is not a palindrome" if palindrome "HelLo" then putStrLn "hello is a palindrome" else putStrLn "hello is not a palindrome"
OpenGenus/cosmos
code/string_algorithms/src/palindrome_checker/palindrome.hs
gpl-3.0
365
0
8
82
86
43
43
10
3
main = do -- All reserved words let break = "break" in putStrLn break let catch = "catch" in putStrLn catch let const = "const" in putStrLn const let continue = "continue" in putStrLn continue let debugger = "debugger" in putStrLn debugger let delete = "delete" in putStrLn delete let enum = "enum" in putStrLn enum let export = "export" in putStrLn export let extends = "extends" in putStrLn extends let finally = "finally" in putStrLn finally let for = "for" in putStrLn for let function = "function" in putStrLn function let implements = "implements" in putStrLn implements let instanceof = "instanceof" in putStrLn instanceof let interface = "interface" in putStrLn interface let new = "new" in putStrLn new let null = "null" in putStrLn null let package = "package" in putStrLn package let private = "private" in putStrLn private let protected = "protected" in putStrLn protected let public = "public" in putStrLn public let return = "return" in putStrLn return let static = "static" in putStrLn static let super = "super" in putStrLn super let switch = "switch" in putStrLn switch let this = "this" in putStrLn this let throw = "throw" in putStrLn throw let try = "try" in putStrLn try let typeof = "typeof" in putStrLn typeof let undefined = "undefined" in putStrLn undefined let var = "var" in putStrLn var let void = "void" in putStrLn void let while = "while" in putStrLn while let with = "with" in putStrLn with let yield = "yield" in putStrLn yield putStrLn "" -- Stdlib functions that need to be encoded putStrLn $ const "stdconst" 2
manyoo/ghcjs
test/fay/reservedWords.hs
mit
1,627
0
10
347
621
257
364
38
1
-- !!! Testing the Word Enum instances. {-# OPTIONS_GHC -F -pgmF ./enum_processor.bat #-} -- The processor is a non-CPP-based equivalent of -- #define printTest(x) (do{ putStr ( " " ++ "x" ++ " = " ) ; print (x) }) -- which is not portable to clang module Main(main) where import Control.Exception import Data.Word import Data.Int main = do putStrLn "Testing Enum Word8:" testEnumWord8 putStrLn "Testing Enum Word16:" testEnumWord16 putStrLn "Testing Enum Word32:" testEnumWord32 putStrLn "Testing Enum Word64:" testEnumWord64 testEnumWord8 :: IO () testEnumWord8 = do -- succ printTest ((succ (0::Word8))) printTest ((succ (minBound::Word8))) mayBomb (printTest ((succ (maxBound::Word8)))) -- pred printTest (pred (1::Word8)) printTest (pred (maxBound::Word8)) mayBomb (printTest (pred (minBound::Word8))) -- toEnum printTest ((map (toEnum::Int->Word8) [1, fromIntegral (minBound::Word8)::Int, fromIntegral (maxBound::Word8)::Int])) mayBomb (printTest ((toEnum (maxBound::Int))::Word8)) -- fromEnum printTest ((map fromEnum [(1::Word8),minBound,maxBound])) -- [x..] aka enumFrom printTest ((take 7 [(1::Word8)..])) printTest ((take 7 [((maxBound::Word8)-5)..])) -- just in case it doesn't catch the upper bound.. -- [x,y..] aka enumFromThen printTest ((take 7 [(1::Word8),2..])) printTest ((take 7 [(1::Word8),7..])) printTest ((take 7 [(1::Word8),1..])) printTest ((take 7 [(1::Word8),0..])) printTest ((take 7 [(5::Word8),2..])) let x = (minBound::Word8) + 1 printTest ((take 7 [x, x-1 ..])) let x = (minBound::Word8) + 5 printTest ((take 7 [x, x-1 ..])) let x = (maxBound::Word8) - 5 printTest ((take 7 [x, (x+1) ..])) -- [x..y] aka enumFromTo printTest ((take 7 ([(1::Word8) .. 5]))) printTest ((take 4 ([(1::Word8) .. 1]))) printTest ((take 7 ([(1::Word8) .. 0]))) printTest ((take 7 ([(5::Word8) .. 0]))) printTest ((take 7 ([(maxBound-(5::Word8)) .. maxBound]))) printTest ((take 7 ([(minBound+(5::Word8)) .. minBound]))) -- [x,y..z] aka enumFromThenTo printTest ((take 7 [(5::Word8),4..1])) printTest ((take 7 [(5::Word8),3..1])) printTest ((take 7 [(5::Word8),3..2])) printTest ((take 7 [(1::Word8),2..1])) printTest ((take 7 [(2::Word8),1..2])) printTest ((take 7 [(2::Word8),1..1])) printTest ((take 7 [(2::Word8),3..1])) let x = (maxBound::Word8) - 4 printTest ((take 7 [x,(x+1)..maxBound])) let x = (minBound::Word8) + 5 printTest ((take 7 [x,(x-1)..minBound])) testEnumWord16 :: IO () testEnumWord16 = do -- succ printTest ((succ (0::Word16))) printTest ((succ (minBound::Word16))) mayBomb (printTest ((succ (maxBound::Word16)))) -- pred printTest (pred (1::Word16)) printTest (pred (maxBound::Word16)) mayBomb (printTest (pred (minBound::Word16))) -- toEnum printTest ((map (toEnum::Int->Word16) [1, fromIntegral (minBound::Word16)::Int, fromIntegral (maxBound::Word16)::Int])) mayBomb (printTest ((toEnum (maxBound::Int))::Word16)) -- fromEnum printTest ((map fromEnum [(1::Word16),minBound,maxBound])) -- [x..] aka enumFrom printTest ((take 7 [(1::Word16)..])) printTest ((take 7 [((maxBound::Word16)-5)..])) -- just in case it doesn't catch the upper bound.. -- [x,y..] aka enumFromThen printTest ((take 7 [(1::Word16),2..])) printTest ((take 7 [(1::Word16),7..])) printTest ((take 7 [(1::Word16),1..])) printTest ((take 7 [(1::Word16),0..])) printTest ((take 7 [(5::Word16),2..])) let x = (minBound::Word16) + 1 printTest ((take 7 [x, x-1 ..])) let x = (minBound::Word16) + 5 printTest ((take 7 [x, x-1 ..])) let x = (maxBound::Word16) - 5 printTest ((take 7 [x, (x+1) ..])) -- [x..y] aka enumFromTo printTest ((take 7 ([(1::Word16) .. 5]))) printTest ((take 4 ([(1::Word16) .. 1]))) printTest ((take 7 ([(1::Word16) .. 0]))) printTest ((take 7 ([(5::Word16) .. 0]))) printTest ((take 7 ([(maxBound-(5::Word16)) .. maxBound]))) printTest ((take 7 ([(minBound+(5::Word16)) .. minBound]))) -- [x,y..z] aka enumFromThenTo printTest ((take 7 [(5::Word16),4..1])) printTest ((take 7 [(5::Word16),3..1])) printTest ((take 7 [(5::Word16),3..2])) printTest ((take 7 [(1::Word16),2..1])) printTest ((take 7 [(2::Word16),1..2])) printTest ((take 7 [(2::Word16),1..1])) printTest ((take 7 [(2::Word16),3..1])) let x = (maxBound::Word16) - 4 printTest ((take 7 [x,(x+1)..maxBound])) let x = (minBound::Word16) + 5 printTest ((take 7 [x,(x-1)..minBound])) testEnumWord32 :: IO () testEnumWord32 = do -- succ printTest ((succ (0::Word32))) printTest ((succ (minBound::Word32))) mayBomb (printTest ((succ (maxBound::Word32)))) -- pred printTest (pred (1::Word32)) printTest (pred (maxBound::Word32)) mayBomb (printTest (pred (minBound::Word32))) -- toEnum printTest ((map (toEnum::Int->Word32) [1, fromIntegral (minBound::Word32)::Int, fromIntegral (maxBound::Int32)::Int])) mayBomb (printTest ((toEnum (maxBound::Int))::Word32)) -- fromEnum printTest ((map fromEnum [(1::Word32),minBound,fromIntegral (maxBound::Int)])) mayBomb (printTest (fromEnum (maxBound::Word32))) -- [x..] aka enumFrom printTest ((take 7 [(1::Word32)..])) printTest ((take 7 [((maxBound::Word32)-5)..])) -- just in case it doesn't catch the upper bound.. -- [x,y..] aka enumFromThen printTest ((take 7 [(1::Word32),2..])) printTest ((take 7 [(1::Word32),7..])) printTest ((take 7 [(1::Word32),1..])) printTest ((take 7 [(1::Word32),0..])) printTest ((take 7 [(5::Word32),2..])) let x = (minBound::Word32) + 1 printTest ((take 7 [x, x-1 ..])) let x = (minBound::Word32) + 5 printTest ((take 7 [x, x-1 ..])) let x = (maxBound::Word32) - 5 printTest ((take 7 [x, (x+1) ..])) -- [x..y] aka enumFromTo printTest ((take 7 ([(1::Word32) .. 5]))) printTest ((take 4 ([(1::Word32) .. 1]))) printTest ((take 7 ([(1::Word32) .. 0]))) printTest ((take 7 ([(5::Word32) .. 0]))) printTest ((take 7 ([(maxBound-(5::Word32)) .. maxBound]))) printTest ((take 7 ([(minBound+(5::Word32)) .. minBound]))) -- [x,y..z] aka enumFromThenTo printTest ((take 7 [(5::Word32),4..1])) printTest ((take 7 [(5::Word32),3..1])) printTest ((take 7 [(5::Word32),3..2])) printTest ((take 7 [(1::Word32),2..1])) printTest ((take 7 [(2::Word32),1..2])) printTest ((take 7 [(2::Word32),1..1])) printTest ((take 7 [(2::Word32),3..1])) let x = (maxBound::Word32) - 4 printTest ((take 7 [x,(x+1)..maxBound])) let x = (minBound::Word32) + 5 printTest ((take 7 [x,(x-1)..minBound])) testEnumWord64 :: IO () testEnumWord64 = do -- succ printTest ((succ (0::Word64))) printTest ((succ (minBound::Word64))) mayBomb (printTest ((succ (maxBound::Word64)))) -- pred printTest (pred (1::Word64)) printTest (pred (maxBound::Word64)) mayBomb (printTest (pred (minBound::Word64))) -- toEnum mayBomb (printTest ((map (toEnum::Int->Word64) [1, fromIntegral (minBound::Word64)::Int, maxBound::Int]))) mayBomb (printTest ((toEnum (maxBound::Int))::Word64)) -- fromEnum printTest ((map fromEnum [(1::Word64),minBound,fromIntegral (maxBound::Int)])) mayBomb (printTest (fromEnum (maxBound::Word64))) -- [x..] aka enumFrom printTest ((take 7 [(1::Word64)..])) printTest ((take 7 [((maxBound::Word64)-5)..])) -- just in case it doesn't catch the upper bound.. -- [x,y..] aka enumFromThen printTest ((take 7 [(1::Word64),2..])) printTest ((take 7 [(1::Word64),7..])) printTest ((take 7 [(1::Word64),1..])) printTest ((take 7 [(1::Word64),0..])) printTest ((take 7 [(5::Word64),2..])) let x = (minBound::Word64) + 1 printTest ((take 7 [x, x-1 ..])) let x = (minBound::Word64) + 5 printTest ((take 7 [x, x-1 ..])) let x = (maxBound::Word64) - 5 printTest ((take 7 [x, (x+1) ..])) -- [x..y] aka enumFromTo printTest ((take 7 ([(1::Word64) .. 5]))) printTest ((take 4 ([(1::Word64) .. 1]))) printTest ((take 7 ([(1::Word64) .. 0]))) printTest ((take 7 ([(5::Word64) .. 0]))) printTest ((take 7 ([(maxBound-(5::Word64)) .. maxBound]))) printTest ((take 7 ([(minBound+(5::Word64)) .. minBound]))) -- [x,y..z] aka enumFromThenTo printTest ((take 7 [(5::Word64),4..1])) printTest ((take 7 [(5::Word64),3..1])) printTest ((take 7 [(5::Word64),3..2])) printTest ((take 7 [(1::Word64),2..1])) printTest ((take 7 [(2::Word64),1..2])) printTest ((take 7 [(2::Word64),1..1])) printTest ((take 7 [(2::Word64),3..1])) let x = (maxBound::Word64) - 4 printTest ((take 7 [x,(x+1)..maxBound])) let x = (minBound::Word64) + 5 printTest ((take 7 [x,(x-1)..minBound])) -- -- -- Utils -- -- mayBomb x = catch x (\(ErrorCall e) -> putStrLn ("error " ++ show e)) `catch` (\e -> putStrLn ("Fail: " ++ show (e :: SomeException)))
ezyang/ghc
libraries/base/tests/enum03.hs
bsd-3-clause
8,901
0
15
1,602
4,803
2,627
2,176
182
1
-- | Types for the general graph colorer. module GraphBase ( Triv, Graph (..), initGraph, graphMapModify, Node (..), newNode, ) where import UniqSet import UniqFM -- | A fn to check if a node is trivially colorable -- For graphs who's color classes are disjoint then a node is 'trivially colorable' -- when it has less neighbors and exclusions than available colors for that node. -- -- For graph's who's color classes overlap, ie some colors alias other colors, then -- this can be a bit more tricky. There is a general way to calculate this, but -- it's likely be too slow for use in the code. The coloring algorithm takes -- a canned function which can be optimised by the user to be specific to the -- specific graph being colored. -- -- for details, see "A Generalised Algorithm for Graph-Coloring Register Allocation" -- Smith, Ramsey, Holloway - PLDI 2004. -- type Triv k cls color = cls -- the class of the node we're trying to color. -> UniqSet k -- the node's neighbors. -> UniqSet color -- the node's exclusions. -> Bool -- | The Interference graph. -- There used to be more fields, but they were turfed out in a previous revision. -- maybe we'll want more later.. -- data Graph k cls color = Graph { -- | All active nodes in the graph. graphMap :: UniqFM (Node k cls color) } -- | An empty graph. initGraph :: Graph k cls color initGraph = Graph { graphMap = emptyUFM } -- | Modify the finite map holding the nodes in the graph. graphMapModify :: (UniqFM (Node k cls color) -> UniqFM (Node k cls color)) -> Graph k cls color -> Graph k cls color graphMapModify f graph = graph { graphMap = f (graphMap graph) } -- | Graph nodes. -- Represents a thing that can conflict with another thing. -- For the register allocater the nodes represent registers. -- data Node k cls color = Node { -- | A unique identifier for this node. nodeId :: k -- | The class of this node, -- determines the set of colors that can be used. , nodeClass :: cls -- | The color of this node, if any. , nodeColor :: Maybe color -- | Neighbors which must be colored differently to this node. , nodeConflicts :: UniqSet k -- | Colors that cannot be used by this node. , nodeExclusions :: UniqSet color -- | Colors that this node would prefer to be, in decending order. , nodePreference :: [color] -- | Neighbors that this node would like to be colored the same as. , nodeCoalesce :: UniqSet k } -- | An empty node. newNode :: k -> cls -> Node k cls color newNode k cls = Node { nodeId = k , nodeClass = cls , nodeColor = Nothing , nodeConflicts = emptyUniqSet , nodeExclusions = emptyUniqSet , nodePreference = [] , nodeCoalesce = emptyUniqSet }
forked-upstream-packages-for-ghcjs/ghc
compiler/utils/GraphBase.hs
bsd-3-clause
3,291
0
11
1,163
391
241
150
44
1
module GMachine where import Types import Heap -- Getter and setter of the G-machine state getOutput :: GMState -> GMOutput getOutput (o, _, _, _, _, _, _) = o putOutput :: GMOutput -> GMState -> GMState putOutput o' (_, i, stack, dump, heap, globals, stats) = (o', i, stack, dump, heap, globals, stats) getHeap :: GMState -> GMHeap getHeap (_, _ , _, _, heap, _, _) = heap putHeap :: GMHeap -> GMState -> GMState putHeap newHeap (output, code, stack, dump, _, globals, stats) = (output, code, stack, dump, newHeap, globals, stats) getStack :: GMState -> GMStack getStack (_, _, stack, _, _, _, _) = stack putStack :: GMStack -> GMState -> GMState putStack newStack (output, code, _, dump, heap, globals, stats) = (output, code, newStack, dump, heap, globals, stats) getDump :: GMState -> GMDump getDump (_, _, _, dump, _, _, _) = dump putDump :: GMDump -> GMState -> GMState putDump dump' (output, i, stack, _, heap, globals, stats) = (output, i, stack, dump', heap, globals, stats) getCode :: GMState -> GMCode getCode (_, code, _, _, _, _, _) = code putCode :: GMCode -> GMState -> GMState putCode newCode (output, _, stack, dump, heap, globals, stats) = (output, newCode, stack, dump, heap, globals, stats) getGlobals :: GMState -> GMGlobals getGlobals (_, _, _, _, _, globals, _) = globals getStats :: GMState -> GMStats getStats (_, _, _, _, _, _, stats) = stats putStats :: GMStats -> GMState -> GMState putStats newStats (ouptut, code, stack, dump, heap, globals, _) = (ouptut, code, stack, dump, heap, globals, newStats) statIncSteps :: GMStats -> GMStats statIncSteps stats = stats + 1 statGetSteps :: GMStats -> Int statGetSteps stats = stats -- The eval function steps through each GM state until the final GM state is -- reached. gmEval :: GMState -> [GMState] gmEval state = state : restStates where restStates | gmFinal state = [] | otherwise = gmEval nextState nextState = doAdmin (gmStep state) gmFinal :: GMState -> Bool gmFinal s = case getCode s of [] -> True _ -> False doAdmin :: GMState -> GMState doAdmin s = putStats (statIncSteps (getStats s)) s gmStep :: GMState -> GMState gmStep state = gmDispatch i (putCode is state) where (i:is) = getCode state gmDispatch :: Instruction -> GMState -> GMState gmDispatch (PushGlobal f) = pushGlobal f gmDispatch (PushInt n) = pushInt n gmDispatch MkAp = mkAp gmDispatch (Push n) = push n gmDispatch (Update n) = update n gmDispatch (Pop n) = pop n gmDispatch Unwind = unwind gmDispatch (Slide n) = slide n gmDispatch (Alloc n) = alloc n gmDispatch Eval = eval2WHNF gmDispatch Add = arithmetic2 (+) gmDispatch Sub = arithmetic2 (-) gmDispatch Mul = arithmetic2 (*) gmDispatch Div = arithmetic2 opDiv gmDispatch Neg = arithmetic1 opNeg gmDispatch (Cond i1 i2) = cond i1 i2 gmDispatch Eq = comparison (==) gmDispatch Ne = comparison (/=) gmDispatch Lt = comparison (<) gmDispatch Le = comparison (<=) gmDispatch Gt = comparison (>) gmDispatch Ge = comparison (>=) gmDispatch (Pack t arity) = pack t arity gmDispatch (Casejump es) = caseJump es gmDispatch (Split n) = split n gmDispatch Print = printer pack :: Int -> Int -> GMState -> GMState pack t n state = putHeap heap' (putStack (addr: drop n s) state) where s = getStack state (heap', addr) = hAlloc (getHeap state) (NConstr t (take n s)) caseJump :: [(Int, GMCode)] -> GMState -> GMState caseJump es s = putCode (i ++ getCode s) s where (NConstr t _) = hLookup (getHeap s) (head (getStack s)) i = aLookup es t (error ("No case for constructor" ++ show t)) split :: Int -> GMState -> GMState split _ state = putStack (as ++ s) state where (NConstr _ as) = hLookup (getHeap state) a (a:s) = getStack state printer :: GMState -> GMState printer s = newState where (addr : _) = getStack s newState = printer' (hLookup (getHeap s) addr) s printer' :: Node -> GMState -> GMState printer' (NNum n) s = putOutput o s' where o = (getOutput s) ++ show n s' = (putStack addrs s) (_ : addrs) = getStack s printer' (NConstr t argAddrs) s = putCode (i' ++ (getCode s)) s' where s'' = putOutput ("Pack{" ++ show t ++ "," ++ show(length argAddrs) ++ "}") s' (_: addrs) = getStack s s' = putStack (argAddrs ++ addrs) s i' = printcode (length argAddrs) printcode :: Int -> [Instruction] printcode 0 = [] printcode n = Eval : Print : printcode (n - 1) opNeg :: Int -> Int opNeg n = -n opDiv :: Int -> Int -> Int opDiv n1 n2 = quot n1 n2 alloc :: Int -> GMState -> GMState alloc n state = putStack stack' state' where state' = putHeap heap' state heap' = fst ret ret = allocNodes n (getHeap state) stack' = addrs ++ (getStack state) addrs = snd ret allocNodes :: Int -> GMHeap -> (GMHeap, [Addr]) allocNodes 0 heap = (heap, []) allocNodes n heap = (heap2, a:as) where (heap1, as) = allocNodes (n - 1) heap (heap2, a) = hAlloc heap1 (NInd hNull) slide :: Int -> GMState -> GMState slide n state = putStack (a: drop n as) state where (a:as) = getStack state pushGlobal :: Name -> GMState -> GMState pushGlobal f state = putStack (addr: getStack state) state where addr = aLookup (getGlobals state) f (error ("Symbol " ++ f ++ " is not defined")) -- pushes an Integer Node into the heap pushInt :: Int -> GMState -> GMState pushInt n state = putHeap newHeap state' where state' = putStack (addr: getStack state) state (newHeap, addr) = hAlloc (getHeap state) (NNum n) mkAp :: GMState -> GMState mkAp state = putHeap heap' (putStack (a:as) state) where (heap', a) = hAlloc (getHeap state) (NAp a1 a2) (a1:a2:as) = getStack state push :: Int -> GMState -> GMState push n state = putStack (a:as) state where as = getStack state a = as !! n pop :: Int -> GMState -> GMState pop n state = putStack stack' state where stack' = drop n (getStack state) update :: Int -> GMState -> GMState update n state = putHeap heap' (putStack as state) where heap' = hUpdate (getHeap state) (as !! n) (NInd a) (a:as) = getStack state boxInteger :: Int -> GMState -> GMState boxInteger n state = putStack (a: getStack state) (putHeap h' state) where (h', a) = hAlloc (getHeap state) (NNum n) boxBoolean :: Bool -> GMState -> GMState boxBoolean b state = putStack (a: getStack state) newState where newState = (putHeap h' state) (h', a) = hAlloc (getHeap state) (NConstr b' []) b' | b = 2 -- True | otherwise = 1 -- False unboxInteger :: Addr -> GMState -> Int unboxInteger a state = ub (hLookup (getHeap state) a) where ub (NNum i) = i ub _ = error "Unboxing a non-integer" primitive1 :: (b -> GMState -> GMState) -- boxing function -> (Addr -> GMState -> a) -- unboxing function -> (a -> b) -- operator -> (GMState -> GMState) -- state transition primitive1 box unbox op state = box (op (unbox a state)) (putStack as state) where (a:as) = getStack state primitive2 :: (b -> GMState -> GMState) -- boxing function -> (Addr -> GMState -> a) -- unboxing function -> (a -> a -> b) -- operator -> (GMState -> GMState) -- state transition primitive2 box unbox op state = box result state' where result = (op (unbox a0 state) (unbox a1 state)) (a0:a1:as) = getStack state state' = (putStack as state) arithmetic1 :: (Int -> Int) -- arithmetic operator -> (GMState -> GMState) -- state transition arithmetic1 = primitive1 boxInteger unboxInteger arithmetic2 :: (Int -> Int -> Int) -- arithmetic operation -> (GMState -> GMState) -- state transition arithmetic2 = primitive2 boxInteger unboxInteger comparison :: (Int -> Int -> Bool) -> GMState -> GMState comparison = primitive2 boxBoolean unboxInteger doLt :: GMState -> GMState doLt state = state' where state' = putStack as (boxBoolean True state) (a0:a1:as) = getStack state result = (<) (unboxInteger a0 state) (unboxInteger a1 state) eval2WHNF :: GMState -> GMState eval2WHNF state = putDump (frame : getDump state) (putStack [a] (putCode [Unwind] state)) where frame = (getCode state, stack) (a : stack) = getStack state cond :: GMCode -> GMCode -> GMState -> GMState cond i1 i2 state = putCode code' state' where state' = putStack stack state (a : stack) = getStack state is = getCode state code' = i ++ is i = getCodeStream i1 i2 (hLookup (getHeap state) a) getCodeStream :: GMCode -> GMCode -> Node -> GMCode getCodeStream i1 i2 (NConstr 2 _) = i1 getCodeStream i1 i2 _ = i2 getArg :: Node -> Addr getArg (NAp a1 a2) = a2 rearrange :: Int -> GMHeap -> GMStack -> GMStack rearrange n heap addrs = take n addrs' ++ drop n addrs where addrs' = map (getArg . hLookup heap) (tail addrs) unwind :: GMState -> GMState unwind state = newState (hLookup heap a) where (a:as) = getStack state heap = getHeap state ((i, stack):dump) = getDump state newState (NNum n) = putCode i (putStack (a:stack) (putDump dump state)) newState (NAp a1 a2) = putCode [Unwind] (putStack (a1:a:as) state) newState (NGlobal n c) | length as >= n = putCode c (putStack as' state) | otherwise = putCode i (putStack (last (a:as):stack) (putDump dump state)) where as' = rearrange n heap (a:as) newState (NInd aInd) = putCode [Unwind] (putStack (aInd:as) state) newState (NConstr t as) = putCode i (putStack (a:stack) (putDump dump state)) builtInDyadic :: Assoc Name Instruction -- list of pairs - [(Name, Instruction)] builtInDyadic = [ ("+", Add), ("-", Sub), ("*", Mul), ("div", Div), ("==", Eq), ("~=", Ne), (">=", Ge), (">", Gt), ("<=", Le), ("<", Lt)] -- end of file
typedvar/hLand
hcore/GMachine.hs
mit
10,154
0
15
2,624
4,116
2,184
1,932
247
5
module FantasyProfession where import System.Random import Probability import Quality import Skill import FantasyStats import Alignment import Precondition data ProfessionalRarity = Basic | Adventurer | Epic deriving (Eq, Show, Read) data Profession = Profession { professionName :: String, professionType :: SkillGroup, professionalRarity :: ProfessionalRarity, professionalRestrictions :: [Precondition], professionalSkills :: [SkillType] } deriving (Eq, Show, Read) --profession rarity profType name skills restrictions = Profession { professionName = name, professionType = profType, professionalRarity = rarity, professionalSkills = skills, professionalRestrictions = restrictions } basicProfession = Profession { professionName = "", professionalRarity = Basic, professionType = Natural, professionalRestrictions = [], professionalSkills = [] } basicNaturalProfession = basicProfession --{ professionType = Natural } basicPerformerProfession = basicProfession { professionType = Performance } basicRogueProfession = basicProfession { professionType = Clandestine } basicEconomicProfession = basicProfession { professionType = Economic } basicMagicalProfession = basicProfession { professionType = Arcane } hunter = basicNaturalProfession { professionName = "hunter" } -- [ ] [ ] --Profession { professionalName = "hunter", professionType = Natural, professionalRarity = Basic, professionalRestrictions = [ ProfessionalRestrictionOnStats Wis 3 ], professionalSkills = [ tracking ] } farmer = basicNaturalProfession { professionName = "farmer" } -- [ ] [ ] --Profession { professionalName = "hunter", professionType = Natural, professionalRarity = Basic, professionalRestrictions = [ ProfessionalRestrictionOnStats Wis 3 ], professionalSkills = [ tracking ] } thief = basicRogueProfession { professionName = "thief" } -- [ ] [] -- dexterityRestriction Good ] dancer = basicPerformerProfession { professionName = "dancer" } -- [ ] [] -- charismaRestrictrion Good ] trader = basicEconomicProfession { professionName = "trader" } -- [ ] [] -- charismaRestriction Good ] illusionist = basicMagicalProfession { professionName = "illusionist" } -- [ ] [] basicNatureProfessions = [ farmer, hunter ] --, tracker ] basicFighterProfessions = [ ] -- brawler, wrestler ] basicRogueProfessions = [ thief ] --, scout, hustler, trickster ] basicPerformerProfessions = [ dancer ] --, singer ] basicEconomicProfessions = [ trader ] --, beggar, gambler ] basicMagicalProfessions = [ illusionist ] -- chanter ] basicReligiousProfessions = [ ] basicProfessions = basicNatureProfessions ++ basicFighterProfessions ++ basicRogueProfessions ++ basicPerformerProfessions ++ basicEconomicProfessions ++ basicMagicalProfessions ++ basicReligiousProfessions --data ProfessionSubtype --data NormalSubtype = Academic | Colonial | Criminal | Drifer | Forester | Nomad | Novitiate | Scavenger --| | | | | --data RareSubtype = Feral | Dilettante | Clandestine | Shadow | Herald | Outcast | Guerrilla --data EpicProfessionalSubtype = Telepathic | Celebrity | Eldritch | Royal data ProfessionalSubtype = ProfessionalSubtype ProfessionalRarity String -- NormalSubtype | RareSubtype | EpicSubtype deriving (Eq, Show, Read) humanizeProfessionalSubtype (ProfessionalSubtype _ s) = s basicProfessionalSubtype = ProfessionalSubtype Basic adventurerProfessionalSubtype = ProfessionalSubtype Adventurer epicProfessionalSubtype = ProfessionalSubtype Epic --basicProfessionalSubtypeNames = [ "academic", "colonial", "criminal", "drifter", "nomad", "novitiate", "scavenger" ] --basicProfessionalSubtypes = map basicProfessionalSubtype basicProfessionalSubtypeNames academic = basicProfessionalSubtype "academic" colonial = basicProfessionalSubtype "colonial" clandestine = adventurerProfessionalSubtype "clandestine" telepathic = epicProfessionalSubtype "telepathic" -- [ foresight (+5) ] normalProfessionalSubtypes = [ academic, colonial ] rareProfessionalSubtypes = [ clandestine ] epicProfessionalSubtypes = [ telepathic ] professionalSubtypes = normalProfessionalSubtypes ++ rareProfessionalSubtypes ++ epicProfessionalSubtypes data Job = Job Profession ProfessionalSubtype Quality deriving (Eq, Show, Read) --data Job = Job Profession ProfessionalSkillLevel humanizedJob :: Job -> String humanizedJob (Job prof st q) = humanizeProfessionalSubtype st ++ " " ++ professionName prof --(profession job) genJob = do professionalSubtype <- pickFrom professionalSubtypes --randomIO :: IO ProfessionalSubtype prof <- pickFrom basicProfessions --randomIO :: IO Profession quality <- genQuality return (Job prof professionalSubtype quality) -- { profession = prof, subtype = professionalSubtype } ------------ ----data ProfessionalClass = Economic | Military | Criminal ----data Professionalt = ProfessionType ProfessionalCompetence -- Level --data ProfessionType = ProfessionType ProfessionalRarity ProfessionalGroupType [ProfessionalClass] --data BasicProfessionType = ProfessionType Basic --data BasicNaturalProfessionType = BasicProfessionType Natural [ --data BasicNatureProfessionType = Hunter | Tracker | Scout --data BasicFighterProfessionType = Brawler | Wrestler --data BasicRogueProfessionType = Thief --data BasicProfessionType = BasicNatureProfessionType | BasicFighterProfessionType -- Aristocrat | Commoner | Fighter | Trader | Pilgrim | Thief | Apothecary | Hunter | Missionary | Dancer | Acolyte | Tracker | Scout --data AdventurerNatureProfessionType = Ranger | Druid --data AdventurerFighterProfessionType = Warrior | Soldier | Archer --data AdventurerRogueProfessionType = Spy | Thief | Ninja | Pirate | Assassin | Diplomat --data AdventurerPerformerProfessionType = Bard --data AdventurerEconomicProfessionType = Gambler | Hustler | Merchant --data AdventurerMageProfessionType = Wizard | Mage | Warlock | Healer -- | Adept --data AdventurerReligiousProfessionType = Monk | Cleric | Priest | WitchDoctor | Inquisitor --data BasicAdventurerProfessionType = BasicNatureProfessionType | BasicFighterProfessionType | BasicRogueProfessionType | BasicEconomicProfessionType | BasicMageProfessionType | BasicReligiousProfessionType --data EpicNatureProfessionType = Treespeaker --data EpicFighterProfessionType = Knight --data EpicRogueProfessionType = Diplomat | Samurai | Assassin | Swashbuckler --data EpicPerformerProfessionType = Caller --data EpicEconomicProfessionType = Gambler | Hustler | Merchant --data EpicMageProfessionType = Archmage --data EpicReligiousProfessionType = Templar | Oracle | Prophet | Paladin --data EpicProfessionType = EpicNatureProfessionType | EpicFighterProfessionType | EpicRogueProfessionType | EpicPerformerProfessionType | EpicEconomicProfessionType | EpicMageProfessionType | EpicReligiousProfessionType -- ----data EpicProfession = EpicProfession [ProfessionalRequirement] ----data DualClass = DualClass { parents :: [ AdventurerProfession ], AdventurerProfession --data RogueProfession = RogueProfession RogueProfessionType ProfessionalCompetence --data AdventurerProfession = RogueProfession | FighterProfession | MageProfession -- Warrior | Archer | Bard | Cleric | Ranger | Monk | Sorceror | Paladin | Rogue | Mage | Priest | Wizard | Knight --data ProfessionType = BasicProfessionType | AdventurerProfessionType | EpicProfessionType -- deriving (Eq, Show, Read, Enum, Bounded) --data Profession = Profession ProfessionType ProfessionSubtype ProfessionalCompetence --Aristocrat | Commoner | Warrior | Soldier | Archer | Bard | Trader | Pilgrim | Thief | Apothecary | Hunter | Cleric | Ranger | Monk | Sorceror | Paladin | Healer | Rogue | Merchant | Seeker | Archmage | Oracle | Priest | Wizard | Knight | Shadowmage | Commander | Diplomat | Ninja | Prophet | Pirate | Swashbuckler | Samurai | Warlord | Sage | Gambler | Scout | Assassin | WitchDoctor | Templar | Sniper | Trapper | Dancer | Dervish | Alchemist | Trickster | Inquisitor | Missionary | Tracker --deriving (Eq, Show, Read, Enum, Bounded) --data ProfessionalSubtype = Academic | Colonial | Rural | Telepathic | Drifter | Novitiate | Infernal | Celestial | Nomad | Forester | Herald | Criminal | Royal | Clandestine | Military | Guerrilla | Shadow | Dread | Scavenger | Feral | Primitive | Dilettante | Outcast | Celebrity | Eldritch -- deriving (Eq, Show, Read, Enum, Bounded) --data NormalSubtype = Academic | Colonial | Criminal | Drifer | Forester | Nomad | Novitiate | Scavenger --| | | | | --data RareSubtype = Feral | Dilettante | Clandestine | Shadow | Herald | Outcast | Guerrilla --data EpicProfessionalSubtype = Telepathic | Celebrity | Eldritch | Royal --data ProfessionalSubtype = NormalSubtype | RareSubtype | EpicSubtype --data ProfessionalRestriction = Profession StatisticValue -- Statistic Integer --data Job = Job ProfessionalSubtype Subtype -- { profession :: Profession, subtype :: ProfessionalSubtype } -- deriving (Eq, Show, Read)
jweissman/heroes
src/FantasyProfession.hs
mit
9,417
4
10
1,699
707
433
274
55
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Unison.Hash (Hash(Hash), toBytes, base32Hex, base32Hexs, fromBase32Hex, fromBytes, unsafeFromBase32Hex, showBase32Hex, validBase32HexChars) where import Unison.Prelude import Data.ByteString.Builder (doubleBE, word64BE, int64BE, toLazyByteString) import qualified Data.ByteArray as BA import qualified Crypto.Hash as CH import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Unison.Hashable as H import qualified Codec.Binary.Base32Hex as Base32Hex import qualified Data.Text as Text import qualified Data.Set as Set -- | Hash which uniquely identifies a Unison type or term newtype Hash = Hash { toBytes :: ByteString } deriving (Eq,Ord,Generic) instance Show Hash where show h = take 999 $ Text.unpack (base32Hex h) instance H.Hashable Hash where tokens h = [H.Bytes (toBytes h)] fromBytesImpl :: ByteString -> Hash fromBytesImpl = fromBytes toBytesImpl :: Hash -> ByteString toBytesImpl = toBytes instance H.Accumulate Hash where accumulate = fromBytes . BA.convert . CH.hashFinalize . go CH.hashInit where go :: CH.Context CH.SHA3_512 -> [H.Token Hash] -> CH.Context CH.SHA3_512 go acc tokens = CH.hashUpdates acc (tokens >>= toBS) toBS (H.Tag b) = [B.singleton b] toBS (H.Bytes bs) = [encodeLength $ B.length bs, bs] toBS (H.Int i) = BL.toChunks . toLazyByteString . int64BE $ i toBS (H.Nat i) = BL.toChunks . toLazyByteString . word64BE $ i toBS (H.Double d) = BL.toChunks . toLazyByteString . doubleBE $ d toBS (H.Text txt) = let tbytes = encodeUtf8 txt in [encodeLength (B.length tbytes), tbytes] toBS (H.Hashed h) = [toBytes h] encodeLength :: Integral n => n -> B.ByteString encodeLength = BL.toStrict . toLazyByteString . word64BE . fromIntegral fromBytes = fromBytesImpl toBytes = toBytesImpl -- | Return the lowercase unpadded base32Hex encoding of this 'Hash'. -- Multibase prefix would be 'v', see https://github.com/multiformats/multibase base32Hex :: Hash -> Text base32Hex (Hash h) = -- we're using an uppercase encoder that adds padding, so we drop the -- padding and convert it to lowercase Text.toLower . Text.dropWhileEnd (== '=') . decodeUtf8 $ Base32Hex.encode h validBase32HexChars :: Set Char validBase32HexChars = Set.fromList $ ['0' .. '9'] ++ ['a' .. 'v'] -- | Produce a 'Hash' from a base32hex-encoded version of its binary representation fromBase32Hex :: Text -> Maybe Hash fromBase32Hex txt = case Base32Hex.decode (encodeUtf8 $ Text.toUpper txt <> paddingChars) of Left (_, _rem) -> Nothing Right h -> pure $ Hash h where -- The decoder we're using is a base32 uppercase decoder that expects padding, -- so we provide it with the appropriate number of padding characters for the -- expected hash length. -- -- The decoder requires 40 bit (8 5-bit characters) chunks, so if the number -- of characters of the input is not a multiple of 8, we add '=' padding chars -- until it is. -- -- See https://tools.ietf.org/html/rfc4648#page-8 paddingChars :: Text paddingChars = case Text.length txt `mod` 8 of 0 -> "" n -> Text.replicate (8 - n) "=" hashLength :: Int hashLength = 512 _paddingChars :: Text _paddingChars = case hashLength `mod` 40 of 0 -> "" 8 -> "======" 16 -> "====" 24 -> "===" 32 -> "=" i -> error $ "impossible hash length `mod` 40 not in {0,8,16,24,32}: " <> show i base32Hexs :: Hash -> String base32Hexs = Text.unpack . base32Hex unsafeFromBase32Hex :: Text -> Hash unsafeFromBase32Hex txt = fromMaybe (error $ "invalid base32Hex value: " ++ Text.unpack txt) $ fromBase32Hex txt fromBytes :: ByteString -> Hash fromBytes = Hash showBase32Hex :: H.Hashable t => t -> String showBase32Hex = base32Hexs . H.accumulate'
unisonweb/platform
unison-core/src/Unison/Hash.hs
mit
3,848
0
14
729
1,025
561
464
75
8
module Graphics.D3D11Binding.Interface.D3D11ClassInstance where data ID3D11ClassInstance = ID3D11ClassInstance
jwvg0425/d3d11binding
src/Graphics/D3D11Binding/Interface/D3D11ClassInstance.hs
mit
113
0
5
9
15
10
5
2
0
{-# LANGUAGE QuasiQuotes, TemplateHaskell, DataKinds, OverloadedStrings #-} -- | Embed compiled purescript into the 'EmbeddedStatic' subsite. -- -- This module provides an alternative way of embedding purescript code into a yesod application, -- and is orthogonal to the support in "Yesod.PureScript". -- -- To use this module, you should place all your purescript code into a single directory as files -- with a @purs@ extension. Next, you should use <http://bower.io/ bower> to manage purescript -- dependencies. You can then give your directory and all dependency directories to the generators -- below. (At the moment, you must list each dependency explicitly. A future improvement is to -- parse bower.json to find dependencies.) -- -- For example, after installing bootstrap, purescript-either, and purescript-maybe using bower and -- then adding purescript code to a directory called @myPurescriptDir@, you could use code such as the -- following to create a static subsite. -- -- >import Yesod.EmbeddedStatic -- >import Yesod.PureScript.EmbeddedGenerator -- > -- >#ifdef DEVELOPMENT -- >#define DEV_BOOL True -- >#else -- >#define DEV_BOOL False -- >#endif -- >mkEmbeddedStatic DEV_BOOL "myStatic" [ -- > -- > purescript "js/mypurescript.js" uglifyJs ["MyPurescriptModule"] -- > [ "myPurescriptDir" -- > , "bower_components/purescript-either/src" -- > , "bower_components/purescript-maybe/src" -- > ] -- > -- > , embedFileAt "css/bootstrap.min.css" "bower_components/bootstrap/dist/boostrap.min.css" -- > , embedDirAt "fonts" "bower_components/bootstrap/dist/fonts" -- >] -- -- The result is that a variable `js_mypurescript_js` of type @Route EmbeddedStatic@ will be created -- that when accessed will contain the javascript generated by the purescript compiler. Assuming -- @StaticR@ is your route to the embdedded static subsite, you can then reference these routes -- using: -- -- >someHandler :: Handler Html -- >someHandler = defaultLayout $ do -- > addStylesheet $ StaticR css_bootstrap_min_css -- > addScript $ StaticR js_mypurescript_js -- > ... -- module Yesod.PureScript.EmbeddedGenerator( purescript , purescript' , purescriptPrelude ) where import Control.Monad (forM) import Control.Monad.Reader (runReaderT) import Data.Default (def) import Language.Haskell.TH (Q) import Language.Haskell.TH.Syntax (lift, liftString, TExp, unTypeQ, unsafeTExpCoerce) import System.Directory (doesDirectoryExist, getDirectoryContents) import System.FilePath ((</>), takeExtension) import System.IO (hPutStrLn, stderr) import Yesod.EmbeddedStatic import Yesod.EmbeddedStatic.Types import qualified Language.PureScript as P import qualified Data.ByteString.Lazy as BL import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL -- | Compile a collection of purescript modules (along with the prelude) to a single javascript -- file. -- -- All generated javascript code will be available under the global @PS@ variable. Thus from julius -- inside a yesod handler, you can access exports from modules via something like -- @[julius|PS.modulename.someexport("Hello, World")|]@. There will not be any call to a main function; you can -- either call the main function yourself from julius inside your handler or use -- the generator below to set 'P.optionsMain'. purescript :: Location -- ^ Location at which the generated javascript should appear inside the static subsite -> (BL.ByteString -> IO BL.ByteString) -- ^ Javascript minifier such as 'uglifyJs' to use when compiling for production. -- This is not used when compiling for development. -> [String] -- ^ List of purescript module names to use as roots for dead code elimination. -- -- If the empty list is given, no dead code elimination is performed and all code will -- appear in the generated javascript. If instead a list of modules is given, the purescript -- compiler will remove any code not reachable from these modules. This is -- primarily useful to remove unused code from dependencies and the prelude. -> [FilePath] -- ^ Directories containing purescript code. All files with a .purs extension located -- recursively in these directories will be given to the purescript compiler. These paths -- are relative to the directory containing the cabal file. -> Generator purescript loc mini roots = purescript' loc prodOpts devOpts mini where prodOpts = P.defaultCompileOptions { P.optionsAdditional = P.CompileOptions "PS" roots [] } devOpts = [|| P.defaultCompileOptions { P.optionsNoOptimizations = True , P.optionsVerboseErrors = True , P.optionsAdditional = P.CompileOptions "PS" $$(unsafeTExpCoerce $ lift roots) [] } ||] -- | A purescript generator which allows you to control the options given to the -- purescript compiler for both production and development. purescript' :: Location -- ^ Location at which the generated javascript should appear inside the static subsite -> P.Options 'P.Compile -- ^ options for compiling during production -> Q (TExp (P.Options 'P.Compile)) -- ^ Template haskell splice for development options. To create a value of this -- type, use @[|| ||]@ around a value of type @'P.Options' 'P.Compile'@. For example, -- @[|| defaultOptions { optionsNoOptimizations = True } ||]@ -> (BL.ByteString -> IO BL.ByteString) -- ^ Javascript minifier such as 'uglifyJs' to use when compiling for production. -- This is not used when compiling for development. -> [FilePath] -- ^ Directories containing purescript code. All files with a .purs extension located -- recursively in these directories will be given to the purescript compiler. These paths -- are relative to the directory containing the cabal file. -> Generator purescript' loc prodOpts devOpts mini dirs = do return [def { ebHaskellName = Just $ pathToName loc , ebLocation = loc , ebMimeType = "application/javascript" , ebProductionContent = compile loc prodOpts dirs >>= mini , ebDevelReload = [| compile $(liftString loc) $(unTypeQ devOpts) $(lift dirs) |] }] -- | Embed the purescript 'P.prelude' into the static subsite. -- -- The prelude only needs to appear once, so this is needed only if you specify 'P.optionsNoPrelude' -- to the above generator, since by default the prelude is included. purescriptPrelude :: Location -- location at which the prelude should appear -> (BL.ByteString -> IO BL.ByteString) -- ^ Javascript minifier such as 'uglifyJs' to use when compiling for production. -- This is not used when compiling for development. -> Generator purescriptPrelude loc mini = return [def { ebHaskellName = Just $ pathToName loc , ebLocation = loc , ebMimeType = "application/javascript" , ebProductionContent = compile loc P.defaultCompileOptions [] >>= mini , ebDevelReload = [| compile $(liftString loc) P.defaultCompileOptions [] |] }] -- | Helper function to compile a list of directories of purescript code. compile :: Location -> P.Options 'P.Compile -> [FilePath] -> IO BL.ByteString compile loc opts dirs = do hPutStrLn stderr $ "Compiling " ++ loc files <- concat <$> mapM getRecursiveContents dirs let modules = P.parseModulesFromFiles id $ if P.optionsNoPrelude opts then files else ("<prelude>", P.prelude) : files case modules of Left err -> do hPutStrLn stderr $ show err return $ TL.encodeUtf8 $ TL.pack $ show err Right ms -> do case P.compile (map snd ms) ["yesod-purescript"] `runReaderT` opts of Left err -> do hPutStrLn stderr err return $ TL.encodeUtf8 $ TL.pack err Right (js, _, _) -> return $ TL.encodeUtf8 $ TL.pack js -- | Get contents of all .purs files recursively in a directory getRecursiveContents :: FilePath -> IO [(FilePath, String)] getRecursiveContents topdir = do names <- getDirectoryContents topdir let properNames = filter (`notElem` [".", ".."]) names paths <- forM properNames $ \name -> do let path = topdir </> name isDirectory <- doesDirectoryExist path case (isDirectory, takeExtension path) of (True, _) -> getRecursiveContents path (False, ".purs") -> do ct <- readFile path return [(path, ct)] _ -> return [] return (concat paths)
jasonzoladz/yesod-purescript
Yesod/PureScript/EmbeddedGenerator.hs
mit
9,060
4
19
2,260
937
541
396
-1
-1
module Folds where import Data.Char import Data.List import Debug.Trace -- Ex 04: myConcat :: [[a]] -> [a] myConcat = foldr (++) [] myTakeWhile_rec :: (a -> Bool) -> [a] -> [a] myTakeWhile_rec f (a:as) | f a = a : myTakeWhile_rec f as myTakeWhile_rec _ (_:_) = [] myTakeWhile_rec _ [] = [] myTakeWhile_fold :: (a -> Bool) -> [a] -> [a] myTakeWhile_fold f = fst . foldr step ([], True) where step _ r@(_, False) = r step a (l, True) | f a = (l ++ [a], True) step _ r@(_, True) = r -- Supports infinite lists lazily myTakeWhile_fold2 :: (a -> Bool) -> [a] -> [a] myTakeWhile_fold2 f = (foldr step []) . map (\ a -> (f a, a)) where step (True, a) l = a:l step _ l = l -- Ex 05: myGroupBy :: (a -> a -> Bool) -> [a] -> [[a]] myGroupBy f = foldr step [[]] where step a [[]] = [[a]] step a (l:ls) | f a (head l) = (a:l):ls step a (l:ls) = [a]:l:ls -- Ex 06: myAny :: (a -> Bool) -> [a] -> Bool myAny f = foldr (||) False . map f myAny2 :: (a -> Bool) -> [a] -> Bool myAny2 f = foldr step False where step _ True = True step a False | f a = True step _ _ = False myCycle :: [a] -> [a] myCycle l0 = foldr step l0 [l0] where step l _ = l ++ myCycle l myWords :: String -> [String] myWords = reverse . foldl' step [""] where step (w:ws) c | not (isSpace c) = (w++[c]):ws step l@(w:_) _ | null w = l step ws _ = "":ws myUnlines :: [String] -> String myUnlines = foldl' step "" where step :: String -> String -> String step r l = r ++ l ++ "\n"
lpenz/realworldhaskell-exercises
ch04/Folds.hs
mit
1,602
0
12
484
874
465
409
43
3
{-# LANGUAGE TemplateHaskell, StandaloneDeriving, DeriveDataTypeable, DeriveGeneric #-} module CoqCoreBind where import qualified Prelude import qualified Data.ByteString import qualified Data.Array import qualified Data.IntMap import qualified FastString import qualified Data.Data as Data import qualified GHC.Generics as Generics import qualified Prelude as P import qualified Control.Monad as M import qualified Language.Haskell.TH as TH data Width = Mk_W8 | Mk_W16 | Mk_W32 | Mk_W64 | Mk_W80 | Mk_W128 | Mk_W256 | Mk_W512 data VisibilityFlag = Mk_Visible | Mk_Specified | Mk_Invisible data UnitId = Mk_PId FastString.FastString data Unique = Mk_MkUnique Prelude.Int data UniqFM ele = Mk_UFM (Data.IntMap.IntMap ele) data TyLit = Mk_NumTyLit Prelude.Integer | Mk_StrTyLit FastString.FastString data TupleSort = Mk_BoxedTuple | Mk_UnboxedTuple | Mk_ConstraintTuple type TickBoxId = Prelude.Int data TcLevel = Mk_TcLevel Prelude.Int data StrictnessMark = Mk_MarkedStrict | Mk_NotMarkedStrict data SrcUnpackedness = Mk_SrcUnpack | Mk_SrcNoUnpack | Mk_NoSrcUnpack data SrcStrictness = Mk_SrcLazy | Mk_SrcStrict | Mk_NoSrcStrict type SourceText = Prelude.String data Safety = Mk_PlaySafe | Mk_PlayInterruptible | Mk_PlayRisky data RuntimeRepInfo = Mk_RuntimeRepInfo_Dummy data Role = Mk_Nominal | Mk_Representational | Mk_Phantom data RecFlag = Mk_Recursive | Mk_NonRecursive data RealSrcSpan = Mk_RealSrcSpan' FastString.FastString Prelude.Int Prelude.Int Prelude.Int Prelude.Int data SrcSpan = Mk_RealSrcSpan RealSrcSpan | Mk_UnhelpfulSpan FastString.FastString data PrimOpVecCat = Mk_IntVec | Mk_WordVec | Mk_FloatVec data NameSpace = Mk_VarName | Mk_DataName | Mk_TvName | Mk_TcClsName data OccName = Mk_OccName NameSpace FastString.FastString data ModuleName = Mk_ModuleName FastString.FastString data Module = Mk_Module UnitId ModuleName data TickBoxOp = Mk_TickBox Module TickBoxId data MetaInfo = Mk_TauTv | Mk_SigTv | Mk_FlatMetaTv type Length = Prelude.Int data PrimOp = Mk_CharGtOp | Mk_CharGeOp | Mk_CharEqOp | Mk_CharNeOp | Mk_CharLtOp | Mk_CharLeOp | Mk_OrdOp | Mk_IntAddOp | Mk_IntSubOp | Mk_IntMulOp | Mk_IntMulMayOfloOp | Mk_IntQuotOp | Mk_IntRemOp | Mk_IntQuotRemOp | Mk_AndIOp | Mk_OrIOp | Mk_XorIOp | Mk_NotIOp | Mk_IntNegOp | Mk_IntAddCOp | Mk_IntSubCOp | Mk_IntGtOp | Mk_IntGeOp | Mk_IntEqOp | Mk_IntNeOp | Mk_IntLtOp | Mk_IntLeOp | Mk_ChrOp | Mk_Int2WordOp | Mk_Int2FloatOp | Mk_Int2DoubleOp | Mk_Word2FloatOp | Mk_Word2DoubleOp | Mk_ISllOp | Mk_ISraOp | Mk_ISrlOp | Mk_WordAddOp | Mk_WordSubCOp | Mk_WordAdd2Op | Mk_WordSubOp | Mk_WordMulOp | Mk_WordMul2Op | Mk_WordQuotOp | Mk_WordRemOp | Mk_WordQuotRemOp | Mk_WordQuotRem2Op | Mk_AndOp | Mk_OrOp | Mk_XorOp | Mk_NotOp | Mk_SllOp | Mk_SrlOp | Mk_Word2IntOp | Mk_WordGtOp | Mk_WordGeOp | Mk_WordEqOp | Mk_WordNeOp | Mk_WordLtOp | Mk_WordLeOp | Mk_PopCnt8Op | Mk_PopCnt16Op | Mk_PopCnt32Op | Mk_PopCnt64Op | Mk_PopCntOp | Mk_Clz8Op | Mk_Clz16Op | Mk_Clz32Op | Mk_Clz64Op | Mk_ClzOp | Mk_Ctz8Op | Mk_Ctz16Op | Mk_Ctz32Op | Mk_Ctz64Op | Mk_CtzOp | Mk_BSwap16Op | Mk_BSwap32Op | Mk_BSwap64Op | Mk_BSwapOp | Mk_Narrow8IntOp | Mk_Narrow16IntOp | Mk_Narrow32IntOp | Mk_Narrow8WordOp | Mk_Narrow16WordOp | Mk_Narrow32WordOp | Mk_DoubleGtOp | Mk_DoubleGeOp | Mk_DoubleEqOp | Mk_DoubleNeOp | Mk_DoubleLtOp | Mk_DoubleLeOp | Mk_DoubleAddOp | Mk_DoubleSubOp | Mk_DoubleMulOp | Mk_DoubleDivOp | Mk_DoubleNegOp | Mk_Double2IntOp | Mk_Double2FloatOp | Mk_DoubleExpOp | Mk_DoubleLogOp | Mk_DoubleSqrtOp | Mk_DoubleSinOp | Mk_DoubleCosOp | Mk_DoubleTanOp | Mk_DoubleAsinOp | Mk_DoubleAcosOp | Mk_DoubleAtanOp | Mk_DoubleSinhOp | Mk_DoubleCoshOp | Mk_DoubleTanhOp | Mk_DoublePowerOp | Mk_DoubleDecode_2IntOp | Mk_DoubleDecode_Int64Op | Mk_FloatGtOp | Mk_FloatGeOp | Mk_FloatEqOp | Mk_FloatNeOp | Mk_FloatLtOp | Mk_FloatLeOp | Mk_FloatAddOp | Mk_FloatSubOp | Mk_FloatMulOp | Mk_FloatDivOp | Mk_FloatNegOp | Mk_Float2IntOp | Mk_FloatExpOp | Mk_FloatLogOp | Mk_FloatSqrtOp | Mk_FloatSinOp | Mk_FloatCosOp | Mk_FloatTanOp | Mk_FloatAsinOp | Mk_FloatAcosOp | Mk_FloatAtanOp | Mk_FloatSinhOp | Mk_FloatCoshOp | Mk_FloatTanhOp | Mk_FloatPowerOp | Mk_Float2DoubleOp | Mk_FloatDecode_IntOp | Mk_NewArrayOp | Mk_SameMutableArrayOp | Mk_ReadArrayOp | Mk_WriteArrayOp | Mk_SizeofArrayOp | Mk_SizeofMutableArrayOp | Mk_IndexArrayOp | Mk_UnsafeFreezeArrayOp | Mk_UnsafeThawArrayOp | Mk_CopyArrayOp | Mk_CopyMutableArrayOp | Mk_CloneArrayOp | Mk_CloneMutableArrayOp | Mk_FreezeArrayOp | Mk_ThawArrayOp | Mk_CasArrayOp | Mk_NewSmallArrayOp | Mk_SameSmallMutableArrayOp | Mk_ReadSmallArrayOp | Mk_WriteSmallArrayOp | Mk_SizeofSmallArrayOp | Mk_SizeofSmallMutableArrayOp | Mk_IndexSmallArrayOp | Mk_UnsafeFreezeSmallArrayOp | Mk_UnsafeThawSmallArrayOp | Mk_CopySmallArrayOp | Mk_CopySmallMutableArrayOp | Mk_CloneSmallArrayOp | Mk_CloneSmallMutableArrayOp | Mk_FreezeSmallArrayOp | Mk_ThawSmallArrayOp | Mk_CasSmallArrayOp | Mk_NewByteArrayOp_Char | Mk_NewPinnedByteArrayOp_Char | Mk_NewAlignedPinnedByteArrayOp_Char | Mk_ByteArrayContents_Char | Mk_SameMutableByteArrayOp | Mk_ShrinkMutableByteArrayOp_Char | Mk_ResizeMutableByteArrayOp_Char | Mk_UnsafeFreezeByteArrayOp | Mk_SizeofByteArrayOp | Mk_SizeofMutableByteArrayOp | Mk_GetSizeofMutableByteArrayOp | Mk_IndexByteArrayOp_Char | Mk_IndexByteArrayOp_WideChar | Mk_IndexByteArrayOp_Int | Mk_IndexByteArrayOp_Word | Mk_IndexByteArrayOp_Addr | Mk_IndexByteArrayOp_Float | Mk_IndexByteArrayOp_Double | Mk_IndexByteArrayOp_StablePtr | Mk_IndexByteArrayOp_Int8 | Mk_IndexByteArrayOp_Int16 | Mk_IndexByteArrayOp_Int32 | Mk_IndexByteArrayOp_Int64 | Mk_IndexByteArrayOp_Word8 | Mk_IndexByteArrayOp_Word16 | Mk_IndexByteArrayOp_Word32 | Mk_IndexByteArrayOp_Word64 | Mk_ReadByteArrayOp_Char | Mk_ReadByteArrayOp_WideChar | Mk_ReadByteArrayOp_Int | Mk_ReadByteArrayOp_Word | Mk_ReadByteArrayOp_Addr | Mk_ReadByteArrayOp_Float | Mk_ReadByteArrayOp_Double | Mk_ReadByteArrayOp_StablePtr | Mk_ReadByteArrayOp_Int8 | Mk_ReadByteArrayOp_Int16 | Mk_ReadByteArrayOp_Int32 | Mk_ReadByteArrayOp_Int64 | Mk_ReadByteArrayOp_Word8 | Mk_ReadByteArrayOp_Word16 | Mk_ReadByteArrayOp_Word32 | Mk_ReadByteArrayOp_Word64 | Mk_WriteByteArrayOp_Char | Mk_WriteByteArrayOp_WideChar | Mk_WriteByteArrayOp_Int | Mk_WriteByteArrayOp_Word | Mk_WriteByteArrayOp_Addr | Mk_WriteByteArrayOp_Float | Mk_WriteByteArrayOp_Double | Mk_WriteByteArrayOp_StablePtr | Mk_WriteByteArrayOp_Int8 | Mk_WriteByteArrayOp_Int16 | Mk_WriteByteArrayOp_Int32 | Mk_WriteByteArrayOp_Int64 | Mk_WriteByteArrayOp_Word8 | Mk_WriteByteArrayOp_Word16 | Mk_WriteByteArrayOp_Word32 | Mk_WriteByteArrayOp_Word64 | Mk_CopyByteArrayOp | Mk_CopyMutableByteArrayOp | Mk_CopyByteArrayToAddrOp | Mk_CopyMutableByteArrayToAddrOp | Mk_CopyAddrToByteArrayOp | Mk_SetByteArrayOp | Mk_AtomicReadByteArrayOp_Int | Mk_AtomicWriteByteArrayOp_Int | Mk_CasByteArrayOp_Int | Mk_FetchAddByteArrayOp_Int | Mk_FetchSubByteArrayOp_Int | Mk_FetchAndByteArrayOp_Int | Mk_FetchNandByteArrayOp_Int | Mk_FetchOrByteArrayOp_Int | Mk_FetchXorByteArrayOp_Int | Mk_NewArrayArrayOp | Mk_SameMutableArrayArrayOp | Mk_UnsafeFreezeArrayArrayOp | Mk_SizeofArrayArrayOp | Mk_SizeofMutableArrayArrayOp | Mk_IndexArrayArrayOp_ByteArray | Mk_IndexArrayArrayOp_ArrayArray | Mk_ReadArrayArrayOp_ByteArray | Mk_ReadArrayArrayOp_MutableByteArray | Mk_ReadArrayArrayOp_ArrayArray | Mk_ReadArrayArrayOp_MutableArrayArray | Mk_WriteArrayArrayOp_ByteArray | Mk_WriteArrayArrayOp_MutableByteArray | Mk_WriteArrayArrayOp_ArrayArray | Mk_WriteArrayArrayOp_MutableArrayArray | Mk_CopyArrayArrayOp | Mk_CopyMutableArrayArrayOp | Mk_AddrAddOp | Mk_AddrSubOp | Mk_AddrRemOp | Mk_Addr2IntOp | Mk_Int2AddrOp | Mk_AddrGtOp | Mk_AddrGeOp | Mk_AddrEqOp | Mk_AddrNeOp | Mk_AddrLtOp | Mk_AddrLeOp | Mk_IndexOffAddrOp_Char | Mk_IndexOffAddrOp_WideChar | Mk_IndexOffAddrOp_Int | Mk_IndexOffAddrOp_Word | Mk_IndexOffAddrOp_Addr | Mk_IndexOffAddrOp_Float | Mk_IndexOffAddrOp_Double | Mk_IndexOffAddrOp_StablePtr | Mk_IndexOffAddrOp_Int8 | Mk_IndexOffAddrOp_Int16 | Mk_IndexOffAddrOp_Int32 | Mk_IndexOffAddrOp_Int64 | Mk_IndexOffAddrOp_Word8 | Mk_IndexOffAddrOp_Word16 | Mk_IndexOffAddrOp_Word32 | Mk_IndexOffAddrOp_Word64 | Mk_ReadOffAddrOp_Char | Mk_ReadOffAddrOp_WideChar | Mk_ReadOffAddrOp_Int | Mk_ReadOffAddrOp_Word | Mk_ReadOffAddrOp_Addr | Mk_ReadOffAddrOp_Float | Mk_ReadOffAddrOp_Double | Mk_ReadOffAddrOp_StablePtr | Mk_ReadOffAddrOp_Int8 | Mk_ReadOffAddrOp_Int16 | Mk_ReadOffAddrOp_Int32 | Mk_ReadOffAddrOp_Int64 | Mk_ReadOffAddrOp_Word8 | Mk_ReadOffAddrOp_Word16 | Mk_ReadOffAddrOp_Word32 | Mk_ReadOffAddrOp_Word64 | Mk_WriteOffAddrOp_Char | Mk_WriteOffAddrOp_WideChar | Mk_WriteOffAddrOp_Int | Mk_WriteOffAddrOp_Word | Mk_WriteOffAddrOp_Addr | Mk_WriteOffAddrOp_Float | Mk_WriteOffAddrOp_Double | Mk_WriteOffAddrOp_StablePtr | Mk_WriteOffAddrOp_Int8 | Mk_WriteOffAddrOp_Int16 | Mk_WriteOffAddrOp_Int32 | Mk_WriteOffAddrOp_Int64 | Mk_WriteOffAddrOp_Word8 | Mk_WriteOffAddrOp_Word16 | Mk_WriteOffAddrOp_Word32 | Mk_WriteOffAddrOp_Word64 | Mk_NewMutVarOp | Mk_ReadMutVarOp | Mk_WriteMutVarOp | Mk_SameMutVarOp | Mk_AtomicModifyMutVarOp | Mk_CasMutVarOp | Mk_CatchOp | Mk_RaiseOp | Mk_RaiseIOOp | Mk_MaskAsyncExceptionsOp | Mk_MaskUninterruptibleOp | Mk_UnmaskAsyncExceptionsOp | Mk_MaskStatus | Mk_AtomicallyOp | Mk_RetryOp | Mk_CatchRetryOp | Mk_CatchSTMOp | Mk_CheckOp | Mk_NewTVarOp | Mk_ReadTVarOp | Mk_ReadTVarIOOp | Mk_WriteTVarOp | Mk_SameTVarOp | Mk_NewMVarOp | Mk_TakeMVarOp | Mk_TryTakeMVarOp | Mk_PutMVarOp | Mk_TryPutMVarOp | Mk_ReadMVarOp | Mk_TryReadMVarOp | Mk_SameMVarOp | Mk_IsEmptyMVarOp | Mk_DelayOp | Mk_WaitReadOp | Mk_WaitWriteOp | Mk_ForkOp | Mk_ForkOnOp | Mk_KillThreadOp | Mk_YieldOp | Mk_MyThreadIdOp | Mk_LabelThreadOp | Mk_IsCurrentThreadBoundOp | Mk_NoDuplicateOp | Mk_ThreadStatusOp | Mk_MkWeakOp | Mk_MkWeakNoFinalizerOp | Mk_AddCFinalizerToWeakOp | Mk_DeRefWeakOp | Mk_FinalizeWeakOp | Mk_TouchOp | Mk_MakeStablePtrOp | Mk_DeRefStablePtrOp | Mk_EqStablePtrOp | Mk_MakeStableNameOp | Mk_EqStableNameOp | Mk_StableNameToIntOp | Mk_ReallyUnsafePtrEqualityOp | Mk_ParOp | Mk_SparkOp | Mk_SeqOp | Mk_GetSparkOp | Mk_NumSparks | Mk_DataToTagOp | Mk_TagToEnumOp | Mk_AddrToAnyOp | Mk_MkApUpd0_Op | Mk_NewBCOOp | Mk_UnpackClosureOp | Mk_GetApStackValOp | Mk_GetCCSOfOp | Mk_GetCurrentCCSOp | Mk_ClearCCSOp | Mk_TraceEventOp | Mk_TraceMarkerOp | Mk_VecBroadcastOp PrimOpVecCat Length Width | Mk_VecPackOp PrimOpVecCat Length Width | Mk_VecUnpackOp PrimOpVecCat Length Width | Mk_VecInsertOp PrimOpVecCat Length Width | Mk_VecAddOp PrimOpVecCat Length Width | Mk_VecSubOp PrimOpVecCat Length Width | Mk_VecMulOp PrimOpVecCat Length Width | Mk_VecDivOp PrimOpVecCat Length Width | Mk_VecQuotOp PrimOpVecCat Length Width | Mk_VecRemOp PrimOpVecCat Length Width | Mk_VecNegOp PrimOpVecCat Length Width | Mk_VecIndexByteArrayOp PrimOpVecCat Length Width | Mk_VecReadByteArrayOp PrimOpVecCat Length Width | Mk_VecWriteByteArrayOp PrimOpVecCat Length Width | Mk_VecIndexOffAddrOp PrimOpVecCat Length Width | Mk_VecReadOffAddrOp PrimOpVecCat Length Width | Mk_VecWriteOffAddrOp PrimOpVecCat Length Width | Mk_VecIndexScalarByteArrayOp PrimOpVecCat Length Width | Mk_VecReadScalarByteArrayOp PrimOpVecCat Length Width | Mk_VecWriteScalarByteArrayOp PrimOpVecCat Length Width | Mk_VecIndexScalarOffAddrOp PrimOpVecCat Length Width | Mk_VecReadScalarOffAddrOp PrimOpVecCat Length Width | Mk_VecWriteScalarOffAddrOp PrimOpVecCat Length Width | Mk_PrefetchByteArrayOp3 | Mk_PrefetchMutableByteArrayOp3 | Mk_PrefetchAddrOp3 | Mk_PrefetchValueOp3 | Mk_PrefetchByteArrayOp2 | Mk_PrefetchMutableByteArrayOp2 | Mk_PrefetchAddrOp2 | Mk_PrefetchValueOp2 | Mk_PrefetchByteArrayOp1 | Mk_PrefetchMutableByteArrayOp1 | Mk_PrefetchAddrOp1 | Mk_PrefetchValueOp1 | Mk_PrefetchByteArrayOp0 | Mk_PrefetchMutableByteArrayOp0 | Mk_PrefetchAddrOp0 | Mk_PrefetchValueOp0 data LeftOrRight = Mk_CLeft | Mk_CRight data IsCafCC = Mk_NotCafCC | Mk_CafCC data Injectivity = Mk_NotInjective | Mk_Injective ([] Prelude.Bool) data IdInfo = Mk_IdInfo_Dummy data HsSrcBang = Mk_HsSrcBang (Prelude.Maybe SourceText) SrcUnpackedness SrcStrictness data Header = Mk_Header SourceText FastString.FastString data GenLocated l e = Mk_L l e type Located e = GenLocated SrcSpan e data FunctionOrData = Mk_IsFunction | Mk_IsData type FunDep a = (,) ([] a) ([] a) type FieldLabelString = FastString.FastString data FieldLbl a = Mk_FieldLabel FieldLabelString Prelude.Bool a type FastStringEnv a = UniqFM a data ExportFlag = Mk_NotExported | Mk_Exported data IdScope = Mk_GlobalId | Mk_LocalId ExportFlag data DefMethSpec ty = Mk_VanillaDM | Mk_GenericDM ty data DataConBoxer = Mk_DataConBoxer_Dummy type ConTag = Prelude.Int data CoAxiomRule = Mk_CoAxiomRule_Dummy type CcName = FastString.FastString data CostCentre = Mk_NormalCC Prelude.Int CcName Module SrcSpan IsCafCC | Mk_AllCafsCC Module SrcSpan data Tickish id = Mk_ProfNote CostCentre Prelude.Bool Prelude.Bool | Mk_HpcTick Module Prelude.Int | Mk_Breakpoint Prelude.Int ([] id) | Mk_SourceNote RealSrcSpan Prelude.String data CType = Mk_CType SourceText (Prelude.Maybe Header) ((,) SourceText FastString.FastString) type CLabelString = FastString.FastString data CCallTarget = Mk_StaticTarget SourceText CLabelString (Prelude.Maybe UnitId) Prelude.Bool | Mk_DynamicTarget data CCallConv = Mk_CCallConv | Mk_CApiConv | Mk_StdCallConv | Mk_PrimCallConv | Mk_JavaScriptCallConv data CCallSpec = Mk_CCallSpec CCallTarget CCallConv Safety data ForeignCall = Mk_CCall CCallSpec data BuiltInSyntax = Mk_BuiltInSyntax | Mk_UserSyntax data BuiltInSynFamily = Mk_BuiltInSynFamily_Dummy type BranchIndex = Prelude.Int data BranchFlag = Mk_Branched | Mk_Unbranched data BooleanFormula a = Mk_BFVar a | Mk_And ([] (Located (BooleanFormula a))) | Mk_Or ([] (Located (BooleanFormula a))) | Mk_Parens (Located (BooleanFormula a)) type Arity = Prelude.Int data AlgTyConFlav = Mk_VanillaAlgTyCon Name | Mk_UnboxedAlgTyCon | Mk_ClassTyCon Class Name | Mk_DataFamInstTyCon CoAxiom TyCon ([] Type_) data Class = Mk_Class TyCon Name Unique ([] Var) ([] (FunDep Var)) ([] Type_) ([] Var) ([] ClassATItem) ([] ((,) Var (Prelude.Maybe ((,) Name (DefMethSpec Type_))))) (BooleanFormula Name) data ClassATItem = Mk_ATI TyCon (Prelude.Maybe ((,) Type_ SrcSpan)) data TyCon = Mk_FunTyCon Unique Name ([] TyBinder) Type_ Type_ Arity Name | Mk_AlgTyCon Unique Name ([] TyBinder) Type_ Type_ Arity ([] Var) ([] Role) (Prelude.Maybe CType) Prelude.Bool ([] Type_) AlgTyConRhs (FastStringEnv (FieldLbl Name)) RecFlag AlgTyConFlav | Mk_SynonymTyCon Unique Name ([] TyBinder) Type_ Type_ Arity ([] Var) ([] Role) Type_ | Mk_FamilyTyCon Unique Name ([] TyBinder) Type_ Type_ Arity ([] Var) (Prelude.Maybe Name) FamTyConFlav (Prelude.Maybe Class) Injectivity | Mk_PrimTyCon Unique Name ([] TyBinder) Type_ Type_ Arity ([] Role) Prelude.Bool (Prelude.Maybe Name) | Mk_PromotedDataCon Unique Name Arity ([] TyBinder) Type_ Type_ ([] Role) DataCon Name RuntimeRepInfo | Mk_TcTyCon Unique Name Prelude.Bool ([] Var) ([] TyBinder) Type_ Type_ Arity ([] Var) data AlgTyConRhs = Mk_AbstractTyCon Prelude.Bool | Mk_DataTyCon ([] DataCon) Prelude.Bool | Mk_TupleTyCon DataCon TupleSort | Mk_NewTyCon DataCon Type_ ((,) ([] Var) Type_) CoAxiom data CoAxiom = Mk_CoAxiom BranchFlag Unique Name Role TyCon Branches Prelude.Bool data Branches = Mk_MkBranches BranchFlag (Data.Array.Array BranchIndex CoAxBranch) data CoAxBranch = Mk_CoAxBranch SrcSpan ([] Var) ([] Var) ([] Role) ([] Type_) Type_ ([] CoAxBranch) data Var = Mk_TyVar Name Prelude.Int Type_ | Mk_TcTyVar Name Prelude.Int Type_ TcTyVarDetails | Mk_Id Name Prelude.Int Type_ IdScope IdDetails IdInfo data IdDetails = Mk_VanillaId | Mk_RecSelId RecSelParent Prelude.Bool | Mk_DataConWorkId DataCon | Mk_DataConWrapId DataCon | Mk_ClassOpId Class | Mk_PrimOpId PrimOp | Mk_FCallId ForeignCall | Mk_TickBoxOpId TickBoxOp | Mk_DFunId Prelude.Bool | Mk_CoVarId data DataCon = Mk_MkData Name Unique ConTag Prelude.Bool ([] Var) ([] TyBinder) ([] Var) ([] TyBinder) ([] EqSpec) ([] Type_) ([] Type_) ([] Type_) Type_ ([] HsSrcBang) ([] (FieldLbl Name)) Var DataConRep Arity Arity TyCon Type_ Prelude.Bool TyCon data DataConRep = Mk_NoDataConRep | Mk_DCR Var DataConBoxer ([] Type_) ([] StrictnessMark) ([] HsImplBang) data HsImplBang = Mk_HsLazy | Mk_HsStrict | Mk_HsUnpack (Prelude.Maybe Coercion) data Coercion = Mk_Refl Role Type_ | Mk_TyConAppCo Role TyCon ([] Coercion) | Mk_AppCo Coercion Coercion | Mk_ForAllCo Var Coercion Coercion | Mk_CoVarCo Var | Mk_AxiomInstCo CoAxiom BranchIndex ([] Coercion) | Mk_UnivCo UnivCoProvenance Role Type_ Type_ | Mk_SymCo Coercion | Mk_TransCo Coercion Coercion | Mk_AxiomRuleCo CoAxiomRule ([] Coercion) | Mk_NthCo Prelude.Int Coercion | Mk_LRCo LeftOrRight Coercion | Mk_InstCo Coercion Coercion | Mk_CoherenceCo Coercion Coercion | Mk_KindCo Coercion | Mk_SubCo Coercion data Type_ = Mk_TyVarTy Var | Mk_AppTy Type_ Type_ | Mk_TyConApp TyCon ([] Type_) | Mk_ForAllTy TyBinder Type_ | Mk_LitTy TyLit | Mk_CastTy Type_ Coercion | Mk_CoercionTy Coercion data TyBinder = Mk_Named Var VisibilityFlag | Mk_Anon Type_ data UnivCoProvenance = Mk_UnsafeCoerceProv | Mk_PhantomProv Coercion | Mk_ProofIrrelProv Coercion | Mk_PluginProv Prelude.String | Mk_HoleProv CoercionHole data CoercionHole = Mk_CoercionHole Unique data EqSpec = Mk_EqSpec Var Type_ data Name = Mk_Name NameSort OccName Prelude.Int SrcSpan data NameSort = Mk_External Module | Mk_WiredIn Module TyThing BuiltInSyntax | Mk_Internal | Mk_System data TyThing = Mk_AnId Var | Mk_AConLike ConLike | Mk_ATyCon TyCon | Mk_ACoAxiom CoAxiom data ConLike = Mk_RealDataCon DataCon | Mk_PatSynCon PatSyn data PatSyn = Mk_MkPatSyn Name Unique ([] Type_) Arity Prelude.Bool ([] (FieldLbl Name)) ([] Var) ([] TyBinder) ([] Type_) ([] Var) ([] TyBinder) ([] Type_) Type_ ((,) Var Prelude.Bool) (Prelude.Maybe ((,) Var Prelude.Bool)) data RecSelParent = Mk_RecSelData TyCon | Mk_RecSelPatSyn PatSyn data TcTyVarDetails = Mk_SkolemTv Prelude.Bool | Mk_FlatSkol Type_ | Mk_RuntimeUnk | Mk_MetaTv MetaInfo TcLevel data MetaDetails = Mk_Flexi | Mk_Indirect Type_ data FamTyConFlav = Mk_DataFamilyTyCon Name | Mk_OpenSynFamilyTyCon | Mk_ClosedSynFamilyTyCon (Prelude.Maybe CoAxiom) | Mk_AbstractClosedSynFamilyTyCon | Mk_BuiltInSynFamTyCon BuiltInSynFamily data Literal = Mk_MachChar Prelude.Char | Mk_MachStr Data.ByteString.ByteString | Mk_MachNullAddr | Mk_MachInt Prelude.Integer | Mk_MachInt64 Prelude.Integer | Mk_MachWord Prelude.Integer | Mk_MachWord64 Prelude.Integer | Mk_MachFloat Prelude.Rational | Mk_MachDouble Prelude.Rational | Mk_MachLabel FastString.FastString (Prelude.Maybe Prelude.Int) FunctionOrData | Mk_LitInteger Prelude.Integer Type_ type CoreBndr = Var data AltCon = Mk_DataAlt DataCon | Mk_LitAlt Literal | Mk_DEFAULT data Expr b = Mk_Var Var | Mk_Lit Literal | Mk_App (Expr b) (Expr b) | Mk_Lam b (Expr b) | Mk_Let (Bind b) (Expr b) | Mk_Case (Expr b) b Type_ ([] ((,) ((,) AltCon ([] b)) (Expr b))) | Mk_Cast (Expr b) Coercion | Mk_Tick (Tickish Var) (Expr b) | Mk_Type Type_ | Mk_Coercion Coercion data Bind b = Mk_NonRec b (Expr b) | Mk_Rec ([] ((,) b (Expr b))) type CoreBind = Bind CoreBndr P.sequence [ do let constraint = (TH.ConT cls `TH.AppT`) tvs <- M.replicateM arity P.$ TH.VarT P.<$> TH.newName "a" P.pure P.$ TH.StandaloneDerivD (P.map constraint tvs) (constraint P.$ P.foldl TH.AppT (TH.ConT ty) tvs) | cls <- [''P.Eq, ''P.Ord, ''P.Show, ''Data.Data, ''Generics.Generic] , (ty,arity) <- [ (''Width , 0) , (''VisibilityFlag , 0) , (''UnitId , 0) , (''Unique , 0) , (''UniqFM , 1) , (''TyLit , 0) , (''TupleSort , 0) , (''TcLevel , 0) , (''StrictnessMark , 0) , (''SrcUnpackedness , 0) , (''SrcStrictness , 0) , (''Safety , 0) , (''RuntimeRepInfo , 0) , (''Role , 0) , (''RecFlag , 0) , (''RealSrcSpan , 0) , (''SrcSpan , 0) , (''PrimOpVecCat , 0) , (''NameSpace , 0) , (''OccName , 0) , (''ModuleName , 0) , (''Module , 0) , (''TickBoxOp , 0) , (''MetaInfo , 0) , (''PrimOp , 0) , (''LeftOrRight , 0) , (''IsCafCC , 0) , (''Injectivity , 0) , (''IdInfo , 0) , (''HsSrcBang , 0) , (''Header , 0) , (''GenLocated , 2) , (''FunctionOrData , 0) , (''FieldLbl , 1) , (''ExportFlag , 0) , (''IdScope , 0) , (''DefMethSpec , 1) , (''DataConBoxer , 0) , (''CoAxiomRule , 0) , (''CostCentre , 0) , (''Tickish , 1) , (''CType , 0) , (''CCallTarget , 0) , (''CCallConv , 0) , (''CCallSpec , 0) , (''ForeignCall , 0) , (''BuiltInSyntax , 0) , (''BuiltInSynFamily , 0) , (''BranchFlag , 0) , (''BooleanFormula , 1) , (''AlgTyConFlav , 0) , (''Class , 0) , (''ClassATItem , 0) , (''TyCon , 0) , (''AlgTyConRhs , 0) , (''CoAxiom , 0) , (''Branches , 0) , (''CoAxBranch , 0) , (''Var , 0) , (''IdDetails , 0) , (''DataCon , 0) , (''DataConRep , 0) , (''HsImplBang , 0) , (''Coercion , 0) , (''Type_ , 0) , (''TyBinder , 0) , (''UnivCoProvenance , 0) , (''CoercionHole , 0) , (''EqSpec , 0) , (''Name , 0) , (''NameSort , 0) , (''TyThing , 0) , (''ConLike , 0) , (''PatSyn , 0) , (''RecSelParent , 0) , (''TcTyVarDetails , 0) , (''MetaDetails , 0) , (''FamTyConFlav , 0) , (''Literal , 0) , (''AltCon , 0) , (''Expr , 1) , (''Bind , 1) ] ]
antalsz/hs-to-coq
structural-isomorphism-plugin/src/CoqCoreBind.hs
mit
24,197
0
16
5,765
5,445
3,217
2,228
872
0
module Main where import qualified Data.ByteString.Lazy as B import qualified Data.ByteString.Lazy.Char8 as C import Data.Char import Data.Word import Data.Bits import System.IO main :: IO () main = do hSetBinaryMode stdin True hSetBinaryMode stdout True bsIn <- C.getContents let hexBs = C.filter (isHexDigit) bsIn B.putStr $ B.pack $ unhex hexBs unhex :: C.ByteString -> [Word8] unhex bsIn = let (nibble, rest) = C.splitAt 2 bsIn in case (C.unpack nibble) of hi:lo:[] -> (unhexByte hi lo) : unhex rest _ -> [] unhexByte :: Char -> Char -> Word8 unhexByte hi lo = shift (unhexNibble hi) 4 .|. unhexNibble lo unhexNibble :: Char -> Word8 unhexNibble ch = let (chDiff, intDiff) = diff ch in toEnum $ (fromEnum ch) - (fromEnum chDiff) + intDiff diff :: Char -> (Char, Int) diff ch | ch >= 'a' = ('a', 10) | ch >= 'A' = ('A', 10) | ch >= '0' = ('0', 0) | otherwise = error $ "Unexpected char [" ++ (show ch) ++ "] in unhexNibble"
andreyk0/hex2bin
Main.hs
mit
997
0
12
236
425
219
206
32
2
module Workplaces.ResourceAddition where import Rules import TestFramework import TestHelpers import Test.Tasty import Test.Tasty.QuickCheck import Test.QuickCheck.Monadic resourceAdditionTests :: TestTree resourceAdditionTests = localOption (QuickCheckMaxRatio 500) $ testGroup "Resource addition tests" $ [ testProperty "Starting working adds resources" $ movingWorkerProperty $ do originalUniverse <- getUniverse (playerId, _, _) <- startWorkingInResourceAddition newUniverse <- getUniverse let originalResources = getPlayerResources originalUniverse playerId newResources = getPlayerResources newUniverse playerId assert $ getWoodAmount originalResources + 1 == getWoodAmount newResources assert $ getIronAmount originalResources + 1 == getIronAmount newResources assert $ getStoneAmount originalResources + 1 == getStoneAmount newResources assert $ getFoodAmount originalResources + 1 == getFoodAmount newResources assert $ getMoneyAmount originalResources + 2 == getMoneyAmount newResources, testProperty "Starting working stops turn" $ movingWorkerProperty $ do (playerId, _, _) <- startWorkingInResourceAddition checkPlayerHasValidOccupants playerId validateNextPlayer playerId ] startWorkingInResourceAddition :: UniversePropertyMonad (PlayerId, WorkerId, WorkplaceId) startWorkingInResourceAddition = startWorkingInWorkplaceType ResourceAddition
martin-kolinek/some-board-game-rules
test/Workplaces/ResourceAddition.hs
mit
1,452
0
13
231
302
148
154
26
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.Text (js_newText, newText, js_splitText, splitText, js_replaceWholeText, replaceWholeText, js_getWholeText, getWholeText, Text, castToText, gTypeText, IsText, toText) 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 "new window[\"Text\"]($1)" js_newText :: JSString -> IO Text -- | <https://developer.mozilla.org/en-US/docs/Web/API/Text Mozilla Text documentation> newText :: (MonadIO m, ToJSString data') => data' -> m Text newText data' = liftIO (js_newText (toJSString data')) foreign import javascript unsafe "$1[\"splitText\"]($2)" js_splitText :: Text -> Word -> IO (Nullable Text) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Text.splitText Mozilla Text.splitText documentation> splitText :: (MonadIO m, IsText self) => self -> Word -> m (Maybe Text) splitText self offset = liftIO (nullableToMaybe <$> (js_splitText (toText self) offset)) foreign import javascript unsafe "$1[\"replaceWholeText\"]($2)" js_replaceWholeText :: Text -> JSString -> IO (Nullable Text) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Text.replaceWholeText Mozilla Text.replaceWholeText documentation> replaceWholeText :: (MonadIO m, IsText self, ToJSString content) => self -> content -> m (Maybe Text) replaceWholeText self content = liftIO (nullableToMaybe <$> (js_replaceWholeText (toText self) (toJSString content))) foreign import javascript unsafe "$1[\"wholeText\"]" js_getWholeText :: Text -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/Text.wholeText Mozilla Text.wholeText documentation> getWholeText :: (MonadIO m, IsText self, FromJSString result) => self -> m result getWholeText self = liftIO (fromJSString <$> (js_getWholeText (toText self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/Text.hs
mit
2,687
28
11
415
691
402
289
44
1
module Web.Hastodon ( module Web.Hastodon.Option , module Web.Hastodon.Streaming , module Web.Hastodon.Types , HastodonClient(..) , mkHastodonClient , getAccountById , getCurrentAccount , getFollowers , getFollowersWithOption , getFollowing , getFollowingWithOption , getAccountStatuses , getAccountStatusesWithOption , postFollow , postUnfollow , postBlock , postUnblock , postMute , postMuteWithOption , postUnmute , getRelationships , getSearchedAccounts , getSearchedAccountsWithOption , postApps , getBlocks , getBlocksWithOption , getFavorites , getFavoritesWithOption , getFollowRequests , getFollowRequestsWithOption , postAuthorizeRequest , postRejectRequest , getInstance , postMediaFile , getMutes , getMutesWithOption , getNotifications , getNotificationsWithOption , getNotificationById , postNotificationsClear , getReports , getSearchedResults , getSearchedResultsWithOption , getStatus , getCard , getContext , getRebloggedBy , getRebloggedByWithOption , getFavoritedBy , getFavoritedByWithOption , postStatus , postStatusWithOption , postStatusWithMediaIds , postReblog , postUnreblog , postFavorite , postUnfavorite , getHomeTimeline , getHomeTimelineWithOption , getPublicTimeline , getPublicTimelineWithOption , getTaggedTimeline , getTaggedTimelineWithOption , streamUser , streamPublic , streamLocal , streamHashtag , streamList ) where import Web.Hastodon.API import Web.Hastodon.Option import Web.Hastodon.Streaming import Web.Hastodon.Types import Web.Hastodon.Util
syucream/hastodon
Web/Hastodon.hs
mit
1,632
0
5
294
258
173
85
74
0
-- Selective fear of numbers -- http://www.codewars.com/kata/55b1fd84a24ad00b32000075/ module Codewars.Exercise.Fear {- of the dark -} where amIAfraid :: String -> Int -> Bool amIAfraid "Monday" = (== 12) amIAfraid "Tuesday" = (> 95) amIAfraid "Wednesday" = (== 34) amIAfraid "Thursday" = (== 0) amIAfraid "Friday" = even amIAfraid "Saturday" = (== 56) amIAfraid "Sunday" = (== 666) . abs
gafiatulin/codewars
src/7 kyu/Fear.hs
mit
406
0
6
75
107
63
44
9
1
module Handler.AnalogWrite where import Global import Import import System.Hardware.Arduino getAnalogWriteR :: Word8 -> Int -> Handler Value getAnalogWriteR p v = do putMVar gArduinoIO analog_write _ <- takeMVar gArduinoRes return $ toJSON () where analog_write = analogWrite (digital p) v
aufheben/lambda-arduino
Handler/AnalogWrite.hs
mit
302
0
9
52
92
46
46
10
1
module Main where import Control.Concurrent (threadDelay) import Control.Monad (unless) import Data.Semigroup ((<>)) import System.IO (hFlush, stdout) import Game.Core (mutate, difference) import Game.IO (printC, printD, prepareScreen) import Game.Read (readSeedContent) import Options.Applicative main :: IO () main = initialize =<< execParser options initialize :: Args -> IO () initialize (Args seedFile interval singleRun) = do (area, cells) <- readSeedContent <$> readFile seedFile prepareScreen printC area cells unless singleRun $ loop area cells where loop area cells = do hFlush stdout threadDelay $ interval * 1000 let nextCells = mutate area cells printD area $ difference cells nextCells loop area nextCells data Args = Args { seedFile :: String, interval :: Int, singleRun :: Bool } parser :: Parser Args parser = Args <$> argument str ( metavar "FILE" <> help "The seed" ) <*> option auto ( short 'i' <> long "interval" <> metavar "INT" <> help "Interval of iterations in milliseconds" <> showDefault <> value 20 ) <*> switch ( long "single-run" ) options :: ParserInfo Args options = info (parser <**> helper) $ fullDesc <> header "Conway's Game of Life"
airt/game-of-life
app/Main.hs
mit
1,272
0
14
282
415
211
204
44
1
{-# LANGUAGE DeriveGeneric #-} module MarketData where import Control.Monad import Data.Aeson import Data.Time import GHC.Generics (Generic) import Data.Time.Clock.POSIX newtype EpochTime = EpochTime {time :: UTCTime} deriving (Show,Eq) instance FromJSON EpochTime where parseJSON (Number v) = return $ EpochTime $ (posixSecondsToUTCTime . fromIntegral) (floor v :: Integer) parseJSON _ = mzero data Market = Market {volume :: Maybe Double ,latest_trade :: EpochTime ,bid :: Maybe Double ,ask :: Maybe Double ,high :: Maybe Double ,low :: Maybe Double ,close :: Maybe Double ,avg :: Maybe Double ,currency :: String ,currency_volume :: Maybe Double ,symbol :: String} deriving (Show,Eq,Generic) instance FromJSON Market
krisajenkins/BellRinger
src/MarketData.hs
epl-1.0
840
0
9
220
239
136
103
30
0
module Util ( palindrome, runLength, none, splitOn, takeWhileInclude, removeCharacters, maxPathSum, runningTotal, removeDuplicates, digits, digitList, digitsToInt, partitionBy, everyNth, rotateInteger, enumerateListRotations, enumerateIntegralRotations, decimalToBinary, concatInts, isPandigital, isPandigital10, truncateRight, truncateLeft, isqrt, sortedListDiff, iterativelyTake, reverseIntegral, withinRange, asList, ) where import Data.Set (toList, fromList) import Data.List (delete, sort, tails, splitAt) import Data.Char (digitToInt) splitOn :: Eq a => a -> [a] -> [[a]] splitOn delim s = splitHelper delim s [] splitHelper :: Eq a => a -> [a] -> [[a]] -> [[a]] splitHelper _ [] result = reverse result splitHelper delim s result = let condition x = x /= delim (l, r) = span condition s r' = if r == [] then [] else tail r in splitHelper delim r' $ l:result everyNth :: Int -> [a] -> [a] everyNth _ [] = [] everyNth n (x:xs) = x:everyNth n remaining where remaining = drop (n-1) xs partitionBy :: [Int] -> [a] -> [[a]] partitionBy _ [] = [] partitionBy [] xs = [xs] partitionBy (size:sizes) xs = grouped:partitionBy sizes remaining where (grouped, remaining) = splitAt size xs digits :: Integral a => a -> Int digits = length.show.toInteger digitList :: Integral a => a -> [a] digitList = (map (fromIntegral.digitToInt)).show.toInteger digitsToInt :: Integral a => [a] -> a digitsToInt digs = sum $ zipWith (*) exps $ reverse digs where exps = iterate (*10) 1 reverseIntegral :: Integral a => a -> a reverseIntegral = digitsToInt.reverse.digitList rotateInteger :: Integral a => a -> a rotateInteger n = r * 10 ^ (d-1) + q where d = (toInteger.digits) n (q, r) = n `divMod` 10 enumerateIntegralRotations :: Integral a => a -> [a] enumerateIntegralRotations n = take d $ iterate rotateInteger n where d = digits n enumerateListRotations :: [a] -> [[a]] enumerateListRotations xs = map (recombineAt xs) [0..n-1] where recombineAt ys i = r ++ l where (l, r) = splitAt i ys n = length xs none :: (a -> Bool) -> [a] -> Bool none fn = not.(any fn) decimalToBinary :: Integral a => a -> String decimalToBinary n = map (\x-> if x then '1' else '0') bits where powers = reverse $ takeWhile (<=n) $ iterate (*2) 1 folder (s, results) x = if x <= s then (s-x, True:results) else (s, False:results) bits = reverse $ snd $ foldl folder (n,[]) powers palindrome :: Eq a => [a] -> Bool palindrome s = s == reverse s runLength :: (Eq a) => [a] -> [(a,Int)] runLength [] = [] runLength (x:xs) = let (match, remaining) = span (== x) xs count = length match + 1 in (x, count) : runLength remaining takeWhileInclude :: (a -> Bool) -> [a] -> [a] takeWhileInclude fn [] = [] takeWhileInclude fn (x:items) = if fn x then x:takeWhileInclude fn items else [x] removeCharacters :: String -> String -> String removeCharacters values str = filter (\c -> not (c `elem` values)) str maxPathSum :: [[Int]] -> Int maxPathSum (x:xs) = let combine acc curr = zipWith (+) curr $ zipWith max acc (tail acc) in head $ foldl combine x xs runningTotal :: Num a => [a] -> [a] runningTotal = scanl1 (+) removeDuplicates :: Ord a => [a] -> [a] removeDuplicates = toList.fromList isPandigital :: Int -> Bool isPandigital n = n <= 987654321 && d == [1..digs] where d = sort $ digitList n digs = digits n isPandigital10 :: Int -> Bool isPandigital10 n = n >= 123456789 && n <= 987654321 && d == [1..9] where d = sort $ digitList n concatInts :: Integral a => [a] -> a concatInts ns = sum parts where parts = zipWith (*) ns offsets offsets = zipWith (^) (repeat 10) $ reverse $ 0:(init exps) exps = runningTotal $ reverse $ map digits ns truncateRight :: Integer -> Integer truncateRight n = n `div` 10 truncateLeft :: Integer -> Integer truncateLeft n = n - delta where delta = n `div` d * d d = 10^(digits n - 1) isqrt :: Integral a => a -> a isqrt = floor.sqrt.fromIntegral sortedListDiff :: Ord a => [a] -> [a] -> [a] sortedListDiff xs [] = xs sortedListDiff [] ys = ys sortedListDiff (x:xs) (y:ys) = if x == y then sortedListDiff xs ys else if x < y then x:sortedListDiff xs (y:ys) else y:sortedListDiff (x:xs) ys iterativelyTake :: Int -> [a] -> [[a]] iterativelyTake n xs = map (take n) (tails xs) withinRange :: Ord a => a -> a -> [a] -> [a] withinRange low high values = taken where dropped = dropWhile (<low) values taken = takeWhile (<=high) dropped asList :: a -> [a] asList a = [a]
liefswanson/projectEuler
src/Util.hs
gpl-2.0
5,039
1
12
1,455
2,075
1,117
958
146
3
{-# LANGUAGE LambdaCase #-} module Spiteful.Reddit where import Control.Concurrent (threadDelay) import Control.Monad (forM, forM_) import Control.Monad.IO.Class import Data.Either.Combinators (mapLeft) import qualified Data.HashMap.Strict as HM import Data.List.Split (chunksOf) import Data.Maybe (fromMaybe, isJust, isNothing, mapMaybe) import Data.Monoid ((<>)) import qualified Network.HTTP.Client.TLS as TLS import Pipes import Reddit hiding (Options, runReddit, upvotePost) import qualified Reddit as R import Reddit.Types.Comment import Reddit.Types.Listing import Reddit.Types.Post (Post(..), PostID) import Spiteful.Logging import Spiteful.Options import Spiteful.Util type EitherR = Either (APIError RedditError) -- Posts type PostProducer m = Producer Post m (EitherR ()) fetchPosts :: MonadIO m => Options -> PostProducer m fetchPosts opts@Options{..} = do logAt Debug $ "Fetching " <> tshow listingType <> " posts from " <> maybe "the entire Reddit" (("subreddit: " <>) . tshow) optSubreddit doFetch opts Nothing where listingType = fromMaybe New optListing doFetch :: MonadIO m => Options -> Maybe PostID -> PostProducer m doFetch opts after = do result <- runReddit opts $ do let fOpts = newFetchOptions opts after Listing _ after' posts <- getPosts' fOpts listingType optSubreddit logFmt Debug "Received {} posts from the {} feed (after = {})" (length posts, tshow listingType, tshow after) return (posts, after') case result of Left err -> return $ Left err Right (posts, after') -> do mapM_ yield posts let isEmpty = null posts && isNothing after -- not after' if isEmpty then return $ Right () else do -- Sleep for 1 second, as per Reddit API recommendation, -- or for longer if we exhausted the listing -- (as it likely means starting from the beginning of it, -- i.e. completely new posts) delaySecs <- case after' of Just _ -> do logAt Trace "Sleeping shortly before continuing with fetch" return 1 Nothing -> do logFmt Debug "Exhausted the {} listing, starting over in {} seconds" (tshow listingType, restartDelaySecs) return restartDelaySecs liftIO $ threadDelay (delaySecs * 1000000) doFetch opts after' where -- | How long to wait when we've exhausted the listing before -- retrying the fetch anew from the beginning. restartDelaySecs = case listingType of New -> 5 Hot -> 60 Rising -> 30 Controversial -> 60 Top -> 5 * 60 -- /top shouldn't really change a lot data Voting = Upvote | Downvote deriving (Bounded, Enum, Eq, Show) voteOnPost :: MonadIO m => Options -> Voting -> Post -> m (EitherR ()) voteOnPost opts voting Post{..} = do let PostID pid = postID R subr = subreddit case optCredentials opts of Nothing -> do logFmt Warn "Cannot vote on post #{} (\"{}\" in /r/{}) due to lack of credentials" (pid, title, subr) return $ Left $ APIError CredentialsError _ -> do logFmt Info "Voting on post #{} (\"{}\" in /r/{}) [{}] -> [{}]" (pid, title, subr, score, newScore) result <- runReddit opts $ doVote postID case result of Left err -> logFmt Warn "Failed to vote on post #{}: {}" (pid, tshow err) Right _ -> logFmt Debug "Successfully voted on post #{} in /r/{}" (pid, subr) return result where newScore = case voting of Upvote -> score + 1 Downvote -> score - 1 doVote = case voting of Upvote -> R.upvotePost Downvote -> R.downvotePost upvotePost :: MonadIO m => Options -> Post -> m (EitherR ()) upvotePost opts = voteOnPost opts Upvote downvotePost :: MonadIO m => Options -> Post -> m (EitherR ()) downvotePost opts = voteOnPost opts Downvote -- Comments type CommentProducer m = Producer Comment m (EitherR ()) fetchNewComments :: MonadIO m => Options -> CommentProducer m fetchNewComments opts@Options{..} = do -- Only authenticated users can watch the stream of all new Reddit comments if isNothing optCredentials && isJust optSubreddit then do logAt Warn "Cannot fetch /comments from the entire Reddit unless logged in" return $ Left (APIError CredentialsError) else do logAt Debug $ "Fetching new comments from " <> maybe "the entire Reddit" (("subreddit: " <>) . tshow) optSubreddit doFetch opts Nothing where doFetch :: MonadIO m => Options -> Maybe CommentID -> CommentProducer m doFetch opts after = do result <- runReddit opts $ do let fetchOpts = newFetchOptions opts after Listing _ after' comments <- getNewComments' fetchOpts optSubreddit logFmt Debug "Received {} new comments (after = {})" (length comments, tshow after) return (comments, after') case result of Left err -> return $ Left err Right (comments, after') -> do mapM_ yield comments let isEmpty = null comments && isNothing after -- not after' if isEmpty then return $ Right () else do -- Sleep for 1 second, as per Reddit API recommendation, -- or for longer if we exhausted the listing -- (as it likely means starting from the beginning of it, -- i.e. completely new posts) delaySecs <- case after' of Just _ -> do logAt Trace "Sleeping for a second before continuing with fetch" return 1 Nothing -> do logAt Debug $ "Exhausted the comment listing, starting over in " <> tshow restartDelaySecs <> " seconds" return restartDelaySecs liftIO $ threadDelay (delaySecs * 1000000) doFetch opts after' restartDelaySecs = 5 fetchCommentReplies :: MonadIO m => Options -> Comment -> CommentProducer m fetchCommentReplies opts Comment{..} = do let Listing _ after commentRefs = replies if null commentRefs && isNothing after then return $ Right () else do logFmt Trace "Looking up replies to comment #{} from /r/{}" (cid, subr) -- TODO: follow the possible "after" in the Listing below; -- it's not very necessary for the purpose this whole function is used yet let Listing _ _ commentReplies = replies resolveCommentRefs opts commentReplies where CommentID cid = commentID R subr = subreddit resolveCommentRefs :: MonadIO m => Options -> [CommentReference] -> CommentProducer m resolveCommentRefs opts commentRefs = do -- CommentReference may hide multiple unresolved CommentIDs; -- gather them all in a single list let justSingularRefs = concatMap treeSubComments commentRefs unresolved = [ cid | Reference _ [CommentID cid] <- justSingularRefs ] -- Resolve those references, getting a HashMap from IDs to Comments result <- runReddit opts $ do let chunked = chunksOf singleCommentGetLimit unresolved resolved <- (concat <$>) . forM chunked $ \cids -> do -- TODO: handle the possible (but unlikely) `after` in the response Listing _ _ comments <- getCommentsInfo (map CommentID cids) return comments return $ HM.fromList (zip unresolved resolved) -- Use it to translate all CommentReferences to Comments case result of Left err -> return $ Left err Right refMap -> do let resolveRef = \case Actual c -> Just c Reference _ [CommentID cid] -> HM.lookup cid refMap _ -> Nothing forM_ (mapMaybe resolveRef justSingularRefs) $ yield return $ Right () where singleCommentGetLimit = 100 -- enforced by Reddit API upvoteComment :: MonadIO m => Options -> Comment -> m (EitherR ()) upvoteComment opts Comment{..} = do let CommentID cid = commentID R subr = subreddit case optCredentials opts of Nothing -> do logFmt Warn "Cannot upvote comment #{} in /r/{} due to lack of credentials" (cid, subr) return $ Left $ APIError CredentialsError _ -> do logFmt Info "Upvoting comment #{} in /r/{} [{}] -> [{}]" (cid, subr, showScore score, showScore $ (+1) <$> score) result <- runReddit opts $ R.upvoteComment commentID case result of Left err -> logFmt Warn "Failed to upvote comment #{}: {}" (cid, tshow err) Right _ -> logFmt Debug "Successfully upvoted comment #{} in /r/{}" (cid, subr) return result where -- Current score may be absent in the Comment record showScore = fromMaybe "?" . (tshow <$>) -- Utilities -- | Run a RedditT action using program Options. runReddit :: MonadIO m => Options -> RedditT m a -> m (EitherR a) runReddit opts action = do -- Reuse HTTP connection manager between Reddit calls. httpManager <- liftIO TLS.getGlobalManager let rOpts = (toRedditOptions opts) { connectionManager = Just httpManager } -- Optionally stub out Reddit API base URL. let withRedditURL = maybe id withBaseURL $ optBaseURL opts (mapLeft fst <$>) . runResumeRedditWith rOpts $ withRedditURL action newFetchOptions :: Options -> Maybe a -> R.Options a newFetchOptions Options{..} after = R.Options { pagination = After <$> after, limit = optBatchSize }
Xion/spiteful
src/Spiteful/Reddit.hs
gpl-2.0
9,557
0
26
2,629
2,428
1,194
1,234
-1
-1
module Main ( main ) where import Sivi import Linear hiding (rotate) import ScrewHoles corner = V3 (-40) 5 0 probeCorner = translate corner $ probeInnerCornerNE 5 (ProbeTool 3 42) bearing = chain 1 [ circularPocket 14 2.5 0.5 , withTool (EndMill 2 42) $ probeZMinus (V3 15 0 0) 5 >> cylinderInner 20 4 , probeZMinus (V3 15 0 0) 5 , translate (V3 0 0 (-2.5)) $ circularPocket 6.5 (11-2.5) 0.5 ] makeProbePocket = translate (V3 (-45) 0 0) $ rectangularPocket 10 10 (10+0.5) 0.5 makeAlignmentPocket = translate (V3 45 0 0) $ rectangularPocket 10 10 (10+0.5) 0.5 back = chain 1 [ message "Place the tool above the location of the bearing and start the spindle" , makeProbePocket , makeAlignmentPocket , message "Stop the spindle" , translate corner $ probeInnerCornerNE 5 (ProbeTool 3 42) , message "Start the spindle" , bearing ] front1 = chain 1 [ probeCorner , bearing , screwHoles , translate (V3 28.6 9 0) $ drill (10+0.5) 1 , translate (V3 (-28.6) 9 0) $ drill (10+0.5) 1 , zRepetition 10.5 (Just 1) (const $ contour [V2 (-35) 22.75, V2 (-35) (-14.5), V2 35 (-14.5), V2 35 22.75] RightSide False) ] front2 = chain 1 [ probeCorner , translate (V3 19.8 54.2 0) $ drill (10+0.5) 1 , translate (V3 (-19.8) 54.2 0) $ drill (10+0.5) 1 , zRepetition 10.5 (Just 1) (const $ contour [V2 35 22.75, V2 24.38 62.9, V2 (-24.38) 62.9, V2 (-35) 22.75] RightSide False) ] zPlate = chain 1 [ message "Begin with the back side of the plate" , back , message "Place the front side face up, centered on the lower area of the part" , front1 , message "Place the part to machine the upper area of the front side" , pause , front2 ] main :: IO () main = putStr . (++"M2\n") . show . getGCode defaultCuttingParameters $ zPlate --main = interface . getGCode defaultCuttingParameters $ zPlate
iemxblog/sivi-haskell
examples/z_plate.hs
gpl-2.0
2,221
0
14
776
729
379
350
44
1
module FormalMethods.Terms where import Notes hiding (constant) makeDefs [ "signature" , "arity" , "constant" , "variable" , "term algebra" , "term" , "equation" , "rule" , "equational theory" , "equational derivation" , "free term algebra" , "free equational theory" , "quotient term algebra" , "substitution" , "position" , "subterm" , "matches" , "matching substitution" , "applicable" , "application" , "unifiable" , "unifier" , "unify" , "equality step" , "equality relation" , "equality proof" , "infinite computations" , "termination" , "terminating" , "confluence" , "confluent" ] eequalityStep :: Note -> Note eequalityStep e = m e <> "-" <> equalityStep eequalityRelation :: Note -> Note eequalityRelation e = m e <> "-" <> equalityRelation
NorfairKing/the-notes
src/FormalMethods/Terms.hs
gpl-2.0
893
0
7
255
170
102
68
-1
-1
-- This file is part of seismic_repa_3.1. -- -- seismic_repa_3.1 is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- seismic_repa_3.1 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 seismic_repa_3.1. If not, see <http://www.gnu.org/licenses/>. -- Implementation of the forward wave propagation {-# LANGUAGE PackageImports, BangPatterns, QuasiQuotes, PatternGuards, TemplateHaskell #-} {-# OPTIONS -Wall -fno-warn-missing-signatures -fno-warn-incomplete-patterns #-} module Seismic where import Data.Array.Repa as R import Data.Array.Repa.Eval import Data.Array.Repa.Stencil import Data.Array.Repa.Stencil.Dim2 import qualified Data.Vector.Unboxed as V -- record type to hold the matrices data SeismicData = SeismicData {ppf :: !(Array U DIM2 Float), apf :: !(Array U DIM2 Float), vel :: !(Array U DIM2 Float) } -- some constants fc = 125.0 v = 2000.0 dt = h/(5.0*2000.0) h = 2000.0/(9.0*fc) fat = (dt*dt)/(h*h*12.0) tf = (2.0 * sqrt pi) / fc a = sqrt 0.5 * pi * fc -- produces correct values genMatrices :: Int -> Int -> SeismicData genMatrices _ 0 = undefined genMatrices 0 _ = undefined genMatrices x y = SeismicData {ppf = ppff, apf = apff, vel = vell} where ppff = fromList (Z :. (x::Int) :. (y::Int)) [0 | _ <- [0..x*y-1]] apff = fromList (Z :. (x::Int) :. (y::Int)) [0 | _ <- [0..x*y-1]] vell = fromList (Z :. (x::Int) :. (y::Int)) [v*v*fat | _ <- [0..x*y-1]] -- values are correct -- produces correct values genSeismicPulseVector :: Int -> Array U DIM1 Float genSeismicPulseVector 0 = undefined genSeismicPulseVector t = pulseVector where pulseVector = fromList (Z :. (t::Int)) [ pulse $ (tt*dt) -tf | tt <- [0.0..fromIntegral(t-1)]] pulse ts = (1.0 - 2.0 * ts * a * ts * a) * exp (-ts * a * ts * a) -- loop n times doNTimes :: SeismicData -> Array U DIM1 Float -> Int -> Int -> Array U DIM2 Float doNTimes !sd !pv !t !ctr | ctr == t = apf sd | otherwise = doNTimes (seismic (ppf sd) apfw (vel sd) ) pv t $ ctr+1 where {-# INLINE apfw #-} apfw = addPulse (apf sd) $ pv `R.unsafeIndex` (Z:. ctr) {-# INLINE addPulse #-} addPulse apff pulse = fromUnboxed (Z:. ySize :. xSize) ((toUnboxed apff) `V.unsafeUpd` [(posV, val (toUnboxed apff) + pulse)]) ex = extent $ apf sd ySize = (head $ listOfShape ex) xSize = (last $ listOfShape ex) posV = (ySize * (ySize `div` 2)) + (xSize `div` 2) -- index is correct val axs = axs `V.unsafeIndex` posV -- extract the value of apf at posV -- the real calculation seismic :: Array U DIM2 Float -> Array U DIM2 Float -> Array U DIM2 Float -> SeismicData seismic !cppf !capf !cvel = SeismicData {ppf = capf, apf = npf, vel = cvel} where {-# INLINE stencil #-} stencil = mapStencil2 (BoundConst 0.0) [stencil2| 0 0 -1 0 0 0 0 16 0 0 -1 16 -60 16 -1 0 0 16 0 0 0 0 -1 0 0 |] capf {-# INLINE npf #-} npf = capf `deepSeqArray` suspendedComputeP $ R.czipWith (-) (R.cmap (*2) capf) $ R.czipWith (-) cppf $ R.czipWith (*) cvel stencil
agremm/Seismic
repa_3/Seismic.hs
gpl-3.0
3,823
0
15
1,087
1,101
612
489
56
1
{-# LANGUAGE NoImplicitPrelude #-} module Vector where import Prelude(Show) import Base import Functional class LikeVector v where map :: (a -> b) -> v a -> v b zip :: (a -> b -> c) -> v a -> v b -> v c fold :: (a -> a -> a) -> v a -> a class LikeNumber a where (+) :: a -> a -> a (*) :: a -> a -> a instance LikeNumber Int where (+) = sumInt (*) = mulInt instance LikeNumber Float where (+) = sumFloat (*) = mulFloat instance LikeNumber Double where (+) = sumDouble (*) = mulDouble data LikeVector2D a = LikeVector2D { vx2D :: a, vy2D :: a } deriving Show instance LikeVector LikeVector2D where map = map2D zip = zip2D fold = fold2D map2D :: (a -> b) -> LikeVector2D a -> LikeVector2D b -- map2D = join . ((. vy2D) .) . (. vx2D) . (LikeVector2D `on`) -- map2D f = (vy2D `at`) . (vx2D `at`) . (on LikeVector2D) . ((f .) . at) map2D = (((at vy2D) . (at vx2D) . (on LikeVector2D)) .) . (((. at) . (.))) -- map2D f v = (LikeVector2D `on` f) (vx v) (vy v) zip2D :: (a -> b -> c) -> LikeVector2D a -> LikeVector2D b -> LikeVector2D c -- zip2D f (LikeVector2D x y) (LikeVector2D x' y') = LikeVector2D (f x x') $ f y y' -- zip2D f v v' = LikeVector2D (f (vx2D v) (vx2D v')) (f (vy2D v) (vy2D v')) zip2D f = join . (join $ (. (LikeVector2D .) . (. vx2D) . f . vx2D) . (.) . (flip (.)) . (. vy2D) . (f . vy2D)) fold2D :: (a -> a -> a) -> LikeVector2D a -> a -- fold2D f (LikeVector2D y) = f x y -- fold2D f v = ((. vy2D) . (f . vx2D)) v v -- fold2D = join . (((. vy2D) .) . (. vx2D)) -- fold2D f v = f (vx2D v) (vy2D v) fold2D f = (((vy2D `at`) . (vx2D `at`)) . (on f) . at) data LikeVector3D a = LikeVector3D { vx3D :: a, vy3D :: a, vz3D :: a } deriving Show instance LikeVector LikeVector3D where map = map3D zip = zip3D fold = foldr3D map3D :: (a -> b) -> LikeVector3D a -> LikeVector3D b map3D f (LikeVector3D x y z) = f z `at` (LikeVector3D `on` f) x y zip3D :: (a -> b -> c) -> LikeVector3D a -> LikeVector3D b -> LikeVector3D c zip3D f (LikeVector3D x y z) (LikeVector3D x' y' z') = LikeVector3D (f x x') (f y y') (f z z') foldr3D :: (a -> a -> a) -> LikeVector3D a -> a -- foldr3D f (LikeVector3D x y z) = f x $ f y z foldr3D f v = ((f . vx3D) v) $ ((. vz3D) . f . vy3D) v v foldl3D :: (a -> a -> a) -> LikeVector3D a -> a foldl3D f (LikeVector3D x y z) = f x y `f` z -- foldl3D f v = f (f (vx3D v) (vy3D v)) (vz3D z) innerProduct :: (LikeVector v, LikeNumber a) => v a -> v a -> a innerProduct = fold (+) $$ zip (*) -- innerProduct = ((fold (+)) .) . (zip (*))
zakharvoit/haskell-homework
Vector.hs
gpl-3.0
2,667
0
16
760
963
535
428
54
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.OpsWorks.UpdateInstance -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Updates a specified instance. -- -- Required Permissions: To use this action, an IAM user must have a Manage -- permissions level for the stack, or an attached policy that explicitly grants -- permissions. For more information on user permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing UserPermissions>. -- -- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_UpdateInstance.html> module Network.AWS.OpsWorks.UpdateInstance ( -- * Request UpdateInstance -- ** Request constructor , updateInstance -- ** Request lenses , uiAmiId , uiArchitecture , uiAutoScalingType , uiEbsOptimized , uiHostname , uiInstallUpdatesOnBoot , uiInstanceId , uiInstanceType , uiLayerIds , uiOs , uiSshKeyName -- * Response , UpdateInstanceResponse -- ** Response constructor , updateInstanceResponse ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.OpsWorks.Types import qualified GHC.Exts data UpdateInstance = UpdateInstance { _uiAmiId :: Maybe Text , _uiArchitecture :: Maybe Architecture , _uiAutoScalingType :: Maybe AutoScalingType , _uiEbsOptimized :: Maybe Bool , _uiHostname :: Maybe Text , _uiInstallUpdatesOnBoot :: Maybe Bool , _uiInstanceId :: Text , _uiInstanceType :: Maybe Text , _uiLayerIds :: List "LayerIds" Text , _uiOs :: Maybe Text , _uiSshKeyName :: Maybe Text } deriving (Eq, Read, Show) -- | 'UpdateInstance' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'uiAmiId' @::@ 'Maybe' 'Text' -- -- * 'uiArchitecture' @::@ 'Maybe' 'Architecture' -- -- * 'uiAutoScalingType' @::@ 'Maybe' 'AutoScalingType' -- -- * 'uiEbsOptimized' @::@ 'Maybe' 'Bool' -- -- * 'uiHostname' @::@ 'Maybe' 'Text' -- -- * 'uiInstallUpdatesOnBoot' @::@ 'Maybe' 'Bool' -- -- * 'uiInstanceId' @::@ 'Text' -- -- * 'uiInstanceType' @::@ 'Maybe' 'Text' -- -- * 'uiLayerIds' @::@ ['Text'] -- -- * 'uiOs' @::@ 'Maybe' 'Text' -- -- * 'uiSshKeyName' @::@ 'Maybe' 'Text' -- updateInstance :: Text -- ^ 'uiInstanceId' -> UpdateInstance updateInstance p1 = UpdateInstance { _uiInstanceId = p1 , _uiLayerIds = mempty , _uiInstanceType = Nothing , _uiAutoScalingType = Nothing , _uiHostname = Nothing , _uiOs = Nothing , _uiAmiId = Nothing , _uiSshKeyName = Nothing , _uiArchitecture = Nothing , _uiInstallUpdatesOnBoot = Nothing , _uiEbsOptimized = Nothing } -- | A custom AMI ID to be used to create the instance. The AMI should be based on -- one of the standard AWS OpsWorks AMIs: Amazon Linux, Ubuntu 12.04 LTS, or -- Ubuntu 14.04 LTS. For more information, see <http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances.html Instances> -- -- If you specify a custom AMI, you must set 'Os' to 'Custom'. uiAmiId :: Lens' UpdateInstance (Maybe Text) uiAmiId = lens _uiAmiId (\s a -> s { _uiAmiId = a }) -- | The instance architecture. Instance types do not necessarily support both -- architectures. For a list of the architectures that are supported by the -- different instance types, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html Instance Families and Types>. uiArchitecture :: Lens' UpdateInstance (Maybe Architecture) uiArchitecture = lens _uiArchitecture (\s a -> s { _uiArchitecture = a }) -- | For load-based or time-based instances, the type. uiAutoScalingType :: Lens' UpdateInstance (Maybe AutoScalingType) uiAutoScalingType = lens _uiAutoScalingType (\s a -> s { _uiAutoScalingType = a }) -- | Whether this is an Amazon EBS-optimized instance. uiEbsOptimized :: Lens' UpdateInstance (Maybe Bool) uiEbsOptimized = lens _uiEbsOptimized (\s a -> s { _uiEbsOptimized = a }) -- | The instance host name. uiHostname :: Lens' UpdateInstance (Maybe Text) uiHostname = lens _uiHostname (\s a -> s { _uiHostname = a }) -- | Whether to install operating system and package updates when the instance -- boots. The default value is 'true'. To control when updates are installed, set -- this value to 'false'. You must then update your instances manually by using 'CreateDeployment' to run the 'update_dependencies' stack command or manually running 'yum' (Amazon -- Linux) or 'apt-get' (Ubuntu) on the instances. -- -- We strongly recommend using the default value of 'true', to ensure that your -- instances have the latest security updates. -- -- uiInstallUpdatesOnBoot :: Lens' UpdateInstance (Maybe Bool) uiInstallUpdatesOnBoot = lens _uiInstallUpdatesOnBoot (\s a -> s { _uiInstallUpdatesOnBoot = a }) -- | The instance ID. uiInstanceId :: Lens' UpdateInstance Text uiInstanceId = lens _uiInstanceId (\s a -> s { _uiInstanceId = a }) -- | The instance type. AWS OpsWorks supports all instance types except Cluster -- Compute, Cluster GPU, and High Memory Cluster. For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html Instance Families and Types>. The parameter values that you use to specify the various types are in the -- API Name column of the Available Instance Types table. uiInstanceType :: Lens' UpdateInstance (Maybe Text) uiInstanceType = lens _uiInstanceType (\s a -> s { _uiInstanceType = a }) -- | The instance's layer IDs. uiLayerIds :: Lens' UpdateInstance [Text] uiLayerIds = lens _uiLayerIds (\s a -> s { _uiLayerIds = a }) . _List -- | The instance's operating system, which must be set to one of the following. -- -- Standard operating systems: An Amazon Linux version such as 'Amazon Linux2014.09', 'Ubuntu 12.04 LTS', or 'Ubuntu 14.04 LTS'. Custom AMIs: 'Custom' The -- default option is the current Amazon Linux version, such as 'Amazon Linux2014.09'. If you set this parameter to 'Custom', you must use the 'CreateInstance' -- action's AmiId parameter to specify the custom AMI that you want to use. For -- more information on the standard operating systems, see <http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html Operating Systems>For -- more information on how to use custom AMIs with OpsWorks, see <http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-custom-ami.html Using CustomAMIs>. uiOs :: Lens' UpdateInstance (Maybe Text) uiOs = lens _uiOs (\s a -> s { _uiOs = a }) -- | The instance SSH key name. uiSshKeyName :: Lens' UpdateInstance (Maybe Text) uiSshKeyName = lens _uiSshKeyName (\s a -> s { _uiSshKeyName = a }) data UpdateInstanceResponse = UpdateInstanceResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'UpdateInstanceResponse' constructor. updateInstanceResponse :: UpdateInstanceResponse updateInstanceResponse = UpdateInstanceResponse instance ToPath UpdateInstance where toPath = const "/" instance ToQuery UpdateInstance where toQuery = const mempty instance ToHeaders UpdateInstance instance ToJSON UpdateInstance where toJSON UpdateInstance{..} = object [ "InstanceId" .= _uiInstanceId , "LayerIds" .= _uiLayerIds , "InstanceType" .= _uiInstanceType , "AutoScalingType" .= _uiAutoScalingType , "Hostname" .= _uiHostname , "Os" .= _uiOs , "AmiId" .= _uiAmiId , "SshKeyName" .= _uiSshKeyName , "Architecture" .= _uiArchitecture , "InstallUpdatesOnBoot" .= _uiInstallUpdatesOnBoot , "EbsOptimized" .= _uiEbsOptimized ] instance AWSRequest UpdateInstance where type Sv UpdateInstance = OpsWorks type Rs UpdateInstance = UpdateInstanceResponse request = post "UpdateInstance" response = nullResponse UpdateInstanceResponse
dysinger/amazonka
amazonka-opsworks/gen/Network/AWS/OpsWorks/UpdateInstance.hs
mpl-2.0
9,029
0
10
1,989
1,084
652
432
109
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Language.Types -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.Language.Types ( -- * Service Configuration languageService -- * OAuth Scopes , cloudPlatformScope -- * AnalyzeSyntaxRequest , AnalyzeSyntaxRequest , analyzeSyntaxRequest , asrEncodingType , asrDocument -- * DependencyEdge , DependencyEdge , dependencyEdge , deHeadTokenIndex , deLabel -- * Status , Status , status , sDetails , sCode , sMessage -- * PartOfSpeechProper , PartOfSpeechProper (..) -- * PartOfSpeechTag , PartOfSpeechTag (..) -- * Sentiment , Sentiment , sentiment , sScore , sMagnitude -- * DocumentType , DocumentType (..) -- * AnalyzeSyntaxRequestEncodingType , AnalyzeSyntaxRequestEncodingType (..) -- * DependencyEdgeLabel , DependencyEdgeLabel (..) -- * PartOfSpeechVoice , PartOfSpeechVoice (..) -- * PartOfSpeechForm , PartOfSpeechForm (..) -- * PartOfSpeechPerson , PartOfSpeechPerson (..) -- * Token , Token , token , tDependencyEdge , tText , tLemma , tPartOfSpeech -- * EntityType , EntityType (..) -- * StatusDetailsItem , StatusDetailsItem , statusDetailsItem , sdiAddtional -- * AnnotateTextRequest , AnnotateTextRequest , annotateTextRequest , atrEncodingType , atrFeatures , atrDocument -- * EntityMention , EntityMention , entityMention , emText , emType -- * TextSpan , TextSpan , textSpan , tsBeginOffSet , tsContent -- * AnnotateTextResponse , AnnotateTextResponse , annotateTextResponse , atrEntities , atrTokens , atrDocumentSentiment , atrSentences , atrLanguage -- * PartOfSpeechTense , PartOfSpeechTense (..) -- * Features , Features , features , fExtractSyntax , fExtractDocumentSentiment , fExtractEntities -- * Document , Document , document , dContent , dLanguage , dGcsContentURI , dType -- * PartOfSpeechMood , PartOfSpeechMood (..) -- * PartOfSpeechCase , PartOfSpeechCase (..) -- * AnalyzeSentimentRequest , AnalyzeSentimentRequest , analyzeSentimentRequest , aEncodingType , aDocument -- * Xgafv , Xgafv (..) -- * AnalyzeEntitiesResponse , AnalyzeEntitiesResponse , analyzeEntitiesResponse , aerEntities , aerLanguage -- * AnnotateTextRequestEncodingType , AnnotateTextRequestEncodingType (..) -- * PartOfSpeechNumber , PartOfSpeechNumber (..) -- * AnalyzeSentimentResponse , AnalyzeSentimentResponse , analyzeSentimentResponse , asrDocumentSentiment , asrSentences , asrLanguage -- * AnalyzeEntitiesRequest , AnalyzeEntitiesRequest , analyzeEntitiesRequest , aerEncodingType , aerDocument -- * AnalyzeEntitiesRequestEncodingType , AnalyzeEntitiesRequestEncodingType (..) -- * Entity , Entity , entity , eName , eSalience , eMetadata , eType , eMentions -- * AnalyzeSyntaxResponse , AnalyzeSyntaxResponse , analyzeSyntaxResponse , aTokens , aSentences , aLanguage -- * EntityMetadata , EntityMetadata , entityMetadata , emAddtional -- * PartOfSpeechAspect , PartOfSpeechAspect (..) -- * PartOfSpeech , PartOfSpeech , partOfSpeech , posProper , posTag , posPerson , posAspect , posCase , posGender , posReciprocity , posNumber , posVoice , posForm , posTense , posMood -- * PartOfSpeechReciprocity , PartOfSpeechReciprocity (..) -- * PartOfSpeechGender , PartOfSpeechGender (..) -- * AnalyzeSentimentRequestEncodingType , AnalyzeSentimentRequestEncodingType (..) -- * EntityMentionType , EntityMentionType (..) -- * Sentence , Sentence , sentence , sSentiment , sText ) where import Network.Google.Language.Types.Product import Network.Google.Language.Types.Sum import Network.Google.Prelude -- | Default request referring to version 'v1' of the Google Cloud Natural Language API. This contains the host and root path used as a starting point for constructing service requests. languageService :: ServiceConfig languageService = defaultService (ServiceId "language:v1") "language.googleapis.com" -- | View and manage your data across Google Cloud Platform services cloudPlatformScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform"] cloudPlatformScope = Proxy;
rueshyna/gogol
gogol-language/gen/Network/Google/Language/Types.hs
mpl-2.0
5,141
0
7
1,368
606
428
178
147
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AndroidEnterprise.Products.GetPermissions -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves the Android app permissions required by this app. -- -- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.products.getPermissions@. module Network.Google.Resource.AndroidEnterprise.Products.GetPermissions ( -- * REST Resource ProductsGetPermissionsResource -- * Creating a Request , productsGetPermissions , ProductsGetPermissions -- * Request Lenses , pgpXgafv , pgpUploadProtocol , pgpEnterpriseId , pgpAccessToken , pgpUploadType , pgpProductId , pgpCallback ) where import Network.Google.AndroidEnterprise.Types import Network.Google.Prelude -- | A resource alias for @androidenterprise.products.getPermissions@ method which the -- 'ProductsGetPermissions' request conforms to. type ProductsGetPermissionsResource = "androidenterprise" :> "v1" :> "enterprises" :> Capture "enterpriseId" Text :> "products" :> Capture "productId" Text :> "permissions" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ProductPermissions -- | Retrieves the Android app permissions required by this app. -- -- /See:/ 'productsGetPermissions' smart constructor. data ProductsGetPermissions = ProductsGetPermissions' { _pgpXgafv :: !(Maybe Xgafv) , _pgpUploadProtocol :: !(Maybe Text) , _pgpEnterpriseId :: !Text , _pgpAccessToken :: !(Maybe Text) , _pgpUploadType :: !(Maybe Text) , _pgpProductId :: !Text , _pgpCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProductsGetPermissions' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pgpXgafv' -- -- * 'pgpUploadProtocol' -- -- * 'pgpEnterpriseId' -- -- * 'pgpAccessToken' -- -- * 'pgpUploadType' -- -- * 'pgpProductId' -- -- * 'pgpCallback' productsGetPermissions :: Text -- ^ 'pgpEnterpriseId' -> Text -- ^ 'pgpProductId' -> ProductsGetPermissions productsGetPermissions pPgpEnterpriseId_ pPgpProductId_ = ProductsGetPermissions' { _pgpXgafv = Nothing , _pgpUploadProtocol = Nothing , _pgpEnterpriseId = pPgpEnterpriseId_ , _pgpAccessToken = Nothing , _pgpUploadType = Nothing , _pgpProductId = pPgpProductId_ , _pgpCallback = Nothing } -- | V1 error format. pgpXgafv :: Lens' ProductsGetPermissions (Maybe Xgafv) pgpXgafv = lens _pgpXgafv (\ s a -> s{_pgpXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pgpUploadProtocol :: Lens' ProductsGetPermissions (Maybe Text) pgpUploadProtocol = lens _pgpUploadProtocol (\ s a -> s{_pgpUploadProtocol = a}) -- | The ID of the enterprise. pgpEnterpriseId :: Lens' ProductsGetPermissions Text pgpEnterpriseId = lens _pgpEnterpriseId (\ s a -> s{_pgpEnterpriseId = a}) -- | OAuth access token. pgpAccessToken :: Lens' ProductsGetPermissions (Maybe Text) pgpAccessToken = lens _pgpAccessToken (\ s a -> s{_pgpAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pgpUploadType :: Lens' ProductsGetPermissions (Maybe Text) pgpUploadType = lens _pgpUploadType (\ s a -> s{_pgpUploadType = a}) -- | The ID of the product. pgpProductId :: Lens' ProductsGetPermissions Text pgpProductId = lens _pgpProductId (\ s a -> s{_pgpProductId = a}) -- | JSONP pgpCallback :: Lens' ProductsGetPermissions (Maybe Text) pgpCallback = lens _pgpCallback (\ s a -> s{_pgpCallback = a}) instance GoogleRequest ProductsGetPermissions where type Rs ProductsGetPermissions = ProductPermissions type Scopes ProductsGetPermissions = '["https://www.googleapis.com/auth/androidenterprise"] requestClient ProductsGetPermissions'{..} = go _pgpEnterpriseId _pgpProductId _pgpXgafv _pgpUploadProtocol _pgpAccessToken _pgpUploadType _pgpCallback (Just AltJSON) androidEnterpriseService where go = buildClient (Proxy :: Proxy ProductsGetPermissionsResource) mempty
brendanhay/gogol
gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Products/GetPermissions.hs
mpl-2.0
5,374
0
20
1,283
785
456
329
118
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.Compute.TargetHTTPSProxies.SetURLMap -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Changes the URL map for TargetHttpsProxy. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.targetHttpsProxies.setUrlMap@. module Network.Google.Resource.Compute.TargetHTTPSProxies.SetURLMap ( -- * REST Resource TargetHTTPSProxiesSetURLMapResource -- * Creating a Request , targetHTTPSProxiesSetURLMap , TargetHTTPSProxiesSetURLMap -- * Request Lenses , thpsumRequestId , thpsumProject , thpsumPayload , thpsumTargetHTTPSProxy ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.targetHttpsProxies.setUrlMap@ method which the -- 'TargetHTTPSProxiesSetURLMap' request conforms to. type TargetHTTPSProxiesSetURLMapResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "targetHttpsProxies" :> Capture "targetHttpsProxy" Text :> "setUrlMap" :> QueryParam "requestId" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] URLMapReference :> Post '[JSON] Operation -- | Changes the URL map for TargetHttpsProxy. -- -- /See:/ 'targetHTTPSProxiesSetURLMap' smart constructor. data TargetHTTPSProxiesSetURLMap = TargetHTTPSProxiesSetURLMap' { _thpsumRequestId :: !(Maybe Text) , _thpsumProject :: !Text , _thpsumPayload :: !URLMapReference , _thpsumTargetHTTPSProxy :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TargetHTTPSProxiesSetURLMap' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'thpsumRequestId' -- -- * 'thpsumProject' -- -- * 'thpsumPayload' -- -- * 'thpsumTargetHTTPSProxy' targetHTTPSProxiesSetURLMap :: Text -- ^ 'thpsumProject' -> URLMapReference -- ^ 'thpsumPayload' -> Text -- ^ 'thpsumTargetHTTPSProxy' -> TargetHTTPSProxiesSetURLMap targetHTTPSProxiesSetURLMap pThpsumProject_ pThpsumPayload_ pThpsumTargetHTTPSProxy_ = TargetHTTPSProxiesSetURLMap' { _thpsumRequestId = Nothing , _thpsumProject = pThpsumProject_ , _thpsumPayload = pThpsumPayload_ , _thpsumTargetHTTPSProxy = pThpsumTargetHTTPSProxy_ } -- | An optional request ID to identify requests. Specify a unique request ID -- so that if you must retry your request, the server will know to ignore -- the request if it has already been completed. For example, consider a -- situation where you make an initial request and the request times out. -- If you make the request again with the same request ID, the server can -- check if original operation with the same request ID was received, and -- if so, will ignore the second request. This prevents clients from -- accidentally creating duplicate commitments. The request ID must be a -- valid UUID with the exception that zero UUID is not supported -- (00000000-0000-0000-0000-000000000000). thpsumRequestId :: Lens' TargetHTTPSProxiesSetURLMap (Maybe Text) thpsumRequestId = lens _thpsumRequestId (\ s a -> s{_thpsumRequestId = a}) -- | Project ID for this request. thpsumProject :: Lens' TargetHTTPSProxiesSetURLMap Text thpsumProject = lens _thpsumProject (\ s a -> s{_thpsumProject = a}) -- | Multipart request metadata. thpsumPayload :: Lens' TargetHTTPSProxiesSetURLMap URLMapReference thpsumPayload = lens _thpsumPayload (\ s a -> s{_thpsumPayload = a}) -- | Name of the TargetHttpsProxy resource whose URL map is to be set. thpsumTargetHTTPSProxy :: Lens' TargetHTTPSProxiesSetURLMap Text thpsumTargetHTTPSProxy = lens _thpsumTargetHTTPSProxy (\ s a -> s{_thpsumTargetHTTPSProxy = a}) instance GoogleRequest TargetHTTPSProxiesSetURLMap where type Rs TargetHTTPSProxiesSetURLMap = Operation type Scopes TargetHTTPSProxiesSetURLMap = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient TargetHTTPSProxiesSetURLMap'{..} = go _thpsumProject _thpsumTargetHTTPSProxy _thpsumRequestId (Just AltJSON) _thpsumPayload computeService where go = buildClient (Proxy :: Proxy TargetHTTPSProxiesSetURLMapResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/TargetHTTPSProxies/SetURLMap.hs
mpl-2.0
5,258
0
17
1,140
557
333
224
92
1
{-#LANGUAGE OverloadedStrings#-} module Data.P440.XML.Instances.IZV where import qualified Data.P440.Domain.IZV as IZV import Data.P440.Domain.SimpleTypes import Data.P440.XML.XML import Data.P440.XML.Instances.SimpleTypes instance ToNode IZV.Файл where toNode (IZV.Файл идЭС версПрог телОтпр должнОтпр фамОтпр извещение) = complex "Файл" ["ИдЭС" =: идЭС ,"ВерсПрог" =: версПрог ,"ТелОтпр" =: телОтпр ,"ДолжнОтпр" =: должнОтпр ,"ФамОтпр" =: фамОтпр] [Single извещение] instance ToNode IZV.Извещение where toNode (IZV.Извещение имяФайла кодРезПроверки датаВремяПроверки датаВремяПериода) = complex_ "Извещение" ["ИмяФайла" =: имяФайла ,"КодРезПроверки" =: кодРезПроверки ,"ДатаВремяПроверки" =: датаВремяПроверки ,"ДатаВремяПериода" =: датаВремяПериода]
Macil-dev/440P-old
src/Data/P440/XML/Instances/IZV.hs
unlicense
1,346
0
9
339
600
310
290
24
0
{-# LANGUAGE GADTs #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} module Data.HMap.Lazy ( module Data.HMap.Lazy, module X ) where import Control.Lens import Control.Lens.Utils import Data.Functor.Utils import Data.Maps as X import Prelude hiding (lookup, (.)) import qualified Data.Maps as Maps import Data.Monoid import Data.Typeable import Data.Default import Data.Traversable import Data.Map (Map) import Data.IntMap (IntMap) import Data.HashMap.Lazy (HashMap) import Data.Hashable (Hashable) import Data.Foldable (Foldable) import Type.Hidden (Hidden) import qualified Type.Hidden as Type import GHC.Generics (Generic) import Data.Container.Hetero ---------------------------------------------------------------------- -- Key ---------------------------------------------------------------------- data Key key val = Key key deriving Show type IntKey = Key Int class IsKey a k v | a -> k v where toKey :: a -> Key k v -- == Instances == instance IsKey (Key k v) k v where toKey = id instance Default k => Default (Key k v) where def = Key def ---------------------------------------------------------------------- -- Hetero wrapper ---------------------------------------------------------------------- -- == Utils == baseElems :: ValMap m k v => Hetero m -> [v] baseElems = elems ∘ unwrap' baseKeys :: ValMap m k v => Hetero m -> [k] baseKeys = keys ∘ unwrap' lookupBase :: GenMap m k v => k -> Hetero m -> Maybe v lookupBase k = Maps.lookup k ∘ unwrap' -- == Instances == instance (IsKey key k v, GenMap m k t, Hidden t) => GenMap (Hetero m) key v where lookup (toKey -> Key k) m = (fmap Type.reveal (Maps.lookup k $ unwrap' m) :: Maybe v) {-# INLINE lookup #-} insert (toKey -> Key k) a m = v `seq` (m & wrapped' %~ Maps.insert k v) where v = Type.hide a {-# INLINE insert #-} ---------------------------------------------------------------------- -- Typeable sets ---------------------------------------------------------------------- type HHashMap k = Hetero (HashMap k Type.Any) type HMap k = Hetero (Map k Type.Any) type HIntMap = Hetero (IntMap Type.Any) type HTHashMap = HHashMap TypeRep type HTMap = HMap TypeRep data TypeKey val = TypeKey deriving Show instance Typeable v => IsKey (TypeKey v) TypeRep v where toKey (_ :: TypeKey val) = Key (typeOf (undefined :: val))
wdanilo/container
src/Data/HMap/Lazy.hs
apache-2.0
2,925
0
11
692
726
410
316
-1
-1
module Chapter4 where awesome = ["Papuchon", "curry", ":)"] alsoAwesome = ["Quake", "The Simons"] allAwesom = [awesome, alsoAwesome] myAbs :: Integer -> Integer myAbs x = if x < 0 then -x else x isPalindrome :: (Eq a) => [a] -> Bool isPalindrome x = reverse x == x f :: (a, b) -> (c, d) -> ((b,d), (a,c)) f x y = ((snd x, snd y), (fst x, fst y)) x = (+) g xs = w `x` 1 where w = length xs
logistark/haskellbookexercises
4 - BasicDatatypes/chapter4.hs
apache-2.0
422
0
8
117
221
128
93
13
2
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, FlexibleContexts #-} module Sync where import Network.HTTP.Conduit import Control.Monad.Except import Control.Monad.Trans.Resource import Control.Monad.Reader (ReaderT, ask, runReaderT) import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import System.FilePath.Posix import System.Directory import Data.List import Data.Maybe import Control.Exception.Lifted import Text.Read (readMaybe) import System.Log.Logger import System.Log.Handler.Simple import System.Log.Handler (setFormatter) import System.Log.Formatter import Data.Typeable import System.IO.Error import Control.Concurrent.Async import Api import qualified ApiTypes as DP import Http (AccessToken) import File import Oauth type CSRFToken = String type ApiAction a = ReaderT (Manager, AccessToken, CSRFToken, DP.Mailbox) (ResourceT IO) a data SyncState = SyncState {localSyncState :: Set File, remoteSyncState :: Set File} deriving (Show, Read) syncDirName :: String syncDirName = "Digipostarkiv" readSyncState :: FilePath -> IO SyncState readSyncState syncFile = do r <- try (readFile syncFile) :: IO (Either IOException String) case r of Right content -> return $ fromMaybe emptyState (readMaybe content) Left _ -> return emptyState where emptyState = SyncState Set.empty Set.empty writeSyncState :: FilePath -> SyncState -> IO () writeSyncState syncFile state = do let tempFile = syncFile ++ ".tmp" writeFile tempFile (show state) renameFile tempFile syncFile getRemoteState :: ApiAction (Map Path RemoteFile) getRemoteState = do (mgr, atoken, csrf, mbox) <- ask let mboxFolders = (DP.folder . DP.folders) mbox contents <- liftIO $ mapConcurrently (\f -> runResourceT $ runReaderT (getFolderContents f) (mgr, atoken, csrf, mbox)) mboxFolders inboxContents <- getInboxContents let allFolders = Map.unions contents return $ Map.union inboxContents allFolders getInboxContents :: ApiAction (Map Path RemoteFile) getInboxContents = do (manager, aToken, _, mbox) <- ask inboxLink <- liftIO $ linkOrException "document_inbox" $ DP.mailboxLinks mbox documents <- liftResourceT $ getDocuments aToken manager inboxLink let inboxDocuments = filter DP.uploaded (DP.document documents) let dirPath = Path "./" let dir = Dir dirPath uploadLink <- liftIO $ linkOrException "upload_document_to_inbox" $ DP.mailboxLinks mbox let folder = DP.Folder "" "" [uploadLink { DP.rel = "upload_document" }] (Just $ DP.Documents inboxDocuments) let remoteDir = RemoteDir dir folder let files = map (mapFileToRemoteFile folder) inboxDocuments return $ Map.fromList $ (dirPath, remoteDir) : files mapFileToRemoteFile :: DP.Folder -> DP.Document -> (Path, RemoteFile) mapFileToRemoteFile fldr doc = let file = fileFromFolderDoc fldr doc in (File.path file, RemoteFile file fldr doc) getFolderContents :: DP.Folder -> ApiAction (Map Path RemoteFile) getFolderContents folder = do (manager, aToken, _, _) <- ask folderLink <- liftIO $ linkOrException "self" $ DP.folderLinks folder fullFolder <- liftResourceT $ getFolder aToken manager folderLink let folderDocuments = filter DP.uploaded (DP.documentInFolder fullFolder) let dir = (pathFromFolder folder, remoteDirFromFolder folder) let files = map (mapFileToRemoteFile folder) folderDocuments return $ Map.fromList (dir : files) getDirContents :: FilePath -> IO [FilePath] getDirContents dirPath = do names <- replaceSpecialChars <$> getDirectoryContents dirPath return $ filter (not . specialFiles) names where specialFiles f = "." `isPrefixOf` f || f `elem` [".", ".."] getLocalState :: FilePath -> IO (Set File) getLocalState syncDirPath = Set.insert (Dir (Path "./")) <$> findFilesRecursive syncDirPath where relativeToSyncDir = makeRelative syncDirPath findFilesRecursive dirPath = do properNames <- getDirContents dirPath content <- forM properNames $ \name -> do let subPath = dirPath </> name isDirectory <- doesDirectoryExist subPath if isDirectory then findFilesRecursive subPath else Set.singleton <$> getLocalFile syncDirPath subPath let contentSet = Set.unions content let relativeDirPath = addTrailingPathSeparator (relativeToSyncDir dirPath) let dir = Dir $ Path relativeDirPath return $ if relativeDirPath == "./" then contentSet else Set.insert dir contentSet getLocalFile :: FilePath -> FilePath -> IO File getLocalFile basePath fullPath = do modificationTime <- getModificationTime fullPath let relativePath = makeRelative basePath fullPath return $ File (Path relativePath) modificationTime initLocalState :: IO (FilePath, FilePath, SyncState, Set File) initLocalState = do syncDir <- getOrCreateSyncDir syncFile <- getSyncFile previousState <- readSyncState syncFile localState <- getLocalState syncDir return (syncDir, syncFile, previousState, localState) applyChangesLocal :: FilePath -> Map Path RemoteFile -> [Change] -> ApiAction [Change] applyChangesLocal syncDir remoteFiles = fmap catMaybes . mapM applyChange where applyChange :: Change -> ApiAction (Maybe Change) applyChange (Created file) = tryWithLogging $ applyCreatedToLocal syncDir remoteFiles file applyChange (Deleted file) = tryWithLogging $ applyDeletedToLocal syncDir file tryWithLogging :: forall m a. (MonadIO m, MonadBaseControl IO m) => m a -> m (Maybe a) tryWithLogging action = do res <- try action case res of Right v -> return $ Just v Left (SomeException e) -> liftIO $ warningM "Sync.tryWithLogging" (show (typeOf e) ++ ": " ++ show e) >> return Nothing applyCreatedToLocal :: FilePath -> Map Path RemoteFile -> File -> ApiAction Change applyCreatedToLocal syncDir remoteFiles file = let createdPath = File.path file absoluteTargetFile = combine syncDir (filePath createdPath) remoteFile = Map.lookup createdPath remoteFiles in case remoteFile of Just r -> Created <$> download r absoluteTargetFile Nothing -> error $ "file to download not found: " ++ show createdPath applyDeletedToLocal :: (MonadIO m, MonadBaseControl IO m) => FilePath -> File -> m Change applyDeletedToLocal syncDir file = do res <- try $ liftIO $ deleteLocal syncDir (File.path file) case res of Right deletedFile -> return $ Deleted deletedFile Left e | isDoesNotExistError e -> liftIO (warningM "Sync.applyDeletedToLocal" (show e)) >> return (Deleted file) Left e -> throw e applyChangesRemote :: FilePath -> Map Path RemoteFile -> [Change] -> ApiAction [Change] applyChangesRemote syncDir rState = fmap catMaybes . applyChanges rState where applyChanges :: Map Path RemoteFile -> [Change] -> ApiAction [Maybe Change] applyChanges _ [] = return [] applyChanges remoteState (headChange:tailChanges) = case headChange of Created (Dir createdPath) -> do res <- tryWithLogging $ applyCreatedDirToRemote createdPath let appliedHead = fmap fst res let newFolder = fmap snd res let newState = case newFolder of Just nf -> Map.insert createdPath nf remoteState Nothing -> remoteState appliedTail <- applyChanges newState tailChanges return $ appliedHead : appliedTail Created (File createdPath _) -> do res <- tryWithLogging $ applyCreatedFileToRemote syncDir remoteState createdPath let appliedHead = fmap fst res let newFile = fmap snd res let newState = case newFile of Just nf -> Map.insert createdPath nf remoteState Nothing -> remoteState appliedTail <- applyChanges newState tailChanges return $ appliedHead : appliedTail Deleted file -> do appliedHead <- tryWithLogging $ applyDeletedToRemote remoteState file appliedTail <- applyChanges remoteState tailChanges return $ appliedHead : appliedTail applyCreatedFileToRemote :: FilePath -> Map Path RemoteFile -> Path -> ApiAction (Change, RemoteFile) applyCreatedFileToRemote syncDir remoteFiles (Path relativeFilePath) = do let parentDirPath = addTrailingPathSeparator . takeDirectory $ relativeFilePath let absoluteFilePath = syncDir </> relativeFilePath let parentDirMaybe = Map.lookup (Path parentDirPath) remoteFiles case parentDirMaybe of Just parentDir -> do remoteFile <- upload parentDir absoluteFilePath return (Created (File (Path relativeFilePath) (modifiedTime (getFile remoteFile))), remoteFile) Nothing -> error $ "no parent dir: " ++ parentDirPath applyCreatedDirToRemote :: Path -> ApiAction (Change, RemoteFile) applyCreatedDirToRemote dirPath = do --For now Digipost only support one level of folders let folderName = takeFileName . takeDirectory . filePath $ dirPath (manager, aToken, csrfToken, mbox) <- ask createFolderLink <- liftIO $ linkOrException "create_folder" $ DP.mailboxLinks mbox newFolder <- liftResourceT $ createFolder aToken manager createFolderLink csrfToken folderName let dir = Dir dirPath return (Created dir, RemoteDir dir newFolder) applyDeletedToRemote :: Map Path RemoteFile -> File -> ApiAction Change applyDeletedToRemote remoteFiles file = do let deletedPath = File.path file let remoteFileMaybe = Map.lookup deletedPath remoteFiles case remoteFileMaybe of Just remoteFile -> do deleteRemote remoteFile return $ Deleted (getFile remoteFile) Nothing -> error $ "remote file not found: " ++ show deletedPath upload :: RemoteFile -> FilePath -> ApiAction RemoteFile upload (RemoteDir _ parentFolder) absoluteFilePath = do uploadLink <- liftIO $ linkOrException "upload_document" (DP.folderLinks parentFolder) (manager, aToken, csrf, _) <- ask doc <- liftResourceT $ uploadDocument aToken manager uploadLink csrf absoluteFilePath liftIO $ debugM "Sync.upload" ("Uploaded " ++ absoluteFilePath) return $ RemoteFile (fileFromFolderDoc parentFolder doc) parentFolder doc upload _ _ = error "parent dir cannot be a file" deleteRemote :: RemoteFile -> ApiAction () deleteRemote (RemoteFile _ _ document) = do (manager, aToken, csrf, _) <- ask liftResourceT $ deleteDocument aToken manager csrf document deleteRemote (RemoteDir _ folder) = do (manager, aToken, csrf, _) <- ask liftResourceT $ deleteFolder aToken manager csrf folder deleteLocal :: FilePath -> Path -> IO File deleteLocal syncDir p@(Path relativePath) = deleteFileOrDir where deleteFileOrDir = do let targetFile = syncDir </> relativePath isDirectory <- doesDirectoryExist targetFile modified <- getModificationTime targetFile if isDirectory then removeDirectoryRecursive targetFile >> return (Dir p) else removeFile targetFile >> return (File p modified) download :: RemoteFile -> FilePath -> ApiAction File download (RemoteFile file _ document) targetFile = do (manager, aToken, _, _) <- ask liftResourceT $ downloadDocument aToken manager targetFile document liftIO $ debugM "Sync.download" ("Downloaded " ++ targetFile) newFileModified <- liftIO $ getModificationTime targetFile return $ File (File.path file) newFileModified download (RemoteDir dir _) targetFile = liftIO $ do dirExists <- doesDirectoryExist targetFile unless dirExists $ createDirectory targetFile return $ Dir (File.path dir) checkLocalChange :: IO Bool checkLocalChange = do (_, _, previousState, localFiles) <- initLocalState let previousLocalFiles = localSyncState previousState let localChanges = computeChanges localFiles previousLocalFiles unless (null localChanges) (liftIO $ infoM "Sync.checkLocalChange" ("localChanges:\n" ++ formatList localChanges)) return $ not (null localChanges) checkRemoteChange :: IO Bool checkRemoteChange = handleTokenRefresh checkRemoteChange' <$> loadAccessToken >>= withHttp withHttp :: (Manager -> ResourceT IO a) -> IO a withHttp action = runResourceT $ liftIO (newManager tlsManagerSettings) >>= action checkRemoteChange' :: Manager -> AccessToken -> ResourceT IO Bool checkRemoteChange' manager token = do (_, _, previousState, _) <- liftIO initLocalState (root, _, mbox) <- getAccount manager token remoteState <- runReaderT getRemoteState (manager, token, DP.csrfToken root, mbox) let remoteFiles = getFileSetFromMap remoteState let previousRemoteFiles = remoteSyncState previousState let remoteChanges = computeChanges remoteFiles previousRemoteFiles unless (null remoteChanges) (liftIO $ infoM "Sync.checkRemoteChange" ("remoteChanges:\n" ++ formatList remoteChanges)) return $ not (null remoteChanges) sync :: IO () sync = handleTokenRefresh sync' <$> loadAccessToken >>= withHttp sync' :: Manager -> AccessToken -> ResourceT IO () sync' manager token = do liftIO $ infoM "Sync.sync" "Start sync" (syncDir, syncFile, previousState, localFiles) <- liftIO initLocalState (root, _, mbox) <- getAccount manager token flip runReaderT (manager, token, DP.csrfToken root, mbox) $ do liftIO $ debugM "Sync.sync" "before getRemoteState" remoteState <- getRemoteState liftIO $ debugM "Sync.sync" "afterGetRemoteState" let remoteFiles = getFileSetFromMap remoteState let previousRemoteFiles = remoteSyncState previousState let previousLocalFiles = localSyncState previousState let localChanges = computeChanges localFiles previousLocalFiles let remoteChanges = computeChanges remoteFiles previousRemoteFiles --server always win if conflict TODO: better handle conflicts let changesToApplyLocal = remoteChanges let changesToApplyRemote = computeChangesToApply localChanges remoteChanges liftIO $ infoM "Sync.sync" ("localChanges:\n" ++ formatList localChanges) liftIO $ infoM "Sync.sync" ("remoteChanges:\n" ++ formatList remoteChanges) appliedLocalChanges <- applyChangesLocal syncDir remoteState changesToApplyLocal appliedRemoteChanges <- applyChangesRemote syncDir remoteState changesToApplyRemote liftIO $ debugM "Sync.sync" "finished applying changes" let newLocalState = computeNewState previousLocalFiles localChanges appliedLocalChanges appliedRemoteChanges let newRemoteState = computeNewState previousRemoteFiles remoteChanges appliedRemoteChanges appliedLocalChanges liftIO $ debugM "Sync.sync" "computed new state" liftIO $ writeSyncState syncFile (SyncState newLocalState newRemoteState) liftIO $ debugM "Sync.sync" "wrote new state to file" return () initLogging :: IO () initLogging = do metaDir <- getMetaDir let logFile = combine metaDir "log" h <- fileHandler logFile DEBUG >>= \lh -> return $ setFormatter lh (simpleLogFormatter "[$time : $loggername : $prio] $msg") updateGlobalLogger "" (addHandler h) updateGlobalLogger "" (setLevel DEBUG) getUserSyncDir :: IO FilePath getUserSyncDir = do homedir <- getHomeDirectory return $ homedir </> syncDirName getOrCreateSyncDir :: IO FilePath getOrCreateSyncDir = do syncDir <- getUserSyncDir createDirectoryIfMissing True syncDir return syncDir getMetaDir :: IO FilePath getMetaDir = do syncDir <- getOrCreateSyncDir let metaDir = syncDir </> ".sync" metaIsFile <- doesFileExist metaDir when metaIsFile $ removeFile metaDir --to upgrade from older versions createDirectoryIfMissing True metaDir return metaDir getSyncFile :: IO FilePath getSyncFile = (</> "db") <$> getMetaDir debugLog :: String -> IO () debugLog = putStrLn -- debugLog _ = return () formatList :: Show a => [a] -> String formatList = unlines . map show
froden/digipostarkiv
src/Sync.hs
apache-2.0
16,595
0
20
3,765
4,618
2,238
2,380
308
6
(lp1 (ccopy_reg _reconstructor p2 (cpygments.token _TokenType p3 c__builtin__ tuple p4 (S'Comment' p5 S'Single' p6 ttRp7 (dp8 S'subtypes' p9 c__builtin__ set p10 ((ltRp11 sS'parent' p12 g2 (g3 g4 (g5 ttRp13 (dp14 g12 g2 (g3 g4 (ttRp15 (dp16 g5 g13 sS'Name' p17 g2 (g3 g4 (g17 ttRp18 (dp19 S'Function' p20 g2 (g3 g4 (g17 g20 ttRp21 (dp22 g9 g10 ((ltRp23 sg12 g18 sbsS'Exception' p24 g2 (g3 g4 (g17 g24 ttRp25 (dp26 g9 g10 ((ltRp27 sg12 g18 sbsS'Tag' p28 g2 (g3 g4 (g17 g28 ttRp29 (dp30 g9 g10 ((ltRp31 sg12 g18 sbsS'Constant' p32 g2 (g3 g4 (g17 g32 ttRp33 (dp34 g9 g10 ((ltRp35 sg12 g18 sbsg12 g15 sS'Pseudo' p36 g2 (g3 g4 (g17 g36 ttRp37 (dp38 g9 g10 ((ltRp39 sg12 g18 sbsS'Attribute' p40 g2 (g3 g4 (g17 g40 ttRp41 (dp42 g9 g10 ((ltRp43 sg12 g18 sbsS'Label' p44 g2 (g3 g4 (g17 g44 ttRp45 (dp46 g9 g10 ((ltRp47 sg12 g18 sbsS'Blubb' p48 g2 (g3 g4 (g17 g48 ttRp49 (dp50 g9 g10 ((ltRp51 sg12 g18 sbsS'Entity' p52 g2 (g3 g4 (g17 g52 ttRp53 (dp54 g9 g10 ((ltRp55 sg12 g18 sbsS'Builtin' p56 g2 (g3 g4 (g17 g56 ttRp57 (dp58 g9 g10 ((lp59 g2 (g3 g4 (g17 g56 g36 ttRp60 (dp61 g9 g10 ((ltRp62 sg12 g57 sbatRp63 sg36 g60 sg12 g18 sbsS'Other' p64 g2 (g3 g4 (g17 g64 ttRp65 (dp66 g9 g10 ((ltRp67 sg12 g18 sbsS'Identifier' p68 g2 (g3 g4 (g17 g68 ttRp69 (dp70 g9 g10 ((ltRp71 sg12 g18 sbsS'Variable' p72 g2 (g3 g4 (g17 g72 ttRp73 (dp74 g12 g18 sS'Global' p75 g2 (g3 g4 (g17 g72 g75 ttRp76 (dp77 g9 g10 ((ltRp78 sg12 g73 sbsS'Instance' p79 g2 (g3 g4 (g17 g72 g79 ttRp80 (dp81 g9 g10 ((ltRp82 sg12 g73 sbsS'Anonymous' p83 g2 (g3 g4 (g17 g72 g83 ttRp84 (dp85 g9 g10 ((ltRp86 sg12 g73 sbsg9 g10 ((lp87 g84 ag80 ag76 ag2 (g3 g4 (g17 g72 S'Class' p88 ttRp89 (dp90 g9 g10 ((ltRp91 sg12 g73 sbatRp92 sg88 g89 sbsg9 g10 ((lp93 g2 (g3 g4 (g17 S'Decorator' p94 ttRp95 (dp96 g9 g10 ((ltRp97 sg12 g18 sbag41 ag33 ag37 ag2 (g3 g4 (g17 S'Namespace' p98 ttRp99 (dp100 g9 g10 ((ltRp101 sg12 g18 sbag69 ag57 ag73 ag65 ag49 ag53 ag21 ag2 (g3 g4 (g17 S'Property' p102 ttRp103 (dp104 g9 g10 ((ltRp105 sg12 g18 sbag45 ag29 ag25 ag2 (g3 g4 (g17 g88 ttRp106 (dp107 g9 g10 ((ltRp108 sg12 g18 sbatRp109 sg102 g103 sg88 g106 sg94 g95 sg98 g99 sbsS'Keyword' p110 g2 (g3 g4 (g110 ttRp111 (dp112 g32 g2 (g3 g4 (g110 g32 ttRp113 (dp114 g9 g10 ((ltRp115 sg12 g111 sbsg12 g15 sg98 g2 (g3 g4 (g110 g98 ttRp116 (dp117 g9 g10 ((ltRp118 sg12 g111 sbsg36 g2 (g3 g4 (g110 g36 ttRp119 (dp120 g9 g10 ((ltRp121 sg12 g111 sbsS'Reserved' p122 g2 (g3 g4 (g110 g122 ttRp123 (dp124 g9 g10 ((ltRp125 sg12 g111 sbsS'Declaration' p126 g2 (g3 g4 (g110 g126 ttRp127 (dp128 g9 g10 ((ltRp129 sg12 g111 sbsg72 g2 (g3 g4 (g110 g72 ttRp130 (dp131 g9 g10 ((ltRp132 sg12 g111 sbsg9 g10 ((lp133 g113 ag123 ag2 (g3 g4 (g110 S'Type' p134 ttRp135 (dp136 g9 g10 ((ltRp137 sg12 g111 sbag127 ag130 ag116 ag119 atRp138 sg134 g135 sbsS'Generic' p139 g2 (g3 g4 (g139 ttRp140 (dp141 S'Prompt' p142 g2 (g3 g4 (g139 g142 ttRp143 (dp144 g9 g10 ((ltRp145 sg12 g140 sbsg12 g15 sS'Deleted' p146 g2 (g3 g4 (g139 g146 ttRp147 (dp148 g9 g10 ((ltRp149 sg12 g140 sbsS'Traceback' p150 g2 (g3 g4 (g139 g150 ttRp151 (dp152 g9 g10 ((ltRp153 sg12 g140 sbsS'Emph' p154 g2 (g3 g4 (g139 g154 ttRp155 (dp156 g9 g10 ((ltRp157 sg12 g140 sbsS'Output' p158 g2 (g3 g4 (g139 g158 ttRp159 (dp160 g9 g10 ((ltRp161 sg12 g140 sbsS'Subheading' p162 g2 (g3 g4 (g139 g162 ttRp163 (dp164 g9 g10 ((ltRp165 sg12 g140 sbsS'Error' p166 g2 (g3 g4 (g139 g166 ttRp167 (dp168 g9 g10 ((ltRp169 sg12 g140 sbsg9 g10 ((lp170 g159 ag155 ag167 ag163 ag151 ag147 ag2 (g3 g4 (g139 S'Heading' p171 ttRp172 (dp173 g9 g10 ((ltRp174 sg12 g140 sbag2 (g3 g4 (g139 S'Inserted' p175 ttRp176 (dp177 g9 g10 ((ltRp178 sg12 g140 sbag2 (g3 g4 (g139 S'Strong' p179 ttRp180 (dp181 g9 g10 ((ltRp182 sg12 g140 sbag143 atRp183 sg179 g180 sg175 g176 sg171 g172 sbsS'Text' p184 g2 (g3 g4 (g184 ttRp185 (dp186 g9 g10 ((lp187 g2 (g3 g4 (g184 S'Symbol' p188 ttRp189 (dp190 g9 g10 ((ltRp191 sg12 g185 sbag2 (g3 g4 (g184 S'Whitespace' p192 ttRp193 (dp194 g9 g10 ((ltRp195 sg12 g185 sbatRp196 sg188 g189 sg192 g193 sg12 g15 sbsS'Punctuation' p197 g2 (g3 g4 (g197 ttRp198 (dp199 g9 g10 ((lp200 g2 (g3 g4 (g197 S'Indicator' p201 ttRp202 (dp203 g9 g10 ((ltRp204 sg12 g198 sbatRp205 sg201 g202 sg12 g15 sbsS'Token' p206 g15 sS'Number' p207 g2 (g3 g4 (S'Literal' p208 g207 ttRp209 (dp210 S'Bin' p211 g2 (g3 g4 (g208 g207 g211 ttRp212 (dp213 g9 g10 ((ltRp214 sg12 g209 sbsS'Binary' p215 g2 (g3 g4 (g208 g207 g215 ttRp216 (dp217 g9 g10 ((ltRp218 sg12 g209 sbsg12 g2 (g3 g4 (g208 ttRp219 (dp220 S'String' p221 g2 (g3 g4 (g208 g221 ttRp222 (dp223 S'Regex' p224 g2 (g3 g4 (g208 g221 g224 ttRp225 (dp226 g9 g10 ((ltRp227 sg12 g222 sbsS'Interpol' p228 g2 (g3 g4 (g208 g221 g228 ttRp229 (dp230 g9 g10 ((ltRp231 sg12 g222 sbsS'Regexp' p232 g2 (g3 g4 (g208 g221 g232 ttRp233 (dp234 g9 g10 ((ltRp235 sg12 g222 sbsg12 g219 sS'Heredoc' p236 g2 (g3 g4 (g208 g221 g236 ttRp237 (dp238 g9 g10 ((ltRp239 sg12 g222 sbsS'Double' p240 g2 (g3 g4 (g208 g221 g240 ttRp241 (dp242 g9 g10 ((ltRp243 sg12 g222 sbsg188 g2 (g3 g4 (g208 g221 g188 ttRp244 (dp245 g9 g10 ((ltRp246 sg12 g222 sbsS'Escape' p247 g2 (g3 g4 (g208 g221 g247 ttRp248 (dp249 g9 g10 ((ltRp250 sg12 g222 sbsS'Character' p251 g2 (g3 g4 (g208 g221 g251 ttRp252 (dp253 g9 g10 ((ltRp254 sg12 g222 sbsS'Interp' p255 g2 (g3 g4 (g208 g221 g255 ttRp256 (dp257 g9 g10 ((ltRp258 sg12 g222 sbsS'Backtick' p259 g2 (g3 g4 (g208 g221 g259 ttRp260 (dp261 g9 g10 ((ltRp262 sg12 g222 sbsS'Char' p263 g2 (g3 g4 (g208 g221 g263 ttRp264 (dp265 g9 g10 ((ltRp266 sg12 g222 sbsg6 g2 (g3 g4 (g208 g221 g6 ttRp267 (dp268 g9 g10 ((ltRp269 sg12 g222 sbsg64 g2 (g3 g4 (g208 g221 g64 ttRp270 (dp271 g9 g10 ((ltRp272 sg12 g222 sbsS'Doc' p273 g2 (g3 g4 (g208 g221 g273 ttRp274 (dp275 g9 g10 ((ltRp276 sg12 g222 sbsg9 g10 ((lp277 g270 ag2 (g3 g4 (g208 g221 S'Atom' p278 ttRp279 (dp280 g9 g10 ((ltRp281 sg12 g222 sbag241 ag264 ag256 ag274 ag237 ag260 ag229 ag244 ag233 ag225 ag267 ag252 ag248 atRp282 sg278 g279 sbsg12 g15 sg207 g209 sS'Scalar' p283 g2 (g3 g4 (g208 g283 ttRp284 (dp285 g9 g10 ((lp286 g2 (g3 g4 (g208 g283 S'Plain' p287 ttRp288 (dp289 g9 g10 ((ltRp290 sg12 g284 sbatRp291 sg12 g219 sg287 g288 sbsg64 g2 (g3 g4 (g208 g64 ttRp292 (dp293 g9 g10 ((ltRp294 sg12 g219 sbsS'Date' p295 g2 (g3 g4 (g208 g295 ttRp296 (dp297 g9 g10 ((ltRp298 sg12 g219 sbsg9 g10 ((lp299 g296 ag222 ag292 ag209 ag284 atRp300 sbsS'Decimal' p301 g2 (g3 g4 (g208 g207 g301 ttRp302 (dp303 g9 g10 ((ltRp304 sg12 g209 sbsS'Float' p305 g2 (g3 g4 (g208 g207 g305 ttRp306 (dp307 g9 g10 ((ltRp308 sg12 g209 sbsS'Hex' p309 g2 (g3 g4 (g208 g207 g309 ttRp310 (dp311 g9 g10 ((ltRp312 sg12 g209 sbsS'Integer' p313 g2 (g3 g4 (g208 g207 g313 ttRp314 (dp315 g9 g10 ((lp316 g2 (g3 g4 (g208 g207 g313 S'Long' p317 ttRp318 (dp319 g9 g10 ((ltRp320 sg12 g314 sbatRp321 sg317 g318 sg12 g209 sbsS'Octal' p322 g2 (g3 g4 (g208 g207 g322 ttRp323 (dp324 g9 g10 ((ltRp325 sg12 g209 sbsg9 g10 ((lp326 g212 ag216 ag323 ag302 ag2 (g3 g4 (g208 g207 S'Oct' p327 ttRp328 (dp329 g9 g10 ((ltRp330 sg12 g209 sbag314 ag306 ag310 atRp331 sg327 g328 sbsg208 g219 sg64 g2 (g3 g4 (g64 ttRp332 (dp333 g9 g10 ((ltRp334 sg12 g15 sbsg166 g2 (g3 g4 (g166 ttRp335 (dp336 g9 g10 ((ltRp337 sg12 g15 sbsS'Operator' p338 g2 (g3 g4 (g338 ttRp339 (dp340 g9 g10 ((lp341 g2 (g3 g4 (g338 S'Word' p342 ttRp343 (dp344 g9 g10 ((ltRp345 sg12 g339 sbatRp346 sg342 g343 sg12 g15 sbsg9 g10 ((lp347 g13 ag335 ag140 ag185 ag18 ag198 ag111 ag219 ag339 ag332 atRp348 sg221 g222 sbsS'Preproc' p349 g2 (g3 g4 (g5 g349 ttRp350 (dp351 g9 g10 ((ltRp352 sg12 g13 sbsg6 g7 sS'Multiline' p353 g2 (g3 g4 (g5 g353 ttRp354 (dp355 g9 g10 ((ltRp356 sg12 g13 sbsg9 g10 ((lp357 g2 (g3 g4 (g5 S'Special' p358 ttRp359 (dp360 g9 g10 ((ltRp361 sg12 g13 sbag350 ag7 ag354 atRp362 sg358 g359 sbsbV--------------------------------------------------------------------- p363 tp364 a(g185 V\u000a tp365 a(g7 V-- SmallCheck: another lightweight testing library. p366 tp367 a(g185 V\u000a tp368 a(g7 V-- Colin Runciman, August 2006 p369 tp370 a(g185 V\u000a tp371 a(g7 V-- Version 0.2 (November 2006) p372 tp373 a(g185 V\u000a tp374 a(g7 V-- p375 tp376 a(g185 V\u000a tp377 a(g7 V-- After QuickCheck, by Koen Claessen and John Hughes (2000-2004). p378 tp379 a(g185 V\u000a tp380 a(g7 V--------------------------------------------------------------------- p381 tp382 a(g185 V\u000a\u000a p383 tp384 a(g123 Vmodule p385 tp386 a(g185 V tp387 a(g99 VSmallCheck p388 tp389 a(g185 V tp390 a(g198 V( tp391 a(g185 V\u000a p392 tp393 a(g21 VsmallCheck p394 tp395 a(g198 V, tp396 a(g185 V tp397 a(g21 VdepthCheck p398 tp399 a(g198 V, tp400 a(g185 V\u000a p401 tp402 a(g135 VProperty p403 tp404 a(g198 V, tp405 a(g185 V tp406 a(g135 VTestable p407 tp408 a(g198 V, tp409 a(g185 V\u000a p410 tp411 a(g21 VforAll p412 tp413 a(g198 V, tp414 a(g185 V tp415 a(g21 VforAllElem p416 tp417 a(g198 V, tp418 a(g185 V\u000a p419 tp420 a(g21 Vexists p421 tp422 a(g198 V, tp423 a(g185 V tp424 a(g21 VexistsDeeperBy p425 tp426 a(g198 V, tp427 a(g185 V tp428 a(g21 VthereExists p429 tp430 a(g198 V, tp431 a(g185 V tp432 a(g21 VthereExistsElem p433 tp434 a(g198 V, tp435 a(g185 V\u000a p436 tp437 a(g198 V( tp438 a(g339 V==> p439 tp440 a(g198 V) tp441 a(g198 V, tp442 a(g185 V\u000a p443 tp444 a(g135 VSeries p445 tp446 a(g198 V, tp447 a(g185 V tp448 a(g135 VSerial p449 tp450 a(g198 V( tp451 a(g339 V.. p452 tp453 a(g198 V) tp454 a(g198 V, tp455 a(g185 V\u000a p456 tp457 a(g198 V( tp458 a(g339 V\u005c/ p459 tp460 a(g198 V) tp461 a(g198 V, tp462 a(g185 V tp463 a(g198 V( tp464 a(g339 V>< p465 tp466 a(g198 V) tp467 a(g198 V, tp468 a(g185 V tp469 a(g21 Vtwo p470 tp471 a(g198 V, tp472 a(g185 V tp473 a(g21 Vthree p474 tp475 a(g198 V, tp476 a(g185 V tp477 a(g21 Vfour p478 tp479 a(g198 V, tp480 a(g185 V\u000a p481 tp482 a(g21 Vcons0 p483 tp484 a(g198 V, tp485 a(g185 V tp486 a(g21 Vcons1 p487 tp488 a(g198 V, tp489 a(g185 V tp490 a(g21 Vcons2 p491 tp492 a(g198 V, tp493 a(g185 V tp494 a(g21 Vcons3 p495 tp496 a(g198 V, tp497 a(g185 V tp498 a(g21 Vcons4 p499 tp500 a(g198 V, tp501 a(g185 V\u000a p502 tp503 a(g21 Valts0 p504 tp505 a(g198 V, tp506 a(g185 V tp507 a(g21 Valts1 p508 tp509 a(g198 V, tp510 a(g185 V tp511 a(g21 Valts2 p512 tp513 a(g198 V, tp514 a(g185 V tp515 a(g21 Valts3 p516 tp517 a(g198 V, tp518 a(g185 V tp519 a(g21 Valts4 p520 tp521 a(g198 V, tp522 a(g185 V\u000a p523 tp524 a(g135 VN tp525 a(g198 V( tp526 a(g339 V.. p527 tp528 a(g198 V) tp529 a(g198 V, tp530 a(g185 V tp531 a(g135 VNat p532 tp533 a(g198 V, tp534 a(g185 V tp535 a(g135 VNatural p536 tp537 a(g198 V, tp538 a(g185 V\u000a p539 tp540 a(g21 Vdepth p541 tp542 a(g198 V, tp543 a(g185 V tp544 a(g21 Vinc p545 tp546 a(g198 V, tp547 a(g185 V tp548 a(g21 Vdec p549 tp550 a(g185 V\u000a p551 tp552 a(g198 V) tp553 a(g185 V tp554 a(g123 Vwhere p555 tp556 a(g185 V\u000a\u000a p557 tp558 a(g123 Vimport p559 tp560 a(g185 V tp561 a(g99 VData.List p562 tp563 a(g185 V tp564 a(g198 V( tp565 a(g21 Vintersperse p566 tp567 a(g198 V) tp568 a(g185 V\u000a tp569 a(g123 Vimport p570 tp571 a(g185 V tp572 a(g99 VControl.Monad p573 tp574 a(g185 V tp575 a(g198 V( tp576 a(g21 Vwhen p577 tp578 a(g198 V) tp579 a(g185 V\u000a tp580 a(g123 Vimport p581 tp582 a(g185 V tp583 a(g99 VSystem.IO p584 tp585 a(g185 V tp586 a(g198 V( tp587 a(g21 Vstdout p588 tp589 a(g198 V, tp590 a(g185 V tp591 a(g21 VhFlush p592 tp593 a(g198 V) tp594 a(g185 V\u000a\u000a p595 tp596 a(g7 V------------------ <Series of depth-bounded values> ----------------- p597 tp598 a(g185 V\u000a\u000a p599 tp600 a(g7 V-- Series arguments should be interpreted as a depth bound (>=0) p601 tp602 a(g185 V\u000a tp603 a(g7 V-- Series results should have finite length p604 tp605 a(g185 V\u000a\u000a p606 tp607 a(g123 Vtype p608 tp609 a(g185 V tp610 a(g135 VSeries p611 tp612 a(g185 V tp613 a(g18 Va tp614 a(g185 V tp615 a(g343 V= tp616 a(g185 V tp617 a(g135 VInt p618 tp619 a(g185 V tp620 a(g343 V-> p621 tp622 a(g185 V tp623 a(g198 V[ tp624 a(g18 Va tp625 a(g198 V] tp626 a(g185 V\u000a\u000a p627 tp628 a(g7 V-- sum p629 tp630 a(g185 V\u000a tp631 a(g123 Vinfixr p632 tp633 a(g185 V tp634 a(g314 V7 tp635 a(g185 V tp636 a(g339 V\u005c/ p637 tp638 a(g185 V\u000a tp639 a(g198 V( tp640 a(g339 V\u005c/ p641 tp642 a(g198 V) tp643 a(g185 V tp644 a(g343 V:: p645 tp646 a(g185 V tp647 a(g135 VSeries p648 tp649 a(g185 V tp650 a(g18 Va tp651 a(g185 V tp652 a(g343 V-> p653 tp654 a(g185 V tp655 a(g135 VSeries p656 tp657 a(g185 V tp658 a(g18 Va tp659 a(g185 V tp660 a(g343 V-> p661 tp662 a(g185 V tp663 a(g135 VSeries p664 tp665 a(g185 V tp666 a(g18 Va tp667 a(g185 V\u000a tp668 a(g21 Vs1 p669 tp670 a(g185 V tp671 a(g339 V\u005c/ p672 tp673 a(g185 V tp674 a(g18 Vs2 p675 tp676 a(g185 V tp677 a(g343 V= tp678 a(g185 V tp679 a(g21 V\u005c tp680 a(g18 Vd tp681 a(g185 V tp682 a(g343 V-> p683 tp684 a(g185 V tp685 a(g18 Vs1 p686 tp687 a(g185 V tp688 a(g18 Vd tp689 a(g185 V tp690 a(g339 V++ p691 tp692 a(g185 V tp693 a(g18 Vs2 p694 tp695 a(g185 V tp696 a(g18 Vd tp697 a(g185 V\u000a\u000a p698 tp699 a(g7 V-- product p700 tp701 a(g185 V\u000a tp702 a(g123 Vinfixr p703 tp704 a(g185 V tp705 a(g314 V8 tp706 a(g185 V tp707 a(g339 V>< p708 tp709 a(g185 V\u000a tp710 a(g198 V( tp711 a(g339 V>< p712 tp713 a(g198 V) tp714 a(g185 V tp715 a(g343 V:: p716 tp717 a(g185 V tp718 a(g135 VSeries p719 tp720 a(g185 V tp721 a(g18 Va tp722 a(g185 V tp723 a(g343 V-> p724 tp725 a(g185 V tp726 a(g135 VSeries p727 tp728 a(g185 V tp729 a(g18 Vb tp730 a(g185 V tp731 a(g343 V-> p732 tp733 a(g185 V tp734 a(g135 VSeries p735 tp736 a(g185 V tp737 a(g198 V( tp738 a(g18 Va tp739 a(g198 V, tp740 a(g18 Vb tp741 a(g198 V) tp742 a(g185 V\u000a tp743 a(g21 Vs1 p744 tp745 a(g185 V tp746 a(g339 V>< p747 tp748 a(g185 V tp749 a(g18 Vs2 p750 tp751 a(g185 V tp752 a(g343 V= tp753 a(g185 V tp754 a(g21 V\u005c tp755 a(g18 Vd tp756 a(g185 V tp757 a(g343 V-> p758 tp759 a(g185 V tp760 a(g198 V[ tp761 a(g198 V( tp762 a(g18 Vx tp763 a(g198 V, tp764 a(g18 Vy tp765 a(g198 V) tp766 a(g185 V tp767 a(g339 V| tp768 a(g185 V tp769 a(g18 Vx tp770 a(g185 V tp771 a(g343 V<- p772 tp773 a(g185 V tp774 a(g18 Vs1 p775 tp776 a(g185 V tp777 a(g18 Vd tp778 a(g198 V, tp779 a(g185 V tp780 a(g18 Vy tp781 a(g185 V tp782 a(g343 V<- p783 tp784 a(g185 V tp785 a(g18 Vs2 p786 tp787 a(g185 V tp788 a(g18 Vd tp789 a(g198 V] tp790 a(g185 V\u000a\u000a p791 tp792 a(g7 V------------------- <methods for type enumeration> ------------------ p793 tp794 a(g185 V\u000a\u000a p795 tp796 a(g7 V-- enumerated data values should be finite and fully defined p797 tp798 a(g185 V\u000a tp799 a(g7 V-- enumerated functional values should be total and strict p800 tp801 a(g185 V\u000a\u000a p802 tp803 a(g7 V-- bounds: p804 tp805 a(g185 V\u000a tp806 a(g7 V-- for data values, the depth of nested constructor applications p807 tp808 a(g185 V\u000a tp809 a(g7 V-- for functional values, both the depth of nested case analysis p810 tp811 a(g185 V\u000a tp812 a(g7 V-- and the depth of results p813 tp814 a(g185 V\u000a \u000a p815 tp816 a(g123 Vclass p817 tp818 a(g185 V tp819 a(g135 VSerial p820 tp821 a(g185 V tp822 a(g18 Va tp823 a(g185 V tp824 a(g123 Vwhere p825 tp826 a(g185 V\u000a p827 tp828 a(g18 Vseries p829 tp830 a(g185 V p831 tp832 a(g343 V:: p833 tp834 a(g185 V tp835 a(g135 VSeries p836 tp837 a(g185 V tp838 a(g18 Va tp839 a(g185 V\u000a p840 tp841 a(g18 Vcoseries p842 tp843 a(g185 V tp844 a(g343 V:: p845 tp846 a(g185 V tp847 a(g135 VSerial p848 tp849 a(g185 V tp850 a(g18 Vb tp851 a(g185 V tp852 a(g343 V=> p853 tp854 a(g185 V tp855 a(g135 VSeries p856 tp857 a(g185 V tp858 a(g198 V( tp859 a(g18 Va tp860 a(g343 V-> p861 tp862 a(g18 Vb tp863 a(g198 V) tp864 a(g185 V\u000a\u000a p865 tp866 a(g123 Vinstance p867 tp868 a(g185 V tp869 a(g135 VSerial p870 tp871 a(g185 V tp872 a(g57 V() p873 tp874 a(g185 V tp875 a(g123 Vwhere p876 tp877 a(g185 V\u000a p878 tp879 a(g18 Vseries p880 tp881 a(g185 V p882 tp883 a(g123 V_ tp884 a(g185 V tp885 a(g343 V= tp886 a(g185 V tp887 a(g198 V[ tp888 a(g57 V() p889 tp890 a(g198 V] tp891 a(g185 V\u000a p892 tp893 a(g18 Vcoseries p894 tp895 a(g185 V tp896 a(g18 Vd tp897 a(g185 V tp898 a(g343 V= tp899 a(g185 V tp900 a(g198 V[ tp901 a(g185 V tp902 a(g21 V\u005c tp903 a(g57 V() p904 tp905 a(g185 V tp906 a(g343 V-> p907 tp908 a(g185 V tp909 a(g18 Vb tp910 a(g185 V\u000a p911 tp912 a(g339 V| tp913 a(g185 V tp914 a(g18 Vb tp915 a(g185 V tp916 a(g343 V<- p917 tp918 a(g185 V tp919 a(g18 Vseries p920 tp921 a(g185 V tp922 a(g18 Vd tp923 a(g185 V tp924 a(g198 V] tp925 a(g185 V\u000a\u000a p926 tp927 a(g123 Vinstance p928 tp929 a(g185 V tp930 a(g135 VSerial p931 tp932 a(g185 V tp933 a(g135 VInt p934 tp935 a(g185 V tp936 a(g123 Vwhere p937 tp938 a(g185 V\u000a p939 tp940 a(g18 Vseries p941 tp942 a(g185 V p943 tp944 a(g18 Vd tp945 a(g185 V tp946 a(g343 V= tp947 a(g185 V tp948 a(g198 V[ tp949 a(g198 V( tp950 a(g339 V- tp951 a(g18 Vd tp952 a(g198 V) tp953 a(g339 V.. p954 tp955 a(g18 Vd tp956 a(g198 V] tp957 a(g185 V\u000a p958 tp959 a(g18 Vcoseries p960 tp961 a(g185 V tp962 a(g18 Vd tp963 a(g185 V tp964 a(g343 V= tp965 a(g185 V tp966 a(g198 V[ tp967 a(g185 V tp968 a(g21 V\u005c tp969 a(g18 Vi tp970 a(g185 V tp971 a(g343 V-> p972 tp973 a(g185 V tp974 a(g123 Vif p975 tp976 a(g185 V tp977 a(g18 Vi tp978 a(g185 V tp979 a(g339 V> tp980 a(g185 V tp981 a(g314 V0 tp982 a(g185 V tp983 a(g123 Vthen p984 tp985 a(g185 V tp986 a(g18 Vf tp987 a(g185 V tp988 a(g198 V( tp989 a(g135 VN tp990 a(g185 V tp991 a(g198 V( tp992 a(g18 Vi tp993 a(g185 V tp994 a(g339 V- tp995 a(g185 V tp996 a(g314 V1 tp997 a(g198 V) tp998 a(g198 V) tp999 a(g185 V\u000a p1000 tp1001 a(g123 Velse p1002 tp1003 a(g185 V tp1004 a(g123 Vif p1005 tp1006 a(g185 V tp1007 a(g18 Vi tp1008 a(g185 V tp1009 a(g339 V< tp1010 a(g185 V tp1011 a(g314 V0 tp1012 a(g185 V tp1013 a(g123 Vthen p1014 tp1015 a(g185 V tp1016 a(g18 Vg tp1017 a(g185 V tp1018 a(g198 V( tp1019 a(g135 VN tp1020 a(g185 V tp1021 a(g198 V( tp1022 a(g18 Vabs p1023 tp1024 a(g185 V tp1025 a(g18 Vi tp1026 a(g185 V tp1027 a(g339 V- tp1028 a(g185 V tp1029 a(g314 V1 tp1030 a(g198 V) tp1031 a(g198 V) tp1032 a(g185 V\u000a p1033 tp1034 a(g123 Velse p1035 tp1036 a(g185 V tp1037 a(g18 Vz tp1038 a(g185 V\u000a p1039 tp1040 a(g339 V| tp1041 a(g185 V tp1042 a(g18 Vz tp1043 a(g185 V tp1044 a(g343 V<- p1045 tp1046 a(g185 V tp1047 a(g18 Valts0 p1048 tp1049 a(g185 V tp1050 a(g18 Vd tp1051 a(g198 V, tp1052 a(g185 V tp1053 a(g18 Vf tp1054 a(g185 V tp1055 a(g343 V<- p1056 tp1057 a(g185 V tp1058 a(g18 Valts1 p1059 tp1060 a(g185 V tp1061 a(g18 Vd tp1062 a(g198 V, tp1063 a(g185 V tp1064 a(g18 Vg tp1065 a(g185 V tp1066 a(g343 V<- p1067 tp1068 a(g185 V tp1069 a(g18 Valts1 p1070 tp1071 a(g185 V tp1072 a(g18 Vd tp1073 a(g185 V tp1074 a(g198 V] tp1075 a(g185 V\u000a\u000a p1076 tp1077 a(g123 Vinstance p1078 tp1079 a(g185 V tp1080 a(g135 VSerial p1081 tp1082 a(g185 V tp1083 a(g135 VInteger p1084 tp1085 a(g185 V tp1086 a(g123 Vwhere p1087 tp1088 a(g185 V\u000a p1089 tp1090 a(g18 Vseries p1091 tp1092 a(g185 V p1093 tp1094 a(g18 Vd tp1095 a(g185 V tp1096 a(g343 V= tp1097 a(g185 V tp1098 a(g198 V[ tp1099 a(g185 V tp1100 a(g18 VtoInteger p1101 tp1102 a(g185 V tp1103 a(g198 V( tp1104 a(g18 Vi tp1105 a(g185 V tp1106 a(g343 V:: p1107 tp1108 a(g185 V tp1109 a(g135 VInt p1110 tp1111 a(g198 V) tp1112 a(g185 V\u000a p1113 tp1114 a(g339 V| tp1115 a(g185 V tp1116 a(g18 Vi tp1117 a(g185 V tp1118 a(g343 V<- p1119 tp1120 a(g185 V tp1121 a(g18 Vseries p1122 tp1123 a(g185 V tp1124 a(g18 Vd tp1125 a(g185 V tp1126 a(g198 V] tp1127 a(g185 V\u000a p1128 tp1129 a(g18 Vcoseries p1130 tp1131 a(g185 V tp1132 a(g18 Vd tp1133 a(g185 V tp1134 a(g343 V= tp1135 a(g185 V tp1136 a(g198 V[ tp1137 a(g185 V tp1138 a(g18 Vf tp1139 a(g185 V tp1140 a(g339 V. tp1141 a(g185 V tp1142 a(g198 V( tp1143 a(g18 VfromInteger p1144 tp1145 a(g185 V tp1146 a(g343 V:: p1147 tp1148 a(g185 V tp1149 a(g135 VInteger p1150 tp1151 a(g343 V-> p1152 tp1153 a(g135 VInt p1154 tp1155 a(g198 V) tp1156 a(g185 V\u000a p1157 tp1158 a(g339 V| tp1159 a(g185 V tp1160 a(g18 Vf tp1161 a(g185 V tp1162 a(g343 V<- p1163 tp1164 a(g185 V tp1165 a(g18 Vseries p1166 tp1167 a(g185 V tp1168 a(g18 Vd tp1169 a(g185 V tp1170 a(g198 V] tp1171 a(g185 V\u000a\u000a p1172 tp1173 a(g123 Vnewtype p1174 tp1175 a(g185 V tp1176 a(g135 VN tp1177 a(g185 V tp1178 a(g18 Va tp1179 a(g185 V tp1180 a(g343 V= tp1181 a(g185 V tp1182 a(g135 VN tp1183 a(g185 V tp1184 a(g18 Va tp1185 a(g185 V\u000a\u000a p1186 tp1187 a(g123 Vinstance p1188 tp1189 a(g185 V tp1190 a(g135 VShow p1191 tp1192 a(g185 V tp1193 a(g18 Va tp1194 a(g185 V tp1195 a(g343 V=> p1196 tp1197 a(g185 V tp1198 a(g135 VShow p1199 tp1200 a(g185 V tp1201 a(g198 V( tp1202 a(g135 VN tp1203 a(g185 V tp1204 a(g18 Va tp1205 a(g198 V) tp1206 a(g185 V tp1207 a(g123 Vwhere p1208 tp1209 a(g185 V\u000a p1210 tp1211 a(g18 Vshow p1212 tp1213 a(g185 V tp1214 a(g198 V( tp1215 a(g135 VN tp1216 a(g185 V tp1217 a(g18 Vi tp1218 a(g198 V) tp1219 a(g185 V tp1220 a(g343 V= tp1221 a(g185 V tp1222 a(g18 Vshow p1223 tp1224 a(g185 V tp1225 a(g18 Vi tp1226 a(g185 V\u000a\u000a p1227 tp1228 a(g123 Vinstance p1229 tp1230 a(g185 V tp1231 a(g198 V( tp1232 a(g135 VIntegral p1233 tp1234 a(g185 V tp1235 a(g18 Va tp1236 a(g198 V, tp1237 a(g185 V tp1238 a(g135 VSerial p1239 tp1240 a(g185 V tp1241 a(g18 Va tp1242 a(g198 V) tp1243 a(g185 V tp1244 a(g343 V=> p1245 tp1246 a(g185 V tp1247 a(g135 VSerial p1248 tp1249 a(g185 V tp1250 a(g198 V( tp1251 a(g135 VN tp1252 a(g185 V tp1253 a(g18 Va tp1254 a(g198 V) tp1255 a(g185 V tp1256 a(g123 Vwhere p1257 tp1258 a(g185 V\u000a p1259 tp1260 a(g18 Vseries p1261 tp1262 a(g185 V p1263 tp1264 a(g18 Vd tp1265 a(g185 V tp1266 a(g343 V= tp1267 a(g185 V tp1268 a(g18 Vmap p1269 tp1270 a(g185 V tp1271 a(g135 VN tp1272 a(g185 V tp1273 a(g198 V[ tp1274 a(g314 V0 tp1275 a(g339 V.. p1276 tp1277 a(g18 Vd' p1278 tp1279 a(g198 V] tp1280 a(g185 V\u000a p1281 tp1282 a(g123 Vwhere p1283 tp1284 a(g185 V\u000a p1285 tp1286 a(g18 Vd' p1287 tp1288 a(g185 V tp1289 a(g343 V= tp1290 a(g185 V tp1291 a(g18 VfromInteger p1292 tp1293 a(g185 V tp1294 a(g198 V( tp1295 a(g18 VtoInteger p1296 tp1297 a(g185 V tp1298 a(g18 Vd tp1299 a(g198 V) tp1300 a(g185 V\u000a p1301 tp1302 a(g18 Vcoseries p1303 tp1304 a(g185 V tp1305 a(g18 Vd tp1306 a(g185 V tp1307 a(g343 V= tp1308 a(g185 V tp1309 a(g198 V[ tp1310 a(g185 V tp1311 a(g21 V\u005c tp1312 a(g198 V( tp1313 a(g135 VN tp1314 a(g185 V tp1315 a(g18 Vi tp1316 a(g198 V) tp1317 a(g185 V tp1318 a(g343 V-> p1319 tp1320 a(g185 V tp1321 a(g123 Vif p1322 tp1323 a(g185 V tp1324 a(g18 Vi tp1325 a(g185 V tp1326 a(g339 V> tp1327 a(g185 V tp1328 a(g314 V0 tp1329 a(g185 V tp1330 a(g123 Vthen p1331 tp1332 a(g185 V tp1333 a(g18 Vf tp1334 a(g185 V tp1335 a(g198 V( tp1336 a(g135 VN tp1337 a(g185 V tp1338 a(g198 V( tp1339 a(g18 Vi tp1340 a(g185 V tp1341 a(g339 V- tp1342 a(g185 V tp1343 a(g314 V1 tp1344 a(g198 V) tp1345 a(g198 V) tp1346 a(g185 V\u000a p1347 tp1348 a(g123 Velse p1349 tp1350 a(g185 V tp1351 a(g18 Vz tp1352 a(g185 V\u000a p1353 tp1354 a(g339 V| tp1355 a(g185 V tp1356 a(g18 Vz tp1357 a(g185 V tp1358 a(g343 V<- p1359 tp1360 a(g185 V tp1361 a(g18 Valts0 p1362 tp1363 a(g185 V tp1364 a(g18 Vd tp1365 a(g198 V, tp1366 a(g185 V tp1367 a(g18 Vf tp1368 a(g185 V tp1369 a(g343 V<- p1370 tp1371 a(g185 V tp1372 a(g18 Valts1 p1373 tp1374 a(g185 V tp1375 a(g18 Vd tp1376 a(g185 V tp1377 a(g198 V] tp1378 a(g185 V\u000a\u000a p1379 tp1380 a(g123 Vtype p1381 tp1382 a(g185 V tp1383 a(g135 VNat p1384 tp1385 a(g185 V tp1386 a(g343 V= tp1387 a(g185 V tp1388 a(g135 VN tp1389 a(g185 V tp1390 a(g135 VInt p1391 tp1392 a(g185 V\u000a tp1393 a(g123 Vtype p1394 tp1395 a(g185 V tp1396 a(g135 VNatural p1397 tp1398 a(g185 V tp1399 a(g343 V= tp1400 a(g185 V tp1401 a(g135 VN tp1402 a(g185 V tp1403 a(g135 VInteger p1404 tp1405 a(g185 V\u000a\u000a p1406 tp1407 a(g123 Vinstance p1408 tp1409 a(g185 V tp1410 a(g135 VSerial p1411 tp1412 a(g185 V tp1413 a(g135 VFloat p1414 tp1415 a(g185 V tp1416 a(g123 Vwhere p1417 tp1418 a(g185 V\u000a p1419 tp1420 a(g18 Vseries p1421 tp1422 a(g185 V tp1423 a(g18 Vd tp1424 a(g185 V p1425 tp1426 a(g343 V= tp1427 a(g185 V tp1428 a(g198 V[ tp1429 a(g185 V tp1430 a(g18 VencodeFloat p1431 tp1432 a(g185 V tp1433 a(g18 Vsig p1434 tp1435 a(g185 V tp1436 a(g18 Vexp p1437 tp1438 a(g185 V\u000a p1439 tp1440 a(g339 V| tp1441 a(g185 V tp1442 a(g198 V( tp1443 a(g18 Vsig p1444 tp1445 a(g198 V, tp1446 a(g18 Vexp p1447 tp1448 a(g198 V) tp1449 a(g185 V tp1450 a(g343 V<- p1451 tp1452 a(g185 V tp1453 a(g18 Vseries p1454 tp1455 a(g185 V tp1456 a(g18 Vd tp1457 a(g198 V, tp1458 a(g185 V\u000a p1459 tp1460 a(g18 Vodd p1461 tp1462 a(g185 V tp1463 a(g18 Vsig p1464 tp1465 a(g185 V tp1466 a(g339 V|| p1467 tp1468 a(g185 V tp1469 a(g18 Vsig p1470 tp1471 a(g339 V== p1472 tp1473 a(g314 V0 tp1474 a(g185 V tp1475 a(g339 V&& p1476 tp1477 a(g185 V tp1478 a(g18 Vexp p1479 tp1480 a(g339 V== p1481 tp1482 a(g314 V0 tp1483 a(g185 V tp1484 a(g198 V] tp1485 a(g185 V\u000a p1486 tp1487 a(g18 Vcoseries p1488 tp1489 a(g185 V tp1490 a(g18 Vd tp1491 a(g185 V tp1492 a(g343 V= tp1493 a(g185 V tp1494 a(g198 V[ tp1495 a(g185 V tp1496 a(g18 Vf tp1497 a(g185 V tp1498 a(g339 V. tp1499 a(g185 V tp1500 a(g18 VdecodeFloat p1501 tp1502 a(g185 V\u000a p1503 tp1504 a(g339 V| tp1505 a(g185 V tp1506 a(g18 Vf tp1507 a(g185 V tp1508 a(g343 V<- p1509 tp1510 a(g185 V tp1511 a(g18 Vseries p1512 tp1513 a(g185 V tp1514 a(g18 Vd tp1515 a(g185 V tp1516 a(g198 V] tp1517 a(g185 V\u000a \u000a p1518 tp1519 a(g123 Vinstance p1520 tp1521 a(g185 V tp1522 a(g135 VSerial p1523 tp1524 a(g185 V tp1525 a(g135 VDouble p1526 tp1527 a(g185 V tp1528 a(g123 Vwhere p1529 tp1530 a(g185 V\u000a p1531 tp1532 a(g18 Vseries p1533 tp1534 a(g185 V p1535 tp1536 a(g18 Vd tp1537 a(g185 V tp1538 a(g343 V= tp1539 a(g185 V tp1540 a(g198 V[ tp1541 a(g185 V tp1542 a(g18 Vfrac p1543 tp1544 a(g185 V tp1545 a(g198 V( tp1546 a(g18 Vx tp1547 a(g185 V tp1548 a(g343 V:: p1549 tp1550 a(g185 V tp1551 a(g135 VFloat p1552 tp1553 a(g198 V) tp1554 a(g185 V\u000a p1555 tp1556 a(g339 V| tp1557 a(g185 V tp1558 a(g18 Vx tp1559 a(g185 V tp1560 a(g343 V<- p1561 tp1562 a(g185 V tp1563 a(g18 Vseries p1564 tp1565 a(g185 V tp1566 a(g18 Vd tp1567 a(g185 V tp1568 a(g198 V] tp1569 a(g185 V\u000a p1570 tp1571 a(g18 Vcoseries p1572 tp1573 a(g185 V tp1574 a(g18 Vd tp1575 a(g185 V tp1576 a(g343 V= tp1577 a(g185 V tp1578 a(g198 V[ tp1579 a(g185 V tp1580 a(g18 Vf tp1581 a(g185 V tp1582 a(g339 V. tp1583 a(g185 V tp1584 a(g198 V( tp1585 a(g18 Vfrac p1586 tp1587 a(g185 V tp1588 a(g343 V:: p1589 tp1590 a(g185 V tp1591 a(g135 VDouble p1592 tp1593 a(g343 V-> p1594 tp1595 a(g135 VFloat p1596 tp1597 a(g198 V) tp1598 a(g185 V\u000a p1599 tp1600 a(g339 V| tp1601 a(g185 V tp1602 a(g18 Vf tp1603 a(g185 V tp1604 a(g343 V<- p1605 tp1606 a(g185 V tp1607 a(g18 Vseries p1608 tp1609 a(g185 V tp1610 a(g18 Vd tp1611 a(g185 V tp1612 a(g198 V] tp1613 a(g185 V\u000a\u000a p1614 tp1615 a(g21 Vfrac p1616 tp1617 a(g185 V tp1618 a(g343 V:: p1619 tp1620 a(g185 V tp1621 a(g198 V( tp1622 a(g135 VReal p1623 tp1624 a(g185 V tp1625 a(g18 Va tp1626 a(g198 V, tp1627 a(g185 V tp1628 a(g135 VFractional p1629 tp1630 a(g185 V tp1631 a(g18 Va tp1632 a(g198 V, tp1633 a(g185 V tp1634 a(g135 VReal p1635 tp1636 a(g185 V tp1637 a(g18 Vb tp1638 a(g198 V, tp1639 a(g185 V tp1640 a(g135 VFractional p1641 tp1642 a(g185 V tp1643 a(g18 Vb tp1644 a(g198 V) tp1645 a(g185 V tp1646 a(g343 V=> p1647 tp1648 a(g185 V tp1649 a(g18 Va tp1650 a(g185 V tp1651 a(g343 V-> p1652 tp1653 a(g185 V tp1654 a(g18 Vb tp1655 a(g185 V\u000a tp1656 a(g21 Vfrac p1657 tp1658 a(g185 V tp1659 a(g343 V= tp1660 a(g185 V tp1661 a(g18 VfromRational p1662 tp1663 a(g185 V tp1664 a(g339 V. tp1665 a(g185 V tp1666 a(g18 VtoRational p1667 tp1668 a(g185 V\u000a\u000a p1669 tp1670 a(g123 Vinstance p1671 tp1672 a(g185 V tp1673 a(g135 VSerial p1674 tp1675 a(g185 V tp1676 a(g135 VChar p1677 tp1678 a(g185 V tp1679 a(g123 Vwhere p1680 tp1681 a(g185 V\u000a p1682 tp1683 a(g18 Vseries p1684 tp1685 a(g185 V tp1686 a(g18 Vd tp1687 a(g185 V p1688 tp1689 a(g343 V= tp1690 a(g185 V tp1691 a(g18 Vtake p1692 tp1693 a(g185 V tp1694 a(g198 V( tp1695 a(g18 Vd tp1696 a(g339 V+ tp1697 a(g314 V1 tp1698 a(g198 V) tp1699 a(g185 V tp1700 a(g198 V[ tp1701 a(g264 V' tp1702 a(g264 Va tp1703 a(g264 V' tp1704 a(g339 V.. p1705 tp1706 a(g264 V' tp1707 a(g264 Vz tp1708 a(g264 V' tp1709 a(g198 V] tp1710 a(g185 V\u000a p1711 tp1712 a(g18 Vcoseries p1713 tp1714 a(g185 V tp1715 a(g18 Vd tp1716 a(g185 V tp1717 a(g343 V= tp1718 a(g185 V tp1719 a(g198 V[ tp1720 a(g185 V tp1721 a(g21 V\u005c tp1722 a(g18 Vc tp1723 a(g185 V tp1724 a(g343 V-> p1725 tp1726 a(g185 V tp1727 a(g18 Vf tp1728 a(g185 V tp1729 a(g198 V( tp1730 a(g135 VN tp1731 a(g185 V tp1732 a(g198 V( tp1733 a(g18 VfromEnum p1734 tp1735 a(g185 V tp1736 a(g18 Vc tp1737 a(g185 V tp1738 a(g339 V- tp1739 a(g185 V tp1740 a(g18 VfromEnum p1741 tp1742 a(g185 V tp1743 a(g264 V' tp1744 a(g264 Va tp1745 a(g264 V' tp1746 a(g198 V) tp1747 a(g198 V) tp1748 a(g185 V\u000a p1749 tp1750 a(g339 V| tp1751 a(g185 V tp1752 a(g18 Vf tp1753 a(g185 V tp1754 a(g343 V<- p1755 tp1756 a(g185 V tp1757 a(g18 Vseries p1758 tp1759 a(g185 V tp1760 a(g18 Vd tp1761 a(g185 V tp1762 a(g198 V] tp1763 a(g185 V\u000a\u000a p1764 tp1765 a(g123 Vinstance p1766 tp1767 a(g185 V tp1768 a(g198 V( tp1769 a(g135 VSerial p1770 tp1771 a(g185 V tp1772 a(g18 Va tp1773 a(g198 V, tp1774 a(g185 V tp1775 a(g135 VSerial p1776 tp1777 a(g185 V tp1778 a(g18 Vb tp1779 a(g198 V) tp1780 a(g185 V tp1781 a(g343 V=> p1782 tp1783 a(g185 V\u000a p1784 tp1785 a(g135 VSerial p1786 tp1787 a(g185 V tp1788 a(g198 V( tp1789 a(g18 Va tp1790 a(g198 V, tp1791 a(g18 Vb tp1792 a(g198 V) tp1793 a(g185 V tp1794 a(g123 Vwhere p1795 tp1796 a(g185 V\u000a p1797 tp1798 a(g18 Vseries p1799 tp1800 a(g185 V p1801 tp1802 a(g343 V= tp1803 a(g185 V tp1804 a(g18 Vseries p1805 tp1806 a(g185 V tp1807 a(g339 V>< p1808 tp1809 a(g185 V tp1810 a(g18 Vseries p1811 tp1812 a(g185 V\u000a p1813 tp1814 a(g18 Vcoseries p1815 tp1816 a(g185 V tp1817 a(g343 V= tp1818 a(g185 V tp1819 a(g18 Vmap p1820 tp1821 a(g185 V tp1822 a(g18 Vuncurry p1823 tp1824 a(g185 V tp1825 a(g339 V. tp1826 a(g185 V tp1827 a(g18 Vcoseries p1828 tp1829 a(g185 V\u000a\u000a p1830 tp1831 a(g123 Vinstance p1832 tp1833 a(g185 V tp1834 a(g198 V( tp1835 a(g135 VSerial p1836 tp1837 a(g185 V tp1838 a(g18 Va tp1839 a(g198 V, tp1840 a(g185 V tp1841 a(g135 VSerial p1842 tp1843 a(g185 V tp1844 a(g18 Vb tp1845 a(g198 V, tp1846 a(g185 V tp1847 a(g135 VSerial p1848 tp1849 a(g185 V tp1850 a(g18 Vc tp1851 a(g198 V) tp1852 a(g185 V tp1853 a(g343 V=> p1854 tp1855 a(g185 V\u000a p1856 tp1857 a(g135 VSerial p1858 tp1859 a(g185 V tp1860 a(g198 V( tp1861 a(g18 Va tp1862 a(g198 V, tp1863 a(g18 Vb tp1864 a(g198 V, tp1865 a(g18 Vc tp1866 a(g198 V) tp1867 a(g185 V tp1868 a(g123 Vwhere p1869 tp1870 a(g185 V\u000a p1871 tp1872 a(g18 Vseries p1873 tp1874 a(g185 V p1875 tp1876 a(g343 V= tp1877 a(g185 V tp1878 a(g21 V\u005c tp1879 a(g18 Vd tp1880 a(g185 V tp1881 a(g343 V-> p1882 tp1883 a(g185 V tp1884 a(g198 V[ tp1885 a(g198 V( tp1886 a(g18 Va tp1887 a(g198 V, tp1888 a(g18 Vb tp1889 a(g198 V, tp1890 a(g18 Vc tp1891 a(g198 V) tp1892 a(g185 V tp1893 a(g339 V| tp1894 a(g185 V tp1895 a(g198 V( tp1896 a(g18 Va tp1897 a(g198 V, tp1898 a(g198 V( tp1899 a(g18 Vb tp1900 a(g198 V, tp1901 a(g18 Vc tp1902 a(g198 V) tp1903 a(g198 V) tp1904 a(g185 V tp1905 a(g343 V<- p1906 tp1907 a(g185 V tp1908 a(g18 Vseries p1909 tp1910 a(g185 V tp1911 a(g18 Vd tp1912 a(g198 V] tp1913 a(g185 V\u000a p1914 tp1915 a(g18 Vcoseries p1916 tp1917 a(g185 V tp1918 a(g343 V= tp1919 a(g185 V tp1920 a(g18 Vmap p1921 tp1922 a(g185 V tp1923 a(g18 Vuncurry3 p1924 tp1925 a(g185 V tp1926 a(g339 V. tp1927 a(g185 V tp1928 a(g18 Vcoseries p1929 tp1930 a(g185 V\u000a\u000a p1931 tp1932 a(g123 Vinstance p1933 tp1934 a(g185 V tp1935 a(g198 V( tp1936 a(g135 VSerial p1937 tp1938 a(g185 V tp1939 a(g18 Va tp1940 a(g198 V, tp1941 a(g185 V tp1942 a(g135 VSerial p1943 tp1944 a(g185 V tp1945 a(g18 Vb tp1946 a(g198 V, tp1947 a(g185 V tp1948 a(g135 VSerial p1949 tp1950 a(g185 V tp1951 a(g18 Vc tp1952 a(g198 V, tp1953 a(g185 V tp1954 a(g135 VSerial p1955 tp1956 a(g185 V tp1957 a(g18 Vd tp1958 a(g198 V) tp1959 a(g185 V tp1960 a(g343 V=> p1961 tp1962 a(g185 V\u000a p1963 tp1964 a(g135 VSerial p1965 tp1966 a(g185 V tp1967 a(g198 V( tp1968 a(g18 Va tp1969 a(g198 V, tp1970 a(g18 Vb tp1971 a(g198 V, tp1972 a(g18 Vc tp1973 a(g198 V, tp1974 a(g18 Vd tp1975 a(g198 V) tp1976 a(g185 V tp1977 a(g123 Vwhere p1978 tp1979 a(g185 V\u000a p1980 tp1981 a(g18 Vseries p1982 tp1983 a(g185 V p1984 tp1985 a(g343 V= tp1986 a(g185 V tp1987 a(g21 V\u005c tp1988 a(g18 Vd tp1989 a(g185 V tp1990 a(g343 V-> p1991 tp1992 a(g185 V tp1993 a(g198 V[ tp1994 a(g198 V( tp1995 a(g18 Va tp1996 a(g198 V, tp1997 a(g18 Vb tp1998 a(g198 V, tp1999 a(g18 Vc tp2000 a(g198 V, tp2001 a(g18 Vd tp2002 a(g198 V) tp2003 a(g185 V tp2004 a(g339 V| tp2005 a(g185 V tp2006 a(g198 V( tp2007 a(g18 Va tp2008 a(g198 V, tp2009 a(g198 V( tp2010 a(g18 Vb tp2011 a(g198 V, tp2012 a(g198 V( tp2013 a(g18 Vc tp2014 a(g198 V, tp2015 a(g18 Vd tp2016 a(g198 V) tp2017 a(g198 V) tp2018 a(g198 V) tp2019 a(g185 V tp2020 a(g343 V<- p2021 tp2022 a(g185 V tp2023 a(g18 Vseries p2024 tp2025 a(g185 V tp2026 a(g18 Vd tp2027 a(g198 V] tp2028 a(g185 V\u000a p2029 tp2030 a(g18 Vcoseries p2031 tp2032 a(g185 V tp2033 a(g343 V= tp2034 a(g185 V tp2035 a(g18 Vmap p2036 tp2037 a(g185 V tp2038 a(g18 Vuncurry4 p2039 tp2040 a(g185 V tp2041 a(g339 V. tp2042 a(g185 V tp2043 a(g18 Vcoseries p2044 tp2045 a(g185 V\u000a\u000a p2046 tp2047 a(g21 Vuncurry3 p2048 tp2049 a(g185 V tp2050 a(g343 V:: p2051 tp2052 a(g185 V tp2053 a(g198 V( tp2054 a(g18 Va tp2055 a(g343 V-> p2056 tp2057 a(g18 Vb tp2058 a(g343 V-> p2059 tp2060 a(g18 Vc tp2061 a(g343 V-> p2062 tp2063 a(g18 Vd tp2064 a(g198 V) tp2065 a(g185 V tp2066 a(g343 V-> p2067 tp2068 a(g185 V tp2069 a(g198 V( tp2070 a(g198 V( tp2071 a(g18 Va tp2072 a(g198 V, tp2073 a(g18 Vb tp2074 a(g198 V, tp2075 a(g18 Vc tp2076 a(g198 V) tp2077 a(g343 V-> p2078 tp2079 a(g18 Vd tp2080 a(g198 V) tp2081 a(g185 V\u000a tp2082 a(g21 Vuncurry3 p2083 tp2084 a(g185 V tp2085 a(g18 Vf tp2086 a(g185 V tp2087 a(g198 V( tp2088 a(g18 Vx tp2089 a(g198 V, tp2090 a(g18 Vy tp2091 a(g198 V, tp2092 a(g18 Vz tp2093 a(g198 V) tp2094 a(g185 V tp2095 a(g343 V= tp2096 a(g185 V tp2097 a(g18 Vf tp2098 a(g185 V tp2099 a(g18 Vx tp2100 a(g185 V tp2101 a(g18 Vy tp2102 a(g185 V tp2103 a(g18 Vz tp2104 a(g185 V\u000a\u000a p2105 tp2106 a(g21 Vuncurry4 p2107 tp2108 a(g185 V tp2109 a(g343 V:: p2110 tp2111 a(g185 V tp2112 a(g198 V( tp2113 a(g18 Va tp2114 a(g343 V-> p2115 tp2116 a(g18 Vb tp2117 a(g343 V-> p2118 tp2119 a(g18 Vc tp2120 a(g343 V-> p2121 tp2122 a(g18 Vd tp2123 a(g343 V-> p2124 tp2125 a(g18 Ve tp2126 a(g198 V) tp2127 a(g185 V tp2128 a(g343 V-> p2129 tp2130 a(g185 V tp2131 a(g198 V( tp2132 a(g198 V( tp2133 a(g18 Va tp2134 a(g198 V, tp2135 a(g18 Vb tp2136 a(g198 V, tp2137 a(g18 Vc tp2138 a(g198 V, tp2139 a(g18 Vd tp2140 a(g198 V) tp2141 a(g343 V-> p2142 tp2143 a(g18 Ve tp2144 a(g198 V) tp2145 a(g185 V\u000a tp2146 a(g21 Vuncurry4 p2147 tp2148 a(g185 V tp2149 a(g18 Vf tp2150 a(g185 V tp2151 a(g198 V( tp2152 a(g18 Vw tp2153 a(g198 V, tp2154 a(g18 Vx tp2155 a(g198 V, tp2156 a(g18 Vy tp2157 a(g198 V, tp2158 a(g18 Vz tp2159 a(g198 V) tp2160 a(g185 V tp2161 a(g343 V= tp2162 a(g185 V tp2163 a(g18 Vf tp2164 a(g185 V tp2165 a(g18 Vw tp2166 a(g185 V tp2167 a(g18 Vx tp2168 a(g185 V tp2169 a(g18 Vy tp2170 a(g185 V tp2171 a(g18 Vz tp2172 a(g185 V\u000a\u000a p2173 tp2174 a(g21 Vtwo p2175 tp2176 a(g185 V p2177 tp2178 a(g343 V:: p2179 tp2180 a(g185 V tp2181 a(g135 VSeries p2182 tp2183 a(g185 V tp2184 a(g18 Va tp2185 a(g185 V tp2186 a(g343 V-> p2187 tp2188 a(g185 V tp2189 a(g135 VSeries p2190 tp2191 a(g185 V tp2192 a(g198 V( tp2193 a(g18 Va tp2194 a(g198 V, tp2195 a(g18 Va tp2196 a(g198 V) tp2197 a(g185 V\u000a tp2198 a(g21 Vtwo p2199 tp2200 a(g185 V p2201 tp2202 a(g18 Vs tp2203 a(g185 V tp2204 a(g343 V= tp2205 a(g185 V tp2206 a(g18 Vs tp2207 a(g185 V tp2208 a(g339 V>< p2209 tp2210 a(g185 V tp2211 a(g18 Vs tp2212 a(g185 V\u000a\u000a p2213 tp2214 a(g21 Vthree p2215 tp2216 a(g185 V tp2217 a(g343 V:: p2218 tp2219 a(g185 V tp2220 a(g135 VSeries p2221 tp2222 a(g185 V tp2223 a(g18 Va tp2224 a(g185 V tp2225 a(g343 V-> p2226 tp2227 a(g185 V tp2228 a(g135 VSeries p2229 tp2230 a(g185 V tp2231 a(g198 V( tp2232 a(g18 Va tp2233 a(g198 V, tp2234 a(g18 Va tp2235 a(g198 V, tp2236 a(g18 Va tp2237 a(g198 V) tp2238 a(g185 V\u000a tp2239 a(g21 Vthree p2240 tp2241 a(g185 V tp2242 a(g18 Vs tp2243 a(g185 V tp2244 a(g343 V= tp2245 a(g185 V tp2246 a(g21 V\u005c tp2247 a(g18 Vd tp2248 a(g185 V tp2249 a(g343 V-> p2250 tp2251 a(g185 V tp2252 a(g198 V[ tp2253 a(g198 V( tp2254 a(g18 Vx tp2255 a(g198 V, tp2256 a(g18 Vy tp2257 a(g198 V, tp2258 a(g18 Vz tp2259 a(g198 V) tp2260 a(g185 V tp2261 a(g339 V| tp2262 a(g185 V tp2263 a(g198 V( tp2264 a(g18 Vx tp2265 a(g198 V, tp2266 a(g198 V( tp2267 a(g18 Vy tp2268 a(g198 V, tp2269 a(g18 Vz tp2270 a(g198 V) tp2271 a(g198 V) tp2272 a(g185 V tp2273 a(g343 V<- p2274 tp2275 a(g185 V tp2276 a(g198 V( tp2277 a(g18 Vs tp2278 a(g185 V tp2279 a(g339 V>< p2280 tp2281 a(g185 V tp2282 a(g18 Vs tp2283 a(g185 V tp2284 a(g339 V>< p2285 tp2286 a(g185 V tp2287 a(g18 Vs tp2288 a(g198 V) tp2289 a(g185 V tp2290 a(g18 Vd tp2291 a(g198 V] tp2292 a(g185 V\u000a\u000a p2293 tp2294 a(g21 Vfour p2295 tp2296 a(g185 V p2297 tp2298 a(g343 V:: p2299 tp2300 a(g185 V tp2301 a(g135 VSeries p2302 tp2303 a(g185 V tp2304 a(g18 Va tp2305 a(g185 V tp2306 a(g343 V-> p2307 tp2308 a(g185 V tp2309 a(g135 VSeries p2310 tp2311 a(g185 V tp2312 a(g198 V( tp2313 a(g18 Va tp2314 a(g198 V, tp2315 a(g18 Va tp2316 a(g198 V, tp2317 a(g18 Va tp2318 a(g198 V, tp2319 a(g18 Va tp2320 a(g198 V) tp2321 a(g185 V\u000a tp2322 a(g21 Vfour p2323 tp2324 a(g185 V p2325 tp2326 a(g18 Vs tp2327 a(g185 V tp2328 a(g343 V= tp2329 a(g185 V tp2330 a(g21 V\u005c tp2331 a(g18 Vd tp2332 a(g185 V tp2333 a(g343 V-> p2334 tp2335 a(g185 V tp2336 a(g198 V[ tp2337 a(g198 V( tp2338 a(g18 Vw tp2339 a(g198 V, tp2340 a(g18 Vx tp2341 a(g198 V, tp2342 a(g18 Vy tp2343 a(g198 V, tp2344 a(g18 Vz tp2345 a(g198 V) tp2346 a(g185 V tp2347 a(g339 V| tp2348 a(g185 V tp2349 a(g198 V( tp2350 a(g18 Vw tp2351 a(g198 V, tp2352 a(g198 V( tp2353 a(g18 Vx tp2354 a(g198 V, tp2355 a(g198 V( tp2356 a(g18 Vy tp2357 a(g198 V, tp2358 a(g18 Vz tp2359 a(g198 V) tp2360 a(g198 V) tp2361 a(g198 V) tp2362 a(g185 V tp2363 a(g343 V<- p2364 tp2365 a(g185 V tp2366 a(g198 V( tp2367 a(g18 Vs tp2368 a(g185 V tp2369 a(g339 V>< p2370 tp2371 a(g185 V tp2372 a(g18 Vs tp2373 a(g185 V tp2374 a(g339 V>< p2375 tp2376 a(g185 V tp2377 a(g18 Vs tp2378 a(g185 V tp2379 a(g339 V>< p2380 tp2381 a(g185 V tp2382 a(g18 Vs tp2383 a(g198 V) tp2384 a(g185 V tp2385 a(g18 Vd tp2386 a(g198 V] tp2387 a(g185 V\u000a\u000a p2388 tp2389 a(g21 Vcons0 p2390 tp2391 a(g185 V tp2392 a(g343 V:: p2393 tp2394 a(g185 V \u000a p2395 tp2396 a(g18 Va tp2397 a(g185 V tp2398 a(g343 V-> p2399 tp2400 a(g185 V tp2401 a(g135 VSeries p2402 tp2403 a(g185 V tp2404 a(g18 Va tp2405 a(g185 V\u000a tp2406 a(g21 Vcons0 p2407 tp2408 a(g185 V tp2409 a(g18 Vc tp2410 a(g185 V tp2411 a(g123 V_ tp2412 a(g185 V tp2413 a(g343 V= tp2414 a(g185 V tp2415 a(g198 V[ tp2416 a(g18 Vc tp2417 a(g198 V] tp2418 a(g185 V\u000a\u000a p2419 tp2420 a(g21 Vcons1 p2421 tp2422 a(g185 V tp2423 a(g343 V:: p2424 tp2425 a(g185 V tp2426 a(g135 VSerial p2427 tp2428 a(g185 V tp2429 a(g18 Va tp2430 a(g185 V tp2431 a(g343 V=> p2432 tp2433 a(g185 V\u000a p2434 tp2435 a(g198 V( tp2436 a(g18 Va tp2437 a(g343 V-> p2438 tp2439 a(g18 Vb tp2440 a(g198 V) tp2441 a(g185 V tp2442 a(g343 V-> p2443 tp2444 a(g185 V tp2445 a(g135 VSeries p2446 tp2447 a(g185 V tp2448 a(g18 Vb tp2449 a(g185 V\u000a tp2450 a(g21 Vcons1 p2451 tp2452 a(g185 V tp2453 a(g18 Vc tp2454 a(g185 V tp2455 a(g18 Vd tp2456 a(g185 V tp2457 a(g343 V= tp2458 a(g185 V tp2459 a(g198 V[ tp2460 a(g18 Vc tp2461 a(g185 V tp2462 a(g18 Vz tp2463 a(g185 V tp2464 a(g339 V| tp2465 a(g185 V tp2466 a(g18 Vd tp2467 a(g185 V tp2468 a(g339 V> tp2469 a(g185 V tp2470 a(g314 V0 tp2471 a(g198 V, tp2472 a(g185 V tp2473 a(g18 Vz tp2474 a(g185 V tp2475 a(g343 V<- p2476 tp2477 a(g185 V tp2478 a(g18 Vseries p2479 tp2480 a(g185 V tp2481 a(g198 V( tp2482 a(g18 Vd tp2483 a(g339 V- tp2484 a(g314 V1 tp2485 a(g198 V) tp2486 a(g198 V] tp2487 a(g185 V\u000a\u000a p2488 tp2489 a(g21 Vcons2 p2490 tp2491 a(g185 V tp2492 a(g343 V:: p2493 tp2494 a(g185 V tp2495 a(g198 V( tp2496 a(g135 VSerial p2497 tp2498 a(g185 V tp2499 a(g18 Va tp2500 a(g198 V, tp2501 a(g185 V tp2502 a(g135 VSerial p2503 tp2504 a(g185 V tp2505 a(g18 Vb tp2506 a(g198 V) tp2507 a(g185 V tp2508 a(g343 V=> p2509 tp2510 a(g185 V\u000a p2511 tp2512 a(g198 V( tp2513 a(g18 Va tp2514 a(g343 V-> p2515 tp2516 a(g18 Vb tp2517 a(g343 V-> p2518 tp2519 a(g18 Vc tp2520 a(g198 V) tp2521 a(g185 V tp2522 a(g343 V-> p2523 tp2524 a(g185 V tp2525 a(g135 VSeries p2526 tp2527 a(g185 V tp2528 a(g18 Vc tp2529 a(g185 V\u000a tp2530 a(g21 Vcons2 p2531 tp2532 a(g185 V tp2533 a(g18 Vc tp2534 a(g185 V tp2535 a(g18 Vd tp2536 a(g185 V tp2537 a(g343 V= tp2538 a(g185 V tp2539 a(g198 V[ tp2540 a(g18 Vc tp2541 a(g185 V tp2542 a(g18 Vy tp2543 a(g185 V tp2544 a(g18 Vz tp2545 a(g185 V tp2546 a(g339 V| tp2547 a(g185 V tp2548 a(g18 Vd tp2549 a(g185 V tp2550 a(g339 V> tp2551 a(g185 V tp2552 a(g314 V0 tp2553 a(g198 V, tp2554 a(g185 V tp2555 a(g198 V( tp2556 a(g18 Vy tp2557 a(g198 V, tp2558 a(g18 Vz tp2559 a(g198 V) tp2560 a(g185 V tp2561 a(g343 V<- p2562 tp2563 a(g185 V tp2564 a(g18 Vseries p2565 tp2566 a(g185 V tp2567 a(g198 V( tp2568 a(g18 Vd tp2569 a(g339 V- tp2570 a(g314 V1 tp2571 a(g198 V) tp2572 a(g198 V] tp2573 a(g185 V\u000a\u000a p2574 tp2575 a(g21 Vcons3 p2576 tp2577 a(g185 V tp2578 a(g343 V:: p2579 tp2580 a(g185 V tp2581 a(g198 V( tp2582 a(g135 VSerial p2583 tp2584 a(g185 V tp2585 a(g18 Va tp2586 a(g198 V, tp2587 a(g185 V tp2588 a(g135 VSerial p2589 tp2590 a(g185 V tp2591 a(g18 Vb tp2592 a(g198 V, tp2593 a(g185 V tp2594 a(g135 VSerial p2595 tp2596 a(g185 V tp2597 a(g18 Vc tp2598 a(g198 V) tp2599 a(g185 V tp2600 a(g343 V=> p2601 tp2602 a(g185 V\u000a p2603 tp2604 a(g198 V( tp2605 a(g18 Va tp2606 a(g343 V-> p2607 tp2608 a(g18 Vb tp2609 a(g343 V-> p2610 tp2611 a(g18 Vc tp2612 a(g343 V-> p2613 tp2614 a(g18 Vd tp2615 a(g198 V) tp2616 a(g185 V tp2617 a(g343 V-> p2618 tp2619 a(g185 V tp2620 a(g135 VSeries p2621 tp2622 a(g185 V tp2623 a(g18 Vd tp2624 a(g185 V\u000a tp2625 a(g21 Vcons3 p2626 tp2627 a(g185 V tp2628 a(g18 Vc tp2629 a(g185 V tp2630 a(g18 Vd tp2631 a(g185 V tp2632 a(g343 V= tp2633 a(g185 V tp2634 a(g198 V[ tp2635 a(g18 Vc tp2636 a(g185 V tp2637 a(g18 Vx tp2638 a(g185 V tp2639 a(g18 Vy tp2640 a(g185 V tp2641 a(g18 Vz tp2642 a(g185 V tp2643 a(g339 V| tp2644 a(g185 V tp2645 a(g18 Vd tp2646 a(g185 V tp2647 a(g339 V> tp2648 a(g185 V tp2649 a(g314 V0 tp2650 a(g198 V, tp2651 a(g185 V tp2652 a(g198 V( tp2653 a(g18 Vx tp2654 a(g198 V, tp2655 a(g18 Vy tp2656 a(g198 V, tp2657 a(g18 Vz tp2658 a(g198 V) tp2659 a(g185 V tp2660 a(g343 V<- p2661 tp2662 a(g185 V tp2663 a(g18 Vseries p2664 tp2665 a(g185 V tp2666 a(g198 V( tp2667 a(g18 Vd tp2668 a(g339 V- tp2669 a(g314 V1 tp2670 a(g198 V) tp2671 a(g198 V] tp2672 a(g185 V\u000a\u000a p2673 tp2674 a(g21 Vcons4 p2675 tp2676 a(g185 V tp2677 a(g343 V:: p2678 tp2679 a(g185 V tp2680 a(g198 V( tp2681 a(g135 VSerial p2682 tp2683 a(g185 V tp2684 a(g18 Va tp2685 a(g198 V, tp2686 a(g185 V tp2687 a(g135 VSerial p2688 tp2689 a(g185 V tp2690 a(g18 Vb tp2691 a(g198 V, tp2692 a(g185 V tp2693 a(g135 VSerial p2694 tp2695 a(g185 V tp2696 a(g18 Vc tp2697 a(g198 V, tp2698 a(g185 V tp2699 a(g135 VSerial p2700 tp2701 a(g185 V tp2702 a(g18 Vd tp2703 a(g198 V) tp2704 a(g185 V tp2705 a(g343 V=> p2706 tp2707 a(g185 V\u000a p2708 tp2709 a(g198 V( tp2710 a(g18 Va tp2711 a(g343 V-> p2712 tp2713 a(g18 Vb tp2714 a(g343 V-> p2715 tp2716 a(g18 Vc tp2717 a(g343 V-> p2718 tp2719 a(g18 Vd tp2720 a(g343 V-> p2721 tp2722 a(g18 Ve tp2723 a(g198 V) tp2724 a(g185 V tp2725 a(g343 V-> p2726 tp2727 a(g185 V tp2728 a(g135 VSeries p2729 tp2730 a(g185 V tp2731 a(g18 Ve tp2732 a(g185 V\u000a tp2733 a(g21 Vcons4 p2734 tp2735 a(g185 V tp2736 a(g18 Vc tp2737 a(g185 V tp2738 a(g18 Vd tp2739 a(g185 V tp2740 a(g343 V= tp2741 a(g185 V tp2742 a(g198 V[ tp2743 a(g18 Vc tp2744 a(g185 V tp2745 a(g18 Vw tp2746 a(g185 V tp2747 a(g18 Vx tp2748 a(g185 V tp2749 a(g18 Vy tp2750 a(g185 V tp2751 a(g18 Vz tp2752 a(g185 V tp2753 a(g339 V| tp2754 a(g185 V tp2755 a(g18 Vd tp2756 a(g185 V tp2757 a(g339 V> tp2758 a(g185 V tp2759 a(g314 V0 tp2760 a(g198 V, tp2761 a(g185 V tp2762 a(g198 V( tp2763 a(g18 Vw tp2764 a(g198 V, tp2765 a(g18 Vx tp2766 a(g198 V, tp2767 a(g18 Vy tp2768 a(g198 V, tp2769 a(g18 Vz tp2770 a(g198 V) tp2771 a(g185 V tp2772 a(g343 V<- p2773 tp2774 a(g185 V tp2775 a(g18 Vseries p2776 tp2777 a(g185 V tp2778 a(g198 V( tp2779 a(g18 Vd tp2780 a(g339 V- tp2781 a(g314 V1 tp2782 a(g198 V) tp2783 a(g198 V] tp2784 a(g185 V\u000a\u000a p2785 tp2786 a(g21 Valts0 p2787 tp2788 a(g185 V tp2789 a(g343 V:: p2790 tp2791 a(g185 V p2792 tp2793 a(g135 VSerial p2794 tp2795 a(g185 V tp2796 a(g18 Va tp2797 a(g185 V tp2798 a(g343 V=> p2799 tp2800 a(g185 V\u000a p2801 tp2802 a(g135 VSeries p2803 tp2804 a(g185 V tp2805 a(g18 Va tp2806 a(g185 V\u000a tp2807 a(g21 Valts0 p2808 tp2809 a(g185 V tp2810 a(g18 Vd tp2811 a(g185 V tp2812 a(g343 V= tp2813 a(g185 V tp2814 a(g18 Vseries p2815 tp2816 a(g185 V tp2817 a(g18 Vd tp2818 a(g185 V\u000a\u000a p2819 tp2820 a(g21 Valts1 p2821 tp2822 a(g185 V tp2823 a(g343 V:: p2824 tp2825 a(g185 V p2826 tp2827 a(g198 V( tp2828 a(g135 VSerial p2829 tp2830 a(g185 V tp2831 a(g18 Va tp2832 a(g198 V, tp2833 a(g185 V tp2834 a(g135 VSerial p2835 tp2836 a(g185 V tp2837 a(g18 Vb tp2838 a(g198 V) tp2839 a(g185 V tp2840 a(g343 V=> p2841 tp2842 a(g185 V\u000a p2843 tp2844 a(g135 VSeries p2845 tp2846 a(g185 V tp2847 a(g198 V( tp2848 a(g18 Va tp2849 a(g343 V-> p2850 tp2851 a(g18 Vb tp2852 a(g198 V) tp2853 a(g185 V\u000a tp2854 a(g21 Valts1 p2855 tp2856 a(g185 V tp2857 a(g18 Vd tp2858 a(g185 V tp2859 a(g343 V= tp2860 a(g185 V tp2861 a(g123 Vif p2862 tp2863 a(g185 V tp2864 a(g18 Vd tp2865 a(g185 V tp2866 a(g339 V> tp2867 a(g185 V tp2868 a(g314 V0 tp2869 a(g185 V tp2870 a(g123 Vthen p2871 tp2872 a(g185 V tp2873 a(g18 Vseries p2874 tp2875 a(g185 V tp2876 a(g198 V( tp2877 a(g18 Vdec p2878 tp2879 a(g185 V tp2880 a(g18 Vd tp2881 a(g198 V) tp2882 a(g185 V\u000a p2883 tp2884 a(g123 Velse p2885 tp2886 a(g185 V tp2887 a(g198 V[ tp2888 a(g21 V\u005c tp2889 a(g123 V_ tp2890 a(g185 V tp2891 a(g343 V-> p2892 tp2893 a(g185 V tp2894 a(g18 Vx tp2895 a(g185 V tp2896 a(g339 V| tp2897 a(g185 V tp2898 a(g18 Vx tp2899 a(g185 V tp2900 a(g343 V<- p2901 tp2902 a(g185 V tp2903 a(g18 Vseries p2904 tp2905 a(g185 V tp2906 a(g18 Vd tp2907 a(g198 V] tp2908 a(g185 V\u000a\u000a p2909 tp2910 a(g21 Valts2 p2911 tp2912 a(g185 V tp2913 a(g343 V:: p2914 tp2915 a(g185 V p2916 tp2917 a(g198 V( tp2918 a(g135 VSerial p2919 tp2920 a(g185 V tp2921 a(g18 Va tp2922 a(g198 V, tp2923 a(g185 V tp2924 a(g135 VSerial p2925 tp2926 a(g185 V tp2927 a(g18 Vb tp2928 a(g198 V, tp2929 a(g185 V tp2930 a(g135 VSerial p2931 tp2932 a(g185 V tp2933 a(g18 Vc tp2934 a(g198 V) tp2935 a(g185 V tp2936 a(g343 V=> p2937 tp2938 a(g185 V\u000a p2939 tp2940 a(g135 VSeries p2941 tp2942 a(g185 V tp2943 a(g198 V( tp2944 a(g18 Va tp2945 a(g343 V-> p2946 tp2947 a(g18 Vb tp2948 a(g343 V-> p2949 tp2950 a(g18 Vc tp2951 a(g198 V) tp2952 a(g185 V\u000a tp2953 a(g21 Valts2 p2954 tp2955 a(g185 V tp2956 a(g18 Vd tp2957 a(g185 V tp2958 a(g343 V= tp2959 a(g185 V tp2960 a(g123 Vif p2961 tp2962 a(g185 V tp2963 a(g18 Vd tp2964 a(g185 V tp2965 a(g339 V> tp2966 a(g185 V tp2967 a(g314 V0 tp2968 a(g185 V tp2969 a(g123 Vthen p2970 tp2971 a(g185 V tp2972 a(g18 Vseries p2973 tp2974 a(g185 V tp2975 a(g198 V( tp2976 a(g18 Vdec p2977 tp2978 a(g185 V tp2979 a(g18 Vd tp2980 a(g198 V) tp2981 a(g185 V\u000a p2982 tp2983 a(g123 Velse p2984 tp2985 a(g185 V tp2986 a(g198 V[ tp2987 a(g21 V\u005c tp2988 a(g123 V_ tp2989 a(g185 V tp2990 a(g123 V_ tp2991 a(g185 V tp2992 a(g343 V-> p2993 tp2994 a(g185 V tp2995 a(g18 Vx tp2996 a(g185 V tp2997 a(g339 V| tp2998 a(g185 V tp2999 a(g18 Vx tp3000 a(g185 V tp3001 a(g343 V<- p3002 tp3003 a(g185 V tp3004 a(g18 Vseries p3005 tp3006 a(g185 V tp3007 a(g18 Vd tp3008 a(g198 V] tp3009 a(g185 V\u000a\u000a p3010 tp3011 a(g21 Valts3 p3012 tp3013 a(g185 V tp3014 a(g343 V:: p3015 tp3016 a(g185 V p3017 tp3018 a(g198 V( tp3019 a(g135 VSerial p3020 tp3021 a(g185 V tp3022 a(g18 Va tp3023 a(g198 V, tp3024 a(g185 V tp3025 a(g135 VSerial p3026 tp3027 a(g185 V tp3028 a(g18 Vb tp3029 a(g198 V, tp3030 a(g185 V tp3031 a(g135 VSerial p3032 tp3033 a(g185 V tp3034 a(g18 Vc tp3035 a(g198 V, tp3036 a(g185 V tp3037 a(g135 VSerial p3038 tp3039 a(g185 V tp3040 a(g18 Vd tp3041 a(g198 V) tp3042 a(g185 V tp3043 a(g343 V=> p3044 tp3045 a(g185 V\u000a p3046 tp3047 a(g135 VSeries p3048 tp3049 a(g185 V tp3050 a(g198 V( tp3051 a(g18 Va tp3052 a(g343 V-> p3053 tp3054 a(g18 Vb tp3055 a(g343 V-> p3056 tp3057 a(g18 Vc tp3058 a(g343 V-> p3059 tp3060 a(g18 Vd tp3061 a(g198 V) tp3062 a(g185 V\u000a tp3063 a(g21 Valts3 p3064 tp3065 a(g185 V tp3066 a(g18 Vd tp3067 a(g185 V tp3068 a(g343 V= tp3069 a(g185 V tp3070 a(g123 Vif p3071 tp3072 a(g185 V tp3073 a(g18 Vd tp3074 a(g185 V tp3075 a(g339 V> tp3076 a(g185 V tp3077 a(g314 V0 tp3078 a(g185 V tp3079 a(g123 Vthen p3080 tp3081 a(g185 V tp3082 a(g18 Vseries p3083 tp3084 a(g185 V tp3085 a(g198 V( tp3086 a(g18 Vdec p3087 tp3088 a(g185 V tp3089 a(g18 Vd tp3090 a(g198 V) tp3091 a(g185 V\u000a p3092 tp3093 a(g123 Velse p3094 tp3095 a(g185 V tp3096 a(g198 V[ tp3097 a(g21 V\u005c tp3098 a(g123 V_ tp3099 a(g185 V tp3100 a(g123 V_ tp3101 a(g185 V tp3102 a(g123 V_ tp3103 a(g185 V tp3104 a(g343 V-> p3105 tp3106 a(g185 V tp3107 a(g18 Vx tp3108 a(g185 V tp3109 a(g339 V| tp3110 a(g185 V tp3111 a(g18 Vx tp3112 a(g185 V tp3113 a(g343 V<- p3114 tp3115 a(g185 V tp3116 a(g18 Vseries p3117 tp3118 a(g185 V tp3119 a(g18 Vd tp3120 a(g198 V] tp3121 a(g185 V\u000a\u000a p3122 tp3123 a(g21 Valts4 p3124 tp3125 a(g185 V tp3126 a(g343 V:: p3127 tp3128 a(g185 V p3129 tp3130 a(g198 V( tp3131 a(g135 VSerial p3132 tp3133 a(g185 V tp3134 a(g18 Va tp3135 a(g198 V, tp3136 a(g185 V tp3137 a(g135 VSerial p3138 tp3139 a(g185 V tp3140 a(g18 Vb tp3141 a(g198 V, tp3142 a(g185 V tp3143 a(g135 VSerial p3144 tp3145 a(g185 V tp3146 a(g18 Vc tp3147 a(g198 V, tp3148 a(g185 V tp3149 a(g135 VSerial p3150 tp3151 a(g185 V tp3152 a(g18 Vd tp3153 a(g198 V, tp3154 a(g185 V tp3155 a(g135 VSerial p3156 tp3157 a(g185 V tp3158 a(g18 Ve tp3159 a(g198 V) tp3160 a(g185 V tp3161 a(g343 V=> p3162 tp3163 a(g185 V\u000a p3164 tp3165 a(g135 VSeries p3166 tp3167 a(g185 V tp3168 a(g198 V( tp3169 a(g18 Va tp3170 a(g343 V-> p3171 tp3172 a(g18 Vb tp3173 a(g343 V-> p3174 tp3175 a(g18 Vc tp3176 a(g343 V-> p3177 tp3178 a(g18 Vd tp3179 a(g343 V-> p3180 tp3181 a(g18 Ve tp3182 a(g198 V) tp3183 a(g185 V\u000a tp3184 a(g21 Valts4 p3185 tp3186 a(g185 V tp3187 a(g18 Vd tp3188 a(g185 V tp3189 a(g343 V= tp3190 a(g185 V tp3191 a(g123 Vif p3192 tp3193 a(g185 V tp3194 a(g18 Vd tp3195 a(g185 V tp3196 a(g339 V> tp3197 a(g185 V tp3198 a(g314 V0 tp3199 a(g185 V tp3200 a(g123 Vthen p3201 tp3202 a(g185 V tp3203 a(g18 Vseries p3204 tp3205 a(g185 V tp3206 a(g198 V( tp3207 a(g18 Vdec p3208 tp3209 a(g185 V tp3210 a(g18 Vd tp3211 a(g198 V) tp3212 a(g185 V\u000a p3213 tp3214 a(g123 Velse p3215 tp3216 a(g185 V tp3217 a(g198 V[ tp3218 a(g21 V\u005c tp3219 a(g123 V_ tp3220 a(g185 V tp3221 a(g123 V_ tp3222 a(g185 V tp3223 a(g123 V_ tp3224 a(g185 V tp3225 a(g123 V_ tp3226 a(g185 V tp3227 a(g343 V-> p3228 tp3229 a(g185 V tp3230 a(g18 Vx tp3231 a(g185 V tp3232 a(g339 V| tp3233 a(g185 V tp3234 a(g18 Vx tp3235 a(g185 V tp3236 a(g343 V<- p3237 tp3238 a(g185 V tp3239 a(g18 Vseries p3240 tp3241 a(g185 V tp3242 a(g18 Vd tp3243 a(g198 V] tp3244 a(g185 V\u000a\u000a p3245 tp3246 a(g123 Vinstance p3247 tp3248 a(g185 V tp3249 a(g135 VSerial p3250 tp3251 a(g185 V tp3252 a(g135 VBool p3253 tp3254 a(g185 V tp3255 a(g123 Vwhere p3256 tp3257 a(g185 V\u000a p3258 tp3259 a(g18 Vseries p3260 tp3261 a(g185 V p3262 tp3263 a(g343 V= tp3264 a(g185 V tp3265 a(g18 Vcons0 p3266 tp3267 a(g185 V tp3268 a(g135 VTrue p3269 tp3270 a(g185 V tp3271 a(g339 V\u005c/ p3272 tp3273 a(g185 V tp3274 a(g18 Vcons0 p3275 tp3276 a(g185 V tp3277 a(g135 VFalse p3278 tp3279 a(g185 V\u000a p3280 tp3281 a(g18 Vcoseries p3282 tp3283 a(g185 V tp3284 a(g18 Vd tp3285 a(g185 V tp3286 a(g343 V= tp3287 a(g185 V tp3288 a(g198 V[ tp3289 a(g185 V tp3290 a(g21 V\u005c tp3291 a(g18 Vx tp3292 a(g185 V tp3293 a(g343 V-> p3294 tp3295 a(g185 V tp3296 a(g123 Vif p3297 tp3298 a(g185 V tp3299 a(g18 Vx tp3300 a(g185 V tp3301 a(g123 Vthen p3302 tp3303 a(g185 V tp3304 a(g18 Vb1 p3305 tp3306 a(g185 V tp3307 a(g123 Velse p3308 tp3309 a(g185 V tp3310 a(g18 Vb2 p3311 tp3312 a(g185 V\u000a p3313 tp3314 a(g339 V| tp3315 a(g185 V tp3316 a(g198 V( tp3317 a(g18 Vb1 p3318 tp3319 a(g198 V, tp3320 a(g18 Vb2 p3321 tp3322 a(g198 V) tp3323 a(g185 V tp3324 a(g343 V<- p3325 tp3326 a(g185 V tp3327 a(g18 Vseries p3328 tp3329 a(g185 V tp3330 a(g18 Vd tp3331 a(g185 V tp3332 a(g198 V] tp3333 a(g185 V\u000a\u000a p3334 tp3335 a(g123 Vinstance p3336 tp3337 a(g185 V tp3338 a(g135 VSerial p3339 tp3340 a(g185 V tp3341 a(g18 Va tp3342 a(g185 V tp3343 a(g343 V=> p3344 tp3345 a(g185 V tp3346 a(g135 VSerial p3347 tp3348 a(g185 V tp3349 a(g198 V( tp3350 a(g135 VMaybe p3351 tp3352 a(g185 V tp3353 a(g18 Va tp3354 a(g198 V) tp3355 a(g185 V tp3356 a(g123 Vwhere p3357 tp3358 a(g185 V\u000a p3359 tp3360 a(g18 Vseries p3361 tp3362 a(g185 V p3363 tp3364 a(g343 V= tp3365 a(g185 V tp3366 a(g18 Vcons0 p3367 tp3368 a(g185 V tp3369 a(g135 VNothing p3370 tp3371 a(g185 V tp3372 a(g339 V\u005c/ p3373 tp3374 a(g185 V tp3375 a(g18 Vcons1 p3376 tp3377 a(g185 V tp3378 a(g135 VJust p3379 tp3380 a(g185 V\u000a p3381 tp3382 a(g18 Vcoseries p3383 tp3384 a(g185 V tp3385 a(g18 Vd tp3386 a(g185 V tp3387 a(g343 V= tp3388 a(g185 V tp3389 a(g198 V[ tp3390 a(g185 V tp3391 a(g21 V\u005c tp3392 a(g18 Vm tp3393 a(g185 V tp3394 a(g343 V-> p3395 tp3396 a(g185 V tp3397 a(g123 Vcase p3398 tp3399 a(g185 V tp3400 a(g18 Vm tp3401 a(g185 V tp3402 a(g123 Vof p3403 tp3404 a(g185 V\u000a p3405 tp3406 a(g135 VNothing p3407 tp3408 a(g185 V tp3409 a(g343 V-> p3410 tp3411 a(g185 V tp3412 a(g18 Vz tp3413 a(g185 V\u000a p3414 tp3415 a(g135 VJust p3416 tp3417 a(g185 V tp3418 a(g18 Vx tp3419 a(g185 V p3420 tp3421 a(g343 V-> p3422 tp3423 a(g185 V tp3424 a(g18 Vf tp3425 a(g185 V tp3426 a(g18 Vx tp3427 a(g185 V\u000a p3428 tp3429 a(g339 V| tp3430 a(g185 V p3431 tp3432 a(g18 Vz tp3433 a(g185 V tp3434 a(g343 V<- p3435 tp3436 a(g185 V tp3437 a(g18 Valts0 p3438 tp3439 a(g185 V tp3440 a(g18 Vd tp3441 a(g185 V tp3442 a(g198 V, tp3443 a(g185 V\u000a p3444 tp3445 a(g18 Vf tp3446 a(g185 V tp3447 a(g343 V<- p3448 tp3449 a(g185 V tp3450 a(g18 Valts1 p3451 tp3452 a(g185 V tp3453 a(g18 Vd tp3454 a(g185 V tp3455 a(g198 V] tp3456 a(g185 V\u000a\u000a p3457 tp3458 a(g123 Vinstance p3459 tp3460 a(g185 V tp3461 a(g198 V( tp3462 a(g135 VSerial p3463 tp3464 a(g185 V tp3465 a(g18 Va tp3466 a(g198 V, tp3467 a(g185 V tp3468 a(g135 VSerial p3469 tp3470 a(g185 V tp3471 a(g18 Vb tp3472 a(g198 V) tp3473 a(g185 V tp3474 a(g343 V=> p3475 tp3476 a(g185 V tp3477 a(g135 VSerial p3478 tp3479 a(g185 V tp3480 a(g198 V( tp3481 a(g135 VEither p3482 tp3483 a(g185 V tp3484 a(g18 Va tp3485 a(g185 V tp3486 a(g18 Vb tp3487 a(g198 V) tp3488 a(g185 V tp3489 a(g123 Vwhere p3490 tp3491 a(g185 V\u000a p3492 tp3493 a(g18 Vseries p3494 tp3495 a(g185 V p3496 tp3497 a(g343 V= tp3498 a(g185 V tp3499 a(g18 Vcons1 p3500 tp3501 a(g185 V tp3502 a(g135 VLeft p3503 tp3504 a(g185 V tp3505 a(g339 V\u005c/ p3506 tp3507 a(g185 V tp3508 a(g18 Vcons1 p3509 tp3510 a(g185 V tp3511 a(g135 VRight p3512 tp3513 a(g185 V\u000a p3514 tp3515 a(g18 Vcoseries p3516 tp3517 a(g185 V tp3518 a(g18 Vd tp3519 a(g185 V tp3520 a(g343 V= tp3521 a(g185 V tp3522 a(g198 V[ tp3523 a(g185 V tp3524 a(g21 V\u005c tp3525 a(g18 Ve tp3526 a(g185 V tp3527 a(g343 V-> p3528 tp3529 a(g185 V tp3530 a(g123 Vcase p3531 tp3532 a(g185 V tp3533 a(g18 Ve tp3534 a(g185 V tp3535 a(g123 Vof p3536 tp3537 a(g185 V\u000a p3538 tp3539 a(g135 VLeft p3540 tp3541 a(g185 V tp3542 a(g18 Vx tp3543 a(g185 V p3544 tp3545 a(g343 V-> p3546 tp3547 a(g185 V tp3548 a(g18 Vf tp3549 a(g185 V tp3550 a(g18 Vx tp3551 a(g185 V\u000a p3552 tp3553 a(g135 VRight p3554 tp3555 a(g185 V tp3556 a(g18 Vy tp3557 a(g185 V tp3558 a(g343 V-> p3559 tp3560 a(g185 V tp3561 a(g18 Vg tp3562 a(g185 V tp3563 a(g18 Vy tp3564 a(g185 V\u000a p3565 tp3566 a(g339 V| tp3567 a(g185 V p3568 tp3569 a(g18 Vf tp3570 a(g185 V tp3571 a(g343 V<- p3572 tp3573 a(g185 V tp3574 a(g18 Valts1 p3575 tp3576 a(g185 V tp3577 a(g18 Vd tp3578 a(g185 V tp3579 a(g198 V, tp3580 a(g185 V\u000a p3581 tp3582 a(g18 Vg tp3583 a(g185 V tp3584 a(g343 V<- p3585 tp3586 a(g185 V tp3587 a(g18 Valts1 p3588 tp3589 a(g185 V tp3590 a(g18 Vd tp3591 a(g185 V tp3592 a(g198 V] tp3593 a(g185 V\u000a\u000a p3594 tp3595 a(g123 Vinstance p3596 tp3597 a(g185 V tp3598 a(g135 VSerial p3599 tp3600 a(g185 V tp3601 a(g18 Va tp3602 a(g185 V tp3603 a(g343 V=> p3604 tp3605 a(g185 V tp3606 a(g135 VSerial p3607 tp3608 a(g185 V tp3609 a(g198 V[ tp3610 a(g18 Va tp3611 a(g198 V] tp3612 a(g185 V tp3613 a(g123 Vwhere p3614 tp3615 a(g185 V\u000a p3616 tp3617 a(g18 Vseries p3618 tp3619 a(g185 V p3620 tp3621 a(g343 V= tp3622 a(g185 V tp3623 a(g18 Vcons0 p3624 tp3625 a(g185 V tp3626 a(g135 V[] p3627 tp3628 a(g185 V tp3629 a(g339 V\u005c/ p3630 tp3631 a(g185 V tp3632 a(g18 Vcons2 p3633 tp3634 a(g185 V tp3635 a(g198 V( tp3636 a(g135 V: tp3637 a(g198 V) tp3638 a(g185 V\u000a p3639 tp3640 a(g18 Vcoseries p3641 tp3642 a(g185 V tp3643 a(g18 Vd tp3644 a(g185 V tp3645 a(g343 V= tp3646 a(g185 V tp3647 a(g198 V[ tp3648 a(g185 V tp3649 a(g21 V\u005c tp3650 a(g18 Vxs p3651 tp3652 a(g185 V tp3653 a(g343 V-> p3654 tp3655 a(g185 V tp3656 a(g123 Vcase p3657 tp3658 a(g185 V tp3659 a(g18 Vxs p3660 tp3661 a(g185 V tp3662 a(g123 Vof p3663 tp3664 a(g185 V\u000a p3665 tp3666 a(g135 V[] p3667 tp3668 a(g185 V p3669 tp3670 a(g343 V-> p3671 tp3672 a(g185 V tp3673 a(g18 Vy tp3674 a(g185 V\u000a p3675 tp3676 a(g198 V( tp3677 a(g18 Vx tp3678 a(g135 V: tp3679 a(g18 Vxs' p3680 tp3681 a(g198 V) tp3682 a(g185 V tp3683 a(g343 V-> p3684 tp3685 a(g185 V tp3686 a(g18 Vf tp3687 a(g185 V tp3688 a(g18 Vx tp3689 a(g185 V tp3690 a(g18 Vxs' p3691 tp3692 a(g185 V\u000a p3693 tp3694 a(g339 V| tp3695 a(g185 V p3696 tp3697 a(g18 Vy tp3698 a(g185 V tp3699 a(g343 V<- p3700 tp3701 a(g185 V tp3702 a(g18 Valts0 p3703 tp3704 a(g185 V tp3705 a(g18 Vd tp3706 a(g185 V tp3707 a(g198 V, tp3708 a(g185 V\u000a p3709 tp3710 a(g18 Vf tp3711 a(g185 V tp3712 a(g343 V<- p3713 tp3714 a(g185 V tp3715 a(g18 Valts2 p3716 tp3717 a(g185 V tp3718 a(g18 Vd tp3719 a(g185 V tp3720 a(g198 V] tp3721 a(g185 V\u000a\u000a p3722 tp3723 a(g7 V-- Warning: the coseries instance here may generate duplicates. p3724 tp3725 a(g185 V\u000a tp3726 a(g123 Vinstance p3727 tp3728 a(g185 V tp3729 a(g198 V( tp3730 a(g135 VSerial p3731 tp3732 a(g185 V tp3733 a(g18 Va tp3734 a(g198 V, tp3735 a(g185 V tp3736 a(g135 VSerial p3737 tp3738 a(g185 V tp3739 a(g18 Vb tp3740 a(g198 V) tp3741 a(g185 V tp3742 a(g343 V=> p3743 tp3744 a(g185 V tp3745 a(g135 VSerial p3746 tp3747 a(g185 V tp3748 a(g198 V( tp3749 a(g18 Va tp3750 a(g343 V-> p3751 tp3752 a(g18 Vb tp3753 a(g198 V) tp3754 a(g185 V tp3755 a(g123 Vwhere p3756 tp3757 a(g185 V\u000a p3758 tp3759 a(g18 Vseries p3760 tp3761 a(g185 V tp3762 a(g343 V= tp3763 a(g185 V tp3764 a(g18 Vcoseries p3765 tp3766 a(g185 V\u000a p3767 tp3768 a(g18 Vcoseries p3769 tp3770 a(g185 V tp3771 a(g18 Vd tp3772 a(g185 V tp3773 a(g343 V= tp3774 a(g185 V tp3775 a(g198 V[ tp3776 a(g185 V tp3777 a(g21 V\u005c tp3778 a(g18 Vf tp3779 a(g185 V tp3780 a(g343 V-> p3781 tp3782 a(g185 V tp3783 a(g18 Vg tp3784 a(g185 V tp3785 a(g198 V[ tp3786 a(g18 Vf tp3787 a(g185 V tp3788 a(g18 Vx tp3789 a(g185 V tp3790 a(g339 V| tp3791 a(g185 V tp3792 a(g18 Vx tp3793 a(g185 V tp3794 a(g343 V<- p3795 tp3796 a(g185 V tp3797 a(g18 Vseries p3798 tp3799 a(g185 V tp3800 a(g18 Vd tp3801 a(g198 V] tp3802 a(g185 V\u000a p3803 tp3804 a(g339 V| tp3805 a(g185 V tp3806 a(g18 Vg tp3807 a(g185 V tp3808 a(g343 V<- p3809 tp3810 a(g185 V tp3811 a(g18 Vseries p3812 tp3813 a(g185 V tp3814 a(g18 Vd tp3815 a(g185 V tp3816 a(g198 V] tp3817 a(g185 V \u000a\u000a p3818 tp3819 a(g7 V-- For customising the depth measure. Use with care! p3820 tp3821 a(g185 V\u000a\u000a p3822 tp3823 a(g21 Vdepth p3824 tp3825 a(g185 V tp3826 a(g343 V:: p3827 tp3828 a(g185 V tp3829 a(g135 VInt p3830 tp3831 a(g185 V tp3832 a(g343 V-> p3833 tp3834 a(g185 V tp3835 a(g135 VInt p3836 tp3837 a(g185 V tp3838 a(g343 V-> p3839 tp3840 a(g185 V tp3841 a(g135 VInt p3842 tp3843 a(g185 V\u000a tp3844 a(g21 Vdepth p3845 tp3846 a(g185 V tp3847 a(g18 Vd tp3848 a(g185 V tp3849 a(g18 Vd' p3850 tp3851 a(g185 V tp3852 a(g339 V| tp3853 a(g185 V tp3854 a(g18 Vd tp3855 a(g185 V tp3856 a(g339 V>= p3857 tp3858 a(g185 V tp3859 a(g314 V0 tp3860 a(g185 V p3861 tp3862 a(g343 V= tp3863 a(g185 V tp3864 a(g18 Vd' p3865 tp3866 a(g339 V+ tp3867 a(g314 V1 tp3868 a(g339 V- tp3869 a(g18 Vd tp3870 a(g185 V\u000a p3871 tp3872 a(g339 V| tp3873 a(g185 V tp3874 a(g18 Votherwise p3875 tp3876 a(g185 V tp3877 a(g343 V= tp3878 a(g185 V tp3879 a(g25 Verror p3880 tp3881 a(g185 V tp3882 a(g222 V" tp3883 a(g222 VSmallCheck.depth: argument < 0 p3884 tp3885 a(g222 V" tp3886 a(g185 V\u000a\u000a p3887 tp3888 a(g21 Vdec p3889 tp3890 a(g185 V tp3891 a(g343 V:: p3892 tp3893 a(g185 V tp3894 a(g135 VInt p3895 tp3896 a(g185 V tp3897 a(g343 V-> p3898 tp3899 a(g185 V tp3900 a(g135 VInt p3901 tp3902 a(g185 V\u000a tp3903 a(g21 Vdec p3904 tp3905 a(g185 V tp3906 a(g18 Vd tp3907 a(g185 V tp3908 a(g339 V| tp3909 a(g185 V tp3910 a(g18 Vd tp3911 a(g185 V tp3912 a(g339 V> tp3913 a(g185 V tp3914 a(g314 V0 tp3915 a(g185 V p3916 tp3917 a(g343 V= tp3918 a(g185 V tp3919 a(g18 Vd tp3920 a(g339 V- tp3921 a(g314 V1 tp3922 a(g185 V\u000a p3923 tp3924 a(g339 V| tp3925 a(g185 V tp3926 a(g18 Votherwise p3927 tp3928 a(g185 V tp3929 a(g343 V= tp3930 a(g185 V tp3931 a(g25 Verror p3932 tp3933 a(g185 V tp3934 a(g222 V" tp3935 a(g222 VSmallCheck.dec: argument <= 0 p3936 tp3937 a(g222 V" tp3938 a(g185 V\u000a\u000a p3939 tp3940 a(g21 Vinc p3941 tp3942 a(g185 V tp3943 a(g343 V:: p3944 tp3945 a(g185 V tp3946 a(g135 VInt p3947 tp3948 a(g185 V tp3949 a(g343 V-> p3950 tp3951 a(g185 V tp3952 a(g135 VInt p3953 tp3954 a(g185 V\u000a tp3955 a(g21 Vinc p3956 tp3957 a(g185 V tp3958 a(g18 Vd tp3959 a(g185 V tp3960 a(g343 V= tp3961 a(g185 V tp3962 a(g18 Vd tp3963 a(g339 V+ tp3964 a(g314 V1 tp3965 a(g185 V\u000a\u000a p3966 tp3967 a(g7 V-- show the extension of a function (in part, bounded both by p3968 tp3969 a(g185 V\u000a tp3970 a(g7 V-- the number and depth of arguments) p3971 tp3972 a(g185 V\u000a tp3973 a(g123 Vinstance p3974 tp3975 a(g185 V tp3976 a(g198 V( tp3977 a(g135 VSerial p3978 tp3979 a(g185 V tp3980 a(g18 Va tp3981 a(g198 V, tp3982 a(g185 V tp3983 a(g135 VShow p3984 tp3985 a(g185 V tp3986 a(g18 Va tp3987 a(g198 V, tp3988 a(g185 V tp3989 a(g135 VShow p3990 tp3991 a(g185 V tp3992 a(g18 Vb tp3993 a(g198 V) tp3994 a(g185 V tp3995 a(g343 V=> p3996 tp3997 a(g185 V tp3998 a(g135 VShow p3999 tp4000 a(g185 V tp4001 a(g198 V( tp4002 a(g18 Va tp4003 a(g343 V-> p4004 tp4005 a(g18 Vb tp4006 a(g198 V) tp4007 a(g185 V tp4008 a(g123 Vwhere p4009 tp4010 a(g185 V\u000a p4011 tp4012 a(g18 Vshow p4013 tp4014 a(g185 V tp4015 a(g18 Vf tp4016 a(g185 V tp4017 a(g343 V= tp4018 a(g185 V \u000a p4019 tp4020 a(g123 Vif p4021 tp4022 a(g185 V tp4023 a(g18 Vmaxarheight p4024 tp4025 a(g185 V tp4026 a(g339 V== p4027 tp4028 a(g185 V tp4029 a(g314 V1 tp4030 a(g185 V\u000a p4031 tp4032 a(g339 V&& p4033 tp4034 a(g185 V tp4035 a(g18 Vsumarwidth p4036 tp4037 a(g185 V tp4038 a(g339 V+ tp4039 a(g185 V tp4040 a(g18 Vlength p4041 tp4042 a(g185 V tp4043 a(g18 Vars p4044 tp4045 a(g185 V tp4046 a(g339 V* tp4047 a(g185 V tp4048 a(g18 Vlength p4049 tp4050 a(g185 V tp4051 a(g222 V" tp4052 a(g222 V->; p4053 tp4054 a(g222 V" tp4055 a(g185 V tp4056 a(g339 V< tp4057 a(g185 V tp4058 a(g18 VwidthLimit p4059 tp4060 a(g185 V tp4061 a(g123 Vthen p4062 tp4063 a(g185 V\u000a p4064 tp4065 a(g222 V" tp4066 a(g222 V{ tp4067 a(g222 V" tp4068 a(g339 V++ p4069 tp4070 a(g198 V( tp4071 a(g185 V\u000a p4072 tp4073 a(g18 Vconcat p4074 tp4075 a(g185 V tp4076 a(g339 V$ tp4077 a(g185 V tp4078 a(g18 Vintersperse p4079 tp4080 a(g185 V tp4081 a(g222 V" tp4082 a(g222 V; tp4083 a(g222 V" tp4084 a(g185 V tp4085 a(g339 V$ tp4086 a(g185 V tp4087 a(g198 V[ tp4088 a(g18 Va tp4089 a(g339 V++ p4090 tp4091 a(g222 V" tp4092 a(g222 V-> p4093 tp4094 a(g222 V" tp4095 a(g339 V++ p4096 tp4097 a(g18 Vr tp4098 a(g185 V tp4099 a(g339 V| tp4100 a(g185 V tp4101 a(g198 V( tp4102 a(g18 Va tp4103 a(g198 V, tp4104 a(g18 Vr tp4105 a(g198 V) tp4106 a(g185 V tp4107 a(g343 V<- p4108 tp4109 a(g185 V tp4110 a(g18 Vars p4111 tp4112 a(g198 V] tp4113 a(g185 V\u000a p4114 tp4115 a(g198 V) tp4116 a(g339 V++ p4117 tp4118 a(g222 V" tp4119 a(g222 V} tp4120 a(g222 V" tp4121 a(g185 V\u000a p4122 tp4123 a(g123 Velse p4124 tp4125 a(g185 V\u000a p4126 tp4127 a(g18 Vconcat p4128 tp4129 a(g185 V tp4130 a(g339 V$ tp4131 a(g185 V tp4132 a(g198 V[ tp4133 a(g18 Va tp4134 a(g339 V++ p4135 tp4136 a(g222 V" tp4137 a(g222 V-> p4138 tp4139 a(g248 V\u005c tp4140 a(g248 Vn tp4141 a(g222 V" tp4142 a(g339 V++ p4143 tp4144 a(g18 Vindent p4145 tp4146 a(g185 V tp4147 a(g18 Vr tp4148 a(g185 V tp4149 a(g339 V| tp4150 a(g185 V tp4151 a(g198 V( tp4152 a(g18 Va tp4153 a(g198 V, tp4154 a(g18 Vr tp4155 a(g198 V) tp4156 a(g185 V tp4157 a(g343 V<- p4158 tp4159 a(g185 V tp4160 a(g18 Vars p4161 tp4162 a(g198 V] tp4163 a(g185 V\u000a p4164 tp4165 a(g123 Vwhere p4166 tp4167 a(g185 V\u000a p4168 tp4169 a(g18 Vars p4170 tp4171 a(g185 V tp4172 a(g343 V= tp4173 a(g185 V tp4174 a(g18 Vtake p4175 tp4176 a(g185 V tp4177 a(g18 VlengthLimit p4178 tp4179 a(g185 V tp4180 a(g198 V[ tp4181 a(g185 V tp4182 a(g198 V( tp4183 a(g18 Vshow p4184 tp4185 a(g185 V tp4186 a(g18 Vx tp4187 a(g198 V, tp4188 a(g185 V tp4189 a(g18 Vshow p4190 tp4191 a(g185 V tp4192 a(g198 V( tp4193 a(g18 Vf tp4194 a(g185 V tp4195 a(g18 Vx tp4196 a(g198 V) tp4197 a(g198 V) tp4198 a(g185 V\u000a p4199 tp4200 a(g339 V| tp4201 a(g185 V tp4202 a(g18 Vx tp4203 a(g185 V tp4204 a(g343 V<- p4205 tp4206 a(g185 V tp4207 a(g18 Vseries p4208 tp4209 a(g185 V tp4210 a(g18 VdepthLimit p4211 tp4212 a(g185 V tp4213 a(g198 V] tp4214 a(g185 V\u000a p4215 tp4216 a(g18 Vmaxarheight p4217 tp4218 a(g185 V tp4219 a(g343 V= tp4220 a(g185 V tp4221 a(g18 Vmaximum p4222 tp4223 a(g185 V p4224 tp4225 a(g198 V[ tp4226 a(g185 V tp4227 a(g18 Vmax p4228 tp4229 a(g185 V tp4230 a(g198 V( tp4231 a(g18 Vheight p4232 tp4233 a(g185 V tp4234 a(g18 Va tp4235 a(g198 V) tp4236 a(g185 V tp4237 a(g198 V( tp4238 a(g18 Vheight p4239 tp4240 a(g185 V tp4241 a(g18 Vr tp4242 a(g198 V) tp4243 a(g185 V\u000a p4244 tp4245 a(g339 V| tp4246 a(g185 V tp4247 a(g198 V( tp4248 a(g18 Va tp4249 a(g198 V, tp4250 a(g18 Vr tp4251 a(g198 V) tp4252 a(g185 V tp4253 a(g343 V<- p4254 tp4255 a(g185 V tp4256 a(g18 Vars p4257 tp4258 a(g185 V tp4259 a(g198 V] tp4260 a(g185 V\u000a p4261 tp4262 a(g18 Vsumarwidth p4263 tp4264 a(g185 V tp4265 a(g343 V= tp4266 a(g185 V tp4267 a(g18 Vsum p4268 tp4269 a(g185 V p4270 tp4271 a(g198 V[ tp4272 a(g185 V tp4273 a(g18 Vlength p4274 tp4275 a(g185 V tp4276 a(g18 Va tp4277 a(g185 V tp4278 a(g339 V+ tp4279 a(g185 V tp4280 a(g18 Vlength p4281 tp4282 a(g185 V tp4283 a(g18 Vr tp4284 a(g185 V \u000a p4285 tp4286 a(g339 V| tp4287 a(g185 V tp4288 a(g198 V( tp4289 a(g18 Va tp4290 a(g198 V, tp4291 a(g18 Vr tp4292 a(g198 V) tp4293 a(g185 V tp4294 a(g343 V<- p4295 tp4296 a(g185 V tp4297 a(g18 Vars p4298 tp4299 a(g198 V] tp4300 a(g185 V\u000a p4301 tp4302 a(g18 Vindent p4303 tp4304 a(g185 V tp4305 a(g343 V= tp4306 a(g185 V tp4307 a(g18 Vunlines p4308 tp4309 a(g185 V tp4310 a(g339 V. tp4311 a(g185 V tp4312 a(g18 Vmap p4313 tp4314 a(g185 V tp4315 a(g198 V( tp4316 a(g222 V" tp4317 a(g222 V p4318 tp4319 a(g222 V" tp4320 a(g339 V++ p4321 tp4322 a(g198 V) tp4323 a(g185 V tp4324 a(g339 V. tp4325 a(g185 V tp4326 a(g18 Vlines p4327 tp4328 a(g185 V\u000a p4329 tp4330 a(g18 Vheight p4331 tp4332 a(g185 V tp4333 a(g343 V= tp4334 a(g185 V tp4335 a(g18 Vlength p4336 tp4337 a(g185 V tp4338 a(g339 V. tp4339 a(g185 V tp4340 a(g18 Vlines p4341 tp4342 a(g185 V\u000a p4343 tp4344 a(g198 V( tp4345 a(g18 VwidthLimit p4346 tp4347 a(g198 V, tp4348 a(g18 VlengthLimit p4349 tp4350 a(g198 V, tp4351 a(g18 VdepthLimit p4352 tp4353 a(g198 V) tp4354 a(g185 V tp4355 a(g343 V= tp4356 a(g185 V tp4357 a(g198 V( tp4358 a(g314 V80 p4359 tp4360 a(g198 V, tp4361 a(g314 V20 p4362 tp4363 a(g198 V, tp4364 a(g314 V3 tp4365 a(g198 V) tp4366 a(g343 V:: p4367 tp4368 a(g198 V( tp4369 a(g135 VInt p4370 tp4371 a(g198 V, tp4372 a(g135 VInt p4373 tp4374 a(g198 V, tp4375 a(g135 VInt p4376 tp4377 a(g198 V) tp4378 a(g185 V\u000a\u000a p4379 tp4380 a(g7 V---------------- <properties and their evaluation> ------------------ p4381 tp4382 a(g185 V\u000a\u000a p4383 tp4384 a(g7 V-- adapted from QuickCheck originals: here results come in lists, p4385 tp4386 a(g185 V\u000a tp4387 a(g7 V-- properties have depth arguments, stamps (for classifying random p4388 tp4389 a(g185 V\u000a tp4390 a(g7 V-- tests) are omitted, existentials are introduced p4391 tp4392 a(g185 V\u000a\u000a p4393 tp4394 a(g123 Vnewtype p4395 tp4396 a(g185 V tp4397 a(g135 VPR p4398 tp4399 a(g185 V tp4400 a(g343 V= tp4401 a(g185 V tp4402 a(g135 VProp p4403 tp4404 a(g185 V tp4405 a(g198 V[ tp4406 a(g135 VResult p4407 tp4408 a(g198 V] tp4409 a(g185 V\u000a\u000a p4410 tp4411 a(g123 Vdata p4412 tp4413 a(g185 V tp4414 a(g135 VResult p4415 tp4416 a(g185 V tp4417 a(g343 V= tp4418 a(g185 V tp4419 a(g135 VResult p4420 tp4421 a(g185 V tp4422 a(g198 V{ tp4423 a(g18 Vok p4424 tp4425 a(g185 V tp4426 a(g343 V:: p4427 tp4428 a(g185 V tp4429 a(g135 VMaybe p4430 tp4431 a(g185 V tp4432 a(g135 VBool p4433 tp4434 a(g198 V, tp4435 a(g185 V tp4436 a(g18 Varguments p4437 tp4438 a(g185 V tp4439 a(g343 V:: p4440 tp4441 a(g185 V tp4442 a(g198 V[ tp4443 a(g135 VString p4444 tp4445 a(g198 V] tp4446 a(g198 V} tp4447 a(g185 V\u000a\u000a p4448 tp4449 a(g21 Vnothing p4450 tp4451 a(g185 V tp4452 a(g343 V:: p4453 tp4454 a(g185 V tp4455 a(g135 VResult p4456 tp4457 a(g185 V\u000a tp4458 a(g21 Vnothing p4459 tp4460 a(g185 V tp4461 a(g343 V= tp4462 a(g185 V tp4463 a(g135 VResult p4464 tp4465 a(g185 V tp4466 a(g198 V{ tp4467 a(g18 Vok p4468 tp4469 a(g185 V tp4470 a(g343 V= tp4471 a(g185 V tp4472 a(g135 VNothing p4473 tp4474 a(g198 V, tp4475 a(g185 V tp4476 a(g18 Varguments p4477 tp4478 a(g185 V tp4479 a(g343 V= tp4480 a(g185 V tp4481 a(g135 V[] p4482 tp4483 a(g198 V} tp4484 a(g185 V\u000a\u000a p4485 tp4486 a(g21 Vresult p4487 tp4488 a(g185 V tp4489 a(g343 V:: p4490 tp4491 a(g185 V tp4492 a(g135 VResult p4493 tp4494 a(g185 V tp4495 a(g343 V-> p4496 tp4497 a(g185 V tp4498 a(g135 VPR p4499 tp4500 a(g185 V\u000a tp4501 a(g21 Vresult p4502 tp4503 a(g185 V tp4504 a(g18 Vres p4505 tp4506 a(g185 V tp4507 a(g343 V= tp4508 a(g185 V tp4509 a(g135 VProp p4510 tp4511 a(g185 V tp4512 a(g198 V[ tp4513 a(g18 Vres p4514 tp4515 a(g198 V] tp4516 a(g185 V\u000a\u000a p4517 tp4518 a(g123 Vnewtype p4519 tp4520 a(g185 V tp4521 a(g135 VProperty p4522 tp4523 a(g185 V tp4524 a(g343 V= tp4525 a(g185 V tp4526 a(g135 VProperty p4527 tp4528 a(g185 V tp4529 a(g198 V( tp4530 a(g135 VInt p4531 tp4532 a(g185 V tp4533 a(g343 V-> p4534 tp4535 a(g185 V tp4536 a(g135 VPR p4537 tp4538 a(g198 V) tp4539 a(g185 V\u000a\u000a p4540 tp4541 a(g123 Vclass p4542 tp4543 a(g185 V tp4544 a(g135 VTestable p4545 tp4546 a(g185 V tp4547 a(g18 Va tp4548 a(g185 V tp4549 a(g123 Vwhere p4550 tp4551 a(g185 V\u000a p4552 tp4553 a(g18 Vproperty p4554 tp4555 a(g185 V tp4556 a(g343 V:: p4557 tp4558 a(g185 V tp4559 a(g18 Va tp4560 a(g185 V tp4561 a(g343 V-> p4562 tp4563 a(g185 V tp4564 a(g135 VInt p4565 tp4566 a(g185 V tp4567 a(g343 V-> p4568 tp4569 a(g185 V tp4570 a(g135 VPR p4571 tp4572 a(g185 V\u000a\u000a p4573 tp4574 a(g123 Vinstance p4575 tp4576 a(g185 V tp4577 a(g135 VTestable p4578 tp4579 a(g185 V tp4580 a(g135 VBool p4581 tp4582 a(g185 V tp4583 a(g123 Vwhere p4584 tp4585 a(g185 V\u000a p4586 tp4587 a(g18 Vproperty p4588 tp4589 a(g185 V tp4590 a(g18 Vb tp4591 a(g185 V tp4592 a(g123 V_ tp4593 a(g185 V tp4594 a(g343 V= tp4595 a(g185 V tp4596 a(g135 VProp p4597 tp4598 a(g185 V tp4599 a(g198 V[ tp4600 a(g135 VResult p4601 tp4602 a(g185 V tp4603 a(g198 V( tp4604 a(g135 VJust p4605 tp4606 a(g185 V tp4607 a(g18 Vb tp4608 a(g198 V) tp4609 a(g185 V tp4610 a(g135 V[] p4611 tp4612 a(g198 V] tp4613 a(g185 V\u000a\u000a p4614 tp4615 a(g123 Vinstance p4616 tp4617 a(g185 V tp4618 a(g135 VTestable p4619 tp4620 a(g185 V tp4621 a(g135 VPR p4622 tp4623 a(g185 V tp4624 a(g123 Vwhere p4625 tp4626 a(g185 V\u000a p4627 tp4628 a(g18 Vproperty p4629 tp4630 a(g185 V tp4631 a(g18 Vprop p4632 tp4633 a(g185 V tp4634 a(g123 V_ tp4635 a(g185 V tp4636 a(g343 V= tp4637 a(g185 V tp4638 a(g18 Vprop p4639 tp4640 a(g185 V\u000a\u000a p4641 tp4642 a(g123 Vinstance p4643 tp4644 a(g185 V tp4645 a(g198 V( tp4646 a(g135 VSerial p4647 tp4648 a(g185 V tp4649 a(g18 Va tp4650 a(g198 V, tp4651 a(g185 V tp4652 a(g135 VShow p4653 tp4654 a(g185 V tp4655 a(g18 Va tp4656 a(g198 V, tp4657 a(g185 V tp4658 a(g135 VTestable p4659 tp4660 a(g185 V tp4661 a(g18 Vb tp4662 a(g198 V) tp4663 a(g185 V tp4664 a(g343 V=> p4665 tp4666 a(g185 V tp4667 a(g135 VTestable p4668 tp4669 a(g185 V tp4670 a(g198 V( tp4671 a(g18 Va tp4672 a(g343 V-> p4673 tp4674 a(g18 Vb tp4675 a(g198 V) tp4676 a(g185 V tp4677 a(g123 Vwhere p4678 tp4679 a(g185 V\u000a p4680 tp4681 a(g18 Vproperty p4682 tp4683 a(g185 V tp4684 a(g18 Vf tp4685 a(g185 V tp4686 a(g343 V= tp4687 a(g185 V tp4688 a(g18 Vf' p4689 tp4690 a(g185 V tp4691 a(g123 Vwhere p4692 tp4693 a(g185 V tp4694 a(g135 VProperty p4695 tp4696 a(g185 V tp4697 a(g18 Vf' p4698 tp4699 a(g185 V tp4700 a(g343 V= tp4701 a(g185 V tp4702 a(g18 VforAll p4703 tp4704 a(g185 V tp4705 a(g18 Vseries p4706 tp4707 a(g185 V tp4708 a(g18 Vf tp4709 a(g185 V\u000a\u000a p4710 tp4711 a(g123 Vinstance p4712 tp4713 a(g185 V tp4714 a(g135 VTestable p4715 tp4716 a(g185 V tp4717 a(g135 VProperty p4718 tp4719 a(g185 V tp4720 a(g123 Vwhere p4721 tp4722 a(g185 V\u000a p4723 tp4724 a(g18 Vproperty p4725 tp4726 a(g185 V tp4727 a(g198 V( tp4728 a(g135 VProperty p4729 tp4730 a(g185 V tp4731 a(g18 Vf tp4732 a(g198 V) tp4733 a(g185 V tp4734 a(g18 Vd tp4735 a(g185 V tp4736 a(g343 V= tp4737 a(g185 V tp4738 a(g18 Vf tp4739 a(g185 V tp4740 a(g18 Vd tp4741 a(g185 V\u000a\u000a p4742 tp4743 a(g21 Vevaluate p4744 tp4745 a(g185 V tp4746 a(g343 V:: p4747 tp4748 a(g185 V tp4749 a(g135 VTestable p4750 tp4751 a(g185 V tp4752 a(g18 Va tp4753 a(g185 V tp4754 a(g343 V=> p4755 tp4756 a(g185 V tp4757 a(g18 Va tp4758 a(g185 V tp4759 a(g343 V-> p4760 tp4761 a(g185 V tp4762 a(g135 VSeries p4763 tp4764 a(g185 V tp4765 a(g135 VResult p4766 tp4767 a(g185 V\u000a tp4768 a(g21 Vevaluate p4769 tp4770 a(g185 V tp4771 a(g18 Vx tp4772 a(g185 V tp4773 a(g18 Vd tp4774 a(g185 V tp4775 a(g343 V= tp4776 a(g185 V tp4777 a(g18 Vrs p4778 tp4779 a(g185 V tp4780 a(g123 Vwhere p4781 tp4782 a(g185 V tp4783 a(g135 VProp p4784 tp4785 a(g185 V tp4786 a(g18 Vrs p4787 tp4788 a(g185 V tp4789 a(g343 V= tp4790 a(g185 V tp4791 a(g18 Vproperty p4792 tp4793 a(g185 V tp4794 a(g18 Vx tp4795 a(g185 V tp4796 a(g18 Vd tp4797 a(g185 V\u000a\u000a p4798 tp4799 a(g21 VforAll p4800 tp4801 a(g185 V tp4802 a(g343 V:: p4803 tp4804 a(g185 V tp4805 a(g198 V( tp4806 a(g135 VShow p4807 tp4808 a(g185 V tp4809 a(g18 Va tp4810 a(g198 V, tp4811 a(g185 V tp4812 a(g135 VTestable p4813 tp4814 a(g185 V tp4815 a(g18 Vb tp4816 a(g198 V) tp4817 a(g185 V tp4818 a(g343 V=> p4819 tp4820 a(g185 V tp4821 a(g135 VSeries p4822 tp4823 a(g185 V tp4824 a(g18 Va tp4825 a(g185 V tp4826 a(g343 V-> p4827 tp4828 a(g185 V tp4829 a(g198 V( tp4830 a(g18 Va tp4831 a(g343 V-> p4832 tp4833 a(g18 Vb tp4834 a(g198 V) tp4835 a(g185 V tp4836 a(g343 V-> p4837 tp4838 a(g185 V tp4839 a(g135 VProperty p4840 tp4841 a(g185 V\u000a tp4842 a(g21 VforAll p4843 tp4844 a(g185 V tp4845 a(g18 Vxs p4846 tp4847 a(g185 V tp4848 a(g18 Vf tp4849 a(g185 V tp4850 a(g343 V= tp4851 a(g185 V tp4852 a(g135 VProperty p4853 tp4854 a(g185 V tp4855 a(g339 V$ tp4856 a(g185 V tp4857 a(g21 V\u005c tp4858 a(g18 Vd tp4859 a(g185 V tp4860 a(g343 V-> p4861 tp4862 a(g185 V tp4863 a(g135 VProp p4864 tp4865 a(g185 V tp4866 a(g339 V$ tp4867 a(g185 V\u000a p4868 tp4869 a(g198 V[ tp4870 a(g185 V tp4871 a(g18 Vr tp4872 a(g198 V{ tp4873 a(g18 Varguments p4874 tp4875 a(g185 V tp4876 a(g343 V= tp4877 a(g185 V tp4878 a(g18 Vshow p4879 tp4880 a(g185 V tp4881 a(g18 Vx tp4882 a(g185 V tp4883 a(g135 V: tp4884 a(g185 V tp4885 a(g18 Varguments p4886 tp4887 a(g185 V tp4888 a(g18 Vr tp4889 a(g198 V} tp4890 a(g185 V\u000a p4891 tp4892 a(g339 V| tp4893 a(g185 V tp4894 a(g18 Vx tp4895 a(g185 V tp4896 a(g343 V<- p4897 tp4898 a(g185 V tp4899 a(g18 Vxs p4900 tp4901 a(g185 V tp4902 a(g18 Vd tp4903 a(g198 V, tp4904 a(g185 V tp4905 a(g18 Vr tp4906 a(g185 V tp4907 a(g343 V<- p4908 tp4909 a(g185 V tp4910 a(g18 Vevaluate p4911 tp4912 a(g185 V tp4913 a(g198 V( tp4914 a(g18 Vf tp4915 a(g185 V tp4916 a(g18 Vx tp4917 a(g198 V) tp4918 a(g185 V tp4919 a(g18 Vd tp4920 a(g185 V tp4921 a(g198 V] tp4922 a(g185 V\u000a\u000a p4923 tp4924 a(g21 VforAllElem p4925 tp4926 a(g185 V tp4927 a(g343 V:: p4928 tp4929 a(g185 V tp4930 a(g198 V( tp4931 a(g135 VShow p4932 tp4933 a(g185 V tp4934 a(g18 Va tp4935 a(g198 V, tp4936 a(g185 V tp4937 a(g135 VTestable p4938 tp4939 a(g185 V tp4940 a(g18 Vb tp4941 a(g198 V) tp4942 a(g185 V tp4943 a(g343 V=> p4944 tp4945 a(g185 V tp4946 a(g198 V[ tp4947 a(g18 Va tp4948 a(g198 V] tp4949 a(g185 V tp4950 a(g343 V-> p4951 tp4952 a(g185 V tp4953 a(g198 V( tp4954 a(g18 Va tp4955 a(g343 V-> p4956 tp4957 a(g18 Vb tp4958 a(g198 V) tp4959 a(g185 V tp4960 a(g343 V-> p4961 tp4962 a(g185 V tp4963 a(g135 VProperty p4964 tp4965 a(g185 V\u000a tp4966 a(g21 VforAllElem p4967 tp4968 a(g185 V tp4969 a(g18 Vxs p4970 tp4971 a(g185 V tp4972 a(g343 V= tp4973 a(g185 V tp4974 a(g18 VforAll p4975 tp4976 a(g185 V tp4977 a(g198 V( tp4978 a(g18 Vconst p4979 tp4980 a(g185 V tp4981 a(g18 Vxs p4982 tp4983 a(g198 V) tp4984 a(g185 V\u000a\u000a p4985 tp4986 a(g21 VthereExists p4987 tp4988 a(g185 V tp4989 a(g343 V:: p4990 tp4991 a(g185 V tp4992 a(g135 VTestable p4993 tp4994 a(g185 V tp4995 a(g18 Vb tp4996 a(g185 V tp4997 a(g343 V=> p4998 tp4999 a(g185 V tp5000 a(g135 VSeries p5001 tp5002 a(g185 V tp5003 a(g18 Va tp5004 a(g185 V tp5005 a(g343 V-> p5006 tp5007 a(g185 V tp5008 a(g198 V( tp5009 a(g18 Va tp5010 a(g343 V-> p5011 tp5012 a(g18 Vb tp5013 a(g198 V) tp5014 a(g185 V tp5015 a(g343 V-> p5016 tp5017 a(g185 V tp5018 a(g135 VProperty p5019 tp5020 a(g185 V\u000a tp5021 a(g21 VthereExists p5022 tp5023 a(g185 V tp5024 a(g18 Vxs p5025 tp5026 a(g185 V tp5027 a(g18 Vf tp5028 a(g185 V tp5029 a(g343 V= tp5030 a(g185 V tp5031 a(g135 VProperty p5032 tp5033 a(g185 V tp5034 a(g339 V$ tp5035 a(g185 V tp5036 a(g21 V\u005c tp5037 a(g18 Vd tp5038 a(g185 V tp5039 a(g343 V-> p5040 tp5041 a(g185 V tp5042 a(g135 VProp p5043 tp5044 a(g185 V tp5045 a(g339 V$ tp5046 a(g185 V\u000a p5047 tp5048 a(g198 V[ tp5049 a(g185 V tp5050 a(g135 VResult p5051 tp5052 a(g185 V\u000a p5053 tp5054 a(g198 V( tp5055 a(g185 V tp5056 a(g135 VJust p5057 tp5058 a(g185 V tp5059 a(g339 V$ tp5060 a(g185 V tp5061 a(g18 Vor p5062 tp5063 a(g185 V tp5064 a(g198 V[ tp5065 a(g185 V tp5066 a(g18 Vall p5067 tp5068 a(g185 V tp5069 a(g18 Vpass p5070 tp5071 a(g185 V tp5072 a(g198 V( tp5073 a(g18 Vevaluate p5074 tp5075 a(g185 V tp5076 a(g198 V( tp5077 a(g18 Vf tp5078 a(g185 V tp5079 a(g18 Vx tp5080 a(g198 V) tp5081 a(g185 V tp5082 a(g18 Vd tp5083 a(g198 V) tp5084 a(g185 V\u000a p5085 tp5086 a(g339 V| tp5087 a(g185 V tp5088 a(g18 Vx tp5089 a(g185 V tp5090 a(g343 V<- p5091 tp5092 a(g185 V tp5093 a(g18 Vxs p5094 tp5095 a(g185 V tp5096 a(g18 Vd tp5097 a(g185 V tp5098 a(g198 V] tp5099 a(g185 V tp5100 a(g198 V) tp5101 a(g185 V\u000a p5102 tp5103 a(g135 V[] p5104 tp5105 a(g185 V tp5106 a(g198 V] tp5107 a(g185 V \u000a p5108 tp5109 a(g123 Vwhere p5110 tp5111 a(g185 V\u000a p5112 tp5113 a(g18 Vpass p5114 tp5115 a(g185 V tp5116 a(g198 V( tp5117 a(g135 VResult p5118 tp5119 a(g185 V tp5120 a(g135 VNothing p5121 tp5122 a(g185 V tp5123 a(g123 V_ tp5124 a(g198 V) tp5125 a(g185 V p5126 tp5127 a(g343 V= tp5128 a(g185 V tp5129 a(g135 VTrue p5130 tp5131 a(g185 V\u000a p5132 tp5133 a(g18 Vpass p5134 tp5135 a(g185 V tp5136 a(g198 V( tp5137 a(g135 VResult p5138 tp5139 a(g185 V tp5140 a(g198 V( tp5141 a(g135 VJust p5142 tp5143 a(g185 V tp5144 a(g18 Vb tp5145 a(g198 V) tp5146 a(g185 V tp5147 a(g123 V_ tp5148 a(g198 V) tp5149 a(g185 V tp5150 a(g343 V= tp5151 a(g185 V tp5152 a(g18 Vb tp5153 a(g185 V\u000a\u000a p5154 tp5155 a(g21 VthereExistsElem p5156 tp5157 a(g185 V tp5158 a(g343 V:: p5159 tp5160 a(g185 V tp5161 a(g135 VTestable p5162 tp5163 a(g185 V tp5164 a(g18 Vb tp5165 a(g185 V tp5166 a(g343 V=> p5167 tp5168 a(g185 V tp5169 a(g198 V[ tp5170 a(g18 Va tp5171 a(g198 V] tp5172 a(g185 V tp5173 a(g343 V-> p5174 tp5175 a(g185 V tp5176 a(g198 V( tp5177 a(g18 Va tp5178 a(g343 V-> p5179 tp5180 a(g18 Vb tp5181 a(g198 V) tp5182 a(g185 V tp5183 a(g343 V-> p5184 tp5185 a(g185 V tp5186 a(g135 VProperty p5187 tp5188 a(g185 V\u000a tp5189 a(g21 VthereExistsElem p5190 tp5191 a(g185 V tp5192 a(g18 Vxs p5193 tp5194 a(g185 V tp5195 a(g343 V= tp5196 a(g185 V tp5197 a(g18 VthereExists p5198 tp5199 a(g185 V tp5200 a(g198 V( tp5201 a(g18 Vconst p5202 tp5203 a(g185 V tp5204 a(g18 Vxs p5205 tp5206 a(g198 V) tp5207 a(g185 V\u000a\u000a p5208 tp5209 a(g21 Vexists p5210 tp5211 a(g185 V tp5212 a(g343 V:: p5213 tp5214 a(g185 V tp5215 a(g198 V( tp5216 a(g135 VSerial p5217 tp5218 a(g185 V tp5219 a(g18 Va tp5220 a(g198 V, tp5221 a(g185 V tp5222 a(g135 VTestable p5223 tp5224 a(g185 V tp5225 a(g18 Vb tp5226 a(g198 V) tp5227 a(g185 V tp5228 a(g343 V=> p5229 tp5230 a(g185 V\u000a p5231 tp5232 a(g198 V( tp5233 a(g18 Va tp5234 a(g343 V-> p5235 tp5236 a(g18 Vb tp5237 a(g198 V) tp5238 a(g185 V tp5239 a(g343 V-> p5240 tp5241 a(g185 V tp5242 a(g135 VProperty p5243 tp5244 a(g185 V\u000a tp5245 a(g21 Vexists p5246 tp5247 a(g185 V tp5248 a(g343 V= tp5249 a(g185 V tp5250 a(g18 VthereExists p5251 tp5252 a(g185 V tp5253 a(g18 Vseries p5254 tp5255 a(g185 V\u000a\u000a p5256 tp5257 a(g21 VexistsDeeperBy p5258 tp5259 a(g185 V tp5260 a(g343 V:: p5261 tp5262 a(g185 V tp5263 a(g198 V( tp5264 a(g135 VSerial p5265 tp5266 a(g185 V tp5267 a(g18 Va tp5268 a(g198 V, tp5269 a(g185 V tp5270 a(g135 VTestable p5271 tp5272 a(g185 V tp5273 a(g18 Vb tp5274 a(g198 V) tp5275 a(g185 V tp5276 a(g343 V=> p5277 tp5278 a(g185 V\u000a p5279 tp5280 a(g198 V( tp5281 a(g135 VInt p5282 tp5283 a(g343 V-> p5284 tp5285 a(g135 VInt p5286 tp5287 a(g198 V) tp5288 a(g185 V tp5289 a(g343 V-> p5290 tp5291 a(g185 V tp5292 a(g198 V( tp5293 a(g18 Va tp5294 a(g343 V-> p5295 tp5296 a(g18 Vb tp5297 a(g198 V) tp5298 a(g185 V tp5299 a(g343 V-> p5300 tp5301 a(g185 V tp5302 a(g135 VProperty p5303 tp5304 a(g185 V\u000a tp5305 a(g21 VexistsDeeperBy p5306 tp5307 a(g185 V tp5308 a(g18 Vf tp5309 a(g185 V tp5310 a(g343 V= tp5311 a(g185 V tp5312 a(g18 VthereExists p5313 tp5314 a(g185 V tp5315 a(g198 V( tp5316 a(g18 Vseries p5317 tp5318 a(g185 V tp5319 a(g339 V. tp5320 a(g185 V tp5321 a(g18 Vf tp5322 a(g198 V) tp5323 a(g185 V\u000a \u000a p5324 tp5325 a(g123 Vinfixr p5326 tp5327 a(g185 V tp5328 a(g314 V0 tp5329 a(g185 V tp5330 a(g339 V==> p5331 tp5332 a(g185 V\u000a\u000a p5333 tp5334 a(g198 V( tp5335 a(g339 V==> p5336 tp5337 a(g198 V) tp5338 a(g185 V tp5339 a(g343 V:: p5340 tp5341 a(g185 V tp5342 a(g135 VTestable p5343 tp5344 a(g185 V tp5345 a(g18 Va tp5346 a(g185 V tp5347 a(g343 V=> p5348 tp5349 a(g185 V tp5350 a(g135 VBool p5351 tp5352 a(g185 V tp5353 a(g343 V-> p5354 tp5355 a(g185 V tp5356 a(g18 Va tp5357 a(g185 V tp5358 a(g343 V-> p5359 tp5360 a(g185 V tp5361 a(g135 VProperty p5362 tp5363 a(g185 V\u000a tp5364 a(g135 VTrue p5365 tp5366 a(g185 V tp5367 a(g339 V==> p5368 tp5369 a(g185 V p5370 tp5371 a(g18 Vx tp5372 a(g185 V tp5373 a(g343 V= tp5374 a(g185 V tp5375 a(g135 VProperty p5376 tp5377 a(g185 V tp5378 a(g198 V( tp5379 a(g18 Vproperty p5380 tp5381 a(g185 V tp5382 a(g18 Vx tp5383 a(g198 V) tp5384 a(g185 V\u000a tp5385 a(g135 VFalse p5386 tp5387 a(g185 V tp5388 a(g339 V==> p5389 tp5390 a(g185 V tp5391 a(g18 Vx tp5392 a(g185 V tp5393 a(g343 V= tp5394 a(g185 V tp5395 a(g135 VProperty p5396 tp5397 a(g185 V tp5398 a(g198 V( tp5399 a(g18 Vconst p5400 tp5401 a(g185 V tp5402 a(g198 V( tp5403 a(g18 Vresult p5404 tp5405 a(g185 V tp5406 a(g18 Vnothing p5407 tp5408 a(g198 V) tp5409 a(g198 V) tp5410 a(g185 V\u000a\u000a p5411 tp5412 a(g7 V--------------------- <top-level test drivers> ---------------------- p5413 tp5414 a(g185 V\u000a\u000a p5415 tp5416 a(g7 V-- similar in spirit to QuickCheck but with iterative deepening p5417 tp5418 a(g185 V\u000a\u000a p5419 tp5420 a(g7 V-- test for values of depths 0..d stopping when a property p5421 tp5422 a(g185 V\u000a tp5423 a(g7 V-- fails or when it has been checked for all these values p5424 tp5425 a(g185 V\u000a tp5426 a(g21 VsmallCheck p5427 tp5428 a(g185 V tp5429 a(g343 V:: p5430 tp5431 a(g185 V tp5432 a(g135 VTestable p5433 tp5434 a(g185 V tp5435 a(g18 Va tp5436 a(g185 V tp5437 a(g343 V=> p5438 tp5439 a(g185 V tp5440 a(g135 VInt p5441 tp5442 a(g185 V tp5443 a(g343 V-> p5444 tp5445 a(g185 V tp5446 a(g18 Va tp5447 a(g185 V tp5448 a(g343 V-> p5449 tp5450 a(g185 V tp5451 a(g135 VIO p5452 tp5453 a(g185 V tp5454 a(g135 VString p5455 tp5456 a(g185 V\u000a tp5457 a(g21 VsmallCheck p5458 tp5459 a(g185 V tp5460 a(g18 Vd tp5461 a(g185 V tp5462 a(g343 V= tp5463 a(g185 V tp5464 a(g18 ViterCheck p5465 tp5466 a(g185 V tp5467 a(g314 V0 tp5468 a(g185 V tp5469 a(g198 V( tp5470 a(g135 VJust p5471 tp5472 a(g185 V tp5473 a(g18 Vd tp5474 a(g198 V) tp5475 a(g185 V\u000a\u000a p5476 tp5477 a(g21 VdepthCheck p5478 tp5479 a(g185 V tp5480 a(g343 V:: p5481 tp5482 a(g185 V tp5483 a(g135 VTestable p5484 tp5485 a(g185 V tp5486 a(g18 Va tp5487 a(g185 V tp5488 a(g343 V=> p5489 tp5490 a(g185 V tp5491 a(g135 VInt p5492 tp5493 a(g185 V tp5494 a(g343 V-> p5495 tp5496 a(g185 V tp5497 a(g18 Va tp5498 a(g185 V tp5499 a(g343 V-> p5500 tp5501 a(g185 V tp5502 a(g135 VIO p5503 tp5504 a(g185 V tp5505 a(g135 VString p5506 tp5507 a(g185 V\u000a tp5508 a(g21 VdepthCheck p5509 tp5510 a(g185 V tp5511 a(g18 Vd tp5512 a(g185 V tp5513 a(g343 V= tp5514 a(g185 V tp5515 a(g18 ViterCheck p5516 tp5517 a(g185 V tp5518 a(g18 Vd tp5519 a(g185 V tp5520 a(g198 V( tp5521 a(g135 VJust p5522 tp5523 a(g185 V tp5524 a(g18 Vd tp5525 a(g198 V) tp5526 a(g185 V\u000a\u000a p5527 tp5528 a(g21 ViterCheck p5529 tp5530 a(g185 V tp5531 a(g343 V:: p5532 tp5533 a(g185 V tp5534 a(g135 VTestable p5535 tp5536 a(g185 V tp5537 a(g18 Va tp5538 a(g185 V tp5539 a(g343 V=> p5540 tp5541 a(g185 V tp5542 a(g135 VInt p5543 tp5544 a(g185 V tp5545 a(g343 V-> p5546 tp5547 a(g185 V tp5548 a(g135 VMaybe p5549 tp5550 a(g185 V tp5551 a(g135 VInt p5552 tp5553 a(g185 V tp5554 a(g343 V-> p5555 tp5556 a(g185 V tp5557 a(g18 Va tp5558 a(g185 V tp5559 a(g343 V-> p5560 tp5561 a(g185 V tp5562 a(g135 VIO p5563 tp5564 a(g185 V tp5565 a(g135 VString p5566 tp5567 a(g185 V\u000a tp5568 a(g21 ViterCheck p5569 tp5570 a(g185 V tp5571 a(g18 VdFrom p5572 tp5573 a(g185 V tp5574 a(g18 VmdTo p5575 tp5576 a(g185 V tp5577 a(g18 Vt tp5578 a(g185 V tp5579 a(g343 V= tp5580 a(g185 V tp5581 a(g18 Viter p5582 tp5583 a(g185 V tp5584 a(g18 VdFrom p5585 tp5586 a(g185 V\u000a p5587 tp5588 a(g123 Vwhere p5589 tp5590 a(g185 V\u000a p5591 tp5592 a(g18 Viter p5593 tp5594 a(g185 V tp5595 a(g343 V:: p5596 tp5597 a(g185 V tp5598 a(g135 VInt p5599 tp5600 a(g185 V tp5601 a(g343 V-> p5602 tp5603 a(g185 V tp5604 a(g135 VIO p5605 tp5606 a(g185 V tp5607 a(g135 VString p5608 tp5609 a(g185 V\u000a p5610 tp5611 a(g18 Viter p5612 tp5613 a(g185 V tp5614 a(g18 Vd tp5615 a(g185 V tp5616 a(g343 V= tp5617 a(g185 V tp5618 a(g123 Vdo p5619 tp5620 a(g185 V\u000a p5621 tp5622 a(g123 Vlet p5623 tp5624 a(g185 V tp5625 a(g135 VProp p5626 tp5627 a(g185 V tp5628 a(g18 Vresults p5629 tp5630 a(g185 V tp5631 a(g343 V= tp5632 a(g185 V tp5633 a(g18 Vproperty p5634 tp5635 a(g185 V tp5636 a(g18 Vt tp5637 a(g185 V tp5638 a(g18 Vd tp5639 a(g185 V\u000a p5640 tp5641 a(g198 V( tp5642 a(g18 Vok p5643 tp5644 a(g198 V, tp5645 a(g18 Vs tp5646 a(g198 V) tp5647 a(g185 V tp5648 a(g343 V<- p5649 tp5650 a(g185 V tp5651 a(g18 Vcheck p5652 tp5653 a(g185 V tp5654 a(g198 V( tp5655 a(g18 VmdTo p5656 tp5657 a(g339 V== p5658 tp5659 a(g135 VNothing p5660 tp5661 a(g198 V) tp5662 a(g185 V tp5663 a(g314 V0 tp5664 a(g185 V tp5665 a(g314 V0 tp5666 a(g185 V tp5667 a(g135 VTrue p5668 tp5669 a(g185 V tp5670 a(g18 Vresults p5671 tp5672 a(g185 V\u000a p5673 tp5674 a(g18 Vmaybe p5675 tp5676 a(g185 V tp5677 a(g198 V( tp5678 a(g18 Viter p5679 tp5680 a(g185 V tp5681 a(g198 V( tp5682 a(g18 Vd tp5683 a(g339 V+ tp5684 a(g314 V1 tp5685 a(g198 V) tp5686 a(g198 V) tp5687 a(g185 V\u000a p5688 tp5689 a(g198 V( tp5690 a(g21 V\u005c tp5691 a(g18 VdTo p5692 tp5693 a(g185 V tp5694 a(g343 V-> p5695 tp5696 a(g185 V tp5697 a(g123 Vif p5698 tp5699 a(g185 V tp5700 a(g18 Vok p5701 tp5702 a(g185 V tp5703 a(g339 V&& p5704 tp5705 a(g185 V tp5706 a(g18 Vd tp5707 a(g185 V tp5708 a(g339 V< tp5709 a(g185 V tp5710 a(g18 VdTo p5711 tp5712 a(g185 V\u000a p5713 tp5714 a(g123 Vthen p5715 tp5716 a(g185 V tp5717 a(g18 Viter p5718 tp5719 a(g185 V tp5720 a(g198 V( tp5721 a(g18 Vd tp5722 a(g339 V+ tp5723 a(g314 V1 tp5724 a(g198 V) tp5725 a(g185 V\u000a p5726 tp5727 a(g123 Velse p5728 tp5729 a(g185 V tp5730 a(g18 Vreturn p5731 tp5732 a(g185 V tp5733 a(g18 Vs tp5734 a(g198 V) tp5735 a(g185 V\u000a p5736 tp5737 a(g18 VmdTo p5738 tp5739 a(g185 V\u000a\u000a p5740 tp5741 a(g21 Vcheck p5742 tp5743 a(g185 V tp5744 a(g343 V:: p5745 tp5746 a(g185 V tp5747 a(g135 VBool p5748 tp5749 a(g185 V tp5750 a(g343 V-> p5751 tp5752 a(g185 V tp5753 a(g135 VInt p5754 tp5755 a(g185 V tp5756 a(g343 V-> p5757 tp5758 a(g185 V tp5759 a(g135 VInt p5760 tp5761 a(g185 V tp5762 a(g343 V-> p5763 tp5764 a(g185 V tp5765 a(g135 VBool p5766 tp5767 a(g185 V tp5768 a(g343 V-> p5769 tp5770 a(g185 V tp5771 a(g198 V[ tp5772 a(g135 VResult p5773 tp5774 a(g198 V] tp5775 a(g185 V tp5776 a(g343 V-> p5777 tp5778 a(g185 V tp5779 a(g135 VIO p5780 tp5781 a(g185 V tp5782 a(g198 V( tp5783 a(g135 VBool p5784 tp5785 a(g198 V, tp5786 a(g185 V tp5787 a(g135 VString p5788 tp5789 a(g198 V) tp5790 a(g185 V\u000a tp5791 a(g21 Vcheck p5792 tp5793 a(g185 V tp5794 a(g18 Vi tp5795 a(g185 V tp5796 a(g18 Vn tp5797 a(g185 V tp5798 a(g18 Vx tp5799 a(g185 V tp5800 a(g18 Vok p5801 tp5802 a(g185 V tp5803 a(g18 Vrs p5804 tp5805 a(g185 V tp5806 a(g339 V| tp5807 a(g185 V tp5808 a(g18 Vnull p5809 tp5810 a(g185 V tp5811 a(g18 Vrs p5812 tp5813 a(g185 V tp5814 a(g343 V= tp5815 a(g185 V tp5816 a(g123 Vdo p5817 tp5818 a(g185 V\u000a p5819 tp5820 a(g123 Vlet p5821 tp5822 a(g185 V tp5823 a(g18 Vs tp5824 a(g185 V tp5825 a(g343 V= tp5826 a(g185 V tp5827 a(g222 V" tp5828 a(g222 V Completed p5829 tp5830 a(g222 V" tp5831 a(g339 V++ p5832 tp5833 a(g18 Vshow p5834 tp5835 a(g185 V tp5836 a(g18 Vn tp5837 a(g339 V++ p5838 tp5839 a(g222 V" tp5840 a(g222 V test(s) p5841 tp5842 a(g222 V" tp5843 a(g185 V\u000a p5844 tp5845 a(g18 Vy tp5846 a(g185 V tp5847 a(g343 V= tp5848 a(g185 V tp5849 a(g123 Vif p5850 tp5851 a(g185 V tp5852 a(g18 Vi tp5853 a(g185 V tp5854 a(g123 Vthen p5855 tp5856 a(g185 V tp5857 a(g222 V" tp5858 a(g222 V. tp5859 a(g222 V" tp5860 a(g185 V tp5861 a(g123 Velse p5862 tp5863 a(g185 V tp5864 a(g222 V" tp5865 a(g222 V without failure. p5866 tp5867 a(g222 V" tp5868 a(g185 V\u000a p5869 tp5870 a(g18 Vz tp5871 a(g185 V tp5872 a(g339 V| tp5873 a(g185 V tp5874 a(g18 Vx tp5875 a(g185 V tp5876 a(g339 V> tp5877 a(g185 V tp5878 a(g314 V0 tp5879 a(g185 V p5880 tp5881 a(g343 V= tp5882 a(g185 V tp5883 a(g222 V" tp5884 a(g222 V But p5885 tp5886 a(g222 V" tp5887 a(g339 V++ p5888 tp5889 a(g18 Vshow p5890 tp5891 a(g185 V tp5892 a(g18 Vx tp5893 a(g339 V++ p5894 tp5895 a(g222 V" tp5896 a(g222 V did not meet ==> condition. p5897 tp5898 a(g222 V" tp5899 a(g185 V\u000a p5900 tp5901 a(g339 V| tp5902 a(g185 V tp5903 a(g18 Votherwise p5904 tp5905 a(g185 V tp5906 a(g343 V= tp5907 a(g185 V tp5908 a(g222 V" tp5909 a(g222 V" tp5910 a(g185 V\u000a p5911 tp5912 a(g18 Vreturn p5913 tp5914 a(g185 V tp5915 a(g198 V( tp5916 a(g18 Vok p5917 tp5918 a(g198 V, tp5919 a(g185 V tp5920 a(g18 Vs tp5921 a(g185 V tp5922 a(g339 V++ p5923 tp5924 a(g185 V tp5925 a(g18 Vy tp5926 a(g185 V tp5927 a(g339 V++ p5928 tp5929 a(g185 V tp5930 a(g18 Vz tp5931 a(g198 V) tp5932 a(g185 V\u000a\u000a p5933 tp5934 a(g21 Vcheck p5935 tp5936 a(g185 V tp5937 a(g18 Vi tp5938 a(g185 V tp5939 a(g18 Vn tp5940 a(g185 V tp5941 a(g18 Vx tp5942 a(g185 V tp5943 a(g18 Vok p5944 tp5945 a(g185 V tp5946 a(g198 V( tp5947 a(g135 VResult p5948 tp5949 a(g185 V tp5950 a(g135 VNothing p5951 tp5952 a(g185 V tp5953 a(g123 V_ tp5954 a(g185 V tp5955 a(g135 V: tp5956 a(g185 V tp5957 a(g18 Vrs p5958 tp5959 a(g198 V) tp5960 a(g185 V tp5961 a(g343 V= tp5962 a(g185 V tp5963 a(g123 Vdo p5964 tp5965 a(g185 V\u000a p5966 tp5967 a(g18 VprogressReport p5968 tp5969 a(g185 V tp5970 a(g18 Vi tp5971 a(g185 V tp5972 a(g18 Vn tp5973 a(g185 V tp5974 a(g18 Vx tp5975 a(g185 V\u000a p5976 tp5977 a(g18 Vcheck p5978 tp5979 a(g185 V tp5980 a(g18 Vi tp5981 a(g185 V tp5982 a(g198 V( tp5983 a(g18 Vn tp5984 a(g339 V+ tp5985 a(g314 V1 tp5986 a(g198 V) tp5987 a(g185 V tp5988 a(g198 V( tp5989 a(g18 Vx tp5990 a(g339 V+ tp5991 a(g314 V1 tp5992 a(g198 V) tp5993 a(g185 V tp5994 a(g18 Vok p5995 tp5996 a(g185 V tp5997 a(g18 Vrs p5998 tp5999 a(g185 V\u000a\u000a p6000 tp6001 a(g21 Vcheck p6002 tp6003 a(g185 V tp6004 a(g18 Vi tp6005 a(g185 V tp6006 a(g18 Vn tp6007 a(g185 V tp6008 a(g18 Vx tp6009 a(g185 V tp6010 a(g18 Vf tp6011 a(g185 V tp6012 a(g198 V( tp6013 a(g135 VResult p6014 tp6015 a(g185 V tp6016 a(g198 V( tp6017 a(g135 VJust p6018 tp6019 a(g185 V tp6020 a(g135 VTrue p6021 tp6022 a(g198 V) tp6023 a(g185 V tp6024 a(g123 V_ tp6025 a(g185 V tp6026 a(g135 V: tp6027 a(g185 V tp6028 a(g18 Vrs p6029 tp6030 a(g198 V) tp6031 a(g185 V tp6032 a(g343 V= tp6033 a(g185 V tp6034 a(g123 Vdo p6035 tp6036 a(g185 V\u000a p6037 tp6038 a(g18 VprogressReport p6039 tp6040 a(g185 V tp6041 a(g18 Vi tp6042 a(g185 V tp6043 a(g18 Vn tp6044 a(g185 V tp6045 a(g18 Vx tp6046 a(g185 V\u000a p6047 tp6048 a(g18 Vcheck p6049 tp6050 a(g185 V tp6051 a(g18 Vi tp6052 a(g185 V tp6053 a(g198 V( tp6054 a(g18 Vn tp6055 a(g339 V+ tp6056 a(g314 V1 tp6057 a(g198 V) tp6058 a(g185 V tp6059 a(g18 Vx tp6060 a(g185 V tp6061 a(g18 Vf tp6062 a(g185 V tp6063 a(g18 Vrs p6064 tp6065 a(g185 V\u000a\u000a p6066 tp6067 a(g21 Vcheck p6068 tp6069 a(g185 V tp6070 a(g18 Vi tp6071 a(g185 V tp6072 a(g18 Vn tp6073 a(g185 V tp6074 a(g18 Vx tp6075 a(g185 V tp6076 a(g18 Vf tp6077 a(g185 V tp6078 a(g198 V( tp6079 a(g135 VResult p6080 tp6081 a(g185 V tp6082 a(g198 V( tp6083 a(g135 VJust p6084 tp6085 a(g185 V tp6086 a(g135 VFalse p6087 tp6088 a(g198 V) tp6089 a(g185 V tp6090 a(g18 Vargs p6091 tp6092 a(g185 V tp6093 a(g135 V: tp6094 a(g185 V tp6095 a(g18 Vrs p6096 tp6097 a(g198 V) tp6098 a(g185 V tp6099 a(g343 V= tp6100 a(g185 V tp6101 a(g123 Vdo p6102 tp6103 a(g185 V\u000a p6104 tp6105 a(g123 Vlet p6106 tp6107 a(g185 V tp6108 a(g18 Vs tp6109 a(g185 V tp6110 a(g343 V= tp6111 a(g185 V tp6112 a(g222 V" tp6113 a(g222 V Failed test no. p6114 tp6115 a(g222 V" tp6116 a(g339 V++ p6117 tp6118 a(g18 Vshow p6119 tp6120 a(g185 V tp6121 a(g198 V( tp6122 a(g18 Vn tp6123 a(g339 V+ tp6124 a(g314 V1 tp6125 a(g198 V) tp6126 a(g339 V++ p6127 tp6128 a(g222 V" tp6129 a(g222 V. Test values follow. p6130 tp6131 a(g222 V" tp6132 a(g185 V\u000a p6133 tp6134 a(g18 Vs' p6135 tp6136 a(g185 V tp6137 a(g343 V= tp6138 a(g185 V tp6139 a(g18 Vs tp6140 a(g185 V tp6141 a(g339 V++ p6142 tp6143 a(g185 V tp6144 a(g222 V" tp6145 a(g222 V: p6146 tp6147 a(g222 V" tp6148 a(g185 V tp6149 a(g339 V++ p6150 tp6151 a(g185 V tp6152 a(g18 Vconcat p6153 tp6154 a(g185 V tp6155 a(g198 V( tp6156 a(g18 Vintersperse p6157 tp6158 a(g185 V tp6159 a(g222 V" tp6160 a(g222 V, p6161 tp6162 a(g222 V" tp6163 a(g185 V tp6164 a(g18 Vargs p6165 tp6166 a(g198 V) tp6167 a(g185 V\u000a p6168 tp6169 a(g123 Vif p6170 tp6171 a(g185 V tp6172 a(g18 Vi tp6173 a(g185 V tp6174 a(g123 Vthen p6175 tp6176 a(g185 V\u000a p6177 tp6178 a(g18 Vcheck p6179 tp6180 a(g185 V tp6181 a(g18 Vi tp6182 a(g185 V tp6183 a(g198 V( tp6184 a(g18 Vn tp6185 a(g339 V+ tp6186 a(g314 V1 tp6187 a(g198 V) tp6188 a(g185 V tp6189 a(g18 Vx tp6190 a(g185 V tp6191 a(g135 VFalse p6192 tp6193 a(g185 V tp6194 a(g18 Vrs p6195 tp6196 a(g185 V\u000a p6197 tp6198 a(g123 Velse p6199 tp6200 a(g185 V\u000a p6201 tp6202 a(g18 Vreturn p6203 tp6204 a(g185 V tp6205 a(g198 V( tp6206 a(g135 VFalse p6207 tp6208 a(g198 V, tp6209 a(g185 V tp6210 a(g18 Vs' p6211 tp6212 a(g198 V) tp6213 a(g185 V\u000a\u000a p6214 tp6215 a(g21 VprogressReport p6216 tp6217 a(g185 V tp6218 a(g343 V:: p6219 tp6220 a(g185 V tp6221 a(g135 VBool p6222 tp6223 a(g185 V tp6224 a(g343 V-> p6225 tp6226 a(g185 V tp6227 a(g135 VInt p6228 tp6229 a(g185 V tp6230 a(g343 V-> p6231 tp6232 a(g185 V tp6233 a(g135 VInt p6234 tp6235 a(g185 V tp6236 a(g343 V-> p6237 tp6238 a(g185 V tp6239 a(g135 VIO p6240 tp6241 a(g185 V tp6242 a(g57 V() p6243 tp6244 a(g185 V\u000a tp6245 a(g21 VprogressReport p6246 tp6247 a(g185 V tp6248 a(g123 V_ tp6249 a(g185 V tp6250 a(g123 V_ tp6251 a(g185 V tp6252 a(g123 V_ tp6253 a(g185 V tp6254 a(g343 V= tp6255 a(g185 V tp6256 a(g18 Vreturn p6257 tp6258 a(g185 V tp6259 a(g57 V() p6260 tp6261 a(g185 V\u000a tp6262 a.
qsnake/pygments
tests/examplefiles/output/SmallCheck.hs
bsd-2-clause
99,778
796
5
19,315
50,465
27,762
22,703
-1
-1
-- Copyright (c) 2012-2019, Christopher Hall <[email protected]> -- Licence BSD2 see LICENSE file {-# LANGUAGE OverloadedStrings, DeriveGeneric #-} module SessionParser where import Data.Aeson --import Data.Aeson.Encode.Pretty (encodePretty) import Data.Text import Data.String import Control.Monad (mzero) import qualified Data.ByteString.Lazy as B import GHC.Generics data Orientation = LeftTabs | RightTabs | TopTabs | BottomTabs deriving Show data Session = Session { name :: !String , orientation :: !Orientation , tabs :: ![String] } deriving (Show, Generic) instance FromJSON Session instance ToJSON Session -- conversion of Orientation to and from JSON toOrientation :: Text -> Orientation toOrientation "top" = TopTabs toOrientation "bottom" = BottomTabs toOrientation "left" = LeftTabs toOrientation "right" = RightTabs toOrientation _ = error "Invalid orientation" fromOrientation :: Data.String.IsString a => Orientation -> a fromOrientation TopTabs = "top" fromOrientation BottomTabs = "bottom" fromOrientation LeftTabs = "left" fromOrientation RightTabs = "right" instance FromJSON Orientation where parseJSON (String v) = return $ toOrientation v parseJSON _ = mzero instance ToJSON Orientation where toJSON tblr = fromOrientation tblr readSession :: String -> IO (Maybe Session) readSession filename = do d <- (eitherDecode <$> getJSON) :: IO (Either String Session) case d of -- error with string Left err -> do putStrLn err return Nothing -- success with Session Right s -> return $ Just s where getJSON = B.readFile filename writeSession :: Session -> String -> IO () writeSession session fileName = putJSON $ encode session where putJSON s = B.writeFile fileName s
hxw/conlecterm
src/SessionParser.hs
bsd-2-clause
1,859
0
12
411
448
233
215
52
2
{-# LANGUAGE CPP #-} module Main where import System.FilePath import System.Process import Control.Monad (when) import System.Exit import System.Directory import System.IO.Error import Control.Exception (catch) import Control.Monad.Error (ErrorT(..)) import Language.GTL.Parser.Monad as GTL import Language.GTL.Parser as GTL import Language.Scade.Lexer as Sc import Language.Scade.Parser as Sc import Language.Promela.Pretty import Language.Scade.Pretty import Language.UPPAAL.PrettyPrinter import Language.GTL.Target.PromelaKCG import Language.GTL.Target.Local import Language.GTL.Translation import Language.GTL.Model --import Language.GTL.Target.PromelaCUDD as PrBd --import Language.GTL.Target.PrettyPrinter as PrPr import Language.GTL.Target.Promela as PrNat import Language.GTL.Target.UPPAAL as UPP import Language.GTL.Target.Printer import Language.GTL.Target.SMT as SMT import Misc.ProgramOptions versionString :: String versionString = "This is the GALS Translation Language of version "++version++".\nBuilt on "++date++"." ++(case tag of Nothing -> "" Just rtag -> "\nBuilt from git tag: "++rtag++".") ++(case branch of Nothing -> "" Just rbranch -> "\nBuilt from git branch: "++rbranch++".") ++smtExts where #ifdef BUILD_VERSION version = BUILD_VERSION #else version = "unknown" #endif #ifdef BUILD_DATE date = BUILD_DATE #else date = "unknown date" #endif #ifdef BUILD_TAG tag = Just BUILD_TAG #else tag = Nothing #endif #ifdef BUILD_BRANCH branch = Just BUILD_BRANCH #else branch = Nothing #endif #ifdef SMTExts smtExts = "" #else smtExts = "\nWARNING: Built with Z3 specific SMT output." #endif main = do opts <- getOptions when (showHelp opts) $ do putStr usage exitSuccess when (showVersion opts) $ do putStrLn versionString exitSuccess let gtl_file = gtlFile opts when (gtl_file == "") $ do ioError $ userError "No GTL file given" exists <- doesFileExist gtl_file when (not exists) $ do ioError . userError $ (gtl_file ++ " does not exist.") (createDirectoryIfMissing True $ outputPath opts) `catch` (\e -> putStrLn $ "Could not create build dir: " ++ (ioeGetErrorString e)) gtl_str <- readFile gtl_file mgtl <- case runGTLParser gtl gtl_str of Left (err,pos) -> return (Left $ "At "++show pos++": "++err) Right defs -> runErrorT $ gtlParseSpec opts defs rgtl <- case mgtl of Left err -> error err Right x -> return x case mode opts of NativeC -> translateGTL (traceFile opts) rgtl >>= putStrLn Local -> verifyLocal opts (dropExtension gtl_file) rgtl --PromelaBuddy -> PrBd.verifyModel opts (dropExtension gtl_file) rgtl {-Tikz -> do str <- PrPr.gtlToTikz rgtl putStrLn str-} Pretty -> putStrLn (simplePrettyPrint rgtl) Native -> PrNat.verifyModel opts (dropExtension gtl_file) rgtl UPPAAL -> putStr (prettySpecification $ UPP.translateSpec rgtl) SMTBMC -> SMT.verifyModelBMC opts rgtl --SMTInduction -> SMT.verifyModelKInduction (smtBinary opts) rgtl return ()
hguenther/gtl
Main.hs
bsd-3-clause
3,183
0
16
678
769
413
356
71
8
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} module Main where import TestUtil import Control.Exception import Control.Monad (when) import Criterion.Main import Data.ExternalSort (externalSortFile) import System.Directory import System.Environment import System.Exit main :: IO () main = do args <- getArgs when (length args < 2) $ do putStrLn "Usage: sort-tester <number of ints> <chunk size>" exitWith (ExitFailure 1) let numberOfIntsStr:chunkSizeStr:restArgs = args putStrLn "Generating random file..." inFile <- genRandomFile (read numberOfIntsStr) outFile <- genOutputFileName finally (withArgs restArgs $ defaultMain [ bgroup "sort-tester" [ bench "sort" $ nfIO (externalSortFile (int32SortCfgOfSize (read chunkSizeStr)) inFile outFile) ] ]) (do removeFile inFile removeFile outFile)
sseefried/external-sort
test/SortTester.hs
bsd-3-clause
1,012
0
21
307
239
116
123
28
1
module Arguments ( Arguments (..) , opts ) where import Options.Applicative import Data.Maybe import Data.Time data Arguments = Arguments { runRate :: NominalDiffTime , exceptionRate :: NominalDiffTime , configFile :: FilePath , logFile :: FilePath , debug :: Bool } setDefault :: Alternative m => a -> m a -> m a setDefault def = fmap (fromMaybe def) . optional parseArgs :: Parser Arguments parseArgs = Arguments <$> ( setDefault 300 . fmap fromIntegral . option auto $ ( short 'r' <> long "runRate" <> metavar "INT" <> help "Rough interval (in seconds) between runs of log-monitor (default 300s)" ) ) <*> ( setDefault 604800 . fmap fromIntegral . option auto $ ( short 'e' <> long "exceptionRate" <> metavar "INT" <> help "Interval (in seconds) for which to email admins with log parsing errors (default one week)" ) ) <*> ( setDefault "log-monitor.yaml" . strOption $ ( short 'c' <> long "config-file" <> metavar "FILE" <> help "Path to config file (default log-monitor.yaml)" ) ) <*> ( setDefault "log-monitor.log" . strOption $ ( short 'l' <> long "log-file" <> metavar "FILE" <> help "File to store log-monitor logs (default log-monitor.log)" ) ) <*> ( switch $ ( short 'd' <> long "debug" <> help "Log additional debugging information" ) ) opts = info (helper <*> parseArgs) ( header "Monitor hslogger-logs and email in case of error." <> fullDesc <> footer "Log file formats require $msg, $loggername, $utcTime and $prio." )
prophet-on-that/log-monitor
src-exe/log-monitor/Arguments.hs
bsd-3-clause
1,887
0
16
694
395
198
197
47
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedLists #-} -- | Optics for the @lens@ library that correspond to the types in -- "Penny.Copper.Types" are in this module. module Penny.Copper.Optics ( module Penny.Copper.Optics.Auto , module Penny.Copper.Optics.Manual ) where import Penny.Copper.Optics.Auto import Penny.Copper.Optics.Manual
massysett/penny
penny/lib/Penny/Copper/Optics.hs
bsd-3-clause
356
0
5
49
43
32
11
7
0
module SOPBench.Roundtrip where import qualified Generics.SOP as SOP import qualified GHC.Generics as GHC class Roundtrip a where roundtrip :: a -> a soproundtrip :: SOP.Generic a => a -> a soproundtrip = SOP.to . SOP.from ghcroundtrip :: GHC.Generic a => a -> a ghcroundtrip = GHC.to . GHC.from
well-typed/generics-sop
generics-sop/bench/SOPBench/Roundtrip.hs
bsd-3-clause
303
0
7
55
102
57
45
9
1
{-# LANGUAGE InstanceSigs #-} -- Because i love it {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RankNTypes #-} -- See syntaxIso module Sky.Parsing.Invertible where import Prelude hiding (id, (.), (<$>), (<*>), pure, print) import Control.Category -- yay import Control.Monad (liftM2, mplus) import Data.Functor.Identity import Text.Read (readMaybe) import Data.Maybe (fromJust) import Sky.Isomorphism.Simple ---------------------------------------------------------------------------------------------------- -- Doesn't work with the van Laarhoven SemiIso: f (SemiIso' ...) requires ImpredicativeTypes -- We are using the simpler version to have an instance of Category. type Iso a b = MumuIso Maybe a b -- Semi-Isomorphisms on lists nil :: Iso () [a] nil = iso (\_ -> return []) toNil where toNil [] = Just () toNil _ = Nothing cons :: Iso (a, [a]) [a] cons = iso doCons headTail where doCons (x, xs) = Just (x : xs) headTail [] = Nothing headTail (x : xs) = Just (x, xs) many :: forall p a. (Syntax p) => p a -> p [a] many p = nil <$> pure () <|> cons <$> p <*> many p -- Semi-Isomorphism for specific characters onlyChar :: Char -> Iso Char Char onlyChar c = iso check check where check input = if input == c then Just c else Nothing ---------------------------------------------------------------------------------------------------- {- A haskell functor is covariant: fmap :: forall f a b. (Functor f) => (a -> b) -> f a -> f b This works for parsers, e.g.: newtype Parser a = Parser { _parse :: String -> a } instance Functor Parser where fmap :: forall a b. (a -> b) -> Parser a -> Parser b fmap f (Parser p) = Parser (f . p) -} {- Pretty-printers on the other hand are contravariant: cofmap :: forall f a b. (Contravariant f) => (a -> b) -> f b -> f a E.g.: newtype Printer a = Printer { _print :: a -> String } instance Contravariant Printer where contramap :: forall a b. (a -> b) -> Printer b -> Printer a contramap f (Printer p) = Printer (p . f) -} {- In order to get both, we can simply apply an isomorphism instead of a function: -} class IsoFunctor f where isomap :: forall a b. Iso a b -> f a -> f b {- We could also make this a profunctor... if it really had 2 arguments. -} infixl 5 <$> (<$>) :: forall f a b. (IsoFunctor f) => Iso a b -> f a -> f b (<$>) = isomap --infixl 4 <*> --class IsoFunctor f => IsoApplicative f where -- (<*>) :: forall a b. f (Iso a b) -> f a -> f b class ProductFunctor f where productF :: forall a b. f a -> f b -> f (a, b) infixl 6 <*> (<*>) :: forall f a b. (ProductFunctor f) => f a -> f b -> f (a, b) (<*>) = productF class Alternative f where emptyF :: forall a. f a choiceF :: forall a. f a -> f a -> f a infixl 4 <|> (<|>) :: forall f a. (Alternative f) => f a -> f a -> f a (<|>) = choiceF class (IsoFunctor f, ProductFunctor f, Alternative f) => Syntax f where pure :: forall a. (Eq a) => a -> f a token :: f Char ---------------------------------------------------------------------------------------------------- -- Demo syntax --demoSyntax :: Parser [[Char]] demoSyntax :: Syntax s => s [[Char]] demoSyntax = many syntaxAB where syntaxAB = cons <$> syntaxA <*> (cons <$> syntaxB <*> (nil <$> pure ())) syntaxA = onlyChar 'a' <$> token syntaxB = onlyChar 'b' <$> token ---------------------------------------------------------------------------------------------------- -- Parser ---- Simple parser / pp from read / show --mkInvertible :: forall a. (Read a, Show a) => Iso String a --mkInvertible = iso readMaybe (return . show) newtype Parser a = Parser { _parse :: String -> [(a, String)] } parse :: Parser a -> String -> [a] parse (Parser p) s = [ x | (x, "") <- p s ] parse1 :: Parser a -> String -> Maybe a parse1 p s = case parse p s of [] -> Nothing (x : _) -> Just x instance IsoFunctor Parser where isomap :: forall a b. Iso a b -> Parser a -> Parser b isomap iso (Parser p) = Parser q where q s = [ (y, rest) | (x, rest) <- p s -- Parse using p , Just y <- [apply iso x] -- Apply isomorphism to results x ] instance ProductFunctor Parser where productF :: forall a b. Parser a -> Parser b -> Parser (a, b) productF (Parser pa) (Parser pb) = Parser p where p s = [ ((x,y), rest2) | (x, rest1) <- pa s -- Parse using pa , (y, rest2) <- pb rest1 -- Parse rest using pb ] instance Alternative Parser where emptyF :: forall a. Parser a emptyF = Parser (\_ -> []) -- Parse nothing (fail) choiceF :: forall a. Parser a -> Parser a -> Parser a choiceF (Parser pa) (Parser pb) = Parser p where p s = pa s ++ pb s -- Simply find all results from either pa or pb instance Syntax Parser where pure :: forall a. (Eq a) => a -> Parser a pure a = Parser (\s -> [(a, s)]) -- Don't parse, just generate a token :: Parser Char token = Parser p where p [] = [] -- No more input p (x : xs) = [(x, xs)] -- Accept x -- Lets test it demoParse = _parse demoSyntax "ababcd" where -- parse demoParser "abab" where ---------------------------------------------------------------------------------------------------- -- Prettyprinter newtype Printer a = Printer { _print :: a -> Maybe String } print :: Printer a -> a -> Maybe String print = _print -- print (Printer p) x = p x instance IsoFunctor Printer where isomap :: forall a b. Iso a b -> Printer a -> Printer b isomap iso (Printer p) = Printer q where q v = unapply iso v -- First "fetch" the value using iso >>= p -- Then print instance ProductFunctor Printer where productF :: forall a b. Printer a -> Printer b -> Printer (a, b) productF (Printer pa) (Printer pb) = Printer p where p (va, vb) = liftM2 (++) (pa va) (pb vb) instance Alternative Printer where emptyF :: forall a. Printer a emptyF = Printer (\_ -> Nothing) -- Just fail choiceF :: forall a. Printer a -> Printer a -> Printer a choiceF (Printer pa) (Printer pb) = Printer p where p v = mplus (pa v) (pb v) -- Print using pa, or pb if pa fails {- case pa v of Just result -> Just result Nothing -> pb v -} instance Syntax Printer where pure :: forall a. (Eq a) => a -> Printer a pure v = Printer p where p value = if value == v -- Check then Just "" -- but don't print else Nothing token :: Printer Char token = Printer p where p v = Just [v] -- Print it -- Lets test it demoPrint = _print demoSyntax ["ab","ab"] where ---------------------------------------------------------------------------------------------------- -- Parser and Prettyprinter are an isomorphism! syntaxIso :: forall a. (forall s. (Syntax s) => s a) -> Iso String a syntaxIso s = iso (parse1 s) (print s) syntaxIsoDemo :: IO () syntaxIsoDemo = do demo <- return $ syntaxIso demoSyntax parsed <- return $ apply demo "ababab" putStrLn $ "Parsed: " ++ show parsed printed <- return $ unapply demo (fromJust parsed) putStrLn $ "Printed: " ++ show printed return ()
xicesky/sky-haskell-playground
src/Sky/Parsing/Invertible.hs
bsd-3-clause
7,624
0
13
2,186
2,122
1,139
983
124
2