_id
stringlengths
64
64
repository
stringlengths
6
84
name
stringlengths
4
110
content
stringlengths
0
248k
license
null
download_url
stringlengths
89
454
language
stringclasses
7 values
comments
stringlengths
0
74.6k
code
stringlengths
0
248k
6f3e9152d7d1f9a0a09554077cbd4661259c0e72b04c787a4bfb6d09c668965b
haskell-mafia/mismi
Data.hs
# LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} module Mismi.IAM.Core.Data ( IamRole (..) ) where import P newtype IamRole = IamRole { iamRole :: Text } deriving (Eq, Show, Ord)
null
https://raw.githubusercontent.com/haskell-mafia/mismi/f6df07a52c6c8b1cf195b58d20ef109e390be014/mismi-iam-core/src/Mismi/IAM/Core/Data.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE NoImplicitPrelude # module Mismi.IAM.Core.Data ( IamRole (..) ) where import P newtype IamRole = IamRole { iamRole :: Text } deriving (Eq, Show, Ord)
408aea0f07f58a268e0f34e1f0dd81bf00d0704915b45a97d35dda4c23a34cc8
haskell-compat/base-compat
Compat.hs
# LANGUAGE CPP , NoImplicitPrelude # module Control.Monad.Compat ( module Base , Monad #if MIN_VERSION_base(4,9,0) , MonadFail #endif , fail , MonadPlus(..) #if !(MIN_VERSION_base(4,8,0)) , foldM , foldM_ , forM , forM_ , guard , mapM , mapM_ , msum , sequence , sequence_ , unless , when , (<$!>) #endif #if !(MIN_VERSION_base(4,9,0)) , forever , filterM , mapAndUnzipM , zipWithM , zipWithM_ , replicateM , replicateM_ #endif ) where #if MIN_VERSION_base(4,9,0) import Control.Monad as Base hiding (fail) import Control.Monad.Fail as Base #else import Control.Monad as Base hiding ( forever , filterM , mapAndUnzipM , zipWithM , zipWithM_ , replicateM , replicateM_ # if !(MIN_VERSION_base(4,8,0)) , foldM , foldM_ , forM , forM_ , guard , mapM , mapM_ , msum , sequence , sequence_ , unless , when # endif ) import Control.Applicative import Data.Foldable.Compat import Data.Traversable import Prelude.Compat #endif #if !(MIN_VERSION_base(4,8,0)) -- | Conditional execution of 'Applicative' expressions. For example, -- > when debug ( putStrLn " Debugging " ) -- will output the string @Debugging@ if the Boolean value @debug@ -- is 'True', and otherwise do nothing. when :: (Applicative f) => Bool -> f () -> f () # INLINEABLE when # {-# SPECIALISE when :: Bool -> IO () -> IO () #-} {-# SPECIALISE when :: Bool -> Maybe () -> Maybe () #-} when p s = if p then s else pure () | @'guard ' b@ is @'pure ' ( ) @ if is ' True ' , and ' empty ' if is ' False ' . guard :: (Alternative f) => Bool -> f () guard True = pure () guard False = empty -- | The reverse of 'when'. unless :: (Applicative f) => Bool -> f () -> f () # INLINEABLE unless # {-# SPECIALISE unless :: Bool -> IO () -> IO () #-} {-# SPECIALISE unless :: Bool -> Maybe () -> Maybe () #-} unless p s = if p then pure () else s | The ' foldM ' function is analogous to ' foldl ' , except that its result is encapsulated in a monad . Note that ' foldM ' works from left - to - right over the list arguments . This could be an issue where @('>>')@ and the ` folded function ' are not commutative . > foldM f a1 [ x1 , x2 , ... , xm ] = = > do > a2 < - f a1 x1 > a3 < - f a2 x2 > ... > f am xm If right - to - left evaluation is required , the input list should be reversed . Note : ' foldM ' is the same as ' foldlM ' encapsulated in a monad. Note that 'foldM' works from left-to-right over the list arguments. This could be an issue where @('>>')@ and the `folded function' are not commutative. > foldM f a1 [x1, x2, ..., xm] == > do > a2 <- f a1 x1 > a3 <- f a2 x2 > ... > f am xm If right-to-left evaluation is required, the input list should be reversed. Note: 'foldM' is the same as 'foldlM' -} foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b {-# INLINEABLE foldM #-} # SPECIALISE foldM : : ( a - > b - > IO a ) - > a - > [ b ] - > IO a # # SPECIALISE foldM : : ( a - > b - > Maybe a ) - > a - > [ b ] - > Maybe a # foldM = foldlM -- | Like 'foldM', but discards the result. foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () {-# INLINEABLE foldM_ #-} {-# SPECIALISE foldM_ :: (a -> b -> IO a) -> a -> [b] -> IO () #-} {-# SPECIALISE foldM_ :: (a -> b -> Maybe a) -> a -> [b] -> Maybe () #-} foldM_ f a xs = foldlM f a xs >> return () infixl 4 <$!> -- | Strict version of 'Data.Functor.<$>'. -- /Since : 4.8.0.0/ (<$!>) :: Monad m => (a -> b) -> m a -> m b {-# INLINE (<$!>) #-} f <$!> m = do x <- m let z = f x z `seq` return z #endif #if !(MIN_VERSION_base(4,9,0)) -- | @'forever' act@ repeats the action infinitely. forever :: (Applicative f) => f a -> f b # INLINE forever # forever a = let a' = a *> a' in a' -- Use explicit sharing here, as it is prevents a space leak regardless of -- optimizations. -- | This generalizes the list-based 'filter' function. # INLINE filterM # filterM :: (Applicative m) => (a -> m Bool) -> [a] -> m [a] filterM p = foldr (\ x -> liftA2 (\ flg -> if flg then (x:) else id) (p x)) (pure []) | The ' mapAndUnzipM ' function maps its first argument over a list , returning -- the result as a pair of lists. This function is mainly used with complicated -- data structures or a state-transforming monad. mapAndUnzipM :: (Applicative m) => (a -> m (b,c)) -> [a] -> m ([b], [c]) # INLINE mapAndUnzipM # mapAndUnzipM f xs = unzip <$> traverse f xs -- | The 'zipWithM' function generalizes 'zipWith' to arbitrary applicative functors. zipWithM :: (Applicative m) => (a -> b -> m c) -> [a] -> [b] -> m [c] # INLINE zipWithM # zipWithM f xs ys = sequenceA (zipWith f xs ys) -- | 'zipWithM_' is the extension of 'zipWithM' which ignores the final result. zipWithM_ :: (Applicative m) => (a -> b -> m c) -> [a] -> [b] -> m () # INLINE zipWithM _ # zipWithM_ f xs ys = sequenceA_ (zipWith f xs ys) | @'replicateM ' n act@ performs the action @n@ times , -- gathering the results. replicateM :: (Applicative m) => Int -> m a -> m [a] # INLINEABLE replicateM # # SPECIALISE replicateM : : Int - > IO a - > IO [ a ] # # SPECIALISE replicateM : : Int - > Maybe a - > Maybe [ a ] # replicateM cnt0 f = loop cnt0 where loop cnt | cnt <= 0 = pure [] | otherwise = liftA2 (:) f (loop (cnt - 1)) -- | Like 'replicateM', but discards the result. replicateM_ :: (Applicative m) => Int -> m a -> m () # INLINEABLE replicateM _ # # replicateM _ : : Int - > IO a - > IO ( ) # # replicateM _ : : Int - > Maybe a - > Maybe ( ) # replicateM_ cnt0 f = loop cnt0 where loop cnt | cnt <= 0 = pure () | otherwise = f *> loop (cnt - 1) #endif
null
https://raw.githubusercontent.com/haskell-compat/base-compat/847aa35c4142f529525ffc645cd035ddb23ce8ee/base-compat/src/Control/Monad/Compat.hs
haskell
| Conditional execution of 'Applicative' expressions. For example, is 'True', and otherwise do nothing. # SPECIALISE when :: Bool -> IO () -> IO () # # SPECIALISE when :: Bool -> Maybe () -> Maybe () # | The reverse of 'when'. # SPECIALISE unless :: Bool -> IO () -> IO () # # SPECIALISE unless :: Bool -> Maybe () -> Maybe () # # INLINEABLE foldM # | Like 'foldM', but discards the result. # INLINEABLE foldM_ # # SPECIALISE foldM_ :: (a -> b -> IO a) -> a -> [b] -> IO () # # SPECIALISE foldM_ :: (a -> b -> Maybe a) -> a -> [b] -> Maybe () # | Strict version of 'Data.Functor.<$>'. # INLINE (<$!>) # | @'forever' act@ repeats the action infinitely. Use explicit sharing here, as it is prevents a space leak regardless of optimizations. | This generalizes the list-based 'filter' function. the result as a pair of lists. This function is mainly used with complicated data structures or a state-transforming monad. | The 'zipWithM' function generalizes 'zipWith' to arbitrary applicative functors. | 'zipWithM_' is the extension of 'zipWithM' which ignores the final result. gathering the results. | Like 'replicateM', but discards the result.
# LANGUAGE CPP , NoImplicitPrelude # module Control.Monad.Compat ( module Base , Monad #if MIN_VERSION_base(4,9,0) , MonadFail #endif , fail , MonadPlus(..) #if !(MIN_VERSION_base(4,8,0)) , foldM , foldM_ , forM , forM_ , guard , mapM , mapM_ , msum , sequence , sequence_ , unless , when , (<$!>) #endif #if !(MIN_VERSION_base(4,9,0)) , forever , filterM , mapAndUnzipM , zipWithM , zipWithM_ , replicateM , replicateM_ #endif ) where #if MIN_VERSION_base(4,9,0) import Control.Monad as Base hiding (fail) import Control.Monad.Fail as Base #else import Control.Monad as Base hiding ( forever , filterM , mapAndUnzipM , zipWithM , zipWithM_ , replicateM , replicateM_ # if !(MIN_VERSION_base(4,8,0)) , foldM , foldM_ , forM , forM_ , guard , mapM , mapM_ , msum , sequence , sequence_ , unless , when # endif ) import Control.Applicative import Data.Foldable.Compat import Data.Traversable import Prelude.Compat #endif #if !(MIN_VERSION_base(4,8,0)) > when debug ( putStrLn " Debugging " ) will output the string @Debugging@ if the Boolean value @debug@ when :: (Applicative f) => Bool -> f () -> f () # INLINEABLE when # when p s = if p then s else pure () | @'guard ' b@ is @'pure ' ( ) @ if is ' True ' , and ' empty ' if is ' False ' . guard :: (Alternative f) => Bool -> f () guard True = pure () guard False = empty unless :: (Applicative f) => Bool -> f () -> f () # INLINEABLE unless # unless p s = if p then pure () else s | The ' foldM ' function is analogous to ' foldl ' , except that its result is encapsulated in a monad . Note that ' foldM ' works from left - to - right over the list arguments . This could be an issue where @('>>')@ and the ` folded function ' are not commutative . > foldM f a1 [ x1 , x2 , ... , xm ] = = > do > a2 < - f a1 x1 > a3 < - f a2 x2 > ... > f am xm If right - to - left evaluation is required , the input list should be reversed . Note : ' foldM ' is the same as ' foldlM ' encapsulated in a monad. Note that 'foldM' works from left-to-right over the list arguments. This could be an issue where @('>>')@ and the `folded function' are not commutative. > foldM f a1 [x1, x2, ..., xm] == > do > a2 <- f a1 x1 > a3 <- f a2 x2 > ... > f am xm If right-to-left evaluation is required, the input list should be reversed. Note: 'foldM' is the same as 'foldlM' -} foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b # SPECIALISE foldM : : ( a - > b - > IO a ) - > a - > [ b ] - > IO a # # SPECIALISE foldM : : ( a - > b - > Maybe a ) - > a - > [ b ] - > Maybe a # foldM = foldlM foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () foldM_ f a xs = foldlM f a xs >> return () infixl 4 <$!> /Since : 4.8.0.0/ (<$!>) :: Monad m => (a -> b) -> m a -> m b f <$!> m = do x <- m let z = f x z `seq` return z #endif #if !(MIN_VERSION_base(4,9,0)) forever :: (Applicative f) => f a -> f b # INLINE forever # forever a = let a' = a *> a' in a' # INLINE filterM # filterM :: (Applicative m) => (a -> m Bool) -> [a] -> m [a] filterM p = foldr (\ x -> liftA2 (\ flg -> if flg then (x:) else id) (p x)) (pure []) | The ' mapAndUnzipM ' function maps its first argument over a list , returning mapAndUnzipM :: (Applicative m) => (a -> m (b,c)) -> [a] -> m ([b], [c]) # INLINE mapAndUnzipM # mapAndUnzipM f xs = unzip <$> traverse f xs zipWithM :: (Applicative m) => (a -> b -> m c) -> [a] -> [b] -> m [c] # INLINE zipWithM # zipWithM f xs ys = sequenceA (zipWith f xs ys) zipWithM_ :: (Applicative m) => (a -> b -> m c) -> [a] -> [b] -> m () # INLINE zipWithM _ # zipWithM_ f xs ys = sequenceA_ (zipWith f xs ys) | @'replicateM ' n act@ performs the action @n@ times , replicateM :: (Applicative m) => Int -> m a -> m [a] # INLINEABLE replicateM # # SPECIALISE replicateM : : Int - > IO a - > IO [ a ] # # SPECIALISE replicateM : : Int - > Maybe a - > Maybe [ a ] # replicateM cnt0 f = loop cnt0 where loop cnt | cnt <= 0 = pure [] | otherwise = liftA2 (:) f (loop (cnt - 1)) replicateM_ :: (Applicative m) => Int -> m a -> m () # INLINEABLE replicateM _ # # replicateM _ : : Int - > IO a - > IO ( ) # # replicateM _ : : Int - > Maybe a - > Maybe ( ) # replicateM_ cnt0 f = loop cnt0 where loop cnt | cnt <= 0 = pure () | otherwise = f *> loop (cnt - 1) #endif
f2420b23b1f288af7c91489100e9bd9eeb3d4575a42d13b9083c3415385441bf
awolven/VkTk
imgui-package.lisp
Copyright 2019 < > ;; ;; Permission is hereby granted, free of charge, to any person obtaining ;; a copy of this software and associated documentation files (the " Software " ) , to deal in the Software without restriction , including ;; without limitation the rights to use, copy, modify, merge, publish, distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to ;; the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . ;; THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION ;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION ;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (in-package :cl-user) (defpackage :imgui (:nicknames :ig) (:use :cl :cffi) (:shadow) (:export #:bullet-text #:show-demo-window #:begin #:end #:set-next-window-pos #:set-next-window-size #:set-cursor-screen-pos #:text #:push-item-width #:pop-item-width #:calc-item-width #:push-text-wrap-pos #:push-allow-keyboard-focus #:pop-allow-keyboard-focus #:push-button-repeat #:pop-button-repeat #:separator #:same-line #:new-line #:spacing #:dummy #:indent #:unindent #:begin-group #:end-group #:imgui-get-cursor-pos #:get-cursor-pos-x #:get-cursor-pos-y #:get-cursor-start-pos #:get-cursor-screen-pos #:align-text-to-frame-padding #:get-text-line-height #:get-frame-height-with-spacing #:push-id #:pop-id #:get-id #:text-unformatted #:text-colored #:text-disabled #:text-wrapped #:label-text #:button #:small-button #:invisible-button #:arrow-button ;;#:image #:image-button #:checkbox #:checkbox-flags #:radio-button #:progress-bar #:bullet #:begin-combo #:end-combo #:combo #:drag-float #:drag-float2 #:drag-float3 #:drag-float4 #:drag-float-range2 #:drag-int #:drag-int2 #:drag-int3 #:drag-int-range2 #:drag-scalar #:drag-scalar-n #:slider-float #:slider-float2 #:slider-float3 #:slider-float4 #:slider-angle #:slider-int #:slider-int2 #:slider-int3 #:slider-int4 #:slider-scalar #:slider-scalar-n #:input-text #:input-text-multiline #:input-float #:input-float2 #:input-float3 #:input-float4 #:input-int #:input-int2 #:input-int3 #:input-int4 #:input-double #:input-scalar #:input-scalar-n #:color-edit #:color-edit3 #:color-edit4 #:color-picker3 #:color-picker4 #:color-button #:set-color-edit-options #:tree-node #:tree-node-ex #:tree-push #:tree-pop #:tree-advance-to-label-pos #:get-tree-node-to-label-spacing #:set-next-tree-node-open #:collapsing-header #:selectable #:list-box #:list-box-header #:list-box-footer #:plot-lines #:plot-histogram #:begin-main-menu-bar #:end-main-menu-bar #:begin-menu-bar #:end-menu-bar #:end-menu #:begin-tooltip #:end-tooltip #:set-tooltip #:open-popup #:begin-popup #:begin-popep-context-item #:begin-popup-context-window #:begin-popup-context-void #:begin-popup-modal #:end-popup #:begin-child #:bool-receptor #:flags-receptor #:get-receptor-value #:log-finish #:log-text #:log-to-clipboard #:key-pressed-p #:menu-item #:begin-menu #:ImVec2_Simple #:ImVec2_ImVec2 #:ImVec2_destroy #:ImVec2_ImVec2Float #:ImVec4_ImVec4 #:ImVec4_destroy #:ImVec4_ImVec4Float #:ImGuiWindowFlags_NoTitleBar #:ImGuiWindowFlags_NoResize #:ImGuiWindowFlags_NoMove #:ImGuiWindowFlags_NoScrollbar #:ImGuiWindowFlags_NoScrollWithMouse #:ImGuiWindowFlags_NoCollapse #:ImGuiWindowFlags_AlwaysAutoResize #:ImGuiWindowFlags_NoBackground #:ImGuiWindowFlags_NoMouseInputs #:ImGuiWindowFlags_NoSavedSettings #:ImGuiWindowFlags_NoInputs #:ImGuiWindowFlags_MenuBar #:ImGuiWindowFlags_HorizontalScrollbar #:ImGuiWindowFlags_NoFocusOnAppearing #:ImGuiWindowFlags_NoBringToFrontOnFocus #:ImGuiWindowFlags_AlwaysVerticalScrollbar #:ImGuiWindowFlags_AlwaysHorizontalScrollbar #:ImGuiWindowFlags_AlwaysUseWindowPadding #:ImGuiWindowFlags_ResizeFromAnySide #:ImGuiWindowFlags_NoNavInputs #:ImGuiWindowFlags_NoNavFocus #:ImGuiWindowFlags_UnsavedDocument #:ImGuiWindowFlags_NoNav #:ImGuiWindowFlags_NoDecoration #:ImGuiWindowFlags_NavFlattened #:ImGuiWindowFlags_ChildWindow #:ImGuiWindowFlags_Tooltip #:ImGuiWindowFlags_Popup #:ImGuiWindowFlags_Modal #:ImGuiWindowFlags_ChildMenu #:ImGuiInputTextFlags_CharsDecimal #:ImGuiInputTextFlags_CharsHexadecimal #:ImGuiInputTextFlags_CharsUppercase #:ImGuiInputTextFlags_CharsNoBlank #:ImGuiInputTextFlags_AutoSelectAll #:ImGuiInputTextFlags_EnterReturnsTrue #:ImGuiInputTextFlags_CallbackCompletion #:ImGuiInputTextFlags_CallbackHistory #:ImGuiInputTextFlags_CallbackAlways #:ImGuiInputTextFlags_CallbackCharFilter #:ImGuiInputTextFlags_AllowTabInput #:ImGuiInputTextFlags_CtrlEnterForNewLine #:ImGuiInputTextFlags_NoHorizontalScroll #:ImGuiInputTextFlags_AlwaysInsertMode #:ImGuiInputTextFlags_ReadOnly #:ImGuiInputTextFlags_Password #:ImGuiInputTextFlags_NoUndoRedo #:ImGuiTreeNodeFlags_Selected #:ImGuiTreeNodeFlags_Framed #:ImGuiTreeNodeFlags_AllowItemOverlap #:ImGuiTreeNodeFlags_NoTreePushOnOpen #:ImGuiTreeNodeFlags_NoAutoOpenOnLog #:ImGuiTreeNodeFlags_DefaultOpen #:ImGuiTreeNodeFlags_OpenOnDoubleClick #:ImGuiTreeNodeFlags_OpenOnArrow #:ImGuiTreeNodeFlags_Leaf #:ImGuiTreeNodeFlags_Bullet #:ImGuiTreeNodeFlags_FramePadding #:ImGuiTreeNodeFlags_NavLeftJumpsBackHere #:ImGuiTreeNodeFlags_CollapsingHeader #:ImGuiSelectableFlags_DontClosePopups #:ImGuiSelectableFlags_SpanAllColumns #:ImGuiSelectableFlags_AllowDoubleClick #:ImGuiComboFlags_PopupAlignLeft #:ImGuiComboFlags_HeightSmall #:ImGuiComboFlags_HeightRegular #:ImGuiComboFlags_HeightLarge #:ImGuiComboFlags_HeightLargest #:ImGuiComboFlags_HeightMask_ #:ImGuiFocusedFlags_ChildWindows #:ImGuiFocusedFlags_RootWindow #:ImGuiFocusedFlags_RootAndChildWindows #:ImGuiHoveredFlags_ChildWindows #:ImGuiHoveredFlags_RootWindow #:ImGuiHoveredFlags_AllowWhenBlockedByPopup #:ImGuiHoveredFlags_AllowWhenBlockedByActiveItem #:ImGuiHoveredFlags_AllowWhenOverlapped #:ImGuiHoveredFlags_RectOnly #:ImGuiHoveredFlags_RootAndChildWindows #:ImGuiDragDropFlags_SourceNoPreviewTooltip #:ImGuiDragDropFlags_SourceNoDisableHover #:ImGuiDragDropFlags_SourceNoHoldToOpenOthers #:ImGuiDragDropFlags_SourceAllowNullID #:ImGuiDragDropFlags_SourceExtern #:ImGuiDragDropFlags_AcceptBeforeDelivery #:ImGuiDragDropFlags_AcceptNoDrawDefaultRect #:ImGuiDragDropFlags_AcceptPeekOnly #:ImGuiKey_Tab #:ImGuiKey_LeftArrow #:ImGuiKey_RightArrow #:ImGuiKey_UpArrow #:ImGuiKey_DownArrow #:ImGuiKey_PageUp #:ImGuiKey_PageDown #:ImGuiKey_Home #:ImGuiKey_End #:ImGuiKey_Delete #:ImGuiKey_Backspace #:ImGuiKey_Enter #:ImGuiKey_Escape #:ImGuiKey_A #:ImGuiKey_C #:ImGuiKey_V #:ImGuiKey_X #:ImGuiKey_Y #:ImGuiKey_Z #:ImGuiKey_COUNT #:ImGuiCol_Text #:ImGuiCol_TextDisabled #:ImGuiCol_WindowBg #:ImGuiCol_ChildBg #:ImGuiCol_PopupBg #:ImGuiCol_Border #:ImGuiCol_BorderShadow #:ImGuiCol_FrameBg #:ImGuiCol_FrameBgHovered #:ImGuiCol_FrameBgActive #:ImGuiCol_TitleBg #:ImGuiCol_TitleBgActive #:ImGuiCol_TitleBgCollapsed #:ImGuiCol_MenuBarBg #:ImGuiCol_ScrollbarBg #:ImGuiCol_ScrollbarGrab #:ImGuiCol_ScrollbarGrabHovered #:ImGuiCol_ScrollbarGrabActive #:ImGuiCol_CheckMark #:ImGuiCol_SliderGrab #:ImGuiCol_SliderGrabActive #:ImGuiCol_Button #:ImGuiCol_ButtonHovered #:ImGuiCol_ButtonActive #:ImGuiCol_Header #:ImGuiCol_HeaderHovered #:ImGuiCol_HeaderActive #:ImGuiCol_Separator #:ImGuiCol_SeparatorHovered #:ImGuiCol_SeparatorActive #:ImGuiCol_ResizeGrip #:ImGuiCol_ResizeGripHovered #:ImGuiCol_ResizeGripActive #:ImGuiCol_CloseButton #:ImGuiCol_CloseButtonHovered #:ImGuiCol_CloseButtonActive #:ImGuiCol_PlotLines #:ImGuiCol_PlotLinesHovered #:ImGuiCol_PlotHistogram #:ImGuiCol_PlotHistogramHovered #:ImGuiCol_TextSelectedBg #:ImGuiCol_ModalWindowDarkening #:ImGuiCol_DragDropTarget #:ImGuiCol_COUNT #:ImGuiStyleVar_Alpha #:ImGuiStyleVar_WindowPadding #:ImGuiStyleVar_WindowRounding #:ImGuiStyleVar_WindowBorderSize #:ImGuiStyleVar_WindowMinSize #:ImGuiStyleVar_ChildRounding #:ImGuiStyleVar_ChildBorderSize #:ImGuiStyleVar_PopupRounding #:ImGuiStyleVar_PopupBorderSize #:ImGuiStyleVar_FramePadding #:ImGuiStyleVar_FrameRounding #:ImGuiStyleVar_FrameBorderSize #:ImGuiStyleVar_ItemSpacing #:ImGuiStyleVar_ItemInnerSpacing #:ImGuiStyleVar_IndentSpacing #:ImGuiStyleVar_GrabMinSize #:ImGuiStyleVar_ButtonTextAlign #:ImGuiStyleVar_Count_ #:ImGuiColorEditFlags_NoAlpha #:ImGuiColorEditFlags_NoPicker #:ImGuiColorEditFlags_NoOptions #:ImGuiColorEditFlags_NoSmallPreview #:ImGuiColorEditFlags_NoInputs #:ImGuiColorEditFlags_NoTooltip #:ImGuiColorEditFlags_NoLabel #:ImGuiColorEditFlags_NoSidePreview #:ImGuiColorEditFlags_NoDragDrop #:ImGuiColorEditFlags_AlphaBar #:ImGuiColorEditFlags_AlphaPreview #:ImGuiColorEditFlags_AlphaPreviewHalf #:ImGuiColorEditFlags_HDR #:ImGuiColorEditFlags_RGB #:ImGuiColorEditFlags_HSV #:ImGuiColorEditFlags_HEX #:ImGuiColorEditFlags_Uint8 #:ImGuiColorEditFlags_Float #:ImGuiColorEditFlags_PickerHueBar #:ImGuiColorEditFlags_PickerHueWheel #:ImGuiMouseCursor_None #:ImGuiMouseCursor_Arrow #:ImGuiMouseCursor_TextInput #:ImGuiMouseCursor_Move #:ImGuiMouseCursor_ResizeNS #:ImGuiMouseCursor_ResizeEW #:ImGuiMouseCursor_ResizeNESW #:ImGuiMouseCursor_ResizeNWSE #:ImGuiMouseCursor_Count_ #:ImGuiCond_Always #:ImGuiCond_Once #:ImGuiCond_FirstUseEver #:ImGuiCond_Appearing #:ImDrawCornerFlags_TopLeft #:ImDrawCornerFlags_TopRight #:ImDrawCornerFlags_BotLeft #:ImDrawCornerFlags_BotRight #:ImDrawCornerFlags_Top #:ImDrawCornerFlags_Bot #:ImDrawCornerFlags_Left #:ImDrawCornerFlags_Right #:ImDrawCornerFlags_All #:ImDrawListFlags_AntiAliasedLines #:ImDrawListFlags_AntiAliasedFill #:igCreateContext #:igDestroyContext #:igGetCurrentContext #:igSetCurrentContext #:igDebugCheckVersionAndDataLayout #:igGetIO #:igGetStyle #:igNewFrame #:igEndFrame #:igRender #:igGetDrawData #:igShowDemoWindow #:igShowAboutWindow #:igShowMetricsWindow #:igShowStyleEditor #:igShowStyleSelector #:igShowFontSelector #:igShowUserGuide #:igGetVersion #:igStyleColorsDark #:igStyleColorsClassic #:igStyleColorsLight #:igBegin #:igEnd #:igBeginChildID #:igEndChild #:igIsWindowAppearing #:igIsWindowCollapsed #:igIsWindowFocused #:igIsWindowHovered #:igGetWindowDrawList #:igGetWindowPos #:igGetWindowSize #:igGetWindowWidth #:igGetWindowHeight #:igGetContentRegionMax #:igGetContentRegionAvail #:igGetContentRegionAvailWidth #:igGetWindowContentRegionMin #:igGetWindowContentRegionMax #:igGetWindowContentRegionWidth #:igSetNextWindowCollapsed #:igSetNextWindowFocus #:igSetNextWindowBgAlpha #:igSetWindowCollapsedBool #:igSetWindowFocus #:igSetWindowFontScale #:igSetWindowCollapsedStr #:igSetWindowFocusStr #:igGetScrollX #:igGetScrollY #:igGetScrollMaxX #:igGetScrollMaxY #:igSetScrollX #:igSetScrollY #:igSetScrollHereY #:igSetScrollFromPosY #:igPushFont #:igPopFont #:igPushStyleColorU32 #:igPopStyleColor #:igPushStyleVarFloat #:igPopStyleVar #:igGetStyleColorVec4 #:igGetFont #:igGetFontSize #:igGetFontTexUvWhitePixel #:igGetColorU32 #:igGetColorU32Vec4 #:igGetColorU32U32 #:igPushItemWidth #:igPopItemWidth #:igCalcItemWidth #:igPushTextWrapPos #:igPopTextWrapPos #:igPushAllowKeyboardFocus #:igPopAllowKeyboardFocus #:igPushButtonRepeat #:igPopButtonRepeat #:igSeparator #:igSameLine #:igNewLine #:igSpacing #:igDummy #:igIndent #:igUnindent #:igBeginGroup #:igEndGroup #:igGetCursorPos #:igGetCursorPosX #:igGetCursorPosY #:igSetCursorPosX #:igSetCursorPosY #:igGetCursorStartPos #:igGetCursorScreenPos #:igAlignTextToFramePadding #:igGetTextLineHeight #:igGetTextLineHeightWithSpacing #:igGetFrameHeight #:igGetFrameHeightWithSpacing #:igPushIDStr #:igPushIDRange #:igPushIDPtr #:igPushIDInt #:igPopID #:igGetIDStr #:igGetIDRange #:igGetIDPtr #:igTextUnformatted #:igText #:igTextV #:igTextDisabled #:igTextDisabledV #:igTextWrapped #:igTextWrappedV #:igLabelText #:igLabelTextV #:igBulletText #:igBulletTextV #:igSmallButton #:igArrowButton #:igCheckbox #:igCheckboxFlags #:igRadioButtonBool #:igRadioButtonIntPtr #:igProgressBar #:igBullet #:igBeginCombo #:igEndCombo #:igCombo #:igComboStr #:igComboFnPtr #:igDragFloat #:igDragFloat2 #:igDragFloat3 #:igDragFloat4 #:igDragFloatRange2 #:igDragInt #:igDragInt2 #:igDragInt3 #:igDragInt4 #:igDragIntRange2 #:igDragScalar #:igDragScalarN #:igSliderFloat #:igSliderFloat2 #:igSliderFloat3 #:igSliderFloat4 #:igSliderAngle #:igSliderInt #:igSliderInt2 #:igSliderInt3 #:igSliderInt4 #:igSliderScalar #:igSliderScalarN #:igVSliderFloat #:igVSliderInt #:igVSliderScalar #:igInputText #:igInputTextMultiline #:igInputFloat #:igInputFloat2 #:igInputFloat3 #:igInputFloat4 #:igInputInt #:igInputInt2 #:igInputInt3 #:igInputInt4 #:igInputDouble #:igInputScalar #:igInputScalarN #:igColorEdit3 #:igColorEdit4 #:igColorPicker3 #:igColorPicker4 #:igColorButton #:igSetColorEditOptions #:igTreeNodeStr #:igTreeNodeStrStr #:igTreeNodePtr #:igTreeNodeVStr #:igTreeNodeVPtr #:igTreeNodeExStr #:igTreeNodeExStrStr #:igTreeNodeExPtr #:igTreeNodeExVStr #:igTreeNodeExVPtr #:igTreePushStr #:igTreePushPtr #:igTreePop #:igTreeAdvanceToLabelPos #:igGetTreeNodeToLabelSpacing #:igSetNextTreeNodeOpen #:igCollapsingHeader #:igCollapsingHeaderBoolPtr #:igSelectable #:igSelectableBoolPtr #:igListBoxStr_arr #:igListBoxFnPtr #:igListBoxHeaderVec2 #:igListBoxHeaderInt #:igListBoxFooter #:igValueBool #:igValueInt #:igValueUint #:igValueFloat #:igBeginMainMenuBar #:igEndMainMenuBar #:igBeginMenuBar #:igEndMenuBar #:igBeginMenu #:igEndMenu #:igMenuItemBool #:igMenuItemBoolPtr #:igBeginTooltip #:igEndTooltip #:igSetTooltip #:igSetTooltipV #:igOpenPopup #:igBeginPopup #:igBeginPopupContextItem #:igBeginPopupContextWindow #:igBeginPopupContextVoid #:igBeginPopupModal #:igEndPopup #:igOpenPopupOnItemClick #:igIsPopupOpen #:igCloseCurrentPopup #:igColumns #:igNextColumn #:igGetColumnIndex #:igGetColumnWidth #:igSetColumnWidth #:igGetColumnOffset #:igSetColumnOffset #:igGetColumnsCount #:igBeginTabBar #:igEndTabBar #:igBeginTabItem #:igEndTabItem #:igSetTabItemClosed #:igLogToTTY #:igLogToFile #:igLogToClipboard #:igLogFinish #:igLogButtons #:igBeginDragDropSource #:igSetDragDropPayload #:igEndDragDropSource #:igBeginDragDropTarget #:igAcceptDragDropPayload #:igEndDragDropTarget #:igGetDragDropPayload #:igPushClipRect #:igPopClipRect #:igSetItemDefaultFocus #:igSetKeyboardFocusHere #:igIsItemHovered #:igIsItemActive #:igIsItemFocused #:igIsItemClicked #:igIsItemVisible #:igIsItemEdited #:igIsItemActivated #:igIsItemDeactivated #:igIsItemDeactivatedAfterEdit #:igIsAnyItemHovered #:igIsAnyItemActive #:igIsAnyItemFocused #:igGetItemRectMin #:igGetItemRectMax #:igGetItemRectSize #:igSetItemAllowOverlap #:igIsRectVisible #:igIsRectVisibleVec2 #:igGetTime #:igGetFrameCount #:igGetOverlayDrawList #:igGetDrawListSharedData #:igGetStyleColorName #:igSetStateStorage #:igGetStateStorage #:igCalcTextSize #:igCalcListClipping #:igBeginChildFrame #:igEndChildFrame #:igColorConvertU32ToFloat4 #:igColorConvertFloat4ToU32 #:igGetKeyIndex #:igIsKeyDown #:igIsKeyPressed #:igIsKeyReleased #:igGetKeyPressedAmount #:igIsMouseDown #:igIsAnyMouseDown #:igIsMouseClicked #:igIsMouseDoubleClicked #:igIsMouseReleased #:igIsMouseDragging #:igIsMouseHoveringRect #:igIsMousePosValid #:igGetMousePos #:igGetMousePosOnOpeningCurrentPopup #:igGetMouseDragDelta #:igResetMouseDragDelta #:igGetMouseCursor #:igSetMouseCursor #:igCaptureKeyboardFromApp #:igCaptureMouseFromApp #:igGetClipboardText #:igSetClipboardText #:igLoadIniSettingsFromDisk #:igLoadIniSettingsFromMemory #:igSaveIniSettingsToDisk #:igSaveIniSettingsToMemory #:igSetAllocatorFunctions #:igMemAlloc #:igMemFree #:ImGuiStyle_ImGuiStyle #:ImGuiStyle_destroy #:ImGuiStyle_ScaleAllSizes #:ImGuiIO_AddInputCharacter #:ImGuiIO_AddInputCharactersUTF8 #:ImGuiIO_ClearInputCharacters #:ImGuiIO_ImGuiIO #:ImGuiIO_destroy #:ImGuiInputTextCallbackData_ImGuiInputTextCallbackData #:ImGuiInputTextCallbackData_destroy #:ImGuiInputTextCallbackData_DeleteChars #:ImGuiInputTextCallbackData_InsertChars #:ImGuiInputTextCallbackData_HasSelection #:ImGuiPayload_ImGuiPayload #:ImGuiPayload_destroy #:ImGuiPayload_Clear #:ImGuiPayload_IsDataType #:ImGuiPayload_IsPreview #:ImGuiPayload_IsDelivery #:ImGuiOnceUponAFrame_ImGuiOnceUponAFrame #:ImGuiOnceUponAFrame_destroy #:ImGuiTextFilter_ImGuiTextFilter #:ImGuiTextFilter_destroy #:ImGuiTextFilter_Draw #:ImGuiTextFilter_PassFilter #:ImGuiTextFilter_Build #:ImGuiTextFilter_Clear #:ImGuiTextFilter_IsActive #:TextRange_TextRange #:TextRange_destroy #:TextRange_TextRangeStr #:TextRange_begin #:TextRange_end #:TextRange_empty #:TextRange_split #:ImGuiTextBuffer_ImGuiTextBuffer #:ImGuiTextBuffer_destroy #:ImGuiTextBuffer_begin #:ImGuiTextBuffer_end #:ImGuiTextBuffer_size #:ImGuiTextBuffer_empty #:ImGuiTextBuffer_clear #:ImGuiTextBuffer_reserve #:ImGuiTextBuffer_c_str #:ImGuiTextBuffer_append #:ImGuiTextBuffer_appendfv #:Pair_PairInt #:Pair_destroy #:Pair_PairFloat #:Pair_PairPtr #:ImGuiStorage_Clear #:ImGuiStorage_GetInt #:ImGuiStorage_SetInt #:ImGuiStorage_GetBool #:ImGuiStorage_SetBool #:ImGuiStorage_GetFloat #:ImGuiStorage_SetFloat #:ImGuiStorage_GetVoidPtr #:ImGuiStorage_SetVoidPtr #:ImGuiStorage_GetIntRef #:ImGuiStorage_GetBoolRef #:ImGuiStorage_GetFloatRef #:ImGuiStorage_GetVoidPtrRef #:ImGuiStorage_SetAllInt #:ImGuiStorage_BuildSortByKey #:ImGuiListClipper_ImGuiListClipper #:ImGuiListClipper_destroy #:ImGuiListClipper_Step #:ImGuiListClipper_Begin #:ImGuiListClipper_End #:ImColor_ImColor #:ImColor_destroy #:ImColor_ImColorInt #:ImColor_ImColorU32 #:ImColor_ImColorFloat #:ImColor_ImColorVec4 #:ImColor_SetHSV #:ImColor_HSV #:ImDrawCmd_ImDrawCmd #:ImDrawCmd_destroy #:ImDrawList_ImDrawList #:ImDrawList_destroy #:ImDrawList_PushClipRect #:ImDrawList_PushClipRectFullScreen #:ImDrawList_PopClipRect #:ImDrawList_PushTextureID #:ImDrawList_PopTextureID #:ImDrawList_GetClipRectMin #:ImDrawList_GetClipRectMax #:ImDrawList_AddLine #:ImDrawList_AddRect #:ImDrawList_AddRectFilled #:ImDrawList_AddRectFilledMultiColor #:ImDrawList_AddQuad #:ImDrawList_AddQuadFilled #:ImDrawList_AddTriangle #:ImDrawList_AddTriangleFilled #:ImDrawList_AddCircle #:ImDrawList_AddCircleFilled #:ImDrawList_AddText #:ImDrawList_AddTextFontPtr #:ImDrawList_AddImage #:ImDrawList_AddImageQuad #:ImDrawList_AddImageRounded #:ImDrawList_AddPolyline #:ImDrawList_AddConvexPolyFilled #:ImDrawList_AddBezierCurve #:ImDrawList_PathClear #:ImDrawList_PathLineTo #:ImDrawList_PathLineToMergeDuplicate #:ImDrawList_PathFillConvex #:ImDrawList_PathStroke #:ImDrawList_PathArcTo #:ImDrawList_PathArcToFast #:ImDrawList_PathBezierCurveTo #:ImDrawList_PathRect #:ImDrawList_ChannelsSplit #:ImDrawList_ChannelsMerge #:ImDrawList_ChannelsSetCurrent #:ImDrawList_AddCallback #:ImDrawList_AddDrawCmd #:ImDrawList_CloneOutput #:ImDrawList_Clear #:ImDrawList_ClearFreeMemory #:ImDrawList_PrimReserve #:ImDrawList_PrimRect #:ImDrawList_PrimRectUV #:ImDrawList_PrimQuadUV #:ImDrawList_PrimWriteVtx #:ImDrawList_PrimWriteIdx #:ImDrawList_PrimVtx #:ImDrawList_UpdateClipRect #:ImDrawList_UpdateTextureID #:ImDrawData_ImDrawData #:ImDrawData_destroy #:ImDrawData_Clear #:ImDrawData_DeIndexAllBuffers #:ImDrawData_ScaleClipRects #:ImFontConfig_ImFontConfig #:ImFontConfig_destroy #:ImFontGlyphRangesBuilder_ImFontGlyphRangesBuilder #:ImFontGlyphRangesBuilder_destroy #:ImFontGlyphRangesBuilder_GetBit #:ImFontGlyphRangesBuilder_SetBit #:ImFontGlyphRangesBuilder_AddChar #:ImFontGlyphRangesBuilder_AddText #:ImFontGlyphRangesBuilder_AddRanges #:ImFontGlyphRangesBuilder_BuildRanges #:ImFontAtlas_ImFontAtlas #:ImFontAtlas_destroy #:ImFontAtlas_AddFont #:ImFontAtlas_AddFontDefault #:ImFontAtlas_AddFontFromFileTTF #:ImFontAtlas_AddFontFromMemoryTTF #:ImFontAtlas_AddFontFromMemoryCompressedTTF #:ImFontAtlas_AddFontFromMemoryCompressedBase85TTF #:ImFontAtlas_ClearInputData #:ImFontAtlas_ClearTexData #:ImFontAtlas_ClearFonts #:ImFontAtlas_Clear #:ImFontAtlas_Build #:ImFontAtlas_GetTexDataAsAlpha8 #:ImFontAtlas_GetTexDataAsRGBA32 #:ImFontAtlas_IsBuilt #:ImFontAtlas_SetTexID #:ImFontAtlas_GetGlyphRangesDefault #:ImFontAtlas_GetGlyphRangesKorean #:ImFontAtlas_GetGlyphRangesJapanese #:ImFontAtlas_GetGlyphRangesChineseFull #:ImFontAtlas_GetGlyphRangesChineseSimplifiedCommon #:ImFontAtlas_GetGlyphRangesCyrillic #:ImFontAtlas_GetGlyphRangesThai #:CustomRect_CustomRect #:CustomRect_destroy #:CustomRect_IsPacked #:ImFontAtlas_AddCustomRectRegular #:ImFontAtlas_AddCustomRectFontGlyph #:ImFontAtlas_GetCustomRectByIndex #:ImFontAtlas_CalcCustomRectUV #:ImFontAtlas_GetMouseCursorTexData #:ImFont_ImFont #:ImFont_destroy #:ImFont_FindGlyph #:ImFont_FindGlyphNoFallback #:ImFont_GetCharAdvance #:ImFont_IsLoaded #:ImFont_GetDebugName #:ImFont_CalcTextSizeA #:ImFont_CalcWordWrapPositionA #:ImFont_RenderChar #:ImFont_RenderText #:ImFont_BuildLookupTable #:ImFont_ClearOutputData #:ImFont_GrowIndex #:ImFont_AddGlyph #:ImFont_AddRemapChar #:ImFont_SetFallbackChar #:igGetWindowPos_nonUDT #:igGetWindowSize_nonUDT #:igGetContentRegionMax_nonUDT #:igGetContentRegionAvail_nonUDT #:igGetWindowContentRegionMin_nonUDT #:igGetWindowContentRegionMax_nonUDT #:igGetFontTexUvWhitePixel_nonUDT #:igGetCursorPos_nonUDT #:igGetCursorStartPos_nonUDT #:igGetCursorScreenPos_nonUDT #:igGetItemRectMin_nonUDT #:igGetItemRectMax_nonUDT #:igGetItemRectSize_nonUDT #:igCalcTextSize_nonUDT #:igColorConvertU32ToFloat4_nonUDT #:igGetMousePos_nonUDT #:igGetMousePosOnOpeningCurrentPopup_nonUDT #:igGetMouseDragDelta_nonUDT #:ImColor_HSV_nonUDT #:ImDrawList_GetClipRectMin_nonUDT #:ImDrawList_GetClipRectMax_nonUDT #:ImFont_CalcTextSizeA_nonUDT #:ImVector_float_ImVector_float #:ImVector_float_destroy #:ImVector_ImWchar_ImVector_ImWchar #:ImVector_ImWchar_destroy #:ImVector_ImFontConfig_ImVector_ImFontConfig #:ImVector_ImFontConfig_destroy #:ImVector_ImFontGlyph_ImVector_ImFontGlyph #:ImVector_ImFontGlyph_destroy #:ImVector_TextRange_ImVector_TextRange #:ImVector_TextRange_destroy #:ImVector_CustomRect_ImVector_CustomRect #:ImVector_CustomRect_destroy #:ImVector_ImDrawChannel_ImVector_ImDrawChannel #:ImVector_ImDrawChannel_destroy #:ImVector_char_ImVector_char #:ImVector_char_destroy #:ImVector_ImTextureID_ImVector_ImTextureID #:ImVector_ImTextureID_destroy #:ImVector_ImDrawVert_ImVector_ImDrawVert #:ImVector_ImDrawVert_destroy #:ImVector_int_ImVector_int #:ImVector_int_destroy #:ImVector_Pair_ImVector_Pair #:ImVector_Pair_destroy #:ImVector_ImFontPtr_ImVector_ImFontPtr #:ImVector_ImFontPtr_destroy #:ImVector_ImVec4_ImVector_ImVec4 #:ImVector_ImVec4_destroy #:ImVector_ImDrawCmd_ImVector_ImDrawCmd #:ImVector_ImDrawCmd_destroy #:ImVector_ImDrawIdx_ImVector_ImDrawIdx #:ImVector_ImDrawIdx_destroy #:ImVector_ImVec2_ImVector_ImVec2 #:ImVector_ImVec2_destroy #:ImVector_float_ImVector_floatVector #:ImVector_ImWchar_ImVector_ImWcharVector #:ImVector_ImFontConfig_ImVector_ImFontConfigVector #:ImVector_ImFontGlyph_ImVector_ImFontGlyphVector #:ImVector_TextRange_ImVector_TextRangeVector #:ImVector_CustomRect_ImVector_CustomRectVector #:ImVector_ImDrawChannel_ImVector_ImDrawChannelVector #:ImVector_char_ImVector_charVector #:ImVector_ImTextureID_ImVector_ImTextureIDVector #:ImVector_ImDrawVert_ImVector_ImDrawVertVector #:ImVector_int_ImVector_intVector #:ImVector_Pair_ImVector_PairVector #:ImVector_ImFontPtr_ImVector_ImFontPtrVector #:ImVector_ImVec4_ImVector_ImVec4Vector #:ImVector_ImDrawCmd_ImVector_ImDrawCmdVector #:ImVector_ImDrawIdx_ImVector_ImDrawIdxVector #:ImVector_ImVec2_ImVector_ImVec2Vector #:ImVector_float_empty #:ImVector_ImWchar_empty #:ImVector_ImFontConfig_empty #:ImVector_ImFontGlyph_empty #:ImVector_TextRange_empty #:ImVector_CustomRect_empty #:ImVector_ImDrawChannel_empty #:ImVector_char_empty #:ImVector_ImTextureID_empty #:ImVector_ImDrawVert_empty #:ImVector_int_empty #:ImVector_Pair_empty #:ImVector_ImFontPtr_empty #:ImVector_ImVec4_empty #:ImVector_ImDrawCmd_empty #:ImVector_ImDrawIdx_empty #:ImVector_ImVec2_empty #:ImVector_float_size #:ImVector_ImWchar_size #:ImVector_ImFontConfig_size #:ImVector_ImFontGlyph_size #:ImVector_TextRange_size #:ImVector_CustomRect_size #:ImVector_ImDrawChannel_size #:ImVector_char_size #:ImVector_ImTextureID_size #:ImVector_ImDrawVert_size #:ImVector_int_size #:ImVector_Pair_size #:ImVector_ImFontPtr_size #:ImVector_ImVec4_size #:ImVector_ImDrawCmd_size #:ImVector_ImDrawIdx_size #:ImVector_ImVec2_size #:ImVector_float_size_in_bytes #:ImVector_ImWchar_size_in_bytes #:ImVector_ImFontConfig_size_in_bytes #:ImVector_ImFontGlyph_size_in_bytes #:ImVector_TextRange_size_in_bytes #:ImVector_CustomRect_size_in_bytes #:ImVector_ImDrawChannel_size_in_bytes #:ImVector_char_size_in_bytes #:ImVector_ImTextureID_size_in_bytes #:ImVector_ImDrawVert_size_in_bytes #:ImVector_int_size_in_bytes #:ImVector_Pair_size_in_bytes #:ImVector_ImFontPtr_size_in_bytes #:ImVector_ImVec4_size_in_bytes #:ImVector_ImDrawCmd_size_in_bytes #:ImVector_ImDrawIdx_size_in_bytes #:ImVector_ImVec2_size_in_bytes #:ImVector_float_capacity #:ImVector_ImWchar_capacity #:ImVector_ImFontConfig_capacity #:ImVector_ImFontGlyph_capacity #:ImVector_TextRange_capacity #:ImVector_CustomRect_capacity #:ImVector_ImDrawChannel_capacity #:ImVector_char_capacity #:ImVector_ImTextureID_capacity #:ImVector_ImDrawVert_capacity #:ImVector_int_capacity #:ImVector_Pair_capacity #:ImVector_ImFontPtr_capacity #:ImVector_ImVec4_capacity #:ImVector_ImDrawCmd_capacity #:ImVector_ImDrawIdx_capacity #:ImVector_ImVec2_capacity #:ImVector_float_clear #:ImVector_ImWchar_clear #:ImVector_ImFontConfig_clear #:ImVector_ImFontGlyph_clear #:ImVector_TextRange_clear #:ImVector_CustomRect_clear #:ImVector_ImDrawChannel_clear #:ImVector_char_clear #:ImVector_ImTextureID_clear #:ImVector_ImDrawVert_clear #:ImVector_int_clear #:ImVector_Pair_clear #:ImVector_ImFontPtr_clear #:ImVector_ImVec4_clear #:ImVector_ImDrawCmd_clear #:ImVector_ImDrawIdx_clear #:ImVector_ImVec2_clear #:ImVector_float_begin #:ImVector_ImWchar_begin #:ImVector_ImFontConfig_begin #:ImVector_ImFontGlyph_begin #:ImVector_TextRange_begin #:ImVector_CustomRect_begin #:ImVector_ImDrawChannel_begin #:ImVector_char_begin #:ImVector_ImTextureID_begin #:ImVector_ImDrawVert_begin #:ImVector_int_begin #:ImVector_Pair_begin #:ImVector_ImFontPtr_begin #:ImVector_ImVec4_begin #:ImVector_ImDrawCmd_begin #:ImVector_ImDrawIdx_begin #:ImVector_ImVec2_begin #:ImVector_float_begin_const #:ImVector_ImWchar_begin_const #:ImVector_ImFontConfig_begin_const #:ImVector_ImFontGlyph_begin_const #:ImVector_TextRange_begin_const #:ImVector_CustomRect_begin_const #:ImVector_ImDrawChannel_begin_const #:ImVector_char_begin_const #:ImVector_ImTextureID_begin_const #:ImVector_ImDrawVert_begin_const #:ImVector_int_begin_const #:ImVector_Pair_begin_const #:ImVector_ImFontPtr_begin_const #:ImVector_ImVec4_begin_const #:ImVector_ImDrawCmd_begin_const #:ImVector_ImDrawIdx_begin_const #:ImVector_ImVec2_begin_const #:ImVector_float_end #:ImVector_ImWchar_end #:ImVector_ImFontConfig_end #:ImVector_ImFontGlyph_end #:ImVector_TextRange_end #:ImVector_CustomRect_end #:ImVector_ImDrawChannel_end #:ImVector_char_end #:ImVector_ImTextureID_end #:ImVector_ImDrawVert_end #:ImVector_int_end #:ImVector_Pair_end #:ImVector_ImFontPtr_end #:ImVector_ImVec4_end #:ImVector_ImDrawCmd_end #:ImVector_ImDrawIdx_end #:ImVector_ImVec2_end #:ImVector_float_end_const #:ImVector_ImWchar_end_const #:ImVector_ImFontConfig_end_const #:ImVector_ImFontGlyph_end_const #:ImVector_TextRange_end_const #:ImVector_CustomRect_end_const #:ImVector_ImDrawChannel_end_const #:ImVector_char_end_const #:ImVector_ImTextureID_end_const #:ImVector_ImDrawVert_end_const #:ImVector_int_end_const #:ImVector_Pair_end_const #:ImVector_ImFontPtr_end_const #:ImVector_ImVec4_end_const #:ImVector_ImDrawCmd_end_const #:ImVector_ImDrawIdx_end_const #:ImVector_ImVec2_end_const #:ImVector_float_front #:ImVector_ImWchar_front #:ImVector_ImFontConfig_front #:ImVector_ImFontGlyph_front #:ImVector_TextRange_front #:ImVector_CustomRect_front #:ImVector_ImDrawChannel_front #:ImVector_char_front #:ImVector_ImTextureID_front #:ImVector_ImDrawVert_front #:ImVector_int_front #:ImVector_Pair_front #:ImVector_ImFontPtr_front #:ImVector_ImVec4_front #:ImVector_ImDrawCmd_front #:ImVector_ImDrawIdx_front #:ImVector_ImVec2_front #:ImVector_float_front_const #:ImVector_ImWchar_front_const #:ImVector_ImFontConfig_front_const #:ImVector_ImFontGlyph_front_const #:ImVector_TextRange_front_const #:ImVector_CustomRect_front_const #:ImVector_ImDrawChannel_front_const #:ImVector_char_front_const #:ImVector_ImTextureID_front_const #:ImVector_ImDrawVert_front_const #:ImVector_int_front_const #:ImVector_Pair_front_const #:ImVector_ImFontPtr_front_const #:ImVector_ImVec4_front_const #:ImVector_ImDrawCmd_front_const #:ImVector_ImDrawIdx_front_const #:ImVector_ImVec2_front_const #:ImVector_float_back #:ImVector_ImWchar_back #:ImVector_ImFontConfig_back #:ImVector_ImFontGlyph_back #:ImVector_TextRange_back #:ImVector_CustomRect_back #:ImVector_ImDrawChannel_back #:ImVector_char_back #:ImVector_ImTextureID_back #:ImVector_ImDrawVert_back #:ImVector_int_back #:ImVector_Pair_back #:ImVector_ImFontPtr_back #:ImVector_ImVec4_back #:ImVector_ImDrawCmd_back #:ImVector_ImDrawIdx_back #:ImVector_ImVec2_back #:ImVector_float_back_const #:ImVector_ImWchar_back_const #:ImVector_ImFontConfig_back_const #:ImVector_ImFontGlyph_back_const #:ImVector_TextRange_back_const #:ImVector_CustomRect_back_const #:ImVector_ImDrawChannel_back_const #:ImVector_char_back_const #:ImVector_ImTextureID_back_const #:ImVector_ImDrawVert_back_const #:ImVector_int_back_const #:ImVector_Pair_back_const #:ImVector_ImFontPtr_back_const #:ImVector_ImVec4_back_const #:ImVector_ImDrawCmd_back_const #:ImVector_ImDrawIdx_back_const #:ImVector_ImVec2_back_const #:ImVector_float_swap #:ImVector_ImWchar_swap #:ImVector_ImFontConfig_swap #:ImVector_ImFontGlyph_swap #:ImVector_TextRange_swap #:ImVector_CustomRect_swap #:ImVector_ImDrawChannel_swap #:ImVector_char_swap #:ImVector_ImTextureID_swap #:ImVector_ImDrawVert_swap #:ImVector_int_swap #:ImVector_Pair_swap #:ImVector_ImFontPtr_swap #:ImVector_ImVec4_swap #:ImVector_ImDrawCmd_swap #:ImVector_ImDrawIdx_swap #:ImVector_ImVec2_swap #:ImVector_float__grow_capacity #:ImVector_ImWchar__grow_capacity #:ImVector_ImFontConfig__grow_capacity #:ImVector_ImFontGlyph__grow_capacity #:ImVector_TextRange__grow_capacity #:ImVector_CustomRect__grow_capacity #:ImVector_ImDrawChannel__grow_capacity #:ImVector_char__grow_capacity #:ImVector_ImTextureID__grow_capacity #:ImVector_ImDrawVert__grow_capacity #:ImVector_int__grow_capacity #:ImVector_Pair__grow_capacity #:ImVector_ImFontPtr__grow_capacity #:ImVector_ImVec4__grow_capacity #:ImVector_ImDrawCmd__grow_capacity #:ImVector_ImDrawIdx__grow_capacity #:ImVector_ImVec2__grow_capacity #:ImVector_float_resize #:ImVector_ImWchar_resize #:ImVector_ImFontConfig_resize #:ImVector_ImFontGlyph_resize #:ImVector_TextRange_resize #:ImVector_CustomRect_resize #:ImVector_ImDrawChannel_resize #:ImVector_char_resize #:ImVector_ImTextureID_resize #:ImVector_ImDrawVert_resize #:ImVector_int_resize #:ImVector_Pair_resize #:ImVector_ImFontPtr_resize #:ImVector_ImVec4_resize #:ImVector_ImDrawCmd_resize #:ImVector_ImDrawIdx_resize #:ImVector_ImVec2_resize #:ImVector_float_resizeT #:ImVector_ImWchar_resizeT #:ImVector_ImFontConfig_resizeT #:ImVector_ImFontGlyph_resizeT #:ImVector_TextRange_resizeT #:ImVector_CustomRect_resizeT #:ImVector_ImDrawChannel_resizeT #:ImVector_char_resizeT #:ImVector_ImTextureID_resizeT #:ImVector_ImDrawVert_resizeT #:ImVector_int_resizeT #:ImVector_Pair_resizeT #:ImVector_ImFontPtr_resizeT #:ImVector_ImVec4_resizeT #:ImVector_ImDrawCmd_resizeT #:ImVector_ImDrawIdx_resizeT #:ImVector_ImVec2_resizeT #:ImVector_float_reserve #:ImVector_ImWchar_reserve #:ImVector_ImFontConfig_reserve #:ImVector_ImFontGlyph_reserve #:ImVector_TextRange_reserve #:ImVector_CustomRect_reserve #:ImVector_ImDrawChannel_reserve #:ImVector_char_reserve #:ImVector_ImTextureID_reserve #:ImVector_ImDrawVert_reserve #:ImVector_int_reserve #:ImVector_Pair_reserve #:ImVector_ImFontPtr_reserve #:ImVector_ImVec4_reserve #:ImVector_ImDrawCmd_reserve #:ImVector_ImDrawIdx_reserve #:ImVector_ImVec2_reserve #:ImVector_float_push_back #:ImVector_ImWchar_push_back #:ImVector_ImFontConfig_push_back #:ImVector_ImFontGlyph_push_back #:ImVector_TextRange_push_back #:ImVector_CustomRect_push_back #:ImVector_ImDrawChannel_push_back #:ImVector_char_push_back #:ImVector_ImTextureID_push_back #:ImVector_ImDrawVert_push_back #:ImVector_int_push_back #:ImVector_Pair_push_back #:ImVector_ImFontPtr_push_back #:ImVector_ImVec4_push_back #:ImVector_ImDrawCmd_push_back #:ImVector_ImDrawIdx_push_back #:ImVector_ImVec2_push_back #:ImVector_float_pop_back #:ImVector_ImWchar_pop_back #:ImVector_ImFontConfig_pop_back #:ImVector_ImFontGlyph_pop_back #:ImVector_TextRange_pop_back #:ImVector_CustomRect_pop_back #:ImVector_ImDrawChannel_pop_back #:ImVector_char_pop_back #:ImVector_ImTextureID_pop_back #:ImVector_ImDrawVert_pop_back #:ImVector_int_pop_back #:ImVector_Pair_pop_back #:ImVector_ImFontPtr_pop_back #:ImVector_ImVec4_pop_back #:ImVector_ImDrawCmd_pop_back #:ImVector_ImDrawIdx_pop_back #:ImVector_ImVec2_pop_back #:ImVector_float_push_front #:ImVector_ImWchar_push_front #:ImVector_ImFontConfig_push_front #:ImVector_ImFontGlyph_push_front #:ImVector_TextRange_push_front #:ImVector_CustomRect_push_front #:ImVector_ImDrawChannel_push_front #:ImVector_char_push_front #:ImVector_ImTextureID_push_front #:ImVector_ImDrawVert_push_front #:ImVector_int_push_front #:ImVector_Pair_push_front #:ImVector_ImFontPtr_push_front #:ImVector_ImVec4_push_front #:ImVector_ImDrawCmd_push_front #:ImVector_ImDrawIdx_push_front #:ImVector_ImVec2_push_front #:ImVector_float_erase #:ImVector_ImWchar_erase #:ImVector_ImFontConfig_erase #:ImVector_ImFontGlyph_erase #:ImVector_TextRange_erase #:ImVector_CustomRect_erase #:ImVector_ImDrawChannel_erase #:ImVector_char_erase #:ImVector_ImTextureID_erase #:ImVector_ImDrawVert_erase #:ImVector_int_erase #:ImVector_Pair_erase #:ImVector_ImFontPtr_erase #:ImVector_ImVec4_erase #:ImVector_ImDrawCmd_erase #:ImVector_ImDrawIdx_erase #:ImVector_ImVec2_erase #:ImVector_float_eraseTPtr #:ImVector_ImWchar_eraseTPtr #:ImVector_ImFontConfig_eraseTPtr #:ImVector_ImFontGlyph_eraseTPtr #:ImVector_TextRange_eraseTPtr #:ImVector_CustomRect_eraseTPtr #:ImVector_ImDrawChannel_eraseTPtr #:ImVector_char_eraseTPtr #:ImVector_ImTextureID_eraseTPtr #:ImVector_ImDrawVert_eraseTPtr #:ImVector_int_eraseTPtr #:ImVector_Pair_eraseTPtr #:ImVector_ImFontPtr_eraseTPtr #:ImVector_ImVec4_eraseTPtr #:ImVector_ImDrawCmd_eraseTPtr #:ImVector_ImDrawIdx_eraseTPtr #:ImVector_ImVec2_eraseTPtr #:ImVector_float_erase_unsorted #:ImVector_ImWchar_erase_unsorted #:ImVector_ImFontConfig_erase_unsorted #:ImVector_ImFontGlyph_erase_unsorted #:ImVector_TextRange_erase_unsorted #:ImVector_CustomRect_erase_unsorted #:ImVector_ImDrawChannel_erase_unsorted #:ImVector_char_erase_unsorted #:ImVector_ImTextureID_erase_unsorted #:ImVector_ImDrawVert_erase_unsorted #:ImVector_int_erase_unsorted #:ImVector_Pair_erase_unsorted #:ImVector_ImFontPtr_erase_unsorted #:ImVector_ImVec4_erase_unsorted #:ImVector_ImDrawCmd_erase_unsorted #:ImVector_ImDrawIdx_erase_unsorted #:ImVector_ImVec2_erase_unsorted #:ImVector_float_insert #:ImVector_ImWchar_insert #:ImVector_ImFontConfig_insert #:ImVector_ImFontGlyph_insert #:ImVector_TextRange_insert #:ImVector_CustomRect_insert #:ImVector_ImDrawChannel_insert #:ImVector_char_insert #:ImVector_ImTextureID_insert #:ImVector_ImDrawVert_insert #:ImVector_int_insert #:ImVector_Pair_insert #:ImVector_ImFontPtr_insert #:ImVector_ImVec4_insert #:ImVector_ImDrawCmd_insert #:ImVector_ImDrawIdx_insert #:ImVector_ImVec2_insert #:ImVector_float_contains #:ImVector_ImWchar_contains #:ImVector_char_contains #:ImVector_int_contains #:ImVector_float_index_from_ptr #:ImVector_ImWchar_index_from_ptr #:ImVector_ImFontConfig_index_from_ptr #:ImVector_ImFontGlyph_index_from_ptr #:ImVector_TextRange_index_from_ptr #:ImVector_CustomRect_index_from_ptr #:ImVector_ImDrawChannel_index_from_ptr #:ImVector_char_index_from_ptr #:ImVector_ImTextureID_index_from_ptr #:ImVector_ImDrawVert_index_from_ptr #:ImVector_int_index_from_ptr #:ImVector_Pair_index_from_ptr #:ImVector_ImFontPtr_index_from_ptr #:ImVector_ImVec4_index_from_ptr #:ImVector_ImDrawCmd_index_from_ptr #:ImVector_ImDrawIdx_index_from_ptr #:ImVector_ImVec2_index_from_ptr #:igLogText #:ImGuiTextBuffer_appendf #:igGET_FLT_MAX #:igColorConvertRGBtoHSV #:igColorConvertHSVtoRGB #:ImVector_ImWchar_create #:ImVector_ImWchar_Init #:ImVector_ImWchar_UnInit #:igBeginChild #:igSetNextWindowPos #:igSetNextWindowSize #:igSetNextWindowSizeConstraints #:igSetNextWindowContentSize #:igSetWindowPosVec2 #:igSetWindowSizeVec2 #:igSetWindowPosStr #:igSetWindowSizeStr #:igPushStyleColor #:igPushStyleVarVec2 #:igSetCursorPos #:igSetCursorScreenPos #:igTextColored #:igTextColoredV #:igButton #:igInvisibleButton #:igImage #:igImageButton #:igPlotLines #:igPlotLinesFnPtr #:igPlotHistogramFloatPtr #:igPlotHistogramFnPtr #:igInputTextMultiline #:igVSliderFloat #:igVSliderInt #:igColorButton #:igSelectable #:igSelectableBoolPtr #:igListBoxHeaderVec2 #:igPushClipRect #:igIsRectVisible #:igBeginChildFrame #:igColorConvertFloat4ToU32 #:igIsMouseHoveringRect #:ImDrawList_PushClipRect #:ImDrawList_AddLine #:ImDrawList_AddRect #:ImDrawList_AddRectFilled #:ImDrawList_AddRectFilledMultiColor #:ImDrawList_AddQuad #:ImDrawList_AddQuadFilled #:ImDrawList_AddTriangle #:ImDrawList_AddTriangleFilled #:ImDrawList_AddCircle #:ImDrawList_AddCircleFilled #:ImDrawList_AddText #:ImDrawList_AddTextFontPtr #:ImDrawList_AddImage #:ImDrawList_AddImageQuad #:ImDrawList_AddImageRounded #:ImDrawList_PathLineTo #:ImDrawList_PathLineToMergeDuplicate #:ImDrawList_PathArcTo #:ImDrawList_PathArcToFast #:ImDrawList_PathBezierCurveTo #:ImDrawList_PathRect #:ImDrawList_PrimRect #:ImDrawList_PrimRectUV #:ImDrawList_PrimQuadUV #:ImDrawList_PrimWriteVtx #:ImDrawList_PrimVtx #:ImDrawData_ScaleClipRects #:igGetWindowPos #:igGetWindowSize #:igGetContentRegionMax #:igGetContentRegionAvail #:igGetWindowContentRegionMin #:igGetWindowContentRegionMax #:igGetFontTexUvWhitePixel #:igGetCursorPos #:igGetCursorStartPos #:igGetCursorScreenPos #:igGetItemRectMin #:igGetItemRectMax #:igGetItemRectSize #:igCalcTextSize #:igColorConvertU32ToFloat4 #:igGetMousePos #:igGetMousePosOnOpeningCurrentPopup #:igGetMouseDragDelta #:ImColor_HSV #:ImDrawList_GetClipRectMin #:ImDrawList_GetClipRectMax #:ImFont_CalcTextSizeA #:igGetWindowPos_nonUDT2 #:igGetWindowSize_nonUDT2 #:igGetContentRegionMax_nonUDT2 #:igGetContentRegionAvail_nonUDT2 #:igGetWindowContentRegionMin_nonUDT2 #:igGetWindowContentRegionMax_nonUDT2 #:igGetFontTexUvWhitePixel_nonUDT2 #:igGetCursorPos_nonUDT2 #:igGetCursorStartPos_nonUDT2 #:igGetCursorScreenPos_nonUDT2 #:igGetItemRectMin_nonUDT2 #:igGetItemRectMax_nonUDT2 #:igCalcTextSize_nonUDT2 #:igColorConvertU32ToFloat4_nonUDT2 #:igGetMousePos_nonUDT2 #:igGetMousePosOnOpeningCurrentPopup_nonUDT2 #:igGetMouseDragDelta_nonUDT2 #:ImColor_HSV_nonUDT2 #:ImDrawList_GetClipRectMin_nonUDT2 #:ImDrawList_GetClipRectMax_nonUDT2 #:ImFont_CalcTextSizeA_nonUDT2))
null
https://raw.githubusercontent.com/awolven/VkTk/fa5d320dd09a03fb2f3aa2fa096401882212144d/ifc/cimgui/imgui-package.lisp
lisp
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the without limitation the rights to use, copy, modify, merge, publish, the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #:image
Copyright 2019 < > " Software " ) , to deal in the Software without restriction , including distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION (in-package :cl-user) (defpackage :imgui (:nicknames :ig) (:use :cl :cffi) (:shadow) (:export #:bullet-text #:show-demo-window #:begin #:end #:set-next-window-pos #:set-next-window-size #:set-cursor-screen-pos #:text #:push-item-width #:pop-item-width #:calc-item-width #:push-text-wrap-pos #:push-allow-keyboard-focus #:pop-allow-keyboard-focus #:push-button-repeat #:pop-button-repeat #:separator #:same-line #:new-line #:spacing #:dummy #:indent #:unindent #:begin-group #:end-group #:imgui-get-cursor-pos #:get-cursor-pos-x #:get-cursor-pos-y #:get-cursor-start-pos #:get-cursor-screen-pos #:align-text-to-frame-padding #:get-text-line-height #:get-frame-height-with-spacing #:push-id #:pop-id #:get-id #:text-unformatted #:text-colored #:text-disabled #:text-wrapped #:label-text #:button #:small-button #:invisible-button #:arrow-button #:image-button #:checkbox #:checkbox-flags #:radio-button #:progress-bar #:bullet #:begin-combo #:end-combo #:combo #:drag-float #:drag-float2 #:drag-float3 #:drag-float4 #:drag-float-range2 #:drag-int #:drag-int2 #:drag-int3 #:drag-int-range2 #:drag-scalar #:drag-scalar-n #:slider-float #:slider-float2 #:slider-float3 #:slider-float4 #:slider-angle #:slider-int #:slider-int2 #:slider-int3 #:slider-int4 #:slider-scalar #:slider-scalar-n #:input-text #:input-text-multiline #:input-float #:input-float2 #:input-float3 #:input-float4 #:input-int #:input-int2 #:input-int3 #:input-int4 #:input-double #:input-scalar #:input-scalar-n #:color-edit #:color-edit3 #:color-edit4 #:color-picker3 #:color-picker4 #:color-button #:set-color-edit-options #:tree-node #:tree-node-ex #:tree-push #:tree-pop #:tree-advance-to-label-pos #:get-tree-node-to-label-spacing #:set-next-tree-node-open #:collapsing-header #:selectable #:list-box #:list-box-header #:list-box-footer #:plot-lines #:plot-histogram #:begin-main-menu-bar #:end-main-menu-bar #:begin-menu-bar #:end-menu-bar #:end-menu #:begin-tooltip #:end-tooltip #:set-tooltip #:open-popup #:begin-popup #:begin-popep-context-item #:begin-popup-context-window #:begin-popup-context-void #:begin-popup-modal #:end-popup #:begin-child #:bool-receptor #:flags-receptor #:get-receptor-value #:log-finish #:log-text #:log-to-clipboard #:key-pressed-p #:menu-item #:begin-menu #:ImVec2_Simple #:ImVec2_ImVec2 #:ImVec2_destroy #:ImVec2_ImVec2Float #:ImVec4_ImVec4 #:ImVec4_destroy #:ImVec4_ImVec4Float #:ImGuiWindowFlags_NoTitleBar #:ImGuiWindowFlags_NoResize #:ImGuiWindowFlags_NoMove #:ImGuiWindowFlags_NoScrollbar #:ImGuiWindowFlags_NoScrollWithMouse #:ImGuiWindowFlags_NoCollapse #:ImGuiWindowFlags_AlwaysAutoResize #:ImGuiWindowFlags_NoBackground #:ImGuiWindowFlags_NoMouseInputs #:ImGuiWindowFlags_NoSavedSettings #:ImGuiWindowFlags_NoInputs #:ImGuiWindowFlags_MenuBar #:ImGuiWindowFlags_HorizontalScrollbar #:ImGuiWindowFlags_NoFocusOnAppearing #:ImGuiWindowFlags_NoBringToFrontOnFocus #:ImGuiWindowFlags_AlwaysVerticalScrollbar #:ImGuiWindowFlags_AlwaysHorizontalScrollbar #:ImGuiWindowFlags_AlwaysUseWindowPadding #:ImGuiWindowFlags_ResizeFromAnySide #:ImGuiWindowFlags_NoNavInputs #:ImGuiWindowFlags_NoNavFocus #:ImGuiWindowFlags_UnsavedDocument #:ImGuiWindowFlags_NoNav #:ImGuiWindowFlags_NoDecoration #:ImGuiWindowFlags_NavFlattened #:ImGuiWindowFlags_ChildWindow #:ImGuiWindowFlags_Tooltip #:ImGuiWindowFlags_Popup #:ImGuiWindowFlags_Modal #:ImGuiWindowFlags_ChildMenu #:ImGuiInputTextFlags_CharsDecimal #:ImGuiInputTextFlags_CharsHexadecimal #:ImGuiInputTextFlags_CharsUppercase #:ImGuiInputTextFlags_CharsNoBlank #:ImGuiInputTextFlags_AutoSelectAll #:ImGuiInputTextFlags_EnterReturnsTrue #:ImGuiInputTextFlags_CallbackCompletion #:ImGuiInputTextFlags_CallbackHistory #:ImGuiInputTextFlags_CallbackAlways #:ImGuiInputTextFlags_CallbackCharFilter #:ImGuiInputTextFlags_AllowTabInput #:ImGuiInputTextFlags_CtrlEnterForNewLine #:ImGuiInputTextFlags_NoHorizontalScroll #:ImGuiInputTextFlags_AlwaysInsertMode #:ImGuiInputTextFlags_ReadOnly #:ImGuiInputTextFlags_Password #:ImGuiInputTextFlags_NoUndoRedo #:ImGuiTreeNodeFlags_Selected #:ImGuiTreeNodeFlags_Framed #:ImGuiTreeNodeFlags_AllowItemOverlap #:ImGuiTreeNodeFlags_NoTreePushOnOpen #:ImGuiTreeNodeFlags_NoAutoOpenOnLog #:ImGuiTreeNodeFlags_DefaultOpen #:ImGuiTreeNodeFlags_OpenOnDoubleClick #:ImGuiTreeNodeFlags_OpenOnArrow #:ImGuiTreeNodeFlags_Leaf #:ImGuiTreeNodeFlags_Bullet #:ImGuiTreeNodeFlags_FramePadding #:ImGuiTreeNodeFlags_NavLeftJumpsBackHere #:ImGuiTreeNodeFlags_CollapsingHeader #:ImGuiSelectableFlags_DontClosePopups #:ImGuiSelectableFlags_SpanAllColumns #:ImGuiSelectableFlags_AllowDoubleClick #:ImGuiComboFlags_PopupAlignLeft #:ImGuiComboFlags_HeightSmall #:ImGuiComboFlags_HeightRegular #:ImGuiComboFlags_HeightLarge #:ImGuiComboFlags_HeightLargest #:ImGuiComboFlags_HeightMask_ #:ImGuiFocusedFlags_ChildWindows #:ImGuiFocusedFlags_RootWindow #:ImGuiFocusedFlags_RootAndChildWindows #:ImGuiHoveredFlags_ChildWindows #:ImGuiHoveredFlags_RootWindow #:ImGuiHoveredFlags_AllowWhenBlockedByPopup #:ImGuiHoveredFlags_AllowWhenBlockedByActiveItem #:ImGuiHoveredFlags_AllowWhenOverlapped #:ImGuiHoveredFlags_RectOnly #:ImGuiHoveredFlags_RootAndChildWindows #:ImGuiDragDropFlags_SourceNoPreviewTooltip #:ImGuiDragDropFlags_SourceNoDisableHover #:ImGuiDragDropFlags_SourceNoHoldToOpenOthers #:ImGuiDragDropFlags_SourceAllowNullID #:ImGuiDragDropFlags_SourceExtern #:ImGuiDragDropFlags_AcceptBeforeDelivery #:ImGuiDragDropFlags_AcceptNoDrawDefaultRect #:ImGuiDragDropFlags_AcceptPeekOnly #:ImGuiKey_Tab #:ImGuiKey_LeftArrow #:ImGuiKey_RightArrow #:ImGuiKey_UpArrow #:ImGuiKey_DownArrow #:ImGuiKey_PageUp #:ImGuiKey_PageDown #:ImGuiKey_Home #:ImGuiKey_End #:ImGuiKey_Delete #:ImGuiKey_Backspace #:ImGuiKey_Enter #:ImGuiKey_Escape #:ImGuiKey_A #:ImGuiKey_C #:ImGuiKey_V #:ImGuiKey_X #:ImGuiKey_Y #:ImGuiKey_Z #:ImGuiKey_COUNT #:ImGuiCol_Text #:ImGuiCol_TextDisabled #:ImGuiCol_WindowBg #:ImGuiCol_ChildBg #:ImGuiCol_PopupBg #:ImGuiCol_Border #:ImGuiCol_BorderShadow #:ImGuiCol_FrameBg #:ImGuiCol_FrameBgHovered #:ImGuiCol_FrameBgActive #:ImGuiCol_TitleBg #:ImGuiCol_TitleBgActive #:ImGuiCol_TitleBgCollapsed #:ImGuiCol_MenuBarBg #:ImGuiCol_ScrollbarBg #:ImGuiCol_ScrollbarGrab #:ImGuiCol_ScrollbarGrabHovered #:ImGuiCol_ScrollbarGrabActive #:ImGuiCol_CheckMark #:ImGuiCol_SliderGrab #:ImGuiCol_SliderGrabActive #:ImGuiCol_Button #:ImGuiCol_ButtonHovered #:ImGuiCol_ButtonActive #:ImGuiCol_Header #:ImGuiCol_HeaderHovered #:ImGuiCol_HeaderActive #:ImGuiCol_Separator #:ImGuiCol_SeparatorHovered #:ImGuiCol_SeparatorActive #:ImGuiCol_ResizeGrip #:ImGuiCol_ResizeGripHovered #:ImGuiCol_ResizeGripActive #:ImGuiCol_CloseButton #:ImGuiCol_CloseButtonHovered #:ImGuiCol_CloseButtonActive #:ImGuiCol_PlotLines #:ImGuiCol_PlotLinesHovered #:ImGuiCol_PlotHistogram #:ImGuiCol_PlotHistogramHovered #:ImGuiCol_TextSelectedBg #:ImGuiCol_ModalWindowDarkening #:ImGuiCol_DragDropTarget #:ImGuiCol_COUNT #:ImGuiStyleVar_Alpha #:ImGuiStyleVar_WindowPadding #:ImGuiStyleVar_WindowRounding #:ImGuiStyleVar_WindowBorderSize #:ImGuiStyleVar_WindowMinSize #:ImGuiStyleVar_ChildRounding #:ImGuiStyleVar_ChildBorderSize #:ImGuiStyleVar_PopupRounding #:ImGuiStyleVar_PopupBorderSize #:ImGuiStyleVar_FramePadding #:ImGuiStyleVar_FrameRounding #:ImGuiStyleVar_FrameBorderSize #:ImGuiStyleVar_ItemSpacing #:ImGuiStyleVar_ItemInnerSpacing #:ImGuiStyleVar_IndentSpacing #:ImGuiStyleVar_GrabMinSize #:ImGuiStyleVar_ButtonTextAlign #:ImGuiStyleVar_Count_ #:ImGuiColorEditFlags_NoAlpha #:ImGuiColorEditFlags_NoPicker #:ImGuiColorEditFlags_NoOptions #:ImGuiColorEditFlags_NoSmallPreview #:ImGuiColorEditFlags_NoInputs #:ImGuiColorEditFlags_NoTooltip #:ImGuiColorEditFlags_NoLabel #:ImGuiColorEditFlags_NoSidePreview #:ImGuiColorEditFlags_NoDragDrop #:ImGuiColorEditFlags_AlphaBar #:ImGuiColorEditFlags_AlphaPreview #:ImGuiColorEditFlags_AlphaPreviewHalf #:ImGuiColorEditFlags_HDR #:ImGuiColorEditFlags_RGB #:ImGuiColorEditFlags_HSV #:ImGuiColorEditFlags_HEX #:ImGuiColorEditFlags_Uint8 #:ImGuiColorEditFlags_Float #:ImGuiColorEditFlags_PickerHueBar #:ImGuiColorEditFlags_PickerHueWheel #:ImGuiMouseCursor_None #:ImGuiMouseCursor_Arrow #:ImGuiMouseCursor_TextInput #:ImGuiMouseCursor_Move #:ImGuiMouseCursor_ResizeNS #:ImGuiMouseCursor_ResizeEW #:ImGuiMouseCursor_ResizeNESW #:ImGuiMouseCursor_ResizeNWSE #:ImGuiMouseCursor_Count_ #:ImGuiCond_Always #:ImGuiCond_Once #:ImGuiCond_FirstUseEver #:ImGuiCond_Appearing #:ImDrawCornerFlags_TopLeft #:ImDrawCornerFlags_TopRight #:ImDrawCornerFlags_BotLeft #:ImDrawCornerFlags_BotRight #:ImDrawCornerFlags_Top #:ImDrawCornerFlags_Bot #:ImDrawCornerFlags_Left #:ImDrawCornerFlags_Right #:ImDrawCornerFlags_All #:ImDrawListFlags_AntiAliasedLines #:ImDrawListFlags_AntiAliasedFill #:igCreateContext #:igDestroyContext #:igGetCurrentContext #:igSetCurrentContext #:igDebugCheckVersionAndDataLayout #:igGetIO #:igGetStyle #:igNewFrame #:igEndFrame #:igRender #:igGetDrawData #:igShowDemoWindow #:igShowAboutWindow #:igShowMetricsWindow #:igShowStyleEditor #:igShowStyleSelector #:igShowFontSelector #:igShowUserGuide #:igGetVersion #:igStyleColorsDark #:igStyleColorsClassic #:igStyleColorsLight #:igBegin #:igEnd #:igBeginChildID #:igEndChild #:igIsWindowAppearing #:igIsWindowCollapsed #:igIsWindowFocused #:igIsWindowHovered #:igGetWindowDrawList #:igGetWindowPos #:igGetWindowSize #:igGetWindowWidth #:igGetWindowHeight #:igGetContentRegionMax #:igGetContentRegionAvail #:igGetContentRegionAvailWidth #:igGetWindowContentRegionMin #:igGetWindowContentRegionMax #:igGetWindowContentRegionWidth #:igSetNextWindowCollapsed #:igSetNextWindowFocus #:igSetNextWindowBgAlpha #:igSetWindowCollapsedBool #:igSetWindowFocus #:igSetWindowFontScale #:igSetWindowCollapsedStr #:igSetWindowFocusStr #:igGetScrollX #:igGetScrollY #:igGetScrollMaxX #:igGetScrollMaxY #:igSetScrollX #:igSetScrollY #:igSetScrollHereY #:igSetScrollFromPosY #:igPushFont #:igPopFont #:igPushStyleColorU32 #:igPopStyleColor #:igPushStyleVarFloat #:igPopStyleVar #:igGetStyleColorVec4 #:igGetFont #:igGetFontSize #:igGetFontTexUvWhitePixel #:igGetColorU32 #:igGetColorU32Vec4 #:igGetColorU32U32 #:igPushItemWidth #:igPopItemWidth #:igCalcItemWidth #:igPushTextWrapPos #:igPopTextWrapPos #:igPushAllowKeyboardFocus #:igPopAllowKeyboardFocus #:igPushButtonRepeat #:igPopButtonRepeat #:igSeparator #:igSameLine #:igNewLine #:igSpacing #:igDummy #:igIndent #:igUnindent #:igBeginGroup #:igEndGroup #:igGetCursorPos #:igGetCursorPosX #:igGetCursorPosY #:igSetCursorPosX #:igSetCursorPosY #:igGetCursorStartPos #:igGetCursorScreenPos #:igAlignTextToFramePadding #:igGetTextLineHeight #:igGetTextLineHeightWithSpacing #:igGetFrameHeight #:igGetFrameHeightWithSpacing #:igPushIDStr #:igPushIDRange #:igPushIDPtr #:igPushIDInt #:igPopID #:igGetIDStr #:igGetIDRange #:igGetIDPtr #:igTextUnformatted #:igText #:igTextV #:igTextDisabled #:igTextDisabledV #:igTextWrapped #:igTextWrappedV #:igLabelText #:igLabelTextV #:igBulletText #:igBulletTextV #:igSmallButton #:igArrowButton #:igCheckbox #:igCheckboxFlags #:igRadioButtonBool #:igRadioButtonIntPtr #:igProgressBar #:igBullet #:igBeginCombo #:igEndCombo #:igCombo #:igComboStr #:igComboFnPtr #:igDragFloat #:igDragFloat2 #:igDragFloat3 #:igDragFloat4 #:igDragFloatRange2 #:igDragInt #:igDragInt2 #:igDragInt3 #:igDragInt4 #:igDragIntRange2 #:igDragScalar #:igDragScalarN #:igSliderFloat #:igSliderFloat2 #:igSliderFloat3 #:igSliderFloat4 #:igSliderAngle #:igSliderInt #:igSliderInt2 #:igSliderInt3 #:igSliderInt4 #:igSliderScalar #:igSliderScalarN #:igVSliderFloat #:igVSliderInt #:igVSliderScalar #:igInputText #:igInputTextMultiline #:igInputFloat #:igInputFloat2 #:igInputFloat3 #:igInputFloat4 #:igInputInt #:igInputInt2 #:igInputInt3 #:igInputInt4 #:igInputDouble #:igInputScalar #:igInputScalarN #:igColorEdit3 #:igColorEdit4 #:igColorPicker3 #:igColorPicker4 #:igColorButton #:igSetColorEditOptions #:igTreeNodeStr #:igTreeNodeStrStr #:igTreeNodePtr #:igTreeNodeVStr #:igTreeNodeVPtr #:igTreeNodeExStr #:igTreeNodeExStrStr #:igTreeNodeExPtr #:igTreeNodeExVStr #:igTreeNodeExVPtr #:igTreePushStr #:igTreePushPtr #:igTreePop #:igTreeAdvanceToLabelPos #:igGetTreeNodeToLabelSpacing #:igSetNextTreeNodeOpen #:igCollapsingHeader #:igCollapsingHeaderBoolPtr #:igSelectable #:igSelectableBoolPtr #:igListBoxStr_arr #:igListBoxFnPtr #:igListBoxHeaderVec2 #:igListBoxHeaderInt #:igListBoxFooter #:igValueBool #:igValueInt #:igValueUint #:igValueFloat #:igBeginMainMenuBar #:igEndMainMenuBar #:igBeginMenuBar #:igEndMenuBar #:igBeginMenu #:igEndMenu #:igMenuItemBool #:igMenuItemBoolPtr #:igBeginTooltip #:igEndTooltip #:igSetTooltip #:igSetTooltipV #:igOpenPopup #:igBeginPopup #:igBeginPopupContextItem #:igBeginPopupContextWindow #:igBeginPopupContextVoid #:igBeginPopupModal #:igEndPopup #:igOpenPopupOnItemClick #:igIsPopupOpen #:igCloseCurrentPopup #:igColumns #:igNextColumn #:igGetColumnIndex #:igGetColumnWidth #:igSetColumnWidth #:igGetColumnOffset #:igSetColumnOffset #:igGetColumnsCount #:igBeginTabBar #:igEndTabBar #:igBeginTabItem #:igEndTabItem #:igSetTabItemClosed #:igLogToTTY #:igLogToFile #:igLogToClipboard #:igLogFinish #:igLogButtons #:igBeginDragDropSource #:igSetDragDropPayload #:igEndDragDropSource #:igBeginDragDropTarget #:igAcceptDragDropPayload #:igEndDragDropTarget #:igGetDragDropPayload #:igPushClipRect #:igPopClipRect #:igSetItemDefaultFocus #:igSetKeyboardFocusHere #:igIsItemHovered #:igIsItemActive #:igIsItemFocused #:igIsItemClicked #:igIsItemVisible #:igIsItemEdited #:igIsItemActivated #:igIsItemDeactivated #:igIsItemDeactivatedAfterEdit #:igIsAnyItemHovered #:igIsAnyItemActive #:igIsAnyItemFocused #:igGetItemRectMin #:igGetItemRectMax #:igGetItemRectSize #:igSetItemAllowOverlap #:igIsRectVisible #:igIsRectVisibleVec2 #:igGetTime #:igGetFrameCount #:igGetOverlayDrawList #:igGetDrawListSharedData #:igGetStyleColorName #:igSetStateStorage #:igGetStateStorage #:igCalcTextSize #:igCalcListClipping #:igBeginChildFrame #:igEndChildFrame #:igColorConvertU32ToFloat4 #:igColorConvertFloat4ToU32 #:igGetKeyIndex #:igIsKeyDown #:igIsKeyPressed #:igIsKeyReleased #:igGetKeyPressedAmount #:igIsMouseDown #:igIsAnyMouseDown #:igIsMouseClicked #:igIsMouseDoubleClicked #:igIsMouseReleased #:igIsMouseDragging #:igIsMouseHoveringRect #:igIsMousePosValid #:igGetMousePos #:igGetMousePosOnOpeningCurrentPopup #:igGetMouseDragDelta #:igResetMouseDragDelta #:igGetMouseCursor #:igSetMouseCursor #:igCaptureKeyboardFromApp #:igCaptureMouseFromApp #:igGetClipboardText #:igSetClipboardText #:igLoadIniSettingsFromDisk #:igLoadIniSettingsFromMemory #:igSaveIniSettingsToDisk #:igSaveIniSettingsToMemory #:igSetAllocatorFunctions #:igMemAlloc #:igMemFree #:ImGuiStyle_ImGuiStyle #:ImGuiStyle_destroy #:ImGuiStyle_ScaleAllSizes #:ImGuiIO_AddInputCharacter #:ImGuiIO_AddInputCharactersUTF8 #:ImGuiIO_ClearInputCharacters #:ImGuiIO_ImGuiIO #:ImGuiIO_destroy #:ImGuiInputTextCallbackData_ImGuiInputTextCallbackData #:ImGuiInputTextCallbackData_destroy #:ImGuiInputTextCallbackData_DeleteChars #:ImGuiInputTextCallbackData_InsertChars #:ImGuiInputTextCallbackData_HasSelection #:ImGuiPayload_ImGuiPayload #:ImGuiPayload_destroy #:ImGuiPayload_Clear #:ImGuiPayload_IsDataType #:ImGuiPayload_IsPreview #:ImGuiPayload_IsDelivery #:ImGuiOnceUponAFrame_ImGuiOnceUponAFrame #:ImGuiOnceUponAFrame_destroy #:ImGuiTextFilter_ImGuiTextFilter #:ImGuiTextFilter_destroy #:ImGuiTextFilter_Draw #:ImGuiTextFilter_PassFilter #:ImGuiTextFilter_Build #:ImGuiTextFilter_Clear #:ImGuiTextFilter_IsActive #:TextRange_TextRange #:TextRange_destroy #:TextRange_TextRangeStr #:TextRange_begin #:TextRange_end #:TextRange_empty #:TextRange_split #:ImGuiTextBuffer_ImGuiTextBuffer #:ImGuiTextBuffer_destroy #:ImGuiTextBuffer_begin #:ImGuiTextBuffer_end #:ImGuiTextBuffer_size #:ImGuiTextBuffer_empty #:ImGuiTextBuffer_clear #:ImGuiTextBuffer_reserve #:ImGuiTextBuffer_c_str #:ImGuiTextBuffer_append #:ImGuiTextBuffer_appendfv #:Pair_PairInt #:Pair_destroy #:Pair_PairFloat #:Pair_PairPtr #:ImGuiStorage_Clear #:ImGuiStorage_GetInt #:ImGuiStorage_SetInt #:ImGuiStorage_GetBool #:ImGuiStorage_SetBool #:ImGuiStorage_GetFloat #:ImGuiStorage_SetFloat #:ImGuiStorage_GetVoidPtr #:ImGuiStorage_SetVoidPtr #:ImGuiStorage_GetIntRef #:ImGuiStorage_GetBoolRef #:ImGuiStorage_GetFloatRef #:ImGuiStorage_GetVoidPtrRef #:ImGuiStorage_SetAllInt #:ImGuiStorage_BuildSortByKey #:ImGuiListClipper_ImGuiListClipper #:ImGuiListClipper_destroy #:ImGuiListClipper_Step #:ImGuiListClipper_Begin #:ImGuiListClipper_End #:ImColor_ImColor #:ImColor_destroy #:ImColor_ImColorInt #:ImColor_ImColorU32 #:ImColor_ImColorFloat #:ImColor_ImColorVec4 #:ImColor_SetHSV #:ImColor_HSV #:ImDrawCmd_ImDrawCmd #:ImDrawCmd_destroy #:ImDrawList_ImDrawList #:ImDrawList_destroy #:ImDrawList_PushClipRect #:ImDrawList_PushClipRectFullScreen #:ImDrawList_PopClipRect #:ImDrawList_PushTextureID #:ImDrawList_PopTextureID #:ImDrawList_GetClipRectMin #:ImDrawList_GetClipRectMax #:ImDrawList_AddLine #:ImDrawList_AddRect #:ImDrawList_AddRectFilled #:ImDrawList_AddRectFilledMultiColor #:ImDrawList_AddQuad #:ImDrawList_AddQuadFilled #:ImDrawList_AddTriangle #:ImDrawList_AddTriangleFilled #:ImDrawList_AddCircle #:ImDrawList_AddCircleFilled #:ImDrawList_AddText #:ImDrawList_AddTextFontPtr #:ImDrawList_AddImage #:ImDrawList_AddImageQuad #:ImDrawList_AddImageRounded #:ImDrawList_AddPolyline #:ImDrawList_AddConvexPolyFilled #:ImDrawList_AddBezierCurve #:ImDrawList_PathClear #:ImDrawList_PathLineTo #:ImDrawList_PathLineToMergeDuplicate #:ImDrawList_PathFillConvex #:ImDrawList_PathStroke #:ImDrawList_PathArcTo #:ImDrawList_PathArcToFast #:ImDrawList_PathBezierCurveTo #:ImDrawList_PathRect #:ImDrawList_ChannelsSplit #:ImDrawList_ChannelsMerge #:ImDrawList_ChannelsSetCurrent #:ImDrawList_AddCallback #:ImDrawList_AddDrawCmd #:ImDrawList_CloneOutput #:ImDrawList_Clear #:ImDrawList_ClearFreeMemory #:ImDrawList_PrimReserve #:ImDrawList_PrimRect #:ImDrawList_PrimRectUV #:ImDrawList_PrimQuadUV #:ImDrawList_PrimWriteVtx #:ImDrawList_PrimWriteIdx #:ImDrawList_PrimVtx #:ImDrawList_UpdateClipRect #:ImDrawList_UpdateTextureID #:ImDrawData_ImDrawData #:ImDrawData_destroy #:ImDrawData_Clear #:ImDrawData_DeIndexAllBuffers #:ImDrawData_ScaleClipRects #:ImFontConfig_ImFontConfig #:ImFontConfig_destroy #:ImFontGlyphRangesBuilder_ImFontGlyphRangesBuilder #:ImFontGlyphRangesBuilder_destroy #:ImFontGlyphRangesBuilder_GetBit #:ImFontGlyphRangesBuilder_SetBit #:ImFontGlyphRangesBuilder_AddChar #:ImFontGlyphRangesBuilder_AddText #:ImFontGlyphRangesBuilder_AddRanges #:ImFontGlyphRangesBuilder_BuildRanges #:ImFontAtlas_ImFontAtlas #:ImFontAtlas_destroy #:ImFontAtlas_AddFont #:ImFontAtlas_AddFontDefault #:ImFontAtlas_AddFontFromFileTTF #:ImFontAtlas_AddFontFromMemoryTTF #:ImFontAtlas_AddFontFromMemoryCompressedTTF #:ImFontAtlas_AddFontFromMemoryCompressedBase85TTF #:ImFontAtlas_ClearInputData #:ImFontAtlas_ClearTexData #:ImFontAtlas_ClearFonts #:ImFontAtlas_Clear #:ImFontAtlas_Build #:ImFontAtlas_GetTexDataAsAlpha8 #:ImFontAtlas_GetTexDataAsRGBA32 #:ImFontAtlas_IsBuilt #:ImFontAtlas_SetTexID #:ImFontAtlas_GetGlyphRangesDefault #:ImFontAtlas_GetGlyphRangesKorean #:ImFontAtlas_GetGlyphRangesJapanese #:ImFontAtlas_GetGlyphRangesChineseFull #:ImFontAtlas_GetGlyphRangesChineseSimplifiedCommon #:ImFontAtlas_GetGlyphRangesCyrillic #:ImFontAtlas_GetGlyphRangesThai #:CustomRect_CustomRect #:CustomRect_destroy #:CustomRect_IsPacked #:ImFontAtlas_AddCustomRectRegular #:ImFontAtlas_AddCustomRectFontGlyph #:ImFontAtlas_GetCustomRectByIndex #:ImFontAtlas_CalcCustomRectUV #:ImFontAtlas_GetMouseCursorTexData #:ImFont_ImFont #:ImFont_destroy #:ImFont_FindGlyph #:ImFont_FindGlyphNoFallback #:ImFont_GetCharAdvance #:ImFont_IsLoaded #:ImFont_GetDebugName #:ImFont_CalcTextSizeA #:ImFont_CalcWordWrapPositionA #:ImFont_RenderChar #:ImFont_RenderText #:ImFont_BuildLookupTable #:ImFont_ClearOutputData #:ImFont_GrowIndex #:ImFont_AddGlyph #:ImFont_AddRemapChar #:ImFont_SetFallbackChar #:igGetWindowPos_nonUDT #:igGetWindowSize_nonUDT #:igGetContentRegionMax_nonUDT #:igGetContentRegionAvail_nonUDT #:igGetWindowContentRegionMin_nonUDT #:igGetWindowContentRegionMax_nonUDT #:igGetFontTexUvWhitePixel_nonUDT #:igGetCursorPos_nonUDT #:igGetCursorStartPos_nonUDT #:igGetCursorScreenPos_nonUDT #:igGetItemRectMin_nonUDT #:igGetItemRectMax_nonUDT #:igGetItemRectSize_nonUDT #:igCalcTextSize_nonUDT #:igColorConvertU32ToFloat4_nonUDT #:igGetMousePos_nonUDT #:igGetMousePosOnOpeningCurrentPopup_nonUDT #:igGetMouseDragDelta_nonUDT #:ImColor_HSV_nonUDT #:ImDrawList_GetClipRectMin_nonUDT #:ImDrawList_GetClipRectMax_nonUDT #:ImFont_CalcTextSizeA_nonUDT #:ImVector_float_ImVector_float #:ImVector_float_destroy #:ImVector_ImWchar_ImVector_ImWchar #:ImVector_ImWchar_destroy #:ImVector_ImFontConfig_ImVector_ImFontConfig #:ImVector_ImFontConfig_destroy #:ImVector_ImFontGlyph_ImVector_ImFontGlyph #:ImVector_ImFontGlyph_destroy #:ImVector_TextRange_ImVector_TextRange #:ImVector_TextRange_destroy #:ImVector_CustomRect_ImVector_CustomRect #:ImVector_CustomRect_destroy #:ImVector_ImDrawChannel_ImVector_ImDrawChannel #:ImVector_ImDrawChannel_destroy #:ImVector_char_ImVector_char #:ImVector_char_destroy #:ImVector_ImTextureID_ImVector_ImTextureID #:ImVector_ImTextureID_destroy #:ImVector_ImDrawVert_ImVector_ImDrawVert #:ImVector_ImDrawVert_destroy #:ImVector_int_ImVector_int #:ImVector_int_destroy #:ImVector_Pair_ImVector_Pair #:ImVector_Pair_destroy #:ImVector_ImFontPtr_ImVector_ImFontPtr #:ImVector_ImFontPtr_destroy #:ImVector_ImVec4_ImVector_ImVec4 #:ImVector_ImVec4_destroy #:ImVector_ImDrawCmd_ImVector_ImDrawCmd #:ImVector_ImDrawCmd_destroy #:ImVector_ImDrawIdx_ImVector_ImDrawIdx #:ImVector_ImDrawIdx_destroy #:ImVector_ImVec2_ImVector_ImVec2 #:ImVector_ImVec2_destroy #:ImVector_float_ImVector_floatVector #:ImVector_ImWchar_ImVector_ImWcharVector #:ImVector_ImFontConfig_ImVector_ImFontConfigVector #:ImVector_ImFontGlyph_ImVector_ImFontGlyphVector #:ImVector_TextRange_ImVector_TextRangeVector #:ImVector_CustomRect_ImVector_CustomRectVector #:ImVector_ImDrawChannel_ImVector_ImDrawChannelVector #:ImVector_char_ImVector_charVector #:ImVector_ImTextureID_ImVector_ImTextureIDVector #:ImVector_ImDrawVert_ImVector_ImDrawVertVector #:ImVector_int_ImVector_intVector #:ImVector_Pair_ImVector_PairVector #:ImVector_ImFontPtr_ImVector_ImFontPtrVector #:ImVector_ImVec4_ImVector_ImVec4Vector #:ImVector_ImDrawCmd_ImVector_ImDrawCmdVector #:ImVector_ImDrawIdx_ImVector_ImDrawIdxVector #:ImVector_ImVec2_ImVector_ImVec2Vector #:ImVector_float_empty #:ImVector_ImWchar_empty #:ImVector_ImFontConfig_empty #:ImVector_ImFontGlyph_empty #:ImVector_TextRange_empty #:ImVector_CustomRect_empty #:ImVector_ImDrawChannel_empty #:ImVector_char_empty #:ImVector_ImTextureID_empty #:ImVector_ImDrawVert_empty #:ImVector_int_empty #:ImVector_Pair_empty #:ImVector_ImFontPtr_empty #:ImVector_ImVec4_empty #:ImVector_ImDrawCmd_empty #:ImVector_ImDrawIdx_empty #:ImVector_ImVec2_empty #:ImVector_float_size #:ImVector_ImWchar_size #:ImVector_ImFontConfig_size #:ImVector_ImFontGlyph_size #:ImVector_TextRange_size #:ImVector_CustomRect_size #:ImVector_ImDrawChannel_size #:ImVector_char_size #:ImVector_ImTextureID_size #:ImVector_ImDrawVert_size #:ImVector_int_size #:ImVector_Pair_size #:ImVector_ImFontPtr_size #:ImVector_ImVec4_size #:ImVector_ImDrawCmd_size #:ImVector_ImDrawIdx_size #:ImVector_ImVec2_size #:ImVector_float_size_in_bytes #:ImVector_ImWchar_size_in_bytes #:ImVector_ImFontConfig_size_in_bytes #:ImVector_ImFontGlyph_size_in_bytes #:ImVector_TextRange_size_in_bytes #:ImVector_CustomRect_size_in_bytes #:ImVector_ImDrawChannel_size_in_bytes #:ImVector_char_size_in_bytes #:ImVector_ImTextureID_size_in_bytes #:ImVector_ImDrawVert_size_in_bytes #:ImVector_int_size_in_bytes #:ImVector_Pair_size_in_bytes #:ImVector_ImFontPtr_size_in_bytes #:ImVector_ImVec4_size_in_bytes #:ImVector_ImDrawCmd_size_in_bytes #:ImVector_ImDrawIdx_size_in_bytes #:ImVector_ImVec2_size_in_bytes #:ImVector_float_capacity #:ImVector_ImWchar_capacity #:ImVector_ImFontConfig_capacity #:ImVector_ImFontGlyph_capacity #:ImVector_TextRange_capacity #:ImVector_CustomRect_capacity #:ImVector_ImDrawChannel_capacity #:ImVector_char_capacity #:ImVector_ImTextureID_capacity #:ImVector_ImDrawVert_capacity #:ImVector_int_capacity #:ImVector_Pair_capacity #:ImVector_ImFontPtr_capacity #:ImVector_ImVec4_capacity #:ImVector_ImDrawCmd_capacity #:ImVector_ImDrawIdx_capacity #:ImVector_ImVec2_capacity #:ImVector_float_clear #:ImVector_ImWchar_clear #:ImVector_ImFontConfig_clear #:ImVector_ImFontGlyph_clear #:ImVector_TextRange_clear #:ImVector_CustomRect_clear #:ImVector_ImDrawChannel_clear #:ImVector_char_clear #:ImVector_ImTextureID_clear #:ImVector_ImDrawVert_clear #:ImVector_int_clear #:ImVector_Pair_clear #:ImVector_ImFontPtr_clear #:ImVector_ImVec4_clear #:ImVector_ImDrawCmd_clear #:ImVector_ImDrawIdx_clear #:ImVector_ImVec2_clear #:ImVector_float_begin #:ImVector_ImWchar_begin #:ImVector_ImFontConfig_begin #:ImVector_ImFontGlyph_begin #:ImVector_TextRange_begin #:ImVector_CustomRect_begin #:ImVector_ImDrawChannel_begin #:ImVector_char_begin #:ImVector_ImTextureID_begin #:ImVector_ImDrawVert_begin #:ImVector_int_begin #:ImVector_Pair_begin #:ImVector_ImFontPtr_begin #:ImVector_ImVec4_begin #:ImVector_ImDrawCmd_begin #:ImVector_ImDrawIdx_begin #:ImVector_ImVec2_begin #:ImVector_float_begin_const #:ImVector_ImWchar_begin_const #:ImVector_ImFontConfig_begin_const #:ImVector_ImFontGlyph_begin_const #:ImVector_TextRange_begin_const #:ImVector_CustomRect_begin_const #:ImVector_ImDrawChannel_begin_const #:ImVector_char_begin_const #:ImVector_ImTextureID_begin_const #:ImVector_ImDrawVert_begin_const #:ImVector_int_begin_const #:ImVector_Pair_begin_const #:ImVector_ImFontPtr_begin_const #:ImVector_ImVec4_begin_const #:ImVector_ImDrawCmd_begin_const #:ImVector_ImDrawIdx_begin_const #:ImVector_ImVec2_begin_const #:ImVector_float_end #:ImVector_ImWchar_end #:ImVector_ImFontConfig_end #:ImVector_ImFontGlyph_end #:ImVector_TextRange_end #:ImVector_CustomRect_end #:ImVector_ImDrawChannel_end #:ImVector_char_end #:ImVector_ImTextureID_end #:ImVector_ImDrawVert_end #:ImVector_int_end #:ImVector_Pair_end #:ImVector_ImFontPtr_end #:ImVector_ImVec4_end #:ImVector_ImDrawCmd_end #:ImVector_ImDrawIdx_end #:ImVector_ImVec2_end #:ImVector_float_end_const #:ImVector_ImWchar_end_const #:ImVector_ImFontConfig_end_const #:ImVector_ImFontGlyph_end_const #:ImVector_TextRange_end_const #:ImVector_CustomRect_end_const #:ImVector_ImDrawChannel_end_const #:ImVector_char_end_const #:ImVector_ImTextureID_end_const #:ImVector_ImDrawVert_end_const #:ImVector_int_end_const #:ImVector_Pair_end_const #:ImVector_ImFontPtr_end_const #:ImVector_ImVec4_end_const #:ImVector_ImDrawCmd_end_const #:ImVector_ImDrawIdx_end_const #:ImVector_ImVec2_end_const #:ImVector_float_front #:ImVector_ImWchar_front #:ImVector_ImFontConfig_front #:ImVector_ImFontGlyph_front #:ImVector_TextRange_front #:ImVector_CustomRect_front #:ImVector_ImDrawChannel_front #:ImVector_char_front #:ImVector_ImTextureID_front #:ImVector_ImDrawVert_front #:ImVector_int_front #:ImVector_Pair_front #:ImVector_ImFontPtr_front #:ImVector_ImVec4_front #:ImVector_ImDrawCmd_front #:ImVector_ImDrawIdx_front #:ImVector_ImVec2_front #:ImVector_float_front_const #:ImVector_ImWchar_front_const #:ImVector_ImFontConfig_front_const #:ImVector_ImFontGlyph_front_const #:ImVector_TextRange_front_const #:ImVector_CustomRect_front_const #:ImVector_ImDrawChannel_front_const #:ImVector_char_front_const #:ImVector_ImTextureID_front_const #:ImVector_ImDrawVert_front_const #:ImVector_int_front_const #:ImVector_Pair_front_const #:ImVector_ImFontPtr_front_const #:ImVector_ImVec4_front_const #:ImVector_ImDrawCmd_front_const #:ImVector_ImDrawIdx_front_const #:ImVector_ImVec2_front_const #:ImVector_float_back #:ImVector_ImWchar_back #:ImVector_ImFontConfig_back #:ImVector_ImFontGlyph_back #:ImVector_TextRange_back #:ImVector_CustomRect_back #:ImVector_ImDrawChannel_back #:ImVector_char_back #:ImVector_ImTextureID_back #:ImVector_ImDrawVert_back #:ImVector_int_back #:ImVector_Pair_back #:ImVector_ImFontPtr_back #:ImVector_ImVec4_back #:ImVector_ImDrawCmd_back #:ImVector_ImDrawIdx_back #:ImVector_ImVec2_back #:ImVector_float_back_const #:ImVector_ImWchar_back_const #:ImVector_ImFontConfig_back_const #:ImVector_ImFontGlyph_back_const #:ImVector_TextRange_back_const #:ImVector_CustomRect_back_const #:ImVector_ImDrawChannel_back_const #:ImVector_char_back_const #:ImVector_ImTextureID_back_const #:ImVector_ImDrawVert_back_const #:ImVector_int_back_const #:ImVector_Pair_back_const #:ImVector_ImFontPtr_back_const #:ImVector_ImVec4_back_const #:ImVector_ImDrawCmd_back_const #:ImVector_ImDrawIdx_back_const #:ImVector_ImVec2_back_const #:ImVector_float_swap #:ImVector_ImWchar_swap #:ImVector_ImFontConfig_swap #:ImVector_ImFontGlyph_swap #:ImVector_TextRange_swap #:ImVector_CustomRect_swap #:ImVector_ImDrawChannel_swap #:ImVector_char_swap #:ImVector_ImTextureID_swap #:ImVector_ImDrawVert_swap #:ImVector_int_swap #:ImVector_Pair_swap #:ImVector_ImFontPtr_swap #:ImVector_ImVec4_swap #:ImVector_ImDrawCmd_swap #:ImVector_ImDrawIdx_swap #:ImVector_ImVec2_swap #:ImVector_float__grow_capacity #:ImVector_ImWchar__grow_capacity #:ImVector_ImFontConfig__grow_capacity #:ImVector_ImFontGlyph__grow_capacity #:ImVector_TextRange__grow_capacity #:ImVector_CustomRect__grow_capacity #:ImVector_ImDrawChannel__grow_capacity #:ImVector_char__grow_capacity #:ImVector_ImTextureID__grow_capacity #:ImVector_ImDrawVert__grow_capacity #:ImVector_int__grow_capacity #:ImVector_Pair__grow_capacity #:ImVector_ImFontPtr__grow_capacity #:ImVector_ImVec4__grow_capacity #:ImVector_ImDrawCmd__grow_capacity #:ImVector_ImDrawIdx__grow_capacity #:ImVector_ImVec2__grow_capacity #:ImVector_float_resize #:ImVector_ImWchar_resize #:ImVector_ImFontConfig_resize #:ImVector_ImFontGlyph_resize #:ImVector_TextRange_resize #:ImVector_CustomRect_resize #:ImVector_ImDrawChannel_resize #:ImVector_char_resize #:ImVector_ImTextureID_resize #:ImVector_ImDrawVert_resize #:ImVector_int_resize #:ImVector_Pair_resize #:ImVector_ImFontPtr_resize #:ImVector_ImVec4_resize #:ImVector_ImDrawCmd_resize #:ImVector_ImDrawIdx_resize #:ImVector_ImVec2_resize #:ImVector_float_resizeT #:ImVector_ImWchar_resizeT #:ImVector_ImFontConfig_resizeT #:ImVector_ImFontGlyph_resizeT #:ImVector_TextRange_resizeT #:ImVector_CustomRect_resizeT #:ImVector_ImDrawChannel_resizeT #:ImVector_char_resizeT #:ImVector_ImTextureID_resizeT #:ImVector_ImDrawVert_resizeT #:ImVector_int_resizeT #:ImVector_Pair_resizeT #:ImVector_ImFontPtr_resizeT #:ImVector_ImVec4_resizeT #:ImVector_ImDrawCmd_resizeT #:ImVector_ImDrawIdx_resizeT #:ImVector_ImVec2_resizeT #:ImVector_float_reserve #:ImVector_ImWchar_reserve #:ImVector_ImFontConfig_reserve #:ImVector_ImFontGlyph_reserve #:ImVector_TextRange_reserve #:ImVector_CustomRect_reserve #:ImVector_ImDrawChannel_reserve #:ImVector_char_reserve #:ImVector_ImTextureID_reserve #:ImVector_ImDrawVert_reserve #:ImVector_int_reserve #:ImVector_Pair_reserve #:ImVector_ImFontPtr_reserve #:ImVector_ImVec4_reserve #:ImVector_ImDrawCmd_reserve #:ImVector_ImDrawIdx_reserve #:ImVector_ImVec2_reserve #:ImVector_float_push_back #:ImVector_ImWchar_push_back #:ImVector_ImFontConfig_push_back #:ImVector_ImFontGlyph_push_back #:ImVector_TextRange_push_back #:ImVector_CustomRect_push_back #:ImVector_ImDrawChannel_push_back #:ImVector_char_push_back #:ImVector_ImTextureID_push_back #:ImVector_ImDrawVert_push_back #:ImVector_int_push_back #:ImVector_Pair_push_back #:ImVector_ImFontPtr_push_back #:ImVector_ImVec4_push_back #:ImVector_ImDrawCmd_push_back #:ImVector_ImDrawIdx_push_back #:ImVector_ImVec2_push_back #:ImVector_float_pop_back #:ImVector_ImWchar_pop_back #:ImVector_ImFontConfig_pop_back #:ImVector_ImFontGlyph_pop_back #:ImVector_TextRange_pop_back #:ImVector_CustomRect_pop_back #:ImVector_ImDrawChannel_pop_back #:ImVector_char_pop_back #:ImVector_ImTextureID_pop_back #:ImVector_ImDrawVert_pop_back #:ImVector_int_pop_back #:ImVector_Pair_pop_back #:ImVector_ImFontPtr_pop_back #:ImVector_ImVec4_pop_back #:ImVector_ImDrawCmd_pop_back #:ImVector_ImDrawIdx_pop_back #:ImVector_ImVec2_pop_back #:ImVector_float_push_front #:ImVector_ImWchar_push_front #:ImVector_ImFontConfig_push_front #:ImVector_ImFontGlyph_push_front #:ImVector_TextRange_push_front #:ImVector_CustomRect_push_front #:ImVector_ImDrawChannel_push_front #:ImVector_char_push_front #:ImVector_ImTextureID_push_front #:ImVector_ImDrawVert_push_front #:ImVector_int_push_front #:ImVector_Pair_push_front #:ImVector_ImFontPtr_push_front #:ImVector_ImVec4_push_front #:ImVector_ImDrawCmd_push_front #:ImVector_ImDrawIdx_push_front #:ImVector_ImVec2_push_front #:ImVector_float_erase #:ImVector_ImWchar_erase #:ImVector_ImFontConfig_erase #:ImVector_ImFontGlyph_erase #:ImVector_TextRange_erase #:ImVector_CustomRect_erase #:ImVector_ImDrawChannel_erase #:ImVector_char_erase #:ImVector_ImTextureID_erase #:ImVector_ImDrawVert_erase #:ImVector_int_erase #:ImVector_Pair_erase #:ImVector_ImFontPtr_erase #:ImVector_ImVec4_erase #:ImVector_ImDrawCmd_erase #:ImVector_ImDrawIdx_erase #:ImVector_ImVec2_erase #:ImVector_float_eraseTPtr #:ImVector_ImWchar_eraseTPtr #:ImVector_ImFontConfig_eraseTPtr #:ImVector_ImFontGlyph_eraseTPtr #:ImVector_TextRange_eraseTPtr #:ImVector_CustomRect_eraseTPtr #:ImVector_ImDrawChannel_eraseTPtr #:ImVector_char_eraseTPtr #:ImVector_ImTextureID_eraseTPtr #:ImVector_ImDrawVert_eraseTPtr #:ImVector_int_eraseTPtr #:ImVector_Pair_eraseTPtr #:ImVector_ImFontPtr_eraseTPtr #:ImVector_ImVec4_eraseTPtr #:ImVector_ImDrawCmd_eraseTPtr #:ImVector_ImDrawIdx_eraseTPtr #:ImVector_ImVec2_eraseTPtr #:ImVector_float_erase_unsorted #:ImVector_ImWchar_erase_unsorted #:ImVector_ImFontConfig_erase_unsorted #:ImVector_ImFontGlyph_erase_unsorted #:ImVector_TextRange_erase_unsorted #:ImVector_CustomRect_erase_unsorted #:ImVector_ImDrawChannel_erase_unsorted #:ImVector_char_erase_unsorted #:ImVector_ImTextureID_erase_unsorted #:ImVector_ImDrawVert_erase_unsorted #:ImVector_int_erase_unsorted #:ImVector_Pair_erase_unsorted #:ImVector_ImFontPtr_erase_unsorted #:ImVector_ImVec4_erase_unsorted #:ImVector_ImDrawCmd_erase_unsorted #:ImVector_ImDrawIdx_erase_unsorted #:ImVector_ImVec2_erase_unsorted #:ImVector_float_insert #:ImVector_ImWchar_insert #:ImVector_ImFontConfig_insert #:ImVector_ImFontGlyph_insert #:ImVector_TextRange_insert #:ImVector_CustomRect_insert #:ImVector_ImDrawChannel_insert #:ImVector_char_insert #:ImVector_ImTextureID_insert #:ImVector_ImDrawVert_insert #:ImVector_int_insert #:ImVector_Pair_insert #:ImVector_ImFontPtr_insert #:ImVector_ImVec4_insert #:ImVector_ImDrawCmd_insert #:ImVector_ImDrawIdx_insert #:ImVector_ImVec2_insert #:ImVector_float_contains #:ImVector_ImWchar_contains #:ImVector_char_contains #:ImVector_int_contains #:ImVector_float_index_from_ptr #:ImVector_ImWchar_index_from_ptr #:ImVector_ImFontConfig_index_from_ptr #:ImVector_ImFontGlyph_index_from_ptr #:ImVector_TextRange_index_from_ptr #:ImVector_CustomRect_index_from_ptr #:ImVector_ImDrawChannel_index_from_ptr #:ImVector_char_index_from_ptr #:ImVector_ImTextureID_index_from_ptr #:ImVector_ImDrawVert_index_from_ptr #:ImVector_int_index_from_ptr #:ImVector_Pair_index_from_ptr #:ImVector_ImFontPtr_index_from_ptr #:ImVector_ImVec4_index_from_ptr #:ImVector_ImDrawCmd_index_from_ptr #:ImVector_ImDrawIdx_index_from_ptr #:ImVector_ImVec2_index_from_ptr #:igLogText #:ImGuiTextBuffer_appendf #:igGET_FLT_MAX #:igColorConvertRGBtoHSV #:igColorConvertHSVtoRGB #:ImVector_ImWchar_create #:ImVector_ImWchar_Init #:ImVector_ImWchar_UnInit #:igBeginChild #:igSetNextWindowPos #:igSetNextWindowSize #:igSetNextWindowSizeConstraints #:igSetNextWindowContentSize #:igSetWindowPosVec2 #:igSetWindowSizeVec2 #:igSetWindowPosStr #:igSetWindowSizeStr #:igPushStyleColor #:igPushStyleVarVec2 #:igSetCursorPos #:igSetCursorScreenPos #:igTextColored #:igTextColoredV #:igButton #:igInvisibleButton #:igImage #:igImageButton #:igPlotLines #:igPlotLinesFnPtr #:igPlotHistogramFloatPtr #:igPlotHistogramFnPtr #:igInputTextMultiline #:igVSliderFloat #:igVSliderInt #:igColorButton #:igSelectable #:igSelectableBoolPtr #:igListBoxHeaderVec2 #:igPushClipRect #:igIsRectVisible #:igBeginChildFrame #:igColorConvertFloat4ToU32 #:igIsMouseHoveringRect #:ImDrawList_PushClipRect #:ImDrawList_AddLine #:ImDrawList_AddRect #:ImDrawList_AddRectFilled #:ImDrawList_AddRectFilledMultiColor #:ImDrawList_AddQuad #:ImDrawList_AddQuadFilled #:ImDrawList_AddTriangle #:ImDrawList_AddTriangleFilled #:ImDrawList_AddCircle #:ImDrawList_AddCircleFilled #:ImDrawList_AddText #:ImDrawList_AddTextFontPtr #:ImDrawList_AddImage #:ImDrawList_AddImageQuad #:ImDrawList_AddImageRounded #:ImDrawList_PathLineTo #:ImDrawList_PathLineToMergeDuplicate #:ImDrawList_PathArcTo #:ImDrawList_PathArcToFast #:ImDrawList_PathBezierCurveTo #:ImDrawList_PathRect #:ImDrawList_PrimRect #:ImDrawList_PrimRectUV #:ImDrawList_PrimQuadUV #:ImDrawList_PrimWriteVtx #:ImDrawList_PrimVtx #:ImDrawData_ScaleClipRects #:igGetWindowPos #:igGetWindowSize #:igGetContentRegionMax #:igGetContentRegionAvail #:igGetWindowContentRegionMin #:igGetWindowContentRegionMax #:igGetFontTexUvWhitePixel #:igGetCursorPos #:igGetCursorStartPos #:igGetCursorScreenPos #:igGetItemRectMin #:igGetItemRectMax #:igGetItemRectSize #:igCalcTextSize #:igColorConvertU32ToFloat4 #:igGetMousePos #:igGetMousePosOnOpeningCurrentPopup #:igGetMouseDragDelta #:ImColor_HSV #:ImDrawList_GetClipRectMin #:ImDrawList_GetClipRectMax #:ImFont_CalcTextSizeA #:igGetWindowPos_nonUDT2 #:igGetWindowSize_nonUDT2 #:igGetContentRegionMax_nonUDT2 #:igGetContentRegionAvail_nonUDT2 #:igGetWindowContentRegionMin_nonUDT2 #:igGetWindowContentRegionMax_nonUDT2 #:igGetFontTexUvWhitePixel_nonUDT2 #:igGetCursorPos_nonUDT2 #:igGetCursorStartPos_nonUDT2 #:igGetCursorScreenPos_nonUDT2 #:igGetItemRectMin_nonUDT2 #:igGetItemRectMax_nonUDT2 #:igCalcTextSize_nonUDT2 #:igColorConvertU32ToFloat4_nonUDT2 #:igGetMousePos_nonUDT2 #:igGetMousePosOnOpeningCurrentPopup_nonUDT2 #:igGetMouseDragDelta_nonUDT2 #:ImColor_HSV_nonUDT2 #:ImDrawList_GetClipRectMin_nonUDT2 #:ImDrawList_GetClipRectMax_nonUDT2 #:ImFont_CalcTextSizeA_nonUDT2))
a2ff17370622d22c4e0543a74a1f11b029bb5ad6de6db212cd372dea491159f1
lispnik/cl-http
mcl-mop-package.lisp
(defpackage "MCL-MOP" (:use :cl #+:mcl :ccl) #+:mcl (:nicknames :mop) (:shadow "METAOBJECT") (:export Readers for Class ; "CLASS-DEFAULT-INITARGS" ; "CLASS-DIRECT-DEFAULT-INITARGS" "CLASS-DIRECT-SLOTS" "CLASS-DIRECT-SUBCLASSES" "CLASS-DIRECT-SUPERCLASSES" ; "CLASS-FINALIZED-P" ; "CLASS-NAME" "CLASS-PRECEDENCE-LIST" "CLASS-PROTOTYPE" "CLASS-SLOTS" "ENSURE-CLASS" "ENSURE-CLASS-USING-CLASS" ;; Readers for Generic Function Metaobjects ; "GENERIC-FUNCTION-ARGUMENT-PRECEDENCE-ORDER" ; "GENERIC-FUNCTION-DECLARATIONS" ; "GENERIC-FUNCTION-LAMBDA-LIST" ; "GENERIC-FUNCTION-METHOD-CLASS" ; "GENERIC-FUNCTION-METHOD-COMBINATION" ; "GENERIC-FUNCTION-METHODS" ; "GENERIC-FUNCTION-NAME" ;; Readers for Method Metaobjects ;; Readers for Slot Definition Metaobjects "SLOT-DEFINITION-ALLOCATION" "SLOT-DEFINITION-INITARGS" "SLOT-DEFINITION-INITFORM" "SLOT-DEFINITION-INITFUNCTION" "SLOT-DEFINITION-NAME" "SLOT-DEFINITION-TYPE" "SLOT-DEFINITION-READERS" ; "SLOT-DEFINITION-LOCATION" "SLOT-DEFINITION-WRITERS" ;; nicht im Standard-MOP "MOP-STANDARD-CLASS" "CANONICALIZE-DEFCLASS-OPTION" "CANONICALIZE-DEFCLASS-OPTIONS" "EFFECTIVE-SLOT-DEFINITION-CLASS" "DIRECT-SLOT-DEFINITION-CLASS" "STANDARD-EFFECTIVE-SLOT-DEFINITION" "STANDARD-DIRECT-SLOT-DEFINITION"))
null
https://raw.githubusercontent.com/lispnik/cl-http/84391892d88c505aed705762a153eb65befb6409/contrib/janderson/xml-1998-02-27/mcl-mop-package.lisp
lisp
"CLASS-DEFAULT-INITARGS" "CLASS-DIRECT-DEFAULT-INITARGS" "CLASS-FINALIZED-P" "CLASS-NAME" Readers for Generic Function Metaobjects "GENERIC-FUNCTION-ARGUMENT-PRECEDENCE-ORDER" "GENERIC-FUNCTION-DECLARATIONS" "GENERIC-FUNCTION-LAMBDA-LIST" "GENERIC-FUNCTION-METHOD-CLASS" "GENERIC-FUNCTION-METHOD-COMBINATION" "GENERIC-FUNCTION-METHODS" "GENERIC-FUNCTION-NAME" Readers for Method Metaobjects Readers for Slot Definition Metaobjects "SLOT-DEFINITION-LOCATION" nicht im Standard-MOP
(defpackage "MCL-MOP" (:use :cl #+:mcl :ccl) #+:mcl (:nicknames :mop) (:shadow "METAOBJECT") (:export Readers for Class "CLASS-DIRECT-SLOTS" "CLASS-DIRECT-SUBCLASSES" "CLASS-DIRECT-SUPERCLASSES" "CLASS-PRECEDENCE-LIST" "CLASS-PROTOTYPE" "CLASS-SLOTS" "ENSURE-CLASS" "ENSURE-CLASS-USING-CLASS" "SLOT-DEFINITION-ALLOCATION" "SLOT-DEFINITION-INITARGS" "SLOT-DEFINITION-INITFORM" "SLOT-DEFINITION-INITFUNCTION" "SLOT-DEFINITION-NAME" "SLOT-DEFINITION-TYPE" "SLOT-DEFINITION-READERS" "SLOT-DEFINITION-WRITERS" "MOP-STANDARD-CLASS" "CANONICALIZE-DEFCLASS-OPTION" "CANONICALIZE-DEFCLASS-OPTIONS" "EFFECTIVE-SLOT-DEFINITION-CLASS" "DIRECT-SLOT-DEFINITION-CLASS" "STANDARD-EFFECTIVE-SLOT-DEFINITION" "STANDARD-DIRECT-SLOT-DEFINITION"))
0b4c3f924da174d433594719453013a343e11cafca5a71dc7e15f2bea3b9990e
VERIMAG-Polyhedra/VPL
QNoneItv.ml
open NumC open Qcanon open Itv open DomainInterfaces module QN = struct type t = coq_Qc option let add qn1 qn2 = match qn1, qn2 with | Some q1, Some q2 -> Some (QNum.add q1 q2) | _,_ -> None (** val opp : t -> t **) let opp = function | Some q -> Some (QNum.opp q) | None -> None let max : coq_Qc -> coq_Qc -> coq_Qc = fun q1 q2 -> if coq_Qclt_le_dec q1 q2 then q2 else q1 let min : coq_Qc -> coq_Qc -> coq_Qc = fun q1 q2 -> if coq_Qclt_le_dec q1 q2 then q1 else q2 * join : t - > t - > t * let join qn1 qn2 = match qn1, qn2 with | Some q1, Some q2 -> Some (max q1 q2) | _,_ -> None let mul qn1 qn2 = match qn1, qn2 with | Some q1, Some q2 -> Some (QNum.mul q1 q2) | _,_ -> None (** val meet : t -> t -> t **) let meet qn1 qn2 = match qn1, qn2 with | Some q1, Some q2 -> Some (min q1 q2) | _,_ -> None end module QNItv = struct type itv = { low : QN.t; up : QN.t } (** val low : itv -> QN.t **) let low x = x.low (** val up : itv -> QN.t **) let up x = x.up type t = itv * top : itv * let top = { low = None; up = None } let fromBndT = function | QItv.Infty -> None | QItv.Open n | QItv.Closed n -> Some n let oppMode = function | BOTH -> BOTH | UP -> LOW | LOW -> UP let fromQItv i = { low = (fromBndT i.QItv.lower); up = (fromBndT i.QItv.upper) } (** val single : coq_Z -> itv **) let single z = let zn = Some z in { low = zn; up = zn } * add : mode - > itv - > itv - > itv * let add m i1 i2 = match m with | BOTH -> { low = QN.add i1.low i2.low; up = QN.add i1.up i2.up } | UP -> { low = None; up = QN.add i1.up i2.up } | LOW -> { low = QN.add i1.low i2.low; up = None} * val opp : itv - > itv * let opp i = { low = QN.opp i.low ; up = QN.opp i.up } mul ( l1,u1 ) ( l2,u2 ) = min ( l1*l2 , l1*u12 , u1 * l2 , u1 * u2 ) , ... let mul m i1 i2 = match m with | BOTH -> let max = QN.join (QN.join (QN.join (QN.mul i1.low i2.low) (QN.mul i1.low i2.up)) (QN.mul i1.up i2.low)) (QN.mul i1.up i2.up) in let min = QN.meet (QN.meet (QN.meet (QN.mul i1.low i2.low) (QN.mul i1.low i2.up)) (QN.mul i1.up i2.low)) (QN.mul i1.up i2.up) in { low = min ; up = max } | UP -> let max = QN.join (QN.join (QN.join (QN.mul i1.low i2.low) (QN.mul i1.low i2.up)) (QN.mul i1.up i2.low)) (QN.mul i1.up i2.up) in { low = None; up = max } | LOW -> let min = QN.meet (QN.meet (QN.meet (QN.mul i1.low i2.low) (QN.mul i1.low i2.up)) (QN.mul i1.up i2.low)) (QN.mul i1.up i2.up) in { low = min ; up = None } * join : mode - > itv - > itv - > itv * let join m i1 i2 = match m with | BOTH -> { low = (QN.meet i1.low i2.low); up = (QN.join i1.up i2.up) } | UP -> { low = None; up = (QN.join i1.up i2.up) } | LOW -> { low = (QN.meet i1.low i2.low); up = None } end
null
https://raw.githubusercontent.com/VERIMAG-Polyhedra/VPL/cd78d6e7d120508fd5a694bdb01300477e5646f8/ocaml/lin/oracle/QNoneItv.ml
ocaml
* val opp : t -> t * * val meet : t -> t -> t * * val low : itv -> QN.t * * val up : itv -> QN.t * * val single : coq_Z -> itv *
open NumC open Qcanon open Itv open DomainInterfaces module QN = struct type t = coq_Qc option let add qn1 qn2 = match qn1, qn2 with | Some q1, Some q2 -> Some (QNum.add q1 q2) | _,_ -> None let opp = function | Some q -> Some (QNum.opp q) | None -> None let max : coq_Qc -> coq_Qc -> coq_Qc = fun q1 q2 -> if coq_Qclt_le_dec q1 q2 then q2 else q1 let min : coq_Qc -> coq_Qc -> coq_Qc = fun q1 q2 -> if coq_Qclt_le_dec q1 q2 then q1 else q2 * join : t - > t - > t * let join qn1 qn2 = match qn1, qn2 with | Some q1, Some q2 -> Some (max q1 q2) | _,_ -> None let mul qn1 qn2 = match qn1, qn2 with | Some q1, Some q2 -> Some (QNum.mul q1 q2) | _,_ -> None let meet qn1 qn2 = match qn1, qn2 with | Some q1, Some q2 -> Some (min q1 q2) | _,_ -> None end module QNItv = struct type itv = { low : QN.t; up : QN.t } let low x = x.low let up x = x.up type t = itv * top : itv * let top = { low = None; up = None } let fromBndT = function | QItv.Infty -> None | QItv.Open n | QItv.Closed n -> Some n let oppMode = function | BOTH -> BOTH | UP -> LOW | LOW -> UP let fromQItv i = { low = (fromBndT i.QItv.lower); up = (fromBndT i.QItv.upper) } let single z = let zn = Some z in { low = zn; up = zn } * add : mode - > itv - > itv - > itv * let add m i1 i2 = match m with | BOTH -> { low = QN.add i1.low i2.low; up = QN.add i1.up i2.up } | UP -> { low = None; up = QN.add i1.up i2.up } | LOW -> { low = QN.add i1.low i2.low; up = None} * val opp : itv - > itv * let opp i = { low = QN.opp i.low ; up = QN.opp i.up } mul ( l1,u1 ) ( l2,u2 ) = min ( l1*l2 , l1*u12 , u1 * l2 , u1 * u2 ) , ... let mul m i1 i2 = match m with | BOTH -> let max = QN.join (QN.join (QN.join (QN.mul i1.low i2.low) (QN.mul i1.low i2.up)) (QN.mul i1.up i2.low)) (QN.mul i1.up i2.up) in let min = QN.meet (QN.meet (QN.meet (QN.mul i1.low i2.low) (QN.mul i1.low i2.up)) (QN.mul i1.up i2.low)) (QN.mul i1.up i2.up) in { low = min ; up = max } | UP -> let max = QN.join (QN.join (QN.join (QN.mul i1.low i2.low) (QN.mul i1.low i2.up)) (QN.mul i1.up i2.low)) (QN.mul i1.up i2.up) in { low = None; up = max } | LOW -> let min = QN.meet (QN.meet (QN.meet (QN.mul i1.low i2.low) (QN.mul i1.low i2.up)) (QN.mul i1.up i2.low)) (QN.mul i1.up i2.up) in { low = min ; up = None } * join : mode - > itv - > itv - > itv * let join m i1 i2 = match m with | BOTH -> { low = (QN.meet i1.low i2.low); up = (QN.join i1.up i2.up) } | UP -> { low = None; up = (QN.join i1.up i2.up) } | LOW -> { low = (QN.meet i1.low i2.low); up = None } end
667b37f6a835c517ca5bbec3eed9ccb5400c3d9ea90447f62adb4650b6f375e9
patrickt/scraps
lookandsay.hs
-- -and-say_sequence Implementation of the look - and - say sequence in 15 lines of code . Arrows are a very nice way to represent sequenced , chainable functions in Haskell . For more info , check the wonderful Wikibooks tutorial at -- import Control.Arrow import Data.List (group) -- `say` produces a new integer by reading out the digits in its argument. -- The >>> operator sequences functions together. say :: Integer -> Integer say = digits >>> encode >>> glue -- digits splits a number up into its component digits. digits :: Integer -> [Integer] digits = fmap read . fmap return . show -- encode performs run-length encoding on its arguments. We get rid of nasty tuple manipulation with the & & & combinator . encode :: (Eq a) => [a] -> [(Int, a)] encode = fmap (length &&& head) . group -- glue assembles the new number out of a list of encoded tuples glue :: [(Int, Integer)] -> Integer glue = read . concatMap show' where show' (a,b) = show a ++ show b -- The iterate method builds an infinite list out of a starting value and method. lookAndSaySequence :: [Integer] lookAndSaySequence = iterate say 1 -- Proof that it works. main :: IO () main = print $ take 15 lookAndSaySequence
null
https://raw.githubusercontent.com/patrickt/scraps/517c8f913000b9d7b886338cf06adf5d9e239d31/lookandsay.hs
haskell
-and-say_sequence `say` produces a new integer by reading out the digits in its argument. The >>> operator sequences functions together. digits splits a number up into its component digits. encode performs run-length encoding on its arguments. glue assembles the new number out of a list of encoded tuples The iterate method builds an infinite list out of a starting value and method. Proof that it works.
Implementation of the look - and - say sequence in 15 lines of code . Arrows are a very nice way to represent sequenced , chainable functions in Haskell . For more info , check the wonderful Wikibooks tutorial at import Control.Arrow import Data.List (group) say :: Integer -> Integer say = digits >>> encode >>> glue digits :: Integer -> [Integer] digits = fmap read . fmap return . show We get rid of nasty tuple manipulation with the & & & combinator . encode :: (Eq a) => [a] -> [(Int, a)] encode = fmap (length &&& head) . group glue :: [(Int, Integer)] -> Integer glue = read . concatMap show' where show' (a,b) = show a ++ show b lookAndSaySequence :: [Integer] lookAndSaySequence = iterate say 1 main :: IO () main = print $ take 15 lookAndSaySequence
637577dafd49588eafa27b87e44ffccdcbcd87d9b1c260bae433bf9e9d243a9a
hatemogi/misaeng
집합.clj
(ns 미생.집합 (:use [clojure.set] [미생.기본])) (정의* 합집합 union 차집합 difference 교집합 intersection 부분집합? subset? 확대집합? superset?)
null
https://raw.githubusercontent.com/hatemogi/misaeng/7b097d9d9ae497606cf54be586fe7a0f50bb7ffc/src/%EB%AF%B8%EC%83%9D/%EC%A7%91%ED%95%A9.clj
clojure
(ns 미생.집합 (:use [clojure.set] [미생.기본])) (정의* 합집합 union 차집합 difference 교집합 intersection 부분집합? subset? 확대집합? superset?)
036aaf19a469651dfd1d120f768532db6178fc04e431faaaa6da2ad4c9b33787
cedlemo/OCaml-GI-ctypes-bindings-generator
Target_list.mli
open Ctypes type t val t_typ : t structure typ (*Not implemented gtk_target_list_new type C Array type for Types.Array tag not implemented*) val add : t structure ptr -> Atom.t structure ptr -> Unsigned.uint32 -> Unsigned.uint32 -> unit val add_image_targets : t structure ptr -> Unsigned.uint32 -> bool -> unit val add_rich_text_targets : t structure ptr -> Unsigned.uint32 -> bool -> Text_buffer.t ptr -> unit (*Not implemented gtk_target_list_add_table type C Array type for Types.Array tag not implemented*) val add_text_targets : t structure ptr -> Unsigned.uint32 -> unit val add_uri_targets : t structure ptr -> Unsigned.uint32 -> unit val find : t structure ptr -> Atom.t structure ptr -> (bool * Unsigned.uint32) val incr_ref : t structure ptr -> t structure ptr val remove : t structure ptr -> Atom.t structure ptr -> unit val unref : t structure ptr -> unit
null
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Target_list.mli
ocaml
Not implemented gtk_target_list_new type C Array type for Types.Array tag not implemented Not implemented gtk_target_list_add_table type C Array type for Types.Array tag not implemented
open Ctypes type t val t_typ : t structure typ val add : t structure ptr -> Atom.t structure ptr -> Unsigned.uint32 -> Unsigned.uint32 -> unit val add_image_targets : t structure ptr -> Unsigned.uint32 -> bool -> unit val add_rich_text_targets : t structure ptr -> Unsigned.uint32 -> bool -> Text_buffer.t ptr -> unit val add_text_targets : t structure ptr -> Unsigned.uint32 -> unit val add_uri_targets : t structure ptr -> Unsigned.uint32 -> unit val find : t structure ptr -> Atom.t structure ptr -> (bool * Unsigned.uint32) val incr_ref : t structure ptr -> t structure ptr val remove : t structure ptr -> Atom.t structure ptr -> unit val unref : t structure ptr -> unit
f6e0a3b8111c1686ee1f3c1640eebb16b964a6489875d9ccaecd8f2a7a1b5e0e
GregoryTravis/holfenstein
FPS.hs
module FPS ( fps , frBufferEmpty ) where import Data.Time.Clock.POSIX (getPOSIXTime) frBufferLen = 20 data FRBuffer = FRBuffer [Double] Double Int frBufferEmpty = FRBuffer [] 0 0 frBufferAvg (FRBuffer _ _ 0) = 0 frBufferAvg (FRBuffer es tot num) = tot / (fromIntegral num) frBufferAdd (FRBuffer es tot num) e | num == frBufferLen = FRBuffer [e] e 1 | otherwise = FRBuffer (e : es) (tot + e) (num + 1) frBufferUpdate :: FRBuffer -> Double -> (Double, FRBuffer) frBufferUpdate frBuf e = (frBufferAvg frBuf, frBufferAdd frBuf e) fps lastNow frBuf = do now <- getPOSIXTime let instantFPS :: Double instantFPS = 1.0 / (realToFrac (now - lastNow)) let (fps, newFRBuf) = frBufferUpdate frBuf instantFPS return (now, fps, newFRBuf)
null
https://raw.githubusercontent.com/GregoryTravis/holfenstein/fcb8743351700c701757dc13fb6defcde53be306/FPS.hs
haskell
module FPS ( fps , frBufferEmpty ) where import Data.Time.Clock.POSIX (getPOSIXTime) frBufferLen = 20 data FRBuffer = FRBuffer [Double] Double Int frBufferEmpty = FRBuffer [] 0 0 frBufferAvg (FRBuffer _ _ 0) = 0 frBufferAvg (FRBuffer es tot num) = tot / (fromIntegral num) frBufferAdd (FRBuffer es tot num) e | num == frBufferLen = FRBuffer [e] e 1 | otherwise = FRBuffer (e : es) (tot + e) (num + 1) frBufferUpdate :: FRBuffer -> Double -> (Double, FRBuffer) frBufferUpdate frBuf e = (frBufferAvg frBuf, frBufferAdd frBuf e) fps lastNow frBuf = do now <- getPOSIXTime let instantFPS :: Double instantFPS = 1.0 / (realToFrac (now - lastNow)) let (fps, newFRBuf) = frBufferUpdate frBuf instantFPS return (now, fps, newFRBuf)
2c3f3c7a5541355e365fa38d4c958b84e5e3d1a4a4ced148e4eb9924f2eedf5f
f-me/carma-public
DeliveryType.hs
module Carma.Model.DeliveryType where import Data.Text import Data.Typeable import Data.Model import Data.Model.View import Carma.Model.Types() import Carma.Model.PgTypes() data DeliveryType = DeliveryType { ident :: PK Int DeliveryType "Тип доставки" , label :: F Text "label" "Тип" } deriving Typeable instance Model DeliveryType where type TableName DeliveryType = "DeliveryType" modelInfo = mkModelInfo DeliveryType ident modelView = \case "" -> Just defaultView _ -> Nothing
null
https://raw.githubusercontent.com/f-me/carma-public/82a9f44f7d919e54daa4114aa08dfec58b01009b/carma-models/src/Carma/Model/DeliveryType.hs
haskell
module Carma.Model.DeliveryType where import Data.Text import Data.Typeable import Data.Model import Data.Model.View import Carma.Model.Types() import Carma.Model.PgTypes() data DeliveryType = DeliveryType { ident :: PK Int DeliveryType "Тип доставки" , label :: F Text "label" "Тип" } deriving Typeable instance Model DeliveryType where type TableName DeliveryType = "DeliveryType" modelInfo = mkModelInfo DeliveryType ident modelView = \case "" -> Just defaultView _ -> Nothing
e0894357ca543ea6befa354cbfb3972e24c6306d856161f2d20d2f4f131163e8
shayne-fletcher/zen
ml_longident.mli
type t = | Lident of string | Ldot of t * string | Lapply of t * t val flatten : t -> string list val last : t -> string val parse : string -> t
null
https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/cos/src/parsing/ml_longident.mli
ocaml
type t = | Lident of string | Ldot of t * string | Lapply of t * t val flatten : t -> string list val last : t -> string val parse : string -> t
c02564b552a86432e463baccd5efde800849075f2e1658d017de1ffe4ecc9f2a
clojure-link/link
http2.clj
(ns link.http.http2 (:require [link.core :refer :all] [link.http.common :refer :all] [clojure.string :as string] [clojure.tools.logging :as logging]) (:import [java.net InetSocketAddress] [io.netty.buffer ByteBufInputStream] [io.netty.channel ChannelFuture SimpleChannelInboundHandler] [io.netty.handler.codec.http HttpResponseStatus HttpServerUpgradeHandler$UpgradeCodecFactory] [io.netty.handler.codec.http2 Http2FrameCodecBuilder Http2HeadersFrame Http2DataFrame Http2Headers Http2Headers$PseudoHeaderName DefaultHttp2Headers DefaultHttp2HeadersFrame DefaultHttp2DataFrame Http2CodecUtil Http2ServerUpgradeCodec] [io.netty.util.concurrent GenericFutureListener])) (defn from-header-iterator "extract ring headers from http2headers" [http2headers-iterator] (as-header-map (iterator-seq http2headers-iterator))) (defn ring-data-from-header [ch ^Http2HeadersFrame frame] (let [server-addr (channel-addr ch) http2headers (.headers frame) uri (str (.path http2headers)) header-map (from-header-iterator (.iterator http2headers))] {:scheme (keyword (str (.scheme http2headers))) :protocol "h2c" :request-method (-> (.method http2headers) (string/lower-case) (keyword)) :uri (find-request-uri uri) :query-string (find-query-string uri) :headers header-map :server-name (.getHostString ^InetSocketAddress server-addr) :server-port (.getPort ^InetSocketAddress server-addr) :remote-addr (.getHostString ^InetSocketAddress (remote-addr ch))})) (defn ring-response-to-http2 [resp alloc] (let [resp (if (map? resp) resp {:body resp}) {status :status headers :headers body :body} resp status (or status 200) content (content-from-ring-body body alloc) http2headers (doto (DefaultHttp2Headers.) (.status (.codeAsText (HttpResponseStatus/valueOf status))))] ;; set headers (doseq [header (or headers {})] (.set ^DefaultHttp2Headers http2headers ^String (key header) ^Object (val header))) (if content [(DefaultHttp2HeadersFrame. http2headers) (DefaultHttp2DataFrame. content true)] [(DefaultHttp2HeadersFrame. http2headers true)]))) (defn http2-on-error [ch exc debug] (let [resp-frames (ring-response-to-http2 {:status 500 :body (if debug (str (.getStackTrace exc)) "Internal Error")} (.alloc ch))] ;; TODO: which stream? (doseq [f resp-frames] (send! ch f)))) (def ^:const http2-data-key "HTTP_DATA") (defn- handle-full-request [ch msg ring-fn async? debug?] (when (.isEndStream msg) (let [ring-req (channel-attr-get ch http2-data-key) stream (.stream msg)] (if-not async? ;; sync (let [ring-resp (ring-fn ring-req) resp-frames (ring-response-to-http2 ring-resp (.alloc ch))] (doseq [f resp-frames] (send! ch (.stream f stream)))) ;; async (let [send-fn (fn [resp] (doseq [f (ring-response-to-http2 resp (.alloc ch))] (send! ch (.stream f stream)))) raise-fn (fn [error] (http2-on-error ch error debug?))] (ring-fn ring-req send-fn raise-fn)))))) (defn http2-stream-handler [ring-fn async? debug?] (create-handler (on-message [ch msg] (println msg) (cond (instance? Http2HeadersFrame msg) (let [ring-data (ring-data-from-header ch msg)] (channel-attr-set! ch http2-data-key ring-data) (handle-full-request ch msg ring-fn async? debug?)) (instance? Http2DataFrame msg) (let [body-in (ByteBufInputStream. (.content ^Http2DataFrame msg)) ring-data (channel-attr-get http2-data-key)] (when (> (.available ^ByteBufInputStream body-in) 0) (channel-attr-set! ch http2-data-key (assoc ring-data :body body-in))) (handle-full-request ch msg ring-fn async? debug?))) ) (on-error [ch exc] (logging/warn exc "Uncaught exception") (http2-on-error ch exc debug?)))) (defn http2-frame-handler [] (.build (Http2FrameCodecBuilder/forServer))) ;; for h2c (defn http2-upgrade-handler [ring-fn async? debug?] (reify HttpServerUpgradeHandler$UpgradeCodecFactory (newUpgradeCodec [this protocol] (when (= protocol Http2CodecUtil/HTTP_UPGRADE_PROTOCOL_NAME) (Http2ServerUpgradeCodec. (http2-frame-handler) (http2-stream-handler ring-fn async? debug?))))))
null
https://raw.githubusercontent.com/clojure-link/link/2b6f6abe70edfade738c7391d38c5b509c798a40/src/link/http/http2.clj
clojure
set headers TODO: which stream? sync async for h2c
(ns link.http.http2 (:require [link.core :refer :all] [link.http.common :refer :all] [clojure.string :as string] [clojure.tools.logging :as logging]) (:import [java.net InetSocketAddress] [io.netty.buffer ByteBufInputStream] [io.netty.channel ChannelFuture SimpleChannelInboundHandler] [io.netty.handler.codec.http HttpResponseStatus HttpServerUpgradeHandler$UpgradeCodecFactory] [io.netty.handler.codec.http2 Http2FrameCodecBuilder Http2HeadersFrame Http2DataFrame Http2Headers Http2Headers$PseudoHeaderName DefaultHttp2Headers DefaultHttp2HeadersFrame DefaultHttp2DataFrame Http2CodecUtil Http2ServerUpgradeCodec] [io.netty.util.concurrent GenericFutureListener])) (defn from-header-iterator "extract ring headers from http2headers" [http2headers-iterator] (as-header-map (iterator-seq http2headers-iterator))) (defn ring-data-from-header [ch ^Http2HeadersFrame frame] (let [server-addr (channel-addr ch) http2headers (.headers frame) uri (str (.path http2headers)) header-map (from-header-iterator (.iterator http2headers))] {:scheme (keyword (str (.scheme http2headers))) :protocol "h2c" :request-method (-> (.method http2headers) (string/lower-case) (keyword)) :uri (find-request-uri uri) :query-string (find-query-string uri) :headers header-map :server-name (.getHostString ^InetSocketAddress server-addr) :server-port (.getPort ^InetSocketAddress server-addr) :remote-addr (.getHostString ^InetSocketAddress (remote-addr ch))})) (defn ring-response-to-http2 [resp alloc] (let [resp (if (map? resp) resp {:body resp}) {status :status headers :headers body :body} resp status (or status 200) content (content-from-ring-body body alloc) http2headers (doto (DefaultHttp2Headers.) (.status (.codeAsText (HttpResponseStatus/valueOf status))))] (doseq [header (or headers {})] (.set ^DefaultHttp2Headers http2headers ^String (key header) ^Object (val header))) (if content [(DefaultHttp2HeadersFrame. http2headers) (DefaultHttp2DataFrame. content true)] [(DefaultHttp2HeadersFrame. http2headers true)]))) (defn http2-on-error [ch exc debug] (let [resp-frames (ring-response-to-http2 {:status 500 :body (if debug (str (.getStackTrace exc)) "Internal Error")} (.alloc ch))] (doseq [f resp-frames] (send! ch f)))) (def ^:const http2-data-key "HTTP_DATA") (defn- handle-full-request [ch msg ring-fn async? debug?] (when (.isEndStream msg) (let [ring-req (channel-attr-get ch http2-data-key) stream (.stream msg)] (if-not async? (let [ring-resp (ring-fn ring-req) resp-frames (ring-response-to-http2 ring-resp (.alloc ch))] (doseq [f resp-frames] (send! ch (.stream f stream)))) (let [send-fn (fn [resp] (doseq [f (ring-response-to-http2 resp (.alloc ch))] (send! ch (.stream f stream)))) raise-fn (fn [error] (http2-on-error ch error debug?))] (ring-fn ring-req send-fn raise-fn)))))) (defn http2-stream-handler [ring-fn async? debug?] (create-handler (on-message [ch msg] (println msg) (cond (instance? Http2HeadersFrame msg) (let [ring-data (ring-data-from-header ch msg)] (channel-attr-set! ch http2-data-key ring-data) (handle-full-request ch msg ring-fn async? debug?)) (instance? Http2DataFrame msg) (let [body-in (ByteBufInputStream. (.content ^Http2DataFrame msg)) ring-data (channel-attr-get http2-data-key)] (when (> (.available ^ByteBufInputStream body-in) 0) (channel-attr-set! ch http2-data-key (assoc ring-data :body body-in))) (handle-full-request ch msg ring-fn async? debug?))) ) (on-error [ch exc] (logging/warn exc "Uncaught exception") (http2-on-error ch exc debug?)))) (defn http2-frame-handler [] (.build (Http2FrameCodecBuilder/forServer))) (defn http2-upgrade-handler [ring-fn async? debug?] (reify HttpServerUpgradeHandler$UpgradeCodecFactory (newUpgradeCodec [this protocol] (when (= protocol Http2CodecUtil/HTTP_UPGRADE_PROTOCOL_NAME) (Http2ServerUpgradeCodec. (http2-frame-handler) (http2-stream-handler ring-fn async? debug?))))))
cd96943a6452ba4d80161221a24299e0d329e2bc463d387b74a45716361c0d8c
jacekschae/learn-re-frame-course-files
recipe_card.cljs
(ns app.recipes.views.recipe-card (:require [app.router :as router] ["@smooth-ui/core-sc" :refer [Button Box Typography]] ["styled-icons/fa-solid/Heart" :refer [Heart]] ["styled-icons/fa-regular/Clock" :refer [Clock]])) (defn recipe-card [{:keys [name saved-count prep-time img id]}] [:> Box {:as "a" :href (router/path-for :recipes) :class "recipe-card"} [:> Box {:class "img-card" :background-image (str "url(" (or img "/img/placeholder.jpg") ")") :background-size "cover" :min-height "280px" :alt name}] [:> Box {:p 2} [:> Typography {:variant "h6" :font-weight 700} name]] [:> Box {:pl 2 :pb 2 :display "flex"} [:> Box {:display "flex" :align-items "center"} [:> Heart {:size 16}] [:> Box {:pl 10} saved-count]] [:> Box {:display "flex" :align-items "center" :pl 5} [:> Clock {:size 16}] [:> Box {:pl 10} prep-time " min"]]]])
null
https://raw.githubusercontent.com/jacekschae/learn-re-frame-course-files/a86e6f14b89c595b4389b03459539a9544af4e1d/increments/27-recipe-route/src/app/recipes/views/recipe_card.cljs
clojure
(ns app.recipes.views.recipe-card (:require [app.router :as router] ["@smooth-ui/core-sc" :refer [Button Box Typography]] ["styled-icons/fa-solid/Heart" :refer [Heart]] ["styled-icons/fa-regular/Clock" :refer [Clock]])) (defn recipe-card [{:keys [name saved-count prep-time img id]}] [:> Box {:as "a" :href (router/path-for :recipes) :class "recipe-card"} [:> Box {:class "img-card" :background-image (str "url(" (or img "/img/placeholder.jpg") ")") :background-size "cover" :min-height "280px" :alt name}] [:> Box {:p 2} [:> Typography {:variant "h6" :font-weight 700} name]] [:> Box {:pl 2 :pb 2 :display "flex"} [:> Box {:display "flex" :align-items "center"} [:> Heart {:size 16}] [:> Box {:pl 10} saved-count]] [:> Box {:display "flex" :align-items "center" :pl 5} [:> Clock {:size 16}] [:> Box {:pl 10} prep-time " min"]]]])
a02a733c03fd42a3209220a0004683de5ea27d439694e703503bbdecc04279fa
GlideAngle/flare-timing
CompInput.hs
module Flight.CompInput ( readComp, writeComp , readTask, writeTask , readCompAndTasks, readCompAndTasksQuietly, writeCompAndTasks , readCompTracks, readCompTracksQuietly ) where import System.FilePath (takeDirectory) import System.Directory (createDirectoryIfMissing) import Control.Exception.Safe (MonadThrow) import Control.Monad.Except (MonadIO, liftIO) import qualified Data.ByteString as BS import Data.Yaml (decodeThrow) import qualified Data.Yaml.Pretty as Y import Control.Concurrent.ParallelIO (parallel, parallel_) import Flight.Field (FieldOrdering(..)) import Flight.Comp ( ScoringInputFiles, CompInputFile(..), TaskInputFile(..) , CompSettings(..), TaskSettings(..) , PilotTrackLogFile(..), TaskFolder(..) ) readComp :: (MonadThrow m, MonadIO m) => CompInputFile -> m (CompSettings k) readComp (CompInputFile path) = liftIO $ BS.readFile path >>= decodeThrow writeComp :: CompInputFile -> CompSettings k -> IO () writeComp (CompInputFile path) compInput = do let cfg = Y.setConfCompare (fieldOrder compInput) Y.defConfig let yaml = Y.encodePretty cfg compInput BS.writeFile path yaml readTask :: (MonadThrow m, MonadIO m) => TaskInputFile -> m (TaskSettings k) readTask (TaskInputFile path) = liftIO $ BS.readFile path >>= decodeThrow writeTask :: TaskInputFile -> TaskSettings k -> IO () writeTask (TaskInputFile path) taskInput = do let cfg = Y.setConfCompare (fieldOrder taskInput) Y.defConfig let yaml = Y.encodePretty cfg taskInput createDirectoryIfMissing True $ takeDirectory path BS.writeFile path yaml readCompTracksQuietly :: (MonadIO m, MonadThrow m) => ScoringInputFiles -> m ((CompSettings k, [TaskSettings k]), ([[PilotTrackLogFile]], [TaskFolder])) readCompTracksQuietly files = do settings@(_, tss) <- readCompAndTasksQuietly files return (settings, ([pilots | TaskSettings{pilots} <- tss], taskFolder <$> tss)) readCompTracks :: ScoringInputFiles -> IO ((CompSettings k, [TaskSettings k]), ([[PilotTrackLogFile]], [TaskFolder])) readCompTracks files = do settings@(_, tss) <- readCompAndTasks files return (settings, ([pilots | TaskSettings{pilots} <- tss], taskFolder <$> tss)) readCompAndTasksQuietly :: (MonadIO m, MonadThrow m) => ScoringInputFiles -> m (CompSettings k, [TaskSettings k]) readCompAndTasksQuietly (compFile, taskFiles) = do settingsComp <- readComp compFile settingsTasks <- sequence [readTask taskFile | taskFile <- taskFiles ] return (settingsComp, settingsTasks) readCompAndTasks :: ScoringInputFiles -> IO (CompSettings k, [TaskSettings k]) readCompAndTasks (compFile, taskFiles) = do putStrLn $ "Reading comp inputs from " ++ show compFile settingsComp <- readComp compFile putStrLn "Reading task inputs from:" settingsTasks <- parallel [ do putStrLn $ "\t" ++ show taskFile readTask taskFile | taskFile <- taskFiles ] return (settingsComp, settingsTasks) writeCompAndTasks :: ScoringInputFiles -> (CompSettings k, [TaskSettings k]) -> IO () writeCompAndTasks (compFile, taskFiles) (comp, tasks) = do putStrLn $ "Writing comp inputs to " ++ show compFile writeComp compFile comp putStrLn "Writing task inputs to:" parallel_ [ do putStrLn $ "\t" ++ show taskFile writeTask taskFile taskSetting | taskSetting <- tasks | taskFile <- taskFiles ]
null
https://raw.githubusercontent.com/GlideAngle/flare-timing/27bd34c1943496987382091441a1c2516c169263/lang-haskell/scribe/library/Flight/CompInput.hs
haskell
module Flight.CompInput ( readComp, writeComp , readTask, writeTask , readCompAndTasks, readCompAndTasksQuietly, writeCompAndTasks , readCompTracks, readCompTracksQuietly ) where import System.FilePath (takeDirectory) import System.Directory (createDirectoryIfMissing) import Control.Exception.Safe (MonadThrow) import Control.Monad.Except (MonadIO, liftIO) import qualified Data.ByteString as BS import Data.Yaml (decodeThrow) import qualified Data.Yaml.Pretty as Y import Control.Concurrent.ParallelIO (parallel, parallel_) import Flight.Field (FieldOrdering(..)) import Flight.Comp ( ScoringInputFiles, CompInputFile(..), TaskInputFile(..) , CompSettings(..), TaskSettings(..) , PilotTrackLogFile(..), TaskFolder(..) ) readComp :: (MonadThrow m, MonadIO m) => CompInputFile -> m (CompSettings k) readComp (CompInputFile path) = liftIO $ BS.readFile path >>= decodeThrow writeComp :: CompInputFile -> CompSettings k -> IO () writeComp (CompInputFile path) compInput = do let cfg = Y.setConfCompare (fieldOrder compInput) Y.defConfig let yaml = Y.encodePretty cfg compInput BS.writeFile path yaml readTask :: (MonadThrow m, MonadIO m) => TaskInputFile -> m (TaskSettings k) readTask (TaskInputFile path) = liftIO $ BS.readFile path >>= decodeThrow writeTask :: TaskInputFile -> TaskSettings k -> IO () writeTask (TaskInputFile path) taskInput = do let cfg = Y.setConfCompare (fieldOrder taskInput) Y.defConfig let yaml = Y.encodePretty cfg taskInput createDirectoryIfMissing True $ takeDirectory path BS.writeFile path yaml readCompTracksQuietly :: (MonadIO m, MonadThrow m) => ScoringInputFiles -> m ((CompSettings k, [TaskSettings k]), ([[PilotTrackLogFile]], [TaskFolder])) readCompTracksQuietly files = do settings@(_, tss) <- readCompAndTasksQuietly files return (settings, ([pilots | TaskSettings{pilots} <- tss], taskFolder <$> tss)) readCompTracks :: ScoringInputFiles -> IO ((CompSettings k, [TaskSettings k]), ([[PilotTrackLogFile]], [TaskFolder])) readCompTracks files = do settings@(_, tss) <- readCompAndTasks files return (settings, ([pilots | TaskSettings{pilots} <- tss], taskFolder <$> tss)) readCompAndTasksQuietly :: (MonadIO m, MonadThrow m) => ScoringInputFiles -> m (CompSettings k, [TaskSettings k]) readCompAndTasksQuietly (compFile, taskFiles) = do settingsComp <- readComp compFile settingsTasks <- sequence [readTask taskFile | taskFile <- taskFiles ] return (settingsComp, settingsTasks) readCompAndTasks :: ScoringInputFiles -> IO (CompSettings k, [TaskSettings k]) readCompAndTasks (compFile, taskFiles) = do putStrLn $ "Reading comp inputs from " ++ show compFile settingsComp <- readComp compFile putStrLn "Reading task inputs from:" settingsTasks <- parallel [ do putStrLn $ "\t" ++ show taskFile readTask taskFile | taskFile <- taskFiles ] return (settingsComp, settingsTasks) writeCompAndTasks :: ScoringInputFiles -> (CompSettings k, [TaskSettings k]) -> IO () writeCompAndTasks (compFile, taskFiles) (comp, tasks) = do putStrLn $ "Writing comp inputs to " ++ show compFile writeComp compFile comp putStrLn "Writing task inputs to:" parallel_ [ do putStrLn $ "\t" ++ show taskFile writeTask taskFile taskSetting | taskSetting <- tasks | taskFile <- taskFiles ]
78955169a2c5550adb8f0b65fc9cc7c04c0b4cc8f82500be5e6164323e99a4e0
bmeurer/ocaml-experimental
bigarray.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) and , INRIA Rocquencourt (* *) Copyright 2000 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../../LICENSE. *) (* *) (***********************************************************************) $ Id$ * Large , multi - dimensional , numerical arrays . This module implements multi - dimensional arrays of integers and floating - point numbers , thereafter referred to as ` ` big arrays '' . The implementation allows efficient sharing of large numerical arrays between code and C or Fortran numerical libraries . Concerning the naming conventions , users of this module are encouraged to do [ open Bigarray ] in their source , then refer to array types and operations via short dot notation , e.g. [ Array1.t ] or [ Array2.sub ] . Big arrays support all the ad - hoc polymorphic operations : - comparisons ( [ =] , [ < > ] , [ < =] , etc , as well as { ! Pervasives.compare } ) ; - hashing ( module [ Hash ] ) ; - and structured input - output ( { ! Pervasives.output_value } and { ! Pervasives.input_value } , as well as the functions from the { ! Marshal } module ) . This module implements multi-dimensional arrays of integers and floating-point numbers, thereafter referred to as ``big arrays''. The implementation allows efficient sharing of large numerical arrays between Caml code and C or Fortran numerical libraries. Concerning the naming conventions, users of this module are encouraged to do [open Bigarray] in their source, then refer to array types and operations via short dot notation, e.g. [Array1.t] or [Array2.sub]. Big arrays support all the Caml ad-hoc polymorphic operations: - comparisons ([=], [<>], [<=], etc, as well as {!Pervasives.compare}); - hashing (module [Hash]); - and structured input-output ({!Pervasives.output_value} and {!Pervasives.input_value}, as well as the functions from the {!Marshal} module). *) * { 6 Element kinds } * Big arrays can contain elements of the following kinds : - IEEE single precision ( 32 bits ) floating - point numbers ( { ! Bigarray.float32_elt } ) , - IEEE double precision ( 64 bits ) floating - point numbers ( { ! Bigarray.float64_elt } ) , - IEEE single precision ( 2 * 32 bits ) floating - point complex numbers ( { ! Bigarray.complex32_elt } ) , - IEEE double precision ( 2 * 64 bits ) floating - point complex numbers ( { ! Bigarray.complex64_elt } ) , - 8 - bit integers ( signed or unsigned ) ( { ! Bigarray.int8_signed_elt } or { ! Bigarray.int8_unsigned_elt } ) , - 16 - bit integers ( signed or unsigned ) ( { ! Bigarray.int16_signed_elt } or { ! Bigarray.int16_unsigned_elt } ) , - Caml integers ( signed , 31 bits on 32 - bit architectures , 63 bits on 64 - bit architectures ) ( { ! } ) , - 32 - bit signed integer ( { ! Bigarray.int32_elt } ) , - 64 - bit signed integers ( { ! Bigarray.int64_elt } ) , - platform - native signed integers ( 32 bits on 32 - bit architectures , 64 bits on 64 - bit architectures ) ( { ! Bigarray.nativeint_elt } ) . Each element kind is represented at the type level by one of the abstract types defined below . - IEEE single precision (32 bits) floating-point numbers ({!Bigarray.float32_elt}), - IEEE double precision (64 bits) floating-point numbers ({!Bigarray.float64_elt}), - IEEE single precision (2 * 32 bits) floating-point complex numbers ({!Bigarray.complex32_elt}), - IEEE double precision (2 * 64 bits) floating-point complex numbers ({!Bigarray.complex64_elt}), - 8-bit integers (signed or unsigned) ({!Bigarray.int8_signed_elt} or {!Bigarray.int8_unsigned_elt}), - 16-bit integers (signed or unsigned) ({!Bigarray.int16_signed_elt} or {!Bigarray.int16_unsigned_elt}), - Caml integers (signed, 31 bits on 32-bit architectures, 63 bits on 64-bit architectures) ({!Bigarray.int_elt}), - 32-bit signed integer ({!Bigarray.int32_elt}), - 64-bit signed integers ({!Bigarray.int64_elt}), - platform-native signed integers (32 bits on 32-bit architectures, 64 bits on 64-bit architectures) ({!Bigarray.nativeint_elt}). Each element kind is represented at the type level by one of the abstract types defined below. *) type float32_elt type float64_elt type complex32_elt type complex64_elt type int8_signed_elt type int8_unsigned_elt type int16_signed_elt type int16_unsigned_elt type int_elt type int32_elt type int64_elt type nativeint_elt type ('a, 'b) kind * To each element kind is associated a type , which is the type of values that can be stored in the big array or read back from it . This type is not necessarily the same as the type of the array elements proper : for instance , a big array whose elements are of kind [ float32_elt ] contains 32 - bit single precision floats , but reading or writing one of its elements from uses the type [ float ] , which is 64 - bit double precision floats . The abstract type [ ( ' a , ' b ) kind ] captures this association of a type [ ' a ] for values read or written in the big array , and of an element kind [ ' b ] which represents the actual contents of the big array . The following predefined values of type [ kind ] list all possible associations of types with element kinds : the type of Caml values that can be stored in the big array or read back from it. This type is not necessarily the same as the type of the array elements proper: for instance, a big array whose elements are of kind [float32_elt] contains 32-bit single precision floats, but reading or writing one of its elements from Caml uses the Caml type [float], which is 64-bit double precision floats. The abstract type [('a, 'b) kind] captures this association of a Caml type ['a] for values read or written in the big array, and of an element kind ['b] which represents the actual contents of the big array. The following predefined values of type [kind] list all possible associations of Caml types with element kinds: *) val float32 : (float, float32_elt) kind (** See {!Bigarray.char}. *) val float64 : (float, float64_elt) kind (** See {!Bigarray.char}. *) val complex32 : (Complex.t, complex32_elt) kind (** See {!Bigarray.char}. *) val complex64 : (Complex.t, complex64_elt) kind (** See {!Bigarray.char}. *) val int8_signed : (int, int8_signed_elt) kind (** See {!Bigarray.char}. *) val int8_unsigned : (int, int8_unsigned_elt) kind (** See {!Bigarray.char}. *) val int16_signed : (int, int16_signed_elt) kind (** See {!Bigarray.char}. *) val int16_unsigned : (int, int16_unsigned_elt) kind (** See {!Bigarray.char}. *) val int : (int, int_elt) kind (** See {!Bigarray.char}. *) val int32 : (int32, int32_elt) kind (** See {!Bigarray.char}. *) val int64 : (int64, int64_elt) kind (** See {!Bigarray.char}. *) val nativeint : (nativeint, nativeint_elt) kind (** See {!Bigarray.char}. *) val char : (char, int8_unsigned_elt) kind * As shown by the types of the values above , big arrays of kind [ float32_elt ] and [ float64_elt ] are accessed using the type [ float ] . Big arrays of complex kinds [ complex32_elt ] , [ complex64_elt ] are accessed with the type { ! Complex.t } . Big arrays of integer kinds are accessed using the smallest integer type large enough to represent the array elements : [ int ] for 8- and 16 - bit integer bigarrays , as well as Caml - integer bigarrays ; [ int32 ] for 32 - bit integer bigarrays ; [ int64 ] for 64 - bit integer bigarrays ; and [ nativeint ] for platform - native integer bigarrays . Finally , big arrays of kind [ int8_unsigned_elt ] can also be accessed as arrays of characters instead of arrays of small integers , by using the kind value [ char ] instead of [ int8_unsigned ] . big arrays of kind [float32_elt] and [float64_elt] are accessed using the Caml type [float]. Big arrays of complex kinds [complex32_elt], [complex64_elt] are accessed with the Caml type {!Complex.t}. Big arrays of integer kinds are accessed using the smallest Caml integer type large enough to represent the array elements: [int] for 8- and 16-bit integer bigarrays, as well as Caml-integer bigarrays; [int32] for 32-bit integer bigarrays; [int64] for 64-bit integer bigarrays; and [nativeint] for platform-native integer bigarrays. Finally, big arrays of kind [int8_unsigned_elt] can also be accessed as arrays of characters instead of arrays of small integers, by using the kind value [char] instead of [int8_unsigned]. *) * { 6 Array layouts } type c_layout * See { ! } . type fortran_layout * To facilitate interoperability with existing C and Fortran code , this library supports two different memory layouts for big arrays , one compatible with the C conventions , the other compatible with the Fortran conventions . In the C - style layout , array indices start at 0 , and multi - dimensional arrays are laid out in row - major format . That is , for a two - dimensional array , all elements of row 0 are contiguous in memory , followed by all elements of row 1 , etc . In other terms , the array elements at [ ( x , y ) ] and [ ( x , y+1 ) ] are adjacent in memory . In the Fortran - style layout , array indices start at 1 , and multi - dimensional arrays are laid out in column - major format . That is , for a two - dimensional array , all elements of column 0 are contiguous in memory , followed by all elements of column 1 , etc . In other terms , the array elements at [ ( x , y ) ] and [ ( x+1 , y ) ] are adjacent in memory . Each layout style is identified at the type level by the abstract types { ! Bigarray.c_layout } and [ fortran_layout ] respectively . this library supports two different memory layouts for big arrays, one compatible with the C conventions, the other compatible with the Fortran conventions. In the C-style layout, array indices start at 0, and multi-dimensional arrays are laid out in row-major format. That is, for a two-dimensional array, all elements of row 0 are contiguous in memory, followed by all elements of row 1, etc. In other terms, the array elements at [(x,y)] and [(x, y+1)] are adjacent in memory. In the Fortran-style layout, array indices start at 1, and multi-dimensional arrays are laid out in column-major format. That is, for a two-dimensional array, all elements of column 0 are contiguous in memory, followed by all elements of column 1, etc. In other terms, the array elements at [(x,y)] and [(x+1, y)] are adjacent in memory. Each layout style is identified at the type level by the abstract types {!Bigarray.c_layout} and [fortran_layout] respectively. *) type 'a layout * The type [ ' a layout ] represents one of the two supported memory layouts : C - style if [ ' a ] is { ! Bigarray.c_layout } , Fortran - style if [ ' a ] is { ! } . memory layouts: C-style if ['a] is {!Bigarray.c_layout}, Fortran-style if ['a] is {!Bigarray.fortran_layout}. *) * { 7 Supported layouts } The abstract values [ c_layout ] and [ fortran_layout ] represent the two supported layouts at the level of values . The abstract values [c_layout] and [fortran_layout] represent the two supported layouts at the level of values. *) val c_layout : c_layout layout val fortran_layout : fortran_layout layout * { 6 Generic arrays ( of arbitrarily many dimensions ) } module Genarray : sig type ('a, 'b, 'c) t * The type [ Genarray.t ] is the type of big arrays with variable numbers of dimensions . Any number of dimensions between 1 and 16 is supported . The three type parameters to [ Genarray.t ] identify the array element kind and layout , as follows : - the first parameter , [ ' a ] , is the type for accessing array elements ( [ float ] , [ int ] , [ int32 ] , [ int64 ] , [ nativeint ] ) ; - the second parameter , [ ' b ] , is the actual kind of array elements ( [ float32_elt ] , [ float64_elt ] , [ int8_signed_elt ] , [ int8_unsigned_elt ] , etc ) ; - the third parameter , [ ' c ] , identifies the array layout ( [ c_layout ] or [ fortran_layout ] ) . For instance , [ ( float , float32_elt , fortran_layout ) Genarray.t ] is the type of generic big arrays containing 32 - bit floats in Fortran layout ; reads and writes in this array use the Caml type [ float ] . numbers of dimensions. Any number of dimensions between 1 and 16 is supported. The three type parameters to [Genarray.t] identify the array element kind and layout, as follows: - the first parameter, ['a], is the Caml type for accessing array elements ([float], [int], [int32], [int64], [nativeint]); - the second parameter, ['b], is the actual kind of array elements ([float32_elt], [float64_elt], [int8_signed_elt], [int8_unsigned_elt], etc); - the third parameter, ['c], identifies the array layout ([c_layout] or [fortran_layout]). For instance, [(float, float32_elt, fortran_layout) Genarray.t] is the type of generic big arrays containing 32-bit floats in Fortran layout; reads and writes in this array use the Caml type [float]. *) external create: ('a, 'b) kind -> 'c layout -> int array -> ('a, 'b, 'c) t = "caml_ba_create" * [ Genarray.create kind layout dimensions ] returns a new big array whose element kind is determined by the parameter [ kind ] ( one of [ float32 ] , [ float64 ] , [ int8_signed ] , etc ) and whose layout is determined by the parameter [ layout ] ( one of [ c_layout ] or [ fortran_layout ] ) . The [ dimensions ] parameter is an array of integers that indicate the size of the big array in each dimension . The length of [ dimensions ] determines the number of dimensions of the bigarray . For instance , [ Genarray.create int32 c_layout [ |4;6;8| ] ] returns a fresh big array of 32 - bit integers , in C layout , having three dimensions , the three dimensions being 4 , 6 and 8 respectively . Big arrays returned by [ Genarray.create ] are not initialized : the initial values of array elements is unspecified . [ Genarray.create ] raises [ Invalid_argument ] if the number of dimensions is not in the range 1 to 16 inclusive , or if one of the dimensions is negative . whose element kind is determined by the parameter [kind] (one of [float32], [float64], [int8_signed], etc) and whose layout is determined by the parameter [layout] (one of [c_layout] or [fortran_layout]). The [dimensions] parameter is an array of integers that indicate the size of the big array in each dimension. The length of [dimensions] determines the number of dimensions of the bigarray. For instance, [Genarray.create int32 c_layout [|4;6;8|]] returns a fresh big array of 32-bit integers, in C layout, having three dimensions, the three dimensions being 4, 6 and 8 respectively. Big arrays returned by [Genarray.create] are not initialized: the initial values of array elements is unspecified. [Genarray.create] raises [Invalid_argument] if the number of dimensions is not in the range 1 to 16 inclusive, or if one of the dimensions is negative. *) external num_dims: ('a, 'b, 'c) t -> int = "caml_ba_num_dims" (** Return the number of dimensions of the given big array. *) val dims : ('a, 'b, 'c) t -> int array (** [Genarray.dims a] returns all dimensions of the big array [a], as an array of integers of length [Genarray.num_dims a]. *) external nth_dim: ('a, 'b, 'c) t -> int -> int = "caml_ba_dim" * [ Genarray.nth_dim a n ] returns the [ n]-th dimension of the big array [ a ] . The first dimension corresponds to [ n = 0 ] ; the second dimension corresponds to [ n = 1 ] ; the last dimension , to [ n = Genarray.num_dims a - 1 ] . Raise [ Invalid_argument ] if [ n ] is less than 0 or greater or equal than [ Genarray.num_dims a ] . big array [a]. The first dimension corresponds to [n = 0]; the second dimension corresponds to [n = 1]; the last dimension, to [n = Genarray.num_dims a - 1]. Raise [Invalid_argument] if [n] is less than 0 or greater or equal than [Genarray.num_dims a]. *) external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind" (** Return the kind of the given big array. *) external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout" (** Return the layout of the given big array. *) external get: ('a, 'b, 'c) t -> int array -> 'a = "caml_ba_get_generic" * Read an element of a generic big array . [ Genarray.get a [ |i1 ; ... ; iN| ] ] returns the element of [ a ] whose coordinates are [ i1 ] in the first dimension , [ i2 ] in the second dimension , ... , [ iN ] in the [ N]-th dimension . If [ a ] has C layout , the coordinates must be greater or equal than 0 and strictly less than the corresponding dimensions of [ a ] . If [ a ] has Fortran layout , the coordinates must be greater or equal than 1 and less or equal than the corresponding dimensions of [ a ] . Raise [ Invalid_argument ] if the array [ a ] does not have exactly [ N ] dimensions , or if the coordinates are outside the array bounds . If [ N > 3 ] , alternate syntax is provided : you can write [ a.{i1 , i2 , ... , iN } ] instead of [ Genarray.get a [ |i1 ; ... ; iN| ] ] . ( The syntax [ a. { ... } ] with one , two or three coordinates is reserved for accessing one- , two- and three - dimensional arrays as described below . ) [Genarray.get a [|i1; ...; iN|]] returns the element of [a] whose coordinates are [i1] in the first dimension, [i2] in the second dimension, ..., [iN] in the [N]-th dimension. If [a] has C layout, the coordinates must be greater or equal than 0 and strictly less than the corresponding dimensions of [a]. If [a] has Fortran layout, the coordinates must be greater or equal than 1 and less or equal than the corresponding dimensions of [a]. Raise [Invalid_argument] if the array [a] does not have exactly [N] dimensions, or if the coordinates are outside the array bounds. If [N > 3], alternate syntax is provided: you can write [a.{i1, i2, ..., iN}] instead of [Genarray.get a [|i1; ...; iN|]]. (The syntax [a.{...}] with one, two or three coordinates is reserved for accessing one-, two- and three-dimensional arrays as described below.) *) external set: ('a, 'b, 'c) t -> int array -> 'a -> unit = "caml_ba_set_generic" * Assign an element of a generic big array . [ Genarray.set a [ |i1 ; ... ; iN| ] v ] stores the value [ v ] in the element of [ a ] whose coordinates are [ i1 ] in the first dimension , [ i2 ] in the second dimension , ... , [ iN ] in the [ N]-th dimension . The array [ a ] must have exactly [ N ] dimensions , and all coordinates must lie inside the array bounds , as described for [ Genarray.get ] ; otherwise , [ Invalid_argument ] is raised . If [ N > 3 ] , alternate syntax is provided : you can write [ a.{i1 , i2 , ... , iN } < - v ] instead of [ Genarray.set a [ |i1 ; ... ; iN| ] v ] . ( The syntax [ a. { ... } < - v ] with one , two or three coordinates is reserved for updating one- , two- and three - dimensional arrays as described below . ) [Genarray.set a [|i1; ...; iN|] v] stores the value [v] in the element of [a] whose coordinates are [i1] in the first dimension, [i2] in the second dimension, ..., [iN] in the [N]-th dimension. The array [a] must have exactly [N] dimensions, and all coordinates must lie inside the array bounds, as described for [Genarray.get]; otherwise, [Invalid_argument] is raised. If [N > 3], alternate syntax is provided: you can write [a.{i1, i2, ..., iN} <- v] instead of [Genarray.set a [|i1; ...; iN|] v]. (The syntax [a.{...} <- v] with one, two or three coordinates is reserved for updating one-, two- and three-dimensional arrays as described below.) *) external sub_left: ('a, 'b, c_layout) t -> int -> int -> ('a, 'b, c_layout) t = "caml_ba_sub" * Extract a sub - array of the given big array by restricting the first ( left - most ) dimension . [ Genarray.sub_left a ofs len ] returns a big array with the same number of dimensions as [ a ] , and the same dimensions as [ a ] , except the first dimension , which corresponds to the interval [ [ ofs ... ofs + len - 1 ] ] of the first dimension of [ a ] . No copying of elements is involved : the sub - array and the original array share the same storage space . In other terms , the element at coordinates [ [ |i1 ; ... ; iN| ] ] of the sub - array is identical to the element at coordinates [ [ |i1+ofs ; ... ; iN| ] ] of the original array [ a ] . [ Genarray.sub_left ] applies only to big arrays in C layout . Raise [ Invalid_argument ] if [ ofs ] and [ len ] do not designate a valid sub - array of [ a ] , that is , if [ ofs < 0 ] , or [ len < 0 ] , or > Genarray.nth_dim a 0 ] . first (left-most) dimension. [Genarray.sub_left a ofs len] returns a big array with the same number of dimensions as [a], and the same dimensions as [a], except the first dimension, which corresponds to the interval [[ofs ... ofs + len - 1]] of the first dimension of [a]. No copying of elements is involved: the sub-array and the original array share the same storage space. In other terms, the element at coordinates [[|i1; ...; iN|]] of the sub-array is identical to the element at coordinates [[|i1+ofs; ...; iN|]] of the original array [a]. [Genarray.sub_left] applies only to big arrays in C layout. Raise [Invalid_argument] if [ofs] and [len] do not designate a valid sub-array of [a], that is, if [ofs < 0], or [len < 0], or [ofs + len > Genarray.nth_dim a 0]. *) external sub_right: ('a, 'b, fortran_layout) t -> int -> int -> ('a, 'b, fortran_layout) t = "caml_ba_sub" * Extract a sub - array of the given big array by restricting the last ( right - most ) dimension . [ Genarray.sub_right a ofs len ] returns a big array with the same number of dimensions as [ a ] , and the same dimensions as [ a ] , except the last dimension , which corresponds to the interval [ [ ofs ... ofs + len - 1 ] ] of the last dimension of [ a ] . No copying of elements is involved : the sub - array and the original array share the same storage space . In other terms , the element at coordinates [ [ |i1 ; ... ; iN| ] ] of the sub - array is identical to the element at coordinates [ [ |i1 ; ... ; iN+ofs| ] ] of the original array [ a ] . [ Genarray.sub_right ] applies only to big arrays in Fortran layout . Raise [ Invalid_argument ] if [ ofs ] and [ len ] do not designate a valid sub - array of [ a ] , that is , if [ ofs < 1 ] , or [ len < 0 ] , or > Genarray.nth_dim a ( Genarray.num_dims a - 1 ) ] . last (right-most) dimension. [Genarray.sub_right a ofs len] returns a big array with the same number of dimensions as [a], and the same dimensions as [a], except the last dimension, which corresponds to the interval [[ofs ... ofs + len - 1]] of the last dimension of [a]. No copying of elements is involved: the sub-array and the original array share the same storage space. In other terms, the element at coordinates [[|i1; ...; iN|]] of the sub-array is identical to the element at coordinates [[|i1; ...; iN+ofs|]] of the original array [a]. [Genarray.sub_right] applies only to big arrays in Fortran layout. Raise [Invalid_argument] if [ofs] and [len] do not designate a valid sub-array of [a], that is, if [ofs < 1], or [len < 0], or [ofs + len > Genarray.nth_dim a (Genarray.num_dims a - 1)]. *) external slice_left: ('a, 'b, c_layout) t -> int array -> ('a, 'b, c_layout) t = "caml_ba_slice" * Extract a sub - array of lower dimension from the given big array by fixing one or several of the first ( left - most ) coordinates . [ a [ |i1 ; ... ; iM| ] ] returns the ` ` slice '' of [ a ] obtained by setting the first [ M ] coordinates to [ i1 ] , ... , [ iM ] . If [ a ] has [ N ] dimensions , the slice has dimension [ N - M ] , and the element at coordinates [ [ |j1 ; ... ; ] ] in the slice is identical to the element at coordinates [ [ |i1 ; ... ; iM ; j1 ; ... ; ] ] in the original array [ a ] . No copying of elements is involved : the slice and the original array share the same storage space . [ ] applies only to big arrays in C layout . Raise [ Invalid_argument ] if [ M > = N ] , or if [ [ |i1 ; ... ; iM| ] ] is outside the bounds of [ a ] . by fixing one or several of the first (left-most) coordinates. [Genarray.slice_left a [|i1; ... ; iM|]] returns the ``slice'' of [a] obtained by setting the first [M] coordinates to [i1], ..., [iM]. If [a] has [N] dimensions, the slice has dimension [N - M], and the element at coordinates [[|j1; ...; j(N-M)|]] in the slice is identical to the element at coordinates [[|i1; ...; iM; j1; ...; j(N-M)|]] in the original array [a]. No copying of elements is involved: the slice and the original array share the same storage space. [Genarray.slice_left] applies only to big arrays in C layout. Raise [Invalid_argument] if [M >= N], or if [[|i1; ... ; iM|]] is outside the bounds of [a]. *) external slice_right: ('a, 'b, fortran_layout) t -> int array -> ('a, 'b, fortran_layout) t = "caml_ba_slice" * Extract a sub - array of lower dimension from the given big array by fixing one or several of the last ( right - most ) coordinates . [ Genarray.slice_right a [ |i1 ; ... ; iM| ] ] returns the ` ` slice '' of [ a ] obtained by setting the last [ M ] coordinates to [ i1 ] , ... , [ iM ] . If [ a ] has [ N ] dimensions , the slice has dimension [ N - M ] , and the element at coordinates [ [ |j1 ; ... ; ] ] in the slice is identical to the element at coordinates [ [ |j1 ; ... ; ) ; i1 ; ... ; iM| ] ] in the original array [ a ] . No copying of elements is involved : the slice and the original array share the same storage space . [ Genarray.slice_right ] applies only to big arrays in Fortran layout . Raise [ Invalid_argument ] if [ M > = N ] , or if [ [ |i1 ; ... ; iM| ] ] is outside the bounds of [ a ] . by fixing one or several of the last (right-most) coordinates. [Genarray.slice_right a [|i1; ... ; iM|]] returns the ``slice'' of [a] obtained by setting the last [M] coordinates to [i1], ..., [iM]. If [a] has [N] dimensions, the slice has dimension [N - M], and the element at coordinates [[|j1; ...; j(N-M)|]] in the slice is identical to the element at coordinates [[|j1; ...; j(N-M); i1; ...; iM|]] in the original array [a]. No copying of elements is involved: the slice and the original array share the same storage space. [Genarray.slice_right] applies only to big arrays in Fortran layout. Raise [Invalid_argument] if [M >= N], or if [[|i1; ... ; iM|]] is outside the bounds of [a]. *) external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit = "caml_ba_blit" * Copy all elements of a big array in another big array . [ Genarray.blit ] copies all elements of [ src ] into [ dst ] . Both arrays [ src ] and [ dst ] must have the same number of dimensions and equal dimensions . Copying a sub - array of [ src ] to a sub - array of [ dst ] can be achieved by applying [ Genarray.blit ] to sub - array or slices of [ src ] and [ dst ] . [Genarray.blit src dst] copies all elements of [src] into [dst]. Both arrays [src] and [dst] must have the same number of dimensions and equal dimensions. Copying a sub-array of [src] to a sub-array of [dst] can be achieved by applying [Genarray.blit] to sub-array or slices of [src] and [dst]. *) external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill" (** Set all elements of a big array to a given value. [Genarray.fill a v] stores the value [v] in all elements of the big array [a]. Setting only some elements of [a] to [v] can be achieved by applying [Genarray.fill] to a sub-array or a slice of [a]. *) val map_file: Unix.file_descr -> ?pos:int64 -> ('a, 'b) kind -> 'c layout -> bool -> int array -> ('a, 'b, 'c) t * Memory mapping of a file as a big array . [ Genarray.map_file fd kind layout shared dims ] returns a big array of kind [ kind ] , layout [ layout ] , and dimensions as specified in [ dims ] . The data contained in this big array are the contents of the file referred to by the file descriptor [ fd ] ( as opened previously with [ Unix.openfile ] , for example ) . The optional [ pos ] parameter is the byte offset in the file of the data being mapped ; it defaults to 0 ( map from the beginning of the file ) . If [ shared ] is [ true ] , all modifications performed on the array are reflected in the file . This requires that [ fd ] be opened with write permissions . If [ shared ] is [ false ] , modifications performed on the array are done in memory only , using copy - on - write of the modified pages ; the underlying file is not affected . [ Genarray.map_file ] is much more efficient than reading the whole file in a big array , modifying that big array , and writing it afterwards . To adjust automatically the dimensions of the big array to the actual size of the file , the major dimension ( that is , the first dimension for an array with C layout , and the last dimension for an array with Fortran layout ) can be given as [ -1 ] . [ Genarray.map_file ] then determines the major dimension from the size of the file . The file must contain an integral number of sub - arrays as determined by the non - major dimensions , otherwise [ Failure ] is raised . If all dimensions of the big array are given , the file size is matched against the size of the big array . If the file is larger than the big array , only the initial portion of the file is mapped to the big array . If the file is smaller than the big array , the file is automatically grown to the size of the big array . This requires write permissions on [ fd ] . [Genarray.map_file fd kind layout shared dims] returns a big array of kind [kind], layout [layout], and dimensions as specified in [dims]. The data contained in this big array are the contents of the file referred to by the file descriptor [fd] (as opened previously with [Unix.openfile], for example). The optional [pos] parameter is the byte offset in the file of the data being mapped; it defaults to 0 (map from the beginning of the file). If [shared] is [true], all modifications performed on the array are reflected in the file. This requires that [fd] be opened with write permissions. If [shared] is [false], modifications performed on the array are done in memory only, using copy-on-write of the modified pages; the underlying file is not affected. [Genarray.map_file] is much more efficient than reading the whole file in a big array, modifying that big array, and writing it afterwards. To adjust automatically the dimensions of the big array to the actual size of the file, the major dimension (that is, the first dimension for an array with C layout, and the last dimension for an array with Fortran layout) can be given as [-1]. [Genarray.map_file] then determines the major dimension from the size of the file. The file must contain an integral number of sub-arrays as determined by the non-major dimensions, otherwise [Failure] is raised. If all dimensions of the big array are given, the file size is matched against the size of the big array. If the file is larger than the big array, only the initial portion of the file is mapped to the big array. If the file is smaller than the big array, the file is automatically grown to the size of the big array. This requires write permissions on [fd]. *) end * { 6 One - dimensional arrays } * One - dimensional arrays . The [ Array1 ] structure provides operations similar to those of { ! . Genarray } , but specialized to the case of one - dimensional arrays . ( The [ Array2 ] and [ Array3 ] structures below provide operations specialized for two- and three - dimensional arrays . ) Statically knowing the number of dimensions of the array allows faster operations , and more precise static type - checking . similar to those of {!Bigarray.Genarray}, but specialized to the case of one-dimensional arrays. (The [Array2] and [Array3] structures below provide operations specialized for two- and three-dimensional arrays.) Statically knowing the number of dimensions of the array allows faster operations, and more precise static type-checking. *) module Array1 : sig type ('a, 'b, 'c) t * The type of one - dimensional big arrays whose elements have type [ ' a ] , representation kind [ ' b ] , and memory layout [ ' c ] . Caml type ['a], representation kind ['b], and memory layout ['c]. *) val create: ('a, 'b) kind -> 'c layout -> int -> ('a, 'b, 'c) t * [ Array1.create kind layout dim ] returns a new bigarray of one dimension , whose size is [ dim ] . [ kind ] and [ layout ] determine the array element kind and the array layout as described for [ Genarray.create ] . one dimension, whose size is [dim]. [kind] and [layout] determine the array element kind and the array layout as described for [Genarray.create]. *) val dim: ('a, 'b, 'c) t -> int * Return the size ( dimension ) of the given one - dimensional big array . big array. *) external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind" (** Return the kind of the given big array. *) external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout" (** Return the layout of the given big array. *) external get: ('a, 'b, 'c) t -> int -> 'a = "%caml_ba_ref_1" * [ Array1.get a x ] , or alternatively [ a.{x } ] , returns the element of [ a ] at index [ x ] . [ x ] must be greater or equal than [ 0 ] and strictly less than [ Array1.dim a ] if [ a ] has C layout . If [ a ] has Fortran layout , [ x ] must be greater or equal than [ 1 ] and less or equal than [ Array1.dim a ] . Otherwise , [ Invalid_argument ] is raised . returns the element of [a] at index [x]. [x] must be greater or equal than [0] and strictly less than [Array1.dim a] if [a] has C layout. If [a] has Fortran layout, [x] must be greater or equal than [1] and less or equal than [Array1.dim a]. Otherwise, [Invalid_argument] is raised. *) external set: ('a, 'b, 'c) t -> int -> 'a -> unit = "%caml_ba_set_1" (** [Array1.set a x v], also written [a.{x} <- v], stores the value [v] at index [x] in [a]. [x] must be inside the bounds of [a] as described in {!Bigarray.Array1.get}; otherwise, [Invalid_argument] is raised. *) external sub: ('a, 'b, 'c) t -> int -> int -> ('a, 'b, 'c) t = "caml_ba_sub" * Extract a sub - array of the given one - dimensional big array . See [ Genarray.sub_left ] for more details . See [Genarray.sub_left] for more details. *) external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit = "caml_ba_blit" * Copy the first big array to the second big array . See [ Genarray.blit ] for more details . See [Genarray.blit] for more details. *) external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill" (** Fill the given big array with the given value. See [Genarray.fill] for more details. *) val of_array: ('a, 'b) kind -> 'c layout -> 'a array -> ('a, 'b, 'c) t * Build a one - dimensional big array initialized from the given array . given array. *) val map_file: Unix.file_descr -> ?pos:int64 -> ('a, 'b) kind -> 'c layout -> bool -> int -> ('a, 'b, 'c) t * Memory mapping of a file as a one - dimensional big array . See { ! . Genarray.map_file } for more details . See {!Bigarray.Genarray.map_file} for more details. *) external unsafe_get: ('a, 'b, 'c) t -> int -> 'a = "%caml_ba_unsafe_ref_1" (** Like {!Bigarray.Array1.get}, but bounds checking is not always performed. Use with caution and only when the program logic guarantees that the access is within bounds. *) external unsafe_set: ('a, 'b, 'c) t -> int -> 'a -> unit = "%caml_ba_unsafe_set_1" (** Like {!Bigarray.Array1.set}, but bounds checking is not always performed. Use with caution and only when the program logic guarantees that the access is within bounds. *) end * { 6 Two - dimensional arrays } * Two - dimensional arrays . The [ Array2 ] structure provides operations similar to those of { ! . Genarray } , but specialized to the case of two - dimensional arrays . similar to those of {!Bigarray.Genarray}, but specialized to the case of two-dimensional arrays. *) module Array2 : sig type ('a, 'b, 'c) t * The type of two - dimensional big arrays whose elements have type [ ' a ] , representation kind [ ' b ] , and memory layout [ ' c ] . Caml type ['a], representation kind ['b], and memory layout ['c]. *) val create: ('a, 'b) kind -> 'c layout -> int -> int -> ('a, 'b, 'c) t * [ Array2.create kind layout dim1 dim2 ] returns a new bigarray of two dimension , whose size is [ dim1 ] in the first dimension and [ dim2 ] in the second dimension . [ kind ] and [ layout ] determine the array element kind and the array layout as described for { ! Bigarray.Genarray.create } . two dimension, whose size is [dim1] in the first dimension and [dim2] in the second dimension. [kind] and [layout] determine the array element kind and the array layout as described for {!Bigarray.Genarray.create}. *) val dim1: ('a, 'b, 'c) t -> int * Return the first dimension of the given two - dimensional big array . val dim2: ('a, 'b, 'c) t -> int * Return the second dimension of the given two - dimensional big array . external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind" (** Return the kind of the given big array. *) external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout" (** Return the layout of the given big array. *) external get: ('a, 'b, 'c) t -> int -> int -> 'a = "%caml_ba_ref_2" (** [Array2.get a x y], also written [a.{x,y}], returns the element of [a] at coordinates ([x], [y]). [x] and [y] must be within the bounds of [a], as described for {!Bigarray.Genarray.get}; otherwise, [Invalid_argument] is raised. *) external set: ('a, 'b, 'c) t -> int -> int -> 'a -> unit = "%caml_ba_set_2" * [ Array2.set a x y v ] , or alternatively [ a.{x , y } < - v ] , stores the value [ v ] at coordinates ( [ x ] , [ y ] ) in [ a ] . [ x ] and [ y ] must be within the bounds of [ a ] , as described for { ! Bigarray.Genarray.set } ; otherwise , [ Invalid_argument ] is raised . stores the value [v] at coordinates ([x], [y]) in [a]. [x] and [y] must be within the bounds of [a], as described for {!Bigarray.Genarray.set}; otherwise, [Invalid_argument] is raised. *) external sub_left: ('a, 'b, c_layout) t -> int -> int -> ('a, 'b, c_layout) t = "caml_ba_sub" * Extract a two - dimensional sub - array of the given two - dimensional big array by restricting the first dimension . See { ! . Genarray.sub_left } for more details . [ ] applies only to arrays with C layout . big array by restricting the first dimension. See {!Bigarray.Genarray.sub_left} for more details. [Array2.sub_left] applies only to arrays with C layout. *) external sub_right: ('a, 'b, fortran_layout) t -> int -> int -> ('a, 'b, fortran_layout) t = "caml_ba_sub" * Extract a two - dimensional sub - array of the given two - dimensional big array by restricting the second dimension . See { ! Bigarray . } for more details . [ Array2.sub_right ] applies only to arrays with Fortran layout . big array by restricting the second dimension. See {!Bigarray.Genarray.sub_right} for more details. [Array2.sub_right] applies only to arrays with Fortran layout. *) val slice_left: ('a, 'b, c_layout) t -> int -> ('a, 'b, c_layout) Array1.t * Extract a row ( one - dimensional slice ) of the given two - dimensional big array . The integer parameter is the index of the row to extract . See { ! . } for more details . [ Array2.slice_left ] applies only to arrays with C layout . big array. The integer parameter is the index of the row to extract. See {!Bigarray.Genarray.slice_left} for more details. [Array2.slice_left] applies only to arrays with C layout. *) val slice_right: ('a, 'b, fortran_layout) t -> int -> ('a, 'b, fortran_layout) Array1.t * Extract a column ( one - dimensional slice ) of the given two - dimensional big array . The integer parameter is the index of the column to extract . See { ! . Genarray.slice_right } for more details . [ Array2.slice_right ] applies only to arrays with Fortran layout . two-dimensional big array. The integer parameter is the index of the column to extract. See {!Bigarray.Genarray.slice_right} for more details. [Array2.slice_right] applies only to arrays with Fortran layout. *) external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit = "caml_ba_blit" * Copy the first big array to the second big array . See { ! } for more details . See {!Bigarray.Genarray.blit} for more details. *) external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill" * Fill the given big array with the given value . See { ! } for more details . See {!Bigarray.Genarray.fill} for more details. *) val of_array: ('a, 'b) kind -> 'c layout -> 'a array array -> ('a, 'b, 'c) t * Build a two - dimensional big array initialized from the given array of arrays . given array of arrays. *) val map_file: Unix.file_descr -> ?pos:int64 -> ('a, 'b) kind -> 'c layout -> bool -> int -> int -> ('a, 'b, 'c) t * Memory mapping of a file as a two - dimensional big array . See { ! . Genarray.map_file } for more details . See {!Bigarray.Genarray.map_file} for more details. *) external unsafe_get: ('a, 'b, 'c) t -> int -> int -> 'a = "%caml_ba_unsafe_ref_2" (** Like {!Bigarray.Array2.get}, but bounds checking is not always performed. *) external unsafe_set: ('a, 'b, 'c) t -> int -> int -> 'a -> unit = "%caml_ba_unsafe_set_2" (** Like {!Bigarray.Array2.set}, but bounds checking is not always performed. *) end * { 6 Three - dimensional arrays } * Three - dimensional arrays . The [ Array3 ] structure provides operations similar to those of { ! . Genarray } , but specialized to the case of three - dimensional arrays . similar to those of {!Bigarray.Genarray}, but specialized to the case of three-dimensional arrays. *) module Array3 : sig type ('a, 'b, 'c) t * The type of three - dimensional big arrays whose elements have type [ ' a ] , representation kind [ ' b ] , and memory layout [ ' c ] . Caml type ['a], representation kind ['b], and memory layout ['c]. *) val create: ('a, 'b) kind -> 'c layout -> int -> int -> int -> ('a, 'b, 'c) t * [ Array3.create kind layout dim1 dim2 dim3 ] returns a new bigarray of three dimension , whose size is [ dim1 ] in the first dimension , [ dim2 ] in the second dimension , and [ dim3 ] in the third . [ kind ] and [ layout ] determine the array element kind and the array layout as described for { ! Bigarray.Genarray.create } . three dimension, whose size is [dim1] in the first dimension, [dim2] in the second dimension, and [dim3] in the third. [kind] and [layout] determine the array element kind and the array layout as described for {!Bigarray.Genarray.create}. *) val dim1: ('a, 'b, 'c) t -> int * Return the first dimension of the given three - dimensional big array . val dim2: ('a, 'b, 'c) t -> int * Return the second dimension of the given three - dimensional big array . val dim3: ('a, 'b, 'c) t -> int * Return the third dimension of the given three - dimensional big array . external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind" (** Return the kind of the given big array. *) external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout" (** Return the layout of the given big array. *) external get: ('a, 'b, 'c) t -> int -> int -> int -> 'a = "%caml_ba_ref_3" (** [Array3.get a x y z], also written [a.{x,y,z}], returns the element of [a] at coordinates ([x], [y], [z]). [x], [y] and [z] must be within the bounds of [a], as described for {!Bigarray.Genarray.get}; otherwise, [Invalid_argument] is raised. *) external set: ('a, 'b, 'c) t -> int -> int -> int -> 'a -> unit = "%caml_ba_set_3" (** [Array3.set a x y v], or alternatively [a.{x,y,z} <- v], stores the value [v] at coordinates ([x], [y], [z]) in [a]. [x], [y] and [z] must be within the bounds of [a], as described for {!Bigarray.Genarray.set}; otherwise, [Invalid_argument] is raised. *) external sub_left: ('a, 'b, c_layout) t -> int -> int -> ('a, 'b, c_layout) t = "caml_ba_sub" * Extract a three - dimensional sub - array of the given three - dimensional big array by restricting the first dimension . See { ! . Genarray.sub_left } for more details . [ Array3.sub_left ] applies only to arrays with C layout . three-dimensional big array by restricting the first dimension. See {!Bigarray.Genarray.sub_left} for more details. [Array3.sub_left] applies only to arrays with C layout. *) external sub_right: ('a, 'b, fortran_layout) t -> int -> int -> ('a, 'b, fortran_layout) t = "caml_ba_sub" * Extract a three - dimensional sub - array of the given three - dimensional big array by restricting the second dimension . See { ! Bigarray . } for more details . [ Array3.sub_right ] applies only to arrays with Fortran layout . three-dimensional big array by restricting the second dimension. See {!Bigarray.Genarray.sub_right} for more details. [Array3.sub_right] applies only to arrays with Fortran layout. *) val slice_left_1: ('a, 'b, c_layout) t -> int -> int -> ('a, 'b, c_layout) Array1.t * Extract a one - dimensional slice of the given three - dimensional big array by fixing the first two coordinates . The integer parameters are the coordinates of the slice to extract . See { ! . } for more details . [ Array3.slice_left_1 ] applies only to arrays with C layout . big array by fixing the first two coordinates. The integer parameters are the coordinates of the slice to extract. See {!Bigarray.Genarray.slice_left} for more details. [Array3.slice_left_1] applies only to arrays with C layout. *) val slice_right_1: ('a, 'b, fortran_layout) t -> int -> int -> ('a, 'b, fortran_layout) Array1.t * Extract a one - dimensional slice of the given three - dimensional big array by fixing the last two coordinates . The integer parameters are the coordinates of the slice to extract . See { ! . Genarray.slice_right } for more details . [ Array3.slice_right_1 ] applies only to arrays with Fortran layout . big array by fixing the last two coordinates. The integer parameters are the coordinates of the slice to extract. See {!Bigarray.Genarray.slice_right} for more details. [Array3.slice_right_1] applies only to arrays with Fortran layout. *) val slice_left_2: ('a, 'b, c_layout) t -> int -> ('a, 'b, c_layout) Array2.t * Extract a two - dimensional slice of the given three - dimensional big array by fixing the first coordinate . The integer parameter is the first coordinate of the slice to extract . See { ! . } for more details . [ Array3.slice_left_2 ] applies only to arrays with C layout . big array by fixing the first coordinate. The integer parameter is the first coordinate of the slice to extract. See {!Bigarray.Genarray.slice_left} for more details. [Array3.slice_left_2] applies only to arrays with C layout. *) val slice_right_2: ('a, 'b, fortran_layout) t -> int -> ('a, 'b, fortran_layout) Array2.t * Extract a two - dimensional slice of the given three - dimensional big array by fixing the last coordinate . The integer parameter is the coordinate of the slice to extract . See { ! . Genarray.slice_right } for more details . [ Array3.slice_right_2 ] applies only to arrays with Fortran layout . three-dimensional big array by fixing the last coordinate. The integer parameter is the coordinate of the slice to extract. See {!Bigarray.Genarray.slice_right} for more details. [Array3.slice_right_2] applies only to arrays with Fortran layout. *) external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit = "caml_ba_blit" * Copy the first big array to the second big array . See { ! } for more details . See {!Bigarray.Genarray.blit} for more details. *) external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill" * Fill the given big array with the given value . See { ! } for more details . See {!Bigarray.Genarray.fill} for more details. *) val of_array: ('a, 'b) kind -> 'c layout -> 'a array array array -> ('a, 'b, 'c) t * Build a three - dimensional big array initialized from the given array of arrays of arrays . given array of arrays of arrays. *) val map_file: Unix.file_descr -> ?pos:int64 -> ('a, 'b) kind -> 'c layout -> bool -> int -> int -> int -> ('a, 'b, 'c) t * Memory mapping of a file as a three - dimensional big array . See { ! . Genarray.map_file } for more details . See {!Bigarray.Genarray.map_file} for more details. *) external unsafe_get: ('a, 'b, 'c) t -> int -> int -> int -> 'a = "%caml_ba_unsafe_ref_3" (** Like {!Bigarray.Array3.get}, but bounds checking is not always performed. *) external unsafe_set: ('a, 'b, 'c) t -> int -> int -> int -> 'a -> unit = "%caml_ba_unsafe_set_3" (** Like {!Bigarray.Array3.set}, but bounds checking is not always performed. *) end * { 6 Coercions between generic big arrays and fixed - dimension big arrays } external genarray_of_array1 : ('a, 'b, 'c) Array1.t -> ('a, 'b, 'c) Genarray.t = "%identity" * Return the generic big array corresponding to the given one - dimensional big array . big array. *) external genarray_of_array2 : ('a, 'b, 'c) Array2.t -> ('a, 'b, 'c) Genarray.t = "%identity" * Return the generic big array corresponding to the given two - dimensional big array . big array. *) external genarray_of_array3 : ('a, 'b, 'c) Array3.t -> ('a, 'b, 'c) Genarray.t = "%identity" * Return the generic big array corresponding to the given three - dimensional big array . big array. *) val array1_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array1.t * Return the one - dimensional big array corresponding to the given generic big array . Raise [ Invalid_argument ] if the generic big array does not have exactly one dimension . generic big array. Raise [Invalid_argument] if the generic big array does not have exactly one dimension. *) val array2_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array2.t * Return the two - dimensional big array corresponding to the given generic big array . Raise [ Invalid_argument ] if the generic big array does not have exactly two dimensions . generic big array. Raise [Invalid_argument] if the generic big array does not have exactly two dimensions. *) val array3_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array3.t * Return the three - dimensional big array corresponding to the given generic big array . Raise [ Invalid_argument ] if the generic big array does not have exactly three dimensions . generic big array. Raise [Invalid_argument] if the generic big array does not have exactly three dimensions. *) * { 6 Re - shaping big arrays } val reshape : ('a, 'b, 'c) Genarray.t -> int array -> ('a, 'b, 'c) Genarray.t * [ reshape b [ |d1; ... ;dN| ] ] converts the big array [ b ] to a [ N]-dimensional array of dimensions [ d1] ... [dN ] . The returned array and the original array [ b ] share their data and have the same layout . For instance , assuming that [ b ] is a one - dimensional array of dimension 12 , [ reshape b [ |3;4| ] ] returns a two - dimensional array [ b ' ] of dimensions 3 and 4 . If [ b ] has C layout , the element [ ( x , y ) ] of [ b ' ] corresponds to the element [ x * 3 + y ] of [ b ] . If [ b ] has Fortran layout , the element [ ( x , y ) ] of [ b ' ] corresponds to the element [ x + ( y - 1 ) * 4 ] of [ b ] . The returned big array must have exactly the same number of elements as the original big array [ b ] . That is , the product of the dimensions of [ b ] must be equal to [ i1 * ... * iN ] . Otherwise , [ Invalid_argument ] is raised . [N]-dimensional array of dimensions [d1]...[dN]. The returned array and the original array [b] share their data and have the same layout. For instance, assuming that [b] is a one-dimensional array of dimension 12, [reshape b [|3;4|]] returns a two-dimensional array [b'] of dimensions 3 and 4. If [b] has C layout, the element [(x,y)] of [b'] corresponds to the element [x * 3 + y] of [b]. If [b] has Fortran layout, the element [(x,y)] of [b'] corresponds to the element [x + (y - 1) * 4] of [b]. The returned big array must have exactly the same number of elements as the original big array [b]. That is, the product of the dimensions of [b] must be equal to [i1 * ... * iN]. Otherwise, [Invalid_argument] is raised. *) val reshape_1 : ('a, 'b, 'c) Genarray.t -> int -> ('a, 'b, 'c) Array1.t * Specialized version of { ! Bigarray.reshape } for reshaping to one - dimensional arrays . one-dimensional arrays. *) val reshape_2 : ('a, 'b, 'c) Genarray.t -> int -> int -> ('a, 'b, 'c) Array2.t * Specialized version of { ! Bigarray.reshape } for reshaping to two - dimensional arrays . two-dimensional arrays. *) val reshape_3 : ('a, 'b, 'c) Genarray.t -> int -> int -> int -> ('a, 'b, 'c) Array3.t * Specialized version of { ! Bigarray.reshape } for reshaping to three - dimensional arrays . three-dimensional arrays. *)
null
https://raw.githubusercontent.com/bmeurer/ocaml-experimental/fe5c10cdb0499e43af4b08f35a3248e5c1a8b541/otherlibs/bigarray/bigarray.mli
ocaml
********************************************************************* Objective Caml the special exception on linking described in file ../../LICENSE. ********************************************************************* * See {!Bigarray.char}. * See {!Bigarray.char}. * See {!Bigarray.char}. * See {!Bigarray.char}. * See {!Bigarray.char}. * See {!Bigarray.char}. * See {!Bigarray.char}. * See {!Bigarray.char}. * See {!Bigarray.char}. * See {!Bigarray.char}. * See {!Bigarray.char}. * See {!Bigarray.char}. * Return the number of dimensions of the given big array. * [Genarray.dims a] returns all dimensions of the big array [a], as an array of integers of length [Genarray.num_dims a]. * Return the kind of the given big array. * Return the layout of the given big array. * Set all elements of a big array to a given value. [Genarray.fill a v] stores the value [v] in all elements of the big array [a]. Setting only some elements of [a] to [v] can be achieved by applying [Genarray.fill] to a sub-array or a slice of [a]. * Return the kind of the given big array. * Return the layout of the given big array. * [Array1.set a x v], also written [a.{x} <- v], stores the value [v] at index [x] in [a]. [x] must be inside the bounds of [a] as described in {!Bigarray.Array1.get}; otherwise, [Invalid_argument] is raised. * Fill the given big array with the given value. See [Genarray.fill] for more details. * Like {!Bigarray.Array1.get}, but bounds checking is not always performed. Use with caution and only when the program logic guarantees that the access is within bounds. * Like {!Bigarray.Array1.set}, but bounds checking is not always performed. Use with caution and only when the program logic guarantees that the access is within bounds. * Return the kind of the given big array. * Return the layout of the given big array. * [Array2.get a x y], also written [a.{x,y}], returns the element of [a] at coordinates ([x], [y]). [x] and [y] must be within the bounds of [a], as described for {!Bigarray.Genarray.get}; otherwise, [Invalid_argument] is raised. * Like {!Bigarray.Array2.get}, but bounds checking is not always performed. * Like {!Bigarray.Array2.set}, but bounds checking is not always performed. * Return the kind of the given big array. * Return the layout of the given big array. * [Array3.get a x y z], also written [a.{x,y,z}], returns the element of [a] at coordinates ([x], [y], [z]). [x], [y] and [z] must be within the bounds of [a], as described for {!Bigarray.Genarray.get}; otherwise, [Invalid_argument] is raised. * [Array3.set a x y v], or alternatively [a.{x,y,z} <- v], stores the value [v] at coordinates ([x], [y], [z]) in [a]. [x], [y] and [z] must be within the bounds of [a], as described for {!Bigarray.Genarray.set}; otherwise, [Invalid_argument] is raised. * Like {!Bigarray.Array3.get}, but bounds checking is not always performed. * Like {!Bigarray.Array3.set}, but bounds checking is not always performed.
and , INRIA Rocquencourt Copyright 2000 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with $ Id$ * Large , multi - dimensional , numerical arrays . This module implements multi - dimensional arrays of integers and floating - point numbers , thereafter referred to as ` ` big arrays '' . The implementation allows efficient sharing of large numerical arrays between code and C or Fortran numerical libraries . Concerning the naming conventions , users of this module are encouraged to do [ open Bigarray ] in their source , then refer to array types and operations via short dot notation , e.g. [ Array1.t ] or [ Array2.sub ] . Big arrays support all the ad - hoc polymorphic operations : - comparisons ( [ =] , [ < > ] , [ < =] , etc , as well as { ! Pervasives.compare } ) ; - hashing ( module [ Hash ] ) ; - and structured input - output ( { ! Pervasives.output_value } and { ! Pervasives.input_value } , as well as the functions from the { ! Marshal } module ) . This module implements multi-dimensional arrays of integers and floating-point numbers, thereafter referred to as ``big arrays''. The implementation allows efficient sharing of large numerical arrays between Caml code and C or Fortran numerical libraries. Concerning the naming conventions, users of this module are encouraged to do [open Bigarray] in their source, then refer to array types and operations via short dot notation, e.g. [Array1.t] or [Array2.sub]. Big arrays support all the Caml ad-hoc polymorphic operations: - comparisons ([=], [<>], [<=], etc, as well as {!Pervasives.compare}); - hashing (module [Hash]); - and structured input-output ({!Pervasives.output_value} and {!Pervasives.input_value}, as well as the functions from the {!Marshal} module). *) * { 6 Element kinds } * Big arrays can contain elements of the following kinds : - IEEE single precision ( 32 bits ) floating - point numbers ( { ! Bigarray.float32_elt } ) , - IEEE double precision ( 64 bits ) floating - point numbers ( { ! Bigarray.float64_elt } ) , - IEEE single precision ( 2 * 32 bits ) floating - point complex numbers ( { ! Bigarray.complex32_elt } ) , - IEEE double precision ( 2 * 64 bits ) floating - point complex numbers ( { ! Bigarray.complex64_elt } ) , - 8 - bit integers ( signed or unsigned ) ( { ! Bigarray.int8_signed_elt } or { ! Bigarray.int8_unsigned_elt } ) , - 16 - bit integers ( signed or unsigned ) ( { ! Bigarray.int16_signed_elt } or { ! Bigarray.int16_unsigned_elt } ) , - Caml integers ( signed , 31 bits on 32 - bit architectures , 63 bits on 64 - bit architectures ) ( { ! } ) , - 32 - bit signed integer ( { ! Bigarray.int32_elt } ) , - 64 - bit signed integers ( { ! Bigarray.int64_elt } ) , - platform - native signed integers ( 32 bits on 32 - bit architectures , 64 bits on 64 - bit architectures ) ( { ! Bigarray.nativeint_elt } ) . Each element kind is represented at the type level by one of the abstract types defined below . - IEEE single precision (32 bits) floating-point numbers ({!Bigarray.float32_elt}), - IEEE double precision (64 bits) floating-point numbers ({!Bigarray.float64_elt}), - IEEE single precision (2 * 32 bits) floating-point complex numbers ({!Bigarray.complex32_elt}), - IEEE double precision (2 * 64 bits) floating-point complex numbers ({!Bigarray.complex64_elt}), - 8-bit integers (signed or unsigned) ({!Bigarray.int8_signed_elt} or {!Bigarray.int8_unsigned_elt}), - 16-bit integers (signed or unsigned) ({!Bigarray.int16_signed_elt} or {!Bigarray.int16_unsigned_elt}), - Caml integers (signed, 31 bits on 32-bit architectures, 63 bits on 64-bit architectures) ({!Bigarray.int_elt}), - 32-bit signed integer ({!Bigarray.int32_elt}), - 64-bit signed integers ({!Bigarray.int64_elt}), - platform-native signed integers (32 bits on 32-bit architectures, 64 bits on 64-bit architectures) ({!Bigarray.nativeint_elt}). Each element kind is represented at the type level by one of the abstract types defined below. *) type float32_elt type float64_elt type complex32_elt type complex64_elt type int8_signed_elt type int8_unsigned_elt type int16_signed_elt type int16_unsigned_elt type int_elt type int32_elt type int64_elt type nativeint_elt type ('a, 'b) kind * To each element kind is associated a type , which is the type of values that can be stored in the big array or read back from it . This type is not necessarily the same as the type of the array elements proper : for instance , a big array whose elements are of kind [ float32_elt ] contains 32 - bit single precision floats , but reading or writing one of its elements from uses the type [ float ] , which is 64 - bit double precision floats . The abstract type [ ( ' a , ' b ) kind ] captures this association of a type [ ' a ] for values read or written in the big array , and of an element kind [ ' b ] which represents the actual contents of the big array . The following predefined values of type [ kind ] list all possible associations of types with element kinds : the type of Caml values that can be stored in the big array or read back from it. This type is not necessarily the same as the type of the array elements proper: for instance, a big array whose elements are of kind [float32_elt] contains 32-bit single precision floats, but reading or writing one of its elements from Caml uses the Caml type [float], which is 64-bit double precision floats. The abstract type [('a, 'b) kind] captures this association of a Caml type ['a] for values read or written in the big array, and of an element kind ['b] which represents the actual contents of the big array. The following predefined values of type [kind] list all possible associations of Caml types with element kinds: *) val float32 : (float, float32_elt) kind val float64 : (float, float64_elt) kind val complex32 : (Complex.t, complex32_elt) kind val complex64 : (Complex.t, complex64_elt) kind val int8_signed : (int, int8_signed_elt) kind val int8_unsigned : (int, int8_unsigned_elt) kind val int16_signed : (int, int16_signed_elt) kind val int16_unsigned : (int, int16_unsigned_elt) kind val int : (int, int_elt) kind val int32 : (int32, int32_elt) kind val int64 : (int64, int64_elt) kind val nativeint : (nativeint, nativeint_elt) kind val char : (char, int8_unsigned_elt) kind * As shown by the types of the values above , big arrays of kind [ float32_elt ] and [ float64_elt ] are accessed using the type [ float ] . Big arrays of complex kinds [ complex32_elt ] , [ complex64_elt ] are accessed with the type { ! Complex.t } . Big arrays of integer kinds are accessed using the smallest integer type large enough to represent the array elements : [ int ] for 8- and 16 - bit integer bigarrays , as well as Caml - integer bigarrays ; [ int32 ] for 32 - bit integer bigarrays ; [ int64 ] for 64 - bit integer bigarrays ; and [ nativeint ] for platform - native integer bigarrays . Finally , big arrays of kind [ int8_unsigned_elt ] can also be accessed as arrays of characters instead of arrays of small integers , by using the kind value [ char ] instead of [ int8_unsigned ] . big arrays of kind [float32_elt] and [float64_elt] are accessed using the Caml type [float]. Big arrays of complex kinds [complex32_elt], [complex64_elt] are accessed with the Caml type {!Complex.t}. Big arrays of integer kinds are accessed using the smallest Caml integer type large enough to represent the array elements: [int] for 8- and 16-bit integer bigarrays, as well as Caml-integer bigarrays; [int32] for 32-bit integer bigarrays; [int64] for 64-bit integer bigarrays; and [nativeint] for platform-native integer bigarrays. Finally, big arrays of kind [int8_unsigned_elt] can also be accessed as arrays of characters instead of arrays of small integers, by using the kind value [char] instead of [int8_unsigned]. *) * { 6 Array layouts } type c_layout * See { ! } . type fortran_layout * To facilitate interoperability with existing C and Fortran code , this library supports two different memory layouts for big arrays , one compatible with the C conventions , the other compatible with the Fortran conventions . In the C - style layout , array indices start at 0 , and multi - dimensional arrays are laid out in row - major format . That is , for a two - dimensional array , all elements of row 0 are contiguous in memory , followed by all elements of row 1 , etc . In other terms , the array elements at [ ( x , y ) ] and [ ( x , y+1 ) ] are adjacent in memory . In the Fortran - style layout , array indices start at 1 , and multi - dimensional arrays are laid out in column - major format . That is , for a two - dimensional array , all elements of column 0 are contiguous in memory , followed by all elements of column 1 , etc . In other terms , the array elements at [ ( x , y ) ] and [ ( x+1 , y ) ] are adjacent in memory . Each layout style is identified at the type level by the abstract types { ! Bigarray.c_layout } and [ fortran_layout ] respectively . this library supports two different memory layouts for big arrays, one compatible with the C conventions, the other compatible with the Fortran conventions. In the C-style layout, array indices start at 0, and multi-dimensional arrays are laid out in row-major format. That is, for a two-dimensional array, all elements of row 0 are contiguous in memory, followed by all elements of row 1, etc. In other terms, the array elements at [(x,y)] and [(x, y+1)] are adjacent in memory. In the Fortran-style layout, array indices start at 1, and multi-dimensional arrays are laid out in column-major format. That is, for a two-dimensional array, all elements of column 0 are contiguous in memory, followed by all elements of column 1, etc. In other terms, the array elements at [(x,y)] and [(x+1, y)] are adjacent in memory. Each layout style is identified at the type level by the abstract types {!Bigarray.c_layout} and [fortran_layout] respectively. *) type 'a layout * The type [ ' a layout ] represents one of the two supported memory layouts : C - style if [ ' a ] is { ! Bigarray.c_layout } , Fortran - style if [ ' a ] is { ! } . memory layouts: C-style if ['a] is {!Bigarray.c_layout}, Fortran-style if ['a] is {!Bigarray.fortran_layout}. *) * { 7 Supported layouts } The abstract values [ c_layout ] and [ fortran_layout ] represent the two supported layouts at the level of values . The abstract values [c_layout] and [fortran_layout] represent the two supported layouts at the level of values. *) val c_layout : c_layout layout val fortran_layout : fortran_layout layout * { 6 Generic arrays ( of arbitrarily many dimensions ) } module Genarray : sig type ('a, 'b, 'c) t * The type [ Genarray.t ] is the type of big arrays with variable numbers of dimensions . Any number of dimensions between 1 and 16 is supported . The three type parameters to [ Genarray.t ] identify the array element kind and layout , as follows : - the first parameter , [ ' a ] , is the type for accessing array elements ( [ float ] , [ int ] , [ int32 ] , [ int64 ] , [ nativeint ] ) ; - the second parameter , [ ' b ] , is the actual kind of array elements ( [ float32_elt ] , [ float64_elt ] , [ int8_signed_elt ] , [ int8_unsigned_elt ] , etc ) ; - the third parameter , [ ' c ] , identifies the array layout ( [ c_layout ] or [ fortran_layout ] ) . For instance , [ ( float , float32_elt , fortran_layout ) Genarray.t ] is the type of generic big arrays containing 32 - bit floats in Fortran layout ; reads and writes in this array use the Caml type [ float ] . numbers of dimensions. Any number of dimensions between 1 and 16 is supported. The three type parameters to [Genarray.t] identify the array element kind and layout, as follows: - the first parameter, ['a], is the Caml type for accessing array elements ([float], [int], [int32], [int64], [nativeint]); - the second parameter, ['b], is the actual kind of array elements ([float32_elt], [float64_elt], [int8_signed_elt], [int8_unsigned_elt], etc); - the third parameter, ['c], identifies the array layout ([c_layout] or [fortran_layout]). For instance, [(float, float32_elt, fortran_layout) Genarray.t] is the type of generic big arrays containing 32-bit floats in Fortran layout; reads and writes in this array use the Caml type [float]. *) external create: ('a, 'b) kind -> 'c layout -> int array -> ('a, 'b, 'c) t = "caml_ba_create" * [ Genarray.create kind layout dimensions ] returns a new big array whose element kind is determined by the parameter [ kind ] ( one of [ float32 ] , [ float64 ] , [ int8_signed ] , etc ) and whose layout is determined by the parameter [ layout ] ( one of [ c_layout ] or [ fortran_layout ] ) . The [ dimensions ] parameter is an array of integers that indicate the size of the big array in each dimension . The length of [ dimensions ] determines the number of dimensions of the bigarray . For instance , [ Genarray.create int32 c_layout [ |4;6;8| ] ] returns a fresh big array of 32 - bit integers , in C layout , having three dimensions , the three dimensions being 4 , 6 and 8 respectively . Big arrays returned by [ Genarray.create ] are not initialized : the initial values of array elements is unspecified . [ Genarray.create ] raises [ Invalid_argument ] if the number of dimensions is not in the range 1 to 16 inclusive , or if one of the dimensions is negative . whose element kind is determined by the parameter [kind] (one of [float32], [float64], [int8_signed], etc) and whose layout is determined by the parameter [layout] (one of [c_layout] or [fortran_layout]). The [dimensions] parameter is an array of integers that indicate the size of the big array in each dimension. The length of [dimensions] determines the number of dimensions of the bigarray. For instance, [Genarray.create int32 c_layout [|4;6;8|]] returns a fresh big array of 32-bit integers, in C layout, having three dimensions, the three dimensions being 4, 6 and 8 respectively. Big arrays returned by [Genarray.create] are not initialized: the initial values of array elements is unspecified. [Genarray.create] raises [Invalid_argument] if the number of dimensions is not in the range 1 to 16 inclusive, or if one of the dimensions is negative. *) external num_dims: ('a, 'b, 'c) t -> int = "caml_ba_num_dims" val dims : ('a, 'b, 'c) t -> int array external nth_dim: ('a, 'b, 'c) t -> int -> int = "caml_ba_dim" * [ Genarray.nth_dim a n ] returns the [ n]-th dimension of the big array [ a ] . The first dimension corresponds to [ n = 0 ] ; the second dimension corresponds to [ n = 1 ] ; the last dimension , to [ n = Genarray.num_dims a - 1 ] . Raise [ Invalid_argument ] if [ n ] is less than 0 or greater or equal than [ Genarray.num_dims a ] . big array [a]. The first dimension corresponds to [n = 0]; the second dimension corresponds to [n = 1]; the last dimension, to [n = Genarray.num_dims a - 1]. Raise [Invalid_argument] if [n] is less than 0 or greater or equal than [Genarray.num_dims a]. *) external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind" external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout" external get: ('a, 'b, 'c) t -> int array -> 'a = "caml_ba_get_generic" * Read an element of a generic big array . [ Genarray.get a [ |i1 ; ... ; iN| ] ] returns the element of [ a ] whose coordinates are [ i1 ] in the first dimension , [ i2 ] in the second dimension , ... , [ iN ] in the [ N]-th dimension . If [ a ] has C layout , the coordinates must be greater or equal than 0 and strictly less than the corresponding dimensions of [ a ] . If [ a ] has Fortran layout , the coordinates must be greater or equal than 1 and less or equal than the corresponding dimensions of [ a ] . Raise [ Invalid_argument ] if the array [ a ] does not have exactly [ N ] dimensions , or if the coordinates are outside the array bounds . If [ N > 3 ] , alternate syntax is provided : you can write [ a.{i1 , i2 , ... , iN } ] instead of [ Genarray.get a [ |i1 ; ... ; iN| ] ] . ( The syntax [ a. { ... } ] with one , two or three coordinates is reserved for accessing one- , two- and three - dimensional arrays as described below . ) [Genarray.get a [|i1; ...; iN|]] returns the element of [a] whose coordinates are [i1] in the first dimension, [i2] in the second dimension, ..., [iN] in the [N]-th dimension. If [a] has C layout, the coordinates must be greater or equal than 0 and strictly less than the corresponding dimensions of [a]. If [a] has Fortran layout, the coordinates must be greater or equal than 1 and less or equal than the corresponding dimensions of [a]. Raise [Invalid_argument] if the array [a] does not have exactly [N] dimensions, or if the coordinates are outside the array bounds. If [N > 3], alternate syntax is provided: you can write [a.{i1, i2, ..., iN}] instead of [Genarray.get a [|i1; ...; iN|]]. (The syntax [a.{...}] with one, two or three coordinates is reserved for accessing one-, two- and three-dimensional arrays as described below.) *) external set: ('a, 'b, 'c) t -> int array -> 'a -> unit = "caml_ba_set_generic" * Assign an element of a generic big array . [ Genarray.set a [ |i1 ; ... ; iN| ] v ] stores the value [ v ] in the element of [ a ] whose coordinates are [ i1 ] in the first dimension , [ i2 ] in the second dimension , ... , [ iN ] in the [ N]-th dimension . The array [ a ] must have exactly [ N ] dimensions , and all coordinates must lie inside the array bounds , as described for [ Genarray.get ] ; otherwise , [ Invalid_argument ] is raised . If [ N > 3 ] , alternate syntax is provided : you can write [ a.{i1 , i2 , ... , iN } < - v ] instead of [ Genarray.set a [ |i1 ; ... ; iN| ] v ] . ( The syntax [ a. { ... } < - v ] with one , two or three coordinates is reserved for updating one- , two- and three - dimensional arrays as described below . ) [Genarray.set a [|i1; ...; iN|] v] stores the value [v] in the element of [a] whose coordinates are [i1] in the first dimension, [i2] in the second dimension, ..., [iN] in the [N]-th dimension. The array [a] must have exactly [N] dimensions, and all coordinates must lie inside the array bounds, as described for [Genarray.get]; otherwise, [Invalid_argument] is raised. If [N > 3], alternate syntax is provided: you can write [a.{i1, i2, ..., iN} <- v] instead of [Genarray.set a [|i1; ...; iN|] v]. (The syntax [a.{...} <- v] with one, two or three coordinates is reserved for updating one-, two- and three-dimensional arrays as described below.) *) external sub_left: ('a, 'b, c_layout) t -> int -> int -> ('a, 'b, c_layout) t = "caml_ba_sub" * Extract a sub - array of the given big array by restricting the first ( left - most ) dimension . [ Genarray.sub_left a ofs len ] returns a big array with the same number of dimensions as [ a ] , and the same dimensions as [ a ] , except the first dimension , which corresponds to the interval [ [ ofs ... ofs + len - 1 ] ] of the first dimension of [ a ] . No copying of elements is involved : the sub - array and the original array share the same storage space . In other terms , the element at coordinates [ [ |i1 ; ... ; iN| ] ] of the sub - array is identical to the element at coordinates [ [ |i1+ofs ; ... ; iN| ] ] of the original array [ a ] . [ Genarray.sub_left ] applies only to big arrays in C layout . Raise [ Invalid_argument ] if [ ofs ] and [ len ] do not designate a valid sub - array of [ a ] , that is , if [ ofs < 0 ] , or [ len < 0 ] , or > Genarray.nth_dim a 0 ] . first (left-most) dimension. [Genarray.sub_left a ofs len] returns a big array with the same number of dimensions as [a], and the same dimensions as [a], except the first dimension, which corresponds to the interval [[ofs ... ofs + len - 1]] of the first dimension of [a]. No copying of elements is involved: the sub-array and the original array share the same storage space. In other terms, the element at coordinates [[|i1; ...; iN|]] of the sub-array is identical to the element at coordinates [[|i1+ofs; ...; iN|]] of the original array [a]. [Genarray.sub_left] applies only to big arrays in C layout. Raise [Invalid_argument] if [ofs] and [len] do not designate a valid sub-array of [a], that is, if [ofs < 0], or [len < 0], or [ofs + len > Genarray.nth_dim a 0]. *) external sub_right: ('a, 'b, fortran_layout) t -> int -> int -> ('a, 'b, fortran_layout) t = "caml_ba_sub" * Extract a sub - array of the given big array by restricting the last ( right - most ) dimension . [ Genarray.sub_right a ofs len ] returns a big array with the same number of dimensions as [ a ] , and the same dimensions as [ a ] , except the last dimension , which corresponds to the interval [ [ ofs ... ofs + len - 1 ] ] of the last dimension of [ a ] . No copying of elements is involved : the sub - array and the original array share the same storage space . In other terms , the element at coordinates [ [ |i1 ; ... ; iN| ] ] of the sub - array is identical to the element at coordinates [ [ |i1 ; ... ; iN+ofs| ] ] of the original array [ a ] . [ Genarray.sub_right ] applies only to big arrays in Fortran layout . Raise [ Invalid_argument ] if [ ofs ] and [ len ] do not designate a valid sub - array of [ a ] , that is , if [ ofs < 1 ] , or [ len < 0 ] , or > Genarray.nth_dim a ( Genarray.num_dims a - 1 ) ] . last (right-most) dimension. [Genarray.sub_right a ofs len] returns a big array with the same number of dimensions as [a], and the same dimensions as [a], except the last dimension, which corresponds to the interval [[ofs ... ofs + len - 1]] of the last dimension of [a]. No copying of elements is involved: the sub-array and the original array share the same storage space. In other terms, the element at coordinates [[|i1; ...; iN|]] of the sub-array is identical to the element at coordinates [[|i1; ...; iN+ofs|]] of the original array [a]. [Genarray.sub_right] applies only to big arrays in Fortran layout. Raise [Invalid_argument] if [ofs] and [len] do not designate a valid sub-array of [a], that is, if [ofs < 1], or [len < 0], or [ofs + len > Genarray.nth_dim a (Genarray.num_dims a - 1)]. *) external slice_left: ('a, 'b, c_layout) t -> int array -> ('a, 'b, c_layout) t = "caml_ba_slice" * Extract a sub - array of lower dimension from the given big array by fixing one or several of the first ( left - most ) coordinates . [ a [ |i1 ; ... ; iM| ] ] returns the ` ` slice '' of [ a ] obtained by setting the first [ M ] coordinates to [ i1 ] , ... , [ iM ] . If [ a ] has [ N ] dimensions , the slice has dimension [ N - M ] , and the element at coordinates [ [ |j1 ; ... ; ] ] in the slice is identical to the element at coordinates [ [ |i1 ; ... ; iM ; j1 ; ... ; ] ] in the original array [ a ] . No copying of elements is involved : the slice and the original array share the same storage space . [ ] applies only to big arrays in C layout . Raise [ Invalid_argument ] if [ M > = N ] , or if [ [ |i1 ; ... ; iM| ] ] is outside the bounds of [ a ] . by fixing one or several of the first (left-most) coordinates. [Genarray.slice_left a [|i1; ... ; iM|]] returns the ``slice'' of [a] obtained by setting the first [M] coordinates to [i1], ..., [iM]. If [a] has [N] dimensions, the slice has dimension [N - M], and the element at coordinates [[|j1; ...; j(N-M)|]] in the slice is identical to the element at coordinates [[|i1; ...; iM; j1; ...; j(N-M)|]] in the original array [a]. No copying of elements is involved: the slice and the original array share the same storage space. [Genarray.slice_left] applies only to big arrays in C layout. Raise [Invalid_argument] if [M >= N], or if [[|i1; ... ; iM|]] is outside the bounds of [a]. *) external slice_right: ('a, 'b, fortran_layout) t -> int array -> ('a, 'b, fortran_layout) t = "caml_ba_slice" * Extract a sub - array of lower dimension from the given big array by fixing one or several of the last ( right - most ) coordinates . [ Genarray.slice_right a [ |i1 ; ... ; iM| ] ] returns the ` ` slice '' of [ a ] obtained by setting the last [ M ] coordinates to [ i1 ] , ... , [ iM ] . If [ a ] has [ N ] dimensions , the slice has dimension [ N - M ] , and the element at coordinates [ [ |j1 ; ... ; ] ] in the slice is identical to the element at coordinates [ [ |j1 ; ... ; ) ; i1 ; ... ; iM| ] ] in the original array [ a ] . No copying of elements is involved : the slice and the original array share the same storage space . [ Genarray.slice_right ] applies only to big arrays in Fortran layout . Raise [ Invalid_argument ] if [ M > = N ] , or if [ [ |i1 ; ... ; iM| ] ] is outside the bounds of [ a ] . by fixing one or several of the last (right-most) coordinates. [Genarray.slice_right a [|i1; ... ; iM|]] returns the ``slice'' of [a] obtained by setting the last [M] coordinates to [i1], ..., [iM]. If [a] has [N] dimensions, the slice has dimension [N - M], and the element at coordinates [[|j1; ...; j(N-M)|]] in the slice is identical to the element at coordinates [[|j1; ...; j(N-M); i1; ...; iM|]] in the original array [a]. No copying of elements is involved: the slice and the original array share the same storage space. [Genarray.slice_right] applies only to big arrays in Fortran layout. Raise [Invalid_argument] if [M >= N], or if [[|i1; ... ; iM|]] is outside the bounds of [a]. *) external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit = "caml_ba_blit" * Copy all elements of a big array in another big array . [ Genarray.blit ] copies all elements of [ src ] into [ dst ] . Both arrays [ src ] and [ dst ] must have the same number of dimensions and equal dimensions . Copying a sub - array of [ src ] to a sub - array of [ dst ] can be achieved by applying [ Genarray.blit ] to sub - array or slices of [ src ] and [ dst ] . [Genarray.blit src dst] copies all elements of [src] into [dst]. Both arrays [src] and [dst] must have the same number of dimensions and equal dimensions. Copying a sub-array of [src] to a sub-array of [dst] can be achieved by applying [Genarray.blit] to sub-array or slices of [src] and [dst]. *) external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill" val map_file: Unix.file_descr -> ?pos:int64 -> ('a, 'b) kind -> 'c layout -> bool -> int array -> ('a, 'b, 'c) t * Memory mapping of a file as a big array . [ Genarray.map_file fd kind layout shared dims ] returns a big array of kind [ kind ] , layout [ layout ] , and dimensions as specified in [ dims ] . The data contained in this big array are the contents of the file referred to by the file descriptor [ fd ] ( as opened previously with [ Unix.openfile ] , for example ) . The optional [ pos ] parameter is the byte offset in the file of the data being mapped ; it defaults to 0 ( map from the beginning of the file ) . If [ shared ] is [ true ] , all modifications performed on the array are reflected in the file . This requires that [ fd ] be opened with write permissions . If [ shared ] is [ false ] , modifications performed on the array are done in memory only , using copy - on - write of the modified pages ; the underlying file is not affected . [ Genarray.map_file ] is much more efficient than reading the whole file in a big array , modifying that big array , and writing it afterwards . To adjust automatically the dimensions of the big array to the actual size of the file , the major dimension ( that is , the first dimension for an array with C layout , and the last dimension for an array with Fortran layout ) can be given as [ -1 ] . [ Genarray.map_file ] then determines the major dimension from the size of the file . The file must contain an integral number of sub - arrays as determined by the non - major dimensions , otherwise [ Failure ] is raised . If all dimensions of the big array are given , the file size is matched against the size of the big array . If the file is larger than the big array , only the initial portion of the file is mapped to the big array . If the file is smaller than the big array , the file is automatically grown to the size of the big array . This requires write permissions on [ fd ] . [Genarray.map_file fd kind layout shared dims] returns a big array of kind [kind], layout [layout], and dimensions as specified in [dims]. The data contained in this big array are the contents of the file referred to by the file descriptor [fd] (as opened previously with [Unix.openfile], for example). The optional [pos] parameter is the byte offset in the file of the data being mapped; it defaults to 0 (map from the beginning of the file). If [shared] is [true], all modifications performed on the array are reflected in the file. This requires that [fd] be opened with write permissions. If [shared] is [false], modifications performed on the array are done in memory only, using copy-on-write of the modified pages; the underlying file is not affected. [Genarray.map_file] is much more efficient than reading the whole file in a big array, modifying that big array, and writing it afterwards. To adjust automatically the dimensions of the big array to the actual size of the file, the major dimension (that is, the first dimension for an array with C layout, and the last dimension for an array with Fortran layout) can be given as [-1]. [Genarray.map_file] then determines the major dimension from the size of the file. The file must contain an integral number of sub-arrays as determined by the non-major dimensions, otherwise [Failure] is raised. If all dimensions of the big array are given, the file size is matched against the size of the big array. If the file is larger than the big array, only the initial portion of the file is mapped to the big array. If the file is smaller than the big array, the file is automatically grown to the size of the big array. This requires write permissions on [fd]. *) end * { 6 One - dimensional arrays } * One - dimensional arrays . The [ Array1 ] structure provides operations similar to those of { ! . Genarray } , but specialized to the case of one - dimensional arrays . ( The [ Array2 ] and [ Array3 ] structures below provide operations specialized for two- and three - dimensional arrays . ) Statically knowing the number of dimensions of the array allows faster operations , and more precise static type - checking . similar to those of {!Bigarray.Genarray}, but specialized to the case of one-dimensional arrays. (The [Array2] and [Array3] structures below provide operations specialized for two- and three-dimensional arrays.) Statically knowing the number of dimensions of the array allows faster operations, and more precise static type-checking. *) module Array1 : sig type ('a, 'b, 'c) t * The type of one - dimensional big arrays whose elements have type [ ' a ] , representation kind [ ' b ] , and memory layout [ ' c ] . Caml type ['a], representation kind ['b], and memory layout ['c]. *) val create: ('a, 'b) kind -> 'c layout -> int -> ('a, 'b, 'c) t * [ Array1.create kind layout dim ] returns a new bigarray of one dimension , whose size is [ dim ] . [ kind ] and [ layout ] determine the array element kind and the array layout as described for [ Genarray.create ] . one dimension, whose size is [dim]. [kind] and [layout] determine the array element kind and the array layout as described for [Genarray.create]. *) val dim: ('a, 'b, 'c) t -> int * Return the size ( dimension ) of the given one - dimensional big array . big array. *) external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind" external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout" external get: ('a, 'b, 'c) t -> int -> 'a = "%caml_ba_ref_1" * [ Array1.get a x ] , or alternatively [ a.{x } ] , returns the element of [ a ] at index [ x ] . [ x ] must be greater or equal than [ 0 ] and strictly less than [ Array1.dim a ] if [ a ] has C layout . If [ a ] has Fortran layout , [ x ] must be greater or equal than [ 1 ] and less or equal than [ Array1.dim a ] . Otherwise , [ Invalid_argument ] is raised . returns the element of [a] at index [x]. [x] must be greater or equal than [0] and strictly less than [Array1.dim a] if [a] has C layout. If [a] has Fortran layout, [x] must be greater or equal than [1] and less or equal than [Array1.dim a]. Otherwise, [Invalid_argument] is raised. *) external set: ('a, 'b, 'c) t -> int -> 'a -> unit = "%caml_ba_set_1" external sub: ('a, 'b, 'c) t -> int -> int -> ('a, 'b, 'c) t = "caml_ba_sub" * Extract a sub - array of the given one - dimensional big array . See [ Genarray.sub_left ] for more details . See [Genarray.sub_left] for more details. *) external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit = "caml_ba_blit" * Copy the first big array to the second big array . See [ Genarray.blit ] for more details . See [Genarray.blit] for more details. *) external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill" val of_array: ('a, 'b) kind -> 'c layout -> 'a array -> ('a, 'b, 'c) t * Build a one - dimensional big array initialized from the given array . given array. *) val map_file: Unix.file_descr -> ?pos:int64 -> ('a, 'b) kind -> 'c layout -> bool -> int -> ('a, 'b, 'c) t * Memory mapping of a file as a one - dimensional big array . See { ! . Genarray.map_file } for more details . See {!Bigarray.Genarray.map_file} for more details. *) external unsafe_get: ('a, 'b, 'c) t -> int -> 'a = "%caml_ba_unsafe_ref_1" external unsafe_set: ('a, 'b, 'c) t -> int -> 'a -> unit = "%caml_ba_unsafe_set_1" end * { 6 Two - dimensional arrays } * Two - dimensional arrays . The [ Array2 ] structure provides operations similar to those of { ! . Genarray } , but specialized to the case of two - dimensional arrays . similar to those of {!Bigarray.Genarray}, but specialized to the case of two-dimensional arrays. *) module Array2 : sig type ('a, 'b, 'c) t * The type of two - dimensional big arrays whose elements have type [ ' a ] , representation kind [ ' b ] , and memory layout [ ' c ] . Caml type ['a], representation kind ['b], and memory layout ['c]. *) val create: ('a, 'b) kind -> 'c layout -> int -> int -> ('a, 'b, 'c) t * [ Array2.create kind layout dim1 dim2 ] returns a new bigarray of two dimension , whose size is [ dim1 ] in the first dimension and [ dim2 ] in the second dimension . [ kind ] and [ layout ] determine the array element kind and the array layout as described for { ! Bigarray.Genarray.create } . two dimension, whose size is [dim1] in the first dimension and [dim2] in the second dimension. [kind] and [layout] determine the array element kind and the array layout as described for {!Bigarray.Genarray.create}. *) val dim1: ('a, 'b, 'c) t -> int * Return the first dimension of the given two - dimensional big array . val dim2: ('a, 'b, 'c) t -> int * Return the second dimension of the given two - dimensional big array . external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind" external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout" external get: ('a, 'b, 'c) t -> int -> int -> 'a = "%caml_ba_ref_2" external set: ('a, 'b, 'c) t -> int -> int -> 'a -> unit = "%caml_ba_set_2" * [ Array2.set a x y v ] , or alternatively [ a.{x , y } < - v ] , stores the value [ v ] at coordinates ( [ x ] , [ y ] ) in [ a ] . [ x ] and [ y ] must be within the bounds of [ a ] , as described for { ! Bigarray.Genarray.set } ; otherwise , [ Invalid_argument ] is raised . stores the value [v] at coordinates ([x], [y]) in [a]. [x] and [y] must be within the bounds of [a], as described for {!Bigarray.Genarray.set}; otherwise, [Invalid_argument] is raised. *) external sub_left: ('a, 'b, c_layout) t -> int -> int -> ('a, 'b, c_layout) t = "caml_ba_sub" * Extract a two - dimensional sub - array of the given two - dimensional big array by restricting the first dimension . See { ! . Genarray.sub_left } for more details . [ ] applies only to arrays with C layout . big array by restricting the first dimension. See {!Bigarray.Genarray.sub_left} for more details. [Array2.sub_left] applies only to arrays with C layout. *) external sub_right: ('a, 'b, fortran_layout) t -> int -> int -> ('a, 'b, fortran_layout) t = "caml_ba_sub" * Extract a two - dimensional sub - array of the given two - dimensional big array by restricting the second dimension . See { ! Bigarray . } for more details . [ Array2.sub_right ] applies only to arrays with Fortran layout . big array by restricting the second dimension. See {!Bigarray.Genarray.sub_right} for more details. [Array2.sub_right] applies only to arrays with Fortran layout. *) val slice_left: ('a, 'b, c_layout) t -> int -> ('a, 'b, c_layout) Array1.t * Extract a row ( one - dimensional slice ) of the given two - dimensional big array . The integer parameter is the index of the row to extract . See { ! . } for more details . [ Array2.slice_left ] applies only to arrays with C layout . big array. The integer parameter is the index of the row to extract. See {!Bigarray.Genarray.slice_left} for more details. [Array2.slice_left] applies only to arrays with C layout. *) val slice_right: ('a, 'b, fortran_layout) t -> int -> ('a, 'b, fortran_layout) Array1.t * Extract a column ( one - dimensional slice ) of the given two - dimensional big array . The integer parameter is the index of the column to extract . See { ! . Genarray.slice_right } for more details . [ Array2.slice_right ] applies only to arrays with Fortran layout . two-dimensional big array. The integer parameter is the index of the column to extract. See {!Bigarray.Genarray.slice_right} for more details. [Array2.slice_right] applies only to arrays with Fortran layout. *) external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit = "caml_ba_blit" * Copy the first big array to the second big array . See { ! } for more details . See {!Bigarray.Genarray.blit} for more details. *) external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill" * Fill the given big array with the given value . See { ! } for more details . See {!Bigarray.Genarray.fill} for more details. *) val of_array: ('a, 'b) kind -> 'c layout -> 'a array array -> ('a, 'b, 'c) t * Build a two - dimensional big array initialized from the given array of arrays . given array of arrays. *) val map_file: Unix.file_descr -> ?pos:int64 -> ('a, 'b) kind -> 'c layout -> bool -> int -> int -> ('a, 'b, 'c) t * Memory mapping of a file as a two - dimensional big array . See { ! . Genarray.map_file } for more details . See {!Bigarray.Genarray.map_file} for more details. *) external unsafe_get: ('a, 'b, 'c) t -> int -> int -> 'a = "%caml_ba_unsafe_ref_2" external unsafe_set: ('a, 'b, 'c) t -> int -> int -> 'a -> unit = "%caml_ba_unsafe_set_2" end * { 6 Three - dimensional arrays } * Three - dimensional arrays . The [ Array3 ] structure provides operations similar to those of { ! . Genarray } , but specialized to the case of three - dimensional arrays . similar to those of {!Bigarray.Genarray}, but specialized to the case of three-dimensional arrays. *) module Array3 : sig type ('a, 'b, 'c) t * The type of three - dimensional big arrays whose elements have type [ ' a ] , representation kind [ ' b ] , and memory layout [ ' c ] . Caml type ['a], representation kind ['b], and memory layout ['c]. *) val create: ('a, 'b) kind -> 'c layout -> int -> int -> int -> ('a, 'b, 'c) t * [ Array3.create kind layout dim1 dim2 dim3 ] returns a new bigarray of three dimension , whose size is [ dim1 ] in the first dimension , [ dim2 ] in the second dimension , and [ dim3 ] in the third . [ kind ] and [ layout ] determine the array element kind and the array layout as described for { ! Bigarray.Genarray.create } . three dimension, whose size is [dim1] in the first dimension, [dim2] in the second dimension, and [dim3] in the third. [kind] and [layout] determine the array element kind and the array layout as described for {!Bigarray.Genarray.create}. *) val dim1: ('a, 'b, 'c) t -> int * Return the first dimension of the given three - dimensional big array . val dim2: ('a, 'b, 'c) t -> int * Return the second dimension of the given three - dimensional big array . val dim3: ('a, 'b, 'c) t -> int * Return the third dimension of the given three - dimensional big array . external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind" external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout" external get: ('a, 'b, 'c) t -> int -> int -> int -> 'a = "%caml_ba_ref_3" external set: ('a, 'b, 'c) t -> int -> int -> int -> 'a -> unit = "%caml_ba_set_3" external sub_left: ('a, 'b, c_layout) t -> int -> int -> ('a, 'b, c_layout) t = "caml_ba_sub" * Extract a three - dimensional sub - array of the given three - dimensional big array by restricting the first dimension . See { ! . Genarray.sub_left } for more details . [ Array3.sub_left ] applies only to arrays with C layout . three-dimensional big array by restricting the first dimension. See {!Bigarray.Genarray.sub_left} for more details. [Array3.sub_left] applies only to arrays with C layout. *) external sub_right: ('a, 'b, fortran_layout) t -> int -> int -> ('a, 'b, fortran_layout) t = "caml_ba_sub" * Extract a three - dimensional sub - array of the given three - dimensional big array by restricting the second dimension . See { ! Bigarray . } for more details . [ Array3.sub_right ] applies only to arrays with Fortran layout . three-dimensional big array by restricting the second dimension. See {!Bigarray.Genarray.sub_right} for more details. [Array3.sub_right] applies only to arrays with Fortran layout. *) val slice_left_1: ('a, 'b, c_layout) t -> int -> int -> ('a, 'b, c_layout) Array1.t * Extract a one - dimensional slice of the given three - dimensional big array by fixing the first two coordinates . The integer parameters are the coordinates of the slice to extract . See { ! . } for more details . [ Array3.slice_left_1 ] applies only to arrays with C layout . big array by fixing the first two coordinates. The integer parameters are the coordinates of the slice to extract. See {!Bigarray.Genarray.slice_left} for more details. [Array3.slice_left_1] applies only to arrays with C layout. *) val slice_right_1: ('a, 'b, fortran_layout) t -> int -> int -> ('a, 'b, fortran_layout) Array1.t * Extract a one - dimensional slice of the given three - dimensional big array by fixing the last two coordinates . The integer parameters are the coordinates of the slice to extract . See { ! . Genarray.slice_right } for more details . [ Array3.slice_right_1 ] applies only to arrays with Fortran layout . big array by fixing the last two coordinates. The integer parameters are the coordinates of the slice to extract. See {!Bigarray.Genarray.slice_right} for more details. [Array3.slice_right_1] applies only to arrays with Fortran layout. *) val slice_left_2: ('a, 'b, c_layout) t -> int -> ('a, 'b, c_layout) Array2.t * Extract a two - dimensional slice of the given three - dimensional big array by fixing the first coordinate . The integer parameter is the first coordinate of the slice to extract . See { ! . } for more details . [ Array3.slice_left_2 ] applies only to arrays with C layout . big array by fixing the first coordinate. The integer parameter is the first coordinate of the slice to extract. See {!Bigarray.Genarray.slice_left} for more details. [Array3.slice_left_2] applies only to arrays with C layout. *) val slice_right_2: ('a, 'b, fortran_layout) t -> int -> ('a, 'b, fortran_layout) Array2.t * Extract a two - dimensional slice of the given three - dimensional big array by fixing the last coordinate . The integer parameter is the coordinate of the slice to extract . See { ! . Genarray.slice_right } for more details . [ Array3.slice_right_2 ] applies only to arrays with Fortran layout . three-dimensional big array by fixing the last coordinate. The integer parameter is the coordinate of the slice to extract. See {!Bigarray.Genarray.slice_right} for more details. [Array3.slice_right_2] applies only to arrays with Fortran layout. *) external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit = "caml_ba_blit" * Copy the first big array to the second big array . See { ! } for more details . See {!Bigarray.Genarray.blit} for more details. *) external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill" * Fill the given big array with the given value . See { ! } for more details . See {!Bigarray.Genarray.fill} for more details. *) val of_array: ('a, 'b) kind -> 'c layout -> 'a array array array -> ('a, 'b, 'c) t * Build a three - dimensional big array initialized from the given array of arrays of arrays . given array of arrays of arrays. *) val map_file: Unix.file_descr -> ?pos:int64 -> ('a, 'b) kind -> 'c layout -> bool -> int -> int -> int -> ('a, 'b, 'c) t * Memory mapping of a file as a three - dimensional big array . See { ! . Genarray.map_file } for more details . See {!Bigarray.Genarray.map_file} for more details. *) external unsafe_get: ('a, 'b, 'c) t -> int -> int -> int -> 'a = "%caml_ba_unsafe_ref_3" external unsafe_set: ('a, 'b, 'c) t -> int -> int -> int -> 'a -> unit = "%caml_ba_unsafe_set_3" end * { 6 Coercions between generic big arrays and fixed - dimension big arrays } external genarray_of_array1 : ('a, 'b, 'c) Array1.t -> ('a, 'b, 'c) Genarray.t = "%identity" * Return the generic big array corresponding to the given one - dimensional big array . big array. *) external genarray_of_array2 : ('a, 'b, 'c) Array2.t -> ('a, 'b, 'c) Genarray.t = "%identity" * Return the generic big array corresponding to the given two - dimensional big array . big array. *) external genarray_of_array3 : ('a, 'b, 'c) Array3.t -> ('a, 'b, 'c) Genarray.t = "%identity" * Return the generic big array corresponding to the given three - dimensional big array . big array. *) val array1_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array1.t * Return the one - dimensional big array corresponding to the given generic big array . Raise [ Invalid_argument ] if the generic big array does not have exactly one dimension . generic big array. Raise [Invalid_argument] if the generic big array does not have exactly one dimension. *) val array2_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array2.t * Return the two - dimensional big array corresponding to the given generic big array . Raise [ Invalid_argument ] if the generic big array does not have exactly two dimensions . generic big array. Raise [Invalid_argument] if the generic big array does not have exactly two dimensions. *) val array3_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array3.t * Return the three - dimensional big array corresponding to the given generic big array . Raise [ Invalid_argument ] if the generic big array does not have exactly three dimensions . generic big array. Raise [Invalid_argument] if the generic big array does not have exactly three dimensions. *) * { 6 Re - shaping big arrays } val reshape : ('a, 'b, 'c) Genarray.t -> int array -> ('a, 'b, 'c) Genarray.t * [ reshape b [ |d1; ... ;dN| ] ] converts the big array [ b ] to a [ N]-dimensional array of dimensions [ d1] ... [dN ] . The returned array and the original array [ b ] share their data and have the same layout . For instance , assuming that [ b ] is a one - dimensional array of dimension 12 , [ reshape b [ |3;4| ] ] returns a two - dimensional array [ b ' ] of dimensions 3 and 4 . If [ b ] has C layout , the element [ ( x , y ) ] of [ b ' ] corresponds to the element [ x * 3 + y ] of [ b ] . If [ b ] has Fortran layout , the element [ ( x , y ) ] of [ b ' ] corresponds to the element [ x + ( y - 1 ) * 4 ] of [ b ] . The returned big array must have exactly the same number of elements as the original big array [ b ] . That is , the product of the dimensions of [ b ] must be equal to [ i1 * ... * iN ] . Otherwise , [ Invalid_argument ] is raised . [N]-dimensional array of dimensions [d1]...[dN]. The returned array and the original array [b] share their data and have the same layout. For instance, assuming that [b] is a one-dimensional array of dimension 12, [reshape b [|3;4|]] returns a two-dimensional array [b'] of dimensions 3 and 4. If [b] has C layout, the element [(x,y)] of [b'] corresponds to the element [x * 3 + y] of [b]. If [b] has Fortran layout, the element [(x,y)] of [b'] corresponds to the element [x + (y - 1) * 4] of [b]. The returned big array must have exactly the same number of elements as the original big array [b]. That is, the product of the dimensions of [b] must be equal to [i1 * ... * iN]. Otherwise, [Invalid_argument] is raised. *) val reshape_1 : ('a, 'b, 'c) Genarray.t -> int -> ('a, 'b, 'c) Array1.t * Specialized version of { ! Bigarray.reshape } for reshaping to one - dimensional arrays . one-dimensional arrays. *) val reshape_2 : ('a, 'b, 'c) Genarray.t -> int -> int -> ('a, 'b, 'c) Array2.t * Specialized version of { ! Bigarray.reshape } for reshaping to two - dimensional arrays . two-dimensional arrays. *) val reshape_3 : ('a, 'b, 'c) Genarray.t -> int -> int -> int -> ('a, 'b, 'c) Array3.t * Specialized version of { ! Bigarray.reshape } for reshaping to three - dimensional arrays . three-dimensional arrays. *)
43c58b343f8cdd3945dfa3221f12a8bb6e41e7722803d0d98af558497d5c7027
mojombo/ernie
ernie_server.erl
-module(ernie_server). -behaviour(gen_server). -include_lib("ernie.hrl"). %% api -export([start_link/1, start/1, process/1, enqueue_request/1, kick/0, fin/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %%==================================================================== %% API %%==================================================================== start_link(Args) -> gen_server:start_link({local, ?MODULE}, ?MODULE, Args, []). start(Args) -> gen_server:start({local, ?MODULE}, ?MODULE, Args, []). process(Sock) -> gen_server:cast(?MODULE, {process, Sock}). enqueue_request(Request) -> gen_server:call(?MODULE, {enqueue_request, Request}). kick() -> gen_server:cast(?MODULE, kick). fin() -> gen_server:cast(?MODULE, fin). %%==================================================================== %% gen_server callbacks %%==================================================================== %%-------------------------------------------------------------------- %% Function: init(Args) -> {ok, State} | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% Description: Initiates the server %%-------------------------------------------------------------------- init([Port, Configs]) -> process_flag(trap_exit, true), error_logger:info_msg("~p starting~n", [?MODULE]), {ok, LSock} = try_listen(Port, 500), spawn(fun() -> loop(LSock) end), Map = init_map(Configs), io:format("pidmap = ~p~n", [Map]), {ok, #state{lsock = LSock, map = Map}}. %%-------------------------------------------------------------------- Function : % % handle_call(Request , From , State ) - > { reply , Reply , State } | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% Description: Handling call messages %%-------------------------------------------------------------------- handle_call({enqueue_request, Request}, _From, State) -> case Request#request.priority of high -> Hq2 = queue:in(Request, State#state.hq), Lq2 = State#state.lq; low -> Hq2 = State#state.hq, Lq2 = queue:in(Request, State#state.lq) end, {reply, ok, State#state{hq = Hq2, lq = Lq2}}; handle_call(_Request, _From, State) -> {reply, ok, State}. %%-------------------------------------------------------------------- Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling cast messages %%-------------------------------------------------------------------- handle_cast({process, Sock}, State) -> Log = #log{hq = queue:len(State#state.hq), lq = queue:len(State#state.lq), taccept = erlang:now()}, Request = #request{sock = Sock, log = Log}, spawn(fun() -> receive_term(Request, State) end), logger:debug("Spawned receiver~n", []), {noreply, State}; handle_cast(kick, State) -> case queue:out(State#state.hq) of {{value, Request}, Hq2} -> State2 = process_request(Request, hq, Hq2, State), {noreply, State2}; {empty, _Hq} -> case queue:out(State#state.lq) of {{value, Request}, Lq2} -> State2 = process_request(Request, lq, Lq2, State), {noreply, State2}; {empty, _Lq} -> {noreply, State} end end; handle_cast(fin, State) -> Listen = State#state.listen, Count = State#state.count, ZCount = State#state.zcount + 1, logger:debug("Fin; Listen = ~p (~p/~p)~n", [Listen, Count, ZCount]), case Listen =:= false andalso ZCount =:= Count of true -> halt(); false -> {noreply, State#state{zcount = ZCount}} end; handle_cast(_Msg, State) -> {noreply, State}. handle_info(Msg, State) -> error_logger:error_msg("Unexpected message: ~p~n", [Msg]), {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVersion, State, _Extra) -> {ok, State}. %%==================================================================== Internal %%==================================================================== %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Module mapping init_map(Configs) -> lists:map((fun extract_mapping/1), Configs). extract_mapping(Config) -> Id = proplists:get_value(id, Config), Mod = proplists:get_value(module, Config), {Mod, Id}. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Listen and loop try_listen(Port, 0) -> error_logger:error_msg("Could not listen on port ~p~n", [Port]), {error, "Could not listen on port"}; try_listen(Port, Times) -> Res = gen_tcp:listen(Port, [binary, {packet, 4}, {active, false}, {reuseaddr, true}, {backlog, 128}]), case Res of {ok, LSock} -> error_logger:info_msg("Listening on port ~p~n", [Port]), % gen_tcp:controlling_process(LSock, ernie_server), {ok, LSock}; {error, Reason} -> error_logger:info_msg("Could not listen on port ~p: ~p~n", [Port, Reason]), timer:sleep(5000), try_listen(Port, Times - 1) end. loop(LSock) -> case gen_tcp:accept(LSock) of {error, closed} -> logger:debug("Listen socket closed~n", []), timer:sleep(infinity); {error, Error} -> logger:debug("Connection accept error: ~p~n", [Error]), loop(LSock); {ok, Sock} -> logger:debug("Accepted socket: ~p~n", [Sock]), ernie_server:process(Sock), loop(LSock) end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Receive and process receive_term(Request, State) -> Sock = Request#request.sock, case gen_tcp:recv(Sock, 0) of {ok, BinaryTerm} -> logger:debug("Got binary term: ~p~n", [BinaryTerm]), Term = binary_to_term(BinaryTerm), logger:info("Got term: ~p~n", [Term]), case Term of {call, '__admin__', Fun, Args} -> ernie_admin:process(Sock, Fun, Args, State); {info, Command, Args} -> Infos = Request#request.infos, Infos2 = [BinaryTerm | Infos], Request2 = Request#request{infos = Infos2}, Request3 = process_info(Request2, Command, Args), receive_term(Request3, State); _Any -> Request2 = Request#request{action = BinaryTerm}, close_if_cast(Term, Request2), ernie_server:enqueue_request(Request2), ernie_server:kick() end; {error, closed} -> ok = gen_tcp:close(Sock) end. process_info(Request, priority, [Priority]) -> Request#request{priority = Priority}; process_info(Request, _Command, _Args) -> Request. process_request(Request, Priority, Q2, State) -> ActionTerm = bert:decode(Request#request.action), {_Type, Mod, _Fun, _Args} = ActionTerm, Specs = lists:filter(fun({X, _Id}) -> Mod =:= X end, State#state.map), case Specs of [] -> no_module(Mod, Request, Priority, Q2, State); _Else -> process_module(ActionTerm, Specs, Request, Priority, Q2, State) end. no_module(Mod, Request, Priority, Q2, State) -> logger:debug("No such module ~p~n", [Mod]), Sock = Request#request.sock, Class = <<"ServerError">>, Message = list_to_binary(io_lib:format("No such module '~p'", [Mod])), gen_tcp:send(Sock, term_to_binary({error, [server, 0, Class, Message, []]})), ok = gen_tcp:close(Sock), finish(Priority, Q2, State). process_module(ActionTerm, [], Request, Priority, Q2, State) -> {_Type, Mod, Fun, _Args} = ActionTerm, logger:debug("No such function ~p:~p~n", [Mod, Fun]), Sock = Request#request.sock, Class = <<"ServerError">>, Message = list_to_binary(io_lib:format("No such function '~p:~p'", [Mod, Fun])), gen_tcp:send(Sock, term_to_binary({error, [server, 0, Class, Message, []]})), ok = gen_tcp:close(Sock), finish(Priority, Q2, State); process_module(ActionTerm, Specs, Request, Priority, Q2, State) -> [{_Mod, Id} | OtherSpecs] = Specs, case Id of native -> logger:debug("Dispatching to native module~n", []), {_Type, Mod, Fun, Args} = ActionTerm, case erlang:function_exported(Mod, Fun, length(Args)) of false -> logger:debug("Not found in native module ~p~n", [Mod]), process_module(ActionTerm, OtherSpecs, Request, Priority, Q2, State); true -> PredFun = list_to_atom(atom_to_list(Fun) ++ "_pred"), logger:debug("Checking ~p:~p(~p) for selection.~n", [Mod, PredFun, Args]), case erlang:function_exported(Mod, PredFun, length(Args)) of false -> logger:debug("No such predicate function ~p:~p(~p).~n", [Mod, PredFun, Args]), process_native_request(ActionTerm, Request, Priority, Q2, State); true -> case apply(Mod, PredFun, Args) of false -> logger:debug("Predicate ~p:~p(~p) returned false.~n", [Mod, PredFun, Args]), process_module(ActionTerm, OtherSpecs, Request, Priority, Q2, State); true -> logger:debug("Predicate ~p:~p(~p) returned true.~n", [Mod, PredFun, Args]), process_native_request(ActionTerm, Request, Priority, Q2, State) end end end; ValidPid when is_pid(ValidPid) -> logger:debug("Found external pid ~p~n", [ValidPid]), process_external_request(ValidPid, Request, Priority, Q2, State) end. close_if_cast(ActionTerm, Request) -> case ActionTerm of {cast, _Mod, _Fun, _Args} -> Sock = Request#request.sock, gen_tcp:send(Sock, term_to_binary({noreply})), ok = gen_tcp:close(Sock), logger:debug("Closed cast.~n", []); _Any -> ok end. finish(Priority, Q2, State) -> case Priority of hq -> State#state{hq = Q2}; lq -> State#state{lq = Q2} end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Native process_native_request(ActionTerm, Request, Priority, Q2, State) -> Count = State#state.count, State2 = State#state{count = Count + 1}, logger:debug("Count = ~p~n", [Count + 1]), Log = Request#request.log, Log2 = Log#log{type = native, tprocess = erlang:now()}, Request2 = Request#request{log = Log2}, spawn(fun() -> ernie_native:process(ActionTerm, Request2) end), finish(Priority, Q2, State2). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % External process_external_request(Pid, Request, Priority, Q2, State) -> Count = State#state.count, State2 = State#state{count = Count + 1}, logger:debug("Count = ~p~n", [Count + 1]), case asset_pool:lease(Pid) of {ok, Asset} -> logger:debug("Leased asset for pool ~p~n", [Pid]), Log = Request#request.log, Log2 = Log#log{type = external, tprocess = erlang:now()}, Request2 = Request#request{log = Log2}, spawn(fun() -> process_now(Pid, Request2, Asset) end), finish(Priority, Q2, State2); empty -> State end. process_now(Pid, Request, Asset) -> try unsafe_process_now(Request, Asset) of _AnyResponse -> Log = Request#request.log, Log2 = Log#log{tdone = erlang:now()}, Request2 = Request#request{log = Log2}, ernie_access_logger:acc(Request2) catch AnyClass:AnyError -> Log = Request#request.log, Log2 = Log#log{tdone = erlang:now()}, Request2 = Request#request{log = Log2}, ernie_access_logger:err(Request2, "External process error ~w: ~w", [AnyClass, AnyError]) after asset_pool:return(Pid, Asset), ernie_server:fin(), ernie_server:kick(), logger:debug("Returned asset ~p~n", [Asset]), gen_tcp:close(Request#request.sock), logger:debug("Closed socket ~p~n", [Request#request.sock]) end. unsafe_process_now(Request, Asset) -> BinaryTerm = Request#request.action, Term = binary_to_term(BinaryTerm), case Term of {call, Mod, Fun, Args} -> logger:debug("Calling ~p:~p(~p)~n", [Mod, Fun, Args]), Sock = Request#request.sock, {asset, Port, Token} = Asset, logger:debug("Asset: ~p ~p~n", [Port, Token]), {ok, Data} = port_wrapper:rpc(Port, BinaryTerm), ok = gen_tcp:send(Sock, Data); {cast, Mod, Fun, Args} -> logger:debug("Casting ~p:~p(~p)~n", [Mod, Fun, Args]), {asset, Port, Token} = Asset, logger:debug("Asset: ~p ~p~n", [Port, Token]), {ok, _Data} = port_wrapper:rpc(Port, BinaryTerm) end.
null
https://raw.githubusercontent.com/mojombo/ernie/a21664e668038291bdbe42684d46cb112242aa7b/elib/ernie_server.erl
erlang
api gen_server callbacks ==================================================================== API ==================================================================== ==================================================================== gen_server callbacks ==================================================================== -------------------------------------------------------------------- Function: init(Args) -> {ok, State} | ignore | {stop, Reason} Description: Initiates the server -------------------------------------------------------------------- -------------------------------------------------------------------- % handle_call(Request , From , State ) - > { reply , Reply , State } | {stop, Reason, Reply, State} | {stop, Reason, State} Description: Handling call messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling cast messages -------------------------------------------------------------------- ==================================================================== ==================================================================== Module mapping Listen and loop gen_tcp:controlling_process(LSock, ernie_server), Receive and process External
-module(ernie_server). -behaviour(gen_server). -include_lib("ernie.hrl"). -export([start_link/1, start/1, process/1, enqueue_request/1, kick/0, fin/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). start_link(Args) -> gen_server:start_link({local, ?MODULE}, ?MODULE, Args, []). start(Args) -> gen_server:start({local, ?MODULE}, ?MODULE, Args, []). process(Sock) -> gen_server:cast(?MODULE, {process, Sock}). enqueue_request(Request) -> gen_server:call(?MODULE, {enqueue_request, Request}). kick() -> gen_server:cast(?MODULE, kick). fin() -> gen_server:cast(?MODULE, fin). { ok , State , Timeout } | init([Port, Configs]) -> process_flag(trap_exit, true), error_logger:info_msg("~p starting~n", [?MODULE]), {ok, LSock} = try_listen(Port, 500), spawn(fun() -> loop(LSock) end), Map = init_map(Configs), io:format("pidmap = ~p~n", [Map]), {ok, #state{lsock = LSock, map = Map}}. { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call({enqueue_request, Request}, _From, State) -> case Request#request.priority of high -> Hq2 = queue:in(Request, State#state.hq), Lq2 = State#state.lq; low -> Hq2 = State#state.hq, Lq2 = queue:in(Request, State#state.lq) end, {reply, ok, State#state{hq = Hq2, lq = Lq2}}; handle_call(_Request, _From, State) -> {reply, ok, State}. Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast({process, Sock}, State) -> Log = #log{hq = queue:len(State#state.hq), lq = queue:len(State#state.lq), taccept = erlang:now()}, Request = #request{sock = Sock, log = Log}, spawn(fun() -> receive_term(Request, State) end), logger:debug("Spawned receiver~n", []), {noreply, State}; handle_cast(kick, State) -> case queue:out(State#state.hq) of {{value, Request}, Hq2} -> State2 = process_request(Request, hq, Hq2, State), {noreply, State2}; {empty, _Hq} -> case queue:out(State#state.lq) of {{value, Request}, Lq2} -> State2 = process_request(Request, lq, Lq2, State), {noreply, State2}; {empty, _Lq} -> {noreply, State} end end; handle_cast(fin, State) -> Listen = State#state.listen, Count = State#state.count, ZCount = State#state.zcount + 1, logger:debug("Fin; Listen = ~p (~p/~p)~n", [Listen, Count, ZCount]), case Listen =:= false andalso ZCount =:= Count of true -> halt(); false -> {noreply, State#state{zcount = ZCount}} end; handle_cast(_Msg, State) -> {noreply, State}. handle_info(Msg, State) -> error_logger:error_msg("Unexpected message: ~p~n", [Msg]), {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVersion, State, _Extra) -> {ok, State}. Internal init_map(Configs) -> lists:map((fun extract_mapping/1), Configs). extract_mapping(Config) -> Id = proplists:get_value(id, Config), Mod = proplists:get_value(module, Config), {Mod, Id}. try_listen(Port, 0) -> error_logger:error_msg("Could not listen on port ~p~n", [Port]), {error, "Could not listen on port"}; try_listen(Port, Times) -> Res = gen_tcp:listen(Port, [binary, {packet, 4}, {active, false}, {reuseaddr, true}, {backlog, 128}]), case Res of {ok, LSock} -> error_logger:info_msg("Listening on port ~p~n", [Port]), {ok, LSock}; {error, Reason} -> error_logger:info_msg("Could not listen on port ~p: ~p~n", [Port, Reason]), timer:sleep(5000), try_listen(Port, Times - 1) end. loop(LSock) -> case gen_tcp:accept(LSock) of {error, closed} -> logger:debug("Listen socket closed~n", []), timer:sleep(infinity); {error, Error} -> logger:debug("Connection accept error: ~p~n", [Error]), loop(LSock); {ok, Sock} -> logger:debug("Accepted socket: ~p~n", [Sock]), ernie_server:process(Sock), loop(LSock) end. receive_term(Request, State) -> Sock = Request#request.sock, case gen_tcp:recv(Sock, 0) of {ok, BinaryTerm} -> logger:debug("Got binary term: ~p~n", [BinaryTerm]), Term = binary_to_term(BinaryTerm), logger:info("Got term: ~p~n", [Term]), case Term of {call, '__admin__', Fun, Args} -> ernie_admin:process(Sock, Fun, Args, State); {info, Command, Args} -> Infos = Request#request.infos, Infos2 = [BinaryTerm | Infos], Request2 = Request#request{infos = Infos2}, Request3 = process_info(Request2, Command, Args), receive_term(Request3, State); _Any -> Request2 = Request#request{action = BinaryTerm}, close_if_cast(Term, Request2), ernie_server:enqueue_request(Request2), ernie_server:kick() end; {error, closed} -> ok = gen_tcp:close(Sock) end. process_info(Request, priority, [Priority]) -> Request#request{priority = Priority}; process_info(Request, _Command, _Args) -> Request. process_request(Request, Priority, Q2, State) -> ActionTerm = bert:decode(Request#request.action), {_Type, Mod, _Fun, _Args} = ActionTerm, Specs = lists:filter(fun({X, _Id}) -> Mod =:= X end, State#state.map), case Specs of [] -> no_module(Mod, Request, Priority, Q2, State); _Else -> process_module(ActionTerm, Specs, Request, Priority, Q2, State) end. no_module(Mod, Request, Priority, Q2, State) -> logger:debug("No such module ~p~n", [Mod]), Sock = Request#request.sock, Class = <<"ServerError">>, Message = list_to_binary(io_lib:format("No such module '~p'", [Mod])), gen_tcp:send(Sock, term_to_binary({error, [server, 0, Class, Message, []]})), ok = gen_tcp:close(Sock), finish(Priority, Q2, State). process_module(ActionTerm, [], Request, Priority, Q2, State) -> {_Type, Mod, Fun, _Args} = ActionTerm, logger:debug("No such function ~p:~p~n", [Mod, Fun]), Sock = Request#request.sock, Class = <<"ServerError">>, Message = list_to_binary(io_lib:format("No such function '~p:~p'", [Mod, Fun])), gen_tcp:send(Sock, term_to_binary({error, [server, 0, Class, Message, []]})), ok = gen_tcp:close(Sock), finish(Priority, Q2, State); process_module(ActionTerm, Specs, Request, Priority, Q2, State) -> [{_Mod, Id} | OtherSpecs] = Specs, case Id of native -> logger:debug("Dispatching to native module~n", []), {_Type, Mod, Fun, Args} = ActionTerm, case erlang:function_exported(Mod, Fun, length(Args)) of false -> logger:debug("Not found in native module ~p~n", [Mod]), process_module(ActionTerm, OtherSpecs, Request, Priority, Q2, State); true -> PredFun = list_to_atom(atom_to_list(Fun) ++ "_pred"), logger:debug("Checking ~p:~p(~p) for selection.~n", [Mod, PredFun, Args]), case erlang:function_exported(Mod, PredFun, length(Args)) of false -> logger:debug("No such predicate function ~p:~p(~p).~n", [Mod, PredFun, Args]), process_native_request(ActionTerm, Request, Priority, Q2, State); true -> case apply(Mod, PredFun, Args) of false -> logger:debug("Predicate ~p:~p(~p) returned false.~n", [Mod, PredFun, Args]), process_module(ActionTerm, OtherSpecs, Request, Priority, Q2, State); true -> logger:debug("Predicate ~p:~p(~p) returned true.~n", [Mod, PredFun, Args]), process_native_request(ActionTerm, Request, Priority, Q2, State) end end end; ValidPid when is_pid(ValidPid) -> logger:debug("Found external pid ~p~n", [ValidPid]), process_external_request(ValidPid, Request, Priority, Q2, State) end. close_if_cast(ActionTerm, Request) -> case ActionTerm of {cast, _Mod, _Fun, _Args} -> Sock = Request#request.sock, gen_tcp:send(Sock, term_to_binary({noreply})), ok = gen_tcp:close(Sock), logger:debug("Closed cast.~n", []); _Any -> ok end. finish(Priority, Q2, State) -> case Priority of hq -> State#state{hq = Q2}; lq -> State#state{lq = Q2} end. Native process_native_request(ActionTerm, Request, Priority, Q2, State) -> Count = State#state.count, State2 = State#state{count = Count + 1}, logger:debug("Count = ~p~n", [Count + 1]), Log = Request#request.log, Log2 = Log#log{type = native, tprocess = erlang:now()}, Request2 = Request#request{log = Log2}, spawn(fun() -> ernie_native:process(ActionTerm, Request2) end), finish(Priority, Q2, State2). process_external_request(Pid, Request, Priority, Q2, State) -> Count = State#state.count, State2 = State#state{count = Count + 1}, logger:debug("Count = ~p~n", [Count + 1]), case asset_pool:lease(Pid) of {ok, Asset} -> logger:debug("Leased asset for pool ~p~n", [Pid]), Log = Request#request.log, Log2 = Log#log{type = external, tprocess = erlang:now()}, Request2 = Request#request{log = Log2}, spawn(fun() -> process_now(Pid, Request2, Asset) end), finish(Priority, Q2, State2); empty -> State end. process_now(Pid, Request, Asset) -> try unsafe_process_now(Request, Asset) of _AnyResponse -> Log = Request#request.log, Log2 = Log#log{tdone = erlang:now()}, Request2 = Request#request{log = Log2}, ernie_access_logger:acc(Request2) catch AnyClass:AnyError -> Log = Request#request.log, Log2 = Log#log{tdone = erlang:now()}, Request2 = Request#request{log = Log2}, ernie_access_logger:err(Request2, "External process error ~w: ~w", [AnyClass, AnyError]) after asset_pool:return(Pid, Asset), ernie_server:fin(), ernie_server:kick(), logger:debug("Returned asset ~p~n", [Asset]), gen_tcp:close(Request#request.sock), logger:debug("Closed socket ~p~n", [Request#request.sock]) end. unsafe_process_now(Request, Asset) -> BinaryTerm = Request#request.action, Term = binary_to_term(BinaryTerm), case Term of {call, Mod, Fun, Args} -> logger:debug("Calling ~p:~p(~p)~n", [Mod, Fun, Args]), Sock = Request#request.sock, {asset, Port, Token} = Asset, logger:debug("Asset: ~p ~p~n", [Port, Token]), {ok, Data} = port_wrapper:rpc(Port, BinaryTerm), ok = gen_tcp:send(Sock, Data); {cast, Mod, Fun, Args} -> logger:debug("Casting ~p:~p(~p)~n", [Mod, Fun, Args]), {asset, Port, Token} = Asset, logger:debug("Asset: ~p ~p~n", [Port, Token]), {ok, _Data} = port_wrapper:rpc(Port, BinaryTerm) end.
4ce09ad2fc362c450eee0f2ee509ccb27725893be807cd066af896af51f75479
degree9/uikit-hl
background.cljs
(ns uikit-hl.background (:require [hoplon.core :as h])) (defn- format-background [background] (str "uk-background-" background)) (defmethod h/do! ::default [elem kw v] (h/do! elem :class {(format-background (name kw)) v}))
null
https://raw.githubusercontent.com/degree9/uikit-hl/b226b1429ea50f8e9a6c1d12c082a3be504dda33/src/uikit_hl/background.cljs
clojure
(ns uikit-hl.background (:require [hoplon.core :as h])) (defn- format-background [background] (str "uk-background-" background)) (defmethod h/do! ::default [elem kw v] (h/do! elem :class {(format-background (name kw)) v}))
0377187a6be46f6ddd623e881c42f3cb25213744c8730300062c1edf158a04b0
FranklinChen/learn-you-some-erlang
multiproc_tests.erl
-module(multiproc_tests). -include_lib("eunit/include/eunit.hrl"). %% sleep's implementation is copy/pasted from the timer module. %% not much to test to be safe. sleep_test_() -> [?_assertEqual(ok, multiproc:sleep(10))]. flush_test_() -> {spawn, [fun() -> self() ! a, self() ! b, ok = multiproc:flush(), self() ! c, [?assertEqual(receive M -> M end, c)] end]}. priority_test_() -> {spawn, [fun() -> self() ! {15, high}, self() ! {7, low}, self() ! {1, low}, self() ! {17, high}, [?assertEqual([high, high, low, low], multiproc:important())] end]}.
null
https://raw.githubusercontent.com/FranklinChen/learn-you-some-erlang/878c8bc2011a12862fe72dd7fdc6c921348c79d6/tests/multiproc_tests.erl
erlang
sleep's implementation is copy/pasted from the timer module. not much to test to be safe.
-module(multiproc_tests). -include_lib("eunit/include/eunit.hrl"). sleep_test_() -> [?_assertEqual(ok, multiproc:sleep(10))]. flush_test_() -> {spawn, [fun() -> self() ! a, self() ! b, ok = multiproc:flush(), self() ! c, [?assertEqual(receive M -> M end, c)] end]}. priority_test_() -> {spawn, [fun() -> self() ! {15, high}, self() ! {7, low}, self() ! {1, low}, self() ! {17, high}, [?assertEqual([high, high, low, low], multiproc:important())] end]}.
edbfd43a7e0f12ec46fadc4c5de725ee553bcba5aec7c73abb547c3747cfa45e
mhwombat/grid
Hexagonal.hs
------------------------------------------------------------------------ -- | Module : Math . Geometry . HexGrid Copyright : ( c ) 2012 - 2022 -- License : BSD-style -- Maintainer : -- Stability : experimental -- Portability : portable -- -- A regular arrangement of hexagonal tiles. -- The userguide, with illustrations, is available at -- <>. -- Also see @Math.Geometry.Grid@ for examples of how to use this class. -- ------------------------------------------------------------------------ # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # module Math.Geometry.Grid.Hexagonal ( -- * Unbounded grid with hexagonal tiles UnboundedHexGrid(..), -- * Hexagonal grid with hexagonal tiles HexHexGrid(..), hexHexGrid, -- * Parallelogram-shaped grid with hexagonal tiles ParaHexGrid(..), paraHexGrid ) where import Math.Geometry.Grid.HexagonalInternal
null
https://raw.githubusercontent.com/mhwombat/grid/b8c4a928733494f4a410127d6ae007857de921f9/src/Math/Geometry/Grid/Hexagonal.hs
haskell
---------------------------------------------------------------------- | License : BSD-style Maintainer : Stability : experimental Portability : portable A regular arrangement of hexagonal tiles. The userguide, with illustrations, is available at <>. Also see @Math.Geometry.Grid@ for examples of how to use this class. ---------------------------------------------------------------------- * Unbounded grid with hexagonal tiles * Hexagonal grid with hexagonal tiles * Parallelogram-shaped grid with hexagonal tiles
Module : Math . Geometry . HexGrid Copyright : ( c ) 2012 - 2022 # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # module Math.Geometry.Grid.Hexagonal ( UnboundedHexGrid(..), HexHexGrid(..), hexHexGrid, ParaHexGrid(..), paraHexGrid ) where import Math.Geometry.Grid.HexagonalInternal
4050e552e643a35cd9cfbaff2456febc360bb3246f8fdcb2d2ea0bf59a82a9d1
sadiqj/ocaml-esp32
untypeast.mli
(**************************************************************************) (* *) (* OCaml *) (* *) ( OCamlPro ) , ( INRIA Saclay ) (* *) Copyright 2007 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) open Parsetree val lident_of_path : Path.t -> Longident.t type mapper = { attribute: mapper -> Typedtree.attribute -> attribute; attributes: mapper -> Typedtree.attribute list -> attribute list; case: mapper -> Typedtree.case -> case; cases: mapper -> Typedtree.case list -> case list; class_declaration: mapper -> Typedtree.class_declaration -> class_declaration; class_description: mapper -> Typedtree.class_description -> class_description; class_expr: mapper -> Typedtree.class_expr -> class_expr; class_field: mapper -> Typedtree.class_field -> class_field; class_signature: mapper -> Typedtree.class_signature -> class_signature; class_structure: mapper -> Typedtree.class_structure -> class_structure; class_type: mapper -> Typedtree.class_type -> class_type; class_type_declaration: mapper -> Typedtree.class_type_declaration -> class_type_declaration; class_type_field: mapper -> Typedtree.class_type_field -> class_type_field; constructor_declaration: mapper -> Typedtree.constructor_declaration -> constructor_declaration; expr: mapper -> Typedtree.expression -> expression; extension_constructor: mapper -> Typedtree.extension_constructor -> extension_constructor; include_declaration: mapper -> Typedtree.include_declaration -> include_declaration; include_description: mapper -> Typedtree.include_description -> include_description; label_declaration: mapper -> Typedtree.label_declaration -> label_declaration; location: mapper -> Location.t -> Location.t; module_binding: mapper -> Typedtree.module_binding -> module_binding; module_declaration: mapper -> Typedtree.module_declaration -> module_declaration; module_expr: mapper -> Typedtree.module_expr -> module_expr; module_type: mapper -> Typedtree.module_type -> module_type; module_type_declaration: mapper -> Typedtree.module_type_declaration -> module_type_declaration; package_type: mapper -> Typedtree.package_type -> package_type; open_description: mapper -> Typedtree.open_description -> open_description; pat: mapper -> Typedtree.pattern -> pattern; row_field: mapper -> Typedtree.row_field -> row_field; object_field: mapper -> Typedtree.object_field -> object_field; signature: mapper -> Typedtree.signature -> signature; signature_item: mapper -> Typedtree.signature_item -> signature_item; structure: mapper -> Typedtree.structure -> structure; structure_item: mapper -> Typedtree.structure_item -> structure_item; typ: mapper -> Typedtree.core_type -> core_type; type_declaration: mapper -> Typedtree.type_declaration -> type_declaration; type_extension: mapper -> Typedtree.type_extension -> type_extension; type_kind: mapper -> Typedtree.type_kind -> type_kind; value_binding: mapper -> Typedtree.value_binding -> value_binding; value_description: mapper -> Typedtree.value_description -> value_description; with_constraint: mapper -> (Path.t * Longident.t Location.loc * Typedtree.with_constraint) -> with_constraint; } val default_mapper : mapper val untype_structure : ?mapper:mapper -> Typedtree.structure -> structure val untype_signature : ?mapper:mapper -> Typedtree.signature -> signature val constant : Asttypes.constant -> Parsetree.constant
null
https://raw.githubusercontent.com/sadiqj/ocaml-esp32/33aad4ca2becb9701eb90d779c1b1183aefeb578/typing/untypeast.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************
( OCamlPro ) , ( INRIA Saclay ) Copyright 2007 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Parsetree val lident_of_path : Path.t -> Longident.t type mapper = { attribute: mapper -> Typedtree.attribute -> attribute; attributes: mapper -> Typedtree.attribute list -> attribute list; case: mapper -> Typedtree.case -> case; cases: mapper -> Typedtree.case list -> case list; class_declaration: mapper -> Typedtree.class_declaration -> class_declaration; class_description: mapper -> Typedtree.class_description -> class_description; class_expr: mapper -> Typedtree.class_expr -> class_expr; class_field: mapper -> Typedtree.class_field -> class_field; class_signature: mapper -> Typedtree.class_signature -> class_signature; class_structure: mapper -> Typedtree.class_structure -> class_structure; class_type: mapper -> Typedtree.class_type -> class_type; class_type_declaration: mapper -> Typedtree.class_type_declaration -> class_type_declaration; class_type_field: mapper -> Typedtree.class_type_field -> class_type_field; constructor_declaration: mapper -> Typedtree.constructor_declaration -> constructor_declaration; expr: mapper -> Typedtree.expression -> expression; extension_constructor: mapper -> Typedtree.extension_constructor -> extension_constructor; include_declaration: mapper -> Typedtree.include_declaration -> include_declaration; include_description: mapper -> Typedtree.include_description -> include_description; label_declaration: mapper -> Typedtree.label_declaration -> label_declaration; location: mapper -> Location.t -> Location.t; module_binding: mapper -> Typedtree.module_binding -> module_binding; module_declaration: mapper -> Typedtree.module_declaration -> module_declaration; module_expr: mapper -> Typedtree.module_expr -> module_expr; module_type: mapper -> Typedtree.module_type -> module_type; module_type_declaration: mapper -> Typedtree.module_type_declaration -> module_type_declaration; package_type: mapper -> Typedtree.package_type -> package_type; open_description: mapper -> Typedtree.open_description -> open_description; pat: mapper -> Typedtree.pattern -> pattern; row_field: mapper -> Typedtree.row_field -> row_field; object_field: mapper -> Typedtree.object_field -> object_field; signature: mapper -> Typedtree.signature -> signature; signature_item: mapper -> Typedtree.signature_item -> signature_item; structure: mapper -> Typedtree.structure -> structure; structure_item: mapper -> Typedtree.structure_item -> structure_item; typ: mapper -> Typedtree.core_type -> core_type; type_declaration: mapper -> Typedtree.type_declaration -> type_declaration; type_extension: mapper -> Typedtree.type_extension -> type_extension; type_kind: mapper -> Typedtree.type_kind -> type_kind; value_binding: mapper -> Typedtree.value_binding -> value_binding; value_description: mapper -> Typedtree.value_description -> value_description; with_constraint: mapper -> (Path.t * Longident.t Location.loc * Typedtree.with_constraint) -> with_constraint; } val default_mapper : mapper val untype_structure : ?mapper:mapper -> Typedtree.structure -> structure val untype_signature : ?mapper:mapper -> Typedtree.signature -> signature val constant : Asttypes.constant -> Parsetree.constant
684b8f1ec4ccc89d0abb5b658dc9b2e51aa4cdf8bbb25d62edd275386bf524da
DSiSc/why3
unix_scheduler.mli
(********************************************************************) (* *) The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University (* *) (* This software is distributed under the terms of the GNU Lesser *) General Public License version 2.1 , with the special exception (* on linking described in file LICENSE. *) (* *) (********************************************************************) module Unix_scheduler : sig val blocking: bool val multiplier: int val timeout: ms:int -> (unit -> bool) -> unit * [ timeout ~ms f ] registers the function [ f ] as a function to be called every [ ms ] milliseconds . The function is called repeatedly until it returns false . the [ ms ] delay is not strictly guaranteed : it is only a minimum delay between the end of the last call and the beginning of the next call . Several functions can be registered at the same time . called every [ms] milliseconds. The function is called repeatedly until it returns false. the [ms] delay is not strictly guaranteed: it is only a minimum delay between the end of the last call and the beginning of the next call. Several functions can be registered at the same time. *) val idle: prio:int -> (unit -> bool) -> unit * [ idle f ] registers the function [ f ] as a function to be called whenever there is nothing else to do . Several functions can be registered at the same time . Several functions can be registered at the same time . Functions registered with higher priority will be called first . called whenever there is nothing else to do. Several functions can be registered at the same time. Several functions can be registered at the same time. Functions registered with higher priority will be called first. *) val main_loop: ?prompt:string -> (string -> 'a) -> unit end
null
https://raw.githubusercontent.com/DSiSc/why3/8ba9c2287224b53075adc51544bc377bc8ea5c75/src/tools/unix_scheduler.mli
ocaml
****************************************************************** This software is distributed under the terms of the GNU Lesser on linking described in file LICENSE. ******************************************************************
The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University General Public License version 2.1 , with the special exception module Unix_scheduler : sig val blocking: bool val multiplier: int val timeout: ms:int -> (unit -> bool) -> unit * [ timeout ~ms f ] registers the function [ f ] as a function to be called every [ ms ] milliseconds . The function is called repeatedly until it returns false . the [ ms ] delay is not strictly guaranteed : it is only a minimum delay between the end of the last call and the beginning of the next call . Several functions can be registered at the same time . called every [ms] milliseconds. The function is called repeatedly until it returns false. the [ms] delay is not strictly guaranteed: it is only a minimum delay between the end of the last call and the beginning of the next call. Several functions can be registered at the same time. *) val idle: prio:int -> (unit -> bool) -> unit * [ idle f ] registers the function [ f ] as a function to be called whenever there is nothing else to do . Several functions can be registered at the same time . Several functions can be registered at the same time . Functions registered with higher priority will be called first . called whenever there is nothing else to do. Several functions can be registered at the same time. Several functions can be registered at the same time. Functions registered with higher priority will be called first. *) val main_loop: ?prompt:string -> (string -> 'a) -> unit end
31801a77eff31128fc51a376e7b3ceab3d7d62c390066cdcfb925f2e422be38e
otabat/couchbase-clj
util.clj
(ns couchbase-clj.util (:require [clojure.data.json :as json])) (defn read-json "Reads a JSON value from input String. If data is nil, then nil is returned. If data is a empty string, then empty string is returned." [data] (when-not (nil? data) (json/read-json data true false ""))) (def ^{:doc "Wrapper of clojure.data.json/json-str. Just for convenience."} write-json json/json-str)
null
https://raw.githubusercontent.com/otabat/couchbase-clj/5f975dc85d0eec554034eefa9d97f1ee7ad9e84a/src/couchbase_clj/util.clj
clojure
(ns couchbase-clj.util (:require [clojure.data.json :as json])) (defn read-json "Reads a JSON value from input String. If data is nil, then nil is returned. If data is a empty string, then empty string is returned." [data] (when-not (nil? data) (json/read-json data true false ""))) (def ^{:doc "Wrapper of clojure.data.json/json-str. Just for convenience."} write-json json/json-str)
6078b9228dffb6722c2b4a50cd02635b37492104fd9923e4188a946f0e22d7f5
levex/wacc
CallingConvention.hs
module WACC.CodeGen.ARM.CallingConvention where import WACC.CodeGen.Types generateCallingConvention :: [Instruction] -> [Instruction] generateCallingConvention = undefined
null
https://raw.githubusercontent.com/levex/wacc/c77164f0c9aeb53d3d13a0370fdedc448b6009a3/src/WACC/CodeGen/ARM/CallingConvention.hs
haskell
module WACC.CodeGen.ARM.CallingConvention where import WACC.CodeGen.Types generateCallingConvention :: [Instruction] -> [Instruction] generateCallingConvention = undefined
07e761ebdcbf1c81e4fc452ad98dbfedc9063960e052e20b2114e862f846b610
semerdzhiev/fp-2020-21
tasks.rkt
#lang racket Задача 0 : Да се дефинира функция ( sum - divisors n a b ) , резултат сумата на числата в затворения интервал [ a , b ] , които са делители на n (define (div x y) (= (remainder x y) 0)) (define (sum-divisors n a b) ( if (> a b) 0 (+ (sum-divisors n (+ a 1) b) (if (div n a) a 0)) ) ) Задача 0 * : Да се дефинира функция ( sum - squares a b ) , резултат сумата от квадратите на числата в затворения интервал [ a , b ] (define (sum-squares a b) ( if (> a b) 0 (+ (* a a) (sum-squares (+ a 1) b)) ) ) Задача 1 * : Да се дефинира функция ( apply f x ) , резултат функцията f приложена x (define (apply f x) (f x) ) за използване на ф - я от по - висок ред (define (square x) (* x x)) ( apply square 5 ) - прилага square на аргумент 5 Задача 1 : Да се дефинира функция ( sum - mapped f a b ) , резултат сумата на резултата на изпълнението на функцията f върху [ a , b ] ; [a, b] -> SUM(f(x)), x <- [a, b] (define (sum-mapped f a b) ( if (> a b) 0 (+ (f a) (sum-mapped f (+ a 1) b)) ) ) Lambda функции : ( lambda ( arg1 arg2 ... argn ) ( ф - ята > ) ) ( sum - mapped square 1 5 ) < = > ( sum - mapped ( lambda ( x ) ( * x x ) ) 1 5 ) Задача 2 : Да се дефинира функция , която връща като резултат произведението на всички четни числа в интервала [ a , b ] 1 : (define (product-mapped f a b) ( if (> a b) 1 (* (f a) (product-mapped f (+ a 1) b)) ) ) (define (product-even a b) (product-mapped (lambda (x) (if (div x 2) x 1)) a b) ) 2 : (define (operation-mapped f a b operation neutral) ( if (> a b) neutral (operation (f a) (operation-mapped f (+ a 1) b operation neutral)) ) ) (define (product-even-2 a b) (operation-mapped (lambda (x) (if (div x 2) x 1)) a b * 1) ) Задача 3 : Да се дефинира функция , която връща като резултат броя на квадрати [ a , b ] ; floor(sqrt(x))^2 == x OR floor(sqrt(x)) == sqrt(x) (define (num-squares a b) (operation-mapped (lambda (x) (if (= (floor (sqrt x)) (sqrt x)) 1 0)) a b + 0) ) Задача 4 : Да се дефинира функция , дали в интервала [ a , b ] , за което функцията f да връща # t NB : find - elem не е много име ; ( NB2 ! : or е специална форма , дефинираме си ( lambda ( x y ) ( or x y ) ) , която го замества (define (find-elem f a b) (operation-mapped f a b (lambda (x y) (or x y)) #f) ) обща форма на : ( define ( accumulate f a b op n ) ) accumulate : извиква функция ( f ) ( [ a , b ] ) и акумулира резултат посредством някаква операция ( op ) с неутрален елемент ( n ) * : Да се дефинира функция ( bind f x ) , резултат функция , изпълнението на която е същото като изпълнението на ( f x ) (define (bind f x) (lambda () (f x))) NB : f , са функции с 1 аргумент Задача 5 : Да се дефинира функция ( compose f g ) , резултат композицията на функциите f и g (define (compose f g) (lambda (x) (f (g x)))) Задача 6 : Да се дефинира функция ( repeat f n ) , резултат функция , еквивалентна на прилагането пъти ; (repeat f n) <=> f ( f ( f ( f ( ... ( f x ) ... ) ) => n пъти (define (id x) x) (define (repeat f n) ( if (= n 0) id (lambda (x) (f ((repeat f (- n 1)) x))) ) )
null
https://raw.githubusercontent.com/semerdzhiev/fp-2020-21/64fa00c4f940f75a28cc5980275b124ca21244bc/group-c/week02/tasks.rkt
racket
[a, b] -> SUM(f(x)), x <- [a, b] floor(sqrt(x))^2 == x OR floor(sqrt(x)) == sqrt(x) ( (repeat f n) <=> f ( f ( f ( f ( ... ( f x ) ... ) ) => n пъти
#lang racket Задача 0 : Да се дефинира функция ( sum - divisors n a b ) , резултат сумата на числата в затворения интервал [ a , b ] , които са делители на n (define (div x y) (= (remainder x y) 0)) (define (sum-divisors n a b) ( if (> a b) 0 (+ (sum-divisors n (+ a 1) b) (if (div n a) a 0)) ) ) Задача 0 * : Да се дефинира функция ( sum - squares a b ) , резултат сумата от квадратите на числата в затворения интервал [ a , b ] (define (sum-squares a b) ( if (> a b) 0 (+ (* a a) (sum-squares (+ a 1) b)) ) ) Задача 1 * : Да се дефинира функция ( apply f x ) , резултат функцията f приложена x (define (apply f x) (f x) ) за използване на ф - я от по - висок ред (define (square x) (* x x)) ( apply square 5 ) - прилага square на аргумент 5 Задача 1 : Да се дефинира функция ( sum - mapped f a b ) , резултат сумата на резултата на изпълнението на функцията f върху [ a , b ] (define (sum-mapped f a b) ( if (> a b) 0 (+ (f a) (sum-mapped f (+ a 1) b)) ) ) Lambda функции : ( lambda ( arg1 arg2 ... argn ) ( ф - ята > ) ) ( sum - mapped square 1 5 ) < = > ( sum - mapped ( lambda ( x ) ( * x x ) ) 1 5 ) Задача 2 : Да се дефинира функция , която връща като резултат произведението на всички четни числа в интервала [ a , b ] 1 : (define (product-mapped f a b) ( if (> a b) 1 (* (f a) (product-mapped f (+ a 1) b)) ) ) (define (product-even a b) (product-mapped (lambda (x) (if (div x 2) x 1)) a b) ) 2 : (define (operation-mapped f a b operation neutral) ( if (> a b) neutral (operation (f a) (operation-mapped f (+ a 1) b operation neutral)) ) ) (define (product-even-2 a b) (operation-mapped (lambda (x) (if (div x 2) x 1)) a b * 1) ) Задача 3 : Да се дефинира функция , която връща като резултат броя на квадрати [ a , b ] (define (num-squares a b) (operation-mapped (lambda (x) (if (= (floor (sqrt x)) (sqrt x)) 1 0)) a b + 0) ) Задача 4 : Да се дефинира функция , дали в интервала [ a , b ] , за което функцията f да връща # t NB2 ! : or е специална форма , дефинираме си ( lambda ( x y ) ( or x y ) ) , която го замества (define (find-elem f a b) (operation-mapped f a b (lambda (x y) (or x y)) #f) ) обща форма на : ( define ( accumulate f a b op n ) ) accumulate : извиква функция ( f ) ( [ a , b ] ) и акумулира резултат посредством някаква операция ( op ) с неутрален елемент ( n ) * : Да се дефинира функция ( bind f x ) , резултат функция , изпълнението на която е същото като изпълнението на ( f x ) (define (bind f x) (lambda () (f x))) NB : f , са функции с 1 аргумент Задача 5 : Да се дефинира функция ( compose f g ) , резултат композицията на функциите f и g (define (compose f g) (lambda (x) (f (g x)))) Задача 6 : Да се дефинира функция ( repeat f n ) , резултат функция , еквивалентна на прилагането пъти (define (id x) x) (define (repeat f n) ( if (= n 0) id (lambda (x) (f ((repeat f (- n 1)) x))) ) )
76e4373f7d6c7d092d44db9dc21241a01e798ed79e4dd151a82fa6c2fe75e332
russmatney/ralphie
doctor.clj
(ns ralphie.doctor) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Doctor log ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn log [& args] (apply print (concat "\n" args "\n"))) (comment (log "Hello" "World"))
null
https://raw.githubusercontent.com/russmatney/ralphie/3b7af4a9ec2dc2b9e59036d67a66f365691f171d/src/ralphie/doctor.clj
clojure
Doctor log
(ns ralphie.doctor) (defn log [& args] (apply print (concat "\n" args "\n"))) (comment (log "Hello" "World"))
9b2d904c6ef20a40a9b62e8a73ce127ba4e5abdf64699853049e5cf7949f059b
weblocks-framework/weblocks
excerpt.lisp
(in-package :weblocks) (export '(*text-data-cutoff-threshold* excerpt excerpt-presentation excerpt-presentation-cutoff-threshold)) (defparameter *text-data-cutoff-threshold* 15 "In the excerpt mode, the number of characters to be rendered before the text is cut off and an ellipsis is inserted.") (defclass excerpt-presentation (text-presentation) ((cutoff-threshold :initform *text-data-cutoff-threshold* :accessor excerpt-presentation-cutoff-threshold :initarg :cutoff-threshold :documentation "Number of characters before the text is cut off.")) (:documentation "Presents a large amount of text as an HTML paragraph.")) (defmethod render-view-field-value (value (presentation excerpt-presentation) field view widget obj &rest args &key highlight &allow-other-keys) (if (null value) (call-next-method) (let* ((orig-item (apply #'print-view-field-value value (make-instance 'text-presentation) field view widget obj args)) (item (apply #'print-view-field-value value presentation field view widget obj args)) (lit-item (if highlight (highlight-regex-matches item highlight presentation) (escape-for-html item)))) (with-html (:span :class "value" (str lit-item) (unless (<= (length orig-item) (excerpt-presentation-cutoff-threshold presentation)) (htm (:span :class "ellipsis" "...")))))))) (defmethod print-view-field-value (value (presentation excerpt-presentation) field view widget obj &rest args) (declare (ignore obj view field args)) (let ((threshold (excerpt-presentation-cutoff-threshold presentation)) (item (call-next-method))) (if (<= (length item) threshold) item (subseq item 0 threshold))))
null
https://raw.githubusercontent.com/weblocks-framework/weblocks/fe96152458c8eb54d74751b3201db42dafe1708b/src/views/types/presentations/excerpt.lisp
lisp
(in-package :weblocks) (export '(*text-data-cutoff-threshold* excerpt excerpt-presentation excerpt-presentation-cutoff-threshold)) (defparameter *text-data-cutoff-threshold* 15 "In the excerpt mode, the number of characters to be rendered before the text is cut off and an ellipsis is inserted.") (defclass excerpt-presentation (text-presentation) ((cutoff-threshold :initform *text-data-cutoff-threshold* :accessor excerpt-presentation-cutoff-threshold :initarg :cutoff-threshold :documentation "Number of characters before the text is cut off.")) (:documentation "Presents a large amount of text as an HTML paragraph.")) (defmethod render-view-field-value (value (presentation excerpt-presentation) field view widget obj &rest args &key highlight &allow-other-keys) (if (null value) (call-next-method) (let* ((orig-item (apply #'print-view-field-value value (make-instance 'text-presentation) field view widget obj args)) (item (apply #'print-view-field-value value presentation field view widget obj args)) (lit-item (if highlight (highlight-regex-matches item highlight presentation) (escape-for-html item)))) (with-html (:span :class "value" (str lit-item) (unless (<= (length orig-item) (excerpt-presentation-cutoff-threshold presentation)) (htm (:span :class "ellipsis" "...")))))))) (defmethod print-view-field-value (value (presentation excerpt-presentation) field view widget obj &rest args) (declare (ignore obj view field args)) (let ((threshold (excerpt-presentation-cutoff-threshold presentation)) (item (call-next-method))) (if (<= (length item) threshold) item (subseq item 0 threshold))))
a00aafc994c1e4ccc663604edcc2e3510c309d003d008a69bddbba0f55a1cd2b
input-output-hk/marlowe-cardano
Channel.hs
# LANGUAGE DataKinds # # LANGUAGE NamedFieldPuns # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # module Language.Marlowe.Runtime.App.Channel ( LastSeen(..) , runContractAction , runDetection , runDiscovery ) where import Control.Concurrent (forkIO, threadDelay) import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TChan (TChan, newTChanIO, readTChan, writeTChan) import Control.Monad (forever, unless, void) import Control.Monad.IO.Class (liftIO) import Data.Aeson (object, (.=)) import Data.Text (Text) import Language.Marlowe.Core.V1.Semantics.Types (Contract) import Language.Marlowe.Runtime.App.Run (runClientWithConfig) import Language.Marlowe.Runtime.App.Stream (ContractStream(..), contractFromStream, streamAllContractIds, streamContractSteps, transactionIdFromStream) import Language.Marlowe.Runtime.App.Types (Config) import Language.Marlowe.Runtime.ChainSync.Api (TxId) import Language.Marlowe.Runtime.Core.Api (ContractId, MarloweVersionTag(V1)) import Language.Marlowe.Runtime.History.Api (ContractStep, CreateStep) import Observe.Event (Event, EventBackend, addField, withEvent) import Observe.Event.Backend (hoistEventBackend) import Observe.Event.Dynamic (DynamicEventSelector(..), DynamicField) import Observe.Event.Syntax ((≔)) import qualified Data.Map.Strict as M (Map, adjust, delete, insert, lookup) import qualified Data.Set as S (Set, insert, member) runDiscovery :: EventBackend IO r DynamicEventSelector -> Config -> Int -> IO (TChan ContractId) runDiscovery eventBackend config pollingFrequency = do channel <- newTChanIO void . forkIO . withEvent (hoistEventBackend liftIO eventBackend) (DynamicEventSelector "DiscoveryProcess") $ \event -> addField event . either (("failure" :: Text) ≔) (const $ ("success" :: Text) ≔ True) =<< runClientWithConfig config (streamAllContractIds eventBackend pollingFrequency channel) pure channel runDetection :: (Either (CreateStep 'V1) (ContractStep 'V1) -> Bool) -> EventBackend IO r DynamicEventSelector -> Config -> Int -> TChan ContractId -> IO (TChan (ContractStream 'V1)) runDetection accept eventBackend config pollingFrequency inChannel = do outChannel <- newTChanIO void . forkIO . forever . runClientWithConfig config FIXME : If ` MarloweSyncClient ` were a ` Monad ` , then we could run -- multiple actions sequentially in a single connection. . withEvent (hoistEventBackend liftIO eventBackend) (DynamicEventSelector "DetectionProcess") $ \event -> do contractId <- liftIO . atomically $ readTChan inChannel addField event $ ("contractId" :: Text) ≔ contractId -- FIXME: If there were concurrency combinators for `MarloweSyncClient`, then we -- could follow multiple contracts in parallel using the same connection. let finishOnClose = True finishOnWait = True streamContractSteps eventBackend pollingFrequency finishOnClose finishOnWait accept contractId outChannel pure outChannel data LastSeen = LastSeen { thisContractId :: ContractId , lastContract :: Contract , lastTxId :: TxId , ignoredTxIds :: S.Set TxId } deriving (Show) runContractAction :: forall r . Text -> EventBackend IO r DynamicEventSelector -> (Event IO r DynamicEventSelector DynamicField -> LastSeen -> IO ()) -> Int -> TChan (ContractStream 'V1) -> TChan ContractId -> IO () runContractAction selectorName eventBackend runInput pollingFrequency inChannel outChannel = let -- Nothing needs updating. rollback :: ContractStream 'V1 -> M.Map ContractId LastSeen -> M.Map ContractId LastSeen rollback = const id -- Remove the contract from tracking. delete :: ContractId -> M.Map ContractId LastSeen -> M.Map ContractId LastSeen delete = M.delete -- Update the contract and its latest transaction. update :: Event IO r DynamicEventSelector DynamicField -> ContractStream 'V1 -> M.Map ContractId LastSeen -> IO (M.Map ContractId LastSeen) update event cs lastSeen = let contractId = csContractId cs in case (contractId `M.lookup` lastSeen, contractFromStream cs, transactionIdFromStream cs) of (Nothing , Just contract, Just txId) -> pure $ M.insert contractId (LastSeen contractId contract txId mempty) lastSeen (Just seen, Just contract, Just txId) -> pure $ M.insert contractId (seen {lastContract = contract, lastTxId = txId}) lastSeen (Just _ , Nothing , Just _ ) -> pure $ M.delete contractId lastSeen (seen , _ , _ ) -> do -- FIXME: Diagnose and remedy situations if this ever occurs. addField event $ ("invalidContractStream" :: Text) ≔ object [ "lastContract" .= fmap lastContract seen , "lastTxId" .= fmap lastTxId seen , "contractStream" .= cs ] pure lastSeen -- Ignore the transaction in the future. ignore :: ContractId -> TxId -> M.Map ContractId LastSeen -> M.Map ContractId LastSeen ignore contractId txId lastSeen = M.adjust (\seen -> seen {ignoredTxIds = txId `S.insert` ignoredTxIds seen}) contractId lastSeen -- Revisit a contract later. revisit :: ContractId -> IO () revisit contractId = -- FIXME: This is a workaround for contract discovery not tailing past the tip of the blockchain. void . forkIO $ threadDelay pollingFrequency >> atomically (writeTChan outChannel contractId) go :: M.Map ContractId LastSeen -> IO () go lastSeen = do lastSeen' <- withEvent eventBackend (DynamicEventSelector selectorName) $ \event -> do cs <- liftIO . atomically $ readTChan inChannel addField event $ ("contractId" :: Text) ≔ csContractId cs case cs of ContractStreamStart{} -> do addField event $ ("action" :: Text) ≔ ("start" :: String) update event cs lastSeen ContractStreamContinued{} -> do addField event $ ("action" :: Text) ≔ ("continued" :: String) update event cs lastSeen ContractStreamRolledBack{} -> do addField event $ ("action" :: Text) ≔ ("rollback" :: String) pure $ rollback cs lastSeen ContractStreamWait{..} -> do addField event $ ("action" :: Text) ≔ ("wait" :: String) case csContractId `M.lookup` lastSeen of Just seen@LastSeen{lastTxId} -> do unless (lastTxId `S.member` ignoredTxIds seen) $ runInput event seen revisit csContractId pure $ ignore csContractId lastTxId lastSeen _ -> do -- FIXME: Diagnose and remedy situations if this ever occurs. addField event $ ("invalidContractStream" :: Text) ≔ object ["contractStream" .= cs] pure lastSeen ContractStreamFinish{..} -> do addField event $ ("action" :: Text) ≔ ("finish" :: String) pure $ delete csContractId lastSeen go lastSeen' in go mempty
null
https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/3c65414ea55ac58d12ea974fa40c4f0deb4cc0a6/marlowe-apps/src/Language/Marlowe/Runtime/App/Channel.hs
haskell
# LANGUAGE OverloadedStrings # multiple actions sequentially in a single connection. FIXME: If there were concurrency combinators for `MarloweSyncClient`, then we could follow multiple contracts in parallel using the same connection. Nothing needs updating. Remove the contract from tracking. Update the contract and its latest transaction. FIXME: Diagnose and remedy situations if this ever occurs. Ignore the transaction in the future. Revisit a contract later. FIXME: This is a workaround for contract discovery not tailing past the tip of the blockchain. FIXME: Diagnose and remedy situations if this ever occurs.
# LANGUAGE DataKinds # # LANGUAGE NamedFieldPuns # # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # module Language.Marlowe.Runtime.App.Channel ( LastSeen(..) , runContractAction , runDetection , runDiscovery ) where import Control.Concurrent (forkIO, threadDelay) import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TChan (TChan, newTChanIO, readTChan, writeTChan) import Control.Monad (forever, unless, void) import Control.Monad.IO.Class (liftIO) import Data.Aeson (object, (.=)) import Data.Text (Text) import Language.Marlowe.Core.V1.Semantics.Types (Contract) import Language.Marlowe.Runtime.App.Run (runClientWithConfig) import Language.Marlowe.Runtime.App.Stream (ContractStream(..), contractFromStream, streamAllContractIds, streamContractSteps, transactionIdFromStream) import Language.Marlowe.Runtime.App.Types (Config) import Language.Marlowe.Runtime.ChainSync.Api (TxId) import Language.Marlowe.Runtime.Core.Api (ContractId, MarloweVersionTag(V1)) import Language.Marlowe.Runtime.History.Api (ContractStep, CreateStep) import Observe.Event (Event, EventBackend, addField, withEvent) import Observe.Event.Backend (hoistEventBackend) import Observe.Event.Dynamic (DynamicEventSelector(..), DynamicField) import Observe.Event.Syntax ((≔)) import qualified Data.Map.Strict as M (Map, adjust, delete, insert, lookup) import qualified Data.Set as S (Set, insert, member) runDiscovery :: EventBackend IO r DynamicEventSelector -> Config -> Int -> IO (TChan ContractId) runDiscovery eventBackend config pollingFrequency = do channel <- newTChanIO void . forkIO . withEvent (hoistEventBackend liftIO eventBackend) (DynamicEventSelector "DiscoveryProcess") $ \event -> addField event . either (("failure" :: Text) ≔) (const $ ("success" :: Text) ≔ True) =<< runClientWithConfig config (streamAllContractIds eventBackend pollingFrequency channel) pure channel runDetection :: (Either (CreateStep 'V1) (ContractStep 'V1) -> Bool) -> EventBackend IO r DynamicEventSelector -> Config -> Int -> TChan ContractId -> IO (TChan (ContractStream 'V1)) runDetection accept eventBackend config pollingFrequency inChannel = do outChannel <- newTChanIO void . forkIO . forever . runClientWithConfig config FIXME : If ` MarloweSyncClient ` were a ` Monad ` , then we could run . withEvent (hoistEventBackend liftIO eventBackend) (DynamicEventSelector "DetectionProcess") $ \event -> do contractId <- liftIO . atomically $ readTChan inChannel addField event $ ("contractId" :: Text) ≔ contractId let finishOnClose = True finishOnWait = True streamContractSteps eventBackend pollingFrequency finishOnClose finishOnWait accept contractId outChannel pure outChannel data LastSeen = LastSeen { thisContractId :: ContractId , lastContract :: Contract , lastTxId :: TxId , ignoredTxIds :: S.Set TxId } deriving (Show) runContractAction :: forall r . Text -> EventBackend IO r DynamicEventSelector -> (Event IO r DynamicEventSelector DynamicField -> LastSeen -> IO ()) -> Int -> TChan (ContractStream 'V1) -> TChan ContractId -> IO () runContractAction selectorName eventBackend runInput pollingFrequency inChannel outChannel = let rollback :: ContractStream 'V1 -> M.Map ContractId LastSeen -> M.Map ContractId LastSeen rollback = const id delete :: ContractId -> M.Map ContractId LastSeen -> M.Map ContractId LastSeen delete = M.delete update :: Event IO r DynamicEventSelector DynamicField -> ContractStream 'V1 -> M.Map ContractId LastSeen -> IO (M.Map ContractId LastSeen) update event cs lastSeen = let contractId = csContractId cs in case (contractId `M.lookup` lastSeen, contractFromStream cs, transactionIdFromStream cs) of (Nothing , Just contract, Just txId) -> pure $ M.insert contractId (LastSeen contractId contract txId mempty) lastSeen (Just seen, Just contract, Just txId) -> pure $ M.insert contractId (seen {lastContract = contract, lastTxId = txId}) lastSeen (Just _ , Nothing , Just _ ) -> pure $ M.delete contractId lastSeen addField event $ ("invalidContractStream" :: Text) ≔ object [ "lastContract" .= fmap lastContract seen , "lastTxId" .= fmap lastTxId seen , "contractStream" .= cs ] pure lastSeen ignore :: ContractId -> TxId -> M.Map ContractId LastSeen -> M.Map ContractId LastSeen ignore contractId txId lastSeen = M.adjust (\seen -> seen {ignoredTxIds = txId `S.insert` ignoredTxIds seen}) contractId lastSeen revisit :: ContractId -> IO () revisit contractId = void . forkIO $ threadDelay pollingFrequency >> atomically (writeTChan outChannel contractId) go :: M.Map ContractId LastSeen -> IO () go lastSeen = do lastSeen' <- withEvent eventBackend (DynamicEventSelector selectorName) $ \event -> do cs <- liftIO . atomically $ readTChan inChannel addField event $ ("contractId" :: Text) ≔ csContractId cs case cs of ContractStreamStart{} -> do addField event $ ("action" :: Text) ≔ ("start" :: String) update event cs lastSeen ContractStreamContinued{} -> do addField event $ ("action" :: Text) ≔ ("continued" :: String) update event cs lastSeen ContractStreamRolledBack{} -> do addField event $ ("action" :: Text) ≔ ("rollback" :: String) pure $ rollback cs lastSeen ContractStreamWait{..} -> do addField event $ ("action" :: Text) ≔ ("wait" :: String) case csContractId `M.lookup` lastSeen of Just seen@LastSeen{lastTxId} -> do unless (lastTxId `S.member` ignoredTxIds seen) $ runInput event seen revisit csContractId pure $ ignore csContractId lastTxId lastSeen _ -> addField event $ ("invalidContractStream" :: Text) ≔ object ["contractStream" .= cs] pure lastSeen ContractStreamFinish{..} -> do addField event $ ("action" :: Text) ≔ ("finish" :: String) pure $ delete csContractId lastSeen go lastSeen' in go mempty
9521df02794f3bfee8c53f9c2565dd8de2c87f585edc4003438fb9cbfbf18736
gfngfn/SATySFi
lineBreakDataMap.mli
open MyUtil open CharBasis val set_from_file : abs_path -> unit val find : Uchar.t -> line_break_class val append_break_opportunity : Uchar.t list -> break_opportunity -> break_opportunity * line_break_element list
null
https://raw.githubusercontent.com/gfngfn/SATySFi/9dbd61df0ab05943b3394830c371e927df45251a/src/chardecoder/lineBreakDataMap.mli
ocaml
open MyUtil open CharBasis val set_from_file : abs_path -> unit val find : Uchar.t -> line_break_class val append_break_opportunity : Uchar.t list -> break_opportunity -> break_opportunity * line_break_element list
d3930d70eab345484e0e9c277bb4a426161dec1b4534fe5590f2cf6881559adb
discus-lang/salt
StripAnnot.hs
module Salt.Core.Transform.StripAnnot where import Salt.Core.Exp.Module import Salt.Core.Exp.Type import Salt.Core.Exp.Term import qualified Data.Map as Map --------------------------------------------------------------------------------------------------- class StripAnnot c where stripAnnot :: c a -> c () --------------------------------------------------------------------------------------------------- instance StripAnnot Module where stripAnnot mm = Module { moduleDecls = map stripAnnot $ moduleDecls mm} --------------------------------------------------------------------------------------------------- instance StripAnnot Decl where stripAnnot dd = case dd of DType d -> DType (stripAnnot d) DTerm d -> DTerm (stripAnnot d) DTest d -> DTest (stripAnnot d) DEmit d -> DEmit (stripAnnot d) instance StripAnnot DeclType where stripAnnot (DeclType _ n tps kResult tBody) = DeclType () n (map stripAnnot tps) (stripAnnot kResult) (stripAnnot tBody) instance StripAnnot DeclTerm where stripAnnot (DeclTerm _ mode n mps tsResult mBody) = DeclTerm () mode n (map stripAnnot mps) (map stripAnnot tsResult) (stripAnnot mBody) instance StripAnnot DeclTest where stripAnnot dd = case dd of DeclTestKind _ w mn t -> DeclTestKind () w mn (stripAnnot t) DeclTestType _ w mn m -> DeclTestType () w mn (stripAnnot m) DeclTestEvalType _ w mn t -> DeclTestEvalType () w mn (stripAnnot t) DeclTestEvalTerm _ w mn m -> DeclTestEvalTerm () w mn (stripAnnot m) DeclTestExec _ w mn m -> DeclTestExec () w mn (stripAnnot m) DeclTestAssert _ w mn m -> DeclTestAssert () w mn (stripAnnot m) instance StripAnnot DeclEmit where stripAnnot dd = case dd of DeclEmit _ mn m -> DeclEmit () mn (stripAnnot m) --------------------------------------------------------------------------------------------------- instance StripAnnot Type where stripAnnot tt = case tt of TAnn _ t -> stripAnnot t TRef r -> TRef (stripAnnot r) TVar u -> TVar u TAbs p t -> TAbs (stripAnnot p) (stripAnnot t) TKey k ts -> TKey k (map stripAnnot ts) instance StripAnnot TypeRef where stripAnnot tr = case tr of TRPrm n -> TRPrm n TRCon n -> TRCon n TRClo clo -> TRClo (stripAnnot clo) instance StripAnnot TypeParams where stripAnnot tps = case tps of TPAnn _ tps' -> stripAnnot tps' TPTypes bts -> TPTypes [(b, stripAnnot t) | (b, t) <- bts] instance StripAnnot TypeArgs where stripAnnot tgs = case tgs of TGAnn _ tgs' -> stripAnnot tgs' TGTypes ts -> TGTypes (map stripAnnot ts) instance StripAnnot TypeClosure where stripAnnot (TypeClosure env tps t) = TypeClosure (stripAnnot env) (stripAnnot tps) (stripAnnot t) instance StripAnnot TypeEnv where stripAnnot (TypeEnv bs) = TypeEnv (map stripAnnot bs) instance StripAnnot TypeEnvBinds where stripAnnot eb = case eb of TypeEnvTypes ts -> TypeEnvTypes (Map.map stripAnnot ts) --------------------------------------------------------------------------------------------------- instance StripAnnot Term where stripAnnot tt = case tt of MAnn _ m -> stripAnnot m MRef r -> MRef (stripAnnot r) MVar u -> MVar u MAbs p m -> MAbs (stripAnnot p) (stripAnnot m) MRec bms m -> MRec (map stripAnnot bms) (stripAnnot m) MKey k ms -> MKey k (map stripAnnot ms) instance StripAnnot TermBind where stripAnnot (MBind b mpss ts m) = MBind b (map stripAnnot mpss) (map stripAnnot ts) (stripAnnot m) instance StripAnnot TermRef where stripAnnot tr = case tr of MRVal v -> MRVal (stripAnnot v) MRPrm n -> MRCon n MRCon c -> MRCon c instance StripAnnot TermParams where stripAnnot mps = case mps of MPAnn _ m -> stripAnnot m MPTerms bms -> MPTerms [(b, stripAnnot m) | (b, m) <- bms] MPTypes bts -> MPTypes [(b, stripAnnot t) | (b, t) <- bts] instance StripAnnot TermArgs where stripAnnot mgs = case mgs of MGAnn _ mgs' -> stripAnnot mgs' MGTerm m -> MGTerm (stripAnnot m) MGTerms ms -> MGTerms (map stripAnnot ms) MGTypes ts -> MGTypes (map stripAnnot ts) instance StripAnnot Value where stripAnnot vv = case vv of VUnit -> VUnit VSymbol n -> VSymbol n VText t -> VText t VBool b -> VBool b VNat n -> VNat n VInt i -> VInt i VWord i -> VWord i VInt8 i -> VInt8 i VInt16 i -> VInt16 i VInt32 i -> VInt32 i VInt64 i -> VInt64 i VWord8 i -> VWord8 i VWord16 i -> VWord16 i VWord32 i -> VWord32 i VWord64 i -> VWord64 i VData n ts vs -> VData n (map stripAnnot ts) (map stripAnnot vs) VRecord nvss -> VRecord [ (n, map stripAnnot vs) | (n, vs) <- nvss ] VVariant n t vs -> VVariant n (stripAnnot t) (map stripAnnot vs) VList t vs -> VList (stripAnnot t) (map stripAnnot vs) VSet t vs -> VSet (stripAnnot t) vs VMap tk tv kvs -> VMap (stripAnnot tk) (stripAnnot tv) (Map.map stripAnnot kvs) VClosure clo -> VClosure (stripAnnot clo) VBundle bb -> VBundle (stripAnnot bb) VLoc t i -> VLoc (stripAnnot t) i VAddr a -> VAddr a VPtr r t a -> VPtr (stripAnnot r) (stripAnnot t) a VExtPair v ts a -> VExtPair (stripAnnot v) (map stripAnnot ts) (stripAnnot a) instance StripAnnot TermClosure where stripAnnot (TermClosure env mps m) = TermClosure (stripAnnot env) (stripAnnot mps) (stripAnnot m) instance StripAnnot TermEnv where stripAnnot (TermEnv bs) = TermEnv (map stripAnnot bs) instance StripAnnot TermEnvBinds where stripAnnot eb = case eb of TermEnvTypes ts -> TermEnvTypes (Map.map stripAnnot ts) TermEnvValues vs -> TermEnvValues (Map.map stripAnnot vs) TermEnvValuesRec vs -> TermEnvValuesRec (Map.map stripAnnot vs) instance StripAnnot Bundle where stripAnnot (Bundle nts nms) = Bundle (Map.map stripAnnot nts) (Map.map stripAnnot nms) instance StripAnnot BundleType where stripAnnot (BundleType _a n tps k t) = BundleType () n (map stripAnnot tps) (stripAnnot k) (stripAnnot t) instance StripAnnot BundleTerm where stripAnnot (BundleTerm _a n tgs ts m) = BundleTerm () n (map stripAnnot tgs) (map stripAnnot ts) (stripAnnot m)
null
https://raw.githubusercontent.com/discus-lang/salt/33c14414ac7e238fdbd8161971b8b8ac67fff569/src/salt/Salt/Core/Transform/StripAnnot.hs
haskell
------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------
module Salt.Core.Transform.StripAnnot where import Salt.Core.Exp.Module import Salt.Core.Exp.Type import Salt.Core.Exp.Term import qualified Data.Map as Map class StripAnnot c where stripAnnot :: c a -> c () instance StripAnnot Module where stripAnnot mm = Module { moduleDecls = map stripAnnot $ moduleDecls mm} instance StripAnnot Decl where stripAnnot dd = case dd of DType d -> DType (stripAnnot d) DTerm d -> DTerm (stripAnnot d) DTest d -> DTest (stripAnnot d) DEmit d -> DEmit (stripAnnot d) instance StripAnnot DeclType where stripAnnot (DeclType _ n tps kResult tBody) = DeclType () n (map stripAnnot tps) (stripAnnot kResult) (stripAnnot tBody) instance StripAnnot DeclTerm where stripAnnot (DeclTerm _ mode n mps tsResult mBody) = DeclTerm () mode n (map stripAnnot mps) (map stripAnnot tsResult) (stripAnnot mBody) instance StripAnnot DeclTest where stripAnnot dd = case dd of DeclTestKind _ w mn t -> DeclTestKind () w mn (stripAnnot t) DeclTestType _ w mn m -> DeclTestType () w mn (stripAnnot m) DeclTestEvalType _ w mn t -> DeclTestEvalType () w mn (stripAnnot t) DeclTestEvalTerm _ w mn m -> DeclTestEvalTerm () w mn (stripAnnot m) DeclTestExec _ w mn m -> DeclTestExec () w mn (stripAnnot m) DeclTestAssert _ w mn m -> DeclTestAssert () w mn (stripAnnot m) instance StripAnnot DeclEmit where stripAnnot dd = case dd of DeclEmit _ mn m -> DeclEmit () mn (stripAnnot m) instance StripAnnot Type where stripAnnot tt = case tt of TAnn _ t -> stripAnnot t TRef r -> TRef (stripAnnot r) TVar u -> TVar u TAbs p t -> TAbs (stripAnnot p) (stripAnnot t) TKey k ts -> TKey k (map stripAnnot ts) instance StripAnnot TypeRef where stripAnnot tr = case tr of TRPrm n -> TRPrm n TRCon n -> TRCon n TRClo clo -> TRClo (stripAnnot clo) instance StripAnnot TypeParams where stripAnnot tps = case tps of TPAnn _ tps' -> stripAnnot tps' TPTypes bts -> TPTypes [(b, stripAnnot t) | (b, t) <- bts] instance StripAnnot TypeArgs where stripAnnot tgs = case tgs of TGAnn _ tgs' -> stripAnnot tgs' TGTypes ts -> TGTypes (map stripAnnot ts) instance StripAnnot TypeClosure where stripAnnot (TypeClosure env tps t) = TypeClosure (stripAnnot env) (stripAnnot tps) (stripAnnot t) instance StripAnnot TypeEnv where stripAnnot (TypeEnv bs) = TypeEnv (map stripAnnot bs) instance StripAnnot TypeEnvBinds where stripAnnot eb = case eb of TypeEnvTypes ts -> TypeEnvTypes (Map.map stripAnnot ts) instance StripAnnot Term where stripAnnot tt = case tt of MAnn _ m -> stripAnnot m MRef r -> MRef (stripAnnot r) MVar u -> MVar u MAbs p m -> MAbs (stripAnnot p) (stripAnnot m) MRec bms m -> MRec (map stripAnnot bms) (stripAnnot m) MKey k ms -> MKey k (map stripAnnot ms) instance StripAnnot TermBind where stripAnnot (MBind b mpss ts m) = MBind b (map stripAnnot mpss) (map stripAnnot ts) (stripAnnot m) instance StripAnnot TermRef where stripAnnot tr = case tr of MRVal v -> MRVal (stripAnnot v) MRPrm n -> MRCon n MRCon c -> MRCon c instance StripAnnot TermParams where stripAnnot mps = case mps of MPAnn _ m -> stripAnnot m MPTerms bms -> MPTerms [(b, stripAnnot m) | (b, m) <- bms] MPTypes bts -> MPTypes [(b, stripAnnot t) | (b, t) <- bts] instance StripAnnot TermArgs where stripAnnot mgs = case mgs of MGAnn _ mgs' -> stripAnnot mgs' MGTerm m -> MGTerm (stripAnnot m) MGTerms ms -> MGTerms (map stripAnnot ms) MGTypes ts -> MGTypes (map stripAnnot ts) instance StripAnnot Value where stripAnnot vv = case vv of VUnit -> VUnit VSymbol n -> VSymbol n VText t -> VText t VBool b -> VBool b VNat n -> VNat n VInt i -> VInt i VWord i -> VWord i VInt8 i -> VInt8 i VInt16 i -> VInt16 i VInt32 i -> VInt32 i VInt64 i -> VInt64 i VWord8 i -> VWord8 i VWord16 i -> VWord16 i VWord32 i -> VWord32 i VWord64 i -> VWord64 i VData n ts vs -> VData n (map stripAnnot ts) (map stripAnnot vs) VRecord nvss -> VRecord [ (n, map stripAnnot vs) | (n, vs) <- nvss ] VVariant n t vs -> VVariant n (stripAnnot t) (map stripAnnot vs) VList t vs -> VList (stripAnnot t) (map stripAnnot vs) VSet t vs -> VSet (stripAnnot t) vs VMap tk tv kvs -> VMap (stripAnnot tk) (stripAnnot tv) (Map.map stripAnnot kvs) VClosure clo -> VClosure (stripAnnot clo) VBundle bb -> VBundle (stripAnnot bb) VLoc t i -> VLoc (stripAnnot t) i VAddr a -> VAddr a VPtr r t a -> VPtr (stripAnnot r) (stripAnnot t) a VExtPair v ts a -> VExtPair (stripAnnot v) (map stripAnnot ts) (stripAnnot a) instance StripAnnot TermClosure where stripAnnot (TermClosure env mps m) = TermClosure (stripAnnot env) (stripAnnot mps) (stripAnnot m) instance StripAnnot TermEnv where stripAnnot (TermEnv bs) = TermEnv (map stripAnnot bs) instance StripAnnot TermEnvBinds where stripAnnot eb = case eb of TermEnvTypes ts -> TermEnvTypes (Map.map stripAnnot ts) TermEnvValues vs -> TermEnvValues (Map.map stripAnnot vs) TermEnvValuesRec vs -> TermEnvValuesRec (Map.map stripAnnot vs) instance StripAnnot Bundle where stripAnnot (Bundle nts nms) = Bundle (Map.map stripAnnot nts) (Map.map stripAnnot nms) instance StripAnnot BundleType where stripAnnot (BundleType _a n tps k t) = BundleType () n (map stripAnnot tps) (stripAnnot k) (stripAnnot t) instance StripAnnot BundleTerm where stripAnnot (BundleTerm _a n tgs ts m) = BundleTerm () n (map stripAnnot tgs) (map stripAnnot ts) (stripAnnot m)
0b2366629d7cea78532f6905ef4d3c7473bad2b9cea6b9e454b47e8c5ade3a30
DSiSc/why3
loc.ml
(********************************************************************) (* *) The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University (* *) (* This software is distributed under the terms of the GNU Lesser *) General Public License version 2.1 , with the special exception (* on linking described in file LICENSE. *) (* *) (********************************************************************) type lexing_loc = Lexing.position * Lexing.position type lexing_loc = Lexing.position * Lexing.position *) open Lexing let current_offset = ref 0 let reloc p = { p with pos_cnum = p.pos_cnum + !current_offset } let set_file file lb = lb.Lexing.lex_curr_p <- { lb.Lexing.lex_curr_p with Lexing.pos_fname = file } let transfer_loc lb_from lb_to = lb_to.lex_start_p <- lb_from.lex_start_p; lb_to.lex_curr_p <- lb_from.lex_curr_p (*s Error locations. *) (* dead code let finally ff f x = let y = try f x with e -> ff (); raise e in ff (); y *) open Format s Line number let report_line fmt l = fmt " % s:%d : " l.pos_fname l.pos_lnum let report_line fmt l = fprintf fmt "%s:%d:" l.pos_fname l.pos_lnum *) type position = string * int * int * int let user_position fname lnum cnum1 cnum2 = (fname,lnum,cnum1,cnum2) let get loc = loc let dummy_position = ("",0,0,0) let join (f1,l1,b1,e1) (f2,_,b2,e2) = assert (f1 = f2); (f1,l1,b1,e1+e2-b2) let extract (b,e) = let f = b.pos_fname in let l = b.pos_lnum in let fc = b.pos_cnum - b.pos_bol in let lc = e.pos_cnum - b.pos_bol in (f,l,fc,lc) let compare = Pervasives.compare let equal = Pervasives.(=) let hash = Hashtbl.hash let gen_report_position fmt (f,l,b,e) = fprintf fmt "File \"%s\", line %d, characters %d-%d" f l b e let report_position fmt = fprintf fmt "%a:@\n" gen_report_position (* located exceptions *) exception Located of position * exn let error ?loc e = match loc with | Some loc -> raise (Located (loc, e)) | None -> raise e let try1 ?loc f x = if Debug.test_flag Debug.stack_trace then f x else try f x with Located _ as e -> raise e | e -> error ?loc e let try2 ?loc f x y = if Debug.test_flag Debug.stack_trace then f x y else try f x y with Located _ as e -> raise e | e -> error ?loc e let try3 ?loc f x y z = if Debug.test_flag Debug.stack_trace then f x y z else try f x y z with Located _ as e -> raise e | e -> error ?loc e let try4 ?loc f x y z t = if Debug.test_flag Debug.stack_trace then f x y z t else try f x y z t with Located _ as e -> raise e | e -> error ?loc e let try5 ?loc f x y z t u = if Debug.test_flag Debug.stack_trace then f x y z t u else try f x y z t u with Located _ as e -> raise e | e -> error ?loc e let try6 ?loc f x y z t u v = if Debug.test_flag Debug.stack_trace then f x y z t u v else try f x y z t u v with Located _ as e -> raise e | e -> error ?loc e let try7 ?loc f x y z t u v w = if Debug.test_flag Debug.stack_trace then f x y z t u v w else try f x y z t u v w with Located _ as e -> raise e | e -> error ?loc e (* located messages *) exception Message of string let errorm ?loc f = let buf = Buffer.create 512 in let fmt = Format.formatter_of_buffer buf in Format.kfprintf (fun _ -> Format.pp_print_flush fmt (); let s = Buffer.contents buf in Buffer.clear buf; error ?loc (Message s)) fmt ("@[" ^^ f ^^ "@]") let () = Exn_printer.register (fun fmt exn -> match exn with | Located (loc,e) -> fprintf fmt "%a%a" report_position loc Exn_printer.exn_printer e | Message s -> fprintf fmt "%s" s | _ -> raise exn) let loc lb = extract (Lexing.lexeme_start_p lb, Lexing.lexeme_end_p lb) let with_location f lb = if Debug.test_flag Debug.stack_trace then f lb else try f lb with | Located _ as e -> raise e | e -> raise (Located (loc lb, e))
null
https://raw.githubusercontent.com/DSiSc/why3/8ba9c2287224b53075adc51544bc377bc8ea5c75/src/util/loc.ml
ocaml
****************************************************************** This software is distributed under the terms of the GNU Lesser on linking described in file LICENSE. ****************************************************************** s Error locations. dead code let finally ff f x = let y = try f x with e -> ff (); raise e in ff (); y located exceptions located messages
The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University General Public License version 2.1 , with the special exception type lexing_loc = Lexing.position * Lexing.position type lexing_loc = Lexing.position * Lexing.position *) open Lexing let current_offset = ref 0 let reloc p = { p with pos_cnum = p.pos_cnum + !current_offset } let set_file file lb = lb.Lexing.lex_curr_p <- { lb.Lexing.lex_curr_p with Lexing.pos_fname = file } let transfer_loc lb_from lb_to = lb_to.lex_start_p <- lb_from.lex_start_p; lb_to.lex_curr_p <- lb_from.lex_curr_p open Format s Line number let report_line fmt l = fmt " % s:%d : " l.pos_fname l.pos_lnum let report_line fmt l = fprintf fmt "%s:%d:" l.pos_fname l.pos_lnum *) type position = string * int * int * int let user_position fname lnum cnum1 cnum2 = (fname,lnum,cnum1,cnum2) let get loc = loc let dummy_position = ("",0,0,0) let join (f1,l1,b1,e1) (f2,_,b2,e2) = assert (f1 = f2); (f1,l1,b1,e1+e2-b2) let extract (b,e) = let f = b.pos_fname in let l = b.pos_lnum in let fc = b.pos_cnum - b.pos_bol in let lc = e.pos_cnum - b.pos_bol in (f,l,fc,lc) let compare = Pervasives.compare let equal = Pervasives.(=) let hash = Hashtbl.hash let gen_report_position fmt (f,l,b,e) = fprintf fmt "File \"%s\", line %d, characters %d-%d" f l b e let report_position fmt = fprintf fmt "%a:@\n" gen_report_position exception Located of position * exn let error ?loc e = match loc with | Some loc -> raise (Located (loc, e)) | None -> raise e let try1 ?loc f x = if Debug.test_flag Debug.stack_trace then f x else try f x with Located _ as e -> raise e | e -> error ?loc e let try2 ?loc f x y = if Debug.test_flag Debug.stack_trace then f x y else try f x y with Located _ as e -> raise e | e -> error ?loc e let try3 ?loc f x y z = if Debug.test_flag Debug.stack_trace then f x y z else try f x y z with Located _ as e -> raise e | e -> error ?loc e let try4 ?loc f x y z t = if Debug.test_flag Debug.stack_trace then f x y z t else try f x y z t with Located _ as e -> raise e | e -> error ?loc e let try5 ?loc f x y z t u = if Debug.test_flag Debug.stack_trace then f x y z t u else try f x y z t u with Located _ as e -> raise e | e -> error ?loc e let try6 ?loc f x y z t u v = if Debug.test_flag Debug.stack_trace then f x y z t u v else try f x y z t u v with Located _ as e -> raise e | e -> error ?loc e let try7 ?loc f x y z t u v w = if Debug.test_flag Debug.stack_trace then f x y z t u v w else try f x y z t u v w with Located _ as e -> raise e | e -> error ?loc e exception Message of string let errorm ?loc f = let buf = Buffer.create 512 in let fmt = Format.formatter_of_buffer buf in Format.kfprintf (fun _ -> Format.pp_print_flush fmt (); let s = Buffer.contents buf in Buffer.clear buf; error ?loc (Message s)) fmt ("@[" ^^ f ^^ "@]") let () = Exn_printer.register (fun fmt exn -> match exn with | Located (loc,e) -> fprintf fmt "%a%a" report_position loc Exn_printer.exn_printer e | Message s -> fprintf fmt "%s" s | _ -> raise exn) let loc lb = extract (Lexing.lexeme_start_p lb, Lexing.lexeme_end_p lb) let with_location f lb = if Debug.test_flag Debug.stack_trace then f lb else try f lb with | Located _ as e -> raise e | e -> raise (Located (loc lb, e))
055bff9cbc5cc8006b0c15d4eae2e722a9f028a31ee44accf0fd560c70c52e1b
robrix/starlight
Text.hs
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingVia # # LANGUAGE FlexibleInstances # # LANGUAGE NamedFieldPuns # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeApplications # module UI.Label.Text ( shader , U(..) , sampler_ , colour_ , V(..) , Frag(..) ) where import Control.Lens (Lens') import Data.Coerce import Data.Functor.I import Data.Generics.Product.Fields import Foreign.Storable (Storable) import GHC.Generics (Generic) import GL.Shader.DSL shader :: Shader shader => shader U V Frag shader = vertex (\ _ V{ pos } IF{ uv } -> main $ do uv .= (pos * xy 1 (-1)) * 0.5 + 0.5 gl_Position .= coerce (ext4 (ext3 (pos * xy 1 (-1)) 0) 1)) >>> fragment (\ U{ sampler, colour } IF{ uv } Frag{ fragColour } -> main $ do -- Get samples for -2/3 and -1/3 valueL <- let' "valueL" $ texture sampler (xy (uv^._x + dFdx (uv^._x)) (uv^._y))^._yz * 255 lowerL <- let' "lowerL" $ mod' valueL 16 upperL <- let' "upperL" $ (valueL - lowerL) / 16 alphaL <- let' "alphaL" $ min' (abs (upperL - lowerL)) 2 Get samples for 0 , +1/3 , and +2/3 valueR <- let' "valueR" $ texture sampler uv ^. _xyz * 255 lowerR <- let' "lowerR" $ mod' valueR 16 upperR <- let' "upperR" $ (valueR - lowerR) / 16 alphaR <- let' "alphaR" $ min' (abs (upperR - lowerR)) 2 -- Average the energy over the pixels on either side rgba <- let' "rgba" $ xyzw ((alphaR ^. _x + alphaR ^. _y + alphaR ^. _z) / 6) ((alphaL ^. _y + alphaR ^. _x + alphaR ^. _y) / 6) ((alphaL ^. _x + alphaL ^. _y + alphaR ^. _x) / 6) 0 iff (colour ^. _x `eq` 0) (fragColour .= 1 - rgba) (fragColour .= colour * rgba)) data U v = U { sampler :: v TextureUnit , colour :: v (Colour Float) } deriving (Generic) instance Vars U sampler_ :: Lens' (U v) (v TextureUnit) sampler_ = field @"sampler" colour_ :: Lens' (U v) (v (Colour Float)) colour_ = field @"colour" newtype V v = V { pos :: v (V2 Float) } deriving (Generic) instance Vars V deriving via Fields V instance Storable (V I) newtype IF v = IF { uv :: v (V2 Float) } deriving (Generic) instance Vars IF
null
https://raw.githubusercontent.com/robrix/starlight/ad80ab74dc2eedbb52a75ac8ce507661d32f488e/src/UI/Label/Text.hs
haskell
Get samples for -2/3 and -1/3 Average the energy over the pixels on either side
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingVia # # LANGUAGE FlexibleInstances # # LANGUAGE NamedFieldPuns # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeApplications # module UI.Label.Text ( shader , U(..) , sampler_ , colour_ , V(..) , Frag(..) ) where import Control.Lens (Lens') import Data.Coerce import Data.Functor.I import Data.Generics.Product.Fields import Foreign.Storable (Storable) import GHC.Generics (Generic) import GL.Shader.DSL shader :: Shader shader => shader U V Frag shader = vertex (\ _ V{ pos } IF{ uv } -> main $ do uv .= (pos * xy 1 (-1)) * 0.5 + 0.5 gl_Position .= coerce (ext4 (ext3 (pos * xy 1 (-1)) 0) 1)) >>> fragment (\ U{ sampler, colour } IF{ uv } Frag{ fragColour } -> main $ do valueL <- let' "valueL" $ texture sampler (xy (uv^._x + dFdx (uv^._x)) (uv^._y))^._yz * 255 lowerL <- let' "lowerL" $ mod' valueL 16 upperL <- let' "upperL" $ (valueL - lowerL) / 16 alphaL <- let' "alphaL" $ min' (abs (upperL - lowerL)) 2 Get samples for 0 , +1/3 , and +2/3 valueR <- let' "valueR" $ texture sampler uv ^. _xyz * 255 lowerR <- let' "lowerR" $ mod' valueR 16 upperR <- let' "upperR" $ (valueR - lowerR) / 16 alphaR <- let' "alphaR" $ min' (abs (upperR - lowerR)) 2 rgba <- let' "rgba" $ xyzw ((alphaR ^. _x + alphaR ^. _y + alphaR ^. _z) / 6) ((alphaL ^. _y + alphaR ^. _x + alphaR ^. _y) / 6) ((alphaL ^. _x + alphaL ^. _y + alphaR ^. _x) / 6) 0 iff (colour ^. _x `eq` 0) (fragColour .= 1 - rgba) (fragColour .= colour * rgba)) data U v = U { sampler :: v TextureUnit , colour :: v (Colour Float) } deriving (Generic) instance Vars U sampler_ :: Lens' (U v) (v TextureUnit) sampler_ = field @"sampler" colour_ :: Lens' (U v) (v (Colour Float)) colour_ = field @"colour" newtype V v = V { pos :: v (V2 Float) } deriving (Generic) instance Vars V deriving via Fields V instance Storable (V I) newtype IF v = IF { uv :: v (V2 Float) } deriving (Generic) instance Vars IF
21880b55fb53a77ef7557d03c5da88ab922079c8dde3f9851dcda29cc0f8badc
haskell-opengl/OpenGLRaw
VertexAttribInteger64Bit.hs
# LANGUAGE PatternSynonyms # -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.NV.VertexAttribInteger64Bit Copyright : ( c ) 2019 -- License : BSD3 -- Maintainer : < > -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.NV.VertexAttribInteger64Bit ( -- * Extension Support glGetNVVertexAttribInteger64Bit, gl_NV_vertex_attrib_integer_64bit, -- * Enums pattern GL_INT64_NV, pattern GL_UNSIGNED_INT64_NV, -- * Functions glGetVertexAttribLi64vNV, glGetVertexAttribLui64vNV, glVertexAttribL1i64NV, glVertexAttribL1i64vNV, glVertexAttribL1ui64NV, glVertexAttribL1ui64vNV, glVertexAttribL2i64NV, glVertexAttribL2i64vNV, glVertexAttribL2ui64NV, glVertexAttribL2ui64vNV, glVertexAttribL3i64NV, glVertexAttribL3i64vNV, glVertexAttribL3ui64NV, glVertexAttribL3ui64vNV, glVertexAttribL4i64NV, glVertexAttribL4i64vNV, glVertexAttribL4ui64NV, glVertexAttribL4ui64vNV, glVertexAttribLFormatNV ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
null
https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/NV/VertexAttribInteger64Bit.hs
haskell
------------------------------------------------------------------------------ | Module : Graphics.GL.NV.VertexAttribInteger64Bit License : BSD3 Stability : stable Portability : portable ------------------------------------------------------------------------------ * Extension Support * Enums * Functions
# LANGUAGE PatternSynonyms # Copyright : ( c ) 2019 Maintainer : < > module Graphics.GL.NV.VertexAttribInteger64Bit ( glGetNVVertexAttribInteger64Bit, gl_NV_vertex_attrib_integer_64bit, pattern GL_INT64_NV, pattern GL_UNSIGNED_INT64_NV, glGetVertexAttribLi64vNV, glGetVertexAttribLui64vNV, glVertexAttribL1i64NV, glVertexAttribL1i64vNV, glVertexAttribL1ui64NV, glVertexAttribL1ui64vNV, glVertexAttribL2i64NV, glVertexAttribL2i64vNV, glVertexAttribL2ui64NV, glVertexAttribL2ui64vNV, glVertexAttribL3i64NV, glVertexAttribL3i64vNV, glVertexAttribL3ui64NV, glVertexAttribL3ui64vNV, glVertexAttribL4i64NV, glVertexAttribL4i64vNV, glVertexAttribL4ui64NV, glVertexAttribL4ui64vNV, glVertexAttribLFormatNV ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
9587d483cd8ae3e1ba9761d98949a862c17fdb7d78b9cc19932b5609e07d2cf0
onedata/op-worker
opt_datasets.erl
%%%------------------------------------------------------------------- @author ( C ) 2021 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . %%% @end %%%------------------------------------------------------------------- %%% @doc %%% Utility functions for manipulating datasets in CT tests. %%% @end %%%------------------------------------------------------------------- -module(opt_datasets). -author("Bartosz Walkowicz"). -include("modules/fslogic/acl.hrl"). -include("modules/dataset/dataset.hrl"). -export([ list_top_datasets/5, list_children_datasets/4, establish/3, establish/4, get_info/3, reattach_dataset/3, detach_dataset/3, update/6, remove/3, get_file_eff_summary/3 ]). -define(CALL(NodeSelector, Args), try opw_test_rpc:insecure_call(NodeSelector, mi_datasets, ?FUNCTION_NAME, Args) of ok -> ok; __RESULT -> {ok, __RESULT} catch throw:__ERROR -> __ERROR end ). %%%=================================================================== %%% API %%%=================================================================== -spec list_top_datasets( oct_background:node_selector(), session:id(), od_space:id(), dataset:state(), dataset_api:listing_opts() ) -> {ok, {dataset_api:entries(), boolean()}} | errors:error(). list_top_datasets(NodeSelector, SessionId, SpaceId, State, Opts) -> ?CALL(NodeSelector, [SessionId, SpaceId, State, Opts, undefined]). -spec list_children_datasets( oct_background:node_selector(), session:id(), dataset:id(), dataset_api:listing_opts() ) -> {ok, {dataset_api:entries(), boolean()}} | errors:error(). list_children_datasets(NodeSelector, SessionId, DatasetId, Opts) -> ?CALL(NodeSelector, [SessionId, DatasetId, Opts, undefined]). -spec establish(oct_background:node_selector(), session:id(), lfm:file_key()) -> {ok, dataset:id()} | errors:error(). establish(NodeSelector, SessionId, FileKey) -> establish(NodeSelector, SessionId, FileKey, 0). -spec establish( oct_background:node_selector(), session:id(), lfm:file_key(), data_access_control:bitmask() ) -> {ok, dataset:id()} | errors:error(). establish(NodeSelector, SessionId, FileKey, ProtectionFlags) -> ?CALL(NodeSelector, [SessionId, FileKey, ProtectionFlags]). -spec get_info(oct_background:node_selector(), session:id(), dataset:id()) -> {ok, dataset_api:info()} | errors:error(). get_info(NodeSelector, SessionId, DatasetId) -> ?CALL(NodeSelector, [SessionId, DatasetId]). -spec reattach_dataset(oct_background:node_selector(), session:id(), dataset:id()) -> ok | errors:error(). reattach_dataset(NodeSelector, SessionId, DatasetId) -> update(NodeSelector, SessionId, DatasetId, ?ATTACHED_DATASET, ?no_flags_mask, ?no_flags_mask). -spec detach_dataset(oct_background:node_selector(), session:id(), dataset:id()) -> ok | errors:error(). detach_dataset(NodeSelector, SessionId, DatasetId) -> update(NodeSelector, SessionId, DatasetId, ?DETACHED_DATASET, ?no_flags_mask, ?no_flags_mask). -spec update( oct_background:node_selector(), session:id(), dataset:id(), undefined | dataset:state(), data_access_control:bitmask(), data_access_control:bitmask() ) -> ok | errors:error(). update(NodeSelector, SessionId, DatasetId, NewState, FlagsToSet, FlagsToUnset) -> ?CALL(NodeSelector, [SessionId, DatasetId, NewState, FlagsToSet, FlagsToUnset]). -spec remove(oct_background:node_selector(), session:id(), dataset:id()) -> ok | errors:error(). remove(NodeSelector, SessionId, DatasetId) -> ?CALL(NodeSelector, [SessionId, DatasetId]). -spec get_file_eff_summary(oct_background:node_selector(), session:id(), lfm:file_key()) -> {ok, dataset_api:file_eff_summary()} | errors:error(). get_file_eff_summary(NodeSelector, SessionId, FileKey) -> ?CALL(NodeSelector, [SessionId, FileKey]).
null
https://raw.githubusercontent.com/onedata/op-worker/c874e554c5cef4d4099b8a68b28d3441a885b82d/test_distributed/utils/opt/opt_datasets.erl
erlang
------------------------------------------------------------------- @end ------------------------------------------------------------------- @doc Utility functions for manipulating datasets in CT tests. @end ------------------------------------------------------------------- =================================================================== API ===================================================================
@author ( C ) 2021 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . -module(opt_datasets). -author("Bartosz Walkowicz"). -include("modules/fslogic/acl.hrl"). -include("modules/dataset/dataset.hrl"). -export([ list_top_datasets/5, list_children_datasets/4, establish/3, establish/4, get_info/3, reattach_dataset/3, detach_dataset/3, update/6, remove/3, get_file_eff_summary/3 ]). -define(CALL(NodeSelector, Args), try opw_test_rpc:insecure_call(NodeSelector, mi_datasets, ?FUNCTION_NAME, Args) of ok -> ok; __RESULT -> {ok, __RESULT} catch throw:__ERROR -> __ERROR end ). -spec list_top_datasets( oct_background:node_selector(), session:id(), od_space:id(), dataset:state(), dataset_api:listing_opts() ) -> {ok, {dataset_api:entries(), boolean()}} | errors:error(). list_top_datasets(NodeSelector, SessionId, SpaceId, State, Opts) -> ?CALL(NodeSelector, [SessionId, SpaceId, State, Opts, undefined]). -spec list_children_datasets( oct_background:node_selector(), session:id(), dataset:id(), dataset_api:listing_opts() ) -> {ok, {dataset_api:entries(), boolean()}} | errors:error(). list_children_datasets(NodeSelector, SessionId, DatasetId, Opts) -> ?CALL(NodeSelector, [SessionId, DatasetId, Opts, undefined]). -spec establish(oct_background:node_selector(), session:id(), lfm:file_key()) -> {ok, dataset:id()} | errors:error(). establish(NodeSelector, SessionId, FileKey) -> establish(NodeSelector, SessionId, FileKey, 0). -spec establish( oct_background:node_selector(), session:id(), lfm:file_key(), data_access_control:bitmask() ) -> {ok, dataset:id()} | errors:error(). establish(NodeSelector, SessionId, FileKey, ProtectionFlags) -> ?CALL(NodeSelector, [SessionId, FileKey, ProtectionFlags]). -spec get_info(oct_background:node_selector(), session:id(), dataset:id()) -> {ok, dataset_api:info()} | errors:error(). get_info(NodeSelector, SessionId, DatasetId) -> ?CALL(NodeSelector, [SessionId, DatasetId]). -spec reattach_dataset(oct_background:node_selector(), session:id(), dataset:id()) -> ok | errors:error(). reattach_dataset(NodeSelector, SessionId, DatasetId) -> update(NodeSelector, SessionId, DatasetId, ?ATTACHED_DATASET, ?no_flags_mask, ?no_flags_mask). -spec detach_dataset(oct_background:node_selector(), session:id(), dataset:id()) -> ok | errors:error(). detach_dataset(NodeSelector, SessionId, DatasetId) -> update(NodeSelector, SessionId, DatasetId, ?DETACHED_DATASET, ?no_flags_mask, ?no_flags_mask). -spec update( oct_background:node_selector(), session:id(), dataset:id(), undefined | dataset:state(), data_access_control:bitmask(), data_access_control:bitmask() ) -> ok | errors:error(). update(NodeSelector, SessionId, DatasetId, NewState, FlagsToSet, FlagsToUnset) -> ?CALL(NodeSelector, [SessionId, DatasetId, NewState, FlagsToSet, FlagsToUnset]). -spec remove(oct_background:node_selector(), session:id(), dataset:id()) -> ok | errors:error(). remove(NodeSelector, SessionId, DatasetId) -> ?CALL(NodeSelector, [SessionId, DatasetId]). -spec get_file_eff_summary(oct_background:node_selector(), session:id(), lfm:file_key()) -> {ok, dataset_api:file_eff_summary()} | errors:error(). get_file_eff_summary(NodeSelector, SessionId, FileKey) -> ?CALL(NodeSelector, [SessionId, FileKey]).
6a7118c092e0f971f230e48d23c26a030d9ced8981090b6ce12de321050f1774
Bogdanp/racket-kafka
99-publish-consume-for-a-while.rkt
#lang racket/base (require kafka kafka/consumer kafka/producer racket/format rackunit rackunit/text-ui) (define N 10000) (define P 8) (define t "99-publish-consume-for-a-while") (run-tests (test-suite "publish-consume-for-a-while" #:before (lambda () (define k (make-client)) (delete-topics k t) (create-topics k (make-CreateTopic #:name t #:partitions P)) (disconnect-all k)) #:after (lambda () (define k (make-client)) (delete-topics k t) (disconnect-all k)) (let () (define msgs null) (define msg-ch (make-channel)) (define g "publish-consume-for-a-while-group") (define consumer-ch (make-channel)) (define consumer-thds (for/list ([i (in-range P)]) (thread (lambda () (let join-loop () (with-handlers ([exn:fail:kafka:server? (lambda (e) (define code (exn:fail:kafka:server-code e)) (case (error-code-symbol code) [(coordinator-not-available rebalance-in-progress) (join-loop)] [else (raise e)]))]) (define k (make-client #:id (~a "consumer-" i))) (define c (make-consumer k g t)) (let loop () (sync (handle-evt consumer-ch (lambda (_) (consumer-stop c) (disconnect-all k))) (handle-evt (consume-evt c) (lambda (type data) (case type [(records) (consumer-commit c) (for ([r (in-vector data)]) (channel-put msg-ch (record-value r))) (loop)] [else (loop)]))))))))))) (define producer-ch (make-channel)) (define producer-thd (thread (lambda () (define k (make-client #:id "producer")) (define p (make-producer k #:flush-interval 500)) (let loop ([n 0] [evts null]) (cond [(= (length evts) 500) (time (for-each sync evts)) (printf "published 500~n") (loop n null)] [(< n N) (define produce-evt (produce p t #"k" #"v" #:partition (modulo n 8))) (sleep (/ (random 5) 1000.0)) (loop (add1 n) (cons produce-evt evts))] [else (time (for-each sync evts)) (printf "publish done~n") (sync producer-ch) (disconnect-all k)]))))) (let loop ([n 0]) (when (zero? (modulo n 100)) (printf "received ~s~n" n)) (unless (= n N) (set! msgs (cons (channel-get msg-ch) msgs)) (loop (add1 n)))) (channel-put producer-ch '(stop)) (thread-wait producer-thd) (for ([_ (in-range P)]) (channel-put consumer-ch '(stop))) (for-each thread-wait consumer-thds))))
null
https://raw.githubusercontent.com/Bogdanp/racket-kafka/3b1fef63c05449150759d5ee22805c4673ae1d4d/tests/99-publish-consume-for-a-while.rkt
racket
#lang racket/base (require kafka kafka/consumer kafka/producer racket/format rackunit rackunit/text-ui) (define N 10000) (define P 8) (define t "99-publish-consume-for-a-while") (run-tests (test-suite "publish-consume-for-a-while" #:before (lambda () (define k (make-client)) (delete-topics k t) (create-topics k (make-CreateTopic #:name t #:partitions P)) (disconnect-all k)) #:after (lambda () (define k (make-client)) (delete-topics k t) (disconnect-all k)) (let () (define msgs null) (define msg-ch (make-channel)) (define g "publish-consume-for-a-while-group") (define consumer-ch (make-channel)) (define consumer-thds (for/list ([i (in-range P)]) (thread (lambda () (let join-loop () (with-handlers ([exn:fail:kafka:server? (lambda (e) (define code (exn:fail:kafka:server-code e)) (case (error-code-symbol code) [(coordinator-not-available rebalance-in-progress) (join-loop)] [else (raise e)]))]) (define k (make-client #:id (~a "consumer-" i))) (define c (make-consumer k g t)) (let loop () (sync (handle-evt consumer-ch (lambda (_) (consumer-stop c) (disconnect-all k))) (handle-evt (consume-evt c) (lambda (type data) (case type [(records) (consumer-commit c) (for ([r (in-vector data)]) (channel-put msg-ch (record-value r))) (loop)] [else (loop)]))))))))))) (define producer-ch (make-channel)) (define producer-thd (thread (lambda () (define k (make-client #:id "producer")) (define p (make-producer k #:flush-interval 500)) (let loop ([n 0] [evts null]) (cond [(= (length evts) 500) (time (for-each sync evts)) (printf "published 500~n") (loop n null)] [(< n N) (define produce-evt (produce p t #"k" #"v" #:partition (modulo n 8))) (sleep (/ (random 5) 1000.0)) (loop (add1 n) (cons produce-evt evts))] [else (time (for-each sync evts)) (printf "publish done~n") (sync producer-ch) (disconnect-all k)]))))) (let loop ([n 0]) (when (zero? (modulo n 100)) (printf "received ~s~n" n)) (unless (= n N) (set! msgs (cons (channel-get msg-ch) msgs)) (loop (add1 n)))) (channel-put producer-ch '(stop)) (thread-wait producer-thd) (for ([_ (in-range P)]) (channel-put consumer-ch '(stop))) (for-each thread-wait consumer-thds))))
68e769e4da957d79615c3d21bf0ec7575a68dfc77e4ab7e93121701270dcfc05
LightAndLight/qtt
Main.hs
# language LambdaCase # # language TypeApplications # module Main where import Test.Hspec import Test.Pretty import Test.Typecheck import Test.Unify main :: IO () main = hspec $ do prettySpec typecheckSpec unifySpec
null
https://raw.githubusercontent.com/LightAndLight/qtt/08a3ee8361178ad13bba659af4751b55c91081b7/test/Main.hs
haskell
# language LambdaCase # # language TypeApplications # module Main where import Test.Hspec import Test.Pretty import Test.Typecheck import Test.Unify main :: IO () main = hspec $ do prettySpec typecheckSpec unifySpec
1c3ac528c9da90ac60834015d8fb81abf8fb81ec6fbb514920be61b6f3eafddf
jeffshrager/biobike
sbbio.lisp
(require 'asdf) (in-package :sb-impl) (defun string-hash (str) (sxhash (string-upcase str))) (define-hash-table-test 'string-equal #'string-equal #'string-hash) (defun in-biodir (path) (format nil "~A/~A" (posix-getenv "BIODIR") path)) (let ((biodir (posix-getenv "BIODIR"))) (push (in-biodir "uffi/") asdf:*central-registry*) (push (in-biodir "clsql/") asdf:*central-registry*)) (asdf:operate 'asdf:load-op :uffi) (asdf:operate 'asdf:load-op :clsql) ( asdf : operate ' asdf : load - op : clsql - mysql ) (load (in-biodir "clinit.cl")) (load (in-biodir "portableaserve/INSTALL.lisp")) (load (in-biodir "clocc/load-xml.lisp"))
null
https://raw.githubusercontent.com/jeffshrager/biobike/5313ec1fe8e82c21430d645e848ecc0386436f57/BioLisp/Portability/sbbio.lisp
lisp
(require 'asdf) (in-package :sb-impl) (defun string-hash (str) (sxhash (string-upcase str))) (define-hash-table-test 'string-equal #'string-equal #'string-hash) (defun in-biodir (path) (format nil "~A/~A" (posix-getenv "BIODIR") path)) (let ((biodir (posix-getenv "BIODIR"))) (push (in-biodir "uffi/") asdf:*central-registry*) (push (in-biodir "clsql/") asdf:*central-registry*)) (asdf:operate 'asdf:load-op :uffi) (asdf:operate 'asdf:load-op :clsql) ( asdf : operate ' asdf : load - op : clsql - mysql ) (load (in-biodir "clinit.cl")) (load (in-biodir "portableaserve/INSTALL.lisp")) (load (in-biodir "clocc/load-xml.lisp"))
162983982915c2b072f8cf9a19e31a34e1760fe441b95e436029e048ab90c638
thosmos/riverdb
mutations.cljs
(ns riverdb.api.mutations (:require [com.fulcrologic.fulcro.algorithms.data-targeting :as dt :refer [process-target]] [com.fulcrologic.fulcro.algorithms.normalize :as norm] [com.fulcrologic.fulcro.algorithms.normalized-state :refer [remove-ident]] [com.fulcrologic.fulcro.application :as fapp] [com.fulcrologic.fulcro.mutations :refer [defmutation]] [com.fulcrologic.semantic-ui.collections.message.ui-message :refer [ui-message]] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.networking.http-remote :as http-remote] [theta.log :as log :refer [debug]] [riverdb.application :refer [SPA]] [riverdb.ui.lookups :as looks] [riverdb.util :as util :refer [sort-maps-by]] [com.fulcrologic.fulcro.algorithms.merge :as merge] [com.fulcrologic.fulcro.algorithms.form-state :as fs] [com.fulcrologic.fulcro.mutations :as fm] [com.fulcrologic.fulcro.algorithms.data-targeting :as targeting] [com.fulcrologic.fulcro.dom :as dom :refer [div]] [com.fulcrologic.fulcro.algorithms.tempid :as tempid] [com.fulcrologic.rad.routing :as rroute] [com.fulcrologic.rad.routing.history :as hist] [com.fulcrologic.rad.routing.html5-history :as hist5 :refer [url->route apply-route!]] [riverdb.ui.routes :as routes] [com.rpl.specter :as sp] [com.fulcrologic.fulcro.routing.dynamic-routing :as dr] [edn-query-language.core :as eql])) ;;; CLIENT (defn set-root-key* [state key value] (assoc state key value)) (defmutation set-root-key "generic mutation to set a root key" [{:keys [key value]}] (action [{:keys [state]}] (do (debug "SET ROOT KEY" key value) (swap! state set-root-key* key value)))) (defn set-root-key! [k v] (comp/transact! SPA `[(set-root-key {:key ~k :value ~v})])) (defmutation merge-ident [{:keys [ident props]}] (action [{:keys [state]}] (swap! state merge/merge-ident ident props))) (defn merge-ident! [ident props] (comp/transact! SPA `[(merge-ident {:ident ~ident :props ~props})])) (defn merge-idents* [state ident-k ident-v coll & targets] (debug "MERGE IDENT" ident-k ident-v targets) (reduce (fn [st m] (let [ident [ident-k (get m ident-v)] st (merge/merge-ident st ident m) st' (if targets (apply dt/integrate-ident* st ident targets) st)] st')) state coll)) (defmutation merge-idents "merge a collection of maps that conform to the ident of the comp c" [{:keys [ident-k ident-v coll targets]}] (action [{:keys [state]}] (debug "MERGE IDENTS" ident-k ident-v targets) (swap! state (fn [st] (reduce (fn [st m] (let [ident [ident-k (get m ident-v)] st (merge/merge-ident st ident m) st' (if targets (apply dt/integrate-ident* st ident targets) st)] st')) st coll))))) (defn merge-idents! [ident-k ident-v coll & targets] (comp/transact! SPA `[(merge-idents {:ident-k ~ident-k :ident-v ~ident-v :coll ~coll :targets ~targets})])) ;(defmutation attempt-login ; "Fulcro mutation: Attempt to log in the user. Triggers a server interaction to see if there is already a cookie." ; [{:keys [uid]}] ; (action [{:keys [state]}] ; (swap! state assoc ; :current-user {:id uid :name ""} ; :server-down false)) ; (remote [env] true)) ;(defmutation server-down ; "Fulcro mutation: Called if the server does not respond so we can show an error." ; [p] ; (action [{:keys [state]}] (swap! state assoc :server-down true))) (defmutation hide-server-error "" [p] (action [{:keys [state]}] (swap! state dissoc :fulcro/server-error))) (defmutation clear-new-user "Fulcro mutation: Used for returning to the sign-in page from the login link. Clears the form." [ignored] (action [{:keys [state]}] (let [uid (util/uuid) new-user {:uid uid :name "" :password "" :password2 ""} user-ident [:user/by-id uid]] (swap! state (fn [s] (-> s (assoc :user/by-id {}) ; clear all users (assoc-in user-ident new-user) (assoc-in [:new-user :page :form] user-ident))))))) (def get-year-fn (fn [ui-year years] (if (some #{ui-year} years) ui-year (when-let [year (first years)] year)))) (defsc Agency [_ _] {:ident [:org.riverdb.db.agencylookup/gid :db/id] :query [:db/id]}) (defsc Project [_ _] {:ident [:org.riverdb.db.projectslookup/gid :db/id], :query [:db/id :riverdb.entity/ns :projectslookup/Active :projectslookup/ProjectID :projectslookup/Name {:projectslookup/AgencyRef (comp/get-query Agency)}]}) (defmutation process-project-years [{:keys [desired-route proj-k]}] (action [{:keys [state]}] (debug (clojure.string/upper-case "process-project-years")) (let [agency-project-years (get-in @state [:component/id :proj-years :agency-project-years]) _ (debug "agency-project-years" agency-project-years) current-project (get @state :ui.riverdb/current-project) current-year (get @state :ui.riverdb/current-year) proj-k (or proj-k (if current-project (keyword (:projectslookup/ProjectID current-project)) (ffirst agency-project-years))) project (when proj-k (get-in agency-project-years [proj-k :project])) sites (when proj-k (get-in agency-project-years [proj-k :sites])) years (when proj-k (get-in agency-project-years [proj-k :years])) year (when years (get-year-fn current-year years))] (swap! state (fn [st] (cond-> st project (merge/merge-component Project project :replace [:ui.riverdb/current-project]) sites (-> (set-root-key* :ui.riverdb/current-project-sites []) (merge-idents* :org.riverdb.db.stationlookup/gid :db/id sites :append [:ui.riverdb/current-project-sites])) year (set-root-key* :ui.riverdb/current-year year)))) (when desired-route (debug "ROUTE TO desired-route" desired-route) (let [params (:params desired-route) rad? (:_rp_ params)] (if rad? (do (log/debug "RAD ROUTE" desired-route) (hist5/apply-route! SPA desired-route)) (do (log/debug "NON-RAD ROUTE" desired-route) (dr/change-route! SPA (:route desired-route)) (hist/replace-route! SPA (:route desired-route) (:params desired-route))))))))) (defmutation process-tac-report "TAC Report post process" [p] (action [{:keys [state]}] (do (debug "TAC POST PROCESS" p) (swap! state update-in [:tac-report-data :no-results-rs] sort-maps-by [:site :date])))) ;(swap! state update-in [:tac-report-data :results-rs] sort-maps-by [:date :site]) ;(swap! state update-in [:tac-report-page :page :field-count] inc) (defmutation clear-tac-report "clear :tac-report-data from local state" [p] (action [{:keys [state]}] (do (debug "CLEAR TAC DATA") (swap! state dissoc :tac-report-data)))) (defmutation set-current-agency "" [{:keys [agency key]}] (action [{:keys [state]}] (do (debug "SET CURRENT AGENCY" key agency) (swap! state assoc key agency)))) (defmutation clear-agency-project-years "" [{:keys [ident]}] (action [{:keys [state]}] (do (debug "CLEAR AGENCY PROJECT YEARS") (swap! state update-in ident (fn [st] (-> st (dissoc :agency-project-years) (dissoc :ui/project-code) (dissoc :ui/proj-year))))))) (defmutation process-all-years "All Years post process" [p] (action [{:keys [state]}] (do (debug "POST PROCESS ALL YEARS" p) (swap! state update :all-years-data sort-maps-by [:date])))) (defmutation sort-years [p] (action [{:keys [state]}] (do (debug "SORT YEARS") (swap! state update :all-sitevisit-years (partial sort >))))) (defmutation set-project [p] (action [{:keys [state]}] (let [prj (:ui/project-code p)] (debug "MUTATION set-project" prj) (swap! state assoc-in [:myvals :project] prj)))) (defmutation process-agency-project-years [p] (action [{:keys [state]}] (debug "process-agency-project-years") (swap! state update :agency-project-years (fn [prjs] (reduce-kv (fn [prjs k v] (assoc-in prjs [k :years] (vec (sort > (:years v))))) prjs prjs))))) (defmutation refresh [p] (action [_] (debug "NOP just to refresh the current component"))) (defmutation update-report-year [p] (action [{:keys [state]}] (let [year (:year p) year (if-not (= year "") (js/parseInt year) year)] (debug "MUTATE REPORT YEAR" year) (swap! state assoc-in [:tac-report-page :page :ui/year] year)))) (defn sort-ident-list-by* "Sort the idents in the list path by the indicated field. Returns the new app-state." ([state path sort-fn] (sort-ident-list-by* state path sort-fn nil)) ([state path sort-fn ident-key] (let [idents (get-in state path []) ident-key (or ident-key (ffirst idents)) items (map (fn [ident] (get-in state ident)) idents) sorted-items (sort-by sort-fn items) new-idents (mapv (fn [item] [ident-key (:db/id item)]) sorted-items)] ;(debug "SORTED" new-idents) (assoc-in state path new-idents)))) (defmutation sort-ident-list-by "sorts a seq of maps at target location by running sort-fn on the maps" [{:keys [idents-path sort-fn ident-key]}] (action [{:keys [state]}] (debug "SORTING SITES") (swap! state sort-ident-list-by* idents-path sort-fn ident-key))) (defmutation save-project [{:keys [id diff]}] (action [{:keys [state]}] (swap! state (fn [s] (-> s ; update the pristine state (fs/entity->pristine* [:org.riverdb.db.projectslookup/gid id]))))) (remote [env] true)) (defmutation reset-form [{:keys [ident]}] (action [{:keys [state]}] (debug "RESET FORM" ident "DIRTY" (get-in @state ident) "PRISTINE" (-> @state (fs/pristine->entity* ident) (get-in ident))) (swap! state fs/pristine->entity* ident))) (defmutation cancel-new-form! [{:keys [ident]}] (action [{:keys [state]}] (debug "MUTATION cancel-new-form!" ident))) (defmutation set-enum [{:keys [key value]}] (action [{:keys [state component]}] (let [comp-ident (comp/get-ident component)] (debug "set-enum" comp-ident key value) (if (eql/ident? value) (swap! state #(-> % (assoc-in (conj comp-ident key) value) (fs/mark-complete* comp-ident key))) (log/error "set-enum requires an ident as a value"))))) (defn set-enum! [this key value] (comp/transact! this [(set-enum {:key key :value value})])) (defn clear-tx-result* [state] ;(debug "CLEAR TX RESULT") (assoc state :root/tx-result {})) (defmutation clear-tx-result [{:keys [] :as params}] (action [{:keys [state]}] (swap! state clear-tx-result*))) (defn clear-tx-result! [] (comp/transact! SPA `[(clear-tx-result)])) (defn show-tx-result* [state result] ( debug " SHOW TX RESULT " ) (when-not (:error result) (js/setTimeout clear-tx-result! 2000)) (assoc state :root/tx-result result)) (defmutation show-tx-result [result] (action [{:keys [state]}] (swap! state (fn [s] (assoc-in s [:root/tx-result] result))))) (defn show-tx-result! [result] (comp/transact! SPA `[(show-tx-result ~result)])) (defn set-create* [state ident creating] (assoc-in state (conj ident :ui/create) creating)) (defn set-saving* [state ident busy] (assoc-in state (conj ident :ui/saving) busy)) (defmutation set-saving [{:keys [ident busy]}] (action [{:keys [state]}] (swap! state set-saving* ident busy))) (defn set-saving! [ident busy] (comp/transact! SPA `[(set-saving {:ident ~ident :busy ~busy})])) (comp/defsc TxResult [this {:keys [result msgs error com.wsscode.pathom.core/reader-error]}] {:query [:result :msgs :error :com.wsscode.pathom.core/reader-error :sticky] :initial-state {:result nil :msgs nil :error nil :com.wsscode.pathom.core/reader-error nil :sticky false} :componentDidMount (fn [this] (let [props (comp/props this)] ;(debug "DID MOUNT TxResult" "props" props) (when (and (not (:error props)) (not (:sticky props))) (js/setTimeout clear-tx-result! 2000))))} (let [error (or error reader-error)] ( debug " " " error " error " result " result ) (div {:style {:position "fixed" :top "50px" :left 0 :right 0 :maxWidth 500 :margin "auto" :zIndex 1000}} (if error (ui-message {:error true} (div :.content {} (div :.ui.right.floated.negative.button {:onClick clear-tx-result!} "OK") (div :.header {} "Error") (div :.horizontal.items (div :.item error)) (when msgs (map-indexed (fn [i msg] (dom/p {:key i} msg)) msgs)))) (ui-message {:success true :onDismiss clear-tx-result!} (div :.content {} (div :.header {} "Success") (dom/p {} result) (when msgs (map-indexed (fn [i msg] (dom/p {:key i} msg)) msgs)))))))) (def ui-tx-result (comp/factory TxResult)) (defn remove-ident* "Removes an ident, if it exists, from a list of idents in app state. This function is safe to use within mutations." [state-map ident path-to-idents] {:pre [(map? state-map)]} (let [new-list (fn [old-list] (vec (filter #(not= ident %) old-list)))] (update-in state-map path-to-idents new-list))) (fm/defmutation delete-sample [{:keys [sv-ident sa-ident]}] (action [{:keys [state]}] (debug "MUTATION delete sample" sv-ident sa-ident) (swap! state (fn [s] (let [sas-path (conj sv-ident :sitevisit/Samples) _ (debug "samples BEFORE" (get-in s sas-path)) res (-> s (remove-ident* sa-ident sas-path) (fs/mark-complete* sv-ident :sitevisit/Samples)) _ (debug "samples AFTER" (get-in res sas-path))] res))))) (defn del-sample [sv-ident sa-ident] (comp/transact! SPA `[(delete-sample ~{:sv-ident sv-ident :sa-ident sa-ident})])) (defmutation set-pristine "changes a form's current state to pristine" [{:keys [ident]}] (action [{:keys [state]}] (swap! state fs/entity->pristine* ident))) (defn set-pristine! [ident] (comp/transact! SPA `[(set-pristine {:ident ~ident})])) (defn get-new-ident [env ident] (if-let [new-ident-v (get-in env [:tempid->realid (second ident)])] [(first ident) new-ident-v] ident)) (defmutation save-entity "saves an entity diff to the backend Datomic DB" [{:keys [ident diff delete] :as params}] (action [{:keys [state]}] (if delete (debug "DELETE ENTITY" ident) (debug "SAVE ENTITY" ident)) (swap! state set-saving* ident true)) (remote [{:keys [state] :as env}] (debug "SAVE ENTITY REMOTE" (:ui.riverdb/current-agency @state)) (-> env (update-in [:ast :params] #(-> % (dissoc :post-mutation) (dissoc :post-params) (dissoc :success-msg) (assoc :agency (get-in @state [:ui.riverdb/current-agency 1])))) ;; remove reverse keys (update-in [:ast :params :diff] (fn [diff] (let [new-diff (sp/transform [sp/ALL sp/LAST sp/ALL] #(when (not (and (keyword? (first %)) (= "_" (first (name (first %)))))) %) diff)] (debug "DIFF" new-diff) new-diff))) (fm/returning TxResult) (fm/with-target [:root/tx-result]))) (ok-action [{:keys [state result] :as env}] (debug "OK ACTION" "IDENT" ident "REF" (:ref env) "result" result "(comp/get-ident (:component env))" (comp/get-ident (:component env))) (debug ":tempid->realid" (:tempid->realid env)) (debug "TRANSACTED AST" (:transacted-ast env)) (if-let [ok-err (get-in result [:body `save-entity :error])] (do (debug "OK ERROR" ok-err) (swap! state (fn [s] (-> s (set-saving* ident false))))) (try (let [{:keys [post-mutation post-params success-msg delete]} (get-in env [:transacted-ast :params]) ident (get-new-ident env ident)] (if delete (swap! state (fn [s] (-> s (show-tx-result* {:result (or success-msg "Delete Succeeded")}) (set-saving* ident false) (dissoc ident)))) (swap! state (fn [s] (-> s (fs/entity->pristine* ident) (show-tx-result* {:result (or success-msg "Save Succeeded")}) (set-saving* ident false) (set-create* ident false))))) (when post-mutation (let [tempid (get-in env [:transacted-ast :params :ident 1]) new-id (get-in env [:tempid->realid tempid]) params (if new-id (assoc post-params :new-id new-id) params) txd `[(~post-mutation ~params)]] (comp/transact! SPA txd)))) (catch js/Object ex (let [ident (get-new-ident env ident)] (log/error "OK Action handler failed: " ex) (swap! state (fn [st] (-> st (set-saving* ident false) (assoc-in [:root/tx-result :error] (str "TX Result Handler failed: " ex)))))))))) (error-action [{:keys [app ref result state] :as env}] (log/info "Mutation Error Result " ident diff result) (swap! state (fn [s] (-> s (set-saving* ident false) (#(if-let [err (get-in result [:error-text])] (assoc-in % [:root/tx-result :error] err) %))))))) (defsc UploadResult [this props] {:query [:errors :msgs]} (debug "UploadResult" props)) (defmutation upload-files [{:keys [config progress-target] :as params}] (action [{:keys [state]}] (debug "UPLOAD FILES" config)) (remote [env] (-> env (fm/returning UploadResult))) (progress-action [{:keys [progress state] :as env}] ;(debug "PROGRESS" progress) (swap! state assoc-in progress-target (http-remote/overall-progress env))) (ok-action [{:keys [state result] :as env}] (let [ident (comp/get-ident (:component env)) {:keys [tempids errors msgs] :as res} (get-in result [:body `upload-files])] (debug "UPLOAD OK" ident res result) (if (seq errors) (do (log/error "OK ERROR" (first errors)) (swap! state (fn [s] (-> s (assoc-in [:root/tx-result :error] (str (if (= (count errors) 1) (first errors) errors))) (assoc-in (conj ident :ui/import-error?) true) (cond-> (seq msgs) (assoc-in [:root/tx-result :msgs] msgs)))))) (swap! state (fn [s] (-> s (assoc-in [:root/tx-result :result] "Import completed") (cond-> (seq msgs) (-> (assoc-in [:root/tx-result :msgs] msgs) (assoc-in [:root/tx-result :sticky] true))))))))) (error-action [{:keys [app ref result state] :as env}] (let [ident (comp/get-ident (:component env)) reader-error (get-in result [:body `upload-files :com.wsscode.pathom.core/reader-error]) error-text (get-in result [:error-text])] (log/error "UPLOAD FILES ERROR" ident result) (when (or reader-error error-text) (swap! state (fn [s] (-> s (assoc-in [:root/tx-result :error] (or reader-error error-text)) (assoc-in (conj ident :ui/import-error?) true) (cond->))))))))
null
https://raw.githubusercontent.com/thosmos/riverdb/9c8dd8d73405e703475e6b78bfdfb943dee27df3/src/main/riverdb/api/mutations.cljs
clojure
CLIENT (defmutation attempt-login "Fulcro mutation: Attempt to log in the user. Triggers a server interaction to see if there is already a cookie." [{:keys [uid]}] (action [{:keys [state]}] (swap! state assoc :current-user {:id uid :name ""} :server-down false)) (remote [env] true)) (defmutation server-down "Fulcro mutation: Called if the server does not respond so we can show an error." [p] (action [{:keys [state]}] (swap! state assoc :server-down true))) clear all users (swap! state update-in [:tac-report-data :results-rs] sort-maps-by [:date :site]) (swap! state update-in [:tac-report-page :page :field-count] inc) (debug "SORTED" new-idents) update the pristine state (debug "CLEAR TX RESULT") (debug "DID MOUNT TxResult" "props" props) remove reverse keys (debug "PROGRESS" progress)
(ns riverdb.api.mutations (:require [com.fulcrologic.fulcro.algorithms.data-targeting :as dt :refer [process-target]] [com.fulcrologic.fulcro.algorithms.normalize :as norm] [com.fulcrologic.fulcro.algorithms.normalized-state :refer [remove-ident]] [com.fulcrologic.fulcro.application :as fapp] [com.fulcrologic.fulcro.mutations :refer [defmutation]] [com.fulcrologic.semantic-ui.collections.message.ui-message :refer [ui-message]] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.networking.http-remote :as http-remote] [theta.log :as log :refer [debug]] [riverdb.application :refer [SPA]] [riverdb.ui.lookups :as looks] [riverdb.util :as util :refer [sort-maps-by]] [com.fulcrologic.fulcro.algorithms.merge :as merge] [com.fulcrologic.fulcro.algorithms.form-state :as fs] [com.fulcrologic.fulcro.mutations :as fm] [com.fulcrologic.fulcro.algorithms.data-targeting :as targeting] [com.fulcrologic.fulcro.dom :as dom :refer [div]] [com.fulcrologic.fulcro.algorithms.tempid :as tempid] [com.fulcrologic.rad.routing :as rroute] [com.fulcrologic.rad.routing.history :as hist] [com.fulcrologic.rad.routing.html5-history :as hist5 :refer [url->route apply-route!]] [riverdb.ui.routes :as routes] [com.rpl.specter :as sp] [com.fulcrologic.fulcro.routing.dynamic-routing :as dr] [edn-query-language.core :as eql])) (defn set-root-key* [state key value] (assoc state key value)) (defmutation set-root-key "generic mutation to set a root key" [{:keys [key value]}] (action [{:keys [state]}] (do (debug "SET ROOT KEY" key value) (swap! state set-root-key* key value)))) (defn set-root-key! [k v] (comp/transact! SPA `[(set-root-key {:key ~k :value ~v})])) (defmutation merge-ident [{:keys [ident props]}] (action [{:keys [state]}] (swap! state merge/merge-ident ident props))) (defn merge-ident! [ident props] (comp/transact! SPA `[(merge-ident {:ident ~ident :props ~props})])) (defn merge-idents* [state ident-k ident-v coll & targets] (debug "MERGE IDENT" ident-k ident-v targets) (reduce (fn [st m] (let [ident [ident-k (get m ident-v)] st (merge/merge-ident st ident m) st' (if targets (apply dt/integrate-ident* st ident targets) st)] st')) state coll)) (defmutation merge-idents "merge a collection of maps that conform to the ident of the comp c" [{:keys [ident-k ident-v coll targets]}] (action [{:keys [state]}] (debug "MERGE IDENTS" ident-k ident-v targets) (swap! state (fn [st] (reduce (fn [st m] (let [ident [ident-k (get m ident-v)] st (merge/merge-ident st ident m) st' (if targets (apply dt/integrate-ident* st ident targets) st)] st')) st coll))))) (defn merge-idents! [ident-k ident-v coll & targets] (comp/transact! SPA `[(merge-idents {:ident-k ~ident-k :ident-v ~ident-v :coll ~coll :targets ~targets})])) (defmutation hide-server-error "" [p] (action [{:keys [state]}] (swap! state dissoc :fulcro/server-error))) (defmutation clear-new-user "Fulcro mutation: Used for returning to the sign-in page from the login link. Clears the form." [ignored] (action [{:keys [state]}] (let [uid (util/uuid) new-user {:uid uid :name "" :password "" :password2 ""} user-ident [:user/by-id uid]] (swap! state (fn [s] (-> s (assoc-in user-ident new-user) (assoc-in [:new-user :page :form] user-ident))))))) (def get-year-fn (fn [ui-year years] (if (some #{ui-year} years) ui-year (when-let [year (first years)] year)))) (defsc Agency [_ _] {:ident [:org.riverdb.db.agencylookup/gid :db/id] :query [:db/id]}) (defsc Project [_ _] {:ident [:org.riverdb.db.projectslookup/gid :db/id], :query [:db/id :riverdb.entity/ns :projectslookup/Active :projectslookup/ProjectID :projectslookup/Name {:projectslookup/AgencyRef (comp/get-query Agency)}]}) (defmutation process-project-years [{:keys [desired-route proj-k]}] (action [{:keys [state]}] (debug (clojure.string/upper-case "process-project-years")) (let [agency-project-years (get-in @state [:component/id :proj-years :agency-project-years]) _ (debug "agency-project-years" agency-project-years) current-project (get @state :ui.riverdb/current-project) current-year (get @state :ui.riverdb/current-year) proj-k (or proj-k (if current-project (keyword (:projectslookup/ProjectID current-project)) (ffirst agency-project-years))) project (when proj-k (get-in agency-project-years [proj-k :project])) sites (when proj-k (get-in agency-project-years [proj-k :sites])) years (when proj-k (get-in agency-project-years [proj-k :years])) year (when years (get-year-fn current-year years))] (swap! state (fn [st] (cond-> st project (merge/merge-component Project project :replace [:ui.riverdb/current-project]) sites (-> (set-root-key* :ui.riverdb/current-project-sites []) (merge-idents* :org.riverdb.db.stationlookup/gid :db/id sites :append [:ui.riverdb/current-project-sites])) year (set-root-key* :ui.riverdb/current-year year)))) (when desired-route (debug "ROUTE TO desired-route" desired-route) (let [params (:params desired-route) rad? (:_rp_ params)] (if rad? (do (log/debug "RAD ROUTE" desired-route) (hist5/apply-route! SPA desired-route)) (do (log/debug "NON-RAD ROUTE" desired-route) (dr/change-route! SPA (:route desired-route)) (hist/replace-route! SPA (:route desired-route) (:params desired-route))))))))) (defmutation process-tac-report "TAC Report post process" [p] (action [{:keys [state]}] (do (debug "TAC POST PROCESS" p) (swap! state update-in [:tac-report-data :no-results-rs] sort-maps-by [:site :date])))) (defmutation clear-tac-report "clear :tac-report-data from local state" [p] (action [{:keys [state]}] (do (debug "CLEAR TAC DATA") (swap! state dissoc :tac-report-data)))) (defmutation set-current-agency "" [{:keys [agency key]}] (action [{:keys [state]}] (do (debug "SET CURRENT AGENCY" key agency) (swap! state assoc key agency)))) (defmutation clear-agency-project-years "" [{:keys [ident]}] (action [{:keys [state]}] (do (debug "CLEAR AGENCY PROJECT YEARS") (swap! state update-in ident (fn [st] (-> st (dissoc :agency-project-years) (dissoc :ui/project-code) (dissoc :ui/proj-year))))))) (defmutation process-all-years "All Years post process" [p] (action [{:keys [state]}] (do (debug "POST PROCESS ALL YEARS" p) (swap! state update :all-years-data sort-maps-by [:date])))) (defmutation sort-years [p] (action [{:keys [state]}] (do (debug "SORT YEARS") (swap! state update :all-sitevisit-years (partial sort >))))) (defmutation set-project [p] (action [{:keys [state]}] (let [prj (:ui/project-code p)] (debug "MUTATION set-project" prj) (swap! state assoc-in [:myvals :project] prj)))) (defmutation process-agency-project-years [p] (action [{:keys [state]}] (debug "process-agency-project-years") (swap! state update :agency-project-years (fn [prjs] (reduce-kv (fn [prjs k v] (assoc-in prjs [k :years] (vec (sort > (:years v))))) prjs prjs))))) (defmutation refresh [p] (action [_] (debug "NOP just to refresh the current component"))) (defmutation update-report-year [p] (action [{:keys [state]}] (let [year (:year p) year (if-not (= year "") (js/parseInt year) year)] (debug "MUTATE REPORT YEAR" year) (swap! state assoc-in [:tac-report-page :page :ui/year] year)))) (defn sort-ident-list-by* "Sort the idents in the list path by the indicated field. Returns the new app-state." ([state path sort-fn] (sort-ident-list-by* state path sort-fn nil)) ([state path sort-fn ident-key] (let [idents (get-in state path []) ident-key (or ident-key (ffirst idents)) items (map (fn [ident] (get-in state ident)) idents) sorted-items (sort-by sort-fn items) new-idents (mapv (fn [item] [ident-key (:db/id item)]) sorted-items)] (assoc-in state path new-idents)))) (defmutation sort-ident-list-by "sorts a seq of maps at target location by running sort-fn on the maps" [{:keys [idents-path sort-fn ident-key]}] (action [{:keys [state]}] (debug "SORTING SITES") (swap! state sort-ident-list-by* idents-path sort-fn ident-key))) (defmutation save-project [{:keys [id diff]}] (action [{:keys [state]}] (swap! state (fn [s] (-> s (fs/entity->pristine* [:org.riverdb.db.projectslookup/gid id]))))) (remote [env] true)) (defmutation reset-form [{:keys [ident]}] (action [{:keys [state]}] (debug "RESET FORM" ident "DIRTY" (get-in @state ident) "PRISTINE" (-> @state (fs/pristine->entity* ident) (get-in ident))) (swap! state fs/pristine->entity* ident))) (defmutation cancel-new-form! [{:keys [ident]}] (action [{:keys [state]}] (debug "MUTATION cancel-new-form!" ident))) (defmutation set-enum [{:keys [key value]}] (action [{:keys [state component]}] (let [comp-ident (comp/get-ident component)] (debug "set-enum" comp-ident key value) (if (eql/ident? value) (swap! state #(-> % (assoc-in (conj comp-ident key) value) (fs/mark-complete* comp-ident key))) (log/error "set-enum requires an ident as a value"))))) (defn set-enum! [this key value] (comp/transact! this [(set-enum {:key key :value value})])) (defn clear-tx-result* [state] (assoc state :root/tx-result {})) (defmutation clear-tx-result [{:keys [] :as params}] (action [{:keys [state]}] (swap! state clear-tx-result*))) (defn clear-tx-result! [] (comp/transact! SPA `[(clear-tx-result)])) (defn show-tx-result* [state result] ( debug " SHOW TX RESULT " ) (when-not (:error result) (js/setTimeout clear-tx-result! 2000)) (assoc state :root/tx-result result)) (defmutation show-tx-result [result] (action [{:keys [state]}] (swap! state (fn [s] (assoc-in s [:root/tx-result] result))))) (defn show-tx-result! [result] (comp/transact! SPA `[(show-tx-result ~result)])) (defn set-create* [state ident creating] (assoc-in state (conj ident :ui/create) creating)) (defn set-saving* [state ident busy] (assoc-in state (conj ident :ui/saving) busy)) (defmutation set-saving [{:keys [ident busy]}] (action [{:keys [state]}] (swap! state set-saving* ident busy))) (defn set-saving! [ident busy] (comp/transact! SPA `[(set-saving {:ident ~ident :busy ~busy})])) (comp/defsc TxResult [this {:keys [result msgs error com.wsscode.pathom.core/reader-error]}] {:query [:result :msgs :error :com.wsscode.pathom.core/reader-error :sticky] :initial-state {:result nil :msgs nil :error nil :com.wsscode.pathom.core/reader-error nil :sticky false} :componentDidMount (fn [this] (let [props (comp/props this)] (when (and (not (:error props)) (not (:sticky props))) (js/setTimeout clear-tx-result! 2000))))} (let [error (or error reader-error)] ( debug " " " error " error " result " result ) (div {:style {:position "fixed" :top "50px" :left 0 :right 0 :maxWidth 500 :margin "auto" :zIndex 1000}} (if error (ui-message {:error true} (div :.content {} (div :.ui.right.floated.negative.button {:onClick clear-tx-result!} "OK") (div :.header {} "Error") (div :.horizontal.items (div :.item error)) (when msgs (map-indexed (fn [i msg] (dom/p {:key i} msg)) msgs)))) (ui-message {:success true :onDismiss clear-tx-result!} (div :.content {} (div :.header {} "Success") (dom/p {} result) (when msgs (map-indexed (fn [i msg] (dom/p {:key i} msg)) msgs)))))))) (def ui-tx-result (comp/factory TxResult)) (defn remove-ident* "Removes an ident, if it exists, from a list of idents in app state. This function is safe to use within mutations." [state-map ident path-to-idents] {:pre [(map? state-map)]} (let [new-list (fn [old-list] (vec (filter #(not= ident %) old-list)))] (update-in state-map path-to-idents new-list))) (fm/defmutation delete-sample [{:keys [sv-ident sa-ident]}] (action [{:keys [state]}] (debug "MUTATION delete sample" sv-ident sa-ident) (swap! state (fn [s] (let [sas-path (conj sv-ident :sitevisit/Samples) _ (debug "samples BEFORE" (get-in s sas-path)) res (-> s (remove-ident* sa-ident sas-path) (fs/mark-complete* sv-ident :sitevisit/Samples)) _ (debug "samples AFTER" (get-in res sas-path))] res))))) (defn del-sample [sv-ident sa-ident] (comp/transact! SPA `[(delete-sample ~{:sv-ident sv-ident :sa-ident sa-ident})])) (defmutation set-pristine "changes a form's current state to pristine" [{:keys [ident]}] (action [{:keys [state]}] (swap! state fs/entity->pristine* ident))) (defn set-pristine! [ident] (comp/transact! SPA `[(set-pristine {:ident ~ident})])) (defn get-new-ident [env ident] (if-let [new-ident-v (get-in env [:tempid->realid (second ident)])] [(first ident) new-ident-v] ident)) (defmutation save-entity "saves an entity diff to the backend Datomic DB" [{:keys [ident diff delete] :as params}] (action [{:keys [state]}] (if delete (debug "DELETE ENTITY" ident) (debug "SAVE ENTITY" ident)) (swap! state set-saving* ident true)) (remote [{:keys [state] :as env}] (debug "SAVE ENTITY REMOTE" (:ui.riverdb/current-agency @state)) (-> env (update-in [:ast :params] #(-> % (dissoc :post-mutation) (dissoc :post-params) (dissoc :success-msg) (assoc :agency (get-in @state [:ui.riverdb/current-agency 1])))) (update-in [:ast :params :diff] (fn [diff] (let [new-diff (sp/transform [sp/ALL sp/LAST sp/ALL] #(when (not (and (keyword? (first %)) (= "_" (first (name (first %)))))) %) diff)] (debug "DIFF" new-diff) new-diff))) (fm/returning TxResult) (fm/with-target [:root/tx-result]))) (ok-action [{:keys [state result] :as env}] (debug "OK ACTION" "IDENT" ident "REF" (:ref env) "result" result "(comp/get-ident (:component env))" (comp/get-ident (:component env))) (debug ":tempid->realid" (:tempid->realid env)) (debug "TRANSACTED AST" (:transacted-ast env)) (if-let [ok-err (get-in result [:body `save-entity :error])] (do (debug "OK ERROR" ok-err) (swap! state (fn [s] (-> s (set-saving* ident false))))) (try (let [{:keys [post-mutation post-params success-msg delete]} (get-in env [:transacted-ast :params]) ident (get-new-ident env ident)] (if delete (swap! state (fn [s] (-> s (show-tx-result* {:result (or success-msg "Delete Succeeded")}) (set-saving* ident false) (dissoc ident)))) (swap! state (fn [s] (-> s (fs/entity->pristine* ident) (show-tx-result* {:result (or success-msg "Save Succeeded")}) (set-saving* ident false) (set-create* ident false))))) (when post-mutation (let [tempid (get-in env [:transacted-ast :params :ident 1]) new-id (get-in env [:tempid->realid tempid]) params (if new-id (assoc post-params :new-id new-id) params) txd `[(~post-mutation ~params)]] (comp/transact! SPA txd)))) (catch js/Object ex (let [ident (get-new-ident env ident)] (log/error "OK Action handler failed: " ex) (swap! state (fn [st] (-> st (set-saving* ident false) (assoc-in [:root/tx-result :error] (str "TX Result Handler failed: " ex)))))))))) (error-action [{:keys [app ref result state] :as env}] (log/info "Mutation Error Result " ident diff result) (swap! state (fn [s] (-> s (set-saving* ident false) (#(if-let [err (get-in result [:error-text])] (assoc-in % [:root/tx-result :error] err) %))))))) (defsc UploadResult [this props] {:query [:errors :msgs]} (debug "UploadResult" props)) (defmutation upload-files [{:keys [config progress-target] :as params}] (action [{:keys [state]}] (debug "UPLOAD FILES" config)) (remote [env] (-> env (fm/returning UploadResult))) (progress-action [{:keys [progress state] :as env}] (swap! state assoc-in progress-target (http-remote/overall-progress env))) (ok-action [{:keys [state result] :as env}] (let [ident (comp/get-ident (:component env)) {:keys [tempids errors msgs] :as res} (get-in result [:body `upload-files])] (debug "UPLOAD OK" ident res result) (if (seq errors) (do (log/error "OK ERROR" (first errors)) (swap! state (fn [s] (-> s (assoc-in [:root/tx-result :error] (str (if (= (count errors) 1) (first errors) errors))) (assoc-in (conj ident :ui/import-error?) true) (cond-> (seq msgs) (assoc-in [:root/tx-result :msgs] msgs)))))) (swap! state (fn [s] (-> s (assoc-in [:root/tx-result :result] "Import completed") (cond-> (seq msgs) (-> (assoc-in [:root/tx-result :msgs] msgs) (assoc-in [:root/tx-result :sticky] true))))))))) (error-action [{:keys [app ref result state] :as env}] (let [ident (comp/get-ident (:component env)) reader-error (get-in result [:body `upload-files :com.wsscode.pathom.core/reader-error]) error-text (get-in result [:error-text])] (log/error "UPLOAD FILES ERROR" ident result) (when (or reader-error error-text) (swap! state (fn [s] (-> s (assoc-in [:root/tx-result :error] (or reader-error error-text)) (assoc-in (conj ident :ui/import-error?) true) (cond->))))))))
a931f56f86f22519ed2c1c0ad44cc61150aa07edd2fbff26a6e90b1e1a85306d
mpickering/apply-refact
Extensions0.hs
{-# LANGUAGE Arrows #-} f = id
null
https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Extensions0.hs
haskell
# LANGUAGE Arrows #
f = id
a4e8a1e2ec1ed267fd395c73b3cd0f3ba340bdbe00ad32dfe7e7a1a2634c90fa
GaloisInc/surveyor
Debugging.hs
{-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # module Surveyor.Core.Handlers.Debugging ( handleDebuggingEvent ) where import Control.Lens ( (^.), (^?), _Just ) import qualified Control.Lens as L import Control.Monad.IO.Class ( MonadIO, liftIO ) import qualified Data.IORef as IOR import Data.Parameterized.Some ( Some(..) ) import qualified Data.Sequence as Seq import qualified Data.Text as T import GHC.Stack ( HasCallStack ) import qualified Lang.Crucible.Simulator.ExecutionTree as LCSET import qualified Prettyprinter as PP import qualified Surveyor.Core.Architecture as SCA import qualified Surveyor.Core.Events as SCE import qualified Surveyor.Core.HandlerMonad as SCH import qualified Surveyor.Core.Logging as SCL import qualified Surveyor.Core.State as SCS import qualified Surveyor.Core.SymbolicExecution as SymEx import qualified Surveyor.Core.SymbolicExecution.ExecutionFeature as SCEF noSessionFor :: (MonadIO m) => SCS.S e u arch s -> SymEx.SessionID s -> m () noSessionFor s0 sessionID = do let msg = SCL.msgWithContext { SCL.logText = [ PP.pretty "No session for SessionID " <> PP.pretty sessionID ] , SCL.logSource = SCL.EventHandler (T.pack "Debug") , SCL.logLevel = SCL.Warn } liftIO $ SCS.logMessage s0 msg sessionStateUnexpected :: (MonadIO m) => SCS.S e u arch s -> SymEx.SessionID s -> String -> m () sessionStateUnexpected s0 sessionID expectedState = do let msg = SCL.msgWithContext { SCL.logText = [ PP.pretty "Symbolic execution session is not " <> PP.pretty expectedState <> PP.pretty ": " <> PP.pretty sessionID ] , SCL.logSource = SCL.EventHandler (T.pack "Debug") , SCL.logLevel = SCL.Warn } liftIO $ SCS.logMessage s0 msg handleDebuggingEvent :: ( SCA.Architecture arch s , SCA.CrucibleExtension arch , MonadIO m , HasCallStack ) => SCS.S e u arch s -> SCE.DebuggingEvent s (SCS.S e u) -> SCH.HandlerT (SCS.State e u s) m (SCS.State e u s) handleDebuggingEvent s0 evt = case evt of SCE.StepExecution sessionID -> do symExSt <- SCH.expectValue (s0 ^? SCS.lArchState . _Just . SCS.symExStateL) Some symEx <- SCH.expectValueWith (SymEx.lookupSessionState symExSt sessionID) $ do noSessionFor s0 sessionID SCH.withFailAction (sessionStateUnexpected s0 sessionID "Suspended") $ do SymEx.Suspended _symNonce suspSt <- return symEx let msg = SCL.msgWith { SCL.logText = [ PP.pretty "Stepping session " <> PP.pretty sessionID ] } liftIO $ SCS.logMessage s0 msg -- To single step, we set the debug execution feature into its -- monitoring mode, which will cause it to stop at every state and -- send it to surveyor. -- -- We then resume execution to restart the process let execFeatureStateRef = SymEx.suspendedDebugFeatureConfig suspSt liftIO $ SCEF.modifyDebuggerState execFeatureStateRef (setDebugState SCEF.Monitoring) liftIO $ SymEx.suspendedResumeUnmodified suspSt Switch the symbolic execution UI to the executing state switchToExecutingState s0 symEx return $! SCS.State s0 SCE.StepOutExecution sessionID -> do symExSt <- SCH.expectValue (s0 ^? SCS.lArchState . _Just . SCS.symExStateL) Some symEx <- SCH.expectValueWith (SymEx.lookupSessionState symExSt sessionID) $ do noSessionFor s0 sessionID SCH.withFailAction (sessionStateUnexpected s0 sessionID "Suspended") $ do SymEx.Suspended _symNonce suspSt <- return symEx let execFeatureStateRef = SymEx.suspendedDebugFeatureConfig suspSt stackDepthRef <- liftIO $ IOR.newIORef 0 liftIO $ SCEF.modifyDebuggerState execFeatureStateRef (setDebugState (SCEF.InactiveUntil (stepOutP stackDepthRef))) liftIO $ SymEx.suspendedResumeUnmodified suspSt switchToExecutingState s0 symEx return $! SCS.State s0 SCE.ContinueExecution sessionID -> do symExSt <- SCH.expectValue (s0 ^? SCS.lArchState . _Just . SCS.symExStateL) Some symEx <- SCH.expectValueWith (SymEx.lookupSessionState symExSt sessionID) $ do noSessionFor s0 sessionID SCH.withFailAction (sessionStateUnexpected s0 sessionID "Suspended") $ do SymEx.Suspended _symNonce suspSt <- return symEx let msg = SCL.msgWith { SCL.logText = [ PP.pretty "Stepping session " <> PP.pretty sessionID ] } liftIO $ SCS.logMessage s0 msg let execFeatureStateRef = SymEx.suspendedDebugFeatureConfig suspSt liftIO $ SCEF.modifyDebuggerState execFeatureStateRef (setDebugState SCEF.Inactive) liftIO $ SymEx.suspendedResumeUnmodified suspSt switchToExecutingState s0 symEx return $! SCS.State s0 SCE.InterruptExecution sessionID -> do symExSt <- SCH.expectValue (s0 ^? SCS.lArchState . _Just . SCS.symExStateL) Some symEx <- SCH.expectValueWith (SymEx.lookupSessionState symExSt sessionID) $ do noSessionFor s0 sessionID SCH.withFailAction (sessionStateUnexpected s0 sessionID "Executing") $ do SymEx.Executing progress <- return symEx -- Interrupt execution by switching the monitor on. The monitor will -- send an event at its next opportunity. That event will trigger a -- state change to the suspended execution viewer. let execFeatureStateRef = SymEx.executionInterrupt progress liftIO $ SCEF.modifyDebuggerState execFeatureStateRef (setDebugState SCEF.Monitoring) return $! SCS.State s0 SCE.EnableRecording sessionID -> do symExSt <- SCH.expectValue (s0 ^? SCS.lArchState . _Just . SCS.symExStateL) Some symEx <- SCH.expectValueWith (SymEx.lookupSessionState symExSt sessionID) $ do noSessionFor s0 sessionID SCH.withFailAction (sessionStateUnexpected s0 sessionID "Suspended") $ do SymEx.Suspended _ suspSt <- return symEx traceRef <- liftIO $ IOR.newIORef mempty _actualRef <- liftIO $ SCEF.modifyDebuggerState (SymEx.suspendedDebugFeatureConfig suspSt) (enableRecording traceRef) return $! SCS.State s0 SCE.DisableRecording sessionID -> do symExSt <- SCH.expectValue (s0 ^? SCS.lArchState . _Just . SCS.symExStateL) Some symEx <- SCH.expectValueWith (SymEx.lookupSessionState symExSt sessionID) $ do noSessionFor s0 sessionID SCH.withFailAction (sessionStateUnexpected s0 sessionID "Suspended") $ do SymEx.Suspended symNonce suspSt <- return symEx let stateRef = SymEx.suspendedDebugFeatureConfig suspSt liftIO $ SCEF.modifyDebuggerState stateRef disableRecording -- If there are any states that have been recorded, save them into the -- state for review liftIO $ SCEF.withRecordedStates stateRef $ \mstates -> do case mstates of Nothing -> return () Just recordedStates -> do let suspSt1 = suspSt { SymEx.suspendedHistory = Just (SymEx.RecordedStateLog 0 recordedStates) } liftIO $ SCS.sEmitEvent s0 (SCE.UpdateSymbolicExecutionState (s0 ^. SCS.lNonce) (SymEx.Suspended symNonce suspSt1)) return $! SCS.State s0 enableRecording :: IOR.IORef (Seq.Seq (Some (LCSET.ExecState p sym ext))) -> Some (SCEF.DebuggerFeatureState p sym ext) -> (Some (SCEF.DebuggerFeatureState p sym ext), IOR.IORef (Seq.Seq (Some (LCSET.ExecState p sym ext)))) enableRecording newRef (Some r) = case r of SCEF.Recording currentRef _nestedState -> (Some r, currentRef) SCEF.Monitoring -> (Some (SCEF.Recording newRef r), newRef) SCEF.Inactive -> (Some (SCEF.Recording newRef r), newRef) SCEF.InactiveUntil {} -> (Some (SCEF.Recording newRef r), newRef) disableRecording :: Some (SCEF.DebuggerFeatureState p sym ext) -> (Some (SCEF.DebuggerFeatureState p sym ext), ()) disableRecording (Some r) = case r of SCEF.Recording _currentRef nestedState -> (Some nestedState, ()) SCEF.Monitoring -> (Some r, ()) SCEF.Inactive -> (Some r, ()) SCEF.InactiveUntil {} -> (Some r, ()) -- | Set the debugger state to the given value, while keeping the current state -- recording configuration setDebugState :: SCEF.DebuggerFeatureState p sym ext SCEF.Normal -> Some (SCEF.DebuggerFeatureState p sym ext) -> (Some (SCEF.DebuggerFeatureState p sym ext), ()) setDebugState newState (Some s) = case s of SCEF.Recording ref _ -> (Some (SCEF.Recording ref newState), ()) SCEF.Monitoring -> (Some newState, ()) SCEF.Inactive -> (Some newState, ()) SCEF.InactiveUntil {} -> (Some newState, ()) -- | Return True once execution returns from the current function -- -- Operationally, increment the stack depth on every call, decrement it on every -- return. If we see a return when the depth is 0, we can return. stepOutP :: IOR.IORef Int -> LCSET.ExecState p sym ext rtp -> IO Bool stepOutP callDepthRef st = case st of LCSET.CallState {} -> do IOR.atomicModifyIORef' callDepthRef (\d -> (d + 1, ())) return False LCSET.TailCallState {} -> do IOR.atomicModifyIORef' callDepthRef (\d -> (d + 1, ())) return False LCSET.ReturnState {} -> do depth <- IOR.readIORef callDepthRef case depth of 0 -> return True _ -> do IOR.atomicModifyIORef' callDepthRef (\d -> (d - 1, ())) return False _ -> return False -- | Construct an 'SymEx.Executing' state (from the suspended state) and switch -- to it by sending an event -- NOTE : This currently sets the metrics to zero ( the previous metrics could be -- stashed in the suspended state, potentially) switchToExecutingState :: (MonadIO m) => SCS.S e u arch s -> SymEx.SymbolicExecutionState arch s SymEx.Suspend -> m () switchToExecutingState s0 symEx@(SymEx.Suspended _nonce suspSt) = do let symConf = SymEx.symbolicExecutionConfig symEx let hdl = suspSt ^. L.to SymEx.suspendedSimState . LCSET.stateContext . L.to LCSET.printHandle let exProgress = SymEx.ExecutionProgress { SymEx.executionMetrics = SymEx.emptyMetrics , SymEx.executionOutputHandle = hdl , SymEx.executionConfig = symConf , SymEx.executionInterrupt = SymEx.suspendedDebugFeatureConfig suspSt , SymEx.executionResume = SymEx.suspendedResumeUnmodified suspSt } let exState = SymEx.Executing exProgress liftIO $ SCS.sEmitEvent s0 (SCE.UpdateSymbolicExecutionState (s0 ^. SCS.lNonce) exState)
null
https://raw.githubusercontent.com/GaloisInc/surveyor/96b6748d811bc2ab9ef330307a324bd00e04819f/surveyor-core/src/Surveyor/Core/Handlers/Debugging.hs
haskell
# LANGUAGE GADTs # # LANGUAGE RankNTypes # To single step, we set the debug execution feature into its monitoring mode, which will cause it to stop at every state and send it to surveyor. We then resume execution to restart the process Interrupt execution by switching the monitor on. The monitor will send an event at its next opportunity. That event will trigger a state change to the suspended execution viewer. If there are any states that have been recorded, save them into the state for review | Set the debugger state to the given value, while keeping the current state recording configuration | Return True once execution returns from the current function Operationally, increment the stack depth on every call, decrement it on every return. If we see a return when the depth is 0, we can return. | Construct an 'SymEx.Executing' state (from the suspended state) and switch to it by sending an event stashed in the suspended state, potentially)
# LANGUAGE ScopedTypeVariables # module Surveyor.Core.Handlers.Debugging ( handleDebuggingEvent ) where import Control.Lens ( (^.), (^?), _Just ) import qualified Control.Lens as L import Control.Monad.IO.Class ( MonadIO, liftIO ) import qualified Data.IORef as IOR import Data.Parameterized.Some ( Some(..) ) import qualified Data.Sequence as Seq import qualified Data.Text as T import GHC.Stack ( HasCallStack ) import qualified Lang.Crucible.Simulator.ExecutionTree as LCSET import qualified Prettyprinter as PP import qualified Surveyor.Core.Architecture as SCA import qualified Surveyor.Core.Events as SCE import qualified Surveyor.Core.HandlerMonad as SCH import qualified Surveyor.Core.Logging as SCL import qualified Surveyor.Core.State as SCS import qualified Surveyor.Core.SymbolicExecution as SymEx import qualified Surveyor.Core.SymbolicExecution.ExecutionFeature as SCEF noSessionFor :: (MonadIO m) => SCS.S e u arch s -> SymEx.SessionID s -> m () noSessionFor s0 sessionID = do let msg = SCL.msgWithContext { SCL.logText = [ PP.pretty "No session for SessionID " <> PP.pretty sessionID ] , SCL.logSource = SCL.EventHandler (T.pack "Debug") , SCL.logLevel = SCL.Warn } liftIO $ SCS.logMessage s0 msg sessionStateUnexpected :: (MonadIO m) => SCS.S e u arch s -> SymEx.SessionID s -> String -> m () sessionStateUnexpected s0 sessionID expectedState = do let msg = SCL.msgWithContext { SCL.logText = [ PP.pretty "Symbolic execution session is not " <> PP.pretty expectedState <> PP.pretty ": " <> PP.pretty sessionID ] , SCL.logSource = SCL.EventHandler (T.pack "Debug") , SCL.logLevel = SCL.Warn } liftIO $ SCS.logMessage s0 msg handleDebuggingEvent :: ( SCA.Architecture arch s , SCA.CrucibleExtension arch , MonadIO m , HasCallStack ) => SCS.S e u arch s -> SCE.DebuggingEvent s (SCS.S e u) -> SCH.HandlerT (SCS.State e u s) m (SCS.State e u s) handleDebuggingEvent s0 evt = case evt of SCE.StepExecution sessionID -> do symExSt <- SCH.expectValue (s0 ^? SCS.lArchState . _Just . SCS.symExStateL) Some symEx <- SCH.expectValueWith (SymEx.lookupSessionState symExSt sessionID) $ do noSessionFor s0 sessionID SCH.withFailAction (sessionStateUnexpected s0 sessionID "Suspended") $ do SymEx.Suspended _symNonce suspSt <- return symEx let msg = SCL.msgWith { SCL.logText = [ PP.pretty "Stepping session " <> PP.pretty sessionID ] } liftIO $ SCS.logMessage s0 msg let execFeatureStateRef = SymEx.suspendedDebugFeatureConfig suspSt liftIO $ SCEF.modifyDebuggerState execFeatureStateRef (setDebugState SCEF.Monitoring) liftIO $ SymEx.suspendedResumeUnmodified suspSt Switch the symbolic execution UI to the executing state switchToExecutingState s0 symEx return $! SCS.State s0 SCE.StepOutExecution sessionID -> do symExSt <- SCH.expectValue (s0 ^? SCS.lArchState . _Just . SCS.symExStateL) Some symEx <- SCH.expectValueWith (SymEx.lookupSessionState symExSt sessionID) $ do noSessionFor s0 sessionID SCH.withFailAction (sessionStateUnexpected s0 sessionID "Suspended") $ do SymEx.Suspended _symNonce suspSt <- return symEx let execFeatureStateRef = SymEx.suspendedDebugFeatureConfig suspSt stackDepthRef <- liftIO $ IOR.newIORef 0 liftIO $ SCEF.modifyDebuggerState execFeatureStateRef (setDebugState (SCEF.InactiveUntil (stepOutP stackDepthRef))) liftIO $ SymEx.suspendedResumeUnmodified suspSt switchToExecutingState s0 symEx return $! SCS.State s0 SCE.ContinueExecution sessionID -> do symExSt <- SCH.expectValue (s0 ^? SCS.lArchState . _Just . SCS.symExStateL) Some symEx <- SCH.expectValueWith (SymEx.lookupSessionState symExSt sessionID) $ do noSessionFor s0 sessionID SCH.withFailAction (sessionStateUnexpected s0 sessionID "Suspended") $ do SymEx.Suspended _symNonce suspSt <- return symEx let msg = SCL.msgWith { SCL.logText = [ PP.pretty "Stepping session " <> PP.pretty sessionID ] } liftIO $ SCS.logMessage s0 msg let execFeatureStateRef = SymEx.suspendedDebugFeatureConfig suspSt liftIO $ SCEF.modifyDebuggerState execFeatureStateRef (setDebugState SCEF.Inactive) liftIO $ SymEx.suspendedResumeUnmodified suspSt switchToExecutingState s0 symEx return $! SCS.State s0 SCE.InterruptExecution sessionID -> do symExSt <- SCH.expectValue (s0 ^? SCS.lArchState . _Just . SCS.symExStateL) Some symEx <- SCH.expectValueWith (SymEx.lookupSessionState symExSt sessionID) $ do noSessionFor s0 sessionID SCH.withFailAction (sessionStateUnexpected s0 sessionID "Executing") $ do SymEx.Executing progress <- return symEx let execFeatureStateRef = SymEx.executionInterrupt progress liftIO $ SCEF.modifyDebuggerState execFeatureStateRef (setDebugState SCEF.Monitoring) return $! SCS.State s0 SCE.EnableRecording sessionID -> do symExSt <- SCH.expectValue (s0 ^? SCS.lArchState . _Just . SCS.symExStateL) Some symEx <- SCH.expectValueWith (SymEx.lookupSessionState symExSt sessionID) $ do noSessionFor s0 sessionID SCH.withFailAction (sessionStateUnexpected s0 sessionID "Suspended") $ do SymEx.Suspended _ suspSt <- return symEx traceRef <- liftIO $ IOR.newIORef mempty _actualRef <- liftIO $ SCEF.modifyDebuggerState (SymEx.suspendedDebugFeatureConfig suspSt) (enableRecording traceRef) return $! SCS.State s0 SCE.DisableRecording sessionID -> do symExSt <- SCH.expectValue (s0 ^? SCS.lArchState . _Just . SCS.symExStateL) Some symEx <- SCH.expectValueWith (SymEx.lookupSessionState symExSt sessionID) $ do noSessionFor s0 sessionID SCH.withFailAction (sessionStateUnexpected s0 sessionID "Suspended") $ do SymEx.Suspended symNonce suspSt <- return symEx let stateRef = SymEx.suspendedDebugFeatureConfig suspSt liftIO $ SCEF.modifyDebuggerState stateRef disableRecording liftIO $ SCEF.withRecordedStates stateRef $ \mstates -> do case mstates of Nothing -> return () Just recordedStates -> do let suspSt1 = suspSt { SymEx.suspendedHistory = Just (SymEx.RecordedStateLog 0 recordedStates) } liftIO $ SCS.sEmitEvent s0 (SCE.UpdateSymbolicExecutionState (s0 ^. SCS.lNonce) (SymEx.Suspended symNonce suspSt1)) return $! SCS.State s0 enableRecording :: IOR.IORef (Seq.Seq (Some (LCSET.ExecState p sym ext))) -> Some (SCEF.DebuggerFeatureState p sym ext) -> (Some (SCEF.DebuggerFeatureState p sym ext), IOR.IORef (Seq.Seq (Some (LCSET.ExecState p sym ext)))) enableRecording newRef (Some r) = case r of SCEF.Recording currentRef _nestedState -> (Some r, currentRef) SCEF.Monitoring -> (Some (SCEF.Recording newRef r), newRef) SCEF.Inactive -> (Some (SCEF.Recording newRef r), newRef) SCEF.InactiveUntil {} -> (Some (SCEF.Recording newRef r), newRef) disableRecording :: Some (SCEF.DebuggerFeatureState p sym ext) -> (Some (SCEF.DebuggerFeatureState p sym ext), ()) disableRecording (Some r) = case r of SCEF.Recording _currentRef nestedState -> (Some nestedState, ()) SCEF.Monitoring -> (Some r, ()) SCEF.Inactive -> (Some r, ()) SCEF.InactiveUntil {} -> (Some r, ()) setDebugState :: SCEF.DebuggerFeatureState p sym ext SCEF.Normal -> Some (SCEF.DebuggerFeatureState p sym ext) -> (Some (SCEF.DebuggerFeatureState p sym ext), ()) setDebugState newState (Some s) = case s of SCEF.Recording ref _ -> (Some (SCEF.Recording ref newState), ()) SCEF.Monitoring -> (Some newState, ()) SCEF.Inactive -> (Some newState, ()) SCEF.InactiveUntil {} -> (Some newState, ()) stepOutP :: IOR.IORef Int -> LCSET.ExecState p sym ext rtp -> IO Bool stepOutP callDepthRef st = case st of LCSET.CallState {} -> do IOR.atomicModifyIORef' callDepthRef (\d -> (d + 1, ())) return False LCSET.TailCallState {} -> do IOR.atomicModifyIORef' callDepthRef (\d -> (d + 1, ())) return False LCSET.ReturnState {} -> do depth <- IOR.readIORef callDepthRef case depth of 0 -> return True _ -> do IOR.atomicModifyIORef' callDepthRef (\d -> (d - 1, ())) return False _ -> return False NOTE : This currently sets the metrics to zero ( the previous metrics could be switchToExecutingState :: (MonadIO m) => SCS.S e u arch s -> SymEx.SymbolicExecutionState arch s SymEx.Suspend -> m () switchToExecutingState s0 symEx@(SymEx.Suspended _nonce suspSt) = do let symConf = SymEx.symbolicExecutionConfig symEx let hdl = suspSt ^. L.to SymEx.suspendedSimState . LCSET.stateContext . L.to LCSET.printHandle let exProgress = SymEx.ExecutionProgress { SymEx.executionMetrics = SymEx.emptyMetrics , SymEx.executionOutputHandle = hdl , SymEx.executionConfig = symConf , SymEx.executionInterrupt = SymEx.suspendedDebugFeatureConfig suspSt , SymEx.executionResume = SymEx.suspendedResumeUnmodified suspSt } let exState = SymEx.Executing exProgress liftIO $ SCS.sEmitEvent s0 (SCE.UpdateSymbolicExecutionState (s0 ^. SCS.lNonce) exState)
df8406311b828d2bd51ff0bdc8966e5e942fcb0be896c3f07f5bc3e8c639b1aa
brendanhay/terrafomo
Settings.hs
-- This module is auto-generated. # LANGUAGE NoImplicitPrelude # # LANGUAGE RecordWildCards # # LANGUAGE StrictData # # LANGUAGE UndecidableInstances # # OPTIONS_GHC -fno - warn - unused - imports # -- | Module : . . Settings Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- module Terrafomo.Rancher.Settings ( -- * EnvironmentMember EnvironmentMember (..) ) where import Data.Functor ((<$>)) import Data.Semigroup ((<>)) import GHC.Base (Proxy#, proxy#, ($)) import qualified Data.Functor.Const as P import qualified Data.List.NonEmpty as P import qualified Data.Map.Strict as P import qualified Data.Maybe as P import qualified Data.Text.Lazy as P import qualified Prelude as P import qualified Terrafomo.Encode as Encode import qualified Terrafomo.HCL as TF import qualified Terrafomo.HIL as TF import qualified Terrafomo.Lens as Lens import qualified Terrafomo.Rancher.Types as P import qualified Terrafomo.Schema as TF -- | The @member@ nested settings definition. data EnvironmentMember s = EnvironmentMember { external_id :: TF.Expr s TF.Id -- ^ @external_id@ -- - (Required) , external_id_type :: TF.Expr s P.Text -- ^ @external_id_type@ -- - (Required) , role :: TF.Expr s P.Text -- ^ @role@ -- - (Required) } deriving (P.Show) instance Lens.HasField "external_id" f (EnvironmentMember s) (TF.Expr s TF.Id) where field = Lens.lens' (external_id :: EnvironmentMember s -> TF.Expr s TF.Id) (\s a -> s { external_id = a } :: EnvironmentMember s) instance Lens.HasField "external_id_type" f (EnvironmentMember s) (TF.Expr s P.Text) where field = Lens.lens' (external_id_type :: EnvironmentMember s -> TF.Expr s P.Text) (\s a -> s { external_id_type = a } :: EnvironmentMember s) instance Lens.HasField "role" f (EnvironmentMember s) (TF.Expr s P.Text) where field = Lens.lens' (role :: EnvironmentMember s -> TF.Expr s P.Text) (\s a -> s { role = a } :: EnvironmentMember s) instance Lens.HasField "external_id" (P.Const r) (TF.Ref EnvironmentMember s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "external_id")) instance Lens.HasField "external_id_type" (P.Const r) (TF.Ref EnvironmentMember s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "external_id_type")) instance Lens.HasField "role" (P.Const r) (TF.Ref EnvironmentMember s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "role")) instance TF.ToHCL (EnvironmentMember s) where toHCL EnvironmentMember{..} = TF.pairs $ P.mempty <> TF.pair "external_id" external_id <> TF.pair "external_id_type" external_id_type <> TF.pair "role" role
null
https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/provider/terrafomo-rancher/gen/Terrafomo/Rancher/Settings.hs
haskell
This module is auto-generated. | Stability : auto-generated * EnvironmentMember | The @member@ nested settings definition. ^ @external_id@ - (Required) ^ @external_id_type@ - (Required) ^ @role@ - (Required)
# LANGUAGE NoImplicitPrelude # # LANGUAGE RecordWildCards # # LANGUAGE StrictData # # LANGUAGE UndecidableInstances # # OPTIONS_GHC -fno - warn - unused - imports # Module : . . Settings Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Terrafomo.Rancher.Settings ( EnvironmentMember (..) ) where import Data.Functor ((<$>)) import Data.Semigroup ((<>)) import GHC.Base (Proxy#, proxy#, ($)) import qualified Data.Functor.Const as P import qualified Data.List.NonEmpty as P import qualified Data.Map.Strict as P import qualified Data.Maybe as P import qualified Data.Text.Lazy as P import qualified Prelude as P import qualified Terrafomo.Encode as Encode import qualified Terrafomo.HCL as TF import qualified Terrafomo.HIL as TF import qualified Terrafomo.Lens as Lens import qualified Terrafomo.Rancher.Types as P import qualified Terrafomo.Schema as TF data EnvironmentMember s = EnvironmentMember { external_id :: TF.Expr s TF.Id , external_id_type :: TF.Expr s P.Text , role :: TF.Expr s P.Text } deriving (P.Show) instance Lens.HasField "external_id" f (EnvironmentMember s) (TF.Expr s TF.Id) where field = Lens.lens' (external_id :: EnvironmentMember s -> TF.Expr s TF.Id) (\s a -> s { external_id = a } :: EnvironmentMember s) instance Lens.HasField "external_id_type" f (EnvironmentMember s) (TF.Expr s P.Text) where field = Lens.lens' (external_id_type :: EnvironmentMember s -> TF.Expr s P.Text) (\s a -> s { external_id_type = a } :: EnvironmentMember s) instance Lens.HasField "role" f (EnvironmentMember s) (TF.Expr s P.Text) where field = Lens.lens' (role :: EnvironmentMember s -> TF.Expr s P.Text) (\s a -> s { role = a } :: EnvironmentMember s) instance Lens.HasField "external_id" (P.Const r) (TF.Ref EnvironmentMember s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "external_id")) instance Lens.HasField "external_id_type" (P.Const r) (TF.Ref EnvironmentMember s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "external_id_type")) instance Lens.HasField "role" (P.Const r) (TF.Ref EnvironmentMember s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "role")) instance TF.ToHCL (EnvironmentMember s) where toHCL EnvironmentMember{..} = TF.pairs $ P.mempty <> TF.pair "external_id" external_id <> TF.pair "external_id_type" external_id_type <> TF.pair "role" role
6ebb2ea834efb6ec19a8ddd9c10762734978b0ae0a077fa24fdfe1c3f913244f
dyzsr/ocaml-selectml
typeplan.ml
(**************************************************************************) (* *) (* OCaml *) (* *) (* *) Copyright 2022 (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Typing for query plans *) open Longident open Asttypes open Parsetree open Ast_helper open Types open Typedtree open Ctype let scope_check scopes exp = let super = Tast_iterator.default_iterator in let current_scope = List.hd scopes in let outer_scopes = List.tl scopes in let current = ref false in let outer = ref false in let expr self exp = match exp.exp_desc with | Texp_ident (Path.Pident id, _, _) -> let scope = Ident.scope id in if scope = current_scope then current := true else if List.mem scope outer_scopes then outer := true | _ -> super.expr self exp in let iterator = {super with expr} in iterator.expr iterator exp; !current || not !outer let rec check_aggregate ~scopes env exp action = let super = Tast_iterator.default_iterator in let expr self exp = match exp.exp_desc with | Texp_aggregate (f, e) when scope_check scopes e -> action exp; check_no_aggregate ~scopes env f; check_no_aggregate ~scopes env e; super.expr self f | _ -> super.expr self exp in let iterator = {super with expr} in iterator.expr iterator exp and check_no_aggregate ~scopes env exp = check_aggregate ~scopes env exp (fun _ -> raise (Typecore.Error ( exp.exp_loc, env, Invalid_use_of_aggregate))) let col_gen = ref 0 let incr_col () = col_gen := !col_gen + 1 let col_of_exp exp = let loc = exp.exp_loc in let name = match exp.exp_desc with | Texp_ident (_, lid, _) -> "__col_" ^ String.concat "_" (flatten lid.txt) | _ -> incr_col(); "__col_" ^ string_of_int !col_gen in let pat = Pat.var (mkloc name loc) in let exp = { exp with exp_desc = Texp_ident (Path.Pident (Ident.create_local name), mkloc (Lident name) loc, {val_type = exp.exp_type; val_kind = Val_reg; val_loc = loc; val_attributes = []; val_uid = Types.Uid.mk ~current_unit:(Env.get_unit_name ()); }) } in (pat, exp) let expand_product exp = match exp.exp_desc with | Texp_tuple es -> let pats, cols = List.split (List.map col_of_exp es) in (es, cols, pats, { exp with exp_desc = Texp_tuple cols }) | Texp_record { fields; representation; extended_expression } -> let exps = ref [] in let cols = ref [] in let pats = ref [] in let fields = Array.map (function | label, Kept t -> label, Kept t | label, Overridden (lid, exp) -> let pat, col = col_of_exp exp in exps := exp :: !exps; cols := col :: !cols; pats := pat :: !pats; label, Overridden (lid, col)) fields in List.rev !exps, List.rev !cols, List.rev !pats, { exp with exp_desc = Texp_record {fields; representation; extended_expression} } | _ -> let pat, col = col_of_exp exp in ([exp], [col], [pat], col) let expand_aggregate ~scopes exp = let current_scope = List.hd scopes in let super = Tast_mapper.default in let aggs = ref [] in let expr self exp = match exp.exp_desc with | Texp_aggregate (func, arg) when scope_check scopes arg -> let argpat, argcol = col_of_exp arg in let retpat, retcol = col_of_exp exp in aggs := (arg, argcol, argpat, Some func, retcol, retpat) :: !aggs; retcol | Texp_ident (Path.Pident id, _, _) when Ident.scope id = current_scope -> let pat, col = col_of_exp exp in aggs := (exp, col, pat, None, col, pat) :: !aggs; col | _ -> super.expr self exp in let mapper = {super with expr} in let exp = mapper.expr mapper exp in let aggs = List.rev !aggs in let funcs = List.map (fun (func, _, _, _, _, _) -> func) aggs in let arglist = List.map (fun (_, arg, _, _, _, _) -> arg) aggs in let argcols = List.map (fun (_, _, col, _, _, _) -> col) aggs in let argpats = List.map (fun (_, _, _, pat, _, _) -> pat) aggs in let retcols = List.map (fun (_, _, _, _, col, _) -> col) aggs in let retpats = List.map (fun (_, _, _, _, _, pat) -> pat) aggs in (funcs, arglist, argcols, argpats, retcols, retpats, exp) let build_plan ~loc env se = let old_env = env in let scope = create_scope () in let child = ref { plan_desc = Tplan_null; plan_loc = loc; plan_env = env; plan_vars = Ident.empty; plan_cardinality = One; plan_patterns = [Pat.construct ~loc (mkloc (Lident "()") loc) None]; } in let handle_from se_from = let vars = Hashtbl.create 31 in let rec aux srcexpr = match srcexpr.psrc_desc with | Psrc_exp (e, s) -> List.iter (fun {txt=v; loc} -> if Hashtbl.mem vars v then raise Typecore.(Error (loc, env, Multiply_bound_variable v)); Hashtbl.add vars v ()) s; let tys = List.map (fun _ -> newvar ()) s in let ty_src = let lid = Ldot (Lident "SelectML", "src") in let path, decl = Env.lookup_type ~loc:e.pexp_loc lid env in assert (List.length decl.type_params = 1); let ty = match tys with | [ty] -> ty | tys -> newty (Ttuple tys) in newconstr path [ty] in (* accumulate value bindings *) let vbs = List.map2 (fun v ty -> let id = Ident.create_scoped ~scope v.txt in let desc = { val_type = ty; val_kind = Val_reg; val_attributes = []; val_loc = v.loc; val_uid = Uid.mk ~current_unit:(Env.get_unit_name ()); } in id, desc) s tys in let exp = Typecore.type_expect old_env e (Typecore.mk_expected ty_src) in let env = List.fold_left (fun env (id, desc) -> Env.add_value id desc env) env vbs in let vars = List.fold_left (fun vars (id, _) -> Ident.add id () vars) Ident.empty vbs in let plan = { plan_loc = srcexpr.psrc_loc; plan_desc = Tplan_source exp; plan_env = env; plan_vars = vars; plan_cardinality = Many; plan_patterns = List.map (fun s -> Pat.var ~loc:srcexpr.psrc_loc s) s; } in plan, vbs | Psrc_product (s1, s2) -> let pl1, vbs1 = aux s1 in let pl2, vbs2 = aux s2 in let vbs = vbs1 @ vbs2 in let env = List.fold_left (fun env (id, desc) -> Env.add_value id desc env) env vbs in let vars = List.fold_left (fun vars (id, _) -> Ident.add id () vars) pl1.plan_vars vbs2 in let plan = { plan_loc = srcexpr.psrc_loc; plan_desc = Tplan_product (pl1, pl2); plan_env = env; plan_vars = vars; plan_cardinality = Many; plan_patterns = pl1.plan_patterns @ pl2.plan_patterns; } in plan, vbs1 @ vbs2 | Psrc_join (s1, s2, e) -> let pl1, vbs1 = aux s1 in let pl2, vbs2 = aux s2 in let vbs = vbs1 @ vbs2 in let joinenv = List.fold_left (fun env (id, desc) -> Env.add_value id desc env) env vbs in let vars = List.fold_left (fun vars (id, _) -> Ident.add id () vars) pl1.plan_vars vbs2 in let exp = Typecore.type_expect joinenv e (Typecore.mk_expected Predef.type_bool) in let plan = { plan_loc = srcexpr.psrc_loc; plan_desc = Tplan_join (pl1, pl2, exp); plan_env = joinenv; plan_vars = vars; plan_cardinality = Many; plan_patterns = pl1.plan_patterns @ pl2.plan_patterns; } in plan, vbs in aux se_from in (* handle FROM clause *) let env = match se.se_from with | None -> env | Some se_from -> let plan, vbs = handle_from se_from in child := plan; List.fold_left (fun env (id, desc) -> Env.add_value id desc env) env vbs in begin_se_scope scope; let scopes = se_scopes () in (* handle WHERE clause *) begin match se.se_where with | None -> () | Some se_where -> let exp = Typecore.type_exp env se_where in check_no_aggregate ~scopes env exp; child := { plan_loc = exp.exp_loc; plan_desc = Tplan_filter (!child, exp); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = (match !child.plan_cardinality with | Zero | One -> Zero | Many -> Many); plan_patterns = !child.plan_patterns } end; (* handle SELECT clause *) let no_aggregate = ref true in let no_extra_project = ref true in let sel_exp = let exp = Typecore.type_exp env se.se_select in check_aggregate ~scopes env exp (fun _ -> no_aggregate := false); exp in if Option.is_some se.se_groupby then no_aggregate := false; if Option.is_some se.se_having then no_extra_project := false; if List.length se.se_orderby > 0 then no_extra_project := false; let aux sexp = let exp = Typecore.type_exp env sexp in check_aggregate ~scopes env exp (fun _ -> no_aggregate := false); exp in let hav_exp = match se.se_having with | Some sexp when !no_aggregate -> Some (aux sexp) | _ -> None in let ord_exps = match se.se_orderby with | _ :: _ when !no_aggregate -> List.map (fun (sexp, _) -> aux sexp) se.se_orderby | _ -> [] in let ord_dirs = List.map (function | _, PAscending -> TAscending | _, PDescending -> TDescending | _, PUsing sexp -> TUsing (Typecore.type_exp old_env sexp)) se.se_orderby in let module TastOrd = struct type t = expression let compare t1 t2 = Stdlib.compare t1 t2 end in let module AstOrd = struct type t = Parsetree.expression let compare t1 t2 = Stdlib.compare t1 t2 end in let module TastMap = Map.Make (TastOrd) in let untype_rmloc e = let rmloc = { Ast_mapper.default_mapper with location = (fun _self _loc -> Location.none) } in rmloc.expr rmloc (Untypeast.untype_expression e) in (* Find identical expressions *) let find_identical (type a) (module Ord : Map.OrderedType with type t = a) (xs : a list) (cols : expression list) : bool array * expression TastMap.t = let module M = Map.Make (Ord) in let m = ref M.empty in let colmap = ref TastMap.empty in let mask = List.map2 (fun x p -> match M.find_opt x !m with | None -> m := M.add x p !m; colmap := TastMap.add p p !colmap; true | Some q -> colmap := TastMap.add p q !colmap; false) xs cols in Array.of_list mask, !colmap in let filter ~mask xs = List.filteri (fun i _ -> mask.(i)) xs in let substitute_columns colmap exp = let rename exp = let super = Tast_mapper.default in let expr self exp = match TastMap.find_opt exp colmap with | None -> super.expr self exp | Some col -> col in let mapper = { super with expr } in mapper.expr mapper exp in rename exp in (* handle aggregation *) let sel_exp, hav_exp, ord_exps = if !no_aggregate then sel_exp, hav_exp, ord_exps else let arglist, argcols, argpats, funcs, retcols, retpats, sel_exp = expand_aggregate ~scopes sel_exp in let prj_list = ref arglist in let prj_cols = ref argcols in let prj_pats = ref argpats in let agg_funcs = ref funcs in let agg_list = ref argcols in let agg_cols = ref retcols in let agg_pats = ref retpats in let aux exp = let arglist, argcols, argpats, funcs, retcols, retpats, exp = expand_aggregate ~scopes exp in prj_list := !prj_list @ arglist; prj_cols := !prj_cols @ argcols; prj_pats := !prj_pats @ argpats; agg_funcs := !agg_funcs @ funcs; agg_list := !agg_list @ argcols; agg_cols := !agg_cols @ retcols; agg_pats := !agg_pats @ retpats; exp in let hav_exp = Option.map aux (match se.se_having, hav_exp with | None, _ -> None | Some sexp, None -> Some (Typecore.type_exp env sexp) | Some _, Some exp -> Some exp) in let ord_exps = List.map aux (match se.se_orderby, ord_exps with | [], _ -> [] | sexps, [] -> List.map (fun (sexp, _) -> Typecore.type_exp env sexp) sexps | _, exps -> exps) in (* handle GROUP BY clause *) let grp_exp = Option.map (fun sexp -> let exp = Typecore.type_exp env sexp in check_no_aggregate ~scopes env exp; let list, cols, pats, exp = expand_product exp in prj_list := !prj_list @ list; prj_cols := !prj_cols @ cols; prj_pats := !prj_pats @ pats; exp) se.se_groupby in (* merge identical columns *) let mask, colmap = let xs = List.map untype_rmloc !prj_list in find_identical (module AstOrd) xs !prj_cols in prj_list := filter ~mask !prj_list; prj_cols := filter ~mask !prj_cols; prj_pats := filter ~mask !prj_pats; let grp_exp = Option.map (substitute_columns colmap) grp_exp in agg_list := List.map (substitute_columns colmap) !agg_list; agg_funcs := List.map (Option.map (substitute_columns colmap)) !agg_funcs; (* build an auxiliary project before grouping *) child := { plan_loc = loc; plan_desc = Tplan_project (!child, !prj_list); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = !child.plan_cardinality; plan_patterns = !prj_pats; }; (* build aggregation *) let module Ord = struct type t = Parsetree.expression option * Parsetree.expression let compare = Stdlib.compare end in let mask, colmap = let xs = List.map2 (fun f e -> Option.map untype_rmloc f, untype_rmloc e) !agg_funcs !agg_list in find_identical (module Ord) xs !agg_cols in agg_funcs := filter ~mask !agg_funcs; agg_list := filter ~mask !agg_list; agg_pats := filter ~mask !agg_pats; let sel_exp = substitute_columns colmap sel_exp in let hav_exp = Option.map (substitute_columns colmap) hav_exp in let ord_exps = List.map (substitute_columns colmap) ord_exps in begin match grp_exp with | None -> child := { plan_loc = loc; plan_desc = Tplan_aggregate_all (!child, !agg_funcs, !agg_list); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = One; plan_patterns = !agg_pats; } | Some grp_exp -> let plan_loc = grp_exp.exp_loc in child := { plan_loc; plan_desc = Tplan_aggregate (!child, grp_exp, !agg_funcs, !agg_list); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = !child.plan_cardinality; plan_patterns = !agg_pats; } end; (sel_exp, hav_exp, ord_exps) in (* handle HAVING and ORDER BY clauses *) let sel_exp = if !no_extra_project then sel_exp else let sel_list, sel_cols, sel_pats, sel_exp = expand_product sel_exp in let prj_list = ref sel_list in let prj_cols = ref sel_cols in let prj_pats = ref sel_pats in let aux = fun exp -> let list, cols, pats, exp = expand_product exp in prj_list := !prj_list @ list; prj_cols := !prj_cols @ cols; prj_pats := !prj_pats @ pats; exp in let hav_exp = Option.map aux hav_exp in let ord_exps = List.map aux ord_exps in (* merge identical columns *) let mask, colmap = let xs = List.map untype_rmloc !prj_list in find_identical (module AstOrd) xs !prj_cols in prj_list := filter ~mask !prj_list; prj_pats := filter ~mask !prj_pats; let sel_exp = substitute_columns colmap sel_exp in let hav_exp = Option.map (substitute_columns colmap) hav_exp in let ord_exps = List.map (substitute_columns colmap) ord_exps in (* build an auxiliary project *) child := { plan_loc = loc; plan_desc = Tplan_project (!child, !prj_list); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = !child.plan_cardinality; plan_patterns = !prj_pats; }; Option.iter (fun exp -> child := { plan_loc = exp.exp_loc; plan_desc = Tplan_filter (!child, exp); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = (match !child.plan_cardinality with | Zero | One -> Zero | Many -> Many); plan_patterns = !prj_pats; }) hav_exp; begin match !child.plan_cardinality with | Zero | One -> () | Many -> if List.length ord_exps > 0 then child := { plan_loc = se.se_orderby_loc; plan_desc = Tplan_sort (!child, ord_exps, ord_dirs); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = !child.plan_cardinality; plan_patterns = !child.plan_patterns; } end; sel_exp in (* build the final project *) child := { plan_loc = sel_exp.exp_loc; plan_desc = Tplan_project (!child, [sel_exp]); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = !child.plan_cardinality; plan_patterns = []; }; if se.se_distinct.txt then child := { plan_loc = se.se_distinct.loc; plan_desc = Tplan_unique !child; plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = !child.plan_cardinality; plan_patterns = []; }; end_se_scope (); !child let type_aggregate env sfunct sarg = let lid = Ldot (Lident "Stdlib", "agg") in let path, decl = Env.lookup_type ~loc:sfunct.pexp_loc lid env in let vars = Ctype.instance_list decl.type_params in let ty_arg, ty_ret = match vars with | [arg; ret] -> arg, ret | _ -> failwith "type_aggregate" in let ty_funct = newconstr path vars in let funct = Typecore.type_expect env sfunct (Typecore.mk_expected ty_funct) in let arg = Typecore.type_expect env sarg (Typecore.mk_expected ty_arg) in funct, arg, ty_ret let transl env plan = let open Untypeast in let open Location in let loc = plan.plan_loc in let lident ?(loc=loc) txt = let strs = String.split_on_char '.' (String.trim txt) in let lid = match unflatten strs with | None -> failwith "transl" | Some lid -> lid in mkloc lid loc in let lunit = lident "()" in let punit = Pat.construct lunit None in let pvar s = Pat.var (mkloc s loc) in let pint n = Pat.constant (Const.int n) in let ptup = function | [] -> punit | [p] -> p | pats -> Pat.tuple pats in let pconstr lid params = match params with | [] -> Pat.construct lid None | ps -> Pat.construct lid (Some ([], ptup ps)) in let eunit = Exp.construct lunit None in let eid txt = Exp.ident (lident ~loc txt) in let eint n = Exp.constant (Const.int n) in let etup = function | [] -> eunit | [e] -> e | exps -> Exp.tuple exps in let fun_ pats exp = List.fold_right (fun pat exp -> Exp.fun_ ~loc Nolabel None pat exp) pats exp in let ($) func arg = Exp.apply func [Nolabel, arg] in let rec exp_of_pat pat = let loc = pat.Parsetree.ppat_loc in match pat.Parsetree.ppat_desc with | Ppat_var s -> Exp.ident ~loc (mkloc (Lident s.txt) loc) | Ppat_construct ({txt=Lident "()"; _}, None) -> eunit | Ppat_tuple l -> etup (List.map exp_of_pat l) | _ -> assert false in let (||>) a b = b $ a in let cmp = eid "Stdlib.compare" in let firstrow = eid "Stdlib.firstrow" in let cagg = lident "Stdlib.Agg" in let csome = lident "Stdlib.Option.Some" in let cnone = lident "Stdlib.Option.None" in let input = eid "SelectML.input" in let output = eid "SelectML.output" in let one = eid "SelectML.one" in let singleton = eid "SelectML.singleton" in let product = eid "SelectML.product" in let join = eid "SelectML.join" in let equijoin = eid "SelectML.equijoin" in let map = eid "SelectML.map" in let filter = eid "SelectML.filter" in let sort = eid "SelectML.sort" in let unique = eid "SelectML.unique" in let group_all = eid "SelectML.group_all" in let group = eid "SelectML.group" in let mkagg pat fs es = let accpat = ptup (List.mapi (fun i _ -> pvar ("__tmp_acc" ^ string_of_int i)) fs) in let accexps = List.mapi (fun i _ -> eid ("__tmp_acc" ^ string_of_int i)) fs in let exps = List.combine accexps es in let vbs, fs = List.mapi (fun i f -> let n = string_of_int i in let acc = "__tmp_accum" ^ n in let iter = "__tmp_iter" ^ n in let res = "__tmp_result" ^ n in match f with | None -> Vb.mk (pconstr cagg [pvar acc; pvar iter; pvar res]) firstrow, (eid acc, eid iter, eid res) | Some f -> Vb.mk (pconstr cagg [pvar acc; pvar iter; pvar res]) f, (eid acc, eid iter, eid res)) fs |> List.split in let accum = etup (List.map (fun (acc, _, _) -> acc) fs) in let iter = fun_ [accpat; pat] @@ etup (List.map2 (fun (_, iter, _) (acc, e) -> iter $ acc $ e) fs exps) in let res = fun_ [accpat] @@ etup (List.map2 (fun (_, _, res) acc -> res $ acc) fs accexps) in List.fold_right (fun vb exp -> Exp.let_ Nonrecursive [vb] exp) vbs (Exp.construct cagg @@ Some (etup [accum; iter; res])) in (* check SelectML module *) let () = let check_exp = eid "ignore" $ Exp.constraint_ (Exp.pack (Mod.ident (lident "SelectML"))) (Typ.package (lident "Stdlib.SelectMLType") []) in ignore (Typecore.type_exp env check_exp) in let rec aux plan = match plan.plan_desc with | Tplan_null -> singleton $ eunit | Tplan_source e -> input $ untype_expression e | Tplan_product (pl1, pl2) -> let pat1 = ptup pl1.plan_patterns in let pat2 = ptup pl2.plan_patterns in let exp = etup @@ List.map exp_of_pat (pl1.plan_patterns @ pl2.plan_patterns) in product $ fun_ [pat1; pat2] exp $ aux pl1 $ aux pl2 | Tplan_join (pl1, pl2, e) -> let pat1 = ptup pl1.plan_patterns in let pat2 = ptup pl2.plan_patterns in let exp = etup @@ List.map exp_of_pat (pl1.plan_patterns @ pl2.plan_patterns) in let cond = untype_expression e in join $ fun_ [pat1; pat2] (Exp.ifthenelse cond (Exp.construct csome (Some exp)) (Some (Exp.construct cnone None))) $ aux pl1 $ aux pl2 | Tplan_equijoin (pl1, e1, pl2, e2) -> let pat1 = ptup pl1.plan_patterns in let pat2 = ptup pl2.plan_patterns in let exp = etup @@ List.map exp_of_pat (pl1.plan_patterns @ pl2.plan_patterns) in let key1 = untype_expression e1 in let key2 = untype_expression e2 in equijoin $ fun_ [pat1; pat2] exp $ aux pl1 $ fun_ [pat1] key1 $ aux pl2 $ fun_ [pat2] key2 | Tplan_project (pl, es) -> let pat = ptup pl.plan_patterns in let exp = etup (List.map untype_expression es) in aux pl ||> (map $ fun_ [pat] exp) | Tplan_filter (pl, e) -> let pat = ptup pl.plan_patterns in let exp = untype_expression e in aux pl ||> (filter $ fun_ [pat] exp) | Tplan_sort (pl, es, os) -> let pat = ptup pl.plan_patterns in let exp = etup (List.map untype_expression es) in let cmpfunc = let args = [pvar "__tmp_key"; pvar "__tmp_a"; pvar "__tmp_b"] in let body = let p1 = ptup (List.mapi (fun i _ -> pvar ("__tmp_a" ^ string_of_int i)) os) in let p2 = ptup (List.mapi (fun i _ -> pvar ("__tmp_b" ^ string_of_int i)) os) in let rec loop i os = let aux o = let a = eid ("__tmp_a" ^ string_of_int i) in let b = eid ("__tmp_b" ^ string_of_int i) in match o with | TAscending -> cmp $ a $ b | TDescending -> cmp $ b $ a | TUsing e -> untype_expression e $ a $ b in match os with | [] -> eint 0 | o :: os -> Exp.match_ (aux o) [Exp.case (pint 0) (loop (i+1) os); Exp.case (pvar "__tmp_res") (eid "__tmp_res")] in Exp.let_ Nonrecursive [Vb.mk p1 (eid "__tmp_key" $ eid "__tmp_a"); Vb.mk p2 (eid "__tmp_key" $ eid "__tmp_b")] (loop 0 os) in fun_ args body in let func = Exp.let_ Nonrecursive [Vb.mk (pvar "__tmp_key") (fun_ [pat] exp); Vb.mk (pvar "__tmp_cmp") cmpfunc] (sort $ (eid "__tmp_cmp" $ eid "__tmp_key")) in aux pl ||> func | Tplan_aggregate_all (pl, fs, es) -> let pat = ptup pl.plan_patterns in let fs = List.map (Option.map untype_expression) fs in let es = List.map untype_expression es in aux pl ||> (group_all $ mkagg pat fs es) ||> singleton | Tplan_aggregate (pl, e, fs, es) -> let pat = ptup pl.plan_patterns in let exp = untype_expression e in let fs = List.map (Option.map untype_expression) fs in let es = List.map untype_expression es in let key = fun_ [pat] exp in aux pl ||> (group $ key $ mkagg pat fs es) | Tplan_unique pl -> aux pl ||> unique in let ast = aux plan in match plan.plan_cardinality with | One -> one $ ast | Zero | Many -> output $ ast let type_select ~loc env se ty_expected_explained = let plan = build_plan ~loc env se in let transl pl = Typecore.type_expect env (transl env pl) ty_expected_explained in plan, transl let () = Typecore.type_select := type_select; Typecore.type_aggregate := type_aggregate (* Query plan optimization *) let pushdown_predicates plan = let open Either in let is_and : Types.value_description -> bool = function | { val_kind = Val_prim { Primitive.prim_name = "%sequand"; prim_arity = 2 } } -> true | _ -> false in let is_eq : Types.value_description -> bool = function | { val_kind = Val_prim { Primitive.prim_name = "%equal"; prim_arity = 2 } } -> true | _ -> false in let is_related_to pl pred = let result = ref false in let super = Tast_iterator.default_iterator in let expr self pred = match pred.exp_desc with | Texp_ident (Path.Pident id, _, _) -> begin try ignore (Ident.find_same id pl.plan_vars); result := true; with Not_found -> () end | _ -> super.expr self pred in let iterator = { super with expr } in iterator.expr iterator pred; !result in let extract_related_preds pred pl = let rec split_ands acc pred = match pred.exp_desc with | Texp_apply ({exp_desc = Texp_ident (_, _, vd)}, [Nolabel, Some e1; Nolabel, Some e2]) when is_and vd -> split_ands (split_ands acc e1) e2 | _ -> pred :: acc in List.partition (is_related_to pl) (split_ands [] pred) in let extract_eq_keys pred pl1 pl2 = match pred.exp_desc with | Texp_apply ({exp_desc = Texp_ident (_, _, vd)}, [Nolabel, Some e1; Nolabel, Some e2]) when is_eq vd -> begin match is_related_to pl1 e1, is_related_to pl2 e1, is_related_to pl1 e2, is_related_to pl2 e2 with | true, false, false, true -> Left (Left (e1, e2)) | false, true, true, false -> Left (Left (e2, e1)) | true, false, _, false | _, false, true, false -> Right (Left pred) | false, true, false, _ | false, _, false, true -> Right (Right pred) | _ -> Left (Right pred) end | _ -> begin match is_related_to pl1 pred, is_related_to pl2 pred with | true, false -> Right (Left pred) | false, true -> Right (Right pred) | _ -> Left (Right pred) end in let rec aux plan related_preds = let loc = plan.plan_loc in let env = plan.plan_env in let make_pred = function | [] -> assert false | hd :: tl -> let lid = Ldot (Lident "Stdlib", "&&") in let path, desc = Env.lookup_value ~loc lid env in List.fold_left (fun acc pred -> { exp_desc = Texp_apply ( { exp_desc = Texp_ident (path, mkloc lid loc, desc); exp_loc = loc; exp_type = desc.val_type; exp_env = env; exp_extra = []; exp_attributes = []; }, [ Nolabel, Some acc; Nolabel, Some pred ] ); exp_loc = loc; exp_type = Predef.type_bool; exp_env = env; exp_extra = []; exp_attributes = []; }) hd tl in let make_key = function | [] -> assert false | key :: [] -> key | keys -> { exp_desc = Texp_tuple keys; exp_loc = loc; exp_type = newty (Ttuple (List.map (fun e -> e.exp_type) keys)); exp_env = env; exp_extra = []; exp_attributes = []; } in match plan.plan_desc with | Tplan_filter (pl, pred) -> let related, unrelated = extract_related_preds pred pl in let pl, unrelated_preds = aux pl (related @ related_preds) in begin match unrelated @ unrelated_preds with | [] -> pl | preds -> { plan with plan_desc = Tplan_filter (pl, make_pred preds) } end, [] | Tplan_source _ -> begin match related_preds with | [] -> plan | preds -> { plan with plan_desc = Tplan_filter (plan, make_pred preds) } end, [] | Tplan_product (pl1, pl2) -> let keys1, keys2, general_preds, pl1_preds, pl2_preds = List.fold_left (fun (keys1, keys2, general_preds, pl1_preds, pl2_preds) pred -> match extract_eq_keys pred pl1 pl2 with | Left (Left (key1, key2)) -> key1 :: keys1, key2 :: keys2, general_preds, pl1_preds, pl2_preds | Left (Right pred) -> keys1, keys2, pred :: general_preds, pl1_preds, pl2_preds | Right (Left pred) -> keys1, keys2, general_preds, pred :: pl1_preds, pl2_preds | Right (Right pred) -> keys1, keys2, general_preds, pl1_preds, pred :: pl2_preds) ([], [], [], [], []) related_preds in begin match keys1, keys2, general_preds with | [], [], [] -> { plan with plan_desc = Tplan_product ( fst (aux pl1 pl1_preds), fst (aux pl2 pl2_preds)) } | [], [], join_preds -> { plan with plan_desc = Tplan_join ( fst (aux pl1 pl1_preds), fst (aux pl2 pl2_preds), make_pred join_preds) } | (_ :: _), (_ :: _), [] -> { plan with plan_desc = Tplan_equijoin ( fst (aux pl1 pl1_preds), make_key keys1, fst (aux pl2 pl2_preds), make_key keys2) } | (_ :: _), (_ :: _), preds -> { plan with plan_desc = Tplan_filter ( { plan with plan_desc = Tplan_equijoin ( fst (aux pl1 pl1_preds), make_key keys1, fst (aux pl2 pl2_preds), make_key keys2) }, make_pred preds) } | _, _, _ -> assert false end, [] | Tplan_join (pl1, pl2, pred) -> aux { plan with plan_desc = Tplan_filter ( { plan with plan_desc = Tplan_product (pl1, pl2) }, pred) } related_preds | Tplan_project (pl, es) -> {plan with plan_desc = Tplan_project (fst (aux pl []), es)}, related_preds | Tplan_sort (pl, es, os) -> {plan with plan_desc = Tplan_sort (fst (aux pl []), es, os)}, related_preds | Tplan_aggregate_all (pl, fs, es) -> {plan with plan_desc = Tplan_aggregate_all (fst (aux pl []), fs, es)}, related_preds | Tplan_aggregate (pl, e, fs, es) -> {plan with plan_desc = Tplan_aggregate (fst (aux pl []), e, fs, es)}, related_preds | Tplan_unique pl -> {plan with plan_desc = Tplan_unique (fst (aux pl []))}, related_preds | _ -> plan, related_preds in fst (aux plan []) let optimize pl = pushdown_predicates pl
null
https://raw.githubusercontent.com/dyzsr/ocaml-selectml/4b5777d28ad5d26ec091898c90a997821258ddb5/typing/typeplan.ml
ocaml
************************************************************************ OCaml All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Typing for query plans accumulate value bindings handle FROM clause handle WHERE clause handle SELECT clause Find identical expressions handle aggregation handle GROUP BY clause merge identical columns build an auxiliary project before grouping build aggregation handle HAVING and ORDER BY clauses merge identical columns build an auxiliary project build the final project check SelectML module Query plan optimization
Copyright 2022 the GNU Lesser General Public License version 2.1 , with the open Longident open Asttypes open Parsetree open Ast_helper open Types open Typedtree open Ctype let scope_check scopes exp = let super = Tast_iterator.default_iterator in let current_scope = List.hd scopes in let outer_scopes = List.tl scopes in let current = ref false in let outer = ref false in let expr self exp = match exp.exp_desc with | Texp_ident (Path.Pident id, _, _) -> let scope = Ident.scope id in if scope = current_scope then current := true else if List.mem scope outer_scopes then outer := true | _ -> super.expr self exp in let iterator = {super with expr} in iterator.expr iterator exp; !current || not !outer let rec check_aggregate ~scopes env exp action = let super = Tast_iterator.default_iterator in let expr self exp = match exp.exp_desc with | Texp_aggregate (f, e) when scope_check scopes e -> action exp; check_no_aggregate ~scopes env f; check_no_aggregate ~scopes env e; super.expr self f | _ -> super.expr self exp in let iterator = {super with expr} in iterator.expr iterator exp and check_no_aggregate ~scopes env exp = check_aggregate ~scopes env exp (fun _ -> raise (Typecore.Error ( exp.exp_loc, env, Invalid_use_of_aggregate))) let col_gen = ref 0 let incr_col () = col_gen := !col_gen + 1 let col_of_exp exp = let loc = exp.exp_loc in let name = match exp.exp_desc with | Texp_ident (_, lid, _) -> "__col_" ^ String.concat "_" (flatten lid.txt) | _ -> incr_col(); "__col_" ^ string_of_int !col_gen in let pat = Pat.var (mkloc name loc) in let exp = { exp with exp_desc = Texp_ident (Path.Pident (Ident.create_local name), mkloc (Lident name) loc, {val_type = exp.exp_type; val_kind = Val_reg; val_loc = loc; val_attributes = []; val_uid = Types.Uid.mk ~current_unit:(Env.get_unit_name ()); }) } in (pat, exp) let expand_product exp = match exp.exp_desc with | Texp_tuple es -> let pats, cols = List.split (List.map col_of_exp es) in (es, cols, pats, { exp with exp_desc = Texp_tuple cols }) | Texp_record { fields; representation; extended_expression } -> let exps = ref [] in let cols = ref [] in let pats = ref [] in let fields = Array.map (function | label, Kept t -> label, Kept t | label, Overridden (lid, exp) -> let pat, col = col_of_exp exp in exps := exp :: !exps; cols := col :: !cols; pats := pat :: !pats; label, Overridden (lid, col)) fields in List.rev !exps, List.rev !cols, List.rev !pats, { exp with exp_desc = Texp_record {fields; representation; extended_expression} } | _ -> let pat, col = col_of_exp exp in ([exp], [col], [pat], col) let expand_aggregate ~scopes exp = let current_scope = List.hd scopes in let super = Tast_mapper.default in let aggs = ref [] in let expr self exp = match exp.exp_desc with | Texp_aggregate (func, arg) when scope_check scopes arg -> let argpat, argcol = col_of_exp arg in let retpat, retcol = col_of_exp exp in aggs := (arg, argcol, argpat, Some func, retcol, retpat) :: !aggs; retcol | Texp_ident (Path.Pident id, _, _) when Ident.scope id = current_scope -> let pat, col = col_of_exp exp in aggs := (exp, col, pat, None, col, pat) :: !aggs; col | _ -> super.expr self exp in let mapper = {super with expr} in let exp = mapper.expr mapper exp in let aggs = List.rev !aggs in let funcs = List.map (fun (func, _, _, _, _, _) -> func) aggs in let arglist = List.map (fun (_, arg, _, _, _, _) -> arg) aggs in let argcols = List.map (fun (_, _, col, _, _, _) -> col) aggs in let argpats = List.map (fun (_, _, _, pat, _, _) -> pat) aggs in let retcols = List.map (fun (_, _, _, _, col, _) -> col) aggs in let retpats = List.map (fun (_, _, _, _, _, pat) -> pat) aggs in (funcs, arglist, argcols, argpats, retcols, retpats, exp) let build_plan ~loc env se = let old_env = env in let scope = create_scope () in let child = ref { plan_desc = Tplan_null; plan_loc = loc; plan_env = env; plan_vars = Ident.empty; plan_cardinality = One; plan_patterns = [Pat.construct ~loc (mkloc (Lident "()") loc) None]; } in let handle_from se_from = let vars = Hashtbl.create 31 in let rec aux srcexpr = match srcexpr.psrc_desc with | Psrc_exp (e, s) -> List.iter (fun {txt=v; loc} -> if Hashtbl.mem vars v then raise Typecore.(Error (loc, env, Multiply_bound_variable v)); Hashtbl.add vars v ()) s; let tys = List.map (fun _ -> newvar ()) s in let ty_src = let lid = Ldot (Lident "SelectML", "src") in let path, decl = Env.lookup_type ~loc:e.pexp_loc lid env in assert (List.length decl.type_params = 1); let ty = match tys with | [ty] -> ty | tys -> newty (Ttuple tys) in newconstr path [ty] in let vbs = List.map2 (fun v ty -> let id = Ident.create_scoped ~scope v.txt in let desc = { val_type = ty; val_kind = Val_reg; val_attributes = []; val_loc = v.loc; val_uid = Uid.mk ~current_unit:(Env.get_unit_name ()); } in id, desc) s tys in let exp = Typecore.type_expect old_env e (Typecore.mk_expected ty_src) in let env = List.fold_left (fun env (id, desc) -> Env.add_value id desc env) env vbs in let vars = List.fold_left (fun vars (id, _) -> Ident.add id () vars) Ident.empty vbs in let plan = { plan_loc = srcexpr.psrc_loc; plan_desc = Tplan_source exp; plan_env = env; plan_vars = vars; plan_cardinality = Many; plan_patterns = List.map (fun s -> Pat.var ~loc:srcexpr.psrc_loc s) s; } in plan, vbs | Psrc_product (s1, s2) -> let pl1, vbs1 = aux s1 in let pl2, vbs2 = aux s2 in let vbs = vbs1 @ vbs2 in let env = List.fold_left (fun env (id, desc) -> Env.add_value id desc env) env vbs in let vars = List.fold_left (fun vars (id, _) -> Ident.add id () vars) pl1.plan_vars vbs2 in let plan = { plan_loc = srcexpr.psrc_loc; plan_desc = Tplan_product (pl1, pl2); plan_env = env; plan_vars = vars; plan_cardinality = Many; plan_patterns = pl1.plan_patterns @ pl2.plan_patterns; } in plan, vbs1 @ vbs2 | Psrc_join (s1, s2, e) -> let pl1, vbs1 = aux s1 in let pl2, vbs2 = aux s2 in let vbs = vbs1 @ vbs2 in let joinenv = List.fold_left (fun env (id, desc) -> Env.add_value id desc env) env vbs in let vars = List.fold_left (fun vars (id, _) -> Ident.add id () vars) pl1.plan_vars vbs2 in let exp = Typecore.type_expect joinenv e (Typecore.mk_expected Predef.type_bool) in let plan = { plan_loc = srcexpr.psrc_loc; plan_desc = Tplan_join (pl1, pl2, exp); plan_env = joinenv; plan_vars = vars; plan_cardinality = Many; plan_patterns = pl1.plan_patterns @ pl2.plan_patterns; } in plan, vbs in aux se_from in let env = match se.se_from with | None -> env | Some se_from -> let plan, vbs = handle_from se_from in child := plan; List.fold_left (fun env (id, desc) -> Env.add_value id desc env) env vbs in begin_se_scope scope; let scopes = se_scopes () in begin match se.se_where with | None -> () | Some se_where -> let exp = Typecore.type_exp env se_where in check_no_aggregate ~scopes env exp; child := { plan_loc = exp.exp_loc; plan_desc = Tplan_filter (!child, exp); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = (match !child.plan_cardinality with | Zero | One -> Zero | Many -> Many); plan_patterns = !child.plan_patterns } end; let no_aggregate = ref true in let no_extra_project = ref true in let sel_exp = let exp = Typecore.type_exp env se.se_select in check_aggregate ~scopes env exp (fun _ -> no_aggregate := false); exp in if Option.is_some se.se_groupby then no_aggregate := false; if Option.is_some se.se_having then no_extra_project := false; if List.length se.se_orderby > 0 then no_extra_project := false; let aux sexp = let exp = Typecore.type_exp env sexp in check_aggregate ~scopes env exp (fun _ -> no_aggregate := false); exp in let hav_exp = match se.se_having with | Some sexp when !no_aggregate -> Some (aux sexp) | _ -> None in let ord_exps = match se.se_orderby with | _ :: _ when !no_aggregate -> List.map (fun (sexp, _) -> aux sexp) se.se_orderby | _ -> [] in let ord_dirs = List.map (function | _, PAscending -> TAscending | _, PDescending -> TDescending | _, PUsing sexp -> TUsing (Typecore.type_exp old_env sexp)) se.se_orderby in let module TastOrd = struct type t = expression let compare t1 t2 = Stdlib.compare t1 t2 end in let module AstOrd = struct type t = Parsetree.expression let compare t1 t2 = Stdlib.compare t1 t2 end in let module TastMap = Map.Make (TastOrd) in let untype_rmloc e = let rmloc = { Ast_mapper.default_mapper with location = (fun _self _loc -> Location.none) } in rmloc.expr rmloc (Untypeast.untype_expression e) in let find_identical (type a) (module Ord : Map.OrderedType with type t = a) (xs : a list) (cols : expression list) : bool array * expression TastMap.t = let module M = Map.Make (Ord) in let m = ref M.empty in let colmap = ref TastMap.empty in let mask = List.map2 (fun x p -> match M.find_opt x !m with | None -> m := M.add x p !m; colmap := TastMap.add p p !colmap; true | Some q -> colmap := TastMap.add p q !colmap; false) xs cols in Array.of_list mask, !colmap in let filter ~mask xs = List.filteri (fun i _ -> mask.(i)) xs in let substitute_columns colmap exp = let rename exp = let super = Tast_mapper.default in let expr self exp = match TastMap.find_opt exp colmap with | None -> super.expr self exp | Some col -> col in let mapper = { super with expr } in mapper.expr mapper exp in rename exp in let sel_exp, hav_exp, ord_exps = if !no_aggregate then sel_exp, hav_exp, ord_exps else let arglist, argcols, argpats, funcs, retcols, retpats, sel_exp = expand_aggregate ~scopes sel_exp in let prj_list = ref arglist in let prj_cols = ref argcols in let prj_pats = ref argpats in let agg_funcs = ref funcs in let agg_list = ref argcols in let agg_cols = ref retcols in let agg_pats = ref retpats in let aux exp = let arglist, argcols, argpats, funcs, retcols, retpats, exp = expand_aggregate ~scopes exp in prj_list := !prj_list @ arglist; prj_cols := !prj_cols @ argcols; prj_pats := !prj_pats @ argpats; agg_funcs := !agg_funcs @ funcs; agg_list := !agg_list @ argcols; agg_cols := !agg_cols @ retcols; agg_pats := !agg_pats @ retpats; exp in let hav_exp = Option.map aux (match se.se_having, hav_exp with | None, _ -> None | Some sexp, None -> Some (Typecore.type_exp env sexp) | Some _, Some exp -> Some exp) in let ord_exps = List.map aux (match se.se_orderby, ord_exps with | [], _ -> [] | sexps, [] -> List.map (fun (sexp, _) -> Typecore.type_exp env sexp) sexps | _, exps -> exps) in let grp_exp = Option.map (fun sexp -> let exp = Typecore.type_exp env sexp in check_no_aggregate ~scopes env exp; let list, cols, pats, exp = expand_product exp in prj_list := !prj_list @ list; prj_cols := !prj_cols @ cols; prj_pats := !prj_pats @ pats; exp) se.se_groupby in let mask, colmap = let xs = List.map untype_rmloc !prj_list in find_identical (module AstOrd) xs !prj_cols in prj_list := filter ~mask !prj_list; prj_cols := filter ~mask !prj_cols; prj_pats := filter ~mask !prj_pats; let grp_exp = Option.map (substitute_columns colmap) grp_exp in agg_list := List.map (substitute_columns colmap) !agg_list; agg_funcs := List.map (Option.map (substitute_columns colmap)) !agg_funcs; child := { plan_loc = loc; plan_desc = Tplan_project (!child, !prj_list); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = !child.plan_cardinality; plan_patterns = !prj_pats; }; let module Ord = struct type t = Parsetree.expression option * Parsetree.expression let compare = Stdlib.compare end in let mask, colmap = let xs = List.map2 (fun f e -> Option.map untype_rmloc f, untype_rmloc e) !agg_funcs !agg_list in find_identical (module Ord) xs !agg_cols in agg_funcs := filter ~mask !agg_funcs; agg_list := filter ~mask !agg_list; agg_pats := filter ~mask !agg_pats; let sel_exp = substitute_columns colmap sel_exp in let hav_exp = Option.map (substitute_columns colmap) hav_exp in let ord_exps = List.map (substitute_columns colmap) ord_exps in begin match grp_exp with | None -> child := { plan_loc = loc; plan_desc = Tplan_aggregate_all (!child, !agg_funcs, !agg_list); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = One; plan_patterns = !agg_pats; } | Some grp_exp -> let plan_loc = grp_exp.exp_loc in child := { plan_loc; plan_desc = Tplan_aggregate (!child, grp_exp, !agg_funcs, !agg_list); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = !child.plan_cardinality; plan_patterns = !agg_pats; } end; (sel_exp, hav_exp, ord_exps) in let sel_exp = if !no_extra_project then sel_exp else let sel_list, sel_cols, sel_pats, sel_exp = expand_product sel_exp in let prj_list = ref sel_list in let prj_cols = ref sel_cols in let prj_pats = ref sel_pats in let aux = fun exp -> let list, cols, pats, exp = expand_product exp in prj_list := !prj_list @ list; prj_cols := !prj_cols @ cols; prj_pats := !prj_pats @ pats; exp in let hav_exp = Option.map aux hav_exp in let ord_exps = List.map aux ord_exps in let mask, colmap = let xs = List.map untype_rmloc !prj_list in find_identical (module AstOrd) xs !prj_cols in prj_list := filter ~mask !prj_list; prj_pats := filter ~mask !prj_pats; let sel_exp = substitute_columns colmap sel_exp in let hav_exp = Option.map (substitute_columns colmap) hav_exp in let ord_exps = List.map (substitute_columns colmap) ord_exps in child := { plan_loc = loc; plan_desc = Tplan_project (!child, !prj_list); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = !child.plan_cardinality; plan_patterns = !prj_pats; }; Option.iter (fun exp -> child := { plan_loc = exp.exp_loc; plan_desc = Tplan_filter (!child, exp); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = (match !child.plan_cardinality with | Zero | One -> Zero | Many -> Many); plan_patterns = !prj_pats; }) hav_exp; begin match !child.plan_cardinality with | Zero | One -> () | Many -> if List.length ord_exps > 0 then child := { plan_loc = se.se_orderby_loc; plan_desc = Tplan_sort (!child, ord_exps, ord_dirs); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = !child.plan_cardinality; plan_patterns = !child.plan_patterns; } end; sel_exp in child := { plan_loc = sel_exp.exp_loc; plan_desc = Tplan_project (!child, [sel_exp]); plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = !child.plan_cardinality; plan_patterns = []; }; if se.se_distinct.txt then child := { plan_loc = se.se_distinct.loc; plan_desc = Tplan_unique !child; plan_env = !child.plan_env; plan_vars = !child.plan_vars; plan_cardinality = !child.plan_cardinality; plan_patterns = []; }; end_se_scope (); !child let type_aggregate env sfunct sarg = let lid = Ldot (Lident "Stdlib", "agg") in let path, decl = Env.lookup_type ~loc:sfunct.pexp_loc lid env in let vars = Ctype.instance_list decl.type_params in let ty_arg, ty_ret = match vars with | [arg; ret] -> arg, ret | _ -> failwith "type_aggregate" in let ty_funct = newconstr path vars in let funct = Typecore.type_expect env sfunct (Typecore.mk_expected ty_funct) in let arg = Typecore.type_expect env sarg (Typecore.mk_expected ty_arg) in funct, arg, ty_ret let transl env plan = let open Untypeast in let open Location in let loc = plan.plan_loc in let lident ?(loc=loc) txt = let strs = String.split_on_char '.' (String.trim txt) in let lid = match unflatten strs with | None -> failwith "transl" | Some lid -> lid in mkloc lid loc in let lunit = lident "()" in let punit = Pat.construct lunit None in let pvar s = Pat.var (mkloc s loc) in let pint n = Pat.constant (Const.int n) in let ptup = function | [] -> punit | [p] -> p | pats -> Pat.tuple pats in let pconstr lid params = match params with | [] -> Pat.construct lid None | ps -> Pat.construct lid (Some ([], ptup ps)) in let eunit = Exp.construct lunit None in let eid txt = Exp.ident (lident ~loc txt) in let eint n = Exp.constant (Const.int n) in let etup = function | [] -> eunit | [e] -> e | exps -> Exp.tuple exps in let fun_ pats exp = List.fold_right (fun pat exp -> Exp.fun_ ~loc Nolabel None pat exp) pats exp in let ($) func arg = Exp.apply func [Nolabel, arg] in let rec exp_of_pat pat = let loc = pat.Parsetree.ppat_loc in match pat.Parsetree.ppat_desc with | Ppat_var s -> Exp.ident ~loc (mkloc (Lident s.txt) loc) | Ppat_construct ({txt=Lident "()"; _}, None) -> eunit | Ppat_tuple l -> etup (List.map exp_of_pat l) | _ -> assert false in let (||>) a b = b $ a in let cmp = eid "Stdlib.compare" in let firstrow = eid "Stdlib.firstrow" in let cagg = lident "Stdlib.Agg" in let csome = lident "Stdlib.Option.Some" in let cnone = lident "Stdlib.Option.None" in let input = eid "SelectML.input" in let output = eid "SelectML.output" in let one = eid "SelectML.one" in let singleton = eid "SelectML.singleton" in let product = eid "SelectML.product" in let join = eid "SelectML.join" in let equijoin = eid "SelectML.equijoin" in let map = eid "SelectML.map" in let filter = eid "SelectML.filter" in let sort = eid "SelectML.sort" in let unique = eid "SelectML.unique" in let group_all = eid "SelectML.group_all" in let group = eid "SelectML.group" in let mkagg pat fs es = let accpat = ptup (List.mapi (fun i _ -> pvar ("__tmp_acc" ^ string_of_int i)) fs) in let accexps = List.mapi (fun i _ -> eid ("__tmp_acc" ^ string_of_int i)) fs in let exps = List.combine accexps es in let vbs, fs = List.mapi (fun i f -> let n = string_of_int i in let acc = "__tmp_accum" ^ n in let iter = "__tmp_iter" ^ n in let res = "__tmp_result" ^ n in match f with | None -> Vb.mk (pconstr cagg [pvar acc; pvar iter; pvar res]) firstrow, (eid acc, eid iter, eid res) | Some f -> Vb.mk (pconstr cagg [pvar acc; pvar iter; pvar res]) f, (eid acc, eid iter, eid res)) fs |> List.split in let accum = etup (List.map (fun (acc, _, _) -> acc) fs) in let iter = fun_ [accpat; pat] @@ etup (List.map2 (fun (_, iter, _) (acc, e) -> iter $ acc $ e) fs exps) in let res = fun_ [accpat] @@ etup (List.map2 (fun (_, _, res) acc -> res $ acc) fs accexps) in List.fold_right (fun vb exp -> Exp.let_ Nonrecursive [vb] exp) vbs (Exp.construct cagg @@ Some (etup [accum; iter; res])) in let () = let check_exp = eid "ignore" $ Exp.constraint_ (Exp.pack (Mod.ident (lident "SelectML"))) (Typ.package (lident "Stdlib.SelectMLType") []) in ignore (Typecore.type_exp env check_exp) in let rec aux plan = match plan.plan_desc with | Tplan_null -> singleton $ eunit | Tplan_source e -> input $ untype_expression e | Tplan_product (pl1, pl2) -> let pat1 = ptup pl1.plan_patterns in let pat2 = ptup pl2.plan_patterns in let exp = etup @@ List.map exp_of_pat (pl1.plan_patterns @ pl2.plan_patterns) in product $ fun_ [pat1; pat2] exp $ aux pl1 $ aux pl2 | Tplan_join (pl1, pl2, e) -> let pat1 = ptup pl1.plan_patterns in let pat2 = ptup pl2.plan_patterns in let exp = etup @@ List.map exp_of_pat (pl1.plan_patterns @ pl2.plan_patterns) in let cond = untype_expression e in join $ fun_ [pat1; pat2] (Exp.ifthenelse cond (Exp.construct csome (Some exp)) (Some (Exp.construct cnone None))) $ aux pl1 $ aux pl2 | Tplan_equijoin (pl1, e1, pl2, e2) -> let pat1 = ptup pl1.plan_patterns in let pat2 = ptup pl2.plan_patterns in let exp = etup @@ List.map exp_of_pat (pl1.plan_patterns @ pl2.plan_patterns) in let key1 = untype_expression e1 in let key2 = untype_expression e2 in equijoin $ fun_ [pat1; pat2] exp $ aux pl1 $ fun_ [pat1] key1 $ aux pl2 $ fun_ [pat2] key2 | Tplan_project (pl, es) -> let pat = ptup pl.plan_patterns in let exp = etup (List.map untype_expression es) in aux pl ||> (map $ fun_ [pat] exp) | Tplan_filter (pl, e) -> let pat = ptup pl.plan_patterns in let exp = untype_expression e in aux pl ||> (filter $ fun_ [pat] exp) | Tplan_sort (pl, es, os) -> let pat = ptup pl.plan_patterns in let exp = etup (List.map untype_expression es) in let cmpfunc = let args = [pvar "__tmp_key"; pvar "__tmp_a"; pvar "__tmp_b"] in let body = let p1 = ptup (List.mapi (fun i _ -> pvar ("__tmp_a" ^ string_of_int i)) os) in let p2 = ptup (List.mapi (fun i _ -> pvar ("__tmp_b" ^ string_of_int i)) os) in let rec loop i os = let aux o = let a = eid ("__tmp_a" ^ string_of_int i) in let b = eid ("__tmp_b" ^ string_of_int i) in match o with | TAscending -> cmp $ a $ b | TDescending -> cmp $ b $ a | TUsing e -> untype_expression e $ a $ b in match os with | [] -> eint 0 | o :: os -> Exp.match_ (aux o) [Exp.case (pint 0) (loop (i+1) os); Exp.case (pvar "__tmp_res") (eid "__tmp_res")] in Exp.let_ Nonrecursive [Vb.mk p1 (eid "__tmp_key" $ eid "__tmp_a"); Vb.mk p2 (eid "__tmp_key" $ eid "__tmp_b")] (loop 0 os) in fun_ args body in let func = Exp.let_ Nonrecursive [Vb.mk (pvar "__tmp_key") (fun_ [pat] exp); Vb.mk (pvar "__tmp_cmp") cmpfunc] (sort $ (eid "__tmp_cmp" $ eid "__tmp_key")) in aux pl ||> func | Tplan_aggregate_all (pl, fs, es) -> let pat = ptup pl.plan_patterns in let fs = List.map (Option.map untype_expression) fs in let es = List.map untype_expression es in aux pl ||> (group_all $ mkagg pat fs es) ||> singleton | Tplan_aggregate (pl, e, fs, es) -> let pat = ptup pl.plan_patterns in let exp = untype_expression e in let fs = List.map (Option.map untype_expression) fs in let es = List.map untype_expression es in let key = fun_ [pat] exp in aux pl ||> (group $ key $ mkagg pat fs es) | Tplan_unique pl -> aux pl ||> unique in let ast = aux plan in match plan.plan_cardinality with | One -> one $ ast | Zero | Many -> output $ ast let type_select ~loc env se ty_expected_explained = let plan = build_plan ~loc env se in let transl pl = Typecore.type_expect env (transl env pl) ty_expected_explained in plan, transl let () = Typecore.type_select := type_select; Typecore.type_aggregate := type_aggregate let pushdown_predicates plan = let open Either in let is_and : Types.value_description -> bool = function | { val_kind = Val_prim { Primitive.prim_name = "%sequand"; prim_arity = 2 } } -> true | _ -> false in let is_eq : Types.value_description -> bool = function | { val_kind = Val_prim { Primitive.prim_name = "%equal"; prim_arity = 2 } } -> true | _ -> false in let is_related_to pl pred = let result = ref false in let super = Tast_iterator.default_iterator in let expr self pred = match pred.exp_desc with | Texp_ident (Path.Pident id, _, _) -> begin try ignore (Ident.find_same id pl.plan_vars); result := true; with Not_found -> () end | _ -> super.expr self pred in let iterator = { super with expr } in iterator.expr iterator pred; !result in let extract_related_preds pred pl = let rec split_ands acc pred = match pred.exp_desc with | Texp_apply ({exp_desc = Texp_ident (_, _, vd)}, [Nolabel, Some e1; Nolabel, Some e2]) when is_and vd -> split_ands (split_ands acc e1) e2 | _ -> pred :: acc in List.partition (is_related_to pl) (split_ands [] pred) in let extract_eq_keys pred pl1 pl2 = match pred.exp_desc with | Texp_apply ({exp_desc = Texp_ident (_, _, vd)}, [Nolabel, Some e1; Nolabel, Some e2]) when is_eq vd -> begin match is_related_to pl1 e1, is_related_to pl2 e1, is_related_to pl1 e2, is_related_to pl2 e2 with | true, false, false, true -> Left (Left (e1, e2)) | false, true, true, false -> Left (Left (e2, e1)) | true, false, _, false | _, false, true, false -> Right (Left pred) | false, true, false, _ | false, _, false, true -> Right (Right pred) | _ -> Left (Right pred) end | _ -> begin match is_related_to pl1 pred, is_related_to pl2 pred with | true, false -> Right (Left pred) | false, true -> Right (Right pred) | _ -> Left (Right pred) end in let rec aux plan related_preds = let loc = plan.plan_loc in let env = plan.plan_env in let make_pred = function | [] -> assert false | hd :: tl -> let lid = Ldot (Lident "Stdlib", "&&") in let path, desc = Env.lookup_value ~loc lid env in List.fold_left (fun acc pred -> { exp_desc = Texp_apply ( { exp_desc = Texp_ident (path, mkloc lid loc, desc); exp_loc = loc; exp_type = desc.val_type; exp_env = env; exp_extra = []; exp_attributes = []; }, [ Nolabel, Some acc; Nolabel, Some pred ] ); exp_loc = loc; exp_type = Predef.type_bool; exp_env = env; exp_extra = []; exp_attributes = []; }) hd tl in let make_key = function | [] -> assert false | key :: [] -> key | keys -> { exp_desc = Texp_tuple keys; exp_loc = loc; exp_type = newty (Ttuple (List.map (fun e -> e.exp_type) keys)); exp_env = env; exp_extra = []; exp_attributes = []; } in match plan.plan_desc with | Tplan_filter (pl, pred) -> let related, unrelated = extract_related_preds pred pl in let pl, unrelated_preds = aux pl (related @ related_preds) in begin match unrelated @ unrelated_preds with | [] -> pl | preds -> { plan with plan_desc = Tplan_filter (pl, make_pred preds) } end, [] | Tplan_source _ -> begin match related_preds with | [] -> plan | preds -> { plan with plan_desc = Tplan_filter (plan, make_pred preds) } end, [] | Tplan_product (pl1, pl2) -> let keys1, keys2, general_preds, pl1_preds, pl2_preds = List.fold_left (fun (keys1, keys2, general_preds, pl1_preds, pl2_preds) pred -> match extract_eq_keys pred pl1 pl2 with | Left (Left (key1, key2)) -> key1 :: keys1, key2 :: keys2, general_preds, pl1_preds, pl2_preds | Left (Right pred) -> keys1, keys2, pred :: general_preds, pl1_preds, pl2_preds | Right (Left pred) -> keys1, keys2, general_preds, pred :: pl1_preds, pl2_preds | Right (Right pred) -> keys1, keys2, general_preds, pl1_preds, pred :: pl2_preds) ([], [], [], [], []) related_preds in begin match keys1, keys2, general_preds with | [], [], [] -> { plan with plan_desc = Tplan_product ( fst (aux pl1 pl1_preds), fst (aux pl2 pl2_preds)) } | [], [], join_preds -> { plan with plan_desc = Tplan_join ( fst (aux pl1 pl1_preds), fst (aux pl2 pl2_preds), make_pred join_preds) } | (_ :: _), (_ :: _), [] -> { plan with plan_desc = Tplan_equijoin ( fst (aux pl1 pl1_preds), make_key keys1, fst (aux pl2 pl2_preds), make_key keys2) } | (_ :: _), (_ :: _), preds -> { plan with plan_desc = Tplan_filter ( { plan with plan_desc = Tplan_equijoin ( fst (aux pl1 pl1_preds), make_key keys1, fst (aux pl2 pl2_preds), make_key keys2) }, make_pred preds) } | _, _, _ -> assert false end, [] | Tplan_join (pl1, pl2, pred) -> aux { plan with plan_desc = Tplan_filter ( { plan with plan_desc = Tplan_product (pl1, pl2) }, pred) } related_preds | Tplan_project (pl, es) -> {plan with plan_desc = Tplan_project (fst (aux pl []), es)}, related_preds | Tplan_sort (pl, es, os) -> {plan with plan_desc = Tplan_sort (fst (aux pl []), es, os)}, related_preds | Tplan_aggregate_all (pl, fs, es) -> {plan with plan_desc = Tplan_aggregate_all (fst (aux pl []), fs, es)}, related_preds | Tplan_aggregate (pl, e, fs, es) -> {plan with plan_desc = Tplan_aggregate (fst (aux pl []), e, fs, es)}, related_preds | Tplan_unique pl -> {plan with plan_desc = Tplan_unique (fst (aux pl []))}, related_preds | _ -> plan, related_preds in fst (aux plan []) let optimize pl = pushdown_predicates pl
df43a5ea432c9243485a4daa137a26430b446704ff65e20a18db5cc983e4107f
jeromesimeon/Galax
datatypes_util.mli
(***********************************************************************) (* *) (* GALAX *) (* XQuery Engine *) (* *) Copyright 2001 - 2007 . (* Distributed only by permission. *) (* *) (***********************************************************************) $ I d : datatypes_util.mli , v 1.26 2007/07/05 08:35:53 simeon Exp $ Module Datatypes_util Description : This module contains basic operations on atomic values and atomic types , at the level . Description: This module contains basic operations on atomic values and atomic types, at the Caml level. *) open Decimal open AnyURI open DateTime open Datatypes (*******************************) (* Parsing from text to values *) (*******************************) val ncname_of_untyped : xs_untyped -> xs_ncname val string_of_untyped : xs_untyped -> xs_string val boolean_of_untyped : xs_untyped -> xs_boolean val decimal_of_untyped : xs_untyped -> xs_decimal val float_of_untyped : xs_untyped -> xs_float val double_of_untyped : xs_untyped -> xs_double val dateTime_of_untyped : xs_untyped -> xs_dateTime val time_of_untyped : xs_untyped -> xs_time val date_of_untyped : xs_untyped -> xs_date val gYearMonth_of_untyped : xs_untyped -> xs_gYearMonth val gYear_of_untyped : xs_untyped -> xs_gYear val gMonthDay_of_untyped : xs_untyped -> xs_gMonthDay val gDay_of_untyped : xs_untyped -> xs_gDay val gMonth_of_untyped : xs_untyped -> xs_gMonth val hexBinary_of_untyped : xs_untyped -> xs_hexBinary val base64Binary_of_untyped : xs_untyped -> xs_base64Binary val anyURI_of_untyped : xs_untyped -> xs_anyURI val qname_of_untyped : Namespace_context.nsenv -> xs_untyped -> xs_QName val notation_of_untyped : xs_untyped -> xs_NOTATION val integer_of_untyped : Namespace_symbols.rtype_symbol -> xs_untyped -> xs_integer val duration_of_untyped : xs_untyped -> xs_duration val yearMonthDuration_of_untyped : xs_untyped -> xs_yearMonthDuration val dayTimeDuration_of_untyped : xs_untyped -> xs_dayTimeDuration val normalize_pi_test : xs_untyped -> xs_ncname (***************) (* Comparisons *) (***************) val string_equal : xs_string -> xs_string -> bool val string_lteq : xs_string -> xs_string -> bool val string_lt : xs_string -> xs_string -> bool val string_gteq : xs_string -> xs_string -> bool val string_gt : xs_string -> xs_string -> bool val bool_equal : xs_boolean -> xs_boolean -> bool val bool_lteq : xs_boolean -> xs_boolean -> bool val bool_lt : xs_boolean -> xs_boolean -> bool val bool_gteq : xs_boolean -> xs_boolean -> bool val bool_gt : xs_boolean -> xs_boolean -> bool val float_equal : xs_float -> xs_float -> bool val float_lteq : xs_float -> xs_float -> bool val float_lt : xs_float -> xs_float -> bool val float_gteq : xs_float -> xs_float -> bool val float_gt : xs_float -> xs_float -> bool val double_equal : xs_double -> xs_double -> bool val double_lteq : xs_double -> xs_double -> bool val double_lt : xs_double -> xs_double -> bool val double_gteq : xs_double -> xs_double -> bool val double_gt : xs_double -> xs_double -> bool val duration_equal : xs_duration -> xs_duration -> bool val duration_lteq : xs_duration -> xs_duration -> bool val duration_lt : xs_duration -> xs_duration -> bool val duration_gteq : xs_duration -> xs_duration -> bool val duration_gt : xs_duration -> xs_duration -> bool val dateTime_equal : xs_dayTimeDuration option -> xs_dateTime -> xs_dateTime -> bool val dateTime_lteq : xs_dayTimeDuration option -> xs_dateTime -> xs_dateTime -> bool val dateTime_lt : xs_dayTimeDuration option -> xs_dateTime -> xs_dateTime -> bool val dateTime_gteq : xs_dayTimeDuration option -> xs_dateTime -> xs_dateTime -> bool val dateTime_gt : xs_dayTimeDuration option -> xs_dateTime -> xs_dateTime -> bool val time_equal : xs_dayTimeDuration option -> xs_time -> xs_time -> bool val time_lteq : xs_dayTimeDuration option -> xs_time -> xs_time -> bool val time_lt : xs_dayTimeDuration option -> xs_time -> xs_time -> bool val time_gteq : xs_dayTimeDuration option -> xs_time -> xs_time -> bool val time_gt : xs_dayTimeDuration option -> xs_time -> xs_time -> bool val date_equal : xs_dayTimeDuration option -> xs_date -> xs_date -> bool val date_lteq : xs_dayTimeDuration option -> xs_date -> xs_date -> bool val date_lt : xs_dayTimeDuration option -> xs_date -> xs_date -> bool val date_gteq : xs_dayTimeDuration option -> xs_date -> xs_date -> bool val date_gt : xs_dayTimeDuration option -> xs_date -> xs_date -> bool val gYearMonth_equal : xs_dayTimeDuration option -> xs_gYearMonth -> xs_gYearMonth -> bool val gYearMonth_lteq : xs_dayTimeDuration option -> xs_gYearMonth -> xs_gYearMonth -> bool val gYearMonth_lt : xs_dayTimeDuration option -> xs_gYearMonth -> xs_gYearMonth -> bool val gYearMonth_gteq : xs_dayTimeDuration option -> xs_gYearMonth -> xs_gYearMonth -> bool val gYearMonth_gt : xs_dayTimeDuration option -> xs_gYearMonth -> xs_gYearMonth -> bool val gYear_equal : xs_dayTimeDuration option -> xs_gYear -> xs_gYear -> bool val gYear_lteq : xs_dayTimeDuration option -> xs_gYear -> xs_gYear -> bool val gYear_lt : xs_dayTimeDuration option -> xs_gYear -> xs_gYear -> bool val gYear_gteq : xs_dayTimeDuration option -> xs_gYear -> xs_gYear -> bool val gYear_gt : xs_dayTimeDuration option -> xs_gYear -> xs_gYear -> bool val gMonthDay_equal : xs_dayTimeDuration option -> xs_gMonthDay -> xs_gMonthDay -> bool val gMonthDay_lteq : xs_dayTimeDuration option -> xs_gMonthDay -> xs_gMonthDay -> bool val gMonthDay_lt : xs_dayTimeDuration option -> xs_gMonthDay -> xs_gMonthDay -> bool val gMonthDay_gteq : xs_dayTimeDuration option -> xs_gMonthDay -> xs_gMonthDay -> bool val gMonthDay_gt : xs_dayTimeDuration option -> xs_gMonthDay -> xs_gMonthDay -> bool val gMonth_equal : xs_dayTimeDuration option -> xs_gMonth -> xs_gMonth -> bool val gMonth_lteq : xs_dayTimeDuration option -> xs_gMonth -> xs_gMonth -> bool val gMonth_lt : xs_dayTimeDuration option -> xs_gMonth -> xs_gMonth -> bool val gMonth_gteq : xs_dayTimeDuration option -> xs_gMonth -> xs_gMonth -> bool val gMonth_gt : xs_dayTimeDuration option -> xs_gMonth -> xs_gMonth -> bool val gDay_equal : xs_dayTimeDuration option -> xs_gDay -> xs_gDay -> bool val gDay_lteq : xs_dayTimeDuration option -> xs_gDay -> xs_gDay -> bool val gDay_lt : xs_dayTimeDuration option -> xs_gDay -> xs_gDay -> bool val gDay_gteq : xs_dayTimeDuration option -> xs_gDay -> xs_gDay -> bool val gDay_gt : xs_dayTimeDuration option -> xs_gDay -> xs_gDay -> bool val hexBinary_equal : xs_hexBinary -> xs_hexBinary -> bool val hexBinary_lteq : xs_hexBinary -> xs_hexBinary -> bool val hexBinary_lt : xs_hexBinary -> xs_hexBinary -> bool val hexBinary_gteq : xs_hexBinary -> xs_hexBinary -> bool val hexBinary_gt : xs_hexBinary -> xs_hexBinary -> bool val base64Binary_equal : xs_base64Binary -> xs_base64Binary -> bool val base64Binary_lteq : xs_base64Binary -> xs_base64Binary -> bool val base64Binary_lt : xs_base64Binary -> xs_base64Binary -> bool val base64Binary_gteq : xs_base64Binary -> xs_base64Binary -> bool val base64Binary_gt : xs_base64Binary -> xs_base64Binary -> bool val anyURI_equal : xs_anyURI -> xs_anyURI -> bool val qname_equal : xs_QName -> xs_QName -> bool val qname_lteq : xs_QName -> xs_QName -> bool val qname_lt : xs_QName -> xs_QName -> bool val qname_gteq : xs_QName -> xs_QName -> bool val qname_gt : xs_QName -> xs_QName -> bool val notation_equal : xs_NOTATION -> xs_NOTATION -> bool val notation_lteq : xs_NOTATION -> xs_NOTATION -> bool val notation_lt : xs_NOTATION -> xs_NOTATION -> bool val notation_gteq : xs_NOTATION -> xs_NOTATION -> bool val notation_gt : xs_NOTATION -> xs_NOTATION -> bool val yearMonthDuration_equal : xs_yearMonthDuration -> xs_yearMonthDuration -> bool val yearMonthDuration_lteq : xs_yearMonthDuration -> xs_yearMonthDuration -> bool val yearMonthDuration_lt : xs_yearMonthDuration -> xs_yearMonthDuration -> bool val yearMonthDuration_gteq : xs_yearMonthDuration -> xs_yearMonthDuration -> bool val yearMonthDuration_gt : xs_yearMonthDuration -> xs_yearMonthDuration -> bool val dayTimeDuration_equal : xs_dayTimeDuration -> xs_dayTimeDuration -> bool val dayTimeDuration_lteq : xs_dayTimeDuration -> xs_dayTimeDuration -> bool val dayTimeDuration_lt : xs_dayTimeDuration -> xs_dayTimeDuration -> bool val dayTimeDuration_gteq : xs_dayTimeDuration -> xs_dayTimeDuration -> bool val dayTimeDuration_gt : xs_dayTimeDuration -> xs_dayTimeDuration -> bool val untyped_equal : xs_untyped -> xs_untyped -> bool val untyped_lteq : xs_untyped -> xs_untyped -> bool val untyped_lt : xs_untyped -> xs_untyped -> bool val untyped_gteq : xs_untyped -> xs_untyped -> bool val untyped_gt : xs_untyped -> xs_untyped -> bool (*******************************) Operations on atomic values (*******************************) val serialize_float : xs_float -> string val serialize_double : xs_double -> string val serialize_base64Binary : xs_base64Binary -> string val serialize_hexBinary : xs_hexBinary -> string (******************************) Operations on atomic types (******************************) val atomic_is_numeric : atomic_type -> bool val atomic_is_anyURI : atomic_type -> bool val atomic_is_anystring : atomic_type -> bool val atomic_type_subsumes : atomic_type -> atomic_type -> bool val untyped_atomic_type : atomic_type val lookup_bltin_type : Namespace_symbols.rtype_symbol -> atomic_type val symbol_of_primitive_type : atomic_type -> Namespace_symbols.rtype_symbol val unit_symbol_of_base_type : atomic_type -> Namespace_symbols.rtype_symbol val can_be_promoted_to : atomic_type -> atomic_type list val bt_can_be_promoted_to : atomic_type -> atomic_type -> (bool * bool) val string_of_atomic_type : Datatypes.atomic_type -> string val compare_types : Datatypes.atomic_type -> Datatypes.atomic_type -> int val base64_of_hex : xs_base64Binary -> xs_hexBinary val hex_of_base64 : xs_hexBinary -> xs_base64Binary
null
https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/datatypes/datatypes_util.mli
ocaml
********************************************************************* GALAX XQuery Engine Distributed only by permission. ********************************************************************* ***************************** Parsing from text to values ***************************** ************* Comparisons ************* ***************************** ***************************** **************************** ****************************
Copyright 2001 - 2007 . $ I d : datatypes_util.mli , v 1.26 2007/07/05 08:35:53 simeon Exp $ Module Datatypes_util Description : This module contains basic operations on atomic values and atomic types , at the level . Description: This module contains basic operations on atomic values and atomic types, at the Caml level. *) open Decimal open AnyURI open DateTime open Datatypes val ncname_of_untyped : xs_untyped -> xs_ncname val string_of_untyped : xs_untyped -> xs_string val boolean_of_untyped : xs_untyped -> xs_boolean val decimal_of_untyped : xs_untyped -> xs_decimal val float_of_untyped : xs_untyped -> xs_float val double_of_untyped : xs_untyped -> xs_double val dateTime_of_untyped : xs_untyped -> xs_dateTime val time_of_untyped : xs_untyped -> xs_time val date_of_untyped : xs_untyped -> xs_date val gYearMonth_of_untyped : xs_untyped -> xs_gYearMonth val gYear_of_untyped : xs_untyped -> xs_gYear val gMonthDay_of_untyped : xs_untyped -> xs_gMonthDay val gDay_of_untyped : xs_untyped -> xs_gDay val gMonth_of_untyped : xs_untyped -> xs_gMonth val hexBinary_of_untyped : xs_untyped -> xs_hexBinary val base64Binary_of_untyped : xs_untyped -> xs_base64Binary val anyURI_of_untyped : xs_untyped -> xs_anyURI val qname_of_untyped : Namespace_context.nsenv -> xs_untyped -> xs_QName val notation_of_untyped : xs_untyped -> xs_NOTATION val integer_of_untyped : Namespace_symbols.rtype_symbol -> xs_untyped -> xs_integer val duration_of_untyped : xs_untyped -> xs_duration val yearMonthDuration_of_untyped : xs_untyped -> xs_yearMonthDuration val dayTimeDuration_of_untyped : xs_untyped -> xs_dayTimeDuration val normalize_pi_test : xs_untyped -> xs_ncname val string_equal : xs_string -> xs_string -> bool val string_lteq : xs_string -> xs_string -> bool val string_lt : xs_string -> xs_string -> bool val string_gteq : xs_string -> xs_string -> bool val string_gt : xs_string -> xs_string -> bool val bool_equal : xs_boolean -> xs_boolean -> bool val bool_lteq : xs_boolean -> xs_boolean -> bool val bool_lt : xs_boolean -> xs_boolean -> bool val bool_gteq : xs_boolean -> xs_boolean -> bool val bool_gt : xs_boolean -> xs_boolean -> bool val float_equal : xs_float -> xs_float -> bool val float_lteq : xs_float -> xs_float -> bool val float_lt : xs_float -> xs_float -> bool val float_gteq : xs_float -> xs_float -> bool val float_gt : xs_float -> xs_float -> bool val double_equal : xs_double -> xs_double -> bool val double_lteq : xs_double -> xs_double -> bool val double_lt : xs_double -> xs_double -> bool val double_gteq : xs_double -> xs_double -> bool val double_gt : xs_double -> xs_double -> bool val duration_equal : xs_duration -> xs_duration -> bool val duration_lteq : xs_duration -> xs_duration -> bool val duration_lt : xs_duration -> xs_duration -> bool val duration_gteq : xs_duration -> xs_duration -> bool val duration_gt : xs_duration -> xs_duration -> bool val dateTime_equal : xs_dayTimeDuration option -> xs_dateTime -> xs_dateTime -> bool val dateTime_lteq : xs_dayTimeDuration option -> xs_dateTime -> xs_dateTime -> bool val dateTime_lt : xs_dayTimeDuration option -> xs_dateTime -> xs_dateTime -> bool val dateTime_gteq : xs_dayTimeDuration option -> xs_dateTime -> xs_dateTime -> bool val dateTime_gt : xs_dayTimeDuration option -> xs_dateTime -> xs_dateTime -> bool val time_equal : xs_dayTimeDuration option -> xs_time -> xs_time -> bool val time_lteq : xs_dayTimeDuration option -> xs_time -> xs_time -> bool val time_lt : xs_dayTimeDuration option -> xs_time -> xs_time -> bool val time_gteq : xs_dayTimeDuration option -> xs_time -> xs_time -> bool val time_gt : xs_dayTimeDuration option -> xs_time -> xs_time -> bool val date_equal : xs_dayTimeDuration option -> xs_date -> xs_date -> bool val date_lteq : xs_dayTimeDuration option -> xs_date -> xs_date -> bool val date_lt : xs_dayTimeDuration option -> xs_date -> xs_date -> bool val date_gteq : xs_dayTimeDuration option -> xs_date -> xs_date -> bool val date_gt : xs_dayTimeDuration option -> xs_date -> xs_date -> bool val gYearMonth_equal : xs_dayTimeDuration option -> xs_gYearMonth -> xs_gYearMonth -> bool val gYearMonth_lteq : xs_dayTimeDuration option -> xs_gYearMonth -> xs_gYearMonth -> bool val gYearMonth_lt : xs_dayTimeDuration option -> xs_gYearMonth -> xs_gYearMonth -> bool val gYearMonth_gteq : xs_dayTimeDuration option -> xs_gYearMonth -> xs_gYearMonth -> bool val gYearMonth_gt : xs_dayTimeDuration option -> xs_gYearMonth -> xs_gYearMonth -> bool val gYear_equal : xs_dayTimeDuration option -> xs_gYear -> xs_gYear -> bool val gYear_lteq : xs_dayTimeDuration option -> xs_gYear -> xs_gYear -> bool val gYear_lt : xs_dayTimeDuration option -> xs_gYear -> xs_gYear -> bool val gYear_gteq : xs_dayTimeDuration option -> xs_gYear -> xs_gYear -> bool val gYear_gt : xs_dayTimeDuration option -> xs_gYear -> xs_gYear -> bool val gMonthDay_equal : xs_dayTimeDuration option -> xs_gMonthDay -> xs_gMonthDay -> bool val gMonthDay_lteq : xs_dayTimeDuration option -> xs_gMonthDay -> xs_gMonthDay -> bool val gMonthDay_lt : xs_dayTimeDuration option -> xs_gMonthDay -> xs_gMonthDay -> bool val gMonthDay_gteq : xs_dayTimeDuration option -> xs_gMonthDay -> xs_gMonthDay -> bool val gMonthDay_gt : xs_dayTimeDuration option -> xs_gMonthDay -> xs_gMonthDay -> bool val gMonth_equal : xs_dayTimeDuration option -> xs_gMonth -> xs_gMonth -> bool val gMonth_lteq : xs_dayTimeDuration option -> xs_gMonth -> xs_gMonth -> bool val gMonth_lt : xs_dayTimeDuration option -> xs_gMonth -> xs_gMonth -> bool val gMonth_gteq : xs_dayTimeDuration option -> xs_gMonth -> xs_gMonth -> bool val gMonth_gt : xs_dayTimeDuration option -> xs_gMonth -> xs_gMonth -> bool val gDay_equal : xs_dayTimeDuration option -> xs_gDay -> xs_gDay -> bool val gDay_lteq : xs_dayTimeDuration option -> xs_gDay -> xs_gDay -> bool val gDay_lt : xs_dayTimeDuration option -> xs_gDay -> xs_gDay -> bool val gDay_gteq : xs_dayTimeDuration option -> xs_gDay -> xs_gDay -> bool val gDay_gt : xs_dayTimeDuration option -> xs_gDay -> xs_gDay -> bool val hexBinary_equal : xs_hexBinary -> xs_hexBinary -> bool val hexBinary_lteq : xs_hexBinary -> xs_hexBinary -> bool val hexBinary_lt : xs_hexBinary -> xs_hexBinary -> bool val hexBinary_gteq : xs_hexBinary -> xs_hexBinary -> bool val hexBinary_gt : xs_hexBinary -> xs_hexBinary -> bool val base64Binary_equal : xs_base64Binary -> xs_base64Binary -> bool val base64Binary_lteq : xs_base64Binary -> xs_base64Binary -> bool val base64Binary_lt : xs_base64Binary -> xs_base64Binary -> bool val base64Binary_gteq : xs_base64Binary -> xs_base64Binary -> bool val base64Binary_gt : xs_base64Binary -> xs_base64Binary -> bool val anyURI_equal : xs_anyURI -> xs_anyURI -> bool val qname_equal : xs_QName -> xs_QName -> bool val qname_lteq : xs_QName -> xs_QName -> bool val qname_lt : xs_QName -> xs_QName -> bool val qname_gteq : xs_QName -> xs_QName -> bool val qname_gt : xs_QName -> xs_QName -> bool val notation_equal : xs_NOTATION -> xs_NOTATION -> bool val notation_lteq : xs_NOTATION -> xs_NOTATION -> bool val notation_lt : xs_NOTATION -> xs_NOTATION -> bool val notation_gteq : xs_NOTATION -> xs_NOTATION -> bool val notation_gt : xs_NOTATION -> xs_NOTATION -> bool val yearMonthDuration_equal : xs_yearMonthDuration -> xs_yearMonthDuration -> bool val yearMonthDuration_lteq : xs_yearMonthDuration -> xs_yearMonthDuration -> bool val yearMonthDuration_lt : xs_yearMonthDuration -> xs_yearMonthDuration -> bool val yearMonthDuration_gteq : xs_yearMonthDuration -> xs_yearMonthDuration -> bool val yearMonthDuration_gt : xs_yearMonthDuration -> xs_yearMonthDuration -> bool val dayTimeDuration_equal : xs_dayTimeDuration -> xs_dayTimeDuration -> bool val dayTimeDuration_lteq : xs_dayTimeDuration -> xs_dayTimeDuration -> bool val dayTimeDuration_lt : xs_dayTimeDuration -> xs_dayTimeDuration -> bool val dayTimeDuration_gteq : xs_dayTimeDuration -> xs_dayTimeDuration -> bool val dayTimeDuration_gt : xs_dayTimeDuration -> xs_dayTimeDuration -> bool val untyped_equal : xs_untyped -> xs_untyped -> bool val untyped_lteq : xs_untyped -> xs_untyped -> bool val untyped_lt : xs_untyped -> xs_untyped -> bool val untyped_gteq : xs_untyped -> xs_untyped -> bool val untyped_gt : xs_untyped -> xs_untyped -> bool Operations on atomic values val serialize_float : xs_float -> string val serialize_double : xs_double -> string val serialize_base64Binary : xs_base64Binary -> string val serialize_hexBinary : xs_hexBinary -> string Operations on atomic types val atomic_is_numeric : atomic_type -> bool val atomic_is_anyURI : atomic_type -> bool val atomic_is_anystring : atomic_type -> bool val atomic_type_subsumes : atomic_type -> atomic_type -> bool val untyped_atomic_type : atomic_type val lookup_bltin_type : Namespace_symbols.rtype_symbol -> atomic_type val symbol_of_primitive_type : atomic_type -> Namespace_symbols.rtype_symbol val unit_symbol_of_base_type : atomic_type -> Namespace_symbols.rtype_symbol val can_be_promoted_to : atomic_type -> atomic_type list val bt_can_be_promoted_to : atomic_type -> atomic_type -> (bool * bool) val string_of_atomic_type : Datatypes.atomic_type -> string val compare_types : Datatypes.atomic_type -> Datatypes.atomic_type -> int val base64_of_hex : xs_base64Binary -> xs_hexBinary val hex_of_base64 : xs_hexBinary -> xs_base64Binary
47f39e13cb12a57fa7f78cd36fbd7c5f0f658cb594fe187d03af405774d85a6d
TokTok/hs-toxcore
Stamped.hs
{-# LANGUAGE Safe #-} {-# LANGUAGE StrictData #-} module Network.Tox.DHT.Stamped where import qualified Data.Foldable as F import Data.List ((\\)) import Data.Map (Map) import qualified Data.Map as Map import Network.Tox.Time (Timestamp) {------------------------------------------------------------------------------- - - :: Implementation. - ------------------------------------------------------------------------------} -- | a collection of objects associated with a timestamp. type Stamped a = Map Timestamp [a] empty :: Stamped a empty = Map.empty -- | add a timestamped object. There is no requirement that the stamp be later -- than that of previously added objects. add :: Timestamp -> a -> Stamped a -> Stamped a add time x = Map.insertWith (++) time [x] delete :: Eq a => Timestamp -> a -> Stamped a -> Stamped a delete time x = Map.adjust (\\ [x]) time findStamps :: (a -> Bool) -> Stamped a -> [Timestamp] findStamps p = Map.keys . Map.filter (any p) dropOlder :: Timestamp -> Stamped a -> Stamped a dropOlder time = Map.mapMaybeWithKey $ \t x -> if t < time then Nothing else Just x getList :: Stamped a -> [a] getList = F.concat popFirst :: Stamped a -> (Maybe (Timestamp, a), Stamped a) popFirst stamped = case Map.toAscList stamped of [] -> (Nothing, stamped) assoc:assocs -> case assoc of (_, []) -> popFirst $ Map.fromAscList assocs (stamp, [a]) -> (Just (stamp, a), Map.fromAscList assocs) (stamp, a:as) -> (Just (stamp, a), Map.fromAscList $ (stamp, as):assocs) {------------------------------------------------------------------------------- - - :: Tests. - ------------------------------------------------------------------------------}
null
https://raw.githubusercontent.com/TokTok/hs-toxcore/3ceab5974c36c4c5dbf7518ba733ec2b6084ce5d/src/Network/Tox/DHT/Stamped.hs
haskell
# LANGUAGE Safe # # LANGUAGE StrictData # ------------------------------------------------------------------------------ - - :: Implementation. - ----------------------------------------------------------------------------- | a collection of objects associated with a timestamp. | add a timestamped object. There is no requirement that the stamp be later than that of previously added objects. ------------------------------------------------------------------------------ - - :: Tests. - -----------------------------------------------------------------------------
module Network.Tox.DHT.Stamped where import qualified Data.Foldable as F import Data.List ((\\)) import Data.Map (Map) import qualified Data.Map as Map import Network.Tox.Time (Timestamp) type Stamped a = Map Timestamp [a] empty :: Stamped a empty = Map.empty add :: Timestamp -> a -> Stamped a -> Stamped a add time x = Map.insertWith (++) time [x] delete :: Eq a => Timestamp -> a -> Stamped a -> Stamped a delete time x = Map.adjust (\\ [x]) time findStamps :: (a -> Bool) -> Stamped a -> [Timestamp] findStamps p = Map.keys . Map.filter (any p) dropOlder :: Timestamp -> Stamped a -> Stamped a dropOlder time = Map.mapMaybeWithKey $ \t x -> if t < time then Nothing else Just x getList :: Stamped a -> [a] getList = F.concat popFirst :: Stamped a -> (Maybe (Timestamp, a), Stamped a) popFirst stamped = case Map.toAscList stamped of [] -> (Nothing, stamped) assoc:assocs -> case assoc of (_, []) -> popFirst $ Map.fromAscList assocs (stamp, [a]) -> (Just (stamp, a), Map.fromAscList assocs) (stamp, a:as) -> (Just (stamp, a), Map.fromAscList $ (stamp, as):assocs)
60b6bcbd4e3ed5ba473cdd0c4f4680079a4c841f624865b794ca3ba33e052be0
inconvergent/cl-veq
mat.lisp
(in-package #:veq-tests) (plan 1) (subtest "mat" (veq:fvprogn (is (veq:lst (veq:f3mtv (veq:f_ `(1f0 2f0 4f0 3f0 3f0 5f0 4f0 3f0 3f0)) (veq:f3+ 1f0 2f0 4f0 1f0 2f0 4f0))) '(46f0 40f0 52f0)) (is (veq:lst (veq:f3mv (veq:f_ `(1f0 2f0 4f0 3f0 3f0 5f0 4f0 3f0 3f0)) (veq:f3+ 1f0 2f0 4f0 1f0 2f0 4f0))) '(42f0 58f0 44f0)) (is (veq:lst (veq:f2mv (veq:f_ `(1f0 2f0 3f0 3f0)) (veq:f2- 1f0 2f0 2f0 4f0))) '(-5f0 -9f0)) (is (veq:lst (veq:f4mv (veq:f_ `(1f0 2f0 4f0 6f0 3f0 3f0 5f0 9f0 4f0 3f0 3f0 6f0 -1f0 3f0 -3f0 8f0)) (veq:f4* 1f0 2f0 -4f0 1f0 2f0 4f0 8f0 1f0))) '(-104f0 -121f0 -58f0 126f0)) (is (veq:lst (veq:f4mv (veq:f4meye) (veq:f4* 1f0 2f0 -4f0 1f0 2f0 4f0 8f0 1f0))) '(2f0 8f0 -32f0 1f0)) (is (veq:lst (veq:f4mv (veq:f4meye 3f0) (veq:f4* 1f0 2f0 -4f0 1f0 2f0 4f0 8f0 1f0))) '(6f0 24f0 -96f0 3f0)) (is (veq:f4mt! (veq:f_ `(1f0 2f0 4f0 6f0 3f0 3f0 5f0 9f0 4f0 3f0 3f0 6f0 -1f0 3f0 -3f0 8f0))) #(1f0 3f0 4f0 -1f0 2f0 3f0 3f0 3f0 4f0 5f0 3f0 -3f0 6f0 9f0 6f0 8f0) :test #'equalp) (is (veq:f3mm (veq:f_ `(1f0 2f0 4f0 2f0 2f0 3f0 3f0 3f0 4f0)) (veq:f_ `(3f0 2f0 4f0 3f0 1f0 2f0 3f0 3f0 1f0))) #(21f0 16f0 12f0 21f0 15f0 15f0 30f0 21f0 22f0) :test #'equalp) (is (veq:f3mtm (veq:f_ `(1f0 2f0 4f0 2f0 2f0 3f0 3f0 3f0 4f0)) (veq:f_ `(3f0 2f0 4f0 3f0 1f0 2f0 3f0 3f0 1f0))) #(18f0 13f0 11f0 21f0 15f0 15f0 33f0 23f0 26f0) :test #'equalp) (is (veq:f3mmt (veq:f_ `(1f0 2f0 4f0 2f0 2f0 3f0 3f0 3f0 4f0)) (veq:f_ `(3f0 2f0 4f0 3f0 1f0 2f0 3f0 3f0 1f0))) #(23f0 13f0 13f0 22f0 14f0 15f0 31f0 20f0 22f0) :test #'equalp) (is (veq:f3mtmt (veq:f_ `(1f0 2f0 4f0 2f0 2f0 3f0 3f0 3f0 4f0)) (veq:f_ `(3f0 2f0 4f0 3f0 1f0 2f0 3f0 3f0 1f0))) #(19f0 11f0 12f0 22f0 14f0 15f0 34f0 23f0 25f0) :test #'equalp) (is (veq:f3mrot* 26.0 (veq:f3norm 0.3 0.4 -2.3)) #(0.6526553 0.752802 0.08561626 -0.73750615 0.6571166 -0.15582836 -0.17356777 0.038559683 0.9840667) :test #'equalp) (is (veq:f3mrot 26.0 (veq:f3norm 0.3 0.4 -2.3)) #(0.6526553 0.752802 0.08561626 0.0 -0.73750615 0.6571166 -0.15582836 0.0 -0.17356777 0.038559683 0.9840667 0.0 0.0 0.0 0.0 1.0) :test #'equalp) (is (veq:d2minv (veq:d_ '(1d0 2d0 3d0 31d0))) #(1.24d00 -0.08d0 -0.12d0 0.04d0 ) :test #'equalp) (is (veq:d3minv (veq:d_ '(1d0 2d0 77d0 3d0 3d0 21d0 -1.2d0 7d0 2d0))) #(-0.08339247693399575d0 0.3164182635438846d0 -0.11178140525195175d0 -0.018452803406671398d0 0.05583155902531346d0 0.1242015613910575d0 0.01454932576295245d0 -0.0055594984622663835d0 -0.00177430801987225d0) :test #'equalp) (is (veq:f4minv (veq:f_ '(1f0 2f0 77f0 7f0 3f0 3f0 21f0 -1f0 -1.2 7f0 2f0 3f0 0f0 1f0 -1f0 -10.1f0))) #(-0.08739566 0.32386506 -0.096500464 -0.12130059 -0.017844949 0.05470082 0.121881254 0.018418644 0.014880082 -0.006174776 -0.00303687 0.01002225 -0.0032401022 0.006027287 0.012368131 -0.09817857) :test #'equalp))) (unless (finalize) (error "error mat tests"))
null
https://raw.githubusercontent.com/inconvergent/cl-veq/433cd43ceb086a95cfe010b1f1b4469164e60d07/test/mat.lisp
lisp
(in-package #:veq-tests) (plan 1) (subtest "mat" (veq:fvprogn (is (veq:lst (veq:f3mtv (veq:f_ `(1f0 2f0 4f0 3f0 3f0 5f0 4f0 3f0 3f0)) (veq:f3+ 1f0 2f0 4f0 1f0 2f0 4f0))) '(46f0 40f0 52f0)) (is (veq:lst (veq:f3mv (veq:f_ `(1f0 2f0 4f0 3f0 3f0 5f0 4f0 3f0 3f0)) (veq:f3+ 1f0 2f0 4f0 1f0 2f0 4f0))) '(42f0 58f0 44f0)) (is (veq:lst (veq:f2mv (veq:f_ `(1f0 2f0 3f0 3f0)) (veq:f2- 1f0 2f0 2f0 4f0))) '(-5f0 -9f0)) (is (veq:lst (veq:f4mv (veq:f_ `(1f0 2f0 4f0 6f0 3f0 3f0 5f0 9f0 4f0 3f0 3f0 6f0 -1f0 3f0 -3f0 8f0)) (veq:f4* 1f0 2f0 -4f0 1f0 2f0 4f0 8f0 1f0))) '(-104f0 -121f0 -58f0 126f0)) (is (veq:lst (veq:f4mv (veq:f4meye) (veq:f4* 1f0 2f0 -4f0 1f0 2f0 4f0 8f0 1f0))) '(2f0 8f0 -32f0 1f0)) (is (veq:lst (veq:f4mv (veq:f4meye 3f0) (veq:f4* 1f0 2f0 -4f0 1f0 2f0 4f0 8f0 1f0))) '(6f0 24f0 -96f0 3f0)) (is (veq:f4mt! (veq:f_ `(1f0 2f0 4f0 6f0 3f0 3f0 5f0 9f0 4f0 3f0 3f0 6f0 -1f0 3f0 -3f0 8f0))) #(1f0 3f0 4f0 -1f0 2f0 3f0 3f0 3f0 4f0 5f0 3f0 -3f0 6f0 9f0 6f0 8f0) :test #'equalp) (is (veq:f3mm (veq:f_ `(1f0 2f0 4f0 2f0 2f0 3f0 3f0 3f0 4f0)) (veq:f_ `(3f0 2f0 4f0 3f0 1f0 2f0 3f0 3f0 1f0))) #(21f0 16f0 12f0 21f0 15f0 15f0 30f0 21f0 22f0) :test #'equalp) (is (veq:f3mtm (veq:f_ `(1f0 2f0 4f0 2f0 2f0 3f0 3f0 3f0 4f0)) (veq:f_ `(3f0 2f0 4f0 3f0 1f0 2f0 3f0 3f0 1f0))) #(18f0 13f0 11f0 21f0 15f0 15f0 33f0 23f0 26f0) :test #'equalp) (is (veq:f3mmt (veq:f_ `(1f0 2f0 4f0 2f0 2f0 3f0 3f0 3f0 4f0)) (veq:f_ `(3f0 2f0 4f0 3f0 1f0 2f0 3f0 3f0 1f0))) #(23f0 13f0 13f0 22f0 14f0 15f0 31f0 20f0 22f0) :test #'equalp) (is (veq:f3mtmt (veq:f_ `(1f0 2f0 4f0 2f0 2f0 3f0 3f0 3f0 4f0)) (veq:f_ `(3f0 2f0 4f0 3f0 1f0 2f0 3f0 3f0 1f0))) #(19f0 11f0 12f0 22f0 14f0 15f0 34f0 23f0 25f0) :test #'equalp) (is (veq:f3mrot* 26.0 (veq:f3norm 0.3 0.4 -2.3)) #(0.6526553 0.752802 0.08561626 -0.73750615 0.6571166 -0.15582836 -0.17356777 0.038559683 0.9840667) :test #'equalp) (is (veq:f3mrot 26.0 (veq:f3norm 0.3 0.4 -2.3)) #(0.6526553 0.752802 0.08561626 0.0 -0.73750615 0.6571166 -0.15582836 0.0 -0.17356777 0.038559683 0.9840667 0.0 0.0 0.0 0.0 1.0) :test #'equalp) (is (veq:d2minv (veq:d_ '(1d0 2d0 3d0 31d0))) #(1.24d00 -0.08d0 -0.12d0 0.04d0 ) :test #'equalp) (is (veq:d3minv (veq:d_ '(1d0 2d0 77d0 3d0 3d0 21d0 -1.2d0 7d0 2d0))) #(-0.08339247693399575d0 0.3164182635438846d0 -0.11178140525195175d0 -0.018452803406671398d0 0.05583155902531346d0 0.1242015613910575d0 0.01454932576295245d0 -0.0055594984622663835d0 -0.00177430801987225d0) :test #'equalp) (is (veq:f4minv (veq:f_ '(1f0 2f0 77f0 7f0 3f0 3f0 21f0 -1f0 -1.2 7f0 2f0 3f0 0f0 1f0 -1f0 -10.1f0))) #(-0.08739566 0.32386506 -0.096500464 -0.12130059 -0.017844949 0.05470082 0.121881254 0.018418644 0.014880082 -0.006174776 -0.00303687 0.01002225 -0.0032401022 0.006027287 0.012368131 -0.09817857) :test #'equalp))) (unless (finalize) (error "error mat tests"))
c2fd0507ae2c43c3498c0c0b6be1974ab4db2badef22d2bbf5379ef34a573eb0
andorp/mini-grin
Exercise02.hs
{-# OPTIONS_GHC -Wno-unused-matches #-} # LANGUAGE GeneralizedNewtypeDeriving , LambdaCase , ConstraintKinds # module Tutorial.Chapter01.Exercise02 where import Data.Int import Data.Word import Data.Maybe import Grin.Exp (Exp(..), Program, Alt, BPat(..), CPat(..), programToDefs) import Control.Monad.Fail import Control.Monad.Reader import Control.Monad.State import Control.Monad.Trans.RWS.Strict (RWST(..)) import Grin.Interpreter.Env (Env) import qualified Grin.Interpreter.Env as Env import Grin.Interpreter.Store (Store) import qualified Grin.Interpreter.Store as Store import qualified Grin.Value as Grin import qualified Data.Map.Strict as Map import Lens.Micro.Platform Motivation : To give a language meaning one could write an interpreter . Using the interpreter we can define the operational semantics of a language . The interpreter can also be regarded as a state transition system over a given abstract domain . This approach is called the DEFINITIONAL INTERPRETER . Our domain consist of * an Environment , which associates variables with values , AND -- NOTE : consider renamind Store - > ( Abstract ) Heap [ to avoid confusion about store operation ] * a Store ( Heap ) which represents the memory of the machine . The store associates heap locations ( Addresses ) with values . Exercise : Read the Grin . Interpreter . Env module Exercise : Read the Grin . Interpreter . Store module During the interpretation * The environment associates variables with values which can be of three kinds : * Primitive ( SValue ) * Node * Unit Values of type Unit can be created by an Update operation , or an effectful external operation . * The store can only hold Node values ( similar to C - style structs ) Note : programs are in Static Single Assignment form , which means rebinding a variable is illegal . Exercise : Read the definition of Value , and SValue types below . These types represent values in a running interpreter . Motivation: To give a language meaning one could write an interpreter. Using the interpreter we can define the operational semantics of a language. The interpreter can also be regarded as a state transition system over a given abstract domain. This approach is called the DEFINITIONAL INTERPRETER. Our domain consist of * an Environment, which associates variables with values, AND -- NOTE: consider renamind Store -> (Abstract) Heap [to avoid confusion about store operation] * a Store (Heap) which represents the memory of the machine. The store associates heap locations (Addresses) with values. Exercise: Read the Grin.Interpreter.Env module Exercise: Read the Grin.Interpreter.Store module During the interpretation * The environment associates variables with values which can be of three kinds: * Primitive (SValue) * Node * Unit Values of type Unit can be created by an Update operation, or an effectful external operation. * The store can only hold Node values (similar to C-style structs) Note: GRIN programs are in Static Single Assignment form, which means rebinding a variable is illegal. Exercise: Read the definition of Value, Node and SValue types below. These types represent values in a running interpreter. -} data Value -- A runtime value can be: = Prim SValue -- A primitive value as simple value | Node Node -- A node value which represents a node in the graph The UNIT value , which represents no information at all . Like ( ) in Haskell . deriving (Eq, Show) data Node = N { tag :: Grin.Tag, args :: [SValue] } deriving (Eq, Show) data SValue = SInt64 Int64 | SWord64 Word64 | SFloat Float | SBool Bool | SChar Char | SLoc Address deriving (Eq, Ord, Show) | For simplicity 's sake , we will represent addresses using Ints . type Address = Int The structure of the interpreter can be represented as a Monad Transformer , which operates on a given Monad ' m ' , which can run arbitrary IO computations . The Env represents the frame , which holds values for variables . The MonadReader abstraction fits well with the frame abstraction . The associates Addresses with Node values , during the execution of the program , contents of the heap location associated with the given address may change . * Store : A new address is allocated using the Store operation , which creates a new heap location , saves the value of which was given to the Store operation via a variable those value must be looked up from the Env . The store operation returns the newly created address . * Fetch : The content of a given address can be retrieved using the Fetch operation . The parameter of the operation is a variable which holds an address value . * Update : The content of an address can be overwritten using the Update operation . The structure of the interpreter can be represented as a Monad Transformer, which operates on a given Monad 'm', which can run arbitrary IO computations. The Env represents the frame, which holds values for variables. The MonadReader abstraction fits well with the frame abstraction. The Heap associates Addresses with Node values, during the execution of the program, contents of the heap location associated with the given address may change. * Store: A new address is allocated using the Store operation, which creates a new heap location, saves the value of which was given to the Store operation via a variable those value must be looked up from the Env. The store operation returns the newly created address. * Fetch: The content of a given address can be retrieved using the Fetch operation. The parameter of the operation is a variable which holds an address value. * Update: The content of an address can be overwritten using the Update operation. -} -- | How to interpret External names in the interpreter. type InterpretExternal = Map.Map Grin.Name ([Value] -> IO Value) data Functions = Functions ^ Functions defined within the program ^ Externals used within the program } newtype Definitional m a = Definitional Reader Writer State (Functions, Env Value) -- Reader on the Functions and the variable value mapping () -- Empty writer: No logging happens at all State is the Store which can be change during the interpretation m a ) deriving ( Functor , Applicative , Monad , MonadIO , MonadReader (Functions, Env Value) , MonadState (Store Address Node) , MonadFail ) -- | Collection of the needed constraints. type DC m = (Monad m, MonadIO m, MonadFail m) During the execution of a GRIN program , the interpeter needs a context to interpret function calls . Firstly , it needs to know all the functions defined in the program . Furthermore , it needs to know how to call external functions ( system / OS functions ) . This is accomplished by ` externalCall ` . This function will be used to interpret external function calls ( in SApp ) . Given an external function 's name , and the actual arguments to the call , it calls the corresponding system / OS function . During the execution of a GRIN program, the interpeter needs a context to interpret function calls. Firstly, it needs to know all the functions defined in the GRIN program. Furthermore, it needs to know how to call external functions (system/OS functions). This is accomplished by `externalCall`. This function will be used to interpret external function calls (in SApp). Given an external function's name, and the actual arguments to the call, it calls the corresponding system/OS function. -} -- The interpreter function gets how to interpret the external functions, -- a program to interpret, and returns a computed value. -- -- It collects the function definitions from the program, -- loads the body of the main function and starts to evaluate that expression. interpreter :: InterpretExternal -> Program -> IO Value interpreter iext prog = fst <$> runInterpreter (eval (SApp "main" [])) where runInterpreter :: (Monad m, MonadIO m, MonadFail m) => Definitional m a -> m (a, Store Address Node) runInterpreter (Definitional r) = do let funs = Functions (programToDefs prog) iext (a,store,()) <- runRWST r (funs, Env.empty) Store.empty pure (a,store) -- * Implementation details -- | Turns a Simple Value from a syntax to a simple value of the semantics. simpleValue :: Grin.SimpleValue -> SValue simpleValue = \case Grin.SInt64 s -> SInt64 s Grin.SWord64 s -> SWord64 s Grin.SFloat s -> SFloat s Grin.SBool s -> SBool s Grin.SChar s -> SChar s -- | Looks up a name from the active frame/environment and returns its value. valueOf :: (DC m) => Grin.Name -> Definitional m Value valueOf name = asks ((`Env.lookup` name) . snd) -- | Looks up a name from the active frame/environment and returns its value, expecting a simple value. svalueOf :: (DC m) => Grin.Name -> Definitional m SValue svalueOf name = do (Prim sv) <- valueOf name pure sv | Creates a new location that can be used in the Store operation . -- The size of the underlying Map will be always the last created location +1, -- which serves the purpose of a new address. alloc :: (DC m) => Definitional m Address alloc = gets Store.size The Eval function , that operates on the Expression part of the GRIN AST . eval :: (DC m) => Exp -> Definitional m Value eval = \case -- Evaluates the given value, assigning a semantical value to a syntactical one. SPure (Grin.Val l) -> value l -- Looks up a variable form the active environment SPure (Grin.Var n) -> do p <- askEnv pure $ Env.lookup p n Calls a function , external or defined internal . SApp fn ps -> do p <- askEnv vs <- pure $ map (Env.lookup p) ps ext <- isExternal fn (if ext then external else funCall eval) fn vs -- Fetches a value from the heap. SFetch n -> do p <- askEnv let v = Env.lookup p n fetchStore v -- Updates the given location with the given value. SUpdate nl nn -> do p <- askEnv let vl = Env.lookup p nl let vn = Env.lookup p nn extStore vl vn unit Matches the given value with one of the alternatives . ECase n alts -> do p <- askEnv v <- pure $ Env.lookup p n -- Select the alternative and continue the evaluation evalCase eval v alts -- Handling stores are differen. Create a new location, saves the given node value to the location , and assignes the created location value to the variable in the pattern . EBind (SStore n) (BVar l) rhs -> do p <- askEnv let v = Env.lookup p n a <- allocStore l extStore a v let p' = Env.insert l a p localEnv p' $ eval rhs -- Evaluates the left expression, than binds its return value to the variable -- extending the environment, run the right epxression with the extended -- environemnt and returns its value. EBind lhs (BVar n) rhs -> do v <- eval lhs p <- askEnv let p' = Env.insert n v p localEnv p' (eval rhs) -- Evaluates the left expression, than binds its return value to the variables -- in the bind pattern if the tag of the computed value matches, -- extending the environment, run the right epxression with the extended -- environemnt and returns its value. EBind lhs (BNodePat n t@(Grin.Tag{}) vs) rhs -> do v <- eval lhs p <- askEnv p' <- flip Env.inserts p <$> bindPattern v (t,vs) let p'' = Env.insert n v p' localEnv p'' (eval rhs) -- After the Case selected the Alternative it just needs to evaluate its body. Alt _n _pat body -> do eval body overGenerative -> error $ show overGenerative -- | How to turn a source defined value to a runtime value value :: (DC m) => Grin.Value -> Definitional m Value value = \case Grin.VPrim sval -> pure $ Prim $ simpleValue sval -- Exercise: Node can refer to names, lookup the names from the environment and create a runtime Node value from -- the value that was defined in the source. Grin.VNode vnode -> undefined vnode -- | Convert a runtime value to an address value val2addr :: (DC m) => Value -> Definitional m Address val2addr v = do (Prim (SLoc addr)) <- pure v pure addr -- | Convert an address value to a runtime value. addr2val :: (DC m) => Address -> Definitional m Value addr2val addr = pure (Prim (SLoc addr)) -- | Convert a heap value, which is a node to a runtime value heapVal2val :: (DC m) => Node -> Definitional m Value heapVal2val node = pure (Node node) -- | Convert a runtime value to a Node value val2heapVal :: (DC m) => Value -> Definitional m Node val2heapVal val = do (Node node) <- pure val pure node -- | Creates the Unit value, which is only created when the Update operation runs. unit :: (DC m) => Definitional m Value unit = pure Unit -- | Creates a list of Name and runtime value pairs which extends the environment for the -- right hand side of the bind. See in lazyAdd or in sumSimple bindPattern :: (DC m) => Value -> (Grin.Tag, [Grin.Name]) -> Definitional m [(Grin.Name, Value)] bindPattern val tags = Exercise : The val should be a Node value , if the tag of the node matches , with the given tag , than the args argument from the Node value must be paired with the names in the -- given pattern. -- TODO: Add reference to the examples. undefined -- | Return the environment, which associates names with values askEnv :: (DC m) => Definitional m (Env Value) askEnv = asks snd -- | Sets the environment to the given one, this is for binds, function calls, -- and alternatives. localEnv :: (DC m) => Env (Value) -> Definitional m Value -> Definitional m Value localEnv env = local (set _2 env) -- | Lookup a function by its name. It should return the Def constructor which contains -- the parameters and the body of the function. lookupFun :: (DC m) => Grin.Name -> Definitional m Exp lookupFun funName = fromJust <$> view (_1 . to functions . at funName) -- | Checks if the given name refers to an external function. isExternal :: (DC m) => Grin.Name -> Definitional m Bool isExternal extName = -- Exercise: Use MonadReader to retrieve the Context and lookup the -- the extName in the context undefined -- | Run the given external with the parameters external :: (DC m) => Grin.Name -> [Value] -> Definitional m Value external = -- Exercise: Use the MonadReader to retrieve the Context and lookup -- the function and apply the parameters to it undefined funCall :: (DC m) => (Exp -> Definitional m Value) -> Grin.Name -> [Value] -> Definitional m Value funCall ev funName values = -- Exercise: -- Lookup the function by the given name -- Retrieve its (Def params body) -- Create an empty env and bind the function parameters to the given values -- Run the eval function on the created new local env and body undefined evalCase :: (DC m) => (Exp -> Definitional m Value) -> Value -> [Alt] -> Definitional m Value evalCase ev = -- Exercise: Find the first Alt that matches the given value . If the Alt has a Node pattern , the must be a Node In that case bind the values to the names defined in the pattern -- create a new local environment and evaluate the body of the alt in it. -- Note that the name in the Alt must bind the value in the environment. undefined | Creates a location for a given name . This is particular for the store structure , where the Store operation must be part of a Bind , thus there will be always a name to -- bind to, which should hold the address of the created location. -- In this Definitional interpreter for every Store operation that the interpreter evaluates -- it must creates a new location. allocStore :: (DC m) => Grin.Name -> Definitional m Value allocStore _name = do addr <- alloc pure $ Prim $ SLoc addr -- | Loads the content from the store addressed by the given value fetchStore :: (DC m) => Value -> Definitional m Value fetchStore addr = do s <- get a <- undefined addr heapVal2val $ Store.lookup a s -- | Extends the store with the given value. extStore :: (DC m) => Value -> Value -> Definitional m () extStore addr val = do a <- undefined addr n <- val2heapVal val modify (Store.insert a n) -- * The externals that the interpreter can understand knownExternals :: Map.Map Grin.Name ([Value] -> IO Value) knownExternals = Map.fromList [ ("prim_int_eq", \[Prim (SInt64 a), Prim (SInt64 b)] -> pure $ Prim (SBool (a == b))) , ("prim_int_gt", \[Prim (SInt64 a), Prim (SInt64 b)] -> pure $ Prim (SBool (a > b))) , ("prim_int_add", \[Prim (SInt64 a), Prim (SInt64 b)] -> pure $ Prim (SInt64 (a + b))) , ("prim_int_sub", \[Prim (SInt64 a), Prim (SInt64 b)] -> pure $ Prim (SInt64 (a - b))) , ("prim_int_mul", \[Prim (SInt64 a), Prim (SInt64 b)] -> pure $ Prim (SInt64 (a * b))) , ("prim_int_print", \[(Prim (SInt64 a))] -> Unit <$ print a) ]
null
https://raw.githubusercontent.com/andorp/mini-grin/99913efa0f81cb2a76893d3e48c6d025df9c40c9/grin/src/Tutorial/Chapter01/Exercise02.hs
haskell
# OPTIONS_GHC -Wno-unused-matches # NOTE : consider renamind Store - > ( Abstract ) Heap [ to avoid confusion about store operation ] NOTE: consider renamind Store -> (Abstract) Heap [to avoid confusion about store operation] A runtime value can be: A primitive value as simple value A node value which represents a node in the graph | How to interpret External names in the interpreter. Reader on the Functions and the variable value mapping Empty writer: No logging happens at all | Collection of the needed constraints. The interpreter function gets how to interpret the external functions, a program to interpret, and returns a computed value. It collects the function definitions from the program, loads the body of the main function and starts to evaluate that expression. * Implementation details | Turns a Simple Value from a syntax to a simple value of the semantics. | Looks up a name from the active frame/environment and returns its value. | Looks up a name from the active frame/environment and returns its value, expecting a simple value. The size of the underlying Map will be always the last created location +1, which serves the purpose of a new address. Evaluates the given value, assigning a semantical value to a syntactical one. Looks up a variable form the active environment Fetches a value from the heap. Updates the given location with the given value. Select the alternative and continue the evaluation Handling stores are differen. Create a new location, saves the given node value Evaluates the left expression, than binds its return value to the variable extending the environment, run the right epxression with the extended environemnt and returns its value. Evaluates the left expression, than binds its return value to the variables in the bind pattern if the tag of the computed value matches, extending the environment, run the right epxression with the extended environemnt and returns its value. After the Case selected the Alternative it just needs to evaluate its body. | How to turn a source defined value to a runtime value Exercise: Node can refer to names, lookup the names from the value that was defined in the source. | Convert a runtime value to an address value | Convert an address value to a runtime value. | Convert a heap value, which is a node to a runtime value | Convert a runtime value to a Node value | Creates the Unit value, which is only created when the Update operation runs. | Creates a list of Name and runtime value pairs which extends the environment for the right hand side of the bind. given pattern. TODO: Add reference to the examples. | Return the environment, which associates names with values | Sets the environment to the given one, this is for binds, function calls, and alternatives. | Lookup a function by its name. It should return the Def constructor which contains the parameters and the body of the function. | Checks if the given name refers to an external function. Exercise: Use MonadReader to retrieve the Context and lookup the the extName in the context | Run the given external with the parameters Exercise: Use the MonadReader to retrieve the Context and lookup the function and apply the parameters to it Exercise: Lookup the function by the given name Retrieve its (Def params body) Create an empty env and bind the function parameters to the given values Run the eval function on the created new local env and body Exercise: create a new local environment and evaluate the body of the alt in it. Note that the name in the Alt must bind the value in the environment. bind to, which should hold the address of the created location. it must creates a new location. | Loads the content from the store addressed by the given value | Extends the store with the given value. * The externals that the interpreter can understand
# LANGUAGE GeneralizedNewtypeDeriving , LambdaCase , ConstraintKinds # module Tutorial.Chapter01.Exercise02 where import Data.Int import Data.Word import Data.Maybe import Grin.Exp (Exp(..), Program, Alt, BPat(..), CPat(..), programToDefs) import Control.Monad.Fail import Control.Monad.Reader import Control.Monad.State import Control.Monad.Trans.RWS.Strict (RWST(..)) import Grin.Interpreter.Env (Env) import qualified Grin.Interpreter.Env as Env import Grin.Interpreter.Store (Store) import qualified Grin.Interpreter.Store as Store import qualified Grin.Value as Grin import qualified Data.Map.Strict as Map import Lens.Micro.Platform Motivation : To give a language meaning one could write an interpreter . Using the interpreter we can define the operational semantics of a language . The interpreter can also be regarded as a state transition system over a given abstract domain . This approach is called the DEFINITIONAL INTERPRETER . Our domain consist of * an Environment , which associates variables with values , AND * a Store ( Heap ) which represents the memory of the machine . The store associates heap locations ( Addresses ) with values . Exercise : Read the Grin . Interpreter . Env module Exercise : Read the Grin . Interpreter . Store module During the interpretation * The environment associates variables with values which can be of three kinds : * Primitive ( SValue ) * Node * Unit Values of type Unit can be created by an Update operation , or an effectful external operation . * The store can only hold Node values ( similar to C - style structs ) Note : programs are in Static Single Assignment form , which means rebinding a variable is illegal . Exercise : Read the definition of Value , and SValue types below . These types represent values in a running interpreter . Motivation: To give a language meaning one could write an interpreter. Using the interpreter we can define the operational semantics of a language. The interpreter can also be regarded as a state transition system over a given abstract domain. This approach is called the DEFINITIONAL INTERPRETER. Our domain consist of * an Environment, which associates variables with values, AND * a Store (Heap) which represents the memory of the machine. The store associates heap locations (Addresses) with values. Exercise: Read the Grin.Interpreter.Env module Exercise: Read the Grin.Interpreter.Store module During the interpretation * The environment associates variables with values which can be of three kinds: * Primitive (SValue) * Node * Unit Values of type Unit can be created by an Update operation, or an effectful external operation. * The store can only hold Node values (similar to C-style structs) Note: GRIN programs are in Static Single Assignment form, which means rebinding a variable is illegal. Exercise: Read the definition of Value, Node and SValue types below. These types represent values in a running interpreter. -} The UNIT value , which represents no information at all . Like ( ) in Haskell . deriving (Eq, Show) data Node = N { tag :: Grin.Tag, args :: [SValue] } deriving (Eq, Show) data SValue = SInt64 Int64 | SWord64 Word64 | SFloat Float | SBool Bool | SChar Char | SLoc Address deriving (Eq, Ord, Show) | For simplicity 's sake , we will represent addresses using Ints . type Address = Int The structure of the interpreter can be represented as a Monad Transformer , which operates on a given Monad ' m ' , which can run arbitrary IO computations . The Env represents the frame , which holds values for variables . The MonadReader abstraction fits well with the frame abstraction . The associates Addresses with Node values , during the execution of the program , contents of the heap location associated with the given address may change . * Store : A new address is allocated using the Store operation , which creates a new heap location , saves the value of which was given to the Store operation via a variable those value must be looked up from the Env . The store operation returns the newly created address . * Fetch : The content of a given address can be retrieved using the Fetch operation . The parameter of the operation is a variable which holds an address value . * Update : The content of an address can be overwritten using the Update operation . The structure of the interpreter can be represented as a Monad Transformer, which operates on a given Monad 'm', which can run arbitrary IO computations. The Env represents the frame, which holds values for variables. The MonadReader abstraction fits well with the frame abstraction. The Heap associates Addresses with Node values, during the execution of the program, contents of the heap location associated with the given address may change. * Store: A new address is allocated using the Store operation, which creates a new heap location, saves the value of which was given to the Store operation via a variable those value must be looked up from the Env. The store operation returns the newly created address. * Fetch: The content of a given address can be retrieved using the Fetch operation. The parameter of the operation is a variable which holds an address value. * Update: The content of an address can be overwritten using the Update operation. -} type InterpretExternal = Map.Map Grin.Name ([Value] -> IO Value) data Functions = Functions ^ Functions defined within the program ^ Externals used within the program } newtype Definitional m a = Definitional Reader Writer State State is the Store which can be change during the interpretation m a ) deriving ( Functor , Applicative , Monad , MonadIO , MonadReader (Functions, Env Value) , MonadState (Store Address Node) , MonadFail ) type DC m = (Monad m, MonadIO m, MonadFail m) During the execution of a GRIN program , the interpeter needs a context to interpret function calls . Firstly , it needs to know all the functions defined in the program . Furthermore , it needs to know how to call external functions ( system / OS functions ) . This is accomplished by ` externalCall ` . This function will be used to interpret external function calls ( in SApp ) . Given an external function 's name , and the actual arguments to the call , it calls the corresponding system / OS function . During the execution of a GRIN program, the interpeter needs a context to interpret function calls. Firstly, it needs to know all the functions defined in the GRIN program. Furthermore, it needs to know how to call external functions (system/OS functions). This is accomplished by `externalCall`. This function will be used to interpret external function calls (in SApp). Given an external function's name, and the actual arguments to the call, it calls the corresponding system/OS function. -} interpreter :: InterpretExternal -> Program -> IO Value interpreter iext prog = fst <$> runInterpreter (eval (SApp "main" [])) where runInterpreter :: (Monad m, MonadIO m, MonadFail m) => Definitional m a -> m (a, Store Address Node) runInterpreter (Definitional r) = do let funs = Functions (programToDefs prog) iext (a,store,()) <- runRWST r (funs, Env.empty) Store.empty pure (a,store) simpleValue :: Grin.SimpleValue -> SValue simpleValue = \case Grin.SInt64 s -> SInt64 s Grin.SWord64 s -> SWord64 s Grin.SFloat s -> SFloat s Grin.SBool s -> SBool s Grin.SChar s -> SChar s valueOf :: (DC m) => Grin.Name -> Definitional m Value valueOf name = asks ((`Env.lookup` name) . snd) svalueOf :: (DC m) => Grin.Name -> Definitional m SValue svalueOf name = do (Prim sv) <- valueOf name pure sv | Creates a new location that can be used in the Store operation . alloc :: (DC m) => Definitional m Address alloc = gets Store.size The Eval function , that operates on the Expression part of the GRIN AST . eval :: (DC m) => Exp -> Definitional m Value eval = \case SPure (Grin.Val l) -> value l SPure (Grin.Var n) -> do p <- askEnv pure $ Env.lookup p n Calls a function , external or defined internal . SApp fn ps -> do p <- askEnv vs <- pure $ map (Env.lookup p) ps ext <- isExternal fn (if ext then external else funCall eval) fn vs SFetch n -> do p <- askEnv let v = Env.lookup p n fetchStore v SUpdate nl nn -> do p <- askEnv let vl = Env.lookup p nl let vn = Env.lookup p nn extStore vl vn unit Matches the given value with one of the alternatives . ECase n alts -> do p <- askEnv v <- pure $ Env.lookup p n evalCase eval v alts to the location , and assignes the created location value to the variable in the pattern . EBind (SStore n) (BVar l) rhs -> do p <- askEnv let v = Env.lookup p n a <- allocStore l extStore a v let p' = Env.insert l a p localEnv p' $ eval rhs EBind lhs (BVar n) rhs -> do v <- eval lhs p <- askEnv let p' = Env.insert n v p localEnv p' (eval rhs) EBind lhs (BNodePat n t@(Grin.Tag{}) vs) rhs -> do v <- eval lhs p <- askEnv p' <- flip Env.inserts p <$> bindPattern v (t,vs) let p'' = Env.insert n v p' localEnv p'' (eval rhs) Alt _n _pat body -> do eval body overGenerative -> error $ show overGenerative value :: (DC m) => Grin.Value -> Definitional m Value value = \case Grin.VPrim sval -> pure $ Prim $ simpleValue sval the environment and create a runtime Node value from Grin.VNode vnode -> undefined vnode val2addr :: (DC m) => Value -> Definitional m Address val2addr v = do (Prim (SLoc addr)) <- pure v pure addr addr2val :: (DC m) => Address -> Definitional m Value addr2val addr = pure (Prim (SLoc addr)) heapVal2val :: (DC m) => Node -> Definitional m Value heapVal2val node = pure (Node node) val2heapVal :: (DC m) => Value -> Definitional m Node val2heapVal val = do (Node node) <- pure val pure node unit :: (DC m) => Definitional m Value unit = pure Unit See in lazyAdd or in sumSimple bindPattern :: (DC m) => Value -> (Grin.Tag, [Grin.Name]) -> Definitional m [(Grin.Name, Value)] bindPattern val tags = Exercise : The val should be a Node value , if the tag of the node matches , with the given tag , than the args argument from the Node value must be paired with the names in the undefined askEnv :: (DC m) => Definitional m (Env Value) askEnv = asks snd localEnv :: (DC m) => Env (Value) -> Definitional m Value -> Definitional m Value localEnv env = local (set _2 env) lookupFun :: (DC m) => Grin.Name -> Definitional m Exp lookupFun funName = fromJust <$> view (_1 . to functions . at funName) isExternal :: (DC m) => Grin.Name -> Definitional m Bool isExternal extName = undefined external :: (DC m) => Grin.Name -> [Value] -> Definitional m Value external = undefined funCall :: (DC m) => (Exp -> Definitional m Value) -> Grin.Name -> [Value] -> Definitional m Value funCall ev funName values = undefined evalCase :: (DC m) => (Exp -> Definitional m Value) -> Value -> [Alt] -> Definitional m Value evalCase ev = Find the first Alt that matches the given value . If the Alt has a Node pattern , the must be a Node In that case bind the values to the names defined in the pattern undefined | Creates a location for a given name . This is particular for the store structure , where the Store operation must be part of a Bind , thus there will be always a name to In this Definitional interpreter for every Store operation that the interpreter evaluates allocStore :: (DC m) => Grin.Name -> Definitional m Value allocStore _name = do addr <- alloc pure $ Prim $ SLoc addr fetchStore :: (DC m) => Value -> Definitional m Value fetchStore addr = do s <- get a <- undefined addr heapVal2val $ Store.lookup a s extStore :: (DC m) => Value -> Value -> Definitional m () extStore addr val = do a <- undefined addr n <- val2heapVal val modify (Store.insert a n) knownExternals :: Map.Map Grin.Name ([Value] -> IO Value) knownExternals = Map.fromList [ ("prim_int_eq", \[Prim (SInt64 a), Prim (SInt64 b)] -> pure $ Prim (SBool (a == b))) , ("prim_int_gt", \[Prim (SInt64 a), Prim (SInt64 b)] -> pure $ Prim (SBool (a > b))) , ("prim_int_add", \[Prim (SInt64 a), Prim (SInt64 b)] -> pure $ Prim (SInt64 (a + b))) , ("prim_int_sub", \[Prim (SInt64 a), Prim (SInt64 b)] -> pure $ Prim (SInt64 (a - b))) , ("prim_int_mul", \[Prim (SInt64 a), Prim (SInt64 b)] -> pure $ Prim (SInt64 (a * b))) , ("prim_int_print", \[(Prim (SInt64 a))] -> Unit <$ print a) ]
0e302f540a5cd73ddc37c4cd91357fe5e63884562082afa40c56532866a5484a
PLSysSec/FaCT
pos.ml
open Lexing type pos = { file:string; line:int; lpos:int; rpos:int } [@@deriving show] let fake_pos = { file=""; line=0; lpos=0; rpos=0 } type 'a pos_ast = { pos:pos; data:'a } [@@deriving show] let pp_pos_ast pp_data fmt { data } = pp_data fmt data let to_pos ?buf:(b=None) { pos_fname=f; pos_lnum=l; pos_bol=lbl; pos_cnum=lc } { pos_cnum=rc } = match b with | None -> { file=f; line=l; lpos=lc-lbl+1; rpos=rc-lbl } | Some lb -> let start = (lexeme_start lb) - lb.lex_curr_p.pos_bol in let ends = (lexeme_end lb) - lb.lex_curr_p.pos_bol in { file=f; line=l; lpos=start+1; rpos=ends+1 } let make_pos startpos endpos data = { pos=(to_pos startpos endpos); data=data } let make_ast pos data = { pos=pos; data=data } let pos_string { file=f; line=l; lpos=lp; rpos=rp } = f ^ ":" ^ string_of_int(l) ^ ":" ^ string_of_int(lp) ^ "-" ^ string_of_int(rp) let unpack fn {data} = fn data let posmap fn = fun pa -> { pa with data=(fn pa.data) } let wrap f pa = { pa with data=f pa.pos pa.data } let xwrap f pa = f pa.pos pa.data let rebind f pa = { pa with data=f pa } let ( @> ) p ast = make_ast p ast let ( << ) s p = pos_string p ^ ": " ^ s
null
https://raw.githubusercontent.com/PLSysSec/FaCT/c08b2e00751b28e1f25d031c3afafc544acfb892/src/pos.ml
ocaml
open Lexing type pos = { file:string; line:int; lpos:int; rpos:int } [@@deriving show] let fake_pos = { file=""; line=0; lpos=0; rpos=0 } type 'a pos_ast = { pos:pos; data:'a } [@@deriving show] let pp_pos_ast pp_data fmt { data } = pp_data fmt data let to_pos ?buf:(b=None) { pos_fname=f; pos_lnum=l; pos_bol=lbl; pos_cnum=lc } { pos_cnum=rc } = match b with | None -> { file=f; line=l; lpos=lc-lbl+1; rpos=rc-lbl } | Some lb -> let start = (lexeme_start lb) - lb.lex_curr_p.pos_bol in let ends = (lexeme_end lb) - lb.lex_curr_p.pos_bol in { file=f; line=l; lpos=start+1; rpos=ends+1 } let make_pos startpos endpos data = { pos=(to_pos startpos endpos); data=data } let make_ast pos data = { pos=pos; data=data } let pos_string { file=f; line=l; lpos=lp; rpos=rp } = f ^ ":" ^ string_of_int(l) ^ ":" ^ string_of_int(lp) ^ "-" ^ string_of_int(rp) let unpack fn {data} = fn data let posmap fn = fun pa -> { pa with data=(fn pa.data) } let wrap f pa = { pa with data=f pa.pos pa.data } let xwrap f pa = f pa.pos pa.data let rebind f pa = { pa with data=f pa } let ( @> ) p ast = make_ast p ast let ( << ) s p = pos_string p ^ ": " ^ s
eb5fe07d99886d638ce6ed4fd5b616493985034cc1f0a6ead6c34c1f9c4f46f2
hasktorch/hasktorch
Dimname.hs
# LANGUAGE DataKinds # # LANGUAGE PolyKinds # # LANGUAGE TemplateHaskell # # LANGUAGE QuasiQuotes # # LANGUAGE ScopedTypeVariables # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TypeFamilies # # LANGUAGE FlexibleInstances # module Torch.Internal.Unmanaged.Type.Dimname where import qualified Language.C.Inline.Cpp as C import qualified Language.C.Inline.Cpp.Unsafe as C import qualified Language.C.Inline.Context as C import qualified Language.C.Types as C import qualified Data.Map as Map import Foreign.C.String import Foreign.C.Types import Foreign import Torch.Internal.Type C.context $ C.cppCtx <> mempty { C.ctxTypesTable = typeTable } C.include "<ATen/core/Dimname.h>" C.include "<vector>" newDimname_n :: Ptr Dimname -> IO (Ptr Dimname) newDimname_n _x = [C.throwBlock| at::Dimname* { return new at::Dimname( *$(at::Dimname* _x)); }|] dimname_symbol :: Ptr Dimname -> IO (Ptr Symbol) dimname_symbol _obj = [C.throwBlock| at::Symbol* { return new at::Symbol((*$(at::Dimname* _obj)).symbol( )); }|] dimname_isBasic :: Ptr Dimname -> IO (CBool) dimname_isBasic _obj = [C.throwBlock| bool { return (*$(at::Dimname* _obj)).isBasic( ); }|] dimname_isWildcard :: Ptr Dimname -> IO (CBool) dimname_isWildcard _obj = [C.throwBlock| bool { return (*$(at::Dimname* _obj)).isWildcard( ); }|] dimname_matches_n :: Ptr Dimname -> Ptr Dimname -> IO (CBool) dimname_matches_n _obj _other = [C.throwBlock| bool { return (*$(at::Dimname* _obj)).matches( *$(at::Dimname* _other)); }|] fromSymbol_s :: Ptr Symbol -> IO (Ptr Dimname) fromSymbol_s _name = [C.throwBlock| at::Dimname* { return new at::Dimname(at::Dimname::fromSymbol( *$(at::Symbol* _name))); }|] wildcard :: IO (Ptr Dimname) wildcard = [C.throwBlock| at::Dimname* { return new at::Dimname(at::Dimname::wildcard( )); }|] isValidName_s :: Ptr StdString -> IO (CBool) isValidName_s _name = [C.throwBlock| bool { return (at::Dimname::isValidName( *$(std::string* _name))); }|]
null
https://raw.githubusercontent.com/hasktorch/hasktorch/6233c173e1dd9fd7218fd13b104da15fc457f67e/libtorch-ffi/src/Torch/Internal/Unmanaged/Type/Dimname.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE DataKinds # # LANGUAGE PolyKinds # # LANGUAGE TemplateHaskell # # LANGUAGE QuasiQuotes # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE FlexibleInstances # module Torch.Internal.Unmanaged.Type.Dimname where import qualified Language.C.Inline.Cpp as C import qualified Language.C.Inline.Cpp.Unsafe as C import qualified Language.C.Inline.Context as C import qualified Language.C.Types as C import qualified Data.Map as Map import Foreign.C.String import Foreign.C.Types import Foreign import Torch.Internal.Type C.context $ C.cppCtx <> mempty { C.ctxTypesTable = typeTable } C.include "<ATen/core/Dimname.h>" C.include "<vector>" newDimname_n :: Ptr Dimname -> IO (Ptr Dimname) newDimname_n _x = [C.throwBlock| at::Dimname* { return new at::Dimname( *$(at::Dimname* _x)); }|] dimname_symbol :: Ptr Dimname -> IO (Ptr Symbol) dimname_symbol _obj = [C.throwBlock| at::Symbol* { return new at::Symbol((*$(at::Dimname* _obj)).symbol( )); }|] dimname_isBasic :: Ptr Dimname -> IO (CBool) dimname_isBasic _obj = [C.throwBlock| bool { return (*$(at::Dimname* _obj)).isBasic( ); }|] dimname_isWildcard :: Ptr Dimname -> IO (CBool) dimname_isWildcard _obj = [C.throwBlock| bool { return (*$(at::Dimname* _obj)).isWildcard( ); }|] dimname_matches_n :: Ptr Dimname -> Ptr Dimname -> IO (CBool) dimname_matches_n _obj _other = [C.throwBlock| bool { return (*$(at::Dimname* _obj)).matches( *$(at::Dimname* _other)); }|] fromSymbol_s :: Ptr Symbol -> IO (Ptr Dimname) fromSymbol_s _name = [C.throwBlock| at::Dimname* { return new at::Dimname(at::Dimname::fromSymbol( *$(at::Symbol* _name))); }|] wildcard :: IO (Ptr Dimname) wildcard = [C.throwBlock| at::Dimname* { return new at::Dimname(at::Dimname::wildcard( )); }|] isValidName_s :: Ptr StdString -> IO (CBool) isValidName_s _name = [C.throwBlock| bool { return (at::Dimname::isValidName( *$(std::string* _name))); }|]
19356ad54d1e69653fc26e859be80a36cb572f8b315214c4f3f7fcc0ef3a018b
gethop-dev/object-storage.s3
project.clj
(defproject dev.gethop/object-storage.s3 "0.6.11-SNAPSHOT" :description "A Duct library for managing AWS S3 objects" :url "-dev/object-storage.s3" :license {:name "Mozilla Public Licence 2.0" :url "-US/MPL/2.0/"} :min-lein-version "2.9.8" :dependencies [[org.clojure/clojure "1.10.0"] [amazonica "0.3.143" :exclusions [com.amazonaws/aws-java-sdk com.amazonaws/amazon-kinesis-client com.amazonaws/dynamodb-streams-kinesis-adapter]] [com.amazonaws/aws-java-sdk-core "1.11.586"] [com.amazonaws/aws-java-sdk-s3 "1.11.586"] [integrant "0.7.0"] [dev.gethop/object-storage.core "0.1.4"]] :deploy-repositories [["snapshots" {:url "" :username :env/CLOJARS_USERNAME :password :env/CLOJARS_PASSWORD :sign-releases false}] ["releases" {:url "" :username :env/CLOJARS_USERNAME :password :env/CLOJARS_PASSWORD :sign-releases false}]] :profiles {:dev [:project/dev :profiles/dev] :repl {:repl-options {:host "0.0.0.0" :port 4001}} :profiles/dev {} :project/dev {:dependencies [[digest "1.4.8"] [http-kit "2.5.3"]] :plugins [[jonase/eastwood "1.2.3"] [lein-cljfmt "0.8.0"]] :eastwood {:linters [:all] :ignored-faults {:unused-namespaces {dev.gethop.object-storage.s3-test true} :keyword-typos {dev.gethop.object-storage.s3 true}} :debug [:progress :time]}}})
null
https://raw.githubusercontent.com/gethop-dev/object-storage.s3/9576a790291f94a699bfc2f5b02edb619b45520e/project.clj
clojure
(defproject dev.gethop/object-storage.s3 "0.6.11-SNAPSHOT" :description "A Duct library for managing AWS S3 objects" :url "-dev/object-storage.s3" :license {:name "Mozilla Public Licence 2.0" :url "-US/MPL/2.0/"} :min-lein-version "2.9.8" :dependencies [[org.clojure/clojure "1.10.0"] [amazonica "0.3.143" :exclusions [com.amazonaws/aws-java-sdk com.amazonaws/amazon-kinesis-client com.amazonaws/dynamodb-streams-kinesis-adapter]] [com.amazonaws/aws-java-sdk-core "1.11.586"] [com.amazonaws/aws-java-sdk-s3 "1.11.586"] [integrant "0.7.0"] [dev.gethop/object-storage.core "0.1.4"]] :deploy-repositories [["snapshots" {:url "" :username :env/CLOJARS_USERNAME :password :env/CLOJARS_PASSWORD :sign-releases false}] ["releases" {:url "" :username :env/CLOJARS_USERNAME :password :env/CLOJARS_PASSWORD :sign-releases false}]] :profiles {:dev [:project/dev :profiles/dev] :repl {:repl-options {:host "0.0.0.0" :port 4001}} :profiles/dev {} :project/dev {:dependencies [[digest "1.4.8"] [http-kit "2.5.3"]] :plugins [[jonase/eastwood "1.2.3"] [lein-cljfmt "0.8.0"]] :eastwood {:linters [:all] :ignored-faults {:unused-namespaces {dev.gethop.object-storage.s3-test true} :keyword-typos {dev.gethop.object-storage.s3 true}} :debug [:progress :time]}}})
38b37b636c1559851df7d788283b04794465c3713525916581d01aead39be0e4
spurious/sagittarius-scheme-mirror
base.sps
#!r6rs (import (tests r6rs base) (tests r6rs test) (rnrs io simple)) (display "Running tests for (rnrs base)\n") (run-base-tests) (report-test-results)
null
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/test/r6rs-test-suite/tests/r6rs/run/base.sps
scheme
#!r6rs (import (tests r6rs base) (tests r6rs test) (rnrs io simple)) (display "Running tests for (rnrs base)\n") (run-base-tests) (report-test-results)
7046d40ceb69fa9cba06d2819738b968cdeaee7cda07c6737022a68922ee2d3d
manuel-serrano/bigloo
prof_emit.scm
;*=====================================================================*/ * serrano / prgm / project / bigloo / comptime / Prof / prof_emit.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : We d Apr 8 17:32:59 1998 * / * Last change : Thu Nov 3 14:28:38 2011 ( serrano ) * / * Copyright : 1998 - 2011 , see LICENSE file * / ;* ------------------------------------------------------------- */ ;* The emission of the Bdb identifier translation table. */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module prof_emit (include "Ast/node.sch" "Ast/unit.sch" "Tools/location.sch") (import tools_shape tools_error tools_misc type_env type_cache object_class object_slots ast_sexp ast_env ast_ident ast_unit module_module module_include engine_param backend_c_prototype backend_cplib) (export (emit-prof-info globals ::output-port))) ;*---------------------------------------------------------------------*/ ;* emit-prof-info ... */ ;*---------------------------------------------------------------------*/ (define (emit-prof-info globals port) (define (emit-global! global) (let ((sfun (global-value global))) (set-variable-name! global) (let ((id (global-id global)) (c-name (global-name global)) (is-alloc (and (sfun? sfun) (memq 'allocator (sfun-property sfun)))) (loc (and (sfun? sfun) (sfun-loc sfun)))) (if (location? loc) (fprint port " fputs( \"((\\\"" id "\\\" " "\\\"" (location-fname loc) "\\\" " (location-pos loc) ") \\\"" c-name "\\\"" (if is-alloc " allocator" "") ")\\n\", (FILE *)bprof_port );") (fprint port " fputs( \"(\\\"" id "\\\" \\\"" c-name "\\\"" (if is-alloc " allocator" "") ")\\n\", (FILE *)bprof_port );"))))) ;; the declaration of the association table (newline port) (newline port) ;; prof demangling table (fprint port "/* prof association table */") (fprint port "static obj_t write_bprof_table() {") (fprint port " extern obj_t bprof_port;") (fprint port " if( bprof_port == BUNSPEC ) bprof_port = (obj_t)fopen( \"" *prof-table-name* "\", \"w\" );") (fprint port " if( bprof_port ) {") ;; the library functions dump (for-each-global! (lambda (g) (when (and (or (>fx (global-occurrence g) 0) (eq? (global-module g) 'foreign)) (global-library g) (global-user? g)) (emit-global! g)))) ;; and then the non function global variables. (for-each (lambda (global) (when (global-user? global) (emit-global! global))) globals) in addition we write that is CONS and some ;; other builtins (for-each (lambda (scm-c) (let ((scm (car scm-c)) (c (cdr scm-c))) (fprint port " fputs( \"(\\\"" scm "\\\" \\\"" c "\\\"" ")\\n\", (FILE *)bprof_port );"))) *builtin-allocators*) (fprint port " }") (fprint port " return BUNSPEC;") (fprint port #"}\n"))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/comptime/Prof/prof_emit.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * The emission of the Bdb identifier translation table. */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * emit-prof-info ... */ *---------------------------------------------------------------------*/ ") "))))) the declaration of the association table prof demangling table ") the library functions dump and then the non function global variables. other builtins ")))
* serrano / prgm / project / bigloo / comptime / Prof / prof_emit.scm * / * Author : * / * Creation : We d Apr 8 17:32:59 1998 * / * Last change : Thu Nov 3 14:28:38 2011 ( serrano ) * / * Copyright : 1998 - 2011 , see LICENSE file * / (module prof_emit (include "Ast/node.sch" "Ast/unit.sch" "Tools/location.sch") (import tools_shape tools_error tools_misc type_env type_cache object_class object_slots ast_sexp ast_env ast_ident ast_unit module_module module_include engine_param backend_c_prototype backend_cplib) (export (emit-prof-info globals ::output-port))) (define (emit-prof-info globals port) (define (emit-global! global) (let ((sfun (global-value global))) (set-variable-name! global) (let ((id (global-id global)) (c-name (global-name global)) (is-alloc (and (sfun? sfun) (memq 'allocator (sfun-property sfun)))) (loc (and (sfun? sfun) (sfun-loc sfun)))) (if (location? loc) (fprint port " fputs( \"((\\\"" id "\\\" " "\\\"" (location-fname loc) "\\\" " (location-pos loc) ") \\\"" c-name "\\\"" (if is-alloc " allocator" "") (fprint port " fputs( \"(\\\"" id "\\\" \\\"" c-name "\\\"" (if is-alloc " allocator" "") (newline port) (newline port) (fprint port "/* prof association table */") (fprint port "static obj_t write_bprof_table() {") (fprint port " extern obj_t bprof_port;") (fprint port " if( bprof_port == BUNSPEC ) bprof_port = (obj_t)fopen( \"" (fprint port " if( bprof_port ) {") (for-each-global! (lambda (g) (when (and (or (>fx (global-occurrence g) 0) (eq? (global-module g) 'foreign)) (global-library g) (global-user? g)) (emit-global! g)))) (for-each (lambda (global) (when (global-user? global) (emit-global! global))) globals) in addition we write that is CONS and some (for-each (lambda (scm-c) (let ((scm (car scm-c)) (c (cdr scm-c))) (fprint port " fputs( \"(\\\"" scm "\\\" \\\"" c "\\\"" *builtin-allocators*) (fprint port " }") (fprint port " return BUNSPEC;") (fprint port #"}\n"))
a0693dffcbe66f3f3e8bb569007621c0111cfbeaba88ea3e3c02b8317617b62d
ogri-la/strongbox-comrades
main.cljs
(ns strongbox-comrades.main (:require [strongbox-comrades.core :as core] [strongbox-comrades.utils :as utils] [strongbox-comrades.ui :as ui])) (enable-console-print!) (defn start [] (core/start) (ui/start "app")) (defn on-js-reload [] ;; unmount root component? (utils/info "reloading") (start)) ;; bootstrap ;; starts the app once but never again. hot reloading during development is handled by figwheel calling ` on - js - reload ` (defonce _ (do (on-js-reload) true))
null
https://raw.githubusercontent.com/ogri-la/strongbox-comrades/bd51a4eb3818bbc6780781ef9e21bd0a449f8d2a/src/strongbox_comrades/main.cljs
clojure
unmount root component? bootstrap starts the app once but never again.
(ns strongbox-comrades.main (:require [strongbox-comrades.core :as core] [strongbox-comrades.utils :as utils] [strongbox-comrades.ui :as ui])) (enable-console-print!) (defn start [] (core/start) (ui/start "app")) (defn on-js-reload [] (utils/info "reloading") (start)) hot reloading during development is handled by figwheel calling ` on - js - reload ` (defonce _ (do (on-js-reload) true))
dab9b631dddb1fca82454d255ed8fdc02ff0433dd5b4ee966fde3649ae067fad
Bodigrim/arithmoi
Coprimes.hs
-- | Module : Math . . Euclidean . Coprimes Copyright : ( c ) 2017 - 2018 Licence : MIT Maintainer : < > -- Container for pairwise coprime numbers . # LANGUAGE ScopedTypeVariables # # LANGUAGE TupleSections # module Math.NumberTheory.Euclidean.Coprimes ( splitIntoCoprimes , Coprimes , unCoprimes , singleton , insert ) where import Prelude hiding (gcd, quot, rem) import Data.Coerce import Data.Euclidean import Data.List (tails) import Data.Maybe import Data.Semiring (Semiring(..), isZero) import Data.Traversable -- | A list of pairwise coprime numbers -- with their multiplicities. newtype Coprimes a b = Coprimes { unCoprimes :: [(a, b)] -- ^ Unwrap. } deriving (Eq, Show) unsafeDivide :: GcdDomain a => a -> a -> a unsafeDivide x y = case x `divide` y of Nothing -> error "violated prerequisite of unsafeDivide" Just z -> z -- | Check whether an element is a unit of the ring. isUnit :: (Eq a, GcdDomain a) => a -> Bool isUnit x = not (isZero x) && isJust (one `divide` x) doPair :: (Eq a, GcdDomain a, Eq b, Num b) => a -> b -> a -> b -> (a, a, [(a, b)]) doPair x xm y ym | isUnit g = (x, y, []) | otherwise = (x', y', concat rests) where g = gcd x y (x', g', xgs) = doPair (x `unsafeDivide` g) xm g (xm + ym) xgs' = if isUnit g' then xgs else (g', xm + ym) : xgs (y', rests) = mapAccumL go (y `unsafeDivide` g) xgs' go w (t, tm) = (w', if isUnit t' || tm == 0 then acc else (t', tm) : acc) where (w', t', acc) = doPair w ym t tm _propDoPair :: (Eq a, Num a, GcdDomain a, Integral b) => a -> b -> a -> b -> Bool _propDoPair x xm y ym = isJust (x `divide` x') && isJust (y `divide` y') && coprime x' y' && all (coprime x' . fst) rest && all (coprime y' . fst) rest && not (any (isUnit . fst) rest) && and [ coprime s t | (s, _) : ts <- tails rest, (t, _) <- ts ] && abs ((x ^ xm) * (y ^ ym)) == abs ((x' ^ xm) * (y' ^ ym) * product (map (uncurry (^)) rest)) where (x', y', rest) = doPair x xm y ym insertInternal :: forall a b. (Eq a, GcdDomain a, Eq b, Num b) => a -> b -> Coprimes a b -> (Coprimes a b, Coprimes a b) insertInternal xx xm | isZero xx && xm == 0 = (, Coprimes []) | isZero xx = const (Coprimes [(zero, 1)], Coprimes []) | otherwise = coerce (go ([], []) xx) where go :: ([(a, b)], [(a, b)]) -> a -> [(a, b)] -> ([(a, b)], [(a, b)]) go (old, new) x rest | isUnit x = (rest ++ old, new) go (old, new) x [] = (old, (x, xm) : new) go _ _ ((x, _) : _) | isZero x = ([(zero, 1)], []) go (old, new) x ((y, ym) : rest) | isUnit y' = go (old, xys ++ new) x' rest | otherwise = go ((y', ym) : old, xys ++ new) x' rest where (x', y', xys) = doPair x xm y ym | Wrap a non - zero number with its multiplicity into ' Coprimes ' . -- > > > singleton 210 1 Coprimes { unCoprimes = [ ( 210,1 ) ] } singleton :: (Eq a, GcdDomain a, Eq b, Num b) => a -> b -> Coprimes a b singleton a b | isZero a && b == 0 = Coprimes [] | isUnit a = Coprimes [] | otherwise = Coprimes [(a, b)] | Add a non - zero number with its multiplicity to ' Coprimes ' . -- > > > insert 360 1 ( singleton 210 1 ) Coprimes { unCoprimes = [ ( 7,1),(5,2),(3,3),(2,4 ) ] } > > > insert 2 4 ( insert 7 1 ( insert 5 2 ( singleton 4 3 ) ) ) Coprimes { unCoprimes = [ ( 7,1),(5,2),(2,10 ) ] } insert :: (Eq a, GcdDomain a, Eq b, Num b) => a -> b -> Coprimes a b -> Coprimes a b insert x xm ys = Coprimes $ unCoprimes zs <> unCoprimes ws where (zs, ws) = insertInternal x xm ys instance (Eq a, GcdDomain a, Eq b, Num b) => Semigroup (Coprimes a b) where (Coprimes xs) <> ys = Coprimes $ unCoprimes zs <> foldMap unCoprimes wss where (zs, wss) = mapAccumL (\vs (x, xm) -> insertInternal x xm vs) ys xs instance (Eq a, GcdDomain a, Eq b, Num b) => Monoid (Coprimes a b) where mempty = Coprimes [] mappend = (<>) -- | The input list is assumed to be a factorisation of some number into a list of powers of ( possibly , composite ) non - zero factors . The output -- list is a factorisation of the same number such that all factors -- are coprime. Such transformation is crucial to continue factorisation -- (lazily, in parallel or concurrent fashion) without having to merge multiplicities of primes , which occurs more than in one -- composite factor. -- > > > splitIntoCoprimes [ ( 140 , 1 ) , ( 165 , 1 ) ] Coprimes { unCoprimes = [ ( 28,1),(33,1),(5,2 ) ] } > > > splitIntoCoprimes [ ( 360 , 1 ) , ( 210 , 1 ) ] Coprimes { unCoprimes = [ ( 7,1),(5,2),(3,3),(2,4 ) ] } splitIntoCoprimes :: (Eq a, GcdDomain a, Eq b, Num b) => [(a, b)] -> Coprimes a b splitIntoCoprimes = foldl (\acc (x, xm) -> insert x xm acc) mempty
null
https://raw.githubusercontent.com/Bodigrim/arithmoi/c72a1017450c2f1f05a959943dec265678b1cbc3/Math/NumberTheory/Euclidean/Coprimes.hs
haskell
| | A list of pairwise coprime numbers with their multiplicities. ^ Unwrap. | Check whether an element is a unit of the ring. | The input list is assumed to be a factorisation of some number list is a factorisation of the same number such that all factors are coprime. Such transformation is crucial to continue factorisation (lazily, in parallel or concurrent fashion) without composite factor.
Module : Math . . Euclidean . Coprimes Copyright : ( c ) 2017 - 2018 Licence : MIT Maintainer : < > Container for pairwise coprime numbers . # LANGUAGE ScopedTypeVariables # # LANGUAGE TupleSections # module Math.NumberTheory.Euclidean.Coprimes ( splitIntoCoprimes , Coprimes , unCoprimes , singleton , insert ) where import Prelude hiding (gcd, quot, rem) import Data.Coerce import Data.Euclidean import Data.List (tails) import Data.Maybe import Data.Semiring (Semiring(..), isZero) import Data.Traversable newtype Coprimes a b = Coprimes { } deriving (Eq, Show) unsafeDivide :: GcdDomain a => a -> a -> a unsafeDivide x y = case x `divide` y of Nothing -> error "violated prerequisite of unsafeDivide" Just z -> z isUnit :: (Eq a, GcdDomain a) => a -> Bool isUnit x = not (isZero x) && isJust (one `divide` x) doPair :: (Eq a, GcdDomain a, Eq b, Num b) => a -> b -> a -> b -> (a, a, [(a, b)]) doPair x xm y ym | isUnit g = (x, y, []) | otherwise = (x', y', concat rests) where g = gcd x y (x', g', xgs) = doPair (x `unsafeDivide` g) xm g (xm + ym) xgs' = if isUnit g' then xgs else (g', xm + ym) : xgs (y', rests) = mapAccumL go (y `unsafeDivide` g) xgs' go w (t, tm) = (w', if isUnit t' || tm == 0 then acc else (t', tm) : acc) where (w', t', acc) = doPair w ym t tm _propDoPair :: (Eq a, Num a, GcdDomain a, Integral b) => a -> b -> a -> b -> Bool _propDoPair x xm y ym = isJust (x `divide` x') && isJust (y `divide` y') && coprime x' y' && all (coprime x' . fst) rest && all (coprime y' . fst) rest && not (any (isUnit . fst) rest) && and [ coprime s t | (s, _) : ts <- tails rest, (t, _) <- ts ] && abs ((x ^ xm) * (y ^ ym)) == abs ((x' ^ xm) * (y' ^ ym) * product (map (uncurry (^)) rest)) where (x', y', rest) = doPair x xm y ym insertInternal :: forall a b. (Eq a, GcdDomain a, Eq b, Num b) => a -> b -> Coprimes a b -> (Coprimes a b, Coprimes a b) insertInternal xx xm | isZero xx && xm == 0 = (, Coprimes []) | isZero xx = const (Coprimes [(zero, 1)], Coprimes []) | otherwise = coerce (go ([], []) xx) where go :: ([(a, b)], [(a, b)]) -> a -> [(a, b)] -> ([(a, b)], [(a, b)]) go (old, new) x rest | isUnit x = (rest ++ old, new) go (old, new) x [] = (old, (x, xm) : new) go _ _ ((x, _) : _) | isZero x = ([(zero, 1)], []) go (old, new) x ((y, ym) : rest) | isUnit y' = go (old, xys ++ new) x' rest | otherwise = go ((y', ym) : old, xys ++ new) x' rest where (x', y', xys) = doPair x xm y ym | Wrap a non - zero number with its multiplicity into ' Coprimes ' . > > > singleton 210 1 Coprimes { unCoprimes = [ ( 210,1 ) ] } singleton :: (Eq a, GcdDomain a, Eq b, Num b) => a -> b -> Coprimes a b singleton a b | isZero a && b == 0 = Coprimes [] | isUnit a = Coprimes [] | otherwise = Coprimes [(a, b)] | Add a non - zero number with its multiplicity to ' Coprimes ' . > > > insert 360 1 ( singleton 210 1 ) Coprimes { unCoprimes = [ ( 7,1),(5,2),(3,3),(2,4 ) ] } > > > insert 2 4 ( insert 7 1 ( insert 5 2 ( singleton 4 3 ) ) ) Coprimes { unCoprimes = [ ( 7,1),(5,2),(2,10 ) ] } insert :: (Eq a, GcdDomain a, Eq b, Num b) => a -> b -> Coprimes a b -> Coprimes a b insert x xm ys = Coprimes $ unCoprimes zs <> unCoprimes ws where (zs, ws) = insertInternal x xm ys instance (Eq a, GcdDomain a, Eq b, Num b) => Semigroup (Coprimes a b) where (Coprimes xs) <> ys = Coprimes $ unCoprimes zs <> foldMap unCoprimes wss where (zs, wss) = mapAccumL (\vs (x, xm) -> insertInternal x xm vs) ys xs instance (Eq a, GcdDomain a, Eq b, Num b) => Monoid (Coprimes a b) where mempty = Coprimes [] mappend = (<>) into a list of powers of ( possibly , composite ) non - zero factors . The output having to merge multiplicities of primes , which occurs more than in one > > > splitIntoCoprimes [ ( 140 , 1 ) , ( 165 , 1 ) ] Coprimes { unCoprimes = [ ( 28,1),(33,1),(5,2 ) ] } > > > splitIntoCoprimes [ ( 360 , 1 ) , ( 210 , 1 ) ] Coprimes { unCoprimes = [ ( 7,1),(5,2),(3,3),(2,4 ) ] } splitIntoCoprimes :: (Eq a, GcdDomain a, Eq b, Num b) => [(a, b)] -> Coprimes a b splitIntoCoprimes = foldl (\acc (x, xm) -> insert x xm acc) mempty
593ba91596e5d9262322e40e92e56ebbd61600f5f368acd19ea292da495c52ac
CSVdB/pinky
Zip.hs
module Utils.Zip where import Import (><) :: [a] -> [b] -> Either String [(a, b)] (x:xs) >< (y:ys) = fmap ((x, y) :) $ xs >< ys [] >< [] = Right [] [] >< _ = Left "The lists do not have the same length" _ >< [] = Left "The lists do not have the same length"
null
https://raw.githubusercontent.com/CSVdB/pinky/e77a4c0812ceb4b8548c41a7652fb247c2ab39e0/pinky-integration-test/src/Utils/Zip.hs
haskell
module Utils.Zip where import Import (><) :: [a] -> [b] -> Either String [(a, b)] (x:xs) >< (y:ys) = fmap ((x, y) :) $ xs >< ys [] >< [] = Right [] [] >< _ = Left "The lists do not have the same length" _ >< [] = Left "The lists do not have the same length"
0b38eaece0b098ff7e73217c462ed0eaa28bbab19f408e4142b9fc9f4a472f76
lathe/punctaffy-for-racket
main.rkt
#lang parendown/slash racket/base punctaffy ; Bindings that every program that uses Punctaffy - based DSLs should ; have at hand. Namely, the notations for the hyperbrackets ; themselves. Copyright 2021 , 2022 The Lathe Authors ; 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 ; ; -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. (require /for-syntax racket/base) (require /for-syntax /only-in syntax/parse attribute syntax-parse) (require /for-syntax /only-in lathe-comforts fn) (require /for-syntax /only-in punctaffy/private/util datum->syntax-with-everything) (require /for-syntax /only-in punctaffy/syntax-object/token-of-syntax list->token-of-syntax syntax->token-of-syntax token-of-syntax-beginning-with-assert-singular token-of-syntax-beginning-with-list* token-of-syntax-beginning-with-splicing-free-var token-of-syntax-beginning-with-syntax) (require /for-syntax /only-in punctaffy/taffy-notation makeshift-taffy-notation-akin-to-^<>d) (provide ^<d ^>d ^< ^>) (define-for-syntax (replace-body stx new-body) (syntax-parse stx / (macro-name . _) /datum->syntax stx `(,#'macro-name ,@new-body) stx stx)) (define-for-syntax (parse-^<>d direction stx) (syntax-parse stx / (op degree contents ...) /hash 'lexical-context (datum->syntax stx '#%lexical-context) 'direction direction 'degree #'degree 'contents (attribute contents) 'token-of-syntax (token-of-syntax-beginning-with-syntax (datum->syntax-with-everything stx '()) (token-of-syntax-beginning-with-list* (list->token-of-syntax /list (syntax->token-of-syntax #'op) (token-of-syntax-beginning-with-assert-singular (token-of-syntax-beginning-with-splicing-free-var 'degree)) (token-of-syntax-beginning-with-splicing-free-var 'contents)) (syntax->token-of-syntax /list))))) (define-syntax ^<d /makeshift-taffy-notation-akin-to-^<>d /fn stx (parse-^<>d '< stx)) (define-syntax ^>d /makeshift-taffy-notation-akin-to-^<>d /fn stx (parse-^<>d '> stx)) (define-for-syntax (parse-^<> direction degree stx) (syntax-parse stx / (op contents ...) /hash 'lexical-context (datum->syntax stx '#%lexical-context) 'direction direction 'degree degree 'contents (attribute contents) 'token-of-syntax (token-of-syntax-beginning-with-syntax (datum->syntax-with-everything stx '()) (token-of-syntax-beginning-with-list* (list->token-of-syntax /list (syntax->token-of-syntax #'op) (token-of-syntax-beginning-with-splicing-free-var 'contents)) (syntax->token-of-syntax /list))))) (define-syntax ^< /makeshift-taffy-notation-akin-to-^<>d /fn stx (parse-^<> '< #'2 stx)) (define-syntax ^> /makeshift-taffy-notation-akin-to-^<>d /fn stx (parse-^<> '> #'1 stx))
null
https://raw.githubusercontent.com/lathe/punctaffy-for-racket/9643122784404562e0f5d6186381f5bc1ba4adcf/punctaffy-lib/main.rkt
racket
have at hand. Namely, the notations for the hyperbrackets themselves. you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, either express or implied. See the License for the specific language governing permissions and limitations under the License.
#lang parendown/slash racket/base punctaffy Bindings that every program that uses Punctaffy - based DSLs should Copyright 2021 , 2022 The Lathe Authors software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , (require /for-syntax racket/base) (require /for-syntax /only-in syntax/parse attribute syntax-parse) (require /for-syntax /only-in lathe-comforts fn) (require /for-syntax /only-in punctaffy/private/util datum->syntax-with-everything) (require /for-syntax /only-in punctaffy/syntax-object/token-of-syntax list->token-of-syntax syntax->token-of-syntax token-of-syntax-beginning-with-assert-singular token-of-syntax-beginning-with-list* token-of-syntax-beginning-with-splicing-free-var token-of-syntax-beginning-with-syntax) (require /for-syntax /only-in punctaffy/taffy-notation makeshift-taffy-notation-akin-to-^<>d) (provide ^<d ^>d ^< ^>) (define-for-syntax (replace-body stx new-body) (syntax-parse stx / (macro-name . _) /datum->syntax stx `(,#'macro-name ,@new-body) stx stx)) (define-for-syntax (parse-^<>d direction stx) (syntax-parse stx / (op degree contents ...) /hash 'lexical-context (datum->syntax stx '#%lexical-context) 'direction direction 'degree #'degree 'contents (attribute contents) 'token-of-syntax (token-of-syntax-beginning-with-syntax (datum->syntax-with-everything stx '()) (token-of-syntax-beginning-with-list* (list->token-of-syntax /list (syntax->token-of-syntax #'op) (token-of-syntax-beginning-with-assert-singular (token-of-syntax-beginning-with-splicing-free-var 'degree)) (token-of-syntax-beginning-with-splicing-free-var 'contents)) (syntax->token-of-syntax /list))))) (define-syntax ^<d /makeshift-taffy-notation-akin-to-^<>d /fn stx (parse-^<>d '< stx)) (define-syntax ^>d /makeshift-taffy-notation-akin-to-^<>d /fn stx (parse-^<>d '> stx)) (define-for-syntax (parse-^<> direction degree stx) (syntax-parse stx / (op contents ...) /hash 'lexical-context (datum->syntax stx '#%lexical-context) 'direction direction 'degree degree 'contents (attribute contents) 'token-of-syntax (token-of-syntax-beginning-with-syntax (datum->syntax-with-everything stx '()) (token-of-syntax-beginning-with-list* (list->token-of-syntax /list (syntax->token-of-syntax #'op) (token-of-syntax-beginning-with-splicing-free-var 'contents)) (syntax->token-of-syntax /list))))) (define-syntax ^< /makeshift-taffy-notation-akin-to-^<>d /fn stx (parse-^<> '< #'2 stx)) (define-syntax ^> /makeshift-taffy-notation-akin-to-^<>d /fn stx (parse-^<> '> #'1 stx))
344dab025eddef3f4e68319fa012aae549c313ddcd42f068b9694da49724d748
darrenldl/ocaml-SeqBox
misc_utils.ml
open Stdint type required_len_and_seek_to = { required_len : int64 ; seek_to : int64 } exception Invalid_range let pad_bytes ? ( filler : uint8 = Uint8.of_int 0x00 ) ( old_bytes : bytes ) ( new_len : int ) : bytes = let buf = Bytes.create 1 in Uint8.to_bytes_big_endian filler buf 0 ; let buf 0 in let old_len = Bytes.length old_bytes in if old_len < new_len then let new_bytes = Bytes.make new_len filler_char in Bytes.blit old_bytes 0 new_bytes 0 old_len ; new_bytes else old_bytes ; ; let buf = Bytes.create 1 in Uint8.to_bytes_big_endian filler buf 0; let filler_char = Bytes.get buf 0 in let old_len = Bytes.length old_bytes in if old_len < new_len then let new_bytes = Bytes.make new_len filler_char in Bytes.blit old_bytes 0 new_bytes 0 old_len; new_bytes else old_bytes ;;*) let get_sub_string (chunk:string) ~(pos:int) ~(len:int) : string = let chunk_size = String.length chunk in if pos < 0 || pos >= chunk_size then raise Invalid_range else if len < 0 then raise Invalid_range else if pos + (len - 1) >= chunk_size then raise Invalid_range else String.sub chunk pos len ;; let get_sub_string_inc_range (chunk:string) ~(start_at:int) ~(end_at:int) : string = get_sub_string chunk ~pos:start_at ~len:(end_at - start_at + 1) ;; let get_sub_string_exc_range (chunk:string) ~(start_at:int) ~(end_before:int) : string = get_sub_string chunk ~pos:start_at ~len:(end_before - start_at) ;; let list_find_option (pred:('a -> bool)) (lst:'a list) : 'a option = try Some (List.find pred lst) with | Not_found -> None ;; let make_path (path_parts:string list) : string = let strip_slash str = let str_len = String.length str in match str_len with | 0 -> str | 1 -> begin if (String.get str 0) = '/' then "" else str end | _ -> begin let char_last = String.get str (str_len - 1) in let char_2nd_last = String.get str (str_len - 2) in if char_last = '/' && char_2nd_last <> '\\' then get_sub_string str ~pos:0 ~len:(str_len - 1) else str end in let lst = List.map strip_slash path_parts in String.concat "/" lst ;; let char_list_to_string (lst:char list) : string = String.concat "" (List.map (fun c -> String.make 1 c) lst) ;; let path_to_list (path:string) : string list = let open Angstrom in let sep : unit Angstrom.t = string "/" *> return () in let escaped_sep : char list Angstrom.t = string "\\/" *> return ['\\'; '/'] in let not_sep : char list Angstrom.t = not_char '/' >>| (fun c -> [c]) in let single_parser : string Angstrom.t = many (choice [ escaped_sep ; not_sep ]) >>| List.concat >>| char_list_to_string in let path_parser : string list Angstrom.t = sep_by sep single_parser in match Angstrom.parse_string path_parser path with | Ok lst -> lst | Error _ -> assert false ;; let path_to_file (path:string) : string = List.hd (List.rev (path_to_list path)) ;; let get_option_ref_init_if_none (eval:(unit -> 'a)) (opt_ref:'a option ref) : 'a = match !opt_ref with | Some x -> x | None -> let x = eval () in opt_ref := Some x; x ;; let pad_string ?(filler:char = '\x00') (input:string) (len:int) : string = let input_len = String.length input in let pad_len = len - input_len in let padding = if pad_len > 0 then String.make pad_len filler else "" in String.concat "" [input; padding] ;; let round_down_to_multiple_int64 ~(multiple_of:int64) (x:int64) : int64 = let (</>) = Int64.div in let (<*>) = Int64.mul in (x </> multiple_of) <*> multiple_of ;; let round_down_to_multiple ~(multiple_of:int) (x:int) : int = (x / multiple_of) * multiple_of ;; let round_up_to_multiple_int64 ~(multiple_of:int64) (x:int64) : int64 = let (</>) = Int64.div in let (<*>) = Int64.mul in let (<+>) = Int64.add in ((x <+> (Int64.pred multiple_of)) </> multiple_of) <*> multiple_of ;; let round_up_to_multiple ~(multiple_of:int) (x:int) : int = ((x + (pred multiple_of)) / multiple_of) * multiple_of ;; let ensure_at_least (type a) ~(at_least:a) (x:a) = max at_least x ;; let ensure_at_most (type a) ~(at_most:a) (x:a) = min at_most x ;; let calc_required_len_and_seek_to_from_byte_range ~(from_byte:int64 option) ~(to_byte:int64 option) ~(force_misalign:bool) ~(bytes_so_far:int64) ~(last_possible_pos:int64) : required_len_and_seek_to = let open Int64_ops in let multiple_of = Int64.of_int Param.Common.block_scan_alignment in let align : int64 -> int64 = if force_misalign then (fun x -> x) else round_down_to_multiple_int64 ~multiple_of in let from_byte = match from_byte with | None -> 0L | Some n -> n |> ensure_at_least ~at_least:0L |> ensure_at_most ~at_most:last_possible_pos |> align in let to_byte = match to_byte with | None -> last_possible_pos | Some n -> n |> ensure_at_least ~at_least:from_byte |> ensure_at_most ~at_most:last_possible_pos in bytes_so_far only affects { required_len = to_byte <-> from_byte <+> 1L ; seek_to = align (from_byte <+> bytes_so_far) } ;;
null
https://raw.githubusercontent.com/darrenldl/ocaml-SeqBox/658c623db8745ae1d804c75880b29fb53435860f/src/misc_utils.ml
ocaml
open Stdint type required_len_and_seek_to = { required_len : int64 ; seek_to : int64 } exception Invalid_range let pad_bytes ? ( filler : uint8 = Uint8.of_int 0x00 ) ( old_bytes : bytes ) ( new_len : int ) : bytes = let buf = Bytes.create 1 in Uint8.to_bytes_big_endian filler buf 0 ; let buf 0 in let old_len = Bytes.length old_bytes in if old_len < new_len then let new_bytes = Bytes.make new_len filler_char in Bytes.blit old_bytes 0 new_bytes 0 old_len ; new_bytes else old_bytes ; ; let buf = Bytes.create 1 in Uint8.to_bytes_big_endian filler buf 0; let filler_char = Bytes.get buf 0 in let old_len = Bytes.length old_bytes in if old_len < new_len then let new_bytes = Bytes.make new_len filler_char in Bytes.blit old_bytes 0 new_bytes 0 old_len; new_bytes else old_bytes ;;*) let get_sub_string (chunk:string) ~(pos:int) ~(len:int) : string = let chunk_size = String.length chunk in if pos < 0 || pos >= chunk_size then raise Invalid_range else if len < 0 then raise Invalid_range else if pos + (len - 1) >= chunk_size then raise Invalid_range else String.sub chunk pos len ;; let get_sub_string_inc_range (chunk:string) ~(start_at:int) ~(end_at:int) : string = get_sub_string chunk ~pos:start_at ~len:(end_at - start_at + 1) ;; let get_sub_string_exc_range (chunk:string) ~(start_at:int) ~(end_before:int) : string = get_sub_string chunk ~pos:start_at ~len:(end_before - start_at) ;; let list_find_option (pred:('a -> bool)) (lst:'a list) : 'a option = try Some (List.find pred lst) with | Not_found -> None ;; let make_path (path_parts:string list) : string = let strip_slash str = let str_len = String.length str in match str_len with | 0 -> str | 1 -> begin if (String.get str 0) = '/' then "" else str end | _ -> begin let char_last = String.get str (str_len - 1) in let char_2nd_last = String.get str (str_len - 2) in if char_last = '/' && char_2nd_last <> '\\' then get_sub_string str ~pos:0 ~len:(str_len - 1) else str end in let lst = List.map strip_slash path_parts in String.concat "/" lst ;; let char_list_to_string (lst:char list) : string = String.concat "" (List.map (fun c -> String.make 1 c) lst) ;; let path_to_list (path:string) : string list = let open Angstrom in let sep : unit Angstrom.t = string "/" *> return () in let escaped_sep : char list Angstrom.t = string "\\/" *> return ['\\'; '/'] in let not_sep : char list Angstrom.t = not_char '/' >>| (fun c -> [c]) in let single_parser : string Angstrom.t = many (choice [ escaped_sep ; not_sep ]) >>| List.concat >>| char_list_to_string in let path_parser : string list Angstrom.t = sep_by sep single_parser in match Angstrom.parse_string path_parser path with | Ok lst -> lst | Error _ -> assert false ;; let path_to_file (path:string) : string = List.hd (List.rev (path_to_list path)) ;; let get_option_ref_init_if_none (eval:(unit -> 'a)) (opt_ref:'a option ref) : 'a = match !opt_ref with | Some x -> x | None -> let x = eval () in opt_ref := Some x; x ;; let pad_string ?(filler:char = '\x00') (input:string) (len:int) : string = let input_len = String.length input in let pad_len = len - input_len in let padding = if pad_len > 0 then String.make pad_len filler else "" in String.concat "" [input; padding] ;; let round_down_to_multiple_int64 ~(multiple_of:int64) (x:int64) : int64 = let (</>) = Int64.div in let (<*>) = Int64.mul in (x </> multiple_of) <*> multiple_of ;; let round_down_to_multiple ~(multiple_of:int) (x:int) : int = (x / multiple_of) * multiple_of ;; let round_up_to_multiple_int64 ~(multiple_of:int64) (x:int64) : int64 = let (</>) = Int64.div in let (<*>) = Int64.mul in let (<+>) = Int64.add in ((x <+> (Int64.pred multiple_of)) </> multiple_of) <*> multiple_of ;; let round_up_to_multiple ~(multiple_of:int) (x:int) : int = ((x + (pred multiple_of)) / multiple_of) * multiple_of ;; let ensure_at_least (type a) ~(at_least:a) (x:a) = max at_least x ;; let ensure_at_most (type a) ~(at_most:a) (x:a) = min at_most x ;; let calc_required_len_and_seek_to_from_byte_range ~(from_byte:int64 option) ~(to_byte:int64 option) ~(force_misalign:bool) ~(bytes_so_far:int64) ~(last_possible_pos:int64) : required_len_and_seek_to = let open Int64_ops in let multiple_of = Int64.of_int Param.Common.block_scan_alignment in let align : int64 -> int64 = if force_misalign then (fun x -> x) else round_down_to_multiple_int64 ~multiple_of in let from_byte = match from_byte with | None -> 0L | Some n -> n |> ensure_at_least ~at_least:0L |> ensure_at_most ~at_most:last_possible_pos |> align in let to_byte = match to_byte with | None -> last_possible_pos | Some n -> n |> ensure_at_least ~at_least:from_byte |> ensure_at_most ~at_most:last_possible_pos in bytes_so_far only affects { required_len = to_byte <-> from_byte <+> 1L ; seek_to = align (from_byte <+> bytes_so_far) } ;;
7e866ab34daf062f9a58bf33ef1040c20f9bb763a2ce0f4d664122a4ad77c48d
markostanimirovic/re-action
core_test.clj
(ns re-action.core-test (:require [clojure.test :refer :all] [re-action.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
null
https://raw.githubusercontent.com/markostanimirovic/re-action/d6cb33d9ac73bedeac4f09996c2c741d21bda7ba/test/re_action/core_test.clj
clojure
(ns re-action.core-test (:require [clojure.test :refer :all] [re-action.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
2ba58305c8efa19a828bf54f7177ab38d9c7fea67dcee280fa050840dd5fc619
datacrypt-project/hitchhiker-tree
bench.clj
(ns hitchhiker.bench (:require [clojure.pprint :as pp] [clojure.string :as str] [clojure.tools.cli :refer [parse-opts]] [excel-templates.build :as excel] [hitchhiker.redis :as redis] [hitchhiker.tree.core :refer [<?? <? go-try] :as core] [hitchhiker.tree.messaging :as msg]) (:import [java.io File FileWriter])) (defn generate-test-datasets "Returns a list of datasets" [] [{:name "in-order" :data (range)} {:name "random" :data (repeatedly rand)}]) (defn core-b-tree "Returns a b-tree with core insert" [b backend] {:structure (<?? (core/b-tree (core/->Config b b 0))) :insert core/insert :delete core/delete :flush (fn [x] (<?? (core/flush-tree x backend)))}) (defn msg-b-tree "Returns a b-tree with msg insert" [b backend] (let [sqrt-b (long (Math/sqrt b))] {:structure (<?? (core/b-tree(core/->Config sqrt-b b (- b sqrt-b)))) :insert msg/insert :delete msg/delete :flush (fn [x] (<?? (core/flush-tree x backend)))})) (defn sorted-set-repr "Returns a sorted set" [] {:structure (sorted-map) :insert (fn [m k v] (go-try (assoc m k v))) :delete (fn [m k] (go-try (dissoc m k))) :flush (fn [set] {:tree set :stats (atom {})})}) (defn create-output-dir [dir aux] (let [my-dir (File. dir aux)] (when (.exists my-dir) (throw (ex-info (str "Output dir already exists: " dir) {}))) (.mkdirs my-dir) (spit (File. my-dir "time") (str (java.util.Date.))) (let [speed-csv (FileWriter. (File. my-dir (str "speed_" aux ".csv"))) flush - csv ( FileWriter . ( File . my - dir ( str " flush_iops _ " aux " .csv " ) ) ) ] {:speed speed-csv ;:flush flush-csv }))) (defn benchmark "n is the total number of samples dataset is the test dataset flush-freq is the number of keys per flush datastruct is the test data structure out is the stream to write the results to (as well as stdout)" [n dataset flush-freq datastruct out delete-xform] (let [{:keys [structure delete insert flush]} datastruct dataset (take n (:data dataset))] (<?? (go-try (loop [[x & data] dataset t 0 tree structure last-flush nil i 0 inserting? true outputs []] (let [i' (inc i) {flushed-tree :tree stats :stats} (when (zero? (mod i' flush-freq)) (flush tree)) before (System/nanoTime) tree' (if inserting? (<? (insert (or flushed-tree tree) x x)) (<? (delete (or flushed-tree tree) x))) after (System/nanoTime) log-inserts (zero? (mod i' (quot n 100))) updated-outputs (atom outputs)] 1000 pieces (binding [*out* (:speed out)] (let [ks (sort (keys last-flush)) avg-ns (float (/ t (quot n 100)))] (when (zero? i) (println (str "elements,op,insert_took_avg_ns," (str/join "," ks)))) (println (str i' "," (if inserting? "insert" "delete") "," avg-ns "," (str/join "," (map #(get last-flush %) ks)))) (swap! updated-outputs conj (-> (into {} last-flush) (assoc :ins-avg-ns avg-ns (if inserting? :insert :delete) true :n i')))))) (cond (seq data) (recur data (if log-inserts 0 (+ t (- after before))) tree' (if stats (merge-with + last-flush @stats) last-flush) i' inserting? @updated-outputs) inserting? (recur (delete-xform dataset) 0 tree' nil i' false @updated-outputs) :else @updated-outputs))))))) (def options [["-n" "--num-operations NUM_OPS" "The number of elements that will be applied to the data structure" :default 100000 :parse-fn #(Long. %) :validate [pos? "n must be positive"]] [nil "--data-structure STRUCT" "Which data structure to run the test on" :default "fractal" :validate [#(#{"fractal" "b-tree" "sorted-set"} %) "Data structure must be fractal, b-tree, or sorted set"]] [nil "--backend testing" "Runs the benchmark with the specified backend" :default "testing" :validate [#(#{"redis" "testing"} %) "Backend must be redis or testing"]] ["-d" "--delete-pattern PATTERN" "Specifies how the operations will be reordered on delete" :default "forward" :validate [#(#{"forward" "reverse" "shuffle" "zero"} %) "Incorrect delete pattern"] ] [nil "--sorted-set" "Runs the benchmarks on a sorted set"] ["-b" "--tree-width WIDTH" "Determines the width of the trees. Fractal trees use sqrt(b) child pointers; the rest is for messages." :default 300 :parse-fn #(Long. %) :validate [pos? "b must be positive"]] ["-f" "--flush-freq FREQ" "After how many operations should the tree get flushed?" :default 1000 :parse-fn #(Long. %) :validate [pos? "flush frequency must be positive"]] ["-h" "--help" "Prints this help"]]) (defn exit [status msg] (println msg) (System/exit status)) (defn error-msg [errors] (str "The following errors occurred while parsing your command:\n\n" (str/join \newline errors))) (defn usage [options-summary] (str/join \newline ["Usage: bench output-dir [options] [-- [other-options]]*" "" "Options:" options-summary "" "Delete patterns:" "forward: we delete the elements in the order they were inserted" "reverse: we delete the elements in the reverse order they were inserted" "shuffle: we delete the elements in a random order" "zero: we repeatedly attempt to delete 0, thus never actually deleting" "" "Backends:" "testing: this backend serializes nothing, just using an extra indirection" "redis: this backend uses a local redis server"])) (defn make-template-for-one-tree-freq-combo [list-of-benchmark-results filter-by] ;(clojure.pprint/pprint list-of-benchmark-results) (assert (= 2 (count list-of-benchmark-results)) "Should be random and ordered") (let [indexed (group-by :ds list-of-benchmark-results)] (map #(vector (:n %1) (:ins-avg-ns %1) (:writes %1) (:ins-avg-ns %2) (:writes %2)) (filter filter-by (:results (first (get indexed "in-order")))) (filter filter-by (:results (first (get indexed "random"))))))) (defn template-one-sheet [pair-of-results-for-one-ds-config] (let [{:keys [tree ds freq n b results delete-pattern]} (first pair-of-results-for-one-ds-config) x {0 [["Data Structure" (name tree) "" "n" n "" "Data Set" ds]] 1 [["Flush Frequency" freq "" "b" b "" "delete pattern" delete-pattern]] [5 18] (make-template-for-one-tree-freq-combo pair-of-results-for-one-ds-config :insert) [22 35] (make-template-for-one-tree-freq-combo pair-of-results-for-one-ds-config :delete)}] x)) (defn -main [& [root & args]] (let [outputs (atom [])] (doseq [args (or (->> args (partition-by #(= % "--")) (map-indexed vector) (filter (comp even? first)) (map second) (seq)) always do one iteration (let [{:keys [options arguments errors summary]} (parse-opts args options) tree-to-test (atom {}) results (atom [])] (cond (or (= "-h" root) (= "--help" root) (nil? root) (:help options)) (exit 0 (usage summary)) (not= (count arguments) 0) (exit 1 (usage summary)) errors (exit 1 (error-msg errors))) (let [backend (case (:backend options) "testing" (core/->TestingBackend) "redis" (do (redis/start-expiry-thread!) (redis/->RedisBackend))) delete-xform (case (:delete-pattern options) "forward" identity "reverse" reverse "shuffle" shuffle "zero" #(repeat (count %) 0.0)) [tree-name structure] (case (:data-structure options) "b-tree" ["b-tree" (core-b-tree (:tree-width options) backend)] "fractal" ["fractal" (msg-b-tree (:tree-width options) backend)] "sorted-set" ["sorted-set" (sorted-set-repr)]) flush-freq (:flush-freq options) codename (str tree-name "__flush_" flush-freq "__b_" (:tree-width options) "__" (:backend options) "__n_" (:num-operations options) "__del_" (:delete-pattern options))] (doseq [ds (generate-test-datasets) :let [codename (str codename "_" (:name ds)) out (create-output-dir root codename) _ (println "Doing" codename) bench-res (benchmark (:num-operations options) ds flush-freq structure out delete-xform)]] (swap! results conj {:tree tree-name :ds (:name ds) :freq flush-freq :n (:num-operations options) :b (:tree-width options) :delete-pattern (:delete-pattern options) :results bench-res})) ;(println "results") ( clojure.pprint/pprint ) (swap! outputs conj (template-one-sheet @results))))) (excel/render-to-file "template_benchmark.xlsx" (.getPath (File. root "analysis.xlsx")) {"SingleDS" (map-indexed (fn [i s] (assoc s :sheet-name (str "Trial " (inc i)))) @outputs)})))
null
https://raw.githubusercontent.com/datacrypt-project/hitchhiker-tree/f7d0f926541d7cb31fac11c2d2245c5bac451b86/env/profiling/hitchhiker/bench.clj
clojure
:flush flush-csv (clojure.pprint/pprint list-of-benchmark-results) (println "results")
(ns hitchhiker.bench (:require [clojure.pprint :as pp] [clojure.string :as str] [clojure.tools.cli :refer [parse-opts]] [excel-templates.build :as excel] [hitchhiker.redis :as redis] [hitchhiker.tree.core :refer [<?? <? go-try] :as core] [hitchhiker.tree.messaging :as msg]) (:import [java.io File FileWriter])) (defn generate-test-datasets "Returns a list of datasets" [] [{:name "in-order" :data (range)} {:name "random" :data (repeatedly rand)}]) (defn core-b-tree "Returns a b-tree with core insert" [b backend] {:structure (<?? (core/b-tree (core/->Config b b 0))) :insert core/insert :delete core/delete :flush (fn [x] (<?? (core/flush-tree x backend)))}) (defn msg-b-tree "Returns a b-tree with msg insert" [b backend] (let [sqrt-b (long (Math/sqrt b))] {:structure (<?? (core/b-tree(core/->Config sqrt-b b (- b sqrt-b)))) :insert msg/insert :delete msg/delete :flush (fn [x] (<?? (core/flush-tree x backend)))})) (defn sorted-set-repr "Returns a sorted set" [] {:structure (sorted-map) :insert (fn [m k v] (go-try (assoc m k v))) :delete (fn [m k] (go-try (dissoc m k))) :flush (fn [set] {:tree set :stats (atom {})})}) (defn create-output-dir [dir aux] (let [my-dir (File. dir aux)] (when (.exists my-dir) (throw (ex-info (str "Output dir already exists: " dir) {}))) (.mkdirs my-dir) (spit (File. my-dir "time") (str (java.util.Date.))) (let [speed-csv (FileWriter. (File. my-dir (str "speed_" aux ".csv"))) flush - csv ( FileWriter . ( File . my - dir ( str " flush_iops _ " aux " .csv " ) ) ) ] {:speed speed-csv }))) (defn benchmark "n is the total number of samples dataset is the test dataset flush-freq is the number of keys per flush datastruct is the test data structure out is the stream to write the results to (as well as stdout)" [n dataset flush-freq datastruct out delete-xform] (let [{:keys [structure delete insert flush]} datastruct dataset (take n (:data dataset))] (<?? (go-try (loop [[x & data] dataset t 0 tree structure last-flush nil i 0 inserting? true outputs []] (let [i' (inc i) {flushed-tree :tree stats :stats} (when (zero? (mod i' flush-freq)) (flush tree)) before (System/nanoTime) tree' (if inserting? (<? (insert (or flushed-tree tree) x x)) (<? (delete (or flushed-tree tree) x))) after (System/nanoTime) log-inserts (zero? (mod i' (quot n 100))) updated-outputs (atom outputs)] 1000 pieces (binding [*out* (:speed out)] (let [ks (sort (keys last-flush)) avg-ns (float (/ t (quot n 100)))] (when (zero? i) (println (str "elements,op,insert_took_avg_ns," (str/join "," ks)))) (println (str i' "," (if inserting? "insert" "delete") "," avg-ns "," (str/join "," (map #(get last-flush %) ks)))) (swap! updated-outputs conj (-> (into {} last-flush) (assoc :ins-avg-ns avg-ns (if inserting? :insert :delete) true :n i')))))) (cond (seq data) (recur data (if log-inserts 0 (+ t (- after before))) tree' (if stats (merge-with + last-flush @stats) last-flush) i' inserting? @updated-outputs) inserting? (recur (delete-xform dataset) 0 tree' nil i' false @updated-outputs) :else @updated-outputs))))))) (def options [["-n" "--num-operations NUM_OPS" "The number of elements that will be applied to the data structure" :default 100000 :parse-fn #(Long. %) :validate [pos? "n must be positive"]] [nil "--data-structure STRUCT" "Which data structure to run the test on" :default "fractal" :validate [#(#{"fractal" "b-tree" "sorted-set"} %) "Data structure must be fractal, b-tree, or sorted set"]] [nil "--backend testing" "Runs the benchmark with the specified backend" :default "testing" :validate [#(#{"redis" "testing"} %) "Backend must be redis or testing"]] ["-d" "--delete-pattern PATTERN" "Specifies how the operations will be reordered on delete" :default "forward" :validate [#(#{"forward" "reverse" "shuffle" "zero"} %) "Incorrect delete pattern"] ] [nil "--sorted-set" "Runs the benchmarks on a sorted set"] ["-b" "--tree-width WIDTH" "Determines the width of the trees. Fractal trees use sqrt(b) child pointers; the rest is for messages." :default 300 :parse-fn #(Long. %) :validate [pos? "b must be positive"]] ["-f" "--flush-freq FREQ" "After how many operations should the tree get flushed?" :default 1000 :parse-fn #(Long. %) :validate [pos? "flush frequency must be positive"]] ["-h" "--help" "Prints this help"]]) (defn exit [status msg] (println msg) (System/exit status)) (defn error-msg [errors] (str "The following errors occurred while parsing your command:\n\n" (str/join \newline errors))) (defn usage [options-summary] (str/join \newline ["Usage: bench output-dir [options] [-- [other-options]]*" "" "Options:" options-summary "" "Delete patterns:" "forward: we delete the elements in the order they were inserted" "reverse: we delete the elements in the reverse order they were inserted" "shuffle: we delete the elements in a random order" "zero: we repeatedly attempt to delete 0, thus never actually deleting" "" "Backends:" "testing: this backend serializes nothing, just using an extra indirection" "redis: this backend uses a local redis server"])) (defn make-template-for-one-tree-freq-combo [list-of-benchmark-results filter-by] (assert (= 2 (count list-of-benchmark-results)) "Should be random and ordered") (let [indexed (group-by :ds list-of-benchmark-results)] (map #(vector (:n %1) (:ins-avg-ns %1) (:writes %1) (:ins-avg-ns %2) (:writes %2)) (filter filter-by (:results (first (get indexed "in-order")))) (filter filter-by (:results (first (get indexed "random"))))))) (defn template-one-sheet [pair-of-results-for-one-ds-config] (let [{:keys [tree ds freq n b results delete-pattern]} (first pair-of-results-for-one-ds-config) x {0 [["Data Structure" (name tree) "" "n" n "" "Data Set" ds]] 1 [["Flush Frequency" freq "" "b" b "" "delete pattern" delete-pattern]] [5 18] (make-template-for-one-tree-freq-combo pair-of-results-for-one-ds-config :insert) [22 35] (make-template-for-one-tree-freq-combo pair-of-results-for-one-ds-config :delete)}] x)) (defn -main [& [root & args]] (let [outputs (atom [])] (doseq [args (or (->> args (partition-by #(= % "--")) (map-indexed vector) (filter (comp even? first)) (map second) (seq)) always do one iteration (let [{:keys [options arguments errors summary]} (parse-opts args options) tree-to-test (atom {}) results (atom [])] (cond (or (= "-h" root) (= "--help" root) (nil? root) (:help options)) (exit 0 (usage summary)) (not= (count arguments) 0) (exit 1 (usage summary)) errors (exit 1 (error-msg errors))) (let [backend (case (:backend options) "testing" (core/->TestingBackend) "redis" (do (redis/start-expiry-thread!) (redis/->RedisBackend))) delete-xform (case (:delete-pattern options) "forward" identity "reverse" reverse "shuffle" shuffle "zero" #(repeat (count %) 0.0)) [tree-name structure] (case (:data-structure options) "b-tree" ["b-tree" (core-b-tree (:tree-width options) backend)] "fractal" ["fractal" (msg-b-tree (:tree-width options) backend)] "sorted-set" ["sorted-set" (sorted-set-repr)]) flush-freq (:flush-freq options) codename (str tree-name "__flush_" flush-freq "__b_" (:tree-width options) "__" (:backend options) "__n_" (:num-operations options) "__del_" (:delete-pattern options))] (doseq [ds (generate-test-datasets) :let [codename (str codename "_" (:name ds)) out (create-output-dir root codename) _ (println "Doing" codename) bench-res (benchmark (:num-operations options) ds flush-freq structure out delete-xform)]] (swap! results conj {:tree tree-name :ds (:name ds) :freq flush-freq :n (:num-operations options) :b (:tree-width options) :delete-pattern (:delete-pattern options) :results bench-res})) ( clojure.pprint/pprint ) (swap! outputs conj (template-one-sheet @results))))) (excel/render-to-file "template_benchmark.xlsx" (.getPath (File. root "analysis.xlsx")) {"SingleDS" (map-indexed (fn [i s] (assoc s :sheet-name (str "Trial " (inc i)))) @outputs)})))
192e418ee48d617b6e655c9fbbc83082190f01d8e73dfcbeb74701de15e70021
Suikaba/SelingerQuantumLambdaCalculus
intuitionistic_typed.ml
open Core open Syntax open Unify exception ITypeError type ityped_term = IConst of constant * itype | IVar of id * itype | ITuple0 of itype | IAbst of id * ityped_term * itype | IApp of ityped_term * ityped_term * itype | IPair of ityped_term * ityped_term * itype | ILet of id * id * ityped_term * ityped_term * itype | IInjL of ityped_term * itype | IInjR of ityped_term * itype | IMatch of ityped_term * (id * ityped_term) * (id * ityped_term) * itype | ILetRec of id * ityped_term * ityped_term * itype let fresh_tyvar = let counter = ref 0 in let body () = counter := !counter + 1; !counter in body let rec string_of_iterm = function | IConst (c, ty) -> Printf.sprintf "(%s : %s)" (string_of_const c) (string_of_itype ty) | IVar (id, ty) -> Printf.sprintf "(%s : %s)" id (string_of_itype ty) | ITuple0 ty -> Printf.sprintf "(* : %s)" (string_of_itype ty) | IAbst (id, t, ty) -> Printf.sprintf "((lam %s . %s) : %s)" id (string_of_iterm t) (string_of_itype ty) | IApp (t1, t2, ty) -> Printf.sprintf "(%s %s : %s)" (string_of_iterm t1) (string_of_iterm t2) (string_of_itype ty) | IPair (t1, t2, ty) -> Printf.sprintf "(<%s, %s> : %s)" (string_of_iterm t1) (string_of_iterm t2) (string_of_itype ty) | ILet (x, y, t1, t2, ty) -> Printf.sprintf "(let <%s, %s> = %s in %s) : %s" x y (string_of_iterm t1) (string_of_iterm t2) (string_of_itype ty) | IInjL (t, ty) -> (match t with | ITuple0 _ -> Printf.sprintf "(1 : %s)" (string_of_itype ty) | t -> Printf.sprintf "(injl(%s) : %s)" (string_of_iterm t) (string_of_itype ty)) | IInjR (t, ty) -> (match t with | ITuple0 _ -> Printf.sprintf "(0 : %s)" (string_of_itype ty) | t -> Printf.sprintf "(injr(%s) : %s)" (string_of_iterm t) (string_of_itype ty)) | IMatch (t1, (x, t2), (y, t3), ty) -> Printf.sprintf "(match %s with %s -> %s | %s -> %s) : %s" (string_of_iterm t1) x (string_of_iterm t2) y (string_of_iterm t3) (string_of_itype ty) | ILetRec (f, t1, t2, ty) -> Printf.sprintf "(let rec %s = %s in %s) : %s" f (string_of_iterm t1) (string_of_iterm t2) (string_of_itype ty) (* type inference *) let ity_const = function | New -> ITyFun (itybit, ITyQbit) | Meas -> ITyFun (ITyQbit, itybit) | H -> ITyFun (ITyQbit, ITyQbit) (* todo *) | _ -> failwith "Not implemented" let rec ity_infer tyenv = function | Const c -> empty_subst, ity_const c, IConst (c, ity_const c) | Var id -> empty_subst, Environment.lookup tyenv id, IVar (id, Environment.lookup tyenv id) | Tuple0 -> empty_subst, ITySingleton, ITuple0 ITySingleton | Abst (id, body) -> let tyarg = ITyVar (fresh_tyvar ()) in let tyenv = Environment.extend tyenv id tyarg in let s, tybody, ibody = ity_infer tyenv body in let ty = ITyFun (subst_type s tyarg, tybody) in s, ty, IAbst (id, ibody, ty) | App (t1, t2) -> let s1, tyf, it1 = ity_infer tyenv t1 in let s2, tyarg, it2 = ity_infer tyenv t2 in let tybody = ITyVar (fresh_tyvar ()) in let s = unify (merge_subst s1 s2) [tyf, ITyFun (tyarg, tybody)] in let ty = subst_type s tybody in s, ty, IApp (it1, it2, ty) | Pair (t1, t2) -> let s1, ty1, it1 = ity_infer tyenv t1 in let s2, ty2, it2 = ity_infer tyenv t2 in merge_subst s1 s2, ITyProd (ty1, ty2), IPair (it1, it2, ITyProd (ty1, ty2)) | Let (x, y, t1, t2) -> let s1, ty1, it1 = ity_infer tyenv t1 in (match ty1 with | ITyVar a -> let fst = ITyVar (fresh_tyvar ()) in let snd = ITyVar (fresh_tyvar ()) in let tyenv = Environment.extend (Environment.extend tyenv x fst) y snd in let s2, ty2, it2 = ity_infer tyenv t2 in let s = unify (merge_subst s1 s2) [ITyVar a, ITyProd (fst, snd)] in s, subst_type s ty2, ILet (x, y, it1, it2, subst_type s ty2) | ITyProd (ty1', ty2') -> let tyenv = Environment.extend tyenv x ty1' in let tyenv = Environment.extend tyenv y ty2' in let s2, ty2, it2 = ity_infer tyenv t2 in let s = merge_subst s1 s2 in s, subst_type s ty2, ILet (x, y, it1, it2, subst_type s ty2) | _ -> raise ITypeError) | InjL t -> let s, ty, it = ity_infer tyenv t in let ty = ITySum (ty, ITyVar (fresh_tyvar ())) in s, ty, IInjL (it, ty) | InjR t -> let s, ty, it = ity_infer tyenv t in let ty = ITySum (ITyVar (fresh_tyvar ()), ty) in s, ty, IInjR (it, ty) | Match (t1, (x, t2), (y, t3)) -> let s1, ty1, it1 = ity_infer tyenv t1 in let s1, xty, yty = (match ty1 with | ITySum (xty, yty) -> s1, xty, yty | ITyVar a -> let xty = ITyVar (fresh_tyvar ()) in let yty = ITyVar (fresh_tyvar ()) in unify s1 [ITyVar a, ITySum (xty, yty)], xty, yty | _ -> raise ITypeError) in let s2, ty2, it2 = ity_infer (Environment.extend tyenv x xty) t2 in let s3, ty3, it3 = ity_infer (Environment.extend tyenv y yty) t3 in let s = unify (merge_subst s1 (merge_subst s2 s3)) [ty2, ty3] in s, subst_type s ty2, IMatch (it1, (x, it2), (y, it3), subst_type s ty2) | LetRec (f, t1, t2) -> let tyenv = Environment.extend tyenv f (ITyVar (fresh_tyvar ())) in let s1, tyf, it1 = ity_infer tyenv t1 in let s2, ty2, it2 = ity_infer tyenv t2 in let s = unify (merge_subst s1 s2) [tyf, Environment.lookup tyenv f] in s, subst_type s ty2, ILetRec (f, it1, it2, subst_type s ty2) (* create intuitionistic typed term *) let ity_term tyenv t = let s, _, it = ity_infer tyenv t in let rec fix_with_singleton = (function | ITyVar _ -> ITySingleton (* replace with singleton *) | ITyQbit -> ITyQbit | ITySingleton -> ITySingleton | ITyFun (ty1, ty2) -> ITyFun (fix_with_singleton ty1, fix_with_singleton ty2) | ITyProd (ty1, ty2) -> ITyProd (fix_with_singleton ty1, fix_with_singleton ty2) | ITySum (ty1, ty2) -> ITySum (fix_with_singleton ty1, fix_with_singleton ty2)) in let rec correct_type = (function | IConst (c, ty) -> IConst (c, fix_with_singleton (subst_type s ty)) | IVar (id, ty) -> IVar (id, fix_with_singleton (subst_type s ty)) | ITuple0 ty -> ITuple0 ty | IAbst (id, t, ty) -> IAbst (id, correct_type t, fix_with_singleton (subst_type s ty)) | IApp (t1, t2, ty) -> IApp (correct_type t1, correct_type t2, fix_with_singleton (subst_type s ty)) | IPair (t1, t2, ty) -> IPair (correct_type t1, correct_type t2, fix_with_singleton (subst_type s ty)) | ILet (x, y, t1, t2, ty) -> ILet (x, y, correct_type t1, correct_type t2, fix_with_singleton (subst_type s ty)) | IInjL (t, ty) -> IInjL (correct_type t, fix_with_singleton (subst_type s ty)) | IInjR (t, ty) -> IInjR (correct_type t, fix_with_singleton (subst_type s ty)) | IMatch (t1, (x, t2), (y, t3), ty) -> IMatch (correct_type t1, (x, correct_type t2), (y, correct_type t3), fix_with_singleton (subst_type s ty)) | ILetRec (f, t1, t2, ty) -> ILetRec (f, correct_type t1, correct_type t2, fix_with_singleton (subst_type s ty))) in correct_type it
null
https://raw.githubusercontent.com/Suikaba/SelingerQuantumLambdaCalculus/6a5160d38ad0333278a3f1c068284e3028068a0a/src/intuitionistic_typed.ml
ocaml
type inference todo create intuitionistic typed term replace with singleton
open Core open Syntax open Unify exception ITypeError type ityped_term = IConst of constant * itype | IVar of id * itype | ITuple0 of itype | IAbst of id * ityped_term * itype | IApp of ityped_term * ityped_term * itype | IPair of ityped_term * ityped_term * itype | ILet of id * id * ityped_term * ityped_term * itype | IInjL of ityped_term * itype | IInjR of ityped_term * itype | IMatch of ityped_term * (id * ityped_term) * (id * ityped_term) * itype | ILetRec of id * ityped_term * ityped_term * itype let fresh_tyvar = let counter = ref 0 in let body () = counter := !counter + 1; !counter in body let rec string_of_iterm = function | IConst (c, ty) -> Printf.sprintf "(%s : %s)" (string_of_const c) (string_of_itype ty) | IVar (id, ty) -> Printf.sprintf "(%s : %s)" id (string_of_itype ty) | ITuple0 ty -> Printf.sprintf "(* : %s)" (string_of_itype ty) | IAbst (id, t, ty) -> Printf.sprintf "((lam %s . %s) : %s)" id (string_of_iterm t) (string_of_itype ty) | IApp (t1, t2, ty) -> Printf.sprintf "(%s %s : %s)" (string_of_iterm t1) (string_of_iterm t2) (string_of_itype ty) | IPair (t1, t2, ty) -> Printf.sprintf "(<%s, %s> : %s)" (string_of_iterm t1) (string_of_iterm t2) (string_of_itype ty) | ILet (x, y, t1, t2, ty) -> Printf.sprintf "(let <%s, %s> = %s in %s) : %s" x y (string_of_iterm t1) (string_of_iterm t2) (string_of_itype ty) | IInjL (t, ty) -> (match t with | ITuple0 _ -> Printf.sprintf "(1 : %s)" (string_of_itype ty) | t -> Printf.sprintf "(injl(%s) : %s)" (string_of_iterm t) (string_of_itype ty)) | IInjR (t, ty) -> (match t with | ITuple0 _ -> Printf.sprintf "(0 : %s)" (string_of_itype ty) | t -> Printf.sprintf "(injr(%s) : %s)" (string_of_iterm t) (string_of_itype ty)) | IMatch (t1, (x, t2), (y, t3), ty) -> Printf.sprintf "(match %s with %s -> %s | %s -> %s) : %s" (string_of_iterm t1) x (string_of_iterm t2) y (string_of_iterm t3) (string_of_itype ty) | ILetRec (f, t1, t2, ty) -> Printf.sprintf "(let rec %s = %s in %s) : %s" f (string_of_iterm t1) (string_of_iterm t2) (string_of_itype ty) let ity_const = function | New -> ITyFun (itybit, ITyQbit) | Meas -> ITyFun (ITyQbit, itybit) | _ -> failwith "Not implemented" let rec ity_infer tyenv = function | Const c -> empty_subst, ity_const c, IConst (c, ity_const c) | Var id -> empty_subst, Environment.lookup tyenv id, IVar (id, Environment.lookup tyenv id) | Tuple0 -> empty_subst, ITySingleton, ITuple0 ITySingleton | Abst (id, body) -> let tyarg = ITyVar (fresh_tyvar ()) in let tyenv = Environment.extend tyenv id tyarg in let s, tybody, ibody = ity_infer tyenv body in let ty = ITyFun (subst_type s tyarg, tybody) in s, ty, IAbst (id, ibody, ty) | App (t1, t2) -> let s1, tyf, it1 = ity_infer tyenv t1 in let s2, tyarg, it2 = ity_infer tyenv t2 in let tybody = ITyVar (fresh_tyvar ()) in let s = unify (merge_subst s1 s2) [tyf, ITyFun (tyarg, tybody)] in let ty = subst_type s tybody in s, ty, IApp (it1, it2, ty) | Pair (t1, t2) -> let s1, ty1, it1 = ity_infer tyenv t1 in let s2, ty2, it2 = ity_infer tyenv t2 in merge_subst s1 s2, ITyProd (ty1, ty2), IPair (it1, it2, ITyProd (ty1, ty2)) | Let (x, y, t1, t2) -> let s1, ty1, it1 = ity_infer tyenv t1 in (match ty1 with | ITyVar a -> let fst = ITyVar (fresh_tyvar ()) in let snd = ITyVar (fresh_tyvar ()) in let tyenv = Environment.extend (Environment.extend tyenv x fst) y snd in let s2, ty2, it2 = ity_infer tyenv t2 in let s = unify (merge_subst s1 s2) [ITyVar a, ITyProd (fst, snd)] in s, subst_type s ty2, ILet (x, y, it1, it2, subst_type s ty2) | ITyProd (ty1', ty2') -> let tyenv = Environment.extend tyenv x ty1' in let tyenv = Environment.extend tyenv y ty2' in let s2, ty2, it2 = ity_infer tyenv t2 in let s = merge_subst s1 s2 in s, subst_type s ty2, ILet (x, y, it1, it2, subst_type s ty2) | _ -> raise ITypeError) | InjL t -> let s, ty, it = ity_infer tyenv t in let ty = ITySum (ty, ITyVar (fresh_tyvar ())) in s, ty, IInjL (it, ty) | InjR t -> let s, ty, it = ity_infer tyenv t in let ty = ITySum (ITyVar (fresh_tyvar ()), ty) in s, ty, IInjR (it, ty) | Match (t1, (x, t2), (y, t3)) -> let s1, ty1, it1 = ity_infer tyenv t1 in let s1, xty, yty = (match ty1 with | ITySum (xty, yty) -> s1, xty, yty | ITyVar a -> let xty = ITyVar (fresh_tyvar ()) in let yty = ITyVar (fresh_tyvar ()) in unify s1 [ITyVar a, ITySum (xty, yty)], xty, yty | _ -> raise ITypeError) in let s2, ty2, it2 = ity_infer (Environment.extend tyenv x xty) t2 in let s3, ty3, it3 = ity_infer (Environment.extend tyenv y yty) t3 in let s = unify (merge_subst s1 (merge_subst s2 s3)) [ty2, ty3] in s, subst_type s ty2, IMatch (it1, (x, it2), (y, it3), subst_type s ty2) | LetRec (f, t1, t2) -> let tyenv = Environment.extend tyenv f (ITyVar (fresh_tyvar ())) in let s1, tyf, it1 = ity_infer tyenv t1 in let s2, ty2, it2 = ity_infer tyenv t2 in let s = unify (merge_subst s1 s2) [tyf, Environment.lookup tyenv f] in s, subst_type s ty2, ILetRec (f, it1, it2, subst_type s ty2) let ity_term tyenv t = let s, _, it = ity_infer tyenv t in let rec fix_with_singleton = (function | ITyQbit -> ITyQbit | ITySingleton -> ITySingleton | ITyFun (ty1, ty2) -> ITyFun (fix_with_singleton ty1, fix_with_singleton ty2) | ITyProd (ty1, ty2) -> ITyProd (fix_with_singleton ty1, fix_with_singleton ty2) | ITySum (ty1, ty2) -> ITySum (fix_with_singleton ty1, fix_with_singleton ty2)) in let rec correct_type = (function | IConst (c, ty) -> IConst (c, fix_with_singleton (subst_type s ty)) | IVar (id, ty) -> IVar (id, fix_with_singleton (subst_type s ty)) | ITuple0 ty -> ITuple0 ty | IAbst (id, t, ty) -> IAbst (id, correct_type t, fix_with_singleton (subst_type s ty)) | IApp (t1, t2, ty) -> IApp (correct_type t1, correct_type t2, fix_with_singleton (subst_type s ty)) | IPair (t1, t2, ty) -> IPair (correct_type t1, correct_type t2, fix_with_singleton (subst_type s ty)) | ILet (x, y, t1, t2, ty) -> ILet (x, y, correct_type t1, correct_type t2, fix_with_singleton (subst_type s ty)) | IInjL (t, ty) -> IInjL (correct_type t, fix_with_singleton (subst_type s ty)) | IInjR (t, ty) -> IInjR (correct_type t, fix_with_singleton (subst_type s ty)) | IMatch (t1, (x, t2), (y, t3), ty) -> IMatch (correct_type t1, (x, correct_type t2), (y, correct_type t3), fix_with_singleton (subst_type s ty)) | ILetRec (f, t1, t2, ty) -> ILetRec (f, correct_type t1, correct_type t2, fix_with_singleton (subst_type s ty))) in correct_type it
c7e690ab27a36aa46b350f7c5219d4bd06c45a36457c6d10dc09fda7577939f3
Timothy-G-Griffin/cc_cl_cam_ac_uk
interp_2.ml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Compiler Construction 2016 Computer Laboratory University of Cambridge ( ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Compiler Construction 2016 Computer Laboratory University of Cambridge Timothy G. Griffin () *****************************************) (* Interpreter 2. A high-level stack-oriented abstract machine with compiler. What do I mean by "high-level"? ---Code is still tree-structured. ---Complex values are pushed onto value stack. ---Slang state (heap) used only for references. ---Code is maintained on a code stack. ---Program variables contained in code. *) open Ast let complain = Errors.complain type address = int type var = string type value = | REF of address | INT of int | BOOL of bool | UNIT | PAIR of value * value | INL of value | INR of value | CLOSURE of closure | REC_CLOSURE of code and closure = code * env and instruction = | PUSH of value | LOOKUP of var | UNARY of unary_oper | OPER of oper | ASSIGN | SWAP | POP | BIND of var | FST | SND | DEREF | APPLY | MK_PAIR | MK_INL | MK_INR | MK_REF | MK_CLOSURE of code | MK_REC of var * code | TEST of code * code | CASE of code * code | WHILE of code * code and code = instruction list and binding = var * value and env = binding list type env_or_value = EV of env | V of value type env_value_stack = env_or_value list (* This is the the slang program state --- that is, values for references *) (* It is an array of referenced values together with next unallocated address *) type state = (value array) * int type interp_state = code * env_value_stack * state (* Printing *) let string_of_list sep f l = let rec aux f = function | [] -> "" | [t] -> (f t) | t :: rest -> (f t) ^ sep ^ (aux f rest) in "[" ^ (aux f l) ^ "]" let rec string_of_value = function | REF a -> "REF(" ^ (string_of_int a) ^ ")" | BOOL b -> string_of_bool b | INT n -> string_of_int n | UNIT -> "UNIT" | PAIR(v1, v2) -> "(" ^ (string_of_value v1) ^ ", " ^ (string_of_value v2) ^ ")" | INL v -> "inl(" ^ (string_of_value v) ^ ")" | INR v -> "inr(" ^ (string_of_value v) ^ ")" | CLOSURE(cl) -> "CLOSURE(" ^ (string_of_closure cl) ^ ")" | REC_CLOSURE(c) -> "REC_CLOSURE(" ^ (string_of_code c) ^ ")" and string_of_closure (c, env) = "(" ^ (string_of_code c) ^ ", " ^ (string_of_env env) ^ ")" and string_of_env env = string_of_list ",\n " string_of_binding env and string_of_binding (x, v) = "(" ^ x ^ ", " ^ (string_of_value v) ^ ")" and string_of_instruction = function | UNARY op -> "UNARY " ^ (string_of_uop op) | OPER op -> "OPER " ^ (string_of_bop op) | MK_PAIR -> "MK_PAIR" | FST -> "FST" | SND -> "SND" | MK_INL -> "MK_INL" | MK_INR -> "MK_INR" | MK_REF -> "MK_REF" | PUSH v -> "PUSH " ^ (string_of_value v) | LOOKUP x -> "LOOKUP " ^ x | TEST(c1, c2) -> "TEST(" ^ (string_of_code c1) ^ ", " ^ (string_of_code c2) ^ ")" | CASE(c1, c2) -> "CASE(" ^ (string_of_code c1) ^ ", " ^ (string_of_code c2) ^ ")" | WHILE(c1, c2) -> "WHILE(" ^ (string_of_code c1) ^ ", " ^ (string_of_code c2) ^ ")" | APPLY -> "APPLY" | BIND x -> "BIND " ^ x | SWAP -> "SWAP" | POP -> "POP" | DEREF -> "DEREF" | ASSIGN -> "ASSIGN" | MK_CLOSURE c -> "MK_CLOSURE(" ^ (string_of_code c) ^ ")" | MK_REC(f, c) -> "MK_REC(" ^ f ^ ", " ^ (string_of_code c) ^ ")" and string_of_code c = string_of_list ";\n " string_of_instruction c let string_of_env_or_value = function | EV env -> "EV " ^ (string_of_env env) | V v -> "V " ^ (string_of_value v) let string_of_env_value_stack = string_of_list ";\n " string_of_env_or_value let string_of_state (heap, i) = let rec aux k = if i < k then "" else (string_of_int k) ^ " -> " ^ (string_of_value (heap.(k))) ^ "\n" ^ (aux (k+1)) in if i = 0 then "" else "\nHeap = \n" ^ (aux 0) let string_of_interp_state (c, evs, s) = "\nCode Stack = \n" ^ (string_of_code c) ^ "\nEnv/Value Stack = \n" ^ (string_of_env_value_stack evs) ^ (string_of_state(s)) (* The "MACHINE" *) (* allocate a new location in the heap and give it value v *) let allocate (heap, i) v = if i < Option.heap_max then let _ = heap.(i) <- v in (i, (heap, i+1)) else complain "runtime error: heap kaput" let deref (heap, _) a = heap.(a) let assign (heap, i) a v = let _ = heap.(a) <- v in (heap, i) (* update : (env * binding) -> env *) let update(env, (x, v)) = (x, v) :: env let mk_fun(c, env) = CLOSURE(c, env) let mk_rec(f, c, env) = CLOSURE(c, (f, REC_CLOSURE(c))::env) in interp_0 : interpret(LetRecFun(f , ( x , body ) , e ) , env ) = let rec = if g = f then FUN ( fun v - > interpret(body , update(new_env , ( x , v ) ) ) ) else env g in interpret(e , new_env , store ) = env x ( fun v - > interpret(body , update(new_env , ( x , v ) ) ) ) lookup ( env1 @ [ ( f , cl1 ) ] @ evn2 , f ) = CLOSURE ( false , ( x , body , ( f , cl2 ) : : env2 ) ) in interp_0: interpret(LetRecFun(f, (x, body), e), env) = let rec new_env g = if g = f then FUN (fun v -> interpret(body, update(new_env, (x, v)))) else env g in interpret(e, new_env, store) new_env x = env x new_env f = FUN (fun v -> interpret(body, update(new_env, (x, v)))) lookup (env1 @ [(f, cl1)] @ evn2, f) = CLOSURE (false, (x, body, (f, cl2) :: env2)) *) let lookup_opt (env, x) = let rec aux = function | [] -> None | (y, v) :: rest -> if x = y then Some(match v with | REC_CLOSURE(body) -> mk_rec(x, body, rest) | _ -> v) else aux rest in aux env let rec search (evs, x) = match evs with | [] -> complain (x ^ " is not defined!\n") | (V _) :: rest -> search (rest, x) | (EV env) :: rest -> (match lookup_opt(env, x) with | None -> search (rest, x) | Some v -> v ) let rec evs_to_env = function | [] -> [] | (V _) :: rest -> evs_to_env rest | (EV env) :: rest -> env @ (evs_to_env rest) let readint () = let _ = print_string "input> " in read_int() let do_unary = function | (NOT, BOOL m) -> BOOL (not m) | (NEG, INT m) -> INT (-m) | (READ, UNIT) -> INT (readint()) | (op, _) -> complain ("malformed unary operator: " ^ (string_of_unary_oper op)) let do_oper = function | (AND, BOOL m, BOOL n) -> BOOL (m && n) | (OR, BOOL m, BOOL n) -> BOOL (m || n) | (EQB, BOOL m, BOOL n) -> BOOL (m = n) | (LT, INT m, INT n) -> BOOL (m < n) | (EQI, INT m, INT n) -> BOOL (m = n) | (ADD, INT m, INT n) -> INT (m + n) | (SUB, INT m, INT n) -> INT (m - n) | (MUL, INT m, INT n) -> INT (m * n) | (DIV, INT m, INT n) -> INT (m / n) | (op, _, _) -> complain ("malformed binary operator: " ^ (string_of_oper op)) (* val step : interp_state -> interp_state = (code * env_value_stack * state) -> (code * env_value_stack * state) *) let step = function (* (code stack, value/env stack, state) -> (code stack, value/env stack, state) *) | ((PUSH v) :: ds, evs, s) -> (ds, (V v) :: evs, s) | (POP :: ds, e :: evs, s) -> (ds, evs, s) | (SWAP :: ds, e1 :: e2 :: evs, s) -> (ds, e2 :: e1 :: evs, s) | ((BIND x) :: ds, (V v) :: evs, s) -> (ds, EV([(x, v)]) :: evs, s) | ((LOOKUP x) :: ds, evs, s) -> (ds, V(search(evs, x)) :: evs, s) | ((UNARY op) :: ds, (V v) :: evs, s) -> (ds, V(do_unary(op, v)) :: evs, s) | ((OPER op) :: ds, (V v2) :: (V v1) :: evs, s) -> (ds, V(do_oper(op, v1, v2)) :: evs, s) | (MK_PAIR :: ds, (V v2) :: (V v1) :: evs, s) -> (ds, V(PAIR(v1, v2)) :: evs, s) | (FST :: ds, V(PAIR (v, _)) :: evs, s) -> (ds, (V v) :: evs, s) | (SND :: ds, V(PAIR (_, v)) :: evs, s) -> (ds, (V v) :: evs, s) | (MK_INL :: ds, (V v) :: evs, s) -> (ds, V(INL v) :: evs, s) | (MK_INR :: ds, (V v) :: evs, s) -> (ds, V(INR v) :: evs, s) | (CASE (c1, _) :: ds, V(INL v)::evs, s) -> (c1 @ ds, (V v) :: evs, s) | (CASE ( _, c2) :: ds, V(INR v)::evs, s) -> (c2 @ ds, (V v) :: evs, s) | ((TEST(c1, c2)) :: ds, V(BOOL true) :: evs, s) -> (c1 @ ds, evs, s) | ((TEST(c1, c2)) :: ds, V(BOOL false) :: evs, s) -> (c2 @ ds, evs, s) | (ASSIGN :: ds, (V v) :: (V (REF a)) :: evs, s) -> (ds, V(UNIT) :: evs, assign s a v) | (DEREF :: ds, (V (REF a)) :: evs, s) -> (ds, V(deref s a) :: evs, s) | (MK_REF :: ds, (V v) :: evs, s) -> let (a, s') = allocate s v in (ds, V(REF a) :: evs, s') | ((WHILE(c1, c2)) :: ds,V(BOOL false) :: evs, s) -> (ds, V(UNIT) :: evs, s) | ((WHILE(c1, c2)) :: ds, V(BOOL true) :: evs, s) -> (c2 @ [POP] @ c1 @ [WHILE(c1, c2)] @ ds, evs, s) | ((MK_CLOSURE c) :: ds, evs, s) -> (ds, V(mk_fun(c, evs_to_env evs)) :: evs, s) | (MK_REC(f, c) :: ds, evs, s) -> (ds, V(mk_rec(f, c, evs_to_env evs)) :: evs, s) | (APPLY :: ds, V(CLOSURE (c, env)) :: (V v) :: evs, s) -> (c @ ds, (V v) :: (EV env) :: evs, s) | state -> complain ("step : bad state = " ^ (string_of_interp_state state) ^ "\n") let rec driver n state = let _ = if Option.verbose then print_string ("\nState " ^ (string_of_int n) ^ " : " ^ (string_of_interp_state state) ^ "\n") else () in match state with | ([], [V v], s) -> (v, s) | _ -> driver (n + 1) (step state) A BIND will leave an env on stack . This gets rid of it . This gets rid of it. *) let leave_scope = [SWAP; POP] (* val compile : expr -> code *) let rec compile = function | Unit -> [PUSH UNIT] | Integer n -> [PUSH (INT n)] | Boolean b -> [PUSH (BOOL b)] | Var x -> [LOOKUP x] | UnaryOp(op, e) -> (compile e) @ [UNARY op] | Op(e1, op, e2) -> (compile e1) @ (compile e2) @ [OPER op] | Pair(e1, e2) -> (compile e1) @ (compile e2) @ [MK_PAIR] | Fst e -> (compile e) @ [FST] | Snd e -> (compile e) @ [SND] | Inl e -> (compile e) @ [MK_INL] | Inr e -> (compile e) @ [MK_INR] | Case(e, (x1, e1), (x2, e2)) -> (compile e) @ [CASE((BIND x1) :: (compile e1) @ leave_scope, (BIND x2) :: (compile e2) @ leave_scope)] | If(e1, e2, e3) -> (compile e1) @ [TEST(compile e2, compile e3)] | Seq [] -> [] | Seq [e] -> compile e | Seq (e ::rest) -> (compile e) @ [POP] @ (compile (Seq rest)) | Ref e -> (compile e) @ [MK_REF] | Deref e -> (compile e) @ [DEREF] | While(e1, e2) -> let cl = compile e1 in cl @ [WHILE(cl, compile e2)] | Assign(e1, e2) -> (compile e1) @ (compile e2) @ [ASSIGN] I chose to evaluate arg first @ (compile e1) @ [APPLY; SWAP; POP] (* get rid of env left on stack *) | Lambda(x, e) -> [MK_CLOSURE((BIND x) :: (compile e) @ leave_scope)] | LetFun(f, (x, body), e) -> (MK_CLOSURE((BIND x) :: (compile body) @ leave_scope)) :: (BIND f) :: (compile e) @ leave_scope | LetRecFun(f, (x, body), e) -> (MK_REC(f, (BIND x) :: (compile body) @ leave_scope)) :: (BIND f) :: (compile e) @ leave_scope The initial Slang state is the Slang state : all locations contain 0 let initial_state = (Array.make Option.heap_max (INT 0), 0) let initial_env = [] (* interpret : expr -> (value * state) *) let interpret e = let c = compile e in let _ = if Option.verbose then print_string("Compile code =\n" ^ (string_of_code c) ^ "\n") else () in driver 1 (c, initial_env, initial_state)
null
https://raw.githubusercontent.com/Timothy-G-Griffin/cc_cl_cam_ac_uk/aabaf64c997301ea69060a1b69e915b9d1031573/slang/interp_2.ml
ocaml
Interpreter 2. A high-level stack-oriented abstract machine with compiler. What do I mean by "high-level"? ---Code is still tree-structured. ---Complex values are pushed onto value stack. ---Slang state (heap) used only for references. ---Code is maintained on a code stack. ---Program variables contained in code. This is the the slang program state --- that is, values for references It is an array of referenced values together with next unallocated address Printing The "MACHINE" allocate a new location in the heap and give it value v update : (env * binding) -> env val step : interp_state -> interp_state = (code * env_value_stack * state) -> (code * env_value_stack * state) (code stack, value/env stack, state) -> (code stack, value/env stack, state) val compile : expr -> code get rid of env left on stack interpret : expr -> (value * state)
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Compiler Construction 2016 Computer Laboratory University of Cambridge ( ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Compiler Construction 2016 Computer Laboratory University of Cambridge Timothy G. Griffin () *****************************************) open Ast let complain = Errors.complain type address = int type var = string type value = | REF of address | INT of int | BOOL of bool | UNIT | PAIR of value * value | INL of value | INR of value | CLOSURE of closure | REC_CLOSURE of code and closure = code * env and instruction = | PUSH of value | LOOKUP of var | UNARY of unary_oper | OPER of oper | ASSIGN | SWAP | POP | BIND of var | FST | SND | DEREF | APPLY | MK_PAIR | MK_INL | MK_INR | MK_REF | MK_CLOSURE of code | MK_REC of var * code | TEST of code * code | CASE of code * code | WHILE of code * code and code = instruction list and binding = var * value and env = binding list type env_or_value = EV of env | V of value type env_value_stack = env_or_value list type state = (value array) * int type interp_state = code * env_value_stack * state let string_of_list sep f l = let rec aux f = function | [] -> "" | [t] -> (f t) | t :: rest -> (f t) ^ sep ^ (aux f rest) in "[" ^ (aux f l) ^ "]" let rec string_of_value = function | REF a -> "REF(" ^ (string_of_int a) ^ ")" | BOOL b -> string_of_bool b | INT n -> string_of_int n | UNIT -> "UNIT" | PAIR(v1, v2) -> "(" ^ (string_of_value v1) ^ ", " ^ (string_of_value v2) ^ ")" | INL v -> "inl(" ^ (string_of_value v) ^ ")" | INR v -> "inr(" ^ (string_of_value v) ^ ")" | CLOSURE(cl) -> "CLOSURE(" ^ (string_of_closure cl) ^ ")" | REC_CLOSURE(c) -> "REC_CLOSURE(" ^ (string_of_code c) ^ ")" and string_of_closure (c, env) = "(" ^ (string_of_code c) ^ ", " ^ (string_of_env env) ^ ")" and string_of_env env = string_of_list ",\n " string_of_binding env and string_of_binding (x, v) = "(" ^ x ^ ", " ^ (string_of_value v) ^ ")" and string_of_instruction = function | UNARY op -> "UNARY " ^ (string_of_uop op) | OPER op -> "OPER " ^ (string_of_bop op) | MK_PAIR -> "MK_PAIR" | FST -> "FST" | SND -> "SND" | MK_INL -> "MK_INL" | MK_INR -> "MK_INR" | MK_REF -> "MK_REF" | PUSH v -> "PUSH " ^ (string_of_value v) | LOOKUP x -> "LOOKUP " ^ x | TEST(c1, c2) -> "TEST(" ^ (string_of_code c1) ^ ", " ^ (string_of_code c2) ^ ")" | CASE(c1, c2) -> "CASE(" ^ (string_of_code c1) ^ ", " ^ (string_of_code c2) ^ ")" | WHILE(c1, c2) -> "WHILE(" ^ (string_of_code c1) ^ ", " ^ (string_of_code c2) ^ ")" | APPLY -> "APPLY" | BIND x -> "BIND " ^ x | SWAP -> "SWAP" | POP -> "POP" | DEREF -> "DEREF" | ASSIGN -> "ASSIGN" | MK_CLOSURE c -> "MK_CLOSURE(" ^ (string_of_code c) ^ ")" | MK_REC(f, c) -> "MK_REC(" ^ f ^ ", " ^ (string_of_code c) ^ ")" and string_of_code c = string_of_list ";\n " string_of_instruction c let string_of_env_or_value = function | EV env -> "EV " ^ (string_of_env env) | V v -> "V " ^ (string_of_value v) let string_of_env_value_stack = string_of_list ";\n " string_of_env_or_value let string_of_state (heap, i) = let rec aux k = if i < k then "" else (string_of_int k) ^ " -> " ^ (string_of_value (heap.(k))) ^ "\n" ^ (aux (k+1)) in if i = 0 then "" else "\nHeap = \n" ^ (aux 0) let string_of_interp_state (c, evs, s) = "\nCode Stack = \n" ^ (string_of_code c) ^ "\nEnv/Value Stack = \n" ^ (string_of_env_value_stack evs) ^ (string_of_state(s)) let allocate (heap, i) v = if i < Option.heap_max then let _ = heap.(i) <- v in (i, (heap, i+1)) else complain "runtime error: heap kaput" let deref (heap, _) a = heap.(a) let assign (heap, i) a v = let _ = heap.(a) <- v in (heap, i) let update(env, (x, v)) = (x, v) :: env let mk_fun(c, env) = CLOSURE(c, env) let mk_rec(f, c, env) = CLOSURE(c, (f, REC_CLOSURE(c))::env) in interp_0 : interpret(LetRecFun(f , ( x , body ) , e ) , env ) = let rec = if g = f then FUN ( fun v - > interpret(body , update(new_env , ( x , v ) ) ) ) else env g in interpret(e , new_env , store ) = env x ( fun v - > interpret(body , update(new_env , ( x , v ) ) ) ) lookup ( env1 @ [ ( f , cl1 ) ] @ evn2 , f ) = CLOSURE ( false , ( x , body , ( f , cl2 ) : : env2 ) ) in interp_0: interpret(LetRecFun(f, (x, body), e), env) = let rec new_env g = if g = f then FUN (fun v -> interpret(body, update(new_env, (x, v)))) else env g in interpret(e, new_env, store) new_env x = env x new_env f = FUN (fun v -> interpret(body, update(new_env, (x, v)))) lookup (env1 @ [(f, cl1)] @ evn2, f) = CLOSURE (false, (x, body, (f, cl2) :: env2)) *) let lookup_opt (env, x) = let rec aux = function | [] -> None | (y, v) :: rest -> if x = y then Some(match v with | REC_CLOSURE(body) -> mk_rec(x, body, rest) | _ -> v) else aux rest in aux env let rec search (evs, x) = match evs with | [] -> complain (x ^ " is not defined!\n") | (V _) :: rest -> search (rest, x) | (EV env) :: rest -> (match lookup_opt(env, x) with | None -> search (rest, x) | Some v -> v ) let rec evs_to_env = function | [] -> [] | (V _) :: rest -> evs_to_env rest | (EV env) :: rest -> env @ (evs_to_env rest) let readint () = let _ = print_string "input> " in read_int() let do_unary = function | (NOT, BOOL m) -> BOOL (not m) | (NEG, INT m) -> INT (-m) | (READ, UNIT) -> INT (readint()) | (op, _) -> complain ("malformed unary operator: " ^ (string_of_unary_oper op)) let do_oper = function | (AND, BOOL m, BOOL n) -> BOOL (m && n) | (OR, BOOL m, BOOL n) -> BOOL (m || n) | (EQB, BOOL m, BOOL n) -> BOOL (m = n) | (LT, INT m, INT n) -> BOOL (m < n) | (EQI, INT m, INT n) -> BOOL (m = n) | (ADD, INT m, INT n) -> INT (m + n) | (SUB, INT m, INT n) -> INT (m - n) | (MUL, INT m, INT n) -> INT (m * n) | (DIV, INT m, INT n) -> INT (m / n) | (op, _, _) -> complain ("malformed binary operator: " ^ (string_of_oper op)) let step = function | ((PUSH v) :: ds, evs, s) -> (ds, (V v) :: evs, s) | (POP :: ds, e :: evs, s) -> (ds, evs, s) | (SWAP :: ds, e1 :: e2 :: evs, s) -> (ds, e2 :: e1 :: evs, s) | ((BIND x) :: ds, (V v) :: evs, s) -> (ds, EV([(x, v)]) :: evs, s) | ((LOOKUP x) :: ds, evs, s) -> (ds, V(search(evs, x)) :: evs, s) | ((UNARY op) :: ds, (V v) :: evs, s) -> (ds, V(do_unary(op, v)) :: evs, s) | ((OPER op) :: ds, (V v2) :: (V v1) :: evs, s) -> (ds, V(do_oper(op, v1, v2)) :: evs, s) | (MK_PAIR :: ds, (V v2) :: (V v1) :: evs, s) -> (ds, V(PAIR(v1, v2)) :: evs, s) | (FST :: ds, V(PAIR (v, _)) :: evs, s) -> (ds, (V v) :: evs, s) | (SND :: ds, V(PAIR (_, v)) :: evs, s) -> (ds, (V v) :: evs, s) | (MK_INL :: ds, (V v) :: evs, s) -> (ds, V(INL v) :: evs, s) | (MK_INR :: ds, (V v) :: evs, s) -> (ds, V(INR v) :: evs, s) | (CASE (c1, _) :: ds, V(INL v)::evs, s) -> (c1 @ ds, (V v) :: evs, s) | (CASE ( _, c2) :: ds, V(INR v)::evs, s) -> (c2 @ ds, (V v) :: evs, s) | ((TEST(c1, c2)) :: ds, V(BOOL true) :: evs, s) -> (c1 @ ds, evs, s) | ((TEST(c1, c2)) :: ds, V(BOOL false) :: evs, s) -> (c2 @ ds, evs, s) | (ASSIGN :: ds, (V v) :: (V (REF a)) :: evs, s) -> (ds, V(UNIT) :: evs, assign s a v) | (DEREF :: ds, (V (REF a)) :: evs, s) -> (ds, V(deref s a) :: evs, s) | (MK_REF :: ds, (V v) :: evs, s) -> let (a, s') = allocate s v in (ds, V(REF a) :: evs, s') | ((WHILE(c1, c2)) :: ds,V(BOOL false) :: evs, s) -> (ds, V(UNIT) :: evs, s) | ((WHILE(c1, c2)) :: ds, V(BOOL true) :: evs, s) -> (c2 @ [POP] @ c1 @ [WHILE(c1, c2)] @ ds, evs, s) | ((MK_CLOSURE c) :: ds, evs, s) -> (ds, V(mk_fun(c, evs_to_env evs)) :: evs, s) | (MK_REC(f, c) :: ds, evs, s) -> (ds, V(mk_rec(f, c, evs_to_env evs)) :: evs, s) | (APPLY :: ds, V(CLOSURE (c, env)) :: (V v) :: evs, s) -> (c @ ds, (V v) :: (EV env) :: evs, s) | state -> complain ("step : bad state = " ^ (string_of_interp_state state) ^ "\n") let rec driver n state = let _ = if Option.verbose then print_string ("\nState " ^ (string_of_int n) ^ " : " ^ (string_of_interp_state state) ^ "\n") else () in match state with | ([], [V v], s) -> (v, s) | _ -> driver (n + 1) (step state) A BIND will leave an env on stack . This gets rid of it . This gets rid of it. *) let leave_scope = [SWAP; POP] let rec compile = function | Unit -> [PUSH UNIT] | Integer n -> [PUSH (INT n)] | Boolean b -> [PUSH (BOOL b)] | Var x -> [LOOKUP x] | UnaryOp(op, e) -> (compile e) @ [UNARY op] | Op(e1, op, e2) -> (compile e1) @ (compile e2) @ [OPER op] | Pair(e1, e2) -> (compile e1) @ (compile e2) @ [MK_PAIR] | Fst e -> (compile e) @ [FST] | Snd e -> (compile e) @ [SND] | Inl e -> (compile e) @ [MK_INL] | Inr e -> (compile e) @ [MK_INR] | Case(e, (x1, e1), (x2, e2)) -> (compile e) @ [CASE((BIND x1) :: (compile e1) @ leave_scope, (BIND x2) :: (compile e2) @ leave_scope)] | If(e1, e2, e3) -> (compile e1) @ [TEST(compile e2, compile e3)] | Seq [] -> [] | Seq [e] -> compile e | Seq (e ::rest) -> (compile e) @ [POP] @ (compile (Seq rest)) | Ref e -> (compile e) @ [MK_REF] | Deref e -> (compile e) @ [DEREF] | While(e1, e2) -> let cl = compile e1 in cl @ [WHILE(cl, compile e2)] | Assign(e1, e2) -> (compile e1) @ (compile e2) @ [ASSIGN] I chose to evaluate arg first @ (compile e1) @ [APPLY; | Lambda(x, e) -> [MK_CLOSURE((BIND x) :: (compile e) @ leave_scope)] | LetFun(f, (x, body), e) -> (MK_CLOSURE((BIND x) :: (compile body) @ leave_scope)) :: (BIND f) :: (compile e) @ leave_scope | LetRecFun(f, (x, body), e) -> (MK_REC(f, (BIND x) :: (compile body) @ leave_scope)) :: (BIND f) :: (compile e) @ leave_scope The initial Slang state is the Slang state : all locations contain 0 let initial_state = (Array.make Option.heap_max (INT 0), 0) let initial_env = [] let interpret e = let c = compile e in let _ = if Option.verbose then print_string("Compile code =\n" ^ (string_of_code c) ^ "\n") else () in driver 1 (c, initial_env, initial_state)
d1e14efbefdce5efc30408511e339f05fcf5ad1e693477e1ec8f53690f3bfa25
mitchellwrosen/boston-haskell-arcade
BlimpBoy.hs
# LANGUAGE TemplateHaskell # module Bha.Game.Impl.BlimpBoy ( game ) where import Bha.Elm.Prelude import qualified Data.Set as Set -- TODO Blimp boy - enemies that fire upwards -- TODO Blimp boy - enemy blimps that fire downwards -- TODO Blimp boy - levels -------------------------------------------------------------------------------- Model -------------------------------------------------------------------------------- blimpx = 35 :: X blimprow = 5 :: Row blimpvel = 3 :: Vel castlecol = 40 :: Col enemycol = 0 :: X enemyrow = 20 :: Row enemyvel = 7 :: Vel pebblevel = 24 :: Vel pebbletimer = 1.0 :: Seconds bombvel = 18 :: Vel bombtimer = 3.0 :: Seconds type Row = Int type Col = Int type X = Double type Y = Double type Vel = Double data Model = Model { blimp :: X , blimpVel :: Vel , enemies :: (Set X) , pebble :: (Set (X, Y)) , numPebbles :: Int , maxNumPebbles :: Int , nextPebble :: Seconds , bombs :: (Set (X, Y)) , numBombs :: Int , maxNumBombs :: Int , nextBomb :: Seconds , health :: Int , money :: Int } deriving stock (Generic, Show) init :: Int -> Int -> Init Void Model init _ _ = pure Model { blimp = blimpx , blimpVel = -blimpvel , enemies = mempty , pebble = mempty , numPebbles = 1 , maxNumPebbles = 2 , nextPebble = pebbletimer , bombs = mempty , numBombs = 1 , maxNumBombs = 2 , nextBomb = bombtimer , health = 50 , money = 0 } -------------------------------------------------------------------------------- -- Update -------------------------------------------------------------------------------- update :: Input Void -> Update Model Void () update = \case Tick dt -> tickUpdate dt Key KeyArrowLeft -> #blimpVel %= negate . abs Key KeyArrowRight -> #blimpVel %= abs Key (KeyChar 'p') -> do money <- use #money maxNumPebbles <- use #maxNumPebbles when (money >= 1 && maxNumPebbles < 5) $ do #money %= subtract 1 #maxNumPebbles %= (+1) Key (KeyChar 'b') -> do money <- use #money maxNumBombs <- use #maxNumBombs when (money >= 3 && maxNumBombs < 5) $ do #money %= subtract 3 #maxNumBombs %= (+1) Key KeySpace -> do supply <- use #numPebbles blimpcol <- use #blimp #pebble %= if supply >= 1 then Set.insert (blimpcol + 0.5, fromIntegral blimprow + 0.5) else id #numPebbles %= (max 0 . subtract 1) Key (KeyChar '1') -> do supply <- use #numBombs blimpcol <- use #blimp #bombs %= if supply >= 1 then Set.insert (blimpcol + 0.5, fromIntegral blimprow + 0.5) else id #numBombs %= (max 0 . subtract 1) Key KeyEsc -> empty _ -> pure () tickUpdate :: Seconds -> Update Model Void () tickUpdate dt = do isCastleAlive blimpDrifts dt enemiesAdvance dt stuffFallsDownward dt removePebbledEnemies removeBombedEnemies enemiesHitCastle possiblySpawnNewEnemy updatePebbleSupply dt updateBombSupply dt isCastleAlive :: Update Model Void () isCastleAlive = do health <- use #health guard (health > 0) blimpDrifts :: Seconds -> Update Model Void () blimpDrifts dt = do blimpVel <- use #blimpVel #blimp %= max 1 . min 55 . \x -> x + blimpVel * realToFrac dt enemiesAdvance :: Seconds -> Update Model Void () enemiesAdvance dt = #enemies %= Set.map (\x -> x + enemyvel * realToFrac dt) stuffFallsDownward :: Seconds -> Update Model Void () stuffFallsDownward dt = do #pebble %= Set.filter ((\y -> y <= fromIntegral enemyrow + 1) . snd) . Set.map (over _2 (\y -> y + pebblevel * realToFrac dt)) #bombs %= Set.filter ((\y -> y <= fromIntegral enemyrow + 1) . snd) . Set.map (over _2 (\y -> y + bombvel * realToFrac dt)) removePebbledEnemies :: Update Model Void () removePebbledEnemies = do pebbles <- use #pebble for_ pebbles $ \(pebblex, pebbley) -> do when (floor pebbley == enemyrow) $ do enemies <- use #enemies let (dead, alive) = Set.partition (\x -> x >= pebblex - 0.5 && x <= pebblex + 0.5) enemies #money %= (+ length dead) #enemies .= alive removeBombedEnemies :: Update Model Void () removeBombedEnemies = do bombs <- use #bombs for_ bombs $ \(bombx, bomby) -> do when (floor bomby == enemyrow) $ do enemies <- use #enemies let (dead, alive) = Set.partition (\x -> x >= bombx - 1.5 && x <= bombx + 1.5) enemies #enemies .= alive #money %= (+ length dead) enemiesHitCastle :: Update Model Void () enemiesHitCastle = do enemies <- use #enemies let (splat, walking) = Set.partition (\x -> floor x >= castlecol) enemies #enemies .= walking #health %= subtract (length splat) possiblySpawnNewEnemy :: Update Model Void () possiblySpawnNewEnemy = do pct <- randomPct when (pct > 0.99) (#enemies %= Set.insert enemycol) updatePebbleSupply :: Seconds -> Update Model Void () updatePebbleSupply dt = do nextPebbleTimer <- use #nextPebble maxNumPebbles <- use #maxNumPebbles #numPebbles %= if nextPebbleTimer <= 0 then min maxNumPebbles . (+1) else id #nextPebble %= \timer -> if timer <= 0 then timer - dt + pebbletimer else timer - dt updateBombSupply :: Seconds -> Update Model Void () updateBombSupply dt = do nextBombTimer <- use #nextBomb maxNumBombs <- use #maxNumBombs #numBombs %= if nextBombTimer <= 0 then min maxNumBombs . (+1) else id #nextBomb %= \timer -> if timer <= 0 then timer - dt + bombtimer else timer - dt -------------------------------------------------------------------------------- -- View -------------------------------------------------------------------------------- view :: Model -> Scene view model = Scene cells NoCursor where cells :: Cells cells = mconcat [ renderSky , renderGround , renderCastle , renderBlimp (model ^. #blimp) , renderPebbles (model ^. #pebble) , renderBombs (model ^. #bombs) , renderEnemies (model ^. #enemies) , renderMoney (model ^. #money) , renderNumPebbles (model ^. #numPebbles) , renderNumBombs (model ^. #numBombs) , renderHealth (model ^. #health) ] renderSky = rect 0 0 60 (enemyrow+1) blue renderGround = rect 0 (enemyrow+1) 60 10 green renderCastle = rect castlecol 5 10 (enemyrow - 5 + 1) 253 renderBlimp :: X -> Cells renderBlimp (round -> col) = rect (col-1) (blimprow-1) 3 2 yellow renderPebbles :: Set (X, Y) -> Cells renderPebbles = foldMap (\(floor -> c, floor -> r) -> set c r (Cell '‧' black blue)) . Set.toList renderBombs :: Set (X, Y) -> Cells renderBombs = foldMap render . Set.toList where render :: (X, Y) -> Cells render (floor -> c, floor -> r) = if r == enemyrow then rect (c-1) r 3 1 red else set c r (Cell '•' black blue) renderEnemies :: Set X -> Cells renderEnemies = foldMap (\c -> set (round c) enemyrow (Cell '∞' black blue)) . Set.toList renderMoney :: Int -> Cells renderMoney money = text 0 (enemyrow+11) white black ("Money: " ++ show money) renderNumPebbles :: Int -> Cells renderNumPebbles pebbles = text 0 (enemyrow+12) white black ("Pebbles: " ++ replicate pebbles '‧') renderNumBombs :: Int -> Cells renderNumBombs bombs = text 0 (enemyrow+13) white black ("Bombs: " ++ replicate bombs '•') renderHealth :: Int -> Cells renderHealth health = text 0 (enemyrow+14) white black ("Health: " ++ show health) -------------------------------------------------------------------------------- -- Tick -------------------------------------------------------------------------------- tickEvery :: Model -> Maybe Seconds tickEvery _ = Just (1/30) -------------------------------------------------------------------------------- -- Subscribe -------------------------------------------------------------------------------- subscribe :: Model -> HashSet Text subscribe _ = mempty -------------------------------------------------------------------------------- -- Game -------------------------------------------------------------------------------- game :: ElmGame Model Void game = ElmGame init update view tickEvery subscribe
null
https://raw.githubusercontent.com/mitchellwrosen/boston-haskell-arcade/2e85fbc4ddd18bad520c7544572f7205ef02015f/src/Bha/Game/Impl/BlimpBoy.hs
haskell
TODO Blimp boy - enemies that fire upwards TODO Blimp boy - enemy blimps that fire downwards TODO Blimp boy - levels ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Update ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ View ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Tick ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Subscribe ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Game ------------------------------------------------------------------------------
# LANGUAGE TemplateHaskell # module Bha.Game.Impl.BlimpBoy ( game ) where import Bha.Elm.Prelude import qualified Data.Set as Set Model blimpx = 35 :: X blimprow = 5 :: Row blimpvel = 3 :: Vel castlecol = 40 :: Col enemycol = 0 :: X enemyrow = 20 :: Row enemyvel = 7 :: Vel pebblevel = 24 :: Vel pebbletimer = 1.0 :: Seconds bombvel = 18 :: Vel bombtimer = 3.0 :: Seconds type Row = Int type Col = Int type X = Double type Y = Double type Vel = Double data Model = Model { blimp :: X , blimpVel :: Vel , enemies :: (Set X) , pebble :: (Set (X, Y)) , numPebbles :: Int , maxNumPebbles :: Int , nextPebble :: Seconds , bombs :: (Set (X, Y)) , numBombs :: Int , maxNumBombs :: Int , nextBomb :: Seconds , health :: Int , money :: Int } deriving stock (Generic, Show) init :: Int -> Int -> Init Void Model init _ _ = pure Model { blimp = blimpx , blimpVel = -blimpvel , enemies = mempty , pebble = mempty , numPebbles = 1 , maxNumPebbles = 2 , nextPebble = pebbletimer , bombs = mempty , numBombs = 1 , maxNumBombs = 2 , nextBomb = bombtimer , health = 50 , money = 0 } update :: Input Void -> Update Model Void () update = \case Tick dt -> tickUpdate dt Key KeyArrowLeft -> #blimpVel %= negate . abs Key KeyArrowRight -> #blimpVel %= abs Key (KeyChar 'p') -> do money <- use #money maxNumPebbles <- use #maxNumPebbles when (money >= 1 && maxNumPebbles < 5) $ do #money %= subtract 1 #maxNumPebbles %= (+1) Key (KeyChar 'b') -> do money <- use #money maxNumBombs <- use #maxNumBombs when (money >= 3 && maxNumBombs < 5) $ do #money %= subtract 3 #maxNumBombs %= (+1) Key KeySpace -> do supply <- use #numPebbles blimpcol <- use #blimp #pebble %= if supply >= 1 then Set.insert (blimpcol + 0.5, fromIntegral blimprow + 0.5) else id #numPebbles %= (max 0 . subtract 1) Key (KeyChar '1') -> do supply <- use #numBombs blimpcol <- use #blimp #bombs %= if supply >= 1 then Set.insert (blimpcol + 0.5, fromIntegral blimprow + 0.5) else id #numBombs %= (max 0 . subtract 1) Key KeyEsc -> empty _ -> pure () tickUpdate :: Seconds -> Update Model Void () tickUpdate dt = do isCastleAlive blimpDrifts dt enemiesAdvance dt stuffFallsDownward dt removePebbledEnemies removeBombedEnemies enemiesHitCastle possiblySpawnNewEnemy updatePebbleSupply dt updateBombSupply dt isCastleAlive :: Update Model Void () isCastleAlive = do health <- use #health guard (health > 0) blimpDrifts :: Seconds -> Update Model Void () blimpDrifts dt = do blimpVel <- use #blimpVel #blimp %= max 1 . min 55 . \x -> x + blimpVel * realToFrac dt enemiesAdvance :: Seconds -> Update Model Void () enemiesAdvance dt = #enemies %= Set.map (\x -> x + enemyvel * realToFrac dt) stuffFallsDownward :: Seconds -> Update Model Void () stuffFallsDownward dt = do #pebble %= Set.filter ((\y -> y <= fromIntegral enemyrow + 1) . snd) . Set.map (over _2 (\y -> y + pebblevel * realToFrac dt)) #bombs %= Set.filter ((\y -> y <= fromIntegral enemyrow + 1) . snd) . Set.map (over _2 (\y -> y + bombvel * realToFrac dt)) removePebbledEnemies :: Update Model Void () removePebbledEnemies = do pebbles <- use #pebble for_ pebbles $ \(pebblex, pebbley) -> do when (floor pebbley == enemyrow) $ do enemies <- use #enemies let (dead, alive) = Set.partition (\x -> x >= pebblex - 0.5 && x <= pebblex + 0.5) enemies #money %= (+ length dead) #enemies .= alive removeBombedEnemies :: Update Model Void () removeBombedEnemies = do bombs <- use #bombs for_ bombs $ \(bombx, bomby) -> do when (floor bomby == enemyrow) $ do enemies <- use #enemies let (dead, alive) = Set.partition (\x -> x >= bombx - 1.5 && x <= bombx + 1.5) enemies #enemies .= alive #money %= (+ length dead) enemiesHitCastle :: Update Model Void () enemiesHitCastle = do enemies <- use #enemies let (splat, walking) = Set.partition (\x -> floor x >= castlecol) enemies #enemies .= walking #health %= subtract (length splat) possiblySpawnNewEnemy :: Update Model Void () possiblySpawnNewEnemy = do pct <- randomPct when (pct > 0.99) (#enemies %= Set.insert enemycol) updatePebbleSupply :: Seconds -> Update Model Void () updatePebbleSupply dt = do nextPebbleTimer <- use #nextPebble maxNumPebbles <- use #maxNumPebbles #numPebbles %= if nextPebbleTimer <= 0 then min maxNumPebbles . (+1) else id #nextPebble %= \timer -> if timer <= 0 then timer - dt + pebbletimer else timer - dt updateBombSupply :: Seconds -> Update Model Void () updateBombSupply dt = do nextBombTimer <- use #nextBomb maxNumBombs <- use #maxNumBombs #numBombs %= if nextBombTimer <= 0 then min maxNumBombs . (+1) else id #nextBomb %= \timer -> if timer <= 0 then timer - dt + bombtimer else timer - dt view :: Model -> Scene view model = Scene cells NoCursor where cells :: Cells cells = mconcat [ renderSky , renderGround , renderCastle , renderBlimp (model ^. #blimp) , renderPebbles (model ^. #pebble) , renderBombs (model ^. #bombs) , renderEnemies (model ^. #enemies) , renderMoney (model ^. #money) , renderNumPebbles (model ^. #numPebbles) , renderNumBombs (model ^. #numBombs) , renderHealth (model ^. #health) ] renderSky = rect 0 0 60 (enemyrow+1) blue renderGround = rect 0 (enemyrow+1) 60 10 green renderCastle = rect castlecol 5 10 (enemyrow - 5 + 1) 253 renderBlimp :: X -> Cells renderBlimp (round -> col) = rect (col-1) (blimprow-1) 3 2 yellow renderPebbles :: Set (X, Y) -> Cells renderPebbles = foldMap (\(floor -> c, floor -> r) -> set c r (Cell '‧' black blue)) . Set.toList renderBombs :: Set (X, Y) -> Cells renderBombs = foldMap render . Set.toList where render :: (X, Y) -> Cells render (floor -> c, floor -> r) = if r == enemyrow then rect (c-1) r 3 1 red else set c r (Cell '•' black blue) renderEnemies :: Set X -> Cells renderEnemies = foldMap (\c -> set (round c) enemyrow (Cell '∞' black blue)) . Set.toList renderMoney :: Int -> Cells renderMoney money = text 0 (enemyrow+11) white black ("Money: " ++ show money) renderNumPebbles :: Int -> Cells renderNumPebbles pebbles = text 0 (enemyrow+12) white black ("Pebbles: " ++ replicate pebbles '‧') renderNumBombs :: Int -> Cells renderNumBombs bombs = text 0 (enemyrow+13) white black ("Bombs: " ++ replicate bombs '•') renderHealth :: Int -> Cells renderHealth health = text 0 (enemyrow+14) white black ("Health: " ++ show health) tickEvery :: Model -> Maybe Seconds tickEvery _ = Just (1/30) subscribe :: Model -> HashSet Text subscribe _ = mempty game :: ElmGame Model Void game = ElmGame init update view tickEvery subscribe
cda861a412f1083ae15061fc5ebbf89c5d702d3dce46762c0d7654982cecfb1a
sacerdot/CovidMonitoring
server.erl
%%%--------------------------------------------------------------------- @doc Modulo server per il progetto del corso di . %%% @end %%%--------------------------------------------------------------------- -module(server). -export([start/0]). %%%------------------------------------------------------------------- %%% @doc PROTOCOLLO DI INIZIALIZZAZIONE: all'avvio si registra . %%% @end %%%------------------------------------------------------------------- start() -> global:register_name(server,self()), io:format("Io sono il server~n",[]), process_flag(trap_exit, true), update_places([]). %%%---------------------------------------------------------------------------- %%% @doc PROTOCOLLO DI MANTENIMENTO DELLA TOPOLOGIA: 1 ) Mantiene una lista dei luoghi attivi . 2 ) i , eliminandoli dalla lista questi muoiono 3 ) Risponde alle richieste ( degli utenti ) . %%% @end %%%---------------------------------------------------------------------------- update_places(PidList) -> receive {new_place, PidPlace} -> update_places([PidPlace | PidList]); {get_places, Pid} -> Pid ! {places, PidList}, update_places(PidList); {'EXIT', Pid, normal} -> io:format("Sto per rimuovere ~p dalla lista dei luoghi~n", [Pid]), update_places(PidList -- [Pid]); {'EXIT', Pid, positive} -> io:format("~p: esce perche' positivo al test~n", [Pid]), update_places(PidList); {'EXIT', Pid, quarantena} -> io:format("~p: esce perche' va in quarantena~n", [Pid]), update_places(PidList); {'EXIT', Pid, Reason} -> io:format("~p exit because ~p~n", [Pid, Reason]), update_places(PidList -- [Pid]); Other -> io:format("Messaggio inaspettato: ~p~n", [Other]), update_places(PidList) end.
null
https://raw.githubusercontent.com/sacerdot/CovidMonitoring/fe969cd51869bbe6479da509c9a6ab21d43e6d11/FabbrettiGrossi/src/server.erl
erlang
--------------------------------------------------------------------- @end --------------------------------------------------------------------- ------------------------------------------------------------------- @doc PROTOCOLLO DI INIZIALIZZAZIONE: @end ------------------------------------------------------------------- ---------------------------------------------------------------------------- @doc PROTOCOLLO DI MANTENIMENTO DELLA TOPOLOGIA: @end ----------------------------------------------------------------------------
@doc Modulo server per il progetto del corso di . -module(server). -export([start/0]). all'avvio si registra . start() -> global:register_name(server,self()), io:format("Io sono il server~n",[]), process_flag(trap_exit, true), update_places([]). 1 ) Mantiene una lista dei luoghi attivi . 2 ) i , eliminandoli dalla lista questi muoiono 3 ) Risponde alle richieste ( degli utenti ) . update_places(PidList) -> receive {new_place, PidPlace} -> update_places([PidPlace | PidList]); {get_places, Pid} -> Pid ! {places, PidList}, update_places(PidList); {'EXIT', Pid, normal} -> io:format("Sto per rimuovere ~p dalla lista dei luoghi~n", [Pid]), update_places(PidList -- [Pid]); {'EXIT', Pid, positive} -> io:format("~p: esce perche' positivo al test~n", [Pid]), update_places(PidList); {'EXIT', Pid, quarantena} -> io:format("~p: esce perche' va in quarantena~n", [Pid]), update_places(PidList); {'EXIT', Pid, Reason} -> io:format("~p exit because ~p~n", [Pid, Reason]), update_places(PidList -- [Pid]); Other -> io:format("Messaggio inaspettato: ~p~n", [Other]), update_places(PidList) end.
c80f5ebf4a28139f4c8693183ed60aca28a44261f7d43670aa37c80c70ed885c
haskell/cabal
Hpc.hs
# LANGUAGE FlexibleContexts # {-# LANGUAGE RankNTypes #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Hpc -- Copyright : Thomas Tuegel 2011 -- License : BSD3 -- -- Maintainer : -- Portability : portable -- This module provides functions for locating various HPC - related paths and -- a function for adding the necessary options to a PackageDescription to build test suites with HPC enabled . module Distribution.Simple.Hpc ( Way(..), guessWay , htmlDir , mixDir , tixDir , tixFilePath , markupPackage , markupTest ) where import Prelude () import Distribution.Compat.Prelude import Distribution.Types.UnqualComponentName import Distribution.ModuleName ( main ) import qualified Distribution.PackageDescription as PD import Distribution.PackageDescription ( Library(..) , TestSuite(..) , testModules ) import Distribution.Pretty import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..) ) import Distribution.Simple.Program ( hpcProgram , requireProgramVersion ) import Distribution.Simple.Program.Hpc ( markup, union ) import Distribution.Simple.Utils ( notice ) import Distribution.Version ( anyVersion ) import Distribution.Verbosity ( Verbosity() ) import System.Directory ( createDirectoryIfMissing, doesFileExist ) import System.FilePath -- ------------------------------------------------------------------------- -- Haskell Program Coverage data Way = Vanilla | Prof | Dyn deriving (Bounded, Enum, Eq, Read, Show) hpcDir :: FilePath -- ^ \"dist/\" prefix -> Way ^ Directory containing component 's HPC .mix files hpcDir distPref way = distPref </> "hpc" </> wayDir where wayDir = case way of Vanilla -> "vanilla" Prof -> "prof" Dyn -> "dyn" mixDir :: FilePath -- ^ \"dist/\" prefix -> Way -> FilePath -- ^ Component name ^ Directory containing test suite 's .mix files mixDir distPref way name = hpcDir distPrefBuild way </> "mix" </> name where This is a hack for HPC over test suites , needed to match the directory where HPC saves and reads .mix files when the main library of the same package is being processed , perhaps in a previous cabal run ( # 5213 ) . E.g. , may be -- @./dist-newstyle/build/x86_64-linux/ghc-9.0.1/cabal-gh5213-0.1/t/tests@ but the path where library mix files reside has two less components at the end ( @t / tests@ ) and this reduced path needs to be passed to both and @ghc@. For non - default optimization levels , the path suffix is one element longer and the extra path element needs -- to be preserved. distPrefElements = splitDirectories distPref distPrefBuild = case drop (length distPrefElements - 3) distPrefElements of ["t", _, "noopt"] -> joinPath $ take (length distPrefElements - 3) distPrefElements ++ ["noopt"] ["t", _, "opt"] -> joinPath $ take (length distPrefElements - 3) distPrefElements ++ ["opt"] [_, "t", _] -> joinPath $ take (length distPrefElements - 2) distPrefElements _ -> distPref tixDir :: FilePath -- ^ \"dist/\" prefix -> Way -> FilePath -- ^ Component name -> FilePath -- ^ Directory containing test suite's .tix files tixDir distPref way name = hpcDir distPref way </> "tix" </> name -- | Path to the .tix file containing a test suite's sum statistics. tixFilePath :: FilePath -- ^ \"dist/\" prefix -> Way -> FilePath -- ^ Component name -> FilePath -- ^ Path to test suite's .tix file tixFilePath distPref way name = tixDir distPref way name </> name <.> "tix" htmlDir :: FilePath -- ^ \"dist/\" prefix -> Way -> FilePath -- ^ Component name -> FilePath -- ^ Path to test suite's HTML markup directory htmlDir distPref way name = hpcDir distPref way </> "html" </> name -- | Attempt to guess the way the test suites in this package were compiled -- and linked with the library so the correct module interfaces are found. guessWay :: LocalBuildInfo -> Way guessWay lbi | withProfExe lbi = Prof | withDynExe lbi = Dyn | otherwise = Vanilla -- | Generate the HTML markup for a test suite. markupTest :: Verbosity -> LocalBuildInfo -> FilePath -- ^ \"dist/\" prefix -> String -- ^ Library name -> TestSuite -> Library -> IO () markupTest verbosity lbi distPref libraryName suite library = do tixFileExists <- doesFileExist $ tixFilePath distPref way $ testName' when tixFileExists $ do -- behaviour of 'markup' depends on version, so we need *a* version -- but no particular one (hpc, hpcVer, _) <- requireProgramVersion verbosity hpcProgram anyVersion (withPrograms lbi) let htmlDir_ = htmlDir distPref way testName' markup hpc hpcVer verbosity (tixFilePath distPref way testName') mixDirs htmlDir_ (exposedModules library) notice verbosity $ "Test coverage report written to " ++ htmlDir_ </> "hpc_index" <.> "html" where way = guessWay lbi testName' = unUnqualComponentName $ testName suite mixDirs = map (mixDir distPref way) [ testName', libraryName ] -- | Generate the HTML markup for all of a package's test suites. markupPackage :: Verbosity -> LocalBuildInfo -> FilePath -- ^ \"dist/\" prefix -> PD.PackageDescription -> [TestSuite] -> IO () markupPackage verbosity lbi distPref pkg_descr suites = do let tixFiles = map (tixFilePath distPref way) testNames tixFilesExist <- traverse doesFileExist tixFiles when (and tixFilesExist) $ do -- behaviour of 'markup' depends on version, so we need *a* version -- but no particular one (hpc, hpcVer, _) <- requireProgramVersion verbosity hpcProgram anyVersion (withPrograms lbi) let outFile = tixFilePath distPref way libraryName htmlDir' = htmlDir distPref way libraryName excluded = concatMap testModules suites ++ [ main ] createDirectoryIfMissing True $ takeDirectory outFile union hpc verbosity tixFiles outFile excluded markup hpc hpcVer verbosity outFile mixDirs htmlDir' included notice verbosity $ "Package coverage report written to " ++ htmlDir' </> "hpc_index.html" where way = guessWay lbi testNames = fmap (unUnqualComponentName . testName) suites mixDirs = map (mixDir distPref way) $ libraryName : testNames included = concatMap (exposedModules) $ PD.allLibraries pkg_descr libraryName = prettyShow $ PD.package pkg_descr
null
https://raw.githubusercontent.com/haskell/cabal/496d6fcc26779e754523a6cc7576aea49ef8056e/Cabal/src/Distribution/Simple/Hpc.hs
haskell
# LANGUAGE RankNTypes # --------------------------------------------------------------------------- | Module : Distribution.Simple.Hpc Copyright : Thomas Tuegel 2011 License : BSD3 Maintainer : Portability : portable a function for adding the necessary options to a PackageDescription to ------------------------------------------------------------------------- Haskell Program Coverage ^ \"dist/\" prefix ^ \"dist/\" prefix ^ Component name @./dist-newstyle/build/x86_64-linux/ghc-9.0.1/cabal-gh5213-0.1/t/tests@ to be preserved. ^ \"dist/\" prefix ^ Component name ^ Directory containing test suite's .tix files | Path to the .tix file containing a test suite's sum statistics. ^ \"dist/\" prefix ^ Component name ^ Path to test suite's .tix file ^ \"dist/\" prefix ^ Component name ^ Path to test suite's HTML markup directory | Attempt to guess the way the test suites in this package were compiled and linked with the library so the correct module interfaces are found. | Generate the HTML markup for a test suite. ^ \"dist/\" prefix ^ Library name behaviour of 'markup' depends on version, so we need *a* version but no particular one | Generate the HTML markup for all of a package's test suites. ^ \"dist/\" prefix behaviour of 'markup' depends on version, so we need *a* version but no particular one
# LANGUAGE FlexibleContexts # This module provides functions for locating various HPC - related paths and build test suites with HPC enabled . module Distribution.Simple.Hpc ( Way(..), guessWay , htmlDir , mixDir , tixDir , tixFilePath , markupPackage , markupTest ) where import Prelude () import Distribution.Compat.Prelude import Distribution.Types.UnqualComponentName import Distribution.ModuleName ( main ) import qualified Distribution.PackageDescription as PD import Distribution.PackageDescription ( Library(..) , TestSuite(..) , testModules ) import Distribution.Pretty import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..) ) import Distribution.Simple.Program ( hpcProgram , requireProgramVersion ) import Distribution.Simple.Program.Hpc ( markup, union ) import Distribution.Simple.Utils ( notice ) import Distribution.Version ( anyVersion ) import Distribution.Verbosity ( Verbosity() ) import System.Directory ( createDirectoryIfMissing, doesFileExist ) import System.FilePath data Way = Vanilla | Prof | Dyn deriving (Bounded, Enum, Eq, Read, Show) -> Way ^ Directory containing component 's HPC .mix files hpcDir distPref way = distPref </> "hpc" </> wayDir where wayDir = case way of Vanilla -> "vanilla" Prof -> "prof" Dyn -> "dyn" -> Way ^ Directory containing test suite 's .mix files mixDir distPref way name = hpcDir distPrefBuild way </> "mix" </> name where This is a hack for HPC over test suites , needed to match the directory where HPC saves and reads .mix files when the main library of the same package is being processed , perhaps in a previous cabal run ( # 5213 ) . E.g. , may be but the path where library mix files reside has two less components at the end ( @t / tests@ ) and this reduced path needs to be passed to both and @ghc@. For non - default optimization levels , the path suffix is one element longer and the extra path element needs distPrefElements = splitDirectories distPref distPrefBuild = case drop (length distPrefElements - 3) distPrefElements of ["t", _, "noopt"] -> joinPath $ take (length distPrefElements - 3) distPrefElements ++ ["noopt"] ["t", _, "opt"] -> joinPath $ take (length distPrefElements - 3) distPrefElements ++ ["opt"] [_, "t", _] -> joinPath $ take (length distPrefElements - 2) distPrefElements _ -> distPref -> Way tixDir distPref way name = hpcDir distPref way </> "tix" </> name -> Way tixFilePath distPref way name = tixDir distPref way name </> name <.> "tix" -> Way htmlDir distPref way name = hpcDir distPref way </> "html" </> name guessWay :: LocalBuildInfo -> Way guessWay lbi | withProfExe lbi = Prof | withDynExe lbi = Dyn | otherwise = Vanilla markupTest :: Verbosity -> LocalBuildInfo -> TestSuite -> Library -> IO () markupTest verbosity lbi distPref libraryName suite library = do tixFileExists <- doesFileExist $ tixFilePath distPref way $ testName' when tixFileExists $ do (hpc, hpcVer, _) <- requireProgramVersion verbosity hpcProgram anyVersion (withPrograms lbi) let htmlDir_ = htmlDir distPref way testName' markup hpc hpcVer verbosity (tixFilePath distPref way testName') mixDirs htmlDir_ (exposedModules library) notice verbosity $ "Test coverage report written to " ++ htmlDir_ </> "hpc_index" <.> "html" where way = guessWay lbi testName' = unUnqualComponentName $ testName suite mixDirs = map (mixDir distPref way) [ testName', libraryName ] markupPackage :: Verbosity -> LocalBuildInfo -> PD.PackageDescription -> [TestSuite] -> IO () markupPackage verbosity lbi distPref pkg_descr suites = do let tixFiles = map (tixFilePath distPref way) testNames tixFilesExist <- traverse doesFileExist tixFiles when (and tixFilesExist) $ do (hpc, hpcVer, _) <- requireProgramVersion verbosity hpcProgram anyVersion (withPrograms lbi) let outFile = tixFilePath distPref way libraryName htmlDir' = htmlDir distPref way libraryName excluded = concatMap testModules suites ++ [ main ] createDirectoryIfMissing True $ takeDirectory outFile union hpc verbosity tixFiles outFile excluded markup hpc hpcVer verbosity outFile mixDirs htmlDir' included notice verbosity $ "Package coverage report written to " ++ htmlDir' </> "hpc_index.html" where way = guessWay lbi testNames = fmap (unUnqualComponentName . testName) suites mixDirs = map (mixDir distPref way) $ libraryName : testNames included = concatMap (exposedModules) $ PD.allLibraries pkg_descr libraryName = prettyShow $ PD.package pkg_descr
d90d949c40dd59cc019a3e575eb3cadf2d423d56a11346c6f458902fc25dbefc
brick-lang/kiln
frontend.ml
module Lexer = Lexer module ParseTree = ParseTree module Parser = struct include Parser module Error = ParserError end
null
https://raw.githubusercontent.com/brick-lang/kiln/21ec6fe8dfd2a807e514c9a794abbf48a7836ab3/frontend/frontend.ml
ocaml
module Lexer = Lexer module ParseTree = ParseTree module Parser = struct include Parser module Error = ParserError end
37daa7caf6f752a7ca88a097debd667986f1185b098313530babfc0dd311ad44
janestreet/core
time_ns_intf.ml
open! Import module type Span = sig * [ t ] is immediate on 64bit boxes and so plays nicely with the GC write barrier . type t = private Int63.t [@@deriving hash] include Span_intf.S with type underlying = Int63.t and type t := t val of_sec_with_microsecond_precision : float -> t val of_int_us : int -> t val of_int_ms : int -> t val to_int_us : t -> int val to_int_ms : t -> int val to_int_sec : t -> int (** The minimum representable time span. *) val min_value_representable : t (** The maximum representable time span. *) val max_value_representable : t * The minimum span that rounds to a [ Time . ] with microsecond precision . val min_value_for_1us_rounding : t * The maximum span that rounds to a [ Time . ] with microsecond precision . val max_value_for_1us_rounding : t (** An alias for [min_value_for_1us_rounding]. *) val min_value : t [@@deprecated "[since 2019-02] use [min_value_representable] or [min_value_for_1us_rounding] \ instead"] (** An alias for [max_value_for_1us_rounding]. *) val max_value : t [@@deprecated "[since 2019-02] use [max_value_representable] or [max_value_for_1us_rounding] \ instead"] (** overflows silently *) val scale_int : t -> int -> t (** overflows silently *) val scale_int63 : t -> Int63.t -> t (** Rounds down, and raises unless denominator is positive. *) val div : t -> t -> Int63.t (** Fast, implemented as the identity function. *) val to_int63_ns : t -> Int63.t (** Fast, implemented as the identity function. *) val of_int63_ns : Int63.t -> t * Will raise on 32 - bit platforms . Consider [ ] instead . val to_int_ns : t -> int val of_int_ns : int -> t val since_unix_epoch : unit -> t val random : ?state:Random.State.t -> unit -> t * WARNING ! ! ! [ to_span ] and [ of_span ] both round to the nearest 1us . Around 135y magnitudes [ to_span ] and [ of_span ] raise . Around 135y magnitudes [to_span] and [of_span] raise. *) val to_span : t -> Span_float.t [@@deprecated "[since 2019-01] use [to_span_float_round_nearest] or \ [to_span_float_round_nearest_microsecond]"] val of_span : Span_float.t -> t [@@deprecated "[since 2019-01] use [of_span_float_round_nearest] or \ [of_span_float_round_nearest_microsecond]"] (** [*_round_nearest] vs [*_round_nearest_microsecond]: If you don't know that you need microsecond precision, use the [*_round_nearest] version. [*_round_nearest_microsecond] is for historical purposes. *) val to_span_float_round_nearest : t -> Span_float.t val to_span_float_round_nearest_microsecond : t -> Span_float.t val of_span_float_round_nearest : Span_float.t -> t val of_span_float_round_nearest_microsecond : Span_float.t -> t (** Note that we expose a sexp format that is not the one exposed in [Core]. *) module Alternate_sexp : sig type nonrec t = t [@@deriving sexp, sexp_grammar] end [@@deprecated "[since 2018-04] use [Span.sexp_of_t] and [Span.t_of_sexp] instead"] val arg_type : t Command.Arg_type.t * [ Span . ] is like [ option ] , except that the value is immediate on architectures where [ Int63.t ] is immediate . This module should mainly be used to avoid allocations . architectures where [Int63.t] is immediate. This module should mainly be used to avoid allocations. *) module Option : sig include Immediate_option.S_int63 with type value := t include Identifiable.S with type t := t include Quickcheck.S with type t := t module Stable : sig module V1 : Stable_int63able.With_stable_witness.S with type t = t module V2 : Stable_int63able.With_stable_witness.S with type t = t end end module Stable : sig module V1 : sig type nonrec t = t [@@deriving hash, equal] include Stable_int63able.With_stable_witness.S with type t := t end module V2 : sig type nonrec t = t [@@deriving hash, equal, sexp_grammar] type nonrec comparator_witness = comparator_witness include Stable_int63able.With_stable_witness.S with type t := t with type comparator_witness := comparator_witness include Comparable.Stable.V1.With_stable_witness.S with type comparable := t with type comparator_witness := comparator_witness include Stringable.S with type t := t end end (*_ See the Jane Street Style Guide for an explanation of [Private] submodules: /#private-submodules *) module Private : sig val of_parts : Parts.t -> t val to_parts : t -> Parts.t end end module type Ofday = sig module Span : Span * [ t ] is immediate on 64bit boxes and so plays nicely with the GC write barrier . type t = private Int63.t * String and sexp output takes the form ' HH : MM : SS.sssssssss ' ; see { ! Core . Ofday_intf } for accepted input . If input includes more than 9 decimal places in seconds , rounds to the nearest nanosecond , with the midpoint rounded up . Allows 60[.sss ... ] seconds for leap seconds but treats it as exactly 60s regardless of fractional part . {!Core.Ofday_intf} for accepted input. If input includes more than 9 decimal places in seconds, rounds to the nearest nanosecond, with the midpoint rounded up. Allows 60[.sss...] seconds for leap seconds but treats it as exactly 60s regardless of fractional part. *) include Ofday_intf.S with type underlying = Int63.t and type t := t and module Span := Span * The largest representable value below [ start_of_next_day ] , i.e. one nanosecond before midnight . before midnight. *) val approximate_end_of_day : t _ This is already exported from [ Ofday_intf . S ] , but we re - declare it to add documentation . documentation. *) * [ add_exn t span ] shifts the time of day [ t ] by [ span ] . It raises if the result is not in the same 24 - hour day . Daylight savings shifts are not accounted for . not in the same 24-hour day. Daylight savings shifts are not accounted for. *) val add_exn : t -> Span.t -> t * [ sub_exn t span ] shifts the time of day [ t ] back by [ span ] . It raises if the result is not in the same 24 - hour day . Daylight savings shifts are not accounted for . is not in the same 24-hour day. Daylight savings shifts are not accounted for. *) val sub_exn : t -> Span.t -> t * [ every span ~start ~stop ] returns a sorted list of all [ t]s that can be expressed as [ start + ( i * span ) ] without overflow , and satisfying [ t > = start & & t < = stop ] . If [ span < = Span.zero || start > stop ] , returns an Error . The result never crosses the midnight boundary . Constructing a list crossing midnight , e.g. every hour from 10 pm to 2 am , requires multiple calls to [ every ] . [start + (i * span)] without overflow, and satisfying [t >= start && t <= stop]. If [span <= Span.zero || start > stop], returns an Error. The result never crosses the midnight boundary. Constructing a list crossing midnight, e.g. every hour from 10pm to 2am, requires multiple calls to [every]. *) val every : Span.t -> start:t -> stop:t -> t list Or_error.t val to_microsecond_string : t -> string val arg_type : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val now : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val of_ofday_float_round_nearest : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val of_ofday_float_round_nearest_microsecond : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val to_ofday_float_round_nearest : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val to_ofday_float_round_nearest_microsecond : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Option : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Zoned : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] end * Time represented as an [ Int63.t ] number of nanoseconds since the epoch . See { ! Time_ns_unix } for important user documentation . Internally , arithmetic is not overflow - checked . Instead , overflows are silently ignored as for [ int ] arithmetic , unless specifically documented otherwise . Conversions may ( or may not ) raise if prior arithmetic operations overflowed . See {!Time_ns_unix} for important user documentation. Internally, arithmetic is not overflow-checked. Instead, overflows are silently ignored as for [int] arithmetic, unless specifically documented otherwise. Conversions may (or may not) raise if prior arithmetic operations overflowed. *) module type Time_ns = sig module Span : Span module Ofday : Ofday with module Span := Span type t = private Int63.t [@@deriving hash, typerep, bin_io] include Comparisons.S with type t := t (** Note that we expose a sexp format that is not the one exposed in [Core]. *) module Alternate_sexp : sig type nonrec t = t [@@deriving compare, equal, hash, sexp, sexp_grammar] include Comparable.S with type t := t end include Time_intf.Shared with type t := t with module Span := Span with module Ofday := Ofday val of_string : string -> t [@@deprecated "[since 2021-04] Use [of_string_with_utc_offset] or [Time_ns_unix.of_string]"] * [ of_string_with_utc_offset ] requires its input to have an explicit UTC offset , e.g. [ 2000 - 01 - 01 12:34:56.789012 - 23 ] , or use the UTC zone , " Z " , e.g. [ 2000 - 01 - 01 12:34:56.789012Z ] . UTC offset, e.g. [2000-01-01 12:34:56.789012-23], or use the UTC zone, "Z", e.g. [2000-01-01 12:34:56.789012Z]. *) val of_string_with_utc_offset : string -> t val to_string : t -> string [@@deprecated "[since 2021-04] Use [to_string_utc] or [Time_ns_unix.to_string]"] * [ to_string_utc ] generates a time string with the UTC zone , " Z " , e.g. [ 2000 - 01 - 01 12:34:56.789012Z ] . 12:34:56.789012Z]. *) val to_string_utc : t -> string * Unix epoch ( 1970 - 01 - 01 00:00:00 UTC ) val epoch : t (** The minimum representable time. *) val min_value_representable : t (** The maximum representable time. *) val max_value_representable : t (** The minimum time that rounds to a [Time.t] with microsecond precision. *) val min_value_for_1us_rounding : t (** The maximum time that rounds to a [Time.t] with microsecond precision. *) val max_value_for_1us_rounding : t (** An alias for [min_value_for_1us_rounding]. *) val min_value : t [@@deprecated "[since 2019-02] use [min_value_representable] or [min_value_for_1us_rounding] \ instead"] (** An alias for [max_value_for_1us_rounding]. *) val max_value : t [@@deprecated "[since 2019-02] use [max_value_representable] or [max_value_for_1us_rounding] \ instead"] (** The current time. *) val now : unit -> t (** overflows silently *) val add : t -> Span.t -> t (** As [add]; rather than over/underflowing, clamps the result to the closed interval between [min_value_representable] and [max_value_representable]. *) val add_saturating : t -> Span.t -> t (** As [sub]; rather than over/underflowing, clamps the result to the closed interval between [min_value_representable] and [max_value_representable]. *) val sub_saturating : t -> Span.t -> t (** overflows silently *) val sub : t -> Span.t -> t (** overflows silently *) val next : t -> t (** overflows silently *) val prev : t -> t (** overflows silently *) val diff : t -> t -> Span.t (** overflows silently *) val abs_diff : t -> t -> Span.t val to_span_since_epoch : t -> Span.t val of_span_since_epoch : Span.t -> t val to_int63_ns_since_epoch : t -> Int63.t val of_int63_ns_since_epoch : Int63.t -> t * Will raise on 32 - bit platforms . Consider [ to_int63_ns_since_epoch ] instead . val to_int_ns_since_epoch : t -> int val of_int_ns_since_epoch : int -> t (** [next_multiple ~base ~after ~interval] returns the smallest [time] of the form: {[ time = base + k * interval ]} where [k >= 0] and [time > after]. It is an error if [interval <= 0]. Supplying [~can_equal_after:true] allows the result to satisfy [time >= after]. Overflows silently. *) val next_multiple : ?can_equal_after:bool (** default is [false] *) -> base:t -> after:t -> interval:Span.t -> unit -> t * [ ~before ~interval ] returns the largest [ time ] of the form : { [ time = base + k * interval ] } where [ k > = 0 ] and [ time < before ] . It is an error if [ interval < = 0 ] . Supplying [ ~can_equal_before : true ] allows the result to satisfy [ time < = before ] . {[ time = base + k * interval ]} where [k >= 0] and [time < before]. It is an error if [interval <= 0]. Supplying [~can_equal_before:true] allows the result to satisfy [time <= before]. *) val prev_multiple : ?can_equal_before:bool (** default is [false] *) -> base:t -> before:t -> interval:Span.t -> unit -> t val random : ?state:Random.State.t -> unit -> t val of_time : Time_float.t -> t [@@deprecated "[since 2019-01] use [of_time_float_round_nearest] or \ [of_time_float_round_nearest_microsecond]"] val to_time : t -> Time_float.t [@@deprecated "[since 2019-01] use [to_time_float_round_nearest] or \ [to_time_float_round_nearest_microsecond]"] (** [*_round_nearest] vs [*_round_nearest_microsecond]: If you don't know that you need microsecond precision, use the [*_round_nearest] version. [*_round_nearest_microsecond] is for historical purposes. *) val to_time_float_round_nearest : t -> Time_float.t val to_time_float_round_nearest_microsecond : t -> Time_float.t val of_time_float_round_nearest : Time_float.t -> t val of_time_float_round_nearest_microsecond : Time_float.t -> t module Utc : sig * [ to_date_and_span_since_start_of_day ] computes the date and intraday - offset of a time in UTC . It may be slower than [ Core . Time_ns.to_date_ofday ] , as this function does not cache partial results while the latter does . time in UTC. It may be slower than [Core.Time_ns.to_date_ofday], as this function does not cache partial results while the latter does. *) val to_date_and_span_since_start_of_day : t -> Date0.t * Span.t (** The inverse of [to_date_and_span_since_start_of_day]. *) val of_date_and_span_since_start_of_day : Date0.t -> Span.t -> t end module Stable : sig module V1 : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix] or [Time_ns.Alternate_sexp]"] module Option : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Alternate_sexp : sig module V1 : sig type t = Alternate_sexp.t [@@deriving bin_io, compare, hash, sexp, sexp_grammar, stable_witness] include Comparator.Stable.V1.S with type t := t and type comparator_witness = Alternate_sexp.comparator_witness include Comparable.Stable.V1.With_stable_witness.S with type comparable := t with type comparator_witness := comparator_witness end end module Span : sig module V1 : sig type nonrec t = Span.t [@@deriving hash, equal] include Stable_int63able.With_stable_witness.S with type t := t end module Option : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module V2 : sig type t = Span.t [@@deriving hash, equal, sexp_grammar] type nonrec comparator_witness = Span.comparator_witness include Stable_int63able.With_stable_witness.S with type t := t with type comparator_witness := comparator_witness include Comparable.Stable.V1.With_stable_witness.S with type comparable := t with type comparator_witness := comparator_witness include Stringable.S with type t := t end end module Ofday : sig module V1 : Stable_int63able.With_stable_witness.S with type t = Ofday.t and type comparator_witness = Ofday.comparator_witness module Option : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Zoned : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] end end module Hash_queue : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Hash_set : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Map : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Option : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Replace_polymorphic_compare : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Set : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Table : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Zone : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val arg_type : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val comparator : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val get_sexp_zone : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val interruptible_pause : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val of_date_ofday_zoned : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val of_string_abs : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val of_string_fix_proto : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val pause : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val pause_forever : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val pp : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val set_sexp_zone : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val sexp_of_t : [ `Use_Time_ns_unix_or_Time_ns_alternate_sexp ] [@@deprecated "[since 2021-03] Use [Time_ns_unix] or [Time_ns.Alternate_sexp]"] val sexp_of_t_abs : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val t_of_sexp : [ `Use_Time_ns_unix_or_Time_ns_alternate_sexp ] [@@deprecated "[since 2021-03] Use [Time_ns_unix] or [Time_ns.Alternate_sexp]"] val t_of_sexp_abs : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val to_date_ofday_zoned : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val to_ofday_zoned : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val to_string_fix_proto : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val validate_bound : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val validate_lbound : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val validate_ubound : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] end
null
https://raw.githubusercontent.com/janestreet/core/f382131ccdcb4a8cd21ebf9a49fa42dcf8183de6/core/src/time_ns_intf.ml
ocaml
* The minimum representable time span. * The maximum representable time span. * An alias for [min_value_for_1us_rounding]. * An alias for [max_value_for_1us_rounding]. * overflows silently * overflows silently * Rounds down, and raises unless denominator is positive. * Fast, implemented as the identity function. * Fast, implemented as the identity function. * [*_round_nearest] vs [*_round_nearest_microsecond]: If you don't know that you need microsecond precision, use the [*_round_nearest] version. [*_round_nearest_microsecond] is for historical purposes. * Note that we expose a sexp format that is not the one exposed in [Core]. _ See the Jane Street Style Guide for an explanation of [Private] submodules: /#private-submodules * Note that we expose a sexp format that is not the one exposed in [Core]. * The minimum representable time. * The maximum representable time. * The minimum time that rounds to a [Time.t] with microsecond precision. * The maximum time that rounds to a [Time.t] with microsecond precision. * An alias for [min_value_for_1us_rounding]. * An alias for [max_value_for_1us_rounding]. * The current time. * overflows silently * As [add]; rather than over/underflowing, clamps the result to the closed interval between [min_value_representable] and [max_value_representable]. * As [sub]; rather than over/underflowing, clamps the result to the closed interval between [min_value_representable] and [max_value_representable]. * overflows silently * overflows silently * overflows silently * overflows silently * overflows silently * [next_multiple ~base ~after ~interval] returns the smallest [time] of the form: {[ time = base + k * interval ]} where [k >= 0] and [time > after]. It is an error if [interval <= 0]. Supplying [~can_equal_after:true] allows the result to satisfy [time >= after]. Overflows silently. * default is [false] * default is [false] * [*_round_nearest] vs [*_round_nearest_microsecond]: If you don't know that you need microsecond precision, use the [*_round_nearest] version. [*_round_nearest_microsecond] is for historical purposes. * The inverse of [to_date_and_span_since_start_of_day].
open! Import module type Span = sig * [ t ] is immediate on 64bit boxes and so plays nicely with the GC write barrier . type t = private Int63.t [@@deriving hash] include Span_intf.S with type underlying = Int63.t and type t := t val of_sec_with_microsecond_precision : float -> t val of_int_us : int -> t val of_int_ms : int -> t val to_int_us : t -> int val to_int_ms : t -> int val to_int_sec : t -> int val min_value_representable : t val max_value_representable : t * The minimum span that rounds to a [ Time . ] with microsecond precision . val min_value_for_1us_rounding : t * The maximum span that rounds to a [ Time . ] with microsecond precision . val max_value_for_1us_rounding : t val min_value : t [@@deprecated "[since 2019-02] use [min_value_representable] or [min_value_for_1us_rounding] \ instead"] val max_value : t [@@deprecated "[since 2019-02] use [max_value_representable] or [max_value_for_1us_rounding] \ instead"] val scale_int : t -> int -> t val scale_int63 : t -> Int63.t -> t val div : t -> t -> Int63.t val to_int63_ns : t -> Int63.t val of_int63_ns : Int63.t -> t * Will raise on 32 - bit platforms . Consider [ ] instead . val to_int_ns : t -> int val of_int_ns : int -> t val since_unix_epoch : unit -> t val random : ?state:Random.State.t -> unit -> t * WARNING ! ! ! [ to_span ] and [ of_span ] both round to the nearest 1us . Around 135y magnitudes [ to_span ] and [ of_span ] raise . Around 135y magnitudes [to_span] and [of_span] raise. *) val to_span : t -> Span_float.t [@@deprecated "[since 2019-01] use [to_span_float_round_nearest] or \ [to_span_float_round_nearest_microsecond]"] val of_span : Span_float.t -> t [@@deprecated "[since 2019-01] use [of_span_float_round_nearest] or \ [of_span_float_round_nearest_microsecond]"] val to_span_float_round_nearest : t -> Span_float.t val to_span_float_round_nearest_microsecond : t -> Span_float.t val of_span_float_round_nearest : Span_float.t -> t val of_span_float_round_nearest_microsecond : Span_float.t -> t module Alternate_sexp : sig type nonrec t = t [@@deriving sexp, sexp_grammar] end [@@deprecated "[since 2018-04] use [Span.sexp_of_t] and [Span.t_of_sexp] instead"] val arg_type : t Command.Arg_type.t * [ Span . ] is like [ option ] , except that the value is immediate on architectures where [ Int63.t ] is immediate . This module should mainly be used to avoid allocations . architectures where [Int63.t] is immediate. This module should mainly be used to avoid allocations. *) module Option : sig include Immediate_option.S_int63 with type value := t include Identifiable.S with type t := t include Quickcheck.S with type t := t module Stable : sig module V1 : Stable_int63able.With_stable_witness.S with type t = t module V2 : Stable_int63able.With_stable_witness.S with type t = t end end module Stable : sig module V1 : sig type nonrec t = t [@@deriving hash, equal] include Stable_int63able.With_stable_witness.S with type t := t end module V2 : sig type nonrec t = t [@@deriving hash, equal, sexp_grammar] type nonrec comparator_witness = comparator_witness include Stable_int63able.With_stable_witness.S with type t := t with type comparator_witness := comparator_witness include Comparable.Stable.V1.With_stable_witness.S with type comparable := t with type comparator_witness := comparator_witness include Stringable.S with type t := t end end module Private : sig val of_parts : Parts.t -> t val to_parts : t -> Parts.t end end module type Ofday = sig module Span : Span * [ t ] is immediate on 64bit boxes and so plays nicely with the GC write barrier . type t = private Int63.t * String and sexp output takes the form ' HH : MM : SS.sssssssss ' ; see { ! Core . Ofday_intf } for accepted input . If input includes more than 9 decimal places in seconds , rounds to the nearest nanosecond , with the midpoint rounded up . Allows 60[.sss ... ] seconds for leap seconds but treats it as exactly 60s regardless of fractional part . {!Core.Ofday_intf} for accepted input. If input includes more than 9 decimal places in seconds, rounds to the nearest nanosecond, with the midpoint rounded up. Allows 60[.sss...] seconds for leap seconds but treats it as exactly 60s regardless of fractional part. *) include Ofday_intf.S with type underlying = Int63.t and type t := t and module Span := Span * The largest representable value below [ start_of_next_day ] , i.e. one nanosecond before midnight . before midnight. *) val approximate_end_of_day : t _ This is already exported from [ Ofday_intf . S ] , but we re - declare it to add documentation . documentation. *) * [ add_exn t span ] shifts the time of day [ t ] by [ span ] . It raises if the result is not in the same 24 - hour day . Daylight savings shifts are not accounted for . not in the same 24-hour day. Daylight savings shifts are not accounted for. *) val add_exn : t -> Span.t -> t * [ sub_exn t span ] shifts the time of day [ t ] back by [ span ] . It raises if the result is not in the same 24 - hour day . Daylight savings shifts are not accounted for . is not in the same 24-hour day. Daylight savings shifts are not accounted for. *) val sub_exn : t -> Span.t -> t * [ every span ~start ~stop ] returns a sorted list of all [ t]s that can be expressed as [ start + ( i * span ) ] without overflow , and satisfying [ t > = start & & t < = stop ] . If [ span < = Span.zero || start > stop ] , returns an Error . The result never crosses the midnight boundary . Constructing a list crossing midnight , e.g. every hour from 10 pm to 2 am , requires multiple calls to [ every ] . [start + (i * span)] without overflow, and satisfying [t >= start && t <= stop]. If [span <= Span.zero || start > stop], returns an Error. The result never crosses the midnight boundary. Constructing a list crossing midnight, e.g. every hour from 10pm to 2am, requires multiple calls to [every]. *) val every : Span.t -> start:t -> stop:t -> t list Or_error.t val to_microsecond_string : t -> string val arg_type : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val now : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val of_ofday_float_round_nearest : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val of_ofday_float_round_nearest_microsecond : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val to_ofday_float_round_nearest : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val to_ofday_float_round_nearest_microsecond : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Option : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Zoned : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] end * Time represented as an [ Int63.t ] number of nanoseconds since the epoch . See { ! Time_ns_unix } for important user documentation . Internally , arithmetic is not overflow - checked . Instead , overflows are silently ignored as for [ int ] arithmetic , unless specifically documented otherwise . Conversions may ( or may not ) raise if prior arithmetic operations overflowed . See {!Time_ns_unix} for important user documentation. Internally, arithmetic is not overflow-checked. Instead, overflows are silently ignored as for [int] arithmetic, unless specifically documented otherwise. Conversions may (or may not) raise if prior arithmetic operations overflowed. *) module type Time_ns = sig module Span : Span module Ofday : Ofday with module Span := Span type t = private Int63.t [@@deriving hash, typerep, bin_io] include Comparisons.S with type t := t module Alternate_sexp : sig type nonrec t = t [@@deriving compare, equal, hash, sexp, sexp_grammar] include Comparable.S with type t := t end include Time_intf.Shared with type t := t with module Span := Span with module Ofday := Ofday val of_string : string -> t [@@deprecated "[since 2021-04] Use [of_string_with_utc_offset] or [Time_ns_unix.of_string]"] * [ of_string_with_utc_offset ] requires its input to have an explicit UTC offset , e.g. [ 2000 - 01 - 01 12:34:56.789012 - 23 ] , or use the UTC zone , " Z " , e.g. [ 2000 - 01 - 01 12:34:56.789012Z ] . UTC offset, e.g. [2000-01-01 12:34:56.789012-23], or use the UTC zone, "Z", e.g. [2000-01-01 12:34:56.789012Z]. *) val of_string_with_utc_offset : string -> t val to_string : t -> string [@@deprecated "[since 2021-04] Use [to_string_utc] or [Time_ns_unix.to_string]"] * [ to_string_utc ] generates a time string with the UTC zone , " Z " , e.g. [ 2000 - 01 - 01 12:34:56.789012Z ] . 12:34:56.789012Z]. *) val to_string_utc : t -> string * Unix epoch ( 1970 - 01 - 01 00:00:00 UTC ) val epoch : t val min_value_representable : t val max_value_representable : t val min_value_for_1us_rounding : t val max_value_for_1us_rounding : t val min_value : t [@@deprecated "[since 2019-02] use [min_value_representable] or [min_value_for_1us_rounding] \ instead"] val max_value : t [@@deprecated "[since 2019-02] use [max_value_representable] or [max_value_for_1us_rounding] \ instead"] val now : unit -> t val add : t -> Span.t -> t val add_saturating : t -> Span.t -> t val sub_saturating : t -> Span.t -> t val sub : t -> Span.t -> t val next : t -> t val prev : t -> t val diff : t -> t -> Span.t val abs_diff : t -> t -> Span.t val to_span_since_epoch : t -> Span.t val of_span_since_epoch : Span.t -> t val to_int63_ns_since_epoch : t -> Int63.t val of_int63_ns_since_epoch : Int63.t -> t * Will raise on 32 - bit platforms . Consider [ to_int63_ns_since_epoch ] instead . val to_int_ns_since_epoch : t -> int val of_int_ns_since_epoch : int -> t val next_multiple -> base:t -> after:t -> interval:Span.t -> unit -> t * [ ~before ~interval ] returns the largest [ time ] of the form : { [ time = base + k * interval ] } where [ k > = 0 ] and [ time < before ] . It is an error if [ interval < = 0 ] . Supplying [ ~can_equal_before : true ] allows the result to satisfy [ time < = before ] . {[ time = base + k * interval ]} where [k >= 0] and [time < before]. It is an error if [interval <= 0]. Supplying [~can_equal_before:true] allows the result to satisfy [time <= before]. *) val prev_multiple -> base:t -> before:t -> interval:Span.t -> unit -> t val random : ?state:Random.State.t -> unit -> t val of_time : Time_float.t -> t [@@deprecated "[since 2019-01] use [of_time_float_round_nearest] or \ [of_time_float_round_nearest_microsecond]"] val to_time : t -> Time_float.t [@@deprecated "[since 2019-01] use [to_time_float_round_nearest] or \ [to_time_float_round_nearest_microsecond]"] val to_time_float_round_nearest : t -> Time_float.t val to_time_float_round_nearest_microsecond : t -> Time_float.t val of_time_float_round_nearest : Time_float.t -> t val of_time_float_round_nearest_microsecond : Time_float.t -> t module Utc : sig * [ to_date_and_span_since_start_of_day ] computes the date and intraday - offset of a time in UTC . It may be slower than [ Core . Time_ns.to_date_ofday ] , as this function does not cache partial results while the latter does . time in UTC. It may be slower than [Core.Time_ns.to_date_ofday], as this function does not cache partial results while the latter does. *) val to_date_and_span_since_start_of_day : t -> Date0.t * Span.t val of_date_and_span_since_start_of_day : Date0.t -> Span.t -> t end module Stable : sig module V1 : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix] or [Time_ns.Alternate_sexp]"] module Option : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Alternate_sexp : sig module V1 : sig type t = Alternate_sexp.t [@@deriving bin_io, compare, hash, sexp, sexp_grammar, stable_witness] include Comparator.Stable.V1.S with type t := t and type comparator_witness = Alternate_sexp.comparator_witness include Comparable.Stable.V1.With_stable_witness.S with type comparable := t with type comparator_witness := comparator_witness end end module Span : sig module V1 : sig type nonrec t = Span.t [@@deriving hash, equal] include Stable_int63able.With_stable_witness.S with type t := t end module Option : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module V2 : sig type t = Span.t [@@deriving hash, equal, sexp_grammar] type nonrec comparator_witness = Span.comparator_witness include Stable_int63able.With_stable_witness.S with type t := t with type comparator_witness := comparator_witness include Comparable.Stable.V1.With_stable_witness.S with type comparable := t with type comparator_witness := comparator_witness include Stringable.S with type t := t end end module Ofday : sig module V1 : Stable_int63able.With_stable_witness.S with type t = Ofday.t and type comparator_witness = Ofday.comparator_witness module Option : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Zoned : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] end end module Hash_queue : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Hash_set : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Map : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Option : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Replace_polymorphic_compare : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Set : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Table : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] module Zone : sig end [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val arg_type : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val comparator : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val get_sexp_zone : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val interruptible_pause : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val of_date_ofday_zoned : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val of_string_abs : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val of_string_fix_proto : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val pause : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val pause_forever : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val pp : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val set_sexp_zone : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val sexp_of_t : [ `Use_Time_ns_unix_or_Time_ns_alternate_sexp ] [@@deprecated "[since 2021-03] Use [Time_ns_unix] or [Time_ns.Alternate_sexp]"] val sexp_of_t_abs : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val t_of_sexp : [ `Use_Time_ns_unix_or_Time_ns_alternate_sexp ] [@@deprecated "[since 2021-03] Use [Time_ns_unix] or [Time_ns.Alternate_sexp]"] val t_of_sexp_abs : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val to_date_ofday_zoned : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val to_ofday_zoned : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val to_string_fix_proto : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val validate_bound : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val validate_lbound : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] val validate_ubound : [ `Use_Time_ns_unix ] [@@deprecated "[since 2021-03] Use [Time_ns_unix]"] end
ff2ef25122053ff0b24cef97b8723682f54df86d0995b639bf28411268e3afb0
larcenists/larceny
puzzle.scm
PUZZLE -- Forest Baskett 's Puzzle benchmark , originally written in . (import (scheme base) (scheme read) (scheme write) (scheme time)) (define (my-iota n) (do ((n n (- n 1)) (list '() (cons (- n 1) list))) ((zero? n) list))) (define size 511) (define classmax 3) (define typemax 12) (define *iii* 0) (define *kount* 0) (define *d* 8) (define *piececount* (make-vector (+ classmax 1) 0)) (define *class* (make-vector (+ typemax 1) 0)) (define *piecemax* (make-vector (+ typemax 1) 0)) (define *puzzle* (make-vector (+ size 1))) (define *p* (make-vector (+ typemax 1))) (define (fit i j) (let ((end (vector-ref *piecemax* i))) (do ((k 0 (+ k 1))) ((or (> k end) (and (vector-ref (vector-ref *p* i) k) (vector-ref *puzzle* (+ j k)))) (if (> k end) #t #f))))) (define (place i j) (let ((end (vector-ref *piecemax* i))) (do ((k 0 (+ k 1))) ((> k end)) (cond ((vector-ref (vector-ref *p* i) k) (vector-set! *puzzle* (+ j k) #t) #t))) (vector-set! *piececount* (vector-ref *class* i) (- (vector-ref *piececount* (vector-ref *class* i)) 1)) (do ((k j (+ k 1))) ((or (> k size) (not (vector-ref *puzzle* k))) (if (> k size) 0 k))))) (define (puzzle-remove i j) (let ((end (vector-ref *piecemax* i))) (do ((k 0 (+ k 1))) ((> k end)) (cond ((vector-ref (vector-ref *p* i) k) (vector-set! *puzzle* (+ j k) #f) #f))) (vector-set! *piececount* (vector-ref *class* i) (+ (vector-ref *piececount* (vector-ref *class* i)) 1)))) (define (trial j) (let ((k 0)) (call-with-current-continuation (lambda (return) (do ((i 0 (+ i 1))) ((> i typemax) (set! *kount* (+ *kount* 1)) #f) (cond ((not (zero? (vector-ref *piececount* (vector-ref *class* i)))) (cond ((fit i j) (set! k (place i j)) (cond ((or (trial k) (zero? k)) (set! *kount* (+ *kount* 1)) (return #t)) (else (puzzle-remove i j)))))))))))) (define (definePiece iclass ii jj kk) (let ((index 0)) (do ((i 0 (+ i 1))) ((> i ii)) (do ((j 0 (+ j 1))) ((> j jj)) (do ((k 0 (+ k 1))) ((> k kk)) (set! index (+ i (* *d* (+ j (* *d* k))))) (vector-set! (vector-ref *p* *iii*) index #t)))) (vector-set! *class* *iii* iclass) (vector-set! *piecemax* *iii* index) (cond ((not (= *iii* typemax)) (set! *iii* (+ *iii* 1)))))) (define (start size) (set! *kount* 0) (do ((m 0 (+ m 1))) ((> m size)) (vector-set! *puzzle* m #t)) (do ((i 1 (+ i 1))) ((> i 5)) (do ((j 1 (+ j 1))) ((> j 5)) (do ((k 1 (+ k 1))) ((> k 5)) (vector-set! *puzzle* (+ i (* *d* (+ j (* *d* k)))) #f)))) (do ((i 0 (+ i 1))) ((> i typemax)) (do ((m 0 (+ m 1))) ((> m size)) (vector-set! (vector-ref *p* i) m #f))) (set! *iii* 0) (definePiece 0 3 1 0) (definePiece 0 1 0 3) (definePiece 0 0 3 1) (definePiece 0 1 3 0) (definePiece 0 3 0 1) (definePiece 0 0 1 3) (definePiece 1 2 0 0) (definePiece 1 0 2 0) (definePiece 1 0 0 2) (definePiece 2 1 1 0) (definePiece 2 1 0 1) (definePiece 2 0 1 1) (definePiece 3 1 1 1) (vector-set! *piececount* 0 13) (vector-set! *piececount* 1 3) (vector-set! *piececount* 2 1) (vector-set! *piececount* 3 1) (let ((m (+ (* *d* (+ *d* 1)) 1)) (n 0)) (cond ((fit 0 m) (set! n (place 0 m))) (else (begin (newline) (display "Error.")))) (if (trial n) *kount* #f))) (define (main) (let* ((count (read)) (input1 (read)) (output (read)) (s2 (number->string count)) (s1 input1) (name "puzzle")) (run-r7rs-benchmark (string-append name ":" s2) count (lambda () (start (hide count input1))) (lambda (result) (equal? result output))))) (for-each (lambda (i) (vector-set! *p* i (make-vector (+ size 1)))) (my-iota (+ typemax 1)))
null
https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/test/Benchmarking/R7RS/src/puzzle.scm
scheme
PUZZLE -- Forest Baskett 's Puzzle benchmark , originally written in . (import (scheme base) (scheme read) (scheme write) (scheme time)) (define (my-iota n) (do ((n n (- n 1)) (list '() (cons (- n 1) list))) ((zero? n) list))) (define size 511) (define classmax 3) (define typemax 12) (define *iii* 0) (define *kount* 0) (define *d* 8) (define *piececount* (make-vector (+ classmax 1) 0)) (define *class* (make-vector (+ typemax 1) 0)) (define *piecemax* (make-vector (+ typemax 1) 0)) (define *puzzle* (make-vector (+ size 1))) (define *p* (make-vector (+ typemax 1))) (define (fit i j) (let ((end (vector-ref *piecemax* i))) (do ((k 0 (+ k 1))) ((or (> k end) (and (vector-ref (vector-ref *p* i) k) (vector-ref *puzzle* (+ j k)))) (if (> k end) #t #f))))) (define (place i j) (let ((end (vector-ref *piecemax* i))) (do ((k 0 (+ k 1))) ((> k end)) (cond ((vector-ref (vector-ref *p* i) k) (vector-set! *puzzle* (+ j k) #t) #t))) (vector-set! *piececount* (vector-ref *class* i) (- (vector-ref *piececount* (vector-ref *class* i)) 1)) (do ((k j (+ k 1))) ((or (> k size) (not (vector-ref *puzzle* k))) (if (> k size) 0 k))))) (define (puzzle-remove i j) (let ((end (vector-ref *piecemax* i))) (do ((k 0 (+ k 1))) ((> k end)) (cond ((vector-ref (vector-ref *p* i) k) (vector-set! *puzzle* (+ j k) #f) #f))) (vector-set! *piececount* (vector-ref *class* i) (+ (vector-ref *piececount* (vector-ref *class* i)) 1)))) (define (trial j) (let ((k 0)) (call-with-current-continuation (lambda (return) (do ((i 0 (+ i 1))) ((> i typemax) (set! *kount* (+ *kount* 1)) #f) (cond ((not (zero? (vector-ref *piececount* (vector-ref *class* i)))) (cond ((fit i j) (set! k (place i j)) (cond ((or (trial k) (zero? k)) (set! *kount* (+ *kount* 1)) (return #t)) (else (puzzle-remove i j)))))))))))) (define (definePiece iclass ii jj kk) (let ((index 0)) (do ((i 0 (+ i 1))) ((> i ii)) (do ((j 0 (+ j 1))) ((> j jj)) (do ((k 0 (+ k 1))) ((> k kk)) (set! index (+ i (* *d* (+ j (* *d* k))))) (vector-set! (vector-ref *p* *iii*) index #t)))) (vector-set! *class* *iii* iclass) (vector-set! *piecemax* *iii* index) (cond ((not (= *iii* typemax)) (set! *iii* (+ *iii* 1)))))) (define (start size) (set! *kount* 0) (do ((m 0 (+ m 1))) ((> m size)) (vector-set! *puzzle* m #t)) (do ((i 1 (+ i 1))) ((> i 5)) (do ((j 1 (+ j 1))) ((> j 5)) (do ((k 1 (+ k 1))) ((> k 5)) (vector-set! *puzzle* (+ i (* *d* (+ j (* *d* k)))) #f)))) (do ((i 0 (+ i 1))) ((> i typemax)) (do ((m 0 (+ m 1))) ((> m size)) (vector-set! (vector-ref *p* i) m #f))) (set! *iii* 0) (definePiece 0 3 1 0) (definePiece 0 1 0 3) (definePiece 0 0 3 1) (definePiece 0 1 3 0) (definePiece 0 3 0 1) (definePiece 0 0 1 3) (definePiece 1 2 0 0) (definePiece 1 0 2 0) (definePiece 1 0 0 2) (definePiece 2 1 1 0) (definePiece 2 1 0 1) (definePiece 2 0 1 1) (definePiece 3 1 1 1) (vector-set! *piececount* 0 13) (vector-set! *piececount* 1 3) (vector-set! *piececount* 2 1) (vector-set! *piececount* 3 1) (let ((m (+ (* *d* (+ *d* 1)) 1)) (n 0)) (cond ((fit 0 m) (set! n (place 0 m))) (else (begin (newline) (display "Error.")))) (if (trial n) *kount* #f))) (define (main) (let* ((count (read)) (input1 (read)) (output (read)) (s2 (number->string count)) (s1 input1) (name "puzzle")) (run-r7rs-benchmark (string-append name ":" s2) count (lambda () (start (hide count input1))) (lambda (result) (equal? result output))))) (for-each (lambda (i) (vector-set! *p* i (make-vector (+ size 1)))) (my-iota (+ typemax 1)))
d9da911b905a6508f73e2db6f47e2edd403cbb59dec5de6e6dc82e93d99fd243
TrustInSoft/tis-interpreter
print_subexps.mli
Modified by TrustInSoft (**************************************************************************) (* *) This file is part of TrustInSoft Analyzer . (* *) (**************************************************************************) (** Printing all subexpression of an expression (including or excluding the top expression itself). *) val pp_all_subexps : ?include_top_exp:bool -> (Cil_types.exp -> Cvalue.V.t) -> Format.formatter -> Cil_types.exp -> unit * [ ? ( include_top_exp = false ) eval_exp fmt exp ] is a pretty printer that prints a list of sub - expressions of a given expression [ exp ] with their values . If [ include_top_exp ] is [ true ] , then it also prints the top expression itself , otherwise it only prints its strict sub - expressions . Attention : this should be always [ false ] when the value of the top expression can not be evaluated . [ eval_exp exp ] should be a function that takes an expression [ exp ] and that evaluates it and returns its value . Usually [ Eval_exprs.eval_expr ~with_alarms state ] ( with appropriate [ ~with_alarms ] and [ state ] parameters ) should be given here ; it is not used by default mainly because of a forward reference issue . printer that prints a list of sub-expressions of a given expression [exp] with their values. If [include_top_exp] is [true], then it also prints the top expression itself, otherwise it only prints its strict sub-expressions. Attention: this should be always [false] when the value of the top expression cannot be evaluated. [eval_exp exp] should be a function that takes an expression [exp] and that evaluates it and returns its value. Usually [Eval_exprs.eval_expr ~with_alarms state] (with appropriate [~with_alarms] and [state] parameters) should be given here; it is not used by default mainly because of a forward reference issue. *) val abstract_print_subexps : ?include_top_exp:bool -> (Cil_types.exp -> Cvalue.V.t) -> Format.formatter -> (string * Cil_types.exp) -> unit * [ abstract_print_subexps ? ( include_top_exp = false ) eval_exp fmt ( descr , exp ) ] is a version of the pretty printer which is used in the corresponding built - in [ tis_print_subexps ] . It simply adds a nice header before printing the sub - expressions of the expression [ exp ] , [ descr ] should be a string describing the expression and it will be included literally in the header . is a version of the pretty printer which is used in the corresponding built-in [tis_print_subexps]. It simply adds a nice header before printing the sub-expressions of the expression [exp], [descr] should be a string describing the expression and it will be included literally in the header. *)
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/value/utils/print_subexps.mli
ocaml
************************************************************************ ************************************************************************ * Printing all subexpression of an expression (including or excluding the top expression itself).
Modified by TrustInSoft This file is part of TrustInSoft Analyzer . val pp_all_subexps : ?include_top_exp:bool -> (Cil_types.exp -> Cvalue.V.t) -> Format.formatter -> Cil_types.exp -> unit * [ ? ( include_top_exp = false ) eval_exp fmt exp ] is a pretty printer that prints a list of sub - expressions of a given expression [ exp ] with their values . If [ include_top_exp ] is [ true ] , then it also prints the top expression itself , otherwise it only prints its strict sub - expressions . Attention : this should be always [ false ] when the value of the top expression can not be evaluated . [ eval_exp exp ] should be a function that takes an expression [ exp ] and that evaluates it and returns its value . Usually [ Eval_exprs.eval_expr ~with_alarms state ] ( with appropriate [ ~with_alarms ] and [ state ] parameters ) should be given here ; it is not used by default mainly because of a forward reference issue . printer that prints a list of sub-expressions of a given expression [exp] with their values. If [include_top_exp] is [true], then it also prints the top expression itself, otherwise it only prints its strict sub-expressions. Attention: this should be always [false] when the value of the top expression cannot be evaluated. [eval_exp exp] should be a function that takes an expression [exp] and that evaluates it and returns its value. Usually [Eval_exprs.eval_expr ~with_alarms state] (with appropriate [~with_alarms] and [state] parameters) should be given here; it is not used by default mainly because of a forward reference issue. *) val abstract_print_subexps : ?include_top_exp:bool -> (Cil_types.exp -> Cvalue.V.t) -> Format.formatter -> (string * Cil_types.exp) -> unit * [ abstract_print_subexps ? ( include_top_exp = false ) eval_exp fmt ( descr , exp ) ] is a version of the pretty printer which is used in the corresponding built - in [ tis_print_subexps ] . It simply adds a nice header before printing the sub - expressions of the expression [ exp ] , [ descr ] should be a string describing the expression and it will be included literally in the header . is a version of the pretty printer which is used in the corresponding built-in [tis_print_subexps]. It simply adds a nice header before printing the sub-expressions of the expression [exp], [descr] should be a string describing the expression and it will be included literally in the header. *)
70d6d25fdced13f006bb6b7f3a8e6e03fa2c00a1f9a7ea2404a3d8cfa58d14c3
larcenists/larceny
124.body.scm
Copyright ( C ) ( 2015 ) . All Rights Reserved . ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without ;;; restriction, including without limitation the rights to use, ;;; copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the ;;; Software is furnished to do so, subject to the following ;;; conditions: ;;; ;;; The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . ;;; THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ;;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ;;; OTHER DEALINGS IN THE SOFTWARE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; reference implementation has been modified by making all three fields of the record into mutable fields . ;;; The mutators are not exported, so they can only be used by ;;; this file. ;;; ;;; The exported procedures have also been modified to detect ;;; major garbage collections. ;;; ;;; Finally, ephemerons whose key and datum are eq? have been ;;; special-cased. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define same-as-key (list 'same-as-key)) (define-record-type <ephemeron> (%make-ephemeron key datum broken?) ephemeron? (key %ephemeron-key %ephemeron-key!) (datum %ephemeron-datum %ephemeron-datum!) (broken? %ephemeron-broken? %ephemeron-broken!)) (define (make-ephemeron key datum) (if (> (major-gc-counter) next-breaking) (break-ephemera!)) (if (eq? key datum) (%make-ephemeron key same-as-key #f) (%make-ephemeron key datum #f))) (define (ephemeron-key x) (if (> (major-gc-counter) next-breaking) (break-ephemera!)) (%ephemeron-key x)) (define (ephemeron-datum x) (if (> (major-gc-counter) next-breaking) (break-ephemera!)) (let ((result (%ephemeron-datum x))) (if (eq? result same-as-key) (%ephemeron-key x) result))) (define (ephemeron-broken? x) (if (> (major-gc-counter) next-breaking) (break-ephemera!)) (%ephemeron-broken? x)) The specification of reference - barrier in SRFI 124 makes no ;;; sense at all, and the only implementation given is this one. (define (reference-barrier key) #t) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; End of reference implementation , as modified for Larceny . ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Breaking ephemerons is expensive in Larceny , on the order of ;;; several major garbage collections. To reduce that overhead ;;; to a fraction of runtime at most 1/N, ephemerons are broken ;;; only after N major garbage collections have been performed. ;;; Furthermore the overhead is avoided altogether in programs that do n't import ( srfi 124 ) . (define gcs-between-breaking 10) (define next-breaking (+ (major-gc-counter) gcs-between-breaking)) (define (break-ephemera!) (define (break-ephemeron! e) (%ephemeron-broken! e #t) (%ephemeron-key! e #f) (%ephemeron-datum! e #f)) (let* ((v1 (sro 1 -1 1)) (v3 (sro 3 -1 1)) (v5 (sro 5 -1 1)) (rl (sro 3 5 -1)) (ht (make-eq-hashtable))) (define (walk-singly-referenced! x) (if (hashtable-contains? ht x) (break-ephemeron! (hashtable-ref ht x #f)))) ;; ht will contain all ephemerons indexed by key (vector-for-each (lambda (x) (if (ephemeron? x) (hashtable-set! ht (%ephemeron-key x) x))) ;; all record-like objects rl) (vector-for-each walk-singly-referenced! v1) (vector-for-each walk-singly-referenced! v3) (vector-for-each walk-singly-referenced! v5)) (set! next-breaking (+ (major-gc-counter) gcs-between-breaking)))
null
https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/lib/SRFI/srfi/124.body.scm
scheme
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The mutators are not exported, so they can only be used by this file. The exported procedures have also been modified to detect major garbage collections. Finally, ephemerons whose key and datum are eq? have been special-cased. sense at all, and the only implementation given is this one. several major garbage collections. To reduce that overhead to a fraction of runtime at most 1/N, ephemerons are broken only after N major garbage collections have been performed. Furthermore the overhead is avoided altogether in programs ht will contain all ephemerons indexed by key all record-like objects
Copyright ( C ) ( 2015 ) . All Rights Reserved . files ( the " Software " ) , to deal in the Software without sell copies of the Software , and to permit persons to whom the included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , reference implementation has been modified by making all three fields of the record into mutable fields . (define same-as-key (list 'same-as-key)) (define-record-type <ephemeron> (%make-ephemeron key datum broken?) ephemeron? (key %ephemeron-key %ephemeron-key!) (datum %ephemeron-datum %ephemeron-datum!) (broken? %ephemeron-broken? %ephemeron-broken!)) (define (make-ephemeron key datum) (if (> (major-gc-counter) next-breaking) (break-ephemera!)) (if (eq? key datum) (%make-ephemeron key same-as-key #f) (%make-ephemeron key datum #f))) (define (ephemeron-key x) (if (> (major-gc-counter) next-breaking) (break-ephemera!)) (%ephemeron-key x)) (define (ephemeron-datum x) (if (> (major-gc-counter) next-breaking) (break-ephemera!)) (let ((result (%ephemeron-datum x))) (if (eq? result same-as-key) (%ephemeron-key x) result))) (define (ephemeron-broken? x) (if (> (major-gc-counter) next-breaking) (break-ephemera!)) (%ephemeron-broken? x)) The specification of reference - barrier in SRFI 124 makes no (define (reference-barrier key) #t) End of reference implementation , as modified for Larceny . Breaking ephemerons is expensive in Larceny , on the order of that do n't import ( srfi 124 ) . (define gcs-between-breaking 10) (define next-breaking (+ (major-gc-counter) gcs-between-breaking)) (define (break-ephemera!) (define (break-ephemeron! e) (%ephemeron-broken! e #t) (%ephemeron-key! e #f) (%ephemeron-datum! e #f)) (let* ((v1 (sro 1 -1 1)) (v3 (sro 3 -1 1)) (v5 (sro 5 -1 1)) (rl (sro 3 5 -1)) (ht (make-eq-hashtable))) (define (walk-singly-referenced! x) (if (hashtable-contains? ht x) (break-ephemeron! (hashtable-ref ht x #f)))) (vector-for-each (lambda (x) (if (ephemeron? x) (hashtable-set! ht (%ephemeron-key x) x))) rl) (vector-for-each walk-singly-referenced! v1) (vector-for-each walk-singly-referenced! v3) (vector-for-each walk-singly-referenced! v5)) (set! next-breaking (+ (major-gc-counter) gcs-between-breaking)))
aba32d7988eccea43b234175766302559ce0363184afa44fae1cf3fddd06e10b
facebookarchive/pfff
source_tree.ml
open Common type subsystem = SubSystem of string type dir = Dir of string let string_of_subsystem (SubSystem s) = s let string_of_dir (Dir s) = s type tree_reorganization = (subsystem * dir list) list let dir_to_dirfinal (Dir s) = Str.global_replace (Str.regexp "/") "___" s let dirfinal_of_dir s = Dir ( Str.global_replace ( Str.regexp " _ _ _ " ) " / " s ) let dirfinal_of_dir s = Dir (Str.global_replace (Str.regexp "___") "/" s) *) let all_subsystem reorg = reorg +> List.map fst +> List.map string_of_subsystem let all_dirs reorg = reorg +> List.map snd +> List.concat +> List.map string_of_dir let reverse_index reorg = let res = ref [] in reorg +> List.iter (fun (SubSystem s1, dirs) -> dirs +> List.iter (fun (Dir s2) -> push (Dir s2, SubSystem s1) res; ); ); List.rev !res let (load_tree_reorganization : Common.filename -> tree_reorganization) = fun file -> let xs = Simple_format.title_colon_elems_space_separated file in xs +> List.map (fun (title, elems) -> SubSystem title, elems +> List.map (fun s -> Dir s) ) let debug_source_tree = false let change_organization_dirs_to_subsystems reorg basedir = let cmd s = if debug_source_tree then pr2 s else Common.command2 s in reorg +> List.iter (fun (SubSystem sub, dirs) -> if not debug_source_tree then Common2.mkdir (spf "%s/%s" basedir sub); dirs +> List.iter (fun (Dir dir) -> let dir' = dir_to_dirfinal (Dir dir) in cmd (spf "mv %s/%s %s/%s/%s" basedir dir basedir sub dir') ); ); () let change_organization_subsystems_to_dirs reorg basedir = let cmd s = if debug_source_tree then pr2 s else Common.command2 s in reorg +> List.iter (fun (SubSystem sub, dirs) -> dirs +> List.iter (fun (Dir dir) -> let dir' = dir_to_dirfinal (Dir dir) in cmd (spf "mv %s/%s/%s %s/%s" basedir sub dir' basedir dir) ); if not debug_source_tree then Unix.rmdir (spf "%s/%s" basedir sub); ); () let (change_organization: tree_reorganization -> Common.filename (* dir *) -> unit) = fun reorg dir -> pr2_gen reorg; pr2_gen dir; let subsystem_bools = all_subsystem reorg +> List.map (fun s -> (Sys.file_exists (Filename.concat dir s))) in let dirs_bools = all_dirs reorg +> List.map (fun s -> (Sys.file_exists (Filename.concat dir s))) in match () with | _ when Common2.and_list subsystem_bools -> assert (not (Common2.or_list dirs_bools)); change_organization_subsystems_to_dirs reorg dir; | _ when Common2.and_list dirs_bools -> assert (not (Common2.or_list subsystem_bools)); change_organization_dirs_to_subsystems reorg dir; | _ -> failwith "have a mix of subsystem and dirs, wierd" let subsystem_of_dir2 (Dir dir) reorg = let index = reverse_index reorg in let dirsplit = Common.split "/" dir in let index = index +> List.map (fun (Dir d, sub) -> Common.split "/" d, sub) in try index +> List.find (fun (dirsplit2, _sub) -> let len = List.length dirsplit2 in Common2.take_safe len dirsplit = dirsplit2 ) +> snd with Not_found -> pr2 (spf "Cant find %s in reorganization information" dir); raise Not_found let subsystem_of_dir a b = Common.profile_code "subsystem_of_dir" (fun () -> subsystem_of_dir2 a b)
null
https://raw.githubusercontent.com/facebookarchive/pfff/ec21095ab7d445559576513a63314e794378c367/h_files-format/source_tree.ml
ocaml
dir
open Common type subsystem = SubSystem of string type dir = Dir of string let string_of_subsystem (SubSystem s) = s let string_of_dir (Dir s) = s type tree_reorganization = (subsystem * dir list) list let dir_to_dirfinal (Dir s) = Str.global_replace (Str.regexp "/") "___" s let dirfinal_of_dir s = Dir ( Str.global_replace ( Str.regexp " _ _ _ " ) " / " s ) let dirfinal_of_dir s = Dir (Str.global_replace (Str.regexp "___") "/" s) *) let all_subsystem reorg = reorg +> List.map fst +> List.map string_of_subsystem let all_dirs reorg = reorg +> List.map snd +> List.concat +> List.map string_of_dir let reverse_index reorg = let res = ref [] in reorg +> List.iter (fun (SubSystem s1, dirs) -> dirs +> List.iter (fun (Dir s2) -> push (Dir s2, SubSystem s1) res; ); ); List.rev !res let (load_tree_reorganization : Common.filename -> tree_reorganization) = fun file -> let xs = Simple_format.title_colon_elems_space_separated file in xs +> List.map (fun (title, elems) -> SubSystem title, elems +> List.map (fun s -> Dir s) ) let debug_source_tree = false let change_organization_dirs_to_subsystems reorg basedir = let cmd s = if debug_source_tree then pr2 s else Common.command2 s in reorg +> List.iter (fun (SubSystem sub, dirs) -> if not debug_source_tree then Common2.mkdir (spf "%s/%s" basedir sub); dirs +> List.iter (fun (Dir dir) -> let dir' = dir_to_dirfinal (Dir dir) in cmd (spf "mv %s/%s %s/%s/%s" basedir dir basedir sub dir') ); ); () let change_organization_subsystems_to_dirs reorg basedir = let cmd s = if debug_source_tree then pr2 s else Common.command2 s in reorg +> List.iter (fun (SubSystem sub, dirs) -> dirs +> List.iter (fun (Dir dir) -> let dir' = dir_to_dirfinal (Dir dir) in cmd (spf "mv %s/%s/%s %s/%s" basedir sub dir' basedir dir) ); if not debug_source_tree then Unix.rmdir (spf "%s/%s" basedir sub); ); () let (change_organization: fun reorg dir -> pr2_gen reorg; pr2_gen dir; let subsystem_bools = all_subsystem reorg +> List.map (fun s -> (Sys.file_exists (Filename.concat dir s))) in let dirs_bools = all_dirs reorg +> List.map (fun s -> (Sys.file_exists (Filename.concat dir s))) in match () with | _ when Common2.and_list subsystem_bools -> assert (not (Common2.or_list dirs_bools)); change_organization_subsystems_to_dirs reorg dir; | _ when Common2.and_list dirs_bools -> assert (not (Common2.or_list subsystem_bools)); change_organization_dirs_to_subsystems reorg dir; | _ -> failwith "have a mix of subsystem and dirs, wierd" let subsystem_of_dir2 (Dir dir) reorg = let index = reverse_index reorg in let dirsplit = Common.split "/" dir in let index = index +> List.map (fun (Dir d, sub) -> Common.split "/" d, sub) in try index +> List.find (fun (dirsplit2, _sub) -> let len = List.length dirsplit2 in Common2.take_safe len dirsplit = dirsplit2 ) +> snd with Not_found -> pr2 (spf "Cant find %s in reorganization information" dir); raise Not_found let subsystem_of_dir a b = Common.profile_code "subsystem_of_dir" (fun () -> subsystem_of_dir2 a b)
4f118de2982c642a5b9a7c53b515fe1fc1c8a432e48b938ee691040b0666f2f1
ocaml/ocamlbuild
glob_lexer.mli
(***********************************************************************) (* *) (* ocamlbuild *) (* *) , , projet Gallium , INRIA Rocquencourt (* *) Copyright 2007 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) Original author : open Glob_ast type token = | ATOM of pattern atom | AND | OR | NOT | LPAR | RPAR | TRUE | FALSE | EOF val token : Lexing.lexbuf -> token
null
https://raw.githubusercontent.com/ocaml/ocamlbuild/792b7c8abdbc712c98ed7e69469ed354b87e125b/src/glob_lexer.mli
ocaml
********************************************************************* ocamlbuild the special exception on linking described in file ../LICENSE. *********************************************************************
, , projet Gallium , INRIA Rocquencourt Copyright 2007 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with Original author : open Glob_ast type token = | ATOM of pattern atom | AND | OR | NOT | LPAR | RPAR | TRUE | FALSE | EOF val token : Lexing.lexbuf -> token
6935aaa6c4979811fd96204639e8a5e5f524f7d766a75f56cd8b9a89a5ed3b94
expipiplus1/vulkan
XR_FB_color_space.hs
{-# language CPP #-} -- | = Name -- -- XR_FB_color_space - instance extension -- -- = Specification -- -- See -- <#XR_FB_color_space XR_FB_color_space> -- in the main specification for complete information. -- -- = Registered Extension Number -- 109 -- -- = Revision -- 1 -- -- = Extension and Version Dependencies -- - Requires OpenXR 1.0 -- -- = See Also -- -- 'ColorSpaceFB', 'SystemColorSpacePropertiesFB', -- 'enumerateColorSpacesFB', 'setColorSpaceFB' -- -- = Document Notes -- -- For more information, see the -- <#XR_FB_color_space OpenXR Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module OpenXR.Extensions.XR_FB_color_space ( enumerateColorSpacesFB , setColorSpaceFB , SystemColorSpacePropertiesFB(..) , ColorSpaceFB( COLOR_SPACE_UNMANAGED_FB , COLOR_SPACE_REC2020_FB , COLOR_SPACE_REC709_FB , COLOR_SPACE_RIFT_CV1_FB , COLOR_SPACE_RIFT_S_FB , COLOR_SPACE_QUEST_FB , COLOR_SPACE_P3_FB , COLOR_SPACE_ADOBE_RGB_FB , .. ) , FB_color_space_SPEC_VERSION , pattern FB_color_space_SPEC_VERSION , FB_COLOR_SPACE_EXTENSION_NAME , pattern FB_COLOR_SPACE_EXTENSION_NAME ) where import OpenXR.Internal.Utils (enumReadPrec) import OpenXR.Internal.Utils (enumShowsPrec) import OpenXR.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.Base (when) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import GHC.Show (showsPrec) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Data.Vector (generateM) import OpenXR.CStruct (FromCStruct) import OpenXR.CStruct (FromCStruct(..)) import OpenXR.CStruct (ToCStruct) import OpenXR.CStruct (ToCStruct(..)) import OpenXR.Zero (Zero) import OpenXR.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Data.Int (Int32) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) import Data.Word (Word32) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Data.Vector (Vector) import OpenXR.CStruct.Utils (advancePtrBytes) import OpenXR.NamedType ((:::)) import OpenXR.Dynamic (InstanceCmds(pXrEnumerateColorSpacesFB)) import OpenXR.Dynamic (InstanceCmds(pXrSetColorSpaceFB)) import OpenXR.Exception (OpenXrException(..)) import OpenXR.Core10.Enums.Result (Result) import OpenXR.Core10.Enums.Result (Result(..)) import OpenXR.Core10.Handles (Session) import OpenXR.Core10.Handles (Session(..)) import OpenXR.Core10.Handles (Session(Session)) import OpenXR.Core10.Handles (Session_T) import OpenXR.Core10.Enums.StructureType (StructureType) import OpenXR.Core10.Enums.Result (Result(SUCCESS)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_SYSTEM_COLOR_SPACE_PROPERTIES_FB)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkXrEnumerateColorSpacesFB :: FunPtr (Ptr Session_T -> Word32 -> Ptr Word32 -> Ptr ColorSpaceFB -> IO Result) -> Ptr Session_T -> Word32 -> Ptr Word32 -> Ptr ColorSpaceFB -> IO Result | xrEnumerateColorSpacesFB - Enumerates color spaces -- -- == Parameter Descriptions -- -- - @session@ is the session that enumerates the supported color spaces. -- - @colorSpaceCapacityInput@ is the capacity of the @colorSpaces@ -- array, or 0 to retrieve the required capacity. -- -- - @colorSpaceCountOutput@ is a pointer to the count of 'ColorSpaceFB' -- @colorSpaces@ written, or a pointer to the required capacity in the case that @colorSpaceCapacityInput@ is @0@. -- -- - @colorSpaces@ is a pointer to an array of 'ColorSpaceFB' color spaces , but be @NULL@ if @colorSpaceCapacityInput@ is @0@. -- -- - See -- <#buffer-size-parameters Buffer Size Parameters> -- chapter for a detailed description of retrieving the required -- @colorSpaces@ size. -- -- = Description -- -- 'enumerateColorSpacesFB' enumerates the color spaces supported by the current session . Runtimes /must/ always return identical buffer contents -- from this enumeration for the lifetime of the session. -- -- == Valid Usage (Implicit) -- - # VUID - xrEnumerateColorSpacesFB - extension - notenabled # The -- @XR_FB_color_space@ extension /must/ be enabled prior to calling -- 'enumerateColorSpacesFB' -- - # VUID - xrEnumerateColorSpacesFB - session - parameter # @session@ /must/ -- be a valid 'OpenXR.Core10.Handles.Session' handle -- - # VUID - xrEnumerateColorSpacesFB - colorSpaceCountOutput - parameter # @colorSpaceCountOutput@ /must/ be a pointer to a @uint32_t@ value -- - # VUID - xrEnumerateColorSpacesFB - colorSpaces - parameter # If @colorSpaceCapacityInput@ is not @0@ , @colorSpaces@ /must/ be a pointer to an array of @colorSpaceCapacityInput@ ' ColorSpaceFB ' -- values -- -- == Return Codes -- -- [<#fundamentals-successcodes Success>] -- - ' OpenXR.Core10.Enums . Result . SUCCESS ' -- -- - 'OpenXR.Core10.Enums.Result.SESSION_LOSS_PENDING' -- -- [<#fundamentals-errorcodes Failure>] -- -- - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST' -- - ' OpenXR.Core10.Enums . Result . ' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID' -- - ' OpenXR.Core10.Enums . Result . ERROR_SIZE_INSUFFICIENT ' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' -- -- = See Also -- -- 'ColorSpaceFB', 'OpenXR.Core10.Handles.Session', 'setColorSpaceFB' enumerateColorSpacesFB :: forall io . (MonadIO io) => -- No documentation found for Nested "xrEnumerateColorSpacesFB" "session" Session -> io (Result, ("colorSpaces" ::: Vector ColorSpaceFB)) enumerateColorSpacesFB session = liftIO . evalContT $ do let xrEnumerateColorSpacesFBPtr = pXrEnumerateColorSpacesFB (case session of Session{instanceCmds} -> instanceCmds) lift $ unless (xrEnumerateColorSpacesFBPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrEnumerateColorSpacesFB is null" Nothing Nothing let xrEnumerateColorSpacesFB' = mkXrEnumerateColorSpacesFB xrEnumerateColorSpacesFBPtr let session' = sessionHandle (session) pColorSpaceCountOutput <- ContT $ bracket (callocBytes @Word32 4) free r <- lift $ traceAroundEvent "xrEnumerateColorSpacesFB" (xrEnumerateColorSpacesFB' session' (0) (pColorSpaceCountOutput) (nullPtr)) lift $ when (r < SUCCESS) (throwIO (OpenXrException r)) colorSpaceCountOutput <- lift $ peek @Word32 pColorSpaceCountOutput pColorSpaces <- ContT $ bracket (callocBytes @ColorSpaceFB ((fromIntegral (colorSpaceCountOutput)) * 4)) free r' <- lift $ traceAroundEvent "xrEnumerateColorSpacesFB" (xrEnumerateColorSpacesFB' session' ((colorSpaceCountOutput)) (pColorSpaceCountOutput) (pColorSpaces)) lift $ when (r' < SUCCESS) (throwIO (OpenXrException r')) colorSpaceCountOutput' <- lift $ peek @Word32 pColorSpaceCountOutput colorSpaces' <- lift $ generateM (fromIntegral (colorSpaceCountOutput')) (\i -> peek @ColorSpaceFB ((pColorSpaces `advancePtrBytes` (4 * (i)) :: Ptr ColorSpaceFB))) pure $ ((r'), colorSpaces') foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkXrSetColorSpaceFB :: FunPtr (Ptr Session_T -> ColorSpaceFB -> IO Result) -> Ptr Session_T -> ColorSpaceFB -> IO Result -- | xrSetColorSpaceFB - Set a color space -- -- == Parameter Descriptions -- -- = Description -- -- 'setColorSpaceFB' provides a mechanism for an application to specify the -- color space used in the final rendered frame. If this function is not -- called, the session will use the color space deemed appropriate by the runtime . Facebook HMDs for both PC and Mobile product lines default to ' COLOR_SPACE_RIFT_CV1_FB ' . The runtime /must/ return -- 'OpenXR.Core10.Enums.Result.ERROR_COLOR_SPACE_UNSUPPORTED_FB' if -- @colorSpace@ is not one of the values enumerated by -- 'enumerateColorSpacesFB'. -- -- == Valid Usage (Implicit) -- -- - #VUID-xrSetColorSpaceFB-extension-notenabled# The -- @XR_FB_color_space@ extension /must/ be enabled prior to calling -- 'setColorSpaceFB' -- -- - #VUID-xrSetColorSpaceFB-session-parameter# @session@ /must/ be a -- valid 'OpenXR.Core10.Handles.Session' handle -- -- - #VUID-xrSetColorSpaceFB-colorspace-parameter# @colorspace@ /must/ be -- a valid 'ColorSpaceFB' value -- -- == Return Codes -- -- [<#fundamentals-successcodes Success>] -- - ' OpenXR.Core10.Enums . Result . SUCCESS ' -- -- - 'OpenXR.Core10.Enums.Result.SESSION_LOSS_PENDING' -- -- [<#fundamentals-errorcodes Failure>] -- -- - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST' -- - ' OpenXR.Core10.Enums . Result . ' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_COLOR_SPACE_UNSUPPORTED_FB' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_FEATURE_UNSUPPORTED' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED' -- -- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' -- -- = See Also -- -- 'ColorSpaceFB', 'OpenXR.Core10.Handles.Session', -- 'enumerateColorSpacesFB' setColorSpaceFB :: forall io . (MonadIO io) => -- | @session@ is a valid 'OpenXR.Core10.Handles.Session' handle. Session No documentation found for Nested " xrSetColorSpaceFB " " colorspace " ColorSpaceFB -> io (Result) setColorSpaceFB session colorspace = liftIO $ do let xrSetColorSpaceFBPtr = pXrSetColorSpaceFB (case session of Session{instanceCmds} -> instanceCmds) unless (xrSetColorSpaceFBPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrSetColorSpaceFB is null" Nothing Nothing let xrSetColorSpaceFB' = mkXrSetColorSpaceFB xrSetColorSpaceFBPtr r <- traceAroundEvent "xrSetColorSpaceFB" (xrSetColorSpaceFB' (sessionHandle (session)) (colorspace)) when (r < SUCCESS) (throwIO (OpenXrException r)) pure $ (r) -- | XrSystemColorSpacePropertiesFB - System property for color space -- -- == Valid Usage (Implicit) -- -- - #VUID-XrSystemColorSpacePropertiesFB-extension-notenabled# The -- @XR_FB_color_space@ extension /must/ be enabled prior to using -- 'SystemColorSpacePropertiesFB' -- -- - #VUID-XrSystemColorSpacePropertiesFB-type-type# @type@ /must/ be ' OpenXR.Core10.Enums . StructureType . TYPE_SYSTEM_COLOR_SPACE_PROPERTIES_FB ' -- -- - #VUID-XrSystemColorSpacePropertiesFB-next-next# @next@ /must/ be -- @NULL@ or a valid pointer to the -- <#valid-usage-for-structure-pointer-chains next structure in a structure chain> -- -- - #VUID-XrSystemColorSpacePropertiesFB-colorSpace-parameter# -- @colorSpace@ /must/ be a valid 'ColorSpaceFB' value -- -- = See Also -- ' ColorSpaceFB ' , ' OpenXR.Core10.Enums . StructureType . StructureType ' data SystemColorSpacePropertiesFB = SystemColorSpacePropertiesFB | @colorSpace@ is the native color space of the XR device . colorSpace :: ColorSpaceFB } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (SystemColorSpacePropertiesFB) #endif deriving instance Show SystemColorSpacePropertiesFB instance ToCStruct SystemColorSpacePropertiesFB where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p SystemColorSpacePropertiesFB{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_COLOR_SPACE_PROPERTIES_FB) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr ColorSpaceFB)) (colorSpace) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_COLOR_SPACE_PROPERTIES_FB) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr ColorSpaceFB)) (zero) f instance FromCStruct SystemColorSpacePropertiesFB where peekCStruct p = do colorSpace <- peek @ColorSpaceFB ((p `plusPtr` 16 :: Ptr ColorSpaceFB)) pure $ SystemColorSpacePropertiesFB colorSpace instance Storable SystemColorSpacePropertiesFB where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero SystemColorSpacePropertiesFB where zero = SystemColorSpacePropertiesFB zero -- | XrColorSpaceFB - Color Space Type -- = = -- -- = See Also -- -- 'SystemColorSpacePropertiesFB', 'enumerateColorSpacesFB', -- 'setColorSpaceFB' newtype ColorSpaceFB = ColorSpaceFB Int32 deriving newtype (Eq, Ord, Storable, Zero) -- | 'COLOR_SPACE_UNMANAGED_FB'. No color correction, not recommended for -- production use. pattern COLOR_SPACE_UNMANAGED_FB = ColorSpaceFB 0 | ' ' . Standard Rec . 2020 chromacities . This is the preferred color space for standardized color across all Oculus HMDs with -- D65 white point. pattern COLOR_SPACE_REC2020_FB = ColorSpaceFB 1 | ' COLOR_SPACE_REC709_FB ' . Standard Rec . 709 chromaticities , similar to -- sRGB. pattern COLOR_SPACE_REC709_FB = ColorSpaceFB 2 | ' COLOR_SPACE_RIFT_CV1_FB ' . Unique color space , between P3 and Adobe RGB using D75 white point . -- Color Space Details with Chromacity Primaries in CIE 1931 xy : -- - Red : ( 0.666 , 0.334 ) -- - Green : ( 0.238 , 0.714 ) -- - Blue : ( 0.139 , 0.053 ) -- - White : ( 0.298 , 0.318 ) pattern COLOR_SPACE_RIFT_CV1_FB = ColorSpaceFB 3 | ' COLOR_SPACE_RIFT_S_FB ' . Unique color space . Similar to Rec 709 using D75 . -- Color Space Details with Chromacity Primaries in CIE 1931 xy : -- - Red : ( 0.640 , 0.330 ) -- - Green : ( 0.292 , 0.586 ) -- - Blue : ( 0.156 , 0.058 ) -- - White : ( 0.298 , 0.318 ) pattern COLOR_SPACE_RIFT_S_FB = ColorSpaceFB 4 | ' COLOR_SPACE_QUEST_FB ' . Unique color space . Similar to Rift CV1 using D75 white point -- Color Space Details with Chromacity Primaries in CIE 1931 xy : -- - Red : ( 0.661 , 0.338 ) -- - Green : ( 0.228 , 0.718 ) -- - Blue : ( 0.142 , 0.042 ) -- - White : ( 0.298 , 0.318 ) pattern COLOR_SPACE_QUEST_FB = ColorSpaceFB 5 | ' COLOR_SPACE_P3_FB ' . Similar to DCI - P3 , but uses D65 white point -- instead. -- Color Space Details with Chromacity Primaries in CIE 1931 xy : -- - Red : ( 0.680 , 0.320 ) -- - Green : ( 0.265 , 0.690 ) -- - Blue : ( 0.150 , 0.060 ) -- - White : ( 0.313 , 0.329 ) pattern COLOR_SPACE_P3_FB = ColorSpaceFB 6 | ' COLOR_SPACE_ADOBE_RGB_FB ' . Standard Adobe chromacities . pattern COLOR_SPACE_ADOBE_RGB_FB = ColorSpaceFB 7 # COMPLETE COLOR_SPACE_UNMANAGED_FB , , COLOR_SPACE_REC709_FB , COLOR_SPACE_RIFT_CV1_FB , COLOR_SPACE_RIFT_S_FB , COLOR_SPACE_QUEST_FB , COLOR_SPACE_P3_FB , COLOR_SPACE_ADOBE_RGB_FB : : ColorSpaceFB # COLOR_SPACE_UNMANAGED_FB , COLOR_SPACE_REC2020_FB , COLOR_SPACE_REC709_FB , COLOR_SPACE_RIFT_CV1_FB , COLOR_SPACE_RIFT_S_FB , COLOR_SPACE_QUEST_FB , COLOR_SPACE_P3_FB , COLOR_SPACE_ADOBE_RGB_FB :: ColorSpaceFB #-} conNameColorSpaceFB :: String conNameColorSpaceFB = "ColorSpaceFB" enumPrefixColorSpaceFB :: String enumPrefixColorSpaceFB = "COLOR_SPACE_" showTableColorSpaceFB :: [(ColorSpaceFB, String)] showTableColorSpaceFB = [ (COLOR_SPACE_UNMANAGED_FB, "UNMANAGED_FB") , (COLOR_SPACE_REC2020_FB, "REC2020_FB") , (COLOR_SPACE_REC709_FB, "REC709_FB") , (COLOR_SPACE_RIFT_CV1_FB, "RIFT_CV1_FB") , (COLOR_SPACE_RIFT_S_FB, "RIFT_S_FB") , (COLOR_SPACE_QUEST_FB, "QUEST_FB") , (COLOR_SPACE_P3_FB, "P3_FB") , (COLOR_SPACE_ADOBE_RGB_FB, "ADOBE_RGB_FB") ] instance Show ColorSpaceFB where showsPrec = enumShowsPrec enumPrefixColorSpaceFB showTableColorSpaceFB conNameColorSpaceFB (\(ColorSpaceFB x) -> x) (showsPrec 11) instance Read ColorSpaceFB where readPrec = enumReadPrec enumPrefixColorSpaceFB showTableColorSpaceFB conNameColorSpaceFB ColorSpaceFB type FB_color_space_SPEC_VERSION = 1 No documentation found for TopLevel " XR_FB_color_space_SPEC_VERSION " pattern FB_color_space_SPEC_VERSION :: forall a . Integral a => a pattern FB_color_space_SPEC_VERSION = 1 type FB_COLOR_SPACE_EXTENSION_NAME = "XR_FB_color_space" No documentation found for TopLevel " " pattern FB_COLOR_SPACE_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern FB_COLOR_SPACE_EXTENSION_NAME = "XR_FB_color_space"
null
https://raw.githubusercontent.com/expipiplus1/vulkan/ebc0dde0bcd9cf251f18538de6524eb4f2ab3e9d/openxr/src/OpenXR/Extensions/XR_FB_color_space.hs
haskell
# language CPP # | = Name XR_FB_color_space - instance extension = Specification See <#XR_FB_color_space XR_FB_color_space> in the main specification for complete information. = Registered Extension Number = Revision = Extension and Version Dependencies = See Also 'ColorSpaceFB', 'SystemColorSpacePropertiesFB', 'enumerateColorSpacesFB', 'setColorSpaceFB' = Document Notes For more information, see the <#XR_FB_color_space OpenXR Specification> This page is a generated document. Fixes and changes should be made to the generator scripts, not directly. == Parameter Descriptions - @session@ is the session that enumerates the supported color spaces. array, or 0 to retrieve the required capacity. - @colorSpaceCountOutput@ is a pointer to the count of 'ColorSpaceFB' @colorSpaces@ written, or a pointer to the required capacity in the - @colorSpaces@ is a pointer to an array of 'ColorSpaceFB' color - See <#buffer-size-parameters Buffer Size Parameters> chapter for a detailed description of retrieving the required @colorSpaces@ size. = Description 'enumerateColorSpacesFB' enumerates the color spaces supported by the from this enumeration for the lifetime of the session. == Valid Usage (Implicit) @XR_FB_color_space@ extension /must/ be enabled prior to calling 'enumerateColorSpacesFB' be a valid 'OpenXR.Core10.Handles.Session' handle values == Return Codes [<#fundamentals-successcodes Success>] - 'OpenXR.Core10.Enums.Result.SESSION_LOSS_PENDING' [<#fundamentals-errorcodes Failure>] - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST' - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE' - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID' - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED' - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' = See Also 'ColorSpaceFB', 'OpenXR.Core10.Handles.Session', 'setColorSpaceFB' No documentation found for Nested "xrEnumerateColorSpacesFB" "session" | xrSetColorSpaceFB - Set a color space == Parameter Descriptions = Description 'setColorSpaceFB' provides a mechanism for an application to specify the color space used in the final rendered frame. If this function is not called, the session will use the color space deemed appropriate by the 'OpenXR.Core10.Enums.Result.ERROR_COLOR_SPACE_UNSUPPORTED_FB' if @colorSpace@ is not one of the values enumerated by 'enumerateColorSpacesFB'. == Valid Usage (Implicit) - #VUID-xrSetColorSpaceFB-extension-notenabled# The @XR_FB_color_space@ extension /must/ be enabled prior to calling 'setColorSpaceFB' - #VUID-xrSetColorSpaceFB-session-parameter# @session@ /must/ be a valid 'OpenXR.Core10.Handles.Session' handle - #VUID-xrSetColorSpaceFB-colorspace-parameter# @colorspace@ /must/ be a valid 'ColorSpaceFB' value == Return Codes [<#fundamentals-successcodes Success>] - 'OpenXR.Core10.Enums.Result.SESSION_LOSS_PENDING' [<#fundamentals-errorcodes Failure>] - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST' - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE' - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID' - 'OpenXR.Core10.Enums.Result.ERROR_COLOR_SPACE_UNSUPPORTED_FB' - 'OpenXR.Core10.Enums.Result.ERROR_FEATURE_UNSUPPORTED' - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED' - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' = See Also 'ColorSpaceFB', 'OpenXR.Core10.Handles.Session', 'enumerateColorSpacesFB' | @session@ is a valid 'OpenXR.Core10.Handles.Session' handle. | XrSystemColorSpacePropertiesFB - System property for color space == Valid Usage (Implicit) - #VUID-XrSystemColorSpacePropertiesFB-extension-notenabled# The @XR_FB_color_space@ extension /must/ be enabled prior to using 'SystemColorSpacePropertiesFB' - #VUID-XrSystemColorSpacePropertiesFB-type-type# @type@ /must/ be - #VUID-XrSystemColorSpacePropertiesFB-next-next# @next@ /must/ be @NULL@ or a valid pointer to the <#valid-usage-for-structure-pointer-chains next structure in a structure chain> - #VUID-XrSystemColorSpacePropertiesFB-colorSpace-parameter# @colorSpace@ /must/ be a valid 'ColorSpaceFB' value = See Also | XrColorSpaceFB - Color Space Type = See Also 'SystemColorSpacePropertiesFB', 'enumerateColorSpacesFB', 'setColorSpaceFB' | 'COLOR_SPACE_UNMANAGED_FB'. No color correction, not recommended for production use. D65 white point. sRGB. instead.
109 1 - Requires OpenXR 1.0 module OpenXR.Extensions.XR_FB_color_space ( enumerateColorSpacesFB , setColorSpaceFB , SystemColorSpacePropertiesFB(..) , ColorSpaceFB( COLOR_SPACE_UNMANAGED_FB , COLOR_SPACE_REC2020_FB , COLOR_SPACE_REC709_FB , COLOR_SPACE_RIFT_CV1_FB , COLOR_SPACE_RIFT_S_FB , COLOR_SPACE_QUEST_FB , COLOR_SPACE_P3_FB , COLOR_SPACE_ADOBE_RGB_FB , .. ) , FB_color_space_SPEC_VERSION , pattern FB_color_space_SPEC_VERSION , FB_COLOR_SPACE_EXTENSION_NAME , pattern FB_COLOR_SPACE_EXTENSION_NAME ) where import OpenXR.Internal.Utils (enumReadPrec) import OpenXR.Internal.Utils (enumShowsPrec) import OpenXR.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.Base (when) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import GHC.Show (showsPrec) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Data.Vector (generateM) import OpenXR.CStruct (FromCStruct) import OpenXR.CStruct (FromCStruct(..)) import OpenXR.CStruct (ToCStruct) import OpenXR.CStruct (ToCStruct(..)) import OpenXR.Zero (Zero) import OpenXR.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Data.Int (Int32) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) import Data.Word (Word32) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Data.Vector (Vector) import OpenXR.CStruct.Utils (advancePtrBytes) import OpenXR.NamedType ((:::)) import OpenXR.Dynamic (InstanceCmds(pXrEnumerateColorSpacesFB)) import OpenXR.Dynamic (InstanceCmds(pXrSetColorSpaceFB)) import OpenXR.Exception (OpenXrException(..)) import OpenXR.Core10.Enums.Result (Result) import OpenXR.Core10.Enums.Result (Result(..)) import OpenXR.Core10.Handles (Session) import OpenXR.Core10.Handles (Session(..)) import OpenXR.Core10.Handles (Session(Session)) import OpenXR.Core10.Handles (Session_T) import OpenXR.Core10.Enums.StructureType (StructureType) import OpenXR.Core10.Enums.Result (Result(SUCCESS)) import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_SYSTEM_COLOR_SPACE_PROPERTIES_FB)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkXrEnumerateColorSpacesFB :: FunPtr (Ptr Session_T -> Word32 -> Ptr Word32 -> Ptr ColorSpaceFB -> IO Result) -> Ptr Session_T -> Word32 -> Ptr Word32 -> Ptr ColorSpaceFB -> IO Result | xrEnumerateColorSpacesFB - Enumerates color spaces - @colorSpaceCapacityInput@ is the capacity of the @colorSpaces@ case that @colorSpaceCapacityInput@ is @0@. spaces , but be @NULL@ if @colorSpaceCapacityInput@ is @0@. current session . Runtimes /must/ always return identical buffer contents - # VUID - xrEnumerateColorSpacesFB - extension - notenabled # The - # VUID - xrEnumerateColorSpacesFB - session - parameter # @session@ /must/ - # VUID - xrEnumerateColorSpacesFB - colorSpaceCountOutput - parameter # @colorSpaceCountOutput@ /must/ be a pointer to a @uint32_t@ value - # VUID - xrEnumerateColorSpacesFB - colorSpaces - parameter # If @colorSpaceCapacityInput@ is not @0@ , @colorSpaces@ /must/ be a pointer to an array of @colorSpaceCapacityInput@ ' ColorSpaceFB ' - ' OpenXR.Core10.Enums . Result . SUCCESS ' - ' OpenXR.Core10.Enums . Result . ' - ' OpenXR.Core10.Enums . Result . ERROR_SIZE_INSUFFICIENT ' enumerateColorSpacesFB :: forall io . (MonadIO io) Session -> io (Result, ("colorSpaces" ::: Vector ColorSpaceFB)) enumerateColorSpacesFB session = liftIO . evalContT $ do let xrEnumerateColorSpacesFBPtr = pXrEnumerateColorSpacesFB (case session of Session{instanceCmds} -> instanceCmds) lift $ unless (xrEnumerateColorSpacesFBPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrEnumerateColorSpacesFB is null" Nothing Nothing let xrEnumerateColorSpacesFB' = mkXrEnumerateColorSpacesFB xrEnumerateColorSpacesFBPtr let session' = sessionHandle (session) pColorSpaceCountOutput <- ContT $ bracket (callocBytes @Word32 4) free r <- lift $ traceAroundEvent "xrEnumerateColorSpacesFB" (xrEnumerateColorSpacesFB' session' (0) (pColorSpaceCountOutput) (nullPtr)) lift $ when (r < SUCCESS) (throwIO (OpenXrException r)) colorSpaceCountOutput <- lift $ peek @Word32 pColorSpaceCountOutput pColorSpaces <- ContT $ bracket (callocBytes @ColorSpaceFB ((fromIntegral (colorSpaceCountOutput)) * 4)) free r' <- lift $ traceAroundEvent "xrEnumerateColorSpacesFB" (xrEnumerateColorSpacesFB' session' ((colorSpaceCountOutput)) (pColorSpaceCountOutput) (pColorSpaces)) lift $ when (r' < SUCCESS) (throwIO (OpenXrException r')) colorSpaceCountOutput' <- lift $ peek @Word32 pColorSpaceCountOutput colorSpaces' <- lift $ generateM (fromIntegral (colorSpaceCountOutput')) (\i -> peek @ColorSpaceFB ((pColorSpaces `advancePtrBytes` (4 * (i)) :: Ptr ColorSpaceFB))) pure $ ((r'), colorSpaces') foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkXrSetColorSpaceFB :: FunPtr (Ptr Session_T -> ColorSpaceFB -> IO Result) -> Ptr Session_T -> ColorSpaceFB -> IO Result runtime . Facebook HMDs for both PC and Mobile product lines default to ' COLOR_SPACE_RIFT_CV1_FB ' . The runtime /must/ return - ' OpenXR.Core10.Enums . Result . SUCCESS ' - ' OpenXR.Core10.Enums . Result . ' setColorSpaceFB :: forall io . (MonadIO io) Session No documentation found for Nested " xrSetColorSpaceFB " " colorspace " ColorSpaceFB -> io (Result) setColorSpaceFB session colorspace = liftIO $ do let xrSetColorSpaceFBPtr = pXrSetColorSpaceFB (case session of Session{instanceCmds} -> instanceCmds) unless (xrSetColorSpaceFBPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrSetColorSpaceFB is null" Nothing Nothing let xrSetColorSpaceFB' = mkXrSetColorSpaceFB xrSetColorSpaceFBPtr r <- traceAroundEvent "xrSetColorSpaceFB" (xrSetColorSpaceFB' (sessionHandle (session)) (colorspace)) when (r < SUCCESS) (throwIO (OpenXrException r)) pure $ (r) ' OpenXR.Core10.Enums . StructureType . TYPE_SYSTEM_COLOR_SPACE_PROPERTIES_FB ' ' ColorSpaceFB ' , ' OpenXR.Core10.Enums . StructureType . StructureType ' data SystemColorSpacePropertiesFB = SystemColorSpacePropertiesFB | @colorSpace@ is the native color space of the XR device . colorSpace :: ColorSpaceFB } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (SystemColorSpacePropertiesFB) #endif deriving instance Show SystemColorSpacePropertiesFB instance ToCStruct SystemColorSpacePropertiesFB where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p SystemColorSpacePropertiesFB{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_COLOR_SPACE_PROPERTIES_FB) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr ColorSpaceFB)) (colorSpace) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_COLOR_SPACE_PROPERTIES_FB) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr ColorSpaceFB)) (zero) f instance FromCStruct SystemColorSpacePropertiesFB where peekCStruct p = do colorSpace <- peek @ColorSpaceFB ((p `plusPtr` 16 :: Ptr ColorSpaceFB)) pure $ SystemColorSpacePropertiesFB colorSpace instance Storable SystemColorSpacePropertiesFB where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero SystemColorSpacePropertiesFB where zero = SystemColorSpacePropertiesFB zero = = newtype ColorSpaceFB = ColorSpaceFB Int32 deriving newtype (Eq, Ord, Storable, Zero) pattern COLOR_SPACE_UNMANAGED_FB = ColorSpaceFB 0 | ' ' . Standard Rec . 2020 chromacities . This is the preferred color space for standardized color across all Oculus HMDs with pattern COLOR_SPACE_REC2020_FB = ColorSpaceFB 1 | ' COLOR_SPACE_REC709_FB ' . Standard Rec . 709 chromaticities , similar to pattern COLOR_SPACE_REC709_FB = ColorSpaceFB 2 | ' COLOR_SPACE_RIFT_CV1_FB ' . Unique color space , between P3 and Adobe RGB using D75 white point . Color Space Details with Chromacity Primaries in CIE 1931 xy : - Red : ( 0.666 , 0.334 ) - Green : ( 0.238 , 0.714 ) - Blue : ( 0.139 , 0.053 ) - White : ( 0.298 , 0.318 ) pattern COLOR_SPACE_RIFT_CV1_FB = ColorSpaceFB 3 | ' COLOR_SPACE_RIFT_S_FB ' . Unique color space . Similar to Rec 709 using D75 . Color Space Details with Chromacity Primaries in CIE 1931 xy : - Red : ( 0.640 , 0.330 ) - Green : ( 0.292 , 0.586 ) - Blue : ( 0.156 , 0.058 ) - White : ( 0.298 , 0.318 ) pattern COLOR_SPACE_RIFT_S_FB = ColorSpaceFB 4 | ' COLOR_SPACE_QUEST_FB ' . Unique color space . Similar to Rift CV1 using D75 white point Color Space Details with Chromacity Primaries in CIE 1931 xy : - Red : ( 0.661 , 0.338 ) - Green : ( 0.228 , 0.718 ) - Blue : ( 0.142 , 0.042 ) - White : ( 0.298 , 0.318 ) pattern COLOR_SPACE_QUEST_FB = ColorSpaceFB 5 | ' COLOR_SPACE_P3_FB ' . Similar to DCI - P3 , but uses D65 white point Color Space Details with Chromacity Primaries in CIE 1931 xy : - Red : ( 0.680 , 0.320 ) - Green : ( 0.265 , 0.690 ) - Blue : ( 0.150 , 0.060 ) - White : ( 0.313 , 0.329 ) pattern COLOR_SPACE_P3_FB = ColorSpaceFB 6 | ' COLOR_SPACE_ADOBE_RGB_FB ' . Standard Adobe chromacities . pattern COLOR_SPACE_ADOBE_RGB_FB = ColorSpaceFB 7 # COMPLETE COLOR_SPACE_UNMANAGED_FB , , COLOR_SPACE_REC709_FB , COLOR_SPACE_RIFT_CV1_FB , COLOR_SPACE_RIFT_S_FB , COLOR_SPACE_QUEST_FB , COLOR_SPACE_P3_FB , COLOR_SPACE_ADOBE_RGB_FB : : ColorSpaceFB # COLOR_SPACE_UNMANAGED_FB , COLOR_SPACE_REC2020_FB , COLOR_SPACE_REC709_FB , COLOR_SPACE_RIFT_CV1_FB , COLOR_SPACE_RIFT_S_FB , COLOR_SPACE_QUEST_FB , COLOR_SPACE_P3_FB , COLOR_SPACE_ADOBE_RGB_FB :: ColorSpaceFB #-} conNameColorSpaceFB :: String conNameColorSpaceFB = "ColorSpaceFB" enumPrefixColorSpaceFB :: String enumPrefixColorSpaceFB = "COLOR_SPACE_" showTableColorSpaceFB :: [(ColorSpaceFB, String)] showTableColorSpaceFB = [ (COLOR_SPACE_UNMANAGED_FB, "UNMANAGED_FB") , (COLOR_SPACE_REC2020_FB, "REC2020_FB") , (COLOR_SPACE_REC709_FB, "REC709_FB") , (COLOR_SPACE_RIFT_CV1_FB, "RIFT_CV1_FB") , (COLOR_SPACE_RIFT_S_FB, "RIFT_S_FB") , (COLOR_SPACE_QUEST_FB, "QUEST_FB") , (COLOR_SPACE_P3_FB, "P3_FB") , (COLOR_SPACE_ADOBE_RGB_FB, "ADOBE_RGB_FB") ] instance Show ColorSpaceFB where showsPrec = enumShowsPrec enumPrefixColorSpaceFB showTableColorSpaceFB conNameColorSpaceFB (\(ColorSpaceFB x) -> x) (showsPrec 11) instance Read ColorSpaceFB where readPrec = enumReadPrec enumPrefixColorSpaceFB showTableColorSpaceFB conNameColorSpaceFB ColorSpaceFB type FB_color_space_SPEC_VERSION = 1 No documentation found for TopLevel " XR_FB_color_space_SPEC_VERSION " pattern FB_color_space_SPEC_VERSION :: forall a . Integral a => a pattern FB_color_space_SPEC_VERSION = 1 type FB_COLOR_SPACE_EXTENSION_NAME = "XR_FB_color_space" No documentation found for TopLevel " " pattern FB_COLOR_SPACE_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern FB_COLOR_SPACE_EXTENSION_NAME = "XR_FB_color_space"
932f3b9528e2bb6606bbaadcd1b3b6d03d4dffa65bc644c4352c62c6176a28a4
MaskRay/99-problems-ocaml
19.ml
let split xs n = let rec go acc n = function | [] -> List.rev acc, [] | h::t as a -> if n == 0 then List.rev acc, a else go (h::acc) (n-1) t in go [] n xs let rotate xs n = if xs = [] then [] else begin let len = List.length xs in let (a,b) = split xs (n mod len) in b @ a end
null
https://raw.githubusercontent.com/MaskRay/99-problems-ocaml/652604f13ba7a73eee06d359b4db549b49ec9bb3/11-20/19.ml
ocaml
let split xs n = let rec go acc n = function | [] -> List.rev acc, [] | h::t as a -> if n == 0 then List.rev acc, a else go (h::acc) (n-1) t in go [] n xs let rotate xs n = if xs = [] then [] else begin let len = List.length xs in let (a,b) = split xs (n mod len) in b @ a end
67459e334ba355a2a457e304f63a2d78ae9541799687f7db36b985abfa0e49e0
rudymatela/express
TH.hs
# LANGUAGE TemplateHaskell , CPP # -- | -- Module : Data.Express.Name.Derive Copyright : ( c ) 2019 - 2021 License : 3 - Clause BSD ( see the file LICENSE ) Maintainer : < > -- Template Haskell utilities . module Data.Express.Utils.TH ( reallyDeriveCascading , deriveWhenNeeded , deriveWhenNeededOrWarn , typeConArgs , typeConArgsThat , typeConCascadingArgsThat , normalizeType , normalizeTypeUnits , isInstanceOf , isntInstanceOf , typeArity , typeConstructors , isTypeSynonym , typeSynonymType , mergeIFns , mergeI , lookupValN , showJustName , typeConstructorsArgNames , (|=>|) , (|++|) , whereI , unboundVars , toBounded , toBoundedQ , module Language.Haskell.TH ) where import Control.Monad import Data.List import Language.Haskell.TH import Language.Haskell.TH.Lib deriveWhenNeeded :: Name -> (Name -> DecsQ) -> Name -> DecsQ deriveWhenNeeded = deriveWhenNeededX False deriveWhenNeededOrWarn :: Name -> (Name -> DecsQ) -> Name -> DecsQ deriveWhenNeededOrWarn = deriveWhenNeededX True deriveWhenNeededX :: Bool -> Name -> (Name -> DecsQ) -> Name -> DecsQ deriveWhenNeededX warnExisting cls reallyDerive t = do is <- t `isInstanceOf` cls if is then do unless (not warnExisting) (reportWarning $ "Instance " ++ showJustName cls ++ " " ++ showJustName t ++ " already exists, skipping derivation") return [] else reallyDerive t -- | Encodes a ' Name ' as a ' String ' . -- This is useful when generating error messages. -- -- > > showJustName ''Int -- > "Int" -- -- > > showJustName ''String -- > "String" -- -- > > showJustName ''Maybe -- > "Maybe" showJustName :: Name -> String showJustName = reverse . takeWhile (/= '.') . reverse . show reallyDeriveCascading :: Name -> (Name -> DecsQ) -> Name -> DecsQ reallyDeriveCascading cls reallyDerive t = return . concat =<< mapM reallyDerive =<< filterM (liftM not . isTypeSynonym) =<< return . (t:) . delete t =<< t `typeConCascadingArgsThat` (`isntInstanceOf` cls) typeConArgs :: Name -> Q [Name] typeConArgs t = do is <- isTypeSynonym t if is then liftM typeConTs $ typeSynonymType t else liftM (nubMerges . map typeConTs . concat . map snd) $ typeConstructors t where typeConTs :: Type -> [Name] typeConTs (AppT t1 t2) = typeConTs t1 `nubMerge` typeConTs t2 typeConTs (SigT t _) = typeConTs t typeConTs (VarT _) = [] typeConTs (ConT n) = [n] #if __GLASGOW_HASKELL__ >= 800 -- typeConTs (PromotedT n) = [n] ? typeConTs (InfixT t1 n t2) = typeConTs t1 `nubMerge` typeConTs t2 typeConTs (UInfixT t1 n t2) = typeConTs t1 `nubMerge` typeConTs t2 typeConTs (ParensT t) = typeConTs t #endif typeConTs _ = [] typeConArgsThat :: Name -> (Name -> Q Bool) -> Q [Name] typeConArgsThat t p = do targs <- typeConArgs t tbs <- mapM (\t' -> do is <- p t'; return (t',is)) targs return [t' | (t',p) <- tbs, p] typeConCascadingArgsThat :: Name -> (Name -> Q Bool) -> Q [Name] t `typeConCascadingArgsThat` p = do ts <- t `typeConArgsThat` p let p' t' = do is <- p t'; return $ t' `notElem` (t:ts) && is tss <- mapM (`typeConCascadingArgsThat` p') ts return $ nubMerges (ts:tss) -- | Normalizes a type by applying it to necessary type variables making it accept zero type parameters . -- The normalized type is paired with a list of necessary type variables. -- -- > > putStrLn $(stringE . show =<< normalizeType ''Int) -- > (ConT ''Int, []) -- -- > > putStrLn $(stringE . show =<< normalizeType ''Maybe) > ( AppT ( ConT '' Maybe ) ( VarT '' a),[VarT '' a ] ) -- -- > > putStrLn $(stringE . show =<< normalizeType ''Either) -- > (AppT (AppT (ConT ''Either) (VarT ''a)) (VarT ''b),[VarT ''a,VarT ''b]) -- -- > > putStrLn $(stringE . show =<< normalizeType ''[]) > ( AppT ( ConT '' [ ] ) ( VarT a),[VarT a ] ) normalizeType :: Name -> Q (Type, [Type]) normalizeType t = do ar <- typeArity t vs <- newVarTs ar return (foldl AppT (ConT t) vs, vs) where newNames :: [String] -> Q [Name] newNames = mapM newName newVarTs :: Int -> Q [Type] newVarTs n = liftM (map VarT) $ newNames (take n . map (:[]) $ cycle ['a'..'z']) -- | Normalizes a type by applying it to units to make it star - kinded . -- (cf. 'normalizeType') normalizeTypeUnits :: Name -> Q Type normalizeTypeUnits t = do ar <- typeArity t return (foldl AppT (ConT t) (replicate ar (TupleT 0))) -- | -- Given a type name and a class name, -- returns whether the type is an instance of that class. -- The given type must be star-kinded (@ * @) -- and the given class double-star-kinded (@ * -> * @. -- > > putStrLn $ ( stringE . show = < < '' Int ` isInstanceOf ` '' ) -- > True -- -- > > putStrLn $(stringE . show =<< ''Int `isInstanceOf` ''Fractional) -- > False isInstanceOf :: Name -> Name -> Q Bool isInstanceOf tn cl = do ty <- normalizeTypeUnits tn isInstance cl [ty] -- | -- The negation of 'isInstanceOf'. isntInstanceOf :: Name -> Name -> Q Bool isntInstanceOf tn cl = liftM not (isInstanceOf tn cl) -- | Given a type name, return the number of arguments taken by that type. Examples in partially broken TH : -- -- > > putStrLn $(stringE . show =<< typeArity ''Int) -- > 0 -- -- > > putStrLn $(stringE . show =<< typeArity ''Maybe) > 1 -- -- > > putStrLn $(stringE . show =<< typeArity ''Either) > 2 -- -- > > putStrLn $(stringE . show =<< typeArity ''[]) > 1 -- -- > > putStrLn $(stringE . show =<< typeArity ''(,)) > 2 -- -- > > putStrLn $(stringE . show =<< typeArity ''(,,)) > 3 -- -- > > putStrLn $(stringE . show =<< typeArity ''String) -- > 0 -- This works for Data 's and Newtype 's and it is useful when generating -- typeclass instances. typeArity :: Name -> Q Int typeArity t = do ti <- reify t return . length $ case ti of #if __GLASGOW_HASKELL__ < 800 TyConI (DataD _ _ ks _ _) -> ks TyConI (NewtypeD _ _ ks _ _) -> ks #else TyConI (DataD _ _ ks _ _ _) -> ks TyConI (NewtypeD _ _ ks _ _ _) -> ks #endif TyConI (TySynD _ ks _) -> ks _ -> error $ "error (typeArity): symbol " ++ show t ++ " is not a newtype, data or type synonym" -- | -- Given a type 'Name', -- returns a list of its type constructor 'Name's -- paired with the type arguments they take. -- the type arguments they take. -- > > putStrLn $ ( stringE . show = < < typeConstructors '' ) -- > [ ('False, []) -- > , ('True, []) -- > ] -- -- > > putStrLn $(stringE . show =<< typeConstructors ''[]) -- > [ ('[], []) -- > , ('(:), [VarT ''a, AppT ListT (VarT ''a)]) -- > ] -- -- > > putStrLn $(stringE . show =<< typeConstructors ''(,)) -- > [('(,), [VarT (mkName "a"), VarT (mkName "b")])] -- -- > > data Point = Pt Int Int -- > > putStrLn $(stringE . show =<< typeConstructors ''Point) -- > [('Pt,[ConT ''Int, ConT ''Int])] typeConstructors :: Name -> Q [(Name,[Type])] typeConstructors t = do ti <- reify t return . map simplify $ case ti of #if __GLASGOW_HASKELL__ < 800 TyConI (DataD _ _ _ cs _) -> cs TyConI (NewtypeD _ _ _ c _) -> [c] #else TyConI (DataD _ _ _ _ cs _) -> cs TyConI (NewtypeD _ _ _ _ c _) -> [c] #endif _ -> error $ "error (typeConstructors): symbol " ++ show t ++ " is neither newtype nor data" where simplify (NormalC n ts) = (n,map snd ts) simplify (RecC n ts) = (n,map trd ts) simplify (InfixC t1 n t2) = (n,[snd t1,snd t2]) trd (x,y,z) = z -- | -- Is the given 'Name' a type synonym? -- -- > > putStrLn $(stringE . show =<< isTypeSynonym 'show) -- > False -- > > putStrLn $ ( stringE . show = < < isTypeSynonym '' ) -- > False -- -- > > putStrLn $(stringE . show =<< isTypeSynonym ''String) -- > True isTypeSynonym :: Name -> Q Bool isTypeSynonym t = do ti <- reify t return $ case ti of TyConI (TySynD _ _ _) -> True _ -> False -- | Resolves a type synonym . -- -- > > putStrLn $(stringE . show =<< typeSynonymType ''String) > AppT ListT ( ConT '' ) typeSynonymType :: Name -> Q Type typeSynonymType t = do ti <- reify t return $ case ti of TyConI (TySynD _ _ t') -> t' _ -> error $ "error (typeSynonymType): symbol " ++ show t ++ " is not a type synonym" -- Append to instance contexts in a declaration. -- -- > sequence [[|Eq b|],[|Eq c|]] |=>| [t|instance Eq a => Cl (Ty a) where f=g|] > = = [ t| instance ( Eq a , Eq b , Eq c ) = > Cl ( Ty a ) where f = g | ] (|=>|) :: Cxt -> DecsQ -> DecsQ c |=>| qds = do ds <- qds return $ map (`ac` c) ds #if __GLASGOW_HASKELL__ < 800 where ac (InstanceD c ts ds) c' = InstanceD (c++c') ts ds ac d _ = d #else where ac (InstanceD o c ts ds) c' = InstanceD o (c++c') ts ds ac d _ = d #endif (|++|) :: DecsQ -> DecsQ -> DecsQ (|++|) = liftM2 (++) mergeIFns :: DecsQ -> DecsQ mergeIFns qds = do ds <- qds return $ map m' ds where #if __GLASGOW_HASKELL__ < 800 m' (InstanceD c ts ds) = InstanceD c ts [foldr1 m ds] #else m' (InstanceD o c ts ds) = InstanceD o c ts [foldr1 m ds] #endif FunD n cs1 `m` FunD _ cs2 = FunD n (cs1 ++ cs2) mergeI :: DecsQ -> DecsQ -> DecsQ qds1 `mergeI` qds2 = do ds1 <- qds1 ds2 <- qds2 return $ ds1 `m` ds2 where #if __GLASGOW_HASKELL__ < 800 [InstanceD c ts ds1] `m` [InstanceD _ _ ds2] = [InstanceD c ts (ds1 ++ ds2)] #else [InstanceD o c ts ds1] `m` [InstanceD _ _ _ ds2] = [InstanceD o c ts (ds1 ++ ds2)] #endif whereI :: DecsQ -> [Dec] -> DecsQ qds `whereI` w = do ds <- qds return $ map (`aw` w) ds #if __GLASGOW_HASKELL__ < 800 where aw (InstanceD c ts ds) w' = InstanceD c ts (ds++w') aw d _ = d #else where aw (InstanceD o c ts ds) w' = InstanceD o c ts (ds++w') aw d _ = d #endif -- > nubMerge xs ys == nub (merge xs ys) -- > nubMerge xs ys == nub (sort (xs ++ ys)) nubMerge :: Ord a => [a] -> [a] -> [a] nubMerge [] ys = ys nubMerge xs [] = xs nubMerge (x:xs) (y:ys) | x < y = x : xs `nubMerge` (y:ys) | x > y = y : (x:xs) `nubMerge` ys | otherwise = x : xs `nubMerge` ys nubMerges :: Ord a => [[a]] -> [a] nubMerges = foldr nubMerge [] typeConstructorsArgNames :: Name -> Q [(Name,[Name])] typeConstructorsArgNames t = do cs <- typeConstructors t sequence [ do ns <- sequence [newName "x" | _ <- ts] return (c,ns) | (c,ts) <- cs ] -- | Lookups the name of a value -- throwing an error when it is not found. -- -- > > putStrLn $(stringE . show =<< lookupValN "show") -- > 'show lookupValN :: String -> Q Name lookupValN s = do mn <- lookupValueName s case mn of Just n -> return n Nothing -> fail $ "lookupValN: cannot find " ++ s -- | Lists all unbound variables in a type. -- This intentionally excludes the 'ForallT' constructor. unboundVars :: Type -> [Name] unboundVars (VarT n) = [n] unboundVars (AppT t1 t2) = nubMerge (unboundVars t1) (unboundVars t2) unboundVars (SigT t _) = unboundVars t unboundVars (ForallT vs _ t) = unboundVars t \\ map nm vs where #if __GLASGOW_HASKELL__ < 900 nm (PlainTV n) = n nm (KindedTV n _) = n #else nm (PlainTV n _) = n nm (KindedTV n _ _) = n #endif unboundVars _ = [] -- | Binds all unbound variables using a 'ForallT' constructor. -- (cf. 'unboundVars') toBounded :: Type -> Type #if __GLASGOW_HASKELL__ < 900 toBounded t = ForallT [PlainTV n | n <- unboundVars t] [] t #else toBounded t = ForallT [PlainTV n SpecifiedSpec | n <- unboundVars t] [] t #endif -- | Same as toBounded but lifted over 'Q' toBoundedQ :: TypeQ -> TypeQ toBoundedQ = liftM toBounded
null
https://raw.githubusercontent.com/rudymatela/express/936212c3cbe441f8144bcced502da023e8b2412d/src/Data/Express/Utils/TH.hs
haskell
| Module : Data.Express.Name.Derive | This is useful when generating error messages. > > showJustName ''Int > "Int" > > showJustName ''String > "String" > > showJustName ''Maybe > "Maybe" typeConTs (PromotedT n) = [n] ? | The normalized type is paired with a list of necessary type variables. > > putStrLn $(stringE . show =<< normalizeType ''Int) > (ConT ''Int, []) > > putStrLn $(stringE . show =<< normalizeType ''Maybe) > > putStrLn $(stringE . show =<< normalizeType ''Either) > (AppT (AppT (ConT ''Either) (VarT ''a)) (VarT ''b),[VarT ''a,VarT ''b]) > > putStrLn $(stringE . show =<< normalizeType ''[]) | (cf. 'normalizeType') | Given a type name and a class name, returns whether the type is an instance of that class. The given type must be star-kinded (@ * @) and the given class double-star-kinded (@ * -> * @. > True > > putStrLn $(stringE . show =<< ''Int `isInstanceOf` ''Fractional) > False | The negation of 'isInstanceOf'. | Given a type name, return the number of arguments taken by that type. > > putStrLn $(stringE . show =<< typeArity ''Int) > 0 > > putStrLn $(stringE . show =<< typeArity ''Maybe) > > putStrLn $(stringE . show =<< typeArity ''Either) > > putStrLn $(stringE . show =<< typeArity ''[]) > > putStrLn $(stringE . show =<< typeArity ''(,)) > > putStrLn $(stringE . show =<< typeArity ''(,,)) > > putStrLn $(stringE . show =<< typeArity ''String) > 0 typeclass instances. | Given a type 'Name', returns a list of its type constructor 'Name's paired with the type arguments they take. the type arguments they take. > [ ('False, []) > , ('True, []) > ] > > putStrLn $(stringE . show =<< typeConstructors ''[]) > [ ('[], []) > , ('(:), [VarT ''a, AppT ListT (VarT ''a)]) > ] > > putStrLn $(stringE . show =<< typeConstructors ''(,)) > [('(,), [VarT (mkName "a"), VarT (mkName "b")])] > > data Point = Pt Int Int > > putStrLn $(stringE . show =<< typeConstructors ''Point) > [('Pt,[ConT ''Int, ConT ''Int])] | Is the given 'Name' a type synonym? > > putStrLn $(stringE . show =<< isTypeSynonym 'show) > False > False > > putStrLn $(stringE . show =<< isTypeSynonym ''String) > True | > > putStrLn $(stringE . show =<< typeSynonymType ''String) Append to instance contexts in a declaration. > sequence [[|Eq b|],[|Eq c|]] |=>| [t|instance Eq a => Cl (Ty a) where f=g|] > nubMerge xs ys == nub (merge xs ys) > nubMerge xs ys == nub (sort (xs ++ ys)) | Lookups the name of a value throwing an error when it is not found. > > putStrLn $(stringE . show =<< lookupValN "show") > 'show | Lists all unbound variables in a type. This intentionally excludes the 'ForallT' constructor. | Binds all unbound variables using a 'ForallT' constructor. (cf. 'unboundVars') | Same as toBounded but lifted over 'Q'
# LANGUAGE TemplateHaskell , CPP # Copyright : ( c ) 2019 - 2021 License : 3 - Clause BSD ( see the file LICENSE ) Maintainer : < > Template Haskell utilities . module Data.Express.Utils.TH ( reallyDeriveCascading , deriveWhenNeeded , deriveWhenNeededOrWarn , typeConArgs , typeConArgsThat , typeConCascadingArgsThat , normalizeType , normalizeTypeUnits , isInstanceOf , isntInstanceOf , typeArity , typeConstructors , isTypeSynonym , typeSynonymType , mergeIFns , mergeI , lookupValN , showJustName , typeConstructorsArgNames , (|=>|) , (|++|) , whereI , unboundVars , toBounded , toBoundedQ , module Language.Haskell.TH ) where import Control.Monad import Data.List import Language.Haskell.TH import Language.Haskell.TH.Lib deriveWhenNeeded :: Name -> (Name -> DecsQ) -> Name -> DecsQ deriveWhenNeeded = deriveWhenNeededX False deriveWhenNeededOrWarn :: Name -> (Name -> DecsQ) -> Name -> DecsQ deriveWhenNeededOrWarn = deriveWhenNeededX True deriveWhenNeededX :: Bool -> Name -> (Name -> DecsQ) -> Name -> DecsQ deriveWhenNeededX warnExisting cls reallyDerive t = do is <- t `isInstanceOf` cls if is then do unless (not warnExisting) (reportWarning $ "Instance " ++ showJustName cls ++ " " ++ showJustName t ++ " already exists, skipping derivation") return [] else reallyDerive t Encodes a ' Name ' as a ' String ' . showJustName :: Name -> String showJustName = reverse . takeWhile (/= '.') . reverse . show reallyDeriveCascading :: Name -> (Name -> DecsQ) -> Name -> DecsQ reallyDeriveCascading cls reallyDerive t = return . concat =<< mapM reallyDerive =<< filterM (liftM not . isTypeSynonym) =<< return . (t:) . delete t =<< t `typeConCascadingArgsThat` (`isntInstanceOf` cls) typeConArgs :: Name -> Q [Name] typeConArgs t = do is <- isTypeSynonym t if is then liftM typeConTs $ typeSynonymType t else liftM (nubMerges . map typeConTs . concat . map snd) $ typeConstructors t where typeConTs :: Type -> [Name] typeConTs (AppT t1 t2) = typeConTs t1 `nubMerge` typeConTs t2 typeConTs (SigT t _) = typeConTs t typeConTs (VarT _) = [] typeConTs (ConT n) = [n] #if __GLASGOW_HASKELL__ >= 800 typeConTs (InfixT t1 n t2) = typeConTs t1 `nubMerge` typeConTs t2 typeConTs (UInfixT t1 n t2) = typeConTs t1 `nubMerge` typeConTs t2 typeConTs (ParensT t) = typeConTs t #endif typeConTs _ = [] typeConArgsThat :: Name -> (Name -> Q Bool) -> Q [Name] typeConArgsThat t p = do targs <- typeConArgs t tbs <- mapM (\t' -> do is <- p t'; return (t',is)) targs return [t' | (t',p) <- tbs, p] typeConCascadingArgsThat :: Name -> (Name -> Q Bool) -> Q [Name] t `typeConCascadingArgsThat` p = do ts <- t `typeConArgsThat` p let p' t' = do is <- p t'; return $ t' `notElem` (t:ts) && is tss <- mapM (`typeConCascadingArgsThat` p') ts return $ nubMerges (ts:tss) Normalizes a type by applying it to necessary type variables making it accept zero type parameters . > ( AppT ( ConT '' Maybe ) ( VarT '' a),[VarT '' a ] ) > ( AppT ( ConT '' [ ] ) ( VarT a),[VarT a ] ) normalizeType :: Name -> Q (Type, [Type]) normalizeType t = do ar <- typeArity t vs <- newVarTs ar return (foldl AppT (ConT t) vs, vs) where newNames :: [String] -> Q [Name] newNames = mapM newName newVarTs :: Int -> Q [Type] newVarTs n = liftM (map VarT) $ newNames (take n . map (:[]) $ cycle ['a'..'z']) Normalizes a type by applying it to units to make it star - kinded . normalizeTypeUnits :: Name -> Q Type normalizeTypeUnits t = do ar <- typeArity t return (foldl AppT (ConT t) (replicate ar (TupleT 0))) > > putStrLn $ ( stringE . show = < < '' Int ` isInstanceOf ` '' ) isInstanceOf :: Name -> Name -> Q Bool isInstanceOf tn cl = do ty <- normalizeTypeUnits tn isInstance cl [ty] isntInstanceOf :: Name -> Name -> Q Bool isntInstanceOf tn cl = liftM not (isInstanceOf tn cl) Examples in partially broken TH : > 1 > 2 > 1 > 2 > 3 This works for Data 's and Newtype 's and it is useful when generating typeArity :: Name -> Q Int typeArity t = do ti <- reify t return . length $ case ti of #if __GLASGOW_HASKELL__ < 800 TyConI (DataD _ _ ks _ _) -> ks TyConI (NewtypeD _ _ ks _ _) -> ks #else TyConI (DataD _ _ ks _ _ _) -> ks TyConI (NewtypeD _ _ ks _ _ _) -> ks #endif TyConI (TySynD _ ks _) -> ks _ -> error $ "error (typeArity): symbol " ++ show t ++ " is not a newtype, data or type synonym" > > putStrLn $ ( stringE . show = < < typeConstructors '' ) typeConstructors :: Name -> Q [(Name,[Type])] typeConstructors t = do ti <- reify t return . map simplify $ case ti of #if __GLASGOW_HASKELL__ < 800 TyConI (DataD _ _ _ cs _) -> cs TyConI (NewtypeD _ _ _ c _) -> [c] #else TyConI (DataD _ _ _ _ cs _) -> cs TyConI (NewtypeD _ _ _ _ c _) -> [c] #endif _ -> error $ "error (typeConstructors): symbol " ++ show t ++ " is neither newtype nor data" where simplify (NormalC n ts) = (n,map snd ts) simplify (RecC n ts) = (n,map trd ts) simplify (InfixC t1 n t2) = (n,[snd t1,snd t2]) trd (x,y,z) = z > > putStrLn $ ( stringE . show = < < isTypeSynonym '' ) isTypeSynonym :: Name -> Q Bool isTypeSynonym t = do ti <- reify t return $ case ti of TyConI (TySynD _ _ _) -> True _ -> False Resolves a type synonym . > AppT ListT ( ConT '' ) typeSynonymType :: Name -> Q Type typeSynonymType t = do ti <- reify t return $ case ti of TyConI (TySynD _ _ t') -> t' _ -> error $ "error (typeSynonymType): symbol " ++ show t ++ " is not a type synonym" > = = [ t| instance ( Eq a , Eq b , Eq c ) = > Cl ( Ty a ) where f = g | ] (|=>|) :: Cxt -> DecsQ -> DecsQ c |=>| qds = do ds <- qds return $ map (`ac` c) ds #if __GLASGOW_HASKELL__ < 800 where ac (InstanceD c ts ds) c' = InstanceD (c++c') ts ds ac d _ = d #else where ac (InstanceD o c ts ds) c' = InstanceD o (c++c') ts ds ac d _ = d #endif (|++|) :: DecsQ -> DecsQ -> DecsQ (|++|) = liftM2 (++) mergeIFns :: DecsQ -> DecsQ mergeIFns qds = do ds <- qds return $ map m' ds where #if __GLASGOW_HASKELL__ < 800 m' (InstanceD c ts ds) = InstanceD c ts [foldr1 m ds] #else m' (InstanceD o c ts ds) = InstanceD o c ts [foldr1 m ds] #endif FunD n cs1 `m` FunD _ cs2 = FunD n (cs1 ++ cs2) mergeI :: DecsQ -> DecsQ -> DecsQ qds1 `mergeI` qds2 = do ds1 <- qds1 ds2 <- qds2 return $ ds1 `m` ds2 where #if __GLASGOW_HASKELL__ < 800 [InstanceD c ts ds1] `m` [InstanceD _ _ ds2] = [InstanceD c ts (ds1 ++ ds2)] #else [InstanceD o c ts ds1] `m` [InstanceD _ _ _ ds2] = [InstanceD o c ts (ds1 ++ ds2)] #endif whereI :: DecsQ -> [Dec] -> DecsQ qds `whereI` w = do ds <- qds return $ map (`aw` w) ds #if __GLASGOW_HASKELL__ < 800 where aw (InstanceD c ts ds) w' = InstanceD c ts (ds++w') aw d _ = d #else where aw (InstanceD o c ts ds) w' = InstanceD o c ts (ds++w') aw d _ = d #endif nubMerge :: Ord a => [a] -> [a] -> [a] nubMerge [] ys = ys nubMerge xs [] = xs nubMerge (x:xs) (y:ys) | x < y = x : xs `nubMerge` (y:ys) | x > y = y : (x:xs) `nubMerge` ys | otherwise = x : xs `nubMerge` ys nubMerges :: Ord a => [[a]] -> [a] nubMerges = foldr nubMerge [] typeConstructorsArgNames :: Name -> Q [(Name,[Name])] typeConstructorsArgNames t = do cs <- typeConstructors t sequence [ do ns <- sequence [newName "x" | _ <- ts] return (c,ns) | (c,ts) <- cs ] lookupValN :: String -> Q Name lookupValN s = do mn <- lookupValueName s case mn of Just n -> return n Nothing -> fail $ "lookupValN: cannot find " ++ s unboundVars :: Type -> [Name] unboundVars (VarT n) = [n] unboundVars (AppT t1 t2) = nubMerge (unboundVars t1) (unboundVars t2) unboundVars (SigT t _) = unboundVars t unboundVars (ForallT vs _ t) = unboundVars t \\ map nm vs where #if __GLASGOW_HASKELL__ < 900 nm (PlainTV n) = n nm (KindedTV n _) = n #else nm (PlainTV n _) = n nm (KindedTV n _ _) = n #endif unboundVars _ = [] toBounded :: Type -> Type #if __GLASGOW_HASKELL__ < 900 toBounded t = ForallT [PlainTV n | n <- unboundVars t] [] t #else toBounded t = ForallT [PlainTV n SpecifiedSpec | n <- unboundVars t] [] t #endif toBoundedQ :: TypeQ -> TypeQ toBoundedQ = liftM toBounded
0ab24e618a887d3a0a757a08c04d63381e046531460f0867ebfbb791397267ab
dbuenzli/stdlib-utf
utf_uchar.ml
(**************************************************************************) (* *) (* OCaml *) (* *) (* The OCaml programmers *) (* *) Copyright 2021 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) include Uchar UTF codecs tools type utf_decode = int This is an int [ 0xDUUUUUU ] decomposed as follows : - [ D ] is four bits for decode information , the highest bit is set if the decode is valid . The three lower bits indicate the number of elements from the source that were consumed by the decode . - [ UUUUUU ] is the decoded Unicode character or the Unicode replacement character U+FFFD if for invalid decodes . - [D] is four bits for decode information, the highest bit is set if the decode is valid. The three lower bits indicate the number of elements from the source that were consumed by the decode. - [UUUUUU] is the decoded Unicode character or the Unicode replacement character U+FFFD if for invalid decodes. *) let valid_bit = 27 let decode_bits = 24 let[@inline] utf_decode_is_valid d = (d lsr valid_bit) = 1 let[@inline] utf_decode_length d = (d lsr decode_bits) land 0b111 let[@inline] utf_decode_uchar d = Uchar.unsafe_of_int (d land 0xFFFFFF) let[@inline] utf_decode n u = ((8 lor n) lsl decode_bits) lor (Uchar.to_int u) let[@inline] utf_decode_invalid n = (n lsl decode_bits) lor 0xFFFD (* rep *) let utf_8_byte_length u = match to_int u with | u when u < 0 -> assert false | u when u <= 0x007F -> 1 | u when u <= 0x07FF -> 2 | u when u <= 0xFFFF -> 3 | u when u <= 0x10FFFF -> 4 | _ -> assert false let utf_16_byte_length u = match to_int u with | u when u < 0 -> assert false | u when u <= 0xFFFF -> 2 | u when u <= 0x10FFFF -> 4 | _ -> assert false
null
https://raw.githubusercontent.com/dbuenzli/stdlib-utf/9e931944697ff6b48a54a10b425a9acdbd4ccb40/utf_uchar.ml
ocaml
************************************************************************ OCaml The OCaml programmers en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ rep
Copyright 2021 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the include Uchar UTF codecs tools type utf_decode = int This is an int [ 0xDUUUUUU ] decomposed as follows : - [ D ] is four bits for decode information , the highest bit is set if the decode is valid . The three lower bits indicate the number of elements from the source that were consumed by the decode . - [ UUUUUU ] is the decoded Unicode character or the Unicode replacement character U+FFFD if for invalid decodes . - [D] is four bits for decode information, the highest bit is set if the decode is valid. The three lower bits indicate the number of elements from the source that were consumed by the decode. - [UUUUUU] is the decoded Unicode character or the Unicode replacement character U+FFFD if for invalid decodes. *) let valid_bit = 27 let decode_bits = 24 let[@inline] utf_decode_is_valid d = (d lsr valid_bit) = 1 let[@inline] utf_decode_length d = (d lsr decode_bits) land 0b111 let[@inline] utf_decode_uchar d = Uchar.unsafe_of_int (d land 0xFFFFFF) let[@inline] utf_decode n u = ((8 lor n) lsl decode_bits) lor (Uchar.to_int u) let utf_8_byte_length u = match to_int u with | u when u < 0 -> assert false | u when u <= 0x007F -> 1 | u when u <= 0x07FF -> 2 | u when u <= 0xFFFF -> 3 | u when u <= 0x10FFFF -> 4 | _ -> assert false let utf_16_byte_length u = match to_int u with | u when u < 0 -> assert false | u when u <= 0xFFFF -> 2 | u when u <= 0x10FFFF -> 4 | _ -> assert false
0ffdf91f3da92520c9a618649ef1adbeafdc5fbec46f0bf4206ded23ccda5757
racket/expeditor
port.rkt
#lang racket/base (provide open-input-string/count input-port-position) (define (open-input-string/count s) (define p (open-input-string s)) (port-count-lines! p) p) (define (input-port-position s) (define-values (lin col pos) (port-next-location s)) (sub1 pos))
null
https://raw.githubusercontent.com/racket/expeditor/f4967d687c690ff1e44d376260bd2d11f9331b00/expeditor-lib/private/port.rkt
racket
#lang racket/base (provide open-input-string/count input-port-position) (define (open-input-string/count s) (define p (open-input-string s)) (port-count-lines! p) p) (define (input-port-position s) (define-values (lin col pos) (port-next-location s)) (sub1 pos))
14dcb557d05a88cc788d1cc043a5aac1b610a49179b23b6a0153f6c1a8dcb147
amnh/ocamion
simplex.mli
* { 1 Simplex Method } The simplex uses an n+1 dimensional figure to move , like an amoeba , around the surface . The extremities of the object are evaluated , the maximal values are modified , while the others are progressed through improvements . The four moves that can be done on the simplex are : reflection , expansion , contraction , and shrinkage . The degree to which these are done is modified by the strategy used . { b References } + + The simplex uses an n+1 dimensional figure to move, like an amoeba, around the surface. The extremities of the object are evaluated, the maximal values are modified, while the others are progressed through improvements. The four moves that can be done on the simplex are: reflection, expansion, contraction, and shrinkage. The degree to which these are done is modified by the strategy used. {b References} + + *) (** {2 Types} *) (** Define a simplex as a collection of points with attached data *) type 'a simplex = (float array * ('a * float)) array (** Simplex strategy defines how to expand, contract, and reflect a simplex *) type simplex_strategy = { alpha : float; (** The Reflection factor *) beta : float; (** The Contraction factor *) gamma : float; (** The Expansion factor *) delta : float; (** The Shrinkage (Massive Contraction) factor *) } * { 2 Default Strategy } * Default Simplex Strategy defined by NMS . [ { alpha = 1.0 ; beta = 0.5 ; gamma = 2.0 ; delta = 0.5 ; } ] [{alpha = 1.0; beta = 0.5; gamma = 2.0; delta = 0.5;}] *) val default_simplex : simplex_strategy * { 2 Given Termination Functions } (** termination is done through the standard deviation of the elements of the simplex. *) val simplex_termination_stddev : float -> 'a simplex -> bool * Simplex termination test defined by , Murray and . This method looks to see that the points are in a stationary position . This is more appropriate for optimizing smooth functions . It can also be used for noisy functions , but would be equivalent to convergence of the simplex . looks to see that the points are in a stationary position. This is more appropriate for optimizing smooth functions. It can also be used for noisy functions, but would be equivalent to convergence of the simplex. *) val simplex_termination_stationary : float -> 'a simplex -> bool * { 2 Given Initialization Functions } (** Set up the initial simplex by randomly selecting points *) val random_simplex : (float array -> 'a * float) -> float array * ('a * float) -> float array option -> 'a simplex (** Set up the initial simplex from a point and a step size *) val initial_simplex : (float array -> 'a * float) -> float array * ('a * float) -> float array option -> 'a simplex * { 2 Optimization Routines } (** [optimize ?termination_test ?tol ?simplex_strategy ?max_iter ?step f i] *) val optimize : ?termination_test:(float -> 'a simplex -> bool) -> ?tol:float -> ?simplex_strategy:simplex_strategy -> ?max_iter:int -> ?step:float array option -> f:(float array -> 'a * float) -> float array * ('a * float) -> float array * ('a * float)
null
https://raw.githubusercontent.com/amnh/ocamion/699c2471b7fdac12f061cf24b588f9eef5bf5cb8/lib/simplex.mli
ocaml
* {2 Types} * Define a simplex as a collection of points with attached data * Simplex strategy defines how to expand, contract, and reflect a simplex * The Reflection factor * The Contraction factor * The Expansion factor * The Shrinkage (Massive Contraction) factor * termination is done through the standard deviation of the elements of the simplex. * Set up the initial simplex by randomly selecting points * Set up the initial simplex from a point and a step size * [optimize ?termination_test ?tol ?simplex_strategy ?max_iter ?step f i]
* { 1 Simplex Method } The simplex uses an n+1 dimensional figure to move , like an amoeba , around the surface . The extremities of the object are evaluated , the maximal values are modified , while the others are progressed through improvements . The four moves that can be done on the simplex are : reflection , expansion , contraction , and shrinkage . The degree to which these are done is modified by the strategy used . { b References } + + The simplex uses an n+1 dimensional figure to move, like an amoeba, around the surface. The extremities of the object are evaluated, the maximal values are modified, while the others are progressed through improvements. The four moves that can be done on the simplex are: reflection, expansion, contraction, and shrinkage. The degree to which these are done is modified by the strategy used. {b References} + + *) type 'a simplex = (float array * ('a * float)) array type simplex_strategy = } * { 2 Default Strategy } * Default Simplex Strategy defined by NMS . [ { alpha = 1.0 ; beta = 0.5 ; gamma = 2.0 ; delta = 0.5 ; } ] [{alpha = 1.0; beta = 0.5; gamma = 2.0; delta = 0.5;}] *) val default_simplex : simplex_strategy * { 2 Given Termination Functions } val simplex_termination_stddev : float -> 'a simplex -> bool * Simplex termination test defined by , Murray and . This method looks to see that the points are in a stationary position . This is more appropriate for optimizing smooth functions . It can also be used for noisy functions , but would be equivalent to convergence of the simplex . looks to see that the points are in a stationary position. This is more appropriate for optimizing smooth functions. It can also be used for noisy functions, but would be equivalent to convergence of the simplex. *) val simplex_termination_stationary : float -> 'a simplex -> bool * { 2 Given Initialization Functions } val random_simplex : (float array -> 'a * float) -> float array * ('a * float) -> float array option -> 'a simplex val initial_simplex : (float array -> 'a * float) -> float array * ('a * float) -> float array option -> 'a simplex * { 2 Optimization Routines } val optimize : ?termination_test:(float -> 'a simplex -> bool) -> ?tol:float -> ?simplex_strategy:simplex_strategy -> ?max_iter:int -> ?step:float array option -> f:(float array -> 'a * float) -> float array * ('a * float) -> float array * ('a * float)
082448a4294bdf93b9ed26e3ab1e516768d37e52141dfd441ba160cd9bb1081a
bsaleil/lc
fftrad4.scm.scm
;;------------------------------------------------------------------------------ Macros (##define-macro (def-macro form . body) `(##define-macro ,form (let () ,@body))) (def-macro (FLOATvector-const . lst) `',(list->vector lst)) (def-macro (FLOATvector? x) `(vector? ,x)) (def-macro (FLOATvector . lst) `(vector ,@lst)) (def-macro (FLOATmake-vector n . init) `(make-vector ,n ,@init)) (def-macro (FLOATvector-ref v i) `(vector-ref ,v ,i)) (def-macro (FLOATvector-set! v i x) `(vector-set! ,v ,i ,x)) (def-macro (FLOATvector-length v) `(vector-length ,v)) (def-macro (nuc-const . lst) `',(list->vector lst)) (def-macro (FLOAT+ . lst) `(+ ,@lst)) (def-macro (FLOAT- . lst) `(- ,@lst)) (def-macro (FLOAT* . lst) `(* ,@lst)) (def-macro (FLOAT/ . lst) `(/ ,@lst)) (def-macro (FLOAT= . lst) `(= ,@lst)) (def-macro (FLOAT< . lst) `(< ,@lst)) (def-macro (FLOAT<= . lst) `(<= ,@lst)) (def-macro (FLOAT> . lst) `(> ,@lst)) (def-macro (FLOAT>= . lst) `(>= ,@lst)) (def-macro (FLOATnegative? . lst) `(negative? ,@lst)) (def-macro (FLOATpositive? . lst) `(positive? ,@lst)) (def-macro (FLOATzero? . lst) `(zero? ,@lst)) (def-macro (FLOATabs . lst) `(abs ,@lst)) (def-macro (FLOATsin . lst) `(sin ,@lst)) (def-macro (FLOATcos . lst) `(cos ,@lst)) (def-macro (FLOATatan . lst) `(atan ,@lst)) (def-macro (FLOATsqrt . lst) `(sqrt ,@lst)) (def-macro (FLOATmin . lst) `(min ,@lst)) (def-macro (FLOATmax . lst) `(max ,@lst)) (def-macro (FLOATround . lst) `(round ,@lst)) (def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst)) (def-macro (GENERIC+ . lst) `(+ ,@lst)) (def-macro (GENERIC- . lst) `(- ,@lst)) (def-macro (GENERIC* . lst) `(* ,@lst)) (def-macro (GENERIC/ . lst) `(/ ,@lst)) (def-macro (GENERICquotient . lst) `(quotient ,@lst)) (def-macro (GENERICremainder . lst) `(remainder ,@lst)) (def-macro (GENERICmodulo . lst) `(modulo ,@lst)) (def-macro (GENERIC= . lst) `(= ,@lst)) (def-macro (GENERIC< . lst) `(< ,@lst)) (def-macro (GENERIC<= . lst) `(<= ,@lst)) (def-macro (GENERIC> . lst) `(> ,@lst)) (def-macro (GENERIC>= . lst) `(>= ,@lst)) (def-macro (GENERICexpt . lst) `(expt ,@lst)) ;;------------------------------------------------------------------------------ Functions used by LC to get time info (def-macro (##lc-time expr) (let ((sym (gensym))) `(let ((r (##lc-exec-stats (lambda () ,expr)))) (##print-perm-string "CPU time: ") (##print-double (+ (cdr (assoc "User time" (cdr r))) (cdr (assoc "Sys time" (cdr r))))) (##print-perm-string "\n") (##print-perm-string "GC CPU time: ") (##print-double (+ (cdr (assoc "GC user time" (cdr r))) (cdr (assoc "GC sys time" (cdr r))))) (##print-perm-string "\n") (map (lambda (el) (##print-perm-string (car el)) (##print-perm-string ": ") (##print-double (cdr el)) (##print-perm-string "\n")) (cdr r)) r))) (define (##lc-exec-stats thunk) (let* ((at-start (##process-statistics)) (result (thunk)) (at-end (##process-statistics))) (define (get-info msg idx) (cons msg (- (f64vector-ref at-end idx) (f64vector-ref at-start idx)))) (list result (get-info "User time" 0) (get-info "Sys time" 1) (get-info "Real time" 2) (get-info "GC user time" 3) (get-info "GC sys time" 4) (get-info "GC real time" 5) (get-info "Nb gcs" 6)))) ;;------------------------------------------------------------------------------ (define (run-bench name count ok? run) (let loop ((i count) (result '(undefined))) (if (< 0 i) (loop (- i 1) (run)) result))) (define (run-benchmark name count ok? run-maker . args) (let ((run (apply run-maker args))) (let ((result (car (##lc-time (run-bench name count ok? run))))) (if (not (ok? result)) (begin (display "*** wrong result ***") (newline) (display "*** got: ") (write result) (newline)))))) ; Gabriel benchmarks (define boyer-iters 20) (define browse-iters 600) (define cpstak-iters 1000) (define ctak-iters 100) (define dderiv-iters 2000000) (define deriv-iters 2000000) (define destruc-iters 500) (define diviter-iters 1000000) (define divrec-iters 1000000) (define puzzle-iters 100) (define tak-iters 2000) (define takl-iters 300) (define trav1-iters 100) (define trav2-iters 20) (define triangl-iters 10) and benchmarks (define ack-iters 10) (define array1-iters 1) (define cat-iters 1) (define string-iters 10) (define sum1-iters 10) (define sumloop-iters 10) (define tail-iters 1) (define wc-iters 1) ; C benchmarks (define fft-iters 2000) (define fib-iters 5) (define fibfp-iters 2) (define mbrot-iters 100) (define nucleic-iters 5) (define pnpoly-iters 100000) (define sum-iters 20000) (define sumfp-iters 20000) (define tfib-iters 20) ; Other benchmarks (define conform-iters 40) (define dynamic-iters 20) (define earley-iters 200) (define fibc-iters 500) (define graphs-iters 300) (define lattice-iters 1) (define matrix-iters 400) (define maze-iters 4000) (define mazefun-iters 1000) (define nqueens-iters 2000) (define paraffins-iters 1000) (define peval-iters 200) (define pi-iters 2) (define primes-iters 100000) (define ray-iters 5) (define scheme-iters 20000) (define simplex-iters 100000) (define slatex-iters 20) (define perm9-iters 10) (define nboyer-iters 100) (define sboyer-iters 100) (define gcbench-iters 1) (define compiler-iters 300) (define nbody-iters 1) (define fftrad4-iters 4) Copyright 2018 , ;;; Permission is hereby granted, free of charge, to any person obtaining ;;; a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction , including without limitation ;;; the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the ;;; Software is furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . ;;; THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS ;;; OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . ;;; IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , ;;; TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ;;; SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ;;; This software calculates radix 4 direct and inverse Fast Fourier Transforms . ;;; The direct transform takes in-order input and produces out-of-order output. ;;; The inverse transform takes out-of-order input and produces in-order output. ;;; ;;; This particular code has guaranteed error bounds, see in particular ;;; the commentary at ;;; ;;; #L6395 (define lut-table-size 512) (define lut-table-size^2 262144) (define lut-table-size^3 134217728) (define log-lut-table-size 9) (define low-lut (FLOATvector-const 1. 0. .7071067811865476 .7071067811865476 .9238795325112867 .3826834323650898 .3826834323650898 .9238795325112867 .9807852804032304 .19509032201612828 .5555702330196022 .8314696123025452 .8314696123025452 .5555702330196022 .19509032201612828 .9807852804032304 .9951847266721969 .0980171403295606 .6343932841636455 .773010453362737 .881921264348355 .47139673682599764 .2902846772544624 .9569403357322088 .9569403357322088 .2902846772544624 .47139673682599764 .881921264348355 .773010453362737 .6343932841636455 .0980171403295606 .9951847266721969 .9987954562051724 .049067674327418015 .6715589548470184 .7409511253549591 .9039892931234433 .4275550934302821 .33688985339222005 .9415440651830208 .970031253194544 .2429801799032639 .5141027441932218 .8577286100002721 .8032075314806449 .5956993044924334 .14673047445536175 .989176509964781 .989176509964781 .14673047445536175 .5956993044924334 .8032075314806449 .8577286100002721 .5141027441932218 .2429801799032639 .970031253194544 .9415440651830208 .33688985339222005 .4275550934302821 .9039892931234433 .7409511253549591 .6715589548470184 .049067674327418015 .9987954562051724 .9996988186962042 .024541228522912288 .6895405447370669 .7242470829514669 .9142097557035307 .40524131400498986 .35989503653498817 .9329927988347388 .9757021300385286 .2191012401568698 .5349976198870973 .8448535652497071 .8175848131515837 .5758081914178453 .17096188876030122 .9852776423889412 .99247953459871 .1224106751992162 .6152315905806268 .7883464276266062 .8700869911087115 .49289819222978404 .26671275747489837 .9637760657954398 .9495281805930367 .31368174039889146 .4496113296546066 .8932243011955153 .7572088465064846 .6531728429537768 .07356456359966743 .9972904566786902 .9972904566786902 .07356456359966743 .6531728429537768 .7572088465064846 .8932243011955153 .4496113296546066 .31368174039889146 .9495281805930367 .9637760657954398 .26671275747489837 .49289819222978404 .8700869911087115 .7883464276266062 .6152315905806268 .1224106751992162 .99247953459871 .9852776423889412 .17096188876030122 .5758081914178453 .8175848131515837 .8448535652497071 .5349976198870973 .2191012401568698 .9757021300385286 .9329927988347388 .35989503653498817 .40524131400498986 .9142097557035307 .7242470829514669 .6895405447370669 .024541228522912288 .9996988186962042 .9999247018391445 .012271538285719925 .6983762494089728 .7157308252838187 .9191138516900578 .3939920400610481 .37131719395183754 .9285060804732156 .9783173707196277 .20711137619221856 .5453249884220465 .8382247055548381 .8245893027850253 .5657318107836132 .18303988795514095 .9831054874312163 .9939069700023561 .11022220729388306 .6248594881423863 .7807372285720945 .8760700941954066 .4821837720791228 .2785196893850531 .9604305194155658 .9533060403541939 .3020059493192281 .46053871095824 .8876396204028539 .765167265622459 .6438315428897915 .0857973123444399 .996312612182778 .9981181129001492 .06132073630220858 .6624157775901718 .7491363945234594 .8986744656939538 .43861623853852766 .3253102921622629 .9456073253805213 .9669764710448521 .25486565960451457 .5035383837257176 .8639728561215867 .7958369046088836 .6055110414043255 .1345807085071262 .99090263542778 .9873014181578584 .15885814333386145 .5857978574564389 .8104571982525948 .8513551931052652 .524589682678469 .2310581082806711 .9729399522055602 .937339011912575 .34841868024943456 .4164295600976372 .9091679830905224 .7326542716724128 .680600997795453 .03680722294135883 .9993223845883495 .9993223845883495 .03680722294135883 .680600997795453 .7326542716724128 .9091679830905224 .4164295600976372 .34841868024943456 .937339011912575 .9729399522055602 .2310581082806711 .524589682678469 .8513551931052652 .8104571982525948 .5857978574564389 .15885814333386145 .9873014181578584 .99090263542778 .1345807085071262 .6055110414043255 .7958369046088836 .8639728561215867 .5035383837257176 .25486565960451457 .9669764710448521 .9456073253805213 .3253102921622629 .43861623853852766 .8986744656939538 .7491363945234594 .6624157775901718 .06132073630220858 .9981181129001492 .996312612182778 .0857973123444399 .6438315428897915 .765167265622459 .8876396204028539 .46053871095824 .3020059493192281 .9533060403541939 .9604305194155658 .2785196893850531 .4821837720791228 .8760700941954066 .7807372285720945 .6248594881423863 .11022220729388306 .9939069700023561 .9831054874312163 .18303988795514095 .5657318107836132 .8245893027850253 .8382247055548381 .5453249884220465 .20711137619221856 .9783173707196277 .9285060804732156 .37131719395183754 .3939920400610481 .9191138516900578 .7157308252838187 .6983762494089728 .012271538285719925 .9999247018391445 .9999811752826011 .006135884649154475 .7027547444572253 .7114321957452164 .9215140393420419 .3883450466988263 .37700741021641826 .9262102421383114 .9795697656854405 .2011046348420919 .5504579729366048 .83486287498638 .8280450452577558 .560661576197336 .18906866414980622 .9819638691095552 .9945645707342554 .10412163387205457 .629638238914927 .7768884656732324 .8790122264286335 .47679923006332214 .2844075372112718 .9587034748958716 .9551411683057707 .29615088824362384 .4659764957679662 .8847970984309378 .7691033376455796 .6391244448637757 .09190895649713272 .9957674144676598 .9984755805732948 .05519524434968994 .6669999223036375 .745057785441466 .901348847046022 .43309381885315196 .33110630575987643 .9435934581619604 .9685220942744173 .24892760574572018 .508830142543107 .8608669386377673 .799537269107905 .600616479383869 .14065823933284924 .9900582102622971 .9882575677307495 .15279718525844344 .5907597018588743 .8068475535437992 .8545579883654005 .5193559901655896 .2370236059943672 .9715038909862518 .9394592236021899 .3426607173119944 .4220002707997997 .9065957045149153 .7368165688773699 .6760927035753159 .04293825693494082 .9990777277526454 .9995294175010931 .030674803176636626 .6850836677727004 .7284643904482252 .9117060320054299 .41084317105790397 .3541635254204904 .9351835099389476 .9743393827855759 .22508391135979283 .5298036246862947 .8481203448032972 .8140363297059484 .5808139580957645 .16491312048996992 .9863080972445987 .9917097536690995 .12849811079379317 .6103828062763095 .7921065773002124 .8670462455156926 .49822766697278187 .2607941179152755 .9653944416976894 .9475855910177411 .3195020308160157 .44412214457042926 .8959662497561851 .7531867990436125 .6578066932970786 .06744391956366406 .9977230666441916 .9968202992911657 .07968243797143013 .6485144010221124 .7612023854842618 .8904487232447579 .45508358712634384 .30784964004153487 .9514350209690083 .9621214042690416 .272621355449949 .48755016014843594 .8730949784182901 .7845565971555752 .6200572117632892 .11631863091190477 .9932119492347945 .984210092386929 .17700422041214875 .5707807458869673 .8211025149911046 .8415549774368984 .5401714727298929 .21311031991609136 .9770281426577544 .9307669610789837 .36561299780477385 .39962419984564684 .9166790599210427 .7200025079613817 .693971460889654 .01840672990580482 .9998305817958234 .9998305817958234 .01840672990580482 .693971460889654 .7200025079613817 .9166790599210427 .39962419984564684 .36561299780477385 .9307669610789837 .9770281426577544 .21311031991609136 .5401714727298929 .8415549774368984 .8211025149911046 .5707807458869673 .17700422041214875 .984210092386929 .9932119492347945 .11631863091190477 .6200572117632892 .7845565971555752 .8730949784182901 .48755016014843594 .272621355449949 .9621214042690416 .9514350209690083 .30784964004153487 .45508358712634384 .8904487232447579 .7612023854842618 .6485144010221124 .07968243797143013 .9968202992911657 .9977230666441916 .06744391956366406 .6578066932970786 .7531867990436125 .8959662497561851 .44412214457042926 .3195020308160157 .9475855910177411 .9653944416976894 .2607941179152755 .49822766697278187 .8670462455156926 .7921065773002124 .6103828062763095 .12849811079379317 .9917097536690995 .9863080972445987 .16491312048996992 .5808139580957645 .8140363297059484 .8481203448032972 .5298036246862947 .22508391135979283 .9743393827855759 .9351835099389476 .3541635254204904 .41084317105790397 .9117060320054299 .7284643904482252 .6850836677727004 .030674803176636626 .9995294175010931 .9990777277526454 .04293825693494082 .6760927035753159 .7368165688773699 .9065957045149153 .4220002707997997 .3426607173119944 .9394592236021899 .9715038909862518 .2370236059943672 .5193559901655896 .8545579883654005 .8068475535437992 .5907597018588743 .15279718525844344 .9882575677307495 .9900582102622971 .14065823933284924 .600616479383869 .799537269107905 .8608669386377673 .508830142543107 .24892760574572018 .9685220942744173 .9435934581619604 .33110630575987643 .43309381885315196 .901348847046022 .745057785441466 .6669999223036375 .05519524434968994 .9984755805732948 .9957674144676598 .09190895649713272 .6391244448637757 .7691033376455796 .8847970984309378 .4659764957679662 .29615088824362384 .9551411683057707 .9587034748958716 .2844075372112718 .47679923006332214 .8790122264286335 .7768884656732324 .629638238914927 .10412163387205457 .9945645707342554 .9819638691095552 .18906866414980622 .560661576197336 .8280450452577558 .83486287498638 .5504579729366048 .2011046348420919 .9795697656854405 .9262102421383114 .37700741021641826 .3883450466988263 .9215140393420419 .7114321957452164 .7027547444572253 .006135884649154475 .9999811752826011 .9999952938095762 .003067956762965976 .7049340803759049 .7092728264388657 .9227011283338785 .38551605384391885 .37984720892405116 .9250492407826776 .9801821359681174 .1980984107179536 .5530167055800276 .8331701647019132 .829761233794523 .5581185312205561 .19208039704989244 .9813791933137546 .9948793307948056 .10106986275482782 .6320187359398091 .7749531065948739 .8804708890521608 .47410021465055 .2873474595447295 .9578264130275329 .9560452513499964 .29321916269425863 .46868882203582796 .8833633386657316 .7710605242618138 .6367618612362842 .094963495329639 .9954807554919269 .9986402181802653 .052131704680283324 .6692825883466361 .7430079521351217 .9026733182372588 .4303264813400826 .3339996514420094 .9425731976014469 .9692812353565485 .24595505033579462 .5114688504379704 .8593018183570084 .8013761717231402 .5981607069963423 .14369503315029444 .9896220174632009 .9887216919603238 .1497645346773215 .5932322950397998 .8050313311429635 .8561473283751945 .5167317990176499 .2400030224487415 .9707721407289504 .9405060705932683 .33977688440682685 .4247796812091088 .9052967593181188 .7388873244606151 .673829000378756 .04600318213091463 .9989412931868569 .9996188224951786 .027608145778965743 .6873153408917592 .726359155084346 .9129621904283982 .4080441628649787 .35703096123343003 .9340925504042589 .9750253450669941 .22209362097320354 .532403127877198 .8464909387740521 .8158144108067338 .5783137964116556 .16793829497473117 .9857975091675675 .9920993131421918 .12545498341154623 .6128100824294097 .79023022143731 .8685707059713409 .49556526182577254 .2637546789748314 .9645897932898128 .9485613499157303 .31659337555616585 .4468688401623742 .8945994856313827 .7552013768965365 .6554928529996153 .07050457338961387 .9975114561403035 .997060070339483 .07662386139203149 .6508466849963809 .7592091889783881 .8918407093923427 .4523495872337709 .3107671527496115 .9504860739494817 .9629532668736839 .2696683255729151 .49022648328829116 .8715950866559511 .7864552135990858 .617647307937804 .11936521481099137 .9928504144598651 .9847485018019042 .17398387338746382 .5732971666980422 .819347520076797 .8432082396418454 .5375870762956455 .21610679707621952 .9763697313300211 .9318842655816681 .3627557243673972 .40243465085941843 .9154487160882678 .7221281939292153 .6917592583641577 .021474080275469508 .9997694053512153 .9998823474542126 .015339206284988102 .696177131491463 .7178700450557317 .9179007756213905 .3968099874167103 .3684668299533723 .9296408958431812 .9776773578245099 .2101118368804696 .5427507848645159 .8398937941959995 .8228497813758263 .5682589526701316 .18002290140569951 .9836624192117303 .9935641355205953 .11327095217756435 .62246127937415 .7826505961665757 .8745866522781761 .4848692480007911 .27557181931095814 .9612804858113206 .9523750127197659 .30492922973540243 .45781330359887723 .8890483558546646 .7631884172633813 .6461760129833164 .08274026454937569 .9965711457905548 .997925286198596 .06438263092985747 .6601143420674205 .7511651319096864 .8973245807054183 .44137126873171667 .32240767880106985 .9466009130832835 .9661900034454125 .257831102162159 .5008853826112408 .8655136240905691 .7939754775543372 .6079497849677736 .13154002870288312 .9913108598461154 .9868094018141855 .16188639378011183 .5833086529376983 .8122505865852039 .8497417680008524 .5271991347819014 .22807208317088573 .973644249650812 .9362656671702783 .35129275608556715 .41363831223843456 .9104412922580672 .7305627692278276 .6828455463852481 .03374117185137759 .9994306045554617 .9992047586183639 .03987292758773981 .6783500431298615 .7347388780959635 .9078861164876663 .41921688836322396 .34554132496398904 .9384035340631081 .9722264970789363 .23404195858354343 .5219752929371544 .8529606049303636 .808656181588175 .5882815482226453 .15582839765426523 .9877841416445722 .9904850842564571 .13762012158648604 .6030665985403482 .7976908409433912 .8624239561110405 .5061866453451553 .25189781815421697 .9677538370934755 .9446048372614803 .32820984357909255 .4358570799222555 .9000158920161603 .7471006059801801 .6647109782033449 .05825826450043576 .9983015449338929 .996044700901252 .0888535525825246 .6414810128085832 .7671389119358204 .8862225301488806 .4632597835518602 .2990798263080405 .9542280951091057 .9595715130819845 .281464937925758 .479493757660153 .8775452902072612 .778816512381476 .6272518154951441 .10717242495680884 .9942404494531879 .9825393022874412 .18605515166344666 .5631993440138341 .8263210628456635 .836547727223512 .5478940591731002 .20410896609281687 .9789481753190622 .9273625256504011 .374164062971458 .39117038430225387 .9203182767091106 .7135848687807936 .7005687939432483 .00920375478205982 .9999576445519639 .9999576445519639 .00920375478205982 .7005687939432483 .7135848687807936 .9203182767091106 .39117038430225387 .374164062971458 .9273625256504011 .9789481753190622 .20410896609281687 .5478940591731002 .836547727223512 .8263210628456635 .5631993440138341 .18605515166344666 .9825393022874412 .9942404494531879 .10717242495680884 .6272518154951441 .778816512381476 .8775452902072612 .479493757660153 .281464937925758 .9595715130819845 .9542280951091057 .2990798263080405 .4632597835518602 .8862225301488806 .7671389119358204 .6414810128085832 .0888535525825246 .996044700901252 .9983015449338929 .05825826450043576 .6647109782033449 .7471006059801801 .9000158920161603 .4358570799222555 .32820984357909255 .9446048372614803 .9677538370934755 .25189781815421697 .5061866453451553 .8624239561110405 .7976908409433912 .6030665985403482 .13762012158648604 .9904850842564571 .9877841416445722 .15582839765426523 .5882815482226453 .808656181588175 .8529606049303636 .5219752929371544 .23404195858354343 .9722264970789363 .9384035340631081 .34554132496398904 .41921688836322396 .9078861164876663 .7347388780959635 .6783500431298615 .03987292758773981 .9992047586183639 .9994306045554617 .03374117185137759 .6828455463852481 .7305627692278276 .9104412922580672 .41363831223843456 .35129275608556715 .9362656671702783 .973644249650812 .22807208317088573 .5271991347819014 .8497417680008524 .8122505865852039 .5833086529376983 .16188639378011183 .9868094018141855 .9913108598461154 .13154002870288312 .6079497849677736 .7939754775543372 .8655136240905691 .5008853826112408 .257831102162159 .9661900034454125 .9466009130832835 .32240767880106985 .44137126873171667 .8973245807054183 .7511651319096864 .6601143420674205 .06438263092985747 .997925286198596 .9965711457905548 .08274026454937569 .6461760129833164 .7631884172633813 .8890483558546646 .45781330359887723 .30492922973540243 .9523750127197659 .9612804858113206 .27557181931095814 .4848692480007911 .8745866522781761 .7826505961665757 .62246127937415 .11327095217756435 .9935641355205953 .9836624192117303 .18002290140569951 .5682589526701316 .8228497813758263 .8398937941959995 .5427507848645159 .2101118368804696 .9776773578245099 .9296408958431812 .3684668299533723 .3968099874167103 .9179007756213905 .7178700450557317 .696177131491463 .015339206284988102 .9998823474542126 .9997694053512153 .021474080275469508 .6917592583641577 .7221281939292153 .9154487160882678 .40243465085941843 .3627557243673972 .9318842655816681 .9763697313300211 .21610679707621952 .5375870762956455 .8432082396418454 .819347520076797 .5732971666980422 .17398387338746382 .9847485018019042 .9928504144598651 .11936521481099137 .617647307937804 .7864552135990858 .8715950866559511 .49022648328829116 .2696683255729151 .9629532668736839 .9504860739494817 .3107671527496115 .4523495872337709 .8918407093923427 .7592091889783881 .6508466849963809 .07662386139203149 .997060070339483 .9975114561403035 .07050457338961387 .6554928529996153 .7552013768965365 .8945994856313827 .4468688401623742 .31659337555616585 .9485613499157303 .9645897932898128 .2637546789748314 .49556526182577254 .8685707059713409 .79023022143731 .6128100824294097 .12545498341154623 .9920993131421918 .9857975091675675 .16793829497473117 .5783137964116556 .8158144108067338 .8464909387740521 .532403127877198 .22209362097320354 .9750253450669941 .9340925504042589 .35703096123343003 .4080441628649787 .9129621904283982 .726359155084346 .6873153408917592 .027608145778965743 .9996188224951786 .9989412931868569 .04600318213091463 .673829000378756 .7388873244606151 .9052967593181188 .4247796812091088 .33977688440682685 .9405060705932683 .9707721407289504 .2400030224487415 .5167317990176499 .8561473283751945 .8050313311429635 .5932322950397998 .1497645346773215 .9887216919603238 .9896220174632009 .14369503315029444 .5981607069963423 .8013761717231402 .8593018183570084 .5114688504379704 .24595505033579462 .9692812353565485 .9425731976014469 .3339996514420094 .4303264813400826 .9026733182372588 .7430079521351217 .6692825883466361 .052131704680283324 .9986402181802653 .9954807554919269 .094963495329639 .6367618612362842 .7710605242618138 .8833633386657316 .46868882203582796 .29321916269425863 .9560452513499964 .9578264130275329 .2873474595447295 .47410021465055 .8804708890521608 .7749531065948739 .6320187359398091 .10106986275482782 .9948793307948056 .9813791933137546 .19208039704989244 .5581185312205561 .829761233794523 .8331701647019132 .5530167055800276 .1980984107179536 .9801821359681174 .9250492407826776 .37984720892405116 .38551605384391885 .9227011283338785 .7092728264388657 .7049340803759049 .003067956762965976 .9999952938095762 )) (define med-lut (FLOATvector-const 1. 0. .9999999999820472 5.9921124526424275e-6 .9999999999281892 1.1984224905069707e-5 .9999999998384257 1.7976337357066685e-5 .9999999997127567 2.396844980841822e-5 .9999999995511824 2.9960562258909154e-5 .9999999993537025 3.5952674708324344e-5 .9999999991203175 4.1944787156448635e-5 .9999999988510269 4.793689960306688e-5 .9999999985458309 5.3929012047963936e-5 .9999999982047294 5.992112449092465e-5 .9999999978277226 6.591323693173387e-5 .9999999974148104 7.190534937017645e-5 .9999999969659927 7.789746180603723e-5 .9999999964812697 8.388957423910108e-5 .9999999959606412 8.988168666915283e-5 .9999999954041073 9.587379909597734e-5 .999999994811668 1.0186591151935948e-4 .9999999941833233 1.0785802393908407e-4 .9999999935190732 1.1385013635493597e-4 .9999999928189177 1.1984224876670004e-4 .9999999920828567 1.2583436117416112e-4 .9999999913108903 1.3182647357710405e-4 .9999999905030187 1.3781858597531374e-4 .9999999896592414 1.4381069836857496e-4 .9999999887795589 1.498028107566726e-4 .9999999878639709 1.5579492313939151e-4 .9999999869124775 1.6178703551651655e-4 .9999999859250787 1.6777914788783258e-4 .9999999849017744 1.737712602531244e-4 .9999999838425648 1.797633726121769e-4 .9999999827474497 1.8575548496477492e-4 .9999999816164293 1.9174759731070332e-4 .9999999804495034 1.9773970964974692e-4 .9999999792466722 2.037318219816906e-4 .9999999780079355 2.0972393430631923e-4 .9999999767332933 2.1571604662341763e-4 .9999999754227459 2.2170815893277063e-4 .9999999740762929 2.2770027123416315e-4 .9999999726939346 2.3369238352737996e-4 .9999999712756709 2.3968449581220595e-4 .9999999698215016 2.45676608088426e-4 .9999999683314271 2.5166872035582493e-4 .9999999668054471 2.5766083261418755e-4 .9999999652435617 2.636529448632988e-4 .9999999636457709 2.696450571029434e-4 .9999999620120748 2.756371693329064e-4 .9999999603424731 2.8162928155297243e-4 .9999999586369661 2.876213937629265e-4 .9999999568955537 2.936135059625534e-4 .9999999551182358 2.99605618151638e-4 .9999999533050126 3.055977303299651e-4 .9999999514558838 3.115898424973196e-4 .9999999495708498 3.1758195465348636e-4 .9999999476499103 3.235740667982502e-4 .9999999456930654 3.2956617893139595e-4 .9999999437003151 3.3555829105270853e-4 .9999999416716594 3.4155040316197275e-4 .9999999396070982 3.475425152589734e-4 .9999999375066316 3.535346273434955e-4 .9999999353702598 3.595267394153237e-4 .9999999331979824 3.6551885147424295e-4 .9999999309897996 3.7151096352003814e-4 .9999999287457114 3.7750307555249406e-4 .9999999264657179 3.8349518757139556e-4 .9999999241498189 3.8948729957652753e-4 .9999999217980144 3.954794115676748e-4 .9999999194103046 4.0147152354462224e-4 .9999999169866894 4.0746363550715466e-4 .9999999145271687 4.134557474550569e-4 .9999999120317428 4.194478593881139e-4 .9999999095004113 4.2543997130611036e-4 .9999999069331744 4.314320832088313e-4 .9999999043300322 4.3742419509606144e-4 .9999999016909845 4.4341630696758576e-4 .9999998990160315 4.4940841882318896e-4 .9999998963051729 4.55400530662656e-4 .999999893558409 4.613926424857717e-4 .9999998907757398 4.673847542923209e-4 .9999998879571651 4.7337686608208844e-4 .9999998851026849 4.793689778548592e-4 .9999998822122994 4.8536108961041806e-4 .9999998792860085 4.913532013485497e-4 .9999998763238122 4.973453130690393e-4 .9999998733257104 5.033374247716714e-4 .9999998702917032 5.09329536456231e-4 .9999998672217907 5.153216481225028e-4 .9999998641159727 5.213137597702719e-4 .9999998609742493 5.27305871399323e-4 .9999998577966206 5.332979830094408e-4 .9999998545830864 5.392900946004105e-4 .9999998513336468 5.452822061720168e-4 .9999998480483018 5.512743177240444e-4 .9999998447270514 5.572664292562783e-4 .9999998413698955 5.632585407685033e-4 .9999998379768343 5.692506522605043e-4 .9999998345478677 5.752427637320661e-4 .9999998310829956 5.812348751829735e-4 .9999998275822183 5.872269866130116e-4 .9999998240455354 5.93219098021965e-4 .9999998204729471 5.992112094096185e-4 .9999998168644535 6.052033207757572e-4 .9999998132200545 6.111954321201659e-4 .99999980953975 6.171875434426292e-4 .9999998058235401 6.231796547429323e-4 .9999998020714248 6.291717660208597e-4 .9999997982834041 6.351638772761965e-4 .9999997944594781 6.411559885087275e-4 .9999997905996466 6.471480997182375e-4 .9999997867039097 6.531402109045114e-4 .9999997827722674 6.591323220673341e-4 .9999997788047197 6.651244332064902e-4 .9999997748012666 6.711165443217649e-4 .9999997707619082 6.771086554129428e-4 .9999997666866443 6.83100766479809e-4 .9999997625754748 6.89092877522148e-4 .9999997584284002 6.950849885397449e-4 .9999997542454201 7.010770995323844e-4 .9999997500265345 7.070692104998515e-4 .9999997457717437 7.130613214419311e-4 .9999997414810473 7.190534323584079e-4 .9999997371544456 7.250455432490666e-4 .9999997327919384 7.310376541136925e-4 .9999997283935259 7.3702976495207e-4 .999999723959208 7.430218757639842e-4 .9999997194889846 7.490139865492199e-4 .9999997149828559 7.55006097307562e-4 .9999997104408218 7.609982080387952e-4 .9999997058628822 7.669903187427045e-4 .9999997012490373 7.729824294190747e-4 .9999996965992869 7.789745400676906e-4 .9999996919136313 7.849666506883372e-4 .99999968719207 7.909587612807992e-4 .9999996824346035 7.969508718448614e-4 .9999996776412315 8.029429823803089e-4 .9999996728119542 8.089350928869263e-4 .9999996679467715 8.149272033644986e-4 .9999996630456833 8.209193138128106e-4 .9999996581086897 8.269114242316472e-4 .9999996531357909 8.329035346207931e-4 .9999996481269865 8.388956449800333e-4 .9999996430822767 8.448877553091527e-4 .9999996380016616 8.508798656079359e-4 .999999632885141 8.56871975876168e-4 .9999996277327151 8.628640861136338e-4 .9999996225443838 8.68856196320118e-4 .9999996173201471 8.748483064954056e-4 .999999612060005 8.808404166392814e-4 .9999996067639574 8.868325267515304e-4 .9999996014320045 8.928246368319371e-4 .9999995960641462 8.988167468802867e-4 .9999995906603825 9.048088568963639e-4 .9999995852207133 9.108009668799535e-4 .9999995797451389 9.167930768308405e-4 .9999995742336589 9.227851867488095e-4 .9999995686862736 9.287772966336457e-4 .9999995631029829 9.347694064851338e-4 .9999995574837868 9.407615163030585e-4 .9999995518286853 9.467536260872047e-4 .9999995461376784 9.527457358373575e-4 .9999995404107661 9.587378455533015e-4 .9999995346479484 9.647299552348216e-4 .9999995288492254 9.707220648817027e-4 .9999995230145969 9.767141744937296e-4 .9999995171440631 9.827062840706872e-4 .9999995112376238 9.886983936123602e-4 .9999995052952791 9.946905031185337e-4 .9999994993170291 .0010006826125889925 .9999994933028736 .0010066747220235214 .9999994872528128 .001012666831421905 .9999994811668466 .0010186589407839286 .999999475044975 .0010246510501093766 .9999994688871979 .0010306431593980344 .9999994626935156 .0010366352686496862 .9999994564639277 .0010426273778641173 .9999994501984345 .0010486194870411127 .999999443897036 .0010546115961804568 .999999437559732 .0010606037052819344 .9999994311865227 .0010665958143453308 .9999994247774079 .0010725879233704307 .9999994183323877 .0010785800323570187 .9999994118514622 .0010845721413048801 .9999994053346313 .0010905642502137994 .9999993987818949 .0010965563590835613 .9999993921932533 .0011025484679139511 .9999993855687062 .0011085405767047535 .9999993789082536 .0011145326854557532 .9999993722118957 .001120524794166735 .9999993654796325 .0011265169028374842 .9999993587114638 .0011325090114677853 .9999993519073898 .001138501120057423 .9999993450674104 .0011444932286061825 .9999993381915255 .0011504853371138485 .9999993312797354 .0011564774455802057 .9999993243320398 .0011624695540050393 .9999993173484387 .001168461662388134 .9999993103289324 .0011744537707292742 .9999993032735206 .0011804458790282454 .9999992961822035 .0011864379872848323 .9999992890549809 .0011924300954988195 .999999281891853 .001198422203669992 .9999992746928197 .0012044143117981348 .999999267457881 .0012104064198830327 .999999260187037 .0012163985279244702 .9999992528802875 .0012223906359222325 .9999992455376326 .0012283827438761045 .9999992381590724 .0012343748517858707 .9999992307446068 .0012403669596513162 .9999992232942359 .001246359067472226 .9999992158079595 .0012523511752483847 .9999992082857777 .001258343282979577 .9999992007276906 .001264335390665588 .999999193133698 .0012703274983062026 .9999991855038001 .0012763196059012057 .9999991778379967 .001282311713450382 .9999991701362881 .0012883038209535163 .999999162398674 .0012942959284103935 .9999991546251547 .0013002880358207985 .9999991468157298 .001306280143184516 .9999991389703996 .001312272250501331 .999999131089164 .0013182643577710285 .999999123172023 .0013242564649933932 .9999991152189767 .0013302485721682098 .9999991072300249 .001336240679295263 .9999990992051678 .0013422327863743383 .9999990911444054 .0013482248934052201 .9999990830477375 .0013542170003876934 .9999990749151643 .001360209107321543 .9999990667466857 .0013662012142065536 .9999990585423016 .0013721933210425101 .9999990503020123 .0013781854278291975 .9999990420258176 .0013841775345664006 .9999990337137175 .0013901696412539043 .999999025365712 .0013961617478914935 .999999016981801 .0014021538544789526 .9999990085619848 .001408145961016067 .9999990001062631 .0014141380675026214 .9999989916146361 .0014201301739384005 .9999989830871038 .0014261222803231893 .9999989745236659 .0014321143866567725 .9999989659243228 .001438106492938935 .9999989572890743 .0014440985991694619 .9999989486179204 .0014500907053481378 .9999989399108612 .0014560828114747475 .9999989311678965 .0014620749175490758 .9999989223890265 .001468067023570908 .9999989135742512 .0014740591295400284 .9999989047235704 .0014800512354562223 .9999988958369843 .0014860433413192743 .9999988869144928 .0014920354471289693 .9999988779560959 .0014980275528850922 .9999988689617937 .0015040196585874275 .9999988599315861 .0015100117642357607 .999998850865473 .0015160038698298762 .9999988417634548 .001521995975369559 .999998832625531 .0015279880808545937 .9999988234517019 .0015339801862847657 .9999988142419675 .0015399722916598592 .9999988049963277 .0015459643969796596 .9999987957147825 .0015519565022439512 .9999987863973319 .0015579486074525195 .9999987770439759 .001563940712605149 .9999987676547146 .0015699328177016243 .999998758229548 .0015759249227417307 .9999987487684759 .0015819170277252528 .9999987392714985 .0015879091326519755 .9999987297386157 .0015939012375216837 .9999987201698276 .0015998933423341623 .9999987105651341 .001605885447089196 .9999987009245352 .0016118775517865696 .999998691248031 .0016178696564260683 .9999986815356214 .0016238617610074765 .9999986717873064 .0016298538655305794 .9999986620030861 .0016358459699951618 .9999986521829605 .0016418380744010084 .9999986423269294 .0016478301787479041 .999998632434993 .0016538222830356339 .9999986225071512 .0016598143872639823 .999998612543404 .0016658064914327345 .9999986025437515 .0016717985955416754 .9999985925081937 .0016777906995905894 .9999985824367305 .0016837828035792617 .9999985723293618 .0016897749075074774 .999998562186088 .0016957670113750207 .9999985520069086 .0017017591151816769 .9999985417918239 .0017077512189272307 .999998531540834 .001713743322611467 .9999985212539385 .0017197354262341706 .9999985109311378 .0017257275297951264 .9999985005724317 .0017317196332941192 .9999984901778203 .0017377117367309341 .9999984797473034 .0017437038401053556 .9999984692808812 .0017496959434171687 .9999984587785538 .0017556880466661582 .9999984482403208 .001761680149852109 .9999984376661826 .0017676722529748061 .999998427056139 .0017736643560340342 .99999841641019 .001779656459029578 .9999984057283358 .0017856485619612225 .9999983950105761 .0017916406648287528 .999998384256911 .0017976327676319532 .9999983734673407 .001803624870370609 .9999983626418649 .0018096169730445048 .9999983517804839 .0018156090756534257 .9999983408831975 .0018216011781971562 .9999983299500057 .0018275932806754815 .9999983189809085 .0018335853830881864 .999998307975906 .0018395774854350557 .9999982969349982 .001845569587715874 .9999982858581851 .0018515616899304264 .9999982747454665 .001857553792078498 .9999982635968426 .001863545894159873 .9999982524123134 .0018695379961743367 .9999982411918789 .001875530098121674 .9999982299355389 .0018815222000016696 .9999982186432936 .0018875143018141083 .999998207315143 .0018935064035587748 .999998195951087 .0018994985052354545 .9999981845511257 .0019054906068439318 .9999981731152591 .0019114827083839918 .999998161643487 .001917474809855419 .9999981501358096 .0019234669112579987 .999998138592227 .0019294590125915154 .9999981270127389 .0019354511138557542 .9999981153973455 .0019414432150504997 .9999981037460468 .0019474353161755369 .9999980920588427 .001953427417230651 .9999980803357332 .001959419518215626 .9999980685767185 .0019654116191302473 .9999980567817984 .0019714037199743 .9999980449509729 .0019773958207475683 .9999980330842422 .0019833879214498375 .999998021181606 .001989380022080892 .9999980092430646 .0019953721226405176 .9999979972686177 .002001364223128498 .9999979852582656 .002007356323544619 .9999979732120081 .002013348423888665 .9999979611298453 .002019340524160421 .9999979490117771 .0020253326243596715 .9999979368578036 .0020313247244862017 .9999979246679247 .002037316824539796 .9999979124421405 .00204330892452024 .999997900180451 .002049301024427318 .9999978878828562 .0020552931242608153 .9999978755493559 .002061285224020516 .9999978631799504 .0020672773237062057 .9999978507746395 .002073269423317669 .9999978383334234 .0020792615228546903 .9999978258563018 .002085253622317055 .999997813343275 .0020912457217045484 .9999978007943428 .002097237821016954 .9999977882095052 .0021032299202540577 .9999977755887623 .0021092220194156444 .9999977629321142 .0021152141185014984 .9999977502395607 .0021212062175114043 .9999977375111019 .002127198316445148 .9999977247467376 .0021331904153025134 .9999977119464681 .002139182514083286 .9999976991102932 .0021451746127872503 .9999976862382131 .002151166711414191 .9999976733302276 .0021571588099638934 .9999976603863368 .0021631509084361423 .9999976474065406 .002169143006830722 .9999976343908391 .002175135105147418 .9999976213392323 .0021811272033860148 .9999976082517201 .002187119301546297 .9999975951283027 .00219311139962805 .9999975819689799 .0021991034976310588 .9999975687737518 .0022050955955551076 .9999975555426184 .0022110876933999816 .9999975422755796 .0022170797911654654 .9999975289726355 .002223071888851344 .9999975156337861 .0022290639864574026 .9999975022590314 .0022350560839834253 .9999974888483714 .002241048181429198 .999997475401806 .0022470402787945045 .9999974619193353 .00225303237607913 .9999974484009593 .0022590244732828596 .9999974348466779 .0022650165704054784 .9999974212564913 .0022710086674467703 .9999974076303992 .002277000764406521 .9999973939684019 .002282992861284515 .9999973802704993 .0022889849580805368 .9999973665366915 .0022949770547943723 .9999973527669782 .0023009691514258054 .9999973389613596 .002306961247974621 .9999973251198357 .0023129533444406045 .9999973112424065 .0023189454408235406 .999997297329072 .0023249375371232135 .9999972833798322 .002330929633339409 .999997269394687 .0023369217294719113 .9999972553736366 .0023429138255205055 .9999972413166809 .0023489059214849765 .9999972272238198 .002354898017365109 .9999972130950534 .0023608901131606883 .9999971989303816 .0023668822088714985 .9999971847298047 .0023728743044973246 .9999971704933224 .0023788664000379523 .9999971562209347 .0023848584954931653 .9999971419126418 .0023908505908627493 .9999971275684435 .0023968426861464883 .99999711318834 .002402834781344168 .9999970987723311 .0024088268764555732 .9999970843204169 .002414818971480488 .9999970698325974 .002420811066418698 .9999970553088726 .0024268031612699878 .9999970407492426 .002432795256034142 .9999970261537071 .002438787350710946 .9999970115222664 .002444779445300184 .9999969968549204 .0024507715398016418 .9999969821516691 .002456763634215103 .9999969674125124 .002462755728540353 .9999969526374506 .0024687478227771774 .9999969378264834 .00247473991692536 .9999969229796108 .002480732010984686 .999996908096833 .0024867241049549406 .9999968931781499 .002492716198835908 .9999968782235614 .0024987082926273734 .9999968632330677 .002504700386329122 .9999968482066687 .002510692479940938 .9999968331443644 .0025166845734626068 .9999968180461547 .0025226766668939127 .9999968029120399 .002528668760234641 .9999967877420196 .002534660853484576 .9999967725360941 .0025406529466435036 .9999967572942633 .002546645039711208 .9999967420165272 .002552637132687474 .9999967267028858 .002558629225572086 .9999967113533391 .0025646213183648297 .9999966959678871 .0025706134110654896 .9999966805465298 .002576605503673851 .9999966650892672 .0025825975961896977 .9999966495960994 .0025885896886128153 .9999966340670262 .0025945817809429885 .9999966185020478 .0026005738731800024 .9999966029011641 .0026065659653236417 .999996587264375 .002612558057373691 .9999965715916808 .002618550149329935 .9999965558830811 .0026245422411921592 .9999965401385762 .002630534332960148 .9999965243581661 .002636526424633687 .9999965085418506 .0026425185162125596 .9999964926896299 .0026485106076965517 .9999964768015038 .0026545026990854484 .9999964608774725 .0026604947903790337 .9999964449175359 .0026664868815770926 .999996428921694 .0026724789726794104 .9999964128899468 .002678471063685772 .9999963968222944 .0026844631545959617 .9999963807187366 .002690455245409765 .9999963645792737 .002696447336126966 .9999963484039053 .00270243942674735 .9999963321926317 .002708431517270702 .9999963159454529 .0027144236076968066 .9999962996623687 .0027204156980254485 .9999962833433793 .002726407788256413 .9999962669884847 .002732399878389485 .9999962505976846 .0027383919684244484 .9999962341709794 .002744384058361089 .9999962177083689 .0027503761481991913 .999996201209853 .0027563682379385403 .9999961846754319 .0027623603275789207 .9999961681051056 .0027683524171201175 .999996151498874 .002774344506561915 .9999961348567371 .002780336595904099 .9999961181786949 .0027863286851464537 .9999961014647475 .0027923207742887642 .9999960847148948 .0027983128633308155 .9999960679291368 .002804304952272392 .9999960511074735 .002810297041113279 .9999960342499049 .0028162891298532606 .9999960173564312 .0028222812184921227 .9999960004270521 .002828273307029649 .9999959834617678 .002834265395465626 .9999959664605781 .0028402574837998367 .9999959494234832 .002846249572032067 .9999959323504831 .0028522416601621014 .9999959152415777 .002858233748189725 .999995898096767 .002864225836114723 .9999958809160512 .0028702179239368793 .9999958636994299 .0028762100116559793 .9999958464469034 .0028822020992718077 .9999958291584717 .0028881941867841495 .9999958118341348 .0028941862741927895 .9999957944738925 .0029001783614975127 .999995777077745 .002906170448698104 .9999957596456922 .0029121625357943475 .9999957421777342 .002918154622786029 .999995724673871 .0029241467096729327 .9999957071341024 .002930138796454844 .9999956895584287 .0029361308831315474 .9999956719468496 .0029421229697028273 .9999956542993652 .0029481150561684695 .9999956366159757 .0029541071425282584 .9999956188966809 .002960099228781979 .9999956011414808 .002966091314929416 .9999955833503754 .002972083400970354 .9999955655233649 .0029780754869045785 .9999955476604491 .0029840675727318736 .999995529761628 .002990059658452025 .9999955118269016 .0029960517440648163 .99999549385627 .0030020438295700336 .9999954758497331 .0030080359149674612 .999995457807291 .003014028000256884 .9999954397289438 .003020020085438087 .9999954216146911 .0030260121705108552 .9999954034645333 .003032004255474973 .9999953852784702 .003037996340330225 .9999953670565019 .003043988425076397 .9999953487986284 .003049980509713273 .9999953305048496 .0030559725942406386 .9999953121751655 .003061964678658278 )) (define high-lut (FLOATvector-const 1. 0. .9999999999999999 1.1703344634137277e-8 .9999999999999998 2.3406689268274554e-8 .9999999999999993 3.5110033902411824e-8 .9999999999999989 4.6813378536549095e-8 .9999999999999983 5.851672317068635e-8 .9999999999999976 7.022006780482361e-8 .9999999999999967 8.192341243896085e-8 .9999999999999957 9.362675707309808e-8 .9999999999999944 1.0533010170723531e-7 .9999999999999931 1.170334463413725e-7 .9999999999999917 1.287367909755097e-7 .9999999999999901 1.4044013560964687e-7 .9999999999999885 1.5214348024378403e-7 .9999999999999866 1.6384682487792116e-7 .9999999999999846 1.7555016951205827e-7 .9999999999999825 1.8725351414619535e-7 .9999999999999802 1.989568587803324e-7 .9999999999999778 2.1066020341446942e-7 .9999999999999752 2.2236354804860645e-7 .9999999999999726 2.3406689268274342e-7 .9999999999999698 2.4577023731688034e-7 .9999999999999668 2.5747358195101726e-7 .9999999999999638 2.6917692658515413e-7 .9999999999999606 2.8088027121929094e-7 .9999999999999571 2.9258361585342776e-7 .9999999999999537 3.042869604875645e-7 .99999999999995 3.159903051217012e-7 .9999999999999463 3.276936497558379e-7 .9999999999999424 3.3939699438997453e-7 .9999999999999384 3.5110033902411114e-7 .9999999999999342 3.6280368365824763e-7 .9999999999999298 3.7450702829238413e-7 .9999999999999254 3.8621037292652057e-7 .9999999999999208 3.979137175606569e-7 .9999999999999161 4.0961706219479325e-7 .9999999999999113 4.2132040682892953e-7 .9999999999999063 4.330237514630657e-7 .9999999999999011 4.447270960972019e-7 .9999999999998959 4.5643044073133796e-7 .9999999999998904 4.68133785365474e-7 .9999999999998849 4.7983712999961e-7 .9999999999998792 4.915404746337459e-7 .9999999999998733 5.032438192678817e-7 .9999999999998674 5.149471639020175e-7 .9999999999998613 5.266505085361531e-7 .9999999999998551 5.383538531702888e-7 .9999999999998487 5.500571978044243e-7 .9999999999998422 5.617605424385598e-7 .9999999999998356 5.734638870726952e-7 .9999999999998288 5.851672317068305e-7 .9999999999998219 5.968705763409657e-7 .9999999999998148 6.085739209751009e-7 .9999999999998076 6.202772656092359e-7 .9999999999998003 6.319806102433709e-7 .9999999999997928 6.436839548775058e-7 .9999999999997853 6.553872995116406e-7 .9999999999997775 6.670906441457753e-7 .9999999999997696 6.7879398877991e-7 .9999999999997616 6.904973334140445e-7 .9999999999997534 7.02200678048179e-7 .9999999999997452 7.139040226823132e-7 .9999999999997368 7.256073673164475e-7 .9999999999997282 7.373107119505817e-7 .9999999999997194 7.490140565847157e-7 .9999999999997107 7.607174012188497e-7 .9999999999997017 7.724207458529835e-7 .9999999999996926 7.841240904871172e-7 .9999999999996834 7.958274351212508e-7 .9999999999996739 8.075307797553844e-7 .9999999999996644 8.192341243895178e-7 .9999999999996547 8.309374690236511e-7 .999999999999645 8.426408136577842e-7 .9999999999996351 8.543441582919173e-7 .999999999999625 8.660475029260503e-7 .9999999999996148 8.777508475601831e-7 .9999999999996044 8.894541921943158e-7 .999999999999594 9.011575368284484e-7 .9999999999995833 9.128608814625808e-7 .9999999999995726 9.245642260967132e-7 .9999999999995617 9.362675707308454e-7 .9999999999995507 9.479709153649775e-7 .9999999999995395 9.596742599991095e-7 .9999999999995283 9.713776046332412e-7 .9999999999995168 9.83080949267373e-7 .9999999999995052 9.947842939015044e-7 .9999999999994935 1.006487638535636e-6 .9999999999994816 1.0181909831697673e-6 .9999999999994696 1.0298943278038984e-6 .9999999999994575 1.0415976724380293e-6 .9999999999994453 1.0533010170721601e-6 .9999999999994329 1.065004361706291e-6 .9999999999994204 1.0767077063404215e-6 .9999999999994077 1.088411050974552e-6 .9999999999993949 1.1001143956086822e-6 .9999999999993819 1.1118177402428122e-6 .9999999999993688 1.1235210848769423e-6 .9999999999993556 1.135224429511072e-6 .9999999999993423 1.1469277741452017e-6 .9999999999993288 1.1586311187793313e-6 .9999999999993151 1.1703344634134605e-6 .9999999999993014 1.1820378080475897e-6 .9999999999992875 1.1937411526817187e-6 .9999999999992735 1.2054444973158477e-6 .9999999999992593 1.2171478419499764e-6 .9999999999992449 1.2288511865841048e-6 .9999999999992305 1.2405545312182331e-6 .999999999999216 1.2522578758523615e-6 .9999999999992012 1.2639612204864894e-6 .9999999999991863 1.2756645651206173e-6 .9999999999991713 1.287367909754745e-6 .9999999999991562 1.2990712543888725e-6 .9999999999991409 1.3107745990229998e-6 .9999999999991255 1.3224779436571269e-6 .9999999999991099 1.3341812882912537e-6 .9999999999990943 1.3458846329253806e-6 .9999999999990785 1.3575879775595072e-6 .9999999999990625 1.3692913221936337e-6 .9999999999990464 1.3809946668277597e-6 .9999999999990302 1.3926980114618857e-6 .9999999999990138 1.4044013560960117e-6 .9999999999989974 1.4161047007301373e-6 .9999999999989807 1.4278080453642627e-6 .9999999999989639 1.439511389998388e-6 .999999999998947 1.451214734632513e-6 .99999999999893 1.462918079266638e-6 .9999999999989128 1.4746214239007625e-6 .9999999999988954 1.486324768534887e-6 .999999999998878 1.4980281131690111e-6 .9999999999988604 1.5097314578031353e-6 .9999999999988426 1.5214348024372591e-6 .9999999999988247 1.5331381470713828e-6 .9999999999988067 1.544841491705506e-6 .9999999999987886 1.5565448363396294e-6 .9999999999987703 1.5682481809737524e-6 .9999999999987519 1.579951525607875e-6 .9999999999987333 1.5916548702419977e-6 .9999999999987146 1.60335821487612e-6 .9999999999986958 1.615061559510242e-6 .9999999999986768 1.626764904144364e-6 .9999999999986577 1.6384682487784858e-6 .9999999999986384 1.6501715934126072e-6 .9999999999986191 1.6618749380467283e-6 .9999999999985996 1.6735782826808495e-6 .9999999999985799 1.6852816273149702e-6 .9999999999985602 1.6969849719490907e-6 .9999999999985402 1.708688316583211e-6 .9999999999985201 1.720391661217331e-6 .9999999999985 1.732095005851451e-6 .9999999999984795 1.7437983504855706e-6 .9999999999984591 1.7555016951196899e-6 .9999999999984385 1.767205039753809e-6 .9999999999984177 1.778908384387928e-6 .9999999999983968 1.7906117290220465e-6 .9999999999983759 1.802315073656165e-6 .9999999999983546 1.814018418290283e-6 .9999999999983333 1.825721762924401e-6 .9999999999983119 1.8374251075585186e-6 .9999999999982904 1.8491284521926361e-6 .9999999999982686 1.8608317968267533e-6 .9999999999982468 1.8725351414608702e-6 .9999999999982249 1.8842384860949866e-6 .9999999999982027 1.8959418307291031e-6 .9999999999981805 1.9076451753632194e-6 .999999999998158 1.919348519997335e-6 .9999999999981355 1.9310518646314507e-6 .9999999999981128 1.942755209265566e-6 .9999999999980901 1.954458553899681e-6 .9999999999980671 1.966161898533796e-6 .999999999998044 1.9778652431679103e-6 .9999999999980208 1.9895685878020246e-6 .9999999999979975 2.0012719324361386e-6 .999999999997974 2.012975277070252e-6 .9999999999979503 2.0246786217043656e-6 .9999999999979265 2.0363819663384787e-6 .9999999999979027 2.048085310972592e-6 .9999999999978786 2.0597886556067045e-6 .9999999999978545 2.0714920002408167e-6 .9999999999978302 2.0831953448749286e-6 .9999999999978058 2.0948986895090404e-6 .9999999999977811 2.106602034143152e-6 .9999999999977564 2.118305378777263e-6 .9999999999977315 2.1300087234113738e-6 .9999999999977065 2.1417120680454843e-6 .9999999999976814 2.153415412679595e-6 .9999999999976561 2.1651187573137046e-6 .9999999999976307 2.1768221019478143e-6 .9999999999976051 2.188525446581924e-6 .9999999999975795 2.200228791216033e-6 .9999999999975536 2.2119321358501417e-6 .9999999999975278 2.22363548048425e-6 .9999999999975017 2.2353388251183586e-6 .9999999999974754 2.247042169752466e-6 .999999999997449 2.2587455143865738e-6 .9999999999974225 2.2704488590206814e-6 .9999999999973959 2.282152203654788e-6 .9999999999973691 2.293855548288895e-6 .9999999999973422 2.305558892923001e-6 .9999999999973151 2.317262237557107e-6 .999999999997288 2.328965582191213e-6 .9999999999972606 2.340668926825318e-6 .9999999999972332 2.352372271459423e-6 .9999999999972056 2.364075616093528e-6 .9999999999971778 2.3757789607276323e-6 .99999999999715 2.3874823053617365e-6 .999999999997122 2.3991856499958403e-6 .9999999999970938 2.4108889946299437e-6 .9999999999970656 2.4225923392640466e-6 .9999999999970371 2.4342956838981495e-6 .9999999999970085 2.445999028532252e-6 .9999999999969799 2.457702373166354e-6 .999999999996951 2.4694057178004558e-6 .999999999996922 2.4811090624345574e-6 .9999999999968929 2.4928124070686583e-6 .9999999999968637 2.504515751702759e-6 .9999999999968343 2.5162190963368595e-6 .9999999999968048 2.5279224409709594e-6 .9999999999967751 2.5396257856050594e-6 .9999999999967454 2.5513291302391585e-6 .9999999999967154 2.5630324748732576e-6 .9999999999966853 2.5747358195073563e-6 .9999999999966551 2.5864391641414546e-6 .9999999999966248 2.5981425087755525e-6 .9999999999965944 2.6098458534096503e-6 .9999999999965637 2.6215491980437473e-6 .999999999996533 2.6332525426778443e-6 .9999999999965021 2.644955887311941e-6 .999999999996471 2.656659231946037e-6 .99999999999644 2.6683625765801328e-6 .9999999999964087 2.680065921214228e-6 .9999999999963772 2.6917692658483234e-6 .9999999999963456 2.703472610482418e-6 .999999999996314 2.7151759551165123e-6 .9999999999962821 2.7268792997506064e-6 .9999999999962501 2.7385826443846996e-6 .9999999999962179 2.750285989018793e-6 .9999999999961857 2.761989333652886e-6 .9999999999961533 2.7736926782869783e-6 .9999999999961208 2.78539602292107e-6 .9999999999960881 2.797099367555162e-6 .9999999999960553 2.808802712189253e-6 .9999999999960224 2.8205060568233443e-6 .9999999999959893 2.832209401457435e-6 .9999999999959561 2.8439127460915247e-6 .9999999999959227 2.8556160907256145e-6 .9999999999958893 2.867319435359704e-6 .9999999999958556 2.879022779993793e-6 .9999999999958219 2.8907261246278814e-6 .9999999999957879 2.90242946926197e-6 .999999999995754 2.9141328138960576e-6 .9999999999957198 2.925836158530145e-6 .9999999999956855 2.9375395031642317e-6 .999999999995651 2.9492428477983186e-6 .9999999999956164 2.9609461924324046e-6 .9999999999955816 2.9726495370664905e-6 .9999999999955468 2.9843528817005757e-6 .9999999999955118 2.996056226334661e-6 .9999999999954767 3.007759570968745e-6 .9999999999954414 3.0194629156028294e-6 .999999999995406 3.0311662602369133e-6 .9999999999953705 3.0428696048709963e-6 .9999999999953348 3.0545729495050794e-6 .999999999995299 3.066276294139162e-6 .999999999995263 3.0779796387732437e-6 .9999999999952269 3.0896829834073255e-6 .9999999999951907 3.101386328041407e-6 .9999999999951543 3.1130896726754873e-6 .9999999999951178 3.1247930173095678e-6 .9999999999950812 3.136496361943648e-6 .9999999999950444 3.148199706577727e-6 .9999999999950075 3.1599030512118063e-6 .9999999999949705 3.171606395845885e-6 .9999999999949333 3.183309740479963e-6 .999999999994896 3.195013085114041e-6 .9999999999948584 3.206716429748118e-6 .9999999999948209 3.218419774382195e-6 .9999999999947832 3.2301231190162714e-6 .9999999999947453 3.2418264636503477e-6 .9999999999947072 3.253529808284423e-6 .9999999999946692 3.265233152918498e-6 .9999999999946309 3.276936497552573e-6 .9999999999945924 3.288639842186647e-6 .9999999999945539 3.300343186820721e-6 .9999999999945152 3.312046531454794e-6 .9999999999944763 3.323749876088867e-6 .9999999999944373 3.3354532207229395e-6 .9999999999943983 3.3471565653570115e-6 .9999999999943591 3.358859909991083e-6 .9999999999943197 3.370563254625154e-6 .9999999999942801 3.3822665992592245e-6 .9999999999942405 3.3939699438932944e-6 .9999999999942008 3.4056732885273643e-6 .9999999999941608 3.4173766331614334e-6 .9999999999941207 3.429079977795502e-6 .9999999999940805 3.4407833224295702e-6 .9999999999940402 3.452486667063638e-6 .9999999999939997 3.4641900116977054e-6 .999999999993959 3.4758933563317723e-6 .9999999999939183 3.4875967009658384e-6 .9999999999938775 3.4993000455999045e-6 .9999999999938364 3.5110033902339697e-6 .9999999999937953 3.5227067348680345e-6 .999999999993754 3.534410079502099e-6 .9999999999937126 3.546113424136163e-6 .999999999993671 3.5578167687702264e-6 .9999999999936293 3.5695201134042896e-6 .9999999999935875 3.581223458038352e-6 .9999999999935454 3.592926802672414e-6 .9999999999935033 3.6046301473064755e-6 .9999999999934611 3.6163334919405365e-6 .9999999999934187 3.628036836574597e-6 .9999999999933762 3.639740181208657e-6 .9999999999933334 3.6514435258427166e-6 .9999999999932907 3.6631468704767755e-6 .9999999999932477 3.674850215110834e-6 .9999999999932047 3.686553559744892e-6 .9999999999931615 3.6982569043789496e-6 .9999999999931181 3.7099602490130064e-6 .9999999999930747 3.7216635936470627e-6 .999999999993031 3.733366938281119e-6 .9999999999929873 3.745070282915174e-6 .9999999999929433 3.756773627549229e-6 .9999999999928992 3.768476972183284e-6 .9999999999928552 3.7801803168173377e-6 .9999999999928109 3.791883661451391e-6 .9999999999927663 3.803587006085444e-6 .9999999999927218 3.8152903507194965e-6 .9999999999926771 3.826993695353548e-6 .9999999999926322 3.838697039987599e-6 .9999999999925873 3.85040038462165e-6 .9999999999925421 3.862103729255701e-6 .9999999999924968 3.87380707388975e-6 .9999999999924514 3.885510418523799e-6 .9999999999924059 3.897213763157848e-6 .9999999999923602 3.9089171077918965e-6 .9999999999923144 3.9206204524259435e-6 .9999999999922684 3.9323237970599905e-6 .9999999999922223 3.9440271416940376e-6 .9999999999921761 3.955730486328084e-6 .9999999999921297 3.967433830962129e-6 .9999999999920832 3.9791371755961736e-6 .9999999999920366 3.990840520230218e-6 .9999999999919899 4.002543864864262e-6 .9999999999919429 4.014247209498305e-6 .9999999999918958 4.025950554132348e-6 .9999999999918486 4.03765389876639e-6 .9999999999918013 4.049357243400431e-6 .9999999999917539 4.061060588034472e-6 .9999999999917063 4.072763932668513e-6 .9999999999916586 4.084467277302553e-6 .9999999999916107 4.096170621936592e-6 .9999999999915626 4.107873966570632e-6 .9999999999915146 4.119577311204669e-6 .9999999999914663 4.131280655838707e-6 .9999999999914179 4.142984000472745e-6 .9999999999913692 4.154687345106781e-6 .9999999999913206 4.166390689740817e-6 .9999999999912718 4.178094034374852e-6 .9999999999912228 4.189797379008887e-6 .9999999999911737 4.201500723642921e-6 .9999999999911244 4.213204068276955e-6 .999999999991075 4.224907412910988e-6 .9999999999910255 4.236610757545021e-6 .9999999999909759 4.248314102179053e-6 .9999999999909261 4.260017446813084e-6 .9999999999908762 4.271720791447115e-6 .9999999999908261 4.283424136081145e-6 .9999999999907759 4.295127480715175e-6 .9999999999907256 4.306830825349204e-6 .9999999999906751 4.3185341699832325e-6 .9999999999906245 4.33023751461726e-6 .9999999999905738 4.3419408592512875e-6 .9999999999905229 4.353644203885314e-6 .9999999999904718 4.36534754851934e-6 .9999999999904207 4.377050893153365e-6 .9999999999903694 4.38875423778739e-6 .999999999990318 4.400457582421414e-6 .9999999999902665 4.4121609270554384e-6 .9999999999902147 4.423864271689461e-6 .9999999999901629 4.435567616323483e-6 .9999999999901109 4.447270960957506e-6 .9999999999900587 4.458974305591527e-6 .9999999999900065 4.470677650225547e-6 .9999999999899541 4.482380994859567e-6 .9999999999899016 4.494084339493587e-6 .9999999999898489 4.5057876841276054e-6 .9999999999897962 4.517491028761624e-6 .9999999999897432 4.529194373395641e-6 .9999999999896901 4.5408977180296584e-6 .999999999989637 4.552601062663675e-6 .9999999999895836 4.564304407297691e-6 .99999999998953 4.5760077519317055e-6 .9999999999894764 4.5877110965657195e-6 .9999999999894227 4.5994144411997335e-6 .9999999999893688 4.611117785833747e-6 .9999999999893148 4.622821130467759e-6 .9999999999892606 4.634524475101771e-6 .9999999999892063 4.646227819735783e-6 .9999999999891518 4.657931164369793e-6 .9999999999890973 4.669634509003803e-6 .9999999999890425 4.681337853637813e-6 .9999999999889877 4.693041198271821e-6 .9999999999889327 4.704744542905829e-6 .9999999999888776 4.716447887539837e-6 .9999999999888223 4.728151232173843e-6 .9999999999887669 4.73985457680785e-6 .9999999999887114 4.751557921441855e-6 .9999999999886556 4.76326126607586e-6 .9999999999885999 4.774964610709864e-6 .9999999999885439 4.786667955343868e-6 .9999999999884878 4.798371299977871e-6 .9999999999884316 4.810074644611873e-6 .9999999999883752 4.821777989245874e-6 .9999999999883187 4.833481333879875e-6 .9999999999882621 4.845184678513876e-6 .9999999999882053 4.856888023147875e-6 .9999999999881484 4.868591367781874e-6 .9999999999880914 4.880294712415872e-6 .9999999999880341 4.89199805704987e-6 .9999999999879768 4.903701401683867e-6 .9999999999879194 4.915404746317863e-6 .9999999999878618 4.9271080909518585e-6 .9999999999878041 4.938811435585853e-6 .9999999999877462 4.9505147802198475e-6 .9999999999876882 4.962218124853841e-6 .99999999998763 4.973921469487834e-6 .9999999999875717 4.985624814121826e-6 .9999999999875133 4.997328158755817e-6 .9999999999874548 5.009031503389808e-6 .9999999999873961 5.0207348480237985e-6 .9999999999873372 5.032438192657788e-6 .9999999999872783 5.0441415372917765e-6 .9999999999872192 5.055844881925764e-6 .9999999999871599 5.067548226559752e-6 .9999999999871007 5.079251571193739e-6 .9999999999870411 5.090954915827725e-6 .9999999999869814 5.10265826046171e-6 .9999999999869217 5.1143616050956945e-6 .9999999999868617 5.126064949729678e-6 .9999999999868017 5.1377682943636615e-6 .9999999999867415 5.149471638997644e-6 .9999999999866811 5.161174983631626e-6 .9999999999866207 5.172878328265607e-6 .9999999999865601 5.184581672899587e-6 .9999999999864994 5.196285017533567e-6 .9999999999864384 5.2079883621675455e-6 .9999999999863775 5.219691706801524e-6 .9999999999863163 5.2313950514355015e-6 .999999999986255 5.243098396069478e-6 .9999999999861935 5.254801740703454e-6 .999999999986132 5.266505085337429e-6 .9999999999860703 5.278208429971404e-6 .9999999999860084 5.289911774605378e-6 .9999999999859465 5.301615119239351e-6 .9999999999858843 5.313318463873323e-6 .9999999999858221 5.325021808507295e-6 .9999999999857597 5.336725153141267e-6 .9999999999856971 5.3484284977752366e-6 .9999999999856345 5.360131842409206e-6 .9999999999855717 5.371835187043175e-6 .9999999999855087 5.383538531677143e-6 .9999999999854456 5.3952418763111104e-6 .9999999999853825 5.406945220945077e-6 .9999999999853191 5.418648565579043e-6 .9999999999852557 5.4303519102130076e-6 .9999999999851921 5.4420552548469724e-6 .9999999999851282 5.453758599480936e-6 .9999999999850644 5.465461944114899e-6 .9999999999850003 5.47716528874886e-6 .9999999999849362 5.488868633382822e-6 .9999999999848719 5.500571978016782e-6 .9999999999848074 5.512275322650742e-6 .9999999999847429 5.523978667284702e-6 .9999999999846781 5.53568201191866e-6 .9999999999846133 5.547385356552617e-6 .9999999999845482 5.5590887011865745e-6 .9999999999844832 5.57079204582053e-6 .9999999999844179 5.582495390454486e-6 .9999999999843525 5.59419873508844e-6 .9999999999842869 5.605902079722394e-6 .9999999999842213 5.617605424356347e-6 .9999999999841555 5.629308768990299e-6 .9999999999840895 5.641012113624251e-6 .9999999999840234 5.652715458258201e-6 .9999999999839572 5.664418802892152e-6 .9999999999838908 5.6761221475261e-6 .9999999999838243 5.687825492160048e-6 .9999999999837577 5.699528836793996e-6 .9999999999836909 5.711232181427943e-6 .999999999983624 5.722935526061889e-6 .9999999999835569 5.734638870695834e-6 .9999999999834898 5.746342215329779e-6 .9999999999834225 5.758045559963722e-6 .999999999983355 5.769748904597665e-6 .9999999999832874 5.781452249231607e-6 .9999999999832196 5.793155593865548e-6 .9999999999831518 5.804858938499489e-6 .9999999999830838 5.816562283133429e-6 .9999999999830157 5.8282656277673675e-6 .9999999999829474 5.839968972401306e-6 .9999999999828789 5.851672317035243e-6 .9999999999828104 5.86337566166918e-6 .9999999999827417 5.875079006303115e-6 .9999999999826729 5.88678235093705e-6 .9999999999826039 5.898485695570985e-6 .9999999999825349 5.910189040204917e-6 .9999999999824656 5.92189238483885e-6 .9999999999823962 5.933595729472782e-6 .9999999999823267 5.945299074106713e-6 .9999999999822571 5.957002418740643e-6 .9999999999821872 5.9687057633745715e-6 .9999999999821173 5.9804091080085e-6 )) (define (make-w log-n) (let* ((n (expt 2 log-n)) ;; number of complexes (result (FLOATmake-vector (* 2 n)))) (define (copy-low-lut) (do ((i 0 (+ i 1))) ((= i lut-table-size)) (let ((index (* i 2))) (FLOATvector-set! result index (FLOATvector-ref low-lut index)) (FLOATvector-set! result (+ index 1) (FLOATvector-ref low-lut (+ index 1)))))) (define (extend-lut multiplier-lut bit-reverse-size bit-reverse-multiplier start end) (define (bit-reverse x n) (do ((i 0 (+ i 1)) (x x (arithmetic-shift x -1)) (result 0 (+ (* result 2) (bitwise-and x 1)))) ((= i n) result))) (let loop ((i start) (j 1)) (if (< i end) (let* ((multiplier-index (* 2 (* (bit-reverse j bit-reverse-size) bit-reverse-multiplier))) (multiplier-real (FLOATvector-ref multiplier-lut multiplier-index)) (multiplier-imag (FLOATvector-ref multiplier-lut (+ multiplier-index 1)))) (let inner ((i i) (k 0)) ;; we copy complex multiples of all entries below ;; start to entries starting at start (if (< k start) (let* ((index (* k 2)) (real (FLOATvector-ref result index)) (imag (FLOATvector-ref result (+ index 1))) (result-real (FLOAT- (FLOAT* multiplier-real real) (FLOAT* multiplier-imag imag))) (result-imag (FLOAT+ (FLOAT* multiplier-real imag) (FLOAT* multiplier-imag real))) (result-index (* i 2))) (FLOATvector-set! result result-index result-real) (FLOATvector-set! result (+ result-index 1) result-imag) (inner (+ i 1) (+ k 1))) (loop i (+ j 1))))) result))) (cond ((<= n lut-table-size) low-lut) ((<= n lut-table-size^2) (copy-low-lut) (extend-lut med-lut (- log-n log-lut-table-size) (arithmetic-shift 1 (- (* 2 log-lut-table-size) log-n)) lut-table-size n)) ((<= n lut-table-size^3) (copy-low-lut) (extend-lut med-lut log-lut-table-size 1 lut-table-size lut-table-size^2) (extend-lut high-lut (- log-n (* 2 log-lut-table-size)) (arithmetic-shift 1 (- (* 3 log-lut-table-size) log-n)) lut-table-size^2 n)) (else (error "asking for too large a table"))))) (define (direct-fft-recursive-4 a W-table) ;; This is a direcct complex fft, using a decimation-in-time ;; algorithm with inputs in natural order and outputs in ;; bit-reversed order. The table of "twiddle" factors is in ;; bit-reversed order. this is from page 66 of and , except that we have ;; combined passes in pairs to cut the number of passes through ;; the vector a (let ((W (FLOATvector 0. 0. 0. 0.))) (define (main-loop M N K SizeOfGroup) (let inner-loop ((K K) (JFirst M)) (if (< JFirst N) (let* ((JLast (+ JFirst SizeOfGroup))) (if (even? K) (begin (FLOATvector-set! W 0 (FLOATvector-ref W-table K)) (FLOATvector-set! W 1 (FLOATvector-ref W-table (+ K 1)))) (begin (FLOATvector-set! W 0 (FLOAT- 0. (FLOATvector-ref W-table K))) (FLOATvector-set! W 1 (FLOATvector-ref W-table (- K 1))))) we know the that the next two complex roots of unity have index 2 K and 2K+1 so that the 2K+1 index root can be gotten from the 2 K index root in the same way that we get W_0 and W_1 from the ;; table depending on whether K is even or not (FLOATvector-set! W 2 (FLOATvector-ref W-table (* K 2))) (FLOATvector-set! W 3 (FLOATvector-ref W-table (+ (* K 2) 1))) (let J-loop ((J0 JFirst)) (if (< J0 JLast) (let* ((J0 J0) (J1 (+ J0 1)) (J2 (+ J0 SizeOfGroup)) (J3 (+ J2 1)) (J4 (+ J2 SizeOfGroup)) (J5 (+ J4 1)) (J6 (+ J4 SizeOfGroup)) (J7 (+ J6 1))) (let ((W_0 (FLOATvector-ref W 0)) (W_1 (FLOATvector-ref W 1)) (W_2 (FLOATvector-ref W 2)) (W_3 (FLOATvector-ref W 3)) (a_J0 (FLOATvector-ref a J0)) (a_J1 (FLOATvector-ref a J1)) (a_J2 (FLOATvector-ref a J2)) (a_J3 (FLOATvector-ref a J3)) (a_J4 (FLOATvector-ref a J4)) (a_J5 (FLOATvector-ref a J5)) (a_J6 (FLOATvector-ref a J6)) (a_J7 (FLOATvector-ref a J7))) ;; first we do the (overlapping) pairs of butterflies with entries 2*SizeOfGroup ;; apart. (let ((Temp_0 (FLOAT- (FLOAT* W_0 a_J4) (FLOAT* W_1 a_J5))) (Temp_1 (FLOAT+ (FLOAT* W_0 a_J5) (FLOAT* W_1 a_J4))) (Temp_2 (FLOAT- (FLOAT* W_0 a_J6) (FLOAT* W_1 a_J7))) (Temp_3 (FLOAT+ (FLOAT* W_0 a_J7) (FLOAT* W_1 a_J6)))) (let ((a_J0 (FLOAT+ a_J0 Temp_0)) (a_J1 (FLOAT+ a_J1 Temp_1)) (a_J2 (FLOAT+ a_J2 Temp_2)) (a_J3 (FLOAT+ a_J3 Temp_3)) (a_J4 (FLOAT- a_J0 Temp_0)) (a_J5 (FLOAT- a_J1 Temp_1)) (a_J6 (FLOAT- a_J2 Temp_2)) (a_J7 (FLOAT- a_J3 Temp_3))) now we do the two ( disjoint ) pairs ;; of butterflies distance SizeOfGroup apart , the first pair with , the second with -W3+W2i ;; we rewrite the multipliers so I ;; don't hurt my head too much when ;; thinking about them. (let ((W_0 W_2) (W_1 W_3) (W_2 (FLOAT- 0. W_3)) (W_3 W_2)) (let ((Temp_0 (FLOAT- (FLOAT* W_0 a_J2) (FLOAT* W_1 a_J3))) (Temp_1 (FLOAT+ (FLOAT* W_0 a_J3) (FLOAT* W_1 a_J2))) (Temp_2 (FLOAT- (FLOAT* W_2 a_J6) (FLOAT* W_3 a_J7))) (Temp_3 (FLOAT+ (FLOAT* W_2 a_J7) (FLOAT* W_3 a_J6)))) (let ((a_J0 (FLOAT+ a_J0 Temp_0)) (a_J1 (FLOAT+ a_J1 Temp_1)) (a_J2 (FLOAT- a_J0 Temp_0)) (a_J3 (FLOAT- a_J1 Temp_1)) (a_J4 (FLOAT+ a_J4 Temp_2)) (a_J5 (FLOAT+ a_J5 Temp_3)) (a_J6 (FLOAT- a_J4 Temp_2)) (a_J7 (FLOAT- a_J5 Temp_3))) (FLOATvector-set! a J0 a_J0) (FLOATvector-set! a J1 a_J1) (FLOATvector-set! a J2 a_J2) (FLOATvector-set! a J3 a_J3) (FLOATvector-set! a J4 a_J4) (FLOATvector-set! a J5 a_J5) (FLOATvector-set! a J6 a_J6) (FLOATvector-set! a J7 a_J7) (J-loop (+ J0 2))))))))) (inner-loop (+ K 1) (+ JFirst (* SizeOfGroup 4))))))))) (define (recursive-bit M N K SizeOfGroup) (if (<= 2 SizeOfGroup) (begin (main-loop M N K SizeOfGroup) (if (< 2048 (- N M)) (let ((new-size (arithmetic-shift (- N M) -2))) (recursive-bit M (+ M new-size) (* K 4) (arithmetic-shift SizeOfGroup -2)) (recursive-bit (+ M new-size) (+ M (* new-size 2)) (+ (* K 4) 1) (arithmetic-shift SizeOfGroup -2)) (recursive-bit (+ M (* new-size 2)) (+ M (* new-size 3)) (+ (* K 4) 2) (arithmetic-shift SizeOfGroup -2)) (recursive-bit (+ M (* new-size 3)) N (+ (* K 4) 3) (arithmetic-shift SizeOfGroup -2))) (recursive-bit M N (* K 4) (arithmetic-shift SizeOfGroup -2)))))) (define (radix-2-pass a) ;; If we're here, the size of our (conceptually complex) array is not a power of 4 , so we need to do a basic radix two pass with w=1 ( so W[0]=1.0 and W[1 ] = 0 . ) and then call recursive - bit appropriately on the two half arrays . (let ((SizeOfGroup (arithmetic-shift (FLOATvector-length a) -1))) (let loop ((J0 0)) (if (< J0 SizeOfGroup) (let ((J0 J0) (J2 (+ J0 SizeOfGroup))) (let ((J1 (+ J0 1)) (J3 (+ J2 1))) (let ((a_J0 (FLOATvector-ref a J0)) (a_J1 (FLOATvector-ref a J1)) (a_J2 (FLOATvector-ref a J2)) (a_J3 (FLOATvector-ref a J3))) (let ((a_J0 (FLOAT+ a_J0 a_J2)) (a_J1 (FLOAT+ a_J1 a_J3)) (a_J2 (FLOAT- a_J0 a_J2)) (a_J3 (FLOAT- a_J1 a_J3))) (FLOATvector-set! a J0 a_J0) (FLOATvector-set! a J1 a_J1) (FLOATvector-set! a J2 a_J2) (FLOATvector-set! a J3 a_J3) (loop (+ J0 2)))))))))) (let* ((n (FLOATvector-length a)) (log_n (two^p>=m n))) there are n/2 complex entries in a ; if is not a power of 4 , then do a single radix-2 pass and do the rest of ;; the passes as radix-4 passes (if (odd? log_n) (recursive-bit 0 n 0 (arithmetic-shift n -2)) (let ((n/2 (arithmetic-shift n -1)) (n/8 (arithmetic-shift n -3))) (radix-2-pass a) (recursive-bit 0 n/2 0 n/8) (recursive-bit n/2 n 1 n/8)))))) (define (inverse-fft-recursive-4 a W-table) ;; This is an complex fft, using a decimation-in-frequency algorithm ;; with inputs in bit-reversed order and outputs in natural order. ;; The organization of the algorithm has little to do with the the associated algorithm on page 41 of and , ;; I just reversed the operations of the direct algorithm given above ( without dividing by 2 each time , so that this has to be " normalized " by dividing by N/2 at the end . ;; The table of "twiddle" factors is in bit-reversed order. (let ((W (FLOATvector 0. 0. 0. 0.))) (define (main-loop M N K SizeOfGroup) (let inner-loop ((K K) (JFirst M)) (if (< JFirst N) (let* ((JLast (+ JFirst SizeOfGroup))) (if (even? K) (begin (FLOATvector-set! W 0 (FLOATvector-ref W-table K)) (FLOATvector-set! W 1 (FLOATvector-ref W-table (+ K 1)))) (begin (FLOATvector-set! W 0 (FLOAT- 0. (FLOATvector-ref W-table K))) (FLOATvector-set! W 1 (FLOATvector-ref W-table (- K 1))))) (FLOATvector-set! W 2 (FLOATvector-ref W-table (* K 2))) (FLOATvector-set! W 3 (FLOATvector-ref W-table (+ (* K 2) 1))) (let J-loop ((J0 JFirst)) (if (< J0 JLast) (let* ((J0 J0) (J1 (+ J0 1)) (J2 (+ J0 SizeOfGroup)) (J3 (+ J2 1)) (J4 (+ J2 SizeOfGroup)) (J5 (+ J4 1)) (J6 (+ J4 SizeOfGroup)) (J7 (+ J6 1))) (let ((W_0 (FLOATvector-ref W 0)) (W_1 (FLOATvector-ref W 1)) (W_2 (FLOATvector-ref W 2)) (W_3 (FLOATvector-ref W 3)) (a_J0 (FLOATvector-ref a J0)) (a_J1 (FLOATvector-ref a J1)) (a_J2 (FLOATvector-ref a J2)) (a_J3 (FLOATvector-ref a J3)) (a_J4 (FLOATvector-ref a J4)) (a_J5 (FLOATvector-ref a J5)) (a_J6 (FLOATvector-ref a J6)) (a_J7 (FLOATvector-ref a J7))) (let ((W_00 W_2) (W_01 W_3) (W_02 (FLOAT- 0. W_3)) (W_03 W_2)) (let ((Temp_0 (FLOAT- a_J0 a_J2)) (Temp_1 (FLOAT- a_J1 a_J3)) (Temp_2 (FLOAT- a_J4 a_J6)) (Temp_3 (FLOAT- a_J5 a_J7))) (let ((a_J0 (FLOAT+ a_J0 a_J2)) (a_J1 (FLOAT+ a_J1 a_J3)) (a_J4 (FLOAT+ a_J4 a_J6)) (a_J5 (FLOAT+ a_J5 a_J7)) (a_J2 (FLOAT+ (FLOAT* W_00 Temp_0) (FLOAT* W_01 Temp_1))) (a_J3 (FLOAT- (FLOAT* W_00 Temp_1) (FLOAT* W_01 Temp_0))) (a_J6 (FLOAT+ (FLOAT* W_02 Temp_2) (FLOAT* W_03 Temp_3))) (a_J7 (FLOAT- (FLOAT* W_02 Temp_3) (FLOAT* W_03 Temp_2)))) (let ((Temp_0 (FLOAT- a_J0 a_J4)) (Temp_1 (FLOAT- a_J1 a_J5)) (Temp_2 (FLOAT- a_J2 a_J6)) (Temp_3 (FLOAT- a_J3 a_J7))) (let ((a_J0 (FLOAT+ a_J0 a_J4)) (a_J1 (FLOAT+ a_J1 a_J5)) (a_J2 (FLOAT+ a_J2 a_J6)) (a_J3 (FLOAT+ a_J3 a_J7)) (a_J4 (FLOAT+ (FLOAT* W_0 Temp_0) (FLOAT* W_1 Temp_1))) (a_J5 (FLOAT- (FLOAT* W_0 Temp_1) (FLOAT* W_1 Temp_0))) (a_J6 (FLOAT+ (FLOAT* W_0 Temp_2) (FLOAT* W_1 Temp_3))) (a_J7 (FLOAT- (FLOAT* W_0 Temp_3) (FLOAT* W_1 Temp_2)))) (FLOATvector-set! a J0 a_J0) (FLOATvector-set! a J1 a_J1) (FLOATvector-set! a J2 a_J2) (FLOATvector-set! a J3 a_J3) (FLOATvector-set! a J4 a_J4) (FLOATvector-set! a J5 a_J5) (FLOATvector-set! a J6 a_J6) (FLOATvector-set! a J7 a_J7) (J-loop (+ J0 2))))))))) (inner-loop (+ K 1) (+ JFirst (* SizeOfGroup 4))))))))) (define (recursive-bit M N K SizeOfGroup) (if (<= 2 SizeOfGroup) (begin (if (< 2048 (- N M)) (let ((new-size (arithmetic-shift (- N M) -2))) (recursive-bit M (+ M new-size) (* K 4) (arithmetic-shift SizeOfGroup -2)) (recursive-bit (+ M new-size) (+ M (* new-size 2)) (+ (* K 4) 1) (arithmetic-shift SizeOfGroup -2)) (recursive-bit (+ M (* new-size 2)) (+ M (* new-size 3)) (+ (* K 4) 2) (arithmetic-shift SizeOfGroup -2)) (recursive-bit (+ M (* new-size 3)) N (+ (* K 4) 3) (arithmetic-shift SizeOfGroup -2))) (recursive-bit M N (* K 4) (arithmetic-shift SizeOfGroup -2))) (main-loop M N K SizeOfGroup)))) (define (radix-2-pass a) (let ((SizeOfGroup (arithmetic-shift (FLOATvector-length a) -1))) (let loop ((J0 0)) (if (< J0 SizeOfGroup) (let ((J0 J0) (J2 (+ J0 SizeOfGroup))) (let ((J1 (+ J0 1)) (J3 (+ J2 1))) (let ((a_J0 (FLOATvector-ref a J0)) (a_J1 (FLOATvector-ref a J1)) (a_J2 (FLOATvector-ref a J2)) (a_J3 (FLOATvector-ref a J3))) (let ((a_J0 (FLOAT+ a_J0 a_J2)) (a_J1 (FLOAT+ a_J1 a_J3)) (a_J2 (FLOAT- a_J0 a_J2)) (a_J3 (FLOAT- a_J1 a_J3))) (FLOATvector-set! a J0 a_J0) (FLOATvector-set! a J1 a_J1) (FLOATvector-set! a J2 a_J2) (FLOATvector-set! a J3 a_J3) (loop (+ J0 2)))))))))) (let* ((n (FLOATvector-length a)) (log_n (two^p>=m n))) (if (odd? log_n) (recursive-bit 0 n 0 (arithmetic-shift n -2)) (let ((n/2 (arithmetic-shift n -1)) (n/8 (arithmetic-shift n -3))) (recursive-bit 0 n/2 0 n/8) (recursive-bit n/2 n 1 n/8) (radix-2-pass a)))))) (define (two^p>=m m) returns smallest p , assumes fixnum m > = 0 (do ((p 0 (+ p 1)) (two^p 1 (* two^p 2))) ((<= m two^p) p))) Works on 2^n complex doubles . (define two^n+1 (expt 2 (+ n 1))) (define inexact-two^-n (FLOAT/ (exact->inexact (expt 2 n)))) (define data ;; A float vector with data[i]=i (let ((result (FLOATmake-vector two^n+1))) (do ((i 0 (+ i 1))) ((= i two^n+1) result) (FLOATvector-set! result i (exact->inexact i))))) (define (run data) (let ((table (make-w (- n 1)))) (direct-fft-recursive-4 data table) (inverse-fft-recursive-4 data table) (do ((j 0 (+ j 1))) ((= j two^n+1)) (FLOATvector-set! data j (FLOAT* (FLOATvector-ref data j) inexact-two^-n))) (FLOATvector-ref data 3))) (define (main . args) (run-benchmark "fftrad4" fftrad4-iters (lambda (result) (FLOAT<= (FLOATabs (FLOAT- result 3.0)) 1e-4)) (lambda (data) (lambda () (run data))) data)) (main)
null
https://raw.githubusercontent.com/bsaleil/lc/ee7867fd2bdbbe88924300e10b14ea717ee6434b/tools/benchtimes/resultVMIL-lc-gsc-lc/LC5/fftrad4.scm.scm
scheme
------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Gabriel benchmarks C benchmarks Other benchmarks Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The direct transform takes in-order input and produces out-of-order output. The inverse transform takes out-of-order input and produces in-order output. This particular code has guaranteed error bounds, see in particular the commentary at #L6395 number of complexes we copy complex multiples of all entries below start to entries starting at start This is a direcct complex fft, using a decimation-in-time algorithm with inputs in natural order and outputs in bit-reversed order. The table of "twiddle" factors is in bit-reversed order. combined passes in pairs to cut the number of passes through the vector a table depending on whether K is even or not first we do the (overlapping) pairs of apart. of butterflies distance SizeOfGroup we rewrite the multipliers so I don't hurt my head too much when thinking about them. If we're here, the size of our (conceptually complex) if is not a power the passes as radix-4 passes This is an complex fft, using a decimation-in-frequency algorithm with inputs in bit-reversed order and outputs in natural order. The organization of the algorithm has little to do with the the I just reversed the operations of the direct algorithm given The table of "twiddle" factors is in bit-reversed order. A float vector with data[i]=i
Macros (##define-macro (def-macro form . body) `(##define-macro ,form (let () ,@body))) (def-macro (FLOATvector-const . lst) `',(list->vector lst)) (def-macro (FLOATvector? x) `(vector? ,x)) (def-macro (FLOATvector . lst) `(vector ,@lst)) (def-macro (FLOATmake-vector n . init) `(make-vector ,n ,@init)) (def-macro (FLOATvector-ref v i) `(vector-ref ,v ,i)) (def-macro (FLOATvector-set! v i x) `(vector-set! ,v ,i ,x)) (def-macro (FLOATvector-length v) `(vector-length ,v)) (def-macro (nuc-const . lst) `',(list->vector lst)) (def-macro (FLOAT+ . lst) `(+ ,@lst)) (def-macro (FLOAT- . lst) `(- ,@lst)) (def-macro (FLOAT* . lst) `(* ,@lst)) (def-macro (FLOAT/ . lst) `(/ ,@lst)) (def-macro (FLOAT= . lst) `(= ,@lst)) (def-macro (FLOAT< . lst) `(< ,@lst)) (def-macro (FLOAT<= . lst) `(<= ,@lst)) (def-macro (FLOAT> . lst) `(> ,@lst)) (def-macro (FLOAT>= . lst) `(>= ,@lst)) (def-macro (FLOATnegative? . lst) `(negative? ,@lst)) (def-macro (FLOATpositive? . lst) `(positive? ,@lst)) (def-macro (FLOATzero? . lst) `(zero? ,@lst)) (def-macro (FLOATabs . lst) `(abs ,@lst)) (def-macro (FLOATsin . lst) `(sin ,@lst)) (def-macro (FLOATcos . lst) `(cos ,@lst)) (def-macro (FLOATatan . lst) `(atan ,@lst)) (def-macro (FLOATsqrt . lst) `(sqrt ,@lst)) (def-macro (FLOATmin . lst) `(min ,@lst)) (def-macro (FLOATmax . lst) `(max ,@lst)) (def-macro (FLOATround . lst) `(round ,@lst)) (def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst)) (def-macro (GENERIC+ . lst) `(+ ,@lst)) (def-macro (GENERIC- . lst) `(- ,@lst)) (def-macro (GENERIC* . lst) `(* ,@lst)) (def-macro (GENERIC/ . lst) `(/ ,@lst)) (def-macro (GENERICquotient . lst) `(quotient ,@lst)) (def-macro (GENERICremainder . lst) `(remainder ,@lst)) (def-macro (GENERICmodulo . lst) `(modulo ,@lst)) (def-macro (GENERIC= . lst) `(= ,@lst)) (def-macro (GENERIC< . lst) `(< ,@lst)) (def-macro (GENERIC<= . lst) `(<= ,@lst)) (def-macro (GENERIC> . lst) `(> ,@lst)) (def-macro (GENERIC>= . lst) `(>= ,@lst)) (def-macro (GENERICexpt . lst) `(expt ,@lst)) Functions used by LC to get time info (def-macro (##lc-time expr) (let ((sym (gensym))) `(let ((r (##lc-exec-stats (lambda () ,expr)))) (##print-perm-string "CPU time: ") (##print-double (+ (cdr (assoc "User time" (cdr r))) (cdr (assoc "Sys time" (cdr r))))) (##print-perm-string "\n") (##print-perm-string "GC CPU time: ") (##print-double (+ (cdr (assoc "GC user time" (cdr r))) (cdr (assoc "GC sys time" (cdr r))))) (##print-perm-string "\n") (map (lambda (el) (##print-perm-string (car el)) (##print-perm-string ": ") (##print-double (cdr el)) (##print-perm-string "\n")) (cdr r)) r))) (define (##lc-exec-stats thunk) (let* ((at-start (##process-statistics)) (result (thunk)) (at-end (##process-statistics))) (define (get-info msg idx) (cons msg (- (f64vector-ref at-end idx) (f64vector-ref at-start idx)))) (list result (get-info "User time" 0) (get-info "Sys time" 1) (get-info "Real time" 2) (get-info "GC user time" 3) (get-info "GC sys time" 4) (get-info "GC real time" 5) (get-info "Nb gcs" 6)))) (define (run-bench name count ok? run) (let loop ((i count) (result '(undefined))) (if (< 0 i) (loop (- i 1) (run)) result))) (define (run-benchmark name count ok? run-maker . args) (let ((run (apply run-maker args))) (let ((result (car (##lc-time (run-bench name count ok? run))))) (if (not (ok? result)) (begin (display "*** wrong result ***") (newline) (display "*** got: ") (write result) (newline)))))) (define boyer-iters 20) (define browse-iters 600) (define cpstak-iters 1000) (define ctak-iters 100) (define dderiv-iters 2000000) (define deriv-iters 2000000) (define destruc-iters 500) (define diviter-iters 1000000) (define divrec-iters 1000000) (define puzzle-iters 100) (define tak-iters 2000) (define takl-iters 300) (define trav1-iters 100) (define trav2-iters 20) (define triangl-iters 10) and benchmarks (define ack-iters 10) (define array1-iters 1) (define cat-iters 1) (define string-iters 10) (define sum1-iters 10) (define sumloop-iters 10) (define tail-iters 1) (define wc-iters 1) (define fft-iters 2000) (define fib-iters 5) (define fibfp-iters 2) (define mbrot-iters 100) (define nucleic-iters 5) (define pnpoly-iters 100000) (define sum-iters 20000) (define sumfp-iters 20000) (define tfib-iters 20) (define conform-iters 40) (define dynamic-iters 20) (define earley-iters 200) (define fibc-iters 500) (define graphs-iters 300) (define lattice-iters 1) (define matrix-iters 400) (define maze-iters 4000) (define mazefun-iters 1000) (define nqueens-iters 2000) (define paraffins-iters 1000) (define peval-iters 200) (define pi-iters 2) (define primes-iters 100000) (define ray-iters 5) (define scheme-iters 20000) (define simplex-iters 100000) (define slatex-iters 20) (define perm9-iters 10) (define nboyer-iters 100) (define sboyer-iters 100) (define gcbench-iters 1) (define compiler-iters 300) (define nbody-iters 1) (define fftrad4-iters 4) Copyright 2018 , to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , This software calculates radix 4 direct and inverse Fast Fourier Transforms . (define lut-table-size 512) (define lut-table-size^2 262144) (define lut-table-size^3 134217728) (define log-lut-table-size 9) (define low-lut (FLOATvector-const 1. 0. .7071067811865476 .7071067811865476 .9238795325112867 .3826834323650898 .3826834323650898 .9238795325112867 .9807852804032304 .19509032201612828 .5555702330196022 .8314696123025452 .8314696123025452 .5555702330196022 .19509032201612828 .9807852804032304 .9951847266721969 .0980171403295606 .6343932841636455 .773010453362737 .881921264348355 .47139673682599764 .2902846772544624 .9569403357322088 .9569403357322088 .2902846772544624 .47139673682599764 .881921264348355 .773010453362737 .6343932841636455 .0980171403295606 .9951847266721969 .9987954562051724 .049067674327418015 .6715589548470184 .7409511253549591 .9039892931234433 .4275550934302821 .33688985339222005 .9415440651830208 .970031253194544 .2429801799032639 .5141027441932218 .8577286100002721 .8032075314806449 .5956993044924334 .14673047445536175 .989176509964781 .989176509964781 .14673047445536175 .5956993044924334 .8032075314806449 .8577286100002721 .5141027441932218 .2429801799032639 .970031253194544 .9415440651830208 .33688985339222005 .4275550934302821 .9039892931234433 .7409511253549591 .6715589548470184 .049067674327418015 .9987954562051724 .9996988186962042 .024541228522912288 .6895405447370669 .7242470829514669 .9142097557035307 .40524131400498986 .35989503653498817 .9329927988347388 .9757021300385286 .2191012401568698 .5349976198870973 .8448535652497071 .8175848131515837 .5758081914178453 .17096188876030122 .9852776423889412 .99247953459871 .1224106751992162 .6152315905806268 .7883464276266062 .8700869911087115 .49289819222978404 .26671275747489837 .9637760657954398 .9495281805930367 .31368174039889146 .4496113296546066 .8932243011955153 .7572088465064846 .6531728429537768 .07356456359966743 .9972904566786902 .9972904566786902 .07356456359966743 .6531728429537768 .7572088465064846 .8932243011955153 .4496113296546066 .31368174039889146 .9495281805930367 .9637760657954398 .26671275747489837 .49289819222978404 .8700869911087115 .7883464276266062 .6152315905806268 .1224106751992162 .99247953459871 .9852776423889412 .17096188876030122 .5758081914178453 .8175848131515837 .8448535652497071 .5349976198870973 .2191012401568698 .9757021300385286 .9329927988347388 .35989503653498817 .40524131400498986 .9142097557035307 .7242470829514669 .6895405447370669 .024541228522912288 .9996988186962042 .9999247018391445 .012271538285719925 .6983762494089728 .7157308252838187 .9191138516900578 .3939920400610481 .37131719395183754 .9285060804732156 .9783173707196277 .20711137619221856 .5453249884220465 .8382247055548381 .8245893027850253 .5657318107836132 .18303988795514095 .9831054874312163 .9939069700023561 .11022220729388306 .6248594881423863 .7807372285720945 .8760700941954066 .4821837720791228 .2785196893850531 .9604305194155658 .9533060403541939 .3020059493192281 .46053871095824 .8876396204028539 .765167265622459 .6438315428897915 .0857973123444399 .996312612182778 .9981181129001492 .06132073630220858 .6624157775901718 .7491363945234594 .8986744656939538 .43861623853852766 .3253102921622629 .9456073253805213 .9669764710448521 .25486565960451457 .5035383837257176 .8639728561215867 .7958369046088836 .6055110414043255 .1345807085071262 .99090263542778 .9873014181578584 .15885814333386145 .5857978574564389 .8104571982525948 .8513551931052652 .524589682678469 .2310581082806711 .9729399522055602 .937339011912575 .34841868024943456 .4164295600976372 .9091679830905224 .7326542716724128 .680600997795453 .03680722294135883 .9993223845883495 .9993223845883495 .03680722294135883 .680600997795453 .7326542716724128 .9091679830905224 .4164295600976372 .34841868024943456 .937339011912575 .9729399522055602 .2310581082806711 .524589682678469 .8513551931052652 .8104571982525948 .5857978574564389 .15885814333386145 .9873014181578584 .99090263542778 .1345807085071262 .6055110414043255 .7958369046088836 .8639728561215867 .5035383837257176 .25486565960451457 .9669764710448521 .9456073253805213 .3253102921622629 .43861623853852766 .8986744656939538 .7491363945234594 .6624157775901718 .06132073630220858 .9981181129001492 .996312612182778 .0857973123444399 .6438315428897915 .765167265622459 .8876396204028539 .46053871095824 .3020059493192281 .9533060403541939 .9604305194155658 .2785196893850531 .4821837720791228 .8760700941954066 .7807372285720945 .6248594881423863 .11022220729388306 .9939069700023561 .9831054874312163 .18303988795514095 .5657318107836132 .8245893027850253 .8382247055548381 .5453249884220465 .20711137619221856 .9783173707196277 .9285060804732156 .37131719395183754 .3939920400610481 .9191138516900578 .7157308252838187 .6983762494089728 .012271538285719925 .9999247018391445 .9999811752826011 .006135884649154475 .7027547444572253 .7114321957452164 .9215140393420419 .3883450466988263 .37700741021641826 .9262102421383114 .9795697656854405 .2011046348420919 .5504579729366048 .83486287498638 .8280450452577558 .560661576197336 .18906866414980622 .9819638691095552 .9945645707342554 .10412163387205457 .629638238914927 .7768884656732324 .8790122264286335 .47679923006332214 .2844075372112718 .9587034748958716 .9551411683057707 .29615088824362384 .4659764957679662 .8847970984309378 .7691033376455796 .6391244448637757 .09190895649713272 .9957674144676598 .9984755805732948 .05519524434968994 .6669999223036375 .745057785441466 .901348847046022 .43309381885315196 .33110630575987643 .9435934581619604 .9685220942744173 .24892760574572018 .508830142543107 .8608669386377673 .799537269107905 .600616479383869 .14065823933284924 .9900582102622971 .9882575677307495 .15279718525844344 .5907597018588743 .8068475535437992 .8545579883654005 .5193559901655896 .2370236059943672 .9715038909862518 .9394592236021899 .3426607173119944 .4220002707997997 .9065957045149153 .7368165688773699 .6760927035753159 .04293825693494082 .9990777277526454 .9995294175010931 .030674803176636626 .6850836677727004 .7284643904482252 .9117060320054299 .41084317105790397 .3541635254204904 .9351835099389476 .9743393827855759 .22508391135979283 .5298036246862947 .8481203448032972 .8140363297059484 .5808139580957645 .16491312048996992 .9863080972445987 .9917097536690995 .12849811079379317 .6103828062763095 .7921065773002124 .8670462455156926 .49822766697278187 .2607941179152755 .9653944416976894 .9475855910177411 .3195020308160157 .44412214457042926 .8959662497561851 .7531867990436125 .6578066932970786 .06744391956366406 .9977230666441916 .9968202992911657 .07968243797143013 .6485144010221124 .7612023854842618 .8904487232447579 .45508358712634384 .30784964004153487 .9514350209690083 .9621214042690416 .272621355449949 .48755016014843594 .8730949784182901 .7845565971555752 .6200572117632892 .11631863091190477 .9932119492347945 .984210092386929 .17700422041214875 .5707807458869673 .8211025149911046 .8415549774368984 .5401714727298929 .21311031991609136 .9770281426577544 .9307669610789837 .36561299780477385 .39962419984564684 .9166790599210427 .7200025079613817 .693971460889654 .01840672990580482 .9998305817958234 .9998305817958234 .01840672990580482 .693971460889654 .7200025079613817 .9166790599210427 .39962419984564684 .36561299780477385 .9307669610789837 .9770281426577544 .21311031991609136 .5401714727298929 .8415549774368984 .8211025149911046 .5707807458869673 .17700422041214875 .984210092386929 .9932119492347945 .11631863091190477 .6200572117632892 .7845565971555752 .8730949784182901 .48755016014843594 .272621355449949 .9621214042690416 .9514350209690083 .30784964004153487 .45508358712634384 .8904487232447579 .7612023854842618 .6485144010221124 .07968243797143013 .9968202992911657 .9977230666441916 .06744391956366406 .6578066932970786 .7531867990436125 .8959662497561851 .44412214457042926 .3195020308160157 .9475855910177411 .9653944416976894 .2607941179152755 .49822766697278187 .8670462455156926 .7921065773002124 .6103828062763095 .12849811079379317 .9917097536690995 .9863080972445987 .16491312048996992 .5808139580957645 .8140363297059484 .8481203448032972 .5298036246862947 .22508391135979283 .9743393827855759 .9351835099389476 .3541635254204904 .41084317105790397 .9117060320054299 .7284643904482252 .6850836677727004 .030674803176636626 .9995294175010931 .9990777277526454 .04293825693494082 .6760927035753159 .7368165688773699 .9065957045149153 .4220002707997997 .3426607173119944 .9394592236021899 .9715038909862518 .2370236059943672 .5193559901655896 .8545579883654005 .8068475535437992 .5907597018588743 .15279718525844344 .9882575677307495 .9900582102622971 .14065823933284924 .600616479383869 .799537269107905 .8608669386377673 .508830142543107 .24892760574572018 .9685220942744173 .9435934581619604 .33110630575987643 .43309381885315196 .901348847046022 .745057785441466 .6669999223036375 .05519524434968994 .9984755805732948 .9957674144676598 .09190895649713272 .6391244448637757 .7691033376455796 .8847970984309378 .4659764957679662 .29615088824362384 .9551411683057707 .9587034748958716 .2844075372112718 .47679923006332214 .8790122264286335 .7768884656732324 .629638238914927 .10412163387205457 .9945645707342554 .9819638691095552 .18906866414980622 .560661576197336 .8280450452577558 .83486287498638 .5504579729366048 .2011046348420919 .9795697656854405 .9262102421383114 .37700741021641826 .3883450466988263 .9215140393420419 .7114321957452164 .7027547444572253 .006135884649154475 .9999811752826011 .9999952938095762 .003067956762965976 .7049340803759049 .7092728264388657 .9227011283338785 .38551605384391885 .37984720892405116 .9250492407826776 .9801821359681174 .1980984107179536 .5530167055800276 .8331701647019132 .829761233794523 .5581185312205561 .19208039704989244 .9813791933137546 .9948793307948056 .10106986275482782 .6320187359398091 .7749531065948739 .8804708890521608 .47410021465055 .2873474595447295 .9578264130275329 .9560452513499964 .29321916269425863 .46868882203582796 .8833633386657316 .7710605242618138 .6367618612362842 .094963495329639 .9954807554919269 .9986402181802653 .052131704680283324 .6692825883466361 .7430079521351217 .9026733182372588 .4303264813400826 .3339996514420094 .9425731976014469 .9692812353565485 .24595505033579462 .5114688504379704 .8593018183570084 .8013761717231402 .5981607069963423 .14369503315029444 .9896220174632009 .9887216919603238 .1497645346773215 .5932322950397998 .8050313311429635 .8561473283751945 .5167317990176499 .2400030224487415 .9707721407289504 .9405060705932683 .33977688440682685 .4247796812091088 .9052967593181188 .7388873244606151 .673829000378756 .04600318213091463 .9989412931868569 .9996188224951786 .027608145778965743 .6873153408917592 .726359155084346 .9129621904283982 .4080441628649787 .35703096123343003 .9340925504042589 .9750253450669941 .22209362097320354 .532403127877198 .8464909387740521 .8158144108067338 .5783137964116556 .16793829497473117 .9857975091675675 .9920993131421918 .12545498341154623 .6128100824294097 .79023022143731 .8685707059713409 .49556526182577254 .2637546789748314 .9645897932898128 .9485613499157303 .31659337555616585 .4468688401623742 .8945994856313827 .7552013768965365 .6554928529996153 .07050457338961387 .9975114561403035 .997060070339483 .07662386139203149 .6508466849963809 .7592091889783881 .8918407093923427 .4523495872337709 .3107671527496115 .9504860739494817 .9629532668736839 .2696683255729151 .49022648328829116 .8715950866559511 .7864552135990858 .617647307937804 .11936521481099137 .9928504144598651 .9847485018019042 .17398387338746382 .5732971666980422 .819347520076797 .8432082396418454 .5375870762956455 .21610679707621952 .9763697313300211 .9318842655816681 .3627557243673972 .40243465085941843 .9154487160882678 .7221281939292153 .6917592583641577 .021474080275469508 .9997694053512153 .9998823474542126 .015339206284988102 .696177131491463 .7178700450557317 .9179007756213905 .3968099874167103 .3684668299533723 .9296408958431812 .9776773578245099 .2101118368804696 .5427507848645159 .8398937941959995 .8228497813758263 .5682589526701316 .18002290140569951 .9836624192117303 .9935641355205953 .11327095217756435 .62246127937415 .7826505961665757 .8745866522781761 .4848692480007911 .27557181931095814 .9612804858113206 .9523750127197659 .30492922973540243 .45781330359887723 .8890483558546646 .7631884172633813 .6461760129833164 .08274026454937569 .9965711457905548 .997925286198596 .06438263092985747 .6601143420674205 .7511651319096864 .8973245807054183 .44137126873171667 .32240767880106985 .9466009130832835 .9661900034454125 .257831102162159 .5008853826112408 .8655136240905691 .7939754775543372 .6079497849677736 .13154002870288312 .9913108598461154 .9868094018141855 .16188639378011183 .5833086529376983 .8122505865852039 .8497417680008524 .5271991347819014 .22807208317088573 .973644249650812 .9362656671702783 .35129275608556715 .41363831223843456 .9104412922580672 .7305627692278276 .6828455463852481 .03374117185137759 .9994306045554617 .9992047586183639 .03987292758773981 .6783500431298615 .7347388780959635 .9078861164876663 .41921688836322396 .34554132496398904 .9384035340631081 .9722264970789363 .23404195858354343 .5219752929371544 .8529606049303636 .808656181588175 .5882815482226453 .15582839765426523 .9877841416445722 .9904850842564571 .13762012158648604 .6030665985403482 .7976908409433912 .8624239561110405 .5061866453451553 .25189781815421697 .9677538370934755 .9446048372614803 .32820984357909255 .4358570799222555 .9000158920161603 .7471006059801801 .6647109782033449 .05825826450043576 .9983015449338929 .996044700901252 .0888535525825246 .6414810128085832 .7671389119358204 .8862225301488806 .4632597835518602 .2990798263080405 .9542280951091057 .9595715130819845 .281464937925758 .479493757660153 .8775452902072612 .778816512381476 .6272518154951441 .10717242495680884 .9942404494531879 .9825393022874412 .18605515166344666 .5631993440138341 .8263210628456635 .836547727223512 .5478940591731002 .20410896609281687 .9789481753190622 .9273625256504011 .374164062971458 .39117038430225387 .9203182767091106 .7135848687807936 .7005687939432483 .00920375478205982 .9999576445519639 .9999576445519639 .00920375478205982 .7005687939432483 .7135848687807936 .9203182767091106 .39117038430225387 .374164062971458 .9273625256504011 .9789481753190622 .20410896609281687 .5478940591731002 .836547727223512 .8263210628456635 .5631993440138341 .18605515166344666 .9825393022874412 .9942404494531879 .10717242495680884 .6272518154951441 .778816512381476 .8775452902072612 .479493757660153 .281464937925758 .9595715130819845 .9542280951091057 .2990798263080405 .4632597835518602 .8862225301488806 .7671389119358204 .6414810128085832 .0888535525825246 .996044700901252 .9983015449338929 .05825826450043576 .6647109782033449 .7471006059801801 .9000158920161603 .4358570799222555 .32820984357909255 .9446048372614803 .9677538370934755 .25189781815421697 .5061866453451553 .8624239561110405 .7976908409433912 .6030665985403482 .13762012158648604 .9904850842564571 .9877841416445722 .15582839765426523 .5882815482226453 .808656181588175 .8529606049303636 .5219752929371544 .23404195858354343 .9722264970789363 .9384035340631081 .34554132496398904 .41921688836322396 .9078861164876663 .7347388780959635 .6783500431298615 .03987292758773981 .9992047586183639 .9994306045554617 .03374117185137759 .6828455463852481 .7305627692278276 .9104412922580672 .41363831223843456 .35129275608556715 .9362656671702783 .973644249650812 .22807208317088573 .5271991347819014 .8497417680008524 .8122505865852039 .5833086529376983 .16188639378011183 .9868094018141855 .9913108598461154 .13154002870288312 .6079497849677736 .7939754775543372 .8655136240905691 .5008853826112408 .257831102162159 .9661900034454125 .9466009130832835 .32240767880106985 .44137126873171667 .8973245807054183 .7511651319096864 .6601143420674205 .06438263092985747 .997925286198596 .9965711457905548 .08274026454937569 .6461760129833164 .7631884172633813 .8890483558546646 .45781330359887723 .30492922973540243 .9523750127197659 .9612804858113206 .27557181931095814 .4848692480007911 .8745866522781761 .7826505961665757 .62246127937415 .11327095217756435 .9935641355205953 .9836624192117303 .18002290140569951 .5682589526701316 .8228497813758263 .8398937941959995 .5427507848645159 .2101118368804696 .9776773578245099 .9296408958431812 .3684668299533723 .3968099874167103 .9179007756213905 .7178700450557317 .696177131491463 .015339206284988102 .9998823474542126 .9997694053512153 .021474080275469508 .6917592583641577 .7221281939292153 .9154487160882678 .40243465085941843 .3627557243673972 .9318842655816681 .9763697313300211 .21610679707621952 .5375870762956455 .8432082396418454 .819347520076797 .5732971666980422 .17398387338746382 .9847485018019042 .9928504144598651 .11936521481099137 .617647307937804 .7864552135990858 .8715950866559511 .49022648328829116 .2696683255729151 .9629532668736839 .9504860739494817 .3107671527496115 .4523495872337709 .8918407093923427 .7592091889783881 .6508466849963809 .07662386139203149 .997060070339483 .9975114561403035 .07050457338961387 .6554928529996153 .7552013768965365 .8945994856313827 .4468688401623742 .31659337555616585 .9485613499157303 .9645897932898128 .2637546789748314 .49556526182577254 .8685707059713409 .79023022143731 .6128100824294097 .12545498341154623 .9920993131421918 .9857975091675675 .16793829497473117 .5783137964116556 .8158144108067338 .8464909387740521 .532403127877198 .22209362097320354 .9750253450669941 .9340925504042589 .35703096123343003 .4080441628649787 .9129621904283982 .726359155084346 .6873153408917592 .027608145778965743 .9996188224951786 .9989412931868569 .04600318213091463 .673829000378756 .7388873244606151 .9052967593181188 .4247796812091088 .33977688440682685 .9405060705932683 .9707721407289504 .2400030224487415 .5167317990176499 .8561473283751945 .8050313311429635 .5932322950397998 .1497645346773215 .9887216919603238 .9896220174632009 .14369503315029444 .5981607069963423 .8013761717231402 .8593018183570084 .5114688504379704 .24595505033579462 .9692812353565485 .9425731976014469 .3339996514420094 .4303264813400826 .9026733182372588 .7430079521351217 .6692825883466361 .052131704680283324 .9986402181802653 .9954807554919269 .094963495329639 .6367618612362842 .7710605242618138 .8833633386657316 .46868882203582796 .29321916269425863 .9560452513499964 .9578264130275329 .2873474595447295 .47410021465055 .8804708890521608 .7749531065948739 .6320187359398091 .10106986275482782 .9948793307948056 .9813791933137546 .19208039704989244 .5581185312205561 .829761233794523 .8331701647019132 .5530167055800276 .1980984107179536 .9801821359681174 .9250492407826776 .37984720892405116 .38551605384391885 .9227011283338785 .7092728264388657 .7049340803759049 .003067956762965976 .9999952938095762 )) (define med-lut (FLOATvector-const 1. 0. .9999999999820472 5.9921124526424275e-6 .9999999999281892 1.1984224905069707e-5 .9999999998384257 1.7976337357066685e-5 .9999999997127567 2.396844980841822e-5 .9999999995511824 2.9960562258909154e-5 .9999999993537025 3.5952674708324344e-5 .9999999991203175 4.1944787156448635e-5 .9999999988510269 4.793689960306688e-5 .9999999985458309 5.3929012047963936e-5 .9999999982047294 5.992112449092465e-5 .9999999978277226 6.591323693173387e-5 .9999999974148104 7.190534937017645e-5 .9999999969659927 7.789746180603723e-5 .9999999964812697 8.388957423910108e-5 .9999999959606412 8.988168666915283e-5 .9999999954041073 9.587379909597734e-5 .999999994811668 1.0186591151935948e-4 .9999999941833233 1.0785802393908407e-4 .9999999935190732 1.1385013635493597e-4 .9999999928189177 1.1984224876670004e-4 .9999999920828567 1.2583436117416112e-4 .9999999913108903 1.3182647357710405e-4 .9999999905030187 1.3781858597531374e-4 .9999999896592414 1.4381069836857496e-4 .9999999887795589 1.498028107566726e-4 .9999999878639709 1.5579492313939151e-4 .9999999869124775 1.6178703551651655e-4 .9999999859250787 1.6777914788783258e-4 .9999999849017744 1.737712602531244e-4 .9999999838425648 1.797633726121769e-4 .9999999827474497 1.8575548496477492e-4 .9999999816164293 1.9174759731070332e-4 .9999999804495034 1.9773970964974692e-4 .9999999792466722 2.037318219816906e-4 .9999999780079355 2.0972393430631923e-4 .9999999767332933 2.1571604662341763e-4 .9999999754227459 2.2170815893277063e-4 .9999999740762929 2.2770027123416315e-4 .9999999726939346 2.3369238352737996e-4 .9999999712756709 2.3968449581220595e-4 .9999999698215016 2.45676608088426e-4 .9999999683314271 2.5166872035582493e-4 .9999999668054471 2.5766083261418755e-4 .9999999652435617 2.636529448632988e-4 .9999999636457709 2.696450571029434e-4 .9999999620120748 2.756371693329064e-4 .9999999603424731 2.8162928155297243e-4 .9999999586369661 2.876213937629265e-4 .9999999568955537 2.936135059625534e-4 .9999999551182358 2.99605618151638e-4 .9999999533050126 3.055977303299651e-4 .9999999514558838 3.115898424973196e-4 .9999999495708498 3.1758195465348636e-4 .9999999476499103 3.235740667982502e-4 .9999999456930654 3.2956617893139595e-4 .9999999437003151 3.3555829105270853e-4 .9999999416716594 3.4155040316197275e-4 .9999999396070982 3.475425152589734e-4 .9999999375066316 3.535346273434955e-4 .9999999353702598 3.595267394153237e-4 .9999999331979824 3.6551885147424295e-4 .9999999309897996 3.7151096352003814e-4 .9999999287457114 3.7750307555249406e-4 .9999999264657179 3.8349518757139556e-4 .9999999241498189 3.8948729957652753e-4 .9999999217980144 3.954794115676748e-4 .9999999194103046 4.0147152354462224e-4 .9999999169866894 4.0746363550715466e-4 .9999999145271687 4.134557474550569e-4 .9999999120317428 4.194478593881139e-4 .9999999095004113 4.2543997130611036e-4 .9999999069331744 4.314320832088313e-4 .9999999043300322 4.3742419509606144e-4 .9999999016909845 4.4341630696758576e-4 .9999998990160315 4.4940841882318896e-4 .9999998963051729 4.55400530662656e-4 .999999893558409 4.613926424857717e-4 .9999998907757398 4.673847542923209e-4 .9999998879571651 4.7337686608208844e-4 .9999998851026849 4.793689778548592e-4 .9999998822122994 4.8536108961041806e-4 .9999998792860085 4.913532013485497e-4 .9999998763238122 4.973453130690393e-4 .9999998733257104 5.033374247716714e-4 .9999998702917032 5.09329536456231e-4 .9999998672217907 5.153216481225028e-4 .9999998641159727 5.213137597702719e-4 .9999998609742493 5.27305871399323e-4 .9999998577966206 5.332979830094408e-4 .9999998545830864 5.392900946004105e-4 .9999998513336468 5.452822061720168e-4 .9999998480483018 5.512743177240444e-4 .9999998447270514 5.572664292562783e-4 .9999998413698955 5.632585407685033e-4 .9999998379768343 5.692506522605043e-4 .9999998345478677 5.752427637320661e-4 .9999998310829956 5.812348751829735e-4 .9999998275822183 5.872269866130116e-4 .9999998240455354 5.93219098021965e-4 .9999998204729471 5.992112094096185e-4 .9999998168644535 6.052033207757572e-4 .9999998132200545 6.111954321201659e-4 .99999980953975 6.171875434426292e-4 .9999998058235401 6.231796547429323e-4 .9999998020714248 6.291717660208597e-4 .9999997982834041 6.351638772761965e-4 .9999997944594781 6.411559885087275e-4 .9999997905996466 6.471480997182375e-4 .9999997867039097 6.531402109045114e-4 .9999997827722674 6.591323220673341e-4 .9999997788047197 6.651244332064902e-4 .9999997748012666 6.711165443217649e-4 .9999997707619082 6.771086554129428e-4 .9999997666866443 6.83100766479809e-4 .9999997625754748 6.89092877522148e-4 .9999997584284002 6.950849885397449e-4 .9999997542454201 7.010770995323844e-4 .9999997500265345 7.070692104998515e-4 .9999997457717437 7.130613214419311e-4 .9999997414810473 7.190534323584079e-4 .9999997371544456 7.250455432490666e-4 .9999997327919384 7.310376541136925e-4 .9999997283935259 7.3702976495207e-4 .999999723959208 7.430218757639842e-4 .9999997194889846 7.490139865492199e-4 .9999997149828559 7.55006097307562e-4 .9999997104408218 7.609982080387952e-4 .9999997058628822 7.669903187427045e-4 .9999997012490373 7.729824294190747e-4 .9999996965992869 7.789745400676906e-4 .9999996919136313 7.849666506883372e-4 .99999968719207 7.909587612807992e-4 .9999996824346035 7.969508718448614e-4 .9999996776412315 8.029429823803089e-4 .9999996728119542 8.089350928869263e-4 .9999996679467715 8.149272033644986e-4 .9999996630456833 8.209193138128106e-4 .9999996581086897 8.269114242316472e-4 .9999996531357909 8.329035346207931e-4 .9999996481269865 8.388956449800333e-4 .9999996430822767 8.448877553091527e-4 .9999996380016616 8.508798656079359e-4 .999999632885141 8.56871975876168e-4 .9999996277327151 8.628640861136338e-4 .9999996225443838 8.68856196320118e-4 .9999996173201471 8.748483064954056e-4 .999999612060005 8.808404166392814e-4 .9999996067639574 8.868325267515304e-4 .9999996014320045 8.928246368319371e-4 .9999995960641462 8.988167468802867e-4 .9999995906603825 9.048088568963639e-4 .9999995852207133 9.108009668799535e-4 .9999995797451389 9.167930768308405e-4 .9999995742336589 9.227851867488095e-4 .9999995686862736 9.287772966336457e-4 .9999995631029829 9.347694064851338e-4 .9999995574837868 9.407615163030585e-4 .9999995518286853 9.467536260872047e-4 .9999995461376784 9.527457358373575e-4 .9999995404107661 9.587378455533015e-4 .9999995346479484 9.647299552348216e-4 .9999995288492254 9.707220648817027e-4 .9999995230145969 9.767141744937296e-4 .9999995171440631 9.827062840706872e-4 .9999995112376238 9.886983936123602e-4 .9999995052952791 9.946905031185337e-4 .9999994993170291 .0010006826125889925 .9999994933028736 .0010066747220235214 .9999994872528128 .001012666831421905 .9999994811668466 .0010186589407839286 .999999475044975 .0010246510501093766 .9999994688871979 .0010306431593980344 .9999994626935156 .0010366352686496862 .9999994564639277 .0010426273778641173 .9999994501984345 .0010486194870411127 .999999443897036 .0010546115961804568 .999999437559732 .0010606037052819344 .9999994311865227 .0010665958143453308 .9999994247774079 .0010725879233704307 .9999994183323877 .0010785800323570187 .9999994118514622 .0010845721413048801 .9999994053346313 .0010905642502137994 .9999993987818949 .0010965563590835613 .9999993921932533 .0011025484679139511 .9999993855687062 .0011085405767047535 .9999993789082536 .0011145326854557532 .9999993722118957 .001120524794166735 .9999993654796325 .0011265169028374842 .9999993587114638 .0011325090114677853 .9999993519073898 .001138501120057423 .9999993450674104 .0011444932286061825 .9999993381915255 .0011504853371138485 .9999993312797354 .0011564774455802057 .9999993243320398 .0011624695540050393 .9999993173484387 .001168461662388134 .9999993103289324 .0011744537707292742 .9999993032735206 .0011804458790282454 .9999992961822035 .0011864379872848323 .9999992890549809 .0011924300954988195 .999999281891853 .001198422203669992 .9999992746928197 .0012044143117981348 .999999267457881 .0012104064198830327 .999999260187037 .0012163985279244702 .9999992528802875 .0012223906359222325 .9999992455376326 .0012283827438761045 .9999992381590724 .0012343748517858707 .9999992307446068 .0012403669596513162 .9999992232942359 .001246359067472226 .9999992158079595 .0012523511752483847 .9999992082857777 .001258343282979577 .9999992007276906 .001264335390665588 .999999193133698 .0012703274983062026 .9999991855038001 .0012763196059012057 .9999991778379967 .001282311713450382 .9999991701362881 .0012883038209535163 .999999162398674 .0012942959284103935 .9999991546251547 .0013002880358207985 .9999991468157298 .001306280143184516 .9999991389703996 .001312272250501331 .999999131089164 .0013182643577710285 .999999123172023 .0013242564649933932 .9999991152189767 .0013302485721682098 .9999991072300249 .001336240679295263 .9999990992051678 .0013422327863743383 .9999990911444054 .0013482248934052201 .9999990830477375 .0013542170003876934 .9999990749151643 .001360209107321543 .9999990667466857 .0013662012142065536 .9999990585423016 .0013721933210425101 .9999990503020123 .0013781854278291975 .9999990420258176 .0013841775345664006 .9999990337137175 .0013901696412539043 .999999025365712 .0013961617478914935 .999999016981801 .0014021538544789526 .9999990085619848 .001408145961016067 .9999990001062631 .0014141380675026214 .9999989916146361 .0014201301739384005 .9999989830871038 .0014261222803231893 .9999989745236659 .0014321143866567725 .9999989659243228 .001438106492938935 .9999989572890743 .0014440985991694619 .9999989486179204 .0014500907053481378 .9999989399108612 .0014560828114747475 .9999989311678965 .0014620749175490758 .9999989223890265 .001468067023570908 .9999989135742512 .0014740591295400284 .9999989047235704 .0014800512354562223 .9999988958369843 .0014860433413192743 .9999988869144928 .0014920354471289693 .9999988779560959 .0014980275528850922 .9999988689617937 .0015040196585874275 .9999988599315861 .0015100117642357607 .999998850865473 .0015160038698298762 .9999988417634548 .001521995975369559 .999998832625531 .0015279880808545937 .9999988234517019 .0015339801862847657 .9999988142419675 .0015399722916598592 .9999988049963277 .0015459643969796596 .9999987957147825 .0015519565022439512 .9999987863973319 .0015579486074525195 .9999987770439759 .001563940712605149 .9999987676547146 .0015699328177016243 .999998758229548 .0015759249227417307 .9999987487684759 .0015819170277252528 .9999987392714985 .0015879091326519755 .9999987297386157 .0015939012375216837 .9999987201698276 .0015998933423341623 .9999987105651341 .001605885447089196 .9999987009245352 .0016118775517865696 .999998691248031 .0016178696564260683 .9999986815356214 .0016238617610074765 .9999986717873064 .0016298538655305794 .9999986620030861 .0016358459699951618 .9999986521829605 .0016418380744010084 .9999986423269294 .0016478301787479041 .999998632434993 .0016538222830356339 .9999986225071512 .0016598143872639823 .999998612543404 .0016658064914327345 .9999986025437515 .0016717985955416754 .9999985925081937 .0016777906995905894 .9999985824367305 .0016837828035792617 .9999985723293618 .0016897749075074774 .999998562186088 .0016957670113750207 .9999985520069086 .0017017591151816769 .9999985417918239 .0017077512189272307 .999998531540834 .001713743322611467 .9999985212539385 .0017197354262341706 .9999985109311378 .0017257275297951264 .9999985005724317 .0017317196332941192 .9999984901778203 .0017377117367309341 .9999984797473034 .0017437038401053556 .9999984692808812 .0017496959434171687 .9999984587785538 .0017556880466661582 .9999984482403208 .001761680149852109 .9999984376661826 .0017676722529748061 .999998427056139 .0017736643560340342 .99999841641019 .001779656459029578 .9999984057283358 .0017856485619612225 .9999983950105761 .0017916406648287528 .999998384256911 .0017976327676319532 .9999983734673407 .001803624870370609 .9999983626418649 .0018096169730445048 .9999983517804839 .0018156090756534257 .9999983408831975 .0018216011781971562 .9999983299500057 .0018275932806754815 .9999983189809085 .0018335853830881864 .999998307975906 .0018395774854350557 .9999982969349982 .001845569587715874 .9999982858581851 .0018515616899304264 .9999982747454665 .001857553792078498 .9999982635968426 .001863545894159873 .9999982524123134 .0018695379961743367 .9999982411918789 .001875530098121674 .9999982299355389 .0018815222000016696 .9999982186432936 .0018875143018141083 .999998207315143 .0018935064035587748 .999998195951087 .0018994985052354545 .9999981845511257 .0019054906068439318 .9999981731152591 .0019114827083839918 .999998161643487 .001917474809855419 .9999981501358096 .0019234669112579987 .999998138592227 .0019294590125915154 .9999981270127389 .0019354511138557542 .9999981153973455 .0019414432150504997 .9999981037460468 .0019474353161755369 .9999980920588427 .001953427417230651 .9999980803357332 .001959419518215626 .9999980685767185 .0019654116191302473 .9999980567817984 .0019714037199743 .9999980449509729 .0019773958207475683 .9999980330842422 .0019833879214498375 .999998021181606 .001989380022080892 .9999980092430646 .0019953721226405176 .9999979972686177 .002001364223128498 .9999979852582656 .002007356323544619 .9999979732120081 .002013348423888665 .9999979611298453 .002019340524160421 .9999979490117771 .0020253326243596715 .9999979368578036 .0020313247244862017 .9999979246679247 .002037316824539796 .9999979124421405 .00204330892452024 .999997900180451 .002049301024427318 .9999978878828562 .0020552931242608153 .9999978755493559 .002061285224020516 .9999978631799504 .0020672773237062057 .9999978507746395 .002073269423317669 .9999978383334234 .0020792615228546903 .9999978258563018 .002085253622317055 .999997813343275 .0020912457217045484 .9999978007943428 .002097237821016954 .9999977882095052 .0021032299202540577 .9999977755887623 .0021092220194156444 .9999977629321142 .0021152141185014984 .9999977502395607 .0021212062175114043 .9999977375111019 .002127198316445148 .9999977247467376 .0021331904153025134 .9999977119464681 .002139182514083286 .9999976991102932 .0021451746127872503 .9999976862382131 .002151166711414191 .9999976733302276 .0021571588099638934 .9999976603863368 .0021631509084361423 .9999976474065406 .002169143006830722 .9999976343908391 .002175135105147418 .9999976213392323 .0021811272033860148 .9999976082517201 .002187119301546297 .9999975951283027 .00219311139962805 .9999975819689799 .0021991034976310588 .9999975687737518 .0022050955955551076 .9999975555426184 .0022110876933999816 .9999975422755796 .0022170797911654654 .9999975289726355 .002223071888851344 .9999975156337861 .0022290639864574026 .9999975022590314 .0022350560839834253 .9999974888483714 .002241048181429198 .999997475401806 .0022470402787945045 .9999974619193353 .00225303237607913 .9999974484009593 .0022590244732828596 .9999974348466779 .0022650165704054784 .9999974212564913 .0022710086674467703 .9999974076303992 .002277000764406521 .9999973939684019 .002282992861284515 .9999973802704993 .0022889849580805368 .9999973665366915 .0022949770547943723 .9999973527669782 .0023009691514258054 .9999973389613596 .002306961247974621 .9999973251198357 .0023129533444406045 .9999973112424065 .0023189454408235406 .999997297329072 .0023249375371232135 .9999972833798322 .002330929633339409 .999997269394687 .0023369217294719113 .9999972553736366 .0023429138255205055 .9999972413166809 .0023489059214849765 .9999972272238198 .002354898017365109 .9999972130950534 .0023608901131606883 .9999971989303816 .0023668822088714985 .9999971847298047 .0023728743044973246 .9999971704933224 .0023788664000379523 .9999971562209347 .0023848584954931653 .9999971419126418 .0023908505908627493 .9999971275684435 .0023968426861464883 .99999711318834 .002402834781344168 .9999970987723311 .0024088268764555732 .9999970843204169 .002414818971480488 .9999970698325974 .002420811066418698 .9999970553088726 .0024268031612699878 .9999970407492426 .002432795256034142 .9999970261537071 .002438787350710946 .9999970115222664 .002444779445300184 .9999969968549204 .0024507715398016418 .9999969821516691 .002456763634215103 .9999969674125124 .002462755728540353 .9999969526374506 .0024687478227771774 .9999969378264834 .00247473991692536 .9999969229796108 .002480732010984686 .999996908096833 .0024867241049549406 .9999968931781499 .002492716198835908 .9999968782235614 .0024987082926273734 .9999968632330677 .002504700386329122 .9999968482066687 .002510692479940938 .9999968331443644 .0025166845734626068 .9999968180461547 .0025226766668939127 .9999968029120399 .002528668760234641 .9999967877420196 .002534660853484576 .9999967725360941 .0025406529466435036 .9999967572942633 .002546645039711208 .9999967420165272 .002552637132687474 .9999967267028858 .002558629225572086 .9999967113533391 .0025646213183648297 .9999966959678871 .0025706134110654896 .9999966805465298 .002576605503673851 .9999966650892672 .0025825975961896977 .9999966495960994 .0025885896886128153 .9999966340670262 .0025945817809429885 .9999966185020478 .0026005738731800024 .9999966029011641 .0026065659653236417 .999996587264375 .002612558057373691 .9999965715916808 .002618550149329935 .9999965558830811 .0026245422411921592 .9999965401385762 .002630534332960148 .9999965243581661 .002636526424633687 .9999965085418506 .0026425185162125596 .9999964926896299 .0026485106076965517 .9999964768015038 .0026545026990854484 .9999964608774725 .0026604947903790337 .9999964449175359 .0026664868815770926 .999996428921694 .0026724789726794104 .9999964128899468 .002678471063685772 .9999963968222944 .0026844631545959617 .9999963807187366 .002690455245409765 .9999963645792737 .002696447336126966 .9999963484039053 .00270243942674735 .9999963321926317 .002708431517270702 .9999963159454529 .0027144236076968066 .9999962996623687 .0027204156980254485 .9999962833433793 .002726407788256413 .9999962669884847 .002732399878389485 .9999962505976846 .0027383919684244484 .9999962341709794 .002744384058361089 .9999962177083689 .0027503761481991913 .999996201209853 .0027563682379385403 .9999961846754319 .0027623603275789207 .9999961681051056 .0027683524171201175 .999996151498874 .002774344506561915 .9999961348567371 .002780336595904099 .9999961181786949 .0027863286851464537 .9999961014647475 .0027923207742887642 .9999960847148948 .0027983128633308155 .9999960679291368 .002804304952272392 .9999960511074735 .002810297041113279 .9999960342499049 .0028162891298532606 .9999960173564312 .0028222812184921227 .9999960004270521 .002828273307029649 .9999959834617678 .002834265395465626 .9999959664605781 .0028402574837998367 .9999959494234832 .002846249572032067 .9999959323504831 .0028522416601621014 .9999959152415777 .002858233748189725 .999995898096767 .002864225836114723 .9999958809160512 .0028702179239368793 .9999958636994299 .0028762100116559793 .9999958464469034 .0028822020992718077 .9999958291584717 .0028881941867841495 .9999958118341348 .0028941862741927895 .9999957944738925 .0029001783614975127 .999995777077745 .002906170448698104 .9999957596456922 .0029121625357943475 .9999957421777342 .002918154622786029 .999995724673871 .0029241467096729327 .9999957071341024 .002930138796454844 .9999956895584287 .0029361308831315474 .9999956719468496 .0029421229697028273 .9999956542993652 .0029481150561684695 .9999956366159757 .0029541071425282584 .9999956188966809 .002960099228781979 .9999956011414808 .002966091314929416 .9999955833503754 .002972083400970354 .9999955655233649 .0029780754869045785 .9999955476604491 .0029840675727318736 .999995529761628 .002990059658452025 .9999955118269016 .0029960517440648163 .99999549385627 .0030020438295700336 .9999954758497331 .0030080359149674612 .999995457807291 .003014028000256884 .9999954397289438 .003020020085438087 .9999954216146911 .0030260121705108552 .9999954034645333 .003032004255474973 .9999953852784702 .003037996340330225 .9999953670565019 .003043988425076397 .9999953487986284 .003049980509713273 .9999953305048496 .0030559725942406386 .9999953121751655 .003061964678658278 )) (define high-lut (FLOATvector-const 1. 0. .9999999999999999 1.1703344634137277e-8 .9999999999999998 2.3406689268274554e-8 .9999999999999993 3.5110033902411824e-8 .9999999999999989 4.6813378536549095e-8 .9999999999999983 5.851672317068635e-8 .9999999999999976 7.022006780482361e-8 .9999999999999967 8.192341243896085e-8 .9999999999999957 9.362675707309808e-8 .9999999999999944 1.0533010170723531e-7 .9999999999999931 1.170334463413725e-7 .9999999999999917 1.287367909755097e-7 .9999999999999901 1.4044013560964687e-7 .9999999999999885 1.5214348024378403e-7 .9999999999999866 1.6384682487792116e-7 .9999999999999846 1.7555016951205827e-7 .9999999999999825 1.8725351414619535e-7 .9999999999999802 1.989568587803324e-7 .9999999999999778 2.1066020341446942e-7 .9999999999999752 2.2236354804860645e-7 .9999999999999726 2.3406689268274342e-7 .9999999999999698 2.4577023731688034e-7 .9999999999999668 2.5747358195101726e-7 .9999999999999638 2.6917692658515413e-7 .9999999999999606 2.8088027121929094e-7 .9999999999999571 2.9258361585342776e-7 .9999999999999537 3.042869604875645e-7 .99999999999995 3.159903051217012e-7 .9999999999999463 3.276936497558379e-7 .9999999999999424 3.3939699438997453e-7 .9999999999999384 3.5110033902411114e-7 .9999999999999342 3.6280368365824763e-7 .9999999999999298 3.7450702829238413e-7 .9999999999999254 3.8621037292652057e-7 .9999999999999208 3.979137175606569e-7 .9999999999999161 4.0961706219479325e-7 .9999999999999113 4.2132040682892953e-7 .9999999999999063 4.330237514630657e-7 .9999999999999011 4.447270960972019e-7 .9999999999998959 4.5643044073133796e-7 .9999999999998904 4.68133785365474e-7 .9999999999998849 4.7983712999961e-7 .9999999999998792 4.915404746337459e-7 .9999999999998733 5.032438192678817e-7 .9999999999998674 5.149471639020175e-7 .9999999999998613 5.266505085361531e-7 .9999999999998551 5.383538531702888e-7 .9999999999998487 5.500571978044243e-7 .9999999999998422 5.617605424385598e-7 .9999999999998356 5.734638870726952e-7 .9999999999998288 5.851672317068305e-7 .9999999999998219 5.968705763409657e-7 .9999999999998148 6.085739209751009e-7 .9999999999998076 6.202772656092359e-7 .9999999999998003 6.319806102433709e-7 .9999999999997928 6.436839548775058e-7 .9999999999997853 6.553872995116406e-7 .9999999999997775 6.670906441457753e-7 .9999999999997696 6.7879398877991e-7 .9999999999997616 6.904973334140445e-7 .9999999999997534 7.02200678048179e-7 .9999999999997452 7.139040226823132e-7 .9999999999997368 7.256073673164475e-7 .9999999999997282 7.373107119505817e-7 .9999999999997194 7.490140565847157e-7 .9999999999997107 7.607174012188497e-7 .9999999999997017 7.724207458529835e-7 .9999999999996926 7.841240904871172e-7 .9999999999996834 7.958274351212508e-7 .9999999999996739 8.075307797553844e-7 .9999999999996644 8.192341243895178e-7 .9999999999996547 8.309374690236511e-7 .999999999999645 8.426408136577842e-7 .9999999999996351 8.543441582919173e-7 .999999999999625 8.660475029260503e-7 .9999999999996148 8.777508475601831e-7 .9999999999996044 8.894541921943158e-7 .999999999999594 9.011575368284484e-7 .9999999999995833 9.128608814625808e-7 .9999999999995726 9.245642260967132e-7 .9999999999995617 9.362675707308454e-7 .9999999999995507 9.479709153649775e-7 .9999999999995395 9.596742599991095e-7 .9999999999995283 9.713776046332412e-7 .9999999999995168 9.83080949267373e-7 .9999999999995052 9.947842939015044e-7 .9999999999994935 1.006487638535636e-6 .9999999999994816 1.0181909831697673e-6 .9999999999994696 1.0298943278038984e-6 .9999999999994575 1.0415976724380293e-6 .9999999999994453 1.0533010170721601e-6 .9999999999994329 1.065004361706291e-6 .9999999999994204 1.0767077063404215e-6 .9999999999994077 1.088411050974552e-6 .9999999999993949 1.1001143956086822e-6 .9999999999993819 1.1118177402428122e-6 .9999999999993688 1.1235210848769423e-6 .9999999999993556 1.135224429511072e-6 .9999999999993423 1.1469277741452017e-6 .9999999999993288 1.1586311187793313e-6 .9999999999993151 1.1703344634134605e-6 .9999999999993014 1.1820378080475897e-6 .9999999999992875 1.1937411526817187e-6 .9999999999992735 1.2054444973158477e-6 .9999999999992593 1.2171478419499764e-6 .9999999999992449 1.2288511865841048e-6 .9999999999992305 1.2405545312182331e-6 .999999999999216 1.2522578758523615e-6 .9999999999992012 1.2639612204864894e-6 .9999999999991863 1.2756645651206173e-6 .9999999999991713 1.287367909754745e-6 .9999999999991562 1.2990712543888725e-6 .9999999999991409 1.3107745990229998e-6 .9999999999991255 1.3224779436571269e-6 .9999999999991099 1.3341812882912537e-6 .9999999999990943 1.3458846329253806e-6 .9999999999990785 1.3575879775595072e-6 .9999999999990625 1.3692913221936337e-6 .9999999999990464 1.3809946668277597e-6 .9999999999990302 1.3926980114618857e-6 .9999999999990138 1.4044013560960117e-6 .9999999999989974 1.4161047007301373e-6 .9999999999989807 1.4278080453642627e-6 .9999999999989639 1.439511389998388e-6 .999999999998947 1.451214734632513e-6 .99999999999893 1.462918079266638e-6 .9999999999989128 1.4746214239007625e-6 .9999999999988954 1.486324768534887e-6 .999999999998878 1.4980281131690111e-6 .9999999999988604 1.5097314578031353e-6 .9999999999988426 1.5214348024372591e-6 .9999999999988247 1.5331381470713828e-6 .9999999999988067 1.544841491705506e-6 .9999999999987886 1.5565448363396294e-6 .9999999999987703 1.5682481809737524e-6 .9999999999987519 1.579951525607875e-6 .9999999999987333 1.5916548702419977e-6 .9999999999987146 1.60335821487612e-6 .9999999999986958 1.615061559510242e-6 .9999999999986768 1.626764904144364e-6 .9999999999986577 1.6384682487784858e-6 .9999999999986384 1.6501715934126072e-6 .9999999999986191 1.6618749380467283e-6 .9999999999985996 1.6735782826808495e-6 .9999999999985799 1.6852816273149702e-6 .9999999999985602 1.6969849719490907e-6 .9999999999985402 1.708688316583211e-6 .9999999999985201 1.720391661217331e-6 .9999999999985 1.732095005851451e-6 .9999999999984795 1.7437983504855706e-6 .9999999999984591 1.7555016951196899e-6 .9999999999984385 1.767205039753809e-6 .9999999999984177 1.778908384387928e-6 .9999999999983968 1.7906117290220465e-6 .9999999999983759 1.802315073656165e-6 .9999999999983546 1.814018418290283e-6 .9999999999983333 1.825721762924401e-6 .9999999999983119 1.8374251075585186e-6 .9999999999982904 1.8491284521926361e-6 .9999999999982686 1.8608317968267533e-6 .9999999999982468 1.8725351414608702e-6 .9999999999982249 1.8842384860949866e-6 .9999999999982027 1.8959418307291031e-6 .9999999999981805 1.9076451753632194e-6 .999999999998158 1.919348519997335e-6 .9999999999981355 1.9310518646314507e-6 .9999999999981128 1.942755209265566e-6 .9999999999980901 1.954458553899681e-6 .9999999999980671 1.966161898533796e-6 .999999999998044 1.9778652431679103e-6 .9999999999980208 1.9895685878020246e-6 .9999999999979975 2.0012719324361386e-6 .999999999997974 2.012975277070252e-6 .9999999999979503 2.0246786217043656e-6 .9999999999979265 2.0363819663384787e-6 .9999999999979027 2.048085310972592e-6 .9999999999978786 2.0597886556067045e-6 .9999999999978545 2.0714920002408167e-6 .9999999999978302 2.0831953448749286e-6 .9999999999978058 2.0948986895090404e-6 .9999999999977811 2.106602034143152e-6 .9999999999977564 2.118305378777263e-6 .9999999999977315 2.1300087234113738e-6 .9999999999977065 2.1417120680454843e-6 .9999999999976814 2.153415412679595e-6 .9999999999976561 2.1651187573137046e-6 .9999999999976307 2.1768221019478143e-6 .9999999999976051 2.188525446581924e-6 .9999999999975795 2.200228791216033e-6 .9999999999975536 2.2119321358501417e-6 .9999999999975278 2.22363548048425e-6 .9999999999975017 2.2353388251183586e-6 .9999999999974754 2.247042169752466e-6 .999999999997449 2.2587455143865738e-6 .9999999999974225 2.2704488590206814e-6 .9999999999973959 2.282152203654788e-6 .9999999999973691 2.293855548288895e-6 .9999999999973422 2.305558892923001e-6 .9999999999973151 2.317262237557107e-6 .999999999997288 2.328965582191213e-6 .9999999999972606 2.340668926825318e-6 .9999999999972332 2.352372271459423e-6 .9999999999972056 2.364075616093528e-6 .9999999999971778 2.3757789607276323e-6 .99999999999715 2.3874823053617365e-6 .999999999997122 2.3991856499958403e-6 .9999999999970938 2.4108889946299437e-6 .9999999999970656 2.4225923392640466e-6 .9999999999970371 2.4342956838981495e-6 .9999999999970085 2.445999028532252e-6 .9999999999969799 2.457702373166354e-6 .999999999996951 2.4694057178004558e-6 .999999999996922 2.4811090624345574e-6 .9999999999968929 2.4928124070686583e-6 .9999999999968637 2.504515751702759e-6 .9999999999968343 2.5162190963368595e-6 .9999999999968048 2.5279224409709594e-6 .9999999999967751 2.5396257856050594e-6 .9999999999967454 2.5513291302391585e-6 .9999999999967154 2.5630324748732576e-6 .9999999999966853 2.5747358195073563e-6 .9999999999966551 2.5864391641414546e-6 .9999999999966248 2.5981425087755525e-6 .9999999999965944 2.6098458534096503e-6 .9999999999965637 2.6215491980437473e-6 .999999999996533 2.6332525426778443e-6 .9999999999965021 2.644955887311941e-6 .999999999996471 2.656659231946037e-6 .99999999999644 2.6683625765801328e-6 .9999999999964087 2.680065921214228e-6 .9999999999963772 2.6917692658483234e-6 .9999999999963456 2.703472610482418e-6 .999999999996314 2.7151759551165123e-6 .9999999999962821 2.7268792997506064e-6 .9999999999962501 2.7385826443846996e-6 .9999999999962179 2.750285989018793e-6 .9999999999961857 2.761989333652886e-6 .9999999999961533 2.7736926782869783e-6 .9999999999961208 2.78539602292107e-6 .9999999999960881 2.797099367555162e-6 .9999999999960553 2.808802712189253e-6 .9999999999960224 2.8205060568233443e-6 .9999999999959893 2.832209401457435e-6 .9999999999959561 2.8439127460915247e-6 .9999999999959227 2.8556160907256145e-6 .9999999999958893 2.867319435359704e-6 .9999999999958556 2.879022779993793e-6 .9999999999958219 2.8907261246278814e-6 .9999999999957879 2.90242946926197e-6 .999999999995754 2.9141328138960576e-6 .9999999999957198 2.925836158530145e-6 .9999999999956855 2.9375395031642317e-6 .999999999995651 2.9492428477983186e-6 .9999999999956164 2.9609461924324046e-6 .9999999999955816 2.9726495370664905e-6 .9999999999955468 2.9843528817005757e-6 .9999999999955118 2.996056226334661e-6 .9999999999954767 3.007759570968745e-6 .9999999999954414 3.0194629156028294e-6 .999999999995406 3.0311662602369133e-6 .9999999999953705 3.0428696048709963e-6 .9999999999953348 3.0545729495050794e-6 .999999999995299 3.066276294139162e-6 .999999999995263 3.0779796387732437e-6 .9999999999952269 3.0896829834073255e-6 .9999999999951907 3.101386328041407e-6 .9999999999951543 3.1130896726754873e-6 .9999999999951178 3.1247930173095678e-6 .9999999999950812 3.136496361943648e-6 .9999999999950444 3.148199706577727e-6 .9999999999950075 3.1599030512118063e-6 .9999999999949705 3.171606395845885e-6 .9999999999949333 3.183309740479963e-6 .999999999994896 3.195013085114041e-6 .9999999999948584 3.206716429748118e-6 .9999999999948209 3.218419774382195e-6 .9999999999947832 3.2301231190162714e-6 .9999999999947453 3.2418264636503477e-6 .9999999999947072 3.253529808284423e-6 .9999999999946692 3.265233152918498e-6 .9999999999946309 3.276936497552573e-6 .9999999999945924 3.288639842186647e-6 .9999999999945539 3.300343186820721e-6 .9999999999945152 3.312046531454794e-6 .9999999999944763 3.323749876088867e-6 .9999999999944373 3.3354532207229395e-6 .9999999999943983 3.3471565653570115e-6 .9999999999943591 3.358859909991083e-6 .9999999999943197 3.370563254625154e-6 .9999999999942801 3.3822665992592245e-6 .9999999999942405 3.3939699438932944e-6 .9999999999942008 3.4056732885273643e-6 .9999999999941608 3.4173766331614334e-6 .9999999999941207 3.429079977795502e-6 .9999999999940805 3.4407833224295702e-6 .9999999999940402 3.452486667063638e-6 .9999999999939997 3.4641900116977054e-6 .999999999993959 3.4758933563317723e-6 .9999999999939183 3.4875967009658384e-6 .9999999999938775 3.4993000455999045e-6 .9999999999938364 3.5110033902339697e-6 .9999999999937953 3.5227067348680345e-6 .999999999993754 3.534410079502099e-6 .9999999999937126 3.546113424136163e-6 .999999999993671 3.5578167687702264e-6 .9999999999936293 3.5695201134042896e-6 .9999999999935875 3.581223458038352e-6 .9999999999935454 3.592926802672414e-6 .9999999999935033 3.6046301473064755e-6 .9999999999934611 3.6163334919405365e-6 .9999999999934187 3.628036836574597e-6 .9999999999933762 3.639740181208657e-6 .9999999999933334 3.6514435258427166e-6 .9999999999932907 3.6631468704767755e-6 .9999999999932477 3.674850215110834e-6 .9999999999932047 3.686553559744892e-6 .9999999999931615 3.6982569043789496e-6 .9999999999931181 3.7099602490130064e-6 .9999999999930747 3.7216635936470627e-6 .999999999993031 3.733366938281119e-6 .9999999999929873 3.745070282915174e-6 .9999999999929433 3.756773627549229e-6 .9999999999928992 3.768476972183284e-6 .9999999999928552 3.7801803168173377e-6 .9999999999928109 3.791883661451391e-6 .9999999999927663 3.803587006085444e-6 .9999999999927218 3.8152903507194965e-6 .9999999999926771 3.826993695353548e-6 .9999999999926322 3.838697039987599e-6 .9999999999925873 3.85040038462165e-6 .9999999999925421 3.862103729255701e-6 .9999999999924968 3.87380707388975e-6 .9999999999924514 3.885510418523799e-6 .9999999999924059 3.897213763157848e-6 .9999999999923602 3.9089171077918965e-6 .9999999999923144 3.9206204524259435e-6 .9999999999922684 3.9323237970599905e-6 .9999999999922223 3.9440271416940376e-6 .9999999999921761 3.955730486328084e-6 .9999999999921297 3.967433830962129e-6 .9999999999920832 3.9791371755961736e-6 .9999999999920366 3.990840520230218e-6 .9999999999919899 4.002543864864262e-6 .9999999999919429 4.014247209498305e-6 .9999999999918958 4.025950554132348e-6 .9999999999918486 4.03765389876639e-6 .9999999999918013 4.049357243400431e-6 .9999999999917539 4.061060588034472e-6 .9999999999917063 4.072763932668513e-6 .9999999999916586 4.084467277302553e-6 .9999999999916107 4.096170621936592e-6 .9999999999915626 4.107873966570632e-6 .9999999999915146 4.119577311204669e-6 .9999999999914663 4.131280655838707e-6 .9999999999914179 4.142984000472745e-6 .9999999999913692 4.154687345106781e-6 .9999999999913206 4.166390689740817e-6 .9999999999912718 4.178094034374852e-6 .9999999999912228 4.189797379008887e-6 .9999999999911737 4.201500723642921e-6 .9999999999911244 4.213204068276955e-6 .999999999991075 4.224907412910988e-6 .9999999999910255 4.236610757545021e-6 .9999999999909759 4.248314102179053e-6 .9999999999909261 4.260017446813084e-6 .9999999999908762 4.271720791447115e-6 .9999999999908261 4.283424136081145e-6 .9999999999907759 4.295127480715175e-6 .9999999999907256 4.306830825349204e-6 .9999999999906751 4.3185341699832325e-6 .9999999999906245 4.33023751461726e-6 .9999999999905738 4.3419408592512875e-6 .9999999999905229 4.353644203885314e-6 .9999999999904718 4.36534754851934e-6 .9999999999904207 4.377050893153365e-6 .9999999999903694 4.38875423778739e-6 .999999999990318 4.400457582421414e-6 .9999999999902665 4.4121609270554384e-6 .9999999999902147 4.423864271689461e-6 .9999999999901629 4.435567616323483e-6 .9999999999901109 4.447270960957506e-6 .9999999999900587 4.458974305591527e-6 .9999999999900065 4.470677650225547e-6 .9999999999899541 4.482380994859567e-6 .9999999999899016 4.494084339493587e-6 .9999999999898489 4.5057876841276054e-6 .9999999999897962 4.517491028761624e-6 .9999999999897432 4.529194373395641e-6 .9999999999896901 4.5408977180296584e-6 .999999999989637 4.552601062663675e-6 .9999999999895836 4.564304407297691e-6 .99999999998953 4.5760077519317055e-6 .9999999999894764 4.5877110965657195e-6 .9999999999894227 4.5994144411997335e-6 .9999999999893688 4.611117785833747e-6 .9999999999893148 4.622821130467759e-6 .9999999999892606 4.634524475101771e-6 .9999999999892063 4.646227819735783e-6 .9999999999891518 4.657931164369793e-6 .9999999999890973 4.669634509003803e-6 .9999999999890425 4.681337853637813e-6 .9999999999889877 4.693041198271821e-6 .9999999999889327 4.704744542905829e-6 .9999999999888776 4.716447887539837e-6 .9999999999888223 4.728151232173843e-6 .9999999999887669 4.73985457680785e-6 .9999999999887114 4.751557921441855e-6 .9999999999886556 4.76326126607586e-6 .9999999999885999 4.774964610709864e-6 .9999999999885439 4.786667955343868e-6 .9999999999884878 4.798371299977871e-6 .9999999999884316 4.810074644611873e-6 .9999999999883752 4.821777989245874e-6 .9999999999883187 4.833481333879875e-6 .9999999999882621 4.845184678513876e-6 .9999999999882053 4.856888023147875e-6 .9999999999881484 4.868591367781874e-6 .9999999999880914 4.880294712415872e-6 .9999999999880341 4.89199805704987e-6 .9999999999879768 4.903701401683867e-6 .9999999999879194 4.915404746317863e-6 .9999999999878618 4.9271080909518585e-6 .9999999999878041 4.938811435585853e-6 .9999999999877462 4.9505147802198475e-6 .9999999999876882 4.962218124853841e-6 .99999999998763 4.973921469487834e-6 .9999999999875717 4.985624814121826e-6 .9999999999875133 4.997328158755817e-6 .9999999999874548 5.009031503389808e-6 .9999999999873961 5.0207348480237985e-6 .9999999999873372 5.032438192657788e-6 .9999999999872783 5.0441415372917765e-6 .9999999999872192 5.055844881925764e-6 .9999999999871599 5.067548226559752e-6 .9999999999871007 5.079251571193739e-6 .9999999999870411 5.090954915827725e-6 .9999999999869814 5.10265826046171e-6 .9999999999869217 5.1143616050956945e-6 .9999999999868617 5.126064949729678e-6 .9999999999868017 5.1377682943636615e-6 .9999999999867415 5.149471638997644e-6 .9999999999866811 5.161174983631626e-6 .9999999999866207 5.172878328265607e-6 .9999999999865601 5.184581672899587e-6 .9999999999864994 5.196285017533567e-6 .9999999999864384 5.2079883621675455e-6 .9999999999863775 5.219691706801524e-6 .9999999999863163 5.2313950514355015e-6 .999999999986255 5.243098396069478e-6 .9999999999861935 5.254801740703454e-6 .999999999986132 5.266505085337429e-6 .9999999999860703 5.278208429971404e-6 .9999999999860084 5.289911774605378e-6 .9999999999859465 5.301615119239351e-6 .9999999999858843 5.313318463873323e-6 .9999999999858221 5.325021808507295e-6 .9999999999857597 5.336725153141267e-6 .9999999999856971 5.3484284977752366e-6 .9999999999856345 5.360131842409206e-6 .9999999999855717 5.371835187043175e-6 .9999999999855087 5.383538531677143e-6 .9999999999854456 5.3952418763111104e-6 .9999999999853825 5.406945220945077e-6 .9999999999853191 5.418648565579043e-6 .9999999999852557 5.4303519102130076e-6 .9999999999851921 5.4420552548469724e-6 .9999999999851282 5.453758599480936e-6 .9999999999850644 5.465461944114899e-6 .9999999999850003 5.47716528874886e-6 .9999999999849362 5.488868633382822e-6 .9999999999848719 5.500571978016782e-6 .9999999999848074 5.512275322650742e-6 .9999999999847429 5.523978667284702e-6 .9999999999846781 5.53568201191866e-6 .9999999999846133 5.547385356552617e-6 .9999999999845482 5.5590887011865745e-6 .9999999999844832 5.57079204582053e-6 .9999999999844179 5.582495390454486e-6 .9999999999843525 5.59419873508844e-6 .9999999999842869 5.605902079722394e-6 .9999999999842213 5.617605424356347e-6 .9999999999841555 5.629308768990299e-6 .9999999999840895 5.641012113624251e-6 .9999999999840234 5.652715458258201e-6 .9999999999839572 5.664418802892152e-6 .9999999999838908 5.6761221475261e-6 .9999999999838243 5.687825492160048e-6 .9999999999837577 5.699528836793996e-6 .9999999999836909 5.711232181427943e-6 .999999999983624 5.722935526061889e-6 .9999999999835569 5.734638870695834e-6 .9999999999834898 5.746342215329779e-6 .9999999999834225 5.758045559963722e-6 .999999999983355 5.769748904597665e-6 .9999999999832874 5.781452249231607e-6 .9999999999832196 5.793155593865548e-6 .9999999999831518 5.804858938499489e-6 .9999999999830838 5.816562283133429e-6 .9999999999830157 5.8282656277673675e-6 .9999999999829474 5.839968972401306e-6 .9999999999828789 5.851672317035243e-6 .9999999999828104 5.86337566166918e-6 .9999999999827417 5.875079006303115e-6 .9999999999826729 5.88678235093705e-6 .9999999999826039 5.898485695570985e-6 .9999999999825349 5.910189040204917e-6 .9999999999824656 5.92189238483885e-6 .9999999999823962 5.933595729472782e-6 .9999999999823267 5.945299074106713e-6 .9999999999822571 5.957002418740643e-6 .9999999999821872 5.9687057633745715e-6 .9999999999821173 5.9804091080085e-6 )) (define (make-w log-n) (result (FLOATmake-vector (* 2 n)))) (define (copy-low-lut) (do ((i 0 (+ i 1))) ((= i lut-table-size)) (let ((index (* i 2))) (FLOATvector-set! result index (FLOATvector-ref low-lut index)) (FLOATvector-set! result (+ index 1) (FLOATvector-ref low-lut (+ index 1)))))) (define (extend-lut multiplier-lut bit-reverse-size bit-reverse-multiplier start end) (define (bit-reverse x n) (do ((i 0 (+ i 1)) (x x (arithmetic-shift x -1)) (result 0 (+ (* result 2) (bitwise-and x 1)))) ((= i n) result))) (let loop ((i start) (j 1)) (if (< i end) (let* ((multiplier-index (* 2 (* (bit-reverse j bit-reverse-size) bit-reverse-multiplier))) (multiplier-real (FLOATvector-ref multiplier-lut multiplier-index)) (multiplier-imag (FLOATvector-ref multiplier-lut (+ multiplier-index 1)))) (let inner ((i i) (k 0)) (if (< k start) (let* ((index (* k 2)) (real (FLOATvector-ref result index)) (imag (FLOATvector-ref result (+ index 1))) (result-real (FLOAT- (FLOAT* multiplier-real real) (FLOAT* multiplier-imag imag))) (result-imag (FLOAT+ (FLOAT* multiplier-real imag) (FLOAT* multiplier-imag real))) (result-index (* i 2))) (FLOATvector-set! result result-index result-real) (FLOATvector-set! result (+ result-index 1) result-imag) (inner (+ i 1) (+ k 1))) (loop i (+ j 1))))) result))) (cond ((<= n lut-table-size) low-lut) ((<= n lut-table-size^2) (copy-low-lut) (extend-lut med-lut (- log-n log-lut-table-size) (arithmetic-shift 1 (- (* 2 log-lut-table-size) log-n)) lut-table-size n)) ((<= n lut-table-size^3) (copy-low-lut) (extend-lut med-lut log-lut-table-size 1 lut-table-size lut-table-size^2) (extend-lut high-lut (- log-n (* 2 log-lut-table-size)) (arithmetic-shift 1 (- (* 3 log-lut-table-size) log-n)) lut-table-size^2 n)) (else (error "asking for too large a table"))))) (define (direct-fft-recursive-4 a W-table) this is from page 66 of and , except that we have (let ((W (FLOATvector 0. 0. 0. 0.))) (define (main-loop M N K SizeOfGroup) (let inner-loop ((K K) (JFirst M)) (if (< JFirst N) (let* ((JLast (+ JFirst SizeOfGroup))) (if (even? K) (begin (FLOATvector-set! W 0 (FLOATvector-ref W-table K)) (FLOATvector-set! W 1 (FLOATvector-ref W-table (+ K 1)))) (begin (FLOATvector-set! W 0 (FLOAT- 0. (FLOATvector-ref W-table K))) (FLOATvector-set! W 1 (FLOATvector-ref W-table (- K 1))))) we know the that the next two complex roots of unity have index 2 K and 2K+1 so that the 2K+1 index root can be gotten from the 2 K index root in the same way that we get W_0 and W_1 from the (FLOATvector-set! W 2 (FLOATvector-ref W-table (* K 2))) (FLOATvector-set! W 3 (FLOATvector-ref W-table (+ (* K 2) 1))) (let J-loop ((J0 JFirst)) (if (< J0 JLast) (let* ((J0 J0) (J1 (+ J0 1)) (J2 (+ J0 SizeOfGroup)) (J3 (+ J2 1)) (J4 (+ J2 SizeOfGroup)) (J5 (+ J4 1)) (J6 (+ J4 SizeOfGroup)) (J7 (+ J6 1))) (let ((W_0 (FLOATvector-ref W 0)) (W_1 (FLOATvector-ref W 1)) (W_2 (FLOATvector-ref W 2)) (W_3 (FLOATvector-ref W 3)) (a_J0 (FLOATvector-ref a J0)) (a_J1 (FLOATvector-ref a J1)) (a_J2 (FLOATvector-ref a J2)) (a_J3 (FLOATvector-ref a J3)) (a_J4 (FLOATvector-ref a J4)) (a_J5 (FLOATvector-ref a J5)) (a_J6 (FLOATvector-ref a J6)) (a_J7 (FLOATvector-ref a J7))) butterflies with entries 2*SizeOfGroup (let ((Temp_0 (FLOAT- (FLOAT* W_0 a_J4) (FLOAT* W_1 a_J5))) (Temp_1 (FLOAT+ (FLOAT* W_0 a_J5) (FLOAT* W_1 a_J4))) (Temp_2 (FLOAT- (FLOAT* W_0 a_J6) (FLOAT* W_1 a_J7))) (Temp_3 (FLOAT+ (FLOAT* W_0 a_J7) (FLOAT* W_1 a_J6)))) (let ((a_J0 (FLOAT+ a_J0 Temp_0)) (a_J1 (FLOAT+ a_J1 Temp_1)) (a_J2 (FLOAT+ a_J2 Temp_2)) (a_J3 (FLOAT+ a_J3 Temp_3)) (a_J4 (FLOAT- a_J0 Temp_0)) (a_J5 (FLOAT- a_J1 Temp_1)) (a_J6 (FLOAT- a_J2 Temp_2)) (a_J7 (FLOAT- a_J3 Temp_3))) now we do the two ( disjoint ) pairs apart , the first pair with , the second with -W3+W2i (let ((W_0 W_2) (W_1 W_3) (W_2 (FLOAT- 0. W_3)) (W_3 W_2)) (let ((Temp_0 (FLOAT- (FLOAT* W_0 a_J2) (FLOAT* W_1 a_J3))) (Temp_1 (FLOAT+ (FLOAT* W_0 a_J3) (FLOAT* W_1 a_J2))) (Temp_2 (FLOAT- (FLOAT* W_2 a_J6) (FLOAT* W_3 a_J7))) (Temp_3 (FLOAT+ (FLOAT* W_2 a_J7) (FLOAT* W_3 a_J6)))) (let ((a_J0 (FLOAT+ a_J0 Temp_0)) (a_J1 (FLOAT+ a_J1 Temp_1)) (a_J2 (FLOAT- a_J0 Temp_0)) (a_J3 (FLOAT- a_J1 Temp_1)) (a_J4 (FLOAT+ a_J4 Temp_2)) (a_J5 (FLOAT+ a_J5 Temp_3)) (a_J6 (FLOAT- a_J4 Temp_2)) (a_J7 (FLOAT- a_J5 Temp_3))) (FLOATvector-set! a J0 a_J0) (FLOATvector-set! a J1 a_J1) (FLOATvector-set! a J2 a_J2) (FLOATvector-set! a J3 a_J3) (FLOATvector-set! a J4 a_J4) (FLOATvector-set! a J5 a_J5) (FLOATvector-set! a J6 a_J6) (FLOATvector-set! a J7 a_J7) (J-loop (+ J0 2))))))))) (inner-loop (+ K 1) (+ JFirst (* SizeOfGroup 4))))))))) (define (recursive-bit M N K SizeOfGroup) (if (<= 2 SizeOfGroup) (begin (main-loop M N K SizeOfGroup) (if (< 2048 (- N M)) (let ((new-size (arithmetic-shift (- N M) -2))) (recursive-bit M (+ M new-size) (* K 4) (arithmetic-shift SizeOfGroup -2)) (recursive-bit (+ M new-size) (+ M (* new-size 2)) (+ (* K 4) 1) (arithmetic-shift SizeOfGroup -2)) (recursive-bit (+ M (* new-size 2)) (+ M (* new-size 3)) (+ (* K 4) 2) (arithmetic-shift SizeOfGroup -2)) (recursive-bit (+ M (* new-size 3)) N (+ (* K 4) 3) (arithmetic-shift SizeOfGroup -2))) (recursive-bit M N (* K 4) (arithmetic-shift SizeOfGroup -2)))))) (define (radix-2-pass a) array is not a power of 4 , so we need to do a basic radix two pass with w=1 ( so W[0]=1.0 and W[1 ] = 0 . ) and then call recursive - bit appropriately on the two half arrays . (let ((SizeOfGroup (arithmetic-shift (FLOATvector-length a) -1))) (let loop ((J0 0)) (if (< J0 SizeOfGroup) (let ((J0 J0) (J2 (+ J0 SizeOfGroup))) (let ((J1 (+ J0 1)) (J3 (+ J2 1))) (let ((a_J0 (FLOATvector-ref a J0)) (a_J1 (FLOATvector-ref a J1)) (a_J2 (FLOATvector-ref a J2)) (a_J3 (FLOATvector-ref a J3))) (let ((a_J0 (FLOAT+ a_J0 a_J2)) (a_J1 (FLOAT+ a_J1 a_J3)) (a_J2 (FLOAT- a_J0 a_J2)) (a_J3 (FLOAT- a_J1 a_J3))) (FLOATvector-set! a J0 a_J0) (FLOATvector-set! a J1 a_J1) (FLOATvector-set! a J2 a_J2) (FLOATvector-set! a J3 a_J3) (loop (+ J0 2)))))))))) (let* ((n (FLOATvector-length a)) (log_n (two^p>=m n))) of 4 , then do a single radix-2 pass and do the rest of (if (odd? log_n) (recursive-bit 0 n 0 (arithmetic-shift n -2)) (let ((n/2 (arithmetic-shift n -1)) (n/8 (arithmetic-shift n -3))) (radix-2-pass a) (recursive-bit 0 n/2 0 n/8) (recursive-bit n/2 n 1 n/8)))))) (define (inverse-fft-recursive-4 a W-table) associated algorithm on page 41 of and , above ( without dividing by 2 each time , so that this has to be " normalized " by dividing by N/2 at the end . (let ((W (FLOATvector 0. 0. 0. 0.))) (define (main-loop M N K SizeOfGroup) (let inner-loop ((K K) (JFirst M)) (if (< JFirst N) (let* ((JLast (+ JFirst SizeOfGroup))) (if (even? K) (begin (FLOATvector-set! W 0 (FLOATvector-ref W-table K)) (FLOATvector-set! W 1 (FLOATvector-ref W-table (+ K 1)))) (begin (FLOATvector-set! W 0 (FLOAT- 0. (FLOATvector-ref W-table K))) (FLOATvector-set! W 1 (FLOATvector-ref W-table (- K 1))))) (FLOATvector-set! W 2 (FLOATvector-ref W-table (* K 2))) (FLOATvector-set! W 3 (FLOATvector-ref W-table (+ (* K 2) 1))) (let J-loop ((J0 JFirst)) (if (< J0 JLast) (let* ((J0 J0) (J1 (+ J0 1)) (J2 (+ J0 SizeOfGroup)) (J3 (+ J2 1)) (J4 (+ J2 SizeOfGroup)) (J5 (+ J4 1)) (J6 (+ J4 SizeOfGroup)) (J7 (+ J6 1))) (let ((W_0 (FLOATvector-ref W 0)) (W_1 (FLOATvector-ref W 1)) (W_2 (FLOATvector-ref W 2)) (W_3 (FLOATvector-ref W 3)) (a_J0 (FLOATvector-ref a J0)) (a_J1 (FLOATvector-ref a J1)) (a_J2 (FLOATvector-ref a J2)) (a_J3 (FLOATvector-ref a J3)) (a_J4 (FLOATvector-ref a J4)) (a_J5 (FLOATvector-ref a J5)) (a_J6 (FLOATvector-ref a J6)) (a_J7 (FLOATvector-ref a J7))) (let ((W_00 W_2) (W_01 W_3) (W_02 (FLOAT- 0. W_3)) (W_03 W_2)) (let ((Temp_0 (FLOAT- a_J0 a_J2)) (Temp_1 (FLOAT- a_J1 a_J3)) (Temp_2 (FLOAT- a_J4 a_J6)) (Temp_3 (FLOAT- a_J5 a_J7))) (let ((a_J0 (FLOAT+ a_J0 a_J2)) (a_J1 (FLOAT+ a_J1 a_J3)) (a_J4 (FLOAT+ a_J4 a_J6)) (a_J5 (FLOAT+ a_J5 a_J7)) (a_J2 (FLOAT+ (FLOAT* W_00 Temp_0) (FLOAT* W_01 Temp_1))) (a_J3 (FLOAT- (FLOAT* W_00 Temp_1) (FLOAT* W_01 Temp_0))) (a_J6 (FLOAT+ (FLOAT* W_02 Temp_2) (FLOAT* W_03 Temp_3))) (a_J7 (FLOAT- (FLOAT* W_02 Temp_3) (FLOAT* W_03 Temp_2)))) (let ((Temp_0 (FLOAT- a_J0 a_J4)) (Temp_1 (FLOAT- a_J1 a_J5)) (Temp_2 (FLOAT- a_J2 a_J6)) (Temp_3 (FLOAT- a_J3 a_J7))) (let ((a_J0 (FLOAT+ a_J0 a_J4)) (a_J1 (FLOAT+ a_J1 a_J5)) (a_J2 (FLOAT+ a_J2 a_J6)) (a_J3 (FLOAT+ a_J3 a_J7)) (a_J4 (FLOAT+ (FLOAT* W_0 Temp_0) (FLOAT* W_1 Temp_1))) (a_J5 (FLOAT- (FLOAT* W_0 Temp_1) (FLOAT* W_1 Temp_0))) (a_J6 (FLOAT+ (FLOAT* W_0 Temp_2) (FLOAT* W_1 Temp_3))) (a_J7 (FLOAT- (FLOAT* W_0 Temp_3) (FLOAT* W_1 Temp_2)))) (FLOATvector-set! a J0 a_J0) (FLOATvector-set! a J1 a_J1) (FLOATvector-set! a J2 a_J2) (FLOATvector-set! a J3 a_J3) (FLOATvector-set! a J4 a_J4) (FLOATvector-set! a J5 a_J5) (FLOATvector-set! a J6 a_J6) (FLOATvector-set! a J7 a_J7) (J-loop (+ J0 2))))))))) (inner-loop (+ K 1) (+ JFirst (* SizeOfGroup 4))))))))) (define (recursive-bit M N K SizeOfGroup) (if (<= 2 SizeOfGroup) (begin (if (< 2048 (- N M)) (let ((new-size (arithmetic-shift (- N M) -2))) (recursive-bit M (+ M new-size) (* K 4) (arithmetic-shift SizeOfGroup -2)) (recursive-bit (+ M new-size) (+ M (* new-size 2)) (+ (* K 4) 1) (arithmetic-shift SizeOfGroup -2)) (recursive-bit (+ M (* new-size 2)) (+ M (* new-size 3)) (+ (* K 4) 2) (arithmetic-shift SizeOfGroup -2)) (recursive-bit (+ M (* new-size 3)) N (+ (* K 4) 3) (arithmetic-shift SizeOfGroup -2))) (recursive-bit M N (* K 4) (arithmetic-shift SizeOfGroup -2))) (main-loop M N K SizeOfGroup)))) (define (radix-2-pass a) (let ((SizeOfGroup (arithmetic-shift (FLOATvector-length a) -1))) (let loop ((J0 0)) (if (< J0 SizeOfGroup) (let ((J0 J0) (J2 (+ J0 SizeOfGroup))) (let ((J1 (+ J0 1)) (J3 (+ J2 1))) (let ((a_J0 (FLOATvector-ref a J0)) (a_J1 (FLOATvector-ref a J1)) (a_J2 (FLOATvector-ref a J2)) (a_J3 (FLOATvector-ref a J3))) (let ((a_J0 (FLOAT+ a_J0 a_J2)) (a_J1 (FLOAT+ a_J1 a_J3)) (a_J2 (FLOAT- a_J0 a_J2)) (a_J3 (FLOAT- a_J1 a_J3))) (FLOATvector-set! a J0 a_J0) (FLOATvector-set! a J1 a_J1) (FLOATvector-set! a J2 a_J2) (FLOATvector-set! a J3 a_J3) (loop (+ J0 2)))))))))) (let* ((n (FLOATvector-length a)) (log_n (two^p>=m n))) (if (odd? log_n) (recursive-bit 0 n 0 (arithmetic-shift n -2)) (let ((n/2 (arithmetic-shift n -1)) (n/8 (arithmetic-shift n -3))) (recursive-bit 0 n/2 0 n/8) (recursive-bit n/2 n 1 n/8) (radix-2-pass a)))))) (define (two^p>=m m) returns smallest p , assumes fixnum m > = 0 (do ((p 0 (+ p 1)) (two^p 1 (* two^p 2))) ((<= m two^p) p))) Works on 2^n complex doubles . (define two^n+1 (expt 2 (+ n 1))) (define inexact-two^-n (FLOAT/ (exact->inexact (expt 2 n)))) (define data (let ((result (FLOATmake-vector two^n+1))) (do ((i 0 (+ i 1))) ((= i two^n+1) result) (FLOATvector-set! result i (exact->inexact i))))) (define (run data) (let ((table (make-w (- n 1)))) (direct-fft-recursive-4 data table) (inverse-fft-recursive-4 data table) (do ((j 0 (+ j 1))) ((= j two^n+1)) (FLOATvector-set! data j (FLOAT* (FLOATvector-ref data j) inexact-two^-n))) (FLOATvector-ref data 3))) (define (main . args) (run-benchmark "fftrad4" fftrad4-iters (lambda (result) (FLOAT<= (FLOATabs (FLOAT- result 3.0)) 1e-4)) (lambda (data) (lambda () (run data))) data)) (main)
7610ed1170427859beb86639beb0c673215e3a2e92b451f4aac5c388df344028
karlhof26/gimp-scheme
torres-analogize.scm
;; ; The GIMP -- an image manipulation program Copyright ( C ) 1995 and ; Analogize script for GIMP 2.4 and Gimp 2.10.24 Copyright ( C ) 2005 < > ; ; Tags: photo, old ; ; Author statement: A script - fu for the GIMP that makes any picture look as if it had ;; been taken using an old analog camera. Exaggerates contrast and ;; saturation and creates a bright and a dark overlay randomly placed . Think of it as kind of a Lomo Kompakt or Kodak instantmatic ;; faking effect. However it still can't make anything to emulate the peculiar chromatism usually achieved using the real thing . ;; Check / for more information . ; ; ; -------------------------------------------------------------------- Distributed by Gimp FX Foundry project ; -------------------------------------------------------------------- ; - Changelog - ; ; -------------------------------------------------------------------- ; ; 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 </>. ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (script-fu-analogize img drawable contrast saturation bright-opacity shadow-opacity duplicate-shadow flatten copy) (let* ( (image 0) (layer 0) (image-width 0) (image-height 0) (half-image-width 0) (half-image-height 0) (center-x 0) (center-y 0) (bright-layer 0) (shadow-layer 0) (shadow-layer2 0) (width-factor 0) (height-factor 0) ) (set! image (if (= copy TRUE) (car (gimp-image-duplicate img)) img)) (gimp-image-undo-group-start image) (set! layer (car (gimp-image-flatten image))) (set! image-width (car (gimp-image-width image))) (set! image-height (car (gimp-image-height image))) (set! half-image-width (/ image-width 2)) (set! half-image-height (/ image-height 2)) (set! width-factor (/ (- 85 (rand 170)) 100)) (set! height-factor (/ (- 85 (rand 170)) 100)) (set! center-x (+ half-image-width (* half-image-width width-factor))) (set! center-y (+ half-image-height (* half-image-height height-factor))) (gimp-drawable-brightness-contrast layer 0.01 (/ contrast 255)) (gimp-hue-saturation layer 0 0 0 saturation) (set! bright-layer (car (gimp-layer-new image image-width image-height 1 "Brillo" bright-opacity 5))) (gimp-image-insert-layer image bright-layer 0 0) (gimp-edit-clear bright-layer) (gimp-context-set-foreground '(255 255 255)) (gimp-edit-blend bright-layer 2 0 2 100 0 0 FALSE FALSE 1 3 TRUE center-x center-y (+ half-image-width center-x) 0) (set! shadow-layer (car (gimp-layer-new image image-width image-height 1 "Sombra" shadow-opacity 5))) (gimp-image-insert-layer image shadow-layer 0 0) (gimp-edit-clear shadow-layer) (gimp-context-set-foreground '(0 0 0)) (if (= (rand 2) 1) (begin ;(gimp-message "rand is 1") ( gimp - message ( number->string ( rand 2 ) ) ) ( gimp - message ( number->string ( rand 2 ) ) ) (gimp-edit-blend shadow-layer 2 0 0 100 0 0 FALSE FALSE 1 4 TRUE 0 0 center-x center-y) (gimp-edit-blend shadow-layer 2 0 0 100 0 0 FALSE FALSE 1 4 TRUE image-width image-height center-x center-y) ) (begin ( gimp - message " rand is not 1 " ) ( gimp - message ( number->string ( rand 2 ) ) ) (gimp-edit-blend shadow-layer 2 0 0 100 0 0 FALSE FALSE 0 0 TRUE image-width 0 center-x center-y) (gimp-edit-blend shadow-layer BLEND-FG-TRANSPARENT LAYER-MODE-NORMAL-LEGACY GRADIENT-LINEAR 100 0 REPEAT-NONE FALSE FALSE 1 4 TRUE 0 image-height center-x center-y) ) ) (cond ((= duplicate-shadow TRUE) (set! shadow-layer2 (car (gimp-layer-copy shadow-layer 0))) (gimp-image-insert-layer image shadow-layer2 0 -1)); was 0 0 ) (cond ((= flatten TRUE) (gimp-image-flatten image)) ) (cond ((= copy TRUE) (gimp-display-new image)) ) (gimp-image-undo-group-end image) (gimp-displays-flush) ) ) (script-fu-register "script-fu-analogize" "Analogize..." "A simple analog camera faking effect A script-fu for the GIMP that makes any picture look as if it had been taken using an old analog camera. Exaggerates contrast and saturation and creates a bright and a dark overlay randomly placed. Think of it as kind of a Lomo Kompakt or Kodak instantmatic faking effect. However it still can't make anything to emulate the peculiar chromatism usually achieved using the real thing. \nfile:torres-analogize.scm" "Ismael Valladolid Torres <>" "Ismael Valladolid Torres" "2005" "RGB*" SF-IMAGE "The image" 0 SF-DRAWABLE "The layer" 0 SF-ADJUSTMENT "Contrast" '(20 0 126 1 5 0 0) SF-ADJUSTMENT "Saturation" '(20 0 60 1 5 0 0) SF-ADJUSTMENT "Bright layer opacity" '(80 0 100 1 10 0 0) SF-ADJUSTMENT "Shadow layer opacity" '(100 0 100 1 10 0 0) SF-TOGGLE "Duplicate the shadow layer" TRUE SF-TOGGLE "Flatten image after processing" FALSE SF-TOGGLE "Work on copy" TRUE ) (script-fu-menu-register "script-fu-analogize" "<Image>/Script-Fu/Toolbox/Artistic") ; end of script
null
https://raw.githubusercontent.com/karlhof26/gimp-scheme/8e00194f318281ef9e7808b96d44ecff7cffd413/torres-analogize.scm
scheme
The GIMP -- an image manipulation program Tags: photo, old Author statement: been taken using an old analog camera. Exaggerates contrast and saturation and creates a bright and a dark overlay randomly faking effect. However it still can't make anything to emulate the -------------------------------------------------------------------- -------------------------------------------------------------------- - Changelog - -------------------------------------------------------------------- This program is free software: you can redistribute it and/or modify (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. along with this program. If not, see </>. (gimp-message "rand is 1") was 0 0 end of script
Copyright ( C ) 1995 and Analogize script for GIMP 2.4 and Gimp 2.10.24 Copyright ( C ) 2005 < > A script - fu for the GIMP that makes any picture look as if it had placed . Think of it as kind of a Lomo Kompakt or Kodak instantmatic peculiar chromatism usually achieved using the real thing . Check / for more information . Distributed by Gimp FX Foundry project it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License (define (script-fu-analogize img drawable contrast saturation bright-opacity shadow-opacity duplicate-shadow flatten copy) (let* ( (image 0) (layer 0) (image-width 0) (image-height 0) (half-image-width 0) (half-image-height 0) (center-x 0) (center-y 0) (bright-layer 0) (shadow-layer 0) (shadow-layer2 0) (width-factor 0) (height-factor 0) ) (set! image (if (= copy TRUE) (car (gimp-image-duplicate img)) img)) (gimp-image-undo-group-start image) (set! layer (car (gimp-image-flatten image))) (set! image-width (car (gimp-image-width image))) (set! image-height (car (gimp-image-height image))) (set! half-image-width (/ image-width 2)) (set! half-image-height (/ image-height 2)) (set! width-factor (/ (- 85 (rand 170)) 100)) (set! height-factor (/ (- 85 (rand 170)) 100)) (set! center-x (+ half-image-width (* half-image-width width-factor))) (set! center-y (+ half-image-height (* half-image-height height-factor))) (gimp-drawable-brightness-contrast layer 0.01 (/ contrast 255)) (gimp-hue-saturation layer 0 0 0 saturation) (set! bright-layer (car (gimp-layer-new image image-width image-height 1 "Brillo" bright-opacity 5))) (gimp-image-insert-layer image bright-layer 0 0) (gimp-edit-clear bright-layer) (gimp-context-set-foreground '(255 255 255)) (gimp-edit-blend bright-layer 2 0 2 100 0 0 FALSE FALSE 1 3 TRUE center-x center-y (+ half-image-width center-x) 0) (set! shadow-layer (car (gimp-layer-new image image-width image-height 1 "Sombra" shadow-opacity 5))) (gimp-image-insert-layer image shadow-layer 0 0) (gimp-edit-clear shadow-layer) (gimp-context-set-foreground '(0 0 0)) (if (= (rand 2) 1) (begin ( gimp - message ( number->string ( rand 2 ) ) ) ( gimp - message ( number->string ( rand 2 ) ) ) (gimp-edit-blend shadow-layer 2 0 0 100 0 0 FALSE FALSE 1 4 TRUE 0 0 center-x center-y) (gimp-edit-blend shadow-layer 2 0 0 100 0 0 FALSE FALSE 1 4 TRUE image-width image-height center-x center-y) ) (begin ( gimp - message " rand is not 1 " ) ( gimp - message ( number->string ( rand 2 ) ) ) (gimp-edit-blend shadow-layer 2 0 0 100 0 0 FALSE FALSE 0 0 TRUE image-width 0 center-x center-y) (gimp-edit-blend shadow-layer BLEND-FG-TRANSPARENT LAYER-MODE-NORMAL-LEGACY GRADIENT-LINEAR 100 0 REPEAT-NONE FALSE FALSE 1 4 TRUE 0 image-height center-x center-y) ) ) (cond ((= duplicate-shadow TRUE) (set! shadow-layer2 (car (gimp-layer-copy shadow-layer 0))) ) (cond ((= flatten TRUE) (gimp-image-flatten image)) ) (cond ((= copy TRUE) (gimp-display-new image)) ) (gimp-image-undo-group-end image) (gimp-displays-flush) ) ) (script-fu-register "script-fu-analogize" "Analogize..." "A simple analog camera faking effect A script-fu for the GIMP that makes any picture look as if it had been taken using an old analog camera. Exaggerates contrast and saturation and creates a bright and a dark overlay randomly placed. Think of it as kind of a Lomo Kompakt or Kodak instantmatic faking effect. However it still can't make anything to emulate the peculiar chromatism usually achieved using the real thing. \nfile:torres-analogize.scm" "Ismael Valladolid Torres <>" "Ismael Valladolid Torres" "2005" "RGB*" SF-IMAGE "The image" 0 SF-DRAWABLE "The layer" 0 SF-ADJUSTMENT "Contrast" '(20 0 126 1 5 0 0) SF-ADJUSTMENT "Saturation" '(20 0 60 1 5 0 0) SF-ADJUSTMENT "Bright layer opacity" '(80 0 100 1 10 0 0) SF-ADJUSTMENT "Shadow layer opacity" '(100 0 100 1 10 0 0) SF-TOGGLE "Duplicate the shadow layer" TRUE SF-TOGGLE "Flatten image after processing" FALSE SF-TOGGLE "Work on copy" TRUE ) (script-fu-menu-register "script-fu-analogize" "<Image>/Script-Fu/Toolbox/Artistic")
c53d77c195383f54da5b7b38849ae52a88fdf4db7bf801232c38eaef0b646258
paurkedal/ocaml-radixmap
ip_radixmap.mli
Copyright ( C ) 2017 - -2022 Petter A. Urkedal < > * * This library is free software ; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version , with the LGPL-3.0 Linking Exception . * * This library 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 Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library . If not , see * < / > and < > , respectively . * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version, with the LGPL-3.0 Linking Exception. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library. If not, see * </> and <>, respectively. *) (** Radix map over IP networks. *) module Poly_v4 : sig type ('a, 'id) t end module Poly_v6 : sig type ('a, 'id) t end module Make_v4 (Cod : Bitword_radixmap_sig.EQUAL) : Ip_radixmap_sig.S with type address = Ipaddr.V4.t and type network = Ipaddr.V4.Prefix.t and type cod = Cod.t and type ('a, 'id) poly = ('a, 'id) Poly_v4.t module Make_v6 (Cod : Bitword_radixmap_sig.EQUAL) : Ip_radixmap_sig.S with type address = Ipaddr.V6.t and type network = Ipaddr.V6.Prefix.t and type cod = Cod.t and type ('a, 'id) poly = ('a, 'id) Poly_v6.t
null
https://raw.githubusercontent.com/paurkedal/ocaml-radixmap/93d0df62ac1da91c42dfdbac579e0e55a2dbdd5e/lib/ip_radixmap.mli
ocaml
* Radix map over IP networks.
Copyright ( C ) 2017 - -2022 Petter A. Urkedal < > * * This library is free software ; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version , with the LGPL-3.0 Linking Exception . * * This library 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 Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library . If not , see * < / > and < > , respectively . * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version, with the LGPL-3.0 Linking Exception. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library. If not, see * </> and <>, respectively. *) module Poly_v4 : sig type ('a, 'id) t end module Poly_v6 : sig type ('a, 'id) t end module Make_v4 (Cod : Bitword_radixmap_sig.EQUAL) : Ip_radixmap_sig.S with type address = Ipaddr.V4.t and type network = Ipaddr.V4.Prefix.t and type cod = Cod.t and type ('a, 'id) poly = ('a, 'id) Poly_v4.t module Make_v6 (Cod : Bitword_radixmap_sig.EQUAL) : Ip_radixmap_sig.S with type address = Ipaddr.V6.t and type network = Ipaddr.V6.Prefix.t and type cod = Cod.t and type ('a, 'id) poly = ('a, 'id) Poly_v6.t
4e2c048660e472971bae87937020f718e89ea7a2997e09369a2ebfb4320a6ff7
wavewave/hoodle
Simple.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # OPTIONS_GHC -fno - warn - orphans # module Data.Hoodle.Simple where import Data.Aeson.TH (defaultOptions, deriveJSON, fieldLabelModifier) import Data.Aeson.Types ( FromJSON (..), ToJSON (..), Value (..), object, (.:), (.=), ) import Data.ByteString.Char8 (ByteString, pack) import Data.Hoodle.Util (fst3, snd3) import qualified Data.Serialize as SE import Data.Strict.Tuple (Pair (..)) import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Data.UUID.V4 (nextRandom) import Lens.Micro (Lens', lens, set) import Prelude hiding (curry, fst, putStrLn, snd, uncurry) -- | type Title = ByteString | Orphan instance for ByteString -- __TODO__: Remove this instance ToJSON ByteString where toJSON = String . TE.decodeUtf8 | Orphan instance for ByteString -- __TODO__: Remove this instance FromJSON ByteString where parseJSON v = TE.encodeUtf8 <$> parseJSON v -- | Orphan instance for Pair instance (SE.Serialize a, SE.Serialize b) => SE.Serialize (Pair a b) where put (x :!: y) = SE.put x >> SE.put y get = (:!:) <$> SE.get <*> SE.get -- | data Dimension = Dim {dim_width :: !Double, dim_height :: !Double} deriving (Show, Eq, Ord) $(deriveJSON defaultOptions {fieldLabelModifier = drop 4} ''Dimension) -- | instance SE.Serialize Dimension where put (Dim w h) = SE.put w >> SE.put h get = Dim <$> SE.get <*> SE.get -- | Pen stroke item data Stroke = Stroke { stroke_tool :: !ByteString, stroke_color :: !ByteString, stroke_width :: !Double, stroke_data :: ![Pair Double Double] } | VWStroke { stroke_tool :: ByteString, stroke_color :: ByteString, stroke_vwdata :: [(Double, Double, Double)] } deriving (Show, Eq, Ord) $(deriveJSON defaultOptions {fieldLabelModifier = drop 7} ''Stroke) instance SE.Serialize Stroke where put Stroke {..} = SE.putWord8 0 >> SE.put stroke_tool >> SE.put stroke_color >> SE.put stroke_width >> SE.put stroke_data put VWStroke {..} = SE.putWord8 1 >> SE.put stroke_tool >> SE.put stroke_color >> SE.put stroke_vwdata get = do tag <- SE.getWord8 case tag of 0 -> Stroke <$> SE.get <*> SE.get <*> SE.get <*> SE.get 1 -> VWStroke <$> SE.get <*> SE.get <*> SE.get _ -> fail "err in Stroke parsing" -- | Image item data Image = Image { img_src :: ByteString, img_pos :: (Double, Double), img_dim :: !Dimension } deriving (Show, Eq, Ord) instance ToJSON Image where toJSON Image {..} = object [ "pos" .= toJSON img_pos, "dim" .= toJSON img_dim ] instance FromJSON Image where parseJSON (Object v) = Image "" <$> v .: "pos" <*> v .: "dim" parseJSON _ = fail "error in parsing Image" $ ( deriveJSON defaultOptions { fieldLabelModifier = drop 4 } '' Image ) instance SE.Serialize Image where put Image {..} = SE.put img_src >> SE.put img_pos >> SE.put img_dim get = Image <$> SE.get <*> SE.get <*> SE.get data SVG = SVG { svg_text :: Maybe ByteString, svg_command :: Maybe ByteString, svg_render :: ByteString, svg_pos :: (Double, Double), svg_dim :: !Dimension } deriving (Show, Eq, Ord) $ ( deriveJSON defaultOptions { fieldLabelModifier = drop 4 } '' SVG ) instance ToJSON SVG where toJSON SVG {..} = object [ "pos" .= toJSON svg_pos, "dim" .= toJSON svg_dim ] instance FromJSON SVG where parseJSON (Object v) = SVG Nothing Nothing "" <$> v .: "pos" <*> v .: "dim" parseJSON _ = fail "error in parsing SVG" -- | instance SE.Serialize SVG where put SVG {..} = SE.put svg_text >> SE.put svg_command >> SE.put svg_render >> SE.put svg_pos >> SE.put svg_dim get = SVG <$> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get -- | data Link = Link { link_id :: ByteString, link_type :: ByteString, link_location :: ByteString, link_text :: Maybe ByteString, link_command :: Maybe ByteString, link_render :: ByteString, link_pos :: (Double, Double), link_dim :: !Dimension } | LinkDocID { link_id :: ByteString, link_linkeddocid :: ByteString, link_location :: ByteString, link_text :: Maybe ByteString, link_command :: Maybe ByteString, link_render :: ByteString, link_pos :: (Double, Double), link_dim :: !Dimension } | LinkAnchor { link_id :: ByteString, link_linkeddocid :: ByteString, link_location :: ByteString, link_anchorid :: ByteString, link_render :: ByteString, link_pos :: (Double, Double), link_dim :: !Dimension } deriving (Show, Eq, Ord) instance ToJSON Link where toJSON Link {..} = object [ "tag" .= String "Link", "id" .= toJSON link_id, "type" .= toJSON link_type, "location" .= toJSON link_location, "pos" .= toJSON link_pos, "dim" .= toJSON link_dim ] toJSON LinkDocID {..} = object [ "tag" .= String "LinkDocID", "id" .= toJSON link_id, "linkeddocid" .= toJSON link_linkeddocid, "location" .= toJSON link_location, "pos" .= toJSON link_pos, "dim" .= toJSON link_dim ] toJSON LinkAnchor {..} = object [ "tag" .= String "LinkAnchor", "id" .= toJSON link_id, "linkeddocid" .= toJSON link_linkeddocid, "location" .= toJSON link_location, "anchorid" .= toJSON link_anchorid, "pos" .= toJSON link_pos, "dim" .= toJSON link_dim ] instance FromJSON Link where parseJSON (Object v) = do tag :: T.Text <- v .: "tag" case tag of "Link" -> Link <$> v .: "id" <*> v .: "type" <*> v .: "location" <*> pure Nothing <*> pure Nothing <*> pure "" <*> v .: "pos" <*> v .: "dim" "LinkDocID" -> LinkDocID <$> v .: "id" <*> v .: "linkeddocid" <*> v .: "location" <*> pure Nothing <*> pure Nothing <*> pure "" <*> v .: "pos" <*> v .: "dim" "LinkAnchor" -> LinkAnchor <$> v .: "id" <*> v .: "linkeddocid" <*> v .: "location" <*> v .: "anchorid" <*> pure "" <*> v .: "pos" <*> v .: "dim" _ -> fail "error in parsing Link" parseJSON _ = fail "error in parsing Link" $ ( deriveJSON defaultOptions { fieldLabelModifier = drop 5 } '' Link ) instance SE.Serialize Link where put Link {..} = SE.putWord8 0 >> SE.put link_id >> SE.put link_type >> SE.put link_location >> SE.put link_text >> SE.put link_command >> SE.put link_render >> SE.put link_pos >> SE.put link_dim put LinkDocID {..} = SE.putWord8 1 >> SE.put link_id >> SE.put link_linkeddocid >> SE.put link_location >> SE.put link_text >> SE.put link_command >> SE.put link_render >> SE.put link_pos >> SE.put link_dim put LinkAnchor {..} = SE.putWord8 2 >> SE.put link_id >> SE.put link_linkeddocid >> SE.put link_location >> SE.put link_anchorid >> SE.put link_render >> SE.put link_pos >> SE.put link_dim get = do tag <- SE.getWord8 case tag of 0 -> Link <$> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get 1 -> LinkDocID <$> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get 2 -> LinkAnchor <$> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get _ -> fail "err in Link parsing" data Anchor = Anchor { anchor_id :: ByteString, anchor_render :: ByteString, anchor_pos :: (Double, Double), anchor_dim :: !Dimension } deriving (Show, Eq, Ord) $(deriveJSON defaultOptions {fieldLabelModifier = drop 7} ''Anchor) instance SE.Serialize Anchor where put Anchor {..} = SE.put anchor_id >> SE.put anchor_render >> SE.put anchor_pos >> SE.put anchor_dim get = Anchor <$> SE.get <*> SE.get <*> SE.get <*> SE.get -- | wrapper of object embeddable in Layer data Item = ItemStroke Stroke | ItemImage Image | ItemSVG SVG | ItemLink Link | ItemAnchor Anchor deriving (Show, Eq, Ord) $(deriveJSON defaultOptions ''Item) -- | instance SE.Serialize Item where put (ItemStroke str) = SE.putWord8 0 >> SE.put str put (ItemImage img) = SE.putWord8 1 >> SE.put img put (ItemSVG svg) = SE.putWord8 2 >> SE.put svg put (ItemLink lnk) = SE.putWord8 3 >> SE.put lnk put (ItemAnchor anc) = SE.putWord8 4 >> SE.put anc get = do tag <- SE.getWord8 case tag of 0 -> ItemStroke <$> SE.get 1 -> ItemImage <$> SE.get 2 -> ItemSVG <$> SE.get 3 -> ItemLink <$> SE.get 4 -> ItemAnchor <$> SE.get _ -> fail "err in Item parsing" -- | data Background = Background { bkg_type :: !ByteString, bkg_color :: !ByteString, bkg_style :: !ByteString } | BackgroundPdf { bkg_type :: ByteString, bkg_domain :: Maybe ByteString, bkg_filename :: Maybe ByteString, bkg_pageno :: Int } | BackgroundEmbedPdf { bkg_type :: ByteString, bkg_pageno :: Int } deriving (Show) $(deriveJSON defaultOptions {fieldLabelModifier = drop 4} ''Background) -- | data Revision = Revision { _revmd5 :: !ByteString, _revtxt :: !ByteString } | RevisionInk { _revmd5 :: !ByteString, _revink :: [Stroke] } deriving (Show) $(deriveJSON defaultOptions {fieldLabelModifier = drop 1} ''Revision) -- | newtype Layer = Layer {layer_items :: [Item]} deriving (Show) $(deriveJSON defaultOptions {fieldLabelModifier = drop 6} ''Layer) -- | data Page = Page { page_dim :: !Dimension, page_bkg :: !Background, page_layers :: ![Layer] } deriving (Show) $(deriveJSON defaultOptions {fieldLabelModifier = drop 5} ''Page) -- | data Hoodle = Hoodle { hoodle_id :: ByteString, hoodle_title :: !Title, hoodle_revisions :: [Revision], hoodle_embeddedpdf :: Maybe ByteString, hoodle_embeddedtext :: Maybe T.Text, hoodle_pages :: ![Page] } deriving (Show) $(deriveJSON defaultOptions {fieldLabelModifier = drop 7} ''Hoodle) -- | getXYtuples :: Stroke -> [(Double, Double)] getXYtuples (Stroke _t _c _w d) = map (\(x :!: y) -> (x, y)) d getXYtuples (VWStroke _t _c d) = map ((,) <$> fst3 <*> snd3) d ---------------------------- -- Lenses ---------------------------- -- | tool :: Lens' Stroke ByteString tool = lens stroke_tool (\f a -> f {stroke_tool = a}) -- | color :: Lens' Stroke ByteString color = lens stroke_color (\f a -> f {stroke_color = a}) -- | hoodleID :: Lens' Hoodle ByteString hoodleID = lens hoodle_id (\f a -> f {hoodle_id = a}) -- | title :: Lens' Hoodle Title title = lens hoodle_title (\f a -> f {hoodle_title = a}) -- | revisions :: Lens' Hoodle [Revision] revisions = lens hoodle_revisions (\f a -> f {hoodle_revisions = a}) -- | revmd5 :: Lens' Revision ByteString revmd5 = lens _revmd5 (\f a -> f {_revmd5 = a}) -- | embeddedPdf :: Lens' Hoodle (Maybe ByteString) embeddedPdf = lens hoodle_embeddedpdf (\f a -> f {hoodle_embeddedpdf = a}) -- | embeddedText :: Lens' Hoodle (Maybe T.Text) embeddedText = lens hoodle_embeddedtext (\f a -> f {hoodle_embeddedtext = a}) -- | pages :: Lens' Hoodle [Page] pages = lens hoodle_pages (\f a -> f {hoodle_pages = a}) -- | dimension :: Lens' Page Dimension dimension = lens page_dim (\f a -> f {page_dim = a}) -- | background :: Lens' Page Background background = lens page_bkg (\f a -> f {page_bkg = a}) -- | layers :: Lens' Page [Layer] layers = lens page_layers (\f a -> f {page_layers = a}) -- | items :: Lens' Layer [Item] items = lens layer_items (\f a -> f {layer_items = a}) -------------------------- -- empty objects -------------------------- -- | emptyHoodle :: IO Hoodle emptyHoodle = do uuid <- nextRandom return $ Hoodle ((pack . show) uuid) "" [] Nothing Nothing [] -- | emptyLayer :: Layer emptyLayer = Layer {layer_items = []} -- | emptyStroke :: Stroke emptyStroke = Stroke "pen" "black" 1.4 [] -- | defaultBackground :: Background defaultBackground = Background { bkg_type = "solid", bkg_color = "white", bkg_style = "lined" } -- | defaultPage :: Page defaultPage = Page { page_dim = Dim 612.0 792.0, page_bkg = defaultBackground, page_layers = [emptyLayer] } -- | defaultHoodle :: IO Hoodle defaultHoodle = set title "untitled" . set embeddedPdf Nothing . set pages [defaultPage] <$> emptyHoodle -- | newPageFromOld :: Page -> Page newPageFromOld page = Page { page_dim = page_dim page, page_bkg = page_bkg page, page_layers = [emptyLayer] }
null
https://raw.githubusercontent.com/wavewave/hoodle/fa7481d14a53733b2f6ae9debc95357d904a943c/types/src/Data/Hoodle/Simple.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE OverloadedStrings # | __TODO__: Remove this __TODO__: Remove this | Orphan instance for Pair | | | Pen stroke item | Image item | | | wrapper of object embeddable in Layer | | | | | | | -------------------------- Lenses -------------------------- | | | | | | | | | | | | | ------------------------ empty objects ------------------------ | | | | | | |
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # OPTIONS_GHC -fno - warn - orphans # module Data.Hoodle.Simple where import Data.Aeson.TH (defaultOptions, deriveJSON, fieldLabelModifier) import Data.Aeson.Types ( FromJSON (..), ToJSON (..), Value (..), object, (.:), (.=), ) import Data.ByteString.Char8 (ByteString, pack) import Data.Hoodle.Util (fst3, snd3) import qualified Data.Serialize as SE import Data.Strict.Tuple (Pair (..)) import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Data.UUID.V4 (nextRandom) import Lens.Micro (Lens', lens, set) import Prelude hiding (curry, fst, putStrLn, snd, uncurry) type Title = ByteString | Orphan instance for ByteString instance ToJSON ByteString where toJSON = String . TE.decodeUtf8 | Orphan instance for ByteString instance FromJSON ByteString where parseJSON v = TE.encodeUtf8 <$> parseJSON v instance (SE.Serialize a, SE.Serialize b) => SE.Serialize (Pair a b) where put (x :!: y) = SE.put x >> SE.put y get = (:!:) <$> SE.get <*> SE.get data Dimension = Dim {dim_width :: !Double, dim_height :: !Double} deriving (Show, Eq, Ord) $(deriveJSON defaultOptions {fieldLabelModifier = drop 4} ''Dimension) instance SE.Serialize Dimension where put (Dim w h) = SE.put w >> SE.put h get = Dim <$> SE.get <*> SE.get data Stroke = Stroke { stroke_tool :: !ByteString, stroke_color :: !ByteString, stroke_width :: !Double, stroke_data :: ![Pair Double Double] } | VWStroke { stroke_tool :: ByteString, stroke_color :: ByteString, stroke_vwdata :: [(Double, Double, Double)] } deriving (Show, Eq, Ord) $(deriveJSON defaultOptions {fieldLabelModifier = drop 7} ''Stroke) instance SE.Serialize Stroke where put Stroke {..} = SE.putWord8 0 >> SE.put stroke_tool >> SE.put stroke_color >> SE.put stroke_width >> SE.put stroke_data put VWStroke {..} = SE.putWord8 1 >> SE.put stroke_tool >> SE.put stroke_color >> SE.put stroke_vwdata get = do tag <- SE.getWord8 case tag of 0 -> Stroke <$> SE.get <*> SE.get <*> SE.get <*> SE.get 1 -> VWStroke <$> SE.get <*> SE.get <*> SE.get _ -> fail "err in Stroke parsing" data Image = Image { img_src :: ByteString, img_pos :: (Double, Double), img_dim :: !Dimension } deriving (Show, Eq, Ord) instance ToJSON Image where toJSON Image {..} = object [ "pos" .= toJSON img_pos, "dim" .= toJSON img_dim ] instance FromJSON Image where parseJSON (Object v) = Image "" <$> v .: "pos" <*> v .: "dim" parseJSON _ = fail "error in parsing Image" $ ( deriveJSON defaultOptions { fieldLabelModifier = drop 4 } '' Image ) instance SE.Serialize Image where put Image {..} = SE.put img_src >> SE.put img_pos >> SE.put img_dim get = Image <$> SE.get <*> SE.get <*> SE.get data SVG = SVG { svg_text :: Maybe ByteString, svg_command :: Maybe ByteString, svg_render :: ByteString, svg_pos :: (Double, Double), svg_dim :: !Dimension } deriving (Show, Eq, Ord) $ ( deriveJSON defaultOptions { fieldLabelModifier = drop 4 } '' SVG ) instance ToJSON SVG where toJSON SVG {..} = object [ "pos" .= toJSON svg_pos, "dim" .= toJSON svg_dim ] instance FromJSON SVG where parseJSON (Object v) = SVG Nothing Nothing "" <$> v .: "pos" <*> v .: "dim" parseJSON _ = fail "error in parsing SVG" instance SE.Serialize SVG where put SVG {..} = SE.put svg_text >> SE.put svg_command >> SE.put svg_render >> SE.put svg_pos >> SE.put svg_dim get = SVG <$> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get data Link = Link { link_id :: ByteString, link_type :: ByteString, link_location :: ByteString, link_text :: Maybe ByteString, link_command :: Maybe ByteString, link_render :: ByteString, link_pos :: (Double, Double), link_dim :: !Dimension } | LinkDocID { link_id :: ByteString, link_linkeddocid :: ByteString, link_location :: ByteString, link_text :: Maybe ByteString, link_command :: Maybe ByteString, link_render :: ByteString, link_pos :: (Double, Double), link_dim :: !Dimension } | LinkAnchor { link_id :: ByteString, link_linkeddocid :: ByteString, link_location :: ByteString, link_anchorid :: ByteString, link_render :: ByteString, link_pos :: (Double, Double), link_dim :: !Dimension } deriving (Show, Eq, Ord) instance ToJSON Link where toJSON Link {..} = object [ "tag" .= String "Link", "id" .= toJSON link_id, "type" .= toJSON link_type, "location" .= toJSON link_location, "pos" .= toJSON link_pos, "dim" .= toJSON link_dim ] toJSON LinkDocID {..} = object [ "tag" .= String "LinkDocID", "id" .= toJSON link_id, "linkeddocid" .= toJSON link_linkeddocid, "location" .= toJSON link_location, "pos" .= toJSON link_pos, "dim" .= toJSON link_dim ] toJSON LinkAnchor {..} = object [ "tag" .= String "LinkAnchor", "id" .= toJSON link_id, "linkeddocid" .= toJSON link_linkeddocid, "location" .= toJSON link_location, "anchorid" .= toJSON link_anchorid, "pos" .= toJSON link_pos, "dim" .= toJSON link_dim ] instance FromJSON Link where parseJSON (Object v) = do tag :: T.Text <- v .: "tag" case tag of "Link" -> Link <$> v .: "id" <*> v .: "type" <*> v .: "location" <*> pure Nothing <*> pure Nothing <*> pure "" <*> v .: "pos" <*> v .: "dim" "LinkDocID" -> LinkDocID <$> v .: "id" <*> v .: "linkeddocid" <*> v .: "location" <*> pure Nothing <*> pure Nothing <*> pure "" <*> v .: "pos" <*> v .: "dim" "LinkAnchor" -> LinkAnchor <$> v .: "id" <*> v .: "linkeddocid" <*> v .: "location" <*> v .: "anchorid" <*> pure "" <*> v .: "pos" <*> v .: "dim" _ -> fail "error in parsing Link" parseJSON _ = fail "error in parsing Link" $ ( deriveJSON defaultOptions { fieldLabelModifier = drop 5 } '' Link ) instance SE.Serialize Link where put Link {..} = SE.putWord8 0 >> SE.put link_id >> SE.put link_type >> SE.put link_location >> SE.put link_text >> SE.put link_command >> SE.put link_render >> SE.put link_pos >> SE.put link_dim put LinkDocID {..} = SE.putWord8 1 >> SE.put link_id >> SE.put link_linkeddocid >> SE.put link_location >> SE.put link_text >> SE.put link_command >> SE.put link_render >> SE.put link_pos >> SE.put link_dim put LinkAnchor {..} = SE.putWord8 2 >> SE.put link_id >> SE.put link_linkeddocid >> SE.put link_location >> SE.put link_anchorid >> SE.put link_render >> SE.put link_pos >> SE.put link_dim get = do tag <- SE.getWord8 case tag of 0 -> Link <$> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get 1 -> LinkDocID <$> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get 2 -> LinkAnchor <$> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get <*> SE.get _ -> fail "err in Link parsing" data Anchor = Anchor { anchor_id :: ByteString, anchor_render :: ByteString, anchor_pos :: (Double, Double), anchor_dim :: !Dimension } deriving (Show, Eq, Ord) $(deriveJSON defaultOptions {fieldLabelModifier = drop 7} ''Anchor) instance SE.Serialize Anchor where put Anchor {..} = SE.put anchor_id >> SE.put anchor_render >> SE.put anchor_pos >> SE.put anchor_dim get = Anchor <$> SE.get <*> SE.get <*> SE.get <*> SE.get data Item = ItemStroke Stroke | ItemImage Image | ItemSVG SVG | ItemLink Link | ItemAnchor Anchor deriving (Show, Eq, Ord) $(deriveJSON defaultOptions ''Item) instance SE.Serialize Item where put (ItemStroke str) = SE.putWord8 0 >> SE.put str put (ItemImage img) = SE.putWord8 1 >> SE.put img put (ItemSVG svg) = SE.putWord8 2 >> SE.put svg put (ItemLink lnk) = SE.putWord8 3 >> SE.put lnk put (ItemAnchor anc) = SE.putWord8 4 >> SE.put anc get = do tag <- SE.getWord8 case tag of 0 -> ItemStroke <$> SE.get 1 -> ItemImage <$> SE.get 2 -> ItemSVG <$> SE.get 3 -> ItemLink <$> SE.get 4 -> ItemAnchor <$> SE.get _ -> fail "err in Item parsing" data Background = Background { bkg_type :: !ByteString, bkg_color :: !ByteString, bkg_style :: !ByteString } | BackgroundPdf { bkg_type :: ByteString, bkg_domain :: Maybe ByteString, bkg_filename :: Maybe ByteString, bkg_pageno :: Int } | BackgroundEmbedPdf { bkg_type :: ByteString, bkg_pageno :: Int } deriving (Show) $(deriveJSON defaultOptions {fieldLabelModifier = drop 4} ''Background) data Revision = Revision { _revmd5 :: !ByteString, _revtxt :: !ByteString } | RevisionInk { _revmd5 :: !ByteString, _revink :: [Stroke] } deriving (Show) $(deriveJSON defaultOptions {fieldLabelModifier = drop 1} ''Revision) newtype Layer = Layer {layer_items :: [Item]} deriving (Show) $(deriveJSON defaultOptions {fieldLabelModifier = drop 6} ''Layer) data Page = Page { page_dim :: !Dimension, page_bkg :: !Background, page_layers :: ![Layer] } deriving (Show) $(deriveJSON defaultOptions {fieldLabelModifier = drop 5} ''Page) data Hoodle = Hoodle { hoodle_id :: ByteString, hoodle_title :: !Title, hoodle_revisions :: [Revision], hoodle_embeddedpdf :: Maybe ByteString, hoodle_embeddedtext :: Maybe T.Text, hoodle_pages :: ![Page] } deriving (Show) $(deriveJSON defaultOptions {fieldLabelModifier = drop 7} ''Hoodle) getXYtuples :: Stroke -> [(Double, Double)] getXYtuples (Stroke _t _c _w d) = map (\(x :!: y) -> (x, y)) d getXYtuples (VWStroke _t _c d) = map ((,) <$> fst3 <*> snd3) d tool :: Lens' Stroke ByteString tool = lens stroke_tool (\f a -> f {stroke_tool = a}) color :: Lens' Stroke ByteString color = lens stroke_color (\f a -> f {stroke_color = a}) hoodleID :: Lens' Hoodle ByteString hoodleID = lens hoodle_id (\f a -> f {hoodle_id = a}) title :: Lens' Hoodle Title title = lens hoodle_title (\f a -> f {hoodle_title = a}) revisions :: Lens' Hoodle [Revision] revisions = lens hoodle_revisions (\f a -> f {hoodle_revisions = a}) revmd5 :: Lens' Revision ByteString revmd5 = lens _revmd5 (\f a -> f {_revmd5 = a}) embeddedPdf :: Lens' Hoodle (Maybe ByteString) embeddedPdf = lens hoodle_embeddedpdf (\f a -> f {hoodle_embeddedpdf = a}) embeddedText :: Lens' Hoodle (Maybe T.Text) embeddedText = lens hoodle_embeddedtext (\f a -> f {hoodle_embeddedtext = a}) pages :: Lens' Hoodle [Page] pages = lens hoodle_pages (\f a -> f {hoodle_pages = a}) dimension :: Lens' Page Dimension dimension = lens page_dim (\f a -> f {page_dim = a}) background :: Lens' Page Background background = lens page_bkg (\f a -> f {page_bkg = a}) layers :: Lens' Page [Layer] layers = lens page_layers (\f a -> f {page_layers = a}) items :: Lens' Layer [Item] items = lens layer_items (\f a -> f {layer_items = a}) emptyHoodle :: IO Hoodle emptyHoodle = do uuid <- nextRandom return $ Hoodle ((pack . show) uuid) "" [] Nothing Nothing [] emptyLayer :: Layer emptyLayer = Layer {layer_items = []} emptyStroke :: Stroke emptyStroke = Stroke "pen" "black" 1.4 [] defaultBackground :: Background defaultBackground = Background { bkg_type = "solid", bkg_color = "white", bkg_style = "lined" } defaultPage :: Page defaultPage = Page { page_dim = Dim 612.0 792.0, page_bkg = defaultBackground, page_layers = [emptyLayer] } defaultHoodle :: IO Hoodle defaultHoodle = set title "untitled" . set embeddedPdf Nothing . set pages [defaultPage] <$> emptyHoodle newPageFromOld :: Page -> Page newPageFromOld page = Page { page_dim = page_dim page, page_bkg = page_bkg page, page_layers = [emptyLayer] }
30cd97eabac5158b78e546a263efc7d63c9d42f185efda0d2ccac2dec81f7567
schemedoc/implementation-metadata
pixie.scm
(short-title "Pixie") (title "Pixie Scheme") (homepage-url "") (person "Jay Reynolds Freeman") (features)
null
https://raw.githubusercontent.com/schemedoc/implementation-metadata/6280d9c4c73833dc5bd1c9bef9b45be6ea5beb68/schemes/pixie.scm
scheme
(short-title "Pixie") (title "Pixie Scheme") (homepage-url "") (person "Jay Reynolds Freeman") (features)
b535e3759b2451c3bf711dea3d6006c115de5206a8288ca976a27de4ec289815
con-kitty/categorifier-c
RandomExpressions.hs
# LANGUAGE ApplicativeDo # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # - Regular tests : ( " test_codegen_small_exprs " , " -t 50 -i 1000 -m 1 " ) ( " test_codegen_little_exprs " , " -t 50 -i 1000 -m 2 " ) ( " test_codegen_medium_exprs " , " -t 40 -i 500 -m 6 " ) ( " test_codegen_large_exprs " , " -t 35 -i 500 -m 16 " ) ( " test_codegen_huge_exprs " , " -t 30 -i 500 -m 64 " ) - Long tests : ( " test_codegen_long_small_exprs " , " -t 1000 -i 10000 -m 1 " ) ( " test_codegen_long_little_exprs " , " -t 500 -i 10000 -m 2 " ) ( " test_codegen_long_medium_exprs " , " -t 100 -i 10000 -m 6 " ) ( " test_codegen_long_large_exprs " , " -t 50 -i 100000 -m 16 " ) - Regular tests: ("test_codegen_small_exprs", "-t 50 -i 1000 -m 1") ("test_codegen_little_exprs", "-t 50 -i 1000 -m 2") ("test_codegen_medium_exprs", "-t 40 -i 500 -m 6") ("test_codegen_large_exprs", "-t 35 -i 500 -m 16") ("test_codegen_huge_exprs", "-t 30 -i 500 -m 64") - Long tests: ("test_codegen_long_small_exprs", "-t 1000 -i 10000 -m 1") ("test_codegen_long_little_exprs", "-t 500 -i 10000 -m 2") ("test_codegen_long_medium_exprs", "-t 100 -i 10000 -m 6") ("test_codegen_long_large_exprs", "-t 50 -i 100000 -m 16") -} module Main ( main, ) where import qualified Categorifier.C.Hedgehog.Options as Options import qualified Categorifier.C.Hedgehog.Paths as Paths import qualified Categorifier.C.KGenGenerate.Test.Plugin as Plugin import Control.Applicative ((<**>)) import Control.Monad.Extra (join, when, whenJust) import Data.IORef (modifyIORef', newIORef, readIORef) import GHC.IO.Encoding (setLocaleEncoding, utf8) import qualified Hedgehog as H import Options.Applicative ( Parser, ParserInfo, auto, execParser, flag, fullDesc, header, help, helper, info, long, metavar, option, progDesc, short, value, ) import PyF (fmt) import System.Exit (exitFailure, exitSuccess) import System.IO (IO) import System.Time.Extra (offsetTime) data Options = Options { optionsMaxIOPerType :: Int, optionsNumInputRuns :: Int, optionsSubprocess :: Plugin.SubprocessConfig, optionsVerbose :: Plugin.QuietConfig, -- | If set, print progress after @x@ test cases. optionsShowProgress :: Maybe Int, optionsHedgehog :: Options.HedgehogOptions, optionsTestTmpDir :: Paths.TestTmpDirOptions } deriving (Eq, Ord, Show) parseOptions :: Parser Options parseOptions = do optionsMaxIOPerType <- option auto $ mconcat [ long "max-ios-per-type", short 'm', metavar "NUM", help "Maximum number of expression inputs and outputs of each type" ] optionsNumInputRuns <- option auto $ mconcat [ long "num-input-runs", short 'i', metavar "NUM", help "Number of input points to test for each expression" ] optionsSubprocess <- flag Plugin.OneProcess Plugin.Subprocess $ mconcat [ long "use-subprocess", short 'p', help "Run generated C code in a subprocess to allow shrinking on fatal errors" ] optionsVerbose <- flag Plugin.Quiet Plugin.Noisy $ mconcat [ long "verbose", short 'v', help "Print a lot of output along the way" ] optionsShowProgress <- option (Just <$> auto) $ mconcat [ long "show-progress", value Nothing, help "Show progress after x test cases" ] optionsHedgehog <- Options.parseHedgehogOptions optionsTestTmpDir <- Paths.parseTestTmpDirOptions pure Options {..} opts0 :: ParserInfo Options opts0 = info (parseOptions <**> helper) ( fullDesc <> progDesc desc <> header "hedgehog-plugin: randomized testing for the test code-generation system" ) where desc = [fmt| This program tests the code-generation system by generating random expressions, code-generating the corresponding C code, running inputs through both the C and the original Haskell and comparing the results. The randomized generation is done in a way that allows the expressions to be shrunk to minimal reproducible failure cases. The limiting factor for this program is basically peak memory consumption. As hedgehog generates larger and larger expressions, you're more likely to encounter an out-of-memory failure. All three input parameters correlate with increased memory consumption, so your best bet is probably to run some tests with many small expressions, some tests with only a few huge expressions and some tests with a few small expressions but many inputs. If you encounter a fatal error like SIGFPE, please re-run the test using the '--use-subprocess' flag to run generated C code in a subprocess whose failure can be analyzed. |] main :: IO () main = do setLocaleEncoding utf8 flags . opts <- execParser opts0 path <- Paths.computeTestTmpDir $ optionsTestTmpDir opts -- Run the tests. result <- testn opts path if result then exitSuccess else exitFailure where testn Options {optionsHedgehog = {..}, ..} pth = do putStrLn [fmt| Running {show optionsNumTestExprs} plugin-based tests on randomized expressions. Each expression will be run on {show optionsNumInputRuns} input points. Each expression may have up to {show optionsMaxIOPerType} input and output variables. |] counter <- newIORef 0 timeElapsed <- offsetTime testcaseCount <- newIORef @Int 0 let config = Plugin.PluginTestConfig { pluginTestQuiet = optionsVerbose, pluginTestSubprocess = optionsSubprocess, pluginTestTopDir = pth } afterTestCase = whenJust optionsShowProgress $ \x -> do cnt <- modifyIORef' testcaseCount (+ 1) *> readIORef testcaseCount when (cnt `mod` x == 0) $ do elapsed <- timeElapsed putStrLn [fmt|Finished {show cnt} out of {show optionsNumTestExprs} test cases. Time elapsed: {show elapsed}s|] property = H.withTests (fromIntegral optionsNumTestExprs) . H.withShrinks (fromIntegral optionsMaxShrinks) $ Plugin.pluginTest config counter optionsNumInputRuns optionsMaxIOPerType afterTestCase Options.checkRNG "Codegen test" hedgeopt property
null
https://raw.githubusercontent.com/con-kitty/categorifier-c/a34ff2603529b4da7ad6ffe681dad095f102d1b9/tests/random_expressions/RandomExpressions.hs
haskell
# LANGUAGE OverloadedStrings # | If set, print progress after @x@ test cases. use-subprocess' flag to run generated C code in a subprocess whose failure Run the tests.
# LANGUAGE ApplicativeDo # # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # - Regular tests : ( " test_codegen_small_exprs " , " -t 50 -i 1000 -m 1 " ) ( " test_codegen_little_exprs " , " -t 50 -i 1000 -m 2 " ) ( " test_codegen_medium_exprs " , " -t 40 -i 500 -m 6 " ) ( " test_codegen_large_exprs " , " -t 35 -i 500 -m 16 " ) ( " test_codegen_huge_exprs " , " -t 30 -i 500 -m 64 " ) - Long tests : ( " test_codegen_long_small_exprs " , " -t 1000 -i 10000 -m 1 " ) ( " test_codegen_long_little_exprs " , " -t 500 -i 10000 -m 2 " ) ( " test_codegen_long_medium_exprs " , " -t 100 -i 10000 -m 6 " ) ( " test_codegen_long_large_exprs " , " -t 50 -i 100000 -m 16 " ) - Regular tests: ("test_codegen_small_exprs", "-t 50 -i 1000 -m 1") ("test_codegen_little_exprs", "-t 50 -i 1000 -m 2") ("test_codegen_medium_exprs", "-t 40 -i 500 -m 6") ("test_codegen_large_exprs", "-t 35 -i 500 -m 16") ("test_codegen_huge_exprs", "-t 30 -i 500 -m 64") - Long tests: ("test_codegen_long_small_exprs", "-t 1000 -i 10000 -m 1") ("test_codegen_long_little_exprs", "-t 500 -i 10000 -m 2") ("test_codegen_long_medium_exprs", "-t 100 -i 10000 -m 6") ("test_codegen_long_large_exprs", "-t 50 -i 100000 -m 16") -} module Main ( main, ) where import qualified Categorifier.C.Hedgehog.Options as Options import qualified Categorifier.C.Hedgehog.Paths as Paths import qualified Categorifier.C.KGenGenerate.Test.Plugin as Plugin import Control.Applicative ((<**>)) import Control.Monad.Extra (join, when, whenJust) import Data.IORef (modifyIORef', newIORef, readIORef) import GHC.IO.Encoding (setLocaleEncoding, utf8) import qualified Hedgehog as H import Options.Applicative ( Parser, ParserInfo, auto, execParser, flag, fullDesc, header, help, helper, info, long, metavar, option, progDesc, short, value, ) import PyF (fmt) import System.Exit (exitFailure, exitSuccess) import System.IO (IO) import System.Time.Extra (offsetTime) data Options = Options { optionsMaxIOPerType :: Int, optionsNumInputRuns :: Int, optionsSubprocess :: Plugin.SubprocessConfig, optionsVerbose :: Plugin.QuietConfig, optionsShowProgress :: Maybe Int, optionsHedgehog :: Options.HedgehogOptions, optionsTestTmpDir :: Paths.TestTmpDirOptions } deriving (Eq, Ord, Show) parseOptions :: Parser Options parseOptions = do optionsMaxIOPerType <- option auto $ mconcat [ long "max-ios-per-type", short 'm', metavar "NUM", help "Maximum number of expression inputs and outputs of each type" ] optionsNumInputRuns <- option auto $ mconcat [ long "num-input-runs", short 'i', metavar "NUM", help "Number of input points to test for each expression" ] optionsSubprocess <- flag Plugin.OneProcess Plugin.Subprocess $ mconcat [ long "use-subprocess", short 'p', help "Run generated C code in a subprocess to allow shrinking on fatal errors" ] optionsVerbose <- flag Plugin.Quiet Plugin.Noisy $ mconcat [ long "verbose", short 'v', help "Print a lot of output along the way" ] optionsShowProgress <- option (Just <$> auto) $ mconcat [ long "show-progress", value Nothing, help "Show progress after x test cases" ] optionsHedgehog <- Options.parseHedgehogOptions optionsTestTmpDir <- Paths.parseTestTmpDirOptions pure Options {..} opts0 :: ParserInfo Options opts0 = info (parseOptions <**> helper) ( fullDesc <> progDesc desc <> header "hedgehog-plugin: randomized testing for the test code-generation system" ) where desc = [fmt| This program tests the code-generation system by generating random expressions, code-generating the corresponding C code, running inputs through both the C and the original Haskell and comparing the results. The randomized generation is done in a way that allows the expressions to be shrunk to minimal reproducible failure cases. The limiting factor for this program is basically peak memory consumption. As hedgehog generates larger and larger expressions, you're more likely to encounter an out-of-memory failure. All three input parameters correlate with increased memory consumption, so your best bet is probably to run some tests with many small expressions, some tests with only a few huge expressions and some tests with a few small expressions but many inputs. If you encounter a fatal error like SIGFPE, please re-run the test using the can be analyzed. |] main :: IO () main = do setLocaleEncoding utf8 flags . opts <- execParser opts0 path <- Paths.computeTestTmpDir $ optionsTestTmpDir opts result <- testn opts path if result then exitSuccess else exitFailure where testn Options {optionsHedgehog = {..}, ..} pth = do putStrLn [fmt| Running {show optionsNumTestExprs} plugin-based tests on randomized expressions. Each expression will be run on {show optionsNumInputRuns} input points. Each expression may have up to {show optionsMaxIOPerType} input and output variables. |] counter <- newIORef 0 timeElapsed <- offsetTime testcaseCount <- newIORef @Int 0 let config = Plugin.PluginTestConfig { pluginTestQuiet = optionsVerbose, pluginTestSubprocess = optionsSubprocess, pluginTestTopDir = pth } afterTestCase = whenJust optionsShowProgress $ \x -> do cnt <- modifyIORef' testcaseCount (+ 1) *> readIORef testcaseCount when (cnt `mod` x == 0) $ do elapsed <- timeElapsed putStrLn [fmt|Finished {show cnt} out of {show optionsNumTestExprs} test cases. Time elapsed: {show elapsed}s|] property = H.withTests (fromIntegral optionsNumTestExprs) . H.withShrinks (fromIntegral optionsMaxShrinks) $ Plugin.pluginTest config counter optionsNumInputRuns optionsMaxIOPerType afterTestCase Options.checkRNG "Codegen test" hedgeopt property
7f105f0820bf7864d6268d56fadf493f5fcddeba9709965c47dc64960f427c93
conal/functor-combo
MemoTrie.hs
# LANGUAGE TypeOperators , TypeFamilies , UndecidableInstances , CPP # #-} # OPTIONS_GHC -Wall # # OPTIONS_GHC -fno - warn - unused - binds -fno - warn - unused - imports # ---------------------------------------------------------------------- -- | Module : FunctorCombo . MemoTrie Copyright : ( c ) Conal Elliott 2010 -- License : BSD3 -- -- Maintainer : -- Stability : experimental -- -- Functor-based memo tries -- ---------------------------------------------------------------------- module FunctorCombo.MemoTrie ( HasTrie(..),memo,memo2,memo3 ) where I think this module has split into StrictMemo and NonstrictMemo #define NonstrictMemo import Control.Arrow (first) import Control.Applicative ((<$>)) import qualified Data.IntTrie as IT -- data-inttrie import Data.Tree TypeCompose #ifdef NonstrictMemo import Data.Lub #endif import FunctorCombo.Functor import FunctorCombo.Regular {-------------------------------------------------------------------- Misc --------------------------------------------------------------------} type Unop a = a -> a bool :: a -> a -> Bool -> a bool t e b = if b then t else e {-------------------------------------------------------------------- Class --------------------------------------------------------------------} infixr 0 :->: #ifdef NonstrictMemo data Trie k v = Trie v (STrie k v) type k :->: v = Trie k v -- Bottom bottom :: a bottom = error "MemoTrie: evaluated bottom. Oops!" -- | Create the trie for the entire domain of a function trie :: HasLub(v) => HasTrie k => (k -> v) -> (k :->: v) trie f = Trie (f bottom) (sTrie f) -- | Convert k trie to k function, i.e., access k field of the trie untrie :: HasLub(v) => HasTrie k => (k :->: v) -> (k -> v) untrie (Trie b t) = const b `lub` sUntrie t #else type Trie k = STrie k type k :->: v = k :-> v -- Bogus HasLub constraint #define HasLub(v) () trie :: HasTrie k => (k -> v) -> (k :->: v) trie = sTrie untrie :: HasTrie k => (k :->: v) -> (k -> v) untrie = sUntrie #endif -- | Memo trie from k to v type k :-> v = STrie k v -- | Domain types with associated memo tries class HasTrie k where -- | Representation of trie with domain type @a@ type STrie k :: * -> * -- | Create the trie for the entire domain of a function sTrie :: HasLub(v) => (k -> v) -> (k :-> v) -- | Convert k trie to k function, i.e., access k field of the trie sUntrie :: HasLub(v) => (k :-> v) -> (k -> v) -- -- | List the trie elements. Order of keys (@:: k@) is always the same. -- enumerate :: HasLub(v) => (k :-> v) -> [(k,v)] -- -- | Domain elements of a trie -- domain :: HasTrie a => [a] domain = map ( enumerate ( trie ( const oops ) ) ) -- where -- oops = error "Data.MemoTrie.domain: range element evaluated." -- TODO: what about enumerate and strict/nonstrict? {-------------------------------------------------------------------- Memo functions --------------------------------------------------------------------} -- | Trie-based function memoizer memo :: HasLub(v) => HasTrie k => Unop (k -> v) memo = untrie . trie | Memoize a binary function , on its first argument and then on its second . Take care to exploit any partial evaluation . memo2 :: HasLub(a) => (HasTrie s,HasTrie t) => Unop (s -> t -> a) -- | Memoize a ternary function on successive arguments. Take care to -- exploit any partial evaluation. memo3 :: HasLub(a) => (HasTrie r,HasTrie s,HasTrie t) => Unop (r -> s -> t -> a) | Lift a memoizer to work with one more argument . mup :: HasLub(c) => HasTrie t => (b -> c) -> (t -> b) -> (t -> c) mup mem f = memo (mem . f) memo2 = mup memo memo3 = mup memo2 {-------------------------------------------------------------------- Instances --------------------------------------------------------------------} instance HasTrie () where type STrie () = Id sTrie f = Id (f ()) sUntrie (Id v) = const v -- enumerate (Id a) = [((),a)] instance (HasTrie a, HasTrie b) => HasTrie (Either a b) where type STrie (Either a b) = Trie a :*: Trie b sTrie f = trie (f . Left) :*: trie (f . Right) sUntrie (ta :*: tb) = untrie ta `either` untrie tb -- enumerate (ta :*: tb) = enum' Left ta `weave` enum' Right tb -- enum' :: HasLub(b) => HasTrie a => (a -> a') -> (a :->: b) -> [(a', b)] -- enum' f = (fmap.first) f . enumerate -- weave :: [a] -> [a] -> [a] -- [] `weave` as = as -- as `weave` [] = as -- (a:as) `weave` bs = a : (bs `weave` as) -- To do: rethink enumerate and come back to it. How might enumeration work in the presence of nonstrict memo tries ? Maybe lub the -- approximation into each of the values enumerated from the strict memo tries. -- Would it help any?? instance (HasTrie a, HasTrie b) => HasTrie (a , b) where type STrie (a , b) = Trie a :. Trie b sTrie f = O (trie (trie . curry f)) sUntrie (O tt) = uncurry (untrie . untrie tt) -- enumerate (O tt) = -- [ ((a,b),x) | (a,t) <- enumerate tt , (b,x) <- enumerate t ] -- Oops: -- Could not deduce ( HasLub ( Trie b v ) ) from the context ( HasLub v ) -- arising from a use of `trie' -- Could not deduce ( HasLub ( Trie b v ) ) from the context ( HasLub v ) -- arising from a use of `untrie' -- Eep. How to fix this one? # define HasTrieIsomorph(Context , Type , , toIso , fromIso ) \ instance Context = > HasTrie ( Type ) where { \ type ( Type ) = Trie ( ) ; \ sTrie f = ( f . ( fromIso ) ) ; \ sUntrie t = sUntrie t . ( toIso ) ; \ enumerate = ( result.fmap.first ) ( fromIso ) enumerate ; \ } HasTrieIsomorph ( ( ) , , Either ( ) ( ) , bool ( Left ( ) ) ( Right ( ) ) , either ( \ ( ) - > True ) ( \ ( ) - > False ) ) HasTrieIsomorph((HasTrie a , HasTrie b , HasTrie c ) , ( a , b , c ) , ( ( a , b),c ) , \ ( a , b , c ) - > ( ( a , b),c ) , \ ( ( a , b),c ) - > ( a , b , c ) ) HasTrieIsomorph((HasTrie a , HasTrie b , HasTrie c , HasTrie d ) , ( a , b , c , d ) , ( ( a , b , c),d ) , \ ( a , b , c , d ) - > ( ( a , b , c),d ) , \ ( ( a , b , c),d ) - > ( a , b , c , d ) ) -- As well as the functor combinators themselves HasTrieIsomorph ( , Const x a , x , , Const ) HasTrieIsomorph ( HasTrie a , I d a , a , unId , I d ) HasTrieIsomorph ( ( HasTrie ( f a ) , HasTrie ( g a ) ) , ( f :* : g ) a , ( f a , g a ) , \ ( fa :* : ) - > ( fa , ) , \ ( fa , ) - > ( fa :* : ) ) HasTrieIsomorph ( ( HasTrie ( f a ) , HasTrie ( g a ) ) , ( f : + : g ) a , Either ( f a ) ( g a ) , eitherF Left Right , either ) HasTrieIsomorph ( HasTrie ( g ( f a ) ) , ( g : . f ) a , g ( f a ) , unO , O ) -- newtype a v = ListTrie ( PF [ a ] [ a ] :-> v ) -- instance HasTrie a = > HasTrie [ a ] where -- type [ a ] = ListTrie a -- f = ( trie ( f . wrap ) ) -- sUntrie ( ListTrie t ) = sUntrie t . unwrap -- enumerate ( ListTrie t ) = ( result.fmap.first ) wrap enumerate $ t -- HasTrieIsomorph ( HasTrie ( PF ( [ a ] ) ( [ a ] ) :-> : v ) -- , a v , PF ( [ a ] ) ( [ a ] ) :-> : v -- , \ ( ListTrie w ) - > w , ) -- Works . Now abstract into a macro # define HasTrieRegular(Context , Type , TrieType , TrieCon ) \ newtype TrieType v = TrieCon ( PF ( Type ) ( Type ) :-> : v ) ; \ instance Context = > HasTrie ( Type ) where { \ type ( Type ) = TrieType ; \ sTrie f = TrieCon ( ( f . wrap ) ) ; \ sUntrie ( TrieCon t ) = sUntrie t . unwrap ; \ enumerate ( TrieCon t ) = ( result.fmap.first ) wrap enumerate t ; \ } ; \ HasTrieIsomorph ( HasTrie ( PF ( Type ) ( Type ) :-> : v ) \ , TrieType v , PF ( Type ) ( Type ) :-> : v \ , \ ( TrieCon w ) - > w , TrieCon ) -- For instance , -- HasTrieRegular(HasTrie a , [ a ] , ListTrie a , ListTrie ) -- HasTrieRegular(HasTrie a , Tree a , TreeTrie a , ) -- Simplify a bit with a macro for unary regular types . -- Make similar defs for binary etc as needed . # define HasTrieRegular1(TypeCon , TrieCon ) \ HasTrieRegular(HasTrie a , a , TrieCon a , TrieCon ) ( [ ] , ListTrie ) HasTrieRegular1(Tree , TreeTrie ) -- HasTrieIsomorph(Context , Type , , toIso , fromIso ) -- HasTrieIsomorph ( HasTrie ( PF [ a ] [ a ] :-> : v ) -- , a v , PF [ a ] [ a ] :-> : v -- , \ ( ListTrie w ) - > w , ) enumerateEnum : : ( , , ) = > ( k :-> : v ) - > [ ( k , v ) ] enumerateEnum t = [ ( k , f k ) | k < - [ 0 .. ] ` weave ` [ -1 , -2 .. ] ] where f = untrie t # define HasTrieIntegral(Type ) \ instance HasTrie Type where { \ type STrie Type = IT.IntTrie ; \ = ( < $ > IT.identity ) ; \ sUntrie = IT.apply ; \ enumerate = enumerateEnum ; \ } HasTrieIntegral(Int ) HasTrieIntegral(Integer ) -- higher - order functions HasTrieIsomorph((HasTrie a , ( a :-> : b ) ) , a - > b , a :-> : b , trie , ) { - { -------------------------------------------------------------------- Testing ------------------------------------------------------------------- #define HasTrieIsomorph(Context,Type,IsoType,toIso,fromIso) \ instance Context => HasTrie (Type) where { \ type STrie (Type) = Trie (IsoType); \ sTrie f = sTrie (f . (fromIso)); \ sUntrie t = sUntrie t . (toIso); \ enumerate = (result.fmap.first) (fromIso) enumerate; \ } HasTrieIsomorph( (), Bool, Either () () , bool (Left ()) (Right ()) , either (\ () -> True) (\ () -> False)) HasTrieIsomorph((HasTrie a, HasTrie b, HasTrie c), (a,b,c), ((a,b),c) , \ (a,b,c) -> ((a,b),c), \ ((a,b),c) -> (a,b,c)) HasTrieIsomorph((HasTrie a, HasTrie b, HasTrie c, HasTrie d) , (a,b,c,d), ((a,b,c),d) , \ (a,b,c,d) -> ((a,b,c),d), \ ((a,b,c),d) -> (a,b,c,d)) -- As well as the functor combinators themselves HasTrieIsomorph( HasTrie x, Const x a, x, getConst, Const ) HasTrieIsomorph( HasTrie a, Id a, a, unId, Id ) HasTrieIsomorph( (HasTrie (f a), HasTrie (g a)) , (f :*: g) a, (f a,g a) , \ (fa :*: ga) -> (fa,ga), \ (fa,ga) -> (fa :*: ga) ) HasTrieIsomorph( (HasTrie (f a), HasTrie (g a)) , (f :+: g) a, Either (f a) (g a) , eitherF Left Right, either InL InR ) HasTrieIsomorph( HasTrie (g (f a)) , (g :. f) a, g (f a) , unO, O ) -- newtype ListTrie a v = ListTrie (PF [a] [a] :-> v) -- instance HasTrie a => HasTrie [a] where -- type STrie [a] = ListTrie a -- sTrie f = ListTrie (trie (f . wrap)) -- sUntrie (ListTrie t) = sUntrie t . unwrap -- enumerate (ListTrie t) = (result.fmap.first) wrap enumerate $ t -- HasTrieIsomorph( HasTrie (PF ([a]) ([a]) :->: v) -- , ListTrie a v, PF ([a]) ([a]) :->: v -- , \ (ListTrie w) -> w, ListTrie ) -- Works. Now abstract into a macro #define HasTrieRegular(Context,Type,TrieType,TrieCon) \ newtype TrieType v = TrieCon (PF (Type) (Type) :->: v); \ instance Context => HasTrie (Type) where { \ type STrie (Type) = TrieType; \ sTrie f = TrieCon (sTrie (f . wrap)); \ sUntrie (TrieCon t) = sUntrie t . unwrap; \ enumerate (TrieCon t) = (result.fmap.first) wrap enumerate t; \ }; \ HasTrieIsomorph( HasTrie (PF (Type) (Type) :->: v) \ , TrieType v, PF (Type) (Type) :->: v \ , \ (TrieCon w) -> w, TrieCon ) -- For instance, -- HasTrieRegular(HasTrie a, [a] , ListTrie a, ListTrie) -- HasTrieRegular(HasTrie a, Tree a, TreeTrie a, TreeTrie) -- Simplify a bit with a macro for unary regular types. -- Make similar defs for binary etc as needed. #define HasTrieRegular1(TypeCon,TrieCon) \ HasTrieRegular(HasTrie a, TypeCon a, TrieCon a, TrieCon) HasTrieRegular1([] , ListTrie) HasTrieRegular1(Tree, TreeTrie) -- HasTrieIsomorph(Context,Type,IsoType,toIso,fromIso) -- HasTrieIsomorph( HasTrie (PF [a] [a] :->: v) -- , ListTrie a v, PF [a] [a] :->: v -- , \ (ListTrie w) -> w, ListTrie ) enumerateEnum :: (Enum k, Num k, HasTrie k) => (k :->: v) -> [(k,v)] enumerateEnum t = [(k, f k) | k <- [0 ..] `weave` [-1, -2 ..]] where f = untrie t #define HasTrieIntegral(Type) \ instance HasTrie Type where { \ type STrie Type = IT.IntTrie; \ sTrie = (<$> IT.identity); \ sUntrie = IT.apply; \ enumerate = enumerateEnum; \ } HasTrieIntegral(Int) HasTrieIntegral(Integer) -- Memoizing higher-order functions HasTrieIsomorph((HasTrie a, HasTrie (a :->: b)), a -> b, a :->: b, trie, untrie) {- {-------------------------------------------------------------------- Testing --------------------------------------------------------------------} fib :: Integer -> Integer fib m = mfib m where mfib = memo fib' fib' 0 = 0 fib' 1 = 1 fib' n = mfib (n-1) + mfib (n-2) The eta - redex in fib is important to prevent a CAF . -} ft1 :: (Bool -> a) -> [a] ft1 f = [f False, f True] f1 :: Bool -> Int f1 False = 0 f1 True = 1 trie1a :: HasTrie a => (Bool -> a) :->: [a] trie1a = trie ft1 trie1b :: HasTrie a => (Bool :->: a) :->: [a] trie1b = trie1a trie1c :: HasTrie a => (Either () () :->: a) :->: [a] trie1c = trie1a trie1d :: HasTrie a => ((Trie () :*: Trie ()) a) :->: [a] trie1d = trie1a trie1e :: HasTrie a => (Trie () a, Trie () a) :->: [a] trie1e = trie1a trie1f :: HasTrie a => (() :->: a, () :->: a) :->: [a] trie1f = trie1a trie1g :: HasTrie a => (a, a) :->: [a] trie1g = trie1a trie1h :: HasTrie a => (Trie a :. Trie a) [a] trie1h = trie1a trie1i :: HasTrie a => a :->: a :->: [a] trie1i = unO trie1a ft2 :: ([Bool] -> Int) -> Int ft2 f = f (alts 15) alts :: Int -> [Bool] alts n = take n (cycle [True,False]) f2 :: [Bool] -> Int f2 = length . filter id Memoization fails : * FunctorCombo . ft2 f2 8 * FunctorCombo . MemoTrie > memo ft2 f2 -- ... (hang forever) ... -- Would nonstrict memoization work? <-memoization/> f3 :: Bool -> Integer f3 = const 3 * FunctorCombo . f3 undefined 3 * FunctorCombo . MemoTrie > memo f3 undefined -- *** Exception: Prelude.undefined f4 :: () -> Integer f4 = const 4 * FunctorCombo . f4 undefined 4 * FunctorCombo . MemoTrie > memo f4 undefined 4 f5 :: ((),()) -> Integer f5 = const 5 * FunctorCombo . f5 undefined 5 * FunctorCombo . MemoTrie > memo f5 undefined 5 f6 :: Either () () -> Integer f6 = const 6 * FunctorCombo . f6 undefined 6 * FunctorCombo . MemoTrie > memo f6 undefined -- *** Exception: Prelude.undefined -- Aha! t6 :: Either () () :-> Integer t6 = trie f6 * FunctorCombo . MemoTrie > t6 -- Id 6 :*: Id 6 -}
null
https://raw.githubusercontent.com/conal/functor-combo/e83af37cc2cc3b9a88dae032e19c731cf7b7b63d/src/FunctorCombo/MemoTrie.hs
haskell
-------------------------------------------------------------------- | License : BSD3 Maintainer : Stability : experimental Functor-based memo tries -------------------------------------------------------------------- data-inttrie ------------------------------------------------------------------- Misc ------------------------------------------------------------------- ------------------------------------------------------------------- Class ------------------------------------------------------------------- Bottom | Create the trie for the entire domain of a function | Convert k trie to k function, i.e., access k field of the trie Bogus HasLub constraint | Memo trie from k to v | Domain types with associated memo tries | Representation of trie with domain type @a@ | Create the trie for the entire domain of a function | Convert k trie to k function, i.e., access k field of the trie -- | List the trie elements. Order of keys (@:: k@) is always the same. enumerate :: HasLub(v) => (k :-> v) -> [(k,v)] -- | Domain elements of a trie domain :: HasTrie a => [a] where oops = error "Data.MemoTrie.domain: range element evaluated." TODO: what about enumerate and strict/nonstrict? ------------------------------------------------------------------- Memo functions ------------------------------------------------------------------- | Trie-based function memoizer | Memoize a ternary function on successive arguments. Take care to exploit any partial evaluation. ------------------------------------------------------------------- Instances ------------------------------------------------------------------- enumerate (Id a) = [((),a)] enumerate (ta :*: tb) = enum' Left ta `weave` enum' Right tb enum' :: HasLub(b) => HasTrie a => (a -> a') -> (a :->: b) -> [(a', b)] enum' f = (fmap.first) f . enumerate weave :: [a] -> [a] -> [a] [] `weave` as = as as `weave` [] = as (a:as) `weave` bs = a : (bs `weave` as) To do: rethink enumerate and come back to it. How might enumeration approximation into each of the values enumerated from the strict memo tries. Would it help any?? enumerate (O tt) = [ ((a,b),x) | (a,t) <- enumerate tt , (b,x) <- enumerate t ] Oops: arising from a use of `trie' arising from a use of `untrie' Eep. How to fix this one? As well as the functor combinators themselves newtype a v = ListTrie ( PF [ a ] [ a ] :-> v ) instance HasTrie a = > HasTrie [ a ] where type [ a ] = ListTrie a f = ( trie ( f . wrap ) ) sUntrie ( ListTrie t ) = sUntrie t . unwrap enumerate ( ListTrie t ) = ( result.fmap.first ) wrap enumerate $ t HasTrieIsomorph ( HasTrie ( PF ( [ a ] ) ( [ a ] ) :-> : v ) , a v , PF ( [ a ] ) ( [ a ] ) :-> : v , \ ( ListTrie w ) - > w , ) Works . Now abstract into a macro For instance , HasTrieRegular(HasTrie a , [ a ] , ListTrie a , ListTrie ) HasTrieRegular(HasTrie a , Tree a , TreeTrie a , ) Simplify a bit with a macro for unary regular types . Make similar defs for binary etc as needed . HasTrieIsomorph(Context , Type , , toIso , fromIso ) HasTrieIsomorph ( HasTrie ( PF [ a ] [ a ] :-> : v ) , a v , PF [ a ] [ a ] :-> : v , \ ( ListTrie w ) - > w , ) higher - order functions ------------------------------------------------------------------ ----------------------------------------------------------------- As well as the functor combinators themselves newtype ListTrie a v = ListTrie (PF [a] [a] :-> v) instance HasTrie a => HasTrie [a] where type STrie [a] = ListTrie a sTrie f = ListTrie (trie (f . wrap)) sUntrie (ListTrie t) = sUntrie t . unwrap enumerate (ListTrie t) = (result.fmap.first) wrap enumerate $ t HasTrieIsomorph( HasTrie (PF ([a]) ([a]) :->: v) , ListTrie a v, PF ([a]) ([a]) :->: v , \ (ListTrie w) -> w, ListTrie ) Works. Now abstract into a macro For instance, HasTrieRegular(HasTrie a, [a] , ListTrie a, ListTrie) HasTrieRegular(HasTrie a, Tree a, TreeTrie a, TreeTrie) Simplify a bit with a macro for unary regular types. Make similar defs for binary etc as needed. HasTrieIsomorph(Context,Type,IsoType,toIso,fromIso) HasTrieIsomorph( HasTrie (PF [a] [a] :->: v) , ListTrie a v, PF [a] [a] :->: v , \ (ListTrie w) -> w, ListTrie ) Memoizing higher-order functions {-------------------------------------------------------------------- Testing ------------------------------------------------------------------- ... (hang forever) ... Would nonstrict memoization work? <-memoization/> *** Exception: Prelude.undefined *** Exception: Prelude.undefined Aha! Id 6 :*: Id 6
# LANGUAGE TypeOperators , TypeFamilies , UndecidableInstances , CPP # #-} # OPTIONS_GHC -Wall # # OPTIONS_GHC -fno - warn - unused - binds -fno - warn - unused - imports # Module : FunctorCombo . MemoTrie Copyright : ( c ) Conal Elliott 2010 module FunctorCombo.MemoTrie ( HasTrie(..),memo,memo2,memo3 ) where I think this module has split into StrictMemo and NonstrictMemo #define NonstrictMemo import Control.Arrow (first) import Control.Applicative ((<$>)) import Data.Tree TypeCompose #ifdef NonstrictMemo import Data.Lub #endif import FunctorCombo.Functor import FunctorCombo.Regular type Unop a = a -> a bool :: a -> a -> Bool -> a bool t e b = if b then t else e infixr 0 :->: #ifdef NonstrictMemo data Trie k v = Trie v (STrie k v) type k :->: v = Trie k v bottom :: a bottom = error "MemoTrie: evaluated bottom. Oops!" trie :: HasLub(v) => HasTrie k => (k -> v) -> (k :->: v) trie f = Trie (f bottom) (sTrie f) untrie :: HasLub(v) => HasTrie k => (k :->: v) -> (k -> v) untrie (Trie b t) = const b `lub` sUntrie t #else type Trie k = STrie k type k :->: v = k :-> v #define HasLub(v) () trie :: HasTrie k => (k -> v) -> (k :->: v) trie = sTrie untrie :: HasTrie k => (k :->: v) -> (k -> v) untrie = sUntrie #endif type k :-> v = STrie k v class HasTrie k where type STrie k :: * -> * sTrie :: HasLub(v) => (k -> v) -> (k :-> v) sUntrie :: HasLub(v) => (k :-> v) -> (k -> v) domain = map ( enumerate ( trie ( const oops ) ) ) memo :: HasLub(v) => HasTrie k => Unop (k -> v) memo = untrie . trie | Memoize a binary function , on its first argument and then on its second . Take care to exploit any partial evaluation . memo2 :: HasLub(a) => (HasTrie s,HasTrie t) => Unop (s -> t -> a) memo3 :: HasLub(a) => (HasTrie r,HasTrie s,HasTrie t) => Unop (r -> s -> t -> a) | Lift a memoizer to work with one more argument . mup :: HasLub(c) => HasTrie t => (b -> c) -> (t -> b) -> (t -> c) mup mem f = memo (mem . f) memo2 = mup memo memo3 = mup memo2 instance HasTrie () where type STrie () = Id sTrie f = Id (f ()) sUntrie (Id v) = const v instance (HasTrie a, HasTrie b) => HasTrie (Either a b) where type STrie (Either a b) = Trie a :*: Trie b sTrie f = trie (f . Left) :*: trie (f . Right) sUntrie (ta :*: tb) = untrie ta `either` untrie tb work in the presence of nonstrict memo tries ? Maybe lub the instance (HasTrie a, HasTrie b) => HasTrie (a , b) where type STrie (a , b) = Trie a :. Trie b sTrie f = O (trie (trie . curry f)) sUntrie (O tt) = uncurry (untrie . untrie tt) Could not deduce ( HasLub ( Trie b v ) ) from the context ( HasLub v ) Could not deduce ( HasLub ( Trie b v ) ) from the context ( HasLub v ) # define HasTrieIsomorph(Context , Type , , toIso , fromIso ) \ instance Context = > HasTrie ( Type ) where { \ type ( Type ) = Trie ( ) ; \ sTrie f = ( f . ( fromIso ) ) ; \ sUntrie t = sUntrie t . ( toIso ) ; \ enumerate = ( result.fmap.first ) ( fromIso ) enumerate ; \ } HasTrieIsomorph ( ( ) , , Either ( ) ( ) , bool ( Left ( ) ) ( Right ( ) ) , either ( \ ( ) - > True ) ( \ ( ) - > False ) ) HasTrieIsomorph((HasTrie a , HasTrie b , HasTrie c ) , ( a , b , c ) , ( ( a , b),c ) , \ ( a , b , c ) - > ( ( a , b),c ) , \ ( ( a , b),c ) - > ( a , b , c ) ) HasTrieIsomorph((HasTrie a , HasTrie b , HasTrie c , HasTrie d ) , ( a , b , c , d ) , ( ( a , b , c),d ) , \ ( a , b , c , d ) - > ( ( a , b , c),d ) , \ ( ( a , b , c),d ) - > ( a , b , c , d ) ) HasTrieIsomorph ( , Const x a , x , , Const ) HasTrieIsomorph ( HasTrie a , I d a , a , unId , I d ) HasTrieIsomorph ( ( HasTrie ( f a ) , HasTrie ( g a ) ) , ( f :* : g ) a , ( f a , g a ) , \ ( fa :* : ) - > ( fa , ) , \ ( fa , ) - > ( fa :* : ) ) HasTrieIsomorph ( ( HasTrie ( f a ) , HasTrie ( g a ) ) , ( f : + : g ) a , Either ( f a ) ( g a ) , eitherF Left Right , either ) HasTrieIsomorph ( HasTrie ( g ( f a ) ) , ( g : . f ) a , g ( f a ) , unO , O ) # define HasTrieRegular(Context , Type , TrieType , TrieCon ) \ newtype TrieType v = TrieCon ( PF ( Type ) ( Type ) :-> : v ) ; \ instance Context = > HasTrie ( Type ) where { \ type ( Type ) = TrieType ; \ sTrie f = TrieCon ( ( f . wrap ) ) ; \ sUntrie ( TrieCon t ) = sUntrie t . unwrap ; \ enumerate ( TrieCon t ) = ( result.fmap.first ) wrap enumerate t ; \ } ; \ HasTrieIsomorph ( HasTrie ( PF ( Type ) ( Type ) :-> : v ) \ , TrieType v , PF ( Type ) ( Type ) :-> : v \ , \ ( TrieCon w ) - > w , TrieCon ) # define HasTrieRegular1(TypeCon , TrieCon ) \ HasTrieRegular(HasTrie a , a , TrieCon a , TrieCon ) ( [ ] , ListTrie ) HasTrieRegular1(Tree , TreeTrie ) enumerateEnum : : ( , , ) = > ( k :-> : v ) - > [ ( k , v ) ] enumerateEnum t = [ ( k , f k ) | k < - [ 0 .. ] ` weave ` [ -1 , -2 .. ] ] where f = untrie t # define HasTrieIntegral(Type ) \ instance HasTrie Type where { \ type STrie Type = IT.IntTrie ; \ = ( < $ > IT.identity ) ; \ sUntrie = IT.apply ; \ enumerate = enumerateEnum ; \ } HasTrieIntegral(Int ) HasTrieIntegral(Integer ) HasTrieIsomorph((HasTrie a , ( a :-> : b ) ) , a - > b , a :-> : b , trie , ) { - Testing #define HasTrieIsomorph(Context,Type,IsoType,toIso,fromIso) \ instance Context => HasTrie (Type) where { \ type STrie (Type) = Trie (IsoType); \ sTrie f = sTrie (f . (fromIso)); \ sUntrie t = sUntrie t . (toIso); \ enumerate = (result.fmap.first) (fromIso) enumerate; \ } HasTrieIsomorph( (), Bool, Either () () , bool (Left ()) (Right ()) , either (\ () -> True) (\ () -> False)) HasTrieIsomorph((HasTrie a, HasTrie b, HasTrie c), (a,b,c), ((a,b),c) , \ (a,b,c) -> ((a,b),c), \ ((a,b),c) -> (a,b,c)) HasTrieIsomorph((HasTrie a, HasTrie b, HasTrie c, HasTrie d) , (a,b,c,d), ((a,b,c),d) , \ (a,b,c,d) -> ((a,b,c),d), \ ((a,b,c),d) -> (a,b,c,d)) HasTrieIsomorph( HasTrie x, Const x a, x, getConst, Const ) HasTrieIsomorph( HasTrie a, Id a, a, unId, Id ) HasTrieIsomorph( (HasTrie (f a), HasTrie (g a)) , (f :*: g) a, (f a,g a) , \ (fa :*: ga) -> (fa,ga), \ (fa,ga) -> (fa :*: ga) ) HasTrieIsomorph( (HasTrie (f a), HasTrie (g a)) , (f :+: g) a, Either (f a) (g a) , eitherF Left Right, either InL InR ) HasTrieIsomorph( HasTrie (g (f a)) , (g :. f) a, g (f a) , unO, O ) #define HasTrieRegular(Context,Type,TrieType,TrieCon) \ newtype TrieType v = TrieCon (PF (Type) (Type) :->: v); \ instance Context => HasTrie (Type) where { \ type STrie (Type) = TrieType; \ sTrie f = TrieCon (sTrie (f . wrap)); \ sUntrie (TrieCon t) = sUntrie t . unwrap; \ enumerate (TrieCon t) = (result.fmap.first) wrap enumerate t; \ }; \ HasTrieIsomorph( HasTrie (PF (Type) (Type) :->: v) \ , TrieType v, PF (Type) (Type) :->: v \ , \ (TrieCon w) -> w, TrieCon ) #define HasTrieRegular1(TypeCon,TrieCon) \ HasTrieRegular(HasTrie a, TypeCon a, TrieCon a, TrieCon) HasTrieRegular1([] , ListTrie) HasTrieRegular1(Tree, TreeTrie) enumerateEnum :: (Enum k, Num k, HasTrie k) => (k :->: v) -> [(k,v)] enumerateEnum t = [(k, f k) | k <- [0 ..] `weave` [-1, -2 ..]] where f = untrie t #define HasTrieIntegral(Type) \ instance HasTrie Type where { \ type STrie Type = IT.IntTrie; \ sTrie = (<$> IT.identity); \ sUntrie = IT.apply; \ enumerate = enumerateEnum; \ } HasTrieIntegral(Int) HasTrieIntegral(Integer) HasTrieIsomorph((HasTrie a, HasTrie (a :->: b)), a -> b, a :->: b, trie, untrie) fib :: Integer -> Integer fib m = mfib m where mfib = memo fib' fib' 0 = 0 fib' 1 = 1 fib' n = mfib (n-1) + mfib (n-2) The eta - redex in fib is important to prevent a CAF . -} ft1 :: (Bool -> a) -> [a] ft1 f = [f False, f True] f1 :: Bool -> Int f1 False = 0 f1 True = 1 trie1a :: HasTrie a => (Bool -> a) :->: [a] trie1a = trie ft1 trie1b :: HasTrie a => (Bool :->: a) :->: [a] trie1b = trie1a trie1c :: HasTrie a => (Either () () :->: a) :->: [a] trie1c = trie1a trie1d :: HasTrie a => ((Trie () :*: Trie ()) a) :->: [a] trie1d = trie1a trie1e :: HasTrie a => (Trie () a, Trie () a) :->: [a] trie1e = trie1a trie1f :: HasTrie a => (() :->: a, () :->: a) :->: [a] trie1f = trie1a trie1g :: HasTrie a => (a, a) :->: [a] trie1g = trie1a trie1h :: HasTrie a => (Trie a :. Trie a) [a] trie1h = trie1a trie1i :: HasTrie a => a :->: a :->: [a] trie1i = unO trie1a ft2 :: ([Bool] -> Int) -> Int ft2 f = f (alts 15) alts :: Int -> [Bool] alts n = take n (cycle [True,False]) f2 :: [Bool] -> Int f2 = length . filter id Memoization fails : * FunctorCombo . ft2 f2 8 * FunctorCombo . MemoTrie > memo ft2 f2 f3 :: Bool -> Integer f3 = const 3 * FunctorCombo . f3 undefined 3 * FunctorCombo . MemoTrie > memo f3 undefined f4 :: () -> Integer f4 = const 4 * FunctorCombo . f4 undefined 4 * FunctorCombo . MemoTrie > memo f4 undefined 4 f5 :: ((),()) -> Integer f5 = const 5 * FunctorCombo . f5 undefined 5 * FunctorCombo . MemoTrie > memo f5 undefined 5 f6 :: Either () () -> Integer f6 = const 6 * FunctorCombo . f6 undefined 6 * FunctorCombo . MemoTrie > memo f6 undefined t6 :: Either () () :-> Integer t6 = trie f6 * FunctorCombo . MemoTrie > t6 -}
42a8c4c77c3a179a24b6a2de9452d5acc9b7d7340e0c3c0c4cfd9f806f70acdc
graninas/Hydra
Interpreter.hs
module Hydra.Core.SqlDB.Interpreter where import Hydra.Prelude import qualified Hydra.Core.SqlDB.Language as L import qualified Hydra.Core.Domain as D interpretSqlDBMethod :: D.NativeSqlConn -> (String -> IO ()) -> L.SqlDBMethodF beM a -> IO a interpretSqlDBMethod nativeConn logger (L.SqlDBMethod runner next) = next <$> runner nativeConn logger runSqlDBL :: D.NativeSqlConn -> (String -> IO ()) -> L.SqlDBL beM a -> IO a runSqlDBL nativeConn logger = foldFree (interpretSqlDBMethod nativeConn logger)
null
https://raw.githubusercontent.com/graninas/Hydra/60d591b1300528f5ffd93efa205012eebdd0286c/lib/hydra-free/src/Hydra/Core/SqlDB/Interpreter.hs
haskell
module Hydra.Core.SqlDB.Interpreter where import Hydra.Prelude import qualified Hydra.Core.SqlDB.Language as L import qualified Hydra.Core.Domain as D interpretSqlDBMethod :: D.NativeSqlConn -> (String -> IO ()) -> L.SqlDBMethodF beM a -> IO a interpretSqlDBMethod nativeConn logger (L.SqlDBMethod runner next) = next <$> runner nativeConn logger runSqlDBL :: D.NativeSqlConn -> (String -> IO ()) -> L.SqlDBL beM a -> IO a runSqlDBL nativeConn logger = foldFree (interpretSqlDBMethod nativeConn logger)
0b4df8bdf3f1c09b9989494d6e13180b7fbbb873f968bd4a89e026755227c1c2
ibabushkin/hapstone
StorableSpec.hs
module Internal.Arm64.StorableSpec where import Foreign import Foreign.C.Types import Test.Hspec import Test.QuickCheck import Hapstone.Internal.Arm64 import Internal.Arm64.Default -- | main spec spec :: Spec spec = describe "Hapstone.Internal.Arm64" $ do arm64OpMemStructSpec csArm64OpSpec csArm64Spec getArm64OpMemStruct :: IO Arm64OpMemStruct getArm64OpMemStruct = do ptr <- mallocArray (sizeOf arm64OpMemStruct) :: IO (Ptr Word8) poke (castPtr ptr) (fromIntegral $ fromEnum Arm64RegB4 :: Word32) poke (plusPtr ptr 4) (fromIntegral $ fromEnum Arm64RegB16 :: Word32) poke (plusPtr ptr 8) (0x03152746 :: Int32) peek (castPtr ptr) <* free ptr arm64OpMemStruct :: Arm64OpMemStruct arm64OpMemStruct = Arm64OpMemStruct Arm64RegB4 Arm64RegB16 0x03152746 -- | Arm64OpMemStruct spec arm64OpMemStructSpec :: Spec arm64OpMemStructSpec = describe "Storable Arm64OpMemStruct" $ do it "is a packed struct" $ sizeOf (undefined :: Arm64OpMemStruct) == sizeOf (0 :: CUInt) * 2 + sizeOf (0 :: Word32) it "has matching peek- and poke-implementations" $ property $ \s@Arm64OpMemStruct{} -> alloca (\p -> poke p s >> peek p) `shouldReturn` s it "parses correctly" $ getArm64OpMemStruct `shouldReturn` arm64OpMemStruct getCsArm64Op :: IO CsArm64Op getCsArm64Op = do ptr <- mallocArray (sizeOf csArm64Op) :: IO (Ptr Word8) poke (castPtr ptr) (0x01234567 :: Word32) poke (plusPtr ptr 4) (fromIntegral $ fromEnum Arm64Vas8b :: Int32) poke (plusPtr ptr 8) (fromIntegral $ fromEnum Arm64VessB :: Int32) poke (plusPtr ptr 12) (fromIntegral $ fromEnum Arm64SftMsl :: Int32) poke (plusPtr ptr 16) (0x01234567 :: Word32) poke (plusPtr ptr 20) (fromIntegral $ fromEnum Arm64ExtUxtb :: Int32) poke (plusPtr ptr 24) (fromIntegral $ fromEnum Arm64OpImm :: Int32) poke (plusPtr ptr 32) (0x0123456789abcdef :: Int64) poke (plusPtr ptr 44) (0x1 :: Word8) peek (castPtr ptr) <* free ptr csArm64Op :: CsArm64Op csArm64Op = CsArm64Op 0x01234567 Arm64Vas8b Arm64VessB (Arm64SftMsl, 0x01234567) Arm64ExtUxtb (Imm 0x0123456789abcdef) 0x1 csArm64OpSpec :: Spec csArm64OpSpec = describe "Storable CsArm64Op" $ do it "has a memory-layout we can handle" $ sizeOf (undefined :: CsArm64Op) == 7*4 + 4 + 12 + 1 + 3 it "has matching peek- and poke-implementations" $ property $ \s@CsArm64Op{} -> alloca (\p -> poke p s >> peek p) `shouldReturn` s it "parses correctly" $ getCsArm64Op `shouldReturn` csArm64Op getCsArm64 :: IO CsArm64 getCsArm64 = do ptr <- mallocArray (sizeOf csArm64) :: IO (Ptr Word8) poke (castPtr ptr) (fromIntegral $ fromEnum Arm64CcEq :: Int32) poke (plusPtr ptr 4) (0x1 :: Word8) poke (plusPtr ptr 5) (0x0 :: Word8) poke (plusPtr ptr 6) (0x1 :: Word8) poke (plusPtr ptr 8) csArm64Op peek (castPtr ptr) <* free ptr csArm64 :: CsArm64 csArm64 = CsArm64 Arm64CcEq True False [csArm64Op] csArm64Spec :: Spec csArm64Spec = describe "Storable CsArm64" $ do it "has a memory-layout we can handle" $ sizeOf (undefined :: CsArm64) == 4 + 3 + 1 + 8*48 it "has matching peek- and poke-implementations" $ property $ \s@CsArm64{} -> alloca (\p -> poke p s >> peek p) `shouldReturn` s it "parses correctly" $ getCsArm64 `shouldReturn` csArm64
null
https://raw.githubusercontent.com/ibabushkin/hapstone/4ac11f0a1e23e5a0f23351149c70bd541ddf5344/test/Internal/Arm64/StorableSpec.hs
haskell
| main spec | Arm64OpMemStruct spec
module Internal.Arm64.StorableSpec where import Foreign import Foreign.C.Types import Test.Hspec import Test.QuickCheck import Hapstone.Internal.Arm64 import Internal.Arm64.Default spec :: Spec spec = describe "Hapstone.Internal.Arm64" $ do arm64OpMemStructSpec csArm64OpSpec csArm64Spec getArm64OpMemStruct :: IO Arm64OpMemStruct getArm64OpMemStruct = do ptr <- mallocArray (sizeOf arm64OpMemStruct) :: IO (Ptr Word8) poke (castPtr ptr) (fromIntegral $ fromEnum Arm64RegB4 :: Word32) poke (plusPtr ptr 4) (fromIntegral $ fromEnum Arm64RegB16 :: Word32) poke (plusPtr ptr 8) (0x03152746 :: Int32) peek (castPtr ptr) <* free ptr arm64OpMemStruct :: Arm64OpMemStruct arm64OpMemStruct = Arm64OpMemStruct Arm64RegB4 Arm64RegB16 0x03152746 arm64OpMemStructSpec :: Spec arm64OpMemStructSpec = describe "Storable Arm64OpMemStruct" $ do it "is a packed struct" $ sizeOf (undefined :: Arm64OpMemStruct) == sizeOf (0 :: CUInt) * 2 + sizeOf (0 :: Word32) it "has matching peek- and poke-implementations" $ property $ \s@Arm64OpMemStruct{} -> alloca (\p -> poke p s >> peek p) `shouldReturn` s it "parses correctly" $ getArm64OpMemStruct `shouldReturn` arm64OpMemStruct getCsArm64Op :: IO CsArm64Op getCsArm64Op = do ptr <- mallocArray (sizeOf csArm64Op) :: IO (Ptr Word8) poke (castPtr ptr) (0x01234567 :: Word32) poke (plusPtr ptr 4) (fromIntegral $ fromEnum Arm64Vas8b :: Int32) poke (plusPtr ptr 8) (fromIntegral $ fromEnum Arm64VessB :: Int32) poke (plusPtr ptr 12) (fromIntegral $ fromEnum Arm64SftMsl :: Int32) poke (plusPtr ptr 16) (0x01234567 :: Word32) poke (plusPtr ptr 20) (fromIntegral $ fromEnum Arm64ExtUxtb :: Int32) poke (plusPtr ptr 24) (fromIntegral $ fromEnum Arm64OpImm :: Int32) poke (plusPtr ptr 32) (0x0123456789abcdef :: Int64) poke (plusPtr ptr 44) (0x1 :: Word8) peek (castPtr ptr) <* free ptr csArm64Op :: CsArm64Op csArm64Op = CsArm64Op 0x01234567 Arm64Vas8b Arm64VessB (Arm64SftMsl, 0x01234567) Arm64ExtUxtb (Imm 0x0123456789abcdef) 0x1 csArm64OpSpec :: Spec csArm64OpSpec = describe "Storable CsArm64Op" $ do it "has a memory-layout we can handle" $ sizeOf (undefined :: CsArm64Op) == 7*4 + 4 + 12 + 1 + 3 it "has matching peek- and poke-implementations" $ property $ \s@CsArm64Op{} -> alloca (\p -> poke p s >> peek p) `shouldReturn` s it "parses correctly" $ getCsArm64Op `shouldReturn` csArm64Op getCsArm64 :: IO CsArm64 getCsArm64 = do ptr <- mallocArray (sizeOf csArm64) :: IO (Ptr Word8) poke (castPtr ptr) (fromIntegral $ fromEnum Arm64CcEq :: Int32) poke (plusPtr ptr 4) (0x1 :: Word8) poke (plusPtr ptr 5) (0x0 :: Word8) poke (plusPtr ptr 6) (0x1 :: Word8) poke (plusPtr ptr 8) csArm64Op peek (castPtr ptr) <* free ptr csArm64 :: CsArm64 csArm64 = CsArm64 Arm64CcEq True False [csArm64Op] csArm64Spec :: Spec csArm64Spec = describe "Storable CsArm64" $ do it "has a memory-layout we can handle" $ sizeOf (undefined :: CsArm64) == 4 + 3 + 1 + 8*48 it "has matching peek- and poke-implementations" $ property $ \s@CsArm64{} -> alloca (\p -> poke p s >> peek p) `shouldReturn` s it "parses correctly" $ getCsArm64 `shouldReturn` csArm64
3d752aef8d7e452de216d1a643de5a61a57bfd8af10073d30a47335c4c4b9a1c
hstreamdb/hstream
StatsSpecUtils.hs
module HStream.StatsSpecUtils where import Control.Concurrent (threadDelay) import Data.Int (Int64) import qualified Data.Map.Strict as Map import Data.Maybe (fromJust) import Test.Hspec import Z.Data.CBytes (CBytes) import HStream.Stats (StatsHolder, resetStatsHolder) # ANN module ( " HLint : ignore Use head " : : String ) # mkTimeSeriesTest :: StatsHolder -> [Int] -> CBytes -> (StatsHolder -> CBytes -> Int64 -> IO ()) -> (StatsHolder -> CBytes -> CBytes -> [Int] -> IO (Maybe [Double])) -> (StatsHolder -> CBytes -> [Int] -> IO (Either String (Map.Map CBytes [Double]))) -> Expectation mkTimeSeriesTest h intervals stats_name stats_add stats_get stats_getall = do stats_add h "key_1" 1000 stats_add h "key_2" 10000 NOTE : we choose to sleep 1s so that we can assume the speed of key_1 wo n't be faster than 2000B / s threadDelay 1000000 stats_add h "key_1" 1000 stats_add h "key_2" 10000 stats_get h stats_name "non-existed-key" intervals `shouldReturn` Nothing Just [rate1_p5s, rate1_p10s] <- stats_get h stats_name "key_1" intervals rate1_p5s `shouldSatisfy` (\s -> s > 0 && s <= 2000) rate1_p10s `shouldSatisfy` (\s -> s > 0 && s <= 2000) Just [rate2_p5s, rate2_p10s] <- stats_get h stats_name "key_2" intervals NOTE : There is a possibility that the speed is less than 2000 . However , in -- typical cases, it shouldn't. rate2_p5s `shouldSatisfy` (\s -> s > 2000 && s <= 20000) rate2_p10s `shouldSatisfy` (\s -> s > 2000 && s <= 20000) Right m <- stats_getall h stats_name intervals Map.lookup "key_1" m `shouldSatisfy` ((\s -> s!!0 > 0 && s!!0 <= 2000) . fromJust) Map.lookup "key_2" m `shouldSatisfy` ((\s -> s!!1 > 2000 && s!!1 <= 20000) . fromJust) resetStatsHolder h stats_getall h stats_name intervals `shouldReturn` Right Map.empty
null
https://raw.githubusercontent.com/hstreamdb/hstream/36f5a8be4c786dfeb3d24cf1253fb6a6dad3c38c/common/stats/test/HStream/StatsSpecUtils.hs
haskell
typical cases, it shouldn't.
module HStream.StatsSpecUtils where import Control.Concurrent (threadDelay) import Data.Int (Int64) import qualified Data.Map.Strict as Map import Data.Maybe (fromJust) import Test.Hspec import Z.Data.CBytes (CBytes) import HStream.Stats (StatsHolder, resetStatsHolder) # ANN module ( " HLint : ignore Use head " : : String ) # mkTimeSeriesTest :: StatsHolder -> [Int] -> CBytes -> (StatsHolder -> CBytes -> Int64 -> IO ()) -> (StatsHolder -> CBytes -> CBytes -> [Int] -> IO (Maybe [Double])) -> (StatsHolder -> CBytes -> [Int] -> IO (Either String (Map.Map CBytes [Double]))) -> Expectation mkTimeSeriesTest h intervals stats_name stats_add stats_get stats_getall = do stats_add h "key_1" 1000 stats_add h "key_2" 10000 NOTE : we choose to sleep 1s so that we can assume the speed of key_1 wo n't be faster than 2000B / s threadDelay 1000000 stats_add h "key_1" 1000 stats_add h "key_2" 10000 stats_get h stats_name "non-existed-key" intervals `shouldReturn` Nothing Just [rate1_p5s, rate1_p10s] <- stats_get h stats_name "key_1" intervals rate1_p5s `shouldSatisfy` (\s -> s > 0 && s <= 2000) rate1_p10s `shouldSatisfy` (\s -> s > 0 && s <= 2000) Just [rate2_p5s, rate2_p10s] <- stats_get h stats_name "key_2" intervals NOTE : There is a possibility that the speed is less than 2000 . However , in rate2_p5s `shouldSatisfy` (\s -> s > 2000 && s <= 20000) rate2_p10s `shouldSatisfy` (\s -> s > 2000 && s <= 20000) Right m <- stats_getall h stats_name intervals Map.lookup "key_1" m `shouldSatisfy` ((\s -> s!!0 > 0 && s!!0 <= 2000) . fromJust) Map.lookup "key_2" m `shouldSatisfy` ((\s -> s!!1 > 2000 && s!!1 <= 20000) . fromJust) resetStatsHolder h stats_getall h stats_name intervals `shouldReturn` Right Map.empty
b42a0efe4b666037173827afd01c2829685a2b94247eb6e50f8377c50e93ebf9
intermine/bluegenes-old
core.cljs
(ns bluegenes.tools.runtemplate.core (:require-macros [cljs.core.async.macros :refer [go]]) (:require [re-frame.core :as re-frame] [cljs.core.async :refer [put! chan <! >! timeout close!]] [reagent.core :as reagent] [reagent.impl.util :as impl :refer [extract-props]] [clojure.string :as str] [intermine.imjs :as imjs])) (defn template-matches-pathtype? [path template] "True if a template has a constraint with a cerain type" (if (some (fn [constraint] (= (get constraint "path") path)) (get (second template) "where")) template)) (defn filter-templates-for-type [path templates] "Filter a collection of templates for a certain path type" (filter #(template-matches-pathtype? path %) templates)) (defn filter-input-constraints [templates type] "Get templates that can use our input type" (filter-templates-for-type type templates)) (defn constraint [] (fn [con update-fn] [:div [:form [:div.form-group [:label (get con "path")] [:div.input-group [:span.input-group-addon (get con "op")] [:input.form-control {:type "text" :value (if (nil? (get con "value")) (get con "values") (get con "value")) :disabled (if (= true (get con "fixed")) "true") :on-change (fn [e] (update-fn con {"value" (.. e -target -value)}))}]]]]])) (defn path-end [path] (last (clojure.string/split path #"\."))) (defn constraints [cons] "Renders a list of constraints ignoring any constraints on id." [:div (for [con cons :when (not (get con "hide"))] ^{:key (get con "path")} [constraint con])]) (defn run-button-handler [state emit] "Emit the data." (emit {:service {:root "www.flymine.org/query"} :data {:format "query" :type "Gene" :value (js->clj (-> @state))}})) (defn run-button [state emit] [:button.btn.btn-info.btn-raised {:on-click (fn [e] (run-button-handler state emit)) } "Run"]) (defn convert-input-to-constraint [input] (cond (= (get-in input [:data :format]) "list") (do {"path" (str (get-in input [:data :type]) "") "op" "IN" "value" (get-in input [:data :name]) "hide" true "fixed" true}) (= (get-in input [:data :format]) "ids") {"path" (str (get-in input [:data :type]) ".id") "op" "ONE OF" "hide" true "values" (get-in input [:data :value]) "fixed" true})) (defn replace-input-constraint [input template] (update-in template ["where"] #(map (fn [con] (if (true? (= (get con "path") (get-in input [:data :type]))) (merge (dissoc con "value" "values") (convert-input-to-constraint input)) con)) %))) (defn fetch-templates-chan [] "Fetch templates from Intermine and return them over a channel" (let [templates-chan (chan)] (-> (js/imjs.Service. #js {:root "www.flymine.org/query"}) (.fetchTemplates) (.then (fn [response] (go (>! templates-chan (js->clj response)))))) templates-chan)) (defn fetch-templates [local-state] "Store Intermine's templates in our local state atom" (-> (js/imjs.Service. #js {:root "www.flymine.org/query"}) (.fetchTemplates) (.then (fn [response] (swap! local-state assoc :all-templates (js->clj response)))))) (defn updater [comp] (let [{:keys [upstream-data]} (reagent/props comp)] (println "new upstream data" upstream-data))) (defn drop-down [] "Render a drop down that only shows our valid templates" (fn [{:keys [templates on-change-handler selected]}] [:select.form-control {:on-change on-change-handler :value selected} (doall (for [[name values] templates] ^{:key name} [:option {:value name} (get values "title")]))])) (defn store-filtered-templates "Filter known templates for a given type (ex. Gene) and associate them to an atom." [local-state template-type all-templates] (swap! local-state assoc :filtered-templates (filter-input-constraints all-templates template-type))) (defn on-select [templates api e] (let [template-name (-> e .-target .-value)] (-> {:query (get templates template-name)} ((:append-state api))))) (defn default-button [e] (fn [] [:div.btn.btn-raised "Defaults"])) (defn save-query [api templates e] (-> {:query (get templates (.. e -target -value))} ((:append-state api)))) (defn template-has-tag? [[name details] tag] (some (fn [t] (= t (str "im:aspect:" tag))) (get details "tags"))) (defn get-row-count "Reset an atom with the row count of an imjs query." [query] (let [c (chan)] (-> (js/imjs.Service. (clj->js #js{:root "www.flymine.org/query"})) (.query (clj->js query)) (.then (fn [q] (.count q))) (.then (fn [ct] (go (>! c ct))))) c)) (defn filter-single-constraints "Returns templates that only have a single constraint." [templates] (filter (fn [[name details]] (< (count (get details "where") 2))) templates)) (defn ^:export preview [] (let [local-state (reagent/atom {:template-counts {} :category nil :all-templates nil :single-constraint-templates {} :filtered-templates nil})] (reagent/create-class {:component-will-update (fn [this new-props] (swap! local-state assoc :category (:category (extract-props new-props)))) :component-did-mount (fn [this] (go (let [templates (<! (fetch-templates-chan)) filtered-templates (filter-input-constraints templates "Gene") ip (reagent/props this) single-constraint-templates (into {} (filter-single-constraints filtered-templates)) adjusted-input-templates (reduce (fn [m [t-name t]] ( println " SEES T " t ) (assoc m t-name (replace-input-constraint ip t))) {} single-constraint-templates) ; adjusted (into {} (map (fn [[n t]] (replace-input-constraint ip t)) single-constraint-templates)) ] (println "IP" adjusted-input-templates) ; (println "adjusted" single-constraint-templates) (println "done") ; Update our state our initial, filtered template data (swap! local-state merge {:all-templates templates :single-constraint-templates single-constraint-templates :adjusted-input-templates adjusted-input-templates :filtered-templates filtered-templates}) (doall (for [[name template] adjusted-input-templates] (go (let [count (<! (get-row-count template))] (swap! local-state assoc-in [:adjusted-input-templates name :count] count)))))))) :reagent-render (fn [] [:div [:div.heading "Popular Queries"] (doall (for [[name data] (take 5 (filter (fn [t] (template-has-tag? t (:category @local-state))) (:adjusted-input-templates @local-state)))] (let [t (get-in @local-state [:all-templates name "title"]) adjusted-title (clojure.string/join " " (rest (clojure.string/split t #"-->")))] ^{:key name} [:div.indented (str adjusted-title " (" (:count data) " rows)")]))) [:div.indented.highlighted "More..."]])}))) (defn replace-constraints [query cons replace] (swap! query update-in ["where"] (fn [constraints] (doall (map (fn [constraint] (if (= constraint cons) (merge constraint replace) constraint)) constraints))))) (defn ^:export main [props] (let [query (reagent.core/atom {}) local-state (reagent.core/atom {:all-templates nil :filtered-templates nil})] (reagent/create-class {:should-component-update (fn [this o n] (println "run template param diff" (nth (clojure.data/diff (extract-props o) (extract-props n)) 1))) :component-did-mount (fn [e] (fetch-templates local-state)) :component-will-receive-props (fn [this comp] (let [old-props (reagent/props this) new-props (extract-props comp)] (->> (:query (:state new-props)) (replace-input-constraint (:upstream-data new-props)) (reset! query)))) :reagent-render (fn [{:keys [api]}] [:div [drop-down {:templates (:all-templates @local-state) :on-change-handler (partial save-query api (:all-templates @local-state))}] Build our constraints DIV (into [:div] (map (fn [where] [constraint where (partial replace-constraints query)]) (get @query "where"))) ; [:div.btn.btn-primary.btn-raised ; {:on-click (fn [e] (println query))} ; "run"] [run-button query (:has-something api)] [default-button]])})))
null
https://raw.githubusercontent.com/intermine/bluegenes-old/5b719c7ac83a7340e0ff65790cf42413c15fb7e9/src/cljs/bluegenes/tools/runtemplate/core.cljs
clojure
adjusted (into {} (map (fn [[n t]] (replace-input-constraint ip t)) single-constraint-templates)) (println "adjusted" single-constraint-templates) Update our state our initial, filtered template data [:div.btn.btn-primary.btn-raised {:on-click (fn [e] (println query))} "run"]
(ns bluegenes.tools.runtemplate.core (:require-macros [cljs.core.async.macros :refer [go]]) (:require [re-frame.core :as re-frame] [cljs.core.async :refer [put! chan <! >! timeout close!]] [reagent.core :as reagent] [reagent.impl.util :as impl :refer [extract-props]] [clojure.string :as str] [intermine.imjs :as imjs])) (defn template-matches-pathtype? [path template] "True if a template has a constraint with a cerain type" (if (some (fn [constraint] (= (get constraint "path") path)) (get (second template) "where")) template)) (defn filter-templates-for-type [path templates] "Filter a collection of templates for a certain path type" (filter #(template-matches-pathtype? path %) templates)) (defn filter-input-constraints [templates type] "Get templates that can use our input type" (filter-templates-for-type type templates)) (defn constraint [] (fn [con update-fn] [:div [:form [:div.form-group [:label (get con "path")] [:div.input-group [:span.input-group-addon (get con "op")] [:input.form-control {:type "text" :value (if (nil? (get con "value")) (get con "values") (get con "value")) :disabled (if (= true (get con "fixed")) "true") :on-change (fn [e] (update-fn con {"value" (.. e -target -value)}))}]]]]])) (defn path-end [path] (last (clojure.string/split path #"\."))) (defn constraints [cons] "Renders a list of constraints ignoring any constraints on id." [:div (for [con cons :when (not (get con "hide"))] ^{:key (get con "path")} [constraint con])]) (defn run-button-handler [state emit] "Emit the data." (emit {:service {:root "www.flymine.org/query"} :data {:format "query" :type "Gene" :value (js->clj (-> @state))}})) (defn run-button [state emit] [:button.btn.btn-info.btn-raised {:on-click (fn [e] (run-button-handler state emit)) } "Run"]) (defn convert-input-to-constraint [input] (cond (= (get-in input [:data :format]) "list") (do {"path" (str (get-in input [:data :type]) "") "op" "IN" "value" (get-in input [:data :name]) "hide" true "fixed" true}) (= (get-in input [:data :format]) "ids") {"path" (str (get-in input [:data :type]) ".id") "op" "ONE OF" "hide" true "values" (get-in input [:data :value]) "fixed" true})) (defn replace-input-constraint [input template] (update-in template ["where"] #(map (fn [con] (if (true? (= (get con "path") (get-in input [:data :type]))) (merge (dissoc con "value" "values") (convert-input-to-constraint input)) con)) %))) (defn fetch-templates-chan [] "Fetch templates from Intermine and return them over a channel" (let [templates-chan (chan)] (-> (js/imjs.Service. #js {:root "www.flymine.org/query"}) (.fetchTemplates) (.then (fn [response] (go (>! templates-chan (js->clj response)))))) templates-chan)) (defn fetch-templates [local-state] "Store Intermine's templates in our local state atom" (-> (js/imjs.Service. #js {:root "www.flymine.org/query"}) (.fetchTemplates) (.then (fn [response] (swap! local-state assoc :all-templates (js->clj response)))))) (defn updater [comp] (let [{:keys [upstream-data]} (reagent/props comp)] (println "new upstream data" upstream-data))) (defn drop-down [] "Render a drop down that only shows our valid templates" (fn [{:keys [templates on-change-handler selected]}] [:select.form-control {:on-change on-change-handler :value selected} (doall (for [[name values] templates] ^{:key name} [:option {:value name} (get values "title")]))])) (defn store-filtered-templates "Filter known templates for a given type (ex. Gene) and associate them to an atom." [local-state template-type all-templates] (swap! local-state assoc :filtered-templates (filter-input-constraints all-templates template-type))) (defn on-select [templates api e] (let [template-name (-> e .-target .-value)] (-> {:query (get templates template-name)} ((:append-state api))))) (defn default-button [e] (fn [] [:div.btn.btn-raised "Defaults"])) (defn save-query [api templates e] (-> {:query (get templates (.. e -target -value))} ((:append-state api)))) (defn template-has-tag? [[name details] tag] (some (fn [t] (= t (str "im:aspect:" tag))) (get details "tags"))) (defn get-row-count "Reset an atom with the row count of an imjs query." [query] (let [c (chan)] (-> (js/imjs.Service. (clj->js #js{:root "www.flymine.org/query"})) (.query (clj->js query)) (.then (fn [q] (.count q))) (.then (fn [ct] (go (>! c ct))))) c)) (defn filter-single-constraints "Returns templates that only have a single constraint." [templates] (filter (fn [[name details]] (< (count (get details "where") 2))) templates)) (defn ^:export preview [] (let [local-state (reagent/atom {:template-counts {} :category nil :all-templates nil :single-constraint-templates {} :filtered-templates nil})] (reagent/create-class {:component-will-update (fn [this new-props] (swap! local-state assoc :category (:category (extract-props new-props)))) :component-did-mount (fn [this] (go (let [templates (<! (fetch-templates-chan)) filtered-templates (filter-input-constraints templates "Gene") ip (reagent/props this) single-constraint-templates (into {} (filter-single-constraints filtered-templates)) adjusted-input-templates (reduce (fn [m [t-name t]] ( println " SEES T " t ) (assoc m t-name (replace-input-constraint ip t))) {} single-constraint-templates) ] (println "IP" adjusted-input-templates) (println "done") (swap! local-state merge {:all-templates templates :single-constraint-templates single-constraint-templates :adjusted-input-templates adjusted-input-templates :filtered-templates filtered-templates}) (doall (for [[name template] adjusted-input-templates] (go (let [count (<! (get-row-count template))] (swap! local-state assoc-in [:adjusted-input-templates name :count] count)))))))) :reagent-render (fn [] [:div [:div.heading "Popular Queries"] (doall (for [[name data] (take 5 (filter (fn [t] (template-has-tag? t (:category @local-state))) (:adjusted-input-templates @local-state)))] (let [t (get-in @local-state [:all-templates name "title"]) adjusted-title (clojure.string/join " " (rest (clojure.string/split t #"-->")))] ^{:key name} [:div.indented (str adjusted-title " (" (:count data) " rows)")]))) [:div.indented.highlighted "More..."]])}))) (defn replace-constraints [query cons replace] (swap! query update-in ["where"] (fn [constraints] (doall (map (fn [constraint] (if (= constraint cons) (merge constraint replace) constraint)) constraints))))) (defn ^:export main [props] (let [query (reagent.core/atom {}) local-state (reagent.core/atom {:all-templates nil :filtered-templates nil})] (reagent/create-class {:should-component-update (fn [this o n] (println "run template param diff" (nth (clojure.data/diff (extract-props o) (extract-props n)) 1))) :component-did-mount (fn [e] (fetch-templates local-state)) :component-will-receive-props (fn [this comp] (let [old-props (reagent/props this) new-props (extract-props comp)] (->> (:query (:state new-props)) (replace-input-constraint (:upstream-data new-props)) (reset! query)))) :reagent-render (fn [{:keys [api]}] [:div [drop-down {:templates (:all-templates @local-state) :on-change-handler (partial save-query api (:all-templates @local-state))}] Build our constraints DIV (into [:div] (map (fn [where] [constraint where (partial replace-constraints query)]) (get @query "where"))) [run-button query (:has-something api)] [default-button]])})))
a8bb0545abc7e50357a419f24441717bda61aa570e6a2466eb5dd86399e41fbf
exercism/racket
hamming-test.rkt
#lang racket/base (require "hamming.rkt") (module+ test (require rackunit rackunit/text-ui) (define suite (test-suite "point mutations tests" (test-eqv? "no difference between empty strands" (hamming-distance "" "") 0) (test-eqv? "no difference between identical strands" (hamming-distance "GATTACA" "GATTACA") 0) (test-eqv? "complete hamming distance in small strand" (hamming-distance "ACT" "GGA") 3) (test-eqv? "small hamming distance in middle somewhere" (hamming-distance "GGACG" "GGTCG") 1) (test-eqv? "larger difference" (hamming-distance "ACCAGGG" "ACTATGG") 2) (test-exn "String length mismatch." exn:fail? (lambda () (hamming-distance "AGACAACAGCCAGCCGCCGGATT" "AGGCAA"))))) (run-tests suite))
null
https://raw.githubusercontent.com/exercism/racket/4110268ed331b1b4dac8888550f05d0dacb1865b/exercises/practice/hamming/hamming-test.rkt
racket
#lang racket/base (require "hamming.rkt") (module+ test (require rackunit rackunit/text-ui) (define suite (test-suite "point mutations tests" (test-eqv? "no difference between empty strands" (hamming-distance "" "") 0) (test-eqv? "no difference between identical strands" (hamming-distance "GATTACA" "GATTACA") 0) (test-eqv? "complete hamming distance in small strand" (hamming-distance "ACT" "GGA") 3) (test-eqv? "small hamming distance in middle somewhere" (hamming-distance "GGACG" "GGTCG") 1) (test-eqv? "larger difference" (hamming-distance "ACCAGGG" "ACTATGG") 2) (test-exn "String length mismatch." exn:fail? (lambda () (hamming-distance "AGACAACAGCCAGCCGCCGGATT" "AGGCAA"))))) (run-tests suite))
36c990701497d60c7dd1f8fa220fb3e2d43ed1a11de2f836cad5c7a45a343844
lambdabot/lambdabot
Common.hs
module Lambdabot.Plugin.Haskell.Pl.Common ( Fixity(..), Expr(..), Pattern(..), Decl(..), TopLevel(..), bt, sizeExpr, mapTopLevel, getExpr, operators, opchars, reservedOps, lookupOp, lookupFix, minPrec, maxPrec, comp, flip', id', const', scomb, cons, nil, fix', if', makeList, getList, readM, Assoc(..), module Data.Maybe, module Control.Arrow, module Data.List, module Control.Monad, module GHC.Base ) where import Data.Maybe (isJust, fromJust) import Data.List (intersperse, minimumBy) import qualified Data.Map as M import Control.Applicative import Control.Monad import Control.Arrow (first, second, (***), (&&&), (|||), (+++)) import Text.ParserCombinators.Parsec.Expr (Assoc(..)) import GHC.Base (assert) -- The rewrite rules can be found at the end of the file Rules.hs -- Not sure if passing the information if it was used as infix or prefix -- is worth threading through the whole thing is worth the effort, -- but it stays that way until the prettyprinting algorithm gets more -- sophisticated. data Fixity = Pref | Inf deriving Show instance Eq Fixity where _ == _ = True instance Ord Fixity where compare _ _ = EQ data Expr = Var Fixity String | Lambda Pattern Expr | App Expr Expr | Let [Decl] Expr deriving (Eq, Ord) data Pattern = PVar String | PCons Pattern Pattern | PTuple Pattern Pattern deriving (Eq, Ord) data Decl = Define { declName :: String, declExpr :: Expr } deriving (Eq, Ord) data TopLevel = TLD Bool Decl | TLE Expr deriving (Eq, Ord) mapTopLevel :: (Expr -> Expr) -> TopLevel -> TopLevel mapTopLevel f tl = case getExpr tl of (e, c) -> c $ f e getExpr :: TopLevel -> (Expr, Expr -> TopLevel) getExpr (TLD True (Define foo e)) = (Let [Define foo e] (Var Pref foo), \e' -> TLD False $ Define foo e') getExpr (TLD False (Define foo e)) = (e, \e' -> TLD False $ Define foo e') getExpr (TLE e) = (e, TLE) sizeExpr :: Expr -> Int sizeExpr (Var _ _) = 1 sizeExpr (App e1 e2) = sizeExpr e1 + sizeExpr e2 + 1 sizeExpr (Lambda _ e) = 1 + sizeExpr e sizeExpr (Let ds e) = 1 + sum (map sizeDecl ds) + sizeExpr e where sizeDecl (Define _ e') = 1 + sizeExpr e' comp, flip', id', const', scomb, cons, nil, fix', if' :: Expr comp = Var Inf "." flip' = Var Pref "flip" id' = Var Pref "id" const' = Var Pref "const" scomb = Var Pref "ap" cons = Var Inf ":" nil = Var Pref "[]" fix' = Var Pref "fix" if' = Var Pref "if'" makeList :: [Expr] -> Expr makeList = foldr (\e1 e2 -> cons `App` e1 `App` e2) nil -- Modularity is a drag getList :: Expr -> ([Expr], Expr) getList (c `App` x `App` tl) | c == cons = first (x:) $ getList tl getList e = ([],e) bt :: a bt = undefined shift, minPrec, maxPrec :: Int shift = 0 maxPrec = shift + 10 minPrec = 0 -- operator precedences are needed both for parsing and prettyprinting operators :: [[(String, (Assoc, Int))]] operators = (map . map . second . second $ (+shift)) [[inf "." AssocRight 9, inf "!!" AssocLeft 9], [inf name AssocRight 8 | name <- ["^", "^^", "**"]], [inf name AssocLeft 7 | name <- ["*", "/", "`quot`", "`rem`", "`div`", "`mod`", ":%", "%"]], [inf name AssocLeft 6 | name <- ["+", "-"]], [inf name AssocRight 5 | name <- [":", "++", "<+>"]], [inf name AssocNone 4 | name <- ["==", "/=", "<", "<=", ">=", ">", "`elem`", "`notElem`"]] ++[inf name AssocLeft 4 | name <- ["<*","*>","<$>","<$","<**>"]], [inf "&&" AssocRight 3, inf "***" AssocRight 3, inf "&&&" AssocRight 3, inf "<|>" AssocLeft 3], [inf "||" AssocRight 2, inf "+++" AssocRight 2, inf "|||" AssocRight 2], [inf ">>" AssocLeft 1, inf ">>=" AssocLeft 1, inf "=<<" AssocRight 1, inf ">>>" AssocRight 1, inf "^>>" AssocRight 1, inf "^<<" AssocRight 1], [inf name AssocRight 0 | name <- ["$", "$!", "`seq`"]] ] where inf name assoc fx = (name, (assoc, fx)) opchars :: [Char] opchars = "!@#$%^*./|=-+:?<>&" reservedOps :: [String] reservedOps = ["->", "..", "="] opFM :: M.Map String (Assoc, Int) opFM = (M.fromList $ concat operators) lookupOp :: String -> Maybe (Assoc, Int) lookupOp k = M.lookup k opFM lookupFix :: String -> (Assoc, Int) lookupFix str = case lookupOp $ str of Nothing -> (AssocLeft, 9 + shift) Just x -> x readM :: (Read a, Alternative m) => String -> m a readM str = case reads str of [(x, "")] -> pure x _ -> empty
null
https://raw.githubusercontent.com/lambdabot/lambdabot/de01f362c7a8fc6f85c37e604168dcccb1283a0e/lambdabot-haskell-plugins/src/Lambdabot/Plugin/Haskell/Pl/Common.hs
haskell
The rewrite rules can be found at the end of the file Rules.hs Not sure if passing the information if it was used as infix or prefix is worth threading through the whole thing is worth the effort, but it stays that way until the prettyprinting algorithm gets more sophisticated. Modularity is a drag operator precedences are needed both for parsing and prettyprinting
module Lambdabot.Plugin.Haskell.Pl.Common ( Fixity(..), Expr(..), Pattern(..), Decl(..), TopLevel(..), bt, sizeExpr, mapTopLevel, getExpr, operators, opchars, reservedOps, lookupOp, lookupFix, minPrec, maxPrec, comp, flip', id', const', scomb, cons, nil, fix', if', makeList, getList, readM, Assoc(..), module Data.Maybe, module Control.Arrow, module Data.List, module Control.Monad, module GHC.Base ) where import Data.Maybe (isJust, fromJust) import Data.List (intersperse, minimumBy) import qualified Data.Map as M import Control.Applicative import Control.Monad import Control.Arrow (first, second, (***), (&&&), (|||), (+++)) import Text.ParserCombinators.Parsec.Expr (Assoc(..)) import GHC.Base (assert) data Fixity = Pref | Inf deriving Show instance Eq Fixity where _ == _ = True instance Ord Fixity where compare _ _ = EQ data Expr = Var Fixity String | Lambda Pattern Expr | App Expr Expr | Let [Decl] Expr deriving (Eq, Ord) data Pattern = PVar String | PCons Pattern Pattern | PTuple Pattern Pattern deriving (Eq, Ord) data Decl = Define { declName :: String, declExpr :: Expr } deriving (Eq, Ord) data TopLevel = TLD Bool Decl | TLE Expr deriving (Eq, Ord) mapTopLevel :: (Expr -> Expr) -> TopLevel -> TopLevel mapTopLevel f tl = case getExpr tl of (e, c) -> c $ f e getExpr :: TopLevel -> (Expr, Expr -> TopLevel) getExpr (TLD True (Define foo e)) = (Let [Define foo e] (Var Pref foo), \e' -> TLD False $ Define foo e') getExpr (TLD False (Define foo e)) = (e, \e' -> TLD False $ Define foo e') getExpr (TLE e) = (e, TLE) sizeExpr :: Expr -> Int sizeExpr (Var _ _) = 1 sizeExpr (App e1 e2) = sizeExpr e1 + sizeExpr e2 + 1 sizeExpr (Lambda _ e) = 1 + sizeExpr e sizeExpr (Let ds e) = 1 + sum (map sizeDecl ds) + sizeExpr e where sizeDecl (Define _ e') = 1 + sizeExpr e' comp, flip', id', const', scomb, cons, nil, fix', if' :: Expr comp = Var Inf "." flip' = Var Pref "flip" id' = Var Pref "id" const' = Var Pref "const" scomb = Var Pref "ap" cons = Var Inf ":" nil = Var Pref "[]" fix' = Var Pref "fix" if' = Var Pref "if'" makeList :: [Expr] -> Expr makeList = foldr (\e1 e2 -> cons `App` e1 `App` e2) nil getList :: Expr -> ([Expr], Expr) getList (c `App` x `App` tl) | c == cons = first (x:) $ getList tl getList e = ([],e) bt :: a bt = undefined shift, minPrec, maxPrec :: Int shift = 0 maxPrec = shift + 10 minPrec = 0 operators :: [[(String, (Assoc, Int))]] operators = (map . map . second . second $ (+shift)) [[inf "." AssocRight 9, inf "!!" AssocLeft 9], [inf name AssocRight 8 | name <- ["^", "^^", "**"]], [inf name AssocLeft 7 | name <- ["*", "/", "`quot`", "`rem`", "`div`", "`mod`", ":%", "%"]], [inf name AssocLeft 6 | name <- ["+", "-"]], [inf name AssocRight 5 | name <- [":", "++", "<+>"]], [inf name AssocNone 4 | name <- ["==", "/=", "<", "<=", ">=", ">", "`elem`", "`notElem`"]] ++[inf name AssocLeft 4 | name <- ["<*","*>","<$>","<$","<**>"]], [inf "&&" AssocRight 3, inf "***" AssocRight 3, inf "&&&" AssocRight 3, inf "<|>" AssocLeft 3], [inf "||" AssocRight 2, inf "+++" AssocRight 2, inf "|||" AssocRight 2], [inf ">>" AssocLeft 1, inf ">>=" AssocLeft 1, inf "=<<" AssocRight 1, inf ">>>" AssocRight 1, inf "^>>" AssocRight 1, inf "^<<" AssocRight 1], [inf name AssocRight 0 | name <- ["$", "$!", "`seq`"]] ] where inf name assoc fx = (name, (assoc, fx)) opchars :: [Char] opchars = "!@#$%^*./|=-+:?<>&" reservedOps :: [String] reservedOps = ["->", "..", "="] opFM :: M.Map String (Assoc, Int) opFM = (M.fromList $ concat operators) lookupOp :: String -> Maybe (Assoc, Int) lookupOp k = M.lookup k opFM lookupFix :: String -> (Assoc, Int) lookupFix str = case lookupOp $ str of Nothing -> (AssocLeft, 9 + shift) Just x -> x readM :: (Read a, Alternative m) => String -> m a readM str = case reads str of [(x, "")] -> pure x _ -> empty
5c6d73b275948ee504bf8950b47051a5dd5857941345620326e5e7330179d1d2
Nutr1t07/wl-bot
Telegram.hs
{-# LANGUAGE OverloadedStrings #-} module Core.Data.Telegram where import Control.Lens ( (^.) ) import Core.Type.Telegram.Request as TR ( SendMsg(SendMsg) ) import Core.Type.Telegram.Update as TU ( Message , Update , edited_message , message ) import Core.Type.Unity.Request as UR import Data.Maybe ( fromJust , isJust , isNothing ) import Data.Text ( pack ) import Data.Text.Lazy ( toStrict ) import Data.Text.Lazy.Builder ( toLazyText ) import HTMLEntities.Decoder ( htmlEncodedText ) import Network.Wreq ( Part , partFile , partText ) | Get Telegram Message ( Message or EditedMessage ) from Telegram Update getMessageFromUpdate :: TU.Update -> (Int, Maybe Message) getMessageFromUpdate tgUpdate = (msg_type, msg) where msg = if msg_type > 1 then Nothing else msgs !! msg_type msgs = [message, edited_message] <*> pure tgUpdate msg_type = Prelude.length $ Prelude.takeWhile isNothing msgs -- | Transform SendMsg into [Part] when local image upload is required. transMsg :: UR.SendMsg -> Either [Part] TR.SendMsg transMsg msg | isJust $ msg ^. imgPath = Left [ partText "chat_id" (pack . show $ msg ^. UR.chat_id) , partText "reply_to_message_id" (pack . show $ msg ^. UR.reply_id) , partFile "photo" (fromJust $ ("images/" <>) <$> msg ^. imgPath) ] | isJust $ msg ^. imgUrl = Right $ TR.SendMsg (msg ^. UR.chat_id) Nothing (msg ^. imgUrl) (msg ^. UR.text) "HTML" (msg ^. reply_id) True | otherwise = Right $ TR.SendMsg (msg ^. UR.chat_id) (decodeHtml <$> msg ^. UR.text) Nothing Nothing "HTML" (msg ^. reply_id) True where decodeHtml = toStrict . toLazyText . htmlEncodedText
null
https://raw.githubusercontent.com/Nutr1t07/wl-bot/4d9db61613a3819d0addbc7e04d77bb2f57892f0/src/Core/Data/Telegram.hs
haskell
# LANGUAGE OverloadedStrings # | Transform SendMsg into [Part] when local image upload is required.
module Core.Data.Telegram where import Control.Lens ( (^.) ) import Core.Type.Telegram.Request as TR ( SendMsg(SendMsg) ) import Core.Type.Telegram.Update as TU ( Message , Update , edited_message , message ) import Core.Type.Unity.Request as UR import Data.Maybe ( fromJust , isJust , isNothing ) import Data.Text ( pack ) import Data.Text.Lazy ( toStrict ) import Data.Text.Lazy.Builder ( toLazyText ) import HTMLEntities.Decoder ( htmlEncodedText ) import Network.Wreq ( Part , partFile , partText ) | Get Telegram Message ( Message or EditedMessage ) from Telegram Update getMessageFromUpdate :: TU.Update -> (Int, Maybe Message) getMessageFromUpdate tgUpdate = (msg_type, msg) where msg = if msg_type > 1 then Nothing else msgs !! msg_type msgs = [message, edited_message] <*> pure tgUpdate msg_type = Prelude.length $ Prelude.takeWhile isNothing msgs transMsg :: UR.SendMsg -> Either [Part] TR.SendMsg transMsg msg | isJust $ msg ^. imgPath = Left [ partText "chat_id" (pack . show $ msg ^. UR.chat_id) , partText "reply_to_message_id" (pack . show $ msg ^. UR.reply_id) , partFile "photo" (fromJust $ ("images/" <>) <$> msg ^. imgPath) ] | isJust $ msg ^. imgUrl = Right $ TR.SendMsg (msg ^. UR.chat_id) Nothing (msg ^. imgUrl) (msg ^. UR.text) "HTML" (msg ^. reply_id) True | otherwise = Right $ TR.SendMsg (msg ^. UR.chat_id) (decodeHtml <$> msg ^. UR.text) Nothing Nothing "HTML" (msg ^. reply_id) True where decodeHtml = toStrict . toLazyText . htmlEncodedText
eef7f121b57eea751e00206ba8129e4c115e73c0fc7e3c2feade428024b76626
Kalimehtar/gtk-cffi
ex6.lisp
424 (asdf:oos 'asdf:load-op :gtk-cffi) (defpackage #:test (:use #:common-lisp #:gdk-cffi #:gtk-cffi #:g-object-cffi) (:shadowing-import-from #:gtk-cffi #:image #:window)) (in-package #:test) (gtk-init) (defvar window) (defvar vbox) (defvar title) (defvar hbox) (defvar vbox-right) (setf window (make-instance 'window)) (setf (gsignal window :destroy) :gtk-main-quit (size-request window) '(600 240)) (add window (setf vbox (make-instance 'v-box))) (let ((title (make-instance 'label :text " Place a background image in GtkEventBox\n Part 2 - using GdkDrawable::draw_pixbuf()"))) (setf (font title) "Times New Roman Italic 10" (color title) "#0000ff" (size-request title) '(-1 40)) (pack* vbox title ((make-instance 'label)) ((setf hbox (make-instance 'h-box :homogeneous t)) :expand t :fill t))) (defun expose-event (widget context &optional (img "none")) (format t "~a ~a ~a~%" widget context img) (let* ((pixbuf (make-instance 'pixbuf :file img)) (w (width pixbuf)) (dest-x (- (width (allocation widget)) w)) (dest-y 0)) (format t "~a~%" pixbuf) (cl-cairo2:with-context ((make-instance 'cl-cairo2:context :pointer context)) (unless (cffi:null-pointer-p (cffi-objects:pointer pixbuf)) (cairo-set-source-pixbuf pixbuf dest-x dest-y) (cl-cairo2:paint)) (let ((ch (child widget))) (when ch (propagate-draw widget ch))))) t) ; (draw-pixbuf (gdk-window widget) ; (style-field widget :bg-gc) pixbuf 0 0 dest-x dest-y) ;(let ((ch (child widget))) ; (when ch ; (propagate- widget ch event))) (let ((eventbox-left (make-instance 'event-box)) (vbox-left (make-instance 'v-box :homogeneous t))) (pack hbox eventbox-left :expand t :fill t) (add eventbox-left vbox-left) (pack* vbox-left ((make-instance 'label :text "This is left eventbox.")) ((make-instance 'label :text "The green ball is the bg image.")) ((make-instance 'label :text "Note that this eventbox")) ((make-instance 'label :text "uses the default gray backgd color."))) (setf (gsignal eventbox-left :draw :data "ball_green3.png") #'expose-event)) (let ((eventbox-right (make-instance 'event-box))) (pack hbox eventbox-right :expand t :fill t) (add eventbox-right (setf vbox-right (make-instance 'v-box :homogeneous t))) (pack* vbox-right ((make-instance 'label :text "This is right eventbox.")) ((make-instance 'label :text "The blue ball is the bg image.")) ((make-instance 'label :text "Note that you can also set")) ((make-instance 'label :text "backgd color for the eventbox!"))) (setf (color eventbox-right :type :bg) "#BAFFB3") (setf (gsignal eventbox-right :draw :data "ball_blue3.png") #'expose-event)) (show window :all t) (gtk-main)
null
https://raw.githubusercontent.com/Kalimehtar/gtk-cffi/fbd8a40a2bbda29f81b1a95ed2530debfe2afe9b/examples/ex6.lisp
lisp
(draw-pixbuf (gdk-window widget) (style-field widget :bg-gc) pixbuf 0 0 dest-x dest-y) (let ((ch (child widget))) (when ch (propagate- widget ch event)))
424 (asdf:oos 'asdf:load-op :gtk-cffi) (defpackage #:test (:use #:common-lisp #:gdk-cffi #:gtk-cffi #:g-object-cffi) (:shadowing-import-from #:gtk-cffi #:image #:window)) (in-package #:test) (gtk-init) (defvar window) (defvar vbox) (defvar title) (defvar hbox) (defvar vbox-right) (setf window (make-instance 'window)) (setf (gsignal window :destroy) :gtk-main-quit (size-request window) '(600 240)) (add window (setf vbox (make-instance 'v-box))) (let ((title (make-instance 'label :text " Place a background image in GtkEventBox\n Part 2 - using GdkDrawable::draw_pixbuf()"))) (setf (font title) "Times New Roman Italic 10" (color title) "#0000ff" (size-request title) '(-1 40)) (pack* vbox title ((make-instance 'label)) ((setf hbox (make-instance 'h-box :homogeneous t)) :expand t :fill t))) (defun expose-event (widget context &optional (img "none")) (format t "~a ~a ~a~%" widget context img) (let* ((pixbuf (make-instance 'pixbuf :file img)) (w (width pixbuf)) (dest-x (- (width (allocation widget)) w)) (dest-y 0)) (format t "~a~%" pixbuf) (cl-cairo2:with-context ((make-instance 'cl-cairo2:context :pointer context)) (unless (cffi:null-pointer-p (cffi-objects:pointer pixbuf)) (cairo-set-source-pixbuf pixbuf dest-x dest-y) (cl-cairo2:paint)) (let ((ch (child widget))) (when ch (propagate-draw widget ch))))) t) (let ((eventbox-left (make-instance 'event-box)) (vbox-left (make-instance 'v-box :homogeneous t))) (pack hbox eventbox-left :expand t :fill t) (add eventbox-left vbox-left) (pack* vbox-left ((make-instance 'label :text "This is left eventbox.")) ((make-instance 'label :text "The green ball is the bg image.")) ((make-instance 'label :text "Note that this eventbox")) ((make-instance 'label :text "uses the default gray backgd color."))) (setf (gsignal eventbox-left :draw :data "ball_green3.png") #'expose-event)) (let ((eventbox-right (make-instance 'event-box))) (pack hbox eventbox-right :expand t :fill t) (add eventbox-right (setf vbox-right (make-instance 'v-box :homogeneous t))) (pack* vbox-right ((make-instance 'label :text "This is right eventbox.")) ((make-instance 'label :text "The blue ball is the bg image.")) ((make-instance 'label :text "Note that you can also set")) ((make-instance 'label :text "backgd color for the eventbox!"))) (setf (color eventbox-right :type :bg) "#BAFFB3") (setf (gsignal eventbox-right :draw :data "ball_blue3.png") #'expose-event)) (show window :all t) (gtk-main)
c460644e8674cc9febe822298eb187f58fffcceed38f350bad825ceea834321e
acieroid/scala-am
fPerm-2.scm
(letrec ((f (lambda (x) (+ (* x x) (* x x))))) (let ((f5 (f 5))) (let ((f3 (f 3))) (let ((f1 (f 1))) (let ((f4 (f 4))) (f 2))))))
null
https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/changesBenevolPaper/fPerm-2.scm
scheme
(letrec ((f (lambda (x) (+ (* x x) (* x x))))) (let ((f5 (f 5))) (let ((f3 (f 3))) (let ((f1 (f 1))) (let ((f4 (f 4))) (f 2))))))
f347c5be963981b657d0aacdab41bf7bf8e3fed8ad07f4214fe4bba34ecfa46c
lilactown/lilac.town
org.clj
(ns clj-org.org (:require [clj-org.util :refer [vec* selective-walk]] [clojure.string :as str] [clojure.zip :as zip] [hiccup.util :refer [escape-html]])) (defn header-value-for [field txt] (->> txt (re-seq (->> field (format "\\#\\+%s: (.+?)\n") re-pattern)) (map second) last)) (defn get-title [txt] (header-value-for "TITLE" txt)) (defn get-draft [txt] (->> txt (header-value-for "DRAFT") Boolean/valueOf)) (defn get-tags [txt] (header-value-for "TAGS" txt)) (defn strip-raw-html-tags-for-now [txt] (-> txt (clojure.string/replace #"#\+(?:HTML|ATTR_HTML):.+?\n" "") (clojure.string/replace #"(?sx) \#\+BEGIN_HTML\s* .*? \#\+END_HTML\s*" ""))) (defn ^:private descend? [el] (and (coll? el) (not (string? el)) (not (map? el)) (not= :pre (first el)) (not= :code (first el)))) (defn apply-fn-to-strings " Walk tree, applying f to each string. If multiple terms result, put them inside a :span tag. " [f tree] (let [f (fn [el] (let [[r0 & rs :as r] (f el)] (cond (string? r) r rs (vec* :span r) :else r0)))] (selective-walk f descend? string? tree))) (defn split-headers-and-body [txt] (let [[_ & rs] (re-find #"(?x) (\n* # Pick up trailing newlines (?:\# # Anything starting w/ '#' (?: # Not starting with: (?!\+(?:HTML:|CAPTION|BEGIN|ATTR_HTML)) # Swallow all lines that match .)+\n*)*) # Swallow everything else as group 2 ((?s)(?:.+)*)" txt)] rs)) (defn convert-body-to-sections [body] (let [matches (re-seq #"(?x) (?: (?: (\*+) \s+ (.+) \n )| ( (?: (?!\*+\s+) .*\n )* ) )" body)] (->> (for [[_ stars hdr body] matches] (if stars [(-> stars count ((partial str "h")) keyword) [:a {:id (str/lower-case hdr) :href (str/lower-case (str "#" (str/replace hdr " " "-")))} hdr]] body)) (remove #{""}) (vec* :div)))) (defn find-paragraphs [s] (->> s (re-seq #"(?x) ((?:.+\n?)+) | (?:\n{2,})") (map (comp (partial vec* :p) rest)))) (defn captionify [s] (->> s (re-seq #"(?sx) ( (?: (?!\[\[) . )+ )? (?: \[\[ (.+?) \]\] )?") (remove (partial every? empty?)) (mapcat (fn [[_ before img]] (cond (not before) [[:a {:href img} [:img {:src img :class "caption"}]]] (not img) [before] :else [before [:a {:href img} [:img {:src img :class "caption"}]]]))))) (defn linkify [s] (->> s (re-seq #"(?sx) ( (?: (?! \[\[.+?\]\[.+?\]\] ) . )+ )? (?: \[\[ (.+?) \]\[ (.+?) \]\] )?") (remove (partial every? empty?)) (mapcat (fn [[_ before lnk body]] (cond (not before) [[:a {:href lnk :target "_blank"} body]] (not lnk) [before] :else [before [:a {:href lnk :target "_blank"} body]]))))) (defn boldify [s] (->> s (re-seq #"(?sx) ( (?: (?!\*) . )+ )? (?: \* ( (?: (?!\*) . )+? ) \* )?") (remove (partial every? empty?)) (mapcat (fn [[_ before strong]] (cond (not before) [[:strong strong]] (not strong) [before] :else [before [:strong strong]]))))) (defn emify [s] (->> s (re-seq #"(?xs) ( (?: (?! (?: (?<=\s|^|\") \/ ([^\/]+) \/ ) ) . )+ )? (?: (?<=\s|^|\") \/ ([^\/]+) \/ )?") (remove (partial every? empty?)) (mapcat (fn [[_ before em]] (cond (not before) [[:em em]] (not em) [before] :else [before [:em em]]))))) (defn code-ify [s] (->> s (re-seq #"(?sx) ( (?: (?! = (.+?) = ) . )+ )? (?: = (.+?) = )?") (remove (partial every? empty?)) (mapcat (fn [[_ before code]] (cond (not before) [[:code code]] (not code) [before] :else [before [:code code]]))))) (defn strike-ify [s] (->> s (re-seq #"(?sx) ( (?: (?! \+ (?!\s+) (.+?) (?!\s+) \+ ) . )+ )? (?: \+ (?!\s+) (.+?) (?!\s+) \+ )?") (remove (partial every? empty?)) (mapcat (fn [[_ before strike]] (cond (not before) [[:strike strike]] (not strike) [before] :else [before [:strike strike]]))))) (defn hr-ify [s] (->> s (re-seq #"(?sx) ( (?: (?! (?<=^|\n) -{5,} ) . )+ )? ( (?<=^|\n) -{5,} )?") (remove (partial every? empty?)) (mapcat (fn [[_ before hr]] (cond (not before) [[:hr]] (not hr) [before] :else [before [:hr]]))))) (defn srcify [txt] (->> txt (re-seq #"(?xs) ( (?: (?! \#\+BEGIN_SRC\s+ \S+ \n .+? \#\+END_SRC\n ) . )+ )? (?: \#\+BEGIN_SRC\s+ (\S+) \n (.+?) \#\+END_SRC\n )?") (remove (partial every? empty?)) (mapcat (fn [[_ before lang block]] (cond (not before) [[:pre [:code {:class (str "lang-" lang)} block]]] (not block) [before] :else [before [:pre [:code {:class (str "lang-" lang)} block]]]))))) (defn quotify [txt] (->> txt (re-seq #"(?xs) ( (?: (?! \#\+BEGIN_QUOTE\n .+? \#\+END_QUOTE\n ) . )+ )? (?: \#\+BEGIN_QUOTE\n (.+?) \#\+END_QUOTE\n )?") (remove (partial every? empty?)) (mapcat (fn [[_ before block]] (cond (not before) [[:blockquote block]] (not block) [before] :else [before [:blockquote block]]))))) (defn example-ify [txt] (->> txt (re-seq #"(?xs) ( (?: (?! \#\+BEGIN_EXAMPLE\n .+? \#\+END_EXAMPLE\n ) . )+ )? (?: \#\+BEGIN_EXAMPLE\n (.+?) \#\+END_EXAMPLE\n )?") (remove (partial every? empty?)) (mapcat (fn [[_ before block]] (cond (not before) [[:pre (escape-html block)]] (not block) [before] :else [before [:pre (escape-html block)]]))))) (defn dashify [txt] (-> txt (clojure.string/replace #"---" "&#x2014;") (clojure.string/replace #"--" "&#x2013;"))) (defn get-plain-lists " Get plain lists and surrounding content out of txt. Defer actual parsing of plain lists. " [txt] (->> txt (re-seq #"(?xs) ( (?: (?! (?<=\n|^) \ * - \ + [^\n] +\n (?: (?<=\n) (?:\ *-\ +|\ +) [^\n]+ \n )* ) . )+ )? ( (?<=\n|^) \ * - \ + [^\n]+ \n (?: (?<=\n) (?:\ *-\ +|\ +) [^\n]+ \n )* )?") (map rest) (remove (partial every? empty?)))) (defn items-seq-to-tree " Convert seq of [level, content] pairs into a tree using zippers. Assumes deltas are a whole multiple of two for now. " [s] (loop [[[level x] & more] s prev 0 ret (-> [:ul] zip/vector-zip zip/down)] (if-not x (zip/root ret) ;; We're done. ;; ... otherwise, figure out where in tree to insert node: (recur more level (let [delta (/ (- prev level) 2)] (cond (> level prev) (-> ret (zip/insert-right [:ul]) zip/right zip/down (zip/insert-right [:li x]) zip/right) (< level prev) (-> ret (#(last (take (inc delta) (iterate zip/up %)))) (zip/insert-right [:li x]) zip/right) :else ;; Simple case -- same level: (-> ret (zip/insert-right [:li x]) zip/right))))))) (defn strip-leading-spaces " Strip leading spaces from every line in input. " [txt] (let [txt-lines (clojure.string/split txt #"\n") spaces-to-strip (->> txt-lines (map (partial re-find #"^( *)")) (map (comp count second)) (apply min))] (apply str (interleave (map (comp (partial apply str) (partial drop spaces-to-strip)) txt-lines) (repeat \newline))))) (defn parse-plain-list [txt] (->> txt strip-leading-spaces (re-seq #"(?xs) (?<=\n|^) (\ *)-\ + ( (?: (?!(?<=\n|^)\ *-\ ) . )+ )") (map rest) (map (juxt (comp count first) second)) items-seq-to-tree)) (defn plain-listify [txt] (->> txt get-plain-lists (mapcat (fn [[before-txt list-txt]] (cond (not before-txt) [(parse-plain-list list-txt)] (not list-txt) [before-txt] :else [before-txt (parse-plain-list list-txt)]))))) (defn tree-linkify [tree] (apply-fn-to-strings linkify tree)) (defn tree-captionify [tree] (apply-fn-to-strings captionify tree)) (defn tree-boldify [tree] (apply-fn-to-strings boldify tree)) (defn tree-emify [tree] (apply-fn-to-strings emify tree)) (defn tree-code-ify [tree] (apply-fn-to-strings code-ify tree)) (defn tree-strike-ify [tree] (apply-fn-to-strings strike-ify tree)) (defn tree-hr-ify [tree] (apply-fn-to-strings hr-ify tree)) (defn tree-srcify [tree] (apply-fn-to-strings srcify tree)) (defn tree-example-ify [tree] (apply-fn-to-strings example-ify tree)) (defn tree-pars [tree] (apply-fn-to-strings find-paragraphs tree)) (defn tree-dashify [tree] (apply-fn-to-strings dashify tree)) (defn tree-listify [tree] (apply-fn-to-strings plain-listify tree)) (defn tree-quotify [tree] (apply-fn-to-strings quotify tree)) (defn ^:private txt->lines [txt] (clojure.string/split txt #"\n")) (defn parse-org [txt] (let [title (get-title txt) [hdrs body] (split-headers-and-body txt) slurped-lines (-> txt escape-html txt->lines) content (-> body strip-raw-html-tags-for-now convert-body-to-sections tree-srcify tree-example-ify tree-quotify tree-listify tree-pars tree-code-ify tree-linkify tree-captionify tree-boldify tree-emify tree-strike-ify tree-hr-ify tree-dashify)] {:title title :headers hdrs :content content})) (comment (parse-org " Asdf =*foo*= jkl ") (parse-org " * testing 123 #+BEGIN_SRC clojure Foo bar baz *1234* 123 #+END_SRC ") (parse-org "#+TITLE: This is an Org Mode file. * This is the outer section ** This is an inner section Inner section body -- /with italic text/! And *bold text* too. - Plain List Item 1 - Plain List Item 2 [[][A link to a Web site]] ") ;;=> {:title "This is an Org Mode file.", :headers "\n#+TITLE: This is an Org Mode file.\n\n", :content [:div [:h1 [:p "This is the outer section"]] [:h2 [:p "This is an inner section"]] [:span [:p [:span [:span "Inner section body &#x2013; " [:em "with italic text"] "! And "] [:strong "bold text"] " too.\n"]] [:ul [:li [:p "Plain List Item 1\n"]] [:li [:p "Plain List Item 2\n"]]] [:p [:span [:a {:href ""} "A link to a Web site"] "\n"]]]]})
null
https://raw.githubusercontent.com/lilactown/lilac.town/295669e4511e79877da14232457dea26f098acd8/src/clj_org/org.clj
clojure
We're done. ... otherwise, figure out where in tree to insert node: Simple case -- same level: =>
(ns clj-org.org (:require [clj-org.util :refer [vec* selective-walk]] [clojure.string :as str] [clojure.zip :as zip] [hiccup.util :refer [escape-html]])) (defn header-value-for [field txt] (->> txt (re-seq (->> field (format "\\#\\+%s: (.+?)\n") re-pattern)) (map second) last)) (defn get-title [txt] (header-value-for "TITLE" txt)) (defn get-draft [txt] (->> txt (header-value-for "DRAFT") Boolean/valueOf)) (defn get-tags [txt] (header-value-for "TAGS" txt)) (defn strip-raw-html-tags-for-now [txt] (-> txt (clojure.string/replace #"#\+(?:HTML|ATTR_HTML):.+?\n" "") (clojure.string/replace #"(?sx) \#\+BEGIN_HTML\s* .*? \#\+END_HTML\s*" ""))) (defn ^:private descend? [el] (and (coll? el) (not (string? el)) (not (map? el)) (not= :pre (first el)) (not= :code (first el)))) (defn apply-fn-to-strings " Walk tree, applying f to each string. If multiple terms result, put them inside a :span tag. " [f tree] (let [f (fn [el] (let [[r0 & rs :as r] (f el)] (cond (string? r) r rs (vec* :span r) :else r0)))] (selective-walk f descend? string? tree))) (defn split-headers-and-body [txt] (let [[_ & rs] (re-find #"(?x) (\n* # Pick up trailing newlines (?:\# # Anything starting w/ '#' (?: # Not starting with: (?!\+(?:HTML:|CAPTION|BEGIN|ATTR_HTML)) # Swallow all lines that match .)+\n*)*) # Swallow everything else as group 2 ((?s)(?:.+)*)" txt)] rs)) (defn convert-body-to-sections [body] (let [matches (re-seq #"(?x) (?: (?: (\*+) \s+ (.+) \n )| ( (?: (?!\*+\s+) .*\n )* ) )" body)] (->> (for [[_ stars hdr body] matches] (if stars [(-> stars count ((partial str "h")) keyword) [:a {:id (str/lower-case hdr) :href (str/lower-case (str "#" (str/replace hdr " " "-")))} hdr]] body)) (remove #{""}) (vec* :div)))) (defn find-paragraphs [s] (->> s (re-seq #"(?x) ((?:.+\n?)+) | (?:\n{2,})") (map (comp (partial vec* :p) rest)))) (defn captionify [s] (->> s (re-seq #"(?sx) ( (?: (?!\[\[) . )+ )? (?: \[\[ (.+?) \]\] )?") (remove (partial every? empty?)) (mapcat (fn [[_ before img]] (cond (not before) [[:a {:href img} [:img {:src img :class "caption"}]]] (not img) [before] :else [before [:a {:href img} [:img {:src img :class "caption"}]]]))))) (defn linkify [s] (->> s (re-seq #"(?sx) ( (?: (?! \[\[.+?\]\[.+?\]\] ) . )+ )? (?: \[\[ (.+?) \]\[ (.+?) \]\] )?") (remove (partial every? empty?)) (mapcat (fn [[_ before lnk body]] (cond (not before) [[:a {:href lnk :target "_blank"} body]] (not lnk) [before] :else [before [:a {:href lnk :target "_blank"} body]]))))) (defn boldify [s] (->> s (re-seq #"(?sx) ( (?: (?!\*) . )+ )? (?: \* ( (?: (?!\*) . )+? ) \* )?") (remove (partial every? empty?)) (mapcat (fn [[_ before strong]] (cond (not before) [[:strong strong]] (not strong) [before] :else [before [:strong strong]]))))) (defn emify [s] (->> s (re-seq #"(?xs) ( (?: (?! (?: (?<=\s|^|\") \/ ([^\/]+) \/ ) ) . )+ )? (?: (?<=\s|^|\") \/ ([^\/]+) \/ )?") (remove (partial every? empty?)) (mapcat (fn [[_ before em]] (cond (not before) [[:em em]] (not em) [before] :else [before [:em em]]))))) (defn code-ify [s] (->> s (re-seq #"(?sx) ( (?: (?! = (.+?) = ) . )+ )? (?: = (.+?) = )?") (remove (partial every? empty?)) (mapcat (fn [[_ before code]] (cond (not before) [[:code code]] (not code) [before] :else [before [:code code]]))))) (defn strike-ify [s] (->> s (re-seq #"(?sx) ( (?: (?! \+ (?!\s+) (.+?) (?!\s+) \+ ) . )+ )? (?: \+ (?!\s+) (.+?) (?!\s+) \+ )?") (remove (partial every? empty?)) (mapcat (fn [[_ before strike]] (cond (not before) [[:strike strike]] (not strike) [before] :else [before [:strike strike]]))))) (defn hr-ify [s] (->> s (re-seq #"(?sx) ( (?: (?! (?<=^|\n) -{5,} ) . )+ )? ( (?<=^|\n) -{5,} )?") (remove (partial every? empty?)) (mapcat (fn [[_ before hr]] (cond (not before) [[:hr]] (not hr) [before] :else [before [:hr]]))))) (defn srcify [txt] (->> txt (re-seq #"(?xs) ( (?: (?! \#\+BEGIN_SRC\s+ \S+ \n .+? \#\+END_SRC\n ) . )+ )? (?: \#\+BEGIN_SRC\s+ (\S+) \n (.+?) \#\+END_SRC\n )?") (remove (partial every? empty?)) (mapcat (fn [[_ before lang block]] (cond (not before) [[:pre [:code {:class (str "lang-" lang)} block]]] (not block) [before] :else [before [:pre [:code {:class (str "lang-" lang)} block]]]))))) (defn quotify [txt] (->> txt (re-seq #"(?xs) ( (?: (?! \#\+BEGIN_QUOTE\n .+? \#\+END_QUOTE\n ) . )+ )? (?: \#\+BEGIN_QUOTE\n (.+?) \#\+END_QUOTE\n )?") (remove (partial every? empty?)) (mapcat (fn [[_ before block]] (cond (not before) [[:blockquote block]] (not block) [before] :else [before [:blockquote block]]))))) (defn example-ify [txt] (->> txt (re-seq #"(?xs) ( (?: (?! \#\+BEGIN_EXAMPLE\n .+? \#\+END_EXAMPLE\n ) . )+ )? (?: \#\+BEGIN_EXAMPLE\n (.+?) \#\+END_EXAMPLE\n )?") (remove (partial every? empty?)) (mapcat (fn [[_ before block]] (cond (not before) [[:pre (escape-html block)]] (not block) [before] :else [before [:pre (escape-html block)]]))))) (defn dashify [txt] (-> txt (clojure.string/replace #"---" "&#x2014;") (clojure.string/replace #"--" "&#x2013;"))) (defn get-plain-lists " Get plain lists and surrounding content out of txt. Defer actual parsing of plain lists. " [txt] (->> txt (re-seq #"(?xs) ( (?: (?! (?<=\n|^) \ * - \ + [^\n] +\n (?: (?<=\n) (?:\ *-\ +|\ +) [^\n]+ \n )* ) . )+ )? ( (?<=\n|^) \ * - \ + [^\n]+ \n (?: (?<=\n) (?:\ *-\ +|\ +) [^\n]+ \n )* )?") (map rest) (remove (partial every? empty?)))) (defn items-seq-to-tree " Convert seq of [level, content] pairs into a tree using zippers. Assumes deltas are a whole multiple of two for now. " [s] (loop [[[level x] & more] s prev 0 ret (-> [:ul] zip/vector-zip zip/down)] (if-not x (recur more level (let [delta (/ (- prev level) 2)] (cond (> level prev) (-> ret (zip/insert-right [:ul]) zip/right zip/down (zip/insert-right [:li x]) zip/right) (< level prev) (-> ret (#(last (take (inc delta) (iterate zip/up %)))) (zip/insert-right [:li x]) zip/right) (-> ret (zip/insert-right [:li x]) zip/right))))))) (defn strip-leading-spaces " Strip leading spaces from every line in input. " [txt] (let [txt-lines (clojure.string/split txt #"\n") spaces-to-strip (->> txt-lines (map (partial re-find #"^( *)")) (map (comp count second)) (apply min))] (apply str (interleave (map (comp (partial apply str) (partial drop spaces-to-strip)) txt-lines) (repeat \newline))))) (defn parse-plain-list [txt] (->> txt strip-leading-spaces (re-seq #"(?xs) (?<=\n|^) (\ *)-\ + ( (?: (?!(?<=\n|^)\ *-\ ) . )+ )") (map rest) (map (juxt (comp count first) second)) items-seq-to-tree)) (defn plain-listify [txt] (->> txt get-plain-lists (mapcat (fn [[before-txt list-txt]] (cond (not before-txt) [(parse-plain-list list-txt)] (not list-txt) [before-txt] :else [before-txt (parse-plain-list list-txt)]))))) (defn tree-linkify [tree] (apply-fn-to-strings linkify tree)) (defn tree-captionify [tree] (apply-fn-to-strings captionify tree)) (defn tree-boldify [tree] (apply-fn-to-strings boldify tree)) (defn tree-emify [tree] (apply-fn-to-strings emify tree)) (defn tree-code-ify [tree] (apply-fn-to-strings code-ify tree)) (defn tree-strike-ify [tree] (apply-fn-to-strings strike-ify tree)) (defn tree-hr-ify [tree] (apply-fn-to-strings hr-ify tree)) (defn tree-srcify [tree] (apply-fn-to-strings srcify tree)) (defn tree-example-ify [tree] (apply-fn-to-strings example-ify tree)) (defn tree-pars [tree] (apply-fn-to-strings find-paragraphs tree)) (defn tree-dashify [tree] (apply-fn-to-strings dashify tree)) (defn tree-listify [tree] (apply-fn-to-strings plain-listify tree)) (defn tree-quotify [tree] (apply-fn-to-strings quotify tree)) (defn ^:private txt->lines [txt] (clojure.string/split txt #"\n")) (defn parse-org [txt] (let [title (get-title txt) [hdrs body] (split-headers-and-body txt) slurped-lines (-> txt escape-html txt->lines) content (-> body strip-raw-html-tags-for-now convert-body-to-sections tree-srcify tree-example-ify tree-quotify tree-listify tree-pars tree-code-ify tree-linkify tree-captionify tree-boldify tree-emify tree-strike-ify tree-hr-ify tree-dashify)] {:title title :headers hdrs :content content})) (comment (parse-org " Asdf =*foo*= jkl ") (parse-org " * testing 123 #+BEGIN_SRC clojure Foo bar baz *1234* 123 #+END_SRC ") (parse-org "#+TITLE: This is an Org Mode file. * This is the outer section ** This is an inner section Inner section body -- /with italic text/! And *bold text* too. - Plain List Item 1 - Plain List Item 2 [[][A link to a Web site]] ") {:title "This is an Org Mode file.", :headers "\n#+TITLE: This is an Org Mode file.\n\n", :content [:div [:h1 [:p "This is the outer section"]] [:h2 [:p "This is an inner section"]] [:span [:p [:span [:span "Inner section body &#x2013; " [:em "with italic text"] "! And "] [:strong "bold text"] " too.\n"]] [:ul [:li [:p "Plain List Item 1\n"]] [:li [:p "Plain List Item 2\n"]]] [:p [:span [:a {:href ""} "A link to a Web site"] "\n"]]]]})
5407f57c1558f88d99c9e27b7ab109019071664130d6defa477940aa8a2b176d
lixiangqi/medic
src2-medic.rkt
#lang medic (layer layer1 (in #:module "src2.rkt" match two instances of ( inc - counter ) [at (inc-counter) [on-entry @log{[1] in @function-name : int-counter}]] match two instances of ( + x 1 ) [at (+ x 1) #:before (inc-counter) [on-entry @log{[2]in @function-name : (+ x 1)}]] only match ( + x 1 ) in g function [at (+ x 1) #:before (begin (define x (inc 4)) _) [on-entry @log{[3]in @function-name : (+ x 1)}]] [(g) [at (+ x 1) [on-entry @log{[4]in @function-name : (+ x 1)}]]] ; only match (inc-counter) in function g [at (inc-counter) #:before (define x (inc 4)) #:after (+ x 1) (on-entry @log{[5]in @function-name : (inc-counter)})] [at (inc-counter) #:before (define x (inc _)) #:after (+ x 1) (on-entry @log{[6]in @function-name : (inc-counter)})]))
null
https://raw.githubusercontent.com/lixiangqi/medic/0920090d3c77d6873b8481841622a5f2d13a732c/demos/demo2/src2-medic.rkt
racket
only match (inc-counter) in function g
#lang medic (layer layer1 (in #:module "src2.rkt" match two instances of ( inc - counter ) [at (inc-counter) [on-entry @log{[1] in @function-name : int-counter}]] match two instances of ( + x 1 ) [at (+ x 1) #:before (inc-counter) [on-entry @log{[2]in @function-name : (+ x 1)}]] only match ( + x 1 ) in g function [at (+ x 1) #:before (begin (define x (inc 4)) _) [on-entry @log{[3]in @function-name : (+ x 1)}]] [(g) [at (+ x 1) [on-entry @log{[4]in @function-name : (+ x 1)}]]] [at (inc-counter) #:before (define x (inc 4)) #:after (+ x 1) (on-entry @log{[5]in @function-name : (inc-counter)})] [at (inc-counter) #:before (define x (inc _)) #:after (+ x 1) (on-entry @log{[6]in @function-name : (inc-counter)})]))
7b17f7d378989c88e8d36ab720d576d5063eb6e9d7395795d2e6d483e0734ee1
hspec/hspec
Sort.hs
-- | -- /NOTE:/ This module is not meant for public consumption. For user documentation look at -discover.html . module Test.Hspec.Discover.Sort ( sortNaturallyBy , NaturalSortKey , naturalSortKey ) where import Control.Arrow import Data.Char import Data.List import Data.Ord sortNaturallyBy :: (a -> (String, Int)) -> [a] -> [a] sortNaturallyBy f = sortBy (comparing ((\ (k, t) -> (naturalSortKey k, t)) . f)) newtype NaturalSortKey = NaturalSortKey [Chunk] deriving (Eq, Ord) data Chunk = Numeric Integer Int | Textual [(Char, Char)] deriving (Eq, Ord) naturalSortKey :: String -> NaturalSortKey naturalSortKey = NaturalSortKey . chunks where chunks [] = [] chunks s@(c:_) | isDigit c = Numeric (read num) (length num) : chunks afterNum | otherwise = Textual (map (toLower &&& id) str) : chunks afterStr where (num, afterNum) = span isDigit s (str, afterStr) = break isDigit s
null
https://raw.githubusercontent.com/hspec/hspec/5029c7c2acaf743f17120619279fc76a0fb97e7a/hspec-discover/src/Test/Hspec/Discover/Sort.hs
haskell
| /NOTE:/ This module is not meant for public consumption. For user
documentation look at -discover.html . module Test.Hspec.Discover.Sort ( sortNaturallyBy , NaturalSortKey , naturalSortKey ) where import Control.Arrow import Data.Char import Data.List import Data.Ord sortNaturallyBy :: (a -> (String, Int)) -> [a] -> [a] sortNaturallyBy f = sortBy (comparing ((\ (k, t) -> (naturalSortKey k, t)) . f)) newtype NaturalSortKey = NaturalSortKey [Chunk] deriving (Eq, Ord) data Chunk = Numeric Integer Int | Textual [(Char, Char)] deriving (Eq, Ord) naturalSortKey :: String -> NaturalSortKey naturalSortKey = NaturalSortKey . chunks where chunks [] = [] chunks s@(c:_) | isDigit c = Numeric (read num) (length num) : chunks afterNum | otherwise = Textual (map (toLower &&& id) str) : chunks afterStr where (num, afterNum) = span isDigit s (str, afterStr) = break isDigit s
c14a8f4f709695ede3f77348728a25b3f3ded420da60f3f8de3944b7eae98a49
pixlsus/registry.gimp.org_static
Lightning.scm
;;------ Lightning ------------------------- ; Create a lightning effect using the plasma plug-in (define (script-fu-lightning width height hue sat turbulence desat) ; Create an img and a layer. width <-> height so we can rotate later (let* ((img (car (gimp-image-new height width 0))) (mainLayer (car (gimp-layer-new img height width 0 "Lightning" 100 0))) (secondLayer (car (gimp-layer-new img height width 0 "Plasma Layer" 100 6))) ) (gimp-image-undo-disable img) (gimp-image-add-layer img mainLayer 0) (gimp-image-add-layer img secondLayer -1) ( gimp - context - set - gradient " FG to BG ( RGB ) " ) -- set in gimp - edit - blend (gimp-context-set-foreground '(0 0 0)) (gimp-context-set-background '(191 191 191)) (gimp-edit-blend mainLayer 0 0 0 100 0 0 FALSE FALSE 1 0.0 TRUE 0 0 0 height) (plug-in-plasma 1 img secondLayer (rand) turbulence) (gimp-desaturate-full secondLayer desat) Merge the second with the first and assign the resulting layer back to the first (set! mainLayer (car (gimp-image-merge-down img secondLayer 0))) (gimp-invert mainLayer) (gimp-levels mainLayer 0 127 255 0.1 0 255) TODO - convert RGB to HSV and use SF - COLOR (gimp-image-rotate img 0) ; Rotate so the lightning bolt is vertical (gimp-display-new img) (gimp-image-undo-enable img) )) (script-fu-register "script-fu-lightning" "<Toolbox>/Xtns/Patterns/Lightning" "Creates lightning" "David Hari" "Taken from tomcat's lightning tutorial - /" "2008" "" SF-VALUE "Width" "256" SF-VALUE "Height" "256" SF-ADJUSTMENT "Hue" '(250 0 360 1 5 0 0) SF-ADJUSTMENT "Saturation" '(100 0 100 1 10 0 0) SF-ADJUSTMENT "Turbulence" '(0.4 0.1 2.0 0.1 0.1 1 0) SF-OPTION "Desaturation method" '("Lightness" "Luminosity") ) ;;------ Lightning Animation --------------- ; Renders the lightning effect as an animation. (define (script-fu-anim-lightning width height hue sat frames turbStart turbEnd randMovement desat) Create the img . height so we can rotate later (let* ((img (car (gimp-image-new height width 0))) (randNum (rand)) (turbVal turbStart) (i 0) ) (gimp-image-undo-disable img) (gimp-context-set-foreground '(0 0 0)) (gimp-context-set-background '(191 191 191)) (while (< i frames) ;; TODO - put frame no. in string (let* ((mainLayer (car (gimp-layer-new img height width 0 "Frame" 100 0))) (secondLayer (car (gimp-layer-new img height width 0 "Plasma Layer" 100 6))) ) (gimp-image-add-layer img mainLayer -1) (gimp-image-add-layer img secondLayer -1) (gimp-edit-blend mainLayer 0 0 0 100 0 0 FALSE FALSE 1 0.0 TRUE 0 0 0 height) ; Increment the turbulence to reach the end value (set! turbVal (+ turbVal (/ (- turbEnd turbStart) frames))) (plug-in-plasma 1 img secondLayer randNum turbVal) (gimp-desaturate-full secondLayer desat) Merge the second with the first and assign the resulting layer back to the first (set! mainLayer (car (gimp-image-merge-down img secondLayer 0))) (gimp-invert mainLayer) (gimp-levels mainLayer 0 127 255 0.1 0 255) TODO - convert RGB to HSV (if (= randMovement TRUE) (set! randNum (rand)) ; Pick a new random number '() ) (set! i (+ i 1)) ) ) (gimp-image-rotate img 0) ; Rotate so the lightning bolt is vertical (gimp-display-new img) (gimp-image-undo-enable img) )) (script-fu-register "script-fu-anim-lightning" "<Toolbox>/Xtns/Anim/Lightning" "Creates the lightning effect as an animation." "David Hari" "" "2008" "" SF-VALUE "Width" "256" SF-VALUE "Height" "256" SF-ADJUSTMENT "Hue" '(250 0 360 1 5 0 0) SF-ADJUSTMENT "Saturation" '(100 0 100 1 10 0 0) SF-ADJUSTMENT "No. of frames" '(10 1 100 1 5 0 1) SF-ADJUSTMENT "Turbulence start" '(0.4 0.1 2.0 0.1 0.1 1 0) SF-ADJUSTMENT "Turbulence end" '(1.0 0.1 2.0 0.1 0.1 1 0) SF-TOGGLE "Random movement" TRUE SF-OPTION "Desaturation method" '("Lightness" "Luminosity") )
null
https://raw.githubusercontent.com/pixlsus/registry.gimp.org_static/ffcde7400f402728373ff6579947c6ffe87d1a5e/registry.gimp.org/files/Lightning.scm
scheme
------ Lightning ------------------------- Create a lightning effect using the plasma plug-in Create an img and a layer. width <-> height so we can rotate later Rotate so the lightning bolt is vertical ------ Lightning Animation --------------- Renders the lightning effect as an animation. TODO - put frame no. in string Increment the turbulence to reach the end value Pick a new random number Rotate so the lightning bolt is vertical
(define (script-fu-lightning width height hue sat turbulence desat) (let* ((img (car (gimp-image-new height width 0))) (mainLayer (car (gimp-layer-new img height width 0 "Lightning" 100 0))) (secondLayer (car (gimp-layer-new img height width 0 "Plasma Layer" 100 6))) ) (gimp-image-undo-disable img) (gimp-image-add-layer img mainLayer 0) (gimp-image-add-layer img secondLayer -1) ( gimp - context - set - gradient " FG to BG ( RGB ) " ) -- set in gimp - edit - blend (gimp-context-set-foreground '(0 0 0)) (gimp-context-set-background '(191 191 191)) (gimp-edit-blend mainLayer 0 0 0 100 0 0 FALSE FALSE 1 0.0 TRUE 0 0 0 height) (plug-in-plasma 1 img secondLayer (rand) turbulence) (gimp-desaturate-full secondLayer desat) Merge the second with the first and assign the resulting layer back to the first (set! mainLayer (car (gimp-image-merge-down img secondLayer 0))) (gimp-invert mainLayer) (gimp-levels mainLayer 0 127 255 0.1 0 255) TODO - convert RGB to HSV and use SF - COLOR (gimp-display-new img) (gimp-image-undo-enable img) )) (script-fu-register "script-fu-lightning" "<Toolbox>/Xtns/Patterns/Lightning" "Creates lightning" "David Hari" "Taken from tomcat's lightning tutorial - /" "2008" "" SF-VALUE "Width" "256" SF-VALUE "Height" "256" SF-ADJUSTMENT "Hue" '(250 0 360 1 5 0 0) SF-ADJUSTMENT "Saturation" '(100 0 100 1 10 0 0) SF-ADJUSTMENT "Turbulence" '(0.4 0.1 2.0 0.1 0.1 1 0) SF-OPTION "Desaturation method" '("Lightness" "Luminosity") ) (define (script-fu-anim-lightning width height hue sat frames turbStart turbEnd randMovement desat) Create the img . height so we can rotate later (let* ((img (car (gimp-image-new height width 0))) (randNum (rand)) (turbVal turbStart) (i 0) ) (gimp-image-undo-disable img) (gimp-context-set-foreground '(0 0 0)) (gimp-context-set-background '(191 191 191)) (let* ((mainLayer (car (gimp-layer-new img height width 0 "Frame" 100 0))) (secondLayer (car (gimp-layer-new img height width 0 "Plasma Layer" 100 6))) ) (gimp-image-add-layer img mainLayer -1) (gimp-image-add-layer img secondLayer -1) (gimp-edit-blend mainLayer 0 0 0 100 0 0 FALSE FALSE 1 0.0 TRUE 0 0 0 height) (set! turbVal (+ turbVal (/ (- turbEnd turbStart) frames))) (plug-in-plasma 1 img secondLayer randNum turbVal) (gimp-desaturate-full secondLayer desat) Merge the second with the first and assign the resulting layer back to the first (set! mainLayer (car (gimp-image-merge-down img secondLayer 0))) (gimp-invert mainLayer) (gimp-levels mainLayer 0 127 255 0.1 0 255) TODO - convert RGB to HSV (if (= randMovement TRUE) '() ) (set! i (+ i 1)) ) ) (gimp-display-new img) (gimp-image-undo-enable img) )) (script-fu-register "script-fu-anim-lightning" "<Toolbox>/Xtns/Anim/Lightning" "Creates the lightning effect as an animation." "David Hari" "" "2008" "" SF-VALUE "Width" "256" SF-VALUE "Height" "256" SF-ADJUSTMENT "Hue" '(250 0 360 1 5 0 0) SF-ADJUSTMENT "Saturation" '(100 0 100 1 10 0 0) SF-ADJUSTMENT "No. of frames" '(10 1 100 1 5 0 1) SF-ADJUSTMENT "Turbulence start" '(0.4 0.1 2.0 0.1 0.1 1 0) SF-ADJUSTMENT "Turbulence end" '(1.0 0.1 2.0 0.1 0.1 1 0) SF-TOGGLE "Random movement" TRUE SF-OPTION "Desaturation method" '("Lightness" "Luminosity") )
96a88e1e484612c72a4e773ef69077d5ca9dfca9adf0635ff937b12fa777b392
0x0f0f0f/gobba
primutil.ml
open Types let parser = Parser.toplevel Lexer.token (** An helper function that helps extracting closures from strings, to be used as functions in the standard library. An empty environment is used since primitives in the standard library should not be able to access external values TODO: compute at compile time *) let lambda_of_string name str = try (match (List.hd (parser (Lexing.from_string (str ^ "\n")))) with | Expr(Lambda(p, body)) -> LazyExpression (Lambda(p, body)) | _ -> failwith "standard library definition error") with | e -> failwith ("standard library definition error in " ^ name ^ ": \n" ^ (Printexc.print_backtrace stderr; Printexc.to_string e))
null
https://raw.githubusercontent.com/0x0f0f0f/gobba/61092207438fb102e36245c46c27a711b8f357cb/lib/primitives/primutil.ml
ocaml
* An helper function that helps extracting closures from strings, to be used as functions in the standard library. An empty environment is used since primitives in the standard library should not be able to access external values TODO: compute at compile time
open Types let parser = Parser.toplevel Lexer.token let lambda_of_string name str = try (match (List.hd (parser (Lexing.from_string (str ^ "\n")))) with | Expr(Lambda(p, body)) -> LazyExpression (Lambda(p, body)) | _ -> failwith "standard library definition error") with | e -> failwith ("standard library definition error in " ^ name ^ ": \n" ^ (Printexc.print_backtrace stderr; Printexc.to_string e))
10a53a36da384088c01e0613039dbb9c54ed115b5816aa30c4b0ca2f0cd5d8a3
cljdoc/cljdoc
fixref.clj
(ns cljdoc.util.fixref "Utilities to rewrite, or support the rewrite of, references in markdown rendered to HTML. For example, external links are rewritten to include nofollow, links to ingested SCM articles are rewritten to their slugs, and scm relative references are rewritten to point to SCM." (:require [clojure.tools.logging :as log] [clojure.java.io :as io] [clojure.string :as string] [cljdoc.util.scm :as scm] [cljdoc.server.routes :as routes]) (:import (org.jsoup Jsoup) (org.jsoup.nodes Document Element Attributes))) (set! *warn-on-reflection* true) (defn- absolute-uri? [s] (or (string/starts-with? s "http://") (string/starts-with? s "https://"))) (defn- anchor-uri? [s] (string/starts-with? s "#")) (defn- split-relpath-anchor "Returns `[relpath anchor]` for path `s`" [s] (rest (re-find #"/?([^#]*)(#.*$)?" s))) (defn- root-relative-path? [s] (string/starts-with? s "/")) (defn- get-cljdoc-url-prefix [s] (first (filter #(string/starts-with? s %) ["" ""]))) (defn- rebase-path "Rebase path `s1` to directory of relative path `s2`. When path `s1` is absolute it is returned." [s1 s2] (if (root-relative-path? s1) s1 (let [p2-dir (if (string/ends-with? s2 "/") s2 (.getParent (io/file s2)))] (str (io/file p2-dir s1))))) (defn- normalize-path "Resolves relative `..` and `.` in path `s`" [s] (str (.normalize (.toPath (io/file s))))) (defn- path-relative-to "Returns `file-path` from `from-dir-path`. Both paths must be relative or absolute." [file-path from-dir-path] (str (.relativize (.toPath (io/file from-dir-path)) (.toPath (io/file file-path))))) (defn- error-ref "When the scm-file-path is unknown, as is currently the case for docstrings, we cannot handle relative refs and return a error ref." [ref scm-file-path] (when (and (not scm-file-path) (not (root-relative-path? ref))) "#!cljdoc-error!ref-must-be-root-relative!")) (defn- fix-link "Return the cljdoc location for a given URL `href` or it's page on GitHub/GitLab etc." ^String [href {:keys [scm-file-path target-path scm-base uri-map] :as _opts}] (or (error-ref href scm-file-path) (let [[href-rel-to-scm-base anchor] (-> href (rebase-path scm-file-path) normalize-path split-relpath-anchor)] (if-let [href-local-doc (get uri-map href-rel-to-scm-base)] (str (if target-path (path-relative-to href-local-doc target-path) href-local-doc) anchor) (str scm-base href-rel-to-scm-base anchor))))) (defn- fix-image ^String [src {:keys [scm-file-path scm-base]}] (or (error-ref src scm-file-path) (let [suffix (when (and (= :github (scm/provider scm-base)) (string/ends-with? src ".svg")) "?sanitize=true")] (if (root-relative-path? src) (str scm-base (subs src 1) suffix) (str scm-base (-> src (rebase-path scm-file-path) normalize-path) suffix))))) (defn uri-mapping "Returns lookup map where key is SCM repo relative file and value is cljdoc root relative `version-entity` slug path at for all `docs`. Ex: `{\"README.md\" \"/d/lread/cljdoc-exerciser/1.0.34/doc/readme}`" [version-entity docs] (->> docs (map (fn [d] [(-> d :attrs :cljdoc.doc/source-file) (->> (-> d :attrs :slug-path) (string/join "/") (assoc version-entity :article-slug) (routes/url-for :artifact/doc :path-params))])) (into {}))) (defn- parse-html ^Document [^String html-str] (let [doc (Jsoup/parse html-str) props (.outputSettings doc)] (.prettyPrint props false) doc)) (defn fix "Rewrite references in HTML produced from rendering markdown. Markdown from SCM can contains references to images and articles. Relative <a> links are links to SCM: * an SCM link that is an article that has been imported to cljdoc => local link (slug for online, html file for offline) * else => SCM formatted (aka blob) link at correct revision Absolute <a> links * when relinking back to cljdoc.org => to root relative to support local testing * else => converted to nofollow link (this includes links rewritten to point SCM) Relative <img> references are links to SCM: - are converted to SCM raw references at correct revision - svg files from GitHub add special querystring parameters * `:html-str` the html of the content we are fixing * `fix-opts` map contains * `:scm-file-path` SCM repo home relative path of content * `:target-path` local relative destination path of content, if provided, used to relativize link paths local path (used for offline bundles) * `:uri-map` - map of relative scm paths to cljdoc doc slugs (or for offline bundles html files) * `:scm` - scm-info from bundle used to link to correct SCM file revision" [html-str {:keys [scm-file-path target-path scm uri-map] :as _fix-opts}] (let [doc (parse-html html-str)] (doseq [^Attributes scm-relative-link (->> (.select doc "a") (map (fn [^Element e] (.attributes e))) (remove (fn [^Attributes a] (= "wikilink" (.get a "data-source")))) (remove (fn [^Attributes a] (absolute-uri? (.get a "href")))) (remove (fn [^Attributes a] (anchor-uri? (.get a "href")))))] (let [fixed-link (fix-link (.get scm-relative-link "href") {:scm-file-path scm-file-path :target-path target-path :scm-base (scm/rev-formatted-base-url scm) :uri-map uri-map})] (.put scm-relative-link "href" fixed-link))) (doseq [^Attributes scm-relative-img (->> (.select doc "img") (map (fn [^Element e] (.attributes e))) (remove (fn [^Attributes a] (absolute-uri? (.get a "src")))))] (.put scm-relative-img "src" (fix-image (.get scm-relative-img "src") {:scm-file-path scm-file-path :scm-base (scm/rev-raw-base-url scm)}))) (doseq [^Attributes absolute-link (->> (.select doc "a") (map (fn [^Element e] (.attributes e))) (filter (fn [^Attributes a] (absolute-uri? (.get a "href")))))] (let [href (.get absolute-link "href")] (if-let [cljdoc-prefix (get-cljdoc-url-prefix href)] (.put absolute-link "href" (subs href (count cljdoc-prefix))) (.put absolute-link "rel" "nofollow")))) (.. doc body html toString))) ;; Some utilities to find which file in a git repository corresponds ;; to a file where a `def` is coming from -------------------------- (defn- find-full-filepath "Return best match for `jar-file-path` source in `known-git-file-paths`." [known-git-file-paths jar-file-path] (let [matches (filter #(string/ends-with? (str "/" %) (str "/" jar-file-path)) known-git-file-paths)] (if (= 1 (count matches)) (first matches) ;; choose shortest path where file sits under what looks like a src dir (let [best-guess (->> matches (filter (fn [git-file] (let [src-path (str "/" (subs git-file 0 (- (count git-file) (count jar-file-path))))] (string/includes? src-path "/src/")))) maybe 2 paths are same length , so ensure a consistent result by sorting first (sort-by count) first)] (if best-guess (log/warnf "Did not find unique file on SCM for jar file %s - chose %s from candidates: %s" jar-file-path best-guess (pr-str matches)) (log/errorf "Did not find unique file on SCM for jar file %s - found no good candidate from candidates: %s" jar-file-path (pr-str matches))) best-guess)))) (defn match-files [known-files fpaths] {:pre [(seq known-files)]} (zipmap fpaths (map #(find-full-filepath known-files %) fpaths))) (comment (require '[cljdoc.render.rich-text :as rich-text]) (defn doc [] (Jsoup/parse (rich-text/markdown-to-html (slurp "")))) (def fix-opts {:git-ls [] :scm {:url "" :sha "07c59d1eadd458534c81d6ef8251b5fd5d754a74"}}) (println (Jsoup/parse hs)) (fix fp hs fo) (rebase "doc/coercion/coercion.md" "../ring/coercion.md") (rebase fp "route_syntax.md") (.relativize (.toPath (java.io.File. fp)) (.toPath (java.io.File. "route_syntax.md"))) (fix "README.md" (rich-text/markdown-to-html (slurp "")) fix-opts) (->> (.select (doc) "img") (map #(.attributes %)) (remove #(or (.startsWith (.get % "src") "http://") (.startsWith (.get % "src") "https://"))) (map #(doto % (.put "src" (fix-image (.get % "src") fix-opts))))) (.get (.attributes (first (.select doc "a"))) "href"))
null
https://raw.githubusercontent.com/cljdoc/cljdoc/c32df6c4cc6a4a5e402907b47aeb900f42a647b0/src/cljdoc/util/fixref.clj
clojure
Some utilities to find which file in a git repository corresponds to a file where a `def` is coming from -------------------------- choose shortest path where file sits under what looks like a src dir
(ns cljdoc.util.fixref "Utilities to rewrite, or support the rewrite of, references in markdown rendered to HTML. For example, external links are rewritten to include nofollow, links to ingested SCM articles are rewritten to their slugs, and scm relative references are rewritten to point to SCM." (:require [clojure.tools.logging :as log] [clojure.java.io :as io] [clojure.string :as string] [cljdoc.util.scm :as scm] [cljdoc.server.routes :as routes]) (:import (org.jsoup Jsoup) (org.jsoup.nodes Document Element Attributes))) (set! *warn-on-reflection* true) (defn- absolute-uri? [s] (or (string/starts-with? s "http://") (string/starts-with? s "https://"))) (defn- anchor-uri? [s] (string/starts-with? s "#")) (defn- split-relpath-anchor "Returns `[relpath anchor]` for path `s`" [s] (rest (re-find #"/?([^#]*)(#.*$)?" s))) (defn- root-relative-path? [s] (string/starts-with? s "/")) (defn- get-cljdoc-url-prefix [s] (first (filter #(string/starts-with? s %) ["" ""]))) (defn- rebase-path "Rebase path `s1` to directory of relative path `s2`. When path `s1` is absolute it is returned." [s1 s2] (if (root-relative-path? s1) s1 (let [p2-dir (if (string/ends-with? s2 "/") s2 (.getParent (io/file s2)))] (str (io/file p2-dir s1))))) (defn- normalize-path "Resolves relative `..` and `.` in path `s`" [s] (str (.normalize (.toPath (io/file s))))) (defn- path-relative-to "Returns `file-path` from `from-dir-path`. Both paths must be relative or absolute." [file-path from-dir-path] (str (.relativize (.toPath (io/file from-dir-path)) (.toPath (io/file file-path))))) (defn- error-ref "When the scm-file-path is unknown, as is currently the case for docstrings, we cannot handle relative refs and return a error ref." [ref scm-file-path] (when (and (not scm-file-path) (not (root-relative-path? ref))) "#!cljdoc-error!ref-must-be-root-relative!")) (defn- fix-link "Return the cljdoc location for a given URL `href` or it's page on GitHub/GitLab etc." ^String [href {:keys [scm-file-path target-path scm-base uri-map] :as _opts}] (or (error-ref href scm-file-path) (let [[href-rel-to-scm-base anchor] (-> href (rebase-path scm-file-path) normalize-path split-relpath-anchor)] (if-let [href-local-doc (get uri-map href-rel-to-scm-base)] (str (if target-path (path-relative-to href-local-doc target-path) href-local-doc) anchor) (str scm-base href-rel-to-scm-base anchor))))) (defn- fix-image ^String [src {:keys [scm-file-path scm-base]}] (or (error-ref src scm-file-path) (let [suffix (when (and (= :github (scm/provider scm-base)) (string/ends-with? src ".svg")) "?sanitize=true")] (if (root-relative-path? src) (str scm-base (subs src 1) suffix) (str scm-base (-> src (rebase-path scm-file-path) normalize-path) suffix))))) (defn uri-mapping "Returns lookup map where key is SCM repo relative file and value is cljdoc root relative `version-entity` slug path at for all `docs`. Ex: `{\"README.md\" \"/d/lread/cljdoc-exerciser/1.0.34/doc/readme}`" [version-entity docs] (->> docs (map (fn [d] [(-> d :attrs :cljdoc.doc/source-file) (->> (-> d :attrs :slug-path) (string/join "/") (assoc version-entity :article-slug) (routes/url-for :artifact/doc :path-params))])) (into {}))) (defn- parse-html ^Document [^String html-str] (let [doc (Jsoup/parse html-str) props (.outputSettings doc)] (.prettyPrint props false) doc)) (defn fix "Rewrite references in HTML produced from rendering markdown. Markdown from SCM can contains references to images and articles. Relative <a> links are links to SCM: * an SCM link that is an article that has been imported to cljdoc => local link (slug for online, html file for offline) * else => SCM formatted (aka blob) link at correct revision Absolute <a> links * when relinking back to cljdoc.org => to root relative to support local testing * else => converted to nofollow link (this includes links rewritten to point SCM) Relative <img> references are links to SCM: - are converted to SCM raw references at correct revision - svg files from GitHub add special querystring parameters * `:html-str` the html of the content we are fixing * `fix-opts` map contains * `:scm-file-path` SCM repo home relative path of content * `:target-path` local relative destination path of content, if provided, used to relativize link paths local path (used for offline bundles) * `:uri-map` - map of relative scm paths to cljdoc doc slugs (or for offline bundles html files) * `:scm` - scm-info from bundle used to link to correct SCM file revision" [html-str {:keys [scm-file-path target-path scm uri-map] :as _fix-opts}] (let [doc (parse-html html-str)] (doseq [^Attributes scm-relative-link (->> (.select doc "a") (map (fn [^Element e] (.attributes e))) (remove (fn [^Attributes a] (= "wikilink" (.get a "data-source")))) (remove (fn [^Attributes a] (absolute-uri? (.get a "href")))) (remove (fn [^Attributes a] (anchor-uri? (.get a "href")))))] (let [fixed-link (fix-link (.get scm-relative-link "href") {:scm-file-path scm-file-path :target-path target-path :scm-base (scm/rev-formatted-base-url scm) :uri-map uri-map})] (.put scm-relative-link "href" fixed-link))) (doseq [^Attributes scm-relative-img (->> (.select doc "img") (map (fn [^Element e] (.attributes e))) (remove (fn [^Attributes a] (absolute-uri? (.get a "src")))))] (.put scm-relative-img "src" (fix-image (.get scm-relative-img "src") {:scm-file-path scm-file-path :scm-base (scm/rev-raw-base-url scm)}))) (doseq [^Attributes absolute-link (->> (.select doc "a") (map (fn [^Element e] (.attributes e))) (filter (fn [^Attributes a] (absolute-uri? (.get a "href")))))] (let [href (.get absolute-link "href")] (if-let [cljdoc-prefix (get-cljdoc-url-prefix href)] (.put absolute-link "href" (subs href (count cljdoc-prefix))) (.put absolute-link "rel" "nofollow")))) (.. doc body html toString))) (defn- find-full-filepath "Return best match for `jar-file-path` source in `known-git-file-paths`." [known-git-file-paths jar-file-path] (let [matches (filter #(string/ends-with? (str "/" %) (str "/" jar-file-path)) known-git-file-paths)] (if (= 1 (count matches)) (first matches) (let [best-guess (->> matches (filter (fn [git-file] (let [src-path (str "/" (subs git-file 0 (- (count git-file) (count jar-file-path))))] (string/includes? src-path "/src/")))) maybe 2 paths are same length , so ensure a consistent result by sorting first (sort-by count) first)] (if best-guess (log/warnf "Did not find unique file on SCM for jar file %s - chose %s from candidates: %s" jar-file-path best-guess (pr-str matches)) (log/errorf "Did not find unique file on SCM for jar file %s - found no good candidate from candidates: %s" jar-file-path (pr-str matches))) best-guess)))) (defn match-files [known-files fpaths] {:pre [(seq known-files)]} (zipmap fpaths (map #(find-full-filepath known-files %) fpaths))) (comment (require '[cljdoc.render.rich-text :as rich-text]) (defn doc [] (Jsoup/parse (rich-text/markdown-to-html (slurp "")))) (def fix-opts {:git-ls [] :scm {:url "" :sha "07c59d1eadd458534c81d6ef8251b5fd5d754a74"}}) (println (Jsoup/parse hs)) (fix fp hs fo) (rebase "doc/coercion/coercion.md" "../ring/coercion.md") (rebase fp "route_syntax.md") (.relativize (.toPath (java.io.File. fp)) (.toPath (java.io.File. "route_syntax.md"))) (fix "README.md" (rich-text/markdown-to-html (slurp "")) fix-opts) (->> (.select (doc) "img") (map #(.attributes %)) (remove #(or (.startsWith (.get % "src") "http://") (.startsWith (.get % "src") "https://"))) (map #(doto % (.put "src" (fix-image (.get % "src") fix-opts))))) (.get (.attributes (first (.select doc "a"))) "href"))
611ad0b4a2c619cd9f4fc5e591d243bd7195d8ab43ead2b424f10f2a87cbaa77
Enecuum/Node
Messages.hs
{-# LANGUAGE DeriveAnyClass #-} module Enecuum.Samples.Assets.Nodes.TstNodes.PingPong.Messages where import Enecuum.Prelude newtype Ping = Ping Text deriving (Show, Eq, Generic, ToJSON, FromJSON) newtype Pong = Pong Int deriving (Show, Eq, Generic, ToJSON, FromJSON)
null
https://raw.githubusercontent.com/Enecuum/Node/3dfbc6a39c84bd45dd5f4b881e067044dde0153a/src/Enecuum/Samples/Assets/Nodes/TstNodes/PingPong/Messages.hs
haskell
# LANGUAGE DeriveAnyClass #
module Enecuum.Samples.Assets.Nodes.TstNodes.PingPong.Messages where import Enecuum.Prelude newtype Ping = Ping Text deriving (Show, Eq, Generic, ToJSON, FromJSON) newtype Pong = Pong Int deriving (Show, Eq, Generic, ToJSON, FromJSON)
3d321080bcd3bce1279f7d84e915bad79d37882f09c01158af27ee0f077eff4d
arthuredelstein/clooj
output.clj
(ns clooj.repl.output (:import (java.awt Point Rectangle) (java.util.concurrent.atomic AtomicBoolean AtomicInteger) (javax.swing JFrame JScrollPane JSplitPane JSlider JTextArea SwingUtilities) (javax.swing.event DocumentEvent DocumentListener))) (defn end-position "Finds the end position of an insert or change in a document as reported in a DocumentEvent instance." [^DocumentEvent document-event] (+ (.getOffset document-event) (.getLength document-event))) (defn tailing-scroll-pane "Embeds the given JTextArea in a JScrollPane that scrolls to the bottom whenever text is inserted or appended." [text-area] (let [scroll-offset (AtomicInteger. -1) scroll-pane (proxy [JScrollPane] [text-area] (paintComponent [graphics] (let [offset (.getAndSet scroll-offset -1)] (when (not= -1 offset) (.. this getVerticalScrollBar (setValue (.y (.modelToView text-area offset)))))) (proxy-super paintComponent graphics))) set-scroll-offset (fn [e] (.set scroll-offset (end-position e)) (.repaint scroll-pane))] (.. text-area getDocument (addDocumentListener (proxy [DocumentListener] [] (changedUpdate [e] (set-scroll-offset e)) (insertUpdate [e] (set-scroll-offset e)) (removeUpdate [e])))) scroll-pane)) ;; manual tests (defn test-text-area "Creates a JTextArea, shows it in a JFrame with a JSlider above it. Returns the text-area instance." [] (let [text-area (JTextArea.) scroll-pane (tailing-scroll-pane text-area) ;[text-area scroll-pane] (tailing-text-area) frame (JFrame. "test") document (.getDocument text-area) slider (JSlider. 0 100) split-pane (JSplitPane. JSplitPane/VERTICAL_SPLIT true slider scroll-pane)] (doto (.getContentPane frame) (.add split-pane)) (doto frame .pack (.setBounds 30 30 400 400) .show) text-area )) (defn write-lines "Write n lines of text (positive integers) in the text-area" [text-area n] (dotimes [i n] (.append text-area (str i "\n"))))
null
https://raw.githubusercontent.com/arthuredelstein/clooj/6d78d07c16ff339e782b0031eae3a2ef1eeb5280/src/clooj/repl/output.clj
clojure
manual tests [text-area scroll-pane] (tailing-text-area)
(ns clooj.repl.output (:import (java.awt Point Rectangle) (java.util.concurrent.atomic AtomicBoolean AtomicInteger) (javax.swing JFrame JScrollPane JSplitPane JSlider JTextArea SwingUtilities) (javax.swing.event DocumentEvent DocumentListener))) (defn end-position "Finds the end position of an insert or change in a document as reported in a DocumentEvent instance." [^DocumentEvent document-event] (+ (.getOffset document-event) (.getLength document-event))) (defn tailing-scroll-pane "Embeds the given JTextArea in a JScrollPane that scrolls to the bottom whenever text is inserted or appended." [text-area] (let [scroll-offset (AtomicInteger. -1) scroll-pane (proxy [JScrollPane] [text-area] (paintComponent [graphics] (let [offset (.getAndSet scroll-offset -1)] (when (not= -1 offset) (.. this getVerticalScrollBar (setValue (.y (.modelToView text-area offset)))))) (proxy-super paintComponent graphics))) set-scroll-offset (fn [e] (.set scroll-offset (end-position e)) (.repaint scroll-pane))] (.. text-area getDocument (addDocumentListener (proxy [DocumentListener] [] (changedUpdate [e] (set-scroll-offset e)) (insertUpdate [e] (set-scroll-offset e)) (removeUpdate [e])))) scroll-pane)) (defn test-text-area "Creates a JTextArea, shows it in a JFrame with a JSlider above it. Returns the text-area instance." [] (let [text-area (JTextArea.) scroll-pane (tailing-scroll-pane text-area) frame (JFrame. "test") document (.getDocument text-area) slider (JSlider. 0 100) split-pane (JSplitPane. JSplitPane/VERTICAL_SPLIT true slider scroll-pane)] (doto (.getContentPane frame) (.add split-pane)) (doto frame .pack (.setBounds 30 30 400 400) .show) text-area )) (defn write-lines "Write n lines of text (positive integers) in the text-area" [text-area n] (dotimes [i n] (.append text-area (str i "\n"))))
f328a0a694db258801aee573d52ce08ee452c0e46abf1f70d7fbca73b47d1b5f
kmicinski/cmsc330examples
ex2.ml
let calcPercent (grade,max) = ((float_of_int grade) /. (float_of_int max)) *. 100.0 let calcPercent' grade max = ((float_of_int grade) /. (float_of_int max)) *. 100.0 let transform (f : ('a*'b) -> 'c) : 'a -> 'b -> 'c = let h a b = f (a,b) in h
null
https://raw.githubusercontent.com/kmicinski/cmsc330examples/78f5acaaae25f11a39817673433efcf33271df6d/ocaml/ex2.ml
ocaml
let calcPercent (grade,max) = ((float_of_int grade) /. (float_of_int max)) *. 100.0 let calcPercent' grade max = ((float_of_int grade) /. (float_of_int max)) *. 100.0 let transform (f : ('a*'b) -> 'c) : 'a -> 'b -> 'c = let h a b = f (a,b) in h