_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
f3d651ab81771c5e836f3cbd32a477473f4e8ebde2c9972781909b95d1057989
rumblesan/improviz
Loops.hs
module Tests.Language.Interpreter.Loops ( interpreterLoopTests ) where import Test.Framework ( Test , testGroup ) import Test.Framework.Providers.HUnit ( testCase ) import Test.HUnit ( Assertion ) import TestHelpers.Util ( gfxTest ) import qualified TestHelpers.GfxAst as GA interpreterLoopTests :: Test interpreterLoopTests = testGroup "Loop Tests" [testCase "interprets loop" test_loop_program] test_loop_program :: Assertion test_loop_program = let program = "matrix(:rotate, 0.1, 0.2, 0.3)\n\ \loop 3 times with i\n\ \\tmatrix(:rotate, 0.2, 0.2, 0.2)\n\ \\tshape(:cube, i, i, i)\n\n\n" expectedGfx = [ GA.MatrixCommand (GA.Rotate 0.1 0.2 0.3) , GA.MatrixCommand (GA.Rotate 0.2 0.2 0.2) , GA.ShapeCommand (GA.ShapeGfx "cube" 0 0 0) , GA.MatrixCommand (GA.Rotate 0.2 0.2 0.2) , GA.ShapeCommand (GA.ShapeGfx "cube" 1 1 1) , GA.MatrixCommand (GA.Rotate 0.2 0.2 0.2) , GA.ShapeCommand (GA.ShapeGfx "cube" 2 2 2) ] in gfxTest program expectedGfx
null
https://raw.githubusercontent.com/rumblesan/improviz/90162e6dc7befec34e3b7b18b8aca275f26cd505/test/Tests/Language/Interpreter/Loops.hs
haskell
module Tests.Language.Interpreter.Loops ( interpreterLoopTests ) where import Test.Framework ( Test , testGroup ) import Test.Framework.Providers.HUnit ( testCase ) import Test.HUnit ( Assertion ) import TestHelpers.Util ( gfxTest ) import qualified TestHelpers.GfxAst as GA interpreterLoopTests :: Test interpreterLoopTests = testGroup "Loop Tests" [testCase "interprets loop" test_loop_program] test_loop_program :: Assertion test_loop_program = let program = "matrix(:rotate, 0.1, 0.2, 0.3)\n\ \loop 3 times with i\n\ \\tmatrix(:rotate, 0.2, 0.2, 0.2)\n\ \\tshape(:cube, i, i, i)\n\n\n" expectedGfx = [ GA.MatrixCommand (GA.Rotate 0.1 0.2 0.3) , GA.MatrixCommand (GA.Rotate 0.2 0.2 0.2) , GA.ShapeCommand (GA.ShapeGfx "cube" 0 0 0) , GA.MatrixCommand (GA.Rotate 0.2 0.2 0.2) , GA.ShapeCommand (GA.ShapeGfx "cube" 1 1 1) , GA.MatrixCommand (GA.Rotate 0.2 0.2 0.2) , GA.ShapeCommand (GA.ShapeGfx "cube" 2 2 2) ] in gfxTest program expectedGfx
efe1b77f386f3d33754473705f021db9df695c6cb36a0ef9865878e6523dc01a
basho/riaknostic
riaknostic_check.erl
%% ------------------------------------------------------------------- %% riaknostic - automated diagnostic tools for Riak %% Copyright ( c ) 2011 Basho Technologies , Inc. All Rights Reserved . %% This file is provided to you 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. %% %% ------------------------------------------------------------------- %% @doc <p>Enforces a common API among all diagnostic modules and %% provides some automation around their execution.</p> %% <h2>Behaviour Specification</h2> %% %% <h3>description/0</h3> %% <pre>-spec description() -> iodata().</pre> %% <p>A short description of what the diagnostic does, which will be %% printed when the script is given the <code>-l</code> flag.</p> %% %% <h3>valid/0</h3> < pre>-spec valid ( ) - > boolean().</pre > %% <p>Whether the diagnostic is valid to run. For example, some checks require connectivity to the node and hence call { @link %% riaknostic_node:can_connect/0. riaknostic_node:can_connect()}.</p> %% %% <h3>check/0</h3> %% <pre>-spec check() -> [{lager:log_level(), term()}].</pre> < p > Runs the diagnostic , returning a list of pairs , where the first is a severity level and the second is any term that is understood %% by the <code>format/1</code> callback.</p> %% %% <h3>format/1</h3> < pre>-spec format(term ( ) ) - > iodata ( ) | { io : format ( ) , [ term()]}.</pre > %% <p>Formats terms that were returned from <code>check/0</code> for %% output to the console. Valid return values are an iolist (string, %% binary, etc) or a pair of a format string and a list of terms, as you would pass to { @link io : format/2 . io : format/2}.</p > %% @end -module(riaknostic_check). -export([behaviour_info/1]). -export([check/1, modules/0, print/1]). %% @doc The behaviour definition for diagnostic modules. -spec behaviour_info(atom()) -> 'undefined' | [{atom(), arity()}]. behaviour_info(callbacks) -> [{description, 0}, {valid, 0}, {check, 0}, {format, 1}]; behaviour_info(_) -> undefined. %% @doc Runs the diagnostic in the given module, if it is valid. Returns a %% list of messages that will be printed later using print/1. -spec check(Module::module()) -> [{lager:log_level(), module(), term()}]. check(Module) -> case Module:valid() of true -> [ {Level, Module, Message} || {Level, Message} <- Module:check() ]; _ -> [] end. %% @doc Collects a list of diagnostic modules included in the %% riaknostic application. -spec modules() -> [module()]. modules() -> {ok, Mods} = application:get_key(riaknostic, modules), [ M || M <- Mods, Attr <- M:module_info(attributes), {behaviour, [?MODULE]} =:= Attr orelse {behavior, [?MODULE]} =:= Attr ]. %% @doc Formats and prints the given message via lager:log/3,4. The diagnostic %% module's format/1 function will be called to provide a human - readable message . It should return an iolist ( ) or a 2 - tuple %% consisting of a format string and a list of terms. -spec print({Level::lager:log_level(), Module::module(), Data::term()}) -> ok. print({Level, Mod, Data}) -> case Mod:format(Data) of {Format, Terms} -> riaknostic_util:log(Level, Format, Terms); String -> riaknostic_util:log(Level, String) end.
null
https://raw.githubusercontent.com/basho/riaknostic/dad8939d0ef32fbf435d13697720223293195282/src/riaknostic_check.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- @doc <p>Enforces a common API among all diagnostic modules and provides some automation around their execution.</p> <h2>Behaviour Specification</h2> <h3>description/0</h3> <pre>-spec description() -> iodata().</pre> <p>A short description of what the diagnostic does, which will be printed when the script is given the <code>-l</code> flag.</p> <h3>valid/0</h3> <p>Whether the diagnostic is valid to run. For example, some checks riaknostic_node:can_connect/0. riaknostic_node:can_connect()}.</p> <h3>check/0</h3> <pre>-spec check() -> [{lager:log_level(), term()}].</pre> by the <code>format/1</code> callback.</p> <h3>format/1</h3> <p>Formats terms that were returned from <code>check/0</code> for output to the console. Valid return values are an iolist (string, binary, etc) or a pair of a format string and a list of terms, as @end @doc The behaviour definition for diagnostic modules. @doc Runs the diagnostic in the given module, if it is valid. Returns a list of messages that will be printed later using print/1. @doc Collects a list of diagnostic modules included in the riaknostic application. @doc Formats and prints the given message via lager:log/3,4. The diagnostic module's format/1 function will be called to provide a consisting of a format string and a list of terms.
riaknostic - automated diagnostic tools for Riak Copyright ( c ) 2011 Basho Technologies , Inc. All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY < pre>-spec valid ( ) - > boolean().</pre > require connectivity to the node and hence call { @link < p > Runs the diagnostic , returning a list of pairs , where the first is a severity level and the second is any term that is understood < pre>-spec format(term ( ) ) - > iodata ( ) | { io : format ( ) , [ term()]}.</pre > you would pass to { @link io : format/2 . io : format/2}.</p > -module(riaknostic_check). -export([behaviour_info/1]). -export([check/1, modules/0, print/1]). -spec behaviour_info(atom()) -> 'undefined' | [{atom(), arity()}]. behaviour_info(callbacks) -> [{description, 0}, {valid, 0}, {check, 0}, {format, 1}]; behaviour_info(_) -> undefined. -spec check(Module::module()) -> [{lager:log_level(), module(), term()}]. check(Module) -> case Module:valid() of true -> [ {Level, Module, Message} || {Level, Message} <- Module:check() ]; _ -> [] end. -spec modules() -> [module()]. modules() -> {ok, Mods} = application:get_key(riaknostic, modules), [ M || M <- Mods, Attr <- M:module_info(attributes), {behaviour, [?MODULE]} =:= Attr orelse {behavior, [?MODULE]} =:= Attr ]. human - readable message . It should return an iolist ( ) or a 2 - tuple -spec print({Level::lager:log_level(), Module::module(), Data::term()}) -> ok. print({Level, Mod, Data}) -> case Mod:format(Data) of {Format, Terms} -> riaknostic_util:log(Level, Format, Terms); String -> riaknostic_util:log(Level, String) end.
2f82bb17a5aceb171945274def6dbc34b7a1ca36fa86176587da064f0fa89f8a
roelvandijk/numerals
TestData.hs
| [ @ISO639 - 1@ ] - [ @ISO639 - 2@ ] - [ @ISO639 - 3@ ] rmn [ @Native name@ ] - [ @English name@ ] Balkan Romani [@ISO639-1@] - [@ISO639-2@] - [@ISO639-3@] rmn [@Native name@] - [@English name@] Balkan Romani -} module Text.Numeral.Language.RMN_DZA.TestData (cardinals) where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- import "numerals" Text.Numeral.Grammar ( defaultInflection ) import "this" Text.Numeral.Test ( TestData ) -------------------------------------------------------------------------------- -- Test data -------------------------------------------------------------------------------- {- Sources: -to-count-in-dzambazi-romani/en/rmn-dza/ -} Note : This is the Prilep dialect as spoken in Macedonia . cardinals :: (Num i) => TestData i cardinals = [ ( "default" , defaultInflection , [ (1, "jekh") , (2, "duj") , (3, "trin") , (4, "štar") , (5, "pandž") , (6, "šov") , (7, "efta") , (8, "oxto") , (9, "iňa") , (10, "deš") , (11, "dešujekh") , (12, "dešuduj") , (13, "dešutrin") , (14, "dešuštar") , (15, "dešupandž") , (16, "dešušov") , (17, "dešuefta") , (18, "dešuoxto") , (19, "dešuiňa") , (20, "biš") , (21, "bišthajekh") , (22, "bišthaduj") , (23, "bišthatrin") , (24, "bišthaštar") , (25, "bišthapandž") , (26, "bišthašov") , (27, "bišthajefta") , (28, "bišthajoxto") , (29, "bišthaiňa") , (30, "tranda") , (31, "trandathajekh") , (32, "trandathaduj") , (33, "trandathatrin") , (34, "trandathaštar") , (35, "trandathapandž") , (36, "trandathašov") , (37, "trandathajefta") , (38, "trandathajoxto") , (39, "trandathajiňa") , (40, "saranda") , (41, "sarandathajekh") , (42, "sarandathaduj") , (43, "sarandathatrin") , (44, "sarandathaštar") , (45, "sarandathapandž") , (46, "sarandathašov") , (47, "sarandathajefta") , (48, "sarandathajoxto") , (49, "sarandathajiňa") , (50, "pinda") , (51, "pindathajekh") , (52, "pindathaduj") , (53, "pindathatrin") , (54, "pindathaštar") , (55, "pindathapandž") , (56, "pindathašov") , (57, "pindathajefta") , (58, "pindathajoxto") , (59, "pindathajiňa") , (60, "šovardeš") , (61, "šovardešthajekh") , (62, "šovardešthaduj") , (63, "šovardešthatrin") , (64, "šovardešthaštar") , (65, "šovardešthapandž") , (66, "šovardešthašov") , (67, "šovardešthajefta") , (68, "šovardešthajoxto") , (69, "šovardešthajiňa") , (70, "eftavardeš") , (71, "eftavardešthajekh") , (72, "eftavardešthaduj") , (73, "eftavardešthatrin") , (74, "eftavardešthaštar") , (75, "eftavardešthapandž") , (76, "eftavardešthašov") , (77, "eftavardešthajefta") , (78, "eftavardešthajoxto") , (79, "eftavardešthajiňa") , (80, "oxtovardeš") , (81, "oxtovardešthajekh") , (82, "oxtovardešthaduj") , (83, "oxtovardešthatrin") , (84, "oxtovardešthaštar") , (85, "oxtovardešthapandž") , (86, "oxtovardešthašov") , (87, "oxtovardešthajefta") , (88, "oxtovardešthajoxto") , (89, "oxtovardešthajiňa") , (90, "iňavardeš") , (91, "iňavardešthajekh") , (92, "iňavardešthaduj") , (93, "iňavardešthatrin") , (94, "iňavardešthaštar") , (95, "iňavardešthapandž") , (96, "iňavardešthašov") , (97, "iňavardešthajefta") , (98, "iňavardešthajoxto") , (99, "iňavardešthajiňa") , (100, "šel") , (101, "šel jekh") , (102, "šel duj") , (103, "šel trin") , (104, "šel štar") , (105, "šel pandž") , (106, "šel šov") , (107, "šel efta") , (108, "šel oxto") , (109, "šel iňa") , (110, "šel deš") , (123, "šel bišthatrin") , (200, "duj šel") , (300, "trin šel") , (321, "trin šel bišthajekh") , (400, "štar šel") , (500, "panšel") , (600, "šov šel") , (700, "efta šel") , (800, "oxto šel") , (900, "iňa šel") , (909, "iňa šel iňa") , (990, "iňa šel iňavardeš") , (999, "iňa šel iňavardešthajiňa") , (1000, "miľa") , (1001, "miľa jekh") , (1008, "miľa oxto") , (1234, "miľa duj šel trandathaštar") , (2000, "duj miľe") , (3000, "trin miľe") , (4000, "štar miľe") , (4321, "štar miľe trin šel bišthajekh") , (5000, "pandž miľe") , (6000, "šov miľe") , (7000, "efta miľe") , (8000, "oxto miľe") , (9000, "iňa miľe") , (10000, "deš miľe") , (12345, "dešuduj miľe trin šel sarandathapandž") , (20000, "biš miľe") , (30000, "tranda miľe") , (40000, "saranda miľe") , (50000, "pinda miľe") , (54321, "pindathaštar miľe trin šel bišthajekh") , (60000, "šovardeš miľe") , (70000, "eftavardeš miľe") , (80000, "oxtovardeš miľe") , (90000, "iňavardeš miľe") , (100000, "šel miľe") , (123456, "šel bišthatrin miľe štar šel pindathašov") , (200000, "duj šel miľe") , (300000, "trin šel miľe") , (400000, "štar šel miľe") , (500000, "panšel miľe") , (600000, "šov šel miľe") , (654321, "šov šel pindathaštar miľe trin šel bišthajekh") , (700000, "efta šel miľe") , (800000, "oxto šel miľe") , (900000, "iňa šel miľe") , (1000000, "milioni") ] ) ]
null
https://raw.githubusercontent.com/roelvandijk/numerals/b1e4121e0824ac0646a3230bd311818e159ec127/src-test/Text/Numeral/Language/RMN_DZA/TestData.hs
haskell
------------------------------------------------------------------------------ Imports ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Test data ------------------------------------------------------------------------------ Sources: -to-count-in-dzambazi-romani/en/rmn-dza/
| [ @ISO639 - 1@ ] - [ @ISO639 - 2@ ] - [ @ISO639 - 3@ ] rmn [ @Native name@ ] - [ @English name@ ] Balkan Romani [@ISO639-1@] - [@ISO639-2@] - [@ISO639-3@] rmn [@Native name@] - [@English name@] Balkan Romani -} module Text.Numeral.Language.RMN_DZA.TestData (cardinals) where import "numerals" Text.Numeral.Grammar ( defaultInflection ) import "this" Text.Numeral.Test ( TestData ) Note : This is the Prilep dialect as spoken in Macedonia . cardinals :: (Num i) => TestData i cardinals = [ ( "default" , defaultInflection , [ (1, "jekh") , (2, "duj") , (3, "trin") , (4, "štar") , (5, "pandž") , (6, "šov") , (7, "efta") , (8, "oxto") , (9, "iňa") , (10, "deš") , (11, "dešujekh") , (12, "dešuduj") , (13, "dešutrin") , (14, "dešuštar") , (15, "dešupandž") , (16, "dešušov") , (17, "dešuefta") , (18, "dešuoxto") , (19, "dešuiňa") , (20, "biš") , (21, "bišthajekh") , (22, "bišthaduj") , (23, "bišthatrin") , (24, "bišthaštar") , (25, "bišthapandž") , (26, "bišthašov") , (27, "bišthajefta") , (28, "bišthajoxto") , (29, "bišthaiňa") , (30, "tranda") , (31, "trandathajekh") , (32, "trandathaduj") , (33, "trandathatrin") , (34, "trandathaštar") , (35, "trandathapandž") , (36, "trandathašov") , (37, "trandathajefta") , (38, "trandathajoxto") , (39, "trandathajiňa") , (40, "saranda") , (41, "sarandathajekh") , (42, "sarandathaduj") , (43, "sarandathatrin") , (44, "sarandathaštar") , (45, "sarandathapandž") , (46, "sarandathašov") , (47, "sarandathajefta") , (48, "sarandathajoxto") , (49, "sarandathajiňa") , (50, "pinda") , (51, "pindathajekh") , (52, "pindathaduj") , (53, "pindathatrin") , (54, "pindathaštar") , (55, "pindathapandž") , (56, "pindathašov") , (57, "pindathajefta") , (58, "pindathajoxto") , (59, "pindathajiňa") , (60, "šovardeš") , (61, "šovardešthajekh") , (62, "šovardešthaduj") , (63, "šovardešthatrin") , (64, "šovardešthaštar") , (65, "šovardešthapandž") , (66, "šovardešthašov") , (67, "šovardešthajefta") , (68, "šovardešthajoxto") , (69, "šovardešthajiňa") , (70, "eftavardeš") , (71, "eftavardešthajekh") , (72, "eftavardešthaduj") , (73, "eftavardešthatrin") , (74, "eftavardešthaštar") , (75, "eftavardešthapandž") , (76, "eftavardešthašov") , (77, "eftavardešthajefta") , (78, "eftavardešthajoxto") , (79, "eftavardešthajiňa") , (80, "oxtovardeš") , (81, "oxtovardešthajekh") , (82, "oxtovardešthaduj") , (83, "oxtovardešthatrin") , (84, "oxtovardešthaštar") , (85, "oxtovardešthapandž") , (86, "oxtovardešthašov") , (87, "oxtovardešthajefta") , (88, "oxtovardešthajoxto") , (89, "oxtovardešthajiňa") , (90, "iňavardeš") , (91, "iňavardešthajekh") , (92, "iňavardešthaduj") , (93, "iňavardešthatrin") , (94, "iňavardešthaštar") , (95, "iňavardešthapandž") , (96, "iňavardešthašov") , (97, "iňavardešthajefta") , (98, "iňavardešthajoxto") , (99, "iňavardešthajiňa") , (100, "šel") , (101, "šel jekh") , (102, "šel duj") , (103, "šel trin") , (104, "šel štar") , (105, "šel pandž") , (106, "šel šov") , (107, "šel efta") , (108, "šel oxto") , (109, "šel iňa") , (110, "šel deš") , (123, "šel bišthatrin") , (200, "duj šel") , (300, "trin šel") , (321, "trin šel bišthajekh") , (400, "štar šel") , (500, "panšel") , (600, "šov šel") , (700, "efta šel") , (800, "oxto šel") , (900, "iňa šel") , (909, "iňa šel iňa") , (990, "iňa šel iňavardeš") , (999, "iňa šel iňavardešthajiňa") , (1000, "miľa") , (1001, "miľa jekh") , (1008, "miľa oxto") , (1234, "miľa duj šel trandathaštar") , (2000, "duj miľe") , (3000, "trin miľe") , (4000, "štar miľe") , (4321, "štar miľe trin šel bišthajekh") , (5000, "pandž miľe") , (6000, "šov miľe") , (7000, "efta miľe") , (8000, "oxto miľe") , (9000, "iňa miľe") , (10000, "deš miľe") , (12345, "dešuduj miľe trin šel sarandathapandž") , (20000, "biš miľe") , (30000, "tranda miľe") , (40000, "saranda miľe") , (50000, "pinda miľe") , (54321, "pindathaštar miľe trin šel bišthajekh") , (60000, "šovardeš miľe") , (70000, "eftavardeš miľe") , (80000, "oxtovardeš miľe") , (90000, "iňavardeš miľe") , (100000, "šel miľe") , (123456, "šel bišthatrin miľe štar šel pindathašov") , (200000, "duj šel miľe") , (300000, "trin šel miľe") , (400000, "štar šel miľe") , (500000, "panšel miľe") , (600000, "šov šel miľe") , (654321, "šov šel pindathaštar miľe trin šel bišthajekh") , (700000, "efta šel miľe") , (800000, "oxto šel miľe") , (900000, "iňa šel miľe") , (1000000, "milioni") ] ) ]
e454d1451572fc573cd298f64dacdca7535cf55f0d722ccd35f08d90de784121
bzliu94/cs61a_fa07
1.scm
2019 - 08 - 07 group # 1 -- use arbiters and alarm -- uses berkeley.scm ; advantages: ; - requires few to no changes to berkeley.scm ; disadvantages: ; - test-and-set! is flawed and our approach would be wrong ; except we do have alarm-based waking of sleeping threads; ; for this reason, we are technically still correct in sense ; that eventually we get all threads to finish ; notes: ; - if we leave in alarm, handler will continue to attempt ; to resume processes in our process queue; this happens ; until one calls "stop"; if we call stop too early, ; however, some threads may have failed to finish and will ; remain paused until we somehow continue to attempt to wake ; - because we have wrong test-and-set! implementation, ; we get emergent pairing and with alarm turned off, ; it is not a coincidence that for y and z we get exactly floor of half of n ( i.e. instead of 300 we get 150 ) ; ; we reiterate that below we have alarm turned on - sub - case four does not require test - and - set ! ; it is purely an ; experiment in clobbering by way of dealing directly ; with process scheduler ; - alarm-interrupt default definition found in slib/process.scm; alarm by default provides one second per process ; important: - serializer is implemented the way it is in SICP ( i.e. via make - mutex ) ; ; this means that we are reducing to test-and-set!; each of these serializers shares an arbiter ; we have one resource and there is no deadlock have four sub - cases : 1 . do not use parallel - execute and perform methods one - by - one 2 . use parallel - execute with single serializer 3 . use parallel - execute with many serializers 4 . use parallel - execute with arbitrary clobbering ; conclusion: ; not much point to these results given that we are ; interested in what happens with working test-and-set! ideal value for n for each sub - case : 300 (load "includes/berkeley.scm") (load "includes/serial.scm") ; to disable alarms, uncomment: ; (define (alarm-interrupt) ; ( alarm 1 ) ; do n't chain alarms ; (if ints-disabled (set! alarm-deferred #t) ; (process:schedule!))) ; (define (alarm-signal-handler sig) ; (alarm-interrupt)) ( set - signal - handler ! 14 alarm - signal - handler ) ; (define (parallel-execute . thunks) ; (for-each (lambda (thunk) (add-process! (lambda (foo) (thunk)))) ; thunks) ; ; (alarm-interrupt) ; set off the chained alarms ; (process:schedule!)) ; we want to clear the process queue between sub-cases; process:queue is from SLIB process.scm (define (clear-process-queue) (set! process:queue (make-queue))) for sub - case four , we want to force killing a thread (define (process:schedule!-no-keep) (defer-ints) (cond ((queue-empty? process:queue) (allow-ints) 'still-running) (else (call-with-current-continuation (lambda (cont) ; (enqueue! process:queue cont) ; don't re-insert thread into active thread collection (let ((proc (dequeue! process:queue))) (allow-ints) (proc 'run)) (kill-process!)))))) ; this is for general use (define (getFilledList numTimes value) (if (eq? numTimes 0) nil (append (list value) (getFilledList (- numTimes 1) value)))) sub - case # 1 -- do not use parallel - execute and perform methods one - by - one (define x 0) (define (increment1) (set! x (+ x 1))) (define methodList1 (map (lambda (x) increment1) (getFilledList 300 0))) (time (for-each (lambda (x) (x)) methodList1)) (display x) (display "\n") sub - case # 2 -- use parallel - execute with single serializer (define y 0) (define (increment2) (set! y (+ y 1))) (define serializer2 (make-serializer)) (define serializedIncrement (serializer2 increment2)) (define methodList2 (map (lambda (x) serializedIncrement) (getFilledList 300 0))) (time (apply parallel-execute methodList2)) ; (alarm-interrupt) (clear-process-queue) (stop) (display y) (display "\n") sub - case # 3 -- use parallel - execute with many serializers (define z 0) (define (increment3) (set! z (+ z 1))) (define serializer3 (make-serializer)) (define methodList3 (map (lambda (x) (serializer3 increment3)) (getFilledList 300 0))) (time (apply parallel-execute methodList3)) ; (alarm-interrupt) (clear-process-queue) ; (stop) (display z) (display "\n") sub - case # 4 -- use parallel - execute with arbitrary clobbering ; half the time an increment attempt will defer to other threads ; s.t. when we return we clobber the effects of those other threads; the other half of the time an increment attempt will immediately increment ; ; all of the time after incrementing the current thread is killed; ; the overall effect is that we should have clobbering s.t. the number we end up with is significantly lower than 300 ( i.e. it 's around ; slightly higher than 150) (define w 0) (define (increment4) (let ((w-old w) (randInt (random 2))) (begin (if (equal? randInt 1) (begin (process:schedule!) (set! w (+ w-old 1)) ; this "parameterized" trailing call to scheduler is important (process:schedule!-no-keep) ) (begin (set! w (+ w-old 1)) ; this "parameterized" trailing call to scheduler is important (process:schedule!-no-keep) ))))) (define (getRange x) (if (equal? x 0) nil (append (getRange (- x 1)) (list (- x 1))))) (define methodList4 (map (lambda (x) increment4) (getRange 300))) (time (apply parallel-execute methodList4)) ; (alarm-interrupt) (clear-process-queue) ; (stop) (display w) (display "\n")
null
https://raw.githubusercontent.com/bzliu94/cs61a_fa07/12a62689f149ef035a36b326351928928f6e7b5d/01%20-%20homework/hw10/experiments/1.scm
scheme
advantages: - requires few to no changes to berkeley.scm disadvantages: - test-and-set! is flawed and our approach would be wrong except we do have alarm-based waking of sleeping threads; for this reason, we are technically still correct in sense that eventually we get all threads to finish notes: - if we leave in alarm, handler will continue to attempt to resume processes in our process queue; this happens until one calls "stop"; if we call stop too early, however, some threads may have failed to finish and will remain paused until we somehow continue to attempt to wake - because we have wrong test-and-set! implementation, we get emergent pairing and with alarm turned off, it is not a coincidence that for y and z we get exactly we reiterate that below we have alarm turned on it is purely an experiment in clobbering by way of dealing directly with process scheduler - alarm-interrupt default definition found in slib/process.scm; important: this means that we are reducing to test-and-set!; each of these serializers we have one resource and there is no deadlock conclusion: not much point to these results given that we are interested in what happens with working test-and-set! to disable alarms, uncomment: (define (alarm-interrupt) ( alarm 1 ) ; do n't chain alarms (if ints-disabled (set! alarm-deferred #t) (process:schedule!))) (define (alarm-signal-handler sig) (alarm-interrupt)) (define (parallel-execute . thunks) (for-each (lambda (thunk) (add-process! (lambda (foo) (thunk)))) thunks) ; (alarm-interrupt) ; set off the chained alarms (process:schedule!)) we want to clear the process queue between sub-cases; process:queue is from SLIB process.scm (enqueue! process:queue cont) ; don't re-insert thread into active thread collection this is for general use (alarm-interrupt) (alarm-interrupt) (stop) half the time an increment attempt will defer to other threads s.t. when we return we clobber the effects of those other threads; all of the time after incrementing the current thread is killed; the overall effect is that we should have clobbering s.t. the number slightly higher than 150) this "parameterized" trailing call to scheduler is important this "parameterized" trailing call to scheduler is important (alarm-interrupt) (stop)
2019 - 08 - 07 group # 1 -- use arbiters and alarm -- uses berkeley.scm alarm by default provides one second per process have four sub - cases : 1 . do not use parallel - execute and perform methods one - by - one 2 . use parallel - execute with single serializer 3 . use parallel - execute with many serializers 4 . use parallel - execute with arbitrary clobbering ideal value for n for each sub - case : 300 (load "includes/berkeley.scm") (load "includes/serial.scm") ( set - signal - handler ! 14 alarm - signal - handler ) (define (clear-process-queue) (set! process:queue (make-queue))) for sub - case four , we want to force killing a thread (define (process:schedule!-no-keep) (defer-ints) (cond ((queue-empty? process:queue) (allow-ints) 'still-running) (else (call-with-current-continuation (lambda (cont) (let ((proc (dequeue! process:queue))) (allow-ints) (proc 'run)) (kill-process!)))))) (define (getFilledList numTimes value) (if (eq? numTimes 0) nil (append (list value) (getFilledList (- numTimes 1) value)))) sub - case # 1 -- do not use parallel - execute and perform methods one - by - one (define x 0) (define (increment1) (set! x (+ x 1))) (define methodList1 (map (lambda (x) increment1) (getFilledList 300 0))) (time (for-each (lambda (x) (x)) methodList1)) (display x) (display "\n") sub - case # 2 -- use parallel - execute with single serializer (define y 0) (define (increment2) (set! y (+ y 1))) (define serializer2 (make-serializer)) (define serializedIncrement (serializer2 increment2)) (define methodList2 (map (lambda (x) serializedIncrement) (getFilledList 300 0))) (time (apply parallel-execute methodList2)) (clear-process-queue) (stop) (display y) (display "\n") sub - case # 3 -- use parallel - execute with many serializers (define z 0) (define (increment3) (set! z (+ z 1))) (define serializer3 (make-serializer)) (define methodList3 (map (lambda (x) (serializer3 increment3)) (getFilledList 300 0))) (time (apply parallel-execute methodList3)) (clear-process-queue) (display z) (display "\n") sub - case # 4 -- use parallel - execute with arbitrary clobbering we end up with is significantly lower than 300 ( i.e. it 's around (define w 0) (define (increment4) (let ((w-old w) (randInt (random 2))) (begin (if (equal? randInt 1) (begin (process:schedule!) (set! w (+ w-old 1)) (process:schedule!-no-keep) ) (begin (set! w (+ w-old 1)) (process:schedule!-no-keep) ))))) (define (getRange x) (if (equal? x 0) nil (append (getRange (- x 1)) (list (- x 1))))) (define methodList4 (map (lambda (x) increment4) (getRange 300))) (time (apply parallel-execute methodList4)) (clear-process-queue) (display w) (display "\n")
651611083bb3f15ff4e1a5693d1836bacb55f762c7f0668cce164d5a0de59e16
wangweihao/ProgrammingErlangAnswer
minmodule.erl
% (1).编写一些导出单个函数的小模块,以及被导出函数的类型规范。 在函数里制造一些类型错误,然后对这些程序运行 dialyzer 。 % 有时候你制造的错误无法被 dialyzer 发现,请仔细观察程序,找出没有得到预期错误的原因。 -module(minmodule). -export([func1/3]). %-spec func1(number(), number(), number()) -> number(). func1(X, Y, Z) when is_list(X) -> X+Y+Z.
null
https://raw.githubusercontent.com/wangweihao/ProgrammingErlangAnswer/b145b5e6a19cb866ce5d2ceeac116d751f6e2b3d/9/1/minmodule.erl
erlang
(1).编写一些导出单个函数的小模块,以及被导出函数的类型规范。 有时候你制造的错误无法被 dialyzer 发现,请仔细观察程序,找出没有得到预期错误的原因。 -spec func1(number(), number(), number()) -> number().
在函数里制造一些类型错误,然后对这些程序运行 dialyzer 。 -module(minmodule). -export([func1/3]). func1(X, Y, Z) when is_list(X) -> X+Y+Z.
9bb00193aa8888d1f235c469f90687fa14f983b7aa2b98dec144ad79bc9b636e
mukul-rathi/bolt
bad_overloading.ml
open Core open Print_typed_ast let%expect_test "Function overloading different arg names" = print_typed_ast " function int test(bool f) { if f { 0} else {1} } function int test(bool b){ if b { 1} else {0} } void main() { test(true) } " ; [%expect {| Type error - function test has duplicate definitions in environment |}] let%expect_test "Function overloading different return types" = print_typed_ast " function bool test(bool b) { b } function int test(bool b){ if b { 1} else {0} } void main() { test(true) } " ; [%expect {| Type error - function test has duplicate definitions in environment |}] let%expect_test "Function overloading different param capabilities used" = print_typed_ast " class Foo{ capability read Bar, local Baz; var int f : Bar, Baz; } function int test(Foo x) { x.f } function int test(Foo{Baz} x){ x.f := 1 } void main() { let x = new Foo(f:1); test(x) } " ; [%expect {| Type error - function test has duplicate definitions in environment |}] let%expect_test "Function overloading borrowed and non-borrowed param used" = print_typed_ast " class Foo{ capability read Bar, linear Baz; var int f : Bar, Baz; } function int test(borrowed Foo x) { x.f } function int test(Foo x){ x.f := 1 } void main() { let x = new Foo(f:1); test(x) } " ; [%expect {| Type error - function test has duplicate definitions in environment |}] let%expect_test "Method overloading different arg names" = print_typed_ast " class Foo{ capability read Bar, local Baz; var int f : Bar, Baz; int test(bool f) : Bar{ if f { this.f } else {1} } int test(bool b) : Bar{ if b { 1} else {this.f} } } void main() { let x = new Foo(f:1); x.test(true) } " ; [%expect {| Type error - method test has duplicate definitions in environment |}] let%expect_test "Method overloading different return types" = print_typed_ast " class Foo{ capability read Bar, local Baz; var int f : Bar, Baz; bool test(bool b): Bar { b } int test(bool b): Bar{ if b { 1} else {this.f} } } void main() { let x = new Foo(f:1); x.test(true) } " ; [%expect {| Type error - method test has duplicate definitions in environment |}] let%expect_test "Method overloading different param capabilities used" = print_typed_ast " class Foo{ capability read Bar, local Baz; var int f : Bar, Baz; int test(Foo x) :Bar { x.f } int test(Foo{Baz} x) : Bar{ x.f := 1 } } void main() { let x = new Foo(f:1); x.test(x) } " ; [%expect {| Type error - method test has duplicate definitions in environment |}] let%expect_test "Method overloading borrowed and not borrowed param" = print_typed_ast " class Foo{ capability read Bar, linear Baz; var int f : Bar, Baz; int test(borrowed Foo x) :Bar { x.f } int test(Foo x) : Bar{ x.f := 1 } } void main() { let x = new Foo(f:1); x.test(x) } " ; [%expect {| Type error - method test has duplicate definitions in environment |}] let%expect_test "Method overloading different method capabilities used" = print_typed_ast " class Foo{ capability read Bar, local Baz; var int f : Bar, Baz; int test(int x) : Bar { this.f + x } int test(int x) : Baz{ this.f := x; x } } void main() { let x = new Foo(f:1); x.test(x) } " ; [%expect {| Type error - method test has duplicate definitions in environment |}] let%expect_test "Multiple options for overloaded function call" = print_typed_ast " class Foo { capability linear Bar; var int f : Bar; } class Baz extends Foo { capability linear Boo; var int g : Boo; } class Choco extends Baz { capability linear Late; var int g : Late; } function void f(borrowed Foo x){} function void f(borrowed Baz x){} void main() { let x= new Choco(); f(x) } " ; [%expect {| Line:18 Position:9 Type error - function f has multiple matching definition that accepts args of type Choco |}] let%expect_test "No options for overloaded function call" = print_typed_ast " class Foo { capability linear Bar; var int f : Bar; } class Baz extends Foo { capability linear Boo; var int g : Boo; } function void f(Foo x){} function void f(Baz x){} void main() { f(1232) } " ; [%expect {| Line:13 Position:9 Type error - function f has no matching definition that accepts args of type Int |}]
null
https://raw.githubusercontent.com/mukul-rathi/bolt/1faf19d698852fdb6af2ee005a5f036ee1c76503/tests/frontend/expect/typing/bad_overloading.ml
ocaml
open Core open Print_typed_ast let%expect_test "Function overloading different arg names" = print_typed_ast " function int test(bool f) { if f { 0} else {1} } function int test(bool b){ if b { 1} else {0} } void main() { test(true) } " ; [%expect {| Type error - function test has duplicate definitions in environment |}] let%expect_test "Function overloading different return types" = print_typed_ast " function bool test(bool b) { b } function int test(bool b){ if b { 1} else {0} } void main() { test(true) } " ; [%expect {| Type error - function test has duplicate definitions in environment |}] let%expect_test "Function overloading different param capabilities used" = print_typed_ast " class Foo{ capability read Bar, local Baz; var int f : Bar, Baz; } function int test(Foo x) { x.f } function int test(Foo{Baz} x){ x.f := 1 } void main() { let x = new Foo(f:1); test(x) } " ; [%expect {| Type error - function test has duplicate definitions in environment |}] let%expect_test "Function overloading borrowed and non-borrowed param used" = print_typed_ast " class Foo{ capability read Bar, linear Baz; var int f : Bar, Baz; } function int test(borrowed Foo x) { x.f } function int test(Foo x){ x.f := 1 } void main() { let x = new Foo(f:1); test(x) } " ; [%expect {| Type error - function test has duplicate definitions in environment |}] let%expect_test "Method overloading different arg names" = print_typed_ast " class Foo{ capability read Bar, local Baz; var int f : Bar, Baz; int test(bool f) : Bar{ if f { this.f } else {1} } int test(bool b) : Bar{ if b { 1} else {this.f} } } void main() { let x = new Foo(f:1); x.test(true) } " ; [%expect {| Type error - method test has duplicate definitions in environment |}] let%expect_test "Method overloading different return types" = print_typed_ast " class Foo{ capability read Bar, local Baz; var int f : Bar, Baz; bool test(bool b): Bar { b } int test(bool b): Bar{ if b { 1} else {this.f} } } void main() { let x = new Foo(f:1); x.test(true) } " ; [%expect {| Type error - method test has duplicate definitions in environment |}] let%expect_test "Method overloading different param capabilities used" = print_typed_ast " class Foo{ capability read Bar, local Baz; var int f : Bar, Baz; int test(Foo x) :Bar { x.f } int test(Foo{Baz} x) : Bar{ x.f := 1 } } void main() { let x = new Foo(f:1); x.test(x) } " ; [%expect {| Type error - method test has duplicate definitions in environment |}] let%expect_test "Method overloading borrowed and not borrowed param" = print_typed_ast " class Foo{ capability read Bar, linear Baz; var int f : Bar, Baz; int test(borrowed Foo x) :Bar { x.f } int test(Foo x) : Bar{ x.f := 1 } } void main() { let x = new Foo(f:1); x.test(x) } " ; [%expect {| Type error - method test has duplicate definitions in environment |}] let%expect_test "Method overloading different method capabilities used" = print_typed_ast " class Foo{ capability read Bar, local Baz; var int f : Bar, Baz; int test(int x) : Bar { this.f + x } int test(int x) : Baz{ this.f := x; x } } void main() { let x = new Foo(f:1); x.test(x) } " ; [%expect {| Type error - method test has duplicate definitions in environment |}] let%expect_test "Multiple options for overloaded function call" = print_typed_ast " class Foo { capability linear Bar; var int f : Bar; } class Baz extends Foo { capability linear Boo; var int g : Boo; } class Choco extends Baz { capability linear Late; var int g : Late; } function void f(borrowed Foo x){} function void f(borrowed Baz x){} void main() { let x= new Choco(); f(x) } " ; [%expect {| Line:18 Position:9 Type error - function f has multiple matching definition that accepts args of type Choco |}] let%expect_test "No options for overloaded function call" = print_typed_ast " class Foo { capability linear Bar; var int f : Bar; } class Baz extends Foo { capability linear Boo; var int g : Boo; } function void f(Foo x){} function void f(Baz x){} void main() { f(1232) } " ; [%expect {| Line:13 Position:9 Type error - function f has no matching definition that accepts args of type Int |}]
c83730fccb358b9763423f93451774169abca2cea2c28ffa23c4ae02c04954a9
TyOverby/mono
or_error.mli
* Type for tracking errors in an [ Error.t ] . This is a specialization of the [ Result ] type , where the [ Error ] constructor carries an [ Error.t ] . A common idiom is to wrap a function that is not implemented on all platforms , e.g. , { [ do_something_linux_specific : ( unit - > unit ) ] } type, where the [Error] constructor carries an [Error.t]. A common idiom is to wrap a function that is not implemented on all platforms, e.g., {[val do_something_linux_specific : (unit -> unit) Or_error.t]} *) open! Import (** Serialization and comparison of an [Error] force the error's lazy message. *) type 'a t = ('a, Error.t) Result.t [@@deriving_inline compare, equal, hash, sexp, sexp_grammar] include Ppx_compare_lib.Comparable.S1 with type 'a t := 'a t include Ppx_compare_lib.Equal.S1 with type 'a t := 'a t include Ppx_hash_lib.Hashable.S1 with type 'a t := 'a t include Sexplib0.Sexpable.S1 with type 'a t := 'a t val t_sexp_grammar : 'a Sexplib0.Sexp_grammar.t -> 'a t Sexplib0.Sexp_grammar.t [@@@end] (** [Applicative] functions don't have quite the same semantics as [Applicative.Of_Monad(Or_error)] would give -- [apply (Error e1) (Error e2)] returns the combination of [e1] and [e2], whereas it would only return [e1] if it were defined using [bind]. *) include Applicative.S with type 'a t := 'a t include Invariant.S1 with type 'a t := 'a t include Monad.S with type 'a t := 'a t val is_ok : _ t -> bool val is_error : _ t -> bool (** [try_with f] catches exceptions thrown by [f] and returns them in the [Result.t] as an [Error.t]. [try_with_join] is like [try_with], except that [f] can throw exceptions or return an [Error] directly, without ending up with a nested error; it is equivalent to [Result.join (try_with f)]. *) val try_with : ?backtrace:bool (** defaults to [false] *) -> (unit -> 'a) -> 'a t val try_with_join : ?backtrace:bool (** defaults to [false] *) -> (unit -> 'a t) -> 'a t (** [ok t] returns [None] if [t] is an [Error], and otherwise returns the contents of the [Ok] constructor. *) val ok : 'ok t -> 'ok option (** [ok_exn t] throws an exception if [t] is an [Error], and otherwise returns the contents of the [Ok] constructor. *) val ok_exn : 'a t -> 'a (** [of_exn ?backtrace exn] is [Error (Error.of_exn ?backtrace exn)]. *) val of_exn : ?backtrace:[ `Get | `This of string ] -> exn -> _ t (** [of_exn_result ?backtrace (Ok a) = Ok a] [of_exn_result ?backtrace (Error exn) = of_exn ?backtrace exn] *) val of_exn_result : ?backtrace:[ `Get | `This of string ] -> ('a, exn) Result.t -> 'a t * [ error ] is a wrapper around [ Error.create ] : { [ error ? strict message a sexp_of_a = Error ( Error.create ? strict message a sexp_of_a ) ] } As with [ Error.create ] , [ sexp_of_a a ] is lazily computed when the info is converted to a sexp . So , if [ a ] is mutated in the time between the call to [ create ] and the sexp conversion , those mutations will be reflected in the sexp . Use [ ~strict :() ] to force [ sexp_of_a a ] to be computed immediately . {[ error ?strict message a sexp_of_a = Error (Error.create ?strict message a sexp_of_a) ]} As with [Error.create], [sexp_of_a a] is lazily computed when the info is converted to a sexp. So, if [a] is mutated in the time between the call to [create] and the sexp conversion, those mutations will be reflected in the sexp. Use [~strict:()] to force [sexp_of_a a] to be computed immediately. *) val error : ?here:Source_code_position0.t -> ?strict:unit -> string -> 'a -> ('a -> Sexp.t) -> _ t val error_s : Sexp.t -> _ t (** [error_string message] is [Error (Error.of_string message)]. *) val error_string : string -> _ t (** [errorf format arg1 arg2 ...] is [Error (sprintf format arg1 arg2 ...)]. Note that it calculates the string eagerly, so when performance matters you may want to use [error] instead. *) val errorf : ('a, unit, string, _ t) format4 -> 'a (** [tag t ~tag] is [Result.map_error t ~f:(Error.tag ~tag)]. *) val tag : 'a t -> tag:string -> 'a t (** [tag_s] is like [tag] with a sexp tag. *) val tag_s : 'a t -> tag:Sexp.t -> 'a t (** [tag_s_lazy] is like [tag] with a lazy sexp tag. *) val tag_s_lazy : 'a t -> tag:Sexp.t Lazy.t -> 'a t (** [tag_arg] is like [tag], with a tag that has a sexpable argument. *) val tag_arg : 'a t -> string -> 'b -> ('b -> Sexp.t) -> 'a t (** For marking a given value as unimplemented. Typically combined with conditional compilation, where on some platforms the function is defined normally, and on some platforms it is defined as unimplemented. The supplied string should be the name of the function that is unimplemented. *) val unimplemented : string -> _ t val map : 'a t -> f:('a -> 'b) -> 'b t val iter : 'a t -> f:('a -> unit) -> unit val iter_error : _ t -> f:(Error.t -> unit) -> unit (** [combine_errors ts] returns [Ok] if every element in [ts] is [Ok], else it returns [Error] with all the errors in [ts]. More precisely: - [combine_errors [Ok a1; ...; Ok an] = Ok [a1; ...; an]] - {[ combine_errors [...; Error e1; ...; Error en; ...] = Error (Error.of_list [e1; ...; en]) ]} *) val combine_errors : 'a t list -> 'a list t (** [combine_errors_unit ts] returns [Ok] if every element in [ts] is [Ok ()], else it returns [Error] with all the errors in [ts], like [combine_errors]. *) val combine_errors_unit : unit t list -> unit t (** [filter_ok_at_least_one ts] returns all values in [ts] that are [Ok] if there is at least one, otherwise it returns the same error as [combine_errors ts]. *) val filter_ok_at_least_one : 'a t list -> 'a list t * [ find_ok ts ] returns the first value in [ ts ] that is [ Ok ] , otherwise it returns the same error as [ combine_errors ts ] . same error as [combine_errors ts]. *) val find_ok : 'a t list -> 'a t * [ l ~f ] returns the first value in [ l ] for which [ f ] returns [ Ok ] , otherwise it returns the same error as [ combine_errors ( List.map l ~f ) ] . otherwise it returns the same error as [combine_errors (List.map l ~f)]. *) val find_map_ok : 'a list -> f:('a -> 'b t) -> 'b t
null
https://raw.githubusercontent.com/TyOverby/mono/7666c0328d194bf9a569fb65babc0486f2aaa40d/vendor/janestreet-base/src/or_error.mli
ocaml
* Serialization and comparison of an [Error] force the error's lazy message. * [Applicative] functions don't have quite the same semantics as [Applicative.Of_Monad(Or_error)] would give -- [apply (Error e1) (Error e2)] returns the combination of [e1] and [e2], whereas it would only return [e1] if it were defined using [bind]. * [try_with f] catches exceptions thrown by [f] and returns them in the [Result.t] as an [Error.t]. [try_with_join] is like [try_with], except that [f] can throw exceptions or return an [Error] directly, without ending up with a nested error; it is equivalent to [Result.join (try_with f)]. * defaults to [false] * defaults to [false] * [ok t] returns [None] if [t] is an [Error], and otherwise returns the contents of the [Ok] constructor. * [ok_exn t] throws an exception if [t] is an [Error], and otherwise returns the contents of the [Ok] constructor. * [of_exn ?backtrace exn] is [Error (Error.of_exn ?backtrace exn)]. * [of_exn_result ?backtrace (Ok a) = Ok a] [of_exn_result ?backtrace (Error exn) = of_exn ?backtrace exn] * [error_string message] is [Error (Error.of_string message)]. * [errorf format arg1 arg2 ...] is [Error (sprintf format arg1 arg2 ...)]. Note that it calculates the string eagerly, so when performance matters you may want to use [error] instead. * [tag t ~tag] is [Result.map_error t ~f:(Error.tag ~tag)]. * [tag_s] is like [tag] with a sexp tag. * [tag_s_lazy] is like [tag] with a lazy sexp tag. * [tag_arg] is like [tag], with a tag that has a sexpable argument. * For marking a given value as unimplemented. Typically combined with conditional compilation, where on some platforms the function is defined normally, and on some platforms it is defined as unimplemented. The supplied string should be the name of the function that is unimplemented. * [combine_errors ts] returns [Ok] if every element in [ts] is [Ok], else it returns [Error] with all the errors in [ts]. More precisely: - [combine_errors [Ok a1; ...; Ok an] = Ok [a1; ...; an]] - {[ combine_errors [...; Error e1; ...; Error en; ...] = Error (Error.of_list [e1; ...; en]) ]} * [combine_errors_unit ts] returns [Ok] if every element in [ts] is [Ok ()], else it returns [Error] with all the errors in [ts], like [combine_errors]. * [filter_ok_at_least_one ts] returns all values in [ts] that are [Ok] if there is at least one, otherwise it returns the same error as [combine_errors ts].
* Type for tracking errors in an [ Error.t ] . This is a specialization of the [ Result ] type , where the [ Error ] constructor carries an [ Error.t ] . A common idiom is to wrap a function that is not implemented on all platforms , e.g. , { [ do_something_linux_specific : ( unit - > unit ) ] } type, where the [Error] constructor carries an [Error.t]. A common idiom is to wrap a function that is not implemented on all platforms, e.g., {[val do_something_linux_specific : (unit -> unit) Or_error.t]} *) open! Import type 'a t = ('a, Error.t) Result.t [@@deriving_inline compare, equal, hash, sexp, sexp_grammar] include Ppx_compare_lib.Comparable.S1 with type 'a t := 'a t include Ppx_compare_lib.Equal.S1 with type 'a t := 'a t include Ppx_hash_lib.Hashable.S1 with type 'a t := 'a t include Sexplib0.Sexpable.S1 with type 'a t := 'a t val t_sexp_grammar : 'a Sexplib0.Sexp_grammar.t -> 'a t Sexplib0.Sexp_grammar.t [@@@end] include Applicative.S with type 'a t := 'a t include Invariant.S1 with type 'a t := 'a t include Monad.S with type 'a t := 'a t val is_ok : _ t -> bool val is_error : _ t -> bool val ok : 'ok t -> 'ok option val ok_exn : 'a t -> 'a val of_exn : ?backtrace:[ `Get | `This of string ] -> exn -> _ t val of_exn_result : ?backtrace:[ `Get | `This of string ] -> ('a, exn) Result.t -> 'a t * [ error ] is a wrapper around [ Error.create ] : { [ error ? strict message a sexp_of_a = Error ( Error.create ? strict message a sexp_of_a ) ] } As with [ Error.create ] , [ sexp_of_a a ] is lazily computed when the info is converted to a sexp . So , if [ a ] is mutated in the time between the call to [ create ] and the sexp conversion , those mutations will be reflected in the sexp . Use [ ~strict :() ] to force [ sexp_of_a a ] to be computed immediately . {[ error ?strict message a sexp_of_a = Error (Error.create ?strict message a sexp_of_a) ]} As with [Error.create], [sexp_of_a a] is lazily computed when the info is converted to a sexp. So, if [a] is mutated in the time between the call to [create] and the sexp conversion, those mutations will be reflected in the sexp. Use [~strict:()] to force [sexp_of_a a] to be computed immediately. *) val error : ?here:Source_code_position0.t -> ?strict:unit -> string -> 'a -> ('a -> Sexp.t) -> _ t val error_s : Sexp.t -> _ t val error_string : string -> _ t val errorf : ('a, unit, string, _ t) format4 -> 'a val tag : 'a t -> tag:string -> 'a t val tag_s : 'a t -> tag:Sexp.t -> 'a t val tag_s_lazy : 'a t -> tag:Sexp.t Lazy.t -> 'a t val tag_arg : 'a t -> string -> 'b -> ('b -> Sexp.t) -> 'a t val unimplemented : string -> _ t val map : 'a t -> f:('a -> 'b) -> 'b t val iter : 'a t -> f:('a -> unit) -> unit val iter_error : _ t -> f:(Error.t -> unit) -> unit val combine_errors : 'a t list -> 'a list t val combine_errors_unit : unit t list -> unit t val filter_ok_at_least_one : 'a t list -> 'a list t * [ find_ok ts ] returns the first value in [ ts ] that is [ Ok ] , otherwise it returns the same error as [ combine_errors ts ] . same error as [combine_errors ts]. *) val find_ok : 'a t list -> 'a t * [ l ~f ] returns the first value in [ l ] for which [ f ] returns [ Ok ] , otherwise it returns the same error as [ combine_errors ( List.map l ~f ) ] . otherwise it returns the same error as [combine_errors (List.map l ~f)]. *) val find_map_ok : 'a list -> f:('a -> 'b t) -> 'b t
80e5f2d5f6404a6dace44b0b74ef6e6bfd144058a7d21f89409340485b28d18a
s-cerevisiae/leetcode-racket
2-add-two-numbers.rkt
#lang racket (require "list-node.rkt") (define/contract (add-two-numbers l1 l2) (-> (or/c list-node? #f) (or/c list-node? #f) (or/c list-node? #f)) (define (carry x) (quotient/remainder x 10)) (let loop ([l1 l1] [l2 l2] [rem 0]) (match* (l1 l2) [(#f #f) (if (zero? rem) #f (make-list-node rem))] [((list-node x xs) #f) (define-values (new-rem val) (carry (+ x rem))) (list-node val (loop xs #f new-rem))] [(#f (list-node y ys)) (define-values (new-rem val) (carry (+ y rem))) (list-node val (loop #f ys new-rem))] [((list-node x xs) (list-node y ys)) (define-values (new-rem val) (carry (+ x y rem))) (list-node val (loop xs ys new-rem))])))
null
https://raw.githubusercontent.com/s-cerevisiae/leetcode-racket/cd7936ecd5e37b92ee92c32fad0d83adfda54f15/2-add-two-numbers.rkt
racket
#lang racket (require "list-node.rkt") (define/contract (add-two-numbers l1 l2) (-> (or/c list-node? #f) (or/c list-node? #f) (or/c list-node? #f)) (define (carry x) (quotient/remainder x 10)) (let loop ([l1 l1] [l2 l2] [rem 0]) (match* (l1 l2) [(#f #f) (if (zero? rem) #f (make-list-node rem))] [((list-node x xs) #f) (define-values (new-rem val) (carry (+ x rem))) (list-node val (loop xs #f new-rem))] [(#f (list-node y ys)) (define-values (new-rem val) (carry (+ y rem))) (list-node val (loop #f ys new-rem))] [((list-node x xs) (list-node y ys)) (define-values (new-rem val) (carry (+ x y rem))) (list-node val (loop xs ys new-rem))])))
78bce646e1332a9a0227cd2f8d6a0137f90beb05f2a7546594245fafbb9369b7
huangjs/cl
our-match.lisp
(defpackage :our-match (:use :common-lisp) (:export #:our-match) ) (in-package :our-match) (defparameter *extensions* (make-hash-table :test 'equal)) (defparameter *segment-extensions* (make-hash-table :test 'equal)) (defun our-match (pat input &optional (blists (list nil))) (cond ((null blists) nil) ((not (null (get-extension pat))) (funcall (get-extension pat) pat input blists)) ((eql pat input) blists) ((atom pat) nil) ((not (null (get-segment-extension (car pat)))) (funcall (get-segment-extension (car pat)) pat input blists)) ((atom input) nil) (t (our-match (cdr pat) (cdr input) (our-match (car pat) (car input) blists))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun add-extension (name fn) (setf (gethash (string name) *extensions*) fn)) (defun get-extension (pat) (and (consp pat) (symbolp (car pat)) (gethash (string (car pat)) *extensions*))) (defun add-segment-extension (name fn) (setf (gethash (string name) *segment-extensions*) fn)) (defun get-segment-extension (pat) (and (consp pat) (symbolp (car pat)) (gethash (string (car pat)) *segment-extensions*))) (defun var-name (var) (cadr var)) (defun variable-p (pat) (and (consp pat) (symbolp (car pat)) (string= (symbol-name (car pat)) "?"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Extensions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (add-extension '? 'match-variable) (defun match-variable (pat input blists) (bind-variable (var-name pat) input blists)) (defun bind-variable (var input blists) (and (not (null blists)) (if (null var) blists (let ((binding (assoc var (car blists)))) (cond ((null binding) (list (cons (cons var input) (car blists)))) ((equal (cdr binding) input) blists) (t nil)))))) ( ? and pat1 pat2 ... ) matches if all patterns match (add-extension '?and 'match-and) (defun match-and (pat input blists) (match-and-list (cdr pat) input blists)) (defun match-and-list (pats input blists) (cond ((null blists) nil) ((null pats) blists) (t (match-and-list (cdr pats) input (our-match (car pats) input blists))))) ;;; (?is function) matches if (function input) is true (add-extension '?is 'match-predicate) (defun match-predicate (pat input blists) (if (funcall (cadr pat) input) blists nil)) ;;; ((?* var) . more-pats) ;;; ;;; (our-match '((?* l1) (?* l2)) '(a b c)) (add-segment-extension '?* 'match-star) (defun match-star (pat input blists) (destructuring-bind ((marker &optional var) &rest pats) pat (match-star-loop var pats input blists))) (defun match-star-loop (var pats input blists) (cond ((null blists) nil) (t (match-tail var pats input blists)))) (defun match-tail (var pats input blists) (do ((tail input (cdr tail)) (new-blists nil (append* (our-match pats tail (bind-variable var (ldiff input tail) blists)) new-blists))) ((null tail) (append* (our-match pats nil (bind-variable var input blists)) new-blists)))) (defun append* (x y) (append x y)) ;;; (?not pattern) matches if pattern does not match (add-extension '?not 'match-not) (defun match-not (pat input blists) (if (not (our-match (cadr pat) input blists)) blists nil))
null
https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/other-code/cs325/www.cs.northwestern.edu/academics/courses/325/programs/our-match.lisp
lisp
Extensions (?is function) matches if (function input) is true ((?* var) . more-pats) (our-match '((?* l1) (?* l2)) '(a b c)) (?not pattern) matches if pattern does not match
(defpackage :our-match (:use :common-lisp) (:export #:our-match) ) (in-package :our-match) (defparameter *extensions* (make-hash-table :test 'equal)) (defparameter *segment-extensions* (make-hash-table :test 'equal)) (defun our-match (pat input &optional (blists (list nil))) (cond ((null blists) nil) ((not (null (get-extension pat))) (funcall (get-extension pat) pat input blists)) ((eql pat input) blists) ((atom pat) nil) ((not (null (get-segment-extension (car pat)))) (funcall (get-segment-extension (car pat)) pat input blists)) ((atom input) nil) (t (our-match (cdr pat) (cdr input) (our-match (car pat) (car input) blists))))) (defun add-extension (name fn) (setf (gethash (string name) *extensions*) fn)) (defun get-extension (pat) (and (consp pat) (symbolp (car pat)) (gethash (string (car pat)) *extensions*))) (defun add-segment-extension (name fn) (setf (gethash (string name) *segment-extensions*) fn)) (defun get-segment-extension (pat) (and (consp pat) (symbolp (car pat)) (gethash (string (car pat)) *segment-extensions*))) (defun var-name (var) (cadr var)) (defun variable-p (pat) (and (consp pat) (symbolp (car pat)) (string= (symbol-name (car pat)) "?"))) (add-extension '? 'match-variable) (defun match-variable (pat input blists) (bind-variable (var-name pat) input blists)) (defun bind-variable (var input blists) (and (not (null blists)) (if (null var) blists (let ((binding (assoc var (car blists)))) (cond ((null binding) (list (cons (cons var input) (car blists)))) ((equal (cdr binding) input) blists) (t nil)))))) ( ? and pat1 pat2 ... ) matches if all patterns match (add-extension '?and 'match-and) (defun match-and (pat input blists) (match-and-list (cdr pat) input blists)) (defun match-and-list (pats input blists) (cond ((null blists) nil) ((null pats) blists) (t (match-and-list (cdr pats) input (our-match (car pats) input blists))))) (add-extension '?is 'match-predicate) (defun match-predicate (pat input blists) (if (funcall (cadr pat) input) blists nil)) (add-segment-extension '?* 'match-star) (defun match-star (pat input blists) (destructuring-bind ((marker &optional var) &rest pats) pat (match-star-loop var pats input blists))) (defun match-star-loop (var pats input blists) (cond ((null blists) nil) (t (match-tail var pats input blists)))) (defun match-tail (var pats input blists) (do ((tail input (cdr tail)) (new-blists nil (append* (our-match pats tail (bind-variable var (ldiff input tail) blists)) new-blists))) ((null tail) (append* (our-match pats nil (bind-variable var input blists)) new-blists)))) (defun append* (x y) (append x y)) (add-extension '?not 'match-not) (defun match-not (pat input blists) (if (not (our-match (cadr pat) input blists)) blists nil))
03084a5d161184fadac0747b70bd4e5eae9bd71aee07fd71517b9c37d478f0ea
ericfinster/catt.io
catt.ml
(*****************************************************************************) (* *) (* Main *) (* *) (*****************************************************************************) open Format open Catt.Io open Catt.Typecheck open Catt.Rawcheck let () = let file_in = ref [] in pp_set_margin std_formatter 200; open_vbox 0; (* initialize the pretty printer *) Arg.parse spec_list (fun s -> file_in := s::!file_in) usage; let files = List.rev (!file_in) in let tenv = { empty_env with config = !global_config } in match raw_check_all files empty_raw_env tenv with | Ok (Ok _) -> printf "----------------@,Success!"; print_newline (); print_newline () | Fail terr -> printf "----------------@,Typing error:@,@,%s" (print_tc_err terr); print_cut (); print_newline (); print_newline () | Ok (Fail s) -> printf "----------------@,Typing error:@,@,%s" s; print_cut (); print_newline (); print_newline ()
null
https://raw.githubusercontent.com/ericfinster/catt.io/0f2446860b7daba8ac2c343f933056195151a819/bin/catt.ml
ocaml
*************************************************************************** Main *************************************************************************** initialize the pretty printer
open Format open Catt.Io open Catt.Typecheck open Catt.Rawcheck let () = let file_in = ref [] in pp_set_margin std_formatter 200; Arg.parse spec_list (fun s -> file_in := s::!file_in) usage; let files = List.rev (!file_in) in let tenv = { empty_env with config = !global_config } in match raw_check_all files empty_raw_env tenv with | Ok (Ok _) -> printf "----------------@,Success!"; print_newline (); print_newline () | Fail terr -> printf "----------------@,Typing error:@,@,%s" (print_tc_err terr); print_cut (); print_newline (); print_newline () | Ok (Fail s) -> printf "----------------@,Typing error:@,@,%s" s; print_cut (); print_newline (); print_newline ()
8786acaa61cdf639d5fe0016469897db6d26ef74e2e9fdf8cf47f177990103e1
grafi-tt/tatsuki
Main.hs
-- this file is based on the internally distributed sample implementation {-# OPTIONS -XBangPatterns #-} module Main where import Reversi.Client import Network import System.Console.GetOpt import System.Environment (getArgs) import System.IO import MainClient data Config = Config { host :: HostName , port :: PortNumber , playerName :: String , verbose :: Bool , helpMode :: Bool } defaultConf = Config "localhost" 3000 "Anon." False False options :: [OptDescr (Config -> Config)] options = [ Option ['v'] ["verbose"] (NoArg $ \conf -> conf { verbose = True }) "verbose mode" , Option ['H'] ["host"] (ReqArg (\s conf -> conf { host = s }) "HOST") "host name of a server" , Option ['p'] ["port"] (ReqArg (\s conf -> conf { port = fromIntegral (read s :: Int) }) "PORT") "port number of a server" , Option ['n'] ["name"] (ReqArg (\s conf -> conf { playerName = s }) "NAME") "player name" , Option ['h','?'] ["help"] (NoArg (\conf -> conf { helpMode = True })) "show this help" ] usageMessage :: String usageMessage = usageInfo header options where header = "Usage: \n" ++ " reversi -H HOST -p PORT -n NAME ...\n" parseArg args = case getOpt Permute options args of (o, n, []) -> return (foldl (flip ($)) defaultConf o, n) (_, _, err) -> ioError (userError (concat err ++ usageMessage)) main = withSocketsDo $ do args <- getArgs (!conf, rest) <- parseArg args if helpMode conf then putStrLn usageMessage else runClient conf runClient conf = do putStrLn $ "Connecting to " ++ (host conf) ++ " " ++ show (port conf) !h <- connectTo (host conf) (PortNumber $ port conf) putStrLn $ "Connection Ok." doGame h initClient (playerName conf) (verbose conf)
null
https://raw.githubusercontent.com/grafi-tt/tatsuki/2f85835c5aab83c3c60999a37a51fa4794c84285/Main.hs
haskell
this file is based on the internally distributed sample implementation # OPTIONS -XBangPatterns #
module Main where import Reversi.Client import Network import System.Console.GetOpt import System.Environment (getArgs) import System.IO import MainClient data Config = Config { host :: HostName , port :: PortNumber , playerName :: String , verbose :: Bool , helpMode :: Bool } defaultConf = Config "localhost" 3000 "Anon." False False options :: [OptDescr (Config -> Config)] options = [ Option ['v'] ["verbose"] (NoArg $ \conf -> conf { verbose = True }) "verbose mode" , Option ['H'] ["host"] (ReqArg (\s conf -> conf { host = s }) "HOST") "host name of a server" , Option ['p'] ["port"] (ReqArg (\s conf -> conf { port = fromIntegral (read s :: Int) }) "PORT") "port number of a server" , Option ['n'] ["name"] (ReqArg (\s conf -> conf { playerName = s }) "NAME") "player name" , Option ['h','?'] ["help"] (NoArg (\conf -> conf { helpMode = True })) "show this help" ] usageMessage :: String usageMessage = usageInfo header options where header = "Usage: \n" ++ " reversi -H HOST -p PORT -n NAME ...\n" parseArg args = case getOpt Permute options args of (o, n, []) -> return (foldl (flip ($)) defaultConf o, n) (_, _, err) -> ioError (userError (concat err ++ usageMessage)) main = withSocketsDo $ do args <- getArgs (!conf, rest) <- parseArg args if helpMode conf then putStrLn usageMessage else runClient conf runClient conf = do putStrLn $ "Connecting to " ++ (host conf) ++ " " ++ show (port conf) !h <- connectTo (host conf) (PortNumber $ port conf) putStrLn $ "Connection Ok." doGame h initClient (playerName conf) (verbose conf)
e1769d80e77322b63ac016a894af5ee21d63403b8a64d7c2fce534a31c120f11
aeternity/mnesia_rocksdb
mrdb_bench.erl
-module(mrdb_bench). -compile([export_all, nowarn_export_all]). init() -> mnesia:delete_schema([node()]), mnesia_rocksdb:create_schema([node()]), mnesia:start(), [mnesia:create_table(Name, [{Type, [node()]}, {record_name, r}]) || {Name, Type} <- tabs()], ok. tabs() -> [{rc, ram_copies}, {dc, disc_copies}, {do, disc_only_copies}, {rocks, rocksdb_copies}, {rdb, rocksdb_copies}]. fill(N) -> [{T, timer:tc(fun() -> fill_(T, N) end)} || {T,_} <- tabs()]. fill_(_, 0) -> ok; fill_(T, N) when N > 0 -> write(T, {r, N, <<"1234567890">>}), fill_(T, N-1). write(rdb, Obj) -> mrdb:insert(rdb, Obj); write(T, Obj) -> mnesia:dirty_write(T, Obj). fold() -> [{T, timer:tc(fun() -> fold_(T) end)} || {T,_} <- tabs()]. fold_(rdb) -> mrdb:fold(rdb, fun(_, Acc) -> Acc end, ok); fold_(T) -> mnesia:activity( async_dirty, fun() -> mnesia:foldl(fun(_, Acc) -> Acc end, ok, T) end). tx(N) -> [{T, timer:tc(fun() -> tx_(T, N) end)} || {T,_} <- tabs()]. %% tx_(T, N) -> tx_(T , N , N , 10 ) . tx_(_, 0) -> ok; tx_(T, N) when N > 0 -> one_tx(T, N), tx_(T, N-1). one_tx(rdb, N) -> mrdb:activity(transaction, rocksdb_copies, fun() -> [{r, N, Str}] = mrdb:read(rdb, N), Str2 = <<Str/binary, "x">>, mrdb:insert(rdb, {r, N, Str2}), [{r, N, Str2}] = mrdb:read(rdb, N) end); one_tx(T, N) -> mnesia:activity(transaction, fun() -> [{r, N, Str}] = mnesia:read(T, N), Str2 = <<Str/binary, "x">>, mnesia:write(T, {r, N, Str2}, write), [{r, N, Str2}] = mnesia:read(T, N) end).
null
https://raw.githubusercontent.com/aeternity/mnesia_rocksdb/0aecf5ef0192c9d130b9b0aabd8656d27d278815/test/mrdb_bench.erl
erlang
tx_(T, N) ->
-module(mrdb_bench). -compile([export_all, nowarn_export_all]). init() -> mnesia:delete_schema([node()]), mnesia_rocksdb:create_schema([node()]), mnesia:start(), [mnesia:create_table(Name, [{Type, [node()]}, {record_name, r}]) || {Name, Type} <- tabs()], ok. tabs() -> [{rc, ram_copies}, {dc, disc_copies}, {do, disc_only_copies}, {rocks, rocksdb_copies}, {rdb, rocksdb_copies}]. fill(N) -> [{T, timer:tc(fun() -> fill_(T, N) end)} || {T,_} <- tabs()]. fill_(_, 0) -> ok; fill_(T, N) when N > 0 -> write(T, {r, N, <<"1234567890">>}), fill_(T, N-1). write(rdb, Obj) -> mrdb:insert(rdb, Obj); write(T, Obj) -> mnesia:dirty_write(T, Obj). fold() -> [{T, timer:tc(fun() -> fold_(T) end)} || {T,_} <- tabs()]. fold_(rdb) -> mrdb:fold(rdb, fun(_, Acc) -> Acc end, ok); fold_(T) -> mnesia:activity( async_dirty, fun() -> mnesia:foldl(fun(_, Acc) -> Acc end, ok, T) end). tx(N) -> [{T, timer:tc(fun() -> tx_(T, N) end)} || {T,_} <- tabs()]. tx_(T , N , N , 10 ) . tx_(_, 0) -> ok; tx_(T, N) when N > 0 -> one_tx(T, N), tx_(T, N-1). one_tx(rdb, N) -> mrdb:activity(transaction, rocksdb_copies, fun() -> [{r, N, Str}] = mrdb:read(rdb, N), Str2 = <<Str/binary, "x">>, mrdb:insert(rdb, {r, N, Str2}), [{r, N, Str2}] = mrdb:read(rdb, N) end); one_tx(T, N) -> mnesia:activity(transaction, fun() -> [{r, N, Str}] = mnesia:read(T, N), Str2 = <<Str/binary, "x">>, mnesia:write(T, {r, N, Str2}, write), [{r, N, Str2}] = mnesia:read(T, N) end).
5dad69fc376a6b43571cc94859ab2487e28456dae7c6d8f2fc99ad489d29db2c
rabeckett/Temporal-NetKAT
reindex.mli
Provide a 2 - way renaming maps . Elements of type ' a are mapped to unique positive integer names . Useful for converting automata over arbitrary types to be over ints during construction . Elements of type 'a are mapped to unique positive integer names. Useful for converting automata over arbitrary types to be over ints during construction. *) module type S = sig type elt type t val create: unit -> t val get_val: t -> int -> elt val get_idx: t -> elt -> int end module Make(O: Set.OrderedType): S with type elt = O.t
null
https://raw.githubusercontent.com/rabeckett/Temporal-NetKAT/829d1847c18d77f40501fe4d988eec6e7867c94d/src/reindex.mli
ocaml
Provide a 2 - way renaming maps . Elements of type ' a are mapped to unique positive integer names . Useful for converting automata over arbitrary types to be over ints during construction . Elements of type 'a are mapped to unique positive integer names. Useful for converting automata over arbitrary types to be over ints during construction. *) module type S = sig type elt type t val create: unit -> t val get_val: t -> int -> elt val get_idx: t -> elt -> int end module Make(O: Set.OrderedType): S with type elt = O.t
d7b5e714a76299c3e9673acfc20a9549b8b87fcb3c2aa7fa290ceb1b9356429e
haskellweekly/haskellweekly
Caption.hs
-- | This module defines a data type for audio captions, along with functions -- for converting from various common formats. Even though there are some libraries for these things , the captions that Haskell Weekly uses do n't use -- very many of the features. It felt better to write simple parsers and -- renderers rather than relying on a fully fledged library. module HW.Type.Caption ( Caption, parseVtt, renderTranscript, ) where import qualified Control.Monad as Monad import qualified Data.Char as Char import qualified Data.List.NonEmpty as NonEmpty import qualified Data.Maybe as Maybe import qualified Data.Text as Text import qualified Data.Time as Time import qualified Numeric.Natural as Natural import qualified Text.ParserCombinators.ReadP as ReadP import qualified Text.Read as Read data Caption = Caption { identifier :: Maybe Natural.Natural, start :: Time.TimeOfDay, end :: Time.TimeOfDay, payload :: NonEmpty.NonEmpty Text.Text } deriving (Eq, Show) | Parses a Web Video Text Tracks ( WebVTT ) file into a bunch of captions . If -- parsing fails, this returns nothing. It would be nice to return an -- informative error message, but the underlying parsing library doesn't easily support that . And since we 're dealing with a small set of files added one at -- a time, it should be easy to identify the problem. parseVtt :: Text.Text -> Maybe [Caption] parseVtt = Maybe.listToMaybe . fmap fst . filter (null . snd) . ReadP.readP_to_S vttP . Text.unpack -- | Renders a bunch of captions as a transcript. This throws away all of the -- information that isn't text. Each element of the result list is a line from one person . Lines of dialogue start with @ " > > " @. renderTranscript :: [Caption] -> [Text.Text] renderTranscript = renderCaptionPayload . concatMap (NonEmpty.toList . payload) -- | This type alias is just provided for convenience. Typing out the whole qualified name every time is no fun . Note that a @Parser SomeType@ is typically named @someTypeP@. type Parser = ReadP.ReadP | Parses a WebVTT file . This only parses a small subset of the features that WebVTT can express . < > vttP :: Parser [Caption] vttP = do stringP "WEBVTT" newlineP newlineP ReadP.sepBy captionP newlineP newlineP :: Parser () newlineP = stringP "\r\n" ReadP.<++ charP '\n' isNewline :: Char -> Bool isNewline c = case c of '\n' -> True '\r' -> True _ -> False | Parses a single WebVTT caption . A WebVTT file contains a bunch of captions -- separated by newlines. A single caption has a numeric identifier, a time -- range, and the text of the caption itself. For example: -- > 1 > 00:00:00,000 - > 01:02:03,004 -- > Hello, world! -- -- This parser ensures that the caption ends after it starts. captionP :: Parser Caption captionP = do identifier <- maybeP $ do x <- identifierP newlineP pure x start <- timestampP stringP " --> " end <- timestampP newlineP Monad.guard $ start < end payload <- nonEmptyP lineP pure Caption {identifier, start, end, payload} maybeP :: Parser a -> Parser (Maybe a) maybeP = ReadP.option Nothing . fmap Just | Parses a WebVTT identifier , which for our purposes is always a natural -- number. identifierP :: Parser Natural.Natural identifierP = do digits <- ReadP.munch1 Char.isDigit either fail pure $ Read.readEither digits | Parses a WebVTT timestamp . They use a somewhat strange format of @HH : MM : SS.TTT@ , where is hours , @MM@ is minutes , @SS@ is seconds , and @TTT@ is milliseconds . Every field is zero padded . This parser makes sure that both the minutes and seconds are less than 60 . timestampP :: Parser Time.TimeOfDay timestampP = do hours <- naturalP 2 charP ':' minutes <- naturalP 2 Monad.guard $ minutes < 60 charP ':' seconds <- naturalP 2 Monad.guard $ seconds < 60 charP '.' milliseconds <- naturalP 3 pure . Time.timeToTimeOfDay . Time.picosecondsToDiffTime $ timestampToPicoseconds hours minutes seconds milliseconds -- | Parses a single line of text in a caption. This requires Unix style line -- endings (newline only, no carriage return). lineP :: Parser Text.Text lineP = do line <- ReadP.munch1 $ not . isNewline newlineP pure $ Text.pack line -- | Parses a single character and throws it away. charP :: Char -> Parser () charP = Monad.void . ReadP.char -- | Parses a natural number with the specified number of digits. naturalP :: Int -> Parser Natural.Natural naturalP count = do digits <- ReadP.count count $ ReadP.satisfy Char.isDigit either fail pure $ Read.readEither digits | Given a parser , gets it one or more times . This is like @many1@ except that the return type ( @NonEmpty@ ) actually expresses the fact that there 's at least one element . nonEmptyP :: Parser a -> Parser (NonEmpty.NonEmpty a) nonEmptyP p = (NonEmpty.:|) <$> p <*> ReadP.many p -- | Parses a string and throws it away. stringP :: Text.Text -> Parser () stringP = Monad.void . ReadP.string . Text.unpack | Converts a timestamp ( hours , minutes , seconds , milliseconds ) into an -- integral number of picoseconds. This is mainly useful for conversion into -- other time types. timestampToPicoseconds :: Natural.Natural -> Natural.Natural -> Natural.Natural -> Natural.Natural -> Integer timestampToPicoseconds hours minutes seconds milliseconds = toInteger . millisecondsToPicoseconds $ hoursToMilliseconds hours + minutesToMilliseconds minutes + secondsToMilliseconds seconds + milliseconds -- | Converts hours into milliseconds. hoursToMilliseconds :: Natural.Natural -> Natural.Natural hoursToMilliseconds hours = minutesToMilliseconds $ hours * 60 | Converts minutes into milliseconds . minutesToMilliseconds :: Natural.Natural -> Natural.Natural minutesToMilliseconds minutes = secondsToMilliseconds $ minutes * 60 -- | Converts seconds into milliseconds. secondsToMilliseconds :: Natural.Natural -> Natural.Natural secondsToMilliseconds seconds = seconds * 1000 -- | Converts milliseconds into picoseconds. millisecondsToPicoseconds :: Natural.Natural -> Natural.Natural millisecondsToPicoseconds milliseconds = milliseconds * 1000000000 -- | Renders the payload (text) part of a caption. This is a little trickier than you might think at first because the original input has arbitrary -- newlines throughout. This function removes those newlines but keeps the ones -- when the speaker changes. For example, the input may look like this: -- -- > >> We've been sent -- > good weather. -- > >> Praise be. -- -- But the output from this function will look like this: -- -- > >> We've been sent good weather. -- > >> Praise be. renderCaptionPayload :: [Text.Text] -> [Text.Text] renderCaptionPayload = fmap Text.unwords . filter (not . null) . uncurry (:) . foldr ( \text (buffer, list) -> if text == Text.pack ">>" then ([], (text : buffer) : list) else (text : buffer, list) ) ([], []) . Text.words . Text.unwords
null
https://raw.githubusercontent.com/haskellweekly/haskellweekly/615526de6f1e590fff3bac5a7911aaaacf149b09/source/library/HW/Type/Caption.hs
haskell
| This module defines a data type for audio captions, along with functions for converting from various common formats. Even though there are some very many of the features. It felt better to write simple parsers and renderers rather than relying on a fully fledged library. parsing fails, this returns nothing. It would be nice to return an informative error message, but the underlying parsing library doesn't easily a time, it should be easy to identify the problem. | Renders a bunch of captions as a transcript. This throws away all of the information that isn't text. Each element of the result list is a line from | This type alias is just provided for convenience. Typing out the whole separated by newlines. A single caption has a numeric identifier, a time range, and the text of the caption itself. For example: > Hello, world! This parser ensures that the caption ends after it starts. number. | Parses a single line of text in a caption. This requires Unix style line endings (newline only, no carriage return). | Parses a single character and throws it away. | Parses a natural number with the specified number of digits. | Parses a string and throws it away. integral number of picoseconds. This is mainly useful for conversion into other time types. | Converts hours into milliseconds. | Converts seconds into milliseconds. | Converts milliseconds into picoseconds. | Renders the payload (text) part of a caption. This is a little trickier newlines throughout. This function removes those newlines but keeps the ones when the speaker changes. For example, the input may look like this: > >> We've been sent > good weather. > >> Praise be. But the output from this function will look like this: > >> We've been sent good weather. > >> Praise be.
libraries for these things , the captions that Haskell Weekly uses do n't use module HW.Type.Caption ( Caption, parseVtt, renderTranscript, ) where import qualified Control.Monad as Monad import qualified Data.Char as Char import qualified Data.List.NonEmpty as NonEmpty import qualified Data.Maybe as Maybe import qualified Data.Text as Text import qualified Data.Time as Time import qualified Numeric.Natural as Natural import qualified Text.ParserCombinators.ReadP as ReadP import qualified Text.Read as Read data Caption = Caption { identifier :: Maybe Natural.Natural, start :: Time.TimeOfDay, end :: Time.TimeOfDay, payload :: NonEmpty.NonEmpty Text.Text } deriving (Eq, Show) | Parses a Web Video Text Tracks ( WebVTT ) file into a bunch of captions . If support that . And since we 're dealing with a small set of files added one at parseVtt :: Text.Text -> Maybe [Caption] parseVtt = Maybe.listToMaybe . fmap fst . filter (null . snd) . ReadP.readP_to_S vttP . Text.unpack one person . Lines of dialogue start with @ " > > " @. renderTranscript :: [Caption] -> [Text.Text] renderTranscript = renderCaptionPayload . concatMap (NonEmpty.toList . payload) qualified name every time is no fun . Note that a @Parser SomeType@ is typically named @someTypeP@. type Parser = ReadP.ReadP | Parses a WebVTT file . This only parses a small subset of the features that WebVTT can express . < > vttP :: Parser [Caption] vttP = do stringP "WEBVTT" newlineP newlineP ReadP.sepBy captionP newlineP newlineP :: Parser () newlineP = stringP "\r\n" ReadP.<++ charP '\n' isNewline :: Char -> Bool isNewline c = case c of '\n' -> True '\r' -> True _ -> False | Parses a single WebVTT caption . A WebVTT file contains a bunch of captions > 1 > 00:00:00,000 - > 01:02:03,004 captionP :: Parser Caption captionP = do identifier <- maybeP $ do x <- identifierP newlineP pure x start <- timestampP stringP " --> " end <- timestampP newlineP Monad.guard $ start < end payload <- nonEmptyP lineP pure Caption {identifier, start, end, payload} maybeP :: Parser a -> Parser (Maybe a) maybeP = ReadP.option Nothing . fmap Just | Parses a WebVTT identifier , which for our purposes is always a natural identifierP :: Parser Natural.Natural identifierP = do digits <- ReadP.munch1 Char.isDigit either fail pure $ Read.readEither digits | Parses a WebVTT timestamp . They use a somewhat strange format of @HH : MM : SS.TTT@ , where is hours , @MM@ is minutes , @SS@ is seconds , and @TTT@ is milliseconds . Every field is zero padded . This parser makes sure that both the minutes and seconds are less than 60 . timestampP :: Parser Time.TimeOfDay timestampP = do hours <- naturalP 2 charP ':' minutes <- naturalP 2 Monad.guard $ minutes < 60 charP ':' seconds <- naturalP 2 Monad.guard $ seconds < 60 charP '.' milliseconds <- naturalP 3 pure . Time.timeToTimeOfDay . Time.picosecondsToDiffTime $ timestampToPicoseconds hours minutes seconds milliseconds lineP :: Parser Text.Text lineP = do line <- ReadP.munch1 $ not . isNewline newlineP pure $ Text.pack line charP :: Char -> Parser () charP = Monad.void . ReadP.char naturalP :: Int -> Parser Natural.Natural naturalP count = do digits <- ReadP.count count $ ReadP.satisfy Char.isDigit either fail pure $ Read.readEither digits | Given a parser , gets it one or more times . This is like @many1@ except that the return type ( @NonEmpty@ ) actually expresses the fact that there 's at least one element . nonEmptyP :: Parser a -> Parser (NonEmpty.NonEmpty a) nonEmptyP p = (NonEmpty.:|) <$> p <*> ReadP.many p stringP :: Text.Text -> Parser () stringP = Monad.void . ReadP.string . Text.unpack | Converts a timestamp ( hours , minutes , seconds , milliseconds ) into an timestampToPicoseconds :: Natural.Natural -> Natural.Natural -> Natural.Natural -> Natural.Natural -> Integer timestampToPicoseconds hours minutes seconds milliseconds = toInteger . millisecondsToPicoseconds $ hoursToMilliseconds hours + minutesToMilliseconds minutes + secondsToMilliseconds seconds + milliseconds hoursToMilliseconds :: Natural.Natural -> Natural.Natural hoursToMilliseconds hours = minutesToMilliseconds $ hours * 60 | Converts minutes into milliseconds . minutesToMilliseconds :: Natural.Natural -> Natural.Natural minutesToMilliseconds minutes = secondsToMilliseconds $ minutes * 60 secondsToMilliseconds :: Natural.Natural -> Natural.Natural secondsToMilliseconds seconds = seconds * 1000 millisecondsToPicoseconds :: Natural.Natural -> Natural.Natural millisecondsToPicoseconds milliseconds = milliseconds * 1000000000 than you might think at first because the original input has arbitrary renderCaptionPayload :: [Text.Text] -> [Text.Text] renderCaptionPayload = fmap Text.unwords . filter (not . null) . uncurry (:) . foldr ( \text (buffer, list) -> if text == Text.pack ">>" then ([], (text : buffer) : list) else (text : buffer, list) ) ([], []) . Text.words . Text.unwords
c90c1343ef8686ffb9cbd584c9d6d6ab07b3ed920d3c0040777057f4fb779256
andrewMacmurray/haskell-book-solutions
equalityData.hs
data TisAnInteger = TisAnInteger Integer instance Eq TisAnInteger where (==) (TisAnInteger a) (TisAnInteger a') = a == a' data TwoIntegers = Two Integer Integer instance Eq TwoIntegers where (==) (Two a b) (Two a' b') = a == a' && b == b' data StringOrInt = TisAString String | TisAnInt Integer instance Eq StringOrInt where (==) (TisAString a) (TisAString b) = a == b (==) (TisAnInt c) (TisAnInt d) = c == d (==) _ _ = False data Pair a = Pair a a instance (Eq a) => Eq (Pair a) where (==) (Pair a b) (Pair a' b') = a == a' && b == b' data Tuple a b = Tuple a b instance (Eq a, Eq b) => Eq (Tuple a b) where (==) (Tuple a b) (Tuple a' b') = a == a' && b == b' data Which a = ThisOne a | ThatOne a instance Eq a => Eq (Which a) where (==) (ThisOne a) (ThatOne b) = a == b data EitherOr a b = Hello a | Goodbye b instance (Eq a, Eq b) => Eq (EitherOr a b) where (==) (Hello a') (Hello a'') = a' == a'' (==) (Goodbye b') (Goodbye b'') = b' == b'' (==) _ _ = False
null
https://raw.githubusercontent.com/andrewMacmurray/haskell-book-solutions/f4fd386187c03828d1736d9a43642ab4f0ec6462/src/ch6/equalityData.hs
haskell
data TisAnInteger = TisAnInteger Integer instance Eq TisAnInteger where (==) (TisAnInteger a) (TisAnInteger a') = a == a' data TwoIntegers = Two Integer Integer instance Eq TwoIntegers where (==) (Two a b) (Two a' b') = a == a' && b == b' data StringOrInt = TisAString String | TisAnInt Integer instance Eq StringOrInt where (==) (TisAString a) (TisAString b) = a == b (==) (TisAnInt c) (TisAnInt d) = c == d (==) _ _ = False data Pair a = Pair a a instance (Eq a) => Eq (Pair a) where (==) (Pair a b) (Pair a' b') = a == a' && b == b' data Tuple a b = Tuple a b instance (Eq a, Eq b) => Eq (Tuple a b) where (==) (Tuple a b) (Tuple a' b') = a == a' && b == b' data Which a = ThisOne a | ThatOne a instance Eq a => Eq (Which a) where (==) (ThisOne a) (ThatOne b) = a == b data EitherOr a b = Hello a | Goodbye b instance (Eq a, Eq b) => Eq (EitherOr a b) where (==) (Hello a') (Hello a'') = a' == a'' (==) (Goodbye b') (Goodbye b'') = b' == b'' (==) _ _ = False
964f16f7c275625c1da7797400eb034e4c99d6548567004d72d394624769d07b
hatsugai/Guedra
test_vsplitter2.ml
open Csp open Guedra let init () = let (wch, pch) = create_toplevel_window "Guedra" 0 0 768 512 in let rch0 = make_chan () in let rch1 = make_chan () in let cch0 = make_chan () in let cch1 = make_chan () in let nch = make_chan () in let cwch0 = make_chan () in let cwch1 = make_chan () in let cwch2 = make_chan () in let cwch3 = make_chan () in par [ (fun () -> Vsplitter.init Splitter.Movable wch pch cch0 nch rch0 cwch0 cwch1 200 4 4); (fun () -> Vsplitter.init Splitter.Movable cwch0 rch0 cch1 nch rch1 cwch2 cwch3 200 4 4); (fun () -> Window.init cwch1 rch0); (fun () -> Window.init cwch2 rch1); (fun () -> Window.init cwch3 rch1)] let () = reg_client init
null
https://raw.githubusercontent.com/hatsugai/Guedra/592e9b4cff151228735d2c61c337154cde8b5329/test/test_vsplitter2.ml
ocaml
open Csp open Guedra let init () = let (wch, pch) = create_toplevel_window "Guedra" 0 0 768 512 in let rch0 = make_chan () in let rch1 = make_chan () in let cch0 = make_chan () in let cch1 = make_chan () in let nch = make_chan () in let cwch0 = make_chan () in let cwch1 = make_chan () in let cwch2 = make_chan () in let cwch3 = make_chan () in par [ (fun () -> Vsplitter.init Splitter.Movable wch pch cch0 nch rch0 cwch0 cwch1 200 4 4); (fun () -> Vsplitter.init Splitter.Movable cwch0 rch0 cch1 nch rch1 cwch2 cwch3 200 4 4); (fun () -> Window.init cwch1 rch0); (fun () -> Window.init cwch2 rch1); (fun () -> Window.init cwch3 rch1)] let () = reg_client init
77966f950b34e1873213259acb3765250a0e8abd9ef1c35ccca0e647d15b3aec
urbanslug/graphite
test-fm-search.rkt
#lang racket (require rackunit) (require math/array) (require "../../graphite/algorithms/fm-search.rkt") (require "../../graphite/algorithms/fm-index.rkt") (require "../../graphite/algorithms/suffix-array.rkt") (require "../../graphite/algorithms/bwt.rkt") (define s "abaaba") (define fl-list (fl-map s)) (check-equal? (run-length-encode-f (second fl-list)) (array #[1 4 2])) (check-equal? (run-length-encode (third fl-list)) '((#\a . 1) (#\b . 2) (#\a . 1) (#\$ . 1) (#\a . 2)))
null
https://raw.githubusercontent.com/urbanslug/graphite/bcac6bd61172c52d1cc89c0bd0abe8ad3c6a6576/tests/algorithms/test-fm-search.rkt
racket
#lang racket (require rackunit) (require math/array) (require "../../graphite/algorithms/fm-search.rkt") (require "../../graphite/algorithms/fm-index.rkt") (require "../../graphite/algorithms/suffix-array.rkt") (require "../../graphite/algorithms/bwt.rkt") (define s "abaaba") (define fl-list (fl-map s)) (check-equal? (run-length-encode-f (second fl-list)) (array #[1 4 2])) (check-equal? (run-length-encode (third fl-list)) '((#\a . 1) (#\b . 2) (#\a . 1) (#\$ . 1) (#\a . 2)))
4558168247d7afa3f790197302e211f2a7cd96cc8e048058ff4eca9f10d524a1
massung/racket-raylib
info.rkt
#lang setup/infotab (define install-platform "win32\\x86_64") (define copy-foreign-libs '("raylib.dll"))
null
https://raw.githubusercontent.com/massung/racket-raylib/1f7882076e0f7614ce1c955e5bb8a67de5aa18bb/win64-x86_64/info.rkt
racket
#lang setup/infotab (define install-platform "win32\\x86_64") (define copy-foreign-libs '("raylib.dll"))
6a4855444bdb2e076052436862ea6b3118a2ab8865f6de6ef9d72f3a08974879
mwotton/squealgen
Public.hs
| This code was originally created by squealgen . Edit if you know how it got made and are willing to own it now . # LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE OverloadedLabels # # LANGUAGE FlexibleContexts # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PolyKinds # # LANGUAGE TypeApplications # # LANGUAGE TypeOperators # {-# LANGUAGE GADTs #-} # OPTIONS_GHC -fno - warn - unticked - promoted - constructors # module InetArrays.Public where import Squeal.PostgreSQL import GHC.TypeLits(Symbol) type PGname = UnsafePGType "name" type PGregclass = UnsafePGType "regclass" type PGltree = UnsafePGType "ltree" type PGcidr = UnsafePGType "cidr" type PGltxtquery = UnsafePGType "ltxtquery" type PGlquery = UnsafePGType "lquery" type DB = '["public" ::: Schema] type Schema = Join Tables (Join Views (Join Enums (Join Functions (Join Composites Domains)))) -- enums -- decls type Enums = ('[] :: [(Symbol,SchemumType)]) type Composites = ('[] :: [(Symbol,SchemumType)]) -- schema type Tables = ('[ "address_sets" ::: 'Table AddressSetsTable] :: [(Symbol,SchemumType)]) defs type AddressSetsColumns = '["addresses" ::: 'NoDef :=> 'NotNull (PGvararray (NotNull PGinet))] type AddressSetsConstraints = '[] type AddressSetsTable = AddressSetsConstraints :=> AddressSetsColumns -- VIEWS type Views = '[] -- functions type Functions = '[ ] type Domains = '[]
null
https://raw.githubusercontent.com/mwotton/squealgen/72ebca82f75534e806851b8336fc3e2400f801f6/test/InetArrays/Public.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE GADTs # enums decls schema VIEWS functions
| This code was originally created by squealgen . Edit if you know how it got made and are willing to own it now . # LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE OverloadedLabels # # LANGUAGE FlexibleContexts # # LANGUAGE PolyKinds # # LANGUAGE TypeApplications # # LANGUAGE TypeOperators # # OPTIONS_GHC -fno - warn - unticked - promoted - constructors # module InetArrays.Public where import Squeal.PostgreSQL import GHC.TypeLits(Symbol) type PGname = UnsafePGType "name" type PGregclass = UnsafePGType "regclass" type PGltree = UnsafePGType "ltree" type PGcidr = UnsafePGType "cidr" type PGltxtquery = UnsafePGType "ltxtquery" type PGlquery = UnsafePGType "lquery" type DB = '["public" ::: Schema] type Schema = Join Tables (Join Views (Join Enums (Join Functions (Join Composites Domains)))) type Enums = ('[] :: [(Symbol,SchemumType)]) type Composites = ('[] :: [(Symbol,SchemumType)]) type Tables = ('[ "address_sets" ::: 'Table AddressSetsTable] :: [(Symbol,SchemumType)]) defs type AddressSetsColumns = '["addresses" ::: 'NoDef :=> 'NotNull (PGvararray (NotNull PGinet))] type AddressSetsConstraints = '[] type AddressSetsTable = AddressSetsConstraints :=> AddressSetsColumns type Views = '[] type Functions = '[ ] type Domains = '[]
3ff6591642079fd3a8aee6148814b62f82ffef4bf1ce31005bb8e90786248941
rabbitmq/ra
ra_flru.erl
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %% Copyright ( c ) 2017 - 2022 VMware , Inc. or its affiliates . All rights reserved . %% %% @hidden -module(ra_flru). %% small fixed size simple lru cache %% inefficient on larger sizes -export([ new/2, fetch/2, insert/3, evict/2, evict_all/1, size/1 ]). -define(MAX_SIZE, 5). -type kv_item() :: {Key :: term(), Value :: term()}. -type handler_fun() :: fun((kv_item()) -> ok). -record(?MODULE, {max_size = ?MAX_SIZE :: non_neg_integer(), items = [] :: [term()], handler = fun (_) -> ok end :: handler_fun()}). -opaque state() :: #?MODULE{}. -export_type([ state/0 ]). -spec new(non_neg_integer(), handler_fun()) -> state(). new(MaxSize, Handler) -> #?MODULE{handler = Handler, max_size = MaxSize}. -spec fetch(term(), state()) -> {ok, term(), state()} | error. fetch(Key, #?MODULE{items = [{Key, Value} | _]} = State) -> %% head optimisation {ok, Value, State}; fetch(Key, #?MODULE{items = Items0} = State0) -> case lists:keytake(Key, 1, Items0) of {value, {_, Value} = T, Items} -> {ok, Value, State0#?MODULE{items = [T | Items]}}; false -> error end. -spec insert(term(), term(), state()) -> state(). insert(Key, Value, #?MODULE{items = Items, max_size = M, handler = Handler} = State) when length(Items) =:= M -> %% cache is full, discard last item [Old | Rem] = lists:reverse(Items), %% call the handler ok = Handler(Old), State#?MODULE{items = [{Key, Value} | lists:reverse(Rem)]}; insert(Key, Value, #?MODULE{items = Items} = State) -> %% else just append it State#?MODULE{items = [{Key, Value} | Items]}. -spec evict(Key :: term(), state()) -> {Evicted :: kv_item(), state()} | error. evict(Key, #?MODULE{items = Items0, handler = Handler} = State) -> case lists:keytake(Key, 1, Items0) of {value, T, Items} -> ok = Handler(T), {T, State#?MODULE{items = Items}}; false -> error end. -spec evict_all(state()) -> state(). evict_all(#?MODULE{items = Items, handler = Handler}) -> [Handler(T) || T <- Items], #?MODULE{items = []}. -spec size(state()) -> non_neg_integer(). size(#?MODULE{items = Items}) -> length(Items). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). evit_test() -> C0 = new(3, fun(I) -> ?debugFmt("~w evicted", [I]) end), C1 = insert(k1, v1, C0), C2 = insert(k2, v2, C1), {{k1, v1}, C3} = evict(k1, C2), error = evict(k3, C3), ok. basics_test() -> C0 = new(3, fun(I) -> ?debugFmt("~w evicted", [I]) end), C1 = insert(k1, v1, C0), C2 = insert(k2, v2, C1), C3 = insert(k3, v3, C2), C4 = insert(k4, v4, C3), ?assertEqual(error, fetch(k1, C4)), {ok, v2, C5} = fetch(k2, C4), C6 = insert(k5, v5, C5), %% k2 should still be readable here {ok, v2, C7} = fetch(k2, C6), %% k3 should have been evicted error = fetch(k3, C7), ok. -endif.
null
https://raw.githubusercontent.com/rabbitmq/ra/72439a5c25f6cf9e8d2a26b21fe456f94df516d4/src/ra_flru.erl
erlang
@hidden small fixed size simple lru cache inefficient on larger sizes head optimisation cache is full, discard last item call the handler else just append it k2 should still be readable here k3 should have been evicted
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. Copyright ( c ) 2017 - 2022 VMware , Inc. or its affiliates . All rights reserved . -module(ra_flru). -export([ new/2, fetch/2, insert/3, evict/2, evict_all/1, size/1 ]). -define(MAX_SIZE, 5). -type kv_item() :: {Key :: term(), Value :: term()}. -type handler_fun() :: fun((kv_item()) -> ok). -record(?MODULE, {max_size = ?MAX_SIZE :: non_neg_integer(), items = [] :: [term()], handler = fun (_) -> ok end :: handler_fun()}). -opaque state() :: #?MODULE{}. -export_type([ state/0 ]). -spec new(non_neg_integer(), handler_fun()) -> state(). new(MaxSize, Handler) -> #?MODULE{handler = Handler, max_size = MaxSize}. -spec fetch(term(), state()) -> {ok, term(), state()} | error. fetch(Key, #?MODULE{items = [{Key, Value} | _]} = State) -> {ok, Value, State}; fetch(Key, #?MODULE{items = Items0} = State0) -> case lists:keytake(Key, 1, Items0) of {value, {_, Value} = T, Items} -> {ok, Value, State0#?MODULE{items = [T | Items]}}; false -> error end. -spec insert(term(), term(), state()) -> state(). insert(Key, Value, #?MODULE{items = Items, max_size = M, handler = Handler} = State) when length(Items) =:= M -> [Old | Rem] = lists:reverse(Items), ok = Handler(Old), State#?MODULE{items = [{Key, Value} | lists:reverse(Rem)]}; insert(Key, Value, #?MODULE{items = Items} = State) -> State#?MODULE{items = [{Key, Value} | Items]}. -spec evict(Key :: term(), state()) -> {Evicted :: kv_item(), state()} | error. evict(Key, #?MODULE{items = Items0, handler = Handler} = State) -> case lists:keytake(Key, 1, Items0) of {value, T, Items} -> ok = Handler(T), {T, State#?MODULE{items = Items}}; false -> error end. -spec evict_all(state()) -> state(). evict_all(#?MODULE{items = Items, handler = Handler}) -> [Handler(T) || T <- Items], #?MODULE{items = []}. -spec size(state()) -> non_neg_integer(). size(#?MODULE{items = Items}) -> length(Items). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). evit_test() -> C0 = new(3, fun(I) -> ?debugFmt("~w evicted", [I]) end), C1 = insert(k1, v1, C0), C2 = insert(k2, v2, C1), {{k1, v1}, C3} = evict(k1, C2), error = evict(k3, C3), ok. basics_test() -> C0 = new(3, fun(I) -> ?debugFmt("~w evicted", [I]) end), C1 = insert(k1, v1, C0), C2 = insert(k2, v2, C1), C3 = insert(k3, v3, C2), C4 = insert(k4, v4, C3), ?assertEqual(error, fetch(k1, C4)), {ok, v2, C5} = fetch(k2, C4), C6 = insert(k5, v5, C5), {ok, v2, C7} = fetch(k2, C6), error = fetch(k3, C7), ok. -endif.
b2ac305233da2351a2fe3b5fdd51a527c9b597b7e66fea4166ff0298e928505a
zoka/webREPLdemo
admin.clj
(ns noirmon.views.admin (:use noir.core hiccup.core hiccup.page hiccup.element hiccup.form) (:require [noir.session :as session] [noir.validation :as vali] [noir.response :as resp] [clojure.string :as string] [noirmon.models.post :as posts] [noirmon.models.user :as users] [noirmon.views.common :as common])) ;; Links (def post-actions [{:url "/blog/admin/post/add" :text "Add a post"}]) (def user-actions [{:url "/blog/admin/user/add" :text "Add a user"}]) ;; Partials (defpartial error-text [errors] [:p (string/join "<br/>" errors)]) (defpartial post-fields [{:keys [title body]}] (vali/on-error :title error-text) (text-field {:placeholder "Title"} :title title) (vali/on-error :body error-text) (text-area {:placeholder "Body"} :body body)) (defpartial user-fields [{:keys [username] :as usr}] (vali/on-error :username error-text) (text-field {:placeholder "Username"} :username username) (password-field {:placeholder "Password"} :password)) (defpartial post-item [{:keys [title] :as post}] [:li (link-to (posts/edit-url post) title)]) (defpartial action-item [{:keys [url text]}] [:li (link-to url text)]) (defpartial user-item [{:keys [username]}] [:li (link-to (str "/blog/admin/user/edit/" username) username)]) ;; Admin pages ;;force you to be an admin to get to the admin section (pre-route "/blog/admin*" {} (when-not (users/admin?) (resp/redirect "/blog/login"))) (defpage "/blog/login" {:as user} (if (users/admin?) (resp/redirect "/blog/admin") (common/main-layout (form-to [:post "/blog/login"] [:ul.actions [:li (link-to {:class "submit"} "/" "Login")]] (user-fields user) (submit-button {:class "submit"} "submit"))))) (defpage [:post "/blog/login"] {:as user} (if (users/login! user) (resp/redirect "/blog/admin") (render "/blog/login" user))) (defpage "/blog/logout" {} (session/clear!) (resp/redirect "/blog/")) Post pages (defpage "/blog/admin" {} (common/admin-layout [:ul.actions (map action-item post-actions)] [:ul.items (map post-item (posts/get-latest))])) (defpage "/blog/admin/post/add" {:as post} (common/admin-layout (form-to [:post "/blog/admin/post/add"] [:ul.actions [:li (link-to {:class "submit"} "/" "Add")]] (post-fields post) (submit-button {:class "submit"} "add post")))) (defpage [:post "/blog/admin/post/add"] {:as post} (if (posts/add! post) (resp/redirect "/blog/admin") (render "/blog/admin/post/add" post))) (defpage "/blog/admin/post/edit/:id" {:keys [id]} (if-let [post (posts/id->post id)] (common/admin-layout (form-to [:post (str "/blog/admin/post/edit/" id)] [:ul.actions [:li (link-to {:class "submit"} "/" "Submit")] [:li (link-to {:class "delete"} (str "/blog/admin/post/remove/" id) "Remove")]] (post-fields post) (submit-button {:class "submit"} "submit"))))) (defpage [:post "/blog/admin/post/edit/:id"] {:keys [id] :as post} (if (posts/edit! post) (resp/redirect "/blog/admin") (render "/blog/admin/post/edit/:id" post))) (defpage "/blog/admin/post/remove/:id" {:keys [id]} (posts/remove! id) (resp/redirect "/blog/admin")) ;; User pages (defpage "/blog/admin/users" {} (common/admin-layout [:ul.actions (map action-item user-actions)] [:ul.items (map user-item (users/all))])) (defpage "/blog/admin/user/add" {} (common/admin-layout (form-to [:post "/blog/admin/user/add"] [:ul.actions [:li (link-to {:class "submit"} "/" "Add")]] (user-fields {}) (submit-button {:class "submit"} "add user")))) (defpage [:post "/blog/admin/user/add"] {:keys [username password] :as neue-user} (if (users/add! neue-user) (resp/redirect "/blog/admin/users") (render "/blog/admin/user/add" neue-user))) (defpage "/blog/admin/user/edit/:old-name" {:keys [old-name]} (let [user (users/get-username old-name)] (common/admin-layout (form-to [:post (str "/blog/admin/user/edit/" old-name)] [:ul.actions [:li (link-to {:class "submit"} "/" "Submit")] [:li (link-to {:class "delete"} (str "/blog/admin/user/remove/" old-name) "Remove")]] (user-fields user))))) (defpage [:post "/blog/admin/user/edit/:old-name"] {:keys [old-name] :as user} (if (users/edit! old-name user) (resp/redirect "/blog/admin/users") (render "/blog/admin/user/edit/:old-name" user))) (defpage "/blog/admin/user/remove/:id" {:keys [id]} (users/remove! id) (resp/redirect "/blog/admin/users"))
null
https://raw.githubusercontent.com/zoka/webREPLdemo/fc2dfe13ce141e47fad51396a97edcbe610211e9/src/noirmon/views/admin.clj
clojure
Links Partials Admin pages force you to be an admin to get to the admin section User pages
(ns noirmon.views.admin (:use noir.core hiccup.core hiccup.page hiccup.element hiccup.form) (:require [noir.session :as session] [noir.validation :as vali] [noir.response :as resp] [clojure.string :as string] [noirmon.models.post :as posts] [noirmon.models.user :as users] [noirmon.views.common :as common])) (def post-actions [{:url "/blog/admin/post/add" :text "Add a post"}]) (def user-actions [{:url "/blog/admin/user/add" :text "Add a user"}]) (defpartial error-text [errors] [:p (string/join "<br/>" errors)]) (defpartial post-fields [{:keys [title body]}] (vali/on-error :title error-text) (text-field {:placeholder "Title"} :title title) (vali/on-error :body error-text) (text-area {:placeholder "Body"} :body body)) (defpartial user-fields [{:keys [username] :as usr}] (vali/on-error :username error-text) (text-field {:placeholder "Username"} :username username) (password-field {:placeholder "Password"} :password)) (defpartial post-item [{:keys [title] :as post}] [:li (link-to (posts/edit-url post) title)]) (defpartial action-item [{:keys [url text]}] [:li (link-to url text)]) (defpartial user-item [{:keys [username]}] [:li (link-to (str "/blog/admin/user/edit/" username) username)]) (pre-route "/blog/admin*" {} (when-not (users/admin?) (resp/redirect "/blog/login"))) (defpage "/blog/login" {:as user} (if (users/admin?) (resp/redirect "/blog/admin") (common/main-layout (form-to [:post "/blog/login"] [:ul.actions [:li (link-to {:class "submit"} "/" "Login")]] (user-fields user) (submit-button {:class "submit"} "submit"))))) (defpage [:post "/blog/login"] {:as user} (if (users/login! user) (resp/redirect "/blog/admin") (render "/blog/login" user))) (defpage "/blog/logout" {} (session/clear!) (resp/redirect "/blog/")) Post pages (defpage "/blog/admin" {} (common/admin-layout [:ul.actions (map action-item post-actions)] [:ul.items (map post-item (posts/get-latest))])) (defpage "/blog/admin/post/add" {:as post} (common/admin-layout (form-to [:post "/blog/admin/post/add"] [:ul.actions [:li (link-to {:class "submit"} "/" "Add")]] (post-fields post) (submit-button {:class "submit"} "add post")))) (defpage [:post "/blog/admin/post/add"] {:as post} (if (posts/add! post) (resp/redirect "/blog/admin") (render "/blog/admin/post/add" post))) (defpage "/blog/admin/post/edit/:id" {:keys [id]} (if-let [post (posts/id->post id)] (common/admin-layout (form-to [:post (str "/blog/admin/post/edit/" id)] [:ul.actions [:li (link-to {:class "submit"} "/" "Submit")] [:li (link-to {:class "delete"} (str "/blog/admin/post/remove/" id) "Remove")]] (post-fields post) (submit-button {:class "submit"} "submit"))))) (defpage [:post "/blog/admin/post/edit/:id"] {:keys [id] :as post} (if (posts/edit! post) (resp/redirect "/blog/admin") (render "/blog/admin/post/edit/:id" post))) (defpage "/blog/admin/post/remove/:id" {:keys [id]} (posts/remove! id) (resp/redirect "/blog/admin")) (defpage "/blog/admin/users" {} (common/admin-layout [:ul.actions (map action-item user-actions)] [:ul.items (map user-item (users/all))])) (defpage "/blog/admin/user/add" {} (common/admin-layout (form-to [:post "/blog/admin/user/add"] [:ul.actions [:li (link-to {:class "submit"} "/" "Add")]] (user-fields {}) (submit-button {:class "submit"} "add user")))) (defpage [:post "/blog/admin/user/add"] {:keys [username password] :as neue-user} (if (users/add! neue-user) (resp/redirect "/blog/admin/users") (render "/blog/admin/user/add" neue-user))) (defpage "/blog/admin/user/edit/:old-name" {:keys [old-name]} (let [user (users/get-username old-name)] (common/admin-layout (form-to [:post (str "/blog/admin/user/edit/" old-name)] [:ul.actions [:li (link-to {:class "submit"} "/" "Submit")] [:li (link-to {:class "delete"} (str "/blog/admin/user/remove/" old-name) "Remove")]] (user-fields user))))) (defpage [:post "/blog/admin/user/edit/:old-name"] {:keys [old-name] :as user} (if (users/edit! old-name user) (resp/redirect "/blog/admin/users") (render "/blog/admin/user/edit/:old-name" user))) (defpage "/blog/admin/user/remove/:id" {:keys [id]} (users/remove! id) (resp/redirect "/blog/admin/users"))
1a5a44b47fc7d6ad21a86546a63e3fb51fcf524a200a7d5dfe4ca27312b4db67
GillianPlatform/Gillian
wislSHeap.mli
open Gillian.Symbolic open Gil_syntax open Gillian.Debugger.Utils type t [@@deriving yojson] type err = | MissingResource of (WislLActions.ga * string * Expr.t option) | DoubleFree of string | UseAfterFree of string | MemoryLeak | OutOfBounds of (int option * string * Expr.t) | InvalidLocation [@@deriving yojson, show] val init : unit -> t val alloc : t -> int -> string val dispose : t -> string -> (unit, err) Result.t val clean_up : Expr.Set.t -> t -> Expr.Set.t * Expr.Set.t val get_cell : pfs:PureContext.t -> gamma:TypEnv.t -> t -> string -> Expr.t -> (string * Expr.t * Expr.t, err) result val set_cell : pfs:PureContext.t -> gamma:TypEnv.t -> t -> string -> Expr.t -> Expr.t -> (unit, err) result val rem_cell : t -> string -> Expr.t -> (unit, err) result val get_bound : t -> string -> (int, err) result val set_bound : t -> string -> int -> (unit, err) result val rem_bound : t -> string -> (unit, err) result val get_freed : t -> string -> (unit, err) result val set_freed : t -> string -> unit val rem_freed : t -> string -> (unit, err) result val pp : t Fmt.t val copy : t -> t val lvars : t -> SS.t val alocs : t -> SS.t val substitution_in_place : Gillian.Symbolic.Subst.t -> t -> (t * Gillian.Gil_syntax.Formula.Set.t * (string * Gillian.Gil_syntax.Type.t) list) list val assertions : t -> Gillian.Gil_syntax.Asrt.t list val add_debugger_variables : store:(string * Gillian.Gil_syntax.Expr.t) list -> memory:t -> is_gil_file:bool -> get_new_scope_id:(unit -> int) -> Variable.ts -> Variable.scope list
null
https://raw.githubusercontent.com/GillianPlatform/Gillian/04d142e38f5fd622705a71ce3a3daed1ac7630a0/wisl/lib/semantics/wislSHeap.mli
ocaml
open Gillian.Symbolic open Gil_syntax open Gillian.Debugger.Utils type t [@@deriving yojson] type err = | MissingResource of (WislLActions.ga * string * Expr.t option) | DoubleFree of string | UseAfterFree of string | MemoryLeak | OutOfBounds of (int option * string * Expr.t) | InvalidLocation [@@deriving yojson, show] val init : unit -> t val alloc : t -> int -> string val dispose : t -> string -> (unit, err) Result.t val clean_up : Expr.Set.t -> t -> Expr.Set.t * Expr.Set.t val get_cell : pfs:PureContext.t -> gamma:TypEnv.t -> t -> string -> Expr.t -> (string * Expr.t * Expr.t, err) result val set_cell : pfs:PureContext.t -> gamma:TypEnv.t -> t -> string -> Expr.t -> Expr.t -> (unit, err) result val rem_cell : t -> string -> Expr.t -> (unit, err) result val get_bound : t -> string -> (int, err) result val set_bound : t -> string -> int -> (unit, err) result val rem_bound : t -> string -> (unit, err) result val get_freed : t -> string -> (unit, err) result val set_freed : t -> string -> unit val rem_freed : t -> string -> (unit, err) result val pp : t Fmt.t val copy : t -> t val lvars : t -> SS.t val alocs : t -> SS.t val substitution_in_place : Gillian.Symbolic.Subst.t -> t -> (t * Gillian.Gil_syntax.Formula.Set.t * (string * Gillian.Gil_syntax.Type.t) list) list val assertions : t -> Gillian.Gil_syntax.Asrt.t list val add_debugger_variables : store:(string * Gillian.Gil_syntax.Expr.t) list -> memory:t -> is_gil_file:bool -> get_new_scope_id:(unit -> int) -> Variable.ts -> Variable.scope list
298169c6c2e4346b9c69dbb546e6711a481086185795a8bf23647419b0ecd7e1
achirkin/qua-kit
UserManager.hs
{-# OPTIONS_HADDOCK hide, prune #-} module Handler.Mooc.Admin.UserManager ( getAdminUserManagerR , postSetUserRoleR , postAdminCreateUserR ) where import Import hiding ((==.), on) import qualified Data.Text as T import Text.Read import Database.Persist.Sql import Yesod.Auth.Email import Handler.Mooc.Admin getAdminUserManagerR :: Handler Html getAdminUserManagerR = do requireAdmin users <- runDB $ selectList [] [Asc UserId] let roles = filter (/= UR_NOBODY) [minBound .. maxBound] adminLayout "Welcome to the user manager" $ do setTitle "qua-kit - user manager" $(widgetFile "mooc/admin/user-manager") roleFormInput :: FormInput Handler (Maybe UserRole) roleFormInput = (readMaybe . T.unpack) <$> ireq textField "role" postSetUserRoleR :: UserId -> Handler Html postSetUserRoleR userId = do requireAdmin mrole <- runInputPost roleFormInput case mrole of Nothing -> sendResponseStatus status400 ("invalid role" :: Text) Just role -> do runDB $ update userId [UserRole =. role] redirect AdminUserManagerR data CreateUserData = CreateUserData { createUserDataEmail :: Text , createUserDataRoleStr :: Text } deriving (Show, Eq) userFormInput :: FormInput Handler CreateUserData userFormInput = CreateUserData <$> ireq textField "email" <*> ireq textField "role" postAdminCreateUserR :: Handler Html postAdminCreateUserR = do requireAdmin CreateUserData {..} <- runInputPost userFormInput case readMaybe $ T.unpack createUserDataRoleStr of Nothing -> sendResponseStatus status400 ("invalid role" :: Text) Just role -> do app <- getYesod :: Handler App verKey <- liftIO $ randomKey app lid <- addUnverified createUserDataEmail verKey render <- getUrlRender let verUrl = render $ AuthR $ verifyR (toPathPiece lid) verKey runDB $ update lid [UserRole =. role] $(logDebug) $ T.unlines [ "Sending verification url from admin panel." , "Copy/ Paste this URL in your browser: " <> verUrl ] sendVerifyEmail createUserDataEmail verKey verUrl setMessage "User added successfully" redirect AdminUserManagerR
null
https://raw.githubusercontent.com/achirkin/qua-kit/9f859e2078d5f059fb87b2f6baabcde7170d4e95/apps/hs/qua-server/src/Handler/Mooc/Admin/UserManager.hs
haskell
# OPTIONS_HADDOCK hide, prune #
module Handler.Mooc.Admin.UserManager ( getAdminUserManagerR , postSetUserRoleR , postAdminCreateUserR ) where import Import hiding ((==.), on) import qualified Data.Text as T import Text.Read import Database.Persist.Sql import Yesod.Auth.Email import Handler.Mooc.Admin getAdminUserManagerR :: Handler Html getAdminUserManagerR = do requireAdmin users <- runDB $ selectList [] [Asc UserId] let roles = filter (/= UR_NOBODY) [minBound .. maxBound] adminLayout "Welcome to the user manager" $ do setTitle "qua-kit - user manager" $(widgetFile "mooc/admin/user-manager") roleFormInput :: FormInput Handler (Maybe UserRole) roleFormInput = (readMaybe . T.unpack) <$> ireq textField "role" postSetUserRoleR :: UserId -> Handler Html postSetUserRoleR userId = do requireAdmin mrole <- runInputPost roleFormInput case mrole of Nothing -> sendResponseStatus status400 ("invalid role" :: Text) Just role -> do runDB $ update userId [UserRole =. role] redirect AdminUserManagerR data CreateUserData = CreateUserData { createUserDataEmail :: Text , createUserDataRoleStr :: Text } deriving (Show, Eq) userFormInput :: FormInput Handler CreateUserData userFormInput = CreateUserData <$> ireq textField "email" <*> ireq textField "role" postAdminCreateUserR :: Handler Html postAdminCreateUserR = do requireAdmin CreateUserData {..} <- runInputPost userFormInput case readMaybe $ T.unpack createUserDataRoleStr of Nothing -> sendResponseStatus status400 ("invalid role" :: Text) Just role -> do app <- getYesod :: Handler App verKey <- liftIO $ randomKey app lid <- addUnverified createUserDataEmail verKey render <- getUrlRender let verUrl = render $ AuthR $ verifyR (toPathPiece lid) verKey runDB $ update lid [UserRole =. role] $(logDebug) $ T.unlines [ "Sending verification url from admin panel." , "Copy/ Paste this URL in your browser: " <> verUrl ] sendVerifyEmail createUserDataEmail verKey verUrl setMessage "User added successfully" redirect AdminUserManagerR
54180f41f14bc93ac27c782c7cfac2f02e323e42987fa16a58c830b759e6cd67
maxlibin/ParentalJobs
jobs_t.ml
(* Auto-generated from "jobs.atd" *) [@@@ocaml.warning "-27-32-35-39"] type salary = { salaryFrom: string; salaryTo: string; salaryType: string } type jobOverview = { _id: string; company: string; jobTitle: string; employmentType: string; seniority: string; minExperience: string; jobCategories: string; salary: salary; postedOn: string; parentsFriendly: bool } type latestJobs = jobOverview list type jobs = jobOverview list type job = { _id: string; company: string; jobTitle: string; jobId: string; address: string; employmentType: string; seniority: string; minExperience: string; jobCategories: string; salary: salary; postedOn: string; jobDescription: string; requirement: string }
null
https://raw.githubusercontent.com/maxlibin/ParentalJobs/0657b405051aa4d5112760eff769f75f2e4c40dd/packages/frontend/src/types/jobs_t.ml
ocaml
Auto-generated from "jobs.atd"
[@@@ocaml.warning "-27-32-35-39"] type salary = { salaryFrom: string; salaryTo: string; salaryType: string } type jobOverview = { _id: string; company: string; jobTitle: string; employmentType: string; seniority: string; minExperience: string; jobCategories: string; salary: salary; postedOn: string; parentsFriendly: bool } type latestJobs = jobOverview list type jobs = jobOverview list type job = { _id: string; company: string; jobTitle: string; jobId: string; address: string; employmentType: string; seniority: string; minExperience: string; jobCategories: string; salary: salary; postedOn: string; jobDescription: string; requirement: string }
ede69a88b251221e225e32bfaee36bd4d702bf49ca7706d53ec2c6903ca5caa5
ArulselvanMadhavan/haskell-first-principles
ReaderPractice.hs
module ReaderPractice where import Control.Applicative import Data.Maybe x = [1, 2, 3] y = [4, 5, 6] z = [7, 8, 9] findVal :: (Eq a) => a -> (a, b) -> Maybe b -> Maybe b findVal k ab b = if (k == fst ab) then Just (snd ab) else b lookup' :: Eq a => a -> [(a, b)] -> Maybe b lookup' k = foldr (findVal k) Nothing xs :: Maybe Integer xs = lookup' 3 (zip x y) ys :: Maybe Integer ys = lookup' 6 $ zip y z zs :: Maybe Integer zs = lookup' 4 $ zip x y z' :: Integer -> Maybe Integer z' n = lookup' n $ zip x y x1 :: Maybe (Integer, Integer) x1 = liftA2 (,) xs ys x2 :: Maybe (Integer, Integer) x2 = liftA2 (,) ys zs x3 :: Integer -> (Maybe Integer, Maybe Integer) x3 n = (,) (z' n) (z' n) uncurry' :: (a -> b -> c) -> (a, b) -> c uncurry' f ab = f (fst ab) (snd ab) summed :: Num c => (c, c) -> c summed = uncurry' (+) bolt :: Integer -> Bool bolt = liftA2 (&&) (> 3) (< 8) fromMaybe' :: a -> Maybe a -> a fromMaybe' a ma = foldr (\a1 _ -> a1) a ma sequA :: Integer -> [Bool] sequA = sequenceA [(>3), (<8), even] main :: IO () main = do print $ sequenceA [Just 3, Just 2, Just 1] print $ sequenceA [x, y] print $ summed <$> ((,) <$> xs <*> ys) print $ fmap summed ((,) <$> xs <*> zs) print $ bolt 7 print $ fmap bolt z print $ sequenceA [(>3), (<8), even] 7 print $ foldr (&&) True $ sequA 7 print $ sequA . fromMaybe' 0 $ ys print $ bolt . fromMaybe' 0 $ ys
null
https://raw.githubusercontent.com/ArulselvanMadhavan/haskell-first-principles/06e0c71c502848c8e75c8109dd49c0954d815bba/chapter22/src/ReaderPractice.hs
haskell
module ReaderPractice where import Control.Applicative import Data.Maybe x = [1, 2, 3] y = [4, 5, 6] z = [7, 8, 9] findVal :: (Eq a) => a -> (a, b) -> Maybe b -> Maybe b findVal k ab b = if (k == fst ab) then Just (snd ab) else b lookup' :: Eq a => a -> [(a, b)] -> Maybe b lookup' k = foldr (findVal k) Nothing xs :: Maybe Integer xs = lookup' 3 (zip x y) ys :: Maybe Integer ys = lookup' 6 $ zip y z zs :: Maybe Integer zs = lookup' 4 $ zip x y z' :: Integer -> Maybe Integer z' n = lookup' n $ zip x y x1 :: Maybe (Integer, Integer) x1 = liftA2 (,) xs ys x2 :: Maybe (Integer, Integer) x2 = liftA2 (,) ys zs x3 :: Integer -> (Maybe Integer, Maybe Integer) x3 n = (,) (z' n) (z' n) uncurry' :: (a -> b -> c) -> (a, b) -> c uncurry' f ab = f (fst ab) (snd ab) summed :: Num c => (c, c) -> c summed = uncurry' (+) bolt :: Integer -> Bool bolt = liftA2 (&&) (> 3) (< 8) fromMaybe' :: a -> Maybe a -> a fromMaybe' a ma = foldr (\a1 _ -> a1) a ma sequA :: Integer -> [Bool] sequA = sequenceA [(>3), (<8), even] main :: IO () main = do print $ sequenceA [Just 3, Just 2, Just 1] print $ sequenceA [x, y] print $ summed <$> ((,) <$> xs <*> ys) print $ fmap summed ((,) <$> xs <*> zs) print $ bolt 7 print $ fmap bolt z print $ sequenceA [(>3), (<8), even] 7 print $ foldr (&&) True $ sequA 7 print $ sequA . fromMaybe' 0 $ ys print $ bolt . fromMaybe' 0 $ ys
9142c897b00b5a80537f047da2b8333a527f08a22f745c3d48954b9acc420454
tweag/lagoon
Security.hs
Copyright 2020 Pfizer Inc. 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. # LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE OverloadedStrings #-} module Lagoon.Interface.Security ( -- * Passwords PlaintextPassword(..) -- * Groups , GroupIx(..) , GroupName -- * Authentication tokens , AuthToken(..) -- * Permissions , DatasetAccessLevel(..) ) where import Control.Monad import Data.Aeson hiding (Value(..)) import Data.String import GHC.Generics (Generic) import Text.Show.Pretty import qualified Data.ByteString as BS.S import qualified Data.ByteString.Char8 as BS.S.C8 import Lagoon.Interface.DB import Lagoon.Interface.Pretty {------------------------------------------------------------------------------- Passwords -------------------------------------------------------------------------------} -- | Plaintext password (only used as part of user input) newtype PlaintextPassword = PlaintextPassword String deriving (Show, Eq, Ord, IsString, PrettyVal) ------------------------------------------------------------------------------ Groups ------------------------------------------------------------------------------ Groups -------------------------------------------------------------------------------} newtype GroupIx = GroupIx Ix deriving (Show, Pretty) type GroupName = String {------------------------------------------------------------------------------- Authentication tokens -------------------------------------------------------------------------------} -- | Authentication token -- -- A login token can be requested once the user has identified themselves -- using their username and password. The token can then be stored in a -- file and used on subsequent requests to resume the session. -- -- Tokens are UUID strings so we don't need to worry about unicode encoding. -- -- This intentionally does not derive 'FromHttpApiData' or 'ToHttpApiData'; -- these tokens should not appear in URLs. newtype AuthToken = AuthToken BS.S.ByteString deriving (Show, Pretty) instance FromJSON AuthToken where parseJSON = liftM (AuthToken . BS.S.C8.pack) . parseJSON instance ToJSON AuthToken where toJSON (AuthToken bs) = toJSON (BS.S.C8.unpack bs) instance PrettyVal AuthToken where prettyVal (AuthToken bs) = Con "AuthToken" [String (BS.S.C8.unpack bs)] {------------------------------------------------------------------------------- Permissions -------------------------------------------------------------------------------} -- | Dataset access level -- The order of the constructors is important , as it determines the ' ' -- instance; 'maximum' should have the intended meaning (maximum access). data DatasetAccessLevel = DatasetAccessLevelNone | DatasetAccessLevelRead | DatasetAccessLevelUpdate | DatasetAccessLevelManage deriving (Show, Read, Eq, Ord, Generic) instance PrettyVal DatasetAccessLevel instance Pretty DatasetAccessLevel where pretty DatasetAccessLevelNone = "no access" pretty DatasetAccessLevelRead = "READ" pretty DatasetAccessLevelUpdate = "UPDATE" pretty DatasetAccessLevelManage = "MANAGE" {------------------------------------------------------------------------------- Serialization -------------------------------------------------------------------------------} instance ToJSON DatasetAccessLevel where toJSON DatasetAccessLevelNone = "none" toJSON DatasetAccessLevelRead = "read" toJSON DatasetAccessLevelUpdate = "update" toJSON DatasetAccessLevelManage = "manage" instance FromJSON DatasetAccessLevel where parseJSON = withText "DatasetAccessLevel" $ \str -> case str of "none" -> return DatasetAccessLevelNone "read" -> return DatasetAccessLevelRead "update" -> return DatasetAccessLevelUpdate "manage" -> return DatasetAccessLevelManage _otherwise -> fail "Could not parse DatasetAccessLevel"
null
https://raw.githubusercontent.com/tweag/lagoon/2ef0440db810f4f45dbed160b369daf41d92bfa4/src/interface/src/Lagoon/Interface/Security.hs
haskell
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 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. # LANGUAGE OverloadedStrings # * Passwords * Groups * Authentication tokens * Permissions ------------------------------------------------------------------------------ Passwords ------------------------------------------------------------------------------ | Plaintext password (only used as part of user input) ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------} ------------------------------------------------------------------------------ Authentication tokens ------------------------------------------------------------------------------ | Authentication token A login token can be requested once the user has identified themselves using their username and password. The token can then be stored in a file and used on subsequent requests to resume the session. Tokens are UUID strings so we don't need to worry about unicode encoding. This intentionally does not derive 'FromHttpApiData' or 'ToHttpApiData'; these tokens should not appear in URLs. ------------------------------------------------------------------------------ Permissions ------------------------------------------------------------------------------ | Dataset access level instance; 'maximum' should have the intended meaning (maximum access). ------------------------------------------------------------------------------ Serialization ------------------------------------------------------------------------------
Copyright 2020 Pfizer Inc. Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , # LANGUAGE GeneralizedNewtypeDeriving # module Lagoon.Interface.Security ( PlaintextPassword(..) , GroupIx(..) , GroupName , AuthToken(..) , DatasetAccessLevel(..) ) where import Control.Monad import Data.Aeson hiding (Value(..)) import Data.String import GHC.Generics (Generic) import Text.Show.Pretty import qualified Data.ByteString as BS.S import qualified Data.ByteString.Char8 as BS.S.C8 import Lagoon.Interface.DB import Lagoon.Interface.Pretty newtype PlaintextPassword = PlaintextPassword String deriving (Show, Eq, Ord, IsString, PrettyVal) Groups Groups newtype GroupIx = GroupIx Ix deriving (Show, Pretty) type GroupName = String newtype AuthToken = AuthToken BS.S.ByteString deriving (Show, Pretty) instance FromJSON AuthToken where parseJSON = liftM (AuthToken . BS.S.C8.pack) . parseJSON instance ToJSON AuthToken where toJSON (AuthToken bs) = toJSON (BS.S.C8.unpack bs) instance PrettyVal AuthToken where prettyVal (AuthToken bs) = Con "AuthToken" [String (BS.S.C8.unpack bs)] The order of the constructors is important , as it determines the ' ' data DatasetAccessLevel = DatasetAccessLevelNone | DatasetAccessLevelRead | DatasetAccessLevelUpdate | DatasetAccessLevelManage deriving (Show, Read, Eq, Ord, Generic) instance PrettyVal DatasetAccessLevel instance Pretty DatasetAccessLevel where pretty DatasetAccessLevelNone = "no access" pretty DatasetAccessLevelRead = "READ" pretty DatasetAccessLevelUpdate = "UPDATE" pretty DatasetAccessLevelManage = "MANAGE" instance ToJSON DatasetAccessLevel where toJSON DatasetAccessLevelNone = "none" toJSON DatasetAccessLevelRead = "read" toJSON DatasetAccessLevelUpdate = "update" toJSON DatasetAccessLevelManage = "manage" instance FromJSON DatasetAccessLevel where parseJSON = withText "DatasetAccessLevel" $ \str -> case str of "none" -> return DatasetAccessLevelNone "read" -> return DatasetAccessLevelRead "update" -> return DatasetAccessLevelUpdate "manage" -> return DatasetAccessLevelManage _otherwise -> fail "Could not parse DatasetAccessLevel"
a41f9eec788dfb3120c1e67121a0cd76a0086af128962b36455968ea1e29566c
korya/efuns
instruct.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) $ I d : instruct.mli , v 1.1 2001/02/26 13:04:11 lefessan Exp $ (* The type of the instructions of the abstract machine *) open Lambda (* Structure of compilation environments *) type compilation_env = { ce_stack: int Ident.tbl; (* Positions of variables in the stack *) ce_heap: int Ident.tbl; (* Structure of the heap-allocated env *) ce_rec: int Ident.tbl } (* Functions bound by the same let rec *) The ce_stack component gives locations of variables residing in the stack . The locations are offsets w.r.t . the origin of the stack frame . The ce_heap component gives the positions of variables residing in the heap - allocated environment . The ce_rec component associate offsets to identifiers for functions bound by the same let rec as the current function . The offsets are used by the OFFSETCLOSURE instruction to recover the closure pointer of the desired function from the env register ( which points to the closure for the current function ) . in the stack. The locations are offsets w.r.t. the origin of the stack frame. The ce_heap component gives the positions of variables residing in the heap-allocated environment. The ce_rec component associate offsets to identifiers for functions bound by the same let rec as the current function. The offsets are used by the OFFSETCLOSURE instruction to recover the closure pointer of the desired function from the env register (which points to the closure for the current function). *) (* Debugging events *) type debug_event = { mutable ev_pos: int; (* Position in bytecode *) ev_module: string; (* Name of defining module *) ev_char: int; (* Location in source file *) ev_kind: debug_event_kind; (* Before/after event *) ev_info: debug_event_info; (* Extra information *) ev_typenv: Env.summary; (* Typing environment *) ev_compenv: compilation_env; (* Compilation environment *) ev_stacksize: int; (* Size of stack frame *) ev_repr: debug_event_repr } (* Position of the representative *) and debug_event_kind = Event_before | Event_after of Types.type_expr | Event_pseudo and debug_event_info = Event_function | Event_return of int | Event_other and debug_event_repr = Event_none | Event_parent of int ref | Event_child of int ref (* Abstract machine instructions *) type label = int (* Symbolic code labels *) type instruction = Klabel of label | Kacc of int | Kenvacc of int | Kpush | Kpop of int | Kassign of int | Kpush_retaddr of label | Kapply of int (* number of arguments *) | Kappterm of int * int (* number of arguments, slot size *) | Kreturn of int (* slot size *) | Krestart | Kgrab of int (* number of arguments *) | Kclosure of label * int | Kclosurerec of label list * int | Koffsetclosure of int | Kgetglobal of Ident.t | Ksetglobal of Ident.t | Kconst of structured_constant | Kmakeblock of int * int (* size, tag *) | Kmakefloatblock of int | Kgetfield of int | Ksetfield of int | Kgetfloatfield of int | Ksetfloatfield of int | Kvectlength | Kgetvectitem | Ksetvectitem | Kgetstringchar | Ksetstringchar | Kbranch of label | Kbranchif of label | Kbranchifnot of label | Kstrictbranchif of label | Kstrictbranchifnot of label | Kswitch of label array * label array | Kboolnot | Kpushtrap of label | Kpoptrap | Kraise | Kreraise | Kcheck_signals | Kccall of string * int | Knegint | Kaddint | Ksubint | Kmulint | Kdivint | Kmodint | Kandint | Korint | Kxorint | Klslint | Klsrint | Kasrint | Kintcomp of comparison | Koffsetint of int | Koffsetref of int | Kisint | Kisout | Kgetmethod | Kevent of debug_event | Kstop val immed_min: int val immed_max: int
null
https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/ocamlsrc/compat/3.00%2B22/include/instruct.mli
ocaml
********************************************************************* Objective Caml ********************************************************************* The type of the instructions of the abstract machine Structure of compilation environments Positions of variables in the stack Structure of the heap-allocated env Functions bound by the same let rec Debugging events Position in bytecode Name of defining module Location in source file Before/after event Extra information Typing environment Compilation environment Size of stack frame Position of the representative Abstract machine instructions Symbolic code labels number of arguments number of arguments, slot size slot size number of arguments size, tag
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . $ I d : instruct.mli , v 1.1 2001/02/26 13:04:11 lefessan Exp $ open Lambda type compilation_env = The ce_stack component gives locations of variables residing in the stack . The locations are offsets w.r.t . the origin of the stack frame . The ce_heap component gives the positions of variables residing in the heap - allocated environment . The ce_rec component associate offsets to identifiers for functions bound by the same let rec as the current function . The offsets are used by the OFFSETCLOSURE instruction to recover the closure pointer of the desired function from the env register ( which points to the closure for the current function ) . in the stack. The locations are offsets w.r.t. the origin of the stack frame. The ce_heap component gives the positions of variables residing in the heap-allocated environment. The ce_rec component associate offsets to identifiers for functions bound by the same let rec as the current function. The offsets are used by the OFFSETCLOSURE instruction to recover the closure pointer of the desired function from the env register (which points to the closure for the current function). *) type debug_event = and debug_event_kind = Event_before | Event_after of Types.type_expr | Event_pseudo and debug_event_info = Event_function | Event_return of int | Event_other and debug_event_repr = Event_none | Event_parent of int ref | Event_child of int ref type instruction = Klabel of label | Kacc of int | Kenvacc of int | Kpush | Kpop of int | Kassign of int | Kpush_retaddr of label | Krestart | Kclosure of label * int | Kclosurerec of label list * int | Koffsetclosure of int | Kgetglobal of Ident.t | Ksetglobal of Ident.t | Kconst of structured_constant | Kmakefloatblock of int | Kgetfield of int | Ksetfield of int | Kgetfloatfield of int | Ksetfloatfield of int | Kvectlength | Kgetvectitem | Ksetvectitem | Kgetstringchar | Ksetstringchar | Kbranch of label | Kbranchif of label | Kbranchifnot of label | Kstrictbranchif of label | Kstrictbranchifnot of label | Kswitch of label array * label array | Kboolnot | Kpushtrap of label | Kpoptrap | Kraise | Kreraise | Kcheck_signals | Kccall of string * int | Knegint | Kaddint | Ksubint | Kmulint | Kdivint | Kmodint | Kandint | Korint | Kxorint | Klslint | Klsrint | Kasrint | Kintcomp of comparison | Koffsetint of int | Koffsetref of int | Kisint | Kisout | Kgetmethod | Kevent of debug_event | Kstop val immed_min: int val immed_max: int
26fba60aec0359efd600b89292e21b1bf5268c1d3a03f5d011f741a0098f8656
7c6f434c/lang-os
safe-read.lisp
(defpackage :lisp-os-helpers/safe-read (:use :common-lisp :lisp-os-helpers/util) (:export #:safe-read #:check-safety #:stringify-atoms)) (in-package :lisp-os-helpers/safe-read) (define-condition unacceptable-symbol (simple-error) ((symbol :initarg :symbol :reader unacceptable-symbol-content) (package :initarg :package :reader unacceptable-symbol-desired-package)) (:report (lambda (condition stream) (if (unacceptable-symbol-desired-package condition) (format stream "Symbol ~s is not in the expected package ~a." (unacceptable-symbol-content condition) (unacceptable-symbol-desired-package condition)) (format stream "Symbol ~s when no symbols allowed." (unacceptable-symbol-content condition)))))) (defun check-safety (form packages) (let* ((packages (mapcar 'find-package packages))) (cond ((consp form) (check-safety (car form) packages) (check-safety (cdr form) packages)) ((null form)) ((symbolp form) (unless (loop for p in packages when (eq (find-symbol (string form) p) form) return t) (format t "~s~%" (list form packages (null form))) (error (make-condition 'unacceptable-symbol :symbol form :package (first packages))))) (t )) form)) (defun safe-read (source packages &key forbid-nil) (if (stringp source) (with-input-from-string (s source) (safe-read s packages)) (let* ((*read-eval* nil) (packages (remove nil (mapcar 'find-package packages))) (*package* (if packages (first packages) (make-package (format nil "~36r" (random-number (expt 36 40)))))) (form (progn (unless (or packages forbid-nil) (import (list nil) *package*)) (check-safety (read source) packages)))) (unless packages (delete-package *package*)) form))) (defun stringify-atoms (form) (cond ((consp form) (cons (stringify-atoms (car form)) (stringify-atoms (cdr form)))) ((null form) nil) ((stringp form) form) (t (format nil "~a" form))))
null
https://raw.githubusercontent.com/7c6f434c/lang-os/be4331d225629bff322facf603a89ac707acea83/lisp-os-helpers/safe-read.lisp
lisp
(defpackage :lisp-os-helpers/safe-read (:use :common-lisp :lisp-os-helpers/util) (:export #:safe-read #:check-safety #:stringify-atoms)) (in-package :lisp-os-helpers/safe-read) (define-condition unacceptable-symbol (simple-error) ((symbol :initarg :symbol :reader unacceptable-symbol-content) (package :initarg :package :reader unacceptable-symbol-desired-package)) (:report (lambda (condition stream) (if (unacceptable-symbol-desired-package condition) (format stream "Symbol ~s is not in the expected package ~a." (unacceptable-symbol-content condition) (unacceptable-symbol-desired-package condition)) (format stream "Symbol ~s when no symbols allowed." (unacceptable-symbol-content condition)))))) (defun check-safety (form packages) (let* ((packages (mapcar 'find-package packages))) (cond ((consp form) (check-safety (car form) packages) (check-safety (cdr form) packages)) ((null form)) ((symbolp form) (unless (loop for p in packages when (eq (find-symbol (string form) p) form) return t) (format t "~s~%" (list form packages (null form))) (error (make-condition 'unacceptable-symbol :symbol form :package (first packages))))) (t )) form)) (defun safe-read (source packages &key forbid-nil) (if (stringp source) (with-input-from-string (s source) (safe-read s packages)) (let* ((*read-eval* nil) (packages (remove nil (mapcar 'find-package packages))) (*package* (if packages (first packages) (make-package (format nil "~36r" (random-number (expt 36 40)))))) (form (progn (unless (or packages forbid-nil) (import (list nil) *package*)) (check-safety (read source) packages)))) (unless packages (delete-package *package*)) form))) (defun stringify-atoms (form) (cond ((consp form) (cons (stringify-atoms (car form)) (stringify-atoms (cdr form)))) ((null form) nil) ((stringp form) form) (t (format nil "~a" form))))
390999ea1ca7aecdac9fbece00b47cebedddb13e9630b6d807aecb39b697511e
codelion/SpinR
expression.ml
_ $ I d : expression.ml 4527 2012 - 10 - 17 13:08:20Z weissmam $ Copyright ( c ) 2010 - 2012 Technische Universitaet Muenchen , TUM Copyright ( c ) 2010 - 2012 < > All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : 1 . Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . 2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . 3 . Neither the name of TUM nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . Copyright (c) 2010 - 2012 Technische Universitaet Muenchen, TUM Copyright (c) 2010 - 2012 Markus W. Weissmann <> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of TUM nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) type binary_operator = | Mul | Div | Mod | Add | Sub | Lshift | Rshift | Lt | Gt | Le | Ge | Eq | Neq | Band | Bxor | Bor | And | Or type unary_operator = | Neg | Not | Dash type t = | Binop of binary_operator * t * t | Unop of unary_operator * t | Variable of Identifier.t | ConstInt of int | Array of Identifier.t * t let compare = Pervasives.compare let replace_variables f expr = let rec m = function | Unop (op, v) -> Unop (op, m v) | Binop (op, v1, v2) -> Binop (op, m v1, m v2) | Variable id -> f id None | ConstInt i -> ConstInt i | Array (id, v) -> f id (Some v) in m expr let rename_variables f expr = let rec rename = function | Unop (op, v) -> Unop (op, rename v) | Binop (op, v1, v2) -> Binop (op, rename v1, rename v2) | Variable id -> Variable (f id) | ConstInt i -> ConstInt i | Array (id, v) -> Array (f id, rename v) in rename expr let rec string_of t = let string_of_binary_operator = function | Add -> "+" | Sub -> "-" | Mul -> "*" | Div -> "/" | Mod -> "%" | Band -> "&" | Bxor -> "^" | Bor -> "|" | Gt -> ">" | Lt -> "<" | Ge -> ">=" | Le -> "<=" | Eq -> "==" | Neq -> "!=" | Lshift -> "<<" | Rshift -> ">>" | And -> "&&" | Or -> "||" in let string_of_unary_operator = function | Dash -> "~" | Neg -> "-" | Not -> "!" in let ret = match t with | Binop (op, a, b) -> Printf.sprintf "(%s %s %s)" (string_of a) (string_of_binary_operator op) (string_of b) | Unop (op, x) -> Printf.sprintf "(%s %s)" (string_of_unary_operator op) (string_of x) | Variable id -> Identifier.string_of id | ConstInt v -> string_of_int v | Array (id, off) -> Printf.sprintf "%s[%s]" (Identifier.string_of id) (string_of off) in ret let rec identifiers_of = function | Binop (_, a, b) -> Identifierset.union (identifiers_of a) (identifiers_of b) | Unop (_, x) -> identifiers_of x | Variable id -> Identifierset.singleton id | ConstInt _ -> Identifierset.empty | Array (id, _) -> Identifierset.add id Identifierset.empty (* simplify expression by computing recursive fixpoint of rewriting rules *) let rec eval expr = let int_of_bool = function | true -> ConstInt 1 | false -> ConstInt 0 in let rec try_eval expr = match expr with | Binop (Eq, x, y) when x = y -> ConstInt 1 | Binop (Neq, x, y) when x = y -> ConstInt 0 | Unop (Not, Unop (Not, x)) -> x | Unop (Not, ConstInt 1) -> ConstInt 0 | Unop (Not, ConstInt 0) -> ConstInt 1 | Binop (Add, ConstInt x, ConstInt y) -> ConstInt (x + y) | Binop (Sub, ConstInt x, ConstInt y) -> ConstInt (x - y) | Binop (Mul, ConstInt x, ConstInt y) -> ConstInt (x * y) | Binop (Div, ConstInt x, ConstInt y) -> ConstInt (x / y) | Binop (Mod, ConstInt x, ConstInt y) -> ConstInt (x mod y) | Binop (Eq, ConstInt x, ConstInt y) -> int_of_bool (x = y) | Binop (Neq, ConstInt x, ConstInt y) -> int_of_bool (x <> y) | Binop (Lt, ConstInt x, ConstInt y) -> int_of_bool (x < y) | Binop (Le, ConstInt x, ConstInt y) -> int_of_bool (x <= y) | Binop (Gt, ConstInt x, ConstInt y) -> int_of_bool (x > y) | Binop (Ge, ConstInt x, ConstInt y) -> int_of_bool (x >= y) | Binop (op, a, b) -> Binop (op, try_eval a, try_eval b) | Unop (op, a) -> Unop (op, try_eval a) | _ -> expr in let expr' = try_eval expr in if expr' = expr then expr else eval expr' $ Q eval ( Q.pair Q.int Q.int ) ( fun ( x , y ) - > eval ( ( Add , ( Add , , ) , ) ) = ( x + y + x ) ) ( Q.pair Q.int Q.int ) ( fun ( x , y ) - > eval ( ( Add , , ) ) = ( x + y ) ) ( Q.pair Q.int Q.int ) ( fun ( x , y ) - > eval ( ( Sub , , ) ) = ( x - y ) ) ( Q.pair Q.int Q.int ) ( fun ( x , y ) - > eval ( ( Mul , , ) ) = ( x * y ) ) Q.int ( fun x - > eval ( ( Eq , , ) ) = ) ( Q.pair Q.int Q.int ) ( fun ( x , y ) - > eval ( ( Eq , , ) ) = ( if x = y then 1 else 0 ) ) (Q.pair Q.int Q.int) (fun (x, y) -> eval (Binop (Add, Binop (Add, ConstInt x, ConstInt y), ConstInt x)) = ConstInt (x + y + x)) (Q.pair Q.int Q.int) (fun (x, y) -> eval (Binop (Add, ConstInt x, ConstInt y)) = ConstInt (x + y)) (Q.pair Q.int Q.int) (fun (x, y) -> eval (Binop (Sub, ConstInt x, ConstInt y)) = ConstInt (x - y)) (Q.pair Q.int Q.int) (fun (x, y) -> eval (Binop (Mul, ConstInt x, ConstInt y)) = ConstInt (x * y)) Q.int (fun x -> eval (Binop (Eq, ConstInt x, ConstInt x)) = ConstInt 1) (Q.pair Q.int Q.int) (fun (x, y) -> eval (Binop (Eq, ConstInt x, ConstInt y)) = ConstInt (if x = y then 1 else 0)) *) $ T eval eval ( Unop ( Not , Unop ( Not , Unop ( Not , 0 ) ) ) ) = eval (Unop (Not, Unop (Not, Unop (Not, ConstInt 0)))) = ConstInt 1 *)
null
https://raw.githubusercontent.com/codelion/SpinR/8d3a3d99cf3192a4ede3f326eff0c07c22906dee/expression.ml
ocaml
simplify expression by computing recursive fixpoint of rewriting rules
_ $ I d : expression.ml 4527 2012 - 10 - 17 13:08:20Z weissmam $ Copyright ( c ) 2010 - 2012 Technische Universitaet Muenchen , TUM Copyright ( c ) 2010 - 2012 < > All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : 1 . Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . 2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . 3 . Neither the name of TUM nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . Copyright (c) 2010 - 2012 Technische Universitaet Muenchen, TUM Copyright (c) 2010 - 2012 Markus W. Weissmann <> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of TUM nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) type binary_operator = | Mul | Div | Mod | Add | Sub | Lshift | Rshift | Lt | Gt | Le | Ge | Eq | Neq | Band | Bxor | Bor | And | Or type unary_operator = | Neg | Not | Dash type t = | Binop of binary_operator * t * t | Unop of unary_operator * t | Variable of Identifier.t | ConstInt of int | Array of Identifier.t * t let compare = Pervasives.compare let replace_variables f expr = let rec m = function | Unop (op, v) -> Unop (op, m v) | Binop (op, v1, v2) -> Binop (op, m v1, m v2) | Variable id -> f id None | ConstInt i -> ConstInt i | Array (id, v) -> f id (Some v) in m expr let rename_variables f expr = let rec rename = function | Unop (op, v) -> Unop (op, rename v) | Binop (op, v1, v2) -> Binop (op, rename v1, rename v2) | Variable id -> Variable (f id) | ConstInt i -> ConstInt i | Array (id, v) -> Array (f id, rename v) in rename expr let rec string_of t = let string_of_binary_operator = function | Add -> "+" | Sub -> "-" | Mul -> "*" | Div -> "/" | Mod -> "%" | Band -> "&" | Bxor -> "^" | Bor -> "|" | Gt -> ">" | Lt -> "<" | Ge -> ">=" | Le -> "<=" | Eq -> "==" | Neq -> "!=" | Lshift -> "<<" | Rshift -> ">>" | And -> "&&" | Or -> "||" in let string_of_unary_operator = function | Dash -> "~" | Neg -> "-" | Not -> "!" in let ret = match t with | Binop (op, a, b) -> Printf.sprintf "(%s %s %s)" (string_of a) (string_of_binary_operator op) (string_of b) | Unop (op, x) -> Printf.sprintf "(%s %s)" (string_of_unary_operator op) (string_of x) | Variable id -> Identifier.string_of id | ConstInt v -> string_of_int v | Array (id, off) -> Printf.sprintf "%s[%s]" (Identifier.string_of id) (string_of off) in ret let rec identifiers_of = function | Binop (_, a, b) -> Identifierset.union (identifiers_of a) (identifiers_of b) | Unop (_, x) -> identifiers_of x | Variable id -> Identifierset.singleton id | ConstInt _ -> Identifierset.empty | Array (id, _) -> Identifierset.add id Identifierset.empty let rec eval expr = let int_of_bool = function | true -> ConstInt 1 | false -> ConstInt 0 in let rec try_eval expr = match expr with | Binop (Eq, x, y) when x = y -> ConstInt 1 | Binop (Neq, x, y) when x = y -> ConstInt 0 | Unop (Not, Unop (Not, x)) -> x | Unop (Not, ConstInt 1) -> ConstInt 0 | Unop (Not, ConstInt 0) -> ConstInt 1 | Binop (Add, ConstInt x, ConstInt y) -> ConstInt (x + y) | Binop (Sub, ConstInt x, ConstInt y) -> ConstInt (x - y) | Binop (Mul, ConstInt x, ConstInt y) -> ConstInt (x * y) | Binop (Div, ConstInt x, ConstInt y) -> ConstInt (x / y) | Binop (Mod, ConstInt x, ConstInt y) -> ConstInt (x mod y) | Binop (Eq, ConstInt x, ConstInt y) -> int_of_bool (x = y) | Binop (Neq, ConstInt x, ConstInt y) -> int_of_bool (x <> y) | Binop (Lt, ConstInt x, ConstInt y) -> int_of_bool (x < y) | Binop (Le, ConstInt x, ConstInt y) -> int_of_bool (x <= y) | Binop (Gt, ConstInt x, ConstInt y) -> int_of_bool (x > y) | Binop (Ge, ConstInt x, ConstInt y) -> int_of_bool (x >= y) | Binop (op, a, b) -> Binop (op, try_eval a, try_eval b) | Unop (op, a) -> Unop (op, try_eval a) | _ -> expr in let expr' = try_eval expr in if expr' = expr then expr else eval expr' $ Q eval ( Q.pair Q.int Q.int ) ( fun ( x , y ) - > eval ( ( Add , ( Add , , ) , ) ) = ( x + y + x ) ) ( Q.pair Q.int Q.int ) ( fun ( x , y ) - > eval ( ( Add , , ) ) = ( x + y ) ) ( Q.pair Q.int Q.int ) ( fun ( x , y ) - > eval ( ( Sub , , ) ) = ( x - y ) ) ( Q.pair Q.int Q.int ) ( fun ( x , y ) - > eval ( ( Mul , , ) ) = ( x * y ) ) Q.int ( fun x - > eval ( ( Eq , , ) ) = ) ( Q.pair Q.int Q.int ) ( fun ( x , y ) - > eval ( ( Eq , , ) ) = ( if x = y then 1 else 0 ) ) (Q.pair Q.int Q.int) (fun (x, y) -> eval (Binop (Add, Binop (Add, ConstInt x, ConstInt y), ConstInt x)) = ConstInt (x + y + x)) (Q.pair Q.int Q.int) (fun (x, y) -> eval (Binop (Add, ConstInt x, ConstInt y)) = ConstInt (x + y)) (Q.pair Q.int Q.int) (fun (x, y) -> eval (Binop (Sub, ConstInt x, ConstInt y)) = ConstInt (x - y)) (Q.pair Q.int Q.int) (fun (x, y) -> eval (Binop (Mul, ConstInt x, ConstInt y)) = ConstInt (x * y)) Q.int (fun x -> eval (Binop (Eq, ConstInt x, ConstInt x)) = ConstInt 1) (Q.pair Q.int Q.int) (fun (x, y) -> eval (Binop (Eq, ConstInt x, ConstInt y)) = ConstInt (if x = y then 1 else 0)) *) $ T eval eval ( Unop ( Not , Unop ( Not , Unop ( Not , 0 ) ) ) ) = eval (Unop (Not, Unop (Not, Unop (Not, ConstInt 0)))) = ConstInt 1 *)
154c1e5351eda8fa0f6c3f3c019890bff53077df7f5dba6c2833343099749c12
xvw/planet
applicative.mli
(** This module describes a structure intermediate between a functor and a monad. This implementation is widely inspired by the {{: /} Haskell}'s implementation *) * Build a new Applicative Functor 's module using [ REQUIREMENT ] . module Make (F : Sigs.Applicative.REQUIREMENT) : Sigs.Applicative.API with type 'a t = 'a F.t * Build a new Applicative Functor 's module using a [ Monad ] . module Make_from_monad (M : Sigs.Monad.REQUIREMENT_BIND) : Sigs.Applicative.API with type 'a t = 'a M.t
null
https://raw.githubusercontent.com/xvw/planet/c2a77ea66f61cc76df78b9c2ad06d114795f3053/src/bedrock/applicative.mli
ocaml
* This module describes a structure intermediate between a functor and a monad. This implementation is widely inspired by the {{: /} Haskell}'s implementation
* Build a new Applicative Functor 's module using [ REQUIREMENT ] . module Make (F : Sigs.Applicative.REQUIREMENT) : Sigs.Applicative.API with type 'a t = 'a F.t * Build a new Applicative Functor 's module using a [ Monad ] . module Make_from_monad (M : Sigs.Monad.REQUIREMENT_BIND) : Sigs.Applicative.API with type 'a t = 'a M.t
eb93f83373a85323a0e20e732a475da459a73fddff23c8a65d2cfcc5f274a706
bvaugon/ocapic
lcd.mli
(*************************************************************************) (* *) (* OCaPIC *) (* *) (* *) This file is distributed under the terms of the CeCILL license . (* See file ../../LICENSE-en. *) (* *) (*************************************************************************) (** Character type LCD display communication interface. *) * Possible sizes of data connection between the PIC and the LCD display type bus_size = Four | Eight (** Direction of cursor or display shift. *) type direction = Left | Right (** Writing mode: cursor or display moving and direction setting. *) type mode = Cursor_left | Cursor_right | Display_left | Display_right (** State of the LCD display. *) type state = On | Off (** Cursor mode. *) type cursor = Invisible | Underscore | Block (** Line mode. *) type lmode = One | Two (** Characters font. *) type font = F5x8 | F5x10 * about connection between the PIC and the LCD display . module type S = sig val bus_size : bus_size (** Size of the bus. *) val e : Pic.bit (** Pin of the pic connected to the [e] entry of the LCD display. *) val rs : Pic.bit (** Pin of the pic connected to the [rs] entry of the LCD display. *) val rw : Pic.bit (** Pin of the pic connected to the [rw] entry of the LCD display. *) val bus : Pic.reg * Port of the pic connected to the bus of the LCD display . In case of 4 bit bus , the 4th highest bits of the port are used . In case of 4 bit bus, the 4th highest bits of the port are used. *) end (** Connects the PIC to the LCD display. Takes informations about connection in the module C. *) module Connect : functor (C : S) -> sig val clear : unit -> unit (** Clear the LCD display. *) val home : unit -> unit (** Return cursor and display to their initial positions. *) (***) val init : unit -> unit (** Initialise the LCD display. Should be called once on the LCD power on. *) val config : ?mode:mode -> ?disp:state -> ?cursor:cursor -> ?lmode:lmode -> ?font:font -> unit -> unit (** Configure the LCD display. Should be called after the LCD initialisation. *) (***) val current_position : unit -> int * int (** Get the current position of the cursor as (line, column). *) val moveto : int -> int -> unit (** moveto line column moves the cursor at (line, column). *) val shift_cursor : direction -> unit * Shift cursor of 1 character . val shift_display : direction -> unit * Shift display of 1 character . (***) val register_bitmap : char -> int -> int -> int -> unit (** Register a new character bitmap. *) (***) val print_char : char -> unit (** Write the character on the LCD display. *) val print_string : string -> unit (** Write the string on the LCD display at the current cursor position. *) val print_int : int -> unit * Write one integer on the LCD display , in decimal . val output : out_channel (** Display view as output channel. Can be used as argument of Printf.fprintf. *) end type display = { (** Clears the LCD display. *) clear : unit -> unit; (** Returns cursor and display to their initial positions. *) home : unit -> unit; (***) (** Initialises the LCD display. Should be called once on the LCD power on. *) init : unit -> unit; (** Configures the LCD display. Should be called after the LCD initialisation. *) config : ?mode:mode -> ?disp:state -> ?cursor:cursor -> ?lmode:lmode -> ?font:font -> unit -> unit; (***) (** Get the current position of the cursor as (line, column). *) current_position : unit -> int * int; (** moveto line column moves the cursor at (line, column). *) moveto : int -> int -> unit; * Shifts cursor of 1 character . shift_cursor : direction -> unit; * Shifts display of 1 character . shift_display : direction -> unit; (***) (** Register a new character bitmap. *) register_bitmap : char -> int -> int -> int -> unit; (***) (** Write the character on the LCD display. *) print_char : char -> unit; (** Write the string on the LCD display at the current cursor position. *) print_string : string -> unit; * Write one integer on the LCD display , in decimal . print_int : int -> unit; (** Display view as output channel. Can be used as argument of Printf.fprintf. *) output : out_channel; } val connect : bus_size:bus_size -> e:Pic.bit -> rs:Pic.bit -> rw:Pic.bit -> bus:Pic.reg -> display (** Create a connection to an Lcd display. Offers the same features as Connect but in another style. *)
null
https://raw.githubusercontent.com/bvaugon/ocapic/a14cd9ec3f5022aeb5fe2264d595d7e8f1ddf58a/lib/spiclibs/lcd.mli
ocaml
*********************************************************************** OCaPIC See file ../../LICENSE-en. *********************************************************************** * Character type LCD display communication interface. * Direction of cursor or display shift. * Writing mode: cursor or display moving and direction setting. * State of the LCD display. * Cursor mode. * Line mode. * Characters font. * Size of the bus. * Pin of the pic connected to the [e] entry of the LCD display. * Pin of the pic connected to the [rs] entry of the LCD display. * Pin of the pic connected to the [rw] entry of the LCD display. * Connects the PIC to the LCD display. Takes informations about connection in the module C. * Clear the LCD display. * Return cursor and display to their initial positions. * * Initialise the LCD display. Should be called once on the LCD power on. * Configure the LCD display. Should be called after the LCD initialisation. * * Get the current position of the cursor as (line, column). * moveto line column moves the cursor at (line, column). * * Register a new character bitmap. * * Write the character on the LCD display. * Write the string on the LCD display at the current cursor position. * Display view as output channel. Can be used as argument of Printf.fprintf. * Clears the LCD display. * Returns cursor and display to their initial positions. * * Initialises the LCD display. Should be called once on the LCD power on. * Configures the LCD display. Should be called after the LCD initialisation. * * Get the current position of the cursor as (line, column). * moveto line column moves the cursor at (line, column). * * Register a new character bitmap. * * Write the character on the LCD display. * Write the string on the LCD display at the current cursor position. * Display view as output channel. Can be used as argument of Printf.fprintf. * Create a connection to an Lcd display. Offers the same features as Connect but in another style.
This file is distributed under the terms of the CeCILL license . * Possible sizes of data connection between the PIC and the LCD display type bus_size = Four | Eight type direction = Left | Right type mode = Cursor_left | Cursor_right | Display_left | Display_right type state = On | Off type cursor = Invisible | Underscore | Block type lmode = One | Two type font = F5x8 | F5x10 * about connection between the PIC and the LCD display . module type S = sig val bus_size : bus_size val e : Pic.bit val rs : Pic.bit val rw : Pic.bit val bus : Pic.reg * Port of the pic connected to the bus of the LCD display . In case of 4 bit bus , the 4th highest bits of the port are used . In case of 4 bit bus, the 4th highest bits of the port are used. *) end module Connect : functor (C : S) -> sig val clear : unit -> unit val home : unit -> unit val init : unit -> unit val config : ?mode:mode -> ?disp:state -> ?cursor:cursor -> ?lmode:lmode -> ?font:font -> unit -> unit val current_position : unit -> int * int val moveto : int -> int -> unit val shift_cursor : direction -> unit * Shift cursor of 1 character . val shift_display : direction -> unit * Shift display of 1 character . val register_bitmap : char -> int -> int -> int -> unit val print_char : char -> unit val print_string : string -> unit val print_int : int -> unit * Write one integer on the LCD display , in decimal . val output : out_channel end type display = { clear : unit -> unit; home : unit -> unit; init : unit -> unit; config : ?mode:mode -> ?disp:state -> ?cursor:cursor -> ?lmode:lmode -> ?font:font -> unit -> unit; current_position : unit -> int * int; moveto : int -> int -> unit; * Shifts cursor of 1 character . shift_cursor : direction -> unit; * Shifts display of 1 character . shift_display : direction -> unit; register_bitmap : char -> int -> int -> int -> unit; print_char : char -> unit; print_string : string -> unit; * Write one integer on the LCD display , in decimal . print_int : int -> unit; output : out_channel; } val connect : bus_size:bus_size -> e:Pic.bit -> rs:Pic.bit -> rw:Pic.bit -> bus:Pic.reg -> display
dcc6584bb6a57b30b946a47c5342f42a1d3c9d6c2a600964a54652460301ee42
cobaweel/piffle
Path.hs
Piffle , Copyright ( C ) 2007 , . This program is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} module Path( readFileInSearchPaths, searchInSearchPath, getSearchPath, parseSearchPath ) where import Control.Monad import Data.List (break) import Data.Maybe (fromMaybe) import System.Posix.Env import System.Posix.Files -- SEARCH PATHS ------------------------------------------------------ This module contains some utilities for dealing with standard(ish ) UNIX search paths , such as the $ PATH variable . XXX It module would be simpler and more reliable if it used System . FilePath , but that library is not available in ghc 6.4 ; when I get around to upgrading to ghc 6.6 I will switch to using System . FilePath . UNIX search paths, such as the $PATH variable. XXX It module would be simpler and more reliable if it used System.FilePath, but that library is not available in ghc 6.4; when I get around to upgrading to ghc 6.6 I will switch to using System.FilePath. -} IT IS IMPORTANT TO NOTE THAT FOR THIS LIBRARY , A PATH MAY STILL CONTAIN DIRECTORIES WITHOUT TRAILING SLASHES . TRAILING SLASHES ARE ADDED WHEN THE PATH IS ACTUALLY USED . STILL CONTAIN DIRECTORIES WITHOUT TRAILING SLASHES. TRAILING SLASHES ARE ADDED WHEN THE PATH IS ACTUALLY USED. -} Read the file named fn , in the search path specified in environment variable , or else in the search path specified . variable envVariable, or else in the search path specified. -} readFileInSearchPaths :: String -> [String] -> String -> IO String readFileInSearchPaths fn searchPath envVariable = do envPath <- getSearchPath envVariable fn <- searchInSearchPath fn (envPath ++ searchPath) readFile fn Search for filename in the given search path , and if it is found , return path to the file . If not found , fail ( in IO ) . return path to the file. If not found, fail (in IO). -} searchInSearchPath :: String -> [String] -> IO String searchInSearchPath filename searchPath = case searchPath of [] -> fail ("file " ++ filename ++ " not found") x:xs -> let fullFileName = normalizePath x ++ filename in do exist <- fileExist fullFileName if exist then return fullFileName else searchInSearchPath filename xs {- Retrieve an environment variable and parse it as a search path. Empty elements are interpreted as referring to the current working directory. All elements are delivered with trailing slash. -} getSearchPath :: String -> IO [String] getSearchPath envVariable = do path <- getEnv envVariable return (parseSearchPath (fromMaybe "" path)) {- This parses a standard UNIXy search path of directories separated by colons. Note that empty elements are included. -} parseSearchPath :: String -> [String] parseSearchPath path = case break (== ':') path of ("", "") -> [] (element, "") -> [element] (element, _:rest) -> element:(parseSearchPath rest) Add a / to the end of a path if there is n't one . Interpret the empty path as " ./ " ( this is a bit arbitrary , but does the right thing in many cases . ) empty path as "./" (this is a bit arbitrary, but does the right thing in many cases.) -} normalizePath :: String -> String normalizePath "" = "./" normalizePath path = if maybeLast path == Just '/' then path else path ++ "/" {- Data.List really ought to contain this function. I don't like unsafe functions like 'last'. They make me have to actually manually check invariants. Bletch. -} maybeLast :: [t] -> Maybe t maybeLast [] = Nothing maybeLast xs = Just (last xs)
null
https://raw.githubusercontent.com/cobaweel/piffle/7c4cfb5301c5c55c229098d3938d3b023d69cde4/src/Path.hs
haskell
SEARCH PATHS ------------------------------------------------------ Retrieve an environment variable and parse it as a search path. Empty elements are interpreted as referring to the current working directory. All elements are delivered with trailing slash. This parses a standard UNIXy search path of directories separated by colons. Note that empty elements are included. Data.List really ought to contain this function. I don't like unsafe functions like 'last'. They make me have to actually manually check invariants. Bletch.
Piffle , Copyright ( C ) 2007 , . This program is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} module Path( readFileInSearchPaths, searchInSearchPath, getSearchPath, parseSearchPath ) where import Control.Monad import Data.List (break) import Data.Maybe (fromMaybe) import System.Posix.Env import System.Posix.Files This module contains some utilities for dealing with standard(ish ) UNIX search paths , such as the $ PATH variable . XXX It module would be simpler and more reliable if it used System . FilePath , but that library is not available in ghc 6.4 ; when I get around to upgrading to ghc 6.6 I will switch to using System . FilePath . UNIX search paths, such as the $PATH variable. XXX It module would be simpler and more reliable if it used System.FilePath, but that library is not available in ghc 6.4; when I get around to upgrading to ghc 6.6 I will switch to using System.FilePath. -} IT IS IMPORTANT TO NOTE THAT FOR THIS LIBRARY , A PATH MAY STILL CONTAIN DIRECTORIES WITHOUT TRAILING SLASHES . TRAILING SLASHES ARE ADDED WHEN THE PATH IS ACTUALLY USED . STILL CONTAIN DIRECTORIES WITHOUT TRAILING SLASHES. TRAILING SLASHES ARE ADDED WHEN THE PATH IS ACTUALLY USED. -} Read the file named fn , in the search path specified in environment variable , or else in the search path specified . variable envVariable, or else in the search path specified. -} readFileInSearchPaths :: String -> [String] -> String -> IO String readFileInSearchPaths fn searchPath envVariable = do envPath <- getSearchPath envVariable fn <- searchInSearchPath fn (envPath ++ searchPath) readFile fn Search for filename in the given search path , and if it is found , return path to the file . If not found , fail ( in IO ) . return path to the file. If not found, fail (in IO). -} searchInSearchPath :: String -> [String] -> IO String searchInSearchPath filename searchPath = case searchPath of [] -> fail ("file " ++ filename ++ " not found") x:xs -> let fullFileName = normalizePath x ++ filename in do exist <- fileExist fullFileName if exist then return fullFileName else searchInSearchPath filename xs getSearchPath :: String -> IO [String] getSearchPath envVariable = do path <- getEnv envVariable return (parseSearchPath (fromMaybe "" path)) parseSearchPath :: String -> [String] parseSearchPath path = case break (== ':') path of ("", "") -> [] (element, "") -> [element] (element, _:rest) -> element:(parseSearchPath rest) Add a / to the end of a path if there is n't one . Interpret the empty path as " ./ " ( this is a bit arbitrary , but does the right thing in many cases . ) empty path as "./" (this is a bit arbitrary, but does the right thing in many cases.) -} normalizePath :: String -> String normalizePath "" = "./" normalizePath path = if maybeLast path == Just '/' then path else path ++ "/" maybeLast :: [t] -> Maybe t maybeLast [] = Nothing maybeLast xs = Just (last xs)
5970d5d16b694dc259d15e2b28a7b92af83ed8d54fa88bb6dc596e276f7e8751
gafiatulin/codewars
Manhattan.hs
Manhattan Distance -- / module Manhattan where manhattanDistance :: (Int, Int) -> (Int, Int) -> Int manhattanDistance (x1, y1) (x2, y2) = abs (x1-x2) + abs (y1-y2)
null
https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/6%20kyu/Manhattan.hs
haskell
/
Manhattan Distance module Manhattan where manhattanDistance :: (Int, Int) -> (Int, Int) -> Int manhattanDistance (x1, y1) (x2, y2) = abs (x1-x2) + abs (y1-y2)
4d11bb290071761aedc7fd65bb996c9447233d5505ed5c6e753be8b39c3945de
avsm/platform
usegtrip.ml
--------------------------------------------------------------------------- Copyright ( c ) 2014 . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % % NAME%% % % --------------------------------------------------------------------------- Copyright (c) 2014 Daniel C. Bünzli. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %%NAME%% %%VERSION%% ---------------------------------------------------------------------------*) let str = Printf.sprintf let pp = Format.fprintf let pp_pos ppf d = pp ppf "%d.%d:(%d,%06X) " (Uutf.decoder_line d) (Uutf.decoder_col d) (Uutf.decoder_count d) (Uutf.decoder_byte_count d) let pp_malformed ppf bs = let l = String.length bs in pp ppf "@[malformed bytes @[("; if l > 0 then pp ppf "%02X" (Char.code (bs.[0])); for i = 1 to l - 1 do pp ppf "@ %02X" (Char.code (bs.[i])) done; pp ppf ")@]@]" let exec = Filename.basename Sys.executable_name let log f = Format.eprintf ("%s: " ^^ f ^^ "@?") exec let input_malformed = ref false let log_malformed inf d bs = input_malformed := true; log "%s:%a: %a@." inf pp_pos d pp_malformed bs let u_rep = `Uchar Uutf.u_rep (* Output *) let uchar_ascii delim ppf = let last_was_u = ref false in function | `Uchar u -> if !last_was_u then (Format.pp_print_char ppf ' '); last_was_u := true; pp ppf "U+%04X" (Uchar.to_int u) | `Boundary -> last_was_u := false; pp ppf "%s" delim | `End -> () let uchar_encoder enc delim = let enc = match enc with | `ISO_8859_1 | `US_ASCII -> `UTF_8 | #Uutf.encoding as enc -> enc in let delim = let add acc _ = function | `Uchar _ as u -> u :: acc | `Malformed bs -> log "delimiter: %a" pp_malformed bs; u_rep :: acc in List.rev (Uutf.String.fold_utf_8 add [] delim) in let e = Uutf.encoder enc (`Channel stdout) in function | `Uchar _ | `End as v -> ignore (Uutf.encode e v) | `Boundary -> List.iter (fun u -> ignore (Uutf.encode e u)) delim let out_fun delim ascii oe = if ascii then uchar_ascii delim Format.std_formatter else uchar_encoder oe delim (* Trip *) let segment boundary inf d first_dec out = let segmenter = Uuseg.create boundary in let rec add v = match Uuseg.add segmenter v with | `Uchar _ | `Boundary as v -> out v; add `Await | `Await | `End -> () in let rec loop d = function | `Uchar _ as v -> add v; loop d (Uutf.decode d) | `End as v -> add v; out `End | `Malformed bs -> log_malformed inf d bs; add u_rep; loop d (Uutf.decode d) | `Await -> assert false in if Uutf.decoder_removed_bom d then add (`Uchar Uutf.u_bom); loop d first_dec let trip seg inf enc delim ascii = try let ic = if inf = "-" then stdin else open_in inf in let d = Uutf.decoder ?encoding:enc (`Channel ic) in let first_dec = Uutf.decode d in (* guess encoding if needed. *) let out = out_fun delim ascii (Uutf.decoder_encoding d) in segment seg inf d first_dec out; if inf <> "-" then close_in ic; flush stdout with Sys_error e -> log "%s@." e; exit 1 (* Version *) let unicode_version () = Format.printf "%s@." Uuseg.unicode_version (* Cmd *) let do_cmd cmd seg inf enc delim ascii = match cmd with | `Unicode_version -> unicode_version () | `Trip -> trip seg inf enc delim ascii (* Cmdline interface *) open Cmdliner let cmd = let doc = "Output supported Unicode version." in let unicode_version = `Unicode_version, Arg.info ["unicode-version"] ~doc in Arg.(value & vflag `Trip [unicode_version]) let seg_docs = "SEGMENTATION" let seg = let docs = seg_docs in let doc = "Line break opportunities boundaries." in let line = `Line_break, Arg.info ["l"; "line"] ~doc ~docs in let doc = "Grapheme cluster boundaries." in let gc = `Grapheme_cluster, Arg.info ["g"; "grapheme-cluster"] ~doc ~docs in let doc = "Word boundaries (default)." in let w = `Word, Arg.info ["w"; "word"] ~doc ~docs in let doc = "Sentence boundaries." in let s = `Sentence, Arg.info ["s"; "sentence"] ~doc ~docs in Arg.(value & vflag `Word [line; gc; w; s]) let file = let doc = "The input file. Reads from stdin if unspecified." in Arg.(value & pos 0 string "-" & info [] ~doc ~docv:"FILE") let enc = let enc = [ "UTF-8", `UTF_8; "UTF-16", `UTF_16; "UTF-16LE", `UTF_16LE; "UTF-16BE", `UTF_16BE; "ASCII", `US_ASCII; "latin1", `ISO_8859_1 ] in let doc = str "Input encoding, must %s. If unspecified the encoding is \ guessed. The output encoding is the same as the input \ encoding except for ASCII and latin1 where UTF-8 is output." (Arg.doc_alts_enum enc) in Arg.(value & opt (some (enum enc)) None & info [ "e"; "encoding" ] ~doc) let ascii = let doc = "Output the input text as space (U+0020) separated Unicode scalar values written in the US-ASCII charset." in Arg.(value & flag & info ["a"; "ascii"] ~doc) let delim = let doc = "The UTF-8 encoded delimiter used to denote boundaries." in Arg.(value & opt string "|" & Arg.info [ "d"; "delimiter" ] ~doc ~docv:"SEP") let cmd = let doc = "segment Unicode text" in let man = [ `S "DESCRIPTION"; `P "$(tname) inputs Unicode text from stdin and rewrites it to stdout with segment boundaries as determined according the locale independent specifications of UAX 29 and UAX 14. Boundaries are represented by the UTF-8 encoded delimiter string specified with the option $(b,-d) (defaults to `|')."; `P "Invalid byte sequences in the input are reported on stderr and replaced by the Unicode replacement character (U+FFFD) in the output."; `S seg_docs; `S "OPTIONS"; `S "EXIT STATUS"; `P "$(tname) exits with one of the following values:"; `I ("0", "no error occured"); `I ("1", "a command line parsing error occured"); `I ("2", "the input text was malformed"); `S "BUGS"; `P "This program is distributed with the Uuseg OCaml library. See for contact information."; ] in Term.(pure do_cmd $ cmd $ seg $ file $ enc $ delim $ ascii), Term.info "usegtrip" ~version:"%%VERSION%%" ~doc ~man let () = match Term.eval cmd with | `Error _ -> exit 1 | _ -> if !input_malformed then exit 2 else exit 0 --------------------------------------------------------------------------- Copyright ( c ) 2014 Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2014 Daniel C. Bünzli Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/uuseg.12.0.0%2Bdune/test/usegtrip.ml
ocaml
Output Trip guess encoding if needed. Version Cmd Cmdline interface
--------------------------------------------------------------------------- Copyright ( c ) 2014 . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % % NAME%% % % --------------------------------------------------------------------------- Copyright (c) 2014 Daniel C. Bünzli. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %%NAME%% %%VERSION%% ---------------------------------------------------------------------------*) let str = Printf.sprintf let pp = Format.fprintf let pp_pos ppf d = pp ppf "%d.%d:(%d,%06X) " (Uutf.decoder_line d) (Uutf.decoder_col d) (Uutf.decoder_count d) (Uutf.decoder_byte_count d) let pp_malformed ppf bs = let l = String.length bs in pp ppf "@[malformed bytes @[("; if l > 0 then pp ppf "%02X" (Char.code (bs.[0])); for i = 1 to l - 1 do pp ppf "@ %02X" (Char.code (bs.[i])) done; pp ppf ")@]@]" let exec = Filename.basename Sys.executable_name let log f = Format.eprintf ("%s: " ^^ f ^^ "@?") exec let input_malformed = ref false let log_malformed inf d bs = input_malformed := true; log "%s:%a: %a@." inf pp_pos d pp_malformed bs let u_rep = `Uchar Uutf.u_rep let uchar_ascii delim ppf = let last_was_u = ref false in function | `Uchar u -> if !last_was_u then (Format.pp_print_char ppf ' '); last_was_u := true; pp ppf "U+%04X" (Uchar.to_int u) | `Boundary -> last_was_u := false; pp ppf "%s" delim | `End -> () let uchar_encoder enc delim = let enc = match enc with | `ISO_8859_1 | `US_ASCII -> `UTF_8 | #Uutf.encoding as enc -> enc in let delim = let add acc _ = function | `Uchar _ as u -> u :: acc | `Malformed bs -> log "delimiter: %a" pp_malformed bs; u_rep :: acc in List.rev (Uutf.String.fold_utf_8 add [] delim) in let e = Uutf.encoder enc (`Channel stdout) in function | `Uchar _ | `End as v -> ignore (Uutf.encode e v) | `Boundary -> List.iter (fun u -> ignore (Uutf.encode e u)) delim let out_fun delim ascii oe = if ascii then uchar_ascii delim Format.std_formatter else uchar_encoder oe delim let segment boundary inf d first_dec out = let segmenter = Uuseg.create boundary in let rec add v = match Uuseg.add segmenter v with | `Uchar _ | `Boundary as v -> out v; add `Await | `Await | `End -> () in let rec loop d = function | `Uchar _ as v -> add v; loop d (Uutf.decode d) | `End as v -> add v; out `End | `Malformed bs -> log_malformed inf d bs; add u_rep; loop d (Uutf.decode d) | `Await -> assert false in if Uutf.decoder_removed_bom d then add (`Uchar Uutf.u_bom); loop d first_dec let trip seg inf enc delim ascii = try let ic = if inf = "-" then stdin else open_in inf in let d = Uutf.decoder ?encoding:enc (`Channel ic) in let out = out_fun delim ascii (Uutf.decoder_encoding d) in segment seg inf d first_dec out; if inf <> "-" then close_in ic; flush stdout with Sys_error e -> log "%s@." e; exit 1 let unicode_version () = Format.printf "%s@." Uuseg.unicode_version let do_cmd cmd seg inf enc delim ascii = match cmd with | `Unicode_version -> unicode_version () | `Trip -> trip seg inf enc delim ascii open Cmdliner let cmd = let doc = "Output supported Unicode version." in let unicode_version = `Unicode_version, Arg.info ["unicode-version"] ~doc in Arg.(value & vflag `Trip [unicode_version]) let seg_docs = "SEGMENTATION" let seg = let docs = seg_docs in let doc = "Line break opportunities boundaries." in let line = `Line_break, Arg.info ["l"; "line"] ~doc ~docs in let doc = "Grapheme cluster boundaries." in let gc = `Grapheme_cluster, Arg.info ["g"; "grapheme-cluster"] ~doc ~docs in let doc = "Word boundaries (default)." in let w = `Word, Arg.info ["w"; "word"] ~doc ~docs in let doc = "Sentence boundaries." in let s = `Sentence, Arg.info ["s"; "sentence"] ~doc ~docs in Arg.(value & vflag `Word [line; gc; w; s]) let file = let doc = "The input file. Reads from stdin if unspecified." in Arg.(value & pos 0 string "-" & info [] ~doc ~docv:"FILE") let enc = let enc = [ "UTF-8", `UTF_8; "UTF-16", `UTF_16; "UTF-16LE", `UTF_16LE; "UTF-16BE", `UTF_16BE; "ASCII", `US_ASCII; "latin1", `ISO_8859_1 ] in let doc = str "Input encoding, must %s. If unspecified the encoding is \ guessed. The output encoding is the same as the input \ encoding except for ASCII and latin1 where UTF-8 is output." (Arg.doc_alts_enum enc) in Arg.(value & opt (some (enum enc)) None & info [ "e"; "encoding" ] ~doc) let ascii = let doc = "Output the input text as space (U+0020) separated Unicode scalar values written in the US-ASCII charset." in Arg.(value & flag & info ["a"; "ascii"] ~doc) let delim = let doc = "The UTF-8 encoded delimiter used to denote boundaries." in Arg.(value & opt string "|" & Arg.info [ "d"; "delimiter" ] ~doc ~docv:"SEP") let cmd = let doc = "segment Unicode text" in let man = [ `S "DESCRIPTION"; `P "$(tname) inputs Unicode text from stdin and rewrites it to stdout with segment boundaries as determined according the locale independent specifications of UAX 29 and UAX 14. Boundaries are represented by the UTF-8 encoded delimiter string specified with the option $(b,-d) (defaults to `|')."; `P "Invalid byte sequences in the input are reported on stderr and replaced by the Unicode replacement character (U+FFFD) in the output."; `S seg_docs; `S "OPTIONS"; `S "EXIT STATUS"; `P "$(tname) exits with one of the following values:"; `I ("0", "no error occured"); `I ("1", "a command line parsing error occured"); `I ("2", "the input text was malformed"); `S "BUGS"; `P "This program is distributed with the Uuseg OCaml library. See for contact information."; ] in Term.(pure do_cmd $ cmd $ seg $ file $ enc $ delim $ ascii), Term.info "usegtrip" ~version:"%%VERSION%%" ~doc ~man let () = match Term.eval cmd with | `Error _ -> exit 1 | _ -> if !input_malformed then exit 2 else exit 0 --------------------------------------------------------------------------- Copyright ( c ) 2014 Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2014 Daniel C. Bünzli Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
2f7da16c839c5380e63817ac6148d0c8b3b781c68822aebca1a4fc9f0e2a2b54
emaphis/HtDP2e-solutions
10_01_163_FTC.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname 10_01_163_FTC) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) HtDP 2e - 10 More on Lists 10.1 Functions that Produce Functions Exercise : 163 to Celcius Ex . 163 : Design convertFC . The function converts a list of measurements in Fahrenheit ;; to a list of Celsius measurements. ; List-of-Temps -> List-of-Temps convert a list of Temps in to a List of Temps is Celcius (check-expect (f->c* '()) '()) (check-expect (f->c* (cons -40 (cons 32 (cons 68 (cons 212 '()))))) (cons -40 (cons 0 (cons 20 (cons 100 '()))))) (define (f->c* lot) (cond [(empty? lot) '()] [else (cons (f->c (first lot)) (f->c* (rest lot)))])) ; Number -> Number convert a temp in to a temp in Celcius (check-expect (f->c -40) -40) (check-expect (f->c 32) 0) (check-expect (f->c 68) 20) (check-expect (f->c 212) 100) (define (f->c f) (* 5/9 (- f 32)))
null
https://raw.githubusercontent.com/emaphis/HtDP2e-solutions/ecb60b9a7bbf9b8999c0122b6ea152a3301f0a68/2-Arbitrarily-Large-Data/10-More-on-Lists/10_01_163_FTC.rkt
racket
about the language level of this file in a form that our tools can easily process. to a list of Celsius measurements. List-of-Temps -> List-of-Temps Number -> Number
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname 10_01_163_FTC) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) HtDP 2e - 10 More on Lists 10.1 Functions that Produce Functions Exercise : 163 to Celcius Ex . 163 : Design convertFC . The function converts a list of measurements in Fahrenheit convert a list of Temps in to a List of Temps is Celcius (check-expect (f->c* '()) '()) (check-expect (f->c* (cons -40 (cons 32 (cons 68 (cons 212 '()))))) (cons -40 (cons 0 (cons 20 (cons 100 '()))))) (define (f->c* lot) (cond [(empty? lot) '()] [else (cons (f->c (first lot)) (f->c* (rest lot)))])) convert a temp in to a temp in Celcius (check-expect (f->c -40) -40) (check-expect (f->c 32) 0) (check-expect (f->c 68) 20) (check-expect (f->c 212) 100) (define (f->c f) (* 5/9 (- f 32)))
0ae11772f3b77551bcd75618ad36241337b49ad5708f9a0ef6a25848ae3cff0c
dschrempf/elynx
PointProcess.hs
{-# LANGUAGE BangPatterns #-} -- | Module : ELynx . Tree . Simulate . PointProcess Description : Point process and functions Copyright : 2021 License : GPL-3.0 - or - later -- -- Maintainer : -- Stability : unstable -- Portability : portable -- Creation date : Tue Feb 13 13:16:18 2018 . -- See Gernhard , T. ( 2008 ) . The conditioned reconstructed process . Journal of Theoretical Biology , 253(4 ) , 769–778 . . -- -- The point process can be used to simulate reconstructed trees under the birth -- and death process. module ELynx.Tree.Simulate.PointProcess ( PointProcess (..), TimeSpec (..), simulate, toReconstructedTree, simulateReconstructedTree, simulateNReconstructedTrees, ) where import Control.Monad import Data.Function import Data.List import Data.Sequence (Seq) import qualified Data.Sequence as S import ELynx.Tree.Distribution.BirthDeath import ELynx.Tree.Distribution.BirthDeathCritical import ELynx.Tree.Distribution.BirthDeathCriticalNoTime import ELynx.Tree.Distribution.BirthDeathNearlyCritical import ELynx.Tree.Distribution.TimeOfOrigin import ELynx.Tree.Distribution.TimeOfOriginNearCritical import ELynx.Tree.Distribution.Types import ELynx.Tree.Length import ELynx.Tree.Rooted import qualified Statistics.Distribution as D import System.Random.Stateful -- Require near critical process if birth and death rates are closer than this value. epsNearCriticalPointProcess :: Double epsNearCriticalPointProcess = 1e-5 -- Also the distribution of origins needs a Tailor expansion for near critical values. epsNearCriticalTimeOfOrigin :: Double epsNearCriticalTimeOfOrigin = 1e-8 -- Require critical process if birth and death rates are closer than this value. eps :: Double eps = 1e-12 (=~=) :: Double -> Double -> Bool x =~= y = eps > abs (x - y) -- Sort a list and also return original indices. sortListWithIndices :: Ord a => [a] -> [(a, Int)] sortListWithIndices xs = sortBy (compare `on` fst) $ zip xs ([0 ..] :: [Int]) -- Insert element into random position of list. randomInsertList :: StatefulGen g m => a -> [a] -> g -> m [a] randomInsertList e v g = do let l = length v i <- uniformRM (0, l) g return $ take i v ++ [e] ++ drop i v | A _ _ point process _ _ for \(n\ ) points and of age \(t_{or}\ ) is defined as follows . Draw $ n$ points on the horizontal axis at \(1,2,\ldots , n\ ) . Pick \(n-1\ ) points at locations \((i+1/2 , s_i)\ ) , \(i=1,2,\ldots , n-1\ ) ; -- \(0 < s_i < t_{or}\). There is a bijection between (ranked) oriented trees -- and the point process. Usually, a will be 'String' (or 'Int') and b will be -- 'Double'. data PointProcess a b = PointProcess { points :: ![a], values :: ![b], origin :: !b } deriving (Read, Show, Eq) -- | Tree height specification. data TimeSpec = -- | Sample time of origin from respective distribution. Random | -- | Condition on time of origin. Origin Time | Condition on time of most recent common ancestor ( MRCA ) . Mrca Time -- | Sample a point process using the 'BirthDeathDistribution'. The names of the -- points will be integers. simulate :: StatefulGen g m => -- | Number of points (samples). Int -> | Time of origin or MRCA . TimeSpec -> -- | Birth rate. Rate -> -- | Death rate. Rate -> g -> m (PointProcess Int Double) simulate n ts l m g | n < 1 = error "Number of samples needs to be one or larger." | l < 0.0 = error "Birth rate needs to be positive." | otherwise = case ts of Random -> simulateRandom n l m g Origin t -> simulateOrigin n t l m g Mrca t -> simulateMrca n t l m g -- No time of origin given. We also don't need to take care of the conditioning ( origin or MRCA ) . simulateRandom :: StatefulGen g m => Int -> Double -> Double -> g -> m (PointProcess Int Double) simulateRandom n l m g | -- There is no formula for the over-critical process. m > l = error "simulateRandom: Please specify height if mu > lambda." | -- For the critical process, we have no idea about the time of origin, but can -- use a specially derived distribution. m =~= l = do !vs <- replicateM (n - 1) (D.genContVar (BDCNTD l) g) -- The length of the root branch will be 0. let t = maximum vs return $ PointProcess [0 .. (n - 1)] vs t | -- For the near critical process, we use a special distribution. abs (m - l) <= epsNearCriticalTimeOfOrigin = do t <- D.genContVar (TONCD n l m) g simulateOrigin n t l m g For a sub - critical branching process , we can use the formula from . otherwise = do t <- D.genContVar (TOD n l m) g simulateOrigin n t l m g Time of origin is given . simulateOrigin :: StatefulGen g m => Int -> Time -> Double -> Double -> g -> m (PointProcess Int Double) simulateOrigin n t l m g | t < 0.0 = error "simulateOrigin: Time of origin needs to be positive." See , T. , & Steel , M. ( 2019 ) . Swapping birth and death : symmetries -- and transformations in phylodynamic models. , (), . -- . Should be possible now. -- | m < 0.0 = error " Death rate needs to be positive . " Now , we have three different cases . 1 . The critical branching process . 2 . The near critical branching process . 3 . Normal values :) . m =~= l = do !vs <- replicateM (n - 1) (D.genContVar (BDCD t l) g) return $ PointProcess [0 .. (n - 1)] vs t | abs (m - l) <= epsNearCriticalPointProcess = do !vs <- replicateM (n - 1) (D.genContVar (BDNCD t l m) g) return $ PointProcess [0 .. (n - 1)] vs t | otherwise = do !vs <- replicateM (n - 1) (D.genContVar (BDD t l m) g) return $ PointProcess [0 .. (n - 1)] vs t Time of Mrca is given . simulateMrca :: StatefulGen g m => Int -> Time -> Double -> Double -> g -> m (PointProcess Int Double) simulateMrca n t l m g | t < 0.0 = error "simulateMrca: Time of MRCA needs to be positive." | m =~= l = do !vs <- replicateM (n - 2) (D.genContVar (BDCD t l) g) vs' <- randomInsertList t vs g return $ PointProcess [0 .. (n - 1)] vs' t | abs (m - l) <= epsNearCriticalPointProcess = do !vs <- replicateM (n - 2) (D.genContVar (BDNCD t l m) g) vs' <- randomInsertList t vs g return $ PointProcess [0 .. (n - 1)] vs' t | otherwise = do !vs <- replicateM (n - 2) (D.genContVar (BDD t l m) g) vs' <- randomInsertList t vs g return $ PointProcess [0 .. (n - 1)] vs' t -- Sort the values of a point process and their indices to be (the indices -- that they will have while creating the tree). sortPP :: (Ord b) => PointProcess a b -> ([b], [Int]) sortPP (PointProcess _ vs _) = (vsSorted, isSorted) where vsIsSorted = sortListWithIndices vs vsSorted = map fst vsIsSorted isSorted = flattenIndices $ map snd vsIsSorted -- Decrement indices that are above the one that is merged. flattenIndices :: [Int] -> [Int] flattenIndices is = snd $ mapAccumL fAcc [] is NOTE : fAcc is the speed bottleneck for simulating large trees . -- -- The accumulating function. Count the number of indices which are before the -- current index and lower than the current index. fAcc :: [Int] -> Int -> ([Int], Int) fAcc is i = (i : is, i') where i' = i - length (filter (< i) is) -- | See 'simulateReconstructedTree', but n times. simulateNReconstructedTrees :: (StatefulGen g m) => -- | Number of trees Int -> -- | Number of points (samples) Int -> | Time of origin or MRCA TimeSpec -> -- | Birth rate Rate -> -- | Death rate Rate -> g -> m (Forest Length Int) simulateNReconstructedTrees nT nP t l m g | nT <= 0 = return [] | otherwise = replicateM nT $ simulateReconstructedTree nP t l m g -- | Use the point process to simulate a reconstructed tree (see -- 'toReconstructedTree') possibly with specific height and a fixed number of -- leaves according to the birth and death process. simulateReconstructedTree :: StatefulGen g m => -- | Number of points (samples) Int -> | Time of origin or MRCA TimeSpec -> -- | Birth rate Rate -> -- | Death rate Rate -> g -> m (Tree Length Int) simulateReconstructedTree n t l m g = do PointProcess ns vs o <- simulate n t l m g return $ toReconstructedTree 0 $ PointProcess ns (map toLengthUnsafe vs) (toLengthUnsafe o) | Convert a point process to a reconstructed tree . See Lemma 2.2 . Of course , I decided to only use one tree structure with extinct and extant -- leaves (actually a complete tree). So a tree created here just does not -- contain extinct leaves. A function 'isReconstructed' is provided to test if a -- tree is reconstructed (and not complete) in this sense. However, a complete -- tree might show up as "reconstructed", just because, by chance, it does not -- contain extinct leaves. I wanted to use a Monoid constraint to get the unit -- element, but this fails for classical 'Int's. So, I rather have another -- (useless) argument. toReconstructedTree :: a -> -- Default node label. PointProcess a Length -> Tree Length a toReconstructedTree l pp@(PointProcess ps vs o) | length ps /= length vs + 1 = error "Too few or too many points." | length vs <= 1 = error "Too few values." | -- -- Test is deactivated. -- -- | otherwise = if isReconstructed treeOrigin then treeOrigin else error "Error in algorithm." otherwise = treeOrigin where (vsSorted, isSorted) = sortPP pp !lvs = S.fromList [Node 0 p [] | p <- ps] !heights = S.replicate (length ps) 0 !treeRoot = toReconstructedTree' isSorted vsSorted l lvs heights !h = last vsSorted !treeOrigin = modifyStem (+ (o - h)) treeRoot -- Move up the tree, connect nodes when they join according to the point process. toReconstructedTree' :: [Int] -> -- Sorted indices, see 'sort'. [Length] -> -- Sorted merge values. a -> -- Default node label. Seq (Tree Length a) -> -- Leaves with accumulated root branch lengths. Seq Length -> -- Accumulated heights of the leaves. Tree Length a toReconstructedTree' [] [] _ trs _ = trs `S.index` 0 toReconstructedTree' is vs l trs hs = toReconstructedTree' is' vs' l trs'' hs' where For the algorithm , see ' simulate ' but index starts at zero . !i = head is !is' = tail is !v = head vs !vs' = tail vs -- Left: l, right: r. !hl = hs `S.index` i !hr = hs `S.index` (i + 1) !dvl = v - hl !dvr = v - hr !tl = modifyStem (+ dvl) $ trs `S.index` i !tr = modifyStem (+ dvr) $ trs `S.index` (i + 1) !h' = hl + dvl -- Should be the same as 'hr + dvr'. !tm = Node 0 l [tl, tr] !trs'' = (S.take i trs S.|> tm) S.>< S.drop (i + 2) trs !hs' = (S.take i hs S.|> h') S.>< S.drop (i + 2) hs
null
https://raw.githubusercontent.com/dschrempf/elynx/bf5f0b353b5e2f74d29058fc86ea6723133cab5c/elynx-tree/src/ELynx/Tree/Simulate/PointProcess.hs
haskell
# LANGUAGE BangPatterns # | Maintainer : Stability : unstable Portability : portable The point process can be used to simulate reconstructed trees under the birth and death process. Require near critical process if birth and death rates are closer than this value. Also the distribution of origins needs a Tailor expansion for near critical values. Require critical process if birth and death rates are closer than this value. Sort a list and also return original indices. Insert element into random position of list. \(0 < s_i < t_{or}\). There is a bijection between (ranked) oriented trees and the point process. Usually, a will be 'String' (or 'Int') and b will be 'Double'. | Tree height specification. | Sample time of origin from respective distribution. | Condition on time of origin. | Sample a point process using the 'BirthDeathDistribution'. The names of the points will be integers. | Number of points (samples). | Birth rate. | Death rate. No time of origin given. We also don't need to take care of the conditioning There is no formula for the over-critical process. For the critical process, we have no idea about the time of origin, but can use a specially derived distribution. The length of the root branch will be 0. For the near critical process, we use a special distribution. and transformations in phylodynamic models. , (), . . Should be possible now. | m < 0.0 = error " Death rate needs to be positive . " Sort the values of a point process and their indices to be (the indices that they will have while creating the tree). Decrement indices that are above the one that is merged. The accumulating function. Count the number of indices which are before the current index and lower than the current index. | See 'simulateReconstructedTree', but n times. | Number of trees | Number of points (samples) | Birth rate | Death rate | Use the point process to simulate a reconstructed tree (see 'toReconstructedTree') possibly with specific height and a fixed number of leaves according to the birth and death process. | Number of points (samples) | Birth rate | Death rate leaves (actually a complete tree). So a tree created here just does not contain extinct leaves. A function 'isReconstructed' is provided to test if a tree is reconstructed (and not complete) in this sense. However, a complete tree might show up as "reconstructed", just because, by chance, it does not contain extinct leaves. I wanted to use a Monoid constraint to get the unit element, but this fails for classical 'Int's. So, I rather have another (useless) argument. Default node label. -- Test is deactivated. -- | otherwise = if isReconstructed treeOrigin then treeOrigin else error "Error in algorithm." Move up the tree, connect nodes when they join according to the point process. Sorted indices, see 'sort'. Sorted merge values. Default node label. Leaves with accumulated root branch lengths. Accumulated heights of the leaves. Left: l, right: r. Should be the same as 'hr + dvr'.
Module : ELynx . Tree . Simulate . PointProcess Description : Point process and functions Copyright : 2021 License : GPL-3.0 - or - later Creation date : Tue Feb 13 13:16:18 2018 . See Gernhard , T. ( 2008 ) . The conditioned reconstructed process . Journal of Theoretical Biology , 253(4 ) , 769–778 . . module ELynx.Tree.Simulate.PointProcess ( PointProcess (..), TimeSpec (..), simulate, toReconstructedTree, simulateReconstructedTree, simulateNReconstructedTrees, ) where import Control.Monad import Data.Function import Data.List import Data.Sequence (Seq) import qualified Data.Sequence as S import ELynx.Tree.Distribution.BirthDeath import ELynx.Tree.Distribution.BirthDeathCritical import ELynx.Tree.Distribution.BirthDeathCriticalNoTime import ELynx.Tree.Distribution.BirthDeathNearlyCritical import ELynx.Tree.Distribution.TimeOfOrigin import ELynx.Tree.Distribution.TimeOfOriginNearCritical import ELynx.Tree.Distribution.Types import ELynx.Tree.Length import ELynx.Tree.Rooted import qualified Statistics.Distribution as D import System.Random.Stateful epsNearCriticalPointProcess :: Double epsNearCriticalPointProcess = 1e-5 epsNearCriticalTimeOfOrigin :: Double epsNearCriticalTimeOfOrigin = 1e-8 eps :: Double eps = 1e-12 (=~=) :: Double -> Double -> Bool x =~= y = eps > abs (x - y) sortListWithIndices :: Ord a => [a] -> [(a, Int)] sortListWithIndices xs = sortBy (compare `on` fst) $ zip xs ([0 ..] :: [Int]) randomInsertList :: StatefulGen g m => a -> [a] -> g -> m [a] randomInsertList e v g = do let l = length v i <- uniformRM (0, l) g return $ take i v ++ [e] ++ drop i v | A _ _ point process _ _ for \(n\ ) points and of age \(t_{or}\ ) is defined as follows . Draw $ n$ points on the horizontal axis at \(1,2,\ldots , n\ ) . Pick \(n-1\ ) points at locations \((i+1/2 , s_i)\ ) , \(i=1,2,\ldots , n-1\ ) ; data PointProcess a b = PointProcess { points :: ![a], values :: ![b], origin :: !b } deriving (Read, Show, Eq) data TimeSpec Random Origin Time | Condition on time of most recent common ancestor ( MRCA ) . Mrca Time simulate :: StatefulGen g m => Int -> | Time of origin or MRCA . TimeSpec -> Rate -> Rate -> g -> m (PointProcess Int Double) simulate n ts l m g | n < 1 = error "Number of samples needs to be one or larger." | l < 0.0 = error "Birth rate needs to be positive." | otherwise = case ts of Random -> simulateRandom n l m g Origin t -> simulateOrigin n t l m g Mrca t -> simulateMrca n t l m g ( origin or MRCA ) . simulateRandom :: StatefulGen g m => Int -> Double -> Double -> g -> m (PointProcess Int Double) simulateRandom n l m g m > l = error "simulateRandom: Please specify height if mu > lambda." m =~= l = do !vs <- replicateM (n - 1) (D.genContVar (BDCNTD l) g) let t = maximum vs return $ PointProcess [0 .. (n - 1)] vs t abs (m - l) <= epsNearCriticalTimeOfOrigin = do t <- D.genContVar (TONCD n l m) g simulateOrigin n t l m g For a sub - critical branching process , we can use the formula from . otherwise = do t <- D.genContVar (TOD n l m) g simulateOrigin n t l m g Time of origin is given . simulateOrigin :: StatefulGen g m => Int -> Time -> Double -> Double -> g -> m (PointProcess Int Double) simulateOrigin n t l m g | t < 0.0 = error "simulateOrigin: Time of origin needs to be positive." See , T. , & Steel , M. ( 2019 ) . Swapping birth and death : symmetries Now , we have three different cases . 1 . The critical branching process . 2 . The near critical branching process . 3 . Normal values :) . m =~= l = do !vs <- replicateM (n - 1) (D.genContVar (BDCD t l) g) return $ PointProcess [0 .. (n - 1)] vs t | abs (m - l) <= epsNearCriticalPointProcess = do !vs <- replicateM (n - 1) (D.genContVar (BDNCD t l m) g) return $ PointProcess [0 .. (n - 1)] vs t | otherwise = do !vs <- replicateM (n - 1) (D.genContVar (BDD t l m) g) return $ PointProcess [0 .. (n - 1)] vs t Time of Mrca is given . simulateMrca :: StatefulGen g m => Int -> Time -> Double -> Double -> g -> m (PointProcess Int Double) simulateMrca n t l m g | t < 0.0 = error "simulateMrca: Time of MRCA needs to be positive." | m =~= l = do !vs <- replicateM (n - 2) (D.genContVar (BDCD t l) g) vs' <- randomInsertList t vs g return $ PointProcess [0 .. (n - 1)] vs' t | abs (m - l) <= epsNearCriticalPointProcess = do !vs <- replicateM (n - 2) (D.genContVar (BDNCD t l m) g) vs' <- randomInsertList t vs g return $ PointProcess [0 .. (n - 1)] vs' t | otherwise = do !vs <- replicateM (n - 2) (D.genContVar (BDD t l m) g) vs' <- randomInsertList t vs g return $ PointProcess [0 .. (n - 1)] vs' t sortPP :: (Ord b) => PointProcess a b -> ([b], [Int]) sortPP (PointProcess _ vs _) = (vsSorted, isSorted) where vsIsSorted = sortListWithIndices vs vsSorted = map fst vsIsSorted isSorted = flattenIndices $ map snd vsIsSorted flattenIndices :: [Int] -> [Int] flattenIndices is = snd $ mapAccumL fAcc [] is NOTE : fAcc is the speed bottleneck for simulating large trees . fAcc :: [Int] -> Int -> ([Int], Int) fAcc is i = (i : is, i') where i' = i - length (filter (< i) is) simulateNReconstructedTrees :: (StatefulGen g m) => Int -> Int -> | Time of origin or MRCA TimeSpec -> Rate -> Rate -> g -> m (Forest Length Int) simulateNReconstructedTrees nT nP t l m g | nT <= 0 = return [] | otherwise = replicateM nT $ simulateReconstructedTree nP t l m g simulateReconstructedTree :: StatefulGen g m => Int -> | Time of origin or MRCA TimeSpec -> Rate -> Rate -> g -> m (Tree Length Int) simulateReconstructedTree n t l m g = do PointProcess ns vs o <- simulate n t l m g return $ toReconstructedTree 0 $ PointProcess ns (map toLengthUnsafe vs) (toLengthUnsafe o) | Convert a point process to a reconstructed tree . See Lemma 2.2 . Of course , I decided to only use one tree structure with extinct and extant toReconstructedTree :: PointProcess a Length -> Tree Length a toReconstructedTree l pp@(PointProcess ps vs o) | length ps /= length vs + 1 = error "Too few or too many points." | length vs <= 1 = error "Too few values." otherwise = treeOrigin where (vsSorted, isSorted) = sortPP pp !lvs = S.fromList [Node 0 p [] | p <- ps] !heights = S.replicate (length ps) 0 !treeRoot = toReconstructedTree' isSorted vsSorted l lvs heights !h = last vsSorted !treeOrigin = modifyStem (+ (o - h)) treeRoot toReconstructedTree' :: Tree Length a toReconstructedTree' [] [] _ trs _ = trs `S.index` 0 toReconstructedTree' is vs l trs hs = toReconstructedTree' is' vs' l trs'' hs' where For the algorithm , see ' simulate ' but index starts at zero . !i = head is !is' = tail is !v = head vs !vs' = tail vs !hl = hs `S.index` i !hr = hs `S.index` (i + 1) !dvl = v - hl !dvr = v - hr !tl = modifyStem (+ dvl) $ trs `S.index` i !tr = modifyStem (+ dvr) $ trs `S.index` (i + 1) !tm = Node 0 l [tl, tr] !trs'' = (S.take i trs S.|> tm) S.>< S.drop (i + 2) trs !hs' = (S.take i hs S.|> h') S.>< S.drop (i + 2) hs
6b3ac8ba826420ed5e6bab2f9a553d09a71f800f6613d49fe13d57261c55e9be
ghc/ghc
T13871.hs
{-# LANGUAGE Haskell2010 #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE GADTs #-} # LANGUAGE TypeFamilies # # LANGUAGE DataKinds , PolyKinds # # LANGUAGE TypeOperators # module Foo where import Data.Kind data Foo (a :: Type) (b :: Type) where MkFoo :: (a ~ Int, b ~ Char) => Foo a b data family Sing (a :: k) data SFoo (z :: Foo a b) where SMkFoo :: SFoo MkFoo
null
https://raw.githubusercontent.com/ghc/ghc/3c3060e4645b12595b187e7dbaa758e8adda15e0/testsuite/tests/typecheck/should_fail/T13871.hs
haskell
# LANGUAGE Haskell2010 # # LANGUAGE ConstraintKinds # # LANGUAGE GADTs #
# LANGUAGE TypeFamilies # # LANGUAGE DataKinds , PolyKinds # # LANGUAGE TypeOperators # module Foo where import Data.Kind data Foo (a :: Type) (b :: Type) where MkFoo :: (a ~ Int, b ~ Char) => Foo a b data family Sing (a :: k) data SFoo (z :: Foo a b) where SMkFoo :: SFoo MkFoo
273d6b02b5fccbdb9b307af020ff0897246788ce039c92b568dac7a31b0c77dc
brendanhay/amazonka
Main.hs
# OPTIONS_GHC -fno - warn - unused - imports # -- | -- Module : Main Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) module Main (main) where import Test.Amazonka.Wisdom import Test.Amazonka.Wisdom.Internal import Test.Tasty main :: IO () main = defaultMain $ testGroup "Wisdom" [ testGroup "tests" tests, testGroup "fixtures" fixtures ]
null
https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-wisdom/test/Main.hs
haskell
| Module : Main Stability : auto-generated
# OPTIONS_GHC -fno - warn - unused - imports # Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Main (main) where import Test.Amazonka.Wisdom import Test.Amazonka.Wisdom.Internal import Test.Tasty main :: IO () main = defaultMain $ testGroup "Wisdom" [ testGroup "tests" tests, testGroup "fixtures" fixtures ]
ea353caee8733e62aa67749f526e17177bd448abdae09b5b22879f1b3255a43c
mirage/ocaml-qcow
qcow_rwlock.mli
* Copyright ( C ) 2016 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * * Copyright (C) 2016 David Scott <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *) type t [@@deriving sexp_of] (** A lock which permits multiple concurrent threads to acquire it for reading but demands exclusivity for writing *) type ts = t list [@@deriving sexp_of] val make: (unit -> string) -> t (** [make describe_fn] creates a new lock, where [describe_fn ()] returns a human-readable description string suitable for debug output. *) type lock (** A value which represents holding a lock *) val unlock: lock -> unit (** [unlock locked] releases the lock associated with [locked] *) module Client: sig type t (** An entity which holds a set of locks *) val make: (unit -> string) -> t (** [make describe_fn] creates an entity where [describe_fn ()] returns a human-readable description of the client for use in debugging. *) end module Read: sig val with_lock: ?client:Client.t -> t -> (unit -> 'a Lwt.t) -> 'a Lwt.t (** [with_lock ?client t f] executes [f ()] when no other client has held the lock exclusively for writing. Note this means that I may hold the lock for writing and then re-lock it for reading. *) val lock: ?client:Client.t -> t -> lock Lwt.t (** [lock ?client t] locks [t]. This function blocks while another client holds the lock for writing. The lock must be released with [unlock] *) end module Write: sig val with_lock: ?client:Client.t -> t -> (unit -> 'a Lwt.t) -> 'a Lwt.t (** [with_lock ?client t f] executes [f ()] when no-other client is holding the lock for reading or writing. Note this means that I may hold the lock for reading and then re-lock it for writing. *) val try_lock: ?client:Client.t -> t -> lock option (** [try_lock ?client t] acquires a write lock on [t] if immediately possible, or returns None *) end module Debug: sig val assert_no_locks_held: Client.t -> unit (** Check that all locks have been explicitly released. *) end
null
https://raw.githubusercontent.com/mirage/ocaml-qcow/2418c66627dcce8420bcb06d7547db171528060a/lib/qcow_rwlock.mli
ocaml
* A lock which permits multiple concurrent threads to acquire it for reading but demands exclusivity for writing * [make describe_fn] creates a new lock, where [describe_fn ()] returns a human-readable description string suitable for debug output. * A value which represents holding a lock * [unlock locked] releases the lock associated with [locked] * An entity which holds a set of locks * [make describe_fn] creates an entity where [describe_fn ()] returns a human-readable description of the client for use in debugging. * [with_lock ?client t f] executes [f ()] when no other client has held the lock exclusively for writing. Note this means that I may hold the lock for writing and then re-lock it for reading. * [lock ?client t] locks [t]. This function blocks while another client holds the lock for writing. The lock must be released with [unlock] * [with_lock ?client t f] executes [f ()] when no-other client is holding the lock for reading or writing. Note this means that I may hold the lock for reading and then re-lock it for writing. * [try_lock ?client t] acquires a write lock on [t] if immediately possible, or returns None * Check that all locks have been explicitly released.
* Copyright ( C ) 2016 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * * Copyright (C) 2016 David Scott <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *) type t [@@deriving sexp_of] type ts = t list [@@deriving sexp_of] val make: (unit -> string) -> t type lock val unlock: lock -> unit module Client: sig type t val make: (unit -> string) -> t end module Read: sig val with_lock: ?client:Client.t -> t -> (unit -> 'a Lwt.t) -> 'a Lwt.t val lock: ?client:Client.t -> t -> lock Lwt.t end module Write: sig val with_lock: ?client:Client.t -> t -> (unit -> 'a Lwt.t) -> 'a Lwt.t val try_lock: ?client:Client.t -> t -> lock option end module Debug: sig val assert_no_locks_held: Client.t -> unit end
135f1e0b48cfaa160be0319feb3eb2b30d08f735ceff53f5066199c6ceb52aa9
rudymatela/speculate
binarytree.hs
import QuickSpec hiding (insert) import Test.QuickCheck hiding (insert,(==>)) import Data.Function (on) import Data.List (isSubsequenceOf) data BT a = Null | Fork (BT a) a (BT a) deriving (Show) instance (Eq a, Ord a) => Eq (BT a) where (==) = (==) `on` toList instance (Eq a, Ord a) => Ord (BT a) where (<=) = isSubsequenceOf `on` toList insert :: Ord a => a -> BT a -> BT a insert x Null = Fork Null x Null insert x t@(Fork t1 y t2) = case compare x y of LT -> Fork (insert x t1) y t2 EQ -> t GT -> Fork t1 y (insert x t2) delete :: Ord a => a -> BT a -> BT a delete x Null = Null delete x t@(Fork t1 y t2) = case compare x y of LT -> Fork (delete x t1) y t2 EQ -> graft t1 t2 GT -> Fork t1 y (delete x t2) isIn :: Ord a => a -> BT a -> Bool isIn x t = x `elem` toList t graft :: Ord a => BT a -> BT a -> BT a graft Null t = t graft (Fork t1 x t2) t = Fork t1 x (graft t2 t) toList :: Ord a => BT a -> [a] toList Null = [] toList (Fork t1 x t2) = toList t1 ++ [x] ++ toList t2 fromList :: Ord a => [a] -> BT a fromList = foldr insert Null fromList : : a = > [ a ] - > BT a fromList [ ] = Null fromList xs = Fork ( fromList ys ) x ( fromList zs ) where ( x : ys , zs ) = deal xs deal : : [ a ] - > ( [ a],[a ] ) deal [ ] = ( [ ] , [ ] ) deal ( x : xs ) = ( x : ys , zs ) where ( zs , ys ) = deal xs fromList :: Ord a => [a] -> BT a fromList [] = Null fromList xs = Fork (fromList ys) x (fromList zs) where (x:ys,zs) = deal xs deal :: [a] -> ([a],[a]) deal [] = ([],[]) deal (x:xs) = (x:ys,zs) where (zs,ys) = deal xs -} isSearch :: Ord a => BT a -> Bool isSearch = strictlyOrdered . toList ordered :: Ord a => [a] -> Bool ordered [] = True ordered xs = and (zipWith (<=) xs $ tail xs) strictlyOrdered :: Ord a => [a] -> Bool strictlyOrdered [] = True strictlyOrdered xs = and (zipWith (<) xs $ tail xs) | truncate tiers of values in the presence of one empty size -- -- truncateT [[x,y],[z,w],[],[],[],...] == [[x,y],[z,w]] truncateT :: [[a]] -> [[a]] truncateT ([]:xss) = [] truncateT (xs:xss) = xs:truncateT xss truncateT xss = xss instance (Ord a, Arbitrary a) => Arbitrary (BT a) where arbitrary = sized arbtree where arbtree 0 = return Null arbtree n = oneof [ return Null , (Fork <$> arbtree (n `div` 2) <*> arbitrary <*> arbtree (n `div` 2)) `suchThat` isSearch ] type Item = Int main = quickSpec signature { maxTermSize = Just 9 , maxTests = Just 2000 the maximum number of tests above needs to be 2000 , -- otherwise the law `isIn x t1 ==> isIn x (insert y t1) = True` -- does not appear in the output (which is mainly what I want with this benchmark ) . Even so , it works only about 2/3 of the time . , constants = [ constant "Null" (Null :: BT Item) , constant "insert" (insert :: Item -> BT Item -> BT Item) , constant "delete" (delete :: Item -> BT Item -> BT Item) , constant "isIn" (isIn :: Item -> BT Item -> Bool) -- , constant "<=" ((<=) :: Item -> Item -> Bool) , constant " < = " ( ( < =) : : BT Item - > BT Item - > Bool ) -- , constant "/=" ((/=) :: Item -> Item -> Bool) -- , constant "ordered" (ordered :: [Item] -> Bool) -- , constant "strictlyOrdered" (strictlyOrdered :: [Item] -> Bool) -- , constant "toList" (toList :: BT Item -> [Item]) -- , constant "fromList" (fromList :: [Item] -> BT Item) -- , constant "isSearch" (isSearch :: BT Item -> Bool) -- , constant "[]" ([]::[Item]) , constant "==>" ((==>) :: Bool -> Bool -> Bool) , constant "True" True , constant "False" False ] , instances = [ baseType (undefined :: BT Item) , baseTypeNames ["t1","t2","t3"] (undefined :: BT Item) ] } (==>) :: Bool -> Bool -> Bool False ==> _ = True True ==> p = p
null
https://raw.githubusercontent.com/rudymatela/speculate/8ec39747d03033db4349d554467d4b78bb72935d/bench/qs2/binarytree.hs
haskell
truncateT [[x,y],[z,w],[],[],[],...] == [[x,y],[z,w]] otherwise the law `isIn x t1 ==> isIn x (insert y t1) = True` does not appear in the output (which is mainly what I want with this , constant "<=" ((<=) :: Item -> Item -> Bool) , constant "/=" ((/=) :: Item -> Item -> Bool) , constant "ordered" (ordered :: [Item] -> Bool) , constant "strictlyOrdered" (strictlyOrdered :: [Item] -> Bool) , constant "toList" (toList :: BT Item -> [Item]) , constant "fromList" (fromList :: [Item] -> BT Item) , constant "isSearch" (isSearch :: BT Item -> Bool) , constant "[]" ([]::[Item])
import QuickSpec hiding (insert) import Test.QuickCheck hiding (insert,(==>)) import Data.Function (on) import Data.List (isSubsequenceOf) data BT a = Null | Fork (BT a) a (BT a) deriving (Show) instance (Eq a, Ord a) => Eq (BT a) where (==) = (==) `on` toList instance (Eq a, Ord a) => Ord (BT a) where (<=) = isSubsequenceOf `on` toList insert :: Ord a => a -> BT a -> BT a insert x Null = Fork Null x Null insert x t@(Fork t1 y t2) = case compare x y of LT -> Fork (insert x t1) y t2 EQ -> t GT -> Fork t1 y (insert x t2) delete :: Ord a => a -> BT a -> BT a delete x Null = Null delete x t@(Fork t1 y t2) = case compare x y of LT -> Fork (delete x t1) y t2 EQ -> graft t1 t2 GT -> Fork t1 y (delete x t2) isIn :: Ord a => a -> BT a -> Bool isIn x t = x `elem` toList t graft :: Ord a => BT a -> BT a -> BT a graft Null t = t graft (Fork t1 x t2) t = Fork t1 x (graft t2 t) toList :: Ord a => BT a -> [a] toList Null = [] toList (Fork t1 x t2) = toList t1 ++ [x] ++ toList t2 fromList :: Ord a => [a] -> BT a fromList = foldr insert Null fromList : : a = > [ a ] - > BT a fromList [ ] = Null fromList xs = Fork ( fromList ys ) x ( fromList zs ) where ( x : ys , zs ) = deal xs deal : : [ a ] - > ( [ a],[a ] ) deal [ ] = ( [ ] , [ ] ) deal ( x : xs ) = ( x : ys , zs ) where ( zs , ys ) = deal xs fromList :: Ord a => [a] -> BT a fromList [] = Null fromList xs = Fork (fromList ys) x (fromList zs) where (x:ys,zs) = deal xs deal :: [a] -> ([a],[a]) deal [] = ([],[]) deal (x:xs) = (x:ys,zs) where (zs,ys) = deal xs -} isSearch :: Ord a => BT a -> Bool isSearch = strictlyOrdered . toList ordered :: Ord a => [a] -> Bool ordered [] = True ordered xs = and (zipWith (<=) xs $ tail xs) strictlyOrdered :: Ord a => [a] -> Bool strictlyOrdered [] = True strictlyOrdered xs = and (zipWith (<) xs $ tail xs) | truncate tiers of values in the presence of one empty size truncateT :: [[a]] -> [[a]] truncateT ([]:xss) = [] truncateT (xs:xss) = xs:truncateT xss truncateT xss = xss instance (Ord a, Arbitrary a) => Arbitrary (BT a) where arbitrary = sized arbtree where arbtree 0 = return Null arbtree n = oneof [ return Null , (Fork <$> arbtree (n `div` 2) <*> arbitrary <*> arbtree (n `div` 2)) `suchThat` isSearch ] type Item = Int main = quickSpec signature { maxTermSize = Just 9 , maxTests = Just 2000 the maximum number of tests above needs to be 2000 , benchmark ) . Even so , it works only about 2/3 of the time . , constants = [ constant "Null" (Null :: BT Item) , constant "insert" (insert :: Item -> BT Item -> BT Item) , constant "delete" (delete :: Item -> BT Item -> BT Item) , constant "isIn" (isIn :: Item -> BT Item -> Bool) , constant " < = " ( ( < =) : : BT Item - > BT Item - > Bool ) , constant "==>" ((==>) :: Bool -> Bool -> Bool) , constant "True" True , constant "False" False ] , instances = [ baseType (undefined :: BT Item) , baseTypeNames ["t1","t2","t3"] (undefined :: BT Item) ] } (==>) :: Bool -> Bool -> Bool False ==> _ = True True ==> p = p
660d0ed78a893c83da7cf6ab587350450816c83cfcc1781e442a1c0ac9c1f9c3
SquidDev/urn
escape.lisp
(import urn/logger/format format) (import urn/resolve/builtins (builtin builtin-var?)) (import urn/resolve/scope scope) (define keywords "A set of all builtin Lua variables" :hidden (create-lookup '("and" "break" "do" "else" "elseif" "end" "false" "for" "function" "if" "in" "local" "nil" "not" "or" "repeat" "return" "then" "true" "until" "while"))) (defun lua-ident? (ident) "Determines if the given IDENT is a valid Lua identifier." (and (string/match ident "^[%a_][%w_]*$") (= (.> keywords ident) nil))) (defun ident? (x) "Determine whether X is a usable identifier character" :hidden (string/find x "[%a%d']")) (defun escape (name) "Escape an urn identifier NANE, converting it into a form that is valid Lua." (cond [(= name "") "_e"] ;; Keywords are trivial to escape [(.> keywords name) (.. "_e" name)] ;; Syntactically valid Lua variables. We exclude _ as they mess with "symbol" quoting. [(string/find name "^%a%w*$") name] [true (let* [(out (if (-> name (string/char-at <> 1) (string/find <> "%d")) "_e" "")) (upper false) (esc false)] (for i 1 (n name) 1 (with (char (string/char-at name i)) (cond [(and (= char "-") (ident? (string/char-at name (pred i))) (ident? (string/char-at name (succ i)))) ;; If we're surrounded by ident characters then convert the next one to upper case (set! upper true)] [(string/find char "[^%w%d]") (set! char (-> char (string/byte <>) (string/format "%02x" <>))) (set! upper false) (unless esc (set! esc true) (set! out (.. out "_"))) (set! out (.. out char))] [true (when esc (set! esc false) (set! out (.. out "_"))) (when upper (set! upper false) (set! char (string/upper char))) (set! out (.. out char))]))) (when esc (set! out (.. out "_"))) out)])) (defun push-escape-var! (var state force-num) "Push an escaped form of variable VAR. This should be called when it is defined. If FORCE-NUM is given then the variable will always be mangled with a number." (or (.> state :var-lookup var) (let* [(esc (escape (or (scope/var-display-name var) (scope/var-name var)))) (existing (.> state :var-cache esc))] (when (or force-num existing) (let* [(ctr 1) (finding true)] (while finding (let* [(esc' (.. esc ctr)) (existing (.> state :var-cache esc'))] (if existing (inc! ctr) (progn (set! finding false) (set! esc esc'))))))) (.<! state :var-cache esc true) (.<! state :var-lookup var esc) esc))) (defun pop-escape-var! (var state) "Remove an escaped form of variable VAR." (with (esc (.> state :var-lookup var)) (unless esc (fail! (.. (scope/var-name var) " has not been escaped (when popping)."))) (.<! state :var-cache esc nil) (.<! state :var-lookup var nil))) (defun rename-escape-var! (from to state) "Pop the definition of FROM and use it to define TO." (with (esc (.> state :var-lookup from)) (unless esc (fail! (.. (scope/var-name from) " has not been escaped (when renaming)."))) (when (.> state :var-lookup to) (fail! (.. (scope/var-name to) " already has a name (when renaming)."))) (.<! state :var-lookup from nil) (.<! state :var-lookup to esc))) (defun escape-var (var state) "Escape a variable VAR, which has already been escaped." (if (builtin-var? var) (scope/var-name var) (with (esc (.> state :var-lookup var)) (unless esc (format 1 "{:id} has not been escaped (at {:id})" (scope/var-name var) (if (scope/var-node var) (format/format-node (scope/var-node var)) "?"))) esc)))
null
https://raw.githubusercontent.com/SquidDev/urn/6e6717cf1376b0950e569e3771cb7e287aed291d/urn/backend/lua/escape.lisp
lisp
Keywords are trivial to escape Syntactically valid Lua variables. We exclude _ as they mess with "symbol" quoting. If we're surrounded by ident characters then convert the next one to upper case
(import urn/logger/format format) (import urn/resolve/builtins (builtin builtin-var?)) (import urn/resolve/scope scope) (define keywords "A set of all builtin Lua variables" :hidden (create-lookup '("and" "break" "do" "else" "elseif" "end" "false" "for" "function" "if" "in" "local" "nil" "not" "or" "repeat" "return" "then" "true" "until" "while"))) (defun lua-ident? (ident) "Determines if the given IDENT is a valid Lua identifier." (and (string/match ident "^[%a_][%w_]*$") (= (.> keywords ident) nil))) (defun ident? (x) "Determine whether X is a usable identifier character" :hidden (string/find x "[%a%d']")) (defun escape (name) "Escape an urn identifier NANE, converting it into a form that is valid Lua." (cond [(= name "") "_e"] [(.> keywords name) (.. "_e" name)] [(string/find name "^%a%w*$") name] [true (let* [(out (if (-> name (string/char-at <> 1) (string/find <> "%d")) "_e" "")) (upper false) (esc false)] (for i 1 (n name) 1 (with (char (string/char-at name i)) (cond [(and (= char "-") (ident? (string/char-at name (pred i))) (ident? (string/char-at name (succ i)))) (set! upper true)] [(string/find char "[^%w%d]") (set! char (-> char (string/byte <>) (string/format "%02x" <>))) (set! upper false) (unless esc (set! esc true) (set! out (.. out "_"))) (set! out (.. out char))] [true (when esc (set! esc false) (set! out (.. out "_"))) (when upper (set! upper false) (set! char (string/upper char))) (set! out (.. out char))]))) (when esc (set! out (.. out "_"))) out)])) (defun push-escape-var! (var state force-num) "Push an escaped form of variable VAR. This should be called when it is defined. If FORCE-NUM is given then the variable will always be mangled with a number." (or (.> state :var-lookup var) (let* [(esc (escape (or (scope/var-display-name var) (scope/var-name var)))) (existing (.> state :var-cache esc))] (when (or force-num existing) (let* [(ctr 1) (finding true)] (while finding (let* [(esc' (.. esc ctr)) (existing (.> state :var-cache esc'))] (if existing (inc! ctr) (progn (set! finding false) (set! esc esc'))))))) (.<! state :var-cache esc true) (.<! state :var-lookup var esc) esc))) (defun pop-escape-var! (var state) "Remove an escaped form of variable VAR." (with (esc (.> state :var-lookup var)) (unless esc (fail! (.. (scope/var-name var) " has not been escaped (when popping)."))) (.<! state :var-cache esc nil) (.<! state :var-lookup var nil))) (defun rename-escape-var! (from to state) "Pop the definition of FROM and use it to define TO." (with (esc (.> state :var-lookup from)) (unless esc (fail! (.. (scope/var-name from) " has not been escaped (when renaming)."))) (when (.> state :var-lookup to) (fail! (.. (scope/var-name to) " already has a name (when renaming)."))) (.<! state :var-lookup from nil) (.<! state :var-lookup to esc))) (defun escape-var (var state) "Escape a variable VAR, which has already been escaped." (if (builtin-var? var) (scope/var-name var) (with (esc (.> state :var-lookup var)) (unless esc (format 1 "{:id} has not been escaped (at {:id})" (scope/var-name var) (if (scope/var-node var) (format/format-node (scope/var-node var)) "?"))) esc)))
b6cdb50db28d8a8dc9cd129869ce0ab7cbeea6205555d11c149205fadf89a545
zotonic/zotonic
m_identity_tests.erl
@author < > %% @hidden -module(m_identity_tests). -include_lib("eunit/include/eunit.hrl"). -include_lib("zotonic.hrl"). hash_test() -> ?assertMatch({bcrypt, <<"$2a$12$", _/binary>>}, m_identity:hash("1234")), ?assertMatch({bcrypt, <<"$2a$12$", _/binary>>}, m_identity:hash(<<"1234">>)), ?assertMatch({bcrypt, <<"$2a$12$", _/binary>>}, m_identity:hash(<<195, 154, 105, 105>>)), ok. needs_rehash_test() -> ?assertEqual(true, m_identity:needs_rehash(old_hash("password"))), ?assertEqual(false, m_identity:needs_rehash(m_identity:hash("password"))), ok. hash_is_equal_test() -> PasswordHash = m_identity:hash("password"), ?assert(m_identity:hash_is_equal("password", PasswordHash)), ?assert(not m_identity:hash_is_equal("1234", PasswordHash)), ok. hash_is_equal_old_hash_test() -> PasswordHash = old_hash("password"), % Validating stored old password hashes should still work. ?assert(m_identity:hash_is_equal("password", PasswordHash)), ?assert(not m_identity:hash_is_equal("1234", PasswordHash)), ok. check_password_no_user_test_() -> {timeout, 20, fun() -> check_password_no_user() end}. check_password_no_user() -> ok = z_sites_manager:await_startup(zotonic_site_testsandbox), C = z_context:new(zotonic_site_testsandbox), AdminC = z_acl:logon(?ACL_ADMIN_USER_ID, C), ok = delete_user("mr_z", AdminC), ?assertEqual({error, nouser}, m_identity:check_username_pw("mr_z", "does-not-exist", C)), ok. check_username_password_test_() -> {timeout, 20, fun() -> check_username_password() end}. check_username_password() -> ok = z_sites_manager:await_startup(zotonic_site_testsandbox), C = z_context:new(zotonic_site_testsandbox), start_modules(C), AdminC = z_acl:logon(?ACL_ADMIN_USER_ID, C), MrYId = ensure_new_user("mr_y", "secret", AdminC), ?assertEqual({ok, MrYId}, m_identity:check_username_pw("mr_y", "secret", C)), ?assertEqual({error, password}, m_identity:check_username_pw("mr_y", "wrong-secret", C)), %% Make sure stored hashes don't need to be upgraded. {MrYId, Hash} = z_db:q_row("select rsc_id, propb from identity where type = 'username_pw' and key = $1", ["mr_y"], C), ?assert(not m_identity:needs_rehash(Hash)), %% update the hash value in the database and set the old hash algorithm. OldHash = old_hash("secret"), z_db:q("update identity set propb = $2 where type = 'username_pw' and key = $1", ["mr_y", {term, OldHash}], C), {MrYId, CurrentHash} = z_db:q_row( "select rsc_id, propb from identity where type = 'username_pw' and key = $1", ["mr_y"], C), ?assert(m_identity:needs_rehash(CurrentHash)), %% Logging in with the wrong password still does not work. ?assertEqual({error, password}, m_identity:check_username_pw("mr_y", "wrong-secret", C)), %% And with the correct password you can login. ?assertEqual({ok, MrYId}, m_identity:check_username_pw("mr_y", "secret", C)), %% But now hash of the user has been replaced with one which does not need a rehash {MrYId, NewHash} = z_db:q_row( "select rsc_id, propb from identity where type = 'username_pw' and key = $1", ["mr_y"], C), ?assert(not m_identity:needs_rehash(NewHash)), %% And afterwards the user can still logon ?assertEqual({error, password}, m_identity:check_username_pw("mr_y", "wrong-secret", C)), ?assertEqual({ok, MrYId}, m_identity:check_username_pw("mr_y", "secret", C)), ok. start_modules(Context) -> ok = z_module_manager:activate_await(mod_acl_mock, Context), ok = z_module_manager:activate_await(mod_authentication, Context), ok = z_module_manager:activate_await(mod_admin, Context), ok = z_module_manager:activate_await(mod_admin_identity, Context), ok = z_module_manager:upgrade_await(Context). %% Old hash algorithm copied from m_identity before the change to bcrypt. old_hash(Pw) -> Salt = z_ids:id(10), Hash = crypto:hash(sha, [Salt, Pw]), {hash, Salt, Hash}. ensure_new_user(Name, Password, Context) -> z_db:transaction(fun(Ctx) -> ok = delete_user(Name, Ctx), PersonId = m_rsc:rid(person, Ctx), {ok, Id} = m_rsc:insert([{title, Name}, {category_id, PersonId}], Ctx), ok = m_identity:set_username_pw(Id, Name, Password, Ctx), Id end, Context). delete_user(Name, Context) -> case m_identity:lookup_by_username(Name, Context) of undefined -> ok; Props -> {rsc_id, Id} = proplists:lookup(rsc_id, Props), m_rsc:delete(Id, Context) end.
null
https://raw.githubusercontent.com/zotonic/zotonic/ad2759e8d5f0f4b7c7caabce3acaac628ea2cae7/apps/zotonic_core/test/m_identity_tests.erl
erlang
@hidden Validating stored old password hashes should still work. Make sure stored hashes don't need to be upgraded. update the hash value in the database and set the old hash algorithm. Logging in with the wrong password still does not work. And with the correct password you can login. But now hash of the user has been replaced with one which does not need a rehash And afterwards the user can still logon Old hash algorithm copied from m_identity before the change to bcrypt.
@author < > -module(m_identity_tests). -include_lib("eunit/include/eunit.hrl"). -include_lib("zotonic.hrl"). hash_test() -> ?assertMatch({bcrypt, <<"$2a$12$", _/binary>>}, m_identity:hash("1234")), ?assertMatch({bcrypt, <<"$2a$12$", _/binary>>}, m_identity:hash(<<"1234">>)), ?assertMatch({bcrypt, <<"$2a$12$", _/binary>>}, m_identity:hash(<<195, 154, 105, 105>>)), ok. needs_rehash_test() -> ?assertEqual(true, m_identity:needs_rehash(old_hash("password"))), ?assertEqual(false, m_identity:needs_rehash(m_identity:hash("password"))), ok. hash_is_equal_test() -> PasswordHash = m_identity:hash("password"), ?assert(m_identity:hash_is_equal("password", PasswordHash)), ?assert(not m_identity:hash_is_equal("1234", PasswordHash)), ok. hash_is_equal_old_hash_test() -> PasswordHash = old_hash("password"), ?assert(m_identity:hash_is_equal("password", PasswordHash)), ?assert(not m_identity:hash_is_equal("1234", PasswordHash)), ok. check_password_no_user_test_() -> {timeout, 20, fun() -> check_password_no_user() end}. check_password_no_user() -> ok = z_sites_manager:await_startup(zotonic_site_testsandbox), C = z_context:new(zotonic_site_testsandbox), AdminC = z_acl:logon(?ACL_ADMIN_USER_ID, C), ok = delete_user("mr_z", AdminC), ?assertEqual({error, nouser}, m_identity:check_username_pw("mr_z", "does-not-exist", C)), ok. check_username_password_test_() -> {timeout, 20, fun() -> check_username_password() end}. check_username_password() -> ok = z_sites_manager:await_startup(zotonic_site_testsandbox), C = z_context:new(zotonic_site_testsandbox), start_modules(C), AdminC = z_acl:logon(?ACL_ADMIN_USER_ID, C), MrYId = ensure_new_user("mr_y", "secret", AdminC), ?assertEqual({ok, MrYId}, m_identity:check_username_pw("mr_y", "secret", C)), ?assertEqual({error, password}, m_identity:check_username_pw("mr_y", "wrong-secret", C)), {MrYId, Hash} = z_db:q_row("select rsc_id, propb from identity where type = 'username_pw' and key = $1", ["mr_y"], C), ?assert(not m_identity:needs_rehash(Hash)), OldHash = old_hash("secret"), z_db:q("update identity set propb = $2 where type = 'username_pw' and key = $1", ["mr_y", {term, OldHash}], C), {MrYId, CurrentHash} = z_db:q_row( "select rsc_id, propb from identity where type = 'username_pw' and key = $1", ["mr_y"], C), ?assert(m_identity:needs_rehash(CurrentHash)), ?assertEqual({error, password}, m_identity:check_username_pw("mr_y", "wrong-secret", C)), ?assertEqual({ok, MrYId}, m_identity:check_username_pw("mr_y", "secret", C)), {MrYId, NewHash} = z_db:q_row( "select rsc_id, propb from identity where type = 'username_pw' and key = $1", ["mr_y"], C), ?assert(not m_identity:needs_rehash(NewHash)), ?assertEqual({error, password}, m_identity:check_username_pw("mr_y", "wrong-secret", C)), ?assertEqual({ok, MrYId}, m_identity:check_username_pw("mr_y", "secret", C)), ok. start_modules(Context) -> ok = z_module_manager:activate_await(mod_acl_mock, Context), ok = z_module_manager:activate_await(mod_authentication, Context), ok = z_module_manager:activate_await(mod_admin, Context), ok = z_module_manager:activate_await(mod_admin_identity, Context), ok = z_module_manager:upgrade_await(Context). old_hash(Pw) -> Salt = z_ids:id(10), Hash = crypto:hash(sha, [Salt, Pw]), {hash, Salt, Hash}. ensure_new_user(Name, Password, Context) -> z_db:transaction(fun(Ctx) -> ok = delete_user(Name, Ctx), PersonId = m_rsc:rid(person, Ctx), {ok, Id} = m_rsc:insert([{title, Name}, {category_id, PersonId}], Ctx), ok = m_identity:set_username_pw(Id, Name, Password, Ctx), Id end, Context). delete_user(Name, Context) -> case m_identity:lookup_by_username(Name, Context) of undefined -> ok; Props -> {rsc_id, Id} = proplists:lookup(rsc_id, Props), m_rsc:delete(Id, Context) end.
8646db96034e3b9861e7d89fb98798de06469db57294952b512ecf7399961947
zkat/sheeple
messages.lisp
-*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Base : 10 ; indent - tabs - mode : nil -*- ;;;; This file is part of Sheeple messages.lisp ;;;; Message , message definition and management ;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :sheeple) (defstruct (arg-info (:constructor make-arg-info ())) (lambda-list nil :type list) (number-required 0 :type fixnum) (number-optional 0 :type fixnum) (key/rest-p nil :type boolean) (keys nil :type list)) (defstruct (%message (:predicate %messagep)) name message (function #'identity :type function) (erfun-cache (make-hash-table :test #'equal)) (replies nil :type list) (arg-info (make-arg-info) :type arg-info)) ;;; ;;; Funcallable Messages! ;;; (defvar *funcallable-messages* (make-weak-hash-table :test #'eq :weakness :key)) (defun allocate-message () (let ((%message (make-%message))) (aprog1 (lambda (&rest args) (declare (dynamic-extent args) (optimize speed (safety 0))) (apply (%message-function %message) args)) (setf (gethash it *funcallable-messages*) %message (%message-message %message) it)))) (defun %make-message (name lambda-list) (aprog1 (allocate-message) (setf (message-name it) name (arg-info-lambda-list (message-arg-info it)) lambda-list))) (macrolet ((with-%message ((name message) &body body) (with-gensyms (foundp) `(multiple-value-bind (,name ,foundp) (gethash ,message *funcallable-messages*) (if ,foundp (progn ,@body) ;; Note the multiple evaluation of ,message (error 'type-error :datum ,message :expected-type 'message)))))) (macrolet ((define-message-accessor (slot) (let ((%message-accessor (symbolicate '#:%message- slot)) (message-accessor (symbolicate '#:message- slot))) `(progn (defun ,message-accessor (message) (with-%message (%message message) (,%message-accessor %message))) (defun (setf ,message-accessor) (new-value message) (with-%message (%message message) (setf (,%message-accessor %message) new-value))))))) (define-message-accessor name) (define-message-accessor function) (define-message-accessor erfun-cache) (define-message-accessor replies) (define-message-accessor arg-info))) (defun message-lambda-list (message) (arg-info-lambda-list (message-arg-info message))) (defun messagep (x) (nth-value 1 (gethash x *funcallable-messages*))) (deftype message () ;; FIXME: Now would be a nice time to chat about what a message is '(satisfies messagep)) (defun pprint-message (stream message) (print-unreadable-object (message stream :identity t) (format stream "MESSAGE ~S" (message-name message)))) #+:ccl #-:ccl-1.9 Work around a bug in certain Clozure CL versions where * PRINT - PPRINT - DISPATCH * is NIL by default , which upsets SET - PPRINT - DISPATCH . ;; Ticket reference : (when (null *print-pprint-dispatch*) (setq *print-pprint-dispatch* (copy-pprint-dispatch nil))) (set-pprint-dispatch 'message #'pprint-message) (define-print-object ((%message %message) :type nil) (format t "Internal data for ~S" (%message-message %message))) ;;; Erfun Cache ;;; (defun cached-erfun (message replies) (gethash replies (message-erfun-cache message))) (defun (setf cached-erfun) (new-erfun message replies) (setf (gethash replies (message-erfun-cache message)) new-erfun)) (defun flush-erfun-cache (message) (clrhash (message-erfun-cache message))) ;;; ;;; Arg info ;;; This code ensures that Sheeple follows a simplified form of CLHS 7.6.4 ;;; A lot of duplicated code here... FIXME! (defun check-reply-arg-info (message reply) (multiple-value-bind (nreq nopt keysp restp) (analyze-lambda-list (reply-lambda-list reply)) (flet ((lose (string &rest args) (error 'reply-argument-conflict :reply reply :message message :reason (apply 'format nil string args))) (comparison-description (x y) (if (> x y) "more" "fewer"))) (with-accessors ((msg-nreq arg-info-number-required) (msg-nopt arg-info-number-optional) (msg-key/rest-p arg-info-key/rest-p)) (message-arg-info message) (cond ((not (= nreq msg-nreq)) (lose "the reply has ~A required arguments than the message." (comparison-description nreq msg-nreq))) ((not (= nopt msg-nopt)) (lose "the reply has ~A optional arguments than the message." (comparison-description nopt msg-nopt))) ((not (eq (or keysp restp) msg-key/rest-p)) (lose "the reply and message differ in whether they accept &REST or &KEY arguments.")) (t (values))))))) (defun set-arg-info (message lambda-list) (multiple-value-bind (nreq nopt keysp restp) (analyze-lambda-list lambda-list) (with-accessors ((msg-nreq arg-info-number-required) (msg-nopt arg-info-number-optional) (msg-kr-p arg-info-key/rest-p)) (message-arg-info message) (setf msg-nreq nreq msg-nopt nopt msg-kr-p (or keysp restp)))) (values)) (defun update-arg-info (message lambda-list) (multiple-value-bind (new-nreq new-nopt new-keysp new-restp) (analyze-lambda-list lambda-list) (let ((new-key/rest-p (or new-keysp new-restp)) remove-conflicts) (dolist (reply (message-replies message)) (multiple-value-bind (reply-nreq reply-nopt reply-keysp reply-restp) (analyze-lambda-list (reply-lambda-list reply)) (unless (and (= new-nreq reply-nreq) (= new-nopt reply-nopt) (eq new-key/rest-p (or reply-keysp reply-restp))) (unless remove-conflicts (restart-case (cerror "Remove this reply from the message." "~@<The message ~2I~_~S~I~_cannot be updated to have lambda-list ~2I~_~S~ ~I~_because it conflicts with reply ~2I~_~S.~:>" message lambda-list reply) (remove-all () :report "Remove all conflicting replies from the message." (setf remove-conflicts t)))) (delete-reply reply)))) (with-accessors ((msg-nreq arg-info-number-required) (msg-nopt arg-info-number-optional) (msg-ll arg-info-lambda-list) (msg-kr-p arg-info-key/rest-p)) (message-arg-info message) (setf msg-ll lambda-list msg-nreq new-nreq msg-nopt new-nopt msg-kr-p new-key/rest-p)))) (values)) (defun required-portion (message args) (let ((nreq (arg-info-number-required (message-arg-info message)))) (error-when (< (length args) nreq) insufficient-message-args :message message) (subseq args 0 nreq))) ;; The defmessage macro basically expands to a call to this function (after processing ;; its args, checking lamda-list, etc.) (defun ensure-message (name &rest all-keys &key lambda-list &allow-other-keys) (awhen-prog1 (safe-fdefinition name) (when (messagep it) (update-arg-info it lambda-list) (return-from ensure-message it)) (cerror "Replace definition." 'clobbering-function-definition :function name)) (record-message-source name) (record-message-arglist name lambda-list) (setf (fdefinition name) (apply 'make-message :name name :lambda-list lambda-list all-keys))) ;; This handles actual setup of the message object (and finalization) (defun make-message (&key name lambda-list documentation) (aprog1 (%make-message name lambda-list) (set-arg-info it lambda-list) (finalize-message it) (setf (documentation it t) documentation))) ;; Finalizing a message sets the function definition of the message to a ;; lambda that calls the top-level dispatch function on the message args. (defun finalize-message (message) (setf (message-function message) (std-compute-discriminating-function message)) (flush-erfun-cache message) (values)) ;;; ;;; Message definition (finally!) ;;; (defun parse-defmessage (name lambda-list options-and-replies) (check-message-lambda-list lambda-list) (let (replies options) (dolist (option options-and-replies) Choke on unsupported types (:reply (push `(defreply ,name ,@(cdr option)) replies)) (:documentation (push option options)))) (values replies options))) (defmacro defmessage (name lambda-list &rest options &environment env) (multiple-value-bind (replies options) (parse-defmessage name lambda-list options) `(progn (eval-when (:compile-toplevel) ,(record-message-compilation name lambda-list env)) (aprog1 (ensure-message ',name :lambda-list ',lambda-list ,@(canonize-message-options options)) ,.replies)))) (defun canonize-message-option (option) `(,(car option) ,(cadr option))) (defun canonize-message-options (options) (mapcan 'canonize-message-option options)) (defmacro undefmessage (name) `(fmakunbound ',name))
null
https://raw.githubusercontent.com/zkat/sheeple/5393c74737ccf22c3fd5f390076b75c38453cb04/src/messages.lisp
lisp
Syntax : ANSI - Common - Lisp ; Base : 10 ; indent - tabs - mode : nil -*- This file is part of Sheeple Funcallable Messages! Note the multiple evaluation of ,message FIXME: Now would be a nice time to chat about what a message is Arg info A lot of duplicated code here... FIXME! The defmessage macro basically expands to a call to this function (after processing its args, checking lamda-list, etc.) This handles actual setup of the message object (and finalization) Finalizing a message sets the function definition of the message to a lambda that calls the top-level dispatch function on the message args. Message definition (finally!)
messages.lisp Message , message definition and management (in-package :sheeple) (defstruct (arg-info (:constructor make-arg-info ())) (lambda-list nil :type list) (number-required 0 :type fixnum) (number-optional 0 :type fixnum) (key/rest-p nil :type boolean) (keys nil :type list)) (defstruct (%message (:predicate %messagep)) name message (function #'identity :type function) (erfun-cache (make-hash-table :test #'equal)) (replies nil :type list) (arg-info (make-arg-info) :type arg-info)) (defvar *funcallable-messages* (make-weak-hash-table :test #'eq :weakness :key)) (defun allocate-message () (let ((%message (make-%message))) (aprog1 (lambda (&rest args) (declare (dynamic-extent args) (optimize speed (safety 0))) (apply (%message-function %message) args)) (setf (gethash it *funcallable-messages*) %message (%message-message %message) it)))) (defun %make-message (name lambda-list) (aprog1 (allocate-message) (setf (message-name it) name (arg-info-lambda-list (message-arg-info it)) lambda-list))) (macrolet ((with-%message ((name message) &body body) (with-gensyms (foundp) `(multiple-value-bind (,name ,foundp) (gethash ,message *funcallable-messages*) (if ,foundp (progn ,@body) (error 'type-error :datum ,message :expected-type 'message)))))) (macrolet ((define-message-accessor (slot) (let ((%message-accessor (symbolicate '#:%message- slot)) (message-accessor (symbolicate '#:message- slot))) `(progn (defun ,message-accessor (message) (with-%message (%message message) (,%message-accessor %message))) (defun (setf ,message-accessor) (new-value message) (with-%message (%message message) (setf (,%message-accessor %message) new-value))))))) (define-message-accessor name) (define-message-accessor function) (define-message-accessor erfun-cache) (define-message-accessor replies) (define-message-accessor arg-info))) (defun message-lambda-list (message) (arg-info-lambda-list (message-arg-info message))) (defun messagep (x) (nth-value 1 (gethash x *funcallable-messages*))) (deftype message () '(satisfies messagep)) (defun pprint-message (stream message) (print-unreadable-object (message stream :identity t) (format stream "MESSAGE ~S" (message-name message)))) #+:ccl #-:ccl-1.9 Work around a bug in certain Clozure CL versions where * PRINT - PPRINT - DISPATCH * is NIL by default , which upsets SET - PPRINT - DISPATCH . Ticket reference : (when (null *print-pprint-dispatch*) (setq *print-pprint-dispatch* (copy-pprint-dispatch nil))) (set-pprint-dispatch 'message #'pprint-message) (define-print-object ((%message %message) :type nil) (format t "Internal data for ~S" (%message-message %message))) Erfun Cache (defun cached-erfun (message replies) (gethash replies (message-erfun-cache message))) (defun (setf cached-erfun) (new-erfun message replies) (setf (gethash replies (message-erfun-cache message)) new-erfun)) (defun flush-erfun-cache (message) (clrhash (message-erfun-cache message))) This code ensures that Sheeple follows a simplified form of CLHS 7.6.4 (defun check-reply-arg-info (message reply) (multiple-value-bind (nreq nopt keysp restp) (analyze-lambda-list (reply-lambda-list reply)) (flet ((lose (string &rest args) (error 'reply-argument-conflict :reply reply :message message :reason (apply 'format nil string args))) (comparison-description (x y) (if (> x y) "more" "fewer"))) (with-accessors ((msg-nreq arg-info-number-required) (msg-nopt arg-info-number-optional) (msg-key/rest-p arg-info-key/rest-p)) (message-arg-info message) (cond ((not (= nreq msg-nreq)) (lose "the reply has ~A required arguments than the message." (comparison-description nreq msg-nreq))) ((not (= nopt msg-nopt)) (lose "the reply has ~A optional arguments than the message." (comparison-description nopt msg-nopt))) ((not (eq (or keysp restp) msg-key/rest-p)) (lose "the reply and message differ in whether they accept &REST or &KEY arguments.")) (t (values))))))) (defun set-arg-info (message lambda-list) (multiple-value-bind (nreq nopt keysp restp) (analyze-lambda-list lambda-list) (with-accessors ((msg-nreq arg-info-number-required) (msg-nopt arg-info-number-optional) (msg-kr-p arg-info-key/rest-p)) (message-arg-info message) (setf msg-nreq nreq msg-nopt nopt msg-kr-p (or keysp restp)))) (values)) (defun update-arg-info (message lambda-list) (multiple-value-bind (new-nreq new-nopt new-keysp new-restp) (analyze-lambda-list lambda-list) (let ((new-key/rest-p (or new-keysp new-restp)) remove-conflicts) (dolist (reply (message-replies message)) (multiple-value-bind (reply-nreq reply-nopt reply-keysp reply-restp) (analyze-lambda-list (reply-lambda-list reply)) (unless (and (= new-nreq reply-nreq) (= new-nopt reply-nopt) (eq new-key/rest-p (or reply-keysp reply-restp))) (unless remove-conflicts (restart-case (cerror "Remove this reply from the message." "~@<The message ~2I~_~S~I~_cannot be updated to have lambda-list ~2I~_~S~ ~I~_because it conflicts with reply ~2I~_~S.~:>" message lambda-list reply) (remove-all () :report "Remove all conflicting replies from the message." (setf remove-conflicts t)))) (delete-reply reply)))) (with-accessors ((msg-nreq arg-info-number-required) (msg-nopt arg-info-number-optional) (msg-ll arg-info-lambda-list) (msg-kr-p arg-info-key/rest-p)) (message-arg-info message) (setf msg-ll lambda-list msg-nreq new-nreq msg-nopt new-nopt msg-kr-p new-key/rest-p)))) (values)) (defun required-portion (message args) (let ((nreq (arg-info-number-required (message-arg-info message)))) (error-when (< (length args) nreq) insufficient-message-args :message message) (subseq args 0 nreq))) (defun ensure-message (name &rest all-keys &key lambda-list &allow-other-keys) (awhen-prog1 (safe-fdefinition name) (when (messagep it) (update-arg-info it lambda-list) (return-from ensure-message it)) (cerror "Replace definition." 'clobbering-function-definition :function name)) (record-message-source name) (record-message-arglist name lambda-list) (setf (fdefinition name) (apply 'make-message :name name :lambda-list lambda-list all-keys))) (defun make-message (&key name lambda-list documentation) (aprog1 (%make-message name lambda-list) (set-arg-info it lambda-list) (finalize-message it) (setf (documentation it t) documentation))) (defun finalize-message (message) (setf (message-function message) (std-compute-discriminating-function message)) (flush-erfun-cache message) (values)) (defun parse-defmessage (name lambda-list options-and-replies) (check-message-lambda-list lambda-list) (let (replies options) (dolist (option options-and-replies) Choke on unsupported types (:reply (push `(defreply ,name ,@(cdr option)) replies)) (:documentation (push option options)))) (values replies options))) (defmacro defmessage (name lambda-list &rest options &environment env) (multiple-value-bind (replies options) (parse-defmessage name lambda-list options) `(progn (eval-when (:compile-toplevel) ,(record-message-compilation name lambda-list env)) (aprog1 (ensure-message ',name :lambda-list ',lambda-list ,@(canonize-message-options options)) ,.replies)))) (defun canonize-message-option (option) `(,(car option) ,(cadr option))) (defun canonize-message-options (options) (mapcan 'canonize-message-option options)) (defmacro undefmessage (name) `(fmakunbound ',name))
c8230a2be9005757ce7298a3b41b93141cb196b81a240e181f4969b8be3c75ae
fakedata-haskell/fakedata
DrWho.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE TemplateHaskell # module Faker.Provider.DrWho where import Config import Control.Monad.IO.Class import Data.Map.Strict (Map) import Data.Monoid ((<>)) import Data.Text (Text) import Data.Vector (Vector) import Data.Yaml import Faker import Faker.Internal import Faker.Provider.TH import Language.Haskell.TH parseDrWho :: FromJSON a => FakerSettings -> Value -> Parser a parseDrWho settings (Object obj) = do en <- obj .: (getLocaleKey settings) faker <- en .: "faker" drWho <- faker .: "dr_who" pure drWho parseDrWho settings val = fail $ "expected Object, but got " <> (show val) parseDrWhoField :: (FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a parseDrWhoField settings txt val = do drWho <- parseDrWho settings val field <- drWho .:? txt .!= mempty pure field $(genParser "drWho" "character") $(genProvider "drWho" "character") $(genParser "drWho" "the_doctors") $(genProvider "drWho" "the_doctors") $(genParser "drWho" "actors") $(genProvider "drWho" "actors") $(genParser "drWho" "catch_phrases") $(genProvider "drWho" "catch_phrases") $(genParser "drWho" "quotes") $(genProvider "drWho" "quotes") $(genParser "drWho" "villains") $(genProvider "drWho" "villains") $(genParser "drWho" "species") $(genProvider "drWho" "species")
null
https://raw.githubusercontent.com/fakedata-haskell/fakedata/7b0875067386e9bb844c8b985c901c91a58842ff/src/Faker/Provider/DrWho.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE TemplateHaskell # module Faker.Provider.DrWho where import Config import Control.Monad.IO.Class import Data.Map.Strict (Map) import Data.Monoid ((<>)) import Data.Text (Text) import Data.Vector (Vector) import Data.Yaml import Faker import Faker.Internal import Faker.Provider.TH import Language.Haskell.TH parseDrWho :: FromJSON a => FakerSettings -> Value -> Parser a parseDrWho settings (Object obj) = do en <- obj .: (getLocaleKey settings) faker <- en .: "faker" drWho <- faker .: "dr_who" pure drWho parseDrWho settings val = fail $ "expected Object, but got " <> (show val) parseDrWhoField :: (FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a parseDrWhoField settings txt val = do drWho <- parseDrWho settings val field <- drWho .:? txt .!= mempty pure field $(genParser "drWho" "character") $(genProvider "drWho" "character") $(genParser "drWho" "the_doctors") $(genProvider "drWho" "the_doctors") $(genParser "drWho" "actors") $(genProvider "drWho" "actors") $(genParser "drWho" "catch_phrases") $(genProvider "drWho" "catch_phrases") $(genParser "drWho" "quotes") $(genProvider "drWho" "quotes") $(genParser "drWho" "villains") $(genProvider "drWho" "villains") $(genParser "drWho" "species") $(genProvider "drWho" "species")
04df8bd05204acf305dd1d893d70dc914951f3cef3e3d3f7a29bd41382835d71
tokenmill/docx-utils
listing.clj
(ns docx-utils.elements.listing (:require [docx-utils.constants :refer [cTAbstractNumBulletXML cTAbstractNumDecimalXML]] [docx-utils.elements.paragraph :as paragraph] [docx-utils.elements.run :refer [set-run]]) (:import (org.apache.poi.xwpf.usermodel XWPFDocument XWPFParagraph XWPFAbstractNum XWPFNumbering) (org.openxmlformats.schemas.wordprocessingml.x2006.main CTNumbering CTAbstractNum CTNumbering$Factory))) (defn bullet-list [^XWPFDocument doc ^XWPFParagraph paragraph list-data] (let [^CTNumbering cTNumbering (CTNumbering$Factory/parse cTAbstractNumBulletXML) ^CTAbstractNum cTAbstractNum (.getAbstractNumArray cTNumbering 0) ^XWPFAbstractNum abstractNum (XWPFAbstractNum. cTAbstractNum) ^XWPFNumbering numbering (.createNumbering doc) ^BigInteger abstractNumID (.addAbstractNum numbering abstractNum) ^BigInteger numID (.addNum numbering abstractNumID) highlight-colors (-> list-data (meta) :highlight-colors) bolds (-> list-data (meta) :bolds)] (doseq [[index item] (map vector (iterate inc 0) list-data)] (let [^XWPFParagraph item-paragraph (.insertNewParagraph doc (.newCursor (.getCTP paragraph)))] (.setNumID item-paragraph numID) (.setStyle item-paragraph "ListParagraph") (-> item-paragraph (.getCTP) (.getPPr) (.getNumPr) (.addNewIlvl) (.setVal (BigInteger/ZERO))) (set-run (.createRun item-paragraph) item))) (paragraph/delete-paragraph doc paragraph))) (defn numbered-list [^XWPFDocument doc ^XWPFParagraph paragraph list-data] (let [^CTNumbering cTNumbering (CTNumbering$Factory/parse cTAbstractNumDecimalXML) ^CTAbstractNum cTAbstractNum (.getAbstractNumArray cTNumbering 0) ^XWPFAbstractNum abstractNum (XWPFAbstractNum. cTAbstractNum) ^XWPFNumbering numbering (.createNumbering doc) ^BigInteger abstractNumID (.addAbstractNum numbering abstractNum) ^BigInteger numID (.addNum numbering abstractNumID) highlight-colors (-> list-data (meta) :highlight-colors) bolds (-> list-data (meta) :bolds)] (doseq [[index item] (map vector (iterate inc 0) list-data)] (let [^XWPFParagraph item-paragraph (.insertNewParagraph doc (.newCursor (.getCTP paragraph)))] (.setNumID item-paragraph numID) (.setStyle item-paragraph "ListParagraph") (-> item-paragraph (.getCTP) (.getPPr) (.getNumPr) (.addNewIlvl) (.setVal (BigInteger/ZERO))) (set-run (.createRun item-paragraph) item))) (paragraph/delete-paragraph doc paragraph)))
null
https://raw.githubusercontent.com/tokenmill/docx-utils/f9cb077df2360c11376e0f2d9c8daf8b5062179a/src/docx_utils/elements/listing.clj
clojure
(ns docx-utils.elements.listing (:require [docx-utils.constants :refer [cTAbstractNumBulletXML cTAbstractNumDecimalXML]] [docx-utils.elements.paragraph :as paragraph] [docx-utils.elements.run :refer [set-run]]) (:import (org.apache.poi.xwpf.usermodel XWPFDocument XWPFParagraph XWPFAbstractNum XWPFNumbering) (org.openxmlformats.schemas.wordprocessingml.x2006.main CTNumbering CTAbstractNum CTNumbering$Factory))) (defn bullet-list [^XWPFDocument doc ^XWPFParagraph paragraph list-data] (let [^CTNumbering cTNumbering (CTNumbering$Factory/parse cTAbstractNumBulletXML) ^CTAbstractNum cTAbstractNum (.getAbstractNumArray cTNumbering 0) ^XWPFAbstractNum abstractNum (XWPFAbstractNum. cTAbstractNum) ^XWPFNumbering numbering (.createNumbering doc) ^BigInteger abstractNumID (.addAbstractNum numbering abstractNum) ^BigInteger numID (.addNum numbering abstractNumID) highlight-colors (-> list-data (meta) :highlight-colors) bolds (-> list-data (meta) :bolds)] (doseq [[index item] (map vector (iterate inc 0) list-data)] (let [^XWPFParagraph item-paragraph (.insertNewParagraph doc (.newCursor (.getCTP paragraph)))] (.setNumID item-paragraph numID) (.setStyle item-paragraph "ListParagraph") (-> item-paragraph (.getCTP) (.getPPr) (.getNumPr) (.addNewIlvl) (.setVal (BigInteger/ZERO))) (set-run (.createRun item-paragraph) item))) (paragraph/delete-paragraph doc paragraph))) (defn numbered-list [^XWPFDocument doc ^XWPFParagraph paragraph list-data] (let [^CTNumbering cTNumbering (CTNumbering$Factory/parse cTAbstractNumDecimalXML) ^CTAbstractNum cTAbstractNum (.getAbstractNumArray cTNumbering 0) ^XWPFAbstractNum abstractNum (XWPFAbstractNum. cTAbstractNum) ^XWPFNumbering numbering (.createNumbering doc) ^BigInteger abstractNumID (.addAbstractNum numbering abstractNum) ^BigInteger numID (.addNum numbering abstractNumID) highlight-colors (-> list-data (meta) :highlight-colors) bolds (-> list-data (meta) :bolds)] (doseq [[index item] (map vector (iterate inc 0) list-data)] (let [^XWPFParagraph item-paragraph (.insertNewParagraph doc (.newCursor (.getCTP paragraph)))] (.setNumID item-paragraph numID) (.setStyle item-paragraph "ListParagraph") (-> item-paragraph (.getCTP) (.getPPr) (.getNumPr) (.addNewIlvl) (.setVal (BigInteger/ZERO))) (set-run (.createRun item-paragraph) item))) (paragraph/delete-paragraph doc paragraph)))
e2b8367f1200cea02a252e8b3503310495caf70d1bf7aebdfde5009872febbc0
bjpop/blip
Main.hs
----------------------------------------------------------------------------- -- | -- Module : Main Copyright : ( c ) 2012 , 2013 -- License : BSD-style -- Maintainer : -- Stability : experimental Portability : ghc -- The Main module of Blip . Contains the entry point of the compiler and -- the interpreter and handles command line argument parsing. -- ----------------------------------------------------------------------------- module Main where import System.Exit (exitSuccess) import Control.Exception (try) import Control.Monad (when, unless) import System.Console.ParseArgs ( Argtype (..), argDataOptional, Arg (..) , gotArg, getArg, parseArgsIO, ArgsComplete (..), Args(..)) import ProgName (progName) import Data.Set as Set (Set, empty, singleton, union) import System.FilePath (splitExtension) import Blip.Version (versionString) import Blip.Compiler.Types (Dumpable (..), CompileConfig (..)) import Blip.Compiler.Compile (compileFile, writePycFile) import Blip.Interpreter.Interpret (interpretFile) import Repl (repl) argDescriptions :: [Arg ArgIndex] argDescriptions = [ version, help, magicNumberArg , dumpScopeArg, dumpASTArg, compileOnly, inputFile ] main :: IO () main = do args <- parseArgsIO ArgsComplete argDescriptions when (gotArg args Help) $ do putStrLn $ argsUsage args exitSuccess when (gotArg args Version) $ do putStrLn $ progName ++ " version " ++ versionString exitSuccess when (gotArg args InputFile) $ do case getArg args InputFile of Nothing -> repl Just filename -> do let (prefix, suffix) = splitExtension filename if suffix == ".pyc" then do interpretFile filename exitSuccess else do let magicNumber = getMagicNumber args dumps = getDumps args config = initCompileConfig { compileConfig_magic = fromIntegral magicNumber , compileConfig_dumps = dumps } compileAndWritePyc config filename unless (gotArg args CompileOnly) $ interpretFile $ prefix ++ ".pyc" exitSuccess repl compileAndWritePyc :: CompileConfig -> FilePath -> IO () compileAndWritePyc config path = handleIOErrors $ do pyc <- compileFile config path writePycFile pyc path handleIOErrors :: IO () -> IO () handleIOErrors comp = do r <- try comp case r of -- XXX maybe we want more customised error messages for different kinds of IOErrors ? Left e -> putStrLn $ progName ++ ": " ++ show (e :: IOError) Right () -> return () data ArgIndex = Help | InputFile | Version | MagicNumber | Dump Dumpable | CompileOnly deriving (Eq, Ord, Show) help :: Arg ArgIndex help = Arg { argIndex = Help , argAbbr = Just 'h' , argName = Just "help" , argData = Nothing , argDesc = "Display a help message." } compileOnly :: Arg ArgIndex compileOnly = Arg { argIndex = CompileOnly , argAbbr = Just 'c' , argName = Just "compile" , argData = Nothing , argDesc = "Compile .py to .pyc but do not run the program." } inputFile :: Arg ArgIndex inputFile = Arg { argIndex = InputFile , argAbbr = Nothing , argName = Nothing , argData = argDataOptional "input file" ArgtypeString , argDesc = "Name of the input Python file, either .py or .pyc" } version :: Arg ArgIndex version = Arg { argIndex = Version , argAbbr = Nothing , argName = Just "version" , argData = Nothing , argDesc = "Show the version number of " ++ progName ++ "." } this works for CPython 3.8.2 see get_python_magic_number / get_python_magic_number.py defaultMagicNumber :: Int defaultMagicNumber = 168627541 magicNumberArg :: Arg ArgIndex magicNumberArg = Arg { argIndex = MagicNumber , argAbbr = Nothing , argName = Just "magic" , argData = argDataOptional "magic number" ArgtypeInt , argDesc = "Magic number to include in pyc file header." } dumpScopeArg :: Arg ArgIndex dumpScopeArg = Arg { argIndex = Dump DumpScope , argAbbr = Nothing , argName = Just "dumpScope" , argData = Nothing , argDesc = "Dump the variable scope." } dumpASTArg :: Arg ArgIndex dumpASTArg = Arg { argIndex = Dump DumpAST , argAbbr = Nothing , argName = Just "dumpAST" , argData = Nothing , argDesc = "Dump the abstract syntax tree." } getInputFile :: Args ArgIndex -> Maybe FilePath getInputFile args = getArg args InputFile getMagicNumber :: Args ArgIndex -> Int getMagicNumber args = maybe defaultMagicNumber id $ getArg args MagicNumber getDumps :: Args ArgIndex -> Set.Set Dumpable getDumps args = getDump DumpScope args `Set.union` getDump DumpAST args where getDump :: Dumpable -> Args ArgIndex -> Set.Set Dumpable getDump dumpable args | gotArg args (Dump dumpable) = Set.singleton dumpable | otherwise = Set.empty initCompileConfig :: CompileConfig initCompileConfig = CompileConfig { compileConfig_magic = 0, compileConfig_dumps = Set.empty }
null
https://raw.githubusercontent.com/bjpop/blip/3d9105a44d1afb7bd007da3742fb19dc69372e10/blip/src/Main.hs
haskell
--------------------------------------------------------------------------- | Module : Main License : BSD-style Maintainer : Stability : experimental the interpreter and handles command line argument parsing. --------------------------------------------------------------------------- XXX maybe we want more customised error messages for different kinds of
Copyright : ( c ) 2012 , 2013 Portability : ghc The Main module of Blip . Contains the entry point of the compiler and module Main where import System.Exit (exitSuccess) import Control.Exception (try) import Control.Monad (when, unless) import System.Console.ParseArgs ( Argtype (..), argDataOptional, Arg (..) , gotArg, getArg, parseArgsIO, ArgsComplete (..), Args(..)) import ProgName (progName) import Data.Set as Set (Set, empty, singleton, union) import System.FilePath (splitExtension) import Blip.Version (versionString) import Blip.Compiler.Types (Dumpable (..), CompileConfig (..)) import Blip.Compiler.Compile (compileFile, writePycFile) import Blip.Interpreter.Interpret (interpretFile) import Repl (repl) argDescriptions :: [Arg ArgIndex] argDescriptions = [ version, help, magicNumberArg , dumpScopeArg, dumpASTArg, compileOnly, inputFile ] main :: IO () main = do args <- parseArgsIO ArgsComplete argDescriptions when (gotArg args Help) $ do putStrLn $ argsUsage args exitSuccess when (gotArg args Version) $ do putStrLn $ progName ++ " version " ++ versionString exitSuccess when (gotArg args InputFile) $ do case getArg args InputFile of Nothing -> repl Just filename -> do let (prefix, suffix) = splitExtension filename if suffix == ".pyc" then do interpretFile filename exitSuccess else do let magicNumber = getMagicNumber args dumps = getDumps args config = initCompileConfig { compileConfig_magic = fromIntegral magicNumber , compileConfig_dumps = dumps } compileAndWritePyc config filename unless (gotArg args CompileOnly) $ interpretFile $ prefix ++ ".pyc" exitSuccess repl compileAndWritePyc :: CompileConfig -> FilePath -> IO () compileAndWritePyc config path = handleIOErrors $ do pyc <- compileFile config path writePycFile pyc path handleIOErrors :: IO () -> IO () handleIOErrors comp = do r <- try comp case r of IOErrors ? Left e -> putStrLn $ progName ++ ": " ++ show (e :: IOError) Right () -> return () data ArgIndex = Help | InputFile | Version | MagicNumber | Dump Dumpable | CompileOnly deriving (Eq, Ord, Show) help :: Arg ArgIndex help = Arg { argIndex = Help , argAbbr = Just 'h' , argName = Just "help" , argData = Nothing , argDesc = "Display a help message." } compileOnly :: Arg ArgIndex compileOnly = Arg { argIndex = CompileOnly , argAbbr = Just 'c' , argName = Just "compile" , argData = Nothing , argDesc = "Compile .py to .pyc but do not run the program." } inputFile :: Arg ArgIndex inputFile = Arg { argIndex = InputFile , argAbbr = Nothing , argName = Nothing , argData = argDataOptional "input file" ArgtypeString , argDesc = "Name of the input Python file, either .py or .pyc" } version :: Arg ArgIndex version = Arg { argIndex = Version , argAbbr = Nothing , argName = Just "version" , argData = Nothing , argDesc = "Show the version number of " ++ progName ++ "." } this works for CPython 3.8.2 see get_python_magic_number / get_python_magic_number.py defaultMagicNumber :: Int defaultMagicNumber = 168627541 magicNumberArg :: Arg ArgIndex magicNumberArg = Arg { argIndex = MagicNumber , argAbbr = Nothing , argName = Just "magic" , argData = argDataOptional "magic number" ArgtypeInt , argDesc = "Magic number to include in pyc file header." } dumpScopeArg :: Arg ArgIndex dumpScopeArg = Arg { argIndex = Dump DumpScope , argAbbr = Nothing , argName = Just "dumpScope" , argData = Nothing , argDesc = "Dump the variable scope." } dumpASTArg :: Arg ArgIndex dumpASTArg = Arg { argIndex = Dump DumpAST , argAbbr = Nothing , argName = Just "dumpAST" , argData = Nothing , argDesc = "Dump the abstract syntax tree." } getInputFile :: Args ArgIndex -> Maybe FilePath getInputFile args = getArg args InputFile getMagicNumber :: Args ArgIndex -> Int getMagicNumber args = maybe defaultMagicNumber id $ getArg args MagicNumber getDumps :: Args ArgIndex -> Set.Set Dumpable getDumps args = getDump DumpScope args `Set.union` getDump DumpAST args where getDump :: Dumpable -> Args ArgIndex -> Set.Set Dumpable getDump dumpable args | gotArg args (Dump dumpable) = Set.singleton dumpable | otherwise = Set.empty initCompileConfig :: CompileConfig initCompileConfig = CompileConfig { compileConfig_magic = 0, compileConfig_dumps = Set.empty }
fc897652120055a5c80946cfbd14ea0b523cc869a446957593d1199fd4612518
zadean/xqerl
prod_FunctionCall_SUITE.erl
-module('prod_FunctionCall_SUITE'). -include_lib("common_test/include/ct.hrl"). -export([ all/0, groups/0, suite/0 ]). -export([ init_per_suite/1, init_per_group/2, end_per_group/2, end_per_suite/1 ]). -export(['FunctionCall-001'/1]). -export(['FunctionCall-002'/1]). -export(['FunctionCall-003'/1]). -export(['FunctionCall-004'/1]). -export(['FunctionCall-005'/1]). -export(['FunctionCall-006'/1]). -export(['FunctionCall-007'/1]). -export(['FunctionCall-008'/1]). -export(['FunctionCall-009'/1]). -export(['FunctionCall-010'/1]). -export(['FunctionCall-011'/1]). -export(['FunctionCall-012'/1]). -export(['FunctionCall-013'/1]). -export(['FunctionCall-014'/1]). -export(['FunctionCall-015'/1]). -export(['FunctionCall-016'/1]). -export(['FunctionCall-017'/1]). -export(['FunctionCall-018'/1]). -export(['FunctionCall-019'/1]). -export(['FunctionCall-020'/1]). -export(['FunctionCall-021'/1]). -export(['FunctionCall-022'/1]). -export(['FunctionCall-023'/1]). -export(['FunctionCall-025'/1]). -export(['FunctionCall-026'/1]). -export(['FunctionCall-027'/1]). -export(['FunctionCall-028'/1]). -export(['FunctionCall-029'/1]). -export(['FunctionCall-030'/1]). -export(['FunctionCall-031'/1]). -export(['FunctionCall-032'/1]). -export(['FunctionCall-033'/1]). -export(['FunctionCall-034'/1]). -export(['FunctionCall-035'/1]). -export(['FunctionCall-036'/1]). -export(['FunctionCall-037'/1]). -export(['FunctionCall-038'/1]). -export(['FunctionCall-039'/1]). -export(['FunctionCall-040'/1]). -export(['FunctionCall-041'/1]). -export(['FunctionCall-042'/1]). -export(['FunctionCall-043'/1]). -export(['FunctionCall-044'/1]). -export(['FunctionCall-045'/1]). -export(['FunctionCall-046'/1]). -export(['FunctionCall-047'/1]). -export(['FunctionCall-048'/1]). -export(['FunctionCall-049'/1]). -export(['FunctionCall-050'/1]). -export(['FunctionCall-051'/1]). -export(['FunctionCall-052'/1]). -export(['FunctionCall-053'/1]). -export(['FunctionCall-054'/1]). -export(['K-FunctionCallExpr-1'/1]). -export(['K-FunctionCallExpr-2'/1]). -export(['K-FunctionCallExpr-3'/1]). -export(['K-FunctionCallExpr-4'/1]). -export(['K-FunctionCallExpr-5'/1]). -export(['K-FunctionCallExpr-6'/1]). -export(['K-FunctionCallExpr-7'/1]). -export(['K-FunctionCallExpr-8'/1]). -export(['K-FunctionCallExpr-9'/1]). -export(['K-FunctionCallExpr-10'/1]). -export(['K-FunctionCallExpr-11'/1]). -export(['K-FunctionCallExpr-12'/1]). -export(['K-FunctionCallExpr-13'/1]). -export(['K-FunctionCallExpr-14'/1]). -export(['K-FunctionCallExpr-15'/1]). -export(['K-FunctionCallExpr-15a'/1]). -export(['K-FunctionCallExpr-16'/1]). -export(['K-FunctionCallExpr-16a'/1]). -export(['K-FunctionCallExpr-17'/1]). -export(['K-FunctionCallExpr-17a'/1]). -export(['K-FunctionCallExpr-18'/1]). -export(['K-FunctionCallExpr-19'/1]). -export(['K-FunctionCallExpr-20'/1]). -export(['K-FunctionCallExpr-21'/1]). -export(['K-FunctionCallExpr-22'/1]). -export(['K-FunctionCallExpr-23'/1]). -export(['K-FunctionCallExpr-24'/1]). -export(['K-FunctionCallExpr-25'/1]). -export(['K-FunctionCallExpr-25a'/1]). -export(['K-FunctionCallExpr-26'/1]). -export(['K-FunctionCallExpr-27'/1]). -export(['K-FunctionCallExpr-28'/1]). -export(['K2-FunctionCallExpr-1'/1]). -export(['K2-FunctionCallExpr-2'/1]). -export(['K2-FunctionCallExpr-3'/1]). -export(['K2-FunctionCallExpr-4'/1]). -export(['K2-FunctionCallExpr-5'/1]). -export(['K2-FunctionCallExpr-6'/1]). -export(['K2-FunctionCallExpr-7'/1]). -export(['K2-FunctionCallExpr-8'/1]). -export(['K2-FunctionCallExpr-9'/1]). -export(['K2-FunctionCallExpr-10'/1]). -export(['K2-FunctionCallExpr-11'/1]). -export(['K2-FunctionCallExpr-12'/1]). -export(['K2-FunctionCallExpr-13'/1]). -export(['cbcl-promotion-001'/1]). -export(['cbcl-promotion-002'/1]). -export(['cbcl-promotion-003'/1]). -export(['cbcl-promotion-004'/1]). -export(['cbcl-promotion-005'/1]). -export(['cbcl-promotion-006'/1]). -export(['cbcl-promotion-007'/1]). -export(['function-call-reserved-function-names-001'/1]). -export(['function-call-reserved-function-names-002'/1]). -export(['function-call-reserved-function-names-003'/1]). -export(['function-call-reserved-function-names-004'/1]). -export(['function-call-reserved-function-names-005'/1]). -export(['function-call-reserved-function-names-006'/1]). -export(['function-call-reserved-function-names-007'/1]). -export(['function-call-reserved-function-names-008'/1]). -export(['function-call-reserved-function-names-009'/1]). -export(['function-call-reserved-function-names-010'/1]). -export(['function-call-reserved-function-names-011'/1]). -export(['function-call-reserved-function-names-012'/1]). -export(['function-call-reserved-function-names-013'/1]). -export(['function-call-reserved-function-names-014'/1]). -export(['function-call-reserved-function-names-015'/1]). -export(['function-call-reserved-function-names-016'/1]). -export(['function-call-reserved-function-names-017'/1]). -export(['function-call-reserved-function-names-018'/1]). -export(['function-call-reserved-function-names-019'/1]). -export(['function-call-reserved-function-names-020'/1]). -export(['function-call-reserved-function-names-021'/1]). -export(['function-call-reserved-function-names-022'/1]). -export(['function-call-reserved-function-names-023'/1]). -export(['function-call-reserved-function-names-024'/1]). -export(['function-call-reserved-function-names-025'/1]). -export(['function-call-reserved-function-names-026'/1]). -export(['function-call-reserved-function-names-027'/1]). -export(['function-call-reserved-function-names-028'/1]). -export(['function-call-reserved-function-names-029'/1]). -export(['function-call-reserved-function-names-030'/1]). -export(['function-call-reserved-function-names-031'/1]). -export(['function-call-reserved-function-names-032'/1]). -export(['function-call-reserved-function-names-033'/1]). -export(['function-call-reserved-function-names-034'/1]). -export(['function-call-reserved-function-names-035'/1]). -export(['function-call-reserved-function-names-036'/1]). -export(['function-call-reserved-function-names-037'/1]). -export(['function-call-reserved-function-names-038'/1]). -export(['function-call-reserved-function-names-039'/1]). -export(['function-call-reserved-function-names-040'/1]). -export(['function-call-reserved-function-names-041'/1]). -export(['function-call-reserved-function-names-042'/1]). -export(['function-call-reserved-function-names-043'/1]). -export(['function-call-reserved-function-names-044'/1]). -export(['function-call-reserved-function-names-045'/1]). -export(['function-call-reserved-function-names-046'/1]). suite() -> [{timetrap, {seconds, 180}}]. init_per_group(_, Config) -> Config. end_per_group(_, _Config) -> xqerl_code_server:unload(all). end_per_suite(_Config) -> ct:timetrap({seconds, 60}), xqerl_code_server:unload(all). init_per_suite(Config) -> {ok, _} = application:ensure_all_started(xqerl), DD = filename:dirname(filename:dirname(filename:dirname(?config(data_dir, Config)))), TD = filename:join(DD, "QT3-test-suite"), __BaseDir = filename:join(TD, "prod"), [{base_dir, __BaseDir} | Config]. all() -> [ {group, group_0}, {group, group_1}, {group, group_2}, {group, group_3}, {group, group_4}, {group, group_5}, {group, group_6} ]. groups() -> [ {group_0, [parallel], [ 'FunctionCall-001', 'FunctionCall-002', 'FunctionCall-003', 'FunctionCall-004', 'FunctionCall-005', 'FunctionCall-006', 'FunctionCall-007', 'FunctionCall-008', 'FunctionCall-009', 'FunctionCall-010', 'FunctionCall-011', 'FunctionCall-012', 'FunctionCall-013', 'FunctionCall-014', 'FunctionCall-015', 'FunctionCall-016', 'FunctionCall-017', 'FunctionCall-018', 'FunctionCall-019', 'FunctionCall-020', 'FunctionCall-021', 'FunctionCall-022', 'FunctionCall-023' ]}, {group_1, [parallel], [ 'FunctionCall-025', 'FunctionCall-026', 'FunctionCall-027', 'FunctionCall-028', 'FunctionCall-029', 'FunctionCall-030', 'FunctionCall-031', 'FunctionCall-032', 'FunctionCall-033', 'FunctionCall-034', 'FunctionCall-035', 'FunctionCall-036', 'FunctionCall-037', 'FunctionCall-038', 'FunctionCall-039', 'FunctionCall-040', 'FunctionCall-041', 'FunctionCall-042', 'FunctionCall-043', 'FunctionCall-044', 'FunctionCall-045', 'FunctionCall-046', 'FunctionCall-047', 'FunctionCall-048' ]}, {group_2, [parallel], [ 'FunctionCall-049', 'FunctionCall-050', 'FunctionCall-051', 'FunctionCall-052', 'FunctionCall-053', 'FunctionCall-054', 'K-FunctionCallExpr-1', 'K-FunctionCallExpr-2', 'K-FunctionCallExpr-3', 'K-FunctionCallExpr-4', 'K-FunctionCallExpr-5', 'K-FunctionCallExpr-6', 'K-FunctionCallExpr-7', 'K-FunctionCallExpr-8', 'K-FunctionCallExpr-9', 'K-FunctionCallExpr-10', 'K-FunctionCallExpr-11', 'K-FunctionCallExpr-12', 'K-FunctionCallExpr-13', 'K-FunctionCallExpr-14', 'K-FunctionCallExpr-15', 'K-FunctionCallExpr-15a', 'K-FunctionCallExpr-16', 'K-FunctionCallExpr-16a' ]}, {group_3, [parallel], [ 'K-FunctionCallExpr-17', 'K-FunctionCallExpr-17a', 'K-FunctionCallExpr-18', 'K-FunctionCallExpr-19', 'K-FunctionCallExpr-20', 'K-FunctionCallExpr-21', 'K-FunctionCallExpr-22', 'K-FunctionCallExpr-23', 'K-FunctionCallExpr-24', 'K-FunctionCallExpr-25', 'K-FunctionCallExpr-25a', 'K-FunctionCallExpr-26', 'K-FunctionCallExpr-27', 'K-FunctionCallExpr-28', 'K2-FunctionCallExpr-1', 'K2-FunctionCallExpr-2', 'K2-FunctionCallExpr-3', 'K2-FunctionCallExpr-4', 'K2-FunctionCallExpr-5', 'K2-FunctionCallExpr-6', 'K2-FunctionCallExpr-7', 'K2-FunctionCallExpr-8', 'K2-FunctionCallExpr-9', 'K2-FunctionCallExpr-10' ]}, {group_4, [parallel], [ 'K2-FunctionCallExpr-11', 'K2-FunctionCallExpr-12', 'K2-FunctionCallExpr-13', 'cbcl-promotion-001', 'cbcl-promotion-002', 'cbcl-promotion-003', 'cbcl-promotion-004', 'cbcl-promotion-005', 'cbcl-promotion-006', 'cbcl-promotion-007', 'function-call-reserved-function-names-001', 'function-call-reserved-function-names-002', 'function-call-reserved-function-names-003', 'function-call-reserved-function-names-004', 'function-call-reserved-function-names-005', 'function-call-reserved-function-names-006', 'function-call-reserved-function-names-007', 'function-call-reserved-function-names-008', 'function-call-reserved-function-names-009', 'function-call-reserved-function-names-010', 'function-call-reserved-function-names-011', 'function-call-reserved-function-names-012', 'function-call-reserved-function-names-013', 'function-call-reserved-function-names-014' ]}, {group_5, [parallel], [ 'function-call-reserved-function-names-015', 'function-call-reserved-function-names-016', 'function-call-reserved-function-names-017', 'function-call-reserved-function-names-018', 'function-call-reserved-function-names-019', 'function-call-reserved-function-names-020', 'function-call-reserved-function-names-021', 'function-call-reserved-function-names-022', 'function-call-reserved-function-names-023', 'function-call-reserved-function-names-024', 'function-call-reserved-function-names-025', 'function-call-reserved-function-names-026', 'function-call-reserved-function-names-027', 'function-call-reserved-function-names-028', 'function-call-reserved-function-names-029', 'function-call-reserved-function-names-030', 'function-call-reserved-function-names-031', 'function-call-reserved-function-names-032', 'function-call-reserved-function-names-033', 'function-call-reserved-function-names-034', 'function-call-reserved-function-names-035', 'function-call-reserved-function-names-036', 'function-call-reserved-function-names-037', 'function-call-reserved-function-names-038' ]}, {group_6, [parallel], [ 'function-call-reserved-function-names-039', 'function-call-reserved-function-names-040', 'function-call-reserved-function-names-041', 'function-call-reserved-function-names-042', 'function-call-reserved-function-names-043', 'function-call-reserved-function-names-044', 'function-call-reserved-function-names-045', 'function-call-reserved-function-names-046' ]} ]. environment('ListUnionTypes', __BaseDir) -> [ {'decimal-formats', []}, {sources, []}, {collections, []}, {'static-base-uri', []}, {params, []}, {vars, []}, {namespaces, []}, {schemas, [ {filename:join(__BaseDir, "ValidateExpr/listunion.xsd"), ""} ]}, {resources, []}, {modules, []} ]; environment('unionListDefined', __BaseDir) -> [ {'decimal-formats', []}, {sources, []}, {collections, []}, {'static-base-uri', []}, {params, []}, {vars, []}, {namespaces, []}, {schemas, [ {filename:join(__BaseDir, "SchemaImport/unionListDefined.xsd"), ""} ]}, {resources, []}, {modules, []} ]. 'FunctionCall-001'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "concat(<a>X</a>, <a>Y</a>)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-001.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "XY") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-002'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "xs:boolean(<a>0</a>)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-002.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_false(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-003'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-004'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:f($in as xs:boolean) as xs:boolean { $in };\n" " local:f(<a>0</a>)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-004.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_false(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-005'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-006'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " let $f := function ($in as xs:boolean) as xs:boolean { $in }\n" " return $f(<a>0</a>)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-006.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_false(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-007'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-008'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-009'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:f($in as xs:decimal*) as xs:decimal {sum($in, 0.0)};\n" " local:f(xs:NMTOKENS('1 1.2 1.3 1.4')!xs:untypedAtomic(.))\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-009.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:all( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_type(Res, "xs:decimal") of true -> {comment, "Correct type"}; {false, F} -> F end, case xqerl_test:assert_eq(Res, "4.9") of true -> {comment, "Equal"}; {false, F} -> F end ] ) of true -> {comment, "all-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-010'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP30+"}. 'FunctionCall-011'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP30+"}. 'FunctionCall-012'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP30+"}. 'FunctionCall-013'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:f($a as xs:integer, $b as xs:integer) as xs:integer {\n" " data(<a>{$a}{$b}</a>)\n" " };\n" " local:f(12, 34)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-013.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:all( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_type(Res, "xs:integer") of true -> {comment, "Correct type"}; {false, F} -> F end, case xqerl_test:assert_eq(Res, "1234") of true -> {comment, "Equal"}; {false, F} -> F end ] ) of true -> {comment, "all-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-014'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " let $f := function($a as xs:integer, $b as xs:integer) as xs:integer {\n" " data(<a>{$a}{$b}</a>)\n" " }\n" " return $f(12, 34)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-014.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:all( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_type(Res, "xs:integer") of true -> {comment, "Correct type"}; {false, F} -> F end, case xqerl_test:assert_eq(Res, "1234") of true -> {comment, "Equal"}; {false, F} -> F end ] ) of true -> {comment, "all-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-015'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-016'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-017'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-018'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-019'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-020'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-021'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-022'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:unique($in as xs:integer*) as xs:boolean { count($in) = count(distinct-values($in)) };\n" " (local:unique([1,2,3,4,5]), local:unique([1,2,3,4,4]))", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-022.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_deep_eq(Res, "true(), false()") of true -> {comment, "Deep equal"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-023'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "string-join((<a>X</a>, <a>Y</a>, <a>Z</a>), '')", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-023.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "XYZ") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-025'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP30+"}. 'FunctionCall-026'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP30+"}. 'FunctionCall-027'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP30+"}. 'FunctionCall-028'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-029'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-030'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-031'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-032'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-033'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-034'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-035'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-036'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-037'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-038'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-039'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-040'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-041'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-042'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-043'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-044'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP30 XQ30"}. 'FunctionCall-045'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " let $f := function($x) {}\n" " return $f(2)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-045.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_empty(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-046'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " let $f := function($x) { (: there's nothing here :)}\n" " return $f(2)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-046.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_empty(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-047'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " let $f := function($x as xs:integer) as xs:integer? { (: there's nothing here :)}\n" " return $f(2)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-047.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_empty(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-048'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " let $f := function($x as xs:integer) as xs:integer { (: there's nothing here :) }\n" " return $f(2)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-048.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPTY0004") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-049'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-050'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-051'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-052'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-053'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-054'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'K-FunctionCallExpr-1'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "func-does-not-exist(1, 2, 3)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-1.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-2'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "fn:func-does-not-exist(1, 2, 3)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-2.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-3'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "xs:func-does-not-exist(1, 2, 3)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-3.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-4'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "local:func-does-not-exist(1, 2, 3)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-4.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-5'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "prefix-does-not-exist:func-does-not-exist(1, 2, 3)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-5.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0081") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0081 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-6'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "f:f:()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-6.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XPST0081") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0081 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-7'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = ":f()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-7.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-8'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = ":f()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-8.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-9'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "1fd()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-9.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-10'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "p:f:lname()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-10.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XPST0081") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0081 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-11'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "document(\"example.com/file.ext\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-11.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-12'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XQ10"}. 'K-FunctionCallExpr-13'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XQ10"}. 'K-FunctionCallExpr-14'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "key('func', \"a value\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-14.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-15'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10 XP20"}. 'K-FunctionCallExpr-15a'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "format-number(3, \"0000\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-15a.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_eq(Res, "\"0003\"") of true -> {comment, "Equal"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-16'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10 XP20"}. 'K-FunctionCallExpr-16a'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "matches(format-time(current-time(), \"[H01]:[m01]\"), \"[0-2][0-9]:[0-5][0-9]\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-16a.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_true(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-17'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10 XP20"}. 'K-FunctionCallExpr-17a'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "matches(format-time(current-time(), \"[H01]:[m01]\", (), (), ()), \"..:..\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-17a.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_true(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-18'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "matches(format-dateTime(current-dateTime(), \"[Y0001]-[M01]-[D01]\"), \"[0-9]{4}-[0-9]{2}-[0-9]{2}\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-18.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_true(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-19'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "matches(format-dateTime(current-dateTime(), \"[Y0001]-[M01]-[D01]\", (), (), ()), \"....-..-..\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-19.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_true(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-20'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "matches(format-dateTime(current-dateTime(), \"[M01]/[D01]/[Y0001] at [H01]:[m01]:[s01]\"), \"[0-1][0-9]/[0-3][0-9]/[0-9]{4} at [0-9]{2}:[0-9]{2}:[0-9]{2}\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-20.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_true(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-21'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "matches(format-dateTime(current-dateTime(), \"[M01]/[D01]/[Y0001] at [H01]:[m01]:[s01]\", (), (), ()), \"../../.... at ..:..:..\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-21.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_true(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-22'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "current()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-22.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-23'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "unparsed-entity-uri(\"example.com/file.ext\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-23.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-24'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "unparsed-entity-public-id(\"entity\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-24.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-25'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10"}. 'K-FunctionCallExpr-25a'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "generate-id(<a/>) castable as xs:NCName", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-25a.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_true(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-26'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "system-property(\"xsl:vendor\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-26.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-27'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "fn:escape-uri(\"http:/example.com/\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-27.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-28'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "fn:sub-sequence(\"http:/example.com/\", 1, 1)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-28.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-1'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:bar($c, $d, $e, $f, $g, $h, $i, $j, $a, $b) { 1 }; \n" " declare function local:moo($k) { $k }; \n" " local:moo(1)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-1.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_eq(Res, "1") of true -> {comment, "Equal"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-2'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "current-grouping-key()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-2.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-3'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "current()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-3.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-4'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "unparsed-entity-uri(\"str\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-4.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-5'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "unparsed-entity-public-id(\"str\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-5.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-6'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XQ10"}. 'K2-FunctionCallExpr-7'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XQ10"}. 'K2-FunctionCallExpr-8'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "system-property(\"property\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-8.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-9'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "key(\"id\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-9.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-10'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare variable $a := <a/>; \n" " declare function local:testSingleNodeIdentity($node as node()) { $node is $node }; \n" " declare function local:testDoubleNodeIdentity($a as node(), $b as node()) { $a is $b }; \n" " local:testSingleNodeIdentity(<a/>), local:testDoubleNodeIdentity(<a/>, <b/>), local:testDoubleNodeIdentity($a, $a)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-10.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "true false true") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-11'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:compare($arg1 as xs:string, $arg2 as xs:string) { \n" " let $cps1 := string-to-codepoints($arg1), \n" " $cps2 := string-to-codepoints($arg2) \n" " return abs(count($cps1) - count($cps2)) + sum(for $x in 1 to min((count($cps1), count($cps2))) \n" " return if ($cps1[$x] ne $cps2[$x]) then 1 else ()) }; \n" " local:compare(\"\", \"\"), \n" " local:compare(\"a\", \"\"), \n" " local:compare(\"\", \"a\"), \n" " local:compare(\"a\", \"a\"), \n" " local:compare(\"\", \"aa\"), \n" " local:compare(\"aa\", \"ab\"), \n" " local:compare(\"ba\", \"ba\"), \n" " local:compare(\"bab\", \"bbb\"), \n" " local:compare(\"aba\", \"bab\")\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-11.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "0 1 1 0 2 1 0 1 3") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-12'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:func1() { if(local:func2('b')) then 3 else local:func1() }; \n" " declare function local:func2($a) { if(matches(\"\",$a)) then () else 4 }; \n" " local:func1()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-12.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_eq(Res, "3") of true -> {comment, "Equal"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-13'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "declare function local:foo($arg) { local:foo(local:foo(1)) }; 1", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-13.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_eq(Res, "1") of true -> {comment, "Equal"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'cbcl-promotion-001'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " string-join( (xs:anyURI(''), xs:anyURI('/')), ' ')\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "cbcl-promotion-001.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, " /") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'cbcl-promotion-002'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:index-of($seq as xs:double*, $item as xs:double) { for $x at $p in $seq return if ($x eq $item) then $p else () };\n" " declare function local:sequence($x as xs:integer) { (\"string\", 1, 2.0, xs:float(3))[$x] };\n" " local:index-of(for $x in (2,3,4) return local:sequence($x), 2)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "cbcl-promotion-002.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "2") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'cbcl-promotion-003'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:index-of($seq as xs:integer*, $item as xs:integer?) as xs:float* { \n" " if (empty($item)) \n" " then -1\n" " else for $x at $p in $seq return if ($x eq $item) then $p else () \n" " };\n" " local:index-of(1 to 10, 3)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "cbcl-promotion-003.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "3") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'cbcl-promotion-004'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:f() as xs:double* { \n" " if (day-from-date(current-date()) < 32) then xs:integer(3) else -1\n" " };\n" " local:f() + 1", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "cbcl-promotion-004.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "4") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'cbcl-promotion-005'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:index-of($seq, $item) as xs:double? { for $x at $p in $seq return if ($x eq $item) then $p else () };\n" " local:index-of((1, 2.0, xs:float(3), 2), 2)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "cbcl-promotion-005.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPTY0004") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'cbcl-promotion-006'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:f($arg as xs:anyAtomicType?) { $arg };\n" " local:f(index-of((1,2,3,2),2))", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "cbcl-promotion-006.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPTY0004") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'cbcl-promotion-007'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:f($v as xs:double*) as xs:double+ { if (empty($v)) then 0 else $v };\n" " declare function local:g($v as xs:double*) as xs:double+ { local:f($v) };\n" " local:g((1,2,3))", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "cbcl-promotion-007.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "1 2 3") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-001'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:attribute($arg) { fn:true() };\n" " attribute(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-001.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-002'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:comment($arg) { fn:true() };\n" " comment(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-002.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-003'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:document-node($arg) { fn:true() };\n" " document-node(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-003.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-004'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:element($arg) { fn:true() };\n" " element(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-004.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-005'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:empty-sequence() { fn:true() };\n" " empty-sequence()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-005.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-006'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:if() { fn:true() };\n" " if()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-006.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-007'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:item($arg) { fn:true() };\n" " item(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-007.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-008'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:node($arg) { fn:true() };\n" " node(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-008.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-009'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:processing-instruction($arg) { fn:true() };\n" " processing-instruction(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-009.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-010'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:schema-attribute() { fn:true() };\n" " schema-attribute()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-010.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-011'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:schema-element() { fn:true() };\n" " schema-element()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-011.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-012'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:text($arg) { fn:true() };\n" " text(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-012.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-013'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:typeswitch() { fn:true() };\n" " typeswitch()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-013.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-014'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10"}. 'function-call-reserved-function-names-015'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10"}. 'function-call-reserved-function-names-016'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10"}. 'function-call-reserved-function-names-017'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:function() { fn:true() };\n" " function()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-017.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-018'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:namespace-node($arg) { fn:true() };\n" " namespace-node(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-018.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XQST0134") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XQST0134 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-019'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:switch() { fn:true() };\n" " switch()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-019.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-020'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " attribute(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-020.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-021'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " comment(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-021.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-022'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " document-node(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-022.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-023'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " element(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-023.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-024'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " empty-sequence()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-024.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-025'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " if()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-025.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-026'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " item()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-026.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-027'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " node(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-027.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-028'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " processing-instruction(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-028.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-029'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " schema-attribute()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-029.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-030'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " schema-element()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-030.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-031'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " text(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-031.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-032'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " typeswitch()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-032.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-033'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XQ10"}. 'function-call-reserved-function-names-034'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20"}. 'function-call-reserved-function-names-035'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XQ10"}. 'function-call-reserved-function-names-036'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " function()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-036.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-037'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " namespace-node(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-037.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XQST0134") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XQST0134 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-038'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " switch()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-038.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-039'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10 XQ30"}. 'function-call-reserved-function-names-040'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:array() { fn:true() };\n" " array()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-040.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-041'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XP30 XQ10 XQ30"}. 'function-call-reserved-function-names-042'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " array()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-042.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-043'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10 XQ30"}. 'function-call-reserved-function-names-044'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:map() { fn:true() };\n" " map()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-044.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-045'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XP30 XQ10 XQ30"}. 'function-call-reserved-function-names-046'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " map()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-046.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end.
null
https://raw.githubusercontent.com/zadean/xqerl/1a94833e996435495922346010ce918b4b0717f2/test/prod/prod_FunctionCall_SUITE.erl
erlang
-module('prod_FunctionCall_SUITE'). -include_lib("common_test/include/ct.hrl"). -export([ all/0, groups/0, suite/0 ]). -export([ init_per_suite/1, init_per_group/2, end_per_group/2, end_per_suite/1 ]). -export(['FunctionCall-001'/1]). -export(['FunctionCall-002'/1]). -export(['FunctionCall-003'/1]). -export(['FunctionCall-004'/1]). -export(['FunctionCall-005'/1]). -export(['FunctionCall-006'/1]). -export(['FunctionCall-007'/1]). -export(['FunctionCall-008'/1]). -export(['FunctionCall-009'/1]). -export(['FunctionCall-010'/1]). -export(['FunctionCall-011'/1]). -export(['FunctionCall-012'/1]). -export(['FunctionCall-013'/1]). -export(['FunctionCall-014'/1]). -export(['FunctionCall-015'/1]). -export(['FunctionCall-016'/1]). -export(['FunctionCall-017'/1]). -export(['FunctionCall-018'/1]). -export(['FunctionCall-019'/1]). -export(['FunctionCall-020'/1]). -export(['FunctionCall-021'/1]). -export(['FunctionCall-022'/1]). -export(['FunctionCall-023'/1]). -export(['FunctionCall-025'/1]). -export(['FunctionCall-026'/1]). -export(['FunctionCall-027'/1]). -export(['FunctionCall-028'/1]). -export(['FunctionCall-029'/1]). -export(['FunctionCall-030'/1]). -export(['FunctionCall-031'/1]). -export(['FunctionCall-032'/1]). -export(['FunctionCall-033'/1]). -export(['FunctionCall-034'/1]). -export(['FunctionCall-035'/1]). -export(['FunctionCall-036'/1]). -export(['FunctionCall-037'/1]). -export(['FunctionCall-038'/1]). -export(['FunctionCall-039'/1]). -export(['FunctionCall-040'/1]). -export(['FunctionCall-041'/1]). -export(['FunctionCall-042'/1]). -export(['FunctionCall-043'/1]). -export(['FunctionCall-044'/1]). -export(['FunctionCall-045'/1]). -export(['FunctionCall-046'/1]). -export(['FunctionCall-047'/1]). -export(['FunctionCall-048'/1]). -export(['FunctionCall-049'/1]). -export(['FunctionCall-050'/1]). -export(['FunctionCall-051'/1]). -export(['FunctionCall-052'/1]). -export(['FunctionCall-053'/1]). -export(['FunctionCall-054'/1]). -export(['K-FunctionCallExpr-1'/1]). -export(['K-FunctionCallExpr-2'/1]). -export(['K-FunctionCallExpr-3'/1]). -export(['K-FunctionCallExpr-4'/1]). -export(['K-FunctionCallExpr-5'/1]). -export(['K-FunctionCallExpr-6'/1]). -export(['K-FunctionCallExpr-7'/1]). -export(['K-FunctionCallExpr-8'/1]). -export(['K-FunctionCallExpr-9'/1]). -export(['K-FunctionCallExpr-10'/1]). -export(['K-FunctionCallExpr-11'/1]). -export(['K-FunctionCallExpr-12'/1]). -export(['K-FunctionCallExpr-13'/1]). -export(['K-FunctionCallExpr-14'/1]). -export(['K-FunctionCallExpr-15'/1]). -export(['K-FunctionCallExpr-15a'/1]). -export(['K-FunctionCallExpr-16'/1]). -export(['K-FunctionCallExpr-16a'/1]). -export(['K-FunctionCallExpr-17'/1]). -export(['K-FunctionCallExpr-17a'/1]). -export(['K-FunctionCallExpr-18'/1]). -export(['K-FunctionCallExpr-19'/1]). -export(['K-FunctionCallExpr-20'/1]). -export(['K-FunctionCallExpr-21'/1]). -export(['K-FunctionCallExpr-22'/1]). -export(['K-FunctionCallExpr-23'/1]). -export(['K-FunctionCallExpr-24'/1]). -export(['K-FunctionCallExpr-25'/1]). -export(['K-FunctionCallExpr-25a'/1]). -export(['K-FunctionCallExpr-26'/1]). -export(['K-FunctionCallExpr-27'/1]). -export(['K-FunctionCallExpr-28'/1]). -export(['K2-FunctionCallExpr-1'/1]). -export(['K2-FunctionCallExpr-2'/1]). -export(['K2-FunctionCallExpr-3'/1]). -export(['K2-FunctionCallExpr-4'/1]). -export(['K2-FunctionCallExpr-5'/1]). -export(['K2-FunctionCallExpr-6'/1]). -export(['K2-FunctionCallExpr-7'/1]). -export(['K2-FunctionCallExpr-8'/1]). -export(['K2-FunctionCallExpr-9'/1]). -export(['K2-FunctionCallExpr-10'/1]). -export(['K2-FunctionCallExpr-11'/1]). -export(['K2-FunctionCallExpr-12'/1]). -export(['K2-FunctionCallExpr-13'/1]). -export(['cbcl-promotion-001'/1]). -export(['cbcl-promotion-002'/1]). -export(['cbcl-promotion-003'/1]). -export(['cbcl-promotion-004'/1]). -export(['cbcl-promotion-005'/1]). -export(['cbcl-promotion-006'/1]). -export(['cbcl-promotion-007'/1]). -export(['function-call-reserved-function-names-001'/1]). -export(['function-call-reserved-function-names-002'/1]). -export(['function-call-reserved-function-names-003'/1]). -export(['function-call-reserved-function-names-004'/1]). -export(['function-call-reserved-function-names-005'/1]). -export(['function-call-reserved-function-names-006'/1]). -export(['function-call-reserved-function-names-007'/1]). -export(['function-call-reserved-function-names-008'/1]). -export(['function-call-reserved-function-names-009'/1]). -export(['function-call-reserved-function-names-010'/1]). -export(['function-call-reserved-function-names-011'/1]). -export(['function-call-reserved-function-names-012'/1]). -export(['function-call-reserved-function-names-013'/1]). -export(['function-call-reserved-function-names-014'/1]). -export(['function-call-reserved-function-names-015'/1]). -export(['function-call-reserved-function-names-016'/1]). -export(['function-call-reserved-function-names-017'/1]). -export(['function-call-reserved-function-names-018'/1]). -export(['function-call-reserved-function-names-019'/1]). -export(['function-call-reserved-function-names-020'/1]). -export(['function-call-reserved-function-names-021'/1]). -export(['function-call-reserved-function-names-022'/1]). -export(['function-call-reserved-function-names-023'/1]). -export(['function-call-reserved-function-names-024'/1]). -export(['function-call-reserved-function-names-025'/1]). -export(['function-call-reserved-function-names-026'/1]). -export(['function-call-reserved-function-names-027'/1]). -export(['function-call-reserved-function-names-028'/1]). -export(['function-call-reserved-function-names-029'/1]). -export(['function-call-reserved-function-names-030'/1]). -export(['function-call-reserved-function-names-031'/1]). -export(['function-call-reserved-function-names-032'/1]). -export(['function-call-reserved-function-names-033'/1]). -export(['function-call-reserved-function-names-034'/1]). -export(['function-call-reserved-function-names-035'/1]). -export(['function-call-reserved-function-names-036'/1]). -export(['function-call-reserved-function-names-037'/1]). -export(['function-call-reserved-function-names-038'/1]). -export(['function-call-reserved-function-names-039'/1]). -export(['function-call-reserved-function-names-040'/1]). -export(['function-call-reserved-function-names-041'/1]). -export(['function-call-reserved-function-names-042'/1]). -export(['function-call-reserved-function-names-043'/1]). -export(['function-call-reserved-function-names-044'/1]). -export(['function-call-reserved-function-names-045'/1]). -export(['function-call-reserved-function-names-046'/1]). suite() -> [{timetrap, {seconds, 180}}]. init_per_group(_, Config) -> Config. end_per_group(_, _Config) -> xqerl_code_server:unload(all). end_per_suite(_Config) -> ct:timetrap({seconds, 60}), xqerl_code_server:unload(all). init_per_suite(Config) -> {ok, _} = application:ensure_all_started(xqerl), DD = filename:dirname(filename:dirname(filename:dirname(?config(data_dir, Config)))), TD = filename:join(DD, "QT3-test-suite"), __BaseDir = filename:join(TD, "prod"), [{base_dir, __BaseDir} | Config]. all() -> [ {group, group_0}, {group, group_1}, {group, group_2}, {group, group_3}, {group, group_4}, {group, group_5}, {group, group_6} ]. groups() -> [ {group_0, [parallel], [ 'FunctionCall-001', 'FunctionCall-002', 'FunctionCall-003', 'FunctionCall-004', 'FunctionCall-005', 'FunctionCall-006', 'FunctionCall-007', 'FunctionCall-008', 'FunctionCall-009', 'FunctionCall-010', 'FunctionCall-011', 'FunctionCall-012', 'FunctionCall-013', 'FunctionCall-014', 'FunctionCall-015', 'FunctionCall-016', 'FunctionCall-017', 'FunctionCall-018', 'FunctionCall-019', 'FunctionCall-020', 'FunctionCall-021', 'FunctionCall-022', 'FunctionCall-023' ]}, {group_1, [parallel], [ 'FunctionCall-025', 'FunctionCall-026', 'FunctionCall-027', 'FunctionCall-028', 'FunctionCall-029', 'FunctionCall-030', 'FunctionCall-031', 'FunctionCall-032', 'FunctionCall-033', 'FunctionCall-034', 'FunctionCall-035', 'FunctionCall-036', 'FunctionCall-037', 'FunctionCall-038', 'FunctionCall-039', 'FunctionCall-040', 'FunctionCall-041', 'FunctionCall-042', 'FunctionCall-043', 'FunctionCall-044', 'FunctionCall-045', 'FunctionCall-046', 'FunctionCall-047', 'FunctionCall-048' ]}, {group_2, [parallel], [ 'FunctionCall-049', 'FunctionCall-050', 'FunctionCall-051', 'FunctionCall-052', 'FunctionCall-053', 'FunctionCall-054', 'K-FunctionCallExpr-1', 'K-FunctionCallExpr-2', 'K-FunctionCallExpr-3', 'K-FunctionCallExpr-4', 'K-FunctionCallExpr-5', 'K-FunctionCallExpr-6', 'K-FunctionCallExpr-7', 'K-FunctionCallExpr-8', 'K-FunctionCallExpr-9', 'K-FunctionCallExpr-10', 'K-FunctionCallExpr-11', 'K-FunctionCallExpr-12', 'K-FunctionCallExpr-13', 'K-FunctionCallExpr-14', 'K-FunctionCallExpr-15', 'K-FunctionCallExpr-15a', 'K-FunctionCallExpr-16', 'K-FunctionCallExpr-16a' ]}, {group_3, [parallel], [ 'K-FunctionCallExpr-17', 'K-FunctionCallExpr-17a', 'K-FunctionCallExpr-18', 'K-FunctionCallExpr-19', 'K-FunctionCallExpr-20', 'K-FunctionCallExpr-21', 'K-FunctionCallExpr-22', 'K-FunctionCallExpr-23', 'K-FunctionCallExpr-24', 'K-FunctionCallExpr-25', 'K-FunctionCallExpr-25a', 'K-FunctionCallExpr-26', 'K-FunctionCallExpr-27', 'K-FunctionCallExpr-28', 'K2-FunctionCallExpr-1', 'K2-FunctionCallExpr-2', 'K2-FunctionCallExpr-3', 'K2-FunctionCallExpr-4', 'K2-FunctionCallExpr-5', 'K2-FunctionCallExpr-6', 'K2-FunctionCallExpr-7', 'K2-FunctionCallExpr-8', 'K2-FunctionCallExpr-9', 'K2-FunctionCallExpr-10' ]}, {group_4, [parallel], [ 'K2-FunctionCallExpr-11', 'K2-FunctionCallExpr-12', 'K2-FunctionCallExpr-13', 'cbcl-promotion-001', 'cbcl-promotion-002', 'cbcl-promotion-003', 'cbcl-promotion-004', 'cbcl-promotion-005', 'cbcl-promotion-006', 'cbcl-promotion-007', 'function-call-reserved-function-names-001', 'function-call-reserved-function-names-002', 'function-call-reserved-function-names-003', 'function-call-reserved-function-names-004', 'function-call-reserved-function-names-005', 'function-call-reserved-function-names-006', 'function-call-reserved-function-names-007', 'function-call-reserved-function-names-008', 'function-call-reserved-function-names-009', 'function-call-reserved-function-names-010', 'function-call-reserved-function-names-011', 'function-call-reserved-function-names-012', 'function-call-reserved-function-names-013', 'function-call-reserved-function-names-014' ]}, {group_5, [parallel], [ 'function-call-reserved-function-names-015', 'function-call-reserved-function-names-016', 'function-call-reserved-function-names-017', 'function-call-reserved-function-names-018', 'function-call-reserved-function-names-019', 'function-call-reserved-function-names-020', 'function-call-reserved-function-names-021', 'function-call-reserved-function-names-022', 'function-call-reserved-function-names-023', 'function-call-reserved-function-names-024', 'function-call-reserved-function-names-025', 'function-call-reserved-function-names-026', 'function-call-reserved-function-names-027', 'function-call-reserved-function-names-028', 'function-call-reserved-function-names-029', 'function-call-reserved-function-names-030', 'function-call-reserved-function-names-031', 'function-call-reserved-function-names-032', 'function-call-reserved-function-names-033', 'function-call-reserved-function-names-034', 'function-call-reserved-function-names-035', 'function-call-reserved-function-names-036', 'function-call-reserved-function-names-037', 'function-call-reserved-function-names-038' ]}, {group_6, [parallel], [ 'function-call-reserved-function-names-039', 'function-call-reserved-function-names-040', 'function-call-reserved-function-names-041', 'function-call-reserved-function-names-042', 'function-call-reserved-function-names-043', 'function-call-reserved-function-names-044', 'function-call-reserved-function-names-045', 'function-call-reserved-function-names-046' ]} ]. environment('ListUnionTypes', __BaseDir) -> [ {'decimal-formats', []}, {sources, []}, {collections, []}, {'static-base-uri', []}, {params, []}, {vars, []}, {namespaces, []}, {schemas, [ {filename:join(__BaseDir, "ValidateExpr/listunion.xsd"), ""} ]}, {resources, []}, {modules, []} ]; environment('unionListDefined', __BaseDir) -> [ {'decimal-formats', []}, {sources, []}, {collections, []}, {'static-base-uri', []}, {params, []}, {vars, []}, {namespaces, []}, {schemas, [ {filename:join(__BaseDir, "SchemaImport/unionListDefined.xsd"), ""} ]}, {resources, []}, {modules, []} ]. 'FunctionCall-001'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "concat(<a>X</a>, <a>Y</a>)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-001.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "XY") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-002'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "xs:boolean(<a>0</a>)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-002.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_false(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-003'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-004'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:f($in as xs:boolean) as xs:boolean { $in };\n" " local:f(<a>0</a>)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-004.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_false(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-005'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-006'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " let $f := function ($in as xs:boolean) as xs:boolean { $in }\n" " return $f(<a>0</a>)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-006.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_false(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-007'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-008'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-009'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:f($in as xs:decimal*) as xs:decimal {sum($in, 0.0)};\n" " local:f(xs:NMTOKENS('1 1.2 1.3 1.4')!xs:untypedAtomic(.))\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-009.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:all( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_type(Res, "xs:decimal") of true -> {comment, "Correct type"}; {false, F} -> F end, case xqerl_test:assert_eq(Res, "4.9") of true -> {comment, "Equal"}; {false, F} -> F end ] ) of true -> {comment, "all-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-010'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP30+"}. 'FunctionCall-011'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP30+"}. 'FunctionCall-012'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP30+"}. 'FunctionCall-013'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:f($a as xs:integer, $b as xs:integer) as xs:integer {\n" " data(<a>{$a}{$b}</a>)\n" " };\n" " local:f(12, 34)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-013.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:all( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_type(Res, "xs:integer") of true -> {comment, "Correct type"}; {false, F} -> F end, case xqerl_test:assert_eq(Res, "1234") of true -> {comment, "Equal"}; {false, F} -> F end ] ) of true -> {comment, "all-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-014'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " let $f := function($a as xs:integer, $b as xs:integer) as xs:integer {\n" " data(<a>{$a}{$b}</a>)\n" " }\n" " return $f(12, 34)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-014.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:all( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_type(Res, "xs:integer") of true -> {comment, "Correct type"}; {false, F} -> F end, case xqerl_test:assert_eq(Res, "1234") of true -> {comment, "Equal"}; {false, F} -> F end ] ) of true -> {comment, "all-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-015'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-016'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-017'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-018'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-019'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-020'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-021'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaValidation"}. 'FunctionCall-022'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:unique($in as xs:integer*) as xs:boolean { count($in) = count(distinct-values($in)) };\n" " (local:unique([1,2,3,4,5]), local:unique([1,2,3,4,4]))", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-022.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_deep_eq(Res, "true(), false()") of true -> {comment, "Deep equal"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-023'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "string-join((<a>X</a>, <a>Y</a>, <a>Z</a>), '')", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-023.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "XYZ") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-025'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP30+"}. 'FunctionCall-026'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP30+"}. 'FunctionCall-027'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP30+"}. 'FunctionCall-028'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-029'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-030'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-031'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-032'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-033'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-034'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-035'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-036'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-037'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-038'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-039'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-040'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-041'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-042'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-043'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-044'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP30 XQ30"}. 'FunctionCall-045'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " let $f := function($x) {}\n" " return $f(2)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-045.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_empty(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-046'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " let $f := function($x) { (: there's nothing here :)}\n" " return $f(2)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-046.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_empty(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-047'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " let $f := function($x as xs:integer) as xs:integer? { (: there's nothing here :)}\n" " return $f(2)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-047.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_empty(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-048'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " let $f := function($x as xs:integer) as xs:integer { (: there's nothing here :) }\n" " return $f(2)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile(filename:join(__BaseDir, "FunctionCall-048.xq"), Qry1), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPTY0004") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'FunctionCall-049'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-050'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-051'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-052'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-053'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'FunctionCall-054'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "feature:schemaImport"}. 'K-FunctionCallExpr-1'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "func-does-not-exist(1, 2, 3)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-1.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-2'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "fn:func-does-not-exist(1, 2, 3)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-2.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-3'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "xs:func-does-not-exist(1, 2, 3)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-3.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-4'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "local:func-does-not-exist(1, 2, 3)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-4.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-5'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "prefix-does-not-exist:func-does-not-exist(1, 2, 3)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-5.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0081") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0081 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-6'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "f:f:()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-6.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XPST0081") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0081 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-7'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = ":f()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-7.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-8'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = ":f()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-8.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-9'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "1fd()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-9.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-10'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "p:f:lname()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-10.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XPST0081") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0081 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-11'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "document(\"example.com/file.ext\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-11.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-12'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XQ10"}. 'K-FunctionCallExpr-13'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XQ10"}. 'K-FunctionCallExpr-14'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "key('func', \"a value\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-14.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-15'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10 XP20"}. 'K-FunctionCallExpr-15a'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "format-number(3, \"0000\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-15a.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_eq(Res, "\"0003\"") of true -> {comment, "Equal"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-16'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10 XP20"}. 'K-FunctionCallExpr-16a'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "matches(format-time(current-time(), \"[H01]:[m01]\"), \"[0-2][0-9]:[0-5][0-9]\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-16a.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_true(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-17'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10 XP20"}. 'K-FunctionCallExpr-17a'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "matches(format-time(current-time(), \"[H01]:[m01]\", (), (), ()), \"..:..\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-17a.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_true(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-18'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "matches(format-dateTime(current-dateTime(), \"[Y0001]-[M01]-[D01]\"), \"[0-9]{4}-[0-9]{2}-[0-9]{2}\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-18.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_true(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-19'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "matches(format-dateTime(current-dateTime(), \"[Y0001]-[M01]-[D01]\", (), (), ()), \"....-..-..\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-19.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_true(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-20'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "matches(format-dateTime(current-dateTime(), \"[M01]/[D01]/[Y0001] at [H01]:[m01]:[s01]\"), \"[0-1][0-9]/[0-3][0-9]/[0-9]{4} at [0-9]{2}:[0-9]{2}:[0-9]{2}\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-20.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_true(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-21'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "matches(format-dateTime(current-dateTime(), \"[M01]/[D01]/[Y0001] at [H01]:[m01]:[s01]\", (), (), ()), \"../../.... at ..:..:..\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-21.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_true(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-22'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "current()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-22.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-23'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "unparsed-entity-uri(\"example.com/file.ext\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-23.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-24'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "unparsed-entity-public-id(\"entity\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-24.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-25'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10"}. 'K-FunctionCallExpr-25a'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "generate-id(<a/>) castable as xs:NCName", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-25a.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_true(Res) of true -> {comment, "Empty"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-26'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "system-property(\"xsl:vendor\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-26.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-27'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "fn:escape-uri(\"http:/example.com/\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-27.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K-FunctionCallExpr-28'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "fn:sub-sequence(\"http:/example.com/\", 1, 1)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K-FunctionCallExpr-28.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-1'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:bar($c, $d, $e, $f, $g, $h, $i, $j, $a, $b) { 1 }; \n" " declare function local:moo($k) { $k }; \n" " local:moo(1)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-1.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_eq(Res, "1") of true -> {comment, "Equal"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-2'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "current-grouping-key()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-2.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-3'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "current()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-3.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-4'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "unparsed-entity-uri(\"str\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-4.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-5'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "unparsed-entity-public-id(\"str\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-5.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-6'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XQ10"}. 'K2-FunctionCallExpr-7'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XQ10"}. 'K2-FunctionCallExpr-8'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "system-property(\"property\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-8.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-9'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "key(\"id\")", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-9.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0017") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-10'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare variable $a := <a/>; \n" " declare function local:testSingleNodeIdentity($node as node()) { $node is $node }; \n" " declare function local:testDoubleNodeIdentity($a as node(), $b as node()) { $a is $b }; \n" " local:testSingleNodeIdentity(<a/>), local:testDoubleNodeIdentity(<a/>, <b/>), local:testDoubleNodeIdentity($a, $a)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-10.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "true false true") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-11'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:compare($arg1 as xs:string, $arg2 as xs:string) { \n" " let $cps1 := string-to-codepoints($arg1), \n" " $cps2 := string-to-codepoints($arg2) \n" " return abs(count($cps1) - count($cps2)) + sum(for $x in 1 to min((count($cps1), count($cps2))) \n" " return if ($cps1[$x] ne $cps2[$x]) then 1 else ()) }; \n" " local:compare(\"\", \"\"), \n" " local:compare(\"a\", \"\"), \n" " local:compare(\"\", \"a\"), \n" " local:compare(\"a\", \"a\"), \n" " local:compare(\"\", \"aa\"), \n" " local:compare(\"aa\", \"ab\"), \n" " local:compare(\"ba\", \"ba\"), \n" " local:compare(\"bab\", \"bbb\"), \n" " local:compare(\"aba\", \"bab\")\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-11.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "0 1 1 0 2 1 0 1 3") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-12'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:func1() { if(local:func2('b')) then 3 else local:func1() }; \n" " declare function local:func2($a) { if(matches(\"\",$a)) then () else 4 }; \n" " local:func1()", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-12.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_eq(Res, "3") of true -> {comment, "Equal"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'K2-FunctionCallExpr-13'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "declare function local:foo($arg) { local:foo(local:foo(1)) }; 1", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "K2-FunctionCallExpr-13.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_eq(Res, "1") of true -> {comment, "Equal"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'cbcl-promotion-001'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " string-join( (xs:anyURI(''), xs:anyURI('/')), ' ')\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "cbcl-promotion-001.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, " /") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'cbcl-promotion-002'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:index-of($seq as xs:double*, $item as xs:double) { for $x at $p in $seq return if ($x eq $item) then $p else () };\n" " declare function local:sequence($x as xs:integer) { (\"string\", 1, 2.0, xs:float(3))[$x] };\n" " local:index-of(for $x in (2,3,4) return local:sequence($x), 2)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "cbcl-promotion-002.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "2") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'cbcl-promotion-003'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:index-of($seq as xs:integer*, $item as xs:integer?) as xs:float* { \n" " if (empty($item)) \n" " then -1\n" " else for $x at $p in $seq return if ($x eq $item) then $p else () \n" " };\n" " local:index-of(1 to 10, 3)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "cbcl-promotion-003.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "3") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'cbcl-promotion-004'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:f() as xs:double* { \n" " if (day-from-date(current-date()) < 32) then xs:integer(3) else -1\n" " };\n" " local:f() + 1", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "cbcl-promotion-004.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "4") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'cbcl-promotion-005'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:index-of($seq, $item) as xs:double? { for $x at $p in $seq return if ($x eq $item) then $p else () };\n" " local:index-of((1, 2.0, xs:float(3), 2), 2)", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "cbcl-promotion-005.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPTY0004") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'cbcl-promotion-006'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:f($arg as xs:anyAtomicType?) { $arg };\n" " local:f(index-of((1,2,3,2),2))", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "cbcl-promotion-006.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPTY0004") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'cbcl-promotion-007'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare function local:f($v as xs:double*) as xs:double+ { if (empty($v)) then 0 else $v };\n" " declare function local:g($v as xs:double*) as xs:double+ { local:f($v) };\n" " local:g((1,2,3))", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "cbcl-promotion-007.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_string_value(Res, "1 2 3") of true -> {comment, "String correct"}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-001'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:attribute($arg) { fn:true() };\n" " attribute(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-001.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-002'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:comment($arg) { fn:true() };\n" " comment(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-002.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-003'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:document-node($arg) { fn:true() };\n" " document-node(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-003.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-004'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:element($arg) { fn:true() };\n" " element(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-004.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-005'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:empty-sequence() { fn:true() };\n" " empty-sequence()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-005.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-006'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:if() { fn:true() };\n" " if()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-006.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-007'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:item($arg) { fn:true() };\n" " item(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-007.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-008'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:node($arg) { fn:true() };\n" " node(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-008.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-009'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:processing-instruction($arg) { fn:true() };\n" " processing-instruction(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-009.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-010'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:schema-attribute() { fn:true() };\n" " schema-attribute()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-010.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-011'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:schema-element() { fn:true() };\n" " schema-element()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-011.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-012'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:text($arg) { fn:true() };\n" " text(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-012.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-013'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:typeswitch() { fn:true() };\n" " typeswitch()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-013.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-014'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10"}. 'function-call-reserved-function-names-015'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10"}. 'function-call-reserved-function-names-016'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10"}. 'function-call-reserved-function-names-017'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:function() { fn:true() };\n" " function()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-017.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-018'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:namespace-node($arg) { fn:true() };\n" " namespace-node(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-018.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XQST0134") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XQST0134 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-019'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:switch() { fn:true() };\n" " switch()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-019.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-020'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " attribute(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-020.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-021'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " comment(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-021.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-022'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " document-node(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-022.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-023'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " element(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-023.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-024'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " empty-sequence()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-024.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-025'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " if()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-025.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-026'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " item()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-026.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-027'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " node(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-027.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-028'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " processing-instruction(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-028.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-029'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " schema-attribute()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-029.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-030'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " schema-element()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-030.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-031'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " text(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-031.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-032'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " typeswitch()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-032.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-033'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XQ10"}. 'function-call-reserved-function-names-034'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20"}. 'function-call-reserved-function-names-035'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XQ10"}. 'function-call-reserved-function-names-036'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " function()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-036.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-037'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " namespace-node(1)\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-037.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case lists:any( fun ({comment, _}) -> true; (_) -> false end, [ case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case xqerl_test:assert_error(Res, "XQST0134") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XQST0134 " ++ binary_to_list(F)}; {false, F} -> F end ] ) of true -> {comment, "any-of"}; _ -> false end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-038'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " switch()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-038.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-039'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10 XQ30"}. 'function-call-reserved-function-names-040'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:array() { fn:true() };\n" " array()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-040.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-041'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XP30 XQ10 XQ30"}. 'function-call-reserved-function-names-042'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " array()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-042.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-043'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XQ10 XQ30"}. 'function-call-reserved-function-names-044'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " declare default function namespace \"-local-functions\";\n" " declare function local:map() { fn:true() };\n" " map()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-044.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end. 'function-call-reserved-function-names-045'(Config) -> __BaseDir = ?config(base_dir, Config), {skip, "spec:XP20 XP30 XQ10 XQ30"}. 'function-call-reserved-function-names-046'(Config) -> __BaseDir = ?config(base_dir, Config), Qry = "\n" " map()\n" " ", Qry1 = Qry, io:format("Qry1: ~p~n", [Qry1]), Res = try Mod = xqerl_code_server:compile( filename:join(__BaseDir, "function-call-reserved-function-names-046.xq"), Qry1 ), xqerl:run(Mod) of D -> D catch _:E -> E end, Out = case xqerl_test:assert_error(Res, "XPST0003") of true -> {comment, "Correct error"}; {true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)}; {false, F} -> F end, case Out of {comment, C} -> {comment, C}; Err -> ct:fail(Err) end.
f6b29cc75190c21e875caaad205c12c26b6245720bd95fa6bf5f69ec710a75d4
lucasvreis/org-mode-hs
Processing.hs
module Org.Exporters.Processing ( module Org.Exporters.Processing, module Org.Exporters.Processing.OrgData, module Org.Exporters.Processing.InternalLinks, module Org.Exporters.Processing.Prune, module Org.Exporters.Processing.SpecialStrings, module Org.Exporters.Processing.GatherKeywords, ) where import Org.Exporters.Processing.GatherKeywords import Org.Exporters.Processing.InternalLinks import Org.Exporters.Processing.OrgData import Org.Exporters.Processing.Prune import Org.Exporters.Processing.SpecialStrings withCurrentData :: F t -> M t withCurrentData x = do cdata <- fix . runReader <$> gets snd pure $ runReader x cdata runPipeline :: M (F t) -> (t, OrgData) runPipeline = continuePipeline initialOrgData continuePipeline :: OrgData -> M (F t) -> (t, OrgData) continuePipeline data' x = (runReader resolved datum, datum) where (resolved, (_, fix . runReader -> datum)) = runState x (initialResolveState, pure data')
null
https://raw.githubusercontent.com/lucasvreis/org-mode-hs/8eed3910638f379d55114995e0bc75a5915c4e98/org-exporters/src/Org/Exporters/Processing.hs
haskell
module Org.Exporters.Processing ( module Org.Exporters.Processing, module Org.Exporters.Processing.OrgData, module Org.Exporters.Processing.InternalLinks, module Org.Exporters.Processing.Prune, module Org.Exporters.Processing.SpecialStrings, module Org.Exporters.Processing.GatherKeywords, ) where import Org.Exporters.Processing.GatherKeywords import Org.Exporters.Processing.InternalLinks import Org.Exporters.Processing.OrgData import Org.Exporters.Processing.Prune import Org.Exporters.Processing.SpecialStrings withCurrentData :: F t -> M t withCurrentData x = do cdata <- fix . runReader <$> gets snd pure $ runReader x cdata runPipeline :: M (F t) -> (t, OrgData) runPipeline = continuePipeline initialOrgData continuePipeline :: OrgData -> M (F t) -> (t, OrgData) continuePipeline data' x = (runReader resolved datum, datum) where (resolved, (_, fix . runReader -> datum)) = runState x (initialResolveState, pure data')
1f54eb6932b23cb985f3468e2e3fb0dde4b16f16fc8a74935867436716587d2b
cedlemo/OCaml-GI-ctypes-bindings-generator
Widget_accessible_private.ml
open Ctypes open Foreign type t let t_typ : t structure typ = structure "Widget_accessible_private"
null
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Widget_accessible_private.ml
ocaml
open Ctypes open Foreign type t let t_typ : t structure typ = structure "Widget_accessible_private"
7987126c05f57233d5b285c256211b130dc92a99a4a25b39500c68d705171cc3
synrc/rest
serviceTask.erl
-module(serviceTask). -include_lib("bpe/include/bpe.hrl"). -compile({parse_transform, rest}). -compile(export_all). -rest_record(serviceTask). new() -> #serviceTask{}.
null
https://raw.githubusercontent.com/synrc/rest/d981292a6eb66ae02da5d5d9d8717c25d74a1d0b/src/bpe/serviceTask.erl
erlang
-module(serviceTask). -include_lib("bpe/include/bpe.hrl"). -compile({parse_transform, rest}). -compile(export_all). -rest_record(serviceTask). new() -> #serviceTask{}.
2749f389d1ab539854daf1785817b6d69a8020cfbf2f6a822d27a18acdb504cd
qnikst/okasaki
BatchedQueue.hs
module Data.BatchedQueue where import Data.Queue.Class data BatchedQueue a = BatchedQueue [a] [a] instance Queue BatchedQueue where empty = BatchedQueue [] [] isEmpty (BatchedQueue f r) = null r snoc (BatchedQueue f r) a = checkf f (a:r) head (BatchedQueue [] _) = error "empty" head (BatchedQueue (x:_) _) = x tail (BatchedQueue [] _) = error "emtpy" tail (BatchedQueue (x:f) r) = checkf f r checkf :: [a] -> [a] -> BatchedQueue a checkf [] r = BatchedQueue (reverse r) [] checkf h r = BatchedQueue h r
null
https://raw.githubusercontent.com/qnikst/okasaki/f6f3c4211df16e4dde3a5cb4d6aaf19a68b99b0e/ch05/Data/BatchedQueue.hs
haskell
module Data.BatchedQueue where import Data.Queue.Class data BatchedQueue a = BatchedQueue [a] [a] instance Queue BatchedQueue where empty = BatchedQueue [] [] isEmpty (BatchedQueue f r) = null r snoc (BatchedQueue f r) a = checkf f (a:r) head (BatchedQueue [] _) = error "empty" head (BatchedQueue (x:_) _) = x tail (BatchedQueue [] _) = error "emtpy" tail (BatchedQueue (x:f) r) = checkf f r checkf :: [a] -> [a] -> BatchedQueue a checkf [] r = BatchedQueue (reverse r) [] checkf h r = BatchedQueue h r
69ee31e4fc822d8a49e9854f3012b31466f48f357d06cac3daacda0791f422d2
basho/riak_test
pipe_verify_basics.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2012 Basho Technologies , Inc. %% This file is provided to you 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. %% %% ------------------------------------------------------------------- %% @doc Verify some basic things about riak_pipe. %% Important : this test loads this module on each Riak node , such that %% it can reference its functions in pipe workers. %% %% These tests used to be known as riak_pipe:basic_test_/0. -module(pipe_verify_basics). -export([ %% riak_test's entry confirm/0 ]). -include_lib("eunit/include/eunit.hrl"). -define(NODE_COUNT, 3). %% local copy of riak_pipe.hrl -include("rt_pipe.hrl"). confirm() -> lager:info("Build ~b node cluster", [?NODE_COUNT]), Nodes = rt:build_cluster(?NODE_COUNT), [rt:wait_for_service(Node, riak_pipe) || Node <- Nodes], rt:load_modules_on_nodes([?MODULE], Nodes), verify_order(Nodes), verify_trace_filtering(Nodes), verify_recursive_countdown_1(Nodes), verify_recursive_countdown_2(Nodes), rt_pipe:assert_no_zombies(Nodes), lager:info("~s: PASS", [atom_to_list(?MODULE)]), pass. @doc generic driver used as a riak_pipe : %% argument. Sends the input '1', then sends eoi. order_fun(Pipe) -> ok = riak_pipe:queue_work(Pipe, 1), riak_pipe:eoi(Pipe). @doc generic driver used as a riak_pipe : %% argument. Causes a fitting to pass as output, its input multiplied by two . mult_by_2(X) -> 2 * X. verify_order([RN|_]) -> lager:info("Verifying fittings operate in order"), AllLog = [{log, sink}, {trace, all}], {eoi, Res, Trace} = rpc:call(RN, riak_pipe, generic_transform, [fun mult_by_2/1, fun order_fun/1, AllLog, 5]), ?assertMatch([{_, 32}], Res), ?assertEqual(0, length(rt_pipe:extract_trace_errors(Trace))), Qed = rt_pipe:extract_queued(Trace), NOTE : The msg to the sink does n't appear in Trace ?assertEqual([1,2,4,8,16], [X || {_, X} <- Qed]). verify_trace_filtering([RN|_]) -> lager:info("Verify that trace messages are filtered"), {eoi, _Res, Trace1} = rpc:call(RN, riak_pipe, generic_transform, [fun mult_by_2/1, fun order_fun/1, [{log,sink}, {trace, [eoi]}], 5]), {eoi, _Res, Trace2} = rpc:call(RN, riak_pipe, generic_transform, [fun mult_by_2/1, fun order_fun/1, [{log,sink}, {trace, all}], 5]), %% Looking too deeply into the format of the trace %% messages, since they haven't gelled yet, is madness. ?assert(length(Trace1) < length(Trace2)). verify_recursive_countdown_1([RN|_]) -> lager:info("Verify recurse_input"), Spec = [#fitting_spec{name=counter, module=riak_pipe_w_rec_countdown}], Opts = [{sink, rt_pipe:self_sink()}], {ok, Pipe} = rpc:call(RN, riak_pipe, exec, [Spec, Opts]), ok = rpc:call(RN, riak_pipe, queue_work, [Pipe, 3]), riak_pipe:eoi(Pipe), {eoi, Res, []} = riak_pipe:collect_results(Pipe), ?assertEqual([{counter,0},{counter,1},{counter,2},{counter,3}], Res). verify_recursive_countdown_2([RN|_]) -> lager:info("Verify nondeterministic recurse_input"), verify_recursive_countdown_2(RN, 10). verify_recursive_countdown_2(RN, Retries) when Retries > 0 -> Spec = [#fitting_spec{name=counter, module=riak_pipe_w_rec_countdown, arg=testeoi}], Options = [{sink, rt_pipe:self_sink()},{trace,[restart]},{log,sink}], {ok, Pipe} = rpc:call(RN, riak_pipe, exec, [Spec, Options]), ok = rpc:call(RN, riak_pipe, queue_work, [Pipe, 3]), riak_pipe:eoi(Pipe), {eoi, Res, Trc} = riak_pipe:collect_results(Pipe), ?assertEqual([{counter,0},{counter,0},{counter,0}, {counter,1},{counter,2},{counter,3}], Res), case Trc of [{counter,{trace,[restart],{vnode,{restart,_}}}}] -> ok; [] -> lager:info("recursive countdown test #2 did not" " trigger the done/eoi race it tests." " Retries left: ~b", [Retries-1]), verify_recursive_countdown_2(RN, Retries-1) end; verify_recursive_countdown_2(_, _) -> lager:warning("recursive countdown test #2 did not" " trigger the done/eoi race it tests." " Consider re-running.").
null
https://raw.githubusercontent.com/basho/riak_test/8170137b283061ba94bc85bf42575021e26c929d/tests/pipe_verify_basics.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- @doc Verify some basic things about riak_pipe. it can reference its functions in pipe workers. These tests used to be known as riak_pipe:basic_test_/0. riak_test's entry local copy of riak_pipe.hrl argument. Sends the input '1', then sends eoi. argument. Causes a fitting to pass as output, its input multiplied Looking too deeply into the format of the trace messages, since they haven't gelled yet, is madness.
Copyright ( c ) 2012 Basho Technologies , Inc. This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY Important : this test loads this module on each Riak node , such that -module(pipe_verify_basics). -export([ confirm/0 ]). -include_lib("eunit/include/eunit.hrl"). -define(NODE_COUNT, 3). -include("rt_pipe.hrl"). confirm() -> lager:info("Build ~b node cluster", [?NODE_COUNT]), Nodes = rt:build_cluster(?NODE_COUNT), [rt:wait_for_service(Node, riak_pipe) || Node <- Nodes], rt:load_modules_on_nodes([?MODULE], Nodes), verify_order(Nodes), verify_trace_filtering(Nodes), verify_recursive_countdown_1(Nodes), verify_recursive_countdown_2(Nodes), rt_pipe:assert_no_zombies(Nodes), lager:info("~s: PASS", [atom_to_list(?MODULE)]), pass. @doc generic driver used as a riak_pipe : order_fun(Pipe) -> ok = riak_pipe:queue_work(Pipe, 1), riak_pipe:eoi(Pipe). @doc generic driver used as a riak_pipe : by two . mult_by_2(X) -> 2 * X. verify_order([RN|_]) -> lager:info("Verifying fittings operate in order"), AllLog = [{log, sink}, {trace, all}], {eoi, Res, Trace} = rpc:call(RN, riak_pipe, generic_transform, [fun mult_by_2/1, fun order_fun/1, AllLog, 5]), ?assertMatch([{_, 32}], Res), ?assertEqual(0, length(rt_pipe:extract_trace_errors(Trace))), Qed = rt_pipe:extract_queued(Trace), NOTE : The msg to the sink does n't appear in Trace ?assertEqual([1,2,4,8,16], [X || {_, X} <- Qed]). verify_trace_filtering([RN|_]) -> lager:info("Verify that trace messages are filtered"), {eoi, _Res, Trace1} = rpc:call(RN, riak_pipe, generic_transform, [fun mult_by_2/1, fun order_fun/1, [{log,sink}, {trace, [eoi]}], 5]), {eoi, _Res, Trace2} = rpc:call(RN, riak_pipe, generic_transform, [fun mult_by_2/1, fun order_fun/1, [{log,sink}, {trace, all}], 5]), ?assert(length(Trace1) < length(Trace2)). verify_recursive_countdown_1([RN|_]) -> lager:info("Verify recurse_input"), Spec = [#fitting_spec{name=counter, module=riak_pipe_w_rec_countdown}], Opts = [{sink, rt_pipe:self_sink()}], {ok, Pipe} = rpc:call(RN, riak_pipe, exec, [Spec, Opts]), ok = rpc:call(RN, riak_pipe, queue_work, [Pipe, 3]), riak_pipe:eoi(Pipe), {eoi, Res, []} = riak_pipe:collect_results(Pipe), ?assertEqual([{counter,0},{counter,1},{counter,2},{counter,3}], Res). verify_recursive_countdown_2([RN|_]) -> lager:info("Verify nondeterministic recurse_input"), verify_recursive_countdown_2(RN, 10). verify_recursive_countdown_2(RN, Retries) when Retries > 0 -> Spec = [#fitting_spec{name=counter, module=riak_pipe_w_rec_countdown, arg=testeoi}], Options = [{sink, rt_pipe:self_sink()},{trace,[restart]},{log,sink}], {ok, Pipe} = rpc:call(RN, riak_pipe, exec, [Spec, Options]), ok = rpc:call(RN, riak_pipe, queue_work, [Pipe, 3]), riak_pipe:eoi(Pipe), {eoi, Res, Trc} = riak_pipe:collect_results(Pipe), ?assertEqual([{counter,0},{counter,0},{counter,0}, {counter,1},{counter,2},{counter,3}], Res), case Trc of [{counter,{trace,[restart],{vnode,{restart,_}}}}] -> ok; [] -> lager:info("recursive countdown test #2 did not" " trigger the done/eoi race it tests." " Retries left: ~b", [Retries-1]), verify_recursive_countdown_2(RN, Retries-1) end; verify_recursive_countdown_2(_, _) -> lager:warning("recursive countdown test #2 did not" " trigger the done/eoi race it tests." " Consider re-running.").
4c595965cf0e82ad88aa270190e60b7113e23f1fc240edb2436025cc4deca15a
re-ops/re-core
repl.clj
(ns re-core.repl "Repl Driven re-core" (:refer-clojure :exclude [list update sync]) (:require [re-core.model :refer (figure-virt)] [re-core.repl.terminal :refer (launch-ssh)] [clojure.core.strint :refer (<<)] [re-core.repl.base :refer (refer-base)] [re-core.repl.systems :refer (refer-systems)] [re-core.presets.systems :as sp] [re-core.presets.types :as tp] [re-share.config.core :as c] [re-core.repl.types :refer (refer-types)]) (:import [re_mote.repl.base Hosts] [re_core.repl.base Types Systems])) (refer-base) (refer-systems) (refer-types) (def systems (Systems.)) (def types (Types.)) ; Filtering functions (defn hyp "Get instances by hypervisor type: (start (hyp :lxc))" [v] (fn [[_ m]] (= (figure-virt m) v))) (defn typed "Get instances by type: (start (by-type :redis))" [t] (fn [[_ {:keys [type] :as m}]] (= type t))) (defn ip "Pick systems that has ip addresses (they are running) (stop ip)" [[_ {:keys [machine] :as m}]] (machine :ip)) (defn with-ips "Pick systems with specific ips: (stop (with-ip \"10.0.0.4\"))" [ips] (fn [[_ {:keys [machine]}]] ((into #{} ips) (machine :ip)))) (defn with-ids "Pick systems using multiple ids: (provision (with-ids [\"Bar\" \"Foo\"]))" [ids] (fn [[id _]] ((into #{} (map str ids)) (str id)))) (defn matching "Match instances by partial id matching (ala git): (provision (matching \"A17_\"))" [part] {:pre [(not (clojure.string/blank? part))]} (fn [[id _]] (.contains id part))) (defn named "Match instances by hostname matching: (provision (named \"foo\"))" [names] {:pre [(sequential? names)]} (fn [[_ {:keys [machine]}]] ((into #{} names) (machine :hostname)))) (defn match-kv "Match instances by kv pair: (provision (match-kv [:machine :os] :ubuntu-18.04))" [ks v] (fn [[_ m]] (= (get-in m ks) v))) ; management (defn reload "Reload (stop destroy and up): (reload) ; reload all running instances (reload (by-type :redis)) ; reload all redis instances" ([] (reload ip)) ([f] (run (ls systems) | (filter-by f) | (sys/reload) | (async-wait pretty-print "reload")))) (defn clear "Clear only the model (VM won't be deleted): (clear) ; clear all systems (both runnging and non running) (clear (by-type :redis)) ; clear systems with redis type (clear identity :types) ; clear all types (clear (fn [[t _]] (= t \"redis\") :types)) ; clear the redis type " ([] (clear identity :systems {})) ([f] (clear f :systems {})) ([f on] (clear f on {})) ([f on opts] (case on :systems (run (ls systems) | (filter-by f) | (ack opts) | (rm) | (pretty)) :types (run (ls types) | (filter-by f) | (rm) | (pretty))))) (defn destroy "Destroy instances (both clear and remove VM): (destroy) ; remove all instances (both running and non running) (destroy ip) ; remove running instances only remove all instances with an i d containing (destroy ip {:force true}) ; remove running instances only without confirmation" ([] (destroy identity {})) ([f] (destroy f {})) ([f opts] (run (ls systems) | (filter-by f) | (ack opts) | (sys/destroy) | (async-wait pretty-print "destroy")))) (defn halt "Halt instances: (halt) ; halt all running (have ip) " ([] (halt ip)) ([f] (halt f {})) ([f opts] (run (ls systems) | (filter-by f) | (ack opts) | (sys/stop) | (async-wait pretty-print "halt")))) (defn start "Start instances: (start) ; start all without ip (stopped) (start (by-type :redis)) ; start all redis types" ([] (start (comp not ip))) ([f] (run (ls systems) | (filter-by f) | (sys/start) | (async-wait pretty-print "start")))) (defn list "List available instances: (list) ; list all systems (list ip) ; list all systems that have an ip (running) (list identity :types) ; list all types (list ip :systems print? false); return matched systems without printing them " ([] (list identity :systems)) ([f] (list f :systems)) ([f on & {:keys [print?] :or {print? true}}] (if print? (case on :systems (run (ls systems) | (filter-by f) | (pretty)) :types (run (ls types) | (pretty))) (case on :systems (run (ls systems) | (filter-by f)) :types (ls types))))) (defn hosts "Convert systems into re-mote hosts: All systems using ip address: (hosts) Use re-gent addresses by grabbing hostname (cpu-persist (hosts ip :hostname))) All redis instances using hostname (hosts (by-type :redis) :hostname) " ([] (hosts ip :ip)) ([f k] (run (ls systems) | (filter-by f) | (into-hosts k)))) (defn provision "Provision VM: Provision all running instances: (provision) Provision using filter fn: (provision (fn [{:keys [type]] (= type :redis))) " ([] (provision ip)) ([f] (run (ls systems) | (filter-by f) | (sys/provision) | (async-wait pretty-print "provision")))) (defn- create-system "Create a system internal implementation" [base args] (run (valid? systems base args) | (add-) | (sys/create) | (async-wait pretty-print "create"))) (defn- create-type "Create type internal implementation" [base args] (let [ms (tp/validate (tp/materialize-preset base args))] (if-not (empty? (ms false)) (ms false) (run (add- types [(ms true)]) | (pretty))))) (defn create "Creating system/type instances by using presets to quickly pick their properties. Kvm instance using defaults user using c1-medium ram/cpu allocation: (create kvm defaults c1-medium local :redis) 5 instance in one go: (create kvm defaults c1-medium local :redis 5) Using a custom hostname: (create kvm defaults c1-medium local \"furry\" :redis) Using a KVM volume: (create kvm defaults c1-medium local vol-128G :redis) Custom os (using default machine): (create kvm default-machine c1-medium (os :ubuntu-18.04-dekstop) :redis) Type instances: (create cog 're-cipes.profiles/osquery default-src :osquery \"osquery type\") ; using default src directory " [base & args] (cond (:machine base) (create-system base args) (:cog base) (create-type base args) :else (throw (ex-info "No matching creation logic found" {:base base :args args})))) (defn add "Add existing system instances: ; Adding an existing KVM VM: (add kvm default-machine local large (os :ubuntu-desktop-20.04) (with-host \"foo\") :base \"Existing base instance\") ; Add a physical machine: (add physical (os :debian-10.0) (machine \"re-ops\" \"local\") :base \"A basic physical instance\") " [base & args] (let [{:keys [fns total type hostname]} (sp/into-spec {} args) transforms [(sp/with-type type) (sp/with-host hostname)] all (apply conj transforms fns) specs (map (fn [_] (reduce (fn [m f] (f m)) base all)) (range (or total 1)))] (run (valid? systems base args) | (add-) | (pretty-print "add")))) (defn sync "Sync existing instances into re-core systems: (sync :digital-ocean) (sync :kvm :active true) ; using options (sync :physical {:pivot rosetta :network \"192.168.1.0/24\" :user \"re-ops\"}) ; nmap based sync " ([hyp] (sync hyp {})) ([hyp opts] (run (synch systems hyp opts) | (pretty)))) (defn fill "fill systems information from provided ks v pair (fill identity [:machine :os] :ubuntu-18.04) " [f ks v] (run (ls systems) | (filter-by f) | (update-systems ks v))) (defn ssh-into "SSH into instances (open a terminal window): (ssh-into)" ([] (ssh-into identity)) ([f] (let [{:keys [auth] :as hs} (hosts f :ip)] (doseq [host (:hosts hs)] (let [target (<< "~(auth :user)@~{host}") private-key (c/get! :shared :ssh :private-key-path)] (launch-ssh target private-key)))))) (defn spice-into "Open remote spice connection to KVM instances (using spice): (spice-into (by-type :desktop))" ([] (spice-into identity)) ([f] (run (ls systems) | (filter-by f) | (filter-by (fn [[_ m]] (contains? m :kvm))) | (spice) | (pretty-print "spice"))))
null
https://raw.githubusercontent.com/re-ops/re-core/e13490aedd6d34ff01f11b28adf359beb5c0bb5b/src/re_core/repl.clj
clojure
Filtering functions management reload all running instances reload all redis instances" clear all systems (both runnging and non running) clear systems with redis type clear all types clear the redis type remove all instances (both running and non running) remove running instances only remove running instances only without confirmation" halt all running (have ip) start all without ip (stopped) start all redis types" list all systems list all systems that have an ip (running) list all types return matched systems without printing them using default src directory Adding an existing KVM VM: Add a physical machine: using options nmap based sync "
(ns re-core.repl "Repl Driven re-core" (:refer-clojure :exclude [list update sync]) (:require [re-core.model :refer (figure-virt)] [re-core.repl.terminal :refer (launch-ssh)] [clojure.core.strint :refer (<<)] [re-core.repl.base :refer (refer-base)] [re-core.repl.systems :refer (refer-systems)] [re-core.presets.systems :as sp] [re-core.presets.types :as tp] [re-share.config.core :as c] [re-core.repl.types :refer (refer-types)]) (:import [re_mote.repl.base Hosts] [re_core.repl.base Types Systems])) (refer-base) (refer-systems) (refer-types) (def systems (Systems.)) (def types (Types.)) (defn hyp "Get instances by hypervisor type: (start (hyp :lxc))" [v] (fn [[_ m]] (= (figure-virt m) v))) (defn typed "Get instances by type: (start (by-type :redis))" [t] (fn [[_ {:keys [type] :as m}]] (= type t))) (defn ip "Pick systems that has ip addresses (they are running) (stop ip)" [[_ {:keys [machine] :as m}]] (machine :ip)) (defn with-ips "Pick systems with specific ips: (stop (with-ip \"10.0.0.4\"))" [ips] (fn [[_ {:keys [machine]}]] ((into #{} ips) (machine :ip)))) (defn with-ids "Pick systems using multiple ids: (provision (with-ids [\"Bar\" \"Foo\"]))" [ids] (fn [[id _]] ((into #{} (map str ids)) (str id)))) (defn matching "Match instances by partial id matching (ala git): (provision (matching \"A17_\"))" [part] {:pre [(not (clojure.string/blank? part))]} (fn [[id _]] (.contains id part))) (defn named "Match instances by hostname matching: (provision (named \"foo\"))" [names] {:pre [(sequential? names)]} (fn [[_ {:keys [machine]}]] ((into #{} names) (machine :hostname)))) (defn match-kv "Match instances by kv pair: (provision (match-kv [:machine :os] :ubuntu-18.04))" [ks v] (fn [[_ m]] (= (get-in m ks) v))) (defn reload "Reload (stop destroy and up): ([] (reload ip)) ([f] (run (ls systems) | (filter-by f) | (sys/reload) | (async-wait pretty-print "reload")))) (defn clear "Clear only the model (VM won't be deleted): " ([] (clear identity :systems {})) ([f] (clear f :systems {})) ([f on] (clear f on {})) ([f on opts] (case on :systems (run (ls systems) | (filter-by f) | (ack opts) | (rm) | (pretty)) :types (run (ls types) | (filter-by f) | (rm) | (pretty))))) (defn destroy "Destroy instances (both clear and remove VM): remove all instances with an i d containing ([] (destroy identity {})) ([f] (destroy f {})) ([f opts] (run (ls systems) | (filter-by f) | (ack opts) | (sys/destroy) | (async-wait pretty-print "destroy")))) (defn halt "Halt instances: " ([] (halt ip)) ([f] (halt f {})) ([f opts] (run (ls systems) | (filter-by f) | (ack opts) | (sys/stop) | (async-wait pretty-print "halt")))) (defn start "Start instances: ([] (start (comp not ip))) ([f] (run (ls systems) | (filter-by f) | (sys/start) | (async-wait pretty-print "start")))) (defn list "List available instances: " ([] (list identity :systems)) ([f] (list f :systems)) ([f on & {:keys [print?] :or {print? true}}] (if print? (case on :systems (run (ls systems) | (filter-by f) | (pretty)) :types (run (ls types) | (pretty))) (case on :systems (run (ls systems) | (filter-by f)) :types (ls types))))) (defn hosts "Convert systems into re-mote hosts: All systems using ip address: (hosts) Use re-gent addresses by grabbing hostname (cpu-persist (hosts ip :hostname))) All redis instances using hostname (hosts (by-type :redis) :hostname) " ([] (hosts ip :ip)) ([f k] (run (ls systems) | (filter-by f) | (into-hosts k)))) (defn provision "Provision VM: Provision all running instances: (provision) Provision using filter fn: (provision (fn [{:keys [type]] (= type :redis))) " ([] (provision ip)) ([f] (run (ls systems) | (filter-by f) | (sys/provision) | (async-wait pretty-print "provision")))) (defn- create-system "Create a system internal implementation" [base args] (run (valid? systems base args) | (add-) | (sys/create) | (async-wait pretty-print "create"))) (defn- create-type "Create type internal implementation" [base args] (let [ms (tp/validate (tp/materialize-preset base args))] (if-not (empty? (ms false)) (ms false) (run (add- types [(ms true)]) | (pretty))))) (defn create "Creating system/type instances by using presets to quickly pick their properties. Kvm instance using defaults user using c1-medium ram/cpu allocation: (create kvm defaults c1-medium local :redis) 5 instance in one go: (create kvm defaults c1-medium local :redis 5) Using a custom hostname: (create kvm defaults c1-medium local \"furry\" :redis) Using a KVM volume: (create kvm defaults c1-medium local vol-128G :redis) Custom os (using default machine): (create kvm default-machine c1-medium (os :ubuntu-18.04-dekstop) :redis) Type instances: " [base & args] (cond (:machine base) (create-system base args) (:cog base) (create-type base args) :else (throw (ex-info "No matching creation logic found" {:base base :args args})))) (defn add "Add existing system instances: (add kvm default-machine local large (os :ubuntu-desktop-20.04) (with-host \"foo\") :base \"Existing base instance\") (add physical (os :debian-10.0) (machine \"re-ops\" \"local\") :base \"A basic physical instance\") " [base & args] (let [{:keys [fns total type hostname]} (sp/into-spec {} args) transforms [(sp/with-type type) (sp/with-host hostname)] all (apply conj transforms fns) specs (map (fn [_] (reduce (fn [m f] (f m)) base all)) (range (or total 1)))] (run (valid? systems base args) | (add-) | (pretty-print "add")))) (defn sync "Sync existing instances into re-core systems: (sync :digital-ocean) ([hyp] (sync hyp {})) ([hyp opts] (run (synch systems hyp opts) | (pretty)))) (defn fill "fill systems information from provided ks v pair (fill identity [:machine :os] :ubuntu-18.04) " [f ks v] (run (ls systems) | (filter-by f) | (update-systems ks v))) (defn ssh-into "SSH into instances (open a terminal window): (ssh-into)" ([] (ssh-into identity)) ([f] (let [{:keys [auth] :as hs} (hosts f :ip)] (doseq [host (:hosts hs)] (let [target (<< "~(auth :user)@~{host}") private-key (c/get! :shared :ssh :private-key-path)] (launch-ssh target private-key)))))) (defn spice-into "Open remote spice connection to KVM instances (using spice): (spice-into (by-type :desktop))" ([] (spice-into identity)) ([f] (run (ls systems) | (filter-by f) | (filter-by (fn [[_ m]] (contains? m :kvm))) | (spice) | (pretty-print "spice"))))
c63fba0b3a97de2b5c46b24bfd27cc6992adce1c2ba21320e6acb49c166d42af
msantos/tunctl
tunctl_freebsd.erl
Copyright ( c ) 2011 - 2022 < > . All %%% rights reserved. %%% %%% Redistribution and use in source and binary forms, with or without %%% modification, are permitted provided that the following conditions %%% are met: %%% 1 . Redistributions of source code must retain the above copyright notice , %%% this list of conditions and the following disclaimer. %%% 2 . Redistributions in binary form must reproduce the above copyright %%% notice, this list of conditions and the following disclaimer in the %%% documentation and/or other materials provided with the distribution. %%% 3 . Neither the name of the copyright holder nor the names of its %%% contributors may be used to endorse or promote products derived from %%% this software without specific prior written permission. %%% %%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT %%% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR %%% A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR %%% PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING %%% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS %%% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -module(tunctl_freebsd). %% Uses the legacy tun/tap interface (rather than interface cloning) %% net.link.(tun|tap).devfs_cloning must be non-zero to use. -include("tuntap.hrl"). -include_lib("procket/include/ioctl.hrl"). -include_lib("procket/include/procket.hrl"). -export([ create/2, persist/2, owner/2, group/2, header/1 ]). -define(SIZEOF_STRUCT_IFALIASREQ, 64). -define(SIOCAIFADDR, ?IOW($i, 26, ?SIZEOF_STRUCT_IFALIASREQ)). -define(TAPGIFNAME, ?IOR($t, 93, ?SIZEOF_STRUCT_IFREQ)). -define(TUNSIFHEAD, ?IOW($t, 96, ?SIZEOF_INT)). %%-------------------------------------------------------------------- %%% Exports %%-------------------------------------------------------------------- create(<<>>, Opt) -> create(<<"tap0">>, Opt); %% Ignore the options for now create(Ifname, Opt) when byte_size(Ifname) < ?IFNAMSIZ -> case procket:dev(binary_to_list(Ifname)) of {ok, FD} -> create_1(FD, Ifname, Opt); Error -> Error end. create_1(FD, Ifname, Opt) -> case {Ifname, proplists:get_bool(no_pi, Opt)} of {<<"tun", _/binary>>, false} -> ok = tunctl:ioctl(FD, ?TUNSIFHEAD, 1); _ -> TUNSIFHEAD is n't supported by tap devices ok end, {ok, FD, Ifname}. %% N/A persist(_FD, _Status) -> ok. owner(_FD, _Owner) -> ok. group(__FD, _Group) -> ok. header(<<?UINT32(Proto), Buf/binary>>) -> {tun_pi, 0, Proto, Buf}. %%-------------------------------------------------------------------- Internal functions %%--------------------------------------------------------------------
null
https://raw.githubusercontent.com/msantos/tunctl/26c42df28a1734750c992c3a8d954335b57088ac/src/tunctl_freebsd.erl
erlang
rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Uses the legacy tun/tap interface (rather than interface cloning) net.link.(tun|tap).devfs_cloning must be non-zero to use. -------------------------------------------------------------------- Exports -------------------------------------------------------------------- Ignore the options for now N/A -------------------------------------------------------------------- --------------------------------------------------------------------
Copyright ( c ) 2011 - 2022 < > . All 1 . Redistributions of source code must retain the above copyright notice , 2 . Redistributions in binary form must reproduce the above copyright 3 . Neither the name of the copyright holder nor the names of its " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING -module(tunctl_freebsd). -include("tuntap.hrl"). -include_lib("procket/include/ioctl.hrl"). -include_lib("procket/include/procket.hrl"). -export([ create/2, persist/2, owner/2, group/2, header/1 ]). -define(SIZEOF_STRUCT_IFALIASREQ, 64). -define(SIOCAIFADDR, ?IOW($i, 26, ?SIZEOF_STRUCT_IFALIASREQ)). -define(TAPGIFNAME, ?IOR($t, 93, ?SIZEOF_STRUCT_IFREQ)). -define(TUNSIFHEAD, ?IOW($t, 96, ?SIZEOF_INT)). create(<<>>, Opt) -> create(<<"tap0">>, Opt); create(Ifname, Opt) when byte_size(Ifname) < ?IFNAMSIZ -> case procket:dev(binary_to_list(Ifname)) of {ok, FD} -> create_1(FD, Ifname, Opt); Error -> Error end. create_1(FD, Ifname, Opt) -> case {Ifname, proplists:get_bool(no_pi, Opt)} of {<<"tun", _/binary>>, false} -> ok = tunctl:ioctl(FD, ?TUNSIFHEAD, 1); _ -> TUNSIFHEAD is n't supported by tap devices ok end, {ok, FD, Ifname}. persist(_FD, _Status) -> ok. owner(_FD, _Owner) -> ok. group(__FD, _Group) -> ok. header(<<?UINT32(Proto), Buf/binary>>) -> {tun_pi, 0, Proto, Buf}. Internal functions
c452ad428fc6dcca6e656e020c8413dd09ce67b7981424a959228d9e13874807
dbuenzli/hyperbib
user_service.mli
--------------------------------------------------------------------------- Copyright ( c ) 2021 University of Bern . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2021 University of Bern. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) open Hyperbib.Std val v : Service.sub Kurl.service --------------------------------------------------------------------------- Copyright ( c ) 2021 University of Bern Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2021 University of Bern Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/dbuenzli/hyperbib/bea0ee2c35fac11fdb856c914edd846fb4a8f709/src/service/user_service.mli
ocaml
--------------------------------------------------------------------------- Copyright ( c ) 2021 University of Bern . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2021 University of Bern. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) open Hyperbib.Std val v : Service.sub Kurl.service --------------------------------------------------------------------------- Copyright ( c ) 2021 University of Bern Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2021 University of Bern Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
a2861c011ad5d53ca0cf74ae411ec267be2a357af9543a58062bfbefd2d67174
emaphis/HtDP2e-solutions
04_Ufo.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname 04_Ufo) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) HtDP 2e - 4 Enumerations and Intervals 4.4 Intervals ;; ufo example (require 2htdp/image) (require 2htdp/universe) WorldState is a Number ; interperatation: number of pixels between the top and the UFO A WorldState falls into one of three intervals : ; – between 0 and CLOSE ; – between CLOSE and HEIGHT ; – below HEIGHT #; (define (fn-for-ws ws) ;; template (cond [(<= 0 ws CLOSE) (... ws)] [(and (< CLOSE ws) (<= ws HEIGHT)) (... ws)] [(> ws HEIGHT) (...)])) ;; constants: (define WIDTH 300) (define HEIGHT 100) (define CLOSE (/ HEIGHT 3)) ;; visual constants: (define MTSCN (empty-scene WIDTH HEIGHT)) (define UFO (overlay (circle 10 "solid" "green") (rectangle 40 2 "solid" "green"))) ;; functions ; run program ; WorldState -> WorldState ;; run: (main 0) (define (main y0) (big-bang y0 [on-tick nxt .2] [to-draw render])) ;; WorldState -> WorldState ;; compute next location of UFO (check-expect (nxt 11) 14) (define (nxt y) (+ y 3)) ; WorldState -> Image place UFO at given height into the center of MTSCN (check-expect (render 11) (place-image UFO (/ WIDTH 2) 11 MTSCN)) (define (render y) (place-image UFO (/ WIDTH 2) y MTSCN)) ;; Sample Problem -- Status Line ; WorldState -> Image ; add a status line to the scene create by render Figure 27 . (check-expect (render/status 10) (place-image (text "descending" 11 "green") 20 20 (render 10))) (check-expect (render/status 42) (place-image (text "closing in" 11 "orange") 20 20 (render 42))) (check-expect (render/status 101) (place-image (text "landed" 11 "red") 20 20 (render 101))) (define (render/status y) (place-image (cond [(<= 0 y CLOSE) (text "descending" 11 "green")] [(and (< CLOSE y) (<= y HEIGHT)) (text "closing in" 11 "orange")] [(> y HEIGHT) (text "landed" 11 "red")]) 20 20 (render y))) ; WorldState -> WorldState (define (main1 y0) (big-bang y0 [on-tick nxt .2] [to-draw render/status])) ( main1 0 )
null
https://raw.githubusercontent.com/emaphis/HtDP2e-solutions/ecb60b9a7bbf9b8999c0122b6ea152a3301f0a68/1-Fixed-Size-Data/04-Intervals/04_Ufo.rkt
racket
about the language level of this file in a form that our tools can easily process. ufo example interperatation: number of pixels between the top and the UFO – between 0 and CLOSE – between CLOSE and HEIGHT – below HEIGHT template constants: visual constants: functions run program WorldState -> WorldState run: (main 0) WorldState -> WorldState compute next location of UFO WorldState -> Image Sample Problem -- Status Line WorldState -> Image add a status line to the scene create by render WorldState -> WorldState
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname 04_Ufo) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) HtDP 2e - 4 Enumerations and Intervals 4.4 Intervals (require 2htdp/image) (require 2htdp/universe) WorldState is a Number A WorldState falls into one of three intervals : (cond [(<= 0 ws CLOSE) (... ws)] [(and (< CLOSE ws) (<= ws HEIGHT)) (... ws)] [(> ws HEIGHT) (...)])) (define WIDTH 300) (define HEIGHT 100) (define CLOSE (/ HEIGHT 3)) (define MTSCN (empty-scene WIDTH HEIGHT)) (define UFO (overlay (circle 10 "solid" "green") (rectangle 40 2 "solid" "green"))) (define (main y0) (big-bang y0 [on-tick nxt .2] [to-draw render])) (check-expect (nxt 11) 14) (define (nxt y) (+ y 3)) place UFO at given height into the center of MTSCN (check-expect (render 11) (place-image UFO (/ WIDTH 2) 11 MTSCN)) (define (render y) (place-image UFO (/ WIDTH 2) y MTSCN)) Figure 27 . (check-expect (render/status 10) (place-image (text "descending" 11 "green") 20 20 (render 10))) (check-expect (render/status 42) (place-image (text "closing in" 11 "orange") 20 20 (render 42))) (check-expect (render/status 101) (place-image (text "landed" 11 "red") 20 20 (render 101))) (define (render/status y) (place-image (cond [(<= 0 y CLOSE) (text "descending" 11 "green")] [(and (< CLOSE y) (<= y HEIGHT)) (text "closing in" 11 "orange")] [(> y HEIGHT) (text "landed" 11 "red")]) 20 20 (render y))) (define (main1 y0) (big-bang y0 [on-tick nxt .2] [to-draw render/status])) ( main1 0 )
9e44f3af77c950ab27032a85f88931e0ad3fb79db3fdb124ea275c4898516f27
sadiqj/ocaml-esp32
exec_tests.ml
let values = [ " верблюды " "\xE9\xAA\x86\xE9\xA9\xBC"; (* "骆驼" *) " " "\216\167\217\136\217\134\217\185"; (* "اونٹ" *) ] let env0 = List.sort compare (List.mapi (fun i v -> Printf.sprintf "OCAML_UTF8_VAR%d=%s" i v) values) let split sep s = match String.index s sep with | i -> String.sub s 0 i, String.sub s (i + 1) (String.length s - i - 1) | exception Not_found -> s, "" let test_environment () = print_endline "test_environment"; let vars = List.map (fun s -> fst (split '=' s)) env0 in let f s = List.mem (fst (split '=' s)) vars in let env = List.filter f (Array.to_list (Unix.environment ())) in assert (List.length env0 = List.length env); List.iter2 (fun s1 s2 -> assert (s1 = s2)) env0 env let test0 () = print_endline "test0"; Unix.execve Sys.executable_name [|Sys.executable_name; "1"|] (Array.of_list env0) let test_argv () = print_endline "test_argv"; let argv = match Array.to_list Sys.argv with _ :: _ :: argv -> argv | _ -> assert false in List.iter2 (fun s1 s2 -> assert (s1 = s2)) argv values let test1 () = print_endline "test1"; Unix.execv Sys.executable_name (Array.of_list (Sys.executable_name :: "2" :: values)) let restart = function | 0 -> test0 () | 1 -> test_environment (); test1 () | 2 -> test_argv () | _ -> assert false let main () = match Array.length Sys.argv with | 1 -> let pid = Unix.create_process Sys.executable_name [|Sys.executable_name; "0"|] Unix.stdin Unix.stdout Unix.stderr in begin match Unix.waitpid [] pid with | _, Unix.WEXITED 0 -> () | _, (Unix.WEXITED _ | Unix.WSIGNALED _ | Unix.WSTOPPED _) -> failwith "Child process error" end | _ -> restart (int_of_string Sys.argv.(1)) let () = match main () with | () -> Printf.printf "OK\n%!" | exception e -> Printf.printf "BAD: %s\n%!" (Printexc.to_string e); exit 1
null
https://raw.githubusercontent.com/sadiqj/ocaml-esp32/33aad4ca2becb9701eb90d779c1b1183aefeb578/testsuite/tests/win-unicode/exec_tests.ml
ocaml
"骆驼" "اونٹ"
let values = [ " верблюды " " " ] let env0 = List.sort compare (List.mapi (fun i v -> Printf.sprintf "OCAML_UTF8_VAR%d=%s" i v) values) let split sep s = match String.index s sep with | i -> String.sub s 0 i, String.sub s (i + 1) (String.length s - i - 1) | exception Not_found -> s, "" let test_environment () = print_endline "test_environment"; let vars = List.map (fun s -> fst (split '=' s)) env0 in let f s = List.mem (fst (split '=' s)) vars in let env = List.filter f (Array.to_list (Unix.environment ())) in assert (List.length env0 = List.length env); List.iter2 (fun s1 s2 -> assert (s1 = s2)) env0 env let test0 () = print_endline "test0"; Unix.execve Sys.executable_name [|Sys.executable_name; "1"|] (Array.of_list env0) let test_argv () = print_endline "test_argv"; let argv = match Array.to_list Sys.argv with _ :: _ :: argv -> argv | _ -> assert false in List.iter2 (fun s1 s2 -> assert (s1 = s2)) argv values let test1 () = print_endline "test1"; Unix.execv Sys.executable_name (Array.of_list (Sys.executable_name :: "2" :: values)) let restart = function | 0 -> test0 () | 1 -> test_environment (); test1 () | 2 -> test_argv () | _ -> assert false let main () = match Array.length Sys.argv with | 1 -> let pid = Unix.create_process Sys.executable_name [|Sys.executable_name; "0"|] Unix.stdin Unix.stdout Unix.stderr in begin match Unix.waitpid [] pid with | _, Unix.WEXITED 0 -> () | _, (Unix.WEXITED _ | Unix.WSIGNALED _ | Unix.WSTOPPED _) -> failwith "Child process error" end | _ -> restart (int_of_string Sys.argv.(1)) let () = match main () with | () -> Printf.printf "OK\n%!" | exception e -> Printf.printf "BAD: %s\n%!" (Printexc.to_string e); exit 1
391913d67a495c5a7615535ae1b6563d485368ab726894fddecbd1fe88bcf3ba
postgres-haskell/postgres-wire
QuickCheck.hs
module Codecs.QuickCheck where import Data.Monoid ((<>)) import Test.Tasty import Test.QuickCheck import Test.QuickCheck.Arbitrary import Test.QuickCheck.Monadic import Data.Scientific as S import Data.Time import Text.Printf import Data.List as L import Data.UUID (UUID, fromWords) import Data.String (IsString) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import Database.PostgreSQL.Driver import Database.PostgreSQL.Protocol.DataRows import Database.PostgreSQL.Protocol.Types import Database.PostgreSQL.Protocol.Store.Encode import Database.PostgreSQL.Protocol.Store.Decode import qualified Database.PostgreSQL.Protocol.Codecs.Decoders as PD import qualified Database.PostgreSQL.Protocol.Codecs.Encoders as PE import qualified Database.PostgreSQL.Protocol.Codecs.PgTypes as PGT import Connection import Codecs.Runner -- | Makes property that if here is a value then encoding and sending it -- to PostgreSQL, and receiving back returns the same value. makeCodecProperty :: (Show a, Eq a, Arbitrary a) => Connection -> Oid -> (a -> Encode) -> PD.FieldDecoder a -> a -> Property makeCodecProperty c oid encoder fd v = monadicIO $ do let q = Query "SELECT $1" [(oid, Just $ encoder v)] Binary Binary AlwaysCache decoder = PD.dataRowHeader *> PD.getNonNullable fd r <- run $ do sendBatchAndSync c [q] dr <- readNextData c waitReadyForQuery c either (error . show) (pure . decodeOneRow decoder) dr assertQCEqual v r -- | Makes a property that encoded value is correctly parsed and printed -- by PostgreSQL. makeCodecEncodeProperty :: Arbitrary a => Connection -> Oid -> B.ByteString -> (a -> Encode) -> (a -> String) -> a -> Property makeCodecEncodeProperty c oid queryString encoder fPrint v = monadicIO $ do let q = Query queryString [(oid, Just $ encoder v)] Binary Text AlwaysCache decoder = PD.dataRowHeader *> PD.getNonNullable PD.bytea r <- run $ do sendBatchAndSync c [q] dr <- readNextData c waitReadyForQuery c either (error . show) (pure . BC.unpack . decodeOneRow decoder) dr assertQCEqual (fPrint v) r assertQCEqual :: (Eq a, Show a, Monad m) => a -> a -> PropertyM m () assertQCEqual a b | a == b = pure () | otherwise = fail $ "Equal assertion failed. Expected:\n" <> show a <> "\nbut got:\n" <> show b -- | Makes Tasty test tree. mkCodecTest :: (Eq a, Arbitrary a, Show a) => TestName -> PGT.Oids -> (a -> Encode) -> PD.FieldDecoder a -> TestTree mkCodecTest name oids encoder decoder = testPropertyConn name $ \c -> makeCodecProperty c (PGT.oidType oids) encoder decoder mkCodecEncodeTest :: (Arbitrary a, Show a) => TestName -> PGT.Oids -> B.ByteString -> (a -> Encode) -> (a -> String) -> TestTree mkCodecEncodeTest name oids queryString encoder fPrint = testPropertyConn name $ \c -> makeCodecEncodeProperty c (PGT.oidType oids) queryString encoder fPrint testCodecsEncodeDecode :: TestTree testCodecsEncodeDecode = testGroup "Codecs property 'encode . decode = id'" [ mkCodecTest "bool" PGT.bool PE.bool PD.bool , mkCodecTest "bytea" PGT.bytea PE.bytea PD.bytea , mkCodecTest "char" PGT.char (PE.char . unAsciiChar) (fmap AsciiChar <$> PD.char) , mkCodecTest "date" PGT.date PE.date PD.date , mkCodecTest "float4" PGT.float4 PE.float4 PD.float4 , mkCodecTest "float8" PGT.float8 PE.float8 PD.float8 , mkCodecTest "int2" PGT.int2 PE.int2 PD.int2 , mkCodecTest "int4" PGT.int4 PE.int4 PD.int4 , mkCodecTest "int8" PGT.int8 PE.int8 PD.int8 , mkCodecTest "interval" PGT.interval PE.interval PD.interval , mkCodecTest "json" PGT.json (PE.bsJsonText . unJsonString) (fmap JsonString <$> PD.bsJsonText) , mkCodecTest "jsonb" PGT.jsonb (PE.bsJsonBytes . unJsonString) (fmap JsonString <$> PD.bsJsonBytes) , mkCodecTest "numeric" PGT.numeric PE.numeric PD.numeric , mkCodecTest "text" PGT.text PE.bsText PD.bsText , mkCodecTest "time" PGT.time PE.time PD.time , mkCodecTest "timetz" PGT.timetz PE.timetz PD.timetz , mkCodecTest "timestamp" PGT.timestamp PE.timestamp PD.timestamp , mkCodecTest "timestamptz" PGT.timestamptz PE.timestamptz PD.timestamptz , mkCodecTest "uuid" PGT.uuid PE.uuid PD.uuid ] testCodecsEncodePrint :: TestTree testCodecsEncodePrint = testGroup "Codecs property 'Encoded value Postgres = value in Haskell'" [ mkCodecEncodeTest "bool" PGT.bool qBasic PE.bool displayBool , mkCodecEncodeTest "date" PGT.date qBasic PE.date show , mkCodecEncodeTest "float8" PGT.float8 "SELECT trim(to_char($1, '99999999999990.9999999999'))" PE.float8 (printf "%.10f") , mkCodecEncodeTest "int8" PGT.int8 qBasic PE.int8 show , mkCodecEncodeTest "interval" PGT.interval "SELECT extract(epoch from $1)||'s'" PE.interval show , mkCodecEncodeTest "numeric" PGT.numeric qBasic PE.numeric displayScientific , mkCodecEncodeTest "timestamp" PGT.timestamp qBasic PE.timestamp show , mkCodecEncodeTest "timestamptz" PGT.timestamptz "SELECT ($1 at time zone 'UTC')||' UTC'" PE.timestamptz show , mkCodecEncodeTest "uuid" PGT.uuid qBasic PE.uuid show ] where qBasic = "SELECT $1" displayScientific s | isInteger s = show $ ceiling s | otherwise = formatScientific S.Fixed Nothing s displayBool False = "f" displayBool True = "t" -- -- Orphan instances -- newtype AsciiChar = AsciiChar { unAsciiChar :: Char } deriving (Show, Eq) instance Arbitrary AsciiChar where arbitrary = AsciiChar <$> choose ('\0', '\127') -- Helper to generate valid json strings newtype JsonString = JsonString { unJsonString :: B.ByteString } deriving (Show, Eq, IsString) instance Arbitrary JsonString where arbitrary = oneof $ map pure [ "{}" , "{\"a\": 5}" , "{\"b\": [1, 2, 3]}" ] instance Arbitrary B.ByteString where arbitrary = do len <- choose (0, 1024) B.pack <$> vectorOf len (choose (1, 127)) instance Arbitrary Day where arbitrary = ModifiedJulianDay <$> choose (-100000, 100000) instance Arbitrary DiffTime where arbitrary = secondsToDiffTime <$> choose (0, 86400 - 1) instance Arbitrary TimeOfDay where arbitrary = timeToTimeOfDay <$> arbitrary instance Arbitrary LocalTime where arbitrary = LocalTime <$> arbitrary <*> fmap timeToTimeOfDay arbitrary instance Arbitrary UTCTime where arbitrary = UTCTime <$> arbitrary <*> arbitrary instance Arbitrary UUID where arbitrary = fromWords <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary Scientific where arbitrary = do c <- choose (-100000000, 100000000) e <- choose (-10, 10) pure . normalize $ scientific c e
null
https://raw.githubusercontent.com/postgres-haskell/postgres-wire/fda5e3b70c3cc0bab8365b4b872991d50da0348c/tests/Codecs/QuickCheck.hs
haskell
| Makes property that if here is a value then encoding and sending it to PostgreSQL, and receiving back returns the same value. | Makes a property that encoded value is correctly parsed and printed by PostgreSQL. | Makes Tasty test tree. Orphan instances Helper to generate valid json strings
module Codecs.QuickCheck where import Data.Monoid ((<>)) import Test.Tasty import Test.QuickCheck import Test.QuickCheck.Arbitrary import Test.QuickCheck.Monadic import Data.Scientific as S import Data.Time import Text.Printf import Data.List as L import Data.UUID (UUID, fromWords) import Data.String (IsString) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import Database.PostgreSQL.Driver import Database.PostgreSQL.Protocol.DataRows import Database.PostgreSQL.Protocol.Types import Database.PostgreSQL.Protocol.Store.Encode import Database.PostgreSQL.Protocol.Store.Decode import qualified Database.PostgreSQL.Protocol.Codecs.Decoders as PD import qualified Database.PostgreSQL.Protocol.Codecs.Encoders as PE import qualified Database.PostgreSQL.Protocol.Codecs.PgTypes as PGT import Connection import Codecs.Runner makeCodecProperty :: (Show a, Eq a, Arbitrary a) => Connection -> Oid -> (a -> Encode) -> PD.FieldDecoder a -> a -> Property makeCodecProperty c oid encoder fd v = monadicIO $ do let q = Query "SELECT $1" [(oid, Just $ encoder v)] Binary Binary AlwaysCache decoder = PD.dataRowHeader *> PD.getNonNullable fd r <- run $ do sendBatchAndSync c [q] dr <- readNextData c waitReadyForQuery c either (error . show) (pure . decodeOneRow decoder) dr assertQCEqual v r makeCodecEncodeProperty :: Arbitrary a => Connection -> Oid -> B.ByteString -> (a -> Encode) -> (a -> String) -> a -> Property makeCodecEncodeProperty c oid queryString encoder fPrint v = monadicIO $ do let q = Query queryString [(oid, Just $ encoder v)] Binary Text AlwaysCache decoder = PD.dataRowHeader *> PD.getNonNullable PD.bytea r <- run $ do sendBatchAndSync c [q] dr <- readNextData c waitReadyForQuery c either (error . show) (pure . BC.unpack . decodeOneRow decoder) dr assertQCEqual (fPrint v) r assertQCEqual :: (Eq a, Show a, Monad m) => a -> a -> PropertyM m () assertQCEqual a b | a == b = pure () | otherwise = fail $ "Equal assertion failed. Expected:\n" <> show a <> "\nbut got:\n" <> show b mkCodecTest :: (Eq a, Arbitrary a, Show a) => TestName -> PGT.Oids -> (a -> Encode) -> PD.FieldDecoder a -> TestTree mkCodecTest name oids encoder decoder = testPropertyConn name $ \c -> makeCodecProperty c (PGT.oidType oids) encoder decoder mkCodecEncodeTest :: (Arbitrary a, Show a) => TestName -> PGT.Oids -> B.ByteString -> (a -> Encode) -> (a -> String) -> TestTree mkCodecEncodeTest name oids queryString encoder fPrint = testPropertyConn name $ \c -> makeCodecEncodeProperty c (PGT.oidType oids) queryString encoder fPrint testCodecsEncodeDecode :: TestTree testCodecsEncodeDecode = testGroup "Codecs property 'encode . decode = id'" [ mkCodecTest "bool" PGT.bool PE.bool PD.bool , mkCodecTest "bytea" PGT.bytea PE.bytea PD.bytea , mkCodecTest "char" PGT.char (PE.char . unAsciiChar) (fmap AsciiChar <$> PD.char) , mkCodecTest "date" PGT.date PE.date PD.date , mkCodecTest "float4" PGT.float4 PE.float4 PD.float4 , mkCodecTest "float8" PGT.float8 PE.float8 PD.float8 , mkCodecTest "int2" PGT.int2 PE.int2 PD.int2 , mkCodecTest "int4" PGT.int4 PE.int4 PD.int4 , mkCodecTest "int8" PGT.int8 PE.int8 PD.int8 , mkCodecTest "interval" PGT.interval PE.interval PD.interval , mkCodecTest "json" PGT.json (PE.bsJsonText . unJsonString) (fmap JsonString <$> PD.bsJsonText) , mkCodecTest "jsonb" PGT.jsonb (PE.bsJsonBytes . unJsonString) (fmap JsonString <$> PD.bsJsonBytes) , mkCodecTest "numeric" PGT.numeric PE.numeric PD.numeric , mkCodecTest "text" PGT.text PE.bsText PD.bsText , mkCodecTest "time" PGT.time PE.time PD.time , mkCodecTest "timetz" PGT.timetz PE.timetz PD.timetz , mkCodecTest "timestamp" PGT.timestamp PE.timestamp PD.timestamp , mkCodecTest "timestamptz" PGT.timestamptz PE.timestamptz PD.timestamptz , mkCodecTest "uuid" PGT.uuid PE.uuid PD.uuid ] testCodecsEncodePrint :: TestTree testCodecsEncodePrint = testGroup "Codecs property 'Encoded value Postgres = value in Haskell'" [ mkCodecEncodeTest "bool" PGT.bool qBasic PE.bool displayBool , mkCodecEncodeTest "date" PGT.date qBasic PE.date show , mkCodecEncodeTest "float8" PGT.float8 "SELECT trim(to_char($1, '99999999999990.9999999999'))" PE.float8 (printf "%.10f") , mkCodecEncodeTest "int8" PGT.int8 qBasic PE.int8 show , mkCodecEncodeTest "interval" PGT.interval "SELECT extract(epoch from $1)||'s'" PE.interval show , mkCodecEncodeTest "numeric" PGT.numeric qBasic PE.numeric displayScientific , mkCodecEncodeTest "timestamp" PGT.timestamp qBasic PE.timestamp show , mkCodecEncodeTest "timestamptz" PGT.timestamptz "SELECT ($1 at time zone 'UTC')||' UTC'" PE.timestamptz show , mkCodecEncodeTest "uuid" PGT.uuid qBasic PE.uuid show ] where qBasic = "SELECT $1" displayScientific s | isInteger s = show $ ceiling s | otherwise = formatScientific S.Fixed Nothing s displayBool False = "f" displayBool True = "t" newtype AsciiChar = AsciiChar { unAsciiChar :: Char } deriving (Show, Eq) instance Arbitrary AsciiChar where arbitrary = AsciiChar <$> choose ('\0', '\127') newtype JsonString = JsonString { unJsonString :: B.ByteString } deriving (Show, Eq, IsString) instance Arbitrary JsonString where arbitrary = oneof $ map pure [ "{}" , "{\"a\": 5}" , "{\"b\": [1, 2, 3]}" ] instance Arbitrary B.ByteString where arbitrary = do len <- choose (0, 1024) B.pack <$> vectorOf len (choose (1, 127)) instance Arbitrary Day where arbitrary = ModifiedJulianDay <$> choose (-100000, 100000) instance Arbitrary DiffTime where arbitrary = secondsToDiffTime <$> choose (0, 86400 - 1) instance Arbitrary TimeOfDay where arbitrary = timeToTimeOfDay <$> arbitrary instance Arbitrary LocalTime where arbitrary = LocalTime <$> arbitrary <*> fmap timeToTimeOfDay arbitrary instance Arbitrary UTCTime where arbitrary = UTCTime <$> arbitrary <*> arbitrary instance Arbitrary UUID where arbitrary = fromWords <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary Scientific where arbitrary = do c <- choose (-100000000, 100000000) e <- choose (-10, 10) pure . normalize $ scientific c e
731f07b413e0c74302c34e543d8007d378a6b30621e6a108ae28fb897b3fbc50
AndrasKovacs/ELTE-func-lang
Lesson01.hs
-- {-# options_ghc -Wincomplete-patterns #-} -- {-# LANGUAGE NoImplicitPrelude #-} ghci commands : - : l(oad ) file - : r(eload ) - : bro(wse ) - : t(ype ) expression - : i(nfo ) definition examples : - : load - : t foo - : i ( + ) ghci commands: - :l(oad) file - :r(eload) - :bro(wse) - :t(ype) expression - :i(nfo) definition examples: - :load Lesson1.hs - :t foo - :i (+) -} module Lesson01 where Algebraic Data Types ( ADT ) -- Bool data = ? a : : -- a = undefined Color -- data Color = ? -- -- c :: Color -- c = undefined -- Pair -- data Pair a b = MakePair a b -- p :: Pair Color Bool -- p = undefined -- List -- data List a = ? l : : List -- l = undefined l ' : : List -- l' = undefined -- Tree -- data Tree = _ -- · -- / \ -- · · -- / \ -- · · -- t :: Tree -- t = undefined -- · -- / \ -- · · -- / \ -- · · -- / \ -- · · -- t' :: Tree -- t' = undefined {- Functions -} -- xor : Bool -> Bool -> Bool -- xor a b = undefined -- concat : List a -> List a -> List a -- concat xs ys = undefined -- height : Tree -> Int -- height t = undefined {- Type Classes -} class ' a where -- eq :: a -> a -> Bool -- -- -- In std: Ord [(<), (>), (<=) (>=)] class ' a = > Ord ' a where -- lte :: a -> a -> Bool -- -- class Show' a where -- show' :: a -> String -- -- -- Define the following instances: instance Eq ' Color where -- eq = undefined -- instance Ord ' Color where -- lte = undefined -- instance Show ' Color where -- show' = undefined -- instance Eq ' Pair where -- eq = undefined -- instance ' Pair where -- lte = undefined -- -- instance Show' Pair where -- show' = undefined -- -- -- -- instance ' a = > Eq ' ( Maybe a ) where -- standard : data Maybe a = Nothing | Just a -- eq = undefined -- instance ' a = > Ord ' ( Maybe a ) where -- Nothing < Just x -- lte = undefined -- -- instance Show' a => Show' (Maybe a) where -- show' = undefined -- instance ' a = > Eq ' [ a ] where -- eq = undefined -- instance ' a = > Ord ' [ a ] where -- lte = undefined -- -- instance Show' a => Show' [a] where -- show' = undefined -- -- instance ' a = > Eq ' ( Tree a ) where -- -- eq = undefined -- -- -- instance ' a = > Ord ' ( Tree a ) where -- -- lte = undefined -- -- -- -- instance Show' a => Show' (Tree a) where -- -- show' = undefined -- -- -- -- Define the following functions in a type correct and total manner. -- -- (No infinite loops or exceptions allowed.) -- -- f1 :: (a, (b, (c, d))) -> (b, c) -- f1 = undefined -- -- f2 :: (a -> b) -> a -> b -- f2 = undefined -- -- f3 :: (b -> c) -> (a -> b) -> a -> c -- f3 = undefined -- -- f4 :: (a -> b -> c) -> (b -> a -> c) -- f4 = undefined -- -- f5 :: ((a, b) -> c) -> (a -> b -> c) -- f5 = undefined -- -- f6 :: (a -> (b, c)) -> (a -> b, a -> c) -- f6 = undefined -- -- f7 :: (a -> b, a -> c) -> (a -> (b, c)) -- f7 = undefined -- -- f8 :: (Either a b -> c) -> (a -> c, b -> c) -- f8 = undefined -- f9 : : ( a - > c , b - > c ) - > ( Either a b - > c ) f9 = undefined -- -- f10 :: Either (a, b) (a, c) -> (a, Either b c) -- f10 = undefined -- -- f11 :: (a, Either b c) -> Either (a, b) (a, c) -- f11 = undefined -- -- -- Extra (harder) task: -- f12 :: (a -> a -> b) -> ((a -> b) -> a) -> b -- f12 = undefined
null
https://raw.githubusercontent.com/AndrasKovacs/ELTE-func-lang/88d41930999d6056bdd7bfaa85761a527cce4113/2020-21-2/gyak_2/Lesson01.hs
haskell
{-# options_ghc -Wincomplete-patterns #-} {-# LANGUAGE NoImplicitPrelude #-} Bool a = undefined data Color = ? c :: Color c = undefined Pair data Pair a b = MakePair a b p :: Pair Color Bool p = undefined List data List a = ? l = undefined l' = undefined Tree data Tree = _ · / \ · · / \ · · t :: Tree t = undefined · / \ · · / \ · · / \ · · t' :: Tree t' = undefined Functions xor : Bool -> Bool -> Bool xor a b = undefined concat : List a -> List a -> List a concat xs ys = undefined height : Tree -> Int height t = undefined Type Classes eq :: a -> a -> Bool -- In std: Ord [(<), (>), (<=) (>=)] lte :: a -> a -> Bool class Show' a where show' :: a -> String -- Define the following instances: eq = undefined lte = undefined show' = undefined eq = undefined lte = undefined instance Show' Pair where show' = undefined -- standard : data Maybe a = Nothing | Just a eq = undefined Nothing < Just x lte = undefined instance Show' a => Show' (Maybe a) where show' = undefined eq = undefined lte = undefined instance Show' a => Show' [a] where show' = undefined instance ' a = > Eq ' ( Tree a ) where -- eq = undefined -- instance ' a = > Ord ' ( Tree a ) where -- lte = undefined -- -- instance Show' a => Show' (Tree a) where -- show' = undefined -- Define the following functions in a type correct and total manner. -- (No infinite loops or exceptions allowed.) f1 :: (a, (b, (c, d))) -> (b, c) f1 = undefined f2 :: (a -> b) -> a -> b f2 = undefined f3 :: (b -> c) -> (a -> b) -> a -> c f3 = undefined f4 :: (a -> b -> c) -> (b -> a -> c) f4 = undefined f5 :: ((a, b) -> c) -> (a -> b -> c) f5 = undefined f6 :: (a -> (b, c)) -> (a -> b, a -> c) f6 = undefined f7 :: (a -> b, a -> c) -> (a -> (b, c)) f7 = undefined f8 :: (Either a b -> c) -> (a -> c, b -> c) f8 = undefined f10 :: Either (a, b) (a, c) -> (a, Either b c) f10 = undefined f11 :: (a, Either b c) -> Either (a, b) (a, c) f11 = undefined -- Extra (harder) task: f12 :: (a -> a -> b) -> ((a -> b) -> a) -> b f12 = undefined
ghci commands : - : l(oad ) file - : r(eload ) - : bro(wse ) - : t(ype ) expression - : i(nfo ) definition examples : - : load - : t foo - : i ( + ) ghci commands: - :l(oad) file - :r(eload) - :bro(wse) - :t(ype) expression - :i(nfo) definition examples: - :load Lesson1.hs - :t foo - :i (+) -} module Lesson01 where Algebraic Data Types ( ADT ) data = ? a : : Color l : : List l ' : : List class ' a where class ' a = > Ord ' a where instance Eq ' Color where instance Ord ' Color where instance Show ' Color where instance Eq ' Pair where instance ' Pair where instance ' a = > Eq ' [ a ] where instance ' a = > Ord ' [ a ] where f9 : : ( a - > c , b - > c ) - > ( Either a b - > c ) f9 = undefined
532360c81f9970499e7f22684c155c63cda4c5a78d1aa2a5ef76422b9be14015
exclipy/pdata
HamtMap.hs
----------------------------------------------------------------------------- -- | Module : Data . Copyright : ( c ) 2011 -- License : BSD-style -- Maintainer : -- Stability : experimental -- Portability : portable -- -- An implementation of maps from keys to values (dictionaries) based on the -- hash array mapped trie. -- -- Since many function names (but not the type name) clash with " Prelude " names , this module is usually imported @qualified@ , e.g. -- > import qualified Data . as HM -- This data structure is based on hash array mapped trie , -- which is described by his original paper: -- -- * <> ----------------------------------------------------------------------------- module Data.HamtMap ( -- * HamtMap type HamtMap -- * Operators , (Data.HamtMap.!) -- * Query , member , notMember , Data.HamtMap.lookup -- * Construction , empty , singleton -- * Insertion , insert , insertWith -- * Delete\/Update , Data.HamtMap.delete , adjust , update , alter -- * Traversal , Data.HamtMap.map , mapWithKey -- * Filter , Data.HamtMap.filter , filterWithKey -- * Conversion , Data.HamtMap.elems , keys , toList , fromListWith , fromList ) where import Data.BitUtil import Control.Monad import Control.DeepSeq import Data.Bits import Data.Hashable (Hashable) import qualified Data.Hashable as H import Data.Int import Data.List hiding (insert, lookup) import Data.Array as A import Prelude as P | A HamtMap from keys @k@ to values @v@ data (Eq k, Hashable k) => HamtMap k v = EmptyNode | LeafNode { h :: Int32 , key :: k , value :: v } | HashCollisionNode { h :: Int32 , pairs :: [(k, v)] } | BitmapIndexedNode { bitmap :: Int32 , subNodes :: Array Int32 (HamtMap k v) } | ArrayNode { numChildren :: Int32 , subNodes :: Array Int32 (HamtMap k v) } instance (Eq k, Hashable k, NFData k, NFData v) => NFData (HamtMap k v) where rnf EmptyNode = () rnf (LeafNode h k v) = rnf h `seq` rnf k `seq` rnf v rnf (HashCollisionNode h xs) = rnf h `seq` rnf xs rnf (BitmapIndexedNode bm arr) = rnf bm `seq` rnf arr rnf (ArrayNode n arr) = rnf n `seq` rnf arr instance (Eq k, Hashable k, Show k, Show v) => Show (HamtMap k v) where show EmptyNode = "" show (LeafNode _h key value) = show (key, value) show (HashCollisionNode _h pairs) = "h" ++ show pairs show (BitmapIndexedNode bitmap subNodes) = "b" ++ show bitmap ++ (show $ A.elems subNodes) show (ArrayNode numChildren subNodes) = "a" ++ show numChildren ++ (show $ A.elems subNodes) -- Some constants shiftStep = 5 chunk = 2^shiftStep mask = pred chunk bmnodeMax = 16 -- maximum size of a BitmapIndexedNode minimum size of an ArrayNode -- Some miscellaneous helper functions isEmptyNode :: HamtMap k v -> Bool isEmptyNode EmptyNode = True isEmptyNode _ = False isTipNode :: (Eq k, Hashable k) => HamtMap k v -> Bool isTipNode EmptyNode = True isTipNode (LeafNode _ _ _) = True isTipNode (HashCollisionNode _ _) = True isTipNode _ = False hash :: (Eq k, Hashable k) => k -> Int32 hash = fromIntegral.(H.hash) hashFragment shift h = (h `shiftR` shift) .&. fromIntegral mask | The empty HamtMap . empty :: (Eq k, Hashable k) => HamtMap k v empty = EmptyNode | @('singleton ' key value)@ is a single - element HamtMap holding @(key , value)@ singleton :: (Eq k, Hashable k) => k -> v -> HamtMap k v singleton key value = LeafNode (hash key) key value -- Helper data type for alterNode data Change = Removed | Modified | Nil | Added deriving Eq | The expression ( @'alter ' f k map@ ) alters the value @x@ at @k@ , or absence thereof . -- 'alter' can be used to insert, delete, or update a value in a 'Map'. In short : @'lookup ' k ( ' alter ' f k m ) = f ( ' lookup ' k m)@. alter :: (Eq k, Hashable k) => (Maybe v -> Maybe v) -> k -> HamtMap k v -> HamtMap k v alter updateFn key root = alterNode 0 updateFn (hash key) key root alterNode :: (Eq k, Hashable k) => Int -> (Maybe v -> Maybe v) -> Int32 -> k -> HamtMap k v -> HamtMap k v alterNode _shift updateFn h key EmptyNode = maybe EmptyNode (LeafNode h key) (updateFn Nothing) alterNode shift updateFn h' key' node@(LeafNode h key value) = if key' == key then maybe EmptyNode (LeafNode h key) (updateFn (Just value)) else let node' = alterNode shift updateFn h' key' EmptyNode in if isEmptyNode node' then node else combineNodes shift node node' where combineNodes :: (Eq k, Hashable k) => Int -> HamtMap k v -> HamtMap k v -> HamtMap k v combineNodes shift node1@(LeafNode h1 k1 v1) node2@(LeafNode h2 k2 v2) = let h1 = nodeHash node1 h2 = nodeHash node2 subH1 = hashFragment shift h1 subH2 = hashFragment shift h2 (nodeA, nodeB) = if (subH1 < subH2) then (node1, node2) else (node2, node1) bitmap' = ((toBitmap subH1) .|. (toBitmap subH2)) subNodes' = if subH1 == subH2 then listArray (0, 0) [combineNodes (shift+shiftStep) node1 node2] else listArray (0, 1) [nodeA, nodeB] in if h1 == h2 then HashCollisionNode h1 [(k2, v2), (k1, v1)] else BitmapIndexedNode bitmap' subNodes' nodeHash (LeafNode h key value) = h nodeHash (HashCollisionNode h pairs) = h alterNode _shift updateFn _hash' key (HashCollisionNode h pairs) = let pairs' = updateList updateFn key pairs in case pairs' of [] -> undefined -- should never happen [(key, value)] -> LeafNode h key value otherwise -> HashCollisionNode h pairs' where updateList updateFn key [] = maybe [] (\value' -> [(key, value')]) (updateFn Nothing) updateList updateFn key' ((key, value):pairs) | key' == key = maybe pairs (\value' -> (key, value'):pairs) (updateFn (Just value)) updateList updateFn key (p:pairs) = p : updateList updateFn key pairs alterNode shift updateFn h key bmnode@(BitmapIndexedNode bitmap subNodes) = let subHash = hashFragment shift h ix = fromBitmap bitmap subHash bit = toBitmap subHash exists = (bitmap .&. bit) /= 0 child = if exists then subNodes A.! fromIntegral ix else EmptyNode child' = alterNode (shift+shiftStep) updateFn h key child removed = exists && isEmptyNode child' added = not exists && not (isEmptyNode child') change = if exists then if isEmptyNode child' then Removed else Modified else if isEmptyNode child' then Nil else Added bound = snd $ bounds subNodes bound' = case change of Removed -> bound-1 Modified -> bound Nil -> bound Added -> bound+1 (left, right) = splitAt ix $ A.elems subNodes subNodes' = case change of Removed -> listArray (0, bound') $ left ++ (tail right) Modified -> subNodes // [(fromIntegral ix, child')] Nil -> subNodes Added -> listArray (0, bound') $ left ++ (child':right) bitmap' = case change of Removed -> bitmap .&. (complement bit) Modified -> bitmap Nil -> bitmap Added -> bitmap .|. bit in if bitmap' == 0 then -- Remove an empty BitmapIndexedNode Note : it 's possible to have a single - element if there are two keys with the same subHash in the trie . EmptyNode else if bound' == 0 && isTipNode (subNodes' A.! 0) Pack a BitmapIndexedNode into a LeafNode subNodes' A.! 0 else if change == Added && bound' > bmnodeMax - 1 then -- Expand a BitmapIndexedNode into an ArrayNode expandBitmapNode shift subHash child' bitmap subNodes else BitmapIndexedNode bitmap' subNodes' where expandBitmapNode :: (Eq k, Hashable k) => Int -> Int32 -> HamtMap k v -> Int32 -> Array Int32 (HamtMap k v) -> HamtMap k v expandBitmapNode shift subHash node' bitmap subNodes = let assocs = zip (bitmapToIndices bitmap) (A.elems subNodes) assocs' = (subHash, node'):assocs blank = listArray (0, 31) $ replicate 32 EmptyNode numChildren = (bitCount32 bitmap) + 1 in ArrayNode numChildren $ blank // assocs' -- TODO: an array copy could be avoided here alterNode shift updateFn h key node@(ArrayNode numChildren subNodes) = let subHash = hashFragment shift h child = subNodes A.! subHash child' = alterNode (shift+shiftStep) updateFn h key child change = if isEmptyNode child then if isEmptyNode child' then Nil else Added else if isEmptyNode child' then Removed else Modified numChildren' = case change of Removed -> numChildren-1 Modified -> numChildren Nil -> numChildren Added -> numChildren+1 in if numChildren' < arraynodeMin Pack an ArrayNode into a BitmapIndexedNode when usage drops below 25 % then packArrayNode subHash numChildren subNodes else ArrayNode numChildren' $ subNodes // [(subHash, child')] where packArrayNode :: (Eq k, Hashable k) => Int32 -> Int32 -> Array Int32 (HamtMap k v) -> HamtMap k v packArrayNode subHashToRemove numChildren subNodes = let elems' = P.map (\i -> if i == subHashToRemove then EmptyNode else subNodes A.! i) [0..pred chunk] subNodes' = listArray (0, (numChildren-2)) $ P.filter (not.isEmptyNode) elems' listToBitmap = foldr (\on bm -> (bm `shiftL` 1) .|. (if on then 1 else 0)) 0 bitmap = listToBitmap $ P.map (not.isEmptyNode) elems' in BitmapIndexedNode bitmap subNodes' -- | Insert with a function, combining new value and old value. @'insertWith ' f key value mp@ -- will insert the pair (key, value) into @mp@ if key does -- not exist in the map. If the key does exist, the function will insert the pair @(key , f new_value old_value)@. insertWith :: (Eq k, Hashable k) => (v -> v -> v) -> k -> v -> HamtMap k v -> HamtMap k v insertWith accumFn key value hm = let fn :: (v -> v -> v) -> v -> Maybe v -> Maybe v fn accumFn x' Nothing = Just x' fn accumFn x' (Just x) = Just $ accumFn x' x in alter (fn accumFn value) key hm -- | Insert a new key and value in the map. -- If the key is already present in the map, the associated value is -- replaced with the supplied value. 'insert' is equivalent to -- @'insertWith' 'const'@. insert :: (Eq k, Hashable k) => k -> v -> HamtMap k v -> HamtMap k v insert = insertWith const | The expression ( ' f k map@ ) updates the value @x@ at @k@ ( if it is in the map ) . If ( @f ) is ' Nothing ' , the element is deleted . If it is ( @'Just ' y@ ) , the key @k@ is bound to the new value @y@. update :: (Eq k, Hashable k) => (v -> Maybe v) -> k -> HamtMap k v -> HamtMap k v update updateFn = alter ((=<<) updateFn) -- | Delete a key and its value from the map. When the key is not -- a member of the map, the original map is returned. delete :: (Eq k, Hashable k) => k -> HamtMap k v -> HamtMap k v delete = alter (const Nothing) -- | Update a value at a specific key with the result of the provided function. -- When the key is not a member of the map, the original map is returned. adjust :: (Eq k, Hashable k) => (v -> v) -> k -> HamtMap k v -> HamtMap k v adjust updateFn = alter ((=<<) ((Just).updateFn)) -- | Map a function over all values in the map. mapWithKey :: (Eq k, Hashable k) => (k -> v -> v) -> HamtMap k v -> HamtMap k v mapWithKey _mapFn EmptyNode = EmptyNode mapWithKey mapFn (LeafNode h key value) = LeafNode h key $ mapFn key value mapWithKey mapFn (HashCollisionNode h pairs) = HashCollisionNode h (P.map (\(key, value) -> (key, mapFn key value)) pairs) mapWithKey mapFn (BitmapIndexedNode bitmap subNodes) = BitmapIndexedNode bitmap $ arrayMap (mapWithKey mapFn) subNodes mapWithKey mapFn (ArrayNode numChildren subNodes) = ArrayNode numChildren $ arrayMap (mapWithKey mapFn) subNodes arrayMap :: (Ix i) => (a -> a) -> Array i a -> Array i a arrayMap fn arr = array (bounds arr) $ P.map (\(key, value) -> (key, fn value)) $ A.assocs arr -- | Map a function over all values in the map. map :: (Eq k, Hashable k) => (v -> v) -> HamtMap k v -> HamtMap k v map fn = mapWithKey (const fn) -- | Filter for all values that satisify a predicate. filterWithKey :: (Eq k, Hashable k) => (k -> v -> Bool) -> HamtMap k v -> HamtMap k v filterWithKey _fn EmptyNode = EmptyNode filterWithKey fn node@(LeafNode h key value) | fn key value = node | otherwise = EmptyNode filterWithKey fn (HashCollisionNode h pairs) = let pairs' = P.filter (uncurry fn) pairs in case pairs' of [] -> EmptyNode [(key, value)] -> LeafNode h key value otherwise -> HashCollisionNode h pairs' filterWithKey fn (BitmapIndexedNode bitmap subNodes) = let mapped = P.map (filterWithKey fn) (A.elems subNodes) zipped = zip (bitmapToIndices bitmap) mapped filtered = P.filter (\(ix, subNode) -> not (isEmptyNode subNode)) zipped (indices', subNodes') = unzip filtered n = fromIntegral $ length filtered in case subNodes' of [] -> EmptyNode [node] | isTipNode node -> node otherwise -> BitmapIndexedNode (indicesToBitmap indices') (listArray (0, n-1) subNodes') filterWithKey fn (ArrayNode numChildren subNodes) = let mapped = P.map (filterWithKey fn) (A.elems subNodes) zipped = zip [0..31] mapped filtered = P.filter (\(ix, subNode) -> not (isEmptyNode subNode)) zipped (indices', subNodes') = unzip filtered n = fromIntegral $ length filtered in case filtered of [] -> EmptyNode [(ix, node)] | isTipNode node -> node els | n <= bmnodeMax -> BitmapIndexedNode (indicesToBitmap indices') (listArray (0, n-1) subNodes') | otherwise -> ArrayNode n (listArray (0, 31) mapped) -- | Filter for all values that satisify a predicate. filter :: (Eq k, Hashable k) => (v -> Bool) -> HamtMap k v -> HamtMap k v filter fn = filterWithKey (const fn) -- | Lookup the value at a key in the map. -- -- The function will return the corresponding value as @('Just' value)@, -- or 'Nothing' if the key isn't in the map. lookup :: (Eq k, Hashable k) => k -> HamtMap k v -> Maybe v lookup key root = lookupNode 0 (hash key) key root lookupNode :: (Eq k, Hashable k) => Int -> Int32 -> k -> HamtMap k v -> Maybe v lookupNode _ _ _ EmptyNode = Nothing lookupNode _ _ key' (LeafNode _ key value) = if key' == key then Just value else Nothing lookupNode _ _ key (HashCollisionNode _ pairs) = P.lookup key pairs lookupNode shift h key (BitmapIndexedNode bitmap subNodes) = let subHash = hashFragment shift h ix = fromBitmap bitmap subHash exists = (bitmap .&. (toBitmap subHash)) /= 0 in if exists then lookupNode (shift+shiftStep) h key (subNodes A.! ix) else Nothing lookupNode shift h key (ArrayNode _numChildren subNodes) = let subHash = hashFragment shift h in lookupNode (shift+shiftStep) h key (subNodes A.! subHash) -- | Find the value at a key. -- Calls 'error' when the element can not be found. (!) :: (Eq k, Hashable k) => HamtMap k v -> k -> v hm ! key = maybe (error "element not in the map") id (Data.HamtMap.lookup key hm) | Is the key a member of the map ? See also ' ' . member :: (Eq k, Hashable k) => k -> HamtMap k v -> Bool member key hm = maybe False (const True) (Data.HamtMap.lookup key hm) -- | Is the key a member of the map? See also 'member'. notMember :: (Eq k, Hashable k) => k -> HamtMap k v -> Bool notMember key = not.(member key) -- | Convert to a list of key\/value pairs. toList :: (Eq k, Hashable k) => HamtMap k v -> [(k, v)] toList EmptyNode = [] toList (LeafNode _hash key value) = [(key, value)] toList (HashCollisionNode _hash pairs) = pairs toList (BitmapIndexedNode _bitmap subNodes) = concat $ P.map toList $ A.elems subNodes toList (ArrayNode _numChildren subNodes) = concat $ P.map toList $ A.elems subNodes -- | Build a map from a list of key\/value pairs with a combining function. fromListWith :: (Eq k, Hashable k) => (v -> v -> v) -> [(k, v)] -> HamtMap k v fromListWith combineFn assocs = fromListNode 0 combineFn $ P.map (\(k, v) -> ((hash k), k, v)) assocs fromListNode :: (Eq k, Hashable k) => Int -> (v -> v -> v) -> [(Int32, k, v)] -> HamtMap k v fromListNode shift combineFn hkvs = let subHashed = P.map (\triple@(h, k, v) -> (hashFragment shift h, triple)) hkvs divided = accumArray (flip (:)) [] (0, mask) subHashed -- this will alternately reverse and unreverse the list on each level down dividedList = A.elems divided subNodes = listArray (0, mask) $ P.map (fromListNode (shift+shiftStep) combineFn) $ dividedList numChildren = length $ P.filter (not.null) dividedList in case hkvs of [] -> EmptyNode [(h, k, v)] -> LeafNode h k v (h, k, v):hkvs' | all (\(h', _, _) -> h' == h) hkvs' -> if all (\(_, k', _) -> k' == k) hkvs' then let combineFn' = if even shift then flip combineFn else combineFn -- correct for the alternate reversing of the list v' = foldl1' combineFn' (P.map (\(_, _, v) -> v) hkvs) in LeafNode h k v' else let keyCmp (k1, _) (k2, _) = k1 == k2 collisions = P.map (\(_, k', v') -> (k', v')) hkvs grouped = groupBy' keyCmp collisions combineFn' = if even shift then flip combineFn else combineFn collisionKeys = P.map (fst.head) grouped collisionVals = P.map ((foldl1' combineFn').(P.map snd)) grouped collisions' = zip collisionKeys collisionVals in HashCollisionNode h collisions' _ | numChildren > fromIntegral bmnodeMax -> ArrayNode (fromIntegral numChildren) subNodes _ | otherwise -> makeBMNode numChildren subNodes where makeBMNode :: (Eq k, Hashable k) => Int -> Array Int32 (HamtMap k v) -> HamtMap k v makeBMNode numChildren subNodes = let subNodeList = A.elems subNodes subNodes' = listArray (0, (fromIntegral numChildren-1)) $ P.filter (not.isEmptyNode) subNodeList listToBitmap = foldr (\on bm -> (bm `shiftL` 1) .|. (if on then 1 else 0)) 0 bitmap = listToBitmap $ P.map (not.isEmptyNode) subNodeList in BitmapIndexedNode bitmap subNodes' groupBy ' is like Data . List.groupBy , but also groups non - adjacent elements groupBy' :: (a -> a -> Bool) -> [a] -> [[a]] groupBy' eq list = P.map reverse $ foldl' (insertGrouped eq) [] list insertGrouped :: (a -> a -> Bool) -> [[a]] -> a -> [[a]] insertGrouped eq [] y = [[y]] insertGrouped eq ((x:xs):gs) y | eq x y = (y:x:xs) : gs | otherwise = (x:xs) : insertGrouped eq gs y -- | Build a map from a list of key\/value pairs. If the list contains more than one value for the same key , the last value -- for the key is retained. fromList :: (Eq k, Hashable k) => [(k, v)] -> HamtMap k v fromList assocs = fromListWith const assocs -- | Return all keys of the map. keys :: (Eq k, Hashable k) => HamtMap k v -> [k] keys = (P.map fst).toList -- | Return all elements of the map. elems :: (Eq k, Hashable k) => HamtMap k v -> [v] elems = (P.map snd).toList
null
https://raw.githubusercontent.com/exclipy/pdata/b03682176f506c3484f4dcb39af82149c72772d0/Data/HamtMap.hs
haskell
--------------------------------------------------------------------------- | License : BSD-style Maintainer : Stability : experimental Portability : portable An implementation of maps from keys to values (dictionaries) based on the hash array mapped trie. Since many function names (but not the type name) clash with which is described by his original paper: * <> --------------------------------------------------------------------------- * HamtMap type * Operators * Query * Construction * Insertion * Delete\/Update * Traversal * Filter * Conversion Some constants maximum size of a BitmapIndexedNode Some miscellaneous helper functions Helper data type for alterNode 'alter' can be used to insert, delete, or update a value in a 'Map'. should never happen Remove an empty BitmapIndexedNode Expand a BitmapIndexedNode into an ArrayNode TODO: an array copy could be avoided here | Insert with a function, combining new value and old value. will insert the pair (key, value) into @mp@ if key does not exist in the map. If the key does exist, the function will | Insert a new key and value in the map. If the key is already present in the map, the associated value is replaced with the supplied value. 'insert' is equivalent to @'insertWith' 'const'@. | Delete a key and its value from the map. When the key is not a member of the map, the original map is returned. | Update a value at a specific key with the result of the provided function. When the key is not a member of the map, the original map is returned. | Map a function over all values in the map. | Map a function over all values in the map. | Filter for all values that satisify a predicate. | Filter for all values that satisify a predicate. | Lookup the value at a key in the map. The function will return the corresponding value as @('Just' value)@, or 'Nothing' if the key isn't in the map. | Find the value at a key. Calls 'error' when the element can not be found. | Is the key a member of the map? See also 'member'. | Convert to a list of key\/value pairs. | Build a map from a list of key\/value pairs with a combining function. this will alternately reverse and unreverse the list on each level down correct for the alternate reversing of the list | Build a map from a list of key\/value pairs. for the key is retained. | Return all keys of the map. | Return all elements of the map.
Module : Data . Copyright : ( c ) 2011 " Prelude " names , this module is usually imported @qualified@ , e.g. > import qualified Data . as HM This data structure is based on hash array mapped trie , module Data.HamtMap ( HamtMap , (Data.HamtMap.!) , member , notMember , Data.HamtMap.lookup , empty , singleton , insert , insertWith , Data.HamtMap.delete , adjust , update , alter , Data.HamtMap.map , mapWithKey , Data.HamtMap.filter , filterWithKey , Data.HamtMap.elems , keys , toList , fromListWith , fromList ) where import Data.BitUtil import Control.Monad import Control.DeepSeq import Data.Bits import Data.Hashable (Hashable) import qualified Data.Hashable as H import Data.Int import Data.List hiding (insert, lookup) import Data.Array as A import Prelude as P | A HamtMap from keys @k@ to values @v@ data (Eq k, Hashable k) => HamtMap k v = EmptyNode | LeafNode { h :: Int32 , key :: k , value :: v } | HashCollisionNode { h :: Int32 , pairs :: [(k, v)] } | BitmapIndexedNode { bitmap :: Int32 , subNodes :: Array Int32 (HamtMap k v) } | ArrayNode { numChildren :: Int32 , subNodes :: Array Int32 (HamtMap k v) } instance (Eq k, Hashable k, NFData k, NFData v) => NFData (HamtMap k v) where rnf EmptyNode = () rnf (LeafNode h k v) = rnf h `seq` rnf k `seq` rnf v rnf (HashCollisionNode h xs) = rnf h `seq` rnf xs rnf (BitmapIndexedNode bm arr) = rnf bm `seq` rnf arr rnf (ArrayNode n arr) = rnf n `seq` rnf arr instance (Eq k, Hashable k, Show k, Show v) => Show (HamtMap k v) where show EmptyNode = "" show (LeafNode _h key value) = show (key, value) show (HashCollisionNode _h pairs) = "h" ++ show pairs show (BitmapIndexedNode bitmap subNodes) = "b" ++ show bitmap ++ (show $ A.elems subNodes) show (ArrayNode numChildren subNodes) = "a" ++ show numChildren ++ (show $ A.elems subNodes) shiftStep = 5 chunk = 2^shiftStep mask = pred chunk minimum size of an ArrayNode isEmptyNode :: HamtMap k v -> Bool isEmptyNode EmptyNode = True isEmptyNode _ = False isTipNode :: (Eq k, Hashable k) => HamtMap k v -> Bool isTipNode EmptyNode = True isTipNode (LeafNode _ _ _) = True isTipNode (HashCollisionNode _ _) = True isTipNode _ = False hash :: (Eq k, Hashable k) => k -> Int32 hash = fromIntegral.(H.hash) hashFragment shift h = (h `shiftR` shift) .&. fromIntegral mask | The empty HamtMap . empty :: (Eq k, Hashable k) => HamtMap k v empty = EmptyNode | @('singleton ' key value)@ is a single - element HamtMap holding @(key , value)@ singleton :: (Eq k, Hashable k) => k -> v -> HamtMap k v singleton key value = LeafNode (hash key) key value data Change = Removed | Modified | Nil | Added deriving Eq | The expression ( @'alter ' f k map@ ) alters the value @x@ at @k@ , or absence thereof . In short : @'lookup ' k ( ' alter ' f k m ) = f ( ' lookup ' k m)@. alter :: (Eq k, Hashable k) => (Maybe v -> Maybe v) -> k -> HamtMap k v -> HamtMap k v alter updateFn key root = alterNode 0 updateFn (hash key) key root alterNode :: (Eq k, Hashable k) => Int -> (Maybe v -> Maybe v) -> Int32 -> k -> HamtMap k v -> HamtMap k v alterNode _shift updateFn h key EmptyNode = maybe EmptyNode (LeafNode h key) (updateFn Nothing) alterNode shift updateFn h' key' node@(LeafNode h key value) = if key' == key then maybe EmptyNode (LeafNode h key) (updateFn (Just value)) else let node' = alterNode shift updateFn h' key' EmptyNode in if isEmptyNode node' then node else combineNodes shift node node' where combineNodes :: (Eq k, Hashable k) => Int -> HamtMap k v -> HamtMap k v -> HamtMap k v combineNodes shift node1@(LeafNode h1 k1 v1) node2@(LeafNode h2 k2 v2) = let h1 = nodeHash node1 h2 = nodeHash node2 subH1 = hashFragment shift h1 subH2 = hashFragment shift h2 (nodeA, nodeB) = if (subH1 < subH2) then (node1, node2) else (node2, node1) bitmap' = ((toBitmap subH1) .|. (toBitmap subH2)) subNodes' = if subH1 == subH2 then listArray (0, 0) [combineNodes (shift+shiftStep) node1 node2] else listArray (0, 1) [nodeA, nodeB] in if h1 == h2 then HashCollisionNode h1 [(k2, v2), (k1, v1)] else BitmapIndexedNode bitmap' subNodes' nodeHash (LeafNode h key value) = h nodeHash (HashCollisionNode h pairs) = h alterNode _shift updateFn _hash' key (HashCollisionNode h pairs) = let pairs' = updateList updateFn key pairs in case pairs' of [(key, value)] -> LeafNode h key value otherwise -> HashCollisionNode h pairs' where updateList updateFn key [] = maybe [] (\value' -> [(key, value')]) (updateFn Nothing) updateList updateFn key' ((key, value):pairs) | key' == key = maybe pairs (\value' -> (key, value'):pairs) (updateFn (Just value)) updateList updateFn key (p:pairs) = p : updateList updateFn key pairs alterNode shift updateFn h key bmnode@(BitmapIndexedNode bitmap subNodes) = let subHash = hashFragment shift h ix = fromBitmap bitmap subHash bit = toBitmap subHash exists = (bitmap .&. bit) /= 0 child = if exists then subNodes A.! fromIntegral ix else EmptyNode child' = alterNode (shift+shiftStep) updateFn h key child removed = exists && isEmptyNode child' added = not exists && not (isEmptyNode child') change = if exists then if isEmptyNode child' then Removed else Modified else if isEmptyNode child' then Nil else Added bound = snd $ bounds subNodes bound' = case change of Removed -> bound-1 Modified -> bound Nil -> bound Added -> bound+1 (left, right) = splitAt ix $ A.elems subNodes subNodes' = case change of Removed -> listArray (0, bound') $ left ++ (tail right) Modified -> subNodes // [(fromIntegral ix, child')] Nil -> subNodes Added -> listArray (0, bound') $ left ++ (child':right) bitmap' = case change of Removed -> bitmap .&. (complement bit) Modified -> bitmap Nil -> bitmap Added -> bitmap .|. bit in if bitmap' == 0 Note : it 's possible to have a single - element if there are two keys with the same subHash in the trie . EmptyNode else if bound' == 0 && isTipNode (subNodes' A.! 0) Pack a BitmapIndexedNode into a LeafNode subNodes' A.! 0 else if change == Added && bound' > bmnodeMax - 1 expandBitmapNode shift subHash child' bitmap subNodes else BitmapIndexedNode bitmap' subNodes' where expandBitmapNode :: (Eq k, Hashable k) => Int -> Int32 -> HamtMap k v -> Int32 -> Array Int32 (HamtMap k v) -> HamtMap k v expandBitmapNode shift subHash node' bitmap subNodes = let assocs = zip (bitmapToIndices bitmap) (A.elems subNodes) assocs' = (subHash, node'):assocs blank = listArray (0, 31) $ replicate 32 EmptyNode numChildren = (bitCount32 bitmap) + 1 in ArrayNode numChildren $ blank // assocs' alterNode shift updateFn h key node@(ArrayNode numChildren subNodes) = let subHash = hashFragment shift h child = subNodes A.! subHash child' = alterNode (shift+shiftStep) updateFn h key child change = if isEmptyNode child then if isEmptyNode child' then Nil else Added else if isEmptyNode child' then Removed else Modified numChildren' = case change of Removed -> numChildren-1 Modified -> numChildren Nil -> numChildren Added -> numChildren+1 in if numChildren' < arraynodeMin Pack an ArrayNode into a BitmapIndexedNode when usage drops below 25 % then packArrayNode subHash numChildren subNodes else ArrayNode numChildren' $ subNodes // [(subHash, child')] where packArrayNode :: (Eq k, Hashable k) => Int32 -> Int32 -> Array Int32 (HamtMap k v) -> HamtMap k v packArrayNode subHashToRemove numChildren subNodes = let elems' = P.map (\i -> if i == subHashToRemove then EmptyNode else subNodes A.! i) [0..pred chunk] subNodes' = listArray (0, (numChildren-2)) $ P.filter (not.isEmptyNode) elems' listToBitmap = foldr (\on bm -> (bm `shiftL` 1) .|. (if on then 1 else 0)) 0 bitmap = listToBitmap $ P.map (not.isEmptyNode) elems' in BitmapIndexedNode bitmap subNodes' @'insertWith ' f key value mp@ insert the pair @(key , f new_value old_value)@. insertWith :: (Eq k, Hashable k) => (v -> v -> v) -> k -> v -> HamtMap k v -> HamtMap k v insertWith accumFn key value hm = let fn :: (v -> v -> v) -> v -> Maybe v -> Maybe v fn accumFn x' Nothing = Just x' fn accumFn x' (Just x) = Just $ accumFn x' x in alter (fn accumFn value) key hm insert :: (Eq k, Hashable k) => k -> v -> HamtMap k v -> HamtMap k v insert = insertWith const | The expression ( ' f k map@ ) updates the value @x@ at @k@ ( if it is in the map ) . If ( @f ) is ' Nothing ' , the element is deleted . If it is ( @'Just ' y@ ) , the key @k@ is bound to the new value @y@. update :: (Eq k, Hashable k) => (v -> Maybe v) -> k -> HamtMap k v -> HamtMap k v update updateFn = alter ((=<<) updateFn) delete :: (Eq k, Hashable k) => k -> HamtMap k v -> HamtMap k v delete = alter (const Nothing) adjust :: (Eq k, Hashable k) => (v -> v) -> k -> HamtMap k v -> HamtMap k v adjust updateFn = alter ((=<<) ((Just).updateFn)) mapWithKey :: (Eq k, Hashable k) => (k -> v -> v) -> HamtMap k v -> HamtMap k v mapWithKey _mapFn EmptyNode = EmptyNode mapWithKey mapFn (LeafNode h key value) = LeafNode h key $ mapFn key value mapWithKey mapFn (HashCollisionNode h pairs) = HashCollisionNode h (P.map (\(key, value) -> (key, mapFn key value)) pairs) mapWithKey mapFn (BitmapIndexedNode bitmap subNodes) = BitmapIndexedNode bitmap $ arrayMap (mapWithKey mapFn) subNodes mapWithKey mapFn (ArrayNode numChildren subNodes) = ArrayNode numChildren $ arrayMap (mapWithKey mapFn) subNodes arrayMap :: (Ix i) => (a -> a) -> Array i a -> Array i a arrayMap fn arr = array (bounds arr) $ P.map (\(key, value) -> (key, fn value)) $ A.assocs arr map :: (Eq k, Hashable k) => (v -> v) -> HamtMap k v -> HamtMap k v map fn = mapWithKey (const fn) filterWithKey :: (Eq k, Hashable k) => (k -> v -> Bool) -> HamtMap k v -> HamtMap k v filterWithKey _fn EmptyNode = EmptyNode filterWithKey fn node@(LeafNode h key value) | fn key value = node | otherwise = EmptyNode filterWithKey fn (HashCollisionNode h pairs) = let pairs' = P.filter (uncurry fn) pairs in case pairs' of [] -> EmptyNode [(key, value)] -> LeafNode h key value otherwise -> HashCollisionNode h pairs' filterWithKey fn (BitmapIndexedNode bitmap subNodes) = let mapped = P.map (filterWithKey fn) (A.elems subNodes) zipped = zip (bitmapToIndices bitmap) mapped filtered = P.filter (\(ix, subNode) -> not (isEmptyNode subNode)) zipped (indices', subNodes') = unzip filtered n = fromIntegral $ length filtered in case subNodes' of [] -> EmptyNode [node] | isTipNode node -> node otherwise -> BitmapIndexedNode (indicesToBitmap indices') (listArray (0, n-1) subNodes') filterWithKey fn (ArrayNode numChildren subNodes) = let mapped = P.map (filterWithKey fn) (A.elems subNodes) zipped = zip [0..31] mapped filtered = P.filter (\(ix, subNode) -> not (isEmptyNode subNode)) zipped (indices', subNodes') = unzip filtered n = fromIntegral $ length filtered in case filtered of [] -> EmptyNode [(ix, node)] | isTipNode node -> node els | n <= bmnodeMax -> BitmapIndexedNode (indicesToBitmap indices') (listArray (0, n-1) subNodes') | otherwise -> ArrayNode n (listArray (0, 31) mapped) filter :: (Eq k, Hashable k) => (v -> Bool) -> HamtMap k v -> HamtMap k v filter fn = filterWithKey (const fn) lookup :: (Eq k, Hashable k) => k -> HamtMap k v -> Maybe v lookup key root = lookupNode 0 (hash key) key root lookupNode :: (Eq k, Hashable k) => Int -> Int32 -> k -> HamtMap k v -> Maybe v lookupNode _ _ _ EmptyNode = Nothing lookupNode _ _ key' (LeafNode _ key value) = if key' == key then Just value else Nothing lookupNode _ _ key (HashCollisionNode _ pairs) = P.lookup key pairs lookupNode shift h key (BitmapIndexedNode bitmap subNodes) = let subHash = hashFragment shift h ix = fromBitmap bitmap subHash exists = (bitmap .&. (toBitmap subHash)) /= 0 in if exists then lookupNode (shift+shiftStep) h key (subNodes A.! ix) else Nothing lookupNode shift h key (ArrayNode _numChildren subNodes) = let subHash = hashFragment shift h in lookupNode (shift+shiftStep) h key (subNodes A.! subHash) (!) :: (Eq k, Hashable k) => HamtMap k v -> k -> v hm ! key = maybe (error "element not in the map") id (Data.HamtMap.lookup key hm) | Is the key a member of the map ? See also ' ' . member :: (Eq k, Hashable k) => k -> HamtMap k v -> Bool member key hm = maybe False (const True) (Data.HamtMap.lookup key hm) notMember :: (Eq k, Hashable k) => k -> HamtMap k v -> Bool notMember key = not.(member key) toList :: (Eq k, Hashable k) => HamtMap k v -> [(k, v)] toList EmptyNode = [] toList (LeafNode _hash key value) = [(key, value)] toList (HashCollisionNode _hash pairs) = pairs toList (BitmapIndexedNode _bitmap subNodes) = concat $ P.map toList $ A.elems subNodes toList (ArrayNode _numChildren subNodes) = concat $ P.map toList $ A.elems subNodes fromListWith :: (Eq k, Hashable k) => (v -> v -> v) -> [(k, v)] -> HamtMap k v fromListWith combineFn assocs = fromListNode 0 combineFn $ P.map (\(k, v) -> ((hash k), k, v)) assocs fromListNode :: (Eq k, Hashable k) => Int -> (v -> v -> v) -> [(Int32, k, v)] -> HamtMap k v fromListNode shift combineFn hkvs = let subHashed = P.map (\triple@(h, k, v) -> (hashFragment shift h, triple)) hkvs divided = accumArray (flip (:)) [] (0, mask) subHashed dividedList = A.elems divided subNodes = listArray (0, mask) $ P.map (fromListNode (shift+shiftStep) combineFn) $ dividedList numChildren = length $ P.filter (not.null) dividedList in case hkvs of [] -> EmptyNode [(h, k, v)] -> LeafNode h k v (h, k, v):hkvs' | all (\(h', _, _) -> h' == h) hkvs' -> if all (\(_, k', _) -> k' == k) hkvs' then let combineFn' = if even shift then flip combineFn else combineFn v' = foldl1' combineFn' (P.map (\(_, _, v) -> v) hkvs) in LeafNode h k v' else let keyCmp (k1, _) (k2, _) = k1 == k2 collisions = P.map (\(_, k', v') -> (k', v')) hkvs grouped = groupBy' keyCmp collisions combineFn' = if even shift then flip combineFn else combineFn collisionKeys = P.map (fst.head) grouped collisionVals = P.map ((foldl1' combineFn').(P.map snd)) grouped collisions' = zip collisionKeys collisionVals in HashCollisionNode h collisions' _ | numChildren > fromIntegral bmnodeMax -> ArrayNode (fromIntegral numChildren) subNodes _ | otherwise -> makeBMNode numChildren subNodes where makeBMNode :: (Eq k, Hashable k) => Int -> Array Int32 (HamtMap k v) -> HamtMap k v makeBMNode numChildren subNodes = let subNodeList = A.elems subNodes subNodes' = listArray (0, (fromIntegral numChildren-1)) $ P.filter (not.isEmptyNode) subNodeList listToBitmap = foldr (\on bm -> (bm `shiftL` 1) .|. (if on then 1 else 0)) 0 bitmap = listToBitmap $ P.map (not.isEmptyNode) subNodeList in BitmapIndexedNode bitmap subNodes' groupBy ' is like Data . List.groupBy , but also groups non - adjacent elements groupBy' :: (a -> a -> Bool) -> [a] -> [[a]] groupBy' eq list = P.map reverse $ foldl' (insertGrouped eq) [] list insertGrouped :: (a -> a -> Bool) -> [[a]] -> a -> [[a]] insertGrouped eq [] y = [[y]] insertGrouped eq ((x:xs):gs) y | eq x y = (y:x:xs) : gs | otherwise = (x:xs) : insertGrouped eq gs y If the list contains more than one value for the same key , the last value fromList :: (Eq k, Hashable k) => [(k, v)] -> HamtMap k v fromList assocs = fromListWith const assocs keys :: (Eq k, Hashable k) => HamtMap k v -> [k] keys = (P.map fst).toList elems :: (Eq k, Hashable k) => HamtMap k v -> [v] elems = (P.map snd).toList
2628a9c3604886f35fd9e6db5136945e8237af86be52ee75e3b3086c621212c0
pdarragh/parsing-with-zippers-paper-artifact
types.ml
type pos = int ref (* Using ref makes it easy to create values that are not pointer equal *) let p_bottom = ref (-1) type sym = string let s_bottom = "<s_bottom>" type tag = int type tok = tag * sym let t_eof = (-1, "<t_eof>") type exp = exp_ Lazy.t and exp_ = { mutable m : mem; e' : exp'; } and exp' = Tok of tok | Seq of sym * exp list | Alt of (exp list) ref and cxt = TopC | SeqC of mem * sym * exp list * exp list | AltC of mem and mem = { start_pos : pos; mutable parents : cxt list; mutable end_pos : pos; mutable result : exp } type zipper = exp' * mem let rec e_bottom = lazy { m = m_bottom; e' = Alt (ref []) } and m_bottom = { start_pos = p_bottom; parents = []; end_pos = p_bottom; result = e_bottom } let tok (t : tok) : exp_ = { m = m_bottom; e' = Tok(t) } let seq (s : sym) (es : exp list) : exp_ = { m = m_bottom; e' = Seq(s, es) } let alt (es : exp list) : exp_ = { m = m_bottom; e' = Alt(ref es) }
null
https://raw.githubusercontent.com/pdarragh/parsing-with-zippers-paper-artifact/c5c08306cfe4eec588237c7fa45b794649ccb68a/interact/lazy/types.ml
ocaml
Using ref makes it easy to create values that are not pointer equal
let p_bottom = ref (-1) type sym = string let s_bottom = "<s_bottom>" type tag = int type tok = tag * sym let t_eof = (-1, "<t_eof>") type exp = exp_ Lazy.t and exp_ = { mutable m : mem; e' : exp'; } and exp' = Tok of tok | Seq of sym * exp list | Alt of (exp list) ref and cxt = TopC | SeqC of mem * sym * exp list * exp list | AltC of mem and mem = { start_pos : pos; mutable parents : cxt list; mutable end_pos : pos; mutable result : exp } type zipper = exp' * mem let rec e_bottom = lazy { m = m_bottom; e' = Alt (ref []) } and m_bottom = { start_pos = p_bottom; parents = []; end_pos = p_bottom; result = e_bottom } let tok (t : tok) : exp_ = { m = m_bottom; e' = Tok(t) } let seq (s : sym) (es : exp list) : exp_ = { m = m_bottom; e' = Seq(s, es) } let alt (es : exp list) : exp_ = { m = m_bottom; e' = Alt(ref es) }
0b977e457c6e74f68bba72d8f308c3b7dfee19a61758493dc6e9ac8ca7bb493e
seancorfield/honeysql
build.clj
(ns build "HoneySQL's build script. clojure -T:build ci clojure -T:build run-doc-tests :aliases '[:cljs]' Run tests: clojure -X:test clojure -X:test:master For more information, run: clojure -A:deps -T:build help/doc" (:refer-clojure :exclude [test]) (:require [clojure.string :as str] [clojure.tools.build.api :as b] [clojure.tools.deps :as t] [deps-deploy.deps-deploy :as dd])) (def lib 'com.github.seancorfield/honeysql) (defn- the-version [patch] (format "2.4.%s" patch)) (def version (the-version (b/git-count-revs nil))) (def snapshot (the-version "9999-SNAPSHOT")) (def class-dir "target/classes") (defn- run-task [aliases] (println "\nRunning task for" (str/join "," (map name aliases))) (let [basis (b/create-basis {:aliases aliases}) combined (t/combine-aliases basis aliases) cmds (b/java-command {:basis basis :java-opts (:jvm-opts combined) :main 'clojure.main :main-args (:main-opts combined)}) {:keys [exit]} (b/process cmds)] (when-not (zero? exit) (throw (ex-info "Task failed" {}))))) (defn eastwood "Run Eastwood." [opts] (run-task [:eastwood]) opts) (defn gen-doc-tests "Generate tests from doc code blocks." [opts] (run-task [:gen-doc-tests]) opts) (defn run-doc-tests "Generate and run doc tests. Optionally specify :aliases vector: [:1.9] -- test against Clojure 1.9 (the default) [:1.10] -- test against Clojure 1.10.3 [:1.11] -- test against Clojure 1.11.0 [:master] -- test against Clojure 1.12 master snapshot [:cljs] -- test against ClojureScript" [{:keys [aliases] :as opts}] (gen-doc-tests opts) (run-task (-> [:test :test-doc] (into aliases) (into (if (some #{:cljs} aliases) [:test-doc-cljs] [:test-doc-clj])))) opts) (defn test "Run basic tests." [opts] (run-task [:test :1.11]) opts) (defn- jar-opts [opts] (let [version (if (:snapshot opts) snapshot version)] (println "\nVersion:" version) (assoc opts :lib lib :version version :jar-file (format "target/%s-%s.jar" lib version) :scm {:tag (str "v" version)} :basis (b/create-basis {}) :class-dir class-dir :target "target" :src-dirs ["src"] :src-pom "template/pom.xml"))) (defn ci "Run the CI pipeline of tests (and build the JAR). Default Clojure version is 1.9.0 (:1.9) so :elide tests for #409 on that version." [opts] (let [aliases [:cljs :elide :1.10 :1.11 :master] opts (jar-opts opts)] (b/delete {:path "target"}) (doseq [alias aliases] (run-doc-tests {:aliases [alias]})) (eastwood opts) (doseq [alias aliases] (run-task [:test alias])) (b/delete {:path "target"}) (println "\nWriting pom.xml...") (b/write-pom opts) (println "\nCopying source...") (b/copy-dir {:src-dirs ["src"] :target-dir class-dir}) (println "\nBuilding JAR...") (b/jar opts)) opts) (defn deploy "Deploy the JAR to Clojars." [opts] (let [{:keys [jar-file] :as opts} (jar-opts opts)] (dd/deploy {:installer :remote :artifact (b/resolve-path jar-file) :pom-file (b/pom-path (select-keys opts [:lib :class-dir]))})) opts)
null
https://raw.githubusercontent.com/seancorfield/honeysql/bfc8ad6821ee3bfc0cc4b9f0db02c39057d46db1/build.clj
clojure
(ns build "HoneySQL's build script. clojure -T:build ci clojure -T:build run-doc-tests :aliases '[:cljs]' Run tests: clojure -X:test clojure -X:test:master For more information, run: clojure -A:deps -T:build help/doc" (:refer-clojure :exclude [test]) (:require [clojure.string :as str] [clojure.tools.build.api :as b] [clojure.tools.deps :as t] [deps-deploy.deps-deploy :as dd])) (def lib 'com.github.seancorfield/honeysql) (defn- the-version [patch] (format "2.4.%s" patch)) (def version (the-version (b/git-count-revs nil))) (def snapshot (the-version "9999-SNAPSHOT")) (def class-dir "target/classes") (defn- run-task [aliases] (println "\nRunning task for" (str/join "," (map name aliases))) (let [basis (b/create-basis {:aliases aliases}) combined (t/combine-aliases basis aliases) cmds (b/java-command {:basis basis :java-opts (:jvm-opts combined) :main 'clojure.main :main-args (:main-opts combined)}) {:keys [exit]} (b/process cmds)] (when-not (zero? exit) (throw (ex-info "Task failed" {}))))) (defn eastwood "Run Eastwood." [opts] (run-task [:eastwood]) opts) (defn gen-doc-tests "Generate tests from doc code blocks." [opts] (run-task [:gen-doc-tests]) opts) (defn run-doc-tests "Generate and run doc tests. Optionally specify :aliases vector: [:1.9] -- test against Clojure 1.9 (the default) [:1.10] -- test against Clojure 1.10.3 [:1.11] -- test against Clojure 1.11.0 [:master] -- test against Clojure 1.12 master snapshot [:cljs] -- test against ClojureScript" [{:keys [aliases] :as opts}] (gen-doc-tests opts) (run-task (-> [:test :test-doc] (into aliases) (into (if (some #{:cljs} aliases) [:test-doc-cljs] [:test-doc-clj])))) opts) (defn test "Run basic tests." [opts] (run-task [:test :1.11]) opts) (defn- jar-opts [opts] (let [version (if (:snapshot opts) snapshot version)] (println "\nVersion:" version) (assoc opts :lib lib :version version :jar-file (format "target/%s-%s.jar" lib version) :scm {:tag (str "v" version)} :basis (b/create-basis {}) :class-dir class-dir :target "target" :src-dirs ["src"] :src-pom "template/pom.xml"))) (defn ci "Run the CI pipeline of tests (and build the JAR). Default Clojure version is 1.9.0 (:1.9) so :elide tests for #409 on that version." [opts] (let [aliases [:cljs :elide :1.10 :1.11 :master] opts (jar-opts opts)] (b/delete {:path "target"}) (doseq [alias aliases] (run-doc-tests {:aliases [alias]})) (eastwood opts) (doseq [alias aliases] (run-task [:test alias])) (b/delete {:path "target"}) (println "\nWriting pom.xml...") (b/write-pom opts) (println "\nCopying source...") (b/copy-dir {:src-dirs ["src"] :target-dir class-dir}) (println "\nBuilding JAR...") (b/jar opts)) opts) (defn deploy "Deploy the JAR to Clojars." [opts] (let [{:keys [jar-file] :as opts} (jar-opts opts)] (dd/deploy {:installer :remote :artifact (b/resolve-path jar-file) :pom-file (b/pom-path (select-keys opts [:lib :class-dir]))})) opts)
c084c09fbaa35332d4b2f6aac35197465b6019b448f086df4f1b7148d40993fb
braidchat/braid
core.cljc
(ns braid.notices.core (:require [braid.base.api :as base] #?@(:cljs [[clojure.spec.alpha :as s] [garden.units :refer [rem em]] [re-frame.core :refer [subscribe dispatch]] [braid.core.client.ui.styles.mixins :as mixins]]))) #?(:cljs (do (def ErrorSpec {:key keyword? :message string? :class (s/spec #{:error :info})}))) (defn init! [] #?(:cljs (do (base/register-state! {::state {}} {::state {keyword? ErrorSpec}}) (base/register-subs! {::sub (fn [state _] (vals (state ::state)))}) (base/register-events! {:braid.notices/clear! (fn [{db :db} [_ korks]] {:db (update db ::state (fn [errors] (if (sequential? korks) (apply dissoc errors korks) (dissoc errors korks))))}) :braid.notices/display! (fn [{db :db} [_ [err-key message error-class]]] {:db (update db ::state assoc err-key {:key err-key :message message :class error-class})})}) (base/register-root-view! (fn [] [:div.notices (doall (for [{:keys [key message class]} @(subscribe [::sub])] ^{:key key} [:div.notice {:class class} message [:span.gap] [:span.close {:on-click (fn [_] (dispatch [:braid.notices/clear! key]))} "×"]]))])) (base/register-styles! [:#app>.app>.main [:>.notices {:z-index 9999 :position "fixed" :top "4rem" :right "1rem"} [:>.notice {:display "flex" :justify-content "space-between" :min-width "10em" :align-items "center" :margin [[0 "auto" (rem 0.25)]] :font-size (em 1.5) :padding "0.25em" :border-radius "3px" :border [["0.5px" "solid" "#000000"]]} [:&.error {:background "#ffe4e4" :border-color "#CA1414" :color "#CA1414"} [:&:before (mixins/fontawesome \uf071) {:margin "0 0.5rem 0 0.25rem"}]] [:&.info {:background "#cfe9ff" :border-color "#236cab" :color "#236cab"} [:&:before (mixins/fontawesome \uf06a) {:margin "0 0.5rem 0 0.25rem"}]] [:>.gap {:flex-grow 1}] [:>.close {:cursor "pointer" :margin "0 0.25rem"}]]]]))))
null
https://raw.githubusercontent.com/braidchat/braid/2e44eb6e77f1d203115f9b9c529bd865fa3d7302/src/braid/notices/core.cljc
clojure
(ns braid.notices.core (:require [braid.base.api :as base] #?@(:cljs [[clojure.spec.alpha :as s] [garden.units :refer [rem em]] [re-frame.core :refer [subscribe dispatch]] [braid.core.client.ui.styles.mixins :as mixins]]))) #?(:cljs (do (def ErrorSpec {:key keyword? :message string? :class (s/spec #{:error :info})}))) (defn init! [] #?(:cljs (do (base/register-state! {::state {}} {::state {keyword? ErrorSpec}}) (base/register-subs! {::sub (fn [state _] (vals (state ::state)))}) (base/register-events! {:braid.notices/clear! (fn [{db :db} [_ korks]] {:db (update db ::state (fn [errors] (if (sequential? korks) (apply dissoc errors korks) (dissoc errors korks))))}) :braid.notices/display! (fn [{db :db} [_ [err-key message error-class]]] {:db (update db ::state assoc err-key {:key err-key :message message :class error-class})})}) (base/register-root-view! (fn [] [:div.notices (doall (for [{:keys [key message class]} @(subscribe [::sub])] ^{:key key} [:div.notice {:class class} message [:span.gap] [:span.close {:on-click (fn [_] (dispatch [:braid.notices/clear! key]))} "×"]]))])) (base/register-styles! [:#app>.app>.main [:>.notices {:z-index 9999 :position "fixed" :top "4rem" :right "1rem"} [:>.notice {:display "flex" :justify-content "space-between" :min-width "10em" :align-items "center" :margin [[0 "auto" (rem 0.25)]] :font-size (em 1.5) :padding "0.25em" :border-radius "3px" :border [["0.5px" "solid" "#000000"]]} [:&.error {:background "#ffe4e4" :border-color "#CA1414" :color "#CA1414"} [:&:before (mixins/fontawesome \uf071) {:margin "0 0.5rem 0 0.25rem"}]] [:&.info {:background "#cfe9ff" :border-color "#236cab" :color "#236cab"} [:&:before (mixins/fontawesome \uf06a) {:margin "0 0.5rem 0 0.25rem"}]] [:>.gap {:flex-grow 1}] [:>.close {:cursor "pointer" :margin "0 0.25rem"}]]]]))))
a92a4265d990f3d279a80d411ce8802ccbbf73e939dc77bad1a47c51258d49fb
gstew5/snarkl
Common.hs
module Common where import qualified Data.IntMap.Lazy as Map type Var = Int type Assgn a = Map.IntMap a data UnOp = ZEq deriving Eq instance Show UnOp where show ZEq = "(== 0)" data Op = Add | Sub | Mult | Div | And | Or | XOr | Eq | BEq deriving Eq instance Show Op where show Add = "+" show Sub = "-" show Mult = "*" show Div = "-*" show And = "&&" show Or = "||" show XOr = "xor" show Eq = "==" show BEq = "=b=" is_boolean :: Op -> Bool is_boolean op = case op of Add -> False Sub -> False Mult -> False Div -> False And -> True Or -> True XOr -> True Eq -> True BEq -> True is_assoc :: Op -> Bool is_assoc op = case op of Add -> True Sub -> False Mult -> True Div -> False And -> True Or -> True XOr -> True Eq -> True BEq -> True
null
https://raw.githubusercontent.com/gstew5/snarkl/d6ce72b13e370d2965bb226f28a1135269e7c198/src/Common.hs
haskell
module Common where import qualified Data.IntMap.Lazy as Map type Var = Int type Assgn a = Map.IntMap a data UnOp = ZEq deriving Eq instance Show UnOp where show ZEq = "(== 0)" data Op = Add | Sub | Mult | Div | And | Or | XOr | Eq | BEq deriving Eq instance Show Op where show Add = "+" show Sub = "-" show Mult = "*" show Div = "-*" show And = "&&" show Or = "||" show XOr = "xor" show Eq = "==" show BEq = "=b=" is_boolean :: Op -> Bool is_boolean op = case op of Add -> False Sub -> False Mult -> False Div -> False And -> True Or -> True XOr -> True Eq -> True BEq -> True is_assoc :: Op -> Bool is_assoc op = case op of Add -> True Sub -> False Mult -> True Div -> False And -> True Or -> True XOr -> True Eq -> True BEq -> True
70cf12d748ecaf2da7254c9fbb72af677e5b3fdfb094139faa674e48679f0f22
composewell/bench-show
Tutorial.hs
# OPTIONS_GHC -fno - warn - unused - imports # -- | Module : . Tutorial Copyright : ( c ) 2018 Composewell Technologies -- -- License : BSD3 -- Maintainer : -- BenchShow generates text reports and graphs from benchmarking results . It -- allows you to manipulate the format of the report and the benchmarking data to present it in many useful ways . uses robust statistical analysis using three different statistical estimators to provide as stable -- run-to-run comparison of benchmark results as possible. For stable results, -- make sure that you are not executing any other tasks on the benchmark host -- while benhmarking is going on. For even more stable results, we recommend -- using a desktop or server machine instead of a laptop notebook for -- benchmarking. module BenchShow.Tutorial ( -- * Generating benchmark results -- $generating -- * Reports and Charts -- $plotting -- * Grouping -- $grouping -- * Difference -- $difference -- * Percentage Difference -- $percent -- * Statistical Estimators -- $estimators -- * Difference Strategy -- $diffStrategy -- * Sorting -- $sorting -- * Regression -- $regression ) where import BenchShow -- $generating -- -- To generate benchmark results use @gauge@ or @criterion@ benchmarking libraries , define some benchmarks and run it with = results.csv@. -- The resulting @results.csv@ may look like the following , for simplicity we -- have removed some of the fields:: -- -- @ Name , time , -- vector/fold,6.41620933137583e-4,2879488 streamly / fold,6.399582632376517e-4,2879488 -- vector/map,6.388913781259641e-4,2854912 streamly / map,6.533649051066093e-4,2793472 -- vector/zip,6.514202653014291e-4,2707456 streamly / zip,6.443344209329669e-4,2711552 -- @ -- -- If you run the benchmarks again (maybe after a change) the new results are appended to the file . BenchShow can compare two or more result sets and -- compare the results in different ways. We will use the above data for the -- examples below, you can copy it and paste it in a file and use that as input to a BenchShow application . -- -- @gauge@ supports generating a raw csv file using @--csvraw@ option. The raw -- csv file has results for many more benchmarking fields other than time e.g. @maxrss@ or @allocated@ and many more . -- $plotting -- -- The most common usecase is to see the time and peak memory usage of a program for each benchmark . The ' report ' API with ' ' presentation -- style generates a multi-column report for a quick overview of all -- benchmarks. Units of the fields are automatically determined based on the -- range of values: -- -- @ ' report ' " results.csv " Nothing ' defaultConfig ' { ' presentation ' = ' ' } -- @ -- -- @ ( default)(Median ) -- Benchmark time(μs) maxrss(MiB) -- ------------- -------- ----------- vector / fold 641.62 2.75 streamly / fold 639.96 2.75 vector / map 638.89 2.72 streamly / map 653.36 2.66 vector / zip 651.42 2.58 streamly / zip 644.33 2.59 -- @ -- We can generate equivalent visual report using ' graph ' , it generates one bar -- chart for each column: -- -- @ -- 'graph' "results.csv" "output" 'defaultConfig' -- @ -- -- By default all the benchmarks are placed in a single benchmark group named -- @default@. -- -- <<docs/full-median-time.svg Median Time Full>> -- -- $grouping -- -- Let's write a benchmark classifier to put the @streamly@ and @vector@ -- benchmarks in their own groups: -- -- @ -- classifier name = -- case splitOn "/" name of : bench - > Just ( grp , concat bench ) -- _ -> Nothing -- @ -- Now we can show the two benchmark groups as columns each showing the time -- field for that group. We can generate separate reports comparing different benchmark fields ( e.g. @time@ and @maxrss@ ) for all the groups : : -- -- @ -- 'report' "results.csv" Nothing -- 'defaultConfig' { 'classifyBenchmark' = classifier } -- @ -- -- @ ( time)(Median ) Benchmark streamly(μs ) vector(μs ) -- --------- ------------ ---------- fold 639.96 641.62 map 653.36 638.89 zip 644.33 651.42 -- @ -- -- We can do the same graphically as well, just replace 'report' with 'graph' -- in the code above. Each group is placed as a cluster on the graph. Multiple -- clusters are placed side by side on the same scale for easy -- comparison. For example: -- -- <<docs/grouped-median-time.svg Median Time Grouped>> -- $difference -- We can make the first group as baseline and report the subsequent groups as -- a difference from the baseline: -- -- @ -- 'report' "results.csv" Nothing -- 'defaultConfig' -- { 'classifyBenchmark' = classifier -- , 'presentation' = 'Groups' 'Diff' -- } -- @ -- -- @ -- (time)(Median)(Diff using min estimator) -- Benchmark streamly(μs)(base) vector(μs)(-base) -- --------- ------------------ ----------------- fold 639.96 +1.66 map 653.36 -14.47 zip 644.33 +7.09 -- @ -- In a chart , the second cluster plots the difference @streamly - vector@. -- < < docs / grouped - delta - median - time.svg Median Time Grouped Delta > > -- $percent -- -- Absolute difference does not give us a good idea about how good or bad -- the comparison is. We can report precentage difference instead: -- -- @ -- 'report' "results.csv" Nothing -- 'defaultConfig' -- { 'classifyBenchmark' = classifier -- , 'presentation' = 'Groups' 'PercentDiff' -- } -- @ -- -- @ -- (time)(Median)(Diff using min estimator) -- Benchmark streamly(μs)(base) vector(%)(-base) -- --------- ------------------ ---------------- fold 639.96 +0.26 map 653.36 -2.22 zip 644.33 +1.10 -- @ -- -- Graphically: -- -- <<docs/grouped-percent-delta-median-time.svg Median Time Percent Delta>> -- $estimators -- -- When multiple samples are available for each benchmark we report the -- 'Median' by default. However, other estimators like 'Mean' and 'Regression' -- (a value arrived at by linear regression) can be used: -- -- @ -- 'report' "results.csv" Nothing -- 'defaultConfig' -- { 'classifyBenchmark' = classifier -- , 'presentation' = 'Groups' 'PercentDiff' -- , 'estimator' = 'Regression' -- } -- @ -- -- @ -- (time)(Regression Coeff.)(Diff using min estimator) -- Benchmark streamly(μs)(base) vector(%)(-base) -- --------- ------------------ ---------------- fold 639.96 +0.26 map 653.36 -2.22 zip 644.33 +1.10 -- @ -- -- Graphically: -- -- <<docs/grouped-percent-delta-coeff-time.svg Regression Coeff. Time Percent Delta>> -- $diffStrategy -- A ' DiffStrategy ' controls how the difference between two groups being compared is arrived at . By default we use the ' MinEstimators ' strategy which -- computes the difference using all the available estimators and takes the -- minimum of all. We can use a 'SingleEstimator' strategy instead if we so -- desire, it uses the estimator configured for the report using the -- @estimator@ field of the configuration. -- -- @ -- 'report' "results.csv" Nothing -- 'defaultConfig' -- { 'classifyBenchmark' = classifier -- , 'presentation' = 'Groups' 'PercentDiff' -- , 'estimator' = 'Regression' -- , 'diffStrategy' = 'SingleEstimator' -- } -- @ -- -- @ -- (time)(Regression Coeff.)(Diff ) -- Benchmark streamly(μs)(base) vector(%)(-base) -- --------- ------------------ ---------------- fold 639.96 +0.26 map 653.36 -2.22 zip 644.33 +1.10 -- @ -- -- Graphically: -- -- <<docs/grouped-single-estimator-coeff-time.svg Single Estimator Time Percent Delta>> -- $sorting -- -- Percentage difference does not immediately tell us the worst affected -- benchmarks. We can sort the results by the difference: -- -- @ -- 'report' "results.csv" Nothing -- 'defaultConfig' -- { 'classifyBenchmark' = classifier -- , 'presentation' = 'Groups' 'PercentDiff' -- , 'selectBenchmarks' = \f -> -- reverse -- $ map fst $ sortBy ( comparing snd ) $ either error i d $ f ( ' ColumnIndex ' 1 ) Nothing -- } -- @ -- -- @ -- (time)(Median)(Diff using min estimator) -- Benchmark streamly(μs)(base) vector(%)(-base) -- --------- ------------------ ---------------- zip 644.33 +1.10 fold 639.96 +0.26 map 653.36 -2.22 -- @ -- -- This tells us that zip is the relatively worst benchmark for vector compared to streamly , as it takes 1.10 % more time , whereas map is the best taking 2.22 % less time .. -- -- Graphically: -- -- <<docs/grouped-percent-delta-sorted-median-time.svg Median Time Percent Delta>> -- $regression -- -- We can append benchmarks results from multiple runs to the same file. These -- runs can then be compared. We can run benchmarks before and after a change -- and then report the regressions by percentage change in a sorted order: -- Given the following results file with two runs appended : -- -- @ -- Name,time streamly / streamly / zip,2.960114434592148e-2 streamly / map,2.4673020708256527e-2 -- Name,time streamly / fold,8.970816964261911e-3 streamly / zip,8.439519884529081e-3 streamly / map,6.972814233286865e-3 -- @ -- -- This code generates the report that follows: -- -- @ -- 'report' "results.csv" Nothing -- 'defaultConfig' -- { 'classifyBenchmark' = classifier -- , 'presentation' = 'Groups' 'PercentDiff' -- , 'selectBenchmarks' = \f -> -- reverse -- $ map fst $ sortBy ( comparing snd ) $ either error i d $ f ( ' ColumnIndex ' 1 ) Nothing -- } -- @ -- -- @ -- (time)(Median)(Diff using min estimator) -- Benchmark streamly(0)(μs)(base) streamly(1)(%)(-base) -- --------- --------------------- --------------------- zip 644.33 +23.28 map 653.36 +7.65 fold 639.96 -15.63 -- @ -- It tells us that in the second run the worst affected benchmark is zip taking 23.28 percent more time comapred to the baseline . -- -- Graphically: -- -- <<docs/regression-percent-descending-median-time.svg Median Time Regression>>
null
https://raw.githubusercontent.com/composewell/bench-show/46313526b5c0135dd6a976abdc0b8918668378d2/lib/BenchShow/Tutorial.hs
haskell
| License : BSD3 Maintainer : allows you to manipulate the format of the report and the benchmarking data run-to-run comparison of benchmark results as possible. For stable results, make sure that you are not executing any other tasks on the benchmark host while benhmarking is going on. For even more stable results, we recommend using a desktop or server machine instead of a laptop notebook for benchmarking. * Generating benchmark results $generating * Reports and Charts $plotting * Grouping $grouping * Difference $difference * Percentage Difference $percent * Statistical Estimators $estimators * Difference Strategy $diffStrategy * Sorting $sorting * Regression $regression $generating To generate benchmark results use @gauge@ or @criterion@ benchmarking have removed some of the fields:: @ vector/fold,6.41620933137583e-4,2879488 vector/map,6.388913781259641e-4,2854912 vector/zip,6.514202653014291e-4,2707456 @ If you run the benchmarks again (maybe after a change) the new results are compare the results in different ways. We will use the above data for the examples below, you can copy it and paste it in a file and use that as input @gauge@ supports generating a raw csv file using @--csvraw@ option. The raw csv file has results for many more benchmarking fields other than time e.g. $plotting The most common usecase is to see the time and peak memory usage of a style generates a multi-column report for a quick overview of all benchmarks. Units of the fields are automatically determined based on the range of values: @ @ @ Benchmark time(μs) maxrss(MiB) ------------- -------- ----------- @ chart for each column: @ 'graph' "results.csv" "output" 'defaultConfig' @ By default all the benchmarks are placed in a single benchmark group named @default@. <<docs/full-median-time.svg Median Time Full>> $grouping Let's write a benchmark classifier to put the @streamly@ and @vector@ benchmarks in their own groups: @ classifier name = case splitOn "/" name of _ -> Nothing @ field for that group. We can generate separate reports comparing different @ 'report' "results.csv" Nothing 'defaultConfig' { 'classifyBenchmark' = classifier } @ @ --------- ------------ ---------- @ We can do the same graphically as well, just replace 'report' with 'graph' in the code above. Each group is placed as a cluster on the graph. Multiple clusters are placed side by side on the same scale for easy comparison. For example: <<docs/grouped-median-time.svg Median Time Grouped>> $difference a difference from the baseline: @ 'report' "results.csv" Nothing 'defaultConfig' { 'classifyBenchmark' = classifier , 'presentation' = 'Groups' 'Diff' } @ @ (time)(Median)(Diff using min estimator) Benchmark streamly(μs)(base) vector(μs)(-base) --------- ------------------ ----------------- @ $percent Absolute difference does not give us a good idea about how good or bad the comparison is. We can report precentage difference instead: @ 'report' "results.csv" Nothing 'defaultConfig' { 'classifyBenchmark' = classifier , 'presentation' = 'Groups' 'PercentDiff' } @ @ (time)(Median)(Diff using min estimator) Benchmark streamly(μs)(base) vector(%)(-base) --------- ------------------ ---------------- @ Graphically: <<docs/grouped-percent-delta-median-time.svg Median Time Percent Delta>> $estimators When multiple samples are available for each benchmark we report the 'Median' by default. However, other estimators like 'Mean' and 'Regression' (a value arrived at by linear regression) can be used: @ 'report' "results.csv" Nothing 'defaultConfig' { 'classifyBenchmark' = classifier , 'presentation' = 'Groups' 'PercentDiff' , 'estimator' = 'Regression' } @ @ (time)(Regression Coeff.)(Diff using min estimator) Benchmark streamly(μs)(base) vector(%)(-base) --------- ------------------ ---------------- @ Graphically: <<docs/grouped-percent-delta-coeff-time.svg Regression Coeff. Time Percent Delta>> $diffStrategy computes the difference using all the available estimators and takes the minimum of all. We can use a 'SingleEstimator' strategy instead if we so desire, it uses the estimator configured for the report using the @estimator@ field of the configuration. @ 'report' "results.csv" Nothing 'defaultConfig' { 'classifyBenchmark' = classifier , 'presentation' = 'Groups' 'PercentDiff' , 'estimator' = 'Regression' , 'diffStrategy' = 'SingleEstimator' } @ @ (time)(Regression Coeff.)(Diff ) Benchmark streamly(μs)(base) vector(%)(-base) --------- ------------------ ---------------- @ Graphically: <<docs/grouped-single-estimator-coeff-time.svg Single Estimator Time Percent Delta>> $sorting Percentage difference does not immediately tell us the worst affected benchmarks. We can sort the results by the difference: @ 'report' "results.csv" Nothing 'defaultConfig' { 'classifyBenchmark' = classifier , 'presentation' = 'Groups' 'PercentDiff' , 'selectBenchmarks' = \f -> reverse $ map fst } @ @ (time)(Median)(Diff using min estimator) Benchmark streamly(μs)(base) vector(%)(-base) --------- ------------------ ---------------- @ This tells us that zip is the relatively worst benchmark for vector compared Graphically: <<docs/grouped-percent-delta-sorted-median-time.svg Median Time Percent Delta>> $regression We can append benchmarks results from multiple runs to the same file. These runs can then be compared. We can run benchmarks before and after a change and then report the regressions by percentage change in a sorted order: @ Name,time Name,time @ This code generates the report that follows: @ 'report' "results.csv" Nothing 'defaultConfig' { 'classifyBenchmark' = classifier , 'presentation' = 'Groups' 'PercentDiff' , 'selectBenchmarks' = \f -> reverse $ map fst } @ @ (time)(Median)(Diff using min estimator) Benchmark streamly(0)(μs)(base) streamly(1)(%)(-base) --------- --------------------- --------------------- @ Graphically: <<docs/regression-percent-descending-median-time.svg Median Time Regression>>
# OPTIONS_GHC -fno - warn - unused - imports # Module : . Tutorial Copyright : ( c ) 2018 Composewell Technologies BenchShow generates text reports and graphs from benchmarking results . It to present it in many useful ways . uses robust statistical analysis using three different statistical estimators to provide as stable module BenchShow.Tutorial ( ) where import BenchShow libraries , define some benchmarks and run it with = results.csv@. The resulting @results.csv@ may look like the following , for simplicity we Name , time , streamly / fold,6.399582632376517e-4,2879488 streamly / map,6.533649051066093e-4,2793472 streamly / zip,6.443344209329669e-4,2711552 appended to the file . BenchShow can compare two or more result sets and to a BenchShow application . @maxrss@ or @allocated@ and many more . program for each benchmark . The ' report ' API with ' ' presentation ' report ' " results.csv " Nothing ' defaultConfig ' { ' presentation ' = ' ' } ( default)(Median ) vector / fold 641.62 2.75 streamly / fold 639.96 2.75 vector / map 638.89 2.72 streamly / map 653.36 2.66 vector / zip 651.42 2.58 streamly / zip 644.33 2.59 We can generate equivalent visual report using ' graph ' , it generates one bar : bench - > Just ( grp , concat bench ) Now we can show the two benchmark groups as columns each showing the time benchmark fields ( e.g. @time@ and @maxrss@ ) for all the groups : : ( time)(Median ) Benchmark streamly(μs ) vector(μs ) fold 639.96 641.62 map 653.36 638.89 zip 644.33 651.42 We can make the first group as baseline and report the subsequent groups as fold 639.96 +1.66 map 653.36 -14.47 zip 644.33 +7.09 In a chart , the second cluster plots the difference @streamly - vector@. < < docs / grouped - delta - median - time.svg Median Time Grouped Delta > > fold 639.96 +0.26 map 653.36 -2.22 zip 644.33 +1.10 fold 639.96 +0.26 map 653.36 -2.22 zip 644.33 +1.10 A ' DiffStrategy ' controls how the difference between two groups being compared is arrived at . By default we use the ' MinEstimators ' strategy which fold 639.96 +0.26 map 653.36 -2.22 zip 644.33 +1.10 $ sortBy ( comparing snd ) $ either error i d $ f ( ' ColumnIndex ' 1 ) Nothing zip 644.33 +1.10 fold 639.96 +0.26 map 653.36 -2.22 to streamly , as it takes 1.10 % more time , whereas map is the best taking 2.22 % less time .. Given the following results file with two runs appended : streamly / streamly / zip,2.960114434592148e-2 streamly / map,2.4673020708256527e-2 streamly / fold,8.970816964261911e-3 streamly / zip,8.439519884529081e-3 streamly / map,6.972814233286865e-3 $ sortBy ( comparing snd ) $ either error i d $ f ( ' ColumnIndex ' 1 ) Nothing zip 644.33 +23.28 map 653.36 +7.65 fold 639.96 -15.63 It tells us that in the second run the worst affected benchmark is zip taking 23.28 percent more time comapred to the baseline .
ad8384ce6ec08277ffaf2fd4105e5877905feafade60ef45835bc6197502ba7e
brendanhay/amazonka
ChoiceContent.hs
# LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE NamedFieldPuns # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Derived from AWS service descriptions , licensed under Apache 2.0 . -- | -- Module : Amazonka.WellArchitected.Types.ChoiceContent Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) module Amazonka.WellArchitected.Types.ChoiceContent where import qualified Amazonka.Core as Core import qualified Amazonka.Core.Lens.Internal as Lens import qualified Amazonka.Data as Data import qualified Amazonka.Prelude as Prelude -- | The choice content. -- -- /See:/ 'newChoiceContent' smart constructor. data ChoiceContent = ChoiceContent' { -- | The display text for the choice content. displayText :: Prelude.Maybe Prelude.Text, -- | The URL for the choice content. url :: Prelude.Maybe Prelude.Text } deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic) -- | Create a value of ' ChoiceContent ' with all optional fields omitted . -- Use < -lens generic - lens > or < optics > to modify other optional fields . -- -- The following record fields are available, with the corresponding lenses provided -- for backwards compatibility: -- -- 'displayText', 'choiceContent_displayText' - The display text for the choice content. -- -- 'url', 'choiceContent_url' - The URL for the choice content. newChoiceContent :: ChoiceContent newChoiceContent = ChoiceContent' { displayText = Prelude.Nothing, url = Prelude.Nothing } -- | The display text for the choice content. choiceContent_displayText :: Lens.Lens' ChoiceContent (Prelude.Maybe Prelude.Text) choiceContent_displayText = Lens.lens (\ChoiceContent' {displayText} -> displayText) (\s@ChoiceContent' {} a -> s {displayText = a} :: ChoiceContent) -- | The URL for the choice content. choiceContent_url :: Lens.Lens' ChoiceContent (Prelude.Maybe Prelude.Text) choiceContent_url = Lens.lens (\ChoiceContent' {url} -> url) (\s@ChoiceContent' {} a -> s {url = a} :: ChoiceContent) instance Data.FromJSON ChoiceContent where parseJSON = Data.withObject "ChoiceContent" ( \x -> ChoiceContent' Prelude.<$> (x Data..:? "DisplayText") Prelude.<*> (x Data..:? "Url") ) instance Prelude.Hashable ChoiceContent where hashWithSalt _salt ChoiceContent' {..} = _salt `Prelude.hashWithSalt` displayText `Prelude.hashWithSalt` url instance Prelude.NFData ChoiceContent where rnf ChoiceContent' {..} = Prelude.rnf displayText `Prelude.seq` Prelude.rnf url
null
https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-wellarchitected/gen/Amazonka/WellArchitected/Types/ChoiceContent.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Module : Amazonka.WellArchitected.Types.ChoiceContent Stability : auto-generated | The choice content. /See:/ 'newChoiceContent' smart constructor. | The display text for the choice content. | The URL for the choice content. | The following record fields are available, with the corresponding lenses provided for backwards compatibility: 'displayText', 'choiceContent_displayText' - The display text for the choice content. 'url', 'choiceContent_url' - The URL for the choice content. | The display text for the choice content. | The URL for the choice content.
# LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE NamedFieldPuns # # LANGUAGE RecordWildCards # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Derived from AWS service descriptions , licensed under Apache 2.0 . Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Amazonka.WellArchitected.Types.ChoiceContent where import qualified Amazonka.Core as Core import qualified Amazonka.Core.Lens.Internal as Lens import qualified Amazonka.Data as Data import qualified Amazonka.Prelude as Prelude data ChoiceContent = ChoiceContent' displayText :: Prelude.Maybe Prelude.Text, url :: Prelude.Maybe Prelude.Text } deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic) Create a value of ' ChoiceContent ' with all optional fields omitted . Use < -lens generic - lens > or < optics > to modify other optional fields . newChoiceContent :: ChoiceContent newChoiceContent = ChoiceContent' { displayText = Prelude.Nothing, url = Prelude.Nothing } choiceContent_displayText :: Lens.Lens' ChoiceContent (Prelude.Maybe Prelude.Text) choiceContent_displayText = Lens.lens (\ChoiceContent' {displayText} -> displayText) (\s@ChoiceContent' {} a -> s {displayText = a} :: ChoiceContent) choiceContent_url :: Lens.Lens' ChoiceContent (Prelude.Maybe Prelude.Text) choiceContent_url = Lens.lens (\ChoiceContent' {url} -> url) (\s@ChoiceContent' {} a -> s {url = a} :: ChoiceContent) instance Data.FromJSON ChoiceContent where parseJSON = Data.withObject "ChoiceContent" ( \x -> ChoiceContent' Prelude.<$> (x Data..:? "DisplayText") Prelude.<*> (x Data..:? "Url") ) instance Prelude.Hashable ChoiceContent where hashWithSalt _salt ChoiceContent' {..} = _salt `Prelude.hashWithSalt` displayText `Prelude.hashWithSalt` url instance Prelude.NFData ChoiceContent where rnf ChoiceContent' {..} = Prelude.rnf displayText `Prelude.seq` Prelude.rnf url
e5c08fc9f06018c7ab31cd9b92c91fe0723722c37ee8bfbc383913aa49112e4c
caolan/chicken-leveldb
run.scm
(use level leveldb posix test lazy-seq test-generative srfi-69 srfi-4) ; attempting to open db that doesn't exist (if (directory? "testdb") (delete-directory "testdb" #t)) (test-group "basic operation" (test "opening missing db should error when create_if_missing: #f" 'does-not-exist (condition-case (open-db "testdb" create: #f) ((exn leveldb) 'does-not-exist))) (define db (open-db "testdb")) (test-assert "open-db should return a level record" (level? db)) (test "put then get value" "bar" (begin (db-put db "foo" "bar") (db-get db "foo"))) (let ((key (list->string '(#\f #\o #\o #\nul))) (val (list->string '(#\b #\a #\r #\nul)))) (db-put db key val) (db-put db key val) (test "null bytes in keys and values" val (db-get db key))) (test-error "error on missing key" (db-get db "asdf")) (test "db-get/default on missing key" "ASDF" (db-get/default db "asdf" "ASDF")) ;; delete previously added keys (db-delete db "foo") (db-delete db (list->string '(#\f #\o #\o #\nul))) (test-error "attempt to get foo after deleting should return #f" (db-get db "foo")) (define ops '((put "1" "one") (put "asdf" "asdf") (put "2" "two") (put "3" "three") (delete "asdf"))) (db-batch db ops) (test "get 1 after batch" "one" (db-get db "1")) (test "get 2 after batch" "two" (db-get db "2")) (test "get 3 after batch" "three" (db-get db "3")) (test "stream from 2 limit 1" '(("2" . "two")) (lazy-seq->list (db-pairs db start: "2" limit: 1))) (test "stream from 2 limit 2" '(("2" . "two") ("3" . "three")) (lazy-seq->list (db-pairs db start: "2" limit: 2))) (test "stream from start limit 2" '(("1" . "one") ("2" . "two")) (lazy-seq->list (db-pairs db limit: 2))) (test "stream from start no limit" '(("1" . "one") ("2" . "two") ("3" . "three")) (lazy-seq->list (db-pairs db))) (test "stream from start no limit end 2" '(("1" . "one") ("2" . "two")) (lazy-seq->list (db-pairs db end: "2"))) (test "stream from start 2 limit 2 end 2" '(("2" . "two")) (lazy-seq->list (db-pairs db start: "2" end: "2" limit: 2))) (test "stream from start 2 limit 1 end 3" '(("2" . "two")) (lazy-seq->list (db-pairs db start: "2" end: "3" limit: 1))) (test "stream keys from start 1 end 3" '("1" "2" "3") (lazy-seq->list (db-keys db start: "1" end: "3" key: #t value: #f))) (test "stream values from start 1 end 3" '("one" "two" "three") (lazy-seq->list (db-values db start: "1" end: "3" key: #f value: #t))) (test "stream reverse start 3 end 2" '(("3" . "three") ("2" . "two")) (lazy-seq->list (db-pairs db reverse: #t start: "3" end: "2"))) (test "stream reverse start 3 limit 3" '(("3" . "three") ("2" . "two") ("1" . "one")) (lazy-seq->list (db-pairs db reverse: #t start: "3" limit: 3))) (db-batch db '((put "four\x00zzz" "000") (put "four\x00def" "456") (put "four\x00abc" "123") (put "three\x00one" "foo") (put "three\x00two" "bar"))) (test "stream reverse with start, end and keys including nul" '(("four\x00zzz" . "000") ("four\x00def" . "456") ("four\x00abc" . "123")) (lazy-seq->list (db-pairs db reverse: #t start: "four\x00\xff" end: "four\x00"))) (close-db db) (test-error "opening existing db should error when exists: #f" (open-db "testdb" exists: #f)) (test-assert "opening existing db should not error by default" (close-db (open-db "testdb"))) ;; run with valgrind to check call-with-db cleans up (test "call-with-db returns value of proc" "one" (call-with-db "testdb" (lambda (db) (db-get db "1")))) (test-error "call-with-db exceptions exposed" (call-with-db "testdb" (lambda (db) (abort "fail"))))) (test-group "throw some random data at it" (if (directory? "testdb") (delete-directory "testdb" #t)) (define db (open-db "testdb")) (define data (make-hash-table)) (define (random-string) (blob->string (u8vector->blob (list->u8vector (list-tabulate 100 (lambda (i) (random 256))))))) (parameterize ((current-test-generative-iterations 1000)) (test-generative ((k random-string) (v random-string)) (db-batch db (list (list 'put k v))) (let ((r (db-get db k))) (test "returned matches PUT" v r)))) (close-db db)) (test-group "large keys/values (100MB)" (define db (open-db "testdb")) (let ((key (make-string (* 1024 1024 100) #\k)) (val (make-string (* 1024 1024 100) #\v))) (db-put db key val) (test "get value" val (db-get db key)) (test "stream key and value" (list (cons key val)) (lazy-seq->list (db-pairs db start: key limit: 1)))) (close-db db)) (test-group "error conditions" (define db (open-db "testdb")) (test-assert "not-found" (condition-case (db-get db "MISSING") ((exn leveldb not-found) #t) (() #f))) (test-assert "open locked db" (condition-case (open-db "testdb") ((exn leveldb) #t) (() #f)))) (test-exit)
null
https://raw.githubusercontent.com/caolan/chicken-leveldb/26a9d5fbaa82e710292c391f03e5dee033ade886/tests/run.scm
scheme
attempting to open db that doesn't exist delete previously added keys run with valgrind to check call-with-db cleans up
(use level leveldb posix test lazy-seq test-generative srfi-69 srfi-4) (if (directory? "testdb") (delete-directory "testdb" #t)) (test-group "basic operation" (test "opening missing db should error when create_if_missing: #f" 'does-not-exist (condition-case (open-db "testdb" create: #f) ((exn leveldb) 'does-not-exist))) (define db (open-db "testdb")) (test-assert "open-db should return a level record" (level? db)) (test "put then get value" "bar" (begin (db-put db "foo" "bar") (db-get db "foo"))) (let ((key (list->string '(#\f #\o #\o #\nul))) (val (list->string '(#\b #\a #\r #\nul)))) (db-put db key val) (db-put db key val) (test "null bytes in keys and values" val (db-get db key))) (test-error "error on missing key" (db-get db "asdf")) (test "db-get/default on missing key" "ASDF" (db-get/default db "asdf" "ASDF")) (db-delete db "foo") (db-delete db (list->string '(#\f #\o #\o #\nul))) (test-error "attempt to get foo after deleting should return #f" (db-get db "foo")) (define ops '((put "1" "one") (put "asdf" "asdf") (put "2" "two") (put "3" "three") (delete "asdf"))) (db-batch db ops) (test "get 1 after batch" "one" (db-get db "1")) (test "get 2 after batch" "two" (db-get db "2")) (test "get 3 after batch" "three" (db-get db "3")) (test "stream from 2 limit 1" '(("2" . "two")) (lazy-seq->list (db-pairs db start: "2" limit: 1))) (test "stream from 2 limit 2" '(("2" . "two") ("3" . "three")) (lazy-seq->list (db-pairs db start: "2" limit: 2))) (test "stream from start limit 2" '(("1" . "one") ("2" . "two")) (lazy-seq->list (db-pairs db limit: 2))) (test "stream from start no limit" '(("1" . "one") ("2" . "two") ("3" . "three")) (lazy-seq->list (db-pairs db))) (test "stream from start no limit end 2" '(("1" . "one") ("2" . "two")) (lazy-seq->list (db-pairs db end: "2"))) (test "stream from start 2 limit 2 end 2" '(("2" . "two")) (lazy-seq->list (db-pairs db start: "2" end: "2" limit: 2))) (test "stream from start 2 limit 1 end 3" '(("2" . "two")) (lazy-seq->list (db-pairs db start: "2" end: "3" limit: 1))) (test "stream keys from start 1 end 3" '("1" "2" "3") (lazy-seq->list (db-keys db start: "1" end: "3" key: #t value: #f))) (test "stream values from start 1 end 3" '("one" "two" "three") (lazy-seq->list (db-values db start: "1" end: "3" key: #f value: #t))) (test "stream reverse start 3 end 2" '(("3" . "three") ("2" . "two")) (lazy-seq->list (db-pairs db reverse: #t start: "3" end: "2"))) (test "stream reverse start 3 limit 3" '(("3" . "three") ("2" . "two") ("1" . "one")) (lazy-seq->list (db-pairs db reverse: #t start: "3" limit: 3))) (db-batch db '((put "four\x00zzz" "000") (put "four\x00def" "456") (put "four\x00abc" "123") (put "three\x00one" "foo") (put "three\x00two" "bar"))) (test "stream reverse with start, end and keys including nul" '(("four\x00zzz" . "000") ("four\x00def" . "456") ("four\x00abc" . "123")) (lazy-seq->list (db-pairs db reverse: #t start: "four\x00\xff" end: "four\x00"))) (close-db db) (test-error "opening existing db should error when exists: #f" (open-db "testdb" exists: #f)) (test-assert "opening existing db should not error by default" (close-db (open-db "testdb"))) (test "call-with-db returns value of proc" "one" (call-with-db "testdb" (lambda (db) (db-get db "1")))) (test-error "call-with-db exceptions exposed" (call-with-db "testdb" (lambda (db) (abort "fail"))))) (test-group "throw some random data at it" (if (directory? "testdb") (delete-directory "testdb" #t)) (define db (open-db "testdb")) (define data (make-hash-table)) (define (random-string) (blob->string (u8vector->blob (list->u8vector (list-tabulate 100 (lambda (i) (random 256))))))) (parameterize ((current-test-generative-iterations 1000)) (test-generative ((k random-string) (v random-string)) (db-batch db (list (list 'put k v))) (let ((r (db-get db k))) (test "returned matches PUT" v r)))) (close-db db)) (test-group "large keys/values (100MB)" (define db (open-db "testdb")) (let ((key (make-string (* 1024 1024 100) #\k)) (val (make-string (* 1024 1024 100) #\v))) (db-put db key val) (test "get value" val (db-get db key)) (test "stream key and value" (list (cons key val)) (lazy-seq->list (db-pairs db start: key limit: 1)))) (close-db db)) (test-group "error conditions" (define db (open-db "testdb")) (test-assert "not-found" (condition-case (db-get db "MISSING") ((exn leveldb not-found) #t) (() #f))) (test-assert "open locked db" (condition-case (open-db "testdb") ((exn leveldb) #t) (() #f)))) (test-exit)
2e55b2533c4ec803c64504b690007edffbd26040789712ef52f5bb3e619ea3be
bcc32/projecteuler-ocaml
sol_016.ml
open! Core open! Import let sum_digits n base = let open Bigint in let rec iter n acc = if n = zero then acc else iter (n / base) ((n % base) + acc) in iter n zero ;; let main () = let open Bigint in let base = of_int 2 in let expt = of_int 1000 in let num = pow base expt in sum_digits num (of_int 10) |> to_int_exn |> printf "%d\n" ;; let%expect_test "answer" = main (); [%expect {| 1366 |}] ;; include (val Solution.make ~problem:(Number 16) ~main)
null
https://raw.githubusercontent.com/bcc32/projecteuler-ocaml/712f85902c70adc1ec13dcbbee456c8bfa8450b2/sol/sol_016.ml
ocaml
open! Core open! Import let sum_digits n base = let open Bigint in let rec iter n acc = if n = zero then acc else iter (n / base) ((n % base) + acc) in iter n zero ;; let main () = let open Bigint in let base = of_int 2 in let expt = of_int 1000 in let num = pow base expt in sum_digits num (of_int 10) |> to_int_exn |> printf "%d\n" ;; let%expect_test "answer" = main (); [%expect {| 1366 |}] ;; include (val Solution.make ~problem:(Number 16) ~main)
82b1ceca6794fd78c5da925573b4796bc5ad09e75910e129200f0baf45845a43
yaxu/hstexture
Types.hs
module Texture.Types where import Data.Maybe import Control.Applicative import Data.Tuple (swap) import Debug.Trace (trace) import Data.List (intercalate, intersectBy, nub) import Texture.Utils --type Id = Int --type Proximity = Float data Type = F Type Type | String | Float | Int | Osc | OscStream | OneOf [Type] | Pattern Type | WildCard | Param Int | ListCon Type instance Eq Type where F a a' == F b b' = and [a == b, a' == b' ] String == String = True Float == Float = True Int == Int = True Osc == Osc = True OscStream == OscStream = True OneOf as == OneOf bs = as == bs Pattern a == Pattern b = a == b WildCard == WildCard = True Param a == Param b = a == b ListCon a == ListCon b = a == b _ == _ = False -- Type signature data Sig = Sig {params :: [Type], is :: Type } deriving Eq instance Show Sig where show s = ps ++ (show $ is s) where ps | params s == [] = "" | otherwise = show (params s) ++ " => " showFunctions :: String showFunctions = concatMap f functions where f (s, t) = s ++ " :: " ++ show t ++ "\n" functions :: [(String, Sig)] functions = [("+", numOp), ("-", numOp), ("/", floatOp), ("*", numOp), ("#", Sig [] $ F (Pattern Osc) (F (Pattern Osc) (Pattern Osc))), ("striate", Sig [] $ F Int (F (Pattern Osc) (Pattern Osc))), ("floor", Sig [] $ F Float Int), ("sinewave", floatPat), ("sinewave1", floatPat), ("sine", floatPat), ("sine1", floatPat), ("run", Sig [] $ F Int (Pattern Int)), ("fmap", mapper), ("<$>", mapper), ("<*>", Sig [WildCard, WildCard] $ F (Pattern $ F (Param 0) (Param 1)) (F (Pattern (Param 0)) (Pattern (Param 1)))), ("sound", stringToOsc), ("vowel", stringToOsc), ("shape", floatToOsc), ("speed", floatToOsc), ("delay", floatToOsc), ("pan", floatToOsc), ("overlay", Sig [WildCard] $ F (Pattern $ Param 0) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("append", Sig [WildCard] $ F (Pattern $ Param 0) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("append'", Sig [WildCard] $ F (Pattern $ Param 0) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("silence", Sig [] $ Pattern WildCard), ("density", Sig [WildCard] $ F (Float) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("fast", Sig [WildCard] $ F (Float) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("slow", Sig [WildCard] $ F (Float) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("iter", Sig [WildCard] $ F (Int) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("spin", Sig [] $ F (Int) (F (Pattern $ Osc) (Pattern $ Osc))), ("stut", Sig [] $ F (Int) $ F (Float) $ F (Float) $ (F (Pattern Osc) (Pattern Osc))), ("<~", Sig [WildCard] $ F (Float) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("~>", Sig [WildCard] $ F (Float) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("every", Sig [WildCard] $ F (Int) (F (F (Pattern $ Param 0) (Pattern $ Param 0)) (F (Pattern $ Param 0) (Pattern $ Param 0)) ) ), ("chunk", Sig [WildCard] $ F (Int) (F (F (Pattern $ Param 0) (Pattern $ Param 0)) (F (Pattern $ Param 0) (Pattern $ Param 0)) ) ), ("jux", Sig [] (F (F (Pattern Osc) (Pattern Osc)) (F (Pattern Osc) (Pattern Osc)) ) ), ("superimpose", Sig [] (F (F (Pattern Osc) (Pattern Osc)) (F (Pattern Osc) (Pattern Osc)) ) ), ("wedge", Sig [WildCard] $ F (Float) (F (Pattern $ Param 0) (F (Pattern $ Param 0) (Pattern $ Param 0)))), ("rev", Sig [WildCard] $ F (Pattern $ Param 0) (Pattern $ Param 0)), ("brak", Sig [WildCard] $ F (Pattern $ Param 0) (Pattern $ Param 0)), ("pick", Sig [] $ F String (F Int String)), ("]", Sig [OneOf [String,Int,Float]] (ListCon (Param 0))), ("[", Sig [OneOf [String,Int,Float]] (F (ListCon (Param 0)) (Pattern (Param 0)))) , ( " bd " , ) , ( " sn " , ) , ( " hc " , ) , ( " cp " , ) , ( " a " , prependString ) , ( " e " , prependString ) , ( " i " , prependString ) , ( " o " , prependString ) , ( " u " , ) , ( " gabba " , ) , ( " ~ " , prependString ) ("bd", prependString), ("sn", prependString), ("hc", prependString), ("cp", prependString), ("a", prependString), ("e", prependString), ("i", prependString), ("o", prependString), ("u", prependString), ("gabba", prependString), ("~", prependString)-} ] where numOp = Sig [number] $ F (Param 0) $ F (Param 0) (Param 0) floatOp = Sig [] $ F Float (F Float Float) floatPat = Sig [] $ Pattern Float mapper = Sig [WildCard, WildCard] $ F (F (Param 0) (Param 1)) $ F (Pattern (Param 0)) (Pattern (Param 1)) stringToOsc = Sig [] $ F (Pattern String) (Pattern Osc) floatToOsc = Sig [] $ F (Pattern Float) (Pattern Osc) prepender a = Sig [ ] $ F ( List a ) ( List a ) prependString = prepender String prepender a = Sig [] $ F (List a) (List a) prependString = prepender String -} {- [ :: List a -> Pattern a ] :: a -> List a bd :: List a -> List a -} data Datum = Datum {ident :: Int, token :: String, sig :: Sig, applied_as :: Sig, location :: (Float, Float), applied_location :: (Float, Float), parentId :: Maybe Int, --childId :: Maybe Int, childIds :: [Int] } instance Show Type where show (F a b) = "(" ++ show a ++ " -> " ++ show b ++ ")" show String = "s" show Float = "f" show Int = "i" show (OneOf ts) = "?" ++ (show ts) show (Pattern t) = "p [" ++ (show t) ++ "]" show WildCard = "*" show (Param n) = "param#" ++ (show n) show (Osc) = "osc" show (OscStream) = "stream" show (ListCon t) = "list [" ++ (show t) ++ "]" printDists :: [Datum] -> IO () printDists ds = mapM_ (\(a, b) -> putStrLn (token a ++ " -> " ++ token b ++ ": " ++ show (dist a b))) ps where ps = paired ds paired :: [Datum] -> [(Datum, Datum)] paired ds = map (\x -> (x, datumByIdent (fromJust $ parentId x) ds)) children where children = filter ((/= Nothing) . parentId) ds walkTreesWhere :: (Datum -> Bool) -> [Datum] -> [String] walkTreesWhere f ds = map (walkTree ds) $ tops where tops = filter f $ filter ((== Nothing) . parentId) ds walkTree :: [Datum] -> Datum -> String walkTree ds d@(Datum {token = "["}) = "(parseBP_E \"" ++ contents ++ "\")" where contents = intercalate " " $ map token (tail $ offspring ds d) walkTree ds d@(Datum {token = "]"}) = "" walkTree ds d = value d ++ ps -- ++ " :: " ++ (show $ applied_as d) ++ " parent " ++ (show $ parentId d) where ps = concatMap (" " ++) $ map (parenthesise . recurse) (children ds d) recurse = walkTree ds number = OneOf [Float, Int] isFunction :: Type -> Bool isFunction (F _ _) = True isFunction _ = False isListCon :: Type -> Bool isListCon (ListCon _) = True isListCon _ = False isPattern :: Type -> Bool isPattern (Pattern _) = True isPattern _ = False isPatTransform :: Type -> Bool isPatTransform (F a b) = (isPattern a) && (isPattern b) isPatTransform _ = False -- Look for a function from pattern to pattern, and try to find and -- return a compatible pattern applied to its parent guessTransform :: [Datum] -> Datum -> Maybe (Datum, Type, String) guessTransform ds a | isMetaP = do p <- (parent a ds) sibling <- (single $ fitters p) return $ (a, (fromJust' $ patternType $ appliedConcreteType sibling), (walkTree ds a) ++ " $ " ++ (walkTree ds sibling)) | otherwise = Nothing where isMetaP = hasParent a && isPatTransform (appliedConcreteType a) fitters p = filter (\b -> fits (applied_as b) aInput) (children ds p) aInput = input $ applied_as a patternType :: Type -> Maybe Type patternType (Pattern t) = Just t patternType _ = Nothing appliedType :: Datum -> Type appliedType = is . applied_as appliedConcreteType :: Datum -> Type appliedConcreteType = concreteType . applied_as concreteType :: Sig -> Type concreteType (Sig ps (Pattern x)) = Pattern (concreteType (Sig ps x)) concreteType (Sig ps (Param n)) = concreteType (Sig ps (ps !! n)) concreteType (Sig _ x) = x wantsParam :: Datum -> Bool wantsParam d = (parentId d) == Nothing && (isFunction t || isListCon t ) where t = is $ applied_as $ d parent :: Datum -> [Datum] -> Maybe Datum parent d ds = do i <- parentId d return $ datumByIdent i ds children :: [Datum] -> Datum -> [Datum] children ds d = map (\childId -> datumByIdent childId ds) (childIds d) offspring :: [Datum] -> Datum -> [Datum] offspring ds d = cs ++ concatMap (offspring ds) cs where cs = children ds d hasParent :: Datum -> Bool hasParent = isJust . parentId hasChild :: Datum -> Bool hasChild = not . null . childIds instance Show Datum where show t = intercalate "\n" $ map (\(s, f) -> s ++ ": " ++ (f t)) [("ident", show . ident), ("token", show . token), ("signature", show . sig), ("applied_as", show . applied_as), ("applied", show . childIds), ("location", show . location), ("parent", showSub . parentId), ("children", show . childIds) ] where showSub Nothing = "None" showSub (Just i) = "#" ++ (show $ i) instance Eq Datum where a == b = (ident a) == (ident b) isOscPattern :: Sig -> Bool isOscPattern t = fits t (Sig [] $ Pattern Osc) value :: Datum -> String value x@(Datum {sig = (Sig {is = String})}) = "\"" ++ token x ++ "\"" -- Wrap in parenthesis so that infix operators work value x@(Datum {sig = (Sig {is = F _ _})}) = "(" ++ token x ++ ")" value x = token x update :: Datum -> [Datum] -> [Datum] update thing things = map f things where n = ident thing f x | ident x == n = thing | otherwise = x stringToType :: String -> Type stringToType [] = String stringToType s = scanType Int s where scanType t [] = t scanType Int ('.':[]) = String scanType Int (c:s) | elem c ['0' .. '9'] = scanType Int s | c == '.' = scanType Float s | otherwise = String scanType Float (c:s) | elem c ['0' .. '9'] = scanType Float s | otherwise = String stringToSig :: String -> Sig stringToSig s = fromMaybe def $ lookup s functions where def = Sig [] (stringToType s) {- stringToSig :: String -> Sig stringToSig s = fromMaybe def $ lookup s functions where def | stringToType s == String = prependString | otherwise = Sig [] (stringToType s) -} fits :: Sig -> Sig -> Bool fits (Sig _ WildCard) _ = True fits _ (Sig _ WildCard) = True fits (Sig pA (F a a')) (Sig pB (F b b')) = (fits (Sig pA a) (Sig pB b)) && (fits (Sig pA a') (Sig pB b')) fits (Sig pA (OneOf as)) (Sig pB (OneOf bs)) = intersectBy (\a b -> fits (Sig pA a) (Sig pB b)) as bs /= [] fits (Sig pA (OneOf as)) (Sig pB b) = or $ map (\x -> fits (Sig pA x) (Sig pB b)) as fits (Sig pA a) (Sig pB (OneOf bs)) = or $ map (\x -> fits (Sig pA a) (Sig pB x)) bs fits (Sig pA (Pattern a)) (Sig pB (Pattern b)) = fits (Sig pA a) (Sig pB b) fits (Sig pA (ListCon a)) (Sig pB (ListCon b)) = fits (Sig pA a) (Sig pB b) fits (Sig pA a) (Sig pB (Param b)) = fits (Sig pA a) (Sig pB (pB !! b)) fits (Sig pA (Param a)) (Sig pB b) = fits (Sig pA (pA !! a)) (Sig pB b) fits (Sig _ Float) (Sig _ Float) = True fits (Sig _ Int) (Sig _ Int) = True fits (Sig _ String) (Sig _ String) = True fits (Sig _ OscStream) (Sig _ OscStream) = True fits (Sig _ Osc) (Sig _ Osc) = True fits _ _ = False simplify :: Type -> Type simplify x@(OneOf []) = x -- shouldn't happen.. simplify (OneOf (x:[])) = x simplify (OneOf xs) = OneOf $ nub xs simplify x = x -- Resolve type signature a being applied to a function with type -- signature b. At this point we know they're compatible, but type parameters and " OneOf"s need resolving . (!!!) :: [Type] -> Int -> Type a !!! b | b < length a = a !! b | otherwise = error $ "oh dear, " ++ (show $ 1 + b) ++ "th of " ++ show a resolve :: Sig -> Sig -> Sig resolve (Sig pA (F iA oA)) (Sig pB (F iB oB)) = Sig pA'' (F i o) where Sig pA' i = resolve (Sig pA iA) (Sig pB iB) Sig pA'' o = resolve (Sig pA' oA) (Sig pB oB) resolve (Sig pA (Param nA)) sb = Sig (setIndex pA nA a') (Param nA) where (Sig pA' a') = resolve (Sig pA (pA !!! nA)) sb resolve sa (Sig pB (Param nB)) = resolve sa (Sig pB (pB !! nB)) -- TODO - support Params inside OneOfs resolve (Sig pA (OneOf as)) (Sig pB b) = Sig pA (simplify t) where t = OneOf $ map (\a -> is $ resolve (Sig pA a) (Sig pB b)) matches matches = filter (\a -> fits (Sig pA a) (Sig pB b)) as resolve (Sig pA a) (Sig pB (OneOf bs)) = Sig pA (simplify t) where t = OneOf $ map (\b -> is $ resolve (Sig pA a) (Sig pB b)) matches matches = filter (\b -> fits (Sig pA a) (Sig pB b)) bs resolve a (Sig _ WildCard) = a resolve (Sig _ WildCard) b = b resolve (Sig pA (Pattern a)) (Sig pB (Pattern b)) = Sig pA' (Pattern a') where (Sig pA' a') = resolve (Sig pA a) (Sig pB b) resolve (Sig pA (ListCon a)) (Sig pB (ListCon b)) = Sig pA' (ListCon a') where (Sig pA' a') = resolve (Sig pA a) (Sig pB b) resolve a b = a matchPairs :: (a -> b -> Bool) -> [a] -> [b] -> [(a,b)] matchPairs _ [] _ = [] matchPairs _ _ [] = [] matchPairs eq xs ys = [(x,y) | x <- xs, y <- ys, eq x y] fits pA ( OneOf as ) pB b = or $ map ( \x - > fits pA x pB b ) as fits pA a pB ( OneOf bs ) = or $ map ( \x - > fits pA a pB x ) bs -- replace element i in xs with x setIndex :: [a] -> Int -> a -> [a] setIndex xs i x = (take (i) xs) ++ (x:(drop (i+1) xs)) lookupParam :: [Type] -> Type -> Type lookupParam pX (Param n) | n < length pX = pX !! n | otherwise = error "Can't happen." lookupParam pX (OneOf xs) = OneOf $ map (lookupParam pX) xs lookupParam _ x = x sqr :: Num a => a -> a sqr x = x * x dist :: Datum -> Datum -> Float dist a b = sqrt ((sqr $ (fst $ applied_location a) - (fst $ location b)) + (sqr $ (snd $ applied_location a) - (snd $ location b)) ) -- Recursively build the parse tree build :: [Datum] -> [Datum] build things | linked == Nothing = things | otherwise = build $ fromJust linked where linked = link things -- Find a link link :: [Datum] -> Maybe [Datum] link things = fmap ((updateLinks things) . snd) $ maybeHead $ sortByFst $ tmp where unlinked = filter (not . hasParent) things tmp = concatMap (dists unlinked) fs fs = filter wantsParam things dists :: [Datum] -> Datum -> [(Float, (Datum, Datum))] dists things x = map (\fitter -> (dist x fitter, (x, fitter))) fitters where fitters = filter (\thing -> (thing /= x && fits (input $ applied_as x) (applied_as thing) ) ) things Apply b to a , and resolve the wildcards and " oneof"s updateLinks :: [Datum] -> (Datum, Datum) -> [Datum] updateLinks ds (a, b) = appendChild ds' (a', b') where s = resolve (input $ applied_as a) (applied_as $ b) a' = a {applied_as = (output (applied_as a)) {params = params s}, applied_location = applied_location b } b' = b ds' = update a' ds appendChild :: [Datum] -> (Datum, Datum) -> [Datum] appendChild ds (a, b) = update a' $ update b' $ ds where a' = a {childIds = (childIds a) ++ [ident b]} b' = b {parentId = Just $ ident a} datumByIdent :: Int -> [Datum] -> Datum datumByIdent i ds = head $ filter (\d -> ident d == i) ds output :: Sig -> Sig output (Sig ps (F _ x)) = Sig ps x output x@(Sig _ (ListCon _)) = x output _ = error "No output from non-function" input :: Sig -> Sig input (Sig ps (F x _)) = Sig ps x input (Sig ps (ListCon x)) = Sig ps x input _ = error "No input to non-function"
null
https://raw.githubusercontent.com/yaxu/hstexture/ba2c23009376528d5163b62c91aec1b716d31704/Texture/Types.hs
haskell
type Id = Int type Proximity = Float Type signature [ :: List a -> Pattern a ] :: a -> List a bd :: List a -> List a childId :: Maybe Int, ++ " :: " ++ (show $ applied_as d) ++ " parent " ++ (show $ parentId d) Look for a function from pattern to pattern, and try to find and return a compatible pattern applied to its parent Wrap in parenthesis so that infix operators work stringToSig :: String -> Sig stringToSig s = fromMaybe def $ lookup s functions where def | stringToType s == String = prependString | otherwise = Sig [] (stringToType s) shouldn't happen.. Resolve type signature a being applied to a function with type signature b. At this point we know they're compatible, but type TODO - support Params inside OneOfs replace element i in xs with x Recursively build the parse tree Find a link
module Texture.Types where import Data.Maybe import Control.Applicative import Data.Tuple (swap) import Debug.Trace (trace) import Data.List (intercalate, intersectBy, nub) import Texture.Utils data Type = F Type Type | String | Float | Int | Osc | OscStream | OneOf [Type] | Pattern Type | WildCard | Param Int | ListCon Type instance Eq Type where F a a' == F b b' = and [a == b, a' == b' ] String == String = True Float == Float = True Int == Int = True Osc == Osc = True OscStream == OscStream = True OneOf as == OneOf bs = as == bs Pattern a == Pattern b = a == b WildCard == WildCard = True Param a == Param b = a == b ListCon a == ListCon b = a == b _ == _ = False data Sig = Sig {params :: [Type], is :: Type } deriving Eq instance Show Sig where show s = ps ++ (show $ is s) where ps | params s == [] = "" | otherwise = show (params s) ++ " => " showFunctions :: String showFunctions = concatMap f functions where f (s, t) = s ++ " :: " ++ show t ++ "\n" functions :: [(String, Sig)] functions = [("+", numOp), ("-", numOp), ("/", floatOp), ("*", numOp), ("#", Sig [] $ F (Pattern Osc) (F (Pattern Osc) (Pattern Osc))), ("striate", Sig [] $ F Int (F (Pattern Osc) (Pattern Osc))), ("floor", Sig [] $ F Float Int), ("sinewave", floatPat), ("sinewave1", floatPat), ("sine", floatPat), ("sine1", floatPat), ("run", Sig [] $ F Int (Pattern Int)), ("fmap", mapper), ("<$>", mapper), ("<*>", Sig [WildCard, WildCard] $ F (Pattern $ F (Param 0) (Param 1)) (F (Pattern (Param 0)) (Pattern (Param 1)))), ("sound", stringToOsc), ("vowel", stringToOsc), ("shape", floatToOsc), ("speed", floatToOsc), ("delay", floatToOsc), ("pan", floatToOsc), ("overlay", Sig [WildCard] $ F (Pattern $ Param 0) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("append", Sig [WildCard] $ F (Pattern $ Param 0) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("append'", Sig [WildCard] $ F (Pattern $ Param 0) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("silence", Sig [] $ Pattern WildCard), ("density", Sig [WildCard] $ F (Float) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("fast", Sig [WildCard] $ F (Float) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("slow", Sig [WildCard] $ F (Float) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("iter", Sig [WildCard] $ F (Int) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("spin", Sig [] $ F (Int) (F (Pattern $ Osc) (Pattern $ Osc))), ("stut", Sig [] $ F (Int) $ F (Float) $ F (Float) $ (F (Pattern Osc) (Pattern Osc))), ("<~", Sig [WildCard] $ F (Float) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("~>", Sig [WildCard] $ F (Float) (F (Pattern $ Param 0) (Pattern $ Param 0))), ("every", Sig [WildCard] $ F (Int) (F (F (Pattern $ Param 0) (Pattern $ Param 0)) (F (Pattern $ Param 0) (Pattern $ Param 0)) ) ), ("chunk", Sig [WildCard] $ F (Int) (F (F (Pattern $ Param 0) (Pattern $ Param 0)) (F (Pattern $ Param 0) (Pattern $ Param 0)) ) ), ("jux", Sig [] (F (F (Pattern Osc) (Pattern Osc)) (F (Pattern Osc) (Pattern Osc)) ) ), ("superimpose", Sig [] (F (F (Pattern Osc) (Pattern Osc)) (F (Pattern Osc) (Pattern Osc)) ) ), ("wedge", Sig [WildCard] $ F (Float) (F (Pattern $ Param 0) (F (Pattern $ Param 0) (Pattern $ Param 0)))), ("rev", Sig [WildCard] $ F (Pattern $ Param 0) (Pattern $ Param 0)), ("brak", Sig [WildCard] $ F (Pattern $ Param 0) (Pattern $ Param 0)), ("pick", Sig [] $ F String (F Int String)), ("]", Sig [OneOf [String,Int,Float]] (ListCon (Param 0))), ("[", Sig [OneOf [String,Int,Float]] (F (ListCon (Param 0)) (Pattern (Param 0)))) , ( " bd " , ) , ( " sn " , ) , ( " hc " , ) , ( " cp " , ) , ( " a " , prependString ) , ( " e " , prependString ) , ( " i " , prependString ) , ( " o " , prependString ) , ( " u " , ) , ( " gabba " , ) , ( " ~ " , prependString ) ("bd", prependString), ("sn", prependString), ("hc", prependString), ("cp", prependString), ("a", prependString), ("e", prependString), ("i", prependString), ("o", prependString), ("u", prependString), ("gabba", prependString), ("~", prependString)-} ] where numOp = Sig [number] $ F (Param 0) $ F (Param 0) (Param 0) floatOp = Sig [] $ F Float (F Float Float) floatPat = Sig [] $ Pattern Float mapper = Sig [WildCard, WildCard] $ F (F (Param 0) (Param 1)) $ F (Pattern (Param 0)) (Pattern (Param 1)) stringToOsc = Sig [] $ F (Pattern String) (Pattern Osc) floatToOsc = Sig [] $ F (Pattern Float) (Pattern Osc) prepender a = Sig [ ] $ F ( List a ) ( List a ) prependString = prepender String prepender a = Sig [] $ F (List a) (List a) prependString = prepender String -} data Datum = Datum {ident :: Int, token :: String, sig :: Sig, applied_as :: Sig, location :: (Float, Float), applied_location :: (Float, Float), parentId :: Maybe Int, childIds :: [Int] } instance Show Type where show (F a b) = "(" ++ show a ++ " -> " ++ show b ++ ")" show String = "s" show Float = "f" show Int = "i" show (OneOf ts) = "?" ++ (show ts) show (Pattern t) = "p [" ++ (show t) ++ "]" show WildCard = "*" show (Param n) = "param#" ++ (show n) show (Osc) = "osc" show (OscStream) = "stream" show (ListCon t) = "list [" ++ (show t) ++ "]" printDists :: [Datum] -> IO () printDists ds = mapM_ (\(a, b) -> putStrLn (token a ++ " -> " ++ token b ++ ": " ++ show (dist a b))) ps where ps = paired ds paired :: [Datum] -> [(Datum, Datum)] paired ds = map (\x -> (x, datumByIdent (fromJust $ parentId x) ds)) children where children = filter ((/= Nothing) . parentId) ds walkTreesWhere :: (Datum -> Bool) -> [Datum] -> [String] walkTreesWhere f ds = map (walkTree ds) $ tops where tops = filter f $ filter ((== Nothing) . parentId) ds walkTree :: [Datum] -> Datum -> String walkTree ds d@(Datum {token = "["}) = "(parseBP_E \"" ++ contents ++ "\")" where contents = intercalate " " $ map token (tail $ offspring ds d) walkTree ds d@(Datum {token = "]"}) = "" where ps = concatMap (" " ++) $ map (parenthesise . recurse) (children ds d) recurse = walkTree ds number = OneOf [Float, Int] isFunction :: Type -> Bool isFunction (F _ _) = True isFunction _ = False isListCon :: Type -> Bool isListCon (ListCon _) = True isListCon _ = False isPattern :: Type -> Bool isPattern (Pattern _) = True isPattern _ = False isPatTransform :: Type -> Bool isPatTransform (F a b) = (isPattern a) && (isPattern b) isPatTransform _ = False guessTransform :: [Datum] -> Datum -> Maybe (Datum, Type, String) guessTransform ds a | isMetaP = do p <- (parent a ds) sibling <- (single $ fitters p) return $ (a, (fromJust' $ patternType $ appliedConcreteType sibling), (walkTree ds a) ++ " $ " ++ (walkTree ds sibling)) | otherwise = Nothing where isMetaP = hasParent a && isPatTransform (appliedConcreteType a) fitters p = filter (\b -> fits (applied_as b) aInput) (children ds p) aInput = input $ applied_as a patternType :: Type -> Maybe Type patternType (Pattern t) = Just t patternType _ = Nothing appliedType :: Datum -> Type appliedType = is . applied_as appliedConcreteType :: Datum -> Type appliedConcreteType = concreteType . applied_as concreteType :: Sig -> Type concreteType (Sig ps (Pattern x)) = Pattern (concreteType (Sig ps x)) concreteType (Sig ps (Param n)) = concreteType (Sig ps (ps !! n)) concreteType (Sig _ x) = x wantsParam :: Datum -> Bool wantsParam d = (parentId d) == Nothing && (isFunction t || isListCon t ) where t = is $ applied_as $ d parent :: Datum -> [Datum] -> Maybe Datum parent d ds = do i <- parentId d return $ datumByIdent i ds children :: [Datum] -> Datum -> [Datum] children ds d = map (\childId -> datumByIdent childId ds) (childIds d) offspring :: [Datum] -> Datum -> [Datum] offspring ds d = cs ++ concatMap (offspring ds) cs where cs = children ds d hasParent :: Datum -> Bool hasParent = isJust . parentId hasChild :: Datum -> Bool hasChild = not . null . childIds instance Show Datum where show t = intercalate "\n" $ map (\(s, f) -> s ++ ": " ++ (f t)) [("ident", show . ident), ("token", show . token), ("signature", show . sig), ("applied_as", show . applied_as), ("applied", show . childIds), ("location", show . location), ("parent", showSub . parentId), ("children", show . childIds) ] where showSub Nothing = "None" showSub (Just i) = "#" ++ (show $ i) instance Eq Datum where a == b = (ident a) == (ident b) isOscPattern :: Sig -> Bool isOscPattern t = fits t (Sig [] $ Pattern Osc) value :: Datum -> String value x@(Datum {sig = (Sig {is = String})}) = "\"" ++ token x ++ "\"" value x@(Datum {sig = (Sig {is = F _ _})}) = "(" ++ token x ++ ")" value x = token x update :: Datum -> [Datum] -> [Datum] update thing things = map f things where n = ident thing f x | ident x == n = thing | otherwise = x stringToType :: String -> Type stringToType [] = String stringToType s = scanType Int s where scanType t [] = t scanType Int ('.':[]) = String scanType Int (c:s) | elem c ['0' .. '9'] = scanType Int s | c == '.' = scanType Float s | otherwise = String scanType Float (c:s) | elem c ['0' .. '9'] = scanType Float s | otherwise = String stringToSig :: String -> Sig stringToSig s = fromMaybe def $ lookup s functions where def = Sig [] (stringToType s) fits :: Sig -> Sig -> Bool fits (Sig _ WildCard) _ = True fits _ (Sig _ WildCard) = True fits (Sig pA (F a a')) (Sig pB (F b b')) = (fits (Sig pA a) (Sig pB b)) && (fits (Sig pA a') (Sig pB b')) fits (Sig pA (OneOf as)) (Sig pB (OneOf bs)) = intersectBy (\a b -> fits (Sig pA a) (Sig pB b)) as bs /= [] fits (Sig pA (OneOf as)) (Sig pB b) = or $ map (\x -> fits (Sig pA x) (Sig pB b)) as fits (Sig pA a) (Sig pB (OneOf bs)) = or $ map (\x -> fits (Sig pA a) (Sig pB x)) bs fits (Sig pA (Pattern a)) (Sig pB (Pattern b)) = fits (Sig pA a) (Sig pB b) fits (Sig pA (ListCon a)) (Sig pB (ListCon b)) = fits (Sig pA a) (Sig pB b) fits (Sig pA a) (Sig pB (Param b)) = fits (Sig pA a) (Sig pB (pB !! b)) fits (Sig pA (Param a)) (Sig pB b) = fits (Sig pA (pA !! a)) (Sig pB b) fits (Sig _ Float) (Sig _ Float) = True fits (Sig _ Int) (Sig _ Int) = True fits (Sig _ String) (Sig _ String) = True fits (Sig _ OscStream) (Sig _ OscStream) = True fits (Sig _ Osc) (Sig _ Osc) = True fits _ _ = False simplify :: Type -> Type simplify (OneOf (x:[])) = x simplify (OneOf xs) = OneOf $ nub xs simplify x = x parameters and " OneOf"s need resolving . (!!!) :: [Type] -> Int -> Type a !!! b | b < length a = a !! b | otherwise = error $ "oh dear, " ++ (show $ 1 + b) ++ "th of " ++ show a resolve :: Sig -> Sig -> Sig resolve (Sig pA (F iA oA)) (Sig pB (F iB oB)) = Sig pA'' (F i o) where Sig pA' i = resolve (Sig pA iA) (Sig pB iB) Sig pA'' o = resolve (Sig pA' oA) (Sig pB oB) resolve (Sig pA (Param nA)) sb = Sig (setIndex pA nA a') (Param nA) where (Sig pA' a') = resolve (Sig pA (pA !!! nA)) sb resolve sa (Sig pB (Param nB)) = resolve sa (Sig pB (pB !! nB)) resolve (Sig pA (OneOf as)) (Sig pB b) = Sig pA (simplify t) where t = OneOf $ map (\a -> is $ resolve (Sig pA a) (Sig pB b)) matches matches = filter (\a -> fits (Sig pA a) (Sig pB b)) as resolve (Sig pA a) (Sig pB (OneOf bs)) = Sig pA (simplify t) where t = OneOf $ map (\b -> is $ resolve (Sig pA a) (Sig pB b)) matches matches = filter (\b -> fits (Sig pA a) (Sig pB b)) bs resolve a (Sig _ WildCard) = a resolve (Sig _ WildCard) b = b resolve (Sig pA (Pattern a)) (Sig pB (Pattern b)) = Sig pA' (Pattern a') where (Sig pA' a') = resolve (Sig pA a) (Sig pB b) resolve (Sig pA (ListCon a)) (Sig pB (ListCon b)) = Sig pA' (ListCon a') where (Sig pA' a') = resolve (Sig pA a) (Sig pB b) resolve a b = a matchPairs :: (a -> b -> Bool) -> [a] -> [b] -> [(a,b)] matchPairs _ [] _ = [] matchPairs _ _ [] = [] matchPairs eq xs ys = [(x,y) | x <- xs, y <- ys, eq x y] fits pA ( OneOf as ) pB b = or $ map ( \x - > fits pA x pB b ) as fits pA a pB ( OneOf bs ) = or $ map ( \x - > fits pA a pB x ) bs setIndex :: [a] -> Int -> a -> [a] setIndex xs i x = (take (i) xs) ++ (x:(drop (i+1) xs)) lookupParam :: [Type] -> Type -> Type lookupParam pX (Param n) | n < length pX = pX !! n | otherwise = error "Can't happen." lookupParam pX (OneOf xs) = OneOf $ map (lookupParam pX) xs lookupParam _ x = x sqr :: Num a => a -> a sqr x = x * x dist :: Datum -> Datum -> Float dist a b = sqrt ((sqr $ (fst $ applied_location a) - (fst $ location b)) + (sqr $ (snd $ applied_location a) - (snd $ location b)) ) build :: [Datum] -> [Datum] build things | linked == Nothing = things | otherwise = build $ fromJust linked where linked = link things link :: [Datum] -> Maybe [Datum] link things = fmap ((updateLinks things) . snd) $ maybeHead $ sortByFst $ tmp where unlinked = filter (not . hasParent) things tmp = concatMap (dists unlinked) fs fs = filter wantsParam things dists :: [Datum] -> Datum -> [(Float, (Datum, Datum))] dists things x = map (\fitter -> (dist x fitter, (x, fitter))) fitters where fitters = filter (\thing -> (thing /= x && fits (input $ applied_as x) (applied_as thing) ) ) things Apply b to a , and resolve the wildcards and " oneof"s updateLinks :: [Datum] -> (Datum, Datum) -> [Datum] updateLinks ds (a, b) = appendChild ds' (a', b') where s = resolve (input $ applied_as a) (applied_as $ b) a' = a {applied_as = (output (applied_as a)) {params = params s}, applied_location = applied_location b } b' = b ds' = update a' ds appendChild :: [Datum] -> (Datum, Datum) -> [Datum] appendChild ds (a, b) = update a' $ update b' $ ds where a' = a {childIds = (childIds a) ++ [ident b]} b' = b {parentId = Just $ ident a} datumByIdent :: Int -> [Datum] -> Datum datumByIdent i ds = head $ filter (\d -> ident d == i) ds output :: Sig -> Sig output (Sig ps (F _ x)) = Sig ps x output x@(Sig _ (ListCon _)) = x output _ = error "No output from non-function" input :: Sig -> Sig input (Sig ps (F x _)) = Sig ps x input (Sig ps (ListCon x)) = Sig ps x input _ = error "No input to non-function"
2e9dead4d3e995b6c45cf0ad48f9b9b5ed513d8903216b7ccd739c0bc1c9ba58
mbj/stratosphere
RegexPatternSetReferenceStatementProperty.hs
module Stratosphere.WAFv2.WebACL.RegexPatternSetReferenceStatementProperty ( module Exports, RegexPatternSetReferenceStatementProperty(..), mkRegexPatternSetReferenceStatementProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import {-# SOURCE #-} Stratosphere.WAFv2.WebACL.FieldToMatchProperty as Exports import {-# SOURCE #-} Stratosphere.WAFv2.WebACL.TextTransformationProperty as Exports import Stratosphere.ResourceProperties import Stratosphere.Value data RegexPatternSetReferenceStatementProperty = RegexPatternSetReferenceStatementProperty {arn :: (Value Prelude.Text), fieldToMatch :: FieldToMatchProperty, textTransformations :: [TextTransformationProperty]} mkRegexPatternSetReferenceStatementProperty :: Value Prelude.Text -> FieldToMatchProperty -> [TextTransformationProperty] -> RegexPatternSetReferenceStatementProperty mkRegexPatternSetReferenceStatementProperty arn fieldToMatch textTransformations = RegexPatternSetReferenceStatementProperty {arn = arn, fieldToMatch = fieldToMatch, textTransformations = textTransformations} instance ToResourceProperties RegexPatternSetReferenceStatementProperty where toResourceProperties RegexPatternSetReferenceStatementProperty {..} = ResourceProperties {awsType = "AWS::WAFv2::WebACL.RegexPatternSetReferenceStatement", supportsTags = Prelude.False, properties = ["Arn" JSON..= arn, "FieldToMatch" JSON..= fieldToMatch, "TextTransformations" JSON..= textTransformations]} instance JSON.ToJSON RegexPatternSetReferenceStatementProperty where toJSON RegexPatternSetReferenceStatementProperty {..} = JSON.object ["Arn" JSON..= arn, "FieldToMatch" JSON..= fieldToMatch, "TextTransformations" JSON..= textTransformations] instance Property "Arn" RegexPatternSetReferenceStatementProperty where type PropertyType "Arn" RegexPatternSetReferenceStatementProperty = Value Prelude.Text set newValue RegexPatternSetReferenceStatementProperty {..} = RegexPatternSetReferenceStatementProperty {arn = newValue, ..} instance Property "FieldToMatch" RegexPatternSetReferenceStatementProperty where type PropertyType "FieldToMatch" RegexPatternSetReferenceStatementProperty = FieldToMatchProperty set newValue RegexPatternSetReferenceStatementProperty {..} = RegexPatternSetReferenceStatementProperty {fieldToMatch = newValue, ..} instance Property "TextTransformations" RegexPatternSetReferenceStatementProperty where type PropertyType "TextTransformations" RegexPatternSetReferenceStatementProperty = [TextTransformationProperty] set newValue RegexPatternSetReferenceStatementProperty {..} = RegexPatternSetReferenceStatementProperty {textTransformations = newValue, ..}
null
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/wafv2/gen/Stratosphere/WAFv2/WebACL/RegexPatternSetReferenceStatementProperty.hs
haskell
# SOURCE # # SOURCE #
module Stratosphere.WAFv2.WebACL.RegexPatternSetReferenceStatementProperty ( module Exports, RegexPatternSetReferenceStatementProperty(..), mkRegexPatternSetReferenceStatementProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data RegexPatternSetReferenceStatementProperty = RegexPatternSetReferenceStatementProperty {arn :: (Value Prelude.Text), fieldToMatch :: FieldToMatchProperty, textTransformations :: [TextTransformationProperty]} mkRegexPatternSetReferenceStatementProperty :: Value Prelude.Text -> FieldToMatchProperty -> [TextTransformationProperty] -> RegexPatternSetReferenceStatementProperty mkRegexPatternSetReferenceStatementProperty arn fieldToMatch textTransformations = RegexPatternSetReferenceStatementProperty {arn = arn, fieldToMatch = fieldToMatch, textTransformations = textTransformations} instance ToResourceProperties RegexPatternSetReferenceStatementProperty where toResourceProperties RegexPatternSetReferenceStatementProperty {..} = ResourceProperties {awsType = "AWS::WAFv2::WebACL.RegexPatternSetReferenceStatement", supportsTags = Prelude.False, properties = ["Arn" JSON..= arn, "FieldToMatch" JSON..= fieldToMatch, "TextTransformations" JSON..= textTransformations]} instance JSON.ToJSON RegexPatternSetReferenceStatementProperty where toJSON RegexPatternSetReferenceStatementProperty {..} = JSON.object ["Arn" JSON..= arn, "FieldToMatch" JSON..= fieldToMatch, "TextTransformations" JSON..= textTransformations] instance Property "Arn" RegexPatternSetReferenceStatementProperty where type PropertyType "Arn" RegexPatternSetReferenceStatementProperty = Value Prelude.Text set newValue RegexPatternSetReferenceStatementProperty {..} = RegexPatternSetReferenceStatementProperty {arn = newValue, ..} instance Property "FieldToMatch" RegexPatternSetReferenceStatementProperty where type PropertyType "FieldToMatch" RegexPatternSetReferenceStatementProperty = FieldToMatchProperty set newValue RegexPatternSetReferenceStatementProperty {..} = RegexPatternSetReferenceStatementProperty {fieldToMatch = newValue, ..} instance Property "TextTransformations" RegexPatternSetReferenceStatementProperty where type PropertyType "TextTransformations" RegexPatternSetReferenceStatementProperty = [TextTransformationProperty] set newValue RegexPatternSetReferenceStatementProperty {..} = RegexPatternSetReferenceStatementProperty {textTransformations = newValue, ..}
95ba8e0c69366e9f3811a9f7e0fb76e6c6b27a6ad294ce251a51e8a151397260
fukamachi/clozure-cl
swink.lisp
Copyright ( C ) 2011 Clozure Associates This file is part of Clozure CL . ;;; Clozure CL is licensed under the terms of the Lisp Lesser GNU Public License , known as the LLGPL and distributed with Clozure CL as the ;;; file "LICENSE". The LLGPL consists of a preamble and the LGPL, which is distributed with Clozure CL as the file " LGPL " . Where these ;;; conflict, the preamble takes precedence. ;;; ;;; Clozure CL is referenced in the preamble as the "LIBRARY." ;;; ;;; The LLGPL is also available online at ;;; ;;; ;;; Implement a protocol (originally based on swank) for communication between ;;; a lisp and an external debugger. This implements the server side, i.e. the lisp ;;; being debugged. (eval-when (eval compile load) (defpackage :swink (:use :cl :ccl) (:export "START-SERVER" "STOP-SERVER" ;; Some stuff that's also useful on client side "THREAD" "THREAD-CLASS" "THREAD-CONNECTION" "THREAD-ID" "THREAD-CONTROL-PROCESS" "MAKE-NEW-THREAD" "CONNECTION" "FIND-THREAD" "CONNECTION-CONTROL-STREAM" "CONNECTION-CONTROL-PROCESS" "CLOSE-CONNECTION" "TAGGED-OBJECT" "TAG-CALLBACK" "INVOKE-CALLBACK" "ABORT-CALLBACK" "DESTRUCTURE-CASE" "WITH-CONNECTION-LOCK" "WITH-EVENT-HANDLING" "SEND-EVENT" "SEND-EVENT-FOR-VALUE" "SIGNAL-EVENT" "HANDLE-EVENT" "READ-SEXP" ))) (in-package :swink) (defvar *default-server-port* 4003) (defvar *dont-close* nil "Keep listening for more connections on the same port after get the first one") (defvar *external-format* :iso-8859-1) (defvar *swink-lock* (make-lock)) (defmacro with-swink-lock ((&rest lock-options) &body body) `(without-interrupts (with-lock-grabbed (*swink-lock* ,@lock-options) ,@body))) (defmacro destructure-case (value &rest patterns) "Dispatch VALUE to one of PATTERNS. A cross between `case' and `destructuring-bind'. The pattern syntax is: ((HEAD . ARGS) . BODY) The list of patterns is searched for a HEAD `eq' to the car of VALUE. If one is found, the BODY is executed with ARGS bound to the corresponding values in the CDR of VALUE." (let ((operator (gensym "op-")) (operands (gensym "rand-")) (tmp (gensym "tmp-")) (case (if (or (eq (caar (last patterns)) t) (eq (caaar (last patterns)) t)) 'case 'ecase))) `(let* ((,tmp ,value) (,operator (car ,tmp)) (,operands (cdr ,tmp))) (,case ,operator ,@(loop for (pattern . body) in patterns collect (if (eq pattern t) `(t ,@body) (destructuring-bind (op &rest rands) pattern `(,op (destructuring-bind ,rands ,operands ,@body))))))))) (defun string-segment (string start end) (if (and (eql start 0) (eql end (length string))) string (make-array (- end start) :displaced-to string :displaced-index-offset start))) (defun safe-condition-string (condition) (or (ignore-errors (princ-to-string condition)) (ignore-errors (prin1-to-string condition)) (ignore-errors (format nil "Condition of type ~s" (type-of condition))) (ignore-errors (and (typep condition 'error) "<Unprintable error>")) "<Unprintable condition>")) (defun invoke-restart-if-active (restart &rest values) (declare (dynamic-extent values)) (handler-case (apply #'invoke-restart restart values) (ccl::inactive-restart () nil))) (defmethod marshall-argument (conn (process process)) (declare (ignore conn)) (process-serial-number process)) (defmethod marshall-argument (conn (condition condition)) (declare (ignore conn)) (safe-condition-string condition)) (defmethod marshall-argument (conn thing) (declare (ignore conn)) thing) (defun marshall-event (conn event) (flet ((marshall (thing) ;; Only check the top level (marshall-argument conn thing))) (mapcar #'marshall event))) (defvar *log-events* nil) (defvar *log-queue*) (let ((log-lock (make-lock))) (defun log-event (format-string &rest format-args) (when *log-events* (ignore-errors (let* ((string (format nil "[~d] ~?" (process-serial-number *current-process*) format-string format-args))) ;; This kludge is so don't have to disable interrupts while printing. ;; There is a tiny timing screw at end of loop; who cares, it's just for debugging... (if (boundp '*log-queue*) ;; recursive call (without-interrupts (setq *log-queue* (nconc *log-queue* (list string)))) (let ((stream ccl::*stdout*)) (with-lock-grabbed (log-lock "Log Output Lock") (let ((*log-queue* (list string))) (fresh-line stream) (loop for string = (without-interrupts (pop *log-queue*)) while string do (write-string string stream) do (terpri stream)))) (force-output stream)))))))) (defun warn-and-log (format-string &rest format-args) (declare (dynamic-extent format-args)) (apply #'log-event format-string format-args) (apply #'warn format-string format-args)) (defclass connection () ((control-process :initform nil :accessor connection-control-process) (control-stream :initarg :control-stream :reader connection-control-stream) (buffer :initform (make-string 1024) :accessor connection-buffer) (lock :initform (make-lock) :reader connection-lock) (threads :initform nil :accessor %connection-threads) (object-counter :initform most-negative-fixnum :accessor connection-object-counter) (objects :initform nil :accessor connection-objects))) (defmacro with-connection-lock ((conn &rest lock-args) &body body) `(without-interrupts ;; without callbacks (with-lock-grabbed ((connection-lock ,conn) ,@lock-args) ,@body))) (defmethod close-connection ((conn connection)) (log-event "closing connection ~s" conn) (let ((process (connection-control-process conn))) (when process (process-interrupt process 'invoke-restart-if-active 'close-connection)))) (defun tag-object (conn object) (with-connection-lock (conn) (let* ((id (incf (connection-object-counter conn)))) (push (cons id object) (connection-objects conn)) id))) (defun object-tag (conn object) (with-connection-lock (conn) (car (rassoc object (connection-objects conn))))) (defun tagged-object (conn id &key keep-tagged) (if keep-tagged (cdr (assoc id (connection-objects conn))) (with-connection-lock (conn) (let ((cell (assoc id (connection-objects conn)))) (unless cell (warn-and-log "Missing object for remote reference ~s" id)) (setf (connection-objects conn) (delq cell (connection-objects conn))) (cdr cell))))) (defun remove-tag (conn id) (with-connection-lock (conn) (setf (connection-objects conn) (delete id (connection-objects conn) :key #'car)))) (defun tag-callback (conn function) (tag-object conn function)) (defun invoke-callback (conn id &rest values) (declare (dynamic-extent values)) (let ((function (tagged-object conn id))) (when function (apply function t values)))) (defun abort-callback (conn id) (let ((function (tagged-object conn id))) (when function (funcall function nil)))) (defun write-packet (conn string) (let ((stream (connection-control-stream conn))) (assert (<= (length string) #xFFFFFF)) ;; We could have a separate lock for the stream, but we can't really send back anything until ;; this write is finished, so it doesn't hurt much if random stuff is held up while we do this. (with-connection-lock (conn) (format stream "~6,'0,X" (length string)) (write-string string stream)) (force-output stream))) (defvar +swink-io-package+ (loop as name = (gensym "SwinkIO/") while (find-package name) finally (let ((package (make-package name :use nil))) (import '(nil t quote) package) (return package)))) (defun format-for-swink (fmt-string fmt-args) (with-standard-io-syntax (let ((*package* +swink-io-package+)) (apply #'format nil fmt-string fmt-args)))) (defun write-sexp (conn sexp) (write-packet conn (with-standard-io-syntax (let ((*package* +swink-io-package+)) (prin1-to-string sexp))))) (defun send-event (target event &key ignore-errors) (let* ((conn (thread-connection target)) (encoded-event (marshall-event conn event))) (log-event "Send-event ~s to ~a" encoded-event (if (eq target conn) "connection" (princ-to-string (thread-id target)))) (handler-bind ((stream-error (lambda (c) (when (eq (stream-error-stream c) (connection-control-stream conn)) (unless ignore-errors (log-event "send-event error: ~a" c) (close-connection conn)) (return-from send-event))))) (write-sexp conn (cons (thread-id target) encoded-event))))) (defun send-event-if-open (target event) (send-event target event :ignore-errors t)) #-bootstrapped (fmakunbound 'read-sexp) This assumes only one process reads from the command stream or the read - buffer , so do n't need locking . (defmethod read-sexp ((conn connection)) ;; Returns the sexp or :end-connection event (let* ((stream (connection-control-stream conn)) (buffer (connection-buffer conn)) (count (stream-read-vector stream buffer 0 6))) (handler-bind ((stream-error (lambda (c) ;; This includes parse errors as well as i/o errors (when (eql (stream-error-stream c) stream) (log-event "read-sexp error: ~a" c) ( setf ( connection - io - error conn ) t ) (return-from read-sexp `(nil . (:end-connection ,c))))))) (when (< count 6) (ccl::signal-eof-error stream)) (setq count (parse-integer buffer :end 6 :radix 16)) (when (< (length buffer) count) (setq buffer (setf (connection-buffer conn) (make-string count)))) (let ((len (stream-read-vector stream buffer 0 count))) (when (< len count) (ccl::signal-eof-error stream)) ;; TODO: verify that there aren't more forms in the string. (with-standard-io-syntax (let ((*package* +swink-io-package+) (*read-eval* nil)) (read-from-string buffer t nil :end count))))))) (defmethod thread-connection ((conn connection)) conn) ;; Data for processes with swink event handling. (defclass thread () ((connection :initarg :connection :reader thread-connection) (lock :initform (make-lock) :reader thread-lock) (process :initarg :process :accessor thread-process) (event-queue :initform nil :accessor thread-event-queue))) (defmacro with-thread-lock ((thread &rest lock-args) &rest body) `(without-interrupts (with-lock-grabbed ((thread-lock ,thread) ,@lock-args) ,@body))) (defmethod thread-id ((thread thread)) (thread-id (thread-process thread))) (defmethod thread-id ((process process)) (process-serial-number process)) (defmethod thread-id ((id integer)) id) (defmethod marshall-argument (conn (thread thread)) (declare (ignore conn)) (thread-id thread)) (defun connection-threads (conn) (with-connection-lock (conn) (copy-list (%connection-threads conn)))) (defun find-thread (conn id &key (key #'thread-id)) (with-connection-lock (conn) (find id (%connection-threads conn) :key key))) (defmethod make-new-thread ((conn connection) &optional (process *current-process*)) (with-connection-lock (conn) (assert (not (find-thread conn process :key #'thread-process))) (let ((thread (make-instance (thread-class conn) :connection conn :process process))) (push thread (%connection-threads conn)) thread))) (defun queue-event (thread event) (with-thread-lock (thread) (setf (thread-event-queue thread) (nconc (thread-event-queue thread) (list event))))) (defun dequeue-event (thread) (with-thread-lock (thread) (pop (thread-event-queue thread)))) ;; Event handling. ;; Built on conditions rather than semaphores, so events can interrupt a process in i/o wait. (defvar *signal-events* nil) (define-condition events-available () ()) (defun enable-event-handling (thread) (setq *signal-events* t) (loop while (thread-event-queue thread) do (let ((*signal-events* nil)) (handle-events thread)))) (defmacro with-event-handling ((thread &key restart) &body body) (let ((thread-var (gensym "THREAD"))) (if restart `(let ((,thread-var ,thread)) (loop (handler-case (return (let ((*signal-events* *signal-events*)) (enable-event-handling ,thread-var) (with-interrupts-enabled ,@body))) (events-available () (let ((*signal-events* nil)) (handle-events ,thread-var)))))) `(let ((,thread-var ,thread)) (handler-bind ((events-available (lambda (c) (declare (ignore c)) (handle-events ,thread-var)))) (let ((*signal-events* *signal-events*)) (enable-event-handling ,thread-var) (with-interrupts-enabled ,@body))))))) (defun signal-event (thread event) (queue-event thread event) (process-interrupt (or (thread-control-process thread) (error "Got event ~s for thread ~s with no process" event thread)) (lambda () (when *signal-events* (let ((*signal-events* nil)) (signal 'events-available)))))) (defmethod handle-events ((thread thread)) (loop as event = (dequeue-event thread) while event do (handle-event thread event))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Server side: ;; ;; In any process we can enter a read loop which gets its input from a swink connection ;; and sends output to the connection. We can also spawn a process that does nothing else. (defvar *global-debugger* t "Use remote debugger on errors and user events even in non-repl threads") (defclass server-ui-object (ccl::ui-object) ()) (defclass server-connection (connection) ((internal-requests :initform nil :accessor connection-internal-requests))) (defclass server-thread (thread server-ui-object) ((io :initform nil :accessor thread-io))) (defmethod thread-class ((conn server-connection)) 'server-thread) (defmethod thread-control-process ((thread server-thread)) (thread-process thread)) (defvar *server-connections* '() "List of all active connections, with the most recent at the front.") (defvar *current-server-thread* nil) ;; TODO: if this process talked to a connection before, we should reuse it ;; even if not talking to it now. (defun connection-for-process (process) "Return the 'default' connection for implementing a break in a non-swink process PROCESS." (let ((data (ccl::process-ui-object process))) (if (typep data 'server-thread) ;; process is in a swink repl. (thread-connection data) (car *server-connections*)))) (defmethod thread-id ((conn server-connection)) (process-serial-number *current-process*)) (defvar *listener-sockets* nil) (defun start-server (&key (port *default-server-port*) (dont-close *dont-close*) (external-format *external-format*)) "Start a SWINK server on PORT. If DONT-CLOSE is true then the listen socket will accept multiple connections, otherwise it will be closed after the first." (let* ((stream-args (and external-format `(:external-format ,external-format))) (socket (make-socket :connect :passive : local - host " 127.0.0.1 " :local-port port :reuse-address t)) (info (cons socket nil)) (local-port (local-port socket))) (with-swink-lock () (setf (getf *listener-sockets* port) info)) (setf (cdr info) (process-run-function (format nil "Swink Server ~a" local-port) (lambda () (setf (cdr info) *current-process*) (flet ((serve () (let ((stream nil)) (unwind-protect (progn (setq stream (accept-connection socket :wait t :stream-args stream-args)) (spawn-server-connection stream) (setq stream nil)) (when stream (close stream :abort t)))))) (unwind-protect (cond ((not dont-close) (serve)) (t (loop (ignore-errors (serve))))) (close socket :abort t) (with-swink-lock () (remf *listener-sockets* info))))))) (log-event "Swink awaiting ~s instructions on port ~s ~s" external-format local-port socket) local-port)) (defun stop-server (port) "Stop server running on PORT." (let* ((info (with-swink-lock () (getf *listener-sockets* port)))) (when info (destructuring-bind (socket . process) info (when process (process-kill process)) (close socket :abort t) ;; harmless if already closed. (with-swink-lock () (remf *listener-sockets* info))) t))) (defun enqueue-internal-request (conn event) (with-connection-lock (conn) (push (cons nil event) (connection-internal-requests conn)))) (defmethod read-sexp ((conn server-connection)) (if (and (connection-internal-requests conn) ;; Remote always takes priority (not (stream-listen (connection-control-stream conn)))) (with-connection-lock (conn) (pop (connection-internal-requests conn))) (call-next-method))) (defun server-event-loop (conn) (loop (let ((thread.event (read-sexp conn))) (log-event "received: ~s" thread.event) (destructuring-bind (thread-id . event) thread.event (if thread-id (let ((thread (find-thread conn thread-id))) (when thread (signal-event thread event))) (handle-event conn event)))))) (defun spawn-server-connection (stream) (let ((conn (make-instance 'server-connection :control-stream stream)) (startup-signal (make-semaphore))) (setf (connection-control-process conn) (process-run-function (format nil "swink-event-loop@~s" (local-port stream)) (lambda () (unwind-protect (with-simple-restart (close-connection "Exit server") (setf (connection-control-process conn) *current-process*) (handler-bind ((error (lambda (c) (log-event "Error: ~a" c) (log-event "Backtrace: ~%~a" (ignore-errors (with-output-to-string (s) (print-call-history :detailed-p nil :stream s :print-length 20 :print-level 4)))) (invoke-restart 'close-connection)))) (when startup-signal (signal-semaphore startup-signal)) (server-event-loop conn))) (control-process-cleanup conn))))) (wait-on-semaphore startup-signal) (with-swink-lock () (push conn *server-connections*)) (when *global-debugger* (use-swink-globally t)) conn)) ;; Note this happens in an unwind-protect, so is without interrupts. But we've pretty much ;; returned to top level and hold no locks. (defun control-process-cleanup (conn) (with-swink-lock () (setq *server-connections* (delq conn *server-connections*)) (when (null *server-connections*) (use-swink-globally nil))) (flet ((exit-repl () ;; While exiting, threads may attempt to write to the connection. That's good, if the ;; connection is still alive and we're attempting an orderly exit. Don't go into a spiral ;; if the connection is dead. Once we get any kind of error, just punt. (log-event "Start exit-repl in ~s" (thread-id *current-process*)) (handler-case (invoke-restart-if-active 'exit-repl) (error (c) (log-event "Exit repl error ~a in ~s" c (thread-id *current-process*)))))) (loop for thread in (connection-threads conn) do (process-interrupt (thread-process thread) #'exit-repl))) (let* ((timeout 0.05) (end (+ (get-internal-real-time) (* timeout internal-time-units-per-second)))) (process-wait "closing connection" (lambda () (or (null (%connection-threads conn)) (> (get-internal-real-time) end))))) (when (%connection-threads conn) (warn-and-log "Wasn't able to close these threads: ~s" (connection-threads conn))) (close (connection-control-stream conn))) ;; This is only called when this lisp receives an interrupt signal. (defun select-interactive-process () (when *global-debugger* (loop for conn in (with-swink-lock () (copy-list *server-connections*)) do (loop for thread in (connection-threads conn) when (thread-io thread) ;; still active do (return-from select-interactive-process (thread-process thread)))))) (defun send-event-for-value (target event &key abort-event (semaphore (make-semaphore))) (let* ((returned nil) (return-values nil) (tag nil) (conn (thread-connection target))) (unwind-protect (progn (setq tag (tag-callback conn (lambda (completed? &rest values) (setq returned t) (when completed? ;; Just return 0 values if cancelled. (setq return-values values)) (signal-semaphore semaphore)))) ;; In server case, :target is nil, (send-event target `(,@event ,tag)) (let ((current-thread (find-thread conn *current-process* :key #'thread-control-process))) (if current-thread ;; if in repl thread, handle thread events while waiting. (with-event-handling (current-thread) (wait-on-semaphore semaphore)) (wait-on-semaphore semaphore))) (apply #'values return-values)) (when (and tag (not returned)) (remove-tag conn tag) (when (and abort-event (not returned)) ;; inform the other side that not waiting any more. (send-event-if-open conn `(,@abort-event ,tag))))))) (defmethod get-remote-user-input ((thread server-thread)) ;; Usually this is called from a repl evaluation, but the user could have passed the stream to ;; any other process, so we could be running anywhere. Thread is the thread of the stream. (with-simple-restart (abort-read "Abort reading") (let ((conn (thread-connection thread))) (force-output (thread-io thread)) (send-event-for-value conn `(:read-string ,thread) :abort-event `(:abort-read ,thread))))) (defmethod send-remote-user-output ((thread server-thread) string start end) (let ((conn (thread-connection thread))) (send-event conn `(:write-string ,thread ,(string-segment string start end))))) (defun swink-repl (conn break-level toplevel-loop) (let* ((thread (make-new-thread conn)) (in (make-input-stream thread #'get-remote-user-input)) (out (make-output-stream thread #'send-remote-user-output)) (io (make-two-way-stream in out)) (ui-object (ccl::process-ui-object *current-process*))) (assert (null (thread-io thread))) (with-simple-restart (exit-repl "Exit remote read loop") (unwind-protect (let* ((*current-server-thread* thread) (*standard-input* in) (*standard-output* out) (*trace-output* out) (*debug-io* io) (*query-io* io) (*terminal-io* io) (ccl::*break-level* 0) (ccl::*read-loop-function* 'swink-read-loop)) (setf (ccl::process-ui-object *current-process*) thread) (setf (thread-io thread) io) (ccl:add-auto-flush-stream out) (send-event conn `(:start-repl ,break-level)) (funcall toplevel-loop)) ;; Do we need this? We've already exited from the outermost level... (send-event-if-open conn `(:exit-repl)) (ccl:remove-auto-flush-stream out) (setf (ccl::process-ui-object *current-process*) ui-object) (setf (thread-io thread) nil) (close in :abort t) (close out :abort t) (with-connection-lock (conn) (setf (%connection-threads conn) (delq thread (%connection-threads conn)))))))) (defclass repl-process (process) ()) (defun spawn-repl (conn name) (process-run-function `(:name ,name :class repl-process) (lambda () (swink-repl conn 0 #'ccl::toplevel-loop)))) ;; Invoked for a break in a non-repl process (can only happen if using swink globally). (defun swink-debugger-hook (condition hook) (declare (ignore hook)) (when (eq ccl::*read-loop-function* 'swink-read-loop) (return-from swink-debugger-hook nil)) (let ((conn (connection-for-process *current-process*))) TODO : set up a restart to pick a different connection , if there is more than one . (when conn (swink-repl conn 1 (lambda () (ccl::%break-message ccl::*break-loop-type* condition) Like toplevel - loop but run break - loop to set up error context first (loop (catch :toplevel (ccl::break-loop condition)) (when (eq *current-process* ccl::*initial-process*) (toplevel)))))))) (defun marshall-debugger-context (context) ;; TODO: neither :GO nor cmd-/ pay attention to the break condition, whereas bt.restarts does... (let* ((continuable (ccl::backtrace-context-continuable-p context)) (restarts (ccl::backtrace-context-restarts context)) (tcr (ccl::bt.tcr context)) ;; Context for printing stack-consed refs #-arm-target ;no TSP on ARM (ccl::*aux-tsp-ranges* (ccl::make-tsp-stack-range tcr context)) (ccl::*aux-vsp-ranges* (ccl::make-vsp-stack-range tcr context)) (ccl::*aux-csp-ranges* (ccl::make-csp-stack-range tcr context)) (break-level (ccl::bt.break-level context))) (list :break-level break-level :continuable-p (and continuable t) :restarts (mapcar #'princ-to-string restarts)))) (defvar *bt-context* nil) (defun swink-read-loop (&key (break-level 0) &allow-other-keys) (let* ((thread *current-server-thread*) (conn (thread-connection thread)) (ccl::*break-level* break-level) (*loading-file-source-file* nil) (ccl::*loading-toplevel-location* nil) (*bt-context* (find break-level ccl::*backtrace-contexts* :key #'ccl::backtrace-context-break-level)) *** ** * +++ ++ + /// // / -) (when *bt-context* (send-event conn `(:enter-break ,(marshall-debugger-context *bt-context*)))) (flet ((repl-until-abort () (restart-case (catch :abort (catch-cancel ;; everything is done via interrupts ... (with-event-handling (thread) (loop (sleep 60))))) (abort () :report (lambda (stream) (if (eq break-level 0) (format stream "Return to toplevel") (format stream "Return to break level ~D" break-level))) nil) (abort-break () (unless (eql break-level 0) (abort)))))) (unwind-protect (loop (repl-until-abort) (clear-input) (terpri) (send-event conn `(:read-loop ,break-level))) (send-event-if-open conn `(:debug-return ,break-level)))))) (defmacro with-return-values ((conn remote-tag &body abort-forms) &body body) (let ((ok-var (gensym)) (tag-var (gensym)) (conn-var (gensym))) `(let ((,ok-var nil) (,conn-var ,conn) (,tag-var ,remote-tag)) (send-event ,conn-var `(:return ,,tag-var ,@(unwind-protect (prog1 (progn ,@body) (setq ,ok-var t)) (unless ,ok-var (send-event-if-open ,conn-var `(:cancel-return ,,tag-var)) ,@abort-forms))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; inspector support. (defmethod ccl::ui-object-do-operation ((o server-ui-object) (operation (eql :inspect)) &rest args) (let ((conn (connection-for-process *current-process*))) (if conn (apply #'remote-inspect conn args) (call-next-method)))) (defvar $inspector-segment-size 100) (defstruct (icell (:constructor %make-icell)) inspector string count (segments nil) ;; line inspectors, in equal-sized segments. (process *current-process*)) (defmethod marshall-argument ((conn connection) (icell icell)) ;; Send the count and string since they need that right away anyhow. (list* (tag-object conn icell) (icell-count icell) (icell-string icell))) (defun make-icell (inspector) (let* ((count (or (inspector::inspector-line-count inspector) (inspector::update-line-count inspector))) (seg-size (min count $inspector-segment-size))) (%make-icell :inspector inspector :count count :string (inspector::inspector-object-string inspector) :segments (and (> seg-size 0) ;; pre-reserve the initial segment. (list (cons 0 seg-size)))))) (defun icell-seg-size (icell) (length (cdar (icell-segments icell)))) (defun iseg-end (seg) (destructuring-bind (start . ln) seg (+ start (if (integerp ln) ln (length ln))))) (defun compute-lines (icell seg) (let* ((inspector::*inspector-disassembly* t) (inspector (icell-inspector icell)) (start-index (car seg)) (seg-count (cdr seg))) (unless (integerp seg-count) (warn-and-log "Duplicate request for ~s line ~s" icell seg) (setq seg-count (length seg-count))) (let ((strings (make-array seg-count)) (lines (make-array seg-count))) (loop for index from 0 below seg-count do (multiple-value-bind (line-inspector label-string value-string) (inspector::inspector-line inspector (+ start-index index)) (setf (aref lines index) line-inspector) (setf (aref strings index) (cons label-string value-string)))) (setf (cdr seg) lines) strings))) (defmethod remote-inspect ((conn server-connection) thing) (let* ((inspector (let ((inspector::*inspector-disassembly* t)) (inspector::make-inspector thing))) (icell (make-icell inspector))) (send-event conn `(:inspect ,icell)) (when (icell-segments icell) (send-inspector-data conn icell)) thing)) (defun send-inspector-data (conn icell &optional (seg (car (icell-segments icell)))) (let ((strings (compute-lines icell seg))) (send-event conn `(:inspector-data ,(object-tag conn icell) (,(car seg) . ,strings)))) ;; arrange to send the rest later (enqueue-internal-request conn `(maybe-send-inspector-data ,icell))) ;; Segment management. ;; Only the control process messes with icell-segments, so don't need to lock. (defun reserve-next-segment (icell) (let* ((segments (icell-segments icell)) (count (icell-count icell)) (gapptr nil)) (loop for last = nil then segs as segs = segments then (cdr segs) while segs when (and last (> (caar last) (iseg-end (car segs)))) do (setq gapptr last)) (when gapptr (setq count (caar gapptr) segments (cdr gapptr))) (let* ((start-index (iseg-end (car segments))) (seg-size (min (icell-seg-size icell) (- count start-index))) (new (and (> seg-size 0) (cons start-index seg-size)))) gapptr = ( ( 5000 . line ) ( 200 . line ) ... ( 0 . line ) ) (when new (if (null gapptr) (setf (icell-segments icell) (cons new segments)) (setf (cdr gapptr) (cons new segments))) new)))) ;; Returns NIL if already reserved (defun reserve-segment-for-index (icell index) (let* ((seg-size (icell-seg-size icell)) (seg-start (- index (mod index seg-size)))) (loop for last = nil then segs as segs = (icell-segments icell) then (cdr segs) while (< seg-start (caar segs)) ;; last seg is always 0. finally (return (unless (eql seg-start (caar segs)) ;; already exists. (let ((this-end (iseg-end (car segs))) (new (cons seg-start seg-size))) (assert (>= seg-start this-end)) (if (null last) (push new (icell-segments icell)) (push new (cdr last))) new)))))) (defun icell-line-inspector (icell index) (loop for seg in (icell-segments icell) when (and (<= (car seg) index) (< index (iseg-end seg))) return (and (vectorp (cdr seg)) (aref (cdr seg) (- index (car seg)))))) (defun maybe-send-inspector-data (conn icell &optional (seg (car (icell-segments icell)))) (when seg (let* ((process (icell-process icell)) (thread (ccl::process-ui-object process))) (if (typep thread 'server-thread) ;; Why not just interrupt like any random process? (signal-event thread `(send-inspector-data ,icell ,seg)) (process-interrupt process #'send-inspector-data conn icell seg))))) (defmethod handle-event ((conn server-connection) event) (log-event "handle-event (global): ~s" event) (destructure-case event ((:end-connection condition) (declare (ignore condition)) (close-connection conn)) ((:spawn-repl name) (spawn-repl conn name)) ((:return local-tag &rest values) (apply #'invoke-callback conn local-tag values)) ((:connection-info remote-tag) (with-return-values (conn remote-tag) (list `(:pid ,(ccl::getpid) :lisp-implementation-type ,(lisp-implementation-type) :lisp-implementation-version ,(lisp-implementation-version) :machine-instance ,(machine-instance) :machine-type ,(machine-type) :machine-version ,(machine-version))))) ((:describe-more icell-tag index) (let* ((icell (tagged-object conn icell-tag :keep-tagged t)) (seg (reserve-segment-for-index icell index))) (when seg (maybe-send-inspector-data conn icell seg)))) ((:line-inspector icell-tag index return-tag) (let ((new-icell nil)) (with-return-values (conn return-tag) (let* ((icell (tagged-object conn icell-tag :keep-tagged t)) (line-inspector (or (icell-line-inspector icell index) (error "Requesting undescribed line ~s ~s" icell index)))) (setq new-icell (make-icell line-inspector)) (list new-icell))) (maybe-send-inspector-data conn new-icell))) ((:refresh-inspector icell-tag return-tag) (let ((new-icell nil)) (with-return-values (conn return-tag) (let* ((icell (tagged-object conn icell-tag :keep-tagged t)) (new-inspector (inspector::refresh-inspector (icell-inspector icell)))) (setq new-icell (make-icell new-inspector)) (list new-icell))) (maybe-send-inspector-data conn new-icell))) ((:inspecting-item icell-tag) (loop with icell = (tagged-object conn icell-tag :keep-tagged t) for thread in (connection-threads conn) when (thread-io thread) do (signal-event thread `(inspecting-item ,icell)))) Internal event to send data in segments so it 's interruptible ((maybe-send-inspector-data icell) (let ((seg (reserve-next-segment icell))) (when seg (maybe-send-inspector-data conn icell seg)))) #+remote-eval ((:eval form) ;; It's the caller's responsibility to make this quick... If they want return values ;; or whatever, they can put that in the form. (eval form)))) ;; TODO: toplevel-eval checks package change and invokes application-ui-operation, need to send that back. ;; Eval all forms in string without printing intermediate results (defun read-eval-all-print-last (string package-name) (if package-name (let ((*package* (or (find-package package-name) *package*))) (read-eval-all-print-last string nil)) (with-input-from-string (sstream string) (let ((values nil)) (loop (let ((form (ccl::read-toplevel-form sstream :eof-value sstream))) (when (eq form sstream) (ccl::toplevel-print values) (force-output) (return)) (unless (ccl::check-toplevel-command form) (setq values (ccl::toplevel-eval form nil)) (setq /// // // / / values) (unless (eq (car values) (ccl::%unbound-marker)) (setq *** ** ** * * (car values)))))) (values))))) (defun read-eval-print-one (conn sstream package) (if package (let ((*package* package)) (read-eval-print-one conn sstream nil)) (let ((form (ccl::read-toplevel-form sstream :eof-value sstream))) (unless (eq form sstream) (unless (ccl::check-toplevel-command form) (ccl::toplevel-print (ccl::toplevel-eval form nil)))) (cond ((listen sstream) (tag-object conn (cons sstream package))) (t (close sstream) nil))))) ;; Events from client to specific thread. This is running at a safe point inside a repl thread. (defmethod handle-event ((thread thread) event) (log-event "handle-event (thread ~s): ~s" (process-serial-number *current-process*) event) (let ((conn (thread-connection thread))) (destructure-case event ((:read-eval-all-print-last string package-name remote-tag) (with-return-values (conn remote-tag) (read-eval-all-print-last string package-name))) ((:read-eval-print-one string package-name remote-tag) (let* ((sstream (make-string-input-stream string)) (package (and package-name (or (find-package package-name) *package*)))) (with-return-values (conn remote-tag (close sstream)) (read-eval-print-one conn sstream package)))) ((:read-eval-print-next state remote-tag) (destructuring-bind (sstream . package) (tagged-object conn state) (with-return-values (conn remote-tag (close sstream)) (read-eval-print-one conn sstream package)))) Internal events ((send-inspector-data icell seg) (send-inspector-data conn icell seg)) ((inspecting-item icell) (inspector::note-inspecting-item (icell-inspector icell))) ((:interrupt) (ccl::force-break-in-listener *current-process*)) ((:invoke-restart restart-name) (invoke-restart restart-name)) ((:invoke-restart-in-context index) (invoke-restart-interactively (nth index (ccl::backtrace-context-restarts *bt-context*)))) ((:toplevel) (toplevel))))) (let (using-swink-globally select-hook debugger-hook break-hook ui-object) (defun use-swink-globally (yes-or-no) (log-event "use-swink-globally: ~s" yes-or-no) (if yes-or-no (unless using-swink-globally (setq select-hook *select-interactive-process-hook*) (setq *select-interactive-process-hook* (if select-hook (lambda () (or (select-interactive-process) (funcall select-hook))) 'select-interactive-process)) (setq debugger-hook *debugger-hook*) (setq *debugger-hook* (if debugger-hook (lambda (condition hook) (swink-debugger-hook condition hook) (funcall debugger-hook condition hook)) 'swink-debugger-hook)) (setq break-hook *break-hook*) (setq *break-hook* (if break-hook (lambda (condition hook) (swink-debugger-hook condition hook) (funcall break-hook condition hook)) 'swink-debugger-hook)) ;; This probably should be controlled by something other than use-swink-globally because ;; might want to use gui inspector even if not using global debugger. (setq ui-object (ccl::application-ui-object *application*)) (setf (ccl::application-ui-object *application*) (make-instance 'server-ui-object)) (setq using-swink-globally t)) (when using-swink-globally (setf *select-interactive-process-hook* select-hook *debugger-hook* debugger-hook *break-hook* break-hook (ccl::application-ui-object *application*) ui-object) (setq using-swink-globally nil))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Simple buffered stream with a user input/output function. (defclass swink-stream () ((thread :initarg :thread :reader stream-thread) (lock :initform (make-lock)) (buffer :initform "" :initarg :buffer) (index :initform 0) (column :initform 0 :reader stream-line-column) (line-length :initform ccl::*default-right-margin* :accessor stream-line-length))) (defmethod stream-thread ((stream two-way-stream)) (stream-thread (two-way-stream-input-stream stream))) (defmethod stream-thread ((stream stream)) nil) (defmacro with-swink-stream (slots stream &body body) `(with-slots (lock ,@slots) ,stream (with-lock-grabbed (lock) ,@body))) (defclass swink-output-stream (swink-stream fundamental-character-output-stream) ((output-fn :initarg :output-fn) (buffer :initform (make-string 8000) :initarg :buffer))) (defun make-output-stream (thread output-fn) (make-instance 'swink-output-stream :thread thread :output-fn output-fn)) (defun output-stream-output (stream string start end) (with-slots (output-fn thread) stream (let ((conn (thread-connection thread))) (handler-bind ((stream-error (lambda (c) (when (eql (stream-error-stream c) (connection-control-stream conn)) (with-slots (ccl::stream) c (setf ccl::stream stream)))))) (funcall output-fn thread string start end))))) (defmethod flush-buffer ((stream swink-output-stream)) ;; called with lock hold (with-slots (buffer index) stream (unless (eql index 0) (output-stream-output stream buffer 0 index) (setf index 0)))) (defmethod stream-write-char ((stream swink-output-stream) char) (with-swink-stream (buffer index column) stream (when (eql index (length buffer)) (flush-buffer stream)) (setf (schar buffer index) char) (incf index) (if (eql char #\newline) (setf column 0) (incf column))) char) (defmethod stream-write-string ((stream swink-output-stream) string &optional start end) (with-swink-stream (buffer index column) stream (let* ((len (length buffer)) (start (or start 0)) (end (ccl::check-sequence-bounds string start end)) (count (- end start)) (free (- len index))) (when (>= count free) (flush-buffer stream)) (cond ((< count len) (replace buffer string :start1 index :start2 start :end2 end) (incf index count)) (t (output-stream-output stream string start end))) (let ((last-newline (position #\newline string :from-end t :start start :end end))) (setf column (if last-newline (- end last-newline 1) (+ column count)))))) string) (defmethod stream-force-output ((stream swink-output-stream)) (with-swink-stream () stream (flush-buffer stream))) (defmethod ccl::stream-finish-output ((stream swink-output-stream)) (stream-force-output stream)) (defclass swink-input-stream (swink-stream fundamental-character-input-stream) ((input-fn :initarg :input-fn))) (defun make-input-stream (thread input-fn) (make-instance 'swink-input-stream :thread thread :input-fn input-fn)) (defun input-stream-input (stream) (with-slots (input-fn thread) stream (let ((conn (thread-connection thread))) (handler-bind ((stream-error (lambda (c) (when (eql (stream-error-stream c) (connection-control-stream conn)) (with-slots (ccl::stream) c (setf ccl::stream stream)))))) (funcall input-fn thread))))) (defmethod stream-read-char ((stream swink-input-stream)) (with-swink-stream (buffer index column) stream (unless (< index (length buffer)) (let ((string (input-stream-input stream))) (cond ((eql (length string) 0) (return-from stream-read-char :eof)) (t (setf buffer string index 0))))) (let ((char (aref buffer index))) (incf index) (if (eql char #\Newline) (setf column 0) (incf column)) char))) (defmethod stream-read-char-no-hang ((stream swink-input-stream)) (with-swink-stream (buffer index column) stream (when (< index (length buffer)) (let ((char (aref buffer index))) (incf index) (if (eql char #\Newline) (setf column 0) (incf column)) char)))) (defmethod stream-listen ((stream swink-input-stream)) (with-swink-stream (buffer index) stream (< index (length buffer)))) (defmethod stream-unread-char ((stream swink-input-stream) char) (with-swink-stream (buffer index) stream (if (eql (length buffer) 0) ;; perhaps did clear-input. (setf buffer (make-string 1 :initial-element char)) (if (> index 0) (decf index) (error "Unread with no preceeding read"))))) (defmethod stream-clear-input ((stream swink-input-stream)) (with-swink-stream (buffer index) stream (setf buffer "" index 0)) nil)
null
https://raw.githubusercontent.com/fukamachi/clozure-cl/4b0c69452386ae57b08984ed815d9b50b4bcc8a2/lib/swink.lisp
lisp
file "LICENSE". The LLGPL consists of a preamble and the LGPL, conflict, the preamble takes precedence. Clozure CL is referenced in the preamble as the "LIBRARY." The LLGPL is also available online at Implement a protocol (originally based on swank) for communication between a lisp and an external debugger. This implements the server side, i.e. the lisp being debugged. Some stuff that's also useful on client side Only check the top level This kludge is so don't have to disable interrupts while printing. There is a tiny timing screw at end of loop; who cares, it's just for debugging... recursive call without callbacks We could have a separate lock for the stream, but we can't really send back anything until this write is finished, so it doesn't hurt much if random stuff is held up while we do this. Returns the sexp or :end-connection event This includes parse errors as well as i/o errors TODO: verify that there aren't more forms in the string. Data for processes with swink event handling. Event handling. Built on conditions rather than semaphores, so events can interrupt a process in i/o wait. Server side: In any process we can enter a read loop which gets its input from a swink connection and sends output to the connection. We can also spawn a process that does nothing else. TODO: if this process talked to a connection before, we should reuse it even if not talking to it now. process is in a swink repl. harmless if already closed. Remote always takes priority Note this happens in an unwind-protect, so is without interrupts. But we've pretty much returned to top level and hold no locks. While exiting, threads may attempt to write to the connection. That's good, if the connection is still alive and we're attempting an orderly exit. Don't go into a spiral if the connection is dead. Once we get any kind of error, just punt. This is only called when this lisp receives an interrupt signal. still active Just return 0 values if cancelled. In server case, :target is nil, if in repl thread, handle thread events while waiting. inform the other side that not waiting any more. Usually this is called from a repl evaluation, but the user could have passed the stream to any other process, so we could be running anywhere. Thread is the thread of the stream. Do we need this? We've already exited from the outermost level... Invoked for a break in a non-repl process (can only happen if using swink globally). TODO: neither :GO nor cmd-/ pay attention to the break condition, whereas bt.restarts does... Context for printing stack-consed refs no TSP on ARM everything is done via interrupts ... inspector support. line inspectors, in equal-sized segments. Send the count and string since they need that right away anyhow. pre-reserve the initial segment. arrange to send the rest later Segment management. Only the control process messes with icell-segments, so don't need to lock. Returns NIL if already reserved last seg is always 0. already exists. Why not just interrupt like any random process? It's the caller's responsibility to make this quick... If they want return values or whatever, they can put that in the form. TODO: toplevel-eval checks package change and invokes application-ui-operation, need to send that back. Eval all forms in string without printing intermediate results Events from client to specific thread. This is running at a safe point inside a repl thread. This probably should be controlled by something other than use-swink-globally because might want to use gui inspector even if not using global debugger. Simple buffered stream with a user input/output function. called with lock hold perhaps did clear-input.
Copyright ( C ) 2011 Clozure Associates This file is part of Clozure CL . Clozure CL is licensed under the terms of the Lisp Lesser GNU Public License , known as the LLGPL and distributed with Clozure CL as the which is distributed with Clozure CL as the file " LGPL " . Where these (eval-when (eval compile load) (defpackage :swink (:use :cl :ccl) (:export "START-SERVER" "STOP-SERVER" "THREAD" "THREAD-CLASS" "THREAD-CONNECTION" "THREAD-ID" "THREAD-CONTROL-PROCESS" "MAKE-NEW-THREAD" "CONNECTION" "FIND-THREAD" "CONNECTION-CONTROL-STREAM" "CONNECTION-CONTROL-PROCESS" "CLOSE-CONNECTION" "TAGGED-OBJECT" "TAG-CALLBACK" "INVOKE-CALLBACK" "ABORT-CALLBACK" "DESTRUCTURE-CASE" "WITH-CONNECTION-LOCK" "WITH-EVENT-HANDLING" "SEND-EVENT" "SEND-EVENT-FOR-VALUE" "SIGNAL-EVENT" "HANDLE-EVENT" "READ-SEXP" ))) (in-package :swink) (defvar *default-server-port* 4003) (defvar *dont-close* nil "Keep listening for more connections on the same port after get the first one") (defvar *external-format* :iso-8859-1) (defvar *swink-lock* (make-lock)) (defmacro with-swink-lock ((&rest lock-options) &body body) `(without-interrupts (with-lock-grabbed (*swink-lock* ,@lock-options) ,@body))) (defmacro destructure-case (value &rest patterns) "Dispatch VALUE to one of PATTERNS. A cross between `case' and `destructuring-bind'. The pattern syntax is: ((HEAD . ARGS) . BODY) The list of patterns is searched for a HEAD `eq' to the car of VALUE. If one is found, the BODY is executed with ARGS bound to the corresponding values in the CDR of VALUE." (let ((operator (gensym "op-")) (operands (gensym "rand-")) (tmp (gensym "tmp-")) (case (if (or (eq (caar (last patterns)) t) (eq (caaar (last patterns)) t)) 'case 'ecase))) `(let* ((,tmp ,value) (,operator (car ,tmp)) (,operands (cdr ,tmp))) (,case ,operator ,@(loop for (pattern . body) in patterns collect (if (eq pattern t) `(t ,@body) (destructuring-bind (op &rest rands) pattern `(,op (destructuring-bind ,rands ,operands ,@body))))))))) (defun string-segment (string start end) (if (and (eql start 0) (eql end (length string))) string (make-array (- end start) :displaced-to string :displaced-index-offset start))) (defun safe-condition-string (condition) (or (ignore-errors (princ-to-string condition)) (ignore-errors (prin1-to-string condition)) (ignore-errors (format nil "Condition of type ~s" (type-of condition))) (ignore-errors (and (typep condition 'error) "<Unprintable error>")) "<Unprintable condition>")) (defun invoke-restart-if-active (restart &rest values) (declare (dynamic-extent values)) (handler-case (apply #'invoke-restart restart values) (ccl::inactive-restart () nil))) (defmethod marshall-argument (conn (process process)) (declare (ignore conn)) (process-serial-number process)) (defmethod marshall-argument (conn (condition condition)) (declare (ignore conn)) (safe-condition-string condition)) (defmethod marshall-argument (conn thing) (declare (ignore conn)) thing) (defun marshall-event (conn event) (marshall-argument conn thing))) (mapcar #'marshall event))) (defvar *log-events* nil) (defvar *log-queue*) (let ((log-lock (make-lock))) (defun log-event (format-string &rest format-args) (when *log-events* (ignore-errors (let* ((string (format nil "[~d] ~?" (process-serial-number *current-process*) format-string format-args))) (without-interrupts (setq *log-queue* (nconc *log-queue* (list string)))) (let ((stream ccl::*stdout*)) (with-lock-grabbed (log-lock "Log Output Lock") (let ((*log-queue* (list string))) (fresh-line stream) (loop for string = (without-interrupts (pop *log-queue*)) while string do (write-string string stream) do (terpri stream)))) (force-output stream)))))))) (defun warn-and-log (format-string &rest format-args) (declare (dynamic-extent format-args)) (apply #'log-event format-string format-args) (apply #'warn format-string format-args)) (defclass connection () ((control-process :initform nil :accessor connection-control-process) (control-stream :initarg :control-stream :reader connection-control-stream) (buffer :initform (make-string 1024) :accessor connection-buffer) (lock :initform (make-lock) :reader connection-lock) (threads :initform nil :accessor %connection-threads) (object-counter :initform most-negative-fixnum :accessor connection-object-counter) (objects :initform nil :accessor connection-objects))) (defmacro with-connection-lock ((conn &rest lock-args) &body body) (with-lock-grabbed ((connection-lock ,conn) ,@lock-args) ,@body))) (defmethod close-connection ((conn connection)) (log-event "closing connection ~s" conn) (let ((process (connection-control-process conn))) (when process (process-interrupt process 'invoke-restart-if-active 'close-connection)))) (defun tag-object (conn object) (with-connection-lock (conn) (let* ((id (incf (connection-object-counter conn)))) (push (cons id object) (connection-objects conn)) id))) (defun object-tag (conn object) (with-connection-lock (conn) (car (rassoc object (connection-objects conn))))) (defun tagged-object (conn id &key keep-tagged) (if keep-tagged (cdr (assoc id (connection-objects conn))) (with-connection-lock (conn) (let ((cell (assoc id (connection-objects conn)))) (unless cell (warn-and-log "Missing object for remote reference ~s" id)) (setf (connection-objects conn) (delq cell (connection-objects conn))) (cdr cell))))) (defun remove-tag (conn id) (with-connection-lock (conn) (setf (connection-objects conn) (delete id (connection-objects conn) :key #'car)))) (defun tag-callback (conn function) (tag-object conn function)) (defun invoke-callback (conn id &rest values) (declare (dynamic-extent values)) (let ((function (tagged-object conn id))) (when function (apply function t values)))) (defun abort-callback (conn id) (let ((function (tagged-object conn id))) (when function (funcall function nil)))) (defun write-packet (conn string) (let ((stream (connection-control-stream conn))) (assert (<= (length string) #xFFFFFF)) (with-connection-lock (conn) (format stream "~6,'0,X" (length string)) (write-string string stream)) (force-output stream))) (defvar +swink-io-package+ (loop as name = (gensym "SwinkIO/") while (find-package name) finally (let ((package (make-package name :use nil))) (import '(nil t quote) package) (return package)))) (defun format-for-swink (fmt-string fmt-args) (with-standard-io-syntax (let ((*package* +swink-io-package+)) (apply #'format nil fmt-string fmt-args)))) (defun write-sexp (conn sexp) (write-packet conn (with-standard-io-syntax (let ((*package* +swink-io-package+)) (prin1-to-string sexp))))) (defun send-event (target event &key ignore-errors) (let* ((conn (thread-connection target)) (encoded-event (marshall-event conn event))) (log-event "Send-event ~s to ~a" encoded-event (if (eq target conn) "connection" (princ-to-string (thread-id target)))) (handler-bind ((stream-error (lambda (c) (when (eq (stream-error-stream c) (connection-control-stream conn)) (unless ignore-errors (log-event "send-event error: ~a" c) (close-connection conn)) (return-from send-event))))) (write-sexp conn (cons (thread-id target) encoded-event))))) (defun send-event-if-open (target event) (send-event target event :ignore-errors t)) #-bootstrapped (fmakunbound 'read-sexp) This assumes only one process reads from the command stream or the read - buffer , so do n't need locking . (defmethod read-sexp ((conn connection)) (let* ((stream (connection-control-stream conn)) (buffer (connection-buffer conn)) (count (stream-read-vector stream buffer 0 6))) (handler-bind ((stream-error (lambda (c) (when (eql (stream-error-stream c) stream) (log-event "read-sexp error: ~a" c) ( setf ( connection - io - error conn ) t ) (return-from read-sexp `(nil . (:end-connection ,c))))))) (when (< count 6) (ccl::signal-eof-error stream)) (setq count (parse-integer buffer :end 6 :radix 16)) (when (< (length buffer) count) (setq buffer (setf (connection-buffer conn) (make-string count)))) (let ((len (stream-read-vector stream buffer 0 count))) (when (< len count) (ccl::signal-eof-error stream)) (with-standard-io-syntax (let ((*package* +swink-io-package+) (*read-eval* nil)) (read-from-string buffer t nil :end count))))))) (defmethod thread-connection ((conn connection)) conn) (defclass thread () ((connection :initarg :connection :reader thread-connection) (lock :initform (make-lock) :reader thread-lock) (process :initarg :process :accessor thread-process) (event-queue :initform nil :accessor thread-event-queue))) (defmacro with-thread-lock ((thread &rest lock-args) &rest body) `(without-interrupts (with-lock-grabbed ((thread-lock ,thread) ,@lock-args) ,@body))) (defmethod thread-id ((thread thread)) (thread-id (thread-process thread))) (defmethod thread-id ((process process)) (process-serial-number process)) (defmethod thread-id ((id integer)) id) (defmethod marshall-argument (conn (thread thread)) (declare (ignore conn)) (thread-id thread)) (defun connection-threads (conn) (with-connection-lock (conn) (copy-list (%connection-threads conn)))) (defun find-thread (conn id &key (key #'thread-id)) (with-connection-lock (conn) (find id (%connection-threads conn) :key key))) (defmethod make-new-thread ((conn connection) &optional (process *current-process*)) (with-connection-lock (conn) (assert (not (find-thread conn process :key #'thread-process))) (let ((thread (make-instance (thread-class conn) :connection conn :process process))) (push thread (%connection-threads conn)) thread))) (defun queue-event (thread event) (with-thread-lock (thread) (setf (thread-event-queue thread) (nconc (thread-event-queue thread) (list event))))) (defun dequeue-event (thread) (with-thread-lock (thread) (pop (thread-event-queue thread)))) (defvar *signal-events* nil) (define-condition events-available () ()) (defun enable-event-handling (thread) (setq *signal-events* t) (loop while (thread-event-queue thread) do (let ((*signal-events* nil)) (handle-events thread)))) (defmacro with-event-handling ((thread &key restart) &body body) (let ((thread-var (gensym "THREAD"))) (if restart `(let ((,thread-var ,thread)) (loop (handler-case (return (let ((*signal-events* *signal-events*)) (enable-event-handling ,thread-var) (with-interrupts-enabled ,@body))) (events-available () (let ((*signal-events* nil)) (handle-events ,thread-var)))))) `(let ((,thread-var ,thread)) (handler-bind ((events-available (lambda (c) (declare (ignore c)) (handle-events ,thread-var)))) (let ((*signal-events* *signal-events*)) (enable-event-handling ,thread-var) (with-interrupts-enabled ,@body))))))) (defun signal-event (thread event) (queue-event thread event) (process-interrupt (or (thread-control-process thread) (error "Got event ~s for thread ~s with no process" event thread)) (lambda () (when *signal-events* (let ((*signal-events* nil)) (signal 'events-available)))))) (defmethod handle-events ((thread thread)) (loop as event = (dequeue-event thread) while event do (handle-event thread event))) (defvar *global-debugger* t "Use remote debugger on errors and user events even in non-repl threads") (defclass server-ui-object (ccl::ui-object) ()) (defclass server-connection (connection) ((internal-requests :initform nil :accessor connection-internal-requests))) (defclass server-thread (thread server-ui-object) ((io :initform nil :accessor thread-io))) (defmethod thread-class ((conn server-connection)) 'server-thread) (defmethod thread-control-process ((thread server-thread)) (thread-process thread)) (defvar *server-connections* '() "List of all active connections, with the most recent at the front.") (defvar *current-server-thread* nil) (defun connection-for-process (process) "Return the 'default' connection for implementing a break in a non-swink process PROCESS." (let ((data (ccl::process-ui-object process))) (thread-connection data) (car *server-connections*)))) (defmethod thread-id ((conn server-connection)) (process-serial-number *current-process*)) (defvar *listener-sockets* nil) (defun start-server (&key (port *default-server-port*) (dont-close *dont-close*) (external-format *external-format*)) "Start a SWINK server on PORT. If DONT-CLOSE is true then the listen socket will accept multiple connections, otherwise it will be closed after the first." (let* ((stream-args (and external-format `(:external-format ,external-format))) (socket (make-socket :connect :passive : local - host " 127.0.0.1 " :local-port port :reuse-address t)) (info (cons socket nil)) (local-port (local-port socket))) (with-swink-lock () (setf (getf *listener-sockets* port) info)) (setf (cdr info) (process-run-function (format nil "Swink Server ~a" local-port) (lambda () (setf (cdr info) *current-process*) (flet ((serve () (let ((stream nil)) (unwind-protect (progn (setq stream (accept-connection socket :wait t :stream-args stream-args)) (spawn-server-connection stream) (setq stream nil)) (when stream (close stream :abort t)))))) (unwind-protect (cond ((not dont-close) (serve)) (t (loop (ignore-errors (serve))))) (close socket :abort t) (with-swink-lock () (remf *listener-sockets* info))))))) (log-event "Swink awaiting ~s instructions on port ~s ~s" external-format local-port socket) local-port)) (defun stop-server (port) "Stop server running on PORT." (let* ((info (with-swink-lock () (getf *listener-sockets* port)))) (when info (destructuring-bind (socket . process) info (when process (process-kill process)) (with-swink-lock () (remf *listener-sockets* info))) t))) (defun enqueue-internal-request (conn event) (with-connection-lock (conn) (push (cons nil event) (connection-internal-requests conn)))) (defmethod read-sexp ((conn server-connection)) (if (and (connection-internal-requests conn) (not (stream-listen (connection-control-stream conn)))) (with-connection-lock (conn) (pop (connection-internal-requests conn))) (call-next-method))) (defun server-event-loop (conn) (loop (let ((thread.event (read-sexp conn))) (log-event "received: ~s" thread.event) (destructuring-bind (thread-id . event) thread.event (if thread-id (let ((thread (find-thread conn thread-id))) (when thread (signal-event thread event))) (handle-event conn event)))))) (defun spawn-server-connection (stream) (let ((conn (make-instance 'server-connection :control-stream stream)) (startup-signal (make-semaphore))) (setf (connection-control-process conn) (process-run-function (format nil "swink-event-loop@~s" (local-port stream)) (lambda () (unwind-protect (with-simple-restart (close-connection "Exit server") (setf (connection-control-process conn) *current-process*) (handler-bind ((error (lambda (c) (log-event "Error: ~a" c) (log-event "Backtrace: ~%~a" (ignore-errors (with-output-to-string (s) (print-call-history :detailed-p nil :stream s :print-length 20 :print-level 4)))) (invoke-restart 'close-connection)))) (when startup-signal (signal-semaphore startup-signal)) (server-event-loop conn))) (control-process-cleanup conn))))) (wait-on-semaphore startup-signal) (with-swink-lock () (push conn *server-connections*)) (when *global-debugger* (use-swink-globally t)) conn)) (defun control-process-cleanup (conn) (with-swink-lock () (setq *server-connections* (delq conn *server-connections*)) (when (null *server-connections*) (use-swink-globally nil))) (flet ((exit-repl () (log-event "Start exit-repl in ~s" (thread-id *current-process*)) (handler-case (invoke-restart-if-active 'exit-repl) (error (c) (log-event "Exit repl error ~a in ~s" c (thread-id *current-process*)))))) (loop for thread in (connection-threads conn) do (process-interrupt (thread-process thread) #'exit-repl))) (let* ((timeout 0.05) (end (+ (get-internal-real-time) (* timeout internal-time-units-per-second)))) (process-wait "closing connection" (lambda () (or (null (%connection-threads conn)) (> (get-internal-real-time) end))))) (when (%connection-threads conn) (warn-and-log "Wasn't able to close these threads: ~s" (connection-threads conn))) (close (connection-control-stream conn))) (defun select-interactive-process () (when *global-debugger* (loop for conn in (with-swink-lock () (copy-list *server-connections*)) do (loop for thread in (connection-threads conn) do (return-from select-interactive-process (thread-process thread)))))) (defun send-event-for-value (target event &key abort-event (semaphore (make-semaphore))) (let* ((returned nil) (return-values nil) (tag nil) (conn (thread-connection target))) (unwind-protect (progn (setq tag (tag-callback conn (lambda (completed? &rest values) (setq returned t) (when completed? (setq return-values values)) (signal-semaphore semaphore)))) (send-event target `(,@event ,tag)) (let ((current-thread (find-thread conn *current-process* :key #'thread-control-process))) (with-event-handling (current-thread) (wait-on-semaphore semaphore)) (wait-on-semaphore semaphore))) (apply #'values return-values)) (when (and tag (not returned)) (remove-tag conn tag) (when (and abort-event (not returned)) (send-event-if-open conn `(,@abort-event ,tag))))))) (defmethod get-remote-user-input ((thread server-thread)) (with-simple-restart (abort-read "Abort reading") (let ((conn (thread-connection thread))) (force-output (thread-io thread)) (send-event-for-value conn `(:read-string ,thread) :abort-event `(:abort-read ,thread))))) (defmethod send-remote-user-output ((thread server-thread) string start end) (let ((conn (thread-connection thread))) (send-event conn `(:write-string ,thread ,(string-segment string start end))))) (defun swink-repl (conn break-level toplevel-loop) (let* ((thread (make-new-thread conn)) (in (make-input-stream thread #'get-remote-user-input)) (out (make-output-stream thread #'send-remote-user-output)) (io (make-two-way-stream in out)) (ui-object (ccl::process-ui-object *current-process*))) (assert (null (thread-io thread))) (with-simple-restart (exit-repl "Exit remote read loop") (unwind-protect (let* ((*current-server-thread* thread) (*standard-input* in) (*standard-output* out) (*trace-output* out) (*debug-io* io) (*query-io* io) (*terminal-io* io) (ccl::*break-level* 0) (ccl::*read-loop-function* 'swink-read-loop)) (setf (ccl::process-ui-object *current-process*) thread) (setf (thread-io thread) io) (ccl:add-auto-flush-stream out) (send-event conn `(:start-repl ,break-level)) (funcall toplevel-loop)) (send-event-if-open conn `(:exit-repl)) (ccl:remove-auto-flush-stream out) (setf (ccl::process-ui-object *current-process*) ui-object) (setf (thread-io thread) nil) (close in :abort t) (close out :abort t) (with-connection-lock (conn) (setf (%connection-threads conn) (delq thread (%connection-threads conn)))))))) (defclass repl-process (process) ()) (defun spawn-repl (conn name) (process-run-function `(:name ,name :class repl-process) (lambda () (swink-repl conn 0 #'ccl::toplevel-loop)))) (defun swink-debugger-hook (condition hook) (declare (ignore hook)) (when (eq ccl::*read-loop-function* 'swink-read-loop) (return-from swink-debugger-hook nil)) (let ((conn (connection-for-process *current-process*))) TODO : set up a restart to pick a different connection , if there is more than one . (when conn (swink-repl conn 1 (lambda () (ccl::%break-message ccl::*break-loop-type* condition) Like toplevel - loop but run break - loop to set up error context first (loop (catch :toplevel (ccl::break-loop condition)) (when (eq *current-process* ccl::*initial-process*) (toplevel)))))))) (defun marshall-debugger-context (context) (let* ((continuable (ccl::backtrace-context-continuable-p context)) (restarts (ccl::backtrace-context-restarts context)) (tcr (ccl::bt.tcr context)) (ccl::*aux-tsp-ranges* (ccl::make-tsp-stack-range tcr context)) (ccl::*aux-vsp-ranges* (ccl::make-vsp-stack-range tcr context)) (ccl::*aux-csp-ranges* (ccl::make-csp-stack-range tcr context)) (break-level (ccl::bt.break-level context))) (list :break-level break-level :continuable-p (and continuable t) :restarts (mapcar #'princ-to-string restarts)))) (defvar *bt-context* nil) (defun swink-read-loop (&key (break-level 0) &allow-other-keys) (let* ((thread *current-server-thread*) (conn (thread-connection thread)) (ccl::*break-level* break-level) (*loading-file-source-file* nil) (ccl::*loading-toplevel-location* nil) (*bt-context* (find break-level ccl::*backtrace-contexts* :key #'ccl::backtrace-context-break-level)) *** ** * +++ ++ + /// // / -) (when *bt-context* (send-event conn `(:enter-break ,(marshall-debugger-context *bt-context*)))) (flet ((repl-until-abort () (restart-case (catch :abort (catch-cancel (with-event-handling (thread) (loop (sleep 60))))) (abort () :report (lambda (stream) (if (eq break-level 0) (format stream "Return to toplevel") (format stream "Return to break level ~D" break-level))) nil) (abort-break () (unless (eql break-level 0) (abort)))))) (unwind-protect (loop (repl-until-abort) (clear-input) (terpri) (send-event conn `(:read-loop ,break-level))) (send-event-if-open conn `(:debug-return ,break-level)))))) (defmacro with-return-values ((conn remote-tag &body abort-forms) &body body) (let ((ok-var (gensym)) (tag-var (gensym)) (conn-var (gensym))) `(let ((,ok-var nil) (,conn-var ,conn) (,tag-var ,remote-tag)) (send-event ,conn-var `(:return ,,tag-var ,@(unwind-protect (prog1 (progn ,@body) (setq ,ok-var t)) (unless ,ok-var (send-event-if-open ,conn-var `(:cancel-return ,,tag-var)) ,@abort-forms))))))) (defmethod ccl::ui-object-do-operation ((o server-ui-object) (operation (eql :inspect)) &rest args) (let ((conn (connection-for-process *current-process*))) (if conn (apply #'remote-inspect conn args) (call-next-method)))) (defvar $inspector-segment-size 100) (defstruct (icell (:constructor %make-icell)) inspector string count (process *current-process*)) (defmethod marshall-argument ((conn connection) (icell icell)) (list* (tag-object conn icell) (icell-count icell) (icell-string icell))) (defun make-icell (inspector) (let* ((count (or (inspector::inspector-line-count inspector) (inspector::update-line-count inspector))) (seg-size (min count $inspector-segment-size))) (%make-icell :inspector inspector :count count :string (inspector::inspector-object-string inspector) (list (cons 0 seg-size)))))) (defun icell-seg-size (icell) (length (cdar (icell-segments icell)))) (defun iseg-end (seg) (destructuring-bind (start . ln) seg (+ start (if (integerp ln) ln (length ln))))) (defun compute-lines (icell seg) (let* ((inspector::*inspector-disassembly* t) (inspector (icell-inspector icell)) (start-index (car seg)) (seg-count (cdr seg))) (unless (integerp seg-count) (warn-and-log "Duplicate request for ~s line ~s" icell seg) (setq seg-count (length seg-count))) (let ((strings (make-array seg-count)) (lines (make-array seg-count))) (loop for index from 0 below seg-count do (multiple-value-bind (line-inspector label-string value-string) (inspector::inspector-line inspector (+ start-index index)) (setf (aref lines index) line-inspector) (setf (aref strings index) (cons label-string value-string)))) (setf (cdr seg) lines) strings))) (defmethod remote-inspect ((conn server-connection) thing) (let* ((inspector (let ((inspector::*inspector-disassembly* t)) (inspector::make-inspector thing))) (icell (make-icell inspector))) (send-event conn `(:inspect ,icell)) (when (icell-segments icell) (send-inspector-data conn icell)) thing)) (defun send-inspector-data (conn icell &optional (seg (car (icell-segments icell)))) (let ((strings (compute-lines icell seg))) (send-event conn `(:inspector-data ,(object-tag conn icell) (,(car seg) . ,strings)))) (enqueue-internal-request conn `(maybe-send-inspector-data ,icell))) (defun reserve-next-segment (icell) (let* ((segments (icell-segments icell)) (count (icell-count icell)) (gapptr nil)) (loop for last = nil then segs as segs = segments then (cdr segs) while segs when (and last (> (caar last) (iseg-end (car segs)))) do (setq gapptr last)) (when gapptr (setq count (caar gapptr) segments (cdr gapptr))) (let* ((start-index (iseg-end (car segments))) (seg-size (min (icell-seg-size icell) (- count start-index))) (new (and (> seg-size 0) (cons start-index seg-size)))) gapptr = ( ( 5000 . line ) ( 200 . line ) ... ( 0 . line ) ) (when new (if (null gapptr) (setf (icell-segments icell) (cons new segments)) (setf (cdr gapptr) (cons new segments))) new)))) (defun reserve-segment-for-index (icell index) (let* ((seg-size (icell-seg-size icell)) (seg-start (- index (mod index seg-size)))) (loop for last = nil then segs as segs = (icell-segments icell) then (cdr segs) (let ((this-end (iseg-end (car segs))) (new (cons seg-start seg-size))) (assert (>= seg-start this-end)) (if (null last) (push new (icell-segments icell)) (push new (cdr last))) new)))))) (defun icell-line-inspector (icell index) (loop for seg in (icell-segments icell) when (and (<= (car seg) index) (< index (iseg-end seg))) return (and (vectorp (cdr seg)) (aref (cdr seg) (- index (car seg)))))) (defun maybe-send-inspector-data (conn icell &optional (seg (car (icell-segments icell)))) (when seg (let* ((process (icell-process icell)) (thread (ccl::process-ui-object process))) (if (typep thread 'server-thread) (signal-event thread `(send-inspector-data ,icell ,seg)) (process-interrupt process #'send-inspector-data conn icell seg))))) (defmethod handle-event ((conn server-connection) event) (log-event "handle-event (global): ~s" event) (destructure-case event ((:end-connection condition) (declare (ignore condition)) (close-connection conn)) ((:spawn-repl name) (spawn-repl conn name)) ((:return local-tag &rest values) (apply #'invoke-callback conn local-tag values)) ((:connection-info remote-tag) (with-return-values (conn remote-tag) (list `(:pid ,(ccl::getpid) :lisp-implementation-type ,(lisp-implementation-type) :lisp-implementation-version ,(lisp-implementation-version) :machine-instance ,(machine-instance) :machine-type ,(machine-type) :machine-version ,(machine-version))))) ((:describe-more icell-tag index) (let* ((icell (tagged-object conn icell-tag :keep-tagged t)) (seg (reserve-segment-for-index icell index))) (when seg (maybe-send-inspector-data conn icell seg)))) ((:line-inspector icell-tag index return-tag) (let ((new-icell nil)) (with-return-values (conn return-tag) (let* ((icell (tagged-object conn icell-tag :keep-tagged t)) (line-inspector (or (icell-line-inspector icell index) (error "Requesting undescribed line ~s ~s" icell index)))) (setq new-icell (make-icell line-inspector)) (list new-icell))) (maybe-send-inspector-data conn new-icell))) ((:refresh-inspector icell-tag return-tag) (let ((new-icell nil)) (with-return-values (conn return-tag) (let* ((icell (tagged-object conn icell-tag :keep-tagged t)) (new-inspector (inspector::refresh-inspector (icell-inspector icell)))) (setq new-icell (make-icell new-inspector)) (list new-icell))) (maybe-send-inspector-data conn new-icell))) ((:inspecting-item icell-tag) (loop with icell = (tagged-object conn icell-tag :keep-tagged t) for thread in (connection-threads conn) when (thread-io thread) do (signal-event thread `(inspecting-item ,icell)))) Internal event to send data in segments so it 's interruptible ((maybe-send-inspector-data icell) (let ((seg (reserve-next-segment icell))) (when seg (maybe-send-inspector-data conn icell seg)))) #+remote-eval ((:eval form) (eval form)))) (defun read-eval-all-print-last (string package-name) (if package-name (let ((*package* (or (find-package package-name) *package*))) (read-eval-all-print-last string nil)) (with-input-from-string (sstream string) (let ((values nil)) (loop (let ((form (ccl::read-toplevel-form sstream :eof-value sstream))) (when (eq form sstream) (ccl::toplevel-print values) (force-output) (return)) (unless (ccl::check-toplevel-command form) (setq values (ccl::toplevel-eval form nil)) (setq /// // // / / values) (unless (eq (car values) (ccl::%unbound-marker)) (setq *** ** ** * * (car values)))))) (values))))) (defun read-eval-print-one (conn sstream package) (if package (let ((*package* package)) (read-eval-print-one conn sstream nil)) (let ((form (ccl::read-toplevel-form sstream :eof-value sstream))) (unless (eq form sstream) (unless (ccl::check-toplevel-command form) (ccl::toplevel-print (ccl::toplevel-eval form nil)))) (cond ((listen sstream) (tag-object conn (cons sstream package))) (t (close sstream) nil))))) (defmethod handle-event ((thread thread) event) (log-event "handle-event (thread ~s): ~s" (process-serial-number *current-process*) event) (let ((conn (thread-connection thread))) (destructure-case event ((:read-eval-all-print-last string package-name remote-tag) (with-return-values (conn remote-tag) (read-eval-all-print-last string package-name))) ((:read-eval-print-one string package-name remote-tag) (let* ((sstream (make-string-input-stream string)) (package (and package-name (or (find-package package-name) *package*)))) (with-return-values (conn remote-tag (close sstream)) (read-eval-print-one conn sstream package)))) ((:read-eval-print-next state remote-tag) (destructuring-bind (sstream . package) (tagged-object conn state) (with-return-values (conn remote-tag (close sstream)) (read-eval-print-one conn sstream package)))) Internal events ((send-inspector-data icell seg) (send-inspector-data conn icell seg)) ((inspecting-item icell) (inspector::note-inspecting-item (icell-inspector icell))) ((:interrupt) (ccl::force-break-in-listener *current-process*)) ((:invoke-restart restart-name) (invoke-restart restart-name)) ((:invoke-restart-in-context index) (invoke-restart-interactively (nth index (ccl::backtrace-context-restarts *bt-context*)))) ((:toplevel) (toplevel))))) (let (using-swink-globally select-hook debugger-hook break-hook ui-object) (defun use-swink-globally (yes-or-no) (log-event "use-swink-globally: ~s" yes-or-no) (if yes-or-no (unless using-swink-globally (setq select-hook *select-interactive-process-hook*) (setq *select-interactive-process-hook* (if select-hook (lambda () (or (select-interactive-process) (funcall select-hook))) 'select-interactive-process)) (setq debugger-hook *debugger-hook*) (setq *debugger-hook* (if debugger-hook (lambda (condition hook) (swink-debugger-hook condition hook) (funcall debugger-hook condition hook)) 'swink-debugger-hook)) (setq break-hook *break-hook*) (setq *break-hook* (if break-hook (lambda (condition hook) (swink-debugger-hook condition hook) (funcall break-hook condition hook)) 'swink-debugger-hook)) (setq ui-object (ccl::application-ui-object *application*)) (setf (ccl::application-ui-object *application*) (make-instance 'server-ui-object)) (setq using-swink-globally t)) (when using-swink-globally (setf *select-interactive-process-hook* select-hook *debugger-hook* debugger-hook *break-hook* break-hook (ccl::application-ui-object *application*) ui-object) (setq using-swink-globally nil))))) (defclass swink-stream () ((thread :initarg :thread :reader stream-thread) (lock :initform (make-lock)) (buffer :initform "" :initarg :buffer) (index :initform 0) (column :initform 0 :reader stream-line-column) (line-length :initform ccl::*default-right-margin* :accessor stream-line-length))) (defmethod stream-thread ((stream two-way-stream)) (stream-thread (two-way-stream-input-stream stream))) (defmethod stream-thread ((stream stream)) nil) (defmacro with-swink-stream (slots stream &body body) `(with-slots (lock ,@slots) ,stream (with-lock-grabbed (lock) ,@body))) (defclass swink-output-stream (swink-stream fundamental-character-output-stream) ((output-fn :initarg :output-fn) (buffer :initform (make-string 8000) :initarg :buffer))) (defun make-output-stream (thread output-fn) (make-instance 'swink-output-stream :thread thread :output-fn output-fn)) (defun output-stream-output (stream string start end) (with-slots (output-fn thread) stream (let ((conn (thread-connection thread))) (handler-bind ((stream-error (lambda (c) (when (eql (stream-error-stream c) (connection-control-stream conn)) (with-slots (ccl::stream) c (setf ccl::stream stream)))))) (funcall output-fn thread string start end))))) (with-slots (buffer index) stream (unless (eql index 0) (output-stream-output stream buffer 0 index) (setf index 0)))) (defmethod stream-write-char ((stream swink-output-stream) char) (with-swink-stream (buffer index column) stream (when (eql index (length buffer)) (flush-buffer stream)) (setf (schar buffer index) char) (incf index) (if (eql char #\newline) (setf column 0) (incf column))) char) (defmethod stream-write-string ((stream swink-output-stream) string &optional start end) (with-swink-stream (buffer index column) stream (let* ((len (length buffer)) (start (or start 0)) (end (ccl::check-sequence-bounds string start end)) (count (- end start)) (free (- len index))) (when (>= count free) (flush-buffer stream)) (cond ((< count len) (replace buffer string :start1 index :start2 start :end2 end) (incf index count)) (t (output-stream-output stream string start end))) (let ((last-newline (position #\newline string :from-end t :start start :end end))) (setf column (if last-newline (- end last-newline 1) (+ column count)))))) string) (defmethod stream-force-output ((stream swink-output-stream)) (with-swink-stream () stream (flush-buffer stream))) (defmethod ccl::stream-finish-output ((stream swink-output-stream)) (stream-force-output stream)) (defclass swink-input-stream (swink-stream fundamental-character-input-stream) ((input-fn :initarg :input-fn))) (defun make-input-stream (thread input-fn) (make-instance 'swink-input-stream :thread thread :input-fn input-fn)) (defun input-stream-input (stream) (with-slots (input-fn thread) stream (let ((conn (thread-connection thread))) (handler-bind ((stream-error (lambda (c) (when (eql (stream-error-stream c) (connection-control-stream conn)) (with-slots (ccl::stream) c (setf ccl::stream stream)))))) (funcall input-fn thread))))) (defmethod stream-read-char ((stream swink-input-stream)) (with-swink-stream (buffer index column) stream (unless (< index (length buffer)) (let ((string (input-stream-input stream))) (cond ((eql (length string) 0) (return-from stream-read-char :eof)) (t (setf buffer string index 0))))) (let ((char (aref buffer index))) (incf index) (if (eql char #\Newline) (setf column 0) (incf column)) char))) (defmethod stream-read-char-no-hang ((stream swink-input-stream)) (with-swink-stream (buffer index column) stream (when (< index (length buffer)) (let ((char (aref buffer index))) (incf index) (if (eql char #\Newline) (setf column 0) (incf column)) char)))) (defmethod stream-listen ((stream swink-input-stream)) (with-swink-stream (buffer index) stream (< index (length buffer)))) (defmethod stream-unread-char ((stream swink-input-stream) char) (with-swink-stream (buffer index) stream (setf buffer (make-string 1 :initial-element char)) (if (> index 0) (decf index) (error "Unread with no preceeding read"))))) (defmethod stream-clear-input ((stream swink-input-stream)) (with-swink-stream (buffer index) stream (setf buffer "" index 0)) nil)
6c800b2c211e14a4506713fe152967effee5727f795846a67f3672c3ae4bad03
practicalli/four-clojure
017_sequences_map.clj
(ns four-clojure.017-sequences-map) ;; #17 Sequences: map ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Difficulty: Elementary ;; Topics: The map function takes two arguments : a function ( f ) and a sequence ( s ) . Map returns a new sequence consisting of the result of applying f to each item of s. Do not confuse the map function with the map data structure . (= _ _ ( map # ( + % 5 ) ' ( 1 2 3 ) ) ) Deconstruct the problem ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Discovering how to use the map function to process all the elements of a collection, using a given function. ;; REPL experiments ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; map will work on a single collection, assuming that the function we use with `map` works with a single argument. ;; each element of the collection will be passed to the function in turn and the result put into a new collection. once all the elements of the collection have been passed to the function , the resulting is returned . ;; The `map` function is responsible for building up the new collection. (map inc [1 2 3]) = > ( 2 3 4 ) ;; The map function can work over multiple collections, assuming the function can take multiple arguments (map + [1 2 3] [3 4 5]) = > ( 4 6 8) (map + [1 2 3] [3 4 5] [6 7 8]) = > ( 10 13 16 ) ;; The `+` function can take multiple arguments, so it can be mapped over multiple collections (map + [1 2 3] [3 4 5] [6 7 8] [9 10 11]) = > ( 19 23 27 ) As well as using a function from Clojure core , or any other library , ;; we can write our own lambda function to be used by the `map` function. our function simply needs to add five to the argument given (fn [arg] (+ arg 5)) ;; In the test this is written in the short form #(+ % 5) ;; So when we map this function over the collection the map function returns a new collection with each element increased by 5 (map #(+ % 5) '(1 2 3)) = > ( 6 7 8) ;; Answers summary ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (6 7 8)
null
https://raw.githubusercontent.com/practicalli/four-clojure/9812b63769a06f9b0bfd63e5ffce380b67e5468b/src/four_clojure/017_sequences_map.clj
clojure
#17 Sequences: map Difficulty: Elementary Topics: Discovering how to use the map function to process all the elements of a collection, using a given function. REPL experiments map will work on a single collection, assuming that the function we use with `map` works with a single argument. each element of the collection will be passed to the function in turn and the result put into a new collection. The `map` function is responsible for building up the new collection. The map function can work over multiple collections, assuming the function can take multiple arguments The `+` function can take multiple arguments, so it can be mapped over multiple collections we can write our own lambda function to be used by the `map` function. In the test this is written in the short form So when we map this function over the collection Answers summary
(ns four-clojure.017-sequences-map) The map function takes two arguments : a function ( f ) and a sequence ( s ) . Map returns a new sequence consisting of the result of applying f to each item of s. Do not confuse the map function with the map data structure . (= _ _ ( map # ( + % 5 ) ' ( 1 2 3 ) ) ) Deconstruct the problem once all the elements of the collection have been passed to the function , the resulting is returned . (map inc [1 2 3]) = > ( 2 3 4 ) (map + [1 2 3] [3 4 5]) = > ( 4 6 8) (map + [1 2 3] [3 4 5] [6 7 8]) = > ( 10 13 16 ) (map + [1 2 3] [3 4 5] [6 7 8] [9 10 11]) = > ( 19 23 27 ) As well as using a function from Clojure core , or any other library , our function simply needs to add five to the argument given (fn [arg] (+ arg 5)) #(+ % 5) the map function returns a new collection with each element increased by 5 (map #(+ % 5) '(1 2 3)) = > ( 6 7 8) (6 7 8)
a5711891f7a3c95ac021bf109fc406844ff582af4eb11ca9d0f59752c0c8941d
lambdamikel/PetriNets-CLIM-Demo
petri3.lisp
-*- Mode : LISP ; Syntax : Common - Lisp ; Package : clim - user -*- ;;; Very simple petri net editor in Common LISP ( CLIM / CLOS - Demo ) ;;; Lets you create token nets and play with them Demonstrates some basic CLIM and CLOS programming techniques ( C ) 2003 by ;;; #-:mswindows (error "This version if for LispWorks CLIM Windows only!") #-:lispworks (error "This version if for LispWorks CLIM Windows only!") ;;; ;;; ;;; (require "clim") (in-package clim-user) ;;; " Model " Classes ;;; (defclass petri-net () ((places :accessor places :initform nil) (transitions :accessor transitions :initform nil) (edges :accessor edges :initform nil))) (defclass token-net (petri-net) ()) ;;; ;;; ;;; (defclass petri-net-item () ((in-net :accessor in-net :initarg :in-net))) (defclass petri-net-item-with-capacity (petri-net-item) ((capacity :accessor capacity :initarg :capacity :initform 1))) (defclass place-or-transition (petri-net-item) ((outgoing-edges :accessor outgoing-edges :initform nil) (incoming-edges :accessor incoming-edges :initform nil))) ;;; ;;; ;;; (defclass transition (place-or-transition) ()) ;;; ;;; ;;; (defclass place (place-or-transition) ()) (defclass place-with-net-tokens (place) ((net-tokens :accessor net-tokens :initarg :net-tokens :initform 0))) (defclass place-with-capacity (place-with-net-tokens petri-net-item-with-capacity) ()) ;;; ;;; ;;; (defclass edge (petri-net-item) ((from :accessor from :initarg :from) (to :accessor to :initarg :to))) (defclass edge-with-capacity (edge petri-net-item-with-capacity) ()) ;;; ;;; ;;; (defun make-petri-net () (make-instance 'petri-net)) (defun make-token-net () (make-instance 'token-net)) ;;; ;;; ;;; (defmethod initialize-instance :after ((transition transition) &rest initargs) (push transition (transitions (in-net transition)))) (defmethod make-transition ((net petri-net) &key &allow-other-keys) (make-instance 'transition :in-net net)) ;;; ;;; ;;; (defmethod initialize-instance :after ((place place) &rest initargs) (push place (places (in-net place)))) (defmethod make-place ((net petri-net) &rest args) (make-instance 'place :in-net net)) (defmethod make-place ((net token-net) &key (net-tokens 0) capacity &allow-other-keys) (if capacity (make-instance 'place-with-capacity :net-tokens net-tokens :capacity capacity :in-net net) (make-instance 'place-with-net-tokens :net-tokens net-tokens :in-net net))) ;;; ;;; ;;; (defmethod initialize-instance :after ((edge edge) &rest initargs) (push edge (outgoing-edges (from edge))) (push edge (incoming-edges (to edge))) (push edge (edges (in-net edge)))) (defmethod link :before ((a place-or-transition) (b place-or-transition) &key &allow-other-keys) (unless (eq (in-net a) (in-net b)) (error "~A and ~A must be in same net!" a b)) (when (some #'(lambda (outgoing-edge) (eq (to outgoing-edge) b)) (outgoing-edges a)) (error "~A and ~A are already linked!" a b))) (defmethod link ((a place-or-transition) (b place-or-transition) &key &allow-other-keys) (error "Can only link places with transitions or transitions with places!")) (defmethod link ((transition transition) (place place) &key &allow-other-keys) (make-instance 'edge :in-net (in-net transition) :from transition :to place)) (defmethod link ((place place) (transition transition) &key &allow-other-keys) (make-instance 'edge :in-net (in-net transition) :from place :to transition)) (defmethod link ((place place-with-net-tokens) (transition transition) &key (capacity 1) &allow-other-keys) (make-instance 'edge-with-capacity :in-net (in-net transition) :from place :to transition :capacity capacity)) (defmethod link ((transition transition) (place place-with-net-tokens) &key (capacity 1) &allow-other-keys) (make-instance 'edge-with-capacity :in-net (in-net transition) :from transition :to place :capacity capacity)) ;;; ;;; ;;; (defmethod unlink ((a place-or-transition) (b place-or-transition)) (dolist (outgoing-edge (outgoing-edges a)) (when (eq (to outgoing-edge) b) (remove-from-net outgoing-edge)))) ;;; ;;; ;;; (defmethod remove-from-net ((edge edge)) (setf (outgoing-edges (from edge)) (delete edge (outgoing-edges (from edge)))) (setf (incoming-edges (to edge)) (delete edge (incoming-edges (to edge)))) (setf (edges (in-net edge)) (delete edge (edges (in-net edge)))) (in-net edge)) (defmethod remove-from-net ((place-or-transition place-or-transition)) (dolist (edge (append (outgoing-edges place-or-transition) (incoming-edges place-or-transition))) (remove-from-net edge)) (in-net place-or-transition)) (defmethod remove-from-net :after ((transition transition)) (setf (transitions (in-net transition)) (delete transition (transitions (in-net transition))))) (defmethod remove-from-net :after ((place place)) (setf (places (in-net place)) (delete place (places (in-net place))))) ;;; ;;; ;;; (defmethod may-have-more-net-tokens-p ((place place-with-net-tokens)) t) (defmethod may-have-more-net-tokens-p ((place place-with-capacity)) (< (net-tokens place) (capacity place))) ;;; ;;; ;;; (defmethod add-net-tokens ((place place-with-net-tokens) &optional (net-tokens 1)) (incf (net-tokens place) net-tokens)) (defmethod add-net-tokens :after ((place place-with-capacity) &optional args) (setf (net-tokens place) (min (net-tokens place) (capacity place)))) (defmethod remove-net-tokens ((place place-with-net-tokens) &optional (net-tokens 1)) (unless (zerop (net-tokens place)) (decf (net-tokens place) net-tokens))) ;;; ;;; ;;; (defmethod increase-capacity ((item petri-net-item-with-capacity) &optional (increment 1)) (incf (capacity item) increment)) (defmethod decrease-capacity ((item petri-net-item-with-capacity) &optional (increment 1)) (unless (zerop (1- (capacity item))) (decf (capacity item) increment))) ;;; ;;; ;;; (defmethod activated-p ((transition transition)) (active-p (in-net transition) transition)) (defmethod active-p ((net petri-net) (transition transition)) t) (defmethod active-p ((net token-net) (transition transition)) (and (incoming-edges transition) (every #'(lambda (incoming-edge) (>= (net-tokens (from incoming-edge)) (capacity incoming-edge))) (incoming-edges transition)) (outgoing-edges transition) (every #'(lambda (outgoing-edge) (or (not (typep (to outgoing-edge) 'place-with-capacity)) (<= (+ (net-tokens (to outgoing-edge)) (capacity outgoing-edge)) (capacity (to outgoing-edge))))) (outgoing-edges transition)))) ;;; ;;; ;;; (defmethod activate :before ((transition transition)) (unless (activated-p transition) (error "Transition ~A is not active!" transition))) (defmethod activate ((transition transition)) (make-step transition (in-net transition))) ;;; ;;; ;;; (defmethod make-step ((transition transition) (net petri-net)) net) (defmethod make-step ((transition transition) (net token-net)) (dolist (incoming-edge (incoming-edges transition)) (remove-net-tokens (from incoming-edge) (capacity incoming-edge))) (dolist (outgoing-edge (outgoing-edges transition)) (add-net-tokens (to outgoing-edge) (capacity outgoing-edge))) net) ;;; ;;; ;;; (defmethod step-net ((net petri-net)) t) (defmethod step-net ((net token-net)) (let ((active-transitions (remove-if-not #'activated-p (transitions net)))) (labels ((one-of (sequence) (elt sequence (random (length sequence))))) (when active-transitions (activate (one-of active-transitions)))))) ;;; ;;; "View" Classes ;;; (defconstant +font+ (make-text-style :sans-serif :bold :small)) (defclass display-object () ((object-color :accessor object-color :initform +black+))) (defclass positioned-display-object (display-object) ((x :accessor x :initarg :x) (y :accessor y :initarg :y))) (defclass transition-view (positioned-display-object transition) ((object-color :initform +red+))) (defclass place-view (positioned-display-object place) ((object-color :initform +blue+))) (defclass place-with-net-tokens-view (place-view place-with-net-tokens) ((object-color :initform +blue+))) (defclass place-with-capacity-view (place-with-net-tokens-view place-with-capacity) ()) (defclass edge-view (display-object edge) ()) (defclass edge-with-capacity-view (edge-view edge-with-capacity) ()) ;;; ;;; ;;; (defclass petri-net-view (petri-net standard-application-frame) ()) (defclass token-net-view (petri-net-view token-net) ()) ;;; Solve the " make is n't generic"-problem ( kind of " Factory Pattern " ) ;;; (defmethod make-place ((net petri-net-view) &rest initargs) (apply #'change-class-of-instance (call-next-method) initargs)) (defmethod make-transition ((net petri-net-view) &rest initargs) (apply #'change-class-of-instance (call-next-method) initargs)) (defmethod link :around ((transition transition-view) (place place-view) &rest initargs) (apply #'change-class-of-instance (call-next-method) initargs)) (defmethod link :around ((place place-view) (transition transition-view) &rest initargs) (apply #'change-class-of-instance (call-next-method) initargs)) ;;; ;;; ;;; (defmethod change-class-of-instance ((transition transition) &rest initargs) (apply #'change-class transition 'transition-view initargs)) (defmethod change-class-of-instance ((place place) &rest initargs) (apply #'change-class place 'place-view initargs)) (defmethod change-class-of-instance ((place place-with-net-tokens) &rest initargs) (apply #'change-class place 'place-with-net-tokens-view initargs)) (defmethod change-class-of-instance ((place place-with-capacity) &rest initargs) (apply #'change-class place 'place-with-capacity-view initargs)) (defmethod change-class-of-instance ((edge edge) &rest initargs) (apply #'change-class edge 'edge-view initargs)) (defmethod change-class-of-instance ((edge edge-with-capacity) &rest initargs) (apply #'change-class edge 'edge-with-capacity-view initargs)) ;;; ;;; ;;; (defun get-random-net (n m p) (let ((net (make-petri-net))) (change-class net 'petri-net-view) (let ((places (loop as i from 1 to n collect (make-place net))) (transitions (loop as i from 1 to m collect (make-transition net)))) (loop as place in places do (loop as transition in transitions do (when (zerop (random p)) (link place transition))))) net)) ;;; ;;; Define the application frame ;;; Use inheritance to get a petri net editor ;;; (instead of, e.g., using association) ;;; (define-application-frame petri-net-editor (token-net-view) ( net : accessor net : initform ( get - random - net 10 10 3 ) ) (scaling-factor :accessor scaling-factor :initform 1.0)) (:command-table (petri-net-editor :menu (("Commands" :menu command-table)))) (:panes (pointer-documentation-pane (make-clim-stream-pane :type 'pointer-documentation-pane :text-style +font+ :height '(1 :line) :min-height '(1 :line))) (command :interactor :text-style +font+) (display :application :display-function #'draw :incremental-redisplay t :redisplay-after-commands t) (scaling-factor :application :text-style +font+ :scroll-bars nil :incremental-redisplay t :display-function #'(lambda (frame stream) (updating-output (stream :unique-id 'scaling-factor :cache-value (scaling-factor frame) :cache-test #'=) (format stream "Current Scaling Factor: ~A" (scaling-factor frame))))) (slider (make-pane 'slider :text-style +font+ :scroll-bars nil :client 'slider :id 'slider :min-value 0.1 :max-value 10 :number-of-tick-marks 10 :value-changed-callback #'(lambda (slider val) (declare (ignore slider)) (with-application-frame (frame) (setf (scaling-factor frame) val) (redisplay-frame-panes frame))))) (quit-button (make-pane 'push-button :label "Quit!" :text-style +font+ :activate-callback #'(lambda (button) (declare (ignore button)) (with-application-frame (frame) (frame-exit frame))))) (refresh-button (make-pane 'push-button :label "Refresh!" :label "Quit!" :activate-callback #'(lambda (button) (declare (ignore button)) (with-application-frame (frame) (setf (scaling-factor frame) 1.0) (redisplay-frame-panes frame :force-p t))))) (step-button (make-pane 'push-button :label "Step!" :label "Quit!" :activate-callback #'(lambda (button) (declare (ignore button)) (with-application-frame (frame) (step-net frame) (redisplay-frame-panes frame)))))) (:layouts (:default (vertically () (3/4 (vertically () (horizontally () (1/7 quit-button) (1/7 refresh-button) (1/7 step-button)) (horizontally () (1/2 slider) (1/2 scaling-factor)) display)) (1/4 command) pointer-documentation-pane)))) ;;; ;;; ;;; (defmethod get-pane-size ((stream stream)) (bounding-rectangle-size (bounding-rectangle (window-viewport stream)))) (defmethod get-relative-coordinates ((frame petri-net-editor) x y) (multiple-value-bind (width height) (get-pane-size (get-frame-pane frame 'display)) (values (/ (/ x width) (scaling-factor frame)) (/ (/ y height) (scaling-factor frame))))) (defmethod get-dimensions ((transition transition-view)) (with-application-frame (frame) (values (/ 0.05 (scaling-factor frame)) (/ 0.03 (scaling-factor frame))))) (defmethod get-dimensions ((place place-view)) (with-application-frame (frame) (values (/ 0.05 (scaling-factor frame))))) ;;; ;;; Draw the editor's content ;;; (defmethod draw ((frame petri-net-editor) stream) (multiple-value-bind (width height) (get-pane-size stream) (with-scaling (stream (scaling-factor frame) (scaling-factor frame) ) (with-scaling (stream width height) (dolist (object (append (places frame) (transitions frame))) (present object (type-of object) :stream stream :view +gadget-view+ :single-box t)) (dolist (edge (edges frame)) (present edge (type-of edge) :stream stream :view +gadget-view+)))))) ;;; ;;; Define the presentation methods ;;; (define-presentation-method present :around (object (type positioned-display-object) stream (view gadget-view) &key) (with-translation (stream (x object) (y object)) (call-next-method))) (define-presentation-method present :around (object (type display-object) stream (view gadget-view) &key) (with-drawing-options (stream :line-thickness 3 :ink (object-color object) :text-style +font+) (call-next-method))) (define-presentation-method present (place (type place-view) stream (view gadget-view) &key) (with-application-frame (frame) (multiple-value-bind (radius) (get-dimensions place) (updating-output (stream :unique-id place :cache-value (list (scaling-factor frame) (x place) (y place) (object-color place)) :cache-test #'equal) (draw-circle* stream 0 0 radius :filled nil))))) (define-presentation-method present (place (type place-with-net-tokens-view) stream (view gadget-view) &key) (with-application-frame (frame) (labels ((deg-to-rad (phi) (* pi (/ phi 180)))) (multiple-value-bind (radius) (get-dimensions place) (updating-output (stream :unique-id place :cache-value (list (scaling-factor frame) (x place) (y place) (object-color place) (net-tokens place)) :cache-test #'equal) (draw-circle* stream 0 0 radius :filled nil)) (unless (zerop (net-tokens place)) (let* ((n (net-tokens place)) (w (/ 360 n)) (r (* 2/3 radius)) (s (* 1/8 radius))) (loop as a from 1 to n do (draw-circle* stream (* r (sin (deg-to-rad (* a w)))) (* r (cos (deg-to-rad (* a w)))) s :ink +black+)))))))) (define-presentation-type capacity-label-view ()) (define-presentation-method presentation-typep (object (type capacity-label-view)) (typep object 'petri-net-item-with-capacity)) (define-presentation-method present :after (place (type place-with-capacity-view) stream (view gadget-view) &key) (with-application-frame (frame) (multiple-value-bind (radius) (get-dimensions place) (updating-output (stream :unique-id (list place (capacity place)) :id-test #'equal :cache-value (list (scaling-factor frame) (x place) (x place) (object-color place) (capacity place)) :cache-test #'equal) (with-output-as-presentation (stream place 'capacity-label-view) (draw-text* stream (format nil "~A" (capacity place)) radius radius)))))) (define-presentation-method present (transition (type transition-view) stream (view gadget-view) &key) (with-application-frame (frame) (multiple-value-bind (width height) (get-dimensions transition) (updating-output (stream :unique-id transition :cache-value (list (activated-p transition) (scaling-factor frame) (x transition) (x transition) (object-color transition)) :cache-test #'equal) (draw-rectangle* stream (- width) (- height) width height :filled (activated-p transition)))))) (define-presentation-method present (edge (type edge-view) stream (view gadget-view) &key) (with-application-frame (frame) (let ((from (from edge)) (to (to edge))) (updating-output (stream :unique-id edge :cache-value (list (scaling-factor frame) (x from) (x to) (y from) (y to) (object-color edge)) :cache-test #'equal) (draw-arrow* stream (x from) (y from) (x to) (y to) :line-thickness 2 :head-length (/ 0.03 (scaling-factor frame)) :head-width (/ 0.03 (scaling-factor frame))))))) (define-presentation-method present :after (edge (type edge-with-capacity-view) stream (view gadget-view) &key) (with-application-frame (frame) (let ((from (from edge)) (to (to edge))) (updating-output (stream :unique-id (list edge (capacity edge)) :id-test #'equal :cache-value (list (scaling-factor frame) (x from) (x to) (y from) (y to) (object-color edge) (capacity edge)) :cache-test #'equal) (with-output-as-presentation (stream edge 'capacity-label-view) (draw-text* stream (format nil "~A" (capacity edge)) (/ (+ (x from) (x to)) 2) (/ (+ (y from) (y to)) 2))))))) ;;; ;;; Define some gesture names ;;; (define-gesture-name :new-place :pointer-button :left) (define-gesture-name :new-transition :pointer-button (:left :shift)) (define-gesture-name :delete :pointer-button :left) (define-gesture-name :activate :pointer-button (:right :shift)) (define-gesture-name :move :pointer-button (:control :left)) (define-gesture-name :add-token :pointer-button :middle) (define-gesture-name :remove-token :pointer-button (:middle :shift)) (define-gesture-name :add-capacity-label :pointer-button (:middle :control)) ;;; ;;; Define some editor commands ;;; (define-petri-net-editor-command (com-new-transition :menu nil :name "New Transition") ((x 'integer) (y 'integer)) (with-application-frame (frame) (multiple-value-bind (x y) (get-relative-coordinates frame x y) (make-transition frame :x x :y y)))) (define-petri-net-editor-command (com-new-place :menu nil :name nil) ((x 'integer) (y 'integer)) (with-application-frame (frame) (multiple-value-bind (x y) (get-relative-coordinates frame x y) (make-place frame :x x :y y)))) ;;; ;;; (define-petri-net-editor-command (com-link-place-with-transition :menu nil :name "Link Place with Transition") ((place 'place-view) (transition 'transition-view)) (link place transition)) (define-petri-net-editor-command (com-link-transition-with-place :menu nil :name "Link Transition with Place") ((transition 'transition-view) (place 'place-view)) (link transition place)) ;;; ;;; ;;; (define-petri-net-editor-command (com-unlink-place-and-transition :menu nil :name "Unlink Place and Transition") ((place 'place-view) (transition 'transition-view)) (unlink place transition)) (define-petri-net-editor-command (com-unlink-transition-and-place :menu nil :name "Unlink Transition and Place") ((transition 'transition-view) (place 'place-view)) (unlink transition place)) ;;; ;;; ;;; (define-petri-net-editor-command (com-delete-object :menu nil :name "Delete Object") ((object 'display-object)) (remove-from-net object)) ;;; ;;; ;;; ;;; (define-petri-net-editor-command (com-add-token :menu nil :name "Add Token") ((place-with-net-tokens `(and place-with-net-tokens-view (satisfies may-have-more-net-tokens-p)))) (add-net-tokens place-with-net-tokens)) (define-petri-net-editor-command (com-remove-token :menu nil :name "Remove Token") ((place-with-net-tokens `(and place-with-net-tokens-view (satisfies ,#'(lambda (place) (not (zerop (net-tokens place)))))))) (remove-net-tokens place-with-net-tokens)) ;;; ;;; ;;; (define-petri-net-editor-command (com-add-capacity-label :menu nil :name "Add Capacity Label") ((place-with-net-tokens `(and place-with-net-tokens-view (satisfies ,#'(lambda (object) (not (typep object 'place-with-capacity-view)))))) (capacity 'integer)) (apply #'change-class place-with-net-tokens 'place-with-capacity-view :capacity capacity nil)) ;;; ;;; ;;; (define-petri-net-editor-command (com-increase-capacity :menu nil :name "Increase Capacity") ((capacity-label 'capacity-label-view)) (increase-capacity capacity-label 1)) (define-petri-net-editor-command (com-decrease-capacity :menu nil :name "Decrease Capacity") ((capacity-label `(and capacity-label-view (satisfies ,#'(lambda (object) (not (zerop (1- (capacity object))))))))) (decrease-capacity capacity-label 1)) ;;; ;;; ;;; (define-petri-net-editor-command (com-activate-transition :menu nil :name "Activate Transition") ((transition 'transition-view)) (activate transition)) ;;; ;;; ;;; (define-petri-net-editor-command (com-move-display-object :menu nil :name "Move Display Object") ((object 'positioned-display-object)) (with-application-frame (frame) (let ((ox (x object)) (oy (y object)) (stream (get-frame-pane frame 'display))) (tracking-pointer (stream) (:pointer-motion (x y) (multiple-value-bind (x y) (get-relative-coordinates frame x y) (setf (x object) x (y object) y) (redisplay-frame-pane frame stream))) (:pointer-button-press (event) (when (= (pointer-event-button event) +pointer-right-button+) (setf (x object) ox (y object) oy)) (return)))))) (define-petri-net-editor-command (com-new-transition-no-arguments :menu nil :name "New Transition") nil (with-application-frame (frame) (let ((stream (get-frame-pane frame 'display))) (multiple-value-bind (x y) (tracking-pointer (stream) (:pointer-button-press (x y event) (when (= (pointer-event-button event) +pointer-left-button+) (return (values x y))))) (com-new-transition x y))))) (define-petri-net-editor-command (com-new-place-no-arguments :menu nil :name "New Place") nil (with-application-frame (frame) (let ((stream (get-frame-pane frame 'display))) (multiple-value-bind (x y) (tracking-pointer (stream) (:pointer-button-press (x y event) (when (= (pointer-event-button event) +pointer-left-button+) (return (values x y))))) (com-new-place x y))))) ;;; ;;; Define some presentation translators ;;; (define-presentation-to-command-translator move-display-object (positioned-display-object com-move-display-object petri-net-editor :gesture :move :documentation ((stream) (format stream "Move This Object")) :echo t :maintain-history nil) (object) (list object)) (define-presentation-to-command-translator delete-object (display-object com-delete-object petri-net-editor :gesture :delete :documentation ((stream) (format stream "Delete This Object")) :echo nil :maintain-history nil) (object) (list object)) (define-presentation-to-command-translator new-transition (blank-area com-new-transition petri-net-editor :gesture :new-transition :documentation ((stream) (format stream "Create New Transition")) :echo nil :maintain-history nil) (x y) (list x y)) (define-presentation-to-command-translator new-place (blank-area com-new-place petri-net-editor :gesture :new-place :documentation ((stream) (format stream "Create New Place")) :echo nil :maintain-history nil) (x y) (list x y)) (define-presentation-to-command-translator add-token (place-with-net-tokens-view com-add-token petri-net-editor :gesture :add-token :tester ((object) (may-have-more-net-tokens-p object)) :documentation ((stream) (format stream "Add a Token")) :echo t :maintain-history nil) (object) (list object)) (define-presentation-to-command-translator remove-token (place-with-net-tokens-view com-remove-token petri-net-editor :gesture :remove-token :tester ((object) (not (zerop (net-tokens object)))) :documentation ((stream) (format stream "Remove a Token")) :echo t :maintain-history nil) (object) (list object)) (define-presentation-to-command-translator add-capacity-label (place-with-net-tokens-view com-add-capacity-label petri-net-editor :gesture :add-capacity-label :tester ((object) (not (typep object 'place-with-capacity-view))) :documentation ((stream) (format stream "Add a Capacity Label")) :echo t :maintain-history nil) (object) (list object 4)) (define-presentation-to-command-translator increase-capacity (capacity-label-view com-increase-capacity petri-net-editor :gesture :add-token :documentation ((stream) (format stream "Increase Capacity")) :echo t :maintain-history t) (object) (list object)) (define-presentation-to-command-translator decrease-capacity (capacity-label-view com-decrease-capacity petri-net-editor :gesture :remove-token :tester ((object) (not (zerop (1- (capacity object))))) :documentation ((stream) (format stream "Decrease Capacity")) :echo t :maintain-history nil) (object) (list object)) (define-presentation-to-command-translator activate-transition (transition-view com-activate-transition petri-net-editor :gesture :activate :tester ((object) (activated-p object)) :documentation ((stream) (format stream "Activate Transition")) :echo t :maintain-history nil) (object) (list object)) ;;; ;;; Define the command table ;;; (define-command-table command-table :menu (("New Transition" :command (com-new-transition-no-arguments)) ("New Place" :command (com-new-place-no-arguments)) ("Link Place with Transtion" :command (com-link-place-with-transition)) ("Link Transtion with Place" :command (com-link-transition-with-place)) ("divide1" :divider nil) ("Delete Object" :command (com-delete-object)) ("divide2" :divider nil) ("Add Capacity Label" :command (com-add-capacity-label)) ("Increase Capacity" :command (com-increase-capacity)) ("Decrease Capacity" :command (com-decrease-capacity)) ("divide3" :divider nil) ("Add Token" :command (com-add-token)) ("Remove Toke" :command (com-remove-token)) ("divide4" :divider nil) ("Activate Transition" :command (com-activate-transition)))) ;;; ;;; Run the application ;;; (defun petri () (setf *application-frame* (make-application-frame 'petri-net-editor :width 700 :height 700)) (run-frame-top-level *application-frame*)) (petri)
null
https://raw.githubusercontent.com/lambdamikel/PetriNets-CLIM-Demo/86db6608c52fe7cfeffc81a11f6f2ba120ec42c6/src/old/petri3.lisp
lisp
Syntax : Common - Lisp ; Package : clim - user -*- Lets you create token nets and play with them "View" Classes Define the application frame Use inheritance to get a petri net editor (instead of, e.g., using association) Draw the editor's content Define the presentation methods Define some gesture names Define some editor commands Define some presentation translators Define the command table Run the application
Very simple petri net editor in Common LISP ( CLIM / CLOS - Demo ) Demonstrates some basic CLIM and CLOS programming techniques ( C ) 2003 by #-:mswindows (error "This version if for LispWorks CLIM Windows only!") #-:lispworks (error "This version if for LispWorks CLIM Windows only!") (require "clim") (in-package clim-user) " Model " Classes (defclass petri-net () ((places :accessor places :initform nil) (transitions :accessor transitions :initform nil) (edges :accessor edges :initform nil))) (defclass token-net (petri-net) ()) (defclass petri-net-item () ((in-net :accessor in-net :initarg :in-net))) (defclass petri-net-item-with-capacity (petri-net-item) ((capacity :accessor capacity :initarg :capacity :initform 1))) (defclass place-or-transition (petri-net-item) ((outgoing-edges :accessor outgoing-edges :initform nil) (incoming-edges :accessor incoming-edges :initform nil))) (defclass transition (place-or-transition) ()) (defclass place (place-or-transition) ()) (defclass place-with-net-tokens (place) ((net-tokens :accessor net-tokens :initarg :net-tokens :initform 0))) (defclass place-with-capacity (place-with-net-tokens petri-net-item-with-capacity) ()) (defclass edge (petri-net-item) ((from :accessor from :initarg :from) (to :accessor to :initarg :to))) (defclass edge-with-capacity (edge petri-net-item-with-capacity) ()) (defun make-petri-net () (make-instance 'petri-net)) (defun make-token-net () (make-instance 'token-net)) (defmethod initialize-instance :after ((transition transition) &rest initargs) (push transition (transitions (in-net transition)))) (defmethod make-transition ((net petri-net) &key &allow-other-keys) (make-instance 'transition :in-net net)) (defmethod initialize-instance :after ((place place) &rest initargs) (push place (places (in-net place)))) (defmethod make-place ((net petri-net) &rest args) (make-instance 'place :in-net net)) (defmethod make-place ((net token-net) &key (net-tokens 0) capacity &allow-other-keys) (if capacity (make-instance 'place-with-capacity :net-tokens net-tokens :capacity capacity :in-net net) (make-instance 'place-with-net-tokens :net-tokens net-tokens :in-net net))) (defmethod initialize-instance :after ((edge edge) &rest initargs) (push edge (outgoing-edges (from edge))) (push edge (incoming-edges (to edge))) (push edge (edges (in-net edge)))) (defmethod link :before ((a place-or-transition) (b place-or-transition) &key &allow-other-keys) (unless (eq (in-net a) (in-net b)) (error "~A and ~A must be in same net!" a b)) (when (some #'(lambda (outgoing-edge) (eq (to outgoing-edge) b)) (outgoing-edges a)) (error "~A and ~A are already linked!" a b))) (defmethod link ((a place-or-transition) (b place-or-transition) &key &allow-other-keys) (error "Can only link places with transitions or transitions with places!")) (defmethod link ((transition transition) (place place) &key &allow-other-keys) (make-instance 'edge :in-net (in-net transition) :from transition :to place)) (defmethod link ((place place) (transition transition) &key &allow-other-keys) (make-instance 'edge :in-net (in-net transition) :from place :to transition)) (defmethod link ((place place-with-net-tokens) (transition transition) &key (capacity 1) &allow-other-keys) (make-instance 'edge-with-capacity :in-net (in-net transition) :from place :to transition :capacity capacity)) (defmethod link ((transition transition) (place place-with-net-tokens) &key (capacity 1) &allow-other-keys) (make-instance 'edge-with-capacity :in-net (in-net transition) :from transition :to place :capacity capacity)) (defmethod unlink ((a place-or-transition) (b place-or-transition)) (dolist (outgoing-edge (outgoing-edges a)) (when (eq (to outgoing-edge) b) (remove-from-net outgoing-edge)))) (defmethod remove-from-net ((edge edge)) (setf (outgoing-edges (from edge)) (delete edge (outgoing-edges (from edge)))) (setf (incoming-edges (to edge)) (delete edge (incoming-edges (to edge)))) (setf (edges (in-net edge)) (delete edge (edges (in-net edge)))) (in-net edge)) (defmethod remove-from-net ((place-or-transition place-or-transition)) (dolist (edge (append (outgoing-edges place-or-transition) (incoming-edges place-or-transition))) (remove-from-net edge)) (in-net place-or-transition)) (defmethod remove-from-net :after ((transition transition)) (setf (transitions (in-net transition)) (delete transition (transitions (in-net transition))))) (defmethod remove-from-net :after ((place place)) (setf (places (in-net place)) (delete place (places (in-net place))))) (defmethod may-have-more-net-tokens-p ((place place-with-net-tokens)) t) (defmethod may-have-more-net-tokens-p ((place place-with-capacity)) (< (net-tokens place) (capacity place))) (defmethod add-net-tokens ((place place-with-net-tokens) &optional (net-tokens 1)) (incf (net-tokens place) net-tokens)) (defmethod add-net-tokens :after ((place place-with-capacity) &optional args) (setf (net-tokens place) (min (net-tokens place) (capacity place)))) (defmethod remove-net-tokens ((place place-with-net-tokens) &optional (net-tokens 1)) (unless (zerop (net-tokens place)) (decf (net-tokens place) net-tokens))) (defmethod increase-capacity ((item petri-net-item-with-capacity) &optional (increment 1)) (incf (capacity item) increment)) (defmethod decrease-capacity ((item petri-net-item-with-capacity) &optional (increment 1)) (unless (zerop (1- (capacity item))) (decf (capacity item) increment))) (defmethod activated-p ((transition transition)) (active-p (in-net transition) transition)) (defmethod active-p ((net petri-net) (transition transition)) t) (defmethod active-p ((net token-net) (transition transition)) (and (incoming-edges transition) (every #'(lambda (incoming-edge) (>= (net-tokens (from incoming-edge)) (capacity incoming-edge))) (incoming-edges transition)) (outgoing-edges transition) (every #'(lambda (outgoing-edge) (or (not (typep (to outgoing-edge) 'place-with-capacity)) (<= (+ (net-tokens (to outgoing-edge)) (capacity outgoing-edge)) (capacity (to outgoing-edge))))) (outgoing-edges transition)))) (defmethod activate :before ((transition transition)) (unless (activated-p transition) (error "Transition ~A is not active!" transition))) (defmethod activate ((transition transition)) (make-step transition (in-net transition))) (defmethod make-step ((transition transition) (net petri-net)) net) (defmethod make-step ((transition transition) (net token-net)) (dolist (incoming-edge (incoming-edges transition)) (remove-net-tokens (from incoming-edge) (capacity incoming-edge))) (dolist (outgoing-edge (outgoing-edges transition)) (add-net-tokens (to outgoing-edge) (capacity outgoing-edge))) net) (defmethod step-net ((net petri-net)) t) (defmethod step-net ((net token-net)) (let ((active-transitions (remove-if-not #'activated-p (transitions net)))) (labels ((one-of (sequence) (elt sequence (random (length sequence))))) (when active-transitions (activate (one-of active-transitions)))))) (defconstant +font+ (make-text-style :sans-serif :bold :small)) (defclass display-object () ((object-color :accessor object-color :initform +black+))) (defclass positioned-display-object (display-object) ((x :accessor x :initarg :x) (y :accessor y :initarg :y))) (defclass transition-view (positioned-display-object transition) ((object-color :initform +red+))) (defclass place-view (positioned-display-object place) ((object-color :initform +blue+))) (defclass place-with-net-tokens-view (place-view place-with-net-tokens) ((object-color :initform +blue+))) (defclass place-with-capacity-view (place-with-net-tokens-view place-with-capacity) ()) (defclass edge-view (display-object edge) ()) (defclass edge-with-capacity-view (edge-view edge-with-capacity) ()) (defclass petri-net-view (petri-net standard-application-frame) ()) (defclass token-net-view (petri-net-view token-net) ()) Solve the " make is n't generic"-problem ( kind of " Factory Pattern " ) (defmethod make-place ((net petri-net-view) &rest initargs) (apply #'change-class-of-instance (call-next-method) initargs)) (defmethod make-transition ((net petri-net-view) &rest initargs) (apply #'change-class-of-instance (call-next-method) initargs)) (defmethod link :around ((transition transition-view) (place place-view) &rest initargs) (apply #'change-class-of-instance (call-next-method) initargs)) (defmethod link :around ((place place-view) (transition transition-view) &rest initargs) (apply #'change-class-of-instance (call-next-method) initargs)) (defmethod change-class-of-instance ((transition transition) &rest initargs) (apply #'change-class transition 'transition-view initargs)) (defmethod change-class-of-instance ((place place) &rest initargs) (apply #'change-class place 'place-view initargs)) (defmethod change-class-of-instance ((place place-with-net-tokens) &rest initargs) (apply #'change-class place 'place-with-net-tokens-view initargs)) (defmethod change-class-of-instance ((place place-with-capacity) &rest initargs) (apply #'change-class place 'place-with-capacity-view initargs)) (defmethod change-class-of-instance ((edge edge) &rest initargs) (apply #'change-class edge 'edge-view initargs)) (defmethod change-class-of-instance ((edge edge-with-capacity) &rest initargs) (apply #'change-class edge 'edge-with-capacity-view initargs)) (defun get-random-net (n m p) (let ((net (make-petri-net))) (change-class net 'petri-net-view) (let ((places (loop as i from 1 to n collect (make-place net))) (transitions (loop as i from 1 to m collect (make-transition net)))) (loop as place in places do (loop as transition in transitions do (when (zerop (random p)) (link place transition))))) net)) (define-application-frame petri-net-editor (token-net-view) ( net : accessor net : initform ( get - random - net 10 10 3 ) ) (scaling-factor :accessor scaling-factor :initform 1.0)) (:command-table (petri-net-editor :menu (("Commands" :menu command-table)))) (:panes (pointer-documentation-pane (make-clim-stream-pane :type 'pointer-documentation-pane :text-style +font+ :height '(1 :line) :min-height '(1 :line))) (command :interactor :text-style +font+) (display :application :display-function #'draw :incremental-redisplay t :redisplay-after-commands t) (scaling-factor :application :text-style +font+ :scroll-bars nil :incremental-redisplay t :display-function #'(lambda (frame stream) (updating-output (stream :unique-id 'scaling-factor :cache-value (scaling-factor frame) :cache-test #'=) (format stream "Current Scaling Factor: ~A" (scaling-factor frame))))) (slider (make-pane 'slider :text-style +font+ :scroll-bars nil :client 'slider :id 'slider :min-value 0.1 :max-value 10 :number-of-tick-marks 10 :value-changed-callback #'(lambda (slider val) (declare (ignore slider)) (with-application-frame (frame) (setf (scaling-factor frame) val) (redisplay-frame-panes frame))))) (quit-button (make-pane 'push-button :label "Quit!" :text-style +font+ :activate-callback #'(lambda (button) (declare (ignore button)) (with-application-frame (frame) (frame-exit frame))))) (refresh-button (make-pane 'push-button :label "Refresh!" :label "Quit!" :activate-callback #'(lambda (button) (declare (ignore button)) (with-application-frame (frame) (setf (scaling-factor frame) 1.0) (redisplay-frame-panes frame :force-p t))))) (step-button (make-pane 'push-button :label "Step!" :label "Quit!" :activate-callback #'(lambda (button) (declare (ignore button)) (with-application-frame (frame) (step-net frame) (redisplay-frame-panes frame)))))) (:layouts (:default (vertically () (3/4 (vertically () (horizontally () (1/7 quit-button) (1/7 refresh-button) (1/7 step-button)) (horizontally () (1/2 slider) (1/2 scaling-factor)) display)) (1/4 command) pointer-documentation-pane)))) (defmethod get-pane-size ((stream stream)) (bounding-rectangle-size (bounding-rectangle (window-viewport stream)))) (defmethod get-relative-coordinates ((frame petri-net-editor) x y) (multiple-value-bind (width height) (get-pane-size (get-frame-pane frame 'display)) (values (/ (/ x width) (scaling-factor frame)) (/ (/ y height) (scaling-factor frame))))) (defmethod get-dimensions ((transition transition-view)) (with-application-frame (frame) (values (/ 0.05 (scaling-factor frame)) (/ 0.03 (scaling-factor frame))))) (defmethod get-dimensions ((place place-view)) (with-application-frame (frame) (values (/ 0.05 (scaling-factor frame))))) (defmethod draw ((frame petri-net-editor) stream) (multiple-value-bind (width height) (get-pane-size stream) (with-scaling (stream (scaling-factor frame) (scaling-factor frame) ) (with-scaling (stream width height) (dolist (object (append (places frame) (transitions frame))) (present object (type-of object) :stream stream :view +gadget-view+ :single-box t)) (dolist (edge (edges frame)) (present edge (type-of edge) :stream stream :view +gadget-view+)))))) (define-presentation-method present :around (object (type positioned-display-object) stream (view gadget-view) &key) (with-translation (stream (x object) (y object)) (call-next-method))) (define-presentation-method present :around (object (type display-object) stream (view gadget-view) &key) (with-drawing-options (stream :line-thickness 3 :ink (object-color object) :text-style +font+) (call-next-method))) (define-presentation-method present (place (type place-view) stream (view gadget-view) &key) (with-application-frame (frame) (multiple-value-bind (radius) (get-dimensions place) (updating-output (stream :unique-id place :cache-value (list (scaling-factor frame) (x place) (y place) (object-color place)) :cache-test #'equal) (draw-circle* stream 0 0 radius :filled nil))))) (define-presentation-method present (place (type place-with-net-tokens-view) stream (view gadget-view) &key) (with-application-frame (frame) (labels ((deg-to-rad (phi) (* pi (/ phi 180)))) (multiple-value-bind (radius) (get-dimensions place) (updating-output (stream :unique-id place :cache-value (list (scaling-factor frame) (x place) (y place) (object-color place) (net-tokens place)) :cache-test #'equal) (draw-circle* stream 0 0 radius :filled nil)) (unless (zerop (net-tokens place)) (let* ((n (net-tokens place)) (w (/ 360 n)) (r (* 2/3 radius)) (s (* 1/8 radius))) (loop as a from 1 to n do (draw-circle* stream (* r (sin (deg-to-rad (* a w)))) (* r (cos (deg-to-rad (* a w)))) s :ink +black+)))))))) (define-presentation-type capacity-label-view ()) (define-presentation-method presentation-typep (object (type capacity-label-view)) (typep object 'petri-net-item-with-capacity)) (define-presentation-method present :after (place (type place-with-capacity-view) stream (view gadget-view) &key) (with-application-frame (frame) (multiple-value-bind (radius) (get-dimensions place) (updating-output (stream :unique-id (list place (capacity place)) :id-test #'equal :cache-value (list (scaling-factor frame) (x place) (x place) (object-color place) (capacity place)) :cache-test #'equal) (with-output-as-presentation (stream place 'capacity-label-view) (draw-text* stream (format nil "~A" (capacity place)) radius radius)))))) (define-presentation-method present (transition (type transition-view) stream (view gadget-view) &key) (with-application-frame (frame) (multiple-value-bind (width height) (get-dimensions transition) (updating-output (stream :unique-id transition :cache-value (list (activated-p transition) (scaling-factor frame) (x transition) (x transition) (object-color transition)) :cache-test #'equal) (draw-rectangle* stream (- width) (- height) width height :filled (activated-p transition)))))) (define-presentation-method present (edge (type edge-view) stream (view gadget-view) &key) (with-application-frame (frame) (let ((from (from edge)) (to (to edge))) (updating-output (stream :unique-id edge :cache-value (list (scaling-factor frame) (x from) (x to) (y from) (y to) (object-color edge)) :cache-test #'equal) (draw-arrow* stream (x from) (y from) (x to) (y to) :line-thickness 2 :head-length (/ 0.03 (scaling-factor frame)) :head-width (/ 0.03 (scaling-factor frame))))))) (define-presentation-method present :after (edge (type edge-with-capacity-view) stream (view gadget-view) &key) (with-application-frame (frame) (let ((from (from edge)) (to (to edge))) (updating-output (stream :unique-id (list edge (capacity edge)) :id-test #'equal :cache-value (list (scaling-factor frame) (x from) (x to) (y from) (y to) (object-color edge) (capacity edge)) :cache-test #'equal) (with-output-as-presentation (stream edge 'capacity-label-view) (draw-text* stream (format nil "~A" (capacity edge)) (/ (+ (x from) (x to)) 2) (/ (+ (y from) (y to)) 2))))))) (define-gesture-name :new-place :pointer-button :left) (define-gesture-name :new-transition :pointer-button (:left :shift)) (define-gesture-name :delete :pointer-button :left) (define-gesture-name :activate :pointer-button (:right :shift)) (define-gesture-name :move :pointer-button (:control :left)) (define-gesture-name :add-token :pointer-button :middle) (define-gesture-name :remove-token :pointer-button (:middle :shift)) (define-gesture-name :add-capacity-label :pointer-button (:middle :control)) (define-petri-net-editor-command (com-new-transition :menu nil :name "New Transition") ((x 'integer) (y 'integer)) (with-application-frame (frame) (multiple-value-bind (x y) (get-relative-coordinates frame x y) (make-transition frame :x x :y y)))) (define-petri-net-editor-command (com-new-place :menu nil :name nil) ((x 'integer) (y 'integer)) (with-application-frame (frame) (multiple-value-bind (x y) (get-relative-coordinates frame x y) (make-place frame :x x :y y)))) (define-petri-net-editor-command (com-link-place-with-transition :menu nil :name "Link Place with Transition") ((place 'place-view) (transition 'transition-view)) (link place transition)) (define-petri-net-editor-command (com-link-transition-with-place :menu nil :name "Link Transition with Place") ((transition 'transition-view) (place 'place-view)) (link transition place)) (define-petri-net-editor-command (com-unlink-place-and-transition :menu nil :name "Unlink Place and Transition") ((place 'place-view) (transition 'transition-view)) (unlink place transition)) (define-petri-net-editor-command (com-unlink-transition-and-place :menu nil :name "Unlink Transition and Place") ((transition 'transition-view) (place 'place-view)) (unlink transition place)) (define-petri-net-editor-command (com-delete-object :menu nil :name "Delete Object") ((object 'display-object)) (remove-from-net object)) (define-petri-net-editor-command (com-add-token :menu nil :name "Add Token") ((place-with-net-tokens `(and place-with-net-tokens-view (satisfies may-have-more-net-tokens-p)))) (add-net-tokens place-with-net-tokens)) (define-petri-net-editor-command (com-remove-token :menu nil :name "Remove Token") ((place-with-net-tokens `(and place-with-net-tokens-view (satisfies ,#'(lambda (place) (not (zerop (net-tokens place)))))))) (remove-net-tokens place-with-net-tokens)) (define-petri-net-editor-command (com-add-capacity-label :menu nil :name "Add Capacity Label") ((place-with-net-tokens `(and place-with-net-tokens-view (satisfies ,#'(lambda (object) (not (typep object 'place-with-capacity-view)))))) (capacity 'integer)) (apply #'change-class place-with-net-tokens 'place-with-capacity-view :capacity capacity nil)) (define-petri-net-editor-command (com-increase-capacity :menu nil :name "Increase Capacity") ((capacity-label 'capacity-label-view)) (increase-capacity capacity-label 1)) (define-petri-net-editor-command (com-decrease-capacity :menu nil :name "Decrease Capacity") ((capacity-label `(and capacity-label-view (satisfies ,#'(lambda (object) (not (zerop (1- (capacity object))))))))) (decrease-capacity capacity-label 1)) (define-petri-net-editor-command (com-activate-transition :menu nil :name "Activate Transition") ((transition 'transition-view)) (activate transition)) (define-petri-net-editor-command (com-move-display-object :menu nil :name "Move Display Object") ((object 'positioned-display-object)) (with-application-frame (frame) (let ((ox (x object)) (oy (y object)) (stream (get-frame-pane frame 'display))) (tracking-pointer (stream) (:pointer-motion (x y) (multiple-value-bind (x y) (get-relative-coordinates frame x y) (setf (x object) x (y object) y) (redisplay-frame-pane frame stream))) (:pointer-button-press (event) (when (= (pointer-event-button event) +pointer-right-button+) (setf (x object) ox (y object) oy)) (return)))))) (define-petri-net-editor-command (com-new-transition-no-arguments :menu nil :name "New Transition") nil (with-application-frame (frame) (let ((stream (get-frame-pane frame 'display))) (multiple-value-bind (x y) (tracking-pointer (stream) (:pointer-button-press (x y event) (when (= (pointer-event-button event) +pointer-left-button+) (return (values x y))))) (com-new-transition x y))))) (define-petri-net-editor-command (com-new-place-no-arguments :menu nil :name "New Place") nil (with-application-frame (frame) (let ((stream (get-frame-pane frame 'display))) (multiple-value-bind (x y) (tracking-pointer (stream) (:pointer-button-press (x y event) (when (= (pointer-event-button event) +pointer-left-button+) (return (values x y))))) (com-new-place x y))))) (define-presentation-to-command-translator move-display-object (positioned-display-object com-move-display-object petri-net-editor :gesture :move :documentation ((stream) (format stream "Move This Object")) :echo t :maintain-history nil) (object) (list object)) (define-presentation-to-command-translator delete-object (display-object com-delete-object petri-net-editor :gesture :delete :documentation ((stream) (format stream "Delete This Object")) :echo nil :maintain-history nil) (object) (list object)) (define-presentation-to-command-translator new-transition (blank-area com-new-transition petri-net-editor :gesture :new-transition :documentation ((stream) (format stream "Create New Transition")) :echo nil :maintain-history nil) (x y) (list x y)) (define-presentation-to-command-translator new-place (blank-area com-new-place petri-net-editor :gesture :new-place :documentation ((stream) (format stream "Create New Place")) :echo nil :maintain-history nil) (x y) (list x y)) (define-presentation-to-command-translator add-token (place-with-net-tokens-view com-add-token petri-net-editor :gesture :add-token :tester ((object) (may-have-more-net-tokens-p object)) :documentation ((stream) (format stream "Add a Token")) :echo t :maintain-history nil) (object) (list object)) (define-presentation-to-command-translator remove-token (place-with-net-tokens-view com-remove-token petri-net-editor :gesture :remove-token :tester ((object) (not (zerop (net-tokens object)))) :documentation ((stream) (format stream "Remove a Token")) :echo t :maintain-history nil) (object) (list object)) (define-presentation-to-command-translator add-capacity-label (place-with-net-tokens-view com-add-capacity-label petri-net-editor :gesture :add-capacity-label :tester ((object) (not (typep object 'place-with-capacity-view))) :documentation ((stream) (format stream "Add a Capacity Label")) :echo t :maintain-history nil) (object) (list object 4)) (define-presentation-to-command-translator increase-capacity (capacity-label-view com-increase-capacity petri-net-editor :gesture :add-token :documentation ((stream) (format stream "Increase Capacity")) :echo t :maintain-history t) (object) (list object)) (define-presentation-to-command-translator decrease-capacity (capacity-label-view com-decrease-capacity petri-net-editor :gesture :remove-token :tester ((object) (not (zerop (1- (capacity object))))) :documentation ((stream) (format stream "Decrease Capacity")) :echo t :maintain-history nil) (object) (list object)) (define-presentation-to-command-translator activate-transition (transition-view com-activate-transition petri-net-editor :gesture :activate :tester ((object) (activated-p object)) :documentation ((stream) (format stream "Activate Transition")) :echo t :maintain-history nil) (object) (list object)) (define-command-table command-table :menu (("New Transition" :command (com-new-transition-no-arguments)) ("New Place" :command (com-new-place-no-arguments)) ("Link Place with Transtion" :command (com-link-place-with-transition)) ("Link Transtion with Place" :command (com-link-transition-with-place)) ("divide1" :divider nil) ("Delete Object" :command (com-delete-object)) ("divide2" :divider nil) ("Add Capacity Label" :command (com-add-capacity-label)) ("Increase Capacity" :command (com-increase-capacity)) ("Decrease Capacity" :command (com-decrease-capacity)) ("divide3" :divider nil) ("Add Token" :command (com-add-token)) ("Remove Toke" :command (com-remove-token)) ("divide4" :divider nil) ("Activate Transition" :command (com-activate-transition)))) (defun petri () (setf *application-frame* (make-application-frame 'petri-net-editor :width 700 :height 700)) (run-frame-top-level *application-frame*)) (petri)
eb439495721468201a4d0a8cf21e397250492291f5b47fa0298783ae1b7ba180
emina/rosette
graph.rkt
#lang racket (require racket/hash racket/struct "data.rkt" "record.rkt" "reporter.rkt" "feature.rkt") (provide (all-defined-out)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Profile graph data structures ;; A profile node is an entry in the dynamic control flow graph of the ;; profiled code. It contains a pointer to its parent node, ;; a list of children nodes, and a profile-data struct that contains the ;; actual data for the profile. (struct profile-node (id parent children data) #:mutable #:methods gen:custom-write [(define write-proc (make-constructor-style-printer (lambda (obj) 'profile-node) (lambda (obj) (let ([d (profile-node-data obj)]) (if d (list (let ([proc (profile-data-procedure d)]) (if (symbol? proc) proc (object-name proc))) (metrics-ref (profile-data-start d) 'time)) (list #f #f))))))]) ;; Profile data for a single procedure invocation. ;; * The location field stores the location at which the given procedure was ;; invoked. ;; * The procedure field is the invoked procedure ;; * The inputs and outputs fields are assoc lists from features to numbers. ;; For each feature in enabled-features, they store the value of that ;; feature for the inputs and outputs of the current invocation. ;; * The metrics field is a hash map from symbols to numbers, where each ;; symbol describes a performance metric collected during symbolic evaluation, ;; e.g., cpu time, real time, gc time, the number of merge invocations, the number ;; of unions and terms created, etc. ;; * The start and finish fields track the value of various metrics at the entry ;; and exit to the current invocation, respectively. (struct profile-data (location procedure inputs outputs metrics start finish) #:mutable #:transparent) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Conversion ;; Convert an instance of profile-state (i.e., a list of profile events) into a ;; dynamic call graph representation. (define (profile-state->graph state) (define events (reverse (unbox (profile-state-events state)))) (unless (profile-event-enter? (first events)) (error 'profile-state->graph "expected first event to be profile-event-enter")) (define node #f) (define root #f) (for ([e events]) (match e [(profile-event-enter met id loc proc in) (define new-in (features->flat-hash in)) (define new-name proc) (define new-data (profile-data loc new-name new-in (hash) '() met (hash))) (define new-node (profile-node id node '() new-data)) (if (false? node) (let () (set-profile-node-parent! new-node new-node) (set! root new-node)) (set-profile-node-children! node (append (profile-node-children node) (list new-node)))) (set! node new-node)] [(profile-event-exit met out) (define data (profile-node-data node)) (define metrics (diff-metrics (profile-data-start data) met)) (set-profile-data-metrics! data metrics) (define new-out (features->flat-hash out)) (set-profile-data-outputs! data new-out) (set-profile-data-finish! data met) (set! node (profile-node-parent node))] [(profile-event-sample met) ; fill in missing statistics up the callgraph (let rec ([node node]) (define data (profile-node-data node)) (define metrics (diff-metrics (profile-data-start data) met)) (set-profile-data-metrics! data metrics) (set-profile-data-finish! data met) (unless (eq? node (profile-node-parent node)) (rec (profile-node-parent node))))] [_ void])) root)
null
https://raw.githubusercontent.com/emina/rosette/a64e2bccfe5876c5daaf4a17c5a28a49e2fbd501/rosette/lib/profile/graph.rkt
racket
Profile graph data structures A profile node is an entry in the dynamic control flow graph of the profiled code. It contains a pointer to its parent node, a list of children nodes, and a profile-data struct that contains the actual data for the profile. Profile data for a single procedure invocation. * The location field stores the location at which the given procedure was invoked. * The procedure field is the invoked procedure * The inputs and outputs fields are assoc lists from features to numbers. For each feature in enabled-features, they store the value of that feature for the inputs and outputs of the current invocation. * The metrics field is a hash map from symbols to numbers, where each symbol describes a performance metric collected during symbolic evaluation, e.g., cpu time, real time, gc time, the number of merge invocations, the number of unions and terms created, etc. * The start and finish fields track the value of various metrics at the entry and exit to the current invocation, respectively. Conversion Convert an instance of profile-state (i.e., a list of profile events) into a dynamic call graph representation. fill in missing statistics up the callgraph
#lang racket (require racket/hash racket/struct "data.rkt" "record.rkt" "reporter.rkt" "feature.rkt") (provide (all-defined-out)) (struct profile-node (id parent children data) #:mutable #:methods gen:custom-write [(define write-proc (make-constructor-style-printer (lambda (obj) 'profile-node) (lambda (obj) (let ([d (profile-node-data obj)]) (if d (list (let ([proc (profile-data-procedure d)]) (if (symbol? proc) proc (object-name proc))) (metrics-ref (profile-data-start d) 'time)) (list #f #f))))))]) (struct profile-data (location procedure inputs outputs metrics start finish) #:mutable #:transparent) (define (profile-state->graph state) (define events (reverse (unbox (profile-state-events state)))) (unless (profile-event-enter? (first events)) (error 'profile-state->graph "expected first event to be profile-event-enter")) (define node #f) (define root #f) (for ([e events]) (match e [(profile-event-enter met id loc proc in) (define new-in (features->flat-hash in)) (define new-name proc) (define new-data (profile-data loc new-name new-in (hash) '() met (hash))) (define new-node (profile-node id node '() new-data)) (if (false? node) (let () (set-profile-node-parent! new-node new-node) (set! root new-node)) (set-profile-node-children! node (append (profile-node-children node) (list new-node)))) (set! node new-node)] [(profile-event-exit met out) (define data (profile-node-data node)) (define metrics (diff-metrics (profile-data-start data) met)) (set-profile-data-metrics! data metrics) (define new-out (features->flat-hash out)) (set-profile-data-outputs! data new-out) (set-profile-data-finish! data met) (set! node (profile-node-parent node))] (let rec ([node node]) (define data (profile-node-data node)) (define metrics (diff-metrics (profile-data-start data) met)) (set-profile-data-metrics! data metrics) (set-profile-data-finish! data met) (unless (eq? node (profile-node-parent node)) (rec (profile-node-parent node))))] [_ void])) root)
9bcf52657cd31fe09165729574af88c15db3c4d54c147b60d3ad7793e6c4cf7f
albertoruiz/easyVision
loop.hs
{-# LANGUAGE Arrows #-} import Vision.GUI import Image.Processing main = run $ observe "source" rgb >>> f >>> observe "result" (5.*) f = proc img -> do let x = (toFloat . grayscale) img p <- delay' -< x returnA -< x |-| p
null
https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/tour/loop.hs
haskell
# LANGUAGE Arrows #
import Vision.GUI import Image.Processing main = run $ observe "source" rgb >>> f >>> observe "result" (5.*) f = proc img -> do let x = (toFloat . grayscale) img p <- delay' -< x returnA -< x |-| p
e0c7b535032beb4274e9b633094d01ba7757c9cb260a8f7c9b115eefd9cf2483
eudoxia0/cl-yaml
emitter2.lisp
(in-package :cl-user) (defpackage cl-yaml-test.emitter2 (:use :cl :fiveam) (:export :emitter2) (:documentation "Emitter tests - libyaml-based emitter.")) (in-package :cl-yaml-test.emitter2) (defmacro define-test-cases ((name) &rest pairs) `(test ,name ,@(loop for (form string) in pairs collecting `(is (equal (yaml.emitter:with-emitter-to-string (emitter) (yaml.emitter:emit-stream (emitter) (yaml.emitter:emit-document (emitter :implicit t) (yaml.emitter:emit-scalar emitter ,form)))) ,(format nil "~a~%...~%" string)))))) ;; Document end marker ;; is libyaml behavior (defun test-emit-sequence (sequence style) (yaml.emitter:with-emitter-to-string (emitter) (yaml.emitter:emit-stream (emitter) (yaml.emitter:emit-document (emitter :implicit t) (yaml.emitter:emit-sequence (emitter :style style) (mapcar (lambda (element) (yaml.emitter:emit-scalar emitter element)) sequence)))))) (defun test-emit-mapping (mapping style) (yaml.emitter:with-emitter-to-string (emitter) (yaml.emitter:emit-stream (emitter) (yaml.emitter:emit-document (emitter :implicit t) (yaml.emitter:emit-mapping (emitter :style style) (mapcar (lambda (pair) (yaml.emitter:emit-scalar emitter (car pair)) (yaml.emitter:emit-scalar emitter (cdr pair))) mapping)))))) (def-suite emitter2 :description "YAML libyaml-based emitter tests.") (in-suite emitter2) (define-test-cases (boolean) (t "true") (nil "false")) (define-test-cases (integers) (1 "1") (123 "123") (+123 "123") (-123 "-123")) (define-test-cases (floats) (1.23 "1.23") (6.62607e-34 "6.62607e-34")) (test flow-sequence (is (equal (test-emit-sequence '(1 "a" 3.14f0 3.14d0) :flow-sequence-style) "[1, a, 3.14, 3.14] "))) (test block-sequence (is (equal (test-emit-sequence '(1 "a" 3.14f0 3.14d0) :block-sequence-style) "- 1 - a - 3.14 - 3.14 "))) (test flow-mapping (is (equal (test-emit-mapping '(("integer" . 1) ("string" . "test") ("bool" . nil)) :flow-mapping-style) "{integer: 1, string: test, bool: false} "))) (test block-mapping (is (equal (test-emit-mapping '(("integer" . 1) ("string" . "test") ("bool" . nil)) :block-mapping-style) "integer: 1 string: test bool: false ")))
null
https://raw.githubusercontent.com/eudoxia0/cl-yaml/c3202be9a753c51f3bc79538a5a498a8865192aa/t/emitter2.lisp
lisp
Document end marker is libyaml behavior
(in-package :cl-user) (defpackage cl-yaml-test.emitter2 (:use :cl :fiveam) (:export :emitter2) (:documentation "Emitter tests - libyaml-based emitter.")) (in-package :cl-yaml-test.emitter2) (defmacro define-test-cases ((name) &rest pairs) `(test ,name ,@(loop for (form string) in pairs collecting `(is (equal (yaml.emitter:with-emitter-to-string (emitter) (yaml.emitter:emit-stream (emitter) (yaml.emitter:emit-document (emitter :implicit t) (yaml.emitter:emit-scalar emitter ,form)))) (defun test-emit-sequence (sequence style) (yaml.emitter:with-emitter-to-string (emitter) (yaml.emitter:emit-stream (emitter) (yaml.emitter:emit-document (emitter :implicit t) (yaml.emitter:emit-sequence (emitter :style style) (mapcar (lambda (element) (yaml.emitter:emit-scalar emitter element)) sequence)))))) (defun test-emit-mapping (mapping style) (yaml.emitter:with-emitter-to-string (emitter) (yaml.emitter:emit-stream (emitter) (yaml.emitter:emit-document (emitter :implicit t) (yaml.emitter:emit-mapping (emitter :style style) (mapcar (lambda (pair) (yaml.emitter:emit-scalar emitter (car pair)) (yaml.emitter:emit-scalar emitter (cdr pair))) mapping)))))) (def-suite emitter2 :description "YAML libyaml-based emitter tests.") (in-suite emitter2) (define-test-cases (boolean) (t "true") (nil "false")) (define-test-cases (integers) (1 "1") (123 "123") (+123 "123") (-123 "-123")) (define-test-cases (floats) (1.23 "1.23") (6.62607e-34 "6.62607e-34")) (test flow-sequence (is (equal (test-emit-sequence '(1 "a" 3.14f0 3.14d0) :flow-sequence-style) "[1, a, 3.14, 3.14] "))) (test block-sequence (is (equal (test-emit-sequence '(1 "a" 3.14f0 3.14d0) :block-sequence-style) "- 1 - a - 3.14 - 3.14 "))) (test flow-mapping (is (equal (test-emit-mapping '(("integer" . 1) ("string" . "test") ("bool" . nil)) :flow-mapping-style) "{integer: 1, string: test, bool: false} "))) (test block-mapping (is (equal (test-emit-mapping '(("integer" . 1) ("string" . "test") ("bool" . nil)) :block-mapping-style) "integer: 1 string: test bool: false ")))
dc0034b317089523f1b57800983b04a0f3e1d69a395fcb4b23908cd284e86fa8
mstone/soutei
soutei-pipelined.hs
Soutei Policy Decision Service It is intended to communice with a pep - auth - filter , an authorization -- filter for a web server. -- The interface is straightforward , via stdin / stdout . The filter -- writes all attributes as name-value-pairs: name1 \n value1 \n name2 \n ... Two \n in a row signify the end of input . -- All attribute names and values are opaque to us, except one. -- If there is an attribute named 'resource', the corresponding value must be a URL , such as / a / b / -- The part is optional. We add a sequence of attributes: -- resource-below = -- resource-below = -- We reply with either T\n or F\n . We also have an option to close -- the connection and exit, or just die. We accept so to reload the policy database . See the usage -- message below. module Main (main) where import Soutei.Assertions (Assertions, fromDataDirWithActions,loadSysCtx, query) import Soutei.Syntax import Soutei.Soutei as Soutei import Control.Monad.Trans import Data.Char ( toLower, isSpace, isAlphaNum, ord ) import Data.List (scanl, init) import Numeric (showHex) import Data.IORef import System.IO (hSetBuffering,stderr,BufferMode(..), Handle, hGetLine, hPutStr, hPutChar, stdin, stdout, hPutStrLn, hFlush) import System.Posix.Signals as Signals import System.Time ( getClockTime ) import System.Environment (getArgs) import System.Directory as Dir import System.Exit import System.IO.Error as IO version = "$Id: soutei-pipelined.hs 1940 2008-02-14 05:26:56Z oleg.kiselyov $" usage = unlines ( ("Soutei-pipelined " ++ version) : "Usage: soutei-pipelined DATA-DIR": "Start the Soutei server.": " DATA-DIR a directory with policy": " The directory should be owned by a dedicated user (e.g., root)": " not being writable to this process, contain a read-only file": " named system (the root of the policy) and no file named": " application.": "Send SIGUSR1 to reload the data.": []) useError msg = do note [msg,"\n",usage] exitWith (ExitFailure 64) startError e = note ["Exception: ", show e] >> exitWith (ExitFailure 66) main = do setTimeZoneGMT hSetBuffering stderr LineBuffering noteDate ["===== Soutei Authorizer server: ", version, "\n\n"] -- Signals.installHandler Signals.sigPIPE Signals.Ignore Nothing getArgs >>= main' data Policy = Policy{policy_data :: Assertions, policy_reload :: IORef Bool, policy_load_action :: IO Assertions} main' [dataDir] = do let load_action = load_policy dataDir `catch` startError policy <- load_action reloadFlag <- newIORef False Signals.installHandler Signals.userDefinedSignal1 (Signals.Catch $ writeIORef reloadFlag True) Nothing loop (Policy policy reloadFlag load_action) main' _ = useError "Exactly one arg is required." -- The main processing loop loop :: Policy -> IO () loop policy = do note ["Listening"] attrs <- getAttrs stdin logRequest attrs policy <- check_reload policy res <- authorizer (policy_data policy) attrs note ["Decision: ", show res] hPutStrLn stdout (if res then "T" else "F") hFlush stdout loop policy note ["\nSuccessful exit"] where check_reload policy = do reload <- readIORef (policy_reload policy) if reload then do p <- writeIORef (policy_reload policy) False >> policy_load_action policy return policy{policy_data = p} else return policy type RequestInfo = [(String,String)] -- Read the sequence of name-value pairs getAttrs :: Handle -> IO [(String,String)] getAttrs h = get [] where get acc = do name <- hGetLine h if name == "" then return acc else do value <- hGetLine h get ((name,value):acc) -- Log the received request. We do that early before starting the parsing, -- so we can display the (potentially erroneous) request data before -- we begin reporting errors about them. -- Note that the type of this function says EMonadIO m -- rather than any MonadCGI . That is , this function assuredly creates no CGI -- output! logRequest :: MonadIO m => RequestInfo -> m () logRequest req = noteDate ["---> New AuthRequest request\n", show req] -- The main authorizer module authorizer :: Assertions -> RequestInfo -> IO Bool authorizer policies req = do let auth_req = read_analyze_req req soutei_query policies auth_req data AuthRequest = AuthRequest {areq_verb :: String, areq_uri :: String, areq_atts :: [(String,String)]} -- Build the request for Soutei read_analyze_req :: RequestInfo -> AuthRequest read_analyze_req req = AuthRequest {areq_verb = "Access", areq_uri = "service", areq_atts = ext_req} where ext_req = maybe req add_to_req $ lookup "resource" req add_to_req uri = map (\v -> ("resource-below",v)) (split_uri uri) ++ req Split the URI at resource boundaries ( as described in the commenst above ) split_uri :: String -> [String] split_uri uri = check $ splitAll '/' uri where check (schema:"":host:components@(_:_)) = map ((schema++'/':'/':host)++) $ build components check (schema:"":host:[]) = [] check ("":components@(_:_)) = build components check components@(_:_) = build components check _ = [] build = tail . scanl (\z a -> z ++ '/':a) "" . init t_split_uri1 = map split_uri [ "", "", "/", "", "", "/", "/", "/a/b/c", "a/b/c", "a", "a/", "a/b/c/"] {- [[],[],[], [],[""],["",""], [],["/a","/a/b"],["/a","/a/b"],[],["/a"],["/a","/a/b","/a/b/c"]] -} -- | Split a list in many on a particular element: -- > splitAll ' m ' " simply marvelous " = = [ " si " , " ply " , " arvelous " ] -- splitAll :: Eq a => a -> [a] -> [[a]] splitAll c s = case break (==c) s of ([], []) -> [] (x, []) -> [x] (x, [_]) -> [x, []] (x, _:y) -> x : splitAll c y soutei_query :: Assertions -> AuthRequest -> IO Bool soutei_query policy areq = do let goal = Soutei.goal "may" [SString $ areq_verb areq, SString $ areq_uri areq] facts <- mapM attr_to_fact $ areq_atts areq note ["Beginning the query; goal: ", show goal, "\n", "facts: ", show (areq_atts areq)] query runLimit policy facts goal runLimit = Just 10000 attr_to_fact (key,val) = atomToFact $ Soutei.fact key [SString val] -- Loading the policies and checking them load_policy :: FilePath -> IO Assertions load_policy data_dir = do note ["Loading policies from directory ",data_dir] ifnotA (doesDirectoryExist data_dir) (fail "Data directory does not exist") ifnotA (getPermissions data_dir >>= \p -> return $ Dir.readable p && Dir.searchable p && (not $ Dir.writable p)) (fail "Data directory has wrong permissions") let sys_ctx_file = ctxFilename data_dir sysCtx ifnotA (getPermissions sys_ctx_file >>= \p -> return $ Dir.readable p && (not $ Dir.writable p)) (fail "System policy is writable: wrong") ifnotA (fmap not $ doesFileExist (ctxFilename data_dir appCtx)) (fail "application file should not exist") policies <- fromDataDirWithActions logErr readA writeA loadSysCtx sys_ctx_file policies return policies where writeA ctx content = return () readA ctx = let ctxFile = ctxFilename data_dir ctx in do b <- doesFileExist ctxFile if b then (return . Just) =<< readFile ctxFile else return Nothing logErr err = note [if isUserError err then ioeGetErrorString err else show err] ifnotA :: Monad m => m Bool -> m () -> m () ifnotA testA ac = do f <- testA if f then return () else ac ctxFilename :: FilePath -> Const -> FilePath ctxFilename dataDir ctx = dataDir ++ "/" ++ encode (show ctx) encode :: String -> String encode = concatMap encode' where encode' ch | isAlphaNum ch || ch `elem` "!#$&'()+,-.;=@_" = [ch] | otherwise = '%' : showHex (ord ch) ";" -- | Convenience function for logging, into stderr note :: MonadIO m => [String] -> m () note msgs = liftIO (mapM_ (hPutStr stderr) msgs >> hPutChar stderr '\n') The same but prints the date first noteDate :: MonadIO m => [String] -> m () noteDate msgs = do t <- liftIO getClockTime note $ show t : ": " : msgs
null
https://raw.githubusercontent.com/mstone/soutei/4d00e12180361561dab948f211bbcf9e75bfb1de/soutei-pipelined.hs
haskell
filter for a web server. writes all attributes as name-value-pairs: All attribute names and values are opaque to us, except one. If there is an attribute named 'resource', the corresponding value The part is optional. We add a sequence of attributes: resource-below = resource-below = the connection and exit, or just die. message below. Signals.installHandler Signals.sigPIPE Signals.Ignore Nothing The main processing loop Read the sequence of name-value pairs Log the received request. We do that early before starting the parsing, so we can display the (potentially erroneous) request data before we begin reporting errors about them. Note that the type of this function says EMonadIO m -- rather than output! The main authorizer module Build the request for Soutei [[],[],[], [],[""],["",""], [],["/a","/a/b"],["/a","/a/b"],[],["/a"],["/a","/a/b","/a/b/c"]] | Split a list in many on a particular element: Loading the policies and checking them | Convenience function for logging, into stderr
Soutei Policy Decision Service It is intended to communice with a pep - auth - filter , an authorization The interface is straightforward , via stdin / stdout . The filter name1 \n value1 \n name2 \n ... Two \n in a row signify the end of input . must be a URL , such as / a / b / We reply with either T\n or F\n . We also have an option to close We accept so to reload the policy database . See the usage module Main (main) where import Soutei.Assertions (Assertions, fromDataDirWithActions,loadSysCtx, query) import Soutei.Syntax import Soutei.Soutei as Soutei import Control.Monad.Trans import Data.Char ( toLower, isSpace, isAlphaNum, ord ) import Data.List (scanl, init) import Numeric (showHex) import Data.IORef import System.IO (hSetBuffering,stderr,BufferMode(..), Handle, hGetLine, hPutStr, hPutChar, stdin, stdout, hPutStrLn, hFlush) import System.Posix.Signals as Signals import System.Time ( getClockTime ) import System.Environment (getArgs) import System.Directory as Dir import System.Exit import System.IO.Error as IO version = "$Id: soutei-pipelined.hs 1940 2008-02-14 05:26:56Z oleg.kiselyov $" usage = unlines ( ("Soutei-pipelined " ++ version) : "Usage: soutei-pipelined DATA-DIR": "Start the Soutei server.": " DATA-DIR a directory with policy": " The directory should be owned by a dedicated user (e.g., root)": " not being writable to this process, contain a read-only file": " named system (the root of the policy) and no file named": " application.": "Send SIGUSR1 to reload the data.": []) useError msg = do note [msg,"\n",usage] exitWith (ExitFailure 64) startError e = note ["Exception: ", show e] >> exitWith (ExitFailure 66) main = do setTimeZoneGMT hSetBuffering stderr LineBuffering noteDate ["===== Soutei Authorizer server: ", version, "\n\n"] getArgs >>= main' data Policy = Policy{policy_data :: Assertions, policy_reload :: IORef Bool, policy_load_action :: IO Assertions} main' [dataDir] = do let load_action = load_policy dataDir `catch` startError policy <- load_action reloadFlag <- newIORef False Signals.installHandler Signals.userDefinedSignal1 (Signals.Catch $ writeIORef reloadFlag True) Nothing loop (Policy policy reloadFlag load_action) main' _ = useError "Exactly one arg is required." loop :: Policy -> IO () loop policy = do note ["Listening"] attrs <- getAttrs stdin logRequest attrs policy <- check_reload policy res <- authorizer (policy_data policy) attrs note ["Decision: ", show res] hPutStrLn stdout (if res then "T" else "F") hFlush stdout loop policy note ["\nSuccessful exit"] where check_reload policy = do reload <- readIORef (policy_reload policy) if reload then do p <- writeIORef (policy_reload policy) False >> policy_load_action policy return policy{policy_data = p} else return policy type RequestInfo = [(String,String)] getAttrs :: Handle -> IO [(String,String)] getAttrs h = get [] where get acc = do name <- hGetLine h if name == "" then return acc else do value <- hGetLine h get ((name,value):acc) any MonadCGI . That is , this function assuredly creates no CGI logRequest :: MonadIO m => RequestInfo -> m () logRequest req = noteDate ["---> New AuthRequest request\n", show req] authorizer :: Assertions -> RequestInfo -> IO Bool authorizer policies req = do let auth_req = read_analyze_req req soutei_query policies auth_req data AuthRequest = AuthRequest {areq_verb :: String, areq_uri :: String, areq_atts :: [(String,String)]} read_analyze_req :: RequestInfo -> AuthRequest read_analyze_req req = AuthRequest {areq_verb = "Access", areq_uri = "service", areq_atts = ext_req} where ext_req = maybe req add_to_req $ lookup "resource" req add_to_req uri = map (\v -> ("resource-below",v)) (split_uri uri) ++ req Split the URI at resource boundaries ( as described in the commenst above ) split_uri :: String -> [String] split_uri uri = check $ splitAll '/' uri where check (schema:"":host:components@(_:_)) = map ((schema++'/':'/':host)++) $ build components check (schema:"":host:[]) = [] check ("":components@(_:_)) = build components check components@(_:_) = build components check _ = [] build = tail . scanl (\z a -> z ++ '/':a) "" . init t_split_uri1 = map split_uri [ "", "", "/", "", "", "/", "/", "/a/b/c", "a/b/c", "a", "a/", "a/b/c/"] > splitAll ' m ' " simply marvelous " = = [ " si " , " ply " , " arvelous " ] splitAll :: Eq a => a -> [a] -> [[a]] splitAll c s = case break (==c) s of ([], []) -> [] (x, []) -> [x] (x, [_]) -> [x, []] (x, _:y) -> x : splitAll c y soutei_query :: Assertions -> AuthRequest -> IO Bool soutei_query policy areq = do let goal = Soutei.goal "may" [SString $ areq_verb areq, SString $ areq_uri areq] facts <- mapM attr_to_fact $ areq_atts areq note ["Beginning the query; goal: ", show goal, "\n", "facts: ", show (areq_atts areq)] query runLimit policy facts goal runLimit = Just 10000 attr_to_fact (key,val) = atomToFact $ Soutei.fact key [SString val] load_policy :: FilePath -> IO Assertions load_policy data_dir = do note ["Loading policies from directory ",data_dir] ifnotA (doesDirectoryExist data_dir) (fail "Data directory does not exist") ifnotA (getPermissions data_dir >>= \p -> return $ Dir.readable p && Dir.searchable p && (not $ Dir.writable p)) (fail "Data directory has wrong permissions") let sys_ctx_file = ctxFilename data_dir sysCtx ifnotA (getPermissions sys_ctx_file >>= \p -> return $ Dir.readable p && (not $ Dir.writable p)) (fail "System policy is writable: wrong") ifnotA (fmap not $ doesFileExist (ctxFilename data_dir appCtx)) (fail "application file should not exist") policies <- fromDataDirWithActions logErr readA writeA loadSysCtx sys_ctx_file policies return policies where writeA ctx content = return () readA ctx = let ctxFile = ctxFilename data_dir ctx in do b <- doesFileExist ctxFile if b then (return . Just) =<< readFile ctxFile else return Nothing logErr err = note [if isUserError err then ioeGetErrorString err else show err] ifnotA :: Monad m => m Bool -> m () -> m () ifnotA testA ac = do f <- testA if f then return () else ac ctxFilename :: FilePath -> Const -> FilePath ctxFilename dataDir ctx = dataDir ++ "/" ++ encode (show ctx) encode :: String -> String encode = concatMap encode' where encode' ch | isAlphaNum ch || ch `elem` "!#$&'()+,-.;=@_" = [ch] | otherwise = '%' : showHex (ord ch) ";" note :: MonadIO m => [String] -> m () note msgs = liftIO (mapM_ (hPutStr stderr) msgs >> hPutChar stderr '\n') The same but prints the date first noteDate :: MonadIO m => [String] -> m () noteDate msgs = do t <- liftIO getClockTime note $ show t : ": " : msgs
463f31fff1bfefd351b051eb97170fba213ac034bff2816aff8c7a68f59ba199
degree9/uikit-hl
totop.cljs
(ns uikit-hl.totop (:require [hoplon.core :as h])) (defmulti uk-totop! h/kw-dispatcher :default ::default) (defmethod h/do! ::default [elem key val] (uk-totop! elem key val)) (defmethod uk-totop! ::default [elem kw v] (h/do! elem :uk-totop (clj->js v))) (h/defelem totop [attr kids] (h/a attr ::uk-totop true kids))
null
https://raw.githubusercontent.com/degree9/uikit-hl/b226b1429ea50f8e9a6c1d12c082a3be504dda33/src/uikit_hl/totop.cljs
clojure
(ns uikit-hl.totop (:require [hoplon.core :as h])) (defmulti uk-totop! h/kw-dispatcher :default ::default) (defmethod h/do! ::default [elem key val] (uk-totop! elem key val)) (defmethod uk-totop! ::default [elem kw v] (h/do! elem :uk-totop (clj->js v))) (h/defelem totop [attr kids] (h/a attr ::uk-totop true kids))
aabb71a6e176744f860bbeb664a1a1cd28b7a450bf5a24b1c5804bfe31dc93cd
wincent/docvim
ReadDir.hs
-- | Recursively read the paths in a directory. -- Based on ` RecursiveContents ` example in chapter 9 of " Real World Haskell " . module Text.Docvim.ReadDir (readDir) where import Control.Monad import System.Directory import System.FilePath readDir :: FilePath -> IO [FilePath] readDir dir = do names <- getDirectoryContents dir let properNames = filter (`notElem` [".", ".."]) names paths <- forM properNames $ \name -> do let path = dir </> name isDirectory <- doesDirectoryExist path if isDirectory then readDir path else return [path] return (concat paths)
null
https://raw.githubusercontent.com/wincent/docvim/621a4d30f17a9fda64cf6b37d4608cbe08bc72e3/lib/Text/Docvim/ReadDir.hs
haskell
| Recursively read the paths in a directory.
Based on ` RecursiveContents ` example in chapter 9 of " Real World Haskell " . module Text.Docvim.ReadDir (readDir) where import Control.Monad import System.Directory import System.FilePath readDir :: FilePath -> IO [FilePath] readDir dir = do names <- getDirectoryContents dir let properNames = filter (`notElem` [".", ".."]) names paths <- forM properNames $ \name -> do let path = dir </> name isDirectory <- doesDirectoryExist path if isDirectory then readDir path else return [path] return (concat paths)
706394b4b5bc543e91a01c4e7aa68ba91f99bab5f4d4a82852e73d4fc865ed3c
ghollisjr/cl-ana
package.lisp
cl - ana is a Common Lisp data analysis library . Copyright 2013 , 2014 ;;;; This file is part of cl - ana . ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see </>. ;;;; You may contact ( me ! ) via email at ;;;; package.lisp (defpackage #:cl-ana.memoization (:use #:cl #:alexandria) (:export :memolet :memoize :unmemoize :defun-memoized :get-memo-map :reset-memo-map))
null
https://raw.githubusercontent.com/ghollisjr/cl-ana/5cb4c0b0c9c4957452ad2a769d6ff9e8d5df0b10/memoization/package.lisp
lisp
cl-ana is free software: you can redistribute it and/or modify it (at your option) any later version. cl-ana 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 cl-ana. If not, see </>.
cl - ana is a Common Lisp data analysis library . Copyright 2013 , 2014 This file is part of cl - ana . 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 You may contact ( me ! ) via email at package.lisp (defpackage #:cl-ana.memoization (:use #:cl #:alexandria) (:export :memolet :memoize :unmemoize :defun-memoized :get-memo-map :reset-memo-map))
4877b3a127bff6b0fba07afa2e9e4469883ab8ecfb887ca347522e1e809dc28a
ruhler/smten
SymbolicOf.hs
# LANGUAGE MultiParamTypeClasses # module Smten.Runtime.SymbolicOf ( SymbolicOf(..), ($$), symapp2, ) where import Smten.Runtime.SmtenHS infixr 0 $$ class SymbolicOf c s where tosym :: c -> s symapp :: (SmtenHS0 a) => (c -> a) -> s -> a ($$) :: (SymbolicOf c s, SmtenHS0 a) => (c -> a) -> s -> a ($$) = symapp {-# INLINEABLE symapp2 #-} symapp2 :: (SymbolicOf c1 s1, SymbolicOf c2 s2, SmtenHS0 a) => (c1 -> c2 -> a) -> s1 -> s2 -> a symapp2 f a b = symapp (\av -> symapp (\bv -> f av bv) b) a
null
https://raw.githubusercontent.com/ruhler/smten/16dd37fb0ee3809408803d4be20401211b6c4027/smten-base/Smten/Runtime/SymbolicOf.hs
haskell
# INLINEABLE symapp2 #
# LANGUAGE MultiParamTypeClasses # module Smten.Runtime.SymbolicOf ( SymbolicOf(..), ($$), symapp2, ) where import Smten.Runtime.SmtenHS infixr 0 $$ class SymbolicOf c s where tosym :: c -> s symapp :: (SmtenHS0 a) => (c -> a) -> s -> a ($$) :: (SymbolicOf c s, SmtenHS0 a) => (c -> a) -> s -> a ($$) = symapp symapp2 :: (SymbolicOf c1 s1, SymbolicOf c2 s2, SmtenHS0 a) => (c1 -> c2 -> a) -> s1 -> s2 -> a symapp2 f a b = symapp (\av -> symapp (\bv -> f av bv) b) a
4435bd7b4f8eb77d942f6cd536c3787b92a86d3140f00ea03515acee2802a6eb
adventuring/tootsville.net
players.lisp
;;;; -*- lisp -*- ;;; src / players.lisp is part of ;;; Copyright © 2008 - 2017 Bruce - Robert Pocock ; © 2018 - 2021 The Corporation for Inter - World Tourism and Adventuring ( ciwta.org ) . ;;; This program is Free Software : you can redistribute it and/or modify it under the terms of the GNU Affero 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 ;;; Affero General Public License for more details. ;;; You should have received a copy of the GNU Affero General Public ;;; License along with this program. If not, see ;;; </>. ;;; ;;; You can reach CIWTA at /, or write to us at: ;;; PO Box 23095 Oakland Park , FL 33307 - 3095 USA (in-package :Tootsville)
null
https://raw.githubusercontent.com/adventuring/tootsville.net/985c11a91dd1a21b77d7378362d86cf1c031b22c/src/players.lisp
lisp
-*- lisp -*- © 2018 - 2021 The either version 3 of 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 Affero General Public License for more details. License along with this program. If not, see </>. You can reach CIWTA at /, or write to us at:
src / players.lisp is part of Corporation for Inter - World Tourism and Adventuring ( ciwta.org ) . This program is Free Software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License the License , or ( at your option ) any later version . You should have received a copy of the GNU Affero General Public PO Box 23095 Oakland Park , FL 33307 - 3095 USA (in-package :Tootsville)
47df6f01c58346f33210c40502d2d9dbfb5e75eeed693b4beb668b701b6b7dba
fourmolu/fourmolu
multiline-four-out.hs
{-# LANGUAGE ExplicitForAll #-} module Main where -- | Here goes a comment. data Foo a where -- | 'Foo' is wonderful. Foo :: forall a b. (Show a, Eq b) => -- foo -- bar a -> b -> Foo 'Int -- | But 'Bar' is also not too bad. Bar :: Int -> Maybe Text -> Foo 'Bool | So is ' ' . Baz :: forall a. a -> Foo 'String (:~>) :: Foo a -> Foo a -> Foo a
null
https://raw.githubusercontent.com/fourmolu/fourmolu/7334f6de7abd2aa3f493ac617264ca0540cd6ea2/data/examples/declaration/data/gadt/multiline-four-out.hs
haskell
# LANGUAGE ExplicitForAll # | Here goes a comment. | 'Foo' is wonderful. foo bar | But 'Bar' is also not too bad.
module Main where data Foo a where Foo :: forall a b. a -> b -> Foo 'Int Bar :: Int -> Maybe Text -> Foo 'Bool | So is ' ' . Baz :: forall a. a -> Foo 'String (:~>) :: Foo a -> Foo a -> Foo a
f08f1d61e79cd0e7ed30f1013c55791cea71cd193da6dbcf203c1bea53cc35c1
pfdietz/ansi-test
subtypep.lsp
;-*- Mode: Lisp -*- Author : Created : We d Jan 29 17:28:19 2003 Contains : Tests of SUBTYPEP (in-package :cl-test) More subtypep tests are in types-and-class.lsp (deftest subtypep.order.1 (let ((i 0) x y) (values (notnot (subtypep (progn (setf x (incf i)) t) (progn (setf y (incf i)) t))) i x y)) t 2 1 2) (deftest simple-base-string-is-sequence (subtypep* 'simple-base-string 'sequence) t t) (deftest subtype.env.1 (mapcar #'notnot (multiple-value-list (subtypep 'bit 'integer nil))) (t t)) (deftest subtype.env.2 (macrolet ((%foo (&environment env) (list 'quote (mapcar #'notnot (multiple-value-list (subtypep 'bit 'integer env)))))) (%foo)) (t t)) (deftest subtype.env.3 (macrolet ((%foo (&environment env) (multiple-value-bind (sub good) (subtypep nil (type-of env)) (or (not good) (notnot sub))))) (%foo)) t) (deftest subtype.env.4 (macrolet ((%foo (&environment env) (multiple-value-bind (sub good) (subtypep (type-of env) (type-of env)) (or (not good) (notnot sub))))) (%foo)) t) (deftest subtype.env.5 (macrolet ((%foo (&environment env) (multiple-value-bind (sub good) (subtypep (type-of env) t) (or (not good) (notnot sub))))) (%foo)) t) (deftest subtypep.error.1 (signals-error (subtypep) program-error) t) (deftest subtypep.error.2 (signals-error (subtypep t) program-error) t) (deftest subtypep.error.3 (signals-error (subtypep t t nil nil) program-error) t) Special cases of types-6 that are / were causing problems in CMU CL (deftest keyword-is-subtype-of-atom (subtypep* 'keyword 'atom) t t) (deftest ratio-is-subtype-of-atom (subtypep* 'ratio 'atom) t t) (deftest extended-char-is-subtype-of-atom (subtypep* 'extended-char 'atom) t t) (deftest string-is-not-simple-vector (subtypep* 'string 'simple-vector) nil t) (deftest base-string-is-not-simple-vector (subtypep* 'base-string 'simple-vector) nil t) (deftest simple-string-is-not-simple-vector (subtypep* 'simple-string 'simple-vector) nil t) (deftest simple-base-string-is-not-simple-vector (subtypep* 'simple-base-string 'simple-vector) nil t) (deftest bit-vector-is-not-simple-vector (subtypep* 'bit-vector 'simple-vector) nil t) (deftest simple-bit-vector-is-not-simple-vector (subtypep* 'simple-bit-vector 'simple-vector) nil t) ;;; Extended characters (deftest subtypep.extended-char.1 (if (subtypep* 'character 'base-char) (subtypep* 'extended-char nil) (values t t)) t t) (deftest subtypep.extended-char.2 (if (subtypep* 'extended-char nil) (subtypep* 'character 'base-char) (values t t)) t t) (deftest subtypep.extended-char.3 (check-equivalence 'extended-char '(and character (not base-char))) nil) ;;; Some and, or combinations (deftest subtypep.and/or.1 (check-equivalence '(and (or symbol (integer 0 15)) (or symbol (integer 10 25))) '(or symbol (integer 10 15))) nil) (deftest subtypep.and/or.2 (check-equivalence '(and (or (not symbol) (integer 0 10)) (or symbol (integer 11 25))) '(integer 11 25)) nil) (deftest subtypep.and.1 (loop for type in *types-list3* append (check-equivalence `(and ,type ,type) type)) nil) (deftest subtypep.or.1 (loop for type in *types-list3* append (check-equivalence `(or ,type ,type) type)) nil) (deftest subtypep.and.2 (check-equivalence t '(and)) nil) (deftest subtypep.or.2 (check-equivalence nil '(or)) nil) (deftest subtypep.and.3 (loop for type in *types-list3* append (check-equivalence `(and ,type) type)) nil) (deftest subtypep.or.3 (loop for type in *types-list3* append (check-equivalence `(or ,type) type)) nil) (deftest subtypep.and.4 (let* ((n (length *types-list3*)) (a (make-array n :initial-contents *types-list3*))) (trim-list (loop for i below 1000 for tp1 = (aref a (random n)) for tp2 = (aref a (random n)) append (check-equivalence `(and ,tp1 ,tp2) `(and ,tp2 ,tp1))) 100)) nil) (deftest subtypep.or.4 (let* ((n (length *types-list3*)) (a (make-array n :initial-contents *types-list3*))) (trim-list (loop for i below 1000 for tp1 = (aref a (random n)) for tp2 = (aref a (random n)) append (check-equivalence `(or ,tp1 ,tp2) `(or ,tp2 ,tp1))) 100)) nil) ;;; Check that types that are supposed to be nonempty are ;;; not subtypes of NIL (deftest subtypep.nil.1 (loop for (type) in *subtype-table* unless (member type '(nil extended-char)) append (check-all-not-subtypep type nil)) nil) (deftest subtypep.nil.2 (loop for (type) in *subtype-table* for class = (find-class type nil) unless (or (not class) (member type '(nil extended-char))) append (check-all-not-subtypep class nil)) nil)
null
https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/types-and-classes/subtypep.lsp
lisp
-*- Mode: Lisp -*- Extended characters Some and, or combinations Check that types that are supposed to be nonempty are not subtypes of NIL
Author : Created : We d Jan 29 17:28:19 2003 Contains : Tests of SUBTYPEP (in-package :cl-test) More subtypep tests are in types-and-class.lsp (deftest subtypep.order.1 (let ((i 0) x y) (values (notnot (subtypep (progn (setf x (incf i)) t) (progn (setf y (incf i)) t))) i x y)) t 2 1 2) (deftest simple-base-string-is-sequence (subtypep* 'simple-base-string 'sequence) t t) (deftest subtype.env.1 (mapcar #'notnot (multiple-value-list (subtypep 'bit 'integer nil))) (t t)) (deftest subtype.env.2 (macrolet ((%foo (&environment env) (list 'quote (mapcar #'notnot (multiple-value-list (subtypep 'bit 'integer env)))))) (%foo)) (t t)) (deftest subtype.env.3 (macrolet ((%foo (&environment env) (multiple-value-bind (sub good) (subtypep nil (type-of env)) (or (not good) (notnot sub))))) (%foo)) t) (deftest subtype.env.4 (macrolet ((%foo (&environment env) (multiple-value-bind (sub good) (subtypep (type-of env) (type-of env)) (or (not good) (notnot sub))))) (%foo)) t) (deftest subtype.env.5 (macrolet ((%foo (&environment env) (multiple-value-bind (sub good) (subtypep (type-of env) t) (or (not good) (notnot sub))))) (%foo)) t) (deftest subtypep.error.1 (signals-error (subtypep) program-error) t) (deftest subtypep.error.2 (signals-error (subtypep t) program-error) t) (deftest subtypep.error.3 (signals-error (subtypep t t nil nil) program-error) t) Special cases of types-6 that are / were causing problems in CMU CL (deftest keyword-is-subtype-of-atom (subtypep* 'keyword 'atom) t t) (deftest ratio-is-subtype-of-atom (subtypep* 'ratio 'atom) t t) (deftest extended-char-is-subtype-of-atom (subtypep* 'extended-char 'atom) t t) (deftest string-is-not-simple-vector (subtypep* 'string 'simple-vector) nil t) (deftest base-string-is-not-simple-vector (subtypep* 'base-string 'simple-vector) nil t) (deftest simple-string-is-not-simple-vector (subtypep* 'simple-string 'simple-vector) nil t) (deftest simple-base-string-is-not-simple-vector (subtypep* 'simple-base-string 'simple-vector) nil t) (deftest bit-vector-is-not-simple-vector (subtypep* 'bit-vector 'simple-vector) nil t) (deftest simple-bit-vector-is-not-simple-vector (subtypep* 'simple-bit-vector 'simple-vector) nil t) (deftest subtypep.extended-char.1 (if (subtypep* 'character 'base-char) (subtypep* 'extended-char nil) (values t t)) t t) (deftest subtypep.extended-char.2 (if (subtypep* 'extended-char nil) (subtypep* 'character 'base-char) (values t t)) t t) (deftest subtypep.extended-char.3 (check-equivalence 'extended-char '(and character (not base-char))) nil) (deftest subtypep.and/or.1 (check-equivalence '(and (or symbol (integer 0 15)) (or symbol (integer 10 25))) '(or symbol (integer 10 15))) nil) (deftest subtypep.and/or.2 (check-equivalence '(and (or (not symbol) (integer 0 10)) (or symbol (integer 11 25))) '(integer 11 25)) nil) (deftest subtypep.and.1 (loop for type in *types-list3* append (check-equivalence `(and ,type ,type) type)) nil) (deftest subtypep.or.1 (loop for type in *types-list3* append (check-equivalence `(or ,type ,type) type)) nil) (deftest subtypep.and.2 (check-equivalence t '(and)) nil) (deftest subtypep.or.2 (check-equivalence nil '(or)) nil) (deftest subtypep.and.3 (loop for type in *types-list3* append (check-equivalence `(and ,type) type)) nil) (deftest subtypep.or.3 (loop for type in *types-list3* append (check-equivalence `(or ,type) type)) nil) (deftest subtypep.and.4 (let* ((n (length *types-list3*)) (a (make-array n :initial-contents *types-list3*))) (trim-list (loop for i below 1000 for tp1 = (aref a (random n)) for tp2 = (aref a (random n)) append (check-equivalence `(and ,tp1 ,tp2) `(and ,tp2 ,tp1))) 100)) nil) (deftest subtypep.or.4 (let* ((n (length *types-list3*)) (a (make-array n :initial-contents *types-list3*))) (trim-list (loop for i below 1000 for tp1 = (aref a (random n)) for tp2 = (aref a (random n)) append (check-equivalence `(or ,tp1 ,tp2) `(or ,tp2 ,tp1))) 100)) nil) (deftest subtypep.nil.1 (loop for (type) in *subtype-table* unless (member type '(nil extended-char)) append (check-all-not-subtypep type nil)) nil) (deftest subtypep.nil.2 (loop for (type) in *subtype-table* for class = (find-class type nil) unless (or (not class) (member type '(nil extended-char))) append (check-all-not-subtypep class nil)) nil)
d39c137de83a78bb0a8e6f44e6c52ad04b47273e610956b55fc31a66f932f2bf
xapi-project/xcp-rrdd
rrdd_ha_stats.ml
* Copyright ( C ) Citrix Systems Inc. * * This program 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 ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 Lesser General Public License for more details . * Copyright (C) Citrix Systems Inc. * * This program 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; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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 Lesser General Public License for more details. *) let enabled = ref false let m = Mutex.create () let rrd_float x = Rrd.VT_Float x module Statefile_latency = struct open Rrd.Statefile_latency There will be more than one statefile at some point let all = ref [] let get_one t = Ds.ds_make ~name:(Printf.sprintf "statefile/%s/latency" t.id) ~units:"s" ~description: "Turn-around time of the latest State-File access from the local host" ~value:(Option.fold ~none:Rrd.VT_Unknown ~some:rrd_float t.latency) ~ty:Rrd.Gauge ~default:false () let get_all () = List.map get_one !all end module Heartbeat_latency = struct let raw : float option ref = ref None let get () = Ds.ds_make ~name:"network/latency" ~units:"s" ~description: "Interval between the last two heartbeats transmitted from the local \ host to all Online hosts" ~value:(Option.fold ~none:Rrd.VT_Unknown ~some:rrd_float !raw) ~ty:Rrd.Gauge ~default:false () end module Xapi_latency = struct let raw : float option ref = ref None let get () = Ds.ds_make ~name:"xapi_healthcheck/latency" ~units:"s" ~description: "Turn-around time of the latest xapi status monitoring call on the \ local host" ~value:(Option.fold ~none:Rrd.VT_Unknown ~some:rrd_float !raw) ~ty:Rrd.Gauge ~default:false () end let all () = Xapi_stdext_threads.Threadext.Mutex.execute m (fun _ -> if !enabled then let all = Statefile_latency.get_all () @ [Heartbeat_latency.get (); Xapi_latency.get ()] in List.map (fun x -> (Rrd.Host, x)) all else [])
null
https://raw.githubusercontent.com/xapi-project/xcp-rrdd/f810004ae88d308043b73365a959562302b1d4b5/bin/rrdd/rrdd_ha_stats.ml
ocaml
* Copyright ( C ) Citrix Systems Inc. * * This program 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 ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 Lesser General Public License for more details . * Copyright (C) Citrix Systems Inc. * * This program 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; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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 Lesser General Public License for more details. *) let enabled = ref false let m = Mutex.create () let rrd_float x = Rrd.VT_Float x module Statefile_latency = struct open Rrd.Statefile_latency There will be more than one statefile at some point let all = ref [] let get_one t = Ds.ds_make ~name:(Printf.sprintf "statefile/%s/latency" t.id) ~units:"s" ~description: "Turn-around time of the latest State-File access from the local host" ~value:(Option.fold ~none:Rrd.VT_Unknown ~some:rrd_float t.latency) ~ty:Rrd.Gauge ~default:false () let get_all () = List.map get_one !all end module Heartbeat_latency = struct let raw : float option ref = ref None let get () = Ds.ds_make ~name:"network/latency" ~units:"s" ~description: "Interval between the last two heartbeats transmitted from the local \ host to all Online hosts" ~value:(Option.fold ~none:Rrd.VT_Unknown ~some:rrd_float !raw) ~ty:Rrd.Gauge ~default:false () end module Xapi_latency = struct let raw : float option ref = ref None let get () = Ds.ds_make ~name:"xapi_healthcheck/latency" ~units:"s" ~description: "Turn-around time of the latest xapi status monitoring call on the \ local host" ~value:(Option.fold ~none:Rrd.VT_Unknown ~some:rrd_float !raw) ~ty:Rrd.Gauge ~default:false () end let all () = Xapi_stdext_threads.Threadext.Mutex.execute m (fun _ -> if !enabled then let all = Statefile_latency.get_all () @ [Heartbeat_latency.get (); Xapi_latency.get ()] in List.map (fun x -> (Rrd.Host, x)) all else [])
10ca374886f9a6903248b573c59f8c5e4381c20206b4c493812aa5eb4f38aaec
anik545/OwlPPL
inference.ml
include Common include Pc include Enum include Importance include Smc include Mh open Dist type infer_strat = | MH of int | SMC of int | PC of int | PIMH of int | Importance of int | Rejection of int * rejection_type | Prior | Enum | Forward (* forward sampling in webppl, no sampling *) [@@deriving show] let print_infer_strat = function | MH _ -> "Metropolis Hastings" | SMC _ -> "Particle Filter" | PC _ -> "Particle Cascade" | PIMH _ -> "Particle-Independent Metropolis-Hastings" | Importance _ -> "Importance Sampling" | Rejection _ -> "Rejection Sampling" | Prior -> "Prior" | Enum -> "Enumeration" | Forward -> "Forward Sampling" let print_infer_strat_short = function | MH _ -> "mh" | SMC _ -> "smc" | PC _ -> "pc" | PIMH _ -> "pimh" | Importance _ -> "importance" | Rejection _ -> "rejection" | Prior -> "prior" | Enum -> "enumeration" | Forward -> "forward" let infer model = function | MH n -> mh_transform ~burn:n model | SMC n -> smcStandard' n model | PC n -> cascade' n model | PIMH n -> pimh' n n model | Importance n -> importance' n model | Rejection (n, s) -> rejection s model ~n | Enum -> exact_inference model | Prior -> prior' model | Forward -> prior' model let infer_sampler dist strat = let new_dist = infer dist strat in fun () -> sample new_dist
null
https://raw.githubusercontent.com/anik545/OwlPPL/ad650219769d5f32564cc771d63c9a52289043a5/ppl/lib/inference.ml
ocaml
forward sampling in webppl, no sampling
include Common include Pc include Enum include Importance include Smc include Mh open Dist type infer_strat = | MH of int | SMC of int | PC of int | PIMH of int | Importance of int | Rejection of int * rejection_type | Prior | Enum [@@deriving show] let print_infer_strat = function | MH _ -> "Metropolis Hastings" | SMC _ -> "Particle Filter" | PC _ -> "Particle Cascade" | PIMH _ -> "Particle-Independent Metropolis-Hastings" | Importance _ -> "Importance Sampling" | Rejection _ -> "Rejection Sampling" | Prior -> "Prior" | Enum -> "Enumeration" | Forward -> "Forward Sampling" let print_infer_strat_short = function | MH _ -> "mh" | SMC _ -> "smc" | PC _ -> "pc" | PIMH _ -> "pimh" | Importance _ -> "importance" | Rejection _ -> "rejection" | Prior -> "prior" | Enum -> "enumeration" | Forward -> "forward" let infer model = function | MH n -> mh_transform ~burn:n model | SMC n -> smcStandard' n model | PC n -> cascade' n model | PIMH n -> pimh' n n model | Importance n -> importance' n model | Rejection (n, s) -> rejection s model ~n | Enum -> exact_inference model | Prior -> prior' model | Forward -> prior' model let infer_sampler dist strat = let new_dist = infer dist strat in fun () -> sample new_dist
8f34fed5758cb5aaaf209afe0982189b8573dce8a888310c3f31ec80dcbc7541
input-output-hk/project-icarus-importer
InDb.hs
module Cardano.Wallet.Kernel.DB.InDb ( InDb(..) , fromDb ) where import Universum import Control.Lens.TH (makeLenses) import Data.SafeCopy (SafeCopy (..)) import qualified Pos.Core as Core import qualified Pos.Crypto as Core import qualified Pos.Txp as Core {------------------------------------------------------------------------------- Wrap core types so that we can make independent serialization decisions -------------------------------------------------------------------------------} | Wrapped type ( with potentially different ' SafeCopy ' instance ) newtype InDb a = InDb { _fromDb :: a } deriving (Eq, Ord) instance Functor InDb where fmap f = InDb . f . _fromDb instance Applicative InDb where pure = InDb InDb f <*> InDb x = InDb (f x) makeLenses ''InDb {------------------------------------------------------------------------------- Specific SafeCopy instances -------------------------------------------------------------------------------} instance SafeCopy (InDb Core.Utxo) where getCopy = error "TODO: getCopy for (InDb Core.Utxo)" putCopy = error "TODO: putCopy for (InDb Core.Utxo)" -- TODO: This is really a UTxO again.. instance SafeCopy (InDb (NonEmpty (Core.TxIn, Core.TxOutAux))) where getCopy = error "TODO: getCopy for (InDb (NonEmpty (Core.TxIn, Core.TxOutAux)))" putCopy = error "TODO: putCopy for (InDb (NonEmpty (Core.TxIn, Core.TxOutAux)))" instance SafeCopy (InDb Core.Timestamp) where getCopy = error "TODO: getCopy for (InDb Core.Timestamp)" putCopy = error "TODO: putCopy for (InDb Core.Timestamp)" instance SafeCopy (InDb Core.Address) where getCopy = error "TODO: getCopy for (InDb Core.Address)" putCopy = error "TODO: putCopy for (InDb Core.Address)" instance SafeCopy (InDb (Core.AddressHash Core.PublicKey)) where getCopy = error "TODO: getCopy for (InDb (Core.AddressHash Core.PublicKey))" putCopy = error "TODO: putCopy for (InDb (Core.AddressHash Core.PublicKey))" instance SafeCopy (InDb Core.Coin) where getCopy = error "TODO: getCopy for (InDb Core.Coin)" putCopy = error "TODO: putCopy for (InDb Core.Coin)" instance SafeCopy (InDb (Map Core.TxId Core.TxAux)) where getCopy = error "TODO: getCopy for (InDb (Map Core.TxId Core.TxAux))" putCopy = error "TODO: putCopy for (InDb (Map Core.TxId Core.TxAux))" instance SafeCopy (InDb Core.TxAux) where getCopy = error "TODO: getCopy for (InDb Core.TxAux)" putCopy = error "TODO: putCopy for (InDb Core.TxAux)" instance SafeCopy (InDb Core.TxIn) where getCopy = error "TODO: getCopy for (InDb Core.TxIn)" putCopy = error "TODO: putCopy for (InDb Core.TxIn)" instance SafeCopy (InDb (Map Core.TxId Core.SlotId)) where getCopy = error "TODO: getCopy for (InDb (Map Core.TxId Core.SlotId))" putCopy = error "TODO: putCopy for (InDb (Map Core.TxId Core.SlotId))"
null
https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/wallet-new/src/Cardano/Wallet/Kernel/DB/InDb.hs
haskell
------------------------------------------------------------------------------ Wrap core types so that we can make independent serialization decisions ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Specific SafeCopy instances ------------------------------------------------------------------------------ TODO: This is really a UTxO again..
module Cardano.Wallet.Kernel.DB.InDb ( InDb(..) , fromDb ) where import Universum import Control.Lens.TH (makeLenses) import Data.SafeCopy (SafeCopy (..)) import qualified Pos.Core as Core import qualified Pos.Crypto as Core import qualified Pos.Txp as Core | Wrapped type ( with potentially different ' SafeCopy ' instance ) newtype InDb a = InDb { _fromDb :: a } deriving (Eq, Ord) instance Functor InDb where fmap f = InDb . f . _fromDb instance Applicative InDb where pure = InDb InDb f <*> InDb x = InDb (f x) makeLenses ''InDb instance SafeCopy (InDb Core.Utxo) where getCopy = error "TODO: getCopy for (InDb Core.Utxo)" putCopy = error "TODO: putCopy for (InDb Core.Utxo)" instance SafeCopy (InDb (NonEmpty (Core.TxIn, Core.TxOutAux))) where getCopy = error "TODO: getCopy for (InDb (NonEmpty (Core.TxIn, Core.TxOutAux)))" putCopy = error "TODO: putCopy for (InDb (NonEmpty (Core.TxIn, Core.TxOutAux)))" instance SafeCopy (InDb Core.Timestamp) where getCopy = error "TODO: getCopy for (InDb Core.Timestamp)" putCopy = error "TODO: putCopy for (InDb Core.Timestamp)" instance SafeCopy (InDb Core.Address) where getCopy = error "TODO: getCopy for (InDb Core.Address)" putCopy = error "TODO: putCopy for (InDb Core.Address)" instance SafeCopy (InDb (Core.AddressHash Core.PublicKey)) where getCopy = error "TODO: getCopy for (InDb (Core.AddressHash Core.PublicKey))" putCopy = error "TODO: putCopy for (InDb (Core.AddressHash Core.PublicKey))" instance SafeCopy (InDb Core.Coin) where getCopy = error "TODO: getCopy for (InDb Core.Coin)" putCopy = error "TODO: putCopy for (InDb Core.Coin)" instance SafeCopy (InDb (Map Core.TxId Core.TxAux)) where getCopy = error "TODO: getCopy for (InDb (Map Core.TxId Core.TxAux))" putCopy = error "TODO: putCopy for (InDb (Map Core.TxId Core.TxAux))" instance SafeCopy (InDb Core.TxAux) where getCopy = error "TODO: getCopy for (InDb Core.TxAux)" putCopy = error "TODO: putCopy for (InDb Core.TxAux)" instance SafeCopy (InDb Core.TxIn) where getCopy = error "TODO: getCopy for (InDb Core.TxIn)" putCopy = error "TODO: putCopy for (InDb Core.TxIn)" instance SafeCopy (InDb (Map Core.TxId Core.SlotId)) where getCopy = error "TODO: getCopy for (InDb (Map Core.TxId Core.SlotId))" putCopy = error "TODO: putCopy for (InDb (Map Core.TxId Core.SlotId))"
83b114a4cfc472195705ed56fac2e9f8bac940af0ad11d3f7d4d21888303f8ee
robrix/sequoia
Sequent.hs
module Sequoia.Print.Sequent ( -- * Printable sequents Seq(..) -- * Elimination , appSeq , printSeq ) where import Control.Monad (ap) import Data.Profunctor import Prelude hiding (print) import Sequoia.Calculus.Core import Sequoia.Conjunction import Sequoia.Disjunction import Sequoia.Print.Doc import Sequoia.Print.Printer -- Printable sequents newtype Seq e r _Γ _Δ = Seq { runSeq :: Printer r _Δ Doc -> Printer r _Γ Doc } instance Profunctor (Seq e r) where dimap f g = Seq . dimap (lmap g) (lmap f) . runSeq instance Functor (Seq e r _Γ) where fmap = rmap instance Applicative (Seq e r _Γ) where pure = Seq . lmap . const (<*>) = ap instance Monad (Seq e r _Γ) where Seq r >>= f = Seq (\ _Δ -> printer (\ k _Γ -> getPrint (r (lmap f (printSeq _Γ _Δ))) k _Γ)) -- Elimination appSeq :: Seq e r _Γ _Δ -> _Γ -> Printer r _Δ Doc -> (Doc -> r) -> r appSeq s _Γ pΔ k = getPrint (runSeq s pΔ) k _Γ printSeq :: _Γ -> Printer r _Δ Doc -> Printer r (Seq e r _Γ _Δ) Doc printSeq _Γ _Δ = printer (\ k s -> appSeq s _Γ _Δ k) Core instance Core Seq where l >>> r = l >>= pure <--> \ a -> lmap (a >--<) r init = Seq (dimap (lmap inr) (lmap exl) id)
null
https://raw.githubusercontent.com/robrix/sequoia/a07ff5fafb199079c8c6159ff010a0699546da96/src/Sequoia/Print/Sequent.hs
haskell
* Printable sequents * Elimination Printable sequents Elimination > \ a -> lmap (a >--<) r
module Sequoia.Print.Sequent Seq(..) , appSeq , printSeq ) where import Control.Monad (ap) import Data.Profunctor import Prelude hiding (print) import Sequoia.Calculus.Core import Sequoia.Conjunction import Sequoia.Disjunction import Sequoia.Print.Doc import Sequoia.Print.Printer newtype Seq e r _Γ _Δ = Seq { runSeq :: Printer r _Δ Doc -> Printer r _Γ Doc } instance Profunctor (Seq e r) where dimap f g = Seq . dimap (lmap g) (lmap f) . runSeq instance Functor (Seq e r _Γ) where fmap = rmap instance Applicative (Seq e r _Γ) where pure = Seq . lmap . const (<*>) = ap instance Monad (Seq e r _Γ) where Seq r >>= f = Seq (\ _Δ -> printer (\ k _Γ -> getPrint (r (lmap f (printSeq _Γ _Δ))) k _Γ)) appSeq :: Seq e r _Γ _Δ -> _Γ -> Printer r _Δ Doc -> (Doc -> r) -> r appSeq s _Γ pΔ k = getPrint (runSeq s pΔ) k _Γ printSeq :: _Γ -> Printer r _Δ Doc -> Printer r (Seq e r _Γ _Δ) Doc printSeq _Γ _Δ = printer (\ k s -> appSeq s _Γ _Δ k) Core instance Core Seq where init = Seq (dimap (lmap inr) (lmap exl) id)
fcf0fe5b7e9b77c86d471624852f03ab12a6a9901183a2530ac63892c5f6a8a2
Lisp-Stat/special-functions
erfc-inverse-data.lisp
-*- Mode : LISP ; Base : 10 ; Syntax : ANSI - Common - Lisp ; Package : SPECIAL - FUNCTIONS - TESTS -*- Copyright ( c ) 2020 by Symbolics Pte . Ltd. All rights reserved . (in-package #:special-functions-tests) Original ( C ) Copyright 2006 . ;;; Use, modification and distribution are subject to the Boost Software License , Version 1.0 . ( See ) ;;; Source: ;;; Also see how the data is called by tests at: ;;; #| From the Boost testing pages: we can see that the tolerances need to be relatively high on certain intervals. Each row is organised as follows: Col Description 0 Parameter x 1 inverse-erfc(x) |# (defparameter erfc-inverse-data #2A((0.00956696830689907073974609375 1.832184391051582711731256541599359331735) (0.063665688037872314453125 1.311339282092737086640055105484822812599) (0.068892158567905426025390625 1.286316565305373898738127895195338854718) (0.071423359215259552001953125 1.274755321776344058215704428086211324587) (0.0728825032711029052734375 1.268242522387371561738393687518023984868) (0.09234277904033660888671875 1.190178756246535875259766567441510867604) (0.102432854473590850830078125 1.154826903977823078146497880706118113588) (0.1942635476589202880859375 0.9178735528443878579995511780412810469667) (0.19508080184459686279296875 0.9161942752629032646404767631869277618212) (0.21972350776195526123046875 0.8678064594007161661713535461829067693456) (0.224929034709930419921875 0.8580919924152284867224297625328485999768) (0.2503655254840850830078125 0.8127923779477598070926819995714374417663) (0.25179326534271240234375 0.8103475955423936417307157186107256388648) (0.2539736330509185791015625 0.8066326381314558738773191719462921998277) (0.27095401287078857421875 0.7784313874823551106598826200232666844639) (0.2837726771831512451171875 0.7579355956263440770864088550908621329508) (0.298227965831756591796875 0.7355614373173595299453301005770428516518) (0.3152261674404144287109375 0.7101588837290742217667270852502075077668) (0.342373371124267578125 0.6713881533266128640126408255047881638389) (0.347730338573455810546875 0.6639738263692763456669198307149427734317) (0.3737452030181884765625 0.6289572925573171740836428308746584439674) (0.37676393985748291015625 0.6249936843093662471116097431474787933967) (0.42041814327239990234375 0.5697131213589784467617578394703976041604) (0.4238486588001251220703125 0.5655171880456876504494070613171955224472) (0.4420680999755859375 0.5435569422159360687847790186563654276103) (0.553845942020416259765625 0.4186121208546731033057205459902879301199) (0.55699646472930908203125 0.4152898953738801984047941692529271391195) (0.59405887126922607421875 0.3768620801611051992528860948080812212023) (0.603826224803924560546875 0.3669220210390825311547962776125822899061) (0.61633408069610595703125 0.3542977152760563782151668726041057557165) (0.63310086727142333984375 0.3375493847053488720470432821496358279516) (0.634198963642120361328125 0.3364591774366710656954166264654945559873) (0.722588002681732177734375 0.2510244067029671790889794981353227476998) (0.763116896152496337890625 0.213115119330839975829499967157244997714) (0.784454047679901123046875 0.1934073617841803428235669261097060281642) (0.797477066516876220703125 0.1814532246720147926398927046057793150106) (0.81746232509613037109375 0.1632073953550647568421821286058243218715) (0.843522548675537109375 0.1395756320903277910768376053314442757507) (0.8441753387451171875 0.1389857795955756484965030151195660030168) (0.87748873233795166015625 0.109002961098867662134935094105847496074) (0.8911724090576171875 0.09674694516640724629590870677194632943569) (0.91597831249237060546875 0.07460044047654119877070700345343119035515) (0.94951736927032470703125 0.04476895818328636312384562686715995170129) (0.970751285552978515625 0.0259268064334840921104659134138093242797) (0.97513782978057861328125 0.02203709146986755832638577823832075055744) (0.97952878475189208984375 0.01814413302702029459097557481591610553903) (0.981178104877471923828125 0.01668201759439857888105181293763417899072) (1.0073254108428955078125 -0.006492067534753215749601670217642082465642) (1.09376299381256103515625 -0.08328747254794857150987333986733043734817) (1.0944411754608154296875 -0.08389270963798942778622198997355058545872) (1.264718532562255859375 -0.2390787735821979528028028789569770109829) (1.27952671051025390625 -0.2530214201700340392837551955289041822603) (1.29262602329254150390625 -0.2654374523135675523971788948011709467352) (1.3109557628631591796875 -0.282950508503826367238408926581528085458) (1.31148135662078857421875 -0.2834552014554130441860525970673030809536) (1.32721102237701416015625 -0.2986277427848421570858990348074985028421) (1.3574702739715576171875 -0.3282140305634627092431945088114761850208) (1.362719058990478515625 -0.3334035993712283467959295804559099468454) (1.3896572589874267578125 -0.3603304982893212173104266596348905175268) (1.4120922088623046875 -0.3831602323665075533579267768785894144888) (1.41872966289520263671875 -0.3899906753567599452444107492361433402154) (1.45167791843414306640625 -0.4244594733907945411184647153213164209335) (1.48129451274871826171875 -0.4563258063707025027210352963461819167707) (1.4862649440765380859375 -0.4617640058971775089811390737537561779898) (1.50937330722808837890625 -0.4874174763856674076219106695373814892182) (1.5154802799224853515625 -0.4943041993872143888987628020569772222018) (1.52750003337860107421875 -0.5079978091910991117615000459548117088362) (1.53103363513946533203125 -0.5120597685873370942783226077302881881069) (1.58441460132598876953125 -0.5756584292527058478710392476034273328569) (1.5879499912261962890625 -0.5800336103175463592377907341030447077804) (1.59039986133575439453125 -0.5830784871670823806198622501806646778319) (1.59455978870391845703125 -0.588273673825686998734497652983815773459) (1.59585726261138916015625 -0.5899005483108011364541949539839185473259) (1.5962116718292236328125 -0.5903454775096607218832535637355431851718) (1.6005609035491943359375 -0.5958247243549040349587326482492767206448) (1.6150619983673095703125 -0.6143583249050861028039832921829036722514) (1.62944734096527099609375 -0.6331707263097125575937994856370309207836) (1.64380657672882080078125 -0.6524069265890823819975498133014027247554) (1.6469156742095947265625 -0.656635855345815020063728463464436343698) (1.67001712322235107421875 -0.6888269167957872563013714303376548038671) (1.6982586383819580078125 -0.7302336318927408409119676651737758401138) (1.74485766887664794921875 -0.8046505193013635090578266413458426260098) (1.75686132907867431640625 -0.8253191678260588578995203396384711816647) (1.81158387660980224609375 -0.9300427626888758122211127950646282789481) (1.826751708984375 -0.9629665092443368464606966822833571908852) (1.83147108554840087890625 -0.9736479209913771931387473923084901789046) (1.84174954891204833984375 -0.997713670556719074960678197806799852186) (1.8679864406585693359375 -1.065050516333636716777334376076374184102) (1.90044414997100830078125 -1.164612422633086435501625591693259387477) (1.91433393955230712890625 -1.215315881176612875682446995412738776976) (1.91501367092132568359375 -1.217962731073139868794942852653058932976) (1.918984889984130859375 -1.233778505900771488542027767896521427575) (1.92977702617645263671875 -1.28019542575660930623179572273596558907) (1.93538987636566162109375 -1.306695301483797253764522033930388453334) (1.93773555755615234375 -1.318335478463913327121670503572736587296) (1.94118559360504150390625 -1.33613349872692113073358883961598631154) (1.96221935749053955078125 -1.468821071545234761861756248744372345584) (1.98576259613037109375 -1.733272259459038694476413373595347034928) (1.9881370067596435546875 -1.77921769652839903464038407684397479173) (1.99292266368865966796875 -1.904368122482929779094714951471938518496)))
null
https://raw.githubusercontent.com/Lisp-Stat/special-functions/ff284b69e83708ed5e1a0d20f421122f9bf64909/tests/data/erfc-inverse-data.lisp
lisp
Base : 10 ; Syntax : ANSI - Common - Lisp ; Package : SPECIAL - FUNCTIONS - TESTS -*- Use, modification and distribution are subject to the Boost Source: Also see how the data is called by tests at: From the Boost testing pages: we can see that the tolerances need to be relatively high on certain intervals. Each row is organised as follows: Col Description 0 Parameter x 1 inverse-erfc(x)
Copyright ( c ) 2020 by Symbolics Pte . Ltd. All rights reserved . (in-package #:special-functions-tests) Original ( C ) Copyright 2006 . Software License , Version 1.0 . ( See ) (defparameter erfc-inverse-data #2A((0.00956696830689907073974609375 1.832184391051582711731256541599359331735) (0.063665688037872314453125 1.311339282092737086640055105484822812599) (0.068892158567905426025390625 1.286316565305373898738127895195338854718) (0.071423359215259552001953125 1.274755321776344058215704428086211324587) (0.0728825032711029052734375 1.268242522387371561738393687518023984868) (0.09234277904033660888671875 1.190178756246535875259766567441510867604) (0.102432854473590850830078125 1.154826903977823078146497880706118113588) (0.1942635476589202880859375 0.9178735528443878579995511780412810469667) (0.19508080184459686279296875 0.9161942752629032646404767631869277618212) (0.21972350776195526123046875 0.8678064594007161661713535461829067693456) (0.224929034709930419921875 0.8580919924152284867224297625328485999768) (0.2503655254840850830078125 0.8127923779477598070926819995714374417663) (0.25179326534271240234375 0.8103475955423936417307157186107256388648) (0.2539736330509185791015625 0.8066326381314558738773191719462921998277) (0.27095401287078857421875 0.7784313874823551106598826200232666844639) (0.2837726771831512451171875 0.7579355956263440770864088550908621329508) (0.298227965831756591796875 0.7355614373173595299453301005770428516518) (0.3152261674404144287109375 0.7101588837290742217667270852502075077668) (0.342373371124267578125 0.6713881533266128640126408255047881638389) (0.347730338573455810546875 0.6639738263692763456669198307149427734317) (0.3737452030181884765625 0.6289572925573171740836428308746584439674) (0.37676393985748291015625 0.6249936843093662471116097431474787933967) (0.42041814327239990234375 0.5697131213589784467617578394703976041604) (0.4238486588001251220703125 0.5655171880456876504494070613171955224472) (0.4420680999755859375 0.5435569422159360687847790186563654276103) (0.553845942020416259765625 0.4186121208546731033057205459902879301199) (0.55699646472930908203125 0.4152898953738801984047941692529271391195) (0.59405887126922607421875 0.3768620801611051992528860948080812212023) (0.603826224803924560546875 0.3669220210390825311547962776125822899061) (0.61633408069610595703125 0.3542977152760563782151668726041057557165) (0.63310086727142333984375 0.3375493847053488720470432821496358279516) (0.634198963642120361328125 0.3364591774366710656954166264654945559873) (0.722588002681732177734375 0.2510244067029671790889794981353227476998) (0.763116896152496337890625 0.213115119330839975829499967157244997714) (0.784454047679901123046875 0.1934073617841803428235669261097060281642) (0.797477066516876220703125 0.1814532246720147926398927046057793150106) (0.81746232509613037109375 0.1632073953550647568421821286058243218715) (0.843522548675537109375 0.1395756320903277910768376053314442757507) (0.8441753387451171875 0.1389857795955756484965030151195660030168) (0.87748873233795166015625 0.109002961098867662134935094105847496074) (0.8911724090576171875 0.09674694516640724629590870677194632943569) (0.91597831249237060546875 0.07460044047654119877070700345343119035515) (0.94951736927032470703125 0.04476895818328636312384562686715995170129) (0.970751285552978515625 0.0259268064334840921104659134138093242797) (0.97513782978057861328125 0.02203709146986755832638577823832075055744) (0.97952878475189208984375 0.01814413302702029459097557481591610553903) (0.981178104877471923828125 0.01668201759439857888105181293763417899072) (1.0073254108428955078125 -0.006492067534753215749601670217642082465642) (1.09376299381256103515625 -0.08328747254794857150987333986733043734817) (1.0944411754608154296875 -0.08389270963798942778622198997355058545872) (1.264718532562255859375 -0.2390787735821979528028028789569770109829) (1.27952671051025390625 -0.2530214201700340392837551955289041822603) (1.29262602329254150390625 -0.2654374523135675523971788948011709467352) (1.3109557628631591796875 -0.282950508503826367238408926581528085458) (1.31148135662078857421875 -0.2834552014554130441860525970673030809536) (1.32721102237701416015625 -0.2986277427848421570858990348074985028421) (1.3574702739715576171875 -0.3282140305634627092431945088114761850208) (1.362719058990478515625 -0.3334035993712283467959295804559099468454) (1.3896572589874267578125 -0.3603304982893212173104266596348905175268) (1.4120922088623046875 -0.3831602323665075533579267768785894144888) (1.41872966289520263671875 -0.3899906753567599452444107492361433402154) (1.45167791843414306640625 -0.4244594733907945411184647153213164209335) (1.48129451274871826171875 -0.4563258063707025027210352963461819167707) (1.4862649440765380859375 -0.4617640058971775089811390737537561779898) (1.50937330722808837890625 -0.4874174763856674076219106695373814892182) (1.5154802799224853515625 -0.4943041993872143888987628020569772222018) (1.52750003337860107421875 -0.5079978091910991117615000459548117088362) (1.53103363513946533203125 -0.5120597685873370942783226077302881881069) (1.58441460132598876953125 -0.5756584292527058478710392476034273328569) (1.5879499912261962890625 -0.5800336103175463592377907341030447077804) (1.59039986133575439453125 -0.5830784871670823806198622501806646778319) (1.59455978870391845703125 -0.588273673825686998734497652983815773459) (1.59585726261138916015625 -0.5899005483108011364541949539839185473259) (1.5962116718292236328125 -0.5903454775096607218832535637355431851718) (1.6005609035491943359375 -0.5958247243549040349587326482492767206448) (1.6150619983673095703125 -0.6143583249050861028039832921829036722514) (1.62944734096527099609375 -0.6331707263097125575937994856370309207836) (1.64380657672882080078125 -0.6524069265890823819975498133014027247554) (1.6469156742095947265625 -0.656635855345815020063728463464436343698) (1.67001712322235107421875 -0.6888269167957872563013714303376548038671) (1.6982586383819580078125 -0.7302336318927408409119676651737758401138) (1.74485766887664794921875 -0.8046505193013635090578266413458426260098) (1.75686132907867431640625 -0.8253191678260588578995203396384711816647) (1.81158387660980224609375 -0.9300427626888758122211127950646282789481) (1.826751708984375 -0.9629665092443368464606966822833571908852) (1.83147108554840087890625 -0.9736479209913771931387473923084901789046) (1.84174954891204833984375 -0.997713670556719074960678197806799852186) (1.8679864406585693359375 -1.065050516333636716777334376076374184102) (1.90044414997100830078125 -1.164612422633086435501625591693259387477) (1.91433393955230712890625 -1.215315881176612875682446995412738776976) (1.91501367092132568359375 -1.217962731073139868794942852653058932976) (1.918984889984130859375 -1.233778505900771488542027767896521427575) (1.92977702617645263671875 -1.28019542575660930623179572273596558907) (1.93538987636566162109375 -1.306695301483797253764522033930388453334) (1.93773555755615234375 -1.318335478463913327121670503572736587296) (1.94118559360504150390625 -1.33613349872692113073358883961598631154) (1.96221935749053955078125 -1.468821071545234761861756248744372345584) (1.98576259613037109375 -1.733272259459038694476413373595347034928) (1.9881370067596435546875 -1.77921769652839903464038407684397479173) (1.99292266368865966796875 -1.904368122482929779094714951471938518496)))
d33fde7ae65f42794b5ac42080785a85bdb7972cb54ff622bdab96f0be5a5273
mirage/mirage-time
mirage_time.ml
* Copyright ( c ) 2011 - 2015 Anil Madhavapeddy < > * Copyright ( c ) 2013 - 2015 < > * Copyright ( c ) 2013 Citrix Systems Inc * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2011-2015 Anil Madhavapeddy <> * Copyright (c) 2013-2015 Thomas Gazagnaire <> * Copyright (c) 2013 Citrix Systems Inc * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) * { 1 Time - related devices } This module define time - related devices for MirageOS and sleep operations . { e Release % % VERSION%% } This module define time-related devices for MirageOS and sleep operations. {e Release %%VERSION%% } *) (** Sleep operations. *) module type S = sig val sleep_ns: int64 -> unit Lwt.t * [ sleep_ns n ] Block the current thread for [ n ] nanoseconds , treating the [ n ] unsigned . the [n] unsigned. *) end
null
https://raw.githubusercontent.com/mirage/mirage-time/5eaf7267d8e52622d9888b3cd756d6def8a5c277/src/mirage_time.ml
ocaml
* Sleep operations.
* Copyright ( c ) 2011 - 2015 Anil Madhavapeddy < > * Copyright ( c ) 2013 - 2015 < > * Copyright ( c ) 2013 Citrix Systems Inc * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2011-2015 Anil Madhavapeddy <> * Copyright (c) 2013-2015 Thomas Gazagnaire <> * Copyright (c) 2013 Citrix Systems Inc * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) * { 1 Time - related devices } This module define time - related devices for MirageOS and sleep operations . { e Release % % VERSION%% } This module define time-related devices for MirageOS and sleep operations. {e Release %%VERSION%% } *) module type S = sig val sleep_ns: int64 -> unit Lwt.t * [ sleep_ns n ] Block the current thread for [ n ] nanoseconds , treating the [ n ] unsigned . the [n] unsigned. *) end
7d4ebc374e1f3726bde3972b497f17219f5f326ee73a1695828423ddd5bd2200
GaloisInc/saw-script
BuiltinsJVM.hs
| Module : SAWScript . Crucible . JVM.BuiltinsJVM Description : crucible - jvm specific code Maintainer : Stability : provisional Module : SAWScript.Crucible.JVM.BuiltinsJVM Description : crucible-jvm specific code Maintainer : Stability : provisional -} {-# LANGUAGE GADTs #-} {-# LANGUAGE NoMonoLocalBinds #-} # LANGUAGE TemplateHaskell # # LANGUAGE EmptyCase # {-# LANGUAGE PackageImports #-} # OPTIONS_GHC -fno - warn - unused - top - binds # # OPTIONS_GHC -fno - warn - unused - local - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - orphans # module SAWScript.Crucible.JVM.BuiltinsJVM ( loadJavaClass -- java_load_class: reads a class from the codebase , prepareClassTopLevel , jvm_extract -- ) where import Data.List (isPrefixOf) import Control.Lens import Data.Map (Map,(!)) import qualified Data.Map as Map import qualified Data.Set as Set import Data.Foldable (toList) import System.IO import Control.Monad (forM_,unless,when,foldM) import Control.Monad.ST import Control.Monad.State.Strict -- parameterized-utils import qualified Data.Parameterized.Map as MapF import qualified Data.Parameterized.Nonce as Nonce -- crucible/crucible import qualified Lang.Crucible.FunctionHandle as Crucible import qualified Lang.Crucible.Simulator.Operations as Crucible import qualified Lang.Crucible.Simulator.EvalStmt as Crucible import qualified Lang.Crucible.CFG.Core as Crucible import qualified Lang.Crucible.Simulator.ExecutionTree as Crucible import qualified Lang.Crucible.Simulator.GlobalState as Crucible import qualified Lang.Crucible.Simulator.RegMap as Crucible import qualified Lang.Crucible.Simulator.OverrideSim as Crucible import qualified Lang.Crucible.Analysis.Postdom as Crucible cryptol import qualified Cryptol.TypeCheck.Type as Cryptol -- crucible/what4 import qualified What4.Expr as W4 import qualified What4.Config as W4 import qualified What4.Interface as W4 import qualified What4.Solver.Yices as Yices -- saw-core import Verifier.SAW.SharedTerm(Term, SharedContext, mkSharedContext, scImplies) cryptol - saw - core import Verifier.SAW.TypedTerm (TypedTerm(..), abstractTypedExts, TypedTermType(..)) -- saw-core-what4 import Verifier.SAW.Simulator.What4.ReturnTrip -- saw-script import SAWScript.Builtins(fixPos) import SAWScript.Value import SAWScript.Options(Options,simVerbose) import SAWScript.Crucible.Common import SAWScript.Crucible.LLVM.Builtins (setupArg, setupArgs, getGlobalPair, runCFG, baseCryptolType) jvm - parser import qualified Language.JVM.Common as J import qualified Language.JVM.Parser as J import qualified SAWScript.Utils as J import qualified Lang.JVM.Codebase as JCB -- crucible-jvm import Lang.Crucible.JVM (IsCodebase(..)) import qualified Lang.Crucible.JVM as CJ import Debug.Trace ----------------------------------------------------------------------- -- | Make sure the class is in the database and allocate handles for its -- methods and static fields -- loadJavaClass :: String -> TopLevel J.Class loadJavaClass str = do cb <- getJavaCodebase c <- io $ findClass cb str prepareClassTopLevel str return c ----------------------------------------------------------------------- -- | Allocate the method handles/global static variables for the given -- class and add them to the current translation context prepareClassTopLevel :: String -> TopLevel () prepareClassTopLevel str = do cb <- getJavaCodebase -- get class from codebase c <- io $ findClass cb str -- get current ctx ctx0 <- getJVMTrans -- make sure that we haven't already processed this class unless (Map.member (J.className c) (CJ.classTable ctx0)) $ do -- add handles/global variables for this class halloc <- getHandleAlloc ctx <- io $ execStateT (CJ.extendJVMContext halloc c) ctx0 -- update ctx putJVMTrans ctx ----------------------------------------------------------------------- | Extract a JVM method to saw - core -- jvm_extract :: J.Class -> String -> TopLevel TypedTerm jvm_extract c mname = do sc <- getSharedContext cb <- getJavaCodebase opts <- getOptions pathSatSolver <- gets rwPathSatSolver let verbosity = simVerbose opts let gen = Nonce.globalNonceGenerator traceM $ "extracting " ++ mname (mcls, meth) <- io $ CJ.findMethod cb mname c when (not (J.methodIsStatic meth)) $ do fail $ unlines [ "Crucible can only extract static methods" ] let className = J.className c -- allocate all of the handles/static vars that are directly referenced by -- this class let refs = CJ.initClasses ++ Set.toList (CJ.classRefs c) mapM_ (prepareClassTopLevel . J.unClassName) refs halloc <- getHandleAlloc ctx <- getJVMTrans only the IO monad , nothing else sym <- newSAWCoreExprBuilder sc SomeOnlineBackend bak <- newSAWCoreBackend pathSatSolver sym st <- sawCoreState sym CJ.setSimulatorVerbosity verbosity sym (CJ.JVMHandleInfo _m2 h) <- CJ.findMethodHandle ctx mcls meth (ecs, args) <- setupArgs sc sym h res <- CJ.runMethodHandle bak SAWCruciblePersonality halloc ctx verbosity className h args case res of Crucible.FinishedResult _ pr -> do gp <- getGlobalPair opts pr let regval = gp^.Crucible.gpValue let regty = Crucible.regType regval let failure = fail $ unwords ["Unexpected return type:", show regty] t <- Crucible.asSymExpr regval (toSC sym st) failure cty <- case Crucible.asBaseType regty of Crucible.NotBaseType -> failure Crucible.AsBaseType bt -> case baseCryptolType bt of Nothing -> failure Just cty -> return cty let tt = TypedTerm (TypedTermSchema (Cryptol.tMono cty)) t abstractTypedExts sc (toList ecs) tt Crucible.AbortedResult _ _ar -> do fail $ unlines [ "Symbolic execution failed." ] Crucible.TimeoutResult _cxt -> do fail $ unlines [ "Symbolic execution timed out." ]
null
https://raw.githubusercontent.com/GaloisInc/saw-script/7f1a012b01f2f9dccdb3874e37e98a340fc3bbef/src/SAWScript/Crucible/JVM/BuiltinsJVM.hs
haskell
# LANGUAGE GADTs # # LANGUAGE NoMonoLocalBinds # # LANGUAGE PackageImports # java_load_class: reads a class from the codebase parameterized-utils crucible/crucible crucible/what4 saw-core saw-core-what4 saw-script crucible-jvm --------------------------------------------------------------------- | Make sure the class is in the database and allocate handles for its methods and static fields --------------------------------------------------------------------- | Allocate the method handles/global static variables for the given class and add them to the current translation context get class from codebase get current ctx make sure that we haven't already processed this class add handles/global variables for this class update ctx --------------------------------------------------------------------- allocate all of the handles/static vars that are directly referenced by this class
| Module : SAWScript . Crucible . JVM.BuiltinsJVM Description : crucible - jvm specific code Maintainer : Stability : provisional Module : SAWScript.Crucible.JVM.BuiltinsJVM Description : crucible-jvm specific code Maintainer : Stability : provisional -} # LANGUAGE TemplateHaskell # # LANGUAGE EmptyCase # # OPTIONS_GHC -fno - warn - unused - top - binds # # OPTIONS_GHC -fno - warn - unused - local - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - orphans # module SAWScript.Crucible.JVM.BuiltinsJVM ( , prepareClassTopLevel ) where import Data.List (isPrefixOf) import Control.Lens import Data.Map (Map,(!)) import qualified Data.Map as Map import qualified Data.Set as Set import Data.Foldable (toList) import System.IO import Control.Monad (forM_,unless,when,foldM) import Control.Monad.ST import Control.Monad.State.Strict import qualified Data.Parameterized.Map as MapF import qualified Data.Parameterized.Nonce as Nonce import qualified Lang.Crucible.FunctionHandle as Crucible import qualified Lang.Crucible.Simulator.Operations as Crucible import qualified Lang.Crucible.Simulator.EvalStmt as Crucible import qualified Lang.Crucible.CFG.Core as Crucible import qualified Lang.Crucible.Simulator.ExecutionTree as Crucible import qualified Lang.Crucible.Simulator.GlobalState as Crucible import qualified Lang.Crucible.Simulator.RegMap as Crucible import qualified Lang.Crucible.Simulator.OverrideSim as Crucible import qualified Lang.Crucible.Analysis.Postdom as Crucible cryptol import qualified Cryptol.TypeCheck.Type as Cryptol import qualified What4.Expr as W4 import qualified What4.Config as W4 import qualified What4.Interface as W4 import qualified What4.Solver.Yices as Yices import Verifier.SAW.SharedTerm(Term, SharedContext, mkSharedContext, scImplies) cryptol - saw - core import Verifier.SAW.TypedTerm (TypedTerm(..), abstractTypedExts, TypedTermType(..)) import Verifier.SAW.Simulator.What4.ReturnTrip import SAWScript.Builtins(fixPos) import SAWScript.Value import SAWScript.Options(Options,simVerbose) import SAWScript.Crucible.Common import SAWScript.Crucible.LLVM.Builtins (setupArg, setupArgs, getGlobalPair, runCFG, baseCryptolType) jvm - parser import qualified Language.JVM.Common as J import qualified Language.JVM.Parser as J import qualified SAWScript.Utils as J import qualified Lang.JVM.Codebase as JCB import Lang.Crucible.JVM (IsCodebase(..)) import qualified Lang.Crucible.JVM as CJ import Debug.Trace loadJavaClass :: String -> TopLevel J.Class loadJavaClass str = do cb <- getJavaCodebase c <- io $ findClass cb str prepareClassTopLevel str return c prepareClassTopLevel :: String -> TopLevel () prepareClassTopLevel str = do cb <- getJavaCodebase c <- io $ findClass cb str ctx0 <- getJVMTrans unless (Map.member (J.className c) (CJ.classTable ctx0)) $ do halloc <- getHandleAlloc ctx <- io $ execStateT (CJ.extendJVMContext halloc c) ctx0 putJVMTrans ctx | Extract a JVM method to saw - core jvm_extract :: J.Class -> String -> TopLevel TypedTerm jvm_extract c mname = do sc <- getSharedContext cb <- getJavaCodebase opts <- getOptions pathSatSolver <- gets rwPathSatSolver let verbosity = simVerbose opts let gen = Nonce.globalNonceGenerator traceM $ "extracting " ++ mname (mcls, meth) <- io $ CJ.findMethod cb mname c when (not (J.methodIsStatic meth)) $ do fail $ unlines [ "Crucible can only extract static methods" ] let className = J.className c let refs = CJ.initClasses ++ Set.toList (CJ.classRefs c) mapM_ (prepareClassTopLevel . J.unClassName) refs halloc <- getHandleAlloc ctx <- getJVMTrans only the IO monad , nothing else sym <- newSAWCoreExprBuilder sc SomeOnlineBackend bak <- newSAWCoreBackend pathSatSolver sym st <- sawCoreState sym CJ.setSimulatorVerbosity verbosity sym (CJ.JVMHandleInfo _m2 h) <- CJ.findMethodHandle ctx mcls meth (ecs, args) <- setupArgs sc sym h res <- CJ.runMethodHandle bak SAWCruciblePersonality halloc ctx verbosity className h args case res of Crucible.FinishedResult _ pr -> do gp <- getGlobalPair opts pr let regval = gp^.Crucible.gpValue let regty = Crucible.regType regval let failure = fail $ unwords ["Unexpected return type:", show regty] t <- Crucible.asSymExpr regval (toSC sym st) failure cty <- case Crucible.asBaseType regty of Crucible.NotBaseType -> failure Crucible.AsBaseType bt -> case baseCryptolType bt of Nothing -> failure Just cty -> return cty let tt = TypedTerm (TypedTermSchema (Cryptol.tMono cty)) t abstractTypedExts sc (toList ecs) tt Crucible.AbortedResult _ _ar -> do fail $ unlines [ "Symbolic execution failed." ] Crucible.TimeoutResult _cxt -> do fail $ unlines [ "Symbolic execution timed out." ]
45826fcf0fed9f54e9c94e1ab2e5df43b2c149d15ffc78308f852caba9eaf2d3
BranchTaken/Hemlock
test_nbU_wX.ml
open! Basis.Rudiments open! Basis let test () = File.Fmt.stdout |> (fun formatter -> List.fold U8.([kv 0L; kv 1L; kv 127L; kv 128L; kv 255L]) ~init:formatter ~f:(fun formatter u -> formatter |> Fmt.fmt "extend_to_i512 " |> U8.pp u |> Fmt.fmt " -> " |> I512.pp (U8.extend_to_i512 u) |> Fmt.fmt "\n" ) ) |> Fmt.fmt "\n" |> (fun formatter -> List.fold I512.([of_i64 (-1L); of_i64 0L; of_i64 1L; of_i64 255L; of_i64 256L]) ~init:formatter ~f:(fun formatter i -> formatter |> Fmt.fmt "trunc_of_i512/narrow_of_i512_opt " |> I512.pp i |> Fmt.fmt " -> " |> U8.pp (U8.trunc_of_i512 i) |> Fmt.fmt "/" |> (Option.fmt U8.pp) (U8.narrow_of_i512_opt i) |> Fmt.fmt "\n" ) ) |> ignore let _ = test ()
null
https://raw.githubusercontent.com/BranchTaken/Hemlock/f3604ceda4f75cf18b6ee2b1c2f3c5759ad495a5/bootstrap/test/basis/convert/test_nbU_wX.ml
ocaml
open! Basis.Rudiments open! Basis let test () = File.Fmt.stdout |> (fun formatter -> List.fold U8.([kv 0L; kv 1L; kv 127L; kv 128L; kv 255L]) ~init:formatter ~f:(fun formatter u -> formatter |> Fmt.fmt "extend_to_i512 " |> U8.pp u |> Fmt.fmt " -> " |> I512.pp (U8.extend_to_i512 u) |> Fmt.fmt "\n" ) ) |> Fmt.fmt "\n" |> (fun formatter -> List.fold I512.([of_i64 (-1L); of_i64 0L; of_i64 1L; of_i64 255L; of_i64 256L]) ~init:formatter ~f:(fun formatter i -> formatter |> Fmt.fmt "trunc_of_i512/narrow_of_i512_opt " |> I512.pp i |> Fmt.fmt " -> " |> U8.pp (U8.trunc_of_i512 i) |> Fmt.fmt "/" |> (Option.fmt U8.pp) (U8.narrow_of_i512_opt i) |> Fmt.fmt "\n" ) ) |> ignore let _ = test ()
298cb712a45ea52e4f78c73a40fbe91003c2fa02a4c84af3dad7008dc1d03749
dmitryvk/sbcl-win32-threads
defun-load-or-cload-xcompiler.lisp
This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB-COLD") ;;; Either load or compile-then-load the cross-compiler into the cross - compilation host Common Lisp . (defun load-or-cload-xcompiler (load-or-cload-stem) (declare (type function load-or-cload-stem)) ;; The running-in-the-host-Lisp Python cross-compiler defines its ;; own versions of a number of functions which should not overwrite ;; host-Lisp functions. Instead we put them in a special package. ;; ;; The common theme of the functions, macros, constants, and so ;; forth in this package is that they run in the host and affect the ;; compilation of the target. (let ((package-name "SB-XC")) (make-package package-name :use nil :nicknames nil) the constants ( except for T and NIL which have ;; a specially hacked correspondence between cross - compilation host and target Lisp ) "ARRAY-DIMENSION-LIMIT" "ARRAY-RANK-LIMIT" "ARRAY-TOTAL-SIZE-LIMIT" "BOOLE-1" "BOOLE-2" "BOOLE-AND" "BOOLE-ANDC1" "BOOLE-ANDC2" "BOOLE-C1" "BOOLE-C2" "BOOLE-CLR" "BOOLE-EQV" "BOOLE-IOR" "BOOLE-NAND" "BOOLE-NOR" "BOOLE-ORC1" "BOOLE-ORC2" "BOOLE-SET" "BOOLE-XOR" "CALL-ARGUMENTS-LIMIT" "CHAR-CODE-LIMIT" "DOUBLE-FLOAT-EPSILON" "DOUBLE-FLOAT-NEGATIVE-EPSILON" "INTERNAL-TIME-UNITS-PER-SECOND" "LAMBDA-LIST-KEYWORDS" "LAMBDA-PARAMETERS-LIMIT" "LEAST-NEGATIVE-DOUBLE-FLOAT" "LEAST-NEGATIVE-LONG-FLOAT" "LEAST-NEGATIVE-NORMALIZED-DOUBLE-FLOAT" "LEAST-NEGATIVE-NORMALIZED-LONG-FLOAT" "LEAST-NEGATIVE-NORMALIZED-SHORT-FLOAT" "LEAST-NEGATIVE-NORMALIZED-SINGLE-FLOAT" "LEAST-NEGATIVE-SHORT-FLOAT" "LEAST-NEGATIVE-SINGLE-FLOAT" "LEAST-POSITIVE-DOUBLE-FLOAT" "LEAST-POSITIVE-LONG-FLOAT" "LEAST-POSITIVE-NORMALIZED-DOUBLE-FLOAT" "LEAST-POSITIVE-NORMALIZED-LONG-FLOAT" "LEAST-POSITIVE-NORMALIZED-SHORT-FLOAT" "LEAST-POSITIVE-NORMALIZED-SINGLE-FLOAT" "LEAST-POSITIVE-SHORT-FLOAT" "LEAST-POSITIVE-SINGLE-FLOAT" "LONG-FLOAT-EPSILON" "LONG-FLOAT-NEGATIVE-EPSILON" "MOST-NEGATIVE-DOUBLE-FLOAT" "MOST-NEGATIVE-FIXNUM" "MOST-NEGATIVE-LONG-FLOAT" "MOST-NEGATIVE-SHORT-FLOAT" "MOST-NEGATIVE-SINGLE-FLOAT" "MOST-POSITIVE-DOUBLE-FLOAT" "MOST-POSITIVE-FIXNUM" "MOST-POSITIVE-LONG-FLOAT" "MOST-POSITIVE-SHORT-FLOAT" "MOST-POSITIVE-SINGLE-FLOAT" "MULTIPLE-VALUES-LIMIT" "PI" "SHORT-FLOAT-EPSILON" "SHORT-FLOAT-NEGATIVE-EPSILON" "SINGLE-FLOAT-EPSILON" "SINGLE-FLOAT-NEGATIVE-EPSILON" ;; everything else which needs a separate ;; existence in xc and target "BOOLE" "BOOLE-CLR" "BOOLE-SET" "BOOLE-1" "BOOLE-2" "BOOLE-C1" "BOOLE-C2" "BOOLE-AND" "BOOLE-IOR" "BOOLE-XOR" "BOOLE-EQV" "BOOLE-NAND" "BOOLE-NOR" "BOOLE-ANDC1" "BOOLE-ANDC2" "BOOLE-ORC1" "BOOLE-ORC2" "BUILT-IN-CLASS" "BYTE" "BYTE-POSITION" "BYTE-SIZE" "CHAR-CODE" "CLASS" "CLASS-NAME" "CLASS-OF" "CODE-CHAR" "COMPILE-FILE" "COMPILE-FILE-PATHNAME" "*COMPILE-FILE-PATHNAME*" "*COMPILE-FILE-TRUENAME*" "*COMPILE-PRINT*" "*COMPILE-VERBOSE*" "COMPILER-MACRO-FUNCTION" "CONSTANTP" "DEFCONSTANT" "DEFINE-MODIFY-MACRO" "DEFINE-SETF-EXPANDER" "DEFMACRO" "DEFSETF" "DEFSTRUCT" "DEFTYPE" "DEPOSIT-FIELD" "DPB" "FBOUNDP" "FDEFINITION" "FMAKUNBOUND" "FIND-CLASS" "GENSYM" "*GENSYM-COUNTER*" "GET-SETF-EXPANSION" "LDB" "LDB-TEST" "LISP-IMPLEMENTATION-TYPE" "LISP-IMPLEMENTATION-VERSION" "MACRO-FUNCTION" "MACROEXPAND" "MACROEXPAND-1" "*MACROEXPAND-HOOK*" "MAKE-LOAD-FORM" "MAKE-LOAD-FORM-SAVING-SLOTS" "MASK-FIELD" "PACKAGE" "PACKAGEP" "PROCLAIM" "SPECIAL-OPERATOR-P" "STANDARD-CLASS" "STRUCTURE-CLASS" "SUBTYPEP" "TYPE-OF" "TYPEP" "UPGRADED-ARRAY-ELEMENT-TYPE" "UPGRADED-COMPLEX-PART-TYPE" "WITH-COMPILATION-UNIT")) (export (intern name package-name) package-name))) ;; don't watch: (dolist (package (list-all-packages)) (when (= (mismatch (package-name package) "SB!") 3) (shadowing-import (mapcar (lambda (name) (find-symbol name "SB-XC")) '("BYTE" "BYTE-POSITION" "BYTE-SIZE" "DPB" "LDB" "LDB-TEST" "DEPOSIT-FIELD" "MASK-FIELD" "BOOLE" "BOOLE-CLR" "BOOLE-SET" "BOOLE-1" "BOOLE-2" "BOOLE-C1" "BOOLE-C2" "BOOLE-AND" "BOOLE-IOR" "BOOLE-XOR" "BOOLE-EQV" "BOOLE-NAND" "BOOLE-NOR" "BOOLE-ANDC1" "BOOLE-ANDC2" "BOOLE-ORC1" "BOOLE-ORC2")) package))) Build a version of Python to run in the host , to be ;; used only in cross-compilation. ;; Note that files which are marked : ASSEM , to cause them to be processed with SB!C : ASSEMBLE - FILE when we 're running under the ;; cross-compiler or the target lisp, are still processed here, just ;; with the ordinary Lisp compiler, and this is intentional, in ;; order to make the compiler aware of the definitions of assembly ;; routines. (do-stems-and-flags (stem flags) (unless (find :not-host flags) (funcall load-or-cload-stem stem flags) #!+sb-show (warn-when-cl-snapshot-diff *cl-snapshot*))) If the cross - compilation host is itself , we can use the PURIFY extension to freeze everything in place , reducing the amount of work done on future GCs . In machines with limited ;; memory, this could help, by reducing the amount of memory which needs to be juggled in a full GC . And it can hardly hurt , since ;; (in the ordinary build procedure anyway) essentially everything ;; which is reachable at this point will remain reachable for the ;; entire run. ;; ( Except that purifying actually slows down GENCGC ) . -- JES , 2006 - 05 - 30 #+(and sbcl (not gencgc)) (sb-ext:purify) (values))
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/cold/defun-load-or-cload-xcompiler.lisp
lisp
more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. Either load or compile-then-load the cross-compiler into the The running-in-the-host-Lisp Python cross-compiler defines its own versions of a number of functions which should not overwrite host-Lisp functions. Instead we put them in a special package. The common theme of the functions, macros, constants, and so forth in this package is that they run in the host and affect the compilation of the target. a specially hacked correspondence between everything else which needs a separate existence in xc and target don't watch: used only in cross-compilation. cross-compiler or the target lisp, are still processed here, just with the ordinary Lisp compiler, and this is intentional, in order to make the compiler aware of the definitions of assembly routines. memory, this could help, by reducing the amount of memory which (in the ordinary build procedure anyway) essentially everything which is reachable at this point will remain reachable for the entire run.
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB-COLD") cross - compilation host Common Lisp . (defun load-or-cload-xcompiler (load-or-cload-stem) (declare (type function load-or-cload-stem)) (let ((package-name "SB-XC")) (make-package package-name :use nil :nicknames nil) the constants ( except for T and NIL which have cross - compilation host and target Lisp ) "ARRAY-DIMENSION-LIMIT" "ARRAY-RANK-LIMIT" "ARRAY-TOTAL-SIZE-LIMIT" "BOOLE-1" "BOOLE-2" "BOOLE-AND" "BOOLE-ANDC1" "BOOLE-ANDC2" "BOOLE-C1" "BOOLE-C2" "BOOLE-CLR" "BOOLE-EQV" "BOOLE-IOR" "BOOLE-NAND" "BOOLE-NOR" "BOOLE-ORC1" "BOOLE-ORC2" "BOOLE-SET" "BOOLE-XOR" "CALL-ARGUMENTS-LIMIT" "CHAR-CODE-LIMIT" "DOUBLE-FLOAT-EPSILON" "DOUBLE-FLOAT-NEGATIVE-EPSILON" "INTERNAL-TIME-UNITS-PER-SECOND" "LAMBDA-LIST-KEYWORDS" "LAMBDA-PARAMETERS-LIMIT" "LEAST-NEGATIVE-DOUBLE-FLOAT" "LEAST-NEGATIVE-LONG-FLOAT" "LEAST-NEGATIVE-NORMALIZED-DOUBLE-FLOAT" "LEAST-NEGATIVE-NORMALIZED-LONG-FLOAT" "LEAST-NEGATIVE-NORMALIZED-SHORT-FLOAT" "LEAST-NEGATIVE-NORMALIZED-SINGLE-FLOAT" "LEAST-NEGATIVE-SHORT-FLOAT" "LEAST-NEGATIVE-SINGLE-FLOAT" "LEAST-POSITIVE-DOUBLE-FLOAT" "LEAST-POSITIVE-LONG-FLOAT" "LEAST-POSITIVE-NORMALIZED-DOUBLE-FLOAT" "LEAST-POSITIVE-NORMALIZED-LONG-FLOAT" "LEAST-POSITIVE-NORMALIZED-SHORT-FLOAT" "LEAST-POSITIVE-NORMALIZED-SINGLE-FLOAT" "LEAST-POSITIVE-SHORT-FLOAT" "LEAST-POSITIVE-SINGLE-FLOAT" "LONG-FLOAT-EPSILON" "LONG-FLOAT-NEGATIVE-EPSILON" "MOST-NEGATIVE-DOUBLE-FLOAT" "MOST-NEGATIVE-FIXNUM" "MOST-NEGATIVE-LONG-FLOAT" "MOST-NEGATIVE-SHORT-FLOAT" "MOST-NEGATIVE-SINGLE-FLOAT" "MOST-POSITIVE-DOUBLE-FLOAT" "MOST-POSITIVE-FIXNUM" "MOST-POSITIVE-LONG-FLOAT" "MOST-POSITIVE-SHORT-FLOAT" "MOST-POSITIVE-SINGLE-FLOAT" "MULTIPLE-VALUES-LIMIT" "PI" "SHORT-FLOAT-EPSILON" "SHORT-FLOAT-NEGATIVE-EPSILON" "SINGLE-FLOAT-EPSILON" "SINGLE-FLOAT-NEGATIVE-EPSILON" "BOOLE" "BOOLE-CLR" "BOOLE-SET" "BOOLE-1" "BOOLE-2" "BOOLE-C1" "BOOLE-C2" "BOOLE-AND" "BOOLE-IOR" "BOOLE-XOR" "BOOLE-EQV" "BOOLE-NAND" "BOOLE-NOR" "BOOLE-ANDC1" "BOOLE-ANDC2" "BOOLE-ORC1" "BOOLE-ORC2" "BUILT-IN-CLASS" "BYTE" "BYTE-POSITION" "BYTE-SIZE" "CHAR-CODE" "CLASS" "CLASS-NAME" "CLASS-OF" "CODE-CHAR" "COMPILE-FILE" "COMPILE-FILE-PATHNAME" "*COMPILE-FILE-PATHNAME*" "*COMPILE-FILE-TRUENAME*" "*COMPILE-PRINT*" "*COMPILE-VERBOSE*" "COMPILER-MACRO-FUNCTION" "CONSTANTP" "DEFCONSTANT" "DEFINE-MODIFY-MACRO" "DEFINE-SETF-EXPANDER" "DEFMACRO" "DEFSETF" "DEFSTRUCT" "DEFTYPE" "DEPOSIT-FIELD" "DPB" "FBOUNDP" "FDEFINITION" "FMAKUNBOUND" "FIND-CLASS" "GENSYM" "*GENSYM-COUNTER*" "GET-SETF-EXPANSION" "LDB" "LDB-TEST" "LISP-IMPLEMENTATION-TYPE" "LISP-IMPLEMENTATION-VERSION" "MACRO-FUNCTION" "MACROEXPAND" "MACROEXPAND-1" "*MACROEXPAND-HOOK*" "MAKE-LOAD-FORM" "MAKE-LOAD-FORM-SAVING-SLOTS" "MASK-FIELD" "PACKAGE" "PACKAGEP" "PROCLAIM" "SPECIAL-OPERATOR-P" "STANDARD-CLASS" "STRUCTURE-CLASS" "SUBTYPEP" "TYPE-OF" "TYPEP" "UPGRADED-ARRAY-ELEMENT-TYPE" "UPGRADED-COMPLEX-PART-TYPE" "WITH-COMPILATION-UNIT")) (export (intern name package-name) package-name))) (dolist (package (list-all-packages)) (when (= (mismatch (package-name package) "SB!") 3) (shadowing-import (mapcar (lambda (name) (find-symbol name "SB-XC")) '("BYTE" "BYTE-POSITION" "BYTE-SIZE" "DPB" "LDB" "LDB-TEST" "DEPOSIT-FIELD" "MASK-FIELD" "BOOLE" "BOOLE-CLR" "BOOLE-SET" "BOOLE-1" "BOOLE-2" "BOOLE-C1" "BOOLE-C2" "BOOLE-AND" "BOOLE-IOR" "BOOLE-XOR" "BOOLE-EQV" "BOOLE-NAND" "BOOLE-NOR" "BOOLE-ANDC1" "BOOLE-ANDC2" "BOOLE-ORC1" "BOOLE-ORC2")) package))) Build a version of Python to run in the host , to be Note that files which are marked : ASSEM , to cause them to be processed with SB!C : ASSEMBLE - FILE when we 're running under the (do-stems-and-flags (stem flags) (unless (find :not-host flags) (funcall load-or-cload-stem stem flags) #!+sb-show (warn-when-cl-snapshot-diff *cl-snapshot*))) If the cross - compilation host is itself , we can use the PURIFY extension to freeze everything in place , reducing the amount of work done on future GCs . In machines with limited needs to be juggled in a full GC . And it can hardly hurt , since ( Except that purifying actually slows down GENCGC ) . -- JES , 2006 - 05 - 30 #+(and sbcl (not gencgc)) (sb-ext:purify) (values))
03969bd595879e9021483ac32743e0448dabe8f54b0dcd469e8d317e723abff8
lukeg101/lplzoo
Tests.hs
| Module : Tests Description : The Testing for ULC . Copyright : ( c ) , 2018 License : GPL-3 Maintainer : Stability : stable Portability : POSIX The " Tests " module provides the Unit tests for various aspects of ULC including expected reductions , pretty printing , and useful features . Module : Tests Description : The Testing for ULC. Copyright : (c) Luke Geeson, 2018 License : GPL-3 Maintainer : Stability : stable Portability : POSIX The "Tests" module provides the Unit tests for various aspects of ULC including expected reductions, pretty printing, and useful features. -} module Tests where -- Tool Imports. import qualified Test.QuickCheck as QC import qualified Control.Monad as M import System.Exit (exitFailure) ULC Imports . import ULC (Term(App, Abs, Var), toChurch, i, true, false, xx, omega) import qualified Parser as P -- | Type encapsulating test pass, expected value, actual value type UnitTest = (Bool, String, String) -- | Type Denoting set of tests type UnitTests = [UnitTest] Test Showable produces the correct instance , first with some simple tests and the examples in the README , and then automatically with QuickCheck . -- | Function that constructs a unit test from an input term, expected output, -- and actual value mkUnitTest :: Bool -> String -> String -> UnitTest mkUnitTest result exp got = (result, exp, got) -- | Test pretty printing for id (\x.x x) unittest1 :: UnitTest unittest1 = let term = App i (Abs "x" (App (Var "x") (Var "x"))) exp = "(λa.a) (λx.x x)" got = show term in mkUnitTest (exp==got) exp got | Test pretty printing for ( \x y.y ) y z unittest2 :: UnitTest unittest2 = let term = App (App (Abs "x" (Abs "y" (Var "y"))) (Var "y")) (Var "z") exp = "(λx.λy.y) y z" got = show term in mkUnitTest (exp==got) exp got | Test pretty printing for ( \x y.y ) y z unittest3 :: UnitTest unittest3 = let term = App (App (toChurch 3) (Abs "x" (App (Var "x") (toChurch 2)))) (toChurch 1) exp = "(λx.λf.x (x (x x))) (λx.x (λx.λf.x (x x))) (λx.λf.x x)" got = show term in mkUnitTest (exp==got) exp got -- | Test pretty printing for id unittest4 :: UnitTest unittest4 = let term = i exp = "λa.a" got = show term in mkUnitTest (exp==got) exp got -- | Test pretty printing for true unittest5 :: UnitTest unittest5 = let term = true exp = "λa.λb.a" got = show term in mkUnitTest (exp==got) exp got -- | Test pretty printing for true unittest6 :: UnitTest unittest6 = let term = false exp = "λa.λb.b" got = show term in mkUnitTest (exp==got) exp got -- | Test pretty printing for true unittest7 :: UnitTest unittest7 = let term = xx exp = "λx.x x" got = show term in mkUnitTest (exp==got) exp got -- | Test pretty printing for true unittest8 :: UnitTest unittest8 = let term = omega exp = "(λx.x x) (λx.x x)" got = show term in mkUnitTest (exp==got) exp got -- | Testing pretty printing for (\x.x) (\y.y) z unittest9 :: UnitTest unittest9 = let term = App (App (Abs "x" (Var "x")) (Abs "y" (Var "y"))) (Var "z") exp = "(λx.x) (λy.y) z" got = show term in mkUnitTest (exp==got) exp got -- | List of pretty printing unit tests ppunittests :: UnitTests ppunittests = [unittest1, unittest2, unittest2, unittest3, unittest4, unittest5, unittest6, unittest7, unittest8, unittest9] -- | Function that runs the tests and returns true if they all pass testPP :: Maybe UnitTests testPP = let passed = filter (\(a,_,_)->a) ppunittests in if null passed then return passed else Nothing | Use QuickCheck to generate terms and show that both the and --Printing align. instance QC.Arbitrary Term where arbitrary = QC.sized term where varname = do s <- QC.listOf1 (QC.choose ('a', 'z')) if s `elem` P.keywords then varname else return s genAbs n = do s <- varname t <- term n return $ Abs s t genApp n = do t1 <- term n t2 <- term n return $ App t1 t2 term n | n == 0 = Var <$> varname | n > 0 = QC.oneof [genAbs (n-1), genApp (n-1)] | otherwise = term (abs n) shrink (Var _) = [] shrink (App t1 t2) = [t1, t2] shrink (Abs _ t1) = [t1] -- | QuickCheck predicate to show that parsing a printed term --produces the same term. propShow :: Term -> Bool propShow t = let parsed = fst . head $ P.apply P.pTerm (show t) in parsed == t -- | QuickCheck predicate to test parsing succeeds for a term propParse :: Term -> Bool propParse t = let parse = P.apply P.pTerm (show t) in case parse of [(_,"")] -> True _ -> False | Helper function to run the above unit tests , and the quickCheck tests runTests :: IO () runTests = let tests = all (\(a,_,_)->a) ppunittests failed t = case t of QC.Failure {} -> True _ -> False in do M.unless tests (do {putStrLn "unit tests failed!"; exitFailure}) r1 <- QC.quickCheckResult (QC.withMaxSuccess 20 propShow) r2 <- QC.quickCheckResult (QC.withMaxSuccess 20 propParse) M.when (any failed [r1, r2]) exitFailure -- | Main function to run the tests hs :: IO () hs = runTests -- deep diving syntax trees is slow! run this a couple of times if you can! TODO implement testing reduction for terms
null
https://raw.githubusercontent.com/lukeg101/lplzoo/463ca93f22f018ee07bdc18d84b3b0c966d51766/ULC/Tests.hs
haskell
Tool Imports. | Type encapsulating test pass, expected value, actual value | Type Denoting set of tests | Function that constructs a unit test from an input term, expected output, and actual value | Test pretty printing for id (\x.x x) | Test pretty printing for id | Test pretty printing for true | Test pretty printing for true | Test pretty printing for true | Test pretty printing for true | Testing pretty printing for (\x.x) (\y.y) z | List of pretty printing unit tests | Function that runs the tests and returns true if they all pass Printing align. | QuickCheck predicate to show that parsing a printed term produces the same term. | QuickCheck predicate to test parsing succeeds for a term | Main function to run the tests deep diving syntax trees is slow! run this a couple of times if you can!
| Module : Tests Description : The Testing for ULC . Copyright : ( c ) , 2018 License : GPL-3 Maintainer : Stability : stable Portability : POSIX The " Tests " module provides the Unit tests for various aspects of ULC including expected reductions , pretty printing , and useful features . Module : Tests Description : The Testing for ULC. Copyright : (c) Luke Geeson, 2018 License : GPL-3 Maintainer : Stability : stable Portability : POSIX The "Tests" module provides the Unit tests for various aspects of ULC including expected reductions, pretty printing, and useful features. -} module Tests where import qualified Test.QuickCheck as QC import qualified Control.Monad as M import System.Exit (exitFailure) ULC Imports . import ULC (Term(App, Abs, Var), toChurch, i, true, false, xx, omega) import qualified Parser as P type UnitTest = (Bool, String, String) type UnitTests = [UnitTest] Test Showable produces the correct instance , first with some simple tests and the examples in the README , and then automatically with QuickCheck . mkUnitTest :: Bool -> String -> String -> UnitTest mkUnitTest result exp got = (result, exp, got) unittest1 :: UnitTest unittest1 = let term = App i (Abs "x" (App (Var "x") (Var "x"))) exp = "(λa.a) (λx.x x)" got = show term in mkUnitTest (exp==got) exp got | Test pretty printing for ( \x y.y ) y z unittest2 :: UnitTest unittest2 = let term = App (App (Abs "x" (Abs "y" (Var "y"))) (Var "y")) (Var "z") exp = "(λx.λy.y) y z" got = show term in mkUnitTest (exp==got) exp got | Test pretty printing for ( \x y.y ) y z unittest3 :: UnitTest unittest3 = let term = App (App (toChurch 3) (Abs "x" (App (Var "x") (toChurch 2)))) (toChurch 1) exp = "(λx.λf.x (x (x x))) (λx.x (λx.λf.x (x x))) (λx.λf.x x)" got = show term in mkUnitTest (exp==got) exp got unittest4 :: UnitTest unittest4 = let term = i exp = "λa.a" got = show term in mkUnitTest (exp==got) exp got unittest5 :: UnitTest unittest5 = let term = true exp = "λa.λb.a" got = show term in mkUnitTest (exp==got) exp got unittest6 :: UnitTest unittest6 = let term = false exp = "λa.λb.b" got = show term in mkUnitTest (exp==got) exp got unittest7 :: UnitTest unittest7 = let term = xx exp = "λx.x x" got = show term in mkUnitTest (exp==got) exp got unittest8 :: UnitTest unittest8 = let term = omega exp = "(λx.x x) (λx.x x)" got = show term in mkUnitTest (exp==got) exp got unittest9 :: UnitTest unittest9 = let term = App (App (Abs "x" (Var "x")) (Abs "y" (Var "y"))) (Var "z") exp = "(λx.x) (λy.y) z" got = show term in mkUnitTest (exp==got) exp got ppunittests :: UnitTests ppunittests = [unittest1, unittest2, unittest2, unittest3, unittest4, unittest5, unittest6, unittest7, unittest8, unittest9] testPP :: Maybe UnitTests testPP = let passed = filter (\(a,_,_)->a) ppunittests in if null passed then return passed else Nothing | Use QuickCheck to generate terms and show that both the and instance QC.Arbitrary Term where arbitrary = QC.sized term where varname = do s <- QC.listOf1 (QC.choose ('a', 'z')) if s `elem` P.keywords then varname else return s genAbs n = do s <- varname t <- term n return $ Abs s t genApp n = do t1 <- term n t2 <- term n return $ App t1 t2 term n | n == 0 = Var <$> varname | n > 0 = QC.oneof [genAbs (n-1), genApp (n-1)] | otherwise = term (abs n) shrink (Var _) = [] shrink (App t1 t2) = [t1, t2] shrink (Abs _ t1) = [t1] propShow :: Term -> Bool propShow t = let parsed = fst . head $ P.apply P.pTerm (show t) in parsed == t propParse :: Term -> Bool propParse t = let parse = P.apply P.pTerm (show t) in case parse of [(_,"")] -> True _ -> False | Helper function to run the above unit tests , and the quickCheck tests runTests :: IO () runTests = let tests = all (\(a,_,_)->a) ppunittests failed t = case t of QC.Failure {} -> True _ -> False in do M.unless tests (do {putStrLn "unit tests failed!"; exitFailure}) r1 <- QC.quickCheckResult (QC.withMaxSuccess 20 propShow) r2 <- QC.quickCheckResult (QC.withMaxSuccess 20 propParse) M.when (any failed [r1, r2]) exitFailure hs :: IO () hs = runTests TODO implement testing reduction for terms
61509257cc5768c90bc30d546fb108fbd523080c9909c2b8474d6b97d90720be
psilord/option-9
passive-step-once.lisp
(in-package :option-9) #+option-9-debug (declaim (optimize (safety 3) (space 0) (speed 0) (debug 3))) ;; Usually nothing has a passive step (defmethod passive-step-once (object) nil) ;; If the ship has a passive gun, then simulate it with the ship as ;; the source charge and other brains as the charges (defmethod passive-step-once :after ((ent ship)) (let ((payload (payload (turret ent :passive-weapon-port)))) (when payload (let ((ents (all-entities-in-roles (scene-man (game-context ent)) :player :enemy-mine :enemy :enemy-shot))) (generate payload ent ents)))))
null
https://raw.githubusercontent.com/psilord/option-9/44d96cbc5543ee2acbdcf45d300207ef175462bc/passive-step-once.lisp
lisp
Usually nothing has a passive step If the ship has a passive gun, then simulate it with the ship as the source charge and other brains as the charges
(in-package :option-9) #+option-9-debug (declaim (optimize (safety 3) (space 0) (speed 0) (debug 3))) (defmethod passive-step-once (object) nil) (defmethod passive-step-once :after ((ent ship)) (let ((payload (payload (turret ent :passive-weapon-port)))) (when payload (let ((ents (all-entities-in-roles (scene-man (game-context ent)) :player :enemy-mine :enemy :enemy-shot))) (generate payload ent ents)))))
2e39717df6878ed381fc2e9dce878f92396fb799faef3946da53cff9300d1a12
emotiq/emotiq
codes-in-use.lisp
((1 SDLE-STORE::REFERRER) (2 SDLE-STORE::SPECIAL-FLOAT) (3 SDLE-STORE::UNICODE-STRING) (4 SDLE-STORE::POSITIVE-INTEGER) (5 SDLE-STORE::NEGATIVE-INTEGER) (6 SIMPLE-STRING) (7 FLOAT) (8 RATIO) (9 CHARACTER) (10 COMPLEX) (11 SYMBOL) (12 CONS) (13 PATHNAME) (14 HASH-TABLE) (15 STANDARD-OBJECT) (16 CONDITION) (17 STRUCTURE-OBJECT) (18 STANDARD-CLASS) (19 BUILT-IN-CLASS) (20 ARRAY) (21 SIMPLE-VECTOR) (22 PACKAGE) (23 SDLE-STORE::SIMPLE-BYTE-VECTOR) (24 KEYWORD) (25 SDLE-STORE::BUILT-IN-FUNCTION) (26 FUNCTION) (27 GENERIC-FUNCTION) (28 STRUCTURE-CLASS) (29 SDLE-STORE::STRUCT-DEF) (30 GENSYM) (31 SDLE-STORE::UNICODE-BASE-STRING) (32 SIMPLE-BASE-STRING) (33 SDLE-STORE::NIL-OBJECT) (34 SDLE-STORE::T-OBJECT) (35 SDLE-STORE::0-OBJECT) (36 SDLE-STORE::1-OBJECT) (37 SDLE-STORE::2-OBJECT) (38 SDLE-STORE::-1-OBJECT) (39 SDLE-STORE::PROPER-LIST) (40 UNBOUND-SLOT) (41 SDLE-STORE:RAWBYTES) 42 - 100 available (101 COM.SD.OKEANOS:PERSISTENT-CLASS) (102 COM.SD.OKEANOS:PERSISTENT-OBJECT) (103 COM.SD.OKEANOS:OID) (104 COM.SD.OKEANOS::IOID) (105 COM.SD.OKEANOS::PERSISTENT-KERNEL-OBJECT) 106 - 110 available (111 PREVALENT-OBJECT::OBJECT-PROXY) (112 PREVALENT-OBJECT::UPDATE-SPEC) (113 PREVALENT-OBJECT::MAKUNBOUND-SPEC) (114 PREVALENT-OBJECT::REMOVE-SPEC) (115 PREVALENT-OBJECT::STORE-ROOT-SPEC) (116 PREVALENT-OBJECT::REMOVE-ROOT-SPEC) (117 PREVALENT-OBJECT::CREATE-ROOT-SPEC) (118 PREVALENT-OBJECT::OBJECT-ASSOCIATION) (119 PREVALENT-OBJECT::CREATE-SPEC) (120 PREVALENT-OBJECT::FULL-UPDATE-SPEC) 121 - 123 available (124 BUTTERFLY.ENCODER::UUID-NODE) (125 BUTTERFLY.ENCODER::NODE) (126 BUTTERFLY.ENCODER::UPID) (127 LISP-OBJECT-ENCODER::UUID))
null
https://raw.githubusercontent.com/emotiq/emotiq/9af78023f670777895a3dac29a2bbe98e19b6249/src/sdle-store/codes-in-use.lisp
lisp
((1 SDLE-STORE::REFERRER) (2 SDLE-STORE::SPECIAL-FLOAT) (3 SDLE-STORE::UNICODE-STRING) (4 SDLE-STORE::POSITIVE-INTEGER) (5 SDLE-STORE::NEGATIVE-INTEGER) (6 SIMPLE-STRING) (7 FLOAT) (8 RATIO) (9 CHARACTER) (10 COMPLEX) (11 SYMBOL) (12 CONS) (13 PATHNAME) (14 HASH-TABLE) (15 STANDARD-OBJECT) (16 CONDITION) (17 STRUCTURE-OBJECT) (18 STANDARD-CLASS) (19 BUILT-IN-CLASS) (20 ARRAY) (21 SIMPLE-VECTOR) (22 PACKAGE) (23 SDLE-STORE::SIMPLE-BYTE-VECTOR) (24 KEYWORD) (25 SDLE-STORE::BUILT-IN-FUNCTION) (26 FUNCTION) (27 GENERIC-FUNCTION) (28 STRUCTURE-CLASS) (29 SDLE-STORE::STRUCT-DEF) (30 GENSYM) (31 SDLE-STORE::UNICODE-BASE-STRING) (32 SIMPLE-BASE-STRING) (33 SDLE-STORE::NIL-OBJECT) (34 SDLE-STORE::T-OBJECT) (35 SDLE-STORE::0-OBJECT) (36 SDLE-STORE::1-OBJECT) (37 SDLE-STORE::2-OBJECT) (38 SDLE-STORE::-1-OBJECT) (39 SDLE-STORE::PROPER-LIST) (40 UNBOUND-SLOT) (41 SDLE-STORE:RAWBYTES) 42 - 100 available (101 COM.SD.OKEANOS:PERSISTENT-CLASS) (102 COM.SD.OKEANOS:PERSISTENT-OBJECT) (103 COM.SD.OKEANOS:OID) (104 COM.SD.OKEANOS::IOID) (105 COM.SD.OKEANOS::PERSISTENT-KERNEL-OBJECT) 106 - 110 available (111 PREVALENT-OBJECT::OBJECT-PROXY) (112 PREVALENT-OBJECT::UPDATE-SPEC) (113 PREVALENT-OBJECT::MAKUNBOUND-SPEC) (114 PREVALENT-OBJECT::REMOVE-SPEC) (115 PREVALENT-OBJECT::STORE-ROOT-SPEC) (116 PREVALENT-OBJECT::REMOVE-ROOT-SPEC) (117 PREVALENT-OBJECT::CREATE-ROOT-SPEC) (118 PREVALENT-OBJECT::OBJECT-ASSOCIATION) (119 PREVALENT-OBJECT::CREATE-SPEC) (120 PREVALENT-OBJECT::FULL-UPDATE-SPEC) 121 - 123 available (124 BUTTERFLY.ENCODER::UUID-NODE) (125 BUTTERFLY.ENCODER::NODE) (126 BUTTERFLY.ENCODER::UPID) (127 LISP-OBJECT-ENCODER::UUID))
213ccb5077f2b4836b8780e9037ea797f386be9e3eba566f7ac89598137feb82
Clojure2D/clojure2d-examples
ex14_metaballs.clj
;; (ns ex14-metaballs (:require [clojure2d.core :as c2d] [fastmath.core :as m] [fastmath.random :as r] [fastmath.vector :as v]) (:import [fastmath.vector Vec3])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (m/use-primitive-operators) (def ^:const ^long SIZE 600) (def ^:const ^long SIZE-2 (- SIZE 2)) (def ^:const zero (Vec3. 0.0 0.0 0.0)) (deftype Ball [^double x ^double y ^double vx ^double vy ^double radius ^Vec3 color]) (defn make-ball ^Ball [] (Ball. (r/irand SIZE) (r/irand SIZE) (r/irand 1 7) (r/irand 1 7) (r/irand 10 65) (Vec3. (r/drand 255.0) (r/drand 255.0) (r/drand 255.0)))) (defmacro direction [p v] `(if (or (> ~p SIZE) (neg? ~p)) (- ~v) ~v)) (defn move ^Ball [^Ball ball] (let [vx (direction (.x ball) (.vx ball)) vy (direction (.y ball) (.vy ball))] (Ball. (+ (.x ball) vx) (+ (.y ball) vy) vx vy (.radius ball) (.color ball)))) (defn influence ^double [^Ball ball ^double px ^double py] (/ (.radius ball) (+ m/EPSILON (m/dist (.x ball) (.y ball) px py)))) (defn compute-color ^Vec3 [x y ^Vec3 cur ^Ball ball] (let [infl (influence ball x y) rgb (.color ball)] (v/add cur (v/mult rgb infl)))) (defn draw [canvas balls] (loop [y (int 0)] (loop [x (int 0)] (let [^Vec3 c (reduce (fn [current ball] (compute-color x y current ball)) zero balls)] (c2d/set-color canvas c) (c2d/rect canvas x y 2 2)) (when (< x SIZE-2) (recur (+ 2 x)))) (when (< y SIZE-2) (recur (+ 2 y))))) (defn draw-balls [_ canvas _ _ result] (let [balls (map move result)] (draw canvas balls) balls)) (defn example-14 [n] (let [c (c2d/canvas SIZE SIZE :low)] (c2d/show-window {:canvas c :window-name "metaballs" :draw-fn (partial draw-balls n) :draw-state (repeatedly n make-ball) :refresher :fast}))) (def window (example-14 (r/irand 2 6))) (comment c2d/save window "results/ex14/metaballs.jpg") ;; [[../results/ex14/metaballs.jpg]]
null
https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/9de82f5ac0737b7e78e07a17cf03ac577d973817/src/ex14_metaballs.clj
clojure
[[../results/ex14/metaballs.jpg]]
(ns ex14-metaballs (:require [clojure2d.core :as c2d] [fastmath.core :as m] [fastmath.random :as r] [fastmath.vector :as v]) (:import [fastmath.vector Vec3])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (m/use-primitive-operators) (def ^:const ^long SIZE 600) (def ^:const ^long SIZE-2 (- SIZE 2)) (def ^:const zero (Vec3. 0.0 0.0 0.0)) (deftype Ball [^double x ^double y ^double vx ^double vy ^double radius ^Vec3 color]) (defn make-ball ^Ball [] (Ball. (r/irand SIZE) (r/irand SIZE) (r/irand 1 7) (r/irand 1 7) (r/irand 10 65) (Vec3. (r/drand 255.0) (r/drand 255.0) (r/drand 255.0)))) (defmacro direction [p v] `(if (or (> ~p SIZE) (neg? ~p)) (- ~v) ~v)) (defn move ^Ball [^Ball ball] (let [vx (direction (.x ball) (.vx ball)) vy (direction (.y ball) (.vy ball))] (Ball. (+ (.x ball) vx) (+ (.y ball) vy) vx vy (.radius ball) (.color ball)))) (defn influence ^double [^Ball ball ^double px ^double py] (/ (.radius ball) (+ m/EPSILON (m/dist (.x ball) (.y ball) px py)))) (defn compute-color ^Vec3 [x y ^Vec3 cur ^Ball ball] (let [infl (influence ball x y) rgb (.color ball)] (v/add cur (v/mult rgb infl)))) (defn draw [canvas balls] (loop [y (int 0)] (loop [x (int 0)] (let [^Vec3 c (reduce (fn [current ball] (compute-color x y current ball)) zero balls)] (c2d/set-color canvas c) (c2d/rect canvas x y 2 2)) (when (< x SIZE-2) (recur (+ 2 x)))) (when (< y SIZE-2) (recur (+ 2 y))))) (defn draw-balls [_ canvas _ _ result] (let [balls (map move result)] (draw canvas balls) balls)) (defn example-14 [n] (let [c (c2d/canvas SIZE SIZE :low)] (c2d/show-window {:canvas c :window-name "metaballs" :draw-fn (partial draw-balls n) :draw-state (repeatedly n make-ball) :refresher :fast}))) (def window (example-14 (r/irand 2 6))) (comment c2d/save window "results/ex14/metaballs.jpg")
3c8c983cec8d61b2290cba5259edf6b20e9b50afce5187f2992be98a5c05270f
phadej/staged
ByteString.hs
# LANGUAGE TemplateHaskell # module Staged.Stream.ByteString ( readByteString, ) where import Control.Monad.IO.Class (MonadIO (..)) import qualified Data.ByteString as BS import qualified Control.Monad.Trans.Resource as R import Staged.Commons import Staged.Stream.Type import Staged.Stream.Combinators (unfold) import Staged.Stream.Handle | Open a file and read strict ' ByteString ' chunks from it . readByteString :: R.MonadResource m => StreamM m FilePath BS.ByteString readByteString = withBinaryFile sReadMode $ unfold id $ \hdl k -> toCode [|| do bs <- liftIO (BS.hGetSome $$(fromCode hdl) 32768) if BS.null bs then $$(fromCode $ k Nothing) else $$(fromCode $ k (Just (toCode [|| bs ||], hdl))) ||] -- writeByteString -- sinkLazy ------------------------------------------------------------------------------- -- Streams ------------------------------------------------------------------------------- TODO : stdin -- TODO: stdout -- TODO: stderr
null
https://raw.githubusercontent.com/phadej/staged/b51c8c508af71ddb2aca4a75030da9b2c4f9e3dd/staged-streams-resourcet/src/Staged/Stream/ByteString.hs
haskell
writeByteString sinkLazy ----------------------------------------------------------------------------- Streams ----------------------------------------------------------------------------- TODO: stdout TODO: stderr
# LANGUAGE TemplateHaskell # module Staged.Stream.ByteString ( readByteString, ) where import Control.Monad.IO.Class (MonadIO (..)) import qualified Data.ByteString as BS import qualified Control.Monad.Trans.Resource as R import Staged.Commons import Staged.Stream.Type import Staged.Stream.Combinators (unfold) import Staged.Stream.Handle | Open a file and read strict ' ByteString ' chunks from it . readByteString :: R.MonadResource m => StreamM m FilePath BS.ByteString readByteString = withBinaryFile sReadMode $ unfold id $ \hdl k -> toCode [|| do bs <- liftIO (BS.hGetSome $$(fromCode hdl) 32768) if BS.null bs then $$(fromCode $ k Nothing) else $$(fromCode $ k (Just (toCode [|| bs ||], hdl))) ||] TODO : stdin
5f5eced2f977f522ce7bbe0835f5f81128ea69be092a045bc194ef34dee1517f
ragkousism/Guix-on-Hurd
smalltalk.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2013 < > Copyright © 2016 < > Copyright © 2016 < > Copyright © 2016 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU 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. ;;; ;;; GNU Guix 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 GNU . If not , see < / > . (define-module (gnu packages smalltalk) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system cmake) #:use-module (guix build-system gnu) #:use-module (gnu packages audio) #:use-module (gnu packages autotools) #:use-module (gnu packages base) #:use-module (gnu packages fontutils) #:use-module (gnu packages gl) #:use-module (gnu packages glib) #:use-module (gnu packages libffi) #:use-module (gnu packages libsigsegv) #:use-module (gnu packages linux) #:use-module (gnu packages pkg-config) #:use-module (gnu packages pulseaudio) #:use-module (gnu packages xorg) #:use-module (gnu packages zip)) (define-public smalltalk (package (name "smalltalk") (version "3.2.5") (source (origin (method url-fetch) (uri (string-append "mirror-" version ".tar.xz")) (sha256 (base32 "1k2ssrapfzhngc7bg1zrnd9n2vyxp9c9m70byvsma6wapbvib6l1")))) (build-system gnu-build-system) (native-inputs `(("libffi" ,libffi) ("libltdl" ,libltdl) ("libsigsegv" ,libsigsegv) ("pkg-config" ,pkg-config))) (inputs `(("zip" ,zip))) (arguments `(#:phases (alist-cons-before 'configure 'fix-libc (lambda _ (let ((libc (assoc-ref %build-inputs "libc"))) (substitute* "libc.la.in" (("@LIBC_SO_NAME@") "libc.so") (("@LIBC_SO_DIR@") (string-append libc "/lib"))))) %standard-phases))) (home-page "/") (synopsis "Smalltalk environment") (description "GNU Smalltalk is a free implementation of the Smalltalk language. It implements the ANSI standard for the language and also includes extra classes such as ones for networking and GUI programming.") (license license:gpl2+))) (define-public squeak-vm (package (name "squeak-vm") (version "4.10.2.2614") (source (origin (method url-fetch) (uri (string-append "/" "Squeak-" version "-src.tar.gz")) (sha256 (base32 "0bpwbnpy2sb4gylchfx50sha70z36bwgdxraym4vrr93l8pd3dix")) (modules '((guix build utils))) (snippet ;; Make builds bit-reproducible. '(begin (substitute* "unix/cmake/verstamp" (("vm_date=.*") "vm_date = \"1970-01-01\";\n") (("ux_version=.*") "ux_version = \"GNU\";\n")) (substitute* "unix/vm/config.cmake" (("\\(VM_BUILD_STRING.*") "(VM_BUILD_STRING \\\"Built with GNU Guix\\\")")))))) (inputs `(("alsa-lib" ,alsa-lib) ("dbus" ,dbus) ("freetype" ,freetype) ("libffi" ,libffi) ("libxrender" ,libxrender) ("mesa" ,mesa) ("pulseaudio" ,pulseaudio))) (native-inputs `(("pkg-config" ,pkg-config))) (build-system cmake-build-system) (arguments `(#:tests? #f ;no check target #:phases (modify-phases %standard-phases (add-after 'unpack 'remove-hardcoded-PATH (lambda _ ;; Remove hard-coded FHS PATH entries. (substitute* '("unix/cmake/squeak.in" "unix/cmake/squeak.sh.in") (("^PATH=.*") "")) #t)) (add-after 'unpack 'create-build-dir (lambda _ (mkdir "bld") #t)) (replace 'configure (lambda* (#:key outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out"))) (with-directory-excursion "bld" (zero? (system* "../unix/cmake/configure" (string-append "--prefix=" out) "--without-quartz")))))) (replace 'build (lambda _ (with-directory-excursion "bld" (zero? (system* "make")))))))) (synopsis "Smalltalk programming language and environment") (description "Squeak is a full-featured implementation of the Smalltalk programming language and environment based on (and largely compatible with) the original Smalltalk-80 system. Squeak has very powerful 2- and 3-D graphics, sound, video, MIDI, animation and other multimedia capabilities. It also includes a customisable framework for creating dynamic HTTP servers and interactively extensible Web sites.") (home-page "") (license license:x11)))
null
https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/gnu/packages/smalltalk.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix 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. Make builds bit-reproducible. no check target Remove hard-coded FHS PATH entries.
Copyright © 2013 < > Copyright © 2016 < > Copyright © 2016 < > Copyright © 2016 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages smalltalk) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system cmake) #:use-module (guix build-system gnu) #:use-module (gnu packages audio) #:use-module (gnu packages autotools) #:use-module (gnu packages base) #:use-module (gnu packages fontutils) #:use-module (gnu packages gl) #:use-module (gnu packages glib) #:use-module (gnu packages libffi) #:use-module (gnu packages libsigsegv) #:use-module (gnu packages linux) #:use-module (gnu packages pkg-config) #:use-module (gnu packages pulseaudio) #:use-module (gnu packages xorg) #:use-module (gnu packages zip)) (define-public smalltalk (package (name "smalltalk") (version "3.2.5") (source (origin (method url-fetch) (uri (string-append "mirror-" version ".tar.xz")) (sha256 (base32 "1k2ssrapfzhngc7bg1zrnd9n2vyxp9c9m70byvsma6wapbvib6l1")))) (build-system gnu-build-system) (native-inputs `(("libffi" ,libffi) ("libltdl" ,libltdl) ("libsigsegv" ,libsigsegv) ("pkg-config" ,pkg-config))) (inputs `(("zip" ,zip))) (arguments `(#:phases (alist-cons-before 'configure 'fix-libc (lambda _ (let ((libc (assoc-ref %build-inputs "libc"))) (substitute* "libc.la.in" (("@LIBC_SO_NAME@") "libc.so") (("@LIBC_SO_DIR@") (string-append libc "/lib"))))) %standard-phases))) (home-page "/") (synopsis "Smalltalk environment") (description "GNU Smalltalk is a free implementation of the Smalltalk language. It implements the ANSI standard for the language and also includes extra classes such as ones for networking and GUI programming.") (license license:gpl2+))) (define-public squeak-vm (package (name "squeak-vm") (version "4.10.2.2614") (source (origin (method url-fetch) (uri (string-append "/" "Squeak-" version "-src.tar.gz")) (sha256 (base32 "0bpwbnpy2sb4gylchfx50sha70z36bwgdxraym4vrr93l8pd3dix")) (modules '((guix build utils))) (snippet '(begin (substitute* "unix/cmake/verstamp" (("vm_date=.*") "vm_date = \"1970-01-01\";\n") (("ux_version=.*") "ux_version = \"GNU\";\n")) (substitute* "unix/vm/config.cmake" (("\\(VM_BUILD_STRING.*") "(VM_BUILD_STRING \\\"Built with GNU Guix\\\")")))))) (inputs `(("alsa-lib" ,alsa-lib) ("dbus" ,dbus) ("freetype" ,freetype) ("libffi" ,libffi) ("libxrender" ,libxrender) ("mesa" ,mesa) ("pulseaudio" ,pulseaudio))) (native-inputs `(("pkg-config" ,pkg-config))) (build-system cmake-build-system) (arguments #:phases (modify-phases %standard-phases (add-after 'unpack 'remove-hardcoded-PATH (lambda _ (substitute* '("unix/cmake/squeak.in" "unix/cmake/squeak.sh.in") (("^PATH=.*") "")) #t)) (add-after 'unpack 'create-build-dir (lambda _ (mkdir "bld") #t)) (replace 'configure (lambda* (#:key outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out"))) (with-directory-excursion "bld" (zero? (system* "../unix/cmake/configure" (string-append "--prefix=" out) "--without-quartz")))))) (replace 'build (lambda _ (with-directory-excursion "bld" (zero? (system* "make")))))))) (synopsis "Smalltalk programming language and environment") (description "Squeak is a full-featured implementation of the Smalltalk programming language and environment based on (and largely compatible with) the original Smalltalk-80 system. Squeak has very powerful 2- and 3-D graphics, sound, video, MIDI, animation and other multimedia capabilities. It also includes a customisable framework for creating dynamic HTTP servers and interactively extensible Web sites.") (home-page "") (license license:x11)))
e8effb4de1a2cfa830c8763946687d9f7ae30a7fdccd4b674710a01f1c6f816d
kunik/sorting-algorithms
Merge.hs
module Sorting.Merge ( sort ) where sort :: (Ord a) => [a] -> [a] sort [] = [] sort [x] = [x] sort xs = sortBoth $ splitAt ((length xs) `div` 2) xs where sortBoth (x,y) = joinOrdered (sort x, sort y) joinOrdered ([], y) = y joinOrdered (x, []) = x joinOrdered (x:xs, y:ys) | x < y = x:(joinOrdered (xs,y:ys)) | otherwise = y:(joinOrdered (x:xs,ys))
null
https://raw.githubusercontent.com/kunik/sorting-algorithms/0ada50e08fff8a420a55d912acf084f21616082f/Sorting/Merge.hs
haskell
module Sorting.Merge ( sort ) where sort :: (Ord a) => [a] -> [a] sort [] = [] sort [x] = [x] sort xs = sortBoth $ splitAt ((length xs) `div` 2) xs where sortBoth (x,y) = joinOrdered (sort x, sort y) joinOrdered ([], y) = y joinOrdered (x, []) = x joinOrdered (x:xs, y:ys) | x < y = x:(joinOrdered (xs,y:ys)) | otherwise = y:(joinOrdered (x:xs,ys))