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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
-----------------------------------------------------------------------------
-- |
-- Module : Writer.Formats.SlugsIn
-- License : MIT (see the LICENSE file)
-- Maintainer : Ioannis Filippidis (jfilippidis@gmail.com)
-- Felix Klein (klein@react.uni-saarland.de)
--
-- Translates GR(1) specification to SlugsIn syntax.
--
-----------------------------------------------------------------------------
module Writer.Formats.SlugsIn where
-----------------------------------------------------------------------------
import Config
import Data.LTL
import Writer.Eval
import Writer.Error
import Data.Specification
import Detection
import Control.Exception
-----------------------------------------------------------------------------
-- | SlugsIn format writer.
writeFormat
:: Configuration -> Specification -> Either Error String
writeFormat c s =
case detectGR c s of
Left v -> case v of
Left err -> Left err
Right _ -> errNoGR1 "not in GR(1)" "slugsin"
Right gr
| level gr > 1 -> errNoGR1 ("in GR(" ++ show (level gr) ++ ")") "slugsin"
| otherwise -> printSlugs gr
where
printSlugs gr = do
let
es = initEnv gr
ss = initSys gr
rs = assertEnv gr
is = assertSys gr
(le,ls) = case liveness gr of
[] -> ([],[])
x:_ -> x
(iv,ov) <- signals c s
return $ "[INPUT]"
++ "\n" ++ unlines iv
++ "\n" ++ "[OUTPUT]"
++ "\n" ++ unlines ov
++ (if null es then "" else
"\n" ++ "[ENV_INIT]" ++
"\n" ++ unlines (map prFormula es))
++ (if null ss then "" else
"\n" ++ "[SYS_INIT]" ++
"\n" ++ unlines (map prFormula ss))
++ (if null rs then "" else
"\n" ++ "[ENV_TRANS]" ++
"\n" ++ unlines (map prFormula rs))
++ (if null is then "" else
"\n" ++ "[SYS_TRANS]" ++
"\n" ++ unlines (map prFormula is))
++ (if null le then "" else
"\n" ++ "[ENV_LIVENESS]" ++
"\n" ++ unlines (map prFormula le))
++ (if null ls then "" else
"\n" ++ "[SYS_LIVENESS]" ++
"\n" ++ unlines (map prFormula ls))
prFormula fml = case fml of
TTrue -> " 1 "
FFalse -> " 0 "
Atomic x -> " " ++ show x ++ " "
Not x -> "! " ++ prFormula x
Next x -> prFormula' x
And [] -> prFormula TTrue
And [x] -> prFormula x
And (x:xr) -> concatMap (\_ -> " & ") xr ++
prFormula x ++
concatMap (\y -> prFormula y) xr
Or [] -> prFormula FFalse
Or [x] -> prFormula x
Or (x:xr) -> concatMap (\_ -> " | ") xr ++
prFormula x ++
concatMap (\y -> prFormula y) xr
Implies x y -> " | ! " ++
prFormula x ++
prFormula y
Equiv x y -> " ! ^ " ++
prFormula x ++
prFormula y
_ -> assert False undefined
where prFormula' f = case f of
TTrue -> " 1 "
FFalse -> " 0 "
Atomic x -> " " ++ show x ++ "' "
Not x -> "! " ++ prFormula' x
Next {} -> assert False undefined
And [] -> prFormula' TTrue
And [x] -> prFormula' x
And (x:xr) -> concatMap (\_ -> " & ") xr ++
prFormula' x ++
concatMap (\y -> prFormula' y) xr
Or [] -> prFormula' FFalse
Or [x] -> prFormula' x
Or (x:xr) -> concatMap (\_ -> " | ") xr ++
prFormula' x ++
concatMap (\y -> prFormula' y) xr
Implies x y -> " | ! " ++
prFormula' x ++
prFormula' y
Equiv x y -> " ! ^ " ++
prFormula' x ++
prFormula' y
_ -> assert False undefined
-----------------------------------------------------------------------------
| reactive-systems/syfco | src/lib/Writer/Formats/SlugsIn.hs | mit | 4,729 | 0 | 21 | 2,199 | 1,192 | 585 | 607 | 96 | 36 |
module Calendar
( calendarWidget
)
where
import Import hiding (for)
import Data.Time.Calendar
import Data.Time.Calendar.WeekDate
import Data.Time.Calendar.MonthDay
import Helpers
import Model.Event
data Calendar = Calendar
{ months :: [Month]
}
deriving (Show)
data Month = Month
{ month :: Int
, year :: Integer
, weeks :: [[Day]]
}
deriving (Show)
calendarWidget :: Handler Widget
calendarWidget = do
day <- liftIO today
-- TODO: calculate exact range
-- actually it would be better if the range was given as param
-- to calendar function but for now range of two years will have all the events
-- we might need
let start = addDays (-365) day
end = addDays 365 day
events <- runDB $ getEvents start end
return $ calendarWidget' day events
calendarWidget' :: Day -> [Entity Event] -> Widget
calendarWidget' currentDay events = [whamlet|
<div #calendar-container>
$forall m <- months $ calendar currentDay
<table #calendar :(not $ sameMonth (month m) currentDay):style="display: none;">
<thead>
<tr>
<th #prev .arrow><
<th colspan=5>_{monthMsg $ month m} - #{show $ year m}
<th #next .arrow>>
<tr>
<th>_{MsgMondayShort}
<th>_{MsgTuesdayShort}
<th>_{MsgWednesdayShort}
<th>_{MsgThursdayShort}
<th>_{MsgFridayShort}
<th>_{MsgSaturdayShort}
<th>_{MsgSundayShort}
<tbody>
$forall week <- weeks m
<tr>
$forall day <- week
<td title=#{eventTitles events day} :(not $ sameMonth (month m) day):.text-muted :(not $ null $ eventTitles events day):.event :(currentDay == day):.current-day>
$if not $ null $ eventTitles events day
<a href=@{DayR day}>
#{show $ thd $ toGregorian day}
$else
#{show $ thd $ toGregorian day}
|]
eventTitles :: [Entity Event] -> Day -> Text
eventTitles allEvents day = intercalate ", " $ map eventTitle events
where
events = filter (\e -> day `elem` eventDays e) $ map entityVal allEvents
eventDays :: Event -> [Day]
eventDays event =
case eventEndDate event of
Just end -> [addDays i start | i <- [0..diffDays end start]]
Nothing -> [start]
where
start = eventStartDate event
sameMonth :: Int -> Day -> Bool
sameMonth month day = month == (snd3 $ toGregorian day)
monthMsg :: Int -> AppMessage
monthMsg 1 = MsgJanuary
monthMsg 2 = MsgFebruary
monthMsg 3 = MsgMarch
monthMsg 4 = MsgApril
monthMsg 5 = MsgMay
monthMsg 6 = MsgJune
monthMsg 7 = MsgJuly
monthMsg 8 = MsgAugust
monthMsg 9 = MsgSeptember
monthMsg 10 = MsgOctober
monthMsg 11 = MsgNovember
monthMsg 12 = MsgDevember
monthMsg _ = MsgUnknownMonth
-- 12 months: current month, 5 months in the past and 6 months to the future
calendar :: Day -> Calendar
calendar day =
let
(year, month, _) = toGregorian day
in
Calendar $ for (months year month) $ \(y, m) -> Month m y $ oneMonth y m
where
months :: Integer -> Int -> [(Integer, Int)]
months year month = for [0..11] $ \i -> validYearAndMonth year (month - 5 + i)
-- this only works for a range of one year
validYearAndMonth :: Integer -> Int -> (Integer, Int)
validYearAndMonth y m =
if m < 1
then (y - 1, 12 + m) -- previous year
else if m > 12
then (y + 1, m - 12) -- next year
else (y, m) -- all is good
oneMonth :: Integer -> Int -> [[Day]]
oneMonth year month = toWeeks $ allDaysInMonth year month
-- break 42 days in to 6 weeks
toWeeks :: [Day] -> [[Day]]
toWeeks (d1:d2:d3:d4:d5:d6:d7:days) = [d1,d2,d3,d4,d5,d6,d7]:toWeeks days
toWeeks _ = []
-- return a list of 42 days that has all the days in given month
-- and some additional days from previous and next month
allDaysInMonth :: Integer -> Int -> [Day]
allDaysInMonth year month =
let
-- first day of this month (week date)
firstDay = dayOfWeek $ fromGregorian year month 1
(prevYear, prevMonth) = prevMonthAndYear year month
(nextYear, nextMonth) = nextMonthAndYear year month
-- days in previous month
daysPrevMonth = daysInMonth prevYear prevMonth
-- days in previous month that should be shown with this month
-- meaning days from monday to the day when this months starts
-- if this month starts from monday then this is empty
prevMonthDays = daysFromPreviousMonth prevYear prevMonth daysPrevMonth firstDay
-- days in current month
currentMonth = daysInMonth year month
-- last day of the month (week day)
lastDay = dayOfWeek $ fromGregorian year month currentMonth
-- days in next month that should be shown with this month
-- meaning days to sunday from the day when this month ends
-- if this month ends in sunday then this is empty
nextMonthDays = daysFromNextMonth nextYear nextMonth lastDay
-- list of days in this month
currentMonthDays = for [1..currentMonth] (fromGregorian year month)
-- all the days together
allDays = prevMonthDays ++ currentMonthDays ++ nextMonthDays
-- rare case where in a leap year February starts in monday and
-- all the days fit inside 4 week period so we need to add two additional weeks
-- condition is smaller than 35 because we are aiming for 42 days (6*7) and
-- 35 is 42 - 7 and I am too lazy to check if this is leap year and february
howManyWeeks = if (length allDays < 35) then 2 else 1
additionalWeeks = if (length allDays < 42)
then [(length nextMonthDays)+1..(length nextMonthDays)+(7*howManyWeeks)]
else []
in
allDays ++ (for additionalWeeks (fromGregorian nextYear nextMonth))
-- list of days from previous month depending on what day does
-- the current month start
-- if first day is 0 (Monday) then this will return empty list
-- if first day is 6 (Sunday) then this will return six days
-- numbered according to the previous month e.g. [26, 27, 28, 29, 30, 31]
daysFromPreviousMonth :: Integer -> Int -> Int -> Int -> [Day]
daysFromPreviousMonth year month days firstDay =
reverse [(fromGregorian year month (days - i + 1)) | i <- [1..firstDay]]
-- list of days from next month depending on what day does
-- the current month end
-- if last day is 0 (Monday) then this will return six days [1, 2, 3, 4, 5, 6]
-- if last day is 6 (Sunday) then this will return empty list
daysFromNextMonth :: Integer -> Int -> Int -> [Day]
daysFromNextMonth year month lastDay =
for [1..6-lastDay] (fromGregorian year month)
-- number of days in given month
daysInMonth :: Integer -> Int -> Int
daysInMonth y m = monthLength (isLeapYear y) m
-- 0 = Monday, 6 = Sunday
dayOfWeek :: Day -> Int
dayOfWeek day = (thd $ toWeekDate day) - 1
-- if january go to december and decrease year by one
prevMonthAndYear :: Integer -> Int -> (Integer, Int)
prevMonthAndYear year 1 = (year - 1, 12)
prevMonthAndYear year month = (year, month - 1)
-- if december go to january and increase year by one
nextMonthAndYear :: Integer -> Int -> (Integer, Int)
nextMonthAndYear year 12 = (year + 1, 1)
nextMonthAndYear year month = (year, month + 1) | isankadn/yesod-testweb-full | Calendar.hs | mit | 7,165 | 0 | 13 | 1,729 | 1,540 | 840 | 700 | -1 | -1 |
module Binomial where
binomial :: Int -> Int -> Int
binomial n k
| 0 <= k && k < n = ((binomial (n-1) (k-1)) + (binomial (n-1) k))
| k == 0 || n == k = 1
| otherwise = 0
| chr0n1x/haskell-things | binomial.hs | mit | 185 | 0 | 11 | 58 | 119 | 61 | 58 | 6 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Biri.Backend.Routes
( generate
) where
import Control.Monad (mfilter)
import Data.Char (toLower, toUpper)
import qualified Data.IntMap.Strict as IM
import Data.List (intercalate)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Vector as V
import Biri.Backend.Routes.Automaton
import Biri.Language.AbstractSyntax
generate :: [Resource] -> Text
generate resources = T.unlines
[ "#include <stdio.h>"
, "#include <string.h>"
, ""
, T.concat ["int next_state[", T.pack (show (1 + states automaton)), "][128] = {"]
, T.concat [" ", T.intercalate ",\n " (map genTable $ V.toList (delta automaton))]
, "};"
, ""
, T.intercalate "\n" (map genHandler [Delete .. Put])
, ""
, "const char *match(const char *method, const char *uri) {"
, " int state = 0;"
, " for(int i = 0, length = strlen(uri); i < length; i++) state = next_state[state][uri[i]];"
, T.intercalate "\n" (map genReturn [Delete .. Put])
, " return NULL;"
, "}"
]
where
automaton :: Automaton
automaton = transform resources
genTable :: Map Char [Int] -> Text
genTable = (T.append "{") . (flip T.append "}") . T.intercalate ", " . map (T.pack . show . head)
. flip map (take 128 ['\0'..]) . flip (M.findWithDefault [states automaton])
genHandler :: Method -> Text
genHandler method = T.concat
[ "char *handler_", T.toLower . T.pack $ show method, "[", T.pack $ show (1 + states automaton), "] = { "
, T.intercalate ", " (map mkHandler [0..states automaton])
, "};"
]
where
mkHandler :: Int -> Text
mkHandler = fromMaybe "NULL" . fmap (T.pack . show . show)
. mfilter (not . null) . fmap (filter (\(Handler m _) -> method == m))
. flip IM.lookup (handlers automaton)
genReturn :: Method -> Text
genReturn method = T.concat
[ " if(strcmp(method, \"", T.toUpper . T.pack $ show method, "\") == 0)"
, " return handler_", T.toLower . T.pack $ show method, "[state];"
]
| am-/biri-lang | src/Biri/Backend/Routes.hs | mit | 2,239 | 0 | 17 | 567 | 712 | 391 | 321 | 50 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Test.Smoke.App.Diff.ExternalDiffCommand
( Command,
enabled,
render,
)
where
import Control.Exception (throwIO)
import Data.List.NonEmpty (NonEmpty ((:|)))
import qualified Data.List.NonEmpty as NonEmpty
import Data.Maybe (isJust)
import qualified Data.Text as Text
import qualified Data.Text.IO as Text.IO
import System.Directory (findExecutable)
import System.Exit (ExitCode (..))
import System.IO (hClose)
import System.IO.Temp (withSystemTempFile)
import System.Process.Text (readProcessWithExitCode)
import Test.Smoke.App.Diff.Types
type Command = NonEmpty String
enabled :: String -> IO Bool
enabled executable = isJust <$> findExecutable executable
render :: Command -> RenderDiff
render command@(executable :| args) left right =
withSystemTempFile "smoke-left-" $ \leftFilePath leftFile ->
withSystemTempFile "smoke-right-" $ \rightFilePath rightFile -> do
Text.IO.hPutStr leftFile left
Text.IO.hPutStr rightFile right
hClose leftFile
hClose rightFile
(exitCode, stdout, stderr) <-
readProcessWithExitCode
executable
(args ++ [leftFilePath, rightFilePath])
""
case exitCode of
ExitSuccess -> return stdout
ExitFailure 1 -> return stdout
ExitFailure code ->
throwIO $
userError $
"`"
++ unwords (NonEmpty.toList command)
++ "`"
++ " failed with status "
++ show code
++ "."
++ "\n"
++ Text.unpack stderr
| SamirTalwar/Smoke | src/app/Test/Smoke/App/Diff/ExternalDiffCommand.hs | mit | 1,621 | 0 | 24 | 430 | 408 | 227 | 181 | 47 | 3 |
module GHCJS.DOM.RTCStatsResponse (
) where
| manyoo/ghcjs-dom | ghcjs-dom-webkit/src/GHCJS/DOM/RTCStatsResponse.hs | mit | 46 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
module Main where
import System.Environment
import Language.Camle.Parser
import Language.Camle.AstToIr
import Text.PrettyPrint
main = do
[filename] <- getArgs
ast <- parseWhile filename
case ast of
(Left error) -> print error
(Right program) -> putStr . render . printIr . astToIr $ program
| willprice/camle-compiler | src/IRMain.hs | mit | 359 | 0 | 13 | 109 | 101 | 53 | 48 | 11 | 2 |
{-# LANGUAGE ForeignFunctionInterface #-}
module Geometry.Clipping where
import Geometry.Point
import Geometry.Polygon
import Foreign.Marshal.Array
import Foreign.Ptr
import System.IO.Unsafe
import Foreign.C
import Data.Int
import Data.Coerce
foreign import ccall "wrapper.cpp UnionArea"
unionAreaPtr :: Ptr CLLong -> Ptr CInt -> CInt -> IO CDouble
foreign import ccall "wrapper.cpp PointInPoly"
pointInPolyPtr :: Ptr CLLong -> CInt -> CLLong -> CLLong -> IO CInt
unionAreaRaw :: [[Int64]] -> Double
unionAreaRaw polys = coerce longRes / 2 ** 60
where numPolys = fromIntegral $ length polys
sizes = map ((`div` 2) . fromIntegral . length) polys
buffer = coerce $ concat polys
longRes = unsafePerformIO $
withArray buffer $ \buffPtr ->
withArray sizes $ \sizesPtr ->
unionAreaPtr buffPtr sizesPtr numPolys
pointInPolyRaw :: [Int64] -> Int64 -> Int64 -> Int
pointInPolyRaw poly x y = fromIntegral $ unsafePerformIO $
withArray (coerce poly) $ \buffPtr ->
pointInPolyPtr buffPtr (fromIntegral $ length poly `div` 2) (coerce x) (coerce y)
pointToInts :: Point -> [Int64]
pointToInts (Point x y) = map round [x * 2 ** 30, y * 2 ** 30]
simpleToInts :: SimplePolygon -> [Int64]
simpleToInts (Simple pts) = concatMap pointToInts pts
unionArea :: [SimplePolygon] -> Double
unionArea = unionAreaRaw . map simpleToInts
polygonArea :: Polygon -> Double
polygonArea (Polygon outer holes) = unionArea $ outer : holes
data PointPosition = Outside | Inside | OnBorder deriving (Eq, Ord, Read, Show)
oppositePosition :: PointPosition -> PointPosition
oppositePosition Outside = Inside
oppositePosition Inside = Outside
oppositePosition OnBorder = OnBorder
positionFromInt :: Int -> PointPosition
positionFromInt 0 = Outside
positionFromInt 1 = Inside
positionFromInt (-1) = OnBorder
positionFromInt i = error $ "Integer " ++ show i ++ " not recognized as a valid point position"
isInSimplePoly :: IsHole -> Point -> SimplePolygon -> PointPosition
isInSimplePoly hole pt poly
| hole = oppositePosition posOnPoly
| otherwise = posOnPoly
where [x, y] = pointToInts pt
posOnPoly = positionFromInt $ pointInPolyRaw (simpleToInts poly) x y
isInPoly :: Point -> Polygon -> PointPosition
isInPoly pt (Polygon outer holes)
| Outside `elem` positions = Outside
| OnBorder `elem` positions = OnBorder
| otherwise = Inside
where positions = isInSimplePoly False pt outer : map (isInSimplePoly True pt) holes
| LukaHorvat/ArtGallery | src/Geometry/Clipping.hs | mit | 2,579 | 0 | 11 | 553 | 791 | 412 | 379 | 57 | 1 |
module Exercise where
pascal :: Int -> [[Int]]
pascal n = [(pascal' k) | k <- [0..n]]
pascal' :: Int -> [Int]
pascal' 0 = [1]
pascal' 1 = [1, 1]
pascal' n = [1] ++ pascal'' (pascal' (n-1)) ++ [1]
pascal'' :: [Int] -> [Int]
pascal'' n = zipWith (+) n (tail n)
| tcoenraad/functioneel-programmeren | 2014/opg1c.hs | mit | 263 | 0 | 11 | 58 | 162 | 90 | 72 | 9 | 1 |
module Solidran.Fibd.DetailSpec (spec) where
import Test.Hspec
import Solidran.Fibd.Detail
spec :: Spec
spec = do
describe "Solidran.Fibd.Detail" $ do
describe "countRabbits" $ do
it "after 1 month, the count should be 1" $ do
countRabbits 1 1 `shouldBe` 1
it "should work on every step of the sample sequence" $ do
countRabbits 1 3 `shouldBe` 1
countRabbits 2 3 `shouldBe` 1
countRabbits 3 3 `shouldBe` 2
countRabbits 4 3 `shouldBe` 2
countRabbits 5 3 `shouldBe` 3
countRabbits 6 3 `shouldBe` 4
it "should work after the sample sequence" $ do
countRabbits 7 3 `shouldBe` 5
countRabbits 8 3 `shouldBe` 7
it "should work with a lower m" $ do
countRabbits 1 2 `shouldBe` 1
countRabbits 3 2 `shouldBe` 1
countRabbits 8 2 `shouldBe` 1
countRabbits 9 2 `shouldBe` 1
countRabbits 13 2 `shouldBe` 1
countRabbits 24 2 `shouldBe` 1
it "should work with a degenerative sequence" $ do
countRabbits 1 1 `shouldBe` 1
countRabbits 3 1 `shouldBe` 0
countRabbits 5 1 `shouldBe` 0
it "should work with an higher m" $ do
countRabbits 1 4 `shouldBe` 1
countRabbits 2 4 `shouldBe` 1
countRabbits 3 4 `shouldBe` 2
countRabbits 4 4 `shouldBe` 3
countRabbits 5 4 `shouldBe` 4
countRabbits 6 4 `shouldBe` 6
countRabbits 7 4 `shouldBe` 9
countRabbits 8 4 `shouldBe` 13
| Jefffrey/Solidran | test/Solidran/Fibd/DetailSpec.hs | mit | 1,746 | 0 | 17 | 713 | 477 | 235 | 242 | 39 | 1 |
module Data.Name.Internal.Spec where
import Data.Name.Internal
import Test.Hspec
import Test.Hspec.QuickCheck
spec :: Spec
spec = do
describe "digits" $ do
it "zero is zero in base 10" $
digits 10 0 `shouldBe` [0 :: Integer]
it "10 has two digits in base 10" $
digits 10 10 `shouldBe` [1, 0 :: Integer]
it "1234’s digits are produced in order in base 10" $
digits 10 1234 `shouldBe` [1, 2, 3, 4 :: Integer]
it "produces two digits for 255 in base 16" $
digits 16 255 `shouldBe` [15, 15 :: Integer]
describe "showNumeral" $ do
it "selects single letters in an alphabet" $
showNumeral "a" (0 :: Integer) `shouldBe` "a"
it "handles indices into degenerate 0-length alphabets" $
showNumeral "" (0 :: Integer) `shouldBe` ""
it "handles out-of-bounds indices into degenerate 1-length alphabets" $
showNumeral "a" (1 :: Integer) `shouldBe` "a"
it "handles out-of-bounds indices into reasonable alphabets" $
showNumeral "ab" (2 :: Integer) `shouldBe` "ba"
describe "interleave" $ do
prop "ignores empty lists at left" $
\ a -> "" `interleave` a `shouldBe` a
prop "ignores empty lists at right" $
\ a -> a `interleave` "" `shouldBe` a
prop "is as long as both its arguments combined" $
\ a b -> length (a `interleave` b) `shouldBe` length a + length (b :: String)
prop "is left-biased" $
\ a b -> ('a' : a) `interleave` b `shouldBe` 'a' : (b `interleave` a)
| antitypical/Surface | test/Data/Name/Internal/Spec.hs | mit | 1,490 | 0 | 16 | 373 | 450 | 242 | 208 | 33 | 1 |
{-# htermination (>=) :: Int -> Int -> Bool #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_GTEQ_5.hs | mit | 48 | 0 | 2 | 10 | 3 | 2 | 1 | 1 | 0 |
module Solidran.Math (factorial) where
factorial :: Int -> Integer
factorial n = product [1..toInteger n]
| Jefffrey/Solidran | src/Solidran/Math.hs | mit | 107 | 0 | 7 | 16 | 39 | 21 | 18 | 3 | 1 |
{-# LANGUAGE CPP #-}
{-
Copyright (C) 2008 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
module Main where
import Network.Gitit
import Network.Gitit.Server
import Network.Gitit.Util (readFileUTF8)
import System.Directory
import Data.Maybe (isNothing)
import Control.Monad.Error()
import Control.Monad.Reader
import System.Log.Logger (Priority(..), setLevel, setHandlers,
getLogger, saveGlobalLogger)
import System.Log.Handler.Simple (fileHandler)
import System.Environment
import System.Exit
import System.IO (stderr)
import System.Console.GetOpt
import Network.Socket hiding (Debug)
import Network.URI
import Data.Version (showVersion)
import qualified Data.ByteString.Char8 as B
import Data.ByteString.UTF8 (fromString)
import Paths_gitit (version, getDataFileName)
main :: IO ()
main = do
-- parse options to get config file
args <- getArgs >>= parseArgs
-- sequence in Either monad gets first Left or all Rights
opts <- case sequence args of
Left Help -> putErr ExitSuccess =<< usageMessage
Left Version -> do
progname <- getProgName
putErr ExitSuccess (progname ++ " version " ++
showVersion version ++ compileInfo ++ copyrightMessage)
Left PrintDefaultConfig -> getDataFileName "data/default.conf" >>=
readFileUTF8 >>= B.putStrLn . fromString >> exitWith ExitSuccess
Right xs -> return xs
conf' <- case [f | ConfigFile f <- opts] of
(x:_) -> getConfigFromFile x
[] -> getDefaultConfig
let conf = foldl handleFlag conf' opts
-- check for external programs that are needed
let repoProg = case repositoryType conf of
Mercurial -> "hg"
Darcs -> "darcs"
Git -> "git"
let prereqs = ["grep", repoProg]
forM_ prereqs $ \prog ->
findExecutable prog >>= \mbFind ->
when (isNothing mbFind) $ error $
"Required program '" ++ prog ++ "' not found in system path."
-- set up logging
let level = if debugMode conf then DEBUG else logLevel conf
logFileHandler <- fileHandler (logFile conf) level
serverLogger <- getLogger "Happstack.Server.AccessLog.Combined"
gititLogger <- getLogger "gitit"
saveGlobalLogger $ setLevel level $ setHandlers [logFileHandler] serverLogger
saveGlobalLogger $ setLevel level $ setHandlers [logFileHandler] gititLogger
-- setup the page repository, template, and static files, if they don't exist
createRepoIfMissing conf
createStaticIfMissing conf
createTemplateIfMissing conf
-- initialize state
initializeGititState conf
let serverConf = nullConf { validator = Nothing, port = portNumber conf,
timeout = 20, logAccess = Nothing }
-- open the requested interface
sock <- socket AF_INET Stream defaultProtocol
setSocketOption sock ReuseAddr 1
device <- inet_addr (getListenOrDefault opts)
bindSocket sock (SockAddrInet (toEnum (portNumber conf)) device)
listen sock 10
-- start the server
simpleHTTPWithSocket sock serverConf $ msum [ wiki conf
, dir "_reloadTemplates" reloadTemplates
]
data ExitOpt
= Help
| Version
| PrintDefaultConfig
data ConfigOpt
= ConfigFile FilePath
| Port Int
| Listen String
| Debug
deriving (Eq)
type Opt = Either ExitOpt ConfigOpt
flags :: [OptDescr Opt]
flags =
[ Option ['h'] ["help"] (NoArg (Left Help))
"Print this help message"
, Option ['v'] ["version"] (NoArg (Left Version))
"Print version information"
, Option ['p'] ["port"] (ReqArg (Right . Port . read) "PORT")
"Specify port"
, Option ['l'] ["listen"] (ReqArg (Right . Listen . checkListen) "INTERFACE")
"Specify IP address to listen on"
, Option [] ["print-default-config"] (NoArg (Left PrintDefaultConfig))
"Print default configuration"
, Option [] ["debug"] (NoArg (Right Debug))
"Print debugging information on each request"
, Option ['f'] ["config-file"] (ReqArg (Right . ConfigFile) "FILE")
"Specify configuration file"
]
checkListen :: String -> String
checkListen l | isIPv6address l = l
| isIPv4address l = l
| otherwise = error "Gitit.checkListen: Not a valid interface name"
getListenOrDefault :: [ConfigOpt] -> String
getListenOrDefault [] = "0.0.0.0"
getListenOrDefault ((Listen l):_) = l
getListenOrDefault (_:os) = getListenOrDefault os
parseArgs :: [String] -> IO [Opt]
parseArgs argv = do
case getOpt Permute flags argv of
(opts,_,[]) -> return opts
(_,_,errs) -> putErr (ExitFailure 1) . (concat errs ++) =<< usageMessage
usageMessage :: IO String
usageMessage = do
progname <- getProgName
return $ usageInfo ("Usage: " ++ progname ++ " [opts...]") flags
copyrightMessage :: String
copyrightMessage = "\nCopyright (C) 2008 John MacFarlane\n" ++
"This is free software; see the source for copying conditions. There is no\n" ++
"warranty, not even for merchantability or fitness for a particular purpose."
compileInfo :: String
compileInfo =
#ifdef _PLUGINS
" +plugins"
#else
" -plugins"
#endif
handleFlag :: Config -> ConfigOpt -> Config
handleFlag conf Debug = conf{ debugMode = True, logLevel = DEBUG }
handleFlag conf (Port p) = conf { portNumber = p }
handleFlag conf _ = conf
putErr :: ExitCode -> String -> IO a
putErr c s = B.hPutStrLn stderr (fromString s) >> exitWith c
| thielema/gitit | gitit.hs | gpl-2.0 | 6,160 | 0 | 18 | 1,395 | 1,468 | 762 | 706 | 123 | 8 |
module Point3D where
import Data.Vector.Storable hiding ((++))
import qualified Data.Vector.Storable as V
import Foreign
import Foreign.C.Types
data Point3D = Point3D {-# UNPACK #-} !Double
{-# UNPACK #-} !Double
{-# UNPACK #-} !Double
data Axis = X | Y | Z deriving (Eq, Show)
instance Show Point3D where
show (Point3D x y z) = "(" ++ (show x) ++ "," ++ (show y) ++ "," ++ (show z) ++")"
instance Storable Point3D where
sizeOf _ = sizeOf (undefined :: Double) * 3
alignment _ = alignment (undefined :: Double)
{-# INLINE peek #-}
peek p = do
a <- peekElemOff q 0
b <- peekElemOff q 1
c <- peekElemOff q 2
return (Point3D a b c)
where
q = castPtr p
poke p (Point3D a b c)= do
pokeElemOff q 0 a
pokeElemOff q 1 b
pokeElemOff q 2 c
where
q = castPtr p
instance Eq Point3D where
(==) (Point3D a b c) (Point3D a' b' c') = (a == a') && (b == b') && (c == c')
(!) :: Point3D -> Int -> Double
(!) (Point3D x y z) i =
case i of 1 -> x
2 -> y
3 -> z
(#) :: Point3D -> Axis -> Double
(Point3D x y z) # ax
| ax == X = x
| ax == Y = y
| ax == Z = z
{-# INLINE (#) #-}
add :: Point3D -> Point3D -> Point3D
{-# INLINE add #-}
add (Point3D a b c) (Point3D a' b' c') = Point3D (a + a') (b + b') (c + c')
sub :: Point3D -> Point3D -> Point3D
{-# INLINE sub #-}
sub (Point3D a b c) (Point3D a' b' c') = Point3D (a - a') (b - b') (c - c')
mult :: Point3D -> Point3D -> Point3D
{-# INLINE mult #-}
mult (Point3D a b c) (Point3D a' b' c') = Point3D (a * a') (b * b') (c * c')
vsum :: Point3D -> Double
{-# INLINE vsum #-}
vsum (Point3D a b c) = a + b + c
norm :: Point3D -> Double
{-# INLINE norm #-}
norm (Point3D a b c) = sqrt (a*a + b*b + c*c)
norm2 :: Point3D -> Double
{-# INLINE norm2 #-}
norm2 (Point3D a b c) = (a*a + b*b + c*c)
euclidean :: Point3D -> Point3D -> Double
{-# INLINE euclidean #-}
euclidean a b = norm (sub a b)
euclidean2 :: Point3D -> Point3D -> Double
{-# INLINE euclidean2 #-}
euclidean2 a b = norm2 (sub a b)
scale :: Double -> Point3D -> Point3D
{-# INLINE scale #-}
scale d (Point3D a b c) = Point3D (a*d) (b*d) (c*d)
scaleDiv :: Point3D -> Double -> Point3D
{-# INLINE scaleDiv #-}
scaleDiv (Point3D a b c) d = Point3D (a/d) (b/d) (c/d)
| peterspackman/hsqc | src/Point3D.hs | gpl-3.0 | 2,311 | 0 | 13 | 631 | 1,076 | 562 | 514 | 69 | 3 |
module Reliquary.Core.TypeCheck where
import Control.Monad.Except
import Reliquary.Core.AST
import Reliquary.Core.DeBruijn
import Reliquary.Core.Evaluate
import Reliquary.Core.Utils
import Debug.Trace
envLookup :: Int -> CoreEnv -> Maybe (CoreTerm, Int)
envLookup n env = if n >= l then Nothing else Just $ env !! n where
l = length env
-- Given an environment of type associations and a term, return the type of
-- that term (or throw a type error)
check :: CoreEnv -> CoreTerm -> Either GenError CoreTerm
check _ CStar = return CStar
check _ CUnitType = return CStar
check env CUnit = return CUnitType
check _ CRelTermType = return CStar
check _ (CRelTerm _) = return CRelTermType
check env (CVar n) = case envLookup n env of
Just (t, d) -> return $ shift (length env - d) t
Nothing -> throwError NotInScope
check env (CApply e e') = do
te <- check env e
te' <- check env e'
case te of
CPi t t' -> if matchTerm te' t
then return $ normalize $ subst 0 e' t'
else throwError $ Mismatch t te'
_ -> throwError $ NotFunction te
check env (CLambda p p') = do
tp <- check env p
if isType tp
then do
tp' <- check ((p, length env):env) p'
return $ CPi p tp'
else throwError $ NotType p
check env (CCons p p') = CSigma <$> check env p <*> check env p'
check env (CFst p) = do
tp <- check env p
case tp of CSigma t _ -> return t
_ -> throwError $ NotPair tp
check env (CSnd p) = do
tp <- check env p
case tp of CSigma _ t -> return t
_ -> throwError $ NotPair tp
check env (CPi p p') = do
tp <- check env p
if isType tp
then do
tp' <- check ((normalize p, length env):env) p'
if isType tp'
then return CStar
else throwError $ NotType p'
else throwError $ NotType p
check env (CSigma p p') = do
tp <- check env p
if isType tp
then do
tp' <- check ((normalize p, length env):env) p'
if isType tp'
then return CStar
else throwError $ NotType tp'
else throwError $ NotType p
| chameco/reliquary | src/Reliquary/Core/TypeCheck.hs | gpl-3.0 | 2,398 | 0 | 15 | 901 | 836 | 405 | 431 | 61 | 11 |
module CC.ShellCheck.Env where
import CC.ShellCheck.Types
import qualified Data.Map.Strict as DM
import Data.Maybe
import qualified Data.Yaml as YML
import System.Directory
--------------------------------------------------------------------------------
-- | Load environment that maps remediation points to textual content.
loadEnv :: FilePath -> IO Env
loadEnv path = do
fileExists <- doesFileExist path
config <- if fileExists
then either (const Nothing) Just <$> YML.decodeFileEither path
else return Nothing
return $! fromMaybe DM.empty config
| filib/codeclimate-shellcheck | src/CC/ShellCheck/Env.hs | gpl-3.0 | 616 | 0 | 12 | 132 | 124 | 68 | 56 | 13 | 2 |
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : Data.Valet
Description : Abstract Value which can be evaluated and rendered.
Copyright : (c) Leonard Monnier, 2015
License : GPL-3
Maintainer : leonard.monnier@gmail.com
Stability : experimental
Portability : portable
This module provides the main elements of the 'Valet' package.
The main aim of this library is to provide a more general implementation
of the digestive-functors package.
The main difference are:
- the view is part of the 'Valet' allowing to render validations;
- it is not mainly targeted toward HTML forms;
- a form created with this library is not necessarely a formlet.
It shares also some very close similarities such as the use of GADTs to define
the structure and its behaviour as 'Applicative' instance.
* Introduction
A 'Valet' can be seen as a value with additional properties. It may be:
- Rendered: displayed in another format than the one of the value itself.
- Set: from a value of another type.
- Modified: changing the value inside the valet.
- Analysed: leading to the production of a report.
- Composed: through the 'Applicative' type-class.
This library relies on lens to set, view or modify the properties of a given
valet. It allows the usage of a known and concise syntax.
* Organisation of the library
The library is organised with:
- Some types, among which the main one is the 'Valet' one.
- Lenses: allowing to set, get and modify the valet's properties.
- Getters: allowing to evaluate or render the valet.
* Creating a valet.
A 'Valet' contains a value of a given type
and is referenced by a key which must be unique.
Here is a basic 'Text' 'Valet' with an empty value:
> textValet :: Valet r m Text
> textValet = valet "myText" ""
The last type of the valet is now 'Text' which indicates that
its value is of type 'Text'.
A valet being an instance of Applicative, you can also use the pure function.
However, in such a case, you will have to later define a key if you wish
to use all the valet's functionnalities.
** The [TODO]
A valet can be set from a given type, matching the provided reader function.
In our case, the reader function is a function which converts the given type to
a 'Text'.
For example, if we want to be able to set a value from a 'String':
> textValet' :: Text -> Value String m Text
> textValet' = valet key data
It is now possible to modify the value of an existing valet:
> name = textValue "name" ""
> haskell = setValue "name" "Haskell"
** Modifications
A modification applies a function to a value
which returns a new value of the same type.
** Modifications and analysis considerations
Both topics are closely related.
An analysis can be seen as a filter using the 'id' function
with potential failure.
It could therefore be possible to approach both subjects with the same function.
However, the problems start when collecting failures.
It is also possible to add transformations to a value.
Tranformations can be of two kinds:
- the ones which just modify a value but never fail: the "filters";
- the ones which can fail: the "validators".
Transformations return a 'Result' which can be either the transformed value
in case of success or an error in case of failure.
To add a filter converting a text to upper case:
> upperTextValue :: Text -> Text -> Valet r m String Text
> upperTextValue key data =
> transformer toUpper $ textValue key data
> where
> toUpper :: Text -> Result Text Text
> toUpper = Success . upper
-}
module Data.Valet
(
-- * Types
Valet
, SomeValet
, Analysis
, RAnalysis
, Modif
, RModif
, Result(..)
, Coerce
-- * Constructors
, valet
, someValet
, analysis
, modif
, check
, report
-- * Lenses
{-|
Lenses are the mean to access, set or modify the different components
of a valet. To know more about lenses, please refer to the
'Control.Lens' library and the various tutorials which have been
written about this library.
-}
, value
, showValueFunc
, key
, analyser
, rAnalyser
, modifier
, rModifier
, reader
, renderer
-- ** Indexed lenses
, keyi
-- * Getters
{-|
Getters can be used as lenses but only to retrieve value, not
to modify or set them.
-}
, eval
, showValue
, render
, renderSubValets
, keys
-- ** Indexed getters
{-|
The key of the 'Valet' must be provided to these getters.
-}
, lookup
) where
import Control.Applicative ((<|>))
import Control.Lens
import Control.Monad ((>=>))
import Data.Monoid
import Prelude hiding (lookup)
import qualified Data.Text as T
----------------------------------------
-- Types
----------------------------------------
{-|
The valet data-type.
* Meaning of the types
** @r@
Type in which the valet can be rendered.
This type has to be a 'Monoid' instance.
For example, the type @r@ could be a 'String'.
It would mean that a 'Valet' with, let's say, an 'Int' value could be
rendered as a 'String'.
For a webform, you could typically define a type HTML such as:
> type HTML = Text
Then, your valet would have type:
> Valet HTML m a
TODO: explain how composite types can be used.
** @m@
Monad in which modifications or analysis occur.
The most likely usage is if you need to analyse a value against the one of a
database (for example to determine if this value does not already exist in
that database.) In such case, the monad type would by 'IO' and your valet would
have type:
> Valet r IO a
The usage of a monad for modifications is less likely but could maybe occur
in some edge cases.
** @a@
Value contained in the valet.
If your valet contains a 'String' then its type would be:
> Valet r m String
-}
data Valet r m a where
-- | Set a key to a valet.
Key :: T.Text -> Valet r m a -> Valet r m a
-- | Add a renderer to a valet.
Render :: Rendered r m -> Valet r m a -> Valet r m a
-- | Add a analyser to a valet.
Analyse :: Analysis r m a -> Valet r m a -> Valet r m a
-- | Add a modifier to a valet.
Modify :: Modif m a -> Valet r m a -> Valet r m a
-- | Convert a renderer to a value.
Read :: (r -> a) -> Valet r m a -> Valet r m a
-- | Display a value as 'Text'.
ShowValue :: (a -> T.Text) -> Valet r m a -> Valet r m a
-- | Applicative transformation. This allows to combine valets in a given
-- data-type in an applicative style.
-- For example 'name' and 'age' being valets:
-- > Person <$> name <*> age
Apply :: Monoid r => Valet r m (c -> a) -> Valet r m c -> Valet r m a
-- | Create a valet by setting its value.
Value :: a -> Valet r m a
-- | Show instance for debugging purposes.
instance Show (Valet r m a) where
show (Value _) = "Value: x"
show (ShowValue _ v) = "Show value: " ++ show v
show (Read _ f) = "Read g: " ++ show f
show (Key x f) = "Key " ++ show x ++ ": " ++ show f
show (Render _ f) = "Render r: " ++ show f
show (Modify _ f) = "Modify g " ++ show f
show (Analyse _ f) = "Analyse g: " ++ show f
show (Apply f1 f2) = "Apply: (" ++ show f1 ++ ", " ++ show f2 ++ ")"
instance (Monoid r) => Functor (Valet r m) where
fmap g = Apply (Value g)
instance (Monoid r) => Applicative (Valet r m) where
pure = Value
(<*>) = Apply
type instance Index (Valet r m a) = T.Text
type instance IxValue (Valet r m a) = r
instance (Monad m, Monoid r) => Ixed (Valet r m a) where
ix k f sv = case sv ^. lookup k of
Just v -> f (v ^. render) <&> \v' -> putValue k sv v'
Nothing -> pure sv
{-|
Allows to use the 'at' lens to set or view values using their key.
-}
instance (Monad m, Monoid r) => At (Valet r m a) where
at k f v = f vr <&> \r -> case r of
Nothing -> v
Just r' -> putValue k v r'
where vr = fmap (view render) $ v ^. lookup k
{-|
Value agnostic valet.
Value agnostic valet are usefull when you wish to get information from
only a given sub-valet.
However, it is at some cost, as you then loose the possibility to retrieve
the value with its type information.
* Use
A typicall use of a value agnostic valet is when you wish to perform
a validation on a single sub-value using a key. It happens for example
with a webform when you wish to verify that a value is indeed unique on the
server side.
* Example
> validate :: (Monad m, Monoid r) => m (Maybe r)
> validate =
> someValet (myValet & at "name" ?~ "Jean") ^. at "name" . _Just . report
The above example illustrates many concepts.
In the first part @(myValet & at "name" ?~ "Jean")@ the value of the valet is
modified using the lens 'at' and the '(?~)' combinator.
We therefore obtain a new 'Valet'. Then, this new valet is converted to
a value agnostic valet ('SomeValet') using the 'someValet' function.
From there, we need to retrieve the sub-valet and perform the analysis
of the value. The first task is accomplished thanks to the 'at' lens.
Since this operation may fail (there might be no sub-valet matching the
provided key) we need to combine it with the '_Just' prism.
Finally, we can perform a 'report' on the 'sub-valet' which will
return all the error messages or 'Nothing' if there are not any.
-}
data SomeValet r m where
SomeValet :: (Monoid r, Monad m) => Valet r m a -> SomeValet r m
{-|
Coerce a value of a given type to a value of another type.
This class is a "trick" which is used to convert 'Valet' or
value agnostic valet ('SomeValet') to 'SomeValet'.
In the second case, the conversion is not actually one. It is
just the 'id' function.
Concretely, when you see @Coerce b (SomeValet r m)@ in a function
signature, you know that you can use indiferentely a 'Valet'
or 'SomeValet' for parameter @b@ (or even a type of your customed
instance if you wish to define one).
-}
class Coerce a b | a -> b where
coerce :: a -> b
instance (Monoid r, Monad m) => Coerce (Valet r m a) (SomeValet r m) where
coerce = SomeValet
instance Coerce (SomeValet r m) (SomeValet r m) where
coerce = id
{-|
Type synonym for a function turning a value agnostic valet ('SomeValet')
to a rendered value @r@.
Having such type allow to the rendered value to access all the 'Valet's
parameters.
-}
type Rendered r m = SomeValet r m -> r
{-|
* Conceptual meaning
An analysis encapsulates in a newtype a monadic function.
It is therefore a 'Kleisli'.
Since the 'Monoid' instance for this newtype
acts at the value level, @b@ must also be a monoid.
* Use by the valet library
In practice in this library the type @r@ is @Maybe (Rendered r)@ meaning that
from the value @a@ of the 'Valet' we might get a rendering @r@.
This type @r@ can be seen as the report of the analysis. It takes a value,
it analyses it and it produces a report (if there is something to report).
This rendering is actually not a value but a function which takes the 'Valet'
as parameter. That way, the rendering can access the data of the 'Valet'
such as its key.
Thanks to its 'Monoid' instance it's easy to combine various analysis into
one:
> analysis3 :: Analysis m a b
> analysis3 = analysis1 <> analysis2
The results of those different analyisis will be combined as a monoid.
* Possible use
A concrete example of an analysis is the validation of the value of a form.
The user submits a form, the value of a given field gets analysed and errors
get reported if any.
-- TODO: update doc.
-}
type Analysis r m a = KleisliMonoid m a (Maybe (Rendered r m))
newtype KleisliMonoid m a b = KleisliMonoid {runKleisliMonoid :: a -> m b}
{-|
* Conceptual meaning
A modification encapsulate in a newtype a monadif function which returns
a value of the same type as the initial value.
It is therefore a 'Kleisli'.
The 'Monoid' instance for this newtype
acts at the monad level @m@ through kleisli composition @(>=>)@.
* Use by the valet library
Thanks to its 'Monoid' instance different modifications acting on the same
type can be combined into one. Each modification will pass its result
to the next one:
> modif3 :: Modif m a
> modif3 = modif1 <> modif2
* Possible use
A concrete example of an modification is the filtering of value.
Imagine you want a last name in upper case, you could have filters to:
- remove all spaces before and after the name (trim);
- convert all characters to upper case.
-}
newtype Modif m a = Modif {runModif :: a -> m a}
{-|
For 'mappend', this instance returns a new 'KleisliMonoid' which function append
the results of both 'KleisliMonoid'' functions.
-}
instance (Monad m, Monoid b) => Monoid (KleisliMonoid m a b) where
mempty = KleisliMonoid (\_ -> return mempty)
mappend k1 k2 = KleisliMonoid g
where
g x = do
r1 <- runKleisliMonoid k1 x
r2 <- runKleisliMonoid k2 x
return (r1 <> r2)
{-|
For 'mappend' this instance returns a new 'Modif' which function is
a monadic combination of both 'Modif'.
-}
instance Monad m => Monoid (Modif m a) where
mempty = Modif (return . id)
Modif g `mappend` Modif h = Modif (g >=> h)
{-|
A result which can denote a success by returning a data,
or a failure by returning a type which can be rendered.
The types are the following:
- @a@: data of the 'Valet';
- @r@: type used to display the error(s);
-}
data Monoid r => Result r a =
Success a
| Failure r
deriving(Show)
instance Monoid r => Functor (Result r) where
fmap g (Success x) = Success $ g x
fmap _ (Failure e) = Failure e
instance Monoid r => Applicative (Result r) where
pure = Success
Success g <*> Success x = Success $ g x
Failure e <*> Success _ = Failure e
Success _ <*> Failure e = Failure e
Failure d <*> Failure e = Failure (d <> e)
----------------------------------------
-- CONSTRUCTORS
----------------------------------------
{-|
Create a new valet.
This function is equivalent to 'pure'.
-}
valet ::
Monoid r
=> a -- ^ Initial value of the valet.
-> Valet r m a
valet = pure
{-|
Convert a value – typically a 'Valet' or 'SomeValet' – to a value
agnostic valet ('SomeValet').
-}
someValet :: Coerce b (SomeValet r m) => b -> SomeValet r m
someValet = Data.Valet.coerce
{-|
Create an analysis from the provided function.
-}
analysis :: (a -> m (Maybe (Rendered r m))) -> Analysis r m a
analysis = KleisliMonoid
{-|
Create a modification from the provided function.
-}
modif :: (a -> m a) -> Modif m a
modif = Modif
{-|
Create an analysis from a monadic boolean function and a renderer.
The typical use case of this function is to create a validation where
the renderer will return an error.
For example, if we want to ensure that an integer is higher than a certain
value we can write:
> higherThan x =
> check (\y -> return (y > x))
> "The value must be higher than " <> read x <> "."
TODO: check the validity of the example.
-}
check :: Monad m => (a -> m Bool) -> Rendered r m -> Analysis r m a
check g e = analysis $ \x -> do
predicate <- g x
if predicate then return Nothing else return $ Just e
{-|
Create a result from a value and a report.
If the report is @Nothin@ and therefore does not contain any errors,
then a @Success@ containing the value is returned.
Otherwise, a @Failure@ containing the error of the report is returned.
-}
result :: Monoid r => a -> Maybe r -> Result r a
result x Nothing = Success x
result _ (Just r) = Failure r
----------------------------------------
-- Setters
----------------------------------------
-- | Generic setter, which provides default behaviors for each patern match.
setter ::
(Valet r m a -> c -> Valet r m a)
-> Valet r m a
-> c
-> Valet r m a
setter _ (Value x) _ = Value x
setter h (ShowValue g v) x = ShowValue g (h v x)
setter h (Key k v) x = Key k (h v x)
setter h (Read g v) x = Read g (h v x)
setter h (Render g v) x = Render g (h v x)
setter h (Modify g v) x = Modify g (h v x)
setter h (Analyse g v) x = Analyse g (h v x)
setter _ (Apply g v) _ = Apply g v
{-|
Set the value of the provided 'Valet'.
* Note
It cannot be used for applicative values.
By doing so, the unmodified valet will be returned.
-}
setValue :: Valet r m a -> a -> Valet r m a
setValue (Value _) x = Value x
setValue v x = setter setValue v x
{-|
Set a function which converts the value of the 'Valet' to 'Text'.
-}
setShowValue :: Valet r m a -> (a -> T.Text) -> Valet r m a
setShowValue (Value x) g = ShowValue g (Value x)
setShowValue (Apply h v) g = ShowValue g (Apply h v)
setShowValue (ShowValue _ v) g = ShowValue g v
setShowValue v x = setter setShowValue v x
{-|
Set the key of a the provided 'Valet'.
This key can then be used to retrieve the different components of the 'Valet'
and its sub-valets.
-}
setKey :: (Monoid r, Monad m) => Valet r m a -> T.Text -> Valet r m a
setKey v k
-- We ensure that the name is at the top if defined.
-- No name is created for an empty text value.
| currentKey <> k == "" = v
| currentKey == "" = Key k v
| otherwise = setKey' v k
where
currentKey = v ^. key
setKey' (Key _ v') k' = Key k' v'
setKey' v' k' = setter setKey' v' k'
{-|
Set the analyser of the provided 'Valet'.
* Note
This will replace the previously existing analyse function of the 'Valet'.
-}
setAnalyser :: Monad m => Valet r m a -> Analysis r m a -> Valet r m a
setAnalyser (Analyse _ v) c = Analyse c v
setAnalyser (Value x) c = Analyse c (Value x)
setAnalyser (Apply g v) c = Analyse c (Apply g v)
setAnalyser v c = setter setAnalyser v c
{-|
Set the modifier of the provided 'Valet'.
* Note
This will replace the previously existing modify function of the 'Valet'.
-}
setModifier ::
(Monad m, Monoid r)
=> Valet r m a
-> Modif m a
-> Valet r m a
setModifier (Modify _ v) m = Modify m v
setModifier (Value x) m = Modify m (Value x)
setModifier (Apply g v) m = Modify m (Apply g v)
setModifier v m = setter setModifier v m
{-|
Provide a function which convert a given type to the one of the data.
This will then be used to set the data of a value by functions
such as 'setValue'.
* Note
It does not apply to applicative values.
In such case, the unmodified 'Valet' will be returned.
-}
setReader :: Valet r m a -> (r -> a) -> Valet r m a
setReader (Value x) g = Read g (Value x)
setReader (Read _ v) g = Read g v
setReader v g = setter setReader v g
{-|
Set the renderer of a value.
-}
setRenderer :: Valet r m a -> (SomeValet r m -> r) -> Valet r m a
setRenderer (Value x) g = Render g (Value x)
setRenderer (Render _ v) g = Render g v
setRenderer (Apply h v) g = Render g (Apply h v)
setRenderer v g = setter setRenderer v g
----------------------------------------
-- Getters
----------------------------------------
-- | Generic getter for 'Valet'.
getter :: Valet r m a -> Valet r m a
getter (ShowValue _ v) = v
getter (Key _ v) = v
getter (Read _ v) = v
getter (Render _ v) = v
getter (Modify _ v) = v
getter (Analyse _ v) = v
getter (Apply g v) = g <*> v
getter (Value x) = Value x
-- | Return the value of a 'Valet'.
getValue :: Valet r m a -> a
getValue (Value x) = x
getValue (Apply g v) = getValue g (getValue v)
getValue v = getValue $ getter v
{-|
Retrieve the value converting the value of a 'Valet' to 'Text'.
If this function does not exist, return one which will always
return an empty 'Text' ("").
-}
getShowValue :: Valet r m a -> a -> T.Text
getShowValue (Value _) = (\_ -> mempty)
getShowValue (Apply _ _) = (\_ -> mempty)
getShowValue (ShowValue g _) = g
getShowValue v = getShowValue $ getter v
-- | Return the analyser of a 'Valet'.
getAnalyser :: (Monoid r, Monad m) => Valet r m a -> Analysis r m a
getAnalyser (Value _) = mempty
getAnalyser (Apply _ _) = mempty
getAnalyser (Analyse g _) = g
getAnalyser v = getAnalyser $ getter v
-- | Return the modifier of a 'Valet'.
getModifier :: Monad m => Valet r m a -> Modif m a
getModifier (Value _) = mempty
getModifier (Apply _ _) = mempty
getModifier (Modify g _) = g
getModifier v = getModifier $ getter v
-- | Return the reader of the 'Valet'.
getReader :: Valet r m a -> r -> a
getReader (Value x) = (\_ -> x)
getReader (Apply g v) = let x = getValue g (getValue v) in (\_ -> x)
getReader v = getReader $ getter v
-- | Return the renderer of the 'Valet'.
getRenderer :: Monoid r => Valet r m a -> SomeValet r m -> r
getRenderer (Render r _) = r
getRenderer (Apply _ _) = mempty
getRenderer (Value _) = mempty
getRenderer v = getRenderer $ getter v
{-|
Return a 'Result' which comes from the evaluation of the valet
applying on it the modification and analysis which have been previously set.
-}
eval :: (Monad m, Monoid r) => Getter (Valet r m a) (m (Result r a))
eval = to $ \x -> case x of
Value v -> return $ Success v
v@(Key _ _) -> do
val <- runModif (v ^. modifier) $ v ^. value
report' <- runKleisliMonoid (v ^. analyser) $ val
return $ result val (report' <*> pure (someValet v))
Apply g v -> do
r1 <- g ^. eval
r2 <- v ^. eval
return $ r1 <*> r2
v -> view eval $ getter v
-- | Generic getter for a value agnostic valet.
sGetter :: SomeValet r m -> SomeValet r m
sGetter (SomeValet (ShowValue _ v)) = SomeValet v
sGetter (SomeValet (Key _ v)) = SomeValet v
sGetter (SomeValet (Read _ v)) = SomeValet v
sGetter (SomeValet (Render _ v)) = SomeValet v
sGetter (SomeValet (Modify _ v)) = SomeValet v
sGetter (SomeValet (Analyse _ v)) = SomeValet v
sGetter (SomeValet (Apply g v)) = SomeValet $ g <*> v
sGetter (SomeValet (Value x)) = SomeValet $ Value x
{-|
Display a value contained in a 'Valet' or value agnostic valet ('SomeValet')
as 'Text'.
If no function to render to render the 'Valet' (which can be set using
the 'showValueFunc' lens) then an empty 'Text' is returned ("").
-}
showValue :: Coerce b (SomeValet r m) => Getter b T.Text
showValue = to $ \sv -> case Data.Valet.coerce sv of
SomeValet (Value _) -> ""
SomeValet (ShowValue g v) -> g $ v ^. value
SomeValet (Apply g v) -> let t1 = g ^. showValue
t2 = v ^. showValue
in
if t1 /= ""
then t1 <> ", " <> t2
else t2
v -> sGetter v ^. showValue
{-|
Get the key of a 'Valet'.
-}
getKey :: Coerce b (SomeValet r m) => b -> T.Text
getKey sv = case Data.Valet.coerce sv of
SomeValet (Value _) -> ""
SomeValet (Key x _) -> x
SomeValet (Apply _ _) -> ""
v -> getKey $ sGetter v
{-|
Return the result of the analysis performed on a valet after its values have
been modified.
* Use
This can be usefull, if you wish to validate the value of a specific element
of a 'Valet'.
* Examples
To obtain a report, you first need to obtain a value agnostic valet
of type 'SomeValet' turning the 'lookup' function into a 'Getter'.
> somePerson :: Maybe (SomeValet r m)
> somePerson = person ^. to (lookup "name)
As the lookup may fail and return a @Maybe (SomeValet r m)@
rather than @SomeValet r m@ the 'report' 'Getter' will need to be used
in conjunction with the '_Just' 'Prism':
> myReport :: m (Maybe r)
> myReport = person ^. to (lookup "name") . _Just . report
Another way to achieve the same result is to turn person into 'SomeValet'
and then use the 'at' lens.
> myReport = someValet person ^. at "name" . _Just . report
TODO: check the validity of the example.
-}
report ::
(Coerce a (SomeValet r m), Monad m, Monoid r)
=> Getter a (m (Maybe r))
report =
to $ result' . Data.Valet.coerce
where
result' (SomeValet v) = do
r <- v ^. eval
case r of
Success _ -> return Nothing
Failure e -> return $ Just e
{-|
Render a value and its sub-values.
-}
render :: (Coerce b (SomeValet r m), Monoid r) => Getter b r
render = to $ \sv -> case Data.Valet.coerce sv of
v@(SomeValet (Key _ v')) -> (v' ^. renderer $ v) <> (someValet v') ^. render
SomeValet (Apply g v) -> g ^. render <> v ^. render
SomeValet (Value _) -> mempty
v -> (view render) $ sGetter v
{-|
Render the sub-valets of a 'Valet' but not the 'Valet' itself.
-}
renderSubValets :: (Coerce b (SomeValet r m), Monoid r) => Getter b r
renderSubValets = to $ \sv -> case Data.Valet.coerce sv of
SomeValet (Value _) -> mempty
SomeValet (Apply g v) -> g ^. render <> v ^. render
v -> (view renderSubValets) $ sGetter v
-- | Lookup for a valet returning a value agnostic valet.
lookup :: Coerce b (SomeValet r m) => T.Text -> Getter b (Maybe (SomeValet r m))
lookup k = to $ \s -> case Data.Valet.coerce s of
SomeValet (Value _) -> Nothing
v@(SomeValet (Key x v')) -> if k == x then Just v else v' ^. lookup k
SomeValet (ShowValue _ v) -> SomeValet v ^. lookup k
SomeValet (Read _ v) -> SomeValet v ^. lookup k
SomeValet (Render _ v) -> SomeValet v ^. lookup k
SomeValet (Modify _ v) -> SomeValet v ^. lookup k
SomeValet (Analyse _ v) -> SomeValet v ^. lookup k
SomeValet (Apply g v) -> SomeValet g ^. lookup k
<|> SomeValet v ^. lookup k
{-|
Get all the keys of a 'Valet' and its sub-valets.
This can be usefull if you wish to ensure that all the keys of a given
'Valet' are indeed unique (as they should be!).
Typically:
> areKeysUnique :: Bool
> areKeysUnique = let ks = valet ^. keys in nub ks == ks
TODO: check the validity of the above example.
-}
keys :: Coerce b (SomeValet r m) => Getter b [T.Text]
keys = to $ \sv -> case Data.Valet.coerce sv of
SomeValet (Value _) -> []
SomeValet (Key x v) -> [x] <> v ^. keys
SomeValet (Apply g v) -> g ^. keys <> v ^. keys
v -> (view keys) $ sGetter v
----------------------------------------
-- LENSES
----------------------------------------
{-|
Value contained in a valet.
As you need to define a value when you create a 'Valet' using 'valet' or 'pure'
functions, this lens is needed only if you wish to set a new value:
> valet' :: Valet r m String
> valet' = valet ~. "new value"
or if you want to access the initially defined value (without applying any
modifications nor analysis):
> myValue :: String
> myValue = valet ^. value
TODO: check that the above examples are valid.
-}
value :: Lens' (Valet r m a) a
value = lens getValue setValue
{-|
Function which convert the value of a 'Valet' to 'Text'.
It is usefull to have such function when you wish to display the value
of the 'Valet' in the renderer function (as the renderer takes as
parameter a value agnostic valet ('SomeValet') rather than a 'Valet').
-}
showValueFunc :: Lens' (Valet r m a) (a -> T.Text)
showValueFunc = lens getShowValue setShowValue
{-|
Key of a valet.
This key should be unique as it can be used for interacting with the sub-valets
contained in a valet.
To ensure this, you can use the 'keys' function or 'keyi' lens.
-}
key :: (Monoid r, Monad m) => Lens' (Valet r m a) T.Text
key = lens getKey setKey
{-|
Analysis of a value.
-}
analyser ::
(Monad m, Monoid r)
=> Lens' (Valet r m a) (Analysis r m a)
analyser = lens getAnalyser setAnalyser
-- | Modification of a value.
modifier ::
(Monad m, Monoid r)
=> Lens' (Valet r m a) (Modif m a)
modifier = lens getModifier setModifier
-- | Reader of a value.
reader :: Lens' (Valet r m a) (r -> a)
reader = lens getReader setReader
{-|
Renderer of a valet.
This renderer could for example render the value as:
- a JSON object;
- a HTML form;
- a SQL statement;
- etc.
It could also be a combination of multiple renderers with a data type such as:
@
data Renderer = Renderer
{ json :: Json
, html :: Html
}
@
-}
renderer :: Monoid r => Lens' (Valet r m a) (SomeValet r m -> r)
renderer = lens getRenderer setRenderer
type RAnalysis r m a = (Analysis r m a, SomeValet r m -> r)
type RModif r m a = (Modif m a, SomeValet r m -> r)
{-|
Lens combining in a tuple an analysis and a rendering (expected to be the
rendering of the analysis).
-}
rAnalyser :: (Monad m, Monoid r) => Lens' (Valet r m a) (RAnalysis r m a)
rAnalyser = lens
(\x -> (getAnalyser x, getRenderer x))
(\z (x , y) -> setAnalyser (setRenderer z y) x)
{-|
Lens combining in a tuple a modifier and a rendering (expected to be the
rendering of the modifier).
-}
rModifier :: (Monad m, Monoid r) => Lens' (Valet r m a) (RModif r m a)
rModifier = lens
(\x -> (getModifier x, getRenderer x))
(\z (x, y) -> setModifier (setRenderer z y) x)
----------------------------------------
-- Indexed lenses
----------------------------------------
{-|
Key of a sub-valet.
This lens can be used to modify the current key or to check if a given
key exists.
-- TODO: examples.
-}
keyi ::
(Monoid r, Monad m)
=> T.Text -- ^ Key of the key.
-> Lens' (Valet r m a) T.Text
keyi k = lens (\x -> x ^. lookup k . _Just . to getKey) (putKey k)
----------------------------------------
-- Indexed Setters
----------------------------------------
{-|
Replace the key of the sub-value matching the provided key, so the
current key will be replaced by the new one.
-}
putKey ::
T.Text -- ^ Current key.
-> Valet r m a
-> T.Text -- ^ New key.
-> Valet r m a
putKey k vt k' = case vt of
Key x v -> if k == x then Key k' v else Key x (putKey k v k')
Apply g v -> putKey k g k' <*> putKey k v k'
x -> setter (putKey k) x k'
{-|
Insert the provided data in the sub-value matching the key.
-}
putValue ::
Monad m
=> T.Text -- ^ Key.
-> Valet r m a
-> r -- ^ Data.
-> Valet r m a
putValue key' = putValueReader key' Nothing
{-|
Insert the provided data in the sub-value matching the key
using the provided reader function, if any.
-}
putValueReader ::
Monad m
=> T.Text -- ^ Key.
-> Maybe (r -> a) -- ^ Optional reader function.
-> Valet r m a
-> r -- ^ Data.
-> Valet r m a
putValueReader key' reader' form val = case form of
Value x -> case reader' of
Just g -> Value $ g val
Nothing -> Value x
Read g v -> Read g $ putValueReader key' (Just g) v val
Key x v -> if key' == x
then Key x $ putValueReader key' reader' v val
else Key x (valueReader reader' v val)
Apply g v -> putValueReader key' Nothing g val
<*> putValueReader key' Nothing v val
x -> setter (putValueReader key' reader') x val
where
valueReader ::
Monad m => Maybe (r -> a) -> Valet r m a -> r -> Valet r m a
valueReader reader'' vt newValet = case vt of
Value x -> case reader'' of
Just g -> Value $ g newValet
Nothing -> Value x
Apply g v -> putValueReader key' Nothing g newValet
<*> putValueReader key' Nothing v newValet
x -> setter (valueReader reader'') x newValet
{-|
Replace the current renderer of a sub-valet matching the provided key
by a new one.
-- TODO: implement as a lens.
-}
putRenderer ::
T.Text -- ^ Key.
-> Valet r m a
-> Rendered r m -- ^ Renderer.
-> Valet r m a
putRenderer k vt r = case vt of
Key x v -> if k == x
then Key k (putRenderer' k v r)
else Key k (putRenderer k v r)
Apply g v -> putRenderer k g r <*> putRenderer k v r
x -> setter (putRenderer k) x r
where
putRenderer' k' vt' r' = case vt' of
Render _ v -> Render r' v
x -> setter (putRenderer' k') x r'
----------------
--- EXAMPLES ---
----------------
-- Validators.
minLength :: Monad m => Int -> RAnalysis T.Text m T.Text
minLength min =
( check
(\x -> return (T.length x >= min))
(\y -> "For " <> (y ^. to getKey) <> " the minimal length is "
<> T.pack (show min) <> ".")
, const "function minLength();"
)
failure :: a -> Bool
failure _ = False
-- Filters.
{-|
-- Monadic filters.
randomInt :: T.Text -> Int -> IO (Result T.Text Int)
randomInt _ x = do
r <- getStdRandom (randomR (1,6))
return $ Success (r * x)
-}
-- Elements.
varchar ::
Monad m
=> T.Text -- ^ Key.
-> Int -- ^ Max length.
-> Valet T.Text m T.Text
varchar name l =
pure mempty
& key .~ name
& showValueFunc .~ T.pack . show
& reader .~ id
& renderer .~ renderVarchar l
int :: Monad m => T.Text -> Valet T.Text m Int
int name =
valet 0
& key .~ name
& showValueFunc .~ T.pack . show
& reader .~ (read . T.unpack)
& renderer .~ renderInt
-- Renderers.
renderInt :: Monad m => SomeValet T.Text m -> T.Text
renderInt f =
"<input name=\"" <> getKey f <> "\" "
<> "type=\"text\" value=\"" <> f ^. showValue <> "\"/>"
renderVarchar :: Monad m => Int -> SomeValet T.Text m -> T.Text
renderVarchar l f =
"<input name=\"" <> getKey f <> "\" "
<> "type=\"text\" value=\"" <> f ^. showValue <> "\" "
<> "length=\"" <> T.pack (show l) <> "\""
<> "/>"
-- Example.
data Page = Page
{ url :: T.Text
, pageName :: T.Text
, visits :: Int
} deriving (Show)
myTest :: Valet T.Text Maybe T.Text
myTest = varchar "url" 256
& rModifier <>~ ( modif (return . T.toUpper)
, \x -> "<script>toUpper(\"" <> x ^. to getKey <> "\");</script>"
)
& rAnalyser <>~ minLength 4
{-|
Example of a custom rendering.
-}
renderPage :: Monad m => Valet T.Text m Page -> T.Text
renderPage f =
"<form name=\"" <> f ^. key <> "\"> "
<> "<h1>My url</h1>"
<> f ^. at "url" . non ""
<> "</form>"
myUrl :: Valet T.Text Maybe T.Text
myUrl =
varchar "url" 256
& rModifier <>~ ( modif (return . T.toUpper)
, \x -> "<script>toUpper(\"" <> x ^. to getKey <> "\");</script>"
)
& rAnalyser <>~ minLength 4
myName :: Valet T.Text Maybe T.Text
myName =
varchar "page" 256
& rAnalyser <>~ minLength 3
myVisits :: Valet T.Text Maybe Int
myVisits = int "visits"
myPage :: Valet T.Text Maybe Page
myPage = (Page <$> myUrl <*> myName <*> myVisits) & key .~ "t"
mySetName :: Valet T.Text Maybe T.Text
mySetName = myName & value .~ "home"
mySetUrl :: Valet T.Text Maybe T.Text
mySetUrl = myUrl & value .~ "http"
mySetPage :: Valet T.Text Maybe Page
mySetPage = myPage
& at "url" ?~ "http"
& at "visits" ?~ "10"
& at "page" ?~ "home"
test = (myPage & at "url" ?~ "H!") ^. lookup "url" . _Just . report
| momomimachli/Valet | src/Data/Valet.hs | gpl-3.0 | 35,551 | 0 | 18 | 9,441 | 7,977 | 4,022 | 3,955 | -1 | -1 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module MEnv.System.GLFW
(
systemHandleFrontBegin,
systemHandleFrontEnd,
systemHandleBackBegin,
systemHandleBackEnd,
) where
import MEnv
systemHandleFrontBegin :: a -> a -> MEnv res a
systemHandleFrontBegin a a' =
return a
systemHandleFrontEnd :: a -> a -> MEnv res a
systemHandleFrontEnd a a' =
return a
systemHandleBackBegin :: a -> a -> MEnv res a
systemHandleBackBegin a a' =
return a
systemHandleBackEnd :: a -> a -> MEnv res a
systemHandleBackEnd a a' =
return a
{-
data Friend
data FriendData =
meta :: XXX,
content :: BS.ByteString
friendsEatData :: ([FriendData] -> [FriendData]) -> MEnv res ()
-}
| karamellpelle/grid | designer/source/MEnv/System/GLFW.hs | gpl-3.0 | 1,424 | 0 | 7 | 298 | 168 | 96 | 72 | 19 | 1 |
-- Copyright 2016, 2017 Robin Raymond
--
-- This file is part of Purple Muon
--
-- Purple Muon is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Purple Muon is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Purple Muon. If not, see <http://www.gnu.org/licenses/>.
{-|
Module : Client.States.InGameState.Loop
Description : The loop function while in the game
Copyright : (c) Robin Raymond, 2016-2017
License : GPL-3
Maintainer : robin@robinraymond.de
Portability : POSIX
-}
module Client.States.InGameState.Loop
( loop
) where
import Protolude
import qualified Client.States.InGameState.Types as CSIT
import qualified Client.Types as CTY
-- | The loop while being in game
-- Note that loop should _not_ pass any errors further along, unless they are
-- fatal. There is no recovery beyond this point, hence no MonadError.
loop :: (MonadIO m, MonadState CSIT.State m, MonadReader CTY.Resources m)
=> m ()
loop = return ()
--import qualified Control.Concurrent.STM as CCS
--import qualified Control.Lens as CLE
--import qualified Control.Lens.Zoom as CLZ
--import qualified Data.IntMap.Strict as DIS
--import qualified Formatting as FOR
--import qualified SDL as SDL
--import qualified SDL.Event as SEV
--import qualified SDL.Font as SFO
--import qualified SDL.Mixer as SMI
--import qualified SDL.Vect as SVE
--import qualified SDL.Video as SVI
--
--import qualified PurpleMuon.Game.Types as PGT
--import qualified PurpleMuon.Input.Util as PIU
--import qualified PurpleMuon.Network.Types as PNT
--import qualified PurpleMuon.Types as PTY
--
--import qualified Client.Assets.Font as CAF
--import qualified Client.Assets.Generic as CAG
--import qualified Client.Assets.Sound as CAS
--import qualified Client.Assets.Util as CAU
--import qualified Client.Event as CEV
--import qualified Client.Frames as CTF
--import qualified Client.Types as CTY
--import qualified Client.Video.Sprite as CVS
--
--playBackgroundMusic :: MonadIO m => m ()
--playBackgroundMusic = do
-- let callback f p = putStrLn (FOR.format (FOR.fixed 0 FOR.% "%: loading " FOR.% FOR.stext) f p)
-- sl <- CAS.soundLoader
-- Right () <- runExceptT $ CAG.loadAssets_ sl CAU.soundAssets callback
-- (Right a) <- runExceptT $ CAG.getAsset sl (CAG.AssetID "click1")
-- SMI.playForever a
--
--loadFonts :: MonadIO m => CAF.FontLoaderType -> m ()
--loadFonts fl = do
-- let callback f p = putStrLn (FOR.format (FOR.fixed 0 FOR.% "%: loading " FOR.% FOR.stext) f p)
-- res <- runExceptT $ CAG.loadAssets fl (CAF.FontSize 24) CAU.fontAssets callback
-- case res of
-- Left e -> print e
-- Right () -> return ()
--
--initLoop :: CTY.Game()
--initLoop = do
-- sta <- get
-- let sl = CLE.view CTY.sprites sta
-- callback f p = putStrLn (FOR.format (FOR.fixed 0 FOR.% "%: loading " FOR.% FOR.stext) f p)
-- fl = CLE.view CTY.fonts sta
--
--
-- playBackgroundMusic
-- loadFonts fl
-- res <- runExceptT $ CAG.loadAssets_ sl CAU.pngAssets callback
-- case res of
-- Right () -> loop
-- Left e -> panic $ "Could not load assets: " <> e
--
--
--loop :: CTY.Game ()
--loop = do
-- CLZ.zoom (CTY.frameState . CTY.frameBegin) CTF.frameBegin
--
-- network
--
-- res <- ask
-- let window = CLE.view CTY.window res
--
-- SEV.mapEvents CEV.handleEvent
-- render
--
-- -- Update keyboard state
-- st <- get
-- let km = CTY._keymap $ CTY._game st
-- CLZ.zoom (CTY.game . CTY.controls) $
-- PIU.updateKeyboardState km
--
--
-- -- advanceGameState
--
-- CLZ.zoom CTY.frameState CTF.manageFps
--
-- sta <- get
-- let fpsC = CLE.view (CTY.frameState . CTY.fpsCounter) sta
-- fps = CTF.formatFps fpsC
-- SVI.windowTitle window SDL.$= ("PM " <> gitTag <> " (" <> fps <> ")")
-- whenM (fmap (CLE.view CTY.running) get) loop
--
--render :: CTY.Game ()
--render = do
-- res <- ask
-- sta <- get
-- let renderer = CLE.view CTY.renderer res
-- sl = CLE.view CTY.sprites sta
-- SVI.rendererDrawColor renderer SDL.$= SVE.V4 0 0 0 0
-- SVI.clear renderer
--
-- void $ runExceptT $ CVS.renderSprite renderer sl (CAG.AssetID "background.png") Nothing 0
-- CVS.noFlip
--
-- appState <- get
-- let pos = CLE.view (CTY.game . CTY.physicalObjects) appState
-- gos = CLE.view (CTY.game . CTY.gameObjects) appState
-- ngos = fmap (CVS.updateRenderInfo pos) gos
--
-- void $ runExceptT $ sequence_ (fmap (CVS.renderGameObject renderer
-- sl
-- (SDL.V2 640 480) -- TODO : fix
-- ) ngos)
--
-- -- Test rendering of font
-- let fl = CLE.view CTY.fonts sta
-- Right f <- runExceptT $ CAG.getAsset fl (CAG.AssetID "kenvector_future_thin:24")
-- sur <- SFO.blended f (SDL.V4 255 255 255 0) "Hello World"
-- t <- SDL.createTextureFromSurface renderer sur
-- SDL.copy renderer t Nothing (Just $ SDL.Rectangle (SDL.P $ SDL.V2 0 0) (SDL.V2 200 50))
--
--
-- SVI.present renderer
--
--
---- TODO: Move this in own module
--network :: CTY.Game ()
--network = do
-- sta <- get
-- let s = CTY._tbqueue $ CTY._netState $ CTY._game sta
-- bin <- liftIO $ CCS.atomically $ CCS.tryReadTBQueue s
-- case bin of
-- Just (PNT.Update objs) -> do
-- modify (CLE.set (CTY.game . CTY.physicalObjects) objs)
-- network
-- Just (PNT.Ping) -> network -- < TODO
-- Just (PNT.CreateGameObject (k, o, mp)) ->
-- let key = PTY.unKey k
-- in case mp of
-- Nothing -> do
-- modify (CLE.over (CTY.game . CTY.gameObjects) (DIS.insert key o))
-- network
-- Just p -> do
-- let mpk = fmap PTY.unKey (CLE.view PGT.mPhOb o)
-- case mpk of
-- Just pk -> do
-- modify (CLE.over (CTY.game . CTY.physicalObjects) (DIS.insert pk p))
-- modify (CLE.over (CTY.game . CTY.gameObjects) (DIS.insert key o))
-- network
-- Nothing -> network -- TODO: Log error. got physical object but no matching id
-- Nothing -> return ()
| r-raymond/purple-muon | src/Client/States/InGameState/Loop.hs | gpl-3.0 | 7,042 | 0 | 7 | 1,985 | 249 | 216 | 33 | -1 | -1 |
-- This file is part of KSQuant2.
-- Copyright (c) 2010 - 2011, Kilian Sprotte. All rights reserved.
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
module MeasureToLily (mToLily, vToLily)
where
import qualified Measure as M (Ms, M(M), E(L,R,D))
import qualified Lily as Ly (Dur(Dur)
, Pitch(Pitch)
, Name(B, C, D, E, F) -- A G
, Accidental(Natural, Sharp) -- Flat
, powerToSimpleDur
, Elt(Chord, Rest, Times)
, Measure(Measure)
, Measures)
import Data.Ratio (numerator, denominator)
import qualified Lisp as L ( LispVal(LispList,LispInteger) )
log2 :: (Num a, Integral a1) => a1 -> a
log2 1 = 0
log2 n | even n = 1 + log2 (div n 2)
log2 _ = error "log2"
midiToLily :: (Num a, Eq a, Show a) => a -> Ly.Pitch
midiToLily 59 = Ly.Pitch Ly.B Ly.Natural 3
midiToLily 60 = Ly.Pitch Ly.C Ly.Natural 4
midiToLily 61 = Ly.Pitch Ly.C Ly.Sharp 4
midiToLily 62 = Ly.Pitch Ly.D Ly.Natural 4
midiToLily 64 = Ly.Pitch Ly.E Ly.Natural 4
midiToLily 65 = Ly.Pitch Ly.F Ly.Natural 4
midiToLily x = error $ "midiToLily not implemented: " ++ show x
durToLily :: Rational -> Ly.Dur
durToLily d = Ly.Dur (base d) (dots d)
where dots d = case numerator d of
1 -> 0
3 -> 1
7 -> 2
15 -> 3
_ -> error "durToLily"
base d = Ly.powerToSimpleDur (log2 (denominator d) - dots d)
ensureListOfIntegers :: L.LispVal -> [Int]
ensureListOfIntegers (L.LispList xs) =
map ensureInt xs
where ensureInt (L.LispInteger x) = fromInteger x
ensureInt _ = error "ensureInt"
ensureListOfIntegers _ = error "ensureListOfIntegers"
eToLily :: M.E -> [Ly.Elt]
eToLily (M.L d tie _ notes _) = [Ly.Chord (durToLily d) midis tie]
where midis = map midiToLily (ensureListOfIntegers notes)
eToLily (M.R d _) = [Ly.Rest (durToLily d)]
eToLily (M.D _ r es) | r == 1 = concatMap eToLily es
| otherwise = let n' = fromInteger (numerator r)
d' = fromInteger (denominator r)
in [Ly.Times n' d' (concatMap eToLily es)]
mToLily :: M.M -> Ly.Measure
mToLily (M.M (n,d) _ e) = Ly.Measure (fromInteger n) (fromInteger d) (eToLily e)
vToLily :: M.Ms -> Ly.Measures
vToLily = map mToLily
| kisp/ksquant2 | MeasureToLily.hs | gpl-3.0 | 3,101 | 0 | 12 | 902 | 899 | 484 | 415 | 52 | 5 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
-- | A Norm is a generalisation of the notion of length or magnituge of a vector. The archetypal norm is just the length of a vector, though the absolute value of a number is more trivial example. Should be prefered over 'abs'. Also contains classes for inner products, aka dot product.
module MathPrelude.Classes.Norm
( Norm(..)
, InnerProd(..)
, ComplexInnerProd(..)
, abs
)
where
import MathPrelude.Prelude.CorePrelude
import MathPrelude.Prelude.NamedNumbers
import qualified Prelude as P
-- | The norm is the length of a object. If the object is a vector, the norm should commute with positive scaling and obey the triangle inequality.
class Norm v s | v → s where
norm ∷ v → s
-- | An inner product is a billinear operation, that is positive definite on the diagonal (iprod v v >= 0, with equality iff v ==0) and nondegenerate.
class InnerProd v s | v → s where
iprod ∷ v → v → s
-- | A complex inner product is much the same as an inner product, but is insead sequilinear, ie only conjugate linear in the second argument.
class ComplexInnerProd v s | v → s where
cxiprod ∷ v → v → s
-----------------------------------
--- Methods
-----------------------------------
-- | The absolute value is a special case of a norm.
abs ∷ Norm s s ⇒ s → s
abs = norm
-----------------------------------
--- Instances
-----------------------------------
instance Norm Int Int where
norm = P.abs
instance Norm Int32 Int32 where
norm = P.abs
instance Norm Int64 Int64 where
norm = P.abs
instance Norm Integer Integer where
norm = P.abs
instance Norm Float Float where
norm = P.abs
instance Norm Double Double where
norm = P.abs
| RossOgilvie/MathPrelude | MathPrelude/Classes/Norm.hs | gpl-3.0 | 1,884 | 0 | 8 | 383 | 277 | 163 | 114 | -1 | -1 |
{-# OPTIONS_HADDOCK ignore-exports #-}
module Fog_Display (
display,
initfn,
keyboardMouse
) where
import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT
import Data.IORef
data TriObject = TriObject {v1 :: Vertex3 GLfloat,
v2 :: Vertex3 GLfloat,
v3 :: Vertex3 GLfloat,
n1 :: Normal3 GLfloat,
n2 :: Normal3 GLfloat,
n3 :: Normal3 GLfloat
} deriving (Show)
triangleList = [TriObject {v1 = Vertex3 1.0 0.0 (0.0 :: GLfloat),
v2 = Vertex3 1.0 0.0 (5.0 :: GLfloat),
v3 = Vertex3 0.707107 0.707107 (0.0 :: GLfloat),
n1 = Normal3 1.0 0.0 (0.0 :: GLfloat),
n2 = Normal3 1.0 0.0 (0.0 :: GLfloat),
n3 = Normal3 0.707107 0.707107 (0.0 :: GLfloat)},
TriObject {v1 = Vertex3 0.707107 0.707107 (5.0 :: GLfloat),
v2 = Vertex3 0.0 1.0 (0.0 :: GLfloat),
v3 = Vertex3 0.0 1.0 (5.0 :: GLfloat),
n1 = Normal3 0.707107 0.707107 (0.0 :: GLfloat),
n2 = Normal3 0.0 1.0 (0.0 :: GLfloat),
n3 = Normal3 0.0 1.0 (0.0 :: GLfloat)},
TriObject {v1 = Vertex3 (-0.707107) 0.707107 (0.0 :: GLfloat),
v2 = Vertex3 (-0.707107) 0.707107 (5.0 :: GLfloat),
v3 = Vertex3 (-1.0) 0.0 (0.0 :: GLfloat),
n1 = Normal3 (-0.707107) 0.707107 (0.0 :: GLfloat),
n2 = Normal3 (-0.707107) 0.707107 (0.0 :: GLfloat),
n3 = Normal3 (-1.0) 0.0 (0.0 :: GLfloat)},
TriObject {v1 = Vertex3 (-1.0) 0.0 (5.0 :: GLfloat),
v2 = Vertex3 (-0.707107) (-0.707107) (0.0 :: GLfloat),
v3 = Vertex3 (-0.707107) (-0.707107) (5.0 :: GLfloat),
n1 = Normal3 (-1.0) 0.0 (0.0 :: GLfloat),
n2 = Normal3 (-0.707107) (-0.707107) (0.0 :: GLfloat),
n3 = Normal3 (-0.707107) (-0.707107) (0.0 :: GLfloat)},
TriObject {v1 = Vertex3 0.0 (-1.0) (0.0 :: GLfloat),
v2 = Vertex3 0.0 (-1.0) (5.0 :: GLfloat),
v3 = Vertex3 0.707107 (-0.707107) (0.0 :: GLfloat),
n1 = Normal3 0.0 (-1.0) (0.0 :: GLfloat),
n2 = Normal3 0.0 (-1.0) (0.0 :: GLfloat),
n3 = Normal3 0.707107 (-0.707107) (0.0 :: GLfloat)},
TriObject {v1 = Vertex3 0.707107 (-0.707107) (5.0 :: GLfloat),
v2 = Vertex3 1.0 0.0 (0.0 :: GLfloat),
v3 = Vertex3 1.0 0.0 (5.0 :: GLfloat),
n1 = Normal3 0.707107 (-0.707107) (0.0 :: GLfloat),
n2 = Normal3 1.0 0.0 (0.0 :: GLfloat),
n3 = Normal3 1.0 0.0 (0.0 :: GLfloat)}]
-- | Display callback.
display :: IORef (GLfloat) -- ^ Current rotation about the x-axis
-> IORef (GLfloat) -- ^ Current rotation about the y-axis
-> IO ()
display io_rotX io_rotY = do
clear [ColorBuffer, DepthBuffer]
rotY <- get io_rotY
rotX <- get io_rotX
preservingMatrix $ do
translate $ zTranslate
rotate rotY $ Vector3 0.0 1.0 0.0
rotate rotX $ Vector3 1.0 0.0 0.0
scale 1.0 1.0 (10.0::GLfloat)
callList cubeList
swapBuffers
flush
where
zTranslate = Vector3 0.0 0.0 (-65.0::GLfloat)
cubeList = DisplayList 1
-- | Keyboard and mouse callback.
-- Invoked when any keyboard or mouse button changes state (Up->Down or Down->Up)
keyboardMouse :: IORef (GLfloat) -- ^ Current rotation about the x-axis
-> IORef (GLfloat) -- ^ Current rotation about the y-axis
-> Key -- ^Key activated (LeftButton, MiddleButton, etc)
-> KeyState -- ^Up or Down
-> Modifiers -- ^Modifier keys (Ctrl, Alt, Shift, etc)
-> Position -- ^Position of the mouse on the screen
-> IO () -- ^IO monad to wrap
keyboardMouse _ _ (Char 'd') Down _ _ = do
(Exp currentFog) <- get fogMode
fogMode $= Exp (currentFog * 1.10)
postRedisplay Nothing
keyboardMouse _ _ (Char 'D') Down _ _ = do
(Exp currentFog) <- get fogMode
fogMode $= Exp (currentFog / 1.10)
postRedisplay Nothing
keyboardMouse io_rotX _ (SpecialKey KeyUp) Down _ _ = do
rotX <- get io_rotX
io_rotX $= rotX - 5.0
postRedisplay Nothing
keyboardMouse io_rotX _ (SpecialKey KeyDown) Down _ _ = do
rotX <- get io_rotX
io_rotX $= rotX + 5.0
postRedisplay Nothing
keyboardMouse _ io_rotY (SpecialKey KeyLeft) Down _ _ = do
rotY <- get io_rotY
io_rotY $= rotY - 5.0
postRedisplay Nothing
keyboardMouse _ io_rotY (SpecialKey KeyRight) Down _ _ = do
rotY <- get io_rotY
io_rotY $= rotY + 5.0
postRedisplay Nothing
keyboardMouse _ _ _ _ _ _ = return ()
-- | Initializes various things for the program.
initfn :: IO ()
initfn = do
frontFace $= CW
depthFunc $= Just Lequal
ambient light0 $= lightAmbient
diffuse light0 $= lightDiffuse
position light0 $= lightPosition
lightModelAmbient $= modelAmb
lightModelTwoSide $= Enabled
lighting $= Enabled
light light0 $= Enabled
materialShininess Front $= matShin_front
materialSpecular Front $= matSpec_front
materialDiffuse Front $= matDiff_front
materialShininess Back $= matShin_back
materialSpecular Back $= matSpec_back
materialDiffuse Back $= matDiff_back
fog $= Enabled
fogMode $= Exp fogDensity
fogColor $= fog_color
clearColor $= Color4 0.8 0.8 0.8 1.0
defineList cubeList Compile $ renderTube
matrixMode $= Projection
perspective 45.0 1.0 1.0 200.0
matrixMode $= Modelview 0
where
light0 = Light 0
lightAmbient = Color4 0.1 0.1 0.1 1.0
lightDiffuse = Color4 1.0 1.0 1.0 1.0
lightPosition = Vertex4 90.0 90.0 0.0 0.0
modelAmb = Color4 0.0 0.0 0.0 1.0
matShin_front = 30.0
matSpec_front = Color4 0.0 0.0 0.0 1.0
matDiff_front = Color4 0.0 1.0 0.0 1.0
matShin_back = 50.0
matSpec_back = Color4 0.0 0.0 1.0 1.0
matDiff_back = Color4 1.0 0.0 0.0 1.0
fogDensity = 0.02
fog_color = Color4 0.8 0.8 0.8 1.0
cubeList = DisplayList 1
renderTube = renderPrimitive TriangleStrip $ mapM_ renderSection triangleList
renderSection triangleObject = do
normal $ n1 triangleObject
vertex $ v1 triangleObject
normal $ n2 triangleObject
vertex $ v2 triangleObject
normal $ n3 triangleObject
vertex $ v3 triangleObject
| rmcmaho/Haskell_OpenGL_Examples | Fog/Fog_Display.hs | gpl-3.0 | 6,852 | 0 | 12 | 2,373 | 2,010 | 1,044 | 966 | 147 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DFAReporting.SubAccounts.Patch
-- 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 an existing subaccount. This method supports patch semantics.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.subaccounts.patch@.
module Network.Google.Resource.DFAReporting.SubAccounts.Patch
(
-- * REST Resource
SubAccountsPatchResource
-- * Creating a Request
, subAccountsPatch
, SubAccountsPatch
-- * Request Lenses
, sapProFileId
, sapPayload
, sapId
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.subaccounts.patch@ method which the
-- 'SubAccountsPatch' request conforms to.
type SubAccountsPatchResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"subaccounts" :>
QueryParam "id" (Textual Int64) :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] SubAccount :>
Patch '[JSON] SubAccount
-- | Updates an existing subaccount. This method supports patch semantics.
--
-- /See:/ 'subAccountsPatch' smart constructor.
data SubAccountsPatch = SubAccountsPatch'
{ _sapProFileId :: !(Textual Int64)
, _sapPayload :: !SubAccount
, _sapId :: !(Textual Int64)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'SubAccountsPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sapProFileId'
--
-- * 'sapPayload'
--
-- * 'sapId'
subAccountsPatch
:: Int64 -- ^ 'sapProFileId'
-> SubAccount -- ^ 'sapPayload'
-> Int64 -- ^ 'sapId'
-> SubAccountsPatch
subAccountsPatch pSapProFileId_ pSapPayload_ pSapId_ =
SubAccountsPatch'
{ _sapProFileId = _Coerce # pSapProFileId_
, _sapPayload = pSapPayload_
, _sapId = _Coerce # pSapId_
}
-- | User profile ID associated with this request.
sapProFileId :: Lens' SubAccountsPatch Int64
sapProFileId
= lens _sapProFileId (\ s a -> s{_sapProFileId = a})
. _Coerce
-- | Multipart request metadata.
sapPayload :: Lens' SubAccountsPatch SubAccount
sapPayload
= lens _sapPayload (\ s a -> s{_sapPayload = a})
-- | Subaccount ID.
sapId :: Lens' SubAccountsPatch Int64
sapId
= lens _sapId (\ s a -> s{_sapId = a}) . _Coerce
instance GoogleRequest SubAccountsPatch where
type Rs SubAccountsPatch = SubAccount
type Scopes SubAccountsPatch =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient SubAccountsPatch'{..}
= go _sapProFileId (Just _sapId) (Just AltJSON)
_sapPayload
dFAReportingService
where go
= buildClient
(Proxy :: Proxy SubAccountsPatchResource)
mempty
| rueshyna/gogol | gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/SubAccounts/Patch.hs | mpl-2.0 | 3,704 | 0 | 15 | 881 | 507 | 298 | 209 | 75 | 1 |
{-# OPTIONS -cpp -fglasgow-exts #-}
module Poly where
import Data.Typeable
data Fn = Fn {fn :: forall t. Eq t => t -> t -> Bool}
--
-- ignore type inside the Fn... is this correct?
--
instance Typeable Fn where
#if __GLASGOW_HASKELL__ >= 603
typeOf _ = mkTyConApp (mkTyCon "Poly.Fn") []
#else
typeOf _ = mkAppTy (mkTyCon "Poly.Fn") []
#endif
| stepcut/plugins | testsuite/eval/eval_fn1/Poly.hs | lgpl-2.1 | 354 | 0 | 12 | 73 | 80 | 46 | 34 | -1 | -1 |
module Git.Command.IndexPack (run) where
run :: [String] -> IO ()
run args = return () | wereHamster/yag | Git/Command/IndexPack.hs | unlicense | 87 | 0 | 7 | 15 | 42 | 23 | 19 | 3 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
module Bantam.Service.Api.Fight (
Fight (..)
, MatchesError (..)
, currentLemma
) where
import Bantam.Service.Data
import Bantam.Service.Data.Fight
import P
import X.Control.Monad.Trans.Either (EitherT, runEitherT)
data MatchesError =
MatchesParseError Text
deriving (Eq, Show)
data Fight m =
Fight {
currentFight :: m (Maybe FightId)
, fightLemmas :: FightId -> m [LemmaId]
, userLemmas :: FightId -> Email -> m [LemmaId]
, getLemma :: FightId -> LemmaId -> m (Maybe Lemma)
, createLemma :: FightId -> Lemma -> m LemmaId
, updateLemma :: FightId -> LemmaId -> Lemma -> m ()
, allowUserLemma :: FightId -> Email -> LemmaId -> m ()
, hasUserLemma :: FightId -> Email -> LemmaId -> m Bool
, inboxLemmas :: FightId -> Email -> m [LemmaId]
, hasInboxLemma :: FightId -> Email -> LemmaId -> m Bool
, approveLemma :: FightId -> LemmaId -> Email -> Review -> m ()
, getMatches :: FightId -> EitherT MatchesError m Matches
}
currentLemma :: Functor m => Fight m -> FightId -> m (Maybe LemmaId)
currentLemma f =
-- FIX We shouldn't throw away the error here, but this is to make the API backwards compatible for now
fmap (either (\_ -> Nothing) matchesCurrentLemma) . runEitherT . getMatches f
| charleso/bantam | bantam-service/src/Bantam/Service/Api/Fight.hs | unlicense | 1,343 | 0 | 14 | 326 | 404 | 223 | 181 | 29 | 1 |
{-# OPTIONS_GHC -Wall #-}
module LogAnalysis where
import Log
-- parseMessage "E 2 562 help help" == LogMessage (Error 2) 562 "help help"
-- parseMessage "I 29 la la la" == LogMessage Info 29 "la la la"
-- parseMessage "This is not in the right format" == Unknown "This is not in the right format"
parseMessage :: String -> LogMessage
parseMessage x =
let elems = drop 1 $ words x
in case x of
('E':' ':_) -> LogMessage
(Error $ read $ head elems)
(read $ elems !! 1)
(unwords $ drop 2 elems)
('W':' ':_) -> LogMessage
Warning
(read $ head elems)
(unwords $ drop 1 elems)
('I':' ':_) -> LogMessage
Info
(read $ head elems)
(unwords $ drop 1 elems)
_ -> Unknown x
-- testParse parse 10 "error.log"
parse :: String -> [LogMessage]
parse = map parseMessage . lines
insert :: LogMessage -> MessageTree -> MessageTree
insert (Unknown _) tree = tree
insert _ tree@(Node _ (Unknown _) _) = tree
insert m Leaf = Node Leaf m Leaf
insert m@(LogMessage _ t _) (Node l n@(LogMessage _ nt _) r)
| t < nt = Node (insert m l) n r
| otherwise = Node l n (insert m r)
build :: [LogMessage] -> MessageTree
build = foldr insert Leaf
inOrder :: MessageTree -> [LogMessage]
inOrder Leaf = []
inOrder (Node l m r) = inOrder l ++ [m] ++ inOrder r
isErrorSeverity50 :: LogMessage -> Bool
isErrorSeverity50 (LogMessage (Error s) _ _) = s >= 50
isErrorSeverity50 _ = False
getMessage :: LogMessage -> String
getMessage (LogMessage _ _ m) = m
getMessage (Unknown m) = m
-- testWhatWentWrong parse whatWentWrong "sample.log"
whatWentWrong :: [LogMessage] -> [String]
whatWentWrong = map getMessage . inOrder . build . filter isErrorSeverity50
| beloglazov/haskell-course | hw2.hs | apache-2.0 | 1,831 | 0 | 13 | 510 | 614 | 314 | 300 | 42 | 4 |
{-
Copyright 2019 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module CodeWorld.Requirements.RequirementsChecker (plugin) where
import CodeWorld.Requirements.Framework
import CodeWorld.Requirements.Requirements
import qualified Data.ByteString as B
import Data.Text.Encoding
import ErrUtils
import HscTypes
import Outputable
import Plugins
import TcRnMonad
plugin :: Plugin
plugin = defaultPlugin {
renamedResultAction = keepRenamedSource,
typeCheckResultAction = \_args -> requirementsChecker
}
requirementsChecker :: ModSummary -> TcGblEnv -> TcM TcGblEnv
requirementsChecker summary env = do
src <- liftIO (B.readFile $ ms_hspp_file summary)
let flags = ms_hspp_opts summary
parsed = ghcParseCode flags [] $ decodeUtf8 src
case parsed of
GHCParsed code -> do
lcl <- getLclEnv
errs <- readTcRef $ tcl_errs lcl
let req = checkRequirements flags errs env code src
case req of
Nothing -> return ()
Just r -> liftIO (putMsg flags $ text r)
GHCNoParse -> return ()
pure env | alphalambda/codeworld | codeworld-requirements/src/CodeWorld/Requirements/RequirementsChecker.hs | apache-2.0 | 1,779 | 0 | 18 | 497 | 279 | 143 | 136 | 29 | 3 |
{-# LANGUAGE OverloadedStrings #-}
-- |Initialize a ROS Package with roshask support.
module PkgInit (initPkg) where
import Data.ByteString.Char8 (ByteString, pack)
import qualified Data.ByteString.Char8 as B
import Data.Char (toLower, toUpper)
import Data.List (intercalate)
import Data.Version (versionBranch)
import System.Directory (createDirectory)
import System.FilePath ((</>))
import System.Process (system)
import Paths_roshask (version)
import PkgBuilder (rosPkg2CabalPkg)
-- |Initialize a package with the given name in the eponymous
-- directory with the given ROS package dependencies.
initPkg :: String -> [String] -> IO ()
initPkg pkgName deps = do _ <- system pkgCmd
prepCMakeLists pkgName
prepCabal pkgName msgDeps
prepSetup pkgName
createDirectory (pkgName</>"src")
prepMain pkgName
prepLib pkgName
putStrLn (fyi pkgName)
where pkgCmd = intercalate " " ("roscreate-pkg":pkgName:deps)
msgDeps = B.intercalate ",\n" $ map (addSpaces . mkDep) deps
addSpaces = B.append $ B.replicate 19 ' '
mkDep = pack . rosPkg2CabalPkg
fyi :: String -> String
fyi pkgName = "Created an empty roshask package.\n" ++
"Please edit "++
show (pkgName</>pkgName++".cabal") ++
" to specify what should be built."
-- Add an entry to the package's CMakeLists.txt file to invoke
-- roshask.
prepCMakeLists :: String -> IO ()
prepCMakeLists pkgName = B.appendFile (pkgName</>"CMakeLists.txt") cmd
where cmd = "\nadd_custom_target(roshask ALL roshask dep ${PROJECT_SOURCE_DIR} COMMAND cd ${PROJECT_SOURCE_DIR} && cabal install)\n"
-- | New packages are constrained to the same major version of roshask
-- that was used to create them.
roshaskVersionBound :: ByteString
roshaskVersionBound = B.pack . ("roshask == "++)
. intercalate "."
. (++["*"])
. map show
$ take 2 (versionBranch version ++ [0..])
-- Generate a .cabal file and a Setup.hs that will perform the
-- necessary dependency tracking and code generation.
prepCabal :: String -> ByteString -> IO ()
prepCabal pkgName rosDeps = B.writeFile (pkgName</>(pkgName++".cabal")) $
B.concat [preamble,"\n",target,"\n\n",lib,"\n"]
where preamble = format [ ("Name", B.append "ROS-" $ B.pack pkgName)
, ("Version","0.0")
, ("Synopsis","I am code")
, ("Cabal-version",">=1.6")
, ("Category","Robotics")
, ("Build-type","Custom") ]
target = B.intercalate "\n" $
[ B.concat ["Executable ", pack pkgName]
, " Build-Depends: base >= 4.2 && < 6,"
, " vector > 0.7,"
, " time >= 1.1,"
, " ROS-rosgraph-msgs,"
, B.append " roshask == 0.2.*" moreDeps
, rosDeps
, " GHC-Options: -O2"
, " Hs-Source-Dirs: src"
, " Main-Is: Main.hs"
, B.append " Other-Modules: " pkgName' ]
lib = B.intercalate "\n" $
[ "Library"
, " Build-Depends: base >= 4.2 && < 6,"
, " vector > 0.7,"
, " time >= 1.1,"
, B.concat [
" ", roshaskVersionBound, moreDeps ]
, rosDeps
, " GHC-Options: -O2"
, B.concat [" Exposed-Modules: ", pkgName']
, " Hs-Source-Dirs: src" ]
pkgName' = pack $ toUpper (head pkgName) : tail pkgName
moreDeps = if B.null rosDeps then "" else ","
-- Format key-value pairs for a .cabal file
format :: [(ByteString,ByteString)] -> ByteString
format fields = B.concat $ map indent fields
where indent (k,v) = let spaces = flip B.replicate ' ' $
19 - B.length k - 1
in B.concat [k,":",spaces,v,"\n"]
-- Generate a Setup.hs file for use by Cabal.
prepSetup :: String -> IO ()
prepSetup pkgName = B.writeFile (pkgName</>"Setup.hs") $
B.concat [ "import Distribution.Simple\n"
, "import Ros.Internal.SetupUtil\n\n"
, "main = defaultMainWithHooks $\n"
, " simpleUserHooks { confHook = "
, "rosConf }\n" ]
prepMain :: String -> IO ()
prepMain pkgName = writeFile (pkgName</>"src"</>"Main.hs") $
"module Main (main) where\n\
\import Ros.Node\n\
\import "++pkgName'++"\n\
\\n\
\main = runNode \""++pkgName++"\" "++nodeName++"\n"
where pkgName' = toUpper (head pkgName) : tail pkgName
nodeName = toLower (head pkgName) : tail pkgName
prepLib :: String -> IO ()
prepLib pkgName = writeFile (pkgName</>"src"</>pkgName'++".hs") . concat $
[ "module "++pkgName'++" ("++nodeName++") where\n"
, "import Ros.Node\n\n"
, nodeName++" :: Node ()\n"
, nodeName++" = return ()\n"]
where pkgName' = toUpper (head pkgName) : tail pkgName
nodeName = toLower (head pkgName) : tail pkgName
| rgleichman/roshask | src/executable/PkgInit.hs | bsd-3-clause | 5,692 | 0 | 15 | 2,117 | 1,190 | 641 | 549 | 100 | 2 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-missing-import-lists #-}
{-# OPTIONS_GHC -fno-warn-implicit-prelude #-}
module Paths_AuthServer (
version,
getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
#if defined(VERSION_base)
#if MIN_VERSION_base(4,0,0)
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#else
catchIO :: IO a -> (Exception.Exception -> IO a) -> IO a
#endif
#else
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#endif
catchIO = Exception.catch
version :: Version
version = Version [0,1,0,0] []
bindir, libdir, dynlibdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/home/ggunn/DFS/AuthServer/.stack-work/install/x86_64-linux/lts-7.13/8.0.1/bin"
libdir = "/home/ggunn/DFS/AuthServer/.stack-work/install/x86_64-linux/lts-7.13/8.0.1/lib/x86_64-linux-ghc-8.0.1/AuthServer-0.1.0.0-HUsbF5losB5ICY0RhRwEou"
dynlibdir = "/home/ggunn/DFS/AuthServer/.stack-work/install/x86_64-linux/lts-7.13/8.0.1/lib/x86_64-linux-ghc-8.0.1"
datadir = "/home/ggunn/DFS/AuthServer/.stack-work/install/x86_64-linux/lts-7.13/8.0.1/share/x86_64-linux-ghc-8.0.1/AuthServer-0.1.0.0"
libexecdir = "/home/ggunn/DFS/AuthServer/.stack-work/install/x86_64-linux/lts-7.13/8.0.1/libexec"
sysconfdir = "/home/ggunn/DFS/AuthServer/.stack-work/install/x86_64-linux/lts-7.13/8.0.1/etc"
getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "AuthServer_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "AuthServer_libdir") (\_ -> return libdir)
getDynLibDir = catchIO (getEnv "AuthServer_dynlibdir") (\_ -> return dynlibdir)
getDataDir = catchIO (getEnv "AuthServer_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "AuthServer_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "AuthServer_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| Garygunn94/DFS | AuthServer/.stack-work/dist/x86_64-linux/Cabal-1.24.2.0/build/autogen/Paths_AuthServer.hs | bsd-3-clause | 2,185 | 0 | 10 | 239 | 410 | 238 | 172 | 33 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.NV.LightMaxExponent
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- All raw functions and tokens from the NV_light_max_exponent extension not
-- already in the OpenGL 3.1 core, see
-- <http://www.opengl.org/registry/specs/NV/light_max_exponent.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.NV.LightMaxExponent (
-- * Tokens
gl_MAX_SHININESS,
gl_MAX_SPOT_EXPONENT
) where
import Graphics.Rendering.OpenGL.Raw.Core32
gl_MAX_SHININESS :: GLenum
gl_MAX_SHININESS = 0x8504
gl_MAX_SPOT_EXPONENT :: GLenum
gl_MAX_SPOT_EXPONENT = 0x8505
| mfpi/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/NV/LightMaxExponent.hs | bsd-3-clause | 882 | 0 | 4 | 114 | 62 | 47 | 15 | 8 | 1 |
{-# LANGUAGE OverloadedStrings, DeriveGeneric, FlexibleInstances, RecordWildCards #-}
{- FIXME: fuck man.. this should be mkQueue'Deq not mkQueue.. having problems compiling, cabal dependency hell wreckage -}
import System.Environment
import ZTail
import Abstract.Wrapper
import Abstract.Queue
import Abstract.Interfaces.Queue
import Control.Monad
import Control.Concurrent
import Control.Concurrent.Async
import Data.Aeson
import Data.Maybe
import Data.Int
import System.Directory
import System.FilePath.Posix
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Lazy.Char8 as BSLC
import qualified Data.ByteString.Char8 as BSC
import qualified System.Metrics.Distribution as Distribution
import qualified System.Metrics.Counter as Counter
import qualified System.Metrics.Gauge as Gauge
import qualified System.Metrics.Label as Label
import qualified System.Remote.Monitoring as Monitoring
import qualified System.Remote.Monitoring.Statsd as Statsd
import ZTail.Tools.EKG
data Dump = Dump {
_dir :: String,
_all :: String
} deriving (Show, Read)
instance FromJSON (HostDataWrapper TailPacket)
instance ToJSON (HostDataWrapper TailPacket)
port = 60001
usage = "usage: ./ztail-dump <dir> [<queue-url://>,..]"
tp'pack v = lazyToStrict $ encode v
tp'unpack v = fromJust $ (decode (strictToLazy v) :: Maybe (HostDataWrapper TailPacket))
strictToLazy v = BSL.fromChunks [v]
lazyToStrict v = BS.concat $ BSL.toChunks v
encode'bsc v = lazyToStrict $ encode v
pack' :: HostDataWrapper TailPacket -> BS.ByteString
pack' tp = lazyToStrict $ encode $ tp
unpack' :: BS.ByteString -> HostDataWrapper TailPacket
unpack' v = fromJust $ decode' $ strictToLazy v
dump'Queues EKG{..} Dump{..} rq = do
forever $ do
tp <- blDequeue rq
case tp of
(Just tp') -> do
let d' = (d tp')
let buf' = (buf d' ++ "\n")
let logpath = (_dir ++ "/" ++ (h tp') ++ "/" ++ (path d'))
let basename = takeDirectory logpath
let len = length (buf d')
createDirectoryIfMissing True basename
appendFile logpath buf'
Counter.inc _logCounter
Gauge.add _lengthGauge (fromIntegral len :: Int64)
Distribution.add _logDistribution (fromIntegral len :: Double)
return ()
Nothing -> do
Counter.inc _dequeueErrorCounter
threadDelay 1000000
main :: IO ()
main = do
ekg'bootstrap port main'
main' :: EKG -> IO ()
main' ekg = do
argv <- getArgs
case argv of
(dir:urls:[]) -> dumper ekg dir (read urls :: [String]) >> return ()
_ -> error usage
dumper ekg dir urls = do
rqs <- mapM (\url -> mkQueue url pack' unpack') urls
let dump = Dump { _dir = dir, _all = dir ++ "/all.log" }
threads <- mapM (\rq -> async $ dump'Queues ekg dump rq) rqs
waitAnyCancel threads
| adarqui/Ztail-Tools | tools/ztail-dump.hs | bsd-3-clause | 2,996 | 8 | 24 | 699 | 897 | 457 | 440 | 75 | 2 |
module Main where
import DockerCompose
import DockerComposeSpec
import Test.Hspec
main :: IO ()
main = mapM_ hspec [ dockerComposeSpec ]
| amarpotghan/docker-compose-dsl | test/Spec.hs | bsd-3-clause | 169 | 0 | 6 | 52 | 38 | 22 | 16 | 6 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Web.RTBBidder.Types.Request.Deal (Deal(..)) where
import qualified Data.Aeson as AESON
import Data.Aeson ((.=), (.:), (.:?), (.!=))
import qualified Data.Text as TX
data Deal = Deal
{ dealId :: TX.Text
, dealBidfloor :: Double
, dealBidfloorcur :: TX.Text
, dealAt :: Maybe Int
, dealWseat :: [TX.Text]
, dealWadomain :: [TX.Text]
, dealExt :: Maybe AESON.Value
} deriving (Show, Eq)
instance AESON.FromJSON Deal where
parseJSON = AESON.withObject "deal" $ \o -> do
dealId <- o .: "id"
dealBidfloor <- o .:? "bidfloor" .!= 0.0
dealBidfloorcur <- o .:? "bidfloorcur" .!= "USD"
dealAt <- o .:? "at"
dealWseat <- o .:? "wseat" .!= []
dealWadomain <- o .:? "wadomain" .!= []
dealExt <- o .:? "ext"
return Deal{..}
instance AESON.ToJSON Deal where
toJSON Deal{..} = AESON.object
[ "id" .= dealId
, "bidfloor" .= dealBidfloor
, "bidfloorcur" .= dealBidfloorcur
, "at" .= dealAt
, "wseat" .= dealWseat
, "wadomain" .= dealWadomain
, "ext" .= dealExt
]
| hiratara/hs-rtb-bidder | src/Web/RTBBidder/Types/Request/Deal.hs | bsd-3-clause | 1,109 | 0 | 12 | 249 | 362 | 204 | 158 | 34 | 0 |
{- |
API for finite state automatons
-}
module FST.AutomatonInterface (
module FST.RegTypes,
module FST.AutomatonTypes,
-- * Types
Automaton,
-- * Construction of automatons
compile,
compileNFA,
-- * Transformation of automatons
determinize,
minimize,
complete,
-- * Query inforation about automatons
initial,
numberOfStates,
numberOfTransitions,
showAutomaton,
) where
import FST.Automaton
import FST.AutomatonTypes
import FST.Complete
import qualified FST.Deterministic as D
import qualified FST.LBFA as L
import FST.RegTypes hiding (reversal)
import FST.Reversal (reversal)
-- | Compile a non-deterministic finite-state automaton
compileNFA :: Ord a => Reg a -> Sigma a -> StateTy -> Automaton a
compileNFA = L.compileToAutomaton
-- | Minimize an automaton using the Brzozowski algorithm. Note that
-- the determinize function must construct an automaton with the
-- usefulS property.
minimize :: Ord a => Automaton a -> Automaton a
minimize = determinize . reversal . determinize . reversal
{-# SPECIALIZE minimize :: Automaton String -> Automaton String #-}
-- | Make a non-deterministic finite-state automaton deterministic
determinize :: Ord a => Automaton a -> Automaton a
determinize = D.determinize
-- | Compile a minimized non-deterministic finite-state automaton
compile :: Ord a => Reg a -> Sigma a -> StateTy -> Automaton a
compile reg sigma s = minimize $ L.compileToAutomaton reg sigma s
-- | Get the initial state of a finite-state automaton
initial :: Automaton a -> StateTy
initial automaton = head $ initials automaton
-- | Count the number of states in a finite-state automaton
numberOfStates :: Ord a => Automaton a -> Int
numberOfStates auto = length $ states auto
-- | Count the number of transitions in a finite-state automaton
numberOfTransitions :: Ord a => Automaton a -> Int
numberOfTransitions auto = sum [length (transitionList auto s)
| s <- states auto]
| johnjcamilleri/fst | FST/AutomatonInterface.hs | bsd-3-clause | 1,974 | 0 | 9 | 372 | 400 | 217 | 183 | 36 | 1 |
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}
module Data.Text.Phonetical where
import Data.Text.Phonetical.Internal
import Data.Attoparsec.Text
import qualified Data.List as L
import Data.Text
import Control.Applicative
phonetic :: Dictionary -> Text -> Text
phonetic dict istr = case (parseOnly (parseAllInDictionary dict) istr) of
Left s -> pack s
Right t -> t
parseAllInDictionary :: Dictionary -> Parser Text
parseAllInDictionary dict = do
plist <- many (mkReplacementParser dict)
rest <- takeText
return $ append (Data.Text.concat plist) rest
mkReplacementParser :: Dictionary -> Parser Text
mkReplacementParser dict = do
(e,nmatchCharLst) <- anyTillAlt
return (append (pack nmatchCharLst) e)
return (append (pack nmatchCharLst) e)
where
anyTillAlt = manyTillWith anyChar altParser
altParser = choice (mkParserList dict)
manyTillWith :: Parser a -> Parser b -> Parser (b,[a])
manyTillWith p end = scn
where
scn = do
ep <- eitherP end p
case ep of
Left e -> return (e,[])
Right c -> do
(e,l) <- scn
return (e,c:l)
mkParserList :: Dictionary -> [Parser Text]
mkParserList dict = L.foldl' parseBuild [] dict
where
parseBuild l (Find (Simple sym) txt ) = (replaceSimple sym txt):l
parseBuild l (Find (Wrapped (Symbol iSym) (Symbol fSym)) txt ) = (replaceWrapped iSym fSym txt):l
replaceSimple sym txt = (string . getSymbol $ sym) *> (pure txt)
replaceWrapped isym fsym t = do
_ <- string isym
(e,cList) <- manyTillWith anyChar (string fsym)
return (append t (pack cList))
| smurphy8/phonetical | src/Data/Text/Phonetical.hs | bsd-3-clause | 1,633 | 0 | 16 | 374 | 610 | 306 | 304 | 41 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
module Control.Funky.Run where
import Data.Default (Default, def)
import qualified Data.Vector as V
import Control.Funky.Type
{-|
evaluate the executable machine into vector of results.
-}
run :: forall a. Default a => Machine (Thunk a) -> Machine a
run (Machine insts) = Machine ret
where
ret :: V.Vector a
ret = V.imap compute insts
compute :: Int -> Thunk a -> a
compute idx inst = case inst of
Thunk f idxs -> f `tap` fmap get idxs
get :: Int -> a
get addr = maybe def id (ret V.!? addr)
| nushio3/funky | Control/Funky/Run.hs | bsd-3-clause | 591 | 0 | 11 | 157 | 195 | 104 | 91 | 14 | 1 |
module Klesi (
Minde(..),
Text(..), Selbri(..), Tag(..), Sumti(..), Mex(..), RelativeClause(..)
) where
import Language.Lojban.Parser(Free(..))
--------------------------------------------------------------------------------
data Minde
= KLAMA Double Double
| CRAKLA Double | RIXYKLA Double
| ZUNLE Double | PRITU Double
| XRUKLALOKRASI
| COhACLUGAU | COhUCLUGAU
| PEBYCISNI Double | PEBYSKA Int Int Int
| BURSKA Int Int Int | FLOSKA Int Int Int
| NAPILNOLOPENBI | PILNOLOPENBI
| NAVISKA | VISKA
| CISNI Double | CISNYGAUFOLDI Double Double
| XRUTI
| VIMCULOPIXRA
| MORJI String ([Sumti] -> Minde) | GASNU String [Sumti]
| REJGAUSETAIJBO FilePath | TCIDUSETAIJBO FilePath
| REJGAUSETAICAK FilePath | TCIDU FilePath
| REJGAUSETAISVG FilePath
| COhO
| MIDYSTE [Minde]
| SRERA String
data Text
= Bridi Selbri [(Tag, Sumti)]
| Prenex [Sumti] Text
| TagGI String Text Text
| Vocative String
| Free [Free]
| MultiText [Text]
| FAhO
| UnknownText String
| ParseError String
deriving (Show, Eq)
data Selbri
= Brivla String
| NA Selbri
| SE Int Selbri
| BE Selbri Sumti
| ME Sumti
| NU Text
| DUhU Text
| UnknownSelbri String
deriving (Show, Eq)
data Tag
= FA Int
| BAI Int String
| FIhO Selbri
| Time [String]
| UnknownTag String
deriving (Show, Eq)
data Sumti
= KU
| CEhUPre
| CEhU Int
| KOhA String
| LA (Either String Selbri)
| LE Selbri
| LO Selbri (Maybe RelativeClause)
| LI Mex
| LerfuString String
| ZOI String
| TUhA Sumti
| LAhE Sumti
| GOI Sumti Sumti
| Relative Sumti RelativeClause
| STense String Sumti Sumti
| SFIhO Selbri Sumti
| UnknownSumti String
deriving (Show, Eq)
data Mex
= Number Double
| JOhI [Mex]
| UnknownMex String
deriving (Show, Eq)
data RelativeClause
= POI Text
| UnknownRelativeClause String
deriving (Show, Eq)
| YoshikuniJujo/cakyrespa | src/Klesi.hs | bsd-3-clause | 1,841 | 30 | 9 | 388 | 639 | 380 | 259 | 80 | 0 |
module Network.Probecraft.Packet.Arp (
Arp (..)
, arpSize
, MACAddress
, HardwareType (..)
, ProtoType (..)
, OpCode (..)
, blankArp
) where
import qualified Data.ByteString as B
import Data.Binary
import Data.Binary.Put
import Data.Binary.Get
import Control.Monad
import Network.Probecraft.Utils
type MACAddress = B.ByteString
data HardwareType = EthernetHw | UnknownHarwareType Word16 deriving (Show,Eq)
data ProtoType = IPv4Proto | UnknownProtoType Word16 deriving (Show,Eq)
data OpCode = Request | Reply | UnknownOpCode Word16 deriving (Show,Eq)
data Arp = Arp {
arpHwType :: HardwareType,
arpProtoType :: ProtoType,
arpHwSize :: Int,
arpProtoSize :: Int,
arpOpCode :: OpCode,
arpSrcHw :: MACAddress,
arpSrcProto :: B.ByteString,
arpTgtHw :: MACAddress,
arpTgtProto :: B.ByteString
} deriving (Show)
blankArp = Arp noType noProto 6 4 noCode noAddrHw noAddrProto noAddrHw noAddrProto
where noType = UnknownHarwareType 0
noProto = UnknownProtoType 0
noCode = UnknownOpCode 0
noAddrHw = unhexify "00:00:00:00:00:00"
noAddrProto = undecimalify "0.0.0.0"
arpSize :: Arp -> Int
arpSize arp = 8 + 2*(arpHwSize arp + arpProtoSize arp)
instance Binary Arp where
get = do
hwType <- getWord16be
protoType <- getWord16be
hwSize <- getWord8 >>= return . fromIntegral
protoSize <- getWord8 >>= return . fromIntegral
opCode <- getWord16be
srcHw <- getByteString hwSize
srcProto <- getByteString protoSize
tgtHw <- getByteString hwSize
tgtProto <- getByteString protoSize
return $ Arp (parseHardwareType hwType) (parseProtoType protoType) hwSize protoSize
(parseOpCode opCode)
srcHw srcProto tgtHw tgtProto
put arp = do
putWord16be $ unparseHardwareType $ arpHwType arp
putWord16be $ unparseProtoType $ arpProtoType arp
putWord8 $ fromIntegral $ arpHwSize arp
putWord8 $ fromIntegral $ arpProtoSize arp
putWord16be $ unparseOpCode $ arpOpCode arp
putByteString $ arpSrcHw arp
putByteString $ arpSrcProto arp
putByteString $ arpTgtHw arp
putByteString $ arpTgtProto arp
parseHardwareType :: Word16 -> HardwareType
parseHardwareType 1 = EthernetHw
parseHardwareType x = UnknownHarwareType x
unparseHardwareType :: HardwareType -> Word16
unparseHardwareType EthernetHw = 1
unparseHardwareType (UnknownHarwareType x) = x
parseProtoType :: Word16 -> ProtoType
parseProtoType 0x800 = IPv4Proto
parseProtoType x = UnknownProtoType x
unparseProtoType :: ProtoType -> Word16
unparseProtoType IPv4Proto = 0x800
unparseProtoType (UnknownProtoType x) = x
parseOpCode :: Word16 -> OpCode
parseOpCode 1 = Request
parseOpCode 2 = Reply
parseOpCode x = UnknownOpCode x
unparseOpCode :: OpCode -> Word16
unparseOpCode Request = 1
unparseOpCode Reply = 2
unparseOpCode (UnknownOpCode x) = x
| lucasdicioccio/probecraft-hs | Network/Probecraft/Packet/Arp.hs | bsd-3-clause | 3,122 | 0 | 11 | 817 | 800 | 417 | 383 | 81 | 1 |
{-# LANGUAGE NoMonomorphismRestriction #-}
module Mandelbrot where
import Diagrams.Prelude hiding (magnitude)
import Diagrams.Backend.PGF
import qualified Diagrams.Backend.PGFSystem as Sys
pgfM d = pgfR "latex.pdf" latexSurface d
>> pgfR "plain.pdf" plaintexSurface d
>> pgfR "context.pdf" contextSurface d
sysM d = sysR "latex.pdf" Sys.latexSurface d
>> sysR "plain.pdf" Sys.plaintexSurface d
>> sysR "context.pdf" Sys.contextSurface d
pgfR n = renderPDF' ("example/pgf/" ++ n) (Width 400)
sysR n = Sys.renderPDF' ("example/system/" ++ n) (Width 300)
test :: Diagram PGF R2
test = rect 12 8 <> text "\\~^[]£"
sqCirle = hbox "hi"
<> square 3 <> circle 1 # fc orange # lwN 0.02
| cchalmers/pgf-system | examples/Mandelbrot.hs | bsd-3-clause | 728 | 0 | 9 | 149 | 228 | 115 | 113 | 17 | 1 |
----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Logging
-- Copyright : (c) Sergey Vinokurov 2016
-- License : BSD3-style (see LICENSE)
-- Maintainer : serg.foo@gmail.com
-- Created : Wednesday, 24 August 2016
----------------------------------------------------------------------------
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module Control.Monad.Logging
( MonadLog(..)
, Severity(..)
, showSeverity
, readSeverity
, knownSeverities
, logError
, logWarning
, logInfo
, logDebug
, logVerboseDebug
) where
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.State
import qualified Control.Monad.State.Strict as SS
import Control.Monad.Writer as Lazy
import Control.Monad.Writer.Strict as Strict
import Data.Bimap (Bimap)
import qualified Data.Bimap as BM
import qualified Data.List as L
import Data.String
import Data.Text.Prettyprint.Doc (Doc)
import Data.Void (Void)
data Severity = VerboseDebug | Debug | Info | Warning | Error
deriving (Eq, Ord, Show)
severities :: (Ord a, IsString a) => Bimap a Severity
severities = BM.fromList
[ ("verbose-debug", VerboseDebug)
, ("debug", Debug)
, ("info", Info)
, ("warning", Warning)
, ("error", Error)
]
showSeverity :: Severity -> String
showSeverity = (severities BM.!>)
readSeverity :: MonadError String m => String -> m Severity
readSeverity str = case BM.lookup str severities of
Nothing -> throwError $
"Invalid verbosity: " ++ str ++
". Allowed values: " ++ L.intercalate ", " knownSeverities
Just x -> pure x
knownSeverities :: (Ord a, IsString a) => [a]
knownSeverities = BM.keys severities
class Monad m => MonadLog m where
logDoc :: Severity -> Doc Void -> m ()
{-# INLINE logError #-}
logError :: MonadLog m => Doc Void -> m ()
logError = logDoc Error
{-# INLINE logWarning #-}
logWarning :: MonadLog m => Doc Void -> m ()
logWarning = logDoc Warning
{-# INLINE logInfo #-}
logInfo :: MonadLog m => Doc Void -> m ()
logInfo = logDoc Info
{-# INLINE logDebug #-}
logDebug :: MonadLog m => Doc Void -> m ()
logDebug = logDoc Debug
{-# INLINE logVerboseDebug #-}
logVerboseDebug :: MonadLog m => Doc Void -> m ()
logVerboseDebug = logDoc VerboseDebug
instance MonadLog m => MonadLog (ExceptT e m) where
{-# INLINE logDoc #-}
logDoc s = lift . logDoc s
instance MonadLog m => MonadLog (ReaderT r m) where
{-# INLINE logDoc #-}
logDoc s = lift . logDoc s
instance MonadLog m => MonadLog (StateT s m) where
{-# INLINE logDoc #-}
logDoc s = lift . logDoc s
instance (MonadLog m, Monoid w) => MonadLog (Lazy.WriterT w m) where
{-# INLINE logDoc #-}
logDoc s = lift . logDoc s
instance (MonadLog m, Monoid w) => MonadLog (Strict.WriterT w m) where
{-# INLINE logDoc #-}
logDoc s = lift . logDoc s
instance MonadLog m => MonadLog (SS.StateT s m) where
{-# INLINE logDoc #-}
logDoc s = lift . logDoc s
| sergv/tags-server | src/Control/Monad/Logging.hs | bsd-3-clause | 3,096 | 0 | 11 | 612 | 863 | 472 | 391 | 81 | 2 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-}
module Language.Rsc.Parser.Common (
xyP, withSpan, postP
, dot, plus, question
, withinSpacesP
) where
import Language.Fixpoint.Parse
import Language.Fixpoint.Types.Errors
import Text.Parsec hiding (State, parse)
import qualified Text.Parsec.Token as T
----------------------------------------------------------------------------------
dot :: Parser String
plus :: Parser String
question :: Parser String
----------------------------------------------------------------------------------
dot = T.dot lexer
plus = T.symbol lexer "+"
question = T.symbol lexer "?"
----------------------------------------------------------------------------------
withinSpacesP :: Parser a -> Parser a
----------------------------------------------------------------------------------
withinSpacesP p = do { spaces; a <- p; spaces; return a }
xyP lP sepP rP
= (\x _ y -> (x, y)) <$> lP <*> (spaces >> sepP) <*> rP
withSpan f p = do pos <- getPosition
x <- p
pos' <- getPosition
return $ f (SS pos pos') x
postP p post = const <$> p <*> post
| UCSD-PL/RefScript | src/Language/Rsc/Parser/Common.hs | bsd-3-clause | 1,586 | 0 | 10 | 410 | 303 | 170 | 133 | 32 | 1 |
-- | A few helpers to work with the AST annotations
module BrownPLT.JavaScript.Syntax.Annotations where
import BrownPLT.JavaScript.Syntax
import Data.Traversable
import Control.Applicative
import Control.Arrow
import Control.Monad.State hiding (mapM)
import Prelude hiding (mapM)
-- | removes annotations
removeAnnotations :: Traversable t => t a -> t ()
removeAnnotations t = reannotate (const ()) t
-- | changes in a tree to another label (constant)
reannotate :: Traversable t => (a -> b) -> t a -> t b
reannotate f tree = (traverse (\a -> pure (f a)) tree) ()
-- | add an extra field to the AST labels (the label would look like @
-- (a, b) @)
addExtraAnnotationField :: Traversable t => b -> t a -> t (a, b)
addExtraAnnotationField def t = (traverse (\z -> pure (z, def)) t) ()
-- | remove an extra field
removeExtraAnnotationField :: Traversable t => t (a, b) -> t a
removeExtraAnnotationField t = (traverse (\(a, b) -> pure a) t) ()
-- | Assigns unique numeric (Int) ids to each node in the AST.
assignUniqueIds :: Traversable t => Int -- ^ starting id
-> t a -- ^ tree root
-> (t (a, Int), Int) -- ^ (tree_w_ids, last_label)
assignUniqueIds first tree =
(returnA *** \i -> i-1) $ runState (mapM f tree) first
where f :: a -> State Int (a, Int)
f a = do i <- get
put (i+1)
return (a, i)
class HasAnnotation a where
getAnnotation :: a b -> b
-- | returns the annotation of an expression
instance HasAnnotation Expression where
getAnnotation e = case e of
(StringLit a s) -> a
(RegexpLit a s g ci) -> a
(NumLit a d) -> a
(IntLit a i) -> a
(BoolLit a b) -> a
(NullLit a) -> a
(ArrayLit a exps) -> a
(ObjectLit a props) -> a
(ThisRef a) -> a
(VarRef a id) -> a
(DotRef a exp id) -> a
(BracketRef a container key) -> a
(NewExpr a ctor params) -> a
(PrefixExpr a op e) -> a
(UnaryAssignExpr a op lv) -> a
(InfixExpr a op e1 e2) -> a
(CondExpr a g et ef) -> a
(AssignExpr a op lv e) -> a
(ParenExpr a e) -> a
(ListExpr a es) -> a
(CallExpr a fn params) -> a
(FuncExpr a mid args s) -> a
instance HasAnnotation Statement where
getAnnotation s = case s of
BlockStmt a _ -> a
EmptyStmt a -> a
ExprStmt a _ -> a
IfStmt a _ _ _ -> a
IfSingleStmt a _ _ -> a
SwitchStmt a _ _ -> a
WhileStmt a _ _ -> a
DoWhileStmt a _ _ -> a
BreakStmt a _ -> a
ContinueStmt a _ -> a
LabelledStmt a _ _ -> a
ForInStmt a _ _ _ -> a
ForStmt a _ _ _ _ -> a
TryStmt a _ _ _ -> a
ThrowStmt a _ -> a
ReturnStmt a _ -> a
WithStmt a _ _ -> a
VarDeclStmt a _ -> a
FunctionStmt a _ _ _ -> a
instance HasAnnotation LValue where
getAnnotation lv = case lv of
LVar a _ -> a
LDot a _ _ -> a
LBracket a _ _ -> a
instance HasAnnotation VarDecl where
getAnnotation (VarDecl a _ _) = a
instance HasAnnotation Prop where
getAnnotation p = case p of
PropId a _ -> a
PropString a _ -> a
PropNum a _ -> a
instance HasAnnotation CaseClause where
getAnnotation c = case c of
CaseClause a _ _ -> a
CaseDefault a _ -> a
instance HasAnnotation CatchClause where
getAnnotation (CatchClause a _ _) = a | brownplt/webbits | src/BrownPLT/JavaScript/Syntax/Annotations.hs | bsd-3-clause | 3,594 | 0 | 12 | 1,249 | 1,304 | 653 | 651 | 89 | 1 |
{-# LANGUAGE OverloadedStrings, ViewPatterns #-}
module Crawl.Play (
play
) where
import Control.Applicative ((<$>), pure, (<*>), liftA2, (<|>))
import Control.Monad (forever, guard)
import Data.List (intersect)
import Data.Maybe (fromMaybe, listToMaybe, isJust)
import System.Exit (exitWith, ExitCode(ExitSuccess))
import Control.Concurrent.Chan.Split (InChan, OutChan, writeChan, readChan)
import Control.Lens ((^..), (^?), at, to, traverse, enum)
import Data.Aeson.Lens (_Integer, _String, _Array, key)
import Numeric.Lens (integral)
import qualified Data.Aeson as A
import qualified Data.HashMap.Strict as H
import qualified Data.HashSet as HS
import qualified Data.Map as M
import qualified Reactive.Banana as R
import qualified Reactive.Banana.Frameworks as R
import qualified Data.Text as T
import Crawl.Backoff
import Crawl.BadForms
import Crawl.BananaUtils
import Crawl.Bindings
import Crawl.Branch
import Crawl.Equipment
import Crawl.Explore
import Crawl.FloorItems
import Crawl.Identify
import Crawl.Inventory
import Crawl.Item
import Crawl.LevelInfo
import Crawl.Messages
import Crawl.Move
import Crawl.Menu
import Crawl.Status
play :: OutChan A.Object -> InChan A.Object -> IO ()
play recvChan sendChan = do
(recvHandler, recvFire) <- R.newAddHandler
let sendHandler = writeChan sendChan
network <- R.compile $ setupNetwork recvHandler sendHandler
R.actuate network
forever $ do
msg <- readChan recvChan
mapM_ recvFire $ demultiplex msg
setupNetwork :: R.Frameworks t => R.AddHandler A.Value -> (A.Object -> IO ()) -> R.Moment t ()
setupNetwork recvHandler sendHandler = do
input <- R.fromAddHandler recvHandler
let demultiplexed = input
ping = R.filterE (\msg -> msg ^? key "msg" == Just "ping") demultiplexed
pong = fmap (const $ H.fromList [("msg", "pong")]) ping
messages = messagesOf demultiplexed
inputModeEvents = filterBy (\msg -> do
guard $ msg ^? key "msg" == Just "input_mode"
msg ^? key "mode"._Integer.integral.enum) demultiplexed
inputModeB = R.stepper MOUSE_MODE_NORMAL inputModeEvents
inputModeChanged = R.filterApply (fmap (/=) inputModeB) inputModeEvents
menus = processMenus demultiplexed
goodbye = R.filterE (\msg -> msg ^? key "msg" == Just "txt" &&
msg ^? key "id" == Just "crt" &&
msg ^? key "lines".key "0"._String.to (T.isInfixOf "Goodbye,") == Just True)
demultiplexed
stillAlive = R.stepper True $ fmap (const False) goodbye
gameOver = R.filterE (\msg -> msg ^? key "msg" == Just "game_ended") demultiplexed
player = playerStatus $ R.filterE (\msg -> msg ^? key "msg" == Just "player") demultiplexed
level = levelInfo $ R.filterE (\msg -> msg ^? key "msg" == Just "map") demultiplexed
loc = R.stepper (Coord 0 0) $
filterBy (\msg -> do
guard $ msg ^? key "msg" == Just "player"
x <- msg ^? key "pos".key "x"._Integer.integral
y <- msg ^? key "pos".key "y"._Integer.integral
return (Coord x y)) demultiplexed
cursor = R.stepper (Coord 0 0) $
filterBy (\msg -> do
guard $ msg ^? key "msg" == Just "cursor"
x <- msg ^? key "loc".key "x"._Integer.integral
y <- msg ^? key "loc".key "y"._Integer.integral
return (Coord x y)) demultiplexed
inv = inventory $ R.filterE (\msg -> msg ^? key "msg" == Just "player") demultiplexed
equip = equipment $ R.filterE (\msg -> msg ^? key "msg" == Just "player") demultiplexed
needRest = (\p -> _hp p < _mhp p || isSlow p) <$> player
rest = (\nr lm t -> if nr
then case lm of
(t', LongRest) | t' == t -> Just Rest
_ -> Just LongRest
else Nothing) <$> needRest <*> lastMove <*> (_time <$> player)
eatChunk =
(\p i -> listToMaybe $ do
(slot, item@(itemData -> ItemFood FOOD_CHUNK)) <- M.toList i
guard $ not (itemColor item `elem` [LIGHTGREEN, LIGHTRED, DARKGRAY])
guard $ hungerLevel p < HS_SATIATED -- for normal races
return $ Eat slot) <$> player <*> inv
eatPermafood =
(\i -> listToMaybe $ do
(slot, (itemData -> ItemFood foodType)) <- M.toList i
guard $ foodType /= FOOD_CHUNK
return $ Eat slot) <$> inv
eatAnything = (<|>) <$> eatChunk <*> eatPermafood
-- Always eat a chunk if possible; permafood only if very hungry
eat = (\p ec ep -> ec <|> (guard (hungerLevel p < HS_HUNGRY) >> ep))
<$> player <*> eatChunk <*> eatPermafood
eatWhenStarving = (\p ea -> guard (hungerLevel p <= HS_STARVING) >> ea)
<$> player <*> eatAnything
floorItems = trackFloorItems cursor level inputModeB messages lastMove loc moves inputModeChanged
pickupRune =
(\l i -> do
(_, is) <- H.lookup l i
guard $ any isRune . knownItems $ is
return (PickUp isRune)) <$> loc <*> floorItems
pickup =
(\l i wi -> do
(_, is) <- H.lookup l i
guard $ any wi . knownItems $ is
return (PickUp wi)) <$> loc <*> floorItems <*> (fmap (wantItem False) inv)
corpses = fmap (HS.fromList . H.keys . H.filter (any butcherable . knownItems . snd)) floorItems
useCorpse = (\l c ->
guard (HS.member l c) >>
return Butcher) <$> loc <*> corpses
-- 'loot' is responsible for getting us to the corpse
burnBooks =
(\fi l p -> do
guard (any isBook $ concatMap (knownItems . snd . snd) . filter ((/= l) . fst) $ H.toList fi)
guard $ canUseGodAbility "Trog" 0 p
return BurnBooks) <$> floorItems <*> loc <*> player
threatened =
(\ll l ->
let monstersInView = [ (monType, dist sq l)
| sq <- HS.toList $ _levelLOS ll,
Just (_monsterType -> monType) <- return (H.lookup sq (_levelMonsters ll)),
not $ nonthreatening monType ]
in not . null $ monstersInView) <$> level <*> loc
nonthreatening m = m `elem` [MONS_TOADSTOOL, MONS_FUNGUS, MONS_PLANT, MONS_BUSH,
MONS_BALLISTOMYCETE, MONS_HYPERACTIVE_BALLISTOMYCETE]
dist (Coord x1 y1) (Coord x2 y2) = max (abs (x1 - x2)) (abs (y1 - y2))
cureConfusion =
(\t p i -> do
guard (t && isConfused p && not (isBerserk p))
slot <- listToMaybe [ slot | (slot, itemData -> ItemPotion (Just POT_CURING)) <- M.toList i ]
return $ Quaff slot) <$> threatened <*> player <*> inv
healWounds =
(\t p i -> do
guard (t && (2 * _hp p < _mhp p) && not (isBerserk p))
slot <- listToMaybe [ slot | (slot, itemData -> ItemPotion (Just POT_HEAL_WOUNDS)) <- M.toList i ]
return $ Quaff slot) <$> threatened <*> player <*> inv
berserk =
(\p i ll l -> do
let teleInstead =
guard (not (canTrogBerserk p) && not (hasStatus "Tele" p) && canRead p && lowHP p) >>
listToMaybe [ slot | (slot, itemData -> ItemScroll (Just SCR_TELEPORTATION)) <- M.toList i ]
guard $ canTrogBerserk p || isJust teleInstead
let monstersInView = [ (monType, dist sq l)
| sq <- HS.toList $ _levelLOS ll,
Just (_monsterType -> monType) <- return (H.lookup sq (_levelMonsters ll)),
not $ nonthreatening monType ]
guard $ not . null $ monstersInView
guard $ lowHP p && not (null $ filter ((<= 1) . snd) monstersInView)
|| sum [ meleeThreat m | (m, d) <- monstersInView, d <= 2] >= _xl p
return $ maybe Berserk Read teleInstead) <$> player <*> inv <*> level <*> loc
where meleeThreat MONS_GNOLL = 1
meleeThreat MONS_WORM = 1
meleeThreat MONS_IGUANA = 2
meleeThreat MONS_ORC_WIZARD = 3
meleeThreat MONS_ORC_PRIEST = 3
meleeThreat MONS_IJYB = 3
meleeThreat MONS_TERENCE = 3
meleeThreat MONS_ICE_BEAST = 4
meleeThreat MONS_CRAZY_YIUF = 4
meleeThreat MONS_OGRE = 6
meleeThreat MONS_ORC_WARRIOR = 6
meleeThreat MONS_SKELETAL_WARRIOR = 7
meleeThreat MONS_PURGY = 8
meleeThreat MONS_SIGMUND = 8
meleeThreat MONS_HILL_GIANT = 10
meleeThreat MONS_ORC_KNIGHT = 12
meleeThreat MONS_URUG = 12
meleeThreat MONS_ERICA = 14
meleeThreat MONS_ORC_WARLORD = 16
meleeThreat MONS_HYDRA = 16
meleeThreat MONS_ETTIN = 16
meleeThreat MONS_RUPERT = 18
meleeThreat MONS_SNORG = 18
meleeThreat MONS_PLAYER_GHOST = 27
meleeThreat _ = 0
lowHP p = 2 * _hp p < _mhp p
trogsHand =
(\p l -> do
guard (not (hasStatus "Regen MR++" p) && canTrogsHand p)
let monstersInView = [ _monsterType mon | sq <- HS.toList $ _levelLOS l, Just mon <- return (H.lookup sq (_levelMonsters l)) ]
guard $ isPoisoned p && _hp p <= 2 || not (null $ monstersInView `intersect` trogsHandMonsters)
return TrogsHand) <$> player <*> level
where trogsHandMonsters = -- http://www.reddit.com/r/roguelikes/comments/1eq3g6/dcss_advice_for_mibe/ca2pwni
[MONS_WIZARD, MONS_OGRE_MAGE, MONS_DEEP_ELF_MAGE, MONS_EROLCHA, MONS_DEEP_ELF_SORCERER,
MONS_DEEP_ELF_DEMONOLOGIST, MONS_ORC_SORCERER, MONS_SPHINX, MONS_GREAT_ORB_OF_EYES, MONS_GOLDEN_EYE,
MONS_LICH, MONS_ANCIENT_LICH, MONS_RUPERT, MONS_NORRIS, MONS_AIZUL, MONS_MENNAS, MONS_LOUISE,
MONS_JORGRUN, MONS_DRACONIAN_SHIFTER, MONS_CACODEMON, MONS_PANDEMONIUM_LORD, MONS_ERESHKIGAL] ++
[MONS_SIGMUND, MONS_GRINDER, MONS_ERICA, MONS_PSYCHE, MONS_KIRKE]
blinkToRune =
(\p i fi pCoord@(Coord px py) -> do
guard (canRead p)
blinkSlot <- listToMaybe [ slot | (slot, itemData -> ItemScroll (Just SCR_BLINKING)) <- M.toList i ]
Coord rx ry <- listToMaybe [ runeCoord | (runeCoord, (_, items)) <- H.toList fi, runeCoord /= pCoord, item <- knownItems items, isRune item ]
return (BlinkTo blinkSlot (rx-px) (ry-py))) <$> player <*> inv <*> floorItems <*> loc
hardBranch p = parseBranch (_place p) `elem` [BRANCH_DEPTHS, BRANCH_SNAKE, BRANCH_SPIDER, BRANCH_SHOALS, BRANCH_SWAMP, BRANCH_ABYSS]
bia =
(\p l -> do
guard (canBiA p)
let monstersInView = [ _monsterType mon | sq <- HS.toList $ _levelLOS l, Just mon <- return (H.lookup sq (_levelMonsters l)) ]
let alliesInView = [ _monsterType mon | sq <- HS.toList $ _levelLOS l, Just mon <- return (H.lookup sq (_levelMonsters l)), _monsterAttitude mon == ATT_FRIENDLY ]
guard $ null alliesInView
guard $ not (null $ monstersInView `intersect` biaMonsters) || (not (null monstersInView) && hardBranch p)
return BiA) <$> player <*> level
where biaMonsters = [MONS_HYDRA, MONS_OKLOB_PLANT, MONS_SONJA]
banish =
(\p l (Coord px py) -> do
guard (canUseGodAbility "Lugonu" 3 p && _mp p >= 4)
Coord tx ty <- listToMaybe [ sq | sq <- HS.toList $ _levelLOS l, Just mon <- return (H.lookup sq (_levelMonsters l)), _monsterType mon `elem` banishMonsters ]
return (Banish (tx-px) (ty-py))) <$> player <*> level <*> loc
where banishMonsters = [MONS_PRINCE_RIBBIT, MONS_CYCLOPS, MONS_HILL_GIANT, MONS_HYDRA, MONS_OKLOB_PLANT, MONS_SONJA, MONS_PLAYER_GHOST]
ruReady = R.stepper False $
(const True <$> R.filterE ((== "<brown>Ru believes you are ready to make a new sacrifice.<lightgrey>") . _msgText) messages)
`R.union` (const False <$> R.filterE (\m -> case m of {RuSacrifice -> True; _ -> False}) moves)
ru = (\r -> do
guard r
return RuSacrifice) <$> ruReady
moveFailures = filterBy (\(t, (t', lm), im) -> guard (im == MOUSE_MODE_COMMAND && t == t') >> return (lm,t)) $
(,,) <$> (_time <$> player) <*> lastMove R.<@> inputModeEvents
exploreWithAuto =
(\ll l b -> (if b then id else const AutoExplore) <$> explore ll l)
<$> level <*> loc <*> backoff isAutoExplore moveFailures (_time <$> player)
where isAutoExplore AutoExplore = True
isAutoExplore _ = False
killWithTab =
(\ll l p lm t ->
case kill ll l p of
Nothing -> Nothing
Just m -> case (m, lm) of
(_, (t', AutoFight)) | t' == t -> Just m
(Attack _ _, _) -> Just AutoFight
_ -> Just m) <$> level <*> loc <*> player <*> lastMove <*> (_time <$> player)
killWithTabIfThreatened =
(\t k -> if t then k else Nothing) <$> threatened <*> killWithTab
invisibleMonsters =
R.stepper False $
(const True <$> R.filterE ((== "<lightred>Deactivating autopickup; reactivate with <white>Ctrl-A<lightred>.<lightgrey>") . _msgText) messages)
`R.union` (const False <$> R.filterE (isReactivatingAutopickup . _msgText) messages)
where isReactivatingAutopickup "<lightred>Reactivating autopickup.<lightgrey>" = True
isReactivatingAutopickup "<lightgrey>Autopickup is now on.<lightgrey>" = True
isReactivatingAutopickup _ = False
killInvisible = (\ims u rnd -> guard ims >> if rnd /= (0 :: Int) then Just (Attack (dxs !! u) (dys !! u)) else Just AutoPickup) <$> invisibleMonsters <*> R.stepper 0 (randomize (0, 7) demultiplexed) <*> R.stepper 0 (randomize (0, 26) demultiplexed)
where dxs = [-1, -1, -1, 0, 1, 1, 1, 0]
dys = [-1, 0, 1, 1, 1, 0, -1, -1]
buffForDepths =
(\p i -> do
guard (hardBranch p)
listToMaybe $
[ Quaff slot | (slot, itemData -> ItemPotion (Just POT_HASTE)) <- M.toList i, not (hasStatus "Fast" p) ] ++
[ Quaff slot | (slot, itemData -> ItemPotion (Just POT_MIGHT)) <- M.toList i, not (hasStatus "Might" p) ] ++
[ Quaff slot | (slot, itemData -> ItemPotion (Just POT_AGILITY)) <- M.toList i, not (hasStatus "Agi" p) ] ++
[ Quaff slot | (slot, itemData -> ItemPotion (Just POT_RESISTANCE)) <- M.toList i, not (hasStatus "Resist" p) ]) <$> player <*> inv
mapDepths = (\p i -> do
guard (hardBranch p)
listToMaybe $
[ Read slot | (slot, itemData -> ItemScroll (Just SCR_MAGIC_MAPPING)) <- M.toList i ]) <$> player <*> inv
useGoodConsumables i =
listToMaybe $
[ Quaff slot | (slot, itemData -> ItemPotion (Just s)) <- M.toList i, s `elem` [POT_EXPERIENCE, POT_BENEFICIAL_MUTATION] ] ++
[ Read slot | (slot, itemData -> ItemScroll (Just SCR_ACQUIREMENT)) <- M.toList i ]
fly = (\p -> guard (_species p == "Gargoyle" && _xl p >= 14 && _mp p >= 3 && not (hasStatus "Fly" p)) >> return GargoyleFlight) <$> player
beenTo = fmap (flip HS.member) $
R.accumB HS.empty $
(HS.insert . dlvl <$> player) R.<@ moves
pastGods = fmap (filter (not . T.null) . HS.toList) $ R.accumB HS.empty $ (HS.insert . _god <$> player) R.<@ moves
lastDump = R.stepper 0 $ (_time <$> player) R.<@ R.filterE (\mv -> case mv of { Dump -> True; _ -> False }) moves
dump = (\l t -> guard (t `div` 10000 > l `div` 10000) >> Just Dump) <$> lastDump <*> (_time <$> player)
move = foldr (liftA2 (flip fromMaybe)) (pure Rest) $ map (fmap filterLegalInForm player <*>) [
dump,
(\p -> guard (_god p == "Lugonu" && _place p == "Abyss") >> return ExitTheAbyss) <$> player,
scanFloorItems <$> level <*> loc <*> floorItems,
eatWhenStarving,
cureConfusion,
blinkToRune,
pickupRune,
bia,
banish,
berserk,
healWounds,
trogsHand,
-- (\p -> guard (_god p == "Makhleb" || _god p == "Nemelex Xobeh" || _god p == "Okawaru") >> return Abandon) <$> player,
(\p f -> guard (_god p == "") >> f) <$> player <*> (findOtherAltar <$> level <*> loc <*> pastGods),
--(\p f -> guard (not ("Trog" `elem` p) || not (null p) && not ("Trog" `elem` p)) >> f) <$> pastGods <*> (findTrogAltar <$> level <*> loc),
ru,
enterBranches <$> level <*> loc <*> beenTo,
mapDepths,
killInvisible,
killWithTabIfThreatened,
eat,
useCorpse,
burnBooks,
pickup,
rest,
killWithTab,
buffForDepths,
loot <$> level <*> loc <*> floorItems <*> inv, -- should probably produce set of things we want here, not in Explore
upgradeEquipment <$> inv <*> equip <*> player <*> eatAnything,
dropJunkEquipment <$> inv <*> equip,
enchantEquipment <$> inv <*> equip,
useGoodConsumables <$> inv,
fly,
exploreWithAuto,
identify <$> inv <*> player,
descend <$> level <*> loc <*> (dlvl <$> player) <*> beenTo
]
(moves, goText) = sendMoves move messages (R.whenE stillAlive inputModeChanged) menus
lastMove = R.stepper (0, GoDown) {- whatever -} $ (,) <$> (_time <$> player) R.<@> moves
clearText = fmap (const " ") goodbye
outputText = goText `R.union` clearText
output = pong `R.union` fmap textInput outputText
R.reactimate $ fmap print messages
R.reactimate $ fmap print outputText
R.reactimate $ fmap sendHandler output
R.reactimate $ fmap (const $ exitWith ExitSuccess) gameOver
demultiplex :: A.Object -> [A.Value]
demultiplex msg = msg^..at "msgs".traverse._Array.traverse
textInput :: T.Text -> A.Object
textInput text = H.fromList [
("msg", "input"),
("text", A.String text)
]
| rwbarton/rw | Crawl/Play.hs | bsd-3-clause | 18,330 | 0 | 30 | 5,559 | 6,119 | 3,168 | 2,951 | -1 | -1 |
module Data.Blockchain.Mining.Block
( MineBlockException(..)
, mineBlock
, mineEmptyBlock
, mineGenesisBlock
) where
import qualified Data.ByteString.Char8 as Char8
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Time.Clock as Time
import qualified Data.Word as Word
import qualified Data.Blockchain as Blockchain
import qualified Data.Blockchain.Crypto as Crypto
data MineBlockException
= InvalidTransactionList
deriving (Eq, Show)
-- | Finds the next block of a blockchain. Depending on blockchain configuration, this function may take a long time to complete.
mineBlock
:: Crypto.PublicKey -- ^ PublicKey address where coinbase reward will be sent
-> [Blockchain.Transaction] -- ^ List of transactions to include in transaction
-> Blockchain.Blockchain Blockchain.Validated -- ^ Validated blockchain
-> IO (Either MineBlockException Blockchain.Block)
mineBlock pubKey txs blockchain =
case Blockchain.validateTransactions blockchain txs of
Left _e -> return (Left InvalidTransactionList)
Right () -> Right <$> mineBlockInternal pubKey reward diff1 difficulty prevBlockHeaderHash txs
where
diff1 = Blockchain.difficulty1Target config
reward = Blockchain.targetReward config (fromIntegral $ length prevBlocks + 1)
config = Blockchain.blockchainConfig blockchain
difficulty = Blockchain.targetDifficulty config $ NonEmpty.toList prevBlocks -- TODO: next diff?
prevBlocks = Blockchain.longestChain blockchain
prevBlock = NonEmpty.last prevBlocks
prevBlockHeaderHash = Crypto.hash (Blockchain.blockHeader prevBlock)
-- | Finds the next block of a blockchain, without including any transactions.
-- Most useful for testing - removes the invariant of an invalid transaction list.
-- Depending on blockchain configuration, this function may take a long time to complete.
mineEmptyBlock
:: Crypto.PublicKey -- ^ PublicKey address where coinbase reward will be sent
-> Blockchain.Blockchain Blockchain.Validated -- ^ Validated blockchain
-> IO (Either MineBlockException Blockchain.Block)
mineEmptyBlock pubKey = mineBlock pubKey mempty
-- | Finds the first block of a blockchain.
-- Depending on blockchain configuration, this function may take a long time to complete.
-- Note: this generates a keypair but throws away the private key. Coinbase reward in genesis block cannot never be spent.
mineGenesisBlock :: Blockchain.BlockchainConfig -> IO Blockchain.Block
mineGenesisBlock config = do
(Crypto.KeyPair pubKey _privKey) <- Crypto.generate
mineBlockInternal pubKey reward diff1 difficulty prevBlockHeaderHash mempty
where
diff1 = Blockchain.difficulty1Target config
reward = Blockchain.initialMiningReward config
difficulty = Blockchain.initialDifficulty config
prevBlockHeaderHash = Crypto.unsafeFromByteString $ Char8.replicate 64 '0'
-- TODO: accept multiple public keys
mineBlockInternal
:: Crypto.PublicKey -> Word.Word -> Blockchain.Hex256 -> Blockchain.Difficulty
-> Crypto.Hash Blockchain.BlockHeader -> [Blockchain.Transaction]
-> IO Blockchain.Block
mineBlockInternal pubKey reward diff1 difficulty prevBlockHeaderHash txs = do
header <- mineHeader
prevBlockHeaderHash
(Crypto.hash coinbaseTx)
(Crypto.hashTreeRoot txs)
diff1
difficulty
-- TODO: add up fees and include in coinbase reward
-- fee = address value - total tx value
return (Blockchain.Block header coinbaseTx txs)
where
coinbaseTx = Blockchain.CoinbaseTransaction $ pure (Blockchain.TransactionOut reward pubKey)
-- TODO: could clean up param list by passing config down to this level
mineHeader
:: Crypto.Hash Blockchain.BlockHeader
-> Crypto.Hash Blockchain.CoinbaseTransaction
-> Crypto.HashTreeRoot Blockchain.Transaction
-> Blockchain.Hex256
-> Blockchain.Difficulty
-> IO Blockchain.BlockHeader
mineHeader prevBlockHeaderHash coinbaseTransactionHash transactionHashTreeRoot diff1 difficulty = do
time <- Time.getCurrentTime
let version = 0
nonce = 0
initialHeader = Blockchain.BlockHeader{..}
mineHeaderInternal initialHeader
where
-- TODO: get current time in case of int overflow,
-- or in case current mining operation is getting close to oldest block time
mineHeaderInternal header =
if Blockchain.blockHeaderHashDifficulty diff1 header >= difficulty
then return header
else mineHeaderInternal (incNonce header)
incNonce :: Blockchain.BlockHeader -> Blockchain.BlockHeader
incNonce header = header { Blockchain.nonce = Blockchain.nonce header + 1 }
| TGOlson/blockchain | lib/Data/Blockchain/Mining/Block.hs | bsd-3-clause | 4,816 | 0 | 12 | 986 | 833 | 437 | 396 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Touch where
import Control.Monad
import Data.Aeson.Types
import Debug.Trace
import Miso
data Touch = Touch
{ identifier :: Int
, screen :: (Double, Double)
, client :: (Double, Double)
, page :: (Double, Double)
} deriving (Eq, Show)
instance FromJSON Touch where
parseJSON =
withObject "touch" $ \o -> do
identifier <- o .: "identifier"
screen <- (,) <$> o .: "screenX" <*> o .: "screenY"
client <- (,) <$> o .: "clientX" <*> o .: "clientY"
page <- (,) <$> o .: "pageX" <*> o .: "pageY"
return Touch {..}
data TouchEvent =
TouchEvent Touch
deriving (Eq, Show)
instance FromJSON TouchEvent where
parseJSON obj = do
((x:_):_) <- parseJSON obj
return $ TouchEvent x
touchDecoder :: Decoder TouchEvent
touchDecoder = Decoder {..}
where
decodeAt = DecodeTargets [["changedTouches"], ["targetTouches"], ["touches"]]
decoder = parseJSON
onTouchMove :: (TouchEvent -> action) -> Attribute action
onTouchMove = on "touchmove" touchDecoder
onTouchStart = on "touchstart" touchDecoder
| dmjio/miso | examples/svg/Touch.hs | bsd-3-clause | 1,128 | 0 | 15 | 237 | 372 | 203 | 169 | 35 | 1 |
{-# LANGUAGE CPP, DeriveGeneric #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Program.Find
-- Copyright : Duncan Coutts 2013
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- A somewhat extended notion of the normal program search path concept.
--
-- Usually when finding executables we just want to look in the usual places
-- using the OS's usual method for doing so. In Haskell the normal OS-specific
-- method is captured by 'findExecutable'. On all common OSs that makes use of
-- a @PATH@ environment variable, (though on Windows it is not just the @PATH@).
--
-- However it is sometimes useful to be able to look in additional locations
-- without having to change the process-global @PATH@ environment variable.
-- So we need an extension of the usual 'findExecutable' that can look in
-- additional locations, either before, after or instead of the normal OS
-- locations.
--
module Distribution.Simple.Program.Find (
-- * Program search path
ProgramSearchPath,
ProgramSearchPathEntry(..),
defaultProgramSearchPath,
findProgramOnSearchPath,
programSearchPathAsPATHVar,
getSystemSearchPath,
) where
import Distribution.Verbosity
( Verbosity )
import Distribution.Simple.Utils
( debug, doesExecutableExist )
import Distribution.System
( OS(..), buildOS )
import qualified System.Directory as Directory
( findExecutable )
import Distribution.Compat.Environment
( getEnvironment )
import System.FilePath as FilePath
( (</>), (<.>), splitSearchPath, searchPathSeparator, getSearchPath
, takeDirectory )
import Data.List
( intercalate, nub )
import Distribution.Compat.Binary
import GHC.Generics
#if defined(mingw32_HOST_OS)
import qualified System.Win32 as Win32
#endif
-- | A search path to use when locating executables. This is analogous
-- to the unix @$PATH@ or win32 @%PATH%@ but with the ability to use
-- the system default method for finding executables ('findExecutable' which
-- on unix is simply looking on the @$PATH@ but on win32 is a bit more
-- complicated).
--
-- The default to use is @[ProgSearchPathDefault]@ but you can add extra dirs
-- either before, after or instead of the default, e.g. here we add an extra
-- dir to search after the usual ones.
--
-- > ['ProgramSearchPathDefault', 'ProgramSearchPathDir' dir]
--
type ProgramSearchPath = [ProgramSearchPathEntry]
data ProgramSearchPathEntry =
ProgramSearchPathDir FilePath -- ^ A specific dir
| ProgramSearchPathDefault -- ^ The system default
deriving (Eq, Generic)
instance Binary ProgramSearchPathEntry
defaultProgramSearchPath :: ProgramSearchPath
defaultProgramSearchPath = [ProgramSearchPathDefault]
findProgramOnSearchPath :: Verbosity -> ProgramSearchPath
-> FilePath -> IO (Maybe (FilePath, [FilePath]))
findProgramOnSearchPath verbosity searchpath prog = do
debug verbosity $ "Searching for " ++ prog ++ " in path."
res <- tryPathElems [] searchpath
case res of
Nothing -> debug verbosity ("Cannot find " ++ prog ++ " on the path")
Just (path, _) -> debug verbosity ("Found " ++ prog ++ " at "++ path)
return res
where
tryPathElems :: [[FilePath]] -> [ProgramSearchPathEntry]
-> IO (Maybe (FilePath, [FilePath]))
tryPathElems _ [] = return Nothing
tryPathElems tried (pe:pes) = do
res <- tryPathElem pe
case res of
(Nothing, notfoundat) -> tryPathElems (notfoundat : tried) pes
(Just foundat, notfoundat) -> return (Just (foundat, alltried))
where
alltried = concat (reverse (notfoundat : tried))
tryPathElem :: ProgramSearchPathEntry -> IO (Maybe FilePath, [FilePath])
tryPathElem (ProgramSearchPathDir dir) =
findFirstExe [ dir </> prog <.> ext | ext <- exeExtensions ]
-- On windows, getSystemSearchPath is not guaranteed 100% correct so we
-- use findExecutable and then approximate the not-found-at locations.
tryPathElem ProgramSearchPathDefault | buildOS == Windows = do
mExe <- findExecutable prog
syspath <- getSystemSearchPath
case mExe of
Nothing ->
let notfoundat = [ dir </> prog | dir <- syspath ] in
return (Nothing, notfoundat)
Just foundat -> do
let founddir = takeDirectory foundat
notfoundat = [ dir </> prog
| dir <- takeWhile (/= founddir) syspath ]
return (Just foundat, notfoundat)
-- On other OSs we can just do the simple thing
tryPathElem ProgramSearchPathDefault = do
dirs <- getSystemSearchPath
findFirstExe [ dir </> prog <.> ext | dir <- dirs, ext <- exeExtensions ]
-- Possible improvement: on Windows, read the list of extensions from
-- the PATHEXT environment variable. By default PATHEXT is ".com; .exe;
-- .bat; .cmd".
exeExtensions = case buildOS of
Windows -> ["", "exe"]
Ghcjs -> ["", "exe"]
_ -> [""]
findFirstExe :: [FilePath] -> IO (Maybe FilePath, [FilePath])
findFirstExe = go []
where
go fs' [] = return (Nothing, reverse fs')
go fs' (f:fs) = do
isExe <- doesExecutableExist f
if isExe
then return (Just f, reverse fs')
else go (f:fs') fs
-- | Interpret a 'ProgramSearchPath' to construct a new @$PATH@ env var.
-- Note that this is close but not perfect because on Windows the search
-- algorithm looks at more than just the @%PATH%@.
programSearchPathAsPATHVar :: ProgramSearchPath -> IO String
programSearchPathAsPATHVar searchpath = do
ess <- mapM getEntries searchpath
return (intercalate [searchPathSeparator] (concat ess))
where
getEntries (ProgramSearchPathDir dir) = return [dir]
getEntries ProgramSearchPathDefault = do
env <- getEnvironment
return (maybe [] splitSearchPath (lookup "PATH" env))
-- | Get the system search path. On Unix systems this is just the @$PATH@ env
-- var, but on windows it's a bit more complicated.
--
getSystemSearchPath :: IO [FilePath]
getSystemSearchPath = fmap nub $ do
#if defined(mingw32_HOST_OS)
processdir <- takeDirectory `fmap` Win32.getModuleFileName Win32.nullHANDLE
currentdir <- Win32.getCurrentDirectory
systemdir <- Win32.getSystemDirectory
windowsdir <- Win32.getWindowsDirectory
pathdirs <- FilePath.getSearchPath
let path = processdir : currentdir
: systemdir : windowsdir
: pathdirs
return path
#else
FilePath.getSearchPath
#endif
#ifdef MIN_VERSION_directory
#if MIN_VERSION_directory(1,2,1)
#define HAVE_directory_121
#endif
#endif
findExecutable :: FilePath -> IO (Maybe FilePath)
#ifdef HAVE_directory_121
findExecutable = Directory.findExecutable
#else
findExecutable prog = do
-- With directory < 1.2.1 'findExecutable' doesn't check that the path
-- really refers to an executable.
mExe <- Directory.findExecutable prog
case mExe of
Just exe -> do
exeExists <- doesExecutableExist exe
if exeExists
then return mExe
else return Nothing
_ -> return mExe
#endif
| randen/cabal | Cabal/Distribution/Simple/Program/Find.hs | bsd-3-clause | 7,382 | 0 | 22 | 1,749 | 1,271 | 696 | 575 | 102 | 11 |
{-# LANGUAGE DeriveDataTypeable #-}
{- -*- Mode: haskell; -*-
Haskell LDAP Interface
Copyright (C) 2005-2009 John Goerzen <jgoerzen@complete.org>
This code is under a 3-clause BSD license; see COPYING for details.
-}
{- |
Module : LDAP.Exceptions
Copyright : Copyright (C) 2005-2009 John Goerzen
License : BSD
Maintainer : John Goerzen,
Maintainer : jgoerzen\@complete.org
Stability : provisional
Portability: portable
Handling LDAP Exceptions
Written by John Goerzen, jgoerzen\@complete.org
-}
module LDAP.Exceptions (-- * Types
LDAPException(..),
-- * General Catching
catchLDAP,
handleLDAP,
failLDAP,
throwLDAP
)
where
import Data.Typeable
import Control.Exception
import LDAP.Types
import LDAP.Data
#if __GLASGOW_HASKELL__ < 610
import Data.Dynamic
#endif
{- | The basic type of LDAP exceptions. These are raised when an operation
does not indicate success. -}
data LDAPException = LDAPException
{code :: LDAPReturnCode, -- ^ Numeric error code
description :: String, -- ^ Description of error
caller :: String -- ^ Calling function
}
deriving (Typeable)
instance Show LDAPException where
show x = caller x ++ ": LDAPException " ++ show (code x) ++
"(" ++ show (fromEnum $ code x) ++ "): " ++
description x
instance Eq LDAPException where
x == y = code x == code y
instance Ord LDAPException where
compare x y = compare (code x) (code y)
#if __GLASGOW_HASKELL__ >= 610
instance Exception LDAPException where
{-
toException = SomeException
fromException (SomeException e) = Just e
fromException _ = Nothing
-}
{- | Execute the given IO action.
If it raises a 'LDAPException', then execute the supplied handler and return
its return value. Otherwise, process as normal. -}
catchLDAP :: IO a -> (LDAPException -> IO a) -> IO a
catchLDAP action handler =
catchJust ldapExceptions action handler
{- | Like 'catchLDAP', with the order of arguments reversed. -}
handleLDAP :: (LDAPException -> IO a) -> IO a -> IO a
handleLDAP = flip catchLDAP
{- | Given an Exception, return Just LDAPException if it was an
'LDAPExcetion', or Nothing otherwise. Useful with functions
like catchJust. -}
ldapExceptions :: LDAPException -> Maybe LDAPException
ldapExceptions e = Just e
#else
{- | Execute the given IO action.
If it raises a 'LDAPException', then execute the supplied handler and return
its return value. Otherwise, process as normal. -}
catchLDAP :: IO a -> (LDAPException -> IO a) -> IO a
catchLDAP = catchDyn
{- | Like 'catchLDAP', with the order of arguments reversed. -}
handleLDAP :: (LDAPException -> IO a) -> IO a -> IO a
handleLDAP = flip catchLDAP
#endif
{- | Catches LDAP errors, and re-raises them as IO errors with fail.
Useful if you don't care to catch LDAP errors, but want to see a sane
error message if one happens. One would often use this as a high-level
wrapper around LDAP calls.
-}
failLDAP :: IO a -> IO a
failLDAP action =
catchLDAP action handler
where handler e = fail ("LDAP error: " ++ show e)
{- | A utility function to throw an 'LDAPException'. The mechanics of throwing
such a thing differ between GHC 6.8.x, Hugs, and GHC 6.10. This function
takes care of the special cases to make it simpler.
With GHC 6.10, it is a type-restricted alias for throw. On all other systems,
it is a type-restricted alias for throwDyn. -}
throwLDAP :: LDAPException -> IO a
#if __GLASGOW_HASKELL__ >= 610
throwLDAP = throw
#else
throwLDAP = throwDyn
#endif
| ezyang/ldap-haskell | LDAP/Exceptions.hs | bsd-3-clause | 3,701 | 0 | 13 | 887 | 423 | 227 | 196 | 35 | 1 |
{-# LANGUAGE Safe #-}
{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Concurrent.QSemN
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (concurrency)
--
-- Quantity semaphores in which each thread may wait for an arbitrary
-- \"amount\".
--
-----------------------------------------------------------------------------
module Control.Concurrent.QSemN
( -- * General Quantity Semaphores
QSemN, -- abstract
newQSemN, -- :: Int -> IO QSemN
waitQSemN, -- :: QSemN -> Int -> IO ()
signalQSemN -- :: QSemN -> Int -> IO ()
) where
import Control.Concurrent.MVar ( MVar, newEmptyMVar, takeMVar, tryTakeMVar
, putMVar, newMVar
, tryPutMVar, isEmptyMVar)
import Control.Exception
import Data.Maybe
-- | 'QSemN' is a quantity semaphore in which the resource is aqcuired
-- and released in units of one. It provides guaranteed FIFO ordering
-- for satisfying blocked `waitQSemN` calls.
--
-- The pattern
--
-- > bracket_ (waitQSemN n) (signalQSemN n) (...)
--
-- is safe; it never loses any of the resource.
--
data QSemN = QSemN !(MVar (Int, [(Int, MVar ())], [(Int, MVar ())]))
-- The semaphore state (i, xs, ys):
--
-- i is the current resource value
--
-- (xs,ys) is the queue of blocked threads, where the queue is
-- given by xs ++ reverse ys. We can enqueue new blocked threads
-- by consing onto ys, and dequeue by removing from the head of xs.
--
-- A blocked thread is represented by an empty (MVar ()). To unblock
-- the thread, we put () into the MVar.
--
-- A thread can dequeue itself by also putting () into the MVar, which
-- it must do if it receives an exception while blocked in waitQSemN.
-- This means that when unblocking a thread in signalQSemN we must
-- first check whether the MVar is already full; the MVar lock on the
-- semaphore itself resolves race conditions between signalQSemN and a
-- thread attempting to dequeue itself.
-- |Build a new 'QSemN' with a supplied initial quantity.
-- The initial quantity must be at least 0.
newQSemN :: Int -> IO QSemN
newQSemN initial
| initial < 0 = fail "newQSemN: Initial quantity must be non-negative"
| otherwise = do
sem <- newMVar (initial, [], [])
return (QSemN sem)
-- |Wait for the specified quantity to become available
waitQSemN :: QSemN -> Int -> IO ()
waitQSemN (QSemN m) sz =
mask_ $ do
(i,b1,b2) <- takeMVar m
let z = i-sz
if z < 0
then do
b <- newEmptyMVar
putMVar m (i, b1, (sz,b):b2)
wait b
else do
putMVar m (z, b1, b2)
return ()
where
wait b = do
takeMVar b `onException`
(uninterruptibleMask_ $ do -- Note [signal uninterruptible]
(i,b1,b2) <- takeMVar m
r <- tryTakeMVar b
r' <- if isJust r
then signal sz (i,b1,b2)
else do putMVar b (); return (i,b1,b2)
putMVar m r')
-- |Signal that a given quantity is now available from the 'QSemN'.
signalQSemN :: QSemN -> Int -> IO ()
signalQSemN (QSemN m) sz = uninterruptibleMask_ $ do
r <- takeMVar m
r' <- signal sz r
putMVar m r'
signal :: Int
-> (Int,[(Int,MVar ())],[(Int,MVar ())])
-> IO (Int,[(Int,MVar ())],[(Int,MVar ())])
signal sz0 (i,a1,a2) = loop (sz0 + i) a1 a2
where
loop 0 bs b2 = return (0, bs, b2)
loop sz [] [] = return (sz, [], [])
loop sz [] b2 = loop sz (reverse b2) []
loop sz ((j,b):bs) b2
| j > sz = do
r <- isEmptyMVar b
if r then return (sz, (j,b):bs, b2)
else loop sz bs b2
| otherwise = do
r <- tryPutMVar b ()
if r then loop (sz-j) bs b2
else loop sz bs b2
| rahulmutt/ghcvm | libraries/base/Control/Concurrent/QSemN.hs | bsd-3-clause | 4,130 | 0 | 19 | 1,162 | 939 | 514 | 425 | 66 | 6 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE BangPatterns #-}
module Optical
( P.either
, P.all
, P.and
, P.any
, P.concat
, P.concatMap
, P.mapM_
, P.notElem
, P.or
, P.sequence_
, (P.<$>)
, P.maybe
-- , P.lines
-- , P.unlines
-- , P.unwords
-- , P.words
, P.curry
, P.fst
, P.snd
, P.uncurry
, (P.$!)
, (++)
, (P..)
, (P.=<<)
, P.asTypeOf
, P.const
, P.flip
, P.id
, map
, P.otherwise
, P.until
, P.ioError
, P.userError
, (!!?)
, (!!)
, (!?)
, (!)
-- , P.break
, P.cycle
-- , P.drop
-- , P.dropWhile
-- , P.filter
, head
, init
, P.iterate
, last
, P.repeat
, P.replicate
, P.scanl
, P.scanl1
, P.scanr
, P.scanr1
-- , P.span
-- , P.splitAt
, tail
-- , P.take
-- , P.takeWhile
, P.unzip
, P.unzip3
, P.zip
, P.zip3
, P.zipWith
, P.zipWith3
, P.subtract
, P.lex
, P.readParen
, (^)
, (P.^^)
, P.even
, P.fromIntegral
, P.gcd
, P.lcm
, P.odd
, P.realToFrac
, P.showChar
, P.showParen
, P.showString
, P.shows
, P.appendFile
, P.getChar
, P.getContents
, P.getLine
, P.interact
, P.print
, P.putChar
, P.putStr
, P.putStrLn
, P.readFile
, P.readIO
, P.readLn
, P.writeFile
, P.read
, P.reads
, (P.&&)
, P.not
, (P.||)
, (P.$)
, P.error
, P.undefined
, P.seq
, P.elem
, P.foldMap
, P.foldl
, F.foldl'
, P.foldl1
, P.foldr
, P.foldr1
, P.length
, P.maximum
, P.minimum
, P.null
, empty
, isEmpty
, transpose
, P.product
, P.sum
, P.mapM
, P.sequence
, P.sequenceA
-- , P.traverse
, for
, for_
, (P.*>)
, (P.<*)
, (P.<*>)
, P.pure
, (P.<$)
, P.fmap
, (P.>>)
, (P.>>=)
, P.fail
, P.return
, P.mappend
, P.mconcat
, P.mempty
, P.maxBound
, P.minBound
, P.enumFrom
, P.enumFromThen
, P.enumFromThenTo
, P.enumFromTo
, P.fromEnum
, P.pred
, P.succ
, P.toEnum
, (P.**)
, P.acos
, P.acosh
, P.asin
, P.asinh
, P.atan
, P.atanh
, P.cos
, P.cosh
, P.exp
, P.log
, P.logBase
, P.pi
, P.sin
, P.sinh
, P.sqrt
, P.tan
, P.tanh
, P.atan2
, P.decodeFloat
, P.encodeFloat
, P.exponent
, P.floatDigits
, P.floatRadix
, P.floatRange
, P.isDenormalized
, P.isIEEE
, P.isInfinite
, P.isNaN
, P.isNegativeZero
, P.scaleFloat
, P.significand
, (P.*)
, (P.+)
, (P.-)
, P.abs
, P.negate
, P.signum
, P.readList
, P.readsPrec
, (P./)
, P.fromRational
, P.recip
, P.div
, P.divMod
, P.mod
, P.quot
, P.quotRem
, P.rem
, P.toInteger
, P.toRational
, P.ceiling
, P.floor
, P.properFraction
, P.round
, P.truncate
, P.show
, P.showList
, P.showsPrec
, (P./=)
, (P.==)
, (P.<)
, (P.<=)
, (P.>)
, (P.>=)
, P.compare
, P.max
, P.min
-- lists
, findIndex
, findIndices
, isPrefixOf
, isSuffixOf
, isInfixOf
, reverse
, lookup
, elemIndex
, elemIndices
, toMaybe
-- classes
, P.Applicative
, P.Bounded
, P.Enum
, P.Eq
, P.Floating
, P.Foldable
, P.Fractional
, P.Functor
, P.Integral
, P.Monad
, P.Monoid
, P.Num (fromInteger)
, P.Ord
, P.Read
, P.Real
, P.RealFloat
, P.RealFrac
, P.Show
-- , P.Traversable
-- data types
, P.IO
, P.Char
, P.Double
, P.Float
, P.Int
, P.Integer
, P.Word
, P.Bool (True, False)
, bool
, P.Either(Left, Right)
, P.Maybe(Just, Nothing)
, P.Ordering (EQ, GT, LT)
-- * type synonyms
-- ** base
, P.FilePath
, P.IOError
, P.Rational
, P.ReadS
, P.ShowS
, P.String
, Storable (..)
, V0 (..)
, V1 (..)
, V2 (..)
, V3 (..)
, V4 (..)
-- * lensy
, ijover
, ijkover
, previewA
, atOrdinals
, atUpdate
, ixOrdinals
, ixUpdate
-- * Monads
-- ** Transformers
, MonadTrans (..)
, MonadReader (..)
-- , ReaderT
-- , Reader
-- , runReaderT
-- , runReader
, MonadState (..)
-- , StateT
-- , State
-- , runStateT
-- , runState
, MonadWriter (..)
-- , WriterT
-- , Writer
-- , runWriterT
-- , runWriter
, MonadIO (..)
, PrimMonad
-- * ST
, ST
, RealWorld
, runST
-- Partial functions
, snatch
, sieze
-- Loops
, for_i
, rfor_i
-- Monadic
, whenM
, unlessM
, whenJust
, whenJustM
, partitionM
, loopM
, whileM
, ifM
, notM
, (||^)
, (&&^)
-- | Isos and contructors for common containers.
, module Optical.Containers
, module Optical.Text
, module Optical.Witherable
, module Optical.Severable
, module Control.Lens
, module Foreign
, Semigroup (..)
) where
import Prelude.Compat hiding ((++), (!!), (^), head, tail, last, init, map, reverse, lookup, filter)
import qualified Prelude.Compat as P
import Control.Lens hiding (mapOf, lined, worded)
import Linear (V0 (..), V1 (..), V2 (..), V3 (..), V4 (..))
import Control.Monad.Reader
import Foreign hiding (Int, Word)
import Control.Monad.State
import Control.Monad.Writer
import Data.Semigroup hiding (First)
import Data.Maybe
import Data.Bool
import Control.Monad.ST
-- import Foreign.Storable (Storable (..))
import Control.Monad.Primitive
import Data.Distributive
import Data.Foldable as F
import Data.Traversable
import Control.Applicative
import qualified Data.List as List
import Optical.Containers
import Optical.Text
import Optical.Witherable
import Optical.Severable
(^) :: Num a => a -> Int -> a
-- should really be word or natural
(^) = (P.^)
------------------------------------------------------------------------
-- Isos
------------------------------------------------------------------------
-- Arrays --------------------------------------------------------------
------------------------------------------------------------------------
-- Text-like
------------------------------------------------------------------------
-- class Monoid b => Building b t where
-- building :: Iso b t
-- buildOf :: Fold s Char -> s -> b
-- flush :: b
------------------------------------------------------------------------
-- Indexing
------------------------------------------------------------------------
-- | Partial index of an element. Throws an error if the element is out
-- of range.
(!?) :: Ixed a => a -> Index a -> Maybe (IxValue a)
x !? i = x ^? ix i
-- | Partial index of an element. Throws an error if the element is out
-- of range.
(!) :: Ixed a => a -> Index a -> IxValue a
(!) x i = x ^?! ix i
-- | Index the ordinal position of an element.
(!!?) :: Foldable t => t a -> Int -> Maybe a
x !!? i = x ^? elementOf folded i
-- | Partial index the ordinal position of an element. Throws an error
-- if the element is out of range.
(!!) :: Foldable t => t a -> Int -> a
x !! i = x ^?! elementOf folded i
------------------------------------------------------------------------
-- List-like functions
------------------------------------------------------------------------
-- | Get the first element of a container if it exists.
head :: Cons s s a a => s -> Maybe a
head = preview _head
-- | Drop the first element of a container if it exists.
tail :: Cons s s a a => s -> Maybe s
tail = preview _tail
-- | Take the last element of a container if it exists.
last :: Snoc s s a a => s -> Maybe a
last = preview _last
-- | Drop the last element of a container if it exists.
init :: Snoc s s a a => s -> Maybe s
init = preview _init
-- | Check if the item is empty.
isEmpty :: AsEmpty a => a -> Bool
isEmpty = has _Empty
-- | Map over every element, using the 'each' class.
map :: Each s t a b => (a -> b) -> s -> t
map = over each
-- | Reverse something.
reverse :: Reversing a => a -> a
reverse = reversing
-- | Alias for 'distribute'.
transpose :: (Distributive g, Functor f) => f (g a) -> g (f a)
transpose = distribute
-- | Since 'Semigroup' is still not a superclass of 'Monoid' it's useful
-- to have separate functions.
(++) :: Monoid a => a -> a -> a
(++) = mappend
-- | Lookup at item in a folable container.
--
-- @
-- lookup :: 'Eq' i => i -> [(i,a)] -> 'Maybe' a
-- @
lookup :: (Eq i, Foldable f, FoldableWithIndex i g) => i -> f (g a) -> Maybe a
lookup i = preview (folded . ifolded . index i)
-- | Take the first item from a foldable if it exists.
toMaybe :: Foldable f => f a -> Maybe a
toMaybe = preview folded
elemIndex :: (FoldableWithIndex i f, Eq a) => a -> f a -> Maybe i
elemIndex = elemIndexOf ifolded
elemIndices :: (FoldableWithIndex i f, Eq a) => a -> f a -> [i]
elemIndices = elemIndicesOf ifolded
findIndex :: FoldableWithIndex i f => (a -> Bool) -> f a -> Maybe i
findIndex = findIndexOf ifolded
findIndices :: FoldableWithIndex i f => (a -> Bool) -> f a -> [i]
findIndices = findIndicesOf ifolded
isPrefixOf :: (Foldable f, Foldable g, Eq a) => f a -> g a -> Bool
isPrefixOf f g = F.toList f `List.isPrefixOf` F.toList g
isSuffixOf :: (Foldable f, Foldable g, Eq a) => f a -> g a -> Bool
isSuffixOf f g = F.toList f `List.isSuffixOf` F.toList g
isInfixOf :: (Foldable f, Foldable g, Eq a) => f a -> g a -> Bool
isInfixOf f g = F.toList f `List.isInfixOf` F.toList g
ijover :: AnIndexedSetter (V2 i) s t a b -> (i -> i -> a -> b) -> s -> t
ijover l f = iover l $ \(V2 i j) -> f i j
ijkover :: AnIndexedSetter (V3 i) s t a b -> (i -> i -> i -> a -> b) -> s -> t
ijkover l f = iover l $ \(V3 i j k) -> f i j k
-- Partial functions ---------------------------------------------------
-- | A verson of 'view' that throws an error if no value is present.
sieze :: MonadReader s m => Getting (First a) s a -> m a
sieze l = fromMaybe (error "grab: empty getter") `liftM` preview l
-- | A version of 'toMaybe' that throws an error if no value is present.
snatch :: Foldable f => f a -> a
snatch = fromMaybe (error "gawk: empty getter") . preview folded
-- Monadic extras ------------------------------------------------------
-- | Only perform the action if the predicate returns 'True'.
whenM :: Monad m => m Bool -> m () -> m ()
whenM mbool action = mbool >>= flip when action
-- | Only perform the action if the predicate returns 'False'.
unlessM :: Monad m => m Bool -> m () -> m ()
unlessM mbool action = mbool >>= flip unless action
-- -- | Throw a monadic exception from a String
-- --
-- -- > erroM = throwM . userError
-- errorM :: MonadThrow m => String -> m a
-- errorM = throwM . userError
-- | Perform some operation on 'Just', given the field inside the 'Just'.
--
-- > whenJust Nothing print == return ()
-- > whenJust (Just 1) print == print 1
whenJust :: Applicative m => Maybe a -> (a -> m ()) -> m ()
whenJust mg f = maybe (pure ()) f mg
-- | Like 'whenJust', but where the test can be monadic.
whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m ()
whenJustM mg f = maybe (return ()) f =<< mg
-- Data.List for Monad
-- | A version of 'partition' that works with a monadic predicate.
--
-- > partitionM (Just . even) [1,2,3] == Just ([2], [1,3])
-- > partitionM (const Nothing) [1,2,3] == Nothing
partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a])
partitionM _ [] = return ([], [])
partitionM f (x:xs) = do
res <- f x
(as,bs) <- partitionM f xs
return ([x | res]++as, [x | not res]++bs)
-- -- | A version of 'concatMap' that works with a monadic predicate.
-- concatMapM :: Monad m => (a -> m [b]) -> [a] -> m [b]
-- concatMapM f = liftM concat . mapM f
-- -- | A version of 'mapMaybe' that works with a monadic predicate.
-- mapMaybeM :: Monad m => (a -> m (Maybe b)) -> [a] -> m [b]
-- mapMaybeM f = liftM catMaybes . mapM f
-- Looping
-- | A looping operation, where the predicate returns 'Left' as a seed for the next loop
-- or 'Right' to abort the loop.
loopM :: Monad m => (a -> m (Either a b)) -> a -> m b
loopM act x = do
res <- act x
case res of
Left x' -> loopM act x'
Right v -> return v
-- | Keep running an operation until it becomes 'False'. As an example:
--
-- @
-- whileM $ do sleep 0.1; notM $ doesFileExist "foo.txt"
-- readFile "foo.txt"
-- @
--
-- If you need some state persisted between each test, use 'loopM'.
whileM :: Monad m => m Bool -> m ()
whileM act = do
b <- act
when b $ whileM act
-- Booleans
-- | Like @if@, but where the test can be monadic.
ifM :: Monad m => m Bool -> m a -> m a -> m a
ifM mb t f = do b <- mb; if b then t else f
-- | Like 'not', but where the test can be monadic.
notM :: Functor m => m Bool -> m Bool
notM = fmap not
-- | The lazy '||' operator lifted to a monad. If the first
-- argument evaluates to 'True' the second argument will not
-- be evaluated.
--
-- > Just True ||^ undefined == Just True
-- > Just False ||^ Just True == Just True
-- > Just False ||^ Just False == Just False
(||^) :: Monad m => m Bool -> m Bool -> m Bool
(||^) a b = ifM a (return True) b
-- | The lazy '&&' operator lifted to a monad. If the first
-- argument evaluates to 'False' the second argument will not
-- be evaluated.
--
-- > Just False &&^ undefined == Just False
-- > Just True &&^ Just True == Just True
-- > Just True &&^ Just False == Just False
(&&^) :: Monad m => m Bool -> m Bool -> m Bool
(&&^) a b = ifM a b (return False)
-- Loops
-- | Simple for loop. Counts from /start/ to /end/-1.
for_i :: Monad m => Int -> Int -> (Int -> m ()) -> m ()
for_i n0 !n f = loop n0
where
loop i | i == n = return ()
| otherwise = f i >> loop (i+1)
{-# INLINE for_i #-}
-- | Simple reverse-for loop. Counts from /start/-1 to /end/ (which
-- must be less than /start/).
rfor_i :: Monad m => Int -> Int -> (Int -> m ()) -> m ()
rfor_i n0 !n f = loop n0
where
loop i | i == n = return ()
| otherwise = let i' = i-1 in f i' >> loop i'
{-# INLINE rfor_i #-}
-- | 'previewA' where a no element leads to 'Control.Applicative.empty'.
previewA :: (Alternative f, MonadReader s m) => Getting (First a) s a -> m (f a)
previewA l = maybe empty pure <$> preview l
-- XXX not allowed to repeat indexes
atOrdinals :: (Foldable f, At s) => f (Index s) -> IndexedTraversal' (Index s) s (Maybe (IxValue s))
atOrdinals is f a = atUpdate a <$> (traverse . itraversed) f (a ^@.. foldMap iat is)
atUpdate :: (Foldable f, At s) => s -> f (Index s, Maybe (IxValue s)) -> s
atUpdate = foldr (\(i, a) -> set (at i) a)
ixOrdinals :: (Foldable f, Ixed s) => f (Index s) -> IndexedTraversal' (Index s) s (IxValue s)
ixOrdinals is f a = ixUpdate a <$> (traverse . itraversed) f (a ^@.. foldMap iix is)
ixUpdate :: (Foldable f, Ixed s) => s -> f (Index s, IxValue s) -> s
ixUpdate = foldr (\(i, a) -> set (ix i) a)
-- module Data.List
-- (
-- -- * Basic functions
-- , intersperse -- ?
-- , intercalate -- ?
-- , subsequences -- ?
-- , permutations -- ?
-- -- ** Special folds
-- , concat -- Monoid
-- , concatMap -- Foldable / Monoid
-- -- * Building lists
-- -- ** Scans
-- , scanl -- ?
-- , scanl1 -- ?
-- , scanr -- ?
-- , scanr1 -- ?
-- -- ** Infinite lists
-- , iterate -- ?
-- , repeat -- ?
-- , replicate -- ?
-- , cycle -- ?
-- -- ** Unfolding
-- , unfoldr -- ?
-- -- * Sublists
-- -- ** Extracting sublists
-- , stripPrefix -- Witherable
-- , group
-- , inits
-- , tails
-- -- * Zipping and unzipping lists
-- , zip -- ?
-- , zip3 -- ?
-- , zip4, zip5, zip6, zip7 -- ?
-- , zipWith -- ?
-- , zipWith3 -- ?
-- , zipWith4, zipWith5, zipWith6, zipWith7 -- ?
-- , unzip -- ?
-- , unzip3 -- ?
-- , unzip4, unzip5, unzip6, unzip7 -- ?
-- -- * Special lists
-- -- ** Functions on strings
-- , lines -- ?
-- , words -- ?
-- , unlines -- ?
-- , unwords -- ?
-- -- ** \"Set\" operations
-- , union -- ?
-- , intersect -- ?
-- -- ** Ordered lists
-- , sort -- ?
-- , insert -- ?
-- -- *** User-supplied equality (replacing an @Eq@ context)
-- -- | The predicate is assumed to define an equivalence.
-- , nubBy -- Witherable
-- , deleteBy -- Witherable
-- , deleteFirstsBy -- Witherable
-- , unionBy -- ?
-- , intersectBy -- ?
-- , groupBy -- ?
-- -- *** User-supplied comparison (replacing an @Ord@ context)
-- -- | The function is assumed to define a total ordering.
-- , sortBy -- ?
-- , insertBy -- ?
| cchalmers/optical | src/Optical.hs | bsd-3-clause | 16,237 | 2 | 12 | 4,057 | 4,583 | 2,620 | 1,963 | 434 | 2 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Snap.Internal.Http.Server.Session.Tests (tests) where
------------------------------------------------------------------------------
#if !MIN_VERSION_base(4,6,0)
import Prelude hiding (catch)
#endif
import Control.Concurrent (MVar, forkIO, killThread, modifyMVar_, myThreadId, newChan, newEmptyMVar, newMVar, putMVar, readMVar, takeMVar, threadDelay, throwTo, withMVar)
import Control.Exception.Lifted (AsyncException (ThreadKilled), Exception, SomeException (..), bracket, catch, evaluate, mask, throwIO, try)
import Control.Monad (forM_, liftM, replicateM_, void, when, (>=>))
import Control.Monad.State.Class (modify)
import Data.ByteString.Builder (Builder, byteString, char8, toLazyByteString)
import Data.ByteString.Builder.Extra (flush)
import Data.ByteString.Builder.Internal (newBuffer)
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.CaseInsensitive as CI
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import qualified Data.Map as Map
import Data.Maybe (isNothing)
import Data.Monoid (mappend)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Data.Typeable (Typeable)
import Data.Word (Word64)
import qualified Network.Http.Client as Http
import System.IO.Streams (InputStream, OutputStream)
import qualified System.IO.Streams as Streams
import qualified System.IO.Streams.Concurrent as Streams
import qualified System.IO.Streams.Debug as Streams
import System.Timeout (timeout)
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import qualified Test.Framework.Runners.Console as Console
import Test.HUnit (assertBool, assertEqual)
------------------------------------------------------------------------------
import Snap.Core (Cookie (Cookie, cookieName, cookieValue), Request (rqContentLength, rqCookies, rqHostName, rqLocalHostname, rqPathInfo, rqQueryString, rqURI), Snap, addResponseCookie, escapeHttp, getHeader, getRequest, getsRequest, modifyResponse, readRequestBody, rqParam, rqPostParam, rqQueryParam, sendFile, sendFilePartial, setContentLength, setHeader, setResponseBody, setResponseStatus, terminateConnection, writeBS, writeBuilder, writeLBS)
import Snap.Http.Server.Types (emptyServerConfig, getDefaultTimeout, getIsSecure, getLocalAddress, getLocalHostname, getLocalPort, getLogAccess, getLogError, getNumAcceptLoops, getOnDataFinished, getOnEscape, getOnException, getOnNewRequest, getOnParse, getOnUserHandlerFinished, getRemoteAddress, getRemotePort, getTwiddleTimeout, isNewConnection, setDefaultTimeout, setIsSecure, setLocalHostname, setLogAccess, setLogError, setNumAcceptLoops, setOnDataFinished, setOnEscape, setOnException, setOnNewRequest, setOnParse, setOnUserHandlerFinished)
import Snap.Internal.Http.Server.Date (getLogDateString)
import Snap.Internal.Http.Server.Session (BadRequestException (..), LengthRequiredException (..), TerminateSessionException (..), httpAcceptLoop, httpSession, snapToServerHandler)
import qualified Snap.Internal.Http.Server.TLS as TLS
import Snap.Internal.Http.Server.Types (AcceptFunc (AcceptFunc), PerSessionData (PerSessionData, _isNewConnection), SendFileHandler, ServerConfig (_logError))
import Snap.Test (RequestBuilder)
import qualified Snap.Test as T
import Snap.Test.Common (coverShowInstance, coverTypeableInstance, expectException)
#ifdef OPENSSL
import qualified Network.Socket as N
#endif
------------------------------------------------------------------------------
tests :: [Test]
tests = [ testPong
, testPong1_0
, testDateHeaderDeleted
, testServerHeader
, testBadParses
, testEof
, testHttp100
, testNoHost
, testNoHost1_0
, testChunkedRequest
, testQueryParams
, testPostParams
, testPostParamsReplacementBody
, testCookie
, testSetCookie
, testUserException
, testUserBodyException
, testEscape
, testPostWithoutLength
, testWeirdMissingSlash
, testOnlyQueryString
, testConnectionClose
, testUserTerminate
, testSendFile
, testBasicAcceptLoop
, testTrivials
#ifdef OPENSSL
, testTLSKeyMismatch
#else
, testCoverTLSStubs
#endif
]
------------------------------------------------------------------------------
#ifdef OPENSSL
testTLSKeyMismatch :: Test
testTLSKeyMismatch = testCase "session/tls-key-mismatch" $ do
expectException $ bracket (TLS.bindHttps "127.0.0.1"
(fromIntegral N.aNY_PORT)
"test/cert.pem"
False
"test/bad_key.pem")
(N.close . fst)
(const $ return ())
expectException $ bracket (TLS.bindHttps "127.0.0.1"
(fromIntegral N.aNY_PORT)
"test/cert.pem"
True
"test/bad_key.pem")
(N.close . fst)
(const $ return ())
#else
testCoverTLSStubs :: Test
testCoverTLSStubs = testCase "session/tls-stubs" $ do
expectException $ TLS.bindHttps "127.0.0.1" 9999
"test/cert.pem" False "test/key.pem"
expectException $ TLS.bindHttps "127.0.0.1" 9999
"test/cert.pem" True "test/key.pem"
let (AcceptFunc afunc) = TLS.httpsAcceptFunc undefined undefined
expectException $ mask $ \restore -> afunc restore
let u = undefined
expectException $ TLS.sendFileFunc u u u u u u u
#endif
------------------------------------------------------------------------------
testPong :: Test
testPong = testCase "session/pong" $ do
do
[(resp, body)] <- runRequestPipeline [return ()] snap1
assertEqual "code1" 200 $ Http.getStatusCode resp
assertEqual "body1" pong body
assertEqual "chunked1" Nothing $
Http.getHeader resp "Transfer-Encoding"
do
[(resp, body)] <- runRequestPipeline [return ()] snap2
assertEqual "code2" 200 $ Http.getStatusCode resp
assertEqual "body2" pong body
assertEqual "chunked2" (Just $ CI.mk "chunked") $
fmap CI.mk $
Http.getHeader resp "Transfer-Encoding"
-- test pipelining
do
[_, (resp, body)] <- runRequestPipeline [return (), return ()] snap3
assertEqual "code3" 233 $ Http.getStatusCode resp
assertEqual "reason3" "ZOMG" $ Http.getStatusMessage resp
assertEqual "body3" pong body
assertEqual "chunked3" Nothing $ Http.getHeader resp "Transfer-Encoding"
do
[_, (resp, body)] <- runRequestPipeline [http_1_0, http_1_0] snap3
assertEqual "code4" 233 $ Http.getStatusCode resp
assertEqual "reason4" "ZOMG" $ Http.getStatusMessage resp
assertEqual "body4" pong body
assertEqual "chunked4" Nothing $ Http.getHeader resp "Transfer-Encoding"
where
http_1_0 = do
T.setHttpVersion (1, 0)
T.setHeader "Connection" "keep-alive"
pong = "PONG"
snap1 = writeBS pong >> modifyResponse (setContentLength 4)
snap2 = do
cookies <- getsRequest rqCookies
if null cookies
then writeBS pong
else writeBS "wat"
snap3 = do
modifyResponse (setResponseStatus 233 "ZOMG" . setContentLength 4)
writeBS pong
------------------------------------------------------------------------------
testPong1_0 :: Test
testPong1_0 = testCase "session/pong1_0" $ do
req <- makeRequest (T.setHttpVersion (1, 0) >>
T.setHeader "Connection" "zzz")
out <- getSessionOutput [req] $ writeBS "PONG"
assertBool "200 ok" $ S.isPrefixOf "HTTP/1.0 200 OK\r\n" out
assertBool "PONG" $ S.isSuffixOf "\r\n\r\nPONG" out
------------------------------------------------------------------------------
testDateHeaderDeleted :: Test
testDateHeaderDeleted = testCase "session/dateHeaderDeleted" $ do
[(resp, _)] <- runRequestPipeline [mkRq] snap
assertBool "date header" $ Just "plop" /= Http.getHeader resp "Date"
[_, (resp2, _)] <- runRequestPipeline [mkRq2, mkRq2] snap
assertBool "date header 2" $ Just "plop" /= Http.getHeader resp2 "Date"
where
snap = do
modifyResponse (setHeader "Date" "plop" .
setHeader "Connection" "ok" .
setContentLength 4)
writeBS "PONG"
mkRq = do
T.setHttpVersion (1,0)
T.setHeader "fnargle" "plop"
T.setHeader "Content-Length" "0"
T.setHeader "Connection" "keep-alive"
mkRq2 = do
T.setHeader "fnargle" "plop"
T.setHeader "Content-Length" "0"
T.setHeader "Connection" "keep-alive"
------------------------------------------------------------------------------
testServerHeader :: Test
testServerHeader = testCase "session/serverHeader" $ do
[(resp, _)] <- runRequestPipeline [return ()] snap
assertEqual "server" (Just "blah") $ Http.getHeader resp "Server"
where
snap = modifyResponse $ setHeader "Server" "blah"
------------------------------------------------------------------------------
testBadParses :: Test
testBadParses = testGroup "session/badParses" [
check 1 "Not an HTTP Request"
, check 2 $ S.concat [ "GET / HTTP/1.1\r\n"
, "&*%^(*&*@YS\r\n\r324932\n)"
]
, check 3 "\n"
]
where
check :: Int -> ByteString -> Test
check n txt = testCase ("session/badParses/" ++ show n) $
expectException $ getSessionOutput [txt] (return ())
------------------------------------------------------------------------------
testEof :: Test
testEof = testCase "session/eof" $ do
l <- runRequestPipeline [] snap
assertBool "eof1" $ null l
out <- getSessionOutput [""] snap
assertEqual "eof2" "" out
where
snap = writeBS "OK"
------------------------------------------------------------------------------
testHttp100 :: Test
testHttp100 = testCase "session/expect100" $ do
req <- makeRequest expect100
out <- getSessionOutput [req] (writeBS "OK")
assertBool "100-continue" $
S.isPrefixOf "HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK" out
req2 <- makeRequest expect100_2
out2 <- getSessionOutput [req2] (writeBS "OK")
assertBool "100-continue-2" $
S.isPrefixOf "HTTP/1.0 100 Continue\r\n\r\nHTTP/1.0 200 OK" out2
where
expect100 = do
queryGetParams
T.setHeader "Expect" "100-continue"
expect100_2 = do
T.setHttpVersion (1, 0)
queryGetParams
T.setHeader "Expect" "100-continue"
------------------------------------------------------------------------------
testNoHost :: Test
testNoHost = testCase "session/noHost" $
expectException $
getSessionOutput ["GET / HTTP/1.1\r\n\r\n"] (writeBS "OK")
------------------------------------------------------------------------------
testNoHost1_0 :: Test
testNoHost1_0 = testCase "session/noHost1_0" $ do
out <- getSessionOutput ["GET / HTTP/1.0\r\n\r\n"] snap1
assertBool "no host 1.0" $ S.isSuffixOf "\r\nbackup-localhost" out
out2 <- getSessionOutput ["GET / HTTP/1.0\r\n\r\n"] snap2
assertBool "no host 1.0-2" $ S.isSuffixOf "\r\nbackup-localhost" out2
where
snap1 = getRequest >>= writeBS . rqHostName
snap2 = getRequest >>= writeBS . rqLocalHostname
------------------------------------------------------------------------------
testChunkedRequest :: Test
testChunkedRequest = testCase "session/chunkedRequest" $ do
[(_, body)] <- runRequestPipeline [chunked] snap
assertEqual "chunked" "ok" body
where
snap = do
m <- liftM (getHeader "Transfer-Encoding") getRequest
if m == Just "chunked"
then readRequestBody 2048 >>= writeLBS
else writeBS "not ok"
chunked = do
T.put "/" "text/plain" "ok"
T.setHeader "Transfer-Encoding" "chunked"
------------------------------------------------------------------------------
testQueryParams :: Test
testQueryParams = testCase "session/queryParams" $ do
[(_, body)] <- runRequestPipeline [queryGetParams] snap
assertEqual "queryParams" expected body
where
expected = S.unlines [
"param1=abc,def"
, "param2=def"
, "param1=abc,def"
, "ok"
]
snap = do
rq <- getRequest
let (Just l) = rqParam "param1" rq
writeBS $ S.concat [ "param1="
, S.intercalate "," l
, "\n" ]
let (Just m) = rqParam "param2" rq
writeBS $ S.concat [ "param2="
, S.intercalate "," m
, "\n"]
let (Just l') = rqQueryParam "param1" rq
writeBS $ S.concat [ "param1="
, S.intercalate "," l'
, "\n" ]
let z = if isNothing $ rqPostParam "param1" rq
then "ok\n" else "bad\n"
writeBS z
return ()
------------------------------------------------------------------------------
testPostParams :: Test
testPostParams = testCase "session/postParams" $ do
[(_, body)] <- runRequestPipeline [queryPostParams] snap
assertEqual "postParams" expected body
where
expected = S.unlines [
"param1=abc,abc"
, "param2=def ,zzz"
, "param1=abc,abc"
, "ok"
, "param2=zzz"
]
snap = do
rq <- getRequest
let (Just l) = rqParam "param1" rq
writeBS $ S.concat [ "param1="
, S.intercalate "," l
, "\n" ]
let (Just m) = rqParam "param2" rq
writeBS $ S.concat [ "param2="
, S.intercalate "," m
, "\n"]
let (Just l') = rqQueryParam "param1" rq
writeBS $ S.concat [ "param1="
, S.intercalate "," l'
, "\n" ]
let z = if isNothing $ rqPostParam "param1" rq
then "ok\n" else "bad\n"
writeBS z
let (Just p) = rqPostParam "param2" rq
writeBS $ S.concat [ "param2="
, S.intercalate "," p
, "\n" ]
return ()
------------------------------------------------------------------------------
testPostParamsReplacementBody :: Test
testPostParamsReplacementBody =
testCase "session/postParamsReplacementBody" $ do
[(_, body)] <- runRequestPipeline [queryPostParams] snap
assertEqual "postParams" expected body
where
expected = "param2=zzz"
snap = readRequestBody 2048 >>= writeLBS
------------------------------------------------------------------------------
testCookie :: Test
testCookie = testCase "session/cookie" $ do
[(_, body)] <- runRequestPipeline [queryGetParams] snap
assertEqual "cookie" expected body
where
expected = S.unlines [ "foo"
, "bar"
]
snap = do
cookies <- liftM rqCookies getRequest
forM_ cookies $ \cookie -> do
writeBS $ S.unlines [ cookieName cookie
, cookieValue cookie
]
------------------------------------------------------------------------------
testSetCookie :: Test
testSetCookie = testCase "session/setCookie" $ do
mapM_ runTest $ zip3 [1..] expecteds cookies
where
runTest (n, expected, cookie) = do
[(resp, _)] <- runRequestPipeline [queryGetParams] $ snap cookie
assertEqual ("cookie" ++ show (n :: Int))
(Just expected)
(Http.getHeader resp "Set-Cookie")
expecteds = [ S.intercalate "; "
[ "foo=bar"
, "path=/"
, "expires=Thu, 01-Jan-1970 00:16:40 GMT"
, "domain=localhost"
]
, "foo=bar"
, "foo=bar; Secure; HttpOnly"
]
cookies = [ Cookie "foo" "bar" (Just $ posixSecondsToUTCTime 1000)
(Just "localhost") (Just "/") False False
, Cookie "foo" "bar" Nothing Nothing Nothing False False
, Cookie "foo" "bar" Nothing Nothing Nothing True True
]
snap cookie = do
modifyResponse $ addResponseCookie cookie
------------------------------------------------------------------------------
testUserException :: Test
testUserException = testCase "session/userException" $ do
expectException $ runRequestPipeline [queryGetParams] snap
where
snap = throwIO TestException
------------------------------------------------------------------------------
testUserBodyException :: Test
testUserBodyException = testCase "session/userBodyException" $ do
expectException $ runRequestPipeline [queryGetParams] snap
where
snap = modifyResponse $ setResponseBody $ \os -> do
Streams.write (Just (byteString "hi" `mappend` flush)) os
throwIO TestException
------------------------------------------------------------------------------
testEscape :: Test
testEscape = testCase "session/testEscape" $ do
req <- makeRequest (return ())
out <- getSessionOutput [req, "OK?"] snap
assertEqual "escape" "OK" out
where
snap = escapeHttp $ \tickle readEnd writeEnd -> do
l <- Streams.toList readEnd
tickle (max 20)
let s = if l == ["OK?"]
then "OK"
else S.append "BAD: " $ S.pack $ show l
Streams.write (Just $ byteString s) writeEnd
Streams.write Nothing writeEnd
------------------------------------------------------------------------------
testPostWithoutLength :: Test
testPostWithoutLength = testCase "session/postWithoutLength" $ do
let req = S.concat [ "POST / HTTP/1.1\r\nHost: localhost\r\n\r\n"
, "Blah blah blah blah blah"
]
is <- Streams.fromList [req]
(os, getInput) <- listOutputStream
expectException $ runSession is os (return ())
out <- liftM S.concat getInput
assertBool "post without length" $
S.isPrefixOf "HTTP/1.1 411 Length Required" out
------------------------------------------------------------------------------
testWeirdMissingSlash :: Test
testWeirdMissingSlash = testCase "session/weirdMissingSlash" $ do
do
let req = "GET foo/bar?z HTTP/1.0\r\n\r\n"
out <- getSessionOutput [req] snap
assertBool "missing slash" $ expected1 `S.isSuffixOf` out
do
let req = "GET /foo/bar?z HTTP/1.0\r\n\r\n"
out <- getSessionOutput [req] snap
assertBool "with slash" $ expected2 `S.isSuffixOf` out
where
expected1 = S.concat [ "\r\n\r\n"
, "foo/bar?z\n"
, "foo/bar\n"
, "z\n"
]
expected2 = S.concat [ "\r\n\r\n"
, "/foo/bar?z\n"
, "foo/bar\n"
, "z\n"
]
p s = writeBuilder $ byteString s `mappend` char8 '\n'
snap = do
rq <- getRequest
p $ rqURI rq
p $ rqPathInfo rq
p $ rqQueryString rq
------------------------------------------------------------------------------
testOnlyQueryString :: Test
testOnlyQueryString = testCase "session/onlyQueryString" $ do
do
let req = "GET ?z HTTP/1.0\r\n\r\n"
out <- getSessionOutput [req] snap
assertBool "missing slash" $ expected `S.isSuffixOf` out
where
expected = S.concat [ "\r\n\r\n"
, "?z\n"
, "\n"
, "z\n"
]
p s = writeBuilder $ byteString s `mappend` char8 '\n'
snap = do
rq <- getRequest
p $ rqURI rq
p $ rqPathInfo rq
p $ rqQueryString rq
------------------------------------------------------------------------------
testConnectionClose :: Test
testConnectionClose = testCase "session/connectionClose" $ do
do
[(resp, _)] <- runRequestPipeline [return (), return ()] snap
assertEqual "close1" (Just $ CI.mk "close") $
fmap CI.mk $
Http.getHeader resp "Connection"
do
[(resp, _)] <- runRequestPipeline [http1_0, http1_0] snap
assertEqual "close2" (Just $ CI.mk "close") $
fmap CI.mk $
Http.getHeader resp "Connection"
do
[(resp, _)] <- runRequestPipeline [http1_0_2, http1_0] (return ())
assertEqual "close3" (Just $ CI.mk "close") $
fmap CI.mk $
Http.getHeader resp "Connection"
where
http1_0 = T.setHttpVersion (1, 0)
http1_0_2 = T.setHttpVersion (1, 0) >> T.setHeader "Connection" "fnargle"
snap = modifyResponse $ setHeader "Connection" "close"
------------------------------------------------------------------------------
testUserTerminate :: Test
testUserTerminate = testCase "session/userTerminate" $ do
expectException $ runRequestPipeline [return ()] snap
where
snap = terminateConnection TestException
------------------------------------------------------------------------------
testSendFile :: Test
testSendFile = testCase "session/sendFile" $ do
[(_, out1)] <- runRequestPipeline [return ()] snap1
[(_, out2)] <- runRequestPipeline [return ()] snap2
assertEqual "sendfile1" "TESTING 1-2-3\n" out1
assertEqual "sendfile2" "EST" out2
where
snap1 = sendFile "test/dummy.txt"
snap2 = sendFilePartial "test/dummy.txt" (1,4)
------------------------------------------------------------------------------
testBasicAcceptLoop :: Test
testBasicAcceptLoop = testCase "session/basicAcceptLoop" $
replicateM_ 1000 $ do
outputs <- runAcceptLoop [return ()] (return ())
let [Output out] = outputs
void (evaluate out) `catch` \(e::SomeException) -> do
throwIO e
assertBool "basic accept" $ S.isPrefixOf "HTTP/1.1 200 OK\r\n" out
------------------------------------------------------------------------------
testTrivials :: Test
testTrivials = testCase "session/trivials" $ do
coverShowInstance $ TerminateSessionException
$ SomeException BadRequestException
coverShowInstance LengthRequiredException
coverShowInstance BadRequestException
coverShowInstance $ TLS.TLSException "ok"
coverTypeableInstance (undefined :: TerminateSessionException)
coverTypeableInstance (undefined :: BadRequestException)
coverTypeableInstance (undefined :: LengthRequiredException)
coverTypeableInstance (undefined :: TLS.TLSException)
expectException (getOnNewRequest emptyServerConfig undefined >>= evaluate)
is <- Streams.fromList []
(os, _) <- Streams.listOutputStream
psd <- makePerSessionData is os
isNewConnection psd >>= assertEqual "new connection" False
-- cover getters
let !_ = getTwiddleTimeout psd
let !_ = getRemotePort psd
let !_ = getRemoteAddress psd
let !_ = getLocalPort psd
let !_ = getLocalAddress psd
getOnParse emptyServerConfig undefined undefined
getOnEscape emptyServerConfig undefined
getOnException emptyServerConfig undefined undefined
getOnDataFinished emptyServerConfig undefined undefined undefined
getOnUserHandlerFinished emptyServerConfig undefined undefined undefined
getLogError emptyServerConfig undefined
getLogAccess emptyServerConfig undefined undefined undefined
let !_ = getLogError emptyServerConfig
let !_ = getLocalHostname emptyServerConfig
let !_ = getDefaultTimeout emptyServerConfig
let !_ = getNumAcceptLoops emptyServerConfig
let !_ = getIsSecure emptyServerConfig
!x <- getLogDateString
threadDelay $ 2 * seconds
!y <- getLogDateString
assertBool (concat ["log dates: ", show x, ", ", show y]) $ x /= y
---------------------
-- query fragments --
---------------------
------------------------------------------------------------------------------
queryGetParams :: RequestBuilder IO ()
queryGetParams = do
T.get "/foo/bar.html" $ Map.fromList [ ("param1", ["abc", "def"])
, ("param2", ["def"])
]
T.addCookies [ Cookie "foo" "bar" Nothing (Just "localhost") (Just "/")
False False ]
modify $ \rq -> rq { rqContentLength = Just 0 }
------------------------------------------------------------------------------
queryPostParams :: RequestBuilder IO ()
queryPostParams = do
T.postUrlEncoded "/" $ Map.fromList [ ("param2", ["zzz"]) ]
T.setQueryStringRaw "param1=abc¶m2=def%20+¶m1=abc"
-----------------------
-- utility functions --
-----------------------
------------------------------------------------------------------------------
_run :: [Test] -> IO ()
_run l = Console.defaultMainWithArgs l ["--plain"]
------------------------------------------------------------------------------
-- | Given a request builder, produce the HTTP request as a ByteString.
makeRequest :: RequestBuilder IO a -> IO ByteString
makeRequest = (T.buildRequest . void) >=> T.requestToString
------------------------------------------------------------------------------
mockSendFileHandler :: OutputStream ByteString -> SendFileHandler
mockSendFileHandler os !_ hdrs fp start nbytes = do
let hstr = toByteString hdrs
Streams.write (Just hstr) os
Streams.withFileAsInputStartingAt (fromIntegral start) fp $
Streams.takeBytes (fromIntegral nbytes) >=> Streams.supplyTo os
Streams.write Nothing os
------------------------------------------------------------------------------
-- | Fill in a 'PerSessionData' with some dummy values.
makePerSessionData :: InputStream ByteString
-> OutputStream ByteString
-> IO PerSessionData
makePerSessionData readEnd writeEnd = do
forceConnectionClose <- newIORef False
let twiddleTimeout f = let z = f 0 in z `seq` return $! ()
let localAddress = "127.0.0.1"
let remoteAddress = "127.0.0.1"
let remotePort = 43321
newConnectionRef <- newIORef False
let psd = PerSessionData forceConnectionClose
twiddleTimeout
newConnectionRef
(mockSendFileHandler writeEnd)
localAddress
80
remoteAddress
remotePort
readEnd
writeEnd
return psd
------------------------------------------------------------------------------
-- | Make a pipe -- the two Input/OutputStream pairs will communicate with each
-- other from separate threads by using 'Chan's.
makePipe :: PipeFunc
makePipe = do
chan1 <- newChan
chan2 <- newChan
clientReadEnd <- Streams.chanToInput chan1
clientWriteEnd <- Streams.chanToOutput chan2 >>=
Streams.contramapM (evaluate . S.copy)
serverReadEnd <- Streams.chanToInput chan2
serverWriteEnd <- Streams.chanToOutput chan1 >>=
Streams.contramapM (evaluate . S.copy)
return ((clientReadEnd, clientWriteEnd), (serverReadEnd, serverWriteEnd))
------------------------------------------------------------------------------
-- | Make a pipe -- the two Input/OutputStream pairs will communicate with each
-- other from separate threads by using 'Chan's. Data moving through the
-- streams will be logged to stdout.
_makeDebugPipe :: ByteString -> PipeFunc
_makeDebugPipe name = do
chan1 <- newChan
chan2 <- newChan
clientReadEnd <- Streams.chanToInput chan1 >>=
Streams.debugInputBS (S.append name "/client-rd")
Streams.stderr
clientWriteEnd <- Streams.chanToOutput chan2 >>=
Streams.debugOutputBS (S.append name "/client-wr")
Streams.stderr >>=
Streams.contramapM (evaluate . S.copy)
serverReadEnd <- Streams.chanToInput chan2 >>=
Streams.debugInputBS (S.append name "/server-rd")
Streams.stderr
serverWriteEnd <- Streams.chanToOutput chan1 >>=
Streams.debugOutputBS (S.append name "/server-wr")
Streams.stderr >>=
Streams.contramapM (evaluate . S.copy)
return ((clientReadEnd, clientWriteEnd), (serverReadEnd, serverWriteEnd))
------------------------------------------------------------------------------
type PipeFunc = IO ( (InputStream ByteString, OutputStream ByteString)
, (InputStream ByteString, OutputStream ByteString)
)
------------------------------------------------------------------------------
-- | Given a bunch of requests, convert them to bytestrings and pipeline them
-- into the 'httpSession' code, recording the results.
runRequestPipeline :: [T.RequestBuilder IO ()]
-> Snap b
-> IO [(Http.Response, ByteString)]
runRequestPipeline = runRequestPipelineDebug makePipe
------------------------------------------------------------------------------
-- | Given a bunch of requests, convert them to bytestrings and pipeline them
-- into the 'httpSession' code, recording the results.
runRequestPipelineDebug :: PipeFunc
-> [T.RequestBuilder IO ()]
-> Snap b
-> IO [(Http.Response, ByteString)]
runRequestPipelineDebug pipeFunc rbs handler = dieIfTimeout $ do
((clientRead, clientWrite), (serverRead, serverWrite)) <- pipeFunc
sigClient <- newEmptyMVar
results <- newMVar []
forM_ rbs $ makeRequest >=> flip Streams.write clientWrite . Just
Streams.write Nothing clientWrite
myTid <- myThreadId
conn <- Http.makeConnection "localhost"
(return ())
clientWrite
clientRead
bracket (do ctid <- mask $ \restore ->
forkIO $ clientThread restore myTid clientRead conn
results sigClient
stid <- forkIO $ serverThread myTid serverRead serverWrite
return (ctid, stid))
(\(ctid, stid) -> mapM_ killThread [ctid, stid])
(\_ -> await sigClient)
readMVar results
where
await sig = takeMVar sig >>= either throwIO (const $ return ())
serverThread myTid serverRead serverWrite = do
runSession serverRead serverWrite handler
`catch` \(e :: SomeException) -> throwTo myTid e
clientThread restore myTid clientRead conn results sig =
(try (restore loop) >>= putMVar (sig :: MVar (Either SomeException ())))
`catch` \(e :: SomeException) -> throwTo myTid e
where
loop = do
eof <- Streams.atEOF clientRead
if eof
then return ()
else do
(resp, body) <- Http.receiveResponse conn $ \rsp istr -> do
!out <- liftM S.concat $ Streams.toList istr
return (rsp, out)
modifyMVar_ results (return . (++ [(resp, body)]))
loop
------------------------------------------------------------------------------
getSessionOutput :: [ByteString]
-> Snap a
-> IO ByteString
getSessionOutput input snap = do
is <- Streams.fromList input >>= Streams.mapM (evaluate . S.copy)
(os0, getList) <- Streams.listOutputStream
os <- Streams.contramapM (evaluate . S.copy) os0
runSession is os snap
liftM S.concat getList
------------------------------------------------------------------------------
runSession :: InputStream ByteString
-> OutputStream ByteString
-> Snap a
-> IO ()
runSession readEnd writeEnd handler = do
buffer <- newBuffer 64000
perSessionData <- makePerSessionData readEnd writeEnd
httpSession buffer (snapToServerHandler handler)
(makeServerConfig ())
perSessionData
Streams.write Nothing writeEnd
------------------------------------------------------------------------------
makeServerConfig :: hookState -> ServerConfig hookState
makeServerConfig hs = setOnException onEx .
setOnNewRequest onStart .
setLogError logErr .
setLogAccess logAccess .
setOnDataFinished onDataFinished .
setOnEscape onEscape .
setOnUserHandlerFinished onUserHandlerFinished .
setDefaultTimeout 10 .
setLocalHostname "backup-localhost" .
setIsSecure False .
setNumAcceptLoops 1 .
setOnParse onParse $
emptyServerConfig
where
onStart !psd = do
void $ readIORef (_isNewConnection psd) >>= evaluate
return hs
logAccess !_ !_ !_ = return $! ()
logErr !e = void $ evaluate $ toByteString e
onParse !_ !_ = return $! ()
onUserHandlerFinished !_ !_ !_ = return $! ()
onDataFinished !_ !_ !_ = return $! ()
onEx !_ !e = throwIO e
onEscape !_ = return $! ()
------------------------------------------------------------------------------
listOutputStream :: IO (OutputStream ByteString, IO [ByteString])
listOutputStream = do
(os, out) <- Streams.listOutputStream
os' <- Streams.contramapM (evaluate . S.copy) os
return (os', out)
------------------------------------------------------------------------------
data TestException = TestException
deriving (Typeable, Show)
instance Exception TestException
------------------------------------------------------------------------------
data Result = SendFile ByteString FilePath Word64 Word64
| Output ByteString
deriving (Eq, Ord, Show)
------------------------------------------------------------------------------
runAcceptLoop :: [T.RequestBuilder IO ()]
-> Snap a
-> IO [Result]
runAcceptLoop requests snap = dieIfTimeout $ do
-- make sure we don't log error on ThreadKilled.
(_, errs') <- run afuncSuicide
assertBool ("errs': " ++ show errs') $ null errs'
-- make sure we gobble IOException.
count <- newIORef 0
(_, errs'') <- run $ afuncIOException count
assertBool ("errs'': " ++ show errs'') $ length errs'' == 2
liftM fst $ run acceptFunc
where
--------------------------------------------------------------------------
run afunc = do
reqStreams <- Streams.fromList requests >>=
Streams.mapM makeRequest >>=
Streams.lockingInputStream
outputs <- newMVar []
lock <- newMVar ()
err <- newMVar []
httpAcceptLoop (snapToServerHandler snap) (config err) $
afunc reqStreams outputs lock
out <- takeMVar outputs
errs <- takeMVar err
return (out, errs)
--------------------------------------------------------------------------
config mvar = (makeServerConfig ()) {
_logError = \b -> let !s = toByteString b
in modifyMVar_ mvar $ \xs -> do
void (evaluate s)
return (xs ++ [s])
}
--------------------------------------------------------------------------
afuncSuicide :: InputStream ByteString
-> MVar [Result]
-> MVar ()
-> AcceptFunc
afuncSuicide _ _ lock = AcceptFunc $ \restore ->
restore $ withMVar lock (\_ -> throwIO ThreadKilled)
--------------------------------------------------------------------------
afuncIOException :: IORef Int
-> InputStream ByteString
-> MVar [Result]
-> MVar ()
-> AcceptFunc
afuncIOException ref _ _ lock = AcceptFunc $ \restore ->
restore $ withMVar lock $ const $ do
x <- readIORef ref
writeIORef ref $! x + 1
if x >= 2
then throwIO ThreadKilled
else throwIO $ userError "hello"
--------------------------------------------------------------------------
acceptFunc :: InputStream ByteString
-> MVar [Result]
-> MVar ()
-> AcceptFunc
acceptFunc inputStream output lock = AcceptFunc $ \restore -> restore $ do
void $ takeMVar lock
b <- atEOF
when b $ myThreadId >>= killThread
os <- Streams.makeOutputStream out >>=
Streams.contramap S.copy
return (sendFileFunc, "localhost", 80, "localhost", 55555, inputStream,
os, putMVar lock ())
where
atEOF = Streams.peek inputStream >>= maybe (return True) f
where
f x | S.null x = do void $ Streams.read inputStream
atEOF
| otherwise = return False
out (Just s) | S.null s = return ()
out (Just s) = modifyMVar_ output $ return . (++ [Output s])
out Nothing = return ()
sendFileFunc !_ !bldr !fp !st !end =
modifyMVar_ output $
return . (++ [(SendFile (toByteString bldr) fp st end)])
------------------------------------------------------------------------------
dieIfTimeout :: IO a -> IO a
dieIfTimeout m = timeout (10 * seconds) m >>= maybe (error "timeout") return
------------------------------------------------------------------------------
seconds :: Int
seconds = (10::Int) ^ (6::Int)
------------------------------------------------------------------------------
toByteString :: Builder -> S.ByteString
toByteString = S.concat . L.toChunks . toLazyByteString
| sopvop/snap-server | test/Snap/Internal/Http/Server/Session/Tests.hs | bsd-3-clause | 40,432 | 0 | 22 | 12,109 | 8,799 | 4,437 | 4,362 | -1 | -1 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Network/Wai/Handler/Warp/IORef.hs" #-}
{-# LANGUAGE CPP #-}
module Network.Wai.Handler.Warp.IORef (
module Data.IORef
) where
import Data.IORef
| phischu/fragnix | tests/packages/scotty/Network.Wai.Handler.Warp.IORef.hs | bsd-3-clause | 311 | 0 | 5 | 150 | 25 | 18 | 7 | 6 | 0 |
yes = C { f = (e h) } | mpickering/hlint-refactor | tests/examples/Bracket12.hs | bsd-3-clause | 21 | 1 | 9 | 8 | 27 | 12 | 15 | 1 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, UnboxedTuples #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.IORef
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Mutable references in the IO monad.
--
-----------------------------------------------------------------------------
module Data.IORef
(
-- * IORefs
IORef, -- abstract, instance of: Eq, Typeable
newIORef,
readIORef,
writeIORef,
modifyIORef,
modifyIORef',
atomicModifyIORef,
atomicModifyIORef',
atomicWriteIORef,
#if !defined(__PARALLEL_HASKELL__)
mkWeakIORef,
#endif
-- ** Memory Model
-- $memmodel
) where
import GHC.Base
import GHC.STRef
import GHC.IORef hiding (atomicModifyIORef)
import qualified GHC.IORef
#if !defined(__PARALLEL_HASKELL__)
import GHC.Weak
#endif
#if !defined(__PARALLEL_HASKELL__)
-- |Make a 'Weak' pointer to an 'IORef', using the second argument as a finalizer
-- to run when 'IORef' is garbage-collected
mkWeakIORef :: IORef a -> IO () -> IO (Weak (IORef a))
mkWeakIORef r@(IORef (STRef r#)) f = IO $ \s ->
case mkWeak# r# r f s of (# s1, w #) -> (# s1, Weak w #)
#endif
-- |Mutate the contents of an 'IORef'.
--
-- Be warned that 'modifyIORef' does not apply the function strictly. This
-- means if the program calls 'modifyIORef' many times, but seldomly uses the
-- value, thunks will pile up in memory resulting in a space leak. This is a
-- common mistake made when using an IORef as a counter. For example, the
-- following will likely produce a stack overflow:
--
-- >ref <- newIORef 0
-- >replicateM_ 1000000 $ modifyIORef ref (+1)
-- >readIORef ref >>= print
--
-- To avoid this problem, use 'modifyIORef'' instead.
modifyIORef :: IORef a -> (a -> a) -> IO ()
modifyIORef ref f = readIORef ref >>= writeIORef ref . f
-- |Strict version of 'modifyIORef'
--
-- /Since: 4.6.0.0/
modifyIORef' :: IORef a -> (a -> a) -> IO ()
modifyIORef' ref f = do
x <- readIORef ref
let x' = f x
x' `seq` writeIORef ref x'
-- |Atomically modifies the contents of an 'IORef'.
--
-- This function is useful for using 'IORef' in a safe way in a multithreaded
-- program. If you only have one 'IORef', then using 'atomicModifyIORef' to
-- access and modify it will prevent race conditions.
--
-- Extending the atomicity to multiple 'IORef's is problematic, so it
-- is recommended that if you need to do anything more complicated
-- then using 'Control.Concurrent.MVar.MVar' instead is a good idea.
--
-- 'atomicModifyIORef' does not apply the function strictly. This is important
-- to know even if all you are doing is replacing the value. For example, this
-- will leak memory:
--
-- >ref <- newIORef '1'
-- >forever $ atomicModifyIORef ref (\_ -> ('2', ()))
--
-- Use 'atomicModifyIORef'' or 'atomicWriteIORef' to avoid this problem.
--
atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b
atomicModifyIORef = GHC.IORef.atomicModifyIORef
-- | Strict version of 'atomicModifyIORef'. This forces both the value stored
-- in the 'IORef' as well as the value returned.
--
-- /Since: 4.6.0.0/
atomicModifyIORef' :: IORef a -> (a -> (a,b)) -> IO b
atomicModifyIORef' ref f = do
b <- atomicModifyIORef ref
(\x -> let (a, b) = f x
in (a, a `seq` b))
b `seq` return b
-- | Variant of 'writeIORef' with the \"barrier to reordering\" property that
-- 'atomicModifyIORef' has.
--
-- /Since: 4.6.0.0/
atomicWriteIORef :: IORef a -> a -> IO ()
atomicWriteIORef ref a = do
x <- atomicModifyIORef ref (\_ -> (a, ()))
x `seq` return ()
{- $memmodel
In a concurrent program, 'IORef' operations may appear out-of-order
to another thread, depending on the memory model of the underlying
processor architecture. For example, on x86, loads can move ahead
of stores, so in the following example:
> maybePrint :: IORef Bool -> IORef Bool -> IO ()
> maybePrint myRef yourRef = do
> writeIORef myRef True
> yourVal <- readIORef yourRef
> unless yourVal $ putStrLn "critical section"
>
> main :: IO ()
> main = do
> r1 <- newIORef False
> r2 <- newIORef False
> forkIO $ maybePrint r1 r2
> forkIO $ maybePrint r2 r1
> threadDelay 1000000
it is possible that the string @"critical section"@ is printed
twice, even though there is no interleaving of the operations of the
two threads that allows that outcome. The memory model of x86
allows 'readIORef' to happen before the earlier 'writeIORef'.
The implementation is required to ensure that reordering of memory
operations cannot cause type-correct code to go wrong. In
particular, when inspecting the value read from an 'IORef', the
memory writes that created that value must have occurred from the
point of view of the current thread.
'atomicModifyIORef' acts as a barrier to reordering. Multiple
'atomicModifyIORef' operations occur in strict program order. An
'atomicModifyIORef' is never observed to take place ahead of any
earlier (in program order) 'IORef' operations, or after any later
'IORef' operations.
-}
| frantisekfarka/ghc-dsi | libraries/base/Data/IORef.hs | bsd-3-clause | 5,378 | 0 | 15 | 1,131 | 590 | 343 | 247 | 41 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.IO.Buffer
-- Copyright : (c) The University of Glasgow 2008
-- License : see libraries/base/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- Buffers used in the IO system
--
-----------------------------------------------------------------------------
module GHC.IO.Buffer (
-- * Buffers of any element
Buffer(..), BufferState(..), CharBuffer, CharBufElem,
-- ** Creation
newByteBuffer,
newCharBuffer,
newBuffer,
emptyBuffer,
-- ** Insertion/removal
bufferRemove,
bufferAdd,
slideContents,
bufferAdjustL,
-- ** Inspecting
isEmptyBuffer,
isFullBuffer,
isFullCharBuffer,
isWriteBuffer,
bufferElems,
bufferAvailable,
summaryBuffer,
-- ** Operating on the raw buffer as a Ptr
withBuffer,
withRawBuffer,
-- ** Assertions
checkBuffer,
-- * Raw buffers
RawBuffer,
readWord8Buf,
writeWord8Buf,
RawCharBuffer,
peekCharBuf,
readCharBuf,
writeCharBuf,
readCharBufPtr,
writeCharBufPtr,
charSize,
) where
import GHC.Base
-- import GHC.IO
import GHC.Num
import GHC.Ptr
import GHC.Word
import GHC.Show
import GHC.Real
import Foreign.C.Types
import Foreign.ForeignPtr
import Foreign.Storable
-- Char buffers use either UTF-16 or UTF-32, with the endianness matching
-- the endianness of the host.
--
-- Invariants:
-- * a Char buffer consists of *valid* UTF-16 or UTF-32
-- * only whole characters: no partial surrogate pairs
#define CHARBUF_UTF32
-- #define CHARBUF_UTF16
--
-- NB. it won't work to just change this to CHARBUF_UTF16. Some of
-- the code to make this work is there, and it has been tested with
-- the Iconv codec, but there are some pieces that are known to be
-- broken. In particular, the built-in codecs
-- e.g. GHC.IO.Encoding.UTF{8,16,32} need to use isFullCharBuffer or
-- similar in place of the ow >= os comparisons.
-- ---------------------------------------------------------------------------
-- Raw blocks of data
type RawBuffer e = ForeignPtr e
readWord8Buf :: RawBuffer Word8 -> Int -> IO Word8
readWord8Buf arr ix = withForeignPtr arr $ \p -> peekByteOff p ix
writeWord8Buf :: RawBuffer Word8 -> Int -> Word8 -> IO ()
writeWord8Buf arr ix w = withForeignPtr arr $ \p -> pokeByteOff p ix w
#ifdef CHARBUF_UTF16
type CharBufElem = Word16
#else
type CharBufElem = Char
#endif
type RawCharBuffer = RawBuffer CharBufElem
peekCharBuf :: RawCharBuffer -> Int -> IO Char
peekCharBuf arr ix = withForeignPtr arr $ \p -> do
(c,_) <- readCharBufPtr p ix
return c
{-# INLINE readCharBuf #-}
readCharBuf :: RawCharBuffer -> Int -> IO (Char, Int)
readCharBuf arr ix = withForeignPtr arr $ \p -> readCharBufPtr p ix
{-# INLINE writeCharBuf #-}
writeCharBuf :: RawCharBuffer -> Int -> Char -> IO Int
writeCharBuf arr ix c = withForeignPtr arr $ \p -> writeCharBufPtr p ix c
{-# INLINE readCharBufPtr #-}
readCharBufPtr :: Ptr CharBufElem -> Int -> IO (Char, Int)
#ifdef CHARBUF_UTF16
readCharBufPtr p ix = do
c1 <- peekElemOff p ix
if (c1 < 0xd800 || c1 > 0xdbff)
then return (chr (fromIntegral c1), ix+1)
else do c2 <- peekElemOff p (ix+1)
return (unsafeChr ((fromIntegral c1 - 0xd800)*0x400 +
(fromIntegral c2 - 0xdc00) + 0x10000), ix+2)
#else
readCharBufPtr p ix = do c <- peekElemOff (castPtr p) ix; return (c, ix+1)
#endif
{-# INLINE writeCharBufPtr #-}
writeCharBufPtr :: Ptr CharBufElem -> Int -> Char -> IO Int
#ifdef CHARBUF_UTF16
writeCharBufPtr p ix ch
| c < 0x10000 = do pokeElemOff p ix (fromIntegral c)
return (ix+1)
| otherwise = do let c' = c - 0x10000
pokeElemOff p ix (fromIntegral (c' `div` 0x400 + 0xd800))
pokeElemOff p (ix+1) (fromIntegral (c' `mod` 0x400 + 0xdc00))
return (ix+2)
where
c = ord ch
#else
writeCharBufPtr p ix ch = do pokeElemOff (castPtr p) ix ch; return (ix+1)
#endif
charSize :: Int
#ifdef CHARBUF_UTF16
charSize = 2
#else
charSize = 4
#endif
-- ---------------------------------------------------------------------------
-- Buffers
-- | A mutable array of bytes that can be passed to foreign functions.
--
-- The buffer is represented by a record, where the record contains
-- the raw buffer and the start/end points of the filled portion. The
-- buffer contents itself is mutable, but the rest of the record is
-- immutable. This is a slightly odd mix, but it turns out to be
-- quite practical: by making all the buffer metadata immutable, we
-- can have operations on buffer metadata outside of the IO monad.
--
-- The "live" elements of the buffer are those between the 'bufL' and
-- 'bufR' offsets. In an empty buffer, 'bufL' is equal to 'bufR', but
-- they might not be zero: for exmaple, the buffer might correspond to
-- a memory-mapped file and in which case 'bufL' will point to the
-- next location to be written, which is not necessarily the beginning
-- of the file.
data Buffer e
= Buffer {
bufRaw :: !(RawBuffer e),
bufState :: BufferState,
bufSize :: !Int, -- in elements, not bytes
bufL :: !Int, -- offset of first item in the buffer
bufR :: !Int -- offset of last item + 1
}
#ifdef CHARBUF_UTF16
type CharBuffer = Buffer Word16
#else
type CharBuffer = Buffer Char
#endif
data BufferState = ReadBuffer | WriteBuffer deriving (Eq)
withBuffer :: Buffer e -> (Ptr e -> IO a) -> IO a
withBuffer Buffer{ bufRaw=raw } f = withForeignPtr (castForeignPtr raw) f
withRawBuffer :: RawBuffer e -> (Ptr e -> IO a) -> IO a
withRawBuffer raw f = withForeignPtr (castForeignPtr raw) f
isEmptyBuffer :: Buffer e -> Bool
isEmptyBuffer Buffer{ bufL=l, bufR=r } = l == r
isFullBuffer :: Buffer e -> Bool
isFullBuffer Buffer{ bufR=w, bufSize=s } = s == w
-- if a Char buffer does not have room for a surrogate pair, it is "full"
isFullCharBuffer :: Buffer e -> Bool
#ifdef CHARBUF_UTF16
isFullCharBuffer buf = bufferAvailable buf < 2
#else
isFullCharBuffer = isFullBuffer
#endif
isWriteBuffer :: Buffer e -> Bool
isWriteBuffer buf = case bufState buf of
WriteBuffer -> True
ReadBuffer -> False
bufferElems :: Buffer e -> Int
bufferElems Buffer{ bufR=w, bufL=r } = w - r
bufferAvailable :: Buffer e -> Int
bufferAvailable Buffer{ bufR=w, bufSize=s } = s - w
bufferRemove :: Int -> Buffer e -> Buffer e
bufferRemove i buf@Buffer{ bufL=r } = bufferAdjustL (r+i) buf
bufferAdjustL :: Int -> Buffer e -> Buffer e
bufferAdjustL l buf@Buffer{ bufR=w }
| l == w = buf{ bufL=0, bufR=0 }
| otherwise = buf{ bufL=l, bufR=w }
bufferAdd :: Int -> Buffer e -> Buffer e
bufferAdd i buf@Buffer{ bufR=w } = buf{ bufR=w+i }
emptyBuffer :: RawBuffer e -> Int -> BufferState -> Buffer e
emptyBuffer raw sz state =
Buffer{ bufRaw=raw, bufState=state, bufR=0, bufL=0, bufSize=sz }
newByteBuffer :: Int -> BufferState -> IO (Buffer Word8)
newByteBuffer c st = newBuffer c c st
newCharBuffer :: Int -> BufferState -> IO CharBuffer
newCharBuffer c st = newBuffer (c * charSize) c st
newBuffer :: Int -> Int -> BufferState -> IO (Buffer e)
newBuffer bytes sz state = do
fp <- mallocForeignPtrBytes bytes
return (emptyBuffer fp sz state)
-- | slides the contents of the buffer to the beginning
slideContents :: Buffer Word8 -> IO (Buffer Word8)
slideContents buf@Buffer{ bufL=l, bufR=r, bufRaw=raw } = do
let elems = r - l
withRawBuffer raw $ \p ->
do _ <- memmove p (p `plusPtr` l) (fromIntegral elems)
return ()
return buf{ bufL=0, bufR=elems }
foreign import ccall unsafe "memmove"
memmove :: Ptr a -> Ptr a -> CSize -> IO (Ptr a)
summaryBuffer :: Buffer a -> String
summaryBuffer buf = "buf" ++ show (bufSize buf) ++ "(" ++ show (bufL buf) ++ "-" ++ show (bufR buf) ++ ")"
-- INVARIANTS on Buffers:
-- * r <= w
-- * if r == w, and the buffer is for reading, then r == 0 && w == 0
-- * a write buffer is never full. If an operation
-- fills up the buffer, it will always flush it before
-- returning.
-- * a read buffer may be full as a result of hLookAhead. In normal
-- operation, a read buffer always has at least one character of space.
checkBuffer :: Buffer a -> IO ()
checkBuffer buf@Buffer{ bufState = state, bufL=r, bufR=w, bufSize=size } = do
check buf (
size > 0
&& r <= w
&& w <= size
&& ( r /= w || state == WriteBuffer || (r == 0 && w == 0) )
&& ( state /= WriteBuffer || w < size ) -- write buffer is never full
)
check :: Buffer a -> Bool -> IO ()
check _ True = return ()
check buf False = error ("buffer invariant violation: " ++ summaryBuffer buf)
| frantisekfarka/ghc-dsi | libraries/base/GHC/IO/Buffer.hs | bsd-3-clause | 9,008 | 10 | 19 | 2,047 | 2,184 | 1,180 | 1,004 | 143 | 2 |
module Fixme where
{-@ hsig :: x:a -> {v:[a] | v == (x:[])} @-}
hsig :: a -> [a]
hsig x = [x]
{-
This crashes with
(VV#F1 = fix#GHC.Types.#58##35#64([x#aJP; fix#GHC.Types.#91##93##35#6m([])]))
z3Pred: error converting (VV#F1 = fix#GHC.Types.#58##35#64([x#aJP; fix#GHC.Types.#91##93##35#6m([])]))
Fatal error: exception Failure("bracket hits exn: TpGen.MakeProver(SMT).Z3RelTypeError
")
Unless these edits
https://github.com/ucsd-progsys/liquid-fixpoint/commit/63e1e1ccfbde4d7a26bd3e328ad111423172a7e9
-}
| mightymoose/liquidhaskell | tests/todo/ListDataCons.hs | bsd-3-clause | 519 | 0 | 6 | 66 | 29 | 18 | 11 | 3 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.UHC
-- Copyright : Andres Loeh 2009
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This module contains most of the UHC-specific code for configuring, building
-- and installing packages.
--
-- Thanks to the authors of the other implementation-specific files, in
-- particular to Isaac Jones, Duncan Coutts and Henning Thielemann, for
-- inspiration on how to design this module.
module Distribution.Simple.UHC (
configure, getInstalledPackages,
buildLib, buildExe, installLib, registerPackage
) where
import Control.Monad
import Data.List
import qualified Data.Map as M ( empty )
import Distribution.Compat.ReadP
import Distribution.InstalledPackageInfo
import Distribution.Package hiding (installedPackageId)
import Distribution.PackageDescription
import Distribution.Simple.BuildPaths
import Distribution.Simple.Compiler as C
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.PackageIndex
import Distribution.Simple.Program
import Distribution.Simple.Utils
import Distribution.Text
import Distribution.Verbosity
import Distribution.Version
import Language.Haskell.Extension
import System.Directory
import System.FilePath
import Distribution.System ( Platform )
-- -----------------------------------------------------------------------------
-- Configuring
configure :: Verbosity -> Maybe FilePath -> Maybe FilePath
-> ProgramConfiguration -> IO (Compiler, Maybe Platform, ProgramConfiguration)
configure verbosity hcPath _hcPkgPath conf = do
(_uhcProg, uhcVersion, conf') <-
requireProgramVersion verbosity uhcProgram
(orLaterVersion (Version [1,0,2] []))
(userMaybeSpecifyPath "uhc" hcPath conf)
let comp = Compiler {
compilerId = CompilerId UHC uhcVersion,
compilerAbiTag = C.NoAbiTag,
compilerCompat = [],
compilerLanguages = uhcLanguages,
compilerExtensions = uhcLanguageExtensions,
compilerProperties = M.empty
}
compPlatform = Nothing
return (comp, compPlatform, conf')
uhcLanguages :: [(Language, C.Flag)]
uhcLanguages = [(Haskell98, "")]
-- | The flags for the supported extensions.
uhcLanguageExtensions :: [(Extension, C.Flag)]
uhcLanguageExtensions =
let doFlag (f, (enable, disable)) = [(EnableExtension f, enable),
(DisableExtension f, disable)]
alwaysOn = ("", ""{- wrong -})
in concatMap doFlag
[(CPP, ("--cpp", ""{- wrong -})),
(PolymorphicComponents, alwaysOn),
(ExistentialQuantification, alwaysOn),
(ForeignFunctionInterface, alwaysOn),
(UndecidableInstances, alwaysOn),
(MultiParamTypeClasses, alwaysOn),
(Rank2Types, alwaysOn),
(PatternSignatures, alwaysOn),
(EmptyDataDecls, alwaysOn),
(ImplicitPrelude, ("", "--no-prelude"{- wrong -})),
(TypeOperators, alwaysOn),
(OverlappingInstances, alwaysOn),
(FlexibleInstances, alwaysOn)]
getInstalledPackages :: Verbosity -> Compiler -> PackageDBStack -> ProgramConfiguration
-> IO InstalledPackageIndex
getInstalledPackages verbosity comp packagedbs conf = do
let compilerid = compilerId comp
systemPkgDir <- rawSystemProgramStdoutConf verbosity uhcProgram conf ["--meta-pkgdir-system"]
userPkgDir <- getUserPackageDir
let pkgDirs = nub (concatMap (packageDbPaths userPkgDir systemPkgDir) packagedbs)
-- putStrLn $ "pkgdirs: " ++ show pkgDirs
-- call to "lines" necessary, because pkgdir contains an extra newline at the end
pkgs <- liftM (map addBuiltinVersions . concat) .
mapM (\ d -> getDirectoryContents d >>= filterM (isPkgDir (display compilerid) d)) .
concatMap lines $ pkgDirs
-- putStrLn $ "pkgs: " ++ show pkgs
let iPkgs =
map mkInstalledPackageInfo $
concatMap parsePackage $
pkgs
-- putStrLn $ "installed pkgs: " ++ show iPkgs
return (fromList iPkgs)
getUserPackageDir :: IO FilePath
getUserPackageDir =
do
homeDir <- getHomeDirectory
return $ homeDir </> ".cabal" </> "lib" -- TODO: determine in some other way
packageDbPaths :: FilePath -> FilePath -> PackageDB -> [FilePath]
packageDbPaths user system db =
case db of
GlobalPackageDB -> [ system ]
UserPackageDB -> [ user ]
SpecificPackageDB path -> [ path ]
-- | Hack to add version numbers to UHC-built-in packages. This should sooner or
-- later be fixed on the UHC side.
addBuiltinVersions :: String -> String
{-
addBuiltinVersions "uhcbase" = "uhcbase-1.0"
addBuiltinVersions "base" = "base-3.0"
addBuiltinVersions "array" = "array-0.2"
-}
addBuiltinVersions xs = xs
-- | Name of the installed package config file.
installedPkgConfig :: String
installedPkgConfig = "installed-pkg-config"
-- | Check if a certain dir contains a valid package. Currently, we are
-- looking only for the presence of an installed package configuration.
-- TODO: Actually make use of the information provided in the file.
isPkgDir :: String -> String -> String -> IO Bool
isPkgDir _ _ ('.' : _) = return False -- ignore files starting with a .
isPkgDir c dir xs = do
let candidate = dir </> uhcPackageDir xs c
-- putStrLn $ "trying: " ++ candidate
doesFileExist (candidate </> installedPkgConfig)
parsePackage :: String -> [PackageId]
parsePackage x = map fst (filter (\ (_,y) -> null y) (readP_to_S parse x))
-- | Create a trivial package info from a directory name.
mkInstalledPackageInfo :: PackageId -> InstalledPackageInfo
mkInstalledPackageInfo p = emptyInstalledPackageInfo
{ installedPackageId = InstalledPackageId (display p),
sourcePackageId = p }
-- -----------------------------------------------------------------------------
-- Building
buildLib :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO ()
buildLib verbosity pkg_descr lbi lib clbi = do
systemPkgDir <- rawSystemProgramStdoutConf verbosity uhcProgram (withPrograms lbi) ["--meta-pkgdir-system"]
userPkgDir <- getUserPackageDir
let runUhcProg = rawSystemProgramConf verbosity uhcProgram (withPrograms lbi)
let uhcArgs = -- set package name
["--pkg-build=" ++ display (packageId pkg_descr)]
-- common flags lib/exe
++ constructUHCCmdLine userPkgDir systemPkgDir
lbi (libBuildInfo lib) clbi
(buildDir lbi) verbosity
-- source files
-- suboptimal: UHC does not understand module names, so
-- we replace periods by path separators
++ map (map (\ c -> if c == '.' then pathSeparator else c))
(map display (libModules lib))
runUhcProg uhcArgs
return ()
buildExe :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Executable -> ComponentLocalBuildInfo -> IO ()
buildExe verbosity _pkg_descr lbi exe clbi = do
systemPkgDir <- rawSystemProgramStdoutConf verbosity uhcProgram (withPrograms lbi) ["--meta-pkgdir-system"]
userPkgDir <- getUserPackageDir
let runUhcProg = rawSystemProgramConf verbosity uhcProgram (withPrograms lbi)
let uhcArgs = -- common flags lib/exe
constructUHCCmdLine userPkgDir systemPkgDir
lbi (buildInfo exe) clbi
(buildDir lbi) verbosity
-- output file
++ ["--output", buildDir lbi </> exeName exe]
-- main source module
++ [modulePath exe]
runUhcProg uhcArgs
constructUHCCmdLine :: FilePath -> FilePath
-> LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo
-> FilePath -> Verbosity -> [String]
constructUHCCmdLine user system lbi bi clbi odir verbosity =
-- verbosity
(if verbosity >= deafening then ["-v4"]
else if verbosity >= normal then []
else ["-v0"])
++ hcOptions UHC bi
-- flags for language extensions
++ languageToFlags (compiler lbi) (defaultLanguage bi)
++ extensionsToFlags (compiler lbi) (usedExtensions bi)
-- packages
++ ["--hide-all-packages"]
++ uhcPackageDbOptions user system (withPackageDB lbi)
++ ["--package=uhcbase"]
++ ["--package=" ++ display (pkgName pkgid) | (_, pkgid) <- componentPackageDeps clbi ]
-- search paths
++ ["-i" ++ odir]
++ ["-i" ++ l | l <- nub (hsSourceDirs bi)]
++ ["-i" ++ autogenModulesDir lbi]
-- cpp options
++ ["--optP=" ++ opt | opt <- cppOptions bi]
-- output path
++ ["--odir=" ++ odir]
-- optimization
++ (case withOptimization lbi of
NoOptimisation -> ["-O0"]
NormalOptimisation -> ["-O1"]
MaximumOptimisation -> ["-O2"])
uhcPackageDbOptions :: FilePath -> FilePath -> PackageDBStack -> [String]
uhcPackageDbOptions user system db = map (\ x -> "--pkg-searchpath=" ++ x)
(concatMap (packageDbPaths user system) db)
-- -----------------------------------------------------------------------------
-- Installation
installLib :: Verbosity -> LocalBuildInfo
-> FilePath -> FilePath -> FilePath
-> PackageDescription -> Library -> IO ()
installLib verbosity _lbi targetDir _dynlibTargetDir builtDir pkg _library = do
-- putStrLn $ "dest: " ++ targetDir
-- putStrLn $ "built: " ++ builtDir
installDirectoryContents verbosity (builtDir </> display (packageId pkg)) targetDir
-- currently hard-coded UHC code generator and variant to use
uhcTarget, uhcTargetVariant :: String
uhcTarget = "bc"
uhcTargetVariant = "plain"
-- root directory for a package in UHC
uhcPackageDir :: String -> String -> FilePath
uhcPackageSubDir :: String -> FilePath
uhcPackageDir pkgid compilerid = pkgid </> uhcPackageSubDir compilerid
uhcPackageSubDir compilerid = compilerid </> uhcTarget </> uhcTargetVariant
-- -----------------------------------------------------------------------------
-- Registering
registerPackage
:: Verbosity
-> InstalledPackageInfo
-> PackageDescription
-> LocalBuildInfo
-> Bool
-> PackageDBStack
-> IO ()
registerPackage verbosity installedPkgInfo pkg lbi inplace _packageDbs = do
let installDirs = absoluteInstallDirs pkg lbi NoCopyDest
pkgdir | inplace = buildDir lbi </> uhcPackageDir (display pkgid) (display compilerid)
| otherwise = libdir installDirs </> uhcPackageSubDir (display compilerid)
createDirectoryIfMissingVerbose verbosity True pkgdir
writeUTF8File (pkgdir </> installedPkgConfig)
(showInstalledPackageInfo installedPkgInfo)
where
pkgid = packageId pkg
compilerid = compilerId (compiler lbi)
| DavidAlphaFox/ghc | libraries/Cabal/Cabal/Distribution/Simple/UHC.hs | bsd-3-clause | 11,353 | 0 | 21 | 2,856 | 2,309 | 1,243 | 1,066 | 184 | 5 |
f xs = case map id xs of
[] -> True
x:xs -> False
| urbanslug/ghc | testsuite/tests/ghci.debugger/scripts/result001.hs | bsd-3-clause | 68 | 1 | 8 | 32 | 39 | 17 | 22 | 3 | 2 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ExistentialQuantification #-}
module CannotDoRep1_0 where
import GHC.Generics
-- We do not support existential quantification
data Dynamic a = forall b. Dynamic b a deriving Generic1
| forked-upstream-packages-for-ghcjs/ghc | testsuite/tests/generics/GenCannotDoRep1_0.hs | bsd-3-clause | 244 | 0 | 6 | 48 | 32 | 21 | 11 | 5 | 0 |
module Main (main) where
import GHC.Conc
import Control.Concurrent
import Control.Exception
import System.Exit
main = do
m <- newEmptyMVar
let action = do setAllocationCounter (10*1024)
enableAllocationLimit
print (length [1..])
forkFinally action (putMVar m)
r <- takeMVar m
case r of
Left e | Just AllocationLimitExceeded <- fromException e -> return ()
_ -> print r >> exitFailure
| urbanslug/ghc | testsuite/tests/concurrent/should_run/allocLimit2.hs | bsd-3-clause | 443 | 0 | 15 | 115 | 155 | 73 | 82 | 15 | 2 |
-- | Interface to the Futhark parser.
module Language.Futhark.Parser
( parseFuthark,
parseExp,
parseModExp,
parseType,
parseValue,
parseValues,
parseDecOrExpIncrM,
ParseError (..),
scanTokensText,
L (..),
Token (..),
)
where
import qualified Data.Text as T
import Language.Futhark.Parser.Lexer
import Language.Futhark.Parser.Parser
import Language.Futhark.Prop
import Language.Futhark.Syntax
-- | Parse an entire Futhark program from the given 'T.Text', using
-- the 'FilePath' as the source name for error messages.
parseFuthark ::
FilePath ->
T.Text ->
Either ParseError UncheckedProg
parseFuthark = parse prog
-- | Parse an Futhark expression from the given 'String', using the
-- 'FilePath' as the source name for error messages.
parseExp ::
FilePath ->
T.Text ->
Either ParseError UncheckedExp
parseExp = parse expression
-- | Parse a Futhark module expression from the given 'String', using the
-- 'FilePath' as the source name for error messages.
parseModExp ::
FilePath ->
T.Text ->
Either ParseError (ModExpBase NoInfo Name)
parseModExp = parse modExpression
-- | Parse an Futhark type from the given 'String', using the
-- 'FilePath' as the source name for error messages.
parseType ::
FilePath ->
T.Text ->
Either ParseError UncheckedTypeExp
parseType = parse futharkType
-- | Parse any Futhark value from the given 'String', using the 'FilePath'
-- as the source name for error messages.
parseValue ::
FilePath ->
T.Text ->
Either ParseError Value
parseValue = parse anyValue
-- | Parse several Futhark values (separated by anything) from the given
-- 'String', using the 'FilePath' as the source name for error
-- messages.
parseValues ::
FilePath ->
T.Text ->
Either ParseError [Value]
parseValues = parse anyValues
| HIPERFIT/futhark | src/Language/Futhark/Parser.hs | isc | 1,817 | 0 | 9 | 338 | 282 | 166 | 116 | 47 | 1 |
module Robot (Robot, initialState, mkRobot, resetName, robotName) where
import Control.Monad.State (StateT)
data Robot = Dummy1
data RunState = Dummy2
initialState :: RunState
initialState = error "You need to implement this function"
mkRobot :: StateT RunState IO Robot
mkRobot = error "You need to implement this function."
resetName :: Robot -> StateT RunState IO ()
resetName robot = error "You need to implement this function."
robotName :: Robot -> IO String
robotName robot = error "You need to implement this function."
| exercism/xhaskell | exercises/practice/robot-name/src/Robot.hs | mit | 534 | 0 | 7 | 86 | 131 | 71 | 60 | 12 | 1 |
--------------------------------------------------------------------------------
-- Sum square difference
-- Problem 6
-- The sum of the squares of the first ten natural numbers is,
-- 1^2 + 2^2 + ... + 10^2 = 385
--
-- The square of the sum of the first ten natural numbers is,
-- (1 + 2 + ... + 10)^2 = 55^2 = 3025
-- Hence the difference between the sum of the squares of the first ten
-- natural numbers and the square of the sum is 3025 − 385 = 2640.
-- Find the difference between the sum of the squares of the first one hundred
-- natural numbers and the square of the sum.
--------------------------------------------------------------------------------
limit = 100
sum_n_1 n = n * (n+1) `div` 2
sum_n_2 n = n * (n+1) * (2*n +1) `div` 6
solve = square_of_sum - sum_of_squares
where
sum_of_squares = sum_n_2 limit
square_of_sum = (sum_n_1 limit) ^2
main = print solve
| bertdouglas/euler-haskell | 001-050/06a.hs | mit | 907 | 0 | 9 | 182 | 126 | 74 | 52 | 7 | 1 |
--duality.hs
module Duality where
data GuessWhat = Chickenbutt deriving Show
data Id a = MkId deriving Show
data Product a b = Product a b deriving Show
data Sum a b =
First a
| Second b
deriving Show
data RecordProduct a b =
RecordProduct { pfirst :: a
, psecond :: b }
deriving (Eq, Show)
newtype NumCow = NumCow Int deriving (Eq, Show)
newtype NumPig = NumPig Int deriving (Eq, Show)
data Farmhouse = Farmhouse NumCow NumPig deriving (Eq, Show)
type Farmhouse' = Product NumCow NumPig --same as Farmhouse
trivialValue :: GuessWhat
trivialValue = Chickenbutt | deciduously/Haskell-First-Principles-Exercises | 3-Getting serious/11-Algebraic Datatypes/code/duality.hs | mit | 619 | 0 | 8 | 155 | 177 | 107 | 70 | 18 | 1 |
module Main where
import Data.Semigroup
import Options.Applicative
import Apple.Maclight
data MaclightOpts = MaclightOpts { backlight :: Light
, lightCommand :: Command
}
options :: Parser MaclightOpts
options = MaclightOpts
<$> argument auto
( metavar "LIGHT"
<> help "The backlight to control (one of 'keyboard' or 'screen')" )
<*> argument auto
( metavar "CMD"
<> help ( unlines ["What to do to the backlight ",
"(one of up, down, max, off, or set=n)"] ))
main :: IO ()
main = execParser parser >>= run
where
parser = info (helper <*> options)
( fullDesc
<> progDesc "Control a Macbook's backlight"
<> header "maclight - a Macbook backlight controller" )
run opts = handleBacklight (backlight opts) (lightCommand opts)
| tych0/maclight | src/maclight.hs | mit | 908 | 0 | 12 | 301 | 192 | 100 | 92 | 22 | 1 |
module Lesson2.BFS.Types where
import Data.Lens.Common (modL)
import Data.List (foldl')
import Data.Hashable (Hashable(..))
import Data.Ord (Ord(..), comparing)
import Data.Set (Set)
import qualified Data.Set as Set
import Lesson2.Types
-------------------------------------------------------------------------------
type BFSGraph = Graph BasicEdge
data BasicEdge a
= BasicEdge {
basicEdgeSource :: Node a
, basicEdgeSink :: Node a
}
-------------------------------------------------------------------------------
instance Show a => Show (BasicEdge a) where
show (BasicEdge a b) = "(" ++ show a ++ ", " ++ show b ++ ")"
instance Hashable a => Hashable (BasicEdge a) where
hash (BasicEdge a b) = foldl' hashWithSalt 1 [a, b]
instance Hashable a => Eq (BasicEdge a) where
a == b = hash a == hash b
instance Hashable a => Ord (BasicEdge a) where
compare = comparing hash
instance EdgeLike BasicEdge where
getEdgeSource = basicEdgeSource
getEdgeSink = basicEdgeSink
getEdgeCost = const Nothing
-------------------------------------------------------------------------------
appendEdge :: Hashable a
=> Node a
-> Node a
-> Graph BasicEdge a
-> Graph BasicEdge a
appendEdge a b = modL graphEdges (Set.union otherSet)
where
otherSet = Set.fromList [BasicEdge a b, BasicEdge b a]
| roman/ai-class-haskell | src/Lesson2/BFS/Types.hs | mit | 1,367 | 0 | 10 | 267 | 419 | 220 | 199 | 32 | 1 |
module Main where
import Criterion.Main (defaultMain)
import Prelude
import qualified Layout.UtilBench as LayoutUtilB
import qualified Foreign.Lua.UtilBench as LuaUtilB
--------------------------------------------------------------------------------
main :: IO ()
main = defaultMain [ LayoutUtilB.benches
, LuaUtilB.benches
]
| rzetterberg/alven | src/bench/Bench.hs | mit | 388 | 0 | 7 | 93 | 63 | 40 | 23 | 8 | 1 |
module TestSuites.LoadCSVSpec (spec) where
--standard
--3rd party
import Test.Hspec.Contrib.HUnit(fromHUnitTest)
import Test.HUnit
--own
import HsPredictor.LoadCSV
import HsPredictor.Queries
import HsPredictor.Types
import HelperFuncs (removeIfExists)
spec = fromHUnitTest $ TestList [
TestLabel ">>stats" test_stats,
TestLabel ">>teams" test_teams,
TestLabel ">>resultsUpcoming" test_resultsUpcoming,
TestLabel ">>resultsAll" test_resultsAll,
TestLabel ">>reloadCSV" test_reloadCSV,
TestLabel ">>getFileContents" test_getFileContents
]
testFilePath = "tests/tmp/test.csv"
testDbPath = "tests/tmp/test.db"
setUp = do
removeIfExists testDbPath
loadCSV testFilePath testDbPath
test_stats = TestCase $ do
setUp
teams <- getTeams testDbPath
s1 <- filterStats "A" teams
s2 <- filterStats "B" teams
assertEqual "A stats" s1 [4,2,0]
assertEqual "B stats" s2 [0,2,4]
where
filterStats t teams = flip getStats testDbPath
((filter (\x -> x==t) teams)!!0)
test_teams = TestCase $ do
setUp
teams <- getTeams testDbPath
(length teams) @?= 4
test_resultsAll = TestCase $ do
setUp
r <- getResultsAll testDbPath
(length r) @?= 14
test_resultsUpcoming = TestCase $ do
setUp
r <- getResultsUpcoming testDbPath
(length r) @?= 2
test_reloadCSV = TestCase $ do
setUp
r <- getResultsAll testDbPath
assertEqual "results all length" (length r) (14)
loadCSV testFilePath testDbPath -- load again
r1 <- getResultsAll testDbPath
(length r1) @?= 14
assertEqual "results before and after" r r1
test_getFileContents = TestCase $ do
c <- getFileContents testFilePath
assertBool "getFileContents" ("" /= c)
| Taketrung/HsPredictor | tests/TestSuites/LoadCSVSpec.hs | mit | 1,708 | 0 | 14 | 330 | 495 | 244 | 251 | 51 | 1 |
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Com.Mysql.Cj.Mysqlx.Protobuf.Error.Severity (Severity(..)) where
import Prelude ((+), (/), (.))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified GHC.Generics as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data Severity = ERROR
| FATAL
deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
instance P'.Mergeable Severity
instance Prelude'.Bounded Severity where
minBound = ERROR
maxBound = FATAL
instance P'.Default Severity where
defaultValue = ERROR
toMaybe'Enum :: Prelude'.Int -> P'.Maybe Severity
toMaybe'Enum 0 = Prelude'.Just ERROR
toMaybe'Enum 1 = Prelude'.Just FATAL
toMaybe'Enum _ = Prelude'.Nothing
instance Prelude'.Enum Severity where
fromEnum ERROR = 0
fromEnum FATAL = 1
toEnum
= P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Com.Mysql.Cj.Mysqlx.Protobuf.Error.Severity") .
toMaybe'Enum
succ ERROR = FATAL
succ _ = Prelude'.error "hprotoc generated code: succ failure for type Com.Mysql.Cj.Mysqlx.Protobuf.Error.Severity"
pred FATAL = ERROR
pred _ = Prelude'.error "hprotoc generated code: pred failure for type Com.Mysql.Cj.Mysqlx.Protobuf.Error.Severity"
instance P'.Wire Severity where
wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum)
wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum)
wireGet 14 = P'.wireGetEnum toMaybe'Enum
wireGet ft' = P'.wireGetErr ft'
wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum
wireGetPacked ft' = P'.wireGetErr ft'
instance P'.GPB Severity
instance P'.MessageAPI msg' (msg' -> Severity) Severity where
getVal m' f' = f' m'
instance P'.ReflectEnum Severity where
reflectEnum = [(0, "ERROR", ERROR), (1, "FATAL", FATAL)]
reflectEnumInfo _
= P'.EnumInfo (P'.makePNF (P'.pack ".Mysqlx.Error.Severity") [] ["Com", "Mysql", "Cj", "Mysqlx", "Protobuf", "Error"] "Severity")
["Com", "Mysql", "Cj", "Mysqlx", "Protobuf", "Error", "Severity.hs"]
[(0, "ERROR"), (1, "FATAL")]
instance P'.TextType Severity where
tellT = P'.tellShow
getT = P'.getRead | naoto-ogawa/h-xproto-mysql | src/Com/Mysql/Cj/Mysqlx/Protobuf/Error/Severity.hs | mit | 2,375 | 0 | 11 | 368 | 638 | 352 | 286 | 51 | 1 |
module Sing where
fstString :: [Char] -> [Char]
fstString x = x ++ " in the rain"
sndString :: [Char] -> [Char]
sndString x = x ++ " over the rainbow"
sing = if (x < y) then fstString x else sndString y
where x = "Singing"
y = "Somewhere"
| rasheedja/HaskellFromFirstPrinciples | Chapter5/fixIt.hs | mit | 252 | 0 | 7 | 63 | 96 | 54 | 42 | 8 | 2 |
module Test.App.Stuff ( tests ) where
import Test.Hspec
import App.Stuff
tests :: IO ()
tests = hspec $ do
describe "Stuff.digits" $ do
it "returns list of digits inside number" $ do
digits 123490 `shouldBe` [1,2,3,4,9,0]
it "returns list of digits inside number" $ do
digits 13490 `shouldBe` [1,3,4,9,0]
describe "Stuff.delFirstMeet" $ do
it "should delete only first meeted symbol" $ do
delFirstMeet ( 3 :: Integer ) [1,2,3,4,3] `shouldBe` [1,2,4,3]
describe "Stuff.countFreq" $ do
it "should return right values" $ do
countFreq ( 3 :: Int ) [1,2,3,3,4,3] `shouldBe` ( 3 :: Int )
it "should return 0 if list not contain this value" $ do
countFreq ( 0 :: Int ) [1,2,3,3,4,3] `shouldBe` ( 0 :: Int )
it "should return 0 for empty list" $ do
countFreq ( 6 :: Int ) [] `shouldBe` ( 0 :: Int )
| triplepointfive/hegine | test/Test/App/Stuff.hs | gpl-2.0 | 860 | 0 | 16 | 211 | 351 | 193 | 158 | 20 | 1 |
module Cryptography.ComputationalProblems.Games.DiscreteGames.Macro where
import Types
import Functions.Application.Macro
import Macro.Arrows
import Macro.Math
import Macro.MetaMacro
-- * Discrete games
-- ** Stop symbol for discrete distinguishers
stopsym_ :: Note
stopsym_ = comm0 "dashv"
stopsym :: Note -> Note
stopsym = (stopsym_ !:)
-- * Reductions for discrete games
-- ** Reduction by transformer
-- | Reduction by given transformer
tred_ :: Note -> Note
tred_ = overset rightarrow
tred :: Note -> Note -> Note
tred = fn . tred_
-- ** Reduction by multiple invocations
mred_ :: Note -> Note
mred_ = (pars cdot_ ^)
mred :: Note -> Note -> Note
mred = (^)
-- | 1 - (1 - x) ^ q
psiq :: Note -> Note -> Note
psiq q = fn $ psi !: q
-- | 1 - (1 - x) ^ (1 / q)
chiq :: Note -> Note -> Note
chiq q = fn $ chi !: q
| NorfairKing/the-notes | src/Cryptography/ComputationalProblems/Games/DiscreteGames/Macro.hs | gpl-2.0 | 878 | 0 | 6 | 218 | 210 | 123 | 87 | 22 | 1 |
{-|
Module : System.Arte.Decode
Description : Main loop for decoding a single trode
Copyright : (c) Greg Hale, 2015
Shea Levy, 2015
License : BSD3
Maintainer : imalsogreg@gmail.com
Stability : experimental
Portability : GHC, Linux
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE BangPatterns #-}
module System.Arte.Decode where
------------------------------------------------------------------------------
import Control.Applicative (pure, (<$>), (<*>))
import Control.Concurrent hiding (Chan)
import Control.Concurrent.Async
import Control.Concurrent.STM
import Control.Lens
import Control.Monad
import Data.Bool
import qualified Data.Aeson as A
import Data.Aeson (Object(..), (.:))
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Foldable as F
import qualified Data.List as L
import qualified Data.Map.Strict as Map
import Data.Maybe
import qualified Data.Text as Text
import Data.Time.Clock
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
import Graphics.Gloss
import Graphics.Gloss.Interface.IO.Game
import qualified Graphics.Gloss.Data.Color as Color
import Options.Applicative
import Pipes
import qualified Pipes.Prelude as P
import Pipes.RealTime
import System.Directory
import System.Exit (exitSuccess)
import System.FilePath ((</>))
import System.IO
import System.Mem (performGC)
import Network.Socket
import qualified Network.Socket.ByteString as BS
import Data.Serialize
------------------------------------------------------------------------------
import Data.Ephys.Cluster
import Data.Ephys.EphysDefs
import Data.Ephys.GlossPictures
import Data.Ephys.OldMWL.FileInfo
import Data.Ephys.OldMWL.Parse
import Data.Ephys.OldMWL.ParseClusterFile
import Data.Ephys.OldMWL.ParsePFile
import Data.Ephys.OldMWL.ParseSpike
import Data.Ephys.PlaceCell
import Data.Ephys.Position
import Data.Ephys.Spike
import Data.Ephys.TrackPosition
import Data.Map.KDMap
import System.Arte.FileUtils
import System.Arte.Net
------------------------------------------------------------------------------
import System.Arte.Decode.Algorithm
import System.Arte.Decode.Config
import System.Arte.Decode.Graphics
import qualified System.Arte.Decode.Histogram as H
import System.Arte.Decode.Types
------------------------------------------------------------------------------
-- | Get the view option that is currently selected.
focusCursor :: DecoderState -- ^ The current decoding state
-> TrodeDrawOption
focusCursor ds = fromMaybe (DrawError "Couldn't index at cursor") $
(ds^.trodeDrawOpt) ^? ix (ds^.clustInd)
------------------------------------------------------------------------------
-- | Generate a 'Picture' displaying the current state.
draw :: DecoderState -- ^ The current decoder state
-> IO Picture
draw ds = do
!p <- readTVarIO $ ds^.pos
!occ <- readTVarIO $ ds^.occupancy
!dPos <- readTVarIO $ ds^.decodedPos :: IO Field
eHist <- translate (-200) 100 <$> makeHistogramScreenPic (ds^.encodeProf) 100 50
dHist <- translate (-200) (-100) <$> makeHistogramScreenPic (ds^.decodeProf) 100 50
let !trackPicture = trackToScreen $ drawTrack defTrack
!posPicture = trackToScreen $ drawPos p
!drawOpt = focusCursor ds
!optsPicture = optsToScreen $ drawOptionsStatePic ds
selectionPic <- case drawOpt of
DrawOccupancy -> return . trackToScreen $ fieldPic occ
DrawDecoding -> return . trackToScreen . fieldPic .
decodeColormap $ dPos
DrawPlaceCell _ dUnit' -> do
u <- readTVarIO dUnit'
return . trackToScreen . fieldPic $ placeField (u^.dpCell) occ
cl@(DrawClusterless _ _) -> mkClusterlessScreenPic cl ds
DrawError e -> return . scale 50 50 $ text e
return $ Pictures [trackPicture, posPicture, optsPicture, selectionPic] --, eHist, dHist]
------------------------------------------------------------------------------
-- | Main action for single-trode decoding
main :: IO ()
main = do
opts <- execParser decoderOpts
print opts
ds <- initialState opts
dsT <- newTVarIO ds
incomingSpikesChan <- atomically newTQueue
putStrLn "Start pos async"
posSock <- socket AF_INET Datagram defaultProtocol
bind posSock $ SockAddrInet (fromIntegral $ psPort $ posSource opts) iNADDR_ANY
ds' <- readTVarIO dsT
print "About to posAsync"
posAsync <- async $ runEffect $ interpretPos opts posSock >->
(forever $ do
p <- await
occ <- liftIO $ atomically $ readTVar (ds'^.occupancy)
liftIO $ print (V.take 5 . V.fromList . L.reverse . L.sort . V.toList $ occ)
lift . atomically $ do
occ <- readTVar (ds^.occupancy)
-- TODO property of the camera: 30 fps
let posField = V.map (/30) $ posToField defTrack p kernel
writeTVar (ds'^.pos) p
writeTVar (ds'^.trackPos) posField
when (p^.speed > runningThresholdSpeed)
(writeTVar (ds'^.occupancy) (updateField (+) occ posField))
)
putStrLn "Start Spike socket asyncs"
sock <- socket AF_INET Datagram defaultProtocol
bind sock $ SockAddrInet 5228 iNADDR_ANY
a <- case clusterless opts of
True -> do
async $ runEffect $ udpSocketProducer 9000 sock >->
(forever $ do
spike <- await
ds2 <- lift . atomically $ readTVar dsT
pos2 <- lift . atomically $ readTVar (ds^.trackPos)
p <- lift . atomically $ readTVar (ds^.pos)
when (clessKeepSpike spike) $
lift (clusterlessAddSpike ds2 p pos2 spike)
)
False -> do
let cbFilePath = ttDir opts
cbFile = cbFilePath </> "cbfile-run"
ttFiles <- getDirectoryContents (ttDir opts)
print $ "TTFiles: " ++ show ttFiles
ttFilePath <- (head . -- TODO s/head/safeHead
filter (`endsIn` ".tt"))
<$> map (ttDir opts </>) <$>
getDirectoryContents (ttDir opts)
clusters' <- getClusters cbFile ttFilePath
case clusters' of
Right clusters -> do
setTrodeClusters defTrack dsT clusters
ds' <- readTVarIO dsT
case ds'^.trode of
Clustered pcTrode ->
async $ runEffect $ udpSocketProducer 9000 sock >->
(forever $ do
spike <- await
let minWid = spikeWidthThreshold defaultClusterlessOpts
when (spikeWidth spike >= minWid && clessKeepSpike spike) $ do
ds2 <- lift . atomically $ readTVar dsT
pos2 <- lift . atomically $ readTVar (ds^.trackPos)
p <- lift . atomically $ readTVar (ds^.pos)
lift (fanoutSpikeToCells ds2 pcTrode p pos2 spike)
return ()
)
_ -> error "Clusterless in clustered context"
let asyncsAndTrodes = [ (a, undefined) ]
reconstructionA <-
async $ if clusterless opts
then runClusterlessReconstruction
defaultClusterlessOpts 0.020 dsT
else runClusterReconstruction undefined 0.020 dsT
fakeMaster <- atomically newTQueue
let spikeAsyncs = map fst asyncsAndTrodes
runGloss opts dsT
putStrLn "Closed filehandles"
putStrLn "wait for asyncs to finish"
_ <- wait posAsync
_ <- mapM wait spikeAsyncs
_ <- wait reconstructionA
return ()
------------------------------------------------------------------------------
-- | Predicate to drop spikes with low enough amplitudes (< amplutdeThreshold)
-- and short enough widths (< spikeWidthThreshold) in clusterless decoding.
clessKeepSpike :: TrodeSpike -- ^ The spike to consider dropping
-> Bool
clessKeepSpike s = amp && wid
where
opt = defaultClusterlessOpts
amp = V.maximum (spikeAmplitudes s) >= amplitudeThreshold opt
wid = spikeWidth s >= spikeWidthThreshold opt
-- | Launch gloss window displaying decoding state.
runGloss :: DecoderArgs -- ^ Decoding parameters
-> TVar DecoderState -- ^ Decoder state
-> IO ()
runGloss opts dsT = do
ds <- initialState opts
playIO (InWindow "ArteDecoder" (700,700) (10,10))
white 100 ds draw (glossInputs dsT) (stepIO dsT)
------------------------------------------------------------------------------
-- | Gloss callback to handle input events
glossInputs :: TVar DecoderState -- ^ Shared decoder state
-> Event -- ^ Gloss event
-> DecoderState -- ^ Pure decoder state from gloss
-> IO DecoderState
glossInputs dsT e ds =
let drawOpt = focusCursor ds in
case e of
EventMotion _ -> return ds
EventKey (SpecialKey KeyEsc) Up _ _ -> exitSuccess
EventKey (SpecialKey k) Up _ _ ->
let f = case k of
KeyRight -> (trodeInd %~ succ) . (clustInd .~ 0)
KeyLeft -> (trodeInd %~ pred) . (clustInd .~ 0)
KeyUp -> clustInd %~ succ
KeyDown -> clustInd %~ pred
_ -> id
in atomically (modifyTVar dsT f) >> return (f ds) -- which copy is actually used?
EventKey _ Down _ _ -> return ds
EventKey (MouseButton LeftButton) Up _ (mouseX,mouseY) ->
case drawOpt of
(DrawClusterless tTrode
(ClessDraw (XChan cX) (YChan cY))) ->
let (treeX, treeY) = screenToSpikes mouseX mouseY
p' = fromMaybe ((ClusterlessPoint
(U.fromList [0,0,0,0]) 1000 (emptyField defTrack)))
(ds^.samplePoint)
p = Just ((p' & pAmplitude . ix cX .~ r2 treeX) &
pAmplitude . ix cY .~ r2 treeY )
ds' = ds & samplePoint .~ p
in atomically (writeTVar dsT ds') >> return ds'
_ -> putStrLn "Ignoring left click" >> return ds
EventKey (MouseButton RightButton) Up _ _ ->
case drawOpt of
(DrawClusterless tTrode (ClessDraw cX cY)) ->
let ds' = ds & samplePoint .~ Nothing
in atomically (writeTVar dsT ds') >> return ds'
_ -> putStrLn "Ignoring right click" >> return ds
_ -> putStrLn ("Ignoring event " ++ show e) >> return ds
------------------------------------------------------------------------------
-- | Step the state one iteration by replacing the pure decoder state handled
-- by gloss with the mutable shared decoder state.
stepIO :: TVar DecoderState -- ^ Shared decoder state
-> Float -- ^ Time since last step
-> DecoderState -- ^ Decoder state from gloss
-> IO DecoderState
stepIO dsT _ _ = do
ds' <- readTVarIO dsT
return ds'
------------------------------------------------------------------------------
-- | Insert a set of cluster boundaries into the state
setTrodeClusters :: Track -- ^ Track definition
-> TVar DecoderState -- ^ Decoder state
-> Map.Map PlaceCellName ClusterMethod
-- ^ The cluster bounds by place cell name
-> IO ()
setTrodeClusters track dsT clusts =
let foldF d (cName,cMethod) =
setTrodeCluster track d cName cMethod in
atomically $ do
ds <- readTVar dsT
ds' <- F.foldlM foldF ds (Map.toList clusts)
writeTVar dsT ds'
------------------------------------------------------------------------------
-- | Apply the point spread function to a position and insert it into the
-- occupancy map and the current position.
updatePos :: TVar DecoderState -- ^ The shared decoder state
-> Position -- ^ The position to spread
-> IO ()
updatePos dsT p = let trackPos' = posToField defTrack p kernel in
atomically $ do
ds <- readTVar dsT
modifyTVar' (ds^.occupancy) (updateField (+) trackPos')
writeTVar (ds^.pos) p
writeTVar (ds^.trackPos) trackPos'
{-# INLINE updatePos #-}
------------------------------------------------------------------------------
-- | Increment each cluster's place field based on whether a spike falls in
-- its bounds.
fanoutSpikeToCells :: DecoderState -- ^ The decoding state
-> PlaceCellTrode -- ^ The trode of interest
-> Position -- ^ The most recently seen position
-> Field -- ^ Occupancy map
-> TrodeSpike -- ^ The spike of interest
-> IO ()
fanoutSpikeToCells ds trode pos trackPos spike =
do
flip F.mapM_ (trode^.dUnits) $ \dpcT -> do
DecodablePlaceCell pc tauN <- readTVarIO dpcT
when (spikeInCluster (pc^.cluster) spike) $ do
let pc' = if pos^.speed > runningThresholdSpeed
then pc & countField %~ updateField (+) trackPos
else pc
tauN' = tauN + 1
atomically $ writeTVar dpcT $ DecodablePlaceCell pc' tauN'
{-# INLINE fanoutSpikeToCells #-}
------------------------------------------------------------------------------
-- | Add a spike in the clusterless case
clusterlessAddSpike :: DecoderState -- ^ The decoding state
-> Position -- ^ The most recently seen camera position
-> Field -- ^ Most recently seen track position
-> TrodeSpike -- ^ The spike to add
-> IO ()
clusterlessAddSpike ds p tPos spike =
case ds^.trode of
Clusterless t' -> H.timeAction (ds^.encodeProf) $ do
atomically $ do
let forKDE = (p^.speed) >= runningThresholdSpeed
let spike' = (makeCPoint spike tPos,
MostRecentTime $ spikeTime spike,
forKDE)
modifyTVar t' $ \(t::ClusterlessTrode) -> t & dtTauN %~ (spike':)
return ()
_ -> error "Clustered in clusterless context"
{-# INLINE clusterlessAddSpike #-}
------------------------------------------------------------------------------
-- | Convert a spike and spread position into a point for the clusterless
-- KD tree.
makeCPoint :: TrodeSpike -- ^ The spike
-> Field -- ^ The position
-> ClusterlessPoint
makeCPoint spike tPos = ClusterlessPoint {
_pAmplitude = U.convert . spikeAmplitudes $ spike
, _pWeight = 1
, _pField = normalize $ gt0 tPos
}
------------------------------------------------------------------------------
-- | Add a cluster to a given trode's list of clusters, creating the trode
-- first if it does not exist.
setTrodeCluster :: Track -- ^ The track model
-> DecoderState -- ^ The decoding state
-> PlaceCellName -- ^ The name of the cluster
-> ClusterMethod -- ^ The bounds of the cluster
-> STM DecoderState
setTrodeCluster track ds placeCellName clustMethod =
case ds^.trode of
Clusterless _ -> error "Tried to set cluster in a clusterless context"
Clustered (PlaceCellTrode pcs sHist) -> do
dsNewClusts <- case Map.lookup placeCellName pcs of
Nothing -> do
dpc' <- newTVar $ DecodablePlaceCell
(newPlaceCell track clustMethod) 0
let newTrode =
PlaceCellTrode (Map.insert placeCellName dpc' pcs) sHist
return $ (ds { _trode = Clustered newTrode })
Just dpc -> do
_ <- swapTVar dpc $
DecodablePlaceCell
(newPlaceCell track clustMethod) 0
return ds
let drawOpts' = clistTrodes $ dsNewClusts^.trode
return $
dsNewClusts { _trodeDrawOpt = drawOpts' }
------------------------------------------------------------------------------
-- | Create a new cluster from a given set of bounds
newPlaceCell :: Track -- ^ Track model
-> ClusterMethod -- ^ The cluster bounds
-> PlaceCell
newPlaceCell track cMethod =
PlaceCell cMethod
(V.replicate (V.length $ allTrackPos track) 0)
------------------------------------------------------------------------------
-- | Does a given file path end in a certain string?
endsIn :: FilePath -- ^ The path of interest
-> String -- ^ The suffix
-> Bool
endsIn fp str = take (length str) (reverse fp) == reverse str
-- | Create a position producer based on the input format
interpretPos :: DecoderArgs -- ^ Arguments for decoding
-> Socket -- ^ Socket to listen on
-> Producer Position IO ()
interpretPos DecoderArgs{..} sock = case psPosFormat posSource of
OatJSON -> let posProducerNoHistory = udpJsonProducer 9000 sock
in posProducerNoHistory
>-> P.map (transOatPosition . unOatPosition)
>-> producePos pos0
ArteBinary -> udpSocketProducer 9000 sock
ArteJSON -> udpJsonProducer 9000 sock
-- | Newtype wrapper around Position for different fromJSON instance
newtype OatPosition = OatPosition { unOatPosition :: Position }
-- Hack! OAT will eventually just do the right thing
-- | Translate OAT position coordinates to arte position coordinates
transOatPosition :: Position -- ^ Position in OAT coordinates
-> Position
transOatPosition p = let x' = (_x . _location $ p) / 4000 + 229
y' = (_y . _location $ p) / 4000 + 21.5
z' = (_z . _location $ p)
in p { _location = Location x' y' z'}
instance A.FromJSON OatPosition where
parseJSON (A.Object v) = do
posConf <- bool ConfUnsure ConfSure <$> v .: "pos_ok"
[pos_x,pos_y] <- v .: "pos_xy"
[vel_x,vel_y] <- v .: "vel_xy"
return . OatPosition $ (Position
(-200)
(Location pos_x pos_y 0)
(Angle 0 0 0)
(atan2 vel_y vel_x)
(-300)
posConf
[]
[]
(-400)
(Location 0 0 0))
| imalsogreg/arte-ephys | arte-decoder/src/System/Arte/Decode.hs | gpl-3.0 | 19,059 | 65 | 33 | 5,797 | 4,135 | 2,137 | 1,998 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
module PetaVision.Data.Weight where
import Codec.Picture
import Control.Monad as M
import qualified Data.Array as AU
import Data.Array.Repa as R
import Data.List as L
import Data.Vector.Unboxed as VU
import PetaVision.Data.Convolution
import PetaVision.Utility.Parallel
import PetaVision.Utility.Time
import Prelude as P
-- the layout of the weigth array is nyp x nxp x nfp x numPatches
type PVPWeight = Array U DIM4 Double
type PVPWeightPatch = Array U DIM3 Double
-- normalize image pixel value to range of [0,upperBound]
normalizeWeightPatch
:: Double -> PVPWeightPatch -> PVPWeightPatch
normalizeWeightPatch upperBound weightPatch =
computeS $ R.map (\x -> (x - minV) / (maxV - minV) * upperBound) weightPatch
where maxV = foldAllS max 0 weightPatch
minV = foldAllS min 10000 weightPatch
normalizeWeight
:: Double -> PVPWeight -> PVPWeight
normalizeWeight upperBound weight =
computeS $
traverse3 weight
minArr
maxArr
(\sh _ _ -> sh)
(\fw fmin fmax sh@(Z :. j :. i :. k :. n) ->
(fw sh - fmin (Z :. n)) / (fmax (Z :. n) - fmin (Z :. n)) *
upperBound)
where (Z :. nyp' :. nxp' :. nfp' :. numPatches') = extent weight
permutedW =
R.backpermute (Z :. numPatches' :. nyp' :. nxp' :. nfp')
(\(Z :. np :. j :. i :. k) -> Z :. j :. i :. k :. np)
weight
bound = 1000000
maxArr =
foldS max (-bound) . foldS max (-bound) . foldS max (-bound) $
permutedW
minArr =
foldS min bound . foldS min bound . foldS min bound $ permutedW
plotWeight :: FilePath -> PVPWeight -> IO ()
plotWeight filePath weight =
do let Z :. nyp' :. nxp' :. nfp' :. numPatches' = extent weight
normalizedW =
normalizeWeight (P.fromIntegral (maxBound :: Pixel8))
weight
weightPatches =
case nfp' of
3 ->
P.map (\n ->
ImageRGB8 $
generateImage
(\i j ->
let r =
fromIntegral . round $
normalizedW R.! (Z :. j :. i :. 0 :. n)
g =
fromIntegral . round $
normalizedW R.! (Z :. j :. i :. 1 :. n)
b =
fromIntegral . round $
normalizedW R.! (Z :. j :. i :. 2 :. n)
in PixelRGB8 r g b)
nyp'
nxp')
[0 .. (numPatches' - 1)]
1 ->
P.map (\n ->
ImageY8 $
generateImage
(\i j ->
let v =
fromIntegral . round $
normalizedW R.! (Z :. j :. i :. 0 :. n)
in v)
nyp'
nxp')
[0 .. (numPatches' - 1)]
_ ->
error $ ("Image channel number is incorrect: " P.++ show nfp')
M.zipWithM_
(\n w ->
savePngImage (filePath P.++ "/" P.++ show n P.++ ".png")
w)
[0 .. (numPatches' - 1)]
weightPatches
plotWeightPatch :: FilePath -> PVPWeightPatch -> IO ()
plotWeightPatch filePath weightPatch =
do let Z :. nyp' :. nxp' :. nfp' = extent weightPatch
normalizedWeightPatch =
normalizeWeightPatch (P.fromIntegral (maxBound :: Pixel8))
weightPatch
w =
case nfp' of
1 ->
ImageY8 $
generateImage
(\i j ->
let v =
fromIntegral . round $
normalizedWeightPatch R.! (Z :. j :. i :. 0)
in v)
nyp'
nxp'
3 ->
ImageRGB8 $
generateImage
(\i j ->
let r =
fromIntegral . round $
normalizedWeightPatch R.! (Z :. j :. i :. 0)
g =
fromIntegral . round $
normalizedWeightPatch R.! (Z :. j :. i :. 1)
b =
fromIntegral . round $
normalizedWeightPatch R.! (Z :. j :. i :. 2)
in PixelRGB8 r g b)
nyp'
nxp'
x -> error $ "plotWeightPatch: Image channel error: " L.++ show (extent weightPatch)
savePngImage filePath w
weightedSum
:: PVPWeight -> Array U DIM1 Double -> Array U DIM3 Double
weightedSum weightPatches a = foldS (+) 0 arr
where arr =
traverse2 weightPatches
a
(\sh _ -> sh)
(\fwp fa sh@(Z :. _j :. _i :. _k :. n) ->
(fwp sh) * (fa (Z :. n)))
weightVisualization :: FilePath -> PVPWeight -> IO ()
weightVisualization filePath weight =
do let Z :. nyp' :. nxp' :. nfp' :. numPatches' = extent weight
M.sequence_
[plotWeightPatch (filePath P.++ show np P.++ "_" P.++ show nf P.++ ".png") .
computeS . extend (Z :. All :. All :. (1 :: Int)) . R.slice weight $
(Z :. All :. All :. nf :. np)
|np <- [0 .. numPatches' - 1]
,nf <- [0 .. nfp' - 1]]
weightListReconstruction :: ParallelParams -> [PVPWeight] -> [Int] -> PVPWeight
weightListReconstruction _ [] _ =
error "weightListReconstruction: empty weight list."
weightListReconstruction _ ((!x):[]) _ =
normalizeWeight (fromIntegral (maxBound :: Pixel8)) x
weightListReconstruction _ (x:y:_) [] =
error "weightListReconstruction: empty stride list."
weightListReconstruction parallelParams (!x:(!y):xs) (s:ss) =
weightListReconstruction parallelParams (newWeight : xs) ss
where
!newWeight = weightReconstruction parallelParams x y s
{-# INLINE weightReconstruction #-}
weightReconstruction
:: ParallelParams -> PVPWeight -> PVPWeight -> Int -> PVPWeight
weightReconstruction parallelParams act weight stride =
computeS .
L.foldl1' R.append .
L.map (R.extend (Z :. All :. All :. All :. (1 :: Int))) .
parMap
rseq
(\z ->
let arr = sumS .
L.foldl1' R.append .
L.map
(R.extend (Z :. All :. All :. All :. (1 :: Int)) . array2RepaArray3) .
L.zipWith
(\weight' y ->
let weightArr =
AU.listArray ((0, 0, 0), (wNy - 1, wNx - 1, wNf - 1)) .
R.toList $
weight' :: AU.Array (Int, Int, Int) Double
actArr = repaArray2Array2 y
in crossCorrelation25D stride actArr weightArr)
weightList $
z
in deepSeqArray arr arr) $
ys
where
(Z :. actNy :. actNx :. actNf :. actNumDict) = extent act
(Z :. wNy :. wNx :. wNf :. wNumDict) = extent weight
xs =
L.map
(\i -> R.slice act (Z :. All :. All :. All :. (i :: Int)))
[0 .. actNumDict - 1]
ys =
L.map
(\arr' ->
L.map (\i -> R.slice arr' (Z :. All :. All :. i)) [0 .. actNf - 1])
xs
weightList =
L.map
(\i -> R.slice weight (Z :. All :. All :. All :. i))
[0 .. wNumDict - 1]
{-# INLINE reorderWeight #-}
reorderWeight :: [Int] -> PVPWeight -> PVPWeight
reorderWeight idx w =
computeS .
R.backpermute
(extent w)
(\(Z :. ny :. nx :. nf :. np) -> (Z :. ny :. nx :. nf :. vec VU.! np)) $
w
where
!vec = VU.fromList idx
{-# INLINE weightReconstructionAct #-}
weightReconstructionAct :: PVPWeightPatch -> PVPWeight -> Int -> PVPWeightPatch
weightReconstructionAct act weight stride =
sumS .
L.foldl1' R.append .
L.map (R.extend (Z :. All :. All :. All :. (1 :: Int)) . array2RepaArray3) .
parZipWith
rdeepseq
(\weight' y ->
let weightArr =
AU.listArray ((0, 0, 0), (wNy - 1, wNx - 1, wNf - 1)) . R.toList $
weight' :: AU.Array (Int, Int, Int) Double
actArr = repaArray2Array2 y
in crossCorrelation25D stride actArr weightArr)
weightList .
L.map (\i -> R.slice act (Z :. All :. All :. i)) $
[0 .. actNf - 1]
where
(Z :. actNy :. actNx :. actNf) = extent act
(Z :. wNy :. wNx :. wNf :. wNumDict) = extent weight
weightList =
L.map
(\i -> R.slice weight (Z :. All :. All :. All :. i))
[0 .. wNumDict - 1]
| XinhuaZhang/PetaVisionHaskell | PetaVision/Data/Weight.hs | gpl-3.0 | 9,108 | 187 | 22 | 3,863 | 2,802 | 1,494 | 1,308 | 225 | 3 |
import Test.QuickCheck
import Data.List
import Prelude
-- Not as easy as I first thought.
-- Given in lab
prime :: Integer -> Bool
prime n = n > 1 && all (\ x -> rem n x /= 0) xs
where xs = takeWhile (\ y -> y^2 <= n) primes
primes :: [Integer]
primes = 2 : filter prime [3..]
primeProduct n = prime $ (+) 1 $ product $ take n primes
main = do
-- Smallest counterexample
print $ take (head $ filter (not . primeProduct) $ [1..] ) primes | vdweegen/UvA-Software_Testing | Lab1/Jordan/exercise6.hs | gpl-3.0 | 449 | 1 | 15 | 105 | 193 | 100 | 93 | 11 | 1 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module MEnv.Env.ScreenObject
(
-- tmp
module MEnv.Env.ScreenObject.GLFW,
--
) where
-- tmp
import MEnv.Env.ScreenObject.GLFW
--
| karamellpelle/grid | designer/source/MEnv/Env/ScreenObject.hs | gpl-3.0 | 891 | 0 | 5 | 165 | 47 | 40 | 7 | 4 | 0 |
module IcfpcEndo.Loader where
import IcfpcEndo.Endo (mkEndo)
import Application.Assets.ConfigScheme
import Middleware.Config.Facade
import Paths_Endo as P
import Data.ByteString.Char8 as X
import qualified Data.IORef as IO
endoDnaInfo = strOption endoDna
load cfg = do
dnaFile <- extract cfg endoDnaInfo
dnaRealFileName <- P.getDataFileName dnaFile
dna <- X.readFile dnaRealFileName
dnaRef <- IO.newIORef dna
return $ mkEndo dnaRef 0
| graninas/ICFPC2007 | Endo/IcfpcEndo/Loader.hs | gpl-3.0 | 458 | 0 | 9 | 77 | 125 | 67 | 58 | 14 | 1 |
{-# OPTIONS_GHC -fdefer-type-errors #-}
{-# OPTIONS_GHC -fwarn-typed-holes #-}
module Parse (Program(Program),
SExpr(Atom,List,Nil),
Atom(Symbol,Number),
agParse,
testText5)
where
import Data.Functor.Identity
import Control.Applicative
import Text.Parsec hiding (many, (<|>), spaces, newline)
import qualified Text.Parsec.Token as T
import Text.Parsec.Language
{- Grammar:
program ::= { sexpr }* <eof>
sexpr ::= explicit-list | implicit-list | atom
explicit-sexpr ::= explicit-list | atom
explicit-list ::= '(' { sexpr }* ')'
implicit-list ::= block-list | line-list
block-list ::= line-list <indent> { line-list }* <outdent>
line-list ::= atom { explicit-sexpr }+ <newline>
atom ::= symbol | number
number ::= <float>
-}
data Program = Program [SExpr] deriving (Show, Eq)
data SExpr = Atom (Atom) | List [SExpr] | Nil deriving (Show, Eq)
data Atom = Symbol String | Number Double deriving (Show, Eq)
-- | Return a Silveretta Program parse tree of the String s.
--parse :: String -> Either ParseError (Program a)
--parse s = IP.parse program "" s
punctuation :: ParsecT String u Identity Char
punctuation = oneOf "{}[]<>#%:.+-*/^&|~!=,"
silverettaDef :: GenLanguageDef String u Identity
silverettaDef = T.LanguageDef { T.commentStart = ";{",
T.commentEnd = ";}",
T.commentLine = ";",
T.nestedComments = True,
T.identStart = punctuation <|> letter,
T.identLetter = punctuation <|> alphaNum,
T.opStart = T.opStart emptyDef,
T.opLetter = T.opLetter emptyDef,
T.reservedNames = [],
T.reservedOpNames = [],
T.caseSensitive = True
}
agTokP :: T.GenTokenParser String u Identity
agTokP = T.makeTokenParser silverettaDef
indentSize :: Int
indentSize = 2
wrap :: [String] -> [String]
wrap sl = case sl of
(x:y:zs) -> let indx = indentation x
indy = indentation y
in
if indy > indx then
((replicate (indy - indx) '(') ++ x):wrap (y:zs)
else if indy < indx then
((wrap1 x) ++ (replicate (indx - indy) ')')):wrap (y:zs)
else
(wrap1 x):wrap (y:zs)
[x] -> if (indentation x) /= 0 then
[(wrap1 x) ++ replicate (indentation x) ')']
else
[wrap1 x]
[] -> []
where
indentation line = (length $ fst (span (==' ') line)) `div` indentSize
wrap1 :: String -> String
wrap1 s = "(" ++ s ++ ")"
spaces :: ParsecT String u Identity ()
spaces = T.whiteSpace agTokP
program :: ParsecT String u Identity Program
program = Program <$> many1 sexpr
list :: ParsecT String u Identity SExpr
list = do
_ <- char '('
spaces
l <- many sexpr
spaces
_ <- char ')'
return $ List $ l
sexpr :: ParsecT String u Identity SExpr
sexpr = (try list <|> atom) <* spaces
atom :: ParsecT String u Identity SExpr
atom = Atom <$> (try symbol <|> number)
symbol :: ParsecT String u Identity Atom
symbol = Symbol <$> T.identifier agTokP
number :: ParsecT String u Identity Atom
number = Number <$> T.float agTokP
agParse :: String -> Either ParseError Program
agParse s = parse program "" $ unlines $ (if (length $ lines s) == 1 then lines . wrap1 else wrap . lines) $ s
testText1 = "(hello)"
testText2 = "hello there"
testText3 = "hello\nthere"
testText4 = "hello\n there"
testText5 = "let\n x <- 1\n y <- 4\n if (> x y)\n + x y\n - y x\nlet\n foo <- bar\n foo"
pmain :: IO ()
pmain = do
print $ agParse testText1
print $ agParse testText2
print $ agParse testText3
print $ agParse testText4
print $ agParse testText5
| Fizzixnerd/silveretta-hs | src/Parse.hs | gpl-3.0 | 3,905 | 2 | 19 | 1,175 | 1,084 | 585 | 499 | 90 | 6 |
module Hadolint.Rule.DL3015 (rule) where
import Hadolint.Rule
import Hadolint.Shell (ParsedShell)
import qualified Hadolint.Shell as Shell
import Language.Docker.Syntax
rule :: Rule ParsedShell
rule = simpleRule code severity message check
where
code = "DL3015"
severity = DLInfoC
message = "Avoid additional packages by specifying `--no-install-recommends`"
check (Run (RunArgs args _)) = foldArguments (Shell.noCommands forgotNoInstallRecommends) args
check _ = True
forgotNoInstallRecommends cmd = isAptGetInstall cmd && not (disablesRecommendOption cmd)
isAptGetInstall = Shell.cmdHasArgs "apt-get" ["install"]
disablesRecommendOption cmd =
Shell.hasFlag "no-install-recommends" cmd
|| Shell.hasArg "APT::Install-Recommends=false" cmd
{-# INLINEABLE rule #-}
| lukasmartinelli/hadolint | src/Hadolint/Rule/DL3015.hs | gpl-3.0 | 815 | 0 | 11 | 136 | 189 | 101 | 88 | 17 | 2 |
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Monad
import Criterion.Main
import Data.Foldable
import Data.Traversable
import GHC.Conc (getNumProcessors)
import System.Random
import System.Random.Shuffle
import qualified Lib as L
main :: IO ()
main = do
let numOperations = 10000
realisticBenchmarkData <- prepareRealisticData numOperations
defaultMain
[ bgroup "High-Contention" $ highContentionBenchs numOperations
, bgroup "Realistic" $ realisticBenchs realisticBenchmarkData
]
where
highContentionBenchs numOperations =
[ bench (show listType) $ nfIO (highContentionBench listType numOperations)
| listType <- L.allTypes ]
realisticBenchs benchData =
[ bench (show listType) $ nfIO (realisticBench listType benchData)
| listType <- L.allTypes ]
highContentionBench :: L.ListType -> Int -> IO ()
highContentionBench listType numOperations = do
numProcessors <- getNumProcessors
let numExtraThreads = 2
let numAddingThreads = numProcessors - numExtraThreads
list <- forM [1 .. numOperations] $ \_ -> randomRIO (0, 99) :: IO Int
let originalNumberOf42 = length $ filter (== 42) list
safeList <- L.fromList listType list
mainLocks <- forM [1 .. numAddingThreads] $ \_ -> newEmptyMVar
extraLocks <- forM [1 .. numExtraThreads] $ \_ -> newEmptyMVar
forkIO $ forM_ [1 .. numOperations] $ \_ -> do
L.add safeList 41
putMVar (extraLocks !! 0) ()
forkIO $ forM_ [1 .. numOperations] $ \_ -> do
L.remove safeList 41
putMVar (extraLocks !! 1) ()
forM_ mainLocks $ \lock -> forkIO $ do
forM_ [1 .. numOperations] $ \_ -> L.add safeList 42
putMVar lock ()
mapM_ takeMVar (mainLocks ++ extraLocks)
pureList <- L.toPureList safeList
return ()
prepareRealisticData :: Int -> IO ([Int], [L.ThreadSafeList Int -> IO ()])
prepareRealisticData numOperations = do
initialElements <- forM [1 .. numOperations] $ \_ -> randomRIO (0, 9999)
operations <- do
let numInsertions = (numOperations * 2) `quot` 10
let numRemovals = (numOperations * 1) `quot` 10
let numFinds = (numOperations * 7) `quot` 10
insertions <- replicateM numInsertions $ do
rand <- randomRIO (0, 9999)
return $ \list -> L.add list rand
removals <- replicateM numRemovals $ do
rand <- randomRIO (0, 9999)
return $ \list -> L.remove list rand >> return ()
finds <- replicateM numFinds $ do
rand <- randomRIO (0, 9999)
return $ \list -> L.contains list rand >> return ()
shuffleM . concat $ [insertions, removals, finds]
return (initialElements, operations)
realisticBench :: Ord a => L.ListType -> ([a], [L.ThreadSafeList a -> IO ()]) -> IO ()
realisticBench listType (initialElements, operations) = do
numProcessors <- getNumProcessors
let numOperations = length initialElements
safeList <- L.fromList listType initialElements
locks <- forM [1 .. numProcessors] $ \_ -> newEmptyMVar
forM_ locks $ \lock -> forkIO $ do
forM_ operations $ \operation -> operation safeList
putMVar lock ()
mapM_ takeMVar locks
pureList <- L.toPureList safeList
return ()
| paulolieuthier/haskell-concurrent-lists | bench/Main.hs | lgpl-2.1 | 3,360 | 0 | 18 | 862 | 1,150 | 566 | 584 | 75 | 1 |
module Math.Topology.KnotTh.Tangle.TableOfLinks
( listOfDTCodes
) where
listOfDTCodes :: [((Int, Int), [[[Int]]])]
listOfDTCodes =
[ ((0, 1),
[ [[]]
])
, ((2, 2),
[ [[4], [2]]
])
, ((3, 1),
[ [[4, 6, 2]]
])
, ((4, 1),
[ [[4, 6, 8, 2]]
])
, ((4, 2),
[ [[6, 8], [2, 4]]
])
, ((5, 1),
[ [[6, 8, 10, 2, 4]]
, [[4, 8, 10, 2, 6]]
])
, ((5, 2),
[ [[6, 8], [4, 10, 2]]
])
, ((6, 1),
[ [[4, 8, 12, 10, 2, 6]]
, [[4, 8, 10, 12, 2, 6]]
, [[4, 8, 10, 2, 12, 6]]
])
, ((6, 2),
[ [[8, 10, 12], [6, 2, 4]]
, [[8, 10, 12], [2, 6, 4]]
, [[6, 10], [2, 12, 4, 8]]
])
, ((6, 3),
[ [[6, 10], [2, 12], [4, 8]]
, [[6, 8], [10, 12], [2, 4]]
, [[6, -8], [-10, 12], [-2, 4]]
])
, ((7, 1),
[ [[8, 10, 12, 14, 2, 4, 6]]
, [[4, 10, 14, 12, 2, 8, 6]]
, [[6, 10, 12, 14, 2, 4, 8]]
, [[6, 10, 12, 14, 4, 2, 8]]
, [[4, 10, 12, 14, 2, 8, 6]]
, [[4, 8, 12, 2, 14, 6, 10]]
, [[4, 8, 10, 12, 2, 14, 6]]
])
, ((7, 2),
[ [[8, 10, 12], [2, 14, 4, 6]]
, [[8, 10, 12], [2, 6, 14, 4]]
, [[6, 10], [2, 14, 12, 4, 8]]
, [[6, 10], [2, 12, 14, 4, 8]]
, [[6, 10], [2, 12, 4, 14, 8]]
, [[6, 8], [10, 12, 14, 2, 4]]
, [[6, -8], [-10, 12, -14, -2, 4]]
, [[6, -8], [-10, 12, -14, 2, -4]]
])
, ((7, 3),
[ [[6, 10], [2, 12], [4, 14, 8]]
])
, ((8, 1),
[ [[4, 10, 16, 14, 12, 2, 8, 6]]
, [[4, 10, 12, 14, 16, 2, 6, 8]]
, [[6, 12, 10, 16, 14, 4, 2, 8]]
, [[6, 10, 12, 16, 14, 4, 2, 8]]
, [[6, 8, 12, 2, 14, 16, 4, 10]]
, [[4, 10, 14, 16, 12, 2, 8, 6]]
, [[4, 10, 12, 14, 2, 16, 6, 8]]
, [[4, 8, 12, 2, 16, 14, 6, 10]]
, [[6, 10, 12, 14, 16, 4, 2, 8]]
, [[4, 8, 12, 2, 14, 16, 6, 10]]
, [[4, 10, 12, 14, 16, 2, 8, 6]]
, [[4, 8, 14, 10, 2, 16, 6, 12]]
, [[4, 10, 12, 14, 2, 16, 8, 6]]
, [[4, 8, 10, 14, 2, 16, 6, 12]]
, [[4, 8, 12, 2, 14, 6, 16, 10]]
, [[6, 8, 14, 12, 4, 16, 2, 10]]
, [[6, 8, 12, 14, 4, 16, 2, 10]]
, [[6, 8, 10, 12, 14, 16, 2, 4]]
, [[4, 8, -12, 2, -14, -16, -6, -10]]
, [[4, 8, -12, 2, -14, -6, -16, -10]]
, [[4, 8, -12, 2, 14, -6, 16, 10]]
])
, ((8, 2),
[ [[10, 12, 14, 16], [8, 2, 4, 6]]
, [[10, 12, 14, 16], [2, 8, 4, 6]]
, [[8, 10, 14], [6, 2, 16, 4, 12]]
, [[10, 12, 14, 16], [2, 8, 6, 4]]
, [[8, 10, 14], [2, 6, 16, 4, 12]]
, [[6, 12], [2, 16, 14, 4, 10, 8]]
, [[8, 10, 12], [2, 16, 14, 4, 6]]
, [[8, 10, 12], [2, 16, 14, 6, 4]]
, [[6, 10], [2, 14, 4, 16, 8, 12]]
, [[6, 10], [2, 12, 14, 4, 16, 8]]
, [[6, 12], [2, 14, 16, 4, 10, 8]]
, [[6, 10], [2, 14, 12, 4, 16, 8]]
, [[6, 8], [10, 14, 12, 16, 2, 4]]
, [[6, 12], [10, 14, 2, 16, 8, 4]]
, [[6, -8], [-10, 14, -12, -16, 2, -4]]
, [[6, -8], [-10, 14, -12, -16, -2, 4]]
])
, ((8, 3),
[ [[6, 12], [2, 14, 16], [10, 4, 8]]
, [[6, 12], [2, 14, 16], [4, 10, 8]]
, [[6, 10], [2, 14], [4, 16, 8, 12]]
, [[10, 14], [12, 16], [2, 6, 4, 8]]
, [[6, 8], [12, 14, 16], [10, 2, 4]]
, [[6, 12], [14, 16, 2], [8, 10, 4]]
, [[6, -8], [-12, 14, -16], [-10, -2, 4]]
, [[6, -8], [-12, 14, -16], [-10, 2, -4]]
, [[6, 8], [-12, 14, -16], [-10, 2, 4]]
, [[10, 14], [-12, -16], [2, -6, 4, -8]]
])
, ((8, 4),
[ [[6, 10], [2, 14], [4, 16], [8, 12]]
, [[6, -10], [2, -14], [-4, -16], [-8, -12]]
, [[6, -10], [2, -14], [-4, 16], [-8, 12]]
])
, ((9, 1),
[ [[10, 12, 14, 16, 18, 2, 4, 6, 8]]
, [[4, 12, 18, 16, 14, 2, 10, 8, 6]]
, [[8, 12, 14, 16, 18, 2, 4, 6, 10]]
, [[6, 12, 14, 18, 16, 2, 4, 10, 8]]
, [[6, 12, 14, 18, 16, 4, 2, 10, 8]]
, [[4, 12, 14, 16, 18, 2, 10, 6, 8]]
, [[4, 12, 16, 18, 14, 2, 10, 8, 6]]
, [[4, 8, 14, 2, 18, 16, 6, 12, 10]]
, [[6, 12, 14, 16, 18, 2, 4, 10, 8]]
, [[8, 12, 14, 16, 18, 2, 6, 4, 10]]
, [[4, 10, 14, 16, 12, 2, 18, 6, 8]]
, [[4, 10, 16, 14, 2, 18, 8, 6, 12]]
, [[6, 12, 14, 16, 18, 4, 2, 10, 8]]
, [[4, 10, 12, 16, 14, 2, 18, 8, 6]]
, [[4, 8, 14, 10, 2, 18, 16, 6, 12]]
, [[4, 12, 16, 18, 14, 2, 8, 10, 6]]
, [[4, 10, 12, 14, 16, 2, 6, 18, 8]]
, [[4, 12, 14, 16, 18, 2, 10, 8, 6]]
, [[4, 8, 10, 14, 2, 18, 16, 6, 12]]
, [[4, 10, 14, 16, 2, 18, 8, 6, 12]]
, [[4, 10, 14, 16, 12, 2, 18, 8, 6]]
, [[4, 8, 10, 14, 2, 16, 18, 6, 12]]
, [[4, 10, 12, 16, 2, 8, 18, 6, 14]]
, [[4, 8, 14, 2, 16, 18, 6, 12, 10]]
, [[4, 8, 12, 2, 16, 6, 18, 10, 14]]
, [[4, 10, 12, 14, 16, 2, 18, 8, 6]]
, [[4, 10, 12, 14, 2, 18, 16, 6, 8]]
, [[4, 8, 12, 2, 16, 14, 6, 18, 10]]
, [[6, 10, 14, 18, 4, 16, 8, 2, 12]]
, [[4, 8, 10, 14, 2, 16, 6, 18, 12]]
, [[4, 10, 12, 14, 2, 18, 16, 8, 6]]
, [[4, 8, 12, 14, 2, 16, 18, 10, 6]]
, [[4, 8, 14, 12, 2, 16, 18, 10, 6]]
, [[6, 8, 10, 16, 14, 18, 4, 2, 12]]
, [[8, 12, 16, 14, 18, 4, 2, 6, 10]]
, [[4, 8, 14, 10, 2, 16, 18, 6, 12]]
, [[4, 10, 14, 12, 16, 2, 6, 18, 8]]
, [[6, 10, 14, 18, 4, 16, 2, 8, 12]]
, [[6, 10, 14, 18, 16, 2, 8, 4, 12]]
, [[6, 16, 14, 12, 4, 2, 18, 10, 8]]
, [[6, 10, 14, 12, 16, 2, 18, 4, 8]]
, [[4, 8, 10, -14, 2, -16, -18, -6, -12]]
, [[4, 8, 10, 14, 2, -16, 6, -18, -12]]
, [[4, 8, 10, -14, 2, -16, -6, -18, -12]]
, [[4, 8, 10, -14, 2, 16, -6, 18, 12]]
, [[4, 10, -14, -12, -16, 2, -6, -18, -8]]
, [[6, 8, 10, 16, 14, -18, 4, 2, -12]]
, [[4, 10, -14, -12, 16, 2, -6, 18, 8]]
, [[6, -10, -14, 12, -16, -2, 18, -4, -8]]
])
, ((9, 2),
[ [[10, 12, 14, 16], [2, 18, 4, 6, 8]]
, [[10, 12, 14, 16], [6, 2, 4, 18, 8]]
, [[8, 10, 14], [6, 2, 18, 16, 4, 12]]
, [[10, 12, 16, 14], [8, 2, 18, 6, 4]]
, [[10, 12, 14, 16], [4, 2, 18, 6, 8]]
, [[10, 12, 14, 16], [2, 8, 4, 18, 6]]
, [[10, 12, 14, 16], [2, 18, 8, 6, 4]]
, [[8, 10, 14], [2, 6, 18, 16, 4, 12]]
, [[10, 12, 14, 16], [2, 8, 18, 6, 4]]
, [[6, 12], [2, 18, 16, 14, 4, 10, 8]]
, [[8, 10, 14], [2, 18, 4, 16, 6, 12]]
, [[8, 10, 14], [2, 18, 6, 16, 4, 12]]
, [[6, 12], [2, 14, 16, 18, 4, 8, 10]]
, [[6, 12], [2, 14, 16, 4, 18, 8, 10]]
, [[6, 12], [2, 14, 16, 18, 4, 10, 8]]
, [[6, 12], [2, 14, 16, 4, 18, 10, 8]]
, [[6, 10], [2, 14, 4, 18, 16, 8, 12]]
, [[6, 10], [2, 12, 16, 4, 18, 8, 14]]
, [[8, 10, 14], [6, 2, 16, 18, 4, 12]]
, [[8, 10, 14], [6, 2, 16, 4, 18, 12]]
, [[8, 10, 14], [2, 6, 16, 18, 4, 12]]
, [[8, 10, 14], [2, 6, 16, 4, 18, 12]]
, [[10, 12, 18, 14], [6, 2, 16, 8, 4]]
, [[8, 12, 16], [2, 18, 4, 10, 6, 14]]
, [[6, 10], [2, 16, 12, 4, 18, 8, 14]]
, [[6, 12], [2, 14, 16, 4, 10, 18, 8]]
, [[6, 12], [2, 16, 18, 14, 4, 10, 8]]
, [[6, 12], [2, 16, 14, 4, 10, 18, 8]]
, [[6, 10], [2, 14, 4, 16, 18, 8, 12]]
, [[6, 10], [2, 14, 4, 16, 8, 18, 12]]
, [[6, 8], [12, 14, 16, 18, 2, 4, 10]]
, [[6, 8], [10, 14, 16, 18, 2, 4, 12]]
, [[6, 8], [12, 16, 14, 18, 10, 2, 4]]
, [[8, 10, 12], [14, 2, 16, 18, 4, 6]]
, [[8, 10, 12], [14, 2, 16, 18, 6, 4]]
, [[6, 10], [12, 16, 14, 18, 2, 8, 4]]
, [[6, 10], [12, 14, 16, 18, 2, 8, 4]]
, [[6, 12], [10, 14, 2, 18, 16, 8, 4]]
, [[8, 10, 14], [6, 16, 4, 18, 2, 12]]
, [[8, 12, 16], [2, 14, 4, 18, 6, 10]]
, [[10, 12, 18, 14], [6, 16, 4, 8, 2]]
, [[8, 10, 12], [6, 14, 16, 18, 2, 4]]
, [[6, -8], [-12, 14, -16, -18, -2, 4, -10]]
, [[6, -8], [-12, 14, -16, -18, 2, -4, -10]]
, [[6, -8], [-10, 14, -16, -18, -2, 4, -12]]
, [[6, -8], [-10, 14, -16, -18, 2, -4, -12]]
, [[6, 8], [-10, 14, -16, -18, 2, 4, -12]]
, [[6, -8], [-12, 16, -14, -18, -10, -2, 4]]
, [[8, -10, 12], [6, -14, 16, -18, 2, -4]]
, [[8, -10, -12], [6, 14, -16, 18, -2, -4]]
, [[8, -10, 12], [6, 14, -16, 18, 2, -4]]
, [[8, 10, -12], [-14, 2, 16, -18, 4, -6]]
, [[10, 12, 18, -14], [6, 2, -16, -8, 4]]
, [[8, -10, -12], [6, -14, -16, -18, -2, -4]]
, [[6, 8], [-12, 14, -16, -18, 2, 4, -10]]
, [[6, 8], [-12, 16, -14, -18, -10, 2, 4]]
, [[6, 10], [2, 14, 4, -16, 8, -18, -12]]
, [[6, 10], [2, -14, 4, 16, -8, 18, 12]]
, [[6, 10], [2, -14, 4, -16, -18, -8, -12]]
, [[6, 10], [2, -14, 4, -16, -8, -18, -12]]
, [[10, -12, 18, -14], [6, 16, -4, -8, 2]]
])
, ((9, 3),
[ [[6, 12], [2, 14, 16], [10, 4, 18, 8]]
, [[6, 12], [2, 14, 16], [4, 10, 18, 8]]
, [[6, 10], [2, 14], [4, 16, 18, 8, 12]]
, [[6, 10], [2, 14], [4, 16, 8, 18, 12]]
, [[6, 12], [2, 14, 16], [4, 18, 8, 10]]
, [[6, 12], [2, 14, 16], [4, 18, 10, 8]]
, [[6, 10], [2, 14], [4, 18, 16, 8, 12]]
, [[12, 16], [14, 10, 18], [2, 6, 4, 8]]
, [[10, 14], [12, 18], [2, 16, 6, 4, 8]]
, [[6, 8], [12, 14, 18], [16, 2, 4, 10]]
, [[6, 12], [14, 18, 2], [8, 16, 10, 4]]
, [[10, 12], [14, 18], [6, 16, 8, 2, 4]]
, [[6, -8], [-12, 14, -18], [-16, -2, 4, -10]]
, [[6, -8], [-12, 14, -18], [-16, 2, -4, -10]]
, [[6, 10], [2, 14], [4, -16, 8, -18, -12]]
, [[6, -10], [2, -14], [-4, -16, -8, -18, -12]]
, [[6, -10], [2, -14], [-4, 16, -8, 18, 12]]
, [[6, 8], [-12, 14, -18], [-16, 2, 4, -10]]
, [[12, 16], [-14, -10, -18], [2, -6, 4, -8]]
, [[10, 12], [14, -18], [-6, 16, 8, 2, 4]]
, [[10, 12], [-14, -18], [-6, 16, -8, 2, 4]]
])
, ((9, 4),
[ [[6, 10], [2, 14], [4, 16], [8, 18, 12]]
])
, ((10, 1),
[ [[4, 12, 20, 18, 16, 14, 2, 10, 8, 6]]
, [[4, 12, 14, 16, 18, 20, 2, 6, 8, 10]]
, [[6, 14, 12, 20, 18, 16, 4, 2, 10, 8]]
, [[6, 12, 14, 20, 18, 16, 4, 2, 10, 8]]
, [[4, 12, 14, 16, 18, 2, 20, 6, 8, 10]]
, [[4, 12, 16, 18, 20, 14, 2, 10, 6, 8]]
, [[4, 12, 14, 18, 16, 20, 2, 10, 8, 6]]
, [[6, 14, 12, 16, 18, 20, 4, 2, 8, 10]]
, [[6, 12, 14, 16, 18, 20, 4, 2, 8, 10]]
, [[4, 12, 14, 18, 16, 2, 20, 10, 8, 6]]
, [[6, 14, 12, 18, 20, 16, 4, 2, 10, 8]]
, [[4, 10, 14, 16, 2, 20, 18, 6, 8, 12]]
, [[4, 10, 18, 16, 12, 2, 20, 8, 6, 14]]
, [[4, 10, 12, 16, 18, 2, 20, 6, 8, 14]]
, [[4, 12, 16, 18, 14, 2, 10, 20, 6, 8]]
, [[6, 14, 12, 16, 18, 20, 4, 2, 10, 8]]
, [[6, 12, 14, 16, 18, 2, 4, 20, 8, 10]]
, [[4, 12, 14, 18, 16, 2, 10, 20, 8, 6]]
, [[6, 12, 14, 16, 18, 2, 4, 20, 10, 8]]
, [[4, 12, 18, 20, 16, 14, 2, 10, 8, 6]]
, [[4, 12, 14, 16, 18, 20, 2, 6, 10, 8]]
, [[6, 12, 14, 18, 20, 16, 4, 2, 10, 8]]
, [[4, 12, 14, 16, 18, 2, 20, 6, 10, 8]]
, [[4, 12, 16, 18, 20, 14, 2, 10, 8, 6]]
, [[4, 12, 14, 16, 18, 20, 2, 10, 8, 6]]
, [[6, 12, 14, 16, 18, 20, 4, 2, 10, 8]]
, [[4, 12, 14, 16, 18, 2, 20, 10, 8, 6]]
, [[4, 10, 14, 16, 2, 20, 18, 8, 6, 12]]
, [[4, 10, 16, 18, 12, 2, 20, 8, 6, 14]]
, [[4, 10, 12, 16, 18, 2, 20, 8, 6, 14]]
, [[4, 12, 16, 18, 14, 2, 10, 20, 8, 6]]
, [[4, 12, 14, 16, 18, 2, 10, 20, 8, 6]]
, [[6, 12, 14, 16, 18, 4, 2, 20, 10, 8]]
, [[4, 8, 14, 2, 20, 18, 16, 6, 12, 10]]
, [[4, 8, 16, 10, 2, 20, 18, 6, 14, 12]]
, [[4, 8, 10, 16, 2, 20, 18, 6, 14, 12]]
, [[4, 10, 16, 12, 2, 8, 20, 18, 6, 14]]
, [[4, 10, 12, 16, 2, 8, 20, 18, 6, 14]]
, [[4, 10, 12, 14, 18, 2, 6, 20, 8, 16]]
, [[4, 10, 12, 16, 2, 20, 6, 18, 8, 14]]
, [[4, 10, 12, 16, 20, 2, 8, 18, 6, 14]]
, [[4, 10, 12, 16, 2, 20, 8, 18, 6, 14]]
, [[4, 10, 16, 14, 2, 20, 8, 18, 6, 12]]
, [[4, 10, 12, 16, 14, 2, 20, 18, 8, 6]]
, [[4, 10, 12, 14, 16, 2, 20, 18, 8, 6]]
, [[6, 8, 14, 2, 16, 18, 20, 4, 10, 12]]
, [[4, 8, 14, 2, 16, 18, 20, 6, 10, 12]]
, [[6, 8, 14, 2, 16, 18, 4, 20, 10, 12]]
, [[4, 8, 14, 2, 16, 18, 6, 20, 10, 12]]
, [[6, 8, 14, 2, 16, 18, 20, 4, 12, 10]]
, [[4, 8, 14, 2, 16, 18, 20, 6, 12, 10]]
, [[6, 8, 14, 2, 16, 18, 4, 20, 12, 10]]
, [[4, 8, 14, 2, 16, 18, 6, 20, 12, 10]]
, [[4, 10, 16, 12, 2, 8, 18, 20, 6, 14]]
, [[4, 8, 12, 2, 16, 6, 20, 18, 10, 14]]
, [[4, 10, 12, 16, 2, 8, 18, 20, 6, 14]]
, [[4, 8, 12, 2, 14, 18, 6, 20, 10, 16]]
, [[4, 8, 14, 10, 2, 18, 6, 20, 12, 16]]
, [[4, 8, 10, 14, 2, 18, 6, 20, 12, 16]]
, [[4, 8, 10, 14, 2, 16, 18, 6, 20, 12]]
, [[8, 10, 16, 14, 2, 18, 20, 6, 4, 12]]
, [[4, 10, 14, 16, 2, 18, 20, 6, 8, 12]]
, [[4, 10, 16, 14, 2, 18, 8, 6, 20, 12]]
, [[8, 10, 14, 16, 2, 18, 20, 6, 4, 12]]
, [[4, 10, 14, 16, 2, 18, 20, 8, 6, 12]]
, [[4, 10, 14, 16, 2, 18, 8, 6, 20, 12]]
, [[4, 10, 14, 12, 18, 2, 6, 20, 8, 16]]
, [[4, 12, 16, 14, 18, 2, 20, 6, 10, 8]]
, [[4, 10, 14, 12, 18, 2, 16, 6, 20, 8]]
, [[4, 8, 16, 10, 2, 18, 20, 6, 14, 12]]
, [[4, 8, 12, 2, 18, 14, 6, 20, 10, 16]]
, [[4, 8, 10, 16, 2, 18, 20, 6, 14, 12]]
, [[4, 8, 10, 14, 2, 18, 16, 6, 20, 12]]
, [[4, 12, 14, 16, 20, 18, 2, 8, 6, 10]]
, [[4, 10, 12, 14, 18, 2, 16, 6, 20, 8]]
, [[4, 12, 18, 20, 14, 16, 2, 10, 8, 6]]
, [[4, 8, 14, 2, 18, 20, 16, 6, 12, 10]]
, [[4, 8, 14, 2, 18, 16, 6, 12, 20, 10]]
, [[6, 8, 12, 2, 16, 4, 18, 20, 10, 14]]
, [[4, 8, 12, 2, 16, 6, 18, 20, 10, 14]]
, [[4, 8, 12, 2, 16, 6, 18, 10, 20, 14]]
, [[6, 8, 14, 16, 4, 18, 20, 2, 10, 12]]
, [[6, 8, 16, 14, 4, 18, 20, 2, 12, 10]]
, [[4, 10, 16, 14, 2, 8, 18, 20, 12, 6]]
, [[6, 8, 16, 14, 4, 18, 20, 2, 10, 12]]
, [[6, 8, 14, 16, 4, 18, 20, 2, 12, 10]]
, [[4, 10, 14, 16, 2, 8, 18, 20, 12, 6]]
, [[4, 8, 12, 14, 2, 16, 20, 18, 10, 6]]
, [[4, 8, 14, 12, 2, 16, 20, 18, 10, 6]]
, [[6, 10, 14, 2, 16, 20, 18, 8, 4, 12]]
, [[6, 10, 20, 14, 16, 18, 4, 8, 2, 12]]
, [[4, 10, 14, 18, 2, 16, 8, 20, 12, 6]]
, [[6, 10, 16, 20, 14, 4, 18, 2, 12, 8]]
, [[6, 10, 14, 2, 16, 18, 20, 8, 4, 12]]
, [[4, 10, 14, 18, 2, 16, 20, 8, 12, 6]]
, [[4, 8, 18, 12, 2, 16, 20, 6, 10, 14]]
, [[4, 8, 12, 18, 2, 16, 20, 6, 10, 14]]
, [[6, 10, 14, 18, 2, 16, 20, 4, 8, 12]]
, [[6, 10, 18, 14, 2, 16, 20, 8, 4, 12]]
, [[6, 10, 18, 14, 16, 4, 20, 8, 2, 12]]
, [[4, 10, 14, 18, 2, 16, 6, 20, 8, 12]]
, [[6, 10, 14, 18, 16, 4, 20, 2, 8, 12]]
, [[6, 10, 18, 16, 14, 4, 20, 8, 2, 12]]
, [[6, 16, 12, 14, 18, 4, 20, 2, 8, 10]]
, [[4, 12, 16, 20, 18, 2, 8, 6, 10, 14]]
, [[6, 10, 14, 16, 18, 4, 20, 2, 8, 12]]
, [[4, 12, 16, 14, 18, 2, 8, 20, 10, 6]]
, [[6, 16, 12, 14, 18, 4, 20, 2, 10, 8]]
, [[6, 10, 14, 16, 2, 18, 4, 20, 8, 12]]
, [[6, 10, 16, 20, 14, 2, 18, 4, 8, 12]]
, [[6, 10, 16, 14, 2, 18, 8, 20, 4, 12]]
, [[6, 8, 10, 14, 16, 18, 20, 2, 4, 12]]
, [[4, 10, 14, 12, 2, 16, 18, 20, 8, 6]]
, [[6, 8, 10, 14, 16, 20, 18, 2, 4, 12]]
, [[6, 10, 14, 16, 4, 18, 2, 20, 12, 8]]
, [[6, 16, 18, 14, 2, 4, 20, 8, 10, 12]]
, [[6, 10, 16, 14, 18, 4, 20, 2, 12, 8]]
, [[6, 8, 18, 14, 16, 4, 20, 2, 10, 12]]
, [[6, 8, 14, 18, 16, 4, 20, 10, 2, 12]]
, [[6, 10, 18, 12, 4, 16, 20, 8, 2, 14]]
, [[6, 10, 12, 20, 18, 16, 8, 2, 4, 14]]
, [[6, 10, 12, 14, 18, 16, 20, 2, 4, 8]]
, [[8, 10, 12, 14, 16, 18, 20, 2, 4, 6]]
, [[4, 8, -14, 2, -16, -18, -20, -6, -10, -12]]
, [[4, 8, 14, 2, -16, -18, 6, -20, -10, -12]]
, [[4, 8, -14, 2, -16, -18, -6, -20, -10, -12]]
, [[4, 8, -14, 2, 16, 18, -6, 20, 10, 12]]
, [[4, 8, -14, 2, -16, -18, -20, -6, -12, -10]]
, [[4, 8, 14, 2, -16, -18, 6, -20, -12, -10]]
, [[4, 8, -14, 2, -16, -18, -6, -20, -12, -10]]
, [[4, 8, -14, 2, 16, 18, -6, 20, 12, 10]]
, [[4, 8, -12, 2, -16, -6, -20, -18, -10, -14]]
, [[4, 8, 12, 2, -14, -18, 6, -20, -10, -16]]
, [[4, 8, -12, 2, -14, -18, -6, -20, -10, -16]]
, [[4, 8, -12, 2, 14, 18, -6, 20, 10, 16]]
, [[4, 8, 10, -14, 2, -18, -6, -20, -12, -16]]
, [[4, 8, 10, -14, 2, -16, -18, -6, -20, -12]]
, [[4, 8, 10, -14, 2, 16, 18, -6, 20, 12]]
, [[4, 10, -14, -16, 2, -18, -20, -6, -8, -12]]
, [[4, 10, -14, -16, 2, 18, 20, -8, -6, 12]]
, [[4, 10, -14, -16, 2, 18, -8, -6, 20, 12]]
, [[4, 10, -14, -16, 2, -18, -20, -8, -6, -12]]
, [[4, 10, -14, -16, 2, -18, -8, -6, -20, -12]]
, [[4, 10, 14, 16, 2, -18, -20, 8, 6, -12]]
, [[4, 8, -12, -18, 2, -16, -20, -6, -10, -14]]
, [[4, 8, -18, -12, 2, -16, -20, -6, -10, -14]]
, [[4, 10, -14, 12, 2, 16, 18, -20, 8, -6]]
, [[4, 8, -12, 2, -16, -6, -18, -20, -10, -14]]
, [[4, 8, -12, 2, 16, -6, 18, 20, 10, 14]]
, [[4, 8, -12, 2, -16, -6, -18, -10, -20, -14]]
, [[4, 8, -12, 2, 16, -6, 18, 10, 20, 14]]
, [[6, 8, 12, 2, -16, 4, -18, -20, -10, -14]]
, [[4, 8, 12, 2, -16, 6, -18, -20, -10, -14]]
, [[4, 8, 12, 2, -16, 6, -18, -10, -20, -14]]
, [[6, 10, 14, 16, 18, 4, -20, 2, 8, -12]]
, [[4, 12, 16, -14, 18, 2, -8, 20, 10, 6]]
, [[6, -10, -18, 14, -2, -16, 20, 8, -4, 12]]
, [[6, -10, -16, 14, -2, -18, 8, 20, -4, -12]]
, [[6, 8, 10, 14, 16, -18, -20, 2, 4, -12]]
, [[4, 12, -16, -14, -18, 2, -8, -20, -10, -6]]
, [[4, 12, -16, 14, -18, 2, 8, -20, -10, -6]]
, [[6, 10, 14, 18, 16, 4, -20, 2, 8, -12]]
, [[6, 8, 10, 14, 16, -20, -18, 2, 4, -12]]
, [[6, -10, -12, 14, -18, -16, 20, -2, -4, -8]]
, [[6, 8, 14, 18, 16, 4, -20, 10, 2, -12]]
])
]
| mishun/tangles | src/Math/Topology/KnotTh/Tangle/TableOfLinks.hs | lgpl-3.0 | 18,676 | 0 | 10 | 7,263 | 14,321 | 9,406 | 4,915 | 406 | 1 |
------------------------------------------------------------------------------
-- |
-- Module : Control.Concurrent.Barrier.Test
-- Copyright : (C) 2010 Aliaksiej Artamonaŭ
-- License : LGPL
--
-- Maintainer : aliaksiej.artamonau@gmail.com
-- Stability : unstable
-- Portability : unportable
--
-- Unit tests for 'Control.Concurrent.Barrier' module.
--
------------------------------------------------------------------------------
------------------------------------------------------------------------------
module Control.Concurrent.Barrier.Test ( tests )
where
------------------------------------------------------------------------------
------------------------------------------------------------------------------
import Control.Concurrent ( forkIO, threadDelay )
import Control.Concurrent.MVar ( MVar, newMVar, readMVar, modifyMVar_ )
import Control.Monad ( forM_, replicateM_ )
------------------------------------------------------------------------------
import Test.Framework ( Test )
import Test.Framework.Providers.HUnit ( testCase )
import Test.HUnit ( Assertion, assertEqual )
------------------------------------------------------------------------------
import Control.Concurrent.Barrier ( Barrier )
import qualified Control.Concurrent.Barrier as Barrier
------------------------------------------------------------------------------
wait :: IO ()
wait = threadDelay 500000
------------------------------------------------------------------------------
tests :: [Test]
tests = [ testCase "wait" test_wait,
testCase "waitCount" test_waitCount
]
------------------------------------------------------------------------------
test_wait :: Assertion
test_wait = do
b <- Barrier.new 5
finished <- newMVar 0
assertFinished finished 0
replicateM_ 4 $ do
worker b finished
wait
assertFinished finished 0
Barrier.wait b
wait
assertFinished finished 4
where worker :: Barrier -> MVar Int -> IO ()
worker b finished = do
forkIO $ do
Barrier.wait b
modifyMVar_ finished (return . (+1))
return ()
assertFinished :: MVar Int -> Int -> IO ()
assertFinished finished n = do
f <- readMVar finished
assertEqual msg n f
where msg = "Number of finished threads is not equal to " ++ show n
------------------------------------------------------------------------------
test_waitCount :: Assertion
test_waitCount = do
b <- Barrier.new 5
assertWaiting b 0
forM_ [1 .. 4] $ \i -> do
worker b
wait
assertWaiting b i
Barrier.wait b
assertWaiting b 0
where assertWaiting :: Barrier -> Int -> IO ()
assertWaiting barrier n = do
waiting <- Barrier.waitingCount barrier
assertEqual msg n waiting
where msg = "Number of waiting threads is not equal to " ++ show n
worker :: Barrier -> IO ()
worker b = do
forkIO $ Barrier.wait b
return ()
------------------------------------------------------------------------------
| aartamonau/haskell-barrier | tests/Control/Concurrent/Barrier/Test.hs | lgpl-3.0 | 3,117 | 0 | 15 | 615 | 604 | 310 | 294 | 56 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : VizViews
Description : Defines the some different look of graphs for the module graphviz.
Copyright : (c) Hans-Jürgen Guth, 2014
License : LGPL
Maintainer : juergen.software@freea2a.de
Stability : experimental
Here is the look of the graphs from graphviz defined.
Feel free to add your own. For more information to the source code,
refer to the docu of the module graphviz.
-}
module VizViews (recordView1, defaultView) where
import TestExplode.TestExplode
import Data.Graph.Inductive.Graph
import Data.Graph.Inductive.PatriciaTree (Gr)
import Data.GraphViz
import Data.GraphViz.Attributes.Complete
import qualified Data.Text.Lazy as L
-- | From the docu of GraphViz. Only numbers in the nodes.
-- But as a test it works.
defaultView :: (Graph gr) => gr nl el -> DotGraph Node
defaultView = graphToDot nonClusteredParams
-- | My own favorite view of the graph
recordView1 :: GraphvizParams Node (Maybe (CasepartInternal cnf locals), Maybe TGDocuInfo)
()
()
(Maybe (CasepartInternal cnf locals), Maybe TGDocuInfo)
recordView1 = nonClusteredParams { fmtNode = fmtNodeMy }
fmtNodeMy :: (Node, (Maybe (CasepartInternal cnf locals), Maybe TGDocuInfo))
-> Attributes
fmtNodeMy (_, mcp) = case mcp of
(Just cp, _) ->
let bgcolor = if cpTypeI cp == Mark
then LightGoldenrod2 --YellowGreen
else
if condDescI cp == ""
then LightGoldenrodYellow
else Yellow
in
let attrs = [ shape Record
, style filled]
in
if condDescI cp ==""
then [Label (RecordLabel [FlipFields[ FieldLabel (shortDescI cp)
]
]
), fillColor bgcolor]
++ attrs
else [Label (RecordLabel [FlipFields[ FieldLabel (condDescI cp)
, FieldLabel (shortDescI cp)
]
]
), fillColor bgcolor]
++ attrs
(Nothing, Nothing) ->
[ styles [filled, dotted]
, fillColor LightGray
, toLabel L.empty]
(Nothing, Just di) -> -- testgraph that is not expanded
[shape Record,
styles [bold, filled],
fillColor Orange,
fontColor Blue,
FontName (L.pack("Times-Italic")),
-- change ".svg" if you use other extensions for the
-- picture of the graph
-- change "../subgraphs/", if you use another
-- subdirectory for the subgraphs
URL (L.pack("../subgraphs/" ++ name di ++ ".svg")),
Label (RecordLabel [FlipFields[ FieldLabel (L.pack ((name di)
++ "\n"
++ (descForNode di) ))
]
])]
| testexplode/testexplode | doc/examples/VizViews.hs | lgpl-3.0 | 3,553 | 0 | 23 | 1,631 | 597 | 324 | 273 | 48 | 6 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Kubernetes.V1.VolumeMount where
import GHC.Generics
import Data.Text
import qualified Data.Aeson
-- | VolumeMount describes a mounting of a Volume within a container.
data VolumeMount = VolumeMount
{ name :: Text -- ^ This must match the Name of a Volume.
, readOnly :: Maybe Bool -- ^ Mounted read-only if true, read-write otherwise (false or unspecified). Defaults to false.
, mountPath :: Text -- ^ Path within the container at which the volume should be mounted.
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON VolumeMount
instance Data.Aeson.ToJSON VolumeMount
| minhdoboi/deprecated-openshift-haskell-api | kubernetes/lib/Kubernetes/V1/VolumeMount.hs | apache-2.0 | 776 | 0 | 9 | 130 | 97 | 60 | 37 | 16 | 0 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QToolBarChangeEvent.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.QToolBarChangeEvent (
QqToolBarChangeEvent(..)
,QqToolBarChangeEvent_nf(..)
,qToolBarChangeEvent_delete
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqToolBarChangeEvent x1 where
qToolBarChangeEvent :: x1 -> IO (QToolBarChangeEvent ())
instance QqToolBarChangeEvent ((Bool)) where
qToolBarChangeEvent (x1)
= withQToolBarChangeEventResult $
qtc_QToolBarChangeEvent (toCBool x1)
foreign import ccall "qtc_QToolBarChangeEvent" qtc_QToolBarChangeEvent :: CBool -> IO (Ptr (TQToolBarChangeEvent ()))
instance QqToolBarChangeEvent ((QToolBarChangeEvent t1)) where
qToolBarChangeEvent (x1)
= withQToolBarChangeEventResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBarChangeEvent1 cobj_x1
foreign import ccall "qtc_QToolBarChangeEvent1" qtc_QToolBarChangeEvent1 :: Ptr (TQToolBarChangeEvent t1) -> IO (Ptr (TQToolBarChangeEvent ()))
class QqToolBarChangeEvent_nf x1 where
qToolBarChangeEvent_nf :: x1 -> IO (QToolBarChangeEvent ())
instance QqToolBarChangeEvent_nf ((Bool)) where
qToolBarChangeEvent_nf (x1)
= withObjectRefResult $
qtc_QToolBarChangeEvent (toCBool x1)
instance QqToolBarChangeEvent_nf ((QToolBarChangeEvent t1)) where
qToolBarChangeEvent_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBarChangeEvent1 cobj_x1
instance Qtoggle (QToolBarChangeEvent a) (()) (IO (Bool)) where
toggle x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBarChangeEvent_toggle cobj_x0
foreign import ccall "qtc_QToolBarChangeEvent_toggle" qtc_QToolBarChangeEvent_toggle :: Ptr (TQToolBarChangeEvent a) -> IO CBool
qToolBarChangeEvent_delete :: QToolBarChangeEvent a -> IO ()
qToolBarChangeEvent_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBarChangeEvent_delete cobj_x0
foreign import ccall "qtc_QToolBarChangeEvent_delete" qtc_QToolBarChangeEvent_delete :: Ptr (TQToolBarChangeEvent a) -> IO ()
| keera-studios/hsQt | Qtc/Gui/QToolBarChangeEvent.hs | bsd-2-clause | 2,562 | 0 | 12 | 352 | 554 | 296 | 258 | -1 | -1 |
import Prelude
import System.Random
import Data.List
lottoSelect :: Int -> Int -> IO [Int]
lottoSelect k n
| k < 0 || n <= 0 = error "k has to be positive and n non-negative."
| otherwise = do
gen <- newStdGen
return (take k (nub (randomRs (1, n) gen)))
| 2dor/99-problems-Haskell | 21-28-lists-again/problem-24.hs | bsd-2-clause | 279 | 0 | 15 | 75 | 114 | 56 | 58 | 9 | 1 |
{-# LANGUAGE Trustworthy #-}
module Control.Concurrent.MVar (
MVar, newMVar, newEmptyMVar, isEmptyMVar, tryTakeMVar, takeMVar, tryPutMVar, tryReadMVar,
readMVar, putMVar, swapMVar, modifyMVar, modifyMVar_,
) where
import System.Mock.IO.Internal
| 3of8/mockio | New_MVar.hs | bsd-2-clause | 258 | 0 | 4 | 37 | 57 | 39 | 18 | 5 | 0 |
{-# LANGUAGE FlexibleContexts #-}
module HERMIT.Dictionary.New where
import Control.Arrow
import HERMIT.Context
import HERMIT.Core
import HERMIT.Kure
import HERMIT.External
import HERMIT.GHC
import HERMIT.ParserCore
import HERMIT.Dictionary.Local.Let hiding (externals)
externals :: [External]
externals = map ((.+ Experiment) . (.+ TODO))
[ external "var" (promoteExprT . isVar :: String -> TransformH LCore ())
[ "var '<v> returns successfully for variable v, and fails otherwise."
, "Useful in combination with \"when\", as in: when (var v) r"
] .+ Predicate
, external "nonrec-intro" ((\ s str -> promoteCoreR (nonRecIntro s str)) :: String -> CoreString -> RewriteH LCore)
[ "Introduce a new non-recursive binding. Only works at Expression or Program nodes."
, "nonrec-into 'v [| e |]"
, "body ==> let v = e in body"
] .+ Introduce .+ Shallow
-- , external "prog-nonrec-intro" ((\ nm core -> promoteProgR $ progNonRecIntro nm core) :: String -> CoreString -> RewriteH Core)
-- [ "Introduce a new top-level definition."
-- , "prog-nonrec-into 'v [| e |]"
-- , "prog ==> ProgCons (v = e) prog" ] .+ Introduce .+ Shallow
-- , external "let-nonrec-intro" ((\ nm core -> promoteExprR $ letNonRecIntro nm core) :: String -> CoreString -> RewriteH Core)
-- [ "Introduce a new definition as a non-recursive let binding."
-- , "let-nonrec-intro 'v [| e |]"
-- , "body ==> let v = e in body" ] .+ Introduce .+ Shallow
]
------------------------------------------------------------------------------------------------------
-- TODO: We might not want to match on TyVars and CoVars here.
-- Probably better to have another predicate that operates on CoreTC, that way it can reach TyVars buried within types.
-- But given the current setup (using Core for most things), changing "var" to operate on CoreTC would make it incompatible with other combinators.
-- I'm not sure how to fix the current setup though.
-- isVar :: (ExtendPath c Crumb, AddBindings c, MonadCatch m) => String -> Transform c m CoreExpr ()
-- isVar nm = (varT matchName <+ typeT (tyVarT matchName) <+ coercionT (coVarCoT matchName))
-- >>= guardM
-- where
-- matchName :: Monad m => Transform c m Var Bool
-- matchName = arr (cmpString2Var nm)
-- TODO: there might be a better module for this
-- | Test if the current expression is an identifier matching the given name.
isVar :: (ExtendPath c Crumb, AddBindings c, MonadCatch m) => String -> Transform c m CoreExpr ()
isVar nm = varT (arr $ cmpString2Var nm) >>= guardM
------------------------------------------------------------------------------------------------------
-- The types of these can probably be generalised after the Core Parser is generalised.
-- | @prog@ ==> @'ProgCons' (v = e) prog@
nonRecIntro :: String -> CoreString -> RewriteH Core
nonRecIntro nm expr = parseCoreExprT expr >>= nonRecIntroR nm
-- TODO: if e is not type-correct, then exprType will crash.
-- Proposal: parseCore should check that its result is (locally) well-typed
-- -- | @prog@ ==> @'ProgCons' (v = e) prog@
-- progNonRecIntro :: String -> CoreString -> RewriteH CoreProg
-- progNonRecIntro nm expr = parseCoreExprT expr >>= progNonRecIntroR nm
-- -- TODO: if e is not type-correct, then exprType will crash.
-- -- Proposal: parseCore should check that its result is (locally) well-typed
-- -- | @body@ ==> @let v = e in body@
-- letNonRecIntro :: String -> CoreString -> RewriteH CoreExpr
-- letNonRecIntro nm expr = parseCoreExprT expr >>= letNonRecIntroR nm
-- -- TODO: if e is not type-correct, then exprTypeOrKind will crash.
-- -- Proposal: parseCore should check that its result is (locally) well-typed
------------------------------------------------------------------------------------------------------
| beni55/hermit | src/HERMIT/Dictionary/New.hs | bsd-2-clause | 4,066 | 0 | 15 | 920 | 336 | 201 | 135 | 25 | 1 |
{-# LANGUAGE RankNTypes #-}
module Web.Twitter.Conduit.Lens
(
-- * 'TT.Response'
TT.Response
, responseStatus
, responseBody
, responseHeaders
-- * 'TT.TwitterErrorMessage'
, TT.TwitterErrorMessage
, twitterErrorMessage
, twitterErrorCode
-- * 'TT.WithCursor'
, TT.WithCursor
, previousCursor
, nextCursor
, contents
-- * Re-exports
, TT.TwitterError(..)
, TT.CursorKey (..)
, TT.IdsCursorKey
, TT.UsersCursorKey
, TT.ListsCursorKey
) where
import Control.Lens
import Data.Text (Text)
import Network.HTTP.Types (Status, ResponseHeaders)
import qualified Web.Twitter.Conduit.Cursor as TT
import qualified Web.Twitter.Conduit.Response as TT
-- * Lenses for 'TT.Response'
responseStatus :: forall responseType. Lens' (TT.Response responseType) Status
responseStatus afb s = (\b -> s { TT.responseStatus = b }) <$> afb (TT.responseStatus s)
responseHeaders :: forall responseType. Lens' (TT.Response responseType) ResponseHeaders
responseHeaders afb s = (\b -> s {TT.responseHeaders = b }) <$> afb (TT.responseHeaders s)
responseBody :: forall a b. Lens (TT.Response a) (TT.Response b) a b
responseBody afb s = (\b -> s { TT.responseBody = b }) <$> afb (TT.responseBody s)
-- * Lenses for 'TT.TwitterErrorMessage'
twitterErrorCode :: Lens' TT.TwitterErrorMessage Int
twitterErrorCode afb s = (\b -> s { TT.twitterErrorCode = b }) <$> afb (TT.twitterErrorCode s)
twitterErrorMessage :: Lens' TT.TwitterErrorMessage Text
twitterErrorMessage afb s = (\b -> s { TT.twitterErrorMessage = b }) <$> afb (TT.twitterErrorMessage s)
-- * Lenses for 'TT.WithCursor'
previousCursor :: forall cursorType cursorKey wrapped. Lens' (TT.WithCursor cursorType cursorKey wrapped) (Maybe cursorType)
previousCursor afb s = (\b -> s { TT.previousCursor = b }) <$> afb (TT.previousCursor s)
nextCursor :: forall cursorType cursorKey wrapped. Lens' (TT.WithCursor cursorType cursorKey wrapped) (Maybe cursorType)
nextCursor afb s = (\b -> s { TT.nextCursor = b }) <$> afb (TT.nextCursor s)
contents :: forall cursorType cursorKey a b. Lens (TT.WithCursor cursorType cursorKey a) (TT.WithCursor cursorType cursorKey b) [a] [b]
contents afb s = (\b -> s { TT.contents = b }) <$> afb (TT.contents s)
| Javran/twitter-conduit | Web/Twitter/Conduit/Lens.hs | bsd-2-clause | 2,339 | 0 | 9 | 465 | 711 | 401 | 310 | 40 | 1 |
{-# LANGUAGE Haskell2010 #-}
-- | Exporting records.
module Bug6( A(A), B(B), b, C(C,c1,c2), D(D,d1), E(E) ) where
-- |
-- This record is exported without its field
data A = A { a :: Int }
-- |
-- .. with its field, but the field is named separately in the export list
-- (the field isn't documented separately since it is already documented here)
data B = B { b :: Int }
-- |
-- .. with fields names as subordinate names in the export
data C = C { c1 :: Int, c2 :: Int }
-- |
-- .. with only some of the fields exported (we can't handle this one -
-- how do we render the declaration?)
data D = D { d1 :: Int, d2 :: Int }
-- | a newtype with a field
newtype E = E { e :: Int }
| haskell/haddock | html-test/src/Bug6.hs | bsd-2-clause | 683 | 0 | 8 | 157 | 148 | 103 | 45 | 18 | 0 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Signal.Core
( Sig(..)
, Signal(..)
, Symbol(..)
, S(..)
, U
, variable
, delay
, Wit(..)
, Witness(..)
, lift
, lift0
, lift1
, lift2
) where
import Control.Monad.Operational.Compositional hiding (join)
import Language.Embedded.VHDL (PredicateExp)
import Signal.Core.Stream (Stream(..))
import qualified Signal.Core.Stream as S
import Data.Bits (Bits)
import Data.Functor.Identity
import Data.Typeable (Typeable)
import Data.Dynamic (Dynamic)
import Data.Ref
import Data.Unique
import Prelude hiding (Left, Right, map, repeat)
import qualified Prelude as P
--------------------------------------------------------------------------------
-- * Signals
--------------------------------------------------------------------------------
newtype Sig i a = Sig (Signal i (Identity a))
newtype Signal i a = Signal (Symbol i a)
newtype Symbol i a = Symbol (Ref (S Symbol i a))
data S sig i a
where
Repeat :: (Typeable a, PredicateExp (IExp i) a)
=> Stream i (IExp i a) -> S sig i (Identity a)
Map :: ( Witness i a, Typeable a
, Witness i b, Typeable b
)
=> (Stream i (U i a) -> Stream i (U i b))
-> sig i a -> S sig i b
Join :: ( Witness i a, Typeable a
, Witness i b, Typeable b
)
=> sig i a -> sig i b -> S sig i (a, b)
Left :: ( Witness i a, Typeable a
, Witness i b, Typeable b
)
=> sig i (a, b) -> S sig i a
Right :: ( Witness i a, Typeable a
, Witness i b, Typeable b
)
=> sig i (a, b) -> S sig i b
Delay :: (Typeable a, PredicateExp (IExp i) a)
=> IExp i a -> sig i (Identity a) -> S sig i (Identity a)
Var :: (Witness i a, Typeable a)
=> Dynamic -> S sig i a
-- | Type for nested tuples, stripping away all Identity
type family U (i :: (* -> *) -> * -> *) a :: *
type instance U i (Identity a) = IExp i a
type instance U i (a, b) = (U i a, U i b)
--------------------------------------------------------------------------------
-- ** Some `smart` constructions
signal :: S Symbol i a -> Signal i a
signal = Signal . symbol
symbol :: S Symbol i a -> Symbol i a
symbol = Symbol . ref
unsymbol :: Symbol i a -> S Symbol i a
unsymbol (Symbol s) = deref s
--------------------------------------------------------------------------------
-- **
repeat
:: (Typeable a, PredicateExp (IExp i) a)
=> Stream i (U i (Identity a))
-> Signal i (Identity a)
repeat s = signal $ Repeat s
map
:: ( Witness i a, Typeable a
, Witness i b, Typeable b
)
=> (Stream i (U i a) -> Stream i (U i b))
-> Signal i a
-> Signal i b
map f (Signal s) = signal $ Map f s
join
:: ( Witness i a, Typeable a
, Witness i b, Typeable b
)
=> Signal i a
-> Signal i b
-> Signal i (a, b)
join (Signal a) (Signal b) = signal $ Join a b
left
:: ( Witness i a, Typeable a
, Witness i b, Typeable b
)
=> Signal i (a, b)
-> Signal i a
left (Signal s) = signal $ Left s
right
:: ( Witness i a, Typeable a
, Witness i b, Typeable b
)
=> Signal i (a, b)
-> Signal i b
right (Signal s) = signal $ Right s
variable
:: (Witness i a, Typeable a)
=> Dynamic
-> Signal i a
variable = signal . Var
--------------------------------------------------------------------------------
-- **
delay :: (Typeable a, PredicateExp e a, e ~ IExp i) => e a -> Sig i a -> Sig i a
delay e (Sig (Signal s)) = Sig . signal $ Delay e s
--------------------------------------------------------------------------------
-- ** Properties of signals
instance Eq (Signal i a) where
Signal (Symbol s1) == Signal (Symbol s2) = s1 == s2
instance (Num (IExp i a), PredicateExp (IExp i) a, Bits a, Typeable a) => Num (Sig i a) where
(+) = lift2 (+)
(-) = lift2 (-)
(*) = lift2 (*)
negate = lift1 negate
abs = lift1 abs
signum = lift1 signum
fromInteger = lift0 . fromInteger
instance (Fractional (IExp i a), PredicateExp (IExp i) a, Bits a, Typeable a) => Fractional (Sig i a) where
(/) = lift2 (/)
recip = lift1 recip
fromRational = lift0 . fromRational
--------------------------------------------------------------------------------
-- * Nested Signals
--------------------------------------------------------------------------------
data Wit i a
where
WE :: ( Typeable a
, PredicateExp (IExp i) a
)
=> Wit i (Identity a)
WP :: ( Witness i a, Typeable a
, Witness i b, Typeable b
)
=> Wit i a -> Wit i b -> Wit i (a, b)
class Witness i a
where
wit :: Wit i a
instance
( Typeable a
, PredicateExp (IExp i) a
)
=> Witness i (Identity a)
where
wit = WE
instance forall i a b.
( Witness i a, Typeable a
, Witness i b, Typeable b
)
=> Witness i (a, b)
where
wit = WP (wit :: Wit i a) (wit :: Wit i b)
--------------------------------------------------------------------------------
-- ** Type for nested tuples of signals
type family Packed (i :: (* -> *) -> * -> *) a :: *
type instance Packed i (Identity a) = Sig i a
type instance Packed i (a, b) = (Packed i a, Packed i b)
pack :: forall i a. Witness i a => Signal i a -> Packed i a
pack s = go (wit :: Wit i a) s
where
go :: Wit i x -> Signal i x -> Packed i x
go (WE) s = Sig s
go (WP u v) s = (,) (go u $ left s) (go v $ right s)
unpack :: forall i a. Witness i a => Packed i a -> Signal i a
unpack s = go (wit :: Wit i a) s
where
go :: Wit i x -> Packed i x -> Signal i x
go (WE) (Sig s) = s
go (WP u v) (l, r) = join (go u l) (go v r)
--------------------------------------------------------------------------------
-- ** General lifting operator
-- todo: I don't like the proxy, or the type family. Possible to find U^(-1)?
lift :: forall proxy i e a b.
( Witness i a, Typeable a
, Witness i b, Typeable b
, e ~ IExp i
)
=> proxy i a b
-> (U i a -> U i b)
-> (Packed i a -> Packed i b)
lift _ f = pack . h . unpack
where
g = stream f :: Stream i (U i a) -> Stream i (U i b)
h = map (stream f) :: Signal i a -> Signal i b
stream :: (a -> b) -> (Stream i a -> Stream i b)
stream f (Stream s) = Stream $ fmap (fmap f) s
--------------------------------------------------------------------------------
-- ** Some common lifting operations
lift0
:: ( Typeable a, PredicateExp e a
, e ~ IExp i
)
=> e a
-> Sig i a
lift0 = Sig . repeat . S.repeat
lift1
:: forall i e a b.
( Typeable a, PredicateExp e a
, Typeable b, PredicateExp e b
, e ~ IExp i
)
=> (e a -> e b)
-> Sig i a
-> Sig i b
lift1 f = lift p f
where
p = undefined :: proxy i (Identity a) (Identity b)
lift2
:: forall i e a b c.
( Typeable a, PredicateExp e a
, Typeable b, PredicateExp e b
, Typeable c, PredicateExp e c
, e ~ IExp i
)
=> (e a -> e b -> e c)
-> Sig i a
-> Sig i b
-> Sig i c
lift2 f = curry $ lift p $ uncurry f
where
p = undefined :: proxy i (Identity a, Identity b) (Identity c)
--------------------------------------------------------------------------------
-- the end.
| markus-git/signal | src/Signal/Core.hs | bsd-3-clause | 7,689 | 15 | 19 | 2,243 | 3,019 | 1,587 | 1,432 | 190 | 2 |
{-# LANGUAGE Strict #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.Aeson as A
import qualified Data.ByteString.Lazy as L
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid ((<>))
import qualified Data.Text as T
import qualified Handlers.Lono as LO
import qualified Handlers.Main as MA
import qualified Handlers.Xandar as XA
import Network.Wai
import Network.Wai.Handler.Warp
import Network.Wai.Middleware.RequestLogger
import System.Environment
import Types.Common
main :: IO ()
main = do
args <- getArgs
conf <- getConfig args
env <- lookupEnv "KAPI_ENV"
let port = appPort conf
let dev = (== Just "development") env
let envDesc = withEnv dev "development mode" "production mode"
putStrLn ("Server started on port " ++ show port ++ " in " ++ envDesc)
let xandarConf = getApiConfig "xandar" conf
let lonoConf = getApiConfig "lono" conf
LO.appInit lonoConf
XA.appInit xandarConf
runApp dev (MA.app xandarConf lonoConf) conf
getApiConfig :: ApiName -> AppConfig -> ApiConfig
getApiConfig apiName conf =
ApiConfig
{ apiPort = appPort conf
, mongoServer = getApiValue (appMongoServers conf) apiName
, mongoDatabase = getApiValue (appMongoDbs conf) apiName
, esIndex = getApiValue (appEsIndices conf) apiName
, esServer = getApiValue (appEsServers conf) apiName
}
getApiValue :: Show a => Map.Map ApiName a -> ApiName -> a
getApiValue appMap apiName =
fromMaybe (get "default") (Map.lookup apiName appMap)
where
get name =
fromMaybe
(error $ "Key " ++ T.unpack name ++ " not found in map " ++ show appMap)
(Map.lookup name appMap)
getConfig :: [String] -> IO AppConfig
getConfig [] = readConfigFile "./config/default.json"
getConfig (f:_) = readConfigFile f
readConfigFile :: String -> IO AppConfig
readConfigFile f = do
putStrLn $ "Config file " <> f
json <- L.readFile f
return $ fromJust (A.decode json)
runApp :: Bool -> Application -> AppConfig -> IO ()
runApp dev app conf = do
let port = fromIntegral $ appPort conf
run port $ withEnv dev logStdoutDev id app
withEnv :: Bool -> t -> t -> t
withEnv dev fd fp =
if dev
then fd
else fp
| gabesoft/kapi | app/Main.hs | bsd-3-clause | 2,202 | 0 | 13 | 432 | 712 | 367 | 345 | 63 | 2 |
module NFA where
type RMachine m a = Flow
| igraves/flow-arrow | examples/nfa.hs | bsd-3-clause | 45 | 0 | 4 | 12 | 12 | 9 | 3 | 2 | 0 |
{-# LANGUAGE UndecidableSuperClasses #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE NoRebindableSyntax #-}
module Spatial98
where
import Prelude (fromInteger, Bool(..), Monad(..))
import qualified Prelude as P
import Data.Foldable
import Data.List
import Data.Typeable
import LocalPrelude
import Lattice
import Topology
import FAlgebra98
import Test.Tasty
import Test.Tasty.Ingredients.Basic
import Test.Tasty.Options
import Test.Tasty.Runners
import qualified Test.Tasty.SmallCheck as SC
import qualified Test.Tasty.QuickCheck as QC
import Test.QuickCheck hiding (Testable)
import Debug.Trace
--------------------------------------------------------------------------------
data EpsLaw (alg :: * -> Constraint) a = EpsLaw
{ epsLawName :: String
, epsilon :: [a] -> Neighborhood a
}
class (HomVariety alg, alg a, Topology a) => Approximate98 alg a where
epsLaws :: [EpsLaw alg a]
instance {-#OVERLAPPABLE#-} (HomVariety alg, alg a, Topology a) => Approximate98 alg a where
epsLaws = []
--------------------------------------------------------------------------------
lookupEpsLaw :: forall alg a.
( Approximate98 alg a
) => String
-> EpsLaw alg a
lookupEpsLaw lawName = case lookup lawName lawmap of
Just x -> x
Nothing -> EpsLaw lawName lowerBound
where
lawmap = map (\x -> (epsLawName x,x)) (epsLaws::[EpsLaw alg a])
epsLaw2quickcheck :: forall (a :: *) alg.
( HomVariety alg
, alg a
, HomTestable a
, Topology a
) => Proxy a -> Law alg -> TestTree
epsLaw2quickcheck p law = QC.testProperty (lawName law) $ do
as <- infiniteListOf (arbitrary::Gen a)
let eps = epsilon (lookupEpsLaw $ lawName law :: EpsLaw alg a) as
return $ checkApproximate as law eps
checkApproximate ::
( Approximate98 alg a
, HomTestable a
) => [a] -> Law alg -> Logic a
checkApproximate as law
= (runHomAST $ subVars (lhs law) varmap)
== (runHomAST $ subVars (rhs law) varmap)
where
varmap = zip (toList (lhs law) ++ toList (rhs law)) as
approxclass2tasty :: forall alg a.
( HomVariety alg
, alg a
, HomTestable a
, Topology a
) => Proxy alg -> Proxy a -> TestTree
approxclass2tasty palg pa = testGroup
( show (typeRep palg) ++ " on " ++ show (typeRep pa) )
$ map (epsLaw2quickcheck pa) (laws::[Law alg])
-- runTestsApprox :: forall alg a.
-- ( HomVariety alg
-- , alg a
-- , HomTestable a
-- , Topology a
-- ) => Proxy alg -> Proxy a -> IO ()
-- -- runTestsApprox _ _ = return ()
-- runTestsApprox = runTasty (approxclass2tasty (Proxy::Proxy alg) (Proxy::Proxy a))
runTasty :: TestTree -> IO ()
runTasty tt = do
case tryIngredients [consoleTestReporter] (singleOption (HideSuccesses True)) tt of
Just x -> x
return ()
instance LowerBounded a => Show (a -> Bool) where
show f = show $ f lowerBound
| mikeizbicki/homoiconic | old/Homogeneous/Spatial98.hs | bsd-3-clause | 2,920 | 34 | 10 | 623 | 827 | 464 | 363 | -1 | -1 |
import Lib
main = basicTest defaultConfig
| willdonnelly/dyre | Tests/basic/Main.hs | bsd-3-clause | 42 | 0 | 5 | 6 | 12 | 6 | 6 | 2 | 1 |
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
module Data.Vitals where
import qualified Prelude
import Control.Lens (makeLenses)
import Data.HasTime (HasTime(..))
import Data.Time (UTCTime)
import Data.Time.Format ()
import Data.Time.LocalTime ()
import Numeric.Units.Dimensional.Prelude
data Weight = Weight {
_wTime :: UTCTime
, _wWeight :: Mass Float
} deriving (Eq, Show)
instance HasTime Weight where
time' elt_fn w =
(\t' -> w { _wTime = t' }) <$> elt_fn (_wTime w)
averageWeight :: [Weight] -> Mass Float
averageWeight ws = average (\a -> _wWeight a /~ kilo gram) ws *~ kilo gram
-- rAverageWeight :: [Weight] -> Weight
-- rAverageWeight ws = rAverage (\a -> a /~ kilo gram) ws *~ kilo gram
-- weightChange :: Weight -> Weight -> Weight
-- weightChange w1 w2 = w1 - w2
data BloodPressure = BloodPressure {
_bpTime :: UTCTime
, _bpSystolic :: Int
, _bpDiastolic :: Int
, _bpPulse :: Int
} deriving (Eq, Show)
-- averageBP :: [BloodPressure] -> BloodPressure
-- averageBP = averageBP_ average
-- rAverageBP :: [BloodPressure] -> BloodPressure
-- rAverageBP = averageBP_ rAverage
-- averageBP_ :: forall t c. Num c => ((BloodPressure -> c) -> t -> Float) -> t -> BloodPressure
-- averageBP_ avg bps =
-- let avgSystolic = round (avg (fromIntegral . bpSystolic) bps :: Float)
-- avgDiastolic = round (avg (fromIntegral . bpDiastolic) bps :: Float)
-- avgPulse = round (avg (fromIntegral . bpPulse) bps :: Float)
-- in BloodPressure avgSystolic avgDiastolic avgPulse
average :: Fractional a => (b -> a) -> [b] -> a
average field bps = Prelude.sum (fmap field bps) Prelude./ fromIntegral (length bps)
-- rAverage :: forall a b. Fractional a => (b -> a) -> [b] -> a
-- rAverage func = ravg Nothing . fmap func
-- where
-- f :: a -> a -> a
-- f b q = b Prelude.+ 0.1 Prelude.* (q Prelude.- b)
-- ravg :: Maybe a -> [a] -> a
-- ravg Nothing [] = 0.0
-- ravg Nothing (w:ws) = ravg (Just w) ws
-- ravg (Just base) [] = base
-- ravg (Just base) (w:ws) = ravg (Just $ f base w) ws
runningAverage :: (Show a, Fractional a) => [a] -> [a]
runningAverage [] = [0.0]
runningAverage [x] = [x]
runningAverage (x:rst) =
let (prev:lst) = runningAverage rst in (prev Prelude.+ 0.1 Prelude.* (x Prelude.- prev)):prev:lst
makeLenses ''Weight
makeLenses ''BloodPressure
| savannidgerinel/health | src/Data/Vitals.hs | bsd-3-clause | 2,650 | 0 | 12 | 664 | 487 | 279 | 208 | 37 | 1 |
{-# language CPP #-}
-- | = Name
--
-- VK_KHR_spirv_1_4 - device extension
--
-- == VK_KHR_spirv_1_4
--
-- [__Name String__]
-- @VK_KHR_spirv_1_4@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 237
--
-- [__Revision__]
-- 1
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.1
--
-- - Requires @VK_KHR_shader_float_controls@
--
-- [__Deprecation state__]
--
-- - /Promoted/ to
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.2-promotions Vulkan 1.2>
--
-- [__Contact__]
--
-- - Jesse Hall
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_spirv_1_4] @critsec%0A<<Here describe the issue or question you have about the VK_KHR_spirv_1_4 extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2019-04-01
--
-- [__IP Status__]
-- No known IP claims.
--
-- [__Interactions and External Dependencies__]
--
-- - Requires SPIR-V 1.4.
--
-- - Promoted to Vulkan 1.2 Core
--
-- [__Contributors__]
--
-- - Alexander Galazin, Arm
--
-- - David Neto, Google
--
-- - Jesse Hall, Google
--
-- - John Kessenich, Google
--
-- - Neil Henning, AMD
--
-- - Tom Olson, Arm
--
-- == Description
--
-- This extension allows the use of SPIR-V 1.4 shader modules. SPIR-V 1.4’s
-- new features primarily make it an easier target for compilers from
-- high-level languages, rather than exposing new hardware functionality.
--
-- SPIR-V 1.4 incorporates features that are also available separately as
-- extensions. SPIR-V 1.4 shader modules do not need to enable those
-- extensions with the @OpExtension@ opcode, since they are integral parts
-- of SPIR-V 1.4.
--
-- SPIR-V 1.4 introduces new floating point execution mode capabilities,
-- also available via @SPV_KHR_float_controls@. Implementations are not
-- required to support all of these new capabilities; support can be
-- queried using
-- 'Vulkan.Extensions.VK_KHR_shader_float_controls.PhysicalDeviceFloatControlsPropertiesKHR'
-- from the @VK_KHR_shader_float_controls@ extension.
--
-- == Promotion to Vulkan 1.2
--
-- All functionality in this extension is included in core Vulkan 1.2, with
-- the KHR suffix omitted. The original type, enum and command names are
-- still available as aliases of the core functionality.
--
-- == New Enum Constants
--
-- - 'KHR_SPIRV_1_4_EXTENSION_NAME'
--
-- - 'KHR_SPIRV_1_4_SPEC_VERSION'
--
-- == Issues
--
-- 1. Should we have an extension specific to this SPIR-V version, or add a
-- version-generic query for SPIR-V version? SPIR-V 1.4 does not need any
-- other API changes.
--
-- __RESOLVED__: Just expose SPIR-V 1.4.
--
-- Most new SPIR-V versions introduce optionally-required capabilities or
-- have implementation-defined limits, and would need more API and
-- specification changes specific to that version to make them available in
-- Vulkan. For example, to support the subgroup capabilities added in
-- SPIR-V 1.3 required introducing
-- 'Vulkan.Core11.Originally_Based_On_VK_KHR_subgroup.PhysicalDeviceSubgroupProperties'
-- to allow querying the supported group operation categories, maximum
-- supported subgroup size, etc. While we could expose the parts of a new
-- SPIR-V version that do not need accompanying changes generically, we
-- will still end up writing extensions specific to each version for the
-- remaining parts. Thus the generic mechanism will not reduce future
-- spec-writing effort. In addition, making it clear which parts of a
-- future version are supported by the generic mechanism and which cannot
-- be used without specific support would be difficult to get right ahead
-- of time.
--
-- 2. Can different stages of the same pipeline use shaders with different
-- SPIR-V versions?
--
-- __RESOLVED__: Yes.
--
-- Mixing SPIR-V versions 1.0-1.3 in the same pipeline has not been
-- disallowed, so it would be inconsistent to disallow mixing 1.4 with
-- previous versions.. SPIR-V 1.4 does not introduce anything that should
-- cause new difficulties here.
--
-- 3. Must Vulkan extensions corresponding to SPIR-V extensions that were
-- promoted to core in 1.4 be enabled in order to use that functionality in
-- a SPIR-V 1.4 module?
--
-- __RESOLVED__: No, with caveats.
--
-- The SPIR-V 1.4 module does not need to declare the SPIR-V extensions,
-- since the functionality is now part of core, so there is no need to
-- enable the Vulkan extension that allows SPIR-V modules to declare the
-- SPIR-V extension. However, when the functionality that is now core in
-- SPIR-V 1.4 is optionally supported, the query for support is provided by
-- a Vulkan extension, and that query can only be used if the extension is
-- enabled.
--
-- This applies to any SPIR-V version; specifically for SPIR-V 1.4 this
-- only applies to the functionality from @SPV_KHR_float_controls@, which
-- was made available in Vulkan by @VK_KHR_shader_float_controls@. Even
-- though the extension was promoted in SPIR-V 1.4, the capabilities are
-- still optional in implementations that support @VK_KHR_spirv_1_4@.
--
-- A SPIR-V 1.4 module does not need to enable @SPV_KHR_float_controls@ in
-- order to use the capabilities, so if the application has /a priori/
-- knowledge that the implementation supports the capabilities, it does not
-- need to enable @VK_KHR_shader_float_controls@. However, if it does not
-- have this knowledge and has to query for support at runtime, it must
-- enable @VK_KHR_shader_float_controls@ in order to use
-- 'Vulkan.Extensions.VK_KHR_shader_float_controls.PhysicalDeviceFloatControlsPropertiesKHR'.
--
-- == Version History
--
-- - Revision 1, 2019-04-01 (Jesse Hall)
--
-- - Internal draft versions
--
-- == See Also
--
-- No cross-references are available
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_KHR_spirv_1_4 Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_KHR_spirv_1_4 ( KHR_SPIRV_1_4_SPEC_VERSION
, pattern KHR_SPIRV_1_4_SPEC_VERSION
, KHR_SPIRV_1_4_EXTENSION_NAME
, pattern KHR_SPIRV_1_4_EXTENSION_NAME
) where
import Data.String (IsString)
type KHR_SPIRV_1_4_SPEC_VERSION = 1
-- No documentation found for TopLevel "VK_KHR_SPIRV_1_4_SPEC_VERSION"
pattern KHR_SPIRV_1_4_SPEC_VERSION :: forall a . Integral a => a
pattern KHR_SPIRV_1_4_SPEC_VERSION = 1
type KHR_SPIRV_1_4_EXTENSION_NAME = "VK_KHR_spirv_1_4"
-- No documentation found for TopLevel "VK_KHR_SPIRV_1_4_EXTENSION_NAME"
pattern KHR_SPIRV_1_4_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern KHR_SPIRV_1_4_EXTENSION_NAME = "VK_KHR_spirv_1_4"
| expipiplus1/vulkan | src/Vulkan/Extensions/VK_KHR_spirv_1_4.hs | bsd-3-clause | 7,038 | 0 | 8 | 1,289 | 283 | 237 | 46 | -1 | -1 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.NV.VertexBufferUnifiedMemory
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.NV.VertexBufferUnifiedMemory (
-- * Extension Support
glGetNVVertexBufferUnifiedMemory,
gl_NV_vertex_buffer_unified_memory,
-- * Enums
pattern GL_COLOR_ARRAY_ADDRESS_NV,
pattern GL_COLOR_ARRAY_LENGTH_NV,
pattern GL_DRAW_INDIRECT_ADDRESS_NV,
pattern GL_DRAW_INDIRECT_LENGTH_NV,
pattern GL_DRAW_INDIRECT_UNIFIED_NV,
pattern GL_EDGE_FLAG_ARRAY_ADDRESS_NV,
pattern GL_EDGE_FLAG_ARRAY_LENGTH_NV,
pattern GL_ELEMENT_ARRAY_ADDRESS_NV,
pattern GL_ELEMENT_ARRAY_LENGTH_NV,
pattern GL_ELEMENT_ARRAY_UNIFIED_NV,
pattern GL_FOG_COORD_ARRAY_ADDRESS_NV,
pattern GL_FOG_COORD_ARRAY_LENGTH_NV,
pattern GL_INDEX_ARRAY_ADDRESS_NV,
pattern GL_INDEX_ARRAY_LENGTH_NV,
pattern GL_NORMAL_ARRAY_ADDRESS_NV,
pattern GL_NORMAL_ARRAY_LENGTH_NV,
pattern GL_SECONDARY_COLOR_ARRAY_ADDRESS_NV,
pattern GL_SECONDARY_COLOR_ARRAY_LENGTH_NV,
pattern GL_TEXTURE_COORD_ARRAY_ADDRESS_NV,
pattern GL_TEXTURE_COORD_ARRAY_LENGTH_NV,
pattern GL_VERTEX_ARRAY_ADDRESS_NV,
pattern GL_VERTEX_ARRAY_LENGTH_NV,
pattern GL_VERTEX_ATTRIB_ARRAY_ADDRESS_NV,
pattern GL_VERTEX_ATTRIB_ARRAY_LENGTH_NV,
pattern GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV,
-- * Functions
glBufferAddressRangeNV,
glColorFormatNV,
glEdgeFlagFormatNV,
glFogCoordFormatNV,
glGetIntegerui64i_vNV,
glIndexFormatNV,
glNormalFormatNV,
glSecondaryColorFormatNV,
glTexCoordFormatNV,
glVertexAttribFormatNV,
glVertexAttribIFormatNV,
glVertexFormatNV
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| haskell-opengl/OpenGLRaw | src/Graphics/GL/NV/VertexBufferUnifiedMemory.hs | bsd-3-clause | 1,993 | 0 | 5 | 230 | 210 | 137 | 73 | 44 | 0 |
{-# OPTIONS_HADDOCK hide #-}
-- |
-- Copyright : (c) 2011 Simon Meier
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Simon Meier <iridcode@gmail.com>
-- Stability : experimental
-- Portability : tested on GHC only
--
-- Testing the correctness of bounded encodings. See the file 'test/TestAll.hs'
-- for an example on how to use the functions provided here.
--
module Codec.Bounded.Encoding.Internal.Test (
EncodingFailure
, evalEncoding
, showEncoding
, testEncoding
, cmpEncoding
, cmpEncoding_
, cmpEncodingErr
) where
import Data.Maybe
import Foreign
import Numeric (showHex)
import Codec.Bounded.Encoding.Internal
import qualified Codec.Bounded.Encoding.Internal.Region as R
------------------------------------------------------------------------------
-- Testing Encodings
------------------------------------------------------------------------------
-- Representing failures
------------------------
-- | A failure of an 'Encoding'.
data EncodingFailure = EncodingFailure String EncodingResult EncodingResult
deriving( Eq )
type EncodingResult = ( [Word8] -- full list
, [[Word8]] -- split list
, [Ptr Word8] ) -- in-write pointers
instance Show EncodingFailure where
show (EncodingFailure cause res1 res2) = unlines $
[ ""
, "Encoding violated post-condition: " ++ cause ++ "!"
] ++
(map (" " ++) $ lines $ unlines
[ "String based result comparison:"
, showEncodingResult stringLine 1 res1
, showEncodingResult stringLine 2 res2
, "Hex based result comparison:"
, showEncodingResult hexLine 1 res1
, showEncodingResult hexLine 2 res2
] )
where
hexLine = concatMap (\x -> pad2 $ showHex x "")
pad2 [ ] = '0':'0':[]
pad2 [x] = '0':x :[]
pad2 xs = xs
stringLine = map (toEnum . fromIntegral)
showEncodingResult line i (full, splits, ptrs) =
unlines $ zipWith (++) names
$ map (quotes . line) (full : splits) ++ [ppPtrs]
where
names = [ show (i::Int) ++ " total result: "
, " front slack: "
, " write result: "
, " reserved space: "
, " back slack: "
, " pointers/diffs: "
]
quotes xs = "'" ++ xs ++ "'"
ppPtrs = show (head ptrs) ++ do
(p1,p2) <- zip ptrs (tail ptrs)
"|" ++ show (p2 `minusPtr` p1) ++ "|" ++ show p2
-- Execution a write and testing its invariants
-----------------------------------------------
-- | Execute an 'Encoding' and return the written list of bytes.
evalEncoding :: Encoding a -> a -> [Word8]
evalEncoding w x = case testEncoding w x of
Left err -> error $ "evalEncoding: " ++ show err
Right res -> res
-- | Execute an 'Encoding' and return the written list of bytes interpreted as
-- Unicode codepoints.
showEncoding :: Encoding a -> a -> [Char]
showEncoding w = map (toEnum . fromEnum) . evalEncoding w
-- | Execute an 'Encoding' twice and check that all post-conditions hold and the
-- written values are identical. In case of success, a list of the written
-- bytes is returned.
testEncoding :: Encoding a -> a -> Either EncodingFailure [Word8]
testEncoding = testEncodingWith (5, 11)
testEncodingWith :: (Int, Int) -> Encoding a -> a -> Either EncodingFailure [Word8]
testEncodingWith (slackF, slackB) w x = unsafePerformIO $ do
res1@(xs1, _, _) <- execEncoding (replicate (slackF + slackB + bound) 40)
res2 <- execEncoding (invert xs1)
return $ check res1 res2
where
bound = getBound w
invert = map complement
check res1@(xs1, [frontSlack1, written1, reserved1, backSlack1], ptrs1)
res2@(_ , [frontSlack2, written2, reserved2, backSlack2], ptrs2)
-- test properties of first write
| length frontSlack1 /= slackF = err "front slack length"
| length backSlack1 /= slackB = err "back slack length"
| length xs1 /= slackF + slackB + bound = err "total length"
| not (ascending ptrs1) = err "pointers 1"
-- test remaining properties of second write
| not (ascending ptrs2) = err "pointers 2"
-- compare encodings
| frontSlack1 /= invert frontSlack2 = err "front over-write"
| backSlack1 /= invert backSlack2 = err "back over-write"
| written1 /= written2 = err "different encodings"
| length reserved1 /= length reserved2 = err "different reserved lengths"
| any (\(a,b) -> a /= complement b) untouched = err "different reserved usage"
| otherwise = Right written1
where
(_, untouched) = break (uncurry (/=)) $ zip reserved1 reserved2
err info = Left (EncodingFailure info res1 res2)
ascending xs = all (uncurry (<=)) $ zip xs (tail xs)
check _ _ = error "impossible"
-- list-to-memory, run write, memory-to-list, report results
execEncoding ys0 = do
r@(buf, size) <- R.fromList ys0
withForeignPtr buf $ \sp -> do
let ep = sp `plusPtr` size
op = sp `plusPtr` slackF
opBound = op `plusPtr` bound
op' <- runEncoding w x op
ys1 <- R.toList r
touchForeignPtr buf
-- cut the written list into: front slack, written, reserved, back slack
case splitAt (op `minusPtr` sp) ys1 of
(frontSlack, ys2) -> case splitAt (op' `minusPtr` op) ys2 of
(written, ys3) -> case splitAt (opBound `minusPtr` op') ys3 of
(reserved, backSlack) -> return $
(ys1, [frontSlack, written, reserved, backSlack], [sp, op, op', opBound, ep])
-- | Compare an 'Encoding' against a reference implementation. @cmpEncoding f e x@
-- returns 'Nothing' iff the encoding @e@ and the function @f@ yield the same
-- result when applied to @x@.
cmpEncoding :: (a -> [Word8]) -> Encoding a -> a
-> Maybe (a, [Word8], Either EncodingFailure [Word8])
cmpEncoding f w x
| result == Right (f x) = Nothing
| otherwise = Just (x, f x, result)
where
result = testEncoding w x
-- | Like 'cmpEncoding', but return only whether the write yielded the same result
-- as the reference implementation.
cmpEncoding_ :: Show a => (a -> [Word8]) -> Encoding a -> a -> Bool
cmpEncoding_ f w = isNothing . cmpEncoding f w
-- | Like 'cmpEncoding', but return an error using @error . show@. This is a
-- convenient way to get a QuickCheck test to output debug information about
-- what went wrong.
cmpEncodingErr :: Show a => (a -> [Word8]) -> Encoding a -> a -> Bool
cmpEncodingErr f w = maybe True (error . show) . cmpEncoding f w
| meiersi/system-io-write | src/Codec/Bounded/Encoding/Internal/Test.hs | bsd-3-clause | 7,071 | 5 | 30 | 2,128 | 1,617 | 889 | 728 | 105 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.