_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
35c0746a058dac82cd067a7acc626cf5c33d23ab96a136ebe5d560e0ad9fe9b6
mchakravarty/lets-program
Game.hs
-- Compile this with 'ghc -o Game Game.hs' and run it with './Game'. import Data.List import Graphics.Gloss.Game -- Window size width = 600 height = 400 -- A sprite representing our character slimeSprite = scale 0.5 0.5 (bmp "Slime.bmp") slimeWidth = fst (snd (boundingBox slimeSprite)) slimeHeight = snd (snd (boundingBox slimeSprite)) -- Additional sprites for a simple animation slimeSprite2 = scale 0.5 0.5 (bmp "Slime2.bmp") slimeSprite3 = scale 0.5 0.5 (bmp "Slime3.bmp") slimeSprite4 = scale 0.5 0.5 (bmp "Slime4.bmp") -- Our game world consists of both the location and the vertical velocity of our character, the state of the character -- animation as well as a list of all currently pressed keys. data World = World Point Float Animation [Char] This starts our gamein a window with a give size , running at 30 frames per second . -- -- The argument 'World (0, 0) 0' is the initial state of our game world, where our character is at the centre of the -- window and has no velocity. -- main = playInScene (InWindow "Slime is here!" (round width, round height) (50, 50)) white 30 (World (0, 0) 0 noAnimation []) level handle [applyMovement, applyVelocity, applyGravity] -- Description of a level as a scene. Scenes depend on the state of the world, which means their rendering changes as the -- world changes. Here, we have the character, where both its location and animation depend on the world state. level = translating spritePosition (animating spriteAnimation slimeSprite) -- Extract the character position from the world. spritePosition (World (x, y) v anim keys) = (x, y) -- Extract the character animation from the world. spriteAnimation (World (x, y) v anim keys) = anim -- Pressing the spacebar makes the character jump. All character keys are tracked in the world state. handle now (EventKey (Char ch) Down _ _) (World (x, y) v anim keys) = World (x, y) v anim (ch : keys) handle now (EventKey (Char ch) Up _ _) (World (x, y) v anim keys) = World (x, y) v anim (delete ch keys) handle now (EventKey (SpecialKey KeySpace) Down _ _) (World (x, y) v anim keys) = World (x, y) 8 (animation [slimeSprite2, slimeSprite3, slimeSprite4] 0.1 now) keys handle now event world = world -- don't change the world in case of any other events -- Move horizontally, but box the character in at the window boundaries. moveX (x, y) offset = if x + offset < (-width / 2) + slimeWidth / 2 then ((-width / 2) + slimeWidth / 2, y) else if x + offset > width / 2 - slimeWidth / 2 then (width / 2 - slimeWidth / 2, y) else (x + offset, y) -- Move vertically, but box the character in at the window boundaries. moveY (x, y) offset = if y + offset < (-height / 2) + slimeHeight / 2 then (x, (-height / 2) + slimeHeight / 2) else if y + offset > height / 2 - slimeHeight / 2 then (x, height / 2 - slimeHeight / 2) else (x, y + offset) -- A pressed 'a' and 'd' key moves the character a fixed distance left or right. applyMovement _now _time (World (x, y) v anim keys) = if elem 'a' keys then World (moveX (x, y) (-10)) v anim keys else if elem 'd' keys then World (moveX (x, y) 10) v anim keys else World (x, y) v anim keys -- Each frame, add the veclocity to the verticial position (y-axis). (A negative velocity corresponds to a downward movement.) applyVelocity _now _time (World (x, y) v anim keys) = World (moveY (x, y) v) v anim keys -- We simulate gravity by decrease the velocity slightly on each frame, corresponding to a downward acceleration. -- -- We bounce of the bottom edge by reverting the velocity (with a damping factor). -- applyGravity _now _time (World (x, y) v anim keys) = World (x, y) (if y <= (-200) + slimeHeight / 2 then v * (-0.5) else v - 0.5) anim keys
null
https://raw.githubusercontent.com/mchakravarty/lets-program/f0b636fd2f2b7db77b70c5208cad53c9fa493f44/step5/Game.hs
haskell
Compile this with 'ghc -o Game Game.hs' and run it with './Game'. Window size A sprite representing our character Additional sprites for a simple animation Our game world consists of both the location and the vertical velocity of our character, the state of the character animation as well as a list of all currently pressed keys. The argument 'World (0, 0) 0' is the initial state of our game world, where our character is at the centre of the window and has no velocity. Description of a level as a scene. Scenes depend on the state of the world, which means their rendering changes as the world changes. Here, we have the character, where both its location and animation depend on the world state. Extract the character position from the world. Extract the character animation from the world. Pressing the spacebar makes the character jump. All character keys are tracked in the world state. don't change the world in case of any other events Move horizontally, but box the character in at the window boundaries. Move vertically, but box the character in at the window boundaries. A pressed 'a' and 'd' key moves the character a fixed distance left or right. Each frame, add the veclocity to the verticial position (y-axis). (A negative velocity corresponds to a downward movement.) We simulate gravity by decrease the velocity slightly on each frame, corresponding to a downward acceleration. We bounce of the bottom edge by reverting the velocity (with a damping factor).
import Data.List import Graphics.Gloss.Game width = 600 height = 400 slimeSprite = scale 0.5 0.5 (bmp "Slime.bmp") slimeWidth = fst (snd (boundingBox slimeSprite)) slimeHeight = snd (snd (boundingBox slimeSprite)) slimeSprite2 = scale 0.5 0.5 (bmp "Slime2.bmp") slimeSprite3 = scale 0.5 0.5 (bmp "Slime3.bmp") slimeSprite4 = scale 0.5 0.5 (bmp "Slime4.bmp") data World = World Point Float Animation [Char] This starts our gamein a window with a give size , running at 30 frames per second . main = playInScene (InWindow "Slime is here!" (round width, round height) (50, 50)) white 30 (World (0, 0) 0 noAnimation []) level handle [applyMovement, applyVelocity, applyGravity] level = translating spritePosition (animating spriteAnimation slimeSprite) spritePosition (World (x, y) v anim keys) = (x, y) spriteAnimation (World (x, y) v anim keys) = anim handle now (EventKey (Char ch) Down _ _) (World (x, y) v anim keys) = World (x, y) v anim (ch : keys) handle now (EventKey (Char ch) Up _ _) (World (x, y) v anim keys) = World (x, y) v anim (delete ch keys) handle now (EventKey (SpecialKey KeySpace) Down _ _) (World (x, y) v anim keys) = World (x, y) 8 (animation [slimeSprite2, slimeSprite3, slimeSprite4] 0.1 now) keys moveX (x, y) offset = if x + offset < (-width / 2) + slimeWidth / 2 then ((-width / 2) + slimeWidth / 2, y) else if x + offset > width / 2 - slimeWidth / 2 then (width / 2 - slimeWidth / 2, y) else (x + offset, y) moveY (x, y) offset = if y + offset < (-height / 2) + slimeHeight / 2 then (x, (-height / 2) + slimeHeight / 2) else if y + offset > height / 2 - slimeHeight / 2 then (x, height / 2 - slimeHeight / 2) else (x, y + offset) applyMovement _now _time (World (x, y) v anim keys) = if elem 'a' keys then World (moveX (x, y) (-10)) v anim keys else if elem 'd' keys then World (moveX (x, y) 10) v anim keys else World (x, y) v anim keys applyVelocity _now _time (World (x, y) v anim keys) = World (moveY (x, y) v) v anim keys applyGravity _now _time (World (x, y) v anim keys) = World (x, y) (if y <= (-200) + slimeHeight / 2 then v * (-0.5) else v - 0.5) anim keys
a40e45099c336d0a391055f65d0485a46c9124c3663d1651621260c27dc680c4
electric-sql/vaxine
vx_test_utils.erl
-module(vx_test_utils). -export([init_multi_dc/4, start_node/4, init_clean_node/2, init_clean_node/3, init_testsuite/0, port/3, node_modifier/1 ]). -export([ an_connect/0, an_connect/1, an_start_tx/1, an_commit_tx/2, an_disconnect/1, vx_connect/0, vx_connect/1, vx_disconnect/1, with_connection/1, with_connection/2, with_replication/3, with_replication_con/2, with_replication_con/3 ]). -export([assert_count/2, assert_count/3, assert_count_msg/2, assert_count_msg/3, assert_receive/1 ]). -include_lib("eunit/include/eunit.hrl"). -include_lib("vx_client/include/vx_proto.hrl"). -define(APP, vx_server). init_multi_dc(Suite, Config, ClusterDcSetup, ErlangEnv) -> ct:pal("[~p]", [Suite]), init_testsuite(), Clusters = set_up_clusters_common([{suite_name, ?MODULE} | Config], ClusterDcSetup, ErlangEnv), Nodes = hd(Clusters), [{clusters, Clusters} | [{nodes, Nodes} | Config]]. start_node({Name, OsEnv}, PortModifier, Config, ErlangEnv) -> NodeConfig = [{monitor_master, true}, {env, OsEnv} ], case ct_slave:start(Name, NodeConfig) of {ok, Node} -> %% code path for compiled dependencies CodePath = lists:filter(fun filelib:is_dir/1, code:get_path()) , lists:foreach(fun(P) -> rpc:call(Node, code, add_patha, [P]) end, CodePath), init_clean_node(Node, PortModifier, ErlangEnv), ct:pal("Node ~p started with ports ~p-~p and config ~p~n", [Name, PortModifier, PortModifier + 5, Config]), {connect, Node}; {error, already_started, Node} -> ct:log("Node ~p already started, reusing node", [Node]), {ready, Node}; {error, Reason, Node} -> ct:pal("Error starting node ~w, reason ~w, will retry", [Node, Reason]), ct_slave:stop(Name), time_utils:wait_until_offline(Node), start_node({Name, OsEnv}, PortModifier, Config, ErlangEnv) end. init_clean_node(Node, PortModifier) -> ok = init_clean_load_applications(Node), init_clean_node_without_loading(Node, PortModifier), ensure_started(Node). init_clean_node(Node, PortModifier, Environment) -> ok = init_clean_load_applications(Node), init_clean_node_without_loading(Node, PortModifier), [ rpc:call(Node, application, set_env, [ App, Key, Value ]) || {App, Key, Value} <- Environment ], ensure_started(Node). init_clean_load_applications(Node) -> % load application to allow for configuring the environment before starting ok = rpc:call(Node, application, load, [riak_core]), ok = rpc:call(Node, application, load, [antidote_stats]), ok = rpc:call(Node, application, load, [ranch]), ok = rpc:call(Node, application, load, [antidote]), ok = rpc:call(Node, application, load, [vx_server]), ok. init_clean_node_without_loading(Node, PortModifier) -> %% get remote working dir of node {ok, NodeWorkingDir} = rpc:call(Node, file, get_cwd, []), %% DATA DIRS ok = rpc:call(Node, application, set_env, [antidote, data_dir, filename:join([NodeWorkingDir, Node, "antidote-data"])]), ok = rpc:call(Node, application, set_env, [riak_core, ring_state_dir, filename:join([NodeWorkingDir, Node, "data"])]), ok = rpc:call(Node, application, set_env, [riak_core, platform_data_dir, filename:join([NodeWorkingDir, Node, "data"])]), PORTS Port = 10000 + PortModifier * 10, ok = rpc:call(Node, application, set_env, [antidote, logreader_port, Port]), ok = rpc:call(Node, application, set_env, [antidote, pubsub_port, Port + 1]), ok = rpc:call(Node, application, set_env, [ranch, pb_port, Port + 2]), ok = rpc:call(Node, application, set_env, [riak_core, handoff_port, Port + 3]), ok = rpc:call(Node, application, set_env, [antidote_stats, metrics_port, Port + 4]), ok = rpc:call(Node, application, set_env, [?APP, pb_port, Port + 5]), %% LOGGING Configuration %% add additional logging handlers to ensure easy access to remote node logs %% for each logging level LogRoot = filename:join([NodeWorkingDir, Node, "logs"]), %% set the logger configuration ok = rpc:call(Node, application, set_env, [antidote, logger, log_config(LogRoot)]), %% set primary output level, no filter rpc:call(Node, logger, set_primary_config, [level, all]), %% load additional logger handlers at remote node rpc:call(Node, logger, add_handlers, [antidote]), %% redirect slave logs to ct_master logs ok = rpc:call(Node, application, set_env, [antidote, ct_master, node()]), ConfLog = #{level => debug, formatter => {logger_formatter, #{single_line => true, max_size => 2048}}, config => #{type => standard_io}}, _ = rpc:call(Node, logger, add_handler, [antidote_redirect_ct, ct_redirect_handler, ConfLog]), %% ANTIDOTE Configuration reduce number of actual log files created to 4 , reduces start - up time of node ok = rpc:call(Node, application, set_env, [riak_core, ring_creation_size, 4]), ok = rpc:call(Node, application, set_env, [antidote, sync_log, true]), ok. ensure_started(Node) -> VX_SERVER Configuration rpc:call(Node, application, ensure_all_started, [?APP]). log_config(LogDir) -> DebugConfig = #{level => debug, formatter => {logger_formatter, #{single_line => true, max_size => 2048}}, config => #{type => {file, filename:join(LogDir, "debug.log")}}}, InfoConfig = #{level => info, formatter => {logger_formatter, #{single_line => true, max_size => 2048}}, config => #{type => {file, filename:join(LogDir, "info.log")}}}, NoticeConfig = #{level => notice, formatter => {logger_formatter, #{single_line => true, max_size => 2048}}, config => #{type => {file, filename:join(LogDir, "notice.log")}}}, WarningConfig = #{level => warning, formatter => {logger_formatter, #{single_line => true, max_size => 2048}}, config => #{type => {file, filename:join(LogDir, "warning.log")}}}, ErrorConfig = #{level => error, formatter => {logger_formatter, #{single_line => true, max_size => 2048}}, config => #{type => {file, filename:join(LogDir, "error.log")}}}, [ {handler, debug_antidote, logger_std_h, DebugConfig}, {handler, info_antidote, logger_std_h, InfoConfig}, {handler, notice_antidote, logger_std_h, NoticeConfig}, {handler, warning_antidote, logger_std_h, WarningConfig}, {handler, error_antidote, logger_std_h, ErrorConfig} ]. init_testsuite() -> {ok, Hostname} = inet:gethostname(), case net_kernel:start([list_to_atom("runner@" ++ Hostname), shortnames]) of {ok, _} -> ok; {error, {already_started, _}} -> ok; {error, {{already_started, _}, _}} -> ok end. port(antidote, logreader_port, N) -> port(N, 0); port(antidote, pubsub_port, N) -> port(N, 1); port(antidote, pb_port, N) -> port(N, 2); port(antidote, handoff_port, N) -> port(N, 3); port(antidote, metric_port, N) -> port(N, 4); port(?APP, pb_port, N) -> port(N, 5). port(PortModifier, SeqNum) -> 10000 + PortModifier * 10 + SeqNum. node_modifier(dev11) -> 1; node_modifier(dev12) -> 2; node_modifier(dev21) -> 3. set_up_clusters_common(Config, ClusterDcSetup, ErlangEnv) -> StartDCs = fun(Nodes) -> %% start each node Cl = pmap( fun({N, Env}) -> PortModified = node_modifier(N), start_node({N, Env}, PortModified, Config, ErlangEnv) end, Nodes), [{Status, Claimant} | OtherNodes] = Cl, %% check if node was reused or not case Status of ready -> ok; connect -> ct:pal("Creating a ring for claimant ~p and other nodes ~p", [Claimant, unpack(OtherNodes)]), ok = rpc:call(Claimant, antidote_dc_manager, add_nodes_to_dc, [unpack(Cl)]) end, Cl end, Clusters = pmap(fun(Cluster) -> StartDCs(Cluster) end, ClusterDcSetup), %% DCs started, but not connected yet pmap( fun([{Status, MainNode} | _] = CurrentCluster) -> case Status of ready -> ok; connect -> ct:pal("~p of ~p subscribing to other external DCs", [MainNode, unpack(CurrentCluster)]), Descriptors = lists:map(fun([{_Status, FirstNode} | _]) -> {ok, Descriptor} = rpc:call(FirstNode, antidote_dc_manager, get_connection_descriptor, []), Descriptor end, Clusters), subscribe to descriptors of other ok = rpc:call(MainNode, antidote_dc_manager, subscribe_updates_from, [Descriptors]) end end, Clusters), ct:log("Clusters joined and data centers connected connected: ~p", [ClusterDcSetup]), [unpack(DC) || DC <- Clusters]. -spec pmap(fun(), list()) -> list(). pmap(F, L) -> Parent = self(), lists:foldl( fun(X, N) -> spawn_link(fun() -> Parent ! {pmap, N, F(X)} end), N+1 end, 0, L), L2 = [receive {pmap, N, R} -> {N, R} end || _ <- L], {_, L3} = lists:unzip(lists:keysort(1, L2)), L3. -spec unpack([{ready | connect, atom()}]) -> [atom()]. unpack(NodesWithStatus) -> [Node || {_Status, Node} <- NodesWithStatus]. get_name(Node) -> [Node0, _Host] = string:split(atom_to_list(Node), "@"), list_to_atom(Node0). an_connect() -> an_connect_int(0). an_connect(Node) when is_atom(Node) -> an_connect_int(node_modifier(get_name(Node))). an_connect_int(N) -> antidotec_pb_socket:start_link("127.0.0.1", vx_test_utils:port(antidote, pb_port, N)). an_start_tx(Pid) -> antidotec_pb:start_transaction(Pid, ignore, [{static, false}]). an_commit_tx(Pid, TxId) -> antidotec_pb:commit_transaction(Pid, TxId). an_disconnect(Pid) -> antidotec_pb_socket:stop(Pid). vx_connect() -> vx_connect_int(0). vx_connect(Node) -> vx_connect_int(node_modifier(get_name(Node))). vx_connect_int(N) -> vx_client:connect("127.0.0.1", vx_test_utils:port(vx_server, pb_port, N), []). vx_disconnect(C) -> vx_client:stop(C). with_connection(Node, Fun) -> ct:log("connect vx_client connect~n"), {ok, C} = vx_connect(Node), try Fun(C) after ct:log("disconnect vx_client connect~n"), vx_disconnect(C) end. with_replication(C, Opts, Fun) -> ok = vx_client:start_replication(C, Opts), ct:log("test replication started on: ~p~n", [C]), try Fun(C) after ct:log("test replication stopped on: ~p~n", [C]), vx_client:stop_replication(C) end. with_replication_con(Node, Opts, Fun) -> with_connection(Node, fun(C) -> with_replication(C, Opts, Fun) end). with_connection(Fun) -> {ok, C} = vx_connect(), try Fun(C) after vx_disconnect(C) end. with_replication_con(Opts, Fun) -> with_connection( fun(C) -> with_replication(C, Opts, Fun) end). assert_receive(Timeout) -> receive M -> erlang:error({unexpected_msg, M}) after Timeout -> ok end. assert_count(N, Timeout) -> assert_count(N, Timeout, fun(M) -> M end). assert_count_msg(N, Timeout) -> assert_count(N, Timeout, fun(#vx_client_msg{msg = Msg}) -> {L, R} = Msg#vx_wal_txn.wal_offset, ?assert( ((0 < L) andalso (L < R)) orelse ((0 == L) andalso (L < R)) ), Msg end). assert_count_msg(Source, N, Timeout) -> assert_count(N, Timeout, fun(#vx_client_msg{pid = Pid, msg = Msg}) when Pid == Source -> {L, R} = Msg#vx_wal_txn.wal_offset, ?assert( ((0 < L) andalso (L < R)) orelse ((0 == L) andalso (L < R)) ), Msg end). assert_count(0, _Timeout, _Fun) -> []; assert_count(N, Timeout, Fun) -> receive M -> ct:log("received: ~p~n", [M]), [Fun(M) | assert_count(N-1, Timeout, Fun)] after Timeout -> ct:log("timeout~n"), erlang:error({not_sufficient_msg_count, N}) end.
null
https://raw.githubusercontent.com/electric-sql/vaxine/7803f96e28203fff08ef7973257225897df1e552/apps/vx_server/test/vx_test_utils.erl
erlang
code path for compiled dependencies load application to allow for configuring the environment before starting get remote working dir of node DATA DIRS LOGGING Configuration add additional logging handlers to ensure easy access to remote node logs for each logging level set the logger configuration set primary output level, no filter load additional logger handlers at remote node redirect slave logs to ct_master logs ANTIDOTE Configuration start each node check if node was reused or not DCs started, but not connected yet
-module(vx_test_utils). -export([init_multi_dc/4, start_node/4, init_clean_node/2, init_clean_node/3, init_testsuite/0, port/3, node_modifier/1 ]). -export([ an_connect/0, an_connect/1, an_start_tx/1, an_commit_tx/2, an_disconnect/1, vx_connect/0, vx_connect/1, vx_disconnect/1, with_connection/1, with_connection/2, with_replication/3, with_replication_con/2, with_replication_con/3 ]). -export([assert_count/2, assert_count/3, assert_count_msg/2, assert_count_msg/3, assert_receive/1 ]). -include_lib("eunit/include/eunit.hrl"). -include_lib("vx_client/include/vx_proto.hrl"). -define(APP, vx_server). init_multi_dc(Suite, Config, ClusterDcSetup, ErlangEnv) -> ct:pal("[~p]", [Suite]), init_testsuite(), Clusters = set_up_clusters_common([{suite_name, ?MODULE} | Config], ClusterDcSetup, ErlangEnv), Nodes = hd(Clusters), [{clusters, Clusters} | [{nodes, Nodes} | Config]]. start_node({Name, OsEnv}, PortModifier, Config, ErlangEnv) -> NodeConfig = [{monitor_master, true}, {env, OsEnv} ], case ct_slave:start(Name, NodeConfig) of {ok, Node} -> CodePath = lists:filter(fun filelib:is_dir/1, code:get_path()) , lists:foreach(fun(P) -> rpc:call(Node, code, add_patha, [P]) end, CodePath), init_clean_node(Node, PortModifier, ErlangEnv), ct:pal("Node ~p started with ports ~p-~p and config ~p~n", [Name, PortModifier, PortModifier + 5, Config]), {connect, Node}; {error, already_started, Node} -> ct:log("Node ~p already started, reusing node", [Node]), {ready, Node}; {error, Reason, Node} -> ct:pal("Error starting node ~w, reason ~w, will retry", [Node, Reason]), ct_slave:stop(Name), time_utils:wait_until_offline(Node), start_node({Name, OsEnv}, PortModifier, Config, ErlangEnv) end. init_clean_node(Node, PortModifier) -> ok = init_clean_load_applications(Node), init_clean_node_without_loading(Node, PortModifier), ensure_started(Node). init_clean_node(Node, PortModifier, Environment) -> ok = init_clean_load_applications(Node), init_clean_node_without_loading(Node, PortModifier), [ rpc:call(Node, application, set_env, [ App, Key, Value ]) || {App, Key, Value} <- Environment ], ensure_started(Node). init_clean_load_applications(Node) -> ok = rpc:call(Node, application, load, [riak_core]), ok = rpc:call(Node, application, load, [antidote_stats]), ok = rpc:call(Node, application, load, [ranch]), ok = rpc:call(Node, application, load, [antidote]), ok = rpc:call(Node, application, load, [vx_server]), ok. init_clean_node_without_loading(Node, PortModifier) -> {ok, NodeWorkingDir} = rpc:call(Node, file, get_cwd, []), ok = rpc:call(Node, application, set_env, [antidote, data_dir, filename:join([NodeWorkingDir, Node, "antidote-data"])]), ok = rpc:call(Node, application, set_env, [riak_core, ring_state_dir, filename:join([NodeWorkingDir, Node, "data"])]), ok = rpc:call(Node, application, set_env, [riak_core, platform_data_dir, filename:join([NodeWorkingDir, Node, "data"])]), PORTS Port = 10000 + PortModifier * 10, ok = rpc:call(Node, application, set_env, [antidote, logreader_port, Port]), ok = rpc:call(Node, application, set_env, [antidote, pubsub_port, Port + 1]), ok = rpc:call(Node, application, set_env, [ranch, pb_port, Port + 2]), ok = rpc:call(Node, application, set_env, [riak_core, handoff_port, Port + 3]), ok = rpc:call(Node, application, set_env, [antidote_stats, metrics_port, Port + 4]), ok = rpc:call(Node, application, set_env, [?APP, pb_port, Port + 5]), LogRoot = filename:join([NodeWorkingDir, Node, "logs"]), ok = rpc:call(Node, application, set_env, [antidote, logger, log_config(LogRoot)]), rpc:call(Node, logger, set_primary_config, [level, all]), rpc:call(Node, logger, add_handlers, [antidote]), ok = rpc:call(Node, application, set_env, [antidote, ct_master, node()]), ConfLog = #{level => debug, formatter => {logger_formatter, #{single_line => true, max_size => 2048}}, config => #{type => standard_io}}, _ = rpc:call(Node, logger, add_handler, [antidote_redirect_ct, ct_redirect_handler, ConfLog]), reduce number of actual log files created to 4 , reduces start - up time of node ok = rpc:call(Node, application, set_env, [riak_core, ring_creation_size, 4]), ok = rpc:call(Node, application, set_env, [antidote, sync_log, true]), ok. ensure_started(Node) -> VX_SERVER Configuration rpc:call(Node, application, ensure_all_started, [?APP]). log_config(LogDir) -> DebugConfig = #{level => debug, formatter => {logger_formatter, #{single_line => true, max_size => 2048}}, config => #{type => {file, filename:join(LogDir, "debug.log")}}}, InfoConfig = #{level => info, formatter => {logger_formatter, #{single_line => true, max_size => 2048}}, config => #{type => {file, filename:join(LogDir, "info.log")}}}, NoticeConfig = #{level => notice, formatter => {logger_formatter, #{single_line => true, max_size => 2048}}, config => #{type => {file, filename:join(LogDir, "notice.log")}}}, WarningConfig = #{level => warning, formatter => {logger_formatter, #{single_line => true, max_size => 2048}}, config => #{type => {file, filename:join(LogDir, "warning.log")}}}, ErrorConfig = #{level => error, formatter => {logger_formatter, #{single_line => true, max_size => 2048}}, config => #{type => {file, filename:join(LogDir, "error.log")}}}, [ {handler, debug_antidote, logger_std_h, DebugConfig}, {handler, info_antidote, logger_std_h, InfoConfig}, {handler, notice_antidote, logger_std_h, NoticeConfig}, {handler, warning_antidote, logger_std_h, WarningConfig}, {handler, error_antidote, logger_std_h, ErrorConfig} ]. init_testsuite() -> {ok, Hostname} = inet:gethostname(), case net_kernel:start([list_to_atom("runner@" ++ Hostname), shortnames]) of {ok, _} -> ok; {error, {already_started, _}} -> ok; {error, {{already_started, _}, _}} -> ok end. port(antidote, logreader_port, N) -> port(N, 0); port(antidote, pubsub_port, N) -> port(N, 1); port(antidote, pb_port, N) -> port(N, 2); port(antidote, handoff_port, N) -> port(N, 3); port(antidote, metric_port, N) -> port(N, 4); port(?APP, pb_port, N) -> port(N, 5). port(PortModifier, SeqNum) -> 10000 + PortModifier * 10 + SeqNum. node_modifier(dev11) -> 1; node_modifier(dev12) -> 2; node_modifier(dev21) -> 3. set_up_clusters_common(Config, ClusterDcSetup, ErlangEnv) -> StartDCs = fun(Nodes) -> Cl = pmap( fun({N, Env}) -> PortModified = node_modifier(N), start_node({N, Env}, PortModified, Config, ErlangEnv) end, Nodes), [{Status, Claimant} | OtherNodes] = Cl, case Status of ready -> ok; connect -> ct:pal("Creating a ring for claimant ~p and other nodes ~p", [Claimant, unpack(OtherNodes)]), ok = rpc:call(Claimant, antidote_dc_manager, add_nodes_to_dc, [unpack(Cl)]) end, Cl end, Clusters = pmap(fun(Cluster) -> StartDCs(Cluster) end, ClusterDcSetup), pmap( fun([{Status, MainNode} | _] = CurrentCluster) -> case Status of ready -> ok; connect -> ct:pal("~p of ~p subscribing to other external DCs", [MainNode, unpack(CurrentCluster)]), Descriptors = lists:map(fun([{_Status, FirstNode} | _]) -> {ok, Descriptor} = rpc:call(FirstNode, antidote_dc_manager, get_connection_descriptor, []), Descriptor end, Clusters), subscribe to descriptors of other ok = rpc:call(MainNode, antidote_dc_manager, subscribe_updates_from, [Descriptors]) end end, Clusters), ct:log("Clusters joined and data centers connected connected: ~p", [ClusterDcSetup]), [unpack(DC) || DC <- Clusters]. -spec pmap(fun(), list()) -> list(). pmap(F, L) -> Parent = self(), lists:foldl( fun(X, N) -> spawn_link(fun() -> Parent ! {pmap, N, F(X)} end), N+1 end, 0, L), L2 = [receive {pmap, N, R} -> {N, R} end || _ <- L], {_, L3} = lists:unzip(lists:keysort(1, L2)), L3. -spec unpack([{ready | connect, atom()}]) -> [atom()]. unpack(NodesWithStatus) -> [Node || {_Status, Node} <- NodesWithStatus]. get_name(Node) -> [Node0, _Host] = string:split(atom_to_list(Node), "@"), list_to_atom(Node0). an_connect() -> an_connect_int(0). an_connect(Node) when is_atom(Node) -> an_connect_int(node_modifier(get_name(Node))). an_connect_int(N) -> antidotec_pb_socket:start_link("127.0.0.1", vx_test_utils:port(antidote, pb_port, N)). an_start_tx(Pid) -> antidotec_pb:start_transaction(Pid, ignore, [{static, false}]). an_commit_tx(Pid, TxId) -> antidotec_pb:commit_transaction(Pid, TxId). an_disconnect(Pid) -> antidotec_pb_socket:stop(Pid). vx_connect() -> vx_connect_int(0). vx_connect(Node) -> vx_connect_int(node_modifier(get_name(Node))). vx_connect_int(N) -> vx_client:connect("127.0.0.1", vx_test_utils:port(vx_server, pb_port, N), []). vx_disconnect(C) -> vx_client:stop(C). with_connection(Node, Fun) -> ct:log("connect vx_client connect~n"), {ok, C} = vx_connect(Node), try Fun(C) after ct:log("disconnect vx_client connect~n"), vx_disconnect(C) end. with_replication(C, Opts, Fun) -> ok = vx_client:start_replication(C, Opts), ct:log("test replication started on: ~p~n", [C]), try Fun(C) after ct:log("test replication stopped on: ~p~n", [C]), vx_client:stop_replication(C) end. with_replication_con(Node, Opts, Fun) -> with_connection(Node, fun(C) -> with_replication(C, Opts, Fun) end). with_connection(Fun) -> {ok, C} = vx_connect(), try Fun(C) after vx_disconnect(C) end. with_replication_con(Opts, Fun) -> with_connection( fun(C) -> with_replication(C, Opts, Fun) end). assert_receive(Timeout) -> receive M -> erlang:error({unexpected_msg, M}) after Timeout -> ok end. assert_count(N, Timeout) -> assert_count(N, Timeout, fun(M) -> M end). assert_count_msg(N, Timeout) -> assert_count(N, Timeout, fun(#vx_client_msg{msg = Msg}) -> {L, R} = Msg#vx_wal_txn.wal_offset, ?assert( ((0 < L) andalso (L < R)) orelse ((0 == L) andalso (L < R)) ), Msg end). assert_count_msg(Source, N, Timeout) -> assert_count(N, Timeout, fun(#vx_client_msg{pid = Pid, msg = Msg}) when Pid == Source -> {L, R} = Msg#vx_wal_txn.wal_offset, ?assert( ((0 < L) andalso (L < R)) orelse ((0 == L) andalso (L < R)) ), Msg end). assert_count(0, _Timeout, _Fun) -> []; assert_count(N, Timeout, Fun) -> receive M -> ct:log("received: ~p~n", [M]), [Fun(M) | assert_count(N-1, Timeout, Fun)] after Timeout -> ct:log("timeout~n"), erlang:error({not_sufficient_msg_count, N}) end.
9b1f89d8e833fa9cc5b1cfc6a326dccf6fc37868815060d474c366df2940fbd4
marcoheisig/adventofcode
day-07.lisp
(defpackage :adventofcode-2020-day-7 (:use :cl)) (in-package :adventofcode-2020-day-7)
null
https://raw.githubusercontent.com/marcoheisig/adventofcode/e96a0da17cd79f424af984ed2648b49ffdacb893/2020/day-07/day-07.lisp
lisp
(defpackage :adventofcode-2020-day-7 (:use :cl)) (in-package :adventofcode-2020-day-7)
937f9fc50f8ed52120cffcdd7758c7837bad42866571e9c8b0e6a9151f34804b
GrammaticalFramework/gf-core
Signal.hs
{-# OPTIONS -cpp #-} ---------------------------------------------------------------------- -- | -- Module : GF.System.Signal Maintainer : -- Stability : (stability) -- Portability : (portability) -- > CVS $ Date : 2005/11/11 11:12:50 $ -- > CVS $Author: bringert $ > CVS $ Revision : 1.3 $ -- Import the right singal handling module . ----------------------------------------------------------------------------- module GF.System.Signal (runInterruptibly,blockInterrupt) where #ifdef USE_INTERRUPT import GF.System.UseSignal (runInterruptibly,blockInterrupt) #else import GF.System.NoSignal (runInterruptibly,blockInterrupt) #endif
null
https://raw.githubusercontent.com/GrammaticalFramework/gf-core/9b4f2dd18b64b770aaebfa1885085e8e3447f119/src/compiler/GF/System/Signal.hs
haskell
# OPTIONS -cpp # -------------------------------------------------------------------- | Module : GF.System.Signal Stability : (stability) Portability : (portability) > CVS $Author: bringert $ ---------------------------------------------------------------------------
Maintainer : > CVS $ Date : 2005/11/11 11:12:50 $ > CVS $ Revision : 1.3 $ Import the right singal handling module . module GF.System.Signal (runInterruptibly,blockInterrupt) where #ifdef USE_INTERRUPT import GF.System.UseSignal (runInterruptibly,blockInterrupt) #else import GF.System.NoSignal (runInterruptibly,blockInterrupt) #endif
61b5f47cdddadd94aa5c6210ab77dcc9f647d2617e17d6c2e5ffcf0fcbf95799
nikita-volkov/rebase
Unsafe.hs
module Rebase.Control.Monad.ST.Unsafe ( module Control.Monad.ST.Unsafe ) where import Control.Monad.ST.Unsafe
null
https://raw.githubusercontent.com/nikita-volkov/rebase/7c77a0443e80bdffd4488a4239628177cac0761b/library/Rebase/Control/Monad/ST/Unsafe.hs
haskell
module Rebase.Control.Monad.ST.Unsafe ( module Control.Monad.ST.Unsafe ) where import Control.Monad.ST.Unsafe
305b104a5f244fe1f4d6f3ca28a5ec54366b92d72e78da156c7bec00c94f898b
facebook/duckling
Tests.hs
Copyright ( c ) 2016 - present , Facebook , Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Temperature.CA.Tests ( tests ) where import Data.String import Prelude import Test.Tasty import Duckling.Temperature.CA.Corpus import Duckling.Dimensions.Types import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "CA Tests" [ makeCorpusTest [Seal Temperature] corpus ]
null
https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/tests/Duckling/Temperature/CA/Tests.hs
haskell
All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree.
Copyright ( c ) 2016 - present , Facebook , Inc. module Duckling.Temperature.CA.Tests ( tests ) where import Data.String import Prelude import Test.Tasty import Duckling.Temperature.CA.Corpus import Duckling.Dimensions.Types import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "CA Tests" [ makeCorpusTest [Seal Temperature] corpus ]
f64c81f6b146f9f92a5d289217d8ca8af11edacf4af0af6fb8cb0e65ddf38230
zudov/haskell-comark
CMark.hs
{-# LANGUAGE LambdaCase #-} # LANGUAGE RecordWildCards # module Comark.TestUtils.CMark ( module CMark , nodeToDoc , nodeToBlock , nodeToInline ) where import Control.Monad (mfilter) import Data.Monoid import qualified Data.Sequence as Seq import Data.Text (Text) import qualified Data.Text as Text import CMark import Comark.Syntax | Converts a cmark 's AST to commonmark 's AST nodeToDoc :: Node -> Doc Text nodeToDoc (Node _ DOCUMENT ns) = Doc $ Seq.fromList $ map nodeToBlock ns nodeToDoc _ = error "Top-level node must be DOCUMENT" nodeToBlock :: Node -> Block Text nodeToBlock (Node _ THEMATIC_BREAK []) = ThematicBreak nodeToBlock (Node _ THEMATIC_BREAK _) = error "THEMATIC_BREAK node has children" nodeToBlock (Node _ PARAGRAPH ns) = Para $ Seq.fromList $ map nodeToInline ns nodeToBlock (Node _ BLOCK_QUOTE ns) = Quote $ Seq.fromList $ map nodeToBlock ns nodeToBlock (Node _ (HTML_BLOCK html) []) = HtmlBlock $ Text.stripEnd html nodeToBlock (Node _ (HTML_BLOCK _) _) = error "HTML node has children" nodeToBlock (Node _ (CODE_BLOCK i c) []) = CodeBlock (mfilter (not . Text.null) $ pure i) c nodeToBlock (Node _ CODE_BLOCK{} _) = error "CODE_BLOCK has children" nodeToBlock (Node _ (HEADING l) ns) = Heading h $ Seq.fromList $ map nodeToInline ns where h = case l of 1 -> Heading1 2 -> Heading2 3 -> Heading3 4 -> Heading4 5 -> Heading5 6 -> Heading6 _ -> error "HEADING has invalid level" nodeToBlock (Node _ (LIST ListAttributes{..}) ns) = List listType' listTight $ Seq.fromList $ map itemToBlocks ns where listType' = case (listType,listDelim) of (BULLET_LIST,_) -> Bullet Asterisk (ORDERED_LIST,PERIOD_DELIM) -> Ordered Period listStart (ORDERED_LIST,PAREN_DELIM) -> Ordered Paren listStart nodeToBlock (Node _ type_ _) = error $ show type_ ++ " isn't a block node" itemToBlocks :: Node -> Blocks Text itemToBlocks (Node _ ITEM ns) = Seq.fromList $ map nodeToBlock ns itemToBlocks (Node _ type_ _ ) = error $ show type_ ++ " isn't an ITEM" nodeToInline :: Node -> Inline Text nodeToInline (Node _ (TEXT t) []) = Str t nodeToInline (Node _ (TEXT _) _) = error "TEXT has children" nodeToInline (Node _ SOFTBREAK []) = SoftBreak nodeToInline (Node _ SOFTBREAK _) = error "SOFTBREAK has children" nodeToInline (Node _ LINEBREAK []) = HardBreak nodeToInline (Node _ LINEBREAK _) = error "LINEBREAK has children" nodeToInline (Node _ (HTML_INLINE html) []) = RawHtml html nodeToInline (Node _ (HTML_INLINE _) _) = error "INLINE_HTML has children" nodeToInline (Node _ (CODE c) []) = Code c nodeToInline (Node _ (CODE _) _) = error "CODE has children" nodeToInline (Node _ EMPH ns) = Emph $ Seq.fromList $ map nodeToInline ns nodeToInline (Node _ STRONG ns) = Strong $ Seq.fromList $ map nodeToInline ns nodeToInline (Node _ (LINK d t) ns) = Link (Seq.fromList $ map nodeToInline ns) d (mfilter (not . Text.null) $ pure t) nodeToInline (Node _ (IMAGE d t) ns) = Image (Seq.fromList $ map nodeToInline ns) d (mfilter (not . Text.null) $ pure t) nodeToInline (Node _ type_ _) = error $ show type_ ++ " is not a block node"
null
https://raw.githubusercontent.com/zudov/haskell-comark/b84cf1d5623008673402da3a5353bdc5891d3a75/comark-testutils/src/Comark/TestUtils/CMark.hs
haskell
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards # module Comark.TestUtils.CMark ( module CMark , nodeToDoc , nodeToBlock , nodeToInline ) where import Control.Monad (mfilter) import Data.Monoid import qualified Data.Sequence as Seq import Data.Text (Text) import qualified Data.Text as Text import CMark import Comark.Syntax | Converts a cmark 's AST to commonmark 's AST nodeToDoc :: Node -> Doc Text nodeToDoc (Node _ DOCUMENT ns) = Doc $ Seq.fromList $ map nodeToBlock ns nodeToDoc _ = error "Top-level node must be DOCUMENT" nodeToBlock :: Node -> Block Text nodeToBlock (Node _ THEMATIC_BREAK []) = ThematicBreak nodeToBlock (Node _ THEMATIC_BREAK _) = error "THEMATIC_BREAK node has children" nodeToBlock (Node _ PARAGRAPH ns) = Para $ Seq.fromList $ map nodeToInline ns nodeToBlock (Node _ BLOCK_QUOTE ns) = Quote $ Seq.fromList $ map nodeToBlock ns nodeToBlock (Node _ (HTML_BLOCK html) []) = HtmlBlock $ Text.stripEnd html nodeToBlock (Node _ (HTML_BLOCK _) _) = error "HTML node has children" nodeToBlock (Node _ (CODE_BLOCK i c) []) = CodeBlock (mfilter (not . Text.null) $ pure i) c nodeToBlock (Node _ CODE_BLOCK{} _) = error "CODE_BLOCK has children" nodeToBlock (Node _ (HEADING l) ns) = Heading h $ Seq.fromList $ map nodeToInline ns where h = case l of 1 -> Heading1 2 -> Heading2 3 -> Heading3 4 -> Heading4 5 -> Heading5 6 -> Heading6 _ -> error "HEADING has invalid level" nodeToBlock (Node _ (LIST ListAttributes{..}) ns) = List listType' listTight $ Seq.fromList $ map itemToBlocks ns where listType' = case (listType,listDelim) of (BULLET_LIST,_) -> Bullet Asterisk (ORDERED_LIST,PERIOD_DELIM) -> Ordered Period listStart (ORDERED_LIST,PAREN_DELIM) -> Ordered Paren listStart nodeToBlock (Node _ type_ _) = error $ show type_ ++ " isn't a block node" itemToBlocks :: Node -> Blocks Text itemToBlocks (Node _ ITEM ns) = Seq.fromList $ map nodeToBlock ns itemToBlocks (Node _ type_ _ ) = error $ show type_ ++ " isn't an ITEM" nodeToInline :: Node -> Inline Text nodeToInline (Node _ (TEXT t) []) = Str t nodeToInline (Node _ (TEXT _) _) = error "TEXT has children" nodeToInline (Node _ SOFTBREAK []) = SoftBreak nodeToInline (Node _ SOFTBREAK _) = error "SOFTBREAK has children" nodeToInline (Node _ LINEBREAK []) = HardBreak nodeToInline (Node _ LINEBREAK _) = error "LINEBREAK has children" nodeToInline (Node _ (HTML_INLINE html) []) = RawHtml html nodeToInline (Node _ (HTML_INLINE _) _) = error "INLINE_HTML has children" nodeToInline (Node _ (CODE c) []) = Code c nodeToInline (Node _ (CODE _) _) = error "CODE has children" nodeToInline (Node _ EMPH ns) = Emph $ Seq.fromList $ map nodeToInline ns nodeToInline (Node _ STRONG ns) = Strong $ Seq.fromList $ map nodeToInline ns nodeToInline (Node _ (LINK d t) ns) = Link (Seq.fromList $ map nodeToInline ns) d (mfilter (not . Text.null) $ pure t) nodeToInline (Node _ (IMAGE d t) ns) = Image (Seq.fromList $ map nodeToInline ns) d (mfilter (not . Text.null) $ pure t) nodeToInline (Node _ type_ _) = error $ show type_ ++ " is not a block node"
5b48fda9e8db92e845a3b7ac6e4babd637d45014019bcaf30a7a66515187870a
mfikes/tach
tach.clj
(ns leiningen.tach (:require [clojure.string :as string] [clojure.java.shell :as shell] [leiningen.core.main :as main] [leiningen.core.classpath :as classpath])) (def exit-code-failed-test 1) (defn clojurescript-jar? [jar-name] (boolean (re-matches #".*/clojurescript-.*\.jar" jar-name))) (defn clojure-jar? [jar-name] (boolean (re-matches #".*/clojure-.*\.jar" jar-name))) (defn render-classpath [cp] (str (string/join ":" cp))) (defn get-execution-environment [args] (when (empty? args) (throw (ex-info "No execution environment specified. Expected lumo or planck." {}))) (let [execution-environment (first args)] (when-not (#{"lumo" "planck"} execution-environment) (throw (ex-info "Execution enviromnents supported: lumo or planck" {:execution-environemnt execution-environment}))) execution-environment)) (defn render-require-test-runner-main [test-runner-main] (pr-str `(require '~test-runner-main))) (defn render-require-cljs-test [] (pr-str `(require 'cljs.test))) (defn render-require-planck-core [planck?] (pr-str (when planck? `(require 'planck.core)))) (defn render-inject-exit-handler [planck?] (pr-str `(do (defmethod cljs.test/report [:cljs.test/default :end-run-tests] [~'m] (when-not (cljs.test/successful? ~'m) ~(if planck? `(planck.core/exit ~exit-code-failed-test) `(.exit js/process ~exit-code-failed-test)))) nil))) (defn get-build [project args] (let [builds (get-in project [:cljsbuild :builds])] (if-some [build-id (second args)] (or (first (filter (fn [build] (= (:id build) build-id)) builds)) (->> builds (filter (fn [[id _]] (= (name id) build-id))) first second)) (first builds)))) (defn filtered-classpath [project] (->> (classpath/get-classpath project) (remove clojurescript-jar?) (remove clojure-jar?))) (defn unquoted [sym] (if (seq? sym) (second sym) sym)) (defn get-test-runner-ns [project build] (unquoted (or (get-in project [:tach :test-runner-ns]) (get-in build [:compiler :main])))) (defn get-source-paths [project build] (or (get-in project [:tach :source-paths]) (get-in build [:source-paths]))) (defn tach-debug? [project] (get-in project [:tach :debug?])) (defn tach-force-non-zero-exit-on-test-failure? [project] (get-in project [:tach :force-non-zero-exit-on-test-failure?])) (defn tach-cache? [project] (get-in project [:tach :cache?])) (defn tach-verbose? [project] (get-in project [:tach :verbose?])) (defn tach-repl? [project] (get-in project [:tach :repl])) (defn exit [code message] (println message) (if-not (zero? code) (main/exit code))) (defn build-command-line [project args] (let [build (get-build project args) _ (when (tach-debug? project) (println "Using this build: " (pr-str build))) test-runner-ns (get-test-runner-ns project build) source-paths (get-source-paths project build)] (when-not test-runner-ns (throw (ex-info "Failed to determine test runner namespace" {}))) (let [execution-environment (get-execution-environment args) planck? (= execution-environment "planck") run-tests (or (not planck?) (not (tach-repl? project))) command-line (concat [execution-environment (when (and (tach-verbose? project) planck?) "-v") "-q" "-c" (-> project filtered-classpath (concat source-paths) render-classpath)] (when (tach-cache? project) (if-let [cache-path (get-in project [:tach :cache-path])] ["--cache" cache-path] ["--auto-cache"])) (when run-tests (when (tach-force-non-zero-exit-on-test-failure? project) ["-e" (render-require-planck-core planck?) "-e" (render-require-cljs-test) "-e" (render-inject-exit-handler planck?)]) ["-e" (render-require-test-runner-main test-runner-ns)]))] command-line))) (defn tach [project & args] (let [command-line (build-command-line project args) _ (when (tach-debug? project) (apply println "Running\n" command-line)) result (apply shell/sh command-line)] (exit (:exit result) (str (:out result) (:err result)))))
null
https://raw.githubusercontent.com/mfikes/tach/ea756b58d33c173076dbc1a1bc3cf940a771461b/src/leiningen/tach.clj
clojure
(ns leiningen.tach (:require [clojure.string :as string] [clojure.java.shell :as shell] [leiningen.core.main :as main] [leiningen.core.classpath :as classpath])) (def exit-code-failed-test 1) (defn clojurescript-jar? [jar-name] (boolean (re-matches #".*/clojurescript-.*\.jar" jar-name))) (defn clojure-jar? [jar-name] (boolean (re-matches #".*/clojure-.*\.jar" jar-name))) (defn render-classpath [cp] (str (string/join ":" cp))) (defn get-execution-environment [args] (when (empty? args) (throw (ex-info "No execution environment specified. Expected lumo or planck." {}))) (let [execution-environment (first args)] (when-not (#{"lumo" "planck"} execution-environment) (throw (ex-info "Execution enviromnents supported: lumo or planck" {:execution-environemnt execution-environment}))) execution-environment)) (defn render-require-test-runner-main [test-runner-main] (pr-str `(require '~test-runner-main))) (defn render-require-cljs-test [] (pr-str `(require 'cljs.test))) (defn render-require-planck-core [planck?] (pr-str (when planck? `(require 'planck.core)))) (defn render-inject-exit-handler [planck?] (pr-str `(do (defmethod cljs.test/report [:cljs.test/default :end-run-tests] [~'m] (when-not (cljs.test/successful? ~'m) ~(if planck? `(planck.core/exit ~exit-code-failed-test) `(.exit js/process ~exit-code-failed-test)))) nil))) (defn get-build [project args] (let [builds (get-in project [:cljsbuild :builds])] (if-some [build-id (second args)] (or (first (filter (fn [build] (= (:id build) build-id)) builds)) (->> builds (filter (fn [[id _]] (= (name id) build-id))) first second)) (first builds)))) (defn filtered-classpath [project] (->> (classpath/get-classpath project) (remove clojurescript-jar?) (remove clojure-jar?))) (defn unquoted [sym] (if (seq? sym) (second sym) sym)) (defn get-test-runner-ns [project build] (unquoted (or (get-in project [:tach :test-runner-ns]) (get-in build [:compiler :main])))) (defn get-source-paths [project build] (or (get-in project [:tach :source-paths]) (get-in build [:source-paths]))) (defn tach-debug? [project] (get-in project [:tach :debug?])) (defn tach-force-non-zero-exit-on-test-failure? [project] (get-in project [:tach :force-non-zero-exit-on-test-failure?])) (defn tach-cache? [project] (get-in project [:tach :cache?])) (defn tach-verbose? [project] (get-in project [:tach :verbose?])) (defn tach-repl? [project] (get-in project [:tach :repl])) (defn exit [code message] (println message) (if-not (zero? code) (main/exit code))) (defn build-command-line [project args] (let [build (get-build project args) _ (when (tach-debug? project) (println "Using this build: " (pr-str build))) test-runner-ns (get-test-runner-ns project build) source-paths (get-source-paths project build)] (when-not test-runner-ns (throw (ex-info "Failed to determine test runner namespace" {}))) (let [execution-environment (get-execution-environment args) planck? (= execution-environment "planck") run-tests (or (not planck?) (not (tach-repl? project))) command-line (concat [execution-environment (when (and (tach-verbose? project) planck?) "-v") "-q" "-c" (-> project filtered-classpath (concat source-paths) render-classpath)] (when (tach-cache? project) (if-let [cache-path (get-in project [:tach :cache-path])] ["--cache" cache-path] ["--auto-cache"])) (when run-tests (when (tach-force-non-zero-exit-on-test-failure? project) ["-e" (render-require-planck-core planck?) "-e" (render-require-cljs-test) "-e" (render-inject-exit-handler planck?)]) ["-e" (render-require-test-runner-main test-runner-ns)]))] command-line))) (defn tach [project & args] (let [command-line (build-command-line project args) _ (when (tach-debug? project) (apply println "Running\n" command-line)) result (apply shell/sh command-line)] (exit (:exit result) (str (:out result) (:err result)))))
9cd377b4e32d16a3efb5d597a7710f257a74cd5b4a1102183c17975528fcfd96
basho/riak_cs
riak_cs_list_objects_ets_cache_sup.erl
%% --------------------------------------------------------------------- %% Copyright ( c ) 2007 - 2013 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 -module(riak_cs_list_objects_ets_cache_sup). -behaviour(supervisor). %% API -export([start_link/0]). %% Supervisor callbacks -export([init/1]). %%%=================================================================== %%% API functions %%%=================================================================== start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== init([]) -> RestartStrategy = one_for_one, MaxRestarts = 1000, MaxSecondsBetweenRestarts = 3600, SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts}, ETSCache = {riak_cs_list_objects_ets_cache, {riak_cs_list_objects_ets_cache, start_link, []}, permanent, 5000, worker, [riak_cs_list_objects_ets_cache]}, {ok, {SupFlags, [ETSCache]}}. %%%=================================================================== Internal functions %%%===================================================================
null
https://raw.githubusercontent.com/basho/riak_cs/c0c1012d1c9c691c74c8c5d9f69d388f5047bcd2/src/riak_cs_list_objects_ets_cache_sup.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 API Supervisor callbacks =================================================================== API functions =================================================================== =================================================================== Supervisor callbacks =================================================================== =================================================================== ===================================================================
Copyright ( c ) 2007 - 2013 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 -module(riak_cs_list_objects_ets_cache_sup). -behaviour(supervisor). -export([start_link/0]). -export([init/1]). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). init([]) -> RestartStrategy = one_for_one, MaxRestarts = 1000, MaxSecondsBetweenRestarts = 3600, SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts}, ETSCache = {riak_cs_list_objects_ets_cache, {riak_cs_list_objects_ets_cache, start_link, []}, permanent, 5000, worker, [riak_cs_list_objects_ets_cache]}, {ok, {SupFlags, [ETSCache]}}. Internal functions
04c75e515241adba5bb7595d771b4ba3404fc916338dee5bb839e012fab576dc
jwiegley/notes
Types.hs
mergeUpdateMaps :: (These a a -> Maybe a) -> Map Prelude.FilePath a -> Map Prelude.FilePath a -> Map Prelude.FilePath a mergeUpdateMaps f = (M.mapMaybe f .) . align mergeSourceUpdateMaps :: Map Prelude.FilePath UpdateSource -> Map Prelude.FilePath UpdateSource -> Map Prelude.FilePath UpdateSource mergeSourceUpdateMaps = mergeUpdateMaps f where f (These _ x@(UpdateSource _)) = Just x f _ = Nothing
null
https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/gists/6260796/Types.hs
haskell
mergeUpdateMaps :: (These a a -> Maybe a) -> Map Prelude.FilePath a -> Map Prelude.FilePath a -> Map Prelude.FilePath a mergeUpdateMaps f = (M.mapMaybe f .) . align mergeSourceUpdateMaps :: Map Prelude.FilePath UpdateSource -> Map Prelude.FilePath UpdateSource -> Map Prelude.FilePath UpdateSource mergeSourceUpdateMaps = mergeUpdateMaps f where f (These _ x@(UpdateSource _)) = Just x f _ = Nothing
063bf4eff33302bd677e83244848422ab3a4b2e9f78ee36e029bb5e497de2e8b
racket/typed-racket
optional-shallow-id-2.rkt
#lang typed/racket/base/shallow ;; basic optional -> shallow (module uuu racket/base (provide bad-sym) (define bad-sym #f)) (module opt typed/racket/base/optional (provide get-sym) (require/typed (submod ".." uuu) (bad-sym Symbol)) (: get-sym (-> Symbol)) (define (get-sym) bad-sym)) (require 'opt typed/rackunit) (check-exn #rx"shape-check" (lambda () (ann (get-sym) Symbol)))
null
https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/succeed/optional/optional-shallow-id-2.rkt
racket
basic optional -> shallow
#lang typed/racket/base/shallow (module uuu racket/base (provide bad-sym) (define bad-sym #f)) (module opt typed/racket/base/optional (provide get-sym) (require/typed (submod ".." uuu) (bad-sym Symbol)) (: get-sym (-> Symbol)) (define (get-sym) bad-sym)) (require 'opt typed/rackunit) (check-exn #rx"shape-check" (lambda () (ann (get-sym) Symbol)))
8c477e31312b322a0dd76b4626cc6688f073d4518a7be113af409e35d4f8a23d
uhc/uhc
Bits.hs
# LANGUAGE NoImplicitPrelude , CPP # # OPTIONS_GHC -XNoImplicitPrelude # ----------------------------------------------------------------------------- -- | -- Module : Data.Bits Copyright : ( c ) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : experimental -- Portability : portable -- -- This module defines bitwise operations for signed and unsigned -- integers. Instances of the class 'Bits' for the 'Int' and ' Integer ' types are available from this module , and instances for -- explicitly sized integral types are available from the -- "Data.Int" and "Data.Word" modules. -- ----------------------------------------------------------------------------- module Data.Bits ( Bits( (.&.), (.|.), xor, -- :: a -> a -> a complement, -- :: a -> a shift, -- :: a -> Int -> a rotate, -- :: a -> Int -> a bit, -- :: Int -> a setBit, -- :: a -> Int -> a clearBit, -- :: a -> Int -> a complementBit, -- :: a -> Int -> a testBit, -- :: a -> Int -> Bool bitSize, -- :: a -> Int isSigned, -- :: a -> Bool shiftL, shiftR, -- :: a -> Int -> a rotateL, rotateR -- :: a -> Int -> a ) instance Bits Int instance Bits Integer ) where -- Defines the @Bits@ class containing bit-based operations. -- See library document for details on the semantics of the -- individual operations. #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__) || defined(__UHC__) #include "MachDeps.h" #endif #ifdef __GLASGOW_HASKELL__ import GHC.Num import GHC.Real import GHC.Base #endif #ifdef __HUGS__ import Hugs.Bits #endif #if defined(__UHC__) #include "IntLikeInstance.h" import UHC.Bits import UHC.Real import UHC.Base #endif infixl 8 `shift`, `rotate`, `shiftL`, `shiftR`, `rotateL`, `rotateR` infixl 7 .&. infixl 6 `xor` infixl 5 .|. {-| The 'Bits' class defines bitwise operations over integral types. * Bits are numbered from 0 with bit 0 being the least significant bit. Minimal complete definition: '.&.', '.|.', 'xor', 'complement', ('shift' or ('shiftL' and 'shiftR')), ('rotate' or ('rotateL' and 'rotateR')), 'bitSize' and 'isSigned'. -} class Num a => Bits a where -- | Bitwise \"and\" (.&.) :: a -> a -> a -- | Bitwise \"or\" (.|.) :: a -> a -> a -- | Bitwise \"xor\" xor :: a -> a -> a {-| Reverse all the bits in the argument -} complement :: a -> a | @'shift ' x i@ shifts @x@ left by @i@ bits if @i@ is positive , or right by @-i@ bits otherwise . Right shifts perform sign extension on signed number types ; i.e. they fill the top bits with 1 if the @x@ is negative and with 0 otherwise . An instance can define either this unified ' shift ' or ' shiftL ' and ' shiftR ' , depending on which is more convenient for the type in question . or right by @-i@ bits otherwise. Right shifts perform sign extension on signed number types; i.e. they fill the top bits with 1 if the @x@ is negative and with 0 otherwise. An instance can define either this unified 'shift' or 'shiftL' and 'shiftR', depending on which is more convenient for the type in question. -} shift :: a -> Int -> a x `shift` i | i<0 = x `shiftR` (-i) | i>0 = x `shiftL` i | otherwise = x | @'rotate ' x i@ rotates @x@ left by @i@ bits if @i@ is positive , or right by @-i@ bits otherwise . For unbounded types like ' Integer ' , ' rotate ' is equivalent to ' shift ' . An instance can define either this unified ' rotate ' or ' rotateL ' and ' rotateR ' , depending on which is more convenient for the type in question . or right by @-i@ bits otherwise. For unbounded types like 'Integer', 'rotate' is equivalent to 'shift'. An instance can define either this unified 'rotate' or 'rotateL' and 'rotateR', depending on which is more convenient for the type in question. -} rotate :: a -> Int -> a x `rotate` i | i<0 = x `rotateR` (-i) | i>0 = x `rotateL` i | otherwise = x -- Rotation can be implemented in terms of two shifts , but care is -- needed for negative values . This suggested implementation assumes -- 2's - complement arithmetic . It is commented out because it would -- require an extra context ( a ) on the signature of ' rotate ' . x ` rotate ` i | i<0 & & isSigned x & & x<0 = let left = i+bitSize x in ( ( x ` shift ` i ) . & . complement ( ( -1 ) ` shift ` left ) ) .| . ( x ` shift ` left ) | i<0 = ( x ` shift ` i ) .| . ( x ` shift ` ( i+bitSize x ) ) | i==0 = x | i>0 = ( x ` shift ` i ) .| . ( x ` shift ` ( i - bitSize x ) ) -- Rotation can be implemented in terms of two shifts, but care is -- needed for negative values. This suggested implementation assumes -- 2's-complement arithmetic. It is commented out because it would -- require an extra context (Ord a) on the signature of 'rotate'. x `rotate` i | i<0 && isSigned x && x<0 = let left = i+bitSize x in ((x `shift` i) .&. complement ((-1) `shift` left)) .|. (x `shift` left) | i<0 = (x `shift` i) .|. (x `shift` (i+bitSize x)) | i==0 = x | i>0 = (x `shift` i) .|. (x `shift` (i-bitSize x)) -} -- | @bit i@ is a value with the @i@th bit set bit :: Int -> a -- | @x \`setBit\` i@ is the same as @x .|. bit i@ setBit :: a -> Int -> a | @x \`clearBit\ ` i@ is the same as @x . & . complement ( bit i)@ clearBit :: a -> Int -> a | @x \`complementBit\ ` i@ is the same as @x bit i@ complementBit :: a -> Int -> a | Return ' True ' if the @n@th bit of the argument is 1 testBit :: a -> Int -> Bool {-| Return the number of bits in the type of the argument. The actual value of the argument is ignored. The function 'bitSize' is undefined for types that do not have a fixed bitsize, like 'Integer'. -} bitSize :: a -> Int {-| Return 'True' if the argument is a signed type. The actual value of the argument is ignored -} isSigned :: a -> Bool bit i = 1 `shiftL` i x `setBit` i = x .|. bit i x `clearBit` i = x .&. complement (bit i) x `complementBit` i = x `xor` bit i x `testBit` i = (x .&. bit i) /= 0 {-| Shift the argument left by the specified number of bits (which must be non-negative). An instance can define either this and 'shiftR' or the unified 'shift', depending on which is more convenient for the type in question. -} shiftL :: a -> Int -> a x `shiftL` i = x `shift` i | Shift the first argument right by the specified number of bits ( which must be non - negative ) . Right shifts perform sign extension on signed number types ; i.e. they fill the top bits with 1 if the @x@ is negative and with 0 otherwise . An instance can define either this and ' shiftL ' or the unified ' shift ' , depending on which is more convenient for the type in question . (which must be non-negative). Right shifts perform sign extension on signed number types; i.e. they fill the top bits with 1 if the @x@ is negative and with 0 otherwise. An instance can define either this and 'shiftL' or the unified 'shift', depending on which is more convenient for the type in question. -} shiftR :: a -> Int -> a x `shiftR` i = x `shift` (-i) {-| Rotate the argument left by the specified number of bits (which must be non-negative). An instance can define either this and 'rotateR' or the unified 'rotate', depending on which is more convenient for the type in question. -} rotateL :: a -> Int -> a x `rotateL` i = x `rotate` i {-| Rotate the argument right by the specified number of bits (which must be non-negative). An instance can define either this and 'rotateL' or the unified 'rotate', depending on which is more convenient for the type in question. -} rotateR :: a -> Int -> a x `rotateR` i = x `rotate` (-i) instance Bits Int where {-# INLINE shift #-} #ifdef __GLASGOW_HASKELL__ (I# x#) .&. (I# y#) = I# (word2Int# (int2Word# x# `and#` int2Word# y#)) (I# x#) .|. (I# y#) = I# (word2Int# (int2Word# x# `or#` int2Word# y#)) (I# x#) `xor` (I# y#) = I# (word2Int# (int2Word# x# `xor#` int2Word# y#)) complement (I# x#) = I# (word2Int# (int2Word# x# `xor#` int2Word# (-1#))) (I# x#) `shift` (I# i#) | i# >=# 0# = I# (x# `iShiftL#` i#) | otherwise = I# (x# `iShiftRA#` negateInt# i#) # INLINE rotate # (I# x#) `rotate` (I# i#) = I# (word2Int# ((x'# `uncheckedShiftL#` i'#) `or#` (x'# `uncheckedShiftRL#` (wsib -# i'#)))) where x'# = int2Word# x# i'# = word2Int# (int2Word# i# `and#` int2Word# (wsib -# 1#)) wsib = WORD_SIZE_IN_BITS# {- work around preprocessor problem (??) -} bitSize _ = WORD_SIZE_IN_BITS # INLINE shiftR # same as the default definition , but we want it inlined ( # 2376 ) x `shiftR` i = x `shift` (-i) #else /* !__GLASGOW_HASKELL__ */ #ifdef __HUGS__ (.&.) = primAndInt (.|.) = primOrInt xor = primXorInt complement = primComplementInt shift = primShiftInt bit = primBitInt testBit = primTestInt bitSize _ = SIZEOF_HSINT*8 #elif defined(__NHC__) (.&.) = nhc_primIntAnd (.|.) = nhc_primIntOr xor = nhc_primIntXor complement = nhc_primIntCompl shiftL = nhc_primIntLsh shiftR = nhc_primIntRsh bitSize _ = 32 #elif defined(__UHC__) (.&.) = primAndInt (.|.) = primOrInt xor = primXorInt complement = primComplementInt shiftL = primShiftLeftInt shiftR = primShiftRightInt rotateL = primRotateLeftInt rotateR = primRotateRightInt #if defined( __UHC_TARGET_JS__ ) bitSize _ = 31 -- for now... #elif defined( __UHC_TARGET_BC__ ) bitSize _ = SIZEOF_HSINT*8 - BITSIZEOF_WORDTAG #else bitSize _ = SIZEOF_HSINT*8 #endif #endif /* __NHC__ , __UHC__ */ x `rotate` i | i<0 && x<0 = let left = i+bitSize x in ((x `shift` i) .&. complement ((-1) `shift` left)) .|. (x `shift` left) | i<0 = (x `shift` i) .|. (x `shift` (i+bitSize x)) | i==0 = x | i>0 = (x `shift` i) .|. (x `shift` (i-bitSize x)) #endif /* !__GLASGOW_HASKELL__ */ isSigned _ = True #ifdef __NHC__ foreign import ccall nhc_primIntAnd :: Int -> Int -> Int foreign import ccall nhc_primIntOr :: Int -> Int -> Int foreign import ccall nhc_primIntXor :: Int -> Int -> Int foreign import ccall nhc_primIntLsh :: Int -> Int -> Int foreign import ccall nhc_primIntRsh :: Int -> Int -> Int foreign import ccall nhc_primIntCompl :: Int -> Int #endif /* __NHC__ */ instance Bits Integer where #if defined(__GLASGOW_HASKELL__) (.&.) = andInteger (.|.) = orInteger xor = xorInteger complement = complementInteger #elif defined(__UHC__) (.&.) = primAndInteger (.|.) = primOrInteger xor = primXorInteger complement = primComplementInteger #else -- reduce bitwise binary operations to special cases we can handle x .&. y | x<0 && y<0 = complement (complement x `posOr` complement y) | otherwise = x `posAnd` y x .|. y | x<0 || y<0 = complement (complement x `posAnd` complement y) | otherwise = x `posOr` y x `xor` y | x<0 && y<0 = complement x `posXOr` complement y | x<0 = complement (complement x `posXOr` y) | y<0 = complement (x `posXOr` complement y) | otherwise = x `posXOr` y assuming infinite 2's - complement arithmetic complement a = -1 - a #endif #ifdef __UHC__ shiftL = primShiftLeftInteger shiftR = primShiftRightInteger #else shift x i | i >= 0 = x * 2^i | otherwise = x `div` 2^(-i) #endif since an Integer never wraps around bitSize _ = error "Data.Bits.bitSize(Integer)" isSigned _ = True #if !defined(__GLASGOW_HASKELL__) && !defined(__UHC__) -- Crude implementation of bitwise operations on Integers: convert them to finite lists of Ints ( least significant first ) , zip and convert -- back again. posAnd requires at least one argument non - negative posOr and posXOr require both arguments non - negative posAnd, posOr, posXOr :: Integer -> Integer -> Integer posAnd x y = fromInts $ zipWith (.&.) (toInts x) (toInts y) posOr x y = fromInts $ longZipWith (.|.) (toInts x) (toInts y) posXOr x y = fromInts $ longZipWith xor (toInts x) (toInts y) longZipWith :: (a -> a -> a) -> [a] -> [a] -> [a] longZipWith f xs [] = xs longZipWith f [] ys = ys longZipWith f (x:xs) (y:ys) = f x y:longZipWith f xs ys toInts :: Integer -> [Int] toInts n | n == 0 = [] | otherwise = mkInt (n `mod` numInts):toInts (n `div` numInts) where mkInt n | n > toInteger(maxBound::Int) = fromInteger (n-numInts) | otherwise = fromInteger n fromInts :: [Int] -> Integer fromInts = foldr catInt 0 where catInt d n = (if d<0 then n+1 else n)*numInts + toInteger d numInts = toInteger (maxBound::Int) - toInteger (minBound::Int) + 1 #endif /* !__GLASGOW_HASKELL__ */ Note [ Constant folding for rotate ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The INLINE on the Int instance of rotate enables it to be constant folded . For example : sumU . ( ` rotate ` 3 ) . replicateU 10000000 $ ( 7 : : Int ) goes to : = \ ( ww_sO7 : : Int # ) ( ww1_sOb : : Int # ) - > case ww1_sOb of wild_XM { _ _ DEFAULT - > Main.$wfold ( + # ww_sO7 56 ) ( + # wild_XM 1 ) ; 10000000 - > ww_sO7 whereas before it was left as a call to $ wrotate . All other Bits instances seem to inline well enough on their own to enable constant folding ; for example ' shift ' : sumU . ( ` shift ` 3 ) . replicateU 10000000 $ ( 7 : : Int ) goes to : Main.$wfold = \ ( ww_sOb : : Int # ) ( ww1_sOf : : Int # ) - > case ww1_sOf of wild_XM { _ _ DEFAULT - > Main.$wfold ( + # ww_sOb 56 ) ( + # wild_XM 1 ) ; 10000000 - > ww_sOb } ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The INLINE on the Int instance of rotate enables it to be constant folded. For example: sumU . mapU (`rotate` 3) . replicateU 10000000 $ (7 :: Int) goes to: Main.$wfold = \ (ww_sO7 :: Int#) (ww1_sOb :: Int#) -> case ww1_sOb of wild_XM { __DEFAULT -> Main.$wfold (+# ww_sO7 56) (+# wild_XM 1); 10000000 -> ww_sO7 whereas before it was left as a call to $wrotate. All other Bits instances seem to inline well enough on their own to enable constant folding; for example 'shift': sumU . mapU (`shift` 3) . replicateU 10000000 $ (7 :: Int) goes to: Main.$wfold = \ (ww_sOb :: Int#) (ww1_sOf :: Int#) -> case ww1_sOf of wild_XM { __DEFAULT -> Main.$wfold (+# ww_sOb 56) (+# wild_XM 1); 10000000 -> ww_sOb } -}
null
https://raw.githubusercontent.com/uhc/uhc/8eb6914df3ba2ba43916a1a4956c6f25aa0e07c5/EHC/ehclib/uhcbase/Data/Bits.hs
haskell
--------------------------------------------------------------------------- | Module : Data.Bits License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : experimental Portability : portable This module defines bitwise operations for signed and unsigned integers. Instances of the class 'Bits' for the 'Int' and explicitly sized integral types are available from the "Data.Int" and "Data.Word" modules. --------------------------------------------------------------------------- :: a -> a -> a :: a -> a :: a -> Int -> a :: a -> Int -> a :: Int -> a :: a -> Int -> a :: a -> Int -> a :: a -> Int -> a :: a -> Int -> Bool :: a -> Int :: a -> Bool :: a -> Int -> a :: a -> Int -> a Defines the @Bits@ class containing bit-based operations. See library document for details on the semantics of the individual operations. | The 'Bits' class defines bitwise operations over integral types. * Bits are numbered from 0 with bit 0 being the least significant bit. Minimal complete definition: '.&.', '.|.', 'xor', 'complement', ('shift' or ('shiftL' and 'shiftR')), ('rotate' or ('rotateL' and 'rotateR')), 'bitSize' and 'isSigned'. | Bitwise \"and\" | Bitwise \"or\" | Bitwise \"xor\" | Reverse all the bits in the argument Rotation can be implemented in terms of two shifts , but care is needed for negative values . This suggested implementation assumes 2's - complement arithmetic . It is commented out because it would require an extra context ( a ) on the signature of ' rotate ' . Rotation can be implemented in terms of two shifts, but care is needed for negative values. This suggested implementation assumes 2's-complement arithmetic. It is commented out because it would require an extra context (Ord a) on the signature of 'rotate'. | @bit i@ is a value with the @i@th bit set | @x \`setBit\` i@ is the same as @x .|. bit i@ | Return the number of bits in the type of the argument. The actual value of the argument is ignored. The function 'bitSize' is undefined for types that do not have a fixed bitsize, like 'Integer'. | Return 'True' if the argument is a signed type. The actual value of the argument is ignored | Shift the argument left by the specified number of bits (which must be non-negative). An instance can define either this and 'shiftR' or the unified 'shift', depending on which is more convenient for the type in question. | Rotate the argument left by the specified number of bits (which must be non-negative). An instance can define either this and 'rotateR' or the unified 'rotate', depending on which is more convenient for the type in question. | Rotate the argument right by the specified number of bits (which must be non-negative). An instance can define either this and 'rotateL' or the unified 'rotate', depending on which is more convenient for the type in question. # INLINE shift # work around preprocessor problem (??) for now... reduce bitwise binary operations to special cases we can handle Crude implementation of bitwise operations on Integers: convert them back again.
# LANGUAGE NoImplicitPrelude , CPP # # OPTIONS_GHC -XNoImplicitPrelude # Copyright : ( c ) The University of Glasgow 2001 ' Integer ' types are available from this module , and instances for module Data.Bits ( Bits( ) instance Bits Int instance Bits Integer ) where #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__) || defined(__UHC__) #include "MachDeps.h" #endif #ifdef __GLASGOW_HASKELL__ import GHC.Num import GHC.Real import GHC.Base #endif #ifdef __HUGS__ import Hugs.Bits #endif #if defined(__UHC__) #include "IntLikeInstance.h" import UHC.Bits import UHC.Real import UHC.Base #endif infixl 8 `shift`, `rotate`, `shiftL`, `shiftR`, `rotateL`, `rotateR` infixl 7 .&. infixl 6 `xor` infixl 5 .|. class Num a => Bits a where (.&.) :: a -> a -> a (.|.) :: a -> a -> a xor :: a -> a -> a complement :: a -> a | @'shift ' x i@ shifts @x@ left by @i@ bits if @i@ is positive , or right by @-i@ bits otherwise . Right shifts perform sign extension on signed number types ; i.e. they fill the top bits with 1 if the @x@ is negative and with 0 otherwise . An instance can define either this unified ' shift ' or ' shiftL ' and ' shiftR ' , depending on which is more convenient for the type in question . or right by @-i@ bits otherwise. Right shifts perform sign extension on signed number types; i.e. they fill the top bits with 1 if the @x@ is negative and with 0 otherwise. An instance can define either this unified 'shift' or 'shiftL' and 'shiftR', depending on which is more convenient for the type in question. -} shift :: a -> Int -> a x `shift` i | i<0 = x `shiftR` (-i) | i>0 = x `shiftL` i | otherwise = x | @'rotate ' x i@ rotates @x@ left by @i@ bits if @i@ is positive , or right by @-i@ bits otherwise . For unbounded types like ' Integer ' , ' rotate ' is equivalent to ' shift ' . An instance can define either this unified ' rotate ' or ' rotateL ' and ' rotateR ' , depending on which is more convenient for the type in question . or right by @-i@ bits otherwise. For unbounded types like 'Integer', 'rotate' is equivalent to 'shift'. An instance can define either this unified 'rotate' or 'rotateL' and 'rotateR', depending on which is more convenient for the type in question. -} rotate :: a -> Int -> a x `rotate` i | i<0 = x `rotateR` (-i) | i>0 = x `rotateL` i | otherwise = x x ` rotate ` i | i<0 & & isSigned x & & x<0 = let left = i+bitSize x in ( ( x ` shift ` i ) . & . complement ( ( -1 ) ` shift ` left ) ) .| . ( x ` shift ` left ) | i<0 = ( x ` shift ` i ) .| . ( x ` shift ` ( i+bitSize x ) ) | i==0 = x | i>0 = ( x ` shift ` i ) .| . ( x ` shift ` ( i - bitSize x ) ) x `rotate` i | i<0 && isSigned x && x<0 = let left = i+bitSize x in ((x `shift` i) .&. complement ((-1) `shift` left)) .|. (x `shift` left) | i<0 = (x `shift` i) .|. (x `shift` (i+bitSize x)) | i==0 = x | i>0 = (x `shift` i) .|. (x `shift` (i-bitSize x)) -} bit :: Int -> a setBit :: a -> Int -> a | @x \`clearBit\ ` i@ is the same as @x . & . complement ( bit i)@ clearBit :: a -> Int -> a | @x \`complementBit\ ` i@ is the same as @x bit i@ complementBit :: a -> Int -> a | Return ' True ' if the @n@th bit of the argument is 1 testBit :: a -> Int -> Bool bitSize :: a -> Int isSigned :: a -> Bool bit i = 1 `shiftL` i x `setBit` i = x .|. bit i x `clearBit` i = x .&. complement (bit i) x `complementBit` i = x `xor` bit i x `testBit` i = (x .&. bit i) /= 0 shiftL :: a -> Int -> a x `shiftL` i = x `shift` i | Shift the first argument right by the specified number of bits ( which must be non - negative ) . Right shifts perform sign extension on signed number types ; i.e. they fill the top bits with 1 if the @x@ is negative and with 0 otherwise . An instance can define either this and ' shiftL ' or the unified ' shift ' , depending on which is more convenient for the type in question . (which must be non-negative). Right shifts perform sign extension on signed number types; i.e. they fill the top bits with 1 if the @x@ is negative and with 0 otherwise. An instance can define either this and 'shiftL' or the unified 'shift', depending on which is more convenient for the type in question. -} shiftR :: a -> Int -> a x `shiftR` i = x `shift` (-i) rotateL :: a -> Int -> a x `rotateL` i = x `rotate` i rotateR :: a -> Int -> a x `rotateR` i = x `rotate` (-i) instance Bits Int where #ifdef __GLASGOW_HASKELL__ (I# x#) .&. (I# y#) = I# (word2Int# (int2Word# x# `and#` int2Word# y#)) (I# x#) .|. (I# y#) = I# (word2Int# (int2Word# x# `or#` int2Word# y#)) (I# x#) `xor` (I# y#) = I# (word2Int# (int2Word# x# `xor#` int2Word# y#)) complement (I# x#) = I# (word2Int# (int2Word# x# `xor#` int2Word# (-1#))) (I# x#) `shift` (I# i#) | i# >=# 0# = I# (x# `iShiftL#` i#) | otherwise = I# (x# `iShiftRA#` negateInt# i#) # INLINE rotate # (I# x#) `rotate` (I# i#) = I# (word2Int# ((x'# `uncheckedShiftL#` i'#) `or#` (x'# `uncheckedShiftRL#` (wsib -# i'#)))) where x'# = int2Word# x# i'# = word2Int# (int2Word# i# `and#` int2Word# (wsib -# 1#)) bitSize _ = WORD_SIZE_IN_BITS # INLINE shiftR # same as the default definition , but we want it inlined ( # 2376 ) x `shiftR` i = x `shift` (-i) #else /* !__GLASGOW_HASKELL__ */ #ifdef __HUGS__ (.&.) = primAndInt (.|.) = primOrInt xor = primXorInt complement = primComplementInt shift = primShiftInt bit = primBitInt testBit = primTestInt bitSize _ = SIZEOF_HSINT*8 #elif defined(__NHC__) (.&.) = nhc_primIntAnd (.|.) = nhc_primIntOr xor = nhc_primIntXor complement = nhc_primIntCompl shiftL = nhc_primIntLsh shiftR = nhc_primIntRsh bitSize _ = 32 #elif defined(__UHC__) (.&.) = primAndInt (.|.) = primOrInt xor = primXorInt complement = primComplementInt shiftL = primShiftLeftInt shiftR = primShiftRightInt rotateL = primRotateLeftInt rotateR = primRotateRightInt #if defined( __UHC_TARGET_JS__ ) #elif defined( __UHC_TARGET_BC__ ) bitSize _ = SIZEOF_HSINT*8 - BITSIZEOF_WORDTAG #else bitSize _ = SIZEOF_HSINT*8 #endif #endif /* __NHC__ , __UHC__ */ x `rotate` i | i<0 && x<0 = let left = i+bitSize x in ((x `shift` i) .&. complement ((-1) `shift` left)) .|. (x `shift` left) | i<0 = (x `shift` i) .|. (x `shift` (i+bitSize x)) | i==0 = x | i>0 = (x `shift` i) .|. (x `shift` (i-bitSize x)) #endif /* !__GLASGOW_HASKELL__ */ isSigned _ = True #ifdef __NHC__ foreign import ccall nhc_primIntAnd :: Int -> Int -> Int foreign import ccall nhc_primIntOr :: Int -> Int -> Int foreign import ccall nhc_primIntXor :: Int -> Int -> Int foreign import ccall nhc_primIntLsh :: Int -> Int -> Int foreign import ccall nhc_primIntRsh :: Int -> Int -> Int foreign import ccall nhc_primIntCompl :: Int -> Int #endif /* __NHC__ */ instance Bits Integer where #if defined(__GLASGOW_HASKELL__) (.&.) = andInteger (.|.) = orInteger xor = xorInteger complement = complementInteger #elif defined(__UHC__) (.&.) = primAndInteger (.|.) = primOrInteger xor = primXorInteger complement = primComplementInteger #else x .&. y | x<0 && y<0 = complement (complement x `posOr` complement y) | otherwise = x `posAnd` y x .|. y | x<0 || y<0 = complement (complement x `posAnd` complement y) | otherwise = x `posOr` y x `xor` y | x<0 && y<0 = complement x `posXOr` complement y | x<0 = complement (complement x `posXOr` y) | y<0 = complement (x `posXOr` complement y) | otherwise = x `posXOr` y assuming infinite 2's - complement arithmetic complement a = -1 - a #endif #ifdef __UHC__ shiftL = primShiftLeftInteger shiftR = primShiftRightInteger #else shift x i | i >= 0 = x * 2^i | otherwise = x `div` 2^(-i) #endif since an Integer never wraps around bitSize _ = error "Data.Bits.bitSize(Integer)" isSigned _ = True #if !defined(__GLASGOW_HASKELL__) && !defined(__UHC__) to finite lists of Ints ( least significant first ) , zip and convert posAnd requires at least one argument non - negative posOr and posXOr require both arguments non - negative posAnd, posOr, posXOr :: Integer -> Integer -> Integer posAnd x y = fromInts $ zipWith (.&.) (toInts x) (toInts y) posOr x y = fromInts $ longZipWith (.|.) (toInts x) (toInts y) posXOr x y = fromInts $ longZipWith xor (toInts x) (toInts y) longZipWith :: (a -> a -> a) -> [a] -> [a] -> [a] longZipWith f xs [] = xs longZipWith f [] ys = ys longZipWith f (x:xs) (y:ys) = f x y:longZipWith f xs ys toInts :: Integer -> [Int] toInts n | n == 0 = [] | otherwise = mkInt (n `mod` numInts):toInts (n `div` numInts) where mkInt n | n > toInteger(maxBound::Int) = fromInteger (n-numInts) | otherwise = fromInteger n fromInts :: [Int] -> Integer fromInts = foldr catInt 0 where catInt d n = (if d<0 then n+1 else n)*numInts + toInteger d numInts = toInteger (maxBound::Int) - toInteger (minBound::Int) + 1 #endif /* !__GLASGOW_HASKELL__ */ Note [ Constant folding for rotate ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The INLINE on the Int instance of rotate enables it to be constant folded . For example : sumU . ( ` rotate ` 3 ) . replicateU 10000000 $ ( 7 : : Int ) goes to : = \ ( ww_sO7 : : Int # ) ( ww1_sOb : : Int # ) - > case ww1_sOb of wild_XM { _ _ DEFAULT - > Main.$wfold ( + # ww_sO7 56 ) ( + # wild_XM 1 ) ; 10000000 - > ww_sO7 whereas before it was left as a call to $ wrotate . All other Bits instances seem to inline well enough on their own to enable constant folding ; for example ' shift ' : sumU . ( ` shift ` 3 ) . replicateU 10000000 $ ( 7 : : Int ) goes to : Main.$wfold = \ ( ww_sOb : : Int # ) ( ww1_sOf : : Int # ) - > case ww1_sOf of wild_XM { _ _ DEFAULT - > Main.$wfold ( + # ww_sOb 56 ) ( + # wild_XM 1 ) ; 10000000 - > ww_sOb } ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The INLINE on the Int instance of rotate enables it to be constant folded. For example: sumU . mapU (`rotate` 3) . replicateU 10000000 $ (7 :: Int) goes to: Main.$wfold = \ (ww_sO7 :: Int#) (ww1_sOb :: Int#) -> case ww1_sOb of wild_XM { __DEFAULT -> Main.$wfold (+# ww_sO7 56) (+# wild_XM 1); 10000000 -> ww_sO7 whereas before it was left as a call to $wrotate. All other Bits instances seem to inline well enough on their own to enable constant folding; for example 'shift': sumU . mapU (`shift` 3) . replicateU 10000000 $ (7 :: Int) goes to: Main.$wfold = \ (ww_sOb :: Int#) (ww1_sOf :: Int#) -> case ww1_sOf of wild_XM { __DEFAULT -> Main.$wfold (+# ww_sOb 56) (+# wild_XM 1); 10000000 -> ww_sOb } -}
6815819bfd5ac7f636152d50d17e4421485b34a0f3546ee71e45e155c876b249
the-dr-lazy/cascade
Applicative.hs
| Module : Cascade . Control . Applicative Description : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! ! Copyright : ( c ) 2020 - 2021 Cascade License : MPL 2.0 Maintainer : < > ( the-dr-lazy.github.io ) Stability : Stable Portability : POSIX ! ! ! INSERT MODULE LONG DESCRIPTION ! ! ! Module : Cascade.Control.Applicative Description : !!! INSERT MODULE SHORT DESCRIPTION !!! Copyright : (c) 2020-2021 Cascade License : MPL 2.0 Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io) Stability : Stable Portability : POSIX !!! INSERT MODULE LONG DESCRIPTION !!! -} module Cascade.Control.Applicative ( module Control.Applicative , pureMaybe ) where import Control.Applicative pureMaybe :: Applicative f => Coercible (Maybe a) (maybe a) => a -> maybe a -> f a pureMaybe def = pure . fromMaybe def . coerce
null
https://raw.githubusercontent.com/the-dr-lazy/cascade/014a5589a2763ce373e8c84a211cddc479872b44/cascade-prelude/src/Cascade/Control/Applicative.hs
haskell
| Module : Cascade . Control . Applicative Description : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! ! Copyright : ( c ) 2020 - 2021 Cascade License : MPL 2.0 Maintainer : < > ( the-dr-lazy.github.io ) Stability : Stable Portability : POSIX ! ! ! INSERT MODULE LONG DESCRIPTION ! ! ! Module : Cascade.Control.Applicative Description : !!! INSERT MODULE SHORT DESCRIPTION !!! Copyright : (c) 2020-2021 Cascade License : MPL 2.0 Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io) Stability : Stable Portability : POSIX !!! INSERT MODULE LONG DESCRIPTION !!! -} module Cascade.Control.Applicative ( module Control.Applicative , pureMaybe ) where import Control.Applicative pureMaybe :: Applicative f => Coercible (Maybe a) (maybe a) => a -> maybe a -> f a pureMaybe def = pure . fromMaybe def . coerce
ebaf2b1ec12f2aba842012de8d1fa225e917fb059bbe2793e7c042414c485652
foreverbell/project-euler-solutions
205.hs
import Data.Array.Unboxed import Data.Array.ST import Control.Monad (guard, forM_, when) import Control.Monad.ST import Text.Printf dynamic :: Int -> Int -> [(Int, Int)] dynamic times dice = assocs $ rec times dice init where cnt = times * dice init = listArray (0, cnt) (1 : (repeat 0)) rec :: Int -> Int -> UArray Int Int -> UArray Int Int rec 0 _ ret = ret rec times dice last = rec (times - 1) dice $ runSTUArray $ do ret <- newArray (0, cnt) 0 forM_ [cnt, cnt - 1 .. 1] $ \i -> do forM_ [1 .. dice] $ \j -> do when (i >= j) $ do v <- readArray ret i writeArray ret i (v + last!(i - j)) return ret peter = dynamic 9 4 colin = dynamic 6 6 solve = sum $ do (a, b) <- peter (c, d) <- colin guard $ a > c return $ b * d main = putStrLn $ printf "%.7f" (a / b) where a = fromIntegral solve :: Double b = (4^9)*(6^6) :: Double
null
https://raw.githubusercontent.com/foreverbell/project-euler-solutions/c0bf2746aafce9be510892814e2d03e20738bf2b/src/205.hs
haskell
import Data.Array.Unboxed import Data.Array.ST import Control.Monad (guard, forM_, when) import Control.Monad.ST import Text.Printf dynamic :: Int -> Int -> [(Int, Int)] dynamic times dice = assocs $ rec times dice init where cnt = times * dice init = listArray (0, cnt) (1 : (repeat 0)) rec :: Int -> Int -> UArray Int Int -> UArray Int Int rec 0 _ ret = ret rec times dice last = rec (times - 1) dice $ runSTUArray $ do ret <- newArray (0, cnt) 0 forM_ [cnt, cnt - 1 .. 1] $ \i -> do forM_ [1 .. dice] $ \j -> do when (i >= j) $ do v <- readArray ret i writeArray ret i (v + last!(i - j)) return ret peter = dynamic 9 4 colin = dynamic 6 6 solve = sum $ do (a, b) <- peter (c, d) <- colin guard $ a > c return $ b * d main = putStrLn $ printf "%.7f" (a / b) where a = fromIntegral solve :: Double b = (4^9)*(6^6) :: Double
2c9931f5cfa3d4a057de1a735749786a1c9e2e20659eb9046c3eeff9a6f75081
reborg/reclojure
reversible.clj
(ns reclojure.lang.protocols.counted (:refer-clojure :exclude [rseq])) (defprotocol Reversible (rseq [this]))
null
https://raw.githubusercontent.com/reborg/reclojure/c8aae4cc384d59262569cbc9c332e08619f292ef/src/reclojure/lang/protocols/reversible.clj
clojure
(ns reclojure.lang.protocols.counted (:refer-clojure :exclude [rseq])) (defprotocol Reversible (rseq [this]))
d05892f7fa79b00f0d9d4ac72808436f681f7a2fa3f9f79f6671c083cc83b45c
ofmooseandmen/Aeromess
F16.hs
-- | ICAO Field Type 16 - Destination aerodrome and total estimated -- elapsed time, destination alternate aerodrome(s). module Data.Icao.F16 ( Data(ades, totalEet, altn1, altn2) , adesParser , parser ) where import Data.Aeromess.Parser import Data.Icao.Location import Data.Icao.Time | Field Type 16 data . data Data = Data { ades :: Aerodrome , totalEet :: Hhmm , altn1 :: Maybe Aerodrome , altn2 :: Maybe Aerodrome } altn :: Parser (Maybe Aerodrome) altn = optional (space >> aerodromeParser) -- | ADES parser. adesParser :: Parser Aerodrome adesParser = do a <- aerodromeParser _ <- dash return a | Field Type 16 parser . parser :: Parser Data parser = do a <- aerodromeParser tett <- hhmmParser a1 <- altn a2 <- altn _ <- dash return (Data a tett a1 a2)
null
https://raw.githubusercontent.com/ofmooseandmen/Aeromess/765f3ea10073993e43c71b6b6955b9f0d234a4ef/src/Data/Icao/F16.hs
haskell
| elapsed time, destination alternate aerodrome(s). | ADES parser.
ICAO Field Type 16 - Destination aerodrome and total estimated module Data.Icao.F16 ( Data(ades, totalEet, altn1, altn2) , adesParser , parser ) where import Data.Aeromess.Parser import Data.Icao.Location import Data.Icao.Time | Field Type 16 data . data Data = Data { ades :: Aerodrome , totalEet :: Hhmm , altn1 :: Maybe Aerodrome , altn2 :: Maybe Aerodrome } altn :: Parser (Maybe Aerodrome) altn = optional (space >> aerodromeParser) adesParser :: Parser Aerodrome adesParser = do a <- aerodromeParser _ <- dash return a | Field Type 16 parser . parser :: Parser Data parser = do a <- aerodromeParser tett <- hhmmParser a1 <- altn a2 <- altn _ <- dash return (Data a tett a1 a2)
0d426f8445c70340ee3c9af78e372980a619fd2df115cd0132c3e6c316c1fd6a
DestyNova/advent_of_code_2021
Part2.hs
module Main where import Text.Parsec import Data.List (intercalate, nub, transpose) import qualified Data.Map as M import Data.Map ((!)) type Coord = (Int,Int) type Grid = M.Map Coord Int main = do txt <- readFile "input.txt" let (Right inp) = parse parser "" txt let g = transpose inp print $ run g gridToMap g = M.fromList [((i,j), g !! j !! i) | i <- [0..w-1], j <- [0..h-1]] where w = length (head g) h = length g run g = run' (gridToMap g) 0 w h 0 where w = length (head g) h = length g run' :: Grid -> Int -> Int -> Int -> Int -> Int run' grid n w h flashes | allZeroes grid = n | otherwise = run' g' (n+1) w h flashes' where flashes' = flashes + M.size (M.filter (>9) flashed) incremented = step grid flashed = doFlashes incremented w h [] g' = reset flashed step = M.map succ reset = M.map (\i -> if i > 9 then 0 else i) allZeroes g = M.size (M.filter (/=0) g) == 0 doFlashes :: Grid -> Int -> Int -> [Coord] -> Grid doFlashes g w h toFlash = g' where flashing = nub $ toFlash ++ M.keys (M.filter (==10) g) g' = case flashing of [] -> g (f:fs) -> doFlashes (applyFlash f w h g) w h fs applyFlash (x,y) w h g = foldr (\c g' -> M.insertWith (+) c 1 g') g neighbours where neighbours = getNeighbours x y w h getNeighbours x y w h = [(x',y') | i <- [-1,0,1], j <- [-1,0,1], let x' = x+i, let y' = y+j, x' >= 0 && x' < w, y' >= 0 && y' < h] parser :: Parsec String () [[Int]] parser = many1 (read . (:[]) <$> digit) `sepEndBy1` newline number :: Parsec String () Int number = read <$> many1 digit
null
https://raw.githubusercontent.com/DestyNova/advent_of_code_2021/f0fea3f81ead9d7d703b266a8b960f5f2bc5a658/day11/Part2.hs
haskell
module Main where import Text.Parsec import Data.List (intercalate, nub, transpose) import qualified Data.Map as M import Data.Map ((!)) type Coord = (Int,Int) type Grid = M.Map Coord Int main = do txt <- readFile "input.txt" let (Right inp) = parse parser "" txt let g = transpose inp print $ run g gridToMap g = M.fromList [((i,j), g !! j !! i) | i <- [0..w-1], j <- [0..h-1]] where w = length (head g) h = length g run g = run' (gridToMap g) 0 w h 0 where w = length (head g) h = length g run' :: Grid -> Int -> Int -> Int -> Int -> Int run' grid n w h flashes | allZeroes grid = n | otherwise = run' g' (n+1) w h flashes' where flashes' = flashes + M.size (M.filter (>9) flashed) incremented = step grid flashed = doFlashes incremented w h [] g' = reset flashed step = M.map succ reset = M.map (\i -> if i > 9 then 0 else i) allZeroes g = M.size (M.filter (/=0) g) == 0 doFlashes :: Grid -> Int -> Int -> [Coord] -> Grid doFlashes g w h toFlash = g' where flashing = nub $ toFlash ++ M.keys (M.filter (==10) g) g' = case flashing of [] -> g (f:fs) -> doFlashes (applyFlash f w h g) w h fs applyFlash (x,y) w h g = foldr (\c g' -> M.insertWith (+) c 1 g') g neighbours where neighbours = getNeighbours x y w h getNeighbours x y w h = [(x',y') | i <- [-1,0,1], j <- [-1,0,1], let x' = x+i, let y' = y+j, x' >= 0 && x' < w, y' >= 0 && y' < h] parser :: Parsec String () [[Int]] parser = many1 (read . (:[]) <$> digit) `sepEndBy1` newline number :: Parsec String () Int number = read <$> many1 digit
a59067d454d8a2617ff5e61ceb728635e3e38748b5e237e2c1c0c09d6574fa35
nasa/Common-Metadata-Repository
ascii.clj
(ns ^:system cmr.opendap.tests.system.app.sizing.ascii "Note: this namespace is exclusively for system tests; all tests defined here will use one or more system test fixtures. Definition used for system tests: * #System_testing" (:require [clojure.test :refer :all] [cmr.http.kit.request :as request] [cmr.opendap.testing.system :as test-system] [cmr.opendap.testing.util :as util] [org.httpkit.client :as httpc])) (use-fixtures :once test-system/with-system) (def collection-id "C1200297231-HMR_TME") (def granule-id "G1200297234-HMR_TME") (def variable-id "V1200297235-HMR_TME") (def granule2-id "G1200301322-HMR_TME") (def variable2-id "V1200301323-HMR_TME") (def variable3-id "V1200297236-HMR_TME") (def options (request/add-token-header {} (util/get-sit-token))) (deftest one-var-size-test (let [response @(httpc/get (format (str ":%s" "/service-bridge/size-estimate/collection/%s" "?granules=%s" "&variables=%s" "&format=ascii") (test-system/http-port) collection-id granule-id variable-id) options)] (is (= 200 (:status response))) (is (= "cmr-service-bridge.v3; format=json" (get-in response [:headers :cmr-media-type]))) (is (= [{:bytes 2 :mb 0.0 :gb 0.0}] (util/parse-response response))))) (deftest one-var-different-gran-size-test (let [response @(httpc/get (format (str ":%s" "/service-bridge/size-estimate/collection/%s" "?granules=%s" "&variables=%s" "&format=ascii") (test-system/http-port) collection-id granule2-id variable2-id) options)] (is (= 200 (:status response))) (is (= "cmr-service-bridge.v3; format=json" (get-in response [:headers :cmr-media-type]))) (is (= [{:bytes 23039998 :mb 21.97 :gb 0.02}] (util/parse-response response))))) (deftest multi-var-size-test (let [response @(httpc/get (format (str ":%s" "/service-bridge/size-estimate/collection/%s" "?granules=%s" "&variables=%s,%s" "&format=ascii") (test-system/http-port) collection-id granule-id variable-id variable3-id) options)] (is (= 200 (:status response))) (is (= "cmr-service-bridge.v3; format=json" (get-in response [:headers :cmr-media-type]))) (is (= [{:bytes 25920000 :mb 24.72 :gb 0.02}] (util/parse-response response))))) (deftest multi-var-different-gran-size-test (let [response @(httpc/get (format (str ":%s" "/service-bridge/size-estimate/collection/%s" "?granules=%s" "&variables=%s,%s" "&format=ascii") (test-system/http-port) collection-id granule2-id variable2-id variable3-id) options)] (is (= 200 (:status response))) (is (= "cmr-service-bridge.v3; format=json" (get-in response [:headers :cmr-media-type]))) (is (= [{:bytes 48959996 :mb 46.69 :gb 0.05}] (util/parse-response response))))) ;; XXX Currently not working; see CMR-5268 (deftest multi-gran-multi-var-size-test (let [response @(httpc/get (format (str ":%s" "/service-bridge/size-estimate/collection/%s" "?granules=%s,%s" "&variables=%s,%s" "&format=ascii") (test-system/http-port) collection-id granule-id granule2-id variable-id variable2-id) options)] (is (= 200 (:status response))) (is (= "cmr-service-bridge.v3; format=json" (get-in response [:headers :cmr-media-type]))) (is (= [{:bytes 46080000 :mb 43.95 :gb 0.04}] (util/parse-response response))))) (deftest size-with-no-sizing-metadata-test (let [collection-id "C1200267318-HMR_TME" granule-id "G1200267320-HMR_TME" variable-id "V1200267322-HMR_TME" response @(httpc/get (format (str ":%s" "/service-bridge/size-estimate/collection/%s" "?granules=%s" "&variables=%s" "&format=ascii") (test-system/http-port) collection-id granule-id variable-id) options)] (is (= 200 (:status response))) (is (= "cmr-service-bridge.v3; format=json" (get-in response [:headers :cmr-media-type]))) (is (= [{:bytes 7775998 :mb 7.42 :gb 0.01}] (util/parse-response response)))))
null
https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/63001cf021d32d61030b1dcadd8b253e4a221662/other/cmr-exchange/service-bridge/test/cmr/opendap/tests/system/app/sizing/ascii.clj
clojure
all tests defined XXX Currently not working; see CMR-5268
(ns ^:system cmr.opendap.tests.system.app.sizing.ascii here will use one or more system test fixtures. Definition used for system tests: * #System_testing" (:require [clojure.test :refer :all] [cmr.http.kit.request :as request] [cmr.opendap.testing.system :as test-system] [cmr.opendap.testing.util :as util] [org.httpkit.client :as httpc])) (use-fixtures :once test-system/with-system) (def collection-id "C1200297231-HMR_TME") (def granule-id "G1200297234-HMR_TME") (def variable-id "V1200297235-HMR_TME") (def granule2-id "G1200301322-HMR_TME") (def variable2-id "V1200301323-HMR_TME") (def variable3-id "V1200297236-HMR_TME") (def options (request/add-token-header {} (util/get-sit-token))) (deftest one-var-size-test (let [response @(httpc/get (format (str ":%s" "/service-bridge/size-estimate/collection/%s" "?granules=%s" "&variables=%s" "&format=ascii") (test-system/http-port) collection-id granule-id variable-id) options)] (is (= 200 (:status response))) (is (= "cmr-service-bridge.v3; format=json" (get-in response [:headers :cmr-media-type]))) (is (= [{:bytes 2 :mb 0.0 :gb 0.0}] (util/parse-response response))))) (deftest one-var-different-gran-size-test (let [response @(httpc/get (format (str ":%s" "/service-bridge/size-estimate/collection/%s" "?granules=%s" "&variables=%s" "&format=ascii") (test-system/http-port) collection-id granule2-id variable2-id) options)] (is (= 200 (:status response))) (is (= "cmr-service-bridge.v3; format=json" (get-in response [:headers :cmr-media-type]))) (is (= [{:bytes 23039998 :mb 21.97 :gb 0.02}] (util/parse-response response))))) (deftest multi-var-size-test (let [response @(httpc/get (format (str ":%s" "/service-bridge/size-estimate/collection/%s" "?granules=%s" "&variables=%s,%s" "&format=ascii") (test-system/http-port) collection-id granule-id variable-id variable3-id) options)] (is (= 200 (:status response))) (is (= "cmr-service-bridge.v3; format=json" (get-in response [:headers :cmr-media-type]))) (is (= [{:bytes 25920000 :mb 24.72 :gb 0.02}] (util/parse-response response))))) (deftest multi-var-different-gran-size-test (let [response @(httpc/get (format (str ":%s" "/service-bridge/size-estimate/collection/%s" "?granules=%s" "&variables=%s,%s" "&format=ascii") (test-system/http-port) collection-id granule2-id variable2-id variable3-id) options)] (is (= 200 (:status response))) (is (= "cmr-service-bridge.v3; format=json" (get-in response [:headers :cmr-media-type]))) (is (= [{:bytes 48959996 :mb 46.69 :gb 0.05}] (util/parse-response response))))) (deftest multi-gran-multi-var-size-test (let [response @(httpc/get (format (str ":%s" "/service-bridge/size-estimate/collection/%s" "?granules=%s,%s" "&variables=%s,%s" "&format=ascii") (test-system/http-port) collection-id granule-id granule2-id variable-id variable2-id) options)] (is (= 200 (:status response))) (is (= "cmr-service-bridge.v3; format=json" (get-in response [:headers :cmr-media-type]))) (is (= [{:bytes 46080000 :mb 43.95 :gb 0.04}] (util/parse-response response))))) (deftest size-with-no-sizing-metadata-test (let [collection-id "C1200267318-HMR_TME" granule-id "G1200267320-HMR_TME" variable-id "V1200267322-HMR_TME" response @(httpc/get (format (str ":%s" "/service-bridge/size-estimate/collection/%s" "?granules=%s" "&variables=%s" "&format=ascii") (test-system/http-port) collection-id granule-id variable-id) options)] (is (= 200 (:status response))) (is (= "cmr-service-bridge.v3; format=json" (get-in response [:headers :cmr-media-type]))) (is (= [{:bytes 7775998 :mb 7.42 :gb 0.01}] (util/parse-response response)))))
4d5b0b25da8d8151804e214d4ad5ccd2d635bb3bbb6304fb518ef0db9c900ea6
orx/ocaml-orx
resource.ml
include Orx_gen.Resource let add_storage group storage first = add_storage (string_of_group group) storage first let remove_storage group storage = remove_storage (Option.map string_of_group group) storage let sync group = sync (Option.map string_of_group group)
null
https://raw.githubusercontent.com/orx/ocaml-orx/ce3be01870b04a1498dbb24bbe4ad0f13d36615c/src/lib/resource.ml
ocaml
include Orx_gen.Resource let add_storage group storage first = add_storage (string_of_group group) storage first let remove_storage group storage = remove_storage (Option.map string_of_group group) storage let sync group = sync (Option.map string_of_group group)
4427865d2b18ba9b03fcfe5f940462d97630e9d437be476e5f08be9447b25ebe
bsansouci/bsb-native
camlinternalMod.ml
(***********************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 2004 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) type shape = | Function | Lazy | Class | Module of shape array | Value of Obj.t let rec init_mod loc shape = match shape with | Function -> let pad1 = 1 and pad2 = 2 and pad3 = 3 and pad4 = 4 and pad5 = 5 and pad6 = 6 and pad7 = 7 and pad8 = 8 in Obj.repr(fun _ -> ignore pad1; ignore pad2; ignore pad3; ignore pad4; ignore pad5; ignore pad6; ignore pad7; ignore pad8; raise (Undefined_recursive_module loc)) | Lazy -> Obj.repr (lazy (raise (Undefined_recursive_module loc))) | Class -> Obj.repr (CamlinternalOO.dummy_class loc) | Module comps -> Obj.repr (Array.map (init_mod loc) comps) | Value v -> v let overwrite o n = assert (Obj.size o >= Obj.size n); for i = 0 to Obj.size n - 1 do Obj.set_field o i (Obj.field n i) done let rec update_mod shape o n = match shape with | Function -> if Obj.tag n = Obj.closure_tag && Obj.size n <= Obj.size o PR # 4008 else overwrite o (Obj.repr (fun x -> (Obj.obj n : _ -> _) x)) | Lazy -> if Obj.tag n = Obj.lazy_tag then Obj.set_field o 0 (Obj.field n 0) else if Obj.tag n = Obj.forward_tag then begin (* PR#4316 *) Obj.set_tag o Obj.forward_tag; Obj.set_field o 0 (Obj.field n 0) end else begin forwarding pointer was shortcut by GC Obj.set_tag o Obj.forward_tag; Obj.set_field o 0 n end | Class -> assert (Obj.tag n = 0 && Obj.size n = 4); overwrite o n | Module comps -> assert (Obj.tag n = 0 && Obj.size n >= Array.length comps); for i = 0 to Array.length comps - 1 do update_mod comps.(i) (Obj.field o i) (Obj.field n i) done | Value v -> () (* the value is already there *)
null
https://raw.githubusercontent.com/bsansouci/bsb-native/9a89457783d6e80deb0fba9ca7372c10a768a9ea/vendor/ocaml/stdlib/camlinternalMod.ml
ocaml
********************************************************************* OCaml the special exception on linking described in file ../LICENSE. ********************************************************************* PR#4316 the value is already there
, projet Cristal , INRIA Rocquencourt Copyright 2004 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with type shape = | Function | Lazy | Class | Module of shape array | Value of Obj.t let rec init_mod loc shape = match shape with | Function -> let pad1 = 1 and pad2 = 2 and pad3 = 3 and pad4 = 4 and pad5 = 5 and pad6 = 6 and pad7 = 7 and pad8 = 8 in Obj.repr(fun _ -> ignore pad1; ignore pad2; ignore pad3; ignore pad4; ignore pad5; ignore pad6; ignore pad7; ignore pad8; raise (Undefined_recursive_module loc)) | Lazy -> Obj.repr (lazy (raise (Undefined_recursive_module loc))) | Class -> Obj.repr (CamlinternalOO.dummy_class loc) | Module comps -> Obj.repr (Array.map (init_mod loc) comps) | Value v -> v let overwrite o n = assert (Obj.size o >= Obj.size n); for i = 0 to Obj.size n - 1 do Obj.set_field o i (Obj.field n i) done let rec update_mod shape o n = match shape with | Function -> if Obj.tag n = Obj.closure_tag && Obj.size n <= Obj.size o PR # 4008 else overwrite o (Obj.repr (fun x -> (Obj.obj n : _ -> _) x)) | Lazy -> if Obj.tag n = Obj.lazy_tag then Obj.set_field o 0 (Obj.field n 0) Obj.set_tag o Obj.forward_tag; Obj.set_field o 0 (Obj.field n 0) end else begin forwarding pointer was shortcut by GC Obj.set_tag o Obj.forward_tag; Obj.set_field o 0 n end | Class -> assert (Obj.tag n = 0 && Obj.size n = 4); overwrite o n | Module comps -> assert (Obj.tag n = 0 && Obj.size n >= Array.length comps); for i = 0 to Array.length comps - 1 do update_mod comps.(i) (Obj.field o i) (Obj.field n i) done
356e39ba97d925b1a646d07715dae6e5756dc7096a75f830a53ad9808cb9978a
jackrusher/sparkledriver
cookies.clj
(ns sparkledriver.cookies (:require [sparkledriver.browser :as brwsr])) (defn browser-cookies->map "Convert `browser`'s current cookies into the map format used by clj-http. This returns cookies from all domains, but cookie names that are set on multiple domains will only be returned once." [browser] (reduce #(assoc %1 (keyword (.getName %2)) {:domain (.getDomain %2) :path (.getPath %2) :value (.getValue %2)}) {} (.getCookies (.manage browser)))) (defn delete-all-cookies! "Clear all cookies from all domains." [browser] (.deleteAllCookies (.manage browser)) browser) (defn delete-cookie! "Delete the named cookie from the given domain. When omitted `domain` defaults to the `browser`'s current domain." ([browser name] (delete-cookie! browser name (.getHost (java.net.URL. (brwsr/current-url browser))))) ([browser name domain] (let [manager (.manage browser) cookies (.getCookies manager)] (when-let [cookie (some (fn [c] (and (= (.getName c) name) (= (.getDomain c) domain) c)) cookies)] (.deleteCookie manager cookie)) browser))) (defn- build-selenium-cookie "Build an instance of org.openqa.selenium.Cookie with `name`, `value` and `options`." [name value options] (.build (reduce (fn [builder [k v]] (case k :domain (.domain builder v) :expires-on (.expiresOn builder v) :http-only (.isHttpOnly builder v) :secure (.isSecure builder v) :path (.path builder v) builder)) (org.openqa.selenium.Cookie$Builder. name value) options))) (defn set-cookie! "Set a cookie with given `name` and `value`. If a cookie with the same name and `domain` is already present, it will be replaced. The following keyword arguments are supported. - `:domain` (String) The cookie domain, defaults to the current domain of the browser. - `:expires-on` (java.util.Date) Expiration date. Must be in the future or the cookie won't be stored. - `:http-only` (Boolean) Cookie's HttpOnly flag, disallow access from JavaScript - `:secure` (Boolean) Cookie's Secure flag, only serve over HTTPS. - `:path` (String) URL path of the cookie." [browser name value & {domain :domain :as options}] (if domain (delete-cookie! browser name domain) (delete-cookie! browser name)) (.addCookie (.manage browser) (build-selenium-cookie name value options)) browser)
null
https://raw.githubusercontent.com/jackrusher/sparkledriver/375885dcad85e37ae2e0d624bc005016ada2982e/src/sparkledriver/cookies.clj
clojure
(ns sparkledriver.cookies (:require [sparkledriver.browser :as brwsr])) (defn browser-cookies->map "Convert `browser`'s current cookies into the map format used by clj-http. This returns cookies from all domains, but cookie names that are set on multiple domains will only be returned once." [browser] (reduce #(assoc %1 (keyword (.getName %2)) {:domain (.getDomain %2) :path (.getPath %2) :value (.getValue %2)}) {} (.getCookies (.manage browser)))) (defn delete-all-cookies! "Clear all cookies from all domains." [browser] (.deleteAllCookies (.manage browser)) browser) (defn delete-cookie! "Delete the named cookie from the given domain. When omitted `domain` defaults to the `browser`'s current domain." ([browser name] (delete-cookie! browser name (.getHost (java.net.URL. (brwsr/current-url browser))))) ([browser name domain] (let [manager (.manage browser) cookies (.getCookies manager)] (when-let [cookie (some (fn [c] (and (= (.getName c) name) (= (.getDomain c) domain) c)) cookies)] (.deleteCookie manager cookie)) browser))) (defn- build-selenium-cookie "Build an instance of org.openqa.selenium.Cookie with `name`, `value` and `options`." [name value options] (.build (reduce (fn [builder [k v]] (case k :domain (.domain builder v) :expires-on (.expiresOn builder v) :http-only (.isHttpOnly builder v) :secure (.isSecure builder v) :path (.path builder v) builder)) (org.openqa.selenium.Cookie$Builder. name value) options))) (defn set-cookie! "Set a cookie with given `name` and `value`. If a cookie with the same name and `domain` is already present, it will be replaced. The following keyword arguments are supported. - `:domain` (String) The cookie domain, defaults to the current domain of the browser. - `:expires-on` (java.util.Date) Expiration date. Must be in the future or the cookie won't be stored. - `:http-only` (Boolean) Cookie's HttpOnly flag, disallow access from JavaScript - `:secure` (Boolean) Cookie's Secure flag, only serve over HTTPS. - `:path` (String) URL path of the cookie." [browser name value & {domain :domain :as options}] (if domain (delete-cookie! browser name domain) (delete-cookie! browser name)) (.addCookie (.manage browser) (build-selenium-cookie name value options)) browser)
c1edb9ebb4ba7edf8de1945e3c7164a45fb48f7a7b5ca5c425a5713f400a6883
terezka/cherry-core
List.hs
| Module : List Description : Work with lists . License : BSD 3 Maintainer : Stability : experimental Portability : POSIX Module : List Description : Work with lists. License : BSD 3 Maintainer : Stability : experimental Portability : POSIX -} module List ( -- * Create List, singleton, repeat, range -- * Transform , map, indexedMap, foldl, foldr, filter, filterMap -- * Utilities , length, reverse, member, all, any, maximum, minimum, sum, product -- * Combine , append, concat, concatMap, intersperse, map2, map3, map4, map5 -- * Sort , sort, sortBy, sortWith * , isEmpty, head, tail, take, drop, partition, unzip ) where import Prelude (Applicative, Char, Eq, Functor, Monad, Num, Ord, Show, Bool(..), Int, Ordering, (-), flip, mappend, mconcat) import Maybe (Maybe (..)) import qualified Prelude import qualified Data.List import qualified Data.Maybe import qualified Internal.Shortcut as Shortcut {-| A list. -} type List a = [a] -- CREATE | Create a list with only one element : > singleton 1234 = = [ 1234 ] > singleton " hi " = = [ " hi " ] > singleton 1234 == [1234] > singleton "hi" == ["hi"] -} singleton :: a -> List a singleton value = [value] | Create a list with * n * copies of a value : > repeat 3 ( 0,0 ) = = [ ( 0,0),(0,0),(0,0 ) ] > repeat 3 (0,0) == [(0,0),(0,0),(0,0)] -} repeat :: Int -> a -> List a repeat = Data.List.replicate | Create a list of numbers , every element increasing by one . You give the lowest and highest number that should be in the list . > range 3 6 = = [ 3 , 4 , 5 , 6 ] > range 3 3 = = [ 3 ] > range 6 3 = = [ ] You give the lowest and highest number that should be in the list. > range 3 6 == [3, 4, 5, 6] > range 3 3 == [3] > range 6 3 == [] -} range :: Int -> Int -> List Int range lo hi = [lo .. hi] -- TRANSFORM {-| Apply a function to every element of a list. > map sqrt [1,4,9] == [1,2,3] > > map not [True,False,True] == [False,True,False] So `map func [ a, b, c ]` is the same as `[ func a, func b, func c ]` -} map :: (a -> b) -> List a -> List b map = Prelude.fmap | Same as ` map ` but the function is also applied to the index of each element ( starting at zero ) . > indexedMap Tuple.pair [ " Tom","Sue","Bob " ] = = [ ( 0,"Tom " ) , ( 1,"Sue " ) , ( 2,"Bob " ) ] element (starting at zero). > indexedMap Tuple.pair ["Tom","Sue","Bob"] == [ (0,"Tom"), (1,"Sue"), (2,"Bob") ] -} indexedMap :: (Int -> a -> b) -> List a -> List b indexedMap f xs = List.map2 f [0 .. (length xs - 1)] xs | Reduce a list from the left . > foldl ( + ) 0 [ 1,2,3 ] = = 6 > foldl (: :) [ ] [ 1,2,3 ] = = [ 3,2,1 ] So ' foldl step state [ 1,2,3 ] ' is like saying : > state > | > step 1 > | > step 2 > | > step 3 > foldl (+) 0 [1,2,3] == 6 > foldl (::) [] [1,2,3] == [3,2,1] So 'foldl step state [1,2,3]' is like saying: > state > |> step 1 > |> step 2 > |> step 3 -} foldl :: (a -> b -> b) -> b -> List a -> b foldl func = -- Note: This function is implemented using fold' to eagerly evaluate the -- accumulator, preventing space leaks. Data.List.foldl' (flip func) | Reduce a list from the right . > foldr ( + ) 0 [ 1,2,3 ] = = 6 > foldr (: :) [ ] [ 1,2,3 ] = = [ 1,2,3 ] So ` foldr step state [ 1,2,3 ] ` is like saying : > state > | > step 3 > | > step 2 > | > step 1 > foldr (+) 0 [1,2,3] == 6 > foldr (::) [] [1,2,3] == [1,2,3] So `foldr step state [1,2,3]` is like saying: > state > |> step 3 > |> step 2 > |> step 1 -} foldr :: (a -> b -> b) -> b -> List a -> b foldr = Data.List.foldr | Keep elements that satisfy the test . > filter isEven [ 1,2,3,4,5,6 ] = = [ 2,4,6 ] > filter isEven [1,2,3,4,5,6] == [2,4,6] -} filter :: (a -> Bool) -> List a -> List a filter = Data.List.filter | Filter out certain values . For example , maybe you have a bunch of strings from an untrusted source and you want to turn them into numbers : > numbers : : List Int > numbers = > filterMap String.toInt [ " 3 " , " hi " , " 12 " , " 4th " , " May " ] > > -- numbers = = [ 3 , 12 ] from an untrusted source and you want to turn them into numbers: > numbers :: List Int > numbers = > filterMap String.toInt ["3", "hi", "12", "4th", "May"] > > -- numbers == [3, 12] -} filterMap :: (a -> Maybe b) -> List a -> List b filterMap toMaybe = Data.Maybe.mapMaybe (\a -> toHMaybe (toMaybe a)) UTILITIES | Determine the length of a list . > length [ 1,2,3 ] = = 3 > length [1,2,3] == 3 -} length :: List a -> Int length = Data.List.length | Reverse a list . > reverse [ 1,2,3,4 ] = = [ 4,3,2,1 ] > reverse [1,2,3,4] == [4,3,2,1] -} reverse :: List a -> List a reverse = Data.List.reverse | Figure out whether a list contains a value . > member 9 [ 1,2,3,4 ] = = False > member 4 [ 1,2,3,4 ] = = True > member 9 [1,2,3,4] == False > member 4 [1,2,3,4] == True -} member :: Prelude.Eq a => a -> List a -> Bool member = Data.List.elem | Determine if all elements satisfy some test . > all isEven [ 2,4 ] = = True > all isEven [ 2,3 ] = = False > all isEven [ ] = = True > all isEven [2,4] == True > all isEven [2,3] == False > all isEven [] == True -} all :: (a -> Bool) -> List a -> Bool all = Data.List.all | Determine if any elements satisfy some test . > any isEven [ 2,3 ] = = True > any isEven [ 1,3 ] = = False > any isEven [ ] = = False > any isEven [2,3] == True > any isEven [1,3] == False > any isEven [] == False -} any :: (a -> Bool) -> List a -> Bool any = Data.List.any | Find the maximum element in a non - empty list . > maximum [ 1,4,2 ] = = Just 4 > maximum [ ] = = Nothing > maximum [1,4,2] == Just 4 > maximum [] == Nothing -} maximum :: Prelude.Ord a => List a -> Maybe a maximum list = case list of [] -> Nothing _ -> Just (Data.List.maximum list) | Find the minimum element in a non - empty list . > minimum [ 3,2,1 ] = = Just 1 > minimum [ ] = = Nothing > minimum [3,2,1] == Just 1 > minimum [] == Nothing -} minimum :: Prelude.Ord a => List a -> Maybe a minimum list = case list of [] -> Nothing _ -> Just (Data.List.minimum list) | Get the sum of the list elements . > sum [ 1,2,3 ] = = 6 > sum [ 1,1,1 ] = = 3 > sum [ ] = = 0 > sum [1,2,3] == 6 > sum [1,1,1] == 3 > sum [] == 0 -} sum :: Prelude.Num a => List a -> a sum = Prelude.sum | Get the product of the list elements . > product [ 2,2,2 ] = = 8 > product [ 3,3,3 ] = = 27 > product [ ] = = 1 > product [2,2,2] == 8 > product [3,3,3] == 27 > product [] == 1 -} product :: Prelude.Num a => List a -> a product = Prelude.product COMBINE | Put two lists together . > append [ 1,1,2 ] [ 3,5,8 ] = = [ 1,1,2,3,5,8 ] > append [ ' a','b ' ] [ ' c ' ] = = [ ' a','b','c ' ] You can also use [ the ` ( + + ) ` operator](Basics#++ ) to append lists . > append [1,1,2] [3,5,8] == [1,1,2,3,5,8] > append ['a','b'] ['c'] == ['a','b','c'] You can also use [the `(++)` operator](Basics#++) to append lists. -} append :: List a -> List a -> List a append = Prelude.mappend | Concatenate a bunch of lists into a single list : > concat [ [ 1,2],[3],[4,5 ] ] = = [ 1,2,3,4,5 ] > concat [[1,2],[3],[4,5]] == [1,2,3,4,5] -} concat :: List (List a) -> List a concat = Prelude.mconcat {-| Map a given function onto a list and flatten the resulting lists. > concatMap f xs == concat (map f xs) -} concatMap :: (a -> List b) -> List a -> List b concatMap = Shortcut.andThen {-| Places the given value between all members of the given list. > intersperse "on" ["turtles","turtles","turtles"] == ["turtles","on","turtles","on","turtles"] -} intersperse :: a -> List a -> List a intersperse = Data.List.intersperse | Combine two lists , combining them with the given function . If one list is longer , the extra elements are dropped . > totals : : List Int - > List Int - > List Int > totals xs ys = > List.map2 ( + ) xs ys > > -- totals [ 1,2,3 ] [ 4,5,6 ] = = [ 5,7,9 ] > > pairs : : List a - > List b - > List ( a , b ) > pairs xs ys = > List.map2 Tuple.pair xs ys > > -- pairs [ " alice","bob","chuck " ] [ 2,5,7,8 ] > -- = = [ ( " alice",2),("bob",5),("chuck",7 ) ] If one list is longer, the extra elements are dropped. > totals :: List Int -> List Int -> List Int > totals xs ys = > List.map2 (+) xs ys > > -- totals [1,2,3] [4,5,6] == [5,7,9] > > pairs :: List a -> List b -> List (a,b) > pairs xs ys = > List.map2 Tuple.pair xs ys > > -- pairs ["alice","bob","chuck"] [2,5,7,8] > -- == [("alice",2),("bob",5),("chuck",7)] -} map2 :: (a -> b -> result) -> List a -> List b -> List result map2 = Data.List.zipWith {-| -} map3 :: (a -> b -> c -> result) -> List a -> List b -> List c -> List result map3 = Data.List.zipWith3 {-| -} map4 :: (a -> b -> c -> d -> result) -> List a -> List b -> List c -> List d -> List result map4 = Data.List.zipWith4 {-| -} map5 :: (a -> b -> c -> d -> e -> result) -> List a -> List b -> List c -> List d -> List e -> List result map5 = Data.List.zipWith5 -- SORT {-| Sort values from lowest to highest sort [3,1,5] == [1,3,5] -} sort :: Prelude.Ord a => List a -> List a sort = Data.List.sort | Sort values by a derived property . > alice = , height=1.62 } > bob = { name="Bob " , height=1.85 } = { name="Chuck " , height=1.76 } > > sortBy .name [ , alice , ] = = [ alice , , ] > sortBy .height [ chuck , alice , ] = = [ alice , , ] > > sortBy String.length [ " mouse","cat " ] = = [ " " ] > alice = { name="Alice", height=1.62 } > bob = { name="Bob" , height=1.85 } > chuck = { name="Chuck", height=1.76 } > > sortBy .name [chuck,alice,bob] == [alice,bob,chuck] > sortBy .height [chuck,alice,bob] == [alice,chuck,bob] > > sortBy String.length ["mouse","cat"] == ["cat","mouse"] -} sortBy :: Prelude.Ord b => (a -> b) -> List a -> List a sortBy = Data.List.sortOn | Sort values with a custom comparison function . > sortWith flippedComparison [ 1,2,3,4,5 ] = = [ 5,4,3,2,1 ] > > flippedComparison a b = > case compare a b of > LT - > GT > EQ - > EQ > GT - > LT This is also the most general sort function , allowing you to define any other : ` sort = = sortWith compare ` > sortWith flippedComparison [1,2,3,4,5] == [5,4,3,2,1] > > flippedComparison a b = > case compare a b of > LT -> GT > EQ -> EQ > GT -> LT This is also the most general sort function, allowing you to define any other: `sort == sortWith compare` -} sortWith :: (a -> a -> Ordering) -> List a -> List a sortWith = Data.List.sortBy DECONSTRUCT {-| Determine if a list is empty. > isEmpty [] == True Note: It is usually preferable to use a `case` to test this so you do not forget to handle the `(x :: xs)` case as well! -} isEmpty :: List a -> Bool isEmpty = Data.List.null | Extract the first element of a list . > head [ 1,2,3 ] = = Just 1 > head [ ] = = Nothing Note : It is usually preferable to use a ` case ` to deconstruct a ` List ` because it gives you ` ( x : : xs ) ` and you can work with both subparts . > head [1,2,3] == Just 1 > head [] == Nothing Note: It is usually preferable to use a `case` to deconstruct a `List` because it gives you `(x :: xs)` and you can work with both subparts. -} head :: List a -> Maybe a head xs = case xs of x : _ -> Just x [] -> Nothing | Extract the rest of the list . > tail [ 1,2,3 ] = = Just [ 2,3 ] > tail [ ] = = Nothing Note : It is usually preferable to use a ` case ` to deconstruct a ` List ` because it gives you ` ( x : : xs ) ` and you can work with both subparts . > tail [1,2,3] == Just [2,3] > tail [] == Nothing Note: It is usually preferable to use a `case` to deconstruct a `List` because it gives you `(x :: xs)` and you can work with both subparts. -} tail :: List a -> Maybe (List a) tail list = case list of _ : xs -> Just xs [] -> Nothing | Take the first * n * members of a list . > take 2 [ 1,2,3,4 ] = = [ 1,2 ] > take 2 [1,2,3,4] == [1,2] -} take :: Int -> List a -> List a take = Data.List.take | Drop the first * n * members of a list . > drop 2 [ 1,2,3,4 ] = = [ 3,4 ] > drop 2 [1,2,3,4] == [3,4] -} drop :: Int -> List a -> List a drop = Data.List.drop | Partition a list based on some test . The first list contains all values that satisfy the test , and the second list contains all the value that do not . > partition ( \x - > x < 3 ) [ 0,1,2,3,4,5 ] = = ( [ 0,1,2 ] , [ 3,4,5 ] ) > partition isEven [ 0,1,2,3,4,5 ] = = ( [ 0,2,4 ] , [ 1,3,5 ] ) that satisfy the test, and the second list contains all the value that do not. > partition (\x -> x < 3) [0,1,2,3,4,5] == ([0,1,2], [3,4,5]) > partition isEven [0,1,2,3,4,5] == ([0,2,4], [1,3,5]) -} partition :: (a -> Bool) -> List a -> (List a, List a) partition = Data.List.partition | Decompose a list of tuples into a tuple of lists . > unzip [ ( 0 , True ) , ( 17 , False ) , ( 1337 , True ) ] = = ( [ 0,17,1337 ] , [ True , False , True ] ) > unzip [(0, True), (17, False), (1337, True)] == ([0,17,1337], [True,False,True]) -} unzip :: List (a, b) -> (List a, List b) unzip = Data.List.unzip -- INTERNAL toHMaybe :: Maybe a -> Data.Maybe.Maybe a toHMaybe maybe = case maybe of Just a -> Data.Maybe.Just a Nothing -> Data.Maybe.Nothing
null
https://raw.githubusercontent.com/terezka/cherry-core/d9bd446e226fc9b04783532969fa670211a150c6/src/List.hs
haskell
* Create * Transform * Utilities * Combine * Sort | A list. CREATE TRANSFORM | Apply a function to every element of a list. > map sqrt [1,4,9] == [1,2,3] > > map not [True,False,True] == [False,True,False] So `map func [ a, b, c ]` is the same as `[ func a, func b, func c ]` Note: This function is implemented using fold' to eagerly evaluate the accumulator, preventing space leaks. numbers = = [ 3 , 12 ] numbers == [3, 12] | Map a given function onto a list and flatten the resulting lists. > concatMap f xs == concat (map f xs) | Places the given value between all members of the given list. > intersperse "on" ["turtles","turtles","turtles"] == ["turtles","on","turtles","on","turtles"] totals [ 1,2,3 ] [ 4,5,6 ] = = [ 5,7,9 ] pairs [ " alice","bob","chuck " ] [ 2,5,7,8 ] = = [ ( " alice",2),("bob",5),("chuck",7 ) ] totals [1,2,3] [4,5,6] == [5,7,9] pairs ["alice","bob","chuck"] [2,5,7,8] == [("alice",2),("bob",5),("chuck",7)] | | | SORT | Sort values from lowest to highest sort [3,1,5] == [1,3,5] | Determine if a list is empty. > isEmpty [] == True Note: It is usually preferable to use a `case` to test this so you do not forget to handle the `(x :: xs)` case as well! INTERNAL
| Module : List Description : Work with lists . License : BSD 3 Maintainer : Stability : experimental Portability : POSIX Module : List Description : Work with lists. License : BSD 3 Maintainer : Stability : experimental Portability : POSIX -} module List List, singleton, repeat, range , map, indexedMap, foldl, foldr, filter, filterMap , length, reverse, member, all, any, maximum, minimum, sum, product , append, concat, concatMap, intersperse, map2, map3, map4, map5 , sort, sortBy, sortWith * , isEmpty, head, tail, take, drop, partition, unzip ) where import Prelude (Applicative, Char, Eq, Functor, Monad, Num, Ord, Show, Bool(..), Int, Ordering, (-), flip, mappend, mconcat) import Maybe (Maybe (..)) import qualified Prelude import qualified Data.List import qualified Data.Maybe import qualified Internal.Shortcut as Shortcut type List a = [a] | Create a list with only one element : > singleton 1234 = = [ 1234 ] > singleton " hi " = = [ " hi " ] > singleton 1234 == [1234] > singleton "hi" == ["hi"] -} singleton :: a -> List a singleton value = [value] | Create a list with * n * copies of a value : > repeat 3 ( 0,0 ) = = [ ( 0,0),(0,0),(0,0 ) ] > repeat 3 (0,0) == [(0,0),(0,0),(0,0)] -} repeat :: Int -> a -> List a repeat = Data.List.replicate | Create a list of numbers , every element increasing by one . You give the lowest and highest number that should be in the list . > range 3 6 = = [ 3 , 4 , 5 , 6 ] > range 3 3 = = [ 3 ] > range 6 3 = = [ ] You give the lowest and highest number that should be in the list. > range 3 6 == [3, 4, 5, 6] > range 3 3 == [3] > range 6 3 == [] -} range :: Int -> Int -> List Int range lo hi = [lo .. hi] map :: (a -> b) -> List a -> List b map = Prelude.fmap | Same as ` map ` but the function is also applied to the index of each element ( starting at zero ) . > indexedMap Tuple.pair [ " Tom","Sue","Bob " ] = = [ ( 0,"Tom " ) , ( 1,"Sue " ) , ( 2,"Bob " ) ] element (starting at zero). > indexedMap Tuple.pair ["Tom","Sue","Bob"] == [ (0,"Tom"), (1,"Sue"), (2,"Bob") ] -} indexedMap :: (Int -> a -> b) -> List a -> List b indexedMap f xs = List.map2 f [0 .. (length xs - 1)] xs | Reduce a list from the left . > foldl ( + ) 0 [ 1,2,3 ] = = 6 > foldl (: :) [ ] [ 1,2,3 ] = = [ 3,2,1 ] So ' foldl step state [ 1,2,3 ] ' is like saying : > state > | > step 1 > | > step 2 > | > step 3 > foldl (+) 0 [1,2,3] == 6 > foldl (::) [] [1,2,3] == [3,2,1] So 'foldl step state [1,2,3]' is like saying: > state > |> step 1 > |> step 2 > |> step 3 -} foldl :: (a -> b -> b) -> b -> List a -> b foldl func = Data.List.foldl' (flip func) | Reduce a list from the right . > foldr ( + ) 0 [ 1,2,3 ] = = 6 > foldr (: :) [ ] [ 1,2,3 ] = = [ 1,2,3 ] So ` foldr step state [ 1,2,3 ] ` is like saying : > state > | > step 3 > | > step 2 > | > step 1 > foldr (+) 0 [1,2,3] == 6 > foldr (::) [] [1,2,3] == [1,2,3] So `foldr step state [1,2,3]` is like saying: > state > |> step 3 > |> step 2 > |> step 1 -} foldr :: (a -> b -> b) -> b -> List a -> b foldr = Data.List.foldr | Keep elements that satisfy the test . > filter isEven [ 1,2,3,4,5,6 ] = = [ 2,4,6 ] > filter isEven [1,2,3,4,5,6] == [2,4,6] -} filter :: (a -> Bool) -> List a -> List a filter = Data.List.filter | Filter out certain values . For example , maybe you have a bunch of strings from an untrusted source and you want to turn them into numbers : > numbers : : List Int > numbers = > filterMap String.toInt [ " 3 " , " hi " , " 12 " , " 4th " , " May " ] > from an untrusted source and you want to turn them into numbers: > numbers :: List Int > numbers = > filterMap String.toInt ["3", "hi", "12", "4th", "May"] > -} filterMap :: (a -> Maybe b) -> List a -> List b filterMap toMaybe = Data.Maybe.mapMaybe (\a -> toHMaybe (toMaybe a)) UTILITIES | Determine the length of a list . > length [ 1,2,3 ] = = 3 > length [1,2,3] == 3 -} length :: List a -> Int length = Data.List.length | Reverse a list . > reverse [ 1,2,3,4 ] = = [ 4,3,2,1 ] > reverse [1,2,3,4] == [4,3,2,1] -} reverse :: List a -> List a reverse = Data.List.reverse | Figure out whether a list contains a value . > member 9 [ 1,2,3,4 ] = = False > member 4 [ 1,2,3,4 ] = = True > member 9 [1,2,3,4] == False > member 4 [1,2,3,4] == True -} member :: Prelude.Eq a => a -> List a -> Bool member = Data.List.elem | Determine if all elements satisfy some test . > all isEven [ 2,4 ] = = True > all isEven [ 2,3 ] = = False > all isEven [ ] = = True > all isEven [2,4] == True > all isEven [2,3] == False > all isEven [] == True -} all :: (a -> Bool) -> List a -> Bool all = Data.List.all | Determine if any elements satisfy some test . > any isEven [ 2,3 ] = = True > any isEven [ 1,3 ] = = False > any isEven [ ] = = False > any isEven [2,3] == True > any isEven [1,3] == False > any isEven [] == False -} any :: (a -> Bool) -> List a -> Bool any = Data.List.any | Find the maximum element in a non - empty list . > maximum [ 1,4,2 ] = = Just 4 > maximum [ ] = = Nothing > maximum [1,4,2] == Just 4 > maximum [] == Nothing -} maximum :: Prelude.Ord a => List a -> Maybe a maximum list = case list of [] -> Nothing _ -> Just (Data.List.maximum list) | Find the minimum element in a non - empty list . > minimum [ 3,2,1 ] = = Just 1 > minimum [ ] = = Nothing > minimum [3,2,1] == Just 1 > minimum [] == Nothing -} minimum :: Prelude.Ord a => List a -> Maybe a minimum list = case list of [] -> Nothing _ -> Just (Data.List.minimum list) | Get the sum of the list elements . > sum [ 1,2,3 ] = = 6 > sum [ 1,1,1 ] = = 3 > sum [ ] = = 0 > sum [1,2,3] == 6 > sum [1,1,1] == 3 > sum [] == 0 -} sum :: Prelude.Num a => List a -> a sum = Prelude.sum | Get the product of the list elements . > product [ 2,2,2 ] = = 8 > product [ 3,3,3 ] = = 27 > product [ ] = = 1 > product [2,2,2] == 8 > product [3,3,3] == 27 > product [] == 1 -} product :: Prelude.Num a => List a -> a product = Prelude.product COMBINE | Put two lists together . > append [ 1,1,2 ] [ 3,5,8 ] = = [ 1,1,2,3,5,8 ] > append [ ' a','b ' ] [ ' c ' ] = = [ ' a','b','c ' ] You can also use [ the ` ( + + ) ` operator](Basics#++ ) to append lists . > append [1,1,2] [3,5,8] == [1,1,2,3,5,8] > append ['a','b'] ['c'] == ['a','b','c'] You can also use [the `(++)` operator](Basics#++) to append lists. -} append :: List a -> List a -> List a append = Prelude.mappend | Concatenate a bunch of lists into a single list : > concat [ [ 1,2],[3],[4,5 ] ] = = [ 1,2,3,4,5 ] > concat [[1,2],[3],[4,5]] == [1,2,3,4,5] -} concat :: List (List a) -> List a concat = Prelude.mconcat concatMap :: (a -> List b) -> List a -> List b concatMap = Shortcut.andThen intersperse :: a -> List a -> List a intersperse = Data.List.intersperse | Combine two lists , combining them with the given function . If one list is longer , the extra elements are dropped . > totals : : List Int - > List Int - > List Int > totals xs ys = > List.map2 ( + ) xs ys > > > pairs : : List a - > List b - > List ( a , b ) > pairs xs ys = > List.map2 Tuple.pair xs ys > If one list is longer, the extra elements are dropped. > totals :: List Int -> List Int -> List Int > totals xs ys = > List.map2 (+) xs ys > > > pairs :: List a -> List b -> List (a,b) > pairs xs ys = > List.map2 Tuple.pair xs ys > -} map2 :: (a -> b -> result) -> List a -> List b -> List result map2 = Data.List.zipWith map3 :: (a -> b -> c -> result) -> List a -> List b -> List c -> List result map3 = Data.List.zipWith3 map4 :: (a -> b -> c -> d -> result) -> List a -> List b -> List c -> List d -> List result map4 = Data.List.zipWith4 map5 :: (a -> b -> c -> d -> e -> result) -> List a -> List b -> List c -> List d -> List e -> List result map5 = Data.List.zipWith5 sort :: Prelude.Ord a => List a -> List a sort = Data.List.sort | Sort values by a derived property . > alice = , height=1.62 } > bob = { name="Bob " , height=1.85 } = { name="Chuck " , height=1.76 } > > sortBy .name [ , alice , ] = = [ alice , , ] > sortBy .height [ chuck , alice , ] = = [ alice , , ] > > sortBy String.length [ " mouse","cat " ] = = [ " " ] > alice = { name="Alice", height=1.62 } > bob = { name="Bob" , height=1.85 } > chuck = { name="Chuck", height=1.76 } > > sortBy .name [chuck,alice,bob] == [alice,bob,chuck] > sortBy .height [chuck,alice,bob] == [alice,chuck,bob] > > sortBy String.length ["mouse","cat"] == ["cat","mouse"] -} sortBy :: Prelude.Ord b => (a -> b) -> List a -> List a sortBy = Data.List.sortOn | Sort values with a custom comparison function . > sortWith flippedComparison [ 1,2,3,4,5 ] = = [ 5,4,3,2,1 ] > > flippedComparison a b = > case compare a b of > LT - > GT > EQ - > EQ > GT - > LT This is also the most general sort function , allowing you to define any other : ` sort = = sortWith compare ` > sortWith flippedComparison [1,2,3,4,5] == [5,4,3,2,1] > > flippedComparison a b = > case compare a b of > LT -> GT > EQ -> EQ > GT -> LT This is also the most general sort function, allowing you to define any other: `sort == sortWith compare` -} sortWith :: (a -> a -> Ordering) -> List a -> List a sortWith = Data.List.sortBy DECONSTRUCT isEmpty :: List a -> Bool isEmpty = Data.List.null | Extract the first element of a list . > head [ 1,2,3 ] = = Just 1 > head [ ] = = Nothing Note : It is usually preferable to use a ` case ` to deconstruct a ` List ` because it gives you ` ( x : : xs ) ` and you can work with both subparts . > head [1,2,3] == Just 1 > head [] == Nothing Note: It is usually preferable to use a `case` to deconstruct a `List` because it gives you `(x :: xs)` and you can work with both subparts. -} head :: List a -> Maybe a head xs = case xs of x : _ -> Just x [] -> Nothing | Extract the rest of the list . > tail [ 1,2,3 ] = = Just [ 2,3 ] > tail [ ] = = Nothing Note : It is usually preferable to use a ` case ` to deconstruct a ` List ` because it gives you ` ( x : : xs ) ` and you can work with both subparts . > tail [1,2,3] == Just [2,3] > tail [] == Nothing Note: It is usually preferable to use a `case` to deconstruct a `List` because it gives you `(x :: xs)` and you can work with both subparts. -} tail :: List a -> Maybe (List a) tail list = case list of _ : xs -> Just xs [] -> Nothing | Take the first * n * members of a list . > take 2 [ 1,2,3,4 ] = = [ 1,2 ] > take 2 [1,2,3,4] == [1,2] -} take :: Int -> List a -> List a take = Data.List.take | Drop the first * n * members of a list . > drop 2 [ 1,2,3,4 ] = = [ 3,4 ] > drop 2 [1,2,3,4] == [3,4] -} drop :: Int -> List a -> List a drop = Data.List.drop | Partition a list based on some test . The first list contains all values that satisfy the test , and the second list contains all the value that do not . > partition ( \x - > x < 3 ) [ 0,1,2,3,4,5 ] = = ( [ 0,1,2 ] , [ 3,4,5 ] ) > partition isEven [ 0,1,2,3,4,5 ] = = ( [ 0,2,4 ] , [ 1,3,5 ] ) that satisfy the test, and the second list contains all the value that do not. > partition (\x -> x < 3) [0,1,2,3,4,5] == ([0,1,2], [3,4,5]) > partition isEven [0,1,2,3,4,5] == ([0,2,4], [1,3,5]) -} partition :: (a -> Bool) -> List a -> (List a, List a) partition = Data.List.partition | Decompose a list of tuples into a tuple of lists . > unzip [ ( 0 , True ) , ( 17 , False ) , ( 1337 , True ) ] = = ( [ 0,17,1337 ] , [ True , False , True ] ) > unzip [(0, True), (17, False), (1337, True)] == ([0,17,1337], [True,False,True]) -} unzip :: List (a, b) -> (List a, List b) unzip = Data.List.unzip toHMaybe :: Maybe a -> Data.Maybe.Maybe a toHMaybe maybe = case maybe of Just a -> Data.Maybe.Just a Nothing -> Data.Maybe.Nothing
e4738d3ef4d85c47ab507524b29a23bb80fcd70140eede9f4591edfeef8a3f0b
jyh/metaprl
itt_int_test.ml
extends Itt_struct extends Itt_int_ext extends Itt_int_arith extends Itt_supinf extends Itt_omega extends Itt_nat open Lm_debug open Lm_printf open Lm_num open Basic_tactics open Itt_struct open Itt_int_base open Itt_int_ext open Itt_int_arith open Itt_supinf open Itt_omega let debug_test_arith = create_debug (**) { debug_name = "test_arith"; debug_description = "Use arithT to prove tests"; debug_value = false } let debug_test_supinf = create_debug (**) { debug_name = "test_supinf"; debug_description = "Use Itt_supinf to prove tests"; debug_value = false } let debug_test_omega = create_debug (**) { debug_name = "test_omega"; debug_description = "Use omegaT to prove tests"; debug_value = true } let debug_test_no_ttca = create_debug (**) { debug_name = "test_no_ttca"; debug_description = "Do not use ttca as a suffix to prove tests"; debug_value = false } let test tac = funT (fun p -> if !debug_test_no_ttca then tac else tac ttca ) let testT = funT (fun p -> if !debug_test_supinf then test supinfT else if !debug_test_omega then test omegaT else if !debug_test_arith then test arithT else begin eprintf "Itt_int_test.testT: No tactic has been chosen@."; failT end ) interactive test 'a 'b 'c : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H> >- 'c in int } --> sequent { <H>; x: ('a >= ('b +@ 1)); t: ('c >= ('b +@ 3)); u: ('b >= ('a +@ 0)) >- "assert"{bfalse} } interactive test2 'a 'b 'c : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H> >- 'c in int } --> sequent { <H>; x: (('b +@ 1) <= 'a); t: ('c > ('b +@ 2)); u: ('b >= ('a +@ 0)) >- "assert"{bfalse} } interactive test3 'a 'b 'c : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H> >- 'c in int } --> sequent { <H>; x: (('b +@ 1) <= 'a); t: ('c > ('b +@ 2)) >- ('b < ('a +@ 0)) } interactive test4 'a 'b : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H>; x: ('a >= 'b); t: ('a < 'b) >- "assert"{bfalse} } interactive test5 'a 'b : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H>; x: ('a >= 'b +@ 0); t: ('a < 'b) >- "assert"{bfalse} } interactive test6 'b 'c : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H> >- 'c in int } --> sequent { <H>; x: (('c *@ ('b +@ ('a *@ 'c)) +@ ('b *@ 'c)) >= 'b +@ 0); t: (((((('c *@ 'b) *@ 1) +@ (2 *@ ('a *@ ('c *@ 'c)))) +@ (('c *@ ((-1) *@ 'a)) *@ 'c)) +@ ('b *@ 'c)) < 'b) >- "assert"{bfalse} } interactive test7 : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H>; 'a < 'b >- 'a <> 'b } interactive test8 : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H>; 'a < 'b >- not{'a = 'b in int} } interactive test9 : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H>; not{'a < 'b} >- 'a >= 'b } interactive test10 : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H>; 'a <> 'b >- 'a <> 'b } interactive test11 : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H> >- 'c in int } --> sequent { <H>; 'a +@ 'b >= 'c; 'c >= 'a +@ 'b +@ 1 >- "false" } interactive test12 : sequent { <H> >- 'a in int } --> sequent { <H>; 3 *@ 'a >= 1; 1 >= 2 *@ 'a >- "false" } interactive test13 : sequent { <H> >- 'a in int } --> sequent { <H>; 'a >= 0; 1 >= 5 *@ 'a >- "assert"{bfalse} } interactive test14 : sequent { <H>; 'a in int >- 2 *@ 'a = (2 *@ 'a) +@ 0 in int } interactive test15 : sequent { <H>; 'a in int >- 2 *@ 'a <> (2 *@ 'a) +@ 1 } let rec gen_term nvars vars intrange maxdepth = let choice=Random.int 2 in if maxdepth>0 && choice=0 then mk_add_term (gen_term nvars vars intrange (maxdepth-1)) (gen_term nvars vars intrange (maxdepth-1)) else if maxdepth>0 && choice=1 then mk_mul_term (gen_term nvars vars intrange (maxdepth-1)) (gen_term nvars vars intrange (maxdepth-1)) else let choice=Random.int 1 in if choice=0 then let i=Random.int (nvars-1) in vars.(i) else mk_number_term (num_of_int (Random.int intrange)) let gen_ineq nvars intrange = (Random.int (nvars-1), Random.int (nvars-1), Random.int intrange) let rec gen nvars intrange left = if left=0 then [] else (gen_ineq nvars intrange)::(gen nvars intrange (left-1)) let triple2term vars (v1,v2,n) = mk_ge_term vars.(v1) (mk_add_term vars.(v2) (mk_number_term (num_of_int n))) let rec assertListT vars = function [triple] -> assertT (triple2term vars triple) | hd::tl -> assertT (triple2term vars hd) thenMT (assertListT vars tl) | _ -> failT let genT vl seed nvars nineq intrange maxdepth = Random.init seed; let vars=Array.of_list vl in let vars = Array.init nvars ( fun i - > mk_var_term ( Lm_symbol.make " v " i ) ) in let terms=Array.init nvars (fun i -> gen_term nvars vars intrange maxdepth) in let l=gen nvars intrange nineq in assertListT terms l interactive testn : sequent {'v in int; 'v1 in int; 'v2 in int; 'v3 in int; 'v4 in int; 'v5 in int; 'v6 in int; 'v7 in int; 'v8 in int; 'v9 in int; "assert"{bfalse} >- "assert"{bfalse} } thm calc: sequent { <H> >- "not"{(((((1+@1)+@1)+@1)+@1)+@1)+@1 = 0 in nat} } = "autoT"
null
https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/itt/tests/itt_int_test.ml
ocaml
extends Itt_struct extends Itt_int_ext extends Itt_int_arith extends Itt_supinf extends Itt_omega extends Itt_nat open Lm_debug open Lm_printf open Lm_num open Basic_tactics open Itt_struct open Itt_int_base open Itt_int_ext open Itt_int_arith open Itt_supinf open Itt_omega let debug_test_arith = { debug_name = "test_arith"; debug_description = "Use arithT to prove tests"; debug_value = false } let debug_test_supinf = { debug_name = "test_supinf"; debug_description = "Use Itt_supinf to prove tests"; debug_value = false } let debug_test_omega = { debug_name = "test_omega"; debug_description = "Use omegaT to prove tests"; debug_value = true } let debug_test_no_ttca = { debug_name = "test_no_ttca"; debug_description = "Do not use ttca as a suffix to prove tests"; debug_value = false } let test tac = funT (fun p -> if !debug_test_no_ttca then tac else tac ttca ) let testT = funT (fun p -> if !debug_test_supinf then test supinfT else if !debug_test_omega then test omegaT else if !debug_test_arith then test arithT else begin eprintf "Itt_int_test.testT: No tactic has been chosen@."; failT end ) interactive test 'a 'b 'c : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H> >- 'c in int } --> sequent { <H>; x: ('a >= ('b +@ 1)); t: ('c >= ('b +@ 3)); u: ('b >= ('a +@ 0)) >- "assert"{bfalse} } interactive test2 'a 'b 'c : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H> >- 'c in int } --> sequent { <H>; x: (('b +@ 1) <= 'a); t: ('c > ('b +@ 2)); u: ('b >= ('a +@ 0)) >- "assert"{bfalse} } interactive test3 'a 'b 'c : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H> >- 'c in int } --> sequent { <H>; x: (('b +@ 1) <= 'a); t: ('c > ('b +@ 2)) >- ('b < ('a +@ 0)) } interactive test4 'a 'b : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H>; x: ('a >= 'b); t: ('a < 'b) >- "assert"{bfalse} } interactive test5 'a 'b : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H>; x: ('a >= 'b +@ 0); t: ('a < 'b) >- "assert"{bfalse} } interactive test6 'b 'c : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H> >- 'c in int } --> sequent { <H>; x: (('c *@ ('b +@ ('a *@ 'c)) +@ ('b *@ 'c)) >= 'b +@ 0); t: (((((('c *@ 'b) *@ 1) +@ (2 *@ ('a *@ ('c *@ 'c)))) +@ (('c *@ ((-1) *@ 'a)) *@ 'c)) +@ ('b *@ 'c)) < 'b) >- "assert"{bfalse} } interactive test7 : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H>; 'a < 'b >- 'a <> 'b } interactive test8 : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H>; 'a < 'b >- not{'a = 'b in int} } interactive test9 : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H>; not{'a < 'b} >- 'a >= 'b } interactive test10 : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H>; 'a <> 'b >- 'a <> 'b } interactive test11 : sequent { <H> >- 'a in int } --> sequent { <H> >- 'b in int } --> sequent { <H> >- 'c in int } --> sequent { <H>; 'a +@ 'b >= 'c; 'c >= 'a +@ 'b +@ 1 >- "false" } interactive test12 : sequent { <H> >- 'a in int } --> sequent { <H>; 3 *@ 'a >= 1; 1 >= 2 *@ 'a >- "false" } interactive test13 : sequent { <H> >- 'a in int } --> sequent { <H>; 'a >= 0; 1 >= 5 *@ 'a >- "assert"{bfalse} } interactive test14 : sequent { <H>; 'a in int >- 2 *@ 'a = (2 *@ 'a) +@ 0 in int } interactive test15 : sequent { <H>; 'a in int >- 2 *@ 'a <> (2 *@ 'a) +@ 1 } let rec gen_term nvars vars intrange maxdepth = let choice=Random.int 2 in if maxdepth>0 && choice=0 then mk_add_term (gen_term nvars vars intrange (maxdepth-1)) (gen_term nvars vars intrange (maxdepth-1)) else if maxdepth>0 && choice=1 then mk_mul_term (gen_term nvars vars intrange (maxdepth-1)) (gen_term nvars vars intrange (maxdepth-1)) else let choice=Random.int 1 in if choice=0 then let i=Random.int (nvars-1) in vars.(i) else mk_number_term (num_of_int (Random.int intrange)) let gen_ineq nvars intrange = (Random.int (nvars-1), Random.int (nvars-1), Random.int intrange) let rec gen nvars intrange left = if left=0 then [] else (gen_ineq nvars intrange)::(gen nvars intrange (left-1)) let triple2term vars (v1,v2,n) = mk_ge_term vars.(v1) (mk_add_term vars.(v2) (mk_number_term (num_of_int n))) let rec assertListT vars = function [triple] -> assertT (triple2term vars triple) | hd::tl -> assertT (triple2term vars hd) thenMT (assertListT vars tl) | _ -> failT let genT vl seed nvars nineq intrange maxdepth = Random.init seed; let vars=Array.of_list vl in let vars = Array.init nvars ( fun i - > mk_var_term ( Lm_symbol.make " v " i ) ) in let terms=Array.init nvars (fun i -> gen_term nvars vars intrange maxdepth) in let l=gen nvars intrange nineq in assertListT terms l interactive testn : sequent {'v in int; 'v1 in int; 'v2 in int; 'v3 in int; 'v4 in int; 'v5 in int; 'v6 in int; 'v7 in int; 'v8 in int; 'v9 in int; "assert"{bfalse} >- "assert"{bfalse} } thm calc: sequent { <H> >- "not"{(((((1+@1)+@1)+@1)+@1)+@1)+@1 = 0 in nat} } = "autoT"
9c2fdeddeef05d65196be12da1cb24a9abed0cba1c82327a8e82235ab8e34856
mdunnio/coinbase-pro
Authenticated.hs
# LANGUAGE DataKinds # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} module CoinbasePro.Authenticated ( accounts , account , accountHistory , accountHolds , listOrders , getOrder , getClientOrder , placeOrder , placeOrderBody , cancelOrder , cancelAll , fills , fees , trailingVolume , limits , deposits , withdrawals , transfer , makeDeposit , makeCoinbaseDeposit , cryptoDepositAddress , makeWithdrawal , makeCoinbaseWithdrawal , makeCryptoWithdrawal , withdrawalFeeEstimate , createStablecoinConversion , paymentMethods , coinbaseAccounts , profiles , profile , profileTransfer , createReport , getReport , getOracle ) where import Control.Monad (void) import Data.Aeson (ToJSON, encode) import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy.Char8 as LC8 import Data.Maybe (fromMaybe) import qualified Data.Set as S import Data.Text (Text, pack) import Data.Text.Encoding (encodeUtf8) import Data.Time.Clock (UTCTime) import Data.UUID (toText) import Network.HTTP.Types (SimpleQuery, SimpleQueryItem, methodDelete, methodGet, methodPost, renderQuery, simpleQueryToQuery) import Servant.Client (ClientM) import qualified CoinbasePro.Authenticated.API as API import CoinbasePro.Authenticated.Accounts (Account, AccountHistory, AccountId (..), Fees, Hold, TrailingVolume (..)) import CoinbasePro.Authenticated.CoinbaseAccounts (CoinbaseAccount) import CoinbasePro.Authenticated.Conversion (StablecoinConversionRequest (..), StablecoinConversionResponse) import CoinbasePro.Authenticated.Deposit (CoinbaseDepositRequest (..), CryptoDepositAddress, DepositRequest (..), DepositResponse) import CoinbasePro.Authenticated.Fills (Fill) import CoinbasePro.Authenticated.Limits (Limits) import CoinbasePro.Authenticated.Oracle (OracleResponse) import CoinbasePro.Authenticated.Orders (Order, PlaceOrderBody (..), STP, Status (..), Statuses (..), TimeInForce, statuses) import CoinbasePro.Authenticated.Payment (PaymentMethod, PaymentMethodId (..)) import CoinbasePro.Authenticated.Profile (Profile, ProfileTransfer (..)) import CoinbasePro.Authenticated.Report (ReportId (..), ReportRequest (..), ReportResponse) import CoinbasePro.Authenticated.Request (CBAuthT (..), authRequest) import CoinbasePro.Authenticated.Transfer (Transfer, TransferType (..)) import CoinbasePro.Authenticated.Withdrawal (CoinbaseWithdrawalRequest (..), CryptoWithdrawalRequest (..), CryptoWithdrawalResponse, WithdrawalFeeEstimateResponse (..), WithdrawalRequest (..), WithdrawalResponse) import CoinbasePro.Request (emptyBody, encodeRequestPath) import CoinbasePro.Types (ClientOrderId (..), CryptoAddress (..), CurrencyType (..), OrderId (..), OrderType, Price, ProductId (..), ProfileId, Side, Size) accountsPath :: Text accountsPath = "accounts" ordersPath :: Text ordersPath = "orders" depositsPath :: Text depositsPath = "deposits" withdrawalsPath :: Text withdrawalsPath = "withdrawals" coinbaseAccountPath :: Text coinbaseAccountPath = "coinbase-account" profilesPath :: Text profilesPath = "profiles" transferPath :: Text transferPath = "transfer" usersPath :: Text usersPath = "users" selfPath :: Text selfPath = "self" reportsPath :: Text reportsPath = "reports" mkSimpleQueryItem :: Show a => Text -> a -> SimpleQueryItem mkSimpleQueryItem s a = (encodeUtf8 s, encodeUtf8 $ pack (show a)) optionalQuery :: Show a => Text -> Maybe a -> [SimpleQueryItem] optionalQuery t = maybe [] (return . mkSimpleQueryItem t) mkProductQuery :: Maybe ProductId -> [SimpleQueryItem] mkProductQuery = optionalQuery "product_id" mkOrderIdQuery :: Maybe OrderId -> SimpleQuery mkOrderIdQuery = optionalQuery "order_id" encodeBody :: (ToJSON b) => b -> ByteString encodeBody = LC8.toStrict . encode -- | /#accounts accounts :: CBAuthT ClientM [Account] accounts = authRequest methodGet requestPath emptyBody API.accounts where requestPath = encodeRequestPath [accountsPath] -- | /#get-an-account account :: AccountId -> CBAuthT ClientM Account account aid@(AccountId t) = authRequest methodGet requestPath emptyBody $ API.singleAccount aid where requestPath = encodeRequestPath [accountsPath, t] -- | /#get-account-history accountHistory :: AccountId -> CBAuthT ClientM [AccountHistory] accountHistory aid@(AccountId t) = authRequest methodGet requestPath emptyBody $ API.accountHistory aid where ledgerPath = "ledger" requestPath = encodeRequestPath [accountsPath, t, ledgerPath] -- | /#get-holds accountHolds :: AccountId -> CBAuthT ClientM [Hold] accountHolds aid@(AccountId t) = authRequest methodGet requestPath emptyBody $ API.accountHolds aid where holdsPath = "holds" requestPath = encodeRequestPath [accountsPath, t, holdsPath] -- | /#list-orders listOrders :: Maybe [Status] -> Maybe ProductId -> CBAuthT ClientM [Order] listOrders st prid = authRequest methodGet requestPath emptyBody $ API.listOrders (defaultStatus st) prid where query = renderQuery True . simpleQueryToQuery $ orderQuery st prid requestPath = encodeRequestPath [ordersPath] <> query orderQuery :: Maybe [Status] -> Maybe ProductId -> SimpleQuery orderQuery ss p = statusQuery ss <> mkProductQuery p statusQuery :: Maybe [Status] -> [SimpleQueryItem] statusQuery ss = mkSimpleQueryItem "status" <$> S.toList (unStatuses . statuses $ defaultStatus ss) defaultStatus :: Maybe [Status] -> [Status] defaultStatus = fromMaybe [All] -- | /#get-an-order getOrder :: OrderId -> CBAuthT ClientM Order getOrder oid = authRequest methodGet requestPath emptyBody $ API.getOrder oid where requestPath = encodeRequestPath [ordersPath, unOrderId oid] -- | /#get-an-order getClientOrder :: ClientOrderId -> CBAuthT ClientM Order getClientOrder cloid = authRequest methodGet requestPath emptyBody $ API.getClientOrder cloid where oid = toText $ unClientOrderId cloid requestPath = encodeRequestPath [ordersPath, "client:" <> oid] -- | /#place-a-new-order placeOrder :: Maybe ClientOrderId -> ProductId -> Side -> Maybe Size -> Maybe Price -> Maybe Bool -> Maybe OrderType -> Maybe STP -> Maybe TimeInForce -> CBAuthT ClientM Order placeOrder clordid prid sd sz price po ot stp tif = authRequest methodPost requestPath (encodeBody body) $ API.placeOrder body where requestPath = encodeRequestPath [ordersPath] body = PlaceOrderBody clordid prid sd sz Nothing price po ot stp tif Nothing Nothing -- | /#place-a-new-order -- Use the underlying post body record placeOrderBody :: PlaceOrderBody -> CBAuthT ClientM Order placeOrderBody body = authRequest methodPost requestPath (encodeBody body) $ API.placeOrder body where requestPath = encodeRequestPath [ordersPath] -- | /#cancel-an-order cancelOrder :: OrderId -> CBAuthT ClientM () cancelOrder oid = void . authRequest methodDelete requestPath emptyBody $ API.cancelOrder oid where requestPath = encodeRequestPath [ordersPath, unOrderId oid] -- | /#cancel-all cancelAll :: Maybe ProductId -> CBAuthT ClientM [OrderId] cancelAll prid = authRequest methodDelete requestPath emptyBody (API.cancelAll prid) where query = renderQuery True . simpleQueryToQuery $ mkProductQuery prid requestPath = encodeRequestPath [ordersPath] <> query -- | /#fills fills :: Maybe ProductId -> Maybe OrderId -> CBAuthT ClientM [Fill] fills prid oid = authRequest methodGet requestPath emptyBody (API.fills prid oid) where fillsPath = "fills" query = renderQuery True . simpleQueryToQuery $ mkSimpleQuery prid oid requestPath = encodeRequestPath [fillsPath] <> query mkSimpleQuery :: Maybe ProductId -> Maybe OrderId -> SimpleQuery mkSimpleQuery p o = mkProductQuery p <> mkOrderIdQuery o -- | /#get-current-fees fees :: CBAuthT ClientM Fees fees = authRequest methodGet feesRequestPath emptyBody API.fees where feesPath = "fees" feesRequestPath = encodeRequestPath [feesPath] -- | /#trailing-volume trailingVolume :: CBAuthT ClientM [TrailingVolume] trailingVolume = authRequest methodGet requestPath emptyBody API.trailingVolume where requestPath = encodeRequestPath [usersPath, selfPath, "trailing-volume"] -- | /#get-current-exchange-limits limits :: CBAuthT ClientM Limits limits = authRequest methodGet requestPath emptyBody API.limits where requestPath = encodeRequestPath [usersPath, selfPath, "exchange-limits"] -- | /#list-deposits deposits :: Maybe ProfileId -> Maybe UTCTime -> Maybe UTCTime -> Maybe Int -> CBAuthT ClientM [Transfer] deposits = transfers DepositTransferType -- | /#list-withdrawals withdrawals :: Maybe ProfileId -> Maybe UTCTime -> Maybe UTCTime -> Maybe Int -> CBAuthT ClientM [Transfer] withdrawals = transfers WithdrawTransferType transfers :: TransferType -> Maybe ProfileId -> Maybe UTCTime -> Maybe UTCTime -> Maybe Int -> CBAuthT ClientM [Transfer] transfers tt prof before after lm = authRequest methodGet requestPath emptyBody $ API.transfers tt prof before after lm where typeQ = return $ mkSimpleQueryItem "type" tt profQ = optionalQuery "profile_id" prof beforeQ = optionalQuery "before" before afterQ = optionalQuery "after" after lmQ = optionalQuery "limit" lm query = renderQuery True . simpleQueryToQuery $ typeQ <> profQ <> beforeQ <> afterQ <> lmQ requestPath = encodeRequestPath [transferPath <> "s"] <> query -- | /#single-deposit | /#single-withdrawal transfer :: PaymentMethodId -> CBAuthT ClientM Transfer transfer pmt@(PaymentMethodId p) = authRequest methodGet requestPath emptyBody $ API.transfer pmt where requestPath = encodeRequestPath [transferPath <> "s", p] -- | /#payment-method makeDeposit :: Double -> Text -> PaymentMethodId -> CBAuthT ClientM DepositResponse makeDeposit amt cur pmi = authRequest methodPost requestPath (encodeBody body) $ API.makeDeposit body where requestPath = encodeRequestPath [depositsPath, "payment-method"] body = DepositRequest amt cur pmi -- | /#coinbase makeCoinbaseDeposit :: Double -> Text -> AccountId -> CBAuthT ClientM DepositResponse makeCoinbaseDeposit amt cur act = authRequest methodPost requestPath (encodeBody body) $ API.makeCoinbaseDeposit body where requestPath = encodeRequestPath [depositsPath, coinbaseAccountPath] body = CoinbaseDepositRequest amt cur act -- | /#generate-a-crypto-deposit-address cryptoDepositAddress :: AccountId -> CBAuthT ClientM CryptoDepositAddress cryptoDepositAddress act = authRequest methodPost requestPath emptyBody $ API.cryptoDepositAddress act where requestPath = encodeRequestPath [coinbaseAccountPath <> "s", pack $ show act, "addresses"] -- | /#payment-method55 makeWithdrawal :: Double -> Text -> PaymentMethodId -> CBAuthT ClientM WithdrawalResponse makeWithdrawal amt cur pmi = authRequest methodPost requestPath (encodeBody body) $ API.makeWithdrawal body where requestPath = encodeRequestPath [withdrawalsPath, "payment-method"] body = WithdrawalRequest amt cur pmi -- | /#coinbase56 makeCoinbaseWithdrawal :: Double -> Text -> AccountId -> CBAuthT ClientM WithdrawalResponse makeCoinbaseWithdrawal amt cur act = authRequest methodPost requestPath (encodeBody body) $ API.makeCoinbaseWithdrawal body where requestPath = encodeRequestPath [withdrawalsPath, coinbaseAccountPath] body = CoinbaseWithdrawalRequest amt cur act -- | /#crypto makeCryptoWithdrawal :: Double -> Text -> Text -> CBAuthT ClientM CryptoWithdrawalResponse makeCryptoWithdrawal amt cur addr = authRequest methodPost requestPath (encodeBody body) $ API.makeCryptoWithdrawal body where requestPath = encodeRequestPath [withdrawalsPath, "crypto"] body = CryptoWithdrawalRequest amt cur addr -- | /#fee-estimate withdrawalFeeEstimate :: CurrencyType -> CryptoAddress -> CBAuthT ClientM WithdrawalFeeEstimateResponse withdrawalFeeEstimate cur addr = authRequest methodGet requestPath emptyBody $ API.withdrawalFeeEstimate cur addr where curQ = return $ mkSimpleQueryItem "currency" cur addrQ = return $ mkSimpleQueryItem "crypto_address" addr query = renderQuery True . simpleQueryToQuery $ curQ <> addrQ requestPath = encodeRequestPath [withdrawalsPath, "fee-estimate"] <> query -- | /#stablecoin-conversions createStablecoinConversion :: CurrencyType -> CurrencyType -> Double -> CBAuthT ClientM StablecoinConversionResponse createStablecoinConversion fromCur toCur amt = authRequest methodPost requestPath (encodeBody body) $ API.createStablecoinConversion body where requestPath = encodeRequestPath ["conversions"] body = StablecoinConversionRequest fromCur toCur amt -- | /#list-payment-methods paymentMethods :: CBAuthT ClientM [PaymentMethod] paymentMethods = authRequest methodGet requestPath emptyBody API.paymentMethods where requestPath = encodeRequestPath ["payment-methods"] -- | /#list-accounts64 coinbaseAccounts :: CBAuthT ClientM [CoinbaseAccount] coinbaseAccounts = authRequest methodGet requestPath emptyBody API.coinbaseAccounts where requestPath = encodeRequestPath [coinbaseAccountPath <> "s"] -- | /#list-profiles profiles :: Maybe Bool -> CBAuthT ClientM [Profile] profiles active = authRequest methodGet requestPath emptyBody $ API.profiles active where activeQ = optionalQuery "active" active query = renderQuery True . simpleQueryToQuery $ activeQ requestPath = encodeRequestPath [profilesPath] <> query -- | /#get-a-profile profile :: ProfileId -> CBAuthT ClientM Profile profile profId = authRequest methodGet requestPath emptyBody $ API.profile profId where requestPath = encodeRequestPath [profilesPath, profId] -- | /#create-profile-transfer profileTransfer :: ProfileId -> ProfileId -> CurrencyType -> String -> CBAuthT ClientM () profileTransfer fromProf toProf cur amt = void . authRequest methodPost requestPath (encodeBody body) $ API.profileTransfer body where requestPath = encodeRequestPath [profilesPath, transferPath] body = ProfileTransfer fromProf toProf cur amt -- | /#create-a-new-report createReport :: ReportRequest -> CBAuthT ClientM ReportResponse createReport req = authRequest methodPost requestPath (encodeBody req) $ API.createReport req where requestPath = encodeRequestPath [reportsPath] -- | /#get-report-status getReport :: ReportId -> CBAuthT ClientM ReportResponse getReport rid = authRequest methodGet requestPath emptyBody $ API.getReport rid where requestPath = encodeRequestPath [reportsPath, toText $ unReportId rid] -- | /#oracle getOracle :: CBAuthT ClientM OracleResponse getOracle = authRequest methodGet requestPath emptyBody API.getOracle where requestPath = encodeRequestPath ["oracle"]
null
https://raw.githubusercontent.com/mdunnio/coinbase-pro/8016dbd7413b43ea4597eb0cb36cc01f7a18c1b4/src/lib/CoinbasePro/Authenticated.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE TypeFamilies # | /#accounts | /#get-an-account | /#get-account-history | /#get-holds | /#list-orders | /#get-an-order | /#get-an-order | /#place-a-new-order | /#place-a-new-order Use the underlying post body record | /#cancel-an-order | /#cancel-all | /#fills | /#get-current-fees | /#trailing-volume | /#get-current-exchange-limits | /#list-deposits | /#list-withdrawals | /#single-deposit | /#payment-method | /#coinbase | /#generate-a-crypto-deposit-address | /#payment-method55 | /#coinbase56 | /#crypto | /#fee-estimate | /#stablecoin-conversions | /#list-payment-methods | /#list-accounts64 | /#list-profiles | /#get-a-profile | /#create-profile-transfer | /#create-a-new-report | /#get-report-status | /#oracle
# LANGUAGE DataKinds # module CoinbasePro.Authenticated ( accounts , account , accountHistory , accountHolds , listOrders , getOrder , getClientOrder , placeOrder , placeOrderBody , cancelOrder , cancelAll , fills , fees , trailingVolume , limits , deposits , withdrawals , transfer , makeDeposit , makeCoinbaseDeposit , cryptoDepositAddress , makeWithdrawal , makeCoinbaseWithdrawal , makeCryptoWithdrawal , withdrawalFeeEstimate , createStablecoinConversion , paymentMethods , coinbaseAccounts , profiles , profile , profileTransfer , createReport , getReport , getOracle ) where import Control.Monad (void) import Data.Aeson (ToJSON, encode) import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy.Char8 as LC8 import Data.Maybe (fromMaybe) import qualified Data.Set as S import Data.Text (Text, pack) import Data.Text.Encoding (encodeUtf8) import Data.Time.Clock (UTCTime) import Data.UUID (toText) import Network.HTTP.Types (SimpleQuery, SimpleQueryItem, methodDelete, methodGet, methodPost, renderQuery, simpleQueryToQuery) import Servant.Client (ClientM) import qualified CoinbasePro.Authenticated.API as API import CoinbasePro.Authenticated.Accounts (Account, AccountHistory, AccountId (..), Fees, Hold, TrailingVolume (..)) import CoinbasePro.Authenticated.CoinbaseAccounts (CoinbaseAccount) import CoinbasePro.Authenticated.Conversion (StablecoinConversionRequest (..), StablecoinConversionResponse) import CoinbasePro.Authenticated.Deposit (CoinbaseDepositRequest (..), CryptoDepositAddress, DepositRequest (..), DepositResponse) import CoinbasePro.Authenticated.Fills (Fill) import CoinbasePro.Authenticated.Limits (Limits) import CoinbasePro.Authenticated.Oracle (OracleResponse) import CoinbasePro.Authenticated.Orders (Order, PlaceOrderBody (..), STP, Status (..), Statuses (..), TimeInForce, statuses) import CoinbasePro.Authenticated.Payment (PaymentMethod, PaymentMethodId (..)) import CoinbasePro.Authenticated.Profile (Profile, ProfileTransfer (..)) import CoinbasePro.Authenticated.Report (ReportId (..), ReportRequest (..), ReportResponse) import CoinbasePro.Authenticated.Request (CBAuthT (..), authRequest) import CoinbasePro.Authenticated.Transfer (Transfer, TransferType (..)) import CoinbasePro.Authenticated.Withdrawal (CoinbaseWithdrawalRequest (..), CryptoWithdrawalRequest (..), CryptoWithdrawalResponse, WithdrawalFeeEstimateResponse (..), WithdrawalRequest (..), WithdrawalResponse) import CoinbasePro.Request (emptyBody, encodeRequestPath) import CoinbasePro.Types (ClientOrderId (..), CryptoAddress (..), CurrencyType (..), OrderId (..), OrderType, Price, ProductId (..), ProfileId, Side, Size) accountsPath :: Text accountsPath = "accounts" ordersPath :: Text ordersPath = "orders" depositsPath :: Text depositsPath = "deposits" withdrawalsPath :: Text withdrawalsPath = "withdrawals" coinbaseAccountPath :: Text coinbaseAccountPath = "coinbase-account" profilesPath :: Text profilesPath = "profiles" transferPath :: Text transferPath = "transfer" usersPath :: Text usersPath = "users" selfPath :: Text selfPath = "self" reportsPath :: Text reportsPath = "reports" mkSimpleQueryItem :: Show a => Text -> a -> SimpleQueryItem mkSimpleQueryItem s a = (encodeUtf8 s, encodeUtf8 $ pack (show a)) optionalQuery :: Show a => Text -> Maybe a -> [SimpleQueryItem] optionalQuery t = maybe [] (return . mkSimpleQueryItem t) mkProductQuery :: Maybe ProductId -> [SimpleQueryItem] mkProductQuery = optionalQuery "product_id" mkOrderIdQuery :: Maybe OrderId -> SimpleQuery mkOrderIdQuery = optionalQuery "order_id" encodeBody :: (ToJSON b) => b -> ByteString encodeBody = LC8.toStrict . encode accounts :: CBAuthT ClientM [Account] accounts = authRequest methodGet requestPath emptyBody API.accounts where requestPath = encodeRequestPath [accountsPath] account :: AccountId -> CBAuthT ClientM Account account aid@(AccountId t) = authRequest methodGet requestPath emptyBody $ API.singleAccount aid where requestPath = encodeRequestPath [accountsPath, t] accountHistory :: AccountId -> CBAuthT ClientM [AccountHistory] accountHistory aid@(AccountId t) = authRequest methodGet requestPath emptyBody $ API.accountHistory aid where ledgerPath = "ledger" requestPath = encodeRequestPath [accountsPath, t, ledgerPath] accountHolds :: AccountId -> CBAuthT ClientM [Hold] accountHolds aid@(AccountId t) = authRequest methodGet requestPath emptyBody $ API.accountHolds aid where holdsPath = "holds" requestPath = encodeRequestPath [accountsPath, t, holdsPath] listOrders :: Maybe [Status] -> Maybe ProductId -> CBAuthT ClientM [Order] listOrders st prid = authRequest methodGet requestPath emptyBody $ API.listOrders (defaultStatus st) prid where query = renderQuery True . simpleQueryToQuery $ orderQuery st prid requestPath = encodeRequestPath [ordersPath] <> query orderQuery :: Maybe [Status] -> Maybe ProductId -> SimpleQuery orderQuery ss p = statusQuery ss <> mkProductQuery p statusQuery :: Maybe [Status] -> [SimpleQueryItem] statusQuery ss = mkSimpleQueryItem "status" <$> S.toList (unStatuses . statuses $ defaultStatus ss) defaultStatus :: Maybe [Status] -> [Status] defaultStatus = fromMaybe [All] getOrder :: OrderId -> CBAuthT ClientM Order getOrder oid = authRequest methodGet requestPath emptyBody $ API.getOrder oid where requestPath = encodeRequestPath [ordersPath, unOrderId oid] getClientOrder :: ClientOrderId -> CBAuthT ClientM Order getClientOrder cloid = authRequest methodGet requestPath emptyBody $ API.getClientOrder cloid where oid = toText $ unClientOrderId cloid requestPath = encodeRequestPath [ordersPath, "client:" <> oid] placeOrder :: Maybe ClientOrderId -> ProductId -> Side -> Maybe Size -> Maybe Price -> Maybe Bool -> Maybe OrderType -> Maybe STP -> Maybe TimeInForce -> CBAuthT ClientM Order placeOrder clordid prid sd sz price po ot stp tif = authRequest methodPost requestPath (encodeBody body) $ API.placeOrder body where requestPath = encodeRequestPath [ordersPath] body = PlaceOrderBody clordid prid sd sz Nothing price po ot stp tif Nothing Nothing placeOrderBody :: PlaceOrderBody -> CBAuthT ClientM Order placeOrderBody body = authRequest methodPost requestPath (encodeBody body) $ API.placeOrder body where requestPath = encodeRequestPath [ordersPath] cancelOrder :: OrderId -> CBAuthT ClientM () cancelOrder oid = void . authRequest methodDelete requestPath emptyBody $ API.cancelOrder oid where requestPath = encodeRequestPath [ordersPath, unOrderId oid] cancelAll :: Maybe ProductId -> CBAuthT ClientM [OrderId] cancelAll prid = authRequest methodDelete requestPath emptyBody (API.cancelAll prid) where query = renderQuery True . simpleQueryToQuery $ mkProductQuery prid requestPath = encodeRequestPath [ordersPath] <> query fills :: Maybe ProductId -> Maybe OrderId -> CBAuthT ClientM [Fill] fills prid oid = authRequest methodGet requestPath emptyBody (API.fills prid oid) where fillsPath = "fills" query = renderQuery True . simpleQueryToQuery $ mkSimpleQuery prid oid requestPath = encodeRequestPath [fillsPath] <> query mkSimpleQuery :: Maybe ProductId -> Maybe OrderId -> SimpleQuery mkSimpleQuery p o = mkProductQuery p <> mkOrderIdQuery o fees :: CBAuthT ClientM Fees fees = authRequest methodGet feesRequestPath emptyBody API.fees where feesPath = "fees" feesRequestPath = encodeRequestPath [feesPath] trailingVolume :: CBAuthT ClientM [TrailingVolume] trailingVolume = authRequest methodGet requestPath emptyBody API.trailingVolume where requestPath = encodeRequestPath [usersPath, selfPath, "trailing-volume"] limits :: CBAuthT ClientM Limits limits = authRequest methodGet requestPath emptyBody API.limits where requestPath = encodeRequestPath [usersPath, selfPath, "exchange-limits"] deposits :: Maybe ProfileId -> Maybe UTCTime -> Maybe UTCTime -> Maybe Int -> CBAuthT ClientM [Transfer] deposits = transfers DepositTransferType withdrawals :: Maybe ProfileId -> Maybe UTCTime -> Maybe UTCTime -> Maybe Int -> CBAuthT ClientM [Transfer] withdrawals = transfers WithdrawTransferType transfers :: TransferType -> Maybe ProfileId -> Maybe UTCTime -> Maybe UTCTime -> Maybe Int -> CBAuthT ClientM [Transfer] transfers tt prof before after lm = authRequest methodGet requestPath emptyBody $ API.transfers tt prof before after lm where typeQ = return $ mkSimpleQueryItem "type" tt profQ = optionalQuery "profile_id" prof beforeQ = optionalQuery "before" before afterQ = optionalQuery "after" after lmQ = optionalQuery "limit" lm query = renderQuery True . simpleQueryToQuery $ typeQ <> profQ <> beforeQ <> afterQ <> lmQ requestPath = encodeRequestPath [transferPath <> "s"] <> query | /#single-withdrawal transfer :: PaymentMethodId -> CBAuthT ClientM Transfer transfer pmt@(PaymentMethodId p) = authRequest methodGet requestPath emptyBody $ API.transfer pmt where requestPath = encodeRequestPath [transferPath <> "s", p] makeDeposit :: Double -> Text -> PaymentMethodId -> CBAuthT ClientM DepositResponse makeDeposit amt cur pmi = authRequest methodPost requestPath (encodeBody body) $ API.makeDeposit body where requestPath = encodeRequestPath [depositsPath, "payment-method"] body = DepositRequest amt cur pmi makeCoinbaseDeposit :: Double -> Text -> AccountId -> CBAuthT ClientM DepositResponse makeCoinbaseDeposit amt cur act = authRequest methodPost requestPath (encodeBody body) $ API.makeCoinbaseDeposit body where requestPath = encodeRequestPath [depositsPath, coinbaseAccountPath] body = CoinbaseDepositRequest amt cur act cryptoDepositAddress :: AccountId -> CBAuthT ClientM CryptoDepositAddress cryptoDepositAddress act = authRequest methodPost requestPath emptyBody $ API.cryptoDepositAddress act where requestPath = encodeRequestPath [coinbaseAccountPath <> "s", pack $ show act, "addresses"] makeWithdrawal :: Double -> Text -> PaymentMethodId -> CBAuthT ClientM WithdrawalResponse makeWithdrawal amt cur pmi = authRequest methodPost requestPath (encodeBody body) $ API.makeWithdrawal body where requestPath = encodeRequestPath [withdrawalsPath, "payment-method"] body = WithdrawalRequest amt cur pmi makeCoinbaseWithdrawal :: Double -> Text -> AccountId -> CBAuthT ClientM WithdrawalResponse makeCoinbaseWithdrawal amt cur act = authRequest methodPost requestPath (encodeBody body) $ API.makeCoinbaseWithdrawal body where requestPath = encodeRequestPath [withdrawalsPath, coinbaseAccountPath] body = CoinbaseWithdrawalRequest amt cur act makeCryptoWithdrawal :: Double -> Text -> Text -> CBAuthT ClientM CryptoWithdrawalResponse makeCryptoWithdrawal amt cur addr = authRequest methodPost requestPath (encodeBody body) $ API.makeCryptoWithdrawal body where requestPath = encodeRequestPath [withdrawalsPath, "crypto"] body = CryptoWithdrawalRequest amt cur addr withdrawalFeeEstimate :: CurrencyType -> CryptoAddress -> CBAuthT ClientM WithdrawalFeeEstimateResponse withdrawalFeeEstimate cur addr = authRequest methodGet requestPath emptyBody $ API.withdrawalFeeEstimate cur addr where curQ = return $ mkSimpleQueryItem "currency" cur addrQ = return $ mkSimpleQueryItem "crypto_address" addr query = renderQuery True . simpleQueryToQuery $ curQ <> addrQ requestPath = encodeRequestPath [withdrawalsPath, "fee-estimate"] <> query createStablecoinConversion :: CurrencyType -> CurrencyType -> Double -> CBAuthT ClientM StablecoinConversionResponse createStablecoinConversion fromCur toCur amt = authRequest methodPost requestPath (encodeBody body) $ API.createStablecoinConversion body where requestPath = encodeRequestPath ["conversions"] body = StablecoinConversionRequest fromCur toCur amt paymentMethods :: CBAuthT ClientM [PaymentMethod] paymentMethods = authRequest methodGet requestPath emptyBody API.paymentMethods where requestPath = encodeRequestPath ["payment-methods"] coinbaseAccounts :: CBAuthT ClientM [CoinbaseAccount] coinbaseAccounts = authRequest methodGet requestPath emptyBody API.coinbaseAccounts where requestPath = encodeRequestPath [coinbaseAccountPath <> "s"] profiles :: Maybe Bool -> CBAuthT ClientM [Profile] profiles active = authRequest methodGet requestPath emptyBody $ API.profiles active where activeQ = optionalQuery "active" active query = renderQuery True . simpleQueryToQuery $ activeQ requestPath = encodeRequestPath [profilesPath] <> query profile :: ProfileId -> CBAuthT ClientM Profile profile profId = authRequest methodGet requestPath emptyBody $ API.profile profId where requestPath = encodeRequestPath [profilesPath, profId] profileTransfer :: ProfileId -> ProfileId -> CurrencyType -> String -> CBAuthT ClientM () profileTransfer fromProf toProf cur amt = void . authRequest methodPost requestPath (encodeBody body) $ API.profileTransfer body where requestPath = encodeRequestPath [profilesPath, transferPath] body = ProfileTransfer fromProf toProf cur amt createReport :: ReportRequest -> CBAuthT ClientM ReportResponse createReport req = authRequest methodPost requestPath (encodeBody req) $ API.createReport req where requestPath = encodeRequestPath [reportsPath] getReport :: ReportId -> CBAuthT ClientM ReportResponse getReport rid = authRequest methodGet requestPath emptyBody $ API.getReport rid where requestPath = encodeRequestPath [reportsPath, toText $ unReportId rid] getOracle :: CBAuthT ClientM OracleResponse getOracle = authRequest methodGet requestPath emptyBody API.getOracle where requestPath = encodeRequestPath ["oracle"]
546d7c88c3d53bbc9565217d5d9206c3ab178fc1f410555c8f35c4db85bc81a3
nyu-acsys/drift
inductive1-2.ml
let rec loop x i = if i < 0 then x else if x < 1 then loop (x - 1) (i - 1) else if x > 2 then loop x (i - 1) else loop (3 - x) (i - 1) let main_p (n:int) = assert (loop 1 n >= 0) let main (w:unit) = let _ = main_p 4 in let _ = for i = 1 to 1000000 do main ( Random.int 1000 ) done for i = 1 to 1000000 do main (Random.int 1000) done *) () let _ = main ()
null
https://raw.githubusercontent.com/nyu-acsys/drift/51a3160d74b761626180da4f7dd0bb950cfe40c0/tests/benchmarks_call/r_type/first/inductive1-2.ml
ocaml
let rec loop x i = if i < 0 then x else if x < 1 then loop (x - 1) (i - 1) else if x > 2 then loop x (i - 1) else loop (3 - x) (i - 1) let main_p (n:int) = assert (loop 1 n >= 0) let main (w:unit) = let _ = main_p 4 in let _ = for i = 1 to 1000000 do main ( Random.int 1000 ) done for i = 1 to 1000000 do main (Random.int 1000) done *) () let _ = main ()
ff11e5ddd20b2d7a7c7b30bc3d6c12042f17d15308d320135450f9b23aa64b1c
aesiniath/unbeliever
System.hs
# OPTIONS_GHC -Wno - dodgy - exports # {-# OPTIONS_GHC -Wno-unused-imports #-} # OPTIONS_HADDOCK not - home # | Common elements from the rest of the ecosystem . This is mostly about re - exports . There are numerous types and functions that are more or less assumed to be in scope when you 're doing much of anything in Haskell ; this module is a convenience to pull in the ones we rely on for the rest of this library . You can just import this directly : @ import " Core . System " @ as there 's no particular benefit to cherry - picking the various sub - modules . Common elements from the rest of the Haskell ecosystem. This is mostly about re-exports. There are numerous types and functions that are more or less assumed to be in scope when you're doing much of anything in Haskell; this module is a convenience to pull in the ones we rely on for the rest of this library. You can just import this directly: @ import "Core.System" @ as there's no particular benefit to cherry-picking the various sub-modules. -} module Core.System ( -- * Base libraries -- | -- Re-exports from foundational libraries supplied by the compiler runtime, -- or from re-implementations of those areas. module Core.System.Base -- * External dependencies -- | Dependencies from libraries outside the traditional ecosystem of Haskell . -- These are typically special cases or custom re-implementations of things -- which are maintained either by ourselves or people we are in regular -- contact with. , module Core.System.External -- * Pretty Printing -- | When using the Render typeclass from " Core . Text . Utilities " you are presented with the @Doc a@ type for accumulating a \"document\ " to be -- pretty printed. There are a large family of combinators used when doing -- this. For convenience they are exposed here. , module Core.System.Pretty ) where import Core.System.Base import Core.System.External import Core.System.Pretty
null
https://raw.githubusercontent.com/aesiniath/unbeliever/a315a894c580b72ca32b3157518c6ba4653d9381/core-program/lib/Core/System.hs
haskell
# OPTIONS_GHC -Wno-unused-imports # * Base libraries | Re-exports from foundational libraries supplied by the compiler runtime, or from re-implementations of those areas. * External dependencies | These are typically special cases or custom re-implementations of things which are maintained either by ourselves or people we are in regular contact with. * Pretty Printing | pretty printed. There are a large family of combinators used when doing this. For convenience they are exposed here.
# OPTIONS_GHC -Wno - dodgy - exports # # OPTIONS_HADDOCK not - home # | Common elements from the rest of the ecosystem . This is mostly about re - exports . There are numerous types and functions that are more or less assumed to be in scope when you 're doing much of anything in Haskell ; this module is a convenience to pull in the ones we rely on for the rest of this library . You can just import this directly : @ import " Core . System " @ as there 's no particular benefit to cherry - picking the various sub - modules . Common elements from the rest of the Haskell ecosystem. This is mostly about re-exports. There are numerous types and functions that are more or less assumed to be in scope when you're doing much of anything in Haskell; this module is a convenience to pull in the ones we rely on for the rest of this library. You can just import this directly: @ import "Core.System" @ as there's no particular benefit to cherry-picking the various sub-modules. -} module Core.System module Core.System.Base Dependencies from libraries outside the traditional ecosystem of Haskell . , module Core.System.External When using the Render typeclass from " Core . Text . Utilities " you are presented with the @Doc a@ type for accumulating a \"document\ " to be , module Core.System.Pretty ) where import Core.System.Base import Core.System.External import Core.System.Pretty
0e122c0e2a5440bbf72ffa1099c25a07fdacfcf409b65fe9f75f2ca4b6b68c59
hbr/albatross
process.ml
open Js_of_ocaml open Js class type stream = object method fd: int readonly_prop end class type process = object method argv: (js_string t) js_array t readonly_prop method cwd: js_string t meth method exit: int -> 'a meth method nextTick: (unit -> unit) callback -> unit meth method stdin: stream t readonly_prop method stdout: stream t readonly_prop method stderr: stream t readonly_prop end let process: process t = Unsafe.eval_string "require('process')" let next_tick (k:unit -> unit): unit = process##nextTick (wrap_callback k) let exit (code:int): 'a = Printf.printf "exiting with code %d\n" code; process##exit code let command_line: string array = let arr = to_array process##.argv in let len = Array.length arr in assert (0 < len); Array.map to_string (Array.sub arr 1 (len - 1)) let current_working_directory (_:unit): string = to_string process##cwd
null
https://raw.githubusercontent.com/hbr/albatross/8f28ef97951f92f30dc69cf94c0bbe20d64fba21/ocaml/fmlib/node/process.ml
ocaml
open Js_of_ocaml open Js class type stream = object method fd: int readonly_prop end class type process = object method argv: (js_string t) js_array t readonly_prop method cwd: js_string t meth method exit: int -> 'a meth method nextTick: (unit -> unit) callback -> unit meth method stdin: stream t readonly_prop method stdout: stream t readonly_prop method stderr: stream t readonly_prop end let process: process t = Unsafe.eval_string "require('process')" let next_tick (k:unit -> unit): unit = process##nextTick (wrap_callback k) let exit (code:int): 'a = Printf.printf "exiting with code %d\n" code; process##exit code let command_line: string array = let arr = to_array process##.argv in let len = Array.length arr in assert (0 < len); Array.map to_string (Array.sub arr 1 (len - 1)) let current_working_directory (_:unit): string = to_string process##cwd
1fd5af2e09d9c65419ee22eed307ca2af3731c5d3a1ea73ec6c13366ab6f2348
snmsts/cl-langserver
clisp.lisp
;;;; -*- indent-tabs-mode: nil -*- SLYNK support for CLISP . Copyright ( C ) 2003 , 2004 , ;;;; 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 . ;;; This is work in progress, but it's already usable. Many things ;;; are adapted from other slynk-*.lisp, in particular from ;;; slynk-allegro (I don't use allegro at all, but it's the shortest one and I found code there enlightening ) . This code will work better with recent versions of CLISP ( say , the last release or CVS HEAD ) while it may not work at all with older ;;; versions. It is reasonable to expect it to work on platforms with ;;; a "SOCKET" package, in particular on GNU/Linux or Unix-like systems , but also on . This backend uses the portable xref from the CMU AI repository and metering.lisp from CLOCC [ 1 ] , which ;;; are conveniently included in SLY. [ 1 ] / (defpackage :ls-clisp (:use cl ls-backend)) (in-package ls-clisp) (eval-when (:compile-toplevel) (unless (string< "2.44" (lisp-implementation-version)) (error "Need at least CLISP version 2.44"))) (defimplementation gray-package-name () "GRAY") if this lisp has the complete CLOS then we use it , otherwise we ;;;; build up a "fake" slynk-mop and then override the methods in the ;;;; inspector. (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *have-mop* (and (find-package :clos) (eql :external (nth-value 1 (find-symbol (string ':standard-slot-definition) :clos)))) "True in those CLISP images which have a complete MOP implementation.")) #+#.(cl:if slynk-clisp::*have-mop* '(cl:and) '(cl:or)) (progn (import-ls-mop-symbols :clos '(:slot-definition-documentation)) (defun slynk-mop:slot-definition-documentation (slot) (clos::slot-definition-documentation slot))) #-#.(cl:if slynk-clisp::*have-mop* '(and) '(or)) (defclass slynk-mop:standard-slot-definition () () (:documentation "Dummy class created so that slynk.lisp will compile and load.")) (let ((getpid (or (find-symbol "PROCESS-ID" :system) old name prior to 2005 - 03 - 01 , clisp < = 2.33.2 (find-symbol "PROGRAM-ID" :system) integrated into the above since 2005 - 02 - 24 (and (find-package :win32) ; optional modules/win32 (find-symbol "GetCurrentProcessId" :win32))))) (defimplementation getpid () ; a required interface (cond (getpid (funcall getpid)) #+win32 ((ext:getenv "PID")) ; where does that come from? (t -1)))) (defimplementation call-with-user-break-handler (handler function) (handler-bind ((system::simple-interrupt-condition (lambda (c) (declare (ignore c)) (funcall handler) (when (find-restart 'socket-status) (invoke-restart (find-restart 'socket-status))) (continue)))) (funcall function))) (defimplementation lisp-implementation-type-name () "clisp") (defimplementation set-default-directory (directory) (setf (ext:default-directory) directory) (namestring (setf *default-pathname-defaults* (ext:default-directory)))) (defimplementation filename-to-pathname (string) (cond ((member :cygwin *features*) (parse-cygwin-filename string)) (t (parse-namestring string)))) (defun parse-cygwin-filename (string) (multiple-value-bind (match _ drive absolute) (regexp:match "^(([a-zA-Z\\]+):)?([\\/])?" string :extended t) (declare (ignore _)) (assert (and match (if drive absolute t)) () "Invalid filename syntax: ~a" string) (let* ((sans-prefix (subseq string (regexp:match-end match))) (path (remove "" (regexp:regexp-split "[\\/]" sans-prefix))) (path (loop for name in path collect (cond ((equal name "..") ':back) (t name)))) (directoryp (or (equal string "") (find (aref string (1- (length string))) "\\/")))) (multiple-value-bind (file type) (cond ((and (not directoryp) (last path)) (let* ((file (car (last path))) (pos (position #\. file :from-end t))) (cond ((and pos (> pos 0)) (values (subseq file 0 pos) (subseq file (1+ pos)))) (t file))))) (make-pathname :host nil :device nil :directory (cons (if absolute :absolute :relative) (let ((path (if directoryp path (butlast path)))) (if drive (cons (regexp:match-string string drive) path) path))) :name file :type type))))) UTF (defimplementation string-to-utf8 (string) (let ((enc (load-time-value (ext:make-encoding :charset "utf-8" :line-terminator :unix) t))) (ext:convert-string-to-bytes string enc))) (defimplementation utf8-to-string (octets) (let ((enc (load-time-value (ext:make-encoding :charset "utf-8" :line-terminator :unix) t))) (ext:convert-string-from-bytes octets enc))) ;;;; TCP Server (defimplementation create-socket (host port &key backlog) (socket:socket-server port :interface host :backlog (or backlog 5))) (defimplementation local-port (socket) (socket:socket-server-port socket)) (defimplementation close-socket (socket) (socket:socket-server-close socket)) (defimplementation accept-connection (socket &key external-format buffering timeout) (declare (ignore buffering timeout)) (socket:socket-accept socket :buffered buffering ;; XXX may not work if t :element-type (if external-format 'character '(unsigned-byte 8)) :external-format (or external-format :default))) #-win32 (defimplementation wait-for-input (streams &optional timeout) (assert (member timeout '(nil t))) (let ((streams (mapcar (lambda (s) (list* s :input nil)) streams))) (loop (cond ((check-sly-interrupts) (return :interrupt)) (timeout (socket:socket-status streams 0 0) (return (loop for (s nil . x) in streams if x collect s))) (t (with-simple-restart (socket-status "Return from socket-status.") (socket:socket-status streams 0 500000)) (let ((ready (loop for (s nil . x) in streams if x collect s))) (when ready (return ready)))))))) #+win32 (defimplementation wait-for-input (streams &optional timeout) (assert (member timeout '(nil t))) (loop (cond ((check-sly-interrupts) (return :interrupt)) (t (let ((ready (remove-if-not #'input-available-p streams))) (when ready (return ready))) (when timeout (return nil)) (sleep 0.1))))) #+win32 ;; Some facts to remember (for the next time we need to debug this): ;; - interactive-sream-p returns t for socket-streams ;; - listen returns nil for socket-streams ;; - (type-of <socket-stream>) is 'stream - ( type - of * terminal - io * ) is ' two - way - stream - stream - element - type on our sockets is usually ( UNSIGNED - BYTE 8) ;; - calling socket:socket-status on non sockets signals an error, ;; but seems to mess up something internally. ;; - calling read-char-no-hang on sockets does not signal an error, ;; but seems to mess up something internally. (defun input-available-p (stream) (case (stream-element-type stream) (character (let ((c (read-char-no-hang stream nil nil))) (cond ((not c) nil) (t (unread-char c stream) t)))) (t (eq (socket:socket-status (cons stream :input) 0 0) :input)))) ;;;; Coding systems (defvar *external-format-to-coding-system* '(((:charset "iso-8859-1" :line-terminator :unix) "latin-1-unix" "iso-latin-1-unix" "iso-8859-1-unix") ((:charset "iso-8859-1") "latin-1" "iso-latin-1" "iso-8859-1") ((:charset "utf-8") "utf-8") ((:charset "utf-8" :line-terminator :unix) "utf-8-unix") ((:charset "euc-jp") "euc-jp") ((:charset "euc-jp" :line-terminator :unix) "euc-jp-unix") ((:charset "us-ascii") "us-ascii") ((:charset "us-ascii" :line-terminator :unix) "us-ascii-unix"))) (defimplementation find-external-format (coding-system) (let ((args (car (rassoc-if (lambda (x) (member coding-system x :test #'equal)) *external-format-to-coding-system*)))) (and args (apply #'ext:make-encoding args)))) ;;;; Slynk functions (defimplementation arglist (fname) (block nil (or (ignore-errors (let ((exp (function-lambda-expression fname))) (and exp (return (second exp))))) (ignore-errors (return (ext:arglist fname))) :not-available))) (defimplementation macroexpand-all (form &optional env) (declare (ignore env)) (ext:expand-form form)) (defimplementation describe-symbol-for-emacs (symbol) "Return a plist describing SYMBOL. Return NIL if the symbol is unbound." (let ((result ())) (flet ((doc (kind) (or (documentation symbol kind) :not-documented)) (maybe-push (property value) (when value (setf result (list* property value result))))) (maybe-push :variable (when (boundp symbol) (doc 'variable))) (when (fboundp symbol) (maybe-push ;; Report WHEN etc. as macros, even though they may be ;; implemented as special operators. (if (macro-function symbol) :macro (typecase (fdefinition symbol) (generic-function :generic-function) (function :function) ;; (type-of 'progn) -> ext:special-operator (t :special-operator))) (doc 'function))) e.g. # ' ( setf elt ) defsetf (maybe-push :setf (doc 'setf))) (when (or (get symbol 'system::type-symbol); cf. clisp/src/describe.lisp (get symbol 'system::defstruct-description) (get symbol 'system::deftype-expander)) (maybe-push :type (doc 'type))) ; even for 'structure (when (find-class symbol nil) (maybe-push :class (doc 'type))) Let this code work compiled in images without FFI (let ((types (load-time-value (and (find-package "FFI") (symbol-value (find-symbol "*C-TYPE-TABLE*" "FFI")))))) ;; Use ffi::*c-type-table* so as not to suffer the overhead of ( ignore - errors ( ffi : parse - c - type symbol ) ) for 99.9 % of symbols which are not FFI type names . (when (and types (nth-value 1 (gethash symbol types))) ;; Maybe use (case (head (ffi:deparse-c-type))) ;; to distinguish struct and union types? (maybe-push :alien-type :not-documented))) result))) (defimplementation describe-definition (symbol namespace) (ecase namespace (:variable (describe symbol)) (:macro (describe (macro-function symbol))) (:function (describe (symbol-function symbol))) (:class (describe (find-class symbol))))) (defimplementation type-specifier-p (symbol) (or (ignore-errors (subtypep nil symbol)) (not (eq (type-specifier-arglist symbol) :not-available)))) (defun fspec-pathname (spec) (let ((path spec) type lines) (when (consp path) (psetq type (car path) path (cadr path) lines (cddr path))) (when (and path (member (pathname-type path) custom:*compiled-file-types* :test #'equal)) (setq path (loop for suffix in custom:*source-file-types* thereis (probe-file (make-pathname :defaults path :type suffix))))) (values path type lines))) (defun fspec-location (name fspec) (multiple-value-bind (file type lines) (fspec-pathname fspec) (list (if type (list name type) name) (cond (file (multiple-value-bind (truename c) (ignore-errors (truename file)) (cond (truename (make-location (list :file (namestring truename)) (if (consp lines) (list* :line lines) (list :function-name (string name))) (when (consp type) (list :snippet (format nil "~A" type))))) (t (list :error (princ-to-string c)))))) (t (list :error (format nil "No source information available for: ~S" fspec))))))) (defimplementation find-definitions (name) (mapcar #'(lambda (e) (fspec-location name e)) (documentation name 'sys::file))) (defun trim-whitespace (string) (string-trim #(#\newline #\space #\tab) string)) (defvar *sly-db-backtrace*) (defun sly-db-backtrace () "Return a list ((ADDRESS . DESCRIPTION) ...) of frames." (let* ((modes '((:all-stack-elements 1) (:all-frames 2) (:only-lexical-frames 3) (:only-eval-and-apply-frames 4) (:only-apply-frames 5))) (mode (cadr (assoc :all-stack-elements modes)))) (do ((frames '()) (last nil frame) (frame (sys::the-frame) (sys::frame-up 1 frame mode))) ((eq frame last) (nreverse frames)) (unless (boring-frame-p frame) (push frame frames))))) (defimplementation call-with-debugging-environment (debugger-loop-fn) (let* (;;(sys::*break-count* (1+ sys::*break-count*)) ;;(sys::*driver* debugger-loop-fn) ;;(sys::*fasoutput-stream* nil) (*sly-db-backtrace* (let* ((f (sys::the-frame)) (bt (sly-db-backtrace)) (rest (member f bt))) (if rest (nthcdr 8 rest) bt)))) (funcall debugger-loop-fn))) (defun nth-frame (index) (nth index *sly-db-backtrace*)) (defun boring-frame-p (frame) (member (frame-type frame) '(stack-value bind-var bind-env compiled-tagbody compiled-block))) (defun frame-to-string (frame) (with-output-to-string (s) (sys::describe-frame s frame))) (defun frame-type (frame) ;; FIXME: should bind *print-length* etc. to small values. (frame-string-type (frame-to-string frame))) FIXME : they changed the layout in 2.44 and not all patterns have ;; been updated. (defvar *frame-prefixes* '(("\\[[0-9]\\+\\] frame binding variables" bind-var) ("<1> #<compiled-function" compiled-fun) ("<1> #<system-function" sys-fun) ("<1> #<special-operator" special-op) ("EVAL frame" eval) ("APPLY frame" apply) ("\\[[0-9]\\+\\] compiled tagbody frame" compiled-tagbody) ("\\[[0-9]\\+\\] compiled block frame" compiled-block) ("block frame" block) ("nested block frame" block) ("tagbody frame" tagbody) ("nested tagbody frame" tagbody) ("catch frame" catch) ("handler frame" handler) ("unwind-protect frame" unwind-protect) ("driver frame" driver) ("\\[[0-9]\\+\\] frame binding environments" bind-env) ("CALLBACK frame" callback) ("- " stack-value) ("<1> " fun) ("<2> " 2nd-frame) )) (defun frame-string-type (string) (cadr (assoc-if (lambda (pattern) (is-prefix-p pattern string)) *frame-prefixes*))) (defimplementation compute-backtrace (start end) (let* ((bt *sly-db-backtrace*) (len (length bt))) (loop for f in (subseq bt start (min (or end len) len)) collect f))) (defimplementation print-frame (frame stream) (let* ((str (frame-to-string frame))) (write-string (extract-frame-line str) stream))) (defun extract-frame-line (frame-string) (let ((s frame-string)) (trim-whitespace (case (frame-string-type s) ((eval special-op) (string-match "EVAL frame .*for form \\(.*\\)" s 1)) (apply (string-match "APPLY frame for call \\(.*\\)" s 1)) ((compiled-fun sys-fun fun) (extract-function-name s)) (t s))))) (defun extract-function-name (string) (let ((1st (car (split-frame-string string)))) (or (string-match (format nil "^<1>[ ~%]*#<[-A-Za-z]* \\(.*\\)>") 1st 1) (string-match (format nil "^<1>[ ~%]*\\(.*\\)") 1st 1) 1st))) (defun split-frame-string (string) (let ((rx (format nil "~%\\(~{~A~^\\|~}\\)" (mapcar #'car *frame-prefixes*)))) (loop for pos = 0 then (1+ (regexp:match-start match)) for match = (regexp:match rx string :start pos) if match collect (subseq string pos (regexp:match-start match)) else collect (subseq string pos) while match))) (defun string-match (pattern string n) (let* ((match (nth-value n (regexp:match pattern string)))) (if match (regexp:match-string string match)))) (defimplementation eval-in-frame (form frame-number) (sys::eval-at (nth-frame frame-number) form)) (defimplementation frame-locals (frame-number) (let ((frame (nth-frame frame-number))) (loop for i below (%frame-count-vars frame) collect (list :name (%frame-var-name frame i) :value (%frame-var-value frame i) :id 0)))) (defimplementation frame-var-value (frame var) (%frame-var-value (nth-frame frame) var)) ;;; Interpreter-Variablen-Environment has the shape NIL or # ( v1 val1 ... vn valn NEXT - ENV ) . (defun %frame-count-vars (frame) (cond ((sys::eval-frame-p frame) (do ((venv (frame-venv frame) (next-venv venv)) (count 0 (+ count (/ (1- (length venv)) 2)))) ((not venv) count))) ((member (frame-type frame) '(compiled-fun sys-fun fun special-op)) (length (%parse-stack-values frame))) (t 0))) (defun %frame-var-name (frame i) (cond ((sys::eval-frame-p frame) (nth-value 0 (venv-ref (frame-venv frame) i))) (t (format nil "~D" i)))) (defun %frame-var-value (frame i) (cond ((sys::eval-frame-p frame) (let ((name (venv-ref (frame-venv frame) i))) (multiple-value-bind (v c) (ignore-errors (sys::eval-at frame name)) (if c (format-sly-db-condition c) v)))) ((member (frame-type frame) '(compiled-fun sys-fun fun special-op)) (let ((str (nth i (%parse-stack-values frame)))) (trim-whitespace (subseq str 2)))) (t (break "Not implemented")))) (defun frame-venv (frame) (let ((env (sys::eval-at frame '(sys::the-environment)))) (svref env 0))) (defun next-venv (venv) (svref venv (1- (length venv)))) (defun venv-ref (env i) "Reference the Ith binding in ENV. Return two values: NAME and VALUE" (let ((idx (* i 2))) (if (< idx (1- (length env))) (values (svref env idx) (svref env (1+ idx))) (venv-ref (next-venv env) (- i (/ (1- (length env)) 2)))))) (defun %parse-stack-values (frame) (labels ((next (fp) (sys::frame-down 1 fp 1)) (parse (fp accu) (let ((str (frame-to-string fp))) (cond ((is-prefix-p "- " str) (parse (next fp) (cons str accu))) ((is-prefix-p "<1> " str) ;;(when (eq (frame-type frame) 'compiled-fun) ;; (pop accu)) (dolist (str (cdr (split-frame-string str))) (when (is-prefix-p "- " str) (push str accu))) (nreverse accu)) (t (parse (next fp) accu)))))) (parse (next frame) '()))) (defun is-prefix-p (regexp string) (if (regexp:match (concatenate 'string "^" regexp) string) t)) (defimplementation return-from-frame (index form) (sys::return-from-eval-frame (nth-frame index) form)) (defimplementation restart-frame (index) (sys::redo-eval-frame (nth-frame index))) (defimplementation frame-source-location (index) `(:error ,(format nil "frame-source-location not implemented. (frame: ~A)" (nth-frame index)))) ;;;; Profiling (defimplementation profile (fname) (eval `(ls-monitor:monitor ,fname))) ;monitor is a macro (defimplementation profiled-functions () ls-monitor:*monitored-functions*) (defimplementation unprofile (fname) (eval `(ls-monitor:unmonitor ,fname))) ;unmonitor is a macro (defimplementation unprofile-all () (ls-monitor:unmonitor)) (defimplementation profile-report () (ls-monitor:report-monitoring)) (defimplementation profile-reset () (ls-monitor:reset-all-monitoring)) (defimplementation profile-package (package callers-p methods) (declare (ignore callers-p methods)) (ls-monitor:monitor-all package)) ;;;; Handle compiler conditions (find out location of error etc.) (defmacro compile-file-frobbing-notes ((&rest args) &body body) "Pass ARGS to COMPILE-FILE, send the compiler notes to *STANDARD-INPUT* and frob them in BODY." `(let ((*error-output* (make-string-output-stream)) (*compile-verbose* t)) (multiple-value-prog1 (compile-file ,@args) (handler-case (with-input-from-string (*standard-input* (get-output-stream-string *error-output*)) ,@body) (sys::simple-end-of-file () nil))))) (defvar *orig-c-warn* (symbol-function 'system::c-warn)) (defvar *orig-c-style-warn* (symbol-function 'system::c-style-warn)) (defvar *orig-c-error* (symbol-function 'system::c-error)) (defvar *orig-c-report-problems* (symbol-function 'system::c-report-problems)) (defmacro dynamic-flet (names-functions &body body) "(dynamic-flet ((NAME FUNCTION) ...) BODY ...) Execute BODY with NAME's function slot set to FUNCTION." `(ext:letf* ,(loop for (name function) in names-functions collect `((symbol-function ',name) ,function)) ,@body)) (defvar *buffer-name* nil) (defvar *buffer-offset*) (defun compiler-note-location () "Return the current compiler location." (let ((lineno1 sys::*compile-file-lineno1*) (lineno2 sys::*compile-file-lineno2*) (file sys::*compile-file-truename*)) (cond ((and file lineno1 lineno2) (make-location (list ':file (namestring file)) (list ':line lineno1))) (*buffer-name* (make-location (list ':buffer *buffer-name*) (list ':offset *buffer-offset* 0))) (t (list :error "No error location available"))))) (defun signal-compiler-warning (cstring args severity orig-fn) (signal 'compiler-condition :severity severity :message (apply #'format nil cstring args) :location (compiler-note-location)) (apply orig-fn cstring args)) (defun c-warn (cstring &rest args) (signal-compiler-warning cstring args :warning *orig-c-warn*)) (defun c-style-warn (cstring &rest args) (dynamic-flet ((sys::c-warn *orig-c-warn*)) (signal-compiler-warning cstring args :style-warning *orig-c-style-warn*))) (defun c-error (&rest args) (signal 'compiler-condition :severity :error :message (apply #'format nil (if (= (length args) 3) (cdr args) args)) :location (compiler-note-location)) (apply *orig-c-error* args)) (defimplementation call-with-compilation-hooks (function) (handler-bind ((warning #'handle-notification-condition)) (dynamic-flet ((system::c-warn #'c-warn) (system::c-style-warn #'c-style-warn) (system::c-error #'c-error)) (funcall function)))) (defun handle-notification-condition (condition) "Handle a condition caused by a compiler warning." (signal 'compiler-condition :original-condition condition :severity :warning :message (princ-to-string condition) :location (compiler-note-location))) (defimplementation slynk-compile-file (input-file output-file load-p external-format &key policy) (declare (ignore policy)) (with-compilation-hooks () (with-compilation-unit () (multiple-value-bind (fasl-file warningsp failurep) (compile-file input-file :output-file output-file :external-format external-format) (values fasl-file warningsp (or failurep (and load-p (not (load fasl-file))))))))) (defimplementation slynk-compile-string (string &key buffer position filename policy) (declare (ignore filename policy)) (with-compilation-hooks () (let ((*buffer-name* buffer) (*buffer-offset* position)) (funcall (compile nil (read-from-string (format nil "(~S () ~A)" 'lambda string)))) t))) from the CMU AI repository . (setq pxref::*handle-package-forms* '(cl:in-package)) (defmacro defxref (name function) `(defimplementation ,name (name) (xref-results (,function name)))) (defxref who-calls pxref:list-callers) (defxref who-references pxref:list-readers) (defxref who-binds pxref:list-setters) (defxref who-sets pxref:list-setters) (defxref list-callers pxref:list-callers) (defxref list-callees pxref:list-callees) (defun xref-results (symbols) (let ((xrefs '())) (dolist (symbol symbols) (push (fspec-location symbol symbol) xrefs)) xrefs)) (when (find-package :ls-loader) (setf (symbol-function (intern "USER-INIT-FILE" :ls-loader)) (lambda () (let ((home (user-homedir-pathname))) (and (ext:probe-directory home) (probe-file (format nil "~A/.slynk.lisp" (namestring (truename home))))))))) ;;; Don't set *debugger-hook* to nil on break. (ext:without-package-lock () (defun break (&optional (format-string "Break") &rest args) (if (not sys::*use-clcs*) (progn (terpri *error-output*) (apply #'format *error-output* (concatenate 'string "*** - " format-string) args) (funcall ext:*break-driver* t)) (let ((condition (make-condition 'simple-condition :format-control format-string :format-arguments args)) ;;(*debugger-hook* nil) Issue 91 ) (ext:with-restarts ((continue :report (lambda (stream) (format stream (sys::text "Return from ~S loop") 'break)) ())) (with-condition-restarts condition (list (find-restart 'continue)) (invoke-debugger condition))))) nil)) ;;;; Inspecting (defmethod emacs-inspect ((o t)) (let* ((*print-array* nil) (*print-pretty* t) (*print-circle* t) (*print-escape* t) (*print-lines* custom:*inspect-print-lines*) (*print-level* custom:*inspect-print-level*) (*print-length* custom:*inspect-print-length*) (sys::*inspect-all* (make-array 10 :fill-pointer 0 :adjustable t)) (tmp-pack (make-package (gensym "INSPECT-TMP-PACKAGE-"))) (*package* tmp-pack) (sys::*inspect-unbound-value* (intern "#<unbound>" tmp-pack))) (let ((inspection (sys::inspect-backend o))) (append (list (format nil "~S~% ~A~{~%~A~}~%" o (sys::insp-title inspection) (sys::insp-blurb inspection))) (loop with count = (sys::insp-num-slots inspection) for i below count append (multiple-value-bind (value name) (funcall (sys::insp-nth-slot inspection) i) `((:value ,name) " = " (:value ,value) (:newline)))))))) (defimplementation quit-lisp () #+lisp=cl (ext:quit) #-lisp=cl (lisp:quit)) (defimplementation preferred-communication-style () nil) FIXME ;;; Clisp 2.48 added experimental support for threads . Basically , you can use : SPAWN now , BUT : ;;; - there are problems with GC , and threads stuffed into weak ;;; hash-tables as is the case for *THREAD-PLIST-TABLE*. ;;; ;;; See test case at ;;; ;;; ;;; Even though said to be fixed, it's not: ;;; ;;; ;;; - The DYNAMIC-FLET above is an implementation technique that's ;;; probably not sustainable in light of threads. This got to be ;;; rewritten. ;;; TCR ( 2009 - 07 - 30 ) #+#.(cl:if (cl:find-package "MP") '(:and) '(:or)) (progn (defimplementation spawn (fn &key name) (mp:make-thread fn :name name)) (defvar *thread-plist-table-lock* (mp:make-mutex :name "THREAD-PLIST-TABLE-LOCK")) (defvar *thread-plist-table* (make-hash-table :weak :key) "A hashtable mapping threads to a plist.") (defvar *thread-id-counter* 0) (defimplementation thread-id (thread) (mp:with-mutex-lock (*thread-plist-table-lock*) (or (getf (gethash thread *thread-plist-table*) 'thread-id) (setf (getf (gethash thread *thread-plist-table*) 'thread-id) (incf *thread-id-counter*))))) (defimplementation find-thread (id) (find id (all-threads) :key (lambda (thread) (getf (gethash thread *thread-plist-table*) 'thread-id)))) (defimplementation thread-name (thread) To guard against returning # < UNBOUND > . (princ-to-string (mp:thread-name thread))) (defimplementation thread-status (thread) (if (thread-alive-p thread) "RUNNING" "STOPPED")) (defimplementation make-lock (&key name) (mp:make-mutex :name name :recursive-p t)) (defimplementation call-with-lock-held (lock function) (mp:with-mutex-lock (lock) (funcall function))) (defimplementation current-thread () (mp:current-thread)) (defimplementation all-threads () (mp:list-threads)) (defimplementation interrupt-thread (thread fn) (mp:thread-interrupt thread :function fn)) (defimplementation kill-thread (thread) (mp:thread-interrupt thread :function t)) (defimplementation thread-alive-p (thread) (mp:thread-active-p thread)) (defvar *mailboxes-lock* (make-lock :name "MAILBOXES-LOCK")) (defvar *mailboxes* (list)) (defstruct (mailbox (:conc-name mailbox.)) thread (lock (make-lock :name "MAILBOX.LOCK")) (waitqueue (mp:make-exemption :name "MAILBOX.WAITQUEUE")) (queue '() :type list)) (defun mailbox (thread) "Return THREAD's mailbox." (mp:with-mutex-lock (*mailboxes-lock*) (or (find thread *mailboxes* :key #'mailbox.thread) (let ((mb (make-mailbox :thread thread))) (push mb *mailboxes*) mb)))) (defimplementation send (thread message) (let* ((mbox (mailbox thread)) (lock (mailbox.lock mbox))) (mp:with-mutex-lock (lock) (setf (mailbox.queue mbox) (nconc (mailbox.queue mbox) (list message))) (mp:exemption-broadcast (mailbox.waitqueue mbox))))) (defimplementation receive-if (test &optional timeout) (let* ((mbox (mailbox (current-thread))) (lock (mailbox.lock mbox))) (assert (or (not timeout) (eq timeout t))) (loop (check-sly-interrupts) (mp:with-mutex-lock (lock) (let* ((q (mailbox.queue mbox)) (tail (member-if test q))) (when tail (setf (mailbox.queue mbox) (nconc (ldiff q tail) (cdr tail))) (return (car tail)))) (when (eq timeout t) (return (values nil t))) (mp:exemption-wait (mailbox.waitqueue mbox) lock :timeout 0.2)))))) ;;;; Weak hashtables (defimplementation make-weak-key-hash-table (&rest args) (apply #'make-hash-table :weak :key args)) (defimplementation make-weak-value-hash-table (&rest args) (apply #'make-hash-table :weak :value args)) (defimplementation save-image (filename &optional restart-function) (let ((args `(,filename ,@(if restart-function `((:init-function ,restart-function)))))) (apply #'ext:saveinitmem args)))
null
https://raw.githubusercontent.com/snmsts/cl-langserver/3b1246a5d0bd58459e7a64708f820bf718cf7175/src/backend/impls/clisp.lisp
lisp
-*- indent-tabs-mode: nil -*- This program is free software; you can redistribute it and/or either version 2 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 General Public License for more details. License along with this program; if not, write to the Free This is work in progress, but it's already usable. Many things are adapted from other slynk-*.lisp, in particular from slynk-allegro (I don't use allegro at all, but it's the shortest versions. It is reasonable to expect it to work on platforms with a "SOCKET" package, in particular on GNU/Linux or Unix-like are conveniently included in SLY. build up a "fake" slynk-mop and then override the methods in the inspector. optional modules/win32 a required interface where does that come from? TCP Server XXX may not work if t Some facts to remember (for the next time we need to debug this): - interactive-sream-p returns t for socket-streams - listen returns nil for socket-streams - (type-of <socket-stream>) is 'stream - calling socket:socket-status on non sockets signals an error, but seems to mess up something internally. - calling read-char-no-hang on sockets does not signal an error, but seems to mess up something internally. Coding systems Slynk functions Report WHEN etc. as macros, even though they may be implemented as special operators. (type-of 'progn) -> ext:special-operator cf. clisp/src/describe.lisp even for 'structure Use ffi::*c-type-table* so as not to suffer the overhead of Maybe use (case (head (ffi:deparse-c-type))) to distinguish struct and union types? (sys::*break-count* (1+ sys::*break-count*)) (sys::*driver* debugger-loop-fn) (sys::*fasoutput-stream* nil) FIXME: should bind *print-length* etc. to small values. been updated. Interpreter-Variablen-Environment has the shape (when (eq (frame-type frame) 'compiled-fun) (pop accu)) Profiling monitor is a macro unmonitor is a macro Handle compiler conditions (find out location of error etc.) Don't set *debugger-hook* to nil on break. (*debugger-hook* nil) Inspecting hash-tables as is the case for *THREAD-PLIST-TABLE*. See test case at Even though said to be fixed, it's not: - The DYNAMIC-FLET above is an implementation technique that's probably not sustainable in light of threads. This got to be rewritten. Weak hashtables
SLYNK support for CLISP . Copyright ( C ) 2003 , 2004 , modify it under the terms of the GNU General Public License as the License , or ( at your option ) any later version . You should have received a copy of the GNU General Public Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . one and I found code there enlightening ) . This code will work better with recent versions of CLISP ( say , the last release or CVS HEAD ) while it may not work at all with older systems , but also on . This backend uses the portable xref from the CMU AI repository and metering.lisp from CLOCC [ 1 ] , which [ 1 ] / (defpackage :ls-clisp (:use cl ls-backend)) (in-package ls-clisp) (eval-when (:compile-toplevel) (unless (string< "2.44" (lisp-implementation-version)) (error "Need at least CLISP version 2.44"))) (defimplementation gray-package-name () "GRAY") if this lisp has the complete CLOS then we use it , otherwise we (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *have-mop* (and (find-package :clos) (eql :external (nth-value 1 (find-symbol (string ':standard-slot-definition) :clos)))) "True in those CLISP images which have a complete MOP implementation.")) #+#.(cl:if slynk-clisp::*have-mop* '(cl:and) '(cl:or)) (progn (import-ls-mop-symbols :clos '(:slot-definition-documentation)) (defun slynk-mop:slot-definition-documentation (slot) (clos::slot-definition-documentation slot))) #-#.(cl:if slynk-clisp::*have-mop* '(and) '(or)) (defclass slynk-mop:standard-slot-definition () () (:documentation "Dummy class created so that slynk.lisp will compile and load.")) (let ((getpid (or (find-symbol "PROCESS-ID" :system) old name prior to 2005 - 03 - 01 , clisp < = 2.33.2 (find-symbol "PROGRAM-ID" :system) integrated into the above since 2005 - 02 - 24 (find-symbol "GetCurrentProcessId" :win32))))) (cond (getpid (funcall getpid)) (t -1)))) (defimplementation call-with-user-break-handler (handler function) (handler-bind ((system::simple-interrupt-condition (lambda (c) (declare (ignore c)) (funcall handler) (when (find-restart 'socket-status) (invoke-restart (find-restart 'socket-status))) (continue)))) (funcall function))) (defimplementation lisp-implementation-type-name () "clisp") (defimplementation set-default-directory (directory) (setf (ext:default-directory) directory) (namestring (setf *default-pathname-defaults* (ext:default-directory)))) (defimplementation filename-to-pathname (string) (cond ((member :cygwin *features*) (parse-cygwin-filename string)) (t (parse-namestring string)))) (defun parse-cygwin-filename (string) (multiple-value-bind (match _ drive absolute) (regexp:match "^(([a-zA-Z\\]+):)?([\\/])?" string :extended t) (declare (ignore _)) (assert (and match (if drive absolute t)) () "Invalid filename syntax: ~a" string) (let* ((sans-prefix (subseq string (regexp:match-end match))) (path (remove "" (regexp:regexp-split "[\\/]" sans-prefix))) (path (loop for name in path collect (cond ((equal name "..") ':back) (t name)))) (directoryp (or (equal string "") (find (aref string (1- (length string))) "\\/")))) (multiple-value-bind (file type) (cond ((and (not directoryp) (last path)) (let* ((file (car (last path))) (pos (position #\. file :from-end t))) (cond ((and pos (> pos 0)) (values (subseq file 0 pos) (subseq file (1+ pos)))) (t file))))) (make-pathname :host nil :device nil :directory (cons (if absolute :absolute :relative) (let ((path (if directoryp path (butlast path)))) (if drive (cons (regexp:match-string string drive) path) path))) :name file :type type))))) UTF (defimplementation string-to-utf8 (string) (let ((enc (load-time-value (ext:make-encoding :charset "utf-8" :line-terminator :unix) t))) (ext:convert-string-to-bytes string enc))) (defimplementation utf8-to-string (octets) (let ((enc (load-time-value (ext:make-encoding :charset "utf-8" :line-terminator :unix) t))) (ext:convert-string-from-bytes octets enc))) (defimplementation create-socket (host port &key backlog) (socket:socket-server port :interface host :backlog (or backlog 5))) (defimplementation local-port (socket) (socket:socket-server-port socket)) (defimplementation close-socket (socket) (socket:socket-server-close socket)) (defimplementation accept-connection (socket &key external-format buffering timeout) (declare (ignore buffering timeout)) (socket:socket-accept socket :element-type (if external-format 'character '(unsigned-byte 8)) :external-format (or external-format :default))) #-win32 (defimplementation wait-for-input (streams &optional timeout) (assert (member timeout '(nil t))) (let ((streams (mapcar (lambda (s) (list* s :input nil)) streams))) (loop (cond ((check-sly-interrupts) (return :interrupt)) (timeout (socket:socket-status streams 0 0) (return (loop for (s nil . x) in streams if x collect s))) (t (with-simple-restart (socket-status "Return from socket-status.") (socket:socket-status streams 0 500000)) (let ((ready (loop for (s nil . x) in streams if x collect s))) (when ready (return ready)))))))) #+win32 (defimplementation wait-for-input (streams &optional timeout) (assert (member timeout '(nil t))) (loop (cond ((check-sly-interrupts) (return :interrupt)) (t (let ((ready (remove-if-not #'input-available-p streams))) (when ready (return ready))) (when timeout (return nil)) (sleep 0.1))))) #+win32 - ( type - of * terminal - io * ) is ' two - way - stream - stream - element - type on our sockets is usually ( UNSIGNED - BYTE 8) (defun input-available-p (stream) (case (stream-element-type stream) (character (let ((c (read-char-no-hang stream nil nil))) (cond ((not c) nil) (t (unread-char c stream) t)))) (t (eq (socket:socket-status (cons stream :input) 0 0) :input)))) (defvar *external-format-to-coding-system* '(((:charset "iso-8859-1" :line-terminator :unix) "latin-1-unix" "iso-latin-1-unix" "iso-8859-1-unix") ((:charset "iso-8859-1") "latin-1" "iso-latin-1" "iso-8859-1") ((:charset "utf-8") "utf-8") ((:charset "utf-8" :line-terminator :unix) "utf-8-unix") ((:charset "euc-jp") "euc-jp") ((:charset "euc-jp" :line-terminator :unix) "euc-jp-unix") ((:charset "us-ascii") "us-ascii") ((:charset "us-ascii" :line-terminator :unix) "us-ascii-unix"))) (defimplementation find-external-format (coding-system) (let ((args (car (rassoc-if (lambda (x) (member coding-system x :test #'equal)) *external-format-to-coding-system*)))) (and args (apply #'ext:make-encoding args)))) (defimplementation arglist (fname) (block nil (or (ignore-errors (let ((exp (function-lambda-expression fname))) (and exp (return (second exp))))) (ignore-errors (return (ext:arglist fname))) :not-available))) (defimplementation macroexpand-all (form &optional env) (declare (ignore env)) (ext:expand-form form)) (defimplementation describe-symbol-for-emacs (symbol) "Return a plist describing SYMBOL. Return NIL if the symbol is unbound." (let ((result ())) (flet ((doc (kind) (or (documentation symbol kind) :not-documented)) (maybe-push (property value) (when value (setf result (list* property value result))))) (maybe-push :variable (when (boundp symbol) (doc 'variable))) (when (fboundp symbol) (maybe-push (if (macro-function symbol) :macro (typecase (fdefinition symbol) (generic-function :generic-function) (function :function) (t :special-operator))) (doc 'function))) e.g. # ' ( setf elt ) defsetf (maybe-push :setf (doc 'setf))) (get symbol 'system::defstruct-description) (get symbol 'system::deftype-expander)) (when (find-class symbol nil) (maybe-push :class (doc 'type))) Let this code work compiled in images without FFI (let ((types (load-time-value (and (find-package "FFI") (symbol-value (find-symbol "*C-TYPE-TABLE*" "FFI")))))) ( ignore - errors ( ffi : parse - c - type symbol ) ) for 99.9 % of symbols which are not FFI type names . (when (and types (nth-value 1 (gethash symbol types))) (maybe-push :alien-type :not-documented))) result))) (defimplementation describe-definition (symbol namespace) (ecase namespace (:variable (describe symbol)) (:macro (describe (macro-function symbol))) (:function (describe (symbol-function symbol))) (:class (describe (find-class symbol))))) (defimplementation type-specifier-p (symbol) (or (ignore-errors (subtypep nil symbol)) (not (eq (type-specifier-arglist symbol) :not-available)))) (defun fspec-pathname (spec) (let ((path spec) type lines) (when (consp path) (psetq type (car path) path (cadr path) lines (cddr path))) (when (and path (member (pathname-type path) custom:*compiled-file-types* :test #'equal)) (setq path (loop for suffix in custom:*source-file-types* thereis (probe-file (make-pathname :defaults path :type suffix))))) (values path type lines))) (defun fspec-location (name fspec) (multiple-value-bind (file type lines) (fspec-pathname fspec) (list (if type (list name type) name) (cond (file (multiple-value-bind (truename c) (ignore-errors (truename file)) (cond (truename (make-location (list :file (namestring truename)) (if (consp lines) (list* :line lines) (list :function-name (string name))) (when (consp type) (list :snippet (format nil "~A" type))))) (t (list :error (princ-to-string c)))))) (t (list :error (format nil "No source information available for: ~S" fspec))))))) (defimplementation find-definitions (name) (mapcar #'(lambda (e) (fspec-location name e)) (documentation name 'sys::file))) (defun trim-whitespace (string) (string-trim #(#\newline #\space #\tab) string)) (defvar *sly-db-backtrace*) (defun sly-db-backtrace () "Return a list ((ADDRESS . DESCRIPTION) ...) of frames." (let* ((modes '((:all-stack-elements 1) (:all-frames 2) (:only-lexical-frames 3) (:only-eval-and-apply-frames 4) (:only-apply-frames 5))) (mode (cadr (assoc :all-stack-elements modes)))) (do ((frames '()) (last nil frame) (frame (sys::the-frame) (sys::frame-up 1 frame mode))) ((eq frame last) (nreverse frames)) (unless (boring-frame-p frame) (push frame frames))))) (defimplementation call-with-debugging-environment (debugger-loop-fn) (*sly-db-backtrace* (let* ((f (sys::the-frame)) (bt (sly-db-backtrace)) (rest (member f bt))) (if rest (nthcdr 8 rest) bt)))) (funcall debugger-loop-fn))) (defun nth-frame (index) (nth index *sly-db-backtrace*)) (defun boring-frame-p (frame) (member (frame-type frame) '(stack-value bind-var bind-env compiled-tagbody compiled-block))) (defun frame-to-string (frame) (with-output-to-string (s) (sys::describe-frame s frame))) (defun frame-type (frame) (frame-string-type (frame-to-string frame))) FIXME : they changed the layout in 2.44 and not all patterns have (defvar *frame-prefixes* '(("\\[[0-9]\\+\\] frame binding variables" bind-var) ("<1> #<compiled-function" compiled-fun) ("<1> #<system-function" sys-fun) ("<1> #<special-operator" special-op) ("EVAL frame" eval) ("APPLY frame" apply) ("\\[[0-9]\\+\\] compiled tagbody frame" compiled-tagbody) ("\\[[0-9]\\+\\] compiled block frame" compiled-block) ("block frame" block) ("nested block frame" block) ("tagbody frame" tagbody) ("nested tagbody frame" tagbody) ("catch frame" catch) ("handler frame" handler) ("unwind-protect frame" unwind-protect) ("driver frame" driver) ("\\[[0-9]\\+\\] frame binding environments" bind-env) ("CALLBACK frame" callback) ("- " stack-value) ("<1> " fun) ("<2> " 2nd-frame) )) (defun frame-string-type (string) (cadr (assoc-if (lambda (pattern) (is-prefix-p pattern string)) *frame-prefixes*))) (defimplementation compute-backtrace (start end) (let* ((bt *sly-db-backtrace*) (len (length bt))) (loop for f in (subseq bt start (min (or end len) len)) collect f))) (defimplementation print-frame (frame stream) (let* ((str (frame-to-string frame))) (write-string (extract-frame-line str) stream))) (defun extract-frame-line (frame-string) (let ((s frame-string)) (trim-whitespace (case (frame-string-type s) ((eval special-op) (string-match "EVAL frame .*for form \\(.*\\)" s 1)) (apply (string-match "APPLY frame for call \\(.*\\)" s 1)) ((compiled-fun sys-fun fun) (extract-function-name s)) (t s))))) (defun extract-function-name (string) (let ((1st (car (split-frame-string string)))) (or (string-match (format nil "^<1>[ ~%]*#<[-A-Za-z]* \\(.*\\)>") 1st 1) (string-match (format nil "^<1>[ ~%]*\\(.*\\)") 1st 1) 1st))) (defun split-frame-string (string) (let ((rx (format nil "~%\\(~{~A~^\\|~}\\)" (mapcar #'car *frame-prefixes*)))) (loop for pos = 0 then (1+ (regexp:match-start match)) for match = (regexp:match rx string :start pos) if match collect (subseq string pos (regexp:match-start match)) else collect (subseq string pos) while match))) (defun string-match (pattern string n) (let* ((match (nth-value n (regexp:match pattern string)))) (if match (regexp:match-string string match)))) (defimplementation eval-in-frame (form frame-number) (sys::eval-at (nth-frame frame-number) form)) (defimplementation frame-locals (frame-number) (let ((frame (nth-frame frame-number))) (loop for i below (%frame-count-vars frame) collect (list :name (%frame-var-name frame i) :value (%frame-var-value frame i) :id 0)))) (defimplementation frame-var-value (frame var) (%frame-var-value (nth-frame frame) var)) NIL or # ( v1 val1 ... vn valn NEXT - ENV ) . (defun %frame-count-vars (frame) (cond ((sys::eval-frame-p frame) (do ((venv (frame-venv frame) (next-venv venv)) (count 0 (+ count (/ (1- (length venv)) 2)))) ((not venv) count))) ((member (frame-type frame) '(compiled-fun sys-fun fun special-op)) (length (%parse-stack-values frame))) (t 0))) (defun %frame-var-name (frame i) (cond ((sys::eval-frame-p frame) (nth-value 0 (venv-ref (frame-venv frame) i))) (t (format nil "~D" i)))) (defun %frame-var-value (frame i) (cond ((sys::eval-frame-p frame) (let ((name (venv-ref (frame-venv frame) i))) (multiple-value-bind (v c) (ignore-errors (sys::eval-at frame name)) (if c (format-sly-db-condition c) v)))) ((member (frame-type frame) '(compiled-fun sys-fun fun special-op)) (let ((str (nth i (%parse-stack-values frame)))) (trim-whitespace (subseq str 2)))) (t (break "Not implemented")))) (defun frame-venv (frame) (let ((env (sys::eval-at frame '(sys::the-environment)))) (svref env 0))) (defun next-venv (venv) (svref venv (1- (length venv)))) (defun venv-ref (env i) "Reference the Ith binding in ENV. Return two values: NAME and VALUE" (let ((idx (* i 2))) (if (< idx (1- (length env))) (values (svref env idx) (svref env (1+ idx))) (venv-ref (next-venv env) (- i (/ (1- (length env)) 2)))))) (defun %parse-stack-values (frame) (labels ((next (fp) (sys::frame-down 1 fp 1)) (parse (fp accu) (let ((str (frame-to-string fp))) (cond ((is-prefix-p "- " str) (parse (next fp) (cons str accu))) ((is-prefix-p "<1> " str) (dolist (str (cdr (split-frame-string str))) (when (is-prefix-p "- " str) (push str accu))) (nreverse accu)) (t (parse (next fp) accu)))))) (parse (next frame) '()))) (defun is-prefix-p (regexp string) (if (regexp:match (concatenate 'string "^" regexp) string) t)) (defimplementation return-from-frame (index form) (sys::return-from-eval-frame (nth-frame index) form)) (defimplementation restart-frame (index) (sys::redo-eval-frame (nth-frame index))) (defimplementation frame-source-location (index) `(:error ,(format nil "frame-source-location not implemented. (frame: ~A)" (nth-frame index)))) (defimplementation profile (fname) (defimplementation profiled-functions () ls-monitor:*monitored-functions*) (defimplementation unprofile (fname) (defimplementation unprofile-all () (ls-monitor:unmonitor)) (defimplementation profile-report () (ls-monitor:report-monitoring)) (defimplementation profile-reset () (ls-monitor:reset-all-monitoring)) (defimplementation profile-package (package callers-p methods) (declare (ignore callers-p methods)) (ls-monitor:monitor-all package)) (defmacro compile-file-frobbing-notes ((&rest args) &body body) "Pass ARGS to COMPILE-FILE, send the compiler notes to *STANDARD-INPUT* and frob them in BODY." `(let ((*error-output* (make-string-output-stream)) (*compile-verbose* t)) (multiple-value-prog1 (compile-file ,@args) (handler-case (with-input-from-string (*standard-input* (get-output-stream-string *error-output*)) ,@body) (sys::simple-end-of-file () nil))))) (defvar *orig-c-warn* (symbol-function 'system::c-warn)) (defvar *orig-c-style-warn* (symbol-function 'system::c-style-warn)) (defvar *orig-c-error* (symbol-function 'system::c-error)) (defvar *orig-c-report-problems* (symbol-function 'system::c-report-problems)) (defmacro dynamic-flet (names-functions &body body) "(dynamic-flet ((NAME FUNCTION) ...) BODY ...) Execute BODY with NAME's function slot set to FUNCTION." `(ext:letf* ,(loop for (name function) in names-functions collect `((symbol-function ',name) ,function)) ,@body)) (defvar *buffer-name* nil) (defvar *buffer-offset*) (defun compiler-note-location () "Return the current compiler location." (let ((lineno1 sys::*compile-file-lineno1*) (lineno2 sys::*compile-file-lineno2*) (file sys::*compile-file-truename*)) (cond ((and file lineno1 lineno2) (make-location (list ':file (namestring file)) (list ':line lineno1))) (*buffer-name* (make-location (list ':buffer *buffer-name*) (list ':offset *buffer-offset* 0))) (t (list :error "No error location available"))))) (defun signal-compiler-warning (cstring args severity orig-fn) (signal 'compiler-condition :severity severity :message (apply #'format nil cstring args) :location (compiler-note-location)) (apply orig-fn cstring args)) (defun c-warn (cstring &rest args) (signal-compiler-warning cstring args :warning *orig-c-warn*)) (defun c-style-warn (cstring &rest args) (dynamic-flet ((sys::c-warn *orig-c-warn*)) (signal-compiler-warning cstring args :style-warning *orig-c-style-warn*))) (defun c-error (&rest args) (signal 'compiler-condition :severity :error :message (apply #'format nil (if (= (length args) 3) (cdr args) args)) :location (compiler-note-location)) (apply *orig-c-error* args)) (defimplementation call-with-compilation-hooks (function) (handler-bind ((warning #'handle-notification-condition)) (dynamic-flet ((system::c-warn #'c-warn) (system::c-style-warn #'c-style-warn) (system::c-error #'c-error)) (funcall function)))) (defun handle-notification-condition (condition) "Handle a condition caused by a compiler warning." (signal 'compiler-condition :original-condition condition :severity :warning :message (princ-to-string condition) :location (compiler-note-location))) (defimplementation slynk-compile-file (input-file output-file load-p external-format &key policy) (declare (ignore policy)) (with-compilation-hooks () (with-compilation-unit () (multiple-value-bind (fasl-file warningsp failurep) (compile-file input-file :output-file output-file :external-format external-format) (values fasl-file warningsp (or failurep (and load-p (not (load fasl-file))))))))) (defimplementation slynk-compile-string (string &key buffer position filename policy) (declare (ignore filename policy)) (with-compilation-hooks () (let ((*buffer-name* buffer) (*buffer-offset* position)) (funcall (compile nil (read-from-string (format nil "(~S () ~A)" 'lambda string)))) t))) from the CMU AI repository . (setq pxref::*handle-package-forms* '(cl:in-package)) (defmacro defxref (name function) `(defimplementation ,name (name) (xref-results (,function name)))) (defxref who-calls pxref:list-callers) (defxref who-references pxref:list-readers) (defxref who-binds pxref:list-setters) (defxref who-sets pxref:list-setters) (defxref list-callers pxref:list-callers) (defxref list-callees pxref:list-callees) (defun xref-results (symbols) (let ((xrefs '())) (dolist (symbol symbols) (push (fspec-location symbol symbol) xrefs)) xrefs)) (when (find-package :ls-loader) (setf (symbol-function (intern "USER-INIT-FILE" :ls-loader)) (lambda () (let ((home (user-homedir-pathname))) (and (ext:probe-directory home) (probe-file (format nil "~A/.slynk.lisp" (namestring (truename home))))))))) (ext:without-package-lock () (defun break (&optional (format-string "Break") &rest args) (if (not sys::*use-clcs*) (progn (terpri *error-output*) (apply #'format *error-output* (concatenate 'string "*** - " format-string) args) (funcall ext:*break-driver* t)) (let ((condition (make-condition 'simple-condition :format-control format-string :format-arguments args)) Issue 91 ) (ext:with-restarts ((continue :report (lambda (stream) (format stream (sys::text "Return from ~S loop") 'break)) ())) (with-condition-restarts condition (list (find-restart 'continue)) (invoke-debugger condition))))) nil)) (defmethod emacs-inspect ((o t)) (let* ((*print-array* nil) (*print-pretty* t) (*print-circle* t) (*print-escape* t) (*print-lines* custom:*inspect-print-lines*) (*print-level* custom:*inspect-print-level*) (*print-length* custom:*inspect-print-length*) (sys::*inspect-all* (make-array 10 :fill-pointer 0 :adjustable t)) (tmp-pack (make-package (gensym "INSPECT-TMP-PACKAGE-"))) (*package* tmp-pack) (sys::*inspect-unbound-value* (intern "#<unbound>" tmp-pack))) (let ((inspection (sys::inspect-backend o))) (append (list (format nil "~S~% ~A~{~%~A~}~%" o (sys::insp-title inspection) (sys::insp-blurb inspection))) (loop with count = (sys::insp-num-slots inspection) for i below count append (multiple-value-bind (value name) (funcall (sys::insp-nth-slot inspection) i) `((:value ,name) " = " (:value ,value) (:newline)))))))) (defimplementation quit-lisp () #+lisp=cl (ext:quit) #-lisp=cl (lisp:quit)) (defimplementation preferred-communication-style () nil) FIXME Clisp 2.48 added experimental support for threads . Basically , you can use : SPAWN now , BUT : - there are problems with GC , and threads stuffed into weak TCR ( 2009 - 07 - 30 ) #+#.(cl:if (cl:find-package "MP") '(:and) '(:or)) (progn (defimplementation spawn (fn &key name) (mp:make-thread fn :name name)) (defvar *thread-plist-table-lock* (mp:make-mutex :name "THREAD-PLIST-TABLE-LOCK")) (defvar *thread-plist-table* (make-hash-table :weak :key) "A hashtable mapping threads to a plist.") (defvar *thread-id-counter* 0) (defimplementation thread-id (thread) (mp:with-mutex-lock (*thread-plist-table-lock*) (or (getf (gethash thread *thread-plist-table*) 'thread-id) (setf (getf (gethash thread *thread-plist-table*) 'thread-id) (incf *thread-id-counter*))))) (defimplementation find-thread (id) (find id (all-threads) :key (lambda (thread) (getf (gethash thread *thread-plist-table*) 'thread-id)))) (defimplementation thread-name (thread) To guard against returning # < UNBOUND > . (princ-to-string (mp:thread-name thread))) (defimplementation thread-status (thread) (if (thread-alive-p thread) "RUNNING" "STOPPED")) (defimplementation make-lock (&key name) (mp:make-mutex :name name :recursive-p t)) (defimplementation call-with-lock-held (lock function) (mp:with-mutex-lock (lock) (funcall function))) (defimplementation current-thread () (mp:current-thread)) (defimplementation all-threads () (mp:list-threads)) (defimplementation interrupt-thread (thread fn) (mp:thread-interrupt thread :function fn)) (defimplementation kill-thread (thread) (mp:thread-interrupt thread :function t)) (defimplementation thread-alive-p (thread) (mp:thread-active-p thread)) (defvar *mailboxes-lock* (make-lock :name "MAILBOXES-LOCK")) (defvar *mailboxes* (list)) (defstruct (mailbox (:conc-name mailbox.)) thread (lock (make-lock :name "MAILBOX.LOCK")) (waitqueue (mp:make-exemption :name "MAILBOX.WAITQUEUE")) (queue '() :type list)) (defun mailbox (thread) "Return THREAD's mailbox." (mp:with-mutex-lock (*mailboxes-lock*) (or (find thread *mailboxes* :key #'mailbox.thread) (let ((mb (make-mailbox :thread thread))) (push mb *mailboxes*) mb)))) (defimplementation send (thread message) (let* ((mbox (mailbox thread)) (lock (mailbox.lock mbox))) (mp:with-mutex-lock (lock) (setf (mailbox.queue mbox) (nconc (mailbox.queue mbox) (list message))) (mp:exemption-broadcast (mailbox.waitqueue mbox))))) (defimplementation receive-if (test &optional timeout) (let* ((mbox (mailbox (current-thread))) (lock (mailbox.lock mbox))) (assert (or (not timeout) (eq timeout t))) (loop (check-sly-interrupts) (mp:with-mutex-lock (lock) (let* ((q (mailbox.queue mbox)) (tail (member-if test q))) (when tail (setf (mailbox.queue mbox) (nconc (ldiff q tail) (cdr tail))) (return (car tail)))) (when (eq timeout t) (return (values nil t))) (mp:exemption-wait (mailbox.waitqueue mbox) lock :timeout 0.2)))))) (defimplementation make-weak-key-hash-table (&rest args) (apply #'make-hash-table :weak :key args)) (defimplementation make-weak-value-hash-table (&rest args) (apply #'make-hash-table :weak :value args)) (defimplementation save-image (filename &optional restart-function) (let ((args `(,filename ,@(if restart-function `((:init-function ,restart-function)))))) (apply #'ext:saveinitmem args)))
079c080bddf49b5ea1f7ad47dca23c0e776bcbf4ccc0574d990c22090bb56816
antifuchs/autobench
deflate.lisp
;;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: png; -*- ;;;; ------------------------------------------------------------------------------------------ ;;;; Title: The DEFLATE Compression (rfc1951) Created : Thu Apr 24 22:12:58 1997 Author : < > ;;;; ------------------------------------------------------------------------------------------ ( c ) copyright 1997,1998 by (in-package :cl-bench.deflate) ;; Note: This implementation is inherently sloooow. On the other hand ;; it is safe and complete and easily verify-able. See ;; <URL:> for an explanation of ;; the algorithm. ;; these DEFVAR used to be DEFCONSTANT, but with a very strict reading ;; of CLtS, they are not truly constant. (defvar +length-encoding+ '#((0 3) (0 4) (0 5) (0 6) (0 7) (0 8) (0 9) (0 10) (1 11) (1 13) (1 15) (1 17) (2 19) (2 23) (2 27) (2 31) (3 35) (3 43) (3 51) (3 59) (4 67) (4 83) (4 99) (4 115) (5 131) (5 163) (5 195) (5 227) (0 258) )) (defvar +dist-encoding+ '#( (0 1) (0 2) (0 3) (0 4) (1 5) (1 7) (2 9) (2 13) (3 17) (3 25) (4 33) (4 49) (5 65) (5 97) (6 129) (6 193) (7 257) (7 385) (8 513) (8 769) (9 1025) (9 1537) (10 2049) (10 3073) (11 4097) (11 6145) (12 8193) (12 12289) (13 16385) (13 24577))) (defvar +fixed-huffman-code-lengths+ (let ((res (make-array 288))) (loop for i from 0 to 143 do (setf (aref res i) 8)) (loop for i from 144 to 255 do (setf (aref res i) 9)) (loop for i from 256 to 279 do (setf (aref res i) 7)) (loop for i from 280 to 287 do (setf (aref res i) 8)) res)) (defstruct bit-stream (octets nil :type (vector (unsigned-byte 8))) ;a vector of octets (pos 0 :type fixnum)) ;bit position within octet stream (declaim (inline bit-stream-read-bit)) (declaim (inline bit-stream-read-byte)) (defun bit-stream-read-bit (source) (prog1 (the fixnum (logand (the fixnum #x1) (the fixnum (ash (the fixnum (aref (the (array (unsigned-byte 8) (*)) (bit-stream-octets source)) (the fixnum (ash (the fixnum (bit-stream-pos source)) -3)))) (the fixnum (- (the fixnum (logand (the fixnum (bit-stream-pos source)) (the fixnum #x7))))))))) (incf (the fixnum (bit-stream-pos source))))) (defun bit-stream-read-byte (source n) "Read one unsigned byte of width 'n' from the bit stream 'source'." (let* ((data (bit-stream-octets source)) (pos (bit-stream-pos source)) (i (ash pos -3))) (declare (type fixnum i) (type fixnum pos)) (prog1 (logand (the fixnum (1- (the fixnum (ash 1 (the fixnum n))))) (the fixnum (logior (the fixnum (ash (aref (the (array (unsigned-byte 8) (*)) data) i) (- (logand pos #x7)))) (the fixnum (ash (aref (the (array (unsigned-byte 8) (*)) data) (+ i 1)) (+ (- 8 (logand pos #x7))))) (the fixnum (ash (aref (the (array (unsigned-byte 8) (*)) data) (+ i 2)) (+ (- 16 (logand pos #x7))))) #|(the fixnum (ash (aref (the (simple-array (unsigned-byte 8) (*)) data) (+ i 3)) (+ (- 24 (logand pos #x7)))))|# ))) (incf (the fixnum (bit-stream-pos source)) (the fixnum n)) ))) (defun bit-stream-read-reversed-byte (source n) "Read one unsigned byte of width 'n' from the bit stream 'source'." (let ((res 0)) (dotimes (k n res) (setf res (logior res (ash (bit-stream-read-bit source) (1- (- n k))))) ))) (defun bit-stream-skip-to-byte-boundary (bs) (setf (bit-stream-pos bs) (* 8 (floor (+ 7 (bit-stream-pos bs)) 8)))) (defun bit-stream-read-symbol (source tree) "Read one symbol (code) from the bit-stream source using the huffman code provided by 'tree'." (do () ((atom tree) tree) (setf tree (if (zerop (bit-stream-read-bit source)) (car tree) (cdr tree))))) (defun build-huffman-tree (lengthen) "Build up a huffman tree given a vector of code lengthen as described in RFC1951." (let* ((max-bits (reduce #'max (map 'list #'identity lengthen))) (max-symbol (1- (length lengthen))) (bl-count (make-array (+ 1 max-bits) :initial-element 0)) (next-code (make-array (+ 1 max-bits) :initial-element 0)) (ht nil)) (dotimes (i (Length lengthen)) (let ((x (aref lengthen i))) (unless (zerop x) (incf (aref bl-count x))))) (let ((code 0)) (loop for bits from 1 to max-bits do (progn (setf code (ash (+ code (aref bl-count (1- bits))) 1)) (setf (aref next-code bits) code)))) (loop for n from 0 to max-symbol do (let ((len (aref lengthen n))) (unless (zerop len) (setf ht (huffman-insert ht len (aref next-code len) n)) (incf (aref next-code len)) ))) ht )) (defun huffman-insert (ht len code sym) (cond ((= 0 len) (assert (null ht)) sym) ((logbitp (- len 1) code) (unless (consp ht) (setq ht (cons nil nil))) (setf (cdr ht) (huffman-insert (cdr ht) (1- len) code sym)) ht) (t (unless (consp ht) (setq ht (cons nil nil))) (setf (car ht) (huffman-insert (car ht) (1- len) code sym)) ht) )) (defun rfc1951-read-huffman-code-lengthen (source code-length-huffman-tree number) (let ((res (make-array number :initial-element 0)) (i 0)) (do () ((= i number)) (let ((qux (bit-stream-read-symbol source code-length-huffman-tree))) (case qux (16 (let ((cnt (+ 3 (bit-stream-read-byte source 2)))) (dotimes (k cnt) (setf (aref res (+ i k)) (aref res (- i 1)))) (incf i cnt))) (17 (let ((cnt (+ 3 (bit-stream-read-byte source 3)))) (dotimes (k cnt) (setf (aref res (+ i k)) 0)) (incf i cnt))) (18 (let ((cnt (+ 11 (bit-stream-read-byte source 7)))) (dotimes (k cnt) (setf (aref res (+ i k)) 0)) (incf i cnt))) (otherwise (setf (aref res i) qux) (incf i)) ))) res)) (defun rfc1951-read-length-dist (source code hdists-ht) (values (+ (cadr (aref +length-encoding+ (- code 257))) (bit-stream-read-byte source (car (aref +length-encoding+ (- code 257))))) (let ((dist-sym (if hdists-ht (bit-stream-read-symbol source hdists-ht) (bit-stream-read-reversed-byte source 5) ))) (+ (cadr (aref +dist-encoding+ dist-sym)) (bit-stream-read-byte source (car (aref +dist-encoding+ dist-sym)))) ) )) (defun rfc1951-uncompress-octets (octets &key (start 0)) (let ((res (make-array 0 :element-type '(unsigned-byte 8) :fill-pointer 0 :adjustable t)) (ptr 0)) (rfc1951-uncompress-bit-stream (make-bit-stream :octets octets :pos (* 8 start)) #'(lambda (buf n) (progn (adjust-array res (list (+ ptr n))) (setf (fill-pointer res) (+ ptr n)) (replace res buf :start1 ptr :end1 (+ ptr n) :start2 0 :end2 n) (incf ptr n)))) res)) (defun rfc1951-uncompress-bit-stream (bs cb) (let (final? ctype (buffer (make-array #x10000 :element-type '(unsigned-byte 8))) (bptr 0)) (declare (type (simple-array (unsigned-byte 8) (#x10000)) buffer) (type fixnum bptr)) (macrolet ((put-byte (byte) `(let ((val ,byte)) (setf (aref buffer bptr) (the (unsigned-byte 8) val)) (setf bptr (the fixnum (logand #xffff (the fixnum (+ bptr 1))))) (when (zerop bptr) (funcall cb buffer #x10000) )))) (loop (setf final? (= (bit-stream-read-bit bs) 1) ctype (bit-stream-read-byte bs 2)) (ecase ctype (0 ;; no compression (bit-stream-skip-to-byte-boundary bs) (let ((len (bit-stream-read-byte bs 16)) (nlen (bit-stream-read-byte bs 16))) (assert (= (logand #xFFFF (lognot nlen)) len)) (dotimes (k len) (put-byte (bit-stream-read-byte bs 8))))) (1 compressed with fixed Huffman code (let ((literal-ht (build-huffman-tree +fixed-huffman-code-lengths+))) (do ((x (bit-stream-read-symbol bs literal-ht) (bit-stream-read-symbol bs literal-ht))) ((= x 256)) (cond ((<= 0 x 255) (put-byte x)) (t (multiple-value-bind (length dist) (rfc1951-read-length-dist bs x nil) (dotimes (k length) (put-byte (aref buffer (logand (- bptr dist) #xffff)))))) )) )) (2 compressed with dynamic codes (let* ((hlit (+ 257 (bit-stream-read-byte bs 5))) ;number of literal code lengths (hdist (+ 1 (bit-stream-read-byte bs 5))) ;number of distance code lengths (hclen (+ 4 (bit-stream-read-byte bs 4))) ;number of code lengths for code length literal-ht distance-ht code-len-ht) ;; slurp the code lengths code lengths (loop for i from 1 to hclen for j in '(16 17 18 0 8 7 9 6 10 5 11 4 12 3 13 2 14 1 15) do (setf (aref hclens j) (bit-stream-read-byte bs 3))) slurp the trees for literals and distances (setf code-len-ht (build-huffman-tree hclens)) (setf literal-ht (build-huffman-tree (rfc1951-read-huffman-code-lengthen bs code-len-ht hlit)) distance-ht (build-huffman-tree (rfc1951-read-huffman-code-lengthen bs code-len-ht hdist))) ;; actually slurp the contents (do ((x (bit-stream-read-symbol bs literal-ht) (bit-stream-read-symbol bs literal-ht))) ((= x 256)) (cond ((<= 0 x 255) (put-byte x)) (t (multiple-value-bind (length dist) (rfc1951-read-length-dist bs x distance-ht) (dotimes (k length) (put-byte (aref buffer (logand (- bptr dist) #xffff)))))) )) )) ) (when final? (funcall cb buffer bptr) (return-from rfc1951-uncompress-bit-stream 'foo)) )))) ;; deflate a gzipped file. Requires reading the header, putting the ;; data into an array, and deflating the array. The format of the ;; header is documented in RFC1952. (defun test-deflate-file (filename) (let ((compressed (make-array 0 :adjustable t :fill-pointer t :element-type '(unsigned-byte 8))) (header-flags 0) (xlen 0)) (with-open-file (in filename :direction :input :element-type '(unsigned-byte 8)) (unless (and (= #x1f (read-byte in)) (= #x8b (read-byte in))) (error "~a is not a gzipped file")) (unless (= #x8 (read-byte in)) (error "~a is not using deflate compression")) (setq header-flags (read-byte in)) ;; skip over the modification time + XFL + OS marker (dotimes (i 6) (read-byte in)) (unless (zerop (logand header-flags 4)) ; contains FEXTRA data (incf xlen (read-byte in)) (incf xlen (* 256 (read-byte in))) (dotimes (i xlen) (read-byte in))) (unless (zerop (logand header-flags 8)) ; contains FNAME data (loop :until (zerop (read-byte in)))) contains FCOMMENT data (loop :until (zerop (read-byte in)))) contains FHCRC (read-byte in) (read-byte in)) (loop :for byte = (read-byte in nil) :while byte :do (vector-push-extend byte compressed))) (rfc1951-uncompress-octets compressed) (values))) (defun run-deflate-file () (test-deflate-file "files/message.gz")) EOF
null
https://raw.githubusercontent.com/antifuchs/autobench/acc14ee2a8899cb630aa8dd02f3ffd7f5858ce28/cl-bench/files/deflate.lisp
lisp
-*- Mode: Lisp; Syntax: Common-Lisp; Package: png; -*- ------------------------------------------------------------------------------------------ Title: The DEFLATE Compression (rfc1951) ------------------------------------------------------------------------------------------ Note: This implementation is inherently sloooow. On the other hand it is safe and complete and easily verify-able. See <URL:> for an explanation of the algorithm. these DEFVAR used to be DEFCONSTANT, but with a very strict reading of CLtS, they are not truly constant. a vector of octets bit position within octet stream (the fixnum (ash (aref (the (simple-array (unsigned-byte 8) (*)) data) (+ i 3)) (+ (- 24 (logand pos #x7))))) no compression number of literal code lengths number of distance code lengths number of code lengths for code slurp the code lengths code lengths actually slurp the contents deflate a gzipped file. Requires reading the header, putting the data into an array, and deflating the array. The format of the header is documented in RFC1952. skip over the modification time + XFL + OS marker contains FEXTRA data contains FNAME data
Created : Thu Apr 24 22:12:58 1997 Author : < > ( c ) copyright 1997,1998 by (in-package :cl-bench.deflate) (defvar +length-encoding+ '#((0 3) (0 4) (0 5) (0 6) (0 7) (0 8) (0 9) (0 10) (1 11) (1 13) (1 15) (1 17) (2 19) (2 23) (2 27) (2 31) (3 35) (3 43) (3 51) (3 59) (4 67) (4 83) (4 99) (4 115) (5 131) (5 163) (5 195) (5 227) (0 258) )) (defvar +dist-encoding+ '#( (0 1) (0 2) (0 3) (0 4) (1 5) (1 7) (2 9) (2 13) (3 17) (3 25) (4 33) (4 49) (5 65) (5 97) (6 129) (6 193) (7 257) (7 385) (8 513) (8 769) (9 1025) (9 1537) (10 2049) (10 3073) (11 4097) (11 6145) (12 8193) (12 12289) (13 16385) (13 24577))) (defvar +fixed-huffman-code-lengths+ (let ((res (make-array 288))) (loop for i from 0 to 143 do (setf (aref res i) 8)) (loop for i from 144 to 255 do (setf (aref res i) 9)) (loop for i from 256 to 279 do (setf (aref res i) 7)) (loop for i from 280 to 287 do (setf (aref res i) 8)) res)) (defstruct bit-stream (declaim (inline bit-stream-read-bit)) (declaim (inline bit-stream-read-byte)) (defun bit-stream-read-bit (source) (prog1 (the fixnum (logand (the fixnum #x1) (the fixnum (ash (the fixnum (aref (the (array (unsigned-byte 8) (*)) (bit-stream-octets source)) (the fixnum (ash (the fixnum (bit-stream-pos source)) -3)))) (the fixnum (- (the fixnum (logand (the fixnum (bit-stream-pos source)) (the fixnum #x7))))))))) (incf (the fixnum (bit-stream-pos source))))) (defun bit-stream-read-byte (source n) "Read one unsigned byte of width 'n' from the bit stream 'source'." (let* ((data (bit-stream-octets source)) (pos (bit-stream-pos source)) (i (ash pos -3))) (declare (type fixnum i) (type fixnum pos)) (prog1 (logand (the fixnum (1- (the fixnum (ash 1 (the fixnum n))))) (the fixnum (logior (the fixnum (ash (aref (the (array (unsigned-byte 8) (*)) data) i) (- (logand pos #x7)))) (the fixnum (ash (aref (the (array (unsigned-byte 8) (*)) data) (+ i 1)) (+ (- 8 (logand pos #x7))))) (the fixnum (ash (aref (the (array (unsigned-byte 8) (*)) data) (+ i 2)) (+ (- 16 (logand pos #x7))))) ))) (incf (the fixnum (bit-stream-pos source)) (the fixnum n)) ))) (defun bit-stream-read-reversed-byte (source n) "Read one unsigned byte of width 'n' from the bit stream 'source'." (let ((res 0)) (dotimes (k n res) (setf res (logior res (ash (bit-stream-read-bit source) (1- (- n k))))) ))) (defun bit-stream-skip-to-byte-boundary (bs) (setf (bit-stream-pos bs) (* 8 (floor (+ 7 (bit-stream-pos bs)) 8)))) (defun bit-stream-read-symbol (source tree) "Read one symbol (code) from the bit-stream source using the huffman code provided by 'tree'." (do () ((atom tree) tree) (setf tree (if (zerop (bit-stream-read-bit source)) (car tree) (cdr tree))))) (defun build-huffman-tree (lengthen) "Build up a huffman tree given a vector of code lengthen as described in RFC1951." (let* ((max-bits (reduce #'max (map 'list #'identity lengthen))) (max-symbol (1- (length lengthen))) (bl-count (make-array (+ 1 max-bits) :initial-element 0)) (next-code (make-array (+ 1 max-bits) :initial-element 0)) (ht nil)) (dotimes (i (Length lengthen)) (let ((x (aref lengthen i))) (unless (zerop x) (incf (aref bl-count x))))) (let ((code 0)) (loop for bits from 1 to max-bits do (progn (setf code (ash (+ code (aref bl-count (1- bits))) 1)) (setf (aref next-code bits) code)))) (loop for n from 0 to max-symbol do (let ((len (aref lengthen n))) (unless (zerop len) (setf ht (huffman-insert ht len (aref next-code len) n)) (incf (aref next-code len)) ))) ht )) (defun huffman-insert (ht len code sym) (cond ((= 0 len) (assert (null ht)) sym) ((logbitp (- len 1) code) (unless (consp ht) (setq ht (cons nil nil))) (setf (cdr ht) (huffman-insert (cdr ht) (1- len) code sym)) ht) (t (unless (consp ht) (setq ht (cons nil nil))) (setf (car ht) (huffman-insert (car ht) (1- len) code sym)) ht) )) (defun rfc1951-read-huffman-code-lengthen (source code-length-huffman-tree number) (let ((res (make-array number :initial-element 0)) (i 0)) (do () ((= i number)) (let ((qux (bit-stream-read-symbol source code-length-huffman-tree))) (case qux (16 (let ((cnt (+ 3 (bit-stream-read-byte source 2)))) (dotimes (k cnt) (setf (aref res (+ i k)) (aref res (- i 1)))) (incf i cnt))) (17 (let ((cnt (+ 3 (bit-stream-read-byte source 3)))) (dotimes (k cnt) (setf (aref res (+ i k)) 0)) (incf i cnt))) (18 (let ((cnt (+ 11 (bit-stream-read-byte source 7)))) (dotimes (k cnt) (setf (aref res (+ i k)) 0)) (incf i cnt))) (otherwise (setf (aref res i) qux) (incf i)) ))) res)) (defun rfc1951-read-length-dist (source code hdists-ht) (values (+ (cadr (aref +length-encoding+ (- code 257))) (bit-stream-read-byte source (car (aref +length-encoding+ (- code 257))))) (let ((dist-sym (if hdists-ht (bit-stream-read-symbol source hdists-ht) (bit-stream-read-reversed-byte source 5) ))) (+ (cadr (aref +dist-encoding+ dist-sym)) (bit-stream-read-byte source (car (aref +dist-encoding+ dist-sym)))) ) )) (defun rfc1951-uncompress-octets (octets &key (start 0)) (let ((res (make-array 0 :element-type '(unsigned-byte 8) :fill-pointer 0 :adjustable t)) (ptr 0)) (rfc1951-uncompress-bit-stream (make-bit-stream :octets octets :pos (* 8 start)) #'(lambda (buf n) (progn (adjust-array res (list (+ ptr n))) (setf (fill-pointer res) (+ ptr n)) (replace res buf :start1 ptr :end1 (+ ptr n) :start2 0 :end2 n) (incf ptr n)))) res)) (defun rfc1951-uncompress-bit-stream (bs cb) (let (final? ctype (buffer (make-array #x10000 :element-type '(unsigned-byte 8))) (bptr 0)) (declare (type (simple-array (unsigned-byte 8) (#x10000)) buffer) (type fixnum bptr)) (macrolet ((put-byte (byte) `(let ((val ,byte)) (setf (aref buffer bptr) (the (unsigned-byte 8) val)) (setf bptr (the fixnum (logand #xffff (the fixnum (+ bptr 1))))) (when (zerop bptr) (funcall cb buffer #x10000) )))) (loop (setf final? (= (bit-stream-read-bit bs) 1) ctype (bit-stream-read-byte bs 2)) (ecase ctype (0 (bit-stream-skip-to-byte-boundary bs) (let ((len (bit-stream-read-byte bs 16)) (nlen (bit-stream-read-byte bs 16))) (assert (= (logand #xFFFF (lognot nlen)) len)) (dotimes (k len) (put-byte (bit-stream-read-byte bs 8))))) (1 compressed with fixed Huffman code (let ((literal-ht (build-huffman-tree +fixed-huffman-code-lengths+))) (do ((x (bit-stream-read-symbol bs literal-ht) (bit-stream-read-symbol bs literal-ht))) ((= x 256)) (cond ((<= 0 x 255) (put-byte x)) (t (multiple-value-bind (length dist) (rfc1951-read-length-dist bs x nil) (dotimes (k length) (put-byte (aref buffer (logand (- bptr dist) #xffff)))))) )) )) (2 compressed with dynamic codes length literal-ht distance-ht code-len-ht) (loop for i from 1 to hclen for j in '(16 17 18 0 8 7 9 6 10 5 11 4 12 3 13 2 14 1 15) do (setf (aref hclens j) (bit-stream-read-byte bs 3))) slurp the trees for literals and distances (setf code-len-ht (build-huffman-tree hclens)) (setf literal-ht (build-huffman-tree (rfc1951-read-huffman-code-lengthen bs code-len-ht hlit)) distance-ht (build-huffman-tree (rfc1951-read-huffman-code-lengthen bs code-len-ht hdist))) (do ((x (bit-stream-read-symbol bs literal-ht) (bit-stream-read-symbol bs literal-ht))) ((= x 256)) (cond ((<= 0 x 255) (put-byte x)) (t (multiple-value-bind (length dist) (rfc1951-read-length-dist bs x distance-ht) (dotimes (k length) (put-byte (aref buffer (logand (- bptr dist) #xffff)))))) )) )) ) (when final? (funcall cb buffer bptr) (return-from rfc1951-uncompress-bit-stream 'foo)) )))) (defun test-deflate-file (filename) (let ((compressed (make-array 0 :adjustable t :fill-pointer t :element-type '(unsigned-byte 8))) (header-flags 0) (xlen 0)) (with-open-file (in filename :direction :input :element-type '(unsigned-byte 8)) (unless (and (= #x1f (read-byte in)) (= #x8b (read-byte in))) (error "~a is not a gzipped file")) (unless (= #x8 (read-byte in)) (error "~a is not using deflate compression")) (setq header-flags (read-byte in)) (dotimes (i 6) (read-byte in)) (incf xlen (read-byte in)) (incf xlen (* 256 (read-byte in))) (dotimes (i xlen) (read-byte in))) (loop :until (zerop (read-byte in)))) contains FCOMMENT data (loop :until (zerop (read-byte in)))) contains FHCRC (read-byte in) (read-byte in)) (loop :for byte = (read-byte in nil) :while byte :do (vector-push-extend byte compressed))) (rfc1951-uncompress-octets compressed) (values))) (defun run-deflate-file () (test-deflate-file "files/message.gz")) EOF
d1f32104b49ba83349c87cd54c7be6735392bf6d26ee88ed3df8d351341af61f
ocaml-flambda/flambda-backend
cmm_builtins.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , 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 GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) open Cmm (** Create a C function call. *) val extcall : dbg:Debuginfo.t -> returns:bool -> alloc:bool -> is_c_builtin:bool -> ty_args:exttype list -> string -> machtype -> expression list -> expression * [ cextcall prim args dbg type_of_result ] returns operation that corresponds to [ prim ] . If [ prim ] is a C builtin supported on the target , returns [ Cmm.operation ] variant for [ prim ] 's intrinsics . corresponds to [prim]. If [prim] is a C builtin supported on the target, returns [Cmm.operation] variant for [prim]'s intrinsics. *) val cextcall : Primitive.description -> expression list -> Debuginfo.t -> machtype -> exttype list -> bool -> expression
null
https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/5052e900ecd11529be548d4c5b5b1ead6e1895c3/backend/cmm_builtins.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ * Create a C function call.
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Cmm val extcall : dbg:Debuginfo.t -> returns:bool -> alloc:bool -> is_c_builtin:bool -> ty_args:exttype list -> string -> machtype -> expression list -> expression * [ cextcall prim args dbg type_of_result ] returns operation that corresponds to [ prim ] . If [ prim ] is a C builtin supported on the target , returns [ Cmm.operation ] variant for [ prim ] 's intrinsics . corresponds to [prim]. If [prim] is a C builtin supported on the target, returns [Cmm.operation] variant for [prim]'s intrinsics. *) val cextcall : Primitive.description -> expression list -> Debuginfo.t -> machtype -> exttype list -> bool -> expression
b82937d0c79f538399615fbd79f13fdc09d0fa01ddaf8395c2a780a352675a85
yi-editor/yi
Modes.hs
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Modes -- License : GPL-2 -- Maintainer : -- Stability : experimental -- Portability : portable -- Definitions for the bulk of modes shipped with . module Yi.Modes (cMode, objectiveCMode, cppMode, cabalMode, clojureMode, srmcMode, ocamlMode, ottMode, gnuMakeMode, perlMode, pythonMode, javaMode, jsonMode, anyExtension, svnCommitMode, whitespaceMode, gitCommitMode, rubyMode ) where import Lens.Micro.Platform ((%~), (&), (.~)) import Data.List (isPrefixOf) import System.FilePath (takeDirectory, takeFileName) import Yi.Buffer import . . import qualified Yi.Lexer.C as C (lexer) import qualified Yi.Lexer.Cabal as Cabal (lexer) import qualified Yi.Lexer.Clojure as Clojure (lexer) import qualified Yi.Lexer.Cplusplus as Cplusplus (lexer) import qualified Yi.Lexer.GitCommit as GitCommit (Token, lexer) import qualified Yi.Lexer.GNUMake as GNUMake (lexer) import qualified Yi.Lexer.Java as Java (lexer) import qualified Yi.Lexer.JSON as JSON (lexer) import qualified Yi.Lexer.ObjectiveC as ObjectiveC (lexer) import qualified Yi.Lexer.OCaml as OCaml (Token, lexer) import qualified Yi.Lexer.Ott as Ott (lexer) import qualified Yi.Lexer.Perl as Perl (lexer) import qualified Yi.Lexer.Python as Python (lexer) import qualified Yi.Lexer.Ruby as Ruby (lexer) import qualified Yi.Lexer.Srmc as Srmc (lexer) import qualified Yi.Lexer.SVNCommit as SVNCommit (lexer) import qualified Yi.Lexer.Whitespace as Whitespace (lexer) import Yi.Mode.Common import Yi.Style (StyleName) cMode :: TokenBasedMode StyleName cMode = styleMode C.lexer & modeNameA .~ "c" & modeAppliesA .~ anyExtension [ "c", "h" ] objectiveCMode :: TokenBasedMode StyleName objectiveCMode = styleMode ObjectiveC.lexer & modeNameA .~ "objective-c" & modeAppliesA .~ anyExtension [ "m", "mm" ] cppMode :: TokenBasedMode StyleName cppMode = styleMode Cplusplus.lexer & modeAppliesA .~ anyExtension [ "cxx", "cpp", "hxx" ] & modeNameA .~ "c++" cabalMode :: TokenBasedMode StyleName cabalMode = styleMode Cabal.lexer & modeNameA .~ "cabal" & modeAppliesA .~ anyExtension [ "cabal" ] & modeToggleCommentSelectionA .~ Just (toggleCommentB "--") clojureMode :: TokenBasedMode StyleName clojureMode = styleMode Clojure.lexer & modeNameA .~ "clojure" & modeAppliesA .~ anyExtension [ "clj", "edn" ] srmcMode :: TokenBasedMode StyleName srmcMode = styleMode Srmc.lexer & modeNameA .~ "srmc" & modeAppliesA .~ anyExtension [ "pepa", "srmc" ] -- pepa is a subset of srmc gitCommitMode :: TokenBasedMode GitCommit.Token gitCommitMode = styleMode GitCommit.lexer & modeNameA .~ "git-commit" & modeAppliesA .~ isCommit where isCommit p _ = case (takeFileName p, takeFileName $ takeDirectory p) of ("COMMIT_EDITMSG", ".git") -> True _ -> False svnCommitMode :: TokenBasedMode StyleName svnCommitMode = styleMode SVNCommit.lexer & modeNameA .~ "svn-commit" & modeAppliesA .~ isCommit where isCommit p _ = "svn-commit" `isPrefixOf` p && extensionMatches ["tmp"] p ocamlMode :: TokenBasedMode OCaml.Token ocamlMode = styleMode OCaml.lexer & modeNameA .~ "ocaml" & modeAppliesA .~ anyExtension [ "ml", "mli", "mly" , "mll", "ml4", "mlp4" ] perlMode :: TokenBasedMode StyleName perlMode = styleMode Perl.lexer & modeNameA .~ "perl" & modeAppliesA .~ anyExtension [ "t", "pl", "pm" ] rubyMode :: TokenBasedMode StyleName rubyMode = styleMode Ruby.lexer & modeNameA .~ "ruby" & modeAppliesA .~ anyExtension [ "rb", "ru" ] pythonMode :: TokenBasedMode StyleName pythonMode = base & modeNameA .~ "python" & modeAppliesA .~ anyExtension [ "py" ] & modeToggleCommentSelectionA .~ Just (toggleCommentB "#") & modeIndentSettingsA %~ (\x -> x { expandTabs = True, tabSize = 4 }) where base = styleMode Python.lexer javaMode :: TokenBasedMode StyleName javaMode = styleMode Java.lexer & modeNameA .~ "java" & modeAppliesA .~ anyExtension [ "java" ] jsonMode :: TokenBasedMode StyleName jsonMode = styleMode JSON.lexer & modeNameA .~ "json" & modeAppliesA .~ anyExtension [ "json" ] gnuMakeMode :: TokenBasedMode StyleName gnuMakeMode = styleMode GNUMake.lexer & modeNameA .~ "Makefile" & modeAppliesA .~ isMakefile & modeIndentSettingsA %~ (\x -> x { expandTabs = False, shiftWidth = 8 }) where isMakefile :: FilePath -> a -> Bool isMakefile path _contents = matches $ takeFileName path where matches "Makefile" = True matches "makefile" = True matches "GNUmakefile" = True matches filename = extensionMatches [ "mk" ] filename ottMode :: TokenBasedMode StyleName ottMode = styleMode Ott.lexer & modeNameA .~ "ott" & modeAppliesA .~ anyExtension [ "ott" ] whitespaceMode :: TokenBasedMode StyleName whitespaceMode = styleMode Whitespace.lexer & modeNameA .~ "whitespace" & modeAppliesA .~ anyExtension [ "ws" ] & modeIndentA .~ (\_ _ -> insertB '\t')
null
https://raw.githubusercontent.com/yi-editor/yi/58c239e3a77cef8f4f77e94677bd6a295f585f5f/yi-misc-modes/src/Yi/Modes.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE PackageImports # # OPTIONS_HADDOCK show-extensions # | Module : Yi.Modes License : GPL-2 Maintainer : Stability : experimental Portability : portable pepa is a subset of srmc
Definitions for the bulk of modes shipped with . module Yi.Modes (cMode, objectiveCMode, cppMode, cabalMode, clojureMode, srmcMode, ocamlMode, ottMode, gnuMakeMode, perlMode, pythonMode, javaMode, jsonMode, anyExtension, svnCommitMode, whitespaceMode, gitCommitMode, rubyMode ) where import Lens.Micro.Platform ((%~), (&), (.~)) import Data.List (isPrefixOf) import System.FilePath (takeDirectory, takeFileName) import Yi.Buffer import . . import qualified Yi.Lexer.C as C (lexer) import qualified Yi.Lexer.Cabal as Cabal (lexer) import qualified Yi.Lexer.Clojure as Clojure (lexer) import qualified Yi.Lexer.Cplusplus as Cplusplus (lexer) import qualified Yi.Lexer.GitCommit as GitCommit (Token, lexer) import qualified Yi.Lexer.GNUMake as GNUMake (lexer) import qualified Yi.Lexer.Java as Java (lexer) import qualified Yi.Lexer.JSON as JSON (lexer) import qualified Yi.Lexer.ObjectiveC as ObjectiveC (lexer) import qualified Yi.Lexer.OCaml as OCaml (Token, lexer) import qualified Yi.Lexer.Ott as Ott (lexer) import qualified Yi.Lexer.Perl as Perl (lexer) import qualified Yi.Lexer.Python as Python (lexer) import qualified Yi.Lexer.Ruby as Ruby (lexer) import qualified Yi.Lexer.Srmc as Srmc (lexer) import qualified Yi.Lexer.SVNCommit as SVNCommit (lexer) import qualified Yi.Lexer.Whitespace as Whitespace (lexer) import Yi.Mode.Common import Yi.Style (StyleName) cMode :: TokenBasedMode StyleName cMode = styleMode C.lexer & modeNameA .~ "c" & modeAppliesA .~ anyExtension [ "c", "h" ] objectiveCMode :: TokenBasedMode StyleName objectiveCMode = styleMode ObjectiveC.lexer & modeNameA .~ "objective-c" & modeAppliesA .~ anyExtension [ "m", "mm" ] cppMode :: TokenBasedMode StyleName cppMode = styleMode Cplusplus.lexer & modeAppliesA .~ anyExtension [ "cxx", "cpp", "hxx" ] & modeNameA .~ "c++" cabalMode :: TokenBasedMode StyleName cabalMode = styleMode Cabal.lexer & modeNameA .~ "cabal" & modeAppliesA .~ anyExtension [ "cabal" ] & modeToggleCommentSelectionA .~ Just (toggleCommentB "--") clojureMode :: TokenBasedMode StyleName clojureMode = styleMode Clojure.lexer & modeNameA .~ "clojure" & modeAppliesA .~ anyExtension [ "clj", "edn" ] srmcMode :: TokenBasedMode StyleName srmcMode = styleMode Srmc.lexer & modeNameA .~ "srmc" gitCommitMode :: TokenBasedMode GitCommit.Token gitCommitMode = styleMode GitCommit.lexer & modeNameA .~ "git-commit" & modeAppliesA .~ isCommit where isCommit p _ = case (takeFileName p, takeFileName $ takeDirectory p) of ("COMMIT_EDITMSG", ".git") -> True _ -> False svnCommitMode :: TokenBasedMode StyleName svnCommitMode = styleMode SVNCommit.lexer & modeNameA .~ "svn-commit" & modeAppliesA .~ isCommit where isCommit p _ = "svn-commit" `isPrefixOf` p && extensionMatches ["tmp"] p ocamlMode :: TokenBasedMode OCaml.Token ocamlMode = styleMode OCaml.lexer & modeNameA .~ "ocaml" & modeAppliesA .~ anyExtension [ "ml", "mli", "mly" , "mll", "ml4", "mlp4" ] perlMode :: TokenBasedMode StyleName perlMode = styleMode Perl.lexer & modeNameA .~ "perl" & modeAppliesA .~ anyExtension [ "t", "pl", "pm" ] rubyMode :: TokenBasedMode StyleName rubyMode = styleMode Ruby.lexer & modeNameA .~ "ruby" & modeAppliesA .~ anyExtension [ "rb", "ru" ] pythonMode :: TokenBasedMode StyleName pythonMode = base & modeNameA .~ "python" & modeAppliesA .~ anyExtension [ "py" ] & modeToggleCommentSelectionA .~ Just (toggleCommentB "#") & modeIndentSettingsA %~ (\x -> x { expandTabs = True, tabSize = 4 }) where base = styleMode Python.lexer javaMode :: TokenBasedMode StyleName javaMode = styleMode Java.lexer & modeNameA .~ "java" & modeAppliesA .~ anyExtension [ "java" ] jsonMode :: TokenBasedMode StyleName jsonMode = styleMode JSON.lexer & modeNameA .~ "json" & modeAppliesA .~ anyExtension [ "json" ] gnuMakeMode :: TokenBasedMode StyleName gnuMakeMode = styleMode GNUMake.lexer & modeNameA .~ "Makefile" & modeAppliesA .~ isMakefile & modeIndentSettingsA %~ (\x -> x { expandTabs = False, shiftWidth = 8 }) where isMakefile :: FilePath -> a -> Bool isMakefile path _contents = matches $ takeFileName path where matches "Makefile" = True matches "makefile" = True matches "GNUmakefile" = True matches filename = extensionMatches [ "mk" ] filename ottMode :: TokenBasedMode StyleName ottMode = styleMode Ott.lexer & modeNameA .~ "ott" & modeAppliesA .~ anyExtension [ "ott" ] whitespaceMode :: TokenBasedMode StyleName whitespaceMode = styleMode Whitespace.lexer & modeNameA .~ "whitespace" & modeAppliesA .~ anyExtension [ "ws" ] & modeIndentA .~ (\_ _ -> insertB '\t')
5d40b5ec6da407f753c10740adf0d1a7aa58221a357a701120059213659d93c6
montelibero-org/veche
UserSpec.hs
# LANGUAGE BlockArguments # # LANGUAGE DisambiguateRecordFields # # LANGUAGE ImportQualifiedPost # # LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} module Handler.UserSpec (spec) where import TestImport import Data.Text qualified as Text import Stellar.Horizon.Client qualified as Stellar import Model.User (User (User)) import Model.User qualified spec :: Spec spec = withApp $ describe "User page" do it "asserts no access to my-account for anonymous users" do get UserR statusIs 403 it "asserts access to my-account for authenticated users" do userEntity <- createUser "foo" Nothing authenticateAs userEntity get UserR statusIs 200 it "asserts user's information is shown" do userEntity <- createUser "bar" Nothing authenticateAs userEntity get UserR let Entity _ User{stellarAddress = Stellar.Address address} = userEntity htmlAnyContain ".user_stellar_address" $ Text.unpack address
null
https://raw.githubusercontent.com/montelibero-org/veche/d2792748bbc703f42a9792a7b212dc6ea41881b3/veche-web/test/Handler/UserSpec.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE BlockArguments # # LANGUAGE DisambiguateRecordFields # # LANGUAGE ImportQualifiedPost # # LANGUAGE NoImplicitPrelude # module Handler.UserSpec (spec) where import TestImport import Data.Text qualified as Text import Stellar.Horizon.Client qualified as Stellar import Model.User (User (User)) import Model.User qualified spec :: Spec spec = withApp $ describe "User page" do it "asserts no access to my-account for anonymous users" do get UserR statusIs 403 it "asserts access to my-account for authenticated users" do userEntity <- createUser "foo" Nothing authenticateAs userEntity get UserR statusIs 200 it "asserts user's information is shown" do userEntity <- createUser "bar" Nothing authenticateAs userEntity get UserR let Entity _ User{stellarAddress = Stellar.Address address} = userEntity htmlAnyContain ".user_stellar_address" $ Text.unpack address
83d12347a3fa2b73668e9f648f3d29d9bafd2fb6086f5fc29a03f24852628f4d
bitblaze-fuzzball/fuzzball
vine_stpvc.mli
type ctx type revctx val typ_to_stp : Stpvc.vc -> Vine.typ -> Stpvc.typ val empty_ctx : unit -> ctx val new_ctx : Stpvc.vc -> Vine.decl list -> ctx val rev_ctx : ctx -> revctx val vine_var_to_stp : Stpvc.vc -> ctx -> Vine.var -> Stpvc.exp val vine_to_stp : Stpvc.vc -> ctx -> Vine.exp -> Stpvc.exp val stp_to_type : Stpvc.exp -> Vine.typ val stp_to_vine : ?strip_nums:bool -> ?ctx:revctx -> Stpvc.exp -> Vine.exp val vc_simplify : Stpvc.vc -> ctx -> Vine.exp -> Vine.exp
null
https://raw.githubusercontent.com/bitblaze-fuzzball/fuzzball/b9a617b45e68fa732f1357fedc08a2a10f87a62c/ocaml/vine_stpvc.mli
ocaml
type ctx type revctx val typ_to_stp : Stpvc.vc -> Vine.typ -> Stpvc.typ val empty_ctx : unit -> ctx val new_ctx : Stpvc.vc -> Vine.decl list -> ctx val rev_ctx : ctx -> revctx val vine_var_to_stp : Stpvc.vc -> ctx -> Vine.var -> Stpvc.exp val vine_to_stp : Stpvc.vc -> ctx -> Vine.exp -> Stpvc.exp val stp_to_type : Stpvc.exp -> Vine.typ val stp_to_vine : ?strip_nums:bool -> ?ctx:revctx -> Stpvc.exp -> Vine.exp val vc_simplify : Stpvc.vc -> ctx -> Vine.exp -> Vine.exp
43e5a08b05459bc59046507fd5a1df78072e0be0ef3bdb69807e4cb09e6dca52
ocaml-multicore/parallel-programming-in-multicore-ocaml
fibonacci_domains.ml
let num_domains = try int_of_string Sys.argv.(1) with _ -> 1 let n = try int_of_string Sys.argv.(2) with _ -> 40 let rec fib n = if n < 2 then 1 else fib (n-1) + fib (n-2) let rec fib_par n d = if d <= 1 then fib n else let a = fib_par (n-1) (d-1) in let b = Domain.spawn (fun _ -> fib_par (n-2) (d-1)) in a + Domain.join b let main = let res = fib_par n num_domains in Printf.printf "fib(%d) = %d\n" n res
null
https://raw.githubusercontent.com/ocaml-multicore/parallel-programming-in-multicore-ocaml/2f95616234907bc0fb95f32bcc49c9b1f9c83d5a/code/task/fibonacci_domains.ml
ocaml
let num_domains = try int_of_string Sys.argv.(1) with _ -> 1 let n = try int_of_string Sys.argv.(2) with _ -> 40 let rec fib n = if n < 2 then 1 else fib (n-1) + fib (n-2) let rec fib_par n d = if d <= 1 then fib n else let a = fib_par (n-1) (d-1) in let b = Domain.spawn (fun _ -> fib_par (n-2) (d-1)) in a + Domain.join b let main = let res = fib_par n num_domains in Printf.printf "fib(%d) = %d\n" n res
aa8953211852088b687dc18a3ec4c7b5f68882e323c26560cb914610e65592bd
nebularis/systest
systest_cleaner.erl
-*- tab - width : 4;erlang - indent - level : 4;indent - tabs - mode : nil -*- %% ex: ts=4 sw=4 et %% ---------------------------------------------------------------------------- %% Copyright ( c ) 2005 - 2012 Nebularis . %% %% Permission is hereby granted, free of charge, to any person obtaining a copy %% of this software and associated documentation files (the "Software"), deal in the Software without restriction , including without limitation the rights %% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the Software is %% furnished to do so, subject to the following conditions: %% %% The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . %% THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR %% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, %% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE %% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING %% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS %% IN THE SOFTWARE. %% ---------------------------------------------------------------------------- %% @hidden %% ---------------------------------------------------------------------------- -module(systest_cleaner). -record(state, {killer, targets, victims}). -behaviour(gen_server). %% API Exports -export([start_link/1, start/1, start_permanent/1, kill/2, kill/3, kill_wait/2, kill_wait/3]). OTP gen_server Exports -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %% %% Public API %% start_permanent(Killer) -> gen_server:start_link({local, ?MODULE}, ?MODULE, [Killer], []). start_link(Killer) -> gen_server:start_link(?MODULE, [Killer], []). start(Killer) -> gen_server:start(?MODULE, [Killer], []). kill_wait(Targets, Killer) -> kill_wait(Targets, Killer, infinity). kill_wait([], _Killer, _Timeout) -> no_targets; kill_wait(Targets, Killer, Timeout) -> {ok, Server} = start(Killer), kill(Targets, Server, Timeout). kill(Targets, Server) -> kill(Targets, Server, infinity). kill([], _Server, _Timeout) -> no_targets; kill(Targets, Server, Timeout) -> MRef = erlang:monitor(process, Server), wait = gen_server:call(Server, {kill, Targets}, Timeout), Result = receive {_Ref, {ok, Killed}} -> check_length(Targets, Killed); {'EXIT', Server, normal} -> is it * possible * that the ' EXIT ' overtakes the reply ! check_length(Targets, dead_pids(Targets)); {'DOWN', MRef, process, Server, Reason} -> {error, Reason} after Timeout -> {error, timeout, dead_pids(Targets)} end, erlang:demonitor(MRef, [flush]), Result. %% %% Internal API %% dead_pids(Targets) -> lists:filter(fun erlang:is_process_alive/1, Targets). check_length(Targets, Killed) -> case length(Killed) =:= length(Targets) of true -> ok; false -> {error, {killed, Targets}} end. %% OTP gen_server API %% init([Killer]) -> process_flag(trap_exit, true), {ok, #state{killer=Killer, targets=queue:new(), victims=[]}}. handle_call({kill, Targets}, From, State=#state{targets=KillQ, killer=Kill}) -> link_and_kill(Targets, Kill), Q2 = queue:snoc(KillQ, {From, Targets}), {reply, wait, State#state{targets=Q2}}; handle_call(_Msg, _From, State) -> {reply, {error, noapi}, State}. handle_cast(_Msg, State) -> {noreply, State}. handle_info({'DOWN', _MRef, process, Pid, _Reason}, State=#state{targets=Targets, victims=Victims}) -> {Client, Nodes} = queue:head(Targets), case lists:member(Pid, Nodes) of false -> {stop, {unexpected_exit, Pid}, State}; true -> T2 = lists:delete(Pid, Nodes), V2 = [Pid|Victims], case T2 of [] -> gen_server:reply(Client, {ok, V2}), Q = queue:tail(Targets), case queue:is_empty(Q) of true -> {stop, normal, State}; false -> {noreply, State#state{targets=Q, victims=[]}} end; _More -> RemainingQueue = queue:cons({Client, T2}, queue:tail(Targets)), {noreply, State#state{targets=RemainingQueue, victims=V2}} end end; handle_info({'EXIT', _, normal}, State) -> {noreply, State}. link_and_kill(Pids, Kill) -> [erlang:monitor(process, P) || P <- Pids], [spawn_link(fun() -> Kill(P) end) || P <- Pids]. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}.
null
https://raw.githubusercontent.com/nebularis/systest/fbef181fd0203137f9f6ca6a471c75ca180ec375/src/systest_cleaner.erl
erlang
ex: ts=4 sw=4 et ---------------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), deal to use, copy, modify, merge, publish, distribute, sublicense, and/or sell furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------------------------- @hidden ---------------------------------------------------------------------------- API Exports Public API Internal API
-*- tab - width : 4;erlang - indent - level : 4;indent - tabs - mode : nil -*- Copyright ( c ) 2005 - 2012 Nebularis . in the Software without restriction , including without limitation the rights copies of the Software , and to permit persons to whom the Software is all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING -module(systest_cleaner). -record(state, {killer, targets, victims}). -behaviour(gen_server). -export([start_link/1, start/1, start_permanent/1, kill/2, kill/3, kill_wait/2, kill_wait/3]). OTP gen_server Exports -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). start_permanent(Killer) -> gen_server:start_link({local, ?MODULE}, ?MODULE, [Killer], []). start_link(Killer) -> gen_server:start_link(?MODULE, [Killer], []). start(Killer) -> gen_server:start(?MODULE, [Killer], []). kill_wait(Targets, Killer) -> kill_wait(Targets, Killer, infinity). kill_wait([], _Killer, _Timeout) -> no_targets; kill_wait(Targets, Killer, Timeout) -> {ok, Server} = start(Killer), kill(Targets, Server, Timeout). kill(Targets, Server) -> kill(Targets, Server, infinity). kill([], _Server, _Timeout) -> no_targets; kill(Targets, Server, Timeout) -> MRef = erlang:monitor(process, Server), wait = gen_server:call(Server, {kill, Targets}, Timeout), Result = receive {_Ref, {ok, Killed}} -> check_length(Targets, Killed); {'EXIT', Server, normal} -> is it * possible * that the ' EXIT ' overtakes the reply ! check_length(Targets, dead_pids(Targets)); {'DOWN', MRef, process, Server, Reason} -> {error, Reason} after Timeout -> {error, timeout, dead_pids(Targets)} end, erlang:demonitor(MRef, [flush]), Result. dead_pids(Targets) -> lists:filter(fun erlang:is_process_alive/1, Targets). check_length(Targets, Killed) -> case length(Killed) =:= length(Targets) of true -> ok; false -> {error, {killed, Targets}} end. OTP gen_server API init([Killer]) -> process_flag(trap_exit, true), {ok, #state{killer=Killer, targets=queue:new(), victims=[]}}. handle_call({kill, Targets}, From, State=#state{targets=KillQ, killer=Kill}) -> link_and_kill(Targets, Kill), Q2 = queue:snoc(KillQ, {From, Targets}), {reply, wait, State#state{targets=Q2}}; handle_call(_Msg, _From, State) -> {reply, {error, noapi}, State}. handle_cast(_Msg, State) -> {noreply, State}. handle_info({'DOWN', _MRef, process, Pid, _Reason}, State=#state{targets=Targets, victims=Victims}) -> {Client, Nodes} = queue:head(Targets), case lists:member(Pid, Nodes) of false -> {stop, {unexpected_exit, Pid}, State}; true -> T2 = lists:delete(Pid, Nodes), V2 = [Pid|Victims], case T2 of [] -> gen_server:reply(Client, {ok, V2}), Q = queue:tail(Targets), case queue:is_empty(Q) of true -> {stop, normal, State}; false -> {noreply, State#state{targets=Q, victims=[]}} end; _More -> RemainingQueue = queue:cons({Client, T2}, queue:tail(Targets)), {noreply, State#state{targets=RemainingQueue, victims=V2}} end end; handle_info({'EXIT', _, normal}, State) -> {noreply, State}. link_and_kill(Pids, Kill) -> [erlang:monitor(process, P) || P <- Pids], [spawn_link(fun() -> Kill(P) end) || P <- Pids]. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}.
befcd36ffb479ee321fac8f449926c536392cf1dcf1819221f4d03c65cdfcac2
cl-axon/cl-aima
mdp-agent.lisp
A simple policy agent for Markov decision processes ( MDPs ) . (defun make-mdp-agent (&key body name mdp program (algorithm 'value-iteration-policy)) "An MDP agent constructs a policy from the MDP once, and then uses that policy repeatedly to take action. The ALGORITHM keyword specifies the algorithm that is used to create the policy; don't confuse it with the PROGRAM keyword, which decides what actions to take." (new-mdp-agent :body body :name name :program (or program (let ((policy nil)) #'(lambda (percept) (when (null policy) (setf policy (funcall algorithm mdp))) (policy-choice (mdp-percept-state percept) policy)))))) (defstructure (mdp-agent (:include agent) (:constructor new-mdp-agent)) (total-reward 0))
null
https://raw.githubusercontent.com/cl-axon/cl-aima/1e6915fa9f3e5f2c6fd75952d674ebec53558d04/uncertainty/agents/mdp-agent.lisp
lisp
don't confuse it with the
A simple policy agent for Markov decision processes ( MDPs ) . (defun make-mdp-agent (&key body name mdp program (algorithm 'value-iteration-policy)) "An MDP agent constructs a policy from the MDP once, and then uses that policy repeatedly to take action. The ALGORITHM keyword specifies the PROGRAM keyword, which decides what actions to take." (new-mdp-agent :body body :name name :program (or program (let ((policy nil)) #'(lambda (percept) (when (null policy) (setf policy (funcall algorithm mdp))) (policy-choice (mdp-percept-state percept) policy)))))) (defstructure (mdp-agent (:include agent) (:constructor new-mdp-agent)) (total-reward 0))
4176a4a340595f215da9e456c4b348a09c41431fffec8fb70937b9fcf508eb21
simplex-chat/simplex-chat
M20220715_groups_chat_item_id.hs
# LANGUAGE QuasiQuotes # module Simplex.Chat.Migrations.M20220715_groups_chat_item_id where import Database.SQLite.Simple (Query) import Database.SQLite.Simple.QQ (sql) m20220715_groups_chat_item_id :: Query m20220715_groups_chat_item_id = [sql| ALTER TABLE groups ADD COLUMN chat_item_id INTEGER DEFAULT NULL REFERENCES chat_items ON DELETE SET NULL; |]
null
https://raw.githubusercontent.com/simplex-chat/simplex-chat/7dcde32680d05468efca6de245a21677915b9f98/src/Simplex/Chat/Migrations/M20220715_groups_chat_item_id.hs
haskell
# LANGUAGE QuasiQuotes # module Simplex.Chat.Migrations.M20220715_groups_chat_item_id where import Database.SQLite.Simple (Query) import Database.SQLite.Simple.QQ (sql) m20220715_groups_chat_item_id :: Query m20220715_groups_chat_item_id = [sql| ALTER TABLE groups ADD COLUMN chat_item_id INTEGER DEFAULT NULL REFERENCES chat_items ON DELETE SET NULL; |]
972eee9e284549d647eccad8aae35fe0cb479609fde39822eaf3f08ce11a54e2
symbiont-io/detsys-testkit
Atomics.hs
# LANGUAGE ForeignFunctionInterface # # LANGUAGE CApiFFI # module Journal.Internal.Atomics where import Data.Coerce (coerce) import Foreign import Foreign.C.Types import Journal.Internal.Utils (int2Int64) ------------------------------------------------------------------------ foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_1" c_atomic_fetch_add_word_1 :: Ptr Word8 -> Word8 -> IO Word8 foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_2" c_atomic_fetch_add_word_2 :: Ptr Word16 -> Word16 -> IO Word16 foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_4" c_atomic_fetch_add_word_4 :: Ptr Word32 -> Word32 -> IO Word32 foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_8" c_atomic_fetch_add_word_8 :: Ptr Word64 -> Word64 -> IO Word64 fetchAddWord8Ptr :: Ptr Word8 -> Word8 -> IO Word8 fetchAddWord8Ptr = c_atomic_fetch_add_word_1 # INLINE fetchAddWord8Ptr # fetchAddWord16Ptr :: Ptr Word16 -> Word16 -> IO Word16 fetchAddWord16Ptr = c_atomic_fetch_add_word_2 # INLINE fetchAddWord16Ptr # fetchAddWord32Ptr :: Ptr Word32 -> Word32 -> IO Word32 fetchAddWord32Ptr = c_atomic_fetch_add_word_4 # INLINE fetchAddWord32Ptr # fetchAddWord64Ptr :: Ptr Word64 -> Word64 -> IO Word64 fetchAddWord64Ptr = c_atomic_fetch_add_word_8 # INLINE fetchAddWord64Ptr # ------------------------------------------------------------------------ foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_1" c_atomic_fetch_add_int_1 :: Ptr Int8 -> Int8 -> IO Int8 foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_2" c_atomic_fetch_add_int_2 :: Ptr Int16 -> Int16 -> IO Int16 foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_4" c_atomic_fetch_add_int_4 :: Ptr Int32 -> Int32 -> IO Int32 foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_8" c_atomic_fetch_add_int_8 :: Ptr Int64 -> Int64 -> IO Int64 fetchAddInt8Ptr :: Ptr Int8 -> Int8 -> IO Int8 fetchAddInt8Ptr = c_atomic_fetch_add_int_1 # INLINE fetchAddInt8Ptr # fetchAddInt16Ptr :: Ptr Int16 -> Int16 -> IO Int16 fetchAddInt16Ptr = c_atomic_fetch_add_int_2 # INLINE fetchAddInt16Ptr # fetchAddInt32Ptr :: Ptr Int32 -> Int32 -> IO Int32 fetchAddInt32Ptr = c_atomic_fetch_add_int_4 # INLINE fetchAddInt32Ptr # fetchAddInt64Ptr :: Ptr Int64 -> Int64 -> IO Int64 fetchAddInt64Ptr = c_atomic_fetch_add_int_8 # INLINE fetchAddInt64Ptr # ------------------------------------------------------------------------ foreign import ccall unsafe "c_atomic_compare_exchange_strong" c_atomic_compare_exchange_strong_4 :: Ptr Int32 -> Int32 -> Int32 -> IO CBool newtype {-# CTYPE "atomic_llong" #-} AtomicLong = AtomicLong Int64 foreign import capi "stdatomic.h atomic_compare_exchange_strong" c_atomic_compare_exchange_strong_8 :: Ptr AtomicLong -> Ptr Int64 -> Int64 -> IO CBool casInt32Ptr :: Ptr Int32 -> Int32 -> Int32 -> IO Bool casInt32Ptr ptr expected desired = do result <- c_atomic_compare_exchange_strong_4 ptr expected desired case result of 0 -> return False 1 -> return True _ -> error "casInt32Addr: impossible, c_atomic_compare_exchange_strong should return a _Bool" casInt64Ptr :: Ptr Int64 -> Int64 -> Int64 -> IO Bool casInt64Ptr ptr expected desired = alloca $ \ expected_ptr -> do poke expected_ptr expected result <- c_atomic_compare_exchange_strong_8 (coerce ptr) expected_ptr desired case result of 0 -> return False 1 -> return True _ -> error "casInt64Addr: impossible, c_atomic_compare_exchange_strong should return a _Bool" casIntPtr :: Ptr Int -> Int -> Int -> IO Bool casIntPtr ptr expected desired = casInt64Ptr (castPtr ptr) (int2Int64 expected) (int2Int64 desired)
null
https://raw.githubusercontent.com/symbiont-io/detsys-testkit/9d835cf5ad1290dea0144aec4e60245b2a893824/src/journal/src/Journal/Internal/Atomics.hs
haskell
---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- # CTYPE "atomic_llong" #
# LANGUAGE ForeignFunctionInterface # # LANGUAGE CApiFFI # module Journal.Internal.Atomics where import Data.Coerce (coerce) import Foreign import Foreign.C.Types import Journal.Internal.Utils (int2Int64) foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_1" c_atomic_fetch_add_word_1 :: Ptr Word8 -> Word8 -> IO Word8 foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_2" c_atomic_fetch_add_word_2 :: Ptr Word16 -> Word16 -> IO Word16 foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_4" c_atomic_fetch_add_word_4 :: Ptr Word32 -> Word32 -> IO Word32 foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_8" c_atomic_fetch_add_word_8 :: Ptr Word64 -> Word64 -> IO Word64 fetchAddWord8Ptr :: Ptr Word8 -> Word8 -> IO Word8 fetchAddWord8Ptr = c_atomic_fetch_add_word_1 # INLINE fetchAddWord8Ptr # fetchAddWord16Ptr :: Ptr Word16 -> Word16 -> IO Word16 fetchAddWord16Ptr = c_atomic_fetch_add_word_2 # INLINE fetchAddWord16Ptr # fetchAddWord32Ptr :: Ptr Word32 -> Word32 -> IO Word32 fetchAddWord32Ptr = c_atomic_fetch_add_word_4 # INLINE fetchAddWord32Ptr # fetchAddWord64Ptr :: Ptr Word64 -> Word64 -> IO Word64 fetchAddWord64Ptr = c_atomic_fetch_add_word_8 # INLINE fetchAddWord64Ptr # foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_1" c_atomic_fetch_add_int_1 :: Ptr Int8 -> Int8 -> IO Int8 foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_2" c_atomic_fetch_add_int_2 :: Ptr Int16 -> Int16 -> IO Int16 foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_4" c_atomic_fetch_add_int_4 :: Ptr Int32 -> Int32 -> IO Int32 foreign import ccall unsafe "stdatomic.h __atomic_fetch_add_8" c_atomic_fetch_add_int_8 :: Ptr Int64 -> Int64 -> IO Int64 fetchAddInt8Ptr :: Ptr Int8 -> Int8 -> IO Int8 fetchAddInt8Ptr = c_atomic_fetch_add_int_1 # INLINE fetchAddInt8Ptr # fetchAddInt16Ptr :: Ptr Int16 -> Int16 -> IO Int16 fetchAddInt16Ptr = c_atomic_fetch_add_int_2 # INLINE fetchAddInt16Ptr # fetchAddInt32Ptr :: Ptr Int32 -> Int32 -> IO Int32 fetchAddInt32Ptr = c_atomic_fetch_add_int_4 # INLINE fetchAddInt32Ptr # fetchAddInt64Ptr :: Ptr Int64 -> Int64 -> IO Int64 fetchAddInt64Ptr = c_atomic_fetch_add_int_8 # INLINE fetchAddInt64Ptr # foreign import ccall unsafe "c_atomic_compare_exchange_strong" c_atomic_compare_exchange_strong_4 :: Ptr Int32 -> Int32 -> Int32 -> IO CBool foreign import capi "stdatomic.h atomic_compare_exchange_strong" c_atomic_compare_exchange_strong_8 :: Ptr AtomicLong -> Ptr Int64 -> Int64 -> IO CBool casInt32Ptr :: Ptr Int32 -> Int32 -> Int32 -> IO Bool casInt32Ptr ptr expected desired = do result <- c_atomic_compare_exchange_strong_4 ptr expected desired case result of 0 -> return False 1 -> return True _ -> error "casInt32Addr: impossible, c_atomic_compare_exchange_strong should return a _Bool" casInt64Ptr :: Ptr Int64 -> Int64 -> Int64 -> IO Bool casInt64Ptr ptr expected desired = alloca $ \ expected_ptr -> do poke expected_ptr expected result <- c_atomic_compare_exchange_strong_8 (coerce ptr) expected_ptr desired case result of 0 -> return False 1 -> return True _ -> error "casInt64Addr: impossible, c_atomic_compare_exchange_strong should return a _Bool" casIntPtr :: Ptr Int -> Int -> Int -> IO Bool casIntPtr ptr expected desired = casInt64Ptr (castPtr ptr) (int2Int64 expected) (int2Int64 desired)
250fdeda601aeb5df8cd038fa11ce0c765a1bea8342df0d68df98b36088e21f8
mlang/chessIO
ECO.hs
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveLift #-} {-# LANGUAGE GADTs #-} # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE RecordWildCards # {-# LANGUAGE TemplateHaskell #-} module Game.Chess.Internal.ECO where import Control.DeepSeq (NFData) import Control.Monad.IO.Class (MonadIO (..)) import Data.Bifunctor (Bifunctor (first)) import Data.Binary (Binary (get, put)) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as BS import Data.Char (chr, ord) import Data.Data () import Data.Foldable (fold) import Data.Functor (($>)) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import Data.Hashable (Hashable) import Data.Maybe (fromMaybe) import Data.MonoTraversable (MonoFoldable (ofoldl')) import Data.Text (Text) import qualified Data.Text as T import Data.Tree (foldTree) import Data.Vector.Binary () import Data.Vector.Instances () import qualified Data.Vector.Unboxed as Unboxed import Data.Void (Void) import Data.Word (Word8) import GHC.Generics (Generic) import Game.Chess.Internal (Ply, Position (moveNumber), startpos, unsafeDoPly) import Game.Chess.PGN (Annotated (_annPly), Game (CG, _cgForest, _cgOutcome, _cgTags), PGN (..), readPGNFile) import Game.Chess.SAN (relaxedSAN) import Instances.TH.Lift () import Language.Haskell.TH.Syntax (Lift) import Language.Haskell.TH.Syntax.Compat (Code, IsCode (fromCode, toCode), SpliceQ, bindCode, joinCode, liftTypedQuote) import Prelude hiding (lookup) import qualified Prelude import Text.Megaparsec (MonadParsec (eof), Parsec, anySingleBut, errorBundlePretty, many, optional, parse, single, (<?>), (<|>)) import Text.Megaparsec.Byte (alphaNumChar, digitChar, space, space1, string) import qualified Text.Megaparsec.Byte.Lexer as L -- | A Chess Opening data Opening = CO { coCode :: !Text , coName :: !Text , coVariation :: !(Maybe Text) , coPlies :: !(Unboxed.Vector Ply) } deriving (Eq, Generic, Lift, Show) instance Binary Opening instance Hashable Opening instance NFData Opening type FileReader = forall m. MonadIO m => FilePath -> m (Either String [Opening]) | Parse an ECO database in .pgn format ecoPgn :: FileReader ecoPgn fp = fmap fromPGN' <$> readPGNFile fp | Parse an ECO database in .eco format scidEco :: FileReader scidEco fp = first errorBundlePretty . parse scid' fp <$> liftIO (BS.readFile fp) -- | Encyclopedia of Chess Openings newtype ECO = ECO { toHashMap :: HashMap Position Opening } deriving (Eq, NFData, Hashable, Semigroup, Monoid) instance Binary ECO where put = put . toList get = fromList <$> get embedECO :: FileReader -> FilePath -> SpliceQ ECO embedECO load fp = fromCode $ (fmap.fmap) liftTypedQuote (load fp) `bindCode` \x -> joinCode $ case x of Right xs -> pure $ toCode [|| fromList $$(fromCode xs) ||] Left err -> fail err toList :: ECO -> [Opening] toList = map snd . HashMap.toList . toHashMap fromList :: [Opening] -> ECO fromList = ECO . HashMap.fromList . fmap (\co -> (pos co, co)) where pos = ofoldl' unsafeDoPly startpos . coPlies | Convert a PGN database to ECO assuming the ECO , Opening and Variation tags are -- being used to identify chess openings. fromPGN :: PGN -> ECO fromPGN = fromList . fromPGN' fromPGN' :: PGN -> [Opening] fromPGN' (PGN games) = map mkCO games where mkCO CG { .. } = CO { .. } where lt = (`Prelude.lookup` _cgTags) coCode = fromMaybe "" $ lt "ECO" coName = fromMaybe "" $ lt "Opening" coVariation = lt "Variation" coPlies = Unboxed.fromList . head . concatMap (foldTree g) $ _cgForest where g a [] = [[_annPly a]] g a xs = (_annPly a :) <$> fold xs opening :: Parser Opening opening = CO <$> lexeme code <*> lexeme var <*> pure Nothing <*> lexeme (plies startpos) code :: Parser Text code = p <?> "code" where p = f <$> alphaNumChar <*> many digitChar <*> optional alphaNumChar f x xs y = let s = x : xs in T.pack . fmap (chr . fromEnum) $ case y of Nothing -> s Just y' -> s ++ [y'] var :: Parser Text var = p <?> "string" where p = fmap (T.pack . fmap (chr . fromEnum)) $ single quoteChar *> many ch <* single quoteChar ch = single backslashChar *> ( single backslashChar $> backslashChar <|> single quoteChar $> quoteChar ) <|> anySingleBut quoteChar plies :: Position -> Parser (Unboxed.Vector Ply) plies = fmap Unboxed.fromList . go where go p = eol <|> line where eol = lexeme (string "*") $> [] line = ply >>= \pl -> (pl :) <$> go (unsafeDoPly p pl) ply = validateMoveNumber p *> lexeme (relaxedSAN p) validateMoveNumber p = optional (lexeme $ L.decimal <* space <* many (single periodChar)) >>= \case Just n | moveNumber p /= n -> fail $ "Invalid move number: " <> show n <> " /= " <> show (moveNumber p) _ -> pure () | A parser for opening databases in SCID .eco format scid :: Parser ECO scid = fromList <$> scid' scid' :: Parser [Opening] scid' = spaceConsumer *> many opening <* eof readECOPGNFile :: MonadIO m => FilePath -> m (Either String ECO) readECOPGNFile = (fmap . fmap) fromList . ecoPgn readSCIDECOFile :: MonadIO m => FilePath -> m (Either String ECO) readSCIDECOFile = (fmap . fmap) fromList . scidEco -- | Retrieve the opening for a particular position lookup :: Position -> ECO -> Maybe Opening lookup pos = HashMap.lookup pos . toHashMap type Parser = Parsec Void ByteString spaceConsumer :: Parser () spaceConsumer = L.space space1 (L.skipLineComment "#") (L.skipBlockComment "{" "}") lexeme :: Parser a -> Parser a lexeme = L.lexeme spaceConsumer periodChar, quoteChar, backslashChar :: Word8 periodChar = fromIntegral $ ord '.' quoteChar = fromIntegral $ ord '"' backslashChar = fromIntegral $ ord '\\'
null
https://raw.githubusercontent.com/mlang/chessIO/3ea2e165fda33fadb56a706d9f07b1b239986c08/src/Game/Chess/Internal/ECO.hs
haskell
# LANGUAGE DeriveGeneric # # LANGUAGE DeriveLift # # LANGUAGE GADTs # # LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # # LANGUAGE TemplateHaskell # | A Chess Opening | Encyclopedia of Chess Openings being used to identify chess openings. | Retrieve the opening for a particular position
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE RecordWildCards # module Game.Chess.Internal.ECO where import Control.DeepSeq (NFData) import Control.Monad.IO.Class (MonadIO (..)) import Data.Bifunctor (Bifunctor (first)) import Data.Binary (Binary (get, put)) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as BS import Data.Char (chr, ord) import Data.Data () import Data.Foldable (fold) import Data.Functor (($>)) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import Data.Hashable (Hashable) import Data.Maybe (fromMaybe) import Data.MonoTraversable (MonoFoldable (ofoldl')) import Data.Text (Text) import qualified Data.Text as T import Data.Tree (foldTree) import Data.Vector.Binary () import Data.Vector.Instances () import qualified Data.Vector.Unboxed as Unboxed import Data.Void (Void) import Data.Word (Word8) import GHC.Generics (Generic) import Game.Chess.Internal (Ply, Position (moveNumber), startpos, unsafeDoPly) import Game.Chess.PGN (Annotated (_annPly), Game (CG, _cgForest, _cgOutcome, _cgTags), PGN (..), readPGNFile) import Game.Chess.SAN (relaxedSAN) import Instances.TH.Lift () import Language.Haskell.TH.Syntax (Lift) import Language.Haskell.TH.Syntax.Compat (Code, IsCode (fromCode, toCode), SpliceQ, bindCode, joinCode, liftTypedQuote) import Prelude hiding (lookup) import qualified Prelude import Text.Megaparsec (MonadParsec (eof), Parsec, anySingleBut, errorBundlePretty, many, optional, parse, single, (<?>), (<|>)) import Text.Megaparsec.Byte (alphaNumChar, digitChar, space, space1, string) import qualified Text.Megaparsec.Byte.Lexer as L data Opening = CO { coCode :: !Text , coName :: !Text , coVariation :: !(Maybe Text) , coPlies :: !(Unboxed.Vector Ply) } deriving (Eq, Generic, Lift, Show) instance Binary Opening instance Hashable Opening instance NFData Opening type FileReader = forall m. MonadIO m => FilePath -> m (Either String [Opening]) | Parse an ECO database in .pgn format ecoPgn :: FileReader ecoPgn fp = fmap fromPGN' <$> readPGNFile fp | Parse an ECO database in .eco format scidEco :: FileReader scidEco fp = first errorBundlePretty . parse scid' fp <$> liftIO (BS.readFile fp) newtype ECO = ECO { toHashMap :: HashMap Position Opening } deriving (Eq, NFData, Hashable, Semigroup, Monoid) instance Binary ECO where put = put . toList get = fromList <$> get embedECO :: FileReader -> FilePath -> SpliceQ ECO embedECO load fp = fromCode $ (fmap.fmap) liftTypedQuote (load fp) `bindCode` \x -> joinCode $ case x of Right xs -> pure $ toCode [|| fromList $$(fromCode xs) ||] Left err -> fail err toList :: ECO -> [Opening] toList = map snd . HashMap.toList . toHashMap fromList :: [Opening] -> ECO fromList = ECO . HashMap.fromList . fmap (\co -> (pos co, co)) where pos = ofoldl' unsafeDoPly startpos . coPlies | Convert a PGN database to ECO assuming the ECO , Opening and Variation tags are fromPGN :: PGN -> ECO fromPGN = fromList . fromPGN' fromPGN' :: PGN -> [Opening] fromPGN' (PGN games) = map mkCO games where mkCO CG { .. } = CO { .. } where lt = (`Prelude.lookup` _cgTags) coCode = fromMaybe "" $ lt "ECO" coName = fromMaybe "" $ lt "Opening" coVariation = lt "Variation" coPlies = Unboxed.fromList . head . concatMap (foldTree g) $ _cgForest where g a [] = [[_annPly a]] g a xs = (_annPly a :) <$> fold xs opening :: Parser Opening opening = CO <$> lexeme code <*> lexeme var <*> pure Nothing <*> lexeme (plies startpos) code :: Parser Text code = p <?> "code" where p = f <$> alphaNumChar <*> many digitChar <*> optional alphaNumChar f x xs y = let s = x : xs in T.pack . fmap (chr . fromEnum) $ case y of Nothing -> s Just y' -> s ++ [y'] var :: Parser Text var = p <?> "string" where p = fmap (T.pack . fmap (chr . fromEnum)) $ single quoteChar *> many ch <* single quoteChar ch = single backslashChar *> ( single backslashChar $> backslashChar <|> single quoteChar $> quoteChar ) <|> anySingleBut quoteChar plies :: Position -> Parser (Unboxed.Vector Ply) plies = fmap Unboxed.fromList . go where go p = eol <|> line where eol = lexeme (string "*") $> [] line = ply >>= \pl -> (pl :) <$> go (unsafeDoPly p pl) ply = validateMoveNumber p *> lexeme (relaxedSAN p) validateMoveNumber p = optional (lexeme $ L.decimal <* space <* many (single periodChar)) >>= \case Just n | moveNumber p /= n -> fail $ "Invalid move number: " <> show n <> " /= " <> show (moveNumber p) _ -> pure () | A parser for opening databases in SCID .eco format scid :: Parser ECO scid = fromList <$> scid' scid' :: Parser [Opening] scid' = spaceConsumer *> many opening <* eof readECOPGNFile :: MonadIO m => FilePath -> m (Either String ECO) readECOPGNFile = (fmap . fmap) fromList . ecoPgn readSCIDECOFile :: MonadIO m => FilePath -> m (Either String ECO) readSCIDECOFile = (fmap . fmap) fromList . scidEco lookup :: Position -> ECO -> Maybe Opening lookup pos = HashMap.lookup pos . toHashMap type Parser = Parsec Void ByteString spaceConsumer :: Parser () spaceConsumer = L.space space1 (L.skipLineComment "#") (L.skipBlockComment "{" "}") lexeme :: Parser a -> Parser a lexeme = L.lexeme spaceConsumer periodChar, quoteChar, backslashChar :: Word8 periodChar = fromIntegral $ ord '.' quoteChar = fromIntegral $ ord '"' backslashChar = fromIntegral $ ord '\\'
403dcc0d462dce30b6a6901ee41c0b58b27f71a41d69a8bd801de04ebfb527c3
solita/mnt-teet
map_features.cljs
(ns teet.map.map-features "Defines rendering styles for map features " (:require [clojure.string :as str] [ol.style.Style] [ol.style.Icon] [ol.style.Stroke] [ol.style.Fill] [ol.render.Feature] [ol.style.Circle] [teet.theme.theme-colors :as theme-colors] [ol.extent :as ol-extent] [teet.asset.asset-model :as asset-model] [teet.log :as log])) (def ^:const map-pin-height 26) (def ^:const map-pin-width 20) (defn- styles [& ol-styles] (into-array (remove nil? ol-styles))) (defn- draw-map-pin-path [ctx] " M9.96587 0.5C15.221 0.5 19.5 4.78348 19.5 9.96587C19.5 12.7235 17.9724 15.4076 15.9208 18.0187C14.9006 19.3172 13.7685 20.5764 12.6603 21.802C12.611 21.8565 12.5618 21.911 12.5126 21.9653C11.6179 22.9546 10.7407 23.9244 9.9694 24.8638C9.1882 23.8963 8.29237 22.8969 7.37848 21.8774L7.31238 21.8036C6.21334 20.5775 5.08749 19.3183 4.07125 18.0195C2.02771 15.4079 0.5 12.7237 0.5 9.96587C0.5 4.78126 4.78126 0.5 9.96587 0.5Z " (doto ctx .beginPath (.moveTo 9.96587 0.5) (.bezierCurveTo 15.221 0.5 19.5 4.78348 19.5 9.96587) (.bezierCurveTo 19.5 12.7235 17.9724 15.4076 15.9208 18.0187) (.bezierCurveTo 14.9006 19.3172 13.7685 20.5764 12.6603 21.802) (.bezierCurveTo 12.611 21.8565 12.5618 21.911 12.5126 21.9653) (.bezierCurveTo 11.6179 22.9546 10.7407 23.9244 9.9694 24.8638) (.bezierCurveTo 9.1882 23.8963 8.29237 22.8969 7.37848 21.8774) (.lineTo 7.31238 21.8036) (.bezierCurveTo 6.21334 20.5775 5.08749 19.3183 4.07125 18.0195) (.bezierCurveTo 2.02771 15.4079 0.5 12.7237 0.5 9.96587) (.bezierCurveTo 0.5 4.78126 4.78126 0.5 9.96587 0.5) .closePath)) (def project-pin-icon (memoize (fn [w h fill stroke center-fill] (let [canvas (.createElement js/document "canvas") scaled-w (/ w map-pin-width) scaled-h (/ h map-pin-height)] (set! (.-width canvas) w) (set! (.-height canvas) h) (let [ctx (.getContext canvas "2d")] (.scale ctx scaled-w scaled-h) (when fill (set! (.-strokeStyle ctx) stroke) ( set ! ( .-lineWidth ctx ) 5 ) (set! (.-fillStyle ctx) fill) ;; draw the map pin (draw-map-pin-path ctx) (.stroke ctx) (.fill ctx)) ;; draw the center white circle in the pin (when center-fill (set! (.-strokeStyle ctx) stroke) (set! (.-fillStyle ctx) center-fill) (doto ctx .beginPath (.arc 10 10 4 0 (* 2 js/Math.PI)) .stroke .fill))) canvas)))) (defn road-line-style ([color feature res] (road-line-style 1 color feature res)) ([width-multiplier color ^ol.render.Feature feature res] (let [line-width (* width-multiplier (+ 3 (min 5 (int (/ 200 res)))))] ;; Show project road geometry line (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color color :width line-width :lineCap "butt"}) :zIndex 2})))) (def ^{:doc "Show project geometry as the road line."} project-line-style (partial road-line-style "blue")) (defn project-line-style-with-buffer [buffer] (fn [feature res] #js [(project-line-style feature res) (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(0,0,255,0.25)" :width (/ (* 2 buffer) res) :opacity 0.5}) :zIndex 3})])) (defn asset-road-line-style [^ol.render.Feature feature res] (case (-> feature .getGeometry .getType) "Point" #js [(ol.style.Style. #js {:image (ol.style.Circle. #js {:fill (ol.style.Fill. #js {:color "black"}) :radius 2})}) (ol.style.Style. #js {:image (ol.style.Circle. #js {:stroke (ol.style.Stroke. #js {:color "black"}) :fill (ol.style.Fill. #js {:color "rgba(0,0,0,0.5)"}) :radius 10})})] "LineString" (project-line-style feature res))) (def electric-pattern (let [a (atom nil) canvas (.createElement js/document "canvas")] (set! (.-width canvas) 32) (set! (.-height canvas) 32) (let [ctx (.getContext canvas "2d")] (set! (.-strokeStyle ctx) "black") (set! (.-lineWidth ctx) 3) (set! (.-fillStyle ctx) "yellow") (.fillRect ctx 0 0 32 32) ;; Draw electricity lightning arrow symbol (.scale ctx 0.0625 0.0625) (.stroke ctx (js/Path2D. "M174.167,512l67.63-223.176H101.992L218.751,0h134.235l-86.647,213.73h143.669L174.167,512z M127.689,271.495h137.467l-47.9,158.072l156.959-198.508H240.614l86.647-213.73h-96.824L127.689,271.495z")) (let [img (js/Image.)] (set! (.-onload img) #(do (js/console.log "img loaded" img) (reset! a (.createPattern ctx img "repeat")))) (set! (.-src img) (.toDataURL canvas)))) a)) (defn- restriction-fill [feature default-color] (let [[type & _] (some-> feature .getProperties (aget "tooltip") (str/split #":"))] (if (= type "Elektripaigaldise kaitsevöönd") @electric-pattern default-color))) (def ^:const small-feature-area-threshold "Minimum feature area divided by resolution to show indicator" 2000) ;; A green transparent circle icon (def ^:const small-feature-icon-src "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAA4ElEQVRYR+2X3Q6AIAiFc61365F7t9ZqttmMAI8sfy7ssoTzAZrgpsxn2eZTM9nXw+W4hBanRCVBBEYFsApTIA1EBNDENYeSnWTDAnBOkHTSyKkfzscHADHK2WR+beyTQrwASogHWAniASgprkGwAJZ6o2UJgQaNG6BG9FIWPgAlo6cQXqs9gHZE0Lpa1gVdNwBGBkYGmmcgdV1aznjKJr4P2v8Ju7iMapaBvY5rZYHb8P20ZFzD4N/90R/ATakEYQVBOq0+BxMtE6mfDPfdNJrFjqwzIrJ/oOk4BwYRjf1dniXWGdHmXjUAAAAASUVORK5CYII=") (defn- small-feature-style [^ol.render.Feature feature res] (let [g (.getGeometry feature)] (when (<= (/ (.getArea g) res) small-feature-area-threshold) (ol.style.Style. #js {:geometry (ol.geom.Point. (ol-extent/getCenter (.getExtent g))) :image (ol.style.Icon. #js {:src small-feature-icon-src :imgSize #js [32 32]})})))) (defn project-related-restriction-style "Show project related restriction as a filled area." [^ol.render.Feature feature res] (let [hover? (.get feature "hover")] (styles (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(143,0,255,0.8)" :width (if hover? 3 1)}) :fill (ol.style.Fill. #js {:color (if hover? "rgba(143,0,255,0.5)" (restriction-fill feature "rgba(143,0,255,0.2)"))}) :zIndex 3}) (when hover? (small-feature-style feature res))))) (defn project-restriction-style "Show restriction geometrys as area. Restrictions are all (multi)polygons." [^ol.render.Feature _feature _res] (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(143,0,255,0.8)" :width 1}) :fill (ol.style.Fill. #js {:color "rgba(143,0,255,0.2)"}) :zIndex 3})) (defn project-pin-style "Show project centroid as a pin icon." [^ol.render.Feature _feature _res] (ol.style.Style. #js {:image (ol.style.Icon. #js {:img (project-pin-icon map-pin-width map-pin-height theme-colors/primary theme-colors/blue-dark theme-colors/white) :imgSize #js [24 30] :anchor #js [0.5 1.0]})})) (defn crosshair-pin-style [^ol.render.Feature _feature _res] (ol.style.Style. #js {:image (ol.style.Icon. #js {:src "/img/crosshair.png" :anchor #js [0.5 0.5]})})) (defn drawn-area-style [^ol.render.Feature feature _res] (let [hover? (.get feature "hover")] (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(0,123,175,0.8)" :width 2}) :fill (ol.style.Fill. #js {:cursor :pointer :color (if hover? "rgba(0,123,175,0.8)" "rgba(0,123,175,0.3)")})}))) (defn cadastral-unit-style "Show cadastral unit." [^ol.render.Feature feature res] (let [hover? (.get feature "hover") selected? (.get feature "selected") res (if (> 1 res) 1 res)] (styles (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(0,0,0,0.6)" :lineDash #js [(/ 15 res), (/ 30 res)] :width 2}) :fill (ol.style.Fill. #js {:cursor :pointer :color (cond selected? "rgba(100,110,105,0.8)" hover? "rgba(100,110,105,0.6)" :else "rgba(186,187,171,0.6)")})}) (when hover? (small-feature-style feature res))))) (defn selected-cadastral-unit-style "style for selected cadastral units" [^ol.render.Feature feature res] (let [hover? (.get feature "hover")] (styles (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(0,94,135,0.8)" :width 2}) :fill (ol.style.Fill. #js {:cursor :pointer :color (if hover? "rgba(0,94,135,0.8)" "rgba(0,94,135,0.5)")})}) (when hover? (small-feature-style feature res))))) (defn selected-restrictions-style "Show project related restriction as a filled area." [^ol.render.Feature feature res] (let [hover? (.get feature "hover")] (styles (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(0,94,135,0.8)" :width 2}) :fill (ol.style.Fill. #js {:cursor :pointer :color (if hover? "rgba(0,94,135,0.8)" "rgba(0,94,135,0.5)")})}) (when hover? (small-feature-style feature res))))) (defn heritage-style "Show heritage points." [^ol.render.Feature _feature _res] ;(js/console.log "heritage feature: " (.getType (.getGeometry _feature))) (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "#9d0002" :width 2}) :fill (ol.style.Fill. #js {:cursor :pointer :color "#c43c39"})})) (def heritage-protection-zone-pattern (let [a (atom nil) canvas (.createElement js/document "canvas")] (set! (.-width canvas) 32) (set! (.-height canvas) 32) (let [ctx (.getContext canvas "2d")] (set! (.-strokeStyle ctx) "black") (set! (.-lineWidth ctx) 3) (set! (.-fillStyle ctx) "purple") (.fillRect ctx 0 0 32 32) (.beginPath ctx) (.moveTo ctx 4 12) (.lineTo ctx 28 2) (.moveTo ctx 4 20) (.lineTo ctx 28 10) (.stroke ctx) (let [img (js/Image.)] (set! (.-onload img) #(do (js/console.log "protection zone img loaded" img) (reset! a (.createPattern ctx img "repeat")))) (set! (.-src img) (.toDataURL canvas)))) a)) (defn heritage-protection-zone-style "Show heritage protection zones" [] (ol.style.Style. #js {:fill (ol.style.Fill. #js {:color @heritage-protection-zone-pattern})})) (defn survey-style "Show survey area." [^ol.render.Feature _feature _res] (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "#830891" :width 2}) :fill (ol.style.Fill. #js {:cursor :pointer :color "#af38bc"})})) (defn ags-survey-style "Show AGS survey feature (point)" [^ol.render.Feature _feature _res] (ol.style.Style. #js {:image (ol.style.Circle. #js {:fill (ol.style.Fill. #js {:color "red"}) :stroke (ol.style.Stroke. #js {:color "black"}) :radius 5})})) (defn highlighted-road-object-style "Show highlighted road object" [^ol.render.Feature feature _res] (let [type (-> feature .getGeometry .getType)] (if (= type "Point") ;; Show a circle indicating feature position (ol.style.Style. #js {:image (ol.style.Circle. #js {:fill (ol.style.Fill. #js {:color "#ff30aa"}) :stroke (ol.style.Stroke. #js {:color "#ffffff"}) :radius 20})}) ;; Stroke the linestring (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "#ffffff" :width 20}) :fill (ol.style.Fill. #js {:cursor :pointer :color "#ff30aa"})})))) (defn- rounded-rect [ctx x y w h r] (doto ctx .beginPath (.moveTo (+ x r) y) (.arcTo (+ x w) y (+ x w) (+ y h) r) (.arcTo (+ x w) (+ y h) x (+ y h) r) (.arcTo x (+ y h) x y r) (.arcTo x y (+ x w) y r) .closePath)) (def text->canvas (memoize (fn [{:keys [font fill stroke text w h x y background-fill r]}] (let [canvas (.createElement js/document "canvas")] (set! (.-width canvas) w) (set! (.-height canvas) h) (let [ctx (.getContext canvas "2d")] (when background-fill (set! (.-fillStyle ctx) background-fill) (rounded-rect ctx 0 0 w h (or r (* w 0.10))) (.fill ctx)) (set! (.-font ctx) font) (set! (.-fillStyle ctx) fill) (set! (.-strokeStyle ctx) stroke) (.fillText ctx text x y) (when stroke (.strokeText ctx text x y))) canvas)))) (def asset-bg-colors "Some random bg colors for asset badges" ["#ff6f59ff" "#254441ff" "#43aa8bff" "#b2b09bff" "#ef3054ff"]) (defn asset-bg-color-by-hash [cls] (nth asset-bg-colors (mod (hash cls) (count asset-bg-colors)))) (defn asset-line-and-icon "Show line between start->end points of asset location and an icon based on asset class." [highlight-oid ^ol.render.Feature feature _res] (let [oid (some-> feature .getProperties (aget "oid")) highlight? (= oid highlight-oid) cls (some-> oid asset-model/asset-oid->fclass-oid-prefix) center (-> feature .getGeometry .getExtent ol-extent/getCenter ol.geom.Point.)] (into-array (remove nil? [(ol.style.Style. #js {:geometry center :image (ol.style.Icon. #js {:anchor #js [0.5 0.5] :imgSize #js [36 20] :img (text->canvas {:font "16px monospace" :fill "black" :w 36 :h 20 :x 3 :y 15 :text cls :background-fill (asset-bg-color-by-hash cls) :r 5})})}) (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "red" :width 3 :lineCap "butt"}) :zIndex 2}) (when highlight? (ol.style.Style. #js {:geometry center :image (ol.style.Circle. #js {:stroke (ol.style.Stroke. #js {:color "green" :width 3}) :radius 15})}))])))) (defn asset-or-component "Show line or circle for asset/component." [^ol.render.Feature feature _res] (if (some->> feature .getGeometry .getType (= "Point")) #js [(ol.style.Style. #js {:image (ol.style.Circle. #js {:stroke (ol.style.Stroke. #js {:color "red" :width 2}) :radius 10})}) (ol.style.Style. #js {:image (ol.style.Circle. #js {:fill (ol.style.Fill. #js {:color "black" :width 1}) :radius 3})})] (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "red" :width 3 ;:lineCap "butt" }) :zIndex 3}))) (defn current-location-radius-style "Show circle radius around current location (point)" [^ol.render.Feature _feature _res] (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "blue"})})) (def region-area-style (constantly (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(100,100,100,0.5)" :width 2}) :fill (ol.style.Fill. #js {:cursor :pointer :color "rgba(200,200,200,0.5)"})})))
null
https://raw.githubusercontent.com/solita/mnt-teet/40d9ffc31b95225f2e4713b70904314c1c862e6c/app/frontend/src/cljs/teet/map/map_features.cljs
clojure
draw the map pin draw the center white circle in the pin Show project road geometry line Draw electricity lightning arrow symbol A green transparent circle icon (js/console.log "heritage feature: " (.getType (.getGeometry _feature))) Show a circle indicating feature position Stroke the linestring :lineCap "butt"
(ns teet.map.map-features "Defines rendering styles for map features " (:require [clojure.string :as str] [ol.style.Style] [ol.style.Icon] [ol.style.Stroke] [ol.style.Fill] [ol.render.Feature] [ol.style.Circle] [teet.theme.theme-colors :as theme-colors] [ol.extent :as ol-extent] [teet.asset.asset-model :as asset-model] [teet.log :as log])) (def ^:const map-pin-height 26) (def ^:const map-pin-width 20) (defn- styles [& ol-styles] (into-array (remove nil? ol-styles))) (defn- draw-map-pin-path [ctx] " M9.96587 0.5C15.221 0.5 19.5 4.78348 19.5 9.96587C19.5 12.7235 17.9724 15.4076 15.9208 18.0187C14.9006 19.3172 13.7685 20.5764 12.6603 21.802C12.611 21.8565 12.5618 21.911 12.5126 21.9653C11.6179 22.9546 10.7407 23.9244 9.9694 24.8638C9.1882 23.8963 8.29237 22.8969 7.37848 21.8774L7.31238 21.8036C6.21334 20.5775 5.08749 19.3183 4.07125 18.0195C2.02771 15.4079 0.5 12.7237 0.5 9.96587C0.5 4.78126 4.78126 0.5 9.96587 0.5Z " (doto ctx .beginPath (.moveTo 9.96587 0.5) (.bezierCurveTo 15.221 0.5 19.5 4.78348 19.5 9.96587) (.bezierCurveTo 19.5 12.7235 17.9724 15.4076 15.9208 18.0187) (.bezierCurveTo 14.9006 19.3172 13.7685 20.5764 12.6603 21.802) (.bezierCurveTo 12.611 21.8565 12.5618 21.911 12.5126 21.9653) (.bezierCurveTo 11.6179 22.9546 10.7407 23.9244 9.9694 24.8638) (.bezierCurveTo 9.1882 23.8963 8.29237 22.8969 7.37848 21.8774) (.lineTo 7.31238 21.8036) (.bezierCurveTo 6.21334 20.5775 5.08749 19.3183 4.07125 18.0195) (.bezierCurveTo 2.02771 15.4079 0.5 12.7237 0.5 9.96587) (.bezierCurveTo 0.5 4.78126 4.78126 0.5 9.96587 0.5) .closePath)) (def project-pin-icon (memoize (fn [w h fill stroke center-fill] (let [canvas (.createElement js/document "canvas") scaled-w (/ w map-pin-width) scaled-h (/ h map-pin-height)] (set! (.-width canvas) w) (set! (.-height canvas) h) (let [ctx (.getContext canvas "2d")] (.scale ctx scaled-w scaled-h) (when fill (set! (.-strokeStyle ctx) stroke) ( set ! ( .-lineWidth ctx ) 5 ) (set! (.-fillStyle ctx) fill) (draw-map-pin-path ctx) (.stroke ctx) (.fill ctx)) (when center-fill (set! (.-strokeStyle ctx) stroke) (set! (.-fillStyle ctx) center-fill) (doto ctx .beginPath (.arc 10 10 4 0 (* 2 js/Math.PI)) .stroke .fill))) canvas)))) (defn road-line-style ([color feature res] (road-line-style 1 color feature res)) ([width-multiplier color ^ol.render.Feature feature res] (let [line-width (* width-multiplier (+ 3 (min 5 (int (/ 200 res)))))] (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color color :width line-width :lineCap "butt"}) :zIndex 2})))) (def ^{:doc "Show project geometry as the road line."} project-line-style (partial road-line-style "blue")) (defn project-line-style-with-buffer [buffer] (fn [feature res] #js [(project-line-style feature res) (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(0,0,255,0.25)" :width (/ (* 2 buffer) res) :opacity 0.5}) :zIndex 3})])) (defn asset-road-line-style [^ol.render.Feature feature res] (case (-> feature .getGeometry .getType) "Point" #js [(ol.style.Style. #js {:image (ol.style.Circle. #js {:fill (ol.style.Fill. #js {:color "black"}) :radius 2})}) (ol.style.Style. #js {:image (ol.style.Circle. #js {:stroke (ol.style.Stroke. #js {:color "black"}) :fill (ol.style.Fill. #js {:color "rgba(0,0,0,0.5)"}) :radius 10})})] "LineString" (project-line-style feature res))) (def electric-pattern (let [a (atom nil) canvas (.createElement js/document "canvas")] (set! (.-width canvas) 32) (set! (.-height canvas) 32) (let [ctx (.getContext canvas "2d")] (set! (.-strokeStyle ctx) "black") (set! (.-lineWidth ctx) 3) (set! (.-fillStyle ctx) "yellow") (.fillRect ctx 0 0 32 32) (.scale ctx 0.0625 0.0625) (.stroke ctx (js/Path2D. "M174.167,512l67.63-223.176H101.992L218.751,0h134.235l-86.647,213.73h143.669L174.167,512z M127.689,271.495h137.467l-47.9,158.072l156.959-198.508H240.614l86.647-213.73h-96.824L127.689,271.495z")) (let [img (js/Image.)] (set! (.-onload img) #(do (js/console.log "img loaded" img) (reset! a (.createPattern ctx img "repeat")))) (set! (.-src img) (.toDataURL canvas)))) a)) (defn- restriction-fill [feature default-color] (let [[type & _] (some-> feature .getProperties (aget "tooltip") (str/split #":"))] (if (= type "Elektripaigaldise kaitsevöönd") @electric-pattern default-color))) (def ^:const small-feature-area-threshold "Minimum feature area divided by resolution to show indicator" 2000) (def ^:const small-feature-icon-src "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAA4ElEQVRYR+2X3Q6AIAiFc61365F7t9ZqttmMAI8sfy7ssoTzAZrgpsxn2eZTM9nXw+W4hBanRCVBBEYFsApTIA1EBNDENYeSnWTDAnBOkHTSyKkfzscHADHK2WR+beyTQrwASogHWAniASgprkGwAJZ6o2UJgQaNG6BG9FIWPgAlo6cQXqs9gHZE0Lpa1gVdNwBGBkYGmmcgdV1aznjKJr4P2v8Ju7iMapaBvY5rZYHb8P20ZFzD4N/90R/ATakEYQVBOq0+BxMtE6mfDPfdNJrFjqwzIrJ/oOk4BwYRjf1dniXWGdHmXjUAAAAASUVORK5CYII=") (defn- small-feature-style [^ol.render.Feature feature res] (let [g (.getGeometry feature)] (when (<= (/ (.getArea g) res) small-feature-area-threshold) (ol.style.Style. #js {:geometry (ol.geom.Point. (ol-extent/getCenter (.getExtent g))) :image (ol.style.Icon. #js {:src small-feature-icon-src :imgSize #js [32 32]})})))) (defn project-related-restriction-style "Show project related restriction as a filled area." [^ol.render.Feature feature res] (let [hover? (.get feature "hover")] (styles (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(143,0,255,0.8)" :width (if hover? 3 1)}) :fill (ol.style.Fill. #js {:color (if hover? "rgba(143,0,255,0.5)" (restriction-fill feature "rgba(143,0,255,0.2)"))}) :zIndex 3}) (when hover? (small-feature-style feature res))))) (defn project-restriction-style "Show restriction geometrys as area. Restrictions are all (multi)polygons." [^ol.render.Feature _feature _res] (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(143,0,255,0.8)" :width 1}) :fill (ol.style.Fill. #js {:color "rgba(143,0,255,0.2)"}) :zIndex 3})) (defn project-pin-style "Show project centroid as a pin icon." [^ol.render.Feature _feature _res] (ol.style.Style. #js {:image (ol.style.Icon. #js {:img (project-pin-icon map-pin-width map-pin-height theme-colors/primary theme-colors/blue-dark theme-colors/white) :imgSize #js [24 30] :anchor #js [0.5 1.0]})})) (defn crosshair-pin-style [^ol.render.Feature _feature _res] (ol.style.Style. #js {:image (ol.style.Icon. #js {:src "/img/crosshair.png" :anchor #js [0.5 0.5]})})) (defn drawn-area-style [^ol.render.Feature feature _res] (let [hover? (.get feature "hover")] (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(0,123,175,0.8)" :width 2}) :fill (ol.style.Fill. #js {:cursor :pointer :color (if hover? "rgba(0,123,175,0.8)" "rgba(0,123,175,0.3)")})}))) (defn cadastral-unit-style "Show cadastral unit." [^ol.render.Feature feature res] (let [hover? (.get feature "hover") selected? (.get feature "selected") res (if (> 1 res) 1 res)] (styles (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(0,0,0,0.6)" :lineDash #js [(/ 15 res), (/ 30 res)] :width 2}) :fill (ol.style.Fill. #js {:cursor :pointer :color (cond selected? "rgba(100,110,105,0.8)" hover? "rgba(100,110,105,0.6)" :else "rgba(186,187,171,0.6)")})}) (when hover? (small-feature-style feature res))))) (defn selected-cadastral-unit-style "style for selected cadastral units" [^ol.render.Feature feature res] (let [hover? (.get feature "hover")] (styles (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(0,94,135,0.8)" :width 2}) :fill (ol.style.Fill. #js {:cursor :pointer :color (if hover? "rgba(0,94,135,0.8)" "rgba(0,94,135,0.5)")})}) (when hover? (small-feature-style feature res))))) (defn selected-restrictions-style "Show project related restriction as a filled area." [^ol.render.Feature feature res] (let [hover? (.get feature "hover")] (styles (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(0,94,135,0.8)" :width 2}) :fill (ol.style.Fill. #js {:cursor :pointer :color (if hover? "rgba(0,94,135,0.8)" "rgba(0,94,135,0.5)")})}) (when hover? (small-feature-style feature res))))) (defn heritage-style "Show heritage points." [^ol.render.Feature _feature _res] (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "#9d0002" :width 2}) :fill (ol.style.Fill. #js {:cursor :pointer :color "#c43c39"})})) (def heritage-protection-zone-pattern (let [a (atom nil) canvas (.createElement js/document "canvas")] (set! (.-width canvas) 32) (set! (.-height canvas) 32) (let [ctx (.getContext canvas "2d")] (set! (.-strokeStyle ctx) "black") (set! (.-lineWidth ctx) 3) (set! (.-fillStyle ctx) "purple") (.fillRect ctx 0 0 32 32) (.beginPath ctx) (.moveTo ctx 4 12) (.lineTo ctx 28 2) (.moveTo ctx 4 20) (.lineTo ctx 28 10) (.stroke ctx) (let [img (js/Image.)] (set! (.-onload img) #(do (js/console.log "protection zone img loaded" img) (reset! a (.createPattern ctx img "repeat")))) (set! (.-src img) (.toDataURL canvas)))) a)) (defn heritage-protection-zone-style "Show heritage protection zones" [] (ol.style.Style. #js {:fill (ol.style.Fill. #js {:color @heritage-protection-zone-pattern})})) (defn survey-style "Show survey area." [^ol.render.Feature _feature _res] (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "#830891" :width 2}) :fill (ol.style.Fill. #js {:cursor :pointer :color "#af38bc"})})) (defn ags-survey-style "Show AGS survey feature (point)" [^ol.render.Feature _feature _res] (ol.style.Style. #js {:image (ol.style.Circle. #js {:fill (ol.style.Fill. #js {:color "red"}) :stroke (ol.style.Stroke. #js {:color "black"}) :radius 5})})) (defn highlighted-road-object-style "Show highlighted road object" [^ol.render.Feature feature _res] (let [type (-> feature .getGeometry .getType)] (if (= type "Point") (ol.style.Style. #js {:image (ol.style.Circle. #js {:fill (ol.style.Fill. #js {:color "#ff30aa"}) :stroke (ol.style.Stroke. #js {:color "#ffffff"}) :radius 20})}) (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "#ffffff" :width 20}) :fill (ol.style.Fill. #js {:cursor :pointer :color "#ff30aa"})})))) (defn- rounded-rect [ctx x y w h r] (doto ctx .beginPath (.moveTo (+ x r) y) (.arcTo (+ x w) y (+ x w) (+ y h) r) (.arcTo (+ x w) (+ y h) x (+ y h) r) (.arcTo x (+ y h) x y r) (.arcTo x y (+ x w) y r) .closePath)) (def text->canvas (memoize (fn [{:keys [font fill stroke text w h x y background-fill r]}] (let [canvas (.createElement js/document "canvas")] (set! (.-width canvas) w) (set! (.-height canvas) h) (let [ctx (.getContext canvas "2d")] (when background-fill (set! (.-fillStyle ctx) background-fill) (rounded-rect ctx 0 0 w h (or r (* w 0.10))) (.fill ctx)) (set! (.-font ctx) font) (set! (.-fillStyle ctx) fill) (set! (.-strokeStyle ctx) stroke) (.fillText ctx text x y) (when stroke (.strokeText ctx text x y))) canvas)))) (def asset-bg-colors "Some random bg colors for asset badges" ["#ff6f59ff" "#254441ff" "#43aa8bff" "#b2b09bff" "#ef3054ff"]) (defn asset-bg-color-by-hash [cls] (nth asset-bg-colors (mod (hash cls) (count asset-bg-colors)))) (defn asset-line-and-icon "Show line between start->end points of asset location and an icon based on asset class." [highlight-oid ^ol.render.Feature feature _res] (let [oid (some-> feature .getProperties (aget "oid")) highlight? (= oid highlight-oid) cls (some-> oid asset-model/asset-oid->fclass-oid-prefix) center (-> feature .getGeometry .getExtent ol-extent/getCenter ol.geom.Point.)] (into-array (remove nil? [(ol.style.Style. #js {:geometry center :image (ol.style.Icon. #js {:anchor #js [0.5 0.5] :imgSize #js [36 20] :img (text->canvas {:font "16px monospace" :fill "black" :w 36 :h 20 :x 3 :y 15 :text cls :background-fill (asset-bg-color-by-hash cls) :r 5})})}) (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "red" :width 3 :lineCap "butt"}) :zIndex 2}) (when highlight? (ol.style.Style. #js {:geometry center :image (ol.style.Circle. #js {:stroke (ol.style.Stroke. #js {:color "green" :width 3}) :radius 15})}))])))) (defn asset-or-component "Show line or circle for asset/component." [^ol.render.Feature feature _res] (if (some->> feature .getGeometry .getType (= "Point")) #js [(ol.style.Style. #js {:image (ol.style.Circle. #js {:stroke (ol.style.Stroke. #js {:color "red" :width 2}) :radius 10})}) (ol.style.Style. #js {:image (ol.style.Circle. #js {:fill (ol.style.Fill. #js {:color "black" :width 1}) :radius 3})})] (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "red" :width 3 }) :zIndex 3}))) (defn current-location-radius-style "Show circle radius around current location (point)" [^ol.render.Feature _feature _res] (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "blue"})})) (def region-area-style (constantly (ol.style.Style. #js {:stroke (ol.style.Stroke. #js {:color "rgba(100,100,100,0.5)" :width 2}) :fill (ol.style.Fill. #js {:cursor :pointer :color "rgba(200,200,200,0.5)"})})))
595a3050146907c88ab01f4e94660e88537dde2b266040e600745dbaa9bfc25a
sky-big/RabbitMQ
rabbit_tracing_traces.erl
The contents of this file are subject to the Mozilla Public License Version 1.1 ( the " License " ) ; you may not use this file except in %% compliance with the License. You may obtain a copy of the License %% at / %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and %% limitations under the License. %% The Original Code is RabbitMQ . %% The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . %% -module(rabbit_tracing_traces). -behaviour(gen_server). -import(rabbit_misc, [pget/2]). -export([list/0, lookup/2, create/3, stop/2, announce/3]). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -record(state, { table }). %%-------------------------------------------------------------------- %% RabbitMQ系统跟踪插件实际工作进程的启动接口 start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). %% 列出当前所有的跟踪信息 list() -> gen_server:call(?MODULE, list, infinity). 查询某一个跟踪信息 lookup(VHost, Name) -> gen_server:call(?MODULE, {lookup, VHost, Name}, infinity). %% 创建跟踪信息 create(VHost, Name, Trace) -> gen_server:call(?MODULE, {create, VHost, Name, Trace}, infinity). %% 删除跟踪信息 stop(VHost, Name) -> gen_server:call(?MODULE, {stop, VHost, Name}, infinity). %% 设置跟踪信息对应的消费进程Pid announce(VHost, Name, Pid) -> gen_server:cast(?MODULE, {announce, {VHost, Name}, Pid}). %%-------------------------------------------------------------------- %% 跟踪进程的回调初始化接口 init([]) -> {ok, #state{table = ets:new(anon, [private])}}. %% 列出当前所有的跟踪信息 handle_call(list, _From, State = #state{table = Table}) -> {reply, [augment(Trace) || {_K, Trace} <- ets:tab2list(Table)], State}; 查询某一个跟踪信息 handle_call({lookup, VHost, Name}, _From, State = #state{table = Table}) -> {reply, case ets:lookup(Table, {VHost, Name}) of [] -> not_found; [{_K, Trace}] -> augment(Trace) end, State}; %% 创建跟踪信息 handle_call({create, VHost, Name, Trace0}, _From, State = #state{table = Table}) -> 判断VHost是否已经存在于跟踪信息 Already = vhost_tracing(VHost, Table), Trace = pset(vhost, VHost, pset(name, Name, Trace0)), true = ets:insert(Table, {{VHost, Name}, Trace}), case Already of true -> ok; %% 如果VHost没有开启跟踪,则在此处开启跟踪 false -> rabbit_trace:start(VHost) end, %% 启动接收跟踪信息的进程 {reply, rabbit_tracing_sup:start_child({VHost, Name}, Trace), State}; %% 删除跟踪信息 handle_call({stop, VHost, Name}, _From, State = #state{table = Table}) -> %% 将ETS里的跟踪信息删除掉 true = ets:delete(Table, {VHost, Name}), 判断VHost是否已经存在于跟踪信息 case vhost_tracing(VHost, Table) of true -> ok; %% 如果没有VHost的跟踪信息,则将该VHost的跟踪功能关闭 false -> rabbit_trace:stop(VHost) end, 关闭接收跟踪信息的进程 rabbit_tracing_sup:stop_child({VHost, Name}), {reply, ok, State}; handle_call(_Req, _From, State) -> {reply, unknown_request, State}. %% 设置跟踪信息对应的消费进程Pid handle_cast({announce, Key, Pid}, State = #state{table = Table}) -> case ets:lookup(Table, Key) of [] -> ok; [{_, Trace}] -> ets:insert(Table, {Key, pset(pid, Pid, Trace)}) end, {noreply, State}; handle_cast(_C, State) -> {noreply, State}. handle_info(_I, State) -> {noreply, State}. terminate(_, _) -> ok. code_change(_, State, _) -> {ok, State}. %%-------------------------------------------------------------------- pset(Key, Value, List) -> [{Key, Value} | proplists:delete(Key, List)]. 判断VHost是否已经存在于跟踪信息 vhost_tracing(VHost, Table) -> case [true || {{V, _}, _} <- ets:tab2list(Table), V =:= VHost] of [] -> false; _ -> true end. augment(Trace) -> Pid = pget(pid, Trace), Trace1 = lists:keydelete(pid, 1, Trace), case Pid of undefined -> Trace1; _ -> rabbit_tracing_consumer:info_all(Pid) ++ Trace1 end.
null
https://raw.githubusercontent.com/sky-big/RabbitMQ/d7a773e11f93fcde4497c764c9fa185aad049ce2/plugins-src/rabbitmq-tracing/src/rabbit_tracing_traces.erl
erlang
compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. -------------------------------------------------------------------- RabbitMQ系统跟踪插件实际工作进程的启动接口 列出当前所有的跟踪信息 创建跟踪信息 删除跟踪信息 设置跟踪信息对应的消费进程Pid -------------------------------------------------------------------- 跟踪进程的回调初始化接口 列出当前所有的跟踪信息 创建跟踪信息 如果VHost没有开启跟踪,则在此处开启跟踪 启动接收跟踪信息的进程 删除跟踪信息 将ETS里的跟踪信息删除掉 如果没有VHost的跟踪信息,则将该VHost的跟踪功能关闭 设置跟踪信息对应的消费进程Pid --------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License Version 1.1 ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " The Original Code is RabbitMQ . The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . -module(rabbit_tracing_traces). -behaviour(gen_server). -import(rabbit_misc, [pget/2]). -export([list/0, lookup/2, create/3, stop/2, announce/3]). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -record(state, { table }). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). list() -> gen_server:call(?MODULE, list, infinity). 查询某一个跟踪信息 lookup(VHost, Name) -> gen_server:call(?MODULE, {lookup, VHost, Name}, infinity). create(VHost, Name, Trace) -> gen_server:call(?MODULE, {create, VHost, Name, Trace}, infinity). stop(VHost, Name) -> gen_server:call(?MODULE, {stop, VHost, Name}, infinity). announce(VHost, Name, Pid) -> gen_server:cast(?MODULE, {announce, {VHost, Name}, Pid}). init([]) -> {ok, #state{table = ets:new(anon, [private])}}. handle_call(list, _From, State = #state{table = Table}) -> {reply, [augment(Trace) || {_K, Trace} <- ets:tab2list(Table)], State}; 查询某一个跟踪信息 handle_call({lookup, VHost, Name}, _From, State = #state{table = Table}) -> {reply, case ets:lookup(Table, {VHost, Name}) of [] -> not_found; [{_K, Trace}] -> augment(Trace) end, State}; handle_call({create, VHost, Name, Trace0}, _From, State = #state{table = Table}) -> 判断VHost是否已经存在于跟踪信息 Already = vhost_tracing(VHost, Table), Trace = pset(vhost, VHost, pset(name, Name, Trace0)), true = ets:insert(Table, {{VHost, Name}, Trace}), case Already of true -> ok; false -> rabbit_trace:start(VHost) end, {reply, rabbit_tracing_sup:start_child({VHost, Name}, Trace), State}; handle_call({stop, VHost, Name}, _From, State = #state{table = Table}) -> true = ets:delete(Table, {VHost, Name}), 判断VHost是否已经存在于跟踪信息 case vhost_tracing(VHost, Table) of true -> ok; false -> rabbit_trace:stop(VHost) end, 关闭接收跟踪信息的进程 rabbit_tracing_sup:stop_child({VHost, Name}), {reply, ok, State}; handle_call(_Req, _From, State) -> {reply, unknown_request, State}. handle_cast({announce, Key, Pid}, State = #state{table = Table}) -> case ets:lookup(Table, Key) of [] -> ok; [{_, Trace}] -> ets:insert(Table, {Key, pset(pid, Pid, Trace)}) end, {noreply, State}; handle_cast(_C, State) -> {noreply, State}. handle_info(_I, State) -> {noreply, State}. terminate(_, _) -> ok. code_change(_, State, _) -> {ok, State}. pset(Key, Value, List) -> [{Key, Value} | proplists:delete(Key, List)]. 判断VHost是否已经存在于跟踪信息 vhost_tracing(VHost, Table) -> case [true || {{V, _}, _} <- ets:tab2list(Table), V =:= VHost] of [] -> false; _ -> true end. augment(Trace) -> Pid = pget(pid, Trace), Trace1 = lists:keydelete(pid, 1, Trace), case Pid of undefined -> Trace1; _ -> rabbit_tracing_consumer:info_all(Pid) ++ Trace1 end.
f0afa5b844a129ca715bc61a37fe789ce15d754ace79f806329dc3966c7d2563
ocaml/oasis
OASISHostPath.mli
(******************************************************************************) OASIS : architecture for building OCaml libraries and applications (* *) Copyright ( C ) 2011 - 2016 , Copyright ( C ) 2008 - 2011 , OCamlCore SARL (* *) (* This library is free software; you can redistribute it and/or modify it *) (* under the terms of the GNU Lesser General Public License as published by *) the Free Software Foundation ; either version 2.1 of the License , or ( at (* your option) any later version, with the OCaml static compilation *) (* exception. *) (* *) (* This library is distributed in the hope that it will be useful, but *) (* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *) (* or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more *) (* details. *) (* *) You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA (******************************************************************************) * Manipulate host filenames @author @author Sylvain Le Gall *) open OASISTypes (** Create a filename out of its components. *) val make: host_filename list -> host_filename (** Convert a unix filename into host filename. *) val of_unix: unix_filename -> host_filename (** Convert a host filename into a unix filename. {b Not exported} *) val to_unix: host_filename -> unix_filename (** Compare host filename. {b Not exported} *) val compare: host_filename -> host_filename -> int (** See {!OASISUnixPath.add_extension}. {b Not exported} *) val add_extension: host_filename -> string -> host_filename (** Map for host filename. {b Not exported.} *) module Map: OASISUtils.MapExt.S with type key = host_filename
null
https://raw.githubusercontent.com/ocaml/oasis/3d1a9421db92a0882ebc58c5df219b18c1e5681d/src/oasis/OASISHostPath.mli
ocaml
**************************************************************************** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by your option) any later version, with the OCaml static compilation exception. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more details. **************************************************************************** * Create a filename out of its components. * Convert a unix filename into host filename. * Convert a host filename into a unix filename. {b Not exported} * Compare host filename. {b Not exported} * See {!OASISUnixPath.add_extension}. {b Not exported} * Map for host filename. {b Not exported.}
OASIS : architecture for building OCaml libraries and applications Copyright ( C ) 2011 - 2016 , Copyright ( C ) 2008 - 2011 , OCamlCore SARL the Free Software Foundation ; either version 2.1 of the License , or ( at You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA * Manipulate host filenames @author @author Sylvain Le Gall *) open OASISTypes val make: host_filename list -> host_filename val of_unix: unix_filename -> host_filename val to_unix: host_filename -> unix_filename val compare: host_filename -> host_filename -> int val add_extension: host_filename -> string -> host_filename module Map: OASISUtils.MapExt.S with type key = host_filename
72c55397520ce3158f57abed2da160c25dc5f58aee8692d94ba4d813dc052b98
ucsd-progsys/nate
liveness.ml
(***********************************************************************) (* *) (* 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 : , v 1.15 2007/01/29 12:10:50 xleroy Exp $ Liveness analysis . Annotate mach code with the set of regs live at each point . Annotate mach code with the set of regs live at each point. *) open Mach let live_at_exit = ref [] let find_live_at_exit k = try List.assoc k !live_at_exit with | Not_found -> Misc.fatal_error "Spill.find_live_at_exit" let live_at_break = ref Reg.Set.empty let live_at_raise = ref Reg.Set.empty let rec live i finally = (* finally is the set of registers live after execution of the instruction sequence. The result of the function is the set of registers live just before the instruction sequence. The instruction i is annotated by the set of registers live across the instruction. *) match i.desc with Iend -> i.live <- finally; finally | Ireturn | Iop(Itailcall_ind) | Iop(Itailcall_imm _) -> (* i.live remains empty since no regs are live across *) Reg.set_of_array i.arg | Iifthenelse(test, ifso, ifnot) -> let at_join = live i.next finally in let at_fork = Reg.Set.union (live ifso at_join) (live ifnot at_join) in i.live <- at_fork; Reg.add_set_array at_fork i.arg | Iswitch(index, cases) -> let at_join = live i.next finally in let at_fork = ref Reg.Set.empty in for i = 0 to Array.length cases - 1 do at_fork := Reg.Set.union !at_fork (live cases.(i) at_join) done; i.live <- !at_fork; Reg.add_set_array !at_fork i.arg | Iloop(body) -> let at_top = ref Reg.Set.empty in (* Yes, there are better algorithms, but we'll just iterate till reaching a fixpoint. *) begin try while true do let new_at_top = Reg.Set.union !at_top (live body !at_top) in if Reg.Set.equal !at_top new_at_top then raise Exit; at_top := new_at_top done with Exit -> () end; i.live <- !at_top; !at_top | Icatch(nfail, body, handler) -> let at_join = live i.next finally in let before_handler = live handler at_join in let before_body = live_at_exit := (nfail,before_handler) :: !live_at_exit ; let before_body = live body at_join in live_at_exit := List.tl !live_at_exit ; before_body in i.live <- before_body; before_body | Iexit nfail -> let this_live = find_live_at_exit nfail in i.live <- this_live ; this_live | Itrywith(body, handler) -> let at_join = live i.next finally in let before_handler = live handler at_join in let saved_live_at_raise = !live_at_raise in live_at_raise := Reg.Set.remove Proc.loc_exn_bucket before_handler; let before_body = live body at_join in live_at_raise := saved_live_at_raise; i.live <- before_body; before_body | Iraise -> (* i.live remains empty since no regs are live across *) Reg.add_set_array !live_at_raise i.arg | _ -> let across_after = Reg.diff_set_array (live i.next finally) i.res in let across = match i.desc with Iop Icall_ind | Iop(Icall_imm _) | Iop(Iextcall _) | Iop(Iintop Icheckbound) | Iop(Iintop_imm(Icheckbound, _)) -> The function call may raise an exception , branching to the nearest enclosing try ... with . Similarly for bounds checks . Hence , everything that must be live at the beginning of the exception handler must also be live across this instr . nearest enclosing try ... with. Similarly for bounds checks. Hence, everything that must be live at the beginning of the exception handler must also be live across this instr. *) Reg.Set.union across_after !live_at_raise | _ -> across_after in i.live <- across; Reg.add_set_array across i.arg let fundecl ppf f = let initially_live = live f.fun_body Reg.Set.empty in (* Sanity check: only function parameters can be live at entrypoint *) let wrong_live = Reg.Set.diff initially_live (Reg.set_of_array f.fun_args) in if not (Reg.Set.is_empty wrong_live) then begin Format.fprintf ppf "%a@." Printmach.regset wrong_live; Misc.fatal_error "Liveness.fundecl" end
null
https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/asmcomp/liveness.ml
ocaml
********************************************************************* Objective Caml ********************************************************************* finally is the set of registers live after execution of the instruction sequence. The result of the function is the set of registers live just before the instruction sequence. The instruction i is annotated by the set of registers live across the instruction. i.live remains empty since no regs are live across Yes, there are better algorithms, but we'll just iterate till reaching a fixpoint. i.live remains empty since no regs are live across Sanity check: only function parameters can be live at entrypoint
, 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 : , v 1.15 2007/01/29 12:10:50 xleroy Exp $ Liveness analysis . Annotate mach code with the set of regs live at each point . Annotate mach code with the set of regs live at each point. *) open Mach let live_at_exit = ref [] let find_live_at_exit k = try List.assoc k !live_at_exit with | Not_found -> Misc.fatal_error "Spill.find_live_at_exit" let live_at_break = ref Reg.Set.empty let live_at_raise = ref Reg.Set.empty let rec live i finally = match i.desc with Iend -> i.live <- finally; finally | Ireturn | Iop(Itailcall_ind) | Iop(Itailcall_imm _) -> Reg.set_of_array i.arg | Iifthenelse(test, ifso, ifnot) -> let at_join = live i.next finally in let at_fork = Reg.Set.union (live ifso at_join) (live ifnot at_join) in i.live <- at_fork; Reg.add_set_array at_fork i.arg | Iswitch(index, cases) -> let at_join = live i.next finally in let at_fork = ref Reg.Set.empty in for i = 0 to Array.length cases - 1 do at_fork := Reg.Set.union !at_fork (live cases.(i) at_join) done; i.live <- !at_fork; Reg.add_set_array !at_fork i.arg | Iloop(body) -> let at_top = ref Reg.Set.empty in begin try while true do let new_at_top = Reg.Set.union !at_top (live body !at_top) in if Reg.Set.equal !at_top new_at_top then raise Exit; at_top := new_at_top done with Exit -> () end; i.live <- !at_top; !at_top | Icatch(nfail, body, handler) -> let at_join = live i.next finally in let before_handler = live handler at_join in let before_body = live_at_exit := (nfail,before_handler) :: !live_at_exit ; let before_body = live body at_join in live_at_exit := List.tl !live_at_exit ; before_body in i.live <- before_body; before_body | Iexit nfail -> let this_live = find_live_at_exit nfail in i.live <- this_live ; this_live | Itrywith(body, handler) -> let at_join = live i.next finally in let before_handler = live handler at_join in let saved_live_at_raise = !live_at_raise in live_at_raise := Reg.Set.remove Proc.loc_exn_bucket before_handler; let before_body = live body at_join in live_at_raise := saved_live_at_raise; i.live <- before_body; before_body | Iraise -> Reg.add_set_array !live_at_raise i.arg | _ -> let across_after = Reg.diff_set_array (live i.next finally) i.res in let across = match i.desc with Iop Icall_ind | Iop(Icall_imm _) | Iop(Iextcall _) | Iop(Iintop Icheckbound) | Iop(Iintop_imm(Icheckbound, _)) -> The function call may raise an exception , branching to the nearest enclosing try ... with . Similarly for bounds checks . Hence , everything that must be live at the beginning of the exception handler must also be live across this instr . nearest enclosing try ... with. Similarly for bounds checks. Hence, everything that must be live at the beginning of the exception handler must also be live across this instr. *) Reg.Set.union across_after !live_at_raise | _ -> across_after in i.live <- across; Reg.add_set_array across i.arg let fundecl ppf f = let initially_live = live f.fun_body Reg.Set.empty in let wrong_live = Reg.Set.diff initially_live (Reg.set_of_array f.fun_args) in if not (Reg.Set.is_empty wrong_live) then begin Format.fprintf ppf "%a@." Printmach.regset wrong_live; Misc.fatal_error "Liveness.fundecl" end
e5308d9e54b63b0ac2e71970059fe207a83e198b138555a03cc427a27f2280e3
janestreet/bonsai
compose_message.mli
open! Core open! Async_kernel open! Bonsai_web val component : send_message:(string -> unit Effect.t) Value.t -> Vdom.Node.t Computation.t
null
https://raw.githubusercontent.com/janestreet/bonsai/4baeedc75bf73a0915e04dc02d8a49b78779e9b0/examples/rpc_chat/client/src/compose_message.mli
ocaml
open! Core open! Async_kernel open! Bonsai_web val component : send_message:(string -> unit Effect.t) Value.t -> Vdom.Node.t Computation.t
41d362c8aeaa587db93af4ba4d4a5f46b9f0fc1ce57ad657024213a25ad03007
screenshotbot/screenshotbot-oss
test-access-checks.lisp
;;;; Copyright 2018-Present Modern Interpreters Inc. ;;;; 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 /. (uiop:define-package :screenshotbot/github/test-access-checks (:use #:cl #:fiveam #:screenshotbot/github/access-checks #:screenshotbot/user-api) (:import-from #:screenshotbot/github/access-checks #:get-repo-id #:get-repo-stars #:repo-string-identifier) (:import-from #:util/mock-recording #:track #:with-recording) (:import-from #:cl-mock #:answer) (:import-from #:screenshotbot/git-repo #:public-repo-p) (:import-from #:screenshotbot/secret #:secret)) (in-package :screenshotbot/github/test-access-checks) (util/fiveam:def-suite) #-sbcl ;; java (test simple-creation (finishes (github-client))) (test github-repo-commit-link (is (equal "" (commit-link (make-instance 'github-repo :link "") "abcd12"))) (is (equal "" (commit-link (make-instance 'github-repo :link "") "abcd12"))) (is (equal "" (commit-link (make-instance 'github-repo :link ":tdrhq/web") "abcd12"))) (is (equal "" (commit-link (make-instance 'github-repo :link ":tdrhq/web.git") "abcd12")))) (test repo-string-identifier (is (equal "tdrhq/fast-example" (repo-string-identifier "-example"))) (is (equal "tdrhq/fast-example" (repo-string-identifier ":tdrhq/fast-example"))) (is (equal "tdrhq/fast-example" (repo-string-identifier ":tdrhq/fast-example.git")))) (test get-repo-stars () (with-recording ((asdf:system-relative-pathname :screenshotbot "github/fixture/get-repo-stars.rec")) (track 'github-api-request :skip-args '(2)) (is (equal (list 42 2) (multiple-value-list (get-repo-stars "tdrhq" "slite")))))) (test public-repo-p (cl-mock:with-mocks () (answer (secret :github-api-secret) "secret") (answer (get-repo-stars "foo" "bar") 20) (is-true (public-repo-p (make-instance 'github-repo :link ":foo/bar"))))) (test public-repo-not-public (cl-mock:with-mocks () (answer (secret :github-api-secret) "secret") (answer (get-repo-stars "foo" "bar") nil) (is-false (public-repo-p (make-instance 'github-repo :link ":foo/bar")))))
null
https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/f798e99c634c65cc90097cd17c31ed493fe4f3c2/src/screenshotbot/github/test-access-checks.lisp
lisp
Copyright 2018-Present Modern Interpreters Inc. java
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 /. (uiop:define-package :screenshotbot/github/test-access-checks (:use #:cl #:fiveam #:screenshotbot/github/access-checks #:screenshotbot/user-api) (:import-from #:screenshotbot/github/access-checks #:get-repo-id #:get-repo-stars #:repo-string-identifier) (:import-from #:util/mock-recording #:track #:with-recording) (:import-from #:cl-mock #:answer) (:import-from #:screenshotbot/git-repo #:public-repo-p) (:import-from #:screenshotbot/secret #:secret)) (in-package :screenshotbot/github/test-access-checks) (util/fiveam:def-suite) (test simple-creation (finishes (github-client))) (test github-repo-commit-link (is (equal "" (commit-link (make-instance 'github-repo :link "") "abcd12"))) (is (equal "" (commit-link (make-instance 'github-repo :link "") "abcd12"))) (is (equal "" (commit-link (make-instance 'github-repo :link ":tdrhq/web") "abcd12"))) (is (equal "" (commit-link (make-instance 'github-repo :link ":tdrhq/web.git") "abcd12")))) (test repo-string-identifier (is (equal "tdrhq/fast-example" (repo-string-identifier "-example"))) (is (equal "tdrhq/fast-example" (repo-string-identifier ":tdrhq/fast-example"))) (is (equal "tdrhq/fast-example" (repo-string-identifier ":tdrhq/fast-example.git")))) (test get-repo-stars () (with-recording ((asdf:system-relative-pathname :screenshotbot "github/fixture/get-repo-stars.rec")) (track 'github-api-request :skip-args '(2)) (is (equal (list 42 2) (multiple-value-list (get-repo-stars "tdrhq" "slite")))))) (test public-repo-p (cl-mock:with-mocks () (answer (secret :github-api-secret) "secret") (answer (get-repo-stars "foo" "bar") 20) (is-true (public-repo-p (make-instance 'github-repo :link ":foo/bar"))))) (test public-repo-not-public (cl-mock:with-mocks () (answer (secret :github-api-secret) "secret") (answer (get-repo-stars "foo" "bar") nil) (is-false (public-repo-p (make-instance 'github-repo :link ":foo/bar")))))
c5e2571ec9755873d8969235e6c71fd460480b0a1dc8aaf576987d443a85edf0
wireapp/wire-server
RichField_user.hs
-- This file is part of the Wire Server implementation. -- Copyright ( C ) 2022 Wire Swiss GmbH < > -- -- 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 </>. module Test.Wire.API.Golden.Generated.RichField_user where import Wire.API.User.RichInfo (RichField (..)) testObject_RichField_user_1 :: RichField testObject_RichField_user_1 = RichField { richFieldType = "2w\ESC\NUL\SUB\158jCn\1011989Wd\1096605", richFieldValue = "\1021059E9Y|\1096050\1028618\168177q'\DLE\1047025[J4Nm\v}^\999599Lv\1024539\&8s\SUBr>." } testObject_RichField_user_2 :: RichField testObject_RichField_user_2 = RichField { richFieldType = "04,\159195pPSFaJak|O\23252k", richFieldValue = ".3jc\21079[^\USgB`p\"\176758zlj\186442\STX\rJOf\2296a" } testObject_RichField_user_3 :: RichField testObject_RichField_user_3 = RichField { richFieldType = "\161641^\167485M\38850\1491\fE^\174329M\156881C", richFieldValue = "%\170207\1032998f=&nM\30236M$@jVP\US\CAN\SI\1102832z\1075590\188083\&3&/Ik\50045W\EM" } testObject_RichField_user_4 :: RichField testObject_RichField_user_4 = RichField {richFieldType = "+", richFieldValue = "\19926\&5"} testObject_RichField_user_5 :: RichField testObject_RichField_user_5 = RichField {richFieldType = ">\1112141a/I", richFieldValue = "\ESC\rz*?\\\1052498D"} testObject_RichField_user_6 :: RichField testObject_RichField_user_6 = RichField { richFieldType = "_B>)Y\DELQ\DELPt|Y\SOH\59840']F\178483qd$ \990736?\b:z\15823\159685", richFieldValue = "\45352\ESC~\DC2)\1028365\SOC5\1034811\US\1085824\NUL\1057752\NAKpEK\"\DC1y\1009608TwV" } testObject_RichField_user_7 :: RichField testObject_RichField_user_7 = RichField {richFieldType = "\1027499\DC17\178533c:s\1097082\&4xN", richFieldValue = "6\ESCp\\hR\164986=\DC1\1049382"} testObject_RichField_user_8 :: RichField testObject_RichField_user_8 = RichField {richFieldType = "1\NUL\999579I\NULJm\1102770\ACK", richFieldValue = "YYF\DC2\1003144\ve/9z(\1008562"} testObject_RichField_user_9 :: RichField testObject_RichField_user_9 = RichField {richFieldType = "D\EOT\\o", richFieldValue = "iJ%\DLE\nfrM'\170474"} testObject_RichField_user_10 :: RichField testObject_RichField_user_10 = RichField { richFieldType = "\7618/>\1003544M\1107526X\SOH!]", richFieldValue = "\35278n&T\DC1N\159606*\RSPhM$\DC2\1108610\12636&sj}\142308" } testObject_RichField_user_11 :: RichField testObject_RichField_user_11 = RichField { richFieldType = "I\1024694\r\1082061\&6\1049288.[\1028722\&8\995398h\151609X\DC2\175361\984286O\64131^U\1053161\RS\SI0v\SOHLQ~", richFieldValue = "x\19030" } testObject_RichField_user_12 :: RichField testObject_RichField_user_12 = RichField { richFieldType = "C\DC4=r\1113151\1028918\v\DLE\NUL\tF\DC1:\154369A'+", richFieldValue = "\44420\&9@\n\1014140\ETB\DLE[\50536d\8516jnB\77871f}" } testObject_RichField_user_13 :: RichField testObject_RichField_user_13 = RichField { richFieldType = "`", richFieldValue = "\161649F\1089849\DLEg\2459Rol\n\CAN6\1046898'\t\1081650\FSlTT\"\ENQ\176762" } testObject_RichField_user_14 :: RichField testObject_RichField_user_14 = RichField { richFieldType = "M\1001275\ETX)I\SO", richFieldValue = "&\176108\ETXTc\1086645\SIw\21351\ETB\142444\&5&_\DEL_;&" } testObject_RichField_user_15 :: RichField testObject_RichField_user_15 = RichField {richFieldType = "j\STXd.h7oc6%\1060914#\GS%\1101520\nz", richFieldValue = "\CAN4w<U\GSB4AM\99187\t\30048"} testObject_RichField_user_16 :: RichField testObject_RichField_user_16 = RichField {richFieldType = "\r", richFieldValue = "\EM$\DC3$\1037458\ESC\SYNp\US\NAK\1048510\awW\141341vHN\SOP"} testObject_RichField_user_17 :: RichField testObject_RichField_user_17 = RichField {richFieldType = "uM\ETX\ACKN\992044", richFieldValue = "T\STX&:3f{\r9/\ETX\DC3\1036871\FS\FS"} testObject_RichField_user_18 :: RichField testObject_RichField_user_18 = RichField { richFieldType = "\160220x\44056\145399\DEL$%\SUB\1097474o\1030668\160528(H`\171983N\92619TjM!{$\14221t\51624}", richFieldValue = "\1102997\ACKZS\1076446\b\1021342\DC2D" } testObject_RichField_user_19 :: RichField testObject_RichField_user_19 = RichField { richFieldType = "(SN\a}L\96657\7999k\ETB", richFieldValue = "\1013177qZj6\26309)2\ETXC<\1094906\&7\1068146\988335=$21m J" } testObject_RichField_user_20 :: RichField testObject_RichField_user_20 = RichField { richFieldType = "O", richFieldValue = "}(=z0w\178979\150294c\125085\US9K\DC4:\SI\994480\988265?\vN) 1\1052831_2 " }
null
https://raw.githubusercontent.com/wireapp/wire-server/c428355b7683b7b7722ea544eba314fc843ad8fa/libs/wire-api/test/golden/Test/Wire/API/Golden/Generated/RichField_user.hs
haskell
This file is part of the Wire Server implementation. This program is free software: you can redistribute it and/or modify it under 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. with this program. If not, see </>.
Copyright ( C ) 2022 Wire Swiss GmbH < > 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 You should have received a copy of the GNU Affero General Public License along module Test.Wire.API.Golden.Generated.RichField_user where import Wire.API.User.RichInfo (RichField (..)) testObject_RichField_user_1 :: RichField testObject_RichField_user_1 = RichField { richFieldType = "2w\ESC\NUL\SUB\158jCn\1011989Wd\1096605", richFieldValue = "\1021059E9Y|\1096050\1028618\168177q'\DLE\1047025[J4Nm\v}^\999599Lv\1024539\&8s\SUBr>." } testObject_RichField_user_2 :: RichField testObject_RichField_user_2 = RichField { richFieldType = "04,\159195pPSFaJak|O\23252k", richFieldValue = ".3jc\21079[^\USgB`p\"\176758zlj\186442\STX\rJOf\2296a" } testObject_RichField_user_3 :: RichField testObject_RichField_user_3 = RichField { richFieldType = "\161641^\167485M\38850\1491\fE^\174329M\156881C", richFieldValue = "%\170207\1032998f=&nM\30236M$@jVP\US\CAN\SI\1102832z\1075590\188083\&3&/Ik\50045W\EM" } testObject_RichField_user_4 :: RichField testObject_RichField_user_4 = RichField {richFieldType = "+", richFieldValue = "\19926\&5"} testObject_RichField_user_5 :: RichField testObject_RichField_user_5 = RichField {richFieldType = ">\1112141a/I", richFieldValue = "\ESC\rz*?\\\1052498D"} testObject_RichField_user_6 :: RichField testObject_RichField_user_6 = RichField { richFieldType = "_B>)Y\DELQ\DELPt|Y\SOH\59840']F\178483qd$ \990736?\b:z\15823\159685", richFieldValue = "\45352\ESC~\DC2)\1028365\SOC5\1034811\US\1085824\NUL\1057752\NAKpEK\"\DC1y\1009608TwV" } testObject_RichField_user_7 :: RichField testObject_RichField_user_7 = RichField {richFieldType = "\1027499\DC17\178533c:s\1097082\&4xN", richFieldValue = "6\ESCp\\hR\164986=\DC1\1049382"} testObject_RichField_user_8 :: RichField testObject_RichField_user_8 = RichField {richFieldType = "1\NUL\999579I\NULJm\1102770\ACK", richFieldValue = "YYF\DC2\1003144\ve/9z(\1008562"} testObject_RichField_user_9 :: RichField testObject_RichField_user_9 = RichField {richFieldType = "D\EOT\\o", richFieldValue = "iJ%\DLE\nfrM'\170474"} testObject_RichField_user_10 :: RichField testObject_RichField_user_10 = RichField { richFieldType = "\7618/>\1003544M\1107526X\SOH!]", richFieldValue = "\35278n&T\DC1N\159606*\RSPhM$\DC2\1108610\12636&sj}\142308" } testObject_RichField_user_11 :: RichField testObject_RichField_user_11 = RichField { richFieldType = "I\1024694\r\1082061\&6\1049288.[\1028722\&8\995398h\151609X\DC2\175361\984286O\64131^U\1053161\RS\SI0v\SOHLQ~", richFieldValue = "x\19030" } testObject_RichField_user_12 :: RichField testObject_RichField_user_12 = RichField { richFieldType = "C\DC4=r\1113151\1028918\v\DLE\NUL\tF\DC1:\154369A'+", richFieldValue = "\44420\&9@\n\1014140\ETB\DLE[\50536d\8516jnB\77871f}" } testObject_RichField_user_13 :: RichField testObject_RichField_user_13 = RichField { richFieldType = "`", richFieldValue = "\161649F\1089849\DLEg\2459Rol\n\CAN6\1046898'\t\1081650\FSlTT\"\ENQ\176762" } testObject_RichField_user_14 :: RichField testObject_RichField_user_14 = RichField { richFieldType = "M\1001275\ETX)I\SO", richFieldValue = "&\176108\ETXTc\1086645\SIw\21351\ETB\142444\&5&_\DEL_;&" } testObject_RichField_user_15 :: RichField testObject_RichField_user_15 = RichField {richFieldType = "j\STXd.h7oc6%\1060914#\GS%\1101520\nz", richFieldValue = "\CAN4w<U\GSB4AM\99187\t\30048"} testObject_RichField_user_16 :: RichField testObject_RichField_user_16 = RichField {richFieldType = "\r", richFieldValue = "\EM$\DC3$\1037458\ESC\SYNp\US\NAK\1048510\awW\141341vHN\SOP"} testObject_RichField_user_17 :: RichField testObject_RichField_user_17 = RichField {richFieldType = "uM\ETX\ACKN\992044", richFieldValue = "T\STX&:3f{\r9/\ETX\DC3\1036871\FS\FS"} testObject_RichField_user_18 :: RichField testObject_RichField_user_18 = RichField { richFieldType = "\160220x\44056\145399\DEL$%\SUB\1097474o\1030668\160528(H`\171983N\92619TjM!{$\14221t\51624}", richFieldValue = "\1102997\ACKZS\1076446\b\1021342\DC2D" } testObject_RichField_user_19 :: RichField testObject_RichField_user_19 = RichField { richFieldType = "(SN\a}L\96657\7999k\ETB", richFieldValue = "\1013177qZj6\26309)2\ETXC<\1094906\&7\1068146\988335=$21m J" } testObject_RichField_user_20 :: RichField testObject_RichField_user_20 = RichField { richFieldType = "O", richFieldValue = "}(=z0w\178979\150294c\125085\US9K\DC4:\SI\994480\988265?\vN) 1\1052831_2 " }
465b375a2a37a9b47444cde4c9edbc10ea18428a7709cbfce542c5e2949e11f8
RichiH/git-annex
SimpleProtocol.hs
Simple line - based protocols . - - Copyright 2013 - 2016 < > - - License : BSD-2 - clause - - Copyright 2013-2016 Joey Hess <> - - License: BSD-2-clause -} # LANGUAGE FlexibleInstances # # OPTIONS_GHC -fno - warn - orphans # module Utility.SimpleProtocol ( Sendable(..), Receivable(..), parseMessage, Serializable(..), Parser, parseFail, parse0, parse1, parse2, parse3, dupIoHandles, getProtocolLine, ) where import Data.Char import GHC.IO.Handle import System.Exit (ExitCode(..)) import Common -- Messages that can be sent. class Sendable m where formatMessage :: m -> [String] -- Messages that can be received. class Receivable m where Passed the first word of the message , returns a Parser that can be be fed the rest of the message to generate -- the value. parseCommand :: String -> Parser m parseMessage :: (Receivable m) => String -> Maybe m parseMessage s = parseCommand command rest where (command, rest) = splitWord s class Serializable a where serialize :: a -> String deserialize :: String -> Maybe a instance Serializable [Char] where serialize = id deserialize = Just instance Serializable ExitCode where serialize ExitSuccess = "0" serialize (ExitFailure n) = show n deserialize "0" = Just ExitSuccess deserialize s = ExitFailure <$> readish s {- Parsing the parameters of messages. Using the right parseN ensures - that the string is split into exactly the requested number of words, - which allows the last parameter of a message to contain arbitrary - whitespace, etc, without needing any special quoting. -} type Parser a = String -> Maybe a parseFail :: Parser a parseFail _ = Nothing parse0 :: a -> Parser a parse0 mk "" = Just mk parse0 _ _ = Nothing parse1 :: Serializable p1 => (p1 -> a) -> Parser a parse1 mk p1 = mk <$> deserialize p1 parse2 :: (Serializable p1, Serializable p2) => (p1 -> p2 -> a) -> Parser a parse2 mk s = mk <$> deserialize p1 <*> deserialize p2 where (p1, p2) = splitWord s parse3 :: (Serializable p1, Serializable p2, Serializable p3) => (p1 -> p2 -> p3 -> a) -> Parser a parse3 mk s = mk <$> deserialize p1 <*> deserialize p2 <*> deserialize p3 where (p1, rest) = splitWord s (p2, p3) = splitWord rest splitWord :: String -> (String, String) splitWord = separate isSpace When a program speaks a simple protocol over stdio , any other output - to stdout ( or anything that attempts to read from stdin ) - will mess up the protocol . To avoid that , close stdin , - and duplicate stderr to stdout . Return two new handles - that are duplicates of the original ( stdin , stdout ) . - to stdout (or anything that attempts to read from stdin) - will mess up the protocol. To avoid that, close stdin, - and duplicate stderr to stdout. Return two new handles - that are duplicates of the original (stdin, stdout). -} dupIoHandles :: IO (Handle, Handle) dupIoHandles = do readh <- hDuplicate stdin writeh <- hDuplicate stdout nullh <- openFile devNull ReadMode nullh `hDuplicateTo` stdin stderr `hDuplicateTo` stdout return (readh, writeh) Reads a line , but to avoid super - long lines eating memory , returns - Nothing if 32 kb have been read without seeing a ' \n ' - - If there is a ' \r ' before the ' \n ' , it is removed , to support - systems using " \r\n " at ends of lines - - This implementation is not super efficient , but as long as the Handle - supports buffering , it avoids reading a character at a time at the - syscall level . - Nothing if 32 kb have been read without seeing a '\n' - - If there is a '\r' before the '\n', it is removed, to support - systems using "\r\n" at ends of lines - - This implementation is not super efficient, but as long as the Handle - supports buffering, it avoids reading a character at a time at the - syscall level. -} getProtocolLine :: Handle -> IO (Maybe String) getProtocolLine h = go (32768 :: Int) [] where go 0 _ = return Nothing go n l = do c <- hGetChar h if c == '\n' then return $ Just $ reverse $ case l of ('\r':rest) -> rest _ -> l else go (n-1) (c:l)
null
https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Utility/SimpleProtocol.hs
haskell
Messages that can be sent. Messages that can be received. the value. Parsing the parameters of messages. Using the right parseN ensures - that the string is split into exactly the requested number of words, - which allows the last parameter of a message to contain arbitrary - whitespace, etc, without needing any special quoting.
Simple line - based protocols . - - Copyright 2013 - 2016 < > - - License : BSD-2 - clause - - Copyright 2013-2016 Joey Hess <> - - License: BSD-2-clause -} # LANGUAGE FlexibleInstances # # OPTIONS_GHC -fno - warn - orphans # module Utility.SimpleProtocol ( Sendable(..), Receivable(..), parseMessage, Serializable(..), Parser, parseFail, parse0, parse1, parse2, parse3, dupIoHandles, getProtocolLine, ) where import Data.Char import GHC.IO.Handle import System.Exit (ExitCode(..)) import Common class Sendable m where formatMessage :: m -> [String] class Receivable m where Passed the first word of the message , returns a Parser that can be be fed the rest of the message to generate parseCommand :: String -> Parser m parseMessage :: (Receivable m) => String -> Maybe m parseMessage s = parseCommand command rest where (command, rest) = splitWord s class Serializable a where serialize :: a -> String deserialize :: String -> Maybe a instance Serializable [Char] where serialize = id deserialize = Just instance Serializable ExitCode where serialize ExitSuccess = "0" serialize (ExitFailure n) = show n deserialize "0" = Just ExitSuccess deserialize s = ExitFailure <$> readish s type Parser a = String -> Maybe a parseFail :: Parser a parseFail _ = Nothing parse0 :: a -> Parser a parse0 mk "" = Just mk parse0 _ _ = Nothing parse1 :: Serializable p1 => (p1 -> a) -> Parser a parse1 mk p1 = mk <$> deserialize p1 parse2 :: (Serializable p1, Serializable p2) => (p1 -> p2 -> a) -> Parser a parse2 mk s = mk <$> deserialize p1 <*> deserialize p2 where (p1, p2) = splitWord s parse3 :: (Serializable p1, Serializable p2, Serializable p3) => (p1 -> p2 -> p3 -> a) -> Parser a parse3 mk s = mk <$> deserialize p1 <*> deserialize p2 <*> deserialize p3 where (p1, rest) = splitWord s (p2, p3) = splitWord rest splitWord :: String -> (String, String) splitWord = separate isSpace When a program speaks a simple protocol over stdio , any other output - to stdout ( or anything that attempts to read from stdin ) - will mess up the protocol . To avoid that , close stdin , - and duplicate stderr to stdout . Return two new handles - that are duplicates of the original ( stdin , stdout ) . - to stdout (or anything that attempts to read from stdin) - will mess up the protocol. To avoid that, close stdin, - and duplicate stderr to stdout. Return two new handles - that are duplicates of the original (stdin, stdout). -} dupIoHandles :: IO (Handle, Handle) dupIoHandles = do readh <- hDuplicate stdin writeh <- hDuplicate stdout nullh <- openFile devNull ReadMode nullh `hDuplicateTo` stdin stderr `hDuplicateTo` stdout return (readh, writeh) Reads a line , but to avoid super - long lines eating memory , returns - Nothing if 32 kb have been read without seeing a ' \n ' - - If there is a ' \r ' before the ' \n ' , it is removed , to support - systems using " \r\n " at ends of lines - - This implementation is not super efficient , but as long as the Handle - supports buffering , it avoids reading a character at a time at the - syscall level . - Nothing if 32 kb have been read without seeing a '\n' - - If there is a '\r' before the '\n', it is removed, to support - systems using "\r\n" at ends of lines - - This implementation is not super efficient, but as long as the Handle - supports buffering, it avoids reading a character at a time at the - syscall level. -} getProtocolLine :: Handle -> IO (Maybe String) getProtocolLine h = go (32768 :: Int) [] where go 0 _ = return Nothing go n l = do c <- hGetChar h if c == '\n' then return $ Just $ reverse $ case l of ('\r':rest) -> rest _ -> l else go (n-1) (c:l)
7cae32219cafab53d01943d9f4d3b1e231d8cc133c367500abacd6900c3d6941
ocsigen/eliom
eliom_client_base.shared.ml
type ('a, 'b) server_function_service = ( unit , 'a , Eliom_service.post , Eliom_service.non_att , Eliom_service.co , Eliom_service.non_ext , Eliom_service.reg , [`WithoutSuffix] , unit , [`One of 'a Eliom_parameter.ocaml] Eliom_parameter.param_name , 'b Eliom_service.ocaml ) Eliom_service.t
null
https://raw.githubusercontent.com/ocsigen/eliom/c3e0eea5bef02e0af3942b6d27585add95d01d6c/src/lib/eliom_client_base.shared.ml
ocaml
type ('a, 'b) server_function_service = ( unit , 'a , Eliom_service.post , Eliom_service.non_att , Eliom_service.co , Eliom_service.non_ext , Eliom_service.reg , [`WithoutSuffix] , unit , [`One of 'a Eliom_parameter.ocaml] Eliom_parameter.param_name , 'b Eliom_service.ocaml ) Eliom_service.t
f7b090b657f625eca979916114fc0ebca9d2c5924963e198e1708d7ff0d685ac
OCamlPro/ez_api
ezFetch.ml
(**************************************************************************) (* *) Copyright 2018 - 2022 OCamlPro (* *) (* All rights reserved. This file is distributed under the terms of the *) GNU Lesser General Public License version 2.1 , with the special (* exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) open EzRequest open Ezjs_fetch let log ?(meth="GET") url = function | None -> () | Some msg -> Ezjs_min.log_str ("[>" ^ msg ^ " " ^ meth ^ " " ^ url ^ "]") let handle_response ?msg url f r = match r with | Error e -> f @@ Error (0, Some (Ezjs_min.to_string e##toString)) | Ok r -> log ~meth:("RECV " ^ string_of_int r.status) url msg; if !Verbose.v land 1 <> 0 then Format.printf "[ez_api] received:\n%s@." r.body; if r.status >= 200 && r.status < 300 then f @@ Ok r.body else f @@ Error (r.status, Some r.body) let make ?msg ?content ?content_type ~meth ~headers url f = log ~meth url msg; if !Verbose.v land 2 <> 0 then Format.printf "[ez_api] sent:\n%s@." (Option.value ~default:"" content); let headers = Option.fold ~none:headers ~some:(fun ct -> ("Content-Type", ct) :: headers) content_type in let body = Option.map (fun s -> RString s) content in fetch ~headers ~meth ?body url to_text (handle_response ?msg url f) module Interface = struct let get ?(meth="GET") ?(headers=[]) ?msg url f = make ?msg ~meth ~headers url f let post ?(meth="POST") ?(content_type="application/json") ?(content="{}") ?(headers=[]) ?msg url f = make ?msg ~content ~content_type ~meth ~headers url f end include Make(Interface) let () = Js_of_ocaml.Js.Unsafe.global##.set_verbose_ := Js_of_ocaml.Js.wrap_callback Verbose.set_verbose; EzDebug.log "ezFetch Loaded"
null
https://raw.githubusercontent.com/OCamlPro/ez_api/5253f7dd8936e923290aa969ee43ebd3dc6fce2d/src/request/js/fetch/ezFetch.ml
ocaml
************************************************************************ All rights reserved. This file is distributed under the terms of the exception on linking described in the file LICENSE. ************************************************************************
Copyright 2018 - 2022 OCamlPro GNU Lesser General Public License version 2.1 , with the special open EzRequest open Ezjs_fetch let log ?(meth="GET") url = function | None -> () | Some msg -> Ezjs_min.log_str ("[>" ^ msg ^ " " ^ meth ^ " " ^ url ^ "]") let handle_response ?msg url f r = match r with | Error e -> f @@ Error (0, Some (Ezjs_min.to_string e##toString)) | Ok r -> log ~meth:("RECV " ^ string_of_int r.status) url msg; if !Verbose.v land 1 <> 0 then Format.printf "[ez_api] received:\n%s@." r.body; if r.status >= 200 && r.status < 300 then f @@ Ok r.body else f @@ Error (r.status, Some r.body) let make ?msg ?content ?content_type ~meth ~headers url f = log ~meth url msg; if !Verbose.v land 2 <> 0 then Format.printf "[ez_api] sent:\n%s@." (Option.value ~default:"" content); let headers = Option.fold ~none:headers ~some:(fun ct -> ("Content-Type", ct) :: headers) content_type in let body = Option.map (fun s -> RString s) content in fetch ~headers ~meth ?body url to_text (handle_response ?msg url f) module Interface = struct let get ?(meth="GET") ?(headers=[]) ?msg url f = make ?msg ~meth ~headers url f let post ?(meth="POST") ?(content_type="application/json") ?(content="{}") ?(headers=[]) ?msg url f = make ?msg ~content ~content_type ~meth ~headers url f end include Make(Interface) let () = Js_of_ocaml.Js.Unsafe.global##.set_verbose_ := Js_of_ocaml.Js.wrap_callback Verbose.set_verbose; EzDebug.log "ezFetch Loaded"
2b03caa95d955c3776c028f21a355b4f06152dfd85cd53827f212dd31d0a62b8
mbutterick/quad
markdown.rkt
#lang debug racket/base (require racket/list racket/match quadwriter/core "tags.rkt" "lang-helper.rkt") (provide (all-defined-out) #%app #%top #%datum #%top-interaction require (all-from-out "tags.rkt")) (define (doc-proc exprs) (define strs (match exprs [(? null?) '(" ")] ; single nonbreaking space, so something prints [strs strs])) ;; markdown parser returns list of paragraphs (root null (match strs [(list str) strs] [_ (add-between strs (list para-break) #:before-first (list para-break) #:after-last (list para-break) #:splice? #true)]))) (make-module-begin doc-proc) (module reader racket/base (require racket/port markdown "lang-helper.rkt") (provide read-syntax get-info) (define get-info get-info-texty) (define read-syntax (make-read-syntax 'quadwriter/markdown (λ (path-string p) (xexpr->parse-tree (parameterize ([current-strict-markdown? #t]) (parse-markdown (port->string p))))))))
null
https://raw.githubusercontent.com/mbutterick/quad/395447f35c2fb9fc7b6199ed185850906d80811d/quadwriter/markdown.rkt
racket
single nonbreaking space, so something prints markdown parser returns list of paragraphs
#lang debug racket/base (require racket/list racket/match quadwriter/core "tags.rkt" "lang-helper.rkt") (provide (all-defined-out) #%app #%top #%datum #%top-interaction require (all-from-out "tags.rkt")) (define (doc-proc exprs) (define strs (match exprs [strs strs])) (root null (match strs [(list str) strs] [_ (add-between strs (list para-break) #:before-first (list para-break) #:after-last (list para-break) #:splice? #true)]))) (make-module-begin doc-proc) (module reader racket/base (require racket/port markdown "lang-helper.rkt") (provide read-syntax get-info) (define get-info get-info-texty) (define read-syntax (make-read-syntax 'quadwriter/markdown (λ (path-string p) (xexpr->parse-tree (parameterize ([current-strict-markdown? #t]) (parse-markdown (port->string p))))))))
2c5e5551e6cdf96346082bd59adeffea2ec69ed7d5c0f12378ec6e286063f5a2
iambrj/imin
interp-Rany-prime.rkt
#lang racket (require "interp-Rvec-prime.rkt") (require "interp-Rfun-prime.rkt") (require "interp-Rlambda-prime.rkt") (require "interp-Rany.rkt") (require "utilities.rkt") (require (prefix-in runtime-config: "runtime-config.rkt")) (provide interp-Rany-prime interp-Rany-prime-class interp-Rany-prime-mixin) (define (interp-Rany-prime-mixin super-class) (class super-class (super-new) (define/override (interp-op op) (verbose "Rany-prime/interp-op" op) (match op ['make-any (lambda (v tg) (Tagged v tg))] ['tag-of-any (match-lambda [(Tagged v^ tg) tg] [v (error 'interp-op "expected tagged value, not ~a" v)])] [else (super interp-op op)])) (define/override ((interp-exp env) e) (define recur (interp-exp env)) (verbose "Rany-prime/interp-exp" e) (match e [(ValueOf e ty) (match (recur e) [(Tagged v^ tg) v^] [v (error 'interp-op "expected tagged value, not ~a" v)])] [(Exit) (error 'interp-exp "exiting")] [else ((super interp-exp env) e)])) )) (define interp-Rany-prime-class (interp-Rany-prime-mixin (interp-Rlambda-prime-mixin (interp-Rfun-prime-mixin (interp-Rvec-prime-mixin interp-Rany-class))))) (define (interp-Rany-prime p) (send (new interp-Rany-prime-class) interp-program p))
null
https://raw.githubusercontent.com/iambrj/imin/baf9e829c2aa85b69a2e86bfba320969ddf05f95/interp-Rany-prime.rkt
racket
#lang racket (require "interp-Rvec-prime.rkt") (require "interp-Rfun-prime.rkt") (require "interp-Rlambda-prime.rkt") (require "interp-Rany.rkt") (require "utilities.rkt") (require (prefix-in runtime-config: "runtime-config.rkt")) (provide interp-Rany-prime interp-Rany-prime-class interp-Rany-prime-mixin) (define (interp-Rany-prime-mixin super-class) (class super-class (super-new) (define/override (interp-op op) (verbose "Rany-prime/interp-op" op) (match op ['make-any (lambda (v tg) (Tagged v tg))] ['tag-of-any (match-lambda [(Tagged v^ tg) tg] [v (error 'interp-op "expected tagged value, not ~a" v)])] [else (super interp-op op)])) (define/override ((interp-exp env) e) (define recur (interp-exp env)) (verbose "Rany-prime/interp-exp" e) (match e [(ValueOf e ty) (match (recur e) [(Tagged v^ tg) v^] [v (error 'interp-op "expected tagged value, not ~a" v)])] [(Exit) (error 'interp-exp "exiting")] [else ((super interp-exp env) e)])) )) (define interp-Rany-prime-class (interp-Rany-prime-mixin (interp-Rlambda-prime-mixin (interp-Rfun-prime-mixin (interp-Rvec-prime-mixin interp-Rany-class))))) (define (interp-Rany-prime p) (send (new interp-Rany-prime-class) interp-program p))
2332562a2f0c99e6667b95208a82e134218b29829aefa89eedf8478eb765f28a
weavejester/compojure
project.clj
(defproject compojure "1.7.0" :description "A concise routing library for Ring" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/tools.macro "0.1.5"] [clout "2.2.1"] [medley "1.4.0"] [ring/ring-core "1.9.5"] [ring/ring-codec "1.2.0"]] :plugins [[lein-codox "0.10.7"]] :codox {:output-path "codox" :metadata {:doc/format :markdown} :source-uri "/{version}/{filepath}#L{line}"} :aliases {"test-all" ["with-profile" "default:+1.8:+1.9:+1.10:+1.11" "test"]} :profiles {:dev {:jvm-opts ^:replace [] :dependencies [[ring/ring-mock "0.4.0"] [criterium "0.4.6"] [javax.servlet/servlet-api "2.5"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} :1.9 {:dependencies [[org.clojure/clojure "1.9.0"]]} :1.10 {:dependencies [[org.clojure/clojure "1.10.0"]]} :1.11 {:dependencies [[org.clojure/clojure "1.11.1"]]}})
null
https://raw.githubusercontent.com/weavejester/compojure/cd9536e11f24c075ec670c2abc4b0405be60c57e/project.clj
clojure
(defproject compojure "1.7.0" :description "A concise routing library for Ring" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/tools.macro "0.1.5"] [clout "2.2.1"] [medley "1.4.0"] [ring/ring-core "1.9.5"] [ring/ring-codec "1.2.0"]] :plugins [[lein-codox "0.10.7"]] :codox {:output-path "codox" :metadata {:doc/format :markdown} :source-uri "/{version}/{filepath}#L{line}"} :aliases {"test-all" ["with-profile" "default:+1.8:+1.9:+1.10:+1.11" "test"]} :profiles {:dev {:jvm-opts ^:replace [] :dependencies [[ring/ring-mock "0.4.0"] [criterium "0.4.6"] [javax.servlet/servlet-api "2.5"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} :1.9 {:dependencies [[org.clojure/clojure "1.9.0"]]} :1.10 {:dependencies [[org.clojure/clojure "1.10.0"]]} :1.11 {:dependencies [[org.clojure/clojure "1.11.1"]]}})
555cb1771bd12af71b2fa251a84d6e8a23a870bba36291d74914060c096d4ca5
Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library
SourceReceiverFlow.hs
{-# LANGUAGE MultiWayIf #-} CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . {-# LANGUAGE OverloadedStrings #-} | Contains the types generated from the schema SourceReceiverFlow module StripeAPI.Types.SourceReceiverFlow where import qualified Control.Monad.Fail import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified StripeAPI.Common import StripeAPI.TypeAlias import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe | Defines the object schema located at @components.schemas.source_receiver_flow@ in the specification . data SourceReceiverFlow = SourceReceiverFlow { -- | address: The address of the receiver source. This is the value that should be communicated to the customer to send their funds to. -- -- Constraints: -- * Maximum length of 5000 sourceReceiverFlowAddress :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), -- | amount_charged: The total amount that was moved to your balance. This is almost always equal to the amount charged. In rare cases when customers deposit excess funds and we are unable to refund those, those funds get moved to your balance and show up in amount_charged as well. The amount charged is expressed in the source\'s currency. sourceReceiverFlowAmountCharged :: GHC.Types.Int, -- | amount_received: The total amount received by the receiver source. \`amount_received = amount_returned + amount_charged\` should be true for consumed sources unless customers deposit excess funds. The amount received is expressed in the source\'s currency. sourceReceiverFlowAmountReceived :: GHC.Types.Int, -- | amount_returned: The total amount that was returned to the customer. The amount returned is expressed in the source\'s currency. sourceReceiverFlowAmountReturned :: GHC.Types.Int, | refund_attributes_method : Type of refund attribute method , one of \`email\ ` , \`manual\ ` , or \`none\ ` . -- -- Constraints: -- * Maximum length of 5000 sourceReceiverFlowRefundAttributesMethod :: Data.Text.Internal.Text, | refund_attributes_status : Type of refund attribute status , one of \`missing\ ` , \`requested\ ` , or \`available\ ` . -- -- Constraints: -- * Maximum length of 5000 sourceReceiverFlowRefundAttributesStatus :: Data.Text.Internal.Text } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON SourceReceiverFlow where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("address" Data.Aeson.Types.ToJSON..=)) (sourceReceiverFlowAddress obj) : ["amount_charged" Data.Aeson.Types.ToJSON..= sourceReceiverFlowAmountCharged obj] : ["amount_received" Data.Aeson.Types.ToJSON..= sourceReceiverFlowAmountReceived obj] : ["amount_returned" Data.Aeson.Types.ToJSON..= sourceReceiverFlowAmountReturned obj] : ["refund_attributes_method" Data.Aeson.Types.ToJSON..= sourceReceiverFlowRefundAttributesMethod obj] : ["refund_attributes_status" Data.Aeson.Types.ToJSON..= sourceReceiverFlowRefundAttributesStatus obj] : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("address" Data.Aeson.Types.ToJSON..=)) (sourceReceiverFlowAddress obj) : ["amount_charged" Data.Aeson.Types.ToJSON..= sourceReceiverFlowAmountCharged obj] : ["amount_received" Data.Aeson.Types.ToJSON..= sourceReceiverFlowAmountReceived obj] : ["amount_returned" Data.Aeson.Types.ToJSON..= sourceReceiverFlowAmountReturned obj] : ["refund_attributes_method" Data.Aeson.Types.ToJSON..= sourceReceiverFlowRefundAttributesMethod obj] : ["refund_attributes_status" Data.Aeson.Types.ToJSON..= sourceReceiverFlowRefundAttributesStatus obj] : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON SourceReceiverFlow where parseJSON = Data.Aeson.Types.FromJSON.withObject "SourceReceiverFlow" (\obj -> (((((GHC.Base.pure SourceReceiverFlow GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "address")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "amount_charged")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "amount_received")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "amount_returned")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "refund_attributes_method")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "refund_attributes_status")) -- | Create a new 'SourceReceiverFlow' with all required fields. mkSourceReceiverFlow :: -- | 'sourceReceiverFlowAmountCharged' GHC.Types.Int -> -- | 'sourceReceiverFlowAmountReceived' GHC.Types.Int -> -- | 'sourceReceiverFlowAmountReturned' GHC.Types.Int -> -- | 'sourceReceiverFlowRefundAttributesMethod' Data.Text.Internal.Text -> -- | 'sourceReceiverFlowRefundAttributesStatus' Data.Text.Internal.Text -> SourceReceiverFlow mkSourceReceiverFlow sourceReceiverFlowAmountCharged sourceReceiverFlowAmountReceived sourceReceiverFlowAmountReturned sourceReceiverFlowRefundAttributesMethod sourceReceiverFlowRefundAttributesStatus = SourceReceiverFlow { sourceReceiverFlowAddress = GHC.Maybe.Nothing, sourceReceiverFlowAmountCharged = sourceReceiverFlowAmountCharged, sourceReceiverFlowAmountReceived = sourceReceiverFlowAmountReceived, sourceReceiverFlowAmountReturned = sourceReceiverFlowAmountReturned, sourceReceiverFlowRefundAttributesMethod = sourceReceiverFlowRefundAttributesMethod, sourceReceiverFlowRefundAttributesStatus = sourceReceiverFlowRefundAttributesStatus }
null
https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Types/SourceReceiverFlow.hs
haskell
# LANGUAGE MultiWayIf # # LANGUAGE OverloadedStrings # | address: The address of the receiver source. This is the value that should be communicated to the customer to send their funds to. Constraints: | amount_charged: The total amount that was moved to your balance. This is almost always equal to the amount charged. In rare cases when customers deposit excess funds and we are unable to refund those, those funds get moved to your balance and show up in amount_charged as well. The amount charged is expressed in the source\'s currency. | amount_received: The total amount received by the receiver source. \`amount_received = amount_returned + amount_charged\` should be true for consumed sources unless customers deposit excess funds. The amount received is expressed in the source\'s currency. | amount_returned: The total amount that was returned to the customer. The amount returned is expressed in the source\'s currency. Constraints: Constraints: | Create a new 'SourceReceiverFlow' with all required fields. | 'sourceReceiverFlowAmountCharged' | 'sourceReceiverFlowAmountReceived' | 'sourceReceiverFlowAmountReturned' | 'sourceReceiverFlowRefundAttributesMethod' | 'sourceReceiverFlowRefundAttributesStatus'
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . | Contains the types generated from the schema SourceReceiverFlow module StripeAPI.Types.SourceReceiverFlow where import qualified Control.Monad.Fail import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified StripeAPI.Common import StripeAPI.TypeAlias import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe | Defines the object schema located at @components.schemas.source_receiver_flow@ in the specification . data SourceReceiverFlow = SourceReceiverFlow * Maximum length of 5000 sourceReceiverFlowAddress :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), sourceReceiverFlowAmountCharged :: GHC.Types.Int, sourceReceiverFlowAmountReceived :: GHC.Types.Int, sourceReceiverFlowAmountReturned :: GHC.Types.Int, | refund_attributes_method : Type of refund attribute method , one of \`email\ ` , \`manual\ ` , or \`none\ ` . * Maximum length of 5000 sourceReceiverFlowRefundAttributesMethod :: Data.Text.Internal.Text, | refund_attributes_status : Type of refund attribute status , one of \`missing\ ` , \`requested\ ` , or \`available\ ` . * Maximum length of 5000 sourceReceiverFlowRefundAttributesStatus :: Data.Text.Internal.Text } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON SourceReceiverFlow where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("address" Data.Aeson.Types.ToJSON..=)) (sourceReceiverFlowAddress obj) : ["amount_charged" Data.Aeson.Types.ToJSON..= sourceReceiverFlowAmountCharged obj] : ["amount_received" Data.Aeson.Types.ToJSON..= sourceReceiverFlowAmountReceived obj] : ["amount_returned" Data.Aeson.Types.ToJSON..= sourceReceiverFlowAmountReturned obj] : ["refund_attributes_method" Data.Aeson.Types.ToJSON..= sourceReceiverFlowRefundAttributesMethod obj] : ["refund_attributes_status" Data.Aeson.Types.ToJSON..= sourceReceiverFlowRefundAttributesStatus obj] : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("address" Data.Aeson.Types.ToJSON..=)) (sourceReceiverFlowAddress obj) : ["amount_charged" Data.Aeson.Types.ToJSON..= sourceReceiverFlowAmountCharged obj] : ["amount_received" Data.Aeson.Types.ToJSON..= sourceReceiverFlowAmountReceived obj] : ["amount_returned" Data.Aeson.Types.ToJSON..= sourceReceiverFlowAmountReturned obj] : ["refund_attributes_method" Data.Aeson.Types.ToJSON..= sourceReceiverFlowRefundAttributesMethod obj] : ["refund_attributes_status" Data.Aeson.Types.ToJSON..= sourceReceiverFlowRefundAttributesStatus obj] : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON SourceReceiverFlow where parseJSON = Data.Aeson.Types.FromJSON.withObject "SourceReceiverFlow" (\obj -> (((((GHC.Base.pure SourceReceiverFlow GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "address")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "amount_charged")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "amount_received")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "amount_returned")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "refund_attributes_method")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "refund_attributes_status")) mkSourceReceiverFlow :: GHC.Types.Int -> GHC.Types.Int -> GHC.Types.Int -> Data.Text.Internal.Text -> Data.Text.Internal.Text -> SourceReceiverFlow mkSourceReceiverFlow sourceReceiverFlowAmountCharged sourceReceiverFlowAmountReceived sourceReceiverFlowAmountReturned sourceReceiverFlowRefundAttributesMethod sourceReceiverFlowRefundAttributesStatus = SourceReceiverFlow { sourceReceiverFlowAddress = GHC.Maybe.Nothing, sourceReceiverFlowAmountCharged = sourceReceiverFlowAmountCharged, sourceReceiverFlowAmountReceived = sourceReceiverFlowAmountReceived, sourceReceiverFlowAmountReturned = sourceReceiverFlowAmountReturned, sourceReceiverFlowRefundAttributesMethod = sourceReceiverFlowRefundAttributesMethod, sourceReceiverFlowRefundAttributesStatus = sourceReceiverFlowRefundAttributesStatus }
bef6e474b5451a482703f124e6e8f592ea6f4ff09ac7572582ff048e00ba50d4
couchbase/couchdb
mochiweb_util.erl
@author < > 2007 Mochi Media , Inc. @doc Utilities for parsing and quoting . -module(mochiweb_util). -author(''). -export([join/2, quote_plus/1, urlencode/1, parse_qs/1, unquote/1]). -export([path_split/1]). -export([urlsplit/1, urlsplit_path/1, urlunsplit/1, urlunsplit_path/1]). -export([guess_mime/1, parse_header/1]). -export([shell_quote/1, cmd/1, cmd_string/1, cmd_port/2, cmd_status/1, cmd_status/2]). -export([record_to_proplist/2, record_to_proplist/3]). -export([safe_relative_path/1, partition/2]). -export([parse_qvalues/1, pick_accepted_encodings/3]). -export([make_io/1]). -export([normalize_path/1]). -export([rand_uniform/2]). -define(PERCENT, 37). % $\% -define(FULLSTOP, 46). % $\. -define(IS_HEX(C), ((C >= $0 andalso C =< $9) orelse (C >= $a andalso C =< $f) orelse (C >= $A andalso C =< $F))). -define(QS_SAFE(C), ((C >= $a andalso C =< $z) orelse (C >= $A andalso C =< $Z) orelse (C >= $0 andalso C =< $9) orelse (C =:= ?FULLSTOP orelse C =:= $- orelse C =:= $~ orelse C =:= $_))). hexdigit(C) when C < 10 -> $0 + C; hexdigit(C) when C < 16 -> $A + (C - 10). unhexdigit(C) when C >= $0, C =< $9 -> C - $0; unhexdigit(C) when C >= $a, C =< $f -> C - $a + 10; unhexdigit(C) when C >= $A, C =< $F -> C - $A + 10. , Sep ) - > { String , [ ] , [ ] } | { Prefix , Sep , Postfix } %% @doc Inspired by Python 2.5's str.partition: partition("foo / bar " , " / " ) = { " foo " , " / " , " bar " } , %% partition("foo", "/") = {"foo", "", ""}. partition(String, Sep) -> case partition(String, Sep, []) of undefined -> {String, "", ""}; Result -> Result end. partition("", _Sep, _Acc) -> undefined; partition(S, Sep, Acc) -> case partition2(S, Sep) of undefined -> [C | Rest] = S, partition(Rest, Sep, [C | Acc]); Rest -> {lists:reverse(Acc), Sep, Rest} end. partition2(Rest, "") -> Rest; partition2([C | R1], [C | R2]) -> partition2(R1, R2); partition2(_S, _Sep) -> undefined. safe_relative_path(string ( ) ) - > string ( ) | undefined %% @doc Return the reduced version of a relative path or undefined if it %% is not safe. safe relative paths can be joined with an absolute path %% and will result in a subdirectory of the absolute path. Safe paths %% never contain a backslash character. safe_relative_path("/" ++ _) -> undefined; safe_relative_path(P) -> case string:chr(P, $\\) of 0 -> safe_relative_path(P, []); _ -> undefined end. safe_relative_path("", Acc) -> case Acc of [] -> ""; _ -> string:join(lists:reverse(Acc), "/") end; safe_relative_path(P, Acc) -> case partition(P, "/") of {"", "/", _} -> %% /foo or foo//bar undefined; {"..", _, _} when Acc =:= [] -> undefined; {"..", _, Rest} -> safe_relative_path(Rest, tl(Acc)); {Part, "/", ""} -> safe_relative_path("", ["", Part | Acc]); {Part, _, Rest} -> safe_relative_path(Rest, [Part | Acc]) end. %% @spec shell_quote(string()) -> string() @doc Quote a string according to UNIX shell quoting rules , returns a string %% surrounded by double quotes. shell_quote(L) -> shell_quote(L, [$\"]). cmd_port([string ( ) ] , Options ) - > port ( ) %% @doc open_port({spawn, mochiweb_util:cmd_string(Argv)}, Options). cmd_port(Argv, Options) -> open_port({spawn, cmd_string(Argv)}, Options). ( ) ] ) - > string ( ) %% @doc os:cmd(cmd_string(Argv)). cmd(Argv) -> os:cmd(cmd_string(Argv)). cmd_string([string ( ) ] ) - > string ( ) %% @doc Create a shell quoted command string from a list of arguments. cmd_string(Argv) -> string:join([shell_quote(X) || X <- Argv], " "). ( ) ] ) - > { ExitStatus::integer ( ) , Stdout::binary ( ) } %% @doc Accumulate the output and exit status from the given application, %% will be spawned with cmd_port/2. cmd_status(Argv) -> cmd_status(Argv, []). ( ) ] , [ atom ( ) ] ) - > { ExitStatus::integer ( ) , Stdout::binary ( ) } %% @doc Accumulate the output and exit status from the given application, %% will be spawned with cmd_port/2. cmd_status(Argv, Options) -> Port = cmd_port(Argv, [exit_status, stderr_to_stdout, use_stdio, binary | Options]), try cmd_loop(Port, []) after catch port_close(Port) end. ( ) , list ( ) ) - > { ExitStatus::integer ( ) , Stdout::binary ( ) } %% @doc Accumulate the output and exit status from a port. cmd_loop(Port, Acc) -> receive {Port, {exit_status, Status}} -> {Status, iolist_to_binary(lists:reverse(Acc))}; {Port, {data, Data}} -> cmd_loop(Port, [Data | Acc]) end. %% @spec join([iolist()], iolist()) -> iolist() %% @doc Join a list of strings or binaries together with the given separator %% string or char or binary. The output is flattened, but may be an %% iolist() instead of a string() if any of the inputs are binary(). join([], _Separator) -> []; join([S], _Separator) -> lists:flatten(S); join(Strings, Separator) -> lists:flatten(revjoin(lists:reverse(Strings), Separator, [])). revjoin([], _Separator, Acc) -> Acc; revjoin([S | Rest], Separator, []) -> revjoin(Rest, Separator, [S]); revjoin([S | Rest], Separator, Acc) -> revjoin(Rest, Separator, [S, Separator | Acc]). ( ) | integer ( ) | float ( ) | string ( ) | binary ( ) ) - > string ( ) %% @doc URL safe encoding of the given term. quote_plus(Atom) when is_atom(Atom) -> quote_plus(atom_to_list(Atom)); quote_plus(Int) when is_integer(Int) -> quote_plus(integer_to_list(Int)); quote_plus(Binary) when is_binary(Binary) -> quote_plus(binary_to_list(Binary)); quote_plus(Float) when is_float(Float) -> quote_plus(mochinum:digits(Float)); quote_plus(String) -> quote_plus(String, []). quote_plus([], Acc) -> lists:reverse(Acc); quote_plus([C | Rest], Acc) when ?QS_SAFE(C) -> quote_plus(Rest, [C | Acc]); quote_plus([$\s | Rest], Acc) -> quote_plus(Rest, [$+ | Acc]); quote_plus([C | Rest], Acc) -> <<Hi:4, Lo:4>> = <<C>>, quote_plus(Rest, [hexdigit(Lo), hexdigit(Hi), ?PERCENT | Acc]). @spec urlencode([{Key , Value } ] ) - > string ( ) %% @doc URL encode the property list. urlencode(Props) -> Pairs = lists:foldr( fun ({K, V}, Acc) -> [quote_plus(K) ++ "=" ++ quote_plus(V) | Acc] end, [], Props), string:join(Pairs, "&"). %% @spec parse_qs(string() | binary()) -> [{Key, Value}] @doc a query string or application / x - www - form - urlencoded . parse_qs(Binary) when is_binary(Binary) -> parse_qs(binary_to_list(Binary)); parse_qs(String) -> parse_qs(String, []). parse_qs([], Acc) -> lists:reverse(Acc); parse_qs(String, Acc) -> {Key, Rest} = parse_qs_key(String), {Value, Rest1} = parse_qs_value(Rest), parse_qs(Rest1, [{Key, Value} | Acc]). parse_qs_key(String) -> parse_qs_key(String, []). parse_qs_key([], Acc) -> {qs_revdecode(Acc), ""}; parse_qs_key([$= | Rest], Acc) -> {qs_revdecode(Acc), Rest}; parse_qs_key(Rest=[$; | _], Acc) -> {qs_revdecode(Acc), Rest}; parse_qs_key(Rest=[$& | _], Acc) -> {qs_revdecode(Acc), Rest}; parse_qs_key([C | Rest], Acc) -> parse_qs_key(Rest, [C | Acc]). parse_qs_value(String) -> parse_qs_value(String, []). parse_qs_value([], Acc) -> {qs_revdecode(Acc), ""}; parse_qs_value([$; | Rest], Acc) -> {qs_revdecode(Acc), Rest}; parse_qs_value([$& | Rest], Acc) -> {qs_revdecode(Acc), Rest}; parse_qs_value([C | Rest], Acc) -> parse_qs_value(Rest, [C | Acc]). %% @spec unquote(string() | binary()) -> string() %% @doc Unquote a URL encoded string. unquote(Binary) when is_binary(Binary) -> unquote(binary_to_list(Binary)); unquote(String) -> qs_revdecode(lists:reverse(String)). qs_revdecode(S) -> qs_revdecode(S, []). qs_revdecode([], Acc) -> Acc; qs_revdecode([$+ | Rest], Acc) -> qs_revdecode(Rest, [$\s | Acc]); qs_revdecode([Lo, Hi, ?PERCENT | Rest], Acc) when ?IS_HEX(Lo), ?IS_HEX(Hi) -> qs_revdecode(Rest, [(unhexdigit(Lo) bor (unhexdigit(Hi) bsl 4)) | Acc]); qs_revdecode([C | Rest], Acc) -> qs_revdecode(Rest, [C | Acc]). urlsplit(Url ) - > { Scheme , Netloc , Path , Query , Fragment } @doc Return a 5 - tuple , does not expand % escapes . Only supports HTTP style %% URLs. urlsplit(Url) -> {Scheme, Url1} = urlsplit_scheme(Url), {Netloc, Url2} = urlsplit_netloc(Url1), {Path, Query, Fragment} = urlsplit_path(Url2), {Scheme, Netloc, Path, Query, Fragment}. urlsplit_scheme(Url) -> case urlsplit_scheme(Url, []) of no_scheme -> {"", Url}; Res -> Res end. urlsplit_scheme([C | Rest], Acc) when ((C >= $a andalso C =< $z) orelse (C >= $A andalso C =< $Z) orelse (C >= $0 andalso C =< $9) orelse C =:= $+ orelse C =:= $- orelse C =:= $.) -> urlsplit_scheme(Rest, [C | Acc]); urlsplit_scheme([$: | Rest], Acc=[_ | _]) -> {string:to_lower(lists:reverse(Acc)), Rest}; urlsplit_scheme(_Rest, _Acc) -> no_scheme. urlsplit_netloc("//" ++ Rest) -> urlsplit_netloc(Rest, []); urlsplit_netloc(Path) -> {"", Path}. urlsplit_netloc("", Acc) -> {lists:reverse(Acc), ""}; urlsplit_netloc(Rest=[C | _], Acc) when C =:= $/; C =:= $?; C =:= $# -> {lists:reverse(Acc), Rest}; urlsplit_netloc([C | Rest], Acc) -> urlsplit_netloc(Rest, [C | Acc]). @spec path_split(string ( ) ) - > { Part , Rest } %% @doc Split a path starting from the left, as in URL traversal. %% path_split("foo/bar") = {"foo", "bar"}, path_split("/foo / bar " ) = { " " , " foo / bar " } . path_split(S) -> path_split(S, []). path_split("", Acc) -> {lists:reverse(Acc), ""}; path_split("/" ++ Rest, Acc) -> {lists:reverse(Acc), Rest}; path_split([C | Rest], Acc) -> path_split(Rest, [C | Acc]). , Netloc , Path , Query , Fragment } ) - > string ( ) @doc Assemble a URL from the 5 - tuple . Path must be absolute . urlunsplit({Scheme, Netloc, Path, Query, Fragment}) -> lists:flatten([case Scheme of "" -> ""; _ -> [Scheme, "://"] end, Netloc, urlunsplit_path({Path, Query, Fragment})]). , Query , Fragment } ) - > string ( ) @doc Assemble a URL path from the 3 - tuple . urlunsplit_path({Path, Query, Fragment}) -> lists:flatten([Path, case Query of "" -> ""; _ -> [$? | Query] end, case Fragment of "" -> ""; _ -> [$# | Fragment] end]). @spec urlsplit_path(Url ) - > { Path , Query , Fragment } @doc Return a 3 - tuple , does not expand % escapes . Only supports HTTP style %% paths. urlsplit_path(Path) -> urlsplit_path(Path, []). urlsplit_path("", Acc) -> {lists:reverse(Acc), "", ""}; urlsplit_path("?" ++ Rest, Acc) -> {Query, Fragment} = urlsplit_query(Rest), {lists:reverse(Acc), Query, Fragment}; urlsplit_path("#" ++ Rest, Acc) -> {lists:reverse(Acc), "", Rest}; urlsplit_path([C | Rest], Acc) -> urlsplit_path(Rest, [C | Acc]). urlsplit_query(Query) -> urlsplit_query(Query, []). urlsplit_query("", Acc) -> {lists:reverse(Acc), ""}; urlsplit_query("#" ++ Rest, Acc) -> {lists:reverse(Acc), Rest}; urlsplit_query([C | Rest], Acc) -> urlsplit_query(Rest, [C | Acc]). guess_mime(string ( ) ) - > string ( ) %% @doc Guess the mime type of a file by the extension of its filename. guess_mime(File) -> case filename:basename(File) of "crossdomain.xml" -> "text/x-cross-domain-policy"; Name -> case mochiweb_mime:from_extension(filename:extension(Name)) of undefined -> "text/plain"; Mime -> Mime end end. %% @spec parse_header(string()) -> {Type, [{K, V}]} @doc a Content - Type like header , return the main Content - Type %% and a property list of options. parse_header(String) -> %% TODO: This is exactly as broken as Python's cgi module. %% Should parse properly like mochiweb_cookies. [Type | Parts] = [string:strip(S) || S <- string:tokens(String, ";")], F = fun (S, Acc) -> case lists:splitwith(fun (C) -> C =/= $= end, S) of {"", _} -> %% Skip anything with no name Acc; {_, ""} -> %% Skip anything with no value Acc; {Name, [$\= | Value]} -> [{string:to_lower(string:strip(Name)), unquote_header(string:strip(Value))} | Acc] end end, {string:to_lower(Type), lists:foldr(F, [], Parts)}. unquote_header("\"" ++ Rest) -> unquote_header(Rest, []); unquote_header(S) -> S. unquote_header("", Acc) -> lists:reverse(Acc); unquote_header("\"", Acc) -> lists:reverse(Acc); unquote_header([$\\, C | Rest], Acc) -> unquote_header(Rest, [C | Acc]); unquote_header([C | Rest], Acc) -> unquote_header(Rest, [C | Acc]). , ) - > proplist ( ) @doc calls record_to_proplist/3 with a default TypeKey of ' _ _ record ' record_to_proplist(Record, Fields) -> record_to_proplist(Record, Fields, '__record'). , , TypeKey ) - > proplist ( ) %% @doc Return a proplist of the given Record with each field in the %% Fields list set as a key with the corresponding value in the Record. TypeKey is the key that is used to store the record type Fields should be obtained by calling record_info(fields , record_type ) where record_type is the record type of Record record_to_proplist(Record, Fields, TypeKey) when tuple_size(Record) - 1 =:= length(Fields) -> lists:zip([TypeKey | Fields], tuple_to_list(Record)). shell_quote([], Acc) -> lists:reverse([$\" | Acc]); shell_quote([C | Rest], Acc) when C =:= $\" orelse C =:= $\` orelse C =:= $\\ orelse C =:= $\$ -> shell_quote(Rest, [C, $\\ | Acc]); shell_quote([C | Rest], Acc) -> shell_quote(Rest, [C | Acc]). %% @spec parse_qvalues(string()) -> [qvalue()] | invalid_qvalue_string @type qvalue ( ) = { media_type ( ) | encoding ( ) , float ( ) } . %% @type media_type() = string(). %% @type encoding() = string(). %% %% @doc Parses a list (given as a string) of elements with Q values associated %% to them. Elements are separated by commas and each element is separated %% from its Q value by a semicolon. Q values are optional but when missing the value of an element is considered as 1.0 . A Q value is always in the range [ 0.0 , 1.0 ] . A Q value list is used for example as the value of the %% HTTP "Accept" and "Accept-Encoding" headers. %% Q values are described in section 2.9 of the RFC 2616 ( HTTP 1.1 ) . %% %% Example: %% parse_qvalues("gzip ; q=0.5 , deflate , identity;q=0.0 " ) - > [ { " gzip " , 0.5 } , { " deflate " , 1.0 } , { " identity " , 0.0 } ] %% parse_qvalues(QValuesStr) -> try lists:map( fun(Pair) -> [Type | Params] = string:tokens(Pair, ";"), NormParams = normalize_media_params(Params), {Q, NonQParams} = extract_q(NormParams), {string:join([string:strip(Type) | NonQParams], ";"), Q} end, string:tokens(string:to_lower(QValuesStr), ",") ) catch _Type:_Error -> invalid_qvalue_string end. normalize_media_params(Params) -> {ok, Re} = re:compile("\\s"), normalize_media_params(Re, Params, []). normalize_media_params(_Re, [], Acc) -> lists:reverse(Acc); normalize_media_params(Re, [Param | Rest], Acc) -> NormParam = re:replace(Param, Re, "", [global, {return, list}]), normalize_media_params(Re, Rest, [NormParam | Acc]). extract_q(NormParams) -> {ok, KVRe} = re:compile("^([^=]+)=([^=]+)$"), {ok, QRe} = re:compile("^((?:0|1)(?:\\.\\d{1,3})?)$"), extract_q(KVRe, QRe, NormParams, []). extract_q(_KVRe, _QRe, [], Acc) -> {1.0, lists:reverse(Acc)}; extract_q(KVRe, QRe, [Param | Rest], Acc) -> case re:run(Param, KVRe, [{capture, [1, 2], list}]) of {match, [Name, Value]} -> case Name of "q" -> {match, [Q]} = re:run(Value, QRe, [{capture, [1], list}]), QVal = case Q of "0" -> 0.0; "1" -> 1.0; Else -> list_to_float(Else) end, case QVal < 0.0 orelse QVal > 1.0 of false -> {QVal, lists:reverse(Acc) ++ Rest} end; _ -> extract_q(KVRe, QRe, Rest, [Param | Acc]) end end. ( ) ] , [ encoding ( ) ] , encoding ( ) ) - > %% [encoding()] %% %% @doc Determines which encodings specified in the given Q values list are %% valid according to a list of supported encodings and a default encoding. %% %% The returned list of encodings is sorted, descendingly, according to the %% Q values of the given list. The last element of this list is the given %% default encoding unless this encoding is explicitily or implicitily marked with a Q value of 0.0 in the given Q values list . %% Note: encodings with the same Q value are kept in the same order as %% found in the input Q values list. %% This encoding picking process is described in section 14.3 of the RFC 2616 ( HTTP 1.1 ) . %% %% Example: %% %% pick_accepted_encodings( [ { " gzip " , 0.5 } , { " deflate " , 1.0 } ] , %% ["gzip", "identity"], %% "identity" %% ) -> %% ["gzip", "identity"] %% pick_accepted_encodings(AcceptedEncs, SupportedEncs, DefaultEnc) -> SortedQList = lists:reverse( lists:sort(fun({_, Q1}, {_, Q2}) -> Q1 < Q2 end, AcceptedEncs) ), {Accepted, Refused} = lists:foldr( fun({E, Q}, {A, R}) -> case Q > 0.0 of true -> {[E | A], R}; false -> {A, [E | R]} end end, {[], []}, SortedQList ), Refused1 = lists:foldr( fun(Enc, Acc) -> case Enc of "*" -> lists:subtract(SupportedEncs, Accepted) ++ Acc; _ -> [Enc | Acc] end end, [], Refused ), Accepted1 = lists:foldr( fun(Enc, Acc) -> case Enc of "*" -> lists:subtract(SupportedEncs, Accepted ++ Refused1) ++ Acc; _ -> [Enc | Acc] end end, [], Accepted ), Accepted2 = case lists:member(DefaultEnc, Accepted1) of true -> Accepted1; false -> Accepted1 ++ [DefaultEnc] end, [E || E <- Accepted2, lists:member(E, SupportedEncs), not lists:member(E, Refused1)]. make_io(Atom) when is_atom(Atom) -> atom_to_list(Atom); make_io(Integer) when is_integer(Integer) -> integer_to_list(Integer); make_io(Io) when is_list(Io); is_binary(Io) -> Io. normalize_path(string ( ) ) - > string ( ) %% @doc Remove duplicate slashes from an uri path ("//foo///bar////" becomes %% "/foo/bar/"). Per RFC 3986 , all but the last path segment must be non - empty . normalize_path(Path) -> normalize_path(Path, []). normalize_path([], Acc) -> lists:reverse(Acc); normalize_path("/" ++ Path, "/" ++ _ = Acc) -> normalize_path(Path, Acc); normalize_path([C|Path], Acc) -> normalize_path(Path, [C|Acc]). -ifdef(rand_mod_unavailable). rand_uniform(Start, End) -> crypto:rand_uniform(Start, End). -else. rand_uniform(Start, End) -> Start + rand:uniform(End - Start) - 1. -endif. %% %% Tests %% -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). make_io_test() -> ?assertEqual( <<"atom">>, iolist_to_binary(make_io(atom))), ?assertEqual( <<"20">>, iolist_to_binary(make_io(20))), ?assertEqual( <<"list">>, iolist_to_binary(make_io("list"))), ?assertEqual( <<"binary">>, iolist_to_binary(make_io(<<"binary">>))), ok. -record(test_record, {field1=f1, field2=f2}). record_to_proplist_test() -> ?assertEqual( [{'__record', test_record}, {field1, f1}, {field2, f2}], record_to_proplist(#test_record{}, record_info(fields, test_record))), ?assertEqual( [{'typekey', test_record}, {field1, f1}, {field2, f2}], record_to_proplist(#test_record{}, record_info(fields, test_record), typekey)), ok. shell_quote_test() -> ?assertEqual( "\"foo \\$bar\\\"\\`' baz\"", shell_quote("foo $bar\"`' baz")), ok. cmd_port_test_spool(Port, Acc) -> receive {Port, eof} -> Acc; {Port, {data, {eol, Data}}} -> cmd_port_test_spool(Port, ["\n", Data | Acc]); {Port, Unknown} -> throw({unknown, Unknown}) after 1000 -> throw(timeout) end. cmd_port_test() -> Port = cmd_port(["echo", "$bling$ `word`!"], [eof, stream, {line, 4096}]), Res = try lists:append(lists:reverse(cmd_port_test_spool(Port, []))) after catch port_close(Port) end, self() ! {Port, wtf}, try cmd_port_test_spool(Port, []) catch throw:{unknown, wtf} -> ok end, try cmd_port_test_spool(Port, []) catch throw:timeout -> ok end, ?assertEqual( "$bling$ `word`!\n", Res). cmd_test() -> ?assertEqual( "$bling$ `word`!\n", cmd(["echo", "$bling$ `word`!"])), ok. cmd_string_test() -> ?assertEqual( "\"echo\" \"\\$bling\\$ \\`word\\`!\"", cmd_string(["echo", "$bling$ `word`!"])), ok. cmd_status_test() -> ?assertEqual( {0, <<"$bling$ `word`!\n">>}, cmd_status(["echo", "$bling$ `word`!"])), ok. parse_header_test() -> ?assertEqual( {"multipart/form-data", [{"boundary", "AaB03x"}]}, parse_header("multipart/form-data; boundary=AaB03x")), %% This tests (currently) intentionally broken behavior ?assertEqual( {"multipart/form-data", [{"b", ""}, {"cgi", "is"}, {"broken", "true\"e"}]}, parse_header("multipart/form-data;b=;cgi=\"i\\s;broken=true\"e;=z;z")), ok. guess_mime_test() -> ?assertEqual("text/plain", guess_mime("")), ?assertEqual("text/plain", guess_mime(".text")), ?assertEqual("application/zip", guess_mime(".zip")), ?assertEqual("application/zip", guess_mime("x.zip")), ?assertEqual("text/html", guess_mime("x.html")), ?assertEqual("application/xhtml+xml", guess_mime("x.xhtml")), ?assertEqual("text/x-cross-domain-policy", guess_mime("crossdomain.xml")), ?assertEqual("text/x-cross-domain-policy", guess_mime("www/crossdomain.xml")), ok. path_split_test() -> {"", "foo/bar"} = path_split("/foo/bar"), {"foo", "bar"} = path_split("foo/bar"), {"bar", ""} = path_split("bar"), ok. urlsplit_test() -> {"", "", "/foo", "", "bar?baz"} = urlsplit("/foo#bar?baz"), {"http", "host:port", "/foo", "", "bar?baz"} = urlsplit(":port/foo#bar?baz"), {"http", "host", "", "", ""} = urlsplit(""), {"", "", "/wiki/Category:Fruit", "", ""} = urlsplit("/wiki/Category:Fruit"), ok. urlsplit_path_test() -> {"/foo/bar", "", ""} = urlsplit_path("/foo/bar"), {"/foo", "baz", ""} = urlsplit_path("/foo?baz"), {"/foo", "", "bar?baz"} = urlsplit_path("/foo#bar?baz"), {"/foo", "", "bar?baz#wibble"} = urlsplit_path("/foo#bar?baz#wibble"), {"/foo", "bar", "baz"} = urlsplit_path("/foo?bar#baz"), {"/foo", "bar?baz", "baz"} = urlsplit_path("/foo?bar?baz#baz"), ok. urlunsplit_test() -> "/foo#bar?baz" = urlunsplit({"", "", "/foo", "", "bar?baz"}), ":port/foo#bar?baz" = urlunsplit({"http", "host:port", "/foo", "", "bar?baz"}), ok. urlunsplit_path_test() -> "/foo/bar" = urlunsplit_path({"/foo/bar", "", ""}), "/foo?baz" = urlunsplit_path({"/foo", "baz", ""}), "/foo#bar?baz" = urlunsplit_path({"/foo", "", "bar?baz"}), "/foo#bar?baz#wibble" = urlunsplit_path({"/foo", "", "bar?baz#wibble"}), "/foo?bar#baz" = urlunsplit_path({"/foo", "bar", "baz"}), "/foo?bar?baz#baz" = urlunsplit_path({"/foo", "bar?baz", "baz"}), ok. join_test() -> ?assertEqual("foo,bar,baz", join(["foo", "bar", "baz"], $,)), ?assertEqual("foo,bar,baz", join(["foo", "bar", "baz"], ",")), ?assertEqual("foo bar", join([["foo", " bar"]], ",")), ?assertEqual("foo bar,baz", join([["foo", " bar"], "baz"], ",")), ?assertEqual("foo", join(["foo"], ",")), ?assertEqual("foobarbaz", join(["foo", "bar", "baz"], "")), ?assertEqual("foo" ++ [<<>>] ++ "bar" ++ [<<>>] ++ "baz", join(["foo", "bar", "baz"], <<>>)), ?assertEqual("foobar" ++ [<<"baz">>], join(["foo", "bar", <<"baz">>], "")), ?assertEqual("", join([], "any")), ok. quote_plus_test() -> "foo" = quote_plus(foo), "1" = quote_plus(1), "1.1" = quote_plus(1.1), "foo" = quote_plus("foo"), "foo+bar" = quote_plus("foo bar"), "foo%0A" = quote_plus("foo\n"), "foo%0A" = quote_plus("foo\n"), "foo%3B%26%3D" = quote_plus("foo;&="), "foo%3B%26%3D" = quote_plus(<<"foo;&=">>), ok. unquote_test() -> ?assertEqual("foo bar", unquote("foo+bar")), ?assertEqual("foo bar", unquote("foo%20bar")), ?assertEqual("foo\r\n", unquote("foo%0D%0A")), ?assertEqual("foo\r\n", unquote(<<"foo%0D%0A">>)), ok. urlencode_test() -> "foo=bar&baz=wibble+%0D%0A&z=1" = urlencode([{foo, "bar"}, {"baz", "wibble \r\n"}, {z, 1}]), ok. parse_qs_test() -> ?assertEqual( [{"foo", "bar"}, {"baz", "wibble \r\n"}, {"z", "1"}], parse_qs("foo=bar&baz=wibble+%0D%0a&z=1")), ?assertEqual( [{"", "bar"}, {"baz", "wibble \r\n"}, {"z", ""}], parse_qs("=bar&baz=wibble+%0D%0a&z=")), ?assertEqual( [{"foo", "bar"}, {"baz", "wibble \r\n"}, {"z", "1"}], parse_qs(<<"foo=bar&baz=wibble+%0D%0a&z=1">>)), ?assertEqual( [], parse_qs("")), ?assertEqual( [{"foo", ""}, {"bar", ""}, {"baz", ""}], parse_qs("foo;bar&baz")), ok. partition_test() -> {"foo", "", ""} = partition("foo", "/"), {"foo", "/", "bar"} = partition("foo/bar", "/"), {"foo", "/", ""} = partition("foo/", "/"), {"", "/", "bar"} = partition("/bar", "/"), {"f", "oo/ba", "r"} = partition("foo/bar", "oo/ba"), ok. safe_relative_path_test() -> "foo" = safe_relative_path("foo"), "foo/" = safe_relative_path("foo/"), "foo" = safe_relative_path("foo/bar/.."), "bar" = safe_relative_path("foo/../bar"), "bar/" = safe_relative_path("foo/../bar/"), "" = safe_relative_path("foo/.."), "" = safe_relative_path("foo/../"), undefined = safe_relative_path("/foo"), undefined = safe_relative_path("../foo"), undefined = safe_relative_path("foo/../.."), undefined = safe_relative_path("foo//"), undefined = safe_relative_path("foo\\bar"), ok. parse_qvalues_test() -> [] = parse_qvalues(""), [{"identity", 0.0}] = parse_qvalues("identity;q=0"), [{"identity", 0.0}] = parse_qvalues("identity ;q=0"), [{"identity", 0.0}] = parse_qvalues(" identity; q =0 "), [{"identity", 0.0}] = parse_qvalues("identity ; q = 0"), [{"identity", 0.0}] = parse_qvalues("identity ; q= 0.0"), [{"gzip", 1.0}, {"deflate", 1.0}, {"identity", 0.0}] = parse_qvalues( "gzip,deflate,identity;q=0.0" ), [{"deflate", 1.0}, {"gzip", 1.0}, {"identity", 0.0}] = parse_qvalues( "deflate,gzip,identity;q=0.0" ), [{"gzip", 1.0}, {"deflate", 1.0}, {"gzip", 1.0}, {"identity", 0.0}] = parse_qvalues("gzip,deflate,gzip,identity;q=0"), [{"gzip", 1.0}, {"deflate", 1.0}, {"identity", 0.0}] = parse_qvalues( "gzip, deflate , identity; q=0.0" ), [{"gzip", 1.0}, {"deflate", 1.0}, {"identity", 0.0}] = parse_qvalues( "gzip; q=1, deflate;q=1.0, identity;q=0.0" ), [{"gzip", 0.5}, {"deflate", 1.0}, {"identity", 0.0}] = parse_qvalues( "gzip; q=0.5, deflate;q=1.0, identity;q=0" ), [{"gzip", 0.5}, {"deflate", 1.0}, {"identity", 0.0}] = parse_qvalues( "gzip; q=0.5, deflate , identity;q=0.0" ), [{"gzip", 0.5}, {"deflate", 0.8}, {"identity", 0.0}] = parse_qvalues( "gzip; q=0.5, deflate;q=0.8, identity;q=0.0" ), [{"gzip", 0.5}, {"deflate", 1.0}, {"identity", 1.0}] = parse_qvalues( "gzip; q=0.5,deflate,identity" ), [{"gzip", 0.5}, {"deflate", 1.0}, {"identity", 1.0}, {"identity", 1.0}] = parse_qvalues("gzip; q=0.5,deflate,identity, identity "), [{"text/html;level=1", 1.0}, {"text/plain", 0.5}] = parse_qvalues("text/html;level=1, text/plain;q=0.5"), [{"text/html;level=1", 0.3}, {"text/plain", 1.0}] = parse_qvalues("text/html;level=1;q=0.3, text/plain"), [{"text/html;level=1", 0.3}, {"text/plain", 1.0}] = parse_qvalues("text/html; level = 1; q = 0.3, text/plain"), [{"text/html;level=1", 0.3}, {"text/plain", 1.0}] = parse_qvalues("text/html;q=0.3;level=1, text/plain"), invalid_qvalue_string = parse_qvalues("gzip; q=1.1, deflate"), invalid_qvalue_string = parse_qvalues("gzip; q=0.5, deflate;q=2"), invalid_qvalue_string = parse_qvalues("gzip, deflate;q=AB"), invalid_qvalue_string = parse_qvalues("gzip; q=2.1, deflate"), invalid_qvalue_string = parse_qvalues("gzip; q=0.1234, deflate"), invalid_qvalue_string = parse_qvalues("text/html;level=1;q=0.3, text/html;level"), ok. pick_accepted_encodings_test() -> ["identity"] = pick_accepted_encodings( [], ["gzip", "identity"], "identity" ), ["gzip", "identity"] = pick_accepted_encodings( [{"gzip", 1.0}], ["gzip", "identity"], "identity" ), ["identity"] = pick_accepted_encodings( [{"gzip", 0.0}], ["gzip", "identity"], "identity" ), ["gzip", "identity"] = pick_accepted_encodings( [{"gzip", 1.0}, {"deflate", 1.0}], ["gzip", "identity"], "identity" ), ["gzip", "identity"] = pick_accepted_encodings( [{"gzip", 0.5}, {"deflate", 1.0}], ["gzip", "identity"], "identity" ), ["identity"] = pick_accepted_encodings( [{"gzip", 0.0}, {"deflate", 0.0}], ["gzip", "identity"], "identity" ), ["gzip"] = pick_accepted_encodings( [{"gzip", 1.0}, {"deflate", 1.0}, {"identity", 0.0}], ["gzip", "identity"], "identity" ), ["gzip", "deflate", "identity"] = pick_accepted_encodings( [{"gzip", 1.0}, {"deflate", 1.0}], ["gzip", "deflate", "identity"], "identity" ), ["gzip", "deflate"] = pick_accepted_encodings( [{"gzip", 1.0}, {"deflate", 1.0}, {"identity", 0.0}], ["gzip", "deflate", "identity"], "identity" ), ["deflate", "gzip", "identity"] = pick_accepted_encodings( [{"gzip", 0.2}, {"deflate", 1.0}], ["gzip", "deflate", "identity"], "identity" ), ["deflate", "deflate", "gzip", "identity"] = pick_accepted_encodings( [{"gzip", 0.2}, {"deflate", 1.0}, {"deflate", 1.0}], ["gzip", "deflate", "identity"], "identity" ), ["deflate", "gzip", "gzip", "identity"] = pick_accepted_encodings( [{"gzip", 0.2}, {"deflate", 1.0}, {"gzip", 1.0}], ["gzip", "deflate", "identity"], "identity" ), ["gzip", "deflate", "gzip", "identity"] = pick_accepted_encodings( [{"gzip", 0.2}, {"deflate", 0.9}, {"gzip", 1.0}], ["gzip", "deflate", "identity"], "identity" ), [] = pick_accepted_encodings( [{"*", 0.0}], ["gzip", "deflate", "identity"], "identity" ), ["gzip", "deflate", "identity"] = pick_accepted_encodings( [{"*", 1.0}], ["gzip", "deflate", "identity"], "identity" ), ["gzip", "deflate", "identity"] = pick_accepted_encodings( [{"*", 0.6}], ["gzip", "deflate", "identity"], "identity" ), ["gzip"] = pick_accepted_encodings( [{"gzip", 1.0}, {"*", 0.0}], ["gzip", "deflate", "identity"], "identity" ), ["gzip", "deflate"] = pick_accepted_encodings( [{"gzip", 1.0}, {"deflate", 0.6}, {"*", 0.0}], ["gzip", "deflate", "identity"], "identity" ), ["deflate", "gzip"] = pick_accepted_encodings( [{"gzip", 0.5}, {"deflate", 1.0}, {"*", 0.0}], ["gzip", "deflate", "identity"], "identity" ), ["gzip", "identity"] = pick_accepted_encodings( [{"deflate", 0.0}, {"*", 1.0}], ["gzip", "deflate", "identity"], "identity" ), ["gzip", "identity"] = pick_accepted_encodings( [{"*", 1.0}, {"deflate", 0.0}], ["gzip", "deflate", "identity"], "identity" ), ok. normalize_path_test() -> "" = normalize_path(""), "/" = normalize_path("/"), "/" = normalize_path("//"), "/" = normalize_path("///"), "foo" = normalize_path("foo"), "/foo" = normalize_path("/foo"), "/foo" = normalize_path("//foo"), "/foo" = normalize_path("///foo"), "foo/" = normalize_path("foo/"), "foo/" = normalize_path("foo//"), "foo/" = normalize_path("foo///"), "foo/bar" = normalize_path("foo/bar"), "foo/bar" = normalize_path("foo//bar"), "foo/bar" = normalize_path("foo///bar"), "foo/bar" = normalize_path("foo////bar"), "/foo/bar" = normalize_path("/foo/bar"), "/foo/bar" = normalize_path("/foo////bar"), "/foo/bar" = normalize_path("////foo/bar"), "/foo/bar" = normalize_path("////foo///bar"), "/foo/bar" = normalize_path("////foo////bar"), "/foo/bar/" = normalize_path("/foo/bar/"), "/foo/bar/" = normalize_path("////foo/bar/"), "/foo/bar/" = normalize_path("/foo////bar/"), "/foo/bar/" = normalize_path("/foo/bar////"), "/foo/bar/" = normalize_path("///foo////bar/"), "/foo/bar/" = normalize_path("////foo/bar////"), "/foo/bar/" = normalize_path("/foo///bar////"), "/foo/bar/" = normalize_path("////foo///bar////"), ok. -endif.
null
https://raw.githubusercontent.com/couchbase/couchdb/8a75fd2faa89f95158de1776354ceccf3e762753/src/mochiweb/mochiweb_util.erl
erlang
$\% $\. @doc Inspired by Python 2.5's str.partition: partition("foo", "/") = {"foo", "", ""}. @doc Return the reduced version of a relative path or undefined if it is not safe. safe relative paths can be joined with an absolute path and will result in a subdirectory of the absolute path. Safe paths never contain a backslash character. /foo or foo//bar @spec shell_quote(string()) -> string() surrounded by double quotes. @doc open_port({spawn, mochiweb_util:cmd_string(Argv)}, Options). @doc os:cmd(cmd_string(Argv)). @doc Create a shell quoted command string from a list of arguments. @doc Accumulate the output and exit status from the given application, will be spawned with cmd_port/2. @doc Accumulate the output and exit status from the given application, will be spawned with cmd_port/2. @doc Accumulate the output and exit status from a port. @spec join([iolist()], iolist()) -> iolist() @doc Join a list of strings or binaries together with the given separator string or char or binary. The output is flattened, but may be an iolist() instead of a string() if any of the inputs are binary(). @doc URL safe encoding of the given term. @doc URL encode the property list. @spec parse_qs(string() | binary()) -> [{Key, Value}] @spec unquote(string() | binary()) -> string() @doc Unquote a URL encoded string. escapes . Only supports HTTP style URLs. @doc Split a path starting from the left, as in URL traversal. path_split("foo/bar") = {"foo", "bar"}, escapes . Only supports HTTP style paths. @doc Guess the mime type of a file by the extension of its filename. @spec parse_header(string()) -> {Type, [{K, V}]} and a property list of options. TODO: This is exactly as broken as Python's cgi module. Should parse properly like mochiweb_cookies. Skip anything with no name Skip anything with no value @doc Return a proplist of the given Record with each field in the Fields list set as a key with the corresponding value in the Record. @spec parse_qvalues(string()) -> [qvalue()] | invalid_qvalue_string @type media_type() = string(). @type encoding() = string(). @doc Parses a list (given as a string) of elements with Q values associated to them. Elements are separated by commas and each element is separated from its Q value by a semicolon. Q values are optional but when missing HTTP "Accept" and "Accept-Encoding" headers. Example: [encoding()] @doc Determines which encodings specified in the given Q values list are valid according to a list of supported encodings and a default encoding. The returned list of encodings is sorted, descendingly, according to the Q values of the given list. The last element of this list is the given default encoding unless this encoding is explicitily or implicitily Note: encodings with the same Q value are kept in the same order as found in the input Q values list. Example: pick_accepted_encodings( ["gzip", "identity"], "identity" ) -> ["gzip", "identity"] @doc Remove duplicate slashes from an uri path ("//foo///bar////" becomes "/foo/bar/"). Tests This tests (currently) intentionally broken behavior
@author < > 2007 Mochi Media , Inc. @doc Utilities for parsing and quoting . -module(mochiweb_util). -author(''). -export([join/2, quote_plus/1, urlencode/1, parse_qs/1, unquote/1]). -export([path_split/1]). -export([urlsplit/1, urlsplit_path/1, urlunsplit/1, urlunsplit_path/1]). -export([guess_mime/1, parse_header/1]). -export([shell_quote/1, cmd/1, cmd_string/1, cmd_port/2, cmd_status/1, cmd_status/2]). -export([record_to_proplist/2, record_to_proplist/3]). -export([safe_relative_path/1, partition/2]). -export([parse_qvalues/1, pick_accepted_encodings/3]). -export([make_io/1]). -export([normalize_path/1]). -export([rand_uniform/2]). -define(IS_HEX(C), ((C >= $0 andalso C =< $9) orelse (C >= $a andalso C =< $f) orelse (C >= $A andalso C =< $F))). -define(QS_SAFE(C), ((C >= $a andalso C =< $z) orelse (C >= $A andalso C =< $Z) orelse (C >= $0 andalso C =< $9) orelse (C =:= ?FULLSTOP orelse C =:= $- orelse C =:= $~ orelse C =:= $_))). hexdigit(C) when C < 10 -> $0 + C; hexdigit(C) when C < 16 -> $A + (C - 10). unhexdigit(C) when C >= $0, C =< $9 -> C - $0; unhexdigit(C) when C >= $a, C =< $f -> C - $a + 10; unhexdigit(C) when C >= $A, C =< $F -> C - $A + 10. , Sep ) - > { String , [ ] , [ ] } | { Prefix , Sep , Postfix } partition("foo / bar " , " / " ) = { " foo " , " / " , " bar " } , partition(String, Sep) -> case partition(String, Sep, []) of undefined -> {String, "", ""}; Result -> Result end. partition("", _Sep, _Acc) -> undefined; partition(S, Sep, Acc) -> case partition2(S, Sep) of undefined -> [C | Rest] = S, partition(Rest, Sep, [C | Acc]); Rest -> {lists:reverse(Acc), Sep, Rest} end. partition2(Rest, "") -> Rest; partition2([C | R1], [C | R2]) -> partition2(R1, R2); partition2(_S, _Sep) -> undefined. safe_relative_path(string ( ) ) - > string ( ) | undefined safe_relative_path("/" ++ _) -> undefined; safe_relative_path(P) -> case string:chr(P, $\\) of 0 -> safe_relative_path(P, []); _ -> undefined end. safe_relative_path("", Acc) -> case Acc of [] -> ""; _ -> string:join(lists:reverse(Acc), "/") end; safe_relative_path(P, Acc) -> case partition(P, "/") of {"", "/", _} -> undefined; {"..", _, _} when Acc =:= [] -> undefined; {"..", _, Rest} -> safe_relative_path(Rest, tl(Acc)); {Part, "/", ""} -> safe_relative_path("", ["", Part | Acc]); {Part, _, Rest} -> safe_relative_path(Rest, [Part | Acc]) end. @doc Quote a string according to UNIX shell quoting rules , returns a string shell_quote(L) -> shell_quote(L, [$\"]). cmd_port([string ( ) ] , Options ) - > port ( ) cmd_port(Argv, Options) -> open_port({spawn, cmd_string(Argv)}, Options). ( ) ] ) - > string ( ) cmd(Argv) -> os:cmd(cmd_string(Argv)). cmd_string([string ( ) ] ) - > string ( ) cmd_string(Argv) -> string:join([shell_quote(X) || X <- Argv], " "). ( ) ] ) - > { ExitStatus::integer ( ) , Stdout::binary ( ) } cmd_status(Argv) -> cmd_status(Argv, []). ( ) ] , [ atom ( ) ] ) - > { ExitStatus::integer ( ) , Stdout::binary ( ) } cmd_status(Argv, Options) -> Port = cmd_port(Argv, [exit_status, stderr_to_stdout, use_stdio, binary | Options]), try cmd_loop(Port, []) after catch port_close(Port) end. ( ) , list ( ) ) - > { ExitStatus::integer ( ) , Stdout::binary ( ) } cmd_loop(Port, Acc) -> receive {Port, {exit_status, Status}} -> {Status, iolist_to_binary(lists:reverse(Acc))}; {Port, {data, Data}} -> cmd_loop(Port, [Data | Acc]) end. join([], _Separator) -> []; join([S], _Separator) -> lists:flatten(S); join(Strings, Separator) -> lists:flatten(revjoin(lists:reverse(Strings), Separator, [])). revjoin([], _Separator, Acc) -> Acc; revjoin([S | Rest], Separator, []) -> revjoin(Rest, Separator, [S]); revjoin([S | Rest], Separator, Acc) -> revjoin(Rest, Separator, [S, Separator | Acc]). ( ) | integer ( ) | float ( ) | string ( ) | binary ( ) ) - > string ( ) quote_plus(Atom) when is_atom(Atom) -> quote_plus(atom_to_list(Atom)); quote_plus(Int) when is_integer(Int) -> quote_plus(integer_to_list(Int)); quote_plus(Binary) when is_binary(Binary) -> quote_plus(binary_to_list(Binary)); quote_plus(Float) when is_float(Float) -> quote_plus(mochinum:digits(Float)); quote_plus(String) -> quote_plus(String, []). quote_plus([], Acc) -> lists:reverse(Acc); quote_plus([C | Rest], Acc) when ?QS_SAFE(C) -> quote_plus(Rest, [C | Acc]); quote_plus([$\s | Rest], Acc) -> quote_plus(Rest, [$+ | Acc]); quote_plus([C | Rest], Acc) -> <<Hi:4, Lo:4>> = <<C>>, quote_plus(Rest, [hexdigit(Lo), hexdigit(Hi), ?PERCENT | Acc]). @spec urlencode([{Key , Value } ] ) - > string ( ) urlencode(Props) -> Pairs = lists:foldr( fun ({K, V}, Acc) -> [quote_plus(K) ++ "=" ++ quote_plus(V) | Acc] end, [], Props), string:join(Pairs, "&"). @doc a query string or application / x - www - form - urlencoded . parse_qs(Binary) when is_binary(Binary) -> parse_qs(binary_to_list(Binary)); parse_qs(String) -> parse_qs(String, []). parse_qs([], Acc) -> lists:reverse(Acc); parse_qs(String, Acc) -> {Key, Rest} = parse_qs_key(String), {Value, Rest1} = parse_qs_value(Rest), parse_qs(Rest1, [{Key, Value} | Acc]). parse_qs_key(String) -> parse_qs_key(String, []). parse_qs_key([], Acc) -> {qs_revdecode(Acc), ""}; parse_qs_key([$= | Rest], Acc) -> {qs_revdecode(Acc), Rest}; parse_qs_key(Rest=[$; | _], Acc) -> {qs_revdecode(Acc), Rest}; parse_qs_key(Rest=[$& | _], Acc) -> {qs_revdecode(Acc), Rest}; parse_qs_key([C | Rest], Acc) -> parse_qs_key(Rest, [C | Acc]). parse_qs_value(String) -> parse_qs_value(String, []). parse_qs_value([], Acc) -> {qs_revdecode(Acc), ""}; parse_qs_value([$; | Rest], Acc) -> {qs_revdecode(Acc), Rest}; parse_qs_value([$& | Rest], Acc) -> {qs_revdecode(Acc), Rest}; parse_qs_value([C | Rest], Acc) -> parse_qs_value(Rest, [C | Acc]). unquote(Binary) when is_binary(Binary) -> unquote(binary_to_list(Binary)); unquote(String) -> qs_revdecode(lists:reverse(String)). qs_revdecode(S) -> qs_revdecode(S, []). qs_revdecode([], Acc) -> Acc; qs_revdecode([$+ | Rest], Acc) -> qs_revdecode(Rest, [$\s | Acc]); qs_revdecode([Lo, Hi, ?PERCENT | Rest], Acc) when ?IS_HEX(Lo), ?IS_HEX(Hi) -> qs_revdecode(Rest, [(unhexdigit(Lo) bor (unhexdigit(Hi) bsl 4)) | Acc]); qs_revdecode([C | Rest], Acc) -> qs_revdecode(Rest, [C | Acc]). urlsplit(Url ) - > { Scheme , Netloc , Path , Query , Fragment } urlsplit(Url) -> {Scheme, Url1} = urlsplit_scheme(Url), {Netloc, Url2} = urlsplit_netloc(Url1), {Path, Query, Fragment} = urlsplit_path(Url2), {Scheme, Netloc, Path, Query, Fragment}. urlsplit_scheme(Url) -> case urlsplit_scheme(Url, []) of no_scheme -> {"", Url}; Res -> Res end. urlsplit_scheme([C | Rest], Acc) when ((C >= $a andalso C =< $z) orelse (C >= $A andalso C =< $Z) orelse (C >= $0 andalso C =< $9) orelse C =:= $+ orelse C =:= $- orelse C =:= $.) -> urlsplit_scheme(Rest, [C | Acc]); urlsplit_scheme([$: | Rest], Acc=[_ | _]) -> {string:to_lower(lists:reverse(Acc)), Rest}; urlsplit_scheme(_Rest, _Acc) -> no_scheme. urlsplit_netloc("//" ++ Rest) -> urlsplit_netloc(Rest, []); urlsplit_netloc(Path) -> {"", Path}. urlsplit_netloc("", Acc) -> {lists:reverse(Acc), ""}; urlsplit_netloc(Rest=[C | _], Acc) when C =:= $/; C =:= $?; C =:= $# -> {lists:reverse(Acc), Rest}; urlsplit_netloc([C | Rest], Acc) -> urlsplit_netloc(Rest, [C | Acc]). @spec path_split(string ( ) ) - > { Part , Rest } path_split("/foo / bar " ) = { " " , " foo / bar " } . path_split(S) -> path_split(S, []). path_split("", Acc) -> {lists:reverse(Acc), ""}; path_split("/" ++ Rest, Acc) -> {lists:reverse(Acc), Rest}; path_split([C | Rest], Acc) -> path_split(Rest, [C | Acc]). , Netloc , Path , Query , Fragment } ) - > string ( ) @doc Assemble a URL from the 5 - tuple . Path must be absolute . urlunsplit({Scheme, Netloc, Path, Query, Fragment}) -> lists:flatten([case Scheme of "" -> ""; _ -> [Scheme, "://"] end, Netloc, urlunsplit_path({Path, Query, Fragment})]). , Query , Fragment } ) - > string ( ) @doc Assemble a URL path from the 3 - tuple . urlunsplit_path({Path, Query, Fragment}) -> lists:flatten([Path, case Query of "" -> ""; _ -> [$? | Query] end, case Fragment of "" -> ""; _ -> [$# | Fragment] end]). @spec urlsplit_path(Url ) - > { Path , Query , Fragment } urlsplit_path(Path) -> urlsplit_path(Path, []). urlsplit_path("", Acc) -> {lists:reverse(Acc), "", ""}; urlsplit_path("?" ++ Rest, Acc) -> {Query, Fragment} = urlsplit_query(Rest), {lists:reverse(Acc), Query, Fragment}; urlsplit_path("#" ++ Rest, Acc) -> {lists:reverse(Acc), "", Rest}; urlsplit_path([C | Rest], Acc) -> urlsplit_path(Rest, [C | Acc]). urlsplit_query(Query) -> urlsplit_query(Query, []). urlsplit_query("", Acc) -> {lists:reverse(Acc), ""}; urlsplit_query("#" ++ Rest, Acc) -> {lists:reverse(Acc), Rest}; urlsplit_query([C | Rest], Acc) -> urlsplit_query(Rest, [C | Acc]). guess_mime(string ( ) ) - > string ( ) guess_mime(File) -> case filename:basename(File) of "crossdomain.xml" -> "text/x-cross-domain-policy"; Name -> case mochiweb_mime:from_extension(filename:extension(Name)) of undefined -> "text/plain"; Mime -> Mime end end. @doc a Content - Type like header , return the main Content - Type parse_header(String) -> [Type | Parts] = [string:strip(S) || S <- string:tokens(String, ";")], F = fun (S, Acc) -> case lists:splitwith(fun (C) -> C =/= $= end, S) of {"", _} -> Acc; {_, ""} -> Acc; {Name, [$\= | Value]} -> [{string:to_lower(string:strip(Name)), unquote_header(string:strip(Value))} | Acc] end end, {string:to_lower(Type), lists:foldr(F, [], Parts)}. unquote_header("\"" ++ Rest) -> unquote_header(Rest, []); unquote_header(S) -> S. unquote_header("", Acc) -> lists:reverse(Acc); unquote_header("\"", Acc) -> lists:reverse(Acc); unquote_header([$\\, C | Rest], Acc) -> unquote_header(Rest, [C | Acc]); unquote_header([C | Rest], Acc) -> unquote_header(Rest, [C | Acc]). , ) - > proplist ( ) @doc calls record_to_proplist/3 with a default TypeKey of ' _ _ record ' record_to_proplist(Record, Fields) -> record_to_proplist(Record, Fields, '__record'). , , TypeKey ) - > proplist ( ) TypeKey is the key that is used to store the record type Fields should be obtained by calling record_info(fields , record_type ) where record_type is the record type of Record record_to_proplist(Record, Fields, TypeKey) when tuple_size(Record) - 1 =:= length(Fields) -> lists:zip([TypeKey | Fields], tuple_to_list(Record)). shell_quote([], Acc) -> lists:reverse([$\" | Acc]); shell_quote([C | Rest], Acc) when C =:= $\" orelse C =:= $\` orelse C =:= $\\ orelse C =:= $\$ -> shell_quote(Rest, [C, $\\ | Acc]); shell_quote([C | Rest], Acc) -> shell_quote(Rest, [C | Acc]). @type qvalue ( ) = { media_type ( ) | encoding ( ) , float ( ) } . the value of an element is considered as 1.0 . A Q value is always in the range [ 0.0 , 1.0 ] . A Q value list is used for example as the value of the Q values are described in section 2.9 of the RFC 2616 ( HTTP 1.1 ) . parse_qvalues("gzip ; q=0.5 , deflate , identity;q=0.0 " ) - > [ { " gzip " , 0.5 } , { " deflate " , 1.0 } , { " identity " , 0.0 } ] parse_qvalues(QValuesStr) -> try lists:map( fun(Pair) -> [Type | Params] = string:tokens(Pair, ";"), NormParams = normalize_media_params(Params), {Q, NonQParams} = extract_q(NormParams), {string:join([string:strip(Type) | NonQParams], ";"), Q} end, string:tokens(string:to_lower(QValuesStr), ",") ) catch _Type:_Error -> invalid_qvalue_string end. normalize_media_params(Params) -> {ok, Re} = re:compile("\\s"), normalize_media_params(Re, Params, []). normalize_media_params(_Re, [], Acc) -> lists:reverse(Acc); normalize_media_params(Re, [Param | Rest], Acc) -> NormParam = re:replace(Param, Re, "", [global, {return, list}]), normalize_media_params(Re, Rest, [NormParam | Acc]). extract_q(NormParams) -> {ok, KVRe} = re:compile("^([^=]+)=([^=]+)$"), {ok, QRe} = re:compile("^((?:0|1)(?:\\.\\d{1,3})?)$"), extract_q(KVRe, QRe, NormParams, []). extract_q(_KVRe, _QRe, [], Acc) -> {1.0, lists:reverse(Acc)}; extract_q(KVRe, QRe, [Param | Rest], Acc) -> case re:run(Param, KVRe, [{capture, [1, 2], list}]) of {match, [Name, Value]} -> case Name of "q" -> {match, [Q]} = re:run(Value, QRe, [{capture, [1], list}]), QVal = case Q of "0" -> 0.0; "1" -> 1.0; Else -> list_to_float(Else) end, case QVal < 0.0 orelse QVal > 1.0 of false -> {QVal, lists:reverse(Acc) ++ Rest} end; _ -> extract_q(KVRe, QRe, Rest, [Param | Acc]) end end. ( ) ] , [ encoding ( ) ] , encoding ( ) ) - > marked with a Q value of 0.0 in the given Q values list . This encoding picking process is described in section 14.3 of the RFC 2616 ( HTTP 1.1 ) . [ { " gzip " , 0.5 } , { " deflate " , 1.0 } ] , pick_accepted_encodings(AcceptedEncs, SupportedEncs, DefaultEnc) -> SortedQList = lists:reverse( lists:sort(fun({_, Q1}, {_, Q2}) -> Q1 < Q2 end, AcceptedEncs) ), {Accepted, Refused} = lists:foldr( fun({E, Q}, {A, R}) -> case Q > 0.0 of true -> {[E | A], R}; false -> {A, [E | R]} end end, {[], []}, SortedQList ), Refused1 = lists:foldr( fun(Enc, Acc) -> case Enc of "*" -> lists:subtract(SupportedEncs, Accepted) ++ Acc; _ -> [Enc | Acc] end end, [], Refused ), Accepted1 = lists:foldr( fun(Enc, Acc) -> case Enc of "*" -> lists:subtract(SupportedEncs, Accepted ++ Refused1) ++ Acc; _ -> [Enc | Acc] end end, [], Accepted ), Accepted2 = case lists:member(DefaultEnc, Accepted1) of true -> Accepted1; false -> Accepted1 ++ [DefaultEnc] end, [E || E <- Accepted2, lists:member(E, SupportedEncs), not lists:member(E, Refused1)]. make_io(Atom) when is_atom(Atom) -> atom_to_list(Atom); make_io(Integer) when is_integer(Integer) -> integer_to_list(Integer); make_io(Io) when is_list(Io); is_binary(Io) -> Io. normalize_path(string ( ) ) - > string ( ) Per RFC 3986 , all but the last path segment must be non - empty . normalize_path(Path) -> normalize_path(Path, []). normalize_path([], Acc) -> lists:reverse(Acc); normalize_path("/" ++ Path, "/" ++ _ = Acc) -> normalize_path(Path, Acc); normalize_path([C|Path], Acc) -> normalize_path(Path, [C|Acc]). -ifdef(rand_mod_unavailable). rand_uniform(Start, End) -> crypto:rand_uniform(Start, End). -else. rand_uniform(Start, End) -> Start + rand:uniform(End - Start) - 1. -endif. -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). make_io_test() -> ?assertEqual( <<"atom">>, iolist_to_binary(make_io(atom))), ?assertEqual( <<"20">>, iolist_to_binary(make_io(20))), ?assertEqual( <<"list">>, iolist_to_binary(make_io("list"))), ?assertEqual( <<"binary">>, iolist_to_binary(make_io(<<"binary">>))), ok. -record(test_record, {field1=f1, field2=f2}). record_to_proplist_test() -> ?assertEqual( [{'__record', test_record}, {field1, f1}, {field2, f2}], record_to_proplist(#test_record{}, record_info(fields, test_record))), ?assertEqual( [{'typekey', test_record}, {field1, f1}, {field2, f2}], record_to_proplist(#test_record{}, record_info(fields, test_record), typekey)), ok. shell_quote_test() -> ?assertEqual( "\"foo \\$bar\\\"\\`' baz\"", shell_quote("foo $bar\"`' baz")), ok. cmd_port_test_spool(Port, Acc) -> receive {Port, eof} -> Acc; {Port, {data, {eol, Data}}} -> cmd_port_test_spool(Port, ["\n", Data | Acc]); {Port, Unknown} -> throw({unknown, Unknown}) after 1000 -> throw(timeout) end. cmd_port_test() -> Port = cmd_port(["echo", "$bling$ `word`!"], [eof, stream, {line, 4096}]), Res = try lists:append(lists:reverse(cmd_port_test_spool(Port, []))) after catch port_close(Port) end, self() ! {Port, wtf}, try cmd_port_test_spool(Port, []) catch throw:{unknown, wtf} -> ok end, try cmd_port_test_spool(Port, []) catch throw:timeout -> ok end, ?assertEqual( "$bling$ `word`!\n", Res). cmd_test() -> ?assertEqual( "$bling$ `word`!\n", cmd(["echo", "$bling$ `word`!"])), ok. cmd_string_test() -> ?assertEqual( "\"echo\" \"\\$bling\\$ \\`word\\`!\"", cmd_string(["echo", "$bling$ `word`!"])), ok. cmd_status_test() -> ?assertEqual( {0, <<"$bling$ `word`!\n">>}, cmd_status(["echo", "$bling$ `word`!"])), ok. parse_header_test() -> ?assertEqual( {"multipart/form-data", [{"boundary", "AaB03x"}]}, parse_header("multipart/form-data; boundary=AaB03x")), ?assertEqual( {"multipart/form-data", [{"b", ""}, {"cgi", "is"}, {"broken", "true\"e"}]}, parse_header("multipart/form-data;b=;cgi=\"i\\s;broken=true\"e;=z;z")), ok. guess_mime_test() -> ?assertEqual("text/plain", guess_mime("")), ?assertEqual("text/plain", guess_mime(".text")), ?assertEqual("application/zip", guess_mime(".zip")), ?assertEqual("application/zip", guess_mime("x.zip")), ?assertEqual("text/html", guess_mime("x.html")), ?assertEqual("application/xhtml+xml", guess_mime("x.xhtml")), ?assertEqual("text/x-cross-domain-policy", guess_mime("crossdomain.xml")), ?assertEqual("text/x-cross-domain-policy", guess_mime("www/crossdomain.xml")), ok. path_split_test() -> {"", "foo/bar"} = path_split("/foo/bar"), {"foo", "bar"} = path_split("foo/bar"), {"bar", ""} = path_split("bar"), ok. urlsplit_test() -> {"", "", "/foo", "", "bar?baz"} = urlsplit("/foo#bar?baz"), {"http", "host:port", "/foo", "", "bar?baz"} = urlsplit(":port/foo#bar?baz"), {"http", "host", "", "", ""} = urlsplit(""), {"", "", "/wiki/Category:Fruit", "", ""} = urlsplit("/wiki/Category:Fruit"), ok. urlsplit_path_test() -> {"/foo/bar", "", ""} = urlsplit_path("/foo/bar"), {"/foo", "baz", ""} = urlsplit_path("/foo?baz"), {"/foo", "", "bar?baz"} = urlsplit_path("/foo#bar?baz"), {"/foo", "", "bar?baz#wibble"} = urlsplit_path("/foo#bar?baz#wibble"), {"/foo", "bar", "baz"} = urlsplit_path("/foo?bar#baz"), {"/foo", "bar?baz", "baz"} = urlsplit_path("/foo?bar?baz#baz"), ok. urlunsplit_test() -> "/foo#bar?baz" = urlunsplit({"", "", "/foo", "", "bar?baz"}), ":port/foo#bar?baz" = urlunsplit({"http", "host:port", "/foo", "", "bar?baz"}), ok. urlunsplit_path_test() -> "/foo/bar" = urlunsplit_path({"/foo/bar", "", ""}), "/foo?baz" = urlunsplit_path({"/foo", "baz", ""}), "/foo#bar?baz" = urlunsplit_path({"/foo", "", "bar?baz"}), "/foo#bar?baz#wibble" = urlunsplit_path({"/foo", "", "bar?baz#wibble"}), "/foo?bar#baz" = urlunsplit_path({"/foo", "bar", "baz"}), "/foo?bar?baz#baz" = urlunsplit_path({"/foo", "bar?baz", "baz"}), ok. join_test() -> ?assertEqual("foo,bar,baz", join(["foo", "bar", "baz"], $,)), ?assertEqual("foo,bar,baz", join(["foo", "bar", "baz"], ",")), ?assertEqual("foo bar", join([["foo", " bar"]], ",")), ?assertEqual("foo bar,baz", join([["foo", " bar"], "baz"], ",")), ?assertEqual("foo", join(["foo"], ",")), ?assertEqual("foobarbaz", join(["foo", "bar", "baz"], "")), ?assertEqual("foo" ++ [<<>>] ++ "bar" ++ [<<>>] ++ "baz", join(["foo", "bar", "baz"], <<>>)), ?assertEqual("foobar" ++ [<<"baz">>], join(["foo", "bar", <<"baz">>], "")), ?assertEqual("", join([], "any")), ok. quote_plus_test() -> "foo" = quote_plus(foo), "1" = quote_plus(1), "1.1" = quote_plus(1.1), "foo" = quote_plus("foo"), "foo+bar" = quote_plus("foo bar"), "foo%0A" = quote_plus("foo\n"), "foo%0A" = quote_plus("foo\n"), "foo%3B%26%3D" = quote_plus("foo;&="), "foo%3B%26%3D" = quote_plus(<<"foo;&=">>), ok. unquote_test() -> ?assertEqual("foo bar", unquote("foo+bar")), ?assertEqual("foo bar", unquote("foo%20bar")), ?assertEqual("foo\r\n", unquote("foo%0D%0A")), ?assertEqual("foo\r\n", unquote(<<"foo%0D%0A">>)), ok. urlencode_test() -> "foo=bar&baz=wibble+%0D%0A&z=1" = urlencode([{foo, "bar"}, {"baz", "wibble \r\n"}, {z, 1}]), ok. parse_qs_test() -> ?assertEqual( [{"foo", "bar"}, {"baz", "wibble \r\n"}, {"z", "1"}], parse_qs("foo=bar&baz=wibble+%0D%0a&z=1")), ?assertEqual( [{"", "bar"}, {"baz", "wibble \r\n"}, {"z", ""}], parse_qs("=bar&baz=wibble+%0D%0a&z=")), ?assertEqual( [{"foo", "bar"}, {"baz", "wibble \r\n"}, {"z", "1"}], parse_qs(<<"foo=bar&baz=wibble+%0D%0a&z=1">>)), ?assertEqual( [], parse_qs("")), ?assertEqual( [{"foo", ""}, {"bar", ""}, {"baz", ""}], parse_qs("foo;bar&baz")), ok. partition_test() -> {"foo", "", ""} = partition("foo", "/"), {"foo", "/", "bar"} = partition("foo/bar", "/"), {"foo", "/", ""} = partition("foo/", "/"), {"", "/", "bar"} = partition("/bar", "/"), {"f", "oo/ba", "r"} = partition("foo/bar", "oo/ba"), ok. safe_relative_path_test() -> "foo" = safe_relative_path("foo"), "foo/" = safe_relative_path("foo/"), "foo" = safe_relative_path("foo/bar/.."), "bar" = safe_relative_path("foo/../bar"), "bar/" = safe_relative_path("foo/../bar/"), "" = safe_relative_path("foo/.."), "" = safe_relative_path("foo/../"), undefined = safe_relative_path("/foo"), undefined = safe_relative_path("../foo"), undefined = safe_relative_path("foo/../.."), undefined = safe_relative_path("foo//"), undefined = safe_relative_path("foo\\bar"), ok. parse_qvalues_test() -> [] = parse_qvalues(""), [{"identity", 0.0}] = parse_qvalues("identity;q=0"), [{"identity", 0.0}] = parse_qvalues("identity ;q=0"), [{"identity", 0.0}] = parse_qvalues(" identity; q =0 "), [{"identity", 0.0}] = parse_qvalues("identity ; q = 0"), [{"identity", 0.0}] = parse_qvalues("identity ; q= 0.0"), [{"gzip", 1.0}, {"deflate", 1.0}, {"identity", 0.0}] = parse_qvalues( "gzip,deflate,identity;q=0.0" ), [{"deflate", 1.0}, {"gzip", 1.0}, {"identity", 0.0}] = parse_qvalues( "deflate,gzip,identity;q=0.0" ), [{"gzip", 1.0}, {"deflate", 1.0}, {"gzip", 1.0}, {"identity", 0.0}] = parse_qvalues("gzip,deflate,gzip,identity;q=0"), [{"gzip", 1.0}, {"deflate", 1.0}, {"identity", 0.0}] = parse_qvalues( "gzip, deflate , identity; q=0.0" ), [{"gzip", 1.0}, {"deflate", 1.0}, {"identity", 0.0}] = parse_qvalues( "gzip; q=1, deflate;q=1.0, identity;q=0.0" ), [{"gzip", 0.5}, {"deflate", 1.0}, {"identity", 0.0}] = parse_qvalues( "gzip; q=0.5, deflate;q=1.0, identity;q=0" ), [{"gzip", 0.5}, {"deflate", 1.0}, {"identity", 0.0}] = parse_qvalues( "gzip; q=0.5, deflate , identity;q=0.0" ), [{"gzip", 0.5}, {"deflate", 0.8}, {"identity", 0.0}] = parse_qvalues( "gzip; q=0.5, deflate;q=0.8, identity;q=0.0" ), [{"gzip", 0.5}, {"deflate", 1.0}, {"identity", 1.0}] = parse_qvalues( "gzip; q=0.5,deflate,identity" ), [{"gzip", 0.5}, {"deflate", 1.0}, {"identity", 1.0}, {"identity", 1.0}] = parse_qvalues("gzip; q=0.5,deflate,identity, identity "), [{"text/html;level=1", 1.0}, {"text/plain", 0.5}] = parse_qvalues("text/html;level=1, text/plain;q=0.5"), [{"text/html;level=1", 0.3}, {"text/plain", 1.0}] = parse_qvalues("text/html;level=1;q=0.3, text/plain"), [{"text/html;level=1", 0.3}, {"text/plain", 1.0}] = parse_qvalues("text/html; level = 1; q = 0.3, text/plain"), [{"text/html;level=1", 0.3}, {"text/plain", 1.0}] = parse_qvalues("text/html;q=0.3;level=1, text/plain"), invalid_qvalue_string = parse_qvalues("gzip; q=1.1, deflate"), invalid_qvalue_string = parse_qvalues("gzip; q=0.5, deflate;q=2"), invalid_qvalue_string = parse_qvalues("gzip, deflate;q=AB"), invalid_qvalue_string = parse_qvalues("gzip; q=2.1, deflate"), invalid_qvalue_string = parse_qvalues("gzip; q=0.1234, deflate"), invalid_qvalue_string = parse_qvalues("text/html;level=1;q=0.3, text/html;level"), ok. pick_accepted_encodings_test() -> ["identity"] = pick_accepted_encodings( [], ["gzip", "identity"], "identity" ), ["gzip", "identity"] = pick_accepted_encodings( [{"gzip", 1.0}], ["gzip", "identity"], "identity" ), ["identity"] = pick_accepted_encodings( [{"gzip", 0.0}], ["gzip", "identity"], "identity" ), ["gzip", "identity"] = pick_accepted_encodings( [{"gzip", 1.0}, {"deflate", 1.0}], ["gzip", "identity"], "identity" ), ["gzip", "identity"] = pick_accepted_encodings( [{"gzip", 0.5}, {"deflate", 1.0}], ["gzip", "identity"], "identity" ), ["identity"] = pick_accepted_encodings( [{"gzip", 0.0}, {"deflate", 0.0}], ["gzip", "identity"], "identity" ), ["gzip"] = pick_accepted_encodings( [{"gzip", 1.0}, {"deflate", 1.0}, {"identity", 0.0}], ["gzip", "identity"], "identity" ), ["gzip", "deflate", "identity"] = pick_accepted_encodings( [{"gzip", 1.0}, {"deflate", 1.0}], ["gzip", "deflate", "identity"], "identity" ), ["gzip", "deflate"] = pick_accepted_encodings( [{"gzip", 1.0}, {"deflate", 1.0}, {"identity", 0.0}], ["gzip", "deflate", "identity"], "identity" ), ["deflate", "gzip", "identity"] = pick_accepted_encodings( [{"gzip", 0.2}, {"deflate", 1.0}], ["gzip", "deflate", "identity"], "identity" ), ["deflate", "deflate", "gzip", "identity"] = pick_accepted_encodings( [{"gzip", 0.2}, {"deflate", 1.0}, {"deflate", 1.0}], ["gzip", "deflate", "identity"], "identity" ), ["deflate", "gzip", "gzip", "identity"] = pick_accepted_encodings( [{"gzip", 0.2}, {"deflate", 1.0}, {"gzip", 1.0}], ["gzip", "deflate", "identity"], "identity" ), ["gzip", "deflate", "gzip", "identity"] = pick_accepted_encodings( [{"gzip", 0.2}, {"deflate", 0.9}, {"gzip", 1.0}], ["gzip", "deflate", "identity"], "identity" ), [] = pick_accepted_encodings( [{"*", 0.0}], ["gzip", "deflate", "identity"], "identity" ), ["gzip", "deflate", "identity"] = pick_accepted_encodings( [{"*", 1.0}], ["gzip", "deflate", "identity"], "identity" ), ["gzip", "deflate", "identity"] = pick_accepted_encodings( [{"*", 0.6}], ["gzip", "deflate", "identity"], "identity" ), ["gzip"] = pick_accepted_encodings( [{"gzip", 1.0}, {"*", 0.0}], ["gzip", "deflate", "identity"], "identity" ), ["gzip", "deflate"] = pick_accepted_encodings( [{"gzip", 1.0}, {"deflate", 0.6}, {"*", 0.0}], ["gzip", "deflate", "identity"], "identity" ), ["deflate", "gzip"] = pick_accepted_encodings( [{"gzip", 0.5}, {"deflate", 1.0}, {"*", 0.0}], ["gzip", "deflate", "identity"], "identity" ), ["gzip", "identity"] = pick_accepted_encodings( [{"deflate", 0.0}, {"*", 1.0}], ["gzip", "deflate", "identity"], "identity" ), ["gzip", "identity"] = pick_accepted_encodings( [{"*", 1.0}, {"deflate", 0.0}], ["gzip", "deflate", "identity"], "identity" ), ok. normalize_path_test() -> "" = normalize_path(""), "/" = normalize_path("/"), "/" = normalize_path("//"), "/" = normalize_path("///"), "foo" = normalize_path("foo"), "/foo" = normalize_path("/foo"), "/foo" = normalize_path("//foo"), "/foo" = normalize_path("///foo"), "foo/" = normalize_path("foo/"), "foo/" = normalize_path("foo//"), "foo/" = normalize_path("foo///"), "foo/bar" = normalize_path("foo/bar"), "foo/bar" = normalize_path("foo//bar"), "foo/bar" = normalize_path("foo///bar"), "foo/bar" = normalize_path("foo////bar"), "/foo/bar" = normalize_path("/foo/bar"), "/foo/bar" = normalize_path("/foo////bar"), "/foo/bar" = normalize_path("////foo/bar"), "/foo/bar" = normalize_path("////foo///bar"), "/foo/bar" = normalize_path("////foo////bar"), "/foo/bar/" = normalize_path("/foo/bar/"), "/foo/bar/" = normalize_path("////foo/bar/"), "/foo/bar/" = normalize_path("/foo////bar/"), "/foo/bar/" = normalize_path("/foo/bar////"), "/foo/bar/" = normalize_path("///foo////bar/"), "/foo/bar/" = normalize_path("////foo/bar////"), "/foo/bar/" = normalize_path("/foo///bar////"), "/foo/bar/" = normalize_path("////foo///bar////"), ok. -endif.
c890dc8bae6f30ecdcc1ffa5e1ab283ca91e8d78be704ea0293dac7cf9379f71
CSCfi/rems
entitlements.clj
(ns rems.db.entitlements "Creating and fetching entitlements." (:require [clj-http.client :as http] [clj-time.core :as time] [clojure.set :refer [union]] [clojure.tools.logging :as log] [mount.core :as mount] [rems.common.application-util :as application-util] [rems.config :refer [env]] [rems.db.applications :as applications] [rems.db.core :as db] [rems.db.outbox :as outbox] [rems.ga4gh :as ga4gh] [rems.json :as json] [rems.scheduler :as scheduler] [rems.service.ega :as ega])) (defn- get-entitlements-payload [entitlements action] (case action :ga4gh (ga4gh/entitlements->passport entitlements) (for [e entitlements] {:application (:catappid e) :resource (:resid e) :user (:userid e) :mail (:mail e) :end (:end e)}))) (defn- post-entitlements! [{:keys [action type entitlements config]}] (case type :ega (when config (try (doseq [entitlement entitlements] ; technically these could be grouped per user & api-key (ega/entitlement-push action entitlement config)) (catch Exception e (log/error "POST failed" e) (or (ex-data e) {:status "exception"})))) :basic ; TODO: let's move this :entitlements-target (v1) at some point to :entitlement-post (v2) (when-let [target (get-in env [:entitlements-target action])] (let [payload (get-entitlements-payload entitlements action) json-payload (json/generate-string payload)] (log/infof "Posting entitlements to %s: %s" target payload) (let [response (try (http/post target {:throw-exceptions false :body json-payload :content-type :json :socket-timeout 2500 :conn-timeout 2500}) (catch Exception e (log/error "POST failed" e) {:status "exception"})) status (:status response)] (if (= 200 status) (log/infof "Posted entitlements to %s: %s -> %s" target payload status) (do (log/warnf "Entitlement post failed: %s", response) (str "failed: " status)))))))) ;; TODO argh adding these everywhere sucks TODO consider using schema coercions (defn- fix-entry-from-db [entry] (-> entry (update-in [:outbox/entitlement-post :action] keyword) (update-in [:outbox/entitlement-post :type] keyword) (update-in [:outbox/entitlement-post :config :type] keyword))) (defn process-outbox! [] (doseq [entry (mapv fix-entry-from-db (outbox/get-due-entries :entitlement-post))] TODO could send multiple entitlements at once instead of one outbox entry at a time (if-let [error (post-entitlements! (:outbox/entitlement-post entry))] (let [entry (outbox/attempt-failed! entry error)] (when (not (:outbox/next-attempt entry)) (log/warn "all attempts to send entitlement post id " (:outbox/id entry) "failed"))) (outbox/attempt-succeeded! (:outbox/id entry))))) (mount/defstate entitlement-poller :start (scheduler/start! "entitlement-poller" process-outbox! (.toStandardDuration (time/seconds 10))) :stop (scheduler/stop! entitlement-poller)) (defn- add-to-outbox! [action type entitlements config] (outbox/put! {:outbox/type :entitlement-post :outbox/deadline (time/plus (time/now) (time/days 1)) ;; hardcoded for now :outbox/entitlement-post {:action action :type type :entitlements entitlements :config config}})) (defn- grant-entitlements! [application-id user-id resource-ids actor end] (log/info "granting entitlements on application" application-id "to" user-id "resources" resource-ids "until" end) (doseq [resource-id (sort resource-ids)] (db/add-entitlement! {:application application-id :user user-id :resource resource-id :approvedby actor :start (time/now) ; TODO should ideally come from the command time :end end}) TODO could generate only one outbox entry per application . Currently one per user - resource pair . (let [entitlements (db/get-entitlements {:application application-id :user user-id :resource resource-id})] (add-to-outbox! :add :basic entitlements nil) (doseq [config (:entitlement-push env)] (add-to-outbox! :add (:type config) entitlements config))))) (defn- revoke-entitlements! [application-id user-id resource-ids actor end] (log/info "revoking entitlements on application" application-id "to" user-id "resources" resource-ids "at" end) (doseq [resource-id (sort resource-ids)] (db/end-entitlements! {:application application-id :user user-id :resource resource-id :revokedby actor :end end}) (let [entitlements (db/get-entitlements {:application application-id :user user-id :resource resource-id})] (add-to-outbox! :remove :basic entitlements nil) (doseq [config (:entitlement-push env)] (add-to-outbox! :remove (:type config) entitlements config))))) (defn- get-entitlements-by-user [application-id] (->> (db/get-entitlements {:application application-id :active-at (time/now)}) (group-by :userid) (map (fn [[userid rows]] [userid (set (map :resourceid rows))])) (into {}))) (defn- update-entitlements-for-application "If the given application is approved, licenses accepted etc. add an entitlement to the db and call the entitlement REST callback (if defined). Likewise if a resource is removed, member left etc. then we end the entitlement and call the REST callback." [application actor] (let [application-id (:application/id application) current-members (set (map :userid (application-util/applicant-and-members application))) past-members (set (map :userid (:application/past-members application))) application-state (:application/state application) application-resources (->> application :application/resources (map :resource/id) set) application-entitlements (get-entitlements-by-user application-id) is-entitled? (fn [userid resource-id] (and (= :application.state/approved application-state) (contains? current-members userid) (application-util/accepted-licenses? application userid) (contains? application-resources resource-id))) entitlements-by-user (fn [userid] (or (application-entitlements userid) #{})) entitlements-to-add (->> (for [userid (union current-members past-members) :let [current-resource-ids (entitlements-by-user userid)] resource-id application-resources :when (is-entitled? userid resource-id) :when (not (contains? current-resource-ids resource-id))] {userid #{resource-id}}) (apply merge-with union)) entitlements-to-remove (->> (for [userid (union current-members past-members) :let [resource-ids (entitlements-by-user userid)] resource-id resource-ids :when (not (is-entitled? userid resource-id))] {userid #{resource-id}}) (apply merge-with union)) members-to-update (keys (merge entitlements-to-add entitlements-to-remove))] (when (seq members-to-update) (log/info "updating entitlements on application" application-id) (doseq [[userid resource-ids] entitlements-to-add] (grant-entitlements! application-id userid resource-ids actor (:entitlement/end application))) (doseq [[userid resource-ids] entitlements-to-remove] TODO should get the time from the event (revoke-entitlements! application-id userid resource-ids actor (time/now)))))) (defn update-entitlements-for-event [event] ;; performance improvement: filter events which may affect entitlements (when (contains? #{:application.event/approved :application.event/closed :application.event/licenses-accepted :application.event/member-removed :application.event/resources-changed :application.event/revoked} (:event/type event)) (let [application (applications/get-application-internal (:application/id event))] (update-entitlements-for-application application (:event/actor event))))) (defn update-entitlements-for-events [events] (doseq [event events] (update-entitlements-for-event event)) ;; this is used as a process manager, so return an explicit empty vector of commands [])
null
https://raw.githubusercontent.com/CSCfi/rems/af65570a5e5a6102aec4dc85d07d0f6fbb60c18d/src/clj/rems/db/entitlements.clj
clojure
technically these could be grouped per user & api-key TODO: let's move this :entitlements-target (v1) at some point to :entitlement-post (v2) TODO argh adding these everywhere sucks hardcoded for now TODO should ideally come from the command time performance improvement: filter events which may affect entitlements this is used as a process manager, so return an explicit empty vector of commands
(ns rems.db.entitlements "Creating and fetching entitlements." (:require [clj-http.client :as http] [clj-time.core :as time] [clojure.set :refer [union]] [clojure.tools.logging :as log] [mount.core :as mount] [rems.common.application-util :as application-util] [rems.config :refer [env]] [rems.db.applications :as applications] [rems.db.core :as db] [rems.db.outbox :as outbox] [rems.ga4gh :as ga4gh] [rems.json :as json] [rems.scheduler :as scheduler] [rems.service.ega :as ega])) (defn- get-entitlements-payload [entitlements action] (case action :ga4gh (ga4gh/entitlements->passport entitlements) (for [e entitlements] {:application (:catappid e) :resource (:resid e) :user (:userid e) :mail (:mail e) :end (:end e)}))) (defn- post-entitlements! [{:keys [action type entitlements config]}] (case type :ega (when config (ega/entitlement-push action entitlement config)) (catch Exception e (log/error "POST failed" e) (or (ex-data e) {:status "exception"})))) (when-let [target (get-in env [:entitlements-target action])] (let [payload (get-entitlements-payload entitlements action) json-payload (json/generate-string payload)] (log/infof "Posting entitlements to %s: %s" target payload) (let [response (try (http/post target {:throw-exceptions false :body json-payload :content-type :json :socket-timeout 2500 :conn-timeout 2500}) (catch Exception e (log/error "POST failed" e) {:status "exception"})) status (:status response)] (if (= 200 status) (log/infof "Posted entitlements to %s: %s -> %s" target payload status) (do (log/warnf "Entitlement post failed: %s", response) (str "failed: " status)))))))) TODO consider using schema coercions (defn- fix-entry-from-db [entry] (-> entry (update-in [:outbox/entitlement-post :action] keyword) (update-in [:outbox/entitlement-post :type] keyword) (update-in [:outbox/entitlement-post :config :type] keyword))) (defn process-outbox! [] (doseq [entry (mapv fix-entry-from-db (outbox/get-due-entries :entitlement-post))] TODO could send multiple entitlements at once instead of one outbox entry at a time (if-let [error (post-entitlements! (:outbox/entitlement-post entry))] (let [entry (outbox/attempt-failed! entry error)] (when (not (:outbox/next-attempt entry)) (log/warn "all attempts to send entitlement post id " (:outbox/id entry) "failed"))) (outbox/attempt-succeeded! (:outbox/id entry))))) (mount/defstate entitlement-poller :start (scheduler/start! "entitlement-poller" process-outbox! (.toStandardDuration (time/seconds 10))) :stop (scheduler/stop! entitlement-poller)) (defn- add-to-outbox! [action type entitlements config] (outbox/put! {:outbox/type :entitlement-post :outbox/entitlement-post {:action action :type type :entitlements entitlements :config config}})) (defn- grant-entitlements! [application-id user-id resource-ids actor end] (log/info "granting entitlements on application" application-id "to" user-id "resources" resource-ids "until" end) (doseq [resource-id (sort resource-ids)] (db/add-entitlement! {:application application-id :user user-id :resource resource-id :approvedby actor :end end}) TODO could generate only one outbox entry per application . Currently one per user - resource pair . (let [entitlements (db/get-entitlements {:application application-id :user user-id :resource resource-id})] (add-to-outbox! :add :basic entitlements nil) (doseq [config (:entitlement-push env)] (add-to-outbox! :add (:type config) entitlements config))))) (defn- revoke-entitlements! [application-id user-id resource-ids actor end] (log/info "revoking entitlements on application" application-id "to" user-id "resources" resource-ids "at" end) (doseq [resource-id (sort resource-ids)] (db/end-entitlements! {:application application-id :user user-id :resource resource-id :revokedby actor :end end}) (let [entitlements (db/get-entitlements {:application application-id :user user-id :resource resource-id})] (add-to-outbox! :remove :basic entitlements nil) (doseq [config (:entitlement-push env)] (add-to-outbox! :remove (:type config) entitlements config))))) (defn- get-entitlements-by-user [application-id] (->> (db/get-entitlements {:application application-id :active-at (time/now)}) (group-by :userid) (map (fn [[userid rows]] [userid (set (map :resourceid rows))])) (into {}))) (defn- update-entitlements-for-application "If the given application is approved, licenses accepted etc. add an entitlement to the db and call the entitlement REST callback (if defined). Likewise if a resource is removed, member left etc. then we end the entitlement and call the REST callback." [application actor] (let [application-id (:application/id application) current-members (set (map :userid (application-util/applicant-and-members application))) past-members (set (map :userid (:application/past-members application))) application-state (:application/state application) application-resources (->> application :application/resources (map :resource/id) set) application-entitlements (get-entitlements-by-user application-id) is-entitled? (fn [userid resource-id] (and (= :application.state/approved application-state) (contains? current-members userid) (application-util/accepted-licenses? application userid) (contains? application-resources resource-id))) entitlements-by-user (fn [userid] (or (application-entitlements userid) #{})) entitlements-to-add (->> (for [userid (union current-members past-members) :let [current-resource-ids (entitlements-by-user userid)] resource-id application-resources :when (is-entitled? userid resource-id) :when (not (contains? current-resource-ids resource-id))] {userid #{resource-id}}) (apply merge-with union)) entitlements-to-remove (->> (for [userid (union current-members past-members) :let [resource-ids (entitlements-by-user userid)] resource-id resource-ids :when (not (is-entitled? userid resource-id))] {userid #{resource-id}}) (apply merge-with union)) members-to-update (keys (merge entitlements-to-add entitlements-to-remove))] (when (seq members-to-update) (log/info "updating entitlements on application" application-id) (doseq [[userid resource-ids] entitlements-to-add] (grant-entitlements! application-id userid resource-ids actor (:entitlement/end application))) (doseq [[userid resource-ids] entitlements-to-remove] TODO should get the time from the event (revoke-entitlements! application-id userid resource-ids actor (time/now)))))) (defn update-entitlements-for-event [event] (when (contains? #{:application.event/approved :application.event/closed :application.event/licenses-accepted :application.event/member-removed :application.event/resources-changed :application.event/revoked} (:event/type event)) (let [application (applications/get-application-internal (:application/id event))] (update-entitlements-for-application application (:event/actor event))))) (defn update-entitlements-for-events [events] (doseq [event events] (update-entitlements-for-event event)) [])
98da3e3c01ff0212e0e5caa8d27fc81e218dec36aa2426c4ac8401d64fbb5653
typeable/octopod
WorkingOverrides.hs
module Data.WorkingOverrides ( WorkingOverrides, WorkingOverrideKey' (..), getConfigValueText, WorkingOverrideKey, WorkingOverrideKeyType (..), destructWorkingOverrides, constructWorkingOverrides, ConfigValue (..), CustomKey (..), CustomConfigValue (..), WorkingConfigTree, WorkingOverride, WorkingOverride', configTreeHasLeaf, destructWorkingOverridesDyn, ) where import Common.Orphans () import Common.Types import Control.Monad.Reader import Control.Monad.Ref import Data.ConfigTree (ConfigTree) import qualified Data.ConfigTree as CT import Data.Foldable import Data.Functor import Data.Map (Map) import qualified Data.Map as M import Data.Maybe (catMaybes) import qualified Data.Maybe as M import Data.Text (Text) import Data.These import GHC.Generics (Generic) import Reflex type WorkingConfigTree k v = ConfigTree k (ConfigValue v) data ConfigValue te = DefaultConfigValue !te | CustomConfigValue !(Either (CustomKey te) (CustomConfigValue te)) deriving stock (Show, Generic, Eq, Ord) newtype CustomKey v = CustomKey v deriving stock (Show, Generic, Eq, Ord) data CustomConfigValue te = CustomValue !te | DeletedValue !(Maybe te) deriving stock (Show, Generic, Eq, Ord) getConfigValueText :: ConfigValue te -> Maybe te getConfigValueText (DefaultConfigValue t) = Just t getConfigValueText (CustomConfigValue (Left (CustomKey t))) = Just t getConfigValueText (CustomConfigValue (Right (CustomValue t))) = Just t getConfigValueText (CustomConfigValue (Right (DeletedValue t))) = t Super inefficient but i do nt care configTreeHasLeaf :: forall m kv te. ( MonadReader (Ref m (Map (Text, ConfigTree kv te) Bool)) m , MonadRef m , Ord kv , Ord te ) => -- | The id of the predicate used for caching Text -> (te -> Bool) -> ConfigTree kv te -> m Bool configTreeHasLeaf name f = memo (\(_, CT.ConfigTree x) -> go $ toList x) . (name,) where go :: [(Maybe te, ConfigTree kv te)] -> m Bool go [] = pure False go ((Just y, _) : _) | f y = pure True go ((_, ct) : rest) = configTreeHasLeaf name f ct >>= \case True -> pure True False -> go rest memo :: (MonadReader (Ref m (Map x y)) m, Ord x, MonadRef m) => (x -> m y) -> x -> m y memo f x = do memoRef <- ask m <- readRef memoRef case M.lookup x m of Just y -> pure y Nothing -> do y <- f x modifyRef memoRef $ M.insert x y pure y type WorkingOverrides = WorkingOverrides' Text type WorkingOverrides' te = ConfigTree te (ConfigValue te) type WorkingOverride = WorkingOverride' Text type WorkingOverride' te = (te, ConfigValue te) type WorkingOverrideKey = WorkingOverrideKey' Text data WorkingOverrideKey' te = WorkingOverrideKey !WorkingOverrideKeyType !te deriving stock (Show) data WorkingOverrideKeyType = CustomWorkingOverrideKey | DefaultWorkingOverrideKey deriving stock (Show, Eq) destructWorkingOverridesDyn :: Reflex t => [Dynamic t WorkingOverride] -> Dynamic t (Overrides l) destructWorkingOverridesDyn = fmap (Overrides . CT.fromFlatList . catMaybes) . sequenceA . (fmap . fmap) (\(k, v) -> (k,) <$> unConfigValue v) destructWorkingOverrides :: [WorkingOverride] -> Overrides l destructWorkingOverrides = Overrides . CT.fromFlatList . M.catMaybes . fmap (\(k, v) -> (k,) <$> unConfigValue v) unConfigValue :: ConfigValue te -> Maybe (OverrideValue' te) unConfigValue (DefaultConfigValue _) = Nothing unConfigValue (CustomConfigValue (Left (CustomKey te))) = Just $ ValueAdded te unConfigValue (CustomConfigValue (Right (CustomValue te))) = Just $ ValueAdded te unConfigValue (CustomConfigValue (Right (DeletedValue _))) = Just ValueDeleted constructWorkingOverrides :: Ord te => DefaultConfig' te l -> Overrides' te l -> WorkingOverrides' te constructWorkingOverrides (DefaultConfig defCT) (Overrides newCT) = CT.catMaybes $ CT.zip newCT defCT <&> \case That x -> Just $ DefaultConfigValue x This x -> case x of ValueDeleted -> Nothing ValueAdded v -> Just $ CustomConfigValue $ Left $ CustomKey v These ValueDeleted v -> Just $ CustomConfigValue $ Right $ DeletedValue $ Just v These (ValueAdded v) _ -> Just $ CustomConfigValue $ Right $ CustomValue v
null
https://raw.githubusercontent.com/typeable/octopod/379c6ea69286dffb202c7904af72d05d9b9f46d6/octopod-frontend/src/Data/WorkingOverrides.hs
haskell
| The id of the predicate used for caching
module Data.WorkingOverrides ( WorkingOverrides, WorkingOverrideKey' (..), getConfigValueText, WorkingOverrideKey, WorkingOverrideKeyType (..), destructWorkingOverrides, constructWorkingOverrides, ConfigValue (..), CustomKey (..), CustomConfigValue (..), WorkingConfigTree, WorkingOverride, WorkingOverride', configTreeHasLeaf, destructWorkingOverridesDyn, ) where import Common.Orphans () import Common.Types import Control.Monad.Reader import Control.Monad.Ref import Data.ConfigTree (ConfigTree) import qualified Data.ConfigTree as CT import Data.Foldable import Data.Functor import Data.Map (Map) import qualified Data.Map as M import Data.Maybe (catMaybes) import qualified Data.Maybe as M import Data.Text (Text) import Data.These import GHC.Generics (Generic) import Reflex type WorkingConfigTree k v = ConfigTree k (ConfigValue v) data ConfigValue te = DefaultConfigValue !te | CustomConfigValue !(Either (CustomKey te) (CustomConfigValue te)) deriving stock (Show, Generic, Eq, Ord) newtype CustomKey v = CustomKey v deriving stock (Show, Generic, Eq, Ord) data CustomConfigValue te = CustomValue !te | DeletedValue !(Maybe te) deriving stock (Show, Generic, Eq, Ord) getConfigValueText :: ConfigValue te -> Maybe te getConfigValueText (DefaultConfigValue t) = Just t getConfigValueText (CustomConfigValue (Left (CustomKey t))) = Just t getConfigValueText (CustomConfigValue (Right (CustomValue t))) = Just t getConfigValueText (CustomConfigValue (Right (DeletedValue t))) = t Super inefficient but i do nt care configTreeHasLeaf :: forall m kv te. ( MonadReader (Ref m (Map (Text, ConfigTree kv te) Bool)) m , MonadRef m , Ord kv , Ord te ) => Text -> (te -> Bool) -> ConfigTree kv te -> m Bool configTreeHasLeaf name f = memo (\(_, CT.ConfigTree x) -> go $ toList x) . (name,) where go :: [(Maybe te, ConfigTree kv te)] -> m Bool go [] = pure False go ((Just y, _) : _) | f y = pure True go ((_, ct) : rest) = configTreeHasLeaf name f ct >>= \case True -> pure True False -> go rest memo :: (MonadReader (Ref m (Map x y)) m, Ord x, MonadRef m) => (x -> m y) -> x -> m y memo f x = do memoRef <- ask m <- readRef memoRef case M.lookup x m of Just y -> pure y Nothing -> do y <- f x modifyRef memoRef $ M.insert x y pure y type WorkingOverrides = WorkingOverrides' Text type WorkingOverrides' te = ConfigTree te (ConfigValue te) type WorkingOverride = WorkingOverride' Text type WorkingOverride' te = (te, ConfigValue te) type WorkingOverrideKey = WorkingOverrideKey' Text data WorkingOverrideKey' te = WorkingOverrideKey !WorkingOverrideKeyType !te deriving stock (Show) data WorkingOverrideKeyType = CustomWorkingOverrideKey | DefaultWorkingOverrideKey deriving stock (Show, Eq) destructWorkingOverridesDyn :: Reflex t => [Dynamic t WorkingOverride] -> Dynamic t (Overrides l) destructWorkingOverridesDyn = fmap (Overrides . CT.fromFlatList . catMaybes) . sequenceA . (fmap . fmap) (\(k, v) -> (k,) <$> unConfigValue v) destructWorkingOverrides :: [WorkingOverride] -> Overrides l destructWorkingOverrides = Overrides . CT.fromFlatList . M.catMaybes . fmap (\(k, v) -> (k,) <$> unConfigValue v) unConfigValue :: ConfigValue te -> Maybe (OverrideValue' te) unConfigValue (DefaultConfigValue _) = Nothing unConfigValue (CustomConfigValue (Left (CustomKey te))) = Just $ ValueAdded te unConfigValue (CustomConfigValue (Right (CustomValue te))) = Just $ ValueAdded te unConfigValue (CustomConfigValue (Right (DeletedValue _))) = Just ValueDeleted constructWorkingOverrides :: Ord te => DefaultConfig' te l -> Overrides' te l -> WorkingOverrides' te constructWorkingOverrides (DefaultConfig defCT) (Overrides newCT) = CT.catMaybes $ CT.zip newCT defCT <&> \case That x -> Just $ DefaultConfigValue x This x -> case x of ValueDeleted -> Nothing ValueAdded v -> Just $ CustomConfigValue $ Left $ CustomKey v These ValueDeleted v -> Just $ CustomConfigValue $ Right $ DeletedValue $ Just v These (ValueAdded v) _ -> Just $ CustomConfigValue $ Right $ CustomValue v
9148ec22e2b459926da32419b6d489388e92fdeabd2faff262d8e72a7ef5d92b
graninas/Functional-Design-and-Architecture
Runtime.hs
module Andromeda.Hardware.Impl.Runtime ( ) where
null
https://raw.githubusercontent.com/graninas/Functional-Design-and-Architecture/5046a3b9cd1d0ef90054c99933c846dc5068c7ad/Second-Edition-Manning-Publications/BookSamples/CH04/Section4p2/src/Andromeda/Hardware/Impl/Runtime.hs
haskell
module Andromeda.Hardware.Impl.Runtime ( ) where
a5f284a9be985c74d53c1f9b76f47e349376c9a58016651af8107e2611cfcf38
diffusionkinetics/open
Setup.hs
{-# LANGUAGE OverloadedStrings #-} module Dampf.Postgres.Setup where import Control.Lens import Control.Monad import Control.Monad.Catch (MonadThrow, throwM) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.List import qualified Data.Text as T import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.Types import Dampf.Postgres.Connect import Dampf.Types createUsers :: (MonadIO m, MonadThrow m) => DampfT m () createUsers = do ms <- view (config . postgres) ds <- view (app . databases) case ms of Just s -> iforM_ ds $ \name spec -> do conn <- createSuperUserPostgresConn let pass = lookupPassword (spec ^. user) s liftIO $ do rls <- query conn "SELECT rolname FROM pg_roles WHERE rolname = ?" (Only $ spec ^. user) case rls :: [Only String] of [] -> void $ execute conn "CREATE USER ? WITH PASSWORD ?" (Identifier $ spec ^. user, pass) _ -> return () destroyConn conn Nothing -> throwM NoDatabaseServer createExtensions :: (MonadIO m, MonadThrow m) => DampfT m () createExtensions = do ms <- view (config . postgres) ds <- view (app . databases) case ms of Just _ -> iforM_ ds $ \name spec -> do conn <- createSuperUserConn name let exts = nub $ spec ^. extensions liftIO . forM_ exts $ \ext -> void $ execute conn "CREATE EXTENSION IF NOT EXISTS ?" (Only $ Identifier ext) destroyConn conn Nothing -> throwM NoDatabaseServer createDatabases :: (MonadIO m, MonadThrow m) => DampfT m () createDatabases = do ms <- view (config . postgres) ds <- view (app . databases) case ms of Just _ -> iforM_ ds $ \name spec -> do conn <- createSuperUserPostgresConn liftIO $ do dbs <- query conn "SELECT datname FROM pg_database WHERE datname = ?" (Only $ T.unpack name) case dbs :: [Only String] of [] -> do void $ execute conn "CREATE DATABASE ?" (Only $ Identifier name) void $ execute conn "GRANT ALL PRIVILEGES ON DATABASE ? TO ?" (Identifier name, Identifier $ spec ^. user) _ -> return () destroyConn conn Nothing -> throwM NoDatabaseServer
null
https://raw.githubusercontent.com/diffusionkinetics/open/673d9a4a099abd9035ccc21e37d8e614a45a1901/dampf/lib/Dampf/Postgres/Setup.hs
haskell
# LANGUAGE OverloadedStrings #
module Dampf.Postgres.Setup where import Control.Lens import Control.Monad import Control.Monad.Catch (MonadThrow, throwM) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.List import qualified Data.Text as T import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.Types import Dampf.Postgres.Connect import Dampf.Types createUsers :: (MonadIO m, MonadThrow m) => DampfT m () createUsers = do ms <- view (config . postgres) ds <- view (app . databases) case ms of Just s -> iforM_ ds $ \name spec -> do conn <- createSuperUserPostgresConn let pass = lookupPassword (spec ^. user) s liftIO $ do rls <- query conn "SELECT rolname FROM pg_roles WHERE rolname = ?" (Only $ spec ^. user) case rls :: [Only String] of [] -> void $ execute conn "CREATE USER ? WITH PASSWORD ?" (Identifier $ spec ^. user, pass) _ -> return () destroyConn conn Nothing -> throwM NoDatabaseServer createExtensions :: (MonadIO m, MonadThrow m) => DampfT m () createExtensions = do ms <- view (config . postgres) ds <- view (app . databases) case ms of Just _ -> iforM_ ds $ \name spec -> do conn <- createSuperUserConn name let exts = nub $ spec ^. extensions liftIO . forM_ exts $ \ext -> void $ execute conn "CREATE EXTENSION IF NOT EXISTS ?" (Only $ Identifier ext) destroyConn conn Nothing -> throwM NoDatabaseServer createDatabases :: (MonadIO m, MonadThrow m) => DampfT m () createDatabases = do ms <- view (config . postgres) ds <- view (app . databases) case ms of Just _ -> iforM_ ds $ \name spec -> do conn <- createSuperUserPostgresConn liftIO $ do dbs <- query conn "SELECT datname FROM pg_database WHERE datname = ?" (Only $ T.unpack name) case dbs :: [Only String] of [] -> do void $ execute conn "CREATE DATABASE ?" (Only $ Identifier name) void $ execute conn "GRANT ALL PRIVILEGES ON DATABASE ? TO ?" (Identifier name, Identifier $ spec ^. user) _ -> return () destroyConn conn Nothing -> throwM NoDatabaseServer
9a1da30600e092e951c830b959bbc322acc3e6111237ff37a299d8edcb441893
winny-/aoc
day12.rkt
#lang debug racket (require racket/hash) (define/contract (small? cave) (symbol? . -> . boolean?) (define s (symbol->string cave)) (string=? s (string-downcase s))) (define (read2 ip) (match (read-line ip) [(? eof-object? e) e] [(regexp "([A-Za-z]+)-([A-Za-z]+)" (list _ start end)) (cons (string->symbol start) (string->symbol end))])) (define (dfs graph can-visit-twice) (let loop ([vertex 'start] [visited (set)] [smol-twice #f] [num 0]) (define all-edges (hash-ref graph vertex (const (set)))) (define edges (set-subtract all-edges (if (or smol-twice (not can-visit-twice)) visited (for/set ([v visited] #:when (not (small? v))) v)))) (for/fold ([acc num]) ([next edges]) (match next ['end (add1 acc)] [(? small?) (loop next (set-add visited next) (or smol-twice (set-member? visited next)) acc)] [_ (loop next visited smol-twice acc)])))) (define (part1 graph) (dfs graph #f)) (define (part2 graph) (dfs graph #t)) (module+ main (define ls (port->list read2)) (define graph (for/fold ([acc (hasheq)]) ([edge (in-list ls)]) (match-define (cons start end) edge) ;; Omit some edges and vertices that do not make sense. (define/match (create-singleton-hash e-start e-end) [('end _) (hasheq)] [(_ 'start) (hasheq e-start (set))] [('start _) (hasheq e-start (set e-end))] [(_ 'end) (hasheq e-start (set e-end))] [(_ _) (hasheq e-start (set e-end) e-end (set e-start))]) (hash-union acc (create-singleton-hash start end) (create-singleton-hash end start) #:combine set-union))) (part1 graph) (part2 graph)) ;; Local Variables: ;; compile-command: "racket day12.rkt < sample.txt" ;; End:
null
https://raw.githubusercontent.com/winny-/aoc/4cb005eb370d355b7a092094e431cda1e5a652a1/2021/day12/day12.rkt
racket
Omit some edges and vertices that do not make sense. Local Variables: compile-command: "racket day12.rkt < sample.txt" End:
#lang debug racket (require racket/hash) (define/contract (small? cave) (symbol? . -> . boolean?) (define s (symbol->string cave)) (string=? s (string-downcase s))) (define (read2 ip) (match (read-line ip) [(? eof-object? e) e] [(regexp "([A-Za-z]+)-([A-Za-z]+)" (list _ start end)) (cons (string->symbol start) (string->symbol end))])) (define (dfs graph can-visit-twice) (let loop ([vertex 'start] [visited (set)] [smol-twice #f] [num 0]) (define all-edges (hash-ref graph vertex (const (set)))) (define edges (set-subtract all-edges (if (or smol-twice (not can-visit-twice)) visited (for/set ([v visited] #:when (not (small? v))) v)))) (for/fold ([acc num]) ([next edges]) (match next ['end (add1 acc)] [(? small?) (loop next (set-add visited next) (or smol-twice (set-member? visited next)) acc)] [_ (loop next visited smol-twice acc)])))) (define (part1 graph) (dfs graph #f)) (define (part2 graph) (dfs graph #t)) (module+ main (define ls (port->list read2)) (define graph (for/fold ([acc (hasheq)]) ([edge (in-list ls)]) (match-define (cons start end) edge) (define/match (create-singleton-hash e-start e-end) [('end _) (hasheq)] [(_ 'start) (hasheq e-start (set))] [('start _) (hasheq e-start (set e-end))] [(_ 'end) (hasheq e-start (set e-end))] [(_ _) (hasheq e-start (set e-end) e-end (set e-start))]) (hash-union acc (create-singleton-hash start end) (create-singleton-hash end start) #:combine set-union))) (part1 graph) (part2 graph))
3eff13387fe40954bda87ba67625f92d229af3ffaece5af33e0452c61518eb22
james-iohk/plutus-scripts
NFTMint.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE MultiParamTypeClasses # # LANGUAGE NoImplicitPrelude # # LANGUAGE OverloadedStrings # {-# LANGUAGE RankNTypes #-} # LANGUAGE RecordWildCards # {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} module NFTMint ( printRedeemer, serialisedScript, scriptSBS, script, writeSerialisedScript, ) where import Cardano.Api (PlutusScript, PlutusScriptV2, writeFileTextEnvelope) import Cardano.Api.Shelley (PlutusScript (..), ScriptDataJsonSchema (ScriptDataJsonDetailedSchema), fromPlutusData, scriptDataToJson) import Codec.Serialise import Data.Aeson as A import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Short as SBS import Data.Functor (void) import qualified Ledger.Typed.Scripts as Scripts import Ledger.Value as Value import qualified Plutus.Script.Utils.V2.Typed.Scripts as PSU.V2 import qualified Plutus.V1.Ledger.Api as PlutusV1 import qualified Plutus.V2.Ledger.Api as PlutusV2 import Plutus.V2.Ledger.Contexts (ownCurrencySymbol) import qualified PlutusTx import PlutusTx.Prelude as P hiding (Semigroup (..), unless, (.)) import Prelude (IO, Semigroup (..), Show (..), print, (.)) data NFTParams = NFTParams -- doesn't need more than the TxOutRef mpTokenName : : ! . mpAmount :: !Integer , mpTxOutRef :: !PlutusV2.TxOutRef , : : ! . PubKeyHash } deriving Show PlutusTx.makeLift ''NFTParams PlutusTx.unstableMakeIsData ''NFTParams redeemer :: NFTParams redeemer = NFTParams { mpAmount = 1, mpTxOutRef = PlutusV2.TxOutRef {txOutRefId = "82669eddc629c8ce5cc3cb908cec6de339281bb0a0ec111880ff0936132ac8b0", txOutRefIdx = 0} } printRedeemer = print $ "Redeemer: " <> A.encode (scriptDataToJson ScriptDataJsonDetailedSchema $ fromPlutusData $ PlutusV2.toData redeemer) {-# INLINABLE mkPolicy #-} mkPolicy :: NFTParams -> BuiltinData -> PlutusV2.ScriptContext -> Bool mkPolicy p _ ctx = traceIfFalse "UTxO not consumed" hasUTxO && traceIfFalse "wrong amount minted" checkNFTAmount where info :: PlutusV2.TxInfo info = PlutusV2.scriptContextTxInfo ctx hasUTxO :: Bool hasUTxO = any (\i -> PlutusV2.txInInfoOutRef i == mpTxOutRef p) $ PlutusV2.txInfoInputs info checkNFTAmount :: Bool checkNFTAmount = case Value.flattenValue (PlutusV2.txInfoMint info) of [(cs, tn', amt)] -> cs == ownCurrencySymbol ctx && tn' == PlutusV2.TokenName "" && amt == 1 _ -> False {- As a Minting Policy -} policy :: NFTParams -> Scripts.MintingPolicy policy mp = PlutusV2.mkMintingPolicyScript $ $$(PlutusTx.compile [|| wrap ||]) `PlutusTx.applyCode` PlutusTx.liftCode mp where wrap mp' = Scripts.mkUntypedMintingPolicy $ mkPolicy mp' {- As a Script -} script :: PlutusV2.Script script = PlutusV2.unMintingPolicyScript $ policy redeemer {- As a Short Byte String -} scriptSBS :: SBS.ShortByteString scriptSBS = SBS.toShort . LBS.toStrict $ serialise script {- As a Serialised Script -} serialisedScript :: PlutusScript PlutusScriptV2 serialisedScript = PlutusScriptSerialised scriptSBS writeSerialisedScript :: IO () writeSerialisedScript = void $ writeFileTextEnvelope "nft-mint-V2.plutus" Nothing serialisedScript
null
https://raw.githubusercontent.com/james-iohk/plutus-scripts/d504776f14be3d127837702068e5b5c3a1b935eb/src/NFTMint.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE DeriveAnyClass # # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE RankNTypes # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeOperators # doesn't need more than the TxOutRef # INLINABLE mkPolicy # As a Minting Policy As a Script As a Short Byte String As a Serialised Script
# LANGUAGE MultiParamTypeClasses # # LANGUAGE NoImplicitPrelude # # LANGUAGE OverloadedStrings # # LANGUAGE RecordWildCards # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # module NFTMint ( printRedeemer, serialisedScript, scriptSBS, script, writeSerialisedScript, ) where import Cardano.Api (PlutusScript, PlutusScriptV2, writeFileTextEnvelope) import Cardano.Api.Shelley (PlutusScript (..), ScriptDataJsonSchema (ScriptDataJsonDetailedSchema), fromPlutusData, scriptDataToJson) import Codec.Serialise import Data.Aeson as A import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Short as SBS import Data.Functor (void) import qualified Ledger.Typed.Scripts as Scripts import Ledger.Value as Value import qualified Plutus.Script.Utils.V2.Typed.Scripts as PSU.V2 import qualified Plutus.V1.Ledger.Api as PlutusV1 import qualified Plutus.V2.Ledger.Api as PlutusV2 import Plutus.V2.Ledger.Contexts (ownCurrencySymbol) import qualified PlutusTx import PlutusTx.Prelude as P hiding (Semigroup (..), unless, (.)) import Prelude (IO, Semigroup (..), Show (..), print, (.)) mpTokenName : : ! . mpAmount :: !Integer , mpTxOutRef :: !PlutusV2.TxOutRef , : : ! . PubKeyHash } deriving Show PlutusTx.makeLift ''NFTParams PlutusTx.unstableMakeIsData ''NFTParams redeemer :: NFTParams redeemer = NFTParams { mpAmount = 1, mpTxOutRef = PlutusV2.TxOutRef {txOutRefId = "82669eddc629c8ce5cc3cb908cec6de339281bb0a0ec111880ff0936132ac8b0", txOutRefIdx = 0} } printRedeemer = print $ "Redeemer: " <> A.encode (scriptDataToJson ScriptDataJsonDetailedSchema $ fromPlutusData $ PlutusV2.toData redeemer) mkPolicy :: NFTParams -> BuiltinData -> PlutusV2.ScriptContext -> Bool mkPolicy p _ ctx = traceIfFalse "UTxO not consumed" hasUTxO && traceIfFalse "wrong amount minted" checkNFTAmount where info :: PlutusV2.TxInfo info = PlutusV2.scriptContextTxInfo ctx hasUTxO :: Bool hasUTxO = any (\i -> PlutusV2.txInInfoOutRef i == mpTxOutRef p) $ PlutusV2.txInfoInputs info checkNFTAmount :: Bool checkNFTAmount = case Value.flattenValue (PlutusV2.txInfoMint info) of [(cs, tn', amt)] -> cs == ownCurrencySymbol ctx && tn' == PlutusV2.TokenName "" && amt == 1 _ -> False policy :: NFTParams -> Scripts.MintingPolicy policy mp = PlutusV2.mkMintingPolicyScript $ $$(PlutusTx.compile [|| wrap ||]) `PlutusTx.applyCode` PlutusTx.liftCode mp where wrap mp' = Scripts.mkUntypedMintingPolicy $ mkPolicy mp' script :: PlutusV2.Script script = PlutusV2.unMintingPolicyScript $ policy redeemer scriptSBS :: SBS.ShortByteString scriptSBS = SBS.toShort . LBS.toStrict $ serialise script serialisedScript :: PlutusScript PlutusScriptV2 serialisedScript = PlutusScriptSerialised scriptSBS writeSerialisedScript :: IO () writeSerialisedScript = void $ writeFileTextEnvelope "nft-mint-V2.plutus" Nothing serialisedScript
fc575c6b4a3b6ccb110e8729f914782b849a7a41dffaa81588f6cbfeb7805be2
discus-lang/ddc
DaConDiscus.hs
module DDC.Core.Discus.Prim.DaConDiscus ( typeDaConDiscus , readDaConDiscus) where import DDC.Core.Discus.Prim.Base import DDC.Core.Discus.Prim.TyConDiscus import DDC.Type.Exp.Simple import DDC.Data.Pretty import Control.DeepSeq import Data.Char import Data.List instance NFData DaConDiscus where rnf !_ = () instance Pretty DaConDiscus where ppr dc = case dc of DaConDiscusTuple n -> text "T" <> int n <> text "#" -- | Read the name of a baked-in data constructor. readDaConDiscus :: String -> Maybe DaConDiscus readDaConDiscus str | Just rest <- stripPrefix "T" str , (ds, "#") <- span isDigit rest , not $ null ds , arity <- read ds = Just $ DaConDiscusTuple arity | otherwise = Nothing -- | Yield the type of a baked-in data constructor. typeDaConDiscus :: DaConDiscus -> Type Name typeDaConDiscus (DaConDiscusTuple n) = tForalls (replicate n kData) $ \args -> foldr tFun (tTupleN args) args
null
https://raw.githubusercontent.com/discus-lang/ddc/2baa1b4e2d43b6b02135257677671a83cb7384ac/src/s1/ddc-core-discus/DDC/Core/Discus/Prim/DaConDiscus.hs
haskell
| Read the name of a baked-in data constructor. | Yield the type of a baked-in data constructor.
module DDC.Core.Discus.Prim.DaConDiscus ( typeDaConDiscus , readDaConDiscus) where import DDC.Core.Discus.Prim.Base import DDC.Core.Discus.Prim.TyConDiscus import DDC.Type.Exp.Simple import DDC.Data.Pretty import Control.DeepSeq import Data.Char import Data.List instance NFData DaConDiscus where rnf !_ = () instance Pretty DaConDiscus where ppr dc = case dc of DaConDiscusTuple n -> text "T" <> int n <> text "#" readDaConDiscus :: String -> Maybe DaConDiscus readDaConDiscus str | Just rest <- stripPrefix "T" str , (ds, "#") <- span isDigit rest , not $ null ds , arity <- read ds = Just $ DaConDiscusTuple arity | otherwise = Nothing typeDaConDiscus :: DaConDiscus -> Type Name typeDaConDiscus (DaConDiscusTuple n) = tForalls (replicate n kData) $ \args -> foldr tFun (tTupleN args) args
290f602dca200dfb16f6d090baed71a3ede832fddeb1154498867608d5398bb3
flexsurfer/re-frisk
protocols.cljs
(ns ^{:mranderson/inlined true} re-frisk.inlined-deps.reagent.v1v0v0.reagent.impl.protocols) (defprotocol Compiler (get-id [this]) (as-element [this x]) (make-element [this argv component jsprops first-child]))
null
https://raw.githubusercontent.com/flexsurfer/re-frisk/638d820c84e23be79b8c52f8f136a611d942443f/re-frisk/src/re_frisk/inlined_deps/reagent/v1v0v0/reagent/impl/protocols.cljs
clojure
(ns ^{:mranderson/inlined true} re-frisk.inlined-deps.reagent.v1v0v0.reagent.impl.protocols) (defprotocol Compiler (get-id [this]) (as-element [this x]) (make-element [this argv component jsprops first-child]))
9b37688a2b0d812d5b43d4f26eb9b62aa48b39a06c37f7b0e8e5a142d9f91084
haskell-works/oops
Oops.hs
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE BlockArguments # {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE EmptyCase #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # {-# LANGUAGE GADTs #-} # LANGUAGE InstanceSigs # # LANGUAGE LambdaCase # # LANGUAGE PolyKinds # {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} # LANGUAGE TypeApplications # # LANGUAGE TypeFamilyDependencies # {-# LANGUAGE TypeOperators #-} # LANGUAGE UndecidableInstances # module Control.Monad.Oops ( -- * MTL/transformer utilities catchF, catch, throwF, throw, snatchF, snatch, runOops, runOopsInExceptT, runOopsInEither, suspend, catchOrMap, catchAsLeft, catchAsNothing, catchAndExitFailure, hoistEither, hoistMaybe, onLeftThrow, onNothingThrow, onLeft, onNothing, recover, recoverOrVoid, onExceptionThrow, onException, CouldBeF, CouldBe, CouldBeAnyOfF, CouldBeAnyOf, Variant, VariantF, ) where import Control.Monad.Error.Class (MonadError (..)) import Control.Monad.Except (ExceptT(ExceptT)) import Control.Monad.IO.Class (MonadIO(liftIO)) import Control.Monad.Trans.Except (mapExceptT, runExceptT) import Data.Bifunctor (first) import Data.Functor.Identity (Identity (..)) import Data.Variant (Catch, CatchF, CouldBe, CouldBeAnyOf, CouldBeAnyOfF, CouldBeF, Variant, VariantF) import Data.Void (Void, absurd) import qualified Control.Monad.Catch as CMC import qualified Data.Variant as DV import qualified System.Exit as IO -- | When working in some monadic context, using 'catch' becomes trickier. The -- intuitive behaviour is that each 'catch' shrinks the variant in the left -- side of my 'MonadError', but this is therefore type-changing: as we can only ' throwError ' and ' ' with a ' MonadError ' type , this is impossible ! -- -- To get round this problem, we have to specialise to 'ExceptT', which allows -- us to map over the error type and change it as we go. If the error we catch -- is the one in the variant that we want to handle, we pluck it out and deal -- with it. Otherwise, we "re-throw" the variant minus the one we've handled. catchF :: forall x e e' f m a. () => Monad m => CatchF x e e' => (f x -> ExceptT (VariantF f e') m a) -> ExceptT (VariantF f e ) m a -> ExceptT (VariantF f e') m a catchF h xs = mapExceptT (>>= go) xs where go = \case Right success -> pure (Right success) Left failure -> case DV.catchF @x failure of Right hit -> runExceptT (h hit) Left miss -> pure (Left miss) -- | Just the same as 'catchF', but specialised for our plain 'Variant' and -- sounding much less like a radio station. catch :: forall x e e' m a. () => Monad m => Catch x e e' => (x -> ExceptT (Variant e') m a) -> ExceptT (Variant e ) m a -> ExceptT (Variant e') m a catch h xs = catchF (h . runIdentity) xs -- | Same as 'catchF' except the error is not removed from the type. -- This is useful for writing recursive computations or computations that -- rethrow the same error type. snatchF :: forall x e f m a. () => Monad m => e `CouldBe` x => (f x -> ExceptT (VariantF f e) m a) -> ExceptT (VariantF f e) m a -> ExceptT (VariantF f e) m a snatchF h xs = mapExceptT (>>= go) xs where go = \case Right success -> pure (Right success) Left failure -> case DV.snatchF @_ @_ @x failure of Right hit -> runExceptT (h hit) Left miss -> pure (Left miss) -- | Same as 'catch' except the error is not removed from the type. -- This is useful for writing recursive computations or computations that -- rethrow the same error type. snatch :: forall x e m a. () => Monad m => e `CouldBe` x => (x -> ExceptT (Variant e) m a) -> ExceptT (Variant e) m a -> ExceptT (Variant e) m a snatch h xs = snatchF (h . runIdentity) xs | Throw an error into a variant ' MonadError ' context . Note that this /isn't/ -- type-changing, so this can work for any 'MonadError', rather than just -- 'ExceptT'. throwF :: forall x e f m a. () => MonadError (VariantF f e) m => e `CouldBe` x => f x -> m a throwF = throwError . DV.throwF | Same as ' throwF ' , but without the @f@ context . Given a value of some type -- within a 'Variant' within a 'MonadError' context, "throw" the error. throw :: forall x e m a. () => MonadError (Variant e) m => e `CouldBe` x => x -> m a throw = throwF . Identity -- | Add 'ExceptT (Variant '[])' to the monad transformer stack. runOops :: () => Monad m => ExceptT (Variant '[]) m a -> m a runOops f = either (absurd . DV.preposterous) pure =<< runExceptT f | Run an oops expression that throws one error in an ExceptT. runOopsInExceptT :: forall x m a. Monad m => ExceptT (Variant '[x]) m a -> ExceptT x m a runOopsInExceptT = mapExceptT (fmap (first DV.toEithers)) | Run an oops expression that throws one error in an Either . -- -- This function can also be implemented this way (which could be instructive for implementing -- your own combinators) runOopsInEither :: forall x m a. Monad m => ExceptT (Variant '[x]) m a -> m (Either x a) runOopsInEither = runExceptT . mapExceptT (fmap (first DV.toEithers)) -- | Suspend the 'ExceptT` monad transformer from the top of the stack so that the -- stack can be manipulated without the 'ExceptT` layer. suspend :: forall x m a n b. () => (m (Either x a) -> n (Either x b)) -> ExceptT x m a -> ExceptT x n b suspend f = ExceptT . f . runExceptT -- | Catch the specified exception and return the caught value as 'Left'. If no -- value was caught, then return the returned value in 'Right'. catchOrMap :: forall x a e' m b. Monad m => (b -> a) -> (x -> ExceptT (Variant e') m a) -> ExceptT (Variant (x : e')) m b -> ExceptT (Variant e') m a catchOrMap g h = catch h . fmap g -- | Catch the specified exception and return the caught value as 'Left'. If no -- value was caught, then return the returned value in 'Right'. catchAsLeft :: forall x e m a. () => Monad m => ExceptT (Variant (x : e)) m a -> ExceptT (Variant e) m (Either x a) catchAsLeft = catchOrMap Right (pure . Left) -- | Catch the specified exception and return 'Nothing'. If no -- value was caught, then return the returned value in 'Just'. catchAsNothing :: forall x e m a. () => Monad m => ExceptT (Variant (x : e)) m a -> ExceptT (Variant e) m (Maybe a) catchAsNothing = catchOrMap Just (pure . (const Nothing)) -- | Catch the specified exception. If that exception is caught, exit the program. catchAndExitFailure :: forall x e m a. () => MonadIO m => ExceptT (Variant (x : e)) m a -> ExceptT (Variant e) m a catchAndExitFailure = catch @x (const (liftIO IO.exitFailure)) -- | When the expression of type 'Either x a' evaluates to 'Left x', throw the 'x', -- otherwise return 'a'. hoistEither :: forall x e m a. () => MonadError (Variant e) m => CouldBeF e x => Monad m => Either x a -> m a hoistEither = either throw pure -- | When the expression of type 'Maybe a' evaluates to 'Nothing', throw the specified value, -- otherwise return 'a'. hoistMaybe :: forall e es m a. () => MonadError (Variant es) m => CouldBe es e => e -> Maybe a -> m a hoistMaybe e = maybe (throw e) pure -- | When the expression of type 'm (Either x a)' evaluates to 'pure (Left x)', throw the 'x', -- otherwise return 'a'. onLeftThrow :: forall x e m a. () => MonadError (Variant e) m => CouldBeF e x => m (Either x a) -> m a onLeftThrow f = f >>= hoistEither -- | When the expression of type 'Maybe a' evaluates to 'Nothing', throw the specified value, -- otherwise return 'a'. onNothingThrow :: forall e es m a. () => MonadError (Variant es) m => CouldBe es e => e -> m (Maybe a) -> m a onNothingThrow e f = f >>= hoistMaybe e -- | Handle the 'Left' constructor of the returned 'Either' onLeft :: forall x m a. () => Monad m => (x -> m a) -> m (Either x a) -> m a onLeft g f = f >>= either g pure -- | Handle the 'Nothing' constructor of the returned 'Maybe' onNothing :: forall m a. () => Monad m => m a -> m (Maybe a) -> m a onNothing g f = f >>= maybe g pure -- | Catch the specified exception and return it instead. -- The evaluated computation must return the same type that is being caught. recover :: forall x e m a. () => Monad m => (x -> a) -> ExceptT (Variant (x : e)) m a -> ExceptT (Variant e) m a recover f = catch (pure . f) -- | Catch the specified exception and return it instead. The evaluated computation -- must return `Void` (ie. it never returns) recoverOrVoid :: forall x e m. () => Monad m => ExceptT (Variant (x : e)) m Void -> ExceptT (Variant e) m x recoverOrVoid = catchOrMap @x absurd pure -- | Catch an exception of the specified type 'x' and throw it as an error onExceptionThrow :: forall x e m a. () => CMC.MonadCatch m => CMC.Exception x => MonadError (Variant e) m => CouldBeF e x => m a -> m a onExceptionThrow = onException @x throw -- | Catch an exception of the specified type 'x' and call the the handler 'h' onException :: forall x m a. () => CMC.MonadCatch m => CMC.Exception x => (x -> m a) -> m a -> m a onException h f = either h pure =<< CMC.try f
null
https://raw.githubusercontent.com/haskell-works/oops/3c44ed1f82c7f36f171656c1745977e82f7f0ce4/src/Control/Monad/Oops.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE DataKinds # # LANGUAGE EmptyCase # # LANGUAGE FlexibleContexts # # LANGUAGE GADTs # # LANGUAGE RankNTypes # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeOperators # * MTL/transformer utilities | When working in some monadic context, using 'catch' becomes trickier. The intuitive behaviour is that each 'catch' shrinks the variant in the left side of my 'MonadError', but this is therefore type-changing: as we can only To get round this problem, we have to specialise to 'ExceptT', which allows us to map over the error type and change it as we go. If the error we catch is the one in the variant that we want to handle, we pluck it out and deal with it. Otherwise, we "re-throw" the variant minus the one we've handled. | Just the same as 'catchF', but specialised for our plain 'Variant' and sounding much less like a radio station. | Same as 'catchF' except the error is not removed from the type. This is useful for writing recursive computations or computations that rethrow the same error type. | Same as 'catch' except the error is not removed from the type. This is useful for writing recursive computations or computations that rethrow the same error type. type-changing, so this can work for any 'MonadError', rather than just 'ExceptT'. within a 'Variant' within a 'MonadError' context, "throw" the error. | Add 'ExceptT (Variant '[])' to the monad transformer stack. This function can also be implemented this way (which could be instructive for implementing your own combinators) | Suspend the 'ExceptT` monad transformer from the top of the stack so that the stack can be manipulated without the 'ExceptT` layer. | Catch the specified exception and return the caught value as 'Left'. If no value was caught, then return the returned value in 'Right'. | Catch the specified exception and return the caught value as 'Left'. If no value was caught, then return the returned value in 'Right'. | Catch the specified exception and return 'Nothing'. If no value was caught, then return the returned value in 'Just'. | Catch the specified exception. If that exception is caught, exit the program. | When the expression of type 'Either x a' evaluates to 'Left x', throw the 'x', otherwise return 'a'. | When the expression of type 'Maybe a' evaluates to 'Nothing', throw the specified value, otherwise return 'a'. | When the expression of type 'm (Either x a)' evaluates to 'pure (Left x)', throw the 'x', otherwise return 'a'. | When the expression of type 'Maybe a' evaluates to 'Nothing', throw the specified value, otherwise return 'a'. | Handle the 'Left' constructor of the returned 'Either' | Handle the 'Nothing' constructor of the returned 'Maybe' | Catch the specified exception and return it instead. The evaluated computation must return the same type that is being caught. | Catch the specified exception and return it instead. The evaluated computation must return `Void` (ie. it never returns) | Catch an exception of the specified type 'x' and throw it as an error | Catch an exception of the specified type 'x' and call the the handler 'h'
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE BlockArguments # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE InstanceSigs # # LANGUAGE LambdaCase # # LANGUAGE PolyKinds # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilyDependencies # # LANGUAGE UndecidableInstances # module Control.Monad.Oops catchF, catch, throwF, throw, snatchF, snatch, runOops, runOopsInExceptT, runOopsInEither, suspend, catchOrMap, catchAsLeft, catchAsNothing, catchAndExitFailure, hoistEither, hoistMaybe, onLeftThrow, onNothingThrow, onLeft, onNothing, recover, recoverOrVoid, onExceptionThrow, onException, CouldBeF, CouldBe, CouldBeAnyOfF, CouldBeAnyOf, Variant, VariantF, ) where import Control.Monad.Error.Class (MonadError (..)) import Control.Monad.Except (ExceptT(ExceptT)) import Control.Monad.IO.Class (MonadIO(liftIO)) import Control.Monad.Trans.Except (mapExceptT, runExceptT) import Data.Bifunctor (first) import Data.Functor.Identity (Identity (..)) import Data.Variant (Catch, CatchF, CouldBe, CouldBeAnyOf, CouldBeAnyOfF, CouldBeF, Variant, VariantF) import Data.Void (Void, absurd) import qualified Control.Monad.Catch as CMC import qualified Data.Variant as DV import qualified System.Exit as IO ' throwError ' and ' ' with a ' MonadError ' type , this is impossible ! catchF :: forall x e e' f m a. () => Monad m => CatchF x e e' => (f x -> ExceptT (VariantF f e') m a) -> ExceptT (VariantF f e ) m a -> ExceptT (VariantF f e') m a catchF h xs = mapExceptT (>>= go) xs where go = \case Right success -> pure (Right success) Left failure -> case DV.catchF @x failure of Right hit -> runExceptT (h hit) Left miss -> pure (Left miss) catch :: forall x e e' m a. () => Monad m => Catch x e e' => (x -> ExceptT (Variant e') m a) -> ExceptT (Variant e ) m a -> ExceptT (Variant e') m a catch h xs = catchF (h . runIdentity) xs snatchF :: forall x e f m a. () => Monad m => e `CouldBe` x => (f x -> ExceptT (VariantF f e) m a) -> ExceptT (VariantF f e) m a -> ExceptT (VariantF f e) m a snatchF h xs = mapExceptT (>>= go) xs where go = \case Right success -> pure (Right success) Left failure -> case DV.snatchF @_ @_ @x failure of Right hit -> runExceptT (h hit) Left miss -> pure (Left miss) snatch :: forall x e m a. () => Monad m => e `CouldBe` x => (x -> ExceptT (Variant e) m a) -> ExceptT (Variant e) m a -> ExceptT (Variant e) m a snatch h xs = snatchF (h . runIdentity) xs | Throw an error into a variant ' MonadError ' context . Note that this /isn't/ throwF :: forall x e f m a. () => MonadError (VariantF f e) m => e `CouldBe` x => f x -> m a throwF = throwError . DV.throwF | Same as ' throwF ' , but without the @f@ context . Given a value of some type throw :: forall x e m a. () => MonadError (Variant e) m => e `CouldBe` x => x -> m a throw = throwF . Identity runOops :: () => Monad m => ExceptT (Variant '[]) m a -> m a runOops f = either (absurd . DV.preposterous) pure =<< runExceptT f | Run an oops expression that throws one error in an ExceptT. runOopsInExceptT :: forall x m a. Monad m => ExceptT (Variant '[x]) m a -> ExceptT x m a runOopsInExceptT = mapExceptT (fmap (first DV.toEithers)) | Run an oops expression that throws one error in an Either . runOopsInEither :: forall x m a. Monad m => ExceptT (Variant '[x]) m a -> m (Either x a) runOopsInEither = runExceptT . mapExceptT (fmap (first DV.toEithers)) suspend :: forall x m a n b. () => (m (Either x a) -> n (Either x b)) -> ExceptT x m a -> ExceptT x n b suspend f = ExceptT . f . runExceptT catchOrMap :: forall x a e' m b. Monad m => (b -> a) -> (x -> ExceptT (Variant e') m a) -> ExceptT (Variant (x : e')) m b -> ExceptT (Variant e') m a catchOrMap g h = catch h . fmap g catchAsLeft :: forall x e m a. () => Monad m => ExceptT (Variant (x : e)) m a -> ExceptT (Variant e) m (Either x a) catchAsLeft = catchOrMap Right (pure . Left) catchAsNothing :: forall x e m a. () => Monad m => ExceptT (Variant (x : e)) m a -> ExceptT (Variant e) m (Maybe a) catchAsNothing = catchOrMap Just (pure . (const Nothing)) catchAndExitFailure :: forall x e m a. () => MonadIO m => ExceptT (Variant (x : e)) m a -> ExceptT (Variant e) m a catchAndExitFailure = catch @x (const (liftIO IO.exitFailure)) hoistEither :: forall x e m a. () => MonadError (Variant e) m => CouldBeF e x => Monad m => Either x a -> m a hoistEither = either throw pure hoistMaybe :: forall e es m a. () => MonadError (Variant es) m => CouldBe es e => e -> Maybe a -> m a hoistMaybe e = maybe (throw e) pure onLeftThrow :: forall x e m a. () => MonadError (Variant e) m => CouldBeF e x => m (Either x a) -> m a onLeftThrow f = f >>= hoistEither onNothingThrow :: forall e es m a. () => MonadError (Variant es) m => CouldBe es e => e -> m (Maybe a) -> m a onNothingThrow e f = f >>= hoistMaybe e onLeft :: forall x m a. () => Monad m => (x -> m a) -> m (Either x a) -> m a onLeft g f = f >>= either g pure onNothing :: forall m a. () => Monad m => m a -> m (Maybe a) -> m a onNothing g f = f >>= maybe g pure recover :: forall x e m a. () => Monad m => (x -> a) -> ExceptT (Variant (x : e)) m a -> ExceptT (Variant e) m a recover f = catch (pure . f) recoverOrVoid :: forall x e m. () => Monad m => ExceptT (Variant (x : e)) m Void -> ExceptT (Variant e) m x recoverOrVoid = catchOrMap @x absurd pure onExceptionThrow :: forall x e m a. () => CMC.MonadCatch m => CMC.Exception x => MonadError (Variant e) m => CouldBeF e x => m a -> m a onExceptionThrow = onException @x throw onException :: forall x m a. () => CMC.MonadCatch m => CMC.Exception x => (x -> m a) -> m a -> m a onException h f = either h pure =<< CMC.try f
f48d923d3d9f2bdb99fd41f233b6036b37a52c9f1f2e355435bedfa229e61755
cmsc430/www
interp.rkt
#lang racket (provide interp) (require "ast.rkt" "interp-prim.rkt") ;; Expr -> Integer (define (interp e) (match e [(Int i) i] [(Prim1 p e) (interp-prim1 p (interp e))] [(IfZero e1 e2 e3) (if (zero? (interp e1)) (interp e2) (interp e3))]))
null
https://raw.githubusercontent.com/cmsc430/www/0809867532b8ef516029ac38093a145db5b424ea/langs/con/interp.rkt
racket
Expr -> Integer
#lang racket (provide interp) (require "ast.rkt" "interp-prim.rkt") (define (interp e) (match e [(Int i) i] [(Prim1 p e) (interp-prim1 p (interp e))] [(IfZero e1 e2 e3) (if (zero? (interp e1)) (interp e2) (interp e3))]))
1465063ae907c9f25ba1f5e054b979718eaf002a1ac7075b118f8d91c35edbb0
FrankC01/clasew
examples5.clj
(ns ^{:author "Frank V. Castellucci" :doc "clasew example 5 - Apple Numbers Examples"} clasew.examples5 (:require [clasew.spreads :as cs] [clasew.numbers :as an] [clojure.pprint :refer :all]) ) ;;; Setup for the example (def p pprint) Demonstrate using Excel as a data store ;; ---------------- BASIC CALLING --------------------------------------------- (def sample1 (cs/clasew-script "clasew-ex5-sample1.numbers" cs/create cs/no-open "path to desktop" nil {:handler_list ["clasew_save_and_quit"] :arg_list [[]]})) ;(p sample1) ;(p (an/clasew-numbers-call! sample1)) (def sample1a (cs/clasew-script "clasew-ex5-sample1a.numbers" cs/create cs/no-open "path to desktop" (cs/create-parms :sheet_name "FY15" :table_list (cs/tables (cs/table :table_name "Q1 - Sales & Returns", :column_count 8, :row_count 10, :header_content ["Region","Sales", "Returns"]))) {:handler_list ["clasew_get_book_info","clasew_quit"] :arg_list [[],[]]})) ( ) ( p ( an / clasew - numbers - call ! ) ) ;; Handler Chaining - Create, put values, get first row, save, quit (def datum (into [] (map vec (for [i (range 5)] (repeatedly 5 #(rand-int 100)))))) ( ) (def sample2 (cs/clasew-script "clasew-ex5-sample2.numbers" cs/create cs/no-open "path to desktop" nil (cs/clasew-handler [[:put-range-data "Sheet 1" "A1:E5" datum] [:get-range-data "Sheet 1" "A1:A5"] [:save-quit]]))) ;(p sample2) ( p ( an / clasew - numbers - call ! ) ) (def sample2a (cs/clasew-script "clasew-ex5-sample2.numbers" cs/no-create cs/open "path to desktop" nil (cs/clasew-handler [[:get-range-formulas "Sheet 1" "used"] [:quit-no-save]]))) ;(p sample2a) ;(p (an/clasew-numbers-call! sample2a)) ;; Demo - Open, Read, Quit (def sample3 (cs/clasew-script "clasew-ex5-sample2.numbers" cs/no-create cs/open "path to desktop" nil (cs/clasew-handler [[:book-info] [:quit]]))) ( ) ( p ( an / clasew - numbers - call ! ) ) ;; Demo pushing your own agenda (def my_script "on run(caller, args) say \"I have control!\" return {my_script: \"No you don't\"} end run") (def sample4 (cs/clasew-script "clasew-ex5-sample2.numbers" cs/no-create cs/open "path to desktop" nil (cs/clasew-handler [[:run-script my_script []] [:quit]]))) ( p ( an / clasew - numbers - call ! ) ) ;; Demo HOF - Create, put values, get first row, save, quit (def wrkbk-name "clasew-ex5-sample5.numbers") (def wrkbk-path "path to desktop") (def sample5 (cs/create-wkbk wrkbk-name wrkbk-path (cs/chain-put-range-data "Sheet 1" datum) [:save-quit])) ; (p sample5) ( p ( an / clasew - numbers - call ! ) ) ( def s5r ( an / clasew - numbers - call ! ) ) ;; Demo misc forms ; Uniform collection (def uniform [[1 2 3] [4 5 6] [7 8 9]]) ; Jagged collection (def jagged [[1] [2 2] [3 3 3]]) (cs/format-range-a1 [0 0 0 9]) (cs/format-range-a1 [0 1 1 9]) (cs/formula-wrap "SUM" cs/format-range-a1 [0 0 0 9]) (cs/formula-wrap "AVG" cs/format-range-a1 [0 0 0 9]) (cs/fsum cs/format-range-a1 [0 0 0 9]) (cs/favg cs/format-range-a1 [0 0 0 9]) (cs/row-ranges uniform) (cs/row-ranges jagged) (cs/row-ranges (cs/pad-rows jagged)) (cs/column-ranges uniform) (cs/column-ranges jagged) (cs/column-ranges (cs/pad-rows jagged)) (map cs/format-range-a1 (cs/column-ranges uniform)) (map cs/format-range-a1 (cs/row-ranges uniform 4 3)) (map cs/format-range-a1 (cs/row-ranges jagged)) (cs/sum-by-row uniform) (cs/sum-by-col uniform) (cs/avg-by-row uniform) (cs/avg-by-col uniform) (cs/extend-rows uniform 0 0 cs/sum-by-row) (cs/extend-columns uniform 0 0 cs/avg-by-col) ;; Put it together (def sample5a (cs/create-wkbk "clasew-ex5-sample5a.numbers" wrkbk-path (cs/chain-put-range-data "Sheet 1" (cs/extend-columns (cs/extend-rows datum 0 0 cs/sum-by-row cs/avg-by-row) 0 0 cs/avg-by-col)) [:save-quit])) ;(p sample5a) ;(p (an/clasew-numbers-call! sample5a)) ;; Demo - cleaning up results (def sample6 (cs/open-wkbk wrkbk-name wrkbk-path [:all-book-info] [:quit])) ;(def s6r (cs/clean-result (an/clasew-numbers-call! sample6))) ;(p s6r) (def sample7 (cs/create-wkbk "clasew-ex5-sample7.numbers" wrkbk-path (cs/chain-add-sheet "First Add" :after "Sheet 1" "Before First Add" :before "First Add" "The End" :at :end (cs/tables (cs/table :table_name "First Table", :row_count 5, :column_count 5)) "The Beginning" :at :beginning "Towards last" :at 5) [:save-quit])) ( ) ( p ( cs / clean - result ( an / clasew - numbers - call ! ) ) ) (def sample8 (cs/open-wkbk "clasew-ex5-sample7.numbers" wrkbk-path (cs/chain-delete-sheet "Sheet 1"))) ( p ( cs / clean - result ( an / clasew - numbers - call ! ) ) )
null
https://raw.githubusercontent.com/FrankC01/clasew/1e5a444bccd4f34c68a1e5d1ec2121a36fd8c959/dev/src/clasew/examples5.clj
clojure
Setup for the example ---------------- BASIC CALLING --------------------------------------------- (p sample1) (p (an/clasew-numbers-call! sample1)) Handler Chaining - Create, put values, get first row, save, quit (p sample2) (p sample2a) (p (an/clasew-numbers-call! sample2a)) Demo - Open, Read, Quit Demo pushing your own agenda Demo HOF - Create, put values, get first row, save, quit (p sample5) Demo misc forms Uniform collection Jagged collection Put it together (p sample5a) (p (an/clasew-numbers-call! sample5a)) Demo - cleaning up results (def s6r (cs/clean-result (an/clasew-numbers-call! sample6))) (p s6r)
(ns ^{:author "Frank V. Castellucci" :doc "clasew example 5 - Apple Numbers Examples"} clasew.examples5 (:require [clasew.spreads :as cs] [clasew.numbers :as an] [clojure.pprint :refer :all]) ) (def p pprint) Demonstrate using Excel as a data store (def sample1 (cs/clasew-script "clasew-ex5-sample1.numbers" cs/create cs/no-open "path to desktop" nil {:handler_list ["clasew_save_and_quit"] :arg_list [[]]})) (def sample1a (cs/clasew-script "clasew-ex5-sample1a.numbers" cs/create cs/no-open "path to desktop" (cs/create-parms :sheet_name "FY15" :table_list (cs/tables (cs/table :table_name "Q1 - Sales & Returns", :column_count 8, :row_count 10, :header_content ["Region","Sales", "Returns"]))) {:handler_list ["clasew_get_book_info","clasew_quit"] :arg_list [[],[]]})) ( ) ( p ( an / clasew - numbers - call ! ) ) (def datum (into [] (map vec (for [i (range 5)] (repeatedly 5 #(rand-int 100)))))) ( ) (def sample2 (cs/clasew-script "clasew-ex5-sample2.numbers" cs/create cs/no-open "path to desktop" nil (cs/clasew-handler [[:put-range-data "Sheet 1" "A1:E5" datum] [:get-range-data "Sheet 1" "A1:A5"] [:save-quit]]))) ( p ( an / clasew - numbers - call ! ) ) (def sample2a (cs/clasew-script "clasew-ex5-sample2.numbers" cs/no-create cs/open "path to desktop" nil (cs/clasew-handler [[:get-range-formulas "Sheet 1" "used"] [:quit-no-save]]))) (def sample3 (cs/clasew-script "clasew-ex5-sample2.numbers" cs/no-create cs/open "path to desktop" nil (cs/clasew-handler [[:book-info] [:quit]]))) ( ) ( p ( an / clasew - numbers - call ! ) ) (def my_script "on run(caller, args) say \"I have control!\" return {my_script: \"No you don't\"} end run") (def sample4 (cs/clasew-script "clasew-ex5-sample2.numbers" cs/no-create cs/open "path to desktop" nil (cs/clasew-handler [[:run-script my_script []] [:quit]]))) ( p ( an / clasew - numbers - call ! ) ) (def wrkbk-name "clasew-ex5-sample5.numbers") (def wrkbk-path "path to desktop") (def sample5 (cs/create-wkbk wrkbk-name wrkbk-path (cs/chain-put-range-data "Sheet 1" datum) [:save-quit])) ( p ( an / clasew - numbers - call ! ) ) ( def s5r ( an / clasew - numbers - call ! ) ) (def uniform [[1 2 3] [4 5 6] [7 8 9]]) (def jagged [[1] [2 2] [3 3 3]]) (cs/format-range-a1 [0 0 0 9]) (cs/format-range-a1 [0 1 1 9]) (cs/formula-wrap "SUM" cs/format-range-a1 [0 0 0 9]) (cs/formula-wrap "AVG" cs/format-range-a1 [0 0 0 9]) (cs/fsum cs/format-range-a1 [0 0 0 9]) (cs/favg cs/format-range-a1 [0 0 0 9]) (cs/row-ranges uniform) (cs/row-ranges jagged) (cs/row-ranges (cs/pad-rows jagged)) (cs/column-ranges uniform) (cs/column-ranges jagged) (cs/column-ranges (cs/pad-rows jagged)) (map cs/format-range-a1 (cs/column-ranges uniform)) (map cs/format-range-a1 (cs/row-ranges uniform 4 3)) (map cs/format-range-a1 (cs/row-ranges jagged)) (cs/sum-by-row uniform) (cs/sum-by-col uniform) (cs/avg-by-row uniform) (cs/avg-by-col uniform) (cs/extend-rows uniform 0 0 cs/sum-by-row) (cs/extend-columns uniform 0 0 cs/avg-by-col) (def sample5a (cs/create-wkbk "clasew-ex5-sample5a.numbers" wrkbk-path (cs/chain-put-range-data "Sheet 1" (cs/extend-columns (cs/extend-rows datum 0 0 cs/sum-by-row cs/avg-by-row) 0 0 cs/avg-by-col)) [:save-quit])) (def sample6 (cs/open-wkbk wrkbk-name wrkbk-path [:all-book-info] [:quit])) (def sample7 (cs/create-wkbk "clasew-ex5-sample7.numbers" wrkbk-path (cs/chain-add-sheet "First Add" :after "Sheet 1" "Before First Add" :before "First Add" "The End" :at :end (cs/tables (cs/table :table_name "First Table", :row_count 5, :column_count 5)) "The Beginning" :at :beginning "Towards last" :at 5) [:save-quit])) ( ) ( p ( cs / clean - result ( an / clasew - numbers - call ! ) ) ) (def sample8 (cs/open-wkbk "clasew-ex5-sample7.numbers" wrkbk-path (cs/chain-delete-sheet "Sheet 1"))) ( p ( cs / clean - result ( an / clasew - numbers - call ! ) ) )
4cfb54c15acb390ed7a62e039a25ce770ffcf6733a1b0c292bcd2f2464c893fd
eamsden/pushbasedFRP
Main.hs
# LANGUAGE TypeOperators # module Main where import FRP.TimeFlies.SignalFunctions import Graphics.Gloss.Data.Picture import Graphics.Gloss.Interface.IO.Game import Prelude hiding (filter) import Stopwatch (timeTracker) import World (WorldSVIn, WorldSVOut, GlossEvent (..), playSF) input :: WorldSVIn :~> SVEvent () input = first ignore >>> cancelLeft >>> filter (\e -> case e of GlossEventKey (MouseButton _) Down _ -> Just () _ -> Nothing) output :: SVSignal Double :~> WorldSVOut output = pureSignalTransformer (color black . text . show) main :: IO () main = playSF (input >>> timeTracker 0 >>> output)
null
https://raw.githubusercontent.com/eamsden/pushbasedFRP/1d6afd7aa2e45f44b9daa4a2265338747a6aa443/Code/gloss-demo/src/Main.hs
haskell
# LANGUAGE TypeOperators # module Main where import FRP.TimeFlies.SignalFunctions import Graphics.Gloss.Data.Picture import Graphics.Gloss.Interface.IO.Game import Prelude hiding (filter) import Stopwatch (timeTracker) import World (WorldSVIn, WorldSVOut, GlossEvent (..), playSF) input :: WorldSVIn :~> SVEvent () input = first ignore >>> cancelLeft >>> filter (\e -> case e of GlossEventKey (MouseButton _) Down _ -> Just () _ -> Nothing) output :: SVSignal Double :~> WorldSVOut output = pureSignalTransformer (color black . text . show) main :: IO () main = playSF (input >>> timeTracker 0 >>> output)
5cc0242161fcb689417a164b0988f5cfe164890ff070ae9f2ffeac2fac3bc04b
babashka/babashka
features.clj
(ns babashka.impl.features {:no-doc true}) ;; included by default (def yaml? (not= "false" (System/getenv "BABASHKA_FEATURE_YAML"))) (def xml? (not= "false" (System/getenv "BABASHKA_FEATURE_XML"))) (def csv? (not= "false" (System/getenv "BABASHKA_FEATURE_CSV"))) (def transit? (not= "false" (System/getenv "BABASHKA_FEATURE_TRANSIT"))) (def java-time? (not= "false" (System/getenv "BABASHKA_FEATURE_JAVA_TIME"))) (def java-net-http? (not= "false" (System/getenv "BABASHKA_FEATURE_JAVA_NET_HTTP"))) (def java-nio? (not= "false" (System/getenv "BABASHKA_FEATURE_JAVA_NIO"))) (def httpkit-client? (not= "false" (System/getenv "BABASHKA_FEATURE_HTTPKIT_CLIENT"))) (def httpkit-server? (not= "false" (System/getenv "BABASHKA_FEATURE_HTTPKIT_SERVER"))) (def core-match? (not= "false" (System/getenv "BABASHKA_FEATURE_CORE_MATCH"))) (def hiccup? (not= "false" (System/getenv "BABASHKA_FEATURE_HICCUP"))) (def test-check? (not= "false" (System/getenv "BABASHKA_FEATURE_TEST_CHECK"))) (def selmer? (not= "false" (System/getenv "BABASHKA_FEATURE_SELMER"))) (def logging? (not= "false" (System/getenv "BABASHKA_FEATURE_LOGGING"))) (def priority-map? (not= "false" (System/getenv "BABASHKA_FEATURE_PRIORITY_MAP"))) ;; excluded by default (def jdbc? (= "true" (System/getenv "BABASHKA_FEATURE_JDBC"))) (def sqlite? (= "true" (System/getenv "BABASHKA_FEATURE_SQLITE"))) (def postgresql? (= "true" (System/getenv "BABASHKA_FEATURE_POSTGRESQL"))) (def oracledb? (= "true" (System/getenv "BABASHKA_FEATURE_ORACLEDB"))) (def hsqldb? (= "true" (System/getenv "BABASHKA_FEATURE_HSQLDB"))) (def datascript? (= "true" (System/getenv "BABASHKA_FEATURE_DATASCRIPT"))) (def lanterna? (= "true" (System/getenv "BABASHKA_FEATURE_LANTERNA"))) (def spec-alpha? (= "true" (System/getenv "BABASHKA_FEATURE_SPEC_ALPHA"))) (def rrb-vector? (= "true" (System/getenv "BABASHKA_FEATURE_RRB_VECTOR"))) (when xml? (require '[babashka.impl.xml])) (when yaml? (require '[babashka.impl.yaml] '[babashka.impl.ordered])) (when jdbc? (require '[babashka.impl.jdbc])) (when csv? (require '[babashka.impl.csv])) (when transit? (require '[babashka.impl.transit])) (when datascript? (require '[babashka.impl.datascript])) (when httpkit-client? (require '[babashka.impl.httpkit-client])) (when httpkit-server? (require '[babashka.impl.httpkit-server])) (when lanterna? (require '[babashka.impl.lanterna])) (when core-match? (require '[babashka.impl.match])) (when hiccup? (require '[babashka.impl.hiccup])) (when test-check? (require '[babashka.impl.clojure.test.check])) (when spec-alpha? (require '[babashka.impl.spec])) (when selmer? (require '[babashka.impl.selmer])) (when logging? (require '[babashka.impl.logging])) (when priority-map? (require '[babashka.impl.priority-map])) (when rrb-vector? (require '[babashka.impl.rrb-vector]))
null
https://raw.githubusercontent.com/babashka/babashka/41dcc9239a15d95f055dfc0d8af33242c1a12e4f/src/babashka/impl/features.clj
clojure
included by default excluded by default
(ns babashka.impl.features {:no-doc true}) (def yaml? (not= "false" (System/getenv "BABASHKA_FEATURE_YAML"))) (def xml? (not= "false" (System/getenv "BABASHKA_FEATURE_XML"))) (def csv? (not= "false" (System/getenv "BABASHKA_FEATURE_CSV"))) (def transit? (not= "false" (System/getenv "BABASHKA_FEATURE_TRANSIT"))) (def java-time? (not= "false" (System/getenv "BABASHKA_FEATURE_JAVA_TIME"))) (def java-net-http? (not= "false" (System/getenv "BABASHKA_FEATURE_JAVA_NET_HTTP"))) (def java-nio? (not= "false" (System/getenv "BABASHKA_FEATURE_JAVA_NIO"))) (def httpkit-client? (not= "false" (System/getenv "BABASHKA_FEATURE_HTTPKIT_CLIENT"))) (def httpkit-server? (not= "false" (System/getenv "BABASHKA_FEATURE_HTTPKIT_SERVER"))) (def core-match? (not= "false" (System/getenv "BABASHKA_FEATURE_CORE_MATCH"))) (def hiccup? (not= "false" (System/getenv "BABASHKA_FEATURE_HICCUP"))) (def test-check? (not= "false" (System/getenv "BABASHKA_FEATURE_TEST_CHECK"))) (def selmer? (not= "false" (System/getenv "BABASHKA_FEATURE_SELMER"))) (def logging? (not= "false" (System/getenv "BABASHKA_FEATURE_LOGGING"))) (def priority-map? (not= "false" (System/getenv "BABASHKA_FEATURE_PRIORITY_MAP"))) (def jdbc? (= "true" (System/getenv "BABASHKA_FEATURE_JDBC"))) (def sqlite? (= "true" (System/getenv "BABASHKA_FEATURE_SQLITE"))) (def postgresql? (= "true" (System/getenv "BABASHKA_FEATURE_POSTGRESQL"))) (def oracledb? (= "true" (System/getenv "BABASHKA_FEATURE_ORACLEDB"))) (def hsqldb? (= "true" (System/getenv "BABASHKA_FEATURE_HSQLDB"))) (def datascript? (= "true" (System/getenv "BABASHKA_FEATURE_DATASCRIPT"))) (def lanterna? (= "true" (System/getenv "BABASHKA_FEATURE_LANTERNA"))) (def spec-alpha? (= "true" (System/getenv "BABASHKA_FEATURE_SPEC_ALPHA"))) (def rrb-vector? (= "true" (System/getenv "BABASHKA_FEATURE_RRB_VECTOR"))) (when xml? (require '[babashka.impl.xml])) (when yaml? (require '[babashka.impl.yaml] '[babashka.impl.ordered])) (when jdbc? (require '[babashka.impl.jdbc])) (when csv? (require '[babashka.impl.csv])) (when transit? (require '[babashka.impl.transit])) (when datascript? (require '[babashka.impl.datascript])) (when httpkit-client? (require '[babashka.impl.httpkit-client])) (when httpkit-server? (require '[babashka.impl.httpkit-server])) (when lanterna? (require '[babashka.impl.lanterna])) (when core-match? (require '[babashka.impl.match])) (when hiccup? (require '[babashka.impl.hiccup])) (when test-check? (require '[babashka.impl.clojure.test.check])) (when spec-alpha? (require '[babashka.impl.spec])) (when selmer? (require '[babashka.impl.selmer])) (when logging? (require '[babashka.impl.logging])) (when priority-map? (require '[babashka.impl.priority-map])) (when rrb-vector? (require '[babashka.impl.rrb-vector]))
06b4fc0102b6531b5309826f56fbc4b0c2ec8e68013abd7794bc288b7496b4f5
alexkazik/qrcode
TextEncoding.hs
# LANGUAGE NoImplicitPrelude # module Codec.QRCode.Data.TextEncoding ( TextEncoding(..) ) where data TextEncoding = Iso8859_1 -- ^ Generate segment out of a ISO-8859-1 text, if the text contains chars -- which aren't in the charset the result will be a failure. | Utf8WithoutECI -- ^ Use an UTF-8 encoded text. -- The reader must do a detection and conversion. -- -- __Please check the readers which should be used if they support this.__ | Utf8WithECI ^ This is the correct way to encode UTF-8 , but it 's reported that not all -- readers support this. -- -- __Please check the readers which should be used if they support this.__ | Iso8859_1OrUtf8WithoutECI -- ^ Try to encode as `Iso8859_1`, if that is not possible use `Utf8WithoutECI`. | Iso8859_1OrUtf8WithECI -- ^ Try to encode as `Iso8859_1`, if that is not possible use `Utf8WithECI`.
null
https://raw.githubusercontent.com/alexkazik/qrcode/7ee12de893c856a968dc1397602a7f81f8ea2c68/qrcode-core/src/Codec/QRCode/Data/TextEncoding.hs
haskell
^ Generate segment out of a ISO-8859-1 text, if the text contains chars which aren't in the charset the result will be a failure. ^ Use an UTF-8 encoded text. The reader must do a detection and conversion. __Please check the readers which should be used if they support this.__ readers support this. __Please check the readers which should be used if they support this.__ ^ Try to encode as `Iso8859_1`, if that is not possible use `Utf8WithoutECI`. ^ Try to encode as `Iso8859_1`, if that is not possible use `Utf8WithECI`.
# LANGUAGE NoImplicitPrelude # module Codec.QRCode.Data.TextEncoding ( TextEncoding(..) ) where data TextEncoding = Iso8859_1 | Utf8WithoutECI | Utf8WithECI ^ This is the correct way to encode UTF-8 , but it 's reported that not all | Iso8859_1OrUtf8WithoutECI | Iso8859_1OrUtf8WithECI
144ef4c4803fabe819cbd2a76448c9c24f8a19088446dcf30f42628c4a425f30
coq/coq
util.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , 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 GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* This file keeps coq_dune self-contained as it is a "bootstrap" utility *) (* Taken from OCaml's stdlib *) From OCaml 's > = 4.10 let list_concat_map f l = let rec aux f acc = function | [] -> List.rev acc | x :: l -> let xs = f x in aux f (List.rev_append xs acc) l in aux f [] l let rec pmap f = function | [] -> [] | x :: xs -> match f x with | None -> pmap f xs | Some x -> x :: pmap f xs
null
https://raw.githubusercontent.com/coq/coq/0973e012d615c0722d483cd5d814bde90c76d7d3/tools/dune_rule_gen/util.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ This file keeps coq_dune self-contained as it is a "bootstrap" utility Taken from OCaml's stdlib
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the From OCaml 's > = 4.10 let list_concat_map f l = let rec aux f acc = function | [] -> List.rev acc | x :: l -> let xs = f x in aux f (List.rev_append xs acc) l in aux f [] l let rec pmap f = function | [] -> [] | x :: xs -> match f x with | None -> pmap f xs | Some x -> x :: pmap f xs
ed98d77a0d95c19bfcfbe2b1e8aa43801d7b5e04be28b7a8ee1050f4ef9fa1cc
viercc/kitchen-sink-hs
Bag.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE TupleSections # | \"Bag\ " or \"multiset\ " data structure . module Data.Bag( Bag(), -- * Basic queries null, size, uniqueLength, count, isSubsetOf, isProperSubsetOf, -- * Construction empty, singleton, -- * Single-item operation insert, delete, pullOut, * Combine two bags append, union, intersection, difference, cartesianProduct, -- * Conversion fromFreqs, toFreqs, toAscFreqs, toDescFreqs, fromFreqsMap, toFreqsMap, fromList, fromAscList, fromDescList, fromDistinctAscList, fromDistinctDescList, toList, toAscList, toDescList, ) where import Prelude hiding (null) import qualified Data.Map.Strict as Map import qualified Data.Foldable as F import Control.Monad ((<=<)) import Data.Bag.Internal -- * Queries -- | O(1) uniqueLength :: Bag k -> Int uniqueLength (MkBag m) = Map.size m -- | Number of an item in a bag. Count is 0 if the item doesn't exist in -- the bag. -- -- Count is always nonnegative. count :: Ord k => k -> Bag k -> Int count k (MkBag m) = Map.findWithDefault 0 k m | @isSubsetOf a b@ = forall k a < = count k b@ isSubsetOf, isProperSubsetOf :: (Ord k) => Bag k -> Bag k -> Bool isSubsetOf a b = uniqueLength a <= uniqueLength b && freqsLE (toFreqs a) (toFreqs b) isProperSubsetOf a b = uniqueLength a <= uniqueLength b && freqsLT (toFreqs a) (toFreqs b) freqsLE, freqsLT :: Ord k => [(k, Int)] -> [(k, Int)] -> Bool freqsLE [] _ = True freqsLE (_:_) [] = False freqsLE ((a,n):as) ((b,m):bs) | a < b = False | a == b = n <= m && freqsLE as bs | otherwise = freqsLE ((a,n):as) bs freqsLT [] [] = False freqsLT [] (_:_) = True freqsLT (_:_) [] = False freqsLT ((a,n):as) ((b,m):bs) | a < b = False | a == b, n > m = False | a == b, n == m = freqsLT as bs | a == b, n < m = freqsLE as bs | otherwise = freqsLE ((a,n):as) bs -- * Construction | /O(log(n))/ Insert a item to a bag . Increases count of that item by 1 . insert :: Ord k => k -> Bag k -> Bag k insert k (MkBag m) = MkBag $ Map.insertWith (+) k 1 m -- | /O(log(n))/ Delete a item from a bag if exists. Decreases count of that item by 1 , if there was one at least . delete :: Ord k => k -> Bag k -> Bag k delete k (MkBag m) = MkBag $ Map.updateWithKey (\_ n -> positiveInt (pred n)) k m | /O(log(n))/ Deletes one item from a bag . If the item does n't exist in the bag , returns @Nothing@. Otherwise , returns the bag after the removal . pullOut :: Ord a => a -> Bag a -> Maybe (Bag a) pullOut x (MkBag m) = case Map.updateLookupWithKey (\_ n -> positiveInt (pred n)) x m of (Nothing, _) -> Nothing (Just _, m') -> Just (MkBag m') -- * Combine | @union a b@ is a bag containing items contained in bags @a@ and/or @b@. For any item @x@ , the count of @x@ in @union a b@ is the larger of @count x a@ and @count x b@. In other words , the following holds for any @x@. -- -- > 'count' x ('union' a b) == max (count x a) (count x b) -- @union a b@ is the minimum bag @c@ such that @a ` isSubsetOf ` c@ and @b ` isSubsetOf ` c@. union :: (Ord k) => Bag k -> Bag k -> Bag k union (MkBag a) (MkBag b) = MkBag $ Map.unionWith max a b | @intersections a b@ is a bag containing items contained in both bags @a@ and @b@. For any item @x@ , the count of @x@ in @intersection a b@ is the smaller of @count x a@ and @count x b@. In other words , the following holds for any @x@. -- -- > 'count' x ('intersection' a b) == min (count x a) (count x b) -- @intersection a b@ is the maximum bag @c@ such that @c ` isSubsetOf ` a@ and @c ` isSubsetOf ` b@. intersection :: (Ord k) => Bag k -> Bag k -> Bag k intersection (MkBag a) (MkBag b) = MkBag $ Map.intersectionWith min a b | @difference a b@ removes items from bag @a@ for every item @b@ contains , as much as possible . -- For any item @x@ , the count of @x@ in @intersection a b@ is @count x a@ subtracted by @count x b@ , but @0@ if the subtraction makes the count negative . -- In other words , the following holds for any @x@. -- -- > 'count' x ('difference' a b) == max 0 (count x a - count x b) -- @difference a b@ is the minimum bag @c@ such that @a ` isSubsetOf ` append b c@. difference :: (Ord k) => Bag k -> Bag k -> Bag k difference (MkBag a) (MkBag b) = MkBag $ Map.differenceWith (\n m -> positiveInt (n - m)) a b -- | @cartesianProduct a b@ is a bag consists of tuples @(x,y)@ where @x@ is from @a@ and @y@ is from @b@ , and for any @(x , y)@ @count ( x , y ) ( cartesianProduct a b ) = count x a * count y b@. cartesianProduct :: (Ord j, Ord k) => Bag j -> Bag k -> Bag (j,k) cartesianProduct a b = MkBag $ Map.fromDistinctAscList [ ((x,y), n*m) | (x,n) <- toAscFreqs a , (y,m) <- toAscFreqs b ] -- * Conversion -- | O(k \* log(k)) fromList :: Ord a => [a] -> Bag a fromList = F.foldl' (flip insert) empty -- | O(k) fromAscList, fromDescList :: Eq a => [a] -> Bag a fromAscList = MkBag . Map.fromDistinctAscList . runLength fromDescList = MkBag . Map.fromDistinctDescList . runLength runLength :: Eq a => [a] -> [(a,Int)] runLength [] = [] runLength (a:as) = loop 1 as where loop !n (x : xs) | a == x = loop (succ n) xs loop n xs = (a,n) : runLength xs toList, toAscList, toDescList :: Bag a -> [a] toList = toAscList toAscList = (\(a,n) -> replicate n a) <=< toAscFreqs toDescList = (\(a,n) -> replicate n a) <=< toDescFreqs -- | O(k) fromDistinctAscList, fromDistinctDescList :: [a] -> Bag a fromDistinctAscList = MkBag . Map.fromDistinctAscList . map (, 1) fromDistinctDescList = MkBag . Map.fromDistinctDescList . map (, 1)
null
https://raw.githubusercontent.com/viercc/kitchen-sink-hs/c3a8b9e3f93f4eced21945a7fd7e47200191a645/data-bag/src/Data/Bag.hs
haskell
# LANGUAGE BangPatterns # * Basic queries * Construction * Single-item operation * Conversion * Queries | O(1) | Number of an item in a bag. Count is 0 if the item doesn't exist in the bag. Count is always nonnegative. * Construction | /O(log(n))/ Delete a item from a bag if exists. Decreases count of that item * Combine > 'count' x ('union' a b) == max (count x a) (count x b) > 'count' x ('intersection' a b) == min (count x a) (count x b) > 'count' x ('difference' a b) == max 0 (count x a - count x b) | @cartesianProduct a b@ is a bag consists of tuples @(x,y)@ * Conversion | O(k \* log(k)) | O(k) | O(k)
# LANGUAGE TupleSections # | \"Bag\ " or \"multiset\ " data structure . module Data.Bag( Bag(), null, size, uniqueLength, count, isSubsetOf, isProperSubsetOf, empty, singleton, insert, delete, pullOut, * Combine two bags append, union, intersection, difference, cartesianProduct, fromFreqs, toFreqs, toAscFreqs, toDescFreqs, fromFreqsMap, toFreqsMap, fromList, fromAscList, fromDescList, fromDistinctAscList, fromDistinctDescList, toList, toAscList, toDescList, ) where import Prelude hiding (null) import qualified Data.Map.Strict as Map import qualified Data.Foldable as F import Control.Monad ((<=<)) import Data.Bag.Internal uniqueLength :: Bag k -> Int uniqueLength (MkBag m) = Map.size m count :: Ord k => k -> Bag k -> Int count k (MkBag m) = Map.findWithDefault 0 k m | @isSubsetOf a b@ = forall k a < = count k b@ isSubsetOf, isProperSubsetOf :: (Ord k) => Bag k -> Bag k -> Bool isSubsetOf a b = uniqueLength a <= uniqueLength b && freqsLE (toFreqs a) (toFreqs b) isProperSubsetOf a b = uniqueLength a <= uniqueLength b && freqsLT (toFreqs a) (toFreqs b) freqsLE, freqsLT :: Ord k => [(k, Int)] -> [(k, Int)] -> Bool freqsLE [] _ = True freqsLE (_:_) [] = False freqsLE ((a,n):as) ((b,m):bs) | a < b = False | a == b = n <= m && freqsLE as bs | otherwise = freqsLE ((a,n):as) bs freqsLT [] [] = False freqsLT [] (_:_) = True freqsLT (_:_) [] = False freqsLT ((a,n):as) ((b,m):bs) | a < b = False | a == b, n > m = False | a == b, n == m = freqsLT as bs | a == b, n < m = freqsLE as bs | otherwise = freqsLE ((a,n):as) bs | /O(log(n))/ Insert a item to a bag . Increases count of that item by 1 . insert :: Ord k => k -> Bag k -> Bag k insert k (MkBag m) = MkBag $ Map.insertWith (+) k 1 m by 1 , if there was one at least . delete :: Ord k => k -> Bag k -> Bag k delete k (MkBag m) = MkBag $ Map.updateWithKey (\_ n -> positiveInt (pred n)) k m | /O(log(n))/ Deletes one item from a bag . If the item does n't exist in the bag , returns @Nothing@. Otherwise , returns the bag after the removal . pullOut :: Ord a => a -> Bag a -> Maybe (Bag a) pullOut x (MkBag m) = case Map.updateLookupWithKey (\_ n -> positiveInt (pred n)) x m of (Nothing, _) -> Nothing (Just _, m') -> Just (MkBag m') | @union a b@ is a bag containing items contained in bags @a@ and/or @b@. For any item @x@ , the count of @x@ in @union a b@ is the larger of @count x a@ and @count x b@. In other words , the following holds for any @x@. @union a b@ is the minimum bag @c@ such that @a ` isSubsetOf ` c@ and @b ` isSubsetOf ` c@. union :: (Ord k) => Bag k -> Bag k -> Bag k union (MkBag a) (MkBag b) = MkBag $ Map.unionWith max a b | @intersections a b@ is a bag containing items contained in both bags @a@ and @b@. For any item @x@ , the count of @x@ in @intersection a b@ is the smaller of @count x a@ and @count x b@. In other words , the following holds for any @x@. @intersection a b@ is the maximum bag @c@ such that @c ` isSubsetOf ` a@ and @c ` isSubsetOf ` b@. intersection :: (Ord k) => Bag k -> Bag k -> Bag k intersection (MkBag a) (MkBag b) = MkBag $ Map.intersectionWith min a b | @difference a b@ removes items from bag @a@ for every item @b@ contains , as much as possible . For any item @x@ , the count of @x@ in @intersection a b@ is @count x a@ subtracted by @count x b@ , but @0@ if the subtraction makes the count negative . In other words , the following holds for any @x@. @difference a b@ is the minimum bag @c@ such that @a ` isSubsetOf ` append b c@. difference :: (Ord k) => Bag k -> Bag k -> Bag k difference (MkBag a) (MkBag b) = MkBag $ Map.differenceWith (\n m -> positiveInt (n - m)) a b where @x@ is from @a@ and @y@ is from @b@ , and for any @(x , y)@ @count ( x , y ) ( cartesianProduct a b ) = count x a * count y b@. cartesianProduct :: (Ord j, Ord k) => Bag j -> Bag k -> Bag (j,k) cartesianProduct a b = MkBag $ Map.fromDistinctAscList [ ((x,y), n*m) | (x,n) <- toAscFreqs a , (y,m) <- toAscFreqs b ] fromList :: Ord a => [a] -> Bag a fromList = F.foldl' (flip insert) empty fromAscList, fromDescList :: Eq a => [a] -> Bag a fromAscList = MkBag . Map.fromDistinctAscList . runLength fromDescList = MkBag . Map.fromDistinctDescList . runLength runLength :: Eq a => [a] -> [(a,Int)] runLength [] = [] runLength (a:as) = loop 1 as where loop !n (x : xs) | a == x = loop (succ n) xs loop n xs = (a,n) : runLength xs toList, toAscList, toDescList :: Bag a -> [a] toList = toAscList toAscList = (\(a,n) -> replicate n a) <=< toAscFreqs toDescList = (\(a,n) -> replicate n a) <=< toDescFreqs fromDistinctAscList, fromDistinctDescList :: [a] -> Bag a fromDistinctAscList = MkBag . Map.fromDistinctAscList . map (, 1) fromDistinctDescList = MkBag . Map.fromDistinctDescList . map (, 1)
7744708849ef9c91580dfe1fc81dc983a2ca87d783e8c414e72fc362622a063a
billstclair/trubanc-lisp
uffi-compat.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; uffi-compat.lisp --- UFFI compatibility layer for CFFI . ;;; Copyright ( C ) 2005 - 2006 , < > Copyright ( C ) 2005 - 2007 , ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . ;;; THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. ;;; Code borrowed from UFFI is Copyright ( c ) . (defpackage #:cffi-uffi-compat (:nicknames #:uffi) ;; is this a good idea? (:use #:cl) (:export ;; immediate types #:def-constant #:def-foreign-type #:def-type #:null-char-p ;; aggregate types #:def-enum #:def-struct #:get-slot-value #:get-slot-pointer #:def-array-pointer #:deref-array #:def-union ;; objects #:allocate-foreign-object #:free-foreign-object #:with-foreign-object #:with-foreign-objects #:size-of-foreign-type #:pointer-address #:deref-pointer #:ensure-char-character #:ensure-char-integer #:ensure-char-storable #:null-pointer-p #:make-null-pointer #:make-pointer #:+null-cstring-pointer+ #:char-array-to-pointer #:with-cast-pointer #:def-foreign-var #:convert-from-foreign-usb8 #:def-pointer-var ;; string functions #:convert-from-cstring #:convert-to-cstring #:free-cstring #:with-cstring #:with-cstrings #:convert-from-foreign-string #:convert-to-foreign-string #:allocate-foreign-string #:with-foreign-string #:with-foreign-strings #:foreign-string-length ; not implemented ;; function call #:def-function ;; libraries #:find-foreign-library #:load-foreign-library #:default-foreign-library-type #:foreign-library-types ;; os #:getenv #:run-shell-command )) (in-package #:cffi-uffi-compat) #+clisp (eval-when (:compile-toplevel :load-toplevel :execute) (when (equal (machine-type) "POWER MACINTOSH") (pushnew :ppc *features*))) (defun convert-uffi-type (uffi-type) "Convert a UFFI primitive type to a CFFI type." Many CFFI types are the same as UFFI . This list handles the ;; exceptions only. (case uffi-type (:cstring :pointer) (:pointer-void :pointer) (:pointer-self :pointer) (:char '(uffi-char :char)) (:unsigned-char '(uffi-char :unsigned-char)) (:byte :char) (:unsigned-byte :unsigned-char) (t (if (listp uffi-type) (case (car uffi-type) ;; this is imho gross but it is what uffi does (quote (convert-uffi-type (second uffi-type))) (* :pointer) (:array `(uffi-array ,(convert-uffi-type (second uffi-type)) ,(third uffi-type))) (:union (second uffi-type)) (:struct (convert-uffi-type (second uffi-type))) (:struct-pointer :pointer)) uffi-type)))) (cffi:define-foreign-type uffi-array-type () ;; ELEMENT-TYPE should be /unparsed/, suitable for passing to mem-aref. ((element-type :initform (error "An element-type is required.") :accessor element-type :initarg :element-type) (nelems :initform (error "nelems is required.") :accessor nelems :initarg :nelems)) (:actual-type :pointer) (:documentation "UFFI's :array type.")) (cffi:define-parse-method uffi-array (element-type count) (make-instance 'uffi-array-type :element-type element-type :nelems (or count 1))) (defmethod cffi:foreign-type-size ((type uffi-array-type)) (* (cffi:foreign-type-size (element-type type)) (nelems type))) (defmethod cffi::aggregatep ((type uffi-array-type)) t) UFFI 's :( unsigned-)char (cffi:define-foreign-type uffi-char () ()) (cffi:define-parse-method uffi-char (base-type) (make-instance 'uffi-char :actual-type base-type)) (defmethod cffi:translate-to-foreign ((value character) (type uffi-char)) (char-code value)) (defmethod cffi:translate-from-foreign (obj (type uffi-char)) (code-char obj)) (defmacro def-type (name type) "Define a Common Lisp type NAME for UFFI type TYPE." (declare (ignore type)) `(deftype ,name () t)) (defmacro def-foreign-type (name type) "Define a new foreign type." `(cffi:defctype ,name ,(convert-uffi-type type))) (defmacro def-constant (name value &key export) "Define a constant and conditionally export it." `(eval-when (:compile-toplevel :load-toplevel :execute) (defconstant ,name ,value) ,@(when export `((export ',name))) ',name)) (defmacro null-char-p (val) "Return true if character is null." `(zerop (char-code ,val))) (defmacro def-enum (enum-name args &key (separator-string "#")) "Creates a constants for a C type enum list, symbols are created in the created in the current package. The symbol is the concatenation of the enum-name name, separator-string, and field-name" (let ((counter 0) (cmds nil) (constants nil)) (declare (fixnum counter)) (dolist (arg args) (let ((name (if (listp arg) (car arg) arg)) (value (if (listp arg) (prog1 (setq counter (cadr arg)) (incf counter)) (prog1 counter (incf counter))))) (setq name (intern (concatenate 'string (symbol-name enum-name) separator-string (symbol-name name)))) (push `(def-constant ,name ,value) constants))) (setf cmds (append '(progn) `((cffi:defctype ,enum-name :int)) (nreverse constants))) cmds)) (defmacro def-struct (name &body fields) "Define a C structure." `(cffi:defcstruct ,name ,@(loop for (name uffi-type) in fields for cffi-type = (convert-uffi-type uffi-type) collect (list name cffi-type)))) ;; TODO: figure out why the compiler macro is kicking in before the setf expander . (defun %foreign-slot-value (obj type field) (cffi:foreign-slot-value obj type field)) (defun (setf %foreign-slot-value) (value obj type field) (setf (cffi:foreign-slot-value obj type field) value)) (defmacro get-slot-value (obj type field) "Access a slot value from a structure." `(%foreign-slot-value ,obj ,type ,field)) UFFI uses a different function when accessing a slot whose ;; type is a pointer. We don't need that in CFFI so we use ;; foreign-slot-value too. (defmacro get-slot-pointer (obj type field) "Access a pointer slot value from a structure." `(cffi:foreign-slot-value ,obj ,type ,field)) (defmacro def-array-pointer (name type) "Define a foreign array type." `(cffi:defctype ,name (uffi-array ,(convert-uffi-type type) 1))) (defmacro deref-array (array type position) "Dereference an array." `(cffi:mem-aref ,array ,(if (constantp type) `',(element-type (cffi::parse-type (convert-uffi-type (eval type)))) `(element-type (cffi::parse-type (convert-uffi-type ,type)))) ,position)) UFFI 's documentation on DEF - UNION is a bit scarce , I 'm not sure if and DEF - UNION are strictly compatible . (defmacro def-union (name &body fields) "Define a foreign union type." `(cffi:defcunion ,name ,@(loop for (name uffi-type) in fields for cffi-type = (convert-uffi-type uffi-type) collect (list name cffi-type)))) (defmacro allocate-foreign-object (type &optional (size 1)) "Allocate one or more instance of a foreign type." `(cffi:foreign-alloc ,(if (constantp type) `',(convert-uffi-type (eval type)) `(convert-uffi-type ,type)) :count ,size)) (defmacro free-foreign-object (ptr) "Free a foreign object allocated by ALLOCATE-FOREIGN-OBJECT." `(cffi:foreign-free ,ptr)) (defmacro with-foreign-object ((var type) &body body) "Wrap the allocation of a foreign object around BODY." `(cffi:with-foreign-object (,var (convert-uffi-type ,type)) ,@body)) Taken from UFFI 's src / objects.lisp (defmacro with-foreign-objects (bindings &rest body) (if bindings `(with-foreign-object ,(car bindings) (with-foreign-objects ,(cdr bindings) ,@body)) `(progn ,@body))) (defmacro size-of-foreign-type (type) "Return the size in bytes of a foreign type." `(cffi:foreign-type-size (convert-uffi-type ,type))) (defmacro pointer-address (ptr) "Return the address of a pointer." `(cffi:pointer-address ,ptr)) (defmacro deref-pointer (ptr type) "Dereference a pointer." `(cffi:mem-ref ,ptr (convert-uffi-type ,type))) (defsetf deref-pointer (ptr type) (value) `(setf (cffi:mem-ref ,ptr (convert-uffi-type ,type)) ,value)) (defmacro ensure-char-character (obj &environment env) "Convert OBJ to a character if it is an integer." (if (constantp obj env) (if (characterp obj) obj (code-char obj)) (let ((obj-var (gensym))) `(let ((,obj-var ,obj)) (if (characterp ,obj-var) ,obj-var (code-char ,obj-var)))))) (defmacro ensure-char-integer (obj &environment env) "Convert OBJ to an integer if it is a character." (if (constantp obj env) (let ((the-obj (eval obj))) (if (characterp the-obj) (char-code the-obj) the-obj)) (let ((obj-var (gensym))) `(let ((,obj-var ,obj)) (if (characterp ,obj-var) (char-code ,obj-var) ,obj-var))))) (defmacro ensure-char-storable (obj) "Ensure OBJ is storable as a character." `(ensure-char-integer ,obj)) (defmacro make-null-pointer (type) "Create a NULL pointer." (declare (ignore type)) `(cffi:null-pointer)) (defmacro make-pointer (address type) "Create a pointer to ADDRESS." (declare (ignore type)) `(cffi:make-pointer ,address)) (defmacro null-pointer-p (ptr) "Return true if PTR is a null pointer." `(cffi:null-pointer-p ,ptr)) (defparameter +null-cstring-pointer+ (cffi:null-pointer) "A constant NULL string pointer.") (defmacro char-array-to-pointer (obj) obj) (defmacro with-cast-pointer ((var ptr type) &body body) "Cast a pointer, does nothing in CFFI." (declare (ignore type)) `(let ((,var ,ptr)) ,@body)) (defmacro def-foreign-var (name type module) "Define a symbol macro to access a foreign variable." (declare (ignore module)) (flet ((lisp-name (name) (intern (cffi-sys:canonicalize-symbol-name-case (substitute #\- #\_ name))))) `(cffi:defcvar ,(if (listp name) name (list name (lisp-name name))) ,(convert-uffi-type type)))) (defmacro def-pointer-var (name value &optional doc) #-openmcl `(defvar ,name ,value ,@(if doc (list doc))) #+openmcl `(ccl::defloadvar ,name ,value ,doc)) (defmacro convert-from-cstring (s) "Convert a cstring to a Lisp string." (let ((ret (gensym))) `(let ((,ret (cffi:foreign-string-to-lisp ,s))) (if (equal ,ret "") nil ,ret)))) (defmacro convert-to-cstring (obj) "Convert a Lisp string to a cstring." (let ((str (gensym))) `(let ((,str ,obj)) (if (null ,str) (cffi:null-pointer) (cffi:foreign-string-alloc ,str))))) (defmacro free-cstring (ptr) "Free a cstring." `(cffi:foreign-string-free ,ptr)) (defmacro with-cstring ((foreign-string lisp-string) &body body) "Binds a newly creating string." (let ((str (gensym)) (body-proc (gensym))) `(flet ((,body-proc (,foreign-string) ,@body)) (let ((,str ,lisp-string)) (if (null ,str) (,body-proc (cffi:null-pointer)) (cffi:with-foreign-string (,foreign-string ,str) (,body-proc ,foreign-string))))))) Taken from UFFI 's src / strings.lisp (defmacro with-cstrings (bindings &rest body) (if bindings `(with-cstring ,(car bindings) (with-cstrings ,(cdr bindings) ,@body)) `(progn ,@body))) (defmacro def-function (name args &key module (returning :void)) "Define a foreign function." (declare (ignore module)) `(cffi:defcfun ,name ,(convert-uffi-type returning) ,@(loop for (name type) in args collect `(,name ,(convert-uffi-type type))))) Taken from UFFI 's src / libraries.lisp (defvar *loaded-libraries* nil "List of foreign libraries loaded. Used to prevent reloading a library") (defun default-foreign-library-type () "Returns string naming default library type for platform" #+(or win32 cygwin mswindows) "dll" #+(or macos macosx darwin ccl-5.0) "dylib" #-(or win32 cygwin mswindows macos macosx darwin ccl-5.0) "so") (defun foreign-library-types () "Returns list of string naming possible library types for platform, sorted by preference" #+(or win32 cygwin mswindows) '("dll" "lib" "so") #+(or macos macosx darwin ccl-5.0) '("dylib" "bundle") #-(or win32 cygwin mswindows macos macosx darwin ccl-5.0) '("so" "a" "o")) (defun find-foreign-library (names directories &key types drive-letters) "Looks for a foreign library. directories can be a single string or a list of strings of candidate directories. Use default library type if type is not specified." (unless types (setq types (foreign-library-types))) (unless (listp types) (setq types (list types))) (unless (listp names) (setq names (list names))) (unless (listp directories) (setq directories (list directories))) #+(or win32 mswindows) (unless (listp drive-letters) (setq drive-letters (list drive-letters))) #-(or win32 mswindows) (setq drive-letters '(nil)) (dolist (drive-letter drive-letters) (dolist (name names) (dolist (dir directories) (dolist (type types) (let ((path (make-pathname #+lispworks :host #+lispworks (when drive-letter drive-letter) #-lispworks :device #-lispworks (when drive-letter drive-letter) :name name :type type :directory (etypecase dir (pathname (pathname-directory dir)) (list dir) (string (pathname-directory (parse-namestring dir))))))) (when (probe-file path) (return-from find-foreign-library path))))))) nil) (defun convert-supporting-libraries-to-string (libs) (let (lib-load-list) (dolist (lib libs) (push (format nil "-l~A" lib) lib-load-list)) (nreverse lib-load-list))) (defun load-foreign-library (filename &key module supporting-libraries force-load) #+(or allegro mcl sbcl clisp) (declare (ignore module supporting-libraries)) #+(or cmu scl sbcl) (declare (ignore module)) (when (and filename (or (null (pathname-directory filename)) (probe-file filename))) (if (pathnamep filename) ;; ensure filename is a string to check if (setq filename (namestring filename))) ; already loaded (if (and (not force-load) (find filename *loaded-libraries* :test #'string-equal)) t ;; return T, but don't reload library (progn FIXME : Hmm , what are these two for ? #+cmu (let ((type (pathname-type (parse-namestring filename)))) (if (string-equal type "so") (sys::load-object-file filename) (alien:load-foreign filename :libraries (convert-supporting-libraries-to-string supporting-libraries)))) #+scl (let ((type (pathname-type (parse-namestring filename)))) (if (string-equal type "so") (sys::load-dynamic-object filename) (alien:load-foreign filename :libraries (convert-supporting-libraries-to-string supporting-libraries)))) #-(or cmu scl) (cffi:load-foreign-library filename) (push filename *loaded-libraries*) t)))) Taken from UFFI 's src / os.lisp (defun getenv (var) "Return the value of the environment variable." #+allegro (sys::getenv (string var)) #+clisp (sys::getenv (string var)) #+(or cmu scl) (cdr (assoc (string var) ext:*environment-list* :test #'equalp :key #'string)) #+gcl (si:getenv (string var)) #+lispworks (lw:environment-variable (string var)) #+lucid (lcl:environment-variable (string var)) #+(or mcl ccl) (ccl::getenv var) #+sbcl (sb-ext:posix-getenv var) #-(or allegro clisp cmu scl gcl lispworks lucid mcl ccl sbcl) (error 'not-implemented :proc (list 'getenv var))) Taken from UFFI 's src / os.lisp modified from function ASDF -- Copyright and Contributors (defun run-shell-command (control-string &rest args &key output) "Interpolate ARGS into CONTROL-STRING as if by FORMAT, and synchronously execute the result using a Bourne-compatible shell, with output to *trace-output*. Returns the shell's exit code." (unless output (setq output *trace-output*)) (let ((command (apply #'format nil control-string args))) #+sbcl (sb-impl::process-exit-code (sb-ext:run-program "/bin/sh" (list "-c" command) :input nil :output output)) #+(or cmu scl) (ext:process-exit-code (ext:run-program "/bin/sh" (list "-c" command) :input nil :output output)) #+allegro (excl:run-shell-command command :input nil :output output) #+lispworks (system:call-system-showing-output command :shell-type "/bin/sh" :output-stream output) #+clisp ;XXX not exactly *trace-output*, I know (ext:run-shell-command command :output :terminal :wait t) #+openmcl (nth-value 1 (ccl:external-process-status (ccl:run-program "/bin/sh" (list "-c" command) :input nil :output output :wait t))) #-(or openmcl clisp lispworks allegro scl cmu sbcl) (error "RUN-SHELL-PROGRAM not implemented for this Lisp") )) Some undocumented UFFI operators ... (defmacro convert-from-foreign-string (obj &key length (locale :default) (null-terminated-p t)) ;; in effect, (eq NULL-TERMINATED-P (null LENGTH)). Hopefully, ;; that's compatible with the intended semantics, which are ;; undocumented. If that's not the case, we can implement ;; NULL-TERMINATED-P in CFFI:FOREIGN-STRING-TO-LISP. (declare (ignore locale null-terminated-p)) (let ((ret (gensym))) `(let ((,ret (cffi:foreign-string-to-lisp ,obj :count ,length))) (if (equal ,ret "") nil ,ret)))) ;; What's the difference between this and convert-to-cstring? (defmacro convert-to-foreign-string (obj) (let ((str (gensym))) `(let ((,str ,obj)) (if (null ,str) (cffi:null-pointer) (cffi:foreign-string-alloc ,str))))) (defmacro allocate-foreign-string (size &key unsigned) (declare (ignore unsigned)) `(cffi:foreign-alloc :char :count ,size)) ;; Ditto. (defmacro with-foreign-string ((foreign-string lisp-string) &body body) (let ((str (gensym))) `(let ((,str ,lisp-string)) (if (null ,str) (let ((,foreign-string (cffi:null-pointer))) ,@body) (cffi:with-foreign-string (,foreign-string ,str) ,@body))))) (defmacro with-foreign-strings (bindings &body body) `(with-foreign-string ,(car bindings) ,@(if (cdr bindings) `((with-foreign-strings ,(cdr bindings) ,@body)) body))) ;; This function returns a form? Where is this used in user-code? (defun foreign-string-length (foreign-string) (declare (ignore foreign-string)) (error "FOREIGN-STRING-LENGTH not implemented.")) ;; This should be optimized. (defun convert-from-foreign-usb8 (s len) (let ((a (make-array len :element-type '(unsigned-byte 8)))) (dotimes (i len a) (setf (aref a i) (cffi:mem-ref s :unsigned-char i)))))
null
https://raw.githubusercontent.com/billstclair/trubanc-lisp/5436d2eca5b1ed10bc47eec7080f6cb90f98ca65/systems/cffi_0.10.4/uffi-compat/uffi-compat.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. is this a good idea? immediate types aggregate types objects string functions not implemented function call libraries os exceptions only. this is imho gross but it is what uffi does ELEMENT-TYPE should be /unparsed/, suitable for passing to mem-aref. TODO: figure out why the compiler macro is kicking in before type is a pointer. We don't need that in CFFI so we use foreign-slot-value too. ensure filename is a string to check if already loaded return T, but don't reload library XXX not exactly *trace-output*, I know in effect, (eq NULL-TERMINATED-P (null LENGTH)). Hopefully, that's compatible with the intended semantics, which are undocumented. If that's not the case, we can implement NULL-TERMINATED-P in CFFI:FOREIGN-STRING-TO-LISP. What's the difference between this and convert-to-cstring? Ditto. This function returns a form? Where is this used in user-code? This should be optimized.
uffi-compat.lisp --- UFFI compatibility layer for CFFI . Copyright ( C ) 2005 - 2006 , < > Copyright ( C ) 2005 - 2007 , files ( the " Software " ) , to deal in the Software without of the Software , and to permit persons to whom the Software is included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , Code borrowed from UFFI is Copyright ( c ) . (defpackage #:cffi-uffi-compat (:use #:cl) (:export #:def-constant #:def-foreign-type #:def-type #:null-char-p #:def-enum #:def-struct #:get-slot-value #:get-slot-pointer #:def-array-pointer #:deref-array #:def-union #:allocate-foreign-object #:free-foreign-object #:with-foreign-object #:with-foreign-objects #:size-of-foreign-type #:pointer-address #:deref-pointer #:ensure-char-character #:ensure-char-integer #:ensure-char-storable #:null-pointer-p #:make-null-pointer #:make-pointer #:+null-cstring-pointer+ #:char-array-to-pointer #:with-cast-pointer #:def-foreign-var #:convert-from-foreign-usb8 #:def-pointer-var #:convert-from-cstring #:convert-to-cstring #:free-cstring #:with-cstring #:with-cstrings #:convert-from-foreign-string #:convert-to-foreign-string #:allocate-foreign-string #:with-foreign-string #:with-foreign-strings #:def-function #:find-foreign-library #:load-foreign-library #:default-foreign-library-type #:foreign-library-types #:getenv #:run-shell-command )) (in-package #:cffi-uffi-compat) #+clisp (eval-when (:compile-toplevel :load-toplevel :execute) (when (equal (machine-type) "POWER MACINTOSH") (pushnew :ppc *features*))) (defun convert-uffi-type (uffi-type) "Convert a UFFI primitive type to a CFFI type." Many CFFI types are the same as UFFI . This list handles the (case uffi-type (:cstring :pointer) (:pointer-void :pointer) (:pointer-self :pointer) (:char '(uffi-char :char)) (:unsigned-char '(uffi-char :unsigned-char)) (:byte :char) (:unsigned-byte :unsigned-char) (t (if (listp uffi-type) (case (car uffi-type) (quote (convert-uffi-type (second uffi-type))) (* :pointer) (:array `(uffi-array ,(convert-uffi-type (second uffi-type)) ,(third uffi-type))) (:union (second uffi-type)) (:struct (convert-uffi-type (second uffi-type))) (:struct-pointer :pointer)) uffi-type)))) (cffi:define-foreign-type uffi-array-type () ((element-type :initform (error "An element-type is required.") :accessor element-type :initarg :element-type) (nelems :initform (error "nelems is required.") :accessor nelems :initarg :nelems)) (:actual-type :pointer) (:documentation "UFFI's :array type.")) (cffi:define-parse-method uffi-array (element-type count) (make-instance 'uffi-array-type :element-type element-type :nelems (or count 1))) (defmethod cffi:foreign-type-size ((type uffi-array-type)) (* (cffi:foreign-type-size (element-type type)) (nelems type))) (defmethod cffi::aggregatep ((type uffi-array-type)) t) UFFI 's :( unsigned-)char (cffi:define-foreign-type uffi-char () ()) (cffi:define-parse-method uffi-char (base-type) (make-instance 'uffi-char :actual-type base-type)) (defmethod cffi:translate-to-foreign ((value character) (type uffi-char)) (char-code value)) (defmethod cffi:translate-from-foreign (obj (type uffi-char)) (code-char obj)) (defmacro def-type (name type) "Define a Common Lisp type NAME for UFFI type TYPE." (declare (ignore type)) `(deftype ,name () t)) (defmacro def-foreign-type (name type) "Define a new foreign type." `(cffi:defctype ,name ,(convert-uffi-type type))) (defmacro def-constant (name value &key export) "Define a constant and conditionally export it." `(eval-when (:compile-toplevel :load-toplevel :execute) (defconstant ,name ,value) ,@(when export `((export ',name))) ',name)) (defmacro null-char-p (val) "Return true if character is null." `(zerop (char-code ,val))) (defmacro def-enum (enum-name args &key (separator-string "#")) "Creates a constants for a C type enum list, symbols are created in the created in the current package. The symbol is the concatenation of the enum-name name, separator-string, and field-name" (let ((counter 0) (cmds nil) (constants nil)) (declare (fixnum counter)) (dolist (arg args) (let ((name (if (listp arg) (car arg) arg)) (value (if (listp arg) (prog1 (setq counter (cadr arg)) (incf counter)) (prog1 counter (incf counter))))) (setq name (intern (concatenate 'string (symbol-name enum-name) separator-string (symbol-name name)))) (push `(def-constant ,name ,value) constants))) (setf cmds (append '(progn) `((cffi:defctype ,enum-name :int)) (nreverse constants))) cmds)) (defmacro def-struct (name &body fields) "Define a C structure." `(cffi:defcstruct ,name ,@(loop for (name uffi-type) in fields for cffi-type = (convert-uffi-type uffi-type) collect (list name cffi-type)))) the setf expander . (defun %foreign-slot-value (obj type field) (cffi:foreign-slot-value obj type field)) (defun (setf %foreign-slot-value) (value obj type field) (setf (cffi:foreign-slot-value obj type field) value)) (defmacro get-slot-value (obj type field) "Access a slot value from a structure." `(%foreign-slot-value ,obj ,type ,field)) UFFI uses a different function when accessing a slot whose (defmacro get-slot-pointer (obj type field) "Access a pointer slot value from a structure." `(cffi:foreign-slot-value ,obj ,type ,field)) (defmacro def-array-pointer (name type) "Define a foreign array type." `(cffi:defctype ,name (uffi-array ,(convert-uffi-type type) 1))) (defmacro deref-array (array type position) "Dereference an array." `(cffi:mem-aref ,array ,(if (constantp type) `',(element-type (cffi::parse-type (convert-uffi-type (eval type)))) `(element-type (cffi::parse-type (convert-uffi-type ,type)))) ,position)) UFFI 's documentation on DEF - UNION is a bit scarce , I 'm not sure if and DEF - UNION are strictly compatible . (defmacro def-union (name &body fields) "Define a foreign union type." `(cffi:defcunion ,name ,@(loop for (name uffi-type) in fields for cffi-type = (convert-uffi-type uffi-type) collect (list name cffi-type)))) (defmacro allocate-foreign-object (type &optional (size 1)) "Allocate one or more instance of a foreign type." `(cffi:foreign-alloc ,(if (constantp type) `',(convert-uffi-type (eval type)) `(convert-uffi-type ,type)) :count ,size)) (defmacro free-foreign-object (ptr) "Free a foreign object allocated by ALLOCATE-FOREIGN-OBJECT." `(cffi:foreign-free ,ptr)) (defmacro with-foreign-object ((var type) &body body) "Wrap the allocation of a foreign object around BODY." `(cffi:with-foreign-object (,var (convert-uffi-type ,type)) ,@body)) Taken from UFFI 's src / objects.lisp (defmacro with-foreign-objects (bindings &rest body) (if bindings `(with-foreign-object ,(car bindings) (with-foreign-objects ,(cdr bindings) ,@body)) `(progn ,@body))) (defmacro size-of-foreign-type (type) "Return the size in bytes of a foreign type." `(cffi:foreign-type-size (convert-uffi-type ,type))) (defmacro pointer-address (ptr) "Return the address of a pointer." `(cffi:pointer-address ,ptr)) (defmacro deref-pointer (ptr type) "Dereference a pointer." `(cffi:mem-ref ,ptr (convert-uffi-type ,type))) (defsetf deref-pointer (ptr type) (value) `(setf (cffi:mem-ref ,ptr (convert-uffi-type ,type)) ,value)) (defmacro ensure-char-character (obj &environment env) "Convert OBJ to a character if it is an integer." (if (constantp obj env) (if (characterp obj) obj (code-char obj)) (let ((obj-var (gensym))) `(let ((,obj-var ,obj)) (if (characterp ,obj-var) ,obj-var (code-char ,obj-var)))))) (defmacro ensure-char-integer (obj &environment env) "Convert OBJ to an integer if it is a character." (if (constantp obj env) (let ((the-obj (eval obj))) (if (characterp the-obj) (char-code the-obj) the-obj)) (let ((obj-var (gensym))) `(let ((,obj-var ,obj)) (if (characterp ,obj-var) (char-code ,obj-var) ,obj-var))))) (defmacro ensure-char-storable (obj) "Ensure OBJ is storable as a character." `(ensure-char-integer ,obj)) (defmacro make-null-pointer (type) "Create a NULL pointer." (declare (ignore type)) `(cffi:null-pointer)) (defmacro make-pointer (address type) "Create a pointer to ADDRESS." (declare (ignore type)) `(cffi:make-pointer ,address)) (defmacro null-pointer-p (ptr) "Return true if PTR is a null pointer." `(cffi:null-pointer-p ,ptr)) (defparameter +null-cstring-pointer+ (cffi:null-pointer) "A constant NULL string pointer.") (defmacro char-array-to-pointer (obj) obj) (defmacro with-cast-pointer ((var ptr type) &body body) "Cast a pointer, does nothing in CFFI." (declare (ignore type)) `(let ((,var ,ptr)) ,@body)) (defmacro def-foreign-var (name type module) "Define a symbol macro to access a foreign variable." (declare (ignore module)) (flet ((lisp-name (name) (intern (cffi-sys:canonicalize-symbol-name-case (substitute #\- #\_ name))))) `(cffi:defcvar ,(if (listp name) name (list name (lisp-name name))) ,(convert-uffi-type type)))) (defmacro def-pointer-var (name value &optional doc) #-openmcl `(defvar ,name ,value ,@(if doc (list doc))) #+openmcl `(ccl::defloadvar ,name ,value ,doc)) (defmacro convert-from-cstring (s) "Convert a cstring to a Lisp string." (let ((ret (gensym))) `(let ((,ret (cffi:foreign-string-to-lisp ,s))) (if (equal ,ret "") nil ,ret)))) (defmacro convert-to-cstring (obj) "Convert a Lisp string to a cstring." (let ((str (gensym))) `(let ((,str ,obj)) (if (null ,str) (cffi:null-pointer) (cffi:foreign-string-alloc ,str))))) (defmacro free-cstring (ptr) "Free a cstring." `(cffi:foreign-string-free ,ptr)) (defmacro with-cstring ((foreign-string lisp-string) &body body) "Binds a newly creating string." (let ((str (gensym)) (body-proc (gensym))) `(flet ((,body-proc (,foreign-string) ,@body)) (let ((,str ,lisp-string)) (if (null ,str) (,body-proc (cffi:null-pointer)) (cffi:with-foreign-string (,foreign-string ,str) (,body-proc ,foreign-string))))))) Taken from UFFI 's src / strings.lisp (defmacro with-cstrings (bindings &rest body) (if bindings `(with-cstring ,(car bindings) (with-cstrings ,(cdr bindings) ,@body)) `(progn ,@body))) (defmacro def-function (name args &key module (returning :void)) "Define a foreign function." (declare (ignore module)) `(cffi:defcfun ,name ,(convert-uffi-type returning) ,@(loop for (name type) in args collect `(,name ,(convert-uffi-type type))))) Taken from UFFI 's src / libraries.lisp (defvar *loaded-libraries* nil "List of foreign libraries loaded. Used to prevent reloading a library") (defun default-foreign-library-type () "Returns string naming default library type for platform" #+(or win32 cygwin mswindows) "dll" #+(or macos macosx darwin ccl-5.0) "dylib" #-(or win32 cygwin mswindows macos macosx darwin ccl-5.0) "so") (defun foreign-library-types () "Returns list of string naming possible library types for platform, sorted by preference" #+(or win32 cygwin mswindows) '("dll" "lib" "so") #+(or macos macosx darwin ccl-5.0) '("dylib" "bundle") #-(or win32 cygwin mswindows macos macosx darwin ccl-5.0) '("so" "a" "o")) (defun find-foreign-library (names directories &key types drive-letters) "Looks for a foreign library. directories can be a single string or a list of strings of candidate directories. Use default library type if type is not specified." (unless types (setq types (foreign-library-types))) (unless (listp types) (setq types (list types))) (unless (listp names) (setq names (list names))) (unless (listp directories) (setq directories (list directories))) #+(or win32 mswindows) (unless (listp drive-letters) (setq drive-letters (list drive-letters))) #-(or win32 mswindows) (setq drive-letters '(nil)) (dolist (drive-letter drive-letters) (dolist (name names) (dolist (dir directories) (dolist (type types) (let ((path (make-pathname #+lispworks :host #+lispworks (when drive-letter drive-letter) #-lispworks :device #-lispworks (when drive-letter drive-letter) :name name :type type :directory (etypecase dir (pathname (pathname-directory dir)) (list dir) (string (pathname-directory (parse-namestring dir))))))) (when (probe-file path) (return-from find-foreign-library path))))))) nil) (defun convert-supporting-libraries-to-string (libs) (let (lib-load-list) (dolist (lib libs) (push (format nil "-l~A" lib) lib-load-list)) (nreverse lib-load-list))) (defun load-foreign-library (filename &key module supporting-libraries force-load) #+(or allegro mcl sbcl clisp) (declare (ignore module supporting-libraries)) #+(or cmu scl sbcl) (declare (ignore module)) (when (and filename (or (null (pathname-directory filename)) (probe-file filename))) (if (and (not force-load) (find filename *loaded-libraries* :test #'string-equal)) (progn FIXME : Hmm , what are these two for ? #+cmu (let ((type (pathname-type (parse-namestring filename)))) (if (string-equal type "so") (sys::load-object-file filename) (alien:load-foreign filename :libraries (convert-supporting-libraries-to-string supporting-libraries)))) #+scl (let ((type (pathname-type (parse-namestring filename)))) (if (string-equal type "so") (sys::load-dynamic-object filename) (alien:load-foreign filename :libraries (convert-supporting-libraries-to-string supporting-libraries)))) #-(or cmu scl) (cffi:load-foreign-library filename) (push filename *loaded-libraries*) t)))) Taken from UFFI 's src / os.lisp (defun getenv (var) "Return the value of the environment variable." #+allegro (sys::getenv (string var)) #+clisp (sys::getenv (string var)) #+(or cmu scl) (cdr (assoc (string var) ext:*environment-list* :test #'equalp :key #'string)) #+gcl (si:getenv (string var)) #+lispworks (lw:environment-variable (string var)) #+lucid (lcl:environment-variable (string var)) #+(or mcl ccl) (ccl::getenv var) #+sbcl (sb-ext:posix-getenv var) #-(or allegro clisp cmu scl gcl lispworks lucid mcl ccl sbcl) (error 'not-implemented :proc (list 'getenv var))) Taken from UFFI 's src / os.lisp modified from function ASDF -- Copyright and Contributors (defun run-shell-command (control-string &rest args &key output) "Interpolate ARGS into CONTROL-STRING as if by FORMAT, and synchronously execute the result using a Bourne-compatible shell, with output to *trace-output*. Returns the shell's exit code." (unless output (setq output *trace-output*)) (let ((command (apply #'format nil control-string args))) #+sbcl (sb-impl::process-exit-code (sb-ext:run-program "/bin/sh" (list "-c" command) :input nil :output output)) #+(or cmu scl) (ext:process-exit-code (ext:run-program "/bin/sh" (list "-c" command) :input nil :output output)) #+allegro (excl:run-shell-command command :input nil :output output) #+lispworks (system:call-system-showing-output command :shell-type "/bin/sh" :output-stream output) (ext:run-shell-command command :output :terminal :wait t) #+openmcl (nth-value 1 (ccl:external-process-status (ccl:run-program "/bin/sh" (list "-c" command) :input nil :output output :wait t))) #-(or openmcl clisp lispworks allegro scl cmu sbcl) (error "RUN-SHELL-PROGRAM not implemented for this Lisp") )) Some undocumented UFFI operators ... (defmacro convert-from-foreign-string (obj &key length (locale :default) (null-terminated-p t)) (declare (ignore locale null-terminated-p)) (let ((ret (gensym))) `(let ((,ret (cffi:foreign-string-to-lisp ,obj :count ,length))) (if (equal ,ret "") nil ,ret)))) (defmacro convert-to-foreign-string (obj) (let ((str (gensym))) `(let ((,str ,obj)) (if (null ,str) (cffi:null-pointer) (cffi:foreign-string-alloc ,str))))) (defmacro allocate-foreign-string (size &key unsigned) (declare (ignore unsigned)) `(cffi:foreign-alloc :char :count ,size)) (defmacro with-foreign-string ((foreign-string lisp-string) &body body) (let ((str (gensym))) `(let ((,str ,lisp-string)) (if (null ,str) (let ((,foreign-string (cffi:null-pointer))) ,@body) (cffi:with-foreign-string (,foreign-string ,str) ,@body))))) (defmacro with-foreign-strings (bindings &body body) `(with-foreign-string ,(car bindings) ,@(if (cdr bindings) `((with-foreign-strings ,(cdr bindings) ,@body)) body))) (defun foreign-string-length (foreign-string) (declare (ignore foreign-string)) (error "FOREIGN-STRING-LENGTH not implemented.")) (defun convert-from-foreign-usb8 (s len) (let ((a (make-array len :element-type '(unsigned-byte 8)))) (dotimes (i len a) (setf (aref a i) (cffi:mem-ref s :unsigned-char i)))))
d824da69ad7c48daa5a3200de46985a0586489e4d8f9d4b8016e4c94d39e2f57
iokasimov/pandora
Jet.hs
# LANGUAGE UndecidableInstances # module Pandora.Paradigm.Primary.Transformer.Jet where import Pandora.Pattern.Category ((<------)) import Pandora.Pattern.Functor.Covariant (Covariant ((<-|-), (<-|--), (<-|-|-), (<-|-))) import Pandora.Pattern.Functor.Traversable (Traversable ((<-/-)), (<-/-/-)) import Pandora.Paradigm.Algebraic ((<-*--)) data Jet t a = Jet a (Jet t (t a)) instance Covariant (->) (->) t => Covariant (->) (->) (Jet t) where f <-|- Jet x xs = Jet <------ f x <------ f <-|-|- xs instance Traversable (->) (->) t => Traversable (->) (->) (Jet t) where f <-/- Jet x xs = Jet <-|-- f x <-*-- (f <-/-/- xs)
null
https://raw.githubusercontent.com/iokasimov/pandora/2a573f4478ed7425a673954a790f64bda3c2574f/Pandora/Paradigm/Primary/Transformer/Jet.hs
haskell
----)) ), (<-|-|-), (<-|-))) )) ---- f x ---- f <-|-|- xs f x <-*-- (f <-/-/- xs)
# LANGUAGE UndecidableInstances # module Pandora.Paradigm.Primary.Transformer.Jet where import Pandora.Pattern.Functor.Traversable (Traversable ((<-/-)), (<-/-/-)) data Jet t a = Jet a (Jet t (t a)) instance Covariant (->) (->) t => Covariant (->) (->) (Jet t) where f <-|- Jet x xs = Jet instance Traversable (->) (->) t => Traversable (->) (->) (Jet t) where
c9cad622e22a88aa9a87e683f6441e08cbf255ca5a047784befbe12b194d8dc1
bcc32/projecteuler-ocaml
geometry.ml
open! Core open! Import let is_pythagorean_triple a b c = (a * a) + (b * b) = c * c let iter_all_pythagorean_triples ~with_hypotenuse_less_than:max_hypot ~f = for m = 2 to Number_theory.Int.isqrt max_hypot + 1 do let m'2 = m * m in for n = 1 to m - 1 do if Number_theory.Int.gcd m n = 1 && (m mod 2 = 0 || n mod 2 = 0) then ( let n'2 = n * n in let mn = 2 * m * n in let rec loop k = let c = k * (m'2 + n'2) in if c > max_hypot then () else ( let a = k * (m'2 - n'2) in let b = k * mn in f a b c; loop (k + 1)) in loop 1) done done ;; FIXME this is buggy , does n't generate in the correct order let pythagorean_triples = let open Sequence.Let_syntax in let triples_unsorted = let%map m, n = let%bind m = Number_theory.Int.natural_numbers () ~init:2 in let%bind n = Sequence.range 1 m in if Number_theory.Int.gcd m n = 1 && (m mod 2 = 0 || n mod 2 = 0) then return (m, n) else Sequence.empty in let a = (m * m) - (n * n) in let b = 2 * m * n in let c = (m * m) + (n * n) in let%bind k = Number_theory.Int.natural_numbers () ~init:1 in return (k * a, k * b, k * c) in Sequence.interleave triples_unsorted ;;
null
https://raw.githubusercontent.com/bcc32/projecteuler-ocaml/712f85902c70adc1ec13dcbbee456c8bfa8450b2/src/geometry.ml
ocaml
open! Core open! Import let is_pythagorean_triple a b c = (a * a) + (b * b) = c * c let iter_all_pythagorean_triples ~with_hypotenuse_less_than:max_hypot ~f = for m = 2 to Number_theory.Int.isqrt max_hypot + 1 do let m'2 = m * m in for n = 1 to m - 1 do if Number_theory.Int.gcd m n = 1 && (m mod 2 = 0 || n mod 2 = 0) then ( let n'2 = n * n in let mn = 2 * m * n in let rec loop k = let c = k * (m'2 + n'2) in if c > max_hypot then () else ( let a = k * (m'2 - n'2) in let b = k * mn in f a b c; loop (k + 1)) in loop 1) done done ;; FIXME this is buggy , does n't generate in the correct order let pythagorean_triples = let open Sequence.Let_syntax in let triples_unsorted = let%map m, n = let%bind m = Number_theory.Int.natural_numbers () ~init:2 in let%bind n = Sequence.range 1 m in if Number_theory.Int.gcd m n = 1 && (m mod 2 = 0 || n mod 2 = 0) then return (m, n) else Sequence.empty in let a = (m * m) - (n * n) in let b = 2 * m * n in let c = (m * m) + (n * n) in let%bind k = Number_theory.Int.natural_numbers () ~init:1 in return (k * a, k * b, k * c) in Sequence.interleave triples_unsorted ;;
e4660b4c83596b03ea669e17b07b6c353d0c7c9ea4911850716f84759189ba4f
cedlemo/OCaml-GI-ctypes-bindings-generator
Font_selection_dialog.ml
open Ctypes open Foreign type t = unit ptr let t_typ : t typ = ptr void let create = foreign "gtk_font_selection_dialog_new" (string @-> returning (ptr Widget.t_typ)) let get_cancel_button = foreign "gtk_font_selection_dialog_get_cancel_button" (t_typ @-> returning (ptr Widget.t_typ)) let get_font_name = foreign "gtk_font_selection_dialog_get_font_name" (t_typ @-> returning (string_opt)) let get_font_selection = foreign "gtk_font_selection_dialog_get_font_selection" (t_typ @-> returning (ptr Widget.t_typ)) let get_ok_button = foreign "gtk_font_selection_dialog_get_ok_button" (t_typ @-> returning (ptr Widget.t_typ)) let get_preview_text = foreign "gtk_font_selection_dialog_get_preview_text" (t_typ @-> returning (string_opt)) let set_font_name = foreign "gtk_font_selection_dialog_set_font_name" (t_typ @-> string @-> returning (bool)) let set_preview_text = foreign "gtk_font_selection_dialog_set_preview_text" (t_typ @-> string @-> returning (void))
null
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Font_selection_dialog.ml
ocaml
open Ctypes open Foreign type t = unit ptr let t_typ : t typ = ptr void let create = foreign "gtk_font_selection_dialog_new" (string @-> returning (ptr Widget.t_typ)) let get_cancel_button = foreign "gtk_font_selection_dialog_get_cancel_button" (t_typ @-> returning (ptr Widget.t_typ)) let get_font_name = foreign "gtk_font_selection_dialog_get_font_name" (t_typ @-> returning (string_opt)) let get_font_selection = foreign "gtk_font_selection_dialog_get_font_selection" (t_typ @-> returning (ptr Widget.t_typ)) let get_ok_button = foreign "gtk_font_selection_dialog_get_ok_button" (t_typ @-> returning (ptr Widget.t_typ)) let get_preview_text = foreign "gtk_font_selection_dialog_get_preview_text" (t_typ @-> returning (string_opt)) let set_font_name = foreign "gtk_font_selection_dialog_set_font_name" (t_typ @-> string @-> returning (bool)) let set_preview_text = foreign "gtk_font_selection_dialog_set_preview_text" (t_typ @-> string @-> returning (void))
388c96afbdf5ed6f5242bc39b9ac67905ae1c8d050fa19a4de8605c0efcb4419
mfoemmel/erlang-otp
corba_request.erl
%%-------------------------------------------------------------------- %% %% %CopyrightBegin% %% Copyright Ericsson AB 1998 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% %% %%----------------------------------------------------------------- %% File: corba_request.erl %% Description: This file contains an corba request server for Orber %% %%----------------------------------------------------------------- -module(corba_request). -behaviour(gen_server). -include_lib("orber/include/corba.hrl"). %%----------------------------------------------------------------- %% External exports %%----------------------------------------------------------------- -export([start/1, stop/0, stop_all/0, create/1, create_schema/1]). %%----------------------------------------------------------------- %% Internal exports %%----------------------------------------------------------------- -export([init/1, terminate/2, install/2, handle_call/3, handle_info/2]). -export([handle_cast/2, dump/0, get_key_from_pid/1]). %%----------------------------------------------------------------- Standard interface CORBA::Request %%----------------------------------------------------------------- -export([add_arg/6, invoke/2, delete/1, send/2, get_response/2]). %%----------------------------------------------------------------- %% Mnesia table definition %%----------------------------------------------------------------- -record('corba_request', {reqid, ctx, operation, arg_list, result, req_flags, pid}). %%----------------------------------------------------------------- Macros %%----------------------------------------------------------------- -define(dirty_query_context, true). %% This macro returns a read fun suitable for evaluation in a transaction -define(read_function(ReqId), fun() -> mnesia:dirty_read(ReqId) end). %% This macro returns a write fun suitable for evaluation in a transaction -define(write_function(R), fun() -> mnesia:dirty_write(R) end). %% This macro returns a write fun suitable for evaluation in a transaction -define(update(R), fun() -> mnesia:dirty_write(R) end). %% This macro returns a delete fun suitable for evaluation in a transaction -define(delete_function(R), fun() -> mnesia:delete(R) end). -ifdef(dirty_query_context). -define(query_check(Q_res), Q_res). -else. -define(query_check(Q_res), {atomic, Q_res}). -endif. -define(CHECK_EXCEPTION(Res), case Res of {'EXCEPTION', E} -> corba:raise(E); R -> R end). %%----------------------------------------------------------------- %% Debugging function %%----------------------------------------------------------------- dump() -> case catch mnesia:dirty_first('orber_request') of {'EXIT', R} -> io:format("Exited with ~p\n",[R]); Key -> dump_print(Key), dump_loop(Key) end. dump_loop(PreviousKey) -> case catch mnesia:dirty_next('orber_request', PreviousKey) of {'EXIT', R} -> io:format("Exited with ~p\n",[R]); '$end_of_table' -> ok; Key -> dump_print(Key), dump_loop(Key) end. dump_print(Key) -> case catch mnesia:dirty_read({'orber_request', Key}) of {'EXIT', R} -> io:format("Exited with ~p\n",[R]); [X] -> io:format("Req Id: ~p, op: ~p\n",[binary_to_term(X#orber_request.object_key), X#orber_request.pid]); _ -> ok end. %%----------------------------------------------------------------- %% External interface functions %%----------------------------------------------------------------- start(Opts) -> gen_server:start_link({local, orber_requestserver}, orber_request, Opts, []). stop() -> gen_server:call(orber_requestserver, stop, infinity). stop_all() -> Fun = fun() -> mnesia:match_object({orber_request, '_', '_', '_', '_', '_', '_', '_'}) end, case catch mnesia:transaction(Fun) of {atomic, Objects} -> lists:foreach(fun({orber_request, _, _, _, _, _, _, _ }) -> ok %gen_server:call(Pid, stop, infinity) end, Objects); R -> R end. create() -> ?CHECK_EXCEPTION(gen_server:call(orber_requestserver, create, infinity)). create(Ctx, OP, Args, Flags) -> ?CHECK_EXCEPTION(gen_server:call(orber_requestserver, {create, Ctx, OP, Args, Flags}, infinity)). delete(ReqId) -> ?CHECK_EXCEPTION(gen_server:call(orber_requestserver, {delete, ReqId}, infinity)). %%------------------------------------------------------------ %% Implementation of standard interface %%------------------------------------------------------------ add_arg(ReqId, ArgumentName, TC, Value, Len, ArgFlags) -> Request = ets:lookup_element(orber_request, ReqId), case Request of [] -> ok; R -> Args = Request#orber_request.arg_list, NewArgs = lists:append(Args, []), ets:insert(orber_request, NewArgs), ok end. invoke(ReqId, InvokeFlags) -> ok. send(ReqId, InvokeFlags) -> ok. get_response(ReqId, ResponseFlags) -> [{_, Val}] = ets:lookup_element(orber_request, ReqId), Val#'orber_request'.result. %%----------------------------------------------------------------- %% Server functions %%----------------------------------------------------------------- init(Env) -> case mnesia:wait_for_tables(['orber_request'], infinity) of ok -> process_flag(trap_exit, true), {ok, []}; StopReason -> {stop, StopReason} end. terminate(From, Reason) -> ok. install(Timeout, Options) -> %% check if there already exists a database. If not, create one. %% DB_initialized = perhaps_create_schema(Nodelist), check if is running . If not , start . DB_started = perhaps_start_mnesia(), Do we have a complete set of IFR tables ? If not , create them . AllTabs = mnesia:system_info(tables), DB_Result = case lists:member(orber_request, AllTabs) of true -> case lists:member({local_content, true}, Options) of true-> mnesia:add_table_copy(orber_request, node(), ram_copies); _ -> mnesia:create_table(orber_request, [{attributes, record_info(fields, orber_objkeys)} |Options]) end; _ -> mnesia:create_table(orber_request, [{attributes, record_info(fields, orber_objkeys)} |Options]) end, Wait = mnesia:wait_for_tables([orber_request], Timeout), %% Check if any error has occured yet. If there are errors, return them. if DB_Result == {atomic, ok}, Wait == ok -> ok; true -> {error, {DB_Result, Wait}} end. %%----------------------------------------------------------------- Func : handle_call/3 %% %% Comment: In objectkey gen_server all exceptions are tupples and corba : raise %% may not be used. It is too time consuming to add catches in every %% function before returning. On the client side there is a case which %% maps every tupple on the format {'exception', E} to corba:raise(E). %%----------------------------------------------------------------- handle_call(stop, From, State) -> {stop, normal, [], State}; handle_call(create, From, State) -> ReqId = term_to_binary({node(), now()}), _F = ?write_function(#'corba_request'{reqid=ReqId}), R = write_result(mnesia:transaction(_F)), ReqId ?query_check(Qres) = mnesia:dirty_read({orber_request, Objkey}), case Qres of [] -> _F = ?write_function(#orber_requests{object_key=Objkey, pid=Pid}), R = write_result(mnesia:transaction(_F)), if R == ok, pid(Pid) -> link(Pid); true -> true end, {reply, R, State}; X -> {reply, {'EXCEPTION', #'INTERNAL'{completion_status=?COMPLETED_NO}}, State} end; handle_call({delete, ReqId}, From, State) -> ?query_check(Qres) = mnesia:dirty_read({orber_request, ReqId}), case Qres of [] -> true; [X] when pid(X#orber_request.pid) -> unlink(X#orber_request.pid); _ -> true end, _F = ?delete_function({orber_request, ReqId}), R = write_result(mnesia:transaction(_F)), {reply, R, State}. handle_info({'EXIT', Pid, Reason}, State) when pid(Pid) -> _MF = fun() -> mnesia:match_object({orber_request, '_', '_', '_', '_', '_', '_', Pid}) end, ?query_check(Qres) = mnesia:ets(_MF), case Qres of [] -> true; X -> remove_requests(X), unlink(Pid); _ -> true end, {noreply, State}. %%----------------------------------------------------------------- %% Internal Functions %%----------------------------------------------------------------- get_reqids_from_pid(Pid) -> case mnesia:dirty_match_object({orber_request, '_', '_', '_', '_', '_', '_', Pid}) of Keys -> [Keys] _ -> corba:raise(#'OBJECT_NOT_EXIST'{completion_status=?COMPLETED_NO}) end. remove_requests([]) -> ok; remove_requests([H|T]) -> _F = ?delete_function({orber_request, H#orber_request.reqid}), write_result(mnesia:transaction(_F)), remove_requests(T). %%----------------------------------------------------------------- %% Check a read transaction query_result(?query_check(Qres)) -> case Qres of [Hres] -> Hres#orber_request.pid; [] -> {'excpetion', #'OBJECT_NOT_EXIST'{completion_status=?COMPLETED_NO}}; Other -> {'excpetion', #'INTERNAL'{completion_status=?COMPLETED_NO}} end. %%----------------------------------------------------------------- %% Check a write transaction write_result({atomic,ok}) -> ok; write_result(Foo) -> {'excpetion', #'INTERNAL'{completion_status=?COMPLETED_NO}}. create_schema(Nodes) -> case mnesia:system_info(use_dir) of false -> mnesia:create_schema(Nodes); _ -> ok end. perhaps_start_mnesia() -> case mnesia:system_info(is_running) of no -> mnesia:start(); _ -> ok end. %%------------------------------------------------------------ %% Standard gen_server cast handle %% handle_cast(_, State) -> {noreply, State}.
null
https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/orber/src/corba_request.erl
erlang
-------------------------------------------------------------------- %CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% ----------------------------------------------------------------- File: corba_request.erl Description: ----------------------------------------------------------------- ----------------------------------------------------------------- External exports ----------------------------------------------------------------- ----------------------------------------------------------------- Internal exports ----------------------------------------------------------------- ----------------------------------------------------------------- ----------------------------------------------------------------- ----------------------------------------------------------------- Mnesia table definition ----------------------------------------------------------------- ----------------------------------------------------------------- ----------------------------------------------------------------- This macro returns a read fun suitable for evaluation in a transaction This macro returns a write fun suitable for evaluation in a transaction This macro returns a write fun suitable for evaluation in a transaction This macro returns a delete fun suitable for evaluation in a transaction ----------------------------------------------------------------- Debugging function ----------------------------------------------------------------- ----------------------------------------------------------------- External interface functions ----------------------------------------------------------------- gen_server:call(Pid, stop, infinity) ------------------------------------------------------------ Implementation of standard interface ------------------------------------------------------------ ----------------------------------------------------------------- Server functions ----------------------------------------------------------------- check if there already exists a database. If not, create one. DB_initialized = perhaps_create_schema(Nodelist), Check if any error has occured yet. If there are errors, return them. ----------------------------------------------------------------- Comment: may not be used. It is too time consuming to add catches in every function before returning. On the client side there is a case which maps every tupple on the format {'exception', E} to corba:raise(E). ----------------------------------------------------------------- ----------------------------------------------------------------- Internal Functions ----------------------------------------------------------------- ----------------------------------------------------------------- Check a read transaction ----------------------------------------------------------------- Check a write transaction ------------------------------------------------------------ Standard gen_server cast handle
Copyright Ericsson AB 1998 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " This file contains an corba request server for Orber -module(corba_request). -behaviour(gen_server). -include_lib("orber/include/corba.hrl"). -export([start/1, stop/0, stop_all/0, create/1, create_schema/1]). -export([init/1, terminate/2, install/2, handle_call/3, handle_info/2]). -export([handle_cast/2, dump/0, get_key_from_pid/1]). Standard interface CORBA::Request -export([add_arg/6, invoke/2, delete/1, send/2, get_response/2]). -record('corba_request', {reqid, ctx, operation, arg_list, result, req_flags, pid}). Macros -define(dirty_query_context, true). -define(read_function(ReqId), fun() -> mnesia:dirty_read(ReqId) end). -define(write_function(R), fun() -> mnesia:dirty_write(R) end). -define(update(R), fun() -> mnesia:dirty_write(R) end). -define(delete_function(R), fun() -> mnesia:delete(R) end). -ifdef(dirty_query_context). -define(query_check(Q_res), Q_res). -else. -define(query_check(Q_res), {atomic, Q_res}). -endif. -define(CHECK_EXCEPTION(Res), case Res of {'EXCEPTION', E} -> corba:raise(E); R -> R end). dump() -> case catch mnesia:dirty_first('orber_request') of {'EXIT', R} -> io:format("Exited with ~p\n",[R]); Key -> dump_print(Key), dump_loop(Key) end. dump_loop(PreviousKey) -> case catch mnesia:dirty_next('orber_request', PreviousKey) of {'EXIT', R} -> io:format("Exited with ~p\n",[R]); '$end_of_table' -> ok; Key -> dump_print(Key), dump_loop(Key) end. dump_print(Key) -> case catch mnesia:dirty_read({'orber_request', Key}) of {'EXIT', R} -> io:format("Exited with ~p\n",[R]); [X] -> io:format("Req Id: ~p, op: ~p\n",[binary_to_term(X#orber_request.object_key), X#orber_request.pid]); _ -> ok end. start(Opts) -> gen_server:start_link({local, orber_requestserver}, orber_request, Opts, []). stop() -> gen_server:call(orber_requestserver, stop, infinity). stop_all() -> Fun = fun() -> mnesia:match_object({orber_request, '_', '_', '_', '_', '_', '_', '_'}) end, case catch mnesia:transaction(Fun) of {atomic, Objects} -> lists:foreach(fun({orber_request, _, _, _, _, _, _, _ }) -> end, Objects); R -> R end. create() -> ?CHECK_EXCEPTION(gen_server:call(orber_requestserver, create, infinity)). create(Ctx, OP, Args, Flags) -> ?CHECK_EXCEPTION(gen_server:call(orber_requestserver, {create, Ctx, OP, Args, Flags}, infinity)). delete(ReqId) -> ?CHECK_EXCEPTION(gen_server:call(orber_requestserver, {delete, ReqId}, infinity)). add_arg(ReqId, ArgumentName, TC, Value, Len, ArgFlags) -> Request = ets:lookup_element(orber_request, ReqId), case Request of [] -> ok; R -> Args = Request#orber_request.arg_list, NewArgs = lists:append(Args, []), ets:insert(orber_request, NewArgs), ok end. invoke(ReqId, InvokeFlags) -> ok. send(ReqId, InvokeFlags) -> ok. get_response(ReqId, ResponseFlags) -> [{_, Val}] = ets:lookup_element(orber_request, ReqId), Val#'orber_request'.result. init(Env) -> case mnesia:wait_for_tables(['orber_request'], infinity) of ok -> process_flag(trap_exit, true), {ok, []}; StopReason -> {stop, StopReason} end. terminate(From, Reason) -> ok. install(Timeout, Options) -> check if is running . If not , start . DB_started = perhaps_start_mnesia(), Do we have a complete set of IFR tables ? If not , create them . AllTabs = mnesia:system_info(tables), DB_Result = case lists:member(orber_request, AllTabs) of true -> case lists:member({local_content, true}, Options) of true-> mnesia:add_table_copy(orber_request, node(), ram_copies); _ -> mnesia:create_table(orber_request, [{attributes, record_info(fields, orber_objkeys)} |Options]) end; _ -> mnesia:create_table(orber_request, [{attributes, record_info(fields, orber_objkeys)} |Options]) end, Wait = mnesia:wait_for_tables([orber_request], Timeout), if DB_Result == {atomic, ok}, Wait == ok -> ok; true -> {error, {DB_Result, Wait}} end. Func : handle_call/3 In objectkey gen_server all exceptions are tupples and corba : raise handle_call(stop, From, State) -> {stop, normal, [], State}; handle_call(create, From, State) -> ReqId = term_to_binary({node(), now()}), _F = ?write_function(#'corba_request'{reqid=ReqId}), R = write_result(mnesia:transaction(_F)), ReqId ?query_check(Qres) = mnesia:dirty_read({orber_request, Objkey}), case Qres of [] -> _F = ?write_function(#orber_requests{object_key=Objkey, pid=Pid}), R = write_result(mnesia:transaction(_F)), if R == ok, pid(Pid) -> link(Pid); true -> true end, {reply, R, State}; X -> {reply, {'EXCEPTION', #'INTERNAL'{completion_status=?COMPLETED_NO}}, State} end; handle_call({delete, ReqId}, From, State) -> ?query_check(Qres) = mnesia:dirty_read({orber_request, ReqId}), case Qres of [] -> true; [X] when pid(X#orber_request.pid) -> unlink(X#orber_request.pid); _ -> true end, _F = ?delete_function({orber_request, ReqId}), R = write_result(mnesia:transaction(_F)), {reply, R, State}. handle_info({'EXIT', Pid, Reason}, State) when pid(Pid) -> _MF = fun() -> mnesia:match_object({orber_request, '_', '_', '_', '_', '_', '_', Pid}) end, ?query_check(Qres) = mnesia:ets(_MF), case Qres of [] -> true; X -> remove_requests(X), unlink(Pid); _ -> true end, {noreply, State}. get_reqids_from_pid(Pid) -> case mnesia:dirty_match_object({orber_request, '_', '_', '_', '_', '_', '_', Pid}) of Keys -> [Keys] _ -> corba:raise(#'OBJECT_NOT_EXIST'{completion_status=?COMPLETED_NO}) end. remove_requests([]) -> ok; remove_requests([H|T]) -> _F = ?delete_function({orber_request, H#orber_request.reqid}), write_result(mnesia:transaction(_F)), remove_requests(T). query_result(?query_check(Qres)) -> case Qres of [Hres] -> Hres#orber_request.pid; [] -> {'excpetion', #'OBJECT_NOT_EXIST'{completion_status=?COMPLETED_NO}}; Other -> {'excpetion', #'INTERNAL'{completion_status=?COMPLETED_NO}} end. write_result({atomic,ok}) -> ok; write_result(Foo) -> {'excpetion', #'INTERNAL'{completion_status=?COMPLETED_NO}}. create_schema(Nodes) -> case mnesia:system_info(use_dir) of false -> mnesia:create_schema(Nodes); _ -> ok end. perhaps_start_mnesia() -> case mnesia:system_info(is_running) of no -> mnesia:start(); _ -> ok end. handle_cast(_, State) -> {noreply, State}.
25fa93f29cca3e40f1ee622f3d31287cce8e4676788b196baaae9f6a2faf689c
evturn/haskellbook
14.07-using-quickcheck.hs
import Data.List (sort) import Test.QuickCheck ----------------------------------------------------------------------------- 1 . half :: Fractional a => a -> a half x = x / 2 halfIdentity :: Fractional a => a -> a halfIdentity = (*2) . half prop_halfIdentity :: Double -> Bool prop_halfIdentity x = halfIdentity x == x ----------------------------------------------------------------------------- 2 . listOrdered :: (Ord a) => [a] -> Bool listOrdered xs = snd $ foldr go (Nothing, True) xs where go _ status@(_, False) = status go y (Nothing, t) = (Just y, t) go y (Just x, t) = (Just y, x >= y) prop_listOrdered :: String -> Bool prop_listOrdered = listOrdered . sort ----------------------------------------------------------------------------- 3 . plusAssociative :: Int -> Int -> Int -> Bool plusAssociative x y z = x + (y + z) == (x + y) + z plusCommutative :: Int -> Int -> Bool plusCommutative x y = x + y == y + x ----------------------------------------------------------------------------- 4 . multAssociative :: Int -> Int -> Int -> Bool multAssociative x y z = x * (y * z) == (x * y) * z multCommutative :: Int -> Int -> Bool multCommutative x y = x * y == y * x ----------------------------------------------------------------------------- 5 . -- | NonZero defined in Test.QuickCheck.Modifiers prop_quotRem :: NonZero Int -> NonZero Int -> Bool prop_quotRem (NonZero x) (NonZero y) = (quot x y) * y + (rem x y) == x prop_divMod :: NonZero Int -> NonZero Int -> Bool prop_divMod (NonZero x) (NonZero y) = (div x y) * y + (mod x y) == x ----------------------------------------------------------------------------- 6 . expoAssociative :: Int -> Int -> Int -> Bool expoAssociative x y z = x ^ (y ^ z) == (x ^ y) ^ z expoCommutative :: Int -> Int -> Bool expoCommutative x y = x ^ y == y ^ x ----------------------------------------------------------------------------- 7 . rereverse :: [a] -> [a] rereverse = reverse . reverse orderedListGen :: Gen [Int] orderedListGen = listOf (arbitrary :: Gen Int) prop_reverseId :: Property prop_reverseId = forAll orderedListGen (\xs -> rereverse xs == id xs) ----------------------------------------------------------------------------- 8 . prop_apply :: Property prop_apply = property $ \x -> (+1) x == ((+1) $ (x :: Int)) prop_compose :: Property prop_compose = property $ \x -> ((+1) . (+1) $ x) == ((+1) $ (+1) (x :: Int)) ----------------------------------------------------------------------------- 9 . prop_combineLists :: [Int] -> [Int] -> Bool prop_combineLists xs ys = foldr (:) xs ys == (++) xs ys prop_combineLists' :: [String] -> Bool prop_combineLists' xs = foldr (++) [] xs == concat xs ----------------------------------------------------------------------------- -- .10 prop_lengthTake :: Positive Int -> NonEmptyList [Int] -> Bool prop_lengthTake (Positive n) (NonEmpty xs) = length (take n xs) == n ----------------------------------------------------------------------------- -- .11 prop_showRead :: Property prop_showRead = forAll orderedListGen (\x -> (read (show x)) == x) main :: IO () main = do putStrLn "1. halfIdentity" quickCheck prop_halfIdentity putStrLn "2. listOrdered" quickCheck prop_listOrdered putStrLn "3. plusAssociative" quickCheck plusAssociative putStrLn "3. plusCommutative" quickCheck plusCommutative putStrLn "4. multAssociative" quickCheck multAssociative putStrLn "4. multCommutative" quickCheck multCommutative putStrLn "5. quotRem" quickCheck prop_quotRem putStrLn "5. divMod" quickCheck prop_divMod putStrLn "6. Should fail -- expoAssociative" quickCheck expoAssociative putStrLn "6. Should fail -- expoCommutative" quickCheck expoCommutative putStrLn "7. reverseId" quickCheck prop_reverseId putStrLn "8. ($)" quickCheck prop_apply putStrLn "8. (.)" quickCheck prop_compose putStrLn "9. combineLists" quickCheck prop_combineLists putStrLn "9. combineLists'" quickCheck prop_combineLists' putStrLn "10. lengthTake" quickCheck prop_lengthTake putStrLn "11. showRead" quickCheck prop_showRead
null
https://raw.githubusercontent.com/evturn/haskellbook/3d310d0ddd4221ffc5b9fd7ec6476b2a0731274a/14/14.07-using-quickcheck.hs
haskell
--------------------------------------------------------------------------- --------------------------------------------------------------------------- --------------------------------------------------------------------------- --------------------------------------------------------------------------- --------------------------------------------------------------------------- | NonZero defined in Test.QuickCheck.Modifiers --------------------------------------------------------------------------- --------------------------------------------------------------------------- --------------------------------------------------------------------------- --------------------------------------------------------------------------- --------------------------------------------------------------------------- .10 --------------------------------------------------------------------------- .11
import Data.List (sort) import Test.QuickCheck 1 . half :: Fractional a => a -> a half x = x / 2 halfIdentity :: Fractional a => a -> a halfIdentity = (*2) . half prop_halfIdentity :: Double -> Bool prop_halfIdentity x = halfIdentity x == x 2 . listOrdered :: (Ord a) => [a] -> Bool listOrdered xs = snd $ foldr go (Nothing, True) xs where go _ status@(_, False) = status go y (Nothing, t) = (Just y, t) go y (Just x, t) = (Just y, x >= y) prop_listOrdered :: String -> Bool prop_listOrdered = listOrdered . sort 3 . plusAssociative :: Int -> Int -> Int -> Bool plusAssociative x y z = x + (y + z) == (x + y) + z plusCommutative :: Int -> Int -> Bool plusCommutative x y = x + y == y + x 4 . multAssociative :: Int -> Int -> Int -> Bool multAssociative x y z = x * (y * z) == (x * y) * z multCommutative :: Int -> Int -> Bool multCommutative x y = x * y == y * x 5 . prop_quotRem :: NonZero Int -> NonZero Int -> Bool prop_quotRem (NonZero x) (NonZero y) = (quot x y) * y + (rem x y) == x prop_divMod :: NonZero Int -> NonZero Int -> Bool prop_divMod (NonZero x) (NonZero y) = (div x y) * y + (mod x y) == x 6 . expoAssociative :: Int -> Int -> Int -> Bool expoAssociative x y z = x ^ (y ^ z) == (x ^ y) ^ z expoCommutative :: Int -> Int -> Bool expoCommutative x y = x ^ y == y ^ x 7 . rereverse :: [a] -> [a] rereverse = reverse . reverse orderedListGen :: Gen [Int] orderedListGen = listOf (arbitrary :: Gen Int) prop_reverseId :: Property prop_reverseId = forAll orderedListGen (\xs -> rereverse xs == id xs) 8 . prop_apply :: Property prop_apply = property $ \x -> (+1) x == ((+1) $ (x :: Int)) prop_compose :: Property prop_compose = property $ \x -> ((+1) . (+1) $ x) == ((+1) $ (+1) (x :: Int)) 9 . prop_combineLists :: [Int] -> [Int] -> Bool prop_combineLists xs ys = foldr (:) xs ys == (++) xs ys prop_combineLists' :: [String] -> Bool prop_combineLists' xs = foldr (++) [] xs == concat xs prop_lengthTake :: Positive Int -> NonEmptyList [Int] -> Bool prop_lengthTake (Positive n) (NonEmpty xs) = length (take n xs) == n prop_showRead :: Property prop_showRead = forAll orderedListGen (\x -> (read (show x)) == x) main :: IO () main = do putStrLn "1. halfIdentity" quickCheck prop_halfIdentity putStrLn "2. listOrdered" quickCheck prop_listOrdered putStrLn "3. plusAssociative" quickCheck plusAssociative putStrLn "3. plusCommutative" quickCheck plusCommutative putStrLn "4. multAssociative" quickCheck multAssociative putStrLn "4. multCommutative" quickCheck multCommutative putStrLn "5. quotRem" quickCheck prop_quotRem putStrLn "5. divMod" quickCheck prop_divMod putStrLn "6. Should fail -- expoAssociative" quickCheck expoAssociative putStrLn "6. Should fail -- expoCommutative" quickCheck expoCommutative putStrLn "7. reverseId" quickCheck prop_reverseId putStrLn "8. ($)" quickCheck prop_apply putStrLn "8. (.)" quickCheck prop_compose putStrLn "9. combineLists" quickCheck prop_combineLists putStrLn "9. combineLists'" quickCheck prop_combineLists' putStrLn "10. lengthTake" quickCheck prop_lengthTake putStrLn "11. showRead" quickCheck prop_showRead
775700384d2e24b4e15ec756a42eb1c3d622e733af5b5d4775be8cbd462e6270
ghcjs/ghcjs
Compat.hs
# LANGUAGE CPP , GeneralizedNewtypeDeriving , OverloadedStrings # compatibility with older GHC compatibility with older GHC -} module Compiler.Compat ( PackageKey , packageKeyString , modulePackageKey , stringToPackageKey , primPackageKey , mainPackageKey , modulePackageName , getPackageName , getInstalledPackageName , getPackageVersion , getInstalledPackageVersion , getPackageLibDirs , getInstalledPackageLibDirs , getPackageHsLibs , getInstalledPackageHsLibs , searchModule , Version(..) , showVersion , isEmptyVersion ) where import Module import DynFlags import FastString import Prelude import Packages hiding ( Version ) import Data.Binary import Data.Text (Text) import qualified Data.Text as T import qualified Data.Version as DV -- we do not support version tags since support for them has -- been broken for a long time anyway newtype Version = Version { unVersion :: [Integer] } deriving (Ord, Eq, Show, Binary) showVersion :: Version -> Text showVersion = T.intercalate "." . map (T.pack . show) . unVersion isEmptyVersion :: Version -> Bool isEmptyVersion = null . unVersion convertVersion :: DV.Version -> Version convertVersion v = Version (map fromIntegral $ versionBranch v) type PackageKey = UnitId packageKeyString :: UnitId -> String packageKeyString = unitIdString modulePackageKey :: Module -> UnitId modulePackageKey = moduleUnitId stringToPackageKey :: String -> InstalledUnitId stringToPackageKey = stringToInstalledUnitId primPackageKey :: UnitId primPackageKey = primUnitId mainPackageKey :: UnitId mainPackageKey = mainUnitId getPackageName :: DynFlags -> UnitId -> String getPackageName dflags = maybe "" ((\(PackageName n) -> unpackFS n) . packageName) . lookupPackage dflags getInstalledPackageName :: DynFlags -> InstalledUnitId -> String getInstalledPackageName dflags = maybe "" ((\(PackageName n) -> unpackFS n) . packageName) . lookupInstalledPackage dflags modulePackageName :: DynFlags -> Module -> String modulePackageName dflags = getPackageName dflags . moduleUnitId getPackageVersion :: DynFlags -> UnitId -> Maybe Version getPackageVersion dflags = fmap (convertVersion . packageVersion) . lookupPackage dflags getInstalledPackageVersion :: DynFlags -> InstalledUnitId -> Maybe Version getInstalledPackageVersion dflags = fmap (convertVersion . packageVersion) . lookupInstalledPackage dflags getPackageLibDirs :: DynFlags -> UnitId -> [FilePath] getPackageLibDirs dflags = maybe [] libraryDirs . lookupPackage dflags getInstalledPackageLibDirs :: DynFlags -> InstalledUnitId -> [FilePath] getInstalledPackageLibDirs dflags = maybe [] libraryDirs . lookupInstalledPackage dflags getPackageHsLibs :: DynFlags -> UnitId -> [String] getPackageHsLibs dflags = maybe [] hsLibraries . lookupPackage dflags getInstalledPackageHsLibs :: DynFlags -> InstalledUnitId -> [String] getInstalledPackageHsLibs dflags = maybe [] hsLibraries . lookupInstalledPackage dflags searchModule :: DynFlags -> ModuleName -> [(String, UnitId)] searchModule dflags = map ((\k -> (getPackageName dflags k, k)) . moduleUnitId . fst) $ fromLookupResult $ lookupModuleWithSuggestions dflags mn Nothing . lookupModuleInAllPackages dflags
null
https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/src/Compiler/Compat.hs
haskell
we do not support version tags since support for them has been broken for a long time anyway
# LANGUAGE CPP , GeneralizedNewtypeDeriving , OverloadedStrings # compatibility with older GHC compatibility with older GHC -} module Compiler.Compat ( PackageKey , packageKeyString , modulePackageKey , stringToPackageKey , primPackageKey , mainPackageKey , modulePackageName , getPackageName , getInstalledPackageName , getPackageVersion , getInstalledPackageVersion , getPackageLibDirs , getInstalledPackageLibDirs , getPackageHsLibs , getInstalledPackageHsLibs , searchModule , Version(..) , showVersion , isEmptyVersion ) where import Module import DynFlags import FastString import Prelude import Packages hiding ( Version ) import Data.Binary import Data.Text (Text) import qualified Data.Text as T import qualified Data.Version as DV newtype Version = Version { unVersion :: [Integer] } deriving (Ord, Eq, Show, Binary) showVersion :: Version -> Text showVersion = T.intercalate "." . map (T.pack . show) . unVersion isEmptyVersion :: Version -> Bool isEmptyVersion = null . unVersion convertVersion :: DV.Version -> Version convertVersion v = Version (map fromIntegral $ versionBranch v) type PackageKey = UnitId packageKeyString :: UnitId -> String packageKeyString = unitIdString modulePackageKey :: Module -> UnitId modulePackageKey = moduleUnitId stringToPackageKey :: String -> InstalledUnitId stringToPackageKey = stringToInstalledUnitId primPackageKey :: UnitId primPackageKey = primUnitId mainPackageKey :: UnitId mainPackageKey = mainUnitId getPackageName :: DynFlags -> UnitId -> String getPackageName dflags = maybe "" ((\(PackageName n) -> unpackFS n) . packageName) . lookupPackage dflags getInstalledPackageName :: DynFlags -> InstalledUnitId -> String getInstalledPackageName dflags = maybe "" ((\(PackageName n) -> unpackFS n) . packageName) . lookupInstalledPackage dflags modulePackageName :: DynFlags -> Module -> String modulePackageName dflags = getPackageName dflags . moduleUnitId getPackageVersion :: DynFlags -> UnitId -> Maybe Version getPackageVersion dflags = fmap (convertVersion . packageVersion) . lookupPackage dflags getInstalledPackageVersion :: DynFlags -> InstalledUnitId -> Maybe Version getInstalledPackageVersion dflags = fmap (convertVersion . packageVersion) . lookupInstalledPackage dflags getPackageLibDirs :: DynFlags -> UnitId -> [FilePath] getPackageLibDirs dflags = maybe [] libraryDirs . lookupPackage dflags getInstalledPackageLibDirs :: DynFlags -> InstalledUnitId -> [FilePath] getInstalledPackageLibDirs dflags = maybe [] libraryDirs . lookupInstalledPackage dflags getPackageHsLibs :: DynFlags -> UnitId -> [String] getPackageHsLibs dflags = maybe [] hsLibraries . lookupPackage dflags getInstalledPackageHsLibs :: DynFlags -> InstalledUnitId -> [String] getInstalledPackageHsLibs dflags = maybe [] hsLibraries . lookupInstalledPackage dflags searchModule :: DynFlags -> ModuleName -> [(String, UnitId)] searchModule dflags = map ((\k -> (getPackageName dflags k, k)) . moduleUnitId . fst) $ fromLookupResult $ lookupModuleWithSuggestions dflags mn Nothing . lookupModuleInAllPackages dflags
fc7ae4873a2e0368e5e83cc5f96791b3cfdb15c0b844ebbd466a040ce36056a3
soegaard/pyffi
python.rkt
#lang racket/base (require "structs.rkt" "python-attributes.rkt" "python-builtins.rkt" "python-bytes.rkt" "python-c-api.rkt" "python-define-delayed.rkt" "python-dict.rkt" "python-environment.rkt" "python-evaluation.rkt" "python-functions.rkt" "python-generator.rkt" "python-initialization.rkt" "python-import.rkt" "python-list.rkt" "python-module.rkt" "python-more-builtins.rkt" "python-operators.rkt" "python-slice.rkt" "python-string.rkt" "python-tuple.rkt" "python-types.rkt") (provide (except-out (all-from-out "structs.rkt" "python-attributes.rkt" "python-builtins.rkt" "python-bytes.rkt" "python-c-api.rkt" "python-define-delayed.rkt" "python-dict.rkt" "python-environment.rkt" "python-evaluation.rkt" "python-functions.rkt" "python-generator.rkt" "python-initialization.rkt" "python-import.rkt" "python-list.rkt" "python-module.rkt" "python-more-builtins.rkt" "python-operators.rkt" "python-slice.rkt" "python-string.rkt" "python-tuple.rkt" "python-types.rkt") ; the values are wrapped in an obj struct below builtins main ; The procedures run and run* return cpointers. Automatic ` pr ` conversion is provided below run run*)) (require "python-delayed.rkt") ;; Modules: builtins, main (define obj-builtins 'uninitialized-obj-builtins) (define obj-main 'uninitialized-obj-main) (add-initialization-thunk (λ () (set! obj-builtins (obj "module" builtins)) (set! obj-main (obj "module" main)))) (provide (rename-out [obj-builtins builtins] [obj-main main])) ;; Automatic conversion: run, run* (require (for-syntax racket/base syntax/parse racket/syntax)) (require racket/format racket/string) (define py-format-exception 'uninitialized-py-format-exception) (define py-format-exception-only 'uninitialized-py-format-exception-only) (define py-format-traceback 'uninitialized-py-format-traceback) (add-initialization-thunk (λ () (set! py-format-exception (get 'traceback.format_exception)) (set! py-format-exception-only (get 'traceback.format_exception_only)) (set! py-format-traceback (get 'traceback.format_tb)))) (define-syntax (handle-python-exception stx) ; When `run` and `run*`returns NULL (represented as #f in Racket), it means an exception occurred on the Python side . ; We must fetch and normalize the exception, exception value and the traceback. Fetching the exception clears the exception flags on the Python side . Formatting the exception as a string is done using the Python module ` traceback ` . (syntax-parse stx [(_handle-python-exception qualified-name result:id) (syntax/loc stx (cond ; everything went fine [result result] ; an exception was raised [else ; fetch exception (and clear flags), then normalize the exception value (define-values (ptype pvalue ptraceback) (PyErr_Fetch)) (define-values (ntype nvalue ntraceback) (PyErr_NormalizeException ptype pvalue ptraceback)) ; format the exception so we can print it ( define msg ( let ( [ args ( flat - vector->py - tuple ( vector ntype nvalue ntraceback ) ) ] ) (python->racket (PyObject_Call py-format-exception args #f)))) (define msg (let ([args (flat-vector->py-tuple (vector ntype nvalue))]) (define x (PyObject_Call py-format-exception-only args #f)) (py-list->list/pr x))) (define tb (and ntraceback (let ([args (flat-vector->py-tuple (vector ntraceback))]) (py-list->list/pr (PyObject_Call py-format-traceback args #f))))) ;; Racket error message convention: ;; ‹srcloc›: ‹name›: ‹message›; ;; ‹continued-message› ... ‹field› : ‹detail› (define full-msg (~a ; "src-loc" ": " qualified-name ": " "Python exception occurred" ";\n" (string-append* (map (λ (m) (~a " " (pystring->string m))) msg)) (if tb (string-append* (map (λ (m) (~a " " m)) tb)) ""))) (raise (exn full-msg (current-continuation-marks)))]))])) (define (prrun x) (define result (run x)) (handle-python-exception 'run result) (pr result)) (define (prrun* x) (define result (run* x)) (handle-python-exception 'run* result) (void result)) (provide (rename-out [prrun run] [prrun* run*]))
null
https://raw.githubusercontent.com/soegaard/pyffi/3c7abdd6463399105f1e4236cd7bfc269e6b2f38/pyffi-lib/pyffi/python.rkt
racket
the values are wrapped in an obj struct below The procedures run and run* return cpointers. Modules: builtins, main Automatic conversion: run, run* When `run` and `run*`returns NULL (represented as #f in Racket), We must fetch and normalize the exception, exception value and the traceback. everything went fine an exception was raised fetch exception (and clear flags), then normalize the exception value format the exception so we can print it Racket error message convention: ‹srcloc›: ‹name›: ‹message›; ‹continued-message› ... "src-loc" ": "
#lang racket/base (require "structs.rkt" "python-attributes.rkt" "python-builtins.rkt" "python-bytes.rkt" "python-c-api.rkt" "python-define-delayed.rkt" "python-dict.rkt" "python-environment.rkt" "python-evaluation.rkt" "python-functions.rkt" "python-generator.rkt" "python-initialization.rkt" "python-import.rkt" "python-list.rkt" "python-module.rkt" "python-more-builtins.rkt" "python-operators.rkt" "python-slice.rkt" "python-string.rkt" "python-tuple.rkt" "python-types.rkt") (provide (except-out (all-from-out "structs.rkt" "python-attributes.rkt" "python-builtins.rkt" "python-bytes.rkt" "python-c-api.rkt" "python-define-delayed.rkt" "python-dict.rkt" "python-environment.rkt" "python-evaluation.rkt" "python-functions.rkt" "python-generator.rkt" "python-initialization.rkt" "python-import.rkt" "python-list.rkt" "python-module.rkt" "python-more-builtins.rkt" "python-operators.rkt" "python-slice.rkt" "python-string.rkt" "python-tuple.rkt" "python-types.rkt") builtins main Automatic ` pr ` conversion is provided below run run*)) (require "python-delayed.rkt") (define obj-builtins 'uninitialized-obj-builtins) (define obj-main 'uninitialized-obj-main) (add-initialization-thunk (λ () (set! obj-builtins (obj "module" builtins)) (set! obj-main (obj "module" main)))) (provide (rename-out [obj-builtins builtins] [obj-main main])) (require (for-syntax racket/base syntax/parse racket/syntax)) (require racket/format racket/string) (define py-format-exception 'uninitialized-py-format-exception) (define py-format-exception-only 'uninitialized-py-format-exception-only) (define py-format-traceback 'uninitialized-py-format-traceback) (add-initialization-thunk (λ () (set! py-format-exception (get 'traceback.format_exception)) (set! py-format-exception-only (get 'traceback.format_exception_only)) (set! py-format-traceback (get 'traceback.format_tb)))) (define-syntax (handle-python-exception stx) it means an exception occurred on the Python side . Fetching the exception clears the exception flags on the Python side . Formatting the exception as a string is done using the Python module ` traceback ` . (syntax-parse stx [(_handle-python-exception qualified-name result:id) (syntax/loc stx (cond [result result] [else (define-values (ptype pvalue ptraceback) (PyErr_Fetch)) (define-values (ntype nvalue ntraceback) (PyErr_NormalizeException ptype pvalue ptraceback)) ( define msg ( let ( [ args ( flat - vector->py - tuple ( vector ntype nvalue ntraceback ) ) ] ) (python->racket (PyObject_Call py-format-exception args #f)))) (define msg (let ([args (flat-vector->py-tuple (vector ntype nvalue))]) (define x (PyObject_Call py-format-exception-only args #f)) (py-list->list/pr x))) (define tb (and ntraceback (let ([args (flat-vector->py-tuple (vector ntraceback))]) (py-list->list/pr (PyObject_Call py-format-traceback args #f))))) ‹field› : ‹detail› (define full-msg qualified-name ": " "Python exception occurred" ";\n" (string-append* (map (λ (m) (~a " " (pystring->string m))) msg)) (if tb (string-append* (map (λ (m) (~a " " m)) tb)) ""))) (raise (exn full-msg (current-continuation-marks)))]))])) (define (prrun x) (define result (run x)) (handle-python-exception 'run result) (pr result)) (define (prrun* x) (define result (run* x)) (handle-python-exception 'run* result) (void result)) (provide (rename-out [prrun run] [prrun* run*]))
26345eed759d726f7df279a418f297f398dbb61256dd6d6b3f2d93579b520577
MrEbbinghaus/fulcro-material-ui-wrapper
card.cljc
(ns ^:deprecated material-ui.surfaces.card (:require [com.fulcrologic.fulcro.algorithms.react-interop :as interop] #?@(:cljs [["@mui/material/Card" :default Card] ["@mui/material/CardContent" :default CardContent] ["@mui/material/CardActions" :default CardActions] ["@mui/material/CardHeader" :default CardHeader] ["@mui/material/CardMedia" :default CardMedia] ["@mui/material/CardActionArea" :default CardActionArea]]))) (def card (interop/react-factory #?(:cljs Card :clj nil))) (def content (interop/react-factory #?(:cljs CardContent :clj nil))) (def actions (interop/react-factory #?(:cljs CardActions :clj nil))) (def action-area (interop/react-factory #?(:cljs CardActionArea :clj nil))) (def header (interop/react-factory #?(:cljs CardHeader :clj nil))) (def media (interop/react-factory #?(:cljs CardMedia :clj nil)))
null
https://raw.githubusercontent.com/MrEbbinghaus/fulcro-material-ui-wrapper/058f1dd4b85542914f92f48a4010ea9ad497e48f/src/material_ui/surfaces/card.cljc
clojure
(ns ^:deprecated material-ui.surfaces.card (:require [com.fulcrologic.fulcro.algorithms.react-interop :as interop] #?@(:cljs [["@mui/material/Card" :default Card] ["@mui/material/CardContent" :default CardContent] ["@mui/material/CardActions" :default CardActions] ["@mui/material/CardHeader" :default CardHeader] ["@mui/material/CardMedia" :default CardMedia] ["@mui/material/CardActionArea" :default CardActionArea]]))) (def card (interop/react-factory #?(:cljs Card :clj nil))) (def content (interop/react-factory #?(:cljs CardContent :clj nil))) (def actions (interop/react-factory #?(:cljs CardActions :clj nil))) (def action-area (interop/react-factory #?(:cljs CardActionArea :clj nil))) (def header (interop/react-factory #?(:cljs CardHeader :clj nil))) (def media (interop/react-factory #?(:cljs CardMedia :clj nil)))
3cf0022fd467f435b6e22437a22c1191c56a274fd88c93cdc5f142975b653b6f
walmartlabs/lacinia-pedestal
internal.clj
Copyright ( c ) 2020 - present Walmart , 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. (ns ^:no-doc com.walmartlabs.lacinia.pedestal.internal "Internal utilities not part of the public API." (:require [clojure.core.async :refer [chan put!]] [cheshire.core :as cheshire] [com.walmartlabs.lacinia.util :as util] [com.walmartlabs.lacinia.parser :as parser] [com.walmartlabs.lacinia.pedestal.cache :as cache] [clojure.string :as str] [com.walmartlabs.lacinia.validator :as validator] [com.walmartlabs.lacinia.constants :as constants] [com.walmartlabs.lacinia.resolve :as resolve] [com.walmartlabs.lacinia.executor :as executor] [io.pedestal.log :as log] [clojure.java.io :as io] [ring.util.response :as response] [io.pedestal.http.jetty.websockets :as ws] [io.pedestal.http :as http] [io.pedestal.interceptor.chain :as chain] [com.walmartlabs.lacinia.pedestal.subscriptions :as subscriptions] [com.walmartlabs.lacinia.tracing :as tracing])) (def ^:private parsed-query-key-path [:request :parsed-lacinia-query]) (defn parse-content-type "Parse `s` as an RFC 2616 media type." [s] (if-let [[_ type _ _ raw-params] (re-matches #"\s*(([^/]+)/([^ ;]+))\s*(\s*;.*)?" (str s))] {:content-type (keyword type) :content-type-params (->> (str/split (str raw-params) #"\s*;\s*") (keep identity) (remove str/blank?) (map #(str/split % #"=")) (mapcat (fn [[k v]] [(keyword (str/lower-case k)) (str/trim v)])) (apply hash-map))})) (defn content-type "Gets the content-type of a request. (without encoding)" [request] (when-let [content-type (get-in request [:headers "content-type"])] (:content-type (parse-content-type content-type)))) (defn on-leave-json-response [context] (let [body (get-in context [:response :body])] (if (map? body) (-> context (assoc-in [:response :headers "Content-Type"] "application/json") (update-in [:response :body] cheshire/generate-string)) context))) (defn failure-response "Generates a bad request Ring response." ([body] (failure-response 400 body)) ([status body] {:status status :headers {} :body body})) (defn message-as-errors [message] {:errors [{:message message}]}) (defn as-errors [exception] {:errors [(util/as-error-map exception)]}) (defn on-enter-query-parser [context compiled-schema cache timing-start] (let [{:keys [graphql-query graphql-operation-name]} (:request context) cache-key (when cache (if graphql-operation-name [graphql-query graphql-operation-name] graphql-query)) cached (cache/get-parsed-query cache cache-key)] (if cached (assoc-in context parsed-query-key-path cached) (try (let [actual-schema (if (map? compiled-schema) compiled-schema (compiled-schema)) parsed-query (parser/parse-query actual-schema graphql-query graphql-operation-name timing-start)] (->> parsed-query (cache/store-parsed-query cache cache-key) (assoc-in context parsed-query-key-path))) (catch Exception e (assoc context :response (failure-response (as-errors e)))))))) (defn on-leave-query-parser [context] (update context :request dissoc :parsed-lacinia-query)) (defn add-error [context exception] (assoc context ::chain/error exception)) (defn on-error-query-parser [context exception] (-> (on-leave-query-parser context) (add-error exception))) (defn on-error-error-response [context ex] (let [{:keys [exception]} (ex-data ex)] (assoc context :response (failure-response 500 (as-errors exception))))) (defn on-enter-prepare-query [context] (try (let [{parsed-query :parsed-lacinia-query vars :graphql-vars} (:request context) {:keys [::tracing/timing-start]} parsed-query start-offset (tracing/offset-from-start timing-start) start-nanos (System/nanoTime) prepared (parser/prepare-with-query-variables parsed-query vars) compiled-schema (get prepared constants/schema-key) errors (validator/validate compiled-schema prepared {}) prepared' (assoc prepared ::tracing/validation {:start-offset start-offset :duration (tracing/duration start-nanos)})] (if (seq errors) (assoc context :response (failure-response {:errors errors})) (assoc-in context parsed-query-key-path prepared'))) (catch Exception e (assoc context :response (failure-response (as-errors e)))))) (defn ^:private remove-status "Remove the :status key from the :extensions map; remove the :extensions key if that is now empty." [error-map] (if-not (contains? error-map :extensions) error-map (let [error-map' (update error-map :extensions dissoc :status)] (if (-> error-map' :extensions seq) error-map' (dissoc error-map' :extensions))))) (defn on-leave-status-conversion [context] (let [response (:response context) errors (get-in response [:body :errors]) statuses (keep #(-> % :extensions :status) errors)] (if (seq statuses) (let [max-status (reduce max (:status response) statuses)] (-> context (assoc-in [:response :status] max-status) (assoc-in [:response :body :errors] (map remove-status errors)))) context))) (defn ^:private apply-exception-to-context "Applies exception to context in the same way Pedestal would if thrown from a synchronous interceptor. Based on the (private) `io.pedestal.interceptor.chain/throwable->ex-info` function of pedestal" [{::chain/keys [execution-id] :as context} exception interceptor-name] (let [exception-str (pr-str (type exception)) msg (str exception-str " in Interceptor " interceptor-name " - " (ex-message exception)) wrapped-exception (ex-info msg (merge {:execution-id execution-id :stage :enter :interceptor interceptor-name :exception-type (keyword exception-str) :exception exception} (ex-data exception)) exception)] (assoc context ::chain/error wrapped-exception))) (defn ^:private apply-result-to-context [context result interceptor-name] Lacinia changed the contract here in 0.36.0 ( to support timeouts ) ; the result ;; may be an exception thrown during initial processing of the query. (if (instance? Throwable result) (do (log/error :event :execution-exception :ex result) ;; Put error in the context map for error interceptors to consume ;; If unhandled, will end up in [[error-response-interceptor]] (apply-exception-to-context context result interceptor-name)) ;; When :data is missing, then a failure occurred during parsing or preparing ;; the request, which indicates a bad request, rather than some failure ;; during execution. (let [status (if (contains? result :data) 200 400) response {:status status :headers {} :body result}] (assoc context :response response)))) (defn ^:private execute-query [context] (let [request (:request context) {q :parsed-lacinia-query app-context :lacinia-app-context} request] (executor/execute-query (assoc app-context constants/parsed-query-key q)))) (defn on-enter-query-executor [interceptor-name] (fn [context] (let [resolver-result (execute-query context) *result (promise)] (resolve/on-deliver! resolver-result (fn [result] (deliver *result result))) (apply-result-to-context context @*result interceptor-name)))) (defn on-enter-async-query-executor [interceptor-name] (fn [context] (let [ch (chan 1) resolver-result (execute-query context)] (resolve/on-deliver! resolver-result (fn [result] (put! ch (apply-result-to-context context result interceptor-name)))) ch))) (defn on-enter-disallow-subscriptions [context] (if (-> context :request :parsed-lacinia-query parser/operations :type (= :subscription)) (assoc context :response (failure-response (message-as-errors "Subscription queries must be processed by the WebSockets endpoint."))) context)) (defn ^:private request-headers-string [headers] (str "{" (->> headers (map (fn [[k v]] (str \" (name k) "\": \"" (name v) \"))) (str/join ", ")) "}")) (defn graphiql-response [api-path subscriptions-path asset-path ide-headers ide-connection-params] (let [replacements {:asset-path asset-path :api-path api-path :subscriptions-path subscriptions-path :initial-connection-params (cheshire/generate-string ide-connection-params) :request-headers (request-headers-string ide-headers)}] (-> "com/walmartlabs/lacinia/pedestal/graphiql.html" io/resource slurp (str/replace #"\{\{(.+?)}}" (fn [[_ key]] (get replacements (keyword key) "--NO-MATCH--"))) response/response (response/content-type "text/html")))) (defn add-subscriptions-support [service-map compiled-schema subscriptions-path subscription-options] (assoc-in service-map [::http/container-options :context-configurator] ;; The listener-fn is responsible for creating the listener; it is passed ;; the request, response, and the ws-map. In sample code, the ws-map ;; has callbacks such as :on-connect and :on-text, but in our scenario ;; the callbacks are created by the listener-fn, so the value is nil. #(ws/add-ws-endpoints % {subscriptions-path nil} {:listener-fn (subscriptions/listener-fn-factory compiled-schema subscription-options)})))
null
https://raw.githubusercontent.com/walmartlabs/lacinia-pedestal/1db186bc35404093a533c66b550b4891271b9401/src/com/walmartlabs/lacinia/pedestal/internal.clj
clojure
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. the result may be an exception thrown during initial processing of the query. Put error in the context map for error interceptors to consume If unhandled, will end up in [[error-response-interceptor]] When :data is missing, then a failure occurred during parsing or preparing the request, which indicates a bad request, rather than some failure during execution. The listener-fn is responsible for creating the listener; it is passed the request, response, and the ws-map. In sample code, the ws-map has callbacks such as :on-connect and :on-text, but in our scenario the callbacks are created by the listener-fn, so the value is nil.
Copyright ( c ) 2020 - present Walmart , Inc. Licensed under the Apache License , Version 2.0 ( the " License " ) distributed under the License is distributed on an " AS IS " BASIS , (ns ^:no-doc com.walmartlabs.lacinia.pedestal.internal "Internal utilities not part of the public API." (:require [clojure.core.async :refer [chan put!]] [cheshire.core :as cheshire] [com.walmartlabs.lacinia.util :as util] [com.walmartlabs.lacinia.parser :as parser] [com.walmartlabs.lacinia.pedestal.cache :as cache] [clojure.string :as str] [com.walmartlabs.lacinia.validator :as validator] [com.walmartlabs.lacinia.constants :as constants] [com.walmartlabs.lacinia.resolve :as resolve] [com.walmartlabs.lacinia.executor :as executor] [io.pedestal.log :as log] [clojure.java.io :as io] [ring.util.response :as response] [io.pedestal.http.jetty.websockets :as ws] [io.pedestal.http :as http] [io.pedestal.interceptor.chain :as chain] [com.walmartlabs.lacinia.pedestal.subscriptions :as subscriptions] [com.walmartlabs.lacinia.tracing :as tracing])) (def ^:private parsed-query-key-path [:request :parsed-lacinia-query]) (defn parse-content-type "Parse `s` as an RFC 2616 media type." [s] (if-let [[_ type _ _ raw-params] (re-matches #"\s*(([^/]+)/([^ ;]+))\s*(\s*;.*)?" (str s))] {:content-type (keyword type) :content-type-params (->> (str/split (str raw-params) #"\s*;\s*") (keep identity) (remove str/blank?) (map #(str/split % #"=")) (mapcat (fn [[k v]] [(keyword (str/lower-case k)) (str/trim v)])) (apply hash-map))})) (defn content-type "Gets the content-type of a request. (without encoding)" [request] (when-let [content-type (get-in request [:headers "content-type"])] (:content-type (parse-content-type content-type)))) (defn on-leave-json-response [context] (let [body (get-in context [:response :body])] (if (map? body) (-> context (assoc-in [:response :headers "Content-Type"] "application/json") (update-in [:response :body] cheshire/generate-string)) context))) (defn failure-response "Generates a bad request Ring response." ([body] (failure-response 400 body)) ([status body] {:status status :headers {} :body body})) (defn message-as-errors [message] {:errors [{:message message}]}) (defn as-errors [exception] {:errors [(util/as-error-map exception)]}) (defn on-enter-query-parser [context compiled-schema cache timing-start] (let [{:keys [graphql-query graphql-operation-name]} (:request context) cache-key (when cache (if graphql-operation-name [graphql-query graphql-operation-name] graphql-query)) cached (cache/get-parsed-query cache cache-key)] (if cached (assoc-in context parsed-query-key-path cached) (try (let [actual-schema (if (map? compiled-schema) compiled-schema (compiled-schema)) parsed-query (parser/parse-query actual-schema graphql-query graphql-operation-name timing-start)] (->> parsed-query (cache/store-parsed-query cache cache-key) (assoc-in context parsed-query-key-path))) (catch Exception e (assoc context :response (failure-response (as-errors e)))))))) (defn on-leave-query-parser [context] (update context :request dissoc :parsed-lacinia-query)) (defn add-error [context exception] (assoc context ::chain/error exception)) (defn on-error-query-parser [context exception] (-> (on-leave-query-parser context) (add-error exception))) (defn on-error-error-response [context ex] (let [{:keys [exception]} (ex-data ex)] (assoc context :response (failure-response 500 (as-errors exception))))) (defn on-enter-prepare-query [context] (try (let [{parsed-query :parsed-lacinia-query vars :graphql-vars} (:request context) {:keys [::tracing/timing-start]} parsed-query start-offset (tracing/offset-from-start timing-start) start-nanos (System/nanoTime) prepared (parser/prepare-with-query-variables parsed-query vars) compiled-schema (get prepared constants/schema-key) errors (validator/validate compiled-schema prepared {}) prepared' (assoc prepared ::tracing/validation {:start-offset start-offset :duration (tracing/duration start-nanos)})] (if (seq errors) (assoc context :response (failure-response {:errors errors})) (assoc-in context parsed-query-key-path prepared'))) (catch Exception e (assoc context :response (failure-response (as-errors e)))))) (defn ^:private remove-status "Remove the :status key from the :extensions map; remove the :extensions key if that is now empty." [error-map] (if-not (contains? error-map :extensions) error-map (let [error-map' (update error-map :extensions dissoc :status)] (if (-> error-map' :extensions seq) error-map' (dissoc error-map' :extensions))))) (defn on-leave-status-conversion [context] (let [response (:response context) errors (get-in response [:body :errors]) statuses (keep #(-> % :extensions :status) errors)] (if (seq statuses) (let [max-status (reduce max (:status response) statuses)] (-> context (assoc-in [:response :status] max-status) (assoc-in [:response :body :errors] (map remove-status errors)))) context))) (defn ^:private apply-exception-to-context "Applies exception to context in the same way Pedestal would if thrown from a synchronous interceptor. Based on the (private) `io.pedestal.interceptor.chain/throwable->ex-info` function of pedestal" [{::chain/keys [execution-id] :as context} exception interceptor-name] (let [exception-str (pr-str (type exception)) msg (str exception-str " in Interceptor " interceptor-name " - " (ex-message exception)) wrapped-exception (ex-info msg (merge {:execution-id execution-id :stage :enter :interceptor interceptor-name :exception-type (keyword exception-str) :exception exception} (ex-data exception)) exception)] (assoc context ::chain/error wrapped-exception))) (defn ^:private apply-result-to-context [context result interceptor-name] (if (instance? Throwable result) (do (log/error :event :execution-exception :ex result) (apply-exception-to-context context result interceptor-name)) (let [status (if (contains? result :data) 200 400) response {:status status :headers {} :body result}] (assoc context :response response)))) (defn ^:private execute-query [context] (let [request (:request context) {q :parsed-lacinia-query app-context :lacinia-app-context} request] (executor/execute-query (assoc app-context constants/parsed-query-key q)))) (defn on-enter-query-executor [interceptor-name] (fn [context] (let [resolver-result (execute-query context) *result (promise)] (resolve/on-deliver! resolver-result (fn [result] (deliver *result result))) (apply-result-to-context context @*result interceptor-name)))) (defn on-enter-async-query-executor [interceptor-name] (fn [context] (let [ch (chan 1) resolver-result (execute-query context)] (resolve/on-deliver! resolver-result (fn [result] (put! ch (apply-result-to-context context result interceptor-name)))) ch))) (defn on-enter-disallow-subscriptions [context] (if (-> context :request :parsed-lacinia-query parser/operations :type (= :subscription)) (assoc context :response (failure-response (message-as-errors "Subscription queries must be processed by the WebSockets endpoint."))) context)) (defn ^:private request-headers-string [headers] (str "{" (->> headers (map (fn [[k v]] (str \" (name k) "\": \"" (name v) \"))) (str/join ", ")) "}")) (defn graphiql-response [api-path subscriptions-path asset-path ide-headers ide-connection-params] (let [replacements {:asset-path asset-path :api-path api-path :subscriptions-path subscriptions-path :initial-connection-params (cheshire/generate-string ide-connection-params) :request-headers (request-headers-string ide-headers)}] (-> "com/walmartlabs/lacinia/pedestal/graphiql.html" io/resource slurp (str/replace #"\{\{(.+?)}}" (fn [[_ key]] (get replacements (keyword key) "--NO-MATCH--"))) response/response (response/content-type "text/html")))) (defn add-subscriptions-support [service-map compiled-schema subscriptions-path subscription-options] (assoc-in service-map [::http/container-options :context-configurator] #(ws/add-ws-endpoints % {subscriptions-path nil} {:listener-fn (subscriptions/listener-fn-factory compiled-schema subscription-options)})))
4be21f721fcfc7e7b0153227aabbac2f9ddc74a01a23dad8952eea7f78c153b7
coq/coq
global.mli
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) * GNU Lesser General Public License Version 2.1 (* * (see LICENSE file for the text of the license) *) (************************************************************************) open Names open Declarations * This module defines the global environment of Coq . The functions below are exactly the same as the ones in [ Safe_typing ] , operating on that global environment . [ add _ * ] functions perform name verification , i.e. check that the name given as argument match those provided by [ Safe_typing ] . below are exactly the same as the ones in [Safe_typing], operating on that global environment. [add_*] functions perform name verification, i.e. check that the name given as argument match those provided by [Safe_typing]. *) val safe_env : unit -> Safe_typing.safe_environment val env : unit -> Environ.env val universes : unit -> UGraph.t val universes_lbound : unit -> UGraph.Bound.t val named_context_val : unit -> Environ.named_context_val val named_context : unit -> Constr.named_context * { 6 Enriching the global environment } (** Changing the (im)predicativity of the system *) val set_impredicative_set : bool -> unit val set_indices_matter : bool -> unit val set_typing_flags : typing_flags -> unit val set_check_guarded : bool -> unit val set_check_positive : bool -> unit val set_check_universes : bool -> unit val typing_flags : unit -> typing_flags val set_allow_sprop : bool -> unit val sprop_allowed : unit -> bool (** Variables, Local definitions, constants, inductive types *) val push_named_assum : (Id.t * Constr.types) -> unit val push_named_def : (Id.t * Entries.section_def_entry) -> unit val push_section_context : Univ.UContext.t -> unit val export_private_constants : Safe_typing.private_constants -> Safe_typing.exported_private_constant list val add_constant : ?typing_flags:typing_flags -> Id.t -> Safe_typing.global_declaration -> Constant.t val fill_opaque : Safe_typing.opaque_certificate -> unit val add_private_constant : Id.t -> Univ.ContextSet.t -> Safe_typing.side_effect_declaration -> Constant.t * Safe_typing.private_constants val add_mind : ?typing_flags:typing_flags -> Id.t -> Entries.mutual_inductive_entry -> MutInd.t (** Extra universe constraints *) val add_constraints : Univ.Constraints.t -> unit val push_context_set : strict:bool -> Univ.ContextSet.t -> unit (** Non-interactive modules and module types *) val add_module : Id.t -> Entries.module_entry -> inline -> ModPath.t * Mod_subst.delta_resolver val add_modtype : Id.t -> Entries.module_type_entry -> inline -> ModPath.t val add_include : Entries.module_struct_entry -> bool -> inline -> Mod_subst.delta_resolver (** Sections *) val open_section : unit -> unit (** [poly] is true when the section should be universe polymorphic *) val close_section : Summary.frozen -> unit (** Close the section and reset the global state to the one at the time when the section what opened. *) val sections_are_opened : unit -> bool (** Interactive modules and module types *) val start_module : Id.t -> ModPath.t val start_modtype : Id.t -> ModPath.t val end_module : Summary.frozen -> Id.t -> (Entries.module_struct_entry * inline) option -> ModPath.t * MBId.t list * Mod_subst.delta_resolver val end_modtype : Summary.frozen -> Id.t -> ModPath.t * MBId.t list val add_module_parameter : MBId.t -> Entries.module_struct_entry -> inline -> Mod_subst.delta_resolver (** {6 Queries in the global environment } *) val lookup_named : variable -> Constr.named_declaration val lookup_constant : Constant.t -> constant_body val lookup_inductive : inductive -> mutual_inductive_body * one_inductive_body val lookup_pinductive : Constr.pinductive -> mutual_inductive_body * one_inductive_body val lookup_mind : MutInd.t -> mutual_inductive_body val lookup_module : ModPath.t -> module_body val lookup_modtype : ModPath.t -> module_type_body val exists_objlabel : Label.t -> bool val constant_of_delta_kn : KerName.t -> Constant.t val mind_of_delta_kn : KerName.t -> MutInd.t type indirect_accessor = { access_proof : Opaqueproof.opaque -> (Constr.t * unit Opaqueproof.delayed_universes) option; } val force_proof : indirect_accessor -> Opaqueproof.opaque -> Constr.t * unit Opaqueproof.delayed_universes val body_of_constant : indirect_accessor -> Constant.t -> (Constr.constr * unit Opaqueproof.delayed_universes * Univ.AbstractContext.t) option * Returns the body of the constant if it has any , and the polymorphic context it lives in . For monomorphic constant , the latter is empty , and for polymorphic constants , the term contains universe variables that need to be instantiated . it lives in. For monomorphic constant, the latter is empty, and for polymorphic constants, the term contains De Bruijn universe variables that need to be instantiated. *) val body_of_constant_body : indirect_accessor -> constant_body -> (Constr.constr * unit Opaqueproof.delayed_universes * Univ.AbstractContext.t) option (** Same as {!body_of_constant} but on {!constant_body}. *) * { 6 Compiled libraries } val start_library : DirPath.t -> ModPath.t val export : output_native_objects:bool -> DirPath.t -> ModPath.t * Safe_typing.compiled_library * Nativelib.native_library val import : Safe_typing.compiled_library -> Univ.ContextSet.t -> Safe_typing.vodigest -> ModPath.t * { 6 Misc } (** Function to get an environment from the constants part of the global * environment and a given context. *) val env_of_context : Environ.named_context_val -> Environ.env val is_joined_environment : unit -> bool val is_polymorphic : GlobRef.t -> bool val is_template_polymorphic : GlobRef.t -> bool val get_template_polymorphic_variables : GlobRef.t -> Univ.Level.t list val is_type_in_type : GlobRef.t -> bool * { 6 Retroknowledge } val register_inline : Constant.t -> unit val register_inductive : inductive -> 'a CPrimitives.prim_ind -> unit * { 6 Oracle } val set_strategy : Constant.t Names.tableKey -> Conv_oracle.level -> unit * { 6 Conversion settings } val set_share_reduction : bool -> unit val set_VM : bool -> unit val set_native_compiler : bool -> unit (* Modifies the global state, registering new universes *) val current_modpath : unit -> ModPath.t val current_dirpath : unit -> DirPath.t val with_global : (Environ.env -> DirPath.t -> 'a Univ.in_universe_context_set) -> 'a val global_env_summary_tag : Safe_typing.safe_environment Summary.Dyn.tag
null
https://raw.githubusercontent.com/coq/coq/f09a8e92bcf3104707ec985c086276c9f76c44e3/library/global.mli
ocaml
********************************************************************** * The Coq Proof Assistant / The Coq Development Team // * This file is distributed under the terms of the * (see LICENSE file for the text of the license) ********************************************************************** * Changing the (im)predicativity of the system * Variables, Local definitions, constants, inductive types * Extra universe constraints * Non-interactive modules and module types * Sections * [poly] is true when the section should be universe polymorphic * Close the section and reset the global state to the one at the time when the section what opened. * Interactive modules and module types * {6 Queries in the global environment } * Same as {!body_of_constant} but on {!constant_body}. * Function to get an environment from the constants part of the global * environment and a given context. Modifies the global state, registering new universes
v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * GNU Lesser General Public License Version 2.1 open Names open Declarations * This module defines the global environment of Coq . The functions below are exactly the same as the ones in [ Safe_typing ] , operating on that global environment . [ add _ * ] functions perform name verification , i.e. check that the name given as argument match those provided by [ Safe_typing ] . below are exactly the same as the ones in [Safe_typing], operating on that global environment. [add_*] functions perform name verification, i.e. check that the name given as argument match those provided by [Safe_typing]. *) val safe_env : unit -> Safe_typing.safe_environment val env : unit -> Environ.env val universes : unit -> UGraph.t val universes_lbound : unit -> UGraph.Bound.t val named_context_val : unit -> Environ.named_context_val val named_context : unit -> Constr.named_context * { 6 Enriching the global environment } val set_impredicative_set : bool -> unit val set_indices_matter : bool -> unit val set_typing_flags : typing_flags -> unit val set_check_guarded : bool -> unit val set_check_positive : bool -> unit val set_check_universes : bool -> unit val typing_flags : unit -> typing_flags val set_allow_sprop : bool -> unit val sprop_allowed : unit -> bool val push_named_assum : (Id.t * Constr.types) -> unit val push_named_def : (Id.t * Entries.section_def_entry) -> unit val push_section_context : Univ.UContext.t -> unit val export_private_constants : Safe_typing.private_constants -> Safe_typing.exported_private_constant list val add_constant : ?typing_flags:typing_flags -> Id.t -> Safe_typing.global_declaration -> Constant.t val fill_opaque : Safe_typing.opaque_certificate -> unit val add_private_constant : Id.t -> Univ.ContextSet.t -> Safe_typing.side_effect_declaration -> Constant.t * Safe_typing.private_constants val add_mind : ?typing_flags:typing_flags -> Id.t -> Entries.mutual_inductive_entry -> MutInd.t val add_constraints : Univ.Constraints.t -> unit val push_context_set : strict:bool -> Univ.ContextSet.t -> unit val add_module : Id.t -> Entries.module_entry -> inline -> ModPath.t * Mod_subst.delta_resolver val add_modtype : Id.t -> Entries.module_type_entry -> inline -> ModPath.t val add_include : Entries.module_struct_entry -> bool -> inline -> Mod_subst.delta_resolver val open_section : unit -> unit val close_section : Summary.frozen -> unit val sections_are_opened : unit -> bool val start_module : Id.t -> ModPath.t val start_modtype : Id.t -> ModPath.t val end_module : Summary.frozen -> Id.t -> (Entries.module_struct_entry * inline) option -> ModPath.t * MBId.t list * Mod_subst.delta_resolver val end_modtype : Summary.frozen -> Id.t -> ModPath.t * MBId.t list val add_module_parameter : MBId.t -> Entries.module_struct_entry -> inline -> Mod_subst.delta_resolver val lookup_named : variable -> Constr.named_declaration val lookup_constant : Constant.t -> constant_body val lookup_inductive : inductive -> mutual_inductive_body * one_inductive_body val lookup_pinductive : Constr.pinductive -> mutual_inductive_body * one_inductive_body val lookup_mind : MutInd.t -> mutual_inductive_body val lookup_module : ModPath.t -> module_body val lookup_modtype : ModPath.t -> module_type_body val exists_objlabel : Label.t -> bool val constant_of_delta_kn : KerName.t -> Constant.t val mind_of_delta_kn : KerName.t -> MutInd.t type indirect_accessor = { access_proof : Opaqueproof.opaque -> (Constr.t * unit Opaqueproof.delayed_universes) option; } val force_proof : indirect_accessor -> Opaqueproof.opaque -> Constr.t * unit Opaqueproof.delayed_universes val body_of_constant : indirect_accessor -> Constant.t -> (Constr.constr * unit Opaqueproof.delayed_universes * Univ.AbstractContext.t) option * Returns the body of the constant if it has any , and the polymorphic context it lives in . For monomorphic constant , the latter is empty , and for polymorphic constants , the term contains universe variables that need to be instantiated . it lives in. For monomorphic constant, the latter is empty, and for polymorphic constants, the term contains De Bruijn universe variables that need to be instantiated. *) val body_of_constant_body : indirect_accessor -> constant_body -> (Constr.constr * unit Opaqueproof.delayed_universes * Univ.AbstractContext.t) option * { 6 Compiled libraries } val start_library : DirPath.t -> ModPath.t val export : output_native_objects:bool -> DirPath.t -> ModPath.t * Safe_typing.compiled_library * Nativelib.native_library val import : Safe_typing.compiled_library -> Univ.ContextSet.t -> Safe_typing.vodigest -> ModPath.t * { 6 Misc } val env_of_context : Environ.named_context_val -> Environ.env val is_joined_environment : unit -> bool val is_polymorphic : GlobRef.t -> bool val is_template_polymorphic : GlobRef.t -> bool val get_template_polymorphic_variables : GlobRef.t -> Univ.Level.t list val is_type_in_type : GlobRef.t -> bool * { 6 Retroknowledge } val register_inline : Constant.t -> unit val register_inductive : inductive -> 'a CPrimitives.prim_ind -> unit * { 6 Oracle } val set_strategy : Constant.t Names.tableKey -> Conv_oracle.level -> unit * { 6 Conversion settings } val set_share_reduction : bool -> unit val set_VM : bool -> unit val set_native_compiler : bool -> unit val current_modpath : unit -> ModPath.t val current_dirpath : unit -> DirPath.t val with_global : (Environ.env -> DirPath.t -> 'a Univ.in_universe_context_set) -> 'a val global_env_summary_tag : Safe_typing.safe_environment Summary.Dyn.tag
6bf56b4ab14fc20966cba50cc1d72302ddf41fc623fcb34ecaf8881590530385
metabase/metabase
field.cljc
(ns metabase.lib.field (:require [metabase.lib.dispatch :as lib.dispatch] [metabase.lib.metadata :as lib.metadata] [metabase.lib.options :as lib.options] [metabase.lib.schema.ref :as lib.schema.ref] [metabase.lib.temporal-bucket :as lib.temporal-bucket] [metabase.lib.util :as lib.util] [metabase.shared.util.i18n :as i18n] [metabase.util.malli :as mu])) (defmulti ^:private ->field {:arglists '([query stage-number field])} (fn [_query _stage-number field] (lib.dispatch/dispatch-value field))) (defmethod ->field :metadata/field [_query _stage-number field-metadata] (lib.options/ensure-uuid (or (:field_ref field-metadata) (when-let [id (:id field-metadata)] [:field id nil]) [:field (:name field-metadata) {:base-type (:base_type field-metadata)}]))) (defn- resolve-field [query stage-number table-or-nil id-or-name] (let [metadata (letfn [(field-metadata [metadata] (when metadata (lib.metadata/field-metadata metadata table-or-nil id-or-name)))] ;;; TODO -- I think maybe this logic should actually be part of [[metabase.lib.metadata]] ;;; -- [[metabase.lib.field-metadata]] should be the one doing this nonsense (or ;; resolve field from the current stage (field-metadata (lib.metadata/stage-metadata query stage-number)) ;; resolve field from the previous stage (if one exists) (when (lib.util/has-stage? query (dec stage-number)) (field-metadata (lib.metadata/stage-metadata query (dec stage-number)))) ;; resolve field from Database metadata ;; note that this might not actually make sense , because the Field in question might not actually ;; be visible from the current stage of the query. But on the other hand it might not be visible but still legal to add , e.g. an implicitly joined Field from another Tables . We need to noodle ;; on this a bit more and figure out how to do this in a way that errors on invalid usage. I'm iterating on this a bit in # 28717 but there is still more work to do (field-metadata (lib.metadata/database-metadata query))))] (when-not (= (:lib/type metadata) :metadata/field) (throw (ex-info (i18n/tru "Could not resolve Field {0}" (pr-str id-or-name)) {:query query :stage-number stage-number :field id-or-name}))) (->field query stage-number metadata))) (defmethod ->field :dispatch-type/string [query stage field-name] (resolve-field query stage nil field-name)) (defmethod ->field :dispatch-type/integer [query stage field-id] (resolve-field query stage nil field-id)) ;;; Pass in a function that takes `query` and `stage` to support ad-hoc usage in tests etc (defmethod ->field :dispatch-type/fn [query stage f] (f query stage)) (defmethod lib.options/options :field [clause] (last clause)) (defmethod lib.options/with-options :field [[_field id-or-name _opts] options] [:field id-or-name options]) (defmethod lib.temporal-bucket/temporal-bucket* :field [[_field id-or-name options] unit] [:field id-or-name (assoc options :temporal-unit unit)]) (defmethod lib.temporal-bucket/temporal-bucket* :field/unresolved [[_placeholder options] unit] [:field/unresolved (assoc options :temporal-unit unit)]) (mu/defn field :- [:or fn? ::lib.schema.ref/field] "Create a `:field` clause. With one or two args: return a function with the signature (f query stage-number) that can be called later to resolve to a `:field` clause. With three args: return a `:field` clause right away." ([x] (fn [query stage-number] (->field query stage-number x))) ([table x] (fn [query stage-number] (resolve-field query stage-number table x))) ([query stage-number x] (->field query stage-number x)))
null
https://raw.githubusercontent.com/metabase/metabase/02e9aa420ef910138b9b5e05f74c96e31286bcf2/src/metabase/lib/field.cljc
clojure
TODO -- I think maybe this logic should actually be part of [[metabase.lib.metadata]] -- [[metabase.lib.field-metadata]] should be the one doing this nonsense resolve field from the current stage resolve field from the previous stage (if one exists) resolve field from Database metadata be visible from the current stage of the query. But on the other hand it might not be visible on this a bit more and figure out how to do this in a way that errors on invalid usage. I'm Pass in a function that takes `query` and `stage` to support ad-hoc usage in tests etc
(ns metabase.lib.field (:require [metabase.lib.dispatch :as lib.dispatch] [metabase.lib.metadata :as lib.metadata] [metabase.lib.options :as lib.options] [metabase.lib.schema.ref :as lib.schema.ref] [metabase.lib.temporal-bucket :as lib.temporal-bucket] [metabase.lib.util :as lib.util] [metabase.shared.util.i18n :as i18n] [metabase.util.malli :as mu])) (defmulti ^:private ->field {:arglists '([query stage-number field])} (fn [_query _stage-number field] (lib.dispatch/dispatch-value field))) (defmethod ->field :metadata/field [_query _stage-number field-metadata] (lib.options/ensure-uuid (or (:field_ref field-metadata) (when-let [id (:id field-metadata)] [:field id nil]) [:field (:name field-metadata) {:base-type (:base_type field-metadata)}]))) (defn- resolve-field [query stage-number table-or-nil id-or-name] (let [metadata (letfn [(field-metadata [metadata] (when metadata (lib.metadata/field-metadata metadata table-or-nil id-or-name)))] (or (field-metadata (lib.metadata/stage-metadata query stage-number)) (when (lib.util/has-stage? query (dec stage-number)) (field-metadata (lib.metadata/stage-metadata query (dec stage-number)))) note that this might not actually make sense , because the Field in question might not actually but still legal to add , e.g. an implicitly joined Field from another Tables . We need to noodle iterating on this a bit in # 28717 but there is still more work to do (field-metadata (lib.metadata/database-metadata query))))] (when-not (= (:lib/type metadata) :metadata/field) (throw (ex-info (i18n/tru "Could not resolve Field {0}" (pr-str id-or-name)) {:query query :stage-number stage-number :field id-or-name}))) (->field query stage-number metadata))) (defmethod ->field :dispatch-type/string [query stage field-name] (resolve-field query stage nil field-name)) (defmethod ->field :dispatch-type/integer [query stage field-id] (resolve-field query stage nil field-id)) (defmethod ->field :dispatch-type/fn [query stage f] (f query stage)) (defmethod lib.options/options :field [clause] (last clause)) (defmethod lib.options/with-options :field [[_field id-or-name _opts] options] [:field id-or-name options]) (defmethod lib.temporal-bucket/temporal-bucket* :field [[_field id-or-name options] unit] [:field id-or-name (assoc options :temporal-unit unit)]) (defmethod lib.temporal-bucket/temporal-bucket* :field/unresolved [[_placeholder options] unit] [:field/unresolved (assoc options :temporal-unit unit)]) (mu/defn field :- [:or fn? ::lib.schema.ref/field] "Create a `:field` clause. With one or two args: return a function with the signature (f query stage-number) that can be called later to resolve to a `:field` clause. With three args: return a `:field` clause right away." ([x] (fn [query stage-number] (->field query stage-number x))) ([table x] (fn [query stage-number] (resolve-field query stage-number table x))) ([query stage-number x] (->field query stage-number x)))
270e0dbf17380d2cbc8a0430824230dbc4e426a17103ab8cd7c0969b9423d288
chrovis/cljam
util.clj
(ns cljam.io.vcf.util (:require [clojure.string :as cstr] [proton.core :as p])) (definline dot-or-nil? "Checks if given string is equal to \".\" or nil." [^String s] `(or (nil? ~s) (empty? ~s) (and (= 1 (.length ~s)) (= \. (.charAt ~s 0))))) (defn- value-parser "Returns a parser function for given type identifier." [type] (case type "Flag" (constantly :exists) "Integer" #(when-not (dot-or-nil? ^String %) (Integer/parseInt %)) "Float" #(when-not (dot-or-nil? ^String %) (Float/parseFloat %)) "Character" #(when-not (dot-or-nil? ^String %) (first %)) "String" #(when-not (dot-or-nil? ^String %) %))) (defn- meta->parser "Creates a key-value paired vector of 'id' and its parser." [{:keys [id number type]}] (let [p (value-parser type)] [id (comp (if (or (= number 1) (= number 0)) first identity) (fn [x] (map p (cstr/split (or x "") #","))))])) (defn info-parser "Returns a parser function defined by meta-info. info-meta must be a sequence of map containing keys :id, :number and :type. The parser takes a string and returns a map." [info-meta] (let [parser-map (into {} (map meta->parser) info-meta)] (fn [^String s] (when-not (dot-or-nil? s) (->> (cstr/split s #";") (into {} (map (fn [ss] (let [[k vs] (cstr/split ss #"\=" 2)] (if-let [parser (parser-map k)] [(keyword k) (parser vs)] (throw (ex-info (str "Undeclared INFO, " k ".") {:info ss})))))))))))) (defn info-stringifier "Returns a stringifier function of INFO field. Takes a vector of maps from info rows of meta-info. The stringifier takes a map and returns a string." [info-meta] (let [id-ordered (mapv :id info-meta) info-type (into {} (map (juxt :id :type)) info-meta)] (fn [info] (when info (->> id-ordered (keep (fn [k] (when-let [v (info (keyword k))] (if (or (= v :exists) (= (info-type k) "Flag")) k (str k "=" (if (sequential? v) (cstr/join "," v) v)))))) (cstr/join ";") not-empty))))) (defn parse-filter "Parses FILTER field and returns a sequence of keywords." [^String s] (when-not (dot-or-nil? s) (map keyword (cstr/split s #";")))) (defn stringify-filter "Stringifies FILTER field. Takes a sequence of keywords or strings." [fltr] (when (and (some? fltr) (some some? fltr)) (cstr/join ";" (map name fltr)))) (defn parse-format "Parses FORMAT field and returns as a sequence of keywords." [^String s] (when-not (dot-or-nil? s) (map keyword (cstr/split s #":")))) (defn stringify-format "Stringifies FORMAT field. Takes a sequence of keywords or strings." [formats] (when-not (or (nil? formats) (empty? formats)) (cstr/join ":" (map name formats)))) (defn parse-genotype "Parses genotype (GT) format and returns a vector of pairs: [allele, phased]. Allele 0 indicates REF allele. 1,2,3... for 1st, 2nd, 3rd allele of ALT." [^String gt] (when-not (dot-or-nil? gt) (->> gt (re-seq #"([\||/])?(.|\d+)") (map (fn [[_ phase ^String allele]] [(when-not (dot-or-nil? allele) (Integer/parseInt allele)) (if phase (= phase "|") (neg? (.indexOf ^String gt "/")))]))))) (defn stringify-genotype "Stringifies genotype map into VCF-style GT string." [gt-seq] (when-not (or (nil? gt-seq) (empty? gt-seq)) (->> gt-seq (mapcat (fn [[allele phase]] [(if phase "|" "/") (or allele \.)])) rest (apply str)))) (defn genotype-seq "Returns a sequence of genotypes represented as sequences of integers." ([^long ploidy ^long n-alt-alleles] (genotype-seq ploidy n-alt-alleles [])) ([^long ploidy ^long n-alt-alleles s] (mapcat (fn [i] (if (= 1 ploidy) [(cons i s)] (genotype-seq (dec ploidy) i (cons i s)))) (range (inc n-alt-alleles))))) (defn genotype-index "Returns an index for given genotype." ^long [genotype] {:pre [(seq genotype) (every? (complement neg?) genotype)]} (letfn [(combination ^long [^long n ^long k] (cond (< n k) 0 (= k n) 1 (or (= k 1) (= k (dec n))) n (< (quot n 2) k) (recur n (- n k)) :else (loop [i (inc (- n k)), j 1, r 1] (if (<= j k) (recur (inc i) (inc j) (quot (* r i) j)) r))))] (->> genotype sort (map-indexed (fn [^long m ^long k] (combination (+ k m) (inc m)))) (apply +)))) (defn biallelic-genotype "Converts a multiallelic `genotype` string into a biallelic one. Ignores all alleles other than the reference allele and the `target-allele`." [genotype ^long target-allele] (->> genotype parse-genotype (map (fn [[allele phased?]] [(when allele (if (= target-allele allele) 1 0)) phased?])) stringify-genotype)) (defn biallelic-coll "Picks up elements in multiallelic `coll` and make a biallelic one. Ignores all alleles other than the reference allele and the `target-allele`." [^long ploidy ^long n-alt-alleles ^long target-allele coll] (keep-indexed (fn [i gt] (when (every? (fn [^long a] (or (= a 0) (= a target-allele))) gt) (nth coll i))) (genotype-seq ploidy n-alt-alleles))) (defn genotype->ints "Convert genotype to a sequence of integers." [gt] (let [parsed-gt (or (cond-> gt (string? gt) parse-genotype) [[nil]])] (->> (assoc-in (vec parsed-gt) [0 1] false) (map (fn [[allele phased]] (bit-or (bit-shift-left (if allele (inc allele) 0) 1) (if phased 1 0))))))) (defn ints->genotype "Convert a sequence of integers to genotype string." [vs] (->> vs (mapcat (fn [i] [(if (odd? i) \| \/) (if (zero? (quot i 2)) "." (dec (quot i 2)))])) rest (apply str) (#(when-not (dot-or-nil? ^String %) %)))) (defn sample-parser "Returns a parser function defined by meta-formats. info must be a sequence of map containing keys :id, :number and :type. The parser takes two string (format-line and sample-line) and returns a map." [formats-meta] (let [parser-map (into {} (map meta->parser) formats-meta)] (fn [^String format-line sample-line] (when-not (dot-or-nil? format-line) (let [ks (cstr/split format-line #":") vs (concat (when (not-empty sample-line) (cstr/split sample-line #":")) (repeat nil))] (into {} (map (fn [[k ^String v]] [(keyword k) (when-not (dot-or-nil? v) ((parser-map k) v))])) (map vector ks vs))))))) (defn stringify-sample "Converts sample map into string. formats must be a sequence of keys in sample-map." [formats sample-map] (->> formats (map (fn [k] [k (get sample-map k)])) reverse (drop-while (fn [[_ v]] (or (nil? v) (= [nil] v)))) (map (fn [[_ v]] (cond (sequential? v) (cstr/join "," (map (fn [i] (if (nil? i) "." i)) v)) (nil? v) "." :else v))) reverse (cstr/join ":") not-empty)) (defn variant-parser "Returns a parser function to parse :filter, :info, :FORMAT and sample columns of VCF. Takes meta-info and header of VCF. The parser takes a variant map and returns a parsed map." [meta-info header] (let [[fmt-kw & sample-kws] (mapv keyword (drop 8 header)) parse-info (info-parser (:info meta-info)) parse-sample (sample-parser (:format meta-info))] (fn [v] (cond-> v true (update :filter parse-filter) true (update :info parse-info) fmt-kw (update fmt-kw parse-format) sample-kws (into (for [k sample-kws] [k (parse-sample (v fmt-kw) (v k))])))))) (defn variant-vals-stringifier "Returns a stringifier function to stringify :filter, :info, :FORMAT and sample columns of VCF. Takes meta-info and header of VCF. The stringifier takes a parsed variant map and returns a map." [meta-info header] (let [[fmt-kw & sample-kws] (mapv keyword (drop 8 header)) stringify-info (info-stringifier (:info meta-info))] (fn [v] (-> v (update :filter stringify-filter) (update :info stringify-info) (update fmt-kw stringify-format) (merge (into {} (for [k sample-kws] [k (stringify-sample (v fmt-kw) (v k))]))))))) (def ^:private ^:const long-breakend-regexp ;; pre-seq [ or ] chr pos [ or ] post-seq #"([ACGTN]*|\.)([\[\]])(.+?)(?::(\d+))([\[\]])([ACGTN]*|\.)") (def ^:private ^:const short-breakend-regexp #"(\.?)([ATGCN]+)(\.?)") (defn parse-breakend "Parses an ALT allele string of SVTYPE=BND. Returns a map with mandatory keys: - `:bases` bases that replaces the reference place - `:join` `:before` or `:after` and optional keys for a mate: - `:chr` chromosome name of the mate sequence - `:pos` genomic position of the mate sequence - `:strand` strand of the mate sequence Returns `nil` if input `alt` is not a breakend." [alt] (if-let [[_ pre-seq [left-bracket] chr pos [right-bracket] post-seq] (re-matches long-breakend-regexp alt)] (let [pre (not-empty pre-seq) post (not-empty post-seq)] (when (and (= left-bracket right-bracket) (or pre post) (not (and pre post))) (when-let [p (p/as-long pos)] {:chr chr, :pos p, :join (if post :before :after), :bases (or pre post), :strand (if (= left-bracket \]) (if post :forward :reverse) (if post :reverse :forward))}))) (when-let [[_ [pre-dot] bases [post-dot]] (re-matches short-breakend-regexp alt)] (when (and (or pre-dot post-dot) (not (and pre-dot post-dot))) {:bases bases, :join (if pre-dot :before :after)})))) (defn stringify-breakend "Returns a string representation of a breakend. If the input is malformed, returns `nil`. See the docstring of `parse-breakend` for the format." [{:keys [chr pos strand join] s :bases}] (when (and (not-empty s) (#{:before :after} join)) (if (and chr pos (#{:forward :reverse} strand)) (let [before? (= join :before) bracket (if (= strand :forward) (if before? \] \[) (if before? \[ \]))] (str (when-not before? s) bracket chr \: pos bracket (when before? s))) (str (when (= :before join) \.) s (when (= :after join) \.))))) (defn- inspect-nucleotides-allele [ref alt] (let [ref-length (count ref) alt-length (count alt) upper-ref (cstr/upper-case ref) upper-alt (cstr/upper-case alt) left-match (->> (map = upper-ref upper-alt) (take-while true?) count) right-match (->> (cstr/reverse upper-alt) (map = (cstr/reverse upper-ref)) (take-while true?) count long (Math/min (- (Math/min ref-length alt-length) left-match))) matched-length (+ left-match right-match)] (cond (= left-match ref-length alt-length) {:type :ref} (and (= left-match ref-length) (< left-match alt-length)) {:type :insertion, :offset (dec left-match), :n-bases (- alt-length left-match), :inserted (subs alt left-match)} (and (< left-match ref-length) (= left-match alt-length)) {:type :deletion, :offset (dec left-match), :n-bases (- ref-length left-match), :deleted (subs ref left-match)} (= (inc matched-length) ref-length alt-length) {:type :snv, :ref (nth ref left-match), :alt (nth alt left-match), :offset left-match} (= matched-length alt-length) {:type :deletion, :offset (dec left-match), :n-bases (- ref-length right-match left-match), :deleted (subs ref left-match (- ref-length right-match))} (= matched-length ref-length) {:type :insertion, :offset (dec left-match), :n-bases (- alt-length right-match left-match), :inserted (subs alt left-match (- alt-length right-match))} (= ref-length alt-length) {:type :mnv, :offset left-match, :ref (subs ref left-match (- ref-length right-match)), :alt (subs alt left-match (- alt-length right-match))} :else {:type :complex}))) (defn inspect-allele "Inspects an `alt` allele by comparing to a `ref` allele string. Returns a map containing `:type` and other detailed information. A value of the key `:type` can be one of the followings: - `:no-call` No variant called - `:spanning-deletion` Placeholder to signify an absent sequence - `:unspecified` Unspecified non-ref allele - `:ref` Duplicated allele of REF - `:id` Symbolic reference - `:snv` Single nucleotide variant - `:mnv` Multiple nucleotide variants - `:insertion` Insertion of a short base sequence - `:deletion` Deletion of a short base sequence - `:complete-insertion` Complete insertion of a long sequence - `:breakend` Breakend of a complex rearrangement - `:complex` Complex nucleotide variants other than snv/mnv/indel - `:other` Can't categorize the allele, might be malformed" [ref alt] (or (when (re-matches #"(?i)[ACGTN]+" (or ref "")) (condp re-matches (or (not-empty alt) ".") #"\." {:type :no-call} #"\*" {:type :spanning-deletion} #"(X|<\*>|<X>)" {:type :unspecified} #"<(.+)>" :>> (fn [[_ id]] {:type :id, :id id}) #"(?i)([ACGTN])<(.+)>" :>> (fn [[_ [base] id]] {:type :complete-insertion, :join :after, :base base, :id id}) #"(?i)<(.+)>([ACGTN])" :>> (fn [[_ id [base]]] {:type :complete-insertion, :join :before, :base base, :id id}) #"(?i)[ACGTN]+" (inspect-nucleotides-allele ref alt) (some-> (parse-breakend alt) (assoc :type :breakend)))) {:type :other}))
null
https://raw.githubusercontent.com/chrovis/cljam/cbaff3c1caafb03d87fd49b8bf7a64853065a1eb/src/cljam/io/vcf/util.clj
clojure
pre-seq [ or ] chr pos [ or ] post-seq
(ns cljam.io.vcf.util (:require [clojure.string :as cstr] [proton.core :as p])) (definline dot-or-nil? "Checks if given string is equal to \".\" or nil." [^String s] `(or (nil? ~s) (empty? ~s) (and (= 1 (.length ~s)) (= \. (.charAt ~s 0))))) (defn- value-parser "Returns a parser function for given type identifier." [type] (case type "Flag" (constantly :exists) "Integer" #(when-not (dot-or-nil? ^String %) (Integer/parseInt %)) "Float" #(when-not (dot-or-nil? ^String %) (Float/parseFloat %)) "Character" #(when-not (dot-or-nil? ^String %) (first %)) "String" #(when-not (dot-or-nil? ^String %) %))) (defn- meta->parser "Creates a key-value paired vector of 'id' and its parser." [{:keys [id number type]}] (let [p (value-parser type)] [id (comp (if (or (= number 1) (= number 0)) first identity) (fn [x] (map p (cstr/split (or x "") #","))))])) (defn info-parser "Returns a parser function defined by meta-info. info-meta must be a sequence of map containing keys :id, :number and :type. The parser takes a string and returns a map." [info-meta] (let [parser-map (into {} (map meta->parser) info-meta)] (fn [^String s] (when-not (dot-or-nil? s) (->> (cstr/split s #";") (into {} (map (fn [ss] (let [[k vs] (cstr/split ss #"\=" 2)] (if-let [parser (parser-map k)] [(keyword k) (parser vs)] (throw (ex-info (str "Undeclared INFO, " k ".") {:info ss})))))))))))) (defn info-stringifier "Returns a stringifier function of INFO field. Takes a vector of maps from info rows of meta-info. The stringifier takes a map and returns a string." [info-meta] (let [id-ordered (mapv :id info-meta) info-type (into {} (map (juxt :id :type)) info-meta)] (fn [info] (when info (->> id-ordered (keep (fn [k] (when-let [v (info (keyword k))] (if (or (= v :exists) (= (info-type k) "Flag")) k (str k "=" (if (sequential? v) (cstr/join "," v) v)))))) (cstr/join ";") not-empty))))) (defn parse-filter "Parses FILTER field and returns a sequence of keywords." [^String s] (when-not (dot-or-nil? s) (map keyword (cstr/split s #";")))) (defn stringify-filter "Stringifies FILTER field. Takes a sequence of keywords or strings." [fltr] (when (and (some? fltr) (some some? fltr)) (cstr/join ";" (map name fltr)))) (defn parse-format "Parses FORMAT field and returns as a sequence of keywords." [^String s] (when-not (dot-or-nil? s) (map keyword (cstr/split s #":")))) (defn stringify-format "Stringifies FORMAT field. Takes a sequence of keywords or strings." [formats] (when-not (or (nil? formats) (empty? formats)) (cstr/join ":" (map name formats)))) (defn parse-genotype "Parses genotype (GT) format and returns a vector of pairs: [allele, phased]. Allele 0 indicates REF allele. 1,2,3... for 1st, 2nd, 3rd allele of ALT." [^String gt] (when-not (dot-or-nil? gt) (->> gt (re-seq #"([\||/])?(.|\d+)") (map (fn [[_ phase ^String allele]] [(when-not (dot-or-nil? allele) (Integer/parseInt allele)) (if phase (= phase "|") (neg? (.indexOf ^String gt "/")))]))))) (defn stringify-genotype "Stringifies genotype map into VCF-style GT string." [gt-seq] (when-not (or (nil? gt-seq) (empty? gt-seq)) (->> gt-seq (mapcat (fn [[allele phase]] [(if phase "|" "/") (or allele \.)])) rest (apply str)))) (defn genotype-seq "Returns a sequence of genotypes represented as sequences of integers." ([^long ploidy ^long n-alt-alleles] (genotype-seq ploidy n-alt-alleles [])) ([^long ploidy ^long n-alt-alleles s] (mapcat (fn [i] (if (= 1 ploidy) [(cons i s)] (genotype-seq (dec ploidy) i (cons i s)))) (range (inc n-alt-alleles))))) (defn genotype-index "Returns an index for given genotype." ^long [genotype] {:pre [(seq genotype) (every? (complement neg?) genotype)]} (letfn [(combination ^long [^long n ^long k] (cond (< n k) 0 (= k n) 1 (or (= k 1) (= k (dec n))) n (< (quot n 2) k) (recur n (- n k)) :else (loop [i (inc (- n k)), j 1, r 1] (if (<= j k) (recur (inc i) (inc j) (quot (* r i) j)) r))))] (->> genotype sort (map-indexed (fn [^long m ^long k] (combination (+ k m) (inc m)))) (apply +)))) (defn biallelic-genotype "Converts a multiallelic `genotype` string into a biallelic one. Ignores all alleles other than the reference allele and the `target-allele`." [genotype ^long target-allele] (->> genotype parse-genotype (map (fn [[allele phased?]] [(when allele (if (= target-allele allele) 1 0)) phased?])) stringify-genotype)) (defn biallelic-coll "Picks up elements in multiallelic `coll` and make a biallelic one. Ignores all alleles other than the reference allele and the `target-allele`." [^long ploidy ^long n-alt-alleles ^long target-allele coll] (keep-indexed (fn [i gt] (when (every? (fn [^long a] (or (= a 0) (= a target-allele))) gt) (nth coll i))) (genotype-seq ploidy n-alt-alleles))) (defn genotype->ints "Convert genotype to a sequence of integers." [gt] (let [parsed-gt (or (cond-> gt (string? gt) parse-genotype) [[nil]])] (->> (assoc-in (vec parsed-gt) [0 1] false) (map (fn [[allele phased]] (bit-or (bit-shift-left (if allele (inc allele) 0) 1) (if phased 1 0))))))) (defn ints->genotype "Convert a sequence of integers to genotype string." [vs] (->> vs (mapcat (fn [i] [(if (odd? i) \| \/) (if (zero? (quot i 2)) "." (dec (quot i 2)))])) rest (apply str) (#(when-not (dot-or-nil? ^String %) %)))) (defn sample-parser "Returns a parser function defined by meta-formats. info must be a sequence of map containing keys :id, :number and :type. The parser takes two string (format-line and sample-line) and returns a map." [formats-meta] (let [parser-map (into {} (map meta->parser) formats-meta)] (fn [^String format-line sample-line] (when-not (dot-or-nil? format-line) (let [ks (cstr/split format-line #":") vs (concat (when (not-empty sample-line) (cstr/split sample-line #":")) (repeat nil))] (into {} (map (fn [[k ^String v]] [(keyword k) (when-not (dot-or-nil? v) ((parser-map k) v))])) (map vector ks vs))))))) (defn stringify-sample "Converts sample map into string. formats must be a sequence of keys in sample-map." [formats sample-map] (->> formats (map (fn [k] [k (get sample-map k)])) reverse (drop-while (fn [[_ v]] (or (nil? v) (= [nil] v)))) (map (fn [[_ v]] (cond (sequential? v) (cstr/join "," (map (fn [i] (if (nil? i) "." i)) v)) (nil? v) "." :else v))) reverse (cstr/join ":") not-empty)) (defn variant-parser "Returns a parser function to parse :filter, :info, :FORMAT and sample columns of VCF. Takes meta-info and header of VCF. The parser takes a variant map and returns a parsed map." [meta-info header] (let [[fmt-kw & sample-kws] (mapv keyword (drop 8 header)) parse-info (info-parser (:info meta-info)) parse-sample (sample-parser (:format meta-info))] (fn [v] (cond-> v true (update :filter parse-filter) true (update :info parse-info) fmt-kw (update fmt-kw parse-format) sample-kws (into (for [k sample-kws] [k (parse-sample (v fmt-kw) (v k))])))))) (defn variant-vals-stringifier "Returns a stringifier function to stringify :filter, :info, :FORMAT and sample columns of VCF. Takes meta-info and header of VCF. The stringifier takes a parsed variant map and returns a map." [meta-info header] (let [[fmt-kw & sample-kws] (mapv keyword (drop 8 header)) stringify-info (info-stringifier (:info meta-info))] (fn [v] (-> v (update :filter stringify-filter) (update :info stringify-info) (update fmt-kw stringify-format) (merge (into {} (for [k sample-kws] [k (stringify-sample (v fmt-kw) (v k))]))))))) (def ^:private ^:const long-breakend-regexp #"([ACGTN]*|\.)([\[\]])(.+?)(?::(\d+))([\[\]])([ACGTN]*|\.)") (def ^:private ^:const short-breakend-regexp #"(\.?)([ATGCN]+)(\.?)") (defn parse-breakend "Parses an ALT allele string of SVTYPE=BND. Returns a map with mandatory keys: - `:bases` bases that replaces the reference place - `:join` `:before` or `:after` and optional keys for a mate: - `:chr` chromosome name of the mate sequence - `:pos` genomic position of the mate sequence - `:strand` strand of the mate sequence Returns `nil` if input `alt` is not a breakend." [alt] (if-let [[_ pre-seq [left-bracket] chr pos [right-bracket] post-seq] (re-matches long-breakend-regexp alt)] (let [pre (not-empty pre-seq) post (not-empty post-seq)] (when (and (= left-bracket right-bracket) (or pre post) (not (and pre post))) (when-let [p (p/as-long pos)] {:chr chr, :pos p, :join (if post :before :after), :bases (or pre post), :strand (if (= left-bracket \]) (if post :forward :reverse) (if post :reverse :forward))}))) (when-let [[_ [pre-dot] bases [post-dot]] (re-matches short-breakend-regexp alt)] (when (and (or pre-dot post-dot) (not (and pre-dot post-dot))) {:bases bases, :join (if pre-dot :before :after)})))) (defn stringify-breakend "Returns a string representation of a breakend. If the input is malformed, returns `nil`. See the docstring of `parse-breakend` for the format." [{:keys [chr pos strand join] s :bases}] (when (and (not-empty s) (#{:before :after} join)) (if (and chr pos (#{:forward :reverse} strand)) (let [before? (= join :before) bracket (if (= strand :forward) (if before? \] \[) (if before? \[ \]))] (str (when-not before? s) bracket chr \: pos bracket (when before? s))) (str (when (= :before join) \.) s (when (= :after join) \.))))) (defn- inspect-nucleotides-allele [ref alt] (let [ref-length (count ref) alt-length (count alt) upper-ref (cstr/upper-case ref) upper-alt (cstr/upper-case alt) left-match (->> (map = upper-ref upper-alt) (take-while true?) count) right-match (->> (cstr/reverse upper-alt) (map = (cstr/reverse upper-ref)) (take-while true?) count long (Math/min (- (Math/min ref-length alt-length) left-match))) matched-length (+ left-match right-match)] (cond (= left-match ref-length alt-length) {:type :ref} (and (= left-match ref-length) (< left-match alt-length)) {:type :insertion, :offset (dec left-match), :n-bases (- alt-length left-match), :inserted (subs alt left-match)} (and (< left-match ref-length) (= left-match alt-length)) {:type :deletion, :offset (dec left-match), :n-bases (- ref-length left-match), :deleted (subs ref left-match)} (= (inc matched-length) ref-length alt-length) {:type :snv, :ref (nth ref left-match), :alt (nth alt left-match), :offset left-match} (= matched-length alt-length) {:type :deletion, :offset (dec left-match), :n-bases (- ref-length right-match left-match), :deleted (subs ref left-match (- ref-length right-match))} (= matched-length ref-length) {:type :insertion, :offset (dec left-match), :n-bases (- alt-length right-match left-match), :inserted (subs alt left-match (- alt-length right-match))} (= ref-length alt-length) {:type :mnv, :offset left-match, :ref (subs ref left-match (- ref-length right-match)), :alt (subs alt left-match (- alt-length right-match))} :else {:type :complex}))) (defn inspect-allele "Inspects an `alt` allele by comparing to a `ref` allele string. Returns a map containing `:type` and other detailed information. A value of the key `:type` can be one of the followings: - `:no-call` No variant called - `:spanning-deletion` Placeholder to signify an absent sequence - `:unspecified` Unspecified non-ref allele - `:ref` Duplicated allele of REF - `:id` Symbolic reference - `:snv` Single nucleotide variant - `:mnv` Multiple nucleotide variants - `:insertion` Insertion of a short base sequence - `:deletion` Deletion of a short base sequence - `:complete-insertion` Complete insertion of a long sequence - `:breakend` Breakend of a complex rearrangement - `:complex` Complex nucleotide variants other than snv/mnv/indel - `:other` Can't categorize the allele, might be malformed" [ref alt] (or (when (re-matches #"(?i)[ACGTN]+" (or ref "")) (condp re-matches (or (not-empty alt) ".") #"\." {:type :no-call} #"\*" {:type :spanning-deletion} #"(X|<\*>|<X>)" {:type :unspecified} #"<(.+)>" :>> (fn [[_ id]] {:type :id, :id id}) #"(?i)([ACGTN])<(.+)>" :>> (fn [[_ [base] id]] {:type :complete-insertion, :join :after, :base base, :id id}) #"(?i)<(.+)>([ACGTN])" :>> (fn [[_ id [base]]] {:type :complete-insertion, :join :before, :base base, :id id}) #"(?i)[ACGTN]+" (inspect-nucleotides-allele ref alt) (some-> (parse-breakend alt) (assoc :type :breakend)))) {:type :other}))
80382f3de93543c9289638d84e1f0c452cdf0962644ec4f66220ec526923fee2
edbutler/nonograms-rule-synthesis
symbolic.rkt
#lang rosette/safe ; all the routines for creating symbolic nonograms objects ; (basically, everything except programs) (provide symbolic-segments symbolic-deduction symbolic-solution-segments/concrete-hints symbolic-line-transition symbolic-line solve-with-symbolic-deduction) (require (only-in racket match-define error values parameterize hash-copy) rosette/lib/angelic "rules.rkt" "action.rkt" "../core/core.rkt") (define (map/with-previous f lst) (reverse (foldl (λ (x acc) (define prev (if (empty? acc) #f (car acc))) (cons (f x prev) acc)) empty lst))) (define (make-list/with-previous len f) (reverse (foldl (λ (i acc) (define prev (if (empty? acc) #f (car acc))) (cons (f i prev) acc)) empty (range/s 0 len)))) (define (symbolic-segments ctx max-segments) (define len (line-length ctx)) (define-symbolic* num-segments integer?) (assert (>= num-segments 0)) (assert (<= num-segments max-segments)) (values (make-list/with-previous max-segments (λ (i prev) (define-symbolic* s integer?) (define-symbolic* e integer?) (define used? (< i num-segments)) (assert (>= s 0)) (assert (< s e)) (assert (<= e len)) (when prev must have gap of at least one between segments (assert (=> used? (> s (segment-end prev))))) (segment s e used?))) num-segments)) (define (symbolic-segments-of-lengths ctx lengths) (define len (line-length ctx)) (map/with-previous (λ (x prev) (define-symbolic* s integer?) (define e (+ s x)) (assert (>= s 0)) (assert (<= e len)) (when prev must have gap of at least one between segments (assert (> s (segment-end prev)))) (segment s e #t)) lengths)) line ? - > ( listof segment ? ) ; create a set of symbolic solution segments for a concrete line, ; with assertions that the segments are consistent with a solution for that line. ; useful for either solving lines or generating solved lines. (define (symbolic-solution-segments/concrete-hints ctx) (define hints (line-hints ctx)) (define len (line-length ctx)) (define segments ; use fold instead of map because we need to reference the previous segment (map/with-previous (λ (h prev) (define-symbolic* s integer?) (define e (+ s h)) (assert (>= s 0)) (assert (<= e len)) (when prev must have gap of at least one between segments (assert (> s (segment-end prev)))) (segment s e #t)) hints)) ; assert these segments are consistent with the board hints (will assert a solved line) (assert (segments-consistent? segments (line-cells ctx))) segments) ; line? -> line? (define (symbolic-deduction start-ctx) (match-define (line hints cells) start-ctx) (line hints (map (λ (c) (if (empty-cell? c) (!!) c)) cells))) (define (symbolic-hint row-len) (define (symhint _) (define-symbolic* h integer?) (assert (> h 0)) (assert (<= h row-len)) h) (define max-hints (quotient (add1 row-len) 2)) (build-list/s max-hints symhint)) ; integer?, boolean? -> line-transition? ; line-transition-end will be a solved context (otherwise it's useless since the start might not be solvable). ; IMPORTANT NOTE: not all of the symoblics used to ensure solved? are part of the return value. ; So this should behave correctly in a verification context but not with e.g., quantifiers. (define (symbolic-line-transition row-len) (define filled (map (λ (_) (!!* cell)) (range/s 0 row-len))) (define partial (map (λ (cell) (if (!!* known?) cell empty-cell)) filled)) (define hnt (symbolic-hint row-len)) (define num-hint (??* 0 (add1 (length hnt)))) (define ctx (line (take hnt num-hint) partial)) ; merely creating the symbolic segments creates the necessary asserts (symbolic-solution-segments/concrete-hints (line (line-hints ctx) filled)) (line-transition ctx filled)) ; creates a symbolic line. ; The line is provably consistent by actually generating a solved line and then emptying some cells. ; Thus, this is as expensive as a symbolic line-transition, and is just a convenience function. ; Much like symbolic-line-transition, the return value does not include all the symbolics created. (define (symbolic-line row-len) (line-transition-start (symbolic-line-transition row-len))) f : ( solver ? , line ? , ( listof segment ? ) - > ' a ) ; start-ctx: line? ; -> 'a ; creates a solver context which asserts the existence of a solved deduction from the given start context. ; then invokes the given procedure `f` with the solver, the solved line, and the segments for that line. ; returns whatever f returns. (define (solve-with-symbolic-deduction f start-ctx) (parameterize ([current-bitwidth #f] [term-cache (hash-copy (term-cache))]) (define checker (current-solver)) (solver-clear checker) (define end-ctx (eval-with-solver checker (symbolic-deduction start-ctx))) ; simply declaring this makes the asserts that end-ctx is correctly solved. (define segments (eval-with-solver checker (symbolic-solution-segments/concrete-hints end-ctx))) (f checker end-ctx segments)))
null
https://raw.githubusercontent.com/edbutler/nonograms-rule-synthesis/16f8dacb17bd77c9d927ab9fa0b8c1678dc68088/src/nonograms/symbolic.rkt
racket
all the routines for creating symbolic nonograms objects (basically, everything except programs) create a set of symbolic solution segments for a concrete line, with assertions that the segments are consistent with a solution for that line. useful for either solving lines or generating solved lines. use fold instead of map because we need to reference the previous segment assert these segments are consistent with the board hints (will assert a solved line) line? -> line? integer?, boolean? -> line-transition? line-transition-end will be a solved context (otherwise it's useless since the start might not be solvable). IMPORTANT NOTE: not all of the symoblics used to ensure solved? are part of the return value. So this should behave correctly in a verification context but not with e.g., quantifiers. merely creating the symbolic segments creates the necessary asserts creates a symbolic line. The line is provably consistent by actually generating a solved line and then emptying some cells. Thus, this is as expensive as a symbolic line-transition, and is just a convenience function. Much like symbolic-line-transition, the return value does not include all the symbolics created. start-ctx: line? -> 'a creates a solver context which asserts the existence of a solved deduction from the given start context. then invokes the given procedure `f` with the solver, the solved line, and the segments for that line. returns whatever f returns. simply declaring this makes the asserts that end-ctx is correctly solved.
#lang rosette/safe (provide symbolic-segments symbolic-deduction symbolic-solution-segments/concrete-hints symbolic-line-transition symbolic-line solve-with-symbolic-deduction) (require (only-in racket match-define error values parameterize hash-copy) rosette/lib/angelic "rules.rkt" "action.rkt" "../core/core.rkt") (define (map/with-previous f lst) (reverse (foldl (λ (x acc) (define prev (if (empty? acc) #f (car acc))) (cons (f x prev) acc)) empty lst))) (define (make-list/with-previous len f) (reverse (foldl (λ (i acc) (define prev (if (empty? acc) #f (car acc))) (cons (f i prev) acc)) empty (range/s 0 len)))) (define (symbolic-segments ctx max-segments) (define len (line-length ctx)) (define-symbolic* num-segments integer?) (assert (>= num-segments 0)) (assert (<= num-segments max-segments)) (values (make-list/with-previous max-segments (λ (i prev) (define-symbolic* s integer?) (define-symbolic* e integer?) (define used? (< i num-segments)) (assert (>= s 0)) (assert (< s e)) (assert (<= e len)) (when prev must have gap of at least one between segments (assert (=> used? (> s (segment-end prev))))) (segment s e used?))) num-segments)) (define (symbolic-segments-of-lengths ctx lengths) (define len (line-length ctx)) (map/with-previous (λ (x prev) (define-symbolic* s integer?) (define e (+ s x)) (assert (>= s 0)) (assert (<= e len)) (when prev must have gap of at least one between segments (assert (> s (segment-end prev)))) (segment s e #t)) lengths)) line ? - > ( listof segment ? ) (define (symbolic-solution-segments/concrete-hints ctx) (define hints (line-hints ctx)) (define len (line-length ctx)) (define segments (map/with-previous (λ (h prev) (define-symbolic* s integer?) (define e (+ s h)) (assert (>= s 0)) (assert (<= e len)) (when prev must have gap of at least one between segments (assert (> s (segment-end prev)))) (segment s e #t)) hints)) (assert (segments-consistent? segments (line-cells ctx))) segments) (define (symbolic-deduction start-ctx) (match-define (line hints cells) start-ctx) (line hints (map (λ (c) (if (empty-cell? c) (!!) c)) cells))) (define (symbolic-hint row-len) (define (symhint _) (define-symbolic* h integer?) (assert (> h 0)) (assert (<= h row-len)) h) (define max-hints (quotient (add1 row-len) 2)) (build-list/s max-hints symhint)) (define (symbolic-line-transition row-len) (define filled (map (λ (_) (!!* cell)) (range/s 0 row-len))) (define partial (map (λ (cell) (if (!!* known?) cell empty-cell)) filled)) (define hnt (symbolic-hint row-len)) (define num-hint (??* 0 (add1 (length hnt)))) (define ctx (line (take hnt num-hint) partial)) (symbolic-solution-segments/concrete-hints (line (line-hints ctx) filled)) (line-transition ctx filled)) (define (symbolic-line row-len) (line-transition-start (symbolic-line-transition row-len))) f : ( solver ? , line ? , ( listof segment ? ) - > ' a ) (define (solve-with-symbolic-deduction f start-ctx) (parameterize ([current-bitwidth #f] [term-cache (hash-copy (term-cache))]) (define checker (current-solver)) (solver-clear checker) (define end-ctx (eval-with-solver checker (symbolic-deduction start-ctx))) (define segments (eval-with-solver checker (symbolic-solution-segments/concrete-hints end-ctx))) (f checker end-ctx segments)))
9dbc41239adca5a50530b6fac172c1907fa0a779db0ad8cb0bf3977dd5253a54
emqx/emqx
emqx_bridge_mqtt_SUITE.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(emqx_bridge_mqtt_SUITE). -compile(nowarn_export_all). -compile(export_all). -import(emqx_dashboard_api_test_helpers, [request/4, uri/1]). -import(emqx_common_test_helpers, [on_exit/1]). -include("emqx/include/emqx.hrl"). -include_lib("eunit/include/eunit.hrl"). -include_lib("common_test/include/ct.hrl"). -include_lib("snabbkaffe/include/snabbkaffe.hrl"). -include("emqx_dashboard/include/emqx_dashboard.hrl"). %% output functions -export([inspect/3]). -define(BRIDGE_CONF_DEFAULT, <<"bridges: {}">>). -define(TYPE_MQTT, <<"mqtt">>). -define(BRIDGE_NAME_INGRESS, <<"ingress_mqtt_bridge">>). -define(BRIDGE_NAME_EGRESS, <<"egress_mqtt_bridge">>). %% Having ingress/egress prefixs of topic names to avoid dead loop while bridging -define(INGRESS_REMOTE_TOPIC, "ingress_remote_topic"). -define(INGRESS_LOCAL_TOPIC, "ingress_local_topic"). -define(EGRESS_REMOTE_TOPIC, "egress_remote_topic"). -define(EGRESS_LOCAL_TOPIC, "egress_local_topic"). -define(SERVER_CONF(Username), #{ <<"server">> => <<"127.0.0.1:1883">>, <<"username">> => Username, <<"password">> => <<"">>, <<"proto_ver">> => <<"v4">>, <<"ssl">> => #{<<"enable">> => false} }). -define(INGRESS_CONF, #{ <<"remote">> => #{ <<"topic">> => <<?INGRESS_REMOTE_TOPIC, "/#">>, <<"qos">> => 1 }, <<"local">> => #{ <<"topic">> => <<?INGRESS_LOCAL_TOPIC, "/${topic}">>, <<"qos">> => <<"${qos}">>, <<"payload">> => <<"${payload}">>, <<"retain">> => <<"${retain}">> } }). -define(EGRESS_CONF, #{ <<"local">> => #{ <<"topic">> => <<?EGRESS_LOCAL_TOPIC, "/#">> }, <<"remote">> => #{ <<"topic">> => <<?EGRESS_REMOTE_TOPIC, "/${topic}">>, <<"payload">> => <<"${payload}">>, <<"qos">> => <<"${qos}">>, <<"retain">> => <<"${retain}">> } }). -define(INGRESS_CONF_NO_PAYLOAD_TEMPLATE, #{ <<"remote">> => #{ <<"topic">> => <<?INGRESS_REMOTE_TOPIC, "/#">>, <<"qos">> => 1 }, <<"local">> => #{ <<"topic">> => <<?INGRESS_LOCAL_TOPIC, "/${topic}">>, <<"qos">> => <<"${qos}">>, <<"retain">> => <<"${retain}">> } }). -define(EGRESS_CONF_NO_PAYLOAD_TEMPLATE, #{ <<"local">> => #{ <<"topic">> => <<?EGRESS_LOCAL_TOPIC, "/#">> }, <<"remote">> => #{ <<"topic">> => <<?EGRESS_REMOTE_TOPIC, "/${topic}">>, <<"qos">> => <<"${qos}">>, <<"retain">> => <<"${retain}">> } }). -define(assertMetrics(Pat, BridgeID), ?assertMetrics(Pat, true, BridgeID) ). -define(assertMetrics(Pat, Guard, BridgeID), ?assertMatch( #{ <<"metrics">> := Pat, <<"node_metrics">> := [ #{ <<"node">> := _, <<"metrics">> := Pat } ] } when Guard, request_bridge_metrics(BridgeID) ) ). inspect(Selected, _Envs, _Args) -> persistent_term:put(?MODULE, #{inspect => Selected}). all() -> emqx_common_test_helpers:all(?MODULE). groups() -> []. suite() -> [{timetrap, {seconds, 30}}]. init_per_suite(Config) -> _ = application:load(emqx_conf), %% some testcases (may from other app) already get emqx_connector started _ = application:stop(emqx_resource), _ = application:stop(emqx_connector), ok = emqx_common_test_helpers:start_apps( [ emqx_rule_engine, emqx_bridge, emqx_dashboard ], fun set_special_configs/1 ), ok = emqx_common_test_helpers:load_config( emqx_rule_engine_schema, <<"rule_engine {rules {}}">> ), ok = emqx_common_test_helpers:load_config(emqx_bridge_schema, ?BRIDGE_CONF_DEFAULT), Config. end_per_suite(_Config) -> emqx_common_test_helpers:stop_apps([ emqx_rule_engine, emqx_bridge, emqx_dashboard ]), ok. set_special_configs(emqx_dashboard) -> emqx_dashboard_api_test_helpers:set_default_config(<<"connector_admin">>); set_special_configs(_) -> ok. init_per_testcase(_, Config) -> {ok, _} = emqx_cluster_rpc:start_link(node(), emqx_cluster_rpc, 1000), ok = snabbkaffe:start_trace(), Config. end_per_testcase(_, _Config) -> clear_resources(), emqx_common_test_helpers:call_janitor(), snabbkaffe:stop(), ok. clear_resources() -> lists:foreach( fun(#{id := Id}) -> ok = emqx_rule_engine:delete_rule(Id) end, emqx_rule_engine:get_rules() ), lists:foreach( fun(#{type := Type, name := Name}) -> {ok, _} = emqx_bridge:remove(Type, Name) end, emqx_bridge:list() ). %%------------------------------------------------------------------------------ %% Testcases %%------------------------------------------------------------------------------ t_mqtt_conn_bridge_ingress(_) -> User1 = <<"user1">>, %% create an MQTT bridge, using POST {ok, 201, Bridge} = request( post, uri(["bridges"]), ServerConf = ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_INGRESS, <<"ingress">> => ?INGRESS_CONF } ), #{ <<"type">> := ?TYPE_MQTT, <<"name">> := ?BRIDGE_NAME_INGRESS } = jsx:decode(Bridge), BridgeIDIngress = emqx_bridge_resource:bridge_id(?TYPE_MQTT, ?BRIDGE_NAME_INGRESS), %% try to create the bridge again ?assertMatch( {ok, 400, _}, request(post, uri(["bridges"]), ServerConf) ), %% try to reconfigure the bridge ?assertMatch( {ok, 200, _}, request(put, uri(["bridges", BridgeIDIngress]), ServerConf) ), %% we now test if the bridge works as expected RemoteTopic = <<?INGRESS_REMOTE_TOPIC, "/1">>, LocalTopic = <<?INGRESS_LOCAL_TOPIC, "/", RemoteTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(LocalTopic), timer:sleep(100), PUBLISH a message to the ' remote ' broker , as we have only one broker , %% the remote broker is also the local one. emqx:publish(emqx_message:make(RemoteTopic, Payload)), %% we should receive a message on the local broker, with specified topic assert_mqtt_msg_received(LocalTopic, Payload), %% verify the metrics of the bridge ?assertMetrics( #{<<"matched">> := 0, <<"received">> := 1}, BridgeIDIngress ), %% delete the bridge {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDIngress]), []), {ok, 200, <<"[]">>} = request(get, uri(["bridges"]), []), ok. t_mqtt_egress_bridge_ignores_clean_start(_) -> BridgeName = atom_to_binary(?FUNCTION_NAME), BridgeID = create_bridge( ?SERVER_CONF(<<"user1">>)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => BridgeName, <<"egress">> => ?EGRESS_CONF, <<"clean_start">> => false } ), {ok, _, #{state := #{name := WorkerName}}} = emqx_resource:get_instance(emqx_bridge_resource:resource_id(BridgeID)), ?assertMatch( #{clean_start := true}, maps:from_list(emqx_connector_mqtt_worker:info(WorkerName)) ), %% delete the bridge {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeID]), []), ok. t_mqtt_conn_bridge_ingress_downgrades_qos_2(_) -> BridgeName = atom_to_binary(?FUNCTION_NAME), BridgeID = create_bridge( ?SERVER_CONF(<<"user1">>)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => BridgeName, <<"ingress">> => emqx_map_lib:deep_merge( ?INGRESS_CONF, #{<<"remote">> => #{<<"qos">> => 2}} ) } ), RemoteTopic = <<?INGRESS_REMOTE_TOPIC, "/1">>, LocalTopic = <<?INGRESS_LOCAL_TOPIC, "/", RemoteTopic/binary>>, Payload = <<"whatqos">>, emqx:subscribe(LocalTopic), emqx:publish(emqx_message:make(undefined, _QoS = 2, RemoteTopic, Payload)), %% we should receive a message on the local broker, with specified topic Msg = assert_mqtt_msg_received(LocalTopic, Payload), ?assertMatch(#message{qos = 1}, Msg), %% delete the bridge {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeID]), []), ok. t_mqtt_conn_bridge_ingress_no_payload_template(_) -> User1 = <<"user1">>, BridgeIDIngress = create_bridge( ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_INGRESS, <<"ingress">> => ?INGRESS_CONF_NO_PAYLOAD_TEMPLATE } ), %% we now test if the bridge works as expected RemoteTopic = <<?INGRESS_REMOTE_TOPIC, "/1">>, LocalTopic = <<?INGRESS_LOCAL_TOPIC, "/", RemoteTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(LocalTopic), timer:sleep(100), PUBLISH a message to the ' remote ' broker , as we have only one broker , %% the remote broker is also the local one. emqx:publish(emqx_message:make(RemoteTopic, Payload)), %% we should receive a message on the local broker, with specified topic Msg = assert_mqtt_msg_received(LocalTopic), ?assertMatch(#{<<"payload">> := Payload}, jsx:decode(Msg#message.payload)), %% verify the metrics of the bridge ?assertMetrics( #{<<"matched">> := 0, <<"received">> := 1}, BridgeIDIngress ), %% delete the bridge {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDIngress]), []), {ok, 200, <<"[]">>} = request(get, uri(["bridges"]), []), ok. t_mqtt_conn_bridge_egress(_) -> %% then we add a mqtt connector, using POST User1 = <<"user1">>, BridgeIDEgress = create_bridge( ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_EGRESS, <<"egress">> => ?EGRESS_CONF } ), ResourceID = emqx_bridge_resource:resource_id(?TYPE_MQTT, ?BRIDGE_NAME_EGRESS), %% we now test if the bridge works as expected LocalTopic = <<?EGRESS_LOCAL_TOPIC, "/1">>, RemoteTopic = <<?EGRESS_REMOTE_TOPIC, "/", LocalTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(RemoteTopic), ?wait_async_action( PUBLISH a message to the ' local ' broker , as we have only one broker , %% the remote broker is also the local one. emqx:publish(emqx_message:make(LocalTopic, Payload)), #{?snk_kind := buffer_worker_flush_ack} ), %% we should receive a message on the "remote" broker, with specified topic Msg = assert_mqtt_msg_received(RemoteTopic, Payload), Size = byte_size(ResourceID), ?assertMatch(<<ResourceID:Size/binary, _/binary>>, Msg#message.from), %% verify the metrics of the bridge ?retry( _Interval = 200, _Attempts = 5, ?assertMetrics( #{<<"matched">> := 1, <<"success">> := 1, <<"failed">> := 0}, BridgeIDEgress ) ), %% delete the bridge {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDEgress]), []), {ok, 200, <<"[]">>} = request(get, uri(["bridges"]), []), ok. t_mqtt_conn_bridge_egress_no_payload_template(_) -> %% then we add a mqtt connector, using POST User1 = <<"user1">>, BridgeIDEgress = create_bridge( ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_EGRESS, <<"egress">> => ?EGRESS_CONF_NO_PAYLOAD_TEMPLATE } ), ResourceID = emqx_bridge_resource:resource_id(?TYPE_MQTT, ?BRIDGE_NAME_EGRESS), %% we now test if the bridge works as expected LocalTopic = <<?EGRESS_LOCAL_TOPIC, "/1">>, RemoteTopic = <<?EGRESS_REMOTE_TOPIC, "/", LocalTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(RemoteTopic), ?wait_async_action( PUBLISH a message to the ' local ' broker , as we have only one broker , %% the remote broker is also the local one. emqx:publish(emqx_message:make(LocalTopic, Payload)), #{?snk_kind := buffer_worker_flush_ack} ), %% we should receive a message on the "remote" broker, with specified topic Msg = assert_mqtt_msg_received(RemoteTopic), the MapMsg is all fields outputed by Rule - Engine . it 's a binary coded json here . ?assertMatch(<<ResourceID:(byte_size(ResourceID))/binary, _/binary>>, Msg#message.from), ?assertMatch(#{<<"payload">> := Payload}, jsx:decode(Msg#message.payload)), %% verify the metrics of the bridge ?retry( _Interval = 200, _Attempts = 5, ?assertMetrics( #{<<"matched">> := 1, <<"success">> := 1, <<"failed">> := 0}, BridgeIDEgress ) ), %% delete the bridge {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDEgress]), []), {ok, 200, <<"[]">>} = request(get, uri(["bridges"]), []), ok. t_egress_custom_clientid_prefix(_Config) -> User1 = <<"user1">>, BridgeIDEgress = create_bridge( ?SERVER_CONF(User1)#{ <<"clientid_prefix">> => <<"my-custom-prefix">>, <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_EGRESS, <<"egress">> => ?EGRESS_CONF } ), ResourceID = emqx_bridge_resource:resource_id(?TYPE_MQTT, ?BRIDGE_NAME_EGRESS), LocalTopic = <<?EGRESS_LOCAL_TOPIC, "/1">>, RemoteTopic = <<?EGRESS_REMOTE_TOPIC, "/", LocalTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(RemoteTopic), timer:sleep(100), emqx:publish(emqx_message:make(LocalTopic, Payload)), Msg = assert_mqtt_msg_received(RemoteTopic, Payload), Size = byte_size(ResourceID), ?assertMatch(<<"my-custom-prefix:", _ResouceID:Size/binary, _/binary>>, Msg#message.from), {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDEgress]), []), ok. t_mqtt_conn_bridge_ingress_and_egress(_) -> User1 = <<"user1">>, BridgeIDIngress = create_bridge( ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_INGRESS, <<"ingress">> => ?INGRESS_CONF } ), BridgeIDEgress = create_bridge( ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_EGRESS, <<"egress">> => ?EGRESS_CONF } ), %% we now test if the bridge works as expected LocalTopic = <<?EGRESS_LOCAL_TOPIC, "/1">>, RemoteTopic = <<?EGRESS_REMOTE_TOPIC, "/", LocalTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(RemoteTopic), #{ <<"metrics">> := #{ <<"matched">> := CntMatched1, <<"success">> := CntSuccess1, <<"failed">> := 0 }, <<"node_metrics">> := [ #{ <<"node">> := _, <<"metrics">> := #{ <<"matched">> := NodeCntMatched1, <<"success">> := NodeCntSuccess1, <<"failed">> := 0 } } ] } = request_bridge_metrics(BridgeIDEgress), ?wait_async_action( PUBLISH a message to the ' local ' broker , as we have only one broker , %% the remote broker is also the local one. emqx:publish(emqx_message:make(LocalTopic, Payload)), #{?snk_kind := buffer_worker_flush_ack} ), %% we should receive a message on the "remote" broker, with specified topic assert_mqtt_msg_received(RemoteTopic, Payload), %% verify the metrics of the bridge timer:sleep(1000), #{ <<"metrics">> := #{ <<"matched">> := CntMatched2, <<"success">> := CntSuccess2, <<"failed">> := 0 }, <<"node_metrics">> := [ #{ <<"node">> := _, <<"metrics">> := #{ <<"matched">> := NodeCntMatched2, <<"success">> := NodeCntSuccess2, <<"failed">> := 0 } } ] } = request_bridge_metrics(BridgeIDEgress), ?assertEqual(CntMatched2, CntMatched1 + 1), ?assertEqual(CntSuccess2, CntSuccess1 + 1), ?assertEqual(NodeCntMatched2, NodeCntMatched1 + 1), ?assertEqual(NodeCntSuccess2, NodeCntSuccess1 + 1), %% delete the bridge {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDEgress]), []), {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDIngress]), []), {ok, 200, <<"[]">>} = request(get, uri(["bridges"]), []), ok. t_ingress_mqtt_bridge_with_rules(_) -> BridgeIDIngress = create_bridge( ?SERVER_CONF(<<"user1">>)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_INGRESS, <<"ingress">> => ?INGRESS_CONF } ), {ok, 201, Rule} = request( post, uri(["rules"]), #{ <<"name">> => <<"A_rule_get_messages_from_a_source_mqtt_bridge">>, <<"enable">> => true, <<"actions">> => [#{<<"function">> => "emqx_bridge_mqtt_SUITE:inspect"}], <<"sql">> => <<"SELECT * from \"$bridges/", BridgeIDIngress/binary, "\"">> } ), #{<<"id">> := RuleId} = jsx:decode(Rule), %% we now test if the bridge works as expected RemoteTopic = <<?INGRESS_REMOTE_TOPIC, "/1">>, LocalTopic = <<?INGRESS_LOCAL_TOPIC, "/", RemoteTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(LocalTopic), timer:sleep(100), PUBLISH a message to the ' remote ' broker , as we have only one broker , %% the remote broker is also the local one. emqx:publish(emqx_message:make(RemoteTopic, Payload)), %% we should receive a message on the local broker, with specified topic assert_mqtt_msg_received(LocalTopic, Payload), and also the rule should be matched , with matched + 1 : {ok, 200, Rule1} = request(get, uri(["rules", RuleId]), []), {ok, 200, Metrics} = request(get, uri(["rules", RuleId, "metrics"]), []), ?assertMatch(#{<<"id">> := RuleId}, jsx:decode(Rule1)), ?assertMatch( #{ <<"metrics">> := #{ <<"matched">> := 1, <<"passed">> := 1, <<"failed">> := 0, <<"failed.exception">> := 0, <<"failed.no_result">> := 0, <<"matched.rate">> := _, <<"matched.rate.max">> := _, <<"matched.rate.last5m">> := _, <<"actions.total">> := 1, <<"actions.success">> := 1, <<"actions.failed">> := 0, <<"actions.failed.out_of_service">> := 0, <<"actions.failed.unknown">> := 0 } }, jsx:decode(Metrics) ), %% we also check if the actions of the rule is triggered ?assertMatch( #{ inspect := #{ event := <<"$bridges/mqtt", _/binary>>, id := MsgId, payload := Payload, topic := RemoteTopic, qos := 0, dup := false, retain := false, pub_props := #{}, timestamp := _ } } when is_binary(MsgId), persistent_term:get(?MODULE) ), %% verify the metrics of the bridge ?assertMetrics( #{<<"matched">> := 0, <<"received">> := 1}, BridgeIDIngress ), {ok, 204, <<>>} = request(delete, uri(["rules", RuleId]), []), {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDIngress]), []). t_egress_mqtt_bridge_with_rules(_) -> BridgeIDEgress = create_bridge( ?SERVER_CONF(<<"user1">>)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_EGRESS, <<"egress">> => ?EGRESS_CONF } ), {ok, 201, Rule} = request( post, uri(["rules"]), #{ <<"name">> => <<"A_rule_send_messages_to_a_sink_mqtt_bridge">>, <<"enable">> => true, <<"actions">> => [BridgeIDEgress], <<"sql">> => <<"SELECT * from \"t/1\"">> } ), #{<<"id">> := RuleId} = jsx:decode(Rule), %% we now test if the bridge works as expected LocalTopic = <<?EGRESS_LOCAL_TOPIC, "/1">>, RemoteTopic = <<?EGRESS_REMOTE_TOPIC, "/", LocalTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(RemoteTopic), timer:sleep(100), PUBLISH a message to the ' local ' broker , as we have only one broker , %% the remote broker is also the local one. emqx:publish(emqx_message:make(LocalTopic, Payload)), %% we should receive a message on the "remote" broker, with specified topic assert_mqtt_msg_received(RemoteTopic, Payload), emqx:unsubscribe(RemoteTopic), %% PUBLISH a message to the rule. Payload2 = <<"hi">>, RuleTopic = <<"t/1">>, RemoteTopic2 = <<?EGRESS_REMOTE_TOPIC, "/", RuleTopic/binary>>, emqx:subscribe(RemoteTopic2), timer:sleep(100), emqx:publish(emqx_message:make(RuleTopic, Payload2)), {ok, 200, Rule1} = request(get, uri(["rules", RuleId]), []), ?assertMatch(#{<<"id">> := RuleId, <<"name">> := _}, jsx:decode(Rule1)), {ok, 200, Metrics} = request(get, uri(["rules", RuleId, "metrics"]), []), ?assertMatch( #{ <<"metrics">> := #{ <<"matched">> := 1, <<"passed">> := 1, <<"failed">> := 0, <<"failed.exception">> := 0, <<"failed.no_result">> := 0, <<"matched.rate">> := _, <<"matched.rate.max">> := _, <<"matched.rate.last5m">> := _, <<"actions.total">> := 1, <<"actions.success">> := 1, <<"actions.failed">> := 0, <<"actions.failed.out_of_service">> := 0, <<"actions.failed.unknown">> := 0 } }, jsx:decode(Metrics) ), %% we should receive a message on the "remote" broker, with specified topic assert_mqtt_msg_received(RemoteTopic2, Payload2), %% verify the metrics of the bridge ?assertMetrics( #{<<"matched">> := 2, <<"success">> := 2, <<"failed">> := 0}, BridgeIDEgress ), {ok, 204, <<>>} = request(delete, uri(["rules", RuleId]), []), {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDEgress]), []). t_mqtt_conn_bridge_egress_reconnect(_) -> %% then we add a mqtt connector, using POST User1 = <<"user1">>, BridgeIDEgress = create_bridge( ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_EGRESS, <<"egress">> => ?EGRESS_CONF, <<"resource_opts">> => #{ <<"worker_pool_size">> => 2, <<"query_mode">> => <<"sync">>, %% using a long time so we can test recovery <<"request_timeout">> => <<"15s">>, %% to make it check the healthy quickly <<"health_check_interval">> => <<"0.5s">>, %% to make it reconnect quickly <<"auto_restart_interval">> => <<"1s">> } } ), on_exit(fun() -> %% delete the bridge {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDEgress]), []), {ok, 200, <<"[]">>} = request(get, uri(["bridges"]), []), ok end), %% we now test if the bridge works as expected LocalTopic = <<?EGRESS_LOCAL_TOPIC, "/1">>, RemoteTopic = <<?EGRESS_REMOTE_TOPIC, "/", LocalTopic/binary>>, Payload0 = <<"hello">>, emqx:subscribe(RemoteTopic), ?wait_async_action( PUBLISH a message to the ' local ' broker , as we have only one broker , %% the remote broker is also the local one. emqx:publish(emqx_message:make(LocalTopic, Payload0)), #{?snk_kind := buffer_worker_flush_ack} ), %% we should receive a message on the "remote" broker, with specified topic assert_mqtt_msg_received(RemoteTopic, Payload0), %% verify the metrics of the bridge ?assertMetrics( #{<<"matched">> := 1, <<"success">> := 1, <<"failed">> := 0}, BridgeIDEgress ), stop the listener 1883 to make the bridge disconnected ok = emqx_listeners:stop_listener('tcp:default'), ct:sleep(1500), PUBLISH 2 messages to the ' local ' broker , the messages should %% be enqueued and the resource will block {ok, SRef} = snabbkaffe:subscribe( fun (#{?snk_kind := buffer_worker_retry_inflight_failed}) -> true; (#{?snk_kind := buffer_worker_flush_nack}) -> true; (_) -> false end, _NEvents = 2, _Timeout = 1_000 ), Payload1 = <<"hello2">>, Payload2 = <<"hello3">>, %% We need to do it in other processes because it'll block due to %% the long timeout spawn(fun() -> emqx:publish(emqx_message:make(LocalTopic, Payload1)) end), spawn(fun() -> emqx:publish(emqx_message:make(LocalTopic, Payload2)) end), {ok, _} = snabbkaffe:receive_events(SRef), %% verify the metrics of the bridge, the message should be queued ?assertMatch( #{<<"status">> := Status} when Status == <<"connecting">> orelse Status == <<"disconnected">>, request_bridge(BridgeIDEgress) ), matched > = 3 because of possible retries . ?assertMetrics( #{ <<"matched">> := Matched, <<"success">> := 1, <<"failed">> := 0, <<"queuing">> := Queuing, <<"inflight">> := Inflight }, Matched >= 3 andalso Inflight + Queuing == 2, BridgeIDEgress ), start the listener 1883 to make the bridge reconnected ok = emqx_listeners:start_listener('tcp:default'), timer:sleep(1500), verify the metrics of the bridge , the 2 queued messages should have been sent ?assertMatch(#{<<"status">> := <<"connected">>}, request_bridge(BridgeIDEgress)), matched > = 3 because of possible retries . ?assertMetrics( #{ <<"matched">> := Matched, <<"success">> := 3, <<"failed">> := 0, <<"queuing">> := 0, <<"retried">> := _ }, Matched >= 3, BridgeIDEgress ), also verify the 2 messages have been sent to the remote broker assert_mqtt_msg_received(RemoteTopic, Payload1), assert_mqtt_msg_received(RemoteTopic, Payload2), ok. t_mqtt_conn_bridge_egress_async_reconnect(_) -> User1 = <<"user1">>, BridgeIDEgress = create_bridge( ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_EGRESS, <<"egress">> => ?EGRESS_CONF, <<"resource_opts">> => #{ <<"worker_pool_size">> => 2, <<"query_mode">> => <<"async">>, %% using a long time so we can test recovery <<"request_timeout">> => <<"15s">>, %% to make it check the healthy quickly <<"health_check_interval">> => <<"0.5s">>, %% to make it reconnect quickly <<"auto_restart_interval">> => <<"1s">> } } ), on_exit(fun() -> %% delete the bridge {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDEgress]), []), {ok, 200, <<"[]">>} = request(get, uri(["bridges"]), []), ok end), Self = self(), LocalTopic = <<?EGRESS_LOCAL_TOPIC, "/1">>, RemoteTopic = <<?EGRESS_REMOTE_TOPIC, "/", LocalTopic/binary>>, emqx:subscribe(RemoteTopic), Publisher = start_publisher(LocalTopic, 200, Self), ct:sleep(1000), stop the listener 1883 to make the bridge disconnected ok = emqx_listeners:stop_listener('tcp:default'), ct:sleep(1500), ?assertMatch( #{<<"status">> := Status} when Status == <<"connecting">> orelse Status == <<"disconnected">>, request_bridge(BridgeIDEgress) ), start the listener 1883 to make the bridge reconnected ok = emqx_listeners:start_listener('tcp:default'), timer:sleep(1500), ?assertMatch( #{<<"status">> := <<"connected">>}, request_bridge(BridgeIDEgress) ), N = stop_publisher(Publisher), %% all those messages should eventually be delivered [ assert_mqtt_msg_received(RemoteTopic, Payload) || I <- lists:seq(1, N), Payload <- [integer_to_binary(I)] ], ok. start_publisher(Topic, Interval, CtrlPid) -> spawn_link(fun() -> publisher(Topic, 1, Interval, CtrlPid) end). stop_publisher(Pid) -> _ = Pid ! {self(), stop}, receive {Pid, N} -> N after 1_000 -> ct:fail("publisher ~p did not stop", [Pid]) end. publisher(Topic, N, Delay, CtrlPid) -> _ = emqx:publish(emqx_message:make(Topic, integer_to_binary(N))), receive {CtrlPid, stop} -> CtrlPid ! {self(), N} after Delay -> publisher(Topic, N + 1, Delay, CtrlPid) end. %% assert_mqtt_msg_received(Topic) -> assert_mqtt_msg_received(Topic, '_', 200). assert_mqtt_msg_received(Topic, Payload) -> assert_mqtt_msg_received(Topic, Payload, 200). assert_mqtt_msg_received(Topic, Payload, Timeout) -> receive {deliver, Topic, Msg = #message{}} when Payload == '_' -> ct:pal("received mqtt ~p on topic ~p", [Msg, Topic]), Msg; {deliver, Topic, Msg = #message{payload = Payload}} -> ct:pal("received mqtt ~p on topic ~p", [Msg, Topic]), Msg after Timeout -> {messages, Messages} = process_info(self(), messages), ct:fail("timeout waiting ~p ms for ~p on topic '~s', messages = ~0p", [ Timeout, Payload, Topic, Messages ]) end. create_bridge(Config = #{<<"type">> := Type, <<"name">> := Name}) -> {ok, 201, Bridge} = request( post, uri(["bridges"]), Config ), ?assertMatch( #{ <<"type">> := Type, <<"name">> := Name }, jsx:decode(Bridge) ), emqx_bridge_resource:bridge_id(Type, Name). request_bridge(BridgeID) -> {ok, 200, Bridge} = request(get, uri(["bridges", BridgeID]), []), jsx:decode(Bridge). request_bridge_metrics(BridgeID) -> {ok, 200, BridgeMetrics} = request(get, uri(["bridges", BridgeID, "metrics"]), []), jsx:decode(BridgeMetrics). request(Method, Url, Body) -> request(<<"connector_admin">>, Method, Url, Body).
null
https://raw.githubusercontent.com/emqx/emqx/2fa4e8e21afe50eae598bb20a3eb95ef158a5098/apps/emqx_bridge/test/emqx_bridge_mqtt_SUITE.erl
erlang
-------------------------------------------------------------------- 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. -------------------------------------------------------------------- output functions Having ingress/egress prefixs of topic names to avoid dead loop while bridging some testcases (may from other app) already get emqx_connector started ------------------------------------------------------------------------------ Testcases ------------------------------------------------------------------------------ create an MQTT bridge, using POST try to create the bridge again try to reconfigure the bridge we now test if the bridge works as expected the remote broker is also the local one. we should receive a message on the local broker, with specified topic verify the metrics of the bridge delete the bridge delete the bridge we should receive a message on the local broker, with specified topic delete the bridge we now test if the bridge works as expected the remote broker is also the local one. we should receive a message on the local broker, with specified topic verify the metrics of the bridge delete the bridge then we add a mqtt connector, using POST we now test if the bridge works as expected the remote broker is also the local one. we should receive a message on the "remote" broker, with specified topic verify the metrics of the bridge delete the bridge then we add a mqtt connector, using POST we now test if the bridge works as expected the remote broker is also the local one. we should receive a message on the "remote" broker, with specified topic verify the metrics of the bridge delete the bridge we now test if the bridge works as expected the remote broker is also the local one. we should receive a message on the "remote" broker, with specified topic verify the metrics of the bridge delete the bridge we now test if the bridge works as expected the remote broker is also the local one. we should receive a message on the local broker, with specified topic we also check if the actions of the rule is triggered verify the metrics of the bridge we now test if the bridge works as expected the remote broker is also the local one. we should receive a message on the "remote" broker, with specified topic PUBLISH a message to the rule. we should receive a message on the "remote" broker, with specified topic verify the metrics of the bridge then we add a mqtt connector, using POST using a long time so we can test recovery to make it check the healthy quickly to make it reconnect quickly delete the bridge we now test if the bridge works as expected the remote broker is also the local one. we should receive a message on the "remote" broker, with specified topic verify the metrics of the bridge be enqueued and the resource will block We need to do it in other processes because it'll block due to the long timeout verify the metrics of the bridge, the message should be queued using a long time so we can test recovery to make it check the healthy quickly to make it reconnect quickly delete the bridge all those messages should eventually be delivered
Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(emqx_bridge_mqtt_SUITE). -compile(nowarn_export_all). -compile(export_all). -import(emqx_dashboard_api_test_helpers, [request/4, uri/1]). -import(emqx_common_test_helpers, [on_exit/1]). -include("emqx/include/emqx.hrl"). -include_lib("eunit/include/eunit.hrl"). -include_lib("common_test/include/ct.hrl"). -include_lib("snabbkaffe/include/snabbkaffe.hrl"). -include("emqx_dashboard/include/emqx_dashboard.hrl"). -export([inspect/3]). -define(BRIDGE_CONF_DEFAULT, <<"bridges: {}">>). -define(TYPE_MQTT, <<"mqtt">>). -define(BRIDGE_NAME_INGRESS, <<"ingress_mqtt_bridge">>). -define(BRIDGE_NAME_EGRESS, <<"egress_mqtt_bridge">>). -define(INGRESS_REMOTE_TOPIC, "ingress_remote_topic"). -define(INGRESS_LOCAL_TOPIC, "ingress_local_topic"). -define(EGRESS_REMOTE_TOPIC, "egress_remote_topic"). -define(EGRESS_LOCAL_TOPIC, "egress_local_topic"). -define(SERVER_CONF(Username), #{ <<"server">> => <<"127.0.0.1:1883">>, <<"username">> => Username, <<"password">> => <<"">>, <<"proto_ver">> => <<"v4">>, <<"ssl">> => #{<<"enable">> => false} }). -define(INGRESS_CONF, #{ <<"remote">> => #{ <<"topic">> => <<?INGRESS_REMOTE_TOPIC, "/#">>, <<"qos">> => 1 }, <<"local">> => #{ <<"topic">> => <<?INGRESS_LOCAL_TOPIC, "/${topic}">>, <<"qos">> => <<"${qos}">>, <<"payload">> => <<"${payload}">>, <<"retain">> => <<"${retain}">> } }). -define(EGRESS_CONF, #{ <<"local">> => #{ <<"topic">> => <<?EGRESS_LOCAL_TOPIC, "/#">> }, <<"remote">> => #{ <<"topic">> => <<?EGRESS_REMOTE_TOPIC, "/${topic}">>, <<"payload">> => <<"${payload}">>, <<"qos">> => <<"${qos}">>, <<"retain">> => <<"${retain}">> } }). -define(INGRESS_CONF_NO_PAYLOAD_TEMPLATE, #{ <<"remote">> => #{ <<"topic">> => <<?INGRESS_REMOTE_TOPIC, "/#">>, <<"qos">> => 1 }, <<"local">> => #{ <<"topic">> => <<?INGRESS_LOCAL_TOPIC, "/${topic}">>, <<"qos">> => <<"${qos}">>, <<"retain">> => <<"${retain}">> } }). -define(EGRESS_CONF_NO_PAYLOAD_TEMPLATE, #{ <<"local">> => #{ <<"topic">> => <<?EGRESS_LOCAL_TOPIC, "/#">> }, <<"remote">> => #{ <<"topic">> => <<?EGRESS_REMOTE_TOPIC, "/${topic}">>, <<"qos">> => <<"${qos}">>, <<"retain">> => <<"${retain}">> } }). -define(assertMetrics(Pat, BridgeID), ?assertMetrics(Pat, true, BridgeID) ). -define(assertMetrics(Pat, Guard, BridgeID), ?assertMatch( #{ <<"metrics">> := Pat, <<"node_metrics">> := [ #{ <<"node">> := _, <<"metrics">> := Pat } ] } when Guard, request_bridge_metrics(BridgeID) ) ). inspect(Selected, _Envs, _Args) -> persistent_term:put(?MODULE, #{inspect => Selected}). all() -> emqx_common_test_helpers:all(?MODULE). groups() -> []. suite() -> [{timetrap, {seconds, 30}}]. init_per_suite(Config) -> _ = application:load(emqx_conf), _ = application:stop(emqx_resource), _ = application:stop(emqx_connector), ok = emqx_common_test_helpers:start_apps( [ emqx_rule_engine, emqx_bridge, emqx_dashboard ], fun set_special_configs/1 ), ok = emqx_common_test_helpers:load_config( emqx_rule_engine_schema, <<"rule_engine {rules {}}">> ), ok = emqx_common_test_helpers:load_config(emqx_bridge_schema, ?BRIDGE_CONF_DEFAULT), Config. end_per_suite(_Config) -> emqx_common_test_helpers:stop_apps([ emqx_rule_engine, emqx_bridge, emqx_dashboard ]), ok. set_special_configs(emqx_dashboard) -> emqx_dashboard_api_test_helpers:set_default_config(<<"connector_admin">>); set_special_configs(_) -> ok. init_per_testcase(_, Config) -> {ok, _} = emqx_cluster_rpc:start_link(node(), emqx_cluster_rpc, 1000), ok = snabbkaffe:start_trace(), Config. end_per_testcase(_, _Config) -> clear_resources(), emqx_common_test_helpers:call_janitor(), snabbkaffe:stop(), ok. clear_resources() -> lists:foreach( fun(#{id := Id}) -> ok = emqx_rule_engine:delete_rule(Id) end, emqx_rule_engine:get_rules() ), lists:foreach( fun(#{type := Type, name := Name}) -> {ok, _} = emqx_bridge:remove(Type, Name) end, emqx_bridge:list() ). t_mqtt_conn_bridge_ingress(_) -> User1 = <<"user1">>, {ok, 201, Bridge} = request( post, uri(["bridges"]), ServerConf = ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_INGRESS, <<"ingress">> => ?INGRESS_CONF } ), #{ <<"type">> := ?TYPE_MQTT, <<"name">> := ?BRIDGE_NAME_INGRESS } = jsx:decode(Bridge), BridgeIDIngress = emqx_bridge_resource:bridge_id(?TYPE_MQTT, ?BRIDGE_NAME_INGRESS), ?assertMatch( {ok, 400, _}, request(post, uri(["bridges"]), ServerConf) ), ?assertMatch( {ok, 200, _}, request(put, uri(["bridges", BridgeIDIngress]), ServerConf) ), RemoteTopic = <<?INGRESS_REMOTE_TOPIC, "/1">>, LocalTopic = <<?INGRESS_LOCAL_TOPIC, "/", RemoteTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(LocalTopic), timer:sleep(100), PUBLISH a message to the ' remote ' broker , as we have only one broker , emqx:publish(emqx_message:make(RemoteTopic, Payload)), assert_mqtt_msg_received(LocalTopic, Payload), ?assertMetrics( #{<<"matched">> := 0, <<"received">> := 1}, BridgeIDIngress ), {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDIngress]), []), {ok, 200, <<"[]">>} = request(get, uri(["bridges"]), []), ok. t_mqtt_egress_bridge_ignores_clean_start(_) -> BridgeName = atom_to_binary(?FUNCTION_NAME), BridgeID = create_bridge( ?SERVER_CONF(<<"user1">>)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => BridgeName, <<"egress">> => ?EGRESS_CONF, <<"clean_start">> => false } ), {ok, _, #{state := #{name := WorkerName}}} = emqx_resource:get_instance(emqx_bridge_resource:resource_id(BridgeID)), ?assertMatch( #{clean_start := true}, maps:from_list(emqx_connector_mqtt_worker:info(WorkerName)) ), {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeID]), []), ok. t_mqtt_conn_bridge_ingress_downgrades_qos_2(_) -> BridgeName = atom_to_binary(?FUNCTION_NAME), BridgeID = create_bridge( ?SERVER_CONF(<<"user1">>)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => BridgeName, <<"ingress">> => emqx_map_lib:deep_merge( ?INGRESS_CONF, #{<<"remote">> => #{<<"qos">> => 2}} ) } ), RemoteTopic = <<?INGRESS_REMOTE_TOPIC, "/1">>, LocalTopic = <<?INGRESS_LOCAL_TOPIC, "/", RemoteTopic/binary>>, Payload = <<"whatqos">>, emqx:subscribe(LocalTopic), emqx:publish(emqx_message:make(undefined, _QoS = 2, RemoteTopic, Payload)), Msg = assert_mqtt_msg_received(LocalTopic, Payload), ?assertMatch(#message{qos = 1}, Msg), {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeID]), []), ok. t_mqtt_conn_bridge_ingress_no_payload_template(_) -> User1 = <<"user1">>, BridgeIDIngress = create_bridge( ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_INGRESS, <<"ingress">> => ?INGRESS_CONF_NO_PAYLOAD_TEMPLATE } ), RemoteTopic = <<?INGRESS_REMOTE_TOPIC, "/1">>, LocalTopic = <<?INGRESS_LOCAL_TOPIC, "/", RemoteTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(LocalTopic), timer:sleep(100), PUBLISH a message to the ' remote ' broker , as we have only one broker , emqx:publish(emqx_message:make(RemoteTopic, Payload)), Msg = assert_mqtt_msg_received(LocalTopic), ?assertMatch(#{<<"payload">> := Payload}, jsx:decode(Msg#message.payload)), ?assertMetrics( #{<<"matched">> := 0, <<"received">> := 1}, BridgeIDIngress ), {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDIngress]), []), {ok, 200, <<"[]">>} = request(get, uri(["bridges"]), []), ok. t_mqtt_conn_bridge_egress(_) -> User1 = <<"user1">>, BridgeIDEgress = create_bridge( ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_EGRESS, <<"egress">> => ?EGRESS_CONF } ), ResourceID = emqx_bridge_resource:resource_id(?TYPE_MQTT, ?BRIDGE_NAME_EGRESS), LocalTopic = <<?EGRESS_LOCAL_TOPIC, "/1">>, RemoteTopic = <<?EGRESS_REMOTE_TOPIC, "/", LocalTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(RemoteTopic), ?wait_async_action( PUBLISH a message to the ' local ' broker , as we have only one broker , emqx:publish(emqx_message:make(LocalTopic, Payload)), #{?snk_kind := buffer_worker_flush_ack} ), Msg = assert_mqtt_msg_received(RemoteTopic, Payload), Size = byte_size(ResourceID), ?assertMatch(<<ResourceID:Size/binary, _/binary>>, Msg#message.from), ?retry( _Interval = 200, _Attempts = 5, ?assertMetrics( #{<<"matched">> := 1, <<"success">> := 1, <<"failed">> := 0}, BridgeIDEgress ) ), {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDEgress]), []), {ok, 200, <<"[]">>} = request(get, uri(["bridges"]), []), ok. t_mqtt_conn_bridge_egress_no_payload_template(_) -> User1 = <<"user1">>, BridgeIDEgress = create_bridge( ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_EGRESS, <<"egress">> => ?EGRESS_CONF_NO_PAYLOAD_TEMPLATE } ), ResourceID = emqx_bridge_resource:resource_id(?TYPE_MQTT, ?BRIDGE_NAME_EGRESS), LocalTopic = <<?EGRESS_LOCAL_TOPIC, "/1">>, RemoteTopic = <<?EGRESS_REMOTE_TOPIC, "/", LocalTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(RemoteTopic), ?wait_async_action( PUBLISH a message to the ' local ' broker , as we have only one broker , emqx:publish(emqx_message:make(LocalTopic, Payload)), #{?snk_kind := buffer_worker_flush_ack} ), Msg = assert_mqtt_msg_received(RemoteTopic), the MapMsg is all fields outputed by Rule - Engine . it 's a binary coded json here . ?assertMatch(<<ResourceID:(byte_size(ResourceID))/binary, _/binary>>, Msg#message.from), ?assertMatch(#{<<"payload">> := Payload}, jsx:decode(Msg#message.payload)), ?retry( _Interval = 200, _Attempts = 5, ?assertMetrics( #{<<"matched">> := 1, <<"success">> := 1, <<"failed">> := 0}, BridgeIDEgress ) ), {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDEgress]), []), {ok, 200, <<"[]">>} = request(get, uri(["bridges"]), []), ok. t_egress_custom_clientid_prefix(_Config) -> User1 = <<"user1">>, BridgeIDEgress = create_bridge( ?SERVER_CONF(User1)#{ <<"clientid_prefix">> => <<"my-custom-prefix">>, <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_EGRESS, <<"egress">> => ?EGRESS_CONF } ), ResourceID = emqx_bridge_resource:resource_id(?TYPE_MQTT, ?BRIDGE_NAME_EGRESS), LocalTopic = <<?EGRESS_LOCAL_TOPIC, "/1">>, RemoteTopic = <<?EGRESS_REMOTE_TOPIC, "/", LocalTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(RemoteTopic), timer:sleep(100), emqx:publish(emqx_message:make(LocalTopic, Payload)), Msg = assert_mqtt_msg_received(RemoteTopic, Payload), Size = byte_size(ResourceID), ?assertMatch(<<"my-custom-prefix:", _ResouceID:Size/binary, _/binary>>, Msg#message.from), {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDEgress]), []), ok. t_mqtt_conn_bridge_ingress_and_egress(_) -> User1 = <<"user1">>, BridgeIDIngress = create_bridge( ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_INGRESS, <<"ingress">> => ?INGRESS_CONF } ), BridgeIDEgress = create_bridge( ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_EGRESS, <<"egress">> => ?EGRESS_CONF } ), LocalTopic = <<?EGRESS_LOCAL_TOPIC, "/1">>, RemoteTopic = <<?EGRESS_REMOTE_TOPIC, "/", LocalTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(RemoteTopic), #{ <<"metrics">> := #{ <<"matched">> := CntMatched1, <<"success">> := CntSuccess1, <<"failed">> := 0 }, <<"node_metrics">> := [ #{ <<"node">> := _, <<"metrics">> := #{ <<"matched">> := NodeCntMatched1, <<"success">> := NodeCntSuccess1, <<"failed">> := 0 } } ] } = request_bridge_metrics(BridgeIDEgress), ?wait_async_action( PUBLISH a message to the ' local ' broker , as we have only one broker , emqx:publish(emqx_message:make(LocalTopic, Payload)), #{?snk_kind := buffer_worker_flush_ack} ), assert_mqtt_msg_received(RemoteTopic, Payload), timer:sleep(1000), #{ <<"metrics">> := #{ <<"matched">> := CntMatched2, <<"success">> := CntSuccess2, <<"failed">> := 0 }, <<"node_metrics">> := [ #{ <<"node">> := _, <<"metrics">> := #{ <<"matched">> := NodeCntMatched2, <<"success">> := NodeCntSuccess2, <<"failed">> := 0 } } ] } = request_bridge_metrics(BridgeIDEgress), ?assertEqual(CntMatched2, CntMatched1 + 1), ?assertEqual(CntSuccess2, CntSuccess1 + 1), ?assertEqual(NodeCntMatched2, NodeCntMatched1 + 1), ?assertEqual(NodeCntSuccess2, NodeCntSuccess1 + 1), {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDEgress]), []), {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDIngress]), []), {ok, 200, <<"[]">>} = request(get, uri(["bridges"]), []), ok. t_ingress_mqtt_bridge_with_rules(_) -> BridgeIDIngress = create_bridge( ?SERVER_CONF(<<"user1">>)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_INGRESS, <<"ingress">> => ?INGRESS_CONF } ), {ok, 201, Rule} = request( post, uri(["rules"]), #{ <<"name">> => <<"A_rule_get_messages_from_a_source_mqtt_bridge">>, <<"enable">> => true, <<"actions">> => [#{<<"function">> => "emqx_bridge_mqtt_SUITE:inspect"}], <<"sql">> => <<"SELECT * from \"$bridges/", BridgeIDIngress/binary, "\"">> } ), #{<<"id">> := RuleId} = jsx:decode(Rule), RemoteTopic = <<?INGRESS_REMOTE_TOPIC, "/1">>, LocalTopic = <<?INGRESS_LOCAL_TOPIC, "/", RemoteTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(LocalTopic), timer:sleep(100), PUBLISH a message to the ' remote ' broker , as we have only one broker , emqx:publish(emqx_message:make(RemoteTopic, Payload)), assert_mqtt_msg_received(LocalTopic, Payload), and also the rule should be matched , with matched + 1 : {ok, 200, Rule1} = request(get, uri(["rules", RuleId]), []), {ok, 200, Metrics} = request(get, uri(["rules", RuleId, "metrics"]), []), ?assertMatch(#{<<"id">> := RuleId}, jsx:decode(Rule1)), ?assertMatch( #{ <<"metrics">> := #{ <<"matched">> := 1, <<"passed">> := 1, <<"failed">> := 0, <<"failed.exception">> := 0, <<"failed.no_result">> := 0, <<"matched.rate">> := _, <<"matched.rate.max">> := _, <<"matched.rate.last5m">> := _, <<"actions.total">> := 1, <<"actions.success">> := 1, <<"actions.failed">> := 0, <<"actions.failed.out_of_service">> := 0, <<"actions.failed.unknown">> := 0 } }, jsx:decode(Metrics) ), ?assertMatch( #{ inspect := #{ event := <<"$bridges/mqtt", _/binary>>, id := MsgId, payload := Payload, topic := RemoteTopic, qos := 0, dup := false, retain := false, pub_props := #{}, timestamp := _ } } when is_binary(MsgId), persistent_term:get(?MODULE) ), ?assertMetrics( #{<<"matched">> := 0, <<"received">> := 1}, BridgeIDIngress ), {ok, 204, <<>>} = request(delete, uri(["rules", RuleId]), []), {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDIngress]), []). t_egress_mqtt_bridge_with_rules(_) -> BridgeIDEgress = create_bridge( ?SERVER_CONF(<<"user1">>)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_EGRESS, <<"egress">> => ?EGRESS_CONF } ), {ok, 201, Rule} = request( post, uri(["rules"]), #{ <<"name">> => <<"A_rule_send_messages_to_a_sink_mqtt_bridge">>, <<"enable">> => true, <<"actions">> => [BridgeIDEgress], <<"sql">> => <<"SELECT * from \"t/1\"">> } ), #{<<"id">> := RuleId} = jsx:decode(Rule), LocalTopic = <<?EGRESS_LOCAL_TOPIC, "/1">>, RemoteTopic = <<?EGRESS_REMOTE_TOPIC, "/", LocalTopic/binary>>, Payload = <<"hello">>, emqx:subscribe(RemoteTopic), timer:sleep(100), PUBLISH a message to the ' local ' broker , as we have only one broker , emqx:publish(emqx_message:make(LocalTopic, Payload)), assert_mqtt_msg_received(RemoteTopic, Payload), emqx:unsubscribe(RemoteTopic), Payload2 = <<"hi">>, RuleTopic = <<"t/1">>, RemoteTopic2 = <<?EGRESS_REMOTE_TOPIC, "/", RuleTopic/binary>>, emqx:subscribe(RemoteTopic2), timer:sleep(100), emqx:publish(emqx_message:make(RuleTopic, Payload2)), {ok, 200, Rule1} = request(get, uri(["rules", RuleId]), []), ?assertMatch(#{<<"id">> := RuleId, <<"name">> := _}, jsx:decode(Rule1)), {ok, 200, Metrics} = request(get, uri(["rules", RuleId, "metrics"]), []), ?assertMatch( #{ <<"metrics">> := #{ <<"matched">> := 1, <<"passed">> := 1, <<"failed">> := 0, <<"failed.exception">> := 0, <<"failed.no_result">> := 0, <<"matched.rate">> := _, <<"matched.rate.max">> := _, <<"matched.rate.last5m">> := _, <<"actions.total">> := 1, <<"actions.success">> := 1, <<"actions.failed">> := 0, <<"actions.failed.out_of_service">> := 0, <<"actions.failed.unknown">> := 0 } }, jsx:decode(Metrics) ), assert_mqtt_msg_received(RemoteTopic2, Payload2), ?assertMetrics( #{<<"matched">> := 2, <<"success">> := 2, <<"failed">> := 0}, BridgeIDEgress ), {ok, 204, <<>>} = request(delete, uri(["rules", RuleId]), []), {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDEgress]), []). t_mqtt_conn_bridge_egress_reconnect(_) -> User1 = <<"user1">>, BridgeIDEgress = create_bridge( ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_EGRESS, <<"egress">> => ?EGRESS_CONF, <<"resource_opts">> => #{ <<"worker_pool_size">> => 2, <<"query_mode">> => <<"sync">>, <<"request_timeout">> => <<"15s">>, <<"health_check_interval">> => <<"0.5s">>, <<"auto_restart_interval">> => <<"1s">> } } ), on_exit(fun() -> {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDEgress]), []), {ok, 200, <<"[]">>} = request(get, uri(["bridges"]), []), ok end), LocalTopic = <<?EGRESS_LOCAL_TOPIC, "/1">>, RemoteTopic = <<?EGRESS_REMOTE_TOPIC, "/", LocalTopic/binary>>, Payload0 = <<"hello">>, emqx:subscribe(RemoteTopic), ?wait_async_action( PUBLISH a message to the ' local ' broker , as we have only one broker , emqx:publish(emqx_message:make(LocalTopic, Payload0)), #{?snk_kind := buffer_worker_flush_ack} ), assert_mqtt_msg_received(RemoteTopic, Payload0), ?assertMetrics( #{<<"matched">> := 1, <<"success">> := 1, <<"failed">> := 0}, BridgeIDEgress ), stop the listener 1883 to make the bridge disconnected ok = emqx_listeners:stop_listener('tcp:default'), ct:sleep(1500), PUBLISH 2 messages to the ' local ' broker , the messages should {ok, SRef} = snabbkaffe:subscribe( fun (#{?snk_kind := buffer_worker_retry_inflight_failed}) -> true; (#{?snk_kind := buffer_worker_flush_nack}) -> true; (_) -> false end, _NEvents = 2, _Timeout = 1_000 ), Payload1 = <<"hello2">>, Payload2 = <<"hello3">>, spawn(fun() -> emqx:publish(emqx_message:make(LocalTopic, Payload1)) end), spawn(fun() -> emqx:publish(emqx_message:make(LocalTopic, Payload2)) end), {ok, _} = snabbkaffe:receive_events(SRef), ?assertMatch( #{<<"status">> := Status} when Status == <<"connecting">> orelse Status == <<"disconnected">>, request_bridge(BridgeIDEgress) ), matched > = 3 because of possible retries . ?assertMetrics( #{ <<"matched">> := Matched, <<"success">> := 1, <<"failed">> := 0, <<"queuing">> := Queuing, <<"inflight">> := Inflight }, Matched >= 3 andalso Inflight + Queuing == 2, BridgeIDEgress ), start the listener 1883 to make the bridge reconnected ok = emqx_listeners:start_listener('tcp:default'), timer:sleep(1500), verify the metrics of the bridge , the 2 queued messages should have been sent ?assertMatch(#{<<"status">> := <<"connected">>}, request_bridge(BridgeIDEgress)), matched > = 3 because of possible retries . ?assertMetrics( #{ <<"matched">> := Matched, <<"success">> := 3, <<"failed">> := 0, <<"queuing">> := 0, <<"retried">> := _ }, Matched >= 3, BridgeIDEgress ), also verify the 2 messages have been sent to the remote broker assert_mqtt_msg_received(RemoteTopic, Payload1), assert_mqtt_msg_received(RemoteTopic, Payload2), ok. t_mqtt_conn_bridge_egress_async_reconnect(_) -> User1 = <<"user1">>, BridgeIDEgress = create_bridge( ?SERVER_CONF(User1)#{ <<"type">> => ?TYPE_MQTT, <<"name">> => ?BRIDGE_NAME_EGRESS, <<"egress">> => ?EGRESS_CONF, <<"resource_opts">> => #{ <<"worker_pool_size">> => 2, <<"query_mode">> => <<"async">>, <<"request_timeout">> => <<"15s">>, <<"health_check_interval">> => <<"0.5s">>, <<"auto_restart_interval">> => <<"1s">> } } ), on_exit(fun() -> {ok, 204, <<>>} = request(delete, uri(["bridges", BridgeIDEgress]), []), {ok, 200, <<"[]">>} = request(get, uri(["bridges"]), []), ok end), Self = self(), LocalTopic = <<?EGRESS_LOCAL_TOPIC, "/1">>, RemoteTopic = <<?EGRESS_REMOTE_TOPIC, "/", LocalTopic/binary>>, emqx:subscribe(RemoteTopic), Publisher = start_publisher(LocalTopic, 200, Self), ct:sleep(1000), stop the listener 1883 to make the bridge disconnected ok = emqx_listeners:stop_listener('tcp:default'), ct:sleep(1500), ?assertMatch( #{<<"status">> := Status} when Status == <<"connecting">> orelse Status == <<"disconnected">>, request_bridge(BridgeIDEgress) ), start the listener 1883 to make the bridge reconnected ok = emqx_listeners:start_listener('tcp:default'), timer:sleep(1500), ?assertMatch( #{<<"status">> := <<"connected">>}, request_bridge(BridgeIDEgress) ), N = stop_publisher(Publisher), [ assert_mqtt_msg_received(RemoteTopic, Payload) || I <- lists:seq(1, N), Payload <- [integer_to_binary(I)] ], ok. start_publisher(Topic, Interval, CtrlPid) -> spawn_link(fun() -> publisher(Topic, 1, Interval, CtrlPid) end). stop_publisher(Pid) -> _ = Pid ! {self(), stop}, receive {Pid, N} -> N after 1_000 -> ct:fail("publisher ~p did not stop", [Pid]) end. publisher(Topic, N, Delay, CtrlPid) -> _ = emqx:publish(emqx_message:make(Topic, integer_to_binary(N))), receive {CtrlPid, stop} -> CtrlPid ! {self(), N} after Delay -> publisher(Topic, N + 1, Delay, CtrlPid) end. assert_mqtt_msg_received(Topic) -> assert_mqtt_msg_received(Topic, '_', 200). assert_mqtt_msg_received(Topic, Payload) -> assert_mqtt_msg_received(Topic, Payload, 200). assert_mqtt_msg_received(Topic, Payload, Timeout) -> receive {deliver, Topic, Msg = #message{}} when Payload == '_' -> ct:pal("received mqtt ~p on topic ~p", [Msg, Topic]), Msg; {deliver, Topic, Msg = #message{payload = Payload}} -> ct:pal("received mqtt ~p on topic ~p", [Msg, Topic]), Msg after Timeout -> {messages, Messages} = process_info(self(), messages), ct:fail("timeout waiting ~p ms for ~p on topic '~s', messages = ~0p", [ Timeout, Payload, Topic, Messages ]) end. create_bridge(Config = #{<<"type">> := Type, <<"name">> := Name}) -> {ok, 201, Bridge} = request( post, uri(["bridges"]), Config ), ?assertMatch( #{ <<"type">> := Type, <<"name">> := Name }, jsx:decode(Bridge) ), emqx_bridge_resource:bridge_id(Type, Name). request_bridge(BridgeID) -> {ok, 200, Bridge} = request(get, uri(["bridges", BridgeID]), []), jsx:decode(Bridge). request_bridge_metrics(BridgeID) -> {ok, 200, BridgeMetrics} = request(get, uri(["bridges", BridgeID, "metrics"]), []), jsx:decode(BridgeMetrics). request(Method, Url, Body) -> request(<<"connector_admin">>, Method, Url, Body).
d4c85e9b7f4b424fe316be21e9cb3e2aa7a0cbd3fc31122272ec98d8a6b21020
rtoy/ansi-cl-tests
adjustable-array-p.lsp
;-*- Mode: Lisp -*- Author : Created : Mon Jan 20 21:25:22 2003 ;;;; Contains: Tests for ADJUSTABLE-ARRAY-P (in-package :cl-test) (deftest adjustable-array-p.1 (notnot (adjustable-array-p (make-array '(5) :adjustable t))) t) (deftest adjustable-array-p.2 (notnot (adjustable-array-p (make-array nil :adjustable t))) t) (deftest adjustable-array-p.3 (notnot (adjustable-array-p (make-array '(2 3) :adjustable t))) t) (deftest adjustable-array-p.4 (notnot (adjustable-array-p (make-array '(2 2 2) :adjustable t))) t) (deftest adjustable-array-p.5 (notnot (adjustable-array-p (make-array '(2 2 2 2) :adjustable t))) t) (deftest adjustable-array-p.6 (macrolet ((%m (z) z)) (let ((a (make-array '(5) :adjustable t))) (notnot (adjustable-array-p (expand-in-current-env (%m a)))))) t) (deftest adjustable-array-p.order.1 (let ((i 0) x) (values (notnot (adjustable-array-p (progn (setf x (incf i)) (make-array '(5) :adjustable t)))) i x)) t 1 1) ;;; Error tests (deftest adjustable-array-p.error.1 (signals-error (adjustable-array-p) program-error) t) (deftest adjustable-array-p.error.2 (signals-error (adjustable-array-p "aaa" nil) program-error) t) (deftest adjustable-array-p.error.3 (signals-type-error x 10 (adjustable-array-p x)) t) (deftest adjustable-array-p.error.4 (check-type-error #'adjustable-array-p #'arrayp) nil) (deftest adjustable-array-p.error.5 (signals-error (locally (adjustable-array-p 10)) type-error) t) (deftest adjustable-array-p.error.6 (signals-error (let ((x 10)) (locally (declare (optimize (safety 3))) (adjustable-array-p x))) type-error) t)
null
https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/adjustable-array-p.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests for ADJUSTABLE-ARRAY-P Error tests
Author : Created : Mon Jan 20 21:25:22 2003 (in-package :cl-test) (deftest adjustable-array-p.1 (notnot (adjustable-array-p (make-array '(5) :adjustable t))) t) (deftest adjustable-array-p.2 (notnot (adjustable-array-p (make-array nil :adjustable t))) t) (deftest adjustable-array-p.3 (notnot (adjustable-array-p (make-array '(2 3) :adjustable t))) t) (deftest adjustable-array-p.4 (notnot (adjustable-array-p (make-array '(2 2 2) :adjustable t))) t) (deftest adjustable-array-p.5 (notnot (adjustable-array-p (make-array '(2 2 2 2) :adjustable t))) t) (deftest adjustable-array-p.6 (macrolet ((%m (z) z)) (let ((a (make-array '(5) :adjustable t))) (notnot (adjustable-array-p (expand-in-current-env (%m a)))))) t) (deftest adjustable-array-p.order.1 (let ((i 0) x) (values (notnot (adjustable-array-p (progn (setf x (incf i)) (make-array '(5) :adjustable t)))) i x)) t 1 1) (deftest adjustable-array-p.error.1 (signals-error (adjustable-array-p) program-error) t) (deftest adjustable-array-p.error.2 (signals-error (adjustable-array-p "aaa" nil) program-error) t) (deftest adjustable-array-p.error.3 (signals-type-error x 10 (adjustable-array-p x)) t) (deftest adjustable-array-p.error.4 (check-type-error #'adjustable-array-p #'arrayp) nil) (deftest adjustable-array-p.error.5 (signals-error (locally (adjustable-array-p 10)) type-error) t) (deftest adjustable-array-p.error.6 (signals-error (let ((x 10)) (locally (declare (optimize (safety 3))) (adjustable-array-p x))) type-error) t)
f439306a35b97dce870fda3b04e550a020b90ca26503c34726436da964edf6c5
janestreet/hardcaml
test_bits_intf.ml
(** Test routines for the various vector calculations in [Bits.Comb] **) open! Import (** Test function called to check a result and provide an error message. In expect tests, this is a thin wrapper around [Expect_test_helpers_core.require]. In long-running regression tests in ../regression, this prints to a log. *) module type Require = sig val require : Source_code_position.t -> bool -> error_message:Sexp.t Lazy.t -> unit end module type Test_ = sig type config * [ test ] tests each primitive in [ config.prims ] [ config.iterations ] times , stopping iteration for a particular primitive at the first error if [ stop_on_first_primitive_error ] . iteration for a particular primitive at the first error if [stop_on_first_primitive_error]. *) val test : ?stop_on_first_primitive_error:bool (** default is [true] *) -> Source_code_position.t -> config -> unit end module type Test_bits = sig (** The following are operations from [Comb.Primitives]. The full [Comb.S] signature is derived from these primitives. *) module Primitive_op : sig type t = | Add | Sub | Mulu | Muls | And | Or | Xor | Not | Eq | Lt | Sel | Mux | Cat [@@deriving enumerate, sexp_of] val name : t -> string val arg_type : t Command.Arg_type.t end * One constructor per ( tested ) module in [ Bits . Comb ] with an associated test name . module Bits_module : sig type t = | Bits_list | Bool_list | X_list | Bits * Special module which breaks a few primtives by inverting the result . Used to test the test - framework itself . test the test-framework itself. *) | BadPrimitives [@@deriving sexp_of, enumerate] val arg_type : t Command.Arg_type.t val module_ : t -> (module Comb.S) val name : t -> string val short_name : t -> string end module Config : sig type t = { bits1 : Bits_module.t ; bits2 : Bits_module.t ; prims : Primitive_op.t list ; iterations : int ; min_bit_width : int ; max_bit_width : int } [@@deriving sexp_of] end module type Require = Require module type Test = Test_ with type config := Config.t module Make (R : Require) : Test module Test : Test end
null
https://raw.githubusercontent.com/janestreet/hardcaml/15727795c2bf922dd852cc0cd895a4ed1d9527e5/test/lib/test_bits_intf.ml
ocaml
* Test routines for the various vector calculations in [Bits.Comb] * * Test function called to check a result and provide an error message. In expect tests, this is a thin wrapper around [Expect_test_helpers_core.require]. In long-running regression tests in ../regression, this prints to a log. * default is [true] * The following are operations from [Comb.Primitives]. The full [Comb.S] signature is derived from these primitives.
open! Import module type Require = sig val require : Source_code_position.t -> bool -> error_message:Sexp.t Lazy.t -> unit end module type Test_ = sig type config * [ test ] tests each primitive in [ config.prims ] [ config.iterations ] times , stopping iteration for a particular primitive at the first error if [ stop_on_first_primitive_error ] . iteration for a particular primitive at the first error if [stop_on_first_primitive_error]. *) val test -> Source_code_position.t -> config -> unit end module type Test_bits = sig module Primitive_op : sig type t = | Add | Sub | Mulu | Muls | And | Or | Xor | Not | Eq | Lt | Sel | Mux | Cat [@@deriving enumerate, sexp_of] val name : t -> string val arg_type : t Command.Arg_type.t end * One constructor per ( tested ) module in [ Bits . Comb ] with an associated test name . module Bits_module : sig type t = | Bits_list | Bool_list | X_list | Bits * Special module which breaks a few primtives by inverting the result . Used to test the test - framework itself . test the test-framework itself. *) | BadPrimitives [@@deriving sexp_of, enumerate] val arg_type : t Command.Arg_type.t val module_ : t -> (module Comb.S) val name : t -> string val short_name : t -> string end module Config : sig type t = { bits1 : Bits_module.t ; bits2 : Bits_module.t ; prims : Primitive_op.t list ; iterations : int ; min_bit_width : int ; max_bit_width : int } [@@deriving sexp_of] end module type Require = Require module type Test = Test_ with type config := Config.t module Make (R : Require) : Test module Test : Test end
1a059905685773b93f2962096260f909edb515b8c001dd971a75b3e754b039f6
facundoolano/advenjure
verbs.cljc
(ns advenjure.verbs #?(:cljs (:require-macros [cljs.core.async.macros :refer [go]])) (:require [clojure.set] [clojure.string :as str] #?(:cljs [goog.string :as gstring]) #?(:clj [clojure.core.async :refer [<! go]] :cljs [cljs.core.async :refer [<!]]) [advenjure.utils :refer [say say-inline find-item direction-mappings current-room remove-item replace-item capfirst directions direction-names get-visible-room]] [advenjure.change-rooms :refer [change-rooms]] [advenjure.hooks :refer [execute eval-precondition eval-postcondition eval-direction eval-direction-sync]] [advenjure.items :refer [print-list describe-container iname all-items]] [advenjure.rooms :as rooms] [advenjure.gettext.core :refer [_ p_]] [advenjure.ui.input :as in] [advenjure.ui.output :as out] [advenjure.dialogs :as dialogs] #?(:cljs [goog.string :refer [format]]) #?(:cljs [advenjure.eval :refer [eval]]))) ;;;; FUNCTIONS TO BUILD VERBS (defn- noop "Does nothing except optionally saying something, the item specific behavior is defined in the item spec." [kw] (fn [gs item & etc] (if-let [speech (get-in item [kw :say])] (say gs speech)))) (defn- ask-ambiguous [item-name items] (let [first-different (fn [spec] (first (filter #(not= % item-name) (:names spec)))) names (map first-different items) names (map #(str "the " %) names) first-names (clojure.string/join ", " (butlast names))] (str "Which " item-name "? " (capfirst first-names) " or " (last names) "?"))) TODO move to a separate ns (def re-escape #?(:clj str/re-quote-replacement :cljs gstring/regExpEscape)) (defn- exclude-string [exclude] (re-escape (if (not-empty exclude) (format "(?!%s$)" (str/join "|" exclude)) ""))) (defn- fill-implicit-item "convert `talk to` to `talk to $`" [command] (cond (not (str/includes? command "$")) (str command " $") (and (str/includes? command "$1") (not (str/includes? command "$2"))) (str command " $2") (and (str/includes? command "$2") (not (str/includes? command "$1"))) (str command " $1") :else command)) (defn- expand-missing-item "convert `talk to $` to [`talk to` `talk to $`]" [command] (cond (str/ends-with? command "$") [command (str/replace command #" \$$" "")] (str/ends-with? command "$1") [command (str/replace command #" \$1$" "")] (str/ends-with? command "$2") [command (str/replace command #" \$2$" "")] :else [command])) (defn- expand-item-placeholders "Translate user friendly placeholders to proper regex groups." [command exclude] (let [exclude (exclude-string exclude)] (-> command (str/replace #"\$1" (str exclude "(?<item1>.*)")) (str/replace #"\$2" (str exclude "(?<item2>.*)")) (str/replace #"\$" (str exclude "(?<item>.*)"))))) (defn- expand-item-commands "applies all the above to the command array" [commands exclude] (->> commands (map str/trim) (map fill-implicit-item) (mapcat expand-missing-item) (map #(expand-item-placeholders % exclude)))) (defn make-item-verb "Takes the verb name, the kw to look up at the item at the handler function, wraps the function with the common logic such as trying to find the item, executing pre/post conditions, etc." [{:keys [commands kw display kw-required handler ignore-item] :or {kw-required true display (first commands) handler (noop kw)} :as spec}] (assoc spec :commands (expand-item-commands commands ignore-item) :handler (fn ([game-state] (say game-state (_ "%s what?" display))) ([game-state item-name] (let [[item :as items] (find-item game-state item-name) conditions (kw item)] (cond (empty? items) (say game-state (_ "I didn't see that.")) (> (count items) 1) (say game-state (ask-ambiguous item-name items)) :else TODO factor out the following ? (go (let [value (<! (eval-precondition conditions game-state))] (cond (string? value) (say game-state value) (false? value) (say game-state (_ "I couldn't %s that." display)) (and kw-required (nil? value)) (say game-state (_ "I couldn't %s that." display)) :else (let [before-state (-> (assoc game-state :__prevalue value) (execute :before-item-handler kw item)) handler-state (handler before-state item) TODO refactor this once before state is dropped post-state (eval-postcondition conditions before-state handler-state)] (execute post-state :after-item-handler kw item))))))))))) (defn make-compound-item-verb "The same as above but adapted to compund verbs." [{:keys [commands kw display kw-required handler ignore-item] :or {kw-required true display (first commands) handler (noop kw)} :as spec}] (assoc spec :commands (expand-item-commands commands ignore-item) :handler (fn ([game-state] (say game-state (_ "%s what?" display))) ([game-state item1] (say game-state (_ "%s %s with what?" display item1))) ([game-state item1-name item2-name] (let [[item1 :as items1] (find-item game-state item1-name) [item2 :as items2] (find-item game-state item2-name) conditions (kw item1)] (cond (or (empty? items1) (empty? items2)) (say game-state (_ "I didn't see that.")) (> (count items1) 1) (say game-state (ask-ambiguous item1-name items1)) (> (count items2) 1) (say game-state (ask-ambiguous item2-name items2)) :else (go (let [value (<! (eval-precondition conditions game-state item2))] (cond (string? value) (say game-state value) (false? value) (say game-state (_ "I couldn't %s that." display)) (and kw-required (nil? value)) (say game-state (_ "I couldn't %s that." display)) :else (let [before-state (-> (assoc game-state :__prevalue value) (execute :before-item-handler kw item1 item2)) handler-state (handler before-state item1 item2) TODO refactor this once old state is dropped post-state (eval-postcondition conditions before-state handler-state)] (execute post-state :after-item-handler kw item1 item2))))))))))) (defn expand-direction-commands [commands exclude] (->> (expand-item-commands commands exclude) (map #(str/replace % #"<item" "<dir")))) (defn make-direction-verb [{:keys [commands ignore-dir handler display] :or {display (first commands)} :as spec}] (assoc spec :commands (expand-direction-commands commands ignore-dir) :handler (fn ([game-state] (say game-state (_ "% where?" display))) ([game-state direction] (handler game-state direction))))) (defn make-movement-item-verb "Constructs verbs that use items to change rooms." [{:keys [kw] :as spec}] (make-item-verb (assoc spec :handler (fn [game-state item] ;; hackishly getting __prevalue so we can get the room kw from the precondition (println "GOING TO " (:__prevalue game-state)) (change-rooms game-state (:__prevalue game-state)))))) (defn make-say-verb [spec] (assoc spec :handler (fn [gs] (say gs (:say spec))))) ;;; VERB HANDLER DEFINITIONS (defn- go-handler [game-state direction] (let [current (current-room game-state)] (if-let [dir (get direction-mappings direction)] (go (let [dir-value (<! (eval-direction game-state dir))] (cond (string? dir-value) (say game-state dir-value) (not dir-value) (say game-state (or (:default-go current) (_ "Couldn't go in that direction."))) :else (let [new-state (change-rooms game-state dir-value)] (eval-postcondition (dir current) game-state new-state))))) ;; it's not a direction name, maybe it's a room name (if-let [roomkw (get-visible-room game-state direction)] (change-rooms game-state roomkw) (say game-state "Go where?"))))) (defn- look-to-handler [game-state direction] (if-let [dir (get direction-mappings direction)] (let [dir-value (eval-direction-sync game-state dir) dir-room (get-in game-state [:room-map dir-value])] (cond (string? dir-value) (say game-state (_ "That direction was blocked.")) (not dir-value) (say game-state (_ "There was nothing in that direction.")) (or (:known dir-room) (:visited dir-room)) (say game-state (_ "The %s was in that direction." (:name dir-room))) :else (say game-state (_ "I didn't know what was in that direction.")))) ;; it's not a direction name, maybe it's a room name (if-let [roomkw (get-visible-room game-state direction)] (let [room-name (get-in game-state [:room-map roomkw :name]) ;; this feels kinda ugly: dir-kw (roomkw (clojure.set/map-invert (current-room game-state))) dir-name (dir-kw direction-names)] (say game-state (_ "The %s was toward %s." room-name dir-name))) (say game-state (_ "Look to where?"))))) (defn- go-back-handler [game-state] (if-let [roomkw (:previous-room game-state)] (if (rooms/connection-dir (current-room game-state) roomkw) (change-rooms game-state roomkw) (say game-state (_ "Where would back be?"))) (say game-state (_ "Where would back be?")))) (defn- look-handler [game-state] (as-> game-state game-state (say game-state (str (rooms/describe (current-room game-state)))) (say game-state " ") (reduce (fn [gs dirkw] (let [dir-value (eval-direction-sync game-state dirkw) dir-name (dirkw direction-names) dir-room (get-in game-state [:room-map dir-value])] (if dir-value (let [prefix (str dir-name ": ")] (cond (string? dir-value) (say gs (str prefix (_ "blocked."))) (or (:visited dir-room) (:known dir-room)) (say gs (str prefix (:name dir-room) ".")) :else (say gs (str prefix "???")))) gs))) game-state directions))) (defn- inventory-handler [game-state] (if (empty? (:inventory game-state)) (say game-state (_ "I wasn't carrying anything.")) (say game-state (str (_ "I was carrying:") (print-list (:inventory game-state)))))) (defn- save-handler [game-state] (out/write-file "saved.game" (dissoc game-state :configuration)) (say game-state (_ "Done."))) (defn- restore-handler [game-state] (go (try (let [loaded-state (<! (in/read-file "saved.game")) saved-state (assoc loaded-state :configuration (:configuration game-state))] (say saved-state (rooms/describe (current-room saved-state)))) (catch #?(:clj java.io.FileNotFoundException :cljs js/Object) e (say game-state (_ "No saved game found.")))))) (defn- exit-handler [game-state] (say game-state (_ "Bye!")) (in/exit)) (defn- look-at-handler [game-state item] (say game-state (:description item))) (defn- look-inside-handler [game-state item] (if-let [custom-say (get-in item [:look-in :say])] (say game-state custom-say) (if (:items item) (say game-state (describe-container item)) (say game-state (_ "I couldn't look inside a %s." (iname item)))))) (defn- take-handler "Try to take an item from the current room or from a container object in the inventory." [game-state item] (if (contains? (:inventory game-state) item) (say game-state (_ "I already had that.")) (-> game-state (say (get-in item [:take :say] (_ "Taken."))) (remove-item item) (update :inventory conj item)))) need to declare it first because take - all calls it (def take_ (make-item-verb {:commands [(_ "take") (_ "get") (_ "pick up") (_ "pick $ up")] :ignore-item [(_ "all") (_ "everything")] :help (_ "Attempt to take the given item.") :kw :take :handler take-handler})) (defn- take-all-handler "Go through every item in the room that defines a value for :take, and attempt to take it." [game-state] (let [items (all-items (:items (current-room game-state))) takeable (remove (comp nil? :take) items) item-names (map #(first (:names %)) takeable) do-take (:handler take_)] (if (empty? item-names) (say game-state (_ "I saw nothing worth taking.")) (reduce (fn [gs-chan iname] (go (let [gs (<! gs-chan) gs (say-inline gs (str iname ": ")) new-state (<! (do-take gs iname))] (or new-state gs)))) (go game-state) item-names)))) (defn- open-handler [game-state item] (cond (not (:closed item)) (say game-state (p_ item "It was already open.")) (:locked item) (say game-state (p_ item "It was locked.")) :else (let [open-item (assoc item :closed false) custom-say (get-in item [:open :say]) new-state (cond custom-say (say game-state custom-say) (:items open-item) (say game-state (describe-container open-item)) :else (say game-state (_ "Opened.")))] (replace-item new-state item open-item)))) (defn- close-handler [game-state item] (if (:closed item) (say game-state (p_ item "It was already closed.")) (let [closed-item (assoc item :closed true)] (-> game-state (say (get-in item [:close :say] (_ "Closed."))) (replace-item item closed-item))))) (defn- unlock-handler [game-state locked key-item] (cond (not (:locked locked)) (say game-state (p_ locked "It wasn't locked.")) (not= locked (:unlocks key-item)) (say game-state (_ "That didn't work.")) :else (let [unlocked (assoc locked :locked false)] (-> game-state (say (get-in locked [:unlock :say] (_ "Unlocked."))) (replace-item locked unlocked))))) (defn- open-with-handler [game-state closed key-item] (cond (not (:closed closed)) (say game-state (p_ closed "It was already open.")) (or (and (:locked closed) (= closed (:unlocks key-item))) (= closed (:opens key-item))) (let [opened (merge closed {:locked false :closed false})] (-> game-state (say (get-in closed [:open-with :say] (_ "Opened."))) (replace-item closed opened))) :else (say game-state (_ "That didn't work.")))) (defn- talk-handler [game-state item] (dialogs/run (:dialog item) game-state)) (declare verbs) FIXME rewrite to autogenerate from verb map help ;; (def help (make-say-verb (clojure.string/join "\n " [(_ "You're playing a text adventure game. You control the character by entering commands. Some available commands are:") ( _ " GO < direction > : move in the given compass direction . For example : \"GO NORTH\ " . " and \"N\ " will work too . " ) ;; (_ "TAKE <item>: add an item to your inventory.") ( _ " : list your inventory contents . \"I\ " will work too . " ) ;; (_ "LOOK: look around.") ;; (_ "LOOK AT <item>: look at some specific item.") ;; (_ "LOOK IN <item>: look inside some container item.") ;; (_ "TALK TO <character>: start a conversation with another character.") ;; (_ "UNLOCK <item> WITH <item>: unlock some item using another one. For example: UNLOCK door WITH key.") ( _ " OPEN , CLOSE , READ , TURN ON , PUT IN , EAT , DRINK , KILL , etc . may work on some objects , just try . " ) ;; (_ "SAVE: save your current progress.") ;; (_ "RESTORE: restore a previously saved game.") ( _ " EXIT : close the game . " ) ( _ " You can use the TAB key to get completion suggestions for a command and the UP / DOWN arrows to search the command history . " ) ] ) ) ) ;;;; VERB DEFINITIONS (defn- make-go-shortcuts "Allow commands like 'north' and 'n' instead of 'go north'" [] (map (fn [dir] {:commands [dir] :handler #(go-handler % dir)}) (keys direction-mappings))) (def verbs (concat (make-go-shortcuts) [(make-direction-verb {:commands [(_ "go") (_ "go to")] :help (_ "Change the location according to the given direction.") :ignore-dir ["back"] :handler go-handler}) (make-direction-verb {:commands [(_ "look to") (_ "look toward")] :help (_ "Describe what's in the given direction.") :handler look-to-handler}) {:commands [(_ "go back") (_ "back") (_ "b")] :help (_ "Go to the previous room, if possible.") :handler go-back-handler} {:commands [(_ "look") (_ "look around") (_ "l")] :help (_ "Look around and enumerate available movement directions.") :handler look-handler} {:commands [(_ "inventory") (_ "i")] :help (_ "Describe the inventory contents.") :handler inventory-handler} {:commands [(_ "save")] :help (_ "Save the current game to a file.") :handler save-handler} {:commands [(_ "restore") (_ "load")] :help (_ "Restore a previous game from file.") :handler restore-handler} {:commands [(_ "exit")] :help (_ "Close the game.") :handler exit-handler} (make-item-verb {:commands [(_ "look at") (_ "describe")] :help (_ "Look at a given item.") :kw :look-at :kw-required false :handler look-at-handler}) (make-item-verb {:commands [(_ "look inside") (_ "look in")] :help (_ "Look inside a given item.") :kw :look-in :kw-required false :handler look-inside-handler}) take_ {:commands [(_ "take all") (_ "take everything") (_ "get all") (_ "get everything")] :help (_ "Attempt to take every visible object.") :handler take-all-handler} (make-item-verb {:commands [(_ "open")] :help (_ "Try to open a closed item.") :kw :open :handler open-handler}) (make-item-verb {:commands [(_ "close")] :help (_ "Try to close an open item.") :kw :close :handler close-handler}) (make-compound-item-verb {:commands [(_ "unlock") (_ "unlock $1 with $2")] :display (_ "unlock") :help (_ "Try to unlock an item.") :kw :unlock :handler unlock-handler}) (make-compound-item-verb {:commands [(_ "open $1 with $2")] :display (_ "open") :help (_ "Try to unlock and open a locked item.") :kw :open-with :kw-required false :handler open-with-handler}) (make-item-verb {:commands [(_ "talk to") (_ "talk with") (_ "talk")] :help (_ "Talk to a given character or item.") :kw :talk :handler talk-handler}) ;; noop verbs (make-item-verb {:commands [(_ "read")] :kw :read}) (make-item-verb {:commands [(_ "use")] :kw :use}) (make-compound-item-verb {:commands [(_ "use $1 with $2")] :kw :use-with}) (make-item-verb {:commands [(_ "move")] :kw :move}) (make-item-verb {:commands [(_ "push")] :kw :push}) (make-item-verb {:commands [(_ "pull")] :kw :pull}) (make-say-verb {:commands [(_ "stand") (_ "stand up") (_ "get up")] :say (_ "I was standing up already")}) (make-movement-item-verb {:commands [(_ "climb")] :kw :climb}) (make-movement-item-verb {:commands [(_ "climb down") (_ "climb $ down")] :kw :climb-down}) (make-movement-item-verb {:commands [(_ "climb up") (_ "climb $ up")] :kw :climb-up}) (make-movement-item-verb {:commands [(_ "enter")] :kw :enter}) ]))
null
https://raw.githubusercontent.com/facundoolano/advenjure/2f05fdae9439ab8830753cc5ef378be66b7db6ef/src/advenjure/verbs.cljc
clojure
FUNCTIONS TO BUILD VERBS hackishly getting __prevalue so we can get the room kw from the precondition VERB HANDLER DEFINITIONS it's not a direction name, maybe it's a room name it's not a direction name, maybe it's a room name this feels kinda ugly: (def help (make-say-verb (clojure.string/join "\n " [(_ "You're playing a text adventure game. You control the character by entering commands. Some available commands are:") (_ "TAKE <item>: add an item to your inventory.") (_ "LOOK: look around.") (_ "LOOK AT <item>: look at some specific item.") (_ "LOOK IN <item>: look inside some container item.") (_ "TALK TO <character>: start a conversation with another character.") (_ "UNLOCK <item> WITH <item>: unlock some item using another one. For example: UNLOCK door WITH key.") (_ "SAVE: save your current progress.") (_ "RESTORE: restore a previously saved game.") VERB DEFINITIONS noop verbs
(ns advenjure.verbs #?(:cljs (:require-macros [cljs.core.async.macros :refer [go]])) (:require [clojure.set] [clojure.string :as str] #?(:cljs [goog.string :as gstring]) #?(:clj [clojure.core.async :refer [<! go]] :cljs [cljs.core.async :refer [<!]]) [advenjure.utils :refer [say say-inline find-item direction-mappings current-room remove-item replace-item capfirst directions direction-names get-visible-room]] [advenjure.change-rooms :refer [change-rooms]] [advenjure.hooks :refer [execute eval-precondition eval-postcondition eval-direction eval-direction-sync]] [advenjure.items :refer [print-list describe-container iname all-items]] [advenjure.rooms :as rooms] [advenjure.gettext.core :refer [_ p_]] [advenjure.ui.input :as in] [advenjure.ui.output :as out] [advenjure.dialogs :as dialogs] #?(:cljs [goog.string :refer [format]]) #?(:cljs [advenjure.eval :refer [eval]]))) (defn- noop "Does nothing except optionally saying something, the item specific behavior is defined in the item spec." [kw] (fn [gs item & etc] (if-let [speech (get-in item [kw :say])] (say gs speech)))) (defn- ask-ambiguous [item-name items] (let [first-different (fn [spec] (first (filter #(not= % item-name) (:names spec)))) names (map first-different items) names (map #(str "the " %) names) first-names (clojure.string/join ", " (butlast names))] (str "Which " item-name "? " (capfirst first-names) " or " (last names) "?"))) TODO move to a separate ns (def re-escape #?(:clj str/re-quote-replacement :cljs gstring/regExpEscape)) (defn- exclude-string [exclude] (re-escape (if (not-empty exclude) (format "(?!%s$)" (str/join "|" exclude)) ""))) (defn- fill-implicit-item "convert `talk to` to `talk to $`" [command] (cond (not (str/includes? command "$")) (str command " $") (and (str/includes? command "$1") (not (str/includes? command "$2"))) (str command " $2") (and (str/includes? command "$2") (not (str/includes? command "$1"))) (str command " $1") :else command)) (defn- expand-missing-item "convert `talk to $` to [`talk to` `talk to $`]" [command] (cond (str/ends-with? command "$") [command (str/replace command #" \$$" "")] (str/ends-with? command "$1") [command (str/replace command #" \$1$" "")] (str/ends-with? command "$2") [command (str/replace command #" \$2$" "")] :else [command])) (defn- expand-item-placeholders "Translate user friendly placeholders to proper regex groups." [command exclude] (let [exclude (exclude-string exclude)] (-> command (str/replace #"\$1" (str exclude "(?<item1>.*)")) (str/replace #"\$2" (str exclude "(?<item2>.*)")) (str/replace #"\$" (str exclude "(?<item>.*)"))))) (defn- expand-item-commands "applies all the above to the command array" [commands exclude] (->> commands (map str/trim) (map fill-implicit-item) (mapcat expand-missing-item) (map #(expand-item-placeholders % exclude)))) (defn make-item-verb "Takes the verb name, the kw to look up at the item at the handler function, wraps the function with the common logic such as trying to find the item, executing pre/post conditions, etc." [{:keys [commands kw display kw-required handler ignore-item] :or {kw-required true display (first commands) handler (noop kw)} :as spec}] (assoc spec :commands (expand-item-commands commands ignore-item) :handler (fn ([game-state] (say game-state (_ "%s what?" display))) ([game-state item-name] (let [[item :as items] (find-item game-state item-name) conditions (kw item)] (cond (empty? items) (say game-state (_ "I didn't see that.")) (> (count items) 1) (say game-state (ask-ambiguous item-name items)) :else TODO factor out the following ? (go (let [value (<! (eval-precondition conditions game-state))] (cond (string? value) (say game-state value) (false? value) (say game-state (_ "I couldn't %s that." display)) (and kw-required (nil? value)) (say game-state (_ "I couldn't %s that." display)) :else (let [before-state (-> (assoc game-state :__prevalue value) (execute :before-item-handler kw item)) handler-state (handler before-state item) TODO refactor this once before state is dropped post-state (eval-postcondition conditions before-state handler-state)] (execute post-state :after-item-handler kw item))))))))))) (defn make-compound-item-verb "The same as above but adapted to compund verbs." [{:keys [commands kw display kw-required handler ignore-item] :or {kw-required true display (first commands) handler (noop kw)} :as spec}] (assoc spec :commands (expand-item-commands commands ignore-item) :handler (fn ([game-state] (say game-state (_ "%s what?" display))) ([game-state item1] (say game-state (_ "%s %s with what?" display item1))) ([game-state item1-name item2-name] (let [[item1 :as items1] (find-item game-state item1-name) [item2 :as items2] (find-item game-state item2-name) conditions (kw item1)] (cond (or (empty? items1) (empty? items2)) (say game-state (_ "I didn't see that.")) (> (count items1) 1) (say game-state (ask-ambiguous item1-name items1)) (> (count items2) 1) (say game-state (ask-ambiguous item2-name items2)) :else (go (let [value (<! (eval-precondition conditions game-state item2))] (cond (string? value) (say game-state value) (false? value) (say game-state (_ "I couldn't %s that." display)) (and kw-required (nil? value)) (say game-state (_ "I couldn't %s that." display)) :else (let [before-state (-> (assoc game-state :__prevalue value) (execute :before-item-handler kw item1 item2)) handler-state (handler before-state item1 item2) TODO refactor this once old state is dropped post-state (eval-postcondition conditions before-state handler-state)] (execute post-state :after-item-handler kw item1 item2))))))))))) (defn expand-direction-commands [commands exclude] (->> (expand-item-commands commands exclude) (map #(str/replace % #"<item" "<dir")))) (defn make-direction-verb [{:keys [commands ignore-dir handler display] :or {display (first commands)} :as spec}] (assoc spec :commands (expand-direction-commands commands ignore-dir) :handler (fn ([game-state] (say game-state (_ "% where?" display))) ([game-state direction] (handler game-state direction))))) (defn make-movement-item-verb "Constructs verbs that use items to change rooms." [{:keys [kw] :as spec}] (make-item-verb (assoc spec :handler (fn [game-state item] (println "GOING TO " (:__prevalue game-state)) (change-rooms game-state (:__prevalue game-state)))))) (defn make-say-verb [spec] (assoc spec :handler (fn [gs] (say gs (:say spec))))) (defn- go-handler [game-state direction] (let [current (current-room game-state)] (if-let [dir (get direction-mappings direction)] (go (let [dir-value (<! (eval-direction game-state dir))] (cond (string? dir-value) (say game-state dir-value) (not dir-value) (say game-state (or (:default-go current) (_ "Couldn't go in that direction."))) :else (let [new-state (change-rooms game-state dir-value)] (eval-postcondition (dir current) game-state new-state))))) (if-let [roomkw (get-visible-room game-state direction)] (change-rooms game-state roomkw) (say game-state "Go where?"))))) (defn- look-to-handler [game-state direction] (if-let [dir (get direction-mappings direction)] (let [dir-value (eval-direction-sync game-state dir) dir-room (get-in game-state [:room-map dir-value])] (cond (string? dir-value) (say game-state (_ "That direction was blocked.")) (not dir-value) (say game-state (_ "There was nothing in that direction.")) (or (:known dir-room) (:visited dir-room)) (say game-state (_ "The %s was in that direction." (:name dir-room))) :else (say game-state (_ "I didn't know what was in that direction.")))) (if-let [roomkw (get-visible-room game-state direction)] (let [room-name (get-in game-state [:room-map roomkw :name]) dir-kw (roomkw (clojure.set/map-invert (current-room game-state))) dir-name (dir-kw direction-names)] (say game-state (_ "The %s was toward %s." room-name dir-name))) (say game-state (_ "Look to where?"))))) (defn- go-back-handler [game-state] (if-let [roomkw (:previous-room game-state)] (if (rooms/connection-dir (current-room game-state) roomkw) (change-rooms game-state roomkw) (say game-state (_ "Where would back be?"))) (say game-state (_ "Where would back be?")))) (defn- look-handler [game-state] (as-> game-state game-state (say game-state (str (rooms/describe (current-room game-state)))) (say game-state " ") (reduce (fn [gs dirkw] (let [dir-value (eval-direction-sync game-state dirkw) dir-name (dirkw direction-names) dir-room (get-in game-state [:room-map dir-value])] (if dir-value (let [prefix (str dir-name ": ")] (cond (string? dir-value) (say gs (str prefix (_ "blocked."))) (or (:visited dir-room) (:known dir-room)) (say gs (str prefix (:name dir-room) ".")) :else (say gs (str prefix "???")))) gs))) game-state directions))) (defn- inventory-handler [game-state] (if (empty? (:inventory game-state)) (say game-state (_ "I wasn't carrying anything.")) (say game-state (str (_ "I was carrying:") (print-list (:inventory game-state)))))) (defn- save-handler [game-state] (out/write-file "saved.game" (dissoc game-state :configuration)) (say game-state (_ "Done."))) (defn- restore-handler [game-state] (go (try (let [loaded-state (<! (in/read-file "saved.game")) saved-state (assoc loaded-state :configuration (:configuration game-state))] (say saved-state (rooms/describe (current-room saved-state)))) (catch #?(:clj java.io.FileNotFoundException :cljs js/Object) e (say game-state (_ "No saved game found.")))))) (defn- exit-handler [game-state] (say game-state (_ "Bye!")) (in/exit)) (defn- look-at-handler [game-state item] (say game-state (:description item))) (defn- look-inside-handler [game-state item] (if-let [custom-say (get-in item [:look-in :say])] (say game-state custom-say) (if (:items item) (say game-state (describe-container item)) (say game-state (_ "I couldn't look inside a %s." (iname item)))))) (defn- take-handler "Try to take an item from the current room or from a container object in the inventory." [game-state item] (if (contains? (:inventory game-state) item) (say game-state (_ "I already had that.")) (-> game-state (say (get-in item [:take :say] (_ "Taken."))) (remove-item item) (update :inventory conj item)))) need to declare it first because take - all calls it (def take_ (make-item-verb {:commands [(_ "take") (_ "get") (_ "pick up") (_ "pick $ up")] :ignore-item [(_ "all") (_ "everything")] :help (_ "Attempt to take the given item.") :kw :take :handler take-handler})) (defn- take-all-handler "Go through every item in the room that defines a value for :take, and attempt to take it." [game-state] (let [items (all-items (:items (current-room game-state))) takeable (remove (comp nil? :take) items) item-names (map #(first (:names %)) takeable) do-take (:handler take_)] (if (empty? item-names) (say game-state (_ "I saw nothing worth taking.")) (reduce (fn [gs-chan iname] (go (let [gs (<! gs-chan) gs (say-inline gs (str iname ": ")) new-state (<! (do-take gs iname))] (or new-state gs)))) (go game-state) item-names)))) (defn- open-handler [game-state item] (cond (not (:closed item)) (say game-state (p_ item "It was already open.")) (:locked item) (say game-state (p_ item "It was locked.")) :else (let [open-item (assoc item :closed false) custom-say (get-in item [:open :say]) new-state (cond custom-say (say game-state custom-say) (:items open-item) (say game-state (describe-container open-item)) :else (say game-state (_ "Opened.")))] (replace-item new-state item open-item)))) (defn- close-handler [game-state item] (if (:closed item) (say game-state (p_ item "It was already closed.")) (let [closed-item (assoc item :closed true)] (-> game-state (say (get-in item [:close :say] (_ "Closed."))) (replace-item item closed-item))))) (defn- unlock-handler [game-state locked key-item] (cond (not (:locked locked)) (say game-state (p_ locked "It wasn't locked.")) (not= locked (:unlocks key-item)) (say game-state (_ "That didn't work.")) :else (let [unlocked (assoc locked :locked false)] (-> game-state (say (get-in locked [:unlock :say] (_ "Unlocked."))) (replace-item locked unlocked))))) (defn- open-with-handler [game-state closed key-item] (cond (not (:closed closed)) (say game-state (p_ closed "It was already open.")) (or (and (:locked closed) (= closed (:unlocks key-item))) (= closed (:opens key-item))) (let [opened (merge closed {:locked false :closed false})] (-> game-state (say (get-in closed [:open-with :say] (_ "Opened."))) (replace-item closed opened))) :else (say game-state (_ "That didn't work.")))) (defn- talk-handler [game-state item] (dialogs/run (:dialog item) game-state)) (declare verbs) FIXME rewrite to autogenerate from verb map help ( _ " GO < direction > : move in the given compass direction . For example : \"GO NORTH\ " . " and \"N\ " will work too . " ) ( _ " : list your inventory contents . \"I\ " will work too . " ) ( _ " OPEN , CLOSE , READ , TURN ON , PUT IN , EAT , DRINK , KILL , etc . may work on some objects , just try . " ) ( _ " EXIT : close the game . " ) ( _ " You can use the TAB key to get completion suggestions for a command and the UP / DOWN arrows to search the command history . " ) ] ) ) ) (defn- make-go-shortcuts "Allow commands like 'north' and 'n' instead of 'go north'" [] (map (fn [dir] {:commands [dir] :handler #(go-handler % dir)}) (keys direction-mappings))) (def verbs (concat (make-go-shortcuts) [(make-direction-verb {:commands [(_ "go") (_ "go to")] :help (_ "Change the location according to the given direction.") :ignore-dir ["back"] :handler go-handler}) (make-direction-verb {:commands [(_ "look to") (_ "look toward")] :help (_ "Describe what's in the given direction.") :handler look-to-handler}) {:commands [(_ "go back") (_ "back") (_ "b")] :help (_ "Go to the previous room, if possible.") :handler go-back-handler} {:commands [(_ "look") (_ "look around") (_ "l")] :help (_ "Look around and enumerate available movement directions.") :handler look-handler} {:commands [(_ "inventory") (_ "i")] :help (_ "Describe the inventory contents.") :handler inventory-handler} {:commands [(_ "save")] :help (_ "Save the current game to a file.") :handler save-handler} {:commands [(_ "restore") (_ "load")] :help (_ "Restore a previous game from file.") :handler restore-handler} {:commands [(_ "exit")] :help (_ "Close the game.") :handler exit-handler} (make-item-verb {:commands [(_ "look at") (_ "describe")] :help (_ "Look at a given item.") :kw :look-at :kw-required false :handler look-at-handler}) (make-item-verb {:commands [(_ "look inside") (_ "look in")] :help (_ "Look inside a given item.") :kw :look-in :kw-required false :handler look-inside-handler}) take_ {:commands [(_ "take all") (_ "take everything") (_ "get all") (_ "get everything")] :help (_ "Attempt to take every visible object.") :handler take-all-handler} (make-item-verb {:commands [(_ "open")] :help (_ "Try to open a closed item.") :kw :open :handler open-handler}) (make-item-verb {:commands [(_ "close")] :help (_ "Try to close an open item.") :kw :close :handler close-handler}) (make-compound-item-verb {:commands [(_ "unlock") (_ "unlock $1 with $2")] :display (_ "unlock") :help (_ "Try to unlock an item.") :kw :unlock :handler unlock-handler}) (make-compound-item-verb {:commands [(_ "open $1 with $2")] :display (_ "open") :help (_ "Try to unlock and open a locked item.") :kw :open-with :kw-required false :handler open-with-handler}) (make-item-verb {:commands [(_ "talk to") (_ "talk with") (_ "talk")] :help (_ "Talk to a given character or item.") :kw :talk :handler talk-handler}) (make-item-verb {:commands [(_ "read")] :kw :read}) (make-item-verb {:commands [(_ "use")] :kw :use}) (make-compound-item-verb {:commands [(_ "use $1 with $2")] :kw :use-with}) (make-item-verb {:commands [(_ "move")] :kw :move}) (make-item-verb {:commands [(_ "push")] :kw :push}) (make-item-verb {:commands [(_ "pull")] :kw :pull}) (make-say-verb {:commands [(_ "stand") (_ "stand up") (_ "get up")] :say (_ "I was standing up already")}) (make-movement-item-verb {:commands [(_ "climb")] :kw :climb}) (make-movement-item-verb {:commands [(_ "climb down") (_ "climb $ down")] :kw :climb-down}) (make-movement-item-verb {:commands [(_ "climb up") (_ "climb $ up")] :kw :climb-up}) (make-movement-item-verb {:commands [(_ "enter")] :kw :enter}) ]))
7e5c1f7f45e1ba49dbe07ca936fbdca6fae7ab1885bd9dfedc7937be535e3526
cac-t-u-s/om-sharp
preferences-window.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ File author : ;============================================================================ ;========================================================================= ; PREFERENCES WINDOW ;========================================================================= (in-package :om) ;;;=========================================================================== DIFFERENT TYPEs OF PReFERENCE ITEMS ;;; TODO : try to use the same code here and in the inspector window ;;; general case = text box (defmethod make-preference-item (type pref-item) (let* ((curr-value (pref-item-value pref-item)) (font (om-def-font :normal))) (om-make-view 'click-and-edit-text :text (format nil " ~A" curr-value) :resizable :w :bg-color (om-def-color :white) :border nil :size (om-make-point (om-string-size (format nil " ~A " curr-value) font) 20) :font font :after-fun #'(lambda (item) (setf (pref-item-value pref-item) (text item)) (maybe-apply-pref-item-after-fun pref-item) )))) (defmethod make-preference-item ((type (eql :list)) pref-item) (let* ((curr-value (pref-item-value pref-item)) (font (om-def-font :normal))) (om-make-view 'click-and-edit-text :text (format nil " ~{~A ~}" curr-value) :resizable :w :bg-color (om-def-color :white) :border nil :size (om-make-point 40 20) :font font :after-fun #'(lambda (item) (let ((val (om-read-list-from-string (text item)))) (if (listp val) (progn (setf (pref-item-value pref-item) val) (setf (text item) (format nil " ~{~A ~}" val)) (maybe-apply-pref-item-after-fun pref-item)) (progn (om-beep-msg "Preference value for '~A' must be a list !" (pref-item-name pref-item)) (setf (text item) (format nil " ~{~A~}" curr-value)) ))) )))) (defmethod make-preference-item ((type (eql :bool)) pref-item) (om-make-di 'om-check-box :checked-p (pref-item-value pref-item) :text "" ;:resizable :w :size (om-make-point 20 18) :font (om-def-font :gui) :di-action #'(lambda (item) (setf (pref-item-value pref-item) (om-checked-p item)) (maybe-apply-pref-item-after-fun pref-item) ))) (defmethod make-preference-item ((type (eql :folder)) pref-item) (let* ((font (om-def-font :normal)) (curr-value (maybe-eval-pref-item-value pref-item)) (str (if curr-value (format nil "~A" curr-value) "")) (textview (om-make-view 'click-and-edit-text :text str :resizable :w :bg-color (om-def-color :white) ;:fg-color (if (probe-file curr-value) (om-def-color :black) (om-def-color :red)) :border nil :size (omp (+ 20 (om-string-size str font)) 20) :font font :after-fun #'(lambda (item) (let ((val (if (equal (text item) "") nil (text item)))) (setf (pref-item-value pref-item) val) (maybe-apply-pref-item-after-fun pref-item))) ))) (om-make-layout 'om-row-layout :resizable :w :subviews (list textview (om-make-view 'om-view :size (omp 20 18) :resizable nil :subviews (list (om-make-graphic-object 'om-icon-button :size (omp 20 18) :position (omp 0 0) :icon :folder-button :icon-pushed :folder-button-pushed :action #'(lambda (button) (declare (ignore button)) (let ((dir (om-choose-directory-dialog :directory *last-open-dir*))) (when dir (setf *last-open-dir* dir) (setf (pref-item-value pref-item) (namestring dir)) (setf (text textview) (pref-item-value pref-item)) (maybe-apply-pref-item-after-fun pref-item) (om-invalidate-view textview) )))) )))) )) (defmethod make-preference-item ((type (eql :file)) pref-item) (let* ((curr-value (maybe-eval-pref-item-value pref-item)) (font (om-def-font :normal)) (textview (om-make-view 'click-and-edit-text :text (format nil "~A" curr-value) :resizable :w :bg-color (om-def-color :white) :fg-color (if (probe-file curr-value) (om-def-color :black) (om-def-color :red)) :border nil :size (omp (om-string-size (format nil " ~A " curr-value) font) 20) :font font :after-fun #'(lambda (item) (setf (pref-item-value pref-item) (pathname (text item))) (maybe-apply-pref-item-after-fun pref-item) (om-set-fg-color item (if (probe-file (pref-item-value pref-item)) (om-def-color :black) (om-def-color :red)))) ))) (om-make-layout 'om-row-layout :resizable :w :subviews (list textview (om-make-view 'om-view :size (omp 20 18) :resizable nil :subviews (list (om-make-graphic-object 'om-icon-button :size (omp 20 18) :position (omp 0 0) :icon :folder-button :icon-pushed :folder-button-pushed :action #'(lambda (button) (declare (ignore button)) (let ((file (om-choose-file-dialog :directory (om-make-pathname :directory (pref-item-value pref-item))))) (when file (setf (pref-item-value pref-item) file) (setf (text textview) (namestring (pref-item-value pref-item))) (maybe-apply-pref-item-after-fun pref-item) (om-set-fg-color textview (if (probe-file (pref-item-value pref-item)) (om-def-color :black) (om-def-color :red))) (om-invalidate-view textview) )))) )))) )) (defmethod make-preference-item ((type list) pref-item) (let ((font (om-def-font :gui))) (om-make-di 'om-popup-list :items type :resizable :w :value (pref-item-value pref-item) :size (om-make-point (+ 36 (reduce #'max (or (mapcar #'(lambda (item) (om-string-size (format nil "~A" item) font)) type) '(20)))) 22) :font font :di-action #'(lambda (item) (setf (pref-item-value pref-item) (om-get-selected-item item)) (maybe-apply-pref-item-after-fun pref-item) )) )) (defmethod make-preference-item ((type number-in-range) pref-item) (let ((y 18)) (om-make-view 'om-view :size (omp 80 y) :resizable nil :subviews (list (om-make-graphic-object 'numbox :position (omp 0 0) :value (pref-item-value pref-item) :bg-color (om-def-color :white) :border t :size (om-make-point 40 y) :font (om-def-font :normal) :decimals (or (number-in-range-decimals type) 0) :min-val (or (number-in-range-min type) 0) :max-val (or (number-in-range-max type) 10000) :after-fun #'(lambda (item) (setf (pref-item-value pref-item) (value item)) (maybe-apply-pref-item-after-fun pref-item) )) )))) (defmethod make-preference-item ((type (eql :number)) pref-item) (make-preference-item (make-number-in-range :min -1000 :max 1000) pref-item)) (defmethod make-preference-item ((type (eql :font)) pref-item) (flet ((font-to-str (font) (if (om-font-p font) (format nil " ~A ~Dpt ~A" (om-font-face font) (round (om-font-size font)) (if (om-font-style font) (format nil "[~{~S~^ ~}]" (om-font-style font)) "")) "-"))) (let ((font (om-def-font :gui))) (om-make-di 'om-button :resizable :w :focus nil :default nil :text (font-to-str (pref-item-value pref-item)) :size (om-make-point (om-string-size (font-to-str (pref-item-value pref-item)) font) #-linux 26 #+linux 20) :font font :di-action #'(lambda (item) (let ((choice (om-choose-font-dialog :font (pref-item-value pref-item)))) (when choice (om-set-dialog-item-text item (font-to-str choice)) (setf (pref-item-value pref-item) choice) (maybe-apply-pref-item-after-fun pref-item))))) ))) (defmethod make-preference-item ((type (eql :color)) pref-item) (om-make-view 'color-view :size (om-make-point 50 16) :with-alpha nil :resizable :w :color (pref-item-value pref-item) :after-fun #'(lambda (item) (setf (pref-item-value pref-item) (color item)) (maybe-apply-pref-item-after-fun pref-item)))) (defmethod make-preference-item ((type (eql :color-a)) pref-item) (om-make-view 'color-view :size (om-make-point 50 16) :with-alpha t :resizable :w :color (pref-item-value pref-item) :after-fun #'(lambda (item) (setf (pref-item-value pref-item) (color item)) (maybe-apply-pref-item-after-fun pref-item)))) (defmethod make-preference-item ((type (eql :action)) pref-item) (let ((buttonstr "Open") (font (om-def-font :gui))) (om-make-di 'om-button :resizable :w :focus nil :default nil :text buttonstr :size (om-make-point (om-string-size buttonstr font) 26) :font font :di-action #'(lambda (item) (declare (ignore item)) (funcall (pref-item-defval pref-item)))))) ;;;=========================================================================== THE VIEW OF ONE PREFERENCE (defmethod make-preference-item ((type (eql :title)) pref-item) (om-make-di 'om-simple-text :size (om-make-point 20 30) :text "" :focus t)) (defun make-preference-view (pref-item) (let* ((font (om-def-font :gui)) (g-item (make-preference-item (pref-item-type pref-item) pref-item)) (doc-text (when (pref-item-doc pref-item) (let* ((real-text (if (listp (pref-item-doc pref-item)) (reduce #'(lambda (s1 s2) (concatenate 'string s1 (string #\Newline) s2)) (pref-item-doc pref-item)) (pref-item-doc pref-item))) (line-w (+ (loop for line in (list! (pref-item-doc pref-item)) maximize (om-string-size line font)) 30)) (line-h (cadr (multiple-value-list (om-string-size real-text font))))) (om-make-di 'om-simple-text :text real-text :font font :size (om-make-point line-w (+ (if (equal (pref-item-type pref-item) :title) 10 2) (* (1+ line-h) (length (list! (pref-item-doc pref-item))))))) )))) (if (equal (pref-item-type pref-item) :title) (let ((title (om-make-di 'om-simple-text :text (pref-item-name pref-item) :font (om-def-font :gui-title) :size (om-make-point 200 16)))) (om-make-layout 'om-column-layout :name (pref-item-id pref-item) :subviews (cons (om-make-layout 'om-row-layout :align :bottom :subviews (list title g-item)) (list! doc-text)))) (let* ((main-text (om-make-di 'om-simple-text :text (pref-item-name pref-item) :font (om-def-font :gui) :size (om-make-point 180 14)))) (om-make-layout 'om-row-layout :name (pref-item-id pref-item) :align :center :subviews (list main-text g-item doc-text)) ) ))) ;;;=========================================================================== THE TAB VIEW OF ONE MODULE (defclass preference-pane (om-column-layout) ((module-id :accessor module-id :initarg :module-id :initform nil))) (defun make-preference-panel (pref-module) (order-preference-module pref-module) (om-make-layout 'preference-pane #+windows :bg-color #+windows (om-make-color .95 .95 .95) :name (pref-module-name pref-module) :module-id (pref-module-id pref-module) :subviews (cons (om-make-di 'om-simple-text :size (omp nil 10)) (loop for pref in (pref-module-items pref-module) when (pref-item-visible pref) collect (make-preference-view pref))) ) ) ;;;=========================================================================== ;;; PREFERENCES WINDOW ; (om-select-window (make-preferences-window)) (defclass preferences-window (om-window) ((tabs :accessor tabs :initform nil))) (defmethod om-window-close-event ((self preferences-window)) (save-preferences) (call-next-method)) (defun make-preferences-window () (let ((win (om-make-window 'preferences-window :title "Preferences and Settings" :menu-items (om-menu-items nil) :size (om-make-point 800 nil) ;:resizable :w ))) (setf (tabs win) (om-make-layout 'om-tab-layout :subviews (mapcar #'make-preference-panel (sort-pref-items *user-preferences*)))) (om-add-subviews win (om-make-layout 'om-column-layout :ratios '(100 1) :subviews (list (tabs win) (om-make-layout 'om-row-layout :subviews (list nil (om-make-di 'om-button :text "Restore defaults" :size (om-make-point 120 24) :di-action #'(lambda (item) (declare (ignore item)) (let* ((current-panel (om-get-current-view (tabs win))) (module-id (module-id current-panel)) (pref-module (find-pref-module module-id))) (restore-default-preferences module-id) (om-remove-all-subviews current-panel) (apply 'om-add-subviews (cons current-panel (loop for pref in (pref-module-items pref-module) when (pref-item-visible pref) collect (make-preference-view pref)))) )) )))) )) win)) (defun find-preferences-window () (car (om-get-all-windows 'preferences-window))) ;;;; CALLED FROM THE MENU (defun show-preferences-win () (let ((win (find-preferences-window))) (if win (om-select-window win) (om-open-window (make-preferences-window))))) ;;;; CALLED FROM ADD_PREFERENCES (defmethod update-preferences-window () (let ((win (find-preferences-window))) (when win (let ((layout (car (om-subviews win))) (current-panel-id (module-id (om-get-current-view (tabs win))))) (om-substitute-subviews layout (tabs win) (setf (tabs win) (om-make-layout 'om-tab-layout :subviews (mapcar #'make-preference-panel (sort-pref-items *user-preferences*))) )) (om-set-current-view (tabs win) (find current-panel-id (om-subviews (tabs win)) :key 'module-id)) )))) (defmethod update-preference-window-module (module) (let ((win (find-preferences-window))) (when win (let ((panel (find module (om-subviews (tabs win)) :key 'module-id))) (when panel (let ((current-panel-id (module-id (om-get-current-view (tabs win)))) (newpanel (make-preference-panel (find-pref-module module)))) (om-substitute-subviews (tabs win) panel newpanel) (om-set-current-view (tabs win) (find current-panel-id (om-subviews (tabs win)) :key 'module-id)) )))))) (defmethod update-preference-window-item (module item) (let ((win (find-preferences-window))) (when win (let ((panel (find module (om-subviews (tabs win)) :key 'module-id))) (when panel (let ((layout (find item (om-subviews panel) :key 'om-get-name))) (when layout (om-substitute-subviews panel layout (make-preference-view (get-pref module item))) ))))))) ; (add-preference :libraries :auto-load "Auto load" :bool nil "Silently loads required libraries")
null
https://raw.githubusercontent.com/cac-t-u-s/om-sharp/80f9537368471d0e6e4accdc9fff01ed277b879e/src/visual-language/windows/preferences-window.lisp
lisp
============================================================================ om#: visual programming language for computer-assisted music composition ============================================================================ This program is free software. For information on usage and redistribution, see the "LICENSE" file in this distribution. 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. ============================================================================ ============================================================================ ========================================================================= PREFERENCES WINDOW ========================================================================= =========================================================================== TODO : try to use the same code here and in the inspector window general case = text box :resizable :w :fg-color (if (probe-file curr-value) (om-def-color :black) (om-def-color :red)) =========================================================================== =========================================================================== =========================================================================== PREFERENCES WINDOW (om-select-window (make-preferences-window)) :resizable :w CALLED FROM THE MENU CALLED FROM ADD_PREFERENCES (add-preference :libraries :auto-load "Auto load" :bool nil "Silently loads required libraries")
File author : (in-package :om) DIFFERENT TYPEs OF PReFERENCE ITEMS (defmethod make-preference-item (type pref-item) (let* ((curr-value (pref-item-value pref-item)) (font (om-def-font :normal))) (om-make-view 'click-and-edit-text :text (format nil " ~A" curr-value) :resizable :w :bg-color (om-def-color :white) :border nil :size (om-make-point (om-string-size (format nil " ~A " curr-value) font) 20) :font font :after-fun #'(lambda (item) (setf (pref-item-value pref-item) (text item)) (maybe-apply-pref-item-after-fun pref-item) )))) (defmethod make-preference-item ((type (eql :list)) pref-item) (let* ((curr-value (pref-item-value pref-item)) (font (om-def-font :normal))) (om-make-view 'click-and-edit-text :text (format nil " ~{~A ~}" curr-value) :resizable :w :bg-color (om-def-color :white) :border nil :size (om-make-point 40 20) :font font :after-fun #'(lambda (item) (let ((val (om-read-list-from-string (text item)))) (if (listp val) (progn (setf (pref-item-value pref-item) val) (setf (text item) (format nil " ~{~A ~}" val)) (maybe-apply-pref-item-after-fun pref-item)) (progn (om-beep-msg "Preference value for '~A' must be a list !" (pref-item-name pref-item)) (setf (text item) (format nil " ~{~A~}" curr-value)) ))) )))) (defmethod make-preference-item ((type (eql :bool)) pref-item) (om-make-di 'om-check-box :checked-p (pref-item-value pref-item) :text "" :size (om-make-point 20 18) :font (om-def-font :gui) :di-action #'(lambda (item) (setf (pref-item-value pref-item) (om-checked-p item)) (maybe-apply-pref-item-after-fun pref-item) ))) (defmethod make-preference-item ((type (eql :folder)) pref-item) (let* ((font (om-def-font :normal)) (curr-value (maybe-eval-pref-item-value pref-item)) (str (if curr-value (format nil "~A" curr-value) "")) (textview (om-make-view 'click-and-edit-text :text str :resizable :w :bg-color (om-def-color :white) :border nil :size (omp (+ 20 (om-string-size str font)) 20) :font font :after-fun #'(lambda (item) (let ((val (if (equal (text item) "") nil (text item)))) (setf (pref-item-value pref-item) val) (maybe-apply-pref-item-after-fun pref-item))) ))) (om-make-layout 'om-row-layout :resizable :w :subviews (list textview (om-make-view 'om-view :size (omp 20 18) :resizable nil :subviews (list (om-make-graphic-object 'om-icon-button :size (omp 20 18) :position (omp 0 0) :icon :folder-button :icon-pushed :folder-button-pushed :action #'(lambda (button) (declare (ignore button)) (let ((dir (om-choose-directory-dialog :directory *last-open-dir*))) (when dir (setf *last-open-dir* dir) (setf (pref-item-value pref-item) (namestring dir)) (setf (text textview) (pref-item-value pref-item)) (maybe-apply-pref-item-after-fun pref-item) (om-invalidate-view textview) )))) )))) )) (defmethod make-preference-item ((type (eql :file)) pref-item) (let* ((curr-value (maybe-eval-pref-item-value pref-item)) (font (om-def-font :normal)) (textview (om-make-view 'click-and-edit-text :text (format nil "~A" curr-value) :resizable :w :bg-color (om-def-color :white) :fg-color (if (probe-file curr-value) (om-def-color :black) (om-def-color :red)) :border nil :size (omp (om-string-size (format nil " ~A " curr-value) font) 20) :font font :after-fun #'(lambda (item) (setf (pref-item-value pref-item) (pathname (text item))) (maybe-apply-pref-item-after-fun pref-item) (om-set-fg-color item (if (probe-file (pref-item-value pref-item)) (om-def-color :black) (om-def-color :red)))) ))) (om-make-layout 'om-row-layout :resizable :w :subviews (list textview (om-make-view 'om-view :size (omp 20 18) :resizable nil :subviews (list (om-make-graphic-object 'om-icon-button :size (omp 20 18) :position (omp 0 0) :icon :folder-button :icon-pushed :folder-button-pushed :action #'(lambda (button) (declare (ignore button)) (let ((file (om-choose-file-dialog :directory (om-make-pathname :directory (pref-item-value pref-item))))) (when file (setf (pref-item-value pref-item) file) (setf (text textview) (namestring (pref-item-value pref-item))) (maybe-apply-pref-item-after-fun pref-item) (om-set-fg-color textview (if (probe-file (pref-item-value pref-item)) (om-def-color :black) (om-def-color :red))) (om-invalidate-view textview) )))) )))) )) (defmethod make-preference-item ((type list) pref-item) (let ((font (om-def-font :gui))) (om-make-di 'om-popup-list :items type :resizable :w :value (pref-item-value pref-item) :size (om-make-point (+ 36 (reduce #'max (or (mapcar #'(lambda (item) (om-string-size (format nil "~A" item) font)) type) '(20)))) 22) :font font :di-action #'(lambda (item) (setf (pref-item-value pref-item) (om-get-selected-item item)) (maybe-apply-pref-item-after-fun pref-item) )) )) (defmethod make-preference-item ((type number-in-range) pref-item) (let ((y 18)) (om-make-view 'om-view :size (omp 80 y) :resizable nil :subviews (list (om-make-graphic-object 'numbox :position (omp 0 0) :value (pref-item-value pref-item) :bg-color (om-def-color :white) :border t :size (om-make-point 40 y) :font (om-def-font :normal) :decimals (or (number-in-range-decimals type) 0) :min-val (or (number-in-range-min type) 0) :max-val (or (number-in-range-max type) 10000) :after-fun #'(lambda (item) (setf (pref-item-value pref-item) (value item)) (maybe-apply-pref-item-after-fun pref-item) )) )))) (defmethod make-preference-item ((type (eql :number)) pref-item) (make-preference-item (make-number-in-range :min -1000 :max 1000) pref-item)) (defmethod make-preference-item ((type (eql :font)) pref-item) (flet ((font-to-str (font) (if (om-font-p font) (format nil " ~A ~Dpt ~A" (om-font-face font) (round (om-font-size font)) (if (om-font-style font) (format nil "[~{~S~^ ~}]" (om-font-style font)) "")) "-"))) (let ((font (om-def-font :gui))) (om-make-di 'om-button :resizable :w :focus nil :default nil :text (font-to-str (pref-item-value pref-item)) :size (om-make-point (om-string-size (font-to-str (pref-item-value pref-item)) font) #-linux 26 #+linux 20) :font font :di-action #'(lambda (item) (let ((choice (om-choose-font-dialog :font (pref-item-value pref-item)))) (when choice (om-set-dialog-item-text item (font-to-str choice)) (setf (pref-item-value pref-item) choice) (maybe-apply-pref-item-after-fun pref-item))))) ))) (defmethod make-preference-item ((type (eql :color)) pref-item) (om-make-view 'color-view :size (om-make-point 50 16) :with-alpha nil :resizable :w :color (pref-item-value pref-item) :after-fun #'(lambda (item) (setf (pref-item-value pref-item) (color item)) (maybe-apply-pref-item-after-fun pref-item)))) (defmethod make-preference-item ((type (eql :color-a)) pref-item) (om-make-view 'color-view :size (om-make-point 50 16) :with-alpha t :resizable :w :color (pref-item-value pref-item) :after-fun #'(lambda (item) (setf (pref-item-value pref-item) (color item)) (maybe-apply-pref-item-after-fun pref-item)))) (defmethod make-preference-item ((type (eql :action)) pref-item) (let ((buttonstr "Open") (font (om-def-font :gui))) (om-make-di 'om-button :resizable :w :focus nil :default nil :text buttonstr :size (om-make-point (om-string-size buttonstr font) 26) :font font :di-action #'(lambda (item) (declare (ignore item)) (funcall (pref-item-defval pref-item)))))) THE VIEW OF ONE PREFERENCE (defmethod make-preference-item ((type (eql :title)) pref-item) (om-make-di 'om-simple-text :size (om-make-point 20 30) :text "" :focus t)) (defun make-preference-view (pref-item) (let* ((font (om-def-font :gui)) (g-item (make-preference-item (pref-item-type pref-item) pref-item)) (doc-text (when (pref-item-doc pref-item) (let* ((real-text (if (listp (pref-item-doc pref-item)) (reduce #'(lambda (s1 s2) (concatenate 'string s1 (string #\Newline) s2)) (pref-item-doc pref-item)) (pref-item-doc pref-item))) (line-w (+ (loop for line in (list! (pref-item-doc pref-item)) maximize (om-string-size line font)) 30)) (line-h (cadr (multiple-value-list (om-string-size real-text font))))) (om-make-di 'om-simple-text :text real-text :font font :size (om-make-point line-w (+ (if (equal (pref-item-type pref-item) :title) 10 2) (* (1+ line-h) (length (list! (pref-item-doc pref-item))))))) )))) (if (equal (pref-item-type pref-item) :title) (let ((title (om-make-di 'om-simple-text :text (pref-item-name pref-item) :font (om-def-font :gui-title) :size (om-make-point 200 16)))) (om-make-layout 'om-column-layout :name (pref-item-id pref-item) :subviews (cons (om-make-layout 'om-row-layout :align :bottom :subviews (list title g-item)) (list! doc-text)))) (let* ((main-text (om-make-di 'om-simple-text :text (pref-item-name pref-item) :font (om-def-font :gui) :size (om-make-point 180 14)))) (om-make-layout 'om-row-layout :name (pref-item-id pref-item) :align :center :subviews (list main-text g-item doc-text)) ) ))) THE TAB VIEW OF ONE MODULE (defclass preference-pane (om-column-layout) ((module-id :accessor module-id :initarg :module-id :initform nil))) (defun make-preference-panel (pref-module) (order-preference-module pref-module) (om-make-layout 'preference-pane #+windows :bg-color #+windows (om-make-color .95 .95 .95) :name (pref-module-name pref-module) :module-id (pref-module-id pref-module) :subviews (cons (om-make-di 'om-simple-text :size (omp nil 10)) (loop for pref in (pref-module-items pref-module) when (pref-item-visible pref) collect (make-preference-view pref))) ) ) (defclass preferences-window (om-window) ((tabs :accessor tabs :initform nil))) (defmethod om-window-close-event ((self preferences-window)) (save-preferences) (call-next-method)) (defun make-preferences-window () (let ((win (om-make-window 'preferences-window :title "Preferences and Settings" :menu-items (om-menu-items nil) :size (om-make-point 800 nil) ))) (setf (tabs win) (om-make-layout 'om-tab-layout :subviews (mapcar #'make-preference-panel (sort-pref-items *user-preferences*)))) (om-add-subviews win (om-make-layout 'om-column-layout :ratios '(100 1) :subviews (list (tabs win) (om-make-layout 'om-row-layout :subviews (list nil (om-make-di 'om-button :text "Restore defaults" :size (om-make-point 120 24) :di-action #'(lambda (item) (declare (ignore item)) (let* ((current-panel (om-get-current-view (tabs win))) (module-id (module-id current-panel)) (pref-module (find-pref-module module-id))) (restore-default-preferences module-id) (om-remove-all-subviews current-panel) (apply 'om-add-subviews (cons current-panel (loop for pref in (pref-module-items pref-module) when (pref-item-visible pref) collect (make-preference-view pref)))) )) )))) )) win)) (defun find-preferences-window () (car (om-get-all-windows 'preferences-window))) (defun show-preferences-win () (let ((win (find-preferences-window))) (if win (om-select-window win) (om-open-window (make-preferences-window))))) (defmethod update-preferences-window () (let ((win (find-preferences-window))) (when win (let ((layout (car (om-subviews win))) (current-panel-id (module-id (om-get-current-view (tabs win))))) (om-substitute-subviews layout (tabs win) (setf (tabs win) (om-make-layout 'om-tab-layout :subviews (mapcar #'make-preference-panel (sort-pref-items *user-preferences*))) )) (om-set-current-view (tabs win) (find current-panel-id (om-subviews (tabs win)) :key 'module-id)) )))) (defmethod update-preference-window-module (module) (let ((win (find-preferences-window))) (when win (let ((panel (find module (om-subviews (tabs win)) :key 'module-id))) (when panel (let ((current-panel-id (module-id (om-get-current-view (tabs win)))) (newpanel (make-preference-panel (find-pref-module module)))) (om-substitute-subviews (tabs win) panel newpanel) (om-set-current-view (tabs win) (find current-panel-id (om-subviews (tabs win)) :key 'module-id)) )))))) (defmethod update-preference-window-item (module item) (let ((win (find-preferences-window))) (when win (let ((panel (find module (om-subviews (tabs win)) :key 'module-id))) (when panel (let ((layout (find item (om-subviews panel) :key 'om-get-name))) (when layout (om-substitute-subviews panel layout (make-preference-view (get-pref module item))) )))))))
cb9fdc8a25cf2a707d9bb9917224e87d1ec970fb0100e9d28a092a00319e6742
alexanderwasey/stupid-computer
Sum.hs
module Sum where import Prelude hiding (sum) sum :: Num a => [a] -> a sum (x:xs) = x + sum xs sum [] = 0
null
https://raw.githubusercontent.com/alexanderwasey/stupid-computer/a485d2f33a4b8d58128a74b9003b9eadffe42702/examples/Sum.hs
haskell
module Sum where import Prelude hiding (sum) sum :: Num a => [a] -> a sum (x:xs) = x + sum xs sum [] = 0
c1bcb7944d0aa138ad33bc6208eeba946fc41061c6d626b0f28b99efb608518f
GaloisInc/daedalus
Operators.hs
module Daedalus.Interp.Operators where import GHC.Float(double2Float) import Daedalus.PP import Daedalus.Panic(panic) import Daedalus.Value import Daedalus.Interp.Env import Daedalus.Interp.Type import Daedalus.Interp.Error import Daedalus.Type.AST hiding (Value, BDCon(..), BDField(..)) evalLiteral :: Env -> Type -> Literal -> Value evalLiteral env t l = case l of LNumber n _ -> case tval of TVInteger -> VInteger n TVUInt s -> vUInt s n TVSInt s -> partial (vSInt s n) TVFloat -> vFloat (fromIntegral n) TVDouble -> vDouble (fromIntegral n) TVNum {} -> panic "compilePureExpr" ["Kind error"] TVBDStruct {} -> bad TVBDUnion {} -> bad TVArray -> bad TVMap -> bad TVOther -> bad LBool b -> VBool b LByte w _ -> vByte w LBytes bs -> vByteString bs LFloating d -> case tval of TVFloat -> vFloat (double2Float d) TVDouble -> vDouble d TVInteger {} -> bad TVUInt {} -> bad TVSInt {} -> bad TVNum {} -> bad TVArray -> bad TVMap -> bad TVBDStruct {} -> bad TVBDUnion {} -> bad TVOther -> bad LPi -> case tval of TVFloat -> vFloatPi TVDouble -> vDoublePi TVInteger {} -> bad TVUInt {} -> bad TVSInt {} -> bad TVNum {} -> bad TVArray -> bad TVMap -> bad TVBDStruct {} -> bad TVBDUnion {} -> bad TVOther -> bad where bad = panic "evalLiteral" [ "unexpected literal", "Type: " ++ show (pp t) ] tval = evalType env t evalUniOp :: UniOp -> Value -> Value evalUniOp op = case op of Not -> vNot Neg -> partial . vNeg ArrayLength -> vArrayLength Concat -> vArrayConcat BitwiseComplement -> vComplement WordToFloat -> vWordToFloat WordToDouble -> vWordToDouble IsNaN -> vIsNaN IsInfinite -> vIsInfinite IsDenormalized -> vIsDenormalized IsNegativeZero -> vIsNegativeZero BytesOfStream -> vBytesOfStream BuilderBuild -> vFinishBuilder evalBinOp :: BinOp -> Value -> Value -> Value evalBinOp op = case op of Add -> partial2 vAdd Sub -> partial2 vSub Mul -> partial2 vMul Div -> partial2 vDiv Mod -> partial2 vMod Lt -> vLt Leq -> vLeq Eq -> vEq NotEq -> vNeq Cat -> vCat LCat -> partial2 vLCat LShift -> partial2 vShiftL RShift -> partial2 vShiftR BitwiseAnd -> vBitAnd BitwiseOr -> vBitOr BitwiseXor -> vBitXor ArrayStream -> vStreamFromArray LookupMap -> vMapLookup BuilderEmit -> vEmit BuilderEmitArray -> vEmitArray BuilderEmitBuilder -> vEmitBuilder LogicAnd -> panic "evalBinOp" ["LogicAnd"] LogicOr -> panic "evalBinOp" ["LogicOr"] evalTriOp :: TriOp -> Value -> Value -> Value -> Value evalTriOp op = case op of RangeUp -> partial3 vRangeUp RangeDown -> partial3 vRangeDown MapDoInsert -> vMapInsert
null
https://raw.githubusercontent.com/GaloisInc/daedalus/3f180d29441960e35386654ec79a2b205bddc157/src/Daedalus/Interp/Operators.hs
haskell
module Daedalus.Interp.Operators where import GHC.Float(double2Float) import Daedalus.PP import Daedalus.Panic(panic) import Daedalus.Value import Daedalus.Interp.Env import Daedalus.Interp.Type import Daedalus.Interp.Error import Daedalus.Type.AST hiding (Value, BDCon(..), BDField(..)) evalLiteral :: Env -> Type -> Literal -> Value evalLiteral env t l = case l of LNumber n _ -> case tval of TVInteger -> VInteger n TVUInt s -> vUInt s n TVSInt s -> partial (vSInt s n) TVFloat -> vFloat (fromIntegral n) TVDouble -> vDouble (fromIntegral n) TVNum {} -> panic "compilePureExpr" ["Kind error"] TVBDStruct {} -> bad TVBDUnion {} -> bad TVArray -> bad TVMap -> bad TVOther -> bad LBool b -> VBool b LByte w _ -> vByte w LBytes bs -> vByteString bs LFloating d -> case tval of TVFloat -> vFloat (double2Float d) TVDouble -> vDouble d TVInteger {} -> bad TVUInt {} -> bad TVSInt {} -> bad TVNum {} -> bad TVArray -> bad TVMap -> bad TVBDStruct {} -> bad TVBDUnion {} -> bad TVOther -> bad LPi -> case tval of TVFloat -> vFloatPi TVDouble -> vDoublePi TVInteger {} -> bad TVUInt {} -> bad TVSInt {} -> bad TVNum {} -> bad TVArray -> bad TVMap -> bad TVBDStruct {} -> bad TVBDUnion {} -> bad TVOther -> bad where bad = panic "evalLiteral" [ "unexpected literal", "Type: " ++ show (pp t) ] tval = evalType env t evalUniOp :: UniOp -> Value -> Value evalUniOp op = case op of Not -> vNot Neg -> partial . vNeg ArrayLength -> vArrayLength Concat -> vArrayConcat BitwiseComplement -> vComplement WordToFloat -> vWordToFloat WordToDouble -> vWordToDouble IsNaN -> vIsNaN IsInfinite -> vIsInfinite IsDenormalized -> vIsDenormalized IsNegativeZero -> vIsNegativeZero BytesOfStream -> vBytesOfStream BuilderBuild -> vFinishBuilder evalBinOp :: BinOp -> Value -> Value -> Value evalBinOp op = case op of Add -> partial2 vAdd Sub -> partial2 vSub Mul -> partial2 vMul Div -> partial2 vDiv Mod -> partial2 vMod Lt -> vLt Leq -> vLeq Eq -> vEq NotEq -> vNeq Cat -> vCat LCat -> partial2 vLCat LShift -> partial2 vShiftL RShift -> partial2 vShiftR BitwiseAnd -> vBitAnd BitwiseOr -> vBitOr BitwiseXor -> vBitXor ArrayStream -> vStreamFromArray LookupMap -> vMapLookup BuilderEmit -> vEmit BuilderEmitArray -> vEmitArray BuilderEmitBuilder -> vEmitBuilder LogicAnd -> panic "evalBinOp" ["LogicAnd"] LogicOr -> panic "evalBinOp" ["LogicOr"] evalTriOp :: TriOp -> Value -> Value -> Value -> Value evalTriOp op = case op of RangeUp -> partial3 vRangeUp RangeDown -> partial3 vRangeDown MapDoInsert -> vMapInsert
33ac6641b9d51582524c7b3baf9eaa272386dba4da69b66570a3d237f5c32855
erlware/relx
check_undefined_test_sup.erl
%%%------------------------------------------------------------------- %% @doc check_undefined_test top level supervisor. %% @end %%%------------------------------------------------------------------- -module(check_undefined_test_sup). -behaviour(supervisor). -export([start_link/0]). -export([init/1]). -define(SERVER, ?MODULE). start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %% sup_flags() = #{strategy => strategy(), % optional %% intensity => non_neg_integer(), % optional period = > ( ) } % optional %% child_spec() = #{id => child_id(), % mandatory start = > ( ) , % mandatory %% restart => restart(), % optional %% shutdown => shutdown(), % optional %% type => worker(), % optional %% modules => modules()} % optional init([]) -> SupFlags = #{strategy => one_for_all, intensity => 0, period => 1}, ChildSpecs = [], {ok, {SupFlags, ChildSpecs}}. %% internal functions
null
https://raw.githubusercontent.com/erlware/relx/16a7972f7679778d9d7f40228b1a20351f1077bd/shelltests/check_undefined_test/apps/check_undefined_test/src/check_undefined_test_sup.erl
erlang
------------------------------------------------------------------- @doc check_undefined_test top level supervisor. @end ------------------------------------------------------------------- sup_flags() = #{strategy => strategy(), % optional intensity => non_neg_integer(), % optional optional child_spec() = #{id => child_id(), % mandatory mandatory restart => restart(), % optional shutdown => shutdown(), % optional type => worker(), % optional modules => modules()} % optional internal functions
-module(check_undefined_test_sup). -behaviour(supervisor). -export([start_link/0]). -export([init/1]). -define(SERVER, ?MODULE). start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). init([]) -> SupFlags = #{strategy => one_for_all, intensity => 0, period => 1}, ChildSpecs = [], {ok, {SupFlags, ChildSpecs}}.
ab09263acfb1dcd2e70590b5c5c13c2dcae8f728b0f73978f01e930e88517ce7
well-typed/large-records
R040.hs
#if PROFILE_CORESIZE {-# OPTIONS_GHC -ddump-to-file -ddump-simpl #-} #endif #if PROFILE_TIMING {-# OPTIONS_GHC -ddump-to-file -ddump-timings #-} #endif # LANGUAGE OverloadedLabels # module Experiment.SR_GetEvens.Sized.R040 where import SuperRecord (Rec) import qualified SuperRecord as SR import Bench.EvensOfSize.Evens040 import Common.RowOfSize.Row040 getEvens :: Rec ExampleRow -> Evens getEvens r = Evens { -- 00 .. 09 evens00 = SR.get #t00 r , evens02 = SR.get #t02 r , evens04 = SR.get #t04 r , evens06 = SR.get #t06 r , evens08 = SR.get #t08 r 10 .. 19 , evens10 = SR.get #t10 r , evens12 = SR.get #t12 r , evens14 = SR.get #t14 r , evens16 = SR.get #t16 r , evens18 = SR.get #t18 r 20 .. 29 , evens20 = SR.get #t20 r , evens22 = SR.get #t22 r , evens24 = SR.get #t24 r , evens26 = SR.get #t26 r , evens28 = SR.get #t28 r 30 .. 39 , evens30 = SR.get #t30 r , evens32 = SR.get #t32 r , evens34 = SR.get #t34 r , evens36 = SR.get #t36 r , evens38 = SR.get #t38 r }
null
https://raw.githubusercontent.com/well-typed/large-records/78d0966e4871847e2c17a0aa821bacf38bdf96bc/large-records-benchmarks/bench/superrecord/Experiment/SR_GetEvens/Sized/R040.hs
haskell
# OPTIONS_GHC -ddump-to-file -ddump-simpl # # OPTIONS_GHC -ddump-to-file -ddump-timings # 00 .. 09
#if PROFILE_CORESIZE #endif #if PROFILE_TIMING #endif # LANGUAGE OverloadedLabels # module Experiment.SR_GetEvens.Sized.R040 where import SuperRecord (Rec) import qualified SuperRecord as SR import Bench.EvensOfSize.Evens040 import Common.RowOfSize.Row040 getEvens :: Rec ExampleRow -> Evens getEvens r = Evens { evens00 = SR.get #t00 r , evens02 = SR.get #t02 r , evens04 = SR.get #t04 r , evens06 = SR.get #t06 r , evens08 = SR.get #t08 r 10 .. 19 , evens10 = SR.get #t10 r , evens12 = SR.get #t12 r , evens14 = SR.get #t14 r , evens16 = SR.get #t16 r , evens18 = SR.get #t18 r 20 .. 29 , evens20 = SR.get #t20 r , evens22 = SR.get #t22 r , evens24 = SR.get #t24 r , evens26 = SR.get #t26 r , evens28 = SR.get #t28 r 30 .. 39 , evens30 = SR.get #t30 r , evens32 = SR.get #t32 r , evens34 = SR.get #t34 r , evens36 = SR.get #t36 r , evens38 = SR.get #t38 r }
9764414e84e195a980098bedacd93744cb44f1f617710be99b69a36f648c9afb
nibbula/yew
chart.lisp
;;; chart.lisp - Draw charts . ;;; (defpackage :chart (:documentation "Draw charts.") (:use :cl :dlib :collections :char-util :table :terminal :keymap :inator :terminal-inator) (:export #:chart #:bar-chart #:horizontal-bar #:vertical-bar #:do-bars #:draw-chart #:make-chart-from #:make-chart-from-table #:chart-viewer #:view-chart #:!view-chart )) (in-package :chart) (defclass chart () ((title :initarg :title :accessor chart-title :initform "" :documentation "The title of the chart.")) (:documentation "A generic chart.")) (defclass bar-chart (chart) ((labels :initarg :labels :accessor chart-labels :initform nil :documentation "Sequence of labels for the bars.") (values :initarg :values :accessor chart-values :initform nil :documentation "Sequence of values.") (bar-fill :initarg :bar-fill :accessor bar-fill :documentation "A thing to fill the bar with.") (vertical-separator :initarg :vertical-separator :accessor vertical-separator :documentation "A thing to separate the labels.") (horizontal-separator :initarg :horizontal-separator :accessor horizontal-separator :documentation "A thing to separate the labels.")) (:documentation "A bar chart.")) (defclass horizontal-bar (bar-chart) () (:default-initargs :vertical-separator "─" :horizontal-separator " │ " :bar-fill #\▒) (:documentation "An horizontal bar chart.")) (defclass vertical-bar (bar-chart) () (:default-initargs :vertical-separator #\─ :horizontal-separator " │ " :bar-fill #\▒) (:documentation "A vertical bar chart.")) (eval-when (:compile-toplevel :load-toplevel :execute) (defmacro do-bars ((label-var value-var chart) &body body) (with-names (c label-iter value-iter) `(progn (loop :with ,c = ,chart :with ,label-var :and ,value-var :and ,label-iter = (oiterator (chart-labels ,c)) :and ,value-iter = (oiterator (chart-values ,c)) :while (not (and (oend-p ,label-iter) (oend-p ,value-iter))) :do (setf ,label-var (oiter-ref ,label-iter) ,value-var (oiter-ref ,value-iter)) ,@body (when (not (oend-p ,label-iter)) (oincr ,label-iter)) (when (not (oend-p ,value-iter)) (oincr ,value-iter))))))) ;; @@@ Specialize for output device? This is only for terminals. (defmethod draw-chart ((chart horizontal-bar)) (with-slots (labels values bar-fill horizontal-separator) chart (flet ((label-string (label) (princ-to-string (or label "")))) (let* ((labels-width (loop :for l :in labels :maximize (display-length (label-string l)))) (max-value (loop :for v :in values :maximize v)) (width (- (tt-width) (display-length horizontal-separator) labels-width))) (do-bars (label value chart) (tt-write-string (label-string label)) (tt-write-string horizontal-separator) (when (not (zerop max-value)) (tt-format "~v,,,va" (round (* value width) max-value) bar-fill bar-fill)) (tt-fresh-line)))))) (defmethod draw-chart ((chart vertical-bar)) (with-slots (labels values bar-fill horizontal-separator vertical-separator) chart (let* ((max-value (loop :for v :in values :maximize v)) (data-count (olength values)) (bar-width (max 1 (truncate (tt-width) data-count))) (left-edge (truncate (- (tt-width) (* data-count bar-width)) 2)) (height (- (tt-height) 2)) (x left-edge)) (do-bars (label value chart) (loop :for y :from height :downto (if (zerop max-value) height (- height (round (* value height) max-value))) :do (tt-move-to y x) (loop :for i :from 0 :below bar-width :do (tt-write-char bar-fill))) (incf x bar-width)) (tt-move-to (- (tt-height) 2) 0) (tt-format "~v,,,va" (1- (tt-width)) vertical-separator vertical-separator)))) (defgeneric make-chart-from (chart-type object &key label-column value-column) (:documentation "Make a chart of ‘chart-type’ from ‘object’.")) (defmethod make-chart-from (type (object chart) &key (label-column 0) (value-column 1)) (declare (ignore label-column value-column)) (when (not (subtypep (type-of object) type)) ;; @@@ What should we do? (warn "Chart is a different type than asked for ~s: ~a." type (type-of object))) object) (defmethod make-chart-from (type (object table) &key (label-column 0) (value-column 1)) "Make a chart of ‘type’ from ‘table’. Get the labels from ‘label-column’ or the first column, and the values from ‘value-column’ or the second column. The columns can be specified as column names or numbers." (flet ((get-col (col default) (if (numberp col) col (or (table-column-number col object :test #'equalp) default)))) (let ((label-col (get-col (or label-column "label") 0)) (value-col (get-col (or value-column "value") 1)) labels values) (omap (lambda (row) (push (oelt row label-col) labels) (push (oelt row value-col) values)) object) (setf labels (nreverse labels) values (nreverse values)) (make-instance type :labels labels :values values)))) (defun make-chart-from-table (type table &key (label-column 0) (value-column 1)) (make-chart-from type table :label-column label-column :value-column value-column)) (defmethod make-chart-from (type (object cons) &key (label-column 0) (value-column 1)) (declare (ignore label-column value-column)) ;; @@@ (multiple-value-bind (labels values) (cond ((let ((first (first object))) (or (and (consp first) (not (consp (cdr first)))) (and (ordered-collection-p first) (>= (olength first) 2)))) Assume it 's a two 2d list . (loop :for e :in object :collecting (car e) :into labels :collecting (if (consp (cdr e)) ;; support alists or plists (cadr e) (cdr e)) :into values :finally (return (values labels values)))) (t Assume it 's 1d . (loop :for e :in object :and i :from 1 :collecting (princ-to-string i) :into labels :collecting e :into values :finally (return (values labels values))))) (make-instance type :labels labels :values values))) (defmethod make-chart-from (type (object vector) &key (label-column 0) (value-column 1)) (multiple-value-bind (labels values) (cond ((and (ordered-collection-p (oelt object 0)) (>= (olength (oelt object 0)) 2)) Assume it 's a two 2d thing . (loop :for e :across object :collecting (oelt e label-column) :into labels :collecting (oelt e value-column) :into values :finally (return (values labels values)))) Assume it 's 1d . (loop :for e :across object :for i :from 1 :collecting (princ-to-string i) :into labels :collecting e :into values :finally (return (values labels values))))) (make-instance type :labels labels :values values))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Chart viewer (defvar *chart-viewer* nil "The current chart viewer.") (defkeymap *chart-viewer-keymap* () `((#\q . quit) (#\? . help) (#\s . sort-chart) (#\i . record-info) (:home . move-to-top) (:end . move-to-bottom) (:up . previous) (:down . next) (:right . scroll-right) (:left . scroll-left) ;;(,(meta-char #\i) . table-info) ;; (#\escape . *chart-viewer-escape-keymap*) )) (defclass chart-viewer (terminal-inator) ((chart :initarg :chart :accessor chart-viewer-chart :initform nil :documentation "The chart to view.")) (:default-initargs :keymap `(,*chart-viewer-keymap* ,*default-inator-keymap*)) (:documentation "View a chart.")) (defmethod update-display ((o chart-viewer)) (tt-move-to 0 0) (tt-erase-below) (draw-chart (chart-viewer-chart o))) ;; (defgeneric sort-chart (inator) ;; (:documentation "Sort the chart.") ;; (:method ((i chart-viewer)) ;; (osort (chart-viewer))) (defun view-chart (chart &key wait-count) "View a chart." (with-terminal-inator (*chart-viewer* 'chart-viewer :chart chart) (cond ((null wait-count) (event-loop *chart-viewer*)) ((zerop wait-count) (update-display *chart-viewer*) (tt-finish-output)) ((integerp wait-count) (zerop wait-count) (loop :for i :from 0 :below wait-count :do (update-display *chart-viewer*) (await-event *chart-viewer*)))))) (defparameter *chart-type-names* '(horizontal-bar vertical-bar) "The different chart types.") #+lish (lish:defcommand view-chart ((chart object :optional t :help "The chart to draw or a table to make it from.") (type choice :short-arg #\t :default "horizontal-bar" :choices *chart-type-names* :help "The type of chart.") (wait-count object :short-arg #\w :help "How many events to wait for before exiting.")) "Draw a chart." (when (not chart) (when (not lish:*input*) (error "View what chart?")) (setf chart lish:*input*)) (when (and wait-count (or (not (integerp wait-count)) (minusp wait-count))) (error "wait-count should be a non-negative integer.")) (let ((cc ;; (error "I don't know how to view a ~s.~%" (type-of chart)))) (make-chart-from (symbolify (string type) :package (find-package :chart)) chart) )) (view-chart cc :wait-count wait-count))) ;; End
null
https://raw.githubusercontent.com/nibbula/yew/c9c216b713e1d0e74c6d43a061344c1e4008d1ca/tools/chart.lisp
lisp
@@@ Specialize for output device? This is only for terminals. @@@ What should we do? @@@ support alists or plists Chart viewer (,(meta-char #\i) . table-info) (#\escape . *chart-viewer-escape-keymap*) (defgeneric sort-chart (inator) (:documentation "Sort the chart.") (:method ((i chart-viewer)) (osort (chart-viewer))) (error "I don't know how to view a ~s.~%" (type-of chart)))) End
chart.lisp - Draw charts . (defpackage :chart (:documentation "Draw charts.") (:use :cl :dlib :collections :char-util :table :terminal :keymap :inator :terminal-inator) (:export #:chart #:bar-chart #:horizontal-bar #:vertical-bar #:do-bars #:draw-chart #:make-chart-from #:make-chart-from-table #:chart-viewer #:view-chart #:!view-chart )) (in-package :chart) (defclass chart () ((title :initarg :title :accessor chart-title :initform "" :documentation "The title of the chart.")) (:documentation "A generic chart.")) (defclass bar-chart (chart) ((labels :initarg :labels :accessor chart-labels :initform nil :documentation "Sequence of labels for the bars.") (values :initarg :values :accessor chart-values :initform nil :documentation "Sequence of values.") (bar-fill :initarg :bar-fill :accessor bar-fill :documentation "A thing to fill the bar with.") (vertical-separator :initarg :vertical-separator :accessor vertical-separator :documentation "A thing to separate the labels.") (horizontal-separator :initarg :horizontal-separator :accessor horizontal-separator :documentation "A thing to separate the labels.")) (:documentation "A bar chart.")) (defclass horizontal-bar (bar-chart) () (:default-initargs :vertical-separator "─" :horizontal-separator " │ " :bar-fill #\▒) (:documentation "An horizontal bar chart.")) (defclass vertical-bar (bar-chart) () (:default-initargs :vertical-separator #\─ :horizontal-separator " │ " :bar-fill #\▒) (:documentation "A vertical bar chart.")) (eval-when (:compile-toplevel :load-toplevel :execute) (defmacro do-bars ((label-var value-var chart) &body body) (with-names (c label-iter value-iter) `(progn (loop :with ,c = ,chart :with ,label-var :and ,value-var :and ,label-iter = (oiterator (chart-labels ,c)) :and ,value-iter = (oiterator (chart-values ,c)) :while (not (and (oend-p ,label-iter) (oend-p ,value-iter))) :do (setf ,label-var (oiter-ref ,label-iter) ,value-var (oiter-ref ,value-iter)) ,@body (when (not (oend-p ,label-iter)) (oincr ,label-iter)) (when (not (oend-p ,value-iter)) (oincr ,value-iter))))))) (defmethod draw-chart ((chart horizontal-bar)) (with-slots (labels values bar-fill horizontal-separator) chart (flet ((label-string (label) (princ-to-string (or label "")))) (let* ((labels-width (loop :for l :in labels :maximize (display-length (label-string l)))) (max-value (loop :for v :in values :maximize v)) (width (- (tt-width) (display-length horizontal-separator) labels-width))) (do-bars (label value chart) (tt-write-string (label-string label)) (tt-write-string horizontal-separator) (when (not (zerop max-value)) (tt-format "~v,,,va" (round (* value width) max-value) bar-fill bar-fill)) (tt-fresh-line)))))) (defmethod draw-chart ((chart vertical-bar)) (with-slots (labels values bar-fill horizontal-separator vertical-separator) chart (let* ((max-value (loop :for v :in values :maximize v)) (data-count (olength values)) (bar-width (max 1 (truncate (tt-width) data-count))) (left-edge (truncate (- (tt-width) (* data-count bar-width)) 2)) (height (- (tt-height) 2)) (x left-edge)) (do-bars (label value chart) (loop :for y :from height :downto (if (zerop max-value) height (- height (round (* value height) max-value))) :do (tt-move-to y x) (loop :for i :from 0 :below bar-width :do (tt-write-char bar-fill))) (incf x bar-width)) (tt-move-to (- (tt-height) 2) 0) (tt-format "~v,,,va" (1- (tt-width)) vertical-separator vertical-separator)))) (defgeneric make-chart-from (chart-type object &key label-column value-column) (:documentation "Make a chart of ‘chart-type’ from ‘object’.")) (defmethod make-chart-from (type (object chart) &key (label-column 0) (value-column 1)) (declare (ignore label-column value-column)) (when (not (subtypep (type-of object) type)) (warn "Chart is a different type than asked for ~s: ~a." type (type-of object))) object) (defmethod make-chart-from (type (object table) &key (label-column 0) (value-column 1)) "Make a chart of ‘type’ from ‘table’. Get the labels from ‘label-column’ or the first column, and the values from ‘value-column’ or the second column. The columns can be specified as column names or numbers." (flet ((get-col (col default) (if (numberp col) col (or (table-column-number col object :test #'equalp) default)))) (let ((label-col (get-col (or label-column "label") 0)) (value-col (get-col (or value-column "value") 1)) labels values) (omap (lambda (row) (push (oelt row label-col) labels) (push (oelt row value-col) values)) object) (setf labels (nreverse labels) values (nreverse values)) (make-instance type :labels labels :values values)))) (defun make-chart-from-table (type table &key (label-column 0) (value-column 1)) (make-chart-from type table :label-column label-column :value-column value-column)) (defmethod make-chart-from (type (object cons) &key (label-column 0) (value-column 1)) (multiple-value-bind (labels values) (cond ((let ((first (first object))) (or (and (consp first) (not (consp (cdr first)))) (and (ordered-collection-p first) (>= (olength first) 2)))) Assume it 's a two 2d list . (loop :for e :in object :collecting (car e) :into labels (cadr e) (cdr e)) :into values :finally (return (values labels values)))) (t Assume it 's 1d . (loop :for e :in object :and i :from 1 :collecting (princ-to-string i) :into labels :collecting e :into values :finally (return (values labels values))))) (make-instance type :labels labels :values values))) (defmethod make-chart-from (type (object vector) &key (label-column 0) (value-column 1)) (multiple-value-bind (labels values) (cond ((and (ordered-collection-p (oelt object 0)) (>= (olength (oelt object 0)) 2)) Assume it 's a two 2d thing . (loop :for e :across object :collecting (oelt e label-column) :into labels :collecting (oelt e value-column) :into values :finally (return (values labels values)))) Assume it 's 1d . (loop :for e :across object :for i :from 1 :collecting (princ-to-string i) :into labels :collecting e :into values :finally (return (values labels values))))) (make-instance type :labels labels :values values))) (defvar *chart-viewer* nil "The current chart viewer.") (defkeymap *chart-viewer-keymap* () `((#\q . quit) (#\? . help) (#\s . sort-chart) (#\i . record-info) (:home . move-to-top) (:end . move-to-bottom) (:up . previous) (:down . next) (:right . scroll-right) (:left . scroll-left) )) (defclass chart-viewer (terminal-inator) ((chart :initarg :chart :accessor chart-viewer-chart :initform nil :documentation "The chart to view.")) (:default-initargs :keymap `(,*chart-viewer-keymap* ,*default-inator-keymap*)) (:documentation "View a chart.")) (defmethod update-display ((o chart-viewer)) (tt-move-to 0 0) (tt-erase-below) (draw-chart (chart-viewer-chart o))) (defun view-chart (chart &key wait-count) "View a chart." (with-terminal-inator (*chart-viewer* 'chart-viewer :chart chart) (cond ((null wait-count) (event-loop *chart-viewer*)) ((zerop wait-count) (update-display *chart-viewer*) (tt-finish-output)) ((integerp wait-count) (zerop wait-count) (loop :for i :from 0 :below wait-count :do (update-display *chart-viewer*) (await-event *chart-viewer*)))))) (defparameter *chart-type-names* '(horizontal-bar vertical-bar) "The different chart types.") #+lish (lish:defcommand view-chart ((chart object :optional t :help "The chart to draw or a table to make it from.") (type choice :short-arg #\t :default "horizontal-bar" :choices *chart-type-names* :help "The type of chart.") (wait-count object :short-arg #\w :help "How many events to wait for before exiting.")) "Draw a chart." (when (not chart) (when (not lish:*input*) (error "View what chart?")) (setf chart lish:*input*)) (when (and wait-count (or (not (integerp wait-count)) (minusp wait-count))) (error "wait-count should be a non-negative integer.")) (let ((cc (make-chart-from (symbolify (string type) :package (find-package :chart)) chart) )) (view-chart cc :wait-count wait-count)))
270ecca80b9f7948d5c5a52e9e97c1304984d3f373ad96e924bc188519d523b6
artyom-poptsov/guile-png
IEND.scm
;;; IEND.scm -- IEND chunk. Copyright ( C ) 2022 < > ;; ;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ;; (at your option) any later version. ;; ;; The 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 the program. If not, see </>. ;;; Commentary: PNG image final chunk ( IEND ) . The IEND chunk must appear last . ;;; Code: (define-module (png core chunk IEND) #:use-module (oop goops) #:use-module (rnrs bytevectors) #:use-module (png core common) #:use-module (png core chunk) #:export (<png-chunk:IEND> png-chunk-decode-IEND)) (define-class <png-chunk:IEND> (<png-chunk>)) (define-method (initialize (chunk <png-chunk:IEND>) initargs) (next-method) (slot-set! chunk 'type 'IEND)) (define-method (%display (chunk <png-chunk:IEND>) (port <port>)) (let ((type (png-chunk-type-info chunk))) (format port "#<png-chunk:IEND ~a ~a>" (list-ref type 2) (object-address/hex-string chunk)))) (define-method (display (chunk <png-chunk:IEND>) (port <port>)) (%display chunk port)) (define-method (write (chunk <png-chunk:IEND>) (port <port>)) (%display chunk port)) (define-method (png-chunk-decode-IEND (chunk <png-chunk>)) (let ((length (png-chunk-length chunk)) (type (png-chunk-type chunk)) (data (png-chunk-data chunk)) (crc (png-chunk-crc chunk))) (make <png-chunk:IEND> #:length length #:type type))) (define-method (png-chunk-encode (chunk <png-chunk:IEND>)) (let ((encoded-chunk (make <png-chunk> #:type 'IEND))) (png-chunk-crc-update! encoded-chunk) encoded-chunk)) (define-method (png-chunk-clone (chunk <png-chunk:IEND>)) (make <png-chunk:IEND> #:length (png-chunk-length chunk) #:type (png-chunk-type chunk) #:data (bytevector-copy (png-chunk-data chunk)) #:crc (png-chunk-crc chunk))) ends here .
null
https://raw.githubusercontent.com/artyom-poptsov/guile-png/c7cc54fea67649d560da8c68782fd22fae32aede/modules/png/core/chunk/IEND.scm
scheme
IEND.scm -- IEND chunk. This program is free software: you can redistribute it and/or modify (at your option) any later version. The program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with the program. If not, see </>. Commentary: Code:
Copyright ( C ) 2022 < > it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License PNG image final chunk ( IEND ) . The IEND chunk must appear last . (define-module (png core chunk IEND) #:use-module (oop goops) #:use-module (rnrs bytevectors) #:use-module (png core common) #:use-module (png core chunk) #:export (<png-chunk:IEND> png-chunk-decode-IEND)) (define-class <png-chunk:IEND> (<png-chunk>)) (define-method (initialize (chunk <png-chunk:IEND>) initargs) (next-method) (slot-set! chunk 'type 'IEND)) (define-method (%display (chunk <png-chunk:IEND>) (port <port>)) (let ((type (png-chunk-type-info chunk))) (format port "#<png-chunk:IEND ~a ~a>" (list-ref type 2) (object-address/hex-string chunk)))) (define-method (display (chunk <png-chunk:IEND>) (port <port>)) (%display chunk port)) (define-method (write (chunk <png-chunk:IEND>) (port <port>)) (%display chunk port)) (define-method (png-chunk-decode-IEND (chunk <png-chunk>)) (let ((length (png-chunk-length chunk)) (type (png-chunk-type chunk)) (data (png-chunk-data chunk)) (crc (png-chunk-crc chunk))) (make <png-chunk:IEND> #:length length #:type type))) (define-method (png-chunk-encode (chunk <png-chunk:IEND>)) (let ((encoded-chunk (make <png-chunk> #:type 'IEND))) (png-chunk-crc-update! encoded-chunk) encoded-chunk)) (define-method (png-chunk-clone (chunk <png-chunk:IEND>)) (make <png-chunk:IEND> #:length (png-chunk-length chunk) #:type (png-chunk-type chunk) #:data (bytevector-copy (png-chunk-data chunk)) #:crc (png-chunk-crc chunk))) ends here .
6a3d3e956a94c1bcf89dc798c71dd04a79bdafadd2f9a53ffca4f2d5a147041d
kronkltd/jiksnu
ciste.clj
{:environment :development :logger "jiksnu.logger" :modules [ "jiksnu.core" "jiksnu.modules.command" "jiksnu.modules.http" "jiksnu.modules.web" ] :services [ "ciste.services.http-kit" "ciste.services.nrepl" "jiksnu.plugins.google-analytics" ] }
null
https://raw.githubusercontent.com/kronkltd/jiksnu/8c91e9b1fddcc0224b028e573f7c3ca2f227e516/resources/ciste.clj
clojure
{:environment :development :logger "jiksnu.logger" :modules [ "jiksnu.core" "jiksnu.modules.command" "jiksnu.modules.http" "jiksnu.modules.web" ] :services [ "ciste.services.http-kit" "ciste.services.nrepl" "jiksnu.plugins.google-analytics" ] }
5dd21f8080792e5ccec7fc7c831d71f901cb5d581c2774f75e4877f26cdb8ce9
dyzsr/ocaml-selectml
array.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , 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 GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* NOTE: If this file is arrayLabels.mli, run tools/sync_stdlib_docs after editing it to generate array.mli. If this file is array.mli, do not edit it directly -- edit arrayLabels.mli instead. *) * Array operations . The labeled version of this module can be used as described in the { ! StdLabels } module . The labeled version of this module can be used as described in the {!StdLabels} module. *) type 'a t = 'a array (** An alias for the type of arrays. *) external length : 'a array -> int = "%array_length" (** Return the length (number of elements) of the given array. *) external get : 'a array -> int -> 'a = "%array_safe_get" * [ get a n ] returns the element number [ n ] of array [ a ] . The first element has number 0 . The last element has number [ length a - 1 ] . You can also write [ a.(n ) ] instead of [ get a n ] . @raise Invalid_argument if [ n ] is outside the range 0 to [ ( length a - 1 ) ] . The first element has number 0. The last element has number [length a - 1]. You can also write [a.(n)] instead of [get a n]. @raise Invalid_argument if [n] is outside the range 0 to [(length a - 1)]. *) external set : 'a array -> int -> 'a -> unit = "%array_safe_set" (** [set a n x] modifies array [a] in place, replacing element number [n] with [x]. You can also write [a.(n) <- x] instead of [set a n x]. @raise Invalid_argument if [n] is outside the range 0 to [length a - 1]. *) external make : int -> 'a -> 'a array = "caml_make_vect" * [ make n x ] returns a fresh array of length [ n ] , initialized with [ x ] . All the elements of this new array are initially physically equal to [ x ] ( in the sense of the [= =] predicate ) . Consequently , if [ x ] is mutable , it is shared among all elements of the array , and modifying [ x ] through one of the array entries will modify all other entries at the same time . @raise Invalid_argument if [ n < 0 ] or [ n > Sys.max_array_length ] . If the value of [ x ] is a floating - point number , then the maximum size is only [ / 2 ] . initialized with [x]. All the elements of this new array are initially physically equal to [x] (in the sense of the [==] predicate). Consequently, if [x] is mutable, it is shared among all elements of the array, and modifying [x] through one of the array entries will modify all other entries at the same time. @raise Invalid_argument if [n < 0] or [n > Sys.max_array_length]. If the value of [x] is a floating-point number, then the maximum size is only [Sys.max_array_length / 2].*) external create : int -> 'a -> 'a array = "caml_make_vect" [@@ocaml.deprecated "Use Array.make/ArrayLabels.make instead."] (** @deprecated [create] is an alias for {!make}. *) external create_float: int -> float array = "caml_make_float_vect" * [ create_float n ] returns a fresh float array of length [ n ] , with uninitialized data . @since 4.03 with uninitialized data. @since 4.03 *) val make_float: int -> float array [@@ocaml.deprecated "Use Array.create_float/ArrayLabels.create_float instead."] (** @deprecated [make_float] is an alias for {!create_float}. *) val init : int -> (int -> 'a) -> 'a array * [ init n f ] returns a fresh array of length [ n ] , with element number [ i ] initialized to the result of [ f i ] . In other terms , [ init n f ] tabulates the results of [ f ] applied to the integers [ 0 ] to [ n-1 ] . @raise Invalid_argument if [ n < 0 ] or [ n > Sys.max_array_length ] . If the return type of [ f ] is [ float ] , then the maximum size is only [ / 2 ] . with element number [i] initialized to the result of [f i]. In other terms, [init n f] tabulates the results of [f] applied to the integers [0] to [n-1]. @raise Invalid_argument if [n < 0] or [n > Sys.max_array_length]. If the return type of [f] is [float], then the maximum size is only [Sys.max_array_length / 2].*) val make_matrix : int -> int -> 'a -> 'a array array * [ make_matrix dimx e ] returns a two - dimensional array ( an array of arrays ) with first dimension [ dimx ] and second dimension [ dimy ] . All the elements of this new matrix are initially physically equal to [ e ] . The element ( [ x , y ] ) of a matrix [ m ] is accessed with the notation [ m.(x).(y ) ] . @raise Invalid_argument if [ dimx ] or [ dimy ] is negative or greater than { ! } . If the value of [ e ] is a floating - point number , then the maximum size is only [ / 2 ] . (an array of arrays) with first dimension [dimx] and second dimension [dimy]. All the elements of this new matrix are initially physically equal to [e]. The element ([x,y]) of a matrix [m] is accessed with the notation [m.(x).(y)]. @raise Invalid_argument if [dimx] or [dimy] is negative or greater than {!Sys.max_array_length}. If the value of [e] is a floating-point number, then the maximum size is only [Sys.max_array_length / 2]. *) val create_matrix : int -> int -> 'a -> 'a array array [@@ocaml.deprecated "Use Array.make_matrix/ArrayLabels.make_matrix instead."] * @deprecated [ create_matrix ] is an alias for { ! } . val append : 'a array -> 'a array -> 'a array (** [append v1 v2] returns a fresh array containing the concatenation of the arrays [v1] and [v2]. @raise Invalid_argument if [length v1 + length v2 > Sys.max_array_length]. *) val concat : 'a array list -> 'a array (** Same as {!append}, but concatenates a list of arrays. *) val sub : 'a array -> int -> int -> 'a array (** [sub a pos len] returns a fresh array of length [len], containing the elements number [pos] to [pos + len - 1] of array [a]. @raise Invalid_argument if [pos] and [len] do not designate a valid subarray of [a]; that is, if [pos < 0], or [len < 0], or [pos + len > length a]. *) val copy : 'a array -> 'a array (** [copy a] returns a copy of [a], that is, a fresh array containing the same elements as [a]. *) val fill : 'a array -> int -> int -> 'a -> unit (** [fill a pos len x] modifies the array [a] in place, storing [x] in elements number [pos] to [pos + len - 1]. @raise Invalid_argument if [pos] and [len] do not designate a valid subarray of [a]. *) val blit : 'a array -> int -> 'a array -> int -> int -> unit * [ blit src src_pos dst dst_pos len ] copies [ len ] elements from array [ src ] , starting at element number [ src_pos ] , to array [ dst ] , starting at element number [ dst_pos ] . It works correctly even if [ src ] and [ dst ] are the same array , and the source and destination chunks overlap . @raise Invalid_argument if [ src_pos ] and [ len ] do not designate a valid subarray of [ src ] , or if [ dst_pos ] and [ len ] do not designate a valid subarray of [ dst ] . from array [src], starting at element number [src_pos], to array [dst], starting at element number [dst_pos]. It works correctly even if [src] and [dst] are the same array, and the source and destination chunks overlap. @raise Invalid_argument if [src_pos] and [len] do not designate a valid subarray of [src], or if [dst_pos] and [len] do not designate a valid subarray of [dst]. *) val to_list : 'a array -> 'a list (** [to_list a] returns the list of all the elements of [a]. *) val of_list : 'a list -> 'a array * [ of_list l ] returns a fresh array containing the elements of [ l ] . @raise Invalid_argument if the length of [ l ] is greater than [ ] . of [l]. @raise Invalid_argument if the length of [l] is greater than [Sys.max_array_length]. *) (** {1 Iterators} *) val iter : ('a -> unit) -> 'a array -> unit * [ iter f a ] applies function [ f ] in turn to all the elements of [ a ] . It is equivalent to [ f ) ; f a.(1 ) ; ... ; f a.(length a - 1 ) ; ( ) ] . the elements of [a]. It is equivalent to [f a.(0); f a.(1); ...; f a.(length a - 1); ()]. *) val iteri : (int -> 'a -> unit) -> 'a array -> unit * Same as { ! iter } , but the function is applied to the index of the element as first argument , and the element itself as second argument . function is applied to the index of the element as first argument, and the element itself as second argument. *) val map : ('a -> 'b) -> 'a array -> 'b array * [ map f a ] applies function [ f ] to all the elements of [ a ] , and builds an array with the results returned by [ f ] : [ [ | f ) ; f a.(1 ) ; ... ; f a.(length a - 1 ) | ] ] . and builds an array with the results returned by [f]: [[| f a.(0); f a.(1); ...; f a.(length a - 1) |]]. *) val mapi : (int -> 'a -> 'b) -> 'a array -> 'b array * Same as { ! map } , but the function is applied to the index of the element as first argument , and the element itself as second argument . function is applied to the index of the element as first argument, and the element itself as second argument. *) val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b array -> 'a * [ fold_left f init a ] computes [ f ( ... ( f ( f init ) ) a.(1 ) ) ... ) a.(n-1 ) ] , where [ n ] is the length of the array [ a ] . [f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)], where [n] is the length of the array [a]. *) val fold_left_map : ('a -> 'b -> 'a * 'c) -> 'a -> 'b array -> 'a * 'c array * [ fold_left_map ] is a combination of { ! fold_left } and { ! map } that threads an accumulator through calls to [ f ] . @since 4.13.0 accumulator through calls to [f]. @since 4.13.0 *) val fold_right : ('b -> 'a -> 'a) -> 'b array -> 'a -> 'a * [ fold_right f a init ] computes [ f ) ( f a.(1 ) ( ... ( f a.(n-1 ) init ) ... ) ) ] , where [ n ] is the length of the array [ a ] . [f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))], where [n] is the length of the array [a]. *) * { 1 Iterators on two arrays } val iter2 : ('a -> 'b -> unit) -> 'a array -> 'b array -> unit * [ iter2 f a b ] applies function [ f ] to all the elements of [ a ] and [ b ] . @raise Invalid_argument if the arrays are not the same size . @since 4.03.0 ( 4.05.0 in ArrayLabels ) and [b]. @raise Invalid_argument if the arrays are not the same size. @since 4.03.0 (4.05.0 in ArrayLabels) *) val map2 : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array * [ map2 f a b ] applies function [ f ] to all the elements of [ a ] and [ b ] , and builds an array with the results returned by [ f ] : [ [ | f a.(0 ) ) ; ... ; f a.(length a - 1 ) b.(length b - 1)| ] ] . @raise Invalid_argument if the arrays are not the same size . @since 4.03.0 ( 4.05.0 in ArrayLabels ) and [b], and builds an array with the results returned by [f]: [[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]]. @raise Invalid_argument if the arrays are not the same size. @since 4.03.0 (4.05.0 in ArrayLabels) *) (** {1 Array scanning} *) val for_all : ('a -> bool) -> 'a array -> bool * [ for_all f [ |a1 ; ... ; an| ] ] checks if all elements of the array satisfy the predicate [ f ] . That is , it returns [ ( f a1 ) & & ( f a2 ) & & ... & & ( f an ) ] . @since 4.03.0 of the array satisfy the predicate [f]. That is, it returns [(f a1) && (f a2) && ... && (f an)]. @since 4.03.0 *) val exists : ('a -> bool) -> 'a array -> bool * [ exists f [ |a1 ; ... ; an| ] ] checks if at least one element of the array satisfies the predicate [ f ] . That is , it returns [ ( f a1 ) || ( f a2 ) || ... || ( f an ) ] . @since 4.03.0 the array satisfies the predicate [f]. That is, it returns [(f a1) || (f a2) || ... || (f an)]. @since 4.03.0 *) val for_all2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool * Same as { ! for_all } , but for a two - argument predicate . @raise Invalid_argument if the two arrays have different lengths . @since 4.11.0 @raise Invalid_argument if the two arrays have different lengths. @since 4.11.0 *) val exists2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool * Same as { ! exists } , but for a two - argument predicate . @raise Invalid_argument if the two arrays have different lengths . @since 4.11.0 @raise Invalid_argument if the two arrays have different lengths. @since 4.11.0 *) val mem : 'a -> 'a array -> bool * [ mem a set ] is true if and only if [ a ] is structurally equal to an element of [ l ] ( i.e. there is an [ x ] in [ l ] such that [ compare a x = 0 ] ) . @since 4.03.0 to an element of [l] (i.e. there is an [x] in [l] such that [compare a x = 0]). @since 4.03.0 *) val memq : 'a -> 'a array -> bool * Same as { ! mem } , but uses physical equality instead of structural equality to compare list elements . @since 4.03.0 instead of structural equality to compare list elements. @since 4.03.0 *) val find_opt : ('a -> bool) -> 'a array -> 'a option * [ find_opt f a ] returns the first element of the array [ a ] that satisfies the predicate [ f ] , or [ None ] if there is no value that satisfies [ f ] in the array [ a ] . @since 4.13.0 the predicate [f], or [None] if there is no value that satisfies [f] in the array [a]. @since 4.13.0 *) val find_map : ('a -> 'b option) -> 'a array -> 'b option * [ find_map f a ] applies [ f ] to the elements of [ a ] in order , and returns the first result of the form [ Some v ] , or [ None ] if none exist . @since 4.13.0 first result of the form [Some v], or [None] if none exist. @since 4.13.0 *) (** {1 Arrays of pairs} *) val split : ('a * 'b) array -> 'a array * 'b array * [ split [ |(a1,b1 ) ; ... ; ( an , bn)| ] ] is [ ( [ |a1 ; ... ; an| ] , [ |b1 ; ... ; bn| ] ) ] . @since 4.13.0 @since 4.13.0 *) val combine : 'a array -> 'b array -> ('a * 'b) array * [ combine [ |a1 ; ... ; an| ] [ |b1 ; ... ; bn| ] ] is [ [ |(a1,b1 ) ; ... ; ( an , bn)| ] ] . Raise [ Invalid_argument ] if the two arrays have different lengths . @since 4.13.0 Raise [Invalid_argument] if the two arrays have different lengths. @since 4.13.0 *) (** {1 Sorting} *) val sort : ('a -> 'a -> int) -> 'a array -> unit * Sort an array in increasing order according to a comparison function . The comparison function must return 0 if its arguments compare as equal , a positive integer if the first is greater , and a negative integer if the first is smaller ( see below for a complete specification ) . For example , { ! Stdlib.compare } is a suitable comparison function . After calling [ sort ] , the array is sorted in place in increasing order . [ sort ] is guaranteed to run in constant heap space and ( at most ) logarithmic stack space . The current implementation uses Heap Sort . It runs in constant stack space . Specification of the comparison function : Let [ a ] be the array and [ cmp ] the comparison function . The following must be true for all [ x ] , [ y ] , [ z ] in [ a ] : - [ cmp x y ] > 0 if and only if [ cmp y x ] < 0 - if [ cmp x y ] > = 0 and [ cmp y z ] > = 0 then [ cmp x z ] > = 0 When [ sort ] returns , [ a ] contains the same elements as before , reordered in such a way that for all i and j valid indices of [ a ] : - [ cmp a.(i ) ) ] > = 0 if and only if i > = j function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, {!Stdlib.compare} is a suitable comparison function. After calling [sort], the array is sorted in place in increasing order. [sort] is guaranteed to run in constant heap space and (at most) logarithmic stack space. The current implementation uses Heap Sort. It runs in constant stack space. Specification of the comparison function: Let [a] be the array and [cmp] the comparison function. The following must be true for all [x], [y], [z] in [a] : - [cmp x y] > 0 if and only if [cmp y x] < 0 - if [cmp x y] >= 0 and [cmp y z] >= 0 then [cmp x z] >= 0 When [sort] returns, [a] contains the same elements as before, reordered in such a way that for all i and j valid indices of [a] : - [cmp a.(i) a.(j)] >= 0 if and only if i >= j *) val stable_sort : ('a -> 'a -> int) -> 'a array -> unit * Same as { ! sort } , but the sorting algorithm is stable ( i.e. elements that compare equal are kept in their original order ) and not guaranteed to run in constant heap space . The current implementation uses Merge Sort . It uses a temporary array of length [ ] , where [ n ] is the length of the array . It is usually faster than the current implementation of { ! sort } . elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. The current implementation uses Merge Sort. It uses a temporary array of length [n/2], where [n] is the length of the array. It is usually faster than the current implementation of {!sort}. *) val fast_sort : ('a -> 'a -> int) -> 'a array -> unit * Same as { ! sort } or { ! } , whichever is faster on typical input . faster on typical input. *) (** {1 Arrays and Sequences} *) val to_seq : 'a array -> 'a Seq.t * Iterate on the array , in increasing order . Modifications of the array during iteration will be reflected in the sequence . @since 4.07 array during iteration will be reflected in the sequence. @since 4.07 *) val to_seqi : 'a array -> (int * 'a) Seq.t * Iterate on the array , in increasing order , yielding indices along elements . Modifications of the array during iteration will be reflected in the sequence . @since 4.07 Modifications of the array during iteration will be reflected in the sequence. @since 4.07 *) val of_seq : 'a Seq.t -> 'a array * Create an array from the generator @since 4.07 @since 4.07 *) (**/**) * { 1 Undocumented functions } (* The following is for system use only. Do not call directly. *) external unsafe_get : 'a array -> int -> 'a = "%array_unsafe_get" external unsafe_set : 'a array -> int -> 'a -> unit = "%array_unsafe_set" module Floatarray : sig external create : int -> floatarray = "caml_floatarray_create" external length : floatarray -> int = "%floatarray_length" external get : floatarray -> int -> float = "%floatarray_safe_get" external set : floatarray -> int -> float -> unit = "%floatarray_safe_set" external unsafe_get : floatarray -> int -> float = "%floatarray_unsafe_get" external unsafe_set : floatarray -> int -> float -> unit = "%floatarray_unsafe_set" end
null
https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/stdlib/array.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ NOTE: If this file is arrayLabels.mli, run tools/sync_stdlib_docs after editing it to generate array.mli. If this file is array.mli, do not edit it directly -- edit arrayLabels.mli instead. * An alias for the type of arrays. * Return the length (number of elements) of the given array. * [set a n x] modifies array [a] in place, replacing element number [n] with [x]. You can also write [a.(n) <- x] instead of [set a n x]. @raise Invalid_argument if [n] is outside the range 0 to [length a - 1]. * @deprecated [create] is an alias for {!make}. * @deprecated [make_float] is an alias for {!create_float}. * [append v1 v2] returns a fresh array containing the concatenation of the arrays [v1] and [v2]. @raise Invalid_argument if [length v1 + length v2 > Sys.max_array_length]. * Same as {!append}, but concatenates a list of arrays. * [sub a pos len] returns a fresh array of length [len], containing the elements number [pos] to [pos + len - 1] of array [a]. @raise Invalid_argument if [pos] and [len] do not designate a valid subarray of [a]; that is, if [pos < 0], or [len < 0], or [pos + len > length a]. * [copy a] returns a copy of [a], that is, a fresh array containing the same elements as [a]. * [fill a pos len x] modifies the array [a] in place, storing [x] in elements number [pos] to [pos + len - 1]. @raise Invalid_argument if [pos] and [len] do not designate a valid subarray of [a]. * [to_list a] returns the list of all the elements of [a]. * {1 Iterators} * {1 Array scanning} * {1 Arrays of pairs} * {1 Sorting} * {1 Arrays and Sequences} */* The following is for system use only. Do not call directly.
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the * Array operations . The labeled version of this module can be used as described in the { ! StdLabels } module . The labeled version of this module can be used as described in the {!StdLabels} module. *) type 'a t = 'a array external length : 'a array -> int = "%array_length" external get : 'a array -> int -> 'a = "%array_safe_get" * [ get a n ] returns the element number [ n ] of array [ a ] . The first element has number 0 . The last element has number [ length a - 1 ] . You can also write [ a.(n ) ] instead of [ get a n ] . @raise Invalid_argument if [ n ] is outside the range 0 to [ ( length a - 1 ) ] . The first element has number 0. The last element has number [length a - 1]. You can also write [a.(n)] instead of [get a n]. @raise Invalid_argument if [n] is outside the range 0 to [(length a - 1)]. *) external set : 'a array -> int -> 'a -> unit = "%array_safe_set" external make : int -> 'a -> 'a array = "caml_make_vect" * [ make n x ] returns a fresh array of length [ n ] , initialized with [ x ] . All the elements of this new array are initially physically equal to [ x ] ( in the sense of the [= =] predicate ) . Consequently , if [ x ] is mutable , it is shared among all elements of the array , and modifying [ x ] through one of the array entries will modify all other entries at the same time . @raise Invalid_argument if [ n < 0 ] or [ n > Sys.max_array_length ] . If the value of [ x ] is a floating - point number , then the maximum size is only [ / 2 ] . initialized with [x]. All the elements of this new array are initially physically equal to [x] (in the sense of the [==] predicate). Consequently, if [x] is mutable, it is shared among all elements of the array, and modifying [x] through one of the array entries will modify all other entries at the same time. @raise Invalid_argument if [n < 0] or [n > Sys.max_array_length]. If the value of [x] is a floating-point number, then the maximum size is only [Sys.max_array_length / 2].*) external create : int -> 'a -> 'a array = "caml_make_vect" [@@ocaml.deprecated "Use Array.make/ArrayLabels.make instead."] external create_float: int -> float array = "caml_make_float_vect" * [ create_float n ] returns a fresh float array of length [ n ] , with uninitialized data . @since 4.03 with uninitialized data. @since 4.03 *) val make_float: int -> float array [@@ocaml.deprecated "Use Array.create_float/ArrayLabels.create_float instead."] val init : int -> (int -> 'a) -> 'a array * [ init n f ] returns a fresh array of length [ n ] , with element number [ i ] initialized to the result of [ f i ] . In other terms , [ init n f ] tabulates the results of [ f ] applied to the integers [ 0 ] to [ n-1 ] . @raise Invalid_argument if [ n < 0 ] or [ n > Sys.max_array_length ] . If the return type of [ f ] is [ float ] , then the maximum size is only [ / 2 ] . with element number [i] initialized to the result of [f i]. In other terms, [init n f] tabulates the results of [f] applied to the integers [0] to [n-1]. @raise Invalid_argument if [n < 0] or [n > Sys.max_array_length]. If the return type of [f] is [float], then the maximum size is only [Sys.max_array_length / 2].*) val make_matrix : int -> int -> 'a -> 'a array array * [ make_matrix dimx e ] returns a two - dimensional array ( an array of arrays ) with first dimension [ dimx ] and second dimension [ dimy ] . All the elements of this new matrix are initially physically equal to [ e ] . The element ( [ x , y ] ) of a matrix [ m ] is accessed with the notation [ m.(x).(y ) ] . @raise Invalid_argument if [ dimx ] or [ dimy ] is negative or greater than { ! } . If the value of [ e ] is a floating - point number , then the maximum size is only [ / 2 ] . (an array of arrays) with first dimension [dimx] and second dimension [dimy]. All the elements of this new matrix are initially physically equal to [e]. The element ([x,y]) of a matrix [m] is accessed with the notation [m.(x).(y)]. @raise Invalid_argument if [dimx] or [dimy] is negative or greater than {!Sys.max_array_length}. If the value of [e] is a floating-point number, then the maximum size is only [Sys.max_array_length / 2]. *) val create_matrix : int -> int -> 'a -> 'a array array [@@ocaml.deprecated "Use Array.make_matrix/ArrayLabels.make_matrix instead."] * @deprecated [ create_matrix ] is an alias for { ! } . val append : 'a array -> 'a array -> 'a array val concat : 'a array list -> 'a array val sub : 'a array -> int -> int -> 'a array val copy : 'a array -> 'a array val fill : 'a array -> int -> int -> 'a -> unit val blit : 'a array -> int -> 'a array -> int -> int -> unit * [ blit src src_pos dst dst_pos len ] copies [ len ] elements from array [ src ] , starting at element number [ src_pos ] , to array [ dst ] , starting at element number [ dst_pos ] . It works correctly even if [ src ] and [ dst ] are the same array , and the source and destination chunks overlap . @raise Invalid_argument if [ src_pos ] and [ len ] do not designate a valid subarray of [ src ] , or if [ dst_pos ] and [ len ] do not designate a valid subarray of [ dst ] . from array [src], starting at element number [src_pos], to array [dst], starting at element number [dst_pos]. It works correctly even if [src] and [dst] are the same array, and the source and destination chunks overlap. @raise Invalid_argument if [src_pos] and [len] do not designate a valid subarray of [src], or if [dst_pos] and [len] do not designate a valid subarray of [dst]. *) val to_list : 'a array -> 'a list val of_list : 'a list -> 'a array * [ of_list l ] returns a fresh array containing the elements of [ l ] . @raise Invalid_argument if the length of [ l ] is greater than [ ] . of [l]. @raise Invalid_argument if the length of [l] is greater than [Sys.max_array_length]. *) val iter : ('a -> unit) -> 'a array -> unit * [ iter f a ] applies function [ f ] in turn to all the elements of [ a ] . It is equivalent to [ f ) ; f a.(1 ) ; ... ; f a.(length a - 1 ) ; ( ) ] . the elements of [a]. It is equivalent to [f a.(0); f a.(1); ...; f a.(length a - 1); ()]. *) val iteri : (int -> 'a -> unit) -> 'a array -> unit * Same as { ! iter } , but the function is applied to the index of the element as first argument , and the element itself as second argument . function is applied to the index of the element as first argument, and the element itself as second argument. *) val map : ('a -> 'b) -> 'a array -> 'b array * [ map f a ] applies function [ f ] to all the elements of [ a ] , and builds an array with the results returned by [ f ] : [ [ | f ) ; f a.(1 ) ; ... ; f a.(length a - 1 ) | ] ] . and builds an array with the results returned by [f]: [[| f a.(0); f a.(1); ...; f a.(length a - 1) |]]. *) val mapi : (int -> 'a -> 'b) -> 'a array -> 'b array * Same as { ! map } , but the function is applied to the index of the element as first argument , and the element itself as second argument . function is applied to the index of the element as first argument, and the element itself as second argument. *) val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b array -> 'a * [ fold_left f init a ] computes [ f ( ... ( f ( f init ) ) a.(1 ) ) ... ) a.(n-1 ) ] , where [ n ] is the length of the array [ a ] . [f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)], where [n] is the length of the array [a]. *) val fold_left_map : ('a -> 'b -> 'a * 'c) -> 'a -> 'b array -> 'a * 'c array * [ fold_left_map ] is a combination of { ! fold_left } and { ! map } that threads an accumulator through calls to [ f ] . @since 4.13.0 accumulator through calls to [f]. @since 4.13.0 *) val fold_right : ('b -> 'a -> 'a) -> 'b array -> 'a -> 'a * [ fold_right f a init ] computes [ f ) ( f a.(1 ) ( ... ( f a.(n-1 ) init ) ... ) ) ] , where [ n ] is the length of the array [ a ] . [f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))], where [n] is the length of the array [a]. *) * { 1 Iterators on two arrays } val iter2 : ('a -> 'b -> unit) -> 'a array -> 'b array -> unit * [ iter2 f a b ] applies function [ f ] to all the elements of [ a ] and [ b ] . @raise Invalid_argument if the arrays are not the same size . @since 4.03.0 ( 4.05.0 in ArrayLabels ) and [b]. @raise Invalid_argument if the arrays are not the same size. @since 4.03.0 (4.05.0 in ArrayLabels) *) val map2 : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array * [ map2 f a b ] applies function [ f ] to all the elements of [ a ] and [ b ] , and builds an array with the results returned by [ f ] : [ [ | f a.(0 ) ) ; ... ; f a.(length a - 1 ) b.(length b - 1)| ] ] . @raise Invalid_argument if the arrays are not the same size . @since 4.03.0 ( 4.05.0 in ArrayLabels ) and [b], and builds an array with the results returned by [f]: [[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]]. @raise Invalid_argument if the arrays are not the same size. @since 4.03.0 (4.05.0 in ArrayLabels) *) val for_all : ('a -> bool) -> 'a array -> bool * [ for_all f [ |a1 ; ... ; an| ] ] checks if all elements of the array satisfy the predicate [ f ] . That is , it returns [ ( f a1 ) & & ( f a2 ) & & ... & & ( f an ) ] . @since 4.03.0 of the array satisfy the predicate [f]. That is, it returns [(f a1) && (f a2) && ... && (f an)]. @since 4.03.0 *) val exists : ('a -> bool) -> 'a array -> bool * [ exists f [ |a1 ; ... ; an| ] ] checks if at least one element of the array satisfies the predicate [ f ] . That is , it returns [ ( f a1 ) || ( f a2 ) || ... || ( f an ) ] . @since 4.03.0 the array satisfies the predicate [f]. That is, it returns [(f a1) || (f a2) || ... || (f an)]. @since 4.03.0 *) val for_all2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool * Same as { ! for_all } , but for a two - argument predicate . @raise Invalid_argument if the two arrays have different lengths . @since 4.11.0 @raise Invalid_argument if the two arrays have different lengths. @since 4.11.0 *) val exists2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool * Same as { ! exists } , but for a two - argument predicate . @raise Invalid_argument if the two arrays have different lengths . @since 4.11.0 @raise Invalid_argument if the two arrays have different lengths. @since 4.11.0 *) val mem : 'a -> 'a array -> bool * [ mem a set ] is true if and only if [ a ] is structurally equal to an element of [ l ] ( i.e. there is an [ x ] in [ l ] such that [ compare a x = 0 ] ) . @since 4.03.0 to an element of [l] (i.e. there is an [x] in [l] such that [compare a x = 0]). @since 4.03.0 *) val memq : 'a -> 'a array -> bool * Same as { ! mem } , but uses physical equality instead of structural equality to compare list elements . @since 4.03.0 instead of structural equality to compare list elements. @since 4.03.0 *) val find_opt : ('a -> bool) -> 'a array -> 'a option * [ find_opt f a ] returns the first element of the array [ a ] that satisfies the predicate [ f ] , or [ None ] if there is no value that satisfies [ f ] in the array [ a ] . @since 4.13.0 the predicate [f], or [None] if there is no value that satisfies [f] in the array [a]. @since 4.13.0 *) val find_map : ('a -> 'b option) -> 'a array -> 'b option * [ find_map f a ] applies [ f ] to the elements of [ a ] in order , and returns the first result of the form [ Some v ] , or [ None ] if none exist . @since 4.13.0 first result of the form [Some v], or [None] if none exist. @since 4.13.0 *) val split : ('a * 'b) array -> 'a array * 'b array * [ split [ |(a1,b1 ) ; ... ; ( an , bn)| ] ] is [ ( [ |a1 ; ... ; an| ] , [ |b1 ; ... ; bn| ] ) ] . @since 4.13.0 @since 4.13.0 *) val combine : 'a array -> 'b array -> ('a * 'b) array * [ combine [ |a1 ; ... ; an| ] [ |b1 ; ... ; bn| ] ] is [ [ |(a1,b1 ) ; ... ; ( an , bn)| ] ] . Raise [ Invalid_argument ] if the two arrays have different lengths . @since 4.13.0 Raise [Invalid_argument] if the two arrays have different lengths. @since 4.13.0 *) val sort : ('a -> 'a -> int) -> 'a array -> unit * Sort an array in increasing order according to a comparison function . The comparison function must return 0 if its arguments compare as equal , a positive integer if the first is greater , and a negative integer if the first is smaller ( see below for a complete specification ) . For example , { ! Stdlib.compare } is a suitable comparison function . After calling [ sort ] , the array is sorted in place in increasing order . [ sort ] is guaranteed to run in constant heap space and ( at most ) logarithmic stack space . The current implementation uses Heap Sort . It runs in constant stack space . Specification of the comparison function : Let [ a ] be the array and [ cmp ] the comparison function . The following must be true for all [ x ] , [ y ] , [ z ] in [ a ] : - [ cmp x y ] > 0 if and only if [ cmp y x ] < 0 - if [ cmp x y ] > = 0 and [ cmp y z ] > = 0 then [ cmp x z ] > = 0 When [ sort ] returns , [ a ] contains the same elements as before , reordered in such a way that for all i and j valid indices of [ a ] : - [ cmp a.(i ) ) ] > = 0 if and only if i > = j function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, {!Stdlib.compare} is a suitable comparison function. After calling [sort], the array is sorted in place in increasing order. [sort] is guaranteed to run in constant heap space and (at most) logarithmic stack space. The current implementation uses Heap Sort. It runs in constant stack space. Specification of the comparison function: Let [a] be the array and [cmp] the comparison function. The following must be true for all [x], [y], [z] in [a] : - [cmp x y] > 0 if and only if [cmp y x] < 0 - if [cmp x y] >= 0 and [cmp y z] >= 0 then [cmp x z] >= 0 When [sort] returns, [a] contains the same elements as before, reordered in such a way that for all i and j valid indices of [a] : - [cmp a.(i) a.(j)] >= 0 if and only if i >= j *) val stable_sort : ('a -> 'a -> int) -> 'a array -> unit * Same as { ! sort } , but the sorting algorithm is stable ( i.e. elements that compare equal are kept in their original order ) and not guaranteed to run in constant heap space . The current implementation uses Merge Sort . It uses a temporary array of length [ ] , where [ n ] is the length of the array . It is usually faster than the current implementation of { ! sort } . elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. The current implementation uses Merge Sort. It uses a temporary array of length [n/2], where [n] is the length of the array. It is usually faster than the current implementation of {!sort}. *) val fast_sort : ('a -> 'a -> int) -> 'a array -> unit * Same as { ! sort } or { ! } , whichever is faster on typical input . faster on typical input. *) val to_seq : 'a array -> 'a Seq.t * Iterate on the array , in increasing order . Modifications of the array during iteration will be reflected in the sequence . @since 4.07 array during iteration will be reflected in the sequence. @since 4.07 *) val to_seqi : 'a array -> (int * 'a) Seq.t * Iterate on the array , in increasing order , yielding indices along elements . Modifications of the array during iteration will be reflected in the sequence . @since 4.07 Modifications of the array during iteration will be reflected in the sequence. @since 4.07 *) val of_seq : 'a Seq.t -> 'a array * Create an array from the generator @since 4.07 @since 4.07 *) * { 1 Undocumented functions } external unsafe_get : 'a array -> int -> 'a = "%array_unsafe_get" external unsafe_set : 'a array -> int -> 'a -> unit = "%array_unsafe_set" module Floatarray : sig external create : int -> floatarray = "caml_floatarray_create" external length : floatarray -> int = "%floatarray_length" external get : floatarray -> int -> float = "%floatarray_safe_get" external set : floatarray -> int -> float -> unit = "%floatarray_safe_set" external unsafe_get : floatarray -> int -> float = "%floatarray_unsafe_get" external unsafe_set : floatarray -> int -> float -> unit = "%floatarray_unsafe_set" end
d5a9c61dd071037bc0efdd4940629fa80257bbfd3f483950b0204861ee824155
vicampo/riposte
equals.rkt
#lang racket/base (require racket/match racket/hash (file "common.rkt")) (define (foo/bar req) (response/jsexpr (hash 'hey #f))) (define (post:foo/bar req) (match (cons (request->jsexpr req) (get-request-header req #"accept")) [(cons (? void?) _) (response/empty #:code 400)] [(cons (not (? hash?)) _ ) (response/empty #:code 400)] [(cons js #f) (response/jsexpr (hash-union (hash 'hey #f) (hash 'body js)))] [(cons js (? bytes? h)) (match (bytes->string h) [(? string? s) (response/jsexpr (hash-union (hash 'hey #t) (hash 'body js 'content-type s)))] [else (response/empty #:code 400)])])) (define-values (start url-generator) (dispatch-rules [("foo" "bar") #:method "get" foo/bar] [("foo" "bar") #:method "post" post:foo/bar] [("foo" "bar") #:method (regexp ".*") not-allowed] [else not-found])) (module+ main (run start))
null
https://raw.githubusercontent.com/vicampo/riposte/0a71e54539cb40b574f84674769792444691a8cf/examples/equals.rkt
racket
#lang racket/base (require racket/match racket/hash (file "common.rkt")) (define (foo/bar req) (response/jsexpr (hash 'hey #f))) (define (post:foo/bar req) (match (cons (request->jsexpr req) (get-request-header req #"accept")) [(cons (? void?) _) (response/empty #:code 400)] [(cons (not (? hash?)) _ ) (response/empty #:code 400)] [(cons js #f) (response/jsexpr (hash-union (hash 'hey #f) (hash 'body js)))] [(cons js (? bytes? h)) (match (bytes->string h) [(? string? s) (response/jsexpr (hash-union (hash 'hey #t) (hash 'body js 'content-type s)))] [else (response/empty #:code 400)])])) (define-values (start url-generator) (dispatch-rules [("foo" "bar") #:method "get" foo/bar] [("foo" "bar") #:method "post" post:foo/bar] [("foo" "bar") #:method (regexp ".*") not-allowed] [else not-found])) (module+ main (run start))
998351c597ea7abf57df40f9cb91a64cdd1f7e8f3c0993d05c0c667b6e1331c9
UU-ComputerScience/uhc
ForeignPtr.hs
# EXCLUDE_IF_TARGET js # {-# EXCLUDE_IF_TARGET cr #-} module ForeignPtr (module Foreign.ForeignPtr) where import Foreign.ForeignPtr
null
https://raw.githubusercontent.com/UU-ComputerScience/uhc/f2b94a90d26e2093d84044b3832a9a3e3c36b129/EHC/ehclib/haskell98/ForeignPtr.hs
haskell
# EXCLUDE_IF_TARGET cr #
# EXCLUDE_IF_TARGET js # module ForeignPtr (module Foreign.ForeignPtr) where import Foreign.ForeignPtr
b08d63cf3424e5d37f13e0e2492b3f44adeab2cf04cb73afed46815ce924cc36
spawnfest/eep49ers
openssl_server_cert_SUITE.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2019 - 2019 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -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. %% %% %CopyrightEnd% %% %% -module(openssl_server_cert_SUITE). -include_lib("common_test/include/ct.hrl"). -include_lib("public_key/include/public_key.hrl"). %% Common test -export([all/0, groups/0, init_per_suite/1, init_per_group/2, init_per_testcase/2, end_per_suite/1, end_per_group/2, end_per_testcase/2 ]). %% Test cases -export([no_auth/0, no_auth/1, auth/0, auth/1, client_auth_empty_cert_accepted/0, client_auth_empty_cert_accepted/1, client_auth_empty_cert_rejected/0, client_auth_empty_cert_rejected/1, client_auth_partial_chain/0, client_auth_partial_chain/1, client_auth_allow_partial_chain/0, client_auth_allow_partial_chain/1, client_auth_do_not_allow_partial_chain/0, client_auth_do_not_allow_partial_chain/1, client_auth_partial_chain_fun_fail/0, client_auth_partial_chain_fun_fail/1, missing_root_cert_no_auth/0, missing_root_cert_no_auth/1, unsupported_sign_algo_client_auth/0, unsupported_sign_algo_client_auth/1, unsupported_sign_algo_cert_client_auth/0, unsupported_sign_algo_cert_client_auth/1, hello_retry_request/0, hello_retry_request/1, custom_groups/0, custom_groups/1, hello_retry_client_auth/0, hello_retry_client_auth/1, hello_retry_client_auth_empty_cert_accepted/0, hello_retry_client_auth_empty_cert_accepted/1, hello_retry_client_auth_empty_cert_rejected/0, hello_retry_client_auth_empty_cert_rejected/1 ]). %%-------------------------------------------------------------------- %% Common Test interface functions ----------------------------------- %%-------------------------------------------------------------------- all() -> [ {group, openssl_server}]. groups() -> [ {openssl_server, [], protocol_groups()}, {'tlsv1.3', [], tls_1_3_protocol_groups()}, {'tlsv1.2', [], pre_tls_1_3_protocol_groups()}, {'tlsv1.1', [], pre_tls_1_3_protocol_groups()}, {'tlsv1', [], pre_tls_1_3_protocol_groups()}, {'dtlsv1.2', [], pre_tls_1_3_protocol_groups()}, {'dtlsv1', [], pre_tls_1_3_protocol_groups()}, {rsa, [], all_version_tests()}, {ecdsa, [], all_version_tests()}, {dsa, [], all_version_tests()}, {rsa_1_3, [], all_version_tests() ++ tls_1_3_tests()}, %% TODO: Create proper conf of openssl server + + [ unsupported_sign_algo_client_auth , unsupported_sign_algo_cert_client_auth ] } , {rsa_pss_rsae, [], all_version_tests() ++ tls_1_3_tests()}, {rsa_pss_pss, [], all_version_tests() ++ tls_1_3_tests()}, {ecdsa_1_3, [], all_version_tests() ++ tls_1_3_tests()} Enable test later when we have OpenSSL version that is able to read EDDSA private key files %%{eddsa_1_3, [], all_version_tests() ++ tls_1_3_tests()} ]. protocol_groups() -> case ssl_test_lib:openssl_sane_dtls() of true -> [{group, 'tlsv1.3'}, {group, 'tlsv1.2'}, {group, 'tlsv1.1'}, {group, 'tlsv1'}, {group, 'dtlsv1.2'}, {group, 'dtlsv1'}]; false -> [{group, 'tlsv1.3'}, {group, 'tlsv1.2'}, {group, 'tlsv1.1'}, {group, 'tlsv1'} ] end. pre_tls_1_3_protocol_groups() -> [{group, rsa}, {group, ecdsa}, {group, dsa}]. tls_1_3_protocol_groups() -> [{group, rsa_1_3}, {group, rsa_pss_rsae}, {group, rsa_pss_pss}, {group, ecdsa_1_3} %%{group, eddsa_1_3} ]. tls_1_3_tests() -> [ hello_retry_request, custom_groups, hello_retry_client_auth, hello_retry_client_auth_empty_cert_accepted, hello_retry_client_auth_empty_cert_rejected ]. all_version_tests() -> [ no_auth, auth, missing_root_cert_no_auth ]. init_per_suite(Config) -> catch crypto:stop(), try crypto:start() of ok -> ssl_test_lib:clean_start(), Config catch _:_ -> {skip, "Crypto did not start"} end. end_per_suite(_Config) -> ssl:stop(), application:unload(ssl), application:stop(crypto). init_per_group(openssl_server, Config0) -> Config = proplists:delete(server_type, proplists:delete(client_type, Config0)), [{client_type, erlang}, {server_type, openssl} | Config]; init_per_group(rsa = Group, Config0) -> Config = ssl_test_lib:make_rsa_cert(Config0), COpts = proplists:get_value(client_rsa_opts, Config), SOpts = proplists:get_value(server_rsa_opts, Config), %% Make sure _rsa* suite is choosen by ssl_test_lib:start_server Version = ssl_test_lib:protocol_version(Config), Ciphers = ssl_cert_tests:test_ciphers(fun(dhe_rsa) -> true; (ecdhe_rsa) -> true; (_) -> false end, Version), case Ciphers of [_|_] -> [{cert_key_alg, rsa} | lists:delete(cert_key_alg, [{client_cert_opts, [{ciphers, Ciphers} | COpts]}, {server_cert_opts, SOpts} | lists:delete(server_cert_opts, lists:delete(client_cert_opts, Config))])]; [] -> {skip, {no_sup, Group, Version}} end; init_per_group(rsa_1_3 = Group, Config0) -> Config = ssl_test_lib:make_rsa_cert(Config0), COpts = proplists:get_value(client_rsa_opts, Config), SOpts = proplists:get_value(server_rsa_opts, Config), %% Make sure _rsa* suite is choosen by ssl_test_lib:start_server Version = ssl_test_lib:protocol_version(Config), Ciphers = ssl_cert_tests:test_ciphers(undefined, Version), case Ciphers of [_|_] -> [{cert_key_alg, rsa} | lists:delete(cert_key_alg, [{client_cert_opts, [{ciphers, Ciphers} | COpts]}, {server_cert_opts, SOpts} | lists:delete(server_cert_opts, lists:delete(client_cert_opts, Config))])]; [] -> {skip, {no_sup, Group, Version}} end; init_per_group(Alg, Config) when Alg == rsa_pss_rsae; Alg == rsa_pss_pss -> Supports = crypto:supports(), RSAOpts = proplists:get_value(rsa_opts, Supports), case lists:member(rsa_pkcs1_pss_padding, RSAOpts) andalso lists:member(rsa_pss_saltlen, RSAOpts) andalso lists:member(rsa_mgf1_md, RSAOpts) andalso ssl_test_lib:is_sane_oppenssl_pss(Alg) of true -> #{client_config := COpts, server_config := SOpts} = ssl_test_lib:make_rsa_pss_pem(Alg, [], Config, ""), [{cert_key_alg, Alg} | lists:delete(cert_key_alg, [{client_cert_opts, COpts}, {server_cert_opts, SOpts} | lists:delete(server_cert_opts, lists:delete(client_cert_opts, Config))])]; false -> {skip, "Missing crypto or OpenSSL support"} end; init_per_group(ecdsa = Group, Config0) -> PKAlg = crypto:supports(public_keys), case lists:member(ecdsa, PKAlg) andalso (lists:member(ecdh, PKAlg) orelse lists:member(dh, PKAlg)) andalso (ssl_test_lib:openssl_ecdsa_suites() =/= []) of true -> Config = ssl_test_lib:make_ecdsa_cert(Config0), COpts = proplists:get_value(client_ecdsa_opts, Config), SOpts = proplists:get_value(server_ecdsa_opts, Config), %% Make sure ecdh* suite is choosen by ssl_test_lib:start_server Version = ssl_test_lib:protocol_version(Config), Ciphers = ssl_cert_tests:test_ciphers(fun(ecdh_ecdsa) -> true; (ecdhe_ecdsa) -> true; (_) -> false end, Version), case Ciphers of [_|_] -> [{cert_key_alg, ecdsa} | lists:delete(cert_key_alg, [{client_cert_opts, [{ciphers, Ciphers} | COpts]}, {server_cert_opts, SOpts} | lists:delete(server_cert_opts, lists:delete(client_cert_opts, Config))] )]; [] -> {skip, {no_sup, Group, Version}} end; false -> {skip, "Missing EC crypto support"} end; init_per_group(ecdsa_1_3 = Group, Config0) -> PKAlg = crypto:supports(public_keys), case lists:member(ecdsa, PKAlg) andalso (lists:member(ecdh, PKAlg) orelse lists:member(dh, PKAlg)) andalso (ssl_test_lib:openssl_ecdsa_suites() =/= []) of true -> Config = ssl_test_lib:make_ecdsa_cert(Config0), COpts = proplists:get_value(client_ecdsa_opts, Config), SOpts = proplists:get_value(server_ecdsa_opts, Config), %% Make sure ecdh* suite is choosen by ssl_test_lib:start_server Version = ssl_test_lib:protocol_version(Config), Ciphers = ssl_cert_tests:test_ciphers(undefined, Version), case Ciphers of [_|_] -> [{cert_key_alg, ecdsa} | lists:delete(cert_key_alg, [{client_cert_opts, [{ciphers, Ciphers} | COpts]}, {server_cert_opts, SOpts} | lists:delete(server_cert_opts, lists:delete(client_cert_opts, Config))] )]; [] -> {skip, {no_sup, Group, Version}} end; false -> {skip, "Missing EC crypto support"} end; init_per_group(eddsa_1_3, Config0) -> PKAlg = crypto:supports(public_keys), PrivDir = proplists:get_value(priv_dir, Config0), case lists:member(eddsa, PKAlg) andalso (lists:member(ecdh, PKAlg)) of true -> Conf = public_key:pkix_test_data(#{server_chain => #{root => ssl_test_lib:eddsa_conf(), intermediates => [ssl_test_lib:eddsa_conf()], peer => ssl_test_lib:eddsa_conf()}, client_chain => #{root => ssl_test_lib:eddsa_conf(), intermediates => [ssl_test_lib:eddsa_conf()], peer => ssl_test_lib:eddsa_conf()}}), [{server_config, SOpts}, {client_config, COpts}] = x509_test:gen_pem_config_files(Conf, filename:join(PrivDir, "client_eddsa"), filename:join(PrivDir, "server_eddsa")), [{cert_key_alg, eddsa} | lists:delete(cert_key_alg, [{client_cert_opts, COpts}, {server_cert_opts, SOpts} | lists:delete(server_cert_opts, lists:delete(client_cert_opts, Config0))] )]; false -> {skip, "Missing EC crypto support"} end; init_per_group(dsa = Group, Config0) -> PKAlg = crypto:supports(public_keys), case lists:member(dss, PKAlg) andalso lists:member(dh, PKAlg) andalso (ssl_test_lib:openssl_dsa_suites() =/= []) of true -> Config = ssl_test_lib:make_dsa_cert(Config0), COpts = proplists:get_value(client_dsa_opts, Config), SOpts = proplists:get_value(server_dsa_opts, Config), %% Make sure dhe_dss* suite is choosen by ssl_test_lib:start_server Version = ssl_test_lib:protocol_version(Config), Ciphers = ssl_cert_tests:test_ciphers(fun(dh_dss) -> true; (dhe_dss) -> true; (_) -> false end, Version), case Ciphers of [_|_] -> [{cert_key_alg, dsa} | lists:delete(cert_key_alg, [{client_cert_opts, [{ciphers, Ciphers} | COpts]}, {server_cert_opts, SOpts} | lists:delete(server_cert_opts, lists:delete(client_cert_opts, Config))])]; [] -> {skip, {no_sup, Group, Version}} end; false -> {skip, "Missing DSS crypto support"} end; init_per_group(GroupName, Config) -> ssl_test_lib:init_per_group_openssl(GroupName, Config). end_per_group(GroupName, Config) -> ssl_test_lib:end_per_group(GroupName, Config). init_per_testcase(_TestCase, Config) -> ssl_test_lib:ct_log_supported_protocol_versions(Config), ct:timetrap({seconds, 30}), Config. end_per_testcase(_TestCase, Config) -> Config. %%-------------------------------------------------------------------- %% Test Cases -------------------------------------------------------- %%-------------------------------------------------------------------- no_auth() -> ssl_cert_tests:no_auth(). no_auth(Config) -> ssl_cert_tests:no_auth(Config). %%-------------------------------------------------------------------- auth() -> ssl_cert_tests:auth(). auth(Config) -> ssl_cert_tests:auth(Config). %%-------------------------------------------------------------------- client_auth_empty_cert_accepted() -> ssl_cert_tests:client_auth_empty_cert_accepted(). client_auth_empty_cert_accepted(Config) -> ssl_cert_tests:client_auth_empty_cert_accepted(Config). %%-------------------------------------------------------------------- client_auth_empty_cert_rejected() -> ssl_cert_tests:client_auth_empty_cert_rejected(). client_auth_empty_cert_rejected(Config) -> ssl_cert_tests:client_auth_empty_cert_rejected(Config). %%-------------------------------------------------------------------- client_auth_partial_chain() -> ssl_cert_tests:client_auth_partial_chain(). client_auth_partial_chain(Config) when is_list(Config) -> ssl_cert_tests:client_auth_partial_chain(Config). %%-------------------------------------------------------------------- client_auth_allow_partial_chain() -> ssl_cert_tests:client_auth_allow_partial_chain(). client_auth_allow_partial_chain(Config) when is_list(Config) -> ssl_cert_tests:client_auth_allow_partial_chain(Config). %%-------------------------------------------------------------------- client_auth_do_not_allow_partial_chain() -> ssl_cert_tests:client_auth_do_not_allow_partial_chain(). client_auth_do_not_allow_partial_chain(Config) when is_list(Config) -> ssl_cert_tests:client_auth_do_not_allow_partial_chain(Config). %%-------------------------------------------------------------------- client_auth_partial_chain_fun_fail() -> ssl_cert_tests:client_auth_partial_chain_fun_fail(). client_auth_partial_chain_fun_fail(Config) when is_list(Config) -> ssl_cert_tests:client_auth_partial_chain_fun_fail(Config). %%-------------------------------------------------------------------- missing_root_cert_no_auth() -> ssl_cert_tests:missing_root_cert_no_auth(). missing_root_cert_no_auth(Config) when is_list(Config) -> ssl_cert_tests:missing_root_cert_no_auth(Config). %%-------------------------------------------------------------------- %% TLS 1.3 Test Cases ------------------------------------------------ %%-------------------------------------------------------------------- hello_retry_request() -> ssl_cert_tests:hello_retry_request(). hello_retry_request(Config) -> ssl_cert_tests:hello_retry_request(Config). %%-------------------------------------------------------------------- custom_groups() -> ssl_cert_tests:custom_groups(). custom_groups(Config) -> ssl_cert_tests:custom_groups(Config). unsupported_sign_algo_cert_client_auth() -> ssl_cert_tests:unsupported_sign_algo_cert_client_auth(). unsupported_sign_algo_cert_client_auth(Config) -> ssl_cert_tests:unsupported_sign_algo_cert_client_auth(Config). unsupported_sign_algo_client_auth() -> ssl_cert_tests:unsupported_sign_algo_client_auth(). unsupported_sign_algo_client_auth(Config) -> ssl_cert_tests:unsupported_sign_algo_client_auth(Config). %%-------------------------------------------------------------------- hello_retry_client_auth() -> ssl_cert_tests:hello_retry_client_auth(). hello_retry_client_auth(Config) -> ssl_cert_tests:hello_retry_client_auth(Config). %%-------------------------------------------------------------------- hello_retry_client_auth_empty_cert_accepted() -> ssl_cert_tests:hello_retry_client_auth_empty_cert_accepted(). hello_retry_client_auth_empty_cert_accepted(Config) -> ssl_cert_tests:hello_retry_client_auth_empty_cert_accepted(Config). %%-------------------------------------------------------------------- hello_retry_client_auth_empty_cert_rejected() -> ssl_cert_tests:hello_retry_client_auth_empty_cert_rejected(). hello_retry_client_auth_empty_cert_rejected(Config) -> ssl_cert_tests:hello_retry_client_auth_empty_cert_rejected(Config).
null
https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/ssl/test/openssl_server_cert_SUITE.erl
erlang
%CopyrightBegin% 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. %CopyrightEnd% Common test Test cases -------------------------------------------------------------------- Common Test interface functions ----------------------------------- -------------------------------------------------------------------- TODO: Create proper conf of openssl server {eddsa_1_3, [], all_version_tests() ++ tls_1_3_tests()} {group, eddsa_1_3} Make sure _rsa* suite is choosen by ssl_test_lib:start_server Make sure _rsa* suite is choosen by ssl_test_lib:start_server Make sure ecdh* suite is choosen by ssl_test_lib:start_server Make sure ecdh* suite is choosen by ssl_test_lib:start_server Make sure dhe_dss* suite is choosen by ssl_test_lib:start_server -------------------------------------------------------------------- Test Cases -------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- TLS 1.3 Test Cases ------------------------------------------------ -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- --------------------------------------------------------------------
Copyright Ericsson AB 2019 - 2019 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(openssl_server_cert_SUITE). -include_lib("common_test/include/ct.hrl"). -include_lib("public_key/include/public_key.hrl"). -export([all/0, groups/0, init_per_suite/1, init_per_group/2, init_per_testcase/2, end_per_suite/1, end_per_group/2, end_per_testcase/2 ]). -export([no_auth/0, no_auth/1, auth/0, auth/1, client_auth_empty_cert_accepted/0, client_auth_empty_cert_accepted/1, client_auth_empty_cert_rejected/0, client_auth_empty_cert_rejected/1, client_auth_partial_chain/0, client_auth_partial_chain/1, client_auth_allow_partial_chain/0, client_auth_allow_partial_chain/1, client_auth_do_not_allow_partial_chain/0, client_auth_do_not_allow_partial_chain/1, client_auth_partial_chain_fun_fail/0, client_auth_partial_chain_fun_fail/1, missing_root_cert_no_auth/0, missing_root_cert_no_auth/1, unsupported_sign_algo_client_auth/0, unsupported_sign_algo_client_auth/1, unsupported_sign_algo_cert_client_auth/0, unsupported_sign_algo_cert_client_auth/1, hello_retry_request/0, hello_retry_request/1, custom_groups/0, custom_groups/1, hello_retry_client_auth/0, hello_retry_client_auth/1, hello_retry_client_auth_empty_cert_accepted/0, hello_retry_client_auth_empty_cert_accepted/1, hello_retry_client_auth_empty_cert_rejected/0, hello_retry_client_auth_empty_cert_rejected/1 ]). all() -> [ {group, openssl_server}]. groups() -> [ {openssl_server, [], protocol_groups()}, {'tlsv1.3', [], tls_1_3_protocol_groups()}, {'tlsv1.2', [], pre_tls_1_3_protocol_groups()}, {'tlsv1.1', [], pre_tls_1_3_protocol_groups()}, {'tlsv1', [], pre_tls_1_3_protocol_groups()}, {'dtlsv1.2', [], pre_tls_1_3_protocol_groups()}, {'dtlsv1', [], pre_tls_1_3_protocol_groups()}, {rsa, [], all_version_tests()}, {ecdsa, [], all_version_tests()}, {dsa, [], all_version_tests()}, {rsa_1_3, [], all_version_tests() ++ tls_1_3_tests()}, + + [ unsupported_sign_algo_client_auth , unsupported_sign_algo_cert_client_auth ] } , {rsa_pss_rsae, [], all_version_tests() ++ tls_1_3_tests()}, {rsa_pss_pss, [], all_version_tests() ++ tls_1_3_tests()}, {ecdsa_1_3, [], all_version_tests() ++ tls_1_3_tests()} Enable test later when we have OpenSSL version that is able to read EDDSA private key files ]. protocol_groups() -> case ssl_test_lib:openssl_sane_dtls() of true -> [{group, 'tlsv1.3'}, {group, 'tlsv1.2'}, {group, 'tlsv1.1'}, {group, 'tlsv1'}, {group, 'dtlsv1.2'}, {group, 'dtlsv1'}]; false -> [{group, 'tlsv1.3'}, {group, 'tlsv1.2'}, {group, 'tlsv1.1'}, {group, 'tlsv1'} ] end. pre_tls_1_3_protocol_groups() -> [{group, rsa}, {group, ecdsa}, {group, dsa}]. tls_1_3_protocol_groups() -> [{group, rsa_1_3}, {group, rsa_pss_rsae}, {group, rsa_pss_pss}, {group, ecdsa_1_3} ]. tls_1_3_tests() -> [ hello_retry_request, custom_groups, hello_retry_client_auth, hello_retry_client_auth_empty_cert_accepted, hello_retry_client_auth_empty_cert_rejected ]. all_version_tests() -> [ no_auth, auth, missing_root_cert_no_auth ]. init_per_suite(Config) -> catch crypto:stop(), try crypto:start() of ok -> ssl_test_lib:clean_start(), Config catch _:_ -> {skip, "Crypto did not start"} end. end_per_suite(_Config) -> ssl:stop(), application:unload(ssl), application:stop(crypto). init_per_group(openssl_server, Config0) -> Config = proplists:delete(server_type, proplists:delete(client_type, Config0)), [{client_type, erlang}, {server_type, openssl} | Config]; init_per_group(rsa = Group, Config0) -> Config = ssl_test_lib:make_rsa_cert(Config0), COpts = proplists:get_value(client_rsa_opts, Config), SOpts = proplists:get_value(server_rsa_opts, Config), Version = ssl_test_lib:protocol_version(Config), Ciphers = ssl_cert_tests:test_ciphers(fun(dhe_rsa) -> true; (ecdhe_rsa) -> true; (_) -> false end, Version), case Ciphers of [_|_] -> [{cert_key_alg, rsa} | lists:delete(cert_key_alg, [{client_cert_opts, [{ciphers, Ciphers} | COpts]}, {server_cert_opts, SOpts} | lists:delete(server_cert_opts, lists:delete(client_cert_opts, Config))])]; [] -> {skip, {no_sup, Group, Version}} end; init_per_group(rsa_1_3 = Group, Config0) -> Config = ssl_test_lib:make_rsa_cert(Config0), COpts = proplists:get_value(client_rsa_opts, Config), SOpts = proplists:get_value(server_rsa_opts, Config), Version = ssl_test_lib:protocol_version(Config), Ciphers = ssl_cert_tests:test_ciphers(undefined, Version), case Ciphers of [_|_] -> [{cert_key_alg, rsa} | lists:delete(cert_key_alg, [{client_cert_opts, [{ciphers, Ciphers} | COpts]}, {server_cert_opts, SOpts} | lists:delete(server_cert_opts, lists:delete(client_cert_opts, Config))])]; [] -> {skip, {no_sup, Group, Version}} end; init_per_group(Alg, Config) when Alg == rsa_pss_rsae; Alg == rsa_pss_pss -> Supports = crypto:supports(), RSAOpts = proplists:get_value(rsa_opts, Supports), case lists:member(rsa_pkcs1_pss_padding, RSAOpts) andalso lists:member(rsa_pss_saltlen, RSAOpts) andalso lists:member(rsa_mgf1_md, RSAOpts) andalso ssl_test_lib:is_sane_oppenssl_pss(Alg) of true -> #{client_config := COpts, server_config := SOpts} = ssl_test_lib:make_rsa_pss_pem(Alg, [], Config, ""), [{cert_key_alg, Alg} | lists:delete(cert_key_alg, [{client_cert_opts, COpts}, {server_cert_opts, SOpts} | lists:delete(server_cert_opts, lists:delete(client_cert_opts, Config))])]; false -> {skip, "Missing crypto or OpenSSL support"} end; init_per_group(ecdsa = Group, Config0) -> PKAlg = crypto:supports(public_keys), case lists:member(ecdsa, PKAlg) andalso (lists:member(ecdh, PKAlg) orelse lists:member(dh, PKAlg)) andalso (ssl_test_lib:openssl_ecdsa_suites() =/= []) of true -> Config = ssl_test_lib:make_ecdsa_cert(Config0), COpts = proplists:get_value(client_ecdsa_opts, Config), SOpts = proplists:get_value(server_ecdsa_opts, Config), Version = ssl_test_lib:protocol_version(Config), Ciphers = ssl_cert_tests:test_ciphers(fun(ecdh_ecdsa) -> true; (ecdhe_ecdsa) -> true; (_) -> false end, Version), case Ciphers of [_|_] -> [{cert_key_alg, ecdsa} | lists:delete(cert_key_alg, [{client_cert_opts, [{ciphers, Ciphers} | COpts]}, {server_cert_opts, SOpts} | lists:delete(server_cert_opts, lists:delete(client_cert_opts, Config))] )]; [] -> {skip, {no_sup, Group, Version}} end; false -> {skip, "Missing EC crypto support"} end; init_per_group(ecdsa_1_3 = Group, Config0) -> PKAlg = crypto:supports(public_keys), case lists:member(ecdsa, PKAlg) andalso (lists:member(ecdh, PKAlg) orelse lists:member(dh, PKAlg)) andalso (ssl_test_lib:openssl_ecdsa_suites() =/= []) of true -> Config = ssl_test_lib:make_ecdsa_cert(Config0), COpts = proplists:get_value(client_ecdsa_opts, Config), SOpts = proplists:get_value(server_ecdsa_opts, Config), Version = ssl_test_lib:protocol_version(Config), Ciphers = ssl_cert_tests:test_ciphers(undefined, Version), case Ciphers of [_|_] -> [{cert_key_alg, ecdsa} | lists:delete(cert_key_alg, [{client_cert_opts, [{ciphers, Ciphers} | COpts]}, {server_cert_opts, SOpts} | lists:delete(server_cert_opts, lists:delete(client_cert_opts, Config))] )]; [] -> {skip, {no_sup, Group, Version}} end; false -> {skip, "Missing EC crypto support"} end; init_per_group(eddsa_1_3, Config0) -> PKAlg = crypto:supports(public_keys), PrivDir = proplists:get_value(priv_dir, Config0), case lists:member(eddsa, PKAlg) andalso (lists:member(ecdh, PKAlg)) of true -> Conf = public_key:pkix_test_data(#{server_chain => #{root => ssl_test_lib:eddsa_conf(), intermediates => [ssl_test_lib:eddsa_conf()], peer => ssl_test_lib:eddsa_conf()}, client_chain => #{root => ssl_test_lib:eddsa_conf(), intermediates => [ssl_test_lib:eddsa_conf()], peer => ssl_test_lib:eddsa_conf()}}), [{server_config, SOpts}, {client_config, COpts}] = x509_test:gen_pem_config_files(Conf, filename:join(PrivDir, "client_eddsa"), filename:join(PrivDir, "server_eddsa")), [{cert_key_alg, eddsa} | lists:delete(cert_key_alg, [{client_cert_opts, COpts}, {server_cert_opts, SOpts} | lists:delete(server_cert_opts, lists:delete(client_cert_opts, Config0))] )]; false -> {skip, "Missing EC crypto support"} end; init_per_group(dsa = Group, Config0) -> PKAlg = crypto:supports(public_keys), case lists:member(dss, PKAlg) andalso lists:member(dh, PKAlg) andalso (ssl_test_lib:openssl_dsa_suites() =/= []) of true -> Config = ssl_test_lib:make_dsa_cert(Config0), COpts = proplists:get_value(client_dsa_opts, Config), SOpts = proplists:get_value(server_dsa_opts, Config), Version = ssl_test_lib:protocol_version(Config), Ciphers = ssl_cert_tests:test_ciphers(fun(dh_dss) -> true; (dhe_dss) -> true; (_) -> false end, Version), case Ciphers of [_|_] -> [{cert_key_alg, dsa} | lists:delete(cert_key_alg, [{client_cert_opts, [{ciphers, Ciphers} | COpts]}, {server_cert_opts, SOpts} | lists:delete(server_cert_opts, lists:delete(client_cert_opts, Config))])]; [] -> {skip, {no_sup, Group, Version}} end; false -> {skip, "Missing DSS crypto support"} end; init_per_group(GroupName, Config) -> ssl_test_lib:init_per_group_openssl(GroupName, Config). end_per_group(GroupName, Config) -> ssl_test_lib:end_per_group(GroupName, Config). init_per_testcase(_TestCase, Config) -> ssl_test_lib:ct_log_supported_protocol_versions(Config), ct:timetrap({seconds, 30}), Config. end_per_testcase(_TestCase, Config) -> Config. no_auth() -> ssl_cert_tests:no_auth(). no_auth(Config) -> ssl_cert_tests:no_auth(Config). auth() -> ssl_cert_tests:auth(). auth(Config) -> ssl_cert_tests:auth(Config). client_auth_empty_cert_accepted() -> ssl_cert_tests:client_auth_empty_cert_accepted(). client_auth_empty_cert_accepted(Config) -> ssl_cert_tests:client_auth_empty_cert_accepted(Config). client_auth_empty_cert_rejected() -> ssl_cert_tests:client_auth_empty_cert_rejected(). client_auth_empty_cert_rejected(Config) -> ssl_cert_tests:client_auth_empty_cert_rejected(Config). client_auth_partial_chain() -> ssl_cert_tests:client_auth_partial_chain(). client_auth_partial_chain(Config) when is_list(Config) -> ssl_cert_tests:client_auth_partial_chain(Config). client_auth_allow_partial_chain() -> ssl_cert_tests:client_auth_allow_partial_chain(). client_auth_allow_partial_chain(Config) when is_list(Config) -> ssl_cert_tests:client_auth_allow_partial_chain(Config). client_auth_do_not_allow_partial_chain() -> ssl_cert_tests:client_auth_do_not_allow_partial_chain(). client_auth_do_not_allow_partial_chain(Config) when is_list(Config) -> ssl_cert_tests:client_auth_do_not_allow_partial_chain(Config). client_auth_partial_chain_fun_fail() -> ssl_cert_tests:client_auth_partial_chain_fun_fail(). client_auth_partial_chain_fun_fail(Config) when is_list(Config) -> ssl_cert_tests:client_auth_partial_chain_fun_fail(Config). missing_root_cert_no_auth() -> ssl_cert_tests:missing_root_cert_no_auth(). missing_root_cert_no_auth(Config) when is_list(Config) -> ssl_cert_tests:missing_root_cert_no_auth(Config). hello_retry_request() -> ssl_cert_tests:hello_retry_request(). hello_retry_request(Config) -> ssl_cert_tests:hello_retry_request(Config). custom_groups() -> ssl_cert_tests:custom_groups(). custom_groups(Config) -> ssl_cert_tests:custom_groups(Config). unsupported_sign_algo_cert_client_auth() -> ssl_cert_tests:unsupported_sign_algo_cert_client_auth(). unsupported_sign_algo_cert_client_auth(Config) -> ssl_cert_tests:unsupported_sign_algo_cert_client_auth(Config). unsupported_sign_algo_client_auth() -> ssl_cert_tests:unsupported_sign_algo_client_auth(). unsupported_sign_algo_client_auth(Config) -> ssl_cert_tests:unsupported_sign_algo_client_auth(Config). hello_retry_client_auth() -> ssl_cert_tests:hello_retry_client_auth(). hello_retry_client_auth(Config) -> ssl_cert_tests:hello_retry_client_auth(Config). hello_retry_client_auth_empty_cert_accepted() -> ssl_cert_tests:hello_retry_client_auth_empty_cert_accepted(). hello_retry_client_auth_empty_cert_accepted(Config) -> ssl_cert_tests:hello_retry_client_auth_empty_cert_accepted(Config). hello_retry_client_auth_empty_cert_rejected() -> ssl_cert_tests:hello_retry_client_auth_empty_cert_rejected(). hello_retry_client_auth_empty_cert_rejected(Config) -> ssl_cert_tests:hello_retry_client_auth_empty_cert_rejected(Config).