code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Text.Parsec
import Control.Monad (when)
import Data.Maybe (fromJust, listToMaybe, catMaybes)
import System.Environment (getArgs)
import System.Console.Docopt
import System.IO (stderr, hPutStrLn)
import System.IO.Unsafe (unsafePerformIO)
{-import Data.Maybe (isJust, fromJust)-}
{-import Debug.Trace-}
patterns :: Docopt
patterns = [docoptFile|USAGE|]
main'' = putStrLn "Hello World!"
main' = do
(infile:outfile:_) <- getArgs
contents <- readFile infile
let res = parse cmParse "" contents
case res of
Left err -> putStrLn $ show err
Right res' -> writeFile outfile res'
main = do
args <- parseArgsOrExit patterns =<< getArgs
when (isPresent args (longOption "help")) $ do
exitWithUsage patterns
when ((isPresent args (argument "INFILE")) || (isPresent args (argument "OUTFILE"))) $ do
hPutStrLn stderr deprecationWarning
contents <- input args
case (parse cmParse "" contents) of
Left err -> putStrLn $ show err
Right out -> output args out
where
deprecationWarning = "`criticmarkuphs INFILE OUTFILE` is deprecated\nSee `criticmarkuphs -h`"
maybeFile args lo ar = listToMaybe $ catMaybes [getArg args (longOption lo), getArg args (argument ar)]
input args = case (maybeFile args "infile" "INFILE") of
Just file -> readFile file
Nothing -> getContents
output args out = case (maybeFile args "outfile" "OUTFILE") of
Just file -> writeFile file out
Nothing -> putStr out
-- should CM keep or drop the text between tags
data Keep = Keep | Drop
deriving (Show)
-- 3 types of tages
-- EOF tag
-- "terminator" tag, containing string indicating end of tag
-- regular tag, containing:
-- . open tag string
-- . transition tag ending current tag
-- . keep/drop text in tag
data CMTag = EOF | Close String | Tag String CMTag Keep
deriving (Show)
-- critic markup tags
cmAdd = Tag "{++" (Close "++}") Keep
cmDel = Tag "{--" (Close "--}") Drop
cmSub = Tag "{~~" (Tag "~>" (Close "~~}") Keep) Drop
cmHil = Tag "{==" (Close "==}") Keep
cmCom = Tag "{>>" (Close "<<}") Drop
cmTags :: [CMTag]
cmTags = [cmAdd,cmDel,cmSub,cmHil,cmCom]
-- | builds the stop characters
stopChars :: String -> CMTag -> String
stopChars stops EOF = stops
stopChars stops (Close str) = addHead stops str
stopChars stops (Tag str _ _) = addHead stops str
-- | prepends the head of a possibly empty string to another string
addHead :: String -> String -> String
addHead str "" = str
addHead str (x:xs) = x:str
-- | keep or drop results of the parser
-- n.b. have to make sure to run the parser even when dropping its results
keepFilter :: Keep -> Parsec String () String -> Parsec String () String
keepFilter Keep x = x
keepFilter Drop x = x >> return ""
matchTag :: CMTag -> Parsec String () String
matchTag EOF = eof >> return ""
matchTag (Close x) = try $ string x >> return ""
matchTag (Tag start stop keep) = do
try $ string start
pre <- keepFilter keep (many $ noneOf stopChars')
post <- matchTag stop <|> -- match the end tag
choice (map innerTag cmTags) <|> -- match a new tag, and continue parsing
choice (map loneStopChar stopChars') -- match a lone stop character, and continue parsing
return (pre ++ post)
where
tagStarts = "{~"
stopChars' = stopChars tagStarts stop
restTag = matchTag (Tag "" stop keep)
loneStopChar x = innerParse (char x >> return [x])
innerTag tag = innerParse (matchTag tag)
innerParse x = do
inner <- keepFilter keep $ x
rest <- restTag
return (inner ++ rest)
cmParse :: Parsec String () String
cmParse = matchTag (Tag "" EOF Keep)
{-cmStart' :: CMTag -> Parsec String () String-}
{-cmStart' (Tag )-}
{- what's the structure of a critic markup document?
- n.b. there is not actually a spec wrt:
- 1. escaping tags in text: e.g. how to insert a literal "{++"?
- 2. overlapping tags: "{++ lorem {>> ipsum ++} dolor <<}" parses to what?
- let's ban overlaps, and no escaping for now
- structure:
- text -> tag + text -> recurse
-}
{-cmStart :: Maybe String -> Parsec String () String-}
{-cmStart Nothing = do-}
{-pre <- many (noneOf "{")-}
{--- we've hit the typical break-}
{-(inner, post) <- cmRest Nothing-}
{-return (concat [pre,inner,post])-}
{-cmStart (Just end@(x:xs)) = do-}
{-pre <- many (noneOf $ x:"{")-}
{--- we stopped because: we ended the tag, we matched the end of tag char, or the usual break-}
{-(try $ string end >> return pre) <|>-}
{-(try $ char x >> cmStart (Just end) >>= \post -> return (concat [pre,[x],post])) <|>-}
{-(cmRest (Just end) >>= \(inner,post) -> return (concat [pre,inner,post]))-}
runTests = sequence_ $ map (outstr) tests
where
outstr' x = putStr ("\"" ++ x ++ "\" :=>: ") >> (parseTest cmParse x)
outstr (x,y) = do
let res = parse cmParse "" x
case res of
Left err -> putStrLn ("Error :: \"" ++ x ++ "\" :=>: " ++ (show err))
Right res' -> if res' == y then putStr "" else putStrLn ("Misparse :: \"" ++ x ++ "\" :=>: \"" ++ res' ++ "\"")
tests = [
("test","test"),
("test {++foo++} test","test foo test"),
("test {--foo--} test","test test"),
("test {--{++foo++}bar--} test","test test"),
("test {++{--foo--}bar++} test","test bar test"),
("test {~~foo~>bar~~} test","test bar test"),
("test {~~foo{++baz++}~>bar~~} test","test bar test"),
("test {~~foo{--baz--}~>bar~~} test","test bar test"),
("test {++foo",""),
("test","test")
]
{-tests = [-}
{-("{++test++}","test"),-}
{-("{++test{++tester++}++}","test{++tester++}")]-}
| balachia/CriticMarkup.hs | CriticMarkup.hs | mit | 5,862 | 0 | 18 | 1,425 | 1,445 | 753 | 692 | 97 | 4 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module CustomContentsDialog where
import Data.Maybe (isJust, fromJust)
import Data.List
import Control.Applicative
import Graphics.UI.Gtk
import Control.Lens hiding (set)
import Data.Either
import SettingsWindowData
import GtkViewModel
import FrameRenderer
import Settings
import Helpers
completionDataDate :: [(String, String)]
completionDataDate = [
(__ "Date formatted in your system language", "%x"),
(__ "Hours and minutes", "%R"),
(__ "Hours, minutes and seconds", "%X"),
(__ "Hour of the day (24h). 00-23", "%H"),
(__ "Hour of the day (24h). 0-23", "%k"),
(__ "Hour of half-day (12h). 01-12", "%I"),
(__ "Hour of half-day (12h). 1-12", "%l"),
(__ "Minute of hour, 00-59", "%M"),
(__ "Second of minute, 00-60", "%S"),
(__ "Year", "%Y"),
(__ "Year of century, 00-99", "%y"),
(__ "Month name, long form, January-December", "%B"),
(__ "Month name, short form, Jan-Dec", "%b"),
(__ "Month of year, 01-12", "%m"),
(__ "Day of month, 01-31", "%d"),
(__ "Day of month, 1-31", "%e"),
(__ "Day of week, short form, Sun-Sat", "%a"),
(__ "Day of week, long form, Sunday-Saturday", "%A")
]
defaultEnvironmentInfo :: EnvironmentInfo
#ifdef CABAL_OS_WINDOWS
defaultEnvironmentInfo = EnvironmentInfo "c:\\Users\\user"
#else
defaultEnvironmentInfo = EnvironmentInfo "/home/user"
#endif
data CompletionRecordType = NormalCompletion | DateCompletion
deriving (Eq, Show)
data CompletionRecord = CompletionRecord
{
complRecordType :: CompletionRecordType,
complRecordDesc :: String,
complRecordValue :: String
} deriving Show
isDateRecord :: CompletionRecord -> Bool
isDateRecord (CompletionRecord t _ _) = t == DateCompletion
showCustomContentsDialog :: WindowClass a => a -> BuilderHolder -> Model DisplayItem -> IO ()
showCustomContentsDialog parent builderHolder displayItemModel = do
let builder = boundBuilder builderHolder
dialog <- builderGetObject builder castToDialog "customContentsDialog"
customContentsEntry <- builderGetObject builder castToEntry "customContentsEntry"
curContents <- itemContents <$> readModel displayItemModel
okBtnBinder <- builderHolderGetButtonBinder builderHolder "customContentsOK"
let okBtn = boundButton okBtnBinder
cancelBtn <- builderGetObject builder castToButton "customContentsCancel"
defaultDisplayItem <- readModel displayItemModel
parseResultLabel <- builderGetObject builder castToLabel "parseResultLabel"
customContentsEntry `on` editableChanged $ do
text <- entryGetText customContentsEntry
let isParseOk = not $ isLeft $ parseFormat text
labelSetMarkup parseResultLabel $ if isParseOk
then getTextToRender (defaultDisplayItem {itemContents = text}) fakeImageInfo defaultEnvironmentInfo
else __ "<span color='red'><b>Incorrect syntax</b></span>"
widgetSetSensitivity okBtn isParseOk
entrySetText customContentsEntry curContents
completion <- entryCompletionNew
let completionData = fmap (uncurry $ CompletionRecord NormalCompletion) completionComboData
++ [CompletionRecord NormalCompletion (__ "% sign") "%%"]
++ fmap (uncurry $ CompletionRecord DateCompletion) completionDataDate
++ [CompletionRecord DateCompletion (__ "% sign") "%%"]
completionStore <- listStoreNew completionData
entryCompletionSetModel completion $ Just completionStore
cellValue <- cellRendererTextNew
cellLayoutPackStart completion cellValue True
cellLayoutSetAttributes completion cellValue completionStore
(\val -> [cellText := complRecordDesc val])
cellDesc <- cellRendererTextNew
cellLayoutPackStart completion cellDesc True
cellLayoutSetAttributes completion cellDesc completionStore
(\val -> [cellText := complRecordValue val])
entryCompletionSetMinimumKeyLength completion 1
entryCompletionSetMatchFunc completion $
customContentsCompletionCb completionData customContentsEntry
entrySetCompletion customContentsEntry completion
completion `on` matchSelected $ \_ iter -> do
let candidate = completionData !! listStoreIterToIndex iter
textSoFar <- entryGetText customContentsEntry
cursorPosBefore <- get customContentsEntry entryCursorPosition
let (beforeCursor, afterCursor) = splitAt cursorPosBefore textSoFar
textWhichGotCompleted <- fromJust <$> textBeforeCursorFromSymbol "%" customContentsEntry
let lengthBeforeCompletion = length beforeCursor - length textWhichGotCompleted
let newText = take lengthBeforeCompletion textSoFar
++ complRecordValue candidate ++ afterCursor
entrySetText customContentsEntry newText
let newPos = lengthBeforeCompletion + length (complRecordValue candidate)
editableSetPosition customContentsEntry newPos
return True
buttonBindCallback okBtnBinder $ do
newText <- entryGetText customContentsEntry
modifyModel displayItemModel $ itemContentsL .~ newText
widgetHide dialog
cancelBtn `on` buttonActivated $ widgetHide dialog
showDialog dialog parent
textBeforeCursorFromSymbol :: String -> Entry -> IO (Maybe String)
textBeforeCursorFromSymbol symbol entry = do
cursorPos <- get entry entryCursorPosition
typed <- take cursorPos <$> entryGetText entry
return $ find (isPrefixOf symbol) $ tail $ reverse $ tails typed
customContentsCompletionCb :: [CompletionRecord] -> Entry -> String -> TreeIter -> IO Bool
customContentsCompletionCb completionModel entry _ iter = do
let candidate = completionModel !! listStoreIterToIndex iter
beforePercent <- textBeforeCursorFromSymbol "%" entry
beforeDate <- textBeforeCursorFromSymbol "%date{" entry
let inDateContext = isJust beforeDate && not ("}" `isInfixOf` fromJust beforeDate)
case beforePercent of
Nothing -> return False
Just fromPercent | inDateContext ->
return $ isDateRecord candidate && fromPercent `isPrefixOf` complRecordValue candidate
Just fromPercent ->
return $ not (isDateRecord candidate) && fromPercent `isPrefixOf` complRecordValue candidate
| emmanueltouzery/imprint | src/CustomContentsDialog.hs | mit | 6,301 | 0 | 17 | 1,215 | 1,432 | 705 | 727 | 119 | 3 |
import TwoPhase
import Control.Applicative
import System.Directory
import System.Environment
import System.Exit
import System.FilePath
import System.IO
main :: IO ()
main = do
args <- getArgs
path <- case args of
[] -> (</> ".tseven") <$> getHomeDirectory
p : _ -> return p
createDirectoryIfMissing
True -- createParents
path
let p1 = path </> "phase1"
p2 = path </> "phase2"
fileExists <- and <$> mapM doesFileExist [p1,p2]
case fileExists of
True -> do
hPutStrLn stderr $ "File(s) already exist(s) in '" ++ path ++"'."
exitFailure
False -> do
putStrLn "Phase 1"
encodeFile p1 phase1Compressed'
putStrLn "Phase 2"
encodeFile p2 phase2Compressed'
exitSuccess
| Lysxia/twentyseven | exec-src/tstables.hs | mit | 755 | 0 | 15 | 194 | 220 | 106 | 114 | 29 | 3 |
--
-- Euler published the remarkable quadratic formula:
--
-- n^2 + n + 41
--
-- It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39.
-- However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when
-- n = 41, 41² + 41 + 41 is clearly divisible by 41.
--
-- Using computers, the incredible formula n^2 79n + 1601 was discovered, which produces
-- 80 primes for the consecutive values n = 0 to 79. The product of the coefficients,
-- 79 and 1601, is 126479.
--
-- Considering quadratics of the form:
--
-- n^2 + an + b, where |a| < 1000 and |b| < 1000
--
-- where |n| is the modulus/absolute value of n
-- e.g. |11| = 11 and |4| = 4
-- Find the product of the coefficients, a and b, for the quadratic expression that produces
-- the maximum number of primes for consecutive values of n, starting with n = 0.
--
import List
import Maybe
import Data.Ord
primes
= 2 : 3 : filter isPrime [5,7..]
isPrime n
= all (notDivs n) $ takeWhile (\ p -> p * p <= n) primes
where notDivs n p = n `mod` p /= 0
numPrimesInQuadratic a b
= length $ takeWhile nthIsPrime [0..]
where nthIsPrime n = isPrime $ toInteger $ abs $ n * n + a * n + b
consecutives
= do a <- [-999 .. 999]
b <- [-999 .. 999]
return (a * b, numPrimesInQuadratic a b)
main
= print $ maximumBy (comparing snd) consecutives
| stu-smith/project-euler-haskell | Euler-027.hs | mit | 1,440 | 0 | 13 | 378 | 258 | 144 | 114 | 17 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Algebraic.Relation.Restriction where
import Condition
import Autolib.Reader
import Autolib.ToDoc
import Autolib.Size
import Autolib.Reporter
import Data.Typeable
data Restriction
= Size_Range (Int, Int)
deriving ( Eq, Ord, Typeable )
$(derives [makeReader, makeToDoc] [''Restriction])
-- local variables:
-- mode: haskell
-- end:
| marcellussiegburg/autotool | collection/src/Algebraic/Relation/Restriction.hs | gpl-2.0 | 431 | 0 | 9 | 72 | 93 | 56 | 37 | 13 | 0 |
-- Module for generating sample patterns for distributed ray tracing
module Distribution (generatePointsOnSphere,
generatePointsOnQuad,
generatePointsOnHemisphere,
generatePointOnHemisphere,
generateRandomUVs,
generateDirectionsOnSphere,
generateStratifiedDirectionOnHemisphere,
generateUnstratifiedDirectionOnHemisphere,
generateStratifiedDirectionsOnHemisphere,
generateUnstratifiedDirectionsOnHemisphere,
randomUV,
stratify,
uvToHemisphere) where
import PolymorphicNum
import Vector
import System.Random
import Control.Monad.State
import Misc
-- Generate a pair of random normalised floats
randomUV :: (RandomGen g) => State g (Double, Double)
randomUV = do u <- randDouble
v <- randDouble
return (saturate u, saturate v)
-- Generate a list of N random UVs
generateRandomUVs :: (RandomGen g) => Int -> State g [(Double, Double)]
generateRandomUVs n = replicateM n randomUV
uvToSphere :: Double -> (Double, Double) -> Position
uvToSphere r (u, v) = Vector (r * x) (r * y) (r * z) 1
where
z = 2 * u - 1
t = 2 * pi * v
w = sqrt (1 - z * z)
x = w * cos t
y = w * sin t
-- Proportional to cosine-weighted solid angle
uvToHemisphere :: Double -> Double -> (Double, Double) -> Position
{-# SPECIALIZE INLINE uvToHemisphere :: Double -> Double -> (Double, Double) -> Position #-}
uvToHemisphere r w (u, v) = Vector (r * x) (r * y) (r * z) w
where
k = sqrt u
theta = 2.0 * pi * v
x = k * cos theta
y = k * sin theta
z = sqrt (1.0 - u)
-- Generate a list of random points on a sphere
generatePointsOnSphere :: (RandomGen g) => Int -> Double -> g -> ([Position], g)
generatePointsOnSphere numPoints r gen
| numPoints <= 1 = ([Vector 0 0 0 1], gen)
| otherwise = (map (uvToSphere r) randomUVs, gen')
where
(randomUVs, gen') = runState (generateRandomUVs numPoints) gen
-- Generate a list of random points on a hemisphere (z > 0)
generatePointsOnHemisphere :: (RandomGen g) => Int -> Double -> g -> ([Position], g)
generatePointsOnHemisphere numPoints r gen
| numPoints <= 1 = ([Vector 0 0 0 1], gen)
| otherwise = (map (uvToHemisphere r 1) randomUVs, gen')
where
(randomUVs, gen') = runState (generateRandomUVs numPoints) gen
generatePointsOnQuad :: (RandomGen g) => Position -> Direction -> Direction -> Int -> g -> ([Position], g)
generatePointsOnQuad pos deltaU deltaV numPoints gen
| numPoints <= 1 = ([Vector 0 0 0 1], gen)
| otherwise = (map (\(u, v) -> pos <+> deltaU <*> u <+> deltaV <*> v) randomUVs, gen')
where
(randomUVs, gen') = runState (generateRandomUVs numPoints) gen
-- Generate a single random point on a hemisphere
generatePointOnHemisphere :: (RandomGen g) => g -> Double -> (Position, g)
generatePointOnHemisphere gen r = (uvToHemisphere r 1 uv, gen')
where
(uv, gen') = runState randomUV gen
-- Stratify over an 8x8 grid
stratify :: (Double, Double) -> Int -> (Double, Double)
stratify (u, v) index = ((col + u) * recipGridX, (row + v) * recipGridY)
where
gridX = 8
gridY = 8
recipGridX = (1.0 :: Double) / gridX
recipGridY = (1.0 :: Double) / gridY
wrappedIndex = index `mod` floor (gridX * gridY)
row = fromIntegral (wrappedIndex `div` floor gridX)
col = fromIntegral (wrappedIndex `mod` floor gridX)
generateDirectionsOnSphere :: (RandomGen g) => Int -> Double -> g -> ([Direction], g)
generateDirectionsOnSphere numPoints r gen
| numPoints <= 1 = ([Vector 0 0 0 1], gen)
| otherwise = (map (setWTo0 . uvToSphere r) randomUVs, gen')
where
(randomUVs, gen') = runState (generateRandomUVs numPoints) gen
generateUnstratifiedDirectionOnHemisphere :: (RandomGen g) => Double -> State g Direction
generateUnstratifiedDirectionOnHemisphere r = do
u <- randDouble
v <- randDouble
return (uvToHemisphere r 0 (u, v))
generateStratifiedDirectionOnHemisphere :: (RandomGen g) => g -> Double -> Int -> (Direction, g)
generateStratifiedDirectionOnHemisphere gen r index = (uvToHemisphere r 0 (stratify uv index), gen')
where
(uv, gen') = runState randomUV gen
generateStratifiedDirectionsOnHemisphere :: (RandomGen g) => Int -> Double -> g -> ([Direction], g)
generateStratifiedDirectionsOnHemisphere numPoints r gen
| numPoints <= 1 = ([Vector 0 0 0 1], gen)
| numPoints `mod` 64 /= 0 = error "Error, must specify point count in multiples of 64 (8x8 grid stratification)"
| otherwise = (map (uvToHemisphere r 0) stratifiedUVs, gen')
where
(randomUVs, gen') = runState (generateRandomUVs numPoints) gen
stratifiedUVs = zipWith stratify randomUVs [0..]
generateUnstratifiedDirectionsOnHemisphere :: (RandomGen g) => Int -> Double -> g -> ([Direction], g)
generateUnstratifiedDirectionsOnHemisphere numPoints r gen
| numPoints <= 1 = ([Vector 0 0 0 1], gen)
| otherwise = (map (uvToHemisphere r 0) randomUVs, gen')
where
(randomUVs, gen') = runState (generateRandomUVs numPoints) gen
| TomHammersley/HaskellRenderer | app/src/Distribution.hs | gpl-2.0 | 5,243 | 0 | 13 | 1,286 | 1,682 | 906 | 776 | 91 | 1 |
f . p' = g . p' | hmemcpy/milewski-ctfp-pdf | src/content/2.2/code/haskell/snippet09.hs | gpl-3.0 | 15 | 0 | 5 | 6 | 16 | 7 | 9 | 1 | 1 |
module Theme (myTheme) where
import Data.Monoid ((<>))
import Yi
import Yi.Style (Color(Default))
defaultColor :: Yi.Style.Color
defaultColor = Yi.Style.Default
myTheme :: Proto UIStyle
myTheme = defaultTheme `override` \super _ -> super
{ modelineAttributes = emptyAttributes { foreground = black, background = darkcyan }
, tabBarAttributes = emptyAttributes { foreground = white, background = defaultColor }
, baseAttributes = emptyAttributes { foreground = defaultColor, background = defaultColor, bold=True }
, commentStyle = withFg darkred <> withBd False <> withItlc True
, selectedStyle = withReverse True
, errorStyle = withBg red <> withFg white
, operatorStyle = withFg brown <> withBd False
, hintStyle = withBg brown <> withFg black
, importStyle = withFg blue
, dataConstructorStyle = withFg blue
, typeStyle = withFg blue
, keywordStyle = withFg yellow
, builtinStyle = withFg brown
, strongHintStyle = withBg brown <> withUnderline True
, stringStyle = withFg brown <> withBd False
, preprocessorStyle = withFg blue
}
| siddhanathan/dotfiles | src/shared/yi/lib/Theme.hs | gpl-3.0 | 1,194 | 0 | 11 | 315 | 314 | 180 | 134 | 24 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.PubSub.Projects.Schemas.ValidateMessage
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Validates a message against a schema.
--
-- /See:/ <https://cloud.google.com/pubsub/docs Cloud Pub/Sub API Reference> for @pubsub.projects.schemas.validateMessage@.
module Network.Google.Resource.PubSub.Projects.Schemas.ValidateMessage
(
-- * REST Resource
ProjectsSchemasValidateMessageResource
-- * Creating a Request
, projectsSchemasValidateMessage
, ProjectsSchemasValidateMessage
-- * Request Lenses
, psvmParent
, psvmXgafv
, psvmUploadProtocol
, psvmAccessToken
, psvmUploadType
, psvmPayload
, psvmCallback
) where
import Network.Google.Prelude
import Network.Google.PubSub.Types
-- | A resource alias for @pubsub.projects.schemas.validateMessage@ method which the
-- 'ProjectsSchemasValidateMessage' request conforms to.
type ProjectsSchemasValidateMessageResource =
"v1" :>
Capture "parent" Text :>
"schemas:validateMessage" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ValidateMessageRequest :>
Post '[JSON] ValidateMessageResponse
-- | Validates a message against a schema.
--
-- /See:/ 'projectsSchemasValidateMessage' smart constructor.
data ProjectsSchemasValidateMessage =
ProjectsSchemasValidateMessage'
{ _psvmParent :: !Text
, _psvmXgafv :: !(Maybe Xgafv)
, _psvmUploadProtocol :: !(Maybe Text)
, _psvmAccessToken :: !(Maybe Text)
, _psvmUploadType :: !(Maybe Text)
, _psvmPayload :: !ValidateMessageRequest
, _psvmCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsSchemasValidateMessage' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'psvmParent'
--
-- * 'psvmXgafv'
--
-- * 'psvmUploadProtocol'
--
-- * 'psvmAccessToken'
--
-- * 'psvmUploadType'
--
-- * 'psvmPayload'
--
-- * 'psvmCallback'
projectsSchemasValidateMessage
:: Text -- ^ 'psvmParent'
-> ValidateMessageRequest -- ^ 'psvmPayload'
-> ProjectsSchemasValidateMessage
projectsSchemasValidateMessage pPsvmParent_ pPsvmPayload_ =
ProjectsSchemasValidateMessage'
{ _psvmParent = pPsvmParent_
, _psvmXgafv = Nothing
, _psvmUploadProtocol = Nothing
, _psvmAccessToken = Nothing
, _psvmUploadType = Nothing
, _psvmPayload = pPsvmPayload_
, _psvmCallback = Nothing
}
-- | Required. The name of the project in which to validate schemas. Format
-- is \`projects\/{project-id}\`.
psvmParent :: Lens' ProjectsSchemasValidateMessage Text
psvmParent
= lens _psvmParent (\ s a -> s{_psvmParent = a})
-- | V1 error format.
psvmXgafv :: Lens' ProjectsSchemasValidateMessage (Maybe Xgafv)
psvmXgafv
= lens _psvmXgafv (\ s a -> s{_psvmXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
psvmUploadProtocol :: Lens' ProjectsSchemasValidateMessage (Maybe Text)
psvmUploadProtocol
= lens _psvmUploadProtocol
(\ s a -> s{_psvmUploadProtocol = a})
-- | OAuth access token.
psvmAccessToken :: Lens' ProjectsSchemasValidateMessage (Maybe Text)
psvmAccessToken
= lens _psvmAccessToken
(\ s a -> s{_psvmAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
psvmUploadType :: Lens' ProjectsSchemasValidateMessage (Maybe Text)
psvmUploadType
= lens _psvmUploadType
(\ s a -> s{_psvmUploadType = a})
-- | Multipart request metadata.
psvmPayload :: Lens' ProjectsSchemasValidateMessage ValidateMessageRequest
psvmPayload
= lens _psvmPayload (\ s a -> s{_psvmPayload = a})
-- | JSONP
psvmCallback :: Lens' ProjectsSchemasValidateMessage (Maybe Text)
psvmCallback
= lens _psvmCallback (\ s a -> s{_psvmCallback = a})
instance GoogleRequest ProjectsSchemasValidateMessage
where
type Rs ProjectsSchemasValidateMessage =
ValidateMessageResponse
type Scopes ProjectsSchemasValidateMessage =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/pubsub"]
requestClient ProjectsSchemasValidateMessage'{..}
= go _psvmParent _psvmXgafv _psvmUploadProtocol
_psvmAccessToken
_psvmUploadType
_psvmCallback
(Just AltJSON)
_psvmPayload
pubSubService
where go
= buildClient
(Proxy ::
Proxy ProjectsSchemasValidateMessageResource)
mempty
| brendanhay/gogol | gogol-pubsub/gen/Network/Google/Resource/PubSub/Projects/Schemas/ValidateMessage.hs | mpl-2.0 | 5,577 | 0 | 17 | 1,250 | 783 | 457 | 326 | 118 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.Reservations.Insert
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a new reservation. For more information, read Reserving zonal
-- resources.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.reservations.insert@.
module Network.Google.Resource.Compute.Reservations.Insert
(
-- * REST Resource
ReservationsInsertResource
-- * Creating a Request
, reservationsInsert
, ReservationsInsert
-- * Request Lenses
, riiRequestId
, riiProject
, riiZone
, riiPayload
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.reservations.insert@ method which the
-- 'ReservationsInsert' request conforms to.
type ReservationsInsertResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"zones" :>
Capture "zone" Text :>
"reservations" :>
QueryParam "requestId" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Reservation :> Post '[JSON] Operation
-- | Creates a new reservation. For more information, read Reserving zonal
-- resources.
--
-- /See:/ 'reservationsInsert' smart constructor.
data ReservationsInsert =
ReservationsInsert'
{ _riiRequestId :: !(Maybe Text)
, _riiProject :: !Text
, _riiZone :: !Text
, _riiPayload :: !Reservation
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ReservationsInsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'riiRequestId'
--
-- * 'riiProject'
--
-- * 'riiZone'
--
-- * 'riiPayload'
reservationsInsert
:: Text -- ^ 'riiProject'
-> Text -- ^ 'riiZone'
-> Reservation -- ^ 'riiPayload'
-> ReservationsInsert
reservationsInsert pRiiProject_ pRiiZone_ pRiiPayload_ =
ReservationsInsert'
{ _riiRequestId = Nothing
, _riiProject = pRiiProject_
, _riiZone = pRiiZone_
, _riiPayload = pRiiPayload_
}
-- | An optional request ID to identify requests. Specify a unique request ID
-- so that if you must retry your request, the server will know to ignore
-- the request if it has already been completed. For example, consider a
-- situation where you make an initial request and the request times out.
-- If you make the request again with the same request ID, the server can
-- check if original operation with the same request ID was received, and
-- if so, will ignore the second request. This prevents clients from
-- accidentally creating duplicate commitments. The request ID must be a
-- valid UUID with the exception that zero UUID is not supported
-- (00000000-0000-0000-0000-000000000000).
riiRequestId :: Lens' ReservationsInsert (Maybe Text)
riiRequestId
= lens _riiRequestId (\ s a -> s{_riiRequestId = a})
-- | Project ID for this request.
riiProject :: Lens' ReservationsInsert Text
riiProject
= lens _riiProject (\ s a -> s{_riiProject = a})
-- | Name of the zone for this request.
riiZone :: Lens' ReservationsInsert Text
riiZone = lens _riiZone (\ s a -> s{_riiZone = a})
-- | Multipart request metadata.
riiPayload :: Lens' ReservationsInsert Reservation
riiPayload
= lens _riiPayload (\ s a -> s{_riiPayload = a})
instance GoogleRequest ReservationsInsert where
type Rs ReservationsInsert = Operation
type Scopes ReservationsInsert =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient ReservationsInsert'{..}
= go _riiProject _riiZone _riiRequestId
(Just AltJSON)
_riiPayload
computeService
where go
= buildClient
(Proxy :: Proxy ReservationsInsertResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/Reservations/Insert.hs | mpl-2.0 | 4,686 | 0 | 17 | 1,073 | 559 | 335 | 224 | 85 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE Trustworthy, UnicodeSyntax, FlexibleInstances, UndecidableInstances #-}
-- | Orphan instances and utility functions for Data.Has, a typeclass for extracting values from a structure by type.
module Magicbane.Has (
module X
, module Magicbane.Has
) where
import Data.Has as X
import Control.Monad.Reader (MonadReader, asks)
import RIO (HasLogFunc(..))
import Magicbane.Logging (ModLogger)
import Magicbane.Metrics (ModMetrics(..), MonadMetrics, getMetrics)
import Magicbane.HTTPClient (ModHttpClient(..), HasHttpManager, getHttpManager)
instance {-# OVERLAPPABLE #-} (Has ModHttpClient α) ⇒ HasHttpManager α where
getHttpManager = (\(ModHttpClient m) → m) <$> getter
instance {-# OVERLAPPABLE #-} Has ModLogger α ⇒ HasLogFunc α where
logFuncL = hasLens
instance (Has ModMetrics α, Monad μ, MonadReader α μ) ⇒ MonadMetrics μ where
getMetrics = (\(ModMetrics m) → m) <$> asks getter
-- | Gets a value of any type from the context.
askObj ∷ (Has β α, MonadReader α μ) ⇒ μ β
askObj = asks getter
-- | Gets a thing from a value of any type from the context. (Useful for configuration fields.)
askOpt ∷ (Has β α, MonadReader α μ) ⇒ (β → ψ) → μ ψ
askOpt f = asks $ f . getter
| myfreeweb/magicbane | library/Magicbane/Has.hs | unlicense | 1,338 | 0 | 10 | 261 | 320 | 184 | 136 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module HepMC.Units
( Units, unitMomentum, unitLength
, parserUnits
) where
import Control.Lens
import HepMC.Parse
data UnitMomentum = MEV | GEV deriving (Eq, Ord, Show)
data UnitLength = MM | CM deriving (Eq, Ord, Show)
type Units = (UnitMomentum, UnitLength)
unitMomentum :: Lens' Units UnitMomentum
unitMomentum = _1
unitLength :: Lens' Units UnitLength
unitLength = _2
unitP :: Parser UnitMomentum
unitP =
string "MEV" *> return MEV <|> string "GEV" *> return GEV
unitL :: Parser UnitLength
unitL =
string "MM" *> return MM <|> string "CM" *> return CM
parserUnits :: Parser Units
parserUnits = tuple (unitP <* skipSpace) (unitL <* skipSpace)
| cspollard/HHepMC | src/HepMC/Units.hs | apache-2.0 | 720 | 0 | 8 | 145 | 229 | 123 | 106 | 21 | 1 |
-- do can have explicit semi colons
f x = do x
x; x | metaborg/jsglr | org.spoofax.jsglr/tests-offside/terms/doaitse/layout10.hs | apache-2.0 | 60 | 0 | 6 | 22 | 20 | 9 | 11 | 2 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Kubernetes.V1.SecurityContext where
import GHC.Generics
import Kubernetes.V1.Capabilities
import Kubernetes.V1.SELinuxOptions
import qualified Data.Aeson
-- | SecurityContext holds security configuration that will be applied to a container. Some fields are present in both SecurityContext and PodSecurityContext. When both are set, the values in SecurityContext take precedence.
data SecurityContext = SecurityContext
{ capabilities :: Maybe Capabilities -- ^ The capabilities to add/drop when running containers. Defaults to the default set of capabilities granted by the container runtime.
, privileged :: Maybe Bool -- ^ Run container in privileged mode. Processes in privileged containers are essentially equivalent to root on the host. Defaults to false.
, seLinuxOptions :: Maybe SELinuxOptions -- ^ The SELinux context to be applied to the container. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
, runAsUser :: Maybe Integer -- ^ The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
, runAsNonRoot :: Maybe Bool -- ^ Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON SecurityContext
instance Data.Aeson.ToJSON SecurityContext
| minhdoboi/deprecated-openshift-haskell-api | kubernetes/lib/Kubernetes/V1/SecurityContext.hs | apache-2.0 | 2,187 | 0 | 9 | 343 | 130 | 79 | 51 | 19 | 0 |
module Kernel.KernelMonad where
import Kernel.Term
import Kernel.Env
import Control.Applicative
import Control.Monad.Reader
import Control.Monad.Error
data KernelError = TypeError String [(LocalEnv, Term)]
| FatalError String
instance Error KernelError where
strMsg = FatalError
{-
instance Show KernelError where
show (TypeError s ts) = "type error: " ++ s ++ " " ++ show (map (uncurry LocalTerm) ts)
show (FatalError s) = "fatal error: " ++ s
-}
newtype Kernel a = Kernel { unKernel :: ErrorT KernelError (Reader Global) a }
instance Functor Kernel where
fmap = liftM
instance Applicative Kernel where
pure = return
(<*>) = ap
instance Monad Kernel where
return = Kernel . return
(Kernel m) >>= k = Kernel $ m >>= \x -> unKernel (k x)
getGlobalBindings :: Kernel GlobalBindings
getGlobalBindings = Kernel $ gbindings <$> ask
getUniverseBindings :: Kernel UnivBindings
getUniverseBindings = Kernel $ ubindings <$> ask
typeError :: String -> [(LocalEnv, Term)] -> Kernel a
typeError s ts = Kernel $ throwError $ TypeError s ts
fatalError :: String -> Kernel a
fatalError s = Kernel $ throwError $ FatalError s
| kik/ToyPr | src/Kernel/KernelMonad.hs | apache-2.0 | 1,156 | 0 | 10 | 221 | 309 | 169 | 140 | 27 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QDragMoveEvent.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:20
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QDragMoveEvent (
QqqDragMoveEvent(..), QqDragMoveEvent(..)
,QqqDragMoveEvent_nf(..), QqDragMoveEvent_nf(..)
,qaccept
,qanswerRect, answerRect
,qignore
,qDragMoveEvent_delete
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Enums.Core.QEvent
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqqDragMoveEvent x1 where
qqDragMoveEvent :: x1 -> IO (QDragMoveEvent ())
class QqDragMoveEvent x1 where
qDragMoveEvent :: x1 -> IO (QDragMoveEvent ())
instance QqDragMoveEvent ((QDragMoveEvent t1)) where
qDragMoveEvent (x1)
= withQDragMoveEventResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDragMoveEvent cobj_x1
foreign import ccall "qtc_QDragMoveEvent" qtc_QDragMoveEvent :: Ptr (TQDragMoveEvent t1) -> IO (Ptr (TQDragMoveEvent ()))
instance QqqDragMoveEvent ((QPoint t1, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qqDragMoveEvent (x1, x2, x3, x4, x5)
= withQDragMoveEventResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent1 cobj_x1 (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
foreign import ccall "qtc_QDragMoveEvent1" qtc_QDragMoveEvent1 :: Ptr (TQPoint t1) -> CLong -> Ptr (TQMimeData t3) -> CLong -> CLong -> IO (Ptr (TQDragMoveEvent ()))
instance QqDragMoveEvent ((Point, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qDragMoveEvent (x1, x2, x3, x4, x5)
= withQDragMoveEventResult $
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent2 cpoint_x1_x cpoint_x1_y (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
foreign import ccall "qtc_QDragMoveEvent2" qtc_QDragMoveEvent2 :: CInt -> CInt -> CLong -> Ptr (TQMimeData t3) -> CLong -> CLong -> IO (Ptr (TQDragMoveEvent ()))
instance QqqDragMoveEvent ((QPoint t1, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers, QEventType)) where
qqDragMoveEvent (x1, x2, x3, x4, x5, x6)
= withQDragMoveEventResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent3 cobj_x1 (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5) (toCLong $ qEnum_toInt x6)
foreign import ccall "qtc_QDragMoveEvent3" qtc_QDragMoveEvent3 :: Ptr (TQPoint t1) -> CLong -> Ptr (TQMimeData t3) -> CLong -> CLong -> CLong -> IO (Ptr (TQDragMoveEvent ()))
instance QqDragMoveEvent ((Point, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers, QEventType)) where
qDragMoveEvent (x1, x2, x3, x4, x5, x6)
= withQDragMoveEventResult $
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent4 cpoint_x1_x cpoint_x1_y (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5) (toCLong $ qEnum_toInt x6)
foreign import ccall "qtc_QDragMoveEvent4" qtc_QDragMoveEvent4 :: CInt -> CInt -> CLong -> Ptr (TQMimeData t3) -> CLong -> CLong -> CLong -> IO (Ptr (TQDragMoveEvent ()))
class QqqDragMoveEvent_nf x1 where
qqDragMoveEvent_nf :: x1 -> IO (QDragMoveEvent ())
class QqDragMoveEvent_nf x1 where
qDragMoveEvent_nf :: x1 -> IO (QDragMoveEvent ())
instance QqDragMoveEvent_nf ((QDragMoveEvent t1)) where
qDragMoveEvent_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDragMoveEvent cobj_x1
instance QqqDragMoveEvent_nf ((QPoint t1, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qqDragMoveEvent_nf (x1, x2, x3, x4, x5)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent1 cobj_x1 (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
instance QqDragMoveEvent_nf ((Point, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qDragMoveEvent_nf (x1, x2, x3, x4, x5)
= withObjectRefResult $
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent2 cpoint_x1_x cpoint_x1_y (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
instance QqqDragMoveEvent_nf ((QPoint t1, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers, QEventType)) where
qqDragMoveEvent_nf (x1, x2, x3, x4, x5, x6)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent3 cobj_x1 (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5) (toCLong $ qEnum_toInt x6)
instance QqDragMoveEvent_nf ((Point, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers, QEventType)) where
qDragMoveEvent_nf (x1, x2, x3, x4, x5, x6)
= withObjectRefResult $
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragMoveEvent4 cpoint_x1_x cpoint_x1_y (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5) (toCLong $ qEnum_toInt x6)
instance Qaccept (QDragMoveEvent a) (()) where
accept x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDragMoveEvent_accept cobj_x0
foreign import ccall "qtc_QDragMoveEvent_accept" qtc_QDragMoveEvent_accept :: Ptr (TQDragMoveEvent a) -> IO ()
qaccept :: QDragMoveEvent a -> ((QRect t1)) -> IO ()
qaccept x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDragMoveEvent_accept1 cobj_x0 cobj_x1
foreign import ccall "qtc_QDragMoveEvent_accept1" qtc_QDragMoveEvent_accept1 :: Ptr (TQDragMoveEvent a) -> Ptr (TQRect t1) -> IO ()
instance Qaccept (QDragMoveEvent a) ((Rect)) where
accept x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QDragMoveEvent_accept1_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QDragMoveEvent_accept1_qth" qtc_QDragMoveEvent_accept1_qth :: Ptr (TQDragMoveEvent a) -> CInt -> CInt -> CInt -> CInt -> IO ()
qanswerRect :: QDragMoveEvent a -> (()) -> IO (QRect ())
qanswerRect x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDragMoveEvent_answerRect cobj_x0
foreign import ccall "qtc_QDragMoveEvent_answerRect" qtc_QDragMoveEvent_answerRect :: Ptr (TQDragMoveEvent a) -> IO (Ptr (TQRect ()))
answerRect :: QDragMoveEvent a -> (()) -> IO (Rect)
answerRect x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDragMoveEvent_answerRect_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QDragMoveEvent_answerRect_qth" qtc_QDragMoveEvent_answerRect_qth :: Ptr (TQDragMoveEvent a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance Qignore (QDragMoveEvent a) (()) where
ignore x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDragMoveEvent_ignore cobj_x0
foreign import ccall "qtc_QDragMoveEvent_ignore" qtc_QDragMoveEvent_ignore :: Ptr (TQDragMoveEvent a) -> IO ()
qignore :: QDragMoveEvent a -> ((QRect t1)) -> IO ()
qignore x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDragMoveEvent_ignore1 cobj_x0 cobj_x1
foreign import ccall "qtc_QDragMoveEvent_ignore1" qtc_QDragMoveEvent_ignore1 :: Ptr (TQDragMoveEvent a) -> Ptr (TQRect t1) -> IO ()
instance Qignore (QDragMoveEvent a) ((Rect)) where
ignore x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QDragMoveEvent_ignore1_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QDragMoveEvent_ignore1_qth" qtc_QDragMoveEvent_ignore1_qth :: Ptr (TQDragMoveEvent a) -> CInt -> CInt -> CInt -> CInt -> IO ()
qDragMoveEvent_delete :: QDragMoveEvent a -> IO ()
qDragMoveEvent_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDragMoveEvent_delete cobj_x0
foreign import ccall "qtc_QDragMoveEvent_delete" qtc_QDragMoveEvent_delete :: Ptr (TQDragMoveEvent a) -> IO ()
| keera-studios/hsQt | Qtc/Gui/QDragMoveEvent.hs | bsd-2-clause | 8,638 | 0 | 18 | 1,349 | 2,656 | 1,387 | 1,269 | -1 | -1 |
{-| Converts a configuration state into a Ssconf map.
As TemplateHaskell require that splices be defined in a separate
module, we combine all the TemplateHaskell functionality that HTools
needs in this module (except the one for unittests).
-}
{-
Copyright (C) 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.WConfd.Ssconf
( SSConf(..)
, emptySSConf
, mkSSConf
) where
import Control.Arrow ((&&&), (***), first)
import qualified Data.ByteString.UTF8 as UTF8
import Data.Foldable (Foldable(..), toList)
import Data.List (partition)
import Data.Maybe (mapMaybe)
import qualified Data.Map as M
import qualified Text.JSON as J
import Ganeti.BasicTypes
import Ganeti.Config
import Ganeti.Constants
import Ganeti.JSON
import Ganeti.Objects
import Ganeti.Ssconf
import Ganeti.Utils
import Ganeti.Types
eqPair :: (String, String) -> String
eqPair (x, y) = x ++ "=" ++ y
mkSSConfHvparams :: Cluster -> [(Hypervisor, [String])]
mkSSConfHvparams cluster = map (id &&& hvparams) [minBound..maxBound]
where
hvparams :: Hypervisor -> [String]
hvparams h = maybe [] hvparamsStrings
$ lookupContainer Nothing h (clusterHvparams cluster)
-- | Convert a collection of hypervisor parameters to strings in the form
-- @key=value@.
hvparamsStrings :: HvParams -> [String]
hvparamsStrings =
map (eqPair . (UTF8.toString *** hvparamShow)) . M.toList . fromContainer
-- | Convert a hypervisor parameter in its JSON representation to a String.
-- Strings, numbers and booleans are just printed (without quotes), booleans
-- printed as @True@/@False@ and other JSON values (should they exist) as
-- their JSON representations.
hvparamShow :: J.JSValue -> String
hvparamShow (J.JSString s) = J.fromJSString s
hvparamShow (J.JSRational _ r) = J.showJSRational r []
hvparamShow (J.JSBool b) = show b
hvparamShow x = J.encode x
mkSSConf :: ConfigData -> SSConf
mkSSConf cdata = SSConf . M.fromList $
[ (SSClusterName, return $ clusterClusterName cluster)
, (SSClusterTags, toList $ tagsOf cluster)
, (SSFileStorageDir, return $ clusterFileStorageDir cluster)
, (SSSharedFileStorageDir, return $ clusterSharedFileStorageDir cluster)
, (SSGlusterStorageDir, return $ clusterGlusterStorageDir cluster)
, (SSMasterCandidates, mapLines nodeName mcs)
, (SSMasterCandidatesIps, mapLines nodePrimaryIp mcs)
, (SSMasterCandidatesCerts, mapLines eqPair . toPairs
. clusterCandidateCerts $ cluster)
, (SSMasterIp, return $ clusterMasterIp cluster)
, (SSMasterNetdev, return $ clusterMasterNetdev cluster)
, (SSMasterNetmask, return . show $ clusterMasterNetmask cluster)
, (SSMasterNode, return
. genericResult (const "NO MASTER") nodeName
. getNode cdata $ clusterMasterNode cluster)
, (SSNodeList, mapLines nodeName nodes)
, (SSNodePrimaryIps, mapLines (spcPair . (nodeName &&& nodePrimaryIp))
nodes )
, (SSNodeSecondaryIps, mapLines (spcPair . (nodeName &&& nodeSecondaryIp))
nodes )
, (SSNodeVmCapable, mapLines (eqPair . (nodeName &&& show . nodeVmCapable))
nodes)
, (SSOfflineNodes, mapLines nodeName offline )
, (SSOnlineNodes, mapLines nodeName online )
, (SSPrimaryIpFamily, return . show . ipFamilyToRaw
. clusterPrimaryIpFamily $ cluster)
, (SSInstanceList, niceSort . mapMaybe instName
. toList . configInstances $ cdata)
, (SSReleaseVersion, return releaseVersion)
, (SSHypervisorList, mapLines hypervisorToRaw
. clusterEnabledHypervisors $ cluster)
, (SSMaintainNodeHealth, return . show . clusterMaintainNodeHealth
$ cluster)
, (SSUidPool, mapLines formatUidRange . clusterUidPool $ cluster)
, (SSNodegroups, mapLines (spcPair . (uuidOf &&& groupName))
nodeGroups)
, (SSNetworks, mapLines (spcPair . (uuidOf
&&& (fromNonEmpty . networkName)))
. configNetworks $ cdata)
, (SSEnabledUserShutdown, return . show . clusterEnabledUserShutdown
$ cluster)
, (SSSshPorts, mapLines (eqPair . (nodeName
&&& getSshPort cdata)) nodes)
] ++
map (first hvparamsSSKey) (mkSSConfHvparams cluster)
where
mapLines :: (Foldable f) => (a -> String) -> f a -> [String]
mapLines f = map f . toList
spcPair (x, y) = x ++ " " ++ y
toPairs = M.assocs . M.mapKeys UTF8.toString . fromContainer
cluster = configCluster cdata
mcs = getMasterOrCandidates cdata
nodes = niceSortKey nodeName . toList $ configNodes cdata
(offline, online) = partition nodeOffline nodes
nodeGroups = niceSortKey groupName . toList $ configNodegroups cdata
-- This will return the empty string only for the situation where the
-- configuration is corrupted and no nodegroup can be found for that node.
getSshPort :: ConfigData -> Node -> String
getSshPort cfg node = maybe "" (show . ndpSshPort)
$ getNodeNdParams cfg node
| leshchevds/ganeti | src/Ganeti/WConfd/Ssconf.hs | bsd-2-clause | 6,530 | 0 | 17 | 1,544 | 1,278 | 709 | 569 | -1 | -1 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, OverloadedStrings, TypeSynonymInstances #-}
{-# LANGUAGE ImpredicativeTypes #-}
{-
Forth target code generator for MSP430.
Code generation is done by instantiating the Primitive type class which results
from a cross compilation.
-}
module Language.Forth.Target.MSP430 (bindMSP430, codeGenerateMSP430) where
import Control.Lens
import qualified Data.ByteString.Char8 as C
import Data.Bits
import Data.Int
import Data.Monoid
import Data.ByteString.Lazy (ByteString)
import Data.IntMap (IntMap)
import qualified Data.Set as Set
import Language.Forth.CellVal
import Language.Forth.CrossCompiler.CodeGenerate
import Language.Forth.Dictionary
import Language.Forth.Primitive
import Language.Forth.TargetPrimitive
import Language.Forth.Word
import Translator.Assembler.Generate
import Translator.Assembler.Target.MSP430
import Translator.Expression
import Translator.Symbol
-- | Bind a polymorphic target dictionary to be an MSP430 specific one
bindMSP430 :: (Dictionary (IM Instr430), IntMap (ForthWord (IM Instr430))) ->
(Dictionary (IM Instr430), IntMap (ForthWord (IM Instr430)))
bindMSP430 = id
-- Forth machine registers
tos = RegOp R4 -- top of stack, cached in register
w = RegOp R5
stack = RegOp R6
ip = RegOp R7
sp = RegOp SP
-- Helpers to unwrap Forth machine registers when used in other addressing modes
indirect (RegOp reg) = Indirect reg
indirectInc (RegOp reg) = IndirectInc reg
-- Helpers to wrap instructions in an insRec
add = binary ADD
and_ = binary AND
bis = binary BIS
call = insRec . CALL
clrc = insRec CLRC
dec = unary DEC
decd = unary DECD
inc = unary INC
incd = unary INCD
inv = unary INV
jc = insRec . JC
jnc = insRec . JNC
jz = insRec . JZ
jmp = insRec . JMP
mov = binary MOV
pop = unary POP
push = unary PUSH
rla = unary RLA
rra = unary RRA
rrc = unary RRC
sub = binary SUB
subc = binary SUBC
tst = unary TST
xor_ = binary XOR
binary ctor s op1 op2 = insRec $ ctor s op1 op2
unary ctor s op = insRec $ ctor s op
label = labRec . mkSymbol
-- | Primitive words for MSP430.
instance Primitive (IM Instr430) where
exit = pop W ip
execute = mov W tos ip <>
popStack tos
swap = mov W tos w <>
mov W (indirect stack) tos <>
mov W w (indirect stack)
drop = popStack tos
dup = pushStack tos
over = mov W (indirect stack) w <>
pushStack tos <>
mov W w tos
rto = pushStack tos <>
pop W tos
tor = push W tos <>
popStack tos
rfetch = pushStack tos <>
mov W (indirect sp) tos
fetch = mov W (indirect tos) tos
cfetch = mov B (indirect tos) tos
store = mov W (indirectInc stack) w <>
mov W w (indirect tos) <>
popStack tos
cstore = mov W (indirectInc stack) w <>
mov B w (indirect tos) <>
popStack tos
plus = add W (indirectInc stack) tos
minus = sub W (indirectInc stack) tos <>
inv W tos <>
inc W tos
and = and_ W (indirectInc stack) tos
or = bis W (indirectInc stack) tos
xor = xor_ W (indirectInc stack) tos
twoStar = rla W tos
twoSlash = rra W tos
lshift = multiShift 'l' rla
rshift = multiShift 'r' (\s r -> clrc <> rrc s r)
zerop = sub W (Imm 1) tos <>
subc W tos tos
lt0 = rla W tos <>
subc W tos tos
constant = pushStack tos <>
mov W (indirect w) tos
umstar = mov W (indirect stack) (Absolute (Identifier "MPY")) <>
mov W tos (Absolute (Identifier "OP2")) <>
mov W (Absolute (Identifier "RESLO")) (indirect stack) <>
mov W (Absolute (Identifier "RESHI")) tos
ummod = mempty -- TBD
colonToken tok = insRec $ Directive $ WORD [tok]
instance TargetPrimitive Instr430 where
cellValue e = insRec $ Directive $ LONG [e]
wordToken (TargetToken _ sym) = colonToken (Identifier sym)
literal val = colonToken (Identifier litSymbol) <> colonToken val
labelOffset sym = colonToken $ Identifier sym - locationCounter
docol = call (Imm (Identifier docolSymbol))
doconst e = call (Imm (Identifier doconstSymbol)) <>
colonToken e
dohere dict tt = (does tt, does)
where does (TargetToken _ _) =
call (Imm (Identifier dohereSymbol)) <>
insRec (Directive $ WORD [Identifier ramBaseSymbol + dict^.tdict.hereRAM])
next = jmp (Imm (Identifier nextSymbol))
lit = pushStack tos <>
mov W (indirectInc ip) tos
docolImpl = mempty -- TBD
doconstImpl = mempty -- TBD
hereImpl = mempty -- TBD
nextImpl = mempty -- TBD
resetRStack = mempty -- TBD
resetStack = mempty -- TBD
-- reservedLabels _ = Set.fromList [mkSymbol (p:b) | p <- ['l', 'r'], b <- [shiftloop, shiftskip]]
-- Helper function for implementing LSHIFT and RSHIFT
multiShift t shift =
popStack w <>
tst W tos <>
jz skip <>
label loop <>
shift W w <>
label skip <>
dec W tos <>
jnc loop <>
mov W w tos
where loop = t : shiftloop
skip = t : shiftskip
shiftloop = "shiftloop"
shiftskip = "shiftskip"
-- Pop data stack to given register
popStack r = mov W (indirectInc stack) r
-- Push given register to data stack. Pushing 'tos' effectively makes room
-- for pushing a new value on the stack (by moving it to 'tos').
-- MSP430 cannot predecrement, so used 'decd' to adjust data stack pointer.
pushStack r = decd W stack <>
mov W r (indirect stack)
-- | Generate code for a dictionary for MSP430
-- codeGenerateMSP430 :: (forall t. Dictionary (IM t)) -> ByteString
codeGenerateMSP430 (dict, allwords) =
emitCode $ codeGenerate Directive pad2 (bindMSP430 (dict, allwords))
| hth313/hthforth | src/Language/Forth/Target/MSP430.hs | bsd-2-clause | 5,836 | 0 | 16 | 1,558 | 1,757 | 902 | 855 | -1 | -1 |
{-# LANGUAGE TypeOperators, DeriveDataTypeable, FlexibleInstances #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Paskell.Expr where
import Data.Generics
import Data.List
import Control.Monad
import Control.Monad.State.Lazy
import Control.Monad.Error
import Data.IORef
data EvalS = ES {
values :: [(String, IORef V)],
decls :: [D]
}
--newtype EvalM a = EvalM { unEvalM :: EvalS -> Either String (IO (a, EvalS)) }
type EvalM = StateT EvalS (ErrorT String IO)
type FailIO = ErrorT String IO
data D = DLet Pat E
| DMkType String [String] [(String, [T])]
| DDecTy [String] T
| DImport String
deriving (Show, Eq, Read)
data V = VReal Double
| VInt Int
-- | VSeed Seed
| VLam ([V]->FailIO V)
| VString String
| VCons String [V]
| VRec [(String,V)]
| VSig E
deriving (Show, Eq, Read)
data T = TLam [T] T
| TApp T T
| TCon String
| TVar String
| TRec [(String,T)]
deriving (Show, Eq, Read, Data, Typeable)
data E = ECon V
| EApp E [E]
| EAssign Pat E
| ELam [Pat] [E]
| EVar String
| ECase E [(Pat, [E])]
| ETy T E
| EIf E [E] [E]
deriving (Show, Eq, Read)
data Pat = PLit V
| PWild
| PVar String
| PCons String [Pat]
-- | PBang Pat
| PTy T Pat
-- | PWithRec
deriving (Show, Eq, Read)
instance Show ([V]->FailIO V) where
show f = "<function>"
instance Read ([V]->FailIO V) where
readsPrec _ s = error $ "read: <function>" ++s
instance Eq ([V]->FailIO V) where
f == g = error "eq: <function>"
flatP e@(PVar nm) = [e]
flatP PWild = []
flatP (PTy _ p) = flatP p
qmap :: (Data a, Typeable b) => (b -> b) -> a -> a
qmap f = everywhere (mkT f)
--qcatMap :: (Data a, Typeable b) => (b -> [b]) -> a -> a
--qcatMap f = everywhere (mkT f)
qquery :: (Data a1, Typeable b) => (b -> [a]) -> a1 -> [a]
qquery qf = everything (++) ([] `mkQ` qf)
flat :: (Data a) => a -> [a]
flat = qquery (:[])
| glutamate/paskell | Paskell/Expr.hs | bsd-3-clause | 2,115 | 0 | 11 | 676 | 782 | 444 | 338 | 63 | 1 |
{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE FlexibleContexts #-}
module Network.Xmpp.Tls where
import Control.Applicative ((<$>))
import qualified Control.Exception.Lifted as Ex
import Control.Monad
import Control.Monad.Error
import Control.Monad.State.Strict
import "crypto-random" Crypto.Random
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC8
import qualified Data.ByteString.Lazy as BL
import Data.Conduit
import Data.IORef
import Data.Monoid
import Data.XML.Types
import Network.DNS.Resolver (ResolvConf)
import Network.TLS
import Network.Xmpp.Stream
import Network.Xmpp.Types
import System.Log.Logger (debugM, errorM, infoM)
import System.X509
mkBackend :: StreamHandle -> Backend
mkBackend con = Backend { backendSend = \bs -> void (streamSend con bs)
, backendRecv = bufferReceive (streamReceive con)
, backendFlush = streamFlush con
, backendClose = streamClose con
}
where
bufferReceive _ 0 = return BS.empty
bufferReceive recv n = BS.concat `liftM` (go n)
where
go m = do
mbBs <- recv m
bs <- case mbBs of
Left e -> Ex.throwIO e
Right r -> return r
case BS.length bs of
0 -> return []
l -> if l < m
then (bs :) `liftM` go (m - l)
else return [bs]
starttlsE :: Element
starttlsE = Element "{urn:ietf:params:xml:ns:xmpp-tls}starttls" [] []
-- | Checks for TLS support and run starttls procedure if applicable
tls :: Stream -> IO (Either XmppFailure ())
tls con = fmap join -- We can have Left values both from exceptions and the
-- error monad. Join unifies them into one error layer
. wrapExceptions
. flip withStream con
. runErrorT $ do
conf <- gets streamConfiguration
sState <- gets streamConnectionState
case sState of
Plain -> return ()
Closed -> do
liftIO $ errorM "Pontarius.Xmpp.Tls" "The stream is closed."
throwError XmppNoStream
Finished -> do
liftIO $ errorM "Pontarius.Xmpp.Tls" "The stream is finished."
throwError XmppNoStream
Secured -> do
liftIO $ errorM "Pontarius.Xmpp.Tls" "The stream is already secured."
throwError TlsStreamSecured
features <- lift $ gets streamFeatures
case (tlsBehaviour conf, streamFeaturesTls features) of
(RequireTls , Just _ ) -> startTls
(RequireTls , Nothing ) -> throwError TlsNoServerSupport
(PreferTls , Just _ ) -> startTls
(PreferTls , Nothing ) -> skipTls
(PreferPlain , Just True) -> startTls
(PreferPlain , _ ) -> skipTls
(RefuseTls , Just True) -> throwError XmppOtherFailure
(RefuseTls , _ ) -> skipTls
where
skipTls = liftIO $ infoM "Pontarius.Xmpp.Tls" "Skipping TLS negotiation"
startTls = do
liftIO $ infoM "Pontarius.Xmpp.Tls" "Running StartTLS"
params <- gets $ tlsParams . streamConfiguration
ErrorT $ pushElement starttlsE
answer <- lift $ pullElement
case answer of
Left e -> throwError e
Right (Element "{urn:ietf:params:xml:ns:xmpp-tls}proceed" [] []) ->
return ()
Right (Element "{urn:ietf:params:xml:ns:xmpp-tls}failure" _ _) -> do
liftIO $ errorM "Pontarius.Xmpp" "startTls: TLS initiation failed."
throwError XmppOtherFailure
Right r ->
liftIO $ errorM "Pontarius.Xmpp.Tls" $
"Unexpected element: " ++ show r
hand <- gets streamHandle
(_raw, _snk, psh, recv, ctx) <- lift $ tlsinit params (mkBackend hand)
let newHand = StreamHandle { streamSend = catchPush . psh
, streamReceive = wrapExceptions . recv
, streamFlush = contextFlush ctx
, streamClose = bye ctx >> streamClose hand
}
lift $ modify ( \x -> x {streamHandle = newHand})
liftIO $ infoM "Pontarius.Xmpp.Tls" "Stream Secured."
either (lift . Ex.throwIO) return =<< lift restartStream
modify (\s -> s{streamConnectionState = Secured})
return ()
client :: MonadIO m => ClientParams -> Backend -> m Context
client params backend = contextNew backend params
tlsinit :: (MonadIO m, MonadIO m1) =>
ClientParams
-> Backend
-> m ( Source m1 BS.ByteString
, Sink BS.ByteString m1 ()
, BS.ByteString -> IO ()
, Int -> m1 BS.ByteString
, Context
)
tlsinit params backend = do
liftIO $ debugM "Pontarius.Xmpp.Tls" "TLS with debug mode enabled."
-- gen <- liftIO (cprgCreate <$> createEntropyPool :: IO SystemRNG)
sysCStore <- liftIO getSystemCertificateStore
let params' = params{clientShared =
(clientShared params){ sharedCAStore =
sysCStore <> sharedCAStore (clientShared params)}}
con <- client params' backend
handshake con
let src = forever $ do
dt <- liftIO $ recvData con
liftIO $ debugM "Pontarius.Xmpp.Tls" ("In :" ++ BSC8.unpack dt)
yield dt
let snk = do
d <- await
case d of
Nothing -> return ()
Just x -> do
sendData con (BL.fromChunks [x])
snk
readWithBuffer <- liftIO $ mkReadBuffer (recvData con)
return ( src
, snk
-- Note: sendData already sends the data to the debug output
, \s -> sendData con $ BL.fromChunks [s]
, liftIO . readWithBuffer
, con
)
mkReadBuffer :: IO BS.ByteString -> IO (Int -> IO BS.ByteString)
mkReadBuffer recv = do
buffer <- newIORef BS.empty
let read' n = do
nc <- readIORef buffer
bs <- if BS.null nc then recv
else return nc
let (result, rest) = BS.splitAt n bs
writeIORef buffer rest
return result
return read'
-- | Connect to an XMPP server and secure the connection with TLS before
-- starting the XMPP streams
--
-- /NB/ RFC 6120 does not specify this method, but some servers, notably GCS,
-- seem to use it.
connectTls :: ResolvConf -- ^ Resolv conf to use (try 'defaultResolvConf' as a
-- default)
-> ClientParams -- ^ TLS parameters to use when securing the connection
-> String -- ^ Host to use when connecting (will be resolved
-- using SRV records)
-> ErrorT XmppFailure IO StreamHandle
connectTls config params host = do
h <- connectSrv config host >>= \h' -> case h' of
Nothing -> throwError TcpConnectionFailure
Just h'' -> return h''
let hand = handleToStreamHandle h
let params' = params{clientServerIdentification
= case clientServerIdentification params of
("", _) -> (host, "")
csi -> csi
}
(_raw, _snk, psh, recv, ctx) <- tlsinit params' $ mkBackend hand
return StreamHandle{ streamSend = catchPush . psh
, streamReceive = wrapExceptions . recv
, streamFlush = contextFlush ctx
, streamClose = bye ctx >> streamClose hand
}
wrapExceptions :: IO a -> IO (Either XmppFailure a)
wrapExceptions f = Ex.catches (liftM Right $ f)
[ Ex.Handler $ return . Left . XmppIOException
, Ex.Handler $ wrap . XmppTlsError
, Ex.Handler $ wrap . XmppTlsException
, Ex.Handler $ return . Left
]
where
wrap = return . Left . TlsError
| Philonous/pontarius-xmpp | source/Network/Xmpp/Tls.hs | bsd-3-clause | 8,390 | 2 | 21 | 3,027 | 2,002 | 1,011 | 991 | 170 | 14 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
module Duckling.Dimensions.UK
( allDimensions
) where
import Duckling.Dimensions.Types
allDimensions :: [Some Dimension]
allDimensions =
[ This Numeral
, This Ordinal
]
| rfranek/duckling | Duckling/Dimensions/UK.hs | bsd-3-clause | 484 | 0 | 6 | 88 | 52 | 33 | 19 | 7 | 1 |
{-# LANGUAGE QuasiQuotes #-}
import DBus.QuasiQuoter
import DBus
import Data.Int
import qualified Data.Map as Map
import Data.Maybe
import Data.Word
import Test.QuickCheck
import Text.Printf
main :: IO ()
main = mapM_ (\(s,a) -> printf "%-25s: " s >> a) tests
prop_simple x y = show (x + y) == [dbus| i i -> s |] f x y
where
f :: [Variant] -> [Variant]
f xs = [toVariant . show . sum $ (map (fromJust . fromVariant) xs :: [Int32])]
prop_nospaces x y = show (x + y) == [dbus|ii->s|] f x y
where
f :: [Variant] -> [Variant]
f xs = [toVariant . show . sum $ (map (fromJust . fromVariant) xs :: [Int32])]
prop_spaces x y = show (x + y) == [dbus| ii-> s |] f x y
where
f :: [Variant] -> [Variant]
f xs = [toVariant . show . sum $ (map (fromJust . fromVariant) xs :: [Int32])]
prop_functor x y = Just (show (x + y)) == [dbusF| i i -> s |] f x y
where
f :: [Variant] -> Maybe [Variant]
f xs = Just [toVariant . show . sum $ (map (fromJust . fromVariant) xs :: [Int32])]
prop_maps = Map.empty == [dbus| a{su} -> a{on} |] f Map.empty
where
f :: [Variant] -> [Variant]
f _ = [toVariant (Map.empty :: Map.Map ObjectPath Int16)]
prop_tuples x y = show x ++ y == [dbus| (is) -> s |] f (x, y)
where
f :: [Variant] -> [Variant]
f [x] =
let (n, s) = fromJust (fromVariant x) :: (Int32, String)
in [toVariant $ show n ++ s]
prop_retvals x = (x, x) == [dbus| i -> ii |] f x
where
f :: [Variant] -> [Variant]
f [x] = [x, x]
prop_values x = x * 2 == [dbus| -> i |] f
where
f :: [Variant] -> [Variant]
f _ = [toVariant (x * 2)]
prop_unit x = () == [dbus| s -> |] f x
where
f :: [Variant] -> [Variant]
f _ = []
tests = [("simple", quickCheck prop_simple)
,("functor", quickCheck prop_functor)
,("maps", quickCheck prop_maps)
,("tuples", quickCheck prop_tuples)
,("retvals", quickCheck prop_retvals)
,("values", quickCheck prop_values)
,("unit", quickCheck prop_unit)
,("no spaces", quickCheck prop_nospaces)
,("spaces", quickCheck prop_spaces)]
| pcapriotti/dbus-qq | tests/Tests.hs | bsd-3-clause | 2,113 | 0 | 13 | 554 | 949 | 531 | 418 | 49 | 1 |
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Fling where
import Control.Arrow (second, (&&&))
import Data.List (sort, groupBy)
import Data.Function (on)
import Data.Tree (Tree(..), Forest, drawForest)
-- Example puzzles
example0 :: Game
example0 = mkGame [[1,4],[1,5],[2,1],[2,5],[5,5],[7,2]]
example1 :: Game
example1 = mkGame [[0,0],[1,2],[2,0],[3,1],[6,3],[7,1]]
example2 :: Game
example2 = mkGame [[1,4],[6,4],[7,4]]
puzzle9_1 :: Game
puzzle9_1 = mkGame [[0,0],[0,2],[1,6],[2,6],[4,1],[5,2],[6,5],[7,3]]
-- Some types
type Point = [Int]
type X = Int
type Y = [Int] -- Dimensions other than X, needs a better name.
newtype Furball = Furball { unFurball :: Point }
deriving Eq
type Row = [X]
type Game = [Furball]
data Move = Move Furball Dir
deriving (Eq, Show)
newtype Dir = Dir { unDir :: Point }
deriving (Eq)
instance Show Furball where
show (Furball pt) = show pt
instance Show Dir where
show (Dir [ 0, -1]) = "North"
show (Dir [ 1, 0]) = "East"
show (Dir [ 0, 1]) = "South"
show (Dir [-1, 0]) = "West"
show (Dir [ 1, 0, 0]) = "Right"
show (Dir [-1, 0, 0]) = "Left"
show (Dir [ 0, 1, 0]) = "Up"
show (Dir [ 0, -1, 0]) = "Down"
show (Dir [ 0, 0, 1]) = "Forwards"
show (Dir [ 0, 0, -1]) = "Backwards"
show (Dir vec) = show vec
-- Transforming stuff
type Transformation = Point -> Point
class Transform a where
transform :: Transformation -> a -> a
instance Transform Furball where
transform xf = Furball . xf . unFurball
instance Transform Dir where
transform xf = Dir . xf . unDir
instance Transform a => Transform [a] where
transform xf = map (transform xf)
instance Transform Move where
transform xf (Move pt dir) = Move (transform xf pt) (transform xf dir)
instance (Transform a, Transform b) => Transform (a, b) where
transform xf (a, b) = (transform xf a, transform xf b)
transformations :: Int -> [(Transformation, Transformation)]
transformations n = zip
[ mx . md | mx <- [id, mirrorX], md <- take n $ iterate ( mirrorDiag .) id]
[ md . mx | mx <- [id, mirrorX], md <- take n $ iterate (revMirrorDiag .) id]
mirrorX :: Point -> Point
mirrorX [] = []
mirrorX (x:dims) = -x:dims
mirrorDiag :: Point -> Point
mirrorDiag [] = []
mirrorDiag (x:dims) = dims ++ [x]
revMirrorDiag :: Point -> Point
revMirrorDiag [] = []
revMirrorDiag dims = last dims : init dims
-- Top-level API
-- | Print a neat forest of winning strategies.
printSolutions :: Game -> IO ()
printSolutions = putStr . drawForest . (fmap . fmap) show . solutions . search
-- | Prune a game tree to only keep the winning paths.
solutions :: Forest (Move, Game) -> Forest (Move, Game)
solutions = concatMap f
where
-- One furball left: we have a winning position.
f n@(Node (_, [_]) []) = [n]
-- Multiple furballs left: recurse.
f (Node mg cs) =
case solutions cs of
[] -> []
cs' -> [Node mg cs']
-- | Build move tree from a starting position.
search :: Game -> Forest (Move, Game)
search = map (\(m, g') -> Node (m, g') (search g')) . moves
-- | Make a game from a list of coordinates.
mkGame :: [Point] -> Game
mkGame = map Furball
-- Generating moves
-- | Noemt gegeven een state alle mogelijke zetten in die state, elk gekoppeld
-- met de bijbehorende nieuwe state.
moves :: Game -> [(Move, Game)]
moves g = concatMap f (transformations n)
where
n = length . unFurball . head $ g
f xf = transform (snd xf)
. (map . second) fromRows
. shifts
. toRows
. transform (fst xf)
$ g
groupOn :: Eq b => (a -> b) -> [a] -> [[a]]
groupOn f = groupBy ((==) `on` f)
toRows :: Game -> [(Y, Row)]
toRows = map (\row -> (fst (head row), map snd row)) . groupOn fst . sort . map ((tail &&& head) . unFurball)
fromRows :: [(Y, Row)] -> Game
fromRows = concatMap (\(y, row) -> map (Furball . (:y)) row)
-- | Probeert voor alle rijen alle bolletjes naar rechts te rollen.
shifts :: [(Y, Row)] -> [(Move, [(Y, Row)])]
shifts [] = []
shifts ((y, row) : yrows) =
map (\(x, r) -> (mkMove x y, (y, r) : yrows)) (shift row) ++
map (second ((y, row) :)) (shifts yrows)
where
mkMove x dims = Move (Furball $ x : dims) (Dir $ 1 : replicate (length dims) 0)
-- | Probeert voor 1 rij alle balletjes naar rechts te rollen (per balletje shift1).
shift :: Row -> [(X, Row)]
shift [] = []
shift [x,y] | x + 2 == y && y <= 0 = []
shift (x : xs) = maybe id (:) (shift1 (x : xs)) ((fmap . second) (x :) (shift xs))
-- | Probeert voor 1 rij het eerste balletje naar rechts te rollen.
shift1 :: Row -> Maybe (X, Row)
shift1 (x : y : [])
| x + 1 == y = Nothing
| otherwise = Just (x, [pred y])
shift1 (x : y : zs) = Just (x, map pred (y : zs))
shift1 _ = Nothing
| MedeaMelana/FlingSolver | Fling.hs | bsd-3-clause | 4,844 | 0 | 14 | 1,139 | 2,195 | 1,227 | 968 | 111 | 3 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-|
Module : Numeric.AERN.Poly.IntPoly.Evaluation
Description : evaluation of interval polynomials
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable
Evaluation of interval polynomials in general using its instance of 'CanEvaluateOtherType'
and specilised cases for evaluation at a point and on an interval.
-}
module Numeric.AERN.Poly.IntPoly.Evaluation
(
PolyEvalOps(..),
PolyEvalMonoOps(..)
-- ,
-- evalPolyAtPointOut,
-- evalPolyAtPointIn,
-- evalPolyOnIntervalOut,
-- evalPolyOnIntervalIn
)
where
import Numeric.AERN.Poly.IntPoly.Config
import Numeric.AERN.Poly.IntPoly.IntPoly
import Numeric.AERN.Poly.IntPoly.New ()
import Numeric.AERN.Poly.IntPoly.Show ()
import Numeric.AERN.Poly.IntPoly.Differentiation
import Numeric.AERN.RmToRn.Domain
import Numeric.AERN.RmToRn.Evaluation
import qualified Numeric.AERN.RealArithmetic.RefinementOrderRounding as ArithInOut
import qualified Numeric.AERN.RealArithmetic.NumericOrderRounding as ArithUpDn
--import Numeric.AERN.RealArithmetic.NumericOrderRounding (ConvertEffortIndicator) -- needed for ghc 6.12
import Numeric.AERN.RealArithmetic.ExactOps
import Numeric.AERN.RealArithmetic.Measures
import qualified Numeric.AERN.RefinementOrder as RefOrd
import qualified Numeric.AERN.NumericOrder as NumOrd
import Numeric.AERN.Basics.SizeLimits
import Numeric.AERN.Basics.Consistency
import Numeric.AERN.Basics.Effort
import qualified Data.IntMap as IntMap
--import qualified Data.Map as Map
import Data.List (sortBy)
import Numeric.AERN.Misc.Debug
_ = unsafePrint
instance
(Ord var, Show var, Show cf, Show (SizeLimits cf),
ArithInOut.RoundedReal cf,
RefOrd.IntervalLike cf,
HasConsistency cf)
=>
CanEvaluateOtherType (IntPoly var cf)
where
type EvalOps (IntPoly var cf) = PolyEvalOps var cf
evalOtherType ops valsMap p@(IntPoly cfg _) =
case polyEvalMonoOps ops of
Nothing -> evalDirect valsLZ p
_ -> evalPolyMono evalDirect ops valsLZ p
where
evalDirect = evalPolyDirect ops
valsLZ = valsMapToValuesLZ subtrCf cfg valsMap
subtrCf val domLE =
addV val (cfV $ neg domLE)
addV = polyEvalAdd ops
cfV = polyEvalCoeff ops
instance
(Ord var, Show var, Show cf, Show (SizeLimits cf),
ArithInOut.RoundedReal cf,
RefOrd.IntervalLike cf,
HasAntiConsistency cf)
=>
CanEvaluateOtherTypeInner (IntPoly var cf)
where
evalOtherTypeInner ops valsMap p@(IntPoly cfg _) =
case polyEvalMonoOps ops of
Nothing -> evalDirect valsLZ p
_ -> evalPolyMono evalDirect ops valsLZ p
where
evalDirect vals p2 =
flipConsistency $
evalPolyDirect ops vals $
flipConsistencyPoly p2
valsLZ = valsMapToValuesLZ subtrCf cfg valsMap
subtrCf val domLE =
addV val (cfV $ neg domLE)
addV = polyEvalAdd ops
cfV = polyEvalCoeff ops
valsMapToValuesLZ ::
(Ord var, Show var, Show t)
=>
(t -> cf -> t) ->
IntPolyCfg var cf ->
(VarBox (IntPoly var cf) t) ->
[t]
valsMapToValuesLZ subtractCf cfg valsMap =
zipWith subtractCf vals domsLE
where
vals = map getValue vars
vars = ipolycfg_vars cfg
domsLE = ipolycfg_domsLE cfg
getValue var =
case lookupVar valsMap var of
Just val -> val
_ -> error $
"aern-poly internal error in Evaluation...valsMapToValuesLZ:"
++ "\n var " ++ show var ++ " not present in valsMap"
++ "\n valsMap = " ++ show valsMap
instance
(Ord var, Show var, Show cf, Show (SizeLimits cf),
ArithInOut.RoundedReal cf,
HasAntiConsistency cf,
RefOrd.IntervalLike cf)
=>
CanEvaluate (IntPoly var cf)
where
type (EvaluationEffortIndicator (IntPoly var cf)) =
IntPolyEffort cf
evaluationDefaultEffort (IntPoly cfg _) =
ipolycfg_effort cfg
evalAtPointOutEff eff valsMap p@(IntPoly cfg _)
| valuesAreExact valsLZ =
evalPolyAtPointOut effCf maxSplitSize valsLZ p
| otherwise =
evalPolyOnIntervalOut effCf maxSplitSize valsLZ p
where
valsLZ = valsMapToValuesLZ (<->) cfg valsMap
(<->) = ArithInOut.subtrOutEff effAdd
effAdd = ArithInOut.fldEffortAdd sampleCf $ ArithInOut.rrEffortField sampleCf effCf
maxSplitSize = ipolyeff_evalMaxSplitSize eff
effCf = ipolyeff_cfRoundedRealEffort eff
sampleCf = ipolycfg_sample_cf cfg
evalAtPointInEff eff valsMap p@(IntPoly cfg _)
| valuesAreExact valsLZ =
evalPolyAtPointIn effCf maxSplitSize valsLZ p
| otherwise =
evalPolyOnIntervalIn effCf maxSplitSize valsLZ p
where
valsLZ = valsMapToValuesLZ (>-<) cfg valsMap
(>-<) = ArithInOut.subtrInEff effAdd
effAdd = ArithInOut.fldEffortAdd sampleCf $ ArithInOut.rrEffortField sampleCf effCf
maxSplitSize = ipolyeff_evalMaxSplitSize eff
effCf = ipolyeff_cfRoundedRealEffort eff
sampleCf = ipolycfg_sample_cf cfg
valuesAreExact ::
HasConsistency t
=>
[t] -> Bool
valuesAreExact values =
and $ map isCertainlyExact values
where
isCertainlyExact val =
isExact val == Just True
--instance
-- (Ord var, Show var,
-- ArithInOut.RoundedReal cf, RefOrd.IntervalLike cf,
-- HasConsistency cf,
-- Show cf, Show (SizeLimits cf))
-- =>
-- HasEvalOps (IntPoly var cf) cf
-- where
-- type EvalOpsEffortIndicator (IntPoly var cf) cf =
-- IntPolyEffort cf
-- evalOpsDefaultEffort _p@(IntPoly cfg _) _sampleCf =
-- ipolycfg_effort cfg
---- (ArithInOut.roundedRealDefaultEffort sampleCf, Int1To10 depth)
---- where
---- depth = 1 + (maxDeg `div` 2)
---- maxDeg = ipolycfg_maxdeg cfg
--
-- evalOpsEff eff _sampleP sampleCf =
-- coeffPolyEvalOpsOut effCf maxSplitSize sampleCf
-- where
-- maxSplitSize = ipolyeff_evalMaxSplitSize eff
-- effCf = ipolyeff_cfRoundedRealEffort eff
data PolyEvalOps var cf val =
PolyEvalOps
{
polyEvalZero :: val,
polyEvalAdd :: (val -> val -> val),
polyEvalMult :: (val -> val -> val),
polyEvalPow :: (val -> Int -> val), {-^ non-negative integer power -}
polyEvalCoeff :: (cf -> val), {-^ coeff conversion -}
polyEvalMaybePoly :: (IntPolyTerms var cf -> Maybe val), {-^ optional direct poly conversion -}
polyEvalSplitMaxSize :: Int,
polyEvalMonoOps :: Maybe (PolyEvalMonoOps var cf val)
}
data PolyEvalMonoOps var cf val =
PolyEvalMonoOps
{
polyEvalMonoOuter :: PolyEvalOps var cf val,
polyEvalMonoLeq :: (val -> val -> Maybe Bool),
polyEvalMonoGetEndpoints :: val -> (val, val),
polyEvalMonoFromEndpoints :: (val, val) -> val,
polyEvalMonoIsExact :: val -> Bool,
polyEvalMonoSplit :: val -> (val, val),
polyEvalMonoMerge :: (val, val) -> val,
polyEvalMonoMin :: val -> val -> val,
polyEvalMonoMax :: val -> val -> val,
polyEvalMonoGetWidthAsDouble :: val -> Double,
polyEvalMonoCfEffortIndicator :: ArithInOut.RoundedRealEffortIndicator cf
}
coeffPolyEvalOpsOut ::
(RefOrd.IntervalLike cf, ArithInOut.RoundedReal cf, HasConsistency cf)
=>
(ArithInOut.RoundedRealEffortIndicator cf) ->
Int ->
cf ->
PolyEvalOps var cf cf
coeffPolyEvalOpsOut eff depth sample =
result
where
result =
PolyEvalOps (zero sample) (<+>) (<*>) (<^>) id (const Nothing) depth $
Just $ PolyEvalMonoOps
result -- outer rounded ops = itself
(<=?)
RefOrd.getEndpointsOut
RefOrd.fromEndpointsOut
isDefinitelyExact
split
(uncurry (</\>))
(NumOrd.minOutEff effMinmax)
(NumOrd.maxOutEff effMinmax)
getWidthAsDouble
eff
isDefinitelyExact a =
isExact a == Just True
split val = (val1, val2)
where
val1 = RefOrd.fromEndpointsOut (valL, valM)
val2 = RefOrd.fromEndpointsOut (valM, valR)
(valL, valR) = RefOrd.getEndpointsOut val
valM = (valL <+> valR) </>| (2 :: Int)
getWidthAsDouble val = wD
where
Just wD = ArithUpDn.convertUpEff (ArithUpDn.convertDefaultEffort val (0::Double)) 0 w
w = valR <-> valL
(valL, valR) = RefOrd.getEndpointsOut val
(<=?) = NumOrd.pLeqEff effComp
(</\>) = RefOrd.meetOutEff effJoin
(<+>) = ArithInOut.addOutEff effAdd
(<->) = ArithInOut.subtrOutEff effAdd
(<*>) = ArithInOut.multOutEff effMult
(<^>) = ArithInOut.powerToNonnegIntOutEff effPwr
(</>|) = ArithInOut.mixedDivOutEff effDivInt
effMult = ArithInOut.fldEffortMult sample $ ArithInOut.rrEffortField sample eff
effPwr = ArithInOut.fldEffortPow sample $ ArithInOut.rrEffortField sample eff
effAdd = ArithInOut.fldEffortAdd sample $ ArithInOut.rrEffortField sample eff
effDivInt = ArithInOut.mxfldEffortDiv sample (1::Int) $ ArithInOut.rrEffortIntMixedField sample eff
effComp = ArithInOut.rrEffortNumComp sample eff
effJoin = ArithInOut.rrEffortJoinMeet sample eff
effMinmax = ArithInOut.rrEffortMinmaxInOut sample eff
instance
(Ord var, Show var, Show cf, Show (SizeLimits cf),
ArithInOut.RoundedReal cf,
HasAntiConsistency cf,
RefOrd.IntervalLike cf)
=>
(HasDistance (IntPoly var cf))
where
type Distance (IntPoly var cf) = cf
type DistanceEffortIndicator (IntPoly var cf) =
IntPolyEffort cf
distanceDefaultEffort p =
evaluationDefaultEffort p
distanceBetweenEff eff p1 p2 =
ArithInOut.absOutEff effAbs $ evalAtPointOutEff eff dombox diff
where
dombox = getDomainBox diff
diff = polyJoinWith (zero sampleCf) (uncurry $ ArithInOut.subtrOutEff effAdd) (p1, p2)
sampleCf = getSampleDomValue p1
effAdd =
ArithInOut.fldEffortAdd sampleCf $
ArithInOut.rrEffortField sampleCf effCf
effAbs =
ArithInOut.rrEffortAbs sampleCf effCf
effCf = ipolyeff_cfRoundedRealEffort eff
instance
(Ord var, Show var, Show cf, Show (SizeLimits cf),
ArithInOut.RoundedReal cf,
HasAntiConsistency cf,
RefOrd.IntervalLike cf)
=>
(HasImprecision (IntPoly var cf))
where
type Imprecision (IntPoly var cf) = cf
type ImprecisionEffortIndicator (IntPoly var cf) =
IntPolyEffort cf
imprecisionDefaultEffort p =
evaluationDefaultEffort p
imprecisionOfEff eff p = distanceBetweenEff eff p p
--instance
-- (Ord var, Show var,
-- ArithInOut.RoundedReal cf, RefOrd.IntervalLike cf,
-- HasAntiConsistency cf,
-- Show cf)
-- =>
-- ArithUpDn.Convertible (IntPoly var cf) cf
-- where
-- type ConvertEffortIndicator (IntPoly var cf) cf =
-- (EvaluationEffortIndicator (IntPoly var cf),
-- RefOrd.GetEndpointsEffortIndicator cf)
-- convertDefaultEffort sampleP sampleCf =
-- (evaluationDefaultEffort sampleP,
-- RefOrd.getEndpointsDefaultEffort sampleCf)
-- convertUpEff (effEval, effGetEndpts) sampleCf p =
-- Just $ snd $ RefOrd.getEndpointsOutEff effGetEndpts range
-- where
-- range = evalOtherType (evalOpsEff effEval sampleP sampleCf) varDoms p
-- varDoms = getDomainBox p
-- sampleP = p
-- convertDnEff (effEval, effGetEndpts) sampleCf p =
-- Just $ fst $ RefOrd.getEndpointsOutEff effGetEndpts range
-- where
-- range = evalOtherType (evalOpsEff effEval sampleP sampleCf) varDoms p
-- varDoms = getDomainBox p
-- sampleP = p
evalPolyAtPointOut, evalPolyAtPointIn ::
(Ord var, Show var,
ArithInOut.RoundedReal cf, RefOrd.IntervalLike cf,
HasAntiConsistency cf,
Show cf)
=>
(ArithInOut.RoundedRealEffortIndicator cf) ->
Int ->
[cf] {- values for each variable respectively -} ->
IntPoly var cf -> cf
evalPolyAtPointOut eff depth values p@(IntPoly cfg _)
=
evalPolyDirect (coeffPolyEvalOpsOut eff depth sample) values p
where
sample = ipolycfg_sample_cf cfg
evalPolyAtPointIn eff depth values p@(IntPoly cfg _)
=
flipConsistency $
evalPolyDirect (coeffPolyEvalOpsOut eff depth sample) values $
flipConsistencyPoly p
where
sample = ipolycfg_sample_cf cfg
evalPolyOnIntervalOut, evalPolyOnIntervalIn ::
(Ord var, Show var,
ArithInOut.RoundedReal cf, RefOrd.IntervalLike cf,
HasAntiConsistency cf,
Show cf, Show (SizeLimits cf))
=>
ArithInOut.RoundedRealEffortIndicator cf
->
Int
->
[cf] {- values for each variable respectively -}
->
IntPoly var cf -> cf
evalPolyOnIntervalOut eff maxSplitDepth values p@(IntPoly cfg _)
=
evalPolyMono evalOut ops values p
where
evalOut = evalPolyDirect ops
ops = coeffPolyEvalOpsOut eff maxSplitDepth sample
sample = ipolycfg_sample_cf cfg
evalPolyOnIntervalIn eff maxSplitDepth values p@(IntPoly cfg _)
=
evalPolyMono evalIn ops values p
where
evalIn values2 p2 =
flipConsistency $
evalPolyDirect ops values2 $
flipConsistencyPoly p2
ops = coeffPolyEvalOpsOut eff maxSplitDepth sample
sample = ipolycfg_sample_cf cfg
evalPolyDirect ::
(Ord var, Show var, Show cf, Show val, Neg cf) =>
(PolyEvalOps var cf val) ->
[val] ->
IntPoly var cf -> val
evalPolyDirect opsV valuesLZ _p@(IntPoly _cfg terms)
=
-- unsafePrint
-- (
-- "evalPolyDirect: "
-- ++ "\n values = " ++ show values
-- ++ "\n p = " ++ show p
-- ) $
ev valuesLZ terms
where
zV = polyEvalZero opsV
addV = polyEvalAdd opsV
multV = polyEvalMult opsV
powV = polyEvalPow opsV
cfV = polyEvalCoeff opsV
polyV = polyEvalMaybePoly opsV
ev [] (IntPolyC cf) = cfV cf
ev (varValueLZ : restValues) (IntPolyV _ powers)
| IntMap.null powers = zV
| lowestExponent == 0 =
resultMaybeWithoutConstantTerm
| otherwise =
(varValueLZ `powV` lowestExponent) `multV` resultMaybeWithoutConstantTerm
where
(lowestExponent, resultMaybeWithoutConstantTerm)
= IntMap.foldWithKey addTerm (highestExponent, zV) powers
(highestExponent, _) = IntMap.findMax powers
addTerm exponent_2 poly (prevExponent, prevVal) = (exponent_2, newVal)
where
newVal = -- Horner scheme:
polyValue
`addV`
(prevVal `multV` (varValueLZ `powV` (prevExponent - exponent_2)))
polyValue =
case polyV poly of
Just value -> value
Nothing -> ev restValues poly
ev varVals terms_2 =
error $
"evalPolyDirect: illegal case:"
++ "\n varVals = " ++ show varVals
++ "\n terms = " ++ show terms_2
-- TODO: make the following function generic for any function representation with nominal derivatives
evalPolyMono ::
(Ord var, Show var,
ArithInOut.RoundedReal cf,
RefOrd.IntervalLike cf,
HasConsistency cf,
Show cf, Show (SizeLimits cf), Show val)
=>
([val] -> IntPoly var cf -> val) -- ^ direct evaluator (typically, @evalPolyDirect opsV@)
->
(PolyEvalOps var cf val)
->
[val] {-^ value for each variable -}
->
IntPoly var cf
->
val
evalPolyMono evalDirect opsV valuesG pOrig@(IntPoly cfg _)
| noMonoOps = direct
-- | noMonotoneVar = useMonotonicityAndSplit
| otherwise =
-- (case segCount > 1 of
-- False -> id
-- True ->
-- unsafePrint
-- (
-- "evalPolyMono:"
-- ++ "\n split into " ++ show segCount ++ " segment(s), "
-- ++ show (emsCountIgnoreNodes resultEMS) ++ " pruned"
-- ++ " (maxSplitSize = " ++ show maxSplitSize ++ ")"
-- ++ "\n polyTermSize p = " ++ show (polyTermSize p)
-- ))
-- unsafePrint
-- (
-- "evalPolyMono: "
-- ++ "\n pOrig = " ++ show pOrig
-- ++ "\n maybeResultL = " ++ show maybeResultL
-- ++ "\n maybeResultR = " ++ show maybeResultR
-- ++ "\n direct = " ++ show direct
-- ) $
case (maybeResultL, maybeResultR) of
(Just resultL, Just resultR) ->
mergeV (resultL, resultR)
_ -> error $
"evalPolyMono: maybeResultL = " ++ show maybeResultL
++ "; maybeResultR = " ++ show maybeResultR
where
vars = ipolycfg_vars cfg
direct = evalDirect valuesG pOrig
(pL, pR) = RefOrd.getEndpointsOut pOrig
maybeResultL = maybeResultForP pL
maybeResultR = maybeResultForP pR
maybeResultForP p =
emsCollectResultsSoFar (curry mergeV) $
useMonotonicityAndSplitting (direct, direct) $
EMSTODO (direct, [direct]) $ zip valuesG $ repeat (False, False)
where
useMonotonicityAndSplitting (minSoFar, maxSoFar) emsTree =
case evalNextLevel 0 emsTree of
(emsTreeNew, Nothing, _) -> emsTreeNew
(emsTreeNew, _, False) -> emsTreeNew
(emsTreeNew, _, _) ->
case emsCollectMinMax minV maxV emsTreeNew of
Just (minSoFarNew, maxSoFarNew) ->
-- unsafePrint
-- (
-- "evalPolyMono: useMonotonicityAndSplitting: processing next layer:"
-- ++ "\n size of emsTreeNew = " ++ show (emsCountNodes emsTreeNew)
-- ++ "\n minSoFarNew = " ++ show minSoFarNew
-- ++ "\n maxSoFarNew = " ++ show maxSoFarNew
-- ) $
useMonotonicityAndSplitting (minSoFarNew, maxSoFarNew) emsTreeNew
_ ->
error $
"evalPolyMono: useMonotonicityAndSplitting: no result in tree!"
++ "\n p = " ++ show p
++ "\n valuesG = " ++ show valuesG
++ "\n minSoFar = " ++ show minSoFar
++ "\n maxSoFar = " ++ show maxSoFar
++ "\n emsTree = " ++ show emsTree
++ "\n emsTreeNew = " ++ show emsTreeNew
where
evalNextLevel nodeCountSoFar (EMSSplit left right) =
(EMSSplit leftNew rightNew, maybeNodeCountR, updatedL || updatedR)
where
(leftNew, maybeNodeCountL, updatedL) = evalNextLevel nodeCountSoFar left
(rightNew, maybeNodeCountR, updatedR) =
case maybeNodeCountL of
Just nodeCountL ->
evalNextLevel nodeCountL right
Nothing ->
(right, Nothing, False)
evalNextLevel nodeCountSoFar t@(EMSDone _) = (t, Just (nodeCountSoFar + 1), False)
evalNextLevel nodeCountSoFar t@(EMSIgnore _) = (t, Just (nodeCountSoFar + 1), False)
evalNextLevel nodeCountSoFar (EMSTODO nosplitResultSamples valuesAndDetectedMonotonicity)
| insideOthers =
(EMSIgnore nosplitResultSamples, Just (nodeCountSoFar + 1), False)
| nodeCountSoFar + 1 >= maxSplitSize = -- node count limit reached
(EMSDone nosplitResultSamples, Nothing, False)
| splitHelps =
(EMSSplit (EMSTODO (leftRes, leftSamples) leftValsEtc) (EMSTODO (rightRes, rightSamples) rightValsEtc),
Just $ nodeCountSoFar + 2, True)
| otherwise = -- ie splitting further does not help:
(EMSDone nosplitResultSamples, Just (nodeCountSoFar + 1), False)
where
insideOthers =
(minSoFar `leqV` nosplitResult == Just True) &&
(nosplitResult `leqV` maxSoFar == Just True)
nosplitResultWidth = getWidthDblV nosplitResult
nosplitResult = fst nosplitResultSamples
leftSamples = getSamplesFor leftValsEtc
rightSamples = getSamplesFor rightValsEtc
getSamplesFor valuesAndDetectedMonotonicity2 =
-- unsafePrint
-- (
-- "getSamplesFor:"
-- ++ "\n valuesAndDetectedMonotonicity2 = " ++ show valuesAndDetectedMonotonicity2
-- ++ "\n samplePoints2 = \n"
-- ++ unlines (map show samplePoints2)
-- ) $
map (fst . useMonotonicity) samplePoints
where
samplePoints = take maxSplitSize samplePoints2
samplePoints2
| someMonotonicityInfo =
interleaveLists
(getPoints True [] valuesAndDetectedMonotonicity2)
(getPoints False [] valuesAndDetectedMonotonicity2)
| otherwise =
getPoints True [] valuesAndDetectedMonotonicity2
someMonotonicityInfo =
or $ map (\(_,(isMono, _)) -> isMono) valuesAndDetectedMonotonicity2
getPoints _shouldAimDown prevValues [] = [reverse prevValues]
getPoints shouldAimDown prevValues (vdm@(value, dm@(detectedMono, isIncreasing)) : rest)
| isExactV value =
getPoints shouldAimDown (vdm : prevValues) rest
| detectedMono =
getPoints shouldAimDown ((valueEndpt, (True, True)) : prevValues) rest
| otherwise =
interleaveLists
(getPoints shouldAimDown ((valueLE, (True, True)) : prevValues) rest)
(getPoints shouldAimDown ((valueRE, (True, True)) : prevValues) rest)
where
valueEndpt
| isIncreasing `xor` shouldAimDown = valueLE
| otherwise = valueRE
(valueLE, valueRE) = getEndPtsV value
splitHelps
| null possibleSplits = False
| otherwise = bestSplitWidth < nosplitResultWidth
((bestSplitWidth, ((leftRes, leftValsEtc), (rightRes, rightValsEtc))))
= bestSplitInfo
(bestSplitInfo : _) =
sortBy (\ (a,_) (b,_) -> compare a b) splitsInfo
splitsInfo =
map getWidth splitResults
where
getWidth result@((leftVal, _),(rightVal, _)) = (width :: Double, result)
where
width = getWidthDblV $ mergeV (leftVal, rightVal)
splitResults =
map computeSplitResult possibleSplits
possibleSplits =
getSplits [] [] valuesAndDetectedMonotonicity
where
getSplits prevSplits _prevValues [] = prevSplits
getSplits prevSplits prevValues (vd@(value, dmAndIncr@(detectedMono, _)) : rest)
| detectedMono =
getSplits prevSplits (vd : prevValues) rest -- do not split value for which p is monotone
| otherwise =
getSplits (newSplit : prevSplits) (vd : prevValues) rest
where
newSplit =
(
prevValuesRev ++ [(valueL, dmAndIncr)] ++ rest
,
prevValuesRev ++ [(valueR, dmAndIncr)] ++ rest
)
prevValuesRev = reverse prevValues
(valueL, valueR) = splitV value
computeSplitResult (valuesAndDM_L, valuesAndDM_R) =
(useMonotonicity valuesAndDM_L, useMonotonicity valuesAndDM_R)
useMonotonicity valuesAndPrevDetectedMonotonicity =
(fromEndPtsV (left, right), valuesAndCurrentDetectedMonotonicity)
where
values = map fst valuesAndPrevDetectedMonotonicity
left = evalDirect valuesL p
right = evalDirect valuesR p
(_noMonotoneVar, valuesL, valuesR, valuesAndCurrentDetectedMonotonicity) =
let ?mixedMultInOutEffort = effMult in
detectMono True [] [] [] $
reverse $ -- undo reverse due to the accummulators
zip vars $ valuesAndPrevDetectedMonotonicity
detectMono noMonotoneVarPrev valuesLPrev valuesRPrev
valuesAndCurrentDetectedMonotonicityPrev []
= (noMonotoneVarPrev, valuesLPrev, valuesRPrev,
valuesAndCurrentDetectedMonotonicityPrev)
detectMono noMonotoneVarPrev valuesLPrev valuesRPrev
valuesAndCurrentDetectedMonotonicityPrev ((var, (val, dmAndIncr@(prevDM, isIncreasing))) : rest)
=
-- unsafePrint
-- (
-- "evalPolyMono: detectMono: deriv = " ++ show deriv
-- ) $
detectMono noMonotoneVarNew (valLNew : valuesLPrev) (valRNew : valuesRPrev)
((val, newDMAndIncr) : valuesAndCurrentDetectedMonotonicityPrev) rest
where
noMonotoneVarNew = noMonotoneVarPrev && varNotMono
(valLNew, valRNew, newDMAndIncr)
| prevDM && isIncreasing = (valL, valR, dmAndIncr)
| prevDM = (valR, valL, dmAndIncr)
| varNotMono = (val, val, dmAndIncr) -- not monotone, we have to be safe
| varNonDecr = (valL, valR, (True, True)) -- non-decreasing on the whole domain - can use endpoints
| otherwise = (valR, valL, (True, False)) -- non-increasing on the whole domain - can use swapped endpoints
(varNonDecr, varNotMono) =
case (valIsExact, zV `leqV` deriv, deriv `leqV` zV) of
(True, _, _) -> (undefined, True) -- when a variable has a thin domain, do not bother separating endpoints
(_, Just True, _) -> (True, False)
(_, _, Just True) -> (False, False)
_ -> (undefined, True)
deriv =
evalPolyDirect opsVOut values $ -- this evaluation must be outer-rounded!
diffPolyOut effCf var p -- range of (d p)/(d var)
(valL, valR) = getEndPtsV val
valIsExact = isExactV val
zV = polyEvalZero opsV
maxSplitSize = polyEvalSplitMaxSize opsV
(noMonoOps, monoOpsV) =
case polyEvalMonoOps opsV of
Nothing -> (True, error "evalPolyMono: internal error: monoOpsV used when not present")
Just monoOpsV_2 -> (False, monoOpsV_2)
leqV = polyEvalMonoLeq monoOpsV
fromEndPtsV = polyEvalMonoFromEndpoints monoOpsV
getEndPtsV = polyEvalMonoGetEndpoints monoOpsV
isExactV = polyEvalMonoIsExact monoOpsV
splitV = polyEvalMonoSplit monoOpsV
mergeV = polyEvalMonoMerge monoOpsV
minV = polyEvalMonoMin monoOpsV
maxV = polyEvalMonoMax monoOpsV
getWidthDblV = polyEvalMonoGetWidthAsDouble monoOpsV
effCf = polyEvalMonoCfEffortIndicator monoOpsV
opsVOut = polyEvalMonoOuter monoOpsV
effMult = ArithInOut.mxfldEffortMult sampleCf (1::Int) $ ArithInOut.rrEffortIntMixedField sampleCf effCf
sampleCf = ipolycfg_sample_cf cfg
-- useMonotonicityAndSplitWith remainingDepth valuesAndPrevDetectedMonotonicity
-- | remainingDepth > 0 && splitHelps =
---- unsafePrint
---- (
---- "evalPolyMono: useMonotonicityAndSplitWith: SPLIT"
---- ++ "\n remainingDepth = " ++ show remainingDepth
---- ++ "\n valuesAndPrevDetectedMonotonicity = " ++ show valuesAndPrevDetectedMonotonicity
---- ++ "\n valuesAndCurrentDetectedMonotonicity = " ++ show valuesAndCurrentDetectedMonotonicity
---- ++ "\n nosplitResult = " ++ show nosplitResult
---- ++ "\n nosplitResultWidth = " ++ show nosplitResultWidth
---- ++ "\n bestSplit = " ++ show bestSplit
---- ++ "\n bestSplitResult = " ++ show _bestSplitResult
---- ++ "\n bestSplitWidth = " ++ show bestSplitWidth
---- ) $
-- computeSplitResultContinueSplitting bestSplit
-- | otherwise =
---- unsafePrint
---- (
---- "evalPolyMono: useMonotonicityAndSplitWith: DONE"
---- ++ "\n remainingDepth = " ++ show remainingDepth
---- ++ "\n valuesAndPrevDetectedMonotonicity = " ++ show valuesAndPrevDetectedMonotonicity
---- ++ "\n valuesAndCurrentDetectedMonotonicity = " ++ show valuesAndCurrentDetectedMonotonicity
---- ++ "\n nosplitResult = " ++ show nosplitResult
---- ++ "\n nosplitResultWidth = " ++ show nosplitResultWidth
---- ) $
-- (nosplitResult, 1 :: Int)
-- where
-- nosplitResult = fromEndPtsV nosplitResultLR
-- (nosplitResultLR, valuesAndCurrentDetectedMonotonicity) =
-- useMonotonicity valuesAndPrevDetectedMonotonicity
-- nosplitResultWidth = getWidthDblV nosplitResult
--
-- splitHelps
-- | null possibleSplits = False
-- | otherwise = bestSplitWidth < nosplitResultWidth
-- (((bestSplitWidth, _bestSplitResult), bestSplit) : _) =
-- sortBy (\ ((a,_),_) ((b,_),_) -> compare a b) $ zip splitWidths possibleSplits
-- splitWidths =
-- map getWidth splitResults
-- where
-- getWidth result = (width :: Double, result)
-- where
-- width = getWidthDblV result
-- splitResults =
-- map computeSplitResult possibleSplits
-- possibleSplits =
-- getSplits [] [] valuesAndCurrentDetectedMonotonicity
-- where
-- getSplits prevSplits _prevValues [] = prevSplits
-- getSplits prevSplits prevValues (vd@(value, dmAndIncr@(detectedMono, _)) : rest)
-- | detectedMono =
-- getSplits prevSplits (vd : prevValues) rest -- do not split value for which p is monotone
-- | otherwise =
-- getSplits (newSplit : prevSplits) (vd : prevValues) rest
-- where
-- newSplit =
-- (
-- prevValuesRev ++ [(valueL, dmAndIncr)] ++ rest
-- ,
-- prevValuesRev ++ [(valueR, dmAndIncr)] ++ rest
-- )
-- prevValuesRev = reverse prevValues
-- (valueL, valueR) = splitV value
--
-- computeSplitResult (valuesAndDM_L, valuesAndDM_R) =
-- mergeV (resultL, resultR)
-- where
-- resultL = fromEndPtsV $ fst $ useMonotonicity valuesAndDM_L
-- resultR = fromEndPtsV $ fst $ useMonotonicity valuesAndDM_R
--
-- computeSplitResultContinueSplitting (valuesAndDM_L, valuesAndDM_R) =
-- (mergeV (resultL, resultR), splitCountL + splitCountR)
-- where
-- (resultL, splitCountL) = useMonotonicityAndSplitWith (remainingDepth - 1) valuesAndDM_L
-- (resultR, splitCountR) = useMonotonicityAndSplitWith (remainingDepth - 1) valuesAndDM_R
interleaveLists :: [a] -> [a] -> [a]
interleaveLists (h1 : t1) (h2 : t2) = h1 : h2 : (interleaveLists t1 t2)
interleaveLists [] list2 = list2
interleaveLists list1 [] = list1
xor False b = b
xor True b = not b
data EvalMonoSpliting task value =
EMSSplit (EvalMonoSpliting task value) (EvalMonoSpliting task value)
| EMSTODO (value, [value]) task
| EMSDone (value, [value])
| EMSIgnore (value, [value])
deriving Show
emsCountNodes ::
EvalMonoSpliting task value -> Int
emsCountNodes (EMSSplit left right) =
(emsCountNodes left) + (emsCountNodes right)
emsCountNodes _ = 1
emsCountIgnoreNodes ::
EvalMonoSpliting task value -> Int
emsCountIgnoreNodes (EMSSplit left right) =
(emsCountIgnoreNodes left) + (emsCountIgnoreNodes right)
emsCountIgnoreNodes (EMSIgnore _) = 1
emsCountIgnoreNodes _ = 0
emsCollectResultsSoFar ::
(value -> value -> value) ->
EvalMonoSpliting task value ->
Maybe value
emsCollectResultsSoFar mergeV emsTree =
aux emsTree
where
aux (EMSIgnore (val, _)) = Just val
aux (EMSDone (val, _)) = Just val
aux (EMSTODO (val, _) _) = Just val
aux (EMSSplit left right) =
do
leftVal <- aux left
rightVal <- aux right
return $ leftVal `mergeV` rightVal
emsCollectMinMax ::
(value -> value -> value) ->
(value -> value -> value) ->
EvalMonoSpliting task value ->
Maybe (value, value)
emsCollectMinMax minV maxV emsTree =
aux emsTree
where
aux (EMSIgnore (_, samples)) = minmaxFromSamples samples
aux (EMSDone (_, samples)) = minmaxFromSamples samples
aux (EMSTODO (_, samples) _) = minmaxFromSamples samples
aux (EMSSplit left right) =
do
(leftMin, leftMax) <- aux left
(rightMin, rightMax) <- aux right
return $
(leftMin `minV` rightMin, leftMax `maxV` rightMax)
minmaxFromSamples [] = Nothing
minmaxFromSamples samples =
Just (foldl1 minV samples, foldl1 maxV samples)
--partiallyEvalPolyAtPointOut ::
-- (Ord var, ArithInOut.RoundedReal cf)
-- =>
-- ArithInOut.RoundedRealEffortIndicator cf ->
-- Map.Map var cf ->
-- IntPoly var cf ->
-- IntPoly var cf
--partiallyEvalPolyAtPointOut effCf valsMap _p@(IntPoly cfg terms) =
-- {- currently there is massive dependency effect here,
-- move this to Composition and deal with it as a special case
-- of composition
-- -}
-- IntPoly cfgVarsRemoved $ pev domsLE terms
-- where
-- cfgVarsRemoved =
-- cfg
-- {
-- ipolycfg_vars = newVars,
-- ipolycfg_domsLE = newDomsLE,
-- ipolycfg_domsLZ = newDomsLZ
-- }
-- where
-- (newVars, newDomsLE, newDomsLZ)
-- = unzip3 $ filter notSubstituted $ zip3 vars domsLE domsLZ
-- where
-- vars = ipolycfg_vars cfg
-- domsLZ = ipolycfg_domsLZ cfg
-- notSubstituted (var, _, _) =
-- var `Map.notMember` valsMap
-- domsLE = ipolycfg_domsLE cfg
-- pev _ t@(IntPolyC _) = t
-- pev (domLE : restDomsLE) (IntPolyV var powers) =
-- case Map.lookup var valsMap of
-- Just value ->
-- let ?addInOutEffort = effAdd in
-- -- evaluate evaluatedPowers using the Horner scheme:
-- foldl (addAndScale (value <-> domLE) highestExponent) heTerms lowerPowers
-- _ ->
-- IntPolyV var evaluatedPowers
-- where
-- evaluatedPowers =
-- IntMap.map (pev restDomsLE) powers
-- ((highestExponent, heTerms) : lowerPowers) =
-- reverse $ IntMap.toAscList evaluatedPowers
-- addAndScale value prevExponent termsSoFar (currExponent, currTerms) =
-- let ?multInOutEffort = effMult in
-- addTermsAux currTerms $ termsMapCoeffs (<*> valuePower) termsSoFar
-- where
-- valuePower =
-- let ?intPowerInOutEffort = effPow in
-- value <^> (prevExponent - currExponent)
-- addTermsAux (IntPolyV v powers1) (IntPolyV _ powers2) =
-- IntPolyV v $ IntMap.unionWith addTermsAux powers1 powers2
-- addTermsAux (IntPolyC val1) (IntPolyC val2) =
-- let ?addInOutEffort = effAdd in
-- IntPolyC $ val1 <+> val2
-- effAdd = ArithInOut.fldEffortAdd sampleCf $ ArithInOut.rrEffortField sampleCf effCf
-- effMult = ArithInOut.fldEffortMult sampleCf $ ArithInOut.rrEffortField sampleCf effCf
-- effPow = ArithInOut.fldEffortPow sampleCf $ ArithInOut.rrEffortField sampleCf effCf
-- sampleCf = domLE
-- | michalkonecny/aern | aern-poly/src/Numeric/AERN/Poly/IntPoly/Evaluation.hs | bsd-3-clause | 37,815 | 10 | 27 | 12,514 | 6,708 | 3,670 | 3,038 | 550 | 16 |
-- Author: Lee Ehudin
-- Contains the entry point for the text editor
module Controller.Runner (hasked) where
import Controller.EventHandler (handleEvents)
import Model.Buffer (newBuffer, newBufferFromFile, writeBufferToFile, getScreen,
getCursorPos)
import View.Curses (updateText, getScreenSize, withCurses)
import Data.Maybe (listToMaybe)
import System.Environment (getArgs)
-- Entry point for the hasked program. Sets up an initial buffer by possibly
-- reading from a file, refreshes the screen once, then goes into the event
-- handler loop.
hasked :: IO ()
hasked = withCurses $ do
args <- getArgs
buffer <- maybe newBuffer newBufferFromFile (listToMaybe args)
screenSize <- getScreenSize
cursorPos <- getCursorPos buffer
getScreen screenSize buffer >>= updateText cursorPos screenSize
handleEvents screenSize buffer
writeBufferToFile buffer
| percivalgambit/hasked | src/Controller/Runner.hs | bsd-3-clause | 903 | 0 | 11 | 161 | 178 | 95 | 83 | 16 | 1 |
module Control.Pipe.Zip (
controllable,
controllable_,
zip,
zip_,
ProducerControl(..),
ZipControl(..),
) where
import qualified Control.Exception as E
import Control.Monad
import Control.Pipe
import Control.Pipe.Coroutine
import Control.Pipe.Exception
import Prelude hiding (zip)
data ProducerControl r
= Done r
| Error E.SomeException
controllable :: Monad m
=> Producer a m r
-> Pipe (Either () (ProducerControl r)) a m r
controllable p = do
x <- pipe (const ()) >+> suspend p
case x of
Left r -> return r
Right (b, p') ->
join $ onException
(await >>= \c -> case c of
Left () -> yield b >> return (controllable (resume p'))
Right (Done r) -> return $ (pipe (const ()) >+> terminate p') >> return r
Right (Error e) -> return $ (pipe (const ()) >+> terminate p') >> throw e)
(pipe (const ()) >+> terminate p')
controllable_ :: Monad m
=> Producer a m r
-> Producer a m r
controllable_ p = pipe Left >+> controllable p
data ZipControl r
= LeftZ (ProducerControl r)
| RightZ (ProducerControl r)
zip :: Monad m
=> Producer a m r
-> Producer b m r
-> Pipe (Either () (ZipControl r)) (Either a b) m r
zip p1 p2 = translate >+> (controllable p1 *+* controllable p2)
where
translate = forever $ await >>= \c -> case c of
Left () -> (yield . Left . Left $ ()) >> (yield . Right . Left $ ())
Right (LeftZ c) -> (yield . Left . Right $ c) >> (yield . Right . Left $ ())
Right (RightZ c) -> (yield . Left . Left $ ()) >> (yield . Right . Right $ c)
zip_ :: Monad m
=> Producer a m r
-> Producer b m r
-> Producer (Either a b) m r
zip_ p1 p2 = pipe Left >+> zip p1 p2
(*+*) :: Monad m
=> Pipe a b m r
-> Pipe a' b' m r
-> Pipe (Either a a') (Either b b') m r
p1 *+* p2 = (continue p1 *** continue p2) >+> both
where
continue p = do
r <- p >+> pipe Right
yield $ Left r
discard
both = await >>= \x -> case x of
Left c -> either (const right) (\a -> yield (Left a) >> both) c
Right c -> either (const left) (\b -> yield (Right b) >> both) c
left = await >>= \x -> case x of
Left c -> either return (\a -> yield (Left a) >> left) c
Right _ -> left
right = await >>= \x -> case x of
Left _ -> right
Right c -> either return (\b -> yield (Right b) >> right) c
| pcapriotti/pipes-extra | Control/Pipe/Zip.hs | bsd-3-clause | 2,433 | 0 | 25 | 734 | 1,157 | 579 | 578 | 69 | 4 |
module Main where
import PScheme.Repl
import PScheme.Reader
import PScheme.Eval (exceptT, defaultEnv, runEval, eval)
import System.IO
import System.Environment (getArgs)
import System.Exit (exitFailure)
import Control.Monad (forM_)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Except
import Control.Monad.IO.Class (liftIO, MonadIO)
parseForms :: [[Token]] -> Either ReadError [Value]
parseForms [] = pure []
parseForms (ts:tss) = do
state <- parse ts
parseLines tss state
parseLines :: [[Token]] -> ParseOutcome -> Either ReadError [Value]
parseLines [] state = case (parsedValue state) of
Nothing -> pure []
Just v -> pure [v]
parseLines (ts:tss) state = case (parsedValue state) of
Nothing -> (parseNext state ts) >>= (parseLines tss)
Just v -> do
state' <- parseNext state ts
vs <- parseLines tss state'
pure (v:vs)
tokeniseAll :: String -> Either ReadError [[Token]]
tokeniseAll s = tokeniseLines (lines s) where
tokeniseLines [] = pure []
tokeniseLines (l:ls) = do
ts <- readTokens l
tss <- tokeniseLines ls
pure $ ts:tss
readHandle :: Handle -> ExceptT ReadError IO [Value]
readHandle h = do
contents <- liftIO $ hGetContents h
lineTokens <- exceptT $ tokeniseAll contents
exceptT $ parseForms lineTokens
evalFile :: FilePath -> IO ()
evalFile filePath = withFile filePath ReadMode $ \h -> do
result <- runExceptT $ readHandle h
case result of
Left err -> print err
Right forms -> do
env <- defaultEnv
valsOrError <- runEval env (traverse eval forms)
case valsOrError of
Left err -> print err
Right vals ->
forM_ vals print
main :: IO ()
main = do
args <- getArgs
case args of
[] -> repl
[filePath] -> evalFile filePath
_ -> do
hPutStrLn stderr "Usage: pscheme [file]"
exitFailure
| lkitching/PScheme | app/Main.hs | bsd-3-clause | 1,848 | 0 | 17 | 402 | 714 | 355 | 359 | 59 | 3 |
{-|
Module : Control.Monad.Fork
Description : Multithreading within monad transformer stacks
Copyright : (c) Andrew Melnick 2016
License : BSD3
Maintainer : Andrew Melnick
Stability : experimental
Portability : portable
Lifting the concept of forking a new thread into common monad transformers
Monads in the MonadFork class are able to run actions in a new thread, but
require some sort of "handler" data in order to do so properly, for example,
the `ExceptT` Transformer requires some action to be run in the event that
the new thread has an exception
The `:<:` operator joins handlers into a chain, so the monad
@(AT (BT (CT IO)))@ will have a handler that looks like
@(A :<: B :<: C :<: ())@, (where `()` is the handler for `IO`), indicating that
the handlers will be applied in the same order as the effects if one were
unwrapping the stack using @runCT (runBT (runAT x)))@
-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
module Control.Monad.Fork where
import Control.Monad.Trans
import Control.Monad.Trans.Maybe
import qualified Control.Monad.State.Lazy as Lazy
import qualified Control.Monad.State.Strict as Strict
import qualified Control.Monad.Writer.Lazy as Lazy
import qualified Control.Monad.Writer.Strict as Strict
import qualified Control.Monad.RWS.Lazy as Lazy
import qualified Control.Monad.RWS.Strict as Strict
import Control.Monad.Reader
import Control.Monad.Except
import Control.Monad.Catch
import Control.Concurrent
infixr 1 :<:
-- | Monads whose actions can be run in a new thread, provided a handler of
-- type `h` is provided
class Monad m => MonadFork h m where
-- | Run an action in a new thread, and return the id of the new thread
forkT :: h -> m () -> m ThreadId
-- | Monads whose actions can not only be run in a new thread, but are able to
-- react to asynchronous exceptions being thrown in the thread
class (MonadMask m, MonadFork h m) => MonadForkFinally h m where
-- | Like `forkT`, but also takes an action to execute on thread completion
--
-- A default implementation is available based on the relationship between
-- `forkIO` and `forkFinally`, however, that implementation will
-- A) Only execute the handler if no exception is thrown, and B)
-- Execute the handler before the thread completion handler, so any effects
-- caused by it will be lost
forkFinallyT :: h -> m a -> (Either SomeException a -> m ()) -> m ThreadId
forkFinallyT handler action and_then = mask $ \restore ->
forkT handler $ try (restore action) >>= and_then
-- | Base of the instance stack, handler does nothing
instance MonadFork () IO where
forkT _ = forkIO
instance MonadForkFinally () IO where
forkFinallyT _ = forkFinally
-- | Environment is provided to the new thread, handler does nothing
instance MonadFork h m => MonadFork h (ReaderT r m) where
forkT subHandler action = ReaderT $ \env ->
forkT subHandler (runReaderT action env)
instance (MonadMask m, MonadForkFinally h m) => MonadForkFinally h (ReaderT r m)
-- | Handler should report a `Nothing` result
instance MonadFork h m => MonadFork (m () :<: h) (MaybeT m) where
forkT (onNothing :<: subHandler) action = MaybeT $ fmap Just $ forkT subHandler $
runMaybeT action >>= \result -> case result of
Just () -> return ()
Nothing -> onNothing
-- | Handler should report a `Left` result
instance MonadFork h m => MonadFork ((e -> m ()) :<: h) (ExceptT e m) where
forkT (onException :<: subHandler) action = ExceptT $ fmap Right $ forkT subHandler $
runExceptT action >>= \result -> case result of
Right () -> return ()
Left ex -> onException ex
-- | Handler should report original and final state
instance MonadFork h m => MonadFork ((s -> s -> m ()) :<: h) (Lazy.StateT s m) where
forkT (reportState :<: subHandler) action = Lazy.StateT $ \s -> fmap (flip (,) s) $ forkT subHandler $
Lazy.runStateT action s >>= \((), s') -> reportState s s'
instance (MonadMask m, MonadForkFinally h m) => MonadForkFinally ((s -> s -> m ()) :<: h) (Lazy.StateT s m)
-- | Handler should report original and final state
instance MonadFork h m => MonadFork ((s -> s -> m ()) :<: h) (Strict.StateT s m) where
forkT (reportState :<: subHandler) action = Strict.StateT $ \s -> fmap (flip (,) s) $ forkT subHandler $
Strict.runStateT action s >>= \((), s') -> reportState s s'
instance (MonadMask m, MonadForkFinally h m) => MonadForkFinally ((s -> s -> m ()) :<: h) (Strict.StateT s m)
-- | Handler should report final monoidal value
instance (Monoid w, MonadFork h m) => MonadFork ((w -> m ()) :<: h) (Lazy.WriterT w m) where
forkT (reportLog :<: subHandler) action = Lazy.WriterT $ fmap (flip (,) mempty) $ forkT subHandler $
Lazy.runWriterT action >>= \((), w) -> reportLog w
instance (Monoid w, MonadMask m, MonadForkFinally h m) => MonadForkFinally ((w -> m ()) :<: h) (Lazy.WriterT w m)
-- | Handler should report final monoidal value
instance (Monoid w, MonadFork h m) => MonadFork ((w -> m ()) :<: h) (Strict.WriterT w m) where
forkT (reportLog :<: subHandler) action = Strict.WriterT $ fmap (flip (,) mempty) $ forkT subHandler $
Strict.runWriterT action >>= \((), w) -> reportLog w
instance (Monoid w, MonadMask m, MonadForkFinally h m) => MonadForkFinally ((w -> m ()) :<: h) (Strict.WriterT w m)
-- | Environment is provided to the new thread, handler should report final monoid value, initial state, and final state
instance (Monoid w, MonadFork h m) => MonadFork ((w -> s -> s -> m ()) :<: h) (Lazy.RWST r w s m) where
forkT (reportLogAndState :<: subHandler) action = Lazy.RWST $ \r s -> fmap (\x -> (x, s, mempty)) $ forkT subHandler $
Lazy.runRWST action r s >>= \((), s', w) -> reportLogAndState w s s'
instance (Monoid w, MonadMask m, MonadForkFinally h m) => MonadForkFinally ((w -> s -> s -> m ()) :<: h) (Lazy.RWST r w s m)
-- | Environment is provided to the new thread, handler should report final monoid value, initial state, and final state
instance (Monoid w, MonadFork h m) => MonadFork ((w -> s -> s -> m ()) :<: h) (Strict.RWST r w s m) where
forkT (reportLogAndState :<: subHandler) action = Strict.RWST $ \r s -> fmap (\x -> (x, s, mempty)) $ forkT subHandler $
Strict.runRWST action r s >>= \((), s', w) -> reportLogAndState w s s'
instance (Monoid w, MonadMask m, MonadForkFinally h m) => MonadForkFinally ((w -> s -> s -> m ()) :<: h) (Strict.RWST r w s m)
-- | A handler chain, a is used to handle the top of the stack, b is then used
-- to handle the rest of the stack
data a :<: b = a :<: b
-- | Convenience type family for referring to handlers
type family ForkHandler (m :: * -> *)
type instance ForkHandler IO = ()
type instance ForkHandler (ReaderT r m) = ForkHandler m
type instance ForkHandler (MaybeT m) = m () :<: ForkHandler m
type instance ForkHandler (ExceptT e m) = (e -> m ()) :<: ForkHandler m
type instance ForkHandler (Lazy.StateT s m) = (s -> s -> m ()) :<: ForkHandler m
type instance ForkHandler (Strict.StateT s m) = (s -> s -> m ()) :<: ForkHandler m
type instance ForkHandler (Lazy.WriterT w m) = (w -> m ()) :<: ForkHandler m
type instance ForkHandler (Strict.WriterT w m) = (w -> m ()) :<: ForkHandler m
type instance ForkHandler (Lazy.RWST r w s m) = (w -> s -> s -> m ()) :<: ForkHandler m
type instance ForkHandler (Strict.RWST r w s m) = (w -> s -> s -> m ()) :<: ForkHandler m
| meln5674/monad-fork2 | Control/Monad/Fork.hs | bsd-3-clause | 7,555 | 0 | 14 | 1,545 | 2,289 | 1,203 | 1,086 | 78 | 0 |
{-| Makes @Closure@ (see "AST") an instance of @Translatable@ (see "CodeGen.Typeclasses") -}
module CodeGen.Closure (
translateClosure,
varSubFromTypeVars,
) where
import CodeGen.Type
import CodeGen.Typeclasses
import CodeGen.Expr ()
import CodeGen.Trace (traceVariable)
import CodeGen.CCodeNames
import CodeGen.ClassTable
import qualified CodeGen.Context as Ctx
import CodeGen.DTrace
import CCode.Main
import qualified Identifiers as ID
import Data.List (intersect)
import qualified AST.AST as A
import qualified AST.Util as Util
import qualified AST.Meta as Meta
import Types as Ty
import Control.Monad.State hiding (void)
import Control.Arrow(first)
import Debug.Trace
varSubFromTypeVars :: [Type] -> [(ID.Name, CCode Lval)]
varSubFromTypeVars = map each
where
each ty =
let ty' = typeVarRefName ty
in (ID.Name $ Ty.getId ty, AsLval ty')
translateClosure :: A.Expr -> [Type] -> ProgramTable -> CCode Toplevel
translateClosure closure typeVars table
| A.isClosure closure =
let arrowType = A.getType closure
resultType = Ty.getResultType arrowType
argTypes = Ty.getArgTypes arrowType
params = A.eparams closure
body = A.body closure
id = Meta.getMetaId . A.getMeta $ closure
funName = closureFunName id
envName = closureEnvName id
traceName = closureTraceName id
boundVars = map (ID.qName . show . A.pname) params
freeVars = map (first ID.qnlocal) $
filter (ID.isLocalQName . fst) $
Util.freeVariables boundVars body
fTypeVars = typeVars `intersect` Util.freeTypeVars body
encEnvNames = map fst freeVars
envNames = map (AsLval . fieldName) encEnvNames
encArgNames = map A.pname params
argNames = map (AsLval . argName) encArgNames
subst = zip encEnvNames envNames ++
zip encArgNames argNames ++
varSubFromTypeVars fTypeVars
ctx = Ctx.setClsCtx (Ctx.new subst table) closure
((bodyName, bodyStat), _) = runState (translate body) ctx
in
Concat [buildEnvironment envName freeVars fTypeVars,
tracefunDecl traceName envName freeVars fTypeVars,
Function (Static $ Typ "value_t") funName
[(Ptr (Ptr encoreCtxT), encoreCtxVar),
(Ptr (Ptr ponyTypeT), encoreRuntimeType),
(Typ "value_t", Var "_args[]"),
(Ptr void, envVar)]
(Seq $
dtraceClosureEntry argNames :
extractArguments params ++
extractEnvironment envName freeVars fTypeVars ++
[bodyStat
,dtraceClosureExit
,returnStmnt bodyName resultType])]
| otherwise =
error
"Tried to translate a closure from something that was not a closure"
where
returnStmnt var ty
| isUnitType ty = Return $ asEncoreArgT (translate ty) unit
| otherwise = Return $ asEncoreArgT (translate ty) var
extractArguments params = extractArguments' params 0
extractArguments' [] _ = []
extractArguments' ((A.Param{A.pname, A.ptype}):args) i =
Assign (Decl (ty, arg)) (getArgument i) : extractArguments' args (i+1)
where
ty = translate ptype
arg = AsLval $ argName pname
getArgument i = fromEncoreArgT ty $ AsExpr $ ArrAcc i (Var "_args")
buildEnvironment name vars typeVars =
StructDecl (Typ $ show name) $
(map translateBinding vars) ++ (map translateTypeVar typeVars)
where
translateBinding (name, ty) =
(translate ty, AsLval $ fieldName name)
translateTypeVar ty =
(Ptr ponyTypeT, AsLval $ typeVarRefName ty)
extractEnvironment envName vars typeVars =
map assignVar vars ++ map assignTypeVar typeVars
where
assignVar (name, ty) =
let fName = fieldName name
in Assign (Decl (translate ty, AsLval fName)) $ getVar fName
assignTypeVar ty =
let fName = typeVarRefName ty
in Seq [Assign (Decl (Ptr ponyTypeT, AsLval fName)) $ getVar fName,
encoreAssert (AsExpr $ AsLval fName)]
getVar name =
(Deref $ Cast (Ptr $ Struct envName) envVar) `Dot` name
tracefunDecl traceName envName members fTypeVars =
Function (Static void) traceName args body
where
args = [(Ptr encoreCtxT, ctxArg), (Ptr void, Var "p")]
ctxArg = Var "_ctx_arg"
body = Seq $
Assign (Decl (Ptr (Ptr encoreCtxT), encoreCtxVar)) (Amp ctxArg) :
Assign (Decl (Ptr $ Struct envName, envVar)) (Var "p") :
extractEnvironment envName members fTypeVars ++
map traceMember members
traceMember (name, ty) = traceVariable ty $ getVar name
getVar name = envVar `Arrow` fieldName name
| Paow/encore | src/back/CodeGen/Closure.hs | bsd-3-clause | 5,274 | 0 | 19 | 1,783 | 1,469 | 759 | 710 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Websave.Web.Data
( getData
) where
import Control.Monad (join)
import Data.ByteString (ByteString)
import Network.Wai (queryString)
import Yesod.Core (MonadHandler, getRequest, reqWaiRequest)
-- TODO move to YesodTools
-- TODO process POST data as well
getData :: MonadHandler m => m (Maybe ByteString)
getData = join . lookup "data" . queryString . reqWaiRequest <$> getRequest
| dimsmol/websave | src/Websave/Web/Data.hs | bsd-3-clause | 427 | 0 | 9 | 62 | 106 | 61 | 45 | 9 | 1 |
--------------------------------------------------------------------------
-- |
-- Module: Harpy
-- Copyright: (c) 2006-2015 Martin Grabmueller and Dirk Kleeblatt
-- License: BSD3
--
-- Maintainer: martin@grabmueller.de
-- Stability: provisional
-- Portability: portable
--
-- Harpy is a library for run-time code generation of x86 machine code.
--
-- This is a convenience module which re-exports the modules which are
-- essential for using Harpy.
----------------------------------------------------------------------------
module Harpy(module Harpy.CodeGenMonad,
module Harpy.Call,
module Harpy.X86Assembler,
module Control.Monad.Trans) where
import Harpy.CodeGenMonad
import Harpy.Call
import Harpy.X86Assembler
import Control.Monad.Trans
| mgrabmueller/harpy | Harpy.hs | bsd-3-clause | 799 | 0 | 5 | 134 | 67 | 49 | 18 | 8 | 0 |
module LinAlg where
import ListNumSyntax
import Data.Number.IReal
import Data.Number.IReal.FoldB
import Data.Ratio
import Data.List
import Data.Bits
type Vector a = [a]
type Matrix a = [Vector a]
-- Ad hoc choice of precision restriction
prec0 x = prec 200 x
-- Multiplication ------------------------------------------
mulM :: (VarPrec a, Num a) => Matrix a -> Matrix a -> Matrix a
mulM = map . apply
apply :: (Num a, VarPrec a) => Matrix a -> Vector a -> Vector a
apply ass bs = map (`dot` bs) (transpose ass)
-- Multiplication with scalar --------------------------------------------------
smul :: Num a => a -> Vector a -> Vector a
smul x = map (x *)
smulM :: Num a => a -> Matrix a -> Matrix a
smulM x = map (smul x)
-- Scalar product --------------------------------------------------------------
dot :: (Num a, VarPrec a) => Vector a -> Vector a -> a
dot xs ys = prec0 (bsum (xs * ys))
-- Norms of vector ------------------------------------------------------------
norm2, norm1, normInf :: (Floating a, Ord a, VarPrec a) => Vector a -> a
norm2 xs = sqrt (dot xs xs)
norm1 = bsum . map abs
normInf = maximum . map abs
-- L_1 and L_infinity norms of matrix -----------------------------------------
normM1, normMInf :: (Ord a, Floating a, VarPrec a) => Matrix a -> a
normM1 = maximum . map norm1
normMInf = normM1 . transpose
-- Condition number of matrix (in L_1 norm) -----------------------------------
condM :: (Floating a, Ord a, VarPrec a) => Matrix a -> a
condM ass = normM1 ass * normM1 (inverse ass)
-- LQ factorization ------------------------------------------------------------
-- LQ factorization of quadratic matrix.
-- We choose LQ rather than QR since it fits better with
-- head/tail access pattern of lists. Returns L and Q, where
-- L is on triangular form, i.e. only non-zero elements present, and
-- Q is represented as a list of normal vectors of Householder reflectors.
lq :: (Floating a, Ord a, VarPrec a) => Matrix a -> (Matrix a, [Vector a])
lq ass@((x:xs):xss@(_:_)) = (bs : lss, vs : vss)
where h:hs = map head ass
d = norm2 (h:hs)
vs = (if h >= 0 then h + d else h - d): hs
v2 = 2*d*(d+abs h) -- d1 = ||vs||^2
-- Multiply ass by Householder reflector matrix
-- generated by vector vs, i.e. compute A - 2*A*v*v^t
bs : bss = prec0 (zipWith f ass vs)
where f as x = as - apply ass vs * repeat (2*x/v2)
(lss,vss) = lq (map tail bss)
lq ass = (ass, [])
-- Solve quadratic, non-singular system Ax = b, using LQ factorization.
solve :: (Floating a, Ord a, VarPrec a) => Matrix a -> Vector a -> Vector a
solve ass = qIter vss . subst lss
where (lss,vss) = lq ass
-- Solve triangular system (matrix is lower triangular)
subst :: Fractional a => [[a]] -> [a] -> [a]
subst [] _ = []
subst ((x:xs):xss) (b:bs) = y : subst xss (bs - xs * repeat y)
where y = b/x
-- Multiply by sequence of Householder matrices
qIter :: (Fractional a, VarPrec a) => [Vector a] -> Vector a -> Vector a
qIter [] bs = bs
qIter (vs : vss) (b : bs) = hh vs (b : qIter vss bs)
-- Vector rs multiplied by Householder reflector matrix generated by vs
hh :: (Fractional a, VarPrec a) => Vector a -> Vector a -> Vector a
hh vs rs = rs - vs * repeat x
where x = 2 * dot rs vs/dot vs vs
inverse :: (Floating a, Ord a, VarPrec a) => Matrix a -> Matrix a
inverse ass = map (solve ass) bss
where bss = map (\k -> replicate k 0 ++ 1 : replicate (n-1-k) 0) [0..n-1]
n = length ass
-- Notorious ill-conditioned example: Hilbert matrix
hilbert n = [[fromRational (1 % (i+j-1)) | i <- [1..n] ] | j <- [1..n] ]
vandermonde xs = take n (iterate (*xs) (replicate n 1))
where n = length xs
{-
Examples:
> condM (hilbert 15) ?? 20
0.15391915629553122413e22
(0.82 secs, 283246752 bytes)
> let ass = hilbert 25 :: Matrix IReal
> mapM_ (? 100) $ solve ass (map sqrt [1..25])
705.1533284963290956608362822423912734910227236293299614122851194081918876326343926875640023119369034821
-439673.9873388597705868990725370476651285605876080956807569044940939165590176737169191270235259441503432119
68204344.9731886365740080624537609996623689444810205308753901423565119434568104831725210699973202379088129882
-4664448582.3034346633655587322862893452286509473730850571024608318992483060505363965128396539508414113288932734
177397301669.4470302993210422259749351478977835134529306395373729499456573463841842107447990766834809423011040738
-4254091706828.1686190716920574829426672777980678548199026748623525425695787052836566266674697317136802722120565833
69545239200122.9144040744433369547417865224879339613940156554671219472545236203917004334667205391996866968931595183
-816847000729018.7737530264497363783287163634866491132650857885691558585008629694744116239295210128489892702899000614
7154341228591462.3012615296054988779018448134073649486823700047095232218238925733189512085896861380925718869840128164
-48009667586828894.5767332565013430439910972214304035550971986293103555764342546810272410148080254252305995120781866206
251844392677531274.0709127325911434838350769774189068254774415143641327544366238651541772916524464117349357235144334991
-1048143734335817624.0336204855464617426412722915751934481683873315855051574469784131062190560275498658327486102529792226
3498210324096944636.4524065506620210607308978049694297040490003525118886804565590254308130573820526159628678426741651309
-9431171401929169455.3424006600477669947185012388808800099904639824329048176939584968420634515763762886683395660091124001
20625644400616390081.3023145571266820730894216095277381736236614083175100283703764598631503021932601076440164701624585386
-36637408250801684992.2327515887414617772781813348542150962395077849459653041754367086153854944131054328104108083193973575
52765488024278928905.4679536245314145289284377844729508688894134162341828418605873919241149475390504553871953987733953659
-61295595789243212173.9536012643337759381753284186801798055604026908049933788464084009039536683226486562275743371985047603
56896779843800653456.9314422266376319337514520994749231451564802652135775892050259875530397079988163136075067115610230454
-41573863983516368926.7055317586515189490950549358051162588877518503235490221753772940736406787440880748304465115113504359
23365653654180951042.9851530663181890194238095089360096426483401824061668322486605839625160258109763064486458688933759486
-9740723523526602431.8575162294625153120767034736388134987019551900158949982443457241958170904379968964746678508149489593
2835293607475155284.1978846389721895478771840783053407794046273623991370837498430393230149403586055906293606569603644531
-514097728749287006.1850108351735689777337751827160575523829387979908417439866364790805580176949298837083538483210154166
43696874386454381.7499373427978656981157281081737498936218190682725431997586473877133365258605530660231535107025476866
(1.06 secs, 291352880 bytes)
-} | sydow/ireal | applications/LinAlg.hs | bsd-3-clause | 7,044 | 0 | 14 | 1,031 | 1,415 | 742 | 673 | 59 | 3 |
module Messages where
import qualified Sound.OSC as SO
import qualified System.MIDI as SM
data DX200Msg = OSCMsg SO.Message | MidiMsg SM.MidiMessage deriving (Show)
| rumblesan/dx200-programmer | src/Messages.hs | bsd-3-clause | 170 | 0 | 7 | 28 | 45 | 29 | 16 | 4 | 0 |
module Main where
import Lib
main :: IO ()
main = putStrLn "Hello, Main here."
| epost/psc-query | psc-query/Main.hs | bsd-3-clause | 81 | 0 | 6 | 17 | 25 | 14 | 11 | 4 | 1 |
{-# OPTIONS_GHC -fno-warn-tabs #-}
import Common
import Hex
import Xor
main = do
putStrLn "=== Challange5 ==="
putStrLn $ hexEncode $ xorBytes message key
where
key = strToVec "ICE"
message = strToVec "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal"
| andrewcchen/matasano-cryptopals-solutions | set1/Challange5.hs | bsd-3-clause | 286 | 0 | 8 | 54 | 56 | 28 | 28 | 9 | 1 |
module Trainer where
import System.Random
import Trainer.Internal
randomListIndex :: Double -> IO Int
randomListIndex hi = do r1 <- randomRIO (0,1)
r2 <- randomRIO (0,1)
return (floor $ positiveStdNormal hi r1 r2)
| epsilonhalbe/VocabuLambda | Trainer.hs | bsd-3-clause | 264 | 0 | 10 | 82 | 86 | 44 | 42 | 7 | 1 |
-- polyacounting.hs
module Math.PolyaCounting where
-- Cameron, Combinatorics, p247-253
import Math.PermutationGroups
import Math.SchreierSims
import Math.QQ
import Math.MPoly
import Math.CombinatoricsCounting (factorial, choose)
-- ROTATION GROUP OF CUBE (AS PERMUTATION OF FACES)
-- 1
-- 2 3 4 5
-- 6
cubeF = fromCycles [[1],[2,3,4,5],[6]]
cubeV = fromCycles [[1,2,3],[4,5,6]]
cubeE = fromCycles [[1,3],[2,4],[5,6]]
cubeGp = schreierSimsTransversals 6 [cubeF, cubeV, cubeE]
-- ROTATION GROUP OF DODECAHEDRON (AS PERMUTATION OF FACES)
-- The top faces are numbered (looking from above)
-- 2
-- 6 3
-- 1
-- 5 4
-- The bottom faces are numbered so that opposite faces add up to 13 (still looking from above)
-- 9 8
-- 12
-- 10 7
-- 11
dodecF = fromCycles [[1],[2,3,4,5,6],[11,10,9,8,7],[12]] -- rotation about a face
dodecV = fromCycles [[1,2,3],[4,6,8],[9,7,5],[12,11,10]] -- rotation about a vertex
dodecE = fromCycles [[1,2],[3,6],[4,9],[5,8],[7,10],[11,12]] -- rotation about an edge
dodecGp = schreierSimsTransversals 12 [dodecF, dodecV, dodecE]
-- in fact any two generate the group
-- The order of the group is 60. It's isomorphic to A5. See:
-- http://en.wikipedia.org/wiki/Icosahedral_symmetry
cycleIndexElt g = monomial (cycleType g)
cycleIndexGp gp = sum [cycleIndexElt g | g <- fix (eltsSS gp)] / fromInteger (orderSS gp)
fix gs = let n = maximum [length xs | PL xs <- gs]
in map (\g -> if g == PL [] then PL [1..n] else g) gs
countingPoly gp vs = substMP (cycleIndexGp gp) [sum [v^i | v <- vs] | i <- [0..]]
polyaCount' gp vs = evalMP (countingPoly gp vs) (repeat 1)
polyaCount gp vs = sum [c | (c,as) <- termsMP (countingPoly gp vs)]
-- COUNTING NON-ISOMORPHIC GRAPHS
toEdge (a,b) = if a < b then (a,b) else (b,a)
(a,b) -^ g = toEdge (a .^ g, b .^ g) -- action on edge induced from action on points
edges :: [(Int,Int)]
edges = doEdges 2
where doEdges n = [(i,n) | i <- [1..n-1]] ++ doEdges (n+1)
numEdgesKn n = fromInteger (toInteger n `choose` 2)
edgesKn n = take (numEdgesKn n) edges
edgeToPoint (a,b) = (b-2)*(b-1) `div` 2 + a
pointToEdge c = edges !! (c-1)
-- given an elt of Sn, return the induced action on the edges of Kn
inducedPermutation n g = PL [edgeToPoint (edge -^ g) | edge <- edgesKn n]
generatorsEdgeGp n = map (inducedPermutation n) (generatorsSn n)
edgeGp n = schreierSimsTransversals m (generatorsEdgeGp n)
where m = numEdgesKn n
{-
partitions n = boundedPartitions n n
where boundedPartitions n k -- partitions of n where the parts are bounded to be <= k
| n <= 0 = [[]]
| k == 0 = []
| k > n = boundedPartitions n (k-1)
| otherwise = map (k:) (boundedPartitions (n-k) k) ++ boundedPartitions n (k-1)
-}
cycleTypesSn n = doCycleTypes n n [[]]
where doCycleTypes n 1 types = map (n:) types
doCycleTypes n i types = concat [doCycleTypes (n-a*i) (i-1) (map (a:) types) | a <- [0..n `div` i] ]
-- the argument is [a_1, ..., a_n], where we're asking about elements with cycle structure 1^a_1 ... n^a_n
numEltsWithCycleType n as = (factorial n) `div` product [i^a * factorial a | (i,a) <- zip [1..] as]
cycleIndexSn n = sum [fromInteger (numEltsWithCycleType n as) * monomial as | as <- cycleTypesSn n] / fromInteger (factorial n)
-- given n, and a cycle type for Sn, calculate the induced cycle index on the edges of Kn
inducedCycleType :: Int -> [Int] -> [Int]
inducedCycleType n as =
let cyclePowers = [(i,a) | (i,a) <- zip [1..] as, a /= 0]
withinCycles = [(i, (i-1) `div` 2 * a) | (i,a) <- cyclePowers] -- each cycle induces a cycle on edges within the cycle
++ [(i `div` 2,a) | (i,a) <- cyclePowers, even i] -- but in the even case, the edge joining opposite points of the cycle has half the period
acrossCycles = [(lcm i j, a * b * gcd i j) | (i,a) <- cyclePowers, (j,b) <- cyclePowers, i < j] -- if the points of an edge fall in cycles of different length, the period of the cycle on the edge is the gcd
++ [(i, i * (a * (a-1) `div` 2)) | (i,a) <- cyclePowers, a > 1] -- when the points of an edge fall in different cycles of the same length, the cycle on the edge also has this length
-- there are (a `choose` 2) choices for pairs of cycles, and given a pair, there are i choices for edges
in collectPowers (withinCycles ++ acrossCycles) -- withinCycles $+ collectPowers acrossCycles
where collectPowers powers = [sum [a | (i,a) <- powers, i == j] | j <- [1..numEdgesKn n]] -- can be done more efficiently
inducedCycleIndex n as =
let cyclePowers = [(i,a) | (i,a) <- zip [1..] as, a /= 0]
withinCycles = [(i, (i-1) `div` 2 * a) | (i,a) <- cyclePowers, i > 1] -- each cycle induces a cycle on edges within the cycle
++ [(i `div` 2,a) | (i,a) <- cyclePowers, even i] -- but in the even case, the edge joining opposite points of the cycle has half the period
acrossCycles = [(lcm i j, a * b * gcd i j) | (i,a) <- cyclePowers, (j,b) <- cyclePowers, i < j] -- if the points of an edge fall in cycles of different length, the period of the cycle on the edge is the gcd
++ [(i, i * (a * (a-1) `div` 2)) | (i,a) <- cyclePowers, a > 1] -- when the points of an edge fall in different cycles of the same length, the cycle on the edge also has this length
-- there are (a `choose` 2) choices for pairs of cycles, and given a pair, there are i choices for edges
in product [x_ i ^ a | (i,a) <- withinCycles ++ acrossCycles]
inducedCycleIndexSn n = sum [fromInteger (numEltsWithCycleType n as) * inducedCycleIndex n as | as <- cycleTypesSn n] / fromInteger (factorial n)
graphCountingPoly n = substMP (inducedCycleIndexSn n) [1+t^i | i <- [0..]]
| nfjinjing/bench-euler | src/Math/PolyaCounting.hs | bsd-3-clause | 5,948 | 0 | 17 | 1,476 | 1,998 | 1,113 | 885 | 57 | 2 |
module Scurry.Comm.Message(
ScurryMsg(..),
) where
import Control.Monad
import Data.Binary
import qualified Data.ByteString as BSS
import Data.Word
import Scurry.Types.Network
import Scurry.Peer
type PingID = Word32
-- |These are the messages we get across the network.
-- They are the management and data protocol.
data ScurryMsg = SFrame BSS.ByteString -- | An ethernet frame.
| SJoin PeerRecord -- | A network join request.
| SJoinReply PeerRecord [EndPoint] -- | A network join reply.
| SKeepAlive PeerRecord -- | A keep alive message.
| SNotifyPeer EndPoint -- | A message to notify others of a peer.
| SRequestPeer -- | A message to request peer listings on the network.
| SPing PingID -- | A Ping command used for diagnostics.
| SEcho PingID -- | A Echo command used to respond to the Ping command.
| SLANProbe -- | A message to probe the local LAN for other members.
| SLANSuggest ScurryPort -- | A message to inform a peer that they may share a LAN with another.
| SAddrRequest -- | A message to request an available VPN address
-- | SAddrReject -- | A message to reject the address a peer has chosen
| SAddrPropose ScurryAddress ScurryMask -- | A message to suggest an address to a peer
-- | SAddrSelect ScurryAddress -- | A message to inform every one we're using an address
| SUnknown -- | An unknown message
deriving (Show)
instance Binary ScurryMsg where
get = do tag <- getWord8
case tag of
0 -> liftM SFrame get -- SFrame
1 -> liftM SJoin get -- SJoin
2 -> liftM2 SJoinReply get get -- SJoinReply
3 -> liftM SKeepAlive get -- SKeepAlive
4 -> liftM SNotifyPeer get -- SNotifyPeer
5 -> return SRequestPeer -- SRequestPeer
6 -> liftM SPing get -- SPing
7 -> liftM SEcho get -- SEcho
8 -> return SLANProbe -- SLANProbe
9 -> liftM SLANSuggest get -- SLANSuggest
10 -> return SAddrRequest -- SAddrRequest
-- 11 -> return SAddrReject -- SAddrReject
12 -> liftM2 SAddrPropose get get -- SAddrPropose
-- 13 -> get >>= (return . SAddrSelect) -- SAddrSelect
_ -> return SUnknown -- Unknown Message
put (SFrame fp) = putWord8 0 >> put fp
put (SJoin m) = putWord8 1 >> put m
put (SJoinReply m p) = putWord8 2 >> put m >> put p
put (SKeepAlive r) = putWord8 3 >> put r
put (SNotifyPeer p) = putWord8 4 >> put p
put SRequestPeer = putWord8 5
put (SPing pp) = putWord8 6 >> put pp
put (SEcho pe) = putWord8 7 >> put pe
put SLANProbe = putWord8 8
put (SLANSuggest ps) = putWord8 9 >> put ps
put SAddrRequest = putWord8 10
-- put SAddrReject = putWord8 11
put (SAddrPropose a m) = putWord8 12 >> put a >> put m
-- put (SAddrSelect p) = putWord8 13 >> put p
put SUnknown = putWord8 255
| dmagyar/scurry | src/Scurry/Comm/Message.hs | bsd-3-clause | 3,581 | 0 | 11 | 1,475 | 612 | 321 | 291 | 52 | 0 |
{-# LANGUAGE RankNTypes #-}
{-
Copyright (C) 2012-2017 Kacper Bak, Jimmy Liang, Michal Antkiewicz <http://gsd.uwaterloo.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-}
{- |
This is in a separate module from the module "Language.Clafer" so that other modules that require
ClaferEnv can just import this module without all the parsing/compiline/generating functionality.
-}
module Language.ClaferT
( ClaferEnv(..)
, irModuleTrace
, uidIClaferMap
, makeEnv
, getAst
, getIr
, ClaferM
, ClaferT
, CErr(..)
, CErrs(..)
, ClaferErr
, ClaferErrs
, ClaferSErr
, ClaferSErrs
, ErrPos(..)
, PartialErrPos(..)
, throwErrs
, throwErr
, catchErrs
, getEnv
, getsEnv
, modifyEnv
, putEnv
, runClafer
, runClaferT
, Throwable(..)
, Span(..)
, Pos(..)
) where
import Control.Monad.Except
import Control.Monad.Identity
import Control.Monad.State
import Data.List
import qualified Data.Map as Map
import Language.Clafer.ClaferArgs
import Language.Clafer.Common
import Language.Clafer.Front.AbsClafer
import Language.Clafer.Front.LexClafer
import Language.Clafer.Intermediate.Intclafer
import Language.Clafer.Intermediate.Tracing
{-
- Examples.
-
- If you need ClaferEnv:
- runClafer args $
- do
- env <- getEnv
- env' = ...
- putEnv env'
-
- Remember to putEnv if you do any modification to the ClaferEnv or else your updates
- are lost!
-
-
- Throwing errors:
-
- throwErr $ ParseErr (ErrFragPos fragId fragPos) "failed parsing"
- throwErr $ ParseErr (ErrModelPos modelPos) "failed parsing"
-
- There is two ways of defining the position of the error. Either define the position
- relative to a fragment, or relative to the model. Pick the one that is convenient.
- Once thrown, the "partial" positions will be automatically updated to contain both
- the model and fragment positions.
- Use throwErrs to throw multiple errors.
- Use catchErrs to catch errors (usually not needed).
-
-}
data ClaferEnv
= ClaferEnv
{ args :: ClaferArgs
, modelFrags :: [String] -- original text of the model fragments
, cAst :: Maybe Module
, cIr :: Maybe (IModule, GEnv, Bool)
, frags :: [Pos] -- line numbers of fragment markers
, astModuleTrace :: Map.Map Span [Ast] -- can keep the Ast map since it never changes
, otherTokens :: [Token] -- non-parseable tokens: comments and escape blocks
} deriving Show
-- | This simulates a field in the ClaferEnv that will always recompute the map,
-- since the IR always changes and the map becomes obsolete
irModuleTrace :: ClaferEnv -> Map.Map Span [Ir]
irModuleTrace env = traceIrModule $ getIModule $ cIr env
where
getIModule (Just (imodule, _, _)) = imodule
getIModule Nothing = error "BUG: irModuleTrace: cannot request IR map before desugaring."
-- | This simulates a field in the ClaferEnv that will always recompute the map,
-- since the IR always changes and the map becomes obsolete
-- maps from a UID to an IClafer with the given UID
uidIClaferMap :: ClaferEnv -> UIDIClaferMap
uidIClaferMap env = createUidIClaferMap $ getIModule $ cIr env
where
getIModule (Just (iModule, _, _)) = iModule
getIModule Nothing = error "BUG: uidIClaferMap: cannot request IClafer map before desugaring."
getAst :: (Monad m) => ClaferT m Module
getAst = do
env <- getEnv
case cAst env of
(Just a) -> return a
_ -> throwErr (ClaferErr "No AST. Did you forget to add fragments or parse?" :: CErr Span) -- Indicates a bug in the Clafer translator.
getIr :: (Monad m) => ClaferT m (IModule, GEnv, Bool)
getIr = do
env <- getEnv
case cIr env of
(Just i) -> return i
_ -> throwErr (ClaferErr "No IR. Did you forget to compile?" :: CErr Span) -- Indicates a bug in the Clafer translator.
makeEnv :: ClaferArgs -> ClaferEnv
makeEnv args' =
ClaferEnv
{ args = args''
, modelFrags = []
, cAst = Nothing
, cIr = Nothing
, frags = []
, astModuleTrace = Map.empty
, otherTokens = []
}
where
args'' = if (CVLGraph `elem` (mode args') ||
Html `elem` (mode args') ||
Graph `elem` (mode args'))
then args'{keep_unused=True}
else args'
-- | Monad for using Clafer.
type ClaferM = ClaferT Identity
-- | Monad Transformer for using Clafer.
type ClaferT m = ExceptT ClaferErrs (StateT ClaferEnv m)
type ClaferErr = CErr ErrPos
type ClaferErrs = CErrs ErrPos
type ClaferSErr = CErr Span
type ClaferSErrs = CErrs Span
-- | Possible errors that can occur when using Clafer
-- | Generate errors using throwErr/throwErrs:
data CErr p
-- | Generic error
= ClaferErr
{ msg :: String
}
-- | Error generated by the parser
| ParseErr
{ pos :: p -- ^ Position of the error
, msg :: String
}
-- | Error generated by semantic analysis
| SemanticErr
{ pos :: p
, msg :: String
}
deriving Show
-- | Clafer keeps track of multiple errors.
data CErrs p =
ClaferErrs {errs :: [CErr p]}
deriving Show
data ErrPos =
ErrPos {
-- | The fragment where the error occurred.
fragId :: Int,
-- | Error positions are relative to their fragments.
-- | For example an error at (Pos 2 3) means line 2 column 3 of the fragment, not the entire model.
fragPos :: Pos,
-- | The error position relative to the model.
modelPos :: Pos
}
deriving Show
-- | The full ErrPos requires lots of information that needs to be consistent. Every time we throw an error,
-- | we need BOTH the (fragId, fragPos) AND modelPos. This makes it easier for developers using ClaferT so they
-- | only need to provide part of the information and the rest is automatically calculated. The code using
-- | ClaferT is more concise and less error-prone.
-- |
-- | modelPos <- modelPosFromFragPos fragdId fragPos
-- | throwErr $ ParserErr (ErrPos fragId fragPos modelPos)
-- |
-- | vs
-- |
-- | throwErr $ ParseErr (ErrFragPos fragId fragPos)
-- |
-- | Hopefully making the error handling easier will make it more universal.
data PartialErrPos =
-- | Position relative to the start of the fragment. Will calculate model position automatically.
-- | fragId starts at 0
-- | The position is relative to the start of the fragment.
ErrFragPos {
pFragId :: Int,
pFragPos :: Pos
} |
ErrFragSpan {
pFragId :: Int,
pFragSpan :: Span
} |
-- | Position relative to the start of the complete model. Will calculate fragId and fragPos automatically.
-- | The position is relative to the entire complete model.
ErrModelPos {
pModelPos :: Pos
}
|
ErrModelSpan {
pModelSpan :: Span
}
deriving Show
class ClaferErrPos p where
toErrPos :: Monad m => p -> ClaferT m ErrPos
instance ClaferErrPos Span where
toErrPos = toErrPos . ErrModelSpan
instance ClaferErrPos ErrPos where
toErrPos = return . id
instance ClaferErrPos PartialErrPos where
toErrPos (ErrFragPos frgId frgPos) =
do
f <- getsEnv frags
let pos' = ((Pos 1 1 : f) !! frgId) `addPos` frgPos
return $ ErrPos frgId frgPos pos'
toErrPos (ErrFragSpan frgId (Span frgPos _)) = toErrPos $ ErrFragPos frgId frgPos
toErrPos (ErrModelPos modelPos') =
do
f <- getsEnv frags
let fragSpans = zipWith Span (Pos 1 1 : f) f
case findFrag modelPos' fragSpans of
Just (frgId, Span fragStart _) -> return $ ErrPos frgId (modelPos' `minusPos` fragStart) modelPos'
Nothing -> return $ ErrPos 1 noPos noPos -- error $ show modelPos' ++ " not within any frag spans: " ++ show fragSpans -- Indicates a bug in the Clafer translator
where
findFrag pos'' spans =
find (inSpan pos'' . snd) (zip [0..] spans)
toErrPos (ErrModelSpan (Span modelPos'' _)) = toErrPos $ ErrModelPos modelPos''
class Throwable t where
toErr :: t -> Monad m => ClaferT m ClaferErr
instance ClaferErrPos p => Throwable (CErr p) where
toErr (ClaferErr mesg) = return $ ClaferErr mesg
toErr err =
do
pos' <- toErrPos $ pos err
return $ err{pos = pos'}
-- | Throw many errors.
throwErrs :: (Monad m, Throwable t) => [t] -> ClaferT m a
throwErrs throws =
do
errors <- mapM toErr throws
throwError $ ClaferErrs errors
-- | Throw one error.
throwErr :: (Monad m, Throwable t) => t -> ClaferT m a
throwErr throw = throwErrs [throw]
-- | Catch errors
catchErrs :: Monad m => ClaferT m a -> ([ClaferErr] -> ClaferT m a) -> ClaferT m a
catchErrs e h = e `catchError` (h . errs)
addPos :: Pos -> Pos -> Pos
addPos (Pos l c) (Pos 1 d) = Pos l (c + d - 1) -- Same line
addPos (Pos l _) (Pos m d) = Pos (l + m - 1) d -- Different line
minusPos :: Pos -> Pos -> Pos
minusPos (Pos l c) (Pos 1 d) = Pos l (c - d + 1) -- Same line
minusPos (Pos l c) (Pos m _) = Pos (l - m + 1) c -- Different line
inSpan :: Pos -> Span -> Bool
inSpan pos' (Span start end) = pos' >= start && pos' <= end
-- | Get the ClaferEnv
getEnv :: Monad m => ClaferT m ClaferEnv
getEnv = get
getsEnv :: Monad m => (ClaferEnv -> a) -> ClaferT m a
getsEnv = gets
-- | Modify the ClaferEnv
modifyEnv :: Monad m => (ClaferEnv -> ClaferEnv) -> ClaferT m ()
modifyEnv = modify
-- | Set the ClaferEnv. Remember to set the env after every change.
putEnv :: Monad m => ClaferEnv -> ClaferT m ()
putEnv = put
-- | Uses the ErrorT convention:
-- | Left is for error (a string containing the error message)
-- | Right is for success (with the result)
runClaferT :: Monad m => ClaferArgs -> ClaferT m a -> m (Either [ClaferErr] a)
runClaferT args' exec =
mapLeft errs `liftM` evalStateT (runExceptT exec) (makeEnv args')
where
mapLeft :: (a -> c) -> Either a b -> Either c b
mapLeft f (Left l) = Left (f l)
mapLeft _ (Right r) = Right r
-- | Convenience
runClafer :: ClaferArgs -> ClaferM a -> Either [ClaferErr] a
runClafer args' = runIdentity . runClaferT args'
| gsdlab/clafer | src/Language/ClaferT.hs | mit | 11,024 | 0 | 16 | 2,628 | 2,214 | 1,218 | 996 | 187 | 2 |
module VersionInfo where
import LibBladeRF.LibBladeRF
import LibBladeRF.Utils
import LibBladeRF.Types
main = withBladeRF $ \dev -> do
libVersion <- bladeRFLibVersion
fwVersion <- bladeRFFwVersion dev
fpgaVersion <- bladeRFFPGAVersion dev
putStrLn $ " libbladeRF version: " ++ (show libVersion)
putStrLn $ " Firmware version: " ++ (show fwVersion)
putStrLn $ " FPGA version: " ++ (show fpgaVersion)
| adamwalker/hlibBladeRF | examples/version/VersionInfo.hs | lgpl-2.1 | 413 | 0 | 11 | 69 | 111 | 55 | 56 | 11 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
-- | High-level scenarios which can be launched.
module Pos.Launcher.Scenario
( runNode
, runNode'
, nodeStartMsg
) where
import Universum
import qualified Data.HashMap.Strict as HM
import Formatting (bprint, build, int, sformat, shown, (%))
import Serokell.Util (listJson)
import Pos.Chain.Genesis as Genesis (Config (..),
GenesisDelegation (..), GenesisWStakeholders (..),
configBootStakeholders, configFtsSeed,
configHeavyDelegation)
import Pos.Chain.Txp (TxpConfiguration, bootDustThreshold)
import Pos.Chain.Update (UpdateConfiguration, curSoftwareVersion,
lastKnownBlockVersion, ourSystemTag)
import Pos.Context (NodeContext (..), getOurPublicKey, npSecretKey)
import Pos.Core (addressHash)
import Pos.Core.Conc (mapConcurrently)
import Pos.Crypto (pskDelegatePk, toPublic)
import qualified Pos.DB.BlockIndex as DB
import qualified Pos.GState as GS
import Pos.Infra.Diffusion.Types (Diffusion)
import Pos.Infra.Reporting (reportError)
import Pos.Infra.Slotting (waitSystemStart)
import Pos.Infra.Util.LogSafe (logInfoS)
import Pos.Launcher.Resource (NodeResources (..))
import Pos.Util.AssertMode (inAssertMode)
import Pos.Util.CompileInfo (HasCompileInfo, compileInfo)
import Pos.Util.Util (HasLens', lensOf)
import Pos.Util.Wlog (WithLogger, askLoggerName, logInfo)
import Pos.Worker (allWorkers)
import Pos.WorkMode.Class (WorkMode)
-- | Entry point of full node.
-- Initialization, running of workers, running of plugins.
runNode'
:: forall ext ctx m.
( HasCompileInfo
, WorkMode ctx m
)
=> Genesis.Config
-> NodeResources ext
-> [ (Text, Diffusion m -> m ()) ]
-> [ (Text, Diffusion m -> m ()) ]
-> Diffusion m -> m ()
runNode' genesisConfig NodeResources {..} workers' plugins' = \diffusion -> do
logInfo $ "Built with: " <> pretty compileInfo
nodeStartMsg
inAssertMode $ logInfo "Assert mode on"
pk <- getOurPublicKey
let pkHash = addressHash pk
logInfoS $ sformat ("My public key is: "%build%", pk hash: "%build)
pk pkHash
let genesisStakeholders = configBootStakeholders genesisConfig
logInfo $ sformat
("Genesis stakeholders ("%int%" addresses, dust threshold "%build%"): "%build)
(length $ getGenesisWStakeholders genesisStakeholders)
(bootDustThreshold genesisStakeholders)
genesisStakeholders
let genesisDelegation = configHeavyDelegation genesisConfig
let formatDlgPair (issuerId, delegateId) =
bprint (build%" -> "%build) issuerId delegateId
logInfo $ sformat ("GenesisDelegation (stakeholder ids): "%listJson)
$ map (formatDlgPair . second (addressHash . pskDelegatePk))
$ HM.toList
$ unGenesisDelegation genesisDelegation
firstGenesisHash <- GS.getFirstGenesisBlockHash $ configGenesisHash
genesisConfig
logInfo $ sformat
("First genesis block hash: "%build%", genesis seed is "%build)
firstGenesisHash
(configFtsSeed genesisConfig)
tipHeader <- DB.getTipHeader
logInfo $ sformat ("Current tip header: "%build) tipHeader
waitSystemStart
let
runWithReportHandler :: (Text, Diffusion m -> m ()) -> m ()
runWithReportHandler (workerName, action) = action diffusion `catch` (reportHandler workerName)
void (mapConcurrently runWithReportHandler (workers' ++ plugins'))
exitFailure
where
reportHandler :: Text -> SomeException -> m b
reportHandler action (SomeException e) = do
loggerName <- askLoggerName
let msg = "Worker/plugin with work name "%shown%" and logger name "%shown%" failed with exception: "%shown
reportError $ sformat msg action loggerName e
exitFailure
-- | Entry point of full node.
-- Initialization, running of workers, running of plugins.
runNode
:: ( HasCompileInfo
, WorkMode ctx m
)
=> Genesis.Config
-> TxpConfiguration
-> NodeResources ext
-> [ (Text, Diffusion m -> m ()) ]
-> Diffusion m -> m ()
runNode genesisConfig txpConfig nr plugins =
runNode' genesisConfig nr workers' plugins
where workers' = allWorkers sid genesisConfig txpConfig nr
sid = addressHash . toPublic . npSecretKey . ncNodeParams . nrContext
$ nr
-- | This function prints a very useful message when node is started.
nodeStartMsg
:: (MonadReader r m, HasLens' r UpdateConfiguration, WithLogger m)
=> m ()
nodeStartMsg = do
uc <- view (lensOf @UpdateConfiguration)
logInfo (msg uc)
where
msg uc = sformat ("Application: " %build% ", last known block version "
%build% ", systemTag: " %build)
(curSoftwareVersion uc)
(lastKnownBlockVersion uc)
(ourSystemTag uc)
| input-output-hk/cardano-sl | lib/src/Pos/Launcher/Scenario.hs | apache-2.0 | 5,177 | 0 | 16 | 1,358 | 1,256 | 676 | 580 | -1 | -1 |
{-
Copyright 2012 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# LANGUAGE OverloadedStrings #-}
module Plush.Server.Utilities (
-- * Responses
notFound, badRequest,
respApp,
-- * JSON Applications
JsonApplication,
jsonApp,
returnJson, returnResponse,
-- * Keyed Applications
KeyedRequest,
keyedApp,
)
where
import qualified Blaze.ByteString.Builder.ByteString as B
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero)
import Data.Aeson
import Network.HTTP.Types
import Network.Wai
-- | 404 \"File not found\"
notFound :: Response
notFound = responseLBS status404
[ ("Content-Type", "text/plain") ] "File not found"
-- | 400 \"Bad Request\"
badRequest :: Response
badRequest = responseLBS status400
[ ("Content-Type", "text/plain") ] "Bad request"
-- | An application that returns a fixed response no matter the request.
respApp :: Response -> Application
respApp resp _ = ($ resp)
-- | Like 'Application', but takes a request type @/a/@ and returns a response
-- type @/b/@.
--
-- Both types are indended to be trasmitted as JSON, so @/a/@ should be an
-- instance of 'FromJSON', and @/b/@ should be an instance of 'ToJSON'.
--
-- The actual type returns @'Either' 'Response' /b/@ so that if an error
-- occurs, the application can return an error response of some sort, rather
-- than JSON.
type JsonApplication a b = a -> IO (Either Response b)
-- | Transforms a 'JsonApplication' into an 'Application'. If a value of type
-- @/a/@ cannot be parsed from the JSON in the request, then 'badRequest'
-- results.
jsonApp :: (FromJSON a, ToJSON b) => JsonApplication a b -> Application
jsonApp jApp req respond = do
body <- strictRequestBody req
case decode body of
Nothing -> respond badRequest
Just a -> jApp a >>= respond . either id jsonResponse
where
jsonResponse =
responseBuilder status200 [ ("Content-Type", "application/json") ]
. B.fromLazyByteString . encode
-- | Utility for returning a JSON response in a JsonApplication
returnJson :: (ToJSON b) => b -> IO (Either Response b)
returnJson = return . Right
-- | Utility for returning 'Response' response in a JsonApplication
returnResponse :: (ToJSON b) => Response -> IO (Either Response b)
returnResponse = return . Left
-- | A request with the form @{ key: /k/, req: /r/ }@, where @/r/@ is an
-- inner request.
data KeyedRequest a = KeyedRequest String a
instance (FromJSON a) => FromJSON (KeyedRequest a) where
parseJSON (Object v) = KeyedRequest <$> v .: "key" <*> v .: "req"
parseJSON _ = mzero
-- | Transforms a 'JsonApplication' into one that takes a 'KeyedRequest'.
-- The first argument is the /key/, and if it matches the key in the request
-- then the inner value is passed on to the inner application. Otherwise,
-- a 'badRequest' results.
keyedApp :: (FromJSON a, ToJSON b) => String -> JsonApplication a b
-> JsonApplication (KeyedRequest a) b
keyedApp key jApp (KeyedRequest key' a) | key' == key = jApp a
keyedApp _ _ _ = returnResponse badRequest
| mzero/plush | src/Plush/Server/Utilities.hs | apache-2.0 | 3,631 | 0 | 12 | 729 | 583 | 328 | 255 | 45 | 2 |
{-# LANGUAGE BangPatterns #-}
-- This is a non-exposed internal module
--
-- The code in this module has been ripped from containers-0.5.5.1:Data.Map.Base [1] almost
-- verbatimely to avoid a dependency of 'template-haskell' on the containers package.
--
-- [1] see https://hackage.haskell.org/package/containers-0.5.5.1
--
-- The original code is BSD-licensed and copyrighted by Daan Leijen, Andriy Palamarchuk, et al.
module Language.Eta.Meta.Lib.Map
( Map
, empty
, insert
, Eta.REPL.Map.lookup
) where
import Eta.REPL.Map
| rahulmutt/ghcvm | libraries/eta-meta/Language/Eta/Meta/Lib/Map.hs | bsd-3-clause | 549 | 0 | 5 | 95 | 42 | 32 | 10 | 7 | 0 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Data/ByteString/Lazy/Builder/Extras.hs" #-}
-- | We decided to rename the Builder modules. Sorry about that.
--
-- The old names will hang about for at least once release cycle before we
-- deprecate them and then later remove them.
--
module Data.ByteString.Lazy.Builder.Extras (
module Data.ByteString.Builder.Extra
) where
import Data.ByteString.Builder.Extra
| phischu/fragnix | tests/packages/scotty/Data.ByteString.Lazy.Builder.Extras.hs | bsd-3-clause | 406 | 0 | 5 | 59 | 33 | 26 | 7 | 5 | 0 |
{-# LANGUAGE RecordWildCards #-}
-- | Build configuration
module Stack.Config.Build where
import Data.Maybe
import Data.Monoid.Extra
import Stack.Types.Config
-- | Interprets BuildOptsMonoid options.
buildOptsFromMonoid :: BuildOptsMonoid -> BuildOpts
buildOptsFromMonoid BuildOptsMonoid{..} = BuildOpts
{ boptsLibProfile = fromFirst
(boptsLibProfile defaultBuildOpts)
(buildMonoidLibProfile <>
First (if tracing || profiling then Just True else Nothing))
, boptsExeProfile = fromFirst
(boptsExeProfile defaultBuildOpts)
(buildMonoidExeProfile <>
First (if tracing || profiling then Just True else Nothing))
, boptsLibStrip = fromFirst
(boptsLibStrip defaultBuildOpts)
(buildMonoidLibStrip <>
First (if noStripping then Just False else Nothing))
, boptsExeStrip = fromFirst
(boptsExeStrip defaultBuildOpts)
(buildMonoidExeStrip <>
First (if noStripping then Just False else Nothing))
, boptsHaddock = fromFirst
(boptsHaddock defaultBuildOpts)
buildMonoidHaddock
, boptsHaddockOpts = haddockOptsFromMonoid buildMonoidHaddockOpts
, boptsOpenHaddocks = fromFirst
(boptsOpenHaddocks defaultBuildOpts)
buildMonoidOpenHaddocks
, boptsHaddockDeps = getFirst buildMonoidHaddockDeps
, boptsHaddockInternal = fromFirst
(boptsHaddockInternal defaultBuildOpts)
buildMonoidHaddockInternal
, boptsHaddockHyperlinkSource = fromFirst
(boptsHaddockHyperlinkSource defaultBuildOpts)
buildMonoidHaddockHyperlinkSource
, boptsInstallExes = fromFirst
(boptsInstallExes defaultBuildOpts)
buildMonoidInstallExes
, boptsPreFetch = fromFirst
(boptsPreFetch defaultBuildOpts)
buildMonoidPreFetch
, boptsKeepGoing = getFirst buildMonoidKeepGoing
, boptsForceDirty = fromFirst
(boptsForceDirty defaultBuildOpts)
buildMonoidForceDirty
, boptsTests = fromFirst (boptsTests defaultBuildOpts) buildMonoidTests
, boptsTestOpts =
testOptsFromMonoid buildMonoidTestOpts additionalArgs
, boptsBenchmarks = fromFirst
(boptsBenchmarks defaultBuildOpts)
buildMonoidBenchmarks
, boptsBenchmarkOpts =
benchmarkOptsFromMonoid buildMonoidBenchmarkOpts additionalArgs
, boptsReconfigure = fromFirst
(boptsReconfigure defaultBuildOpts)
buildMonoidReconfigure
, boptsCabalVerbose = fromFirst
(boptsCabalVerbose defaultBuildOpts)
buildMonoidCabalVerbose
, boptsSplitObjs = fromFirst
(boptsSplitObjs defaultBuildOpts)
buildMonoidSplitObjs
}
where
-- These options are not directly used in bopts, instead they
-- transform other options.
tracing = getAny buildMonoidTrace
profiling = getAny buildMonoidProfile
noStripping = getAny buildMonoidNoStrip
-- Additional args for tracing / profiling
additionalArgs =
if tracing || profiling
then Just $ "+RTS" : catMaybes [trac, prof, Just "-RTS"]
else Nothing
trac =
if tracing
then Just "-xc"
else Nothing
prof =
if profiling
then Just "-p"
else Nothing
haddockOptsFromMonoid :: HaddockOptsMonoid -> HaddockOpts
haddockOptsFromMonoid HaddockOptsMonoid{..} =
defaultHaddockOpts
{hoAdditionalArgs = hoMonoidAdditionalArgs}
testOptsFromMonoid :: TestOptsMonoid -> Maybe [String] -> TestOpts
testOptsFromMonoid TestOptsMonoid{..} madditional =
defaultTestOpts
{ toRerunTests = fromFirst (toRerunTests defaultTestOpts) toMonoidRerunTests
, toAdditionalArgs = fromMaybe [] madditional <> toMonoidAdditionalArgs
, toCoverage = fromFirst (toCoverage defaultTestOpts) toMonoidCoverage
, toDisableRun = fromFirst (toDisableRun defaultTestOpts) toMonoidDisableRun
}
benchmarkOptsFromMonoid :: BenchmarkOptsMonoid -> Maybe [String] -> BenchmarkOpts
benchmarkOptsFromMonoid BenchmarkOptsMonoid{..} madditional =
defaultBenchmarkOpts
{ beoAdditionalArgs =
fmap (\args -> unwords args <> " ") madditional <>
getFirst beoMonoidAdditionalArgs
, beoDisableRun = fromFirst
(beoDisableRun defaultBenchmarkOpts)
beoMonoidDisableRun
}
| mrkkrp/stack | src/Stack/Config/Build.hs | bsd-3-clause | 4,419 | 0 | 13 | 1,083 | 801 | 432 | 369 | 99 | 8 |
module Comment00004 where
dropBitMask xs
| t = 1
-- | otherwise = go
| charleso/intellij-haskforce | tests/gold/parser/Comment00004.hs | apache-2.0 | 80 | 0 | 7 | 25 | 19 | 10 | 9 | 3 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Network.MPD.Applicative.ConnectionSpec (main, spec) where
import TestUtil
import Network.MPD.Applicative.Connection
import Network.MPD.Applicative.Database
import Network.MPD.Applicative.PlaybackControl
import Network.MPD.Core
import Network.MPD.Commands.Types
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "password" $ do
it "sends a password" $ do
password "foo"
`with` [("password foo", Right "OK")]
`shouldBe` Right ()
it "authenticates a session" $ do
let convo = [("lsinfo \"/\""
, Right "ACK [4@0] {play} you don't have \
\permission for \"play\"")
,("password foo", Right "OK")
,("lsinfo \"/\"", Right "directory: /bar\nOK")]
expected_resp = Right [LsDirectory "/bar"]
cmd_in = lsInfo "/"
withPassword "foo" convo cmd_in `shouldBe` expected_resp
it "fails if the password is incorrect" $ do
let convo = [("play"
, Right "ACK [4@0] {play} you don't have \
\permission for \"play\"")
,("password foo"
, Right "ACK [3@0] {password} incorrect password")]
expected_resp =
Left $ ACK InvalidPassword " incorrect password"
cmd_in = play Nothing
withPassword "foo" convo cmd_in `shouldBe` expected_resp
describe "ping" $ do
it "sends a ping" $ do
ping `with` [("ping", Right "OK")] `shouldBe` Right ()
| bens/libmpd-haskell | tests/Network/MPD/Applicative/ConnectionSpec.hs | lgpl-2.1 | 1,771 | 0 | 18 | 682 | 363 | 195 | 168 | 37 | 1 |
{-# LANGUAGE RecordWildCards #-}
module Test.Haddock
( module Test.Haddock.Config
, runAndCheck, runHaddock, checkFiles
) where
import Control.Monad
import Data.Maybe
import System.Directory
import System.Exit
import System.FilePath
import System.IO
import System.Process
import qualified Data.ByteString.Char8 as BS
import Test.Haddock.Config
import Test.Haddock.Process
import Test.Haddock.Utils
data CheckResult
= Fail
| Pass
| NoRef
| Error String
| Accepted
deriving Eq
runAndCheck :: Config c -> IO ()
runAndCheck cfg = do
runHaddock cfg
checkFiles cfg
checkFiles :: Config c -> IO ()
checkFiles cfg@(Config { .. }) = do
putStrLn "Testing output files..."
files <- ignore <$> getDirectoryTree (cfgOutDir cfg)
failed <- liftM catMaybes . forM files $ \file -> do
putStr $ "Checking \"" ++ file ++ "\"... "
status <- maybeAcceptFile cfg file =<< checkFile cfg file
case status of
Fail -> putStrLn "FAIL" >> (return $ Just file)
Pass -> putStrLn "PASS" >> (return Nothing)
NoRef -> putStrLn "PASS [no .ref]" >> (return Nothing)
Error msg -> putStrLn ("ERROR (" ++ msg ++ ")") >> return Nothing
Accepted -> putStrLn "ACCEPTED" >> return Nothing
if null failed
then do
putStrLn "All tests passed!"
exitSuccess
else do
maybeDiff cfg failed
exitFailure
where
ignore = filter (not . dcfgCheckIgnore cfgDirConfig)
maybeDiff :: Config c -> [FilePath] -> IO ()
maybeDiff (Config { cfgDiffTool = Nothing }) _ = pure ()
maybeDiff cfg@(Config { cfgDiffTool = (Just diff) }) files = do
putStrLn "Diffing failed cases..."
forM_ files $ diffFile cfg diff
runHaddock :: Config c -> IO ()
runHaddock cfg@(Config { .. }) = do
createEmptyDirectory $ cfgOutDir cfg
putStrLn "Generating documentation..."
forM_ cfgPackages $ \tpkg -> do
haddockStdOut <- openFile cfgHaddockStdOut WriteMode
let pc = processConfig
{ pcArgs = concat
[ cfgHaddockArgs
, pure $ "--odir=" ++ outDir cfgDirConfig tpkg
, tpkgFiles tpkg
]
, pcEnv = Just $ cfgEnv
, pcStdOut = Just $ haddockStdOut
}
handle <- runProcess' cfgHaddockPath pc
waitForSuccess "Failed to run Haddock on specified test files" handle
checkFile :: Config c -> FilePath -> IO CheckResult
checkFile cfg file = do
hasRef <- doesFileExist $ refFile dcfg file
if hasRef
then do
mout <- readOut cfg file
mref <- readRef cfg file
return $ case (mout, mref) of
(Just out, Just ref)
| ccfgEqual ccfg out ref -> Pass
| otherwise -> Fail
_ -> Error "Failed to parse input files"
else return NoRef
where
ccfg = cfgCheckConfig cfg
dcfg = cfgDirConfig cfg
-- We use ByteString here to ensure that no lazy I/O is performed.
-- This way to ensure that the reference file isn't held open in
-- case after `diffFile` (which is problematic if we need to rewrite
-- the reference file in `maybeAcceptFile`)
-- | Read the reference artifact for a test
readRef :: Config c -> FilePath -> IO (Maybe c)
readRef cfg file =
ccfgRead ccfg . BS.unpack
<$> BS.readFile (refFile dcfg file)
where
ccfg = cfgCheckConfig cfg
dcfg = cfgDirConfig cfg
-- | Read (and clean) the test output artifact for a test
readOut :: Config c -> FilePath -> IO (Maybe c)
readOut cfg file =
fmap (ccfgClean ccfg file) . ccfgRead ccfg . BS.unpack
<$> BS.readFile (outFile dcfg file)
where
ccfg = cfgCheckConfig cfg
dcfg = cfgDirConfig cfg
diffFile :: Config c -> FilePath -> FilePath -> IO ()
diffFile cfg diff file = do
Just out <- readOut cfg file
Just ref <- readRef cfg file
writeFile outFile' $ ccfgDump ccfg out
writeFile refFile' $ ccfgDump ccfg ref
putStrLn $ "Diff for file \"" ++ file ++ "\":"
hFlush stdout
handle <- runProcess' diff $ processConfig
{ pcArgs = [outFile', refFile']
, pcStdOut = Just $ stdout
}
waitForProcess handle >> return ()
where
dcfg = cfgDirConfig cfg
ccfg = cfgCheckConfig cfg
outFile' = outFile dcfg file <.> "dump"
refFile' = outFile dcfg file <.> "ref" <.> "dump"
maybeAcceptFile :: Config c -> FilePath -> CheckResult -> IO CheckResult
maybeAcceptFile cfg file result
| cfgAccept cfg && result `elem` [NoRef, Fail] = do
Just out <- readOut cfg file
writeFile (refFile dcfg file) $ ccfgDump ccfg out
pure Accepted
where
dcfg = cfgDirConfig cfg
ccfg = cfgCheckConfig cfg
maybeAcceptFile _ _ result = pure result
outDir :: DirConfig -> TestPackage -> FilePath
outDir dcfg tpkg = dcfgOutDir dcfg </> tpkgName tpkg
outFile :: DirConfig -> FilePath -> FilePath
outFile dcfg file = dcfgOutDir dcfg </> file
refFile :: DirConfig -> FilePath -> FilePath
refFile dcfg file = dcfgRefDir dcfg </> file
| Helkafen/haddock | haddock-test/src/Test/Haddock.hs | bsd-2-clause | 5,180 | 0 | 19 | 1,502 | 1,506 | 734 | 772 | 125 | 6 |
{-# LANGUAGE FlexibleInstances #-}
module SafeInfered05_A where
class C a where
f :: a -> String
instance C [Int] where
f _ = "[Int]"
| forked-upstream-packages-for-ghcjs/ghc | testsuite/tests/safeHaskell/safeInfered/SafeInfered05_A.hs | bsd-3-clause | 141 | 0 | 7 | 31 | 42 | 23 | 19 | 6 | 0 |
module T8603 where
import Control.Monad
import Data.Functor
import Control.Monad.Trans.Class( lift )
import Control.Monad.Trans.State( StateT )
newtype RV a = RV { getPDF :: [(Rational,a)] } deriving (Show, Eq)
instance Functor RV where
fmap f = RV . map (\(x,y) -> (x, f y)) . getPDF
instance Monad RV where
return x = RV [(1,x)]
rv >>= f = RV $
do (p,a) <- getPDF rv
guard (p > 0)
(q,b) <- getPDF $ f a
guard (q > 0)
return (p*q, b)
type RVState s a = StateT s RV a
uniform :: [a] -> RV a
uniform x = RV [(1/fromIntegral (length x), y) | y <- x]
testRVState1 :: RVState s Bool
testRVState1
= do prize <- lift uniform [1,2,3]
return False
-- lift :: (MonadTrans t, Monad m) => m a -> t m a | urbanslug/ghc | testsuite/tests/typecheck/should_fail/T8603.hs | bsd-3-clause | 745 | 0 | 12 | 192 | 357 | 194 | 163 | 23 | 1 |
-------------------------------------------------------------------------------
-- |
-- Module : Network.CURL000
-- Copyright : Copyright (c) 2012-2015 Krzysztof Kardzis
-- License : ISC License (MIT/BSD-style, see LICENSE file for details)
--
-- Maintainer : Krzysztof Kardzis <kkardzis@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-- <<https://ga-beacon.appspot.com/UA-53767359-1/curlhs/Network-CURL000>>
-------------------------------------------------------------------------------
module Network.CURL000 (
-----------------------------------------------------------------------------
-- * Run-Time Linking
-----------------------------------------------------------------------------
module Network.CURL000.LibLD
) where
import Network.CURL000.LibLD
| kkardzis/curlhs | Network/CURL000.hs | isc | 819 | 0 | 5 | 96 | 36 | 29 | 7 | 3 | 0 |
-- list comprehensions
-- Applying an expression to each value in a list
ghci> [x*2 | x <- [1..10]]
[2,4,6,8,10,12,14,16,18,20]
-- And also filtering out some of the values
ghci> [x*2 | x <- [1..10], x*2 > 12 ]
[14,16,18,20]
-- Using a function to filter out some of the vaalues
ghci> [x | x <- [50..100], x `mod` 7 == 4]
[53,60,67,74,81,88,95]
-- Put the comprehension into a function, to allow reuse:
ghci> let boomBangs xs = [ if x < 3 then "BOOM!" else "BANG!" | x <- xs, odd x ]
ghci> boomBangs [1..10]
["BOOM!","BANG!","BANG!","BANG!","BANG!"]
-- Can include multiple predicates, sepaarted by commas
ghci>[ x | x <- [10..20], x /= 13, x /= 15, x /= 19]
[10,11,12,14,16,17,18,20]
-- Can draw from more than one lists
-- In which case, every combination of elements is generated.
-- This taks first value from first list, then loops through all values from the second list
-- Then takes second vlaue from the first list.
ghci>[ x + y | x <- [1..2], y <- [ 10, 100, 1000] ]
[11,101,1001,12,102,1002]
-- Combining lists og words
ghci> let nouns = ["cat","dog","frog"]
ghci> let adjectives = ["happy","smily","grumpy"]
ghci> [adjective ++ " " ++ noun | adjective <- adjectives, noun <- nouns]
["happy cat","happy dog","happy frog","smily cat","smily dog","smily frog",
"grumpy cat","grumpy dog","grumpy frog"]
-- Using underscore as a temporary variable, as we don't care about the values
ghci>let length' xs = sum [ 1 | _ <- xs ]
ghci>length "hello world"
11
| claremacrae/haskell_snippets | list_comprehensions.hs | mit | 1,470 | 9 | 9 | 261 | 527 | 306 | 221 | -1 | -1 |
module RandomExample where
import Control.Applicative (liftA3)
import Control.Monad (replicateM)
import Control.Monad.Trans.State
import System.Random
-- newtype State s a =
-- State { runState :: s -> (a, s) }
-- Six-sided die
data Die =
DieOne
| DieTwo
| DieThree
| DieFour
| DieFive
| DieSix
deriving (Eq, Show)
intToDie :: Int -> Die
intToDie n =
case n of
1 -> DieOne
2 -> DieTwo
3 -> DieThree
4 -> DieFour
5 -> DieFive
6 -> DieSix
-- Use this tactic _extremely_ sparingly.
x -> error $ "intToDie got non 1-6 integer: " ++ show x
rollDieThreeTimes :: (Die, Die, Die)
rollDieThreeTimes = do
-- this will produce the same results every
-- time because it is free of effects.
-- This is fine for this demonstration.
let s = mkStdGen 0
(d1, s1) = randomR (1, 6) s
(d2, s2) = randomR (1, 6) s1
(d3, _) = randomR (1, 6) s2
(intToDie d1, intToDie d2, intToDie d3)
rollDie :: State StdGen Die
rollDie = state $ do
(n, s) <- randomR (1, 6)
return (intToDie n, s)
rollDie' :: State StdGen Die
rollDie' =
intToDie <$> state (randomR (1, 6))
rollDieThreeTimes' :: State StdGen (Die, Die, Die)
rollDieThreeTimes' =
liftA3 (,,) rollDie rollDie rollDie
nDie :: Int -> State StdGen [Die]
nDie n = replicateM n rollDie
-- keep rolling until we reach or exceed 20
rollsToGetTwenty :: StdGen -> Int
rollsToGetTwenty g = go 0 0 g
where go :: Int -> Int -> StdGen -> Int
go sum count gen
| sum >= 20 = count
| otherwise =
let (die, nextGen) = randomR (1, 6) gen
in go (sum + die) (count + 1) nextGen
rollsToGetN :: Int -> StdGen -> Int
rollsToGetN i g = go 0 0 g
where go :: Int -> Int -> StdGen -> Int
go sum count gen
| sum >= i = count
| otherwise =
let (die, nextGen) = randomR (1, 6) gen
in go (sum + die) (count + 1) nextGen
rollsCountLogged :: Int -> StdGen -> (Int, [Die])
rollsCountLogged i g = go 0 0 g []
where go :: Int -> Int -> StdGen -> [Die] -> (Int, [Die])
go sum count gen acc
| sum >= i = (count, acc)
| otherwise =
let (die, nextGen) = randomR (1, 6) gen
in go (sum + die) (count + 1) nextGen (intToDie die : acc)
| mitochon/hexercise | src/haskellbook/ch23/ch23.hs | mit | 2,290 | 0 | 13 | 674 | 862 | 458 | 404 | 66 | 7 |
import Network.SimpleServe (listen, makeStore)
main :: IO ()
main = do
store <- makeStore
listen store
| ngasull/hs-simple-serve | src/Main.hs | mit | 108 | 1 | 7 | 21 | 45 | 21 | 24 | 5 | 1 |
{-
Parser.hs: Parser for the Flounder interface definition language
Part of Flounder: a strawman device definition DSL for Barrelfish
Copyright (c) 2009, ETH Zurich.
All rights reserved.
This file is distributed under the terms in the attached LICENSE file.
If you do not find this file, copies can be found by writing to:
ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
-}
module Parser where
import FuguBackend
import qualified System
import Text.ParserCombinators.Parsec as Parsec
import Text.ParserCombinators.Parsec.Expr
import Text.ParserCombinators.Parsec.Pos
import qualified Text.ParserCombinators.Parsec.Token as P
import Text.ParserCombinators.Parsec.Language( javaStyle )
import Char
import Numeric
import Data.List
import Text.Printf
parse filename = parseFromFile errorFile filename
lexer = P.makeTokenParser (javaStyle
{ P.reservedNames = [ "errors",
"success",
"failure"
]
, P.reservedOpNames = ["*","/","+","-"]
, P.commentStart = "/*"
, P.commentEnd = "*/"
, P.commentLine = "//"
})
whiteSpace = P.whiteSpace lexer
reserved = P.reserved lexer
identifier = P.identifier lexer
stringLit = P.stringLiteral lexer
comma = P.comma lexer
commaSep = P.commaSep lexer
commaSep1 = P.commaSep1 lexer
parens = P.parens lexer
braces = P.braces lexer
squares = P.squares lexer
semiSep = P.semiSep lexer
symbol = P.symbol lexer
errorFile =
do
whiteSpace
errors <- many1 errorClass
return errors
errorClass =
do
reserved "errors"
name <- identifier
classE <- identifier
errors <- braces $ many1 (errorCase classE)
symbol ";" <?> " ';' missing from end of " ++ name ++ " error definition"
return $ ErrorClass name errors
errorCase classE =
do
successCase classE
<|> (failureCase classE)
<|> (defaultSuccessCase classE)
defaultSuccessCase classE =
do
reserved "default"
(ErrorField _ name descr) <- successCase classE
return $ ErrorField DefaultSuccess name descr
successCase classE =
do
reserved "success"
acronym <- identifier
description <- stringLit
symbol "," <?> " ',' missing from end of " ++ acronym ++ " definition"
return $ ErrorField Success (classE ++ acronym) description
failureCase classE =
do
reserved "failure"
acronym <- identifier
description <- stringLit
symbol "," <?> " ',' missing from end of " ++ acronym ++ " definition"
return $ ErrorField Failure (classE ++ acronym) description
| modeswitch/barrelfish | tools/fugu/Parser.hs | mit | 2,938 | 0 | 11 | 936 | 596 | 304 | 292 | 70 | 1 |
-- String array joining in Haskell
-- http://www.codewars.com/kata/5436bb1df0c10d280900131f
module JoinedWords where
joinS :: [String] -> String -> String
joinS l s = drop (length s) (foldl (\str w -> str ++ s ++ w) "" l)
| gafiatulin/codewars | src/7 kyu/JoinedWords.hs | mit | 224 | 0 | 11 | 38 | 71 | 39 | 32 | 3 | 1 |
module Main where
import Marc
import Data.List
import System.Environment
import Options.Applicative
data MarcDumpOptions = MarcDumpOptions
{
file :: String
,recordNumbersAndOffsets :: Bool
}
runWithOptions :: MarcDumpOptions -> IO ()
runWithOptions opts = do
s <- readFile $ file opts
let records = readBatchFromString s
mapM_ (putStrLn . marcDumpFormat) records
main :: IO ()
main = execParser opts >>= runWithOptions
where
parser = MarcDumpOptions <$> argument str (metavar "file")
<*> switch (short 'p' <>
long "print" <>
help "print numbers")
opts = info parser (
fullDesc
<> progDesc "MARCDUMP utility"
<> header "MARCDUmp")
| ccatalfo/marc | src/Main.hs | mit | 714 | 0 | 12 | 176 | 204 | 103 | 101 | 23 | 1 |
import Text.ParserCombinators.Parsec hiding (spaces)
import System.Environment
import Control.Monad
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| String String
| Bool Bool
parseString :: Parser LispVal
parseString = do
char '"'
x <- many (noneOf "\"")
char '"'
return $ String x
parseAtom :: Parser LispVal
parseAtom = do
first <- letter <|> symbol
rest <- many (letter <|> digit <|> symbol)
let atom = first:rest
return $ case atom of
"#t" -> Bool True
"#f" -> Bool False
_ -> Atom atom
parseNumber :: Parser LispVal
parseNumber = do
x <- many1 digit
return $ Number $ read x
parseExpr :: Parser LispVal
parseExpr = parseAtom
<|> parseString
<|> parseNumber
symbol :: Parser Char
symbol = oneOf "!#$%&|*+-/:<=>?@^_~"
spaces :: Parser ()
spaces = skipMany1 space
readExpr :: String -> String
readExpr input = case parse parseExpr "lisp" input of
Left err -> "No match: " ++ show err
Right _ -> "Found value"
main :: IO ()
main = do
(expr:_) <- getArgs
putStrLn $ readExpr expr
| mmwtsn/write-yourself-a-scheme | 02-parsing/exercises/01-with-do.hs | mit | 1,145 | 14 | 11 | 296 | 425 | 200 | 225 | 44 | 3 |
module Bassbull where
import qualified Data.ByteString.Lazy as BL
import qualified Data.Foldable as F
import Data.Csv.Streaming
-- a simple type alias for data
type BaseballStats = (BL.ByteString, Int, BL.ByteString, Int)
getAtBatsSum :: FilePath -> IO Int
getAtBatsSum battingCsv = do
csvData <- BL.readFile battingCsv
return $ F.foldr summer 0 (baseballStats csvData)
baseballStats :: BL.ByteString -> Records BaseballStats
baseballStats = decode NoHeader
summer :: (a, b, c, Int) -> Int -> Int
summer = (+) . fourth
fourth :: (a, b, c, d) -> d
fourth (_, _, _, d) = d
| Sgoettschkes/learning | haskell/HowIStart/bassbull/src/Bassbull.hs | mit | 583 | 0 | 10 | 102 | 203 | 118 | 85 | 15 | 1 |
{-# LANGUAGE BangPatterns #-}
-- Copyright © 2012 Bart Massey
-- [This program is licensed under the "MIT License"]
-- Please see the file COPYING in the source
-- distribution of this software for license terms.
import Control.Exception
import Control.Monad
import Data.Array.IO
import qualified Data.Bits as B
import qualified Data.ByteString.Lazy as BS
import Data.Char
import Data.Word
import System.Console.ParseArgs
import System.IO
data ArgInd = ArgEncrypt | ArgDecrypt | ArgKey | ArgReps
deriving (Ord, Eq, Show)
argd :: [ Arg ArgInd ]
argd = [
Arg {
argIndex = ArgEncrypt,
argName = Just "encrypt",
argAbbr = Just 'e',
argData = Nothing,
argDesc = "Use encryption mode."
},
Arg {
argIndex = ArgDecrypt,
argName = Just "decrypt",
argAbbr = Just 'd',
argData = Nothing,
argDesc = "Use decryption mode."
},
Arg {
argIndex = ArgKey,
argName = Just "key",
argAbbr = Just 'k',
argData = argDataOptional "keytext" ArgtypeString,
argDesc = "Encryption or decryption key (dangerous)."
},
Arg {
argIndex = ArgReps,
argName = Just "reps",
argAbbr = Just 'r',
argData = argDataDefaulted "repcount" ArgtypeInt 20,
argDesc = "Number of key sched reps (20 default, 1 for CS1)."
} ]
type CState = IOUArray Word8 Word8
fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
initKeystream :: String -> [Word8] -> Int -> IO CState
initKeystream key iv reps = do
let keystream = concat $ replicate reps $
take 256 $ cycle $ map (fi . ord) key ++ iv
state <- newListArray (0, 255) [0..255]
mixArray keystream state (0, 0)
where
mixArray :: [Word8] -> CState -> (Word8, Word8) -> IO CState
mixArray (k : ks) a (i, j0) = do
si <- readArray a i
let j = j0 + si + k
sj <- readArray a j
writeArray a i sj
writeArray a j si
mixArray ks a (i + 1, j)
mixArray [] a (0, _) = return a
mixArray _ _ _ = error "internal error: bad mix state"
readIV :: IO [Word8]
readIV = do
ivs <- BS.hGet stdin 10
let ivl = BS.unpack ivs
return ivl
makeIV :: IO [Word8]
makeIV =
withBinaryFile "/dev/urandom" ReadMode $ \h ->
do
hSetBuffering h NoBuffering
ivs <- BS.hGet h 10
BS.hPut stdout ivs
return $ BS.unpack ivs
{-
accumMapM :: (Functor m, Monad m) => (a -> b -> m (a, b)) -> a -> [b] -> m [b]
accumMapM _ _ [] = return []
accumMapM a acc (b : bs) = do
(acc', b') <- a acc b
fmap (b' :) $ accumMapM a acc' bs
-}
accumMapM_ :: Monad m => (a -> b -> m a) -> a -> [b] -> m ()
accumMapM_ _ _ [] = return ()
accumMapM_ a acc (b : bs) = do
acc' <- a acc b
accumMapM_ a acc' bs
type Accum = ((Word8, Word8), CState)
stepRC4 :: Accum -> Char -> IO Accum
stepRC4 ((!i0, !j0), !state) !b = do
let !i = i0 + 1
!si <- readArray state i
let !j = j0 + si
!sj <- readArray state j
writeArray state j si
writeArray state i sj
!k <- readArray state (si + sj)
putChar $ chr $ fi $ B.xor k $ fi $ ord b
return ((i, j), state)
applyKeystream :: CState -> String -> IO ()
applyKeystream state intext =
accumMapM_ stepRC4 ((0, 0), state) intext
applyStreamCipher :: CState -> IO ()
applyStreamCipher state =
getContents >>= applyKeystream state
-- http://stackoverflow.com/a/4064482
getKey :: String -> IO String
getKey prompt = do
bracket
(openFile "/dev/tty" ReadWriteMode)
(\h -> hClose h)
(\h -> do
hPutStr h prompt
hFlush h
old <- hGetEcho h
key <- bracket_
(hSetEcho h False)
(hSetEcho h old)
(hGetLine h)
hPutStrLn h ""
return key)
main :: IO ()
main = do
hSetBinaryMode stdin True
hSetBinaryMode stdout True
hSetBuffering stdin $ BlockBuffering $ Just $ 64 * 1024
hSetBuffering stdout $ BlockBuffering $ Just $ 64 * 1024
argv <- parseArgsIO ArgsComplete argd
let e = gotArg argv ArgEncrypt
let d = gotArg argv ArgDecrypt
unless ((e && not d) || (d && not e)) $
usageError argv "Exactly one of -e or -d is required."
k <- case gotArg argv ArgKey of
True -> return $ getRequiredArg argv ArgKey
False -> getKey "key:"
let r = getRequiredArg argv ArgReps
unless (r > 0) $
usageError argv "Reps must be positive."
iv <- if e then makeIV else readIV
s <- initKeystream k iv r
applyStreamCipher s
| BartMassey/ciphersaber | ciphersaber.hs | mit | 4,381 | 4 | 15 | 1,179 | 1,561 | 772 | 789 | 128 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Lucid.Server where
import Control.Monad
import qualified Data.ByteString.Char8 as SC
import Happstack.Server
import Lucid
-- | happstack server utils
serve :: ServerPart Response -> IO ()
serve response =
simpleHTTP (nullConf {port = 8001}) $ do
decodeBody (defaultBodyPolicy "/tmp/" 4096 4096 4096)
response
includeLibDir :: ServerPart Response -> ServerPart Response
includeLibDir page = msum
[ dir "" page
, dir "lib" $ serveDirectory EnableBrowsing [] "lib"
]
instance ToMessage (Html ()) where
toContentType _ = SC.pack "text/html; charset=UTF-8"
toMessage = renderBS
| tonyday567/hdcharts | src/Lucid/Server.hs | mit | 753 | 0 | 10 | 158 | 183 | 96 | 87 | 20 | 1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
module Hydrazine.Server.Boxen where
import Servant
import Control.Monad.Trans.Either
import Data.Functor.Identity
import Data.Time.LocalTime
import Control.Monad
import Data.Maybe
import Control.Monad.Trans.Class
import Control.Monad.Trans.Except
import qualified Hasql as H
import qualified Data.Text as T
import Hydrazine.JSON
import Hydrazine.Server.Postgres
getBoxen :: DBConn -> EitherT ServantErr IO [BoxInfo]
getBoxen conn = do
runTx conn (
do (boxen :: [(Int,T.Text,T.Text,Maybe Int,Maybe LocalTime,Bool)])
<- lift $ H.listEx $ [H.stmt|
SELECT id
, name
, mac
, boot_image
, boot_until
, boot_forever
FROM boxen
ORDER BY name ASC
|]
boxInfos <- forM boxen (\(boxId,_,_,mImg,_,_)
-> do mName <- case mImg of
Nothing -> return Nothing
Just imgId -> do
(mname :: Maybe (Identity T.Text))
<- lift $ H.maybeEx $ [H.stmt|
SELECT name
FROM images
WHERE id = ?
|] imgId
return (mname >>= (Just . unwrapId))
(bFlags :: [(T.Text,Maybe T.Text)])
<- lift $ H.listEx $ [H.stmt|
SELECT key
, value
FROM bootflags
WHERE box_id = ?
ORDER BY key ASC
|] boxId
(logs :: [(T.Text,LocalTime)])
<- lift $ H.listEx $ [H.stmt|
SELECT image_name
, boot_time
FROM boots
WHERE boots.box_id = ?
ORDER BY boots.boot_time DESC
|] boxId
return (mName,bFlags,logs)
)
return $ zip boxen boxInfos
)
( right . map (\((_,name,macaddr,_,mUntil,bForever),(mName,bFlags,logs)) ->
BoxInfo { boxName = name
, mac = formatMac macaddr
, boot = let fs = map (\(k,v) -> BootFlag k v) bFlags
in case mName of
Nothing -> Nothing
Just iName -> Just $ BootSettings
iName (BootUntil bForever mUntil) fs
, bootlogs = map (\(n,t) -> BootInstance n t) logs
})
)
getBox :: DBConn -> T.Text -> EitherT ServantErr IO BoxInfo
getBox conn n = do
runTx conn (
do (mBox :: Maybe (Int,T.Text,T.Text,Maybe Int,Maybe LocalTime,Bool))
<- lift $ H.maybeEx $ [H.stmt|
SELECT id
, name
, mac
, boot_image
, boot_until
, boot_forever
FROM boxen
WHERE name = ?
ORDER BY name ASC
|] n
when (isNothing mBox) $
throwE err404 { errBody = "machine not found" }
let box@(boxId,_,_,mImg,_,_) = fromJust mBox
mName <- case mImg of
Nothing -> return Nothing
Just imgId -> do
(mname :: Maybe (Identity T.Text))
<- lift $ H.maybeEx $ [H.stmt|
SELECT name
FROM images
WHERE id = ?
|] imgId
return (mname >>= (Just . unwrapId))
(bFlags :: [(T.Text,Maybe T.Text)])
<- lift $ H.listEx $ [H.stmt|
SELECT key
, value
FROM bootflags
WHERE box_id = ?
ORDER BY key ASC
|] boxId
(logs :: [(T.Text,LocalTime)])
<- lift $ H.listEx $ [H.stmt|
SELECT image_name
, boot_time
FROM boots
WHERE boots.box_id = ?
ORDER BY boots.boot_time DESC
|] boxId
return (box,mName,bFlags,logs)
)
(
\((_,_,macaddr,_,mUntil,bForever),mName,bFlags,logs) ->
right $
BoxInfo { boxName = n
, mac = formatMac macaddr
, boot = mName >>= (\iName -> Just $ BootSettings
iName (BootUntil bForever mUntil) (map (\(k,v) -> BootFlag k v) bFlags))
, bootlogs = map (\(i,t) -> BootInstance i t) logs
}
)
newBox :: DBConn -> T.Text -> NewBox -> EitherT ServantErr IO EmptyValue
newBox conn n (NewBox m) = do
runTx conn (do
(res :: Maybe (Identity Int)) <- lift $ H.maybeEx $ [H.stmt|
SELECT id
FROM "boxen"
WHERE name = ?
|] n
when (res /= Nothing) (throwE
err400 { errBody = "a box with that name already exists" })
(res' :: Maybe (Identity Int)) <- lift $ H.maybeEx $ [H.stmt|
SELECT id
FROM "boxen"
WHERE mac = ?
|] (stripMac m)
when (res' /= Nothing) (throwE
err400 { errBody = "a box with that MAC address already exists" })
lift $ H.unitEx $ [H.stmt|
INSERT INTO "boxen"
(name,mac)
VALUES
(?,?)
|] n (stripMac m)
) (returnEmptyValue)
updateBox :: DBConn -> T.Text -> UpdateBox -> EitherT ServantErr IO EmptyValue
updateBox conn name (UpdateBox img til fs) =
runTx conn (do
(boxId :: Maybe (Identity Int))
<- lift $ H.maybeEx $ [H.stmt|
SELECT id
FROM "boxen"
WHERE name = ?
|] name
when (isNothing boxId) $
throwE err400 { errBody = "a box with that name doesn't exist" }
when (isJust img) $
if (fromJust img) == ""
then lift $ H.unitEx $ [H.stmt|
UPDATE "boxen"
SET boot_image = NULL
WHERE name = ?
|] name
else do
(imgId :: Maybe (Identity Int))
<- lift $ H.maybeEx $ [H.stmt|
SELECT id
FROM "images"
WHERE name = ?
|] img
when (isNothing imgId) $
throwE err400 { errBody = "image doesn't exist" }
lift $ H.unitEx $ [H.stmt|
UPDATE "boxen"
SET boot_image = ?
WHERE name = ?
|] (unwrapId $ fromJust imgId) name
when (isNothing fs) $ do
lift $ H.unitEx $ [H.stmt|
DELETE FROM "bootflags"
WHERE box_id = ?
|] (unwrapId $ fromJust boxId)
(bfs :: [(T.Text,Maybe T.Text)])
<- lift $ H.listEx $ [H.stmt|
SELECT key
, value
FROM "defaultbootflags"
WHERE image_id = ?
|] (unwrapId $ fromJust imgId)
forM_ bfs (\(key,val) ->
lift $ H.unitEx $ [H.stmt|
INSERT INTO "bootflags"
(box_id,key,value)
VALUES
(?,?,?)
|] (unwrapId $ fromJust boxId) key val
)
when (isJust til) $
let (BootUntil bForever mUntil) = fromJust til
in lift $ H.unitEx $ [H.stmt|
UPDATE "boxen"
SET boot_forever = ?
, boot_until = ?
WHERE name = ?
|] bForever mUntil name
when (isJust fs) $ do
lift $ H.unitEx $ [H.stmt|
DELETE FROM "bootflags"
WHERE box_id = ?
|] (unwrapId $ fromJust boxId)
forM_ (fromJust fs) (\(BootFlag key val) ->
lift $ H.unitEx $ [H.stmt|
INSERT INTO "bootflags"
(box_id,key,value)
VALUES
(?,?,?)
|] (unwrapId $ fromJust boxId) key val
)
) (returnEmptyValue)
deleteBox :: DBConn -> T.Text -> EitherT ServantErr IO ()
deleteBox conn name =
runTx_ conn (do
(mBoxId :: Maybe (Identity Int))
<- lift $ H.maybeEx $ [H.stmt|
SELECT id
FROM "boxen"
WHERE name = ?
|] name
when (isNothing mBoxId) $
throwE err400 { errBody = "a box with that name doesn't exist" }
let boxId = unwrapId $ fromJust mBoxId
lift $ H.unitEx $ [H.stmt|
DELETE FROM "boots"
WHERE box_id = ?
|] boxId
lift $ H.unitEx $ [H.stmt|
DELETE FROM "bootflags"
WHERE box_id = ?
|] boxId
lift $ H.unitEx $ [H.stmt|
DELETE FROM "boxen"
WHERE id = ?
|] boxId
)
| dgonyeo/hydrazine | src/Hydrazine/Server/Boxen.hs | mit | 10,840 | 0 | 29 | 5,945 | 2,189 | 1,172 | 1,017 | 146 | 3 |
-- mood.hs
module MoodIsBlahOrWoot where
data Mood = Blah | Woot deriving Show
changeMood Blah = Woot
changeMood _ = Blah
| Lyapunov/haskell-programming-from-first-principles | chapter_4/mood.hs | mit | 127 | 0 | 5 | 26 | 34 | 20 | 14 | 4 | 1 |
module Problem17 where
import Data.Char (isSpace)
main = print $ sum $ map (length . filter (not . isSpace) . spellIt) [1..1000]
spellIt :: Int -> String
spellIt 1000 = "one thousand"
spellIt n | n >= 100 = spellIt (n `div` 100) ++ " hundred" ++ sep " and " (spellIt (n `rem` 100))
| n >= 90 = "ninety" ++ sep " " (spellIt (n `rem` 90))
| n >= 80 = "eighty" ++ sep " " (spellIt (n `rem` 80))
| n >= 70 = "seventy" ++ sep " " (spellIt (n `rem` 70))
| n >= 60 = "sixty" ++ sep " " (spellIt (n `rem` 60))
| n >= 50 = "fifty" ++ sep " " (spellIt (n `rem` 50))
| n >= 40 = "forty" ++ sep " " (spellIt (n `rem` 40))
| n >= 30 = "thirty" ++ sep " " (spellIt (n `rem` 30))
| n >= 20 = "twenty" ++ sep " " (spellIt (n `rem` 20))
where
sep a "" = ""
sep a b = a ++ b
spellIt 19 = "nineteen"
spellIt 18 = "eighteen"
spellIt 17 = "seventeen"
spellIt 16 = "sixteen"
spellIt 15 = "fifteen"
spellIt 14 = "fourteen"
spellIt 13 = "thirteen"
spellIt 12 = "twelve"
spellIt 11 = "eleven"
spellIt 10 = "ten"
spellIt 9 = "nine"
spellIt 8 = "eight"
spellIt 7 = "seven"
spellIt 6 = "six"
spellIt 5 = "five"
spellIt 4 = "four"
spellIt 3 = "three"
spellIt 2 = "two"
spellIt 1 = "one"
spellIt 0 = ""
| DevJac/haskell-project-euler | src/Problem17.hs | mit | 1,304 | 0 | 12 | 391 | 615 | 316 | 299 | 36 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
-- |
-- Module: TestCase
-- Description: All test cases aggregated and exported as tests :: [Test].
-- Copyright: Copyright (c) 2015-2016 Jan Sipr
-- License: MIT
--
-- Stability: stable
-- Portability: NoImplicitPrelude
--
-- All test cases aggregated and exported as @'tests' :: ['Test']@.
module TestCase (tests)
where
import Test.Framework (Test, testGroup)
import qualified TestCase.Network.SIP.Parser as Parser (tests)
import qualified TestCase.Network.SIP.Parser.Header as Parser.Header (tests)
import qualified TestCase.Network.SIP.Parser.Line as Parser.Line (tests)
import qualified TestCase.Network.SIP.Parser.RequestMethod as
Parser.RequestMethod (tests)
import qualified TestCase.Network.SIP.Parser.Uri as Parser.Uri (tests)
import qualified TestCase.Network.SIP.Serialization as Serialization (tests)
import qualified TestCase.Network.SIP.Serialization.FirstLine as
Serialization.FirstLine (tests)
import qualified TestCase.Network.SIP.Serialization.Header as
Serialization.Header (tests)
import qualified TestCase.Network.SIP.Serialization.Status as
Serialization.Status (tests)
import qualified TestCase.Network.SIP.Serialization.Uri as
Serialization.Uri (tests)
tests :: [Test]
tests =
[ testGroup "TestCase.Network.SIP.Parser.Header" Parser.Header.tests
, testGroup "TestCase.Network.SIP.Parser.Line" Parser.Line.tests
, testGroup "TestCase.Network.SIP.Parser" Parser.tests
, testGroup "TestCase.Network.SIP.Parser.RequestMethod"
Parser.RequestMethod.tests
, testGroup "TestCase.Network.SIP.Parser.Uri" Parser.Uri.tests
, testGroup "TestCase.Network.SIP.Serialization"
Serialization.tests
, testGroup "TestCase.Network.SIP.Serialization.FirstLine"
Serialization.FirstLine.tests
, testGroup "TestCase.Network.SIP.Serialization.Header"
Serialization.Header.tests
, testGroup "TestCase.Network.SIP.Serialization.Status"
Serialization.Status.tests
, testGroup "TestCase.Network.SIP.Serialization.Uri"
Serialization.Uri.tests
]
| Siprj/ragnarok | test/TestCase.hs | mit | 2,111 | 0 | 7 | 300 | 328 | 217 | 111 | 36 | 1 |
{-# language NoImplicitPrelude, DoAndIfThenElse, OverloadedStrings, ExtendedDefaultRules #-}
{-# LANGUAGE CPP, ScopedTypeVariables #-}
-- | Description : Argument parsing and basic messaging loop, using Haskell
-- Chans to communicate with the ZeroMQ sockets.
module Main (main) where
import IHaskellPrelude
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Char8 as CBS
-- Standard library imports.
import Control.Concurrent (threadDelay)
import Control.Concurrent.Chan
import Control.Arrow (second)
import Data.Aeson
import System.Directory
import System.Process (readProcess, readProcessWithExitCode)
import System.Exit (exitSuccess, ExitCode(ExitSuccess))
import Control.Exception (try, SomeException)
import System.Environment (getArgs)
#if MIN_VERSION_ghc(7,8,0)
import System.Environment (setEnv)
#endif
import System.Posix.Signals
import qualified Data.Map as Map
import qualified Data.Text.Encoding as E
import Data.List (break, last)
import Data.Version (showVersion)
-- IHaskell imports.
import IHaskell.Convert (convert)
import IHaskell.Eval.Completion (complete)
import IHaskell.Eval.Inspect (inspect)
import IHaskell.Eval.Evaluate
import IHaskell.Display
import IHaskell.Eval.Info
import IHaskell.Eval.Widgets (widgetHandler)
import IHaskell.Flags
import IHaskell.IPython
import IHaskell.Types
import IHaskell.Publish
import IHaskell.IPython.ZeroMQ
import IHaskell.IPython.Types
import qualified IHaskell.IPython.Message.UUID as UUID
import qualified IHaskell.IPython.Stdin as Stdin
-- Cabal imports.
import Paths_ihaskell(version)
-- GHC API imports.
import GHC hiding (extensions, language)
-- | Compute the GHC API version number using the dist/build/autogen/cabal_macros.h
ghcVersionInts :: [Int]
ghcVersionInts = map (fromJust . readMay) . words . map dotToSpace $ VERSION_ghc
where
dotToSpace '.' = ' '
dotToSpace x = x
consoleBanner :: Text
consoleBanner =
"Welcome to IHaskell! Run `IHaskell --help` for more information.\n" <>
"Enter `:help` to learn more about IHaskell built-ins."
main :: IO ()
main = do
args <- parseFlags <$> getArgs
case args of
Left errorMessage -> hPutStrLn stderr errorMessage
Right args -> ihaskell args
ihaskell :: Args -> IO ()
ihaskell (Args (ShowDefault helpStr) args) = showDefault helpStr args
ihaskell (Args ConvertLhs args) = showingHelp ConvertLhs args $ convert args
ihaskell (Args InstallKernelSpec args) = showingHelp InstallKernelSpec args $ do
let kernelSpecOpts = parseKernelArgs args
replaceIPythonKernelspec kernelSpecOpts
ihaskell (Args (Kernel (Just filename)) args) = do
let kernelSpecOpts = parseKernelArgs args
runKernel kernelSpecOpts filename
ihaskell a@(Args (Kernel Nothing) _) = do
hPutStrLn stderr "No kernel profile JSON specified."
hPutStrLn stderr "This may be a bug!"
hPrint stderr a
showDefault :: String -> [Argument] -> IO ()
showDefault helpStr flags =
case find (== Version) flags of
Just _ ->
putStrLn (showVersion version)
Nothing ->
putStrLn helpStr
showingHelp :: IHaskellMode -> [Argument] -> IO () -> IO ()
showingHelp mode flags act =
case find (== Help) flags of
Just _ ->
putStrLn $ help mode
Nothing ->
act
-- | Parse initialization information from the flags.
parseKernelArgs :: [Argument] -> KernelSpecOptions
parseKernelArgs = foldl' addFlag defaultKernelSpecOptions
where
addFlag kernelSpecOpts (ConfFile filename) =
kernelSpecOpts { kernelSpecConfFile = return (Just filename) }
addFlag kernelSpecOpts KernelDebug =
kernelSpecOpts { kernelSpecDebug = True }
addFlag kernelSpecOpts (GhcLibDir libdir) =
kernelSpecOpts { kernelSpecGhcLibdir = libdir }
addFlag kernelSpecOpts (KernelspecInstallPrefix prefix) =
kernelSpecOpts { kernelSpecInstallPrefix = Just prefix }
addFlag kernelSpecOpts KernelspecUseStack =
kernelSpecOpts { kernelSpecUseStack = True }
addFlag kernelSpecOpts flag = error $ "Unknown flag" ++ show flag
-- | Run the IHaskell language kernel.
runKernel :: KernelSpecOptions -- ^ Various options from when the kernel was installed.
-> String -- ^ File with kernel profile JSON (ports, etc).
-> IO ()
runKernel kernelOpts profileSrc = do
let debug = kernelSpecDebug kernelOpts
libdir = kernelSpecGhcLibdir kernelOpts
useStack = kernelSpecUseStack kernelOpts
-- Parse the profile file.
let profileErr = error $ "ihaskell: "++profileSrc++": Failed to parse profile file"
profile <- liftM (fromMaybe profileErr . decode) $ LBS.readFile profileSrc
-- Necessary for `getLine` and their ilk to work.
dir <- getIHaskellDir
Stdin.recordKernelProfile dir profile
#if MIN_VERSION_ghc(7,8,0)
when useStack $ do
-- Detect if we have stack
runResult <- try $ readProcessWithExitCode "stack" [] ""
let stack =
case runResult :: Either SomeException (ExitCode, String, String) of
Left _ -> False
Right (exitCode, stackStdout, _) -> exitCode == ExitSuccess && "The Haskell Tool Stack" `isInfixOf` stackStdout
-- If we're in a stack directory, use `stack` to set the environment
-- We can't do this with base <= 4.6 because setEnv doesn't exist.
when stack $ do
stackEnv <- lines <$> readProcess "stack" ["exec", "env"] ""
forM_ stackEnv $ \line ->
let (var, val) = break (== '=') line
in case tailMay val of
Nothing -> return ()
Just val' -> setEnv var val'
#endif
-- Serve on all sockets and ports defined in the profile.
interface <- serveProfile profile debug
-- Create initial state in the directory the kernel *should* be in.
state <- initialKernelState
modifyMVar_ state $ \kernelState -> return $
kernelState { kernelDebug = debug }
-- Receive and reply to all messages on the shell socket.
interpret libdir True $ \hasSupportLibraries -> do
-- Ignore Ctrl-C the first time. This has to go inside the `interpret`, because GHC API resets the
-- signal handlers for some reason (completely unknown to me).
liftIO ignoreCtrlC
liftIO $ modifyMVar_ state $ \kernelState -> return $
kernelState { supportLibrariesAvailable = hasSupportLibraries }
-- Initialize the context by evaluating everything we got from the command line flags.
let noPublish _ = return ()
noWidget s _ = return s
evaluator line = void $ do
-- Create a new state each time.
stateVar <- liftIO initialKernelState
state <- liftIO $ takeMVar stateVar
evaluate state line noPublish noWidget
confFile <- liftIO $ kernelSpecConfFile kernelOpts
case confFile of
Just filename -> liftIO (readFile filename) >>= evaluator
Nothing -> return ()
forever $ do
-- Read the request from the request channel.
request <- liftIO $ readChan $ shellRequestChannel interface
-- Create a header for the reply.
replyHeader <- createReplyHeader (header request)
-- We handle comm messages and normal ones separately. The normal ones are a standard
-- request/response style, while comms can be anything, and don't necessarily require a response.
if isCommMessage request
then do
oldState <- liftIO $ takeMVar state
let replier = writeChan (iopubChannel interface)
widgetMessageHandler = widgetHandler replier replyHeader
tempState <- handleComm replier oldState request replyHeader
newState <- flushWidgetMessages tempState [] widgetMessageHandler
liftIO $ putMVar state newState
liftIO $ writeChan (shellReplyChannel interface) SendNothing
else do
-- Create the reply, possibly modifying kernel state.
oldState <- liftIO $ takeMVar state
(newState, reply) <- replyTo interface request replyHeader oldState
liftIO $ putMVar state newState
-- Write the reply to the reply channel.
liftIO $ writeChan (shellReplyChannel interface) reply
where
ignoreCtrlC =
installHandler keyboardSignal (CatchOnce $ putStrLn "Press Ctrl-C again to quit kernel.")
Nothing
isCommMessage req = msgType (header req) `elem` [CommDataMessage, CommCloseMessage]
-- Initial kernel state.
initialKernelState :: IO (MVar KernelState)
initialKernelState = newMVar defaultKernelState
-- | Create a new message header, given a parent message header.
createReplyHeader :: MessageHeader -> Interpreter MessageHeader
createReplyHeader parent = do
-- Generate a new message UUID.
newMessageId <- liftIO UUID.random
let repType = fromMaybe err (replyType $ msgType parent)
err = error $ "No reply for message " ++ show (msgType parent)
return
MessageHeader
{ identifiers = identifiers parent
, parentHeader = Just parent
, metadata = Map.fromList []
, messageId = newMessageId
, sessionId = sessionId parent
, username = username parent
, msgType = repType
}
-- | Compute a reply to a message.
replyTo :: ZeroMQInterface -> Message -> MessageHeader -> KernelState -> Interpreter (KernelState, Message)
-- Reply to kernel info requests with a kernel info reply. No computation needs to be done, as a
-- kernel info reply is a static object (all info is hard coded into the representation of that
-- message type).
replyTo _ KernelInfoRequest{} replyHeader state =
return
(state, KernelInfoReply
{ header = replyHeader
, protocolVersion = "5.0"
, banner = "IHaskell " ++ (showVersion version) ++ " GHC " ++ VERSION_ghc
, implementation = "IHaskell"
, implementationVersion = showVersion version
, languageInfo = LanguageInfo
{ languageName = "haskell"
, languageVersion = VERSION_ghc
, languageFileExtension = ".hs"
, languageCodeMirrorMode = "ihaskell"
}
})
replyTo _ CommInfoRequest{} replyHeader state =
let comms = Map.mapKeys (UUID.uuidToString) (openComms state) in
return
(state, CommInfoReply
{ header = replyHeader
, commInfo = Map.map (\(Widget w) -> targetName w) comms
})
-- Reply to a shutdown request by exiting the main thread. Before shutdown, reply to the request to
-- let the frontend know shutdown is happening.
replyTo interface ShutdownRequest { restartPending = restartPending } replyHeader _ = liftIO $ do
writeChan (shellReplyChannel interface) $ ShutdownReply replyHeader restartPending
exitSuccess
-- Reply to an execution request. The reply itself does not require computation, but this causes
-- messages to be sent to the IOPub socket with the output of the code in the execution request.
replyTo interface req@ExecuteRequest { getCode = code } replyHeader state = do
-- Convenience function to send a message to the IOPub socket.
let send msg = liftIO $ writeChan (iopubChannel interface) msg
-- Log things so that we can use stdin.
dir <- liftIO getIHaskellDir
liftIO $ Stdin.recordParentHeader dir $ header req
-- Notify the frontend that the kernel is busy computing. All the headers are copies of the reply
-- header with a different message type, because this preserves the session ID, parent header, and
-- other important information.
busyHeader <- liftIO $ dupHeader replyHeader StatusMessage
send $ PublishStatus busyHeader Busy
-- Construct a function for publishing output as this is going. This function accepts a boolean
-- indicating whether this is the final output and the thing to display. Store the final outputs in
-- a list so that when we receive an updated non-final output, we can clear the entire output and
-- re-display with the updated output.
displayed <- liftIO $ newMVar []
updateNeeded <- liftIO $ newMVar False
pagerOutput <- liftIO $ newMVar []
let execCount = getExecutionCounter state
-- Let all frontends know the execution count and code that's about to run
inputHeader <- liftIO $ dupHeader replyHeader InputMessage
send $ PublishInput inputHeader (T.unpack code) execCount
-- Run code and publish to the frontend as we go.
let widgetMessageHandler = widgetHandler send replyHeader
publish = publishResult send replyHeader displayed updateNeeded pagerOutput (usePager state)
updatedState <- evaluate state (T.unpack code) publish widgetMessageHandler
-- Notify the frontend that we're done computing.
idleHeader <- liftIO $ dupHeader replyHeader StatusMessage
send $ PublishStatus idleHeader Idle
-- Take pager output if we're using the pager.
pager <- if usePager state
then liftIO $ readMVar pagerOutput
else return []
return
(updatedState, ExecuteReply
{ header = replyHeader
, pagerOutput = pager
, executionCounter = execCount
, status = Ok
})
-- Check for a trailing empty line. If it doesn't exist, we assume the code is incomplete,
-- otherwise we assume the code is complete. Todo: Implement a mechanism that only requests
-- a trailing empty line, when multiline code is entered.
replyTo _ req@IsCompleteRequest{} replyHeader state = do
isComplete <- isInputComplete
let reply = IsCompleteReply { header = replyHeader, reviewResult = isComplete }
return (state, reply)
where
isInputComplete = do
let code = lines $ inputToReview req
if nub (last code) == " "
then return CodeComplete
else return $ CodeIncomplete $ indent 4
indent n = take n $ repeat ' '
replyTo _ req@CompleteRequest{} replyHeader state = do
let code = getCode req
pos = getCursorPos req
(matchedText, completions) <- complete (T.unpack code) pos
let start = pos - length matchedText
end = pos
reply = CompleteReply replyHeader (map T.pack completions) start end Map.empty True
return (state, reply)
replyTo _ req@InspectRequest{} replyHeader state = do
result <- inspect (T.unpack $ inspectCode req) (inspectCursorPos req)
let reply =
case result of
Just (Display datas) -> InspectReply
{ header = replyHeader
, inspectStatus = True
, inspectData = datas
}
_ -> InspectReply { header = replyHeader, inspectStatus = False, inspectData = [] }
return (state, reply)
-- TODO: Implement history_reply.
replyTo _ HistoryRequest{} replyHeader state = do
let reply = HistoryReply
{ header = replyHeader
-- FIXME
, historyReply = []
}
return (state, reply)
-- Accomodating the workaround for retrieving list of open comms from the kernel
--
-- The main idea is that the frontend opens a comm at kernel startup, whose target is a widget that
-- sends back the list of live comms and commits suicide.
--
-- The message needs to be written to the iopub channel, and not returned from here. If returned,
-- the same message also gets written to the shell channel, which causes issues due to two messages
-- having the same identifiers in their headers.
--
-- Sending the message only on the shell_reply channel doesn't work, so we send it as a comm message
-- on the iopub channel and return the SendNothing message.
replyTo interface open@CommOpen{} replyHeader state = do
let send msg = liftIO $ writeChan (iopubChannel interface) msg
incomingUuid = commUuid open
target = commTargetName open
targetMatches = target == "ipython.widget"
valueMatches = commData open == object ["widget_class" .= "ipywidgets.CommInfo"]
commMap = openComms state
uuidTargetPairs = map (second targetName) $ Map.toList commMap
pairProcessor (x, y) = T.pack (UUID.uuidToString x) .= object ["target_name" .= T.pack y]
currentComms = object $ map pairProcessor $ (incomingUuid, "comm") : uuidTargetPairs
replyValue = object [ "method" .= "custom"
, "content" .= object ["comms" .= currentComms]
]
msg = CommData replyHeader (commUuid open) replyValue
-- To the iopub channel you go
when (targetMatches && valueMatches) $ send msg
return (state, SendNothing)
-- TODO: What else can be implemented?
replyTo _ message _ state = do
liftIO $ hPutStrLn stderr $ "Unimplemented message: " ++ show message
return (state, SendNothing)
-- | Handle comm messages
handleComm :: (Message -> IO ()) -> KernelState -> Message -> MessageHeader -> Interpreter KernelState
handleComm send kernelState req replyHeader = do
-- MVars to hold intermediate data during publishing
displayed <- liftIO $ newMVar []
updateNeeded <- liftIO $ newMVar False
pagerOutput <- liftIO $ newMVar []
let widgets = openComms kernelState
uuid = commUuid req
dat = commData req
communicate value = do
head <- dupHeader replyHeader CommDataMessage
send $ CommData head uuid value
toUsePager = usePager kernelState
-- Create a publisher according to current state, use that to build
-- a function that executes an IO action and publishes the output to
-- the frontend simultaneously.
let run = capturedIO publish kernelState
publish = publishResult send replyHeader displayed updateNeeded pagerOutput toUsePager
-- Notify the frontend that the kernel is busy
busyHeader <- liftIO $ dupHeader replyHeader StatusMessage
liftIO . send $ PublishStatus busyHeader Busy
newState <- case Map.lookup uuid widgets of
Nothing -> return kernelState
Just (Widget widget) ->
case msgType $ header req of
CommDataMessage -> do
disp <- run $ comm widget dat communicate
pgrOut <- liftIO $ readMVar pagerOutput
liftIO $ publish $ FinalResult disp (if toUsePager then pgrOut else []) []
return kernelState
CommCloseMessage -> do
disp <- run $ close widget dat
pgrOut <- liftIO $ readMVar pagerOutput
liftIO $ publish $ FinalResult disp (if toUsePager then pgrOut else []) []
return kernelState { openComms = Map.delete uuid widgets }
-- Notify the frontend that the kernel is idle once again
idleHeader <- liftIO $ dupHeader replyHeader StatusMessage
liftIO . send $ PublishStatus idleHeader Idle
return newState
| sumitsahrawat/IHaskell | main/Main.hs | mit | 18,868 | 0 | 22 | 4,531 | 4,009 | 2,052 | 1,957 | 293 | 6 |
{-
- Whidgle.Rules
-
- A mixture of game rules and heuristics.
-}
-- export everything
module Whidgle.Rules where
import Control.Lens
import Data.Function
import Whidgle.Types
-- How many steps away an opponent can be before we consider the possibility of attack behavior.
reasonablyClose :: Int
reasonablyClose = 10
-- The number of turns to plan for in the future.
nearFuture :: Int
nearFuture = 300
-- Constants dealing to avoidance of enemies.
attackDamage, wiggleRoom, gobboRoom, tavernRoom, tavernAvoid :: Int
attackDamage = 20 -- assume attacks do at least this much damage
wiggleRoom = 10 -- don't fight without at least this much wiggle-room
gobboRoom = 10 -- with less than this health, avoid gobbos
tavernRoom = 90 -- with less than this health, drink when near a tavern
tavernAvoid = 95 -- with more than this health, never drink near a tavern
-- Determine whether we need a drink.
needsDrink :: Int -> Hero -> Bool
-- be far more willing to drink when near a tavern than when far
-- dist * 5 : assumes about an opportunity cost of 2.5g/tile when drinking
needsDrink dist us =
us^.heroLife <= max (tavernRoom - dist * 5) wiggleRoom
-- Determines whether a hero should assail another hero.
-- (minding that we can't trust others to follow the same logic)
canFight :: Int -> Hero -> Hero -> Bool
canFight dist assailant target =
assailant^.heroLife - dist > target^.heroLife + wiggleRoom + attackDamage
-- Determines whether a hero can even assail another hero. If it's false, the
-- assailant will just get maimed to death.
canEverFight :: Int -> Hero -> Hero -> Bool
canEverFight dist assailant target =
assailant^.heroLife - dist > target^.heroLife + attackDamage
-- Determines whether a hero can take a mine without dying.
canTakeMine :: Int -> Hero -> Bool
canTakeMine dist us =
us^.heroLife - dist > gobboRoom + attackDamage
-- The score which indicates a venue is no longer worth pursuing, or that it must be pursued.
-- Think of it as an unenforced ceiling.
overwhelming :: Int
overwhelming = 1000
-- returns true if we should attack something given their current avoidance ratio
shouldAttackRatio :: (Int, Int) -> Bool
shouldAttackRatio = (<0.7) . uncurry ((/) `on` fromIntegral) -- require 7/10 misses at most
initialAvoidanceRatio :: (Int, Int)
initialAvoidanceRatio = (0, 2) -- begin assuming we've successfully attacked twice
| Zekka/whidgle | src/Whidgle/Rules.hs | mit | 2,374 | 0 | 10 | 418 | 364 | 216 | 148 | 32 | 1 |
{- |
Module : $Header$
Description : library names for HetCASL and development graphs
Copyright : (c) Christian Maeder, DFKI GmbH 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : portable
Abstract syntax of HetCASL specification libraries
Follows Sect. II:2.2.5 of the CASL Reference Manual.
-}
module Common.LibName where
import Common.Doc
import Common.DocUtils
import Common.Id
import Common.Keywords
import Common.Utils
import Data.Char
import Data.List
import Data.Ord
import System.FilePath
import System.Time
import Data.Graph.Inductive.Graph
omTs :: [Token]
omTs = [genToken "OM"]
mkQualName :: SIMPLE_ID -> LibId -> Id -> Id
mkQualName nodeId libId i =
Id omTs [i, simpleIdToId nodeId, libIdToId libId] $ posOfId i
isQualNameFrom :: SIMPLE_ID -> LibId -> Id -> Bool
isQualNameFrom nodeId libId i@(Id _ cs _) = case cs of
_ : n : l : _ | isQualName i ->
n == simpleIdToId nodeId && libIdToId libId == l
_ -> True
isQualName :: Id -> Bool
isQualName (Id ts cs _) = case cs of
_ : _ : _ -> ts == omTs
_ -> False
libIdOfQualName :: Id -> Id
libIdOfQualName j@(Id _ cs _) = case cs of
[_, _, i] | isQualName j -> i
_ -> error "libIdOfQualName: Check by isQualName before calling getLibId!"
getNodeId :: Id -> Id
getNodeId j@(Id _ cs _) = case cs of
[_, i, _] | isQualName j -> i
_ -> error "Check by isQualName before calling getNodeId!"
unQualName :: Id -> Id
unQualName j@(Id _ cs _) = case cs of
i : _ | isQualName j -> i
_ -> j
libIdToId :: LibId -> Id
libIdToId li = let
path = splitOn '/' $ show li
toTok s = Token s $ getRange li
in mkId $ map toTok $ intersperse "/" path
data LibName = LibName
{ getLibId :: LibId
, libVersion :: Maybe VersionNumber }
emptyLibName :: String -> LibName
emptyLibName s = LibName (IndirectLink s nullRange "" noTime) Nothing
data LibId = IndirectLink PATH Range FilePath ClockTime
-- pos: start of PATH
noTime :: ClockTime
noTime = TOD 0 0
-- | Returns the LibId of a LibName
getModTime :: LibId -> ClockTime
getModTime (IndirectLink _ _ _ m) = m
updFilePathOfLibId :: FilePath -> ClockTime -> LibId -> LibId
updFilePathOfLibId fp mt (IndirectLink p r _ _) = IndirectLink p r fp mt
setFilePath :: FilePath -> ClockTime -> LibName -> LibName
setFilePath fp mt ln =
ln { getLibId = updFilePathOfLibId fp mt $ getLibId ln }
getFilePath :: LibName -> FilePath
getFilePath ln =
case getLibId ln of
IndirectLink _ _ fp _ -> fp
data VersionNumber = VersionNumber [String] Range
-- pos: "version", start of first string
type PATH = String
instance GetRange LibId where
getRange (IndirectLink _ r _ _) = r
instance Show LibId where
show (IndirectLink s1 _ _ _) = s1
instance GetRange LibName where
getRange = getRange . getLibId
instance Show LibName where
show = show . hsep . prettyLibName
prettyVersionNumber :: VersionNumber -> [Doc]
prettyVersionNumber (VersionNumber v _) =
[keyword versionS, hcat $ punctuate dot $ map codeToken v]
prettyLibName :: LibName -> [Doc]
prettyLibName (LibName i mv) = pretty i : case mv of
Nothing -> []
Just v -> prettyVersionNumber v
instance Eq LibId where
IndirectLink s1 _ _ _ == IndirectLink s2 _ _ _ = s1 == s2
instance Ord LibId where
IndirectLink s1 _ _ _ <= IndirectLink s2 _ _ _ = s1 <= s2
instance Eq LibName where
ln1 == ln2 = compare ln1 ln2 == EQ
instance Ord LibName where
compare = comparing getLibId
instance Pretty LibName where
pretty = fsep . prettyLibName
instance Pretty LibId where
pretty = structId . show
data LinkPath a = LinkPath a [(LibId, Node)] deriving (Ord, Eq)
type SLinkPath = LinkPath String
showSLinkPath :: SLinkPath -> String
showSLinkPath (LinkPath x l) = s l where
s ((_, n) : l1) = show n ++ "/" ++ s l1
s _ = x
instance Show a => Show (LinkPath a) where
show (LinkPath x l) = showSLinkPath $ LinkPath (show x) l
instance Functor LinkPath where
fmap f (LinkPath x l) = LinkPath (f x) l
addToPath :: LibId -> Node -> LinkPath a -> LinkPath a
addToPath libid n (LinkPath x l) = LinkPath x $ (libid, n) : l
initPath :: LibId -> Node -> a -> LinkPath a
initPath libid n x = LinkPath x [(libid, n)]
convertFileToLibStr :: FilePath -> String
convertFileToLibStr = mkLibStr . takeBaseName
stripLibChars :: String -> String
stripLibChars = filter (\ c -> isAlphaNum c || elem c "'_/")
mkLibStr :: String -> String
mkLibStr = dropWhile (== '/') . stripLibChars
| nevrenato/Hets_Fork | Common/LibName.hs | gpl-2.0 | 4,558 | 0 | 12 | 999 | 1,589 | 812 | 777 | 111 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.IReader
-- License : GPL-2
-- Maintainer : yi-devel@googlegroups.com
-- Stability : experimental
-- Portability : portable
--
-- This module defines a list type and operations on it; it further
-- provides functions which write in and out the list. The goal is to
-- make it easy for the user to store a large number of text buffers
-- and cycle among them, making edits as she goes. The idea is
-- inspired by \"incremental reading\", see
-- <http://en.wikipedia.org/wiki/Incremental_reading>.
module Yi.IReader where
import Control.Exception
import Control.Monad
import Data.Binary
import qualified Data.ByteString.Char8 as B (pack, unpack, readFile, ByteString)
import qualified Data.ByteString.Lazy.Char8 as BL (fromChunks)
import Data.Default
import Data.Sequence as S
import Data.Typeable
import Yi.Buffer.HighLevel (replaceBufferContent, topB)
import Yi.Buffer.Misc (getBufferDyn, putBufferDyn, elemsB)
import Yi.Editor (withCurrentBuffer)
import Yi.Keymap (YiM)
import Yi.Paths (getArticleDbFilename)
import qualified Yi.Rope as R
import Yi.Utils
import Yi.Types (YiVariable)
-- | TODO: Why 'B.ByteString'?
type Article = B.ByteString
newtype ArticleDB = ADB { unADB :: Seq Article }
deriving (Typeable, Binary)
instance Default ArticleDB where
def = ADB S.empty
instance YiVariable ArticleDB
-- | Take an 'ArticleDB', and return the first 'Article' and an
-- ArticleDB - *without* that article.
split :: ArticleDB -> (Article, ArticleDB)
split (ADB adb) = case viewl adb of
EmptyL -> (B.pack "", def)
(a :< b) -> (a, ADB b)
-- | Get the first article in the list. We use the list to express
-- relative priority; the first is the most, the last least. We then
-- just cycle through - every article gets equal time.
getLatestArticle :: ArticleDB -> Article
getLatestArticle = fst . split -- we only want the article
-- | We remove the old first article, and we stick it on the end of the
-- list using the presumably modified version.
removeSetLast :: ArticleDB -> Article -> ArticleDB
removeSetLast adb old = ADB (unADB (snd (split adb)) S.|> old)
-- we move the last entry to the entry 'length `div` n'from the
-- beginning; so 'shift 1' would do nothing (eg. the last index is 50,
-- 50 `div` 1 == 50, so the item would be moved to where it is) 'shift
-- 2' will move it to the middle of the list, though; last index = 50,
-- then 50 `div` 2 will shift the item to index 25, and so on down to
-- 50 `div` 50 - the head of the list/Seq.
shift :: Int ->ArticleDB -> ArticleDB
shift n adb = if n < 2 || lst < 2 then adb else ADB $ (r S.|> lastentry) >< s'
where lst = S.length (unADB adb) - 1
(r,s) = S.splitAt (lst `div` n) (unADB adb)
(s' :> lastentry) = S.viewr s
-- | Insert a new article with top priority (that is, at the front of the list).
insertArticle :: ArticleDB -> Article -> ArticleDB
insertArticle (ADB adb) new = ADB (new S.<| adb)
-- | Serialize given 'ArticleDB' out.
writeDB :: ArticleDB -> YiM ()
writeDB adb = void $ io . join . fmap (`encodeFile` adb) $ getArticleDbFilename
-- | Read in database from 'getArticleDbFilename' and then parse it
-- into an 'ArticleDB'.
readDB :: YiM ArticleDB
readDB = io $ (getArticleDbFilename >>= r) `catch` returnDefault
where r = fmap (decode . BL.fromChunks . return) . B.readFile
-- We read in with strict bytestrings to guarantee the file is
-- closed, and then we convert it to the lazy bytestring
-- data.binary expects. This is inefficient, but alas...
returnDefault (_ :: SomeException) = return def
-- | Returns the database as it exists on the disk, and the current Yi
-- buffer contents. Note that the Default typeclass gives us an empty
-- Seq. So first we try the buffer state in the hope we can avoid a
-- very expensive read from disk, and if we find nothing (that is, if
-- we get an empty Seq), only then do we call 'readDB'.
oldDbNewArticle :: YiM (ArticleDB, Article)
oldDbNewArticle = do
saveddb <- withCurrentBuffer getBufferDyn
newarticle <- fmap (B.pack . R.toString) $ withCurrentBuffer elemsB
if not $ S.null (unADB saveddb)
then return (saveddb, newarticle)
else readDB >>= \olddb -> return (olddb, newarticle)
-- | Given an 'ArticleDB', dump the scheduled article into the buffer
-- (replacing previous contents).
setDisplayedArticle :: ArticleDB -> YiM ()
setDisplayedArticle newdb = do
let next = getLatestArticle newdb
withCurrentBuffer $ do
replaceBufferContent $ R.fromString (B.unpack next)
topB -- replaceBufferContents moves us to bottom?
putBufferDyn newdb
-- | Go to next one. This ignores the buffer, but it doesn't remove
-- anything from the database. However, the ordering does change.
nextArticle :: YiM ()
nextArticle = do
(oldb,_) <- oldDbNewArticle
-- Ignore buffer, just set the first article last
let newdb = removeSetLast oldb (getLatestArticle oldb)
writeDB newdb
setDisplayedArticle newdb
-- | Delete current article (the article as in the database), and go
-- to next one.
deleteAndNextArticle :: YiM ()
deleteAndNextArticle = do
(oldb,_) <- oldDbNewArticle -- throw away changes
let ndb = ADB $ case viewl (unADB oldb) of -- drop 1st article
EmptyL -> empty
(_ :< b) -> b
writeDB ndb
setDisplayedArticle ndb
-- | The main action. We fetch the old database, we fetch the modified
-- article from the buffer, then we call the function 'updateSetLast'
-- which removes the first article and pushes our modified article to
-- the end of the list.
saveAndNextArticle :: Int -> YiM ()
saveAndNextArticle n = do
(oldb,newa) <- oldDbNewArticle
let newdb = shift n $ removeSetLast oldb newa
writeDB newdb
setDisplayedArticle newdb
-- | Assume the buffer is an entirely new article just imported this
-- second, and save it. We don't want to use 'updateSetLast' since
-- that will erase an article.
saveAsNewArticle :: YiM ()
saveAsNewArticle = do
oldb <- readDB -- make sure we read from disk - we aren't in iread-mode!
(_,newa) <- oldDbNewArticle -- we ignore the fst - the Default is 'empty'
let newdb = insertArticle oldb newa
writeDB newdb
| atsukotakahashi/wi | src/library/Yi/IReader.hs | gpl-2.0 | 6,476 | 0 | 15 | 1,334 | 1,174 | 647 | 527 | 89 | 2 |
module Display (idle, display) where
import Graphics.UI.GLUT
import Control.Monad
import Data.IORef
import Cube
import Points
display :: IORef GLfloat -> IORef (GLfloat, GLfloat) -> DisplayCallback
display angle pos = do
clear [ColorBuffer, DepthBuffer] -- clear depth buffer, too
clear [ColorBuffer]
loadIdentity
(x',y') <- get pos
translate $ Vector3 x' y' 0
preservingMatrix $ do
a <- get angle
rotate a $ Vector3 0 0 1
rotate a $ Vector3 0 0.1 1 -- changed y-component a bit to show off cube corners
scale 0.7 0.7 (0.7::GLfloat)
forM_ (points 7) $ \(x,y,z) -> preservingMatrix $ do
color $ Color3 ((x+1)/2) ((y+1)/2) ((z+1)/2)
translate $ Vector3 x y z
cube 0.1
color $ Color3 (0::GLfloat) 0 0 -- set outline color to black
cubeFrame 0.1 -- draw the outline
swapBuffers
idle :: IORef GLfloat -> IORef GLfloat -> IdleCallback
idle angle delta = do
d <- get delta
angle $~! (+ d)
postRedisplay Nothing
| MaximusDesign/Haskell_Project | display.hs | gpl-2.0 | 982 | 0 | 20 | 230 | 389 | 193 | 196 | 30 | 1 |
module SetProp
where
import Helpers
import Ticket
toTwo :: [a] -> [(a, a)]
toTwo (a:b:xs) = (a,b):toTwo xs
toTwo _ = []
setProp :: Ticket -> [String] -> IO ()
setProp tick vals = do
putStrLn $ "property to: " ++ title tick ++ " - " ++ (show vals) ++ "."
saveTicket (addCategories (toTwo vals) tick)
handleSetProp args = paramList setProp args "set" "Usage: set ticket-name category-class category"
| anttisalonen/nix | src/SetProp.hs | gpl-3.0 | 414 | 0 | 11 | 85 | 173 | 90 | 83 | 11 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Commands.List (commands) where
import Core
import Options
import Pretty.List
( AnyField(..)
, Field(..)
, FieldSpec(..)
, (=.)
, buildOptions
, buildOptionsWithoutId
)
import Schema
commands :: Command (SqlM ())
commands = CommandGroup CommandInfo
{ commandName = "list"
, commandHeaderDesc = "list database entries"
, commandDesc =
"List database entries of various information stored in the database."
} [ SingleCommand CommandInfo
{ commandName = "algorithm"
, commandHeaderDesc = "list registered algorithms"
, commandDesc = "List all registered algorithms."
}
$ buildOptions
[ "name" =. StringField 'n' $ Simple AlgorithmName
, "pretty-name" =. StringField 'p' $ Optional AlgorithmPrettyName
]
, SingleCommand CommandInfo
{ commandName = "dataset"
, commandHeaderDesc = "list registered datasets"
, commandDesc = "List all registered datasets."
}
$ buildOptions ([] :: [(String, FieldSpec Dataset)])
, SingleCommand CommandInfo
{ commandName = "external-impl"
, commandHeaderDesc = "list external implementations"
, commandDesc = "List all external implementations."
}
$ buildOptions
[ "algorith" =. IdField 'a' $ Simple ExternalImplAlgorithmId
, "name" =. StringField 'n' $ Simple ExternalImplName
, "pretty-name" =. StringField 'p' $ Optional ExternalImplPrettyName
]
, SingleCommand CommandInfo
{ commandName = "external-timer"
, commandHeaderDesc = "list timings of external implementations"
, commandDesc = "List all timings of external implementations."
}
$ buildOptionsWithoutId
[ AnyField ExternalTimerPlatformId
, AnyField ExternalTimerVariantId
, AnyField ExternalTimerImplId
]
[ "platform" =. IdField 'p' $ Simple ExternalTimerPlatformId
, "variant" =. IdField 'v' $ Simple ExternalTimerVariantId
, "implementation" =. IdField 'i' $ Simple ExternalTimerImplId
, "algorithm" =. IdField 'a' $ Simple ExternalTimerAlgorithmId
, "name" =. StringField 'n' $ Simple ExternalTimerName
, "min" =. SortOnlyField $ ExternalTimerMinTime
, "avg" =. SortOnlyField $ ExternalTimerAvgTime
, "max" =. SortOnlyField $ ExternalTimerMaxTime
, "std-dev" =. SortOnlyField $ ExternalTimerStdDev
]
, SingleCommand CommandInfo
{ commandName = "graph"
, commandHeaderDesc = "list graphs"
, commandDesc = "List all graphs."
}
$ buildOptions
[ "name" =. StringField 'n' $ Simple GraphName
, "dataset" =. IdField 'd' $ Simple GraphDatasetId
, "pretty-name" =. StringField 'r' $ Optional GraphPrettyName
, "path" =. StringField 'p' $ Simple GraphPath
]
, SingleCommand CommandInfo
{ commandName = "implementation"
, commandHeaderDesc = "list implementations"
, commandDesc = "List all implementations."
}
$ buildOptions
[ "algorithm" =. IdField 'a' $ Simple ImplementationAlgorithmId
, "name" =. StringField 'n' $ Simple ImplementationName
, "type" =. EnumField 't' $ Simple ImplementationType
, "pretty-name" =. StringField 'p' $ Optional ImplementationPrettyName
]
, SingleCommand CommandInfo
{ commandName = "platform"
, commandHeaderDesc = "list platforms"
, commandDesc = "List all platforms."
}
$ buildOptions
[ "name" =. StringField 'n' $ Simple PlatformName
, "pretty-name" =. StringField 'p' $ Optional PlatformPrettyName
, "available" =. SortOnlyField $ PlatformAvailable
, "default" =. SortOnlyField $ PlatformIsDefault
]
, SingleCommand CommandInfo
{ commandName = "properties"
, commandHeaderDesc = "list properties"
, commandDesc = "List all properties."
}
$ buildOptions
[ "property" =. StringField 'p' $ Simple PropertyNameProperty
, "step-prop" =. EnumField 's' $ Simple PropertyNameIsStepProp
]
, SingleCommand CommandInfo
{ commandName = "graph-properties"
, commandHeaderDesc = "list graph properties"
, commandDesc = "List all graph properties."
}
$ buildOptionsWithoutId
[ AnyField GraphPropValueGraphId
, AnyField GraphPropValuePropId
]
[ "graph" =. IdField 'g' $ Simple GraphPropValueGraphId
, "graph-prop" =. IdField 'p' $ Simple GraphPropValuePropId
, "value" =. SortOnlyField $ GraphPropValueValue
]
, SingleCommand CommandInfo
{ commandName = "step-properties"
, commandHeaderDesc = "list step properties"
, commandDesc = "List all step properties."
}
$ buildOptionsWithoutId
[ AnyField StepPropValueAlgorithmId
, AnyField StepPropValueVariantId
, AnyField StepPropValueStepId
, AnyField StepPropValuePropId
]
[ "algorithm" =. IdField 'a' $ Simple StepPropValueAlgorithmId
, "variant" =. IdField 'v' $ Simple StepPropValueVariantId
, "step" =. IntField 's' $ Simple StepPropValueStepId
, "prop-id" =. IdField 'p' $ Simple StepPropValuePropId
, "value" =. SortOnlyField $ StepPropValueValue
]
, SingleCommand CommandInfo
{ commandName = "run-config"
, commandHeaderDesc = "list run configs"
, commandDesc = "List all run configs."
}
$ buildOptions
[ "algorithm" =. IdField 'a' $ Simple RunConfigAlgorithmId
, "platform" =. IdField 'p' $ Simple RunConfigPlatformId
, "dataset" =. IdField 'd' $ Simple RunConfigDatasetId
, "commit" =. StringField 'c' $
Converted RunConfigAlgorithmVersion CommitId
, "repeats" =. SortOnlyField $ RunConfigRepeats
]
, SingleCommand CommandInfo
{ commandName = "run"
, commandHeaderDesc = "list runs"
, commandDesc = "List all runs."
}
$ buildOptions
[ "run-config" =. IdField 'r' $ Simple RunRunConfigId
, "algorithm" =. IdField 'a' $ Simple RunAlgorithmId
, "variant" =. IdField 'v' $ Simple RunVariantId
, "implementation" =. IdField 'i' $ Simple RunImplId
, "validated" =. EnumField 'l' $ Simple RunValidated
, "time" =. SortOnlyField $ RunTimestamp
]
, SingleCommand CommandInfo
{ commandName = "timer"
, commandHeaderDesc = "list global timers"
, commandDesc = "List all global timers."
}
$ buildOptionsWithoutId
[AnyField TotalTimerRunId, AnyField TotalTimerName]
[ "run" =. IdField 'r' $ Simple TotalTimerRunId
, "name" =. StringField 'n' $ Simple TotalTimerName
, "min" =. SortOnlyField $ TotalTimerMinTime
, "avg" =. SortOnlyField $ TotalTimerAvgTime
, "max" =. SortOnlyField $ TotalTimerMaxTime
, "stddev" =. SortOnlyField $ TotalTimerStdDev
]
, SingleCommand CommandInfo
{ commandName = "step-timer"
, commandHeaderDesc = "list step timers"
, commandDesc = "List all step timers."
}
$ buildOptionsWithoutId
[ AnyField StepTimerRunId
, AnyField StepTimerStepId
, AnyField StepTimerName
]
[ "run" =. IdField 'r' $ Simple StepTimerRunId
, "step" =. IntField 's' $ Simple StepTimerStepId
, "name" =. StringField 'n' $ Simple StepTimerName
, "min" =. SortOnlyField $ StepTimerMinTime
, "avg" =. SortOnlyField $ StepTimerAvgTime
, "max" =. SortOnlyField $ StepTimerMaxTime
, "stddev" =. SortOnlyField $ StepTimerStdDev
]
, SingleCommand CommandInfo
{ commandName = "variant-config"
, commandHeaderDesc = "list variant configs"
, commandDesc = "List all variant configs."
}
$ buildOptions
[ "name" =. StringField 'n' $ Simple VariantConfigName
, "algorithm" =. IdField 'a' $ Simple VariantConfigAlgorithmId
, "default" =. SortOnlyField $ VariantConfigIsDefault
]
, SingleCommand CommandInfo
{ commandName = "variant"
, commandHeaderDesc = "list registered variant"
, commandDesc = "List all registered variants."
}
$ buildOptions
[ "variantconfig" =. IdField 'v' $ Simple VariantVariantConfigId
, "algorithm" =. IdField 'a' $ Simple VariantAlgorithmId
, "graph" =. IdField 'g' $ Simple VariantGraphId
, "props-stored" =. EnumField 'p' $ Simple VariantPropsStored
, "retries" =. SortOnlyField $ VariantRetryCount
]
]
| merijn/GPU-benchmarks | benchmark-analysis/ingest-src/Commands/List.hs | gpl-3.0 | 9,279 | 0 | 12 | 2,967 | 1,786 | 935 | 851 | 180 | 1 |
{-# LANGUAGE FlexibleInstances #-}
module AnsiParser.Types where
import qualified Data.ByteString.Char8 as B
import Data.String (IsString)
data Color
= Black
| Red
| Green
| Brown
| Blue
| Magenta
| Cyan
| White
deriving (Show, Eq)
data ColorPos
= Foreground
| Background
deriving (Show, Eq)
data ColorCmd
= DefaultColor -- other stuff to, TODO
| Bold
| Set (Color, ColorPos)
deriving (Show, Eq)
-- Here, we will handle "ESC ] 0" (set both icon name + window title)
-- by replacing it with two separate commands.
data OSCmd
= IconName String
| WindowTitle String
| ColorOverride Integer String
| DynamicTextColor String
| Font String
deriving (Show, Eq)
data C1
= Index -- = D
| NextLine -- = E
| TabSet -- = H
| ReverseIndex -- = M
| SS2 -- Single shift select of G2 character set; = N
| SS3 -- like SS2, but for G3; = O
| StartGuarded -- = V
| EndGuarded -- = W
| ReturnTerminalId -- = Z
| PrivacyMessage -- = ^
| APC -- Application program command, = _
deriving (Show, Eq, Enum, Ord)
-- not implemented: | StartString -- = X
data Cmd
= CSI Char [String] -- Control Sequence (Initiator)
| SGR [ColorCmd] -- Select Graphic Rendition i.e. colors, fonts
| OSC OSCmd -- Operating System Command
| NonPrint NonPrint -- A nonprinting character
| C1 C1
deriving (Show, Eq)
data NonPrint
= Bell
| Backspace
| CarriageReturn
| Enquiry
| FormFeed
| LineFeed
| ShiftIn
| ShiftOut
| VerticalTab
deriving (Show, Eq, Ord, Enum)
data Expr
= Plain String
| Cmd Cmd
deriving (Show, Eq)
| pscollins/ansi-parser | src/AnsiParser/Types.hs | gpl-3.0 | 1,590 | 0 | 7 | 387 | 358 | 222 | 136 | 65 | 0 |
{-# LANGUAGE FlexibleContexts #-}
module NA.Image.Utils
( channelToDouble
, channelToWord8
, normalise
, duplicate
, toHSV
)
where
import NA.Image
import Control.Monad
import Data.Word
import Data.Array.ST
import Data.Array.Unboxed
channelToDouble :: Channel Word8 -> Channel Double
channelToDouble = amap fromIntegral
channelToWord8 :: Channel Double -> Channel Word8
channelToWord8 = amap truncate
normalise :: (Fractional b, Ord b, IArray UArray b) => Image b -> Image b
normalise = imap normaliseChannel
normaliseChannel :: (Fractional e, Ord e, Ix i, IArray a e) => a i e -> a i e
normaliseChannel c = let cMax = cfold1 max c
cMin = cfold1 min c
in amap (\x -> 255*(x-cMin)/(cMax-cMin)) c
duplicate :: Image Word8 -> Image Word8 -> Image Word8
duplicate (Image r1 g1 b1) (Image r2 g2 b2) = Image r g b
where r = duplicateChannel r1 r2
g = duplicateChannel g1 g2
b = duplicateChannel b1 b2
duplicateChannel :: Channel Word8 -> Channel Word8 -> Channel Word8
duplicateChannel c1 c2 = runSTUArray $ do
dup <- newArray ((h0, w0), (h1, width)) 0
forM_ (Prelude.reverse $ range ((h0,w0), (h1,w1))) $ \(y,x) -> do
let x' = x + (w1-w0+1) + 4 + w0 -1
writeArray dup (y,x ) $ c1!(y,x)
writeArray dup (y,x') $ c2!(y,x)
return dup
where ((h0, w0), (h1, w1)) = bounds c1
width = (w1-w0+1)*2 + 4 + w0 - 1
toHSV :: (Integral e, IArray UArray e, IArray a e) => Image e -> (a Coordinate e, a Coordinate e, a Coordinate e)
toHSV (Image r g b) = let triplets = zip3 (elems r) (elems g) (elems b)
(h, s, v) = unzip3 $ map (getHSV 0) triplets
sizes = bounds r
mkArray = array sizes . zip (range sizes)
in (mkArray h, mkArray s, mkArray v)
getHSV :: Integral t => t -> (t, t, t) -> (t, t, t)
getHSV disp triplet@(x, y, z)
| cMax == x = finishHSV triplet cMin disp
| otherwise = getHSV (disp+85) (y, z, x)
where cMax = maximum [x, y, z]
cMin = minimum [x, y, z]
finishHSV :: Integral t => (t, t, t) -> t -> t -> (t, t, t)
finishHSV (x, y, z) cMin disp = let v = x
s = x - cMin
h = 43 * (y - z) `div` s + disp
in (h, s, v)
| paradoja/numerical-analysis-haskell | NA/Image/Utils.hs | gpl-3.0 | 2,554 | 0 | 21 | 938 | 1,081 | 571 | 510 | 54 | 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.SourceRepo.Projects.UpdateConfig
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates the Cloud Source Repositories configuration of the project.
--
-- /See:/ <https://cloud.google.com/source-repositories/docs/apis Cloud Source Repositories API Reference> for @sourcerepo.projects.updateConfig@.
module Network.Google.Resource.SourceRepo.Projects.UpdateConfig
(
-- * REST Resource
ProjectsUpdateConfigResource
-- * Creating a Request
, projectsUpdateConfig
, ProjectsUpdateConfig
-- * Request Lenses
, pucXgafv
, pucUploadProtocol
, pucAccessToken
, pucUploadType
, pucPayload
, pucName
, pucCallback
) where
import Network.Google.Prelude
import Network.Google.SourceRepo.Types
-- | A resource alias for @sourcerepo.projects.updateConfig@ method which the
-- 'ProjectsUpdateConfig' request conforms to.
type ProjectsUpdateConfigResource =
"v1" :>
Capture "name" Text :>
"config" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] UpdateProjectConfigRequest :>
Patch '[JSON] ProjectConfig
-- | Updates the Cloud Source Repositories configuration of the project.
--
-- /See:/ 'projectsUpdateConfig' smart constructor.
data ProjectsUpdateConfig =
ProjectsUpdateConfig'
{ _pucXgafv :: !(Maybe Xgafv)
, _pucUploadProtocol :: !(Maybe Text)
, _pucAccessToken :: !(Maybe Text)
, _pucUploadType :: !(Maybe Text)
, _pucPayload :: !UpdateProjectConfigRequest
, _pucName :: !Text
, _pucCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsUpdateConfig' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pucXgafv'
--
-- * 'pucUploadProtocol'
--
-- * 'pucAccessToken'
--
-- * 'pucUploadType'
--
-- * 'pucPayload'
--
-- * 'pucName'
--
-- * 'pucCallback'
projectsUpdateConfig
:: UpdateProjectConfigRequest -- ^ 'pucPayload'
-> Text -- ^ 'pucName'
-> ProjectsUpdateConfig
projectsUpdateConfig pPucPayload_ pPucName_ =
ProjectsUpdateConfig'
{ _pucXgafv = Nothing
, _pucUploadProtocol = Nothing
, _pucAccessToken = Nothing
, _pucUploadType = Nothing
, _pucPayload = pPucPayload_
, _pucName = pPucName_
, _pucCallback = Nothing
}
-- | V1 error format.
pucXgafv :: Lens' ProjectsUpdateConfig (Maybe Xgafv)
pucXgafv = lens _pucXgafv (\ s a -> s{_pucXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pucUploadProtocol :: Lens' ProjectsUpdateConfig (Maybe Text)
pucUploadProtocol
= lens _pucUploadProtocol
(\ s a -> s{_pucUploadProtocol = a})
-- | OAuth access token.
pucAccessToken :: Lens' ProjectsUpdateConfig (Maybe Text)
pucAccessToken
= lens _pucAccessToken
(\ s a -> s{_pucAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pucUploadType :: Lens' ProjectsUpdateConfig (Maybe Text)
pucUploadType
= lens _pucUploadType
(\ s a -> s{_pucUploadType = a})
-- | Multipart request metadata.
pucPayload :: Lens' ProjectsUpdateConfig UpdateProjectConfigRequest
pucPayload
= lens _pucPayload (\ s a -> s{_pucPayload = a})
-- | The name of the requested project. Values are of the form
-- \`projects\/\`.
pucName :: Lens' ProjectsUpdateConfig Text
pucName = lens _pucName (\ s a -> s{_pucName = a})
-- | JSONP
pucCallback :: Lens' ProjectsUpdateConfig (Maybe Text)
pucCallback
= lens _pucCallback (\ s a -> s{_pucCallback = a})
instance GoogleRequest ProjectsUpdateConfig where
type Rs ProjectsUpdateConfig = ProjectConfig
type Scopes ProjectsUpdateConfig =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsUpdateConfig'{..}
= go _pucName _pucXgafv _pucUploadProtocol
_pucAccessToken
_pucUploadType
_pucCallback
(Just AltJSON)
_pucPayload
sourceRepoService
where go
= buildClient
(Proxy :: Proxy ProjectsUpdateConfigResource)
mempty
| brendanhay/gogol | gogol-sourcerepo/gen/Network/Google/Resource/SourceRepo/Projects/UpdateConfig.hs | mpl-2.0 | 5,146 | 0 | 17 | 1,188 | 779 | 454 | 325 | 113 | 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.CloudResourceManager.Projects.GetIAMPolicy
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns the IAM access control policy for the specified project.
-- Permission is denied if the policy or the resource do not exist.
--
-- /See:/ <https://cloud.google.com/resource-manager Cloud Resource Manager API Reference> for @cloudresourcemanager.projects.getIamPolicy@.
module Network.Google.Resource.CloudResourceManager.Projects.GetIAMPolicy
(
-- * REST Resource
ProjectsGetIAMPolicyResource
-- * Creating a Request
, projectsGetIAMPolicy
, ProjectsGetIAMPolicy
-- * Request Lenses
, pgipXgafv
, pgipUploadProtocol
, pgipAccessToken
, pgipUploadType
, pgipPayload
, pgipResource
, pgipCallback
) where
import Network.Google.Prelude
import Network.Google.ResourceManager.Types
-- | A resource alias for @cloudresourcemanager.projects.getIamPolicy@ method which the
-- 'ProjectsGetIAMPolicy' request conforms to.
type ProjectsGetIAMPolicyResource =
"v3" :>
CaptureMode "resource" "getIamPolicy" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] GetIAMPolicyRequest :>
Post '[JSON] Policy
-- | Returns the IAM access control policy for the specified project.
-- Permission is denied if the policy or the resource do not exist.
--
-- /See:/ 'projectsGetIAMPolicy' smart constructor.
data ProjectsGetIAMPolicy =
ProjectsGetIAMPolicy'
{ _pgipXgafv :: !(Maybe Xgafv)
, _pgipUploadProtocol :: !(Maybe Text)
, _pgipAccessToken :: !(Maybe Text)
, _pgipUploadType :: !(Maybe Text)
, _pgipPayload :: !GetIAMPolicyRequest
, _pgipResource :: !Text
, _pgipCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsGetIAMPolicy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pgipXgafv'
--
-- * 'pgipUploadProtocol'
--
-- * 'pgipAccessToken'
--
-- * 'pgipUploadType'
--
-- * 'pgipPayload'
--
-- * 'pgipResource'
--
-- * 'pgipCallback'
projectsGetIAMPolicy
:: GetIAMPolicyRequest -- ^ 'pgipPayload'
-> Text -- ^ 'pgipResource'
-> ProjectsGetIAMPolicy
projectsGetIAMPolicy pPgipPayload_ pPgipResource_ =
ProjectsGetIAMPolicy'
{ _pgipXgafv = Nothing
, _pgipUploadProtocol = Nothing
, _pgipAccessToken = Nothing
, _pgipUploadType = Nothing
, _pgipPayload = pPgipPayload_
, _pgipResource = pPgipResource_
, _pgipCallback = Nothing
}
-- | V1 error format.
pgipXgafv :: Lens' ProjectsGetIAMPolicy (Maybe Xgafv)
pgipXgafv
= lens _pgipXgafv (\ s a -> s{_pgipXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pgipUploadProtocol :: Lens' ProjectsGetIAMPolicy (Maybe Text)
pgipUploadProtocol
= lens _pgipUploadProtocol
(\ s a -> s{_pgipUploadProtocol = a})
-- | OAuth access token.
pgipAccessToken :: Lens' ProjectsGetIAMPolicy (Maybe Text)
pgipAccessToken
= lens _pgipAccessToken
(\ s a -> s{_pgipAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pgipUploadType :: Lens' ProjectsGetIAMPolicy (Maybe Text)
pgipUploadType
= lens _pgipUploadType
(\ s a -> s{_pgipUploadType = a})
-- | Multipart request metadata.
pgipPayload :: Lens' ProjectsGetIAMPolicy GetIAMPolicyRequest
pgipPayload
= lens _pgipPayload (\ s a -> s{_pgipPayload = a})
-- | REQUIRED: The resource for which the policy is being requested. See the
-- operation documentation for the appropriate value for this field.
pgipResource :: Lens' ProjectsGetIAMPolicy Text
pgipResource
= lens _pgipResource (\ s a -> s{_pgipResource = a})
-- | JSONP
pgipCallback :: Lens' ProjectsGetIAMPolicy (Maybe Text)
pgipCallback
= lens _pgipCallback (\ s a -> s{_pgipCallback = a})
instance GoogleRequest ProjectsGetIAMPolicy where
type Rs ProjectsGetIAMPolicy = Policy
type Scopes ProjectsGetIAMPolicy =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only"]
requestClient ProjectsGetIAMPolicy'{..}
= go _pgipResource _pgipXgafv _pgipUploadProtocol
_pgipAccessToken
_pgipUploadType
_pgipCallback
(Just AltJSON)
_pgipPayload
resourceManagerService
where go
= buildClient
(Proxy :: Proxy ProjectsGetIAMPolicyResource)
mempty
| brendanhay/gogol | gogol-resourcemanager/gen/Network/Google/Resource/CloudResourceManager/Projects/GetIAMPolicy.hs | mpl-2.0 | 5,513 | 0 | 16 | 1,219 | 782 | 457 | 325 | 115 | 1 |
-- pfacs 20 -> [2, 5]
module Pr35 (pfacs', pfacs, unique, primes) where
import Pr31 -- isqrt, isprime
import Pr33 -- c -- coprime
import Pr32 -- g -- gcd
pfacs' :: Int -> [Int]
pfacs' n =
if isprime n then [n] else
let
ps = takeWhile (<= (isqrt n)) primes
p = head $ filter (\x -> not (c x n)) ps
in p:(pfacs' $ div n p)
-- usage e.g. take 4 primes -> [2,3,5,7]
primes = filter isprime [2..]
pfacs :: Int -> [Int]
pfacs n = (unique . pfacs') n
unique :: Eq a => [a] -> [a]
unique [] = []
unique [x] = [x]
unique (x:xs) = x : unique [y | y <- xs, y /= x]
| ekalosak/haskell-practice | Pr35.hs | lgpl-3.0 | 587 | 0 | 16 | 158 | 273 | 150 | 123 | 18 | 2 |
module Hecate.Error (module Hecate.Error) where
import Control.Exception (Exception)
import Data.Typeable (Typeable)
import TOML (TOMLError)
-- | 'AppError' represents application errors
data AppError
= CsvDecoding String
| TOML TOMLError
| Configuration String
| Aeson String
| GPG String
| Database String
| FileSystem String
| AmbiguousInput String
| Migration String
| Default String
deriving (Typeable)
instance Show AppError where
show (CsvDecoding s) = "CSV Decoding Error: " ++ s
show (TOML e) = show e
show (Configuration s) = "Configuration Error: " ++ s
show (Aeson s) = "Aeson Error: " ++ s
show (GPG s) = s
show (Database s) = "Database Error: " ++ s
show (FileSystem s) = "Filesystem Error: " ++ s
show (AmbiguousInput s) = "Ambiguous Input: " ++ s
show (Migration s) = "Migration Error: " ++ s
show (Default s) = "Error: " ++ s
instance Exception AppError
| henrytill/hecate | src/Hecate/Error.hs | apache-2.0 | 1,021 | 0 | 8 | 294 | 294 | 157 | 137 | 28 | 0 |
module Redigo where
| aloiscochard/redigo | src/Redigo.hs | apache-2.0 | 20 | 0 | 2 | 3 | 4 | 3 | 1 | 1 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE JavaScriptFFI #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PackageImports #-}
{-
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-
Thanks to Luite Stegeman, whose code this is heavily based on.
Note that this code is very dependent on the internals of GHCJS, so
complain if this is broken. It's not unlikely.
-}
{- If you want to do these things you are a bad person and you should feel bad -}
module Internal.DeepEq where
import Control.Exception (evaluate)
import Control.Monad
import "base" Prelude
import System.IO.Unsafe
import Unsafe.Coerce
#ifdef ghcjs_HOST_OS
import GHCJS.Foreign
import GHCJS.Types
import JavaScript.Array
-- traverse the object and get the thunks out of it
foreign import javascript unsafe "cw$getThunks($1)"
js_getThunks :: Int -> IO JSArray
foreign import javascript unsafe "cw$deepEq($1, $2)"
js_deepEq :: Int -> Int -> IO Bool
data JSRefD a = JSRefD a
evaluateFully :: a -> IO a
evaluateFully x = do
x' <- evaluate x
ths <- js_getThunks (unsafeCoerce x')
when (not $ isNull $ unsafeCoerce ths) $ forM_ (toList ths) evalElem
return x'
where
evalElem :: JSRef Int -> IO ()
evalElem y =
let (JSRefD o) = unsafeCoerce y in void (evaluateFully o)
deepEq :: a -> a -> Bool
deepEq x y = unsafePerformIO $ do
x' <- evaluateFully x
y' <- evaluateFully y
js_deepEq (unsafeCoerce x') (unsafeCoerce y')
#else
evaluateFully :: a -> IO a
evaluateFully x = error "Only available with GHCJS"
deepEq :: a -> a -> Bool
deepEq x y = error "Only available with GHCJS"
#endif
| d191562687/codeworld | codeworld-base/src/Internal/DeepEq.hs | apache-2.0 | 2,323 | 6 | 12 | 537 | 335 | 171 | 164 | 16 | 1 |
module Segments.Common.Time where
import Data.Time (formatTime, defaultTimeLocale)
import Data.Time.LocalTime (getZonedTime)
import Segments.Base
-- powerline.segments.common.time.date
timeDateSegment :: SegmentHandler
timeDateSegment args _ = do
let isTime = argLookup args "istime" False
let fmt = argLookup args "format" "%Y-%m-%d"
let hlGroup = flip HighlightGroup Nothing $
if isTime
then "time"
else "date"
t <- getZonedTime
return2 $ Segment hlGroup $ formatTime defaultTimeLocale fmt t
| rdnetto/powerline-hs | src/Segments/Common/Time.hs | apache-2.0 | 583 | 0 | 11 | 150 | 138 | 71 | 67 | 14 | 2 |
module HEP.Util.Parsing where
import Control.Monad.Identity
import Control.Exception (bracket)
import Text.Parsec
import System.IO
readConfig :: (Show a) => FilePath -> (ParsecT String () Identity a) -> IO a
readConfig fp parser = do
putStrLn fp
bracket (openFile fp ReadMode) hClose $ \fh -> do
str <- hGetContents fh
let r = parse parser "" str
case r of
Right result -> do putStrLn (show result)
return $! result
Left err -> error (show err)
| wavewave/HEPUtil | src/HEP/Util/Parsing.hs | bsd-2-clause | 512 | 0 | 18 | 140 | 192 | 94 | 98 | 15 | 2 |
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-}
module Handler.Forening where
import Import
getForeningR :: Forening -> Handler Html
getForeningR forening = standardLayout $(widgetFile "forening")
| dtekcth/DtekPortalen | src/Handler/Forening.hs | bsd-2-clause | 216 | 0 | 8 | 25 | 40 | 21 | 19 | 5 | 1 |
{-# LANGUAGE OverloadedLists #-}
module FnReps.Polynomial.UnaryChebSparse where
import FnReps.Polynomial.UnaryChebSparse.DCTMultiplication
--import Numeric.AERN.MPFRBasis.Interval
import Numeric.AERN.DoubleBasis.Interval ()
import qualified Data.HashMap.Strict as HM
{-|
Unary polynomials over the domain [-1,1] with interval coefficients in the Chebyshev basis.
The interval coefficients are supposed to have a very small width.
-}
data UnaryChebSparse =
UnaryChebSparse
{
unaryChebSparse_terms :: HM.HashMap Int RA
}
-- deriving (Show)
instance Show UnaryChebSparse where
show (UnaryChebSparse terms) =
"(UnaryChebSparse " ++ show (HM.toList terms) ++ ")"
instance Eq UnaryChebSparse where
(==) = error "cannot compare UnaryChebSparse interval polynomials for equality, please use ==? instead of == etc."
instance Ord UnaryChebSparse where
compare = error "cannot compare UnaryChebSparse interval polynomials for equality, please use >? instead of > etc."
instance Num UnaryChebSparse where
fromInteger n = UnaryChebSparse (HM.singleton 0 (fromInteger n))
abs _ = error $ "abs not implemented for UnaryChebSparse interval polynomials."
signum _ = error $ "signum not implemented for UnaryChebSparse interval polynomials."
negate (UnaryChebSparse terms) =
UnaryChebSparse $ fmap negate terms
(UnaryChebSparse termsL) + (UnaryChebSparse termsR) =
UnaryChebSparse $ HM.unionWith (+) termsL termsR
(UnaryChebSparse terms1) * (UnaryChebSparse terms2) =
UnaryChebSparse $ multiplyDCT_terms terms1 terms2
| michalkonecny/aern | aern-fnreps/src/FnReps/Polynomial/UnaryChebSparse.hs | bsd-3-clause | 1,628 | 0 | 11 | 313 | 286 | 152 | 134 | 25 | 0 |
{-# LANGUAGE TemplateHaskell, TypeFamilies #-}
module Linear.NURBS.Types (
Weight(..), weightPoint, weightValue, ofWeight, weight, wpoint,
Span(..), spanStart, spanEnd,
KnotData(..), knotData, knotDataAt, knotDataSpan,
NURBS(..), nurbsPoints, nurbsKnot, nurbsKnoti, nurbsDegree
) where
import Prelude.Unicode
import Control.Lens
import Linear.Vector hiding (basis)
import Linear.Affine
import Linear.Metric
-- | Point with weight
data Weight f a = Weight { _weightPoint ∷ f a, _weightValue ∷ a } deriving (Eq, Ord, Read, Show)
makeLenses ''Weight
-- | Make point with weight
ofWeight ∷ Additive f ⇒ f a → a → Weight f a
pt `ofWeight` w = Weight pt w
-- | Weight lens
weight ∷ (Additive f, Fractional a) ⇒ Lens' (Weight f a) a
weight = lens fromw tow where
fromw (Weight _ w) = w
tow (Weight pt w) w' = Weight ((w' / w) *^ pt) w'
-- | Point lens
wpoint ∷ (Additive f, Additive g, Fractional a) ⇒ Lens (Weight f a) (Weight g a) (f a) (g a)
wpoint = lens fromw tow where
fromw (Weight pt w) = (1.0 / w) *^ pt
tow (Weight _ w) pt' = Weight (w *^ pt') w
instance Functor f ⇒ Functor (Weight f) where
fmap f (Weight pt w) = Weight (fmap f pt) (f w)
instance Traversable f ⇒ Traversable (Weight f) where
traverse f (Weight pt w) = Weight <$> traverse f pt <*> f w
instance Additive f ⇒ Additive (Weight f) where
zero = Weight zero 0
Weight lx lw ^+^ Weight rx rw = Weight (lx ^+^ rx) (lw + rw)
Weight lx lw ^-^ Weight rx rw = Weight (lx ^-^ rx) (lw - rw)
lerp a (Weight lx lw) (Weight rx rw) = Weight (lerp a lx rx) (a * lw + (1 - a) * rw)
liftU2 f (Weight lx lw) (Weight rx rw) = Weight (liftU2 f lx rx) (f lw rw)
liftI2 f (Weight lx lw) (Weight rx rw) = Weight (liftI2 f lx rx) (f lw rw)
instance Affine f ⇒ Affine (Weight f) where
type Diff (Weight f) = Weight (Diff f)
Weight lx lw .-. Weight rx rw = Weight (lx .-. rx) (lw - rw)
Weight lx lw .+^ Weight x w = Weight (lx .+^ x) (lw + w)
Weight lx lw .-^ Weight x w = Weight (lx .-^ x) (lw - w)
instance Foldable f ⇒ Foldable (Weight f) where
foldMap f (Weight x w) = foldMap f x `mappend` f w
instance Metric f ⇒ Metric (Weight f) where
dot (Weight lx lw) (Weight rx rw) = dot lx rx + lw * rw
-- | Knot span
data Span a = Span {
_spanStart ∷ a,
_spanEnd ∷ a }
deriving (Eq, Ord, Read)
makeLenses ''Span
instance Functor Span where
fmap f (Span s e) = Span (f s) (f e)
instance Foldable Span where
foldMap f (Span s e) = f s `mappend` f e
instance Traversable Span where
traverse f (Span s e) = Span <$> f s <*> f e
instance Show a ⇒ Show (Span a) where
show (Span s e) = show (s, e)
-- | Knot evaluation data, used to compute basis functions
data KnotData a = KnotData {
_knotDataAt ∷ a,
_knotDataSpan ∷ Span a,
_knotData ∷ [(Span a, a)] }
deriving (Eq, Ord, Read, Show)
makeLenses ''KnotData
-- | NURBS
data NURBS f a = NURBS {
_nurbsPoints ∷ [Weight f a],
_nurbsKnot ∷ [a],
_nurbsDegree ∷ Int }
deriving (Eq, Ord, Read, Show)
makeLenses ''NURBS
instance Functor f ⇒ Functor (NURBS f) where
fmap f (NURBS pts k d) = NURBS (map (fmap f) pts) (map f k) d
instance Foldable f ⇒ Foldable (NURBS f) where
foldMap f (NURBS pts k _) = mconcat (map (foldMap f) pts) `mappend` mconcat (map f k)
nurbsKnoti ∷ Lens' (NURBS f a) [a]
nurbsKnoti = lens fromn ton where
fromn (NURBS wpts k d)
| length k ≡ succ (length wpts) = k
| otherwise = drop d $ reverse $ drop d $ reverse k
ton (NURBS wpts k d) k'
| length k ≡ succ (length wpts) = NURBS wpts k' d
| otherwise = NURBS wpts (replicate d (k' ^?! _head) ++ k' ++ replicate d (k' ^?! _last)) d
| mvoidex/nurbs | src/Linear/NURBS/Types.hs | bsd-3-clause | 3,622 | 32 | 14 | 790 | 1,845 | 939 | 906 | -1 | -1 |
import Data.List (findIndex, sortBy)
import Data.Function (on)
import Data.Maybe (fromJust)
import Data.Array
import Data.Array.ST
import Control.Monad (forM_)
import Control.Monad.ST
import Text.Printf
squares = ["GO", "A1", "CC1", "A2", "T1", "R1", "B1", "CH1", "B2", "B3", "JAIL", "C1", "U1", "C2", "C3", "R2", "D1", "CC2", "D2", "D3", "FP", "E1", "CH2", "E2", "E3", "R3", "F1", "F2", "U2", "F3", "G2J", "G1", "G2", "CC3", "G3", "R4", "CH3", "H1", "T2", "H2"]
nDice = 4
nSquare = length squares
getIndex :: String -> Int
getIndex square = fromJust $ findIndex (== square) squares
fall :: String -> [String]
fall "G2J" = ["JAIL"]
fall cc@('C':'C':c) = "GO" : "JAIL" : replicate 14 cc
fall ch@('C':'H':c) = "GO" : "JAIL" : "C1" : "E3" : "H2" : "R1" : nextR : nextR : nextU : back3 : replicate 6 ch where
index = getIndex ch
back3 = squares !! ((index - 3) `mod` nSquare)
nextR = case c of
"1" -> "R2"
"2" -> "R3"
"3" -> "R1"
nextU = case c of
"1" -> "U1"
"2" -> "U2"
"3" -> "U1"
fall x = [x]
type State = (Int, Int) -- (sqr, doubles)
type StateArray = Array State Double
go' :: State -> Double -> [(State, Double)]
go' (sqr, doubles) prob = concat $ do
x <- [1 .. nDice]
y <- [1 .. nDice]
let doubles' = if x == y then (doubles + 1) else 0
let sqr' = squares !! ((sqr + x + y) `mod` nSquare)
let (sqr'', doubles'') = tryGoJail (sqr', doubles')
let falls = fall sqr''
let prob'' = prob / ((fromIntegral nDice) ^ 2) / (fromIntegral (length falls))
return $ zip (zip (map getIndex falls) (repeat doubles'')) (repeat prob'') where
tryGoJail (_, 3) = ("JAIL", 0)
tryGoJail x = x
go :: StateArray -> StateArray
go probs = runSTArray $ do
ret <- newArray ((0, 0), (nSquare - 1, 2)) 0 :: ST s (STArray s State Double)
forM_ [0 .. nSquare - 1] $ \sqr -> do
forM_ [0 .. 2] $ \doubles -> do
let expands = go' (sqr, doubles) (probs!(sqr, doubles))
forM_ expands $ \((sqr', doubles'), prob') -> do
old <- readArray ret (sqr', doubles')
writeArray ret (sqr', doubles') (old + prob')
return ret
goIter :: StateArray -> Int -> StateArray
goIter probs 0 = probs
goIter probs count = goIter (go probs) (count - 1)
solve :: Array Int Double
solve = runSTArray $ do
ret <- newArray (0, nSquare - 1) 0 :: ST s (STArray s Int Double)
let probs = goIter init 233
forM_ [0 .. nSquare - 1] $ \sqr -> do
writeArray ret sqr ((probs!(sqr, 0)) + (probs!(sqr, 1)) + (probs!(sqr, 2)))
return ret
where init = listArray ((0, 0), (nSquare - 1, 2)) (1 : repeat 0)
main = putStrLn $ concat $ map (printNum . fst) $ take 3 $ reverse $ sortBy (compare `on` snd) (assocs solve) where
printNum :: Int -> String
printNum = printf "%02d"
| foreverbell/project-euler-solutions | src/84.hs | bsd-3-clause | 2,834 | 0 | 22 | 722 | 1,323 | 721 | 602 | 66 | 5 |
-- !!! Testing Refs
import Data.IORef
a1 =
newIORef 'a' >>= \ v ->
readIORef v >>= \ x ->
print x
a2 =
newIORef 'a' >>= \ v ->
writeIORef v 'b' >>
readIORef v >>= \ x ->
print x
a3 =
newIORef 'a' >>= \ v1 ->
newIORef 'a' >>= \ v2 ->
print (v1 == v1, v1 == v2, v2 == v2)
| FranklinChen/Hugs | tests/rts/refs.hs | bsd-3-clause | 293 | 20 | 11 | 89 | 153 | 78 | 75 | 14 | 1 |
module EmbedTest where
import Syntax
import Driving
import Util.Miscellaneous
checkStep = Invoke "cS"
step = Invoke "s"
getAnswer = Invoke "gA"
getTime = Invoke "gT"
add = Invoke "a"
checkPerson = Invoke "cP"
movePerson = Invoke "mP"
moveLight = Invoke "mL"
times = Invoke "t"
ololo = Invoke "ololo"
g1 = [checkStep([C "St" [C "T" [], C "T" [], C "T" []],V 3,C "T" []]) , step([C "St" [C "T" [], C "T" [], C "T" []],V 3,V 7]) , getAnswer([V 4, V 7, C "some" [V 8]]) , getTime([V 3, V 10]) , add([V 10,V 8, V 9])]
g2 = [checkPerson([C "St" [C "T" [], C "T" [], C "T" []],V 36,C "T" []]) , movePerson([C "St" [C "T" [], C "T" [], C "T" []],V 36,V 21]) , moveLight([V 21,V 7]) , checkStep([V 7, V 26,C "T" []]) , step([V 7, V 26,V 30]) , getAnswer([V 27,V 30,C "some" [V 31]]) , getTime([V 26,V 33]) , add([V 33,V 31,V 32]) , times([V 36,C "S" [V 41]]) , add([V 41,C "S" [V 32],V 9])]
g3 = [checkPerson([C "St" [C "T" [], C "T" [], C "T" []],V 36,C "T" []]) , movePerson([C "St" [C "T" [], C "T" [], C "T" []],V 36,V 21]) , moveLight([V 21,V 7]) , checkStep([V 7, V 26,C "T" []]) , ololo([]), step([V 7, V 26,V 30]) , getAnswer([V 27,V 30,C "some" [V 31]]) , getTime([V 26,V 33]) , add([V 33,V 31,V 32]) , times([V 36,C "S" [V 41]]) , add([V 41,C "S" [V 32],V 9])]
test = embedGoals g1 g2
test' = map (map trd3) (split (map (\ x -> (undefined, undefined, x)) g3) g1)
| kajigor/uKanren_transformations | test/EmbedTest.hs | bsd-3-clause | 1,502 | 0 | 12 | 410 | 1,081 | 560 | 521 | 19 | 1 |
{-# Language TypeFamilies #-}
module Data.Source.ByteString.Lazy.Char8.Offset where
import Data.Char
import Data.Source.Class
import qualified Data.ByteString.Lazy as B
data Src
= Src
{ loc :: Int
, str :: B.ByteString
} deriving (Eq,Ord,Show,Read)
mkSrc :: B.ByteString -> Src
mkSrc = Src 0
instance Source Src where
type Location Src = Int
type Element Src = Char
type Token Src = B.ByteString
type Error Src = ()
offset = loc
uncons (Src loc bs)
= Right $ B.uncons bs >>= \(w,t) ->
let ch = chr $ fromIntegral w
in return (ch, Src (loc+1) t)
view (Src loc bs) _ eh nh
= case B.uncons bs of
Nothing -> eh
Just (w,t) -> let ch = chr $ fromIntegral w
in nh ch $ Src (loc+1) t
location (Src ofs _)
= ofs
token (Src lloc lbs) (Src rloc _)
= B.take (fromIntegral $ rloc - lloc) lbs
| permeakra/source | Data/Source/ByteString/Lazy/Char8/Offset.hs | bsd-3-clause | 932 | 0 | 14 | 298 | 373 | 199 | 174 | 31 | 1 |
{-# LANGUAGE BangPatterns, CPP, Rank2Types, ScopedTypeVariables,
TypeOperators #-}
-- |
-- Module: Data.BloomFilter
-- Copyright: Bryan O'Sullivan
-- License: BSD3
--
-- Maintainer: Bryan O'Sullivan <bos@serpentine.com>
-- Stability: unstable
-- Portability: portable
--
-- A fast, space efficient Bloom filter implementation. A Bloom
-- filter is a set-like data structure that provides a probabilistic
-- membership test.
--
-- * Queries do not give false negatives. When an element is added to
-- a filter, a subsequent membership test will definitely return
-- 'True'.
--
-- * False positives /are/ possible. If an element has not been added
-- to a filter, a membership test /may/ nevertheless indicate that
-- the element is present.
--
-- This module provides low-level control. For an easier to use
-- interface, see the "Data.BloomFilter.Easy" module.
module Data.BloomFilter
(
-- * Overview
-- $overview
-- ** Ease of use
-- $ease
-- ** Performance
-- $performance
-- * Types
Hash
, Bloom
, MBloom
-- * Immutable Bloom filters
-- ** Creation
, unfoldB
, fromListB
, emptyB
, singletonB
-- ** Accessors
, lengthB
, elemB
, notElemB
-- ** Mutators
, insertB
, insertListB
-- * Mutable Bloom filters
-- ** Immutability wrappers
, createB
, modifyB
-- ** Creation
, newMB
, unsafeFreezeMB
, thawMB
-- ** Accessors
, lengthMB
, elemMB
-- ** Mutation
, insertMB
-- * The underlying representation
-- | If you serialize the raw bit arrays below to disk, do not
-- expect them to be portable to systems with different
-- conventions for endianness or word size.
-- | The raw bit array used by the immutable 'Bloom' type.
, bitArrayB
-- | The raw bit array used by the immutable 'MBloom' type.
, bitArrayMB
-- | Reconstruction
, constructB
) where
#include "MachDeps.h"
import Control.Monad (liftM, forM_)
import Control.Monad.ST (ST, runST)
import Control.DeepSeq (NFData(..))
import Data.Array.Base (unsafeAt, unsafeRead, unsafeWrite)
import Data.Array.ST (STUArray, thaw, unsafeFreeze)
import Data.Array.Unboxed (UArray, assocs)
import Data.Bits ((.&.), (.|.))
import Data.BloomFilter.Array (newArray)
import Data.BloomFilter.Util (FastShift(..), (:*)(..), nextPowerOfTwo)
import Data.Word (Word32)
-- Make sure we're not performing any expensive arithmetic operations.
import Prelude hiding ((/), div, divMod, mod, rem)
{-
import Debug.Trace
traceM :: (Show a, Monad m) => a -> m ()
traceM v = show v `trace` return ()
traces :: Show a => a -> b -> b
traces s = trace (show s)
-}
-- | A hash value is 32 bits wide. This limits the maximum size of a
-- filter to about four billion elements, or 512 megabytes of memory.
type Hash = Word32
-- | A mutable Bloom filter, for use within the 'ST' monad.
data MBloom s a = MB {
hashMB :: !(a -> [Hash])
, shiftMB :: {-# UNPACK #-} !Int
, maskMB :: {-# UNPACK #-} !Int
, bitArrayMB :: {-# UNPACK #-} !(STUArray s Int Hash)
}
-- | An immutable Bloom filter, suitable for querying from pure code.
data Bloom a = B {
hashB :: !(a -> [Hash])
, shiftB :: {-# UNPACK #-} !Int
, maskB :: {-# UNPACK #-} !Int
, bitArrayB :: {-# UNPACK #-} !(UArray Int Hash)
}
instance Show (MBloom s a) where
show mb = "MBloom { " ++ show (lengthMB mb) ++ " bits } "
instance Show (Bloom a) where
show ub = "Bloom { " ++ show (lengthB ub) ++ " bits } "
instance NFData (Bloom a) where
rnf !_ = ()
-- | Create a new mutable Bloom filter. For efficiency, the number of
-- bits used may be larger than the number requested. It is always
-- rounded up to the nearest higher power of two, but clamped at a
-- maximum of 4 gigabits, since hashes are 32 bits in size.
--
-- For a safer creation interface, use 'createB'. To convert a
-- mutable filter to an immutable filter for use in pure code, use
-- 'unsafeFreezeMB'.
newMB :: (a -> [Hash]) -- ^ family of hash functions to use
-> Int -- ^ number of bits in filter
-> ST s (MBloom s a)
newMB hash numBits = MB hash shift mask `liftM` newArray numElems numBytes
where twoBits | numBits < 1 = 1
| numBits > maxHash = maxHash
| isPowerOfTwo numBits = numBits
| otherwise = nextPowerOfTwo numBits
numElems = max 2 (twoBits `shiftR` logBitsInHash)
numBytes = numElems `shiftL` logBytesInHash
trueBits = numElems `shiftL` logBitsInHash
shift = logPower2 trueBits
mask = trueBits - 1
isPowerOfTwo n = n .&. (n - 1) == 0
maxHash :: Int
#if WORD_SIZE_IN_BITS == 64
maxHash = 4294967296
#else
maxHash = 1073741824
#endif
logBitsInHash :: Int
logBitsInHash = 5 -- logPower2 bitsInHash
logBytesInHash :: Int
logBytesInHash = 2 -- logPower2 (sizeOf (undefined :: Hash))
-- | Create an immutable Bloom filter, using the given setup function
-- which executes in the 'ST' monad.
--
-- Example:
--
-- @
--import "Data.BloomFilter.Hash" (cheapHashes)
--
--filter = createB (cheapHashes 3) 1024 $ \mf -> do
-- insertMB mf \"foo\"
-- insertMB mf \"bar\"
-- @
--
-- Note that the result of the setup function is not used.
createB :: (a -> [Hash]) -- ^ family of hash functions to use
-> Int -- ^ number of bits in filter
-> (forall s. (MBloom s a -> ST s z)) -- ^ setup function (result is discarded)
-> Bloom a
{-# INLINE createB #-}
createB hash numBits body = runST $ do
mb <- newMB hash numBits
_ <- body mb
unsafeFreezeMB mb
-- | Create an empty Bloom filter.
--
-- This function is subject to fusion with 'insertB'
-- and 'insertListB'.
emptyB :: (a -> [Hash]) -- ^ family of hash functions to use
-> Int -- ^ number of bits in filter
-> Bloom a
{-# INLINE [1] emptyB #-}
emptyB hash numBits = createB hash numBits (\_ -> return ())
-- | Create a Bloom filter with a single element.
--
-- This function is subject to fusion with 'insertB'
-- and 'insertListB'.
singletonB :: (a -> [Hash]) -- ^ family of hash functions to use
-> Int -- ^ number of bits in filter
-> a -- ^ element to insert
-> Bloom a
{-# INLINE [1] singletonB #-}
singletonB hash numBits elt = createB hash numBits (\mb -> insertMB mb elt)
-- | Given a filter's mask and a hash value, compute an offset into
-- a word array and a bit offset within that word.
hashIdx :: Int -> Word32 -> (Int :* Int)
hashIdx mask x = (y `shiftR` logBitsInHash) :* (y .&. hashMask)
where hashMask = 31 -- bitsInHash - 1
y = fromIntegral x .&. mask
-- | Hash the given value, returning a list of (word offset, bit
-- offset) pairs, one per hash value.
hashesM :: MBloom s a -> a -> [Int :* Int]
hashesM mb elt = hashIdx (maskMB mb) `map` hashMB mb elt
-- | Hash the given value, returning a list of (word offset, bit
-- offset) pairs, one per hash value.
hashesU :: Bloom a -> a -> [Int :* Int]
hashesU ub elt = hashIdx (maskB ub) `map` hashB ub elt
-- | Insert a value into a mutable Bloom filter. Afterwards, a
-- membership query for the same value is guaranteed to return @True@.
insertMB :: MBloom s a -> a -> ST s ()
insertMB mb elt = do
let mu = bitArrayMB mb
forM_ (hashesM mb elt) $ \(word :* bit) -> do
old <- unsafeRead mu word
unsafeWrite mu word (old .|. (1 `shiftL` bit))
-- | Query a mutable Bloom filter for membership. If the value is
-- present, return @True@. If the value is not present, there is
-- /still/ some possibility that @True@ will be returned.
elemMB :: a -> MBloom s a -> ST s Bool
elemMB elt mb = loop (hashesM mb elt)
where mu = bitArrayMB mb
loop ((word :* bit):wbs) = do
i <- unsafeRead mu word
if i .&. (1 `shiftL` bit) == 0
then return False
else loop wbs
loop _ = return True
-- | Query an immutable Bloom filter for membership. If the value is
-- present, return @True@. If the value is not present, there is
-- /still/ some possibility that @True@ will be returned.
elemB :: a -> Bloom a -> Bool
elemB elt ub = all test (hashesU ub elt)
where test (off :* bit) = (bitArrayB ub `unsafeAt` off) .&. (1 `shiftL` bit) /= 0
modifyB :: (forall s. (MBloom s a -> ST s z)) -- ^ mutation function (result is discarded)
-> Bloom a
-> Bloom a
{-# INLINE modifyB #-}
modifyB body ub = runST $ do
mb <- thawMB ub
_ <- body mb
unsafeFreezeMB mb
-- | Create a new Bloom filter from an existing one, with the given
-- member added.
--
-- This function may be expensive, as it is likely to cause the
-- underlying bit array to be copied.
--
-- Repeated applications of this function with itself are subject to
-- fusion.
insertB :: a -> Bloom a -> Bloom a
{-# NOINLINE insertB #-}
insertB elt = modifyB (flip insertMB elt)
-- | Create a new Bloom filter from an existing one, with the given
-- members added.
--
-- This function may be expensive, as it is likely to cause the
-- underlying bit array to be copied.
--
-- Repeated applications of this function with itself are subject to
-- fusion.
insertListB :: [a] -> Bloom a -> Bloom a
{-# NOINLINE insertListB #-}
insertListB elts = modifyB $ \mb -> mapM_ (insertMB mb) elts
{-# RULES "Bloom insertB . insertB" forall a b u.
insertB b (insertB a u) = insertListB [a,b] u
#-}
{-# RULES "Bloom insertListB . insertB" forall x xs u.
insertListB xs (insertB x u) = insertListB (x:xs) u
#-}
{-# RULES "Bloom insertB . insertListB" forall x xs u.
insertB x (insertListB xs u) = insertListB (x:xs) u
#-}
{-# RULES "Bloom insertListB . insertListB" forall xs ys u.
insertListB xs (insertListB ys u) = insertListB (xs++ys) u
#-}
{-# RULES "Bloom insertListB . emptyB" forall h n xs.
insertListB xs (emptyB h n) = fromListB h n xs
#-}
{-# RULES "Bloom insertListB . singletonB" forall h n x xs.
insertListB xs (singletonB h n x) = fromListB h n (x:xs)
#-}
-- | Query an immutable Bloom filter for non-membership. If the value
-- /is/ present, return @False@. If the value is not present, there
-- is /still/ some possibility that @True@ will be returned.
notElemB :: a -> Bloom a -> Bool
notElemB elt ub = any test (hashesU ub elt)
where test (off :* bit) = (bitArrayB ub `unsafeAt` off) .&. (1 `shiftL` bit) == 0
-- | Create an immutable Bloom filter from a mutable one. The mutable
-- filter /must not/ be modified afterwards, or a runtime crash may
-- occur. For a safer creation interface, use 'createB'.
unsafeFreezeMB :: MBloom s a -> ST s (Bloom a)
unsafeFreezeMB mb = B (hashMB mb) (shiftMB mb) (maskMB mb) `liftM`
unsafeFreeze (bitArrayMB mb)
-- | Copy an immutable Bloom filter to create a mutable one. There is
-- no non-copying equivalent.
thawMB :: Bloom a -> ST s (MBloom s a)
thawMB ub = MB (hashB ub) (shiftB ub) (maskB ub) `liftM` thaw (bitArrayB ub)
-- bitsInHash :: Int
-- bitsInHash = sizeOf (undefined :: Hash) `shiftL` 3
-- | Return the size of a mutable Bloom filter, in bits.
lengthMB :: MBloom s a -> Int
lengthMB = shiftL 1 . shiftMB
-- | Return the size of an immutable Bloom filter, in bits.
lengthB :: Bloom a -> Int
lengthB = shiftL 1 . shiftB
-- | Build an immutable Bloom filter from a seed value. The seeding
-- function populates the filter as follows.
--
-- * If it returns 'Nothing', it is finished producing values to
-- insert into the filter.
--
-- * If it returns @'Just' (a,b)@, @a@ is added to the filter and
-- @b@ is used as a new seed.
unfoldB :: forall a b. (a -> [Hash]) -- ^ family of hash functions to use
-> Int -- ^ number of bits in filter
-> (b -> Maybe (a, b)) -- ^ seeding function
-> b -- ^ initial seed
-> Bloom a
{-# INLINE unfoldB #-}
unfoldB hashes numBits f k = createB hashes numBits (loop k)
where loop :: forall s. b -> MBloom s a -> ST s ()
loop j mb = case f j of
Just (a, j') -> insertMB mb a >> loop j' mb
_ -> return ()
-- | Create an immutable Bloom filter, populating it from a list of
-- values.
--
-- Here is an example that uses the @cheapHashes@ function from the
-- "Data.BloomFilter.Hash" module to create a hash function that
-- returns three hashes.
--
-- @
--import "Data.BloomFilter.Hash" (cheapHashes)
--
--filt = fromListB (cheapHashes 3) 1024 [\"foo\", \"bar\", \"quux\"]
-- @
fromListB :: (a -> [Hash]) -- ^ family of hash functions to use
-> Int -- ^ number of bits in filter
-> [a] -- ^ values to populate with
-> Bloom a
{-# INLINE [1] fromListB #-}
fromListB hashes numBits list = createB hashes numBits $ forM_ list . insertMB
{-# RULES "Bloom insertListB . fromListB" forall h n xs ys.
insertListB xs (fromListB h n ys) = fromListB h n (xs ++ ys)
#-}
{-
-- This is a simpler definition, but GHC doesn't inline the unfold
-- sensibly.
fromListB hashes numBits = unfoldB hashes numBits convert
where convert (x:xs) = Just (x, xs)
convert _ = Nothing
-}
-- | Slow, crummy way of computing the integer log of an integer known
-- to be a power of two.
logPower2 :: Int -> Int
logPower2 k = go 0 k
where go j 1 = j
go j n = go (j+1) (n `shiftR` 1)
-- $overview
--
-- Each of the functions for creating Bloom filters accepts two parameters:
--
-- * The number of bits that should be used for the filter. Note that
-- a filter is fixed in size; it cannot be resized after creation.
--
-- * A function that accepts a value, and should return a fixed-size
-- list of hashes of that value. To keep the false positive rate
-- low, the hashes computes should, as far as possible, be
-- independent.
--
-- By choosing these parameters with care, it is possible to tune for
-- a particular false positive rate. The @suggestSizing@ function in
-- the "Data.BloomFilter.Easy" module calculates useful estimates for
-- these parameters.
-- $ease
--
-- This module provides both mutable and immutable interfaces for
-- creating and querying a Bloom filter. It is most useful as a
-- low-level way to create a Bloom filter with a custom set of
-- characteristics, perhaps in combination with the hashing functions
-- in 'Data.BloomFilter.Hash'.
--
-- For a higher-level interface that is easy to use, see the
-- 'Data.BloomFilter.Easy' module.
-- $performance
--
-- The implementation has been carefully tuned for high performance
-- and low space consumption.
--
-- For efficiency, the number of bits requested when creating a Bloom
-- filter is rounded up to the nearest power of two. This lets the
-- implementation use bitwise operations internally, instead of much
-- more expensive multiplication, division, and modulus operations.
-- Reconstruction
{-# INLINE constructB #-}
constructB :: (a -> [Hash])
-> UArray Int Hash
-> Bloom a
constructB hash array = B hash shift mask array
where
assc = assocs array
numElems = length assc
numBytes = numElems * (2 ^ logBytesInHash)
trueBits = numElems `shiftL` logBitsInHash
shift = logPower2 trueBits
mask = trueBits - 1
| brinchj/bloomfilter | Data/BloomFilter.hs | bsd-3-clause | 15,366 | 0 | 15 | 3,793 | 2,530 | 1,445 | 1,085 | 197 | 3 |
-- | Facilities for composing SOAC functions. Mostly intended for use
-- by the fusion module, but factored into a separate module for ease
-- of testing, debugging and development. Of course, there is nothing
-- preventing you from using the exported functions whereever you
-- want.
--
-- Important: this module is \"dumb\" in the sense that it does not
-- check the validity of its inputs, and does not have any
-- functionality for massaging SOACs to be fusible. It is assumed
-- that the given SOACs are immediately compatible.
--
-- The module will, however, remove duplicate inputs after fusion.
module Futhark.Optimise.Fusion.Composing
( fuseMaps
, fuseRedomap
, mergeReduceOps
)
where
import Data.List
import qualified Data.HashMap.Lazy as HM
import qualified Data.HashSet as HS
import qualified Data.Map as M
import Data.Maybe
import qualified Futhark.Analysis.HORepresentation.SOAC as SOAC
import Futhark.Representation.AST
import Futhark.Binder
(Bindable(..), insertBinding, insertBindings, mkLet')
import Futhark.Construct (mapResult)
-- | @fuseMaps lam1 inp1 out1 lam2 inp2@ fuses the function @lam1@ into
-- @lam2@. Both functions must be mapping functions, although @lam2@
-- may have leading reduction parameters. @inp1@ and @inp2@ are the
-- array inputs to the SOACs containing @lam1@ and @lam2@
-- respectively. @out1@ are the identifiers to which the output of
-- the SOAC containing @lam1@ is bound. It is nonsensical to call
-- this function unless the intersection of @out1@ and @inp2@ is
-- non-empty.
--
-- If @lam2@ accepts more parameters than there are elements in
-- @inp2@, it is assumed that the surplus (which are positioned at the
-- beginning of the parameter list) are reduction (accumulator)
-- parameters, that do not correspond to array elements, and they are
-- thus not modified.
--
-- The result is the fused function, and a list of the array inputs
-- expected by the SOAC containing the fused function.
fuseMaps :: Bindable lore =>
Names -- ^ The producer var names that still need to be returned
-> Lambda lore -- ^ Function of SOAC to be fused.
-> [SOAC.Input] -- ^ Input of SOAC to be fused.
-> [(VName,Ident)] -- ^ Output of SOAC to be fused. The
-- first identifier is the name of the
-- actual output, where the second output
-- is an identifier that can be used to
-- bind a single element of that output.
-> Lambda lore -- ^ Function to be fused with.
-> [SOAC.Input] -- ^ Input of SOAC to be fused with.
-> (Lambda lore, [SOAC.Input]) -- ^ The fused lambda and the inputs of
-- the resulting SOAC.
fuseMaps unfus_nms lam1 inp1 out1 lam2 inp2 = (lam2', HM.elems inputmap)
where lam2' =
lam2 { lambdaParams = [ Param name t
| Ident name t <- lam2redparams ++ HM.keys inputmap ]
, lambdaBody = new_body2'
}
new_body2 = let bnds res = [ mkLet' [] [p] $ PrimOp $ SubExp e
| (p,e) <- zip pat res]
bindLambda res =
bnds res `insertBindings` makeCopiesInner (lambdaBody lam2)
in makeCopies $ mapResult bindLambda (lambdaBody lam1)
new_body2_rses = bodyResult new_body2
new_body2'= new_body2 { bodyResult = new_body2_rses ++
map (Var . identName) unfus_pat }
-- infusible variables are added at the end of the result/pattern/type
(lam2redparams, unfus_pat, pat, inputmap, makeCopies, makeCopiesInner) =
fuseInputs unfus_nms lam1 inp1 out1 lam2 inp2
--(unfus_accpat, unfus_arrpat) = splitAt (length unfus_accs) unfus_pat
fuseInputs :: Bindable lore =>
Names
-> Lambda lore -> [SOAC.Input] -> [(VName,Ident)]
-> Lambda lore -> [SOAC.Input]
-> ([Ident], [Ident], [Ident],
HM.HashMap Ident SOAC.Input,
Body lore -> Body lore, Body lore -> Body lore)
fuseInputs unfus_nms lam1 inp1 out1 lam2 inp2 =
(lam2redparams, unfus_vars, outbnds, inputmap, makeCopies, makeCopiesInner)
where (lam2redparams, lam2arrparams) =
splitAt (length lam2params - length inp2) lam2params
lam1params = map paramIdent $ lambdaParams lam1
lam2params = map paramIdent $ lambdaParams lam2
lam1inputmap = HM.fromList $ zip lam1params inp1
lam2inputmap = HM.fromList $ zip lam2arrparams inp2
(lam2inputmap', makeCopiesInner) = removeDuplicateInputs lam2inputmap
originputmap = lam1inputmap `HM.union` lam2inputmap'
outins = uncurry (outParams $ map fst out1) $
unzip $ HM.toList lam2inputmap'
outbnds= filterOutParams out1 outins
(inputmap, makeCopies) =
removeDuplicateInputs $ originputmap `HM.difference` outins
-- Cosmin: @unfus_vars@ is supposed to be the lam2 vars corresponding to unfus_nms (?)
getVarParPair x = case SOAC.isVarInput (snd x) of
Just nm -> Just (nm, fst x)
Nothing -> Nothing --should not be reached!
outinsrev = HM.fromList $ mapMaybe getVarParPair $ HM.toList outins
unfusible outname
| outname `HS.member` unfus_nms =
outname `HM.lookup` HM.union outinsrev (HM.fromList out1)
unfusible _ = Nothing
unfus_vars= mapMaybe (unfusible . fst) out1
outParams :: [VName] -> [Ident] -> [SOAC.Input]
-> HM.HashMap Ident SOAC.Input
outParams out1 lam2arrparams inp2 =
HM.fromList $ mapMaybe isOutParam $ zip lam2arrparams inp2
where isOutParam (p, inp)
| Just a <- SOAC.isVarInput inp,
a `elem` out1 = Just (p, inp)
isOutParam _ = Nothing
filterOutParams :: [(VName,Ident)]
-> HM.HashMap Ident SOAC.Input
-> [Ident]
filterOutParams out1 outins =
snd $ mapAccumL checkUsed outUsage out1
where outUsage = HM.foldlWithKey' add M.empty outins
where add m p inp =
case SOAC.isVarInput inp of
Just v -> M.insertWith (++) v [p] m
Nothing -> m
checkUsed m (a,ra) =
case M.lookup a m of
Just (p:ps) -> (M.insert a ps m, p)
_ -> (m, ra)
removeDuplicateInputs :: Bindable lore =>
HM.HashMap Ident SOAC.Input
-> (HM.HashMap Ident SOAC.Input, Body lore -> Body lore)
removeDuplicateInputs = fst . HM.foldlWithKey' comb ((HM.empty, id), M.empty)
where comb ((parmap, inner), arrmap) par arr =
case M.lookup arr arrmap of
Nothing -> ((HM.insert par arr parmap, inner),
M.insert arr (identName par) arrmap)
Just par' -> ((parmap, inner . forward par par'),
arrmap)
forward to from b =
mkLet' [] [to] (PrimOp $ SubExp $ Var from)
`insertBinding` b
fuseRedomap :: Bindable lore =>
Names -> [VName]
-> [SubExp] -> Lambda lore -> [SOAC.Input] -> [(VName,Ident)]
-> Lambda lore -> [SOAC.Input]
-> (Lambda lore, [SOAC.Input])
fuseRedomap unfus_nms outVars p_nes p_lam p_inparr outPairs c_lam c_inparr =
-- We hack the implementation of map o redomap to handle this case:
-- (i) we remove the accumulator formal paramter and corresponding
-- (body) result from from redomap's fold-lambda body
let acc_len = length p_nes
unfus_arrs = filter (`HS.member` unfus_nms) outVars
lam1_body = lambdaBody p_lam
lam1_accres = take acc_len $ bodyResult lam1_body
lam1_arrres = drop acc_len $ bodyResult lam1_body
lam1_hacked = p_lam { lambdaParams = drop acc_len $ lambdaParams p_lam
, lambdaBody = lam1_body { bodyResult = lam1_arrres }
, lambdaReturnType = drop acc_len $ lambdaReturnType p_lam }
-- (ii) we remove the accumulator's (global) output result from
-- @outPairs@, then ``map o redomap'' fuse the two lambdas
-- (in the usual way), and construct the extra return types
-- for the arrays that fall through.
(res_lam, new_inp) = fuseMaps (HS.fromList unfus_arrs) lam1_hacked p_inparr
(drop acc_len outPairs) c_lam c_inparr
(_,extra_rtps) = unzip $ filter (\(nm,_)->elem nm unfus_arrs) $
zip (drop acc_len outVars) $ drop acc_len $
lambdaReturnType p_lam
-- (iii) Finally, we put back the accumulator's formal parameter and
-- (body) result in the first position of the obtained lambda.
(accrtps, accpars) = ( take acc_len $ lambdaReturnType p_lam
, take acc_len $ lambdaParams p_lam )
res_body = lambdaBody res_lam
res_rses = bodyResult res_body
res_body'= res_body { bodyResult = lam1_accres ++ res_rses }
res_lam' = res_lam { lambdaParams = accpars ++ lambdaParams res_lam
, lambdaBody = res_body'
, lambdaReturnType = accrtps ++ lambdaReturnType res_lam ++ extra_rtps
}
in (res_lam', new_inp)
mergeReduceOps :: Bindable lore => Lambda lore -> Lambda lore -> Lambda lore
mergeReduceOps (Lambda par1 bdy1 rtp1) (Lambda par2 bdy2 rtp2) =
let body' = Body (bodyLore bdy1)
(bodyBindings bdy1 ++ bodyBindings bdy2)
(bodyResult bdy1 ++ bodyResult bdy2)
(len1, len2) = (length rtp1, length rtp2)
par' = take len1 par1 ++ take len2 par2 ++ drop len1 par1 ++ drop len2 par2
in Lambda par' body' (rtp1++rtp2)
| mrakgr/futhark | src/Futhark/Optimise/Fusion/Composing.hs | bsd-3-clause | 9,930 | 0 | 16 | 2,998 | 2,180 | 1,171 | 1,009 | 139 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE UnicodeSyntax #-}
import Shake
import Foreign.Storable (sizeOf)
import System.Console.GetOpt
import System.IO
import Control.Applicative
import Control.Concurrent
import Control.Eternal
import Control.Exception
import Control.Monad
main ∷ IO ()
main = do
shakeArgs ← getArgs
current ← getCurrentDirectory
let (actions, _, _) = getOpt RequireOrder shakeOptions shakeArgs
Options { optPlatform = platform
, optForce = force
, optPretend = test
} ← foldl (>>=) (return defaultOptions) actions
shakeIt shakeArgs current force test platform
data Options = Options
{ optPlatform ∷ String
, optForce ∷ Bool
, optPretend ∷ Bool
}
defaultOptions ∷ Options
defaultOptions = Options {
optPlatform = if | os ∈ ["win32", "mingw32", "cygwin32"] →
if sizeOf (undefined :: Int) == 8 then "Win_x64"
else "Win"
| os ∈ ["darwin"] → "Mac"
| otherwise → "Linux"
, optForce = False
, optPretend = False
}
shakeOptions ∷ [OptDescr (Options → IO Options)]
shakeOptions = [
Option "v" ["version"] (NoArg showV) "Display Version",
Option "h" ["help"] (NoArg displayHelp) "Display Help",
Option "p" ["platform"] (ReqArg getp "STRING") "operating system platform",
Option "f" ["force"] (NoArg forceRebuild) "force script rebuild",
Option "P" ["pretend"] (NoArg pretend) "pretend building (testing shake script)"
]
getp ∷ ∀ (m :: * → *). Monad m ⇒ String → Options → m Options
forceRebuild ∷ ∀ (m ∷ * → *). Monad m ⇒ Options → m Options
pretend ∷ ∀ (m ∷ * → *). Monad m ⇒ Options → m Options
-- note ο is not o but greek ο instead ^__^
getp arg ο = return ο { optPlatform = arg }
forceRebuild ο = return ο { optForce = True }
pretend ο = return ο { optPretend = True }
displayHelp ο = do
prg ← getProgName
hPutStrLn stderr (usageInfo prg shakeOptions)
return ο { optForce = True }
| Heather/Shake.it.off | src/Main.hs | bsd-3-clause | 2,343 | 0 | 12 | 678 | 637 | 344 | 293 | 55 | 4 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE DataKinds #-}
module Control.Eff.Internal.Eff (Eff(..),run,runM,runTCQ,send) where
import Control.Eff.Internal.Union
import Control.Eff.Internal.TCQ
data Eff r a = Pure a | forall x. Eff (Union r x) (TCQ (Eff r) x a)
instance Functor (Eff r) where
{-# INLINE fmap #-}
fmap f (Pure a) = Pure (f a)
fmap f (Eff u q) = Eff u (Then q (Singleton (Pure . f)))
instance Applicative (Eff r) where
{-# INLINE pure #-}
pure = Pure
{-# INLINE (<*>) #-}
Pure f <*> Pure x = Pure $ f x
Pure f <*> Eff u q = Eff u (Then q (Singleton (Pure . f)))
Eff u q <*> Pure x = Eff u (Then q (Singleton (Pure . ($x))))
Eff u q <*> ex = Eff u (Then q (Singleton (<$> ex)))
instance Monad (Eff r) where
{-# INLINE return #-}
return = Pure
{-# INLINE (>>=) #-}
Pure x >>= f = f x
Eff u q >>= f = Eff u (Then q (Singleton f))
{-# INLINE runTCQ #-}
runTCQ :: TCQ (Eff r) a b -> a -> Eff r b
runTCQ tcq x = case viewl tcq of
FirstL k -> k x
ConsL k t -> case k x of
Pure n -> runTCQ t n
Eff u q -> Eff u (Then q t)
run :: Eff '[] a -> a
run (Pure x) = x
run (Eff _ _) = error "User is a magician"
runM :: Monad m => Eff '[m] a -> m a
runM (Pure x) = return x
runM (Eff u q) = extract u >>= runM . runTCQ q
{-# INLINE send #-}
send :: Member q r => q a -> Eff r a
send qa = Eff (inject qa) (Singleton Pure)
| Lazersmoke/reee-monads | src/Control/Eff/Internal/Eff.hs | bsd-3-clause | 1,522 | 0 | 14 | 413 | 726 | 363 | 363 | 43 | 3 |
{-# LANGUAGE PackageImports #-}
import "hitweb" Application (getApplicationDev)
import Network.Wai.Handler.Warp
(runSettings, defaultSettings, settingsPort)
import Control.Concurrent (forkIO)
import System.Directory (doesFileExist, removeFile)
import System.Exit (exitSuccess)
import Control.Concurrent (threadDelay)
main :: IO ()
main = do
putStrLn "Starting devel application"
(port, app) <- getApplicationDev
forkIO $ runSettings defaultSettings
{ settingsPort = port
} app
loop
loop :: IO ()
loop = do
threadDelay 100000
e <- doesFileExist "yesod-devel/devel-terminate"
if e then terminateDevel else loop
terminateDevel :: IO ()
terminateDevel = exitSuccess
| NicolasDP/hitweb | devel.hs | bsd-3-clause | 707 | 0 | 10 | 123 | 186 | 101 | 85 | 23 | 2 |
{-# language CPP #-}
{-# language QuasiQuotes #-}
{-# language TemplateHaskell #-}
#ifndef ENABLE_INTERNAL_DOCUMENTATION
{-# OPTIONS_HADDOCK hide #-}
#endif
module OpenCV.Internal.Core.Types.Point.TH
( mkPointType
) where
import "base" Data.List ( intercalate )
import "base" Data.Monoid ( (<>) )
import "base" Foreign.Marshal.Alloc ( alloca )
import "base" Foreign.Storable ( peek )
import "base" System.IO.Unsafe ( unsafePerformIO )
import qualified "inline-c" Language.C.Inline.Unsafe as CU
import "linear" Linear ( V2(..), V3(..) )
import "template-haskell" Language.Haskell.TH
import "template-haskell" Language.Haskell.TH.Quote ( quoteExp )
import "this" OpenCV.Internal.C.PlacementNew.TH ( mkPlacementNewInstance )
import "this" OpenCV.Internal.C.Types
import "this" OpenCV.Internal.Core.Types.Point
import "this" OpenCV.Internal
mkPointType
:: String -- ^ Point type name, for both Haskell and C
-> Integer -- ^ Point dimension
-> String -- ^ Point template name in C
-> Name -- ^ Depth type name in Haskell
-> String -- ^ Depth type name in C
-> Q [Dec]
mkPointType pTypeNameStr dim cTemplateStr depthTypeName cDepthTypeStr
| dim < 2 || dim > 3 = fail $ "mkPointType: Unsupported dimension: " <> show dim
| otherwise =
fmap concat . sequence $
[ pure <$> pointTySynD
, fromPtrDs
, isPointOpenCVInstanceDs
, isPointHaskellInstanceDs
, mkPlacementNewInstance pTypeName
]
where
pTypeName :: Name
pTypeName = mkName pTypeNameStr
cPointTypeStr :: String
cPointTypeStr = pTypeNameStr
pTypeQ :: Q Type
pTypeQ = conT pTypeName
depthTypeQ :: Q Type
depthTypeQ = conT depthTypeName
dimTypeQ :: Q Type
dimTypeQ = litT (numTyLit dim)
pointTySynD :: Q Dec
pointTySynD =
tySynD pTypeName
[]
([t|Point|] `appT` dimTypeQ `appT` depthTypeQ)
fromPtrDs :: Q [Dec]
fromPtrDs =
[d|
instance FromPtr $(pTypeQ) where
fromPtr = objFromPtr Point $ $(finalizerExpQ)
|]
where
finalizerExpQ :: Q Exp
finalizerExpQ = do
ptr <- newName "ptr"
lamE [varP ptr] $
quoteExp CU.exp $
"void { delete $(" <> cPointTypeStr <> " * " <> nameBase ptr <> ") }"
isPointOpenCVInstanceDs :: Q [Dec]
isPointOpenCVInstanceDs =
[d|
instance IsPoint (Point $(dimTypeQ)) $(depthTypeQ) where
toPoint = id
toPointIO = pure
fromPoint = id
|]
isPointHaskellInstanceDs :: Q [Dec]
isPointHaskellInstanceDs =
let ix = fromInteger dim - 2
in withLinear (linearTypeQs !! ix)
(linearConNames !! ix)
where
linearTypeQs :: [Q Type]
linearTypeQs = map conT [''V2, ''V3]
linearConNames :: [Name]
linearConNames = ['V2, 'V3]
withLinear :: Q Type -> Name -> Q [Dec]
withLinear lpTypeQ lvConName =
[d|
instance IsPoint $(lpTypeQ) $(depthTypeQ) where
toPoint = unsafePerformIO . toPointIO
toPointIO = $(toPointIOExpQ)
fromPoint = $(fromPointExpQ)
|]
where
toPointIOExpQ :: Q Exp
toPointIOExpQ = do
ns <- mapM newName elemNames
lamE [conP lvConName $ map varP ns]
$ appE [e|fromPtr|]
$ quoteExp CU.exp
$ inlineCStr ns
where
inlineCStr :: [Name] -> String
inlineCStr ns = concat
[ cPointTypeStr
, " * { new cv::" <> cTemplateStr
, "<" <> cDepthTypeStr <> ">"
, "(" <> intercalate ", " (map elemQuote ns) <> ")"
, " }"
]
where
elemQuote :: Name -> String
elemQuote n = "$(" <> cDepthTypeStr <> " " <> nameBase n <> ")"
fromPointExpQ :: Q Exp
fromPointExpQ = do
point <- newName "point"
pointPtr <- newName "pointPtr"
ptrNames <- mapM (newName . (<> "Ptr")) elemNames
withPtrNames point pointPtr ptrNames
where
withPtrNames :: Name -> Name -> [Name] -> Q Exp
withPtrNames point pointPtr ptrNames =
lamE [varP point]
$ appE [e|unsafePerformIO|]
$ withPtrVarsExpQ ptrNames
where
withPtrVarsExpQ :: [Name] -> Q Exp
withPtrVarsExpQ = foldr (\p -> appE [e|alloca|] . lamE [varP p]) withAllocatedVars
withAllocatedVars :: Q Exp
withAllocatedVars =
appE ([e|withPtr|] `appE` varE point)
$ lamE [varP pointPtr]
$ doE
[ noBindS $ quoteExp CU.block inlineCStr
, noBindS extractExpQ
]
inlineCStr :: String
inlineCStr = unlines $
concat
[ "void {"
, "const cv::" <> cTemplateStr
, "<" <> cDepthTypeStr <> ">"
, " & p = *$("
, cPointTypeStr
, " * "
, nameBase pointPtr
, ");"
]
: map ptrLine (zip [0..] ptrNames)
<> ["}"]
where
ptrLine :: (Int, Name) -> String
ptrLine (ix, ptrName) =
"*$(" <> cDepthTypeStr <> " * " <> nameBase ptrName <> ") = p." <> elemNames !! ix <> ";"
-- Applies the constructor to the values that are
-- read from the pointers.
extractExpQ :: Q Exp
extractExpQ = foldl (\acc peekExp -> [e|(<*>)|] `appE` acc `appE` peekExp)
([e|pure|] `appE` conE lvConName)
peekExpQs
where
peekExpQs :: [Q Exp]
peekExpQs = map (\p -> [e|peek|] `appE` varE p) ptrNames
elemNames :: [String]
elemNames = take (fromInteger dim)
["x", "y", "z"]
| lukexi/haskell-opencv | src/OpenCV/Internal/Core/Types/Point/TH.hs | bsd-3-clause | 6,656 | 0 | 23 | 2,797 | 1,392 | 778 | 614 | -1 | -1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
module ZM.Type.Float64(IEEE_754_binary64(..)) where
import Data.Model
import ZM.Type.Bits11
import ZM.Type.Bits52
import ZM.Type.Words
-- |An IEEE-754 Big Endian 64 bits Float
data IEEE_754_binary64 =
IEEE_754_binary64
{ sign :: Sign
, exponent :: MostSignificantFirst Bits11
, fraction :: MostSignificantFirst Bits52
}
deriving (Eq, Ord, Show, Generic, Model)
| tittoassini/typed | src/ZM/Type/Float64.hs | bsd-3-clause | 513 | 0 | 9 | 141 | 98 | 60 | 38 | 13 | 0 |
{-# LANGUAGE OverloadedStrings #-}
import qualified Graphics.UI.Threepenny as UI
import Graphics.UI.Threepenny.Core
import Foundation.Common
import Examples.Blog
import Control.Applicative
import Control.Monad
import Data.List (intersperse)
main :: IO ()
main = do
startGUI Config
{ tpPort = 10000
, tpCustomHTML = Nothing
, tpStatic = "static/"
} setup
setup :: Window -> IO ()
setup w = void $ do
UI.addStyleSheet w "foundation.css"
UI.addStyleSheet w "normalize.css"
getBody w #+ mainPage
mainPage :: [IO Element]
mainPage =
[ navBar
, rowClass #+
[ articles
, blogSideBar
]
, blogFooter
]
articles :: IO Element
articles = UI.div # set UI.class_ "large-9 columns" # set role "content" #+
intersperse UI.hr
[ baconArticle
, baconArticle
, baconArticle
, baconArticle
, baconArticle
]
blogSideBar :: IO Element
blogSideBar = sideBar $ unwords
[ "Pork drumstick turkey fugiat."
, "Tri-tip elit turducken pork chop in."
, "Swine short ribs meatball irure bacon nulla pork belly cupidatat meatloaf cow."
]
baconArticle :: IO Element
baconArticle = articleEntry "Article Test" "Kyle Carter" "Aug 12, 2003"
[ unwords
[ "Bacon ipsum dolor sit amet nulla ham qui sint exercitation eiusmod commodo, chuck duis velit."
, "Aute in reprehenderit, dolore aliqua non est magna in labore pig pork biltong."
, "Eiusmod swine spare ribs reprehenderit culpa."
]
, unwords
[ "Boudin aliqua adipisicing rump corned beef."
, "Nulla corned beef sunt ball tip, qui bresaola enim jowl."
, "Capicola short ribs minim salami nulla nostrud pastrami."
]
]
[ unwords
[ "Pork drumstick turkey fugiat."
, "Tri-tip elit turducken pork chop in."
, "Swine short ribs meatball irure bacon nulla pork belly cupidatat meatloaf cow."
, "Nulla corned beef sunt ball tip, qui bresaola enim jowl."
, "Capicola short ribs minim salami nulla nostrud pastrami."
, "Nulla corned beef sunt ball tip, qui bresaola enim jowl."
, "Capicola short ribs minim salami nulla nostrud pastrami."
]
, unwords
[ "Pork drumstick turkey fugiat."
, "Tri-tip elit turducken pork chop in."
, "Swine short ribs meatball irure bacon nulla pork belly cupidatat meatloaf cow."
, "Nulla corned beef sunt ball tip, qui bresaola enim jowl."
, "Capicola short ribs minim salami nulla nostrud pastrami."
, "Nulla corned beef sunt ball tip, qui bresaola enim jowl."
, "Capicola short ribs minim salami nulla nostrud pastrami."
]
]
| kylcarte/threepenny-extras | src/Examples/BlogTest.hs | bsd-3-clause | 2,566 | 0 | 9 | 578 | 380 | 213 | 167 | 66 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternGuards #-}
-----------------------------------------------------------------------------
-- |
-- Module : Text.CSL.Eval.Date
-- Copyright : (c) Andrea Rossato
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Andrea Rossato <andrea.rossato@unitn.it>
-- Stability : unstable
-- Portability : unportable
--
-- The CSL implementation
--
-----------------------------------------------------------------------------
module Text.CSL.Eval.Date where
import Prelude
import qualified Control.Exception as E
import Control.Monad.State
import Data.List.Split
import Data.Maybe (fromMaybe, isNothing)
import Data.Text (Text)
import qualified Data.Text as T
import Text.CSL.Exception
import Text.CSL.Eval.Common
import Text.CSL.Eval.Output
import Text.CSL.Style
import Text.CSL.Reference
import Text.CSL.Util ( toRead, last' )
import Text.Pandoc.Definition ( Inline (Str) )
import Text.Printf (printf)
evalDate :: Element -> State EvalState [Output]
evalDate (Date s f fm dl dp dp') = do
tm <- gets $ terms . env
k <- getStringVar "ref-id"
em <- gets mode
let updateFM (Formatting aa ab ac ad ae af ag ah ai aj ak al am an ahl)
(Formatting _ _ bc bd be bf bg bh _ bj bk _ _ _ _) =
Formatting aa ab (updateS ac bc)
(updateS ad bd)
(updateS ae be)
(updateS af bf)
(updateS ag bg)
(updateS ah bh)
ai
(updateS aj bj)
(if bk /= ak then bk else ak)
al am an ahl
updateS a b = if b /= a && b /= "" then b else a
case f of
NoFormDate -> outputList fm dl .
concatMap (formatDate em k tm dp) <$> mapM getDateVar s
_ -> do res <- getDate f
case res of
Date _ _ lfm ldl ldp _ -> do
let go dps = return . outputList (updateFM fm lfm) (if ldl /= "" then ldl else dl) .
concatMap (formatDate em k tm dps)
update l x@(DatePart a b c d) =
case filter ((==) a . dpName) l of
(DatePart _ b' c' d':_) -> DatePart a (updateS b b')
(updateS c c')
(updateFM d d')
_ -> x
updateDP = map (update dp) ldp
date = mapM getDateVar s
case dp' of
"year-month" -> go (filter ((/=) "day" . dpName) updateDP) =<< date
"year" -> go (filter ((==) "year" . dpName) updateDP) =<< date
_ -> go updateDP =<< date
_ -> return []
evalDate _ = return []
getDate :: DateForm -> State EvalState Element
getDate f = do
x <- filter (\(Date _ df _ _ _ _) -> df == f) <$> gets (dates . env)
case x of
[x'] -> return x'
_ -> return $ Date [] NoFormDate emptyFormatting "" [] ""
formatDate :: EvalMode -> Text -> [CslTerm] -> [DatePart] -> [RefDate] -> [Output]
formatDate em k tm dp date
| [d] <- date = concatMap (formatDatePart d) dp
| (a:b:_) <- date = addODate . concat $ doRange a b
| otherwise = []
where
addODate [] = []
addODate xs = [ODate xs]
splitDate a b = case split (onSublist $ diff a b dp) dp of
[x,y,z] -> (x,y,z)
_ -> E.throw ErrorSplittingDate
doRange a b = let (x,y,z) = splitDate a b in
map (formatDatePart a) x ++
withDelim y
(map (formatDatePart a) (rmSuffix y))
(map (formatDatePart b) (rmPrefix y))
++
map (formatDatePart b) z
-- the point of rmPrefix is to remove the blank space that otherwise
-- gets added after the delimiter in a range: 24- 26.
rmPrefix (dp':rest) = dp'{ dpFormatting =
(dpFormatting dp') { prefix = "" } } : rest
rmPrefix [] = []
rmSuffix (dp':rest)
| null rest = [dp'{ dpFormatting =
(dpFormatting dp') { suffix = "" } }]
| otherwise = dp':rmSuffix rest
rmSuffix [] = []
diff (RefDate ya ma sa da _ _)
(RefDate yb mb sb db _ _)
= filter (\x -> dpName x `elem` ns)
where ns =
case () of
_ | ya /= yb -> ["year","month","day"]
| ma /= mb || sa /= sb ->
if isNothing da && isNothing db
then ["month"]
else ["month","day"]
| da /= db -> ["day"]
| otherwise -> ["year","month","day"]
term f t = let f' = if f `elem` ["verb", "short", "verb-short", "symbol"]
then read . T.unpack $ toRead f
else Long
in maybe "" termPlural $ findTerm t f' tm
formatDatePart (RefDate y m e d o _) (DatePart n f _ fm)
| "year" <- n, Just y' <- y = return $ OYear (formatYear f y') k fm
| "month" <- n, Just m' <- m = output fm (formatMonth f fm m')
| "month" <- n, Just e' <- e =
case e' of
RawSeason s -> [OStr s fm]
_ -> output fm . term f . T.pack $
(printf "season-%02d" $ fromMaybe 0 $ seasonToInt e')
| "day" <- n, Just d' <- d = output fm (formatDay f m d')
| "year" <- n, o /= mempty = output fm (unLiteral o)
| otherwise = []
withDelim xs o1 o2
| null (concat o1 ++ concat o2) = []
| otherwise = o1 ++ (case dpRangeDelim <$> last' xs of
["-"] -> [[OPan [Str "\x2013"]]]
[s] -> [[OPan [Str s]]]
_ -> []) ++ o2
formatYear f y
| "short" <- f = T.pack $ printf "%02d" y
| isSorting em
, y < 0 = T.pack $ printf "-%04d" (abs y)
| isSorting em = T.pack $ printf "%04d" y
| y < 0 = (T.pack $ printf "%d" (abs y)) <> term "" "bc"
| y < 1000
, y > 0 = (T.pack $ printf "%d" y) <> term "" "ad"
| y == 0 = ""
| otherwise = T.pack $ printf "%d" y
formatMonth f fm m
| "short" <- f = getMonth $ period . termPlural
| "long" <- f = getMonth termPlural
| "numeric" <- f = T.pack $ printf "%d" m
| otherwise = T.pack $ printf "%02d" m
where
period = if stripPeriods fm then T.filter (/= '.') else id
getMonth g = case findTerm ("month-" <> T.pack (printf "%02d" m))
(read . T.unpack $ toRead f) tm of
Nothing -> T.pack (show m)
Just x -> g x
formatDay f m d
| "numeric-leading-zeros" <- f = T.pack $ printf "%02d" d
| "ordinal" <- f = ordinal tm ("month-" <> maybe "0" (T.pack . printf "%02d") m) d
| otherwise = T.pack $ printf "%d" d
ordinal :: [CslTerm] -> Text -> Int -> Text
ordinal ts v s
| s < 10 = let a = termPlural (getWith1 (show s)) in
if T.null a
then setOrd (term "")
else T.pack (show s) <> a
| s < 100 = let a = termPlural (getWith2 (show s))
b = getWith1 [last (show s)] in
if not (T.null a)
then T.pack (show s) <> a
else if T.null (termPlural b) ||
(not (T.null (termMatch b)) &&
termMatch b /= "last-digit")
then setOrd (term "")
else setOrd b
| otherwise = let a = getWith2 last2
b = getWith1 [last (show s)] in
if not (T.null (termPlural a)) &&
termMatch a /= "whole-number"
then setOrd a
else if T.null (termPlural b) ||
(not (T.null (termMatch b)) &&
termMatch b /= "last-digit")
then setOrd (term "")
else setOrd b
where
setOrd = T.append (T.pack $ show s) . termPlural
getWith1 = term . T.append "-0" . T.pack
getWith2 = term . T.append "-" . T.pack
last2 = reverse . take 2 . reverse $ show s
term t = getOrdinal v ("ordinal" <> t) ts
longOrdinal :: [CslTerm] -> Text -> Int -> Text
longOrdinal ts v s
| s > 10 ||
s == 0 = ordinal ts v s
| otherwise = case s `mod` 10 of
1 -> term "01"
2 -> term "02"
3 -> term "03"
4 -> term "04"
5 -> term "05"
6 -> term "06"
7 -> term "07"
8 -> term "08"
9 -> term "09"
_ -> term "10"
where
term t = termPlural $ getOrdinal v ("long-ordinal-" <> t) ts
getOrdinal :: Text -> Text -> [CslTerm] -> CslTerm
getOrdinal v s ts
= fromMaybe newTerm $ findTerm' s Long gender ts `mplus`
findTerm' s Long Neuter ts
where
gender = if v `elem` numericVars || "month" `T.isPrefixOf` v
then maybe Neuter termGender $ findTerm v Long ts
else Neuter
| jgm/pandoc-citeproc | src/Text/CSL/Eval/Date.hs | bsd-3-clause | 10,495 | 0 | 26 | 4,918 | 3,431 | 1,714 | 1,717 | 200 | 12 |
{-| The API part of @feed-gipeda@. The console client is just a thin wrapper
around this.
-}
module FeedGipeda
( Endpoint (..)
, feedGipeda
, module FeedGipeda.Types
) where
import Control.Arrow (second)
import Control.Concurrent (forkIO)
import Control.Concurrent.Chan (Chan, newChan, readChan,
writeChan)
import qualified Control.Distributed.Backend.P2P as P2P
import Control.Distributed.Process (Process, RemoteTable,
getSelfNode, liftIO, say,
spawnLocal)
import Control.Distributed.Process.Node (initRemoteTable, runProcess)
import Control.Logging as Logging
import Control.Monad (forever, void, when)
import Data.List (elemIndex)
import Data.Maybe (fromMaybe, isJust)
import Data.Set (Set)
import Data.Time (NominalDiffTime)
import qualified FeedGipeda.Config as Config
import qualified FeedGipeda.Gipeda as Gipeda
import FeedGipeda.GitShell (SHA)
import qualified FeedGipeda.Master as Master
import qualified FeedGipeda.Master.CommitQueue as CommitQueue
import qualified FeedGipeda.Master.File as Master.File
import FeedGipeda.Prelude
import FeedGipeda.Repo (Repo)
import qualified FeedGipeda.TaskScheduler as TaskScheduler
import qualified FeedGipeda.THGenerated as THGenerated
import FeedGipeda.Types
import Network.URI (parseURI)
import System.Directory (getAppUserDataDirectory)
import System.Exit (exitSuccess)
import System.FilePath ((</>))
remoteTable :: RemoteTable
remoteTable =
THGenerated.__remoteTable initRemoteTable
{-| The parameters correspond exactly to the command line parameters, to
you should read the @--help@ message for more thorough documentation.
@feedGipeda@ determines the appropriate mode of operation (e.g. watching or one-shot).
It also works as master or slave node, depending on which endpoints are given.
Lastly, @verbose@ will lead to more debug output.
-}
feedGipeda
:: Paths
-> Command
-> Deployment
-> ProcessRole
-> Verbosity
-> IO ()
feedGipeda paths cmd deployment role_ verbosity = do
case verbosity of
Verbose -> Logging.setLogLevel Logging.LevelDebug
NotVerbose -> Logging.setLogLevel Logging.LevelWarn
case cmd of
Check ->
-- Just perform a syntax check on the given configFile
Config.checkFile (configFile paths) >>= maybe exitSuccess error
Build mode timeout -> do
case slaveEndpoint role_ of
Just (Endpoint shost sport) -> do
let
run = if isBoth role_ then void . forkIO else id
Endpoint mhost mport = masterEndpoint role_
master = P2P.makeNodeId (mhost ++ ":" ++ show mport)
run (TaskScheduler.work shost (show sport) master remoteTable)
_ -> return ()
case (role_, masterEndpoint role_) of
(Slave _ _, _) -> return ()
(_, Endpoint host port) -> do
queue <- CommitQueue.new
P2P.bootstrap host (show port) [] remoteTable $ do
-- We supply no seeds, so the node won't have been created yet.
-- I think this is a bug.
_ <- getSelfNode
let
toTask :: (Repo, SHA) -> IO (TaskScheduler.Task String)
toTask (repo, commit) = do
script <- Gipeda.determineBenchmarkScript repo
let closure = THGenerated.benchmarkClosure script repo commit timeout
let finalize = Master.File.writeBenchmarkCSV repo commit . fromMaybe ""
return (THGenerated.stringDict, closure, finalize)
TaskScheduler.start (CommitQueue.dequeue queue >>= toTask)
liftIO (Master.checkForNewCommits paths deployment mode queue)
| sgraf812/feed-gipeda | src/FeedGipeda.hs | bsd-3-clause | 4,308 | 0 | 30 | 1,481 | 834 | 457 | 377 | 75 | 6 |
module Main where
import System.Environment
import Language.Sheo.Parser
import Language.Sheo.Printer
compile :: String -> IO ()
compile fileName = do prgm <- parse fileName
case prgm of
Just p' -> print $ prettyPrint p'
Nothing -> return ()
usage :: IO ()
usage = print "pass a filename ya dingus"
main :: IO ()
main = do args <- getArgs
case args of
[fileName] -> compile fileName;
_ -> usage | forestbelton/sheo | app/Main.hs | bsd-3-clause | 519 | 0 | 11 | 194 | 153 | 77 | 76 | 16 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.