lang
stringclasses 10
values | seed
stringlengths 5
2.12k
|
---|---|
haskell | {-# LANGUAGE RankNTypes, OverloadedStrings #-}
{-# LANGUAGE CPP #-}
module Test.Tasty.Silver.Advanced
( -- * Constructing golden tests
goldenTest1,
goldenTestIO,
goldenTestIO1, |
haskell | import qualified Tunebank.Model.AbcMetadataSubmission as NewTune (AbcMetadataSubmission(..))
import Tunebank.Model.Comment (CommentId(..), Comment(..))
import qualified Tunebank.Model.CommentSubmission as CommentMsg (Submission(..))
import Data.Abc.Validator (normaliseKeySignature, normaliseRhythm)
import Debug.Trace (traceM)
-- | This is just a simple newtype wrapper for our 'IORef'.
newtype DBConfig = DBConfig {
_getPool :: Pool Connection
}
-- | This is also a simple newtype wrapper for our DB Monad. This is very
-- similar to Persistent's 'SqlPersistT' type.
newtype PostgresT m a = PostgresT (ReaderT DBConfig m a) |
haskell | module Main where
mathTables :: [(Integer, Integer, Integer)]
mathTables = [(x,y,x*y) | x <- [1..12], y <- [1..12]]
|
haskell | clearHeistCache :: Heist b -> IO ()
clearHeistCache = clearCacheTagState . _heistCTS
-----------------------------
-- SnapletSplice functions --
-----------------------------
------------------------------------------------------------------------------ |
haskell |
import Data.Functor ((<&>))
import Data.Foldable (traverse_)
import qualified Paths_aoc as Paths
import Challenge
main :: IO ()
main = do
traverse_ (\(challenge, num) -> do
fileLines <- Paths.getDataFileName ("data/" ++ _dataFile challenge) >>= readFile <&> lines
putStrLn $ show num ++ ".1: " ++ (_part1 challenge $ fileLines)
putStrLn $ show num ++ ".2: " ++ (_part2 challenge $ fileLines)
) (zip challenges [1..])
|
haskell | PrettyPC(..),
ShowPC(..),
drawSubTrees,
drawAnnotations,
drawGroup,
shift,
terminalShift,
nonTerminalShift,
wrap,
indent, |
haskell | return (Just dstAddress)
getDstAddress (DstFile dstFile) addressesPath = do
maddress <- getAddress dstFile
case maddress of
Just address -> do
let dstAddress = fromJust maddress |
haskell | networkTest1 = testCase "Simple call" $ do
t <- tcpServer port
let server = serve t $ \ "mod" "f" [IntTerm a] -> return $ Success $ IntTerm (a+1)
withAsync server $ \_ -> do
delay
c <- tcpClient "localhost" port
result <- call c "mod" "f" [IntTerm 3]
result @?= Right (IntTerm 4)
|
haskell | ktokens = tokens where
tokens = spaces >> (end <|> more)
more = (:) <$> (numToken <|> wordToken) <*> tokens
end = eof >> return []
wordToken = do word <- many1 (noneOf " \t\r\n\f\v")
case word of "def" -> return KtDef
"extern" -> return KtExtern |
haskell |
type GenIdentPartEnabled p =
(GenIdentPartPrefix p ~ A Ident, GenIdentPartNum p ~ P Natural)
data EGenIdentPart p m a where
GetGenIdentPart :: GenIdentPartEnabled p => EGenIdentPart p m (Ident p)
makeSem ''EGenIdentPart
genIdentPart :: (GenIdentPartEnabled p, Member (EGenIdentPart p) r)
=> Sem r (Ident p)
genIdentPart = getGenIdentPart
|
haskell | deriving (Eq, Ord, Show)
addPlayers :: IO Players
addPlayers = addPlayers' PlayersInfo { _p1 = "", _p2 = "", _p3 = "", _p4 = "" }
addPlayers' :: PlayersInfo -> IO Players |
haskell | module Kadena.Types
( module X
) where
-- NB: This is really the Consensus Service's type module but as consensus is all encompassing, it's also the primary types file
-- NB: this is evil, please remove
import Kadena.Types.Base as X
import Kadena.Types.Comms as X
import Kadena.Types.Command as X
import Kadena.Types.Config as X
import Kadena.Types.ConfigChange as X
import Kadena.Types.Dispatch as X
import Kadena.Types.Event as X
import Kadena.Types.Evidence as X |
haskell | ZeroD == ZeroD = True
(SuccD a) == (SuccD b) = a == b
_ == _ = False;
equalDC :: D [] -> D [] -> Bool;
equalDC = (==);
foo :: D []
foo = SuccD [SuccD [ZeroD], ZeroD]
|
haskell | foldOrientation :: a -> a -> Orientation -> a
foldOrientation l _ Horizontal = l
foldOrientation _ r Vertical = r
-- | get the point before the given point, vertically or horizontally
beforeByOrientationP :: Orientation -> Point -> Point
beforeByOrientationP = foldOrientation leftOfP aboveP
-- | get the point after the given point, vertically or horizontally
afterByOrientationP :: Orientation -> Point -> Point |
haskell | module Domain.Model.Actor,
module Domain.Model.Character,
module Domain.Model.Country,
module Domain.Model.Work
)
where
import Domain.Model.Actor
import Domain.Model.Character
import Domain.Model.Country |
haskell | module Models.HomeContext.From
( fromPosts
) where
import qualified Hakyll
import qualified Models.PostContext.Main as PostContext
fromPosts :: [Hakyll.Item String] -> Hakyll.Tags -> Hakyll.Context String
fromPosts posts tags =
Hakyll.listField "posts" (PostContext.fromTags tags) (take 10 <$> Hakyll.recentFirst posts)
|
haskell | _ -> json noMatch
checkCycle3 :: MatchingRequestChecker
checkCycle3 _ MatchingRequest { cycle3Dataset = Just (Cycle3Dataset (NinoAttribute "goodvalue")) } = json match
checkCycle3 nextCheck request = nextCheck request
checkMatchingDataset :: MatchingRequestChecker |
haskell | class Monad m =>
MonadHandle h m
| m -> h
where
openFile :: FilePath -> IOMode -> m h
hPutStr :: h -> String -> m ()
hClose :: h -> m ()
hGetContents :: h -> m String
hPutStrLn :: h -> String -> m ()
hPutStrLn h s = hPutStr h s >> hPutStr h "\n" |
haskell |
import Graphics.Vty (Vty (nextEvent, update), mkVty, userConfig, text, shutdown, horizCat, Image, picForImage, defAttr, withForeColor, red)
-- TODO: This won't take care of background and cursor
-- We don't use the existing Monoid instance for Images
type View = [Image]
initConcur :: IO ()
initConcur = return ()
|
haskell |
import Statix.Regex as Re
data Path n l t = End n | Via (n, l, Maybe t) (Path n l t)
deriving (Eq)
type CriticalEdge n l = (n , Regex l)
{- A Graph monad interface -}
class (Monad m, Eq l, Ord n) => MonadGraph n l d m | m -> n l d where
newNode :: d -> m n |
haskell | import System.Environment (getArgs)
import Lib
main :: IO ()
main = head <$> getArgs >>= startApp
|
haskell | Run . flip Battery 50 $
concat
[ ["--template", onClick (const "~/scripts/powercontrol.sh menu") "\61457 <acstatus>"],
["--Low", "30"],
["--High", "80"],
["--low", danger],
["--normal", fg],
["--high", fg],
["--"],
["-o", "<left>%"], -- (<timeleft>)
["-O", "<left>% Charging"],
["-i", "<left>%"]
]
] |
haskell | -- the file's magic number is as follows:
--
-- 0x89 - high bit set, to check for 8 bit transmission errors and to avoid being treated as a text file
-- 3 bytes - identifies the particular file format. i.e. 'PNG' or 'JHC'
-- 0x0D 0x0A - DOS style line ending, to detect errors.
-- 0x1A - EOF marker, to avoid corrupting the screen when typed under dos/windows |
haskell | TestTree (insert (7 :: Int) (fromList [1 .. 6])) `shouldBe` TestTree (fromList [1 .. 7])
invariantBinatyTree (insert (8 :: Int) (fromList [1 .. 7])) `shouldBe` True
TestTree (insert (8 :: Int) (fromList [1 .. 7])) `shouldBe` TestTree (fromList [1 .. 8])
invariantBinatyTree (insert (9 :: Int) (fromList [1 .. 8])) `shouldBe` True
TestTree (insert (9 :: Int) (fromList [1 .. 8])) `shouldBe` TestTree (fromList [1 .. 9])
invariantBinatyTree (insert (1 :: Int) Leaf) `shouldBe` True
TestTree (insert (1 :: Int) Leaf) `shouldBe` TestTree (Node Leaf (1 NL.:| []) Leaf)
invariantBinatyTree (insert (1 :: Int) example2) `shouldBe` True
TestTree (insert (1 :: Int) example2) `shouldBe` TestTree example1 where
example1 = Node Leaf (1 NL.:| [1, 1, 1]) Leaf
example2 = Node Leaf (1 NL.:| [1, 1]) Leaf
testFromList :: SpecWith () |
haskell | <gh_stars>1-10
{-# LANGUAGE OverloadedStrings #-}
module GlobInString ( script ) where
import Prelude
import Shell
-- This test ensures that we escape string literals properly if they
-- have an embedded glob.
script :: ShellM ()
script = do
run $ command "echo" ["*"] |
haskell | {-# LANGUAGE MonoLocalBinds #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
-- | A module describing error paths
module Rhodium.Blamer.Path where
import Data.List
import Data.Maybe
import qualified Data.Map as M
import Rhodium.TypeGraphs.Graph
import Rhodium.TypeGraphs.GraphReset
import Rhodium.TypeGraphs.GraphProperties
import Rhodium.TypeGraphs.GraphUtils
import Rhodium.TypeGraphs.Touchables
import Rhodium.Solver.Rules
|
haskell | app = do
rate <- option auto $ long "rate" <> help "sampling rate" <> value 44100
buf <- option auto $ long "buffer" <> help "number of samples for the buffer" <> value 1024
device <- option auto $ long "device" <> help "device index" <> value (-1)
helper
pure $ withPortAudio $ do
(_, devs) <- getDevices
if device < 0
then forM_ (zip [0 :: Int ..] devs) $ \(i, dev) ->
putStrLn $ show i ++ ": " ++ deviceName dev
else do
let dev = devs !! device
phase <- newMVar 0 |
haskell |
rng :: RNG
rng = mkRNG rng_periph_base
rccenable rccdisable
L476.RNG_HASH
where
rccenable = modifyReg rcc_reg_ahb2enr $ setBit rcc_ahb2enr_rngen
rccdisable = modifyReg rcc_reg_ahb2enr $ clearBit rcc_ahb2enr_rngen |
haskell |
playMuFourPlayersWithUpdates ::
(MonadRandom m, Bind m)
=> Updates m NOfFour (Tuple4 Score)
-> Dependencies m NOfFour
-> EndCondition
-> m (Tuple4 Score)
playMuFourPlayersWithUpdates (Updates dealUpdate biddingResultUpdate trickWinnerUpdate scoresUpdate) (Dependencies getBid getViceTrump getChiefTrump getPartner getCard) endCondition =
playMuWithUpdate scoresUpdate getCardPositions stages endCondition OneOfFour |
haskell | bob = reexport2 `seq` usedFunction1
class MyClass1 a where myClass1 :: a
class MyClass2 a where myClass2 :: a
class MyClass3 a where myClass3 :: a
foo _ = (myClass2, classWithFunc)
[quasi| hello |]
coerced = coerce coerceValue :: Int
|
haskell | )
where
largestFactor :: Integer -> Integer
largestFactor n = maximum $ factor n
factor :: Integer -> [Integer]
factor 1 = []
factor n =
let divisors =
dropWhile ((/= 0) . mod n) [2 .. ceiling $ sqrt $ fromIntegral n]
in let prime = if null divisors then n else head divisors
in (prime :) $ factor $ div n prime
main :: IO () |
haskell |
typeDecl :: ClosTypingEnvironment ()
typeDecl = do
declare (undefined :: DiffCrap)
declare (undefined :: TRecord)
declare (undefined :: TFunctions) |
haskell | {-# LANGUAGE StandaloneKindSignatures #-}
{-# LANGUAGE PolyKinds, ExplicitForAll #-}
module SAKS_Fail009 where
import Data.Kind (Type)
type T :: forall j -> j -> Type
data T (k :: Type -> Type) (a :: k)
|
haskell | import T3449A
class Foo a where
f1 :: a
f2 :: a
instance Foo Char where
f1 = f2
f2 = aChar |
haskell |
module Main where
import Text.HTML.TagSoup hiding (parseTags, renderTags)
import Text.HTML.TagSoup.Fast.Utf8Only
import Text.HTML.TagSoup.Entity
import Text.HTML.TagSoup.Match
import Control.Monad
import Data.List |
haskell | import Day1 (expenseReport)
ans :: IO Int
ans = calc <$> expenseReport
calc :: [Int] -> Int |
haskell | where
import Q.Currency
-- | Canadian dollar
cad :: Currency
cad = Currency {
cName = "Canadian dollar"
, cCode = "CAD"
, cIsoCode = 124
, cFracsPerUnit = 100
} |
haskell | noCacheP :: Parser Option
noCacheP = lexeme $ string "--no-cache" $> Cache Nothing
cacheP :: Parser Option
cacheP = lexeme $ Cache . Just <$> (string "--cache" *> char '\n' *> decimal)
intervalP :: Parser Option
intervalP = lexeme $ Interval <$> (string "--interval" *> char '\n' *> decimal)
urlP :: Parser Text
urlP = lexeme url |
haskell |
-- | Creates a list of temperaments.
tempList :: [Temp] -> TempList
tempList xs = TempList $ tabList $ fmap unTemp xs
-- | Selects one of the temperaments by index.
fromTempList :: TempList -> Sig -> Temp
fromTempList (TempList tab) asig = Temp $ fromTabList tab asig
-- | Selects one of the temperaments by index. Works at the time of instrument initialization (remains constant).
fromTempListD :: TempList -> D -> Temp |
haskell | {-# htermination truncate :: Float -> Int #-}
|
haskell |
pushBit :: Bit -> State Register32 Bit
pushBit bit = do
register <- get
put $ BitsExt.apply0Bit bit $ BitsExt.shiftl1 register
return $ BitsExt.testLeftBit register |
haskell | module Modules.Modules.Modules.Modules.Modules.Modules.M140 () where
|
haskell | import qualified Database.Redis as Redis
import Network.Wai.Middleware.Static
import System.Environment (lookupEnv)
import Web.Scotty.Hastache (scottyH', setTemplatesDir)
import Web.Scotty.Trans (file, get, middleware)
import qualified Controllers.Urls as UrlsCtrl (loadRoutes)
|
haskell | :<|> GetAllTodos
todoHandlers :: ServerT API App
todoHandlers =
newTodo
:<|> completeTodo
:<|> updateTodo
:<|> deleteTodo
:<|> getTodo
:<|> getTodos
-- | API
type API = "todo" :> TodoAPI
|
haskell | <> P.progDesc "Generate a single-elimination tournament bracket from new-line separated contestant names provided in stdin."
<> P.header "pingpongmageddon")
optParser :: P.Parser CmdArgs
optParser = CmdArgs
<$> P.flag GraphViz JSON (P.long "json"
<> P.short 'j'
<> P.help "Output JSON format tournament instead of GraphViz")
<*> P.option P.auto (P.long "seed"
<> P.short 's'
<> P.value defaultSeed
<> P.metavar "INTEGER"
<> P.help "Specify a fixed random seed") |
haskell | module Reverse where
rvrs :: String -> String
rvrs x = concat [awesome, is, curry]
where awesome = drop 9 x
is = take 4 (drop 5 x)
curry = take 5 x
main :: IO ()
main = print $ rvrs "Curry is awesome"
|
haskell | import OCI.Pass.Manager
import Data.TypeDesc
-- === Definition === --
newtype UnresolvedConses = UnresolvedConses [Expr Cons]
newtype NegativeConses = NegativeConses [Expr Cons]
makeLenses ''UnresolvedConses |
haskell |
-- This function takes a list of values and returns the list of zscores
-- Order is maintained
allZScores :: (Floating a) => [a] -> [a]
allZScores [] = []
allZScores [a] = [a]
allZScores xs = map getZ xs
where getZ = zScore (mean xs) (standardDeviation xs)
-- This will take a Score, a Mean, and a Standard Deviation and return the |
haskell | afew :: Test
afew = testGroup "Mixed, AFew" [testCase "AFew: C1" c1
,testCase "AFew: C2" c2
,testCase "AFew: C3" c3
,testCase "AFew: C4" c4]
where c1 = C1 @?= fromChurch (\ c _ _ _ -> c)
c2 = C2 1 'a' @?= fromChurch (\ _ f _ _ -> f 1 'a')
c3 = C3 True True @?= fromChurch (\ _ _ f _ -> f True True)
c4 = C4 @?= fromChurch (\ _ _ _ c -> c)
|
haskell | posType <- string "fen" <|> string "startpos"
spaces
(FEN pos _ _) <- if posType == "fen"
then fenParser
else return $ FEN initialBoard 0 0
spaces
liftM CmdPosition $ option pos (string "moves" >> parserMoveList pos)
where
parserMoveList pos = do
mm <- optionMaybe (spaces >> moveParser pos)
case mm of
Just m -> parserMoveList $ makeMove m pos |
haskell | , reserved
, whiteSpace
, withinBraces
, withinBrackets
, withinParens )
import Text.Parsec
import Text.Parsec.String (Parser)
import qualified Data.Text as T
-- | Parse a ghost module definition. I.e. the main structure for a
-- ghost-lang module. |
haskell | serversFull :: Int -> [(ServerCfg, Maybe Int)] -> Bool
serversFull max = all (isStoppedOrFull . snd)
where isStoppedOrFull (Just cnt) = cnt >= max
isStoppedOrFull Nothing = True
firstDown :: [(ServerCfg, Maybe Int)] -> Maybe ServerCfg
firstDown = (fst <$>) . find (isNothing . snd)
needToStop :: Int -> [(ServerCfg, Maybe Int)] -> [ServerCfg]
needToStop max srvs = map fst $ case nonEmpty of
[] -> drop 1 empty
_ -> empty
where running = map (fmap fromJust) $ filter (isJust . snd) srvs
nonFull = filter ((< max) . snd) running
(nonEmpty, empty) = partition ((> 0) . snd) nonFull |
haskell |
{-|
Constructs a 'Clause' from a list of 'Literal's
-}
mkClauseFromLits :: [Literal] -> Clause
mkClauseFromLits =
foldl clauseAddLiteral emptyClause |
haskell | , " </div>"
, " <div align='center'>"
, " <div class='textareas'>"
, " <textarea id='tree1' rows='1'></textarea>"
, " <textarea id='code1' rows='1'></textarea>"
, " </div>"
, " </div>"
, " </div>"
, " <div id='col2' class='col'>"
, " <div align='center'>"
, " <input class='dna' type='text' value='FF' id='input2' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false'>"
, " </div>" |
haskell | go [] n = (one,n)
go (p : ps) n =
if n <= 1 then (one,n)
else (multiply f (primePower p r), m)
where
(r,s) = factorOut p n
(f,m) = go ps s
destSmooth :: [Natural] -> Natural -> Maybe Factor
destSmooth ps n =
if m == 1 then Just f else Nothing
where
(f,m) = trialDivision ps n |
haskell | TokPipe -> "|"
TokTick -> "`"
TokDot -> "."
TokComma -> ","
TokUnderscore -> "_"
TokBackslash -> "\\"
TokLowerName qual name -> printQual qual <> name
TokUpperName qual name -> printQual qual <> name
TokOperator qual sym -> printQual qual <> sym
TokSymbolName qual sym -> printQual qual <> "(" <> sym <> ")" |
haskell | -- Exercise#5
-- Quicksort of numbers.
-- What would be the effect of replacing <= by < in the original definition of qsort? Hint: consider the example qsort1 [2,2,3,1,1].
-- Exercise on page#13: 1.7.5 -- PIH, Second Edition.
-- <NAME> V V :: 01st Oct, 2016.
qsort1 :: Ord a => [a] -> [a]
qsort1 [] = [] |
haskell | module Barbies.Internal
( -- * Functor
Internal.gbmapDefault
, Generics.GFunctor(..)
, Internal.CanDeriveFunctorB
, Internal.CanDeriveFunctorT
-- * Traversable |
haskell | part1 :: (Gen, Gen) -> Int
part1 (a,b) = length $ filter (==0) $ take (40*10^6) $ zipWith bitcount ga gb
where
ga = generator $ a { _filter = 1 }
gb = generator $ b { _filter = 1}
part2 :: (Gen, Gen) -> Int
part2 (a,b) = length $ filter (==0) $ take ( 5*10^6) $ zipWith bitcount ga gb
where
ga = generator a
gb = generator b |
haskell | , diversifyN
-- ** Inverse Injection
, Reinterpret
-- , Reinterpreted
, reinterpret
, Reinterpret'
, reinterpret'
, ReinterpretL
-- , ReinterpretedL
, reinterpretL
, ReinterpretL'
, reinterpretL'
, ReinterpretN'
, reinterpretN'
|
haskell | , secureHandshake
, module Oscoin.P2P.Handshake.Simple
, module Oscoin.P2P.Handshake.Noise
, Types.Handshake
, Types.HandshakeRole(..)
, Types.HandshakeResult
, Types.hrPeerInfo
, Types.hrPreSend
, Types.hrPostRecv
, Types.HandshakeT |
haskell | {-# LANGUAGE TemplateHaskell #-}
-- | Static files.
module HL.Static where
import Yesod.Static
staticFiles "static/"
|
haskell |
module Y2020.AOC23 where
import AOC (Solution (PureSolution))
import Data.List (foldl') |
haskell |
Maintainer : <EMAIL>
-}
module Camfort.Input
(
-- * Classes
Default(..)
-- * Datatypes and Aliases
, ProgramFile |
haskell |
data Parappa f g a = DaWrappa (f a) (g a)
instance (Functor f, Functor g) => Functor (Parappa f g) where
fmap f (DaWrappa fa ga) = DaWrappa (fmap f fa) (fmap f ga)
data IgnoreOne f g a b = IgnoringSomething (f a) (g b)
instance Functor g => Functor (IgnoreOne f g a) where
fmap f (IgnoringSomething fa gb) = IgnoringSomething fa (fmap f gb)
data Notorious g o a t = Notorious (g o) (g a) (g t)
instance Functor g => Functor (Notorious g o a) where |
haskell | => IndexEntry
-> FilePath
-> HMGitT m ()
putLs _ fp = liftIO $ putStrLn fp
putLsDetail :: MonadIO m
=> IndexEntry
-> FilePath
-> HMGitT m ()
putLsDetail idx fp = liftIO |
haskell | mydrop _ [] = []
mydrop 0 xs = xs
mydrop n (x:xs) = mydrop (n-1) xs
-- mydrop 3 [1,2,3,4,5]
-- mydrop 2 [2,3,4,5]
-- mydrop 1 [3,4,5]
-- mydrop 0 [4,5]
-- [4,5]
myinit :: [a] -> [a] |
haskell | <gh_stars>10-100
-- Lucas numbers
-- http://www.codewars.com/kata/55a7de09273f6652b200002e/
module Codewars.Exercise.Lucas where
lucasnum :: Int -> Integer
lucasnum n = (if (n<0) then (-1)^n' else 1) * (fibS n' + 2 * fibS (n'-1))
where n' = abs n
fib = (map fibS [0 ..] !!)
fibS 0 = 0
fibS 1 = 1
fibS k | k > 0 = fib (k-2) + fib (k-1) |
haskell | module FluentTest
(
) where
data Fluent a = Fluent a
|
haskell | , 0xFB1E
, 0x8BF9
, 0x9BD8
, 0xABBB
, 0xBB9A
, 0x4A75 |
haskell | bin2dec' _ x = trace ( "the value is expected binary value composed of '0' or '1'. The written value is incorrect") undefined
hexNumP = hex2dec <$> (string "0x" *> many alphaNum) where
hex2dec nums = toDecimal hex2dec' nums
hex2dec' c x = case lookup (toUpper c) $ zip "0123456789ABCDEF" [0..] of
Just v -> v * 16^x |
haskell | newtype TMVar a = TMVar (TVar (Maybe a))
newTMVar :: a -> STM (TMVar a)
newTMVar a = do
t <- newTVar (Just a)
return $ TMVar t |
haskell | {-# LANGUAGE Safe #-}
module Data.UTC.Class.Epoch
( Epoch(..)
) where
-- | The instant in time also known as __the epoch__: 1970-01-01T00:00:00Z
class Epoch t where
epoch :: t
|
haskell | isNothing' = not . isJust'
mayybee :: b -> (a -> b) -> Maybe a -> b
mayybee x f y = fromMaybe x (f <$> y)
fromMaybe' :: a -> Maybe a -> a
fromMaybe' x Nothing = x
fromMaybe' _ (Just x') = x'
data BinaryTree a =
Leaf |
haskell | instance QqStyleOptionMenuItem ((QStyleOptionMenuItem t1)) where
qStyleOptionMenuItem (x1)
= withQStyleOptionMenuItemResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionMenuItem1 cobj_x1
foreign import ccall "qtc_QStyleOptionMenuItem1" qtc_QStyleOptionMenuItem1 :: Ptr (TQStyleOptionMenuItem t1) -> IO (Ptr (TQStyleOptionMenuItem ()))
|
haskell | , ft_Get_Sfnt_LangTag'
) where
import FreeType.Core.Base.Types
import FreeType.Core.Types.Types
import FreeType.Format.SFNT.Types
import Foreign.Ptr
|
haskell | let out = \s -> writer ((), s)
inp = return "42"
run = register (Money 0) inp out
result = lines (snd (runWriter run))
result `shouldBe` ["42.00"]
it "can add amounts, printing the total" $ do |
haskell | move' = foldl' move1'
origin' :: (Int, Int)
origin' = (3, 1)
positions' :: [[Direction]] -> [(Int, Int)]
positions' ds = scanl move' origin' ds
buttons' :: [[Direction]] -> [Char]
buttons' ds = map button' $ positions' ds
result2 =
do t <- input
-- t <- pure test :: IO Text
case parseOnly directionSet t of |
haskell | data Ctxt = Ctxt { _req :: FnRequest
, db :: Pool Connection
, library :: Library
, pushover :: Maybe (Push.APIToken, Push.UserKey)
, siteurl :: Text
}
instance RequestContext Ctxt where |
haskell | Lua.callFunc "table.pack" True (23 :: Lua.Integer) (Char8.pack "moin")
, "failing lua procedure call" =:
"foo" `shouldBeErrorMessageOf` do
Lua.openlibs
Lua.callFunc "error" (Char8.pack "foo") :: Lua ()
, "Error when Lua-to-Haskell result conversion fails" =:
"expected string, got 'false' (boolean)" `shouldBeErrorMessageOf` do
Lua.openlibs
Lua.callFunc "rawequal" (Char8.pack "a") () :: Lua String
]
-- The following test case will hang if there's a problem with garbage
-- collection. |
haskell |
import DB.Model.Convert.Value.Native (encode, decodeMaybe)
-- import LibPrelude.Types
import LibPrelude
import qualified Network.Google.Datastore as DS
import Data.Typeable
import Data.Text (Text)
import qualified Data.Scientific as Sci |
haskell |
{-# INLINE modify #-}
modify :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> (a -> a) -> Int -> m ()
modify = MG.modify
{-# INLINE unsafeRead #-}
unsafeRead :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> m a
unsafeRead = MG.unsafeRead
{-# INLINE unsafeWrite #-} |
haskell | import qualified Data.Set as Set
-- import Data.Time
-- import GHC.Exts
import System.Directory
import Network.POP3.SSLClient |
haskell |
-- | obtain pointer to the underlying data if applicable
array'data'ptr ::
forall m r.
(MonadPlus m) =>
f a ->
(Storable a => ForeignPtr a -> m r) ->
m r
data DeviceArray a = (Storable a, EdhXchg a, Typeable a) =>
DeviceArray
{ device'array'cap :: !Int,
device'array'ref :: !(ForeignPtr a) |
haskell | import GHC.TypeLits (Nat, natVal, KnownNat)
data Foo = Bar Nat
data SFoo = SBar Int
deriving (Show)
type family ExtractNat (a :: Foo) :: Nat where
ExtractNat (Bar x) = x
sing :: forall a. KnownNat (ExtractNat a) => Proxy a -> SFoo |
haskell | module Main where
import SmackMyBitch
main :: IO ()
main = sendMsg |
haskell | initVal = toReal $ Fraction num den
in valSimplified == initVal
-- | Tests addition of fractions
prop_addition :: Fraction -> Fraction -> Bool
prop_addition fracA fracB = let
eval1 = toReal (fracA + fracB)
eval2 = (toReal fracA) + (toReal fracB)
in abs(eval1 - eval2) < marginErr -- Can't test for equality due to floating point errors |
haskell | import Classifier
import Data.Set (Set)
import qualified Data.Set as Set
import System.IO.Unsafe (unsafePerformIO)
import qualified System.Random as R |
haskell | findAppointments :: Day -> (Appointment -> Bool) -> WD [Appointment]
findAppointments lastDay p = do
appts <- findFirstAppointments lastDay
if null appts
then return []
else do
let appts'
= filter
(allP [ (<= nextDayStartTime lastDay) . time, p ]) |
haskell | -- and one actual. These sets of alerts can either be pushed to us by
-- Prometheus, or we can poll for them from AlertManager. The mode of operation
-- can be specified on a per-source basis.
--
-- In the case of alerts being pushed to us, we use a PushSource to keep a
-- reference to some mutable state (the latest list of alerts) so that we have
-- something to compare against when we are asked to perform a comparison.
--
-- In the case of us having to pull alerts, we use a PullSource to store the
-- URL of the AlertManager from which to pull, and an optional token with which |
haskell | import Control.Monad.Fix (fix)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Trace
import Control.Monad.Trans.Control (MonadBaseControl)
import Data.IORef (modifyIORef', newIORef, readIORef)
-- | Runs a 'TraceT' action, returning any collected samples alongside its output. The samples are
-- sorted chronologically by completion time (e.g. the head is the first span to complete).
-- |
haskell | <gh_stars>0
-- See https://hspec.github.io/hspec-discover.html for details
{-# OPTIONS_GHC -F -pgmF hspec-discover #-} |
haskell | next res
evalMemoryMonad state (ModifyBitfield mut next) = do
modifyTVar' (torrentStateBitField state) (force . mut)
next
evalMemoryMonad state (ReadRequestablePieces next) = do
res <- readTVar (torrentStateRequestablePieces state)
next res
evalMemoryMonad state (ModifyRequestablePieces mut next) = do
modifyTVar' (torrentStateRequestablePieces state) (force . mut)
next
evalMemoryMonad state (RecordDownloaded s b next) = do |
haskell | ( OctrcArgs(..)
, getOctrcArgs
) where
import Data.List ( isSuffixOf )
import Data.Maybe ( fromMaybe )
import Data.Semigroup ( (<>) )
import Data.Typeable ( Typeable )
import Options.Applicative
import System.Directory ( createDirectoryIfMissing )
import Octrc.Common |
haskell |
perms treat ctrl = (less,total) where
total = binomial (length ctrl + length treat) (length treat)
less = length $ filter (<= sum treat)
$ sums (treat ++ ctrl) (length treat)
sums x n
| l < n || n < 0 = [] |
haskell | else take 1 cShownReducedExp ++ "." ++ drop 1 cShownReducedExp
| c == 0 = "0"
| otherwise = dropZerosFromRight $
if read cShownReducedExp > (-10 :: Integer)
then cShownReducedExp
else take 2 cShownReducedExp ++ "." ++ drop 2 cShownReducedExp
in c' ++ "e" ++ (if e >= 0 then "+" else "") ++ show e |
haskell | mcx_circ :: QbIn
-> Circ QbOut
mcx_circ = unpack template_mcx
mcx_reversible :: (QbIn,QbOut)
-> Circ (QbIn,QbOut)
mcx_reversible = classical_to_reversible mcx_circ
build_circuit
mcx_m :: (Bool,Bool,Bool,Bool,Bool,Bool,Bool,Bool,Bool) -> Bool
mcx_m (a0,a1, a2, a3, a4, a5, a6, a7, a8) =
a0 && a1 && a2 && a3 && a4 && a5 && a6 && a7 && a8
|
haskell | ---
data ListZipper a = LZ a [a] [a] -- LZ(a) = a * L(a)^2
left :: ListZipper a -> ListZipper a
left (LZ _ [] _) = error "already on the left end"
left (LZ a (x:l) r) = LZ x l (a:r) |
haskell | -- Copyright : (C) 2015-2016, <NAME>
-- License : None
-- Maintainer : <NAME> <<EMAIL>>
-- Stability : experimental
--
-- Types for the ParodyBot, including some very simple access to Spotify.
----------------------------------------------------------------------------
module SpotTypes where
|
haskell | -- just recursively go through the list of primes to compute the factors of n
primeFactors n = factor n primes
where factor n (p:ps)
| p*p > n = [n]
| n `mod` p == 0 = p : factor (n `div` p) (p:ps)
| otherwise = factor n ps
ans = last (primeFactors 600851475143) |
End of preview. Expand
in Dataset Viewer.
This dataset contains 10000 random snippets of 5-15 lines parsed from bigcode/starcoderdata
.
Specifically, I consider 10 languages: Haskell, Python, cpp, java, typescript, shell, csharp, rust, php, and swift. And, I collect 1000 documents for each language, and then extract 5-15 random lines from the document to create this dataset.
See MagiCoder and their seed collection process. In my usecase, I needed some inspiration documents for generating synthetic datasets.
- Downloads last month
- 57