code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Network.Google.Jobs
-- 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)
--
-- Cloud Talent Solution provides the capability to create, read, update,
-- and delete job postings, as well as search jobs based on keywords and
-- filters.
--
-- /See:/ <https://cloud.google.com/talent-solution/job-search/docs/ Cloud Talent Solution API Reference>
module Network.Google.Jobs
(
-- * Service Configuration
jobsService
-- * OAuth Scopes
, cloudPlatformScope
, jobsScope
-- * API Declaration
, JobsAPI
-- * Resources
-- ** jobs.projects.operations.get
, module Network.Google.Resource.Jobs.Projects.Operations.Get
-- ** jobs.projects.tenants.clientEvents.create
, module Network.Google.Resource.Jobs.Projects.Tenants.ClientEvents.Create
-- ** jobs.projects.tenants.companies.create
, module Network.Google.Resource.Jobs.Projects.Tenants.Companies.Create
-- ** jobs.projects.tenants.companies.delete
, module Network.Google.Resource.Jobs.Projects.Tenants.Companies.Delete
-- ** jobs.projects.tenants.companies.get
, module Network.Google.Resource.Jobs.Projects.Tenants.Companies.Get
-- ** jobs.projects.tenants.companies.list
, module Network.Google.Resource.Jobs.Projects.Tenants.Companies.List
-- ** jobs.projects.tenants.companies.patch
, module Network.Google.Resource.Jobs.Projects.Tenants.Companies.Patch
-- ** jobs.projects.tenants.completeQuery
, module Network.Google.Resource.Jobs.Projects.Tenants.CompleteQuery
-- ** jobs.projects.tenants.create
, module Network.Google.Resource.Jobs.Projects.Tenants.Create
-- ** jobs.projects.tenants.delete
, module Network.Google.Resource.Jobs.Projects.Tenants.Delete
-- ** jobs.projects.tenants.get
, module Network.Google.Resource.Jobs.Projects.Tenants.Get
-- ** jobs.projects.tenants.jobs.batchCreate
, module Network.Google.Resource.Jobs.Projects.Tenants.Jobs.BatchCreate
-- ** jobs.projects.tenants.jobs.batchDelete
, module Network.Google.Resource.Jobs.Projects.Tenants.Jobs.BatchDelete
-- ** jobs.projects.tenants.jobs.batchUpdate
, module Network.Google.Resource.Jobs.Projects.Tenants.Jobs.BatchUpdate
-- ** jobs.projects.tenants.jobs.create
, module Network.Google.Resource.Jobs.Projects.Tenants.Jobs.Create
-- ** jobs.projects.tenants.jobs.delete
, module Network.Google.Resource.Jobs.Projects.Tenants.Jobs.Delete
-- ** jobs.projects.tenants.jobs.get
, module Network.Google.Resource.Jobs.Projects.Tenants.Jobs.Get
-- ** jobs.projects.tenants.jobs.list
, module Network.Google.Resource.Jobs.Projects.Tenants.Jobs.List
-- ** jobs.projects.tenants.jobs.patch
, module Network.Google.Resource.Jobs.Projects.Tenants.Jobs.Patch
-- ** jobs.projects.tenants.jobs.search
, module Network.Google.Resource.Jobs.Projects.Tenants.Jobs.Search
-- ** jobs.projects.tenants.jobs.searchForAlert
, module Network.Google.Resource.Jobs.Projects.Tenants.Jobs.SearchForAlert
-- ** jobs.projects.tenants.list
, module Network.Google.Resource.Jobs.Projects.Tenants.List
-- ** jobs.projects.tenants.patch
, module Network.Google.Resource.Jobs.Projects.Tenants.Patch
-- * Types
-- ** LatLng
, LatLng
, latLng
, llLatitude
, llLongitude
-- ** MendelDebugInputNamespacedDebugInput
, MendelDebugInputNamespacedDebugInput
, mendelDebugInputNamespacedDebugInput
, mdindiAddtional
-- ** ApplicationInfo
, ApplicationInfo
, applicationInfo
, aiURIs
, aiEmails
, aiInstruction
-- ** MendelDebugInput
, MendelDebugInput
, mendelDebugInput
, mdiNamespacedDebugInput
-- ** MatchingJob
, MatchingJob
, matchingJob
, mjJobTitleSnippet
, mjJobSummary
, mjCommuteInfo
, mjSearchTextSnippet
, mjJob
-- ** CompensationFilterType
, CompensationFilterType (..)
-- ** Status
, Status
, status
, sDetails
, sCode
, sMessage
-- ** RequestMetadata
, RequestMetadata
, requestMetadata
, rmDomain
, rmAllowMissingIds
, rmUserId
, rmSessionId
, rmDeviceInfo
-- ** CommuteFilterCommuteMethod
, CommuteFilterCommuteMethod (..)
-- ** BatchCreateJobsResponse
, BatchCreateJobsResponse
, batchCreateJobsResponse
, bcjrJobResults
-- ** SearchJobsRequestDiversificationLevel
, SearchJobsRequestDiversificationLevel (..)
-- ** CompensationInfo
, CompensationInfo
, compensationInfo
, ciAnnualizedTotalCompensationRange
, ciEntries
, ciAnnualizedBaseCompensationRange
-- ** BatchUpdateJobsResponse
, BatchUpdateJobsResponse
, batchUpdateJobsResponse
, bujrJobResults
-- ** BatchDeleteJobsResponse
, BatchDeleteJobsResponse
, batchDeleteJobsResponse
, bdjrJobResults
-- ** HistogramQuery
, HistogramQuery
, histogramQuery
, hqHistogramQuery
-- ** CompletionResult
, CompletionResult
, completionResult
, crSuggestion
, crImageURI
, crType
-- ** Location
, Location
, location
, lLatLng
, lRadiusMiles
, lLocationType
, lPostalAddress
-- ** Operation
, Operation
, operation
, oDone
, oError
, oResponse
, oName
, oMetadata
-- ** Empty
, Empty
, empty
-- ** ClientEvent
, ClientEvent
, clientEvent
, ceRequestId
, ceJobEvent
, ceEventNotes
, ceCreateTime
, ceEventId
-- ** JobDegreeTypesItem
, JobDegreeTypesItem (..)
-- ** ProjectsTenantsJobsListJobView
, ProjectsTenantsJobsListJobView (..)
-- ** BatchUpdateJobsRequest
, BatchUpdateJobsRequest
, batchUpdateJobsRequest
, bujrUpdateMask
, bujrJobs
-- ** Money
, Money
, money
, mCurrencyCode
, mNanos
, mUnits
-- ** JobDerivedInfoJobCategoriesItem
, JobDerivedInfoJobCategoriesItem (..)
-- ** ListCompaniesResponse
, ListCompaniesResponse
, listCompaniesResponse
, lcrNextPageToken
, lcrCompanies
, lcrMetadata
-- ** CompensationEntryType
, CompensationEntryType (..)
-- ** NamespacedDebugInput
, NamespacedDebugInput
, namespacedDebugInput
, ndiDisableAutomaticEnrollmentSelection
, ndiDisableExpTags
, ndiDisableOrganicSelection
, ndiForcedFlags
, ndiConditionallyForcedExps
, ndiAbsolutelyForcedExpTags
, ndiAbsolutelyForcedExpNames
, ndiDisableManualEnrollmentSelection
, ndiDisableExps
, ndiAbsolutelyForcedExps
, ndiDisableExpNames
, ndiConditionallyForcedExpNames
, ndiConditionallyForcedExpTags
, ndiForcedRollouts
-- ** CommuteFilter
, CommuteFilter
, commuteFilter
, cfCommuteMethod
, cfAllowImpreciseAddresses
, cfTravelDuration
, cfStartCoordinates
, cfRoadTraffic
, cfDePartureTime
-- ** BatchDeleteJobsRequest
, BatchDeleteJobsRequest
, batchDeleteJobsRequest
, bdjrNames
-- ** JobQueryEmploymentTypesItem
, JobQueryEmploymentTypesItem (..)
-- ** JobCustomAttributes
, JobCustomAttributes
, jobCustomAttributes
, jcaAddtional
-- ** JobEvent
, JobEvent
, jobEvent
, jeJobs
, jeType
-- ** SearchJobsRequest
, SearchJobsRequest
, searchJobsRequest
, sjrRequestMetadata
, sjrJobView
, sjrMaxPageSize
, sjrOrderBy
, sjrOffSet
, sjrSearchMode
, sjrDiversificationLevel
, sjrHistogramQueries
, sjrJobQuery
, sjrEnableBroadening
, sjrPageToken
, sjrCustomRankingInfo
, sjrDisableKeywordMatch
-- ** HistogramQueryResultHistogram
, HistogramQueryResultHistogram
, histogramQueryResultHistogram
, hqrhAddtional
-- ** StatusDetailsItem
, StatusDetailsItem
, statusDetailsItem
, sdiAddtional
-- ** HistogramQueryResult
, HistogramQueryResult
, histogramQueryResult
, hqrHistogramQuery
, hqrHistogram
-- ** DeviceInfoDeviceType
, DeviceInfoDeviceType (..)
-- ** CompensationEntryUnit
, CompensationEntryUnit (..)
-- ** JobResult
, JobResult
, jobResult
, jrStatus
, jrJob
-- ** NamespacedDebugInputForcedFlags
, NamespacedDebugInputForcedFlags
, namespacedDebugInputForcedFlags
, ndiffAddtional
-- ** ResponseMetadata
, ResponseMetadata
, responseMetadata
, rmRequestId
-- ** CommuteInfo
, CommuteInfo
, commuteInfo
, ciTravelDuration
, ciJobLocation
-- ** JobJobLevel
, JobJobLevel (..)
-- ** JobVisibility
, JobVisibility (..)
-- ** JobEmploymentTypesItem
, JobEmploymentTypesItem (..)
-- ** CustomRankingInfoImportanceLevel
, CustomRankingInfoImportanceLevel (..)
-- ** JobDerivedInfo
, JobDerivedInfo
, jobDerivedInfo
, jdiJobCategories
, jdiLocations
-- ** BatchOperationMetadata
, BatchOperationMetadata
, batchOperationMetadata
, bomState
, bomUpdateTime
, bomEndTime
, bomSuccessCount
, bomFailureCount
, bomCreateTime
, bomStateDescription
, bomTotalCount
-- ** CompanyDerivedInfo
, CompanyDerivedInfo
, companyDerivedInfo
, cdiHeadquartersLocation
-- ** CompensationFilterUnitsItem
, CompensationFilterUnitsItem (..)
-- ** CompensationFilter
, CompensationFilter
, compensationFilter
, cfIncludeJobsWithUnspecifiedCompensationRange
, cfRange
, cfUnits
, cfType
-- ** Tenant
, Tenant
, tenant
, tName
, tExternalId
-- ** JobPostingRegion
, JobPostingRegion (..)
-- ** Company
, Company
, company
, cHiringAgency
, cCareerSiteURI
, cEeoText
, cSize
, cWebsiteURI
, cSuspended
, cKeywordSearchableJobCustomAttributes
, cImageURI
, cHeadquartersAddress
, cName
, cDisplayName
, cExternalId
, cDerivedInfo
-- ** CustomAttribute
, CustomAttribute
, customAttribute
, caLongValues
, caFilterable
, caKeywordSearchable
, caStringValues
-- ** Job
, Job
, job
, jDePartment
, jApplicationInfo
, jLanguageCode
, jCompensationInfo
, jResponsibilities
, jJobStartTime
, jPromotionValue
, jAddresses
, jJobBenefits
, jVisibility
, jJobLevel
, jPostingUpdateTime
, jCustomAttributes
, jPostingPublishTime
, jName
, jDegreeTypes
, jCompany
, jQualifications
, jCompanyDisplayName
, jIncentives
, jJobEndTime
, jPostingRegion
, jTitle
, jEmploymentTypes
, jDerivedInfo
, jProcessingOptions
, jPostingExpireTime
, jDescription
, jRequisitionId
, jPostingCreateTime
-- ** CompanySize
, CompanySize (..)
-- ** ProjectsTenantsCompleteQueryType
, ProjectsTenantsCompleteQueryType (..)
-- ** Xgafv
, Xgafv (..)
-- ** LocationFilter
, LocationFilter
, locationFilter
, lfLatLng
, lfDistanceInMiles
, lfRegionCode
, lfTelecommutePreference
, lfAddress
-- ** ListJobsResponse
, ListJobsResponse
, listJobsResponse
, ljrNextPageToken
, ljrJobs
, ljrMetadata
-- ** CommuteFilterRoadTraffic
, CommuteFilterRoadTraffic (..)
-- ** CompletionResultType
, CompletionResultType (..)
-- ** JobQuery
, JobQuery
, jobQuery
, jqLanguageCodes
, jqDisableSpellCheck
, jqCustomAttributeFilter
, jqCommuteFilter
, jqPublishTimeRange
, jqLocationFilters
, jqCompanyDisplayNames
, jqJobCategories
, jqCompanies
, jqCompensationFilter
, jqQuery
, jqQueryLanguageCode
, jqEmploymentTypes
, jqExcludedJobs
-- ** BatchCreateJobsRequest
, BatchCreateJobsRequest
, batchCreateJobsRequest
, bcjrJobs
-- ** ProjectsTenantsCompleteQueryScope
, ProjectsTenantsCompleteQueryScope (..)
-- ** SpellingCorrection
, SpellingCorrection
, spellingCorrection
, scCorrected
, scCorrectedText
, scCorrectedHTML
-- ** CompleteQueryResponse
, CompleteQueryResponse
, completeQueryResponse
, cqrMetadata
, cqrCompletionResults
-- ** TimeOfDay'
, TimeOfDay'
, timeOfDay
, todNanos
, todHours
, todMinutes
, todSeconds
-- ** LocationLocationType
, LocationLocationType (..)
-- ** CompensationEntry
, CompensationEntry
, compensationEntry
, ceAmount
, ceExpectedUnitsPerYear
, ceRange
, ceType
, ceDescription
, ceUnit
-- ** OperationMetadata
, OperationMetadata
, operationMetadata
, omAddtional
-- ** CompensationRange
, CompensationRange
, compensationRange
, crMaxCompensation
, crMinCompensation
-- ** JobEventType
, JobEventType (..)
-- ** CustomRankingInfo
, CustomRankingInfo
, customRankingInfo
, criImportanceLevel
, criRankingExpression
-- ** ProcessingOptions
, ProcessingOptions
, processingOptions
, poHTMLSanitization
, poDisableStreetAddressResolution
-- ** PostalAddress
, PostalAddress
, postalAddress
, paLanguageCode
, paSortingCode
, paRegionCode
, paSublocality
, paPostalCode
, paLocality
, paRecipients
, paAdministrativeArea
, paAddressLines
, paRevision
, paOrganization
-- ** BatchOperationMetadataState
, BatchOperationMetadataState (..)
-- ** DeviceInfo
, DeviceInfo
, deviceInfo
, diId
, diDeviceType
-- ** ListTenantsResponse
, ListTenantsResponse
, listTenantsResponse
, ltrTenants
, ltrNextPageToken
, ltrMetadata
-- ** OperationResponse
, OperationResponse
, operationResponse
, orAddtional
-- ** SearchJobsRequestSearchMode
, SearchJobsRequestSearchMode (..)
-- ** LocationFilterTelecommutePreference
, LocationFilterTelecommutePreference (..)
-- ** ProcessingOptionsHTMLSanitization
, ProcessingOptionsHTMLSanitization (..)
-- ** JobQueryJobCategoriesItem
, JobQueryJobCategoriesItem (..)
-- ** SearchJobsResponse
, SearchJobsResponse
, searchJobsResponse
, sjrNextPageToken
, sjrHistogramQueryResults
, sjrLocationFilters
, sjrMatchingJobs
, sjrTotalSize
, sjrMetadata
, sjrBroadenedQueryJobsCount
, sjrSpellCorrection
-- ** JobJobBenefitsItem
, JobJobBenefitsItem (..)
-- ** SearchJobsRequestJobView
, SearchJobsRequestJobView (..)
-- ** NamespacedDebugInputForcedRollouts
, NamespacedDebugInputForcedRollouts
, namespacedDebugInputForcedRollouts
, ndifrAddtional
-- ** TimestampRange
, TimestampRange
, timestampRange
, trStartTime
, trEndTime
) where
import Network.Google.Prelude
import Network.Google.Jobs.Types
import Network.Google.Resource.Jobs.Projects.Operations.Get
import Network.Google.Resource.Jobs.Projects.Tenants.ClientEvents.Create
import Network.Google.Resource.Jobs.Projects.Tenants.Companies.Create
import Network.Google.Resource.Jobs.Projects.Tenants.Companies.Delete
import Network.Google.Resource.Jobs.Projects.Tenants.Companies.Get
import Network.Google.Resource.Jobs.Projects.Tenants.Companies.List
import Network.Google.Resource.Jobs.Projects.Tenants.Companies.Patch
import Network.Google.Resource.Jobs.Projects.Tenants.CompleteQuery
import Network.Google.Resource.Jobs.Projects.Tenants.Create
import Network.Google.Resource.Jobs.Projects.Tenants.Delete
import Network.Google.Resource.Jobs.Projects.Tenants.Get
import Network.Google.Resource.Jobs.Projects.Tenants.Jobs.BatchCreate
import Network.Google.Resource.Jobs.Projects.Tenants.Jobs.BatchDelete
import Network.Google.Resource.Jobs.Projects.Tenants.Jobs.BatchUpdate
import Network.Google.Resource.Jobs.Projects.Tenants.Jobs.Create
import Network.Google.Resource.Jobs.Projects.Tenants.Jobs.Delete
import Network.Google.Resource.Jobs.Projects.Tenants.Jobs.Get
import Network.Google.Resource.Jobs.Projects.Tenants.Jobs.List
import Network.Google.Resource.Jobs.Projects.Tenants.Jobs.Patch
import Network.Google.Resource.Jobs.Projects.Tenants.Jobs.Search
import Network.Google.Resource.Jobs.Projects.Tenants.Jobs.SearchForAlert
import Network.Google.Resource.Jobs.Projects.Tenants.List
import Network.Google.Resource.Jobs.Projects.Tenants.Patch
{- $resources
TODO
-}
-- | Represents the entirety of the methods and resources available for the Cloud Talent Solution API service.
type JobsAPI =
ProjectsTenantsCompaniesListResource :<|>
ProjectsTenantsCompaniesPatchResource
:<|> ProjectsTenantsCompaniesGetResource
:<|> ProjectsTenantsCompaniesCreateResource
:<|> ProjectsTenantsCompaniesDeleteResource
:<|> ProjectsTenantsJobsListResource
:<|> ProjectsTenantsJobsPatchResource
:<|> ProjectsTenantsJobsGetResource
:<|> ProjectsTenantsJobsCreateResource
:<|> ProjectsTenantsJobsBatchUpdateResource
:<|> ProjectsTenantsJobsBatchDeleteResource
:<|> ProjectsTenantsJobsBatchCreateResource
:<|> ProjectsTenantsJobsSearchForAlertResource
:<|> ProjectsTenantsJobsSearchResource
:<|> ProjectsTenantsJobsDeleteResource
:<|> ProjectsTenantsClientEventsCreateResource
:<|> ProjectsTenantsListResource
:<|> ProjectsTenantsPatchResource
:<|> ProjectsTenantsGetResource
:<|> ProjectsTenantsCreateResource
:<|> ProjectsTenantsCompleteQueryResource
:<|> ProjectsTenantsDeleteResource
:<|> ProjectsOperationsGetResource
|
brendanhay/gogol
|
gogol-jobs/gen/Network/Google/Jobs.hs
|
mpl-2.0
| 18,014
| 0
| 26
| 3,913
| 2,067
| 1,500
| 567
| 470
| 0
|
{-# LANGUAGE OverloadedStrings #-}
module Controller.Login
( checkPassword
, loginAccount
, viewLogin
, postLogin
, loginHandler
, postLogout
, postLogoutHandler
, postUser
, userHandler
) where
import Control.Applicative ((<|>))
import Control.Monad (when, unless)
import Control.Monad.Trans.Class (lift)
import qualified Crypto.BCrypt as BCrypt
import qualified Data.ByteString as BS
import Data.Function (on)
import Data.Maybe (fromMaybe)
import qualified Network.Wai as Wai
import Network.HTTP.Types.Method (methodGet, methodPost)
import qualified Network.HTTP.Types.Method as HTM
import Ops
import Has
import qualified JSON
import Model.Id.Types
import Model.Party
import Model.Identity
import Model.Permission
import Model.Notification
import Model.Token
import HTTP.Cookie
import HTTP.Form.Deform
import HTTP.Path.Parser
import Action
import Controller.Paths
import Controller.Form
import Controller.Angular
import Controller.Notification
import View.Login
import {-# SOURCE #-} Controller.Root
import {-# SOURCE #-} Controller.Party
loginAccount :: API -> SiteAuth -> Bool -> Handler Response
loginAccount api auth su = do
(sess :: Session) <- createSession auth su
let Token (Id tok) ex = (accountToken . sessionAccountToken) sess
cook <- setSignedCookie "session" tok ex
case api of
JSON -> return $ okResponse [cook] $ JSON.recordEncoding $ identityJSON (Identified sess)
HTML -> peeks $ otherRouteResponse [cook] viewParty (HTML, TargetProfile)
loginHandler :: API -> HTM.Method -> [(BS.ByteString, BS.ByteString)] -> Action
loginHandler api method _
| method == methodGet && api == HTML = viewLoginAction
| method == methodPost = postLoginAction api
| otherwise = error "unhandled api/method combo" -- TODO: better error
viewLogin :: ActionRoute ()
viewLogin = action GET ("user" >/> "login") $ \() -> viewLoginAction
-- | The action for handling GET for user/login
viewLoginAction :: Action
viewLoginAction = withAuth $ do
angular
maybeIdentity
(peeks (blankForm . htmlLogin))
(const (peeks (otherRouteResponse [] viewParty (HTML, TargetProfile))))
checkPassword :: BS.ByteString -> SiteAuth -> Bool
checkPassword p = any (`BCrypt.validatePassword` p) . accountPasswd
postLogin :: ActionRoute API
postLogin = action POST (pathAPI </< "user" </< "login") postLoginAction
data LoginRequest = LoginRequest BS.ByteString BS.ByteString Bool
-- | The action for handling POST for user/login
postLoginAction :: API -> Action
postLoginAction = \api -> withoutAuth $ do
(Just auth, su) <- runForm ((api == HTML) `thenUse` htmlLogin) $ do
email <- "email" .:> emailTextForm
password <- "password" .:> deform
superuser <- "superuser" .:> deform
let _ = LoginRequest email password superuser
(auth :: Maybe SiteAuth) <- lift $ lookupSiteAuthByEmail True email
let p :: Maybe Party
p = view <$> auth
-- The site auth will contain a member value, indicating the
-- user's right to edit group 0 (databrary site). There is no
-- inheritance for this value, so this is essentially looking
-- at the member value for the direct authorization between the user and
-- group 0. See examples of typical superadmins like party 1, party 7 in 0.sql.
su = superuser && any ((PermissionADMIN ==) . accessMember) auth
attempts <- lift $ maybe (return 0) recentAccountLogins p
let pass = checkPassword password `any` auth
block = attempts > 4
lift $ auditAccountLogin pass (fromMaybe nobodyParty p) email
when block $ "email" .:> deformError "Too many login attempts. Try again later."
unless pass $ "password" .:> deformError "Incorrect email address or password. Both are case-sensitive, and institutional addresses are preferred."
return (auth, su)
loginAccount api auth su
postLogout :: ActionRoute API
postLogout = action POST (pathAPI </< "user" </< "logout") $ \api -> postLogoutHandler api []
postLogoutHandler :: API -> [(BS.ByteString, BS.ByteString)] -> Action -- TODO: guard against methods besides POST
postLogoutHandler = \api _ -> withAuth $ do
_ <- maybeIdentity (return False) removeSession
case api of
JSON -> return $ okResponse [cook] $ JSON.recordEncoding $ identityJSON NotLoggedIn
HTML -> peeks $ otherRouteResponse [cook] viewRoot HTML
where cook = clearCookie "session"
userJSONField :: BS.ByteString -> Maybe BS.ByteString -> Handler (Maybe JSON.Encoding)
userJSONField "notifications" _ = Just . JSON.toEncoding <$> countUserNotifications
userJSONField _ _ = return Nothing
userHandler :: API -> [(BS.ByteString, BS.ByteString)] -> Action
userHandler api _ =
withAuth $ do
method <- peeks Wai.requestMethod
if method == methodGet && api == JSON then viewUserAction
else if method == methodPost then postUserAction api
else error "unhandled api/method combo" -- TODO: better error
-- viewUser :: ActionRoute ()
-- viewUser = action GET (pathJSON </< "user") $ \() -> withAuth $ viewUserAction
viewUserAction :: Handler Response
viewUserAction = do
ident <- peek
let i = identityJSON ident
q <- JSON.jsonQuery userJSONField =<< peeks Wai.queryString
return $ okResponse [] (i `JSON.foldObjectIntoRec` q)
postUser :: ActionRoute API -- TODO: remove when
postUser = action POST (pathAPI </< "user") $ \api -> withAuth $ postUserAction api
data UpdateUserRequest = UpdateUserRequest () (Maybe BS.ByteString) (Maybe BS.ByteString)
postUserAction :: API -> Handler Response
postUserAction api = do
auth <- peek
let acct = siteAccount auth
auth' <- runForm ((api == HTML) `thenUse` htmlUserForm acct) $ do
csrfForm
-- TODO: pass old password into UpdateUserRequest
"auth" .:> (deformGuard "Incorrect password" . (`checkPassword` auth) =<< deform)
email <- "email" .:> deformNonEmpty emailTextForm
passwd <- "password" .:> deformNonEmpty (passwordForm acct)
let _ = UpdateUserRequest () email passwd
let acct' = acct
{ accountEmail = fromMaybe (accountEmail acct) email
, accountParty = (accountParty acct){ partyAccount = Just acct' }
}
return auth
{ siteAccount = acct'
, accountPasswd = passwd <|> accountPasswd auth
}
changeAccount auth'
when (on (/=) (accountEmail . siteAccount) auth' auth || on (/=) accountPasswd auth' auth) $
createNotification (blankNotification acct NoticeAccountChange) -- use old acct (email)
{ notificationParty = Just $ partyRow $ accountParty acct
, notificationDelivered = DeliveryAsync -- force immediate delivery
}
case api of
JSON -> return $ okResponse [] $ JSON.recordEncoding $ partyJSON $ accountParty $ siteAccount auth'
HTML -> peeks $ otherRouteResponse [] viewParty (api, TargetProfile)
|
databrary/databrary
|
src/Controller/Login.hs
|
agpl-3.0
| 6,828
| 0
| 20
| 1,305
| 1,882
| 982
| 900
| -1
| -1
|
module Ape.Transform.Specialize where
import qualified Ape.Expr as E
import Ape.Env
import Ape.Transform.Substitute
-- Specialization beta expands every lambda with the given value list
specialize :: E.Expr E.Info -> [E.Value E.Info] -> E.Expr E.Info
specialize (E.Let i v b) args = E.Let i v (specialize b args)
specialize (E.Complex (E.Atomic (E.Val val))) args = specializeLambda val args
specialize expr _ = expr
specializeLambda :: E.Value E.Info -> [E.Value E.Info] -> E.Expr E.Info
specializeLambda (E.Lambda _ v _ b) (arg:args) = specialize (substitute e b) args
where e = insertEnv emptyEnv v arg
specializeLambda val _ = E.Complex $ E.Atomic $ E.Val val
specializeApp :: Env (E.Value E.Info) -> E.CExpr E.Info -> E.Expr E.Info
specializeApp e (E.App _ (v:vs)) = specLambda
where
-- Get the lambda to specialize
lambda = case v of
E.Var _ n -> lookupEnv e n
l -> l
-- Generate a new specialized expression
specLambda = specializeLambda lambda vs
specializeApp _ c = E.Complex $ c
|
madmann91/Ape
|
src/Ape/Transform/Specialize.hs
|
lgpl-3.0
| 1,057
| 0
| 12
| 227
| 404
| 205
| 199
| 19
| 2
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
-- | Module for interfacing <http://radioreddit.com>
module Web.Radio.Reddit where
import Control.Monad (liftM)
import Data.Aeson
import Data.Conduit (($$+-))
import Data.Conduit.Attoparsec (sinkParser)
import qualified Data.HashMap.Strict as HM
import Data.Maybe (fromMaybe)
import GHC.Generics (Generic)
import Network.HTTP.Conduit
import qualified Web.Radio as Radio
data Reddit = Reddit
{ title :: String
, artist :: String
, preview_url :: String
, download_url :: Maybe String
} deriving (Show, Generic)
instance FromJSON Reddit
instance Radio.Radio Reddit where
data Param Reddit = Genre String
parsePlaylist (Object hm) = do
let songs = HM.lookup "songs" hm >>=
\(Object hm') -> HM.lookup "song" hm'
case fromJSON $ fromMaybe Null songs of
Success s -> s
Error err -> error $ "Parse playlist failed: " ++ show err
parsePlaylist _ = error "Unrecognized playlist format."
getPlaylist (Genre g) = do
let url = "http://radioreddit.com/api/" ++ g ++ "/status.json"
req <- parseUrl url
withManager $ \manager -> do
res <- http req manager
liftM Radio.parsePlaylist (responseBody res $$+- sinkParser json)
songUrl _ x = return $ fromMaybe (preview_url x) (download_url x)
songMeta x = Radio.SongMeta (artist x) "" (title x)
tagged _ = False
genres :: IO [String]
genres = return
[ "main", "electronic", "rock", "metal"
, "indie", "hiphop", "random", "talk" ]
pprGenres :: [String] -> IO ()
pprGenres [] = return ()
pprGenres gs = do
putStrLn $ foldr1 f (take 4 gs)
pprGenres $ drop 4 gs
where
f a b = a ++ concat (replicate (20 - length a) " ") ++ b
|
rnons/lord
|
Web/Radio/Reddit.hs
|
unlicense
| 1,960
| 0
| 15
| 539
| 590
| 308
| 282
| 49
| 1
|
module External.A227192 (a227192) where
import Helpers.ListHelpers (runLengths)
import Helpers.BaseRepresentation (toBase)
a227192 :: Integer -> Int
a227192 = sum . scanl1 (+) . runLengths . toBase 2
|
peterokagey/haskellOEIS
|
src/External/A227192.hs
|
apache-2.0
| 201
| 0
| 8
| 27
| 65
| 37
| 28
| 5
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Web.Views.Site where
import Model.CoreTypes
import Control.Monad
import Text.Blaze.XHtml5 ((!))
import qualified Data.Text as T
import qualified Text.Blaze.Bootstrap as H
import qualified Text.Blaze.XHtml5 as H
import qualified Text.Blaze.XHtml5.Attributes as A
data SiteView
= SiteView
{ sv_blogName :: T.Text
, sv_blogDesc :: T.Text
, sv_user :: Maybe User
}
siteView :: SiteView -> H.Html -> H.Html
siteView sv body =
H.html $
do H.head $
do H.title (H.toHtml $ sv_blogName sv)
H.meta ! A.charset "utf-8"
H.meta ! A.name "viewport" ! A.content "width=device-width, initial-scale=1"
H.link ! A.href "/css/bootstrap.min.css" ! A.rel "stylesheet"
H.link ! A.href "/css/blog.css" ! A.rel "stylesheet"
H.body $
do H.div ! A.class_ "blog-masthead" $
H.div ! A.class_ "container" $
H.nav ! A.class_ "blog-nav" $
do H.a ! A.class_ "blog-nav-item" ! A.href "/" $ "Home"
H.a ! A.class_ "blog-nav-item" ! A.href "/about" $ "About"
case sv_user sv of
Nothing ->
do H.a ! A.class_ "blog-nav-item" ! A.href "/login" $ "Login"
H.a ! A.class_ "blog-nav-item" ! A.href "/register" $ "Register"
Just user ->
do when (userIsAdmin user || userIsAuthor user) $
H.a ! A.class_ "blog-nav-item" ! A.href "/write" $ "Write"
when (userIsAdmin user) $
H.a ! A.class_ "blog-nav-item" ! A.href "/manage" $ "Manage"
H.a ! A.class_ "blog-nav-item" ! A.href "/logout" $ "Logout"
H.div ! A.class_ "container" $ body
H.div ! A.class_ "blog-footer" $
do H.p $
do H.span "Blog template built for "
H.a ! A.href "http://getbootstrap.com" $ "Bootstrap"
H.span " by "
H.a ! A.href "https://twitter.com/mdo" $ "@mdo"
H.p $
H.a ! A.href "#" $ "Back to top"
H.script ! A.href "https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" $ mempty
H.script ! A.href "/js/bootstrap.min.js" $ mempty
panelWithErrorView :: T.Text -> Maybe T.Text -> H.Html -> H.Html
panelWithErrorView title mError ct =
H.div ! A.class_ "panel panel-info" ! A.style "margin-top: 30px;" $
do H.div ! A.class_ "panel-heading" $
H.div ! A.class_ "panel-title" $ H.toHtml title
H.div ! A.class_ "panel-body" $
do case mError of
Just errMsg ->
H.alertBox H.BootAlertDanger (H.toHtml errMsg)
Nothing -> mempty
H.div ct
|
agrafix/funblog
|
src/Web/Views/Site.hs
|
apache-2.0
| 2,846
| 0
| 26
| 967
| 874
| 417
| 457
| 61
| 2
|
module Generators where
import qualified Data.List as L
import Lib
import Test.QuickCheck
replaceSlash :: [Char] -> [Char]
replaceSlash ('\\':'\"':xs) = '\"' : replaceSlash xs
replaceSlash ('\\':'\\':xs) = '\\' : replaceSlash xs
replaceSlash ('\\':'n':xs) = '\n' : replaceSlash xs
replaceSlash (x:xs) = x : replaceSlash xs
replaceSlash [] = []
trimQuotes :: [Char] -> [Char]
trimQuotes = reverse . (L.drop 1) . reverse . (L.drop 1)
escapedCharToChar :: [Char] -> Char
escapedCharToChar "\\\"" = '\"'
escapedCharToChar "\\\\" = '\\'
escapedCharToChar "\\n" = '\n'
escapedCharToChar _ = '\0'
genLetter :: Gen Char
genLetter = elements (['A'..'Z'] ++ ['a'..'z'])
genDigit :: Gen Char
genDigit = elements ['0'..'9']
genDigits :: Gen Word
genDigits = arbitrary
genIdentSymbol :: Gen Char
genIdentSymbol = elements ['-', '_']
genMixed :: Gen [Char]
genMixed = listOf1 $ oneof [ genDigit, genIdentSymbol, genLetter ]
genIdent :: Gen [Char]
genIdent = do
f <- genLetter
rest <- genMixed
pure $ f : rest
genBadIdent :: Gen [Char]
genBadIdent = do
f <- oneof [ genDigit, genIdentSymbol ]
rest <- genMixed
pure $ f : rest
-- | gen assignement stuff
genAssignment :: Gen Assignment
genAssignment =
oneof [ Assignment <$> (Ident <$> genIdent)
, pure NoAssignment
]
assignmentToString :: Assignment -> String
assignmentToString (Assignment (Ident str)) = str ++ " <- "
assignmentToString NoAssignment = ""
genStringSymbol :: Gen Char
genStringSymbol = elements [' ', '!', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', ']', '^', '_', '`', '{', '|', '}', '~']
genEscaped :: Gen [Char]
genEscaped = oneof [ pure "\\\\"
, pure "\\\""
, pure "\\n"
]
genEscapedString :: Gen [Char]
genEscapedString =
fmap mconcat $ listOf1 $ oneof [ listOf $ oneof [ genDigit, genLetter, genStringSymbol ]
, genEscaped
]
genString :: Gen [Char]
genString =
let
begQuoteAndStr = (++) <$> (pure "\"") <*> genEscapedString
lastChar = (:[]) <$> oneof [ genDigit, genLetter ]
withLastChar = (++) <$> begQuoteAndStr <*> lastChar
in
(++) <$> withLastChar <*> (pure "\"")
-- | String Concat generator stuff
genStringConcat :: Gen StringConcat
genStringConcat =
oneof [ genStrIdentConcat
, genStrConcat
, genStrIdent
, genStrString
]
where
genStrIdentConcat =
let
ident' = Ident <$> genIdent
strConcat = genStringConcat
in
StrIdentConcat <$> ident' <*> strConcat
genStrConcat =
let
str = genString
strConcat = genStringConcat
in
StrConcat <$> str <*> strConcat
genStrIdent = StrIdent <$> (Ident <$> genIdent)
genStrString = StrString <$> genString
stringConcatToString :: StringConcat -> String
stringConcatToString (StrIdentConcat (Ident ident') rest) = ident' ++ " ++ " ++ (stringConcatToString rest)
stringConcatToString (StrConcat str rest) = str ++ " ++ " ++ (stringConcatToString rest)
stringConcatToString (StrIdent (Ident ident')) = ident'
stringConcatToString (StrString str) = str
genStrConcatToParsed :: StringConcat -> StringConcat
genStrConcatToParsed (StrIdentConcat ident' rest) = StrIdentConcat ident' (genStrConcatToParsed rest)
genStrConcatToParsed (StrConcat str rest) = StrConcat (trimQuotes $ replaceSlash str) (genStrConcatToParsed rest)
genStrConcatToParsed strIdent@(StrIdent _) = strIdent
genStrConcatToParsed (StrString str) = StrString (trimQuotes $ replaceSlash str)
-- | declaration generator stuff
genDeclaration :: Gen Declaration
genDeclaration = do
Declaration <$> (Ident <$> genIdent) <*> genStringConcat
declarationToString :: Declaration -> String
declarationToString (Declaration (Ident i) strConcat) = i ++ " = " ++ (stringConcatToString strConcat) ++ ";"
genDeclarationToParsed :: Declaration -> Declaration
genDeclarationToParsed (Declaration i strConcat) = Declaration i $ genStrConcatToParsed strConcat
-- | httpGet generator stuff
genHttpGet :: Gen HttpGet
genHttpGet = HttpGet <$> genStringConcat
httpGetToString :: HttpGet -> String
httpGetToString (HttpGet strConcat) = "httpGet " ++ stringConcatToString strConcat
genHttpGetToParsed :: HttpGet -> HttpGet
genHttpGetToParsed (HttpGet strConcat) = HttpGet $ genStrConcatToParsed strConcat
-- | method generator stuff
genMethod :: Gen Method
genMethod =
oneof [ genMethodHttpGet
]
where
genMethodHttpGet = MethodHttpGet <$> genHttpGet
methodToString :: Method -> String
methodToString (MethodHttpGet httpGet') = httpGetToString httpGet'
genMethodToParsed :: Method -> Method
genMethodToParsed (MethodHttpGet httpGet') = MethodHttpGet $ genHttpGetToParsed httpGet'
-- | errorHandler generator stuff
genErrorHandler :: Gen ErrorHandler
genErrorHandler =
oneof [ genErrorHandlerLog
, genErrorHandlerEmail
]
where
genErrorHandlerLog = ErrorHandlerLog <$> genStringConcat
genErrorHandlerEmail = ErrorHandlerEmail <$> genStringConcat
errorHandlerToString :: ErrorHandler -> String
errorHandlerToString (ErrorHandlerLog strConcat) = "log " ++ stringConcatToString strConcat
errorHandlerToString (ErrorHandlerEmail strConcat) = "email " ++ stringConcatToString strConcat
genErrorHandlerToParsed :: ErrorHandler -> ErrorHandler
genErrorHandlerToParsed (ErrorHandlerLog strConcat) = ErrorHandlerLog $ genStrConcatToParsed strConcat
genErrorHandlerToParsed (ErrorHandlerEmail strConcat) = ErrorHandlerEmail $ genStrConcatToParsed strConcat
-- | handleError generator stuff
genHandleError :: Gen HandleError
genHandleError = HandleError <$> genDigits <*> genErrorHandler
genHandleErrors :: Gen [ HandleError ]
genHandleErrors = vectorOf 2 $ genHandleError
-- genHandleErrors = listOf1 $ genHandleError -- Takes a few seconds but works
handleErrorToString :: HandleError -> String
handleErrorToString (HandleError status errorHandler') = ": handleError " ++ show status ++ " " ++ errorHandlerToString errorHandler'
genHandleErrorToParsed :: HandleError -> HandleError
genHandleErrorToParsed (HandleError status errorHandler') = HandleError status $ genErrorHandlerToParsed errorHandler'
-- | action generator stuff
genAction :: Gen Action
genAction = Action <$> genAssignment <*> genMethod <*> genPossibleHandleErrors
where
genPossibleHandleErrors = oneof [ genHandleErrors
, (:[]) <$> genHandleError
, pure []
]
actionToString :: Action -> String
actionToString (Action{..}) = assignmentToString actionAssignment ++ methodToString actionMethod ++ (mconcat $ L.intersperse " " $ handleErrorToString <$> actionHandleError) ++ ";"
genActionToParsed :: Action -> Action
genActionToParsed (Action{..}) = Action actionAssignment (genMethodToParsed actionMethod) (genHandleErrorToParsed <$> actionHandleError)
-- | actions generator stuff
genActions :: Gen Actions
-- genActions = Actions <$> (listOf $ oneof [ IsAction <$> genAction -- Takes a few seconds but works
genActions = Actions <$> (vectorOf 2 $ oneof [ IsAction <$> genAction
, IsDeclaration <$> genDeclaration
]
)
actionsToString :: Actions -> String
actionsToString (Actions actionOrDeclarations) = mconcat $ L.intersperse "\n" $ actOrDecToString <$> actionOrDeclarations
where
actOrDecToString (IsAction action') = actionToString action'
actOrDecToString (IsDeclaration declaration') = declarationToString declaration'
genActionsToParsed :: Actions -> Actions
genActionsToParsed (Actions actionOrDeclarations) = Actions $ genActOrGenDecToParsed <$> actionOrDeclarations
where
genActOrGenDecToParsed (IsAction action') = IsAction $ genActionToParsed action'
genActOrGenDecToParsed (IsDeclaration declaration') = IsDeclaration $ genDeclarationToParsed declaration'
-- | WithCameraId generator stuff
genWithCameraId :: Gen WithCameraId
genWithCameraId = WithCameraId <$> (Ident <$> genIdent)
withCameraIdToString :: WithCameraId -> String
withCameraIdToString (WithCameraId (Ident i)) = "withCameraId " ++ i
-- | WithLiveUnitId generator stuff
genWithLiveUnitId :: Gen WithLiveUnitId
genWithLiveUnitId = WithLiveUnitId <$> (Ident <$> genIdent)
withLiveUnitIdToString :: WithLiveUnitId -> String
withLiveUnitIdToString (WithLiveUnitId (Ident i)) = "withLiveUnitId " ++ i
-- | InitFunc generator stuff
genInitFunc :: Gen InitFunc
genInitFunc = oneof [ InitWithCameraId <$> genWithCameraId
, InitWithLiveUnitId <$> genWithLiveUnitId
]
initFuncToString :: InitFunc -> String
initFuncToString (InitWithCameraId withCameraId') = withCameraIdToString withCameraId'
initFuncToString (InitWithLiveUnitId withLiveUnitId') = withLiveUnitIdToString withLiveUnitId'
-- | JsonValue generator stuff
genJsonValue :: Gen JsonValue
genJsonValue = JsonValue <$> genStringConcat
jsonValueToString :: JsonValue -> String
jsonValueToString (JsonValue stringConcat') = stringConcatToString stringConcat'
genJsonValueToParsed :: JsonValue -> JsonValue
genJsonValueToParsed (JsonValue strConcat) = JsonValue $ genStrConcatToParsed strConcat
-- | JsonParam generator stuff
genJsonParam :: Gen JsonParam
genJsonParam = JsonParam <$> genMixed <*> genJsonValue
jsonParamToString :: JsonParam -> String
jsonParamToString (JsonParam key value) = "\"" ++ key ++ "\" : " ++ (jsonValueToString value)
genJsonParamToParsed :: JsonParam -> JsonParam
genJsonParamToParsed (JsonParam key value) = (JsonParam key (genJsonValueToParsed value))
-- | JsonParamList generator stuff
genJsonParamList :: Gen JsonParamList
genJsonParamList = JsonParamList <$> vectorOf 2 genJsonParam
-- genJsonParamList = JsonParamList <$> listOf1 genJsonParam -- works but takes longer
jsonParamListToString :: JsonParamList -> String
jsonParamListToString (JsonParamList jPList) = mconcat $ L.intersperse ", " $ jsonParamToString <$> jPList
genJsonParamListToParsed :: JsonParamList -> JsonParamList
genJsonParamListToParsed (JsonParamList jPList) = JsonParamList $ genJsonParamToParsed <$> jPList
-- | JsonObject generator stuff
genJsonObject :: Gen JsonObject
genJsonObject = JsonObject <$> genJsonParamList
jsonObjectToString :: JsonObject -> String
jsonObjectToString (JsonObject jsonParamList') = "{ " ++ (jsonParamListToString jsonParamList') ++ " }"
genJsonObjectToParsed :: JsonObject -> JsonObject
genJsonObjectToParsed (JsonObject jsonParamList') = JsonObject $ genJsonParamListToParsed jsonParamList'
-- | response generator stuffs
genResponse :: Gen Response
genResponse = Response <$> genDigits <*> genJsonObject
responseToString :: Response -> String
responseToString (Response status jsonObject') = "responseJson " ++ (show status) ++ (jsonObjectToString jsonObject')
genResponseToParsed :: Response -> Response
genResponseToParsed (Response status jsonObject') = Response status (genJsonObjectToParsed jsonObject')
-- | system call generator stuffs
genSystemCall :: Gen SystemCall
genSystemCall = SystemCall <$> genInitFunc <*> genActions <*> genResponse <*> genHandleErrors
systemCallToString :: SystemCall -> String
systemCallToString (SystemCall initFunc' actions' response' handleErrors')
= (initFuncToString initFunc')
++ " { "
++ (actionsToString actions')
++ " } "
++ (responseToString response')
++ (mconcat $ L.intersperse " " $ handleErrorToString <$> handleErrors')
genSystemCallToParsed :: SystemCall -> SystemCall
genSystemCallToParsed (SystemCall initFunc' actions' response' handleErrors')
= SystemCall
initFunc'
(genActionsToParsed actions')
(genResponseToParsed response')
(genHandleErrorToParsed <$> handleErrors')
|
sbditto85/parsedsltest
|
test/Generators.hs
|
apache-2.0
| 11,940
| 0
| 12
| 2,171
| 2,899
| 1,519
| 1,380
| -1
| -1
|
module Handler.Root where
import Import
-- This is a handler function for the GET request method on the RootR
-- resource pattern. All of your resource patterns are defined in
-- config/routes
--
-- The majority of the code you will write in Yesod lives in these handler
-- functions. You can spread them across multiple files if you are so
-- inclined, or create a single monolithic file.
getRootR :: Handler RepHtml
getRootR = do
defaultLayout $ do
let spaces = [0..8] :: [Integer]
boardId <- lift newIdent
setTitle "~ How Civilized ~"
$(widgetFile "homepage")
|
MichaelBaker/haskell-tictactoe
|
Handler/Root.hs
|
bsd-2-clause
| 601
| 0
| 13
| 134
| 82
| 44
| 38
| 9
| 1
|
module Data.Propagator
( Cell
, Change(..)
, Propagated(..)
, PropagatedNum
, PropagatedFloating
, PropagatedInterval
, cell
, cellWith
, known
, write, content, with
, watch
, watch2
, lift1, lift2
, Prop(..)
, lower, arg
, lower1, lower2
, forwards
, backwards
) where
import Data.Propagator.Cell
import Data.Propagator.Class
import Data.Propagator.Num
import Data.Propagator.Prop
|
ekmett/propagators
|
src/Data/Propagator.hs
|
bsd-2-clause
| 422
| 0
| 5
| 92
| 113
| 76
| 37
| 23
| 0
|
import Data.Set
nb = (reverse . snd . (Prelude.foldl f (empty, [])))
where
f (s, acc) c =
if c `member` s
then (s, acc)
else (c `insert` s, c : acc)
main = do
str <- getLine
putStrLn $ nb str
|
pbl64k/HackerRank-Contests
|
2014-07-18-FP/RemoveDuplicates/rd.accepted.hs
|
bsd-2-clause
| 259
| 3
| 10
| 109
| 127
| 65
| 62
| 9
| 2
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import MyPrelude
import TstPrelude
import TstUtil
import RBPCP.Handler.Conf
import PaymentChannel.Test
import qualified RBPCP.Handler.Internal.Funding.Test as FundTest
import qualified PaymentChannel as PC
import qualified RBPCP.Types as RBPCP
import qualified Network.Haskoin.Transaction as HT
import qualified Network.Haskoin.Crypto as HC
import qualified Network.Haskoin.Constants as HCC
import qualified Network.Bitcoin.AddrIndex.API as Addr
import qualified Control.Monad.Logger as Log
import qualified Text.Show.Pretty as Pretty
import qualified Network.Bitcoin.AddrIndex.Types as AI
import qualified BitcoinSigner.App as SignApp
import qualified Util.Bitcoin.CoreFee as Fee
numMaxPayments :: Int
numMaxPayments = 100
numThreads :: Int
numThreads = 50
maxOpenPrice :: BtcAmount
maxOpenPrice = 50000
minOpenPrice :: BtcAmount
minOpenPrice = 10000
changeAddress :: HC.Address
changeAddress =
if HCC.getNetwork == HCC.prodnet
then "1JAtvgYXjKQq18rbDmFvhFC2nh7PZwQtJ"
else "mkkHB1Z3pCQQMiuXrZ82RsHectcB1ttK1k"
signConf :: SignApp.ServerConf
signConf = SignApp.ServerConf (Fee.BlockDelay 10) addrIndexServer
addrIndexServer :: AI.AddrIndexServerUrl
addrIndexServer =
AI.AddrIndexServerUrl
(BaseUrl Https "blockchain.runeks.me" 443 "")
(BaseUrl Https "blockchaintest.runeks.me" 443 "")
logLevel :: Log.LogLevel
logLevel = Log.LevelError
btcNetwork :: DisabledNet
btcNetwork = DisabledNet
testServerRootKey :: PC.RootPrv
testServerRootKey = PC.createRootPrv
"4b52502262a65ab2f7f42e4d12484aef2aa89c3c2d7f2f842be16aa41af8024e"
main :: IO ()
main = do
HCC.switchToTestnet3
hspec (specDerive >> spec)
specDerive :: Spec
specDerive =
describe "Mock funding tx" $
it "can be deterministically derived from any ChanParams" $ do
cp <- generate arbitrary
numReplicas <- generate $ choose (2,100)
resL <- replicateM numReplicas $ FundTest.deriveMockFunding cp
resL `shouldSatisfy` all (== head resL)
spec :: Spec
spec =
describe "Payment channel" $
around (withRbpcpServer btcNetwork logLevel (testServerRootKey,signConf) (minOpenPrice,maxOpenPrice)) $
it "can be funded, opened, paid to, closed" $ \serverArgs@(testConf, _, _) -> do
clientArgL <- replicateM numThreads (genClientArgs testConf)
numPayL <- doConcurrently (fundOpenPayClose serverArgs) clientArgL
putStrLn $ unwords [ "Done!", show $ sum (map length numPayL), "payments executed." ]
genClientArgs :: ServerConf chain -> IO (HC.PrvKeyC, HC.PubKeyC, LockTimeDate)
genClientArgs testConf = do
-- Generate client pubkey + channel expiration date
ArbitraryPubKeyC prvKey pubKey <- generate arbitrary
now <- liftIO currentTime
lockTime <- generate $ genLockTimeDate (scSettings testConf) now (24 * 7 * 52 :: Hour)
return (prvKey, pubKey, lockTime)
fundOpenPayClose :: BlockchainRun chainM chain
=> (ServerConf chain, BaseUrl, ReqMan)
-> (HC.PrvKeyC, HC.PubKeyC, LockTimeDate)
-> IO [BtcAmount]
fundOpenPayClose (testConf, servUrl, man) (prvKey, pubKey, lockTime) = do
-- GET FundingInfo + wait for funding
(fundInfo, chanParams) <- fetchServerFundingInfo runServReq lockTime pubKey
(fundingTx, addrFundInfo) <- waitBlockchainFunding man testConf chanParams fundInfo
let fundingVal = fromIntegral (Addr.asiValue addrFundInfo)
dustLimit = fromIntegral $ RBPCP.fundingInfoDustLimit fundInfo
openPrice = fromIntegral $ RBPCP.fundingInfoOpenPrice fundInfo
if fundingVal < openPrice + dustLimit
then do
putStrLn $ unwords [ "Insufficient funding value:", show fundingVal ++ "."
, "Open price:", show openPrice ++ "."
, "Dust limit:", show dustLimit ]
return []
else do
putStrLn $ "Channel funded. Value: " ++ show fundingVal
-- * Create client state + initial payment
let fundingVout = Addr.asiFundingVout addrFundInfo
sharedSecret = Just $ getSecret clientChan
(clientChan, initPay) = either (error . show) id $
channelWithInitialPayment prvKey lockTime (fundingTx,fundingVout) fundInfo
-- Util
let apiRun = rbpcpApi (RBPCP.BtcTxId $ HT.txHash fundingTx) fundingVout sharedSecret
-- * Open payment channel
PC.getFundingAmount clientChan `shouldBe` fundingVal
openChan runServReq apiRun fundInfo initPay
-- * Make payments
(finalState, payValL) <- makePayments runServReq apiRun fundInfo clientChan
-- * Close channel
closeChannel runServReq apiRun finalState
return payValL
where
runServReq :: String -> ClientM a -> IO a
runServReq = testRunReq (servUrl, man)
fetchServerFundingInfo
:: (String -> ClientM RBPCP.FundingInfo -> IO RBPCP.FundingInfo)
-> LockTimeDate
-> HC.PubKeyC
-> IO (RBPCP.FundingInfo, ChanParams)
fetchServerFundingInfo runServReq lockTime pubKey = do
fundInfo <- runServReq "FundingInfo" $ fundingInfo clientPK (toWord32 lockTime)
-- Log.runStdoutLoggingT . Log.logInfoN . cs $ unlines
-- [ "Received FundingInfo from server:" , Pretty.ppShow fundInfo ]
let cpE = validFundingInfo (MkSendPubKey pubKey) lockTime fundInfo
cpE `shouldSatisfy` isRight
return (fundInfo, either (error . show) id cpE)
where
clientPK = RBPCP.Client pubKey
waitBlockchainFunding
:: BlockchainRun chainM chain
=> ReqMan
-> ServerConf chain
-> ChanParams
-> RBPCP.FundingInfo
-> IO (HT.Tx, AI.AddressFundingInfo)
waitBlockchainFunding man testConf chanParams fundInfo = do
-- putStrLn $ unwords
-- [ "Please pay at least"
-- , show (fromIntegral $ RBPCP.fundingInfoOpenPrice fundInfo :: BtcAmount)
-- , "to funding address " ++ showJsonStr (PC.getFundingAddress chanParams)
-- ]
(fundingTx, addrFundInfo) <- loopFundingWait testConf man fundInfo chanParams
-- Elegant solution: parse possible server error response and wait a bit if it's "insufficienct conf count"
-- putStrLn "Waiting a bit to make sure server's blockchain-view is in sync with ours..."
-- threadDelay 10000000
return (fundingTx, addrFundInfo)
openChan runServReq apiRun fundInfo initPay = do
openPayRes <- runServReq "ChanOpen" $ apiRun ChanOpen initPay
RBPCP.paymentResultValueReceived openPayRes `shouldBe` RBPCP.fundingInfoOpenPrice fundInfo
makePayments runServReq apiRun fundInfo clientChan = do
numPayments <- generate $ choose (0, numMaxPayments)
payAmountLst <- generate . vectorOf numPayments $
choose (0 :: Word64 , ceiling $ 2*(availableValue `divRatio` numPayments))
foldM makePayment (clientChan,[]) (map fromIntegral payAmountLst :: [BtcAmount])
where
fundingVal = PC.getFundingAmount clientChan
availableValue = fundingVal - fromIntegral (RBPCP.fundingInfoOpenPrice fundInfo)
makePayment :: (ClientPayChan, [BtcAmount])
-> BtcAmount
-> IO (ClientPayChan, [BtcAmount])
makePayment (!state, !payLst) val = do
let (newState, payment, actualAmt) = createPaymentCapped state (Capped val)
payRes <- runServReq "ChanPay" $ apiRun ChanPay payment
RBPCP.paymentResultValueReceived payRes `shouldBe` fromIntegral actualAmt
-- putStrLn $ "Payment sent. Value: " ++ show actualAmt
return (newState, actualAmt : payLst)
closeChannel runServReq apiRun clientChan = do
-- putStrLn $ unwords [ "Closing channel; withdrawing to" , showJsonStr changeAddress ]
arbFee <- fromIntegral <$> generate (choose (0 :: Word64, fromIntegral $ channelValueLeft clientChan))
let (_, closingPayment, _) = createClosingPayment clientChan changeAddress (arbFee :: BtcAmount)
closeRes <- runServReq "ChanClose" $ apiRun ChanClose closingPayment
closeRes `shouldSatisfy` isJust . RBPCP.paymentResultSettlementTxid
|
runeksvendsen/rbpcp-handler
|
test/Spec.hs
|
bsd-3-clause
| 8,282
| 0
| 17
| 1,897
| 1,865
| 986
| 879
| -1
| -1
|
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : dave.laing.80@gmail.com
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TemplateHaskell #-}
module Fragment.Pair.Ast.Term (
TmFPair
, AsTmPair(..)
) where
import Data.Functor.Classes (showsUnaryWith, showsBinaryWith)
import Bound (Bound(..))
import Control.Lens.Iso (bimapping)
import Control.Lens.Prism (Prism')
import Control.Lens.Wrapped (_Wrapped, _Unwrapped)
import Control.Lens.TH (makePrisms)
import Data.Deriving (deriveEq1, deriveOrd1, deriveShow1)
import Ast.Term
import Data.Bitransversable
import Data.Functor.Rec
data TmFPair (k :: (* -> *) -> * -> *) (ty :: ((* -> *) -> * -> *) -> (* -> *) -> * -> *) (pt :: (* -> *) -> * -> *) f a =
TmPairF (f a) (f a)
| TmFstF (f a)
| TmSndF (f a)
deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
makePrisms ''TmFPair
deriveEq1 ''TmFPair
deriveOrd1 ''TmFPair
deriveShow1 ''TmFPair
instance EqRec (TmFPair ki ty pt) where
liftEqRec eR _ (TmPairF x1 y1) (TmPairF x2 y2) =
eR x1 x2 && eR y1 y2
liftEqRec eR _ (TmFstF x1) (TmFstF x2) =
eR x1 x2
liftEqRec eR _ (TmSndF x1) (TmSndF x2) =
eR x1 x2
liftEqRec _ _ _ _ =
False
instance OrdRec (TmFPair ki ty pt) where
liftCompareRec cR _ (TmPairF x1 y1) (TmPairF x2 y2) =
case cR x1 x2 of
EQ -> cR y1 y2
x -> x
liftCompareRec _ _ (TmPairF _ _) _ = LT
liftCompareRec _ _ _ (TmPairF _ _) = GT
liftCompareRec cR _ (TmFstF x1) (TmFstF x2) =
cR x1 x2
liftCompareRec _ _ (TmFstF _) _ = LT
liftCompareRec _ _ _ (TmFstF _) = GT
liftCompareRec cR _ (TmSndF x1) (TmSndF x2) =
cR x1 x2
instance ShowRec (TmFPair ki ty pt) where
liftShowsPrecRec sR _ _ _ n (TmPairF x y) =
showsBinaryWith sR sR "TmPairF" n x y
liftShowsPrecRec sR _ _ _ n (TmFstF x) =
showsUnaryWith sR "TmFstF" n x
liftShowsPrecRec sR _ _ _ n (TmSndF x) =
showsUnaryWith sR "TmSndF" n x
instance Bound (TmFPair ki ty pt) where
TmPairF x y >>>= f = TmPairF (x >>= f) (y >>= f)
TmFstF x >>>= f = TmFstF (x >>= f)
TmSndF x >>>= f = TmSndF (x >>= f)
instance Bitransversable (TmFPair ki ty pt) where
bitransverse fT fL (TmPairF x y) = TmPairF <$> fT fL x <*> fT fL y
bitransverse fT fL (TmFstF x) = TmFstF <$> fT fL x
bitransverse fT fL (TmSndF x) = TmSndF <$> fT fL x
class AsTmPair ki ty pt tm where
_TmPairP :: Prism' (tm ki ty pt f a) (TmFPair ki ty pt f a)
_TmPair :: Prism' (Term ki ty pt tm a) (Term ki ty pt tm a, Term ki ty pt tm a)
_TmPair = _Wrapped . _TmAstTerm . _TmPairP . _TmPairF . bimapping _Unwrapped _Unwrapped
_TmFst :: Prism' (Term ki ty pt tm a) (Term ki ty pt tm a)
_TmFst = _Wrapped . _TmAstTerm . _TmPairP . _TmFstF . _Unwrapped
_TmSnd :: Prism' (Term ki ty pt tm a) (Term ki ty pt tm a)
_TmSnd = _Wrapped . _TmAstTerm . _TmPairP . _TmSndF . _Unwrapped
instance AsTmPair ki ty pt TmFPair where
_TmPairP = id
instance {-# OVERLAPPABLE #-} AsTmPair ki ty pt (TmSum xs) => AsTmPair ki ty pt (TmSum (x ': xs)) where
_TmPairP = _TmNext . _TmPairP
instance {-# OVERLAPPING #-} AsTmPair ki ty pt (TmSum (TmFPair ': xs)) where
_TmPairP = _TmNow . _TmPairP
|
dalaing/type-systems
|
src/Fragment/Pair/Ast/Term.hs
|
bsd-3-clause
| 3,462
| 0
| 10
| 759
| 1,387
| 717
| 670
| 83
| 0
|
{-# LANGUAGE RankNTypes #-}
-- | Futhark Compiler Driver
module Main (main) where
import Data.Maybe
import Control.Category (id)
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.IO as T
import System.IO
import System.Exit
import System.Console.GetOpt
import Prelude hiding (id)
import Futhark.Pass
import Futhark.Actions
import Futhark.Compiler
import Futhark.Util.Options
import Futhark.Pipeline
import qualified Futhark.Representation.SOACS as SOACS
import Futhark.Representation.SOACS (SOACS)
import qualified Futhark.Representation.Kernels as Kernels
import Futhark.Representation.Kernels (Kernels)
import qualified Futhark.Representation.ExplicitMemory as ExplicitMemory
import Futhark.Representation.ExplicitMemory (ExplicitMemory)
import Futhark.Representation.AST (Prog, pretty)
import Futhark.TypeCheck (Checkable)
import qualified Futhark.Util.Pretty as PP
import Futhark.Optimise.InliningDeadFun
import Futhark.Optimise.CSE
import Futhark.Optimise.Fusion
import Futhark.Pass.FirstOrderTransform
import Futhark.Pass.Simplify
import Futhark.Optimise.InPlaceLowering
import Futhark.Optimise.DoubleBuffer
import Futhark.Optimise.TileLoops
import Futhark.Pass.KernelBabysitting
import Futhark.Pass.ExtractKernels
import Futhark.Pass.ExpandAllocations
import Futhark.Pass.ExplicitAllocations
import Futhark.Pass.CoalesceMemoryAccesses
import Futhark.Passes (standardPipeline)
data Config = Config { futharkConfig :: FutharkConfig
, futharkPipeline :: [UntypedPass]
, futharkAction :: UntypedAction
}
data UntypedPassState = SOACS SOACS.Prog
| Kernels Kernels.Prog
| ExplicitMemory ExplicitMemory.Prog
class Representation s where
-- | A human-readable description of the representation expected or
-- contained, usable for error messages.
representation :: s -> String
instance Representation UntypedPassState where
representation (SOACS _) = "SOACS"
representation (Kernels _) = "Kernels"
representation (ExplicitMemory _) = "ExplicitMemory"
instance PP.Pretty UntypedPassState where
ppr (SOACS prog) = PP.ppr prog
ppr (Kernels prog) = PP.ppr prog
ppr (ExplicitMemory prog) = PP.ppr prog
data UntypedPass = UntypedPass (UntypedPassState
-> PipelineConfig
-> FutharkM UntypedPassState)
data UntypedAction = SOACSAction (Action SOACS)
| KernelsAction (Action Kernels)
| ExplicitMemoryAction (Action ExplicitMemory)
| PolyAction (Action SOACS) (Action Kernels) (Action ExplicitMemory)
untypedActionName :: UntypedAction -> String
untypedActionName (SOACSAction a) = actionName a
untypedActionName (KernelsAction a) = actionName a
untypedActionName (ExplicitMemoryAction a) = actionName a
untypedActionName (PolyAction a _ _) = actionName a
instance Representation UntypedAction where
representation (SOACSAction _) = "SOACS"
representation (KernelsAction _) = "Kernels"
representation (ExplicitMemoryAction _) = "ExplicitMemory"
representation PolyAction{} = "<any>"
newConfig :: Config
newConfig = Config newFutharkConfig [] $ PolyAction printAction printAction printAction
changeFutharkConfig :: (FutharkConfig -> FutharkConfig)
-> Config -> Config
changeFutharkConfig f cfg = cfg { futharkConfig = f $ futharkConfig cfg }
type FutharkOption = FunOptDescr Config
passOption :: String -> UntypedPass -> String -> [String] -> FutharkOption
passOption desc pass short long =
Option short long
(NoArg $ Right $ \cfg ->
cfg { futharkPipeline = futharkPipeline cfg ++ [pass] })
desc
explicitMemoryProg :: String -> UntypedPassState -> FutharkM ExplicitMemory.Prog
explicitMemoryProg _ (ExplicitMemory prog) =
return prog
explicitMemoryProg name rep =
compileError (T.pack $
"Pass " ++ name ++
" expects ExplicitMemory representation, but got " ++ representation rep) $
pretty rep
soacsProg :: String -> UntypedPassState -> FutharkM SOACS.Prog
soacsProg _ (SOACS prog) =
return prog
soacsProg name rep =
compileError (T.pack $
"Pass " ++ name ++
" expects SOACS representation, but got " ++ representation rep) $
pretty rep
kernelsProg :: String -> UntypedPassState -> FutharkM Kernels.Prog
kernelsProg _ (Kernels prog) =
return prog
kernelsProg name rep =
compileError (T.pack $
"Pass " ++ name ++
" expects Kernels representation, but got " ++ representation rep) $
pretty rep
typedPassOption :: Checkable tolore =>
(String -> UntypedPassState -> FutharkM (Prog fromlore))
-> (Prog tolore -> UntypedPassState)
-> Pass fromlore tolore
-> String
-> FutharkOption
typedPassOption getProg putProg pass short =
passOption (passDescription pass) (UntypedPass perform) short long
where perform s config = do
prog <- getProg (passName pass) s
putProg <$> runPasses (onePass pass) config prog
long = [passLongOption pass]
soacsPassOption :: Pass SOACS SOACS -> String -> FutharkOption
soacsPassOption =
typedPassOption soacsProg SOACS
kernelsPassOption :: Pass Kernels Kernels -> String -> FutharkOption
kernelsPassOption =
typedPassOption kernelsProg Kernels
explicitMemoryPassOption :: Pass ExplicitMemory ExplicitMemory -> String -> FutharkOption
explicitMemoryPassOption =
typedPassOption explicitMemoryProg ExplicitMemory
simplifyOption :: String -> FutharkOption
simplifyOption short =
passOption (passDescription pass) (UntypedPass perform) short long
where perform (SOACS prog) config =
SOACS <$> runPasses (onePass simplifySOACS) config prog
perform (Kernels prog) config =
Kernels <$> runPasses (onePass simplifyKernels) config prog
perform (ExplicitMemory prog) config =
ExplicitMemory <$> runPasses (onePass simplifyExplicitMemory) config prog
long = [passLongOption pass]
pass = simplifySOACS
cseOption :: String -> FutharkOption
cseOption short =
passOption (passDescription pass) (UntypedPass perform) short long
where perform (SOACS prog) config =
SOACS <$> runPasses (onePass $ performCSE True) config prog
perform (Kernels prog) config =
Kernels <$> runPasses (onePass $ performCSE True) config prog
perform (ExplicitMemory prog) config =
ExplicitMemory <$> runPasses (onePass $ performCSE False) config prog
long = [passLongOption pass]
pass = performCSE True :: Pass SOACS SOACS
soacsPipelineOption :: String -> Pipeline SOACS SOACS -> String -> [String]
-> FutharkOption
soacsPipelineOption desc pipeline =
passOption desc $ UntypedPass pipelinePass
where pipelinePass (SOACS prog) config =
SOACS <$> runPasses pipeline config prog
pipelinePass rep _ =
compileErrorS (T.pack $ "Expected SOACS representation, but got " ++
representation rep) $
pretty rep
commandLineOptions :: [FutharkOption]
commandLineOptions =
[ Option "V" ["verbose"]
(OptArg (\file -> Right $ changeFutharkConfig $
\opts -> opts { futharkVerbose = Just file }) "FILE")
"Print verbose output on standard error; wrong program to FILE."
, Option [] ["compile-sequential"]
(NoArg $ Right $ \opts ->
opts { futharkAction = ExplicitMemoryAction seqCodeGenAction })
"Translate program into sequential C and write it on standard output."
, Option [] ["compile-imperative"]
(NoArg $ Right $ \opts ->
opts { futharkAction = ExplicitMemoryAction impCodeGenAction })
"Translate program into the imperative IL and write it on standard output."
, Option [] ["compile-imperative-kernels"]
(NoArg $ Right $ \opts ->
opts { futharkAction = ExplicitMemoryAction kernelImpCodeGenAction })
"Translate program into the imperative IL with kernels and write it on standard output."
, Option "i" ["interpret"]
(NoArg $ Right $ \opts -> opts { futharkAction = SOACSAction
interpretAction' })
"Run the program via an interpreter."
, Option [] ["range-analysis"]
(NoArg $ Right $ \opts -> opts { futharkAction = PolyAction rangeAction rangeAction rangeAction })
"Print the program with range annotations added."
, Option "p" ["print"]
(NoArg $ Right $ \opts -> opts { futharkAction = PolyAction printAction printAction printAction })
"Prettyprint the resulting internal representation on standard output (default action)."
, typedPassOption soacsProg Kernels firstOrderTransform "f"
, soacsPassOption fuseSOACs "o"
, soacsPassOption inlineAggressively []
, soacsPassOption removeDeadFunctions []
, kernelsPassOption inPlaceLowering []
, kernelsPassOption babysitKernels []
, kernelsPassOption tileLoops []
, typedPassOption soacsProg Kernels extractKernels []
, typedPassOption kernelsProg ExplicitMemory explicitAllocations "a"
, explicitMemoryPassOption doubleBuffer []
, explicitMemoryPassOption expandAllocations []
, explicitMemoryPassOption coalesceMemoryAccesses []
, cseOption []
, simplifyOption "e"
, soacsPipelineOption "Run the default optimised pipeline"
standardPipeline "s" ["standard"]
]
-- | Entry point. Non-interactive, except when reading interpreter
-- input from standard input.
main :: IO ()
main = mainWithOptions newConfig commandLineOptions compile
where compile [file] config =
Just $ do
res <- runFutharkM (m file config) $
isJust $ futharkVerbose $ futharkConfig config
case res of
Left err -> do
dumpError (futharkConfig config) err
exitWith $ ExitFailure 2
Right () -> return ()
compile _ _ =
Nothing
m file config = do
source <- liftIO $ T.readFile file
prog <- runPipelineOnSource (futharkConfig config) id file source
runPolyPasses config prog
runPolyPasses :: Config -> SOACS.Prog -> FutharkM ()
runPolyPasses config prog = do
prog' <- foldM (runPolyPass pipeline_config) (SOACS prog) (futharkPipeline config)
case (prog', futharkAction config) of
(SOACS soacs_prog, SOACSAction action) ->
actionProcedure action soacs_prog
(Kernels kernels_prog, KernelsAction action) ->
actionProcedure action kernels_prog
(ExplicitMemory mem_prog, ExplicitMemoryAction action) ->
actionProcedure action mem_prog
(SOACS soacs_prog, PolyAction soacs_action _ _) ->
actionProcedure soacs_action soacs_prog
(Kernels kernels_prog, PolyAction _ kernels_action _) ->
actionProcedure kernels_action kernels_prog
(ExplicitMemory mem_prog, PolyAction _ _ mem_action) ->
actionProcedure mem_action mem_prog
(_, action) ->
compileError (T.pack $ "Action " <>
untypedActionName action <>
" expects " ++ representation action ++ " representation, but got " ++
representation prog' ++ ".") $
pretty prog'
where pipeline_config =
PipelineConfig { pipelineVerbose = isJust $ futharkVerbose $ futharkConfig config
, pipelineValidate = True
}
runPolyPass :: PipelineConfig
-> UntypedPassState -> UntypedPass -> FutharkM UntypedPassState
runPolyPass pipeline_config s (UntypedPass f) =
f s pipeline_config
|
mrakgr/futhark
|
src/futhark.hs
|
bsd-3-clause
| 11,798
| 0
| 20
| 2,724
| 2,871
| 1,491
| 1,380
| 254
| 7
|
{-# Language BangPatterns #-}
module InternalCoordinates (
angle
,bond
,dihedral
,transform2Cart
) where
import Control.Applicative
import Control.Lens
import Data.List as DL
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
-- =======> Internal Modules <========
import CommonTypes
-- =================> <=======================
-- =============> <=================
type VD = VU.Vector Double
-- =============> <==================
vecdot :: VD -> VD -> Double
vecdot v1 v2 = VU.sum $ VU.zipWith (*) v1 v2
vecnorm :: VD -> Double
vecnorm v = sqrt $ vecdot v v
vecCross :: VD -> VD -> VD
vecCross !v1 !v2 = VU.fromList $ fmap permute [(1,2),(2,0),(0,1)]
where permute (i,j) = (v1 VU.! i)*(v2 VU.! j) - (v2 VU.! i)*(v1 VU.! j)
vecsub :: VD -> VD -> VD
vecsub !v1 !v2 = VU.zipWith (-) v1 v2
dif2 :: VD -> VD -> VD -> Double
dif2 !p1 !p2 !p3 = (p1 `vecsub` p2) `vecdot` (p3 `vecsub` p2)
-- =============> <============
bond :: VD -> VD -> Double
bond !p1 !p2 = vecnorm $ p1 `vecsub` p2
angle :: VD -> VD -> VD -> Double
angle !p1 !p2 !p3 = acos $ arg
where arg = (dif2 p1 p2 p3) / ((p1 `bond` p2) * (p2 `bond` p3))
dihedral :: VD -> VD -> VD -> VD -> Double
dihedral !p1 !p2 !p3 !p4 =
let [xba,xca,xcb,xdb] = DL.zipWith (vecsub) [p2,p3,p3,p4] [p1,p1,p2,p2]
[w1,w2] = DL.zipWith vecCross [xba,xcb] [xca,xdb]
[n1,n2] = fmap vecnorm [w1,w2]
teta = acos $ ((w1 `vecdot` w2) / (n1*n2))
in if (signum $ w2 `vecdot` xba) > 0.0 then teta else -teta
calcInternals :: Connections -> Molecule -> Internals
calcInternals conex mol = undefined{- V.map fun conex
where vss = chunks 3 $ mol ^. getCoord to R.toUnboxed
fun x = case x of
Bond a b -> bond
Angle a b c -> angle
Dihedral a b c d -> dihedral-}
chunks :: Int -> VD -> V.Vector VD
chunks n v = V.map (\x -> VU.backpermute v $ VU.generate n $ \y -> n*x +y ) ixs
where dim = (VU.lenght v) `div` n
ixs = V.generate dim id
transform2Cart :: Internals -> VD
transform2Cart = undefined
|
felipeZ/Dynamics
|
src/InternalCoodinates.hs
|
bsd-3-clause
| 2,361
| 0
| 13
| 768
| 833
| 461
| 372
| 44
| 2
|
-- TODO Download template files
module Installer (runInstaller ) where
import System.Directory
import System.IO
import Lib
import Network.Download
import Data.Either
url = "http://benkushigian.com/makeltx/"
fileListings = "files.out"
-- Naive Installer - no options
-- TODO Download appropriate files from benkushigian.com/makeltx
runInstaller = do
mldir <- getAppUserDataDirectory programName
-- If directory exists, output error message
mldirExists <- doesDirectoryExist mldir
if mldirExists then do
putStrLn "textools already installed, or leftover directory from a previous install."
putStrLn $ "To reinstall, please remove " ++ mldir
else do
let mlpkg = mldir ++ "/package-lists"
let mlrc = mldir ++ "/makeltx.rc"
let templates = mldir ++ "/templates"
let templ_xml = templates ++ "/templates.xml"
putStrLn "Installing MakeLTX..."
putStrLn "Creating directories..."
putStrLn mldir
createDirectoryIfMissing True mldir
putStrLn mlpkg
createDirectory mlpkg
-- Download from url
-- putStrLn "Downloading files..."
-- doc <- openURI $ url ++ fileListings
-- let toDownload = extractRelativePaths lefts[doc]
--extractRelativePaths stuff
-- | [] = []
-- | lines stuff
|
bkushigian/makeltx
|
src/Installer.hs
|
bsd-3-clause
| 1,312
| 0
| 13
| 301
| 196
| 98
| 98
| 25
| 2
|
-- | Module containing everything you need to define an 'Api' type. Import
-- this unqualified for easy 'Api' definitions.
--
-- Exports the instance of 'SingI' for all 'Typeable' types. This will
-- cause issues for @CustomStar@-style 'SingI' instances, but is nearly
-- required for Serv.
module Serv.Api.Prelude (
module Serv.Api
, module Network.HTTP.Kinder
, SingI (..)
) where
import Data.Singletons
import Data.Singletons.TypeRepTYPE ()
import Network.HTTP.Kinder
import Serv.Api
|
tel/serv
|
serv/src/Serv/Api/Prelude.hs
|
bsd-3-clause
| 539
| 0
| 5
| 120
| 60
| 42
| 18
| 8
| 0
|
{-# LANGUAGE BangPatterns, CPP, EmptyDataDecls, DeriveDataTypeable, OverloadedStrings #-}
-- | Take low-level 'Event'@s@ and turn them high-level data
-- structures.
module Bio.Sequence.Stockholm.Document
( -- * Data types
Stockholm(..)
, StockholmSeq(..)
, Ann(..)
, FileAnnotation(..)
, SequenceAnnotation(..)
, ColumnAnnotation(..)
, InFile
, InSeq
-- * Conduits
, parseDoc
, renderDoc
)
where
-- from base
import Control.Applicative ((<$>))
import Control.DeepSeq (NFData(..))
import Control.Monad (mplus)
import Data.Maybe (fromMaybe)
import Data.Typeable (Typeable)
-- from containers
import qualified Data.Map as M
-- from bytestring
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as L
-- from biocore
import Bio.Core.Sequence
-- from conduit
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
-- from this package
import Bio.Sequence.Stockholm.Stream
----------------------------------------------------------------------
-- Types
-- | An Stockholm 1.0 formatted file represented in memory.
data Stockholm = Stockholm [Ann FileAnnotation]
[Ann (ColumnAnnotation InFile)]
[StockholmSeq]
deriving (Show, Eq, Ord, Typeable)
instance NFData Stockholm where
rnf (Stockholm file clmn seqs) = rnf file `seq` rnf clmn `seq` rnf seqs
-- | A sequence in Stockholm 1.0 format.
data StockholmSeq = StSeq !SeqLabel
!SeqData
[Ann SequenceAnnotation]
[Ann (ColumnAnnotation InSeq)]
deriving (Eq, Ord, Typeable)
-- We don't derive Show to be able support biocore-0.1, which
-- doesn't have Show instances for SeqLabel and SeqData.
instance Show StockholmSeq where
showsPrec prec (StSeq (SeqLabel l) (SeqData d) sa ca) =
showParen (prec > 10) $
showString "StSeq (SeqLabel " .
showsPrec 11 l .
showString ") (SeqData " .
showsPrec 11 d .
(')':) . (' ':) .
showsPrec 11 sa .
(' ':) .
showsPrec 11 ca
instance NFData StockholmSeq where
rnf (StSeq _ _ sa ca) = rnf sa `seq` rnf ca
instance BioSeq StockholmSeq where
seqlabel (StSeq sl _ _ _) = sl
seqdata (StSeq _ sd _ _) = sd
seqlength (StSeq _ sd _ _) = Offset $ L.length (unSD sd)
-- | A generic annotation.
data Ann d = Ann { feature :: !d
, text :: !L.ByteString
}
deriving (Show, Eq, Ord, Typeable)
instance NFData (Ann d) where
-- already strict, default instance
-- | Possible file annotations.
data FileAnnotation =
AC -- ^ Accession number: Accession number in form PFxxxxx.version or PBxxxxxx.
| ID -- ^ Identification: One word name for family.
| DE -- ^ Definition: Short description of family.
| AU -- ^ Author: Authors of the entry.
| SE -- ^ Source of seed: The source suggesting the seed members belong to one family.
| GA -- ^ Gathering method: Search threshold to build the full alignment.
| TC -- ^ Trusted Cutoff: Lowest sequence score and domain score of match in the full alignment.
| NC -- ^ Noise Cutoff: Highest sequence score and domain score of match not in full alignment.
| TP -- ^ Type: Type of family (presently Family, Domain, Motif or Repeat).
| SQ -- ^ Sequence: Number of sequences in alignment.
| AM -- ^ Alignment Method: The order ls and fs hits are aligned to the model to build the full align.
| DC -- ^ Database Comment: Comment about database reference.
| DR -- ^ Database Reference: Reference to external database.
| RC -- ^ Reference Comment: Comment about literature reference.
| RN -- ^ Reference Number: Reference Number.
| RM -- ^ Reference Medline: Eight digit medline UI number.
| RT -- ^ Reference Title: Reference Title.
| RA -- ^ Reference Author: Reference Author
| RL -- ^ Reference Location: Journal location.
| PI -- ^ Previous identifier: Record of all previous ID lines.
| KW -- ^ Keywords: Keywords.
| CC -- ^ Comment: Comments.
| NE -- ^ Pfam accession: Indicates a nested domain.
| NL -- ^ Location: Location of nested domains - sequence ID, start and end of insert.
| F_Other !B.ByteString -- ^ Other file annotation.
deriving (Show, Eq, Ord, Typeable)
-- | Possible column annotations. Phantom type can be 'InFile'
-- or 'InSeq'.
data ColumnAnnotation a =
SS -- ^ Secondary structure.
| SA -- ^ Surface accessibility.
| TM -- ^ TransMembrane.
| PP -- ^ Posterior probability.
| LI -- ^ LIgand binding.
| AS -- ^ Active site.
| PAS -- ^ AS - Pfam predicted.
| SAS -- ^ AS - from SwissProt.
| IN -- ^ INtron (in or after).
| C_Other !B.ByteString -- ^ Other column annotation.
deriving (Show, Eq, Ord, Typeable)
-- | Phantom type for 'ColumnAnnotation's of the whole file.
data InFile
-- | Phantom type for 'ColumnAnnotation's of a single sequence.
data InSeq
-- | Possible sequence annotations.
data SequenceAnnotation =
S_AC -- ^ Accession number
| S_DE -- ^ Description
| S_DR -- ^ Database reference
| OS -- ^ Organism (species)
| OC -- ^ Organism classification (clade, etc.)
| LO -- ^ Look (Color, etc.)
| S_Other !B.ByteString -- ^ Other sequence annotation.
deriving (Show, Eq, Ord, Typeable)
----------------------------------------------------------------------
-- Parsing and showing features
-- | Parse a feature.
type ParseFeature a = B.ByteString -> a
-- | Show a feature.
type ShowFeature a = a -> B.ByteString
-- | Helper to create 'ParseFeature'@s@.
mkParseFeature :: (B.ByteString -> a -> B.ByteString)
-> [(B.ByteString, a)]
-> (B.ByteString -> a)
-> ParseFeature a
mkParseFeature modify anns mkOther =
let annots = M.fromList anns
in \feat -> let featMod = modify feat (error "mkParseFeature: never here")
in fromMaybe (mkOther feat) $ M.lookup featMod annots
-- | Helper to create 'ShowFeature'@s@.
mkShowFeature :: Ord a =>
(B.ByteString -> a -> B.ByteString)
-> [(B.ByteString, a)]
-> (a -> Maybe B.ByteString)
-> ShowFeature a
mkShowFeature modify anns fromOther =
let annots = M.fromList [(a,b) | (b,a) <- anns]
in \ann -> fromMaybe (error "mkShowFeature: never here 2") $
fromOther ann `mplus` (mod' <$> M.lookup ann annots)
where mod' = flip modify (error "mkShowFeature: never here 1")
-- | Parse and show sequence annotations.
parseSeqFeature :: ParseFeature SequenceAnnotation
showSeqFeature :: ShowFeature SequenceAnnotation
(parseSeqFeature, showSeqFeature) =
( mkParseFeature const seqFeatures S_Other
, mkShowFeature const seqFeatures f )
where
f (S_Other o) = Just o
f _ = Nothing
seqFeatures = [("LO",LO), ("OC",OC), ("OS",OS),
("AC",S_AC), ("DE",S_DE), ("DR",S_DR)]
-- | Parse and show file annotations.
parseFileFeature :: ParseFeature FileAnnotation
showFileFeature :: ShowFeature FileAnnotation
(parseFileFeature, showFileFeature) =
( mkParseFeature const fileFeatures F_Other
, mkShowFeature const fileFeatures f )
where
f (F_Other o) = Just o
f _ = Nothing
fileFeatures = [("AC",AC), ("AM",AM), ("AU",AU), ("CC",CC),
("DC",DC), ("DE",DE), ("DR",DR), ("GA",GA),
("ID",ID), ("KW",KW), ("NC",NC), ("NE",NE),
("NL",NL), ("PI",PI), ("RA",RA), ("RC",RC),
("RL",RL), ("RM",RM), ("RN",RN), ("RT",RT),
("SE",SE), ("SQ",SQ), ("TC",TC), ("TP",TP)]
-- | Parse and show column annotations.
parseClmnFeature :: ClmnFeatureLoc a => ParseFeature (ColumnAnnotation a)
parseClmnFeature = mkParseFeature removeSuffix clmnFeatures C_Other
where
removeSuffix feat phantom =
let suffix = clmnFeatureSuffix phantom
(f, s) = B.splitAt (B.length feat - B.length suffix) feat
in if suffix == s then f else ""
showClmnFeature :: ClmnFeatureLoc a => ShowFeature (ColumnAnnotation a)
showClmnFeature = mkShowFeature addSuffix clmnFeatures f
where
f (C_Other o) = Just o
f _ = Nothing
addSuffix feat phantom = feat `B.append` clmnFeatureSuffix phantom
clmnFeatures :: [(B.ByteString, ColumnAnnotation a)]
clmnFeatures = [("AS",AS), ("IN",IN), ("LI",LI), ("PAS",PAS), ("PP",PP),
("SA",SA), ("SAS",SAS), ("SS",SS), ("TM",TM)]
class ClmnFeatureLoc a where
clmnFeatureSuffix :: b a -> B.ByteString
instance ClmnFeatureLoc InSeq where
clmnFeatureSuffix _ = ""
instance ClmnFeatureLoc InFile where
clmnFeatureSuffix _ = "_cons"
----------------------------------------------------------------------
-- Specilized Maps.
type DiffMap a b = M.Map a [b]
insertDM :: Ord a => (a, b) -> DiffMap a b -> DiffMap a b
insertDM (key, val) = M.insertWith' (\_ old -> val:old) key [val]
finishDM :: (b -> L.ByteString) -> DiffMap a b -> M.Map a L.ByteString
finishDM f = fmap (L.concat . map f . reverse)
type AnnMap d = DiffMap d L.ByteString
insertAnn :: Ord d => Ann d -> AnnMap d -> AnnMap d
insertAnn (Ann key val) = insertDM (key, val)
finishAnn :: AnnMap d -> [Ann d]
finishAnn m = [Ann a b | (a, b) <- M.toList (finishDM id m)]
type SeqAnnMap d = M.Map B.ByteString (AnnMap d)
insertSM :: Ord d => B.ByteString -> Ann d -> SeqAnnMap d -> SeqAnnMap d
insertSM sq ann = M.alter (just . insertAnn ann . fromMaybe M.empty) sq
where
just !x = Just x
finishSM :: SeqAnnMap d -> M.Map B.ByteString [Ann d]
finishSM = fmap finishAnn
data PartialAnns =
PartialAnns { paFileAnns :: !(AnnMap FileAnnotation)
, paFileColAnns :: !(AnnMap (ColumnAnnotation InFile))
, paSeqAnns :: !(SeqAnnMap SequenceAnnotation)
, paSeqColAnns :: !(SeqAnnMap (ColumnAnnotation InSeq))
}
emptyPA :: PartialAnns
emptyPA = PartialAnns M.empty M.empty M.empty M.empty
insertPA_GF :: Ann (FileAnnotation ) -> PartialAnns -> PartialAnns
insertPA_GC :: Ann (ColumnAnnotation InFile) -> PartialAnns -> PartialAnns
insertPA_GS :: B.ByteString -> Ann (SequenceAnnotation ) -> PartialAnns -> PartialAnns
insertPA_GR :: B.ByteString -> Ann (ColumnAnnotation InSeq ) -> PartialAnns -> PartialAnns
insertPA_GF ann pa = pa { paFileAnns = insertAnn ann (paFileAnns pa) }
insertPA_GC ann pa = pa { paFileColAnns = insertAnn ann (paFileColAnns pa) }
insertPA_GS sq ann pa = pa { paSeqAnns = insertSM sq ann (paSeqAnns pa) }
insertPA_GR sq ann pa = pa { paSeqColAnns = insertSM sq ann (paSeqColAnns pa) }
----------------------------------------------------------------------
-- [Event <-> Document] conversion functions
-- | Conduit that parses 'Event'@s@ into documents 'Stockholm'.
parseDoc :: Monad m => C.Conduit Event m Stockholm
parseDoc = C.conduitState LookingForHeader push close
where
-- FIXME: Nice exceptions
close LookingForHeader = return []
close (InsideStockholm annots seqs) = return [makeStockholm annots seqs]
push state (EvComment _) =
return (C.StateProducing state [])
push LookingForHeader EvHeader =
continue (emptyPA, M.empty)
push LookingForHeader x =
fail $ "parseDoc: unexpected " ++ show x ++ " before header"
push (InsideStockholm _ _) EvHeader =
fail "parseDoc: unexpected header"
push (InsideStockholm annots seqs) EvEnd =
return (C.StateProducing LookingForHeader [makeStockholm annots seqs])
push (InsideStockholm annots seqs) (EvSeqData label data_) =
continue (annots, insertDM (label, data_) seqs)
push (InsideStockholm annots seqs) (EvGF feat data_) =
continue (insertPA_GF (Ann (parseFileFeature feat) data_) annots, seqs)
push (InsideStockholm annots seqs) (EvGC feat data_) =
continue (insertPA_GC (Ann (parseClmnFeature feat) data_) annots, seqs)
push (InsideStockholm annots seqs) (EvGS sq feat data_) =
continue (insertPA_GS sq (Ann (parseSeqFeature feat) data_) annots, seqs)
push (InsideStockholm annots seqs) (EvGR sq feat data_) =
continue (insertPA_GR sq (Ann (parseClmnFeature feat) data_) annots, seqs)
continue (annots, seqs) = return (C.StateProducing (InsideStockholm annots seqs) [])
{-# INLINE continue #-}
data ParseDoc = LookingForHeader
| InsideStockholm
{ pdAnnots :: {-# UNPACK #-} !PartialAnns
, pdSeqs :: !(DiffMap B.ByteString L.ByteString)
}
-- | Glue everything into place, as the Stockholm format lets
-- everything be everywhere and split in any number of parts.
makeStockholm :: PartialAnns -> DiffMap B.ByteString L.ByteString -> Stockholm
makeStockholm annots seqsDM =
let fileAnns_ = finishAnn (paFileAnns annots)
fileColAnns = finishAnn (paFileColAnns annots)
seqAnns_ = finishSM (paSeqAnns annots)
seqColAnns = finishSM (paSeqColAnns annots)
stseqs = [StSeq (SeqLabel $ l sq) (SeqData dt) (f sq seqAnns_) (f sq seqColAnns)
| (sq, dt) <- M.toList (finishDM id seqsDM)]
where
f = M.findWithDefault []
l = L.fromChunks . return
in Stockholm fileAnns_ fileColAnns stseqs
-- | Conduit that renders 'Stockholm'@s@ into 'Event'@s@.
renderDoc :: Monad m => C.Conduit Stockholm m Event
renderDoc = CL.concatMap toEvents
where
toEvents (Stockholm file clmn seqs) =
(EvHeader:) $
toEventsFileAnns file $
toEventsSeqs seqs $
toEventsFileClmn clmn $
[EvEnd]
toEventsFileAnns [] = id
toEventsFileAnns (a:as) =
(EvGF (showFileFeature $ feature a) (text a) :) .
toEventsFileAnns as
toEventsFileClmn [] = id
toEventsFileClmn (a:as) =
wrap (EvGC (showClmnFeature $ feature a)) (text a) .
toEventsFileClmn as
toEventsSeqs (StSeq (SeqLabel name) (SeqData seqd) sa ca : xs) =
wrap (EvSeqData name') seqd .
toEventsSeqAnns name' sa .
toEventsSeqClmn name' ca .
toEventsSeqs xs
where name' = B.concat $ L.toChunks name
toEventsSeqs [] = id
toEventsSeqAnns _ [] = id
toEventsSeqAnns n (a:as) =
(EvGS n (showSeqFeature $ feature a) (text a) :) .
toEventsSeqAnns n as
toEventsSeqClmn _ [] = id
toEventsSeqClmn n (a:as) =
wrap (EvGR n (showClmnFeature $ feature a)) (text a) .
toEventsSeqClmn n as
wrap :: (L.ByteString -> b) -> L.ByteString -> [b] -> [b]
wrap mk bs = case L.splitAt 70 bs of
(x, "") -> (mk x :)
(x, xs) -> (mk x :) . wrap mk xs
|
meteficha/biostockholm
|
src/Bio/Sequence/Stockholm/Document.hs
|
bsd-3-clause
| 15,182
| 0
| 17
| 4,070
| 4,088
| 2,225
| 1,863
| -1
| -1
|
import Test.Hspec
import Warships.BattleField
import qualified Data.Map.Strict as Map
-- •....
-- .□.□.
-- .■...
-- .□.■.
-- ...□.
testField :: BattleField
testField = BattleField 5 5 g2 s2
where
s2 = Map.fromList
[ (ShipID 1, 1)
, (ShipID 2, 1)
, (ShipID 3, 2)
]
g2 = Map.fromList
[ ((0,0), Miss)
, ((3,1), Ship Hidden (ShipID 1))
, ((3,3), Ship Injured (ShipID 2))
, ((3,4), Ship Hidden (ShipID 2))
, ((1,1), Ship Hidden (ShipID 3))
, ((1,2), Ship Injured (ShipID 3))
, ((1,3), Ship Hidden (ShipID 3))
]
main :: IO ()
main = hspec $
describe "attack" $ do
describe "on empty cell" $
it "marks it missed" $
let pos = (1, 0) in
getCell pos (attack pos testField) `shouldBe` Miss
describe "on miss cell" $
it "does nothing" $
let pos = (0, 0) in
getCell pos (attack pos testField) `shouldBe` Miss
describe "on an injured ships cell" $
it "does nothing" $
let pos = (3, 3) in
getCell pos (attack pos testField) `shouldBe` Ship Injured (ShipID 2)
describe "on a well feeling ships cell" $ do
it "marks it injured if ship has extra well feeling cells" $
let pos = (1, 1) in
getCell pos (attack pos testField) `shouldBe` Ship Injured (ShipID 3)
it "marks it killed if all ship cells are dead" $
let pos = (3, 4) in
getCell pos (attack pos testField) `shouldBe` Ship Killed (ShipID 2)
it "marks remaining injured cells dead" $
getCell (3, 3) (attack (3, 4) testField) `shouldBe` Ship Killed (ShipID 2)
it "marks adjust cells dead" $
getCell (4, 4) (attack (3, 4) testField) `shouldBe` Miss
describe "on a one cell ship" $ do
it "marks it dead" $
let pos = (3, 1) in
getCell pos (attack pos testField) `shouldBe` Ship Killed (ShipID 1)
it "marks adjust cells dead" $
getCell (2, 1) (attack (3, 1) testField) `shouldBe` Miss
|
triplepointfive/battleship
|
test/Spec.hs
|
bsd-3-clause
| 2,041
| 6
| 16
| 625
| 821
| 421
| 400
| 49
| 1
|
{-# LANGUAGE OverloadedStrings #-}
-- | MOO command parsing and execution
module MOO.Command (
-- * Data Structures
Command(..)
-- * Parsing Typed Commands
, parseWords
, parseCommand
-- * Executing MOO Code
, runCommand
) where
import Control.Applicative ((<$>))
import Control.Monad (void, foldM)
import Data.Char (isSpace, isDigit)
import Data.Monoid (Monoid(mempty, mappend, mconcat), First(First, getFirst))
import Data.Text (Text)
import Text.Parsec (parse, try, many, many1, char, anyChar, noneOf, spaces,
satisfy, between, eof, (<|>))
import Text.Parsec.Text (Parser)
import qualified Data.IntSet as IS
import qualified Data.Text as T
import {-# SOURCE #-} MOO.Connection
import MOO.Object
import {-# SOURCE #-} MOO.Task
import MOO.Types
import MOO.Verb
import qualified MOO.List as Lst
import qualified MOO.String as Str
commandWord :: Parser Text
commandWord = do
word <- many1 wordChar
spaces
return (T.concat word)
where wordChar = T.singleton <$> satisfy nonspecial <|>
T.pack <$> quotedChars <|>
T.singleton <$> backslashChar <|>
trailingBackslash
nonspecial '\"' = False
nonspecial '\\' = False
nonspecial c = not $ isSpace c
quotedChars = between (char '"') quoteEnd $
many (noneOf "\"\\" <|> backslashChar)
quoteEnd = void (char '"') <|> eof <|> void trailingBackslash
backslashChar = try (char '\\' >> anyChar)
trailingBackslash = try (char '\\' >> eof) >> return ""
commandWords :: Parser [Text]
commandWords = between spaces eof $ many commandWord
builtinCommand :: Parser Text
builtinCommand = say <|> emote <|> eval
where say = char '\"' >> return "say"
emote = char ':' >> return "emote"
eval = char ';' >> return "eval"
command :: Parser (Text, Text)
command = between spaces eof $ do
verb <- builtinCommand <|> commandWord <|> return ""
argstr <- T.pack <$> many anyChar
return (verb, argstr)
matchPrep :: [StrT] -> (StrT, (PrepSpec, StrT), StrT)
matchPrep = matchPrep' id prepPhrases
where matchPrep' dobj _ [] = (Str.unwords $ dobj [], (PrepNone, ""), "")
matchPrep' dobj ((spec,phrase):phrases) args
| phrase == argsPhrase =
(Str.unwords $ dobj [], (spec, Str.unwords argsPhrase),
Str.unwords iobj)
| otherwise = matchPrep' dobj phrases args
where (argsPhrase, iobj) = splitAt (length phrase) args
matchPrep' dobj [] (arg:args) =
matchPrep' (dobj . (arg :)) prepPhrases args
-- | A structure describing a player's parsed command
data Command = Command {
commandVerb :: StrT
, commandArgs :: [StrT]
, commandArgStr :: StrT
, commandDObjStr :: StrT
, commandPrepSpec :: PrepSpec
, commandPrepStr :: StrT
, commandIObjStr :: StrT
}
-- | Split a typed command into words according to the MOO rules for quoting
-- and escaping.
parseWords :: Text -> [StrT]
parseWords argstr = map Str.fromText args
where Right args = parse commandWords "" argstr
-- | Return a 'Command' value describing the arguments of a typed command as
-- parsed into verb, preposition, direct and indirect object, etc.
parseCommand :: Text -> Command
parseCommand cmd = Command {
commandVerb = Str.fromText verb
, commandArgs = args
, commandArgStr = Str.fromText argstr
, commandDObjStr = dobjstr
, commandPrepSpec = prepSpec
, commandPrepStr = prepstr
, commandIObjStr = iobjstr
}
where Right (verb, argstr) = parse command "" cmd
args = parseWords argstr
(dobjstr, (prepSpec, prepstr), iobjstr) = matchPrep args
objectNumber :: Parser ObjId
objectNumber = fmap read $ between (char '#') eof $ many1 (satisfy isDigit)
matchObject :: ObjId -> StrT -> MOO ObjId
matchObject player str
| Str.null str = return nothing
| otherwise = case parse objectNumber "" (Str.toText str) of
Right oid -> do
obj <- getObject oid
case obj of
Just _ -> return oid
Nothing -> matchObject' player str
Left _ -> matchObject' player str
where matchObject' :: ObjId -> StrT -> MOO ObjId
matchObject' player str = case str of
"me" -> return player
"here" -> maybe nothing (objectForMaybe . objectLocation) <$>
getObject player
_ -> do
maybePlayer <- getObject player
case maybePlayer of
Nothing -> return failedMatch
Just player' -> do
let holding = objectContents player'
maybeRoom = objectLocation player'
roomContents <-
maybe (return IS.empty)
(fmap (maybe IS.empty objectContents) . getObject)
maybeRoom
matchName str $ IS.toList (holding `IS.union` roomContents)
matchName :: StrT -> [ObjId] -> MOO ObjId
matchName str = fmap (uncurry matchResult) .
foldM (matchName' str) ([], [])
matchName' :: StrT -> ([ObjId], [ObjId]) -> ObjId ->
MOO ([ObjId], [ObjId])
matchName' str matches@(exact, prefix) oid = do
maybeAliases <- readProperty oid "aliases"
maybeObj <- getObject oid
let aliases = case maybeAliases of
Just (Lst v) -> Lst.toList v
_ -> []
names = maybe id ((:) . Str . objectName) maybeObj aliases
return $ case searchNames str names of
ExactMatch -> (oid : exact, prefix)
PrefixMatch -> (exact, oid : prefix)
NoMatch -> matches
matchResult :: [ObjId] -> [ObjId] -> ObjId
matchResult [oid] _ = oid
matchResult [] [oid] = oid
matchResult [] [] = failedMatch
matchResult _ _ = ambiguousMatch
searchNames :: StrT -> [Value] -> Match
searchNames str = mconcat . map (nameMatch str)
nameMatch :: StrT -> Value -> Match
nameMatch str (Str name)
| str == name = ExactMatch
| str `Str.isPrefixOf` name = PrefixMatch
nameMatch _ _ = NoMatch
data Match = NoMatch | PrefixMatch | ExactMatch
instance Monoid Match where
mempty = NoMatch
NoMatch `mappend` match = match
_ `mappend` ExactMatch = ExactMatch
match `mappend` _ = match
-- | Execute a typed command by locating and calling an appropriate MOO verb
-- for the current player, matching @dobj@ and @iobj@ objects against the
-- strings in the typed command.
runCommand :: Command -> MOO Value
runCommand Command { commandVerb = "" } = return zero
runCommand command = do
player <- getPlayer
dobj <- matchObject player (commandDObjStr command)
iobj <- matchObject player (commandIObjStr command)
room <- objectForMaybe . (objectLocation =<<) <$> getObject player
maybeVerb <- getFirst . mconcat . map First <$>
mapM (locateVerb dobj iobj) [player, room, dobj, iobj]
case maybeVerb of
Just (this, spec) -> callCommandVerb player spec this command dobj iobj
Nothing -> findVerb verbPermX "huh" room >>= \found -> case found of
(Just verbLoc, Just verb) ->
callCommandVerb player (verbLoc, verb) room command dobj iobj
_ -> notify player "I couldn't understand that." >> return zero
where locateVerb :: ObjId -> ObjId -> ObjId ->
MOO (Maybe (ObjId, (ObjId, Verb)))
locateVerb dobj iobj this =
let acceptable verb =
objMatch this (verbDirectObject verb) dobj &&
objMatch this (verbIndirectObject verb) iobj &&
prepMatch (verbPreposition verb) (commandPrepSpec command)
in findVerb acceptable (commandVerb command) this >>= \found ->
case found of
(Just verbLoc, Just verb) -> return $ Just (this, (verbLoc, verb))
_ -> return Nothing
|
verement/etamoo
|
src/MOO/Command.hs
|
bsd-3-clause
| 8,114
| 0
| 24
| 2,411
| 2,401
| 1,257
| 1,144
| 175
| 13
|
module Data.Function.Apply where
import Data.Function.Slip
(-$) = flip
infixl 8 -$
(--$) = (<<~>)
infixl 8 --$
(---$) = (<<~~>)
infixl 8 ---$
(----$) = (<<~~~>)
infixl 8 ----$
|
athanclark/composition-extra
|
src/Data/Function/Apply.hs
|
bsd-3-clause
| 186
| 0
| 4
| 39
| 67
| 47
| 20
| 10
| 1
|
module Database.Hitcask.Util where
remove :: Eq a => a -> [a] -> [a]
remove x = filter (not . (== x))
untilM :: (Monad m) => m Bool -> m a -> m [a]
untilM f action = go []
where go xs = do
x <- f
if not x
then do
y <- action
go (y:xs)
else return $! xs
|
tcrayford/hitcask
|
Database/Hitcask/Util.hs
|
bsd-3-clause
| 366
| 0
| 14
| 175
| 159
| 81
| 78
| 12
| 2
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
------------------------------------------------------------------------------
module Snap.Test.Common where
import Blaze.ByteString.Builder
import Control.DeepSeq
import Control.Exception.Lifted (SomeException (..), catch,
evaluate, finally, try)
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Control
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy as L
import Data.Monoid
import Data.Typeable
import Network.Socket
import qualified Network.Socket.ByteString as N
#if !(MIN_VERSION_base(4,6,0))
import Prelude hiding (catch)
#endif
import System.Timeout
import Test.HUnit (assertFailure)
import Test.QuickCheck
------------------------------------------------------------------------------
instance Arbitrary S.ByteString where
arbitrary = liftM S.pack arbitrary
instance Arbitrary L.ByteString where
arbitrary = do
n <- choose(0,5)
chunks <- replicateM n arbitrary
return $! L.fromChunks chunks
------------------------------------------------------------------------------
expectException :: IO a -> IO ()
expectException m = do
e <- try m
case e of
Left (z::SomeException) -> length (show z) `seq` return ()
Right _ -> assertFailure "expected exception, didn't get it"
------------------------------------------------------------------------------
expectExceptionBeforeTimeout :: IO a -- ^ action to run
-> Int -- ^ number of seconds to expect
-- exception by
-> IO Bool
expectExceptionBeforeTimeout act nsecs = do
x <- timeout (nsecs * (10::Int)^(6::Int)) f
case x of
Nothing -> return False
(Just y) -> return y
where
f = (act >> return False) `catch` \(e::SomeException) -> do
if show e == "<<timeout>>"
then return False
else return True
------------------------------------------------------------------------------
withSock :: Int -> (Socket -> IO a) -> IO a
withSock port go = do
addr <- liftM (addrAddress . Prelude.head) $
getAddrInfo (Just myHints)
(Just "127.0.0.1")
(Just $ show port)
sock <- socket AF_INET Stream defaultProtocol
connect sock addr
go sock `finally` sClose sock
where
myHints = defaultHints { addrFlags = [ AI_NUMERICHOST ] }
------------------------------------------------------------------------------
recvAll :: Socket -> IO ByteString
recvAll sock = do
b <- f mempty sock
return $! toByteString b
where
f b sk = do
s <- N.recv sk 100000
if S.null s
then return b
else f (b `mappend` fromByteString s) sk
------------------------------------------------------------------------------
ditchHeaders :: [ByteString] -> [ByteString]
ditchHeaders ("":xs) = xs
ditchHeaders ("\r":xs) = xs
ditchHeaders (_:xs) = ditchHeaders xs
ditchHeaders [] = []
------------------------------------------------------------------------------
forceSameType :: a -> a -> a
forceSameType _ a = a
------------------------------------------------------------------------------
-- | Kill the false negative on derived show instances.
coverShowInstance :: (Monad m, Show a) => a -> m ()
coverShowInstance x = a `deepseq` b `deepseq` c `deepseq` return ()
where
a = showsPrec 0 x ""
b = show x
c = showList [x] ""
------------------------------------------------------------------------------
coverReadInstance :: (MonadIO m, Read a) => a -> m ()
coverReadInstance x = do
liftIO $ eatException $ evaluate $ forceSameType [(x,"")] $ readsPrec 0 ""
liftIO $ eatException $ evaluate $ forceSameType [([x],"")] $ readList ""
------------------------------------------------------------------------------
coverEqInstance :: (Monad m, Eq a) => a -> m ()
coverEqInstance x = a `seq` b `seq` return ()
where
a = x == x
b = x /= x
------------------------------------------------------------------------------
coverOrdInstance :: (Monad m, Ord a) => a -> m ()
coverOrdInstance x = a `deepseq` b `deepseq` return ()
where
a = [ x < x
, x >= x
, x > x
, x <= x
, compare x x == EQ ]
b = min a $ max a a
------------------------------------------------------------------------------
coverTypeableInstance :: (Monad m, Typeable a) => a -> m ()
coverTypeableInstance a = typeOf a `seq` return ()
------------------------------------------------------------------------------
eatException :: (MonadBaseControl IO m) => m a -> m ()
eatException a = (a >> return ()) `catch` handler
where
handler :: (MonadBaseControl IO m) => SomeException -> m ()
handler _ = return ()
|
afcowie/new-snap-server
|
test/Snap/Test/Common.hs
|
bsd-3-clause
| 5,366
| 0
| 13
| 1,351
| 1,381
| 737
| 644
| 104
| 3
|
{-# LANGUAGE ParallelListComp, TemplateHaskell, TypeOperators #-}
module Colours
where
import Control.Monad
import Control.Category
import Data.Label
import Prelude hiding ((.), id)
data Colour = Colour {
_red :: Int,
_green :: Int,
_blue :: Int,
_alpha :: Double
} deriving (Show, Eq, Ord)
mkLabels[''Colour]
range = 25
-- find if the number is between the two numbers
withinRange :: Int -> Int -> Bool
withinRange x y = x - range < y && x + range > y
-- generate the rate at which two colours are friends
matesRates :: Colour -> Colour -> Int
matesRates x y = length ranged
where
ranged = [1 | c <- [red, green, blue], withinRange (get c x) (get c y)]
-- generate a new alpha based on the input colours
newAlpha :: Colour -> Colour -> Double
newAlpha (Colour _ _ _ a1) (Colour _ _ _ a2)
| a1 > a2 = (a1 + a2) / 2
| a1 < a2 = (a1 + (a2 / 2)) / 2
| otherwise = a1
-- generate a new red based on the input coloours
newRed :: Colour -> Colour -> Int
newRed (Colour r1 _ _ _) (Colour r2 _ _ _)
| r1 > r2 = div (r1 + r2) 2
| r1 < r2 = div (r1 + (div r2 2)) 2
| otherwise = r1
-- generate a new green based on the input colours
newGreen :: Colour -> Colour -> Int
newGreen (Colour _ g1 _ _) (Colour _ g2 _ _)
| g1 > g2 = div (g1 + g2) 2
| g1 < g2 = div (g1 + (div g2 2)) 2
| otherwise = g1
-- generate a new blue based on the input colours
newBlue :: Colour -> Colour -> Int
newBlue (Colour _ _ b1 _) (Colour _ _ b2 _)
| b1 > b2 = div (b1 + b2) 2
| b1 < b2 = div (b1 + (div b2 2)) 2
| otherwise = b1
|
eeue56/DinosaurCube
|
Colours.hs
|
bsd-3-clause
| 1,577
| 10
| 11
| 416
| 676
| 350
| 326
| 39
| 1
|
module Reporting.Result where
import qualified Control.Monad as M
import Control.Monad.Except (Except, runExcept)
import Data.Coapplicative
import qualified Reporting.Annotation as A
-- TASK
data Result warning error result =
Result
[A.Located warning]
(RawResult [A.Located error] result)
deriving (Show)
data RawResult e a
= Ok a
| Err e
deriving (Show)
-- HELPERS
ok :: a -> Result w e a
ok value =
Result [] (Ok value)
throw :: A.Region -> e -> Result w e a
throw region err =
Result [] (Err [A.At region err])
throwMany :: [A.Located e] -> Result w e a
throwMany errors =
Result [] (Err errors)
from :: (e -> e') -> Except [A.Located e] a -> Result w e' a
from f except =
case runExcept except of
Right answer ->
ok answer
Left errors ->
throwMany (map (fmap f) errors)
mapError :: (e -> e') -> Result w e a -> Result w e' a
mapError f (Result warnings rawResult) =
Result warnings $
case rawResult of
Ok v ->
Ok v
Err msgs ->
Err (map (fmap f) msgs)
warn :: A.Region -> w -> Result w e ()
warn region warning =
Result [A.At region warning] (Ok ())
addWarnings :: [A.Located w] -> Result w e a -> Result w e a
addWarnings newWarnings (Result warnings rawResult) =
Result (newWarnings ++ warnings) rawResult
destruct :: (e -> b) -> (a -> b) -> RawResult e a -> b
destruct errFunc okFunc rawResult =
case rawResult of
Ok answer ->
okFunc answer
Err errors ->
errFunc errors
toMaybe :: Result w x a -> Maybe a
toMaybe (Result _ (Ok a)) = Just a
toMaybe (Result _ (Err _)) = Nothing
toEither :: Result w x a -> Either [x] a
toEither (Result _ (Ok a)) = Right a
toEither (Result _ (Err x)) = Left $ fmap extract x
-- EXTRA FANCY HELPERS
instance M.Functor (Result w e) where
fmap func (Result warnings rawResult) =
case rawResult of
Ok a ->
Result warnings (Ok (func a))
Err msgs ->
Result warnings (Err msgs)
instance Applicative (Result w e) where
pure value =
ok value
(<*>) (Result warnings resultFunc) (Result warnings' resultVal) =
Result (warnings ++ warnings') $
case (resultFunc, resultVal) of
(Ok func, Ok val) ->
Ok (func val)
(Err msgs, Err msgs') ->
Err (msgs ++ msgs')
(Err msgs, _) ->
Err msgs
(_, Err msgs) ->
Err msgs
instance M.Monad (Result w e) where
return value =
ok value
(>>=) (Result warnings rawResult) callback =
case rawResult of
Err msg ->
Result warnings (Err msg)
Ok value ->
let (Result warnings' rawResult') = callback value
in
Result (warnings ++ warnings') rawResult'
|
avh4/elm-format
|
elm-format-lib/src/Reporting/Result.hs
|
bsd-3-clause
| 2,861
| 0
| 14
| 900
| 1,162
| 581
| 581
| 88
| 2
|
{-# LANGUAGE CPP #-}
module Text.EditDistance.ArrayUtilities (
unsafeReadArray, unsafeWriteArray,
unsafeReadArray', unsafeWriteArray',
stringToArray
) where
import Control.Monad (forM_)
import Control.Monad.ST
import Data.Array.ST
import Data.Array.Base (unsafeRead, unsafeWrite, getNumElements)
#ifdef __GLASGOW_HASKELL__
import GHC.Arr (unsafeIndex)
#else
import Data.Ix (index)
{-# INLINE unsafeIndex #-}
unsafeIndex :: Ix i => (i, i) -> i -> Int
unsafeIndex = index
#endif
{-# INLINE unsafeReadArray #-}
unsafeReadArray :: (MArray a e m, Ix i) => a i e -> i -> m e
unsafeReadArray marr i = do
f <- unsafeReadArray' marr
f i
{-# INLINE unsafeWriteArray #-}
unsafeWriteArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ()
unsafeWriteArray marr i e = do
f <- unsafeWriteArray' marr
f i e
{-# INLINE unsafeReadArray' #-}
unsafeReadArray' :: (MArray a e m, Ix i) => a i e -> m (i -> m e)
unsafeReadArray' marr = do
(l,u) <- getBounds marr
return $ \i -> unsafeRead marr (unsafeIndex (l,u) i)
{-# INLINE unsafeWriteArray' #-}
unsafeWriteArray' :: (MArray a e m, Ix i) => a i e -> m (i -> e -> m ())
unsafeWriteArray' marr = do
(l,u) <- getBounds marr
return $ \i e -> unsafeWrite marr (unsafeIndex (l,u) i) e
{-# INLINE stringToArray #-}
stringToArray :: String -> Int -> ST s (STUArray s Int Char)
stringToArray str str_len = do
array <- newArray_ (1, str_len)
write <- unsafeWriteArray' array
forM_ (zip [1..] str) (uncurry write)
return array
{-
showArray :: STUArray s (Int, Int) Int -> ST s String
showArray array = do
((il, jl), (iu, ju)) <- getBounds array
flip (flip foldM "") [(i, j) | i <- [il..iu], j <- [jl.. ju]] $ \rest (i, j) -> do
elt <- readArray array (i, j)
return $ rest ++ show (i, j) ++ ": " ++ show elt ++ ", "
-}
|
batterseapower/edit-distance
|
Text/EditDistance/ArrayUtilities.hs
|
bsd-3-clause
| 1,830
| 0
| 12
| 399
| 532
| 276
| 256
| 40
| 1
|
-- |Module that contains the configuration types for Haskoop.
module Haskoop.Configuration.Types where
data JobConfiguration = JobConfiguration {
input :: [String],
output :: String,
hadoop :: String,
streamingJar :: String,
optionalOptions :: [OptionalOption],
genericOptions :: [GenericOption]
}
data OptionalOption
= File String
| InputFormat String
| OutputFormat String
| Partitioner String
| CmdEnv String String
| InputReader String
| Background Bool
| Verbose Bool
| LazyOutput Bool
| NumReduceTasks Int
| MapDebug String
| ReduceDebug String
| IO String
data GenericOption
= Conf String
| Property String String
| FileSystem HostName
| JobTracker HostName
| Files [String]
| LibJars [String]
| Archives [String]
type Host = String
type Port = Int
data HostName = LocalHost | RemoteHost Host Port
|
jejansse/Haskoop
|
src/Haskoop/Configuration/Types.hs
|
bsd-3-clause
| 837
| 16
| 9
| 150
| 225
| 137
| 88
| 33
| 0
|
module Main where
import Control.Monad.IO.Class (liftIO)
import LambdaCalc.Eval
import LambdaCalc.Parser
import LambdaCalc.Syntax
import System.Console.Haskeline
loop :: InputT IO ()
loop = do
maybeInput <- getInputLine "λ >"
case maybeInput of
Nothing -> outputStrLn "Au revoir"
Just input -> liftIO (process input) >> loop
process :: String -> IO ()
process s =
let exs = parseExpr s in
case exs of
Right ev -> print (runEval ev)
Left err -> print err
main :: IO ()
main = runInputT defaultSettings loop
|
AlphaMarc/WYAH
|
app/LambdaRepl.hs
|
bsd-3-clause
| 637
| 0
| 13
| 211
| 192
| 96
| 96
| 20
| 2
|
-----------------------------------------------------------------------------
--
-- Module : Scoutess.Types
-- Copyright : 2012 Jeremy Shaw, Alp Mestanogullari
-- License : BSD3
--
-- Maintainer : alpmestan@gmail.com
-- Stability :
-- Portability :
--
-- | Contains the base types used in the rest of the program.
--
-----------------------------------------------------------------------------
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-}
module Scoutess.Types where
import Control.Arrow
import Control.Category (Category)
import Control.Exception (Exception)
import Control.Monad.Error (Error(..))
import Control.Monad.Trans.Maybe
import Control.Monad.Writer
import Data.Data (Typeable, Typeable2, Data(..))
import Data.Function (on)
import Data.Monoid
import Data.Set (Set)
import Data.Text (Text, pack)
import Distribution.Package
import Distribution.PackageDescription
import Distribution.Simple.LocalBuildInfo (LocalBuildInfo)
import System.FilePath ((</>))
--------------------
-- Scoutess arrow --
--------------------
type Scoutess' = MaybeT (WriterT [ComponentReport] IO)
-- | A Scoutess computation is an IO function make from components. Each component may fail and\/or record
-- 'ComponentReport's in addition to its return value.
newtype Scoutess a b = Scoutess {unScoutess :: Kleisli Scoutess' a b}
deriving (Category, Arrow, ArrowApply, ArrowChoice, ArrowLoop, ArrowPlus, ArrowZero)
----------------
-- Components --
----------------
-- | A component is an IO function that may fail and\/or record log messages. It also signifies
-- if it was successful with the 'Bool'.
-- TODO: make this a newtype to ease error messages.
type Component b = MaybeT (WriterT [Text] IO) (Bool, b)
---------------------------
-- Dealing with packages --
---------------------------
-- | A package that we've seen the cabal file of but not neccesarily fetched yet
data VersionInfo = VersionInfo
{ viCabalPath :: !FilePath -- ^ The parsed .cabal file
, viPackageIden :: !PackageIdentifier -- ^ The package identifier
-- , viDependencies :: ![Dependency] -- ^ Dependencies of the package
, viVersionTag :: !Text -- ^ If two packages have the same name and version,
-- this is the tiebreaker
, viSourceLocation :: !SourceLocation -- ^ Where this package came from
} deriving Show
-- | Information about a package which has been fetched and is locally available now
data SourceInfo = SourceInfo
{ siPath :: FilePath -- ^ path to its location
, siVersionInfo :: VersionInfo -- ^ information about the package
}
deriving (Show, Typeable, Eq, Ord)
-- | 'Eq' and 'Ord' will ignore the 'GenericPackageDescription'. 'Ord' because it isn't an instance
-- naturally and 'Eq' in order to make 'Ord' consistent.
instance Eq VersionInfo where
vi == vi' = (viVersionTag vi, viSourceLocation vi) == (viVersionTag vi', viSourceLocation vi')
instance Ord VersionInfo where
vi `compare` vi' = (viVersionTag vi, viSourceLocation vi) `compare` (viVersionTag vi', viSourceLocation vi')
-- | Places where sources can be found.
-- TODO: Include support for torrents and Hackage-style RemoteDBs (for example, Hackage mirrors)
-- TODO: Branches and tags for Bzr, Git, Hg (others?)
data SourceLocation
= Bzr Text -- ^ get source from a bzr repo
| Cd FilePath SourceLocation -- ^ source is in the sub-directory of another 'SourceLocation'
| Darcs Text (Maybe Text) -- ^ get source from a darcs repo (optional tag)
| Dir FilePath -- ^ get source from local directory
| Process FilePath [String] SourceLocation -- ^ get source and run a process in the source directory
| Git Text -- ^ get source from a git repo
| Hackage -- ^ get source from hackage
| Hg Text -- ^ get source from mercurial
| Patch SourceLocation Text -- ^ Apply the patch given in the 'Text' to the target
| Quilt SourceLocation SourceLocation -- ^ get source and apply a quilt patch
| Svn Text -- ^ get source from subversion
| Tla Text -- ^ get source from tla
| Uri Text (Maybe Text) -- ^ get source as @.tar.gz@ from uri (optional md5sum checksum)
deriving (Read, Show, Eq, Ord, Data, Typeable)
---------------------
-- Container types --
---------------------
-- | A set of locations
data SourceSpec
= SourceSpec { ssLocations :: Set SourceLocation }
deriving Show
-- | Corresponds to a virtual repository
data VersionSpec = VersionSpec
{ vsVersions :: Set VersionInfo -- ^ The packages contained in the repository
, vsPreferences :: Maybe Text -- ^ Repositories can also contain a file specifying preferred versions.
}
deriving (Show, Eq, Ord)
instance Monoid VersionSpec where
mappend vs1 vs2 = VersionSpec ((mappend `on` vsVersions) vs1 vs2) ((mappend `on` vsPreferences) vs1 vs2)
mempty = VersionSpec mempty mempty
-- | The finalised sources of the build
data BuildSources = BuildSources
{ targetSource :: [SourceInfo] -- ^ The source for the target
, depSources :: [SourceInfo] -- ^ The sources for the dependencies (in reverse topological order)
}
deriving Show
-----------
-- Other --
-----------
-- | Configuration for fetching sources
data SourceConfig = SourceConfig
{ srcCacheDir :: FilePath -- ^ path to directory that holds retrieved source
}
deriving (Eq, Ord, Read, Show, Data, Typeable)
-- | The data type representing a local package repository
data LocalHackage = LocalHackage
{ hackageDir :: FilePath
, hackageTmpDir :: FilePath
} deriving Show
-- | type for errors this service might encounter
--
-- should this be an 'Exception' or just an 'Error'?
--
-- Do we need to include the 'SourceLocation' in the error?
data SourceException
= SourceErrorOther Text
| SourceErrorUnknown
deriving (Eq, Ord, Read, Show, Data, Typeable)
instance Error SourceException where
noMsg = SourceErrorUnknown
strMsg s = SourceErrorOther (pack s)
instance Exception SourceException
-- | The information we need in order to build a package
-- TODO: just including the 'TargetSpec' is a bit lazy, we probably should
-- extract the fields we need instead.
data BuildSpec = BuildSpec
{ bsTargetSpec :: TargetSpec -- ^ input to scoutess
, bsTargetInfo :: [VersionInfo] -- ^ information about the target package
, bsDependencies :: [VersionInfo] -- ^ in reverse topological order
, bsToBuild :: Bool -- ^ is there a build needed?
}
deriving Show
data TargetSpec = TargetSpec
{ tsName :: String
, tsTargets :: Set Target
, tsTmpDir :: FilePath
, tsGhcPath :: FilePath
}
deriving Show
-- | The initial input to scoutess. A bit of a mess.
data Target = Target
{ tName :: Text -- ^ the name of the target package
, tVersion :: Maybe Text -- ^ the version of the target package
, tLocation :: Maybe SourceLocation
-- , tseLocation :: SourceLocation -- ^ the 'SourceLocation' of the target package
-- , tseTmpDir :: FilePath -- ^ a directory that scoutess will put temporary files in
-- , tseLocalHackage :: LocalHackage -- ^ the local hackage repo
-- , tsePackageDB :: FilePath -- ^ the directory to be used as a package-db
-- , tseSourceConfig :: SourceConfig -- ^ the directory to unpack things from repos in
-- , tseCustomCabalArgs :: [Text] -- ^ any additional arguments to pass to cabal
}
deriving (Eq, Ord, Show)
data Locations = Locations
{ lTmpDir :: FilePath
, lLocalHackage :: LocalHackage
, lPackageDB :: FilePath
, lSandboxDir :: FilePath
, lSourceConfig :: SourceConfig
, lGhcPath :: FilePath
}
deriving Show
mkLocations :: FilePath -> FilePath -> Locations
mkLocations tmpDir ghcPath = Locations
{ lTmpDir = tmpDir
, lLocalHackage = LocalHackage (tmpDir </> "localHackage") (tmpDir </> "localHackage" </> "temp")
, lPackageDB = tmpDir </> "package-cache"
, lSandboxDir = tmpDir </> "cabal-sandbox"
, lSourceConfig = SourceConfig (tmpDir </> "srcCacheDir")
, lGhcPath = ghcPath
}
-- | The initial input to scoutess. A bit of a mess.
data TargetSpecExt = TargetSpecExt
{ tseName :: Text -- ^ the name of the target package
, tseVersion :: Text -- ^ the version of the target package
, tseLocation :: SourceLocation -- ^ the 'SourceLocation' of the target package
, tseTmpDir :: FilePath -- ^ a directory that scoutess will put temporary files in
, tseLocalHackage :: LocalHackage -- ^ the local hackage repo
, tsePackageDB :: FilePath -- ^ the directory to be used as a package-db
, tseSourceConfig :: SourceConfig -- ^ the directory to unpack things from repos in
, tseCustomCabalArgs :: [Text] -- ^ any additional arguments to pass to cabal
}
deriving Show
-- | Each component can report success or (non-fatal) failure along with extra information
data ComponentReport = ComponentReport
{ componentName :: Text
, componendSuccess :: Bool
, componentOutput :: Text
} deriving Show
-- TODO: should we just have a link to the LocalBuildInfo?
data BuildReport = BuildReport
{ brBuildSpec :: BuildSpec
, brLocalBuildInfo :: [LocalBuildInfo]
}
deriving Show
-- | A cut down 'BuildReport' containing a record of which packages were built
data PriorRun = PriorRun
{ prTarget :: VersionInfo
, prDependencies :: Set VersionInfo
}
deriving Show
-- | A link to a 00-index.tar.gz file
data LocalHackageIndex = LocalHackageIndex
{ pathToIndex :: FilePath
}
deriving Show
|
cartazio/scoutess
|
Scoutess/Types.hs
|
bsd-3-clause
| 10,363
| 0
| 10
| 2,750
| 1,405
| 862
| 543
| 146
| 1
|
-- |
-- Module : Crypto.Hash.Blake2s
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : experimental
-- Portability : unknown
--
-- Module containing the binding functions to work with the
-- Blake2s cryptographic hash.
--
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
module Crypto.Hash.Blake2s
( Blake2s_160 (..), Blake2s_224 (..), Blake2s_256 (..)
) where
import Crypto.Hash.Types
import Foreign.Ptr (Ptr)
import Data.Data
import Data.Typeable
import Data.Word (Word8, Word32)
-- | Blake2s (160 bits) cryptographic hash algorithm
data Blake2s_160 = Blake2s_160
deriving (Show,Data,Typeable)
instance HashAlgorithm Blake2s_160 where
type HashBlockSize Blake2s_160 = 64
type HashDigestSize Blake2s_160 = 20
type HashInternalContextSize Blake2s_160 = 136
hashBlockSize _ = 64
hashDigestSize _ = 20
hashInternalContextSize _ = 136
hashInternalInit p = c_blake2s_init p 160
hashInternalUpdate = c_blake2s_update
hashInternalFinalize p = c_blake2s_finalize p 160
-- | Blake2s (224 bits) cryptographic hash algorithm
data Blake2s_224 = Blake2s_224
deriving (Show,Data,Typeable)
instance HashAlgorithm Blake2s_224 where
type HashBlockSize Blake2s_224 = 64
type HashDigestSize Blake2s_224 = 28
type HashInternalContextSize Blake2s_224 = 136
hashBlockSize _ = 64
hashDigestSize _ = 28
hashInternalContextSize _ = 136
hashInternalInit p = c_blake2s_init p 224
hashInternalUpdate = c_blake2s_update
hashInternalFinalize p = c_blake2s_finalize p 224
-- | Blake2s (256 bits) cryptographic hash algorithm
data Blake2s_256 = Blake2s_256
deriving (Show,Data,Typeable)
instance HashAlgorithm Blake2s_256 where
type HashBlockSize Blake2s_256 = 64
type HashDigestSize Blake2s_256 = 32
type HashInternalContextSize Blake2s_256 = 136
hashBlockSize _ = 64
hashDigestSize _ = 32
hashInternalContextSize _ = 136
hashInternalInit p = c_blake2s_init p 256
hashInternalUpdate = c_blake2s_update
hashInternalFinalize p = c_blake2s_finalize p 256
foreign import ccall unsafe "cryptonite_blake2s_init"
c_blake2s_init :: Ptr (Context a) -> Word32 -> IO ()
foreign import ccall "cryptonite_blake2s_update"
c_blake2s_update :: Ptr (Context a) -> Ptr Word8 -> Word32 -> IO ()
foreign import ccall unsafe "cryptonite_blake2s_finalize"
c_blake2s_finalize :: Ptr (Context a) -> Word32 -> Ptr (Digest a) -> IO ()
|
tekul/cryptonite
|
Crypto/Hash/Blake2s.hs
|
bsd-3-clause
| 2,785
| 0
| 11
| 691
| 548
| 298
| 250
| 53
| 0
|
{-# LANGUAGE CPP, ScopedTypeVariables #-}
{-|
This module provides a logical representation of OpenFlow switches and protocol messages.
An OpenFlow message is either a switch-to-controller message or controller-to-switch message.
In either case, each message is tagged with a unique message identifier.
-}
module Nettle.OpenFlow.Messages (
TransactionID
, SCMessage (..)
, CSMessage (..)
) where
import Data.ByteString (ByteString)
import Data.Word
import qualified Nettle.OpenFlow.Port as Port
import Nettle.OpenFlow.Action
import qualified Nettle.OpenFlow.Packet as Packet
import Nettle.OpenFlow.Switch
import Nettle.OpenFlow.Match
import qualified Nettle.OpenFlow.FlowTable as FlowTable
import Nettle.OpenFlow.Statistics
import Nettle.OpenFlow.Error
-- | Every OpenFlow message is tagged with a MessageID value.
type TransactionID = Word32
-- | The Switch can send the following messages to
-- the controller.
data SCMessage = SCHello -- ^ Sent after a switch establishes a TCP connection to the controller
| SCEchoRequest ![Word8] -- ^ Switch requests an echo reply
| SCEchoReply ![Word8] -- ^ Switch responds to an echo request
| Features !SwitchFeatures -- ^ Switch reports its features
| PacketIn !Packet.PacketInfo -- ^ Switch sends a packet to the controller
| PortStatus !Port.PortStatus -- ^ Switch sends port status
| FlowRemoved !FlowTable.FlowRemoved -- ^ Switch reports that a flow has been removed
| StatsReply !StatsReply -- ^ Switch reports statistics
| Error !SwitchError -- ^ Switch reports an error
| BarrierReply -- ^ Switch responds that a barrier has been processed
| QueueConfigReply !QueueConfigReply
deriving (Show,Eq)
-- |The controller can send these messages to the switch.
data CSMessage
= CSHello -- ^ Controller must send hello before sending any other messages
| CSEchoRequest ![Word8] -- ^ Controller requests a switch echo
| CSEchoReply ![Word8] -- ^ Controller responds to a switch echo request
| FeaturesRequest -- ^ Controller requests features information
| PacketOut !Packet.PacketOut -- ^ Controller commands switch to send a packet
| FlowMod !FlowTable.FlowMod -- ^ Controller modifies a switch flow table
| PortMod !Port.PortMod -- ^ Controller configures a switch port
| StatsRequest !StatsRequest -- ^ Controller requests statistics
| BarrierRequest -- ^ Controller requests a barrier
| SetConfig
| ExtQueueModify !Port.PortID ![QueueConfig]
| ExtQueueDelete !Port.PortID ![QueueConfig]
| Vendor ByteString
| GetQueueConfig !QueueConfigRequest
deriving (Eq)
instance Show CSMessage where
show CSHello = "Hello"
show (CSEchoRequest _) = "EchoRequest"
show (CSEchoReply _) = "EchoReply"
show FeaturesRequest = "FeaturesRequest"
show (PacketOut po) = show po
show (FlowMod fm) = show fm
show (PortMod pm) = show pm
show (StatsRequest r) = show r
show BarrierRequest = "BarrierRequest"
show SetConfig = "SetConfig"
show (ExtQueueModify p q) = "QueueModify " ++ show p ++ " " ++ show q
show (ExtQueueDelete p q) = "QueueDelete " ++ show p ++ " " ++ show q
show (Vendor _) = show "Vendor _"
show (GetQueueConfig cfg) = show cfg
|
brownsys/nettle-openflow
|
src/Nettle/OpenFlow/Messages.hs
|
bsd-3-clause
| 3,426
| 0
| 9
| 806
| 564
| 316
| 248
| 99
| 0
|
-- | A renderer that produces a native Haskell 'String', mostly meant for
-- debugging purposes.
--
{-# LANGUAGE OverloadedStrings, GADTs #-}
module Text.Blaze.Renderer.String
( fromChoiceString
, renderMarkup
, renderHtml
) where
import Data.List (isInfixOf)
import qualified Data.ByteString.Char8 as SBC
import qualified Data.Text as T
import qualified Data.ByteString as S
import Text.Blaze.Internal
-- | Escape predefined XML entities in a string
--
escapeMarkupEntities :: String -- ^ String to escape
-> String -- ^ String to append
-> String -- ^ Resulting string
escapeMarkupEntities [] k = k
escapeMarkupEntities (c:cs) k = case c of
'<' -> '&' : 'l' : 't' : ';' : escapeMarkupEntities cs k
'>' -> '&' : 'g' : 't' : ';' : escapeMarkupEntities cs k
'&' -> '&' : 'a' : 'm' : 'p' : ';' : escapeMarkupEntities cs k
'"' -> '&' : 'q' : 'u' : 'o' : 't' : ';' : escapeMarkupEntities cs k
'\'' -> '&' : '#' : '3' : '9' : ';' : escapeMarkupEntities cs k
x -> x : escapeMarkupEntities cs k
-- | Render a 'ChoiceString'.
--
fromChoiceString :: ChoiceString -- ^ String to render
-> String -- ^ String to append
-> String -- ^ Resulting string
fromChoiceString (Static s) = getString s
fromChoiceString (String s) = escapeMarkupEntities s
fromChoiceString (Text s) = escapeMarkupEntities $ T.unpack s
fromChoiceString (ByteString s) = (SBC.unpack s ++)
fromChoiceString (PreEscaped x) = case x of
String s -> (s ++)
Text s -> (\k -> T.foldr (:) k s)
s -> fromChoiceString s
fromChoiceString (External x) = case x of
-- Check that the sequence "</" is *not* in the external data.
String s -> if "</" `isInfixOf` s then id else (s ++)
Text s -> if "</" `T.isInfixOf` s then id else (\k -> T.foldr (:) k s)
ByteString s -> if "</" `S.isInfixOf` s then id else (SBC.unpack s ++)
s -> fromChoiceString s
fromChoiceString (AppendChoiceString x y) =
fromChoiceString x . fromChoiceString y
fromChoiceString EmptyChoiceString = id
{-# INLINE fromChoiceString #-}
-- | Render some 'Markup' to an appending 'String'.
--
renderString :: Markup -- ^ Markup to render
-> String -- ^ String to append
-> String -- ^ Resulting String
renderString = go id
where
go :: (String -> String) -> MarkupM b -> String -> String
go attrs (Parent _ open close content) =
getString open . attrs . ('>' :) . go id content . getString close
go attrs (CustomParent tag content) =
('<' :) . fromChoiceString tag . attrs . ('>' :) . go id content .
("</" ++) . fromChoiceString tag . ('>' :)
go attrs (Leaf _ begin end) = getString begin . attrs . getString end
go attrs (CustomLeaf tag close) =
('<' :) . fromChoiceString tag . attrs .
(if close then (" />" ++) else ('>' :))
go attrs (AddAttribute _ key value h) = flip go h $
getString key . fromChoiceString value . ('"' :) . attrs
go attrs (AddCustomAttribute key value h) = flip go h $
(' ' :) . fromChoiceString key . ("=\"" ++) . fromChoiceString value .
('"' :) . attrs
go _ (Content content) = fromChoiceString content
go _ (Comment comment) =
("<!-- " ++) . fromChoiceString comment . (" -->" ++)
go attrs (Append h1 h2) = go attrs h1 . go attrs h2
go _ (Empty _) = id
{-# NOINLINE go #-}
{-# INLINE renderString #-}
-- | Render markup to a lazy 'String'.
--
renderMarkup :: Markup -> String
renderMarkup html = renderString html ""
{-# INLINE renderMarkup #-}
renderHtml :: Markup -> String
renderHtml = renderMarkup
{-# INLINE renderHtml #-}
{-# DEPRECATED renderHtml
"Use renderHtml from Text.Blaze.Html.Renderer.String instead" #-}
|
dylex/blaze-markup
|
src/Text/Blaze/Renderer/String.hs
|
bsd-3-clause
| 3,917
| 0
| 14
| 1,072
| 1,151
| 614
| 537
| 74
| 11
|
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE GADTs #-}
module Hmond.Types ( Host (..)
, Metric (..)
, MetricRecord (..)
, makeMetric
, mrType
, MetricSlope (..)
, MetricType (..)
, ValueGenerator (..)
, Env (..)
, Config (..)
, ClusterInfo (..)
) where
import Data.Int (Int8, Int16, Int32)
import Data.Word (Word8, Word16, Word32)
import Data.Time.Clock
import Network
data Host = Host { hostname :: String
, hostIP :: String
, hostMetrics :: [Metric]
}
data MetricRecord a = MkMr { mrName :: String
, mrValue :: MetricType a
, mrUnits :: Maybe String
, mrTN :: Int
, mrTMAX :: Int
, mrDMAX :: Int
, mrSlope :: MetricSlope
} deriving Show
nullMetricRecord :: MetricRecord a
nullMetricRecord = MkMr { mrUnits = Nothing
, mrTN = 60
, mrTMAX = 60
, mrDMAX = 180
, mrSlope = Unspecified
}
data Metric = forall a. MkM (MetricRecord a) (MetricRecord a -> Metric)
makeMetric :: (MetricType a -> ValueGenerator a)
-> MetricType a
-> String
-> Metric
makeMetric mkGen mv name = MkM (metricRecord) (metricGenerator $ mkGen mv)
where metricRecord = nullMetricRecord { mrName = name }
metricGenerator :: ValueGenerator a -> MetricRecord a -> Metric
metricGenerator gen mr = MkM mr' $ metricGenerator gen'
where (mv', gen') = runGenerator gen
mr' = mr { mrValue = mv' }
data MetricType a where
MtInt8 :: Int8 -> MetricType Int8
MtInt16 :: Int16 -> MetricType Int16
MtInt32 :: Int32 -> MetricType Int32
MtUInt8 :: Word8 -> MetricType Word8
MtUInt16 :: Word16 -> MetricType Word16
MtUInt32 :: Word32 -> MetricType Word32
MtFloat :: Float -> MetricType Float
MtDouble :: Double -> MetricType Double
MtString :: String -> MetricType String
-- MtTimestamp :: Timestamp -> MetricType Timestamp
instance Show (MetricType a) where
show (MtInt8 i) = show i
show (MtInt16 i) = show i
show (MtInt32 i) = show i
show (MtUInt8 i) = show i
show (MtUInt16 i) = show i
show (MtUInt32 i) = show i
show (MtFloat i) = show i
show (MtDouble i) = show i
show (MtString i) = i
mrType :: MetricRecord a -> String
mrType mr = case mrValue mr of
MtInt8 _ -> "int8"
MtInt16 _ -> "int16"
MtInt32 _ -> "int32"
MtUInt8 _ -> "word8"
MtUInt16 _ -> "word16"
MtUInt32 _ -> "word32"
MtFloat _ -> "float"
MtDouble _ -> "double"
MtString _ -> "string"
data MetricSlope = Zero | Positive | Negative | Both | Unspecified
instance Show MetricSlope where
show Zero = "zero"
show Positive = "positive"
show Negative = "negative"
show Both = "both"
show Unspecified = "unspecified"
data ValueGenerator a = ValueGenerator {
runGenerator :: (MetricType a, ValueGenerator a)
}
data Env = Env {
envHosts :: [Host]
}
data Config = Config { cfgPort :: PortNumber
, cfgMetricUpdatePeriod :: NominalDiffTime
, cfgCluster :: ClusterInfo
} deriving (Show)
data ClusterInfo = ClusterInfo { clName :: String
, clOwner :: String
, clLatlong :: String
, clUrl :: String
} deriving (Show)
|
benarmston/hmond
|
src/Hmond/Types.hs
|
bsd-3-clause
| 4,154
| 0
| 10
| 1,773
| 1,009
| 555
| 454
| 97
| 9
|
{-# LANGUAGE DeriveDataTypeable #-}
module Data.Combinator.SKI where
import Data.Data (Data)
import Data.Typeable (Typeable)
import Test.QuickCheck
import Control.Applicative
data SKI = S | K | I | Ap SKI SKI
deriving (Eq, Ord, Data, Typeable)
-- | >>> Ap (Ap S K) K
-- ``skk
-- >>> Ap (Ap (Ap S I) I) (Ap (Ap S I) I)
-- ```sii``sii
instance Show SKI where
showsPrec d = showParen (app_prec < d) . f where
f S = showChar 's'
f K = showChar 'k'
f I = showChar 'i'
f (Ap x y) = showChar '`' . shows x . shows y
app_prec = 10
instance Arbitrary SKI where
arbitrary = frequency
[ (,) 1 $ pure S
, (,) 1 $ pure K
, (,) 1 $ pure I
, (,) 2 $ Ap <$> arbitrary <*> arbitrary
]
instance CoArbitrary SKI where
coarbitrary = coarbitrary . show
|
kmyk/proof-haskell
|
Data/Combinator/SKI.hs
|
mit
| 833
| 0
| 12
| 249
| 286
| 151
| 135
| 23
| 0
|
{-# OPTIONS -i.. #-}
module Main where
import Graphics.Rendering.OpenGL as OpenGL
import Graphics.SDL as SDL hiding (flip)
import Data.IORef
import System.Environment
import Control.Monad
import Objects
step = 0.1
succStep x = x + step
predStep x = x - step
main = withInit [InitVideo] $
do progName <- getProgName
setVideoMode width height 0 [OpenGL,Resizeable]
setCaption progName ""
resizeGLScene width height
initAndRun
where width = 640
height = 480
initAndRun :: IO ()
initAndRun =
do (textures,image,xrot,yrot,xspeed,yspeed) <- myInit
setVideoMode width height 0 [OpenGL,Resizeable]
resizeGLScene width height
let loop = do delay 10
event <- pollEvent
drawGLScreen textures image xrot yrot xspeed yspeed
quit <- case event of
Quit -> return True
KeyDown (Keysym SDLK_q _ _) -> return True
KeyDown (Keysym SDLK_LEFT _ _) -> modifyIORef yspeed predStep >> return False
KeyDown (Keysym SDLK_RIGHT _ _) -> modifyIORef yspeed succStep >> return False
KeyDown (Keysym SDLK_UP _ _) -> modifyIORef xspeed predStep >> return False
KeyDown (Keysym SDLK_DOWN _ _) -> modifyIORef xspeed succStep >> return False
KeyDown (Keysym SDLK_f _ _) -> modifyIORef image (flip mod 3 . succ) >> return False
VideoResize w h -> resizeGLScene w h >> return False
_ -> return False
when (not quit) loop
loop
where width = 640
height = 480
drawGLScreen :: [TextureObject] -> IORef Int -> IORef GLfloat -> IORef GLfloat -> IORef GLfloat -> IORef GLfloat -> IO ()
drawGLScreen textures imageRef xrotRef yrotRef xspeedRef yspeedRef
= do clear [ColorBuffer, DepthBuffer]
loadIdentity
xrot <- get xrotRef
yrot <- get yrotRef
xspeed <- get xspeedRef
yspeed <- get yspeedRef
filter <- get imageRef
translate $ Vector3 0 0 (-5::GLfloat)
rotate xrot $ Vector3 (1::GLfloat) 0 0
rotate yrot $ Vector3 (0::GLfloat) 1 0
texture Texture2D $= Enabled
textureBinding Texture2D $= Just (textures!!filter)
renderPrimitive Quads $
mapM_ (\((n1,n2,n3),points) ->
do normal $ Normal3 n1 n2 n3
mapM_ (\((coord1,coord2),(x,y,z)) ->
do texCoord $ TexCoord2 coord1 coord2
vertex $ Vertex3 x y z
) points
) quadsPoints
xrotRef $= xrot+xspeed
yrotRef $= yrot+yspeed
glSwapBuffers
myInit :: IO ([TextureObject], IORef Int,IORef GLfloat, IORef GLfloat, IORef GLfloat, IORef GLfloat)
myInit = do image <- loadBMP "Data/lesson8/glass.bmp"
tex1 <- loadObject image $ textureFilter Texture2D $= ((Nearest, Nothing),Nearest)
tex2 <- loadObject image $ textureFilter Texture2D $= ((Linear', Nothing),Linear')
tex3 <- loadObject image $ do generateMipmap Texture2D $= Enabled
textureFilter Texture2D $= ((Linear', Just Nearest),Linear')
[xrot,yrot,xspeed,yspeed] <- mapM newIORef [0,0,0,0]
image <- newIORef 0
blend $= Enabled
blendEquation $= FuncAdd
blendFunc $= (OpenGL.SrcAlpha,OneMinusSrcAlpha)
depthFunc $= Just Less
clearColor $= Color4 0 0 1 1
shadeModel $= Smooth
return (map objTexId [tex1,tex2,tex3],image,xrot,yrot,xspeed,yspeed)
resizeGLScene w h
= do setVideoMode w h 0 [OpenGL,Resizeable]
viewport $= (Position 0 0, Size (fromIntegral w) (fromIntegral h))
matrixMode $= Projection
loadIdentity
perspective 45 radio 0.1 100
matrixMode $= Modelview 0
where radio = fromIntegral w / fromIntegral h
quadsPoints :: [((GLfloat,GLfloat,GLfloat),[((GLfloat,GLfloat),(GLfloat,GLfloat,GLfloat))])]
quadsPoints =
[
((0,0,1) -- Font
,[((0,0),(-1,-1,1))
,((1,0),(1,-1,1))
,((1,1),(1,1,1))
,((0,1),(-1,1,1))])
,((0,0,-1) -- Back
,[((1,0),(-1,-1,-1))
,((1,1),(-1,1,-1))
,((0,1),(1,1,-1))
,((0,0),(1,-1,-1))])
,((0,1,0) -- Top
,[((0,1),(-1,1,-1))
,((0,0),(-1,1,1))
,((1,0),(1,1,1))
,((1,1),(1,1,-1))])
,((0,-1,0) -- Bottom
,[((1,1),(-1,-1,-1))
,((0,1),(1,-1,-1))
,((0,0),(1,-1,1))
,((1,0),(-1,-1,1))])
,((1,0,0) -- Right
,[((1,0),(1,-1,-1))
,((1,1),(1,1,-1))
,((0,1),(1,1,1))
,((0,0),(1,-1,1))])
,((-1,0,0) -- Left
,[((0,0),(-1,-1,-1))
,((1,0),(-1,-1,1))
,((1,1),(-1,1,1))
,((0,1),(-1,1,-1))])
]
|
keera-studios/hssdl
|
Examples/NeHe/lesson08/lesson8.sdl.hs
|
bsd-3-clause
| 5,156
| 0
| 20
| 1,830
| 2,143
| 1,179
| 964
| 122
| 9
|
-- Global references; types
--
-- Author: Patrick Maier
-----------------------------------------------------------------------------
{-# LANGUAGE DeriveGeneric
, DeriveDataTypeable #-}
module Control.Parallel.HdpH.Internal.Type.GRef
( -- * global references
GRef(..),
-- * registry for global references
-- GRefReg(..),
TaskRef(..),
taskHandle
) where
import Prelude
import Control.Parallel.HdpH.Internal.Location (NodeId)
-- import Control.Parallel.HdpH.Internal.Misc (AnyType)
import Data.Binary (Binary)
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Control.DeepSeq (NFData)
-----------------------------------------------------------------------------
-- global references
-- Global references, comprising a locally unique slot on the hosting node
-- and the hosting node's ID. Note that the slot, represented by a positive
-- integer, must be unique over the life time of the hosting node (ie. it
-- can not be reused). Note also that the type constructor 'GRef' takes
-- a phantom type parameter, tracking the type of the referenced object.
data GRef a = GRef { slot :: !Int,
at :: !NodeId }
data TaskRef = TaskRef { slotT :: !Int,
atT :: !NodeId }
deriving (Generic,Typeable,Eq,Show)
instance Binary TaskRef
instance NFData TaskRef
taskHandle :: GRef a -> TaskRef
taskHandle g = TaskRef { slotT = slot g , atT = at g }
|
robstewart57/hdph-rs
|
src/Control/Parallel/HdpH/Internal/Type/GRef.hs
|
bsd-3-clause
| 1,468
| 0
| 9
| 299
| 221
| 136
| 85
| 30
| 1
|
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "src/Foreign/Marshal/Utils/Compat.hs" #-}
{-# LANGUAGE CPP, NoImplicitPrelude #-}
{-# LANGUAGE ForeignFunctionInterface #-}
module Foreign.Marshal.Utils.Compat (
module Base
, fillBytes
) where
import Foreign.Marshal.Utils as Base
|
phischu/fragnix
|
tests/packages/scotty/Foreign.Marshal.Utils.Compat.hs
|
bsd-3-clause
| 322
| 0
| 4
| 84
| 29
| 22
| 7
| 8
| 0
|
-- | A very simple cache
module Cache
( Cache
, newCache
, lookupCache
, clearCache
) where
import Hash
import Control.Concurrent.MVar (MVar, newEmptyMVar, readMVar, putMVar)
import Data.Array.IO (IOArray, newArray, readArray, writeArray, getBounds)
import Data.Char (digitToInt)
-------------------------
data Cache a
= Cache
{ array :: IOArray Int [CacheEntry a]
, cacheLineSize :: Int -- length of the lists
}
data CacheEntry a
= CacheEntry
{ question :: Hash
, answer :: MVar a
}
newCache :: Int -> IO (Cache a)
newCache x = do
a <- newArray (0,255) []
return $ Cache a x
clearCache :: Cache a -> IO ()
clearCache c = do
(a,b) <- getBounds $ array c
mapM_ (\i -> writeArray (array c) i []) [a..b]
lookupCache :: Cache a -> Hash -> IO (Either a (a -> IO ()))
lookupCache ch e = modifyCacheLine (array ch) (getIndex e) $ \vv ->
case lookupIA (cacheLineSize ch) (\x -> e == question x) vv of
(Just x_, c) -> do
x <- readMVar (answer x_)
return (x_ : c, Left x)
(Nothing, c) -> do
v <- newEmptyMVar
return (CacheEntry e v: c, Right $ putMVar v)
where
lookupIA :: Int -> (a -> Bool) -> [a] -> (Maybe a, [a])
lookupIA i p l = f i l where
f _ (x: xs) | p x = (Just x, xs)
f 1 _ = (Nothing, [])
f i (x: xs) = case f (i-1) xs of
(a, b) -> (a, x:b)
f _ [] = (Nothing, [])
modifyCacheLine ch i f = do
x <- readArray ch i
(x', r) <- f x
writeArray ch i x'
return r
getIndex :: Hash -> Int
getIndex e = 16 * digitToInt a + digitToInt b where (a:b:_) = show e
|
lambdacube3d/lambdacube-editor
|
compiler-service/Cache.hs
|
bsd-3-clause
| 1,738
| 0
| 15
| 582
| 775
| 404
| 371
| 48
| 5
|
{-
(c) The GRASP/AQUA Project, Glasgow University, 1993-1998
\section[StgLint]{A ``lint'' pass to check for Stg correctness}
-}
{-# LANGUAGE CPP #-}
module StgLint ( lintStgBindings ) where
import StgSyn
import Bag ( Bag, emptyBag, isEmptyBag, snocBag, bagToList )
import Id ( Id, idType, isLocalId )
import VarSet
import DataCon
import CoreSyn ( AltCon(..) )
import PrimOp ( primOpType )
import Literal ( literalType )
import Maybes
import Name ( getSrcLoc )
import ErrUtils ( MsgDoc, Severity(..), mkLocMessage )
import Type
import TyCon
import Util
import SrcLoc
import Outputable
import Control.Monad
import Data.Function
#include "HsVersions.h"
{-
Checks for
(a) *some* type errors
(b) locally-defined variables used but not defined
Note: unless -dverbose-stg is on, display of lint errors will result
in "panic: bOGUS_LVs".
WARNING:
~~~~~~~~
This module has suffered bit-rot; it is likely to yield lint errors
for Stg code that is currently perfectly acceptable for code
generation. Solution: don't use it! (KSW 2000-05).
************************************************************************
* *
\subsection{``lint'' for various constructs}
* *
************************************************************************
@lintStgBindings@ is the top-level interface function.
-}
lintStgBindings :: String -> [StgBinding] -> [StgBinding]
lintStgBindings whodunnit binds
= {-# SCC "StgLint" #-}
case (initL (lint_binds binds)) of
Nothing -> binds
Just msg -> pprPanic "" (vcat [
text "*** Stg Lint ErrMsgs: in" <+>
text whodunnit <+> text "***",
msg,
text "*** Offending Program ***",
pprStgBindings binds,
text "*** End of Offense ***"])
where
lint_binds :: [StgBinding] -> LintM ()
lint_binds [] = return ()
lint_binds (bind:binds) = do
binders <- lintStgBinds bind
addInScopeVars binders $
lint_binds binds
lintStgArg :: StgArg -> LintM (Maybe Type)
lintStgArg (StgLitArg lit) = return (Just (literalType lit))
lintStgArg (StgVarArg v) = lintStgVar v
lintStgVar :: Id -> LintM (Maybe Kind)
lintStgVar v = do checkInScope v
return (Just (idType v))
lintStgBinds :: StgBinding -> LintM [Id] -- Returns the binders
lintStgBinds (StgNonRec binder rhs) = do
lint_binds_help (binder,rhs)
return [binder]
lintStgBinds (StgRec pairs)
= addInScopeVars binders $ do
mapM_ lint_binds_help pairs
return binders
where
binders = [b | (b,_) <- pairs]
lint_binds_help :: (Id, StgRhs) -> LintM ()
lint_binds_help (binder, rhs)
= addLoc (RhsOf binder) $ do
-- Check the rhs
_maybe_rhs_ty <- lintStgRhs rhs
-- Check binder doesn't have unlifted type
checkL (not (isUnliftedType binder_ty))
(mkUnliftedTyMsg binder rhs)
-- Check match to RHS type
-- Actually we *can't* check the RHS type, because
-- unsafeCoerce means it really might not match at all
-- notably; eg x::Int = (error @Bool "urk") |> unsafeCoerce...
-- case maybe_rhs_ty of
-- Nothing -> return ()
-- Just rhs_ty -> checkTys binder_ty
-- rhs_ty
--- (mkRhsMsg binder rhs_ty)
return ()
where
binder_ty = idType binder
lintStgRhs :: StgRhs -> LintM (Maybe Type) -- Just ty => type is exact
lintStgRhs (StgRhsClosure _ _ _ _ [] expr)
= lintStgExpr expr
lintStgRhs (StgRhsClosure _ _ _ _ binders expr)
= addLoc (LambdaBodyOf binders) $
addInScopeVars binders $ runMaybeT $ do
body_ty <- MaybeT $ lintStgExpr expr
return (mkFunTys (map idType binders) body_ty)
lintStgRhs (StgRhsCon _ con args) = runMaybeT $ do
arg_tys <- mapM (MaybeT . lintStgArg) args
MaybeT $ checkFunApp con_ty arg_tys (mkRhsConMsg con_ty arg_tys)
where
con_ty = dataConRepType con
lintStgExpr :: StgExpr -> LintM (Maybe Type) -- Just ty => type is exact
lintStgExpr (StgLit l) = return (Just (literalType l))
lintStgExpr e@(StgApp fun args) = runMaybeT $ do
fun_ty <- MaybeT $ lintStgVar fun
arg_tys <- mapM (MaybeT . lintStgArg) args
MaybeT $ checkFunApp fun_ty arg_tys (mkFunAppMsg fun_ty arg_tys e)
lintStgExpr e@(StgConApp con args) = runMaybeT $ do
arg_tys <- mapM (MaybeT . lintStgArg) args
MaybeT $ checkFunApp con_ty arg_tys (mkFunAppMsg con_ty arg_tys e)
where
con_ty = dataConRepType con
lintStgExpr e@(StgOpApp (StgPrimOp op) args _) = runMaybeT $ do
arg_tys <- mapM (MaybeT . lintStgArg) args
MaybeT $ checkFunApp op_ty arg_tys (mkFunAppMsg op_ty arg_tys e)
where
op_ty = primOpType op
lintStgExpr (StgOpApp _ args res_ty) = runMaybeT $ do
-- We don't have enough type information to check
-- the application for StgFCallOp and StgPrimCallOp; ToDo
_maybe_arg_tys <- mapM (MaybeT . lintStgArg) args
return res_ty
lintStgExpr (StgLam bndrs _) = do
addErrL (text "Unexpected StgLam" <+> ppr bndrs)
return Nothing
lintStgExpr (StgLet binds body) = do
binders <- lintStgBinds binds
addLoc (BodyOfLetRec binders) $
addInScopeVars binders $
lintStgExpr body
lintStgExpr (StgLetNoEscape binds body) = do
binders <- lintStgBinds binds
addLoc (BodyOfLetRec binders) $
addInScopeVars binders $
lintStgExpr body
lintStgExpr (StgTick _ expr) = lintStgExpr expr
lintStgExpr (StgCase scrut bndr alts_type alts) = runMaybeT $ do
_ <- MaybeT $ lintStgExpr scrut
in_scope <- MaybeT $ liftM Just $
case alts_type of
AlgAlt tc -> check_bndr tc >> return True
PrimAlt tc -> check_bndr tc >> return True
UbxTupAlt _ -> return False -- Binder is always dead in this case
PolyAlt -> return True
MaybeT $ addInScopeVars [bndr | in_scope] $
lintStgAlts alts scrut_ty
where
scrut_ty = idType bndr
UnaryRep scrut_rep = repType scrut_ty -- Not used if scrutinee is unboxed tuple
check_bndr tc = case tyConAppTyCon_maybe scrut_rep of
Just bndr_tc -> checkL (tc == bndr_tc) bad_bndr
Nothing -> addErrL bad_bndr
where
bad_bndr = mkDefltMsg bndr tc
lintStgAlts :: [StgAlt]
-> Type -- Type of scrutinee
-> LintM (Maybe Type) -- Just ty => type is accurage
lintStgAlts alts scrut_ty = do
maybe_result_tys <- mapM (lintAlt scrut_ty) alts
-- Check the result types
case catMaybes (maybe_result_tys) of
[] -> return Nothing
(first_ty:_tys) -> do -- mapM_ check tys
return (Just first_ty)
where
-- check ty = checkTys first_ty ty (mkCaseAltMsg alts)
-- We can't check that the alternatives have the
-- same type, because they don't, with unsafeCoerce#
lintAlt :: Type -> (AltCon, [Id], StgExpr) -> LintM (Maybe Type)
lintAlt _ (DEFAULT, _, rhs)
= lintStgExpr rhs
lintAlt scrut_ty (LitAlt lit, _, rhs) = do
checkTys (literalType lit) scrut_ty (mkAltMsg1 scrut_ty)
lintStgExpr rhs
lintAlt scrut_ty (DataAlt con, args, rhs) = do
case splitTyConApp_maybe scrut_ty of
Just (tycon, tys_applied) | isAlgTyCon tycon &&
not (isNewTyCon tycon) -> do
let
cons = tyConDataCons tycon
arg_tys = dataConInstArgTys con tys_applied
-- This does not work for existential constructors
checkL (con `elem` cons) (mkAlgAltMsg2 scrut_ty con)
checkL (length args == dataConRepArity con) (mkAlgAltMsg3 con args)
when (isVanillaDataCon con) $
mapM_ check (zipEqual "lintAlgAlt:stg" arg_tys args)
return ()
_ ->
addErrL (mkAltMsg1 scrut_ty)
addInScopeVars args $
lintStgExpr rhs
where
check (ty, arg) = checkTys ty (idType arg) (mkAlgAltMsg4 ty arg)
-- elem: yes, the elem-list here can sometimes be long-ish,
-- but as it's use-once, probably not worth doing anything different
-- We give it its own copy, so it isn't overloaded.
elem _ [] = False
elem x (y:ys) = x==y || elem x ys
{-
************************************************************************
* *
\subsection[lint-monad]{The Lint monad}
* *
************************************************************************
-}
newtype LintM a = LintM
{ unLintM :: [LintLocInfo] -- Locations
-> IdSet -- Local vars in scope
-> Bag MsgDoc -- Error messages so far
-> (a, Bag MsgDoc) -- Result and error messages (if any)
}
data LintLocInfo
= RhsOf Id -- The variable bound
| LambdaBodyOf [Id] -- The lambda-binder
| BodyOfLetRec [Id] -- One of the binders
dumpLoc :: LintLocInfo -> (SrcSpan, SDoc)
dumpLoc (RhsOf v) =
(srcLocSpan (getSrcLoc v), text " [RHS of " <> pp_binders [v] <> char ']' )
dumpLoc (LambdaBodyOf bs) =
(srcLocSpan (getSrcLoc (head bs)), text " [in body of lambda with binders " <> pp_binders bs <> char ']' )
dumpLoc (BodyOfLetRec bs) =
(srcLocSpan (getSrcLoc (head bs)), text " [in body of letrec with binders " <> pp_binders bs <> char ']' )
pp_binders :: [Id] -> SDoc
pp_binders bs
= sep (punctuate comma (map pp_binder bs))
where
pp_binder b
= hsep [ppr b, dcolon, ppr (idType b)]
initL :: LintM a -> Maybe MsgDoc
initL (LintM m)
= case (m [] emptyVarSet emptyBag) of { (_, errs) ->
if isEmptyBag errs then
Nothing
else
Just (vcat (punctuate blankLine (bagToList errs)))
}
instance Functor LintM where
fmap = liftM
instance Applicative LintM where
pure a = LintM $ \_loc _scope errs -> (a, errs)
(<*>) = ap
(*>) = thenL_
instance Monad LintM where
(>>=) = thenL
(>>) = (*>)
thenL :: LintM a -> (a -> LintM b) -> LintM b
thenL m k = LintM $ \loc scope errs
-> case unLintM m loc scope errs of
(r, errs') -> unLintM (k r) loc scope errs'
thenL_ :: LintM a -> LintM b -> LintM b
thenL_ m k = LintM $ \loc scope errs
-> case unLintM m loc scope errs of
(_, errs') -> unLintM k loc scope errs'
checkL :: Bool -> MsgDoc -> LintM ()
checkL True _ = return ()
checkL False msg = addErrL msg
addErrL :: MsgDoc -> LintM ()
addErrL msg = LintM $ \loc _scope errs -> ((), addErr errs msg loc)
addErr :: Bag MsgDoc -> MsgDoc -> [LintLocInfo] -> Bag MsgDoc
addErr errs_so_far msg locs
= errs_so_far `snocBag` mk_msg locs
where
mk_msg (loc:_) = let (l,hdr) = dumpLoc loc
in mkLocMessage SevWarning l (hdr $$ msg)
mk_msg [] = msg
addLoc :: LintLocInfo -> LintM a -> LintM a
addLoc extra_loc m = LintM $ \loc scope errs
-> unLintM m (extra_loc:loc) scope errs
addInScopeVars :: [Id] -> LintM a -> LintM a
addInScopeVars ids m = LintM $ \loc scope errs
-> let
new_set = mkVarSet ids
in unLintM m loc (scope `unionVarSet` new_set) errs
{-
Checking function applications: we only check that the type has the
right *number* of arrows, we don't actually compare the types. This
is because we can't expect the types to be equal - the type
applications and type lambdas that we use to calculate accurate types
have long since disappeared.
-}
checkFunApp :: Type -- The function type
-> [Type] -- The arg type(s)
-> MsgDoc -- Error message
-> LintM (Maybe Type) -- Just ty => result type is accurate
checkFunApp fun_ty arg_tys msg
= do { case mb_msg of
Just msg -> addErrL msg
Nothing -> return ()
; return mb_ty }
where
(mb_ty, mb_msg) = cfa True fun_ty arg_tys
cfa :: Bool -> Type -> [Type] -> (Maybe Type -- Accurate result?
, Maybe MsgDoc) -- Errors?
cfa accurate fun_ty [] -- Args have run out; that's fine
= (if accurate then Just fun_ty else Nothing, Nothing)
cfa accurate fun_ty arg_tys@(arg_ty':arg_tys')
| Just (arg_ty, res_ty) <- splitFunTy_maybe fun_ty
= if accurate && not (arg_ty `stgEqType` arg_ty')
then (Nothing, Just msg) -- Arg type mismatch
else cfa accurate res_ty arg_tys'
| Just (_, fun_ty') <- splitForAllTy_maybe fun_ty
= cfa False fun_ty' arg_tys
| Just (tc,tc_args) <- splitTyConApp_maybe fun_ty
, isNewTyCon tc
= if length tc_args < tyConArity tc
then WARN( True, text "cfa: unsaturated newtype" <+> ppr fun_ty $$ msg )
(Nothing, Nothing) -- This is odd, but I've seen it
else cfa False (newTyConInstRhs tc tc_args) arg_tys
| Just tc <- tyConAppTyCon_maybe fun_ty
, not (isTypeFamilyTyCon tc) -- Definite error
= (Nothing, Just msg) -- Too many args
| otherwise
= (Nothing, Nothing)
stgEqType :: Type -> Type -> Bool
-- Compare types, but crudely because we have discarded
-- both casts and type applications, so types might look
-- different but be the same. So reply "True" if in doubt.
-- "False" means that the types are definitely different.
--
-- Fundamentally this is a losing battle because of unsafeCoerce
stgEqType orig_ty1 orig_ty2
= gos (repType orig_ty1) (repType orig_ty2)
where
gos :: RepType -> RepType -> Bool
gos (UbxTupleRep tys1) (UbxTupleRep tys2)
= equalLength tys1 tys2 && and (zipWith go tys1 tys2)
gos (UnaryRep ty1) (UnaryRep ty2) = go ty1 ty2
gos _ _ = False
go :: UnaryType -> UnaryType -> Bool
go ty1 ty2
| Just (tc1, tc_args1) <- splitTyConApp_maybe ty1
, Just (tc2, tc_args2) <- splitTyConApp_maybe ty2
, let res = if tc1 == tc2
then equalLength tc_args1 tc_args2 && and (zipWith (gos `on` repType) tc_args1 tc_args2)
else -- TyCons don't match; but don't bleat if either is a
-- family TyCon because a coercion might have made it
-- equal to something else
(isFamilyTyCon tc1 || isFamilyTyCon tc2)
= if res then True
else
pprTrace "stgEqType: unequal" (vcat [ppr ty1, ppr ty2])
False
| otherwise = True -- Conservatively say "fine".
-- Type variables in particular
checkInScope :: Id -> LintM ()
checkInScope id = LintM $ \loc scope errs
-> if isLocalId id && not (id `elemVarSet` scope) then
((), addErr errs (hsep [ppr id, text "is out of scope"]) loc)
else
((), errs)
checkTys :: Type -> Type -> MsgDoc -> LintM ()
checkTys ty1 ty2 msg = LintM $ \loc _scope errs
-> if (ty1 `stgEqType` ty2)
then ((), errs)
else ((), addErr errs msg loc)
_mkCaseAltMsg :: [StgAlt] -> MsgDoc
_mkCaseAltMsg _alts
= ($$) (text "In some case alternatives, type of alternatives not all same:")
(Outputable.empty) -- LATER: ppr alts
mkDefltMsg :: Id -> TyCon -> MsgDoc
mkDefltMsg bndr tc
= ($$) (text "Binder of a case expression doesn't match type of scrutinee:")
(ppr bndr $$ ppr (idType bndr) $$ ppr tc)
mkFunAppMsg :: Type -> [Type] -> StgExpr -> MsgDoc
mkFunAppMsg fun_ty arg_tys expr
= vcat [text "In a function application, function type doesn't match arg types:",
hang (text "Function type:") 4 (ppr fun_ty),
hang (text "Arg types:") 4 (vcat (map (ppr) arg_tys)),
hang (text "Expression:") 4 (ppr expr)]
mkRhsConMsg :: Type -> [Type] -> MsgDoc
mkRhsConMsg fun_ty arg_tys
= vcat [text "In a RHS constructor application, con type doesn't match arg types:",
hang (text "Constructor type:") 4 (ppr fun_ty),
hang (text "Arg types:") 4 (vcat (map (ppr) arg_tys))]
mkAltMsg1 :: Type -> MsgDoc
mkAltMsg1 ty
= ($$) (text "In a case expression, type of scrutinee does not match patterns")
(ppr ty)
mkAlgAltMsg2 :: Type -> DataCon -> MsgDoc
mkAlgAltMsg2 ty con
= vcat [
text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
ppr ty,
ppr con
]
mkAlgAltMsg3 :: DataCon -> [Id] -> MsgDoc
mkAlgAltMsg3 con alts
= vcat [
text "In some algebraic case alternative, number of arguments doesn't match constructor:",
ppr con,
ppr alts
]
mkAlgAltMsg4 :: Type -> Id -> MsgDoc
mkAlgAltMsg4 ty arg
= vcat [
text "In some algebraic case alternative, type of argument doesn't match data constructor:",
ppr ty,
ppr arg
]
_mkRhsMsg :: Id -> Type -> MsgDoc
_mkRhsMsg binder ty
= vcat [hsep [text "The type of this binder doesn't match the type of its RHS:",
ppr binder],
hsep [text "Binder's type:", ppr (idType binder)],
hsep [text "Rhs type:", ppr ty]
]
mkUnliftedTyMsg :: Id -> StgRhs -> SDoc
mkUnliftedTyMsg binder rhs
= (text "Let(rec) binder" <+> quotes (ppr binder) <+>
text "has unlifted type" <+> quotes (ppr (idType binder)))
$$
(text "RHS:" <+> ppr rhs)
|
tjakway/ghcjvm
|
compiler/stgSyn/StgLint.hs
|
bsd-3-clause
| 17,569
| 0
| 19
| 5,151
| 4,716
| 2,396
| 2,320
| -1
| -1
|
{- |
Module : $Header$
Description : XPath utilities
Copyright : (c) Christian Maeder, DFKI GmbH 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : portable
XPath utilities independent of xml package.
references:
<http://www.w3.org/TR/xpath/>
<http://www.galiel.net/el/study/XPath_Overview.html>
<http://www.fh-wedel.de/~si/HXmlToolbox/hxpath/diplomarbeit.pdf>
<http://hackage.haskell.org/package/hxt-xpath>
(modules XPathParser, XPathDataTypes)
<http://hackage.haskell.org/package/hxt-8.5.0>
(modules Text.XML.HXT.DOM.Unicode, Text.XML.HXT.Parser.XmlCharParser)
<http://www.w3.org/TR/REC-xml/#NT-Name>
Unicode is not
fully supported. A qualified name is an ncName or two ncNames
separated by a colon (different from OWL uris).
-}
module Common.XPath where
import Text.ParserCombinators.Parsec
import Common.Parsec
import Data.Char
import Data.List
-- * data types and pretty printing (via show)
-- | axis specifier
data Axis
= Ancestor Bool -- ^ or self?
| Attribute
| Child
| Descendant Bool -- ^ or self?
| Following Bool -- ^ sibling?
| Namespace
| Parent
| Preceding Bool -- ^ sibling?
| Self
deriving Show
-- | all possible values
allAxis :: [Axis]
allAxis = let bl = [True, False] in
[ Attribute
, Child
, Namespace
, Parent
, Self ]
++ [ Ancestor b | b <- bl ]
++ [ Descendant b | b <- bl ]
++ [ Following b | b <- bl ]
++ [ Preceding b | b <- bl ]
-- | utility to show (constant) constructors as lower case strings
lowerShow :: Show a => a -> String
lowerShow = map toLower . show
-- | proper string representation (do not use show)
showAxis :: Axis -> String
showAxis a =
let s = takeWhile isAlpha $ lowerShow a
orSelf b = if b then s ++ "-or-self" else s
sibl b = if b then s ++ "-sibling" else s
in case a of
Ancestor c -> orSelf c
Descendant c -> orSelf c
Following c -> sibl c
Preceding c -> sibl c
_ -> s
-- | testing attribute, namespace or element nodes (usually) by name
data NodeTest
= NameTest String -- ^ optional prefix and local part (possibly a * wildcard)
| PI String -- ^ processing-instruction node type with optional literal
| Node -- ^ true for any node (therefore rarely used)
| Comment -- ^ true for comment nodes
| Text -- ^ true for text nodes
deriving Show
-- | all node types without processing-instruction
nodeTypes :: [NodeTest]
nodeTypes = [Node, Comment, Text]
-- | the processing-instruction string
pIS :: String
pIS = "processing-instruction"
-- | put parens arount a string
paren :: String -> String
paren = ('(' :) . (++ ")")
-- | proper string representation (do not use show)
showNodeTest :: NodeTest -> String
showNodeTest t = case t of
NameTest q -> q
PI s -> pIS ++ paren s
_ -> lowerShow t ++ paren ""
-- | the stuff of a path between the slashes
data Step = Step Axis NodeTest [Expr] -- ^ with predicate list
-- | string representation considering abbreviations
showStep :: Step -> String
showStep (Step a n ps) =
let t = showNodeTest n in
case (a, n) of
(Attribute, _) -> '@' : t
(Child, _) -> t
(Self, Node) -> "."
(Parent, Node) -> ".."
_ -> showAxis a ++ "::" ++ t
++ concatMap showPred ps
instance Show Step where
show = showStep
-- | test for @descendant-or-self::node()@ step
isDescOrSelfNode :: Step -> Bool
isDescOrSelfNode (Step a n _) = case (a, n) of
(Descendant True, Node) -> True
_ -> False
-- | only absolute paths may be empty
data Path = Path Bool [Step] -- ^ absolute?
-- | show a path abbreviating @\/descendant-or-self::node()\/@
showSteps :: Bool -> [Step] -> String
showSteps abso sts = let h = if abso then "/" else "" in case sts of
[] -> h
s : r -> let f = h ++ showStep s in case r of
[] -> f
_ -> if abso && isDescOrSelfNode s then "//" ++ showSteps False r
else f ++ showSteps True r
instance Show Path where
show (Path abso sts) = showSteps abso sts
-- | indicator for primary expressions
data PrimKind
= Var -- ^ leading dollar
| Literal -- ^ single or double quotes
| Number -- ^ digits possibly with decimal point
-- | expressions where function calls, unary and infix expressions are generic
data Expr
= GenExpr Bool String [Expr] -- ^ infix?, op or fct, and arguments
| PathExpr (Maybe Expr) Path -- ^ optional filter and path
| FilterExpr Expr [Expr] -- ^ primary expression with predicates
| PrimExpr PrimKind String
instance Show Expr where
show = showExpr
-- | put square brackets around an expression
showPred :: Expr -> String
showPred e = '[' : showExpr e ++ "]"
-- | show expression with minimal parens
showExpr :: Expr -> String
showExpr e = case e of
GenExpr infx op args ->
if infx then
showInfixExpr op args
else op ++ paren (intercalate "," $ map showExpr args)
PathExpr m p -> case m of
Nothing -> ""
Just f -> showExpr f
++ show p
FilterExpr pe ps ->
(if isPrimExpr pe then id else paren) (showExpr pe)
++ concatMap showPred ps
PrimExpr k s -> case k of
Literal -> show $ filter (/= '"') s
_ -> s
{- | show arguments with minimal parens interspersed with the infix operator.
Also treat the unary minus where the argument list is a singleton.
Alphanumeric operators are shown with spaces, which looks bad for @mod@ and
@div@ in conjunction with additive, relational, or equality operators. The
unary minus gets a leading blank if the preceding character is a
'ncNameChar'. -}
showInfixExpr :: String -> [Expr] -> String
showInfixExpr op args = case args of
[] -> op -- cannot happen
[arg] -> -- unary minus
let s = showExpr arg
in op ++ case arg of
GenExpr True aOp _ -> case aOp of
"|" -> s
_ -> paren s
_ -> s
arg : rargs ->
let mi = findIndex (elem op) inOps
f = parenExpr False mi arg
padOp
| any isAlpha op = ' ' : op ++ " "
| elem op addOps && not (null f) && ncNameChar (last f) = ' ' : op
| otherwise = op
in f ++ concatMap ((padOp ++) . parenExpr True mi) rargs
{- | put parens around arguments that have a lower precedence or
equal precendence if they are a right argument. -}
parenExpr :: Bool -> Maybe Int -> Expr -> String
parenExpr rst mi e =
let s = showExpr e
in case e of
GenExpr True op (_ : _ : _) ->
let mj = findIndex (elem op) inOps
putPar = case (mi, mj) of
(Just i, Just j) -> i > j || rst && i == j
_ -> True
in if putPar then paren s else s
_ -> s
-- | test if expression is primary
isPrimExpr :: Expr -> Bool
isPrimExpr e = case e of
PrimExpr _ _ -> True
GenExpr False _ _ -> True
_ -> False
-- * infix operators
-- | unequal (@!=@) and equal (@=@)
eqOps :: [String]
eqOps = ["!=", "="]
-- | the four other comparisons
relOps :: [String]
relOps = ["<=", ">=", "<", ">"]
-- | @+@ and @-@, where @-@ is allowed within names and as unary operator
addOps :: [String]
addOps = ["+", "-"]
-- | @*@, div and mod, where @*@ is also used as wildcard for node names
multOps :: [String]
multOps = ["*", "div", "mod"]
{- | all infix operators. Lowest precedence for @or@ followed by @and@,
highest is union(@|@). Only these three operators may get more than two
arguments. -}
inOps :: [[String]]
inOps =
[ ["or"]
, ["and"]
, eqOps
, relOps
, addOps
, multOps
, ["|"]]
-- * parsers
-- | skip trailing spaces
skips :: Parser a -> Parser a
skips = (<< spaces)
-- | parse keyword and skip spaces
symbol :: String -> Parser String
symbol = skips . tryString
-- | skip left paren
lpar :: Parser ()
lpar = forget (symbol "(")
-- | skip right paren
rpar :: Parser ()
rpar = forget (symbol ")")
-- | non-abbreviated axis parser
axis :: Parser Axis
axis = choice (map (\ a -> symbol (showAxis a) >> return a) allAxis)
<?> "axis"
-- | the axis specifier parser
abbrAxis :: Parser Axis
abbrAxis =
(symbol "@" >> return Attribute)
<|> try (axis << symbol "::")
<|> return Child
<?> "abbrAxis"
-- | starting name character (no unicode)
ncNameStart :: Char -> Bool
ncNameStart c = isAlpha c || c == '_'
-- | name character (without @+@) including centered dot (and no other unicode)
ncNameChar :: Char -> Bool
ncNameChar c = isAlphaNum c || elem c ".-_\183"
-- | non-colon xml names (non-skipping)
ncName :: Parser String
ncName = satisfy ncNameStart <:> many (satisfy ncNameChar) <?> "ncName"
-- | literal string within single or double quotes (skipping)
literal :: Parser String
literal = skips $
(char '"' >> many (satisfy (/= '"')) << string "\"")
<|> (char '\'' >> many (satisfy (/= '\'')) << string "'")
-- | ncName or wild-card (@*@) (skipping)
localName :: Parser String
localName = symbol "*" <|> skips ncName <?> "localName"
-- | the node test parser
nodeTest :: Parser NodeTest
nodeTest = fmap PI (symbol pIS >> lpar >> literal << rpar)
<|> choice (map (\ t -> symbol (lowerShow t)
>> lpar >> rpar >> return t) nodeTypes)
<|> do
p <- try (ncName <++> string ":")
l <- localName
return $ NameTest $ p ++ l
<|> do
l <- localName
return $ NameTest l
<?> "nodeTest"
-- | parent or self abbreviated steps
abbrStep :: Parser Step
abbrStep =
(symbol ".." >> return (Step Parent Node []))
<|> (symbol "." >> return (Step Self Node []))
<?> "abbrStep"
-- | the predicate (expression in square brackets) parser
predicate :: Parser Expr
predicate = symbol "[" >> expr << symbol "]" <?> "predicate"
-- | the step (stuff between slashes) parser
step :: Parser Step
step = abbrStep <|> do
a <- abbrAxis
t <- nodeTest
ps <- many predicate
return (Step a t ps)
<?> "step"
-- | the implicit @descendant-or-self::node()@ step constant
descOrSelfStep :: Step
descOrSelfStep = Step (Descendant True) Node []
-- | a double or single slash
doubleSlash :: Parser Bool
doubleSlash = (symbol "//" >> return True) <|> (symbol "/" >> return False)
{- | a step starting with a single or double slash,
the latter yielding two steps. -}
slashStep :: Parser [Step]
slashStep = do
b <- doubleSlash
s <- step
return (if b then [descOrSelfStep, s] else [s])
<?> "slashStep"
-- | parse the steps of a relative path
relPath :: Parser [Step]
relPath = do
s <- step
sl <- many slashStep
return (s : concat sl)
<?> "relPath"
-- | a (possibly empty) absolute or (non-empty) relative path
path :: Parser Path
path = do
m <- optionMaybe doubleSlash
s <- (case m of
Just False -> optionL
_ -> id) relPath
return (case m of
Nothing -> Path False s
Just b -> Path True $ if b then descOrSelfStep : s else s)
<?> "path"
-- | at least one digit and at most one decimal point (skipping)
number :: Parser String
number = skips $ many1 digit <++> optionL (char '.' <:> many digit)
<|> try (char '.' <:> many1 digit)
-- | a qualified name (prefixed or unprefixed)
qualName :: Parser String
qualName = skips $ ncName <++> optionL (char ':' <:> ncName)
-- | parse a primary expression (including 'fct' or 'expr' in parens)
primExpr :: Parser Expr
primExpr = fmap (PrimExpr Var) (char '$' <:> qualName)
<|> (lpar >> expr << rpar)
<|> fmap (PrimExpr Literal) literal
<|> fmap (PrimExpr Number) number
<|> fct
-- | parse a function call by checking the qname and the left paren
fct :: Parser Expr
fct = do
q <- try $ do
n <- qualName
if elem n $ pIS : map lowerShow nodeTypes
then fail $ n ++ " not allowed as function name"
else lpar >> return n
args <- sepBy expr (symbol ",")
rpar
return $ GenExpr False q args
-- | parse a filter expresssion as primary expression followed by predicates
filterExpr :: Parser Expr
filterExpr = do
e <- primExpr
ps <- many predicate
return $ if null ps then e else FilterExpr e ps
{- | a path expression is either a filter expression followed by a (non-empty)
absoulte path or an ordinary 'path'. -}
pathExpr :: Parser Expr
pathExpr = do
f <- filterExpr
s <- optionL $ do
b <- doubleSlash
r <- relPath
return $ if b then descOrSelfStep : r else r
return $ if null s then f else PathExpr (Just f) $ Path True s
<|> fmap (PathExpr Nothing) path
-- | parse multiple argument expressions separated by an infix symbol
singleInfixExpr :: Parser Expr -> String -> Parser Expr
singleInfixExpr p s = do
l <- sepBy1 p $ symbol s
return $ case l of
[e] -> e
_ -> GenExpr True s l
-- | 'pathExpr' are arguments of union expression
unionExpr :: Parser Expr
unionExpr = singleInfixExpr pathExpr "|"
-- | 'unionExpr' can be prefixed by the unary minus
unaryExpr :: Parser Expr
unaryExpr = fmap (GenExpr True "-" . (: [])) (symbol "-" >> unaryExpr)
<|> unionExpr
{- | parse as many arguments separated by any infix symbol as possible
but construct left-associative binary application trees. -}
leftAssocExpr :: Parser Expr -> [String] -> Parser Expr
leftAssocExpr p ops =
chainl1 p $ do
op <- choice $ map symbol ops
return $ \ a b -> GenExpr True op [a, b]
-- * all final infix parsers using 'leftAssocExpr' or 'singleInfixExpr'
multExpr :: Parser Expr
multExpr = leftAssocExpr unaryExpr multOps
addExpr :: Parser Expr
addExpr = leftAssocExpr multExpr addOps
relExpr :: Parser Expr
relExpr = leftAssocExpr addExpr relOps
eqExpr :: Parser Expr
eqExpr = leftAssocExpr relExpr eqOps
andExpr :: Parser Expr
andExpr = singleInfixExpr eqExpr "and"
-- | the top-level expressions interspersed by @or@.
expr :: Parser Expr
expr = singleInfixExpr andExpr "or"
-- * checking sanity of paths
data PrincipalNodeType
= TAttribute
| TNamespace
| TElement
deriving Eq
principalNodeType :: Axis -> PrincipalNodeType
principalNodeType a = case a of
Attribute -> TAttribute
Namespace -> TNamespace
_ -> TElement
-- | may this step have further steps
isElementNode :: Step -> Bool
isElementNode (Step a t _) =
principalNodeType a == TElement && case t of
Node -> True
NameTest _ -> True
_ -> False
isLegalPath :: [Step] -> Bool
isLegalPath l = case l of
[] -> True
[_] -> True
s : r -> isElementNode s && isLegalPath r
finalStep :: Path -> Maybe Step
finalStep (Path _ l) = case l of
[] -> Nothing
_ -> Just $ last l
finalPrincipalNodeType :: Path -> PrincipalNodeType
finalPrincipalNodeType p = case finalStep p of
Nothing -> TElement
Just (Step a _ _) -> principalNodeType a
data BasicType
= NodeSet
| Boolean
| Numeral
| String
| Object
type FctEnv = [(String, (BasicType, [BasicType]))]
type VarEnv = [(String, BasicType)]
coreFcts :: FctEnv
coreFcts =
[ ("last", (Numeral, []))
, ("position", (Numeral, []))
, ("count", (Numeral, [NodeSet]))
, ("id", (NodeSet, [Object]))
, ("local-name", (String, [NodeSet]))
, ("namespace-uri", (String, [NodeSet]))
, ("name", (String, [NodeSet]))
, ("string", (String, [Object]))
, ("concat", (String, [String, String]))
, ("substring-before", (String, [String, String]))
, ("substring-after", (String, [String, String]))
, ("substring", (String, [String, Numeral, Numeral]))
, ("starts-with", (Boolean, [String, String]))
, ("contains", (Boolean, [String, String]))
, ("string-length", (Numeral, [String]))
, ("normalize-space", (String, [String]))
, ("translate", (String, [String, String, String]))
, ("boolean", (Boolean, [Object]))
, ("not", (Boolean, [Boolean]))
, ("true", (Boolean, []))
, ("false", (Boolean, []))
, ("lang", (Boolean, [String]))
, ("number", (Numeral, [Object]))
, ("sum", (Numeral, [NodeSet]))
, ("floor", (Numeral, [Numeral]))
, ("ceiling", (Numeral, [Numeral]))
, ("round", (Numeral, [Numeral]))
]
basicType :: Expr -> BasicType
basicType e = case e of
GenExpr infx op _ ->
if infx then case op of
"|" -> NodeSet
_ | elem op $ ["or", "and"] ++ eqOps ++ relOps -> Boolean
| elem op $ addOps ++ multOps -> Numeral
_ -> Object
else case lookup op coreFcts of
Just (t, _) -> t
Nothing -> Object
PrimExpr k _ -> case k of
Number -> Numeral
Literal -> String
Var -> Object
_ -> NodeSet
isPathExpr :: Expr -> Bool
isPathExpr e = case e of
GenExpr True "|" args -> all isPathExpr args
GenExpr False "id" [_] -> True
PrimExpr Var _ -> True
PathExpr m (Path _ s) -> isLegalPath s && maybe True isPathExpr m
FilterExpr p _ -> isPathExpr p
_ -> False
-- | parse string
parseExpr :: String -> Either String Expr
parseExpr s = case parse (expr << eof) "" s of
Right e | isPathExpr e -> Right e
Left e -> Left $ show e
_ -> Left "not a legal path expression"
getPaths :: Expr -> [Path]
getPaths e = case e of
GenExpr True "|" args -> concatMap getPaths args
PathExpr m p@(Path _ s) -> case m of
Nothing -> [p]
Just fe -> map (\ (Path r f) -> Path r $ f ++ s) $ getPaths fe
FilterExpr p _ -> getPaths p
_ -> []
|
keithodulaigh/Hets
|
Common/XPath.hs
|
gpl-2.0
| 16,894
| 0
| 20
| 3,900
| 5,057
| 2,673
| 2,384
| 412
| 9
|
-- |
-- Module : Crypto.Cipher.ChaChaPoly1305
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : stable
-- Portability : good
--
-- A simple AEAD scheme using ChaCha20 and Poly1305. See
-- <https://tools.ietf.org/html/rfc7539 RFC 7539>.
--
-- The State is not modified in place, so each function changing the State,
-- returns a new State.
--
-- Authenticated Data need to be added before any call to 'encrypt' or 'decrypt',
-- and once all the data has been added, then 'finalizeAAD' need to be called.
--
-- Once 'finalizeAAD' has been called, no further 'appendAAD' call should be make.
--
-- >import Data.ByteString.Char8 as B
-- >import Data.ByteArray
-- >import Crypto.Error
-- >import Crypto.Cipher.ChaChaPoly1305 as C
-- >
-- >encrypt
-- > :: ByteString -- nonce (12 random bytes)
-- > -> ByteString -- symmetric key
-- > -> ByteString -- optional associated data (won't be encrypted)
-- > -> ByteString -- input plaintext to be encrypted
-- > -> CryptoFailable ByteString -- ciphertext with a 128-bit tag attached
-- >encrypt nonce key header plaintext = do
-- > st1 <- C.nonce12 nonce >>= C.initialize key
-- > let
-- > st2 = C.finalizeAAD $ C.appendAAD header st1
-- > (out, st3) = C.encrypt plaintext st2
-- > auth = C.finalize st3
-- > return $ out `B.append` Data.ByteArray.convert auth
--
module Crypto.Cipher.ChaChaPoly1305
( State
, Nonce
, nonce12
, nonce8
, incrementNonce
, initialize
, appendAAD
, finalizeAAD
, encrypt
, decrypt
, finalize
) where
import Control.Monad (when)
import Crypto.Internal.ByteArray (ByteArrayAccess, ByteArray, Bytes, ScrubbedBytes)
import qualified Crypto.Internal.ByteArray as B
import Crypto.Internal.Imports
import Crypto.Error
import qualified Crypto.Cipher.ChaCha as ChaCha
import qualified Crypto.MAC.Poly1305 as Poly1305
import Data.Memory.Endian
import qualified Data.ByteArray.Pack as P
import Foreign.Ptr
import Foreign.Storable
-- | A ChaChaPoly1305 State.
--
-- The state is immutable, and only new state can be created
data State = State !ChaCha.State
!Poly1305.State
!Word64 -- AAD length
!Word64 -- ciphertext length
-- | Valid Nonce for ChaChaPoly1305.
--
-- It can be created with 'nonce8' or 'nonce12'
data Nonce = Nonce8 Bytes | Nonce12 Bytes
instance ByteArrayAccess Nonce where
length (Nonce8 n) = B.length n
length (Nonce12 n) = B.length n
withByteArray (Nonce8 n) = B.withByteArray n
withByteArray (Nonce12 n) = B.withByteArray n
-- Based on the following pseudo code:
--
-- chacha20_aead_encrypt(aad, key, iv, constant, plaintext):
-- nonce = constant | iv
-- otk = poly1305_key_gen(key, nonce)
-- ciphertext = chacha20_encrypt(key, 1, nonce, plaintext)
-- mac_data = aad | pad16(aad)
-- mac_data |= ciphertext | pad16(ciphertext)
-- mac_data |= num_to_4_le_bytes(aad.length)
-- mac_data |= num_to_4_le_bytes(ciphertext.length)
-- tag = poly1305_mac(mac_data, otk)
-- return (ciphertext, tag)
pad16 :: Word64 -> Bytes
pad16 n
| modLen == 0 = B.empty
| otherwise = B.replicate (16 - modLen) 0
where
modLen = fromIntegral (n `mod` 16)
-- | Nonce smart constructor 12 bytes IV, nonce constructor
nonce12 :: ByteArrayAccess iv => iv -> CryptoFailable Nonce
nonce12 iv
| B.length iv /= 12 = CryptoFailed CryptoError_IvSizeInvalid
| otherwise = CryptoPassed . Nonce12 . B.convert $ iv
-- | 8 bytes IV, nonce constructor
nonce8 :: ByteArrayAccess ba
=> ba -- ^ 4 bytes constant
-> ba -- ^ 8 bytes IV
-> CryptoFailable Nonce
nonce8 constant iv
| B.length constant /= 4 = CryptoFailed CryptoError_IvSizeInvalid
| B.length iv /= 8 = CryptoFailed CryptoError_IvSizeInvalid
| otherwise = CryptoPassed . Nonce8 . B.concat $ [constant, iv]
-- | Increment a nonce
incrementNonce :: Nonce -> Nonce
incrementNonce (Nonce8 n) = Nonce8 $ incrementNonce' n 4
incrementNonce (Nonce12 n) = Nonce12 $ incrementNonce' n 0
incrementNonce' :: Bytes -> Int -> Bytes
incrementNonce' b offset = B.copyAndFreeze b $ \s ->
loop s (s `plusPtr` offset)
where
loop :: Ptr Word8 -> Ptr Word8 -> IO ()
loop s p
| s == (p `plusPtr` (B.length b - offset - 1)) = peek s >>= poke s . (+) 1
| otherwise = do
r <- (+) 1 <$> peek p
poke p r
when (r == 0) $ loop s (p `plusPtr` 1)
-- | Initialize a new ChaChaPoly1305 State
--
-- The key length need to be 256 bits, and the nonce
-- procured using either `nonce8` or `nonce12`
initialize :: ByteArrayAccess key
=> key -> Nonce -> CryptoFailable State
initialize key (Nonce8 nonce) = initialize' key nonce
initialize key (Nonce12 nonce) = initialize' key nonce
initialize' :: ByteArrayAccess key
=> key -> Bytes -> CryptoFailable State
initialize' key nonce
| B.length key /= 32 = CryptoFailed CryptoError_KeySizeInvalid
| otherwise = CryptoPassed $ State encState polyState 0 0
where
rootState = ChaCha.initialize 20 key nonce
(polyKey, encState) = ChaCha.generate rootState 64
polyState = throwCryptoError $ Poly1305.initialize (B.take 32 polyKey :: ScrubbedBytes)
-- | Append Authenticated Data to the State and return
-- the new modified State.
--
-- Once no further call to this function need to be make,
-- the user should call 'finalizeAAD'
appendAAD :: ByteArrayAccess ba => ba -> State -> State
appendAAD ba (State encState macState aadLength plainLength) =
State encState newMacState newLength plainLength
where
newMacState = Poly1305.update macState ba
newLength = aadLength + fromIntegral (B.length ba)
-- | Finalize the Authenticated Data and return the finalized State
finalizeAAD :: State -> State
finalizeAAD (State encState macState aadLength plainLength) =
State encState newMacState aadLength plainLength
where
newMacState = Poly1305.update macState $ pad16 aadLength
-- | Encrypt a piece of data and returns the encrypted Data and the
-- updated State.
encrypt :: ByteArray ba => ba -> State -> (ba, State)
encrypt input (State encState macState aadLength plainLength) =
(output, State newEncState newMacState aadLength newPlainLength)
where
(output, newEncState) = ChaCha.combine encState input
newMacState = Poly1305.update macState output
newPlainLength = plainLength + fromIntegral (B.length input)
-- | Decrypt a piece of data and returns the decrypted Data and the
-- updated State.
decrypt :: ByteArray ba => ba -> State -> (ba, State)
decrypt input (State encState macState aadLength plainLength) =
(output, State newEncState newMacState aadLength newPlainLength)
where
(output, newEncState) = ChaCha.combine encState input
newMacState = Poly1305.update macState input
newPlainLength = plainLength + fromIntegral (B.length input)
-- | Generate an authentication tag from the State.
finalize :: State -> Poly1305.Auth
finalize (State _ macState aadLength plainLength) =
Poly1305.finalize $ Poly1305.updates macState
[ pad16 plainLength
, either (error "finalize: internal error") id $ P.fill 16 (P.putStorable (toLE aadLength) >> P.putStorable (toLE plainLength))
]
|
vincenthz/cryptonite
|
Crypto/Cipher/ChaChaPoly1305.hs
|
bsd-3-clause
| 7,487
| 0
| 17
| 1,726
| 1,514
| 808
| 706
| 109
| 1
|
{-# LANGUAGE RankNTypes #-}
module GhcUtils where
import Data.Generics
import GHC
import GHC.SYB.Utils
import NameSet
import Control.Monad
{-
From Data.Generics
-- | Summarise all nodes in top-down, left-to-right order
everything :: (r -> r -> r) -> GenericQ r -> GenericQ r
-- Apply f to x to summarise top-level node;
-- use gmapQ to recurse into immediate subterms;
-- use ordinary foldl to reduce list of intermediate results
--
everything k f x = foldl k (f x) (gmapQ (everything k f) x)
-- | A variation of 'everything', using a 'GenericQ Bool' to skip
-- parts of the input 'Data'.
everythingBut :: GenericQ Bool -> (r -> r -> r) -> r -> GenericQ r -> GenericQ r
everythingBut q k z f x
| q x = z
| otherwise = foldl k (f x) (gmapQ (everythingBut q k z f) x)
-- From GHC SYB Utils
-- | Like 'everything', but avoid known potholes, based on the 'Stage' that
-- generated the Ast.
everythingStaged :: Stage -> (r -> r -> r) -> r -> GenericQ r -> GenericQ r
everythingStaged stage k z f x
| (const False `extQ` postTcType `extQ` fixity `extQ` nameSet) x = z
| otherwise = foldl k (f x) (gmapQ (everythingStaged stage k z f) x)
where nameSet = const (stage `elem` [Parser,TypeChecker]) :: NameSet -> Bool
postTcType = const (stage<TypeChecker) :: PostTcType -> Bool
fixity = const (stage<Renamer) :: GHC.Fixity -> Bool
-}
-- TODO: pass this routine back to syb-utils (when it works properly)
-- Question: how to handle partial results in the otherwise step?
everythingButStaged :: Stage -> (r -> r -> r) -> r -> GenericQ (r,Bool) -> GenericQ r
everythingButStaged stage k z f x
| (const False `extQ` postTcType `extQ` fixity `extQ` nameSet) x = z
| stop == True = v
| otherwise = foldl k v (gmapQ (everythingButStaged stage k z f) x)
where (v, stop) = f x
nameSet = const (stage `elem` [Parser,TypeChecker]) :: NameSet -> Bool
postTcType = const (stage<TypeChecker) :: PostTcType -> Bool
fixity = const (stage<Renamer) :: GHC.Fixity -> Bool
{-
-- | Look up a subterm by means of a maybe-typed filter
something :: GenericQ (Maybe u) -> GenericQ (Maybe u)
-- "something" can be defined in terms of "everything"
-- when a suitable "choice" operator is used for reduction
--
something = everything orElse
-}
-- | Look up a subterm by means of a maybe-typed filter
somethingStaged :: Stage -> (Maybe u) -> GenericQ (Maybe u) -> GenericQ (Maybe u)
-- "something" can be defined in terms of "everything"
-- when a suitable "choice" operator is used for reduction
--
somethingStaged stage z = everythingStaged stage orElse z
-- ---------------------------------------------------------------------
{-
-- | Apply a monadic transformation at least somewhere
somewhere :: MonadPlus m => GenericM m -> GenericM m
-- We try "f" in top-down manner, but descent into "x" when we fail
-- at the root of the term. The transformation fails if "f" fails
-- everywhere, say succeeds nowhere.
--
somewhere f x = f x `mplus` gmapMp (somewhere f) x
-}
-- | Apply a monadic transformation at least somewhere
somewhereStaged :: MonadPlus m => Stage -> GenericM m -> GenericM m
-- We try "f" in top-down manner, but descent into "x" when we fail
-- at the root of the term. The transformation fails if "f" fails
-- everywhere, say succeeds nowhere.
--
somewhereStaged stage f x
| (const False `extQ` postTcType `extQ` fixity `extQ` nameSet) x = mzero
| otherwise = f x `mplus` gmapMp (somewhereStaged stage f) x
where nameSet = const (stage `elem` [Parser,TypeChecker]) :: NameSet -> Bool
postTcType = const (stage<TypeChecker) :: PostTcType -> Bool
fixity = const (stage<Renamer) :: GHC.Fixity -> Bool
-- ---------------------------------------------------------------------
{-
-- | Apply a transformation everywhere in bottom-up manner
everywhere :: (forall a. Data a => a -> a)
-> (forall a. Data a => a -> a)
-- Use gmapT to recurse into immediate subterms;
-- recall: gmapT preserves the outermost constructor;
-- post-process recursively transformed result via f
--
everywhere f = f . gmapT (everywhere f)
-}
{-
-- | Apply a transformation everywhere in bottom-up manner
-- Note type GenericT = forall a. Data a => a -> a
everywhereStaged :: Stage
-> (forall a. Data a => a -> a)
-> (forall a. Data a => a -> a)
-- Use gmapT to recurse into immediate subterms;
-- recall: gmapT preserves the outermost constructor;
-- post-process recursively transformed result via f
--
everywhereStaged stage f = f . gmapT (everywhere f)
| (const False `extQ` postTcType `extQ` fixity `extQ` nameSet) = mzero
| otherwise = f . gmapT (everywhere stage f)
where nameSet = const (stage `elem` [Parser,TypeChecker]) :: NameSet -> Bool
postTcType = const (stage<TypeChecker) :: PostTcType -> Bool
fixity = const (stage<Renamer) :: GHC.Fixity -> Bool
-}
-- ---------------------------------------------------------------------
{-
-- | Apply a transformation everywhere in top-down manner
everywhere' :: (forall a. Data a => a -> a)
-> (forall a. Data a => a -> a)
-- Arguments of (.) are flipped compared to everywhere
everywhere' f = gmapT (everywhere' f) . f
-}
{-
-- | Apply a transformation everywhere in top-down manner
everywhere' :: (forall a. Data a => a -> a)
-> (forall a. Data a => a -> a)
-- Arguments of (.) are flipped compared to everywhere
everywhere' f = gmapT (everywhere' f) . f
-}
-- ---------------------------------------------------------------------
{-
-- | Monadic variation on everywhere
everywhereM :: Monad m => GenericM m -> GenericM m
-- Bottom-up order is also reflected in order of do-actions
everywhereM f x = do x' <- gmapM (everywhereM f) x
f x'
-}
-- | Monadic variation on everywhere
everywhereMStaged :: Monad m => Stage -> GenericM m -> GenericM m
-- Bottom-up order is also reflected in order of do-actions
everywhereMStaged stage f x
| (const False `extQ` postTcType `extQ` fixity `extQ` nameSet) x = return x
| otherwise = do x' <- gmapM (everywhereMStaged stage f) x
f x'
where nameSet = const (stage `elem` [Parser,TypeChecker]) :: NameSet -> Bool
postTcType = const (stage<TypeChecker) :: PostTcType -> Bool
fixity = const (stage<Renamer) :: GHC.Fixity -> Bool
{-
everywhereStaged stage f = f . gmapT (everywhere f)
| (const False `extQ` postTcType `extQ` fixity `extQ` nameSet) = mzero
| otherwise = f . gmapT (everywhere stage f)
where nameSet = const (stage `elem` [Parser,TypeChecker]) :: NameSet -> Bool
postTcType = const (stage<TypeChecker) :: PostTcType -> Bool
fixity = const (stage<Renamer) :: GHC.Fixity -> Bool
-}
|
RefactoringTools/HaRe
|
old/refactorer/GhcUtils.hs
|
bsd-3-clause
| 7,027
| 0
| 13
| 1,692
| 713
| 387
| 326
| 33
| 1
|
module Main where
import qualified MaybeHug
-- any type can be an instance of Huggable
instance MaybeHug.Huggable Int where
wantsHug n = True
-- a Cutie
data Cutie = Cutie { name :: String, wantsHug :: Bool }
-- let's make Cutie Huggable
instance MaybeHug.Huggable Cutie where
wantsHug = wantsHug
main :: IO ()
main = do
-- hug an Int
putStrLn $ MaybeHug.maybeHug (3::Int)
-- hug a cutie
putStrLn $ MaybeHug.maybeHug $ Cutie { name = "Brad", wantsHug = True }
-- this cutie doesn't want hugs
putStrLn $ MaybeHug.maybeHug $ Cutie { name = "Jen", wantsHug = False }
|
yurrriq/maybe-hugs
|
haskell/app/Main.hs
|
cc0-1.0
| 585
| 0
| 9
| 122
| 155
| 89
| 66
| 12
| 1
|
{-# LANGUAGE QuasiQuotes, TemplateHaskell, CPP, GADTs, TypeFamilies, OverloadedStrings, FlexibleContexts, EmptyDataDecls, FlexibleInstances, GeneralizedNewtypeDeriving, MultiParamTypeClasses #-}
module UniqueTest where
import Init
#ifndef WITH_NOSQL
import Control.Monad (void)
#endif
#ifdef WITH_NOSQL
mkPersist persistSettings [persistUpperCase|
#else
share [mkPersist sqlSettings, mkMigrate "uniqueMigrate"] [persistLowerCase|
#endif
TestNonNull
fieldA Int
UniqueTestNonNull fieldA
deriving Eq Show
TestNull
fieldA Int
fieldB Int Maybe
UniqueTestNull fieldA fieldB !force
deriving Eq Show
#ifndef WITH_NOSQL
TestCheckmark
name Text
value Text
active Checkmark nullable
UniqueTestCheckmark name active !force
deriving Eq Show
#endif
|]
#ifdef WITH_NOSQL
cleanDB :: (MonadIO m, PersistQuery backend, PersistEntityBackend TestNonNull ~ backend) => ReaderT backend m ()
cleanDB = do
deleteWhere ([] :: [Filter TestNonNull])
deleteWhere ([] :: [Filter TestNull])
db :: Action IO () -> Assertion
db = db' cleanDB
#endif
specs :: Spec
specs = describe "uniqueness constraints" $
#ifdef WITH_NOSQL
return ()
#else
do
it "are respected for non-nullable Ints" $ do
let ins = insert . TestNonNull
(db $ void $ ins 1 >> ins 2)
(db $ void $ ins 1 >> ins 2 >> ins 1) `shouldThrow` anyException
(db $ void $ ins 1 >>= \k -> ins 2 >> delete k >> ins 1)
it "are respected for nullable Ints" $ do
let ins a b = insert $ TestNull a b
ctx = ins 1 Nothing >> ins 1 Nothing >> ins 1 Nothing >>
ins 1 (Just 3) >> ins 1 (Just 4)
(db $ void ctx)
(db $ void $ ctx >> ins 1 (Just 3)) `shouldThrow` anyException
(db $ void $ ctx >> ins 1 (Just 4)) `shouldThrow` anyException
(db $ void $ ctx >>= \k -> delete k >> ins 1 (Just 4))
it "work for Checkmark" $ do
let ins k v a = insert $ TestCheckmark k v a
ctx = ins "name" "John" Inactive
>> ins "name" "Stewart" Inactive
>> ins "name" "Doroty" Active
>> ins "color" "blue" Inactive
(db $ void ctx)
(db $ void $ ctx >> ins "name" "Melissa" Active) `shouldThrow` anyException
(db $ void $ ctx >> ins "name" "Melissa" Inactive)
(db $ void $ ctx >>= flip update [TestCheckmarkActive =. Active])
(db $ void $ do
void ctx
updateWhere [TestCheckmarkName ==. "name"]
[TestCheckmarkActive =. Inactive]
ins "name" "Melissa" Active)
#endif
|
nakaji-dayo/persistent
|
persistent-test/UniqueTest.hs
|
mit
| 2,577
| 0
| 10
| 692
| 169
| 93
| 76
| 36
| 1
|
{-# LANGUAGE OverloadedStrings, DataKinds #-}
module MethodSpec where
import Control.Monad
import qualified Data.Aeson as J
import qualified Language.LSP.Types as J
import Test.Hspec
import qualified Data.Text as T
-- ---------------------------------------------------------------------
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "Method enum aeson instance consistency" diagnosticsSpec
-- ---------------------------------------------------------------------
clientMethods :: [T.Text]
clientMethods = [
-- General
"initialize"
,"initialized"
,"shutdown"
,"exit"
,"$/cancelRequest"
-- Workspace
,"workspace/didChangeConfiguration"
,"workspace/didChangeWatchedFiles"
,"workspace/symbol"
,"workspace/executeCommand"
-- Document
,"textDocument/didOpen"
,"textDocument/didChange"
,"textDocument/willSave"
,"textDocument/willSaveWaitUntil"
,"textDocument/didSave"
,"textDocument/didClose"
,"textDocument/completion"
,"completionItem/resolve"
,"textDocument/hover"
,"textDocument/signatureHelp"
,"textDocument/references"
,"textDocument/documentHighlight"
,"textDocument/documentSymbol"
,"textDocument/formatting"
,"textDocument/rangeFormatting"
,"textDocument/onTypeFormatting"
,"textDocument/definition"
,"textDocument/codeAction"
,"textDocument/codeLens"
,"codeLens/resolve"
,"textDocument/documentLink"
,"documentLink/resolve"
,"textDocument/rename"
,"textDocument/prepareRename"
]
serverMethods :: [T.Text]
serverMethods = [
-- Window
"window/showMessage"
,"window/showMessageRequest"
,"window/logMessage"
,"telemetry/event"
-- Client
,"client/registerCapability"
,"client/unregisterCapability"
-- Workspace
,"workspace/applyEdit"
-- Document
,"textDocument/publishDiagnostics"
]
diagnosticsSpec :: Spec
diagnosticsSpec = do
describe "Client Methods" $ do
it "maintains roundtrip consistency" $ do
forM_ clientMethods $ \m -> do
(J.toJSON <$> (J.fromJSON (J.String m) :: J.Result (J.SomeClientMethod)))
`shouldBe` (J.Success $ J.String m)
describe "Server Methods" $ do
it "maintains roundtrip consistency" $ do
forM_ serverMethods $ \m -> do
(J.toJSON <$> (J.fromJSON (J.String m) :: J.Result (J.SomeServerMethod)))
`shouldBe` (J.Success $ J.String m)
-- ---------------------------------
|
alanz/haskell-lsp
|
lsp/test/MethodSpec.hs
|
mit
| 2,413
| 0
| 24
| 393
| 438
| 256
| 182
| 68
| 1
|
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, RecordWildCards,
QuasiQuotes, TemplateHaskell #-}
module Main where
import Prelude hiding (product)
import Control.Monad.IO.Class (liftIO)
import qualified Database.Persist.Sqlite as Db
import Network.HTTP.Types
import Network.Wai.Middleware.RequestLogger
import Network.Wai.Middleware.Static
import Web.Scotty
import Control.Applicative ((<$>), (<*>))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Models
main :: IO()
main = do
Db.runSqlite "my.db" $ Db.runMigration migrateAll
-- liftIO $ Db.runSqlite "example.db" insertInitialData
Db.withSqlitePool "my.db" 10 $ \pool ->
scotty 3000 $ do
middleware logStdoutDev
middleware $ staticPolicy (noDots >-> addBase "public")
get "/" $
redirect "index.html"
<% _.each(entities, function (entity) { %>
get "/<%= baseName %>/<%= pluralize(entity.name) %>" $ do
(<%= pluralize(entity.name) %> :: [Db.Entity <%= _.capitalize(entity.name) %>]) <-
liftIO $ flip Db.runSqlPersistMPool pool $ Db.selectList [] []
json <%= pluralize(entity.name) %>
get "/<%= baseName %>/<%= pluralize(entity.name) %>/:id" $ do
(id :: Integer) <- param "id"
let key :: Db.Key <%= _.capitalize(entity.name) %> = Db.Key (Db.PersistInt64 $ fromIntegral id)
(<%= entity.name %> :: Maybe <%= _.capitalize(entity.name) %>) <-
liftIO $ flip Db.runSqlPersistMPool pool $ Db.get $ key
case <%= entity.name %> of
Just e -> do setHeader "Access-Control-Allow-Origin" "*"
json $ Db.Entity key e
Nothing -> status notFound404
post "/<%= baseName %>/<%= pluralize(entity.name) %>" $ do
e :: <%= _.capitalize(entity.name) %> <- jsonData
id <- liftIO $ flip Db.runSqlPersistMPool pool $ Db.insert e
json $ Db.Entity id e
put "/<%= baseName %>/<%= pluralize(entity.name) %>/:id" $ do
(id :: Integer) <- param "id"
let key :: Db.Key <%= _.capitalize(entity.name) %> = Db.Key (Db.PersistInt64 $ fromIntegral id)
e :: <%= _.capitalize(entity.name) %> <- jsonData
(<%= entity.name %> :: Maybe <%= _.capitalize(entity.name) %>) <-
liftIO $ flip Db.runSqlPersistMPool pool $ Db.get $ key
case <%= entity.name %> of
Just _ -> do liftIO $ flip Db.runSqlPersistMPool pool $ Db.replace key $ e
json $ Db.Entity key e
Nothing -> status notFound404
delete "/<%= baseName %>/<%= pluralize(entity.name) %>/:id" $ do
(id :: Integer) <- param "id"
let key :: Db.Key <%= _.capitalize(entity.name) %> = Db.Key (Db.PersistInt64 $ fromIntegral id)
(<%= entity.name %> :: Maybe <%= _.capitalize(entity.name) %>) <-
liftIO $ flip Db.runSqlPersistMPool pool $ Db.get $ key
case <%= entity.name %> of
Just _ -> do liftIO $ flip Db.runSqlPersistMPool pool $ Db.delete $ key
status noContent204
Nothing -> status notFound404
<% }); %>
notFound $ do
status notFound404
html $ "<h1>Not found :(</h1>"
|
rayokota/generator-angular-scotty
|
app/templates/src/_Main.hs
|
mit
| 3,285
| 37
| 14
| 841
| 1,021
| 535
| 486
| -1
| -1
|
import Drawing
import Geometry
main = drawPicture myPicture
myPicture points =
drawLine (a,b) &
drawLine (c,d) &
drawLabels [a,b,c,d,e] ["A","B","C","D","E"]&
message $ "Perpendicular Lines"
where [a,b] = take 2 points
[c,d] = circle_circle (a,b) (b,a)
[e] = line_line (a,b) (c,d)
|
alphalambda/k12math
|
contrib/MHills/GeometryLessons/code/teacher/key_lesson5b.hs
|
mit
| 333
| 3
| 10
| 92
| 167
| 94
| 73
| 11
| 1
|
{-# LANGUAGE OverloadedStrings #-}
--------
--
-- Module: Quark.Window.TitleBar
-- Author: Stefan Peterson
-- License: MIT License
--
-- Maintainer: Stefan Peterson (stefan.j.peterson@gmail.com)
-- Stability: Stable
-- Portability: Unknown
--
--------
--
-- Module for functions related to the title bar
--
--------
module Quark.Window.TitleBar ( setTitle ) where
import Quark.Frontend.HSCurses ( Window ( TitleBar )
, setTextColor
, mvAddString
, move
, refresh
, hideCursor )
import Quark.Colors
import Quark.Helpers
import Quark.Types
setTitle :: Window -> String -> IO ()
setTitle w path = do
setTextColor w titleBarPair
mvAddString w 0 0 (fixToLenPadMid c leftText suffix ' ')
move w 0 0
hideCursor
refresh w
where
(TitleBar _ (_, c)) = w
leftText = prefix ++ (trimPathHead k path)
k = (c - length prefix - length suffix)
prefix = "quark - "
suffix = " 0.0.1a "
|
sjpet/quark
|
src/Quark/Window/TitleBar.hs
|
mit
| 1,086
| 0
| 10
| 358
| 223
| 126
| 97
| 23
| 1
|
import Distribution.Simple
import Distribution.Simple.LocalBuildInfo
import Distribution.PackageDescription
import System.Cmd
import System.Directory
import GHC.IO.Exception
main = defaultMainWithHooks (simpleUserHooks { postBuild = buildLibrary
, postClean = cleanLibrary })
where
buildLibrary _ _ pkg info = do
putStrLn "Compiling standard library modules..."
cwd <- getCurrentDirectory
setCurrentDirectory $ cwd ++ "/Std"
code <- system "make"
case code of
ExitFailure _ -> fail "Build failed."
ExitSuccess -> putStrLn "Build succeeded."
cleanLibrary _ _ pkg info = do
putStrLn "Cleaning standard library modules..."
cwd <- getCurrentDirectory
setCurrentDirectory $ cwd ++ "/Std"
code <- system "make clean"
case code of
ExitFailure _ -> fail "Build failed."
ExitSuccess -> putStrLn "Build succeeded."
|
rfw/castor
|
Setup.hs
|
mit
| 990
| 1
| 10
| 288
| 216
| 102
| 114
| 24
| 3
|
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-}
--------------------------------------------------------------------
-- |
-- Module : Network.Curl.Types
-- Copyright : (c) Galois Inc 2007-2009
-- License : BSD3
--
-- Maintainer: Sigbjorn Finne <sof@galois.com>
-- Stability : provisional
-- Portability: portable
--
-- Basic set of types for the Haskell curl binding, including the
-- @Curl@ handle type which holds the C library stateful connection
-- handle along with a set of cleanup actions tht should be performed
-- upon shutting down the curl session.
--
--------------------------------------------------------------------
module Network.Shpider.Curl.Types
( CurlH, URLString, Port, Long, LLong, Slist_
, Curl, curlPrim, mkCurl, mkCurlWithCleanup
, OptionMap, shareCleanup, runCleanup, updateCleanup
, manual_cleanup , mkCurl_no_cleanup
) where
import Network.Shpider.Curl.Debug
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.Storable
import Data.Word
import Control.Concurrent
import Control.Monad.Fix(mfix)
import Data.Maybe(fromMaybe)
import qualified Data.IntMap as M
import Data.IORef
import System.IO
data Curl_
type CurlH = Ptr Curl_
type URLString = String
type Port = Long
type Long = Word32
type LLong = Word64
data Slist_
data Curl = Curl
{ curlH :: MVar (ForeignPtr Curl_) -- libcurl is not thread-safe.
, curlCleanup :: IORef OptionMap -- deallocate Haskell curl data
}
-- | Execute a "primitve" curl operation.
-- NOTE: See warnings about the use of 'withForeginPtr'.
curlPrim :: Curl -> (IORef OptionMap -> CurlH -> IO a) -> IO a
curlPrim c f = withMVar (curlH c) $ \ h ->
withForeignPtr h $ f $ curlCleanup c
-- | Allocates a Haskell handle from a C handle.
-- | No garbage collection so cookies are written deterministically
mkCurl_no_cleanup :: CurlH -> IO Curl
mkCurl_no_cleanup h = do
debug "ALLOC: CURL"
fh <- newForeignPtr_ h
v1 <- newMVar fh
v2 <- newIORef om_empty
let new_h = Curl { curlH = v1, curlCleanup = v2 }
return new_h
-- | Allocates a Haskell handle from a C handle.
mkCurl :: CurlH -> IO Curl
mkCurl h =
mkCurlWithCleanup h om_empty
-- | Allocates a Haskell handle from a C handle.
mkCurlWithCleanup :: CurlH -> OptionMap -> IO Curl
mkCurlWithCleanup h clean = do
debug "ALLOC: CURL"
fh <- newForeignPtr_ h
v1 <- newMVar fh
v2 <- newIORef clean
let new_h = Curl { curlH = v1, curlCleanup = v2 }
fin <- mkIOfin $ do debug "FREE: CURL"
runCleanup v2
withForeignPtr fh easy_cleanup
addForeignPtrFinalizer fin fh
return new_h
-- Manually cleanup a curl instance, writing cookies etc.
manual_cleanup curl = do
fh <- readMVar $ curlH curl
debug "FREE: CURL"
runCleanup $ curlCleanup curl
withForeignPtr fh easy_cleanup
-- Admin code for cleaning up marshalled data.
-- Note that these functions assume that they are running atomically,
-- so access to them should be protected by a lock.
--------------------------------------------------------------------------------
runCleanup :: IORef OptionMap -> IO ()
runCleanup r = do m <- readIORef r
om_cleanup m
writeIORef r om_empty
shareCleanup :: IORef OptionMap -> IO OptionMap
shareCleanup r = do old <- readIORef r
new <- om_dup old
writeIORef r new
return new
updateCleanup :: IORef OptionMap -> Int -> IO () -> IO ()
updateCleanup r option act = writeIORef r =<< om_set option act =<< readIORef r
-- Maps that associate curl options with IO actions to
-- perform cleanup for them.
--------------------------------------------------------------------------------
type OptionMap = M.IntMap (IO ())
-- | An empty option map.
om_empty :: OptionMap
om_empty = M.empty
-- | Set the IO action for an option,
-- executing the previvous action, if there was one.
om_set :: Int -> IO () -> OptionMap -> IO OptionMap
om_set opt new_act old_map =
do fromMaybe (return ()) old_act
return new_map
where
(old_act,new_map) = M.insertLookupWithKey (\_ a _ -> a) opt new_act old_map
-- | Execute all IO actions in the map.
om_cleanup :: OptionMap -> IO ()
om_cleanup m = sequence_ (M.elems m)
-- | Replace the actions in a map, with actions that
-- will only be executed the second time they are invoked.
om_dup :: OptionMap -> IO OptionMap
om_dup old_map = M.fromList `fmap` mapM dup (M.assocs old_map)
where dup (x,old_io) = do new_io <- shareIO old_io
return (x,new_io)
-- Share a cleanup action. When we share cleanup duty between two handles
-- we need to ensure that the first handle to perform the cleanup will do
-- nothing (because the other handle still needs the resources).
shareIO :: IO () -> IO (IO ())
shareIO act =
do v <- newMVar False
let new_act = do b <- takeMVar v
if b then act else putMVar v True
return new_act
--------------------------------------------------------------------------------
-- FFI for inalizers.
-- | Make a finalizer from an IO action.
mkIOfin :: IO a -> IO (FinalizerPtr b)
mkIOfin m = mfix (\ptr -> ioFinalizer (m >> freeHaskellFunPtr ptr))
foreign import ccall
"curl/curl.h curl_easy_cleanup" easy_cleanup :: CurlH -> IO ()
foreign import ccall "wrapper"
ioFinalizer :: IO () -> IO (FinalizerPtr a)
|
elginer/shpider
|
Network/Shpider/Curl/Types.hs
|
mit
| 5,461
| 0
| 13
| 1,215
| 1,201
| 618
| 583
| -1
| -1
|
module Geometry
( sphereVolume
, sphereArea
, cubeVolume
, cubeArea
, cuboidArea
, cuboidVolume
) where
sphereVolume :: Float -> Float
sphereVolume radius = (4.0 / 3.0) * pi * (radius ^ 3)
sphereArea :: Float -> Float
sphereArea radius = 4 * pi * (radius ^ 2)
cubeVolume :: Float -> Float
cubeVolume side = cuboidVolume side side side
cubeArea :: Float -> Float
cubeArea side = cuboidArea side side side
cuboidVolume :: Float -> Float -> Float -> Float
cuboidVolume a b c = rectArea a b * c
cuboidArea :: Float -> Float -> Float -> Float
cuboidArea a b c = reacArea a b * 2 + reacArea a c * 2 reacArea c b * 2
reacArea :: Float -> Float -> Float
reacArea a b = a * b
|
hackrole/learn_haskell
|
haskell-good/ch06/Geometry.hs
|
mit
| 675
| 0
| 9
| 143
| 270
| 141
| 129
| 21
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DeriveGeneric #-}
module StrawPoll.Types where
import Data.Time
import GHC.Generics
import Data.Aeson
import Data.Text
import Database.Persist as DB
import Database.Persist.TH
share [mkPersist sqlSettings { mpsGenerateLenses = True, mpsPrefixFields = False }, mkMigrate "migrateAll" ] [persistLowerCase|
Poll json
question Text
createdAt UTCTime Maybe default=CURRENT_TIME
deriving Show
deriving Eq
deriving Generic
PollOption json
pid PollId Maybe
option Text
deriving Show
deriving Eq
deriving Generic
PollAnswer json
questionId PollOptionId
answeredAt UTCTime default=CURRENT_TIME
ip Text Maybe
deriving Show
deriving Eq
deriving Generic
|]
emptyPoll = Poll "" Nothing
emptyOption = PollOption Nothing ""
|
cschneid/strawpollhs
|
src/shared/StrawPoll/Types.hs
|
mit
| 1,319
| 0
| 9
| 344
| 110
| 70
| 40
| 23
| 1
|
{-# OPTIONS #-}
-- ------------------------------------------------------------
module Holumbus.Crawler.Util
where
import Control.Applicative ( liftA2 )
import Data.List
import qualified Text.Regex.XMLSchema.String as RE
-- ------------------------------------------------------------
-- | create temp file name
mkTmpFile :: Int -> String -> Int -> String
mkTmpFile n s i = (s ++) . reverse . take n . (++ replicate n '0') . reverse . show $ i
-- ------------------------------------------------------------
-- | Simple predicate genertor for filtering of URIs
-- If the first predicate (isAllowed) holds and the second (isDenied) does not hold
-- the predicate holds. This can be used for constructing simple URL filters
simpleFollowRef :: (String -> Bool) -> (String -> Bool) -> (String -> Bool)
simpleFollowRef isAllowed isDenied
= isAllowed .&&. (not . isDenied)
where
(.&&.) = liftA2 (&&)
-- | A convenient function, that takes two lists of strings in regexp syntax,
-- The first list are the patterns for the allowed strings,
-- the second one for the patterns to deny the string.
-- Two regular expressions are build from these lists of strings,
-- and the string to be tested is matched against both regexes
simpleFollowRef' :: [String] -> [String] -> (String -> Bool)
simpleFollowRef' allowed denied
= simpleFollowRef allowed' denied'
where
mkAlt :: [String] -> String
mkAlt rs = "(" ++ intercalate "|" rs ++ ")"
allowed'
| null allowed = const True
| otherwise = match $ mkAlt allowed
denied'
| null denied = const False
| otherwise = match $ mkAlt denied
-- ------------------------------------------------------------
match :: String -> String -> Bool
match re = RE.matchRE (parseRE re)
sed :: (String -> String) -> String -> String -> String
sed edit re = parseRE re `seq` RE.sed edit re
split :: String -> String -> (String, String)
split re = parseRE re `seq` RE.split re
tokenize :: String -> String -> [String]
tokenize re = parseRE re `seq` RE.tokenize re
-- ------------------------------------------------------------
parseRE :: String -> RE.Regex
parseRE re = check . RE.parseRegex $ re
where
check re'
| RE.isZero re' = error $ "\nsyntax error in regexp: " ++ re ++ "\n" ++ RE.errRegex re'
| otherwise = re'
-- ------------------------------------------------------------
|
ichistmeinname/holumbus
|
src/Holumbus/Crawler/Util.hs
|
mit
| 2,994
| 0
| 11
| 1,053
| 569
| 303
| 266
| 35
| 1
|
module Handler.Home where
import Import
import qualified Database.Esqueleto as E
import qualified Data.Time.Format as Time
-- This is a handler function for the GET request method on the HomeR
-- resource pattern. All of your resource patterns are defined in
-- config/routes
--
-- The majority of the code you will write in Yesod lives in these handler
-- functions. You can spread them across multiple files if you are so
-- inclined, or create a single monolithic file.
getHomeR :: Handler Html
getHomeR = do
articles <- runDB $
E.select
$ E.from $ \(article `E.InnerJoin` language) -> do
E.on $ article E.^. ArticleLang E.==. language E.^. LanguageId
E.orderBy [ E.desc (article E.^. ArticleUpdated) ]
E.limit 5
return (article, language)
defaultLayout $ do
master <- getYesod
let settings = appSettings master
setTitle "Lambdar"
$(widgetFile "homepage")
|
builtinnya/lambdar-website
|
Handler/Home.hs
|
mit
| 932
| 0
| 16
| 208
| 199
| 105
| 94
| 18
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Pages where
import Data.Monoid
import Data.Time.Clock
import Data.Time.Format
import Prelude hiding (head)
import Text.Blaze.Html5
frontPage :: Int -> Int -> UTCTime -> Html
frontPage a b t = do
docType
head $ title "this is a front page!!"
body $ do
p "this is a paragraph!!"
p ("we got an integer: " <> toHtml a)
p ("and another: " <> toHtml b)
let time = formatTime defaultTimeLocale rfc822DateFormat t
p ("request was served at " <> toHtml time)
|
patrickt/blimp
|
Pages.hs
|
mit
| 580
| 0
| 13
| 171
| 156
| 78
| 78
| 17
| 1
|
module Example where
import Data.Serialize
import Network.Hstack
data AddRequest = AddRequest {
a :: Int,
b :: Int
} deriving Show
instance Serialize AddRequest where
put = f where
f r = do
put $ (a r)
put $ (b r)
get = do
a' <- get
b' <- get
return $ AddRequest a' b'
data AddResponse = AddResponse {
result :: Int
} deriving Show
instance Serialize AddResponse where
put = f where
f r = put $ (result r)
get = do
result' <- get
return $ AddResponse result'
d :: ServiceDescriptor AddRequest AddResponse
d = ServiceDescriptor "add"
|
davidhinkes/hstack
|
example/Example.hs
|
mit
| 594
| 0
| 12
| 161
| 209
| 109
| 100
| 27
| 1
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Language.PureScript.Binding.Dependency where
import Data.Monoid
import Data.Text.Lazy (Text)
import Data.Type.Bool
import Data.Proxy
import Language.PureScript.Binding.Class
import Data.Text.Lazy.Builder
data TList where
(:-) :: a -> TList -> TList
TNil :: TList
infixr 5 :-
type family Deps (a :: k) :: TList
class ConsDecl r (elem :: Bool) a where
consDecl :: p elem -> q a -> r -> r
instance ConsDecl r True a where
consDecl _ _ = id
instance HasPureScript a => ConsDecl Builder 'False a where
consDecl _ p r = dataDecl p <> singleton '\n' <> foreignDecl p <> singleton '\n' <> r
instance HasPureScript a => ConsDecl [Builder] 'False a where
consDecl _ p r = dataDecl p : foreignDecl p : r
type family Elem (a :: k) (as :: TList) :: Bool where
Elem a TNil = False
Elem a (a :- as) = True
Elem a (a' :- as) = Elem a as
type NotElem a b = Not (Elem a b)
type family (a :: TList) ++ (b :: TList) :: TList
type instance TNil ++ ys = ys
type instance (x :- xs) ++ ys = x :- xs ++ ys
type family Yet (done :: TList) (as :: TList) :: TList
type instance Yet done TNil = TNil
type instance Yet done (a :- as) = If (Elem a done) (Yet done as) (a :- Yet done as)
class Decls' r (b :: Bool) (ds :: TList) (as :: TList) where
decls' :: Proxy b -> Proxy ds -> Proxy as -> r
instance (Monoid r, ConsDecl r elm d) => Decls' r elm (d :- ds) TNil where
decls' _ _ _ = consDecl (Proxy :: Proxy elm) (Proxy :: Proxy d) mempty
type NextDecls r a as d ds =
Decls' r (Elem a (d :- ds)) (a :- d :- ds) (Yet (d :- ds) (as ++ Deps a))
instance (ConsDecl r elm d, NextDecls r a as d ds) => Decls' r elm (d :- ds) (a :- as) where
decls' _ _ _ =
consDecl (Proxy :: Proxy elm) (Proxy :: Proxy d) $
decls'
(Proxy :: Proxy (Elem a (d :- ds)))
(Proxy :: Proxy (a :- d :- ds))
(Proxy :: Proxy (Yet (d :- ds) (as ++ Deps a)))
type Decls r a = Decls' r False (a :- TNil) (Deps a)
type AllDecls r a as = Decls' r False (a :- TNil) (as ++ Deps a)
-- | convert to PureScript Declaration Strings.
--
-- @
-- decls (Proxy :: Proxy Type)
-- @
decls :: forall proxy a. Decls [Builder] a => proxy a -> [Builder]
decls _ = decls' (Proxy :: Proxy False) (Proxy :: Proxy (a :- TNil)) (Proxy :: Proxy (Deps a))
-- | convert to PureScript module String.
--
-- automatically include dependencies.
--
-- @
-- mkModule \"Module.Name\" (Proxy :: Proxy (TypeA :- TypeB :- TNil))
-- @
mkModule :: forall proxy a (as :: TList). AllDecls Builder a as
=> String -- ^ module name
-> proxy (a :- as) -> Text
mkModule modName _ = toLazyText $
fromString "module " <>
fromString modName <>
fromString " where\n\n" <>
fromString "import Data.JSON ()\n\n" <>
ds
where
ds = decls' (Proxy :: Proxy False) (Proxy :: Proxy (a :- TNil)) (Proxy :: Proxy (as ++ Deps a))
|
philopon/haskell-purescript-binding
|
Language/PureScript/Binding/Dependency.hs
|
mit
| 3,275
| 4
| 14
| 780
| 1,219
| 674
| 545
| 70
| 1
|
-- The solution of exercise 1.37
-- [a] An infinite continued fraction is an expression of the form:
--
-- N_1
-- f = -------------------------
-- N_2
-- D_1 + -------------------
-- N_3
-- D_2 + ------------
-- N_4
-- D_3 + -----
-- ...
--
-- As an example, one can show that the infinite continued fraction
-- expansion with the N_i and the D_i all equal to 1 produces 1 / \phi,
-- where \phi is the golden ratio (described in section 1.2.2). One way
-- to approximate an infinite continued fraction is to truncate the
-- expansion after a given number of terms. Such a truncation -- a
-- so-called `k-term finite continued fraction` -- has the form:
--
-- N_1
-- --------------------
-- N_2
-- D_1 + --------------
-- N_k
-- ... + -----
-- D_k
--
-- Suppose that `n` and `d` are procedures of one argument (the term
-- index i) that return the N_i and D_i of the terms of the continued
-- fraction. Define a procedure cont-frac such that evaluating `(cont-
-- frac n d k)` computes the value of the k-term finite continued
-- fraction. Check your procedure by approximating 1 / \phi using
--
-- (cont-frac (lambda (i) 1.0)
-- (lambda (i) 1.0)
-- k)
--
-- for successive values of `k`. How large must you make k in order to
-- get an approximation that is accurate to 4 decimal places?
--
-- [b] If your cont-frac procedure generates a recursive process, write
-- one that generates an iterative process. If it generates an
-- iterative process, write one that generates a recursive process.
--
-- -------- (above from SICP)
--
-- The `cont-frac` procedure as a recursive process
contFrac
:: (Eq a, Num a, Fractional b) =>
(a -> b) -> (a -> b) -> a -> b
contFrac n d k =
let iter counter =
(n counter) / (d counter + if k == counter
then 0
else iter (counter + 1))
in iter 1
-- The `cont-frac` procedure as a iterative process
contFracIter
:: (Eq a, Num a, Fractional b) =>
(a -> b) -> (a -> b) -> a -> b
contFracIter n d k =
let iter counter result
| counter == 0 = result
| otherwise = iter (counter - 1)
(n counter / (d counter + result))
in iter k 0
-- The recursive process to compute golden ratio
golden_ratio :: (Eq a, Num a, Fractional b) => a -> b
golden_ratio k =
contFrac (\x -> 1.0) (\x -> 1.0) k
-- The iterative process to compute golden ratio
golden_ratioIter :: (Eq a, Num a, Fractional b) => a -> b
golden_ratioIter k =
contFracIter (\x -> 1.0) (\x -> 1.0) k
--
-- At least 4 items needed to get an approximation that is accurate to 4
-- decimal places:
--
-- Input items k: 9
-- [ The exact value ] 0.6180339887498949
-- [ Result (iterative) ] 0.6181818181818182
-- [ Result (recursive) ] 0.6181818181818182
--
-- Input items k: 10
-- [ The exact value ] 0.6180339887498949
-- [ Result (iterative) ] 0.6179775280898876
-- [ Result (recursive) ] 0.6179775280898876
--
-- Input items k: 11
-- [ The exact value ] 0.6180339887498949
-- [ Result (iterative) ] 0.6180555555555556
-- [ Result (recursive) ] 0.6180555555555556
--
|
perryleo/sicp
|
ch1/sicpc1e37.hs
|
mit
| 3,539
| 0
| 15
| 1,153
| 452
| 266
| 186
| 24
| 2
|
-- {-# LANGUAGE TypeApplications #-}
-- :set -XTypeApplications
module Main_Original where
import Data.Char (isAlphaNum, isSpace)
newtype Password = Password String deriving Show
newtype Username = Username String deriving Show
newtype Error = Error String deriving Show
-- EITHER
checkPasswordLength' :: String -> Either String String
checkPasswordLength' password =
case (length password > 20 || length password < 4) of
True -> Left "Too long or short"
_ -> Right password
requireAlphaNum' :: String -> Either String String
requireAlphaNum' xs =
case (all isAlphaNum xs) of
True -> Right xs
_ -> Left "Not all characters are alpha-numeric"
cleanWhitespace' :: String -> Either String String
cleanWhitespace' "" = Left "Empty string"
cleanWhitespace' (x:xs) =
case (isSpace x) of
True -> cleanWhitespace' xs
False -> Right (x:xs)
validatePassword' :: String -> Either String String
validatePassword' password =
do
cleaned <- cleanWhitespace' password
cleanedAlpha <- requireAlphaNum' cleaned
checkPasswordLength' cleanedAlpha
validatePassword'' :: String -> Either String String
validatePassword'' password = cleanWhitespace' password >>= requireAlphaNum' >>= checkPasswordLength'
validatePassword''order :: String -> Either String String
validatePassword''order password = cleanWhitespace' password >>= checkPasswordLength' >>= requireAlphaNum'
-- TESTS
printTestResult :: Either String () -> IO ()
printTestResult r =
case r of
Left err -> putStrLn err
Right () -> putStrLn "All Tests Pass"
-- printTestResult (Left "foo")
-- printTestResult (Right ())
eq :: (Eq a, Show a) => Int -> a -> a -> Either String ()
eq n actual expected =
case (actual == expected) of
True -> Right ()
False -> Left (unlines
[ "Test " ++ show n
, " Expected: " ++ show expected
, " But got: " ++ show actual
])
-- test1 :: IO ()
-- test1 =
-- do
-- one <- eq 1 (checkPasswordLength' "") (Left "Too long or short")),
-- two <- eq 2 (checkPasswordLength' "julielovesbooks") (Right "julielovesbooks")),
-- three <- eq 3 (checkPasswordLength' "afasdfasdfasdfasdfasdfasdfasdf") (Left "Too long or short")),
-- four <- eq 4 (cleanWhitespace' " foo") (Right "foo")),
-- five <- eq 5 (cleanWhitespace' "foo") (Right "foo")),
-- six <- eq 6 (cleanWhitespace' "foo ") (Right "foo "))]
test2 :: IO ()
test2 = printTestResult $
(eq 1 (checkPasswordLength' "") (Left "Too long or short")) >>=
(\_ -> (eq 2 (checkPasswordLength' "julielovesbooks") (Right "julielovesbooks_")) >>=
(\_ -> (eq 3 (checkPasswordLength' "afasdfasdfasdfasdfasdfasdfasdf") (Left "Too long or short"))))
-- eq 2 (checkPasswordLength' "julielovesbooks") (Right "julielovesbooks")
-- eq 3 (checkPasswordLength' "afasdfasdfasdfasdfasdfasdfasdf") (Left "Too long or short")
-- eq 4 (cleanWhitespace' " foo") (Right "foo")
-- eq 5 (cleanWhitespace' "foo") (Right "foo")
-- eq 6 (cleanWhitespace' "foo ") (Right "foo ")
-- *Main> :kind []
-- [] :: * -> *
-- *Main> [] >>= \_ -> []
-- []
-- *Main> [] >>= \x -> [x]
-- []
-- *Main> [2] >>= \x -> [x]
-- [2]
-- *Main> [2] >>= \x -> [3,x]
-- [3,2]
-- *Main> Just 4 >>= \x -> Just (3 + x)
-- Just 7
test :: IO ()
test = printTestResult $
do
eq 1 (checkPasswordLength' "") (Left "Too long or short")
eq 2 (checkPasswordLength' "julielovesbooks") (Right "julielovesbooks")
eq 3 (checkPasswordLength' "afasdfasdfasdfasdfasdfasdfasdf") (Left "Too long or short")
eq 4 (cleanWhitespace' " foo") (Right "foo")
eq 5 (cleanWhitespace' "foo") (Right "foo")
eq 6 (cleanWhitespace' "foo ") (Right "foo ")
-- what is do doing here?
-- do is syntax-sugar for >>=
-- but we're ignoring return values... right?
-- so how is this catching failures?
-- because >>= is itself catching the LAST item passing or an intermediate test passing?
-- MAYBE
checkPasswordLength :: String -> Maybe String
checkPasswordLength password =
case (length password > 20 || length password < 4) of
True -> Nothing
_ -> Just password
requireAlphaNum :: String -> Maybe String
requireAlphaNum xs =
case (all isAlphaNum xs) of
True -> Just xs
_ -> Nothing
cleanWhitespace :: String -> Maybe String
cleanWhitespace "" = Nothing
cleanWhitespace (x:xs) =
case (isSpace x) of
True -> cleanWhitespace xs
False -> Just (x:xs)
checkAllThree :: String -> Maybe String
checkAllThree password =
case cleanWhitespace password of
Just cleaned ->
case requireAlphaNum cleaned of
Just cleanedAlpha ->
case checkPasswordLength cleanedAlpha of
Just cleanAlphaSized -> Just cleanAlphaSized
_ -> Nothing
_ -> Nothing
_ -> Nothing
checkAllThreeAgain :: String -> Maybe String
checkAllThreeAgain password =
do
cleaned <- cleanWhitespace password
cleanedAlpha <- requireAlphaNum cleaned
checkPasswordLength cleanedAlpha
checkAllThreeAgain' :: String -> Maybe String
checkAllThreeAgain' password =
cleanWhitespace password >>= requireAlphaNum >>= checkPasswordLength
-- *Main> :type (>>=) @IO @String
-- exercise: convert this to do syntax:
reverseLine :: IO ()
-- reverseLine = getLine >>= (print . reverse)
reverseLine =
do
line <- getLine
(print . reverse) line
bindMaybe :: Maybe a -> (a -> Maybe b) -> Maybe b
bindMaybe Nothing _ = Nothing
bindMaybe (Just x) f = f x
-- *Main> bindMaybe Nothing (\x -> Just x)
-- Nothing
-- *Main> bindMaybe (Just 1) (\x -> Just (x + 2))
-- Just 3
data StringOrValue a = Str String | Val a deriving Show
bindStringOrValue
:: StringOrValue a
-> (a -> StringOrValue b)
-> StringOrValue b
bindStringOrValue (Str s) f = (Str s)
bindStringOrValue (Val x) f = f x
-- bindStringOrValue (Str "foo") (\x -> (Str "bar"))
-- bindStringOrValue (Str "foo") (\x -> (Val x))
-- bindStringOrValue (Val 1) (\x -> (Str "bar"))
-- bindStringOrValue (Val 1) (\x -> (Val (x + 1)))
main_Original :: IO ()
main_Original =
do
putStr "Please enter a password\n> "
password <- getLine
print (requireAlphaNum password)
-- print (checkPasswordLength password && requireAlphaNum password)
|
brodyberg/Notes
|
FindingSuccessAndFailure/validation-book/lib/Main_Original.hs
|
mit
| 6,235
| 0
| 14
| 1,325
| 1,407
| 712
| 695
| 115
| 4
|
lucky :: (Integral a) => a -> String
lucky 7 = "LUCKY NUMBER SEVEN!!!"
lucky x = "Sorry, you're out of luck, pal"
factorial :: (Integral a) => a -> a
factorial 0 = 1
factorial n = n * factorial (n - 1)
addVectors :: (Integral a) => (a, a) -> (a, a) -> (a, a)
addVectors (x1, y1) (x2, y2) = (x1 + y1, x2 + y2)
tell :: (Show a) => [a] -> String
tell [] = "The list is empty"
tell (x:[]) = "The list has one element: " ++ show x ++ "."
tell (x:y:[]) = "The list has two elements: " ++ show x ++ " and " ++ show y ++ "."
tell (x:y:z:[]) = "The list has three elements: " ++ show x ++ " and " ++ show y ++ " and " ++ show z ++ "."
tell (x:y:_) = "The list has a whole bunch of elements."
length' :: (Num b) => [a] -> b
length' [] = 0
length' (_:xs) = 1 + length' xs
sum' :: (Num a) => [a] -> a
sum' [] = 0
sum' (x:xs) = x + sum' xs
myCompare :: (Ord a) => a -> a -> Ordering
a `myCompare` b
| a > b = GT
| a == b = EQ
| otherwise = LT
bmiTell :: (RealFloat a) => a -> a -> String
bmiTell weight height
| bmi <= 18.5 = "Underweight"
| bmi <= 25.0 = "Normal"
| bmi <= 30.0 = "Overweight"
| otherwise = ":("
where bmi = weight / height ^ 2
|
diminishedprime/.org
|
reading-list/learn_you_a_haskell/syntax_in_functions.hs
|
mit
| 1,165
| 0
| 11
| 301
| 603
| 312
| 291
| 32
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Collab.Test.ParseTests
( tests
) where
import Test.HUnit
import Collab.Parse
tests = TestList
[ TestCase $ ("", "", "") @=? parseMessage ""
, TestCase $ ("foo", "", "") @=? parseMessage "foo"
, TestCase $ ("foo", "bar", "") @=? parseMessage "foo@bar"
, TestCase $ ("foo", "", "[]") @=? parseMessage "foo[]"
, TestCase $ ("foo", "bar", "[]") @=? parseMessage "foo@bar[]"
, TestCase $ ("foo", "bar", "{}") @=? parseMessage "foo@bar{}"
, TestCase $ ("foo", "bar", "{{[]}}") @=? parseMessage "foo@bar{{[]}}"
]
|
dennis84/collab-haskell
|
test/Collab/Test/ParseTests.hs
|
mit
| 613
| 0
| 9
| 146
| 192
| 110
| 82
| 13
| 1
|
module Homepage
(
module Homepage.Handlers
, module Homepage.Types
)
where
import Homepage.Handlers
import Homepage.Types
|
gregorycollins/homepage
|
src/Homepage.hs
|
gpl-2.0
| 125
| 0
| 5
| 17
| 28
| 18
| 10
| 6
| 0
|
module Text.Pandoc.Readers.DocBook ( readDocBook ) where
import Data.Char (toUpper)
import Text.Pandoc.Shared (safeRead)
import Text.Pandoc.Options
import Text.Pandoc.Definition
import Text.Pandoc.Builder
import Text.XML.Light
import Text.Pandoc.Compat.TagSoupEntity (lookupEntity)
import Data.Either (rights)
import Data.Generics
import Data.Monoid
import Data.Char (isSpace)
import Control.Monad.State
import Control.Applicative ((<$>))
import Data.List (intersperse)
import Data.Maybe (fromMaybe)
import Text.TeXMath (readMathML, writeTeX)
import Text.Pandoc.Error (PandocError)
import Text.Pandoc.Compat.Except
import Data.Default
import Data.Foldable (asum)
{-
List of all DocBook tags, with [x] indicating implemented,
[o] meaning intentionally left unimplemented (pass through):
[o] abbrev - An abbreviation, especially one followed by a period
[x] abstract - A summary
[o] accel - A graphical user interface (GUI) keyboard shortcut
[x] ackno - Acknowledgements in an Article
[o] acronym - An often pronounceable word made from the initial
[o] action - A response to a user event
[o] address - A real-world address, generally a postal address
[ ] affiliation - The institutional affiliation of an individual
[ ] alt - Text representation for a graphical element
[o] anchor - A spot in the document
[x] answer - An answer to a question posed in a QandASet
[x] appendix - An appendix in a Book or Article
[x] appendixinfo - Meta-information for an Appendix
[o] application - The name of a software program
[x] area - A region defined for a Callout in a graphic or code example
[x] areaset - A set of related areas in a graphic or code example
[x] areaspec - A collection of regions in a graphic or code example
[ ] arg - An argument in a CmdSynopsis
[x] article - An article
[x] articleinfo - Meta-information for an Article
[ ] artpagenums - The page numbers of an article as published
[x] attribution - The source of a block quote or epigraph
[ ] audiodata - Pointer to external audio data
[ ] audioobject - A wrapper for audio data and its associated meta-information
[x] author - The name of an individual author
[ ] authorblurb - A short description or note about an author
[x] authorgroup - Wrapper for author information when a document has
multiple authors or collabarators
[x] authorinitials - The initials or other short identifier for an author
[o] beginpage - The location of a page break in a print version of the document
[ ] bibliocoverage - The spatial or temporal coverage of a document
[x] bibliodiv - A section of a Bibliography
[x] biblioentry - An entry in a Bibliography
[x] bibliography - A bibliography
[ ] bibliographyinfo - Meta-information for a Bibliography
[ ] biblioid - An identifier for a document
[o] bibliolist - A wrapper for a set of bibliography entries
[ ] bibliomisc - Untyped bibliographic information
[x] bibliomixed - An entry in a Bibliography
[ ] bibliomset - A cooked container for related bibliographic information
[ ] biblioref - A cross reference to a bibliographic entry
[ ] bibliorelation - The relationship of a document to another
[ ] biblioset - A raw container for related bibliographic information
[ ] bibliosource - The source of a document
[ ] blockinfo - Meta-information for a block element
[x] blockquote - A quotation set off from the main text
[x] book - A book
[x] bookinfo - Meta-information for a Book
[x] bridgehead - A free-floating heading
[x] callout - A “called out” description of a marked Area
[x] calloutlist - A list of Callouts
[x] caption - A caption
[x] caution - A note of caution
[x] chapter - A chapter, as of a book
[x] chapterinfo - Meta-information for a Chapter
[ ] citation - An inline bibliographic reference to another published work
[ ] citebiblioid - A citation of a bibliographic identifier
[ ] citerefentry - A citation to a reference page
[ ] citetitle - The title of a cited work
[ ] city - The name of a city in an address
[x] classname - The name of a class, in the object-oriented programming sense
[ ] classsynopsis - The syntax summary for a class definition
[ ] classsynopsisinfo - Information supplementing the contents of
a ClassSynopsis
[ ] cmdsynopsis - A syntax summary for a software command
[ ] co - The location of a callout embedded in text
[x] code - An inline code fragment
[x] col - Specifications for a column in an HTML table
[x] colgroup - A group of columns in an HTML table
[ ] collab - Identifies a collaborator
[ ] collabname - The name of a collaborator
[ ] colophon - Text at the back of a book describing facts about its production
[x] colspec - Specifications for a column in a table
[x] command - The name of an executable program or other software command
[x] computeroutput - Data, generally text, displayed or presented by a computer
[ ] confdates - The dates of a conference for which a document was written
[ ] confgroup - A wrapper for document meta-information about a conference
[ ] confnum - An identifier, frequently numerical, associated with a conference for which a document was written
[ ] confsponsor - The sponsor of a conference for which a document was written
[ ] conftitle - The title of a conference for which a document was written
[x] constant - A programming or system constant
[ ] constraint - A constraint in an EBNF production
[ ] constraintdef - The definition of a constraint in an EBNF production
[ ] constructorsynopsis - A syntax summary for a constructor
[ ] contractnum - The contract number of a document
[ ] contractsponsor - The sponsor of a contract
[ ] contrib - A summary of the contributions made to a document by a
credited source
[ ] copyright - Copyright information about a document
[ ] coref - A cross reference to a co
[ ] corpauthor - A corporate author, as opposed to an individual
[ ] corpcredit - A corporation or organization credited in a document
[ ] corpname - The name of a corporation
[ ] country - The name of a country
[ ] database - The name of a database, or part of a database
[x] date - The date of publication or revision of a document
[ ] dedication - A wrapper for the dedication section of a book
[ ] destructorsynopsis - A syntax summary for a destructor
[ ] edition - The name or number of an edition of a document
[ ] editor - The name of the editor of a document
[x] email - An email address
[x] emphasis - Emphasized text
[x] entry - A cell in a table
[ ] entrytbl - A subtable appearing in place of an Entry in a table
[ ] envar - A software environment variable
[x] epigraph - A short inscription at the beginning of a document or component
note: also handle embedded attribution tag
[x] equation - A displayed mathematical equation
[ ] errorcode - An error code
[ ] errorname - An error name
[ ] errortext - An error message.
[ ] errortype - The classification of an error message
[ ] example - A formal example, with a title
[ ] exceptionname - The name of an exception
[ ] fax - A fax number
[ ] fieldsynopsis - The name of a field in a class definition
[x] figure - A formal figure, generally an illustration, with a title
[x] filename - The name of a file
[ ] firstname - The first name of a person
[ ] firstterm - The first occurrence of a term
[x] footnote - A footnote
[ ] footnoteref - A cross reference to a footnote (a footnote mark)
[x] foreignphrase - A word or phrase in a language other than the primary
language of the document
[x] formalpara - A paragraph with a title
[ ] funcdef - A function (subroutine) name and its return type
[ ] funcparams - Parameters for a function referenced through a function
pointer in a synopsis
[ ] funcprototype - The prototype of a function
[ ] funcsynopsis - The syntax summary for a function definition
[ ] funcsynopsisinfo - Information supplementing the FuncDefs of a FuncSynopsis
[x] function - The name of a function or subroutine, as in a
programming language
[x] glossary - A glossary
[x] glossaryinfo - Meta-information for a Glossary
[x] glossdef - A definition in a GlossEntry
[x] glossdiv - A division in a Glossary
[x] glossentry - An entry in a Glossary or GlossList
[x] glosslist - A wrapper for a set of GlossEntrys
[x] glosssee - A cross-reference from one GlossEntry to another
[x] glossseealso - A cross-reference from one GlossEntry to another
[x] glossterm - A glossary term
[ ] graphic - A displayed graphical object (not an inline)
Note: in DocBook v5 `graphic` is discarded
[ ] graphicco - A graphic that contains callout areas
Note: in DocBook v5 `graphicco` is discarded
[ ] group - A group of elements in a CmdSynopsis
[ ] guibutton - The text on a button in a GUI
[ ] guiicon - Graphic and/or text appearing as a icon in a GUI
[ ] guilabel - The text of a label in a GUI
[x] guimenu - The name of a menu in a GUI
[x] guimenuitem - The name of a terminal menu item in a GUI
[x] guisubmenu - The name of a submenu in a GUI
[ ] hardware - A physical part of a computer system
[ ] highlights - A summary of the main points of the discussed component
[ ] holder - The name of the individual or organization that holds a copyright
[o] honorific - The title of a person
[ ] html:form - An HTML form
[x] imagedata - Pointer to external image data (only `fileref` attribute
implemented but not `entityref` which would require parsing of the DTD)
[x] imageobject - A wrapper for image data and its associated meta-information
[ ] imageobjectco - A wrapper for an image object with callouts
[x] important - An admonition set off from the text
[x] index - An index
[x] indexdiv - A division in an index
[x] indexentry - An entry in an index
[x] indexinfo - Meta-information for an Index
[x] indexterm - A wrapper for terms to be indexed
[x] info - A wrapper for information about a component or other block. (DocBook v5)
[x] informalequation - A displayed mathematical equation without a title
[x] informalexample - A displayed example without a title
[ ] informalfigure - A untitled figure
[ ] informaltable - A table without a title
[ ] initializer - The initializer for a FieldSynopsis
[x] inlineequation - A mathematical equation or expression occurring inline
[ ] inlinegraphic - An object containing or pointing to graphical data
that will be rendered inline
[x] inlinemediaobject - An inline media object (video, audio, image, and so on)
[ ] interface - An element of a GUI
[ ] interfacename - The name of an interface
[ ] invpartnumber - An inventory part number
[ ] isbn - The International Standard Book Number of a document
[ ] issn - The International Standard Serial Number of a periodical
[ ] issuenum - The number of an issue of a journal
[x] itemizedlist - A list in which each entry is marked with a bullet or
other dingbat
[ ] itermset - A set of index terms in the meta-information of a document
[ ] jobtitle - The title of an individual in an organization
[x] keycap - The text printed on a key on a keyboard
[ ] keycode - The internal, frequently numeric, identifier for a key
on a keyboard
[x] keycombo - A combination of input actions
[ ] keysym - The symbolic name of a key on a keyboard
[ ] keyword - One of a set of keywords describing the content of a document
[ ] keywordset - A set of keywords describing the content of a document
[ ] label - A label on a Question or Answer
[ ] legalnotice - A statement of legal obligations or requirements
[ ] lhs - The left-hand side of an EBNF production
[ ] lineage - The portion of a person's name indicating a relationship to
ancestors
[ ] lineannotation - A comment on a line in a verbatim listing
[x] link - A hypertext link
[x] listitem - A wrapper for the elements of a list item
[x] literal - Inline text that is some literal value
[x] literallayout - A block of text in which line breaks and white space are
to be reproduced faithfully
[ ] lot - A list of the titles of formal objects (as tables or figures) in
a document
[ ] lotentry - An entry in a list of titles
[ ] manvolnum - A reference volume number
[x] markup - A string of formatting markup in text that is to be
represented literally
[ ] mathphrase - A mathematical phrase, an expression that can be represented
with ordinary text and a small amount of markup
[ ] medialabel - A name that identifies the physical medium on which some
information resides
[x] mediaobject - A displayed media object (video, audio, image, etc.)
[ ] mediaobjectco - A media object that contains callouts
[x] member - An element of a simple list
[x] menuchoice - A selection or series of selections from a menu
[ ] methodname - The name of a method
[ ] methodparam - Parameters to a method
[ ] methodsynopsis - A syntax summary for a method
[x] mml:math - A MathML equation
[ ] modespec - Application-specific information necessary for the
completion of an OLink
[ ] modifier - Modifiers in a synopsis
[ ] mousebutton - The conventional name of a mouse button
[ ] msg - A message in a message set
[ ] msgaud - The audience to which a message in a message set is relevant
[ ] msgentry - A wrapper for an entry in a message set
[ ] msgexplan - Explanatory material relating to a message in a message set
[ ] msginfo - Information about a message in a message set
[ ] msglevel - The level of importance or severity of a message in a message set
[ ] msgmain - The primary component of a message in a message set
[ ] msgorig - The origin of a message in a message set
[ ] msgrel - A related component of a message in a message set
[ ] msgset - A detailed set of messages, usually error messages
[ ] msgsub - A subcomponent of a message in a message set
[ ] msgtext - The actual text of a message component in a message set
[ ] nonterminal - A non-terminal in an EBNF production
[x] note - A message set off from the text
[ ] objectinfo - Meta-information for an object
[ ] olink - A link that addresses its target indirectly, through an entity
[ ] ooclass - A class in an object-oriented programming language
[ ] ooexception - An exception in an object-oriented programming language
[ ] oointerface - An interface in an object-oriented programming language
[x] option - An option for a software command
[x] optional - Optional information
[x] orderedlist - A list in which each entry is marked with a sequentially
incremented label
[ ] orgdiv - A division of an organization
[ ] orgname - The name of an organization other than a corporation
[ ] otheraddr - Uncategorized information in address
[ ] othercredit - A person or entity, other than an author or editor,
credited in a document
[ ] othername - A component of a persons name that is not a first name,
surname, or lineage
[ ] package - A package
[ ] pagenums - The numbers of the pages in a book, for use in a bibliographic
entry
[x] para - A paragraph
[ ] paramdef - Information about a function parameter in a programming language
[x] parameter - A value or a symbolic reference to a value
[ ] part - A division in a book
[ ] partinfo - Meta-information for a Part
[ ] partintro - An introduction to the contents of a part
[ ] personblurb - A short description or note about a person
[ ] personname - The personal name of an individual
[ ] phone - A telephone number
[ ] phrase - A span of text
[ ] pob - A post office box in an address
[ ] postcode - A postal code in an address
[x] preface - Introductory matter preceding the first chapter of a book
[ ] prefaceinfo - Meta-information for a Preface
[ ] primary - The primary word or phrase under which an index term should be
sorted
[ ] primaryie - A primary term in an index entry, not in the text
[ ] printhistory - The printing history of a document
[ ] procedure - A list of operations to be performed in a well-defined sequence
[ ] production - A production in a set of EBNF productions
[ ] productionrecap - A cross-reference to an EBNF production
[ ] productionset - A set of EBNF productions
[ ] productname - The formal name of a product
[ ] productnumber - A number assigned to a product
[x] programlisting - A literal listing of all or part of a program
[ ] programlistingco - A program listing with associated areas used in callouts
[x] prompt - A character or string indicating the start of an input field in
a computer display
[ ] property - A unit of data associated with some part of a computer system
[ ] pubdate - The date of publication of a document
[ ] publisher - The publisher of a document
[ ] publishername - The name of the publisher of a document
[ ] pubsnumber - A number assigned to a publication other than an ISBN or ISSN
or inventory part number
[x] qandadiv - A titled division in a QandASet
[o] qandaentry - A question/answer set within a QandASet
[o] qandaset - A question-and-answer set
[x] question - A question in a QandASet
[x] quote - An inline quotation
[ ] refclass - The scope or other indication of applicability of a
reference entry
[ ] refdescriptor - A description of the topic of a reference page
[ ] refentry - A reference page (originally a UNIX man-style reference page)
[ ] refentryinfo - Meta-information for a Refentry
[ ] refentrytitle - The title of a reference page
[ ] reference - A collection of reference entries
[ ] referenceinfo - Meta-information for a Reference
[ ] refmeta - Meta-information for a reference entry
[ ] refmiscinfo - Meta-information for a reference entry other than the title
and volume number
[ ] refname - The name of (one of) the subject(s) of a reference page
[ ] refnamediv - The name, purpose, and classification of a reference page
[ ] refpurpose - A short (one sentence) synopsis of the topic of a reference
page
[x] refsect1 - A major subsection of a reference entry
[x] refsect1info - Meta-information for a RefSect1
[x] refsect2 - A subsection of a RefSect1
[x] refsect2info - Meta-information for a RefSect2
[x] refsect3 - A subsection of a RefSect2
[x] refsect3info - Meta-information for a RefSect3
[x] refsection - A recursive section in a refentry
[x] refsectioninfo - Meta-information for a refsection
[ ] refsynopsisdiv - A syntactic synopsis of the subject of the reference page
[ ] refsynopsisdivinfo - Meta-information for a RefSynopsisDiv
[x] releaseinfo - Information about a particular release of a document
[ ] remark - A remark (or comment) intended for presentation in a draft
manuscript
[ ] replaceable - Content that may or must be replaced by the user
[ ] returnvalue - The value returned by a function
[ ] revdescription - A extended description of a revision to a document
[ ] revhistory - A history of the revisions to a document
[ ] revision - An entry describing a single revision in the history of the
revisions to a document
[ ] revnumber - A document revision number
[ ] revremark - A description of a revision to a document
[ ] rhs - The right-hand side of an EBNF production
[x] row - A row in a table
[ ] sbr - An explicit line break in a command synopsis
[x] screen - Text that a user sees or might see on a computer screen
[o] screenco - A screen with associated areas used in callouts
[o] screeninfo - Information about how a screen shot was produced
[ ] screenshot - A representation of what the user sees or might see on a
computer screen
[ ] secondary - A secondary word or phrase in an index term
[ ] secondaryie - A secondary term in an index entry, rather than in the text
[x] sect1 - A top-level section of document
[x] sect1info - Meta-information for a Sect1
[x] sect2 - A subsection within a Sect1
[x] sect2info - Meta-information for a Sect2
[x] sect3 - A subsection within a Sect2
[x] sect3info - Meta-information for a Sect3
[x] sect4 - A subsection within a Sect3
[x] sect4info - Meta-information for a Sect4
[x] sect5 - A subsection within a Sect4
[x] sect5info - Meta-information for a Sect5
[x] section - A recursive section
[x] sectioninfo - Meta-information for a recursive section
[x] see - Part of an index term directing the reader instead to another entry
in the index
[x] seealso - Part of an index term directing the reader also to another entry
in the index
[ ] seealsoie - A See also entry in an index, rather than in the text
[ ] seeie - A See entry in an index, rather than in the text
[x] seg - An element of a list item in a segmented list
[x] seglistitem - A list item in a segmented list
[x] segmentedlist - A segmented list, a list of sets of elements
[x] segtitle - The title of an element of a list item in a segmented list
[ ] seriesvolnums - Numbers of the volumes in a series of books
[ ] set - A collection of books
[ ] setindex - An index to a set of books
[ ] setindexinfo - Meta-information for a SetIndex
[ ] setinfo - Meta-information for a Set
[ ] sgmltag - A component of SGML markup
[ ] shortaffil - A brief description of an affiliation
[ ] shortcut - A key combination for an action that is also accessible through
a menu
[ ] sidebar - A portion of a document that is isolated from the main
narrative flow
[ ] sidebarinfo - Meta-information for a Sidebar
[x] simpara - A paragraph that contains only text and inline markup, no block
elements
[x] simplelist - An undecorated list of single words or short phrases
[ ] simplemsgentry - A wrapper for a simpler entry in a message set
[ ] simplesect - A section of a document with no subdivisions
[ ] spanspec - Formatting information for a spanned column in a table
[ ] state - A state or province in an address
[ ] step - A unit of action in a procedure
[ ] stepalternatives - Alternative steps in a procedure
[ ] street - A street address in an address
[ ] structfield - A field in a structure (in the programming language sense)
[ ] structname - The name of a structure (in the programming language sense)
[ ] subject - One of a group of terms describing the subject matter of a
document
[ ] subjectset - A set of terms describing the subject matter of a document
[ ] subjectterm - A term in a group of terms describing the subject matter of
a document
[x] subscript - A subscript (as in H2O, the molecular formula for water)
[ ] substeps - A wrapper for steps that occur within steps in a procedure
[x] subtitle - The subtitle of a document
[x] superscript - A superscript (as in x2, the mathematical notation for x
multiplied by itself)
[ ] surname - A family name; in western cultures the last name
[ ] svg:svg - An SVG graphic
[x] symbol - A name that is replaced by a value before processing
[ ] synopfragment - A portion of a CmdSynopsis broken out from the main body
of the synopsis
[ ] synopfragmentref - A reference to a fragment of a command synopsis
[ ] synopsis - A general-purpose element for representing the syntax of
commands or functions
[ ] systemitem - A system-related item or term
[ ] table - A formal table in a document
[ ] task - A task to be completed
[ ] taskprerequisites - The prerequisites for a task
[ ] taskrelated - Information related to a task
[ ] tasksummary - A summary of a task
[x] tbody - A wrapper for the rows of a table or informal table
[x] td - A table entry in an HTML table
[x] term - The word or phrase being defined or described in a variable list
[ ] termdef - An inline term definition
[ ] tertiary - A tertiary word or phrase in an index term
[ ] tertiaryie - A tertiary term in an index entry, rather than in the text
[ ] textdata - Pointer to external text data
[ ] textobject - A wrapper for a text description of an object and its
associated meta-information
[ ] tfoot - A table footer consisting of one or more rows
[x] tgroup - A wrapper for the main content of a table, or part of a table
[x] th - A table header entry in an HTML table
[x] thead - A table header consisting of one or more rows
[x] tip - A suggestion to the user, set off from the text
[x] title - The text of the title of a section of a document or of a formal
block-level element
[x] titleabbrev - The abbreviation of a Title
[x] toc - A table of contents
[x] tocback - An entry in a table of contents for a back matter component
[x] tocchap - An entry in a table of contents for a component in the body of
a document
[x] tocentry - A component title in a table of contents
[x] tocfront - An entry in a table of contents for a front matter component
[x] toclevel1 - A top-level entry within a table of contents entry for a
chapter-like component
[x] toclevel2 - A second-level entry within a table of contents entry for a
chapter-like component
[x] toclevel3 - A third-level entry within a table of contents entry for a
chapter-like component
[x] toclevel4 - A fourth-level entry within a table of contents entry for a
chapter-like component
[x] toclevel5 - A fifth-level entry within a table of contents entry for a
chapter-like component
[x] tocpart - An entry in a table of contents for a part of a book
[ ] token - A unit of information
[x] tr - A row in an HTML table
[ ] trademark - A trademark
[x] type - The classification of a value
[x] ulink - A link that addresses its target by means of a URL
(Uniform Resource Locator)
[x] uri - A Uniform Resource Identifier
[x] userinput - Data entered by the user
[x] varargs - An empty element in a function synopsis indicating a variable
number of arguments
[x] variablelist - A list in which each entry is composed of a set of one or
more terms and an associated description
[x] varlistentry - A wrapper for a set of terms and the associated description
in a variable list
[x] varname - The name of a variable
[ ] videodata - Pointer to external video data
[ ] videoobject - A wrapper for video data and its associated meta-information
[ ] void - An empty element in a function synopsis indicating that the
function in question takes no arguments
[ ] volumenum - The volume number of a document in a set (as of books in a set
or articles in a journal)
[x] warning - An admonition set off from the text
[x] wordasword - A word meant specifically as a word and not representing
anything else
[x] xref - A cross reference to another part of the document
[ ] year - The year of publication of a document
[x] ?asciidoc-br? - line break from asciidoc docbook output
-}
type DB = ExceptT PandocError (State DBState)
data DBState = DBState{ dbSectionLevel :: Int
, dbQuoteType :: QuoteType
, dbMeta :: Meta
, dbAcceptsMeta :: Bool
, dbBook :: Bool
, dbFigureTitle :: Inlines
, dbContent :: [Content]
} deriving Show
instance Default DBState where
def = DBState{ dbSectionLevel = 0
, dbQuoteType = DoubleQuote
, dbMeta = mempty
, dbAcceptsMeta = False
, dbBook = False
, dbFigureTitle = mempty
, dbContent = [] }
readDocBook :: ReaderOptions -> String -> Either PandocError Pandoc
readDocBook _ inp = (\blocks -> Pandoc (dbMeta st') (toList . mconcat $ blocks)) <$> bs
where (bs , st') = flip runState (def{ dbContent = tree }) . runExceptT . mapM parseBlock $ tree
tree = normalizeTree . parseXML . handleInstructions $ inp
-- We treat <?asciidoc-br?> specially (issue #1236), converting it
-- to <br/>, since xml-light doesn't parse the instruction correctly.
-- Other xml instructions are simply removed from the input stream.
handleInstructions :: String -> String
handleInstructions ('<':'?':'a':'s':'c':'i':'i':'d':'o':'c':'-':'b':'r':'?':'>':xs) = '<':'b':'r':'/':'>': handleInstructions xs
handleInstructions xs = case break (=='<') xs of
(ys, []) -> ys
([], '<':zs) -> '<' : handleInstructions zs
(ys, zs) -> ys ++ handleInstructions zs
getFigure :: Element -> DB Blocks
getFigure e = do
tit <- case filterChild (named "title") e of
Just t -> getInlines t
Nothing -> return mempty
modify $ \st -> st{ dbFigureTitle = tit }
res <- getBlocks e
modify $ \st -> st{ dbFigureTitle = mempty }
return res
-- normalize input, consolidating adjacent Text and CRef elements
normalizeTree :: [Content] -> [Content]
normalizeTree = everywhere (mkT go)
where go :: [Content] -> [Content]
go (Text (CData CDataRaw _ _):xs) = xs
go (Text (CData CDataText s1 z):Text (CData CDataText s2 _):xs) =
Text (CData CDataText (s1 ++ s2) z):xs
go (Text (CData CDataText s1 z):CRef r:xs) =
Text (CData CDataText (s1 ++ convertEntity r) z):xs
go (CRef r:Text (CData CDataText s1 z):xs) =
Text (CData CDataText (convertEntity r ++ s1) z):xs
go (CRef r1:CRef r2:xs) =
Text (CData CDataText (convertEntity r1 ++ convertEntity r2) Nothing):xs
go xs = xs
convertEntity :: String -> String
convertEntity e = maybe (map toUpper e) (:[]) (lookupEntity e)
-- convenience function to get an attribute value, defaulting to ""
attrValue :: String -> Element -> String
attrValue attr elt =
case lookupAttrBy (\x -> qName x == attr) (elAttribs elt) of
Just z -> z
Nothing -> ""
-- convenience function
named :: String -> Element -> Bool
named s e = qName (elName e) == s
--
acceptingMetadata :: DB a -> DB a
acceptingMetadata p = do
modify (\s -> s { dbAcceptsMeta = True } )
res <- p
modify (\s -> s { dbAcceptsMeta = False })
return res
checkInMeta :: Monoid a => DB () -> DB a
checkInMeta p = do
accepts <- dbAcceptsMeta <$> get
when accepts p
return mempty
addMeta :: ToMetaValue a => String -> a -> DB ()
addMeta field val = modify (setMeta field val)
instance HasMeta DBState where
setMeta field v s = s {dbMeta = setMeta field v (dbMeta s)}
deleteMeta field s = s {dbMeta = deleteMeta field (dbMeta s)}
isBlockElement :: Content -> Bool
isBlockElement (Elem e) = qName (elName e) `elem` blocktags
where blocktags = ["toc","index","para","formalpara","simpara",
"ackno","epigraph","blockquote","bibliography","bibliodiv",
"biblioentry","glossee","glosseealso","glossary",
"glossdiv","glosslist","chapter","appendix","preface",
"bridgehead","sect1","sect2","sect3","sect4","sect5","section",
"refsect1","refsect2","refsect3","refsection",
"important","caution","note","tip","warning","qandadiv",
"question","answer","abstract","itemizedlist","orderedlist",
"variablelist","article","book","table","informaltable",
"informalexample",
"screen","programlisting","example","calloutlist"]
isBlockElement _ = False
-- Trim leading and trailing newline characters
trimNl :: String -> String
trimNl = reverse . go . reverse . go
where go ('\n':xs) = xs
go xs = xs
-- meld text into beginning of first paragraph of Blocks.
-- assumes Blocks start with a Para; if not, does nothing.
addToStart :: Inlines -> Blocks -> Blocks
addToStart toadd bs =
case toList bs of
(Para xs : rest) -> para (toadd <> fromList xs) <> fromList rest
_ -> bs
-- function that is used by both mediaobject (in parseBlock)
-- and inlinemediaobject (in parseInline)
-- A DocBook mediaobject is a wrapper around a set of alternative presentations
getMediaobject :: Element -> DB Inlines
getMediaobject e = do
imageUrl <- case filterChild (named "imageobject") e of
Nothing -> return mempty
Just z -> case filterChild (named "imagedata") z of
Nothing -> return mempty
Just i -> return $ attrValue "fileref" i
let getCaption el = case filterChild (\x -> named "caption" x
|| named "textobject" x
|| named "alt" x) el of
Nothing -> return mempty
Just z -> mconcat <$> (mapM parseInline $ elContent z)
figTitle <- gets dbFigureTitle
let (caption, title) = if isNull figTitle
then (getCaption e, "")
else (return figTitle, "fig:")
liftM (image imageUrl title) caption
getBlocks :: Element -> DB Blocks
getBlocks e = mconcat <$> (mapM parseBlock $ elContent e)
parseBlock :: Content -> DB Blocks
parseBlock (Text (CData CDataRaw _ _)) = return mempty -- DOCTYPE
parseBlock (Text (CData _ s _)) = if all isSpace s
then return mempty
else return $ plain $ trimInlines $ text s
parseBlock (CRef x) = return $ plain $ str $ map toUpper x
parseBlock (Elem e) =
case qName (elName e) of
"toc" -> return mempty -- skip TOC, since in pandoc it's autogenerated
"index" -> return mempty -- skip index, since page numbers meaningless
"para" -> parseMixed para (elContent e)
"formalpara" -> do
tit <- case filterChild (named "title") e of
Just t -> (para . strong . (<> str ".")) <$>
getInlines t
Nothing -> return mempty
(tit <>) <$> parseMixed para (elContent e)
"simpara" -> parseMixed para (elContent e)
"ackno" -> parseMixed para (elContent e)
"epigraph" -> parseBlockquote
"blockquote" -> parseBlockquote
"attribution" -> return mempty
"titleabbrev" -> return mempty
"authorinitials" -> return mempty
"title" -> checkInMeta getTitle
"author" -> checkInMeta getAuthor
"authorgroup" -> checkInMeta getAuthorGroup
"releaseinfo" -> checkInMeta (getInlines e >>= addMeta "release")
"date" -> checkInMeta getDate
"bibliography" -> sect 0
"bibliodiv" -> sect 1
"biblioentry" -> parseMixed para (elContent e)
"bibliomixed" -> parseMixed para (elContent e)
"glosssee" -> para . (\ils -> text "See " <> ils <> str ".")
<$> getInlines e
"glossseealso" -> para . (\ils -> text "See also " <> ils <> str ".")
<$> getInlines e
"glossary" -> sect 0
"glossdiv" -> definitionList <$>
mapM parseGlossEntry (filterChildren (named "glossentry") e)
"glosslist" -> definitionList <$>
mapM parseGlossEntry (filterChildren (named "glossentry") e)
"chapter" -> sect 0
"appendix" -> sect 0
"preface" -> sect 0
"bridgehead" -> para . strong <$> getInlines e
"sect1" -> sect 1
"sect2" -> sect 2
"sect3" -> sect 3
"sect4" -> sect 4
"sect5" -> sect 5
"section" -> gets dbSectionLevel >>= sect . (+1)
"refsect1" -> sect 1
"refsect2" -> sect 2
"refsect3" -> sect 3
"refsection" -> gets dbSectionLevel >>= sect . (+1)
"important" -> blockQuote . (para (strong $ str "Important") <>)
<$> getBlocks e
"caution" -> blockQuote . (para (strong $ str "Caution") <>)
<$> getBlocks e
"note" -> blockQuote . (para (strong $ str "Note") <>)
<$> getBlocks e
"tip" -> blockQuote . (para (strong $ str "Tip") <>)
<$> getBlocks e
"warning" -> blockQuote . (para (strong $ str "Warning") <>)
<$> getBlocks e
"area" -> return mempty
"areaset" -> return mempty
"areaspec" -> return mempty
"qandadiv" -> gets dbSectionLevel >>= sect . (+1)
"question" -> addToStart (strong (str "Q:") <> str " ") <$> getBlocks e
"answer" -> addToStart (strong (str "A:") <> str " ") <$> getBlocks e
"abstract" -> blockQuote <$> getBlocks e
"calloutlist" -> bulletList <$> callouts
"itemizedlist" -> bulletList <$> listitems
"orderedlist" -> do
let listStyle = case attrValue "numeration" e of
"arabic" -> Decimal
"loweralpha" -> LowerAlpha
"upperalpha" -> UpperAlpha
"lowerroman" -> LowerRoman
"upperroman" -> UpperRoman
_ -> Decimal
let start = fromMaybe 1 $
(attrValue "override" <$> filterElement (named "listitem") e)
>>= safeRead
orderedListWith (start,listStyle,DefaultDelim)
<$> listitems
"variablelist" -> definitionList <$> deflistitems
"figure" -> getFigure e
"mediaobject" -> para <$> getMediaobject e
"caption" -> return mempty
"info" -> metaBlock
"articleinfo" -> metaBlock
"sectioninfo" -> return mempty -- keywords & other metadata
"refsectioninfo" -> return mempty -- keywords & other metadata
"refsect1info" -> return mempty -- keywords & other metadata
"refsect2info" -> return mempty -- keywords & other metadata
"refsect3info" -> return mempty -- keywords & other metadata
"sect1info" -> return mempty -- keywords & other metadata
"sect2info" -> return mempty -- keywords & other metadata
"sect3info" -> return mempty -- keywords & other metadata
"sect4info" -> return mempty -- keywords & other metadata
"sect5info" -> return mempty -- keywords & other metadata
"chapterinfo" -> return mempty -- keywords & other metadata
"glossaryinfo" -> return mempty -- keywords & other metadata
"appendixinfo" -> return mempty -- keywords & other metadata
"bookinfo" -> metaBlock
"article" -> modify (\st -> st{ dbBook = False }) >>
getBlocks e
"book" -> modify (\st -> st{ dbBook = True }) >> getBlocks e
"table" -> parseTable
"informaltable" -> parseTable
"informalexample" -> divWith ("", ["informalexample"], []) <$>
getBlocks e
"literallayout" -> codeBlockWithLang
"screen" -> codeBlockWithLang
"programlisting" -> codeBlockWithLang
"?xml" -> return mempty
_ -> getBlocks e
where parseMixed container conts = do
let (ils,rest) = break isBlockElement conts
ils' <- (trimInlines . mconcat) <$> mapM parseInline ils
let p = if ils' == mempty then mempty else container ils'
case rest of
[] -> return p
(r:rs) -> do
b <- parseBlock r
x <- parseMixed container rs
return $ p <> b <> x
codeBlockWithLang = do
let classes' = case attrValue "language" e of
"" -> []
x -> [x]
return $ codeBlockWith (attrValue "id" e, classes', [])
$ trimNl $ strContentRecursive e
parseBlockquote = do
attrib <- case filterChild (named "attribution") e of
Nothing -> return mempty
Just z -> (para . (str "— " <>) . mconcat)
<$> (mapM parseInline $ elContent z)
contents <- getBlocks e
return $ blockQuote (contents <> attrib)
listitems = mapM getBlocks $ filterChildren (named "listitem") e
callouts = mapM getBlocks $ filterChildren (named "callout") e
deflistitems = mapM parseVarListEntry $ filterChildren
(named "varlistentry") e
parseVarListEntry e' = do
let terms = filterChildren (named "term") e'
let items = filterChildren (named "listitem") e'
terms' <- mapM getInlines terms
items' <- mapM getBlocks items
return (mconcat $ intersperse (str "; ") terms', items')
parseGlossEntry e' = do
let terms = filterChildren (named "glossterm") e'
let items = filterChildren (named "glossdef") e'
terms' <- mapM getInlines terms
items' <- mapM getBlocks items
return (mconcat $ intersperse (str "; ") terms', items')
getTitle = do
tit <- getInlines e
subtit <- case filterChild (named "subtitle") e of
Just s -> (text ": " <>) <$>
getInlines s
Nothing -> return mempty
addMeta "title" (tit <> subtit)
getAuthor = (:[]) <$> getInlines e >>= addMeta "author"
getAuthorGroup = do
let terms = filterChildren (named "author") e
mapM getInlines terms >>= addMeta "author"
getDate = getInlines e >>= addMeta "date"
parseTable = do
let isCaption x = named "title" x || named "caption" x
caption <- case filterChild isCaption e of
Just t -> getInlines t
Nothing -> return mempty
let e' = fromMaybe e $ filterChild (named "tgroup") e
let isColspec x = named "colspec" x || named "col" x
let colspecs = case filterChild (named "colgroup") e' of
Just c -> filterChildren isColspec c
_ -> filterChildren isColspec e'
let isRow x = named "row" x || named "tr" x
headrows <- case filterChild (named "thead") e' of
Just h -> case filterChild isRow h of
Just x -> parseRow x
Nothing -> return []
Nothing -> return []
bodyrows <- case filterChild (named "tbody") e' of
Just b -> mapM parseRow
$ filterChildren isRow b
Nothing -> mapM parseRow
$ filterChildren isRow e'
let toAlignment c = case findAttr (unqual "align") c of
Just "left" -> AlignLeft
Just "right" -> AlignRight
Just "center" -> AlignCenter
_ -> AlignDefault
let toWidth c = case findAttr (unqual "colwidth") c of
Just w -> fromMaybe 0
$ safeRead $ '0': filter (\x ->
(x >= '0' && x <= '9')
|| x == '.') w
Nothing -> 0 :: Double
let numrows = case bodyrows of
[] -> 0
xs -> maximum $ map length xs
let aligns = case colspecs of
[] -> replicate numrows AlignDefault
cs -> map toAlignment cs
let widths = case colspecs of
[] -> replicate numrows 0
cs -> let ws = map toWidth cs
tot = sum ws
in if all (> 0) ws
then map (/ tot) ws
else replicate numrows 0
let headrows' = if null headrows
then replicate numrows mempty
else headrows
return $ table caption (zip aligns widths)
headrows' bodyrows
isEntry x = named "entry" x || named "td" x || named "th" x
parseRow = mapM (parseMixed plain . elContent) . filterChildren isEntry
sect n = do isbook <- gets dbBook
let n' = if isbook || n == 0 then n + 1 else n
headerText <- case filterChild (named "title") e `mplus`
(filterChild (named "info") e >>=
filterChild (named "title")) of
Just t -> getInlines t
Nothing -> return mempty
modify $ \st -> st{ dbSectionLevel = n }
b <- getBlocks e
let ident = attrValue "id" e
modify $ \st -> st{ dbSectionLevel = n - 1 }
return $ headerWith (ident,[],[]) n' headerText <> b
metaBlock = acceptingMetadata (getBlocks e) >> return mempty
getInlines :: Element -> DB Inlines
getInlines e' = (trimInlines . mconcat) <$> (mapM parseInline $ elContent e')
strContentRecursive :: Element -> String
strContentRecursive = strContent .
(\e' -> e'{ elContent = map elementToStr $ elContent e' })
elementToStr :: Content -> Content
elementToStr (Elem e') = Text $ CData CDataText (strContentRecursive e') Nothing
elementToStr x = x
parseInline :: Content -> DB Inlines
parseInline (Text (CData _ s _)) = return $ text s
parseInline (CRef ref) =
return $ maybe (text $ map toUpper ref) (text . (:[])) $ lookupEntity ref
parseInline (Elem e) =
case qName (elName e) of
"equation" -> equation displayMath
"informalequation" -> equation displayMath
"inlineequation" -> equation math
"subscript" -> subscript <$> innerInlines
"superscript" -> superscript <$> innerInlines
"inlinemediaobject" -> getMediaobject e
"quote" -> do
qt <- gets dbQuoteType
let qt' = if qt == SingleQuote then DoubleQuote else SingleQuote
modify $ \st -> st{ dbQuoteType = qt' }
contents <- innerInlines
modify $ \st -> st{ dbQuoteType = qt }
return $ if qt == SingleQuote
then singleQuoted contents
else doubleQuoted contents
"simplelist" -> simpleList
"segmentedlist" -> segmentedList
"classname" -> codeWithLang
"code" -> codeWithLang
"filename" -> codeWithLang
"literal" -> codeWithLang
"computeroutput" -> codeWithLang
"prompt" -> codeWithLang
"parameter" -> codeWithLang
"option" -> codeWithLang
"optional" -> do x <- getInlines e
return $ str "[" <> x <> str "]"
"markup" -> codeWithLang
"wordasword" -> emph <$> innerInlines
"command" -> codeWithLang
"varname" -> codeWithLang
"function" -> codeWithLang
"type" -> codeWithLang
"symbol" -> codeWithLang
"constant" -> codeWithLang
"userinput" -> codeWithLang
"varargs" -> return $ code "(...)"
"keycap" -> return (str $ strContent e)
"keycombo" -> keycombo <$> (mapM parseInline $ elContent e)
"menuchoice" -> menuchoice <$> (mapM parseInline $
filter isGuiMenu $ elContent e)
"xref" -> do
content <- dbContent <$> get
let linkend = attrValue "linkend" e
let title = case attrValue "endterm" e of
"" -> maybe "???" xrefTitleByElem (findElementById linkend content)
endterm -> maybe "???" strContent (findElementById endterm content)
return $ link ('#' : linkend) "" (singleton (Str title))
"email" -> return $ link ("mailto:" ++ strContent e) ""
$ str $ strContent e
"uri" -> return $ link (strContent e) "" $ str $ strContent e
"ulink" -> link (attrValue "url" e) "" <$> innerInlines
"link" -> do
ils <- innerInlines
let href = case findAttr (QName "href" (Just "http://www.w3.org/1999/xlink") Nothing) e of
Just h -> h
_ -> ('#' : attrValue "linkend" e)
let ils' = if ils == mempty then str href else ils
return $ link href "" ils'
"foreignphrase" -> emph <$> innerInlines
"emphasis" -> case attrValue "role" e of
"bold" -> strong <$> innerInlines
"strong" -> strong <$> innerInlines
"strikethrough" -> strikeout <$> innerInlines
_ -> emph <$> innerInlines
"footnote" -> (note . mconcat) <$> (mapM parseBlock $ elContent e)
"title" -> return mempty
"affiliation" -> return mempty
-- Note: this isn't a real docbook tag; it's what we convert
-- <?asciidor-br?> to in handleInstructions, above. A kludge to
-- work around xml-light's inability to parse an instruction.
"br" -> return linebreak
_ -> innerInlines
where innerInlines = (trimInlines . mconcat) <$>
(mapM parseInline $ elContent e)
equation constructor = return $ mconcat $
map (constructor . writeTeX)
$ rights
$ map (readMathML . showElement . everywhere (mkT removePrefix))
$ filterChildren (\x -> qName (elName x) == "math" &&
qPrefix (elName x) == Just "mml") e
removePrefix elname = elname { qPrefix = Nothing }
codeWithLang = do
let classes' = case attrValue "language" e of
"" -> []
l -> [l]
return $ codeWith (attrValue "id" e,classes',[]) $ strContentRecursive e
simpleList = (mconcat . intersperse (str "," <> space)) <$> mapM getInlines
(filterChildren (named "member") e)
segmentedList = do
tit <- maybe (return mempty) getInlines $ filterChild (named "title") e
segtits <- mapM getInlines $ filterChildren (named "segtitle") e
segitems <- mapM (mapM getInlines . filterChildren (named "seg"))
$ filterChildren (named "seglistitem") e
let toSeg = mconcat . zipWith (\x y -> strong (x <> str ":") <> space <>
y <> linebreak) segtits
let segs = mconcat $ map toSeg segitems
let tit' = if tit == mempty
then mempty
else strong tit <> linebreak
return $ linebreak <> tit' <> segs
keycombo = spanWith ("",["keycombo"],[]) .
mconcat . intersperse (str "+")
menuchoice = spanWith ("",["menuchoice"],[]) .
mconcat . intersperse (text " > ")
isGuiMenu (Elem x) = named "guimenu" x || named "guisubmenu" x ||
named "guimenuitem" x
isGuiMenu _ = False
findElementById idString content
= asum [filterElement (\x -> attrValue "id" x == idString) el | Elem el <- content]
-- Use the 'xreflabel' attribute for getting the title of a xref link;
-- if there's no such attribute, employ some heuristics based on what
-- docbook-xsl does.
xrefTitleByElem el
| not (null xrefLabel) = xrefLabel
| otherwise = case qName (elName el) of
"chapter" -> descendantContent "title" el
"sect1" -> descendantContent "title" el
"sect2" -> descendantContent "title" el
"sect3" -> descendantContent "title" el
"sect4" -> descendantContent "title" el
"sect5" -> descendantContent "title" el
"cmdsynopsis" -> descendantContent "command" el
"funcsynopsis" -> descendantContent "function" el
_ -> qName (elName el) ++ "_title"
where
xrefLabel = attrValue "xreflabel" el
descendantContent name = maybe "???" strContent
. findElement (QName name Nothing Nothing)
|
poxu/pandoc
|
src/Text/Pandoc/Readers/DocBook.hs
|
gpl-2.0
| 52,723
| 0
| 24
| 15,635
| 7,401
| 3,661
| 3,740
| 509
| 112
|
{-# LANGUAGE UnicodeSyntax #-}
{-# LANGUAGE TemplateHaskell #-}
module Shakugan.Types where
import Control.Lens
import Control.Monad.State.Strict
import qualified Data.Map as M
import qualified Data.Vector as V
import FreeGame
makeLenses ''V.Vector
-- | Bitmaps with movement associated to with them.
data MovingBitmap = MovingBitmap { _movingBitmap ∷ Bitmap
, _movementAmount ∷ V2 Double
}
makeLenses ''MovingBitmap
-- | Collection of bitmaps with some meta-data to keep track of where
-- we are.
data Sprite =
Sprite { _spriteMaps ∷ V.Vector MovingBitmap
-- ^ Vector of sprites for this graphic
, _spriteNext ∷ Int -- ^ Index of next sprite to render
, _spriteSince ∷ Int -- ^ Frames since sprite was changed
}
makeLenses ''Sprite
data Effects = Effects { _effectFireball ∷ Sprite
, _effectFirebeam ∷ Sprite
}
makeLenses ''Effects
data CharacterSprites =
CharacterSprites { _charFacingLeft ∷ Sprite
, _charFacingRight ∷ Sprite
, _charRunningLeft ∷ Sprite
, _charRunningRight ∷ Sprite
, _charJumpingRight ∷ Sprite
, _charJumpingLeft ∷ Sprite
, _effects ∷ Effects
}
makeLenses ''CharacterSprites
data Resources =
Resources { _charSprites ∷ CharacterSprites
, _backdrop ∷ Bitmap
}
makeLenses ''Resources
data Direction = LeftD | RightD deriving Show
makeLenses ''Direction
data Player = Player { _keysHeld ∷ M.Map Key Int
, _position ∷ V2 Double
, _facing ∷ Direction
, _falling ∷ Bool
, _jumping ∷ Bool
}
makeLenses ''Player
data Field =
Field { _player ∷ Player }
makeLenses ''Field
data GameFrame =
GameFrame { _resources ∷ Resources
, _field ∷ Field
, _quit ∷ Bool
, _targetFramerate ∷ Int
}
makeLenses ''GameFrame
type GameLoop = StateT GameFrame Game
|
Fuuzetsu/shakugan-no-haskell
|
src/Shakugan/Types.hs
|
gpl-3.0
| 2,191
| 0
| 10
| 741
| 397
| 230
| 167
| 51
| 0
|
import System.Environment
main :: IO ()
main = do
query <- getEnv "QUERY_STRING"
let
hostDir = "/home/public/"
bchar = '-'
(gameVer, _:addrs) = break (== bchar) query
(filename, addrsString)
| bchar `elem` query = (hostDir ++ "host_" ++ gameVer ++ ".txt", addrs)
| otherwise = (hostDir ++ "host.txt", query)
putStr . ("Content-type: text/plain\r\n\r\n" ++) =<< readFile filename
writeFile filename addrsString
|
yairchu/defend
|
server/match.hs
|
gpl-3.0
| 447
| 0
| 14
| 97
| 157
| 81
| 76
| 13
| 1
|
module DBus.Mpris.MediaPlayer2.Player.Data
( PlaybackStatus(..)
, LoopStatus(..)
, Metadata(..)
) where
import Data.Map
import DBus (Variant)
-- | A playback state.
data PlaybackStatus = Playing -- ^ A track is currently playing.
| Paused -- ^ A track is currently paused.
| Stopped -- ^ There is no track currently playing.
deriving (Eq, Show, Read)
-- | A repeat / loop status
data LoopStatus = None -- ^ The playback will stop when there are no more tracks to play
| Track -- ^ The current track will start again from the begining once it has finished playing
| Playlist -- ^ The playback loops through a list of tracks
deriving (Eq, Show, Read)
-- In case we want to add more fields in the future, here's the list
-- Mpris properties:
-- mpris:trackid
-- mpris:length
-- mpris:artUrl
--
-- Common Xesam properties:
--
-- xesam:album
-- xesam:albumArtist
-- xesam:artist
-- xesam:asText
-- xesam:audioBPM
-- xesam:autoRating
-- xesam:comment
-- xesam:composer
-- xesam:contentCreated
-- xesam:discNumber
-- xesam:firstUsed
-- xesam:genre
-- xesam:lastUsed
-- xesam:lyricist
-- xesam:title
-- xesam:trackNumber
-- xesam:url
-- xesam:useCount
-- xesam:userRating
-- | Metadata about the current track
data Metadata = Metadata
{ trackId :: Maybe String -- ^ Mpris Track ID
, len :: Maybe Integer -- ^ Length in microseconds
, album :: Maybe String -- ^ Album
, artist :: Maybe String -- ^ Artist
, title :: Maybe String -- ^ Title
, url :: Maybe String -- ^ Url
, unknown :: Map String Variant -- ^ Unknown fields
} deriving (Show)
|
Fuco1/mpris
|
src/DBus/Mpris/MediaPlayer2/Player/Data.hs
|
gpl-3.0
| 1,797
| 0
| 9
| 522
| 225
| 151
| 74
| 23
| 0
|
{-# OPTIONS_HADDOCK hide #-}
--------------------------------------------------------------------------------
-- |
-- Module : Tct.Main.Debug
-- Copyright : (c) Martin Avanzini <martin.avanzini@uibk.ac.at>,
-- Georg Moser <georg.moser@uibk.ac.at>,
-- Andreas Schnabl <andreas.schnabl@uibk.ac.at>,
-- License : LGPL (see COPYING)
--
-- Maintainer : Martin Avanzini <martin.avanzini@uibk.ac.at>
-- Stability : unstable
-- Portability : unportable
--
-- Debug Utilities.
--------------------------------------------------------------------------------
module Tct.Main.Debug where
-- MA:TODO: output to stream specified in Tct.Config, integrate in solver monad
import System.IO
import Tct.Processor(Proof, SomeProcessor)
import Termlib.Utils (PrettyPrintable (..))
data Message = SolveStart
| SolveFinish (Proof SomeProcessor)
class DebugM m where
setDebug :: Bool -> m ()
debugEnabled :: m Bool
debugMsgPut :: PrettyPrintable body => Int -> String -> Maybe body -> m ()
putErrLn :: String -> IO ()
putErrLn s = hPutStr stderr (s ++ "\n")
|
mzini/TcT
|
source/Tct/Main/Debug.hs
|
gpl-3.0
| 1,132
| 0
| 12
| 223
| 170
| 98
| 72
| 13
| 1
|
-- Eso de repetirse está muy bien, pero a veces es tedioso para el reiterador, he aquí distintas versiones en haskell para cansinos de alta arcunia
-- Granada 12-02-2018
-- Versión 0, recursiva
hello_worlds 0 = return ()
hello_worlds n = do
putStrLn "Hello Worlds"
hello_worlds (n-1)
-- Versión 1, con replicate, la cual no termino de entender
bye_worlds n = mapM putStrLn $ replicate n "Bye Word"
-- Versión 2 simple y bonita, recursiva
olvido 1 = "Se me ha olvidado"
olvido n = "Se me ha olvidado\n" ++ olvido( n-1 )
olvidos n = putStrLn ( olvido n )
-- Versión 3 por compresión
amor n = putStrLn s
where (x:s) = concat [ "\nte quiero" | _<- [1..n]]
----------------------------------------
main = do
n <- readLn :: IO Int
hello_worlds n
bye_worlds n
olvidos n
amor n
|
BlancaCC/cultutrilla
|
haskell_aprendizaje/básicos/bucle_de_amor.hs
|
gpl-3.0
| 807
| 0
| 11
| 169
| 202
| 97
| 105
| 16
| 1
|
{-
----------------------------------------------------------------------------------
- Copyright (C) 2010-2011 Massachusetts Institute of Technology
- Copyright (C) 2010-2011 Yuan Tang <yuantang@csail.mit.edu>
- Charles E. Leiserson <cel@mit.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 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/>.
-
- Suggestsions: yuantang@csail.mit.edu
- Bugs: yuantang@csail.mit.edu
-
--------------------------------------------------------------------------------
-}
module Main where
import System.Environment
import System.Exit
import System.IO
import Data.List
import System.Directory
import System.Cmd (rawSystem)
import Data.Char (isSpace)
import qualified Data.Map as Map
import Text.ParserCombinators.Parsec (runParser)
import PData
import PMainParser
main :: IO ()
main = do args <- getArgs
whilst (null args) $ do
printUsage
exitFailure
let (inFiles, inDirs, mode, debug, showFile, userArgs)
= parseArgs ([], [], PDefault, False, True, []) args
whilst (mode == PHelp) $ do
printOptions
exitFailure
whilst (mode /= PNoPP) $ do
ppopp (mode, debug, showFile, userArgs) (zip inFiles inDirs)
-- pass everything to icc after preprocessing and Pochoir optimization
let iccArgs = userArgs
putStrLn (icc ++ " " ++ intercalate " " iccArgs)
rawSystem icc iccArgs
whilst (showFile == False) $ do
let outFiles = map (rename "_pochoir") inFiles
removeFile $ intercalate " " outFiles
whilst :: Bool -> IO () -> IO ()
whilst True action = action
whilst False action = return ()
ppopp :: (PMode, Bool, Bool, [String]) -> [(String, String)] -> IO ()
ppopp (_, _, _, _) [] = return ()
ppopp (mode, debug, showFile, userArgs) ((inFile, inDir):files) =
do putStrLn ("pochoir called with mode =" ++ show mode)
pochoirLibPath <- catch (getEnv "POCHOIR_LIB_PATH")(\e -> return "EnvError")
whilst (pochoirLibPath == "EnvError") $ do
putStrLn ("Pochoir environment variable not set:")
putStrLn ("POCHOIR_LIB_PATH")
exitFailure
{-
cilkStubPath <- catch (getEnv "CILK_HEADER_PATH")(\e -> return "EnvError")
whilst (cilkStubPath == "EnvError") $ do
putStrLn ("Environment variable CILK_HEADER_PATH is NOT set")
exitFailure
let envPath = ["-I" ++ cilkStubPath] ++ ["-I" ++ pochoirLibPath]
-}
let envPath = ["-I" ++ pochoirLibPath]
let iccPPFile = inDir ++ getPPFile inFile
let iccPPArgs = if debug == False
then iccPPFlags ++ envPath ++ [inFile]
else iccDebugPPFlags ++ envPath ++ [inFile]
-- a pass of icc preprocessing
putStrLn (icc ++ " " ++ intercalate " " iccPPArgs)
rawSystem icc iccPPArgs
-- a pass of pochoir compilation
whilst (mode /= PDebug) $ do
let outFile = rename "_pochoir" inFile
inh <- openFile iccPPFile ReadMode
outh <- openFile outFile WriteMode
putStrLn ("pochoir " ++ show mode ++ " " ++ iccPPFile)
pProcess mode inh outh
hClose inh
hClose outh
whilst (mode == PDebug) $ do
let midFile = getMidFile inFile
let outFile = rename "_pochoir" midFile
putStrLn ("mv " ++ midFile ++ " " ++ outFile)
renameFile midFile outFile
ppopp (mode, debug, showFile, userArgs) files
getMidFile :: String -> String
getMidFile a
| isSuffixOf ".cpp" a || isSuffixOf ".cxx" a = take (length a - 4) a ++ ".i"
| otherwise = a
rename :: String -> String -> String
rename pSuffix fname = name ++ pSuffix ++ ".cpp"
where (name, suffix) = break ('.' ==) fname
getPPFile :: String -> String
getPPFile fname = name ++ ".i"
where (name, suffix) = break ('.' ==) fname
{-
getObjFile :: String -> String -> [String]
getObjFile dir fname = ["-o"] ++ [dir++name]
where (name, suffix) = break ('.' ==) fname
-}
pInitState = ParserState { pMode = PCaching, pState = Unrelated, pMacro = Map.empty, pArray = Map.empty, pStencil = Map.empty, pShape = Map.empty, pRange = Map.empty, pKernel = Map.empty}
icc = "icpc"
iccFlags = ["-O3", "-DNDEBUG", "-std=c++0x", "-Wall", "-Werror", "-ipo"]
iccPPFlags = ["-P", "-C", "-DNCHECK_SHAPE", "-DNDEBUG", "-std=c++0x", "-Wall", "-Werror", "-ipo"]
-- iccDebugFlags = ["-DDEBUG", "-O0", "-g3", "-std=c++0x", "-include", "cilk_stub.h"]
iccDebugFlags = ["-DDEBUG", "-O0", "-g3", "-std=c++0x"]
-- iccDebugPPFlags = ["-P", "-C", "-DCHECK_SHAPE", "-DDEBUG", "-g3", "-std=c++0x", "-include", "cilk_stub.h"]
iccDebugPPFlags = ["-P", "-C", "-DCHECK_SHAPE", "-DDEBUG", "-g3", "-std=c++0x"]
parseArgs :: ([String], [String], PMode, Bool, Bool, [String]) -> [String] -> ([String], [String], PMode, Bool, Bool, [String])
parseArgs (inFiles, inDirs, mode, debug, showFile, userArgs) aL
| elem "--help" aL =
let l_mode = PHelp
aL' = delete "--help" aL
in (inFiles, inDirs, l_mode, debug, showFile, aL')
| elem "-h" aL =
let l_mode = PHelp
aL' = delete "-h" aL
in (inFiles, inDirs, l_mode, debug, showFile, aL')
| elem "-auto-optimize" aL =
let l_mode = PDefault
aL' = delete "-auto-optimize" aL
in (inFiles, inDirs, l_mode, debug, showFile, aL')
| elem "-split-caching" aL =
let l_mode = PCaching
aL' = delete "-split-caching" aL
in parseArgs (inFiles, inDirs, l_mode, debug, showFile, aL') aL'
| elem "-split-c-pointer" aL =
let l_mode = PCPointer
aL' = delete "-split-c-pointer" aL
in parseArgs (inFiles, inDirs, l_mode, debug, showFile, aL') aL'
| elem "-split-opt-pointer" aL =
let l_mode = POptPointer
aL' = delete "-split-opt-pointer" aL
in parseArgs (inFiles, inDirs, l_mode, debug, showFile, aL') aL'
| elem "-split-pointer" aL =
let l_mode = PPointer
aL' = delete "-split-pointer" aL
in parseArgs (inFiles, inDirs, l_mode, debug, showFile, aL') aL'
| elem "-split-macro-shadow" aL =
let l_mode = PMacroShadow
aL' = delete "-split-macro-shadow" aL
in parseArgs (inFiles, inDirs, l_mode, debug, showFile, aL') aL'
| elem "-showFile" aL =
let l_showFile = True
aL' = delete "-showFile" aL
in parseArgs (inFiles, inDirs, mode, debug, l_showFile, aL') aL'
| elem "-debug" aL =
let l_debug = True
l_mode = PDebug
aL' = delete "-debug" aL
in parseArgs (inFiles, inDirs, l_mode, l_debug, showFile, aL') aL'
| null aL == False =
let (l_files, l_dirs, l_mode, aL') = findCPP aL ([], [], mode, aL)
in (l_files, l_dirs, l_mode, debug, showFile, aL')
| otherwise =
let l_mode = PNoPP
in (inFiles, inDirs, l_mode, debug, showFile, aL)
findCPP :: [String] -> ([String], [String], PMode, [String]) -> ([String], [String], PMode, [String])
findCPP [] (l_files, l_dirs, l_mode, l_al) =
let l_mode' =
if null l_files == True || null l_dirs == True then PNoPP else l_mode
in (l_files, l_dirs, l_mode', l_al)
findCPP (a:as) (l_files, l_dirs, l_mode, l_al)
| isSuffixOf ".cpp" a || isSuffixOf ".cxx" a =
let l_file = drop (1 + (pLast $ findIndices (== '/') a)) a
l_dir = take (1 + (pLast $ findIndices (== '/') a)) a
l_files' = l_files ++ [l_file]
l_dirs' = l_dirs ++ [l_dir]
pLast [] = -1
pLast aL@(a:as) = last aL
l_pochoir_file = rename "_pochoir" l_file
(prefix, suffix) = break (a == ) l_al
l_al' = prefix ++ [l_pochoir_file] ++ tail suffix
in findCPP as (l_files', l_dirs', l_mode, l_al')
| otherwise = findCPP as (l_files, l_dirs, l_mode, l_al)
printUsage :: IO ()
printUsage =
do putStrLn ("Usage: pochoir [OPTION] [filename]")
putStrLn ("Try `pochoir --help' for more options.")
printOptions :: IO ()
printOptions =
do putStrLn ("Usage: pochoir [OPTION] [filename]")
putStrLn ("Run the Pochoir stencil compiler on [filename].")
putStrLn ("-auto-optimize : " ++ breakline ++ "Let the Pochoir compiler automatically choose the best optimizing level for you! (default)")
putStrLn ("-split-macro-shadow $filename : " ++ breakline ++
"using macro tricks to split the interior and boundary regions")
putStrLn ("-split-pointer $filename : " ++ breakline ++
"Default Mode : split the interior and boundary region, and using C-style pointer to optimize the base case")
pProcess :: PMode -> Handle -> Handle -> IO ()
pProcess mode inh outh =
do ls <- hGetContents inh
let pRevInitState = pInitState { pMode = mode }
case runParser pParser pRevInitState "" $ stripWhite ls of
Left err -> print err
Right str -> hPutStrLn outh str
|
rrnewton/PochoirMods
|
PMain.hs
|
gpl-3.0
| 9,702
| 0
| 16
| 2,613
| 2,610
| 1,378
| 1,232
| 166
| 3
|
-- | Evaluator for P
-- | Juan García Garland (Nov. 2016)
module Eval where
import State
import Language
import Memory
import State
-- | eval evaluates P
eval :: Program -> Integer -> Integer
eval p@(Program vin sec vout) inp
= let initialMemory = singletonMemory vin inp
in evalState (evalProg p inp) initialMemory
evalProg :: Program -> Integer -> State Memory Integer
evalProg (Program varin sec varout) inp = put (singletonMemory varin inp) >>
evalSec sec >>
get >>= \mem ->
return $ lookUp varout mem
evalSent :: Sent -> State Memory ()
evalSent (Assign var expr)
= get >>= \mem ->
case expr of
Zero -> put (update var 0 mem)
Succ x -> put (update var (n+1) mem)
where
n = lookUp x mem
Pred x -> put (update var (pre n) mem)
where
n = lookUp x mem
pre n = if n==0 then 0 else n-1
evalSent w@(While (Nonzero varcond) sec)
= get >>= \mem ->
case lookUp varcond mem of
0 -> put mem
n -> evalSec sec >>
evalSent w
evalSec (Sec []) = return ()
evalSec (Sec (s:ss)) = evalSent s >>
evalSec (Sec ss)
|
jota191/PLang
|
src/Eval.hs
|
gpl-3.0
| 1,278
| 0
| 14
| 471
| 457
| 229
| 228
| 33
| 5
|
{-| Module : CoreToImportEnv
License : GPL
Maintainer : helium@cs.uu.nl
Stability : experimental
Portability : portable
-}
module Helium.ModuleSystem.CoreToImportEnv(getImportEnvironment) where
import Lvm.Core.Expr
import Lvm.Core.Utils
import Helium.Utils.Utils
import Helium.StaticAnalysis.Miscellaneous.TypeConversion
import Helium.Parser.ParseLibrary
import Helium.Parser.Lexer(lexer)
import Helium.Parser.Parser(type_, contextAndType)
import Helium.ModuleSystem.ImportEnvironment
import Helium.Syntax.UHA_Utils
import Lvm.Common.Id
import Helium.Syntax.UHA_Syntax
import Helium.Parser.OperatorTable
import Top.Types
import Lvm.Common.Byte(stringFromBytes)
import Helium.Syntax.UHA_Range(makeImportRange, setNameRange)
typeFromCustoms :: String -> [Custom] -> TpScheme
typeFromCustoms n [] =
internalError "CoreToImportEnv" "typeFromCustoms"
("function import without type: " ++ n)
typeFromCustoms n ( CustomDecl (DeclKindCustom ident) [CustomBytes bytes] : cs)
| stringFromId ident == "type" =
let string = filter (/= '!') (stringFromBytes bytes)
in makeTpSchemeFromType (parseFromString contextAndType string)
| otherwise =
typeFromCustoms n cs
typeFromCustoms _ _ = error "Pattern match failure in ModuleSystem.CoreToImportEnv.typeFromCustoms"
parseFromString :: HParser a -> String -> a
parseFromString p string =
case lexer [] "CoreToImportEnv" string of
Left _ -> internalError "CoreToImportEnv" "parseFromString" ("lex error in " ++ string)
Right (tokens, _) ->
case runHParser p "CoreToImportEnv" tokens True {- wait for EOF -} of
Left _ -> internalError "CoreToImportEnv" "parseFromString" ("parse error in " ++ string)
Right x -> x
typeSynFromCustoms :: String -> [Custom] -> (Int, Tps -> Tp) -- !!! yuck
typeSynFromCustoms n (CustomBytes bs:cs) =
let
typeSynDecl = stringFromBytes bs
-- (too?) simple parser; works because type variables in synonym decls are renamed to 1 letter
ids = ( map (\x -> nameFromString [x])
. filter (' '/=)
. takeWhile ('='/=)
. drop (length n + 1)
)
typeSynDecl
rhsType = ( drop 1
. dropWhile ('='/=)
)
typeSynDecl
in
( arityFromCustoms n cs
, \ts -> makeTpFromType (zip ids ts) (parseFromString type_ rhsType)
)
typeSynFromCustoms n _ =
internalError "CoreToImportEnv" "typeSynFromCustoms"
("type synonym import missing definition: " ++ n)
-- in compiled Core files types have a kind (e.g. * -> *),
-- in Helium the have a number indicating the arity
arityFromCustoms :: String -> [Custom] -> Int
arityFromCustoms n [] =
internalError "CoreToImportEnv" "arityFromCustoms"
("type constructor import without kind: " ++ n)
arityFromCustoms _ ( CustomInt arity : _ ) = arity
arityFromCustoms _ ( CustomDecl (DeclKindCustom ident) [CustomBytes bytes] : _ )
| stringFromId ident == "kind" =
(length . filter ('*'==) . stringFromBytes) bytes - 1
-- the number of stars minus 1 is the arity
arityFromCustoms n (_:cs) = arityFromCustoms n cs
makeOperatorTable :: Name -> [Custom] -> [(Name, (Int, Assoc))]
makeOperatorTable oper (CustomInt i : CustomBytes bs : _) =
let
associativity =
case stringFromBytes bs of
"left" -> AssocLeft
"right" -> AssocRight
"none" -> AssocNone
assocStr -> intErr ("unknown associativity: " ++ assocStr)
intErr = internalError "CoreToImportEnv" "makeOperatorTable"
in
if getNameName oper == "-" then
-- special rule: unary minus has the associativity
-- and the priority of the infix operator -
[ (oper, (i, associativity))
, (intUnaryMinusName, (i, associativity))
, (floatUnaryMinusName, (i, associativity))
]
else
[(oper, (i, associativity))]
makeOperatorTable oper _ =
internalError "CoreToImportEnv" "makeOperatorTable"
("infix decl missing priority or associativity: " ++ show oper)
makeImportName :: String -> Id -> Id -> Name
makeImportName importedInMod importedFromMod n =
setNameRange
(nameFromId n)
(makeImportRange (idFromString importedInMod) importedFromMod)
getImportEnvironment :: String -> [CoreDecl] -> ImportEnvironment
getImportEnvironment importedInModule = foldr insert emptyEnvironment
where
insert decl =
case decl of
-- functions
DeclAbstract { declName = n
, declAccess = Imported{importModule = importedFromModId}
, declCustoms = cs
} ->
addType
(makeImportName importedInModule importedFromModId n)
(typeFromCustoms (stringFromId n) cs)
-- functions from non-core/non-lvm libraries and lvm-instructions
DeclExtern { declName = n
, declAccess = Imported{importModule = importedFromModId}
, declCustoms = cs
} ->
addType
(makeImportName importedInModule importedFromModId n)
(typeFromCustoms (stringFromId n) cs)
-- constructors
DeclCon { declName = n
, declAccess = Imported{importModule = importedFromModId}
, declCustoms = cs
} ->
addValueConstructor
(makeImportName importedInModule importedFromModId n)
(typeFromCustoms (stringFromId n) cs)
-- type constructor import
DeclCustom { declName = n
, declAccess = Imported{importModule = importedFromModId}
, declKind = DeclKindCustom ident
, declCustoms = cs
}
| stringFromId ident == "data" ->
addTypeConstructor
(makeImportName importedInModule importedFromModId n)
(arityFromCustoms (stringFromId n) cs)
-- type synonym declarations
-- important: a type synonym also introduces a new type constructor!
DeclCustom { declName = n
, declAccess = Imported{importModule = importedFromModId}
, declKind = DeclKindCustom ident
, declCustoms = cs
}
| stringFromId ident == "typedecl" ->
let typename = makeImportName importedInModule importedFromModId n
pair = typeSynFromCustoms (stringFromId n) cs
in addTypeSynonym typename pair . addTypeConstructor typename (fst pair)
-- infix decls
DeclCustom { declName = n
, declKind = DeclKindCustom ident
, declCustoms = cs
}
| stringFromId ident == "infix" ->
flip (foldr (uncurry addOperator)) (makeOperatorTable (nameFromId n) cs)
-- typing strategies
DeclCustom { declName = _
, declKind = DeclKindCustom ident
, declCustoms = cs
}
| stringFromId ident == "strategy" ->
let (CustomDecl _ [CustomBytes bytes]) = head cs
text = stringFromBytes bytes
in case reads text of
[(rule, [])] -> addTypingStrategies rule
_ -> intErr "Could not parse typing strategy from core file"
-- !!! Print importedFromModId from "declAccess = Imported{importModule = importedFromModId}" as well
DeclAbstract{ declName = n } ->
intErr ("don't know how to handle declared DeclAbstract: " ++ stringFromId n)
DeclExtern { declName = n } ->
intErr ("don't know how to handle declared DeclExtern: " ++ stringFromId n)
DeclCon { declName = n } ->
intErr ("don't know how to handle declared DeclCon: " ++ stringFromId n)
DeclCustom { declName = n } ->
intErr ("don't know how to handle DeclCustom: " ++ stringFromId n)
DeclValue { declName = n } ->
intErr ("don't know how to handle DeclValue: " ++ stringFromId n)
DeclImport { declName = n } ->
intErr ("don't know how to handle DeclImport: " ++ stringFromId n)
intErr = internalError "CoreToImportEnv" "getImportEnvironment"
|
roberth/uu-helium
|
src/Helium/ModuleSystem/CoreToImportEnv.hs
|
gpl-3.0
| 9,006
| 0
| 18
| 3,109
| 1,871
| 984
| 887
| 152
| 14
|
module Signal.UtilsBench where
import Signal.Utils
import System.Random
-- These two functions are wrappers around actually benchmarked functions. They
-- unwrap a tuple created by dataShift and pass the parameters from the tuple to
-- benchmarked functions. They should be inlined.
{-# INLINE benchCyclicShiftLeft #-}
benchCyclicShiftLeft :: (Int, [Double]) -> [Double]
benchCyclicShiftLeft (n, sig) = cyclicShiftLeft n sig
{-# INLINE benchCyclicShiftRight #-}
benchCyclicShiftRight :: (Int, [Double]) -> [Double]
benchCyclicShiftRight (n, sig) = cyclicShiftRight n sig
-- Function that generates data on which benchmarked functions will operate
dataShift :: RandomGen g => g -> Int -> Int -> (Int, [Double])
dataShift gen n sigSize = (n, take sigSize $ randoms gen)
|
oqc/hqt
|
QuranBench/Signal/UtilsBench.hs
|
gpl-3.0
| 774
| 0
| 10
| 115
| 163
| 94
| 69
| 11
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.OpsWorks.DeleteLayer
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Deletes a specified layer. You must first stop and then delete all associated
-- instances or unassign registered instances. For more information, see <http://docs.aws.amazon.com/opsworks/latest/userguide/workinglayers-basics-delete.html How toDelete a Layer>.
--
-- Required Permissions: To use this action, an IAM user must have a Manage
-- permissions level for the stack, or an attached policy that explicitly grants
-- permissions. For more information on user permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing UserPermissions>.
--
-- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_DeleteLayer.html>
module Network.AWS.OpsWorks.DeleteLayer
(
-- * Request
DeleteLayer
-- ** Request constructor
, deleteLayer
-- ** Request lenses
, dlLayerId
-- * Response
, DeleteLayerResponse
-- ** Response constructor
, deleteLayerResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.OpsWorks.Types
import qualified GHC.Exts
newtype DeleteLayer = DeleteLayer
{ _dlLayerId :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeleteLayer' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dlLayerId' @::@ 'Text'
--
deleteLayer :: Text -- ^ 'dlLayerId'
-> DeleteLayer
deleteLayer p1 = DeleteLayer
{ _dlLayerId = p1
}
-- | The layer ID.
dlLayerId :: Lens' DeleteLayer Text
dlLayerId = lens _dlLayerId (\s a -> s { _dlLayerId = a })
data DeleteLayerResponse = DeleteLayerResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DeleteLayerResponse' constructor.
deleteLayerResponse :: DeleteLayerResponse
deleteLayerResponse = DeleteLayerResponse
instance ToPath DeleteLayer where
toPath = const "/"
instance ToQuery DeleteLayer where
toQuery = const mempty
instance ToHeaders DeleteLayer
instance ToJSON DeleteLayer where
toJSON DeleteLayer{..} = object
[ "LayerId" .= _dlLayerId
]
instance AWSRequest DeleteLayer where
type Sv DeleteLayer = OpsWorks
type Rs DeleteLayer = DeleteLayerResponse
request = post "DeleteLayer"
response = nullResponse DeleteLayerResponse
|
dysinger/amazonka
|
amazonka-opsworks/gen/Network/AWS/OpsWorks/DeleteLayer.hs
|
mpl-2.0
| 3,290
| 0
| 9
| 690
| 350
| 215
| 135
| 47
| 1
|
module Opal.Distance (
module Opal.Distance.Calc,
module Opal.Distance.Stations,
module Opal.Distance.Units,
) where
import Opal.Distance.Calc
import Opal.Distance.Stations
import Opal.Distance.Units
|
mzhou/opaldist
|
src/Opal/Distance.hs
|
agpl-3.0
| 213
| 0
| 5
| 30
| 48
| 33
| 15
| 7
| 0
|
{-# LANGUAGE LambdaCase #-}
import ViperVM.Graph.Builtins
import ViperVM.Platform.Platform
import ViperVM.Platform.Runtime
import ViperVM.Platform.Logger
import ViperVM.Library.FloatMatrixAdd
import ViperVM.Library.FloatMatrixSub
import ViperVM.Library.FloatMatrixMul
import ViperVM.Library.FloatMatrixTranspose
import ViperVM.Library.FloatMatrixPotrf
import ViperVM.Library.FloatMatrixTrsm
import ViperVM.UserInterface
import ViperVM.Scheduling.Eager
import Control.Monad
import Data.Map as Map
import qualified Data.List as List
import System.Environment
import Paths_ViperVM
main :: IO ()
main = do
-- Parsing command line
expr <- getArgs >>= \case
["-e",s] -> return s
[] -> return "(let* ((h (add b b))) (sub a (add h h)))"
_ -> error "Invalid parameters"
-- Configuraing platform and runtime
let config = Configuration {
libraryOpenCL = "/usr/lib/libOpenCL.so",
logger = (stdOutLogger <=< clocked) . filterLevel LogDebug
}
putStrLn "Initializing platform and runtime..."
pf <- initPlatform config
rt <- initRuntime pf eagerScheduler
let
(w,h) = (16, 16) :: (Int,Int)
triangular = [ replicate n (0.0 :: Float) ++ repeat (fromIntegral n + 1.0) | n <- [0..]]
triangular' n = fmap (take n) (take n triangular)
triMul n = let m = List.transpose (triangular' n) in crossWith (\xs ys -> foldl1 (+) $ zipWith (*) xs ys) m m
crossWith f ys xs = fmap (\x -> fmap (\y -> f x y) ys) xs
putStrLn "Initializing input data"
a <- initFloatMatrixF rt (\_ _ -> 5.0) w h
b <- initFloatMatrixF rt (\_ _ -> 2.0) w h
c <- initFloatMatrix rt (triMul 32)
t <- initFloatMatrixF rt (\x y -> if x <= y then fromIntegral x+1.0 else 0.0) w h
let file = "apps/samples/lisp/Sample.lisp"
ctx <- readFile =<< getDataFileName file
myBuiltins <- loadBuiltins rt [
("add", floatMatrixAddBuiltin),
("sub", floatMatrixSubBuiltin),
("mul", floatMatrixMulBuiltin),
("transpose", floatMatrixTransposeBuiltin),
("potrf", floatMatrixPotrfBuiltin),
("trsm", floatMatrixTrsmBuiltin),
("a", dataBuiltin a),
("b", dataBuiltin b),
("c", dataBuiltin c),
("t", dataBuiltin t)
]
putStrLn ("Evaluating: " ++ show expr)
let builtins = Map.union defaultBuiltins myBuiltins
r <- evalLispWithContext builtins ctx expr
putStrLn ("================\nResult:" ++ show r)
printFloatMatrix rt r
putStrLn "Done."
|
hsyl20/HViperVM
|
apps/LispSOCL.hs
|
lgpl-3.0
| 2,501
| 0
| 16
| 551
| 778
| 412
| 366
| 60
| 4
|
module SumAbsorption where
import Either
import Sum
sumAbsorptionLeft, sumAbsorptionRight :: (d -> c) -> (e -> c) -> (a -> d) -> (b -> e) -> Either a b -> c
sumAbsorptionLeft g h i j = Either.either g h . Sum.sum i j
sumAbsorptionRight g h i j = Either.either (g . i) (h . j)
sal0,sal1,sar0,sar1 :: String
sal0 = sumAbsorptionLeft (++" g::d->c ") (++ " h:e->c ") (++" i::a->d ") (++" j::b->e ") (Left "foo")
sal1 = sumAbsorptionLeft (++" g::d->c ") (++ " h:e->c ") (++" i::a->d ") (++" j::b->e ") (Right "foo")
sar0 = sumAbsorptionRight (++" g::d->c ") (++ " h:e->c ") (++" i::a->d ") (++" j::b->e ") (Left "foo")
sar1 = sumAbsorptionRight (++" g::d->c ") (++ " h:e->c ") (++" i::a->d ") (++" j::b->e ") (Right "foo")
-- End
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/book/2019-Program_Design_by_Calculation-Oliveira/2015-05-LambdaConf/SumAbsorption.hs
|
unlicense
| 765
| 0
| 10
| 174
| 301
| 175
| 126
| 11
| 1
|
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : Haskoin.Address
Copyright : No rights reserved
License : MIT
Maintainer : jprupp@protonmail.ch
Stability : experimental
Portability : POSIX
Base58, CashAddr, Bech32 address and WIF private key serialization support.
-}
module Haskoin.Address
( -- * Addresses
Address(..)
, isPubKeyAddress
, isScriptAddress
, isWitnessPubKeyAddress
, isWitnessScriptAddress
, addrToText
, textToAddr
, bech32ToAddr
, cashToAddr
, base58ToAddr
, addrToJSON
, addrToEncoding
, addrFromJSON
, pubKeyAddr
, pubKeyWitnessAddr
, pubKeyCompatWitnessAddr
, p2pkhAddr
, p2wpkhAddr
, p2shAddr
, p2wshAddr
, inputAddress
, outputAddress
, addressToScript
, addressToScriptBS
, addressToOutput
, payToScriptAddress
, payToWitnessScriptAddress
, payToNestedScriptAddress
, scriptToAddress
, scriptToAddressBS
, module Haskoin.Address.Base58
, module Haskoin.Address.Bech32
, module Haskoin.Address.CashAddr
) where
import Control.Applicative
import Control.Arrow (second)
import Control.DeepSeq
import Control.Monad
import Data.Aeson as A
import Data.Aeson.Encoding as A
import Data.Aeson.Types
import Data.Binary (Binary (..))
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Bytes.Get
import Data.Bytes.Put
import Data.Bytes.Serial
import Data.Hashable
import Data.Maybe
import Data.Serialize (Serialize (..))
import Data.Text (Text)
import qualified Data.Text as T
import Data.Word (Word8)
import GHC.Generics (Generic)
import Haskoin.Address.Base58
import Haskoin.Address.Bech32
import Haskoin.Address.CashAddr
import Haskoin.Constants
import Haskoin.Crypto
import Haskoin.Keys.Common
import Haskoin.Script
import Haskoin.Util
-- | Address format for Bitcoin and Bitcoin Cash.
data Address
-- | pay to public key hash (regular)
= PubKeyAddress
{ getAddrHash160 :: !Hash160
-- ^ RIPEMD160 hash of public key's SHA256 hash
}
-- | pay to script hash
| ScriptAddress
{ getAddrHash160 :: !Hash160
-- ^ RIPEMD160 hash of script's SHA256 hash
}
-- | pay to witness public key hash
| WitnessPubKeyAddress
{ getAddrHash160 :: !Hash160
-- ^ RIPEMD160 hash of public key's SHA256 hash
}
-- | pay to witness script hash
| WitnessScriptAddress
{ getAddrHash256 :: !Hash256
-- ^ HASH256 hash of script
}
-- | other witness address
| WitnessAddress
{ getAddrVersion :: !Word8
, getAddrData :: !ByteString
}
deriving
(Eq, Ord, Generic, Show, Read, Hashable, NFData)
instance Serial Address where
serialize (PubKeyAddress k) = do
putWord8 0x00
serialize k
serialize (ScriptAddress s) = do
putWord8 0x01
serialize s
serialize (WitnessPubKeyAddress h) = do
putWord8 0x02
serialize h
serialize (WitnessScriptAddress s) = do
putWord8 0x03
serialize s
serialize (WitnessAddress v d) = do
putWord8 0x04
putWord8 v
putWord64be (fromIntegral (B.length d))
putByteString d
deserialize =
getWord8 >>= \case
0x00 -> PubKeyAddress <$> deserialize
0x01 -> ScriptAddress <$> deserialize
0x02 -> WitnessPubKeyAddress <$> deserialize
0x03 -> WitnessScriptAddress <$> deserialize
0x04 -> WitnessAddress <$> getWord8 <*>
(getByteString . fromIntegral =<< getWord64be)
b -> fail . T.unpack $
"Could not decode address type byte: " <>
encodeHex (B.singleton b)
instance Serialize Address where
put = serialize
get = deserialize
instance Binary Address where
put = serialize
get = deserialize
-- | 'Address' pays to a public key hash.
isPubKeyAddress :: Address -> Bool
isPubKeyAddress PubKeyAddress {} = True
isPubKeyAddress _ = False
-- | 'Address' pays to a script hash.
isScriptAddress :: Address -> Bool
isScriptAddress ScriptAddress {} = True
isScriptAddress _ = False
-- | 'Address' pays to a witness public key hash. Only valid for SegWit
-- networks.
isWitnessPubKeyAddress :: Address -> Bool
isWitnessPubKeyAddress WitnessPubKeyAddress {} = True
isWitnessPubKeyAddress _ = False
isWitnessScriptAddress :: Address -> Bool
isWitnessScriptAddress WitnessScriptAddress {} = True
isWitnessScriptAddress _ = False
isWitnessAddress :: Address -> Bool
isWitnessAddress WitnessAddress {} = True
isWitnessAddress _ = False
addrToJSON :: Network -> Address -> Value
addrToJSON net a = toJSON (addrToText net a)
addrToEncoding :: Network -> Address -> Encoding
addrToEncoding net = maybe null_ text . addrToText net
-- | JSON parsing for Bitcoin addresses. Works with 'Base58', 'CashAddr' and
-- 'Bech32'.
addrFromJSON :: Network -> Value -> Parser Address
addrFromJSON net =
withText "address" $ \t ->
case textToAddr net t of
Nothing -> fail "could not decode address"
Just x -> return x
-- | Convert address to human-readable string. Uses 'Base58', 'Bech32', or
-- 'CashAddr' depending on network.
addrToText :: Network -> Address -> Maybe Text
addrToText net a@PubKeyAddress {getAddrHash160 = h}
| isNothing (getCashAddrPrefix net) =
Just . encodeBase58Check . runPutS $ base58put net a
| otherwise = cashAddrEncode net 0 (runPutS $ serialize h)
addrToText net a@ScriptAddress {getAddrHash160 = h}
| isNothing (getCashAddrPrefix net) =
Just . encodeBase58Check . runPutS $ base58put net a
| otherwise =
cashAddrEncode net 1 (runPutS $ serialize h)
addrToText net WitnessPubKeyAddress {getAddrHash160 = h} = do
hrp <- getBech32Prefix net
segwitEncode hrp 0 (B.unpack (runPutS $ serialize h))
addrToText net WitnessScriptAddress {getAddrHash256 = h} = do
hrp <- getBech32Prefix net
segwitEncode hrp 0 (B.unpack (runPutS $ serialize h))
addrToText net WitnessAddress {getAddrVersion = v, getAddrData = d} = do
hrp <- getBech32Prefix net
segwitEncode hrp v (B.unpack d)
-- | Parse 'Base58', 'Bech32' or 'CashAddr' address, depending on network.
textToAddr :: Network -> Text -> Maybe Address
textToAddr net txt =
cashToAddr net txt <|> bech32ToAddr net txt <|> base58ToAddr net txt
cashToAddr :: Network -> Text -> Maybe Address
cashToAddr net txt = do
(ver, bs) <- cashAddrDecode net txt
case ver of
0 -> PubKeyAddress <$> eitherToMaybe (runGetS deserialize bs)
1 -> ScriptAddress <$> eitherToMaybe (runGetS deserialize bs)
_ -> Nothing
bech32ToAddr :: Network -> Text -> Maybe Address
bech32ToAddr net txt = do
hrp <- getBech32Prefix net
(ver, bs) <- second B.pack <$> segwitDecode hrp txt
case ver of
0 -> case B.length bs of
20 -> WitnessPubKeyAddress <$> eitherToMaybe (runGetS deserialize bs)
32 -> WitnessScriptAddress <$> eitherToMaybe (runGetS deserialize bs)
_ -> Nothing
_ -> Just $ WitnessAddress ver bs
base58ToAddr :: Network -> Text -> Maybe Address
base58ToAddr net txt =
eitherToMaybe . runGetS (base58get net) =<< decodeBase58Check txt
base58get :: MonadGet m => Network -> m Address
base58get net = do
pfx <- getWord8
addr <- deserialize
f pfx addr
where
f x a
| x == getAddrPrefix net = return $ PubKeyAddress a
| x == getScriptPrefix net = return $ ScriptAddress a
| otherwise = fail "Does not recognize address prefix"
base58put :: MonadPut m => Network -> Address -> m ()
base58put net (PubKeyAddress h) = do
putWord8 (getAddrPrefix net)
serialize h
base58put net (ScriptAddress h) = do
putWord8 (getScriptPrefix net)
serialize h
base58put _ _ = error "Cannot serialize this address as Base58"
-- | Obtain a standard pay-to-public-key-hash address from a public key.
pubKeyAddr :: PubKeyI -> Address
pubKeyAddr = PubKeyAddress . addressHash . runPutS . serialize
-- | Obtain a standard pay-to-public-key-hash (P2PKH) address from a 'Hash160'.
p2pkhAddr :: Hash160 -> Address
p2pkhAddr = PubKeyAddress
-- | Obtain a SegWit pay-to-witness-public-key-hash (P2WPKH) address from a
-- public key.
pubKeyWitnessAddr :: PubKeyI -> Address
pubKeyWitnessAddr = WitnessPubKeyAddress . addressHash . runPutS . serialize
-- | Obtain a backwards-compatible SegWit P2SH-P2WPKH address from a public key.
pubKeyCompatWitnessAddr :: PubKeyI -> Address
pubKeyCompatWitnessAddr =
p2shAddr .
addressHash .
encodeOutputBS .
PayWitnessPKHash .
addressHash .
runPutS .
serialize
-- | Obtain a SegWit pay-to-witness-public-key-hash (P2WPKH) address from a
-- 'Hash160'.
p2wpkhAddr :: Hash160 -> Address
p2wpkhAddr = WitnessPubKeyAddress
-- | Obtain a standard pay-to-script-hash (P2SH) address from a 'Hash160'.
p2shAddr :: Hash160 -> Address
p2shAddr = ScriptAddress
-- | Obtain a SegWit pay-to-witness-script-hash (P2WSH) address from a 'Hash256'
p2wshAddr :: Hash256 -> Address
p2wshAddr = WitnessScriptAddress
-- | Compute a standard pay-to-script-hash (P2SH) address for an output script.
payToScriptAddress :: ScriptOutput -> Address
payToScriptAddress = p2shAddr . addressHash . encodeOutputBS
-- | Compute a SegWit pay-to-witness-script-hash (P2WSH) address for an output
-- script.
payToWitnessScriptAddress :: ScriptOutput -> Address
payToWitnessScriptAddress = p2wshAddr . sha256 . encodeOutputBS
-- | Compute a backwards-compatible SegWit P2SH-P2WSH address.
payToNestedScriptAddress :: ScriptOutput -> Address
payToNestedScriptAddress =
p2shAddr . addressHash . encodeOutputBS . toP2WSH . encodeOutput
-- | Encode an output script from an address. Will fail if using a
-- pay-to-witness address on a non-SegWit network.
addressToOutput :: Address -> ScriptOutput
addressToOutput =
\case
PubKeyAddress h -> PayPKHash h
ScriptAddress h -> PayScriptHash h
WitnessPubKeyAddress h -> PayWitnessPKHash h
WitnessScriptAddress h -> PayWitnessScriptHash h
WitnessAddress v d -> PayWitness v d
-- | Get output script AST for an 'Address'.
addressToScript :: Address -> Script
addressToScript = encodeOutput . addressToOutput
-- | Encode address as output script in 'ByteString' form.
addressToScriptBS :: Address -> ByteString
addressToScriptBS = runPutS . serialize . addressToScript
-- | Decode an output script into an 'Address' if it has such representation.
scriptToAddress :: Script -> Either String Address
scriptToAddress =
maybeToEither "Could not decode address" . outputAddress <=< decodeOutput
-- | Decode a serialized script into an 'Address'.
scriptToAddressBS :: ByteString -> Either String Address
scriptToAddressBS =
maybeToEither "Could not decode address" . outputAddress <=< decodeOutputBS
-- | Get the 'Address' of a 'ScriptOutput'.
outputAddress :: ScriptOutput -> Maybe Address
outputAddress =
\case
PayPKHash h -> Just $ PubKeyAddress h
PayScriptHash h -> Just $ ScriptAddress h
PayPK k -> Just $ pubKeyAddr k
PayWitnessPKHash h -> Just $ WitnessPubKeyAddress h
PayWitnessScriptHash h -> Just $ WitnessScriptAddress h
PayWitness v d -> Just $ WitnessAddress v d
_ -> Nothing
-- | Infer the 'Address' of a 'ScriptInput'.
inputAddress :: ScriptInput -> Maybe Address
inputAddress =
\case
(RegularInput (SpendPKHash _ key)) -> Just $ pubKeyAddr key
(ScriptHashInput _ rdm) -> Just $ payToScriptAddress rdm
_ -> Nothing
|
haskoin/haskoin
|
src/Haskoin/Address.hs
|
unlicense
| 12,426
| 0
| 16
| 3,235
| 2,567
| 1,329
| 1,238
| -1
| -1
|
-- Copyright (c) 2013-2015 PivotCloud, Inc.
--
-- Aws.Kinesis
--
-- Please feel free to contact us at licensing@pivotmail.com with any
-- contributions, additions, or other feedback; we would love to hear from
-- you.
--
-- 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: Aws.Kinesis
-- Copyright: Copyright (c) 2013-2015 PivotCloud, Inc.
-- license: Apache License, Version 2.0
-- Maintainer: Lars Kuhtz <lars@alephcloud.com>
-- Stability: experimental
--
-- /API Version: 2013-12-02/
--
-- <http://docs.aws.amazon.com/kinesis/2013-12-02/APIReference>
--
-- The types and functions of this package are supposed to be
-- use with the machinery from the
-- <https://hackage.haskell.org/package/aws aws package>.
--
-- Here is a very simple example for making a single request to AWS Kinesis.
--
-- > import Aws
-- > import Aws.Core
-- > import Aws.General
-- > import Aws.Kinesis
-- > import Data.IORef
-- >
-- > cfg <- Aws.baseConfiguration
-- > creds <- Credentials "access-key-id" "secret-access-key" `fmap` newIORef []
-- > let kinesisCfg = KinesisConfiguration UsWest2
-- > simpleAws cfg kinesisCfg $ ListStreams Nothing Nothing
--
-- In order to run the example you must replace @"access-key-id"@ and
-- @"secret-access-key"@ with the respective values for your AWS account.
{-# LANGUAGE OverloadedStrings #-}
module Aws.Kinesis
( module Aws.Kinesis.Core
, module Aws.Kinesis.Types
, module Aws.Kinesis.Commands.CreateStream
, module Aws.Kinesis.Commands.DeleteStream
, module Aws.Kinesis.Commands.DescribeStream
, module Aws.Kinesis.Commands.GetRecords
, module Aws.Kinesis.Commands.GetShardIterator
, module Aws.Kinesis.Commands.ListStreams
, module Aws.Kinesis.Commands.MergeShards
, module Aws.Kinesis.Commands.PutRecord
, module Aws.Kinesis.Commands.PutRecords
, module Aws.Kinesis.Commands.SplitShard
) where
import Aws.Kinesis.Core
import Aws.Kinesis.Types
import Aws.Kinesis.Commands.CreateStream
import Aws.Kinesis.Commands.DeleteStream
import Aws.Kinesis.Commands.DescribeStream
import Aws.Kinesis.Commands.GetRecords
import Aws.Kinesis.Commands.GetShardIterator
import Aws.Kinesis.Commands.ListStreams
import Aws.Kinesis.Commands.MergeShards
import Aws.Kinesis.Commands.PutRecord
import Aws.Kinesis.Commands.PutRecords
import Aws.Kinesis.Commands.SplitShard
|
alephcloud/hs-aws-kinesis
|
src/Aws/Kinesis.hs
|
apache-2.0
| 2,788
| 0
| 5
| 346
| 232
| 181
| 51
| 26
| 0
|
{-
MinimaxLazy.hs
Copyright (c) 2014 by Sebastien Soudan.
Apache License Version 2.0, January 2004
-}
-- | Strategy based on a lazy implementation of the Minimax algorithm.
--
-- The game tree is NOT computed beforehand but generated up to a certain depth while it is evaluated.
-- The size of the heap is quite limited - it can fit in 3MB for a depth of 4.
-- The total amount of allocation is still important.
-- This implementation is slower than the one of "Minimax".
--
-- See also "Minimax", "MinimaxAlphaBeta"
module MinimaxLazy (doMove) where
import Board (PieceColor (..))
import Data.List
import State
-- | Lazy implementation of the minimax
-- Game tree is constructed as we go through it.
--
-- Relies on 'State.evalState' method to rate a given 'State'.
--
-- from wikipedia [http://en.wikipedia.org/wiki/Minimax]
--
-- function minimax(node, depth, maximizingPlayer)
-- if depth = 0 or node is a terminal node
-- return the heuristic value of node
-- if maximizingPlayer
-- bestValue := -∞
-- for each child of node
-- val := minimax(child, depth - 1, FALSE)
-- bestValue := max(bestValue, val);
-- return bestValue
-- else
-- bestValue := +∞
-- for each child of node
-- val := minimax(child, depth - 1, TRUE)
-- bestValue := min(bestValue, val);
-- return bestValue
-- (* Initial call for maximizing player *)
-- minimax(origin, depth, TRUE)
minimax :: SuperState -- ^ The current state
-> Int -- ^ The remaining depth to explore
-> Bool -- ^ Maximizing player?
-> Int -- ^ Returns the payoff of this branch
minimax state 0 _ = evalState state
minimax state depth maximizingPlayer = if maximizingPlayer then maximum $ map (\m -> minimax m (depth - 1) False) nextState
else minimum $ map (\m -> minimax m (depth - 1) True) nextState
where nextState = nextStates state
-- | Depth of the game tree to explore
defaultDepth :: Int
defaultDepth = 4
-- | Evaluate an option as defined by the 'SuperState' is would lead a player to.
evalOption :: SuperState -> PieceColor -> (Int, SuperState)
evalOption state color = (minimax state defaultDepth (color == Black), state)
-- | Compare two pair of ('Int', 'SuperState') based on the value of the first Int.
compareOption :: (Int, SuperState) -> (Int, SuperState) -> Ordering
compareOption (s1,_) (s2,_) = s1 `compare` s2
-- | Select the next move based on the minimax algorithm and the 'evalOption'/'compareOption' 'SuperState' comparison functions.
--
-- >>> doMove (State Board.initialBoard History.newHistory White, [])
-- -> move:
-- a6->a5
-- ---- B ----
-- a b c d e f g h
-- ┌────────────────┐
-- 0 │♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜ │
-- 1 │♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟ │
-- 2 │. . . . . . . . │
-- 3 │. . . . . . . . │
-- 4 │. . . . . . . . │
-- 5 │♙ . . . . . . . │
-- 6 │. ♙ ♙ ♙ ♙ ♙ ♙ ♙ │
-- 7 │♖ ♘ ♗ ♔ ♕ ♗ ♘ ♖ │
-- └────────────────┘
-- a b c d e f g h
-- ---- W ----
--
-- -> player: Black
-- -> score: 0
doMove :: SuperState -> SuperState
doMove s = snd $ optimizeBy compareOption options
where options = map (`evalOption` playerColor) (nextStates s)
playerColor = (getPlayer . fst) s
optimizeBy = case playerColor of White -> minimumBy
Black -> maximumBy
|
ssoudan/hsChess
|
src/MinimaxLazy.hs
|
apache-2.0
| 3,677
| 0
| 12
| 996
| 413
| 256
| 157
| 24
| 2
|
-- Copyright (c) 2015 Jonathan M. Lange <jml@mumak.net>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Utils ( hazardTestApp
, hazardTestApp'
, Utils.get
, getAs
, Utils.post
, postAs
, requiresAuth
, makeTestDeck
) where
import BasicPrelude
import Control.Monad.STM (atomically)
import qualified Data.ByteString as B
import qualified Data.ByteString.Base64 as Base64
import qualified Data.Text as Text
import Data.IORef
import Data.Maybe
import Network.HTTP.Types.Header (Header)
import Network.Wai (Application)
import Test.Hspec.Wai
import Web.Spock.Safe (spockAsApp, spockT)
import Haverer.Deck
import Hazard (hazardWeb', makeHazard)
testDeck :: FullDeck
testDeck = fromJust $ makeDeck [
Soldier
, Soldier
, Clown
, Minister
, Wizard
, Wizard
, Soldier
, Knight
, Knight
, Priestess
, Clown
, Soldier
, General
, Soldier
, Priestess
, Prince
]
makeTestApp :: IO ByteString -> IO FullDeck -> IO Application
makeTestApp passwords decks = do
hazard <- atomically makeHazard
spockAsApp $ spockT id $ hazardWeb' hazard passwords decks
hazardTestApp :: IO Application
hazardTestApp = makeTestApp (return "password") (return testDeck)
hazardTestApp' :: IORef FullDeck -> IO Application
hazardTestApp' decks = makeTestApp (return "password") (readIORef decks)
get url = request "GET" url [acceptJson] ""
post url = request "POST" url [acceptJson]
getAs username url = request "GET" url [authHeader username "password", acceptJson] ""
postAs username url = request "POST" url [authHeader username "password", acceptJson]
authHeader :: B.ByteString -> B.ByteString -> Header
authHeader username password = ("Authorization", B.concat ["Basic ", encodedCredentials])
where encodedCredentials = Base64.encode $ B.concat [username, ":", password]
acceptJson :: Header
acceptJson = ("Accept", "application/json")
requiresAuth :: ResponseMatcher
requiresAuth = "Basic authentication is required" { matchStatus = 401
, matchHeaders = [
"WWW-Authenticate" <:> "Basic realm=\"Hazard API\""
]
}
makeTestDeck :: Text -> FullDeck
makeTestDeck =
fromJust . makeDeck . map charToCard . textToString . Text.toLower
where
charToCard 's' = Soldier
charToCard 'c' = Clown
charToCard 'k' = Knight
charToCard 'p' = Priestess
charToCard 'w' = Wizard
charToCard 'g' = General
charToCard 'm' = Minister
charToCard 'x' = Prince
|
jml/hazard
|
tests/Utils.hs
|
apache-2.0
| 3,300
| 0
| 9
| 825
| 669
| 378
| 291
| 73
| 8
|
module PowerDivisibility.A048798 (a048798) where
import Helpers.Primes (primePowers)
a048798 :: Integer -> Integer
a048798 n = f $ primePowers n where
f = product . map (\(a, b) -> a ^ mod (-b) 3)
|
peterokagey/haskellOEIS
|
src/PowerDivisibility/A048798.hs
|
apache-2.0
| 200
| 0
| 14
| 36
| 87
| 48
| 39
| 5
| 1
|
stuff = if a == "hai" then putStrLn "Hai!" else putStrLn "pls"
a = "hai"
|
zackp30/programs
|
hs/stuff.hs
|
apache-2.0
| 78
| 0
| 6
| 20
| 29
| 15
| 14
| -1
| -1
|
eje13 :: [Int] -> Int
eje13 xs = sum (filter even (map (^2) xs))
|
tonilopezmr/Learning-Haskell
|
Exercises/2/Exercise_13.hs
|
apache-2.0
| 64
| 0
| 10
| 13
| 44
| 23
| 21
| 2
| 1
|
import Data.List (permutations, tails, nub, delete)
import Data.Set (Set)
import qualified Data.Set as Set
import Helpers.SetHelpers (flatMap)
import Helpers.ListHelpers (cartesianProduct)
import qualified Data.MemoCombinators as Memo
type ConfigurationState = Set [Int]
canonical :: Int -> [Int] -> [Int]
canonical n l = minimum $ concatMap f $ necklaces l where
f necklace = map incrementNecklace [1..n] where
incrementNecklace i = map ((`mod` n) . (+i)) necklace
necklaces :: [Int] -> [[Int]]
necklaces l = map (take len) $ take len initialSegments where
len = length l
initialSegments = tails $ concat $ repeat l
-- This is slow and should be memoized.
configurationSum :: Int -> [Int] -> [Int] -> Set [Int]
configurationSum = Memo.memo3 Memo.integral (Memo.list Memo.integral) (Memo.list Memo.integral) configurationSum' where
configurationSum' n c1 c2 = Set.fromList $ map (canonical n . zipWith (+) c1) $ necklaces c2
initialStates = Set.delete [0,0,0,0,0] . Set.fromList . configurations where
configurations n = map (canonical n) $ cartesianProduct n [1..n]
addAll :: Int -> [Int] -> Set [Int] -> Set [Int]
addAll n configuration configurationState = Set.delete (replicate n 0) $ flatMap (configurationSum n configuration) configurationState
nextGeneration :: Int -> ConfigurationState -> Set ConfigurationState
nextGeneration n configurationState = Set.map (`addAllN` configurationState) $ initialStates n where
addAllN = addAll n
nextGeneration5 :: ConfigurationState -> Set ConfigurationState
nextGeneration5 = nextGeneration 5
flippable :: Int -> Bool
flippable n = recurse (Set.singleton states) (Set.singleton states) where
states = initialStates n
recurse allKnown currentGeneration
| Set.null currentGeneration = error $ show allKnown
| Set.member Set.empty currentGeneration = True
| otherwise = recurse (Set.union allKnown nextGen) nextGen where
nextGen = Set.difference (flatMap (nextGeneration n) currentGeneration) allKnown
|
peterokagey/haskellOEIS
|
src/Sandbox/Sami/SpinningSwitches/CyclicGroup.hs
|
apache-2.0
| 2,032
| 0
| 13
| 354
| 720
| 375
| 345
| 35
| 1
|
-- | Convert back and forth between the 'Old.Doc' type of the @ansi-wl-pprint@
-- and the 'New.Doc' of the prettyprinter package. Useful in order to use the
-- @prettyprinter@ library together with another library that produces
-- @ansi-wl-pprint@ output, and vice versa.
--
-- @
-- ╭────────────────────╮ 'fromAnsiWlPprint' ╭────────────────────╮
-- │ 'Old.Doc' ├───────────────────────▷│ 'New.Doc' 'NewTerm.AnsiStyle' │
-- │ (ansi-wl-pprint) │◁───────────────────────┤ (prettyprinter) │
-- ╰────────────────────╯ 'toAnsiWlPprint' ╰────────────────────╯
-- @
--
-- These conversion functions work well, but strictly speaking they are __not__
-- inverses of each other. @ansi-wl-pprint@ supports slightly less features than
-- @prettyprinter@ – the latter has italics, and allows reacting on the
-- configured ribbon width via 'New.withPageWidth'.
module Prettyprinter.Convert.AnsiWlPprint (
fromAnsiWlPprint,
toAnsiWlPprint,
) where
import qualified Data.Text as T
import qualified Prettyprinter.Internal as New
import qualified Prettyprinter.Render.Terminal.Internal as NewTerm
import qualified System.Console.ANSI as Ansi
import qualified Text.PrettyPrint.ANSI.Leijen.Internal as Old
-- | @ansi-wl-pprint ───▷ prettyprinter@
fromAnsiWlPprint :: Old.Doc -> New.Doc NewTerm.AnsiStyle
fromAnsiWlPprint = \doc -> case doc of
Old.Fail -> New.Fail
Old.Empty -> New.Empty
Old.Char c -> New.Char c
Old.Text l t -> New.Text l (T.pack t)
Old.Line -> New.Line
Old.FlatAlt x y -> New.FlatAlt (go x) (go y)
Old.Cat x y -> New.Cat (go x) (go y)
Old.Nest i x -> New.Nest i (go x)
Old.Union x y -> New.Union (go x) (go y)
Old.Column f -> New.Column (go . f)
Old.Columns f -> New.WithPageWidth (go . f . convert)
where
convert :: New.PageWidth -> Maybe Int
convert (New.AvailablePerLine width _ribbon) = Just width
convert New.Unbounded = Nothing
Old.Nesting f -> New.Nesting (go . f)
Old.Color layer intensity color x ->
let convertLayerIntensity :: Ansi.ConsoleLayer -> Ansi.ColorIntensity -> NewTerm.Color -> NewTerm.AnsiStyle
convertLayerIntensity Ansi.Foreground Ansi.Dull = NewTerm.colorDull
convertLayerIntensity Ansi.Background Ansi.Dull = NewTerm.bgColorDull
convertLayerIntensity Ansi.Foreground Ansi.Vivid = NewTerm.color
convertLayerIntensity Ansi.Background Ansi.Vivid = NewTerm.bgColor
convertColor :: Ansi.Color -> NewTerm.AnsiStyle
convertColor c = convertLayerIntensity layer intensity (case c of
Ansi.Black -> NewTerm.Black
Ansi.Red -> NewTerm.Red
Ansi.Green -> NewTerm.Green
Ansi.Yellow -> NewTerm.Yellow
Ansi.Blue -> NewTerm.Blue
Ansi.Magenta -> NewTerm.Magenta
Ansi.Cyan -> NewTerm.Cyan
Ansi.White -> NewTerm.White )
in New.annotate (convertColor color) (go x)
Old.Intensify intensity x -> case intensity of
Ansi.BoldIntensity -> New.annotate NewTerm.bold (go x)
Ansi.FaintIntensity -> go x
Ansi.NormalIntensity -> go x
Old.Italicize i x -> case i of
False -> go x
True -> New.annotate NewTerm.italicized (go x)
Old.Underline _ x -> New.annotate NewTerm.underlined (go x)
Old.RestoreFormat{} -> error "Malformed input: RestoreFormat mayb only be used during rendering. Please report this as a bug."
where
go = fromAnsiWlPprint
-- | @prettyprinter ───▷ ansi-wl-pprint@
toAnsiWlPprint :: New.Doc NewTerm.AnsiStyle -> Old.Doc
toAnsiWlPprint = \doc -> case doc of
New.Fail -> Old.Fail
New.Empty -> Old.Empty
New.Char c -> Old.Char c
New.Text l t -> Old.Text l (T.unpack t)
New.Line -> Old.Line
New.FlatAlt x y -> Old.FlatAlt (go x) (go y)
New.Cat x y -> Old.Cat (go x) (go y)
New.Nest i x -> Old.Nest i (go x)
New.Union x y -> Old.Union (go x) (go y)
New.Column f -> Old.Column (go . f)
New.WithPageWidth f -> Old.Columns (go . f . convert)
where
convert :: Maybe Int -> New.PageWidth
convert Nothing = New.Unbounded
convert (Just width) = New.AvailablePerLine width 1.0
New.Nesting f -> Old.Nesting (go . f)
New.Annotated style x -> (convertFg . convertBg . convertBold . convertUnderlining) (go x)
-- Italics are unsupported by ansi-wl-pprint so we skip them
where
convertFg, convertBg, convertBold, convertUnderlining :: Old.Doc -> Old.Doc
convertFg = case NewTerm.ansiForeground style of
Nothing -> id
Just (intensity, color) -> convertColor True intensity color
convertBg = case NewTerm.ansiBackground style of
Nothing -> id
Just (intensity, color) -> convertColor False intensity color
convertBold = case NewTerm.ansiBold style of
Nothing -> id
Just NewTerm.Bold -> Old.bold
convertUnderlining = case NewTerm.ansiUnderlining style of
Nothing -> id
Just NewTerm.Underlined -> Old.underline
convertColor
:: Bool -- True = foreground, False = background
-> NewTerm.Intensity
-> NewTerm.Color
-> Old.Doc
-> Old.Doc
convertColor True NewTerm.Vivid NewTerm.Black = Old.black
convertColor True NewTerm.Vivid NewTerm.Red = Old.red
convertColor True NewTerm.Vivid NewTerm.Green = Old.green
convertColor True NewTerm.Vivid NewTerm.Yellow = Old.yellow
convertColor True NewTerm.Vivid NewTerm.Blue = Old.blue
convertColor True NewTerm.Vivid NewTerm.Magenta = Old.magenta
convertColor True NewTerm.Vivid NewTerm.Cyan = Old.cyan
convertColor True NewTerm.Vivid NewTerm.White = Old.white
convertColor True NewTerm.Dull NewTerm.Black = Old.dullblack
convertColor True NewTerm.Dull NewTerm.Red = Old.dullred
convertColor True NewTerm.Dull NewTerm.Green = Old.dullgreen
convertColor True NewTerm.Dull NewTerm.Yellow = Old.dullyellow
convertColor True NewTerm.Dull NewTerm.Blue = Old.dullblue
convertColor True NewTerm.Dull NewTerm.Magenta = Old.dullmagenta
convertColor True NewTerm.Dull NewTerm.Cyan = Old.dullcyan
convertColor True NewTerm.Dull NewTerm.White = Old.dullwhite
convertColor False NewTerm.Vivid NewTerm.Black = Old.onblack
convertColor False NewTerm.Vivid NewTerm.Red = Old.onred
convertColor False NewTerm.Vivid NewTerm.Green = Old.ongreen
convertColor False NewTerm.Vivid NewTerm.Yellow = Old.onyellow
convertColor False NewTerm.Vivid NewTerm.Blue = Old.onblue
convertColor False NewTerm.Vivid NewTerm.Magenta = Old.onmagenta
convertColor False NewTerm.Vivid NewTerm.Cyan = Old.oncyan
convertColor False NewTerm.Vivid NewTerm.White = Old.onwhite
convertColor False NewTerm.Dull NewTerm.Black = Old.ondullblack
convertColor False NewTerm.Dull NewTerm.Red = Old.ondullred
convertColor False NewTerm.Dull NewTerm.Green = Old.ondullgreen
convertColor False NewTerm.Dull NewTerm.Yellow = Old.ondullyellow
convertColor False NewTerm.Dull NewTerm.Blue = Old.ondullblue
convertColor False NewTerm.Dull NewTerm.Magenta = Old.ondullmagenta
convertColor False NewTerm.Dull NewTerm.Cyan = Old.ondullcyan
convertColor False NewTerm.Dull NewTerm.White = Old.ondullwhite
where
go = toAnsiWlPprint
|
quchen/prettyprinter
|
prettyprinter-convert-ansi-wl-pprint/src/Prettyprinter/Convert/AnsiWlPprint.hs
|
bsd-2-clause
| 8,135
| 0
| 18
| 2,068
| 2,003
| 1,011
| 992
| 122
| 49
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QCoreApplication_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:32
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Core.QCoreApplication_h where
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Foreign.Marshal.Array
instance QunSetUserMethod (QCoreApplication ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QCoreApplication_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QCoreApplication_unSetUserMethod" qtc_QCoreApplication_unSetUserMethod :: Ptr (TQCoreApplication a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QCoreApplicationSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QCoreApplication_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QCoreApplication ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QCoreApplication_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QCoreApplicationSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QCoreApplication_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QCoreApplication ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QCoreApplication_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QCoreApplicationSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QCoreApplication_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QCoreApplication ()) (QCoreApplication x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QCoreApplication setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QCoreApplication_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QCoreApplication_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQCoreApplication x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QCoreApplication_setUserMethod" qtc_QCoreApplication_setUserMethod :: Ptr (TQCoreApplication a) -> CInt -> Ptr (Ptr (TQCoreApplication x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QCoreApplication :: (Ptr (TQCoreApplication x0) -> IO ()) -> IO (FunPtr (Ptr (TQCoreApplication x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QCoreApplication_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QCoreApplicationSc a) (QCoreApplication x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QCoreApplication setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QCoreApplication_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QCoreApplication_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQCoreApplication x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QCoreApplication ()) (QCoreApplication x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QCoreApplication setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QCoreApplication_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QCoreApplication_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQCoreApplication x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QCoreApplication_setUserMethodVariant" qtc_QCoreApplication_setUserMethodVariant :: Ptr (TQCoreApplication a) -> CInt -> Ptr (Ptr (TQCoreApplication x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QCoreApplication :: (Ptr (TQCoreApplication x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQCoreApplication x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QCoreApplication_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QCoreApplicationSc a) (QCoreApplication x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QCoreApplication setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QCoreApplication_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QCoreApplication_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQCoreApplication x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QCoreApplication ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QCoreApplication_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QCoreApplication_unSetHandler" qtc_QCoreApplication_unSetHandler :: Ptr (TQCoreApplication a) -> CWString -> IO (CBool)
instance QunSetHandler (QCoreApplicationSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QCoreApplication_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QCoreApplication ()) (QCoreApplication x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QCoreApplication1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QCoreApplication1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QCoreApplication_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQCoreApplication x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qCoreApplicationFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QCoreApplication_setHandler1" qtc_QCoreApplication_setHandler1 :: Ptr (TQCoreApplication a) -> CWString -> Ptr (Ptr (TQCoreApplication x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QCoreApplication1 :: (Ptr (TQCoreApplication x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQCoreApplication x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QCoreApplication1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QCoreApplicationSc a) (QCoreApplication x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QCoreApplication1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QCoreApplication1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QCoreApplication_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQCoreApplication x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qCoreApplicationFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qnotify_h (QCoreApplication ()) ((QObject t1, QEvent t2)) where
notify_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QCoreApplication_notify cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QCoreApplication_notify" qtc_QCoreApplication_notify :: Ptr (TQCoreApplication a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance Qnotify_h (QCoreApplicationSc a) ((QObject t1, QEvent t2)) where
notify_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QCoreApplication_notify cobj_x0 cobj_x1 cobj_x2
instance QeventFilter_h (QCoreApplication ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QCoreApplication_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QCoreApplication_eventFilter" qtc_QCoreApplication_eventFilter :: Ptr (TQCoreApplication a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QCoreApplicationSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QCoreApplication_eventFilter cobj_x0 cobj_x1 cobj_x2
|
uduki/hsQt
|
Qtc/Core/QCoreApplication_h.hs
|
bsd-2-clause
| 14,150
| 0
| 18
| 2,991
| 4,422
| 2,114
| 2,308
| -1
| -1
|
{-# LANGUAGE BangPatterns, ScopedTypeVariables #-}
{-# OPTIONS_HADDOCK hide #-}
-- |
-- Module : Numeric.SpecFunctions.Internal
-- Copyright : (c) 2009, 2011, 2012 Bryan O'Sullivan
-- License : BSD3
--
-- Maintainer : bos@serpentine.com
-- Stability : experimental
-- Portability : portable
--
-- Internal module with implementation of special functions.
module Numeric.SpecFunctions.Internal
( module Numeric.SpecFunctions.Internal
, Compat.log1p
, Compat.expm1
) where
import Control.Applicative
import Data.Bits ((.&.), (.|.), shiftR)
import Data.Int (Int64)
import Data.Word (Word)
import Data.Default.Class
import qualified Data.Vector.Unboxed as U
import Data.Vector.Unboxed ((!))
import Text.Printf
import Numeric.Polynomial.Chebyshev (chebyshevBroucke)
import Numeric.Polynomial (evaluatePolynomial, evaluatePolynomialL, evaluateEvenPolynomialL
,evaluateOddPolynomialL)
import Numeric.RootFinding (Root(..), newtonRaphson, NewtonParam(..), Tolerance(..))
import Numeric.Series
import Numeric.MathFunctions.Constants
import Numeric.SpecFunctions.Compat (log1p)
import qualified Numeric.SpecFunctions.Compat as Compat
----------------------------------------------------------------
-- Error function
----------------------------------------------------------------
-- | Error function.
--
-- \[
-- \operatorname{erf}(x) = \frac{2}{\sqrt{\pi}} \int_{0}^{x} \exp(-t^2) dt
-- \]
--
-- Function limits are:
--
-- \[
-- \begin{aligned}
-- &\operatorname{erf}(-\infty) &=& -1 \\
-- &\operatorname{erf}(0) &=& \phantom{-}\,0 \\
-- &\operatorname{erf}(+\infty) &=& \phantom{-}\,1 \\
-- \end{aligned}
-- \]
erf :: Double -> Double
erf = Compat.erf
{-# INLINE erf #-}
-- | Complementary error function.
--
-- \[
-- \operatorname{erfc}(x) = 1 - \operatorname{erf}(x)
-- \]
--
-- Function limits are:
--
-- \[
-- \begin{aligned}
-- &\operatorname{erf}(-\infty) &=&\, 2 \\
-- &\operatorname{erf}(0) &=&\, 1 \\
-- &\operatorname{erf}(+\infty) &=&\, 0 \\
-- \end{aligned}
-- \]
erfc :: Double -> Double
erfc = Compat.erfc
{-# INLINE erfc #-}
-- | Inverse of 'erf'.
invErf :: Double -- ^ /p/ ∈ [-1,1]
-> Double
invErf p
| p == 1 = m_pos_inf
| p == -1 = m_neg_inf
| p < 1 && p > -1 = if p > 0 then r else -r
| otherwise = error "invErf: p must in [-1,1] range"
where
-- We solve equation same as in invErfc. We're able to ruse same
-- Halley step by solving equation:
-- > pp - erf x = 0
-- instead of
-- > erf x - pp = 0
pp = abs p
r = step $ step $ guessInvErfc $ 1 - pp
step x = invErfcHalleyStep (pp - erf x) x
-- | Inverse of 'erfc'.
invErfc :: Double -- ^ /p/ ∈ [0,2]
-> Double
invErfc p
| p == 2 = m_neg_inf
| p == 0 = m_pos_inf
| p >0 && p < 2 = if p <= 1 then r else -r
| otherwise = modErr $ "invErfc: p must be in [0,2] got " ++ show p
where
pp | p <= 1 = p
| otherwise = 2 - p
-- We perform 2 Halley steps in order to get to solution
r = step $ step $ guessInvErfc pp
step x = invErfcHalleyStep (erfc x - pp) x
-- Initial guess for invErfc & invErf
guessInvErfc :: Double -> Double
guessInvErfc p
= -0.70711 * ((2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t)
where
t = sqrt $ -2 * log( 0.5 * p)
-- Halley step for solving invErfc
invErfcHalleyStep :: Double -> Double -> Double
invErfcHalleyStep err x
= x + err / (1.12837916709551257 * exp(-x * x) - x * err)
----------------------------------------------------------------
-- Gamma function
----------------------------------------------------------------
data L = L {-# UNPACK #-} !Double {-# UNPACK #-} !Double
-- | Compute the logarithm of the gamma function, Γ(/x/).
--
-- \[
-- \Gamma(x) = \int_0^{\infty}t^{x-1}e^{-t}\,dt = (x - 1)!
-- \]
--
-- This implementation uses Lanczos approximation. It gives 14 or more
-- significant decimal digits, except around /x/ = 1 and /x/ = 2,
-- where the function goes to zero.
--
-- Returns ∞ if the input is outside of the range (0 < /x/
-- ≤ 1e305).
logGamma :: Double -> Double
logGamma z
| z <= 0 = m_pos_inf
-- For very small values z we can just use Laurent expansion
| z < m_sqrt_eps = log (1/z - m_eulerMascheroni)
-- For z<1 we use recurrence. Γ(z+1) = z·Γ(z) Note that in order to
-- avoid precision loss we have to compute parameter to
-- approximations here:
--
-- > (z + 1) - 1 = z
-- > (z + 1) - 2 = z - 1
--
-- Simple passing (z + 1) to piecewise approxiations and computing
-- difference leads to bad loss of precision near 1.
-- This is reason lgamma1_15 & lgamma15_2 have three parameters
| z < 0.5 = lgamma1_15 z (z - 1) - log z
| z < 1 = lgamma15_2 z (z - 1) - log z
-- Piecewise polynomial approximations
| z <= 1.5 = lgamma1_15 (z - 1) (z - 2)
| z < 2 = lgamma15_2 (z - 1) (z - 2)
| z < 15 = lgammaSmall z
-- Otherwise we switch to Lanczos approximation
| otherwise = lanczosApprox z
-- | Synonym for 'logGamma'. Retained for compatibility
logGammaL :: Double -> Double
logGammaL = logGamma
{-# DEPRECATED logGammaL "Use logGamma instead" #-}
-- Polynomial expansion used in interval (1,1.5]
--
-- > logΓ(z) = (z-1)(z-2)(Y + R(z-1))
lgamma1_15 :: Double -> Double -> Double
lgamma1_15 zm1 zm2
= r * y + r * ( evaluatePolynomial zm1 tableLogGamma_1_15P
/ evaluatePolynomial zm1 tableLogGamma_1_15Q
)
where
r = zm1 * zm2
y = 0.52815341949462890625
tableLogGamma_1_15P,tableLogGamma_1_15Q :: U.Vector Double
tableLogGamma_1_15P = U.fromList
[ 0.490622454069039543534e-1
, -0.969117530159521214579e-1
, -0.414983358359495381969e0
, -0.406567124211938417342e0
, -0.158413586390692192217e0
, -0.240149820648571559892e-1
, -0.100346687696279557415e-2
]
{-# NOINLINE tableLogGamma_1_15P #-}
tableLogGamma_1_15Q = U.fromList
[ 1
, 0.302349829846463038743e1
, 0.348739585360723852576e1
, 0.191415588274426679201e1
, 0.507137738614363510846e0
, 0.577039722690451849648e-1
, 0.195768102601107189171e-2
]
{-# NOINLINE tableLogGamma_1_15Q #-}
-- Polynomial expansion used in interval (1.5,2)
--
-- > logΓ(z) = (2-z)(1-z)(Y + R(2-z))
lgamma15_2 :: Double -> Double -> Double
lgamma15_2 zm1 zm2
= r * y + r * ( evaluatePolynomial (-zm2) tableLogGamma_15_2P
/ evaluatePolynomial (-zm2) tableLogGamma_15_2Q
)
where
r = zm1 * zm2
y = 0.452017307281494140625
tableLogGamma_15_2P,tableLogGamma_15_2Q :: U.Vector Double
tableLogGamma_15_2P = U.fromList
[ -0.292329721830270012337e-1
, 0.144216267757192309184e0
, -0.142440390738631274135e0
, 0.542809694055053558157e-1
, -0.850535976868336437746e-2
, 0.431171342679297331241e-3
]
{-# NOINLINE tableLogGamma_15_2P #-}
tableLogGamma_15_2Q = U.fromList
[ 1
, -0.150169356054485044494e1
, 0.846973248876495016101e0
, -0.220095151814995745555e0
, 0.25582797155975869989e-1
, -0.100666795539143372762e-2
, -0.827193521891290553639e-6
]
{-# NOINLINE tableLogGamma_15_2Q #-}
-- Polynomial expansion used in interval (2,3)
--
-- > logΓ(z) = (z - 2)(z + 1)(Y + R(z-2))
lgamma2_3 :: Double -> Double
lgamma2_3 z
= r * y + r * ( evaluatePolynomial zm2 tableLogGamma_2_3P
/ evaluatePolynomial zm2 tableLogGamma_2_3Q
)
where
r = zm2 * (z + 1)
zm2 = z - 2
y = 0.158963680267333984375e0
tableLogGamma_2_3P,tableLogGamma_2_3Q :: U.Vector Double
tableLogGamma_2_3P = U.fromList
[ -0.180355685678449379109e-1
, 0.25126649619989678683e-1
, 0.494103151567532234274e-1
, 0.172491608709613993966e-1
, -0.259453563205438108893e-3
, -0.541009869215204396339e-3
, -0.324588649825948492091e-4
]
{-# NOINLINE tableLogGamma_2_3P #-}
tableLogGamma_2_3Q = U.fromList
[ 1
, 0.196202987197795200688e1
, 0.148019669424231326694e1
, 0.541391432071720958364e0
, 0.988504251128010129477e-1
, 0.82130967464889339326e-2
, 0.224936291922115757597e-3
, -0.223352763208617092964e-6
]
{-# NOINLINE tableLogGamma_2_3Q #-}
-- For small z we can just use Gamma function recurrence and reduce
-- problem to interval [2,3] and use polynomial approximation
-- there. Surpringly it gives very good precision
lgammaSmall :: Double -> Double
lgammaSmall = go 0
where
go acc z | z < 3 = acc + lgamma2_3 z
| otherwise = go (acc + log zm1) zm1
where
zm1 = z - 1
-- Lanczos approximation for gamma function.
--
-- > Γ(z) = sqrt(2π)(z + g - 0.5)^(z - 0.5)·exp{-(z + g - 0.5)}·A_g(z)
--
-- Coeffients are taken from boost. Constants are absorbed into
-- polynomial's coefficients.
lanczosApprox :: Double -> Double
lanczosApprox z
= (log (z + g - 0.5) - 1) * (z - 0.5)
+ log (evalRatio tableLanczos z)
where
g = 6.024680040776729583740234375
tableLanczos :: U.Vector (Double,Double)
{-# NOINLINE tableLanczos #-}
tableLanczos = U.fromList
[ (56906521.91347156388090791033559122686859 , 0)
, (103794043.1163445451906271053616070238554 , 39916800)
, (86363131.28813859145546927288977868422342 , 120543840)
, (43338889.32467613834773723740590533316085 , 150917976)
, (14605578.08768506808414169982791359218571 , 105258076)
, (3481712.15498064590882071018964774556468 , 45995730)
, (601859.6171681098786670226533699352302507 , 13339535)
, (75999.29304014542649875303443598909137092 , 2637558)
, (6955.999602515376140356310115515198987526 , 357423)
, (449.9445569063168119446858607650988409623 , 32670)
, (19.51992788247617482847860966235652136208 , 1925)
, (0.5098416655656676188125178644804694509993 , 66)
, (0.006061842346248906525783753964555936883222 , 1)
]
-- Evaluate rational function. Polynomials in both numerator and
-- denominator must have same order. Function seems to be too specific
-- so it's not exposed
--
-- Special care taken in order to avoid overflow for large values of x
evalRatio :: U.Vector (Double,Double) -> Double -> Double
evalRatio coef x
| x > 1 = fini $ U.foldl' stepL (L 0 0) coef
| otherwise = fini $ U.foldr' stepR (L 0 0) coef
where
fini (L num den) = num / den
stepR (a,b) (L num den) = L (num * x + a) (den * x + b)
stepL (L num den) (a,b) = L (num * rx + a) (den * rx + b)
rx = recip x
-- |
-- Compute the log gamma correction factor for Stirling
-- approximation for @x@ ≥ 10. This correction factor is
-- suitable for an alternate (but less numerically accurate)
-- definition of 'logGamma':
--
-- \[
-- \log\Gamma(x) = \frac{1}{2}\log(2\pi) + (x-\frac{1}{2})\log x - x + \operatorname{logGammaCorrection}(x)
-- \]
logGammaCorrection :: Double -> Double
logGammaCorrection x
| x < 10 = m_NaN
| x < big = chebyshevBroucke (t * t * 2 - 1) coeffs / x
| otherwise = 1 / (x * 12)
where
big = 94906265.62425156
t = 10 / x
coeffs = U.fromList [
0.1666389480451863247205729650822e+0,
-0.1384948176067563840732986059135e-4,
0.9810825646924729426157171547487e-8,
-0.1809129475572494194263306266719e-10,
0.6221098041892605227126015543416e-13,
-0.3399615005417721944303330599666e-15,
0.2683181998482698748957538846666e-17
]
-- | Compute the normalized lower incomplete gamma function
-- γ(/z/,/x/). Normalization means that γ(/z/,∞)=1
--
-- \[
-- \gamma(z,x) = \frac{1}{\Gamma(z)}\int_0^{x}t^{z-1}e^{-t}\,dt
-- \]
--
-- Uses Algorithm AS 239 by Shea.
incompleteGamma :: Double -- ^ /z/ ∈ (0,∞)
-> Double -- ^ /x/ ∈ (0,∞)
-> Double
-- Notation used:
-- + P(a,x) - regularized lower incomplete gamma
-- + Q(a,x) - regularized upper incomplete gamma
incompleteGamma a x
| a <= 0 || x < 0 = error
$ "incompleteGamma: Domain error z=" ++ show a ++ " x=" ++ show x
| x == 0 = 0
| x == m_pos_inf = 1
-- For very small x we use following expansion for P:
--
-- See http://functions.wolfram.com/GammaBetaErf/GammaRegularized/06/01/05/01/01/
| x < sqrt m_epsilon && a > 1
= x**a / a / exp (logGamma a) * (1 - a*x / (a + 1))
| x < 0.5 = case () of
_| (-0.4)/log x < a -> taylorSeriesP
| otherwise -> taylorSeriesComplQ
| x < 1.1 = case () of
_| 0.75*x < a -> taylorSeriesP
| otherwise -> taylorSeriesComplQ
| a > 20 && useTemme = uniformExpansion
| x - (1 / (3 * x)) < a = taylorSeriesP
| otherwise = contFraction
where
mu = (x - a) / a
useTemme = (a > 200 && 20/a > mu*mu)
|| (abs mu < 0.4)
-- Gautschi's algorithm.
--
-- Evaluate series for P(a,x). See [Temme1994] Eq. 5.5 and [NOTE:
-- incompleteGamma.taylorP]
factorP
| a < 10 = x ** a
/ (exp x * exp (logGamma (a + 1)))
| a < 1182.5 = (x * exp 1 / a) ** a
/ exp x
/ sqrt (2*pi*a)
/ exp (logGammaCorrection a)
| otherwise = (x * exp 1 / a * exp (-x/a)) ** a
/ sqrt (2*pi*a)
/ exp (logGammaCorrection a)
taylorSeriesP
= sumPowerSeries x (scanSequence (/) 1 $ enumSequenceFrom (a+1))
* factorP
-- Series for 1-Q(a,x). See [Temme1994] Eq. 5.5
taylorSeriesComplQ
= sumPowerSeries (-x) (scanSequence (/) 1 (enumSequenceFrom 1) / enumSequenceFrom a)
* x**a / exp(logGamma a)
-- Legendre continued fractions
contFraction = 1 - ( exp ( log x * a - x - logGamma a )
/ evalContFractionB frac
)
where
frac = (\k -> (k*(a-k), x - a + 2*k + 1)) <$> enumSequenceFrom 0
-- Evaluation based on uniform expansions. See [Temme1994] 5.2
uniformExpansion =
let -- Coefficients f_m in paper
fm :: U.Vector Double
fm = U.fromList [ 1.00000000000000000000e+00
,-3.33333333333333370341e-01
, 8.33333333333333287074e-02
,-1.48148148148148153802e-02
, 1.15740740740740734316e-03
, 3.52733686067019369930e-04
,-1.78755144032921825352e-04
, 3.91926317852243766954e-05
,-2.18544851067999240532e-06
,-1.85406221071515996597e-06
, 8.29671134095308545622e-07
,-1.76659527368260808474e-07
, 6.70785354340149841119e-09
, 1.02618097842403069078e-08
,-4.38203601845335376897e-09
, 9.14769958223679020897e-10
,-2.55141939949462514346e-11
,-5.83077213255042560744e-11
, 2.43619480206674150369e-11
,-5.02766928011417632057e-12
, 1.10043920319561347525e-13
, 3.37176326240098513631e-13
]
y = - log1pmx mu
eta = sqrt (2 * y) * signum mu
-- Evaluate S_α (Eq. 5.9)
loop !_ !_ u 0 = u
loop bm1 bm0 u i = let t = (fm ! i) + (fromIntegral i + 1)*bm1 / a
u' = eta * u + t
in loop bm0 t u' (i-1)
s_a = let n = U.length fm
in loop (fm ! (n-1)) (fm ! (n-2)) 0 (n-3)
/ exp (logGammaCorrection a)
in 1/2 * erfc(-eta*sqrt(a/2)) - exp(-(a*y)) / sqrt (2*pi*a) * s_a
-- Adapted from Numerical Recipes §6.2.1
-- | Inverse incomplete gamma function. It's approximately inverse of
-- 'incompleteGamma' for the same /z/. So following equality
-- approximately holds:
--
-- > invIncompleteGamma z . incompleteGamma z ≈ id
invIncompleteGamma :: Double -- ^ /z/ ∈ (0,∞)
-> Double -- ^ /p/ ∈ [0,1]
-> Double
invIncompleteGamma a p
| a <= 0 =
modErr $ printf "invIncompleteGamma: a must be positive. a=%g p=%g" a p
| p < 0 || p > 1 =
modErr $ printf "invIncompleteGamma: p must be in [0,1] range. a=%g p=%g" a p
| p == 0 = 0
| p == 1 = 1 / 0
| otherwise = loop 0 guess
where
-- Solve equation γ(a,x) = p using Halley method
loop :: Int -> Double -> Double
loop i x
| i >= 12 = x'
-- For small s derivative becomes approximately 1/x*exp(-x) and
-- skyrockets for small x. If it happens correct answer is 0.
| isInfinite f' = 0
| abs dx < eps * x' = x'
| otherwise = loop (i + 1) x'
where
-- Value of γ(a,x) - p
f = incompleteGamma a x - p
-- dγ(a,x)/dx
f' | a > 1 = afac * exp( -(x - a1) + a1 * (log x - lna1))
| otherwise = exp( -x + a1 * log x - gln)
u = f / f'
-- Halley correction to Newton-Rapson step
corr = u * (a1 / x - 1)
dx = u / (1 - 0.5 * min 1.0 corr)
-- New approximation to x
x' | x < dx = 0.5 * x -- Do not go below 0
| otherwise = x - dx
-- Calculate inital guess for root
guess
--
| a > 1 =
let t = sqrt $ -2 * log(if p < 0.5 then p else 1 - p)
x1 = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t
x2 = if p < 0.5 then -x1 else x1
in max 1e-3 (a * (1 - 1/(9*a) - x2 / (3 * sqrt a)) ** 3)
-- For a <= 1 use following approximations:
-- γ(a,1) ≈ 0.253a + 0.12a²
--
-- γ(a,x) ≈ γ(a,1)·x^a x < 1
-- γ(a,x) ≈ γ(a,1) + (1 - γ(a,1))(1 - exp(1 - x)) x >= 1
| otherwise =
let t = 1 - a * (0.253 + a*0.12)
in if p < t
then (p / t) ** (1 / a)
else 1 - log( 1 - (p-t) / (1-t))
-- Constants
a1 = a - 1
lna1 = log a1
afac = exp( a1 * (lna1 - 1) - gln )
gln = logGamma a
eps = 1e-8
----------------------------------------------------------------
-- Beta function
----------------------------------------------------------------
-- | Compute the natural logarithm of the beta function.
--
-- \[
-- B(a,b) = \int_0^1 t^{a-1}(1-t)^{b-1}\,dt = \frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)}
-- \]
logBeta
:: Double -- ^ /a/ > 0
-> Double -- ^ /b/ > 0
-> Double
logBeta a b
| p < 0 = m_NaN
| p == 0 = m_pos_inf
| p >= 10 = allStirling
| q >= 10 = twoStirling
-- This order of summands marginally improves precision
| otherwise = logGamma p + (logGamma q - logGamma pq)
where
p = min a b
q = max a b
ppq = p / pq
pq = p + q
-- When both parameters are large than 10 we can use Stirling
-- approximation with correction. It's more precise than sum of
-- logarithms of gamma functions
allStirling
= log q * (-0.5)
+ m_ln_sqrt_2_pi
+ logGammaCorrection p
+ (logGammaCorrection q - logGammaCorrection pq)
+ (p - 0.5) * log ppq
+ q * log1p(-ppq)
-- Otherwise only two of three gamma functions use Stirling
-- approximation
twoStirling
= logGamma p
+ (logGammaCorrection q - logGammaCorrection pq)
+ p
- p * log pq
+ (q - 0.5) * log1p(-ppq)
-- | Regularized incomplete beta function.
--
-- \[
-- I(x;a,b) = \frac{1}{B(a,b)} \int_0^x t^{a-1}(1-t)^{b-1}\,dt
-- \]
--
-- Uses algorithm AS63 by Majumder and Bhattachrjee and quadrature
-- approximation for large /p/ and /q/.
incompleteBeta :: Double -- ^ /a/ > 0
-> Double -- ^ /b/ > 0
-> Double -- ^ /x/, must lie in [0,1] range
-> Double
incompleteBeta p q = incompleteBeta_ (logBeta p q) p q
-- | Regularized incomplete beta function. Same as 'incompleteBeta'
-- but also takes logarithm of beta function as parameter.
incompleteBeta_ :: Double -- ^ logarithm of beta function for given /p/ and /q/
-> Double -- ^ /a/ > 0
-> Double -- ^ /b/ > 0
-> Double -- ^ /x/, must lie in [0,1] range
-> Double
incompleteBeta_ beta p q x
| p <= 0 || q <= 0 =
modErr $ printf "incompleteBeta_: p <= 0 || q <= 0. p=%g q=%g x=%g" p q x
| x < 0 || x > 1 || isNaN x =
modErr $ printf "incompleteBeta_: x out of [0,1] range. p=%g q=%g x=%g" p q x
| x == 0 || x == 1 = x
| p >= (p+q) * x = incompleteBetaWorker beta p q x
| otherwise = 1 - incompleteBetaWorker beta q p (1 - x)
-- Approximation of incomplete beta by quandrature.
--
-- Note that x =< p/(p+q)
incompleteBetaApprox :: Double -> Double -> Double -> Double -> Double
incompleteBetaApprox beta p q x
| ans > 0 = 1 - ans
| otherwise = -ans
where
-- Constants
p1 = p - 1
q1 = q - 1
mu = p / (p + q)
lnmu = log mu
lnmuc = log1p (-mu)
-- Upper limit for integration
xu = max 0 $ min (mu - 10*t) (x - 5*t)
where
t = sqrt $ p*q / ( (p+q) * (p+q) * (p + q + 1) )
-- Calculate incomplete beta by quadrature
go y w = let t = x + (xu - x) * y
in w * exp( p1 * (log t - lnmu) + q1 * (log(1-t) - lnmuc) )
s = U.sum $ U.zipWith go coefY coefW
ans = s * (xu - x) * exp( p1 * lnmu + q1 * lnmuc - beta )
-- Worker for incomplete beta function. It is separate function to
-- avoid confusion with parameter during parameter swapping
incompleteBetaWorker :: Double -> Double -> Double -> Double -> Double
incompleteBetaWorker beta p q x
-- For very large p and q this method becomes very slow so another
-- method is used.
| p > 3000 && q > 3000 = incompleteBetaApprox beta p q x
| otherwise = loop (p+q) (truncate $ q + cx * (p+q)) 1 1 1
where
-- Constants
eps = 1e-15
cx = 1 - x
-- Common multiplies for expansion. Accurate calculation is a bit
-- tricky. Performing calculation in log-domain leads to slight
-- loss of precision for small x, while using ** prone to
-- underflows.
--
-- If either beta function of x**p·(1-x)**(q-1) underflows we
-- switch to log domain. It could waste work but there's no easy
-- switch criterion.
factor
| beta < m_min_log || prod < m_tiny = exp( p * log x + (q - 1) * log cx - beta)
| otherwise = prod / exp beta
where
prod = x**p * cx**(q - 1)
-- Soper's expansion of incomplete beta function
loop !psq (ns :: Int) ai term betain
| done = betain' * factor / p
| otherwise = loop psq' (ns - 1) (ai + 1) term' betain'
where
-- New values
term' = term * fact / (p + ai)
betain' = betain + term'
fact | ns > 0 = (q - ai) * x/cx
| ns == 0 = (q - ai) * x
| otherwise = psq * x
-- Iterations are complete
done = db <= eps && db <= eps*betain' where db = abs term'
psq' = if ns < 0 then psq + 1 else psq
-- | Compute inverse of regularized incomplete beta function. Uses
-- initial approximation from AS109, AS64 and Halley method to solve
-- equation.
invIncompleteBeta :: Double -- ^ /a/ > 0
-> Double -- ^ /b/ > 0
-> Double -- ^ /x/ ∈ [0,1]
-> Double
invIncompleteBeta p q a
| p <= 0 || q <= 0 =
modErr $ printf "invIncompleteBeta p <= 0 || q <= 0. p=%g q=%g a=%g" p q a
| a < 0 || a > 1 =
modErr $ printf "invIncompleteBeta x must be in [0,1]. p=%g q=%g a=%g" p q a
| a == 0 || a == 1 = a
| otherwise = invIncompleteBetaWorker (logBeta p q) p q a
invIncompleteBetaWorker :: Double -> Double -> Double -> Double -> Double
invIncompleteBetaWorker beta a b p = loop (0::Int) (invIncBetaGuess beta a b p)
where
a1 = a - 1
b1 = b - 1
-- Solve equation using Halley method
loop !i !x
-- We cannot continue at this point so we simply return `x'
| x == 0 || x == 1 = x
-- When derivative becomes infinite we cannot continue
-- iterations. It can only happen in vicinity of 0 or 1. It's
-- hardly possible to get good answer in such circumstances but
-- `x' is already reasonable.
| isInfinite f' = x
-- Iterations limit reached. Most of the time solution will
-- converge to answer because of discreteness of Double. But
-- solution have good precision already.
| i >= 10 = x
-- Solution converges
| abs dx <= 16 * m_epsilon * x = x'
| otherwise = loop (i+1) x'
where
-- Calculate Halley step.
f = incompleteBeta_ beta a b x - p
f' = exp $ a1 * log x + b1 * log1p (-x) - beta
u = f / f'
-- We bound Halley correction to Newton-Raphson to (-1,1) range
corr | d > 1 = 1
| d < -1 = -1
| isNaN d = 0
| otherwise = d
where
d = u * (a1 / x - b1 / (1 - x))
dx = u / (1 - 0.5 * corr)
-- Next approximation. If Halley step leads us out of [0,1]
-- range we revert to bisection.
x' | z < 0 = x / 2
| z > 1 = (x + 1) / 2
| otherwise = z
where z = x - dx
-- Calculate initial guess for inverse incomplete beta function.
invIncBetaGuess :: Double -> Double -> Double -> Double -> Double
-- Calculate initial guess. for solving equation for inverse incomplete beta.
-- It's really hodgepodge of different approximations accumulated over years.
--
-- Equations are referred to by name of paper and number e.g. [AS64 2]
-- In AS64 papers equations are not numbered so they are refered to by
-- number of appearance starting from definition of incomplete beta.
invIncBetaGuess beta a b p
-- If both a and b are less than 1 incomplete beta have inflection
-- point.
--
-- > x = (1 - a) / (2 - a - b)
--
-- We approximate incomplete beta by neglecting one of factors under
-- integral and then rescaling result of integration into [0,1]
-- range.
| a < 1 && b < 1 =
let x_infl = (1 - a) / (2 - a - b)
p_infl = incompleteBeta a b x_infl
x | p < p_infl = let xg = (a * p * exp beta) ** (1/a) in xg / (1+xg)
| otherwise = let xg = (b * (1-p) * exp beta) ** (1/b) in 1 - xg/(1+xg)
in x
-- If both a and b larger or equal that 1 but not too big we use
-- same approximation as above but calculate it a bit differently
| a+b <= 6 && a>1 && b>1 =
let x_infl = (a - 1) / (a + b - 2)
p_infl = incompleteBeta a b x_infl
x | p < p_infl = exp ((log(p * a) + beta) / a)
| otherwise = 1 - exp((log((1-p) * b) + beta) / b)
in x
-- For small a and not too big b we use approximation from boost.
| b < 5 && a <= 1 =
let x | p**(1/a) < 0.5 = (p * a * exp beta) ** (1/a)
| otherwise = 1 - (1 - p ** (b * exp beta))**(1/b)
in x
-- When a>>b and both are large approximation from [Temme1992],
-- section 4 "the incomplete gamma function case" used. In this
-- region it greatly improves over other approximation (AS109, AS64,
-- "Numerical Recipes")
--
-- FIXME: It could be used when b>>a too but it require inverse of
-- upper incomplete gamma to be precise enough. In current
-- implementation it loses precision in horrible way (40
-- order of magnitude off for sufficiently small p)
| a+b > 5 && a/b > 4 =
let -- Calculate initial approximation to eta using eq 4.1
eta0 = invIncompleteGamma b (1-p) / a
mu = b / a -- Eq. 4.3
-- A lot of helpers for calculation of
w = sqrt(1 + mu) -- Eq. 4.9
w_2 = w * w
w_3 = w_2 * w
w_4 = w_2 * w_2
w_5 = w_3 * w_2
w_6 = w_3 * w_3
w_7 = w_4 * w_3
w_8 = w_4 * w_4
w_9 = w_5 * w_4
w_10 = w_5 * w_5
d = eta0 - mu
d_2 = d * d
d_3 = d_2 * d
d_4 = d_2 * d_2
w1 = w + 1
w1_2 = w1 * w1
w1_3 = w1 * w1_2
w1_4 = w1_2 * w1_2
-- Evaluation of eq 4.10
e1 = (w + 2) * (w - 1) / (3 * w)
+ (w_3 + 9 * w_2 + 21 * w + 5) * d
/ (36 * w_2 * w1)
- (w_4 - 13 * w_3 + 69 * w_2 + 167 * w + 46) * d_2
/ (1620 * w1_2 * w_3)
- (7 * w_5 + 21 * w_4 + 70 * w_3 + 26 * w_2 - 93 * w - 31) * d_3
/ (6480 * w1_3 * w_4)
- (75 * w_6 + 202 * w_5 + 188 * w_4 - 888 * w_3 - 1345 * w_2 + 118 * w + 138) * d_4
/ (272160 * w1_4 * w_5)
e2 = (28 * w_4 + 131 * w_3 + 402 * w_2 + 581 * w + 208) * (w - 1)
/ (1620 * w1 * w_3)
- (35 * w_6 - 154 * w_5 - 623 * w_4 - 1636 * w_3 - 3983 * w_2 - 3514 * w - 925) * d
/ (12960 * w1_2 * w_4)
- ( 2132 * w_7 + 7915 * w_6 + 16821 * w_5 + 35066 * w_4 + 87490 * w_3
+ 141183 * w_2 + 95993 * w + 21640
) * d_2
/ (816480 * w_5 * w1_3)
- ( 11053 * w_8 + 53308 * w_7 + 117010 * w_6 + 163924 * w_5 + 116188 * w_4
- 258428 * w_3 - 677042 * w_2 - 481940 * w - 105497
) * d_3
/ (14696640 * w1_4 * w_6)
e3 = -( (3592 * w_7 + 8375 * w_6 - 1323 * w_5 - 29198 * w_4 - 89578 * w_3
- 154413 * w_2 - 116063 * w - 29632
) * (w - 1)
)
/ (816480 * w_5 * w1_2)
- ( 442043 * w_9 + 2054169 * w_8 + 3803094 * w_7 + 3470754 * w_6 + 2141568 * w_5
- 2393568 * w_4 - 19904934 * w_3 - 34714674 * w_2 - 23128299 * w - 5253353
) * d
/ (146966400 * w_6 * w1_3)
- ( 116932 * w_10 + 819281 * w_9 + 2378172 * w_8 + 4341330 * w_7 + 6806004 * w_6
+ 10622748 * w_5 + 18739500 * w_4 + 30651894 * w_3 + 30869976 * w_2
+ 15431867 * w + 2919016
) * d_2
/ (146966400 * w1_4 * w_7)
eta = evaluatePolynomialL (1/a) [eta0, e1, e2, e3]
-- Now we solve eq 4.2 to recover x using Newton iterations
u = eta - mu * log eta + (1 + mu) * log(1 + mu) - mu
cross = 1 / (1 + mu);
lower = if eta < mu then cross else 0
upper = if eta < mu then 1 else cross
x_guess = (lower + upper) / 2
func x = ( u + log x + mu*log(1 - x)
, 1/x - mu/(1-x)
)
Root x0 = newtonRaphson def{newtonTol=RelTol 1e-8} (lower, x_guess, upper) func
in x0
-- For large a and b approximation from AS109 (Carter
-- approximation). It's reasonably good in this region
| a > 1 && b > 1 =
let r = (y*y - 3) / 6
s = 1 / (2*a - 1)
t = 1 / (2*b - 1)
h = 2 / (s + t)
w = y * sqrt(h + r) / h - (t - s) * (r + 5/6 - 2 / (3 * h))
in a / (a + b * exp(2 * w))
-- Otherwise we revert to approximation from AS64 derived from
-- [AS64 2] when it's applicable.
--
-- It slightly reduces average number of iterations when `a' and
-- `b' have different magnitudes.
| chi2 > 0 && ratio > 1 = 1 - 2 / (ratio + 1)
-- If all else fails we use approximation from "Numerical
-- Recipes". It's very similar to approximations [AS64 4,5] but
-- it never goes out of [0,1] interval.
| otherwise = case () of
_| p < t / w -> (a * p * w) ** (1/a)
| otherwise -> 1 - (b * (1 - p) * w) ** (1/b)
where
lna = log $ a / (a+b)
lnb = log $ b / (a+b)
t = exp( a * lna ) / a
u = exp( b * lnb ) / b
w = t + u
where
-- Formula [AS64 2]
ratio = (4*a + 2*b - 2) / chi2
-- Quantile of chi-squared distribution. Formula [AS64 3].
chi2 = 2 * b * (1 - t + y * sqrt t) ** 3
where
t = 1 / (9 * b)
-- `y' is Hasting's approximation of p'th quantile of standard
-- normal distribution.
y = r - ( 2.30753 + 0.27061 * r )
/ ( 1.0 + ( 0.99229 + 0.04481 * r ) * r )
where
r = sqrt $ - 2 * log p
----------------------------------------------------------------
-- Sinc function
----------------------------------------------------------------
-- | Compute sinc function @sin(x)\/x@
sinc :: Double -> Double
sinc x
| ax < eps_0 = 1
| ax < eps_2 = 1 - x2/6
| ax < eps_4 = 1 - x2/6 + x2*x2/120
| otherwise = sin x / x
where
ax = abs x
x2 = x*x
-- For explanation of choice see `doc/sinc.hs'
eps_0 = 1.8250120749944284e-8 -- sqrt (6ε/4)
eps_2 = 1.4284346431400855e-4 -- (30ε)**(1/4) / 2
eps_4 = 4.043633626430947e-3 -- (1206ε)**(1/6) / 2
----------------------------------------------------------------
-- Logarithm
----------------------------------------------------------------
-- | Compute log(1+x)-x:
log1pmx :: Double -> Double
log1pmx x
| x < -1 = error "Domain error"
| x == -1 = m_neg_inf
| ax > 0.95 = log(1 + x) - x
| ax < m_epsilon = -(x * x) /2
| otherwise = - x * x * sumPowerSeries (-x) (recip <$> enumSequenceFrom 2)
where
ax = abs x
-- | /O(log n)/ Compute the logarithm in base 2 of the given value.
log2 :: Int -> Int
log2 v0
| v0 <= 0 = modErr $ "log2: nonpositive input, got " ++ show v0
| otherwise = go 5 0 v0
where
go !i !r !v | i == -1 = r
| v .&. b i /= 0 = let si = U.unsafeIndex sv i
in go (i-1) (r .|. si) (v `shiftR` si)
| otherwise = go (i-1) r v
b = U.unsafeIndex bv
!bv = U.fromList [ 0x02, 0x0c, 0xf0, 0xff00
, fromIntegral (0xffff0000 :: Word)
, fromIntegral (0xffffffff00000000 :: Word)]
!sv = U.fromList [1,2,4,8,16,32]
----------------------------------------------------------------
-- Factorial
----------------------------------------------------------------
-- | Compute the factorial function /n/!. Returns +∞ if the input is
-- above 170 (above which the result cannot be represented by a
-- 64-bit 'Double').
factorial :: Int -> Double
factorial n
| n < 0 = error "Numeric.SpecFunctions.factorial: negative input"
| n > 170 = m_pos_inf
| otherwise = U.unsafeIndex factorialTable n
-- | Compute the natural logarithm of the factorial function. Gives
-- 16 decimal digits of precision.
logFactorial :: Integral a => a -> Double
logFactorial n
| n < 0 = error "Numeric.SpecFunctions.logFactorial: negative input"
-- For smaller inputs we just look up table
| n <= 170 = log $ U.unsafeIndex factorialTable (fromIntegral n)
-- Otherwise we use asymptotic Stirling's series. Number of terms
-- necessary depends on the argument.
| n < 1500 = stirling + rx * ((1/12) - (1/360)*rx*rx)
| otherwise = stirling + (1/12)*rx
where
stirling = (x - 0.5) * log x - x + m_ln_sqrt_2_pi
x = fromIntegral n + 1
rx = 1 / x
{-# SPECIALIZE logFactorial :: Int -> Double #-}
-- | Calculate the error term of the Stirling approximation. This is
-- only defined for non-negative values.
--
-- \[
-- \operatorname{stirlingError}(n) = \log(n!) - \log(\sqrt{2\pi n}\frac{n}{e}^n)
-- \]
stirlingError :: Double -> Double
stirlingError n
| n <= 15.0 = case properFraction (n+n) of
(i,0) -> sfe `U.unsafeIndex` i
_ -> logGamma (n+1.0) - (n+0.5) * log n + n -
m_ln_sqrt_2_pi
| n > 500 = evaluateOddPolynomialL (1/n) [s0,-s1]
| n > 80 = evaluateOddPolynomialL (1/n) [s0,-s1,s2]
| n > 35 = evaluateOddPolynomialL (1/n) [s0,-s1,s2,-s3]
| otherwise = evaluateOddPolynomialL (1/n) [s0,-s1,s2,-s3,s4]
where
s0 = 0.083333333333333333333 -- 1/12
s1 = 0.00277777777777777777778 -- 1/360
s2 = 0.00079365079365079365079365 -- 1/1260
s3 = 0.000595238095238095238095238 -- 1/1680
s4 = 0.0008417508417508417508417508 -- 1/1188
sfe = U.fromList [ 0.0,
0.1534264097200273452913848, 0.0810614667953272582196702,
0.0548141210519176538961390, 0.0413406959554092940938221,
0.03316287351993628748511048, 0.02767792568499833914878929,
0.02374616365629749597132920, 0.02079067210376509311152277,
0.01848845053267318523077934, 0.01664469118982119216319487,
0.01513497322191737887351255, 0.01387612882307074799874573,
0.01281046524292022692424986, 0.01189670994589177009505572,
0.01110455975820691732662991, 0.010411265261972096497478567,
0.009799416126158803298389475, 0.009255462182712732917728637,
0.008768700134139385462952823, 0.008330563433362871256469318,
0.007934114564314020547248100, 0.007573675487951840794972024,
0.007244554301320383179543912, 0.006942840107209529865664152,
0.006665247032707682442354394, 0.006408994188004207068439631,
0.006171712263039457647532867, 0.005951370112758847735624416,
0.005746216513010115682023589, 0.005554733551962801371038690 ]
----------------------------------------------------------------
-- Combinatorics
----------------------------------------------------------------
-- |
-- Quickly compute the natural logarithm of /n/ @`choose`@ /k/, with
-- no checking.
--
-- Less numerically stable:
--
-- > exp $ lg (n+1) - lg (k+1) - lg (n-k+1)
-- > where lg = logGamma . fromIntegral
logChooseFast :: Double -> Double -> Double
logChooseFast n k = -log (n + 1) - logBeta (n - k + 1) (k + 1)
-- | Calculate binomial coefficient using exact formula
chooseExact :: Int -> Int -> Double
n `chooseExact` k
= U.foldl' go 1 $ U.enumFromTo 1 k
where
go a i = a * (nk + j) / j
where j = fromIntegral i :: Double
nk = fromIntegral (n - k)
-- | Compute logarithm of the binomial coefficient.
logChoose :: Int -> Int -> Double
n `logChoose` k
| k > n = (-1) / 0
-- For very large N exact algorithm overflows double so we
-- switch to beta-function based one
| k' < 50 && (n < 20000000) = log $ chooseExact n k'
| otherwise = logChooseFast (fromIntegral n) (fromIntegral k)
where
k' = min k (n-k)
-- | Compute the binomial coefficient /n/ @\``choose`\`@ /k/. For
-- values of /k/ > 50, this uses an approximation for performance
-- reasons. The approximation is accurate to 12 decimal places in the
-- worst case
--
-- Example:
--
-- > 7 `choose` 3 == 35
choose :: Int -> Int -> Double
n `choose` k
| k > n = 0
| k' < 50 = chooseExact n k'
| approx < max64 = fromIntegral . round64 $ approx
| otherwise = approx
where
k' = min k (n-k)
approx = exp $ logChooseFast (fromIntegral n) (fromIntegral k')
max64 = fromIntegral (maxBound :: Int64)
round64 x = round x :: Int64
-- | Compute ψ(/x/), the first logarithmic derivative of the gamma
-- function.
--
-- \[
-- \psi(x) = \frac{d}{dx} \ln \left(\Gamma(x)\right) = \frac{\Gamma'(x)}{\Gamma(x)}
-- \]
--
-- Uses Algorithm AS 103 by Bernardo, based on Minka's C implementation.
digamma :: Double -> Double
digamma x
| isNaN x || isInfinite x = m_NaN
-- FIXME:
-- This is ugly. We are testing here that number is in fact
-- integer. It's somewhat tricky question to answer. When ε for
-- given number becomes 1 or greater every number is represents
-- an integer. We also must make sure that excess precision
-- won't bite us.
| x <= 0 && fromIntegral (truncate x :: Int64) == x = m_neg_inf
-- Jeffery's reflection formula
| x < 0 = digamma (1 - x) + pi / tan (negate pi * x)
| x <= 1e-6 = - γ - 1/x + trigamma1 * x
| x' < c = r
-- De Moivre's expansion
| otherwise = let s = 1/x'
in evaluateEvenPolynomialL s
[ r + log x' - 0.5 * s
, - 1/12
, 1/120
, - 1/252
, 1/240
, - 1/132
, 391/32760
]
where
γ = m_eulerMascheroni
c = 12
-- Reduce to digamma (x + n) where (x + n) >= c
(r, x') = reduce 0 x
where
reduce !s y
| y < c = reduce (s - 1 / y) (y + 1)
| otherwise = (s, y)
----------------------------------------------------------------
-- Constants
----------------------------------------------------------------
-- Coefficients for 18-point Gauss-Legendre integration. They are
-- used in implementation of incomplete gamma and beta functions.
coefW,coefY :: U.Vector Double
coefW = U.fromList [ 0.0055657196642445571, 0.012915947284065419, 0.020181515297735382
, 0.027298621498568734, 0.034213810770299537, 0.040875750923643261
, 0.047235083490265582, 0.053244713977759692, 0.058860144245324798
, 0.064039797355015485, 0.068745323835736408, 0.072941885005653087
, 0.076598410645870640, 0.079687828912071670, 0.082187266704339706
, 0.084078218979661945, 0.085346685739338721, 0.085983275670394821
]
coefY = U.fromList [ 0.0021695375159141994, 0.011413521097787704, 0.027972308950302116
, 0.051727015600492421, 0.082502225484340941, 0.12007019910960293
, 0.16415283300752470, 0.21442376986779355, 0.27051082840644336
, 0.33199876341447887, 0.39843234186401943, 0.46931971407375483
, 0.54413605556657973, 0.62232745288031077, 0.70331500465597174
, 0.78649910768313447, 0.87126389619061517, 0.95698180152629142
]
{-# NOINLINE coefW #-}
{-# NOINLINE coefY #-}
trigamma1 :: Double
trigamma1 = 1.6449340668482264365 -- pi**2 / 6
modErr :: String -> a
modErr msg = error $ "Numeric.SpecFunctions." ++ msg
factorialTable :: U.Vector Double
{-# NOINLINE factorialTable #-}
factorialTable = U.fromListN 171
[ 1.0
, 1.0
, 2.0
, 6.0
, 24.0
, 120.0
, 720.0
, 5040.0
, 40320.0
, 362880.0
, 3628800.0
, 3.99168e7
, 4.790016e8
, 6.2270208e9
, 8.71782912e10
, 1.307674368e12
, 2.0922789888e13
, 3.55687428096e14
, 6.402373705728e15
, 1.21645100408832e17
, 2.43290200817664e18
, 5.109094217170944e19
, 1.1240007277776077e21
, 2.5852016738884974e22
, 6.204484017332394e23
, 1.5511210043330984e25
, 4.032914611266056e26
, 1.0888869450418352e28
, 3.0488834461171384e29
, 8.841761993739702e30
, 2.6525285981219103e32
, 8.222838654177922e33
, 2.631308369336935e35
, 8.683317618811886e36
, 2.9523279903960412e38
, 1.0333147966386144e40
, 3.719933267899012e41
, 1.3763753091226343e43
, 5.23022617466601e44
, 2.0397882081197442e46
, 8.159152832478977e47
, 3.3452526613163803e49
, 1.4050061177528798e51
, 6.041526306337383e52
, 2.6582715747884485e54
, 1.1962222086548019e56
, 5.5026221598120885e57
, 2.5862324151116818e59
, 1.2413915592536073e61
, 6.082818640342675e62
, 3.0414093201713376e64
, 1.5511187532873822e66
, 8.065817517094388e67
, 4.2748832840600255e69
, 2.308436973392414e71
, 1.2696403353658275e73
, 7.109985878048634e74
, 4.0526919504877214e76
, 2.3505613312828785e78
, 1.386831185456898e80
, 8.32098711274139e81
, 5.075802138772247e83
, 3.146997326038793e85
, 1.9826083154044399e87
, 1.2688693218588415e89
, 8.24765059208247e90
, 5.44344939077443e92
, 3.647111091818868e94
, 2.4800355424368305e96
, 1.711224524281413e98
, 1.197857166996989e100
, 8.504785885678623e101
, 6.1234458376886085e103
, 4.470115461512684e105
, 3.307885441519386e107
, 2.4809140811395396e109
, 1.88549470166605e111
, 1.4518309202828586e113
, 1.1324281178206297e115
, 8.946182130782974e116
, 7.15694570462638e118
, 5.797126020747368e120
, 4.753643337012841e122
, 3.9455239697206583e124
, 3.314240134565353e126
, 2.81710411438055e128
, 2.422709538367273e130
, 2.1077572983795275e132
, 1.8548264225739844e134
, 1.650795516090846e136
, 1.4857159644817613e138
, 1.352001527678403e140
, 1.2438414054641305e142
, 1.1567725070816416e144
, 1.087366156656743e146
, 1.0329978488239058e148
, 9.916779348709496e149
, 9.619275968248211e151
, 9.426890448883246e153
, 9.332621544394413e155
, 9.332621544394415e157
, 9.425947759838358e159
, 9.614466715035125e161
, 9.902900716486179e163
, 1.0299016745145626e166
, 1.0813967582402908e168
, 1.1462805637347082e170
, 1.2265202031961378e172
, 1.3246418194518288e174
, 1.4438595832024934e176
, 1.5882455415227428e178
, 1.7629525510902446e180
, 1.974506857221074e182
, 2.2311927486598134e184
, 2.543559733472187e186
, 2.9250936934930154e188
, 3.393108684451898e190
, 3.9699371608087206e192
, 4.68452584975429e194
, 5.574585761207606e196
, 6.689502913449126e198
, 8.094298525273443e200
, 9.875044200833601e202
, 1.214630436702533e205
, 1.5061417415111406e207
, 1.8826771768889257e209
, 2.372173242880047e211
, 3.0126600184576594e213
, 3.856204823625804e215
, 4.974504222477286e217
, 6.466855489220473e219
, 8.471580690878819e221
, 1.1182486511960041e224
, 1.4872707060906857e226
, 1.9929427461615188e228
, 2.6904727073180504e230
, 3.6590428819525483e232
, 5.012888748274991e234
, 6.917786472619488e236
, 9.615723196941088e238
, 1.3462012475717523e241
, 1.898143759076171e243
, 2.6953641378881624e245
, 3.8543707171800725e247
, 5.5502938327393044e249
, 8.047926057471992e251
, 1.1749972043909107e254
, 1.7272458904546386e256
, 2.5563239178728654e258
, 3.808922637630569e260
, 5.713383956445854e262
, 8.62720977423324e264
, 1.3113358856834524e267
, 2.0063439050956823e269
, 3.0897696138473508e271
, 4.789142901463393e273
, 7.471062926282894e275
, 1.1729568794264143e278
, 1.8532718694937346e280
, 2.946702272495038e282
, 4.714723635992061e284
, 7.590705053947218e286
, 1.2296942187394494e289
, 2.0044015765453023e291
, 3.287218585534296e293
, 5.423910666131589e295
, 9.003691705778436e297
, 1.5036165148649988e300
, 2.526075744973198e302
, 4.269068009004705e304
, 7.257415615307998e306
]
-- [NOTE: incompleteGamma.taylorP]
--
-- Incompltete gamma uses several algorithms for different parts of
-- parameter space. Most troublesome is P(a,x) Taylor series
-- [Temme1994,Eq.5.5] which requires to evaluate rather nasty
-- expression:
--
-- x^a x^a
-- ------------- = -------------
-- exp(x)·Γ(a+1) exp(x)·a·Γ(a)
--
-- Conditions:
-- | 0.5<x<1.1 = x < 4/3*a
-- | otherwise = x < a
--
-- For small `a` computation could be performed directly. However for
-- largish values of `a` it's possible some of factor in the
-- expression overflow. Values below take into account ranges for
-- Taylor P approximation:
--
-- · a > 155 - x^a could overflow
-- · a > 1182.5 - exp(x) could overflow
--
-- Usual way to avoid overflow problem is to perform calculations in
-- the log domain. It however doesn't work very well in this case
-- since we encounter catastrophic cancellations and could easily lose
-- up to 6(!) digits for large `a`.
--
-- So we take another approach and use Stirling approximation with
-- correction (logGammaCorrection).
--
-- x^a / x·e \^a 1
-- ≈ ------------------------- = | --- | · ----------------
-- exp(x)·sqrt(2πa)·(a/e)^a) \ a / exp(x)·sqrt(2πa)
--
-- We're using this approach as soon as logGammaCorrection starts
-- working (a>10) because we don't have implementation for gamma
-- function and exp(logGamma z) results in errors for large a.
--
-- Once we get into region when exp(x) could overflow we rewrite
-- expression above once more:
--
-- / x·e \^a 1
-- | --- · e^(-x/a) | · ---------
-- \ a / sqrt(2πa)
--
-- This approach doesn't work very well but it's still big improvement
-- over calculations in the log domain.
|
Shimuuar/math-functions
|
Numeric/SpecFunctions/Internal.hs
|
bsd-2-clause
| 48,485
| 2
| 34
| 14,211
| 11,369
| 6,160
| 5,209
| 849
| 4
|
{-| Implementation of the Ganeti Query2 common objects.
-}
{-
Copyright (C) 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Query.Common
( rsNoData
, rsUnavail
, rsNormal
, rsMaybeNoData
, rsMaybeUnavail
, rsUnknown
, missingRuntime
, rpcErrorToStatus
, timeStampFields
, uuidFields
, serialFields
, tagsFields
, dictFieldGetter
, buildNdParamField
) where
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import Text.JSON (JSON, showJSON)
import qualified Ganeti.Constants as C
import Ganeti.Config
import Ganeti.Objects
import Ganeti.Rpc
import Ganeti.Query.Language
import Ganeti.Query.Types
import Ganeti.Types
-- * Generic functions
-- | Conversion from 'VType' to 'FieldType'.
vTypeToQFT :: VType -> FieldType
vTypeToQFT VTypeString = QFTOther
vTypeToQFT VTypeMaybeString = QFTOther
vTypeToQFT VTypeBool = QFTBool
vTypeToQFT VTypeSize = QFTUnit
vTypeToQFT VTypeInt = QFTNumber
-- * Result helpers
-- | Helper for a result with no data.
rsNoData :: ResultEntry
rsNoData = ResultEntry RSNoData Nothing
-- | Helper for result for an entity which supports no such field.
rsUnavail :: ResultEntry
rsUnavail = ResultEntry RSUnavail Nothing
-- | Helper to declare a normal result.
rsNormal :: (JSON a) => a -> ResultEntry
rsNormal a = ResultEntry RSNormal $ Just (showJSON a)
-- | Helper to declare a result from a 'Maybe' (the item might be
-- missing, in which case we return no data). Note that there's some
-- ambiguity here: in some cases, we mean 'RSNoData', but in other
-- 'RSUnavail'; this is easy to solve in simple cases, but not in
-- nested dicts. If you want to return 'RSUnavail' in case of 'Nothing'
-- use the function 'rsMaybeUnavail'.
rsMaybeNoData :: (JSON a) => Maybe a -> ResultEntry
rsMaybeNoData = maybe rsNoData rsNormal
-- | Helper to declare a result from a 'Maybe'. This version returns
-- a 'RSUnavail' in case of 'Nothing'. It should be used for optional
-- fields that are not set. For cases where 'Nothing' means that there
-- was an error, consider using 'rsMaybe' instead.
rsMaybeUnavail :: (JSON a) => Maybe a -> ResultEntry
rsMaybeUnavail = maybe rsUnavail rsNormal
-- | Helper for unknown field result.
rsUnknown :: ResultEntry
rsUnknown = ResultEntry RSUnknown Nothing
-- | Helper for a missing runtime parameter.
missingRuntime :: FieldGetter a b
missingRuntime = FieldRuntime (\_ _ -> ResultEntry RSNoData Nothing)
-- * Error conversion
-- | Convert RpcError to ResultStatus
rpcErrorToStatus :: RpcError -> ResultStatus
rpcErrorToStatus OfflineNodeError = RSOffline
rpcErrorToStatus _ = RSNoData
-- * Common fields
-- | The list of timestamp fields.
timeStampFields :: (TimeStampObject a) => FieldList a b
timeStampFields =
[ (FieldDefinition "ctime" "CTime" QFTTimestamp "Creation timestamp",
FieldSimple (rsNormal . cTimeOf), QffNormal)
, (FieldDefinition "mtime" "MTime" QFTTimestamp "Modification timestamp",
FieldSimple (rsNormal . mTimeOf), QffNormal)
]
-- | The list of UUID fields.
uuidFields :: (UuidObject a) => String -> FieldList a b
uuidFields name =
[ (FieldDefinition "uuid" "UUID" QFTText (name ++ " UUID"),
FieldSimple (rsNormal . uuidOf), QffNormal) ]
-- | The list of serial number fields.
serialFields :: (SerialNoObject a) => String -> FieldList a b
serialFields name =
[ (FieldDefinition "serial_no" "SerialNo" QFTNumber
(name ++ " object serial number, incremented on each modification"),
FieldSimple (rsNormal . serialOf), QffNormal) ]
-- | The list of tag fields.
tagsFields :: (TagsObject a) => FieldList a b
tagsFields =
[ (FieldDefinition "tags" "Tags" QFTOther "Tags",
FieldSimple (rsNormal . tagsOf), QffNormal) ]
-- * Generic parameter functions
-- | Returns a field from a (possibly missing) 'DictObject'. This is
-- used by parameter dictionaries, usually. Note that we have two
-- levels of maybe: the top level dict might be missing, or one key in
-- the dictionary might be.
dictFieldGetter :: (DictObject a) => String -> Maybe a -> ResultEntry
dictFieldGetter k = maybe rsNoData (rsMaybeNoData . lookup k . toDict)
-- | Ndparams optimised lookup map.
ndParamTypes :: Map.Map String FieldType
ndParamTypes = Map.map vTypeToQFT C.ndsParameterTypes
-- | Ndparams title map.
ndParamTitles :: Map.Map String FieldTitle
ndParamTitles = C.ndsParameterTitles
-- | Ndparam getter builder: given a field, it returns a FieldConfig
-- getter, that is a function that takes the config and the object and
-- returns the Ndparam field specified when the getter was built.
ndParamGetter :: (NdParamObject a) =>
String -- ^ The field we're building the getter for
-> ConfigData -> a -> ResultEntry
ndParamGetter field config =
dictFieldGetter field . getNdParamsOf config
-- | Builds the ndparam fields for an object.
buildNdParamField :: (NdParamObject a) => String -> FieldData a b
buildNdParamField field =
let full_name = "ndp/" ++ field
title = fromMaybe field $ field `Map.lookup` ndParamTitles
qft = fromMaybe QFTOther $ field `Map.lookup` ndParamTypes
desc = "The \"" ++ field ++ "\" node parameter"
in (FieldDefinition full_name title qft desc,
FieldConfig (ndParamGetter field), QffNormal)
|
apyrgio/snf-ganeti
|
src/Ganeti/Query/Common.hs
|
bsd-2-clause
| 6,515
| 0
| 11
| 1,152
| 965
| 540
| 425
| 86
| 1
|
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE MultiParamTypeClasses #-}
--------------------------------------------------------------------
-- |
-- Copyright : (c) Edward Kmett and Dan Doel 2014
-- License : BSD2
-- Maintainer: Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability: non-portable
--
--------------------------------------------------------------------
module Ermine.Syntax.Convention
( Convention(..)
, AsConvention(..)
, strict
, conv
, Conventional(..)
) where
import Control.Applicative
import Control.Lens hiding (strict)
import Control.Monad.Fix
import Control.Monad.Reader.Class
import Control.Monad.Zip
import qualified Data.Binary as Binary
import Data.Binary (Binary)
import Data.Bytes.Serial
import Data.Data
import Data.Default
import Data.Distributive
import Data.Foldable
import Data.Functor.Rep
import Data.Hashable
import Data.Hashable.Extras
import Data.Monoid
import qualified Data.Serialize as Serialize
import Data.Serialize (Serialize)
import GHC.Generics hiding (Rep)
import Prelude
-- | calling conventions for applications and lambdas
data Convention
= C -- lazy core appliction
| U -- strict unboxed value
| D -- strict dictionary application
| N -- strict native value application (for strings and foreign java objects)
deriving (Eq,Ord,Show,Read,Enum,Bounded,Typeable,Data,Generic)
instance Hashable Convention where
hashWithSalt n i = n `hashWithSalt` fromEnum i
instance Serial Convention where
serialize = serialize . fromEnum
deserialize = toEnum <$> deserialize
instance Binary Convention where
put = serialize
get = deserialize
instance Serialize Convention where
put = serialize
get = deserialize
strict :: Convention -> Bool
strict C = False
strict U = True
strict D = True
strict N = True
class AsConvention t where
_Convention :: Prism' t Convention
instance AsConvention Convention where
_Convention = id
data Conventional a = Conventional a a a a
deriving (Eq,Ord,Show,Read,Foldable,Traversable,Typeable,Data,Generic)
instance Num a => Num (Conventional a) where
(+) = liftA2 (+)
(-) = liftA2 (-)
(*) = liftA2 (*)
negate = fmap negate
abs = fmap abs
signum = fmap abs
fromInteger = pure . fromInteger
instance Hashable a => Hashable (Conventional a)
instance Hashable1 Conventional
instance Serial1 Conventional where
serializeWith f (Conventional a b c d) = f a >> f b >> f c >> f d
deserializeWith f = Conventional <$> f <*> f <*> f <*> f
instance Serial a => Serial (Conventional a) where
serialize = serializeWith serialize
deserialize = deserializeWith deserialize
instance Binary a => Binary (Conventional a) where
put = serializeWith Binary.put
get = deserializeWith Binary.get
instance Serialize a => Serialize (Conventional a) where
put = serializeWith Serialize.put
get = deserializeWith Serialize.get
instance Default a => Default (Conventional a) where
def = Conventional def def def def
conv :: Convention -> Lens' (Conventional a) a
conv C = \ f (Conventional c u d n) -> f c <&> \c' -> Conventional c' u d n
conv U = \ f (Conventional c u d n) -> f u <&> \u' -> Conventional c u' d n
conv D = \ f (Conventional c u d n) -> f d <&> \d' -> Conventional c u d' n
conv N = \ f (Conventional c u d n) -> f n <&> \n' -> Conventional c u d n'
type instance Index (Conventional a) = Convention
type instance IxValue (Conventional a) = a
instance Ixed (Conventional a) where
ix = conv
instance Representable Conventional where
type Rep Conventional = Convention
tabulate f = Conventional (f C) (f U) (f D) (f N)
index (Conventional c _ _ _) C = c
index (Conventional _ u _ _) U = u
index (Conventional _ _ d _) D = d
index (Conventional _ _ _ n) N = n
instance Functor Conventional where
a <$ _ = Conventional a a a a
fmap f (Conventional a b c d) = Conventional (f a) (f b) (f c) (f d)
instance Applicative Conventional where
pure a = Conventional a a a a
Conventional fa fb fc fd <*> Conventional aa ab ac ad = Conventional (fa aa) (fb ab) (fc ac) (fd ad)
_ *> x = x
x <* _ = x
instance Monad Conventional where
return a = Conventional a a a a
_ >> x = x
Conventional a b c d >>= f = Conventional a' b' c' d' where
Conventional a' _ _ _ = f a
Conventional _ b' _ _ = f b
Conventional _ _ c' _ = f c
Conventional _ _ _ d' = f d
instance Distributive Conventional where
distribute = distributeRep
instance MonadReader Convention Conventional where
ask = askRep
local = localRep
instance MonadFix Conventional where
mfix = mfixRep
instance MonadZip Conventional where
mzip = mzipRep
mzipWith = mzipWithRep
instance FunctorWithIndex Convention Conventional where
imap f (Conventional c u d n) = Conventional (f C c) (f U u) (f D d) (f N n)
instance FoldableWithIndex Convention Conventional where
ifoldMap f (Conventional c u d n) = f C c <> f U u <> f D d <> f N n
instance TraversableWithIndex Convention Conventional where
itraverse f (Conventional c u d n) = Conventional <$> f C c <*> f U u <*> f D d <*> f N n
|
PipocaQuemada/ermine
|
src/Ermine/Syntax/Convention.hs
|
bsd-2-clause
| 5,282
| 0
| 10
| 1,033
| 1,821
| 946
| 875
| 134
| 1
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE UndecidableSuperClasses #-}
module Data.Generics.Product.Internal.Fields
( Context_
, Context'
, Context0
, Context
, derived
) where
import Data.Generics.Internal.Families
import Data.Generics.Product.Internal.GLens
import Data.Kind (Constraint, Type)
import GHC.Generics
import GHC.TypeLits (Symbol, ErrorMessage(..), TypeError)
import Data.Generics.Internal.Errors
import Data.Generics.Internal.Profunctor.Lens
import Data.Generics.Internal.Profunctor.Iso
-- Full context
class Context (field :: Symbol) s t a b | s field -> a, t field -> b, s field b -> t, t field a -> s
instance
( HasTotalFieldP field (Rep s) ~ 'Just a
, HasTotalFieldP field (Rep t) ~ 'Just b
, HasTotalFieldP field (Rep (Indexed s)) ~ 'Just a'
, HasTotalFieldP field (Rep (Indexed t)) ~ 'Just b'
, t ~ Infer s a' b
, s ~ Infer t b' a
) => Context field s t a b
-- Alternative type inference
type Context_ field s t a b
= ( HasTotalFieldP field (Rep s) ~ 'Just a
, HasTotalFieldP field (Rep t) ~ 'Just b
, UnifyHead s t
, UnifyHead t s
)
-- Monomorphic
type Context' field s a
= ( Generic s
, ErrorUnless field s (CollectField field (Rep s))
, GLens' (HasTotalFieldPSym field) (Rep s) a
, Defined (Rep s)
(NoGeneric s '[ 'Text "arising from a generic lens focusing on the "
':<>: QuoteType field ':<>: 'Text " field of type " ':<>: QuoteType a
, 'Text "in " ':<>: QuoteType s])
(() :: Constraint)
)
-- No inference
type Context0 field s t a b
= ( Generic s
, Generic t
, GLens (HasTotalFieldPSym field) (Rep s) (Rep t) a b
, ErrorUnless field s (CollectField field (Rep s))
, Defined (Rep s)
(NoGeneric s '[ 'Text "arising from a generic lens focusing on the "
':<>: QuoteType field ':<>: 'Text " field of type " ':<>: QuoteType a
, 'Text "in " ':<>: QuoteType s])
(() :: Constraint)
)
derived :: forall field s t a b. Context0 field s t a b => Lens s t a b
derived = repIso . glens @(HasTotalFieldPSym field)
{-# INLINE derived #-}
type family ErrorUnless (field :: Symbol) (s :: Type) (stat :: TypeStat) :: Constraint where
ErrorUnless field s ('TypeStat _ _ '[])
= TypeError
( 'Text "The type "
':<>: 'ShowType s
':<>: 'Text " does not contain a field named '"
':<>: 'Text field ':<>: 'Text "'."
)
ErrorUnless field s ('TypeStat (n ': ns) _ _)
= TypeError
( 'Text "Not all constructors of the type "
':<>: 'ShowType s
':$$: 'Text " contain a field named '"
':<>: 'Text field ':<>: 'Text "'."
':$$: 'Text "The offending constructors are:"
':$$: ShowSymbols (n ': ns)
)
ErrorUnless _ _ ('TypeStat '[] '[] _)
= ()
data HasTotalFieldPSym :: Symbol -> (TyFun (Type -> Type) (Maybe Type))
type instance Eval (HasTotalFieldPSym sym) tt = HasTotalFieldP sym tt
|
kcsongor/generic-lens
|
generic-lens-core/src/Data/Generics/Product/Internal/Fields.hs
|
bsd-3-clause
| 3,498
| 2
| 16
| 930
| 1,094
| 589
| 505
| -1
| -1
|
module SPARC.CodeGen.CondCode (
getCondCode,
condIntCode,
condFltCode
)
where
import GhcPrelude
import {-# SOURCE #-} SPARC.CodeGen.Gen32
import SPARC.CodeGen.Base
import SPARC.Instr
import SPARC.Regs
import SPARC.Cond
import SPARC.Imm
import SPARC.Base
import NCGMonad
import Format
import GHC.Cmm
import OrdList
import Outputable
getCondCode :: CmmExpr -> NatM CondCode
getCondCode (CmmMachOp mop [x, y])
=
case mop of
MO_F_Eq W32 -> condFltCode EQQ x y
MO_F_Ne W32 -> condFltCode NE x y
MO_F_Gt W32 -> condFltCode GTT x y
MO_F_Ge W32 -> condFltCode GE x y
MO_F_Lt W32 -> condFltCode LTT x y
MO_F_Le W32 -> condFltCode LE x y
MO_F_Eq W64 -> condFltCode EQQ x y
MO_F_Ne W64 -> condFltCode NE x y
MO_F_Gt W64 -> condFltCode GTT x y
MO_F_Ge W64 -> condFltCode GE x y
MO_F_Lt W64 -> condFltCode LTT x y
MO_F_Le W64 -> condFltCode LE x y
MO_Eq _ -> condIntCode EQQ x y
MO_Ne _ -> condIntCode NE x y
MO_S_Gt _ -> condIntCode GTT x y
MO_S_Ge _ -> condIntCode GE x y
MO_S_Lt _ -> condIntCode LTT x y
MO_S_Le _ -> condIntCode LE x y
MO_U_Gt _ -> condIntCode GU x y
MO_U_Ge _ -> condIntCode GEU x y
MO_U_Lt _ -> condIntCode LU x y
MO_U_Le _ -> condIntCode LEU x y
_ -> pprPanic "SPARC.CodeGen.CondCode.getCondCode" (ppr (CmmMachOp mop [x,y]))
getCondCode other = pprPanic "SPARC.CodeGen.CondCode.getCondCode" (ppr other)
-- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be
-- passed back up the tree.
condIntCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
condIntCode cond x (CmmLit (CmmInt y _))
| fits13Bits y
= do
(src1, code) <- getSomeReg x
let
src2 = ImmInt (fromInteger y)
code' = code `snocOL` SUB False True src1 (RIImm src2) g0
return (CondCode False cond code')
condIntCode cond x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let
code__2 = code1 `appOL` code2 `snocOL`
SUB False True src1 (RIReg src2) g0
return (CondCode False cond code__2)
condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
condFltCode cond x y = do
dflags <- getDynFlags
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
tmp <- getNewRegNat FF64
let
promote x = FxTOy FF32 FF64 x tmp
pk1 = cmmExprType dflags x
pk2 = cmmExprType dflags y
code__2 =
if pk1 `cmmEqType` pk2 then
code1 `appOL` code2 `snocOL`
FCMP True (cmmTypeFormat pk1) src1 src2
else if typeWidth pk1 == W32 then
code1 `snocOL` promote src1 `appOL` code2 `snocOL`
FCMP True FF64 tmp src2
else
code1 `appOL` code2 `snocOL` promote src2 `snocOL`
FCMP True FF64 src1 tmp
return (CondCode True cond code__2)
|
sdiehl/ghc
|
compiler/nativeGen/SPARC/CodeGen/CondCode.hs
|
bsd-3-clause
| 3,073
| 0
| 15
| 992
| 1,008
| 497
| 511
| 81
| 23
|
{-
Problem 37
Find all 11 primes that are left- and right-truncatable
Result
748317
2.7 s
-}
module Problem37 (solution) where
import Data.Numbers.Primes
import Data.List
import CommonFunctions
solution = sum' . take 11 . filter isTruncatable $ candidates
where candidates = dropWhile (<= 7) primes -- exclude single digit primes
isTruncatable n = allPrimes truncates
where n' = explodeInt10 n
allPrimes = all $ isPrime . implodeInt 10
truncates = middle (inits n') ++ middle (tails n')
middle = init . tail -- Everything but head and last
-- (since inits xs = [xs ... []])
|
quchen/HaskellEuler
|
src/Problem37.hs
|
bsd-3-clause
| 707
| 0
| 10
| 229
| 139
| 75
| 64
| 11
| 1
|
-- -----------------------------------------------------------------------------
module Demo.Util(
printSlaveResume, nidNode, expandNodenames, filterNodes ) where
-- -----------------------------------------------------------------------------
import Control.Arrow( (&&&) )
import Control.Monad( forM_ )
import Control.Distributed.Process( NodeId )
import Text.Regex.TDFA( (=~) )
import Data.List( sort, group )
import qualified Data.Text as T( Text, pack, unpack, append )
import Text.Parsec.Text( Parser )
import Text.Parsec.Prim( (<|>), (<?>), try, parse )
import Text.Parsec.Combinator( many1, sepBy1 )
import Text.Parsec.Char( char, alphaNum, digit )
-- -----------------------------------------------------------------------------
nidNode :: NodeId -> T.Text
nidNode nid = case regres of
[_:nn:_] -> T.pack nn
_ -> T.pack "*"
where
regres = show nid =~ "nid://(.+):(.+):(.+)" :: [[String]]
-- -----------------------------------------------------------------------------
rle :: [NodeId] -> [(Int, T.Text)]
rle slaves = map (length &&& head) sorted
where
sorted = group . sort . map nidNode $ slaves
-- -----------------------------------------------------------------------------
printSlaveResume :: String -> [NodeId] -> IO ()
printSlaveResume pre slaves = do
putStrLn $ pre ++ " " ++ (show . length $ slaves) ++ " slave/s"
forM_ (rle slaves) $ \(n,name) ->
putStrLn $ pre ++ " ->" ++ T.unpack name ++ " = " ++ show n
-- -----------------------------------------------------------------------------
expandNodenames :: T.Text -> [T.Text]
expandNodenames def = case parse nodeList "" def of
Left err -> error $ show err
Right x -> x
-- -----------------------------------------------------------------------------
filterNodes :: [NodeId] -> String -> [NodeId]
filterNodes slaves names = filter ((`elem` assigned) . nidNode) slaves
where
assigned = expandNodenames . T.pack $ names
-- -----------------------------------------------------------------------------
nodeList :: Parser [T.Text]
nodeList = do {
l <- sepBy1 nodes $ char ',';
return $ concat l
} <?> "node list"
-- -----------------------------------------------------------------------------
nodes :: Parser [T.Text]
nodes = do {
pre <- nodePrefix;
l <- intList <|> return [];
if null l
then return [pre]
else return $ map (T.append pre . T.pack . show) l
} <?> "nodes"
-- -----------------------------------------------------------------------------
nodePrefix :: Parser T.Text
nodePrefix = fmap T.pack $ many1 alphaNum
-- -----------------------------------------------------------------------------
intList :: Parser [Integer]
intList = do {
_ <- char '[';
l <- sepBy1 intSequence $ char ',';
_ <- char ']';
return . sort $ concat l
} <?> "intList"
-- -----------------------------------------------------------------------------
intSequence :: Parser [Integer]
intSequence = try (
do {
a <- number;
_ <- char '-';
b <- number;
return [a..b]
})
<|>
do {
n <- number;
return [n]
} <?> "intSequence"
-- -----------------------------------------------------------------------------
number :: Parser Integer
number = do {
ds <- many1 digit;
return $ read ds
} <?> "number"
-- -----------------------------------------------------------------------------
|
zhensydow/dist-demo
|
src/Demo/Util.hs
|
bsd-3-clause
| 3,653
| 0
| 15
| 832
| 945
| 514
| 431
| 71
| 2
|
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
module Array where
import Ivory.Language
import Ivory.Compile.C.CmdlineFrontend
cmodule :: Module
cmodule = package "Array" $ do
incl arrayExample
incl arrayTernary
runArrayExample :: IO ()
runArrayExample = runCompiler [cmodule] [] initialOpts { outDir = Nothing }
arrayExample :: Def('[Ref s (Array 4 (Stored Uint8)), Uint8] :-> ())
arrayExample = proc "arrayExample" $ \arr n -> body $ do
arrayMap $ \ ix -> do
v <- deref (arr ! ix)
store (arr ! ix) (v + n)
arrayTernary :: Def('[IBool] :-> IFloat)
arrayTernary = proc "arrayTernary" $ \b -> body $ do
a1 <- local (vs 1)
a2 <- local (vs 2)
ares <- assign (b ? (a1, a2))
deref (ares ! 3) >>= ret
where
vs :: IFloat -> Init (Array 4 (Stored IFloat))
vs v = iarray (map ival [v, v, v, v])
|
Hodapp87/ivory
|
ivory-examples/examples/Array.hs
|
bsd-3-clause
| 833
| 0
| 17
| 178
| 372
| 192
| 180
| 24
| 1
|
-- | Parse .cabal files in pedantic detail.
module Edit.Parser where
import Edit.Types
import Text.Parsec hiding (space, spaces, many, (<|>))
-- import Text.Parsec.Char
import Text.Parsec.Text
import Data.Text (Text, pack)
import Control.Applicative
import Data.Functor (void)
spaces :: Parser Int
spaces = do
ss <- many $ char ' '
return $ length ss
restOfLine :: Parser Text
restOfLine = pack <$> many (noneOf "\r\n") <* endOfLine
fieldName :: Parser Text
fieldName = pack <$> manyTill identiferChar (char ':')
identiferChar :: Parser Char
identiferChar = char '-' <|> letter
continuationLine :: Int -> Parser ContinuationLine
continuationLine i = blankLine BlankCLine <|> try nonEmpty where
nonEmpty = do
s <- spaces
if s > i then ContinuationLine s <$> restOfLine
else fail "not indented enough for continuation line"
sectionField :: Int -> Parser SectionLine
sectionField i = try $ do
s <- spaces
if s > i then SectionField s <$> fieldName <*> spaces <*> restOfLine <*>
many (continuationLine s)
else fail "not indented enough for section field"
comment :: Parser DetailedPackage
comment = try $ Comment <$> spaces <*> (string "--" *> restOfLine)
globalField :: Parser DetailedPackage
globalField = try $ do
s <- spaces
GlobalField s <$> fieldName <*> spaces <*> restOfLine <*>
many (continuationLine s)
section :: Parser DetailedPackage
section = try $ do
s <- spaces
Section s <$> (pack <$> many1 identiferChar) <*> spaces <*> restOfLine <*>
many (sectionField s <|> blankLine BlankSLine)
blankLine :: a -> Parser a
blankLine a = try $ spaces *> (endOfLine) *> pure a
detailedPackageLine :: Parser DetailedPackage
detailedPackageLine =
label comment "comment" <|>
label globalField "global field" <|>
label section "section"
-- label (blankLine BlankLine) "blank line"
detailedParser :: Parser [DetailedPackage]
detailedParser = many detailedPackageLine <* spaces <* eof
|
bergey/cabal-edit
|
src/Edit/Parser.hs
|
bsd-3-clause
| 2,009
| 0
| 14
| 419
| 594
| 300
| 294
| 50
| 2
|
--------------------------------------------------------------------------------
{-# LANGUAGE ForeignFunctionInterface #-}
module Firefly.Audio
( Loop (..)
, playMusic
, stopMusic
, setMusicVolume
, getMusicVolume
, playSound
, playSoundPanning
, playSoundPosition
) where
--------------------------------------------------------------------------------
import Foreign.C.Types
import Foreign.C.String
import Foreign.ForeignPtr
import Foreign.Ptr
--------------------------------------------------------------------------------
import Firefly.Audio.Internal
--------------------------------------------------------------------------------
foreign import ccall unsafe "ff_playMusic" ff_playMusic
:: CString -> CInt -> IO ()
foreign import ccall unsafe "ff_stopMusic" ff_stopMusic
:: IO ()
foreign import ccall unsafe "ff_setMusicVolume" ff_setMusicVolume
:: CDouble -> IO ()
foreign import ccall unsafe "ff_getMusicVolume" ff_getMusicVolume
:: IO CDouble
foreign import ccall unsafe "ff_playSound" ff_playSound
:: Ptr CSound -> IO ()
foreign import ccall unsafe "ff_playSoundPanning" ff_playSoundPanning
:: Ptr CSound -> CDouble -> CDouble -> IO ()
foreign import ccall unsafe "ff_playSoundPosition" ff_playSoundPosition
:: Ptr CSound -> CDouble -> CDouble -> IO ()
--------------------------------------------------------------------------------
-- | Loop mode for 'playMusic'
data Loop
= Loop Int -- ^ Loop N times
| DontLoop -- ^ Just play once
| LoopForever -- ^ Loop until the world ends
deriving (Show)
--------------------------------------------------------------------------------
fromLoop :: Loop -> CInt
fromLoop (Loop n) = fromIntegral n
fromLoop DontLoop = 1
fromLoop LoopForever = -1
--------------------------------------------------------------------------------
-- | Play some background music. This stops the previous background music (if
-- any) from playing.
--
-- Supported formats depend on your platform and version of SDL_mixer, but WAV,
-- OGG and MP3 should be a safe bet.
--
-- This call is non-blocking.
playMusic :: FilePath -> Loop -> IO ()
playMusic filePath l = withCString filePath $ \str ->
ff_playMusic str (fromLoop l)
--------------------------------------------------------------------------------
-- | Stop the currently playing music without starting a new track.
stopMusic :: IO ()
stopMusic = ff_stopMusic
--------------------------------------------------------------------------------
-- | Set the music volume. Argument must be between 0 and 1.
setMusicVolume :: Double -> IO ()
setMusicVolume v = ff_setMusicVolume (realToFrac v)
{-# INLINE setMusicVolume #-}
--------------------------------------------------------------------------------
-- | Obtain the music volume
getMusicVolume :: IO Double
getMusicVolume = fmap realToFrac ff_getMusicVolume
{-# INLINE getMusicVolume #-}
--------------------------------------------------------------------------------
-- Play some sound.
--
-- This call is non-blocking.
playSound :: Sound -> IO ()
playSound (Sound fptr) = withForeignPtr fptr ff_playSound
--------------------------------------------------------------------------------
-- | Play a sound with panning
playSoundPanning :: Sound -- ^ Sound to play
-> Double -- ^ Panning: 0 for completely left, 1 for right
-> Double -- ^ Sound distance: between 0 and 1
-> IO () -- ^ Non-blocking
playSoundPanning (Sound fptr) panning distance = withForeignPtr fptr $ \ptr ->
ff_playSoundPanning ptr (realToFrac panning) (realToFrac distance)
--------------------------------------------------------------------------------
-- | Play a sound at a given position defined in radians and distance
--
-- The radians are interpreted like this:
--
-- > (3 * pi / 4)
-- >
-- > pi (user) 0
-- >
-- > pi / 2
--
-- So 0 is directly in front of the user.
playSoundPosition :: Sound -- ^ Sound to play
-> Double -- ^ Angle in radians
-> Double -- ^ Sound distance: between 0 and 1
-> IO () -- ^ Non-blocking
playSoundPosition (Sound fptr) angle distance = withForeignPtr fptr $ \ptr ->
ff_playSoundPosition ptr (realToFrac angle) (realToFrac distance)
|
jaspervdj/firefly
|
src/Firefly/Audio.hs
|
bsd-3-clause
| 4,394
| 0
| 10
| 825
| 653
| 365
| 288
| 63
| 1
|
--
-- Copyright (c) 2012 Mark Dittmer - http://www.markdittmer.org
-- Developed for a Google Summer of Code project - http://gsoc2012.markdittmer.org
--
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
module System.FSNotify.Path
( findFiles
, findDirs
, canonicalizeDirPath
, canonicalizePath
, hasThisExtension
) where
import Prelude hiding (FilePath)
import Control.Applicative
import Control.Monad
-- import Filesystem
-- import Filesystem.Path hiding (concat)
import qualified Data.Text as T
import qualified System.Directory as D
import System.PosixCompat.Files as PF
import System.FilePath
getDirectoryContentsPath :: FilePath -> IO [FilePath]
getDirectoryContentsPath path = (map (path </>)) . filter (not . dots) <$> D.getDirectoryContents path
where
dots "." = True
dots ".." = True
dots _ = False
fileDirContents :: FilePath -> IO ([FilePath],[FilePath])
fileDirContents path = do
contents <- getDirectoryContentsPath path
stats <- mapM getFileStatus contents
let pairs = zip stats contents
let files = [ f | (s, f) <- pairs, PF.isRegularFile s]
let dirs = [ d | (s, d) <- pairs, PF.isDirectory s]
return (files, dirs)
findAllFiles :: FilePath -> IO [FilePath]
findAllFiles path = do
(files, dirs) <- fileDirContents path
nestedFiles <- mapM findAllFiles dirs
return (files ++ concat nestedFiles)
findImmediateFiles, findImmediateDirs :: FilePath -> IO [FilePath]
findImmediateFiles = fileDirContents >=> mapM D.canonicalizePath . fst
findImmediateDirs = fileDirContents >=> mapM D.canonicalizePath . snd
findAllDirs :: FilePath -> IO [FilePath]
findAllDirs path = do
dirs <- findImmediateDirs path
nestedDirs <- mapM findAllDirs dirs
return (dirs ++ concat nestedDirs)
findFiles :: Bool -> FilePath -> IO [FilePath]
findFiles True path = findAllFiles =<< canonicalizeDirPath path
findFiles False path = findImmediateFiles =<< canonicalizeDirPath path
findDirs :: Bool -> FilePath -> IO [FilePath]
findDirs True path = findAllDirs =<< canonicalizeDirPath path
findDirs False path = findImmediateDirs =<< canonicalizeDirPath path
-- | add a trailing slash to ensure the path indicates a directory
addTrailingSlash :: FilePath -> FilePath
addTrailingSlash = addTrailingPathSeparator
canonicalizeDirPath :: FilePath -> IO FilePath
canonicalizeDirPath path = addTrailingSlash `fmap` D.canonicalizePath path
-- | bugfix older version of canonicalizePath (system-fileio <= 0.3.7) loses trailing slash
canonicalizePath :: FilePath -> IO FilePath
canonicalizePath path = let was_dir = null (takeFileName path) in
if not was_dir then D.canonicalizePath path
else canonicalizeDirPath path
hasThisExtension :: FilePath -> T.Text -> Bool
hasThisExtension p ext = takeExtension p == T.unpack ext
|
tomv564/hfsnotify
|
src/System/FSNotify/Path.hs
|
bsd-3-clause
| 2,925
| 0
| 13
| 566
| 741
| 385
| 356
| -1
| -1
|
{-# LANGUAGE FlexibleContexts, DataKinds, ConstraintKinds #-}
module Text.GentleMark ( module Text.GentleMark.Term, Source, parse ) where
import Text.GentleMark.Term
import Text.GentleMark.Parsec
import Control.Applicative hiding ( many )
import Data.Functor.Identity
import Text.Parsec.Prim hiding ( parse )
import Text.Parsec.Char
type Source s = Stream s Identity Char
parse :: Source s => s -> [Term Toplevel]
parse = either (error . show) id . runParser (spaces *> many toplevelTerm) () ""
|
apsk/gentlemark
|
src/Text/GentleMark.hs
|
bsd-3-clause
| 514
| 0
| 9
| 86
| 145
| 85
| 60
| 11
| 1
|
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RebindableSyntax #-}
module Mantle.Examples.Counter where
import Mantle.Prelude
import Mantle.Logic
import Mantle.Interface
import Mantle.Synchronous
import Mantle.Verilog
counter :: SyncComp (Output Int)
counter out = component $ do
count <- reg 0
onClock $ do
count <=: rd count + 1
out =: rd count
extCounter :: Synchronous ()
extCounter = do
out <- make counter
ext <- extOutput "count"
ext =: out
counterCode = genModule "IntCounter" $ buildSync extCounter
|
aninhumer/mantle
|
src/Mantle/Examples/Counter.hs
|
bsd-3-clause
| 585
| 0
| 13
| 116
| 159
| 79
| 80
| 21
| 1
|
{-# LANGUAGE ExistentialQuantification, MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude, TypeFamilies #-}
module Network.NineP.Server.File.Internal
( NineP, NinePST
, CommonFile(..), File(..)
, File'(..), file'
) where
import Prelude hiding (read)
import Control.Monad.State(StateT(..))
import Control.Monad.Except(ExceptT, throwError)
import Data.Word(Word64, Word32)
import qualified Data.Map as M
import Control.Concurrent.MState (MState)
import qualified Data.ByteString.Lazy as L
import Data.NineP.Mode
import Data.NineP.Stat
import Network.NineP.Server.Error
type NineP t = MState t (ExceptT NinePError IO)
type NinePST s t = StateT s (MState t (ExceptT NinePError IO))
class CommonFile a s where
qidPath :: a -> NineP s Word64
qidVersion :: a -> NineP s Word32
stat :: a -> NineP s Stat
remove :: a -> NineP s ()
parent :: a -> NineP s (File' s)
wstat :: a -> WStat -> NineP s ()
class CommonFile a s => File a s where
type FileData a s
lookup :: a -> NineP s (M.Map String (File' s))
lookup _ = return M.empty
create :: a -> String -> Permission -> NineP s (File' s)
create _ _ _ = throwError ErrFidBadUse
open :: a -> Mode -> NineP s (FileData a s)
read :: a -> Word64 -> Word32 -> NinePST (FileData a s) s L.ByteString
write :: a -> Word64 -> L.ByteString -> NinePST (FileData a s) s Word32
clunk :: a -> Maybe (FileData a s) -> NineP s ()
data File' s = forall a.(File a s) => File' a (Maybe (FileData a s))
file' :: File a s => a -> File' s
file' file = File' file Nothing
|
Elemir/network-ninep
|
src/Network/NineP/Server/File/Internal.hs
|
bsd-3-clause
| 1,631
| 10
| 13
| 381
| 613
| 334
| 279
| 38
| 1
|
module Settings.TargetDirectory (
targetDirectory, targetPath, pkgDataFile, pkgHaddockFile, pkgLibraryFile,
pkgGhciLibraryFile
) where
import Base
import Expression
import Settings.User
-- TODO: move to Settings.hs?
-- User can override the default target directory settings given below
targetDirectory :: Stage -> Package -> FilePath
targetDirectory = userTargetDirectory
-- Path to the target directory from GHC source root
targetPath :: Stage -> Package -> FilePath
targetPath stage pkg = pkgPath pkg -/- targetDirectory stage pkg
pkgDataFile :: Stage -> Package -> FilePath
pkgDataFile stage pkg = targetPath stage pkg -/- "package-data.mk"
-- Relative path to a package haddock file, e.g.:
-- "libraries/array/dist-install/doc/html/array/array.haddock"
pkgHaddockFile :: Package -> FilePath
pkgHaddockFile pkg =
targetPath Stage1 pkg -/- "doc/html" -/- name -/- name <.> "haddock"
where name = pkgNameString pkg
-- Relative path to a package library file, e.g.:
-- "libraries/array/dist-install/build/libHSarray-0.5.1.0.a"
-- TODO: remove code duplication for computing buildPath
pkgLibraryFile :: Stage -> Package -> String -> Way -> Action FilePath
pkgLibraryFile stage pkg componentId way = do
extension <- libsuf way
let buildPath = targetPath stage pkg -/- "build"
return $ buildPath -/- "libHS" ++ componentId <.> extension
-- Relative path to a package ghci library file, e.g.:
-- "libraries/array/dist-install/build/HSarray-0.5.1.0.o"
pkgGhciLibraryFile :: Stage -> Package -> String -> FilePath
pkgGhciLibraryFile stage pkg componentId =
targetPath stage pkg -/- "build" -/- "HS" ++ componentId <.> "o"
|
quchen/shaking-up-ghc
|
src/Settings/TargetDirectory.hs
|
bsd-3-clause
| 1,659
| 0
| 11
| 259
| 315
| 166
| 149
| 24
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.