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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
-- odds :: Int -> [Int]
-- returns the first n odds
odds n = map f [0..n-1]
where f x = x * 2 + 1
-- defined using lambda notation
odds n = map (\ x -> x * 2 + 1) [0..n-1]
|
calebgregory/fp101x
|
wk2/odds.hs
|
mit
| 176 | 6 | 9 | 49 | 96 | 43 | 53 | 3 | 1 |
import Data.List
import Network
import System.IO
import Control.Monad.Reader
import System.Exit
import Control.Exception
import Text.Printf
import Text.Regex.Posix
server = "irc.esper.net"
port = 6667
chan = "#gamocosm"
nick = "hmmmbot"
putStrLnStderr :: String -> IO ()
putStrLnStderr str = hPutStrLn stderr str
main :: IO ()
main = bracket connect hClose run
connect :: IO Handle
connect = do
h <- connectTo server (PortNumber (fromIntegral port))
hSetBuffering h NoBuffering
return h
sock_write :: Handle -> String -> String -> IO ()
sock_write h s t = do
hPrintf h "%s %s\r\n" s t
putStrLnStderr $ printf "< %s %s" s t
sock_read :: Handle -> IO String
sock_read h = hGetLine h
run :: Handle -> IO ()
run h = do
sock_write h "NICK" nick
sock_write h "USER" $ printf "%s 0 * :%s" nick nick
forever $ do
line <- sock_read h
deal_with_it h line join_room
ping :: String -> Bool
ping line | "PING :" `isPrefixOf` line = True
ping _ = False
pong :: Handle -> String -> IO ()
pong h line = do
putStrLnStderr line
sock_write h "PONG" (':' : drop 6 line)
deal_with_it :: Handle -> String -> (Handle -> String -> IO ()) -> IO ()
deal_with_it h line _ | ping line = pong h line
deal_with_it h line fn = fn h line
join_room :: Handle -> String -> IO ()
join_room h line | (printf ":%s MODE %s" nick nick) `isPrefixOf` line = do
sock_write h "JOIN" chan
forever $ do
line <- sock_read h
deal_with_it h line process
join_room _ line = putStrLnStderr line
process :: Handle -> String -> IO ()
process h line =
let
process' _ ((_:user:msg:_):_) = do
putStrLn $ printf "> %s: %s" user (init msg)
hFlush stdout
process' line _ = putStrLnStderr line
in process' line (line =~ ((printf ":(.*)!.* PRIVMSG %s :(.*)" chan) :: String) :: [[String]])
|
Raekye/irc-bot-history
|
ibh.hs
|
mit
| 1,774 | 7 | 15 | 358 | 804 | 368 | 436 | 59 | 2 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.NavigatorUserMediaErrorCallback
(newNavigatorUserMediaErrorCallback,
newNavigatorUserMediaErrorCallbackSync,
newNavigatorUserMediaErrorCallbackAsync,
NavigatorUserMediaErrorCallback)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUserMediaErrorCallback Mozilla NavigatorUserMediaErrorCallback documentation>
newNavigatorUserMediaErrorCallback ::
(MonadDOM m) =>
(NavigatorUserMediaError -> JSM ()) ->
m NavigatorUserMediaErrorCallback
newNavigatorUserMediaErrorCallback callback
= liftDOM
(NavigatorUserMediaErrorCallback . Callback <$>
function
(\ _ _ [error] ->
fromJSValUnchecked error >>= \ error' -> callback error'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUserMediaErrorCallback Mozilla NavigatorUserMediaErrorCallback documentation>
newNavigatorUserMediaErrorCallbackSync ::
(MonadDOM m) =>
(NavigatorUserMediaError -> JSM ()) ->
m NavigatorUserMediaErrorCallback
newNavigatorUserMediaErrorCallbackSync callback
= liftDOM
(NavigatorUserMediaErrorCallback . Callback <$>
function
(\ _ _ [error] ->
fromJSValUnchecked error >>= \ error' -> callback error'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUserMediaErrorCallback Mozilla NavigatorUserMediaErrorCallback documentation>
newNavigatorUserMediaErrorCallbackAsync ::
(MonadDOM m) =>
(NavigatorUserMediaError -> JSM ()) ->
m NavigatorUserMediaErrorCallback
newNavigatorUserMediaErrorCallbackAsync callback
= liftDOM
(NavigatorUserMediaErrorCallback . Callback <$>
asyncFunction
(\ _ _ [error] ->
fromJSValUnchecked error >>= \ error' -> callback error'))
|
ghcjs/jsaddle-dom
|
src/JSDOM/Generated/NavigatorUserMediaErrorCallback.hs
|
mit
| 3,050 | 0 | 13 | 753 | 561 | 335 | 226 | 51 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.Storage
(js_key, key, js_getItem, getItem, js_setItem, setItem,
js_removeItem, removeItem, js_clear, clear, js_getLength,
getLength, Storage, castToStorage, gTypeStorage)
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 (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
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.Enums
foreign import javascript unsafe "$1[\"key\"]($2)" js_key ::
JSRef Storage -> Word -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.key Mozilla Storage.key documentation>
key ::
(MonadIO m, FromJSString result) =>
Storage -> Word -> m (Maybe result)
key self index
= liftIO (fromMaybeJSString <$> (js_key (unStorage self) index))
foreign import javascript unsafe "$1[\"getItem\"]($2)" js_getItem
:: JSRef Storage -> JSString -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.getItem Mozilla Storage.getItem documentation>
getItem ::
(MonadIO m, ToJSString key, FromJSString result) =>
Storage -> key -> m (Maybe result)
getItem self key
= liftIO
(fromMaybeJSString <$>
(js_getItem (unStorage self) (toJSString key)))
foreign import javascript unsafe "$1[\"setItem\"]($2, $3)"
js_setItem :: JSRef Storage -> JSString -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.setItem Mozilla Storage.setItem documentation>
setItem ::
(MonadIO m, ToJSString key, ToJSString data') =>
Storage -> key -> data' -> m ()
setItem self key data'
= liftIO
(js_setItem (unStorage self) (toJSString key) (toJSString data'))
foreign import javascript unsafe "$1[\"removeItem\"]($2)"
js_removeItem :: JSRef Storage -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.removeItem Mozilla Storage.removeItem documentation>
removeItem :: (MonadIO m, ToJSString key) => Storage -> key -> m ()
removeItem self key
= liftIO (js_removeItem (unStorage self) (toJSString key))
foreign import javascript unsafe "$1[\"clear\"]()" js_clear ::
JSRef Storage -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.clear Mozilla Storage.clear documentation>
clear :: (MonadIO m) => Storage -> m ()
clear self = liftIO (js_clear (unStorage self))
foreign import javascript unsafe "$1[\"length\"]" js_getLength ::
JSRef Storage -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.length Mozilla Storage.length documentation>
getLength :: (MonadIO m) => Storage -> m Word
getLength self = liftIO (js_getLength (unStorage self))
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/JSFFI/Generated/Storage.hs
|
mit
| 3,381 | 46 | 11 | 530 | 915 | 515 | 400 | 56 | 1 |
module Main where
import Data.List
import Control.Monad
import Control.Applicative
import System.IO
main = do
ls <- lines <$> readFile "../JavaScript/JQuery/UI/Internal.hs"
h <- openFile "../JavaScript/JQuery/UI/nonghcjs.txt" WriteMode
forM_ ls $ \l -> do
let sig = filter ("jq_" `isPrefixOf`) (tails l)
case sig of
[] -> return ()
(x:_) -> do
let fun = head (words x)
hPutStrLn h (unwords . words $ x)
hPutStrLn h (fun ++ " = error \"" ++ fun ++ ": only available in JavaScript\"")
hClose h
|
co-dan/ghcjs-jqueryui
|
util/genNonGhcjs.hs
|
mit
| 549 | 0 | 21 | 137 | 195 | 96 | 99 | 17 | 2 |
-- -*- mode: haskell -*-
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
module SAT.State where
-- $Id$
import SAT.Types
import Autolib.ToDoc
import Autolib.Reader
import Autolib.Set
import qualified Autolib.Relation as Relation
import Autolib.FiniteMap
data State =
State { assignment :: Belegung -- ^ erfüllend
, satisfying :: Set Literal -- ^ dazu gehörende literale
, todo :: Int -- ^ noch so viele klauseln
, width :: Int -- ^ soviele literale pro klausel
, formula :: Formel -- ^ soweit schon gebaut
, clause :: Klausel -- ^ currently being built
, csat :: Bool -- ^ klausel ist bereits erfüllt?
, unfrequent :: Set Literal
, morefrequent :: Set Literal
, dependencies :: Relation.Type Variable Variable
}
$(derives [makeReader, makeToDoc] [''State])
|
Erdwolf/autotool-bonn
|
src/SAT/State.hs
|
gpl-2.0
| 824 | 5 | 10 | 179 | 156 | 101 | 55 | 20 | 0 |
module Main where
import System.Environment(getArgs)
primes :: [Int]
primes = sieve [2..]
where sieve (p:xs) = p : sieve [ x | x <- xs, x `mod` p /= 0 ]
countPrimes :: Int -> Int -> Int
countPrimes lower upper =
length $ takeWhile (<= upper) $ dropWhile (< lower) $ primes
processLine :: String -> String
processLine line =
let (lower,upper) = read ("(" ++ line ++ ")")
in show $ countPrimes lower upper
main :: IO ()
main = do
[inputFile] <- getArgs
input <- readFile inputFile
mapM_ putStrLn $ map processLine $ lines input
|
cryptica/CodeEval
|
Challenges/63_CountingPrimes/main.hs
|
gpl-3.0
| 561 | 0 | 12 | 133 | 244 | 126 | 118 | 17 | 1 |
{-# LANGUAGE NamedFieldPuns, BangPatterns #-}
module Runtime.PID
( PID
, Message(..)
, writePID
, readPID
, tID, newPID, forkPID) where
import Control.Concurrent
import Control.Concurrent.STM
import Data.Map.Strict (Map)
import Name
import Runtime.Hole
data PID obj = PID {q :: TQueue (Message obj), tID :: ThreadId} deriving Eq
type ShadowMap obj = Map ThreadId (PID obj)
data Message obj =
Quit
| Mark ([PID obj] -> IO())
| Call Name [obj] (ShadowMap obj) (Hole obj) (Hole obj)
instance Show (PID a) where
show PID{tID = x} = show x
writePID PID{q}= writeTQueue q
readPID PID{q} = readTQueue q
newPID :: IO (PID a)
newPID = do
q <- newTQueueIO
PID q <$> myThreadId
forkPID :: (PID a -> IO ()) -> IO (PID a)
forkPID action = do
q <- newTQueueIO
tID <- forkIO $ do
pid <- PID q <$> myThreadId
action pid
let pid = PID{q,tID}
return pid
|
antarestrader/sapphire
|
Runtime/PID.hs
|
gpl-3.0
| 890 | 0 | 13 | 202 | 387 | 204 | 183 | 34 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Hoodle.Widget.Clock
-- Copyright : (c) 2013 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-- Clock widget drawing and action
--
-----------------------------------------------------------------------------
module Hoodle.Widget.Clock where
import Control.Lens (view,set,over)
import Control.Monad.State
import Data.Functor.Identity (Identity(..))
import Data.List (delete)
import Data.Time
import Graphics.Rendering.Cairo
--
import Data.Hoodle.BBox
import Data.Hoodle.Simple
import Graphics.Hoodle.Render.Util.HitTest
--
import Hoodle.Coroutine.Draw
import Hoodle.Coroutine.Pen
import Hoodle.Device
import Hoodle.Type.Canvas
import Hoodle.Type.Coroutine
import Hoodle.Type.Enum
import Hoodle.Type.Event
import Hoodle.Type.HoodleState
import Hoodle.Type.PageArrangement
import Hoodle.Type.Widget
import Hoodle.View.Coordinate
import Hoodle.View.Draw
--
-- |
data CWAction = Move (CanvasCoordinate,CanvasCoordinate)
deriving (Show)
checkPointerInClock :: (CanvasId,CanvasInfo a,CanvasGeometry)
-> PointerCoord
-> Maybe CWAction
checkPointerInClock (_cid,cinfo,geometry) pcoord
| b =
let oxy@(CvsCoord (x,y)) = (desktop2Canvas geometry . device2Desktop geometry) pcoord
owxy@(CvsCoord (x0,y0)) = view (canvasWidgets.clockWidgetConfig.clockWidgetPosition) cinfo
obbox = BBox (x0-50,y0-50) (x0+50,y0+50)
r | isPointInBBox obbox (x,y) = Just (Move (oxy,owxy))
| otherwise = Nothing
in r
| otherwise = Nothing
where b = view (canvasWidgets.widgetConfig.doesUseClockWidget) cinfo
-- |
startClockWidget :: (CanvasId,CanvasInfo a,CanvasGeometry)
-> CWAction
-> MainCoroutine ()
startClockWidget (cid,cinfo,geometry) (Move (oxy,owxy)) = do
xst <- get
let hdl = getHoodle xst
(srcsfc,Dim wsfc hsfc) <- liftIO (canvasImageSurface Nothing geometry hdl)
-- need to draw other widgets here
let otherwidgets = delete ClockWidget allWidgets
liftIO $ renderWith srcsfc (drawWidgets otherwidgets hdl cinfo Nothing)
-- end : need to draw other widgets here ^^^
tgtsfc <- liftIO $ createImageSurface FormatARGB32 (floor wsfc) (floor hsfc)
ctime <- liftIO getCurrentTime
manipulateCW cid geometry (srcsfc,tgtsfc) owxy oxy ctime
liftIO $ surfaceFinish srcsfc
liftIO $ surfaceFinish tgtsfc
-- | main event loop for clock widget
manipulateCW :: CanvasId
-> CanvasGeometry
-> (Surface,Surface)
-> CanvasCoordinate
-> CanvasCoordinate
-> UTCTime
-> MainCoroutine ()
manipulateCW cid geometry (srcsfc,tgtsfc) owxy oxy otime = do
r <- nextevent
case r of
PenMove _ pcoord -> do
processWithDefTimeInterval
(manipulateCW cid geometry (srcsfc,tgtsfc) owxy oxy)
(\ctime -> moveClockWidget cid geometry (srcsfc,tgtsfc) owxy oxy pcoord
>> manipulateCW cid geometry (srcsfc,tgtsfc) owxy oxy ctime)
otime
PenUp _ _ -> invalidate cid
_ -> return ()
moveClockWidget :: CanvasId
-> CanvasGeometry
-> (Surface,Surface)
-> CanvasCoordinate
-> CanvasCoordinate
-> PointerCoord
-> MainCoroutine ()
moveClockWidget cid geometry (srcsfc,tgtsfc) (CvsCoord (xw,yw)) (CvsCoord (x0,y0)) pcoord = do
let CvsCoord (x,y) = (desktop2Canvas geometry . device2Desktop geometry) pcoord
xst <- get
let CanvasDimension (Dim cw ch) = canvasDim geometry
cinfobox = getCanvasInfo cid xst
nposx | xw+x-x0 < -50 = -50
| xw+x-x0 > cw-50 = cw-50
| otherwise = xw+x-x0
nposy | yw+y-y0 < -50 = -50
| yw+y-y0 > ch-50 = ch-50
| otherwise = yw+y-y0
nwpos = CvsCoord (nposx,nposy)
changeact :: CanvasInfo a -> CanvasInfo a
changeact cinfo =
set (canvasWidgets.clockWidgetConfig.clockWidgetPosition) nwpos $ cinfo
ncinfobox = (runIdentity . forBoth unboxBiXform (return . changeact)) cinfobox
put (setCanvasInfo (cid,ncinfobox) xst)
--
xst2 <- get
let cinfobox2 = getCanvasInfo cid xst2
cfg = view (unboxLens (canvasWidgets.clockWidgetConfig)) cinfobox2
liftIO $ forBoth' unboxBiAct (\cinfo-> virtualDoubleBufferDraw srcsfc tgtsfc (return ())
(renderClockWidget Nothing cfg)
>> doubleBufferFlush tgtsfc cinfo) cinfobox2
-- |
toggleClock :: CanvasId -> MainCoroutine ()
toggleClock cid = do
modify (\xst ->
let ncinfobox = (over (unboxLens (canvasWidgets.widgetConfig.doesUseClockWidget)) not
. getCanvasInfo cid ) xst
in setCanvasInfo (cid,ncinfobox) xst)
invalidateInBBox Nothing Efficient cid
|
wavewave/hoodle-core
|
src/Hoodle/Widget/Clock.hs
|
gpl-3.0
| 5,455 | 0 | 22 | 1,677 | 1,474 | 771 | 703 | 106 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.Packed.Static.Imports
-- Copyright : (c) Reiner Pope 2008
-- License : GPL-style
--
-- Maintainer : Reiner Pope <[email protected]>
-- Stability : experimental
-- Portability : portable
--
-- Useful imports from other packages. In particular:
-- imports from TFP, Foreign.Storable, and HMatrix.
--
-----------------------------------------------------------------------------
module Data.Packed.Static.Imports(
H.Element,
H.Field,
H.Linear,
F.Storable,
module Types.Data.Num,
True,
(:<=:),
Min,
) where
import qualified Numeric.LinearAlgebra as H
import qualified Foreign.Storable as F
import Types.Data.Num
import Types.Data.Bool(True)
import Types.Data.Ord((:<=:), Min)
|
reinerp/hmatrix-static
|
Data/Packed/Static/Imports.hs
|
gpl-3.0
| 826 | 0 | 5 | 131 | 112 | 81 | 31 | 14 | 0 |
module QFeldspar.Nat.TH where
import QFeldspar.MyPrelude
import Language.Haskell.TH.Syntax
nat :: Word32 -> String -> Q Exp
nat 0 p = do Just nm <- lookupValueName (p ++ "Zro")
return (ConE nm)
nat n p = do Just nm <- lookupValueName (p ++ "Suc")
AppE (ConE nm) <$> (nat (n - 1) p)
natP :: Word32 -> String -> Q Pat
natP 0 p = do Just nm <- lookupValueName (p ++ "Zro")
return (ConP nm [])
natP n p = do Just nm <- lookupValueName (p ++ "Suc")
sp <- natP (n - 1) p
return (ConP nm [sp])
natT :: Word32 -> String -> Q Type
natT 0 p = do Just nm <- lookupValueName (p ++ "Zro")
return (ConT nm)
natT n p = do Just nm <- lookupValueName (p ++ "Suc")
AppT (ConT nm) <$> (natT (n - 1) p)
|
shayan-najd/QFeldspar
|
QFeldspar/Nat/TH.hs
|
gpl-3.0
| 783 | 0 | 11 | 242 | 385 | 185 | 200 | 19 | 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.Subnetworks.Insert
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a subnetwork in the specified project using the data included in
-- the request.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.subnetworks.insert@.
module Network.Google.Resource.Compute.Subnetworks.Insert
(
-- * REST Resource
SubnetworksInsertResource
-- * Creating a Request
, subnetworksInsert
, SubnetworksInsert
-- * Request Lenses
, siProject
, siPayload
, siRegion
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.subnetworks.insert@ method which the
-- 'SubnetworksInsert' request conforms to.
type SubnetworksInsertResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"regions" :>
Capture "region" Text :>
"subnetworks" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Subnetwork :> Post '[JSON] Operation
-- | Creates a subnetwork in the specified project using the data included in
-- the request.
--
-- /See:/ 'subnetworksInsert' smart constructor.
data SubnetworksInsert = SubnetworksInsert'
{ _siProject :: !Text
, _siPayload :: !Subnetwork
, _siRegion :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'SubnetworksInsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'siProject'
--
-- * 'siPayload'
--
-- * 'siRegion'
subnetworksInsert
:: Text -- ^ 'siProject'
-> Subnetwork -- ^ 'siPayload'
-> Text -- ^ 'siRegion'
-> SubnetworksInsert
subnetworksInsert pSiProject_ pSiPayload_ pSiRegion_ =
SubnetworksInsert'
{ _siProject = pSiProject_
, _siPayload = pSiPayload_
, _siRegion = pSiRegion_
}
-- | Project ID for this request.
siProject :: Lens' SubnetworksInsert Text
siProject
= lens _siProject (\ s a -> s{_siProject = a})
-- | Multipart request metadata.
siPayload :: Lens' SubnetworksInsert Subnetwork
siPayload
= lens _siPayload (\ s a -> s{_siPayload = a})
-- | Name of the region scoping this request.
siRegion :: Lens' SubnetworksInsert Text
siRegion = lens _siRegion (\ s a -> s{_siRegion = a})
instance GoogleRequest SubnetworksInsert where
type Rs SubnetworksInsert = Operation
type Scopes SubnetworksInsert =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient SubnetworksInsert'{..}
= go _siProject _siRegion (Just AltJSON) _siPayload
computeService
where go
= buildClient
(Proxy :: Proxy SubnetworksInsertResource)
mempty
|
rueshyna/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/Subnetworks/Insert.hs
|
mpl-2.0
| 3,652 | 0 | 16 | 869 | 470 | 281 | 189 | 73 | 1 |
import System.Random
main = do
putStr . show =<< randomRIO (0, 100 :: Int)
putStr ", "
print =<< randomRIO (0, 100 :: Int)
print =<< (randomIO :: IO Float)
f1 <- randomIO :: IO Float
putStr $ show (f1 * 5 + 5) ++ ", "
f2 <- randomIO :: IO Float
print $ f2 * 5 + 5
let s1 = mkStdGen 42
let (i1, s2) = randomR (0, 100 :: Int) s1
let (i2, _) = randomR (0, 100 :: Int) s2
putStrLn $ show i1 ++ ", " ++ show i2
let s3 = mkStdGen 42
let (i3, s4) = randomR (0, 100 :: Int) s3
let (i4, _) = randomR (0, 100 :: Int) s4
putStrLn $ show i3 ++ ", " ++ show i4
|
daewon/til
|
haskell/haskell_by_example/random_number.hs
|
mpl-2.0
| 628 | 0 | 12 | 210 | 327 | 161 | 166 | 18 | 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.Glacier.ListVaults
-- 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.
-- | This operation lists all vaults owned by the calling user's account. The list
-- returned in the response is ASCII-sorted by vault name.
--
-- By default, this operation returns up to 1,000 items. If there are more
-- vaults to list, the response 'marker' field contains the vault Amazon Resource
-- Name (ARN) at which to continue the list with a new List Vaults request;
-- otherwise, the 'marker' field is 'null'. To return a list of vaults that begins
-- at a specific vault, set the 'marker' request parameter to the vault ARN you
-- obtained from a previous List Vaults request. You can also limit the number
-- of vaults returned in the response by specifying the 'limit' parameter in the
-- request.
--
-- An AWS account has full permission to perform all operations (actions).
-- However, AWS Identity and Access Management (IAM) users don't have any
-- permissions by default. You must grant them explicit permission to perform
-- specific actions. For more information, see <http://docs.aws.amazon.com/amazonglacier/latest/dev/using-iam-with-amazon-glacier.html Access Control Using AWS Identityand Access Management (IAM)>.
--
-- For conceptual information and underlying REST API, go to <http://docs.aws.amazon.com/amazonglacier/latest/dev/retrieving-vault-info.html Retrieving VaultMetadata in Amazon Glacier> and <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-vaults-get.html List Vaults > in the /Amazon Glacier DeveloperGuide/.
--
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-ListVaults.html>
module Network.AWS.Glacier.ListVaults
(
-- * Request
ListVaults
-- ** Request constructor
, listVaults
-- ** Request lenses
, lvAccountId
, lvLimit
, lvMarker
-- * Response
, ListVaultsResponse
-- ** Response constructor
, listVaultsResponse
-- ** Response lenses
, lvrMarker
, lvrVaultList
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.RestJSON
import Network.AWS.Glacier.Types
import qualified GHC.Exts
data ListVaults = ListVaults
{ _lvAccountId :: Text
, _lvLimit :: Maybe Text
, _lvMarker :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'ListVaults' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lvAccountId' @::@ 'Text'
--
-- * 'lvLimit' @::@ 'Maybe' 'Text'
--
-- * 'lvMarker' @::@ 'Maybe' 'Text'
--
listVaults :: Text -- ^ 'lvAccountId'
-> ListVaults
listVaults p1 = ListVaults
{ _lvAccountId = p1
, _lvMarker = Nothing
, _lvLimit = Nothing
}
-- | The 'AccountId' value is the AWS account ID. This value must match the AWS
-- account ID associated with the credentials used to sign the request. You can
-- either specify an AWS account ID or optionally a single apos'-'apos (hyphen),
-- in which case Amazon Glacier uses the AWS account ID associated with the
-- credentials used to sign the request. If you specify your Account ID, do not
-- include any hyphens (apos-apos) in the ID.
lvAccountId :: Lens' ListVaults Text
lvAccountId = lens _lvAccountId (\s a -> s { _lvAccountId = a })
-- | The maximum number of items returned in the response. If you don't specify a
-- value, the List Vaults operation returns up to 1,000 items.
lvLimit :: Lens' ListVaults (Maybe Text)
lvLimit = lens _lvLimit (\s a -> s { _lvLimit = a })
-- | A string used for pagination. The marker specifies the vault ARN after which
-- the listing of vaults should begin.
lvMarker :: Lens' ListVaults (Maybe Text)
lvMarker = lens _lvMarker (\s a -> s { _lvMarker = a })
data ListVaultsResponse = ListVaultsResponse
{ _lvrMarker :: Maybe Text
, _lvrVaultList :: List "VaultList" DescribeVaultOutput
} deriving (Eq, Read, Show)
-- | 'ListVaultsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lvrMarker' @::@ 'Maybe' 'Text'
--
-- * 'lvrVaultList' @::@ ['DescribeVaultOutput']
--
listVaultsResponse :: ListVaultsResponse
listVaultsResponse = ListVaultsResponse
{ _lvrVaultList = mempty
, _lvrMarker = Nothing
}
-- | The vault ARN at which to continue pagination of the results. You use the
-- marker in another List Vaults request to obtain more vaults in the list.
lvrMarker :: Lens' ListVaultsResponse (Maybe Text)
lvrMarker = lens _lvrMarker (\s a -> s { _lvrMarker = a })
-- | List of vaults.
lvrVaultList :: Lens' ListVaultsResponse [DescribeVaultOutput]
lvrVaultList = lens _lvrVaultList (\s a -> s { _lvrVaultList = a }) . _List
instance ToPath ListVaults where
toPath ListVaults{..} = mconcat
[ "/"
, toText _lvAccountId
, "/vaults"
]
instance ToQuery ListVaults where
toQuery ListVaults{..} = mconcat
[ "marker" =? _lvMarker
, "limit" =? _lvLimit
]
instance ToHeaders ListVaults
instance ToJSON ListVaults where
toJSON = const (toJSON Empty)
instance AWSRequest ListVaults where
type Sv ListVaults = Glacier
type Rs ListVaults = ListVaultsResponse
request = get
response = jsonResponse
instance FromJSON ListVaultsResponse where
parseJSON = withObject "ListVaultsResponse" $ \o -> ListVaultsResponse
<$> o .:? "Marker"
<*> o .:? "VaultList" .!= mempty
|
romanb/amazonka
|
amazonka-glacier/gen/Network/AWS/Glacier/ListVaults.hs
|
mpl-2.0
| 6,329 | 0 | 12 | 1,325 | 711 | 433 | 278 | 76 | 1 |
{- | Pipelining is sending multiple requests over a socket and receiving the responses later in the same order (a' la HTTP pipelining). This is faster than sending one request, waiting for the response, then sending the next request, and so on. This implementation returns a /promise (future)/ response for each request that when invoked waits for the response if not already arrived. Multiple threads can send on the same pipeline (and get promises back); it will send each thread's request right away without waiting.
A pipeline closes itself when a read or write causes an error, so you can detect a broken pipeline by checking isClosed. It also closes itself when garbage collected, or you can close it explicitly. -}
{-# LANGUAGE DoRec, RecordWildCards, NamedFieldPuns, ScopedTypeVariables #-}
module System.IO.Pipeline (
IOE,
-- * IOStream
IOStream(..),
-- * Pipeline
Pipeline, newPipeline, send, call, close, isClosed
) where
import Prelude hiding (length)
import GHC.Conc (ThreadStatus(..), threadStatus)
import Control.Concurrent (ThreadId, forkIO, killThread)
import Control.Concurrent.Chan
import Control.Monad.MVar
import Control.Monad.Error
onException :: (Monad m) => ErrorT e m a -> m () -> ErrorT e m a
-- ^ If first action throws an exception then run second action then re-throw
onException (ErrorT action) releaser = ErrorT $ do
e <- action
either (const releaser) (const $ return ()) e
return e
type IOE = ErrorT IOError IO
-- ^ IO monad with explicit error
-- * IOStream
-- | An IO sink and source where value of type @o@ are sent and values of type @i@ are received.
data IOStream i o = IOStream {
writeStream :: o -> IOE (),
readStream :: IOE i,
closeStream :: IO () }
-- * Pipeline
-- | Thread-safe and pipelined connection
data Pipeline i o = Pipeline {
vStream :: MVar (IOStream i o), -- ^ Mutex on handle, so only one thread at a time can write to it
responseQueue :: Chan (MVar (Either IOError i)), -- ^ Queue of threads waiting for responses. Every time a response arrive we pop the next thread and give it the response.
listenThread :: ThreadId
}
-- | Create new Pipeline over given handle. You should 'close' pipeline when finished, which will also close handle. If pipeline is not closed but eventually garbage collected, it will be closed along with handle.
newPipeline :: IOStream i o -> IO (Pipeline i o)
newPipeline stream = do
vStream <- newMVar stream
responseQueue <- newChan
rec
let pipe = Pipeline{..}
listenThread <- forkIO (listen pipe)
addMVarFinalizer vStream $ do
killThread listenThread
closeStream stream
return pipe
close :: Pipeline i o -> IO ()
-- ^ Close pipe and underlying connection
close Pipeline{..} = do
killThread listenThread
closeStream =<< readMVar vStream
isClosed :: Pipeline i o -> IO Bool
isClosed Pipeline{listenThread} = do
status <- threadStatus listenThread
return $ case status of
ThreadRunning -> False
ThreadFinished -> True
ThreadBlocked _ -> False
ThreadDied -> True
--isPipeClosed Pipeline{..} = isClosed =<< readMVar vHandle -- isClosed hangs while listen loop is waiting on read
listen :: Pipeline i o -> IO ()
-- ^ Listen for responses and supply them to waiting threads in order
listen Pipeline{..} = do
stream <- readMVar vStream
forever $ do
e <- runErrorT $ readStream stream
var <- readChan responseQueue
putMVar var e
case e of
Left err -> closeStream stream >> ioError err -- close and stop looping
Right _ -> return ()
send :: Pipeline i o -> o -> IOE ()
-- ^ Send message to destination; the destination must not response (otherwise future 'call's will get these responses instead of their own).
-- Throw IOError and close pipeline if send fails
send p@Pipeline{..} message = withMVar vStream (flip writeStream message) `onException` close p
call :: Pipeline i o -> o -> IOE (IOE i)
-- ^ Send message to destination and return /promise/ of response from one message only. The destination must reply to the message (otherwise promises will have the wrong responses in them).
-- Throw IOError and closes pipeline if send fails, likewise for promised response.
call p@Pipeline{..} message = withMVar vStream doCall `onException` close p where
doCall stream = do
writeStream stream message
var <- newEmptyMVar
liftIO $ writeChan responseQueue var
return $ ErrorT (readMVar var) -- return promise
{- Authors: Tony Hannan <[email protected]>
Copyright 2011 10gen Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -}
|
mongodb/mongoDB-haskell
|
System/IO/Pipeline.hs
|
apache-2.0
| 4,966 | 20 | 14 | 893 | 894 | 454 | 440 | 67 | 4 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PolyKinds #-}
module Data.Container.Opts where
import Prelude
import Type.Bool
import Data.Typeable
import Data.Container.Utils
------------------
-- === Opts === --
------------------
type family ParamsOf op cont :: [*]
type family ModsOf op cont :: [*]
data Opt a = P a -- Provided
| N -- Not provided
deriving (Show)
-- Knowledge
data Knowledge a = Known a
| Unknown
deriving (Show)
-- Mods
data Ixed = Ixed
-- Parameters
data Safe = Safe
data Unchecked = Unchecked
data Unsafe = Unsafe
data Inplace = Inplace
-- Formatters
data Try = Try
data Raw = Raw
-------------------------
type family MatchOpts (provided :: [*]) (selected :: [*]) :: [Opt *] where
MatchOpts (p ': ps) sel = (p `CheckIfKnown` sel) ': MatchOpts ps sel
MatchOpts '[] sel = '[]
type family CheckIfKnown flag flags :: Opt * where
CheckIfKnown f (f ': fs) = P f
CheckIfKnown f (f' ': fs) = CheckIfKnown f fs
CheckIfKnown f '[] = N
-------------------------
-- === Opt queries === --
-------------------------
data Query (mods :: [*]) (params :: [*]) = Query
data OptQuery (mods :: [Opt *]) (params :: [Opt *]) = OptQuery
-----------------------
-- === Opt utils === --
-----------------------
class CondOpt (opt :: Opt *) where ifOpt :: Proxy opt -> a -> a -> a
instance CondOpt (P a) where ifOpt _ = const ; {-# INLINE ifOpt #-}
instance CondOpt N where ifOpt _ = flip const ; {-# INLINE ifOpt #-}
------------------------
-- === OptBuilder === --
------------------------
newtype OptBuilder (mods :: [*]) (params :: [*]) a = OptBuilder a deriving (Show, Functor)
type OptBuilderBase = OptBuilder '[] '[]
class FuncTrans mods params f a | a mods params -> f where transFunc :: OptBuilder mods params f -> a
instance (mods ~ mods', params ~ params', f ~ f') => FuncTrans mods params f (OptBuilder mods' params' f') where transFunc = id
instance (f ~ (Query mods params -> a -> b)) => FuncTrans mods params f (a -> b) where transFunc (OptBuilder f) = f Query
class FuncBuilder f a | a -> f where buildFunc :: f -> a
instance {-# OVERLAPPABLE #-} (f ~ a, g ~ b) => FuncBuilder (f -> g) (a -> b) where buildFunc = id
instance {-# OVERLAPPABLE #-} (t ~ (f -> g), mods ~ '[], params ~ '[]) => FuncBuilder (f -> g) (OptBuilder mods params t) where buildFunc = OptBuilder
-- utils
optBuilder :: f -> OptBuilderBase f
optBuilder = OptBuilder
{-# INLINE optBuilder #-}
queryBuilder :: FuncTrans '[] '[] f a => f -> a
queryBuilder = transFunc . optBuilder
{-# INLINE queryBuilder #-}
extendOptBuilder :: Query newMods newParams
-> Query collectedMods collectedParams
-> OptBuilder mods params a
-> OptBuilder (Concat newMods (Concat collectedMods mods ))
(Concat newParams (Concat collectedParams params))
a
extendOptBuilder _ _ (OptBuilder a) = OptBuilder a
{-# INLINE extendOptBuilder #-}
appFunc :: (f -> g) -> OptBuilder ms ps f -> OptBuilder ms ps g
appFunc = fmap
{-# INLINE appFunc #-}
withTransFunc f = transFunc . appFunc f
{-# INLINE withTransFunc #-}
--------------------------------
type Concat lst lst' = Concat' (Reverse lst) lst'
type family Concat' lst lst' where
Concat' (x ': xs) lst = Concat' xs (x ': lst)
Concat' '[] lst = lst
type Reverse lst = Reverse' lst '[]
type family Reverse' (lst :: [*]) (lst' :: [*]) where
Reverse' '[] lst = lst
Reverse' (l ': ls) lst = Reverse' ls (l ': lst)
----------------------------------
type family OptData provided datas opt where
OptData (o ': ps) (d,ds) o = d
OptData (p ': ps) (d,ds) o = OptData ps ds o
type family QueryData provided query datas where
QueryData p (q ': qs) d = (OptData p d q, QueryData p qs d)
QueryData p '[] d = ()
class GetOptData (provided :: [*]) datas opt where getOptData :: Proxy provided -> datas -> Proxy opt -> OptData provided datas opt
instance {-# OVERLAPPABLE #-} ( datas ~ (a,as)
, GetOptData ps as o
, OptData ps as o ~ OptData (p ': ps) (a, as) o
) => GetOptData (p ': ps) datas o where getOptData _ (a,as) o = getOptData (Proxy :: Proxy ps) as o ; {-# INLINE getOptData #-}
instance {-# OVERLAPPABLE #-} datas ~ (a,as) => GetOptData (p ': ps) datas p where getOptData _ (a,as) _ = a ; {-# INLINE getOptData #-}
class GetQueryData (provided :: [*]) (query :: [*]) datas where getQueryData :: Proxy provided -> Proxy query -> datas -> QueryData provided query datas
instance {-# OVERLAPPABLE #-} (GetQueryData p qs datas, GetOptData p datas q)
=> GetQueryData p (q ': qs) datas where getQueryData p q datas = (getOptData p datas (Proxy :: Proxy q), getQueryData p (Proxy :: Proxy qs) datas) ; {-# INLINE getQueryData #-}
instance {-# OVERLAPPABLE #-} GetQueryData p '[] datas where getQueryData _ _ _ = () ; {-# INLINE getQueryData #-}
ixed = queryBuilder $ transFunc .: extendOptBuilder (Query :: Query '[ Ixed ] '[] ) ; {-# INLINE ixed #-}
raw = queryBuilder $ transFunc .: extendOptBuilder (Query :: Query '[] '[ Raw ]) ; {-# INLINE raw #-}
try = queryBuilder $ transFunc .: extendOptBuilder (Query :: Query '[] '[ Try ]) ; {-# INLINE try #-}
unchecked = queryBuilder $ transFunc .: extendOptBuilder (Query :: Query '[] '[ Unchecked ]) ; {-# INLINE unchecked #-}
unsafe = queryBuilder $ transFunc .: extendOptBuilder (Query :: Query '[] '[ Unsafe ]) ; {-# INLINE unsafe #-}
inplace = queryBuilder $ transFunc .: extendOptBuilder (Query :: Query '[] '[ Inplace ]) ; {-# INLINE inplace #-}
|
wdanilo/container
|
src/Data/Container/Opts.hs
|
apache-2.0
| 6,535 | 0 | 12 | 2,012 | 2,009 | 1,116 | 893 | -1 | -1 |
import Data.List (elemIndex)
import Data.Maybe (fromJust)
collatz :: Integer -> [Integer]
collatz n = if n == 1
then [n]
else if even n
then [n] ++ collatz (quot n 2)
else [n] ++ collatz (3*n+1)
findMaximum :: [Int] -> Int
findMaximum lst = let theMax = maximum lst
in fromJust (elemIndex theMax lst)
main = do
let numbers = [1..1000000]
let collatzLengths = map (length . collatz) numbers
let maximumInput = 1 + findMaximum collatzLengths -- +1: We start with 1
print maximumInput
|
ulikoehler/ProjectEuler
|
Euler14.hs
|
apache-2.0
| 589 | 0 | 12 | 191 | 214 | 110 | 104 | 16 | 3 |
import Data.List (nub, subsequences, map)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map, fromSet, (!))
type State = Set Int
type Flips = Set Int
type GraphState = Set State
type M = Map State State -- Map that sends states to their canonical representation
-- Maybe use compositions instead of subsets to represent the different states? Then n is implicit.
canonicalStateMap :: Int -> Set State -> M
canonicalStateMap n = fromSet (canonicalState n)
allStates :: Int -> Set State
allStates n = Set.fromList $ Data.List.map Set.fromList $ subsequences [0..n-1]
startingState :: Map State State -> Set State -> Set State
startingState m = Data.Set.map (m !)
canonicalState :: Int -> State -> State
canonicalState n xs = minimum $ concatMap (\as -> [as, complement n as]) $ foldr prependShifted [xs] [1..n] where
prependShifted _ as@(a:_) = shiftSet n a : as
complement :: Int -> State -> State
complement n s = Set.fromList [0..n-1] \\ s
shiftSet :: Int -> State -> State
shiftSet n = Data.Set.map (\i -> (i + 1) `mod` n)
nextGraphState :: [Move] -> GraphState -> GraphState
nextGraphState moves currentState = foldr union Data.Set.empty allMoves where
allMoves = Data.List.map (`doMove` currentState) moves
-- Make canonical
doMove :: Move -> GraphState -> GraphState
doMove move = Data.Set.map (move -|-)
(-|-) :: Ord a => Set a -> Set a -> Set a
x -|- y = (x \\ y) `union` (y \\ x)
-- isPossible :: Int -> Bool
-- isPossible n = recurse [startingState] where
-- states = allStates n
-- stateMap = canonicalStateMap n states
-- startingState = startingState stateMap states
-- recurse graphStates = where
-- nextState =
-- nextGraphState :: Map State State -> Set State -> GraphState -> GraphState
-- nextGraphState canonicalLookup everyState graphState = foldr () Set.empty graphState
|
peterokagey/haskellOEIS
|
src/Sandbox/OpenishProblems/Problem79.hs
|
apache-2.0
| 1,844 | 0 | 11 | 331 | 566 | 310 | 256 | 28 | 1 |
module Calculus.Opra10
( module Calculus.Opra
, Opra10(..)
) where
-- standard modules
-- local modules
import Basics
import Calculus.Opra
data Opra10 = Opra10_0_0 | Opra10_0_1 | Opra10_0_2 | Opra10_0_3
| Opra10_0_4 | Opra10_0_5 | Opra10_0_6 | Opra10_0_7
| Opra10_0_8 | Opra10_0_9 | Opra10_0_10 | Opra10_0_11
| Opra10_0_12 | Opra10_0_13 | Opra10_0_14 | Opra10_0_15
| Opra10_0_16 | Opra10_0_17 | Opra10_0_18 | Opra10_0_19
| Opra10_0_20 | Opra10_0_21 | Opra10_0_22 | Opra10_0_23
| Opra10_0_24 | Opra10_0_25 | Opra10_0_26 | Opra10_0_27
| Opra10_0_28 | Opra10_0_29 | Opra10_0_30 | Opra10_0_31
| Opra10_0_32 | Opra10_0_33 | Opra10_0_34 | Opra10_0_35
| Opra10_0_36 | Opra10_0_37 | Opra10_0_38 | Opra10_0_39
| Opra10_1_0 | Opra10_1_1 | Opra10_1_2 | Opra10_1_3
| Opra10_1_4 | Opra10_1_5 | Opra10_1_6 | Opra10_1_7
| Opra10_1_8 | Opra10_1_9 | Opra10_1_10 | Opra10_1_11
| Opra10_1_12 | Opra10_1_13 | Opra10_1_14 | Opra10_1_15
| Opra10_1_16 | Opra10_1_17 | Opra10_1_18 | Opra10_1_19
| Opra10_1_20 | Opra10_1_21 | Opra10_1_22 | Opra10_1_23
| Opra10_1_24 | Opra10_1_25 | Opra10_1_26 | Opra10_1_27
| Opra10_1_28 | Opra10_1_29 | Opra10_1_30 | Opra10_1_31
| Opra10_1_32 | Opra10_1_33 | Opra10_1_34 | Opra10_1_35
| Opra10_1_36 | Opra10_1_37 | Opra10_1_38 | Opra10_1_39
| Opra10_2_0 | Opra10_2_1 | Opra10_2_2 | Opra10_2_3
| Opra10_2_4 | Opra10_2_5 | Opra10_2_6 | Opra10_2_7
| Opra10_2_8 | Opra10_2_9 | Opra10_2_10 | Opra10_2_11
| Opra10_2_12 | Opra10_2_13 | Opra10_2_14 | Opra10_2_15
| Opra10_2_16 | Opra10_2_17 | Opra10_2_18 | Opra10_2_19
| Opra10_2_20 | Opra10_2_21 | Opra10_2_22 | Opra10_2_23
| Opra10_2_24 | Opra10_2_25 | Opra10_2_26 | Opra10_2_27
| Opra10_2_28 | Opra10_2_29 | Opra10_2_30 | Opra10_2_31
| Opra10_2_32 | Opra10_2_33 | Opra10_2_34 | Opra10_2_35
| Opra10_2_36 | Opra10_2_37 | Opra10_2_38 | Opra10_2_39
| Opra10_3_0 | Opra10_3_1 | Opra10_3_2 | Opra10_3_3
| Opra10_3_4 | Opra10_3_5 | Opra10_3_6 | Opra10_3_7
| Opra10_3_8 | Opra10_3_9 | Opra10_3_10 | Opra10_3_11
| Opra10_3_12 | Opra10_3_13 | Opra10_3_14 | Opra10_3_15
| Opra10_3_16 | Opra10_3_17 | Opra10_3_18 | Opra10_3_19
| Opra10_3_20 | Opra10_3_21 | Opra10_3_22 | Opra10_3_23
| Opra10_3_24 | Opra10_3_25 | Opra10_3_26 | Opra10_3_27
| Opra10_3_28 | Opra10_3_29 | Opra10_3_30 | Opra10_3_31
| Opra10_3_32 | Opra10_3_33 | Opra10_3_34 | Opra10_3_35
| Opra10_3_36 | Opra10_3_37 | Opra10_3_38 | Opra10_3_39
| Opra10_4_0 | Opra10_4_1 | Opra10_4_2 | Opra10_4_3
| Opra10_4_4 | Opra10_4_5 | Opra10_4_6 | Opra10_4_7
| Opra10_4_8 | Opra10_4_9 | Opra10_4_10 | Opra10_4_11
| Opra10_4_12 | Opra10_4_13 | Opra10_4_14 | Opra10_4_15
| Opra10_4_16 | Opra10_4_17 | Opra10_4_18 | Opra10_4_19
| Opra10_4_20 | Opra10_4_21 | Opra10_4_22 | Opra10_4_23
| Opra10_4_24 | Opra10_4_25 | Opra10_4_26 | Opra10_4_27
| Opra10_4_28 | Opra10_4_29 | Opra10_4_30 | Opra10_4_31
| Opra10_4_32 | Opra10_4_33 | Opra10_4_34 | Opra10_4_35
| Opra10_4_36 | Opra10_4_37 | Opra10_4_38 | Opra10_4_39
| Opra10_5_0 | Opra10_5_1 | Opra10_5_2 | Opra10_5_3
| Opra10_5_4 | Opra10_5_5 | Opra10_5_6 | Opra10_5_7
| Opra10_5_8 | Opra10_5_9 | Opra10_5_10 | Opra10_5_11
| Opra10_5_12 | Opra10_5_13 | Opra10_5_14 | Opra10_5_15
| Opra10_5_16 | Opra10_5_17 | Opra10_5_18 | Opra10_5_19
| Opra10_5_20 | Opra10_5_21 | Opra10_5_22 | Opra10_5_23
| Opra10_5_24 | Opra10_5_25 | Opra10_5_26 | Opra10_5_27
| Opra10_5_28 | Opra10_5_29 | Opra10_5_30 | Opra10_5_31
| Opra10_5_32 | Opra10_5_33 | Opra10_5_34 | Opra10_5_35
| Opra10_5_36 | Opra10_5_37 | Opra10_5_38 | Opra10_5_39
| Opra10_6_0 | Opra10_6_1 | Opra10_6_2 | Opra10_6_3
| Opra10_6_4 | Opra10_6_5 | Opra10_6_6 | Opra10_6_7
| Opra10_6_8 | Opra10_6_9 | Opra10_6_10 | Opra10_6_11
| Opra10_6_12 | Opra10_6_13 | Opra10_6_14 | Opra10_6_15
| Opra10_6_16 | Opra10_6_17 | Opra10_6_18 | Opra10_6_19
| Opra10_6_20 | Opra10_6_21 | Opra10_6_22 | Opra10_6_23
| Opra10_6_24 | Opra10_6_25 | Opra10_6_26 | Opra10_6_27
| Opra10_6_28 | Opra10_6_29 | Opra10_6_30 | Opra10_6_31
| Opra10_6_32 | Opra10_6_33 | Opra10_6_34 | Opra10_6_35
| Opra10_6_36 | Opra10_6_37 | Opra10_6_38 | Opra10_6_39
| Opra10_7_0 | Opra10_7_1 | Opra10_7_2 | Opra10_7_3
| Opra10_7_4 | Opra10_7_5 | Opra10_7_6 | Opra10_7_7
| Opra10_7_8 | Opra10_7_9 | Opra10_7_10 | Opra10_7_11
| Opra10_7_12 | Opra10_7_13 | Opra10_7_14 | Opra10_7_15
| Opra10_7_16 | Opra10_7_17 | Opra10_7_18 | Opra10_7_19
| Opra10_7_20 | Opra10_7_21 | Opra10_7_22 | Opra10_7_23
| Opra10_7_24 | Opra10_7_25 | Opra10_7_26 | Opra10_7_27
| Opra10_7_28 | Opra10_7_29 | Opra10_7_30 | Opra10_7_31
| Opra10_7_32 | Opra10_7_33 | Opra10_7_34 | Opra10_7_35
| Opra10_7_36 | Opra10_7_37 | Opra10_7_38 | Opra10_7_39
| Opra10_8_0 | Opra10_8_1 | Opra10_8_2 | Opra10_8_3
| Opra10_8_4 | Opra10_8_5 | Opra10_8_6 | Opra10_8_7
| Opra10_8_8 | Opra10_8_9 | Opra10_8_10 | Opra10_8_11
| Opra10_8_12 | Opra10_8_13 | Opra10_8_14 | Opra10_8_15
| Opra10_8_16 | Opra10_8_17 | Opra10_8_18 | Opra10_8_19
| Opra10_8_20 | Opra10_8_21 | Opra10_8_22 | Opra10_8_23
| Opra10_8_24 | Opra10_8_25 | Opra10_8_26 | Opra10_8_27
| Opra10_8_28 | Opra10_8_29 | Opra10_8_30 | Opra10_8_31
| Opra10_8_32 | Opra10_8_33 | Opra10_8_34 | Opra10_8_35
| Opra10_8_36 | Opra10_8_37 | Opra10_8_38 | Opra10_8_39
| Opra10_9_0 | Opra10_9_1 | Opra10_9_2 | Opra10_9_3
| Opra10_9_4 | Opra10_9_5 | Opra10_9_6 | Opra10_9_7
| Opra10_9_8 | Opra10_9_9 | Opra10_9_10 | Opra10_9_11
| Opra10_9_12 | Opra10_9_13 | Opra10_9_14 | Opra10_9_15
| Opra10_9_16 | Opra10_9_17 | Opra10_9_18 | Opra10_9_19
| Opra10_9_20 | Opra10_9_21 | Opra10_9_22 | Opra10_9_23
| Opra10_9_24 | Opra10_9_25 | Opra10_9_26 | Opra10_9_27
| Opra10_9_28 | Opra10_9_29 | Opra10_9_30 | Opra10_9_31
| Opra10_9_32 | Opra10_9_33 | Opra10_9_34 | Opra10_9_35
| Opra10_9_36 | Opra10_9_37 | Opra10_9_38 | Opra10_9_39
| Opra10_10_00 | Opra10_10_01 | Opra10_10_02 | Opra10_10_03
| Opra10_10_04 | Opra10_10_05 | Opra10_10_06 | Opra10_10_07
| Opra10_10_08 | Opra10_10_09 | Opra10_10_10 | Opra10_10_11
| Opra10_10_12 | Opra10_10_13 | Opra10_10_14 | Opra10_10_15
| Opra10_10_16 | Opra10_10_17 | Opra10_10_18 | Opra10_10_19
| Opra10_10_20 | Opra10_10_21 | Opra10_10_22 | Opra10_10_23
| Opra10_10_24 | Opra10_10_25 | Opra10_10_26 | Opra10_10_27
| Opra10_10_28 | Opra10_10_29 | Opra10_10_30 | Opra10_10_31
| Opra10_10_32 | Opra10_10_33 | Opra10_10_34 | Opra10_10_35
| Opra10_10_36 | Opra10_10_37 | Opra10_10_38 | Opra10_10_39
| Opra10_11_00 | Opra10_11_01 | Opra10_11_02 | Opra10_11_03
| Opra10_11_04 | Opra10_11_05 | Opra10_11_06 | Opra10_11_07
| Opra10_11_08 | Opra10_11_09 | Opra10_11_10 | Opra10_11_11
| Opra10_11_12 | Opra10_11_13 | Opra10_11_14 | Opra10_11_15
| Opra10_11_16 | Opra10_11_17 | Opra10_11_18 | Opra10_11_19
| Opra10_11_20 | Opra10_11_21 | Opra10_11_22 | Opra10_11_23
| Opra10_11_24 | Opra10_11_25 | Opra10_11_26 | Opra10_11_27
| Opra10_11_28 | Opra10_11_29 | Opra10_11_30 | Opra10_11_31
| Opra10_11_32 | Opra10_11_33 | Opra10_11_34 | Opra10_11_35
| Opra10_11_36 | Opra10_11_37 | Opra10_11_38 | Opra10_11_39
| Opra10_12_00 | Opra10_12_01 | Opra10_12_02 | Opra10_12_03
| Opra10_12_04 | Opra10_12_05 | Opra10_12_06 | Opra10_12_07
| Opra10_12_08 | Opra10_12_09 | Opra10_12_10 | Opra10_12_11
| Opra10_12_12 | Opra10_12_13 | Opra10_12_14 | Opra10_12_15
| Opra10_12_16 | Opra10_12_17 | Opra10_12_18 | Opra10_12_19
| Opra10_12_20 | Opra10_12_21 | Opra10_12_22 | Opra10_12_23
| Opra10_12_24 | Opra10_12_25 | Opra10_12_26 | Opra10_12_27
| Opra10_12_28 | Opra10_12_29 | Opra10_12_30 | Opra10_12_31
| Opra10_12_32 | Opra10_12_33 | Opra10_12_34 | Opra10_12_35
| Opra10_12_36 | Opra10_12_37 | Opra10_12_38 | Opra10_12_39
| Opra10_13_00 | Opra10_13_01 | Opra10_13_02 | Opra10_13_03
| Opra10_13_04 | Opra10_13_05 | Opra10_13_06 | Opra10_13_07
| Opra10_13_08 | Opra10_13_09 | Opra10_13_10 | Opra10_13_11
| Opra10_13_12 | Opra10_13_13 | Opra10_13_14 | Opra10_13_15
| Opra10_13_16 | Opra10_13_17 | Opra10_13_18 | Opra10_13_19
| Opra10_13_20 | Opra10_13_21 | Opra10_13_22 | Opra10_13_23
| Opra10_13_24 | Opra10_13_25 | Opra10_13_26 | Opra10_13_27
| Opra10_13_28 | Opra10_13_29 | Opra10_13_30 | Opra10_13_31
| Opra10_13_32 | Opra10_13_33 | Opra10_13_34 | Opra10_13_35
| Opra10_13_36 | Opra10_13_37 | Opra10_13_38 | Opra10_13_39
| Opra10_14_00 | Opra10_14_01 | Opra10_14_02 | Opra10_14_03
| Opra10_14_04 | Opra10_14_05 | Opra10_14_06 | Opra10_14_07
| Opra10_14_08 | Opra10_14_09 | Opra10_14_10 | Opra10_14_11
| Opra10_14_12 | Opra10_14_13 | Opra10_14_14 | Opra10_14_15
| Opra10_14_16 | Opra10_14_17 | Opra10_14_18 | Opra10_14_19
| Opra10_14_20 | Opra10_14_21 | Opra10_14_22 | Opra10_14_23
| Opra10_14_24 | Opra10_14_25 | Opra10_14_26 | Opra10_14_27
| Opra10_14_28 | Opra10_14_29 | Opra10_14_30 | Opra10_14_31
| Opra10_14_32 | Opra10_14_33 | Opra10_14_34 | Opra10_14_35
| Opra10_14_36 | Opra10_14_37 | Opra10_14_38 | Opra10_14_39
| Opra10_15_00 | Opra10_15_01 | Opra10_15_02 | Opra10_15_03
| Opra10_15_04 | Opra10_15_05 | Opra10_15_06 | Opra10_15_07
| Opra10_15_08 | Opra10_15_09 | Opra10_15_10 | Opra10_15_11
| Opra10_15_12 | Opra10_15_13 | Opra10_15_14 | Opra10_15_15
| Opra10_15_16 | Opra10_15_17 | Opra10_15_18 | Opra10_15_19
| Opra10_15_20 | Opra10_15_21 | Opra10_15_22 | Opra10_15_23
| Opra10_15_24 | Opra10_15_25 | Opra10_15_26 | Opra10_15_27
| Opra10_15_28 | Opra10_15_29 | Opra10_15_30 | Opra10_15_31
| Opra10_15_32 | Opra10_15_33 | Opra10_15_34 | Opra10_15_35
| Opra10_15_36 | Opra10_15_37 | Opra10_15_38 | Opra10_15_39
| Opra10_16_00 | Opra10_16_01 | Opra10_16_02 | Opra10_16_03
| Opra10_16_04 | Opra10_16_05 | Opra10_16_06 | Opra10_16_07
| Opra10_16_08 | Opra10_16_09 | Opra10_16_10 | Opra10_16_11
| Opra10_16_12 | Opra10_16_13 | Opra10_16_14 | Opra10_16_15
| Opra10_16_16 | Opra10_16_17 | Opra10_16_18 | Opra10_16_19
| Opra10_16_20 | Opra10_16_21 | Opra10_16_22 | Opra10_16_23
| Opra10_16_24 | Opra10_16_25 | Opra10_16_26 | Opra10_16_27
| Opra10_16_28 | Opra10_16_29 | Opra10_16_30 | Opra10_16_31
| Opra10_16_32 | Opra10_16_33 | Opra10_16_34 | Opra10_16_35
| Opra10_16_36 | Opra10_16_37 | Opra10_16_38 | Opra10_16_39
| Opra10_17_00 | Opra10_17_01 | Opra10_17_02 | Opra10_17_03
| Opra10_17_04 | Opra10_17_05 | Opra10_17_06 | Opra10_17_07
| Opra10_17_08 | Opra10_17_09 | Opra10_17_10 | Opra10_17_11
| Opra10_17_12 | Opra10_17_13 | Opra10_17_14 | Opra10_17_15
| Opra10_17_16 | Opra10_17_17 | Opra10_17_18 | Opra10_17_19
| Opra10_17_20 | Opra10_17_21 | Opra10_17_22 | Opra10_17_23
| Opra10_17_24 | Opra10_17_25 | Opra10_17_26 | Opra10_17_27
| Opra10_17_28 | Opra10_17_29 | Opra10_17_30 | Opra10_17_31
| Opra10_17_32 | Opra10_17_33 | Opra10_17_34 | Opra10_17_35
| Opra10_17_36 | Opra10_17_37 | Opra10_17_38 | Opra10_17_39
| Opra10_18_00 | Opra10_18_01 | Opra10_18_02 | Opra10_18_03
| Opra10_18_04 | Opra10_18_05 | Opra10_18_06 | Opra10_18_07
| Opra10_18_08 | Opra10_18_09 | Opra10_18_10 | Opra10_18_11
| Opra10_18_12 | Opra10_18_13 | Opra10_18_14 | Opra10_18_15
| Opra10_18_16 | Opra10_18_17 | Opra10_18_18 | Opra10_18_19
| Opra10_18_20 | Opra10_18_21 | Opra10_18_22 | Opra10_18_23
| Opra10_18_24 | Opra10_18_25 | Opra10_18_26 | Opra10_18_27
| Opra10_18_28 | Opra10_18_29 | Opra10_18_30 | Opra10_18_31
| Opra10_18_32 | Opra10_18_33 | Opra10_18_34 | Opra10_18_35
| Opra10_18_36 | Opra10_18_37 | Opra10_18_38 | Opra10_18_39
| Opra10_19_00 | Opra10_19_01 | Opra10_19_02 | Opra10_19_03
| Opra10_19_04 | Opra10_19_05 | Opra10_19_06 | Opra10_19_07
| Opra10_19_08 | Opra10_19_09 | Opra10_19_10 | Opra10_19_11
| Opra10_19_12 | Opra10_19_13 | Opra10_19_14 | Opra10_19_15
| Opra10_19_16 | Opra10_19_17 | Opra10_19_18 | Opra10_19_19
| Opra10_19_20 | Opra10_19_21 | Opra10_19_22 | Opra10_19_23
| Opra10_19_24 | Opra10_19_25 | Opra10_19_26 | Opra10_19_27
| Opra10_19_28 | Opra10_19_29 | Opra10_19_30 | Opra10_19_31
| Opra10_19_32 | Opra10_19_33 | Opra10_19_34 | Opra10_19_35
| Opra10_19_36 | Opra10_19_37 | Opra10_19_38 | Opra10_19_39
| Opra10_20_00 | Opra10_20_01 | Opra10_20_02 | Opra10_20_03
| Opra10_20_04 | Opra10_20_05 | Opra10_20_06 | Opra10_20_07
| Opra10_20_08 | Opra10_20_09 | Opra10_20_10 | Opra10_20_11
| Opra10_20_12 | Opra10_20_13 | Opra10_20_14 | Opra10_20_15
| Opra10_20_16 | Opra10_20_17 | Opra10_20_18 | Opra10_20_19
| Opra10_20_20 | Opra10_20_21 | Opra10_20_22 | Opra10_20_23
| Opra10_20_24 | Opra10_20_25 | Opra10_20_26 | Opra10_20_27
| Opra10_20_28 | Opra10_20_29 | Opra10_20_30 | Opra10_20_31
| Opra10_20_32 | Opra10_20_33 | Opra10_20_34 | Opra10_20_35
| Opra10_20_36 | Opra10_20_37 | Opra10_20_38 | Opra10_20_39
| Opra10_21_00 | Opra10_21_01 | Opra10_21_02 | Opra10_21_03
| Opra10_21_04 | Opra10_21_05 | Opra10_21_06 | Opra10_21_07
| Opra10_21_08 | Opra10_21_09 | Opra10_21_10 | Opra10_21_11
| Opra10_21_12 | Opra10_21_13 | Opra10_21_14 | Opra10_21_15
| Opra10_21_16 | Opra10_21_17 | Opra10_21_18 | Opra10_21_19
| Opra10_21_20 | Opra10_21_21 | Opra10_21_22 | Opra10_21_23
| Opra10_21_24 | Opra10_21_25 | Opra10_21_26 | Opra10_21_27
| Opra10_21_28 | Opra10_21_29 | Opra10_21_30 | Opra10_21_31
| Opra10_21_32 | Opra10_21_33 | Opra10_21_34 | Opra10_21_35
| Opra10_21_36 | Opra10_21_37 | Opra10_21_38 | Opra10_21_39
| Opra10_22_00 | Opra10_22_01 | Opra10_22_02 | Opra10_22_03
| Opra10_22_04 | Opra10_22_05 | Opra10_22_06 | Opra10_22_07
| Opra10_22_08 | Opra10_22_09 | Opra10_22_10 | Opra10_22_11
| Opra10_22_12 | Opra10_22_13 | Opra10_22_14 | Opra10_22_15
| Opra10_22_16 | Opra10_22_17 | Opra10_22_18 | Opra10_22_19
| Opra10_22_20 | Opra10_22_21 | Opra10_22_22 | Opra10_22_23
| Opra10_22_24 | Opra10_22_25 | Opra10_22_26 | Opra10_22_27
| Opra10_22_28 | Opra10_22_29 | Opra10_22_30 | Opra10_22_31
| Opra10_22_32 | Opra10_22_33 | Opra10_22_34 | Opra10_22_35
| Opra10_22_36 | Opra10_22_37 | Opra10_22_38 | Opra10_22_39
| Opra10_23_00 | Opra10_23_01 | Opra10_23_02 | Opra10_23_03
| Opra10_23_04 | Opra10_23_05 | Opra10_23_06 | Opra10_23_07
| Opra10_23_08 | Opra10_23_09 | Opra10_23_10 | Opra10_23_11
| Opra10_23_12 | Opra10_23_13 | Opra10_23_14 | Opra10_23_15
| Opra10_23_16 | Opra10_23_17 | Opra10_23_18 | Opra10_23_19
| Opra10_23_20 | Opra10_23_21 | Opra10_23_22 | Opra10_23_23
| Opra10_23_24 | Opra10_23_25 | Opra10_23_26 | Opra10_23_27
| Opra10_23_28 | Opra10_23_29 | Opra10_23_30 | Opra10_23_31
| Opra10_23_32 | Opra10_23_33 | Opra10_23_34 | Opra10_23_35
| Opra10_23_36 | Opra10_23_37 | Opra10_23_38 | Opra10_23_39
| Opra10_24_00 | Opra10_24_01 | Opra10_24_02 | Opra10_24_03
| Opra10_24_04 | Opra10_24_05 | Opra10_24_06 | Opra10_24_07
| Opra10_24_08 | Opra10_24_09 | Opra10_24_10 | Opra10_24_11
| Opra10_24_12 | Opra10_24_13 | Opra10_24_14 | Opra10_24_15
| Opra10_24_16 | Opra10_24_17 | Opra10_24_18 | Opra10_24_19
| Opra10_24_20 | Opra10_24_21 | Opra10_24_22 | Opra10_24_23
| Opra10_24_24 | Opra10_24_25 | Opra10_24_26 | Opra10_24_27
| Opra10_24_28 | Opra10_24_29 | Opra10_24_30 | Opra10_24_31
| Opra10_24_32 | Opra10_24_33 | Opra10_24_34 | Opra10_24_35
| Opra10_24_36 | Opra10_24_37 | Opra10_24_38 | Opra10_24_39
| Opra10_25_00 | Opra10_25_01 | Opra10_25_02 | Opra10_25_03
| Opra10_25_04 | Opra10_25_05 | Opra10_25_06 | Opra10_25_07
| Opra10_25_08 | Opra10_25_09 | Opra10_25_10 | Opra10_25_11
| Opra10_25_12 | Opra10_25_13 | Opra10_25_14 | Opra10_25_15
| Opra10_25_16 | Opra10_25_17 | Opra10_25_18 | Opra10_25_19
| Opra10_25_20 | Opra10_25_21 | Opra10_25_22 | Opra10_25_23
| Opra10_25_24 | Opra10_25_25 | Opra10_25_26 | Opra10_25_27
| Opra10_25_28 | Opra10_25_29 | Opra10_25_30 | Opra10_25_31
| Opra10_25_32 | Opra10_25_33 | Opra10_25_34 | Opra10_25_35
| Opra10_25_36 | Opra10_25_37 | Opra10_25_38 | Opra10_25_39
| Opra10_26_00 | Opra10_26_01 | Opra10_26_02 | Opra10_26_03
| Opra10_26_04 | Opra10_26_05 | Opra10_26_06 | Opra10_26_07
| Opra10_26_08 | Opra10_26_09 | Opra10_26_10 | Opra10_26_11
| Opra10_26_12 | Opra10_26_13 | Opra10_26_14 | Opra10_26_15
| Opra10_26_16 | Opra10_26_17 | Opra10_26_18 | Opra10_26_19
| Opra10_26_20 | Opra10_26_21 | Opra10_26_22 | Opra10_26_23
| Opra10_26_24 | Opra10_26_25 | Opra10_26_26 | Opra10_26_27
| Opra10_26_28 | Opra10_26_29 | Opra10_26_30 | Opra10_26_31
| Opra10_26_32 | Opra10_26_33 | Opra10_26_34 | Opra10_26_35
| Opra10_26_36 | Opra10_26_37 | Opra10_26_38 | Opra10_26_39
| Opra10_27_00 | Opra10_27_01 | Opra10_27_02 | Opra10_27_03
| Opra10_27_04 | Opra10_27_05 | Opra10_27_06 | Opra10_27_07
| Opra10_27_08 | Opra10_27_09 | Opra10_27_10 | Opra10_27_11
| Opra10_27_12 | Opra10_27_13 | Opra10_27_14 | Opra10_27_15
| Opra10_27_16 | Opra10_27_17 | Opra10_27_18 | Opra10_27_19
| Opra10_27_20 | Opra10_27_21 | Opra10_27_22 | Opra10_27_23
| Opra10_27_24 | Opra10_27_25 | Opra10_27_26 | Opra10_27_27
| Opra10_27_28 | Opra10_27_29 | Opra10_27_30 | Opra10_27_31
| Opra10_27_32 | Opra10_27_33 | Opra10_27_34 | Opra10_27_35
| Opra10_27_36 | Opra10_27_37 | Opra10_27_38 | Opra10_27_39
| Opra10_28_00 | Opra10_28_01 | Opra10_28_02 | Opra10_28_03
| Opra10_28_04 | Opra10_28_05 | Opra10_28_06 | Opra10_28_07
| Opra10_28_08 | Opra10_28_09 | Opra10_28_10 | Opra10_28_11
| Opra10_28_12 | Opra10_28_13 | Opra10_28_14 | Opra10_28_15
| Opra10_28_16 | Opra10_28_17 | Opra10_28_18 | Opra10_28_19
| Opra10_28_20 | Opra10_28_21 | Opra10_28_22 | Opra10_28_23
| Opra10_28_24 | Opra10_28_25 | Opra10_28_26 | Opra10_28_27
| Opra10_28_28 | Opra10_28_29 | Opra10_28_30 | Opra10_28_31
| Opra10_28_32 | Opra10_28_33 | Opra10_28_34 | Opra10_28_35
| Opra10_28_36 | Opra10_28_37 | Opra10_28_38 | Opra10_28_39
| Opra10_29_00 | Opra10_29_01 | Opra10_29_02 | Opra10_29_03
| Opra10_29_04 | Opra10_29_05 | Opra10_29_06 | Opra10_29_07
| Opra10_29_08 | Opra10_29_09 | Opra10_29_10 | Opra10_29_11
| Opra10_29_12 | Opra10_29_13 | Opra10_29_14 | Opra10_29_15
| Opra10_29_16 | Opra10_29_17 | Opra10_29_18 | Opra10_29_19
| Opra10_29_20 | Opra10_29_21 | Opra10_29_22 | Opra10_29_23
| Opra10_29_24 | Opra10_29_25 | Opra10_29_26 | Opra10_29_27
| Opra10_29_28 | Opra10_29_29 | Opra10_29_30 | Opra10_29_31
| Opra10_29_32 | Opra10_29_33 | Opra10_29_34 | Opra10_29_35
| Opra10_29_36 | Opra10_29_37 | Opra10_29_38 | Opra10_29_39
| Opra10_30_00 | Opra10_30_01 | Opra10_30_02 | Opra10_30_03
| Opra10_30_04 | Opra10_30_05 | Opra10_30_06 | Opra10_30_07
| Opra10_30_08 | Opra10_30_09 | Opra10_30_10 | Opra10_30_11
| Opra10_30_12 | Opra10_30_13 | Opra10_30_14 | Opra10_30_15
| Opra10_30_16 | Opra10_30_17 | Opra10_30_18 | Opra10_30_19
| Opra10_30_20 | Opra10_30_21 | Opra10_30_22 | Opra10_30_23
| Opra10_30_24 | Opra10_30_25 | Opra10_30_26 | Opra10_30_27
| Opra10_30_28 | Opra10_30_29 | Opra10_30_30 | Opra10_30_31
| Opra10_30_32 | Opra10_30_33 | Opra10_30_34 | Opra10_30_35
| Opra10_30_36 | Opra10_30_37 | Opra10_30_38 | Opra10_30_39
| Opra10_31_00 | Opra10_31_01 | Opra10_31_02 | Opra10_31_03
| Opra10_31_04 | Opra10_31_05 | Opra10_31_06 | Opra10_31_07
| Opra10_31_08 | Opra10_31_09 | Opra10_31_10 | Opra10_31_11
| Opra10_31_12 | Opra10_31_13 | Opra10_31_14 | Opra10_31_15
| Opra10_31_16 | Opra10_31_17 | Opra10_31_18 | Opra10_31_19
| Opra10_31_20 | Opra10_31_21 | Opra10_31_22 | Opra10_31_23
| Opra10_31_24 | Opra10_31_25 | Opra10_31_26 | Opra10_31_27
| Opra10_31_28 | Opra10_31_29 | Opra10_31_30 | Opra10_31_31
| Opra10_31_32 | Opra10_31_33 | Opra10_31_34 | Opra10_31_35
| Opra10_31_36 | Opra10_31_37 | Opra10_31_38 | Opra10_31_39
| Opra10_32_00 | Opra10_32_01 | Opra10_32_02 | Opra10_32_03
| Opra10_32_04 | Opra10_32_05 | Opra10_32_06 | Opra10_32_07
| Opra10_32_08 | Opra10_32_09 | Opra10_32_10 | Opra10_32_11
| Opra10_32_12 | Opra10_32_13 | Opra10_32_14 | Opra10_32_15
| Opra10_32_16 | Opra10_32_17 | Opra10_32_18 | Opra10_32_19
| Opra10_32_20 | Opra10_32_21 | Opra10_32_22 | Opra10_32_23
| Opra10_32_24 | Opra10_32_25 | Opra10_32_26 | Opra10_32_27
| Opra10_32_28 | Opra10_32_29 | Opra10_32_30 | Opra10_32_31
| Opra10_32_32 | Opra10_32_33 | Opra10_32_34 | Opra10_32_35
| Opra10_32_36 | Opra10_32_37 | Opra10_32_38 | Opra10_32_39
| Opra10_33_00 | Opra10_33_01 | Opra10_33_02 | Opra10_33_03
| Opra10_33_04 | Opra10_33_05 | Opra10_33_06 | Opra10_33_07
| Opra10_33_08 | Opra10_33_09 | Opra10_33_10 | Opra10_33_11
| Opra10_33_12 | Opra10_33_13 | Opra10_33_14 | Opra10_33_15
| Opra10_33_16 | Opra10_33_17 | Opra10_33_18 | Opra10_33_19
| Opra10_33_20 | Opra10_33_21 | Opra10_33_22 | Opra10_33_23
| Opra10_33_24 | Opra10_33_25 | Opra10_33_26 | Opra10_33_27
| Opra10_33_28 | Opra10_33_29 | Opra10_33_30 | Opra10_33_31
| Opra10_33_32 | Opra10_33_33 | Opra10_33_34 | Opra10_33_35
| Opra10_33_36 | Opra10_33_37 | Opra10_33_38 | Opra10_33_39
| Opra10_34_00 | Opra10_34_01 | Opra10_34_02 | Opra10_34_03
| Opra10_34_04 | Opra10_34_05 | Opra10_34_06 | Opra10_34_07
| Opra10_34_08 | Opra10_34_09 | Opra10_34_10 | Opra10_34_11
| Opra10_34_12 | Opra10_34_13 | Opra10_34_14 | Opra10_34_15
| Opra10_34_16 | Opra10_34_17 | Opra10_34_18 | Opra10_34_19
| Opra10_34_20 | Opra10_34_21 | Opra10_34_22 | Opra10_34_23
| Opra10_34_24 | Opra10_34_25 | Opra10_34_26 | Opra10_34_27
| Opra10_34_28 | Opra10_34_29 | Opra10_34_30 | Opra10_34_31
| Opra10_34_32 | Opra10_34_33 | Opra10_34_34 | Opra10_34_35
| Opra10_34_36 | Opra10_34_37 | Opra10_34_38 | Opra10_34_39
| Opra10_35_00 | Opra10_35_01 | Opra10_35_02 | Opra10_35_03
| Opra10_35_04 | Opra10_35_05 | Opra10_35_06 | Opra10_35_07
| Opra10_35_08 | Opra10_35_09 | Opra10_35_10 | Opra10_35_11
| Opra10_35_12 | Opra10_35_13 | Opra10_35_14 | Opra10_35_15
| Opra10_35_16 | Opra10_35_17 | Opra10_35_18 | Opra10_35_19
| Opra10_35_20 | Opra10_35_21 | Opra10_35_22 | Opra10_35_23
| Opra10_35_24 | Opra10_35_25 | Opra10_35_26 | Opra10_35_27
| Opra10_35_28 | Opra10_35_29 | Opra10_35_30 | Opra10_35_31
| Opra10_35_32 | Opra10_35_33 | Opra10_35_34 | Opra10_35_35
| Opra10_35_36 | Opra10_35_37 | Opra10_35_38 | Opra10_35_39
| Opra10_36_00 | Opra10_36_01 | Opra10_36_02 | Opra10_36_03
| Opra10_36_04 | Opra10_36_05 | Opra10_36_06 | Opra10_36_07
| Opra10_36_08 | Opra10_36_09 | Opra10_36_10 | Opra10_36_11
| Opra10_36_12 | Opra10_36_13 | Opra10_36_14 | Opra10_36_15
| Opra10_36_16 | Opra10_36_17 | Opra10_36_18 | Opra10_36_19
| Opra10_36_20 | Opra10_36_21 | Opra10_36_22 | Opra10_36_23
| Opra10_36_24 | Opra10_36_25 | Opra10_36_26 | Opra10_36_27
| Opra10_36_28 | Opra10_36_29 | Opra10_36_30 | Opra10_36_31
| Opra10_36_32 | Opra10_36_33 | Opra10_36_34 | Opra10_36_35
| Opra10_36_36 | Opra10_36_37 | Opra10_36_38 | Opra10_36_39
| Opra10_37_00 | Opra10_37_01 | Opra10_37_02 | Opra10_37_03
| Opra10_37_04 | Opra10_37_05 | Opra10_37_06 | Opra10_37_07
| Opra10_37_08 | Opra10_37_09 | Opra10_37_10 | Opra10_37_11
| Opra10_37_12 | Opra10_37_13 | Opra10_37_14 | Opra10_37_15
| Opra10_37_16 | Opra10_37_17 | Opra10_37_18 | Opra10_37_19
| Opra10_37_20 | Opra10_37_21 | Opra10_37_22 | Opra10_37_23
| Opra10_37_24 | Opra10_37_25 | Opra10_37_26 | Opra10_37_27
| Opra10_37_28 | Opra10_37_29 | Opra10_37_30 | Opra10_37_31
| Opra10_37_32 | Opra10_37_33 | Opra10_37_34 | Opra10_37_35
| Opra10_37_36 | Opra10_37_37 | Opra10_37_38 | Opra10_37_39
| Opra10_38_00 | Opra10_38_01 | Opra10_38_02 | Opra10_38_03
| Opra10_38_04 | Opra10_38_05 | Opra10_38_06 | Opra10_38_07
| Opra10_38_08 | Opra10_38_09 | Opra10_38_10 | Opra10_38_11
| Opra10_38_12 | Opra10_38_13 | Opra10_38_14 | Opra10_38_15
| Opra10_38_16 | Opra10_38_17 | Opra10_38_18 | Opra10_38_19
| Opra10_38_20 | Opra10_38_21 | Opra10_38_22 | Opra10_38_23
| Opra10_38_24 | Opra10_38_25 | Opra10_38_26 | Opra10_38_27
| Opra10_38_28 | Opra10_38_29 | Opra10_38_30 | Opra10_38_31
| Opra10_38_32 | Opra10_38_33 | Opra10_38_34 | Opra10_38_35
| Opra10_38_36 | Opra10_38_37 | Opra10_38_38 | Opra10_38_39
| Opra10_39_00 | Opra10_39_01 | Opra10_39_02 | Opra10_39_03
| Opra10_39_04 | Opra10_39_05 | Opra10_39_06 | Opra10_39_07
| Opra10_39_08 | Opra10_39_09 | Opra10_39_10 | Opra10_39_11
| Opra10_39_12 | Opra10_39_13 | Opra10_39_14 | Opra10_39_15
| Opra10_39_16 | Opra10_39_17 | Opra10_39_18 | Opra10_39_19
| Opra10_39_20 | Opra10_39_21 | Opra10_39_22 | Opra10_39_23
| Opra10_39_24 | Opra10_39_25 | Opra10_39_26 | Opra10_39_27
| Opra10_39_28 | Opra10_39_29 | Opra10_39_30 | Opra10_39_31
| Opra10_39_32 | Opra10_39_33 | Opra10_39_34 | Opra10_39_35
| Opra10_39_36 | Opra10_39_37 | Opra10_39_38 | Opra10_39_39
| Opra10_s_0 | Opra10_s_1 | Opra10_s_2 | Opra10_s_3
| Opra10_s_4 | Opra10_s_5 | Opra10_s_6 | Opra10_s_7
| Opra10_s_8 | Opra10_s_9 | Opra10_s_10 | Opra10_s_11
| Opra10_s_12 | Opra10_s_13 | Opra10_s_14 | Opra10_s_15
| Opra10_s_16 | Opra10_s_17 | Opra10_s_18 | Opra10_s_19
| Opra10_s_20 | Opra10_s_21 | Opra10_s_22 | Opra10_s_23
| Opra10_s_24 | Opra10_s_25 | Opra10_s_26 | Opra10_s_27
| Opra10_s_28 | Opra10_s_29 | Opra10_s_30 | Opra10_s_31
| Opra10_s_32 | Opra10_s_33 | Opra10_s_34 | Opra10_s_35
| Opra10_s_36 | Opra10_s_37 | Opra10_s_38 | Opra10_s_39
deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance Opram Opra10 where
m _ = 10
instance Calculus Opra10 where
rank _ = 2
cName _ = "opra-10"
cNameGqr _ ="opra10"
cReadRel = readOpram
cShowRel = showOpram
cSparqifyRel = sparqifyOpram
cGqrifyRel = sparqifyOpram
cBaserelationsArealList = areal cBaserelationsList
cBaserelationsNonArealList = nonAreal cBaserelationsList
bcConvert = opraConvert 10
|
spatial-reasoning/zeno
|
src/Calculus/Opra10.hs
|
bsd-2-clause
| 30,136 | 0 | 6 | 8,891 | 5,074 | 3,365 | 1,709 | 429 | 0 |
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, BangPatterns #-}
module Main (
main
) where
import Common
import Channels
import BuggyLazyEvaluation
import qualified Optimizations as Optimizations
import Control.DeepSeq
import System.Random
import Data.List as L
import qualified Data.Vector.Unboxed as BV
import System.Environment
import System.Exit (die)
import Criterion.Main
import Criterion.Main.Options
import Criterion.Types
-- NOTE: many params are passed from the command-line, so the compiler
-- can not optimize (cheating) the code in advance.
main = do
args <- getArgs
case args of
["test", "channels", chanTypeS, seedS, vectorDimensionS, channelDimensionS]
-> do let seed :: Int = read seedS
let vectorDimension :: Int = read vectorDimensionS
let channelDimension :: Int = read channelDimensionS
let fuzzyNormalizer = 12456789
let chanType = case chanTypeS of
"default"
-> OneDefaultChan
"bounded"
-> OneBoundedChan
"mvar"
-> OneMVarChan
testChannels chanType seed fuzzyNormalizer vectorDimension channelDimension
["test", "deadlock1", chanTypeS, seedS, fuzzyS, elementsS]
-> do let seed :: Int = read seedS
let fuzzyNormalizer :: Int = read fuzzyS
let nrOfElements :: Int = read elementsS
let chanType = case chanTypeS of
"default"
-> OneDefaultChan
"bounded"
-> OneBoundedChan
"mvar"
-> OneMVarChan
let producedEementsForSecond :: Int = 5000
let consumedElementsForSecond :: Int = 500
let wait s = 10^6 `div` s
process_manager seed fuzzyNormalizer (wait producedEementsForSecond) (wait consumedElementsForSecond) nrOfElements
["bench", "strict1", seedS, vectorDimensionS, channelDimensionS, useStrictS]
-> do let seed :: Int = read seedS
let vectorDimension :: Int = read vectorDimensionS
let channelDimension :: Int = read channelDimensionS
let useStrict = case useStrictS of
"0" -> False
"1" -> True
let f = Optimizations.processVectorsBV seed vectorDimension channelDimension useStrict
runMode
(Run defaultConfig Prefix [""])
[bench "processVectorsBV" $ nf f 0]
putStrLn $ "processVectorsBV result: " ++ show (f 0)
["bench", "fusion1", seedS, vectorDimensionS]
-> do let seed :: Int = read seedS
let vectorDimension :: Int = read vectorDimensionS
let !l = force $ L.take vectorDimension $ randoms $ mkStdGen seed
runMode
(Run defaultConfig Prefix [""])
[ bench "list initial warm-up evaluation - not consider" $ nf L.sum l
, bench "fusion list with foldl" $ nf Optimizations.fusionOnListFoldl l
, bench "fused list with foldl" $ nf Optimizations.fusedOnListFoldl l
, bench "fusion list with foldl'" $ nf Optimizations.fusionOnListFoldl' l
, bench "fused list with foldl'" $ nf Optimizations.fusedOnListFoldl' l
, bench "fusion list with foldr" $ nf Optimizations.fusionOnListFoldr l
, bench "fused list with foldr" $ nf Optimizations.fusedOnListFoldr l
, bench "io-stream" $ nfIO $ Optimizations.fusionOnStream l
, bench "fused io-stream" $ nfIO $ Optimizations.fusedOnStream l
]
putStrLn $ "fusion list with foldl: " ++ show (Optimizations.fusionOnListFoldl l)
putStrLn $ "fusion list with foldr: " ++ show (Optimizations.fusionOnListFoldr l)
putStrLn $ "fused list with foldl: " ++ show (Optimizations.fusedOnListFoldl l)
putStrLn $ "fused list with foldr: " ++ show (Optimizations.fusedOnListFoldr l)
r1 <- Optimizations.fusionOnStream l
r2 <- Optimizations.fusedOnStream l
putStrLn $ "io-stream: " ++ show r1
putStrLn $ "fused io-stream: " ++ show r2
["bench", "chan1", seedS, vectorDimensionS]
-> do let seed :: Int = read seedS
let vectorDimension :: Int = read vectorDimensionS
let !l = force $ BV.fromListN vectorDimension $ L.take vectorDimension $ randoms $ mkStdGen seed
runMode
(Run defaultConfig Prefix [""])
[ bench "list initial warm-up evaluation - not consider" $ nf (BV.foldl (+) 0) l
, bench "sumOnVector" $ nf Optimizations.sumOnVector l
, bench "sumOnStream" $ nfIO $ Optimizations.sumOnStream l
, bench "sumOnChan" $ nfIO $ Optimizations.sumOnChan l
, bench "sumOnUnagi" $ nfIO $ Optimizations.sumOnUnagi l
]
r1 <- Optimizations.sumOnStream l
r2 <- Optimizations.sumOnChan l
r3 <- Optimizations.sumOnUnagi l
putStrLn $ "sumOnVector: " ++ show (Optimizations.sumOnVector l)
putStrLn $ "sumOnStream: " ++ show r1
putStrLn $ "sumOnChan: " ++ show r2
putStrLn $ "sumOnUnagi: " ++ show r3
["bench", "task1", seedS, vectorDimensionS]
-> do let seed :: Int = read seedS
let vectorDimension :: Int = read vectorDimensionS
let !l = force $ BV.fromListN vectorDimension $ L.take vectorDimension $ randoms $ mkStdGen seed
runMode
(Run defaultConfig Prefix [""])
[ bench "list initial warm-up evaluation - not consider" $ nf (BV.foldl (+) 0) l
, bench "sumOnChan" $ nfIO $ Optimizations.sumOnChan l
, bench "sumUsingTasks" $ nfIO $ Optimizations.sumUsingTasks l
]
r1 <- Optimizations.sumOnChan l
r2 <- Optimizations.sumUsingTasks l
putStrLn $ "sumOnChan: " ++ show r1
putStrLn $ "sumUsingTasks: " ++ show r2
["test", "buggy-lazy-evaluation"]
-> testBuggyLazyEvaluation
_ -> die "Unrecognized options."
|
massimo-zaniboni/threads-post
|
src/Main.hs
|
bsd-2-clause
| 6,369 | 0 | 20 | 2,131 | 1,556 | 741 | 815 | 116 | 13 |
module Main where
import Haggis.Parser
import Haggis.Checker
import Haggis.Interpreter
main :: IO ()
main = undefined
|
sivawashere/haggis
|
src/Main.hs
|
bsd-2-clause
| 119 | 0 | 6 | 17 | 34 | 20 | 14 | 6 | 1 |
{-# LANGUAGE RankNTypes, RecordWildCards, FlexibleInstances #-}
-- Example of using device-check
import Test.DeviceCheck
import Control.Concurrent
import Data.Monoid
import Control.Monad
main = do
v_in <- newEmptyMVar
v_out <- newEmptyMVar
let loop :: Int -> IO ()
loop n = do
i <- takeMVar v_in
putMVar v_out n
loop (i + n)
forkIO $ loop 0
let dut :: DUT Int
dut = DUT
{ send_in = putMVar v_in
, recv_out = takeMVar v_out
}
runDutM "seed" (callout dut) program
return ()
------------------------------------------------------------------------------
program :: DutM (ExampleCmd Int) ()
program = do
property prop
sender <> recvr
where
sender = forever $ do
w1 <- randR (0,20)
wait w1
d2 <- randR (0,255::Int)
send (fromIntegral d2)
recvr = forever $ do
w1 <- randR (0,20)
wait w1
recv
prop :: Prop (ExampleCmd Int)
prop = Prop "prop" $ \ cmds -> step (map send1 cmds) (map recv1 cmds) 0
where
step (Nothing:is) (Nothing:os) n = Nothing : step is os n
step (Nothing:is) (Just (Ret b):os) n
| b == n = Nothing : step is os n
| otherwise = repeat (Just "bad")
step (Just a:is) (Nothing:os) n = Nothing : step is os (n + a)
step (Just a:is) (Just (Ret b):os) n
| b == n = Nothing : step is os (n + a)
| otherwise = repeat (Just "bad")
------------------------------------------------------------------------------
send :: a -> DutM (ExampleCmd a) ()
send d = putCmd0 $ mempty { send1 = Just d }
recv :: DutM (ExampleCmd a) a
recv = putCmd1 $ \ reply -> mempty { recv1 = Just reply }
------------------------------------------------------------------------------
data DUT a = DUT
{ send_in :: a -> IO ()
, recv_out :: IO a
}
data ExampleCmd a resp = ExampleCmd
{ send1 :: Maybe a
, recv1 :: Maybe (resp a)
}
-- This is called once per cycle.
callout :: (Num a) => DUT a -> ExampleCmd a Reply -> IO (ExampleCmd a Ret)
callout (DUT { .. }) (ExampleCmd { .. }) = do
-- print "callout"
send1' <- case send1 of
Nothing -> do
send_in 0
return Nothing
Just u -> do
send_in u
return $ Just u
recv1' <- case recv1 of
Nothing -> do
_ <- recv_out
return Nothing
Just (Reply resp) -> do
u <- recv_out
resp u
return $ Just (Ret u)
let cmd = ExampleCmd
{ send1 = send1'
, recv1 = recv1'
}
-- print cmd
return cmd
instance Show a => Show (ExampleCmd a Ret) where
show (ExampleCmd { .. }) =
"FifoCmd { send1 = " ++ show send1 ++
", recv1 = " ++ show recv1 ++
"}"
instance Monoid (ExampleCmd a b) where
mempty = ExampleCmd
{ send1 = Nothing
, recv1 = Nothing
}
mappend f1 f2 = ExampleCmd
{ send1 = send1 f1 `mplus` send1 f2
, recv1 = recv1 f1 `mplus` recv1 f2
}
|
ku-fpg/device-check
|
example/Main.hs
|
bsd-3-clause
| 3,555 | 0 | 16 | 1,492 | 1,134 | 561 | 573 | 86 | 4 |
{-# LANGUAGE OverloadedStrings #-}
import System.IO
import Text.XML.Pipe
import Network
import HttpPullTlsCl
main :: IO ()
main = do
h <- connectTo "localhost" $ PortNumber 443
testPusher (undefined :: HttpPullTlsCl Handle) (One h)
(HttpPullTlsClArgs "localhost" 443 "/"
(XmlNode (nullQ "poll") [] [] []) pendingQ drtn gtPth)
pendingQ :: XmlNode -> Bool
pendingQ (XmlNode (_, "nothing") _ [] []) = False
pendingQ _ = True
drtn :: XmlNode -> Maybe Int
drtn (XmlNode (_, "slow") _ [] []) = Just 20000000
drtn (XmlNode (_, "medium") _ [] []) = Just 10000000
drtn (XmlNode (_, "fast") _ [] []) = Just 5000000
drtn (XmlNode (_, "very_fast") _ [] []) = Just 1000000
drtn (XmlNode (_, "fastest") _ [] []) = Just 100000
drtn _ = Nothing
gtPth :: XmlNode -> FilePath
gtPth (XmlNode (_, "father") _ [] []) = "family"
gtPth _ = "others"
|
YoshikuniJujo/forest
|
subprojects/xml-push/testHttpPullTlsCl.hs
|
bsd-3-clause
| 839 | 4 | 13 | 155 | 401 | 207 | 194 | 24 | 1 |
module Main (main) where
import qualified Distribution.ModuleName as ModuleName
import Distribution.PackageDescription
import Distribution.PackageDescription.Check hiding (doesFileExist)
import Distribution.PackageDescription.Configuration
import Distribution.PackageDescription.Parse
import Distribution.Package
import Distribution.System
import Distribution.Simple
import Distribution.Simple.Configure
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.GHC
import Distribution.Simple.Program
import Distribution.Simple.Program.HcPkg
import Distribution.Simple.Setup (ConfigFlags(configStripLibs), fromFlag, toFlag)
import Distribution.Simple.Utils (defaultPackageDesc, writeFileAtomic, toUTF8)
import Distribution.Simple.Build (writeAutogenFiles)
import Distribution.Simple.Register
import Distribution.Text
import Distribution.Verbosity
import qualified Distribution.InstalledPackageInfo as Installed
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Control.Exception (bracket)
import Control.Monad
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.List
import Data.Maybe
import System.IO
import System.Directory
import System.Environment
import System.Exit (exitWith, ExitCode(..))
import System.FilePath
main :: IO ()
main = do hSetBuffering stdout LineBuffering
args <- getArgs
case args of
"hscolour" : dir : distDir : args' ->
runHsColour dir distDir args'
"check" : dir : [] ->
doCheck dir
"copy" : dir : distDir
: strip : myDestDir : myPrefix : myLibdir : myDocdir
: ghcLibWays : args' ->
doCopy dir distDir
strip myDestDir myPrefix myLibdir myDocdir
("dyn" `elem` words ghcLibWays)
args'
"register" : dir : distDir : ghc : ghcpkg : topdir
: myDestDir : myPrefix : myLibdir : myDocdir
: relocatableBuild : args' ->
doRegister dir distDir ghc ghcpkg topdir
myDestDir myPrefix myLibdir myDocdir
relocatableBuild args'
"configure" : dir : distDir : dll0Modules : config_args ->
generate dir distDir dll0Modules config_args
"sdist" : dir : distDir : [] ->
doSdist dir distDir
["--version"] ->
defaultMainArgs ["--version"]
_ -> die syntax_error
syntax_error :: [String]
syntax_error =
["syntax: ghc-cabal configure <configure-args> -- <distdir> <directory>...",
" ghc-cabal install <ghc-pkg> <directory> <distdir> <destdir> <prefix> <args>...",
" ghc-cabal hscolour <distdir> <directory> <args>..."]
die :: [String] -> IO a
die errs = do mapM_ (hPutStrLn stderr) errs
exitWith (ExitFailure 1)
withCurrentDirectory :: FilePath -> IO a -> IO a
withCurrentDirectory directory io
= bracket (getCurrentDirectory) (setCurrentDirectory)
(const (setCurrentDirectory directory >> io))
-- We need to use the autoconfUserHooks, as the packages that use
-- configure can create a .buildinfo file, and we need any info that
-- ends up in it.
userHooks :: UserHooks
userHooks = autoconfUserHooks
runDefaultMain :: IO ()
runDefaultMain
= do let verbosity = normal
gpdFile <- defaultPackageDesc verbosity
gpd <- readPackageDescription verbosity gpdFile
case buildType (flattenPackageDescription gpd) of
Just Configure -> defaultMainWithHooks autoconfUserHooks
-- time has a "Custom" Setup.hs, but it's actually Configure
-- plus a "./Setup test" hook. However, Cabal is also
-- "Custom", but doesn't have a configure script.
Just Custom ->
do configureExists <- doesFileExist "configure"
if configureExists
then defaultMainWithHooks autoconfUserHooks
else defaultMain
-- not quite right, but good enough for us:
_ -> defaultMain
doSdist :: FilePath -> FilePath -> IO ()
doSdist directory distDir
= withCurrentDirectory directory
$ withArgs (["sdist", "--builddir", distDir])
runDefaultMain
doCheck :: FilePath -> IO ()
doCheck directory
= withCurrentDirectory directory
$ do let verbosity = normal
gpdFile <- defaultPackageDesc verbosity
gpd <- readPackageDescription verbosity gpdFile
case filter isFailure $ checkPackage gpd Nothing of
[] -> return ()
errs -> mapM_ print errs >> exitWith (ExitFailure 1)
where isFailure (PackageDistSuspicious {}) = False
isFailure (PackageDistSuspiciousWarn {}) = False
isFailure _ = True
runHsColour :: FilePath -> FilePath -> [String] -> IO ()
runHsColour directory distdir args
= withCurrentDirectory directory
$ defaultMainArgs ("hscolour" : "--builddir" : distdir : args)
doCopy :: FilePath -> FilePath
-> FilePath -> FilePath -> FilePath -> FilePath -> FilePath -> Bool
-> [String]
-> IO ()
doCopy directory distDir
strip myDestDir myPrefix myLibdir myDocdir withSharedLibs
args
= withCurrentDirectory directory $ do
let copyArgs = ["copy", "--builddir", distDir]
++ (if null myDestDir
then []
else ["--destdir", myDestDir])
++ args
copyHooks = userHooks {
copyHook = noGhcPrimHook
$ modHook False
$ copyHook userHooks
}
defaultMainWithHooksArgs copyHooks copyArgs
where
noGhcPrimHook f pd lbi us flags
= let pd'
| packageName pd == PackageName "ghc-prim" =
case library pd of
Just lib ->
let ghcPrim = fromJust (simpleParse "GHC.Prim")
ems = filter (ghcPrim /=) (exposedModules lib)
lib' = lib { exposedModules = ems }
in pd { library = Just lib' }
Nothing ->
error "Expected a library, but none found"
| otherwise = pd
in f pd' lbi us flags
modHook relocatableBuild f pd lbi us flags
= do let verbosity = normal
idts = updateInstallDirTemplates relocatableBuild
myPrefix myLibdir myDocdir
(installDirTemplates lbi)
progs = withPrograms lbi
stripProgram' = stripProgram {
programFindLocation = \_ _ -> return (Just strip) }
progs' <- configureProgram verbosity stripProgram' progs
let lbi' = lbi {
withPrograms = progs',
installDirTemplates = idts,
configFlags = cfg,
stripLibs = fromFlag (configStripLibs cfg),
withSharedLib = withSharedLibs
}
-- This hack allows to interpret the "strip"
-- command-line argument being set to ':' to signify
-- disabled library stripping
cfg | strip == ":" = (configFlags lbi) { configStripLibs = toFlag False }
| otherwise = configFlags lbi
f pd lbi' us flags
doRegister :: FilePath -> FilePath -> FilePath -> FilePath
-> FilePath -> FilePath -> FilePath -> FilePath -> FilePath
-> String -> [String]
-> IO ()
doRegister directory distDir ghc ghcpkg topdir
myDestDir myPrefix myLibdir myDocdir
relocatableBuildStr args
= withCurrentDirectory directory $ do
relocatableBuild <- case relocatableBuildStr of
"YES" -> return True
"NO" -> return False
_ -> die ["Bad relocatableBuildStr: " ++
show relocatableBuildStr]
let regArgs = "register" : "--builddir" : distDir : args
regHooks = userHooks {
regHook = modHook relocatableBuild
$ regHook userHooks
}
defaultMainWithHooksArgs regHooks regArgs
where
modHook relocatableBuild f pd lbi us flags
= do let verbosity = normal
idts = updateInstallDirTemplates relocatableBuild
myPrefix myLibdir myDocdir
(installDirTemplates lbi)
progs = withPrograms lbi
ghcpkgconf = topdir </> "package.conf.d"
ghcProgram' = ghcProgram {
programPostConf = \_ cp -> return cp { programDefaultArgs = ["-B" ++ topdir] },
programFindLocation = \_ _ -> return (Just ghc) }
ghcPkgProgram' = ghcPkgProgram {
programPostConf = \_ cp -> return cp { programDefaultArgs =
["--global-package-db", ghcpkgconf]
++ ["--force" | not (null myDestDir) ] },
programFindLocation = \_ _ -> return (Just ghcpkg) }
configurePrograms ps conf = foldM (flip (configureProgram verbosity)) conf ps
progs' <- configurePrograms [ghcProgram', ghcPkgProgram'] progs
instInfos <- dump (hcPkgInfo progs') verbosity GlobalPackageDB
let installedPkgs' = PackageIndex.fromList instInfos
let updateComponentConfig (cn, clbi, deps)
= (cn, updateComponentLocalBuildInfo clbi, deps)
updateComponentLocalBuildInfo clbi = clbi -- TODO: remove
ccs' = map updateComponentConfig (componentsConfigs lbi)
lbi' = lbi {
componentsConfigs = ccs',
installedPkgs = installedPkgs',
installDirTemplates = idts,
withPrograms = progs'
}
f pd lbi' us flags
updateInstallDirTemplates :: Bool -> FilePath -> FilePath -> FilePath
-> InstallDirTemplates
-> InstallDirTemplates
updateInstallDirTemplates relocatableBuild myPrefix myLibdir myDocdir idts
= idts {
prefix = toPathTemplate $
if relocatableBuild
then "$topdir"
else myPrefix,
libdir = toPathTemplate $
if relocatableBuild
then "$topdir"
else myLibdir,
libsubdir = toPathTemplate "$libname",
docdir = toPathTemplate $
if relocatableBuild
then "$topdir/../doc/html/libraries/$pkgid"
else (myDocdir </> "$pkgid"),
htmldir = toPathTemplate "$docdir"
}
-- On Windows we need to split the ghc package into 2 pieces, or the
-- DLL that it makes contains too many symbols (#5987). There are
-- therefore 2 libraries, not just the 1 that Cabal assumes.
mangleIPI :: FilePath -> FilePath -> LocalBuildInfo
-> Installed.InstalledPackageInfo -> Installed.InstalledPackageInfo
mangleIPI "compiler" "stage2" lbi ipi
| isWindows =
-- Cabal currently only ever installs ONE Haskell library, c.f.
-- the code in Cabal.Distribution.Simple.Register. If it
-- ever starts installing more we'll have to find the
-- library that's too big and split that.
let [old_hslib] = Installed.hsLibraries ipi
in ipi {
Installed.hsLibraries = [old_hslib, old_hslib ++ "-0"]
}
where isWindows = case hostPlatform lbi of
Platform _ Windows -> True
_ -> False
mangleIPI _ _ _ ipi = ipi
generate :: FilePath -> FilePath -> String -> [String] -> IO ()
generate directory distdir dll0Modules config_args
= withCurrentDirectory directory
$ do let verbosity = normal
-- XXX We shouldn't just configure with the default flags
-- XXX And this, and thus the "getPersistBuildConfig distdir" below,
-- aren't going to work when the deps aren't built yet
withArgs (["configure", "--distdir", distdir, "--ipid", "$pkg-$version"] ++ config_args)
runDefaultMain
lbi <- getPersistBuildConfig distdir
let pd0 = localPkgDescr lbi
writePersistBuildConfig distdir lbi
hooked_bi <-
if (buildType pd0 == Just Configure) || (buildType pd0 == Just Custom)
then do
maybe_infoFile <- defaultHookedPackageDesc
case maybe_infoFile of
Nothing -> return emptyHookedBuildInfo
Just infoFile -> readHookedBuildInfo verbosity infoFile
else
return emptyHookedBuildInfo
let pd = updatePackageDescription hooked_bi pd0
-- generate Paths_<pkg>.hs and cabal-macros.h
writeAutogenFiles verbosity pd lbi
-- generate inplace-pkg-config
withLibLBI pd lbi $ \lib clbi ->
do cwd <- getCurrentDirectory
let ipid = ComponentId (display (packageId pd))
let installedPkgInfo = inplaceInstalledPackageInfo cwd distdir
pd (Installed.AbiHash "") lib lbi clbi
final_ipi = mangleIPI directory distdir lbi $ installedPkgInfo {
Installed.installedComponentId = ipid,
Installed.compatPackageKey = ipid,
Installed.haddockHTMLs = []
}
content = Installed.showInstalledPackageInfo final_ipi ++ "\n"
writeFileAtomic (distdir </> "inplace-pkg-config") (BS.pack $ toUTF8 content)
let
comp = compiler lbi
libBiModules lib = (libBuildInfo lib, libModules lib)
exeBiModules exe = (buildInfo exe, ModuleName.main : exeModules exe)
biModuless = (maybeToList $ fmap libBiModules $ library pd)
++ (map exeBiModules $ executables pd)
buildableBiModuless = filter isBuildable biModuless
where isBuildable (bi', _) = buildable bi'
(bi, modules) = case buildableBiModuless of
[] -> error "No buildable component found"
[biModules] -> biModules
_ -> error ("XXX ghc-cabal can't handle " ++
"more than one buildinfo yet")
-- XXX Another Just...
Just ghcProg = lookupProgram ghcProgram (withPrograms lbi)
dep_pkgs = PackageIndex.topologicalOrder (packageHacks (installedPkgs lbi))
forDeps f = concatMap f dep_pkgs
-- copied from Distribution.Simple.PreProcess.ppHsc2Hs
packageHacks = case compilerFlavor (compiler lbi) of
GHC -> hackRtsPackage
_ -> id
-- We don't link in the actual Haskell libraries of our
-- dependencies, so the -u flags in the ldOptions of the rts
-- package mean linking fails on OS X (it's ld is a tad
-- stricter than gnu ld). Thus we remove the ldOptions for
-- GHC's rts package:
hackRtsPackage index =
case PackageIndex.lookupPackageName index (PackageName "rts") of
[(_,[rts])] ->
PackageIndex.insert rts{
Installed.ldOptions = [],
Installed.libraryDirs = filter (not . ("gcc-lib" `isSuffixOf`)) (Installed.libraryDirs rts)} index
-- GHC <= 6.12 had $topdir/gcc-lib in their
-- library-dirs for the rts package, which causes
-- problems when we try to use the in-tree mingw,
-- due to accidentally picking up the incompatible
-- libraries there. So we filter out gcc-lib from
-- the RTS's library-dirs here.
_ -> error "No (or multiple) ghc rts package is registered!!"
dep_ids = map snd (externalPackageDeps lbi)
deps = map display dep_ids
dep_direct = map (fromMaybe (error "ghc-cabal: dep_keys failed")
. PackageIndex.lookupComponentId
(installedPkgs lbi)
. fst)
. externalPackageDeps
$ lbi
dep_ipids = map (display . Installed.installedComponentId) dep_direct
depLibNames
| packageKeySupported comp = dep_ipids
| otherwise = deps
depNames = map (display . packageName) dep_ids
transitive_dep_ids = map Installed.sourcePackageId dep_pkgs
transitiveDeps = map display transitive_dep_ids
transitiveDepLibNames
| packageKeySupported comp = map fixupRtsLibName transitiveDeps
| otherwise = transitiveDeps
fixupRtsLibName "rts-1.0" = "rts"
fixupRtsLibName x = x
transitiveDepNames = map (display . packageName) transitive_dep_ids
libraryDirs = forDeps Installed.libraryDirs
-- The mkLibraryRelDir function is a bit of a hack.
-- Ideally it should be handled in the makefiles instead.
mkLibraryRelDir "rts" = "rts/dist/build"
mkLibraryRelDir "ghc" = "compiler/stage2/build"
mkLibraryRelDir "Cabal" = "libraries/Cabal/Cabal/dist-install/build"
mkLibraryRelDir l = "libraries/" ++ l ++ "/dist-install/build"
libraryRelDirs = map mkLibraryRelDir transitiveDepNames
wrappedIncludeDirs <- wrap $ forDeps Installed.includeDirs
wrappedLibraryDirs <- wrap libraryDirs
let variablePrefix = directory ++ '_':distdir
mods = map display modules
otherMods = map display (otherModules bi)
allMods = mods ++ otherMods
let xs = [variablePrefix ++ "_VERSION = " ++ display (pkgVersion (package pd)),
-- TODO: move inside withLibLBI
variablePrefix ++ "_COMPONENT_ID = " ++ display (localCompatPackageKey lbi),
-- copied from mkComponentsLocalBuildInfo
variablePrefix ++ "_COMPONENT_ID = " ++ display (localComponentId lbi),
variablePrefix ++ "_MODULES = " ++ unwords mods,
variablePrefix ++ "_HIDDEN_MODULES = " ++ unwords otherMods,
variablePrefix ++ "_SYNOPSIS =" ++ synopsis pd,
variablePrefix ++ "_HS_SRC_DIRS = " ++ unwords (hsSourceDirs bi),
variablePrefix ++ "_DEPS = " ++ unwords deps,
variablePrefix ++ "_DEP_IPIDS = " ++ unwords dep_ipids,
variablePrefix ++ "_DEP_NAMES = " ++ unwords depNames,
variablePrefix ++ "_DEP_COMPONENT_IDS = " ++ unwords depLibNames,
variablePrefix ++ "_TRANSITIVE_DEPS = " ++ unwords transitiveDeps,
variablePrefix ++ "_TRANSITIVE_DEP_COMPONENT_IDS = " ++ unwords transitiveDepLibNames,
variablePrefix ++ "_TRANSITIVE_DEP_NAMES = " ++ unwords transitiveDepNames,
variablePrefix ++ "_INCLUDE_DIRS = " ++ unwords (includeDirs bi),
variablePrefix ++ "_INCLUDES = " ++ unwords (includes bi),
variablePrefix ++ "_INSTALL_INCLUDES = " ++ unwords (installIncludes bi),
variablePrefix ++ "_EXTRA_LIBRARIES = " ++ unwords (extraLibs bi),
variablePrefix ++ "_EXTRA_LIBDIRS = " ++ unwords (extraLibDirs bi),
variablePrefix ++ "_C_SRCS = " ++ unwords (cSources bi),
variablePrefix ++ "_CMM_SRCS := $(addprefix cbits/,$(notdir $(wildcard " ++ directory ++ "/cbits/*.cmm)))",
variablePrefix ++ "_DATA_FILES = " ++ unwords (dataFiles pd),
-- XXX This includes things it shouldn't, like:
-- -odir dist-bootstrapping/build
variablePrefix ++ "_HC_OPTS = " ++ escape (unwords
( programDefaultArgs ghcProg
++ hcOptions GHC bi
++ languageToFlags (compiler lbi) (defaultLanguage bi)
++ extensionsToFlags (compiler lbi) (usedExtensions bi)
++ programOverrideArgs ghcProg)),
variablePrefix ++ "_CC_OPTS = " ++ unwords (ccOptions bi),
variablePrefix ++ "_CPP_OPTS = " ++ unwords (cppOptions bi),
variablePrefix ++ "_LD_OPTS = " ++ unwords (ldOptions bi),
variablePrefix ++ "_DEP_INCLUDE_DIRS_SINGLE_QUOTED = " ++ unwords wrappedIncludeDirs,
variablePrefix ++ "_DEP_CC_OPTS = " ++ unwords (forDeps Installed.ccOptions),
variablePrefix ++ "_DEP_LIB_DIRS_SINGLE_QUOTED = " ++ unwords wrappedLibraryDirs,
variablePrefix ++ "_DEP_LIB_DIRS_SEARCHPATH = " ++ mkSearchPath libraryDirs,
variablePrefix ++ "_DEP_LIB_REL_DIRS = " ++ unwords libraryRelDirs,
variablePrefix ++ "_DEP_LIB_REL_DIRS_SEARCHPATH = " ++ mkSearchPath libraryRelDirs,
variablePrefix ++ "_DEP_EXTRA_LIBS = " ++ unwords (forDeps Installed.extraLibraries),
variablePrefix ++ "_DEP_LD_OPTS = " ++ unwords (forDeps Installed.ldOptions),
variablePrefix ++ "_BUILD_GHCI_LIB = " ++ boolToYesNo (withGHCiLib lbi),
"",
-- Sometimes we need to modify the automatically-generated package-data.mk
-- bindings in a special way for the GHC build system, so allow that here:
"$(eval $(" ++ directory ++ "_PACKAGE_MAGIC))"
]
writeFile (distdir ++ "/package-data.mk") $ unlines xs
writeFileUtf8 (distdir ++ "/haddock-prologue.txt") $
if null (description pd) then synopsis pd
else description pd
unless (null dll0Modules) $
do let dll0Mods = words dll0Modules
dllMods = allMods \\ dll0Mods
dllModSets = map unwords [dll0Mods, dllMods]
writeFile (distdir ++ "/dll-split") $ unlines dllModSets
where
escape = foldr (\c xs -> if c == '#' then '\\':'#':xs else c:xs) []
wrap = mapM wrap1
wrap1 s
| null s = die ["Wrapping empty value"]
| '\'' `elem` s = die ["Single quote in value to be wrapped:", s]
-- We want to be able to assume things like <space><quote> is the
-- start of a value, so check there are no spaces in confusing
-- positions
| head s == ' ' = die ["Leading space in value to be wrapped:", s]
| last s == ' ' = die ["Trailing space in value to be wrapped:", s]
| otherwise = return ("\'" ++ s ++ "\'")
mkSearchPath = intercalate [searchPathSeparator]
boolToYesNo True = "YES"
boolToYesNo False = "NO"
-- | Version of 'writeFile' that always uses UTF8 encoding
writeFileUtf8 f txt = withFile f WriteMode $ \hdl -> do
hSetEncoding hdl utf8
hPutStr hdl txt
|
siddhanathan/ghc
|
utils/ghc-cabal/Main.hs
|
bsd-3-clause
| 23,916 | 0 | 23 | 8,471 | 4,668 | 2,389 | 2,279 | 388 | 14 |
{-# LANGUAGE PackageImports #-}
module Data.Complex (module M) where
import "base" Data.Complex as M
|
silkapp/base-noprelude
|
src/Data/Complex.hs
|
bsd-3-clause
| 106 | 0 | 4 | 18 | 21 | 15 | 6 | 3 | 0 |
module Auth where
import Types
import System.Environment
getConf :: IO [String]
getConf = do
env <- getEnv "FIREBASE_CONF"
file <- readFile env
return $ lines file
|
sphaso/firebase-haskell-client
|
test/Auth.hs
|
bsd-3-clause
| 217 | 0 | 8 | 79 | 58 | 29 | 29 | 8 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module OpenRTB.Types.Enum.APIFrameworkSpec where
import Control.Applicative
import Data.Aeson
import Data.Aeson.TH
import Test.Hspec
import Test.QuickCheck
import Test.Instances
import OpenRTB.Types.Enum.APIFramework
data Mock = Mock { api :: APIFramework } deriving (Eq, Show)
$(deriveJSON defaultOptions ''Mock)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "APIFramework" $ do
context "JSON" $ do
it "should convert back and forth" $ property $ do
\m -> (decode . encode) m == Just (m :: Mock)
instance Arbitrary Mock where
arbitrary = Mock <$> arbitrary
|
ankhers/openRTB-hs
|
spec/OpenRTB/Types/Enum/APIFrameworkSpec.hs
|
bsd-3-clause
| 661 | 0 | 18 | 111 | 195 | 106 | 89 | 21 | 1 |
{-# LANGUAGE FlexibleInstances
, BangPatterns
, MagicHash
, ScopedTypeVariables
, TypeFamilies
, UndecidableInstances
, OverlappingInstances
, DeriveDataTypeable
, MultiParamTypeClasses
, NamedFieldPuns
#-}
-- State monad transformer is needed for both step & graph:
#ifndef MODNAME
#define MODNAME Intel.Cnc4
#endif
#define CNC_SCHEDULER 4
#define STEPLIFT S.lift$
#define GRAPHLIFT S.lift$
#define SUPPRESS_runGraph
#define DEFINED_free_items
#include "Cnc.Header.hs"
------------------------------------------------------------
-- Version 4: Global work queue and worker threads that spin until
-- execution is finished. Note, this ALSO includes the mortal threads
-- business from version 6.
#include "shared_5_6.hs"
-- FIXME: TODO: This version needs the Mortal threads mechanism in version 6...
-- Otherwise it creates extra threads that SPIN, which is terrible.
----------------------------------------------------------------------------------------------------
get col tag = ver5_6_core_get (return ()) col tag
-- get col tag =
-- do (HiddenState5 { stack, mortal }) <- S.get
-- let io = do myId <- myThreadId
-- modifyHotVar_ mortal (Set.insert myId)
-- ver5_6_core_get io col tag
-- At finalize time we set up the workers and run them.
finalize userFinalAction =
do (state @ HiddenState5 { stack, numworkers, mortal } ) <- S.get
let worker id =
do x <- STEPLIFT tryPop stack
let lifecheck =
do myId <- STEPLIFT myThreadId
set <- STEPLIFT readHotVar mortal
return (Set.notMember myId set)
case x of
Nothing -> do n <- STEPLIFT readHotVar numworkers
--STEPLIFT putStrLn$ "NUM WORKERS IS " ++ show n++"\n"
-- numWorkers == 0 implies a message to shutdown.
if n == 0
then do --STEPLIFT putStrLn$ "================ SHUTTING DOWN "++ show id ++"=============="
return ()
else do -- A mortal thread should never spin:
b <- lifecheck
if b
-- Should we be cooperative by sleeping a little?
--System.Posix.usleep 1000
then do STEPLIFT yield
worker id
else return ()
Just action -> do action
b <- lifecheck
if b then worker id else return ()
let finalAction =
do S.modify$ \stt -> stt { myid = numCapabilities-1 }
val <- userFinalAction
-- UGLY Convention: reusing numworkers variable that's already in the type:
-- This variable becomes a "command" rather than diagnosing the current state. Zero means stop working.
STEPLIFT writeHotVar numworkers 0 -- Shut workers down (eventually).
--STEPLIFT putStrLn$ " ..............>>>>>>>>>>>>>>>>>>> Initiated shutdown...........\n"
return val
-- The final action will itself be one of the threads and it
-- will replace itself when it blocks on a get. Therefore we
-- request one fewer worker:
--ver5_6_core_finalize joiner finalAction worker False (numCapabilities-1)
--
-- FIXME: TODO: Currently having inexplicable problems on embarassingly_par with the N-1 approach.
-- For now oversubscribing intentionally as the lesser of evils:
ver5_6_core_finalize (error "joiner unused") finalAction worker False numCapabilities (\_ -> return ())
------------------------------------------------------------
quiescence_support = False
|
rrnewton/Haskell-CnC
|
Intel/Cnc4.hs
|
bsd-3-clause
| 3,484 | 34 | 14 | 849 | 366 | 219 | 147 | 40 | 5 |
module Utility.Image
( mapImage
, mapImageBits
, foldImage
, foldImageBits
, bestMatchingColors
, tileImage
) where
import Graphics.Imlib
import qualified Data.Map as M
import Data.Ix
import Foreign
import Data.List
import Math.Metric
--instance Metric ImlibColor where
-- distance (ImlibColor _ r1 g1 b1) (ImlibColor _ r2 g2 b2) =
-- let r = fromIntegral r1 - fromIntegral r2
-- b = fromIntegral b1 - fromIntegral b2
-- g = fromIntegral g1 - fromIntegral g2
-- in sqrt(3*(r*r)+4*(g*g)+2*(b*b))
instance Metric ImlibColor where
distance (ImlibColor _ r1 g1 b1) (ImlibColor _ r2 g2 b2) =
let r' = (fromIntegral r1 + fromIntegral r2) / 2
r = fromIntegral r1 - fromIntegral r2
b = fromIntegral b1 - fromIntegral b2
g = fromIntegral g1 - fromIntegral g2
in sqrt((2+r'/256)*(r*r)+4*(g*g)+(2+(255-r')/256)*(b*b))
instance Ord ImlibColor where
compare a@(ImlibColor a1 r1 g1 b1) b@(ImlibColor a2 r2 g2 b2) =
let da = distance a (ImlibColor 255 255 255 255)
db = distance b (ImlibColor 255 255 255 255)
in compare da db
mapImage :: (Int -> Int -> ImlibColor -> a) -> IO [a]
mapImage f = do
w <- imageGetWidth
h <- imageGetHeight
p <- imageGetDataForReadingOnly
arr <- peekArray (w*h) p
return $ [f x y c | ((x,y),c) <- zip [(x,y) | y <- [0..(h-1)], x <- [0..(w-1)]] $ map colorFromBits arr]
mapImageBits :: (Int -> Int -> Word32 -> a) -> IO [a]
mapImageBits f = do
w <- imageGetWidth
h <- imageGetHeight
p <- imageGetDataForReadingOnly
arr <- peekArray (w*h) p
return $ [f x y b | ((x,y),b) <- zip [(x,y) | y <- [0..(h-1)], x <- [0..(w-1)]] arr]
foldImage :: (Int -> Int -> ImlibColor -> a -> a) -> a -> IO a
foldImage f a = do
w <- imageGetWidth
h <- imageGetHeight
p <- imageGetDataForReadingOnly
arr <- peekArray (w*h) p
return $ foldl' (\a' ((x,y),c) -> f x y c a') a $ zip [(x,y) | y <- [0..(h-1)], x <- [0..(w-1)]] $ map colorFromBits arr
foldImageBits :: (Int -> Int -> Word32 -> a -> a) -> a -> IO a
foldImageBits f a = do
w <- imageGetWidth
h <- imageGetHeight
p <- imageGetDataForReadingOnly
arr <- peekArray (w*h) p
return $ foldl' (\a' ((x,y),b) -> f x y b a') a $ zip [(x,y) | y <- [0..(h-1)], x <- [0..(w-1)]] arr
bestMatchingColors :: [ImlibColor] -> ImlibColor -> [ImlibColor]
bestMatchingColors (x:xs) c =
if null (x:xs)
then [ImlibColor 255 0 0 0,ImlibColor 255 255 255 255]
else recur xs c (distance x c) [x,ImlibColor 255 255 255 255]
where
recur [] _ _ xs' = xs'
recur (y:ys) c min xs' =
let s = distance y c
in if s < min
then recur ys c s (y:xs')
else recur ys c min xs'
data Neighbour = N | NE | E | SE | S | SW | W | NW
deriving (Eq,Ord,Ix,Show)
--neighbours :: (a,a) -> (a,a) -> (a,a) -> a -> (M.Map Neighbour ((a,a),a)),[Neighbour])
--neighbours (x,y) (w,h) (tw,th) o =
tileImage :: ImlibImage -> (Int,Int) -> Int -> String -> IO [ImlibImage]
tileImage image (tile_w,tile_h) overlap path = do
contextSetImage image
name <- imageGetFilename >>= return . takeWhile (not.(=='.'))
let path' = reverse $ dropWhile (=='/') $ reverse path
w <- imageGetWidth
h <- imageGetHeight
m <- if overlap == 0
then do
let numtiles_w = w `div` tile_w
let numtiles_h = h `div` tile_h
foldImageBits (\x y b m ->
let k = (x `div` tile_w) + (numtiles_w * (y `div` tile_h))
m' = M.insertWith (++) k [b] m
in if x >= (numtiles_w * tile_w) || y >= (numtiles_h * tile_h)
then m
else m') M.empty
else do
let numtiles_w = w `div` tile_w
let numtiles_h = h `div` tile_h
let max_x = if numtiles_w <= 1
then numtiles_w*tile_w-1
else if even numtiles_w
then (numtiles_w-2)*(tile_w-overlap)-(snd $ numtiles_w `divMod` 2)-1+(2*tile_w)-1
else (numtiles_w-2)*(tile_w-overlap)-(snd $ numtiles_w `divMod` 2)-1+(2*tile_w)
let max_y = if numtiles_h <= 1
then numtiles_h*tile_h-1
else if even numtiles_h
then (numtiles_h-2)*(tile_h-overlap)-(snd $ numtiles_h `divMod` 2)-1+(2*tile_h)-1
else (numtiles_h-2)*(tile_h-overlap)-(snd $ numtiles_h `divMod` 2)-1+(2*tile_h)
print numtiles_w
print numtiles_h
print max_x
print max_y
foldImageBits (\x y b m ->
let tws = takeWhile (<=x) [0,(tile_w-overlap)..]
ths = takeWhile (<=y) [0,(tile_h-overlap)..]
k = (length tws - 1) + (numtiles_w * (length ths - 1))
kw = k - 1
kh = k - numtiles_w
-- the following mess is responsible for creating the approriate neighboring
-- indices for the fold at the end of the let clause (an image is like a grid, think
-- of that and you'll get the idea what i am doing here)
-- i already thought of an replacement, which can been seen above,
-- the 'neighbours' function (which is commented out)
ks = case (last tws == x, last ths == y) of
(True,True) ->
case (x == 0, y == 0) of
(True,True) -> [k]
(True,False) ->
case (x == max_x, y == max_y) of
(False,False) -> [kh,k]
otherwise -> [kh]
(False,True) ->
case (x == max_x, y == max_y) of
(False,False) -> [kw,k]
otherwise -> [kw]
(False,False) ->
case (x == max_x, y == max_y) of
(False,False) -> [k,kw,kh,kh-1]
(True,False) -> [kh-1,kw]
(False,True) -> [kh-1,kh]
(True,True) -> [kh-1]
(False,True) ->
case (x == 0, y == 0) of
(True,True) -> [k]
(True,False) -> [kh,k]
(False,True) -> [k]
(False,False) ->
case (x == max_x, y == max_y) of
(False,False) -> [kh,k]
(False,True) -> [kh]
(True,False) ->
case (x == 0, y == 0) of
(True,True) -> [k]
(True,False) -> [k]
(False,True) -> [kw,k]
(False,False) ->
case (x == max_x, y == max_y) of
(False,False) -> [kw,k]
(True,False) -> [kw]
(False,False) -> [k]
-- this fold creates... whatever, i forgot, but it looks important
m' = foldl' (\m'' k -> M.insertWith (++) k [b] m'') m ks
in if x > max_x || y > max_y
then m
else m') M.empty --[(x,y) | y <- [0..(h-1)], x <- [0..(w-1)]]
sequence $ M.elems $ M.mapWithKey (\k xs -> withArray (reverse xs) (\p -> do
tile <- createImageUsingData tile_w tile_h p
contextSetImage tile
imageSetFormat "png"
saveImage $ path' ++ "/" ++ name ++ (show k) ++ ".png"
tile' <- loadImage $ path' ++ "/" ++ name ++ (show k) ++ ".png"
return tile')) m
--testfoo = do
-- image <- loadImage "mars_heightmap.png"
-- tileImage image (64,64) 1 "./tiles/"
|
rakete/ObjViewer
|
src/Utility/Image.hs
|
bsd-3-clause
| 8,474 | 1 | 28 | 3,592 | 2,926 | 1,574 | 1,352 | 154 | 27 |
module CmdLineProcessing
( processCmdLine
) where
import System.Environment (getArgs)
import Data.List (partition, sort, intercalate)
import Data.Tuple (swap)
import System.Console.GetOpt
import Tags
data TemplateOpts = H1
| H2
| Count { count :: Int }
deriving(Show, Eq, Ord)
tempfilename :: String
tempfilename = "./dokuwiki.template"
options :: [OptDescr TemplateOpts]
options = [
Option "c" ["count"] (ReqArg (\s -> Count (read s :: Int)) "") "Count of required templates",
Option "1" ["heading-level-1"] (NoArg H1) "Create Heading Level 1",
Option "2" ["heading-level-2"] (NoArg H2) "Create Heading Level 2"
]
processCmdLine :: IO ()
processCmdLine = do
args <- getArgs
let opts = getOpt RequireOrder options args
header = "Usage: dkwikitemp [OPTION...] files..."
case opts of
(o, no, []) -> execute o no
(_, _, err) -> ioError (userError (mappend (mconcat err) $ usageInfo header options)) :: IO ()
execute :: [TemplateOpts] -> [FilePath] -> IO ()
execute opts files
| null files = writeFile tempfilename templatestring
| otherwise = mapM_ (flip writeFile templatestring) files
where
templatestring = constructTemplateString opt_count opt_headers
count_headers = getCount opts
opt_headers = fst count_headers
opt_count = snd count_headers
getCount :: [TemplateOpts] -> ([TemplateOpts], TemplateOpts)
getCount = fmap head . swap . partition helper
where
helper :: TemplateOpts -> Bool
helper (Count _) = True
helper _ = False
constructTemplateString :: TemplateOpts -> [TemplateOpts] -> String
constructTemplateString (Count c) = intercalate "\n\n"
. foldr helper []
. concat
. replicate c
. sort
where
{- TODO: make total-}
helper :: TemplateOpts -> [String] -> [String]
helper H1 acc = h1:acc
helper H2 acc = h2:acc
|
ajjaic/dokuwiki-template
|
src/CmdLineProcessing.hs
|
bsd-3-clause
| 2,079 | 0 | 17 | 610 | 614 | 324 | 290 | 48 | 2 |
module Parsers.Tests where
import qualified Types.BotTypes as BT
import Data.List (nub)
import qualified Data.Text.Lazy as Text
import Parsers.IRCMessageParser (parseMessage)
import qualified Test.Tasty as T
import qualified Test.Tasty.QuickCheck as T
import Text.ParserCombinators.ReadP (readP_to_S)
tests :: T.TestTree
tests = T.testGroup "IRC Message Parser Tests"
[ qcTests
]
qcTests :: T.TestTree
qcTests = T.testGroup "QuickCheck Tests"
[ T.testProperty "alwaysTerminate" alwaysTerminate
]
alwaysTerminate :: String -> Bool
alwaysTerminate s = case parseMessage (Text.pack s) of
_ -> True
{-parseUser1 :: Assertion-}
{-parseUser1 = readP_to_S parseUser str @=? [("~fluttersh", "@1.1.1.1")]-}
{-where str = "[email protected]"-}
{-parseUser2 :: Assertion-}
{-parseUser2 = readP_to_S parseUser str @=? [("fluttershy", " PRIVMSG (...)")]-}
{-where str = "fluttershy PRIVMSG (...)"-}
{-parseUser3 :: Assertion-}
{-parseUser3 = readP_to_S parseUser str @=? []-}
{-where str = "@1.1.1.1"-}
{-parseNickname1 :: Assertion-}
{-parseNickname1 = assertBool "" $ ("bus000_", "!~fluttersh@") `elem`-}
{-readP_to_S parseNickname str-}
{-where str = "bus000_!~fluttersh@"-}
{-parseNickname2 :: Assertion-}
{-parseNickname2 = assertBool "" (not $ ("123456789", "") `elem`-}
{-readP_to_S parseNickname str)-}
{-where str = "123456789"-}
{-parseIP6addr1 :: Assertion-}
{-parseIP6addr1 = readP_to_S parseIP6addr str @=?-}
{-[("2001:DB8:A0B:12F0:0:0:0:1", "")]-}
{-where str = "2001:DB8:A0B:12F0:0:0:0:1"-}
{-parseIP6addr2 :: Assertion-}
{-parseIP6addr2 = readP_to_S parseIP6addr str @=? []-}
{-where str = "2001:DB8:A0B:12F0:0:0:1"-}
{-parseIP6addr3 :: Assertion-}
{-parseIP6addr3 = readP_to_S parseIP6addr str @=?-}
{-[("2001:DB8:A0B:12F0:0:0:0:1", " PRIVMSG (...)")]-}
{-where str = "2001:DB8:A0B:12F0:0:0:0:1 PRIVMSG (...)"-}
{-parseIP6addr4 :: Assertion-}
{-parseIP6addr4 = readP_to_S parseIP6addr str @=?-}
{-[("0:0:0:0:0:0:127.0.0.1", "")]-}
{-where str = "0:0:0:0:0:0:127.0.0.1"-}
{-parseIP6addr5 :: Assertion-}
{-parseIP6addr5 = readP_to_S parseIP6addr str @=? [("1:2:3:4:5:6:7:8", "")]-}
{-where str = "1:2:3:4:5:6:7:8"-}
{-parseIP4addr1 :: Assertion-}
{-parseIP4addr1 = readP_to_S parseIP4addr str @=? [("192.168.1.6", " PRIVMSG ..")]-}
{-where str = "192.168.1.6 PRIVMSG .."-}
{-parseIP4addr2 :: Assertion-}
{-parseIP4addr2 = readP_to_S parseIP4addr str @=? [("192.168.1.6", ".123")]-}
{-where str = "192.168.1.6.123"-}
{-parseHostaddr1 :: Assertion-}
{-parseHostaddr1 = readP_to_S parseHostaddr str @=?-}
{-[("0:0:0:0:0:0:127.0.0.1", "")]-}
{-where str = "0:0:0:0:0:0:127.0.0.1"-}
{-parseHostaddr2 :: Assertion-}
{-parseHostaddr2 = readP_to_S parseHostaddr str @=? []-}
{-where str = "0:0:0:0:0:127.0.0.1"-}
{-parseShortname1 :: Assertion-}
{-parseShortname1 = assertBool "" $ ("bus000-asdf", " PRIV") `elem`-}
{-readP_to_S parseShortname str-}
{-where str = "bus000-asdf PRIV"-}
{-parseShortname2 :: Assertion-}
{-parseShortname2 = assertBool "" $ ("wolfe", ".freenode.net NOTICE *:123") `elem`-}
{-readP_to_S parseShortname str-}
{-where str = "wolfe.freenode.net NOTICE *:123"-}
{-parseShortname3 :: Assertion-}
{-parseShortname3 = [("a", "")] @=? readP_to_S parseShortname "a"-}
{-parseHostname1 :: Assertion-}
{-parseHostname1 = assertBool "" $ ("wolfe.freenode.net", " NOTICE *:123") `elem`-}
{-readP_to_S parseHostname str-}
{-where str = "wolfe.freenode.net NOTICE *:123"-}
{-parseHostname2 :: Assertion-}
{-parseHostname2 = assertBool "" $ ("wolfe.free-node.net", " NOTICE *:123") `elem`-}
{-readP_to_S parseHostname str-}
{-where str = "wolfe.free-node.net NOTICE *:123"-}
{-parseHostname3 :: Assertion-}
{-parseHostname3 = readP_to_S parseHostname str @=? []-}
{-where str = ".wolfe.free-node.net NOTICE *:123"-}
{-parseHost1 :: Assertion-}
{-parseHost1 = assertBool "" $ ("wolfe.freenode.net", " NOTICE *:123") `elem`-}
{-readP_to_S parseHost str-}
{-where str = "wolfe.freenode.net NOTICE *:123"-}
{-parseHost2 :: Assertion-}
{-parseHost2 = assertBool "" $ ("0:0:0:0:0:0:127.0.0.1", "") `elem`-}
{-readP_to_S parseHost str-}
{-where str = "0:0:0:0:0:0:127.0.0.1"-}
{-parseNicknamePrefix1 :: Assertion-}
{-parseNicknamePrefix1 = assertBool "" $ (expected, rest) `elem` output-}
{-where-}
{-str = "[email protected] PRIVMSG"-}
{-expected = BT.NicknamePrefix-}
{-(BT.IRCUser "bus000_" (Just "~fluttersh") (Just "1.1.1.1"))-}
{-rest = " PRIVMSG"-}
{-output = readP_to_S parseNicknamePrefix str-}
{-parseNicknamePrefix2 :: Assertion-}
{-parseNicknamePrefix2 = assertBool "" $ (expected, rest) `elem` output-}
{-where-}
{-str = "bus000_!~fluttersh PRIVMSG"-}
{-expected = BT.NicknamePrefix-}
{-(BT.IRCUser "bus000_" (Just "~fluttersh") Nothing)-}
{-rest = " PRIVMSG"-}
{-output = readP_to_S parseNicknamePrefix str-}
{-parseNicknamePrefix3 :: Assertion-}
{-parseNicknamePrefix3 = assertBool "" $ (expected, rest) `elem` output-}
{-where-}
{-str = "bus000_ PRIVMSG"-}
{-expected = BT.NicknamePrefix-}
{-(BT.IRCUser "bus000_" Nothing Nothing)-}
{-rest = " PRIVMSG"-}
{-output = readP_to_S parseNicknamePrefix str-}
{-parseServername1 :: Assertion-}
{-parseServername1 = assertBool "" $ (expected, rest) `elem` output-}
{-where-}
{-str = "wolfe.freenode.net NOTICE * :trailing"-}
{-expected = BT.ServernamePrefix "wolfe.freenode.net"-}
{-rest = " NOTICE * :trailing"-}
{-output = readP_to_S parseServername str-}
{-parseServername2 :: Assertion-}
{-parseServername2 = assertBool "" $ (expected, rest) `elem` output-}
{-where-}
{-str = "wolfe.free-node.net NOTICE * :trailing"-}
{-expected = BT.ServernamePrefix "wolfe.free-node.net"-}
{-rest = " NOTICE * :trailing"-}
{-output = readP_to_S parseServername str-}
{-parseTrailing1 :: Assertion-}
{-parseTrailing1 = assertBool "" $ (expected, rest) `elem` output-}
{-where-}
{-str = ": this is a trailing message \r\n"-}
{-expected = ": this is a trailing message "-}
{-rest = "\r\n"-}
{-output = readP_to_S parseTrailing str-}
{-parseMiddle1 :: Assertion-}
{-parseMiddle1 = assertBool "" $ (expected, rest) `elem` output-}
{-where-}
{-str = "parameter123 :trailing message\r\n"-}
{-expected = "parameter123"-}
{-rest = " :trailing message\r\n"-}
{-output = readP_to_S parseMiddle str-}
{-parseMiddle2 :: Assertion-}
{-parseMiddle2 = [] @=? output-}
{-where-}
{-str = ":parameter123 :trailing message\r\n"-}
{-output = readP_to_S parseMiddle str-}
{-parseParams1 :: Assertion-}
{-parseParams1 = assertBool "" $ (expected, rest) `elem` output-}
{-where-}
{-str = " parameter1~ parameter2! parameter3` parameter4: :trailing mes\r\n"-}
{-expected = (["parameter1~", "parameter2!", "parameter3`", "parameter4:"],-}
{-Just "trailing mes")-}
{-rest = "\r\n"-}
{-output = readP_to_S parseParams str-}
{-parseParams2 :: Assertion-}
{-parseParams2 = [(([], Nothing), str)] @=? output-}
{-where-}
{-str = "param :trailing\r\n"-}
{-output = readP_to_S parseParams str-}
{-parseParams3 :: Assertion-}
{-parseParams3 = assertBool "" $ (expected, rest) `elem` output-}
{-where-}
{-str = " 1 2 3 4 5 6 7 8 9 10 11 12 13 14 trailing message\r\n"-}
{-expected = (["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",-}
{-"13", "14"], Just "trailing message")-}
{-rest = "\r\n"-}
{-output = readP_to_S parseParams str-}
{-parseParams4 :: Assertion-}
{-parseParams4 = assertBool "" $ (expected, rest) `elem` output-}
{-where-}
{-str = " 1 2 3 4 5 6 7 8 9 10 11 12 13 14 :trailing message\r\n"-}
{-expected = (["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",-}
{-"13", "14"], Just "trailing message")-}
{-rest = "\r\n"-}
{-output = readP_to_S parseParams str-}
{-parseCommand1 :: Assertion-}
{-parseCommand1 = [(expected, rest)] @=? output-}
{-where-}
{-str = "PRIVMSG #dikufags :this is a message\r\n"-}
{-expected = BT.PRIVMSG-}
{-rest = " #dikufags :this is a message\r\n"-}
{-output = readP_to_S parseCommand str-}
{-parseCommand2 :: Assertion-}
{-parseCommand2 = [(expected, rest)] @=? output-}
{-where-}
{-str = "NOTICE #dikufags :this is a message\r\n"-}
{-expected = BT.NOTICE-}
{-rest = " #dikufags :this is a message\r\n"-}
{-output = readP_to_S parseCommand str-}
{-parseCommand3 :: Assertion-}
{-parseCommand3 = [] @=? output-}
{-where-}
{-str = "NOTCOMMAND #dikufags :this is a message\r\n"-}
{-output = readP_to_S parseCommand str-}
{-parseCommand4 :: Assertion-}
{-parseCommand4 = [(expected, rest)] @=? output-}
{-where-}
{-str = "004 #dikufags :this is a message\r\n"-}
{-expected = BT.NUMCOM 4-}
{-rest = " #dikufags :this is a message\r\n"-}
{-output = readP_to_S parseCommand str-}
{-parseCommand5 :: Assertion-}
{-parseCommand5 = [] @=? output-}
{-where-}
{-str = "04 #dikufags :this is a message\r\n"-}
{-output = readP_to_S parseCommand str-}
{-parseMessage1 :: Assertion-}
{-parseMessage1 = [(expected, "")] @=? nub output-}
{-where-}
{-str = ":[email protected] PRIVMSG #dikufags_test :my message\r\n"-}
{-expected = BT.IRCMessage prefix command params trailing-}
{-prefix = Just $ BT.NicknamePrefix-}
{-(BT.IRCUser "bus000_" (Just "~fluttersh") (Just "1.1.1.1"))-}
{-command = BT.PRIVMSG-}
{-params = ["#dikufags_test"]-}
{-trailing = Just "my message"-}
{-output = readP_to_S parseMessage str-}
{-parseMessage2 :: Assertion-}
{-parseMessage2 = [(expected, "")] @=? nub output-}
{-where-}
{-str = "PING :wolfe.freenode.net\r\n"-}
{-expected = BT.IRCMessage prefix command params trailing-}
{-prefix = Nothing-}
{-command = BT.PING-}
{-params = []-}
{-trailing = Just "wolfe.freenode.net"-}
{-output = readP_to_S parseMessage str-}
{-parseMessage3 :: Assertion-}
{-parseMessage3 = [(expected, "")] @=? nub output-}
{-where-}
{-str = ":wolfe.freenode.net NOTICE * :*** Looking up your hostname...\r\n"-}
{-expected = BT.IRCMessage prefix command params trailing-}
{-prefix = Just $ BT.ServernamePrefix "wolfe.freenode.net"-}
{-command = BT.NOTICE-}
{-params = ["*"]-}
{-trailing = Just "*** Looking up your hostname..."-}
{-output = readP_to_S parseMessage str-}
{-parseMessage4 :: Assertion-}
{-parseMessage4 = [(expected, "")] @=? nub output-}
{-where-}
{-str = ":wolfe.freenode.net 252 dikunttest123 28 :IRC Operators online\r\n"-}
{-expected = BT.IRCMessage prefix command params trailing-}
{-prefix = Just $ BT.ServernamePrefix "wolfe.freenode.net"-}
{-command = BT.NUMCOM 252-}
{-params = ["dikunttest123", "28"]-}
{-trailing = Just "IRC Operators online"-}
{-output = readP_to_S parseMessage str-}
{-parseMessage5 :: Assertion-}
{-parseMessage5 = [] @=? nub output-}
{-where-}
{-str = ":wolfe.freenode.net 252 dikunttest123 28 :IRC Operators online"-}
{-output = readP_to_S parseMessage str-}
{-parseMessage6 :: Assertion-}
{-parseMessage6 = [(expected, "")] @=? nub output-}
{-where-}
{-str = ":[email protected] PRIVMSG #dikufags :Hm\r\n"-}
{-expected = BT.IRCMessage prefix command params trailing-}
{-prefix = Just $ BT.nicknamePrefix "_Hephaestus" (Just "~Ghost")-}
{-(Just "152.115.87.26")-}
{-command = BT.PRIVMSG-}
{-params = ["#dikufags"]-}
{-trailing = Just "Hm"-}
{-output = readP_to_S parseMessage str-}
{-parseMessage7 :: Assertion-}
{-parseMessage7 = [(expected, "")] @=? nub output-}
{-where-}
{-str = ":wilhelm.freenode.net NOTICE * :*** Looking up your hostname...\r\n"-}
{-expected = BT.IRCMessage prefix command params trailing-}
{-prefix = Just $ BT.ServernamePrefix "wilhelm.freenode.net"-}
{-command = BT.NOTICE-}
{-params = ["*"]-}
{-trailing = Just "*** Looking up your hostname..."-}
{-output = readP_to_S parseMessage str-}
{-parseLayer2_1 :: Assertion-}
{-parseLayer2_1 = Just result @=? parseServerMessage ircMessage-}
{-where-}
{-result = BT.ServerNoticeServer "wilhelm.freenode.net" "*"-}
{-"*** Looking up your hostname..."-}
{-ircMessage = BT.IRCMessage prefix command params trailing-}
{-prefix = Just $ BT.ServernamePrefix "wilhelm.freenode.net"-}
{-command = BT.NOTICE-}
{-params = ["*"]-}
{-trailing = Just "*** Looking up your hostname..."-}
|
bus000/Dikunt
|
test/Parsers/Tests.hs
|
bsd-3-clause
| 12,523 | 0 | 9 | 2,131 | 431 | 366 | 65 | 17 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_HADDOCK show-extensions #-}
{-|
Module : $Header$
Copyright : (c) 2015 Swinburne Software Innovation Lab
License : BSD3
Maintainer : Rhys Adams <[email protected]>
Stability : unstable
Portability : portable
API executable entry point.
-}
module Main where
import Eclogues.API (AbsFile)
import Eclogues.APIElection (LeadershipError (..), ManagedZK, ZKURI, whileLeader)
import Eclogues.AppConfig (AppConfig (AppConfig))
import qualified Eclogues.AppConfig as Config
import qualified Eclogues.Job as Job
import Eclogues.Monitoring.Monitor (followAegleMaster)
import qualified Eclogues.Persist as Persist
import Eclogues.Scheduling.AuroraZookeeper (followAuroraMaster)
import Eclogues.Scheduling.Run (
runScheduleCommand, schedulerJobUI, requireSchedConf)
import qualified Eclogues.State.Monad as ES
import Eclogues.State.Types (AppState)
import Eclogues.Threads.Update (loadSchedulerState, monitorCluster)
import Eclogues.Threads.Server (serve)
import Eclogues.Util (AbsDir (getDir), readJSON, orError)
import Control.Applicative ((<|>))
import Control.Concurrent (threadDelay)
import qualified Control.Concurrent.AdvSTM as STM
import Control.Concurrent.AdvSTM.TChan (newTChanIO, writeTChan, readTChan)
import Control.Concurrent.AdvSTM.TVar (newTVarIO)
import Control.Concurrent.Async (Concurrently (..), runConcurrently)
import Control.Concurrent.Lock (Lock)
import qualified Control.Concurrent.Lock as Lock
import Control.Exception (throwIO)
import Control.Lens ((^.))
import Control.Monad (forever)
import Control.Monad.Trans (lift)
import Control.Monad.Except (runExceptT)
import Data.Aeson.TH (deriveFromJSON, defaultOptions)
import Data.Default.Generics (def)
import Data.Metrology ((%), (#))
import Data.Metrology.SI (Second (Second), micro)
import qualified Data.Text as T
import Data.Time.Clock.POSIX (getPOSIXTime)
import Data.Word (Word16)
import Database.Zookeeper (ZKError)
import Network.URI (URI (uriPath), escapeURIString, isUnescapedInURI)
import Path (toFilePath)
import Path.IO (createDirectoryIfMissing)
import System.IO (hPutStrLn, stderr)
import System.Random (mkStdGen, setStdGen)
-- | User-supplied API configuration.
data ApiConfig = ApiConfig { jobsDir :: AbsDir
, zookeeperHosts :: ZKURI
, bindAddress :: String
, bindPort :: Word16
, subexecutorUser :: T.Text
, outputUrlPrefix :: URI }
$(deriveFromJSON defaultOptions ''ApiConfig)
main :: IO ()
main = do
seedStdGen
apiConf <- orError =<< readJSON "/etc/xdg/eclogues/api.json"
let (ApiConfig _ zkUri host port _ _) = apiConf
-- Used to prevent multiple web server threads from running at the same
-- time. This can happen if the web thread doesn't finish dying between
-- losing and regaining ZK election master status.
webLock <- Lock.new
res <- runExceptT . whileLeader zkUri host port $ withZK apiConf webLock
case res of
Left (LZKError e) ->
error $ "Zookeeper coordination error: " ++ show e
Left (ActionException ex) -> throwIO ex
Left ZookeeperInvariantViolated -> error "ZookeeperInvariantViolated!"
Left LeadershipLost -> error "impossibru!"
Right e ->
error $ "Aurora ZK lookup error: " ++ show e
withZK :: ApiConfig -> Lock -> ManagedZK -> IO ZKError
withZK apiConf webLock zk = do
let jdir = getDir $ jobsDir apiConf
schedV <- newTChanIO -- Scheduler action channel
(followAuroraFailure, getAurora) <- followAuroraMaster zk
(followAegleFailure, getAegle) <- followAegleMaster zk
createDirectoryIfMissing False jdir
Persist.withPersistDir jdir $ \pctx' -> do
let conf = AppConfig jdir getAurora schedV pctx' jobURI outURI user getAegle
user = subexecutorUser apiConf
jobURI = schedulerJobUI $ T.unpack user
outURI = mkOutputURI $ outputUrlPrefix apiConf
host = bindAddress apiConf
port = fromIntegral $ bindPort apiConf
zkErrors = Concurrently followAuroraFailure
<|> Concurrently followAegleFailure
lift $ withPersist host port conf webLock zkErrors
withPersist :: String -> Int -> AppConfig -> Lock -> Concurrently ZKError -> IO ZKError
withPersist host port conf webLock zkErrors = do
st <- loadFromDB conf
stateV <- newTVarIO st
clusterV <- newTVarIO Nothing
let web = Lock.with webLock $ serve (pure ()) host port conf stateV clusterV
updater = forever $ do
loadSchedulerState conf stateV
threadDelay . floor $ ((1 % Second) # micro Second :: Double)
monitor = forever $ do
monitorCluster (Config.monitorUrl conf) stateV clusterV
threadDelay . floor $ ((30 % Second) # micro Second :: Double)
-- TODO: catch run error and reschedule
enacter = forever . STM.atomically $ runSingleCommand conf
-- Configure threads ignoring monitoring if the relevant configuration is not provided
hPutStrLn stderr $ "Starting server on " ++ host ++ ':':show port
runConcurrently $ Concurrently (const (error "web failed") <$> web)
<|> Concurrently updater
<|> Concurrently enacter
<|> Concurrently monitor
<|> zkErrors
-- | Append the job name and file path to the path of the job output server URI.
mkOutputURI :: URI -> Job.Name -> AbsFile -> URI
mkOutputURI pf name path = pf { uriPath = uriPath pf ++ name' ++ escapedPath }
where
escapedPath = escapeURIString isUnescapedInURI $ toFilePath path
name' = T.unpack $ Job.nameText name
loadFromDB :: AppConfig -> IO AppState
loadFromDB conf = fmap ((^. ES.appState) . snd) . ES.runStateTS def $ do
(js, cmds) <- Persist.atomically (Config.pctx conf) $
(,) <$> Persist.allJobs <*> Persist.allIntents
ES.loadJobs js
lift . STM.atomically $ mapM_ (writeTChan $ Config.schedChan conf) cmds
-- | Read a single scheduler command from 'Config.schedChan' and send it to
-- the scheduler, waiting if it is unavailable.
runSingleCommand :: AppConfig -> STM.AdvSTM ()
runSingleCommand conf = do
cmd <- readTChan $ Config.schedChan conf
schedConf <- requireSchedConf conf
STM.onCommit . throwExc $ do
runScheduleCommand schedConf cmd
Persist.atomically (Config.pctx conf) $ Persist.deleteIntent cmd
where
throwExc act = either throwIO pure =<< runExceptT act
-- | Seed the PRNG with the current time.
seedStdGen :: IO ()
seedStdGen = do
curTime <- getPOSIXTime
-- Unlikely to start twice within a millisecond
let pico = floor (curTime * 1e3) :: Int
setStdGen $ mkStdGen pico
|
futufeld/eclogues
|
eclogues-impl/app/api/Main.hs
|
bsd-3-clause
| 6,900 | 0 | 17 | 1,545 | 1,690 | 905 | 785 | 126 | 5 |
{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.Win32.Com.Server.ConnectionPoint
-- Copyright : (c) Sigbjorn Finne <[email protected]> 1998-99
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Generic implementation of COM connectable objects \/ connection points,
-- server side.
--
-- The connection between this framework impl. and the Haskell object
-- responsible for firing events on the registered sinks, is still
-- up in the air. The current arrangement is for the object and a
-- particular connection point to share an IORef holding the current
-- set of registered sinks. The object will then fire the events
-- by using the (generated) stubs for that particular event interface.
--
-- Probably want to abstract away the details of how sink broadcasting
-- is done.
--
-----------------------------------------------------------------------------
module System.Win32.Com.Server.ConnectionPoint
(
mkConnectionContainer
) where
import System.Win32.Com.Server
import System.Win32.Com.Automation.Connection ( iidIConnectionPointContainer, iidIConnectionPoint,
IConnectionPointContainer, IConnectionPoint,
iidIEnumConnections, iidIEnumConnectionPoints
)
import Prelude hiding (catch)
import System.Win32.Com
import System.Win32.Com.HDirect.HDirect ( writeWord32, Ptr, sizeofPtr )
import System.Win32.Com.Server.EnumInterface ( mkEnumInterface )
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.Storable
import System.IO.Unsafe ( unsafePerformIO )
import System.IO ( fixIO )
import Data.IORef ( IORef, newIORef, readIORef, writeIORef )
import Data.Word
import Data.Int
import System.Win32.Com.Exception
import Control.Exception (catch, SomeException(..))
type ThisPtr = Ptr (IUnknown ())
mkConnectionContainer :: [(IID (IUnknown ()), IORef [(Word32, IUnknown ())])]
-> IO (IConnectionPointContainer ())
mkConnectionContainer ls = fixIO $ \ ip -> do
let ils = unsafePerformIO (mapM (mkConnection ip) ls)
addrOf_eCP <- export_enumCP (enumConnectionPoints (map snd ils))
addrOf_fCP <- export_fCP (findConnectionPoint ils)
vtbl <- createComVTable [ addrOf_eCP, addrOf_fCP ]
createComInstance "" () (return ())
[mkIface iidIConnectionPointContainer vtbl]
iidIConnectionPointContainer
mkConnection :: IConnectionPointContainer ()
-> (IID (IUnknown ()), IORef [(Word32, IUnknown ())])
-> IO (IID (IUnknown ()), IConnectionPoint ())
mkConnection ip (iid, regd_sinks) = do
vtbl <- mkConnectionPointVTBL ip iid regd_sinks
ip <- createComInstance "" () (return ())
[ mkIface iidIConnectionPoint vtbl ]
iidIConnectionPoint
return (iid, ip)
mkConnectionPointVTBL :: IConnectionPointContainer ()
-> IID (IUnknown iid)
-> IORef [(Word32, IUnknown ())]
-> IO (ComVTable (IConnectionPoint a) objState)
mkConnectionPointVTBL ip iid sinks = do
addrOf_gi <- export_gi (getConnectionInterface iid)
addrOf_gcpc <- export_gcpc (getConnectionPointContainer ip)
cookie_ref <- newIORef (0::Word32)
addrOf_adv <- export_adv (advise sinks cookie_ref iid)
addrOf_unadv <- export_unadv (unadvise sinks)
addrOf_eC <- export_eCP (enumConnections sinks)
createComVTable
[ addrOf_gi , addrOf_gcpc , addrOf_adv, addrOf_unadv, addrOf_eC ]
getConnectionInterface :: IID iid
-> ThisPtr
-> Ptr GUID
-> IO HRESULT
getConnectionInterface iid _ piid
| piid == nullPtr = return e_POINTER
| otherwise = do
writeGUID piid (iidToGUID iid)
return s_OK
foreign import stdcall "wrapper"
export_gi :: (ThisPtr -> Ptr GUID -> IO HRESULT) -> IO (Ptr ())
getConnectionPointContainer :: IConnectionPointContainer ()
-> ThisPtr
-> Ptr (Ptr (IUnknown b))
-> IO HRESULT
getConnectionPointContainer ip _ pip = do
writeIUnknown True{-addRef-} pip ip
return s_OK
foreign import stdcall "wrapper"
export_gcpc :: (ThisPtr -> Ptr (Ptr (IUnknown b)) -> IO HRESULT) -> IO (Ptr ())
advise :: IORef [(Word32,IUnknown ())]
-> IORef Word32
-> IID (IUnknown iid)
-> ThisPtr
-> PrimIP ()
-> Ptr Word32
-> IO HRESULT
advise sinks cookie_ref iid this pUnkSink pdwCookie = do
ls <- readIORef sinks
cookie <- readIORef cookie_ref
ip <- unmarshallIUnknown False pUnkSink
catch (do
ip2 <- ip # queryInterface iid
if nullPtr == pdwCookie then
return e_POINTER
else do
writeIORef cookie_ref (cookie+1)
writeIORef sinks ((cookie,castIface ip2):ls)
writeWord32 pdwCookie cookie
return s_OK
)(\(e::SomeException) -> return cONNECT_E_CANNOTCONNECT)
foreign import stdcall "wrapper"
export_adv :: (ThisPtr -> PrimIP () -> Ptr Word32 -> IO HRESULT) -> IO (Ptr ())
unadvise :: IORef [(Word32,IUnknown ())]
-> ThisPtr
-> Word32
-> IO HRESULT
unadvise sinks this dwCookie = do
ls <- readIORef sinks
case break ((==dwCookie).fst) ls of
(ls,[]) -> return cONNECT_E_NOCONNECTION
(ls, _:rs) -> do
-- just drop the interface pointer and let
-- the GC release it.
writeIORef sinks (ls++rs)
return s_OK
foreign import stdcall "wrapper"
export_unadv :: (ThisPtr -> Word32 -> IO HRESULT) -> IO (Ptr ())
enumConnections :: IORef [(Word32,IUnknown ())]
-> ThisPtr
-> Ptr (Ptr (IUnknown a))
-> IO HRESULT
enumConnections sinks this ppCP
| ppCP == nullPtr = return e_POINTER
| otherwise = do
ls <- readIORef sinks
vtbl <- mkEnumInterface (map snd ls) (fromIntegral sizeofPtr) (writeIUnknown True)
ip <- createComInstance "" () (return ())
[mkIface iidIEnumConnections vtbl]
iidIEnumConnections
writeIUnknown True ppCP ip
return s_OK
foreign import stdcall "wrapper"
export_enumCP :: (ThisPtr -> Ptr (Ptr (IUnknown b)) -> IO HRESULT) -> IO (Ptr ())
enumConnectionPoints :: [IConnectionPoint ()]
-> ThisPtr
-> Ptr (Ptr (IUnknown b))
-> IO HRESULT
enumConnectionPoints ls this ppEnum
| ppEnum == nullPtr = return e_POINTER
| otherwise = do
vtbl <- mkEnumInterface ls (fromIntegral sizeofPtr) (writeIUnknown True)
ip <- createComInstance "" () (return ())
[mkIface iidIEnumConnectionPoints vtbl]
iidIEnumConnectionPoints
writeIUnknown True ppEnum ip
return s_OK
foreign import stdcall "wrapper"
export_eCP :: (ThisPtr -> Ptr (Ptr (IUnknown b)) -> IO HRESULT) -> IO (Ptr ())
findConnectionPoint :: [(IID (IUnknown ()), IConnectionPoint ())]
-> ThisPtr
-> Ptr GUID
-> Ptr (Ptr (IUnknown ()))
-> IO HRESULT
findConnectionPoint ls this riid ppCP
| ppCP == nullPtr = return e_POINTER
| otherwise = do
guid <- unmarshallGUID False riid
let iid = guidToIID guid
case (lookup iid ls) of
Nothing -> do
poke ppCP nullPtr
return cONNECT_E_NOCONNECTION
Just i -> do
writeIUnknown True ppCP i
return s_OK
foreign import stdcall "wrapper"
export_fCP :: (ThisPtr -> Ptr GUID -> Ptr (Ptr (IUnknown b)) -> IO HRESULT) -> IO (Ptr ())
cONNECT_E_NOCONNECTION :: HRESULT
cONNECT_E_NOCONNECTION = 0x80040200
cONNECT_E_ADVISELIMIT :: HRESULT
cONNECT_E_ADVISELIMIT = 0x80040201
cONNECT_E_CANNOTCONNECT :: HRESULT
cONNECT_E_CANNOTCONNECT = 0x80040202
cONNECT_E_OVERRIDDEN :: HRESULT
cONNECT_E_OVERRIDDEN = 0x80040203
|
jjinkou2/ComForGHC7.4
|
System/Win32/Com/Server/ConnectionPoint.hs
|
bsd-3-clause
| 7,964 | 64 | 19 | 1,960 | 2,245 | 1,136 | 1,109 | 169 | 2 |
-----------------------------------------------------------------------------
--
-- Module : Control.Monad.Supervisor
-- Copyright :
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability :
-- Portability :
--
-- | A supervisor monad that explore the execution tree of an internal monad and define extra behaviours thanks to flexible instance definitions for each particular purpose.
-- It can inject new behaviours for backtracking, trace generation, testing, transaction rollbacks etc
-- The supervisor monad is used in the package MFlow to control the routing, tracing, state management, back button management and navigation in general
--
-----------------------------------------------------------------------------
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances,
UndecidableInstances, DeriveDataTypeable,
FunctionalDependencies #-}
module Control.Monad.Supervisor where
import Control.Monad.Trans
import Control.Monad.State
import Data.Typeable
import Debug.Trace
(!>)= flip trace
--class Monad m => MonadState1 s m where
-- get :: m s
-- put :: s -> m ()
-- | The internal computation can be reexecuted, proceed forward or backward
data Control a = Control a | Forward a | Backward deriving (Typeable, Read, Show)
-- | The supervisor add a Control wrapper that is interpreted by the monad instance
newtype Sup s m a = Sup { runSup :: m (Control a ) }
-- | The supervise class add two general modifiers that can be applied:
class MonadState s m => Supervise s m where
supBack :: s -> m () -- ^ Called before initiating backtracking in a control point
-- When the computation goes back, by default
-- the state is kepth. This procedure can change
-- that behaviour. The state passed is the one before the
-- computation was executed.
supBack = const $ return ()
supervise :: s -> m (Control a) -> m (Control a) -- ^ When the conputation has been executed
-- this method is an opportunity for modifying the result
-- By default: supervise _= id
supervise= const $ id
-- | Flag the computation that executes @breturn@ as a control point.
--
-- When the computation is going back, it will be re-executed (see the monad definition)
breturn :: Monad m => a -> Sup s m a
breturn = Sup . return . Control
--instance MonadState () IO where
-- get= return()
-- put= const $ return ()
--instance MonadState s m => Supervise s m
-- | The Supervisor Monad is in essence an Identity monad transformer when executing Forward.
instance Supervise s m => Monad (Sup s m) where
fail _ = Sup . return $ Backward
return x = Sup . return $ Forward x
x >>= f = Sup $ loop
where
loop = do
s <- get
-- execution as usual if supervise== id
v <- supervise s $ runSup x
case v of
-- a normal execution if supervise== id
Forward y -> supervise s $ runSup (f y)
-- Backward was returned, stop the branch of execution and propagate it back
Backward -> return Backward
-- the computaton x was a control point. if the branch of execution goes Backward
-- then x will be reexecuted. supBack will control the state backtracking, how much of
-- the current state we want to keep and how much we want to backtrack
Control y -> do
z <- supervise s $ runSup (f y)
case z of
Backward -> supBack s >> loop -- re-execute x
other -> return other
instance MonadTrans (Sup s) where
lift f = Sup $ f >>= return . Forward
instance (MonadIO m,Supervise s m)=> MonadIO (Sup s m) where
liftIO iof= Sup $ liftIO iof >>= return . Forward
instance Supervise s m => MonadState s (Sup s m) where
get= lift get
put = lift . put
|
agocorona/control-monad-supervisor
|
Control/Monad/Supervisor.hs
|
bsd-3-clause
| 4,141 | 0 | 19 | 1,248 | 608 | 328 | 280 | 40 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.MapBufferAlignment
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/ARB/map_buffer_alignment.txt ARB_map_buffer_alignment> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.MapBufferAlignment (
-- * Enums
gl_MIN_MAP_BUFFER_ALIGNMENT
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/ARB/MapBufferAlignment.hs
|
bsd-3-clause
| 682 | 0 | 4 | 78 | 37 | 31 | 6 | 3 | 0 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.EXT.TextureMirrorClamp
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.EXT.TextureMirrorClamp (
-- * Extension Support
glGetEXTTextureMirrorClamp,
gl_EXT_texture_mirror_clamp,
-- * Enums
pattern GL_MIRROR_CLAMP_EXT,
pattern GL_MIRROR_CLAMP_TO_BORDER_EXT,
pattern GL_MIRROR_CLAMP_TO_EDGE_EXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/EXT/TextureMirrorClamp.hs
|
bsd-3-clause
| 751 | 0 | 5 | 99 | 57 | 42 | 15 | 9 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module ConfigParser (MachineConfig(..), StartConfig(..), Rules, readConfig) where
import Data.ByteString (ByteString)
import Data.Yaml (FromJSON(..), (.:))
import qualified Data.Yaml as Yaml
import Machine (Meta(..))
readConfig :: ByteString -> Either String MachineConfig
readConfig = Yaml.decodeEither
data MachineConfig = MachineConfig { meta :: Meta, start :: StartConfig, rules :: Rules }
deriving (Eq, Show)
instance FromJSON MachineConfig where
parseJSON (Yaml.Object o) = MachineConfig <$> o .: "meta" <*> o .: "start" <*> o .: "rules"
instance FromJSON Meta where
parseJSON (Yaml.Object o) = Meta <$> o .: "noActionSymbol"
<*> o .: "anySymbol"
<*> o .: "emptySymbol"
<*> o .: "emptyTape"
data StartConfig = StartConfig { state :: String, tape :: String }
deriving (Eq, Show)
instance FromJSON StartConfig where
parseJSON (Yaml.Object o) = StartConfig <$> o .: "state" <*> o .: "tape"
type Rules = [String]
|
prSquirrel/turingmachine
|
src/ConfigParser.hs
|
bsd-3-clause
| 1,137 | 0 | 13 | 293 | 321 | 184 | 137 | 23 | 1 |
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE MagicHash, UnboxedTuples, TypeFamilies, DeriveDataTypeable,
MultiParamTypeClasses, FlexibleInstances, NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Exts
-- Copyright : (c) The University of Glasgow 2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- GHC Extensions: this is the Approved Way to get at GHC-specific extensions.
--
-- Note: no other base module should import this module.
-----------------------------------------------------------------------------
module GHC.Exts
(
-- * Representations of some basic types
Int(..),Word(..),Float(..),Double(..),
Char(..),
Ptr(..), FunPtr(..),
-- * The maximum tuple size
maxTupleSize,
-- * Primitive operations
module GHC.Prim,
shiftL#, shiftRL#, iShiftL#, iShiftRA#, iShiftRL#,
uncheckedShiftL64#, uncheckedShiftRL64#,
uncheckedIShiftL64#, uncheckedIShiftRA64#,
isTrue#,
-- * Fusion
build, augment,
-- * Overloaded string literals
IsString(..),
-- * Debugging
breakpoint, breakpointCond,
-- * Ids with special behaviour
lazy, inline, oneShot,
-- * Running 'RealWorld' state transformers
runRW#,
-- * Safe coercions
--
-- | These are available from the /Trustworthy/ module "Data.Coerce" as well
--
-- @since 4.7.0.0
Data.Coerce.coerce, Data.Coerce.Coercible,
-- * Equality
type (~~),
-- * Representation polymorphism
GHC.Prim.TYPE, RuntimeRep(..), VecCount(..), VecElem(..),
-- * Transform comprehensions
Down(..), groupWith, sortWith, the,
-- * Event logging
traceEvent,
-- * SpecConstr annotations
SpecConstrAnnotation(..),
-- * The call stack
currentCallStack,
-- * The Constraint kind
Constraint,
-- * The Any type
Any,
-- * Overloaded lists
IsList(..)
) where
import GHC.Prim hiding ( coerce, TYPE )
import qualified GHC.Prim
import GHC.Base hiding ( coerce )
import GHC.Word
import GHC.Int
import GHC.Ptr
import GHC.Stack
import qualified Data.Coerce
import Data.String
import Data.OldList
import Data.Data
import Data.Ord
import Data.Version ( Version(..), makeVersion )
import qualified Debug.Trace
-- XXX This should really be in Data.Tuple, where the definitions are
maxTupleSize :: Int
maxTupleSize = 62
-- | 'the' ensures that all the elements of the list are identical
-- and then returns that unique element
the :: Eq a => [a] -> a
the (x:xs)
| all (x ==) xs = x
| otherwise = errorWithoutStackTrace "GHC.Exts.the: non-identical elements"
the [] = errorWithoutStackTrace "GHC.Exts.the: empty list"
-- | The 'sortWith' function sorts a list of elements using the
-- user supplied function to project something out of each element
sortWith :: Ord b => (a -> b) -> [a] -> [a]
sortWith f = sortBy (\x y -> compare (f x) (f y))
-- | The 'groupWith' function uses the user supplied function which
-- projects an element out of every list element in order to first sort the
-- input list and then to form groups by equality on these projected elements
{-# INLINE groupWith #-}
groupWith :: Ord b => (a -> b) -> [a] -> [[a]]
groupWith f xs = build (\c n -> groupByFB c n (\x y -> f x == f y) (sortWith f xs))
groupByFB :: ([a] -> lst -> lst) -> lst -> (a -> a -> Bool) -> [a] -> lst
groupByFB c n eq xs0 = groupByFBCore xs0
where groupByFBCore [] = n
groupByFBCore (x:xs) = c (x:ys) (groupByFBCore zs)
where (ys, zs) = span (eq x) xs
-- -----------------------------------------------------------------------------
-- tracing
traceEvent :: String -> IO ()
traceEvent = Debug.Trace.traceEventIO
{-# DEPRECATED traceEvent "Use 'Debug.Trace.traceEvent' or 'Debug.Trace.traceEventIO'" #-} -- deprecated in 7.4
{- **********************************************************************
* *
* SpecConstr annotation *
* *
********************************************************************** -}
-- Annotating a type with NoSpecConstr will make SpecConstr
-- not specialise for arguments of that type.
-- This data type is defined here, rather than in the SpecConstr module
-- itself, so that importing it doesn't force stupidly linking the
-- entire ghc package at runtime
data SpecConstrAnnotation = NoSpecConstr | ForceSpecConstr
deriving( Data, Eq )
{- **********************************************************************
* *
* The IsList class *
* *
********************************************************************** -}
-- | The 'IsList' class and its methods are intended to be used in
-- conjunction with the OverloadedLists extension.
--
-- @since 4.7.0.0
class IsList l where
-- | The 'Item' type function returns the type of items of the structure
-- @l@.
type Item l
-- | The 'fromList' function constructs the structure @l@ from the given
-- list of @Item l@
fromList :: [Item l] -> l
-- | The 'fromListN' function takes the input list's length as a hint. Its
-- behaviour should be equivalent to 'fromList'. The hint can be used to
-- construct the structure @l@ more efficiently compared to 'fromList'. If
-- the given hint does not equal to the input list's length the behaviour of
-- 'fromListN' is not specified.
fromListN :: Int -> [Item l] -> l
fromListN _ = fromList
-- | The 'toList' function extracts a list of @Item l@ from the structure @l@.
-- It should satisfy fromList . toList = id.
toList :: l -> [Item l]
instance IsList [a] where
type (Item [a]) = a
fromList = id
toList = id
-- | @since 4.8.0.0
instance IsList Version where
type (Item Version) = Int
fromList = makeVersion
toList = versionBranch
-- | Be aware that 'fromList . toList = id' only for unfrozen 'CallStack's,
-- since 'toList' removes frozenness information.
--
-- @since 4.9.0.0
instance IsList CallStack where
type (Item CallStack) = (String, SrcLoc)
fromList = fromCallSiteList
toList = getCallStack
|
vikraman/ghc
|
libraries/base/GHC/Exts.hs
|
bsd-3-clause
| 6,740 | 0 | 12 | 1,825 | 998 | 609 | 389 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
-- | Profiles as defined by various sources
module Text.StringPrep.Profiles
( namePrepProfile
, saslPrepProfile
) where
import qualified Data.Set as Set
import Data.Text (Text, singleton)
import Text.StringPrep
-- | Nameprep profile (RFC 3491)
namePrepProfile :: Bool -> StringPrepProfile
namePrepProfile allowUnassigned =
Profile {
maps = [b1,b2],
shouldNormalize = True,
prohibited = (if allowUnassigned then id else (a1:))
[c12,c22,c3,c4,c5,c6,c7,c8,c9],
shouldCheckBidi = True
}
nonAsciiSpaces :: Set.Set Char
nonAsciiSpaces = Set.fromList [ '\x00A0', '\x1680', '\x2000', '\x2001', '\x2002'
, '\x2003', '\x2004', '\x2005', '\x2006', '\x2007'
, '\x2008', '\x2009', '\x200A', '\x200B', '\x202F'
, '\x205F', '\x3000'
]
toSpace :: Char -> Text
toSpace x = if x `Set.member` nonAsciiSpaces then " " else singleton x
-- | SASLPrep profile (RFC 4013). The parameter determines whether unassigned
-- charater are allowed (query behaviour) or disallowed (store)
saslPrepProfile :: Bool -> StringPrepProfile
saslPrepProfile allowUnassigned = Profile
{ maps = [b1, toSpace]
, shouldNormalize = True
, prohibited = (if allowUnassigned then id else (a1:))
[c12, c21, c22, c3, c4, c5, c6, c7, c8, c9]
, shouldCheckBidi = True
}
|
Porges/stringprep-hs
|
Text/StringPrep/Profiles.hs
|
bsd-3-clause
| 1,490 | 12 | 10 | 412 | 356 | 222 | 134 | 29 | 2 |
{-# LANGUAGE GADTs, ScopedTypeVariables, TypeOperators, PolyKinds, DataKinds, PartialTypeSignatures, TypeSynonymInstances, FlexibleInstances, TypeFamilies#-}
module TestSurvey
where
import Data.Typeable
type Prompt = String
data Survey a where
Respond :: Typeable a => Prompt -> (String -> a) -> Survey a
Choose :: Typeable a => Prompt -> Choice a -> Survey a
(:+:) :: Survey b -> Survey c -> Survey (b, c)
Group :: String -> Survey a -> Survey a
data Choice a where
Item :: Typeable a => Prompt -> a -> Choice a
(:|:) :: Choice a -> Choice a -> Choice a
(:||:) :: Choice b -> Choice c -> Choice (Either b c)
(:->:) :: Typeable b => Choice b -> Survey c -> Choice (b, c)
type DepSurvey a b = Survey (Either a (a, b))
type CondSurvey b = DepSurvey Bool b
text :: Prompt -> Survey String
text p = Respond p id
prompt :: Prompt -> Choice Prompt
prompt p = Item p p
prompted :: Prompt -> Survey a -> Choice (Prompt, a)
prompted p = (prompt p :->:)
type Name = String
type Age = Int
name :: Survey Name
name = Respond "Your name" id
age :: Survey Age
age = Respond "Your age" (read :: String -> Int)
person :: Survey (Name, Age)
person = name :+: age
personal :: Survey (Name, Age)
personal = Group "Your personal infromation" person
rating :: Survey Int
rating = Choose "Rating" $ Item "Excellent" 3 :|: Item "Good" 1 :|: Item "Bad" (-1)
voteQuestion :: Survey (Either Char Bool)
voteQuestion = Choose
"Did you vote/who did you vote for?" $
(Item "Candidate A" 'a' :|:
Item "Candidate B" 'b' :|:
Item "Candidate C" 'c')
:||: (Item "Didn’t vote" False :|:
Item "Rather not say" True)
existingCustomer :: CondSurvey String
existingCustomer = Choose "Have you bought anything from us before?" $
Item "No" False :||: (Item "Yes" True :->: Respond "Which?" id)
numSurvey :: CondSurvey Int
numSurvey = Choose "Have you bought anything from us before?" $
Item "No" False :||: (Item "Yes" True :->: Respond "How many?" (read :: String -> Int))
-- getSurvey :: Typeable a => String -> Survey a
--getSurvey "existingCustomer" = existingCustomer
--getSurvey "existingCustomer1" = existingCustomer1
-- getSurvey "age" = age
data Surveys = CondString (CondSurvey String) | CondNum (CondSurvey Int)
getSurvey "existingCustomer" = CondString existingCustomer
getSurvey "numSurvey" = CondNum numSurvey
run = do
l <- getLine
case getSurvey l of
(CondString s) -> do
runSurvey s
return ()
(CondNum s) -> do
runSurvey s
return ()
-- runSurvey :: forall a. Typeable a => Survey a -> IO a
runSurvey :: Survey a -> IO a
runSurvey (Group name sub) = do
putStrLn $ "\n" ++ name
putStrLn $ replicate (length name) '='
runSurvey sub
runSurvey (Respond prompt parser) = do
putStr ""
putStr $ prompt ++ " "
ans <- getLine
return $ parser ans
runSurvey (Choose prompt choiceExp) = do
putStr $ "\n" ++ prompt ++ ": \n"
dispChoices 1 choiceExp
ans <- readLn :: IO Int
selected (ans - 1) choiceExp
where
dispChoices :: Int -> Choice a -> IO Int
dispChoices num (Item text _) = do
putStrLn $ "[" ++ show num ++ "] " ++ text
return $ succ num
dispChoices num (choice :->: _) = dispChoices num choice
dispChoices num (l :|: r) = disp2 num l r
dispChoices num (l :||: r) = disp2 num l r
disp2 :: Int -> Choice a -> Choice b -> IO Int
disp2 num l r = do
next <- dispChoices num l
dispChoices next r
runSurvey (left :+: right) = do
la <- runSurvey left
ra <- runSurvey right
return (la, ra)
selected :: Int -> Choice a -> IO a
selected 0 (Item _ val) = return val
selected n (choice :->: sub) = do
choiceval <- selected n choice
subval <- runSurvey sub
return (choiceval, subval)
selected n (l :|: r)
| n < llen = selected n l
| otherwise = selected (n - llen) r
where llen = choiceLength l
selected n (l :||: r)
| n < llen = Left <$> selected n l
| otherwise = Right <$> selected (n-llen) r
where llen = choiceLength l
choiceLength :: Choice a -> Int
choiceLength (Item _ _) = 1
choiceLength (c :->: s) = choiceLength c
choiceLength (l :|: r) = choiceLength l + choiceLength r
choiceLength (l :||: r) = choiceLength l + choiceLength r
-- runAS :: forall a. Typeable a => AllSurveys -> IO a
-- runAS (AS s) = runSurvey s
--
-- data AllSurveys where
-- AS :: Typeable a => Survey a -> AllSurveys
--
-- getSurvey :: String -> AllSurveys
-- getSurvey "age" = AS age
-- getSurvey "personal" = AS personal
class Container f where
data Location f
get :: Location f -> f a -> Maybe a
instance Container [] where
data Location [] = ListLoc Int
get (ListLoc i) xs
| i < length xs = Just $ xs!!i
| otherwise = Nothing
data Tree a = Node a (Tree a)
instance Container Tree where
data Location Tree = ThisNode | NodePath Int (Location Tree)
get ThisNode (Node x _) = Just x
get (NodePath i path) (Node _ sfo) = get path =<< get i sfo
|
homam/fsm-conversational-ui
|
src/TestSurvey.hs
|
bsd-3-clause
| 5,089 | 0 | 13 | 1,288 | 1,805 | 890 | 915 | 122 | 4 |
module Inter.Quora.Strings where
import qualified Data.HashMap.Lazy as M
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as MV
import Control.Monad.ST
import Data.Foldable (forM_)
import Data.Hashable
import Data.List (minimumBy)
import Inter.Quora.General (occurrenceGroups)
import Types
{- | Find the first non-repeated character
* Strategy
* Make a set of elements which occur only once
* Scan the string testing each char for membership in the set
* Complexity (let N be string length and A be alphabet size)
* singles
* filter: n
* occurrenceGroups: N log A
* N log A
* M.toList: n
* minimumBy: n
* = N log A
-}
firstUniqueChar :: String -> Maybe Char
firstUniqueChar s =
if M.null singles
then Nothing
else Just . fst . minimumBy occursBefore $ M.toList singles
where
singles = M.filter ((==1) . ogCount) $ occurrenceGroups s
occursBefore a b = (ogFirst $ snd a) `compare` (ogFirst $ snd b)
{- | Reverse a vector recursively
Complexity: n
-}
revRecursive :: V.Vector a -> V.Vector a
revRecursive v
| V.null v = v
| otherwise = V.snoc (revRecursive $ V.tail v) (V.head v)
{- | Iteratively reverse a mutable vector
* Strategy
* Thaw the input into the ST monad
* Pivoting around the middle, swap ends working inward
* Freeze and return (shh, you didn't see any mutation!)
* Complexity: n
-}
revIterative :: V.Vector a -> V.Vector a
revIterative v = runST $ do
mv <- V.thaw v
forM_ [0..half-1] $ \i -> MV.swap mv i ((n-i)-1)
V.freeze mv
where
n = V.length v
half = n `div` 2
{- | Determine if two vectors are anagrams
* Naive n log n solution (requires Ord a)
@
\a b -> (V.sort a) == (V.sort b)
@
* Strategy
* Two strings are anagrams iff the counts of characters
occurring in each matches those of the other
* Build an efficient hash-based occurrence group count of each
* Then compare
* Complexity: 3n ~ n
* occurrenceGroups: n
* M.map: n
* (==) on hash maps: n
-}
anagrams :: (Eq a, Hashable a) => [a] -> [a] -> Bool
anagrams a b =
M.map ogCount (occurrenceGroups a) ==
M.map ogCount (occurrenceGroups b)
{- | Determine if a vector is a palindrome
* Naive three pass approach
@
\v -> v == reverse v
@
* Strategy
* It's the same complexity class really, but we can scan
inward from both sides of the vector and check for equality
-}
palindrome :: Eq a => V.Vector a -> Bool
palindrome v = all (\i -> v V.! i == v V.! ((n-i)-1)) [0..half-1]
where
n = V.length v
half = n `div` 2
|
begriffs/algorithm-freezer
|
src/Inter/Quora/Strings.hs
|
bsd-3-clause
| 2,603 | 0 | 14 | 640 | 575 | 306 | 269 | 36 | 2 |
-- -*- flycheck-disabled-checkers: '(haskell-ghc haskell-stack-ghc); -*-
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
----------------------------------------------------------------------
-- |
-- Module : Basic
-- Copyright : (c) 2016 Conal Elliott
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Suite of automated tests
----------------------------------------------------------------------
{-# OPTIONS_GHC -fplugin=ReificationRules.Plugin -dcore-lint -fexpose-all-unfoldings #-}
{-# OPTIONS_GHC -dsuppress-idinfo -dsuppress-module-prefixes -dsuppress-uniques #-}
-- {-# OPTIONS_GHC -fplugin-opt=ReificationRules.Plugin:trace #-}
-- When I list the plugin in the test suite's .cabal target instead of here, I get
--
-- <command line>: Could not find module ‘ReificationRules.Plugin’
-- It is a member of the hidden package ‘reification-rules-0.0.0’.
-- Perhaps you need to add ‘reification-rules’ to the build-depends in your .cabal file.
module Basic (tests) where
import Data.Tuple (swap)
import Distribution.TestSuite
import ReificationRules.HOS (E,Prim,reify)
import qualified ReificationRules.Run as Run
import ReificationRules.Misc (Binop)
-- Whether to render to a PDF (vs print reified expression)
render :: Bool
render = True -- False
-- For FP & parallelism talk
tests :: IO [Test]
tests = return
[ nopTest
-- , test 0.5 "foo-a" (\ x -> x * (-1) :: Double)
, test 0.5 "foo-b" (\ x y -> x - y * (-1) :: Double)
, test 0.5 "foo-c" (\ x y -> x - (-1) * y :: Double)
, test 0.5 "foo-d" (\ x y -> (-1) * y - x :: Double)
, test 0.5 "foo-e" (\ x y -> y * (-1) - x :: Double)
-- , test 0.5 "not" not -- works
-- , test 0.5 "fst" (fst :: (Int,Bool) -> Int)
-- , test 0.5 "if" (\ (a :: Int) -> if a > 0 then a else negate a)
-- , test 0.5 "or-not" (\ x y -> x || not y)
-- , test 0.5 "pow-6" (\ (a :: Double) -> (a + 1) ^ (6 :: Int)) -- product tree
-- , test 0.5 "pow-7" (\ (a :: Double) -> (a + 1) ^ (7 :: Int))
-- , test 0.5 "swap" (swap @Int @Bool)
-- , test 0.5 "map-just" (fmap not . Just)
-- , test 0.5 "nothing" (Nothing :: Maybe Bool)
-- , test 0.5 "undefined" (undefined :: ())
-- , test 0.5 "min-int" (min :: Binop Int) -- fails
]
{--------------------------------------------------------------------
Testing utilities
--------------------------------------------------------------------}
test :: Run.Okay a => Double -> String -> a -> Test
test _ _ _ = error "test called"
{-# NOINLINE test #-}
{-# RULES "test" forall nm sep a. test sep nm a = mkTest sep nm (reify a) #-}
mkTest :: Run.Okay a => Double -> String -> E Prim a -> Test
mkTest sep nm e = Test inst
where
inst = TestInstance
{ run = Finished Pass <$ go e
, name = nm
, tags = []
, options = []
, setOption = \_ _ -> Right inst
}
go | render = Run.run nm [Run.ranksep sep]
| otherwise = print
nopTest :: Test
nopTest = Group "nop" False []
|
conal/reification-rules
|
test/Basic.hs
|
bsd-3-clause
| 3,340 | 0 | 13 | 747 | 484 | 285 | 199 | 41 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- | A project to describe Haskell syntax for newbies and intermediates alike.
module Language.Haskell.Describe where
import Control.Applicative
import Control.Monad.Error
import Control.Monad.State
import Data.Data
import Data.Functor.Identity
import Data.Maybe
import Data.Proxy
import Data.Typeable
import Language.Haskell.Exts.Pretty
import Language.Haskell.Exts.Syntax
describe :: String
describe = prettyPrint (generate 0 :: Module)
generate :: Data a => Int -> a
generate i =
result
where
result =
fromMaybe (error ("Unable to generate a value for type: " ++ show (typeOf result)))
(samples <|> pure (generic i))
samples :: Data a => Maybe a
samples =
cast (Ident "foo") <|>
cast (ModuleName "Module.Name.Here") <|>
cast (SrcLoc "" 0 0)
generic :: Data a => Int -> a
generic i =
result
where result =
fromMaybe (fromConstrB (generate 0)
(head (dataTypeConstrs (dataTypeOf result))))
(cast ([generate 0,generate 1] :: [Decl]))
list =
show (dataTypeConstrs (dataTypeOf result) !! i) ==
"[]"
tmap :: (Typeable a,Typeable c) => (c -> c) -> a -> Maybe a
tmap f a =
case cast a of
Nothing -> return a
Just c -> cast (f c)
|
chrisdone/haskell-describe
|
src/Language/Haskell/Describe.hs
|
bsd-3-clause
| 1,381 | 0 | 15 | 334 | 428 | 226 | 202 | 42 | 2 |
module Numeric.Digamma (digamma) where
import Numeric.SpecFunctions (digamma)
|
bgamari/digamma
|
Numeric/Digamma.hs
|
bsd-3-clause
| 79 | 0 | 5 | 8 | 21 | 13 | 8 | 2 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeSynonymInstances #-}
--------------------------------------------------------------------------------
-- |
-- Module : Alfred.Query
-- Copyright : (c) 2014 Patrick Bahr
-- License : BSD3
-- Maintainer : Patrick Bahr <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC Extensions)
--
-- This module provides utility functions to query web APIs. These
-- queries can then be used to feed Alfred with suggestions.
--
--------------------------------------------------------------------------------
module Alfred.Query
( jsonQuery
, jsonQuery'
, xmlQuery
, xmlQueryLazy
, escapeString
, escapeText
, Query
, transformQuery
, Query'
) where
import Data.Aeson
import Network.HTTP.Conduit
import Network.HTTP.Types hiding (Query)
import Network.URI hiding (escapeString)
import qualified Data.Text as T
import Data.ByteString.Lazy
import Data.Text (Text)
import System.IO.Error
import Text.XML.Expat.Tree
-- | Type representing queries for use in 'Alfred.runScript'.
type Query a = Query' Text a
-- | Alternative type representing queries for use in
-- 'Alfred.runScript''.
type Query' q a = q -> IO (Either Text a)
-- | This function performs a query by performing an HTTP GET request
-- at the url obtained by concatenating the first argument with the
-- second one (after escaping it). The returned query takes a string
-- as an argument and appends it to the base url to obtain the url
-- that is used for the query. The result is then parsed as a JSON
-- object. For example, for a Google search:
--
-- @
-- runQuery :: Query (Text,[Text])
-- runQuery = jsonQuery suggestURL
--
-- suggestURL = "http://google.com/complete/search?client=firefox&q="
-- @
--
jsonQuery :: FromJSON a => Text -> Query a
jsonQuery = jsonQuery' id
-- | This function is a variant of 'jsonQuery' that takes a function
-- as an additional argument that is used to transform the raw
-- 'ByteString' that is returned by the query. This can be helpful if
-- the source does not provide valid UTF-8 formatted JSON. For
-- example, for a Google search:
--
-- @
-- runQuery :: Query (Text,[Text])
-- runQuery = jsonQuery' (encodeUtf8 . decodeLatin1) suggestURL
--
-- suggestURL = "http://google.com/complete/search?client=firefox&q="
-- @
--
jsonQuery' :: FromJSON a => (ByteString -> ByteString) -> Text -> Query a
jsonQuery' convert = genericQuery mkJSONRequest result
where result res = case eitherDecode (convert $ responseBody res) of
Left msg -> return $ Left $ T.concat
["JSON decoding error: ", T.pack msg, "\n", T.pack $ show $ responseBody res]
Right res -> return (Right res)
-- | Constructions a request for doing an XML query.
mkJSONRequest :: Request -> Request
mkJSONRequest req = req {requestHeaders=jsonHeaders}
where jsonHeaders :: [Header]
jsonHeaders = (hContentType, "application/json; charset=utf-8") : requestHeaders req
-- | This function performs a query by performing an HTTP GET request
-- at the url obtained by concatenating the first argument with the
-- second one (after escaping it). The returned query takes a string
-- as an argument and appends it to the base url to obtain the url
-- that is used for the query. The result is then parsed as an XML
-- document. For example, for a DBLP search:
--
-- @
-- runQuery :: Query (Node Text Text)
-- runQuery query = xmlQuery suggestURL query
--
-- suggestURL = "http://dblp.uni-trier.de/search/author?xauthor="
-- @
--
xmlQuery :: (GenericXMLString a, GenericXMLString b) => Text -> Query (Node a b)
xmlQuery = genericQuery mkXMLRequest result
where result res = let (tree, err) = parse defaultParseOptions (responseBody res) in
case err of
Just msg -> return $ Left $ T.concat
["XML decoding error: ", T.pack $ show msg ,"\n", T.pack $ show (responseBody res)]
Nothing -> return (Right tree)
-- | Lazy variant of 'xmlQueryLazy'. This function may be useful if
-- results tend to be lengthy and only a small prefix of the result is
-- used.
xmlQueryLazy :: (GenericXMLString a, GenericXMLString b) => Text -> Query (Node a b)
xmlQueryLazy = genericQuery mkXMLRequest result
where result res = let (tree, _) = parse defaultParseOptions (responseBody res)
in return (Right tree)
-- | Generic function to construct queries.
genericQuery :: (Request -> Request)
-> (Response ByteString -> IO (Either Text b))
-> Text -> Query b
genericQuery modRequest result base query = let urlText = T.concat [base, escapeText query] in
case (parseUrl $ T.unpack urlText) of
Nothing -> return $ Left $ T.concat ["illformed url: ", urlText]
Just req -> catchIOError execute (return . Left . T.pack . show)
where execute = withManager (\man -> (httpLbs (modRequest req) man)) >>= result
-- | Constructions a request for doing a JSON query.
mkXMLRequest :: Request -> Request
mkXMLRequest req = req {requestHeaders=xmlHeaders}
where xmlHeaders :: [Header]
xmlHeaders = (hContentType, "application/xml") : requestHeaders req
-- | Functorial map for 'Query''.
transformQuery :: (a -> b) -> Query' q a -> Query' q b
transformQuery f = fmap (fmap (fmap f))
-- | Escapes the string for use in a URL.
escapeString :: String -> String
escapeString = escapeURIString isUnescapedInURI
-- | Escapes the text for use in a URL.
escapeText :: Text -> Text
escapeText = T.pack . escapeString . T.unpack
|
pa-ba/alfred
|
src/Alfred/Query.hs
|
bsd-3-clause
| 5,706 | 0 | 19 | 1,244 | 1,027 | 572 | 455 | 64 | 2 |
-- https://www.fpcomplete.com/user/bartosz/understanding-algebras
module FAlgebra where
----------------
-- Algebra:
-- (1) A way to construct expressions
-- (2) A way to evaluate expressions (produce a single value)
-- define our expressions (non-recursive)
-- ExprF :: a -> ExprF a
-- ExprF :: * -> *
data ExprF a = Const Int
| Add a a
| Mul a a
fixpoint :: (a -> a) -> a
fixpoint f = f valA
where valA = fixpoint f
-- define our fix-point type-level function
-- Fix :: (a -> a) -> Fix t
-- Fix :: (* -> *) -> *
newtype Fix f = Fx (f (Fix f))
-- Fx :: f (Fix f) -> Fix f
unFix :: Fix f -> f (Fix f)
unFix (Fx x) = x
-- define Expr as the fix-point of ExprF
-- Expr = Fx $ ExrFC $ Fx
type Expr = Fix ExprF
-- we can map over expr
-- endofunctor: maps a given category into itself
-- Hask: the category of all Haskell types
instance Functor ExprF where
fmap _ (Const i) = Const i
fmap eval (Add l r) = Add (eval l) (eval r)
fmap eval (Mul l r) = Mul (eval l) (eval r)
-- our evaluator for a single top-level expression
-- picked one type (Int) as our evaluation target (carrier type of the algebra)
alg :: ExprF Int -> Int
alg (Const i) = i
alg (Add l r) = l + r
alg (Mul l r) = l * r
-- hand-rolled eval
evalFull :: Expr -> Int
evalFull (Fx (Const n)) = n
evalFull (Fx (Add l r)) = evalFull l + evalFull r
evalFull (Fx (Mul l r)) = evalFull l * evalFull r
-- partial
evalShape :: Expr -> ExprF Int
evalShape (Fx (Const n)) = Const n
evalShape (Fx (Add l r)) = Add (alg $ evalShape l) (alg $ evalShape r)
evalShape (Fx (Mul l r)) = Mul (alg $ evalShape l) (alg $ evalShape r)
evalFull2 :: Expr -> Int
evalFull2 = alg . evalShape
-- eval using alg & fmap
evalFull3 :: Expr -> Int
evalFull3 = alg . evalShape'
where
evalShape' :: Expr -> ExprF Int
evalShape' = fmap (alg . evalShape') . unFix
-- general evaluation function for any reduction / evaluator function
evalGeneral :: (ExprF a -> a) -> Expr -> a
evalGeneral red = red . evalShape'
where
evalShape' = fmap (red . evalShape') . unFix
----------------
-- F-Algebra
-- 1. structure: functor f (endofunctor)
-- 2. carrier type: a
-- 3. evaluator: morphism from f(a) -> a
type Algebra f a = f a -> a
type SimpleA = Algebra ExprF Int
alg' :: SimpleA
alg' = alg
-- initial algebra (doesn't loose any information!)
type ExprInitAlg = Algebra ExprF (Fix ExprF)
ex_init_alg :: ExprInitAlg
ex_init_alg = Fx
-- homomorphism: a mapping that preserves certain strucutre, in case of an
-- algebra, we want to keep the functor fixed, so homomorphism should map
-- carrier types and evaluators.
--
-- homomorphism from initial algebra
-- g :: Fix f -> a
-- fmap g :: f (Fix f) -> f a
-- f (Fix f) --- fmap g ---> f a
-- | |
-- Fx alg
-- | |
-- v v
-- Fix f ------- g --------> a
--
-- Reversing Fx we get:
--
-- f (Fix f) --- fmap g ---> f a
-- ^ |
-- | |
-- unFix alg
-- | |
-- | v
-- Fix f ------- g --------> a
--
-- So to implement g, our general evaluator, we should apply `unFix`, `fmap g`
-- and then `alg`.
--
-- g = alg . (fmap g) . unFix
-- where alg :: f a -> a
g :: Expr -> Int
g = alg . (fmap g) . unFix
cata :: (Functor f) => Algebra f a -> Fix f -> a
cata algg = gg'
where gg' = algg . (fmap gg') . unFix
-- Lists
data ListF a b = Nil | Cons a b
instance Functor (ListF a) where
fmap f (Nil ) = Nil
fmap f (Cons a b) = Cons a (f b)
algSum :: ListF Int Int -> Int
algSum (Nil ) = 0
algSum (Cons a b) = a + b
lst :: Fix (ListF Int)
lst = Fx $ Cons 1 $ Fx $ Cons 2 $ Fx $ Cons 3 $ Fx Nil
sumLst :: Fix (ListF Int) -> Int
sumLst = cata algSum
|
dterei/Scraps
|
haskell/freemtl/FAlgebra.hs
|
bsd-3-clause
| 3,814 | 0 | 11 | 1,078 | 1,047 | 564 | 483 | 59 | 1 |
{-
Model.hs (adapted from model.c which is (c) Silicon Graphics, Inc.)
Copyright (c) Sven Panne 2002-2005 <[email protected]>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
This program demonstrates modeling transformations.
-}
import System.Exit ( exitWith, ExitCode(ExitSuccess) )
import Graphics.UI.GLUT
myInit :: IO ()
myInit = do
clearColor $= Color4 0 0 0 0
shadeModel $= Flat
drawTriangle :: IO ()
drawTriangle = do
-- resolve overloading, not needed in "real" programs
let vertex2f = vertex :: Vertex2 GLfloat -> IO ()
renderPrimitive LineLoop $ do
vertex2f (Vertex2 0 25 )
vertex2f (Vertex2 25 (-25))
vertex2f (Vertex2 (-25) (-25))
display :: DisplayCallback
display = do
clear [ ColorBuffer ]
-- resolve overloading, not needed in "real" programs
let color3f = color :: Color3 GLfloat -> IO ()
translatef = translate :: Vector3 GLfloat -> IO ()
scalef = scale :: GLfloat -> GLfloat -> GLfloat -> IO ()
rotatef = rotate :: GLfloat -> Vector3 GLfloat -> IO ()
color3f (Color3 1 1 1)
loadIdentity
color3f (Color3 1 1 1)
drawTriangle
lineStipple $= Just (1, 0xF0F0)
loadIdentity
translatef (Vector3 (-20) 0 0)
drawTriangle
lineStipple $= Just (1, 0xF00F)
loadIdentity
scalef 1.5 0.5 1.0
drawTriangle
lineStipple $= Just (1, 0x8888)
loadIdentity
rotatef 90 (Vector3 0 0 1)
drawTriangle
lineStipple $= Nothing
flush
reshape :: ReshapeCallback
reshape size@(Size w h) = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
let wf = fromIntegral w
hf = fromIntegral h
if w <= h
then ortho (-50) 50 (-50 * hf/wf) (50 * hf/wf) (-1) 1
else ortho (-50 * wf/hf) (50 * wf/hf) (-50) 50 (-1) 1
matrixMode $= Modelview 0
keyboard :: KeyboardMouseCallback
keyboard (Char '\27') Down _ _ = exitWith ExitSuccess
keyboard _ _ _ _ = return ()
main :: IO ()
main = do
(progName, _args) <- getArgsAndInitialize
initialDisplayMode $= [ SingleBuffered, RGBMode ]
initialWindowSize $= Size 500 500
initialWindowPosition $= Position 100 100
createWindow progName
myInit
displayCallback $= display
reshapeCallback $= Just reshape
keyboardMouseCallback $= Just keyboard
mainLoop
|
FranklinChen/hugs98-plus-Sep2006
|
packages/GLUT/examples/RedBook/Model.hs
|
bsd-3-clause
| 2,378 | 0 | 14 | 575 | 788 | 381 | 407 | 64 | 2 |
module System.Build.Access.Overview where
class Overview r where
overview ::
Maybe FilePath
-> r
-> r
getOverview ::
r
-> Maybe FilePath
|
tonymorris/lastik
|
System/Build/Access/Overview.hs
|
bsd-3-clause
| 167 | 0 | 8 | 51 | 45 | 24 | 21 | 9 | 0 |
module Language.LaTeX.Builder.MonoidUtils (ø, (⊕), (<>), (<||>), (<&&>), mapNonEmpty) where
import Data.Monoid.Unicode ((⊕))
ø :: Monoid m => m
ø = mempty
(<||>) :: (Monoid a, Eq a) => a -> a -> a
a <||> b | a == ø = b
| otherwise = a
(<&&>) :: (Monoid a, Eq a, Monoid b) => a -> b -> b
a <&&> b | a == ø = ø
| otherwise = b
mapNonEmpty :: (Eq a, Monoid a, Monoid b) => (a -> b) -> a -> b
mapNonEmpty f x | x == ø = ø
| otherwise = f x
|
np/hlatex
|
Language/LaTeX/Builder/MonoidUtils.hs
|
bsd-3-clause
| 503 | 0 | 8 | 158 | 265 | 144 | 121 | 13 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
module Stack.Options.GhciParser where
import Data.Version (showVersion)
import Options.Applicative
import Options.Applicative.Args
import Options.Applicative.Builder.Extra
import Paths_stack as Meta
import Stack.Config (packagesParser)
import Stack.Ghci (GhciOpts (..))
import Stack.Options.BuildParser (flagsParser)
import Stack.Options.Completion
import Stack.Prelude
-- | Parser for GHCI options
ghciOptsParser :: Parser GhciOpts
ghciOptsParser = GhciOpts
<$> many
(textArgument
(metavar "TARGET/FILE" <>
completer (targetCompleter <> fileExtCompleter [".hs", ".lhs"]) <>
help ("If none specified, use all local packages. " <>
"See https://docs.haskellstack.org/en/v" <>
showVersion Meta.version <>
"/build_command/#target-syntax for details. " <>
"If a path to a .hs or .lhs file is specified, it will be loaded.")))
<*> fmap concat (many (argsOption (long "ghci-options" <>
metavar "OPTIONS" <>
completer ghcOptsCompleter <>
help "Additional options passed to GHCi")))
<*> manyArgsOptions
(long "ghc-options" <>
metavar "OPTIONS" <>
completer ghcOptsCompleter <>
help "Additional options passed to both GHC and GHCi")
<*> flagsParser
<*> optional
(strOption (long "with-ghc" <>
metavar "GHC" <>
help "Use this GHC to run GHCi"))
<*> (not <$> boolFlags True "load" "load modules on start-up" idm)
<*> packagesParser
<*> optional
(textOption
(long "main-is" <>
metavar "TARGET" <>
completer targetCompleter <>
help "Specify which target should contain the main \
\module to load, such as for an executable for \
\test suite or benchmark."))
<*> switch (long "load-local-deps" <> help "Load all local dependencies of your targets")
-- TODO: deprecate this? probably useless.
<*> switch (long "skip-intermediate-deps" <> help "Skip loading intermediate target dependencies" <> internal)
<*> boolFlags True "package-hiding" "package hiding" idm
<*> switch (long "no-build" <> help "Don't build before launching GHCi" <> internal)
<*> switch (long "only-main" <> help "Only load and import the main module. If no main module, no modules will be loaded.")
|
MichielDerhaeg/stack
|
src/Stack/Options/GhciParser.hs
|
bsd-3-clause
| 3,166 | 0 | 29 | 1,353 | 459 | 232 | 227 | 50 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.EXT.SecondaryColor
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/EXT/secondary_color.txt EXT_secondary_color> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.EXT.SecondaryColor (
-- * Enums
gl_COLOR_SUM_EXT,
gl_CURRENT_SECONDARY_COLOR_EXT,
gl_SECONDARY_COLOR_ARRAY_EXT,
gl_SECONDARY_COLOR_ARRAY_POINTER_EXT,
gl_SECONDARY_COLOR_ARRAY_SIZE_EXT,
gl_SECONDARY_COLOR_ARRAY_STRIDE_EXT,
gl_SECONDARY_COLOR_ARRAY_TYPE_EXT,
-- * Functions
glSecondaryColor3bEXT,
glSecondaryColor3bvEXT,
glSecondaryColor3dEXT,
glSecondaryColor3dvEXT,
glSecondaryColor3fEXT,
glSecondaryColor3fvEXT,
glSecondaryColor3iEXT,
glSecondaryColor3ivEXT,
glSecondaryColor3sEXT,
glSecondaryColor3svEXT,
glSecondaryColor3ubEXT,
glSecondaryColor3ubvEXT,
glSecondaryColor3uiEXT,
glSecondaryColor3uivEXT,
glSecondaryColor3usEXT,
glSecondaryColor3usvEXT,
glSecondaryColorPointerEXT
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/EXT/SecondaryColor.hs
|
bsd-3-clause
| 1,380 | 0 | 4 | 154 | 115 | 84 | 31 | 27 | 0 |
-- | Parsing and printing binary XML.
module Network.CCNx.BinaryXML
( Block (..)
, printBinaryXML
, parseBinaryXML
) where
import Data.Bits
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Char
import Data.Word
import Text.Printf
-- | Binary XML structure.
data Block
= BLOB [Word8]
| UDATA String
| TAG String [Block]
| ATTR String String
| DTAG Int [Block]
| DATTR Int String
| EXT Int
deriving Show
data BlockType = BLOB' | UDATA' | TAG' | ATTR' | DTAG' | DATTR' | EXT' deriving Show
-- | Print binary XML.
printBinaryXML :: Block -> ByteString
printBinaryXML = B.pack . formatBlock
formatBlock :: Block -> [Word8]
formatBlock a = case a of
BLOB a -> formatHeader BLOB' (length a) ++ a
UDATA a -> formatHeader UDATA' (length a) ++ map (fromIntegral . ord) a
TAG a b -> formatHeader TAG' (length a - 1) ++ map (fromIntegral . ord) a ++ concatMap formatBlock b ++ [0x00]
ATTR a b -> formatHeader ATTR' (length a - 1) ++ map (fromIntegral . ord) a ++ formatBlock (UDATA b)
DTAG a b -> formatHeader DTAG' a ++ concatMap formatBlock b ++ [0x00]
DATTR a b -> formatHeader DATTR' a ++ formatBlock (UDATA b)
EXT a -> formatHeader EXT' a
blockTypeCode :: BlockType -> Word8
blockTypeCode a = case a of
BLOB' -> 5
UDATA' -> 6
TAG' -> 1
ATTR' -> 3
DTAG' -> 2
DATTR' -> 4
EXT' -> 0
blockType :: Word8 -> BlockType
blockType a = case a .&. 0x7 of
5 -> BLOB'
6 -> UDATA'
1 -> TAG'
3 -> ATTR'
2 -> DTAG'
4 -> DATTR'
0 -> EXT'
a -> error $ "unknown block type : " ++ show a
formatHeader :: BlockType -> Int -> [Word8]
formatHeader _ a | a < 0 = error "number is not positive"
formatHeader t a = f (shiftR a 4) ++ [shiftL (fromIntegral $ a .&. 0xF) 3 .|. 0x80 .|. blockTypeCode t]
where
f 0 = []
f a = f (shiftR a 7) ++ [fromIntegral (a .&. 0x7F)]
-- | Parse binary XML.
parseBinaryXML :: ByteString -> Block
parseBinaryXML = fst . parseBlock . B.unpack
parseBlock :: [Word8] -> (Block, [Word8])
parseBlock a = case tt of
BLOB' -> (BLOB $ take n rest, drop n rest)
UDATA' -> (UDATA udata, drop n rest)
where
udata = map (chr . fromIntegral) $ take n rest
TAG' -> (TAG (map (chr . fromIntegral) $ take (n + 1) rest) blocks, rest')
where
(blocks, rest') = parseBlocks $ drop (n + 1) rest
ATTR' -> (ATTR (map (chr . fromIntegral) $ take (n + 1) rest) a, rest')
where
(a, rest') = case parseBlock $ drop (n + 1) rest of
(UDATA a, b) -> (a, b)
_ -> error "expecting UDATA after ATTR"
DTAG' -> (DTAG n blocks, rest')
where
(blocks, rest') = parseBlocks rest
DATTR' -> (DATTR n a, rest')
where
(a, rest') = case parseBlock rest of
(UDATA a, b) -> (a, b)
_ -> error "expecting UDATA after DATTR"
EXT' -> (EXT n, rest)
where
((tt, n), rest) = parseHeader a
parseBlocks :: [Word8] -> ([Block], [Word8])
parseBlocks (0x00 : rest) = ([], rest)
parseBlocks a = (block : blocks, rest')
where
(block, rest) = parseBlock a
(blocks, rest') = parseBlocks rest
parseHeader :: [Word8] -> ((BlockType, Int), [Word8])
parseHeader a = ((tt, n), b)
where
tt = blockType a2
(a1, a2 : b) = case span (not . flip testBit 7) a of
(_, []) -> error $ "parseHeader: " ++ concat [ printf "%02x" a | a <- a ]
a -> a
n = f (fromIntegral $ shiftR a2 3 .&. 0xF) 4 $ reverse a1
f n _ [] = n
f n s (a : b) = f (n .|. shiftL (fromIntegral a) s) (s + 7) b
|
tomahawkins/ccnx
|
Network/CCNx/BinaryXML.hs
|
bsd-3-clause
| 3,466 | 0 | 14 | 866 | 1,523 | 802 | 721 | 90 | 9 |
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE FlexibleInstances #-}
-- | This module contains miscellaneous functions plus a few pieces of
-- functionality that are missing from the standard Haskell libraries.
module Data.IterIO.Extra
( -- * Miscellaneous
iterLoop
, inumSplit
-- , fixIterPure
-- * Functionality missing from system libraries
, SendRecvString(..)
, hShutdown
-- * Debugging functions
, traceInput, traceI
) where
import Control.Concurrent (myThreadId)
import Control.Concurrent.MVar
import Control.Monad
import Control.Monad.Trans
import Data.ByteString.Internal (inlinePerformIO)
import Data.Monoid
import Debug.Trace
import Foreign.C
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as L
import Network.Socket
import Network.Socket.ByteString as S
import Network.Socket.ByteString.Lazy as L
import System.IO
import Data.IterIO.Iter
import Data.IterIO.Inum
import Data.Typeable
import System.IO.Error
import GHC.IO.FD (FD(..))
import GHC.IO.Handle.Types (Handle__(..))
import GHC.IO.Handle.Internals (wantWritableHandle)
foreign import ccall unsafe "sys/socket.h shutdown"
c_shutdown :: CInt -> CInt -> IO CInt
-- | Create a loopback @('Iter', 'Onum')@ pair. The iteratee and
-- enumerator can be used in different threads. Any data fed into the
-- 'Iter' will in turn be fed by the 'Onum' into whatever 'Iter' it
-- is given. This is useful for testing a protocol implementation
-- against itself.
iterLoop :: (MonadIO m, ChunkData t, Show t) =>
m (Iter t m (), Onum t m a)
iterLoop = do
-- The loopback is implemented with an MVar (MVar Chunk). The
-- enumerator waits on the inner MVar, while the iteratee uses the outer
-- MVar to avoid races when appending to the stored chunk.
mv <- liftIO $ newEmptyMVar >>= newMVar
return (iter mv, enum mv)
where
iter mv = do
c@(Chunk _ eof) <- chunkI
liftIO $ withMVar mv $ \p ->
do mp <- tryTakeMVar p
putMVar p $ case mp of
Nothing -> c
Just c' -> mappend c' c
if eof then return () else iter mv
-- Note the ifeed mempty, which is there in case the enum feeds
-- an iter that starts with a liftIO or something, and the other
-- half of the loopback interface waits for the result of that
-- liftIO to start producing data.
enum mv = mkInumM (ifeed mempty >> loop)
where loop = do p <- liftIO $ readMVar mv
Chunk t eof <- liftIO $ takeMVar p
done <- ifeed t
when (not $ eof || done) loop
-- | Returns an 'Iter' that always returns itself until a result is
-- produced. You can fuse @inumSplit@ to an 'Iter' to produce an
-- 'Iter' that can safely be fed (e.g., with 'enumPure') from multiple
-- threads.
inumSplit :: (MonadIO m, ChunkData t) => Inum t t m a
inumSplit iter1 = do
mv <- liftIO $ newMVar $ IterF iter1
iter mv
where
iter mv = do
(Chunk t eof) <- chunkI
rold <- liftIO $ takeMVar mv
rnew <- runIterMC (passCtl pullupResid) (reRunIter rold) $ chunk t
liftIO $ putMVar mv rnew
case rnew of
IterF _ | not eof -> iter mv
_ -> return rnew
{- fixIterPure allows MonadFix instances, which support
out-of-order name bindings in a "rec" block, provided your file
has {-# LANGUAGE RecursiveDo #-} at the top. A contrived example
would be:
fixtest :: IO Int
fixtest = enumPure [10] `cat` enumPure [1] |$ fixee
where
fixee :: Iter [Int] IO Int
fixee = rec
liftIO $ putStrLn "test #1"
c <- return $ a + b
liftIO $ putStrLn "test #2"
a <- headI
liftIO $ putStrLn "test #3"
b <- headI
liftIO $ putStrLn "test #4"
return c
-- A very convoluted way of computing factorial
fixtest2 :: Int -> IO Int
fixtest2 i = do
f <- enumPure [2] `cat` enumPure [1] |$ mfix fact
run $ f i
where
fact :: (Int -> Iter [Int] IO Int)
-> Iter [Int] IO (Int -> Iter [Int] IO Int)
fact f = do
ignore <- headI
liftIO $ putStrLn $ "ignoring " ++ show ignore
base <- headI
liftIO $ putStrLn $ "base is " ++ show base
return $ \n -> if n <= 0
then return base
else liftM (n *) (f $ n - 1)
-- | This is a fixed point combinator for iteratees over monads that
-- have no side effects. If you wish to use @rec@ with such a monad,
-- you can define an instance of 'MonadFix' in which
-- @'mfix' = fixIterPure@. However, be warned that this /only/ works
-- when computations in the monad have no side effects, as
-- @fixIterPure@ will repeatedly re-invoke the function passsed in
-- when more input is required (thereby also repeating side-effects).
-- For cases in which the monad may have side effects, if the monad is
-- in the 'MonadIO' class then there is already an 'mfix' instance
-- defined using 'fixMonadIO'.
fixIterPure :: (ChunkData t, MonadFix m) =>
(a -> Iter t m a) -> Iter t m a
fixIterPure f = Iter $ \c ->
let ff ~(Done a _) = check $ runIter (f a) c
-- Warning: IterF case re-runs function, repeating side effects
check (IterF _) = return $ IterF $ Iter $ \c' ->
runIter (fixIterPure f) (mappend c c')
check (IterM m) = m >>= check
check r = return r
in IterM $ mfix ff
-}
--
-- Some utility functions for things that are made hard by the Haskell
-- libraries
--
-- | @SendRecvString@ is the class of string-like objects that can be
-- used with datagram sockets.
class (Show t) => SendRecvString t where
genRecv :: Socket -> Int -> IO t
genSend :: Socket -> t -> IO ()
genRecvFrom :: Socket -> Int -> IO (t, SockAddr)
genSendTo :: Socket -> t -> SockAddr -> IO ()
instance SendRecvString [Char] where
genRecv s len = liftM S8.unpack $ S.recv s len
genSend s str = S.sendAll s (S8.pack str)
genRecvFrom s len = do (str, a) <- S.recvFrom s len
return (S8.unpack str, a)
genSendTo s str dest = S.sendAllTo s (S8.pack str) dest
instance SendRecvString S.ByteString where
genRecv s len = S.recv s len
genSend s str = S.sendAll s str
genRecvFrom s len = S.recvFrom s len
genSendTo s str dest = S.sendAllTo s str dest
instance SendRecvString L.ByteString where
genRecv s len = do str <- S.recv s len
return $ L.fromChunks [str]
genSend s str = L.sendAll s str
genRecvFrom s len = do (str, a) <- S.recvFrom s len
return (L.fromChunks [str], a)
genSendTo s str dest = S.sendManyTo s (L.toChunks str) dest
-- | Flushes a file handle and calls the /shutdown/ system call so as
-- to write an EOF to a socket while still being able to read from it.
-- This is very important when the same file handle is being used to
-- to read data in an 'Onum' and to write data in an 'Iter'. Proper
-- protocol functioning may require the 'Iter' to send an EOF (e.g., a
-- TCP FIN segment), but the 'Onum' may still be reading from the
-- socket in a different thread.
hShutdown :: Handle -> CInt -> IO Int
hShutdown h how = do
hFlush h
wantWritableHandle "hShutdown" h $ \Handle__ {haDevice = dev} ->
case cast dev of
Just (FD {fdFD = fd}) -> liftM fromEnum $ c_shutdown fd how
Nothing -> ioError (ioeSetErrorString
(mkIOError illegalOperationErrorType
"hShutdown" (Just h) Nothing)
"handle is not a file descriptor")
--
-- Debugging
--
-- | For debugging, print a tag along with the current residual input.
-- Not referentially transparent.
traceInput :: (ChunkData t, Monad m) => String -> Iter t m ()
traceInput tag = Iter $ \c -> trace (tag ++ ": " ++ show c) $ Done () c
-- | For debugging. Print the current thread ID and a message. Not
-- referentially transparent.
traceI :: (ChunkData t, Monad m) => String -> Iter t m ()
traceI msg = Iter $ \c -> inlinePerformIO $ do
tid <- myThreadId
traceIO $ show tid ++ ": " ++ msg
return $ Done () c
|
scslab/iterIO
|
Data/IterIO/Extra.hs
|
bsd-3-clause
| 8,568 | 0 | 18 | 2,553 | 1,507 | 785 | 722 | 103 | 3 |
import Data.List (sortOn, minimumBy)
import Data.Function (on)
type Point = (Double, Double)
ccw :: Point -> Point -> Point -> Double
ccw (xa, ya) (xb, yb) (xc, yc) = (xb - xa) * (yc - ya) - (yb - ya) * (xc - xa)
grahamScan :: [Point] -> [Point]
grahamScan [] = []
grahamScan pts = wrap sortedPts [p0]
where p0@(x, y)= minimumBy (compare `on` snd) pts
sortedPts = sortOn (\(px, py) -> atan2 (py-y) (px-x) ) $ filter (/=p0) pts
wrap [] ps = ps
wrap (s:ss) [p] = wrap ss [s, p]
wrap (s:ss) (p1:p2:ps)
| ccw s p1 p2 > 0 = wrap (s:ss) (p2:ps)
| otherwise = wrap ss (s:p1:p2:ps)
main = do
-- We build the set of points of integer coordinates within a circle of radius 5
let pts = [(x,y) | x<-[-5..5], y<-[-5..5], x^2+y^2<=5^2]
-- And extract the convex hull
print $ grahamScan pts
|
Gathros/algorithm-archive
|
contents/graham_scan/code/haskell/grahamScan.hs
|
mit
| 848 | 6 | 16 | 223 | 473 | 258 | 215 | 18 | 3 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Serials.Model.Scan where
import Data.Time
import Data.Text
import Data.Aeson
import Data.Data
import Database.RethinkDB.NoClash
import GHC.Generics
data Scan = Scan {
date :: UTCTime,
total :: Int,
new :: [Text],
updated :: [Text]
} deriving (Show, Eq, Generic)
instance ToJSON Scan
instance FromJSON Scan
instance ToDatum Scan
instance FromDatum Scan
|
seanhess/serials
|
server/Serials/Model/Scan.hs
|
mit
| 440 | 0 | 9 | 72 | 122 | 71 | 51 | 19 | 0 |
module Lib.Makefile.InstantiatePattern
( instantiatePatternByOutput
, instantiatePatternByMatch
) where
import Prelude.Compat hiding (FilePath)
import Control.Monad (guard, msum)
import Lib.FilePath ((</>), FilePath, splitFileName)
import BMake.Interpreter (interpolateCmds)
import Lib.Makefile.Types
import qualified Lib.StringPattern as StringPattern
plugFilePattern :: StringPattern.Match -> FilePattern -> Maybe FilePath
plugFilePattern match (FilePattern dir file) = (dir </>) <$> StringPattern.plug match file
instantiatePatternByMatch :: StringPattern.Match -> Pattern -> Maybe Target
instantiatePatternByMatch match (Target outputs inputs ooInputs cmds pos) =
interpolateCmds mStem <$>
( Target
<$> mPluggedOutputs
<*> mPluggedInputs
<*> mPluggedOOInputs
<*> pure cmds
<*> pure pos
)
where
mStem = Just $ StringPattern.matchPlaceHolder1 match
plugInputMatch (InputPattern pat) = plugFilePattern match pat
plugInputMatch (InputPath str) = Just str
mPluggedOutputs = traverse (plugFilePattern match) outputs
mPluggedInputs = traverse plugInputMatch inputs
mPluggedOOInputs = traverse plugInputMatch ooInputs
instantiatePatternByOutput :: FilePath -> Pattern -> Maybe Target
instantiatePatternByOutput outputPath target =
msum $ map tryMatchOutput (targetOutputs target)
where
(outputDir, outputFile) = splitFileName outputPath
tryMatchOutput (FilePattern patDir patFile) = do
guard (patDir == outputDir)
outputMatch <- StringPattern.match patFile outputFile
instantiatePatternByMatch outputMatch target
|
buildsome/buildsome
|
src/Lib/Makefile/InstantiatePattern.hs
|
gpl-2.0
| 1,606 | 0 | 11 | 261 | 407 | 212 | 195 | 34 | 2 |
{-# language
ExistentialQuantification
#-}
module Rasa.Ext.Views.Internal.AnyRenderable
( AnyRenderable(..)
) where
import Rasa.Ext
data AnyRenderable =
forall r. Renderable r => AnyRenderable r
instance Renderable AnyRenderable where
render width height scrollAmt (AnyRenderable r) = render width height scrollAmt r
|
samcal/rasa
|
rasa-ext-views/src/Rasa/Ext/Views/Internal/AnyRenderable.hs
|
gpl-3.0
| 331 | 0 | 8 | 52 | 82 | 46 | 36 | 9 | 0 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Type.Coercion
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : not portable
--
-- Definition of representational equality ('Coercion').
--
-- @since 4.7.0.0
-----------------------------------------------------------------------------
module Data.Type.Coercion
( Coercion(..)
, coerceWith
, gcoerceWith
, sym
, trans
, repr
, TestCoercion(..)
) where
import qualified Data.Type.Equality as Eq
import Data.Maybe
import GHC.Enum
import GHC.Show
import GHC.Read
import GHC.Base
-- | Representational equality. If @Coercion a b@ is inhabited by some terminating
-- value, then the type @a@ has the same underlying representation as the type @b@.
--
-- To use this equality in practice, pattern-match on the @Coercion a b@ to get out
-- the @Coercible a b@ instance, and then use 'coerce' to apply it.
--
-- @since 4.7.0.0
data Coercion a b where
Coercion :: Coercible a b => Coercion a b
-- with credit to Conal Elliott for 'ty', Erik Hesselink & Martijn van
-- Steenbergen for 'type-equality', Edward Kmett for 'eq', and Gabor Greif
-- for 'type-eq'
-- | Type-safe cast, using representational equality
coerceWith :: Coercion a b -> a -> b
coerceWith Coercion x = coerce x
-- | Generalized form of type-safe cast using representational equality
--
-- @since 4.10.0.0
gcoerceWith :: Coercion a b -> (Coercible a b => r) -> r
gcoerceWith Coercion x = x
-- | Symmetry of representational equality
sym :: Coercion a b -> Coercion b a
sym Coercion = Coercion
-- | Transitivity of representational equality
trans :: Coercion a b -> Coercion b c -> Coercion a c
trans Coercion Coercion = Coercion
-- | Convert propositional (nominal) equality to representational equality
repr :: (a Eq.:~: b) -> Coercion a b
repr Eq.Refl = Coercion
deriving instance Eq (Coercion a b)
deriving instance Show (Coercion a b)
deriving instance Ord (Coercion a b)
-- | @since 4.7.0.0
deriving instance Coercible a b => Read (Coercion a b)
-- | @since 4.7.0.0
instance Coercible a b => Enum (Coercion a b) where
toEnum 0 = Coercion
toEnum _ = errorWithoutStackTrace "Data.Type.Coercion.toEnum: bad argument"
fromEnum Coercion = 0
-- | @since 4.7.0.0
deriving instance Coercible a b => Bounded (Coercion a b)
-- | This class contains types where you can learn the equality of two types
-- from information contained in /terms/. Typically, only singleton types should
-- inhabit this class.
class TestCoercion f where
-- | Conditionally prove the representational equality of @a@ and @b@.
testCoercion :: f a -> f b -> Maybe (Coercion a b)
-- | @since 4.7.0.0
instance TestCoercion ((Eq.:~:) a) where
testCoercion Eq.Refl Eq.Refl = Just Coercion
-- | @since 4.10.0.0
instance TestCoercion ((Eq.:~~:) a) where
testCoercion Eq.HRefl Eq.HRefl = Just Coercion
-- | @since 4.7.0.0
instance TestCoercion (Coercion a) where
testCoercion Coercion Coercion = Just Coercion
|
ezyang/ghc
|
libraries/base/Data/Type/Coercion.hs
|
bsd-3-clause
| 3,477 | 0 | 11 | 646 | 602 | 335 | 267 | 53 | 1 |
-- |Convenient functions for parsing JSON responses. Use these
-- functions to write the 'readJSON' method of the 'JSON' class.
module Database.CouchDB.JSON
( jsonString
, jsonInt
, jsonObject
, jsonField
, jsonBool
, jsonIsTrue
) where
import Text.JSON
import Data.Ratio (numerator,denominator)
jsonString :: JSValue -> Result String
jsonString (JSString s) = return (fromJSString s)
jsonString _ = fail "expected a string"
jsonInt :: (Integral n) => JSValue -> Result n
jsonInt (JSRational _ r) = case (numerator r, denominator r) of
(n,1) -> return (fromIntegral n)
otherwise -> fail "expected an integer; got a rational"
jsonInt _ = fail "expected an integer"
jsonObject :: JSValue -> Result [(String,JSValue)]
jsonObject (JSObject obj) = return (fromJSObject obj)
jsonObject v = fail $ "expected an object, got " ++ (show v)
jsonBool :: JSValue -> Result Bool
jsonBool (JSBool b) = return b
jsonBool v = fail $ "expected a boolean value, got " ++ show v
-- |Extract a field as a value of type 'a'. If the field does not
-- exist or cannot be parsed as type 'a', fail.
jsonField :: JSON a => String -> [(String,JSValue)] -> Result a
jsonField field obj = case lookup field obj of
Just v -> readJSON v
Nothing -> fail $ "could not find the field " ++ field
-- |'True' when the field is defined and is true. Otherwise, 'False'.
jsonIsTrue :: String -> [(String,JSValue)] -> Result Bool
jsonIsTrue field obj = case lookup field obj of
Just (JSBool True) -> return True
otherwise -> return False
|
arjunguha/haskell-couchdb
|
src/Database/CouchDB/JSON.hs
|
bsd-3-clause
| 1,532 | 0 | 10 | 291 | 452 | 233 | 219 | 31 | 2 |
foo =
let (xs, ys) = ([1,2..3], [4,5..6]) in
bar
|
mpickering/ghc-exactprint
|
tests/examples/ghc710/DroppedComma.hs
|
bsd-3-clause
| 55 | 0 | 10 | 16 | 46 | 26 | 20 | 3 | 1 |
{-# LANGUAGE DataKinds, GADTs, LambdaCase, ViewPatterns #-}
module Commands.Frontends.Dragon13.Optimize where
import Commands.Extra
import Commands.Frontends.Dragon13.Lens
import Commands.Frontends.Dragon13.Types
import Commands.LHS
import Control.Lens
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NonEmpty
import Data.Semigroup.Applicative (Ap (..))
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as T
import Data.Bifunctor (second)
import Data.Either (partitionEithers)
import qualified Data.List as List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
-- | a grammar can be normalized/optimized with its @i@ and @n@ type parameters.
type DNSGrammarOptimizeable t n = DNSGrammar DNSInfo t n
-- | see 'simplifyGrammar'.
type DNSProductionOptimizeable t n = DNSProduction DNSInfo t n
-- | see 'vocabularizeGrammar'
type DNSVocabularyOptimizeable t n = DNSVocabulary DNSInfo t n
-- | see ''. an edge in an adjacency graph.
type DNSAdjacency t n = Adjacency (SomeDNSLHS n) (DNSProductionOptimizeable t n)
-- | see 'inlineGrammar'. quick access to the right-hand side of a production to be inlined.
type DNSInlined t n = Map (SomeDNSLHS n) (DNSRHS t n)
-- | see 'vocabularizeGrammar'
type DNSVocabularized n = Map n (DNSLHS LHSList LHSDefined n)
-- ================================================================ --
{-| transforms a 'DNSGrammar' into one that Dragon NaturallySpeaking accepts:
* grammars with recursive productions crash Dragon
NaturallySpeaking (no cycle detection I guess?)
* grammars that are "too complex" (by some opaque metric) throw a
@BadGrammar@ exception:
inlining decreases depth by increasing breadth
TODO prop> introduces no naming collisions
-}
optimizeGrammar' :: (Eq t) => DnsOptimizationSettings -> DNSGrammar DNSInfo t LHS -> DNSGrammar DNSInfo t Text
optimizeGrammar' settings
= tidyupGrammar
-- . expandGrammar
. vocabularizeGrammar
. inlineGrammar settings
. simplifyGrammar
optimizeDNSInfoGrammar :: (Eq t, Ord n) => DnsOptimizationSettings -> DNSGrammar DNSInfo t n -> DNSGrammar DNSInfo t n
optimizeDNSInfoGrammar settings
= vocabularizeGrammar
. inlineGrammar settings
. simplifyGrammar
optimizeAnyDNSGrammar :: (Eq t, Ord n) => DnsOptimizationSettings -> DNSGrammar i t n -> DNSGrammar i t n
optimizeAnyDNSGrammar _settings
= vocabularizeGrammar
. simplifyGrammar
{- |
-- TODO prop> \(NonEmpty ls) -> length ls <= expandProductionCycle_measure ls
-}
expandProductionCycle_measure :: [DNSProductionOptimizeable t n] -> Natural
expandProductionCycle_measure ps = n + (n * d)
where
n = List.genericLength ps
d = expandProductionMaxDepth ps
{- | for a cycle of mutually-recursive productions, take the 'maximum'
of their 'dnsExpand's.
since we must expand each production to the
same depth, and since each production can be configured with its own
depth, we need some aggregate.
-}
expandProductionMaxDepth :: [DNSProductionOptimizeable t n] -> Natural
expandProductionMaxDepth
= maximum
. fmap (\p -> p ^. dnsProductionInfo.dnsExpand)
-- ================================================================ --
{-| inline any "small" productions.
-}
inlineGrammar :: (Ord n) => DnsOptimizationSettings -> DNSGrammar DNSInfo t n -> DNSGrammar DNSInfo t n
-- inlineGrammar = inlineGrammar'
inlineGrammar settings grammar = inlineGrammar' grammar'
where
grammar' = if settings^.dnsOptimizeInlineSmall
then (grammar & over (dnsProductions.each) markInlinedIfSmall)
else grammar
-- NOTE markInlinedIfSmall doesn't need to be iterated, as inlining only increases the size of a right-hand side
{-| we don't inline away 'DNSVocabulary's because they:
* have simple names, for easy debugging.
* are "cheap" wrt Dragon NaturallySpeaking's opaque grammar-complexity measure.
the 'dnsExport' is never inlined away.
-}
inlineGrammar' :: (Ord n) => DNSGrammar DNSInfo t n -> DNSGrammar DNSInfo t n
inlineGrammar' (DNSGrammar (_e:|_ps) _vs _is) = DNSGrammar (e:|ps) _vs _is
where
e = inlineProduction theInlined $ _e
ps = inlineProduction theInlined <$> notInlined
theInlined = yesInlined -- TODO rewriteOn each other?
(yesInlined, notInlined) = partitionInlined _ps
-- -- | assumes the 'DNSInlined' are acyclic wrt each other: otherwise, doesn't terminate.
-- inlineAway :: (Ord n) => DNSInlined t n -> [DNSProduction DNSInfo t n] -> [DNSProduction DNSInfo t n]
-- inlineAway = undefined -- TODO rewriteOn?
inlineProduction :: (Ord n) => DNSInlined t n -> DNSProduction DNSInfo t n -> DNSProduction DNSInfo t n
inlineProduction lrs = rewriteOn dnsProductionRHS $ \case
DNSNonTerminal l -> shouldInlineLHS lrs l
_ -> Nothing
shouldInlineLHS :: (Ord n) => DNSInlined t n -> SomeDNSLHS n -> Maybe (DNSRHS t n)
shouldInlineLHS lrs l = Map.lookup l lrs
partitionInlined
:: (Ord n)
=> [DNSProduction DNSInfo t n]
-> ( DNSInlined t n , [DNSProduction DNSInfo t n] )
partitionInlined ps = (yesInlined, notInlined) -- TODO don't in-line cycles
where
yesInlined = Map.fromList . fmap (\(DNSProduction _ l r) -> (SomeDNSLHS l, r)) $ _yesInlined
(_yesInlined, notInlined) = List.partition (view (dnsProductionInfo.dnsInline)) ps
markInlinedIfSmall :: DNSProduction DNSInfo t n -> DNSProduction DNSInfo t n
markInlinedIfSmall (DNSProduction i l r) = DNSProduction i' l r
where
i' = if isDNSRHSSmall r
then i & set dnsInline True
else i
{-| any right-hand side without non-singleton 'DNSSequence' or 'DNSAlternatives' is small, even nested
-}
isDNSRHSSmall :: DNSRHS t n -> Bool
isDNSRHSSmall = \case
DNSTerminal {} -> True
DNSNonTerminal {} -> True
DNSOptional r -> isDNSRHSSmall r
DNSMultiple r -> isDNSRHSSmall r
DNSSequence (r :| []) -> isDNSRHSSmall r
DNSAlternatives (r :| []) -> isDNSRHSSmall r
_ -> False
-- ================================================================ --
-- |
-- TODO prop>
vocabularizeGrammar :: (Ord n, Eq t) => DNSGrammar i t n -> DNSGrammar i t n
vocabularizeGrammar (DNSGrammar _ps _vs _is) = DNSGrammar ps vs _is
where
ps = rules2lists vocabularized <$> productions
vs = vocabularies <> _vs
vocabularized = Map.fromList . fmap (\(DNSList n) -> (n, DNSList n)) $ (vocabularies ^.. each.dnsVocabularyLHS) -- TODO partial function
(productions, vocabularies) = partitionVocabularizables _ps
-- |
partitionVocabularizables
:: NonEmpty (DNSProduction i t n)
-> (NonEmpty (DNSProduction i t n), [DNSVocabulary i t n])
partitionVocabularizables (e:|_ps) = (e:|ps, vs)
where
(ps, vs) = partitionEithers . fmap canVocabularize $ _ps
-- |
canVocabularize :: DNSProduction i t n -> Either (DNSProduction i t n) (DNSVocabulary i t n)
canVocabularize p@(DNSProduction i (DNSRule n) r) = case (getAp . onlyTokens) r of
Nothing -> Left p
Just ts -> Right $ DNSVocabulary i (DNSList n) ts -- make sure this doesn't introduce a naming conflict with existing DNSList. might be best to just treat rules and lists as if they shared the same namespace.
{- | returns all the tokens in the right-hand side, but only if that
right-hand side has only tokens (or nested alternatives thereof).
>>> :set -XOverloadedLists -XOverloadedStrings
>>> getApp $ onlyTokens $ DNSTerminal "one"
Just [DNSToken "one"]
>>> getApp $ onlyTokens $ DNSSequence ["one"]
Nothing
>>> getApp $ onlyTokens $ DNSAlternatives ["one", DNSNonTerminal undefined]
Nothing
>>> getApp $ onlyTokens $ DNSAlternatives ["one", DNSAlternatives ["two", "three"], "four"]
Just [DNSToken "one",DNSToken "two",DNSToken "three",DNSToken "four"]
@('foldMap' onlyTokens :: [DNSRHS t n] -> 'Ap' Maybe [t])@,
where the 'Foldable' is @[]@ and the 'Monoid' is @'Ap' Maybe [_]@,
has the correct short-circuiting behavior.
(see <https://byorgey.wordpress.com/2011/04/18/monoids-for-maybe/>)
-}
onlyTokens :: DNSRHS t n -> Ap Maybe [DNSToken t]
onlyTokens = \case
DNSTerminal t -> (Ap . Just) [t]
DNSAlternatives rs -> foldMap onlyTokens rs
_ -> Ap Nothing
-- |
rules2lists :: (Ord n) => DNSVocabularized n -> DNSProduction i t n -> DNSProduction i t n
rules2lists ls = transformOn dnsProductionRHS $ \case
DNSNonTerminal (SomeDNSLHS (DNSRule ((flip Map.lookup) ls -> Just l))) -> DNSNonTerminal (SomeDNSLHS l)
r -> r
-- ================================================================ --
-- | Tidy up the grammar by contacting the left-hand sides, without collisions.
tidyupGrammar :: DNSGrammar i t LHS -> DNSGrammar i t Text
tidyupGrammar = second (T.pack . showLHS . tidyupLHS)
-- |
tidyupLHS :: LHS -> LHS
tidyupLHS = bimapLHS fGUI fInt
where
fGUI (GUI (Package _) (Module _) (Identifier occ)) = GUI (Package "") (Module "") (Identifier occ)
fInt = id
-- TODO safely tidyup i.e. unambiguously. compare each against all, with getNames. Build a Trie?
-- ================================================================ --
simplifyGrammar :: (Eq t, Eq n) => DNSGrammar i t n -> DNSGrammar i t n
simplifyGrammar = over (dnsProductions.each.dnsProductionRHS) (simplifyRHS)
{- |
all simplifications are "inductive" (I think that's the word), i.e. they structurally reduce the input. Thus, we know 'rewrite' terminates.
-}
simplifyRHS :: (Eq t, Eq n) => DNSRHS t n -> DNSRHS t n
simplifyRHS = rewrite $ \case
-- singleton
DNSSequence (r :| []) -> Just r
DNSAlternatives (r :| []) -> Just r
-- idempotent
DNSMultiple (DNSMultiple r) -> Just$ DNSMultiple r -- TODO valid?
DNSOptional (DNSOptional r) -> Just$ DNSOptional r -- TODO valid?
-- additive identity. terminates.
DNSAlternatives (filterAway (==ZeroDNSRHS) -> Just []) -> Just$ ZeroDNSRHS
DNSAlternatives (filterAway (==ZeroDNSRHS) -> Just (r:rs)) -> Just$ DNSAlternatives (r :| rs)
-- multiplicative identity. terminates.
DNSSequence (filterAway (==UnitDNSRHS) -> Just []) -> Just$ UnitDNSRHS
DNSSequence (filterAway (==UnitDNSRHS) -> Just (r:rs)) -> Just$ DNSSequence (r :| rs)
--
_ -> Nothing
{- |
@
filter (not p) <$> filterAway p xs = filterAway p xs
filterAway p xs = Nothing | Just (filter (not p) xs)
(<) (length <$> filterAway p xs) (Just (length xs))
-- Nothing | Just True
fromJust (filterAway p xs) < (length xs)
True
"inductive"
case filterAway p xs of
Nothing -> True
Just ys -> length ys < length xs
case filterAway (==x) xs of
Nothing -> not (x elem xs)
Just ys -> not (x elem ys)
@
@
case filterAway p xs of
Nothing -> -- nothing was filtered away ("input preserved")
Just [] -> -- everything was filtered away
Just (x:xs) -> -- some items were filtered away
@
-}
filterAway :: (a -> Bool) -> NonEmpty a -> Maybe [a]
filterAway p xs = case NonEmpty.partition p xs of -- partition odd [1,2,3,4] == ([1,3], [2,4])
([],_) -> Nothing
(_,ys) -> Just ys
|
sboosali/commands-frontend-DragonNaturallySpeaking
|
sources/Commands/Frontends/Dragon13/Optimize.hs
|
bsd-3-clause
| 10,988 | 0 | 19 | 2,065 | 2,373 | 1,249 | 1,124 | -1 | -1 |
{-# language CPP #-}
{-# language MultiParamTypeClasses #-}
#ifndef ENABLE_INTERNAL_DOCUMENTATION
{-# OPTIONS_HADDOCK hide #-}
#endif
#if __GLASGOW_HASKELL__ >= 800
{-# options_ghc -Wno-redundant-constraints #-}
#endif
module OpenCV.Internal.ImgProc.MiscImgTransform.ColorCodes where
import "base" Data.Int ( Int32 )
import "base" Data.Proxy ( Proxy(..) )
import "base" Data.Word
import "base" GHC.TypeLits
import "this" OpenCV.Internal.ImgProc.MiscImgTransform
import "this" OpenCV.TypeLevel
--------------------------------------------------------------------------------
{- | Valid color conversions described by the following graph:
<<doc/color_conversions.png>>
-}
class ColorConversion (fromColor :: ColorCode) (toColor :: ColorCode) where
colorConversionCode :: Proxy fromColor -> Proxy toColor -> Int32
-- | Names of color encodings
data ColorCode
= BayerBG -- ^ ('bayerBG') Bayer pattern with BG in the second row, second and third column
| BayerGB -- ^ ('bayerGB') Bayer pattern with GB in the second row, second and third column
| BayerGR -- ^ ('bayerGR') Bayer pattern with GR in the second row, second and third column
| BayerRG -- ^ ('bayerRG') Bayer pattern with RG in the second row, second and third column
| BGR -- ^ ('bgr') 24 bit RGB color space with channels: (B8:G8:R8)
| BGR555 -- ^ ('bgr555') 15 bit RGB color space
| BGR565 -- ^ ('bgr565') 16 bit RGB color space
| BGRA -- ^ ('bgra') 32 bit RGBA color space with channels: (B8:G8:R8:A8)
| BGRA_I420 -- ^ ('bgra_I420')
| BGRA_IYUV -- ^ ('bgra_IYUV')
| BGRA_NV12 -- ^ ('bgra_NV12')
| BGRA_NV21 -- ^ ('bgra_NV21')
| BGRA_UYNV -- ^ ('bgra_UYNV')
| BGRA_UYVY -- ^ ('bgra_UYVY')
| BGRA_Y422 -- ^ ('bgra_Y422')
| BGRA_YUNV -- ^ ('bgra_YUNV')
| BGRA_YUY2 -- ^ ('bgra_YUY2')
| BGRA_YUYV -- ^ ('bgra_YUYV')
| BGRA_YV12 -- ^ ('bgra_YV12')
| BGRA_YVYU -- ^ ('bgra_YVYU')
| BGR_EA -- ^ ('bgr_EA') Edge-Aware
| BGR_FULL -- ^ ('bgr_FULL')
| BGR_I420 -- ^ ('bgr_I420')
| BGR_IYUV -- ^ ('bgr_IYUV')
| BGR_NV12 -- ^ ('bgr_NV12')
| BGR_NV21 -- ^ ('bgr_NV21')
| BGR_UYNV -- ^ ('bgr_UYNV')
| BGR_UYVY -- ^ ('bgr_UYVY')
| BGR_VNG -- ^ ('bgr_VNG')
| BGR_Y422 -- ^ ('bgr_Y422')
| BGR_YUNV -- ^ ('bgr_YUNV')
| BGR_YUY2 -- ^ ('bgr_YUY2')
| BGR_YUYV -- ^ ('bgr_YUYV')
| BGR_YV12 -- ^ ('bgr_YV12')
| BGR_YVYU -- ^ ('bgr_YVYU')
| GRAY -- ^ ('gray') 8 bit single channel color space
| GRAY_420 -- ^ ('gray_420')
| GRAY_I420 -- ^ ('gray_I420')
| GRAY_IYUV -- ^ ('gray_IYUV')
| GRAY_NV12 -- ^ ('gray_NV12')
| GRAY_NV21 -- ^ ('gray_NV21')
| GRAY_UYNV -- ^ ('gray_UYNV')
| GRAY_UYVY -- ^ ('gray_UYVY')
| GRAY_Y422 -- ^ ('gray_Y422')
| GRAY_YUNV -- ^ ('gray_YUNV')
| GRAY_YUY2 -- ^ ('gray_YUY2')
| GRAY_YUYV -- ^ ('gray_YUYV')
| GRAY_YV12 -- ^ ('gray_YV12')
| GRAY_YVYU -- ^ ('gray_YVYU')
| HLS -- ^ ('hls')
| HLS_FULL -- ^ ('hls_FULL')
| HSV -- ^ ('hsv')
| HSV_FULL -- ^ ('hsv_FULL')
| Lab -- ^ ('lab')
| LBGR -- ^ ('lbgr')
| LRGB -- ^ ('lrgb')
| Luv -- ^ ('luv')
| MRGBA -- ^ ('mrgba')
| RGB -- ^ ('rgb') 24 bit RGB color space with channels: (R8:G8:B8)
| RGBA -- ^ ('rgba')
| RGBA_I420 -- ^ ('rgba_I420')
| RGBA_IYUV -- ^ ('rgba_IYUV')
| RGBA_NV12 -- ^ ('rgba_NV12')
| RGBA_NV21 -- ^ ('rgba_NV21')
| RGBA_UYNV -- ^ ('rgba_UYNV')
| RGBA_UYVY -- ^ ('rgba_UYVY')
| RGBA_Y422 -- ^ ('rgba_Y422')
| RGBA_YUNV -- ^ ('rgba_YUNV')
| RGBA_YUY2 -- ^ ('rgba_YUY2')
| RGBA_YUYV -- ^ ('rgba_YUYV')
| RGBA_YV12 -- ^ ('rgba_YV12')
| RGBA_YVYU -- ^ ('rgba_YVYU')
| RGB_EA -- ^ ('rgb_EA') Edge-Aware
| RGB_FULL -- ^ ('rgb_FULL')
| RGB_I420 -- ^ ('rgb_I420')
| RGB_IYUV -- ^ ('rgb_IYUV')
| RGB_NV12 -- ^ ('rgb_NV12')
| RGB_NV21 -- ^ ('rgb_NV21')
| RGB_UYNV -- ^ ('rgb_UYNV')
| RGB_UYVY -- ^ ('rgb_UYVY')
| RGB_VNG -- ^ ('rgb_VNG')
| RGB_Y422 -- ^ ('rgb_Y422')
| RGB_YUNV -- ^ ('rgb_YUNV')
| RGB_YUY2 -- ^ ('rgb_YUY2')
| RGB_YUYV -- ^ ('rgb_YUYV')
| RGB_YV12 -- ^ ('rgb_YV12')
| RGB_YVYU -- ^ ('rgb_YVYU')
| XYZ -- ^ ('xyz')
| YCrCb -- ^ ('yCrCb')
| YUV -- ^ ('yuv')
| YUV420p -- ^ ('yuv420p')
| YUV420sp -- ^ ('yuv420sp')
| YUV_I420 -- ^ ('yuv_I420')
| YUV_IYUV -- ^ ('yuv_IYUV')
| YUV_YV12 -- ^ ('yuv_YV12')
--------------------------------------------------------------------------------
bayerBG :: Proxy 'BayerBG ; bayerBG = Proxy
bayerGB :: Proxy 'BayerGB ; bayerGB = Proxy
bayerGR :: Proxy 'BayerGR ; bayerGR = Proxy
bayerRG :: Proxy 'BayerRG ; bayerRG = Proxy
bgr :: Proxy 'BGR ; bgr = Proxy
bgr555 :: Proxy 'BGR555 ; bgr555 = Proxy
bgr565 :: Proxy 'BGR565 ; bgr565 = Proxy
bgra :: Proxy 'BGRA ; bgra = Proxy
bgra_I420 :: Proxy 'BGRA_I420; bgra_I420 = Proxy
bgra_IYUV :: Proxy 'BGRA_IYUV; bgra_IYUV = Proxy
bgra_NV12 :: Proxy 'BGRA_NV12; bgra_NV12 = Proxy
bgra_NV21 :: Proxy 'BGRA_NV21; bgra_NV21 = Proxy
bgra_UYNV :: Proxy 'BGRA_UYNV; bgra_UYNV = Proxy
bgra_UYVY :: Proxy 'BGRA_UYVY; bgra_UYVY = Proxy
bgra_Y422 :: Proxy 'BGRA_Y422; bgra_Y422 = Proxy
bgra_YUNV :: Proxy 'BGRA_YUNV; bgra_YUNV = Proxy
bgra_YUY2 :: Proxy 'BGRA_YUY2; bgra_YUY2 = Proxy
bgra_YUYV :: Proxy 'BGRA_YUYV; bgra_YUYV = Proxy
bgra_YV12 :: Proxy 'BGRA_YV12; bgra_YV12 = Proxy
bgra_YVYU :: Proxy 'BGRA_YVYU; bgra_YVYU = Proxy
bgr_EA :: Proxy 'BGR_EA ; bgr_EA = Proxy
bgr_FULL :: Proxy 'BGR_FULL ; bgr_FULL = Proxy
bgr_I420 :: Proxy 'BGR_I420 ; bgr_I420 = Proxy
bgr_IYUV :: Proxy 'BGR_IYUV ; bgr_IYUV = Proxy
bgr_NV12 :: Proxy 'BGR_NV12 ; bgr_NV12 = Proxy
bgr_NV21 :: Proxy 'BGR_NV21 ; bgr_NV21 = Proxy
bgr_UYNV :: Proxy 'BGR_UYNV ; bgr_UYNV = Proxy
bgr_UYVY :: Proxy 'BGR_UYVY ; bgr_UYVY = Proxy
bgr_VNG :: Proxy 'BGR_VNG ; bgr_VNG = Proxy
bgr_Y422 :: Proxy 'BGR_Y422 ; bgr_Y422 = Proxy
bgr_YUNV :: Proxy 'BGR_YUNV ; bgr_YUNV = Proxy
bgr_YUY2 :: Proxy 'BGR_YUY2 ; bgr_YUY2 = Proxy
bgr_YUYV :: Proxy 'BGR_YUYV ; bgr_YUYV = Proxy
bgr_YV12 :: Proxy 'BGR_YV12 ; bgr_YV12 = Proxy
bgr_YVYU :: Proxy 'BGR_YVYU ; bgr_YVYU = Proxy
gray :: Proxy 'GRAY ; gray = Proxy
gray_420 :: Proxy 'GRAY_420 ; gray_420 = Proxy
gray_I420 :: Proxy 'GRAY_I420; gray_I420 = Proxy
gray_IYUV :: Proxy 'GRAY_IYUV; gray_IYUV = Proxy
gray_NV12 :: Proxy 'GRAY_NV12; gray_NV12 = Proxy
gray_NV21 :: Proxy 'GRAY_NV21; gray_NV21 = Proxy
gray_UYNV :: Proxy 'GRAY_UYNV; gray_UYNV = Proxy
gray_UYVY :: Proxy 'GRAY_UYVY; gray_UYVY = Proxy
gray_Y422 :: Proxy 'GRAY_Y422; gray_Y422 = Proxy
gray_YUNV :: Proxy 'GRAY_YUNV; gray_YUNV = Proxy
gray_YUY2 :: Proxy 'GRAY_YUY2; gray_YUY2 = Proxy
gray_YUYV :: Proxy 'GRAY_YUYV; gray_YUYV = Proxy
gray_YV12 :: Proxy 'GRAY_YV12; gray_YV12 = Proxy
gray_YVYU :: Proxy 'GRAY_YVYU; gray_YVYU = Proxy
hls :: Proxy 'HLS ; hls = Proxy
hls_FULL :: Proxy 'HLS_FULL ; hls_FULL = Proxy
hsv :: Proxy 'HSV ; hsv = Proxy
hsv_FULL :: Proxy 'HSV_FULL ; hsv_FULL = Proxy
lab :: Proxy 'Lab ; lab = Proxy
lbgr :: Proxy 'LBGR ; lbgr = Proxy
lrgb :: Proxy 'LRGB ; lrgb = Proxy
luv :: Proxy 'Luv ; luv = Proxy
mrgba :: Proxy 'MRGBA ; mrgba = Proxy
rgb :: Proxy 'RGB ; rgb = Proxy
rgba :: Proxy 'RGBA ; rgba = Proxy
rgba_I420 :: Proxy 'RGBA_I420; rgba_I420 = Proxy
rgba_IYUV :: Proxy 'RGBA_IYUV; rgba_IYUV = Proxy
rgba_NV12 :: Proxy 'RGBA_NV12; rgba_NV12 = Proxy
rgba_NV21 :: Proxy 'RGBA_NV21; rgba_NV21 = Proxy
rgba_UYNV :: Proxy 'RGBA_UYNV; rgba_UYNV = Proxy
rgba_UYVY :: Proxy 'RGBA_UYVY; rgba_UYVY = Proxy
rgba_Y422 :: Proxy 'RGBA_Y422; rgba_Y422 = Proxy
rgba_YUNV :: Proxy 'RGBA_YUNV; rgba_YUNV = Proxy
rgba_YUY2 :: Proxy 'RGBA_YUY2; rgba_YUY2 = Proxy
rgba_YUYV :: Proxy 'RGBA_YUYV; rgba_YUYV = Proxy
rgba_YV12 :: Proxy 'RGBA_YV12; rgba_YV12 = Proxy
rgba_YVYU :: Proxy 'RGBA_YVYU; rgba_YVYU = Proxy
rgb_EA :: Proxy 'RGB_EA ; rgb_EA = Proxy
rgb_FULL :: Proxy 'RGB_FULL ; rgb_FULL = Proxy
rgb_I420 :: Proxy 'RGB_I420 ; rgb_I420 = Proxy
rgb_IYUV :: Proxy 'RGB_IYUV ; rgb_IYUV = Proxy
rgb_NV12 :: Proxy 'RGB_NV12 ; rgb_NV12 = Proxy
rgb_NV21 :: Proxy 'RGB_NV21 ; rgb_NV21 = Proxy
rgb_UYNV :: Proxy 'RGB_UYNV ; rgb_UYNV = Proxy
rgb_UYVY :: Proxy 'RGB_UYVY ; rgb_UYVY = Proxy
rgb_VNG :: Proxy 'RGB_VNG ; rgb_VNG = Proxy
rgb_Y422 :: Proxy 'RGB_Y422 ; rgb_Y422 = Proxy
rgb_YUNV :: Proxy 'RGB_YUNV ; rgb_YUNV = Proxy
rgb_YUY2 :: Proxy 'RGB_YUY2 ; rgb_YUY2 = Proxy
rgb_YUYV :: Proxy 'RGB_YUYV ; rgb_YUYV = Proxy
rgb_YV12 :: Proxy 'RGB_YV12 ; rgb_YV12 = Proxy
rgb_YVYU :: Proxy 'RGB_YVYU ; rgb_YVYU = Proxy
xyz :: Proxy 'XYZ ; xyz = Proxy
yCrCb :: Proxy 'YCrCb ; yCrCb = Proxy
yuv :: Proxy 'YUV ; yuv = Proxy
yuv420p :: Proxy 'YUV420p ; yuv420p = Proxy
yuv420sp :: Proxy 'YUV420sp ; yuv420sp = Proxy
yuv_I420 :: Proxy 'YUV_I420 ; yuv_I420 = Proxy
yuv_IYUV :: Proxy 'YUV_IYUV ; yuv_IYUV = Proxy
yuv_YV12 :: Proxy 'YUV_YV12 ; yuv_YV12 = Proxy
--------------------------------------------------------------------------------
instance ColorConversion 'BGR 'BGRA where colorConversionCode _ _ = c'COLOR_BGR2BGRA
instance ColorConversion 'RGB 'RGBA where colorConversionCode _ _ = c'COLOR_RGB2RGBA
instance ColorConversion 'BGRA 'BGR where colorConversionCode _ _ = c'COLOR_BGRA2BGR
instance ColorConversion 'RGBA 'RGB where colorConversionCode _ _ = c'COLOR_RGBA2RGB
instance ColorConversion 'BGR 'RGBA where colorConversionCode _ _ = c'COLOR_BGR2RGBA
instance ColorConversion 'RGB 'BGRA where colorConversionCode _ _ = c'COLOR_RGB2BGRA
instance ColorConversion 'RGBA 'BGR where colorConversionCode _ _ = c'COLOR_RGBA2BGR
instance ColorConversion 'BGRA 'RGB where colorConversionCode _ _ = c'COLOR_BGRA2RGB
instance ColorConversion 'BGR 'RGB where colorConversionCode _ _ = c'COLOR_BGR2RGB
instance ColorConversion 'RGB 'BGR where colorConversionCode _ _ = c'COLOR_RGB2BGR
instance ColorConversion 'BGRA 'RGBA where colorConversionCode _ _ = c'COLOR_BGRA2RGBA
instance ColorConversion 'RGBA 'BGRA where colorConversionCode _ _ = c'COLOR_RGBA2BGRA
instance ColorConversion 'BGR 'GRAY where colorConversionCode _ _ = c'COLOR_BGR2GRAY
instance ColorConversion 'RGB 'GRAY where colorConversionCode _ _ = c'COLOR_RGB2GRAY
instance ColorConversion 'GRAY 'BGR where colorConversionCode _ _ = c'COLOR_GRAY2BGR
instance ColorConversion 'GRAY 'RGB where colorConversionCode _ _ = c'COLOR_GRAY2RGB
instance ColorConversion 'GRAY 'BGRA where colorConversionCode _ _ = c'COLOR_GRAY2BGRA
instance ColorConversion 'GRAY 'RGBA where colorConversionCode _ _ = c'COLOR_GRAY2RGBA
instance ColorConversion 'BGRA 'GRAY where colorConversionCode _ _ = c'COLOR_BGRA2GRAY
instance ColorConversion 'RGBA 'GRAY where colorConversionCode _ _ = c'COLOR_RGBA2GRAY
instance ColorConversion 'BGR 'BGR565 where colorConversionCode _ _ = c'COLOR_BGR2BGR565
instance ColorConversion 'RGB 'BGR565 where colorConversionCode _ _ = c'COLOR_RGB2BGR565
instance ColorConversion 'BGR565 'BGR where colorConversionCode _ _ = c'COLOR_BGR5652BGR
instance ColorConversion 'BGR565 'RGB where colorConversionCode _ _ = c'COLOR_BGR5652RGB
instance ColorConversion 'BGRA 'BGR565 where colorConversionCode _ _ = c'COLOR_BGRA2BGR565
instance ColorConversion 'RGBA 'BGR565 where colorConversionCode _ _ = c'COLOR_RGBA2BGR565
instance ColorConversion 'BGR565 'BGRA where colorConversionCode _ _ = c'COLOR_BGR5652BGRA
instance ColorConversion 'BGR565 'RGBA where colorConversionCode _ _ = c'COLOR_BGR5652RGBA
instance ColorConversion 'GRAY 'BGR565 where colorConversionCode _ _ = c'COLOR_GRAY2BGR565
instance ColorConversion 'BGR565 'GRAY where colorConversionCode _ _ = c'COLOR_BGR5652GRAY
instance ColorConversion 'BGR 'BGR555 where colorConversionCode _ _ = c'COLOR_BGR2BGR555
instance ColorConversion 'RGB 'BGR555 where colorConversionCode _ _ = c'COLOR_RGB2BGR555
instance ColorConversion 'BGR555 'BGR where colorConversionCode _ _ = c'COLOR_BGR5552BGR
instance ColorConversion 'BGR555 'RGB where colorConversionCode _ _ = c'COLOR_BGR5552RGB
instance ColorConversion 'BGRA 'BGR555 where colorConversionCode _ _ = c'COLOR_BGRA2BGR555
instance ColorConversion 'RGBA 'BGR555 where colorConversionCode _ _ = c'COLOR_RGBA2BGR555
instance ColorConversion 'BGR555 'BGRA where colorConversionCode _ _ = c'COLOR_BGR5552BGRA
instance ColorConversion 'BGR555 'RGBA where colorConversionCode _ _ = c'COLOR_BGR5552RGBA
instance ColorConversion 'GRAY 'BGR555 where colorConversionCode _ _ = c'COLOR_GRAY2BGR555
instance ColorConversion 'BGR555 'GRAY where colorConversionCode _ _ = c'COLOR_BGR5552GRAY
instance ColorConversion 'BGR 'XYZ where colorConversionCode _ _ = c'COLOR_BGR2XYZ
instance ColorConversion 'RGB 'XYZ where colorConversionCode _ _ = c'COLOR_RGB2XYZ
instance ColorConversion 'XYZ 'BGR where colorConversionCode _ _ = c'COLOR_XYZ2BGR
instance ColorConversion 'XYZ 'RGB where colorConversionCode _ _ = c'COLOR_XYZ2RGB
instance ColorConversion 'BGR 'YCrCb where colorConversionCode _ _ = c'COLOR_BGR2YCrCb
instance ColorConversion 'RGB 'YCrCb where colorConversionCode _ _ = c'COLOR_RGB2YCrCb
instance ColorConversion 'YCrCb 'BGR where colorConversionCode _ _ = c'COLOR_YCrCb2BGR
instance ColorConversion 'YCrCb 'RGB where colorConversionCode _ _ = c'COLOR_YCrCb2RGB
instance ColorConversion 'BGR 'HSV where colorConversionCode _ _ = c'COLOR_BGR2HSV
instance ColorConversion 'RGB 'HSV where colorConversionCode _ _ = c'COLOR_RGB2HSV
instance ColorConversion 'BGR 'Lab where colorConversionCode _ _ = c'COLOR_BGR2Lab
instance ColorConversion 'RGB 'Lab where colorConversionCode _ _ = c'COLOR_RGB2Lab
instance ColorConversion 'BGR 'Luv where colorConversionCode _ _ = c'COLOR_BGR2Luv
instance ColorConversion 'RGB 'Luv where colorConversionCode _ _ = c'COLOR_RGB2Luv
instance ColorConversion 'BGR 'HLS where colorConversionCode _ _ = c'COLOR_BGR2HLS
instance ColorConversion 'RGB 'HLS where colorConversionCode _ _ = c'COLOR_RGB2HLS
instance ColorConversion 'HSV 'BGR where colorConversionCode _ _ = c'COLOR_HSV2BGR
instance ColorConversion 'HSV 'RGB where colorConversionCode _ _ = c'COLOR_HSV2RGB
instance ColorConversion 'Lab 'BGR where colorConversionCode _ _ = c'COLOR_Lab2BGR
instance ColorConversion 'Lab 'RGB where colorConversionCode _ _ = c'COLOR_Lab2RGB
instance ColorConversion 'Luv 'BGR where colorConversionCode _ _ = c'COLOR_Luv2BGR
instance ColorConversion 'Luv 'RGB where colorConversionCode _ _ = c'COLOR_Luv2RGB
instance ColorConversion 'HLS 'BGR where colorConversionCode _ _ = c'COLOR_HLS2BGR
instance ColorConversion 'HLS 'RGB where colorConversionCode _ _ = c'COLOR_HLS2RGB
instance ColorConversion 'BGR 'HSV_FULL where colorConversionCode _ _ = c'COLOR_BGR2HSV_FULL
instance ColorConversion 'RGB 'HSV_FULL where colorConversionCode _ _ = c'COLOR_RGB2HSV_FULL
instance ColorConversion 'BGR 'HLS_FULL where colorConversionCode _ _ = c'COLOR_BGR2HLS_FULL
instance ColorConversion 'RGB 'HLS_FULL where colorConversionCode _ _ = c'COLOR_RGB2HLS_FULL
instance ColorConversion 'HSV 'BGR_FULL where colorConversionCode _ _ = c'COLOR_HSV2BGR_FULL
instance ColorConversion 'HSV 'RGB_FULL where colorConversionCode _ _ = c'COLOR_HSV2RGB_FULL
instance ColorConversion 'HLS 'BGR_FULL where colorConversionCode _ _ = c'COLOR_HLS2BGR_FULL
instance ColorConversion 'HLS 'RGB_FULL where colorConversionCode _ _ = c'COLOR_HLS2RGB_FULL
instance ColorConversion 'LBGR 'Lab where colorConversionCode _ _ = c'COLOR_LBGR2Lab
instance ColorConversion 'LRGB 'Lab where colorConversionCode _ _ = c'COLOR_LRGB2Lab
instance ColorConversion 'LBGR 'Luv where colorConversionCode _ _ = c'COLOR_LBGR2Luv
instance ColorConversion 'LRGB 'Luv where colorConversionCode _ _ = c'COLOR_LRGB2Luv
instance ColorConversion 'Lab 'LBGR where colorConversionCode _ _ = c'COLOR_Lab2LBGR
instance ColorConversion 'Lab 'LRGB where colorConversionCode _ _ = c'COLOR_Lab2LRGB
instance ColorConversion 'Luv 'LBGR where colorConversionCode _ _ = c'COLOR_Luv2LBGR
instance ColorConversion 'Luv 'LRGB where colorConversionCode _ _ = c'COLOR_Luv2LRGB
instance ColorConversion 'BGR 'YUV where colorConversionCode _ _ = c'COLOR_BGR2YUV
instance ColorConversion 'RGB 'YUV where colorConversionCode _ _ = c'COLOR_RGB2YUV
instance ColorConversion 'YUV 'BGR where colorConversionCode _ _ = c'COLOR_YUV2BGR
instance ColorConversion 'YUV 'RGB where colorConversionCode _ _ = c'COLOR_YUV2RGB
instance ColorConversion 'YUV 'RGB_NV12 where colorConversionCode _ _ = c'COLOR_YUV2RGB_NV12
instance ColorConversion 'YUV 'BGR_NV12 where colorConversionCode _ _ = c'COLOR_YUV2BGR_NV12
instance ColorConversion 'YUV 'RGB_NV21 where colorConversionCode _ _ = c'COLOR_YUV2RGB_NV21
instance ColorConversion 'YUV 'BGR_NV21 where colorConversionCode _ _ = c'COLOR_YUV2BGR_NV21
instance ColorConversion 'YUV420sp 'RGB where colorConversionCode _ _ = c'COLOR_YUV420sp2RGB
instance ColorConversion 'YUV420sp 'BGR where colorConversionCode _ _ = c'COLOR_YUV420sp2BGR
instance ColorConversion 'YUV 'RGBA_NV12 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_NV12
instance ColorConversion 'YUV 'BGRA_NV12 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_NV12
instance ColorConversion 'YUV 'RGBA_NV21 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_NV21
instance ColorConversion 'YUV 'BGRA_NV21 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_NV21
instance ColorConversion 'YUV420sp 'RGBA where colorConversionCode _ _ = c'COLOR_YUV420sp2RGBA
instance ColorConversion 'YUV420sp 'BGRA where colorConversionCode _ _ = c'COLOR_YUV420sp2BGRA
instance ColorConversion 'YUV 'RGB_YV12 where colorConversionCode _ _ = c'COLOR_YUV2RGB_YV12
instance ColorConversion 'YUV 'BGR_YV12 where colorConversionCode _ _ = c'COLOR_YUV2BGR_YV12
instance ColorConversion 'YUV 'RGB_IYUV where colorConversionCode _ _ = c'COLOR_YUV2RGB_IYUV
instance ColorConversion 'YUV 'BGR_IYUV where colorConversionCode _ _ = c'COLOR_YUV2BGR_IYUV
instance ColorConversion 'YUV 'RGB_I420 where colorConversionCode _ _ = c'COLOR_YUV2RGB_I420
instance ColorConversion 'YUV 'BGR_I420 where colorConversionCode _ _ = c'COLOR_YUV2BGR_I420
instance ColorConversion 'YUV420p 'RGB where colorConversionCode _ _ = c'COLOR_YUV420p2RGB
instance ColorConversion 'YUV420p 'BGR where colorConversionCode _ _ = c'COLOR_YUV420p2BGR
instance ColorConversion 'YUV 'RGBA_YV12 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_YV12
instance ColorConversion 'YUV 'BGRA_YV12 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_YV12
instance ColorConversion 'YUV 'RGBA_IYUV where colorConversionCode _ _ = c'COLOR_YUV2RGBA_IYUV
instance ColorConversion 'YUV 'BGRA_IYUV where colorConversionCode _ _ = c'COLOR_YUV2BGRA_IYUV
instance ColorConversion 'YUV 'RGBA_I420 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_I420
instance ColorConversion 'YUV 'BGRA_I420 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_I420
instance ColorConversion 'YUV420p 'RGBA where colorConversionCode _ _ = c'COLOR_YUV420p2RGBA
instance ColorConversion 'YUV420p 'BGRA where colorConversionCode _ _ = c'COLOR_YUV420p2BGRA
instance ColorConversion 'YUV 'GRAY_420 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_420
instance ColorConversion 'YUV 'GRAY_NV21 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_NV21
instance ColorConversion 'YUV 'GRAY_NV12 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_NV12
instance ColorConversion 'YUV 'GRAY_YV12 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_YV12
instance ColorConversion 'YUV 'GRAY_IYUV where colorConversionCode _ _ = c'COLOR_YUV2GRAY_IYUV
instance ColorConversion 'YUV 'GRAY_I420 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_I420
instance ColorConversion 'YUV420sp 'GRAY where colorConversionCode _ _ = c'COLOR_YUV420sp2GRAY
instance ColorConversion 'YUV420p 'GRAY where colorConversionCode _ _ = c'COLOR_YUV420p2GRAY
instance ColorConversion 'YUV 'RGB_UYVY where colorConversionCode _ _ = c'COLOR_YUV2RGB_UYVY
instance ColorConversion 'YUV 'BGR_UYVY where colorConversionCode _ _ = c'COLOR_YUV2BGR_UYVY
instance ColorConversion 'YUV 'RGB_Y422 where colorConversionCode _ _ = c'COLOR_YUV2RGB_Y422
instance ColorConversion 'YUV 'BGR_Y422 where colorConversionCode _ _ = c'COLOR_YUV2BGR_Y422
instance ColorConversion 'YUV 'RGB_UYNV where colorConversionCode _ _ = c'COLOR_YUV2RGB_UYNV
instance ColorConversion 'YUV 'BGR_UYNV where colorConversionCode _ _ = c'COLOR_YUV2BGR_UYNV
instance ColorConversion 'YUV 'RGBA_UYVY where colorConversionCode _ _ = c'COLOR_YUV2RGBA_UYVY
instance ColorConversion 'YUV 'BGRA_UYVY where colorConversionCode _ _ = c'COLOR_YUV2BGRA_UYVY
instance ColorConversion 'YUV 'RGBA_Y422 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_Y422
instance ColorConversion 'YUV 'BGRA_Y422 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_Y422
instance ColorConversion 'YUV 'RGBA_UYNV where colorConversionCode _ _ = c'COLOR_YUV2RGBA_UYNV
instance ColorConversion 'YUV 'BGRA_UYNV where colorConversionCode _ _ = c'COLOR_YUV2BGRA_UYNV
instance ColorConversion 'YUV 'RGB_YUY2 where colorConversionCode _ _ = c'COLOR_YUV2RGB_YUY2
instance ColorConversion 'YUV 'BGR_YUY2 where colorConversionCode _ _ = c'COLOR_YUV2BGR_YUY2
instance ColorConversion 'YUV 'RGB_YVYU where colorConversionCode _ _ = c'COLOR_YUV2RGB_YVYU
instance ColorConversion 'YUV 'BGR_YVYU where colorConversionCode _ _ = c'COLOR_YUV2BGR_YVYU
instance ColorConversion 'YUV 'RGB_YUYV where colorConversionCode _ _ = c'COLOR_YUV2RGB_YUYV
instance ColorConversion 'YUV 'BGR_YUYV where colorConversionCode _ _ = c'COLOR_YUV2BGR_YUYV
instance ColorConversion 'YUV 'RGB_YUNV where colorConversionCode _ _ = c'COLOR_YUV2RGB_YUNV
instance ColorConversion 'YUV 'BGR_YUNV where colorConversionCode _ _ = c'COLOR_YUV2BGR_YUNV
instance ColorConversion 'YUV 'RGBA_YUY2 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_YUY2
instance ColorConversion 'YUV 'BGRA_YUY2 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_YUY2
instance ColorConversion 'YUV 'RGBA_YVYU where colorConversionCode _ _ = c'COLOR_YUV2RGBA_YVYU
instance ColorConversion 'YUV 'BGRA_YVYU where colorConversionCode _ _ = c'COLOR_YUV2BGRA_YVYU
instance ColorConversion 'YUV 'RGBA_YUYV where colorConversionCode _ _ = c'COLOR_YUV2RGBA_YUYV
instance ColorConversion 'YUV 'BGRA_YUYV where colorConversionCode _ _ = c'COLOR_YUV2BGRA_YUYV
instance ColorConversion 'YUV 'RGBA_YUNV where colorConversionCode _ _ = c'COLOR_YUV2RGBA_YUNV
instance ColorConversion 'YUV 'BGRA_YUNV where colorConversionCode _ _ = c'COLOR_YUV2BGRA_YUNV
instance ColorConversion 'YUV 'GRAY_UYVY where colorConversionCode _ _ = c'COLOR_YUV2GRAY_UYVY
instance ColorConversion 'YUV 'GRAY_YUY2 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_YUY2
instance ColorConversion 'YUV 'GRAY_Y422 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_Y422
instance ColorConversion 'YUV 'GRAY_UYNV where colorConversionCode _ _ = c'COLOR_YUV2GRAY_UYNV
instance ColorConversion 'YUV 'GRAY_YVYU where colorConversionCode _ _ = c'COLOR_YUV2GRAY_YVYU
instance ColorConversion 'YUV 'GRAY_YUYV where colorConversionCode _ _ = c'COLOR_YUV2GRAY_YUYV
instance ColorConversion 'YUV 'GRAY_YUNV where colorConversionCode _ _ = c'COLOR_YUV2GRAY_YUNV
instance ColorConversion 'RGBA 'MRGBA where colorConversionCode _ _ = c'COLOR_RGBA2mRGBA
instance ColorConversion 'MRGBA 'RGBA where colorConversionCode _ _ = c'COLOR_mRGBA2RGBA
instance ColorConversion 'RGB 'YUV_I420 where colorConversionCode _ _ = c'COLOR_RGB2YUV_I420
instance ColorConversion 'BGR 'YUV_I420 where colorConversionCode _ _ = c'COLOR_BGR2YUV_I420
instance ColorConversion 'RGB 'YUV_IYUV where colorConversionCode _ _ = c'COLOR_RGB2YUV_IYUV
instance ColorConversion 'BGR 'YUV_IYUV where colorConversionCode _ _ = c'COLOR_BGR2YUV_IYUV
instance ColorConversion 'RGBA 'YUV_I420 where colorConversionCode _ _ = c'COLOR_RGBA2YUV_I420
instance ColorConversion 'BGRA 'YUV_I420 where colorConversionCode _ _ = c'COLOR_BGRA2YUV_I420
instance ColorConversion 'RGBA 'YUV_IYUV where colorConversionCode _ _ = c'COLOR_RGBA2YUV_IYUV
instance ColorConversion 'BGRA 'YUV_IYUV where colorConversionCode _ _ = c'COLOR_BGRA2YUV_IYUV
instance ColorConversion 'RGB 'YUV_YV12 where colorConversionCode _ _ = c'COLOR_RGB2YUV_YV12
instance ColorConversion 'BGR 'YUV_YV12 where colorConversionCode _ _ = c'COLOR_BGR2YUV_YV12
instance ColorConversion 'RGBA 'YUV_YV12 where colorConversionCode _ _ = c'COLOR_RGBA2YUV_YV12
instance ColorConversion 'BGRA 'YUV_YV12 where colorConversionCode _ _ = c'COLOR_BGRA2YUV_YV12
instance ColorConversion 'BayerBG 'BGR where colorConversionCode _ _ = c'COLOR_BayerBG2BGR
instance ColorConversion 'BayerGB 'BGR where colorConversionCode _ _ = c'COLOR_BayerGB2BGR
instance ColorConversion 'BayerRG 'BGR where colorConversionCode _ _ = c'COLOR_BayerRG2BGR
instance ColorConversion 'BayerGR 'BGR where colorConversionCode _ _ = c'COLOR_BayerGR2BGR
instance ColorConversion 'BayerBG 'RGB where colorConversionCode _ _ = c'COLOR_BayerBG2RGB
instance ColorConversion 'BayerGB 'RGB where colorConversionCode _ _ = c'COLOR_BayerGB2RGB
instance ColorConversion 'BayerRG 'RGB where colorConversionCode _ _ = c'COLOR_BayerRG2RGB
instance ColorConversion 'BayerGR 'RGB where colorConversionCode _ _ = c'COLOR_BayerGR2RGB
instance ColorConversion 'BayerBG 'GRAY where colorConversionCode _ _ = c'COLOR_BayerBG2GRAY
instance ColorConversion 'BayerGB 'GRAY where colorConversionCode _ _ = c'COLOR_BayerGB2GRAY
instance ColorConversion 'BayerRG 'GRAY where colorConversionCode _ _ = c'COLOR_BayerRG2GRAY
instance ColorConversion 'BayerGR 'GRAY where colorConversionCode _ _ = c'COLOR_BayerGR2GRAY
instance ColorConversion 'BayerBG 'BGR_VNG where colorConversionCode _ _ = c'COLOR_BayerBG2BGR_VNG
instance ColorConversion 'BayerGB 'BGR_VNG where colorConversionCode _ _ = c'COLOR_BayerGB2BGR_VNG
instance ColorConversion 'BayerRG 'BGR_VNG where colorConversionCode _ _ = c'COLOR_BayerRG2BGR_VNG
instance ColorConversion 'BayerGR 'BGR_VNG where colorConversionCode _ _ = c'COLOR_BayerGR2BGR_VNG
instance ColorConversion 'BayerBG 'RGB_VNG where colorConversionCode _ _ = c'COLOR_BayerBG2RGB_VNG
instance ColorConversion 'BayerGB 'RGB_VNG where colorConversionCode _ _ = c'COLOR_BayerGB2RGB_VNG
instance ColorConversion 'BayerRG 'RGB_VNG where colorConversionCode _ _ = c'COLOR_BayerRG2RGB_VNG
instance ColorConversion 'BayerGR 'RGB_VNG where colorConversionCode _ _ = c'COLOR_BayerGR2RGB_VNG
instance ColorConversion 'BayerBG 'BGR_EA where colorConversionCode _ _ = c'COLOR_BayerBG2BGR_EA
instance ColorConversion 'BayerGB 'BGR_EA where colorConversionCode _ _ = c'COLOR_BayerGB2BGR_EA
instance ColorConversion 'BayerRG 'BGR_EA where colorConversionCode _ _ = c'COLOR_BayerRG2BGR_EA
instance ColorConversion 'BayerGR 'BGR_EA where colorConversionCode _ _ = c'COLOR_BayerGR2BGR_EA
instance ColorConversion 'BayerBG 'RGB_EA where colorConversionCode _ _ = c'COLOR_BayerBG2RGB_EA
instance ColorConversion 'BayerGB 'RGB_EA where colorConversionCode _ _ = c'COLOR_BayerGB2RGB_EA
instance ColorConversion 'BayerRG 'RGB_EA where colorConversionCode _ _ = c'COLOR_BayerRG2RGB_EA
instance ColorConversion 'BayerGR 'RGB_EA where colorConversionCode _ _ = c'COLOR_BayerGR2RGB_EA
-- | Gives the number of channels associated with a particular color encoding
type family ColorCodeChannels (cc :: ColorCode) :: Nat where
ColorCodeChannels 'BayerBG = 1
ColorCodeChannels 'BayerGB = 1
ColorCodeChannels 'BayerGR = 1
ColorCodeChannels 'BayerRG = 1
ColorCodeChannels 'BGR = 3
ColorCodeChannels 'BGR555 = 2
ColorCodeChannels 'BGR565 = 2
ColorCodeChannels 'BGRA = 4
ColorCodeChannels 'BGRA_I420 = 4
ColorCodeChannels 'BGRA_IYUV = 4
ColorCodeChannels 'BGRA_NV12 = 4
ColorCodeChannels 'BGRA_NV21 = 4
ColorCodeChannels 'BGRA_UYNV = 4
ColorCodeChannels 'BGRA_UYVY = 4
ColorCodeChannels 'BGRA_Y422 = 4
ColorCodeChannels 'BGRA_YUNV = 4
ColorCodeChannels 'BGRA_YUY2 = 4
ColorCodeChannels 'BGRA_YUYV = 4
ColorCodeChannels 'BGRA_YV12 = 4
ColorCodeChannels 'BGRA_YVYU = 4
ColorCodeChannels 'BGR_EA = 3
ColorCodeChannels 'BGR_FULL = 3
ColorCodeChannels 'BGR_I420 = 3
ColorCodeChannels 'BGR_IYUV = 3
ColorCodeChannels 'BGR_NV12 = 3
ColorCodeChannels 'BGR_NV21 = 3
ColorCodeChannels 'BGR_UYNV = 3
ColorCodeChannels 'BGR_UYVY = 3
ColorCodeChannels 'BGR_VNG = 3
ColorCodeChannels 'BGR_Y422 = 3
ColorCodeChannels 'BGR_YUNV = 3
ColorCodeChannels 'BGR_YUY2 = 3
ColorCodeChannels 'BGR_YUYV = 3
ColorCodeChannels 'BGR_YV12 = 3
ColorCodeChannels 'BGR_YVYU = 3
ColorCodeChannels 'GRAY = 1
ColorCodeChannels 'GRAY_420 = 1
ColorCodeChannels 'GRAY_I420 = 1
ColorCodeChannels 'GRAY_IYUV = 1
ColorCodeChannels 'GRAY_NV12 = 1
ColorCodeChannels 'GRAY_NV21 = 1
ColorCodeChannels 'GRAY_UYNV = 1
ColorCodeChannels 'GRAY_UYVY = 1
ColorCodeChannels 'GRAY_Y422 = 1
ColorCodeChannels 'GRAY_YUNV = 1
ColorCodeChannels 'GRAY_YUY2 = 1
ColorCodeChannels 'GRAY_YUYV = 1
ColorCodeChannels 'GRAY_YV12 = 1
ColorCodeChannels 'GRAY_YVYU = 1
ColorCodeChannels 'HLS = 3
ColorCodeChannels 'HLS_FULL = 3
ColorCodeChannels 'HSV = 3
ColorCodeChannels 'HSV_FULL = 3
ColorCodeChannels 'Lab = 3
ColorCodeChannels 'LBGR = 3
ColorCodeChannels 'LRGB = 3
ColorCodeChannels 'Luv = 3
ColorCodeChannels 'MRGBA = 4
ColorCodeChannels 'RGB = 3
ColorCodeChannels 'RGBA = 4
ColorCodeChannels 'RGBA_I420 = 4
ColorCodeChannels 'RGBA_IYUV = 4
ColorCodeChannels 'RGBA_NV12 = 4
ColorCodeChannels 'RGBA_NV21 = 4
ColorCodeChannels 'RGBA_UYNV = 4
ColorCodeChannels 'RGBA_UYVY = 4
ColorCodeChannels 'RGBA_Y422 = 4
ColorCodeChannels 'RGBA_YUNV = 4
ColorCodeChannels 'RGBA_YUY2 = 4
ColorCodeChannels 'RGBA_YUYV = 4
ColorCodeChannels 'RGBA_YV12 = 4
ColorCodeChannels 'RGBA_YVYU = 4
ColorCodeChannels 'RGB_EA = 3
ColorCodeChannels 'RGB_FULL = 3
ColorCodeChannels 'RGB_I420 = 3
ColorCodeChannels 'RGB_IYUV = 3
ColorCodeChannels 'RGB_NV12 = 3
ColorCodeChannels 'RGB_NV21 = 3
ColorCodeChannels 'RGB_UYNV = 3
ColorCodeChannels 'RGB_UYVY = 3
ColorCodeChannels 'RGB_VNG = 3
ColorCodeChannels 'RGB_Y422 = 3
ColorCodeChannels 'RGB_YUNV = 3
ColorCodeChannels 'RGB_YUY2 = 3
ColorCodeChannels 'RGB_YUYV = 3
ColorCodeChannels 'RGB_YV12 = 3
ColorCodeChannels 'RGB_YVYU = 3
ColorCodeChannels 'XYZ = 3
ColorCodeChannels 'YCrCb = 3
ColorCodeChannels 'YUV = 3
ColorCodeChannels 'YUV420p = 3
ColorCodeChannels 'YUV420sp = 3
ColorCodeChannels 'YUV_I420 = 1
ColorCodeChannels 'YUV_IYUV = 1
ColorCodeChannels 'YUV_YV12 = 1
class ColorCodeMatchesChannels (code :: ColorCode) (channels :: DS Nat)
instance ColorCodeMatchesChannels code 'D
instance (ColorCodeChannels code ~ channels) => ColorCodeMatchesChannels code ('S channels)
type family ColorCodeDepth (srcCode :: ColorCode) (dstCode :: ColorCode) (srcDepth :: DS *) :: DS * where
ColorCodeDepth 'BGR 'BGRA ('S depth) = 'S depth
ColorCodeDepth 'RGB 'BGRA ('S depth) = 'S depth
ColorCodeDepth 'BGRA 'BGR ('S depth) = 'S depth
ColorCodeDepth 'RGBA 'BGR ('S depth) = 'S depth
ColorCodeDepth 'RGB 'BGR ('S depth) = 'S depth
ColorCodeDepth 'BGR 'RGB ('S depth) = 'S depth
ColorCodeDepth 'BGRA 'RGBA ('S depth) = 'S depth
ColorCodeDepth 'BGRA 'RGB ('S depth) = 'S depth
ColorCodeDepth 'BGR 'BGR565 ('S Word8) = 'S Word8
ColorCodeDepth 'BGR 'BGR555 ('S Word8) = 'S Word8
ColorCodeDepth 'RGB 'BGR565 ('S Word8) = 'S Word8
ColorCodeDepth 'RGB 'BGR555 ('S Word8) = 'S Word8
ColorCodeDepth 'BGRA 'BGR565 ('S Word8) = 'S Word8
ColorCodeDepth 'BGRA 'BGR555 ('S Word8) = 'S Word8
ColorCodeDepth 'RGBA 'BGR565 ('S Word8) = 'S Word8
ColorCodeDepth 'RGBA 'BGR555 ('S Word8) = 'S Word8
ColorCodeDepth 'BGR565 'BGR ('S Word8) = 'S Word8
ColorCodeDepth 'BGR555 'BGR ('S Word8) = 'S Word8
ColorCodeDepth 'BGR565 'RGB ('S Word8) = 'S Word8
ColorCodeDepth 'BGR555 'RGB ('S Word8) = 'S Word8
ColorCodeDepth 'BGR565 'BGRA ('S Word8) = 'S Word8
ColorCodeDepth 'BGR555 'BGRA ('S Word8) = 'S Word8
ColorCodeDepth 'BGR565 'RGBA ('S Word8) = 'S Word8
ColorCodeDepth 'BGR555 'RGBA ('S Word8) = 'S Word8
ColorCodeDepth 'BGR 'GRAY ('S depth) = 'S depth
ColorCodeDepth 'BGRA 'GRAY ('S depth) = 'S depth
ColorCodeDepth 'RGB 'GRAY ('S depth) = 'S depth
ColorCodeDepth 'RGBA 'GRAY ('S depth) = 'S depth
ColorCodeDepth 'BGR565 'GRAY ('S Word8) = 'S Word8
ColorCodeDepth 'BGR555 'GRAY ('S Word8) = 'S Word8
ColorCodeDepth 'GRAY 'RGB ('S depth) = 'S depth
ColorCodeDepth 'GRAY 'BGR ('S depth) = 'S depth
ColorCodeDepth 'GRAY 'BGRA ('S depth) = 'S depth
ColorCodeDepth 'GRAY 'BGR565 ('S Word8) = 'S Word8
ColorCodeDepth 'GRAY 'BGR555 ('S Word8) = 'S Word8
ColorCodeDepth 'BGR 'YCrCb ('S depth) = 'S depth
ColorCodeDepth 'BGR 'YUV ('S depth) = 'S depth
ColorCodeDepth 'RGB 'YCrCb ('S depth) = 'S depth
ColorCodeDepth 'RGB 'YUV ('S depth) = 'S depth
ColorCodeDepth 'YCrCb 'BGR ('S depth) = 'S depth
ColorCodeDepth 'YCrCb 'RGB ('S depth) = 'S depth
ColorCodeDepth 'YUV 'BGR ('S depth) = 'S depth
ColorCodeDepth 'YUV 'RGB ('S depth) = 'S depth
ColorCodeDepth 'BGR 'XYZ ('S depth) = 'S depth
ColorCodeDepth 'RGB 'XYZ ('S depth) = 'S depth
ColorCodeDepth 'XYZ 'BGR ('S depth) = 'S depth
ColorCodeDepth 'XYZ 'RGB ('S depth) = 'S depth
ColorCodeDepth 'BGR 'HSV ('S Word8) = 'S Word8
ColorCodeDepth 'RGB 'HSV ('S Word8) = 'S Word8
ColorCodeDepth 'BGR 'HSV_FULL ('S Word8) = 'S Word8
ColorCodeDepth 'RGB 'HSV_FULL ('S Word8) = 'S Word8
ColorCodeDepth 'BGR 'HLS ('S Word8) = 'S Word8
ColorCodeDepth 'RGB 'HLS ('S Word8) = 'S Word8
ColorCodeDepth 'BGR 'HLS_FULL ('S Word8) = 'S Word8
ColorCodeDepth 'RGB 'HLS_FULL ('S Word8) = 'S Word8
ColorCodeDepth 'BGR 'HSV ('S Float) = 'S Float
ColorCodeDepth 'RGB 'HSV ('S Float) = 'S Float
ColorCodeDepth 'BGR 'HSV_FULL ('S Float) = 'S Float
ColorCodeDepth 'RGB 'HSV_FULL ('S Float) = 'S Float
ColorCodeDepth 'BGR 'HLS ('S Float) = 'S Float
ColorCodeDepth 'RGB 'HLS ('S Float) = 'S Float
ColorCodeDepth 'BGR 'HLS_FULL ('S Float) = 'S Float
ColorCodeDepth 'RGB 'HLS_FULL ('S Float) = 'S Float
ColorCodeDepth 'HSV 'BGR ('S Word8) = 'S Word8
ColorCodeDepth 'HSV 'RGB ('S Word8) = 'S Word8
ColorCodeDepth 'HSV 'BGR_FULL ('S Word8) = 'S Word8
ColorCodeDepth 'HSV 'RGB_FULL ('S Word8) = 'S Word8
ColorCodeDepth 'HLS 'BGR ('S Word8) = 'S Word8
ColorCodeDepth 'HLS 'RGB ('S Word8) = 'S Word8
ColorCodeDepth 'HLS 'BGR_FULL ('S Word8) = 'S Word8
ColorCodeDepth 'HLS 'RGB_FULL ('S Word8) = 'S Word8
ColorCodeDepth 'HSV 'BGR ('S Float) = 'S Float
ColorCodeDepth 'HSV 'RGB ('S Float) = 'S Float
ColorCodeDepth 'HSV 'BGR_FULL ('S Float) = 'S Float
ColorCodeDepth 'HSV 'RGB_FULL ('S Float) = 'S Float
ColorCodeDepth 'HLS 'BGR ('S Float) = 'S Float
ColorCodeDepth 'HLS 'RGB ('S Float) = 'S Float
ColorCodeDepth 'HLS 'BGR_FULL ('S Float) = 'S Float
ColorCodeDepth 'HLS 'RGB_FULL ('S Float) = 'S Float
ColorCodeDepth 'BGR 'Lab ('S Word8) = 'S Word8
ColorCodeDepth 'RGB 'Lab ('S Word8) = 'S Word8
ColorCodeDepth 'LBGR 'Lab ('S Word8) = 'S Word8
ColorCodeDepth 'LRGB 'Lab ('S Word8) = 'S Word8
ColorCodeDepth 'BGR 'Luv ('S Word8) = 'S Word8
ColorCodeDepth 'RGB 'Luv ('S Word8) = 'S Word8
ColorCodeDepth 'LBGR 'Luv ('S Word8) = 'S Word8
ColorCodeDepth 'LRGB 'Luv ('S Word8) = 'S Word8
ColorCodeDepth 'BGR 'Lab ('S Float) = 'S Float
ColorCodeDepth 'RGB 'Lab ('S Float) = 'S Float
ColorCodeDepth 'LBGR 'Lab ('S Float) = 'S Float
ColorCodeDepth 'LRGB 'Lab ('S Float) = 'S Float
ColorCodeDepth 'BGR 'Luv ('S Float) = 'S Float
ColorCodeDepth 'RGB 'Luv ('S Float) = 'S Float
ColorCodeDepth 'LBGR 'Luv ('S Float) = 'S Float
ColorCodeDepth 'LRGB 'Luv ('S Float) = 'S Float
ColorCodeDepth 'Lab 'BGR ('S Word8) = 'S Word8
ColorCodeDepth 'Lab 'RGB ('S Word8) = 'S Word8
ColorCodeDepth 'Lab 'LBGR ('S Word8) = 'S Word8
ColorCodeDepth 'Lab 'LRGB ('S Word8) = 'S Word8
ColorCodeDepth 'Luv 'BGR ('S Word8) = 'S Word8
ColorCodeDepth 'Luv 'RGB ('S Word8) = 'S Word8
ColorCodeDepth 'Luv 'LBGR ('S Word8) = 'S Word8
ColorCodeDepth 'Luv 'LRGB ('S Word8) = 'S Word8
ColorCodeDepth 'Lab 'BGR ('S Float) = 'S Float
ColorCodeDepth 'Lab 'RGB ('S Float) = 'S Float
ColorCodeDepth 'Lab 'LBGR ('S Float) = 'S Float
ColorCodeDepth 'Lab 'LRGB ('S Float) = 'S Float
ColorCodeDepth 'Luv 'BGR ('S Float) = 'S Float
ColorCodeDepth 'Luv 'RGB ('S Float) = 'S Float
ColorCodeDepth 'Luv 'LBGR ('S Float) = 'S Float
ColorCodeDepth 'Luv 'LRGB ('S Float) = 'S Float
ColorCodeDepth 'BayerBG 'GRAY ('S Word8) = 'S Word8
ColorCodeDepth 'BayerBG 'GRAY ('S Word16) = 'S Word16
ColorCodeDepth 'BayerGB 'GRAY ('S Word8) = 'S Word8
ColorCodeDepth 'BayerGB 'GRAY ('S Word16) = 'S Word16
ColorCodeDepth 'BayerGR 'GRAY ('S Word8) = 'S Word8
ColorCodeDepth 'BayerGR 'GRAY ('S Word16) = 'S Word16
ColorCodeDepth 'BayerRG 'GRAY ('S Word8) = 'S Word8
ColorCodeDepth 'BayerRG 'GRAY ('S Word16) = 'S Word16
ColorCodeDepth 'BayerBG 'BGR ('S Word8) = 'S Word8
ColorCodeDepth 'BayerBG 'BGR ('S Word16) = 'S Word16
ColorCodeDepth 'BayerGB 'BGR ('S Word8) = 'S Word8
ColorCodeDepth 'BayerGB 'BGR ('S Word16) = 'S Word16
ColorCodeDepth 'BayerGR 'BGR ('S Word8) = 'S Word8
ColorCodeDepth 'BayerGR 'BGR ('S Word16) = 'S Word16
ColorCodeDepth 'BayerRG 'BGR ('S Word8) = 'S Word8
ColorCodeDepth 'BayerRG 'BGR ('S Word16) = 'S Word16
ColorCodeDepth 'BayerBG 'BGR_VNG ('S Word8) = 'S Word8
ColorCodeDepth 'BayerBG 'BGR_VNG ('S Word16) = 'S Word16
ColorCodeDepth 'BayerGB 'BGR_VNG ('S Word8) = 'S Word8
ColorCodeDepth 'BayerGB 'BGR_VNG ('S Word16) = 'S Word16
ColorCodeDepth 'BayerGR 'BGR_VNG ('S Word8) = 'S Word8
ColorCodeDepth 'BayerGR 'BGR_VNG ('S Word16) = 'S Word16
ColorCodeDepth 'BayerRG 'BGR_VNG ('S Word8) = 'S Word8
ColorCodeDepth 'BayerRG 'BGR_VNG ('S Word16) = 'S Word16
ColorCodeDepth 'BayerBG 'BGR_EA ('S Word8) = 'S Word8
ColorCodeDepth 'BayerBG 'BGR_EA ('S Word16) = 'S Word16
ColorCodeDepth 'BayerGB 'BGR_EA ('S Word8) = 'S Word8
ColorCodeDepth 'BayerGB 'BGR_EA ('S Word16) = 'S Word16
ColorCodeDepth 'BayerGR 'BGR_EA ('S Word8) = 'S Word8
ColorCodeDepth 'BayerGR 'BGR_EA ('S Word16) = 'S Word16
ColorCodeDepth 'BayerRG 'BGR_EA ('S Word8) = 'S Word8
ColorCodeDepth 'BayerRG 'BGR_EA ('S Word16) = 'S Word16
ColorCodeDepth 'YUV 'BGR_NV21 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'RGB_NV21 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'BGR_NV12 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'RGB_NV12 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'BGRA_NV21 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'RGBA_NV21 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'BGRA_NV12 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'RGBA_NV12 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'BGR_YV12 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'RGB_YV12 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'BGRA_YV12 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'RGBA_YV12 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'BGR_IYUV ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'RGB_IYUV ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'BGRA_IYUV ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'RGBA_IYUV ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'GRAY_420 ('S Word8) = 'S Word8
ColorCodeDepth 'RGB 'YUV_YV12 ('S Word8) = 'S Word8
ColorCodeDepth 'BGR 'YUV_YV12 ('S Word8) = 'S Word8
ColorCodeDepth 'RGBA 'YUV_YV12 ('S Word8) = 'S Word8
ColorCodeDepth 'BGRA 'YUV_YV12 ('S Word8) = 'S Word8
ColorCodeDepth 'RGB 'YUV_IYUV ('S Word8) = 'S Word8
ColorCodeDepth 'BGR 'YUV_IYUV ('S Word8) = 'S Word8
ColorCodeDepth 'RGBA 'YUV_IYUV ('S Word8) = 'S Word8
ColorCodeDepth 'BGRA 'YUV_IYUV ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'RGB_UYVY ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'BGR_UYVY ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'RGBA_UYVY ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'BGRA_UYVY ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'RGB_YUY2 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'BGR_YUY2 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'RGB_YVYU ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'BGR_YVYU ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'RGBA_YUY2 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'BGRA_YUY2 ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'RGBA_YVYU ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'BGRA_YVYU ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'GRAY_UYVY ('S Word8) = 'S Word8
ColorCodeDepth 'YUV 'GRAY_YUY2 ('S Word8) = 'S Word8
ColorCodeDepth 'RGBA 'MRGBA ('S Word8) = 'S Word8
ColorCodeDepth 'MRGBA 'RGBA ('S Word8) = 'S Word8
ColorCodeDepth srcCode dstCode 'D = 'D
|
lukexi/haskell-opencv
|
src/OpenCV/Internal/ImgProc/MiscImgTransform/ColorCodes.hs
|
bsd-3-clause
| 43,996 | 0 | 9 | 10,080 | 13,169 | 6,710 | 6,459 | -1 | -1 |
{-# LANGUAGE ForeignFunctionInterface, JavaScriptFFI, MagicHash,
UnliftedFFITypes
#-}
module Data.JSString.RealFloat ( FPFormat(..)
, realFloat
, formatRealFloat
, formatDouble
, formatFloat
) where
import GHC.Exts (Int#, Float#, Double#, Int(..), Float(..), Double(..))
import Data.JSString
-- | Control the rendering of floating point numbers.
data FPFormat = Exponent
-- ^ Scientific notation (e.g. @2.3e123@).
| Fixed
-- ^ Standard decimal notation.
| Generic
-- ^ Use decimal notation for values between @0.1@ and
-- @9,999,999@, and scientific notation otherwise.
deriving (Enum, Read, Show)
realFloat :: (RealFloat a) => a -> JSString
realFloat = error "Data.JSString.RealFloat.realFloat not yet implemented"
{-# RULES "realFloat/Double" realFloat = genericDouble #-}
{-# RULES "realFoat/Float" realFloat = genericFloat #-}
{-# SPECIALIZE realFloat :: Double -> JSString #-}
{-# SPECIALIZE realFloat :: Float -> JSString #-}
{-# NOINLINE realFloat #-}
formatRealFloat :: (RealFloat a)
=> FPFormat
-> Maybe Int
-> a
-> JSString
formatRealFloat = error "Data.JSString.RealFloat.formatRealFloat not yet implemented"
{-# RULES "formatRealFloat/Double" formatRealFloat = formatDouble #-}
{-# RULES "formatRealFloat/Float" formatRealFloat = formatFloat #-}
{-# SPECIALIZE formatRealFloat :: FPFormat -> Maybe Int -> Double -> JSString #-}
{-# SPECIALIZE formatRealFloat :: FPFormat -> Maybe Int -> Float -> JSString #-}
{-# NOINLINE formatRealFloat #-}
genericDouble :: Double -> JSString
genericDouble (D# d) = js_doubleGeneric -1# d
{-# INLINE genericDouble #-}
genericFloat :: Float -> JSString
genericFloat (F# f) = js_floatGeneric -1# f
{-# INLINE genericFloat #-}
formatDouble :: FPFormat -> Maybe Int -> Double -> JSString
formatDouble fmt Nothing (D# d)
= case fmt of
Fixed -> js_doubleToFixed -1# d
Exponent -> js_doubleToExponent -1# d
Generic -> js_doubleGeneric -1# d
formatDouble fmt (Just (I# decs)) (D# d)
= case fmt of
Fixed -> js_doubleToFixed decs d
Exponent -> js_doubleToExponent decs d
Generic -> js_doubleGeneric decs d
{-# INLINE formatDouble #-}
formatFloat :: FPFormat -> Maybe Int -> Float -> JSString
formatFloat fmt Nothing (F# f)
= case fmt of
Fixed -> js_floatToFixed -1# f
Exponent -> js_floatToExponent -1# f
Generic -> js_floatGeneric -1# f
formatFloat fmt (Just (I# decs)) (F# f)
= case fmt of
Fixed -> js_floatToFixed decs f
Exponent -> js_floatToExponent decs f
Generic -> js_floatGeneric decs f
{-# INLINE formatFloat #-}
foreign import javascript unsafe
"h$jsstringDoubleToFixed"
js_doubleToFixed :: Int# -> Double# -> JSString
foreign import javascript unsafe
"h$jsstringDoubleToFixed"
js_floatToFixed :: Int# -> Float# -> JSString
foreign import javascript unsafe
"h$jsstringDoubleToExponent($1,$2)"
js_doubleToExponent :: Int# -> Double# -> JSString
foreign import javascript unsafe
"h$jsstringDoubleToExponent($1,$2)"
js_floatToExponent :: Int# -> Float# -> JSString
foreign import javascript unsafe
"h$jsstringDoubleGeneric($1,$2)"
js_doubleGeneric :: Int# -> Double# -> JSString
foreign import javascript unsafe
"h$jsstringDoubleGeneric($1,$2)"
js_floatGeneric :: Int# -> Float# -> JSString
|
tavisrudd/ghcjs-base
|
Data/JSString/RealFloat.hs
|
mit
| 3,626 | 20 | 10 | 914 | 679 | 360 | 319 | 73 | 5 |
{-# OPTIONS_GHC -fno-warn-deprecations #-}
module Network.Wai.Handler.Warp.Internal
( Settings (..)
, getOnOpen
, getOnClose
, getOnException
) where
import Network.Wai.Handler.Warp.Settings (Settings (..))
import Network.Socket (SockAddr)
import Network.Wai (Request)
import Control.Exception (SomeException)
getOnOpen :: Settings -> SockAddr -> IO Bool
getOnOpen = settingsOnOpen
getOnClose :: Settings -> SockAddr -> IO ()
getOnClose = settingsOnClose
getOnException :: Settings -> Maybe Request -> SomeException -> IO ()
getOnException = settingsOnException
|
jberryman/wai
|
warp/Network/Wai/Handler/Warp/Internal.hs
|
mit
| 586 | 0 | 9 | 90 | 149 | 88 | 61 | 16 | 1 |
-- |
-- Module: FRP.Netwire.Analyze
-- Copyright: (c) 2013 Ertugrul Soeylemez
-- License: BSD3
-- Maintainer: Ertugrul Soeylemez <[email protected]>
module FRP.Netwire.Analyze
( -- * Linear graphs
lAvg,
lGraph,
lGraphN,
-- * Staircase graphs
sAvg,
sGraph,
sGraphN,
-- * Peaks
highPeak,
highPeakBy,
lowPeak,
lowPeakBy,
-- * Debug
avgFps,
framerate
)
where
import qualified FRP.Netwire.Utils.Timeline as Tl
import qualified Data.Foldable as F
import qualified Data.Sequence as Seq
import Control.Wire
import Prelude hiding ((.), id)
-- | Average framerate over the last given number of samples. One
-- important thing to note is that the value of this wire will generally
-- disagree with 'sAvg' composed with 'framerate'. This is expected,
-- because this wire simply calculates the arithmetic mean, whereas
-- 'sAvg' will actually integrate the framerate graph.
--
-- Note: This wire is for debugging purposes only, because it exposes
-- discrete time. Do not taint your application with discrete time.
--
-- * Complexity: O(n) time and space wrt number of samples.
avgFps ::
(RealFloat b, HasTime t s)
=> Int -- ^ Number of samples.
-> Wire s e m a b
avgFps int | int < 1 = error "avgFps: Non-positive number of samples"
avgFps int = loop Seq.empty
where
intf = fromIntegral int
afps = (/ intf) . F.foldl' (+) 0
loop ss' =
mkSF $ \ds _ ->
let fps = recip . realToFrac . dtime $ ds
ss = Seq.take int (fps Seq.<| ss')
in if isInfinite fps
then (afps ss', loop ss')
else ss `seq` (afps ss, loop ss)
-- | Current framerate.
--
-- Note: This wire is for debugging purposes only, because it exposes
-- discrete time. Do not taint your application with discrete time.
--
-- * Inhibits: when the clock stopped ticking.
framerate ::
(Eq b, Fractional b, HasTime t s, Monoid e)
=> Wire s e m a b
framerate =
mkPure $ \ds _ ->
let dt = realToFrac (dtime ds)
in (if dt == 0 then Left mempty else Right (recip dt), framerate)
-- | High peak.
--
-- * Depends: now.
highPeak :: (Ord a) => Wire s e m a a
highPeak = highPeakBy compare
-- | High peak with respect to the given comparison function.
--
-- * Depends: now.
highPeakBy :: (a -> a -> Ordering) -> Wire s e m a a
highPeakBy = peakBy GT
-- | Calculate the average of the signal over the given interval (from
-- now). This is done by calculating the integral of the corresponding
-- linearly interpolated graph and dividing it by the interval length.
-- See 'Tl.linAvg' for details.
--
-- Linear interpolation can be slow. If you don't need it, you can use
-- the staircase variant 'sAvg'.
--
-- Example: @lAvg 2@
--
-- * Complexity: O(s) space, O(s) time wrt number of samples in the
-- interval.
--
-- * Depends: now.
lAvg ::
(Fractional a, Fractional t, HasTime t s)
=> t -- ^ Interval size.
-> Wire s e m a a
lAvg int =
mkSF $ \ds x ->
let t = dtime ds in
(x, loop t (Tl.singleton t x))
where
loop t' tl' =
mkSF $ \ds x ->
let t = t' + dtime ds
t0 = t - int
tl = Tl.linCutL t0 (Tl.insert t x tl')
a = Tl.linAvg t0 t tl
in (a, loop t tl)
-- | Produce a linearly interpolated graph for the given points in time,
-- where the magnitudes of the points are distances from /now/.
--
-- Linear interpolation can be slow. If you don't need it, you can use
-- the faster staircase variant 'sGraph'.
--
-- Example: @lGraph [0, 1, 2]@ will output the interpolated inputs at
-- /now/, one second before now and two seconds before now.
--
-- * Complexity: O(s) space, O(n * log s) time, where s = number of
-- samples in the interval, n = number of requested data points.
--
-- * Depends: now.
lGraph ::
(Fractional a, Fractional t, HasTime t s)
=> [t] -- ^ Data points to produce.
-> Wire s e m a [a]
lGraph qts =
mkSF $ \ds x ->
let t = dtime ds in
(x <$ qts, loop t (Tl.singleton t x))
where
earliest = maximum (map abs qts)
loop t' tl' =
mkSF $ \ds x ->
let t = t' + dtime ds
tl = Tl.linCutL (t - earliest) (Tl.insert t x tl')
ps = map (\qt -> Tl.linLookup (t - abs qt) tl) qts
in (ps, loop t tl)
-- | Graph the given interval from now with the given number of evenly
-- distributed points in time. Convenience interface to 'lGraph'.
--
-- Linear interpolation can be slow. If you don't need it, you can use
-- the faster staircase variant 'sGraphN'.
--
-- * Complexity: O(s) space, O(n * log s) time, where s = number of
-- samples in the interval, n = number of requested data points.
--
-- * Depends: now.
lGraphN ::
(Fractional a, Fractional t, HasTime t s)
=> t -- ^ Interval to graph from now.
-> Int -- ^ Number of data points to produce.
-> Wire s e m a [a]
lGraphN int n
| int <= 0 = error "lGraphN: Non-positive interval"
| n <= 0 = error "lGraphN: Non-positive number of data points"
lGraphN int n =
let n1 = n - 1
f qt = realToFrac int * fromIntegral qt / fromIntegral n1
in lGraph (map f [0..n1])
-- | Low peak.
--
-- * Depends: now.
lowPeak :: (Ord a) => Wire s e m a a
lowPeak = lowPeakBy compare
-- | Low peak with respect to the given comparison function.
--
-- * Depends: now.
lowPeakBy :: (a -> a -> Ordering) -> Wire s e m a a
lowPeakBy = peakBy LT
-- | Given peak with respect to the given comparison function.
peakBy ::
(Eq o)
=> o -- ^ This ordering means the first argument is larger.
-> (a -> a -> o) -- ^ Compare two elements.
-> Wire s e m a a
peakBy o comp = mkSFN $ \x -> (x, loop x)
where
loop x' =
mkSFN $ \x ->
id &&& loop $
if comp x x' == o then x else x'
-- | Calculate the average of the signal over the given interval (from
-- now). This is done by calculating the integral of the corresponding
-- staircase graph and dividing it by the interval length. See
-- 'Tl.scAvg' for details.
--
-- See also 'lAvg'.
--
-- Example: @sAvg 2@
--
-- * Complexity: O(s) space, O(s) time wrt number of samples in the
-- interval.
--
-- * Depends: now.
sAvg ::
(Fractional a, Fractional t, HasTime t s)
=> t -- ^ Interval size.
-> Wire s e m a a
sAvg int =
mkSF $ \ds x ->
let t = dtime ds in
(x, loop t (Tl.singleton t x))
where
loop t' tl' =
mkSF $ \ds x ->
let t = t' + dtime ds
t0 = t - int
tl = Tl.scCutL t0 (Tl.insert t x tl')
a = Tl.scAvg t0 t tl
in (a, loop t tl)
-- | Produce a staircase graph for the given points in time, where the
-- magnitudes of the points are distances from /now/.
--
-- See also 'lGraph'.
--
-- Example: @sGraph [0, 1, 2]@ will output the inputs at /now/, one
-- second before now and two seconds before now.
--
-- * Complexity: O(s) space, O(n * log s) time, where s = number of
-- samples in the interval, n = number of requested data points.
--
-- * Depends: now.
sGraph ::
(Fractional t, HasTime t s)
=> [t] -- ^ Data points to produce.
-> Wire s e m a [a]
sGraph qts =
mkSF $ \ds x ->
let t = dtime ds in
(x <$ qts, loop t (Tl.singleton t x))
where
earliest = maximum (map abs qts)
loop t' tl' =
mkSF $ \ds x ->
let t = t' + dtime ds
tl = Tl.scCutL (t - earliest) (Tl.insert t x tl')
ps = map (\qt -> Tl.scLookup (t - abs qt) tl) qts
in (ps, loop t tl)
-- | Graph the given interval from now with the given number of evenly
-- distributed points in time. Convenience interface to 'sGraph'.
--
-- See also 'lGraphN'.
--
-- * Complexity: O(s) space, O(n * log s) time, where s = number of
-- samples in the interval, n = number of requested data points.
--
-- * Depends: now.
sGraphN ::
(Fractional t, HasTime t s)
=> t -- ^ Interval to graph from now.
-> Int -- ^ Number of data points to produce.
-> Wire s e m a [a]
sGraphN int n
| int <= 0 = error "sGraphN: Non-positive interval"
| n <= 0 = error "sGraphN: Non-positive number of data points"
sGraphN int n =
let n1 = n - 1
f qt = realToFrac int * fromIntegral qt / fromIntegral n1
in sGraph (map f [0..n1])
|
jship/metronome
|
local_deps/netwire/FRP/Netwire/Analyze.hs
|
bsd-3-clause
| 8,503 | 0 | 19 | 2,487 | 1,960 | 1,067 | 893 | 143 | 2 |
<?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="hu-HU">
<title>SOAP Support Add-on</title>
<maps>
<homeID>soap</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
kingthorin/zap-extensions
|
addOns/soap/src/main/javahelp/org/zaproxy/zap/extension/soap/resources/help_hu_HU/helpset_hu_HU.hs
|
apache-2.0
| 965 | 77 | 67 | 157 | 413 | 209 | 204 | -1 | -1 |
module A3 where
import D3
import C3
import B3
main :: Tree Int ->Bool
main t = isSame (sumSquares (fringe t))
(sumSquares (B3.myFringe t)+sumSquares (C3.myFringe t))
|
kmate/HaRe
|
old/testing/moveDefBtwMods/A3.hs
|
bsd-3-clause
| 195 | 0 | 11 | 55 | 79 | 41 | 38 | 7 | 1 |
module A3 where
import C3
main xs = sumSquares xs + anotherFun xs
|
kmate/HaRe
|
old/testing/duplication/A3_TokOut.hs
|
bsd-3-clause
| 81 | 0 | 6 | 28 | 25 | 13 | 12 | 3 | 1 |
{-# OPTIONS -fno-warn-unused-imports #-}
#include "HsConfigure.h"
-- #hide
module Data.Time.Calendar.Days
(
-- * Days
Day(..),addDays,diffDays
) where
import Control.DeepSeq
import Data.Ix
import Data.Typeable
#if LANGUAGE_Rank2Types
import Data.Data
#endif
-- | The Modified Julian Day is a standard count of days, with zero being the day 1858-11-17.
newtype Day = ModifiedJulianDay {toModifiedJulianDay :: Integer} deriving (Eq,Ord
#if LANGUAGE_DeriveDataTypeable
#if LANGUAGE_Rank2Types
,Data, Typeable
#endif
#endif
)
instance NFData Day where
rnf (ModifiedJulianDay a) = rnf a
-- necessary because H98 doesn't have "cunning newtype" derivation
instance Enum Day where
succ (ModifiedJulianDay a) = ModifiedJulianDay (succ a)
pred (ModifiedJulianDay a) = ModifiedJulianDay (pred a)
toEnum = ModifiedJulianDay . toEnum
fromEnum (ModifiedJulianDay a) = fromEnum a
enumFrom (ModifiedJulianDay a) = fmap ModifiedJulianDay (enumFrom a)
enumFromThen (ModifiedJulianDay a) (ModifiedJulianDay b) = fmap ModifiedJulianDay (enumFromThen a b)
enumFromTo (ModifiedJulianDay a) (ModifiedJulianDay b) = fmap ModifiedJulianDay (enumFromTo a b)
enumFromThenTo (ModifiedJulianDay a) (ModifiedJulianDay b) (ModifiedJulianDay c) = fmap ModifiedJulianDay (enumFromThenTo a b c)
-- necessary because H98 doesn't have "cunning newtype" derivation
instance Ix Day where
range (ModifiedJulianDay a,ModifiedJulianDay b) = fmap ModifiedJulianDay (range (a,b))
index (ModifiedJulianDay a,ModifiedJulianDay b) (ModifiedJulianDay c) = index (a,b) c
inRange (ModifiedJulianDay a,ModifiedJulianDay b) (ModifiedJulianDay c) = inRange (a,b) c
rangeSize (ModifiedJulianDay a,ModifiedJulianDay b) = rangeSize (a,b)
addDays :: Integer -> Day -> Day
addDays n (ModifiedJulianDay a) = ModifiedJulianDay (a + n)
diffDays :: Day -> Day -> Integer
diffDays (ModifiedJulianDay a) (ModifiedJulianDay b) = a - b
{-
instance Show Day where
show (ModifiedJulianDay d) = "MJD " ++ (show d)
-- necessary because H98 doesn't have "cunning newtype" derivation
instance Num Day where
(ModifiedJulianDay a) + (ModifiedJulianDay b) = ModifiedJulianDay (a + b)
(ModifiedJulianDay a) - (ModifiedJulianDay b) = ModifiedJulianDay (a - b)
(ModifiedJulianDay a) * (ModifiedJulianDay b) = ModifiedJulianDay (a * b)
negate (ModifiedJulianDay a) = ModifiedJulianDay (negate a)
abs (ModifiedJulianDay a) = ModifiedJulianDay (abs a)
signum (ModifiedJulianDay a) = ModifiedJulianDay (signum a)
fromInteger = ModifiedJulianDay
instance Real Day where
toRational (ModifiedJulianDay a) = toRational a
instance Integral Day where
toInteger (ModifiedJulianDay a) = toInteger a
quotRem (ModifiedJulianDay a) (ModifiedJulianDay b) = (ModifiedJulianDay c,ModifiedJulianDay d) where
(c,d) = quotRem a b
-}
|
beni55/haste-compiler
|
libraries/time/lib/Data/Time/Calendar/Days.hs
|
bsd-3-clause
| 2,782 | 2 | 9 | 401 | 566 | 299 | 267 | 28 | 1 |
-- Generated by protobuf-simple. DO NOT EDIT!
module Types.BoolListPacked where
import Control.Applicative ((<$>))
import Prelude ()
import qualified Data.ProtoBufInt as PB
newtype BoolListPacked = BoolListPacked
{ value :: PB.Seq PB.Bool
} deriving (PB.Show, PB.Eq, PB.Ord)
instance PB.Default BoolListPacked where
defaultVal = BoolListPacked
{ value = PB.defaultVal
}
instance PB.Mergeable BoolListPacked where
merge a b = BoolListPacked
{ value = PB.merge (value a) (value b)
}
instance PB.Required BoolListPacked where
reqTags _ = PB.fromList []
instance PB.WireMessage BoolListPacked where
fieldToValue (PB.WireTag 1 PB.LenDelim) self = (\v -> self{value = PB.merge (value self) v}) <$> PB.getBoolPacked
fieldToValue (PB.WireTag 1 PB.VarInt) self = (\v -> self{value = PB.append (value self) v}) <$> PB.getBool
fieldToValue tag self = PB.getUnknown tag self
messageToFields self = do
PB.putBoolPacked (PB.WireTag 1 PB.LenDelim) (value self)
|
sru-systems/protobuf-simple
|
test/Types/BoolListPacked.hs
|
mit
| 993 | 0 | 13 | 174 | 348 | 186 | 162 | 21 | 0 |
import Drawing
main = drawPicture myPicture
myPicture points =
coordinates &
drawPoints [a,b,a',b'] &
drawLabels [a,b,a',b'] ["A","B","A'","B'"] &
drawSegment (a,b) &
drawSegment (a',b') &
message "Translation of AB 3 units right and 1 unit down"
where
[a,b] = [(1,1),(2,2)]
a' = translate a (3,-1)
b' = translate b (3,-1)
translate a (x,y) = a'
where (x1,y1) = a
a' = (x1+x,y1+y)
|
alphalambda/k12math
|
contrib/MHills/GeometryLessons/code/teacher/key_lesson8b.hs
|
mit
| 465 | 0 | 11 | 145 | 222 | 126 | 96 | 15 | 1 |
module Chapter08 (Nat(..), mult, Expr(..), folde, Tree(..), complete) where
data Nat = Zero
| Succ Nat deriving (Show, Eq)
add :: Nat -> Nat -> Nat
add = undefined
mult :: Nat -> Nat -> Nat
mult = undefined
data Expr = Val Int
| Add Expr Expr
| Mul Expr Expr
folde :: (Int -> a) -> (a -> a-> a) -> (a -> a -> a) -> Expr -> a
folde = undefined
data Tree a = Leaf a
| Node (Tree a) a (Tree a)
complete :: Tree a -> Bool
complete = undefined
|
EindhovenHaskellMeetup/meetup
|
courses/programming-in-haskell/pih-exercises/src/Chapter08.hs
|
mit
| 487 | 0 | 10 | 145 | 221 | 127 | 94 | 16 | 1 |
{-# LANGUAGE NamedFieldPuns, RecordWildCards #-}
import Graphics.SpriteKit
import Actions
import Constants
import Convenience
import GameState
import Pipes
import Random
import Scenery
lazyLambda :: LambdaScene
lazyLambda
= (sceneWithSize (Size width height))
{ sceneBackgroundColor = skyColour
, sceneChildren = [bird, movingNodes, groundPhysics, score]
, sceneData = initialSceneState
, sceneUpdate = Just update
, scenePhysicsWorld = physicsWorld
{ worldGravity = Vector 0 (-5)
, worldContactDidBegin = Just contact
}
, sceneHandleEvent = Just handleEvent
}
(bird1Texture, birdWidth, birdHeight) = defineTexture "Bird-01.png"
(bird2Texture, _, _) = defineTexture "Bird-02.png"
(bird3Texture, _, _) = defineTexture "Bird-03.png"
bird :: LambdaNode
bird = (spriteWithTexture bird1Texture)
{ nodeName = Just "Lambda"
, nodePosition = Point (width * 0.35) (height * 0.6)
, nodeActionDirectives = [runActionForever flap]
, nodePhysicsBody
= Just $
(bodyWithCircleOfRadius (birdHeight / 2) Nothing)
{ bodyCategoryBitMask = categoryBitMask [Bird]
, bodyCollisionBitMask = categoryBitMask [World]
, bodyContactTestBitMask = categoryBitMask [World, Score]
}
}
where
flap = animateWithTextures
[bird1Texture, bird2Texture, bird3Texture, bird2Texture] 0.1
movingNodes :: LambdaNode
movingNodes = (node $ pipes : groundSprites ++ skySprites)
{ nodeName = Just "Moving" }
groundPhysics :: LambdaNode
groundPhysics = (node [])
{ nodePosition = Point 0 (groundTileHeight / 2)
, nodePhysicsBody = Just $
(bodyWithEdgeFromPointToPoint (Point 0 (groundTileHeight / 2))
(Point width (groundTileHeight / 2)))
{ bodyCategoryBitMask = categoryBitMask [World] }
}
pipes :: LambdaNode
pipes = (node [])
{ nodeActionDirectives = [runActionSequenceForever
[ customAction (spawnPipePair birdWidth)
, waitForDuration{ actionDuration = 1.5 }
] ]
, nodeUserData = PipesState randomNums
}
score :: LambdaNode
score = (labelNodeWithFontNamed "MarkerFelt-Wide")
{ nodeName = Just "Score"
, nodePosition = Point (width / 2) (3 * height / 4)
, nodeZPosition = 100
, labelText = "0"
}
update :: LambdaScene -> TimeInterval -> LambdaScene
update scene@Scene{ sceneData = sceneState@SceneState{..} } _dt
= case gameState of
Running
| keyPressed -> bumpLambda scene{ sceneData = sceneState{ keyPressed = False } }
| bumpScore -> incScore scene{ sceneData = sceneState{ bumpScore = False } }
| otherwise -> tiltLambda scene
Crash -> crash scene{ sceneData = sceneState{ gameState = Over } }
Over -> scene
bumpLambda :: LambdaScene -> LambdaScene
bumpLambda scene
= scene { sceneActionDirectives = [runCustomActionOn "Lambda" bumpAction] }
tiltLambda :: LambdaScene -> LambdaScene
tiltLambda scene
= scene{ sceneActionDirectives = [runCustomActionOn "Lambda" tiltAction] }
crash :: LambdaScene -> LambdaScene
crash scene
= scene { sceneActionDirectives = [ runActionOn "Lambda" crashAction
, runActionOn "Moving" stopMoving
] }
where
crashAction = sequenceActions
[ (rotateByAngle (-pi * 4)){ actionDuration = 1 }
, fadeOut{ actionDuration = 0.2 }
]
stopMoving = sequenceActions
[ waitForDuration{ actionDuration = 1 }
, customAction $ \node _ -> node{ nodeSpeed = 0 }
]
incScore :: LambdaScene -> LambdaScene
incScore scene@Scene{ sceneData = sceneState }
= scene
{ sceneActionDirectives = [runCustomActionOn "Score" setScore]
, sceneData = sceneState{ sceneScore = newScore }
}
where
newScore = sceneScore sceneState + 1
setScore label@Label{} _dt = label{ labelText = show newScore }
setScore node _ = node
contact :: SceneState
-> PhysicsContact u
-> (Maybe SceneState, Maybe (Node u), Maybe (Node u))
contact state@SceneState{..} PhysicsContact{..}
| (isWorld contactBodyA || isWorld contactBodyB) && gameState == Running
= (Just state{ gameState = Crash }, Nothing, Nothing)
| isScore contactBodyA || isScore contactBodyB
= (Just state{ bumpScore = True }, Nothing, Nothing)
| otherwise
= (Nothing, Nothing, Nothing)
handleEvent :: Event -> SceneState -> Maybe SceneState
handleEvent KeyEvent{ keyEventType = KeyDown } state = Just state{ keyPressed = True }
handleEvent _ _ = Nothing
|
mchakravarty/lazy-lambda
|
LazyLambda.hsproj/LazyLambda.hs
|
mit
| 5,177 | 0 | 14 | 1,690 | 1,298 | 717 | 581 | 104 | 3 |
-- ex4.5.hs ex4.6.hs
data Client i = GovOrg { clientId :: i, clientName :: String }
| Company { clientId :: i, clientName :: String
, person :: Person, duty :: String }
| Individual { clientId :: i, person :: Person }
deriving Show
data Person = Person { firstName :: String, lastName :: String }
deriving Show
data ClientKind = GovOrgKind | CompanyKind | IndividualKind
deriving (Show, Eq, Ord)
instance Eq Person where
Person{firstName=fnm1,lastName=lnm1}
== Person{firstName=fnm2,lastName=lnm2} = fnm1==fnm2 && lnm1==lnm2
instance Eq i => Eq (Client i) where
GovOrg{clientId=cid1,clientName=cnm1}
== GovOrg{clientId=cid2,clientName=cnm2} = cid1==cid2 && cnm1==cnm2
Company{clientId=cid1,clientName=cnm1,person=p1,duty=d1}
== Company{clientId=cid2,clientName=cnm2,person=p2,duty=d2} =
cid1==cid2 && cnm1==cnm2 && p1==p2 && d1==d2
Individual{clientId=cid1,person=p1}
== Individual{clientId=cid2,person=p2} = cid1==cid2 && p1==p2
_ == _ = False
instance Ord Person where
Person{firstName=fnm1,lastName=lnm1}
<= Person{firstName=fnm2,lastName=lnm2} = fnm1<=fnm2 && lnm1<=lnm2
instance (Eq i, Ord i) => Ord (Client i) where
Individual{clientId=cid1,person=p1}
<= Individual{clientId=cid2,person=p2} = cid1<=cid2 && p1<=p2
Individual{} <= GovOrg{} = False
Individual{} <= Company{} = False
Company{} <= GovOrg{} = False
Company{} <= Individual{} = True
Company{clientId=cid1,clientName=cnm1,person=p1,duty=d1}
<= Company{clientId=cid2,clientName=cnm2,person=p2,duty=d2}
= cid1<=cid2 && cnm1<=cnm2 && p1<=p2 && d1<=d2
GovOrg{} <= Individual{} = True
GovOrg{} <= Company{} = True
GovOrg{clientId=cid1,clientName=cnm1}
<= GovOrg{clientId=cid2,clientName=cnm2} = cid1<=cid2 && cnm1<=cnm2
|
hnfmr/beginning_haskell
|
ex4.6.hs
|
mit
| 1,875 | 0 | 12 | 390 | 820 | 450 | 370 | 38 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Data.Vector.Generic.Fixed
( toFixed
, fromFixed
, (!)
, slice
, empty
, singleton
, replicate
) where
import Prelude hiding (replicate)
import qualified Data.Vector.Generic as G
import GHC.Exts
import GHC.TypeLits
import Numeric.Mod
newtype V (n :: Nat) v a = V { unV :: v a }
-- === Conversion ===
toFixed :: forall n v a. (KnownNat n, G.Vector v a) => a -> v a -> V n v a
toFixed padding v = let m = natValInt' (proxy# :: Proxy# n)
l = G.length v
in if m > l
then V (v G.++ G.replicate (m - l) padding)
else V (G.take m v)
fromFixed :: V n v a -> v a
fromFixed = unV
-- === Helpers ===
natValInt' :: KnownNat n => Proxy# n -> Int
natValInt' m = fromInteger (natVal' m)
-- === Replicated vector api ===
-- ACCESSORS
(!) :: (KnownNat n, G.Vector v a) => V n v a -> Mod n -> a
(V v) ! i = v G.! fromIntegral i
slice :: ( KnownNat start
, KnownNat length
, KnownNat total
, GT ~ CmpNat total (start + length)
, G.Vector v a
) => Proxy# start -> Proxy# length -> V total v a -> V length v a
slice n m = V . G.slice (natValInt' n) (natValInt' m) . unV
-- CONSTRUCTION
empty :: G.Vector v a => V 0 v a
empty = V G.empty
singleton :: G.Vector v a => a -> V 1 v a
singleton = V . G.singleton
replicate :: (KnownNat n, G.Vector v a) => Proxy# n -> a -> V n v a
replicate p a = V (G.replicate (natValInt' p) a)
|
nickspinale/n-vector
|
src/Data/Vector/Generic/Fixed.hs
|
mit
| 1,792 | 0 | 13 | 577 | 643 | 342 | 301 | 46 | 2 |
-- CommandLineArguments.hs ---
--
-- Filename: CommandLineArguments.hs
-- Description:
-- Author: Manuel Schneckenreither
-- Maintainer:
-- Created: Thu Sep 4 12:25:37 2014 (+0200)
-- Version:
-- Package-Requires: ()
-- Last-Updated: Tue Apr 11 14:34:02 2017 (+0200)
-- By: Manuel Schneckenreither
-- Update #: 38
-- URL:
-- Doc URL:
-- Keywords:
-- Compatibility:
--
--
-- Commentary:
--
--
--
--
-- Change Log:
--
--
--
--
--
-- Code:
-- | Reexporting the modules in ./CmdLineArguments
module Data.Rewriting.ARA.ByInferenceRules.CmdLineArguments
(
-- reexported modules
module Data.Rewriting.ARA.ByInferenceRules.CmdLineArguments.Type
, module Data.Rewriting.ARA.ByInferenceRules.CmdLineArguments.Parse
) where
import Data.Rewriting.ARA.ByInferenceRules.CmdLineArguments.Parse
import Data.Rewriting.ARA.ByInferenceRules.CmdLineArguments.Type
--
-- CmdLineArguments.hs ends here
|
ComputationWithBoundedResources/ara-inference
|
src/Data/Rewriting/ARA/ByInferenceRules/CmdLineArguments.hs
|
mit
| 946 | 0 | 5 | 166 | 83 | 72 | 11 | 6 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Data.PublicSuffix.TH
( moduleDirectory
, mkRules
) where
import Control.Applicative
import Data.Char
import Data.PublicSuffix.Types
import Language.Haskell.TH
import qualified Language.Haskell.TH.Syntax as TH
import System.FilePath (dropFileName)
import Prelude
readRulesFile :: FilePath -> IO [Rule]
readRulesFile inputFile = do
body <- readFile inputFile
return $ parseRules body
isComment :: String -> Bool
isComment ('/':'/':_) = True
isComment _ = False
splitDot :: String -> [String]
splitDot [] = [""]
splitDot x =
let (y, z) = break (== '.') x in
y : (if z == "" then [] else splitDot $ drop 1 z)
parseRules :: String -> [Rule]
parseRules body =
map parseRule $
filter ruleLine $
map (takeWhile (not . isSpace)) $ -- Each line is only read up to the first whitespace.
lines body -- The Public Suffix List consists of a series of lines, separated by \n.
where
ruleLine line = not $ isComment line || null line
parseRule :: String -> Rule
parseRule line = case line of
[] -> error "parseRule: unexpected empty line"
'!':rest -> Rule { isException = True, ruleLabels = splitDot rest }
_ -> Rule { isException = False, ruleLabels = splitDot line }
moduleDirectory :: Q Exp
moduleDirectory =
TH.LitE . TH.StringL . dropFileName . TH.loc_filename <$> TH.qLocation
mkRules :: String -> FilePath -> Q [Dec]
mkRules funName filePath = do
rules <- runIO $ readRulesFile filePath
rulesE <- mapM genRule rules
return
[ SigD (mkName "rules") (AppT ListT (ConT ''Rule))
, FunD (mkName funName) [Clause [] (NormalB $ ListE $ rulesE) []]
]
where
genRule :: Rule -> ExpQ
genRule rule = do
ruleE <- [| Rule |]
trueE <- [| True |]
falseE <- [| False |]
return $ foldl1 AppE
[ ruleE
, if isException rule then trueE else falseE
, ListE $ reverse $ map (\x -> LitE $ StringL x) (ruleLabels rule)
]
|
wereHamster/publicsuffix-haskell
|
src/Data/PublicSuffix/TH.hs
|
mit
| 2,203 | 0 | 17 | 658 | 678 | 358 | 320 | 55 | 3 |
module Zeno.Unification (
Unifiable (..), Unification (..),
applyUnification, mergeUnifiers, allUnifiers,
) where
import Prelude ()
import Zeno.Prelude
import Zeno.Utils
import Zeno.Traversing
import qualified Data.Map as Map
-- |The result of trying to unify two values where
-- 'NoUnifier' indicates that unification was impossible,
-- This is essentially 'Maybe (Substitution n a)'.
data Unification n a
= Unifier !(Substitution n a)
| NoUnifier
-- |Values which can be unified
class Unifiable a where
type Names a
unify :: a -> a -> Unification (Names a) a
-- |Appending two unifiers will create a unifier that will
-- perform both unifications, if such a unifier is still valid.
instance (Ord a, Eq b) => Monoid (Unification a b) where
mempty = Unifier mempty
mappend NoUnifier _ = NoUnifier
mappend _ NoUnifier = NoUnifier
mappend (Unifier left) (Unifier right)
| and (Map.elems inter) = Unifier (Map.union left right)
| otherwise = NoUnifier
where inter = Map.intersectionWith (==) left right
-- |This is like 'catMaybes'
mergeUnifiers :: [Unification a b] -> [Substitution a b]
mergeUnifiers = foldl' addUni []
where addUni subs NoUnifier = subs
addUni subs (Unifier sub) = sub : subs
applyUnification :: (WithinTraversable a f, Eq a) =>
Unification a a -> f -> f
applyUnification NoUnifier = id
applyUnification (Unifier sub) = substitute sub
allUnifiers :: (Unifiable a, WithinTraversable a f, Eq a, Ord (Names a)) =>
a -> f -> [Substitution (Names a) a]
allUnifiers from = mergeUnifiers . execWriter . (mapWithinM unifiers)
where unifiers to = tell [unify from to] >> return to
|
Gurmeet-Singh/Zeno
|
src/Zeno/Unification.hs
|
mit
| 1,646 | 0 | 12 | 312 | 507 | 269 | 238 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Unit.LayoutSpec (spec) where
import Data.Char (isLetter, isNumber)
import qualified Data.Text as T
import TestImport
import Data.List ((!!))
import Layout.Util (removeClass)
-------------------------------------------------------------------------------
spec :: Spec
spec = describe "removeClass" $ do
it "removes with single class" $
property prop_checkRemove_single
it "removes with multiple classes" $
property prop_checkRemove_multi
instance Arbitrary Text where
arbitrary = fromString <$> listOf1 (suchThat (arbitrary :: Gen Char) constraint)
where
constraint c = isLetter c || isNumber c || c == '-'
{-|
Property that makes sure the added class is removed when using a single class.
-}
prop_checkRemove_single :: Text -- ^ Class to add and remove
-> [(Text, Text)] -- ^ All other attributes
-> Bool
prop_checkRemove_single classToRemove based
= (removeClass classToRemove inpAttrs) == outpAttrs
where
inpAttrs = ("class", classToRemove) : based
outpAttrs = ("class", "") : based
{-|
Property that makes sure the added class is removed when using multiple classes.
Takes a list of classes and a random positive number. The random number is
modulated to an index of a class inside the class list. The class that has that
index is passed in to 'removeClass' as the class to be removed.
-}
prop_checkRemove_multi :: Positive Int -- ^ Index of class to test removal of
-> [Text] -- ^ All other class names
-> [(Text, Text)] -- ^ All other attributes
-> Bool
prop_checkRemove_multi (Positive randIndex) inpClasses otherAttrs
= (removeClass classToRemove inpAttrs) == outpAttrs
where
inpAttrs = ("class", joinAttrVals inpClasses) : otherAttrs
outpAttrs = ("class", joinAttrVals outpClasses) : otherAttrs
outpClasses = filter (/= classToRemove) inpClasses
classIndex' = (length inpClasses) `mod` randIndex
classIndex = if classIndex' == 0
then classIndex'
else classIndex' - 1
classToRemove = if null inpClasses
then ""
else inpClasses !! classIndex
-------------------------------------------------------------------------------
-- * Utils
{-|
Takes a list of HTML tag attribute values and joins them together. Can be used
to join a list of classes to give a tag.
>>> joinAttrVals ["btn", "btn-default"]
"btn btn-default"
>>> joinAttrVals [" btn", " btn-lg"]
"btn btn-lg"
-}
joinAttrVals :: [Text] -> Text
joinAttrVals = T.intercalate " " . map T.strip
|
rzetterberg/alven
|
src/test/Unit/LayoutSpec.hs
|
mit
| 2,778 | 0 | 11 | 725 | 456 | 254 | 202 | 41 | 3 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
module LiveVDom.Types where
-- Generic imports
import Control.Applicative
import Control.Concurrent.STM
import Control.Concurrent.STM.Notify
import Control.Monad hiding (mapM, mapM_, sequence)
import Data.Foldable (mapM_, toList, traverse_)
import Data.Monoid
import Data.Sequence ((|>))
import qualified Data.Sequence as S
import Data.Traversable
import Prelude hiding (mapM, mapM_, sequence)
-- Template haskell related
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
-- VDOM related
import Data.String
import GHCJS.VDOM.Attribute
import LiveVDom.Adapter.Types
--ghcjs-base
import Data.JSString (JSString)
import qualified Data.JSString as JS (pack, unpack)
newtype DomLoc = DomLoc { unDomLoc :: Int } deriving (Eq, Show)
type ElementLoc = [DomLoc]
domAt :: ElementLoc -> LiveVDom -> LiveVDom
domAt ((DomLoc i):xs) (LiveVNode _ _ _ _ children) = domAt xs $ S.index children i
instance (IsString a) => IsString (STMEnvelope a) where
fromString = return . fromString
-- | Resulting type from the quasiquoted valentine
data LiveVDom =
LiveVText {liveVTextEvents :: ![Attribute], liveVirtualText :: STMEnvelope JSString } -- ^ Child text with no tag name, properties, or children
| StaticText { staticTextEvents :: ![Attribute], staticText :: {-# UNPACK #-} !JSString }
| LiveVNode { liveVNodeEvents :: ![Attribute]
, liveVNodeTagName :: {-# UNPACK #-} !TagName
, liveVNodeNameSpace :: {-# UNPACK #-} !(Maybe JSString)
, liveVNodePropsList :: {-# UNPACK #-} ![Property]
, liveVNodeChildren :: !(S.Seq (LiveVDom))} -- ^ Basic tree structor for a node with children and properties
| LiveChild { liveVChildEvents :: ![Attribute], liveVChild :: STMEnvelope (LiveVDom)} -- ^ DOM that can change
| LiveChildren {liveVChildEvents :: ![Attribute], liveVChildren :: STMEnvelope (S.Seq (LiveVDom))} -- ^ A child that can change
-- |The instance on Monoid is designed to make it easy to paste together nodes in a for each kind of way
-- notably blending children and adding childs
-- However the text conditions are terminal
-- Events are kept with the incoming LiveVDom
-- append is like:
{-|
>>> let foo = [valentine| <div>
<div>
<div>
<div> |]
let bar = [valentine| <div> |]
$> foo <> bar
<div>
<div>
<div>
<div>
<bar>
let baz = [valentine| <div>
some text which will erase everything
|]
let bing = [valentine| <div> |]
$> baz <> bing
<div>
some text which will erase everything
|-}
instance Monoid LiveVDom where
mempty = StaticText [] ""
mappend nodeL nodeR = case nodeL of
(StaticText [] "") -> nodeR -- memtpy law RHS
txt@(LiveVText _ _ ) -> txt
txt@(StaticText _ _) -> txt -- Notice this means that all text is terminal (with respect to the monoid)!!!
(LiveVNode as tag nameSpace props children) -> LiveVNode as tag nameSpace props (appendToLastChild nodeR children )
(LiveChild es env) -> LiveChildren es $ fmap (appendToLastChild nodeR) (S.singleton <$> env)
lc@(LiveChildren es env) -> LiveChildren es (fmap (appendToLastChild nodeR) env)
where
appendToLastChild node children
|S.null children = S.singleton node
|otherwise = let index = S.length children - 1
in S.adjust (<> node) index children
-- | A template haskell representation for parsing
data PLiveVDom =
PLiveVText {pLiveVirtualText :: JSString } -- ^ Child text with no tag name, properties, or children
| PLiveVNode {pLiveVNodeTagName :: TagName
, pLiveVNodeNameSpace :: Maybe JSString
, pLiveVNodePropsList :: [Property]
, pLiveVNodeChildren :: [PLiveVDom]} -- ^ Basic tree structor for a node with children and properties
| PLiveChildren {pLiveVChild :: Exp} -- ^ A parsed TH Exp that will get turned into LiveChild
| PLiveInterpText {pLiveInterpText :: Exp} -- ^ Interpolated text that will get transformed into LiveVText
deriving (Show,Eq)
instance Lift PLiveVDom where
lift (PLiveVText st) = AppE (ConE 'PLiveVText) <$> (lift $ JS.unpack st)
lift (PLiveVNode tn ns pl ch) = do
qtn <- lift tn
qns <- lift $ fmap JS.unpack ns
qpl <- lift pl
qch <- lift ch
return $ AppE (AppE (AppE (AppE (ConE 'PLiveVNode) qtn) qns) qpl) qch
lift (PLiveChildren e) = return e
lift (PLiveInterpText t) = return t
-- | Add an event to a LiveVDom
addEvent :: Attribute -> LiveVDom -> LiveVDom
addEvent ev (LiveVText evs ch) = LiveVText (evs ++ [ev]) ch -- Child text with no tag name, properties, or children
addEvent ev (LiveVNode evs tn ns pls ch) = LiveVNode (evs ++ [ev]) tn ns pls ch -- Basic tree structor for a node with children and properties
addEvent ev (LiveChild evs vch) = LiveChild (evs ++ [ev]) vch -- DOM that can change
addEvent ev (LiveChildren evs vchs) = LiveChildren (evs ++ [ev]) vchs -- A child that can change
-- | Add multiple events to LiveVDom
addEvents :: [Attribute] -> LiveVDom -> LiveVDom
addEvents ev (LiveVText evs ch) = LiveVText (evs ++ ev) ch -- Child text with no tag name, properties, or children
addEvents ev (StaticText evs ch) = StaticText (evs ++ ev) ch -- Child text with no tag name, properties, or children
addEvents ev (LiveVNode evs tn ns pls ch) = LiveVNode (evs ++ ev) tn ns pls ch -- Basic tree structor for a node with children and properties
addEvents ev (LiveChild evs vch) = LiveChild (evs ++ ev) vch -- DOM that can change
addEvents ev (LiveChildren evs vchs) = LiveChildren (evs ++ ev) vchs
-- | Add a list of property to LiveVNode if it is a liveVNode
-- If it isn't it leaves the rest alone
addProps :: LiveVDom -> [Property] -> LiveVDom
addProps (LiveVNode evs tn ns pl ch) pl' = LiveVNode evs tn ns (pl ++ pl') ch
addProps l _ = l
-- | Append a list of children to LiveVDom
addChildren :: S.Seq (LiveVDom) -> LiveVDom -> LiveVDom
addChildren children (LiveVText _ _) = error "Error: Text node can't have children"
addChildren children (StaticText _ _) = error "Error: Static text nodes can't have children"
addChildren children (LiveVNode evs tn ns pls ch) = LiveVNode evs tn ns pls $ ch S.>< children
addChildren children (LiveChild _ _) = error "Error: LiveChild node can't have children"
addChildren children (LiveChildren evs vchs) = LiveChildren evs $ (S.>< children) <$> vchs
-- | Append a single child to LiveVDom
addChild :: LiveVDom -> LiveVDom -> LiveVDom
addChild x lv = addChildren (S.singleton x) lv
-- | add a dom listener to a a given node and all children of that node
addDomListener :: TMVar () -> LiveVDom -> STM ()
addDomListener tm (LiveVText _ t) = addListener t tm
addDomListener tm (StaticText _ t) = return ()
addDomListener tm (LiveVNode _ _ _ _ ch) = traverse_ (addDomListener tm) ch
addDomListener tm (LiveChild _ vch) = (addListener vch tm) >>
(addDomListener tm =<< recv vch)
addDomListener tm (LiveChildren _ vchs) = do
addListener vchs tm
xs <- recv vchs
mapM_ (addDomListener tm) xs
-- | Wait for a change in LiveVDom
-- this recursively adds an empty tmvar to each element
-- and waits for a change
waitForDom :: STMEnvelope (LiveVDom) -> IO ()
waitForDom envDom = do
dom <- recvIO envDom
listener <- atomically $ do
listen <- newEmptyTMVar
addListener envDom listen
addDomListener listen dom
return listen
atomically $ readTMVar listener
|
plow-technologies/live-vdom
|
src/LiveVDom/Types.hs
|
mit
| 7,971 | 0 | 17 | 2,003 | 1,945 | 1,034 | 911 | 123 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleInstances #-}
module Systems where
import Control.Monad.IO.Class (liftIO)
--import Control.Monad (when, liftM, join)
import Control.Lens
import qualified Data.IntMap.Strict as I
import Types
import HasComponents
-- probably not needed:
--newtype StorableSystem = StorableSystem {toAction :: Cesh ()}
-- | Systems are run on every entity that matches the input matcher
class System s where
-- | Dependencies for the System, these are 'Component's which the System takes as input
deps :: s -> [TagId]
-- | Outputs of the System, these are 'Component's which the System can modify
outs :: s -> [TagId]
-- | Internal; Convert the system to an action. Specifies how the System is called
-- and results are handled.
toAction :: s -> Cesh ()
-- | Registers a 'System', meaning it is now in use and will be run every frame.
-- The order in which the 'System's are run is specified by the order they are registered.
-- NOTE: This should be done before any Entities are added.
registerSystem :: System s => s -> Cesh ()
registerSystem sys = do
let storableSystem = toAction sys
systems %= (storableSystem :)
-- | Container in which the Components are stored and passed for Systems
type CList a = [a]
-- | Input system
newtype InputSystem o = InputSystem (IO o)
instance HasComponents o => System (InputSystem o) where
deps _ = []
outs _ = extractTagIds (error "typeholder" :: o)
toAction (InputSystem sys) = do
entities <- _
res <- liftIO sys
compsByType %= (M.union $ toSomeComponents res)
return ()
-- | Output system
newtype OutputSystem d = OutputSystem (d -> IO ())
instance HasComponents d => System (OutputSystem (CList d)) where
deps _ = extractTagIds (error "typeholder" :: d)
outs _ = []
toAction (OutputSystem sys) = do
-- TODO: get inputs
liftIO $ sys undefined
-- | Semipure system
-- Pure computation, but may also add or remove Components (or Entities?).
newtype SemipureSystem d o = SemipureSystem (d -> Cesh o)
instance (HasComponents d, HasComponents o) => System (SemipureSystem (CList d) (CList o)) where
deps _ = extractTagIds (error "typeholder" :: d)
outs _ = extractTagIds (error "typeholder" :: o)
toAction (SemipureSystem sys) = do
-- TODO: get inputs
res <- sys undefined
-- TODO: save results
return ()
-- | Pure system
-- Can only do pure computations and may not modify anything else than what is in the type signature.
newtype PureSystem d o = PureSystem (d -> o)
instance (HasComponents d, HasComponents o) => System (PureSystem (CList d) (CList o)) where
deps _ = extractTagIds (error "typeholder" :: d)
outs _ = extractTagIds (error "typeholder" :: o)
toAction (PureSystem sys) = do
-- TODO: get inputs
let res = sys undefined
-- TODO: save results
return ()
|
TK009/CESH
|
src/Systems.hs
|
mit
| 2,976 | 0 | 11 | 697 | 665 | 354 | 311 | 46 | 1 |
-- | Like Latency, but creating lots of channels
import Hypervisor.XenStore
import Hypervisor.DomainInfo
import Hypervisor.Debug
import Data.List
import Control.Monad
import Control.Applicative
import Control.Distributed.Process
import Control.Distributed.Process.Node
import Network.Transport.IVC (createTransport, waitForDoms, waitForKey)
import Data.Binary (encode, decode)
pingServer :: Process ()
pingServer = forever $ do
them <- expect
sendChan them ()
-- TODO: should this be automatic?
reconnectPort them
pingClient :: Int -> ProcessId -> Process ()
pingClient n them = do
replicateM_ n $ do
(sc, rc) <- newChan :: Process (SendPort (), ReceivePort ())
send them sc
receiveChan rc
liftIO . writeDebugConsole $ "Did " ++ show n ++ " pings\n"
initialProcess :: XenStore -> String -> Process ()
initialProcess xs "SERVER" = do
us <- getSelfPid
liftIO $ xsWrite xs "/process/server-pid" (show (encode us))
pingServer
initialProcess xs "CLIENT" = do
them <- liftIO $ decode . read <$> waitForKey xs "/process/server-pid"
pingClient 10 them
main :: IO ()
main = do
xs <- initXenStore
Right transport <- createTransport xs
doms <- sort <$> waitForDoms xs 2
me <- xsGetDomId xs
let role = if me == head doms then "SERVER" else "CLIENT"
node <- newLocalNode transport initRemoteTable
runProcess node $ initialProcess xs role
|
hackern/network-transport-ivc
|
benchmarks/Channels/Main.hs
|
mit
| 1,378 | 0 | 14 | 247 | 445 | 217 | 228 | 39 | 2 |
-- | This module, as the name suggests, serves as a utility module for ciphers
-- like the Vigenère cipher, which depends upon shifting alphabet characters by
-- some amount.
module Text.Cipher.Util where
import Data.Char (toLower, toUpper)
import Data.List (elemIndex, nub)
-- | Checks whether its argument is a member of the German vowel set (a, ä, e,
-- i, o, ö, u, ü).
isVowel :: Char -> Bool
isVowel = flip elem "aeiouäöü"
-- | Returns a character's position (0-based index) in the alphabet.
--
-- __Note:__ `c' can be passed as both lower and upper case.
alphabetPos :: Char -> Maybe Int
alphabetPos c = elemIndex (toLower c) ['a'..'z']
-- | Finds the alphabet's nth character and wraps around larger indices.
--
-- __Note:__ Returns only lowercase letters.
--
-- @isAlpha c ==> (charAtPos =<< alphabetPos c) == return (toLower c)@
charAtPos :: Int -> Maybe Char
charAtPos p = lookup (abs $ p `mod` 26) (zip [0..] ['a'..'z'])
-- | Generates a unique alphabet starting with the key, with all consecutively
-- duplicated characters removed.
--
-- >>> makeAlpha "hello"
-- "HELOABCDFGIJKMNPQRSTUVWXYZ"
--
-- @all isAlpha str ==> length (makeAlpha str) == 26@
makeAlpha :: String -> String
makeAlpha k = nub (key ++ alpha)
where
alpha = ['A' .. 'Z']
key = map toUpper =<< words k
|
kmein/ciphers
|
src/Text/Cipher/Util.hs
|
mit
| 1,311 | 0 | 8 | 243 | 217 | 127 | 90 | 13 | 1 |
module Palindrome where
palindrome :: Eq a => [a] -> Bool
palindrome [] = True
palindrome [_] = True
palindrome xs = (head xs) == (last xs) && (palindrome $ init $ tail xs)
|
kaveet/haskell-snippets
|
modules/lists/Palindrome.hs
|
mit
| 176 | 0 | 8 | 37 | 86 | 45 | 41 | 5 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
module Hogldev.CubemapTexture (
CubemapTexture (..)
, CubeMapFilenames (..)
, cubeMapTexBind
, loadCubemapTexture
) where
import Control.Arrow (second)
import Control.Monad (forM_)
import System.FilePath (combine)
import qualified Graphics.Rendering.OpenGL.GL.VertexArrays as GL
import Graphics.Rendering.OpenGL hiding (Texture)
import Graphics.GLUtil.JuicyTextures
import Graphics.GLUtil
data CubemapTexture =
CubemapTexture
{ textureObject :: !TextureObject
} deriving Show
data CubeMapFilenames =
CubeMapFilenames
{ directory :: !FilePath
, posXFilename :: !FilePath
, negXFilename :: !FilePath
, posYFilename :: !FilePath
, negYFilename :: !FilePath
, posZFilename :: !FilePath
, negZFilename :: !FilePath
} deriving Show
-- | A helper function to handle images. Stolen from GLUtil library.
loadCubeTexture :: forall a. IsPixelData a =>
TextureTargetCubeMapFace -> TextureObject -> TexInfo a -> IO TextureObject
loadCubeTexture target obj tex = do
textureBinding Texture2D $= Just obj
loadTex $ texColor tex
return obj
where
loadTex TexMono = case pixelType of
GL.UnsignedShort -> loadAux Luminance16 Luminance
GL.Float -> loadAux R32F Red
GL.HalfFloat -> loadAux R16F Red
GL.UnsignedByte -> loadAux R8 Red
_ -> loadAux Luminance' Luminance
loadTex TexRG = case pixelType of
GL.UnsignedShort -> loadAux RG16 RGInteger
GL.Float -> loadAux RG32F RG
GL.HalfFloat -> loadAux RG16F RG
GL.UnsignedByte -> loadAux RG8UI RGInteger
GL.Byte -> loadAux RG8I RGInteger
GL.Int -> loadAux RG32I RGInteger
GL.UnsignedInt -> loadAux RG32UI RGInteger
_ -> error "Unknown pixelType for TexRG"
loadTex TexRGB = loadAux RGBA' RGB
loadTex TexBGR = loadAux RGBA' BGR
loadTex TexRGBA = loadAux RGBA' RGBA
sz = TextureSize2D (texWidth tex) (texHeight tex)
pixelType = glType (undefined::Elem a)
loadAux i e = withPixels (texData tex)
(texImage2D target NoProxy 0 i sz 0 . PixelData e pixelType)
loadCubemapTexture :: CubeMapFilenames -> IO CubemapTexture
loadCubemapTexture CubeMapFilenames{..} = do
[object] <- genObjectNames 1
textureBinding TextureCubeMap $= Just object
forM_ targetFile $ \ (target, fileName) -> do
res <- readTexInfo fileName (loadCubeTexture target object)
case res of
Left msg -> error msg
Right _ -> do
textureFilter TextureCubeMap $= ((Linear', Nothing), Linear')
textureWrapMode TextureCubeMap S $= (Repeated, ClampToEdge)
textureWrapMode TextureCubeMap T $= (Repeated, ClampToEdge)
textureWrapMode TextureCubeMap R $= (Repeated, ClampToEdge)
return CubemapTexture { textureObject = object }
where
targetFile :: [(TextureTargetCubeMapFace, FilePath)]
targetFile = map (second (combine directory))
[ (TextureCubeMapPositiveX, posXFilename)
, (TextureCubeMapNegativeX, negXFilename)
, (TextureCubeMapPositiveY, posYFilename)
, (TextureCubeMapNegativeY, negYFilename)
, (TextureCubeMapPositiveZ, posZFilename)
, (TextureCubeMapNegativeZ, negZFilename)
]
cubeMapTexBind :: CubemapTexture -> TextureUnit -> IO ()
cubeMapTexBind CubemapTexture{..} textureUnit = do
activeTexture $= textureUnit
textureBinding TextureCubeMap $= Just textureObject
|
triplepointfive/hogldev
|
common/Hogldev/CubemapTexture.hs
|
mit
| 3,838 | 0 | 18 | 966 | 926 | 481 | 445 | 103 | 16 |
module Paths_snap (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
version :: Version
version = Version {versionBranch = [0,1], versionTags = []}
bindir, libdir, datadir, libexecdir :: FilePath
bindir = "/Users/kieran/.cabal/bin"
libdir = "/Users/kieran/.cabal/lib/snap-0.1/ghc-7.4.2"
datadir = "/Users/kieran/.cabal/share/snap-0.1"
libexecdir = "/Users/kieran/.cabal/libexec"
getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath
getBinDir = catchIO (getEnv "snap_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "snap_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "snap_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "snap_libexecdir") (\_ -> return libexecdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
|
kjgorman/melchior
|
comparison/snap/dist/build/autogen/Paths_snap.hs
|
mit
| 1,102 | 0 | 10 | 164 | 323 | 184 | 139 | 25 | 1 |
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Foundation.hs file.
module Settings where
import ClassyPrelude.Yesod hiding (throw)
import Control.Exception (throw)
import Data.Aeson (Result (..), fromJSON, withObject, (.!=),
(.:?))
import Data.FileEmbed (embedFile)
import Data.Yaml (decodeEither')
import Database.Persist.Postgresql (PostgresConf)
import Language.Haskell.TH.Syntax (Exp, Name, Q)
import Network.Wai.Handler.Warp (HostPreference)
import Yesod.Default.Config2 (applyEnvValue, configSettingsYml)
import Yesod.Default.Util (WidgetFileSettings, widgetFileNoReload,
widgetFileReload)
import Yesod.Fay
-- | Runtime settings to configure this application. These settings can be
-- loaded from various sources: defaults, environment variables, config files,
-- theoretically even a database.
data AppSettings = AppSettings
{ appStaticDir :: String
-- ^ Directory from which to serve static files.
, appDatabaseConf :: PostgresConf
-- ^ Configuration settings for accessing the database.
, appRoot :: Text
-- ^ Base for all generated URLs.
, appHost :: HostPreference
-- ^ Host/interface the server should bind to.
, appPort :: Int
-- ^ Port to listen on
, appIpFromHeader :: Bool
-- ^ Get the IP address from the header when logging. Useful when sitting
-- behind a reverse proxy.
, appDetailedRequestLogging :: Bool
-- ^ Use detailed request logging system
, appShouldLogAll :: Bool
-- ^ Should all log messages be displayed?
, appReloadTemplates :: Bool
-- ^ Use the reload version of templates
, appMutableStatic :: Bool
-- ^ Assume that files in the static dir may change after compilation
, appSkipCombining :: Bool
-- ^ Perform no stylesheet/script combining
-- Example app-specific configuration values.
, appCopyright :: Text
-- ^ Copyright text to appear in the footer of the page
, appAnalytics :: Maybe Text
-- ^ Google Analytics code
, appYaWebMaster :: Maybe Text
-- ^ Yandex Webmaster
}
instance FromJSON AppSettings where
parseJSON = withObject "AppSettings" $ \o -> do
let defaultDev =
#if DEVELOPMENT
True
#else
False
#endif
appStaticDir <- o .: "static-dir"
appDatabaseConf <- o .: "database"
appRoot <- o .: "approot"
appHost <- fromString <$> o .: "host"
appPort <- o .: "port"
appIpFromHeader <- o .: "ip-from-header"
appDetailedRequestLogging <- o .:? "detailed-logging" .!= defaultDev
appShouldLogAll <- o .:? "should-log-all" .!= defaultDev
appReloadTemplates <- o .:? "reload-templates" .!= defaultDev
appMutableStatic <- o .:? "mutable-static" .!= defaultDev
appSkipCombining <- o .:? "skip-combining" .!= defaultDev
appCopyright <- o .: "copyright"
appAnalytics <- o .:? "analytics"
appYaWebMaster <- o .:? "yawebmaster"
return AppSettings {..}
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
--
-- For more information on modifying behavior, see:
--
-- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def
-- | How static files should be combined.
combineSettings :: CombineSettings
combineSettings = def
-- The rest of this file contains settings which rarely need changing by a
-- user.
widgetFile :: String -> Q Exp
widgetFile = (if appReloadTemplates compileTimeAppSettings
then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
fayFile' :: Exp -> FayFile
fayFile' staticR moduleName =
(if appReloadTemplates compileTimeAppSettings
then fayFileReload
else fayFileProd)
settings
where
settings = (yesodFaySettings moduleName)
{ yfsSeparateRuntime = Just ("static", staticR)
-- , yfsPostProcess = readProcess "java" ["-jar", "closure-compiler.jar"]
, yfsExternal = Just ("static", staticR)
, yfsPackages = ["fay-dom"]
, yfsTypecheckDevel = True
}
-- | Raw bytes at compile time of @config/settings.yml@
configSettingsYmlBS :: ByteString
configSettingsYmlBS = $(embedFile configSettingsYml)
-- | @config/settings.yml@, parsed to a @Value@.
configSettingsYmlValue :: Value
configSettingsYmlValue = either throw id $ decodeEither' configSettingsYmlBS
-- | A version of @AppSettings@ parsed at compile time from @config/settings.yml@.
compileTimeAppSettings :: AppSettings
compileTimeAppSettings =
case fromJSON $ applyEnvValue False mempty configSettingsYmlValue of
Error e -> error e
Success settings -> settings
-- The following two functions can be used to combine multiple CSS or JS files
-- at compile time to decrease the number of http requests.
-- Sample usage (inside a Widget):
--
-- > $(combineStylesheets 'StaticR [style1_css, style2_css])
combineStylesheets :: Name -> [Route Static] -> Q Exp
combineStylesheets = combineStylesheets'
(appSkipCombining compileTimeAppSettings)
combineSettings
combineScripts :: Name -> [Route Static] -> Q Exp
combineScripts = combineScripts'
(appSkipCombining compileTimeAppSettings)
combineSettings
|
swamp-agr/carbuyer-advisor
|
Settings.hs
|
mit
| 6,022 | 0 | 12 | 1,629 | 830 | 476 | 354 | -1 | -1 |
{-# htermination (succTup0 :: Tup0 -> Tup0) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Tup0 = Tup0 ;
data MyInt = Pos Nat | Neg Nat ;
data Nat = Succ Nat | Zero ;
fromEnumTup0 :: Tup0 -> MyInt
fromEnumTup0 Tup0 = Pos Zero;
primMinusNat :: Nat -> Nat -> MyInt;
primMinusNat Zero Zero = Pos Zero;
primMinusNat Zero (Succ y) = Neg (Succ y);
primMinusNat (Succ x) Zero = Pos (Succ x);
primMinusNat (Succ x) (Succ y) = primMinusNat x y;
primPlusNat :: Nat -> Nat -> Nat;
primPlusNat Zero Zero = Zero;
primPlusNat Zero (Succ y) = Succ y;
primPlusNat (Succ x) Zero = Succ x;
primPlusNat (Succ x) (Succ y) = Succ (Succ (primPlusNat x y));
primPlusInt :: MyInt -> MyInt -> MyInt;
primPlusInt (Pos x) (Neg y) = primMinusNat x y;
primPlusInt (Neg x) (Pos y) = primMinusNat y x;
primPlusInt (Neg x) (Neg y) = Neg (primPlusNat x y);
primPlusInt (Pos x) (Pos y) = Pos (primPlusNat x y);
psMyInt :: MyInt -> MyInt -> MyInt
psMyInt = primPlusInt;
pt :: (c -> a) -> (b -> c) -> b -> a;
pt f g x = f (g x);
primEqNat :: Nat -> Nat -> MyBool;
primEqNat Zero Zero = MyTrue;
primEqNat Zero (Succ y) = MyFalse;
primEqNat (Succ x) Zero = MyFalse;
primEqNat (Succ x) (Succ y) = primEqNat x y;
primEqInt :: MyInt -> MyInt -> MyBool;
primEqInt (Pos (Succ x)) (Pos (Succ y)) = primEqNat x y;
primEqInt (Neg (Succ x)) (Neg (Succ y)) = primEqNat x y;
primEqInt (Pos Zero) (Neg Zero) = MyTrue;
primEqInt (Neg Zero) (Pos Zero) = MyTrue;
primEqInt (Neg Zero) (Neg Zero) = MyTrue;
primEqInt (Pos Zero) (Pos Zero) = MyTrue;
primEqInt vv vw = MyFalse;
esEsMyInt :: MyInt -> MyInt -> MyBool
esEsMyInt = primEqInt;
toEnum0 MyTrue vx = Tup0;
toEnum1 vx = toEnum0 (esEsMyInt vx (Pos Zero)) vx;
toEnumTup0 :: MyInt -> Tup0
toEnumTup0 vx = toEnum1 vx;
succTup0 :: Tup0 -> Tup0
succTup0 = pt toEnumTup0 (pt (psMyInt (Pos (Succ Zero))) fromEnumTup0);
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/basic_haskell/succ_1.hs
|
mit
| 1,934 | 0 | 13 | 422 | 927 | 488 | 439 | 48 | 1 |
module HaskQuest.Game.State
( module HaskQuest.Game.State.GameStateMonad
, module HaskQuest.Game.State.SimpleState
) where
import HaskQuest.Game.State.GameStateMonad
import HaskQuest.Game.State.SimpleState
|
pdarragh/HaskQuest
|
src/HaskQuest/Game/State.hs
|
mit
| 219 | 0 | 5 | 27 | 39 | 28 | 11 | 5 | 0 |
{-
Copyright (C) 2006-2012 John MacFarlane <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Readers.LaTeX
Copyright : Copyright (C) 2006-2012 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
Conversion of LaTeX to 'Pandoc' document.
-}
module Text.Pandoc.Readers.LaTeX ( readLaTeX,
rawLaTeXInline,
rawLaTeXBlock,
handleIncludes
) where
import Text.ParserCombinators.Parsec hiding ((<|>), space, many, optional)
import Text.Pandoc.Definition
import Text.Pandoc.Shared
import Text.Pandoc.Parsing
import qualified Text.Pandoc.UTF8 as UTF8
import Data.Char ( chr, ord )
import Control.Monad
import Text.Pandoc.Builder
import Data.Char (isLetter, isPunctuation, isSpace)
import Control.Applicative
import Data.Monoid
import System.FilePath (replaceExtension)
import Data.List (intercalate)
import qualified Data.Map as M
-- | Parse LaTeX from string and return 'Pandoc' document.
readLaTeX :: ParserState -- ^ Parser state, including options for parser
-> String -- ^ String to parse (assumes @'\n'@ line endings)
-> Pandoc
readLaTeX = readWith parseLaTeX
parseLaTeX :: LP Pandoc
parseLaTeX = do
bs <- blocks
eof
st <- getState
let title' = stateTitle st
let authors' = stateAuthors st
let date' = stateDate st
return $ Pandoc (Meta title' authors' date') $ toList bs
type LP = GenParser Char ParserState
anyControlSeq :: LP String
anyControlSeq = do
char '\\'
next <- option '\n' anyChar
name <- case next of
'\n' -> return ""
c | isLetter c -> (c:) <$> (many letter <* optional sp)
| otherwise -> return [c]
return name
controlSeq :: String -> LP String
controlSeq name = try $ do
char '\\'
case name of
"" -> mzero
[c] | not (isLetter c) -> string [c]
cs -> string cs <* notFollowedBy letter <* optional sp
return name
dimenarg :: LP String
dimenarg = try $ do
ch <- option "" $ string "="
num <- many1 digit
dim <- oneOfStrings ["pt","pc","in","bp","cm","mm","dd","cc","sp"]
return $ ch ++ num ++ dim
sp :: LP ()
sp = skipMany1 $ satisfy (\c -> c == ' ' || c == '\t')
<|> (try $ newline >>~ lookAhead anyChar >>~ notFollowedBy blankline)
isLowerHex :: Char -> Bool
isLowerHex x = x >= '0' && x <= '9' || x >= 'a' && x <= 'f'
tildeEscape :: LP Char
tildeEscape = try $ do
string "^^"
c <- satisfy (\x -> x >= '\0' && x <= '\128')
d <- if isLowerHex c
then option "" $ count 1 (satisfy isLowerHex)
else return ""
if null d
then case ord c of
x | x >= 64 && x <= 127 -> return $ chr (x - 64)
| otherwise -> return $ chr (x + 64)
else return $ chr $ read ('0':'x':c:d)
comment :: LP ()
comment = do
char '%'
skipMany (satisfy (/='\n'))
newline
return ()
bgroup :: LP ()
bgroup = () <$ char '{'
<|> () <$ controlSeq "bgroup"
<|> () <$ controlSeq "begingroup"
egroup :: LP ()
egroup = () <$ char '}'
<|> () <$ controlSeq "egroup"
<|> () <$ controlSeq "endgroup"
grouped :: Monoid a => LP a -> LP a
grouped parser = try $ bgroup *> (mconcat <$> manyTill parser egroup)
braced :: LP String
braced = bgroup *> (concat <$> manyTill
( many1 (satisfy (\c -> c /= '\\' && c /= '}' && c /= '{'))
<|> try (string "\\}")
<|> try (string "\\{")
<|> try (string "\\\\")
<|> ((\x -> "{" ++ x ++ "}") <$> braced)
<|> count 1 anyChar
) egroup)
bracketed :: Monoid a => LP a -> LP a
bracketed parser = try $ char '[' *> (mconcat <$> manyTill parser (char ']'))
trim :: String -> String
trim = removeLeadingTrailingSpace
mathDisplay :: LP String -> LP Inlines
mathDisplay p = displayMath <$> (try p >>= applyMacros' . trim)
mathInline :: LP String -> LP Inlines
mathInline p = math <$> (try p >>= applyMacros')
mathChars :: LP String
mathChars = concat <$>
many ( many1 (satisfy (\c -> c /= '$' && c /='\\'))
<|> (\c -> ['\\',c]) <$> (try $ char '\\' *> anyChar)
)
double_quote :: LP Inlines
double_quote = (doubleQuoted . mconcat) <$>
(try $ string "``" *> manyTill inline (try $ string "''"))
single_quote :: LP Inlines
single_quote = char '`' *>
( try ((singleQuoted . mconcat) <$>
manyTill inline (try $ char '\'' >> notFollowedBy letter))
<|> lit "`")
inline :: LP Inlines
inline = (mempty <$ comment)
<|> (space <$ sp)
<|> inlineText
<|> inlineCommand
<|> grouped inline
<|> (char '-' *> option (str "-")
((char '-') *> option (str "–") (str "—" <$ char '-')))
<|> double_quote
<|> single_quote
<|> (str "’" <$ char '\'')
<|> (str "\160" <$ char '~')
<|> (mathDisplay $ string "$$" *> mathChars <* string "$$")
<|> (mathInline $ char '$' *> mathChars <* char '$')
<|> (superscript <$> (char '^' *> tok))
<|> (subscript <$> (char '_' *> tok))
<|> (failUnlessLHS *> char '|' *> doLHSverb)
<|> (str <$> count 1 tildeEscape)
<|> (str <$> string "]")
<|> (str <$> string "#") -- TODO print warning?
<|> (str <$> string "&") -- TODO print warning?
-- <|> (str <$> count 1 (satisfy (\c -> c /= '\\' && c /='\n' && c /='}' && c /='{'))) -- eat random leftover characters
inlines :: LP Inlines
inlines = mconcat <$> many (notFollowedBy (char '}') *> inline)
block :: LP Blocks
block = (mempty <$ comment)
<|> (mempty <$ ((spaceChar <|> newline) *> spaces))
<|> environment
<|> mempty <$ macro -- TODO improve macros, make them work everywhere
<|> blockCommand
<|> grouped block
<|> paragraph
<|> (mempty <$ char '&') -- loose & in table environment
blocks :: LP Blocks
blocks = mconcat <$> many block
blockCommand :: LP Blocks
blockCommand = try $ do
name <- anyControlSeq
star <- option "" (string "*" <* optional sp)
let name' = name ++ star
case M.lookup name' blockCommands of
Just p -> p
Nothing -> case M.lookup name blockCommands of
Just p -> p
Nothing -> mzero
inBrackets :: Inlines -> Inlines
inBrackets x = (str "[") <> x <> (str "]")
-- eat an optional argument and one or more arguments in braces
ignoreInlines :: String -> (String, LP Inlines)
ignoreInlines name = (name, doraw <|> (mempty <$ optargs))
where optargs = skipopts *> skipMany (try $ optional sp *> braced)
contseq = '\\':name
doraw = (rawInline "latex" . (contseq ++) . snd) <$>
(getState >>= guard . stateParseRaw >> (withRaw optargs))
ignoreBlocks :: String -> (String, LP Blocks)
ignoreBlocks name = (name, doraw <|> (mempty <$ optargs))
where optargs = skipopts *> skipMany (try $ optional sp *> braced)
contseq = '\\':name
doraw = (rawBlock "latex" . (contseq ++) . snd) <$>
(getState >>= guard . stateParseRaw >> (withRaw optargs))
blockCommands :: M.Map String (LP Blocks)
blockCommands = M.fromList $
[ ("par", mempty <$ skipopts)
, ("title", mempty <$ (skipopts *> tok >>= addTitle))
, ("subtitle", mempty <$ (skipopts *> tok >>= addSubtitle))
, ("author", mempty <$ (skipopts *> authors))
-- -- in letter class, temp. store address & sig as title, author
, ("address", mempty <$ (skipopts *> tok >>= addTitle))
, ("signature", mempty <$ (skipopts *> authors))
, ("date", mempty <$ (skipopts *> tok >>= addDate))
-- sectioning
, ("chapter", updateState (\s -> s{ stateHasChapters = True }) *> section 0)
, ("section", section 1)
, ("subsection", section 2)
, ("subsubsection", section 3)
, ("paragraph", section 4)
, ("subparagraph", section 5)
-- beamer slides
, ("frametitle", section 3)
, ("framesubtitle", section 4)
-- letters
, ("opening", (para . trimInlines) <$> (skipopts *> tok))
, ("closing", skipopts *> closing)
--
, ("rule", skipopts *> tok *> tok *> pure horizontalRule)
, ("begin", mzero) -- these are here so they won't be interpreted as inline
, ("end", mzero)
, ("item", skipopts *> loose_item)
, ("documentclass", skipopts *> braced *> preamble)
] ++ map ignoreBlocks
-- these commands will be ignored unless --parse-raw is specified,
-- in which case they will appear as raw latex blocks
[ "newcommand", "renewcommand", "newenvironment", "renewenvironment"
-- newcommand, etc. should be parsed by macro, but we need this
-- here so these aren't parsed as inline commands to ignore
, "special", "pdfannot", "pdfstringdef"
, "bibliography", "bibliographystyle"
, "maketitle", "makeindex", "makeglossary"
, "addcontentsline", "addtocontents", "addtocounter"
-- \ignore{} is used conventionally in literate haskell for definitions
-- that are to be processed by the compiler but not printed.
, "ignore"
, "hyperdef"
, "noindent"
, "markboth", "markright", "markleft"
, "hspace", "vspace"
]
addTitle :: Inlines -> LP ()
addTitle tit = updateState (\s -> s{ stateTitle = toList tit })
addSubtitle :: Inlines -> LP ()
addSubtitle tit = updateState (\s -> s{ stateTitle = stateTitle s ++
toList (str ":" <> linebreak <> tit) })
authors :: LP ()
authors = try $ do
char '{'
let oneAuthor = mconcat <$>
many1 (notFollowedBy' (controlSeq "and") >> inline)
auths <- sepBy oneAuthor (controlSeq "and")
char '}'
updateState (\s -> s { stateAuthors = map (normalizeSpaces . toList) auths })
addDate :: Inlines -> LP ()
addDate dat = updateState (\s -> s{ stateDate = toList dat })
section :: Int -> LP Blocks
section lvl = do
hasChapters <- stateHasChapters `fmap` getState
let lvl' = if hasChapters then lvl + 1 else lvl
skipopts
contents <- grouped inline
return $ header lvl' contents
inlineCommand :: LP Inlines
inlineCommand = try $ do
name <- anyControlSeq
guard $ not $ isBlockCommand name
parseRaw <- stateParseRaw `fmap` getState
star <- option "" (string "*")
let name' = name ++ star
let rawargs = withRaw (skipopts *> option "" dimenarg
*> many braced) >>= applyMacros' . snd
let raw = if parseRaw
then (rawInline "latex" . (('\\':name') ++)) <$> rawargs
else mempty <$> rawargs
case M.lookup name' inlineCommands of
Just p -> p <|> raw
Nothing -> case M.lookup name inlineCommands of
Just p -> p <|> raw
Nothing -> raw
unlessParseRaw :: LP ()
unlessParseRaw = getState >>= guard . not . stateParseRaw
isBlockCommand :: String -> Bool
isBlockCommand s = maybe False (const True) $ M.lookup s blockCommands
inlineCommands :: M.Map String (LP Inlines)
inlineCommands = M.fromList $
[ ("emph", emph <$> tok)
, ("textit", emph <$> tok)
, ("textsc", smallcaps <$> tok)
, ("sout", strikeout <$> tok)
, ("textsuperscript", superscript <$> tok)
, ("textsubscript", subscript <$> tok)
, ("textbackslash", lit "\\")
, ("backslash", lit "\\")
, ("textbf", strong <$> tok)
, ("ldots", lit "…")
, ("dots", lit "…")
, ("mdots", lit "…")
, ("sim", lit "~")
, ("label", unlessParseRaw >> (inBrackets <$> tok))
, ("ref", unlessParseRaw >> (inBrackets <$> tok))
, ("(", mathInline $ manyTill anyChar (try $ string "\\)"))
, ("[", mathDisplay $ manyTill anyChar (try $ string "\\]"))
, ("ensuremath", mathInline $ braced)
, ("P", lit "¶")
, ("S", lit "§")
, ("$", lit "$")
, ("%", lit "%")
, ("&", lit "&")
, ("#", lit "#")
, ("_", lit "_")
, ("{", lit "{")
, ("}", lit "}")
-- old TeX commands
, ("em", emph <$> inlines)
, ("it", emph <$> inlines)
, ("sl", emph <$> inlines)
, ("bf", strong <$> inlines)
, ("rm", inlines)
, ("itshape", emph <$> inlines)
, ("slshape", emph <$> inlines)
, ("scshape", smallcaps <$> inlines)
, ("bfseries", strong <$> inlines)
, ("/", pure mempty) -- italic correction
, ("aa", lit "å")
, ("AA", lit "Å")
, ("ss", lit "ß")
, ("o", lit "ø")
, ("O", lit "Ø")
, ("L", lit "Ł")
, ("l", lit "ł")
, ("ae", lit "æ")
, ("AE", lit "Æ")
, ("pounds", lit "£")
, ("euro", lit "€")
, ("copyright", lit "©")
, ("`", option (str "`") $ try $ tok >>= accent grave)
, ("'", option (str "'") $ try $ tok >>= accent acute)
, ("^", option (str "^") $ try $ tok >>= accent circ)
, ("~", option (str "~") $ try $ tok >>= accent tilde)
, ("\"", option (str "\"") $ try $ tok >>= accent umlaut)
, (".", option (str ".") $ try $ tok >>= accent dot)
, ("=", option (str "=") $ try $ tok >>= accent macron)
, ("c", option (str "c") $ try $ tok >>= accent cedilla)
, ("i", lit "i")
, ("\\", linebreak <$ (optional (bracketed inline) *> optional sp))
, (",", pure mempty)
, ("@", pure mempty)
, (" ", lit "\160")
, ("ps", pure $ str "PS." <> space)
, ("TeX", lit "TeX")
, ("LaTeX", lit "LaTeX")
, ("bar", lit "|")
, ("textless", lit "<")
, ("textgreater", lit ">")
, ("thanks", (note . mconcat) <$> (char '{' *> manyTill block (char '}')))
, ("footnote", (note . mconcat) <$> (char '{' *> manyTill block (char '}')))
, ("verb", doverb)
, ("lstinline", doverb)
, ("texttt", (code . stringify . toList) <$> tok)
, ("url", (unescapeURL <$> braced) >>= \url ->
pure (link url "" (codeWith ("",["url"],[]) url)))
, ("href", (unescapeURL <$> braced <* optional sp) >>= \url ->
tok >>= \lab ->
pure (link url "" lab))
, ("includegraphics", skipopts *> (unescapeURL <$> braced) >>=
(\src -> pure (image src "" (str "image"))))
, ("cite", citation "cite" NormalCitation False)
, ("citep", citation "citep" NormalCitation False)
, ("citep*", citation "citep*" NormalCitation False)
, ("citeal", citation "citeal" NormalCitation False)
, ("citealp", citation "citealp" NormalCitation False)
, ("citealp*", citation "citealp*" NormalCitation False)
, ("autocite", citation "autocite" NormalCitation False)
, ("footcite", citation "footcite" NormalCitation False)
, ("parencite", citation "parencite" NormalCitation False)
, ("supercite", citation "supercite" NormalCitation False)
, ("footcitetext", citation "footcitetext" NormalCitation False)
, ("citeyearpar", citation "citeyearpar" SuppressAuthor False)
, ("citeyear", citation "citeyear" SuppressAuthor False)
, ("autocite*", citation "autocite*" SuppressAuthor False)
, ("cite*", citation "cite*" SuppressAuthor False)
, ("parencite*", citation "parencite*" SuppressAuthor False)
, ("textcite", citation "textcite" AuthorInText False)
, ("citet", citation "citet" AuthorInText False)
, ("citet*", citation "citet*" AuthorInText False)
, ("citealt", citation "citealt" AuthorInText False)
, ("citealt*", citation "citealt*" AuthorInText False)
, ("textcites", citation "textcites" AuthorInText True)
, ("cites", citation "cites" NormalCitation True)
, ("autocites", citation "autocites" NormalCitation True)
, ("footcites", citation "footcites" NormalCitation True)
, ("parencites", citation "parencites" NormalCitation True)
, ("supercites", citation "supercites" NormalCitation True)
, ("footcitetexts", citation "footcitetexts" NormalCitation True)
, ("Autocite", citation "Autocite" NormalCitation False)
, ("Footcite", citation "Footcite" NormalCitation False)
, ("Parencite", citation "Parencite" NormalCitation False)
, ("Supercite", citation "Supercite" NormalCitation False)
, ("Footcitetext", citation "Footcitetext" NormalCitation False)
, ("Citeyearpar", citation "Citeyearpar" SuppressAuthor False)
, ("Citeyear", citation "Citeyear" SuppressAuthor False)
, ("Autocite*", citation "Autocite*" SuppressAuthor False)
, ("Cite*", citation "Cite*" SuppressAuthor False)
, ("Parencite*", citation "Parencite*" SuppressAuthor False)
, ("Textcite", citation "Textcite" AuthorInText False)
, ("Textcites", citation "Textcites" AuthorInText True)
, ("Cites", citation "Cites" NormalCitation True)
, ("Autocites", citation "Autocites" NormalCitation True)
, ("Footcites", citation "Footcites" NormalCitation True)
, ("Parencites", citation "Parencites" NormalCitation True)
, ("Supercites", citation "Supercites" NormalCitation True)
, ("Footcitetexts", citation "Footcitetexts" NormalCitation True)
, ("citetext", complexNatbibCitation NormalCitation)
, ("citeauthor", (try (tok *> optional sp *> controlSeq "citetext") *>
complexNatbibCitation AuthorInText)
<|> citation "citeauthor" AuthorInText False)
] ++ map ignoreInlines
-- these commands will be ignored unless --parse-raw is specified,
-- in which case they will appear as raw latex blocks:
[ "index", "nocite" ]
unescapeURL :: String -> String
unescapeURL ('\\':x:xs) | isEscapable x = x:unescapeURL xs
where isEscapable '%' = True
isEscapable '#' = True
isEscapable _ = False
unescapeURL (x:xs) = x:unescapeURL xs
unescapeURL [] = ""
doverb :: LP Inlines
doverb = do
marker <- anyChar
code <$> manyTill (satisfy (/='\n')) (char marker)
doLHSverb :: LP Inlines
doLHSverb = codeWith ("",["haskell"],[]) <$> manyTill (satisfy (/='\n')) (char '|')
lit :: String -> LP Inlines
lit = pure . str
accent :: (Char -> Char) -> Inlines -> LP Inlines
accent f ils =
case toList ils of
(Str (x:xs) : ys) -> return $ fromList $ (Str (f x : xs) : ys)
[] -> mzero
_ -> return ils
grave :: Char -> Char
grave 'A' = 'À'
grave 'E' = 'È'
grave 'I' = 'Ì'
grave 'O' = 'Ò'
grave 'U' = 'Ù'
grave 'a' = 'à'
grave 'e' = 'è'
grave 'i' = 'ì'
grave 'o' = 'ò'
grave 'u' = 'ù'
grave c = c
acute :: Char -> Char
acute 'A' = 'Á'
acute 'E' = 'É'
acute 'I' = 'Í'
acute 'O' = 'Ó'
acute 'U' = 'Ú'
acute 'Y' = 'Ý'
acute 'a' = 'á'
acute 'e' = 'é'
acute 'i' = 'í'
acute 'o' = 'ó'
acute 'u' = 'ú'
acute 'y' = 'ý'
acute 'C' = 'Ć'
acute 'c' = 'ć'
acute 'L' = 'Ĺ'
acute 'l' = 'ĺ'
acute 'N' = 'Ń'
acute 'n' = 'ń'
acute 'R' = 'Ŕ'
acute 'r' = 'ŕ'
acute 'S' = 'Ś'
acute 's' = 'ś'
acute 'Z' = 'Ź'
acute 'z' = 'ź'
acute c = c
circ :: Char -> Char
circ 'A' = 'Â'
circ 'E' = 'Ê'
circ 'I' = 'Î'
circ 'O' = 'Ô'
circ 'U' = 'Û'
circ 'a' = 'â'
circ 'e' = 'ê'
circ 'i' = 'î'
circ 'o' = 'ô'
circ 'u' = 'û'
circ 'C' = 'Ĉ'
circ 'c' = 'ĉ'
circ 'G' = 'Ĝ'
circ 'g' = 'ĝ'
circ 'H' = 'Ĥ'
circ 'h' = 'ĥ'
circ 'J' = 'Ĵ'
circ 'j' = 'ĵ'
circ 'S' = 'Ŝ'
circ 's' = 'ŝ'
circ 'W' = 'Ŵ'
circ 'w' = 'ŵ'
circ 'Y' = 'Ŷ'
circ 'y' = 'ŷ'
circ c = c
tilde :: Char -> Char
tilde 'A' = 'Ã'
tilde 'a' = 'ã'
tilde 'O' = 'Õ'
tilde 'o' = 'õ'
tilde 'I' = 'Ĩ'
tilde 'i' = 'ĩ'
tilde 'U' = 'Ũ'
tilde 'u' = 'ũ'
tilde 'N' = 'Ñ'
tilde 'n' = 'ñ'
tilde c = c
umlaut :: Char -> Char
umlaut 'A' = 'Ä'
umlaut 'E' = 'Ë'
umlaut 'I' = 'Ï'
umlaut 'O' = 'Ö'
umlaut 'U' = 'Ü'
umlaut 'a' = 'ä'
umlaut 'e' = 'ë'
umlaut 'i' = 'ï'
umlaut 'o' = 'ö'
umlaut 'u' = 'ü'
umlaut c = c
dot :: Char -> Char
dot 'C' = 'Ċ'
dot 'c' = 'ċ'
dot 'E' = 'Ė'
dot 'e' = 'ė'
dot 'G' = 'Ġ'
dot 'g' = 'ġ'
dot 'I' = 'İ'
dot 'Z' = 'Ż'
dot 'z' = 'ż'
dot c = c
macron :: Char -> Char
macron 'A' = 'Ā'
macron 'E' = 'Ē'
macron 'I' = 'Ī'
macron 'O' = 'Ō'
macron 'U' = 'Ū'
macron 'a' = 'ā'
macron 'e' = 'ē'
macron 'i' = 'ī'
macron 'o' = 'ō'
macron 'u' = 'ū'
macron c = c
cedilla :: Char -> Char
cedilla 'c' = 'ç'
cedilla 'C' = 'Ç'
cedilla 's' = 'ş'
cedilla 'S' = 'Ş'
cedilla c = c
tok :: LP Inlines
tok = try $ grouped inline <|> inlineCommand <|> str <$> (count 1 $ inlineChar)
opt :: LP Inlines
opt = bracketed inline <* optional sp
skipopts :: LP ()
skipopts = skipMany opt
inlineText :: LP Inlines
inlineText = str <$> many1 inlineChar
inlineChar :: LP Char
inlineChar = satisfy $ \c ->
not (c == '\\' || c == '$' || c == '%' || c == '^' || c == '_' ||
c == '&' || c == '~' || c == '#' || c == '{' || c == '}' ||
c == '^' || c == '\'' || c == '`' || c == '-' || c == ']' ||
c == ' ' || c == '\t' || c == '\n' )
environment :: LP Blocks
environment = do
controlSeq "begin"
name <- braced
case M.lookup name environments of
Just p -> p <|> rawEnv name
Nothing -> rawEnv name
rawEnv :: String -> LP Blocks
rawEnv name = do
let addBegin x = "\\begin{" ++ name ++ "}" ++ x
parseRaw <- stateParseRaw `fmap` getState
if parseRaw
then (rawBlock "latex" . addBegin) <$>
(withRaw (env name blocks) >>= applyMacros' . snd)
else env name blocks
-- | Replace "include" commands with file contents.
handleIncludes :: String -> IO String
handleIncludes [] = return []
handleIncludes ('\\':xs) =
case runParser include defaultParserState "input" ('\\':xs) of
Right (fs, rest) -> do let getfile f = catch (UTF8.readFile f)
(\_ -> return "")
yss <- mapM getfile fs
(intercalate "\n" yss ++) `fmap`
handleIncludes rest
_ -> case runParser (verbCmd <|> verbatimEnv) defaultParserState
"input" ('\\':xs) of
Right (r, rest) -> (r ++) `fmap` handleIncludes rest
_ -> ('\\':) `fmap` handleIncludes xs
handleIncludes (x:xs) = (x:) `fmap` handleIncludes xs
include :: LP ([FilePath], String)
include = do
name <- controlSeq "include" <|> controlSeq "usepackage"
skipopts
fs <- (splitBy (==',')) <$> braced
rest <- getInput
let fs' = if name == "include"
then map (flip replaceExtension ".tex") fs
else map (flip replaceExtension ".sty") fs
return (fs', rest)
verbCmd :: LP (String, String)
verbCmd = do
(_,r) <- withRaw $ do
controlSeq "verb"
c <- anyChar
manyTill anyChar (char c)
rest <- getInput
return (r, rest)
verbatimEnv :: LP (String, String)
verbatimEnv = do
(_,r) <- withRaw $ do
controlSeq "begin"
name <- braced
guard $ name == "verbatim" || name == "Verbatim" ||
name == "lstlisting" || name == "minted"
verbEnv name
rest <- getInput
return (r,rest)
rawLaTeXBlock :: GenParser Char ParserState String
rawLaTeXBlock = snd <$> withRaw (environment <|> blockCommand)
rawLaTeXInline :: GenParser Char ParserState Inline
rawLaTeXInline = do
(res, raw) <- withRaw inlineCommand
if res == mempty
then return (Str "")
else RawInline "latex" <$> (applyMacros' raw)
environments :: M.Map String (LP Blocks)
environments = M.fromList
[ ("document", env "document" blocks <* skipMany anyChar)
, ("letter", env "letter" letter_contents)
, ("center", env "center" blocks)
, ("tabular", env "tabular" simpTable)
, ("quote", blockQuote <$> env "quote" blocks)
, ("quotation", blockQuote <$> env "quotation" blocks)
, ("verse", blockQuote <$> env "verse" blocks)
, ("itemize", bulletList <$> listenv "itemize" (many item))
, ("description", definitionList <$> listenv "description" (many descItem))
, ("enumerate", ordered_list)
, ("code", failUnlessLHS *>
(codeBlockWith ("",["sourceCode","literate","haskell"],[]) <$>
verbEnv "code"))
, ("verbatim", codeBlock <$> (verbEnv "verbatim"))
, ("Verbatim", codeBlock <$> (verbEnv "Verbatim"))
, ("lstlisting", codeBlock <$> (verbEnv "lstlisting"))
, ("minted", liftA2 (\l c -> codeBlockWith ("",[l],[]) c)
(grouped (many1 $ satisfy (/= '}'))) (verbEnv "minted"))
, ("displaymath", mathEnv Nothing "displaymath")
, ("equation", mathEnv Nothing "equation")
, ("equation*", mathEnv Nothing "equation*")
, ("gather", mathEnv (Just "gathered") "gather")
, ("gather*", mathEnv (Just "gathered") "gather*")
, ("multline", mathEnv (Just "gathered") "multline")
, ("multline*", mathEnv (Just "gathered") "multline*")
, ("eqnarray", mathEnv (Just "aligned") "eqnarray")
, ("eqnarray*", mathEnv (Just "aligned") "eqnarray*")
, ("align", mathEnv (Just "aligned") "align")
, ("align*", mathEnv (Just "aligned") "align*")
, ("alignat", mathEnv (Just "aligned") "alignat")
, ("alignat*", mathEnv (Just "aligned") "alignat*")
]
letter_contents :: LP Blocks
letter_contents = do
bs <- blocks
st <- getState
-- add signature (author) and address (title)
let addr = case stateTitle st of
[] -> mempty
x -> para $ trimInlines $ fromList x
updateState $ \s -> s{ stateAuthors = [], stateTitle = [] }
return $ addr <> bs -- sig added by \closing
closing :: LP Blocks
closing = do
contents <- tok
st <- getState
let sigs = case stateAuthors st of
[] -> mempty
xs -> para $ trimInlines $ fromList
$ intercalate [LineBreak] xs
return $ para (trimInlines contents) <> sigs
item :: LP Blocks
item = blocks *> controlSeq "item" *> skipopts *> blocks
loose_item :: LP Blocks
loose_item = do
ctx <- stateParserContext `fmap` getState
if ctx == ListItemState
then mzero
else return mempty
descItem :: LP (Inlines, [Blocks])
descItem = do
blocks -- skip blocks before item
controlSeq "item"
optional sp
ils <- opt
bs <- blocks
return (ils, [bs])
env :: String -> LP a -> LP a
env name p = p <* (controlSeq "end" *> braced >>= guard . (== name))
listenv :: String -> LP a -> LP a
listenv name p = try $ do
oldCtx <- stateParserContext `fmap` getState
updateState $ \st -> st{ stateParserContext = ListItemState }
res <- env name p
updateState $ \st -> st{ stateParserContext = oldCtx }
return res
mathEnv :: Maybe String -> String -> LP Blocks
mathEnv innerEnv name = para <$> mathDisplay (inner <$> verbEnv name)
where inner x = case innerEnv of
Nothing -> x
Just y -> "\\begin{" ++ y ++ "}\n" ++ x ++
"\\end{" ++ y ++ "}"
verbEnv :: String -> LP String
verbEnv name = do
skipopts
optional blankline
let endEnv = try $ controlSeq "end" *> braced >>= guard . (== name)
res <- manyTill anyChar endEnv
return $ stripTrailingNewlines res
ordered_list :: LP Blocks
ordered_list = do
optional sp
(_, style, delim) <- option (1, DefaultStyle, DefaultDelim) $
try $ char '[' *> anyOrderedListMarker <* char ']'
spaces
optional $ try $ controlSeq "setlength" *> grouped (controlSeq "itemindent") *> braced
spaces
start <- option 1 $ try $ do controlSeq "setcounter"
grouped (string "enum" *> many1 (oneOf "iv"))
optional sp
num <- grouped (many1 digit)
spaces
return $ (read num + 1 :: Int)
bs <- listenv "enumerate" (many item)
return $ orderedListWith (start, style, delim) bs
paragraph :: LP Blocks
paragraph = do
x <- mconcat <$> many1 inline
if x == mempty
then return mempty
else return $ para $ trimInlines x
preamble :: LP Blocks
preamble = mempty <$> manyTill preambleBlock beginDoc
where beginDoc = lookAhead $ controlSeq "begin" *> string "{document}"
preambleBlock = (mempty <$ comment)
<|> (mempty <$ sp)
<|> (mempty <$ blanklines)
<|> (mempty <$ macro)
<|> blockCommand
<|> (mempty <$ anyControlSeq)
<|> (mempty <$ braced)
<|> (mempty <$ anyChar)
-------
-- citations
addPrefix :: [Inline] -> [Citation] -> [Citation]
addPrefix p (k:ks) = k {citationPrefix = p ++ citationPrefix k} : ks
addPrefix _ _ = []
addSuffix :: [Inline] -> [Citation] -> [Citation]
addSuffix s ks@(_:_) =
let k = last ks
s' = case s of
(Str (c:_):_)
| not (isPunctuation c || isSpace c) -> Str "," : Space : s
_ -> s
in init ks ++ [k {citationSuffix = citationSuffix k ++ s'}]
addSuffix _ _ = []
simpleCiteArgs :: LP [Citation]
simpleCiteArgs = try $ do
first <- optionMaybe $ toList <$> opt
second <- optionMaybe $ toList <$> opt
char '{'
keys <- manyTill citationLabel (char '}')
let (pre, suf) = case (first , second ) of
(Just s , Nothing) -> (mempty, s )
(Just s , Just t ) -> (s , t )
_ -> (mempty, mempty)
conv k = Citation { citationId = k
, citationPrefix = []
, citationSuffix = []
, citationMode = NormalCitation
, citationHash = 0
, citationNoteNum = 0
}
return $ addPrefix pre $ addSuffix suf $ map conv keys
citationLabel :: LP String
citationLabel = trim <$>
(many1 (satisfy $ \c -> c /=',' && c /='}') <* optional (char ',') <* optional sp)
cites :: CitationMode -> Bool -> LP [Citation]
cites mode multi = try $ do
cits <- if multi
then many1 simpleCiteArgs
else count 1 simpleCiteArgs
let (c:cs) = concat cits
return $ case mode of
AuthorInText -> c {citationMode = mode} : cs
_ -> map (\a -> a {citationMode = mode}) (c:cs)
citation :: String -> CitationMode -> Bool -> LP Inlines
citation name mode multi = do
(c,raw) <- withRaw $ cites mode multi
return $ cite c (rawInline "latex" $ "\\" ++ name ++ raw)
complexNatbibCitation :: CitationMode -> LP Inlines
complexNatbibCitation mode = try $ do
let ils = (toList . trimInlines . mconcat) <$>
many (notFollowedBy (oneOf "\\};") >> inline)
let parseOne = try $ do
skipSpaces
pref <- ils
cit' <- inline -- expect a citation
let citlist = toList cit'
cits' <- case citlist of
[Cite cs _] -> return cs
_ -> mzero
suff <- ils
skipSpaces
optional $ char ';'
return $ addPrefix pref $ addSuffix suff $ cits'
(c:cits, raw) <- withRaw $ grouped parseOne
return $ cite (c{ citationMode = mode }:cits)
(rawInline "latex" $ "\\citetext" ++ raw)
-- tables
parseAligns :: LP [Alignment]
parseAligns = try $ do
char '{'
optional $ char '|'
let cAlign = AlignCenter <$ char 'c'
let lAlign = AlignLeft <$ char 'l'
let rAlign = AlignRight <$ char 'r'
let alignChar = optional sp *> (cAlign <|> lAlign <|> rAlign)
aligns' <- sepEndBy alignChar (optional $ char '|')
spaces
char '}'
spaces
return aligns'
hline :: LP ()
hline = () <$ (try $ spaces >> controlSeq "hline")
lbreak :: LP ()
lbreak = () <$ (try $ spaces *> controlSeq "\\")
amp :: LP ()
amp = () <$ (try $ spaces *> char '&')
parseTableRow :: Int -- ^ number of columns
-> LP [Blocks]
parseTableRow cols = try $ do
let tableCellInline = notFollowedBy (amp <|> lbreak) >> inline
let tableCell = (plain . trimInlines . mconcat) <$> many tableCellInline
cells' <- sepBy tableCell amp
guard $ length cells' == cols
spaces
return cells'
simpTable :: LP Blocks
simpTable = try $ do
spaces
aligns <- parseAligns
let cols = length aligns
optional hline
header' <- option [] $ try (parseTableRow cols <* lbreak <* hline)
rows <- sepEndBy (parseTableRow cols) (lbreak <* optional hline)
spaces
let header'' = if null header'
then replicate cols mempty
else header'
lookAhead $ controlSeq "end" -- make sure we're at end
return $ table mempty (zip aligns (repeat 0)) header'' rows
|
castaway/pandoc
|
src/Text/Pandoc/Readers/LaTeX.hs
|
gpl-2.0
| 32,597 | 0 | 43 | 8,566 | 11,502 | 5,973 | 5,529 | 832 | 4 |
{- |
Module : ./Isabelle/Isa2DG.hs
Description : Import data generated by hol2hets into a DG
Copyright : (c) Jonathan von Schroeder, DFKI GmbH 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
-}
module Isabelle.Isa2DG where
import Static.GTheory
import Static.DevGraph
import Static.DgUtils
import Static.History
import Static.ComputeTheory
import Static.AnalysisStructured (insLink)
import Logic.Prover
import Logic.ExtSign
import Logic.Grothendieck
import Logic.Logic (ide)
import Common.LibName
import Common.Id
import Common.AS_Annotation
import Common.IRI (simpleIdToIRI)
import Isabelle.Logic_Isabelle
import Isabelle.IsaSign
import Isabelle.IsaImport (importIsaDataIO, IsaData)
import Driver.Options
import qualified Data.Map as Map
import Data.Graph.Inductive.Graph (Node)
import Data.List (intercalate)
import Data.Maybe (catMaybes)
import Control.Monad (unless, when)
import Control.Concurrent (forkIO, killThread)
import Common.Utils
import System.Exit
import System.Directory
import System.FilePath
_insNodeDG :: Sign -> [Named Sentence] -> String
-> DGraph -> (DGraph, Node)
_insNodeDG sig sens n dg =
let gt = G_theory Isabelle Nothing (makeExtSign Isabelle sig) startSigId
(toThSens sens) startThId
labelK = newInfoNodeLab
(makeName (simpleIdToIRI (mkSimpleId n)))
(newNodeInfo DGEmpty)
gt
k = getNewNodeDG dg
insN = [InsertNode (k, labelK)]
newDG = changesDGH dg insN
labCh = [SetNodeLab labelK (k, labelK
{ globalTheory = computeLabelTheory Map.empty newDG
(k, labelK) })]
newDG1 = changesDGH newDG labCh in (newDG1, k)
analyzeMessages :: Int -> [String] -> IO ()
analyzeMessages _ [] = return ()
analyzeMessages i (x : xs) = do
case x of
'v' : i' : ':' : msg -> when (read [i'] < i) $ putStr $ msg ++ "\n"
_ -> putStr $ x ++ "\n"
analyzeMessages i xs
anaThyFile :: HetcatsOpts -> FilePath -> IO (Maybe (LibName, LibEnv))
anaThyFile opts path = do
fp <- canonicalizePath path
tempFile <- getTempFile "" (takeBaseName fp)
fifo <- getTempFifo (takeBaseName fp)
exportScript' <- fmap (</> "export.sh") $ getEnvDef
"HETS_ISA_TOOLS" "./Isabelle/export"
exportScript <- canonicalizePath exportScript'
e1 <- doesFileExist exportScript
unless e1 $ fail
"Export script not available! Maybe you need to specify HETS_ISA_TOOLS"
(l, close) <- readFifo fifo
tid <- forkIO $ analyzeMessages (verbose opts) (lines . concat $ l)
(ex, sout, err) <- executeProcess exportScript [fp, tempFile, fifo] ""
close
killThread tid
removeFile fifo
case ex of
ExitFailure _ -> do
removeFile tempFile
soutF <- getTempFile sout (takeBaseName fp ++ ".sout")
errF <- getTempFile err (takeBaseName fp ++ ".serr")
fail $ "Export Failed! - Export script died prematurely. See " ++ soutF
++ " and " ++ errF ++ " for details."
ExitSuccess -> do
ret <- anaIsaFile opts tempFile
removeFile tempFile
return ret
mkNode :: (DGraph, Map.Map String (Node, Sign)) -> IsaData ->
(DGraph, Map.Map String (Node, Sign))
mkNode (dg, m) (name, header', imps, keywords', uses', body) =
let sens = map (\ sen ->
let name' = case sen of
Locale n' _ _ _ -> "locale " ++ qname n'
Class n' _ _ _ -> "class " ++ qname n'
Datatypes dts -> "datatype " ++ intercalate "_"
(map (qname . datatypeName) dts)
Consts cs -> "consts " ++ intercalate "_"
(map (\ (n', _, _) -> n') cs)
TypeSynonym n' _ _ _ -> "type_synonym " ++ qname n'
Axioms axs -> "axioms " ++ intercalate "_"
(map (qname . axiomName) axs)
Lemma _ _ _ l -> "lemma " ++ (intercalate "_" . map qname
. catMaybes $ map propsName l)
Definition n' _ _ _ _ _ -> "definition " ++ show n'
Fun _ _ _ _ _ fsigs -> "fun " ++ intercalate "_"
(map (\ (n', _, _, _) -> n') fsigs)
_ -> ""
in makeNamed name' sen) body
sgns = Map.foldWithKey (\ k a l ->
if elem k imps then snd a : l else l) [] m
sgn = foldl union_sig (emptySign { imports = imps,
header = header',
keywords = keywords',
uses = uses' }) sgns
(dg', n) = _insNodeDG sgn sens name dg
m' = Map.insert name (n, sgn) m
dgRet = foldr (\ imp dg'' ->
case Map.lookup imp m of
Just (n', s') ->
let gsig = G_sign Isabelle (makeExtSign Isabelle s')
startSigId
incl = gEmbed2 gsig $ mkG_morphism Isabelle
(ide sgn)
in insLink dg'' incl globalDef DGLinkImports n' n
Nothing -> dg'') dg' imps
in (dgRet, m')
anaIsaFile :: HetcatsOpts -> FilePath -> IO (Maybe (LibName, LibEnv))
anaIsaFile _ path = do
theories <- importIsaDataIO path
let name = "Imported Theory"
(dg, _) = foldl mkNode (emptyDG, Map.empty) theories
le = Map.insert (emptyLibName name) dg Map.empty
return $ Just (emptyLibName name,
computeLibEnvTheories le)
|
gnn/Hets
|
Isabelle/Isa2DG.hs
|
gpl-2.0
| 5,581 | 0 | 25 | 1,739 | 1,720 | 885 | 835 | 127 | 12 |
{-# LANGUAGE OverloadedStrings #-}
module QueryHelpers where
import qualified Data.ByteString.Char8 as B
import Network.HTTP.Types.URI
extractQueryParam :: B.ByteString -> B.ByteString -> Maybe B.ByteString
extractQueryParam qs paramName = lookup paramName (parseSimpleQuery qs)
extractQS :: B.ByteString -> B.ByteString
extractQS url = (B.split '?' url) !! 1
apiKeyFromUrl :: B.ByteString -> Maybe B.ByteString
apiKeyFromUrl url = extractQueryParam (extractQS url) "key"
searchQueryFromUrl :: B.ByteString -> Maybe B.ByteString
searchQueryFromUrl url = extractQueryParam (extractQS url) "q"
sortOrderFromUrl :: B.ByteString -> Maybe B.ByteString
sortOrderFromUrl url = extractQueryParam (extractQS url) "sort"
pageNumberFromUrl :: B.ByteString -> Maybe B.ByteString
pageNumberFromUrl url = extractQueryParam (extractQS url) "page"
recipeIdFromUrl :: B.ByteString -> Maybe B.ByteString
recipeIdFromUrl url = extractQueryParam (extractQS url) "rId"
|
moosingin3space/dailymenu
|
tests/QueryHelpers.hs
|
gpl-3.0
| 959 | 0 | 8 | 119 | 274 | 140 | 134 | 18 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE StandaloneDeriving #-}
-- | Examples on the effects of newtype deriving.
--
module Deriving.Anyclass where
newtype Foo a = MkFoo a deriving Show
class Show a => Bar a where
bar :: a -> String
bar = show
deriving instance Bar a => Bar (Foo a)
instance Bar Int
-- Now try with:
--
-- >>> bar (MkFoo (22 :: Int))
-- "MkFoo 22"
--
-- https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#extension-DeriveAnyClass
--
-- Quote:
-- With DeriveAnyClass you can derive any other class. The compiler will simply
-- generate an instance declaration with no explicitly-defined methods. This is
-- mostly useful in classes whose minimal set is empty,
|
capitanbatata/sandbox
|
haskell-extensions/src/Deriving/Anyclass.hs
|
gpl-3.0
| 734 | 0 | 7 | 133 | 91 | 55 | 36 | 9 | 0 |
{-# LANGUAGE
OverloadedStrings
, FlexibleContexts
#-}
module Cabal.Preferred where
import Cabal.Types
import Imports
import Data.Attoparsec.Text.Lazy as A
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import qualified Data.Text.Lazy.Encoding as LT
import Network.HTTP.Client
import Data.Foldable
import Data.HashMap.Lazy as HM hiding (empty)
import Control.Applicative
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Reader
import Control.Concurrent
satisfies :: [Int] -> Preferred -> Bool
satisfies = any . satisfiesConstraint
where
satisfiesConstraint :: [Int] -> Constraint -> Bool
satisfiesConstraint ns c =
case c of
EqualTo es -> satisfiesEqual ns es
Between g ls us -> satisfiesBetween ns (g,ls) us
Above g ls | g == GreaterThan -> satisfiesGreaterThan ns ls
| otherwise -> satisfiesGreaterThanEq ns ls
Below us -> satisfiesBelow ns us
satisfiesEqual :: [Int] -> EqVersion -> Bool
satisfiesEqual [] Nil = True
satisfiesEqual (n:ns) (Cons x xs)
| n == x = satisfiesEqual ns xs
| otherwise = False
satisfiesEqual _ Wildcard = True
satisfiesEqual _ _ = False
satisfiesBelow :: [Int] -> [Int] -> Bool
satisfiesBelow [] [] = False -- they were the same
satisfiesBelow (n:ns) (x:xs)
| n < x = True
| n == x = satisfiesBelow ns xs
| otherwise = False
satisfiesBelow (_:_) [] = False -- more specific, and thus greater
satisfiesBelow [] (_:_) = True
satisfiesGreaterThan :: [Int] -> [Int] -> Bool
satisfiesGreaterThan [] [] = False -- they were the same
satisfiesGreaterThan (n:ns) (x:xs)
| n > x = True
| n == x = satisfiesGreaterThan ns xs
| otherwise = False
satisfiesGreaterThan (_:_) [] = True
satisfiesGreaterThan [] (_:_) = False
satisfiesGreaterThanEq :: [Int] -> [Int] -> Bool
satisfiesGreaterThanEq [] [] = True
satisfiesGreaterThanEq (n:ns) (x:xs)
| n > x = True
| n == x = satisfiesGreaterThanEq ns xs
| otherwise = False
satisfiesGreaterThanEq (_:_) [] = True
satisfiesGreaterThanEq [] (_:_) = False
satisfiesBetween :: [Int] -> (Greater, [Int]) -> [Int] -> Bool
satisfiesBetween ns (g,ls) us =
satisfiesBelow ns us && (case g of
GreaterThan -> satisfiesGreaterThan ns ls
GreaterThanEq -> satisfiesGreaterThanEq ns ls)
parsePreferred :: Parser Preferred
parsePreferred =
(A.skipSpace >> parseConstraint) `A.sepBy1` (A.skipSpace >> parseOr)
where
parseConstraint :: Parser Constraint
parseConstraint =
EqualTo <$> parseEqualV
<|> Below <$> parseLessV
<|> (\(g,l,u) -> Between g l u) <$> parseBetween
<|> Above <$> parseGreater <*> parseExactV
parseEqualV :: Parser EqVersion
parseEqualV = do
parseEq
xs <- (digOrWild `A.sepBy1` A.char '.') <?> "Wildcard Version"
let go :: Either Int Char -> EqVersion -> Parser EqVersion
go (Right _) Nil = pure Wildcard
go (Right _) _ = empty
go (Left d) xs' = pure $ Cons d xs'
foldrM go Nil xs
where
parseEq :: Parser T.Text
parseEq = A.string "==" <?> "Equal"
digOrWild :: Parser (Either Int Char)
digOrWild = (Left . read) <$> A.many1 A.digit
<|> Right <$> A.char '*'
parseBetween :: Parser (Greater, [Int], [Int])
parseBetween = do
A.skipSpace
g <- parseGreater
l <- parseExactV
A.skipSpace
parseAnd
A.skipSpace
u <- parseLessV
pure (g,l,u)
parseGreater :: Parser Greater
parseGreater = GreaterThanEq <$ parseGq
<|> GreaterThan <$ parseGt
where
parseGt :: Parser T.Text
parseGt = A.string ">" <?> "GT"
parseGq :: Parser T.Text
parseGq = A.string ">=" <?> "GEQ"
parseExactV :: Parser [Int]
parseExactV = do
xs <- (A.many1 A.digit `A.sepBy1` char '.') <?> "Exact Version"
pure (read <$> xs)
parseLessV :: Parser [Int]
parseLessV = do
parseLt
parseExactV
where
parseLt :: Parser T.Text
parseLt = A.string "<" <?> "LT"
parseAnd :: Parser T.Text
parseAnd = A.string "&&" <?> "And"
parseOr :: Parser T.Text
parseOr = A.string "||" <?> "Or"
fetchPreferred :: Env -> IO (HashMap PackageName Preferred)
fetchPreferred env =
go `catch` (\e -> do print (e :: SomeException)
threadDelay 5000000
fetchPreferred env
)
where
go = do
let manager = envManager env
request <- parseUrl "https://hackage.haskell.org/packages/preferred-versions"
response <- httpLbs request manager
let xs = dropWhile ("--" `LT.isPrefixOf`)
. LT.lines . LT.decodeUtf8 . responseBody $ response
startingPref c = c == '<' || c == '>' || c == '='
parsePref p = case A.parse parsePreferred p of
Done _ r -> pure r
e -> throwM . ParseError . show $ e
nameAndPrefs :: LT.Text -> IO (PackageName, Preferred)
nameAndPrefs l = do
let (n,p) = LT.span (not . startingPref) l
p' <- parsePref $ LT.strip p
pure ( PackageName . T.strip . LT.toStrict $ n
, p'
)
ys <- mapM nameAndPrefs xs
pure $ HM.fromList ys
|
athanclark/happ-store
|
src/Cabal/Preferred.hs
|
gpl-3.0
| 5,643 | 0 | 19 | 1,799 | 1,832 | 940 | 892 | 141 | 17 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}
module Lamdu.GUI.DefinitionEdit
( make
, diveToNameEdit
) where
import Prelude.Compat
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Control.Lens.Tuple
import Control.MonadA (MonadA)
import Data.Store.Transaction (Transaction)
import Data.Vector.Vector2 (Vector2(..))
import qualified Graphics.DrawingCombinators as Draw
import qualified Graphics.UI.Bottle.Animation as Anim
import qualified Graphics.UI.Bottle.EventMap as E
import Graphics.UI.Bottle.View (View(..))
import Graphics.UI.Bottle.Widget (Widget)
import qualified Graphics.UI.Bottle.Widget as Widget
import qualified Graphics.UI.Bottle.Widgets as BWidgets
import Graphics.UI.Bottle.WidgetsEnvT (WidgetEnvT)
import Lamdu.Config (Config)
import qualified Lamdu.Config as Config
import qualified Lamdu.Data.Anchors as Anchors
import qualified Lamdu.Data.Definition as Definition
import Lamdu.Expr.Scheme (Scheme(..), schemeType)
import Lamdu.GUI.CodeEdit.Settings (Settings)
import qualified Lamdu.GUI.ExpressionEdit as ExpressionEdit
import qualified Lamdu.GUI.ExpressionEdit.BinderEdit as BinderEdit
import qualified Lamdu.GUI.ExpressionEdit.BuiltinEdit as BuiltinEdit
import Lamdu.GUI.ExpressionGui (ExpressionGui)
import qualified Lamdu.GUI.ExpressionGui as ExpressionGui
import Lamdu.GUI.ExpressionGui.Monad (ExprGuiM)
import qualified Lamdu.GUI.ExpressionGui.Monad as ExprGuiM
import qualified Lamdu.GUI.ExpressionGui.Types as ExprGuiT
import qualified Lamdu.GUI.WidgetIds as WidgetIds
import Lamdu.Sugar.Names.Types (Name(..), DefinitionN)
import Lamdu.Sugar.NearestHoles (NearestHoles)
import qualified Lamdu.Sugar.Types as Sugar
type T = Transaction
toExprGuiMPayload :: ([Sugar.EntityId], NearestHoles) -> ExprGuiT.Payload
toExprGuiMPayload (entityIds, nearestHoles) =
ExprGuiT.emptyPayload nearestHoles & ExprGuiT.plStoredEntityIds .~ entityIds
make ::
MonadA m => Anchors.CodeProps m -> Config -> Settings ->
DefinitionN m ([Sugar.EntityId], NearestHoles) ->
WidgetEnvT (T m) (Widget (T m))
make cp config settings defS =
case exprGuiDefS ^. Sugar.drBody of
Sugar.DefinitionBodyExpression bodyExpr ->
makeExprDefinition exprGuiDefS bodyExpr
Sugar.DefinitionBodyBuiltin builtin ->
makeBuiltinDefinition exprGuiDefS builtin
& ExprGuiM.run ExpressionEdit.make cp config settings
<&> (^. ExpressionGui.egWidget)
where
exprGuiDefS =
defS
<&> Lens.mapped %~ toExprGuiMPayload
<&> ExprGuiT.markRedundantTypes
topLevelSchemeTypeView :: MonadA m => Widget.R -> Sugar.EntityId -> Scheme -> ExprGuiM m (ExpressionGui m)
topLevelSchemeTypeView minWidth entityId scheme =
-- At the definition-level, Schemes can be shown as ordinary
-- types to avoid confusing forall's:
ExpressionGui.makeTypeView entityId (scheme ^. schemeType) minWidth
makeBuiltinDefinition ::
MonadA m =>
Sugar.Definition (Name m) m (ExprGuiT.SugarExpr m) ->
Sugar.DefinitionBuiltin m -> ExprGuiM m (ExpressionGui m)
makeBuiltinDefinition def builtin =
do
assignment <-
[ ExpressionGui.makeNameOriginEdit name (Widget.joinId myId ["name"])
, ExprGuiM.makeLabel "=" $ Widget.toAnimId myId
, BuiltinEdit.make builtin myId
]
& sequenceA
>>= ExprGuiM.widgetEnv . BWidgets.hboxCenteredSpaced
<&> ExpressionGui.fromValueWidget
typeView <-
topLevelSchemeTypeView 0 entityId (builtin ^. Sugar.biType)
[assignment, typeView]
& ExpressionGui.vboxTopFocalAlignedTo 0
& return
where
name = def ^. Sugar.drName
entityId = def ^. Sugar.drEntityId
myId = WidgetIds.fromEntityId entityId
typeIndicatorId :: Widget.Id -> Widget.Id
typeIndicatorId myId = Widget.joinId myId ["type indicator"]
typeIndicator ::
MonadA m => Widget.R -> Draw.Color -> Widget.Id -> ExprGuiM m (ExpressionGui m)
typeIndicator width color myId =
do
config <- ExprGuiM.readConfig
let typeIndicatorHeight =
realToFrac $ Config.typeIndicatorFrameWidth config ^. _2
Anim.unitSquare (Widget.toAnimId (typeIndicatorId myId))
& View 1
& Widget.fromView
& Widget.scale (Vector2 width typeIndicatorHeight)
& Widget.tint color
& ExpressionGui.fromValueWidget
& return
acceptableTypeIndicator ::
MonadA m =>
Widget.R -> T m a -> Draw.Color -> Widget.Id ->
ExprGuiM m (ExpressionGui m)
acceptableTypeIndicator width accept color myId =
do
config <- ExprGuiM.readConfig
let acceptKeyMap =
Widget.keysEventMapMovesCursor (Config.acceptDefinitionTypeKeys config)
(E.Doc ["Edit", "Accept inferred type"]) (accept >> return myId)
typeIndicator width color myId
>>= ExpressionGui.egWidget %%~
ExprGuiM.widgetEnv .
BWidgets.makeFocusableView (typeIndicatorId myId) .
Widget.weakerEvents acceptKeyMap
makeExprDefinition ::
MonadA m =>
Sugar.Definition (Name m) m (ExprGuiT.SugarExpr m) ->
Sugar.DefinitionExpression (Name m) m (ExprGuiT.SugarExpr m) ->
ExprGuiM m (ExpressionGui m)
makeExprDefinition def bodyExpr =
do
config <- ExprGuiM.readConfig
bodyWidget <-
BinderEdit.make (def ^. Sugar.drName)
(bodyExpr ^. Sugar.deContent) myId
let width = bodyWidget ^. ExpressionGui.egWidget . Widget.width
vspace <- ExpressionGui.verticalSpace
typeWidget <-
case bodyExpr ^. Sugar.deTypeInfo of
Sugar.DefinitionExportedTypeInfo scheme ->
typeIndicator width (Config.typeIndicatorMatchColor config) myId :
[ topLevelSchemeTypeView width entityId scheme
| Lens.hasn't (Sugar.deContent . Sugar.bParams . Sugar._DefintionWithoutParams) bodyExpr
] & sequence
Sugar.DefinitionNewType (Sugar.AcceptNewType oldScheme _ accept) ->
case oldScheme of
Definition.NoExportedType ->
[ acceptableTypeIndicator width accept (Config.typeIndicatorFirstTimeColor config) myId
]
Definition.ExportedType scheme ->
[ acceptableTypeIndicator width accept (Config.typeIndicatorErrorColor config) myId
, topLevelSchemeTypeView width entityId scheme
]
& sequence
<&> ExpressionGui.vboxTopFocalAlignedTo 0 . concatMap (\w -> [vspace, w])
ExpressionGui.vboxTopFocalAlignedTo 0 [bodyWidget, typeWidget]
& return
where
entityId = def ^. Sugar.drEntityId
myId = WidgetIds.fromEntityId entityId
diveToNameEdit :: Widget.Id -> Widget.Id
diveToNameEdit = BinderEdit.diveToNameEdit
|
rvion/lamdu
|
Lamdu/GUI/DefinitionEdit.hs
|
gpl-3.0
| 7,143 | 0 | 21 | 1,784 | 1,688 | 912 | 776 | -1 | -1 |
{-|
Stability : provisional
Portability : haskell98
Simplistic ANSI color support.
-}
module AnsiColor
( Color(..)
, bold
, inColor
) where
import Data.List
data Color = Black
| Red
| Green
| Yellow
| Blue
| Magenta
| Cyan
| White
| Default
deriving Enum
esc :: [String] -> String
esc [] = ""
esc xs = "\ESC[" ++ (concat . intersperse ";" $ xs) ++ "m"
col :: Color -> Bool -> Color -> [String]
col fg bf bg = show (fromEnum fg + 30) : bf' [show (fromEnum bg + 40)]
where bf' | bf = ("01" :)
| otherwise = id
inColor :: Color -> Bool -> Color -> String -> String
inColor c bf bg txt = esc (col c bf bg) ++ txt ++ esc ["00"]
bold :: String -> String
bold = ansi "1" "22"
-- italic = ansi "3" "23"
-- underline = ansi "4" "24"
-- inverse = ansi "7" "27"
ansi :: String -> String -> String -> String
ansi on off txt = esc [on] ++ txt ++ esc [off]
|
Heather/hackport
|
AnsiColor.hs
|
gpl-3.0
| 1,018 | 0 | 11 | 356 | 338 | 182 | 156 | 28 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Estuary.Languages.CineCer0.VideoSpec where
import Language.Haskell.Exts
import Control.Applicative
import Data.Time
import Data.Text
import TextShow
import Data.Tempo
import Data.Text (Text)
import Estuary.Languages.CineCer0.Signal
data Colour = Colour (Signal Text) | ColourRGB (Signal Rational) (Signal Rational) (Signal Rational) | ColourHSL (Signal Rational) (Signal Rational) (Signal Rational) | ColourRGBA (Signal Rational) (Signal Rational) (Signal Rational) (Signal Rational) | ColourHSLA (Signal Rational) (Signal Rational) (Signal Rational) (Signal Rational)
-- instance Eq Colour where
-- (==) (Colour a) (Colour b) = True
-- (==) (ColourRGB a b c) (ColourRGB a' b' c') = True
-- (==) _ _ = False
data Source = VideoSource Text | ImageSource Text | TextSource Text deriving (Show, Eq)
data LayerSpec = LayerSpec {
source :: Source,
z :: Signal Int,
anchorTime :: (Tempo -> UTCTime -> UTCTime), -- vid reproduction
playbackPosition :: Signal (Maybe NominalDiffTime),
playbackRate :: Signal (Maybe Rational),
mute :: Signal Bool,
volume :: Signal Rational,
fontFamily :: Signal Text,
fontSize :: Signal Rational,
colour :: Colour,
strike :: Signal Bool,
bold :: Signal Bool,
italic :: Signal Bool,
border :: Signal Bool,
posX :: Signal Rational, -- geom
posY :: Signal Rational,
width :: Signal Rational,
height :: Signal Rational,
rotate :: Signal Rational,
opacity :: Signal (Maybe Rational), -- video style
blur :: Signal (Maybe Rational),
brightness :: Signal (Maybe Rational),
contrast :: Signal (Maybe Rational),
grayscale :: Signal (Maybe Rational),
saturate :: Signal (Maybe Rational),
mask :: Signal Text
}
instance Show LayerSpec where
show s = show $ source s
emptyLayerSpec :: LayerSpec
emptyLayerSpec = LayerSpec {
source = VideoSource "",
z = constantSignal 0,
anchorTime = defaultAnchor,
playbackPosition = playNatural_Pos 0.0,
playbackRate = playNatural_Rate 0.0,
mute = constantSignal True,
volume = constantSignal 0.0,
fontFamily = constantSignal "sans-serif",
fontSize = constantSignal 1,
colour = Colour (constantSignal "White"),
strike = constantSignal False,
bold = constantSignal False,
italic = constantSignal False,
border = constantSignal False,
posX = constantSignal 0.0,
posY = constantSignal 0.0,
width = constantSignal 1.0,
height = constantSignal 1.0,
rotate = constantSignal 0,
opacity = constantSignal' Nothing,
blur = constantSignal Nothing,
brightness = constantSignal Nothing,
contrast = constantSignal Nothing,
grayscale = constantSignal Nothing,
saturate = constantSignal Nothing,
mask = emptyText
}
videoToLayerSpec :: Text -> LayerSpec
videoToLayerSpec x = emptyLayerSpec { source = VideoSource x}
imageToLayerSpec :: Text -> LayerSpec
imageToLayerSpec x = emptyLayerSpec { source = ImageSource x}
textToLayerSpec :: Text -> LayerSpec
textToLayerSpec x = emptyLayerSpec { source = TextSource x}
-- it should be just five arguments _ _ _ _ _
emptyText :: Signal Text
emptyText _ _ _ _ _ = Data.Text.empty
--
-- Geometric Functions --
setPosX :: Signal Rational -> LayerSpec -> LayerSpec
setPosX s v = v { posX = s }
shiftPosX :: Signal Rational -> LayerSpec -> LayerSpec
shiftPosX s v = v {
posX = s * posX v
}
setPosY :: Signal Rational -> LayerSpec -> LayerSpec
setPosY s v = v { posY = s }
shiftPosY :: Signal Rational -> LayerSpec -> LayerSpec
shiftPosY s v = v {
posY = s * posY v
}
setCoord :: Signal Rational -> Signal Rational -> LayerSpec -> LayerSpec
setCoord s1 s2 vs = vs { posX = s1, posY = s2}
shiftCoord :: Signal Rational -> Signal Rational -> LayerSpec -> LayerSpec
shiftCoord s1 s2 vs = vs {
posX = s1 * posX vs,
posY = s2 * posY vs
}
setWidth :: Signal Rational -> LayerSpec -> LayerSpec
setWidth s v = v { width = s }
shiftWidth :: Signal Rational -> LayerSpec -> LayerSpec
shiftWidth s v = v {
width = s * width v
}
setHeight :: Signal Rational -> LayerSpec -> LayerSpec
setHeight s v = v { height = s }
shiftHeight :: Signal Rational -> LayerSpec -> LayerSpec
shiftHeight s v = v {
height = s * height v
}
setSize :: Signal Rational -> LayerSpec -> LayerSpec
setSize s vs = vs { width = s, height = s}
shiftSize :: Signal Rational -> LayerSpec -> LayerSpec
shiftSize s vs = vs {
width = s * width vs,
height = s * height vs
}
setRotate :: Signal Rational -> LayerSpec -> LayerSpec
setRotate s v = v { rotate = s }
shiftRotate :: Signal Rational -> LayerSpec -> LayerSpec
shiftRotate s v = v {
rotate = s * rotate v
}
setZIndex :: Signal Int -> LayerSpec -> LayerSpec
setZIndex n tx = tx { z = n }
--
-- Text-only Functions --
setFontFamily :: Signal Text -> LayerSpec -> LayerSpec
setFontFamily s tx = tx { fontFamily = s }
setFontSize :: Signal Rational -> LayerSpec -> LayerSpec
setFontSize s tx = tx { fontSize = s }
setStrike :: LayerSpec -> LayerSpec
setStrike tx = tx { strike = constantSignal True }
setBold :: LayerSpec -> LayerSpec
setBold tx = tx { bold = constantSignal True}
setItalic :: LayerSpec -> LayerSpec
setItalic tx = tx { italic = constantSignal True}
setBorder :: LayerSpec -> LayerSpec
setBorder tx = tx { border = constantSignal True}
setColourStr :: Signal Text -> LayerSpec -> LayerSpec
setColourStr clr tx = tx { colour = Colour clr }
setRGB :: Signal Rational -> Signal Rational -> Signal Rational -> LayerSpec -> LayerSpec
setRGB r g b tx = tx { colour = ColourRGB r g b}
setHSL :: Signal Rational -> Signal Rational -> Signal Rational -> LayerSpec -> LayerSpec
setHSL h s v tx = tx { colour = ColourHSL h s v}
setRGBA :: Signal Rational -> Signal Rational -> Signal Rational -> Signal Rational -> LayerSpec -> LayerSpec
setRGBA r g b a tx = tx { colour = ColourRGBA r g b a}
setHSLA :: Signal Rational -> Signal Rational -> Signal Rational -> Signal Rational -> LayerSpec -> LayerSpec
setHSLA h s l a tx = tx { colour = ColourHSLA h s l a}
--
-- Video-styling Functions --
setOpacity :: Signal (Maybe Rational) -> LayerSpec -> LayerSpec
setOpacity s v = v { opacity = s }
shiftOpacity :: Signal (Maybe Rational) -> LayerSpec -> LayerSpec
shiftOpacity s v = v {
opacity = multipleMaybeSignal s (opacity v)
}
setBlur :: Signal (Maybe Rational) -> LayerSpec -> LayerSpec
setBlur s v = v { blur = s }
shiftBlur :: Signal (Maybe Rational) -> LayerSpec -> LayerSpec
shiftBlur s v = v {
blur = multipleMaybeSignal s (blur v)
}
setBrightness :: Signal (Maybe Rational) -> LayerSpec -> LayerSpec
setBrightness s v = v { brightness = s }
shiftBrightness :: Signal (Maybe Rational) -> LayerSpec -> LayerSpec
shiftBrightness s v = v {
brightness = multipleMaybeSignal s (brightness v)
}
setContrast :: Signal (Maybe Rational) -> LayerSpec -> LayerSpec
setContrast s v = v { contrast = s }
shiftContrast :: Signal (Maybe Rational) -> LayerSpec -> LayerSpec
shiftContrast s v = v {
contrast = multipleMaybeSignal s (contrast v)
}
setGrayscale :: Signal (Maybe Rational) -> LayerSpec -> LayerSpec
setGrayscale s v = v { grayscale = s }
shiftGrayscale :: Signal (Maybe Rational) -> LayerSpec -> LayerSpec
shiftGrayscale s v = v {
grayscale = multipleMaybeSignal s (grayscale v)
}
setSaturate :: Signal (Maybe Rational) -> LayerSpec -> LayerSpec
setSaturate s v = v { saturate = s }
shiftSaturate :: Signal (Maybe Rational) -> LayerSpec -> LayerSpec
shiftSaturate s v = v {
saturate = multipleMaybeSignal s (saturate v)
}
--
-- Masks for Video Functions --
circleMask :: Signal Rational -> LayerSpec -> LayerSpec
circleMask s vs = vs {
mask = \a b c d e -> "clip-path:circle(" <> (showt (realToFrac ((
(((s a b c d e)*71)-71)*(-1)
) :: Rational) :: Double)) <> "% at 50% 50%);"
}
circleMask' :: Signal Rational -> Signal Rational -> Signal Rational -> LayerSpec -> LayerSpec
circleMask' m n s vs = vs {
mask = \a b c d e -> "clip-path:circle(" <> (showt (realToFrac ((
(((m a b c d e)*71)-71)*(-1)
) :: Rational) :: Double)) <> "% at " <> (showt (realToFrac (((n a b c d e)*100) :: Rational) :: Double)) <> "% " <> (showt (realToFrac (((s a b c d e)*100) :: Rational) :: Double)) <> "%);"
}
sqrMask :: Signal Rational -> LayerSpec -> LayerSpec
sqrMask s vs = vs {
mask = \a b c d e -> "clip-path: inset(" <> (showt (realToFrac (((s a b c d e)*50) :: Rational) :: Double)) <> "%);"
}
rectMask :: Signal Rational -> Signal Rational -> Signal Rational -> Signal Rational -> LayerSpec -> LayerSpec
rectMask m n s t vs = vs {
mask = \ a b c d e -> "clip-path: inset(" <> (showt (realToFrac (((m a b c d e)*100) :: Rational) :: Double)) <> "% " <> (showt (realToFrac (((n a b c d e)*100) :: Rational) :: Double)) <> "% " <> (showt (realToFrac (((s a b c d e)*100) :: Rational) :: Double)) <> "% " <> (showt (realToFrac (((t a b c d e)*100) :: Rational) :: Double)) <> "%);"
}
--
-- Audio --
setMute :: LayerSpec -> LayerSpec
setMute v = v { mute = constantSignal True }
setUnmute :: LayerSpec -> LayerSpec
setUnmute v = v { mute = constantSignal False}
setVolume:: Signal Rational -> LayerSpec -> LayerSpec
setVolume vol v = v { volume = vol }
--
-- Time Functions --
-- anchorTime:: -- parser
quant:: Rational -> Rational -> LayerSpec -> LayerSpec
quant nc offset vs = vs { anchorTime = quantAnchor nc offset }
freerun :: LayerSpec -> LayerSpec
freerun vs = vs {
playbackPosition = freeRun
}
playNatural :: Rational -> LayerSpec -> LayerSpec
playNatural n vs = vs {
playbackPosition = playNatural_Pos n,
playbackRate = playNatural_Rate n
}
playSnap :: Rational -> LayerSpec -> LayerSpec
playSnap n vs = vs {
playbackPosition = playRound_Pos n,
playbackRate = playRound_Rate n
}
playSnapMetre :: Rational -> LayerSpec -> LayerSpec
playSnapMetre n vs = vs {
playbackPosition = playRoundMetre_Pos n,
playbackRate = playRoundMetre_Rate n
}
playEvery :: Rational -> Rational -> LayerSpec -> LayerSpec
playEvery m n vs = vs {
playbackPosition = playEvery_Pos m n,
playbackRate = playEvery_Rate m n
}
playChop :: Signal Rational -> Signal Rational -> Signal Rational -> LayerSpec -> LayerSpec
playChop l m n vs = vs {
playbackPosition = playChop_Pos l m n,
playbackRate = playChop_Rate l m n
}
playChop' :: Signal Rational -> Signal Rational -> LayerSpec -> LayerSpec
playChop' m n vs = vs {
playbackPosition = playChop_Pos' m n,
playbackRate = playChop_Rate' m n
}
playRate :: Rational -> LayerSpec -> LayerSpec
playRate n vs = vs {
playbackPosition = rate_Pos n,
playbackRate = rate_Rate n
}
|
d0kt0r0/estuary
|
client/src/Estuary/Languages/CineCer0/VideoSpec.hs
|
gpl-3.0
| 10,524 | 0 | 26 | 2,094 | 3,788 | 2,015 | 1,773 | 223 | 1 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Shared where
import Reflex.Dom.WebSocket.Message
import GHC.Generics
import Data.Aeson
import Data.Text
type Request = Request1 :<|> Request2 :<|> Request3 :<|> Request4
data Request1 = Request1 Text
deriving (Generic, Show)
data Request2 = Request2 (Text, Text)
deriving (Generic, Show)
data Request3 = Request3 [Text]
deriving (Generic, Show)
data Request4 = Request4 Text
deriving (Generic, Show)
data Response1 = Response1 Int
deriving (Generic, Show)
data Response2 = Response2 Text
deriving (Generic, Show)
data Response3 = Response3 (Text, Int)
deriving (Generic, Show)
instance WebSocketMessage Request Request1 where
type ResponseT Request Request1 = Response1
instance WebSocketMessage Request Request2 where
type ResponseT Request Request2 = Response2
instance WebSocketMessage Request Request3 where
type ResponseT Request Request3 = Response3
instance WebSocketMessage Request Request4 where
type ResponseT Request Request4 = Response1
instance ToJSON (Request1) where
toEncoding = genericToEncoding defaultOptions
instance FromJSON (Request1)
instance ToJSON (Request2) where
toEncoding = genericToEncoding defaultOptions
instance FromJSON (Request2)
instance ToJSON (Request3) where
toEncoding = genericToEncoding defaultOptions
instance FromJSON (Request3)
instance ToJSON (Request4) where
toEncoding = genericToEncoding defaultOptions
instance FromJSON (Request4)
instance ToJSON (Response1) where
toEncoding = genericToEncoding defaultOptions
instance FromJSON (Response1)
instance ToJSON (Response2) where
toEncoding = genericToEncoding defaultOptions
instance FromJSON (Response2)
instance ToJSON (Response3) where
toEncoding = genericToEncoding defaultOptions
instance FromJSON (Response3)
|
dfordivam/reflex-websocket-interface
|
example/shared/Shared.hs
|
gpl-3.0
| 1,986 | 0 | 7 | 288 | 492 | 269 | 223 | 55 | 0 |
-----------------------------------------------------------------------------
--
-- Module : Data.DICOM.VL
-- Copyright : Copyright (c) DICOM Grid 2015
-- License : GPL-3
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability :
--
-----------------------------------------------------------------------------
{-# LANGUAGE PatternSynonyms #-}
module Data.DICOM.VL
( VL()
, runVL
, pattern UndefinedValueLength
, vl
) where
import Data.Int (Int64)
newtype VL = VL { runVL :: Int64 } deriving (Show, Eq, Ord)
-- Pattern synonyms for matching DICOM magic constants
pattern UndefinedValueLength = VL 0xFFFFFFFF
-- Smart constructors
vl :: Int64 -> VL
vl = VL
|
dicomgrid/dicom-haskell-library
|
src/Data/DICOM/VL.hs
|
gpl-3.0
| 726 | 0 | 6 | 137 | 103 | 67 | 36 | 14 | 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.SecurityCenter.Organizations.Operations.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets the latest state of a long-running operation. Clients can use this
-- method to poll the operation result at intervals as recommended by the
-- API service.
--
-- /See:/ <https://console.cloud.google.com/apis/api/securitycenter.googleapis.com/overview Security Command Center API Reference> for @securitycenter.organizations.operations.get@.
module Network.Google.Resource.SecurityCenter.Organizations.Operations.Get
(
-- * REST Resource
OrganizationsOperationsGetResource
-- * Creating a Request
, organizationsOperationsGet
, OrganizationsOperationsGet
-- * Request Lenses
, oogXgafv
, oogUploadProtocol
, oogAccessToken
, oogUploadType
, oogName
, oogCallback
) where
import Network.Google.Prelude
import Network.Google.SecurityCenter.Types
-- | A resource alias for @securitycenter.organizations.operations.get@ method which the
-- 'OrganizationsOperationsGet' request conforms to.
type OrganizationsOperationsGetResource =
"v1p1beta1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Operation
-- | Gets the latest state of a long-running operation. Clients can use this
-- method to poll the operation result at intervals as recommended by the
-- API service.
--
-- /See:/ 'organizationsOperationsGet' smart constructor.
data OrganizationsOperationsGet =
OrganizationsOperationsGet'
{ _oogXgafv :: !(Maybe Xgafv)
, _oogUploadProtocol :: !(Maybe Text)
, _oogAccessToken :: !(Maybe Text)
, _oogUploadType :: !(Maybe Text)
, _oogName :: !Text
, _oogCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OrganizationsOperationsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'oogXgafv'
--
-- * 'oogUploadProtocol'
--
-- * 'oogAccessToken'
--
-- * 'oogUploadType'
--
-- * 'oogName'
--
-- * 'oogCallback'
organizationsOperationsGet
:: Text -- ^ 'oogName'
-> OrganizationsOperationsGet
organizationsOperationsGet pOogName_ =
OrganizationsOperationsGet'
{ _oogXgafv = Nothing
, _oogUploadProtocol = Nothing
, _oogAccessToken = Nothing
, _oogUploadType = Nothing
, _oogName = pOogName_
, _oogCallback = Nothing
}
-- | V1 error format.
oogXgafv :: Lens' OrganizationsOperationsGet (Maybe Xgafv)
oogXgafv = lens _oogXgafv (\ s a -> s{_oogXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
oogUploadProtocol :: Lens' OrganizationsOperationsGet (Maybe Text)
oogUploadProtocol
= lens _oogUploadProtocol
(\ s a -> s{_oogUploadProtocol = a})
-- | OAuth access token.
oogAccessToken :: Lens' OrganizationsOperationsGet (Maybe Text)
oogAccessToken
= lens _oogAccessToken
(\ s a -> s{_oogAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
oogUploadType :: Lens' OrganizationsOperationsGet (Maybe Text)
oogUploadType
= lens _oogUploadType
(\ s a -> s{_oogUploadType = a})
-- | The name of the operation resource.
oogName :: Lens' OrganizationsOperationsGet Text
oogName = lens _oogName (\ s a -> s{_oogName = a})
-- | JSONP
oogCallback :: Lens' OrganizationsOperationsGet (Maybe Text)
oogCallback
= lens _oogCallback (\ s a -> s{_oogCallback = a})
instance GoogleRequest OrganizationsOperationsGet
where
type Rs OrganizationsOperationsGet = Operation
type Scopes OrganizationsOperationsGet =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient OrganizationsOperationsGet'{..}
= go _oogName _oogXgafv _oogUploadProtocol
_oogAccessToken
_oogUploadType
_oogCallback
(Just AltJSON)
securityCenterService
where go
= buildClient
(Proxy :: Proxy OrganizationsOperationsGetResource)
mempty
|
brendanhay/gogol
|
gogol-securitycenter/gen/Network/Google/Resource/SecurityCenter/Organizations/Operations/Get.hs
|
mpl-2.0
| 5,017 | 0 | 15 | 1,078 | 699 | 410 | 289 | 100 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.