_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
124433eb820514f84e6c95f053adb153167461d5b3b7bed121f1494f400a5c6e
erlang/corba
data_types_SUITE.erl
%%----------------------------------------------------------------- %% %% %CopyrightBegin% %% Copyright Ericsson AB 2002 - 2016 . 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% %% %% %%----------------------------------------------------------------- %% File : data_types_SUITE.erl %% Purpose : %%----------------------------------------------------------------- -module(data_types_SUITE). -include_lib("common_test/include/ct.hrl"). -include_lib("orber/include/corba.hrl"). -define(default_timeout, test_server:minutes(3)). -define(match(ExpectedRes, Expr), fun() -> AcTuAlReS = (catch (Expr)), case AcTuAlReS of ExpectedRes -> io:format("------ CORRECT RESULT ------~n~p~n", [AcTuAlReS]), AcTuAlReS; _ -> io:format("###### ERROR ERROR ######~n~p~n", [AcTuAlReS]), exit(AcTuAlReS) end end()). %%----------------------------------------------------------------- %% External exports %%----------------------------------------------------------------- -export([all/0, suite/0,groups/0,init_per_suite/1, end_per_suite/1, init_per_group/2,end_per_group/2]). %%----------------------------------------------------------------- %% Internal exports %%----------------------------------------------------------------- -compile(export_all). %%----------------------------------------------------------------- %% Func: all/1 : %% Returns: %%----------------------------------------------------------------- suite() -> [{ct_hooks,[ts_install_cth]}]. all() -> [fixed_type, any_type]. groups() -> []. init_per_suite(Config) -> Config. end_per_suite(_Config) -> ok. init_per_group(_GroupName, Config) -> Config. end_per_group(_GroupName, Config) -> Config. %%----------------------------------------------------------------- Init and cleanup functions . %%----------------------------------------------------------------- init_per_testcase(_Case, Config) -> Path = code:which(?MODULE), code:add_pathz(filename:join(filename:dirname(Path), "idl_output")), Dog=test_server:timetrap(?default_timeout), [{watchdog, Dog}|Config]. end_per_testcase(_Case, Config) -> Path = code:which(?MODULE), code:del_path(filename:join(filename:dirname(Path), "idl_output")), Dog = proplists:get_value(watchdog, Config), test_server:timetrap_cancel(Dog), ok. %%----------------------------------------------------------------- Test Case : Fixed %% Description: %%----------------------------------------------------------------- fixed_type(_) -> Val1 = ?match({fixed,3,2,314}, orber_test_server:val1()), _Val2 = ?match({fixed,3,2,314}, orber_test_server:val2()), _Val3 = ?match({fixed,3,2,314}, orber_test_server:val3()), Val4 = ?match({fixed,3,2,314}, orber_test_server:val4()), Val5 = ?match({fixed,2,2,14}, orber_test_server:val5()), _Val6 = ?match({fixed,1,0,3}, orber_test_server:val6()), Val7 = ?match({fixed,2,2,-14}, orber_test_server:val7()), _Val8 = ?match({fixed,1,0,-3}, orber_test_server:val8()), Val9 = ?match({fixed,3,2,328}, orber_test_server:val9()), Val10 = ?match({fixed,4,4,4396}, orber_test_server:val10()), Val11 = ?match({fixed,31,29,2242857142857142857142857142857}, orber_test_server:val11()), Val12 = ?match({fixed,9,6,123140001}, orber_test_server:val12()), Val13 = ?match({fixed,9,1,123140001}, orber_test_server:val13()), Val14 = ?match({fixed,14,6,-12313876959999}, orber_test_server:val14()), Val15 = ?match({fixed,14,6,12314123240001}, orber_test_server:val15()), Val16 = ?match({fixed,17,7,15163459846280001}, orber_test_server:val16()), _Val17 = ?match({fixed,3,2,402}, orber_test_server:val17()), _Val18 = ?match({fixed,5,4,40401}, orber_test_server:val18()), _Val19 = ?match({fixed,3,0,200}, orber_test_server:val19()), Val20 = ?match({fixed,31,0,1999999999999999999999999999999}, orber_test_server:val20()), Val21 = ?match({fixed,1,0,0}, orber_test_server:val21()), Val22 = ?match({fixed,31,0,9999999999999999999999999999998}, orber_test_server:val22()), Val23 = ?match({fixed,1,0,1}, orber_test_server:val23()), _Val24 = ?match({fixed,5,0,19998}, orber_test_server:val24()), _Val25 = ?match({fixed,2,0,40}, orber_test_server:val25()), Val26 = ?match({fixed,31,0,9999999999999999999999999999999}, orber_test_server:val26()), ?match(Val1, fixed:create(3,2,314)), Val27 = ?match({fixed,6,2,314}, fixed:create(6,2,314)), ?match({tk_fixed,3,2}, fixed:get_typecode(Val1)), ?match({tk_fixed,6,2}, fixed:get_typecode(Val27)), ?match({'EXCEPTION',{'BAD_PARAM',_,_,_}}, fixed:create(3,2,3140)), ?match({'EXCEPTION',{'BAD_PARAM',_,_,_}}, fixed:create(5,6,314)), ?match({'EXCEPTION',{'BAD_PARAM',_,_,_}}, fixed:create(32,2,314)), ?match(Val10, fixed:multiply(Val4, Val5)), ?match(Val16, fixed:multiply(Val12, Val13)), ?match(Val22, fixed:multiply(Val26, Val26)), ?match(Val9, fixed:add(Val4, Val5)), ?match(Val15, fixed:add(Val12, Val13)), ?match(Val20, fixed:add(Val26, Val26)), ?match(Val11, fixed:divide(Val4, Val5)), ?match(Val23, fixed:divide(Val26, Val26)), ?match(Val14, fixed:subtract(Val12, Val13)), ?match(Val21, fixed:subtract(Val26, Val26)), ?match(Val7, fixed:unary_minus(Val5)), ?match(Val5, fixed:unary_minus(Val7)), ok. %%----------------------------------------------------------------- %% Test Case: Any type %% Description: %%----------------------------------------------------------------- any_type(_) -> ?match(#any{typecode=undefined, value=undefined}, any:create()), ?match(#any{typecode=tk_short, value=undefined}, any:set_typecode(any:create(), tk_short)), ?match({'EXCEPTION', #'BAD_TYPECODE'{}}, any:set_typecode(any:create(), "wrong")), ?match({'EXCEPTION', #'BAD_TYPECODE'{}}, any:create("wrong", 1)), ?match(#any{typecode=tk_short, value = 1}, any:create(tk_short, 1)), ?match(tk_short, any:get_typecode(any:create(tk_short, 1))), ?match(1, any:get_value(any:create(tk_short, 1))), ?match(#any{typecode=tk_short, value=2}, any:set_value(any:create(tk_short, 1), 2)), ok.
null
https://raw.githubusercontent.com/erlang/corba/396df81473a386d0315bbba830db6f9d4b12a04f/lib/orber/test/data_types_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% ----------------------------------------------------------------- File : data_types_SUITE.erl Purpose : ----------------------------------------------------------------- ----------------------------------------------------------------- External exports ----------------------------------------------------------------- ----------------------------------------------------------------- Internal exports ----------------------------------------------------------------- ----------------------------------------------------------------- Func: all/1 Returns: ----------------------------------------------------------------- ----------------------------------------------------------------- ----------------------------------------------------------------- ----------------------------------------------------------------- Description: ----------------------------------------------------------------- ----------------------------------------------------------------- Test Case: Any type Description: -----------------------------------------------------------------
Copyright Ericsson AB 2002 - 2016 . 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(data_types_SUITE). -include_lib("common_test/include/ct.hrl"). -include_lib("orber/include/corba.hrl"). -define(default_timeout, test_server:minutes(3)). -define(match(ExpectedRes, Expr), fun() -> AcTuAlReS = (catch (Expr)), case AcTuAlReS of ExpectedRes -> io:format("------ CORRECT RESULT ------~n~p~n", [AcTuAlReS]), AcTuAlReS; _ -> io:format("###### ERROR ERROR ######~n~p~n", [AcTuAlReS]), exit(AcTuAlReS) end end()). -export([all/0, suite/0,groups/0,init_per_suite/1, end_per_suite/1, init_per_group/2,end_per_group/2]). -compile(export_all). : suite() -> [{ct_hooks,[ts_install_cth]}]. all() -> [fixed_type, any_type]. groups() -> []. init_per_suite(Config) -> Config. end_per_suite(_Config) -> ok. init_per_group(_GroupName, Config) -> Config. end_per_group(_GroupName, Config) -> Config. Init and cleanup functions . init_per_testcase(_Case, Config) -> Path = code:which(?MODULE), code:add_pathz(filename:join(filename:dirname(Path), "idl_output")), Dog=test_server:timetrap(?default_timeout), [{watchdog, Dog}|Config]. end_per_testcase(_Case, Config) -> Path = code:which(?MODULE), code:del_path(filename:join(filename:dirname(Path), "idl_output")), Dog = proplists:get_value(watchdog, Config), test_server:timetrap_cancel(Dog), ok. Test Case : Fixed fixed_type(_) -> Val1 = ?match({fixed,3,2,314}, orber_test_server:val1()), _Val2 = ?match({fixed,3,2,314}, orber_test_server:val2()), _Val3 = ?match({fixed,3,2,314}, orber_test_server:val3()), Val4 = ?match({fixed,3,2,314}, orber_test_server:val4()), Val5 = ?match({fixed,2,2,14}, orber_test_server:val5()), _Val6 = ?match({fixed,1,0,3}, orber_test_server:val6()), Val7 = ?match({fixed,2,2,-14}, orber_test_server:val7()), _Val8 = ?match({fixed,1,0,-3}, orber_test_server:val8()), Val9 = ?match({fixed,3,2,328}, orber_test_server:val9()), Val10 = ?match({fixed,4,4,4396}, orber_test_server:val10()), Val11 = ?match({fixed,31,29,2242857142857142857142857142857}, orber_test_server:val11()), Val12 = ?match({fixed,9,6,123140001}, orber_test_server:val12()), Val13 = ?match({fixed,9,1,123140001}, orber_test_server:val13()), Val14 = ?match({fixed,14,6,-12313876959999}, orber_test_server:val14()), Val15 = ?match({fixed,14,6,12314123240001}, orber_test_server:val15()), Val16 = ?match({fixed,17,7,15163459846280001}, orber_test_server:val16()), _Val17 = ?match({fixed,3,2,402}, orber_test_server:val17()), _Val18 = ?match({fixed,5,4,40401}, orber_test_server:val18()), _Val19 = ?match({fixed,3,0,200}, orber_test_server:val19()), Val20 = ?match({fixed,31,0,1999999999999999999999999999999}, orber_test_server:val20()), Val21 = ?match({fixed,1,0,0}, orber_test_server:val21()), Val22 = ?match({fixed,31,0,9999999999999999999999999999998}, orber_test_server:val22()), Val23 = ?match({fixed,1,0,1}, orber_test_server:val23()), _Val24 = ?match({fixed,5,0,19998}, orber_test_server:val24()), _Val25 = ?match({fixed,2,0,40}, orber_test_server:val25()), Val26 = ?match({fixed,31,0,9999999999999999999999999999999}, orber_test_server:val26()), ?match(Val1, fixed:create(3,2,314)), Val27 = ?match({fixed,6,2,314}, fixed:create(6,2,314)), ?match({tk_fixed,3,2}, fixed:get_typecode(Val1)), ?match({tk_fixed,6,2}, fixed:get_typecode(Val27)), ?match({'EXCEPTION',{'BAD_PARAM',_,_,_}}, fixed:create(3,2,3140)), ?match({'EXCEPTION',{'BAD_PARAM',_,_,_}}, fixed:create(5,6,314)), ?match({'EXCEPTION',{'BAD_PARAM',_,_,_}}, fixed:create(32,2,314)), ?match(Val10, fixed:multiply(Val4, Val5)), ?match(Val16, fixed:multiply(Val12, Val13)), ?match(Val22, fixed:multiply(Val26, Val26)), ?match(Val9, fixed:add(Val4, Val5)), ?match(Val15, fixed:add(Val12, Val13)), ?match(Val20, fixed:add(Val26, Val26)), ?match(Val11, fixed:divide(Val4, Val5)), ?match(Val23, fixed:divide(Val26, Val26)), ?match(Val14, fixed:subtract(Val12, Val13)), ?match(Val21, fixed:subtract(Val26, Val26)), ?match(Val7, fixed:unary_minus(Val5)), ?match(Val5, fixed:unary_minus(Val7)), ok. any_type(_) -> ?match(#any{typecode=undefined, value=undefined}, any:create()), ?match(#any{typecode=tk_short, value=undefined}, any:set_typecode(any:create(), tk_short)), ?match({'EXCEPTION', #'BAD_TYPECODE'{}}, any:set_typecode(any:create(), "wrong")), ?match({'EXCEPTION', #'BAD_TYPECODE'{}}, any:create("wrong", 1)), ?match(#any{typecode=tk_short, value = 1}, any:create(tk_short, 1)), ?match(tk_short, any:get_typecode(any:create(tk_short, 1))), ?match(1, any:get_value(any:create(tk_short, 1))), ?match(#any{typecode=tk_short, value=2}, any:set_value(any:create(tk_short, 1), 2)), ok.
bd4cec669963eea974945adf8632522f2d00961eace8b58be2d0f8ed1374226c
GaloisInc/LIMA
Types.hs
-- | Module : Language . Copyright : Galois Inc. 2016 -- License : BSD3 -- -- Maintainer : -- Stability : experimental -- Portability : unknown -- Collect common types for the DSL and code generator . -- module Language.LIMA.Types ( UID , Name , Path , Phase(..) ) where type UID = Int -- | A name. type Name = String -- | A hierarchical name. type Path = [Name] -- | A phase is either the minimum phase or the exact phase. data Phase = MinPhase Int | ExactPhase Int deriving (Show)
null
https://raw.githubusercontent.com/GaloisInc/LIMA/8006bb52b2fb5d3264fe55ef8c9b7c89ab7f4630/lima/src/Language/LIMA/Types.hs
haskell
| License : BSD3 Maintainer : Stability : experimental Portability : unknown | A name. | A hierarchical name. | A phase is either the minimum phase or the exact phase.
Module : Language . Copyright : Galois Inc. 2016 Collect common types for the DSL and code generator . module Language.LIMA.Types ( UID , Name , Path , Phase(..) ) where type UID = Int type Name = String type Path = [Name] data Phase = MinPhase Int | ExactPhase Int deriving (Show)
efa91588151107c5dfe817bc1bc897bf5bd3f69d222b083b2d606b0db1deca7c
hoplon/demos
api.clj
(ns app.api (:require [app.datomic-query :refer [fetch-random-data]] [castra.core :refer [defrpc]])) (defrpc get-state [] (fetch-random-data))
null
https://raw.githubusercontent.com/hoplon/demos/50d613892db0624a4f0326c1427d82f5b8e2390f/castra-datomic-free/src/app/api.clj
clojure
(ns app.api (:require [app.datomic-query :refer [fetch-random-data]] [castra.core :refer [defrpc]])) (defrpc get-state [] (fetch-random-data))
0aafb19db8292a076c6a9400e158d0168b5c1f4273356e915163d28ed108027c
emqx/emqx-web-hook
prop_webhook_hooks.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 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(prop_webhook_hooks). -include_lib("proper/include/proper.hrl"). -import(emqx_ct_proper_types, [ conninfo/0 , clientinfo/0 , sessioninfo/0 , message/0 , connack_return_code/0 , topictab/0 , topic/0 , subopts/0 ]). -define(ALL(Vars, Types, Exprs), ?SETUP(fun() -> State = do_setup(), fun() -> do_teardown(State) end end, ?FORALL(Vars, Types, Exprs))). %%-------------------------------------------------------------------- %% Properties %%-------------------------------------------------------------------- prop_client_connect() -> ?ALL({ConnInfo, ConnProps, Env}, {conninfo(), conn_properties(), empty_env()}, begin ok = emqx_web_hook:on_client_connect(ConnInfo, ConnProps, Env), Body = receive_http_request_body(), Body = emqx_json:encode( #{action => client_connect, node => stringfy(node()), clientid => maps:get(clientid, ConnInfo), username => maybe(maps:get(username, ConnInfo)), ipaddress => peer2addr(maps:get(peername, ConnInfo)), keepalive => maps:get(keepalive, ConnInfo), proto_ver => maps:get(proto_ver, ConnInfo) }), true end). prop_client_connack() -> ?ALL({ConnInfo, Rc, AckProps, Env}, {conninfo(), connack_return_code(), ack_properties(), empty_env()}, begin ok = emqx_web_hook:on_client_connack(ConnInfo, Rc, AckProps, Env), Body = receive_http_request_body(), Body = emqx_json:encode( #{action => client_connack, node => stringfy(node()), clientid => maps:get(clientid, ConnInfo), username => maybe(maps:get(username, ConnInfo)), ipaddress => peer2addr(maps:get(peername, ConnInfo)), keepalive => maps:get(keepalive, ConnInfo), proto_ver => maps:get(proto_ver, ConnInfo), conn_ack => Rc }), true end). prop_client_connected() -> ?ALL({ClientInfo, ConnInfo, Env}, {clientinfo(), conninfo(), empty_env()}, begin ok = emqx_web_hook:on_client_connected(ClientInfo, ConnInfo, Env), Body = receive_http_request_body(), Body = emqx_json:encode( #{action => client_connected, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), ipaddress => peer2addr(maps:get(peerhost, ClientInfo)), keepalive => maps:get(keepalive, ConnInfo), proto_ver => maps:get(proto_ver, ConnInfo), connected_at => maps:get(connected_at, ConnInfo) }), true end). prop_client_disconnected() -> ?ALL({ClientInfo, Reason, ConnInfo, Env}, {clientinfo(), shutdown_reason(), disconnected_conninfo(), empty_env()}, begin ok = emqx_web_hook:on_client_disconnected(ClientInfo, Reason, ConnInfo, Env), Body = receive_http_request_body(), Body = emqx_json:encode( #{action => client_disconnected, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), disconnected_at => maps:get(disconnected_at, ConnInfo), reason => stringfy(Reason) }), true end). prop_client_subscribe() -> ?ALL({ClientInfo, SubProps, TopicTab, Env}, {clientinfo(), sub_properties(), topictab(), topic_filter_env()}, begin ok = emqx_web_hook:on_client_subscribe(ClientInfo, SubProps, TopicTab, Env), Matched = filter_topictab(TopicTab, Env), lists:foreach(fun({Topic, Opts}) -> Body = receive_http_request_body(), Body = emqx_json:encode( #{action => client_subscribe, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), topic => Topic, opts => Opts}) end, Matched), true end). prop_client_unsubscribe() -> ?ALL({ClientInfo, SubProps, TopicTab, Env}, {clientinfo(), unsub_properties(), topictab(), topic_filter_env()}, begin ok = emqx_web_hook:on_client_unsubscribe(ClientInfo, SubProps, TopicTab, Env), Matched = filter_topictab(TopicTab, Env), lists:foreach(fun({Topic, Opts}) -> Body = receive_http_request_body(), Body = emqx_json:encode( #{action => client_unsubscribe, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), topic => Topic, opts => Opts}) end, Matched), true end). prop_session_subscribed() -> ?ALL({ClientInfo, Topic, SubOpts, Env}, {clientinfo(), topic(), subopts(), topic_filter_env()}, begin ok = emqx_web_hook:on_session_subscribed(ClientInfo, Topic, SubOpts, Env), filter_topic_match(Topic, Env) andalso begin Body = receive_http_request_body(), Body1 = emqx_json:encode( #{action => session_subscribed, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), topic => Topic, opts => SubOpts }), Body = Body1 end, true end). prop_session_unsubscribed() -> ?ALL({ClientInfo, Topic, SubOpts, Env}, {clientinfo(), topic(), subopts(), empty_env()}, begin ok = emqx_web_hook:on_session_unsubscribed(ClientInfo, Topic, SubOpts, Env), filter_topic_match(Topic, Env) andalso begin Body = receive_http_request_body(), Body = emqx_json:encode( #{action => session_unsubscribed, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), topic => Topic }) end, true end). prop_session_terminated() -> ?ALL({ClientInfo, Reason, SessInfo, Env}, {clientinfo(), shutdown_reason(), sessioninfo(), empty_env()}, begin ok = emqx_web_hook:on_session_terminated(ClientInfo, Reason, SessInfo, Env), Body = receive_http_request_body(), Body = emqx_json:encode( #{action => session_terminated, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), reason => stringfy(Reason) }), true end). prop_message_publish() -> ?ALL({Msg, Env, Encode}, {message(), topic_filter_env(), payload_encode()}, begin application:set_env(emqx_web_hook, encode_payload, Encode), {ok, Msg} = emqx_web_hook:on_message_publish(Msg, Env), application:unset_env(emqx_web_hook, encode_payload), (not emqx_message:is_sys(Msg)) andalso filter_topic_match(emqx_message:topic(Msg), Env) andalso begin Body = receive_http_request_body(), Body = emqx_json:encode( #{action => message_publish, node => stringfy(node()), from_client_id => emqx_message:from(Msg), from_username => maybe(emqx_message:get_header(username, Msg)), topic => emqx_message:topic(Msg), qos => emqx_message:qos(Msg), retain => emqx_message:get_flag(retain, Msg), payload => encode(emqx_message:payload(Msg), Encode), ts => emqx_message:timestamp(Msg) }) end, true end). prop_message_delivered() -> ?ALL({ClientInfo, Msg, Env, Encode}, {clientinfo(), message(), topic_filter_env(), payload_encode()}, begin application:set_env(emqx_web_hook, encode_payload, Encode), ok = emqx_web_hook:on_message_delivered(ClientInfo, Msg, Env), application:unset_env(emqx_web_hook, encode_payload), (not emqx_message:is_sys(Msg)) andalso filter_topic_match(emqx_message:topic(Msg), Env) andalso begin Body = receive_http_request_body(), Body = emqx_json:encode( #{action => message_delivered, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), from_client_id => emqx_message:from(Msg), from_username => maybe(emqx_message:get_header(username, Msg)), topic => emqx_message:topic(Msg), qos => emqx_message:qos(Msg), retain => emqx_message:get_flag(retain, Msg), payload => encode(emqx_message:payload(Msg), Encode), ts => emqx_message:timestamp(Msg) }) end, true end). prop_message_acked() -> ?ALL({ClientInfo, Msg, Env, Encode}, {clientinfo(), message(), empty_env(), payload_encode()}, begin application:set_env(emqx_web_hook, encode_payload, Encode), ok = emqx_web_hook:on_message_acked(ClientInfo, Msg, Env), application:unset_env(emqx_web_hook, encode_payload), (not emqx_message:is_sys(Msg)) andalso filter_topic_match(emqx_message:topic(Msg), Env) andalso begin Body = receive_http_request_body(), Body = emqx_json:encode( #{action => message_acked, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), from_client_id => emqx_message:from(Msg), from_username => maybe(emqx_message:get_header(username, Msg)), topic => emqx_message:topic(Msg), qos => emqx_message:qos(Msg), retain => emqx_message:get_flag(retain, Msg), payload => encode(emqx_message:payload(Msg), Encode), ts => emqx_message:timestamp(Msg) }) end, true end). %%-------------------------------------------------------------------- %% Helper %%-------------------------------------------------------------------- do_setup() -> %% Pre-defined envs application:set_env(emqx_web_hook, path, "path"), application:set_env(emqx_web_hook, headers, []), meck:new(ehttpc_pool, [passthrough, no_history]), meck:expect(ehttpc_pool, pick_worker, fun(_, _) -> ok end), Self = self(), meck:new(ehttpc, [passthrough, no_history]), meck:expect(ehttpc, request, fun(_ClientId, Method, {Path, Headers, Body}) -> Self ! {Method, Path, Headers, Body}, {ok, ok, ok} end), meck:new(emqx_metrics, [passthrough, no_history]), meck:expect(emqx_metrics, inc, fun(_) -> ok end), ok. do_teardown(_) -> meck:unload(ehttpc_pool), meck:unload(ehttpc), meck:unload(emqx_metrics). maybe(undefined) -> null; maybe(T) -> T. peer2addr({Host, _}) -> list_to_binary(inet:ntoa(Host)); peer2addr(Host) -> list_to_binary(inet:ntoa(Host)). ensure_to_binary(Atom) when is_atom(Atom) -> atom_to_binary(Atom, utf8); ensure_to_binary(Bin) when is_binary(Bin) -> Bin. stringfy({shutdown, Reason}) -> stringfy(Reason); stringfy(Term) when is_atom(Term); is_binary(Term) -> Term; stringfy(Term) -> unicode:characters_to_binary(io_lib:format("~0p", [Term])). receive_http_request_body() -> receive {post, _, _, Body} -> Body after 100 -> exit(waiting_message_timeout) end. receive_http_request_bodys() -> receive_http_request_bodys_([]). receive_http_request_bodys_(Acc) -> receive {post, _, _, Body} -> receive_http_request_bodys_([Body|Acc]) after 1000 -> lists:reverse(Acc) end. filter_topictab(TopicTab, {undefined}) -> TopicTab; filter_topictab(TopicTab, {TopicFilter}) -> lists:filter(fun({Topic, _}) -> emqx_topic:match(Topic, TopicFilter) end, TopicTab). filter_topic_match(_Topic, {undefined}) -> true; filter_topic_match(Topic, {TopicFilter}) -> emqx_topic:match(Topic, TopicFilter). encode(Bin, base64) -> base64:encode(Bin); encode(Bin, base62) -> emqx_base62:encode(Bin); encode(Bin, _) -> Bin. %%-------------------------------------------------------------------- %% Generators %%-------------------------------------------------------------------- conn_properties() -> #{}. ack_properties() -> #{}. sub_properties() -> #{}. unsub_properties() -> #{}. shutdown_reason() -> oneof([any(), {shutdown, atom()}]). empty_env() -> {undefined}. topic_filter_env() -> oneof([{<<"#">>}, {undefined}, {topic()}]). payload_encode() -> oneof([base62, base64, undefined]). http_code() -> oneof([socket_closed_remotely, others]). disconnected_conninfo() -> ?LET(Info, conninfo(), begin Info#{disconnected_at => erlang:system_time(millisecond)} end).
null
https://raw.githubusercontent.com/emqx/emqx-web-hook/28436cca2735cb4f4c39c64bfcf51e7689e16986/test/props/prop_webhook_hooks.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. -------------------------------------------------------------------- -------------------------------------------------------------------- Properties -------------------------------------------------------------------- -------------------------------------------------------------------- Helper -------------------------------------------------------------------- Pre-defined envs -------------------------------------------------------------------- Generators --------------------------------------------------------------------
Copyright ( c ) 2020 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(prop_webhook_hooks). -include_lib("proper/include/proper.hrl"). -import(emqx_ct_proper_types, [ conninfo/0 , clientinfo/0 , sessioninfo/0 , message/0 , connack_return_code/0 , topictab/0 , topic/0 , subopts/0 ]). -define(ALL(Vars, Types, Exprs), ?SETUP(fun() -> State = do_setup(), fun() -> do_teardown(State) end end, ?FORALL(Vars, Types, Exprs))). prop_client_connect() -> ?ALL({ConnInfo, ConnProps, Env}, {conninfo(), conn_properties(), empty_env()}, begin ok = emqx_web_hook:on_client_connect(ConnInfo, ConnProps, Env), Body = receive_http_request_body(), Body = emqx_json:encode( #{action => client_connect, node => stringfy(node()), clientid => maps:get(clientid, ConnInfo), username => maybe(maps:get(username, ConnInfo)), ipaddress => peer2addr(maps:get(peername, ConnInfo)), keepalive => maps:get(keepalive, ConnInfo), proto_ver => maps:get(proto_ver, ConnInfo) }), true end). prop_client_connack() -> ?ALL({ConnInfo, Rc, AckProps, Env}, {conninfo(), connack_return_code(), ack_properties(), empty_env()}, begin ok = emqx_web_hook:on_client_connack(ConnInfo, Rc, AckProps, Env), Body = receive_http_request_body(), Body = emqx_json:encode( #{action => client_connack, node => stringfy(node()), clientid => maps:get(clientid, ConnInfo), username => maybe(maps:get(username, ConnInfo)), ipaddress => peer2addr(maps:get(peername, ConnInfo)), keepalive => maps:get(keepalive, ConnInfo), proto_ver => maps:get(proto_ver, ConnInfo), conn_ack => Rc }), true end). prop_client_connected() -> ?ALL({ClientInfo, ConnInfo, Env}, {clientinfo(), conninfo(), empty_env()}, begin ok = emqx_web_hook:on_client_connected(ClientInfo, ConnInfo, Env), Body = receive_http_request_body(), Body = emqx_json:encode( #{action => client_connected, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), ipaddress => peer2addr(maps:get(peerhost, ClientInfo)), keepalive => maps:get(keepalive, ConnInfo), proto_ver => maps:get(proto_ver, ConnInfo), connected_at => maps:get(connected_at, ConnInfo) }), true end). prop_client_disconnected() -> ?ALL({ClientInfo, Reason, ConnInfo, Env}, {clientinfo(), shutdown_reason(), disconnected_conninfo(), empty_env()}, begin ok = emqx_web_hook:on_client_disconnected(ClientInfo, Reason, ConnInfo, Env), Body = receive_http_request_body(), Body = emqx_json:encode( #{action => client_disconnected, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), disconnected_at => maps:get(disconnected_at, ConnInfo), reason => stringfy(Reason) }), true end). prop_client_subscribe() -> ?ALL({ClientInfo, SubProps, TopicTab, Env}, {clientinfo(), sub_properties(), topictab(), topic_filter_env()}, begin ok = emqx_web_hook:on_client_subscribe(ClientInfo, SubProps, TopicTab, Env), Matched = filter_topictab(TopicTab, Env), lists:foreach(fun({Topic, Opts}) -> Body = receive_http_request_body(), Body = emqx_json:encode( #{action => client_subscribe, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), topic => Topic, opts => Opts}) end, Matched), true end). prop_client_unsubscribe() -> ?ALL({ClientInfo, SubProps, TopicTab, Env}, {clientinfo(), unsub_properties(), topictab(), topic_filter_env()}, begin ok = emqx_web_hook:on_client_unsubscribe(ClientInfo, SubProps, TopicTab, Env), Matched = filter_topictab(TopicTab, Env), lists:foreach(fun({Topic, Opts}) -> Body = receive_http_request_body(), Body = emqx_json:encode( #{action => client_unsubscribe, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), topic => Topic, opts => Opts}) end, Matched), true end). prop_session_subscribed() -> ?ALL({ClientInfo, Topic, SubOpts, Env}, {clientinfo(), topic(), subopts(), topic_filter_env()}, begin ok = emqx_web_hook:on_session_subscribed(ClientInfo, Topic, SubOpts, Env), filter_topic_match(Topic, Env) andalso begin Body = receive_http_request_body(), Body1 = emqx_json:encode( #{action => session_subscribed, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), topic => Topic, opts => SubOpts }), Body = Body1 end, true end). prop_session_unsubscribed() -> ?ALL({ClientInfo, Topic, SubOpts, Env}, {clientinfo(), topic(), subopts(), empty_env()}, begin ok = emqx_web_hook:on_session_unsubscribed(ClientInfo, Topic, SubOpts, Env), filter_topic_match(Topic, Env) andalso begin Body = receive_http_request_body(), Body = emqx_json:encode( #{action => session_unsubscribed, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), topic => Topic }) end, true end). prop_session_terminated() -> ?ALL({ClientInfo, Reason, SessInfo, Env}, {clientinfo(), shutdown_reason(), sessioninfo(), empty_env()}, begin ok = emqx_web_hook:on_session_terminated(ClientInfo, Reason, SessInfo, Env), Body = receive_http_request_body(), Body = emqx_json:encode( #{action => session_terminated, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), reason => stringfy(Reason) }), true end). prop_message_publish() -> ?ALL({Msg, Env, Encode}, {message(), topic_filter_env(), payload_encode()}, begin application:set_env(emqx_web_hook, encode_payload, Encode), {ok, Msg} = emqx_web_hook:on_message_publish(Msg, Env), application:unset_env(emqx_web_hook, encode_payload), (not emqx_message:is_sys(Msg)) andalso filter_topic_match(emqx_message:topic(Msg), Env) andalso begin Body = receive_http_request_body(), Body = emqx_json:encode( #{action => message_publish, node => stringfy(node()), from_client_id => emqx_message:from(Msg), from_username => maybe(emqx_message:get_header(username, Msg)), topic => emqx_message:topic(Msg), qos => emqx_message:qos(Msg), retain => emqx_message:get_flag(retain, Msg), payload => encode(emqx_message:payload(Msg), Encode), ts => emqx_message:timestamp(Msg) }) end, true end). prop_message_delivered() -> ?ALL({ClientInfo, Msg, Env, Encode}, {clientinfo(), message(), topic_filter_env(), payload_encode()}, begin application:set_env(emqx_web_hook, encode_payload, Encode), ok = emqx_web_hook:on_message_delivered(ClientInfo, Msg, Env), application:unset_env(emqx_web_hook, encode_payload), (not emqx_message:is_sys(Msg)) andalso filter_topic_match(emqx_message:topic(Msg), Env) andalso begin Body = receive_http_request_body(), Body = emqx_json:encode( #{action => message_delivered, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), from_client_id => emqx_message:from(Msg), from_username => maybe(emqx_message:get_header(username, Msg)), topic => emqx_message:topic(Msg), qos => emqx_message:qos(Msg), retain => emqx_message:get_flag(retain, Msg), payload => encode(emqx_message:payload(Msg), Encode), ts => emqx_message:timestamp(Msg) }) end, true end). prop_message_acked() -> ?ALL({ClientInfo, Msg, Env, Encode}, {clientinfo(), message(), empty_env(), payload_encode()}, begin application:set_env(emqx_web_hook, encode_payload, Encode), ok = emqx_web_hook:on_message_acked(ClientInfo, Msg, Env), application:unset_env(emqx_web_hook, encode_payload), (not emqx_message:is_sys(Msg)) andalso filter_topic_match(emqx_message:topic(Msg), Env) andalso begin Body = receive_http_request_body(), Body = emqx_json:encode( #{action => message_acked, node => stringfy(node()), clientid => maps:get(clientid, ClientInfo), username => maybe(maps:get(username, ClientInfo)), from_client_id => emqx_message:from(Msg), from_username => maybe(emqx_message:get_header(username, Msg)), topic => emqx_message:topic(Msg), qos => emqx_message:qos(Msg), retain => emqx_message:get_flag(retain, Msg), payload => encode(emqx_message:payload(Msg), Encode), ts => emqx_message:timestamp(Msg) }) end, true end). do_setup() -> application:set_env(emqx_web_hook, path, "path"), application:set_env(emqx_web_hook, headers, []), meck:new(ehttpc_pool, [passthrough, no_history]), meck:expect(ehttpc_pool, pick_worker, fun(_, _) -> ok end), Self = self(), meck:new(ehttpc, [passthrough, no_history]), meck:expect(ehttpc, request, fun(_ClientId, Method, {Path, Headers, Body}) -> Self ! {Method, Path, Headers, Body}, {ok, ok, ok} end), meck:new(emqx_metrics, [passthrough, no_history]), meck:expect(emqx_metrics, inc, fun(_) -> ok end), ok. do_teardown(_) -> meck:unload(ehttpc_pool), meck:unload(ehttpc), meck:unload(emqx_metrics). maybe(undefined) -> null; maybe(T) -> T. peer2addr({Host, _}) -> list_to_binary(inet:ntoa(Host)); peer2addr(Host) -> list_to_binary(inet:ntoa(Host)). ensure_to_binary(Atom) when is_atom(Atom) -> atom_to_binary(Atom, utf8); ensure_to_binary(Bin) when is_binary(Bin) -> Bin. stringfy({shutdown, Reason}) -> stringfy(Reason); stringfy(Term) when is_atom(Term); is_binary(Term) -> Term; stringfy(Term) -> unicode:characters_to_binary(io_lib:format("~0p", [Term])). receive_http_request_body() -> receive {post, _, _, Body} -> Body after 100 -> exit(waiting_message_timeout) end. receive_http_request_bodys() -> receive_http_request_bodys_([]). receive_http_request_bodys_(Acc) -> receive {post, _, _, Body} -> receive_http_request_bodys_([Body|Acc]) after 1000 -> lists:reverse(Acc) end. filter_topictab(TopicTab, {undefined}) -> TopicTab; filter_topictab(TopicTab, {TopicFilter}) -> lists:filter(fun({Topic, _}) -> emqx_topic:match(Topic, TopicFilter) end, TopicTab). filter_topic_match(_Topic, {undefined}) -> true; filter_topic_match(Topic, {TopicFilter}) -> emqx_topic:match(Topic, TopicFilter). encode(Bin, base64) -> base64:encode(Bin); encode(Bin, base62) -> emqx_base62:encode(Bin); encode(Bin, _) -> Bin. conn_properties() -> #{}. ack_properties() -> #{}. sub_properties() -> #{}. unsub_properties() -> #{}. shutdown_reason() -> oneof([any(), {shutdown, atom()}]). empty_env() -> {undefined}. topic_filter_env() -> oneof([{<<"#">>}, {undefined}, {topic()}]). payload_encode() -> oneof([base62, base64, undefined]). http_code() -> oneof([socket_closed_remotely, others]). disconnected_conninfo() -> ?LET(Info, conninfo(), begin Info#{disconnected_at => erlang:system_time(millisecond)} end).
50e6fd7988bec33edd723d54abd3b0ae27b646137c269d37f1ae2221c61b5889
rcherrueau/APE
lang.rkt
#lang racket/base ;; ,-,-,-. ;; `,| | | ,-. . . ,-. ,-. . . ,-. ,-. ;; | ; | . ,-| | | | ,-| | | | | | ;; ' `-' `-^ `-^ `-' `-^ `-^ `-' `-' ;; Ownership Types Checker. ;; ;; Naming conventions: - X , Y , FOO ( ie , uppercase variables ) and ` stx ' are syntax objects ;; - XS (with an uppercase "S" at the end) is a syntax list of syntax ;; objects, e.g., #'(a b c 1 v) ;; - Xs (with a small "s" at the end) is a list of syntax objects, e.g. , ( list # ' a # ' b # ' c # ' 1 # ' v ) ;; - t^ is the ownership scheme of t ;; ;; Phases: ;; - Desugaring phase (ir>) :: Transforms the surface syntax into an ;; Intermediate Representation. ;; - Meta phase (M>) :: Collects meta information for later use and ;; checks no duplicate class/field/def names according to [FKF98] ;; (see Bibliography). ;; - Simple type checking (?>) :: Type checks the program for simple ;; types ("simple" as in simply typed λ calculus, i.e., no ;; ownership). Based on [FKF98] (see Bibliography). ;; - Ownership type checking (Θ>) :: Type checks the program for ;; ownership types. Based on [CPN98] (see Bibliography). ;; ;; Global: ;; - meta:CS is the set of defined ownership scheme - meta : FS is the map of fields with ownership type field as value ;; - meta:DS is the map of definitions with return ownership type as ;; value (require "utils.rkt" "check.rkt") (provide (rename-out [lang-read read] [lang-read-syntax read-syntax])) ;; Reader (define (lang-read in) (syntax->datum (lang-read-syntax #f in))) (define (lang-read-syntax source-name in) ;; Check program, return program in intermediate representation and ;; its meta values. (define-values (prog-ir meta:CS meta:FS meta:DS) (check (port->lines-stx source-name in))) ;; Log final AST (log-sclang-debug (stx->string prog-ir #:newline? #f)) ;; Execution #`(module cpn98-lang racket/base ;; #,prog (void))) ;; Profiling lang: ;; ;; Remove compiled directory. Then run with ;; > racket -l errortrace -t lang.rkt ;; ;; (module+ main ;; (require profile) ;; (define ctx-params-example ;; (bytes->path #"/home/rfish/prog/APE/racket/CPN98/examples/ctx-params-example.rkt")) ;; (profile ;; (call-with-input-file ctx-params-example ;; (λ (in) ( read - line in ) ; ; Strip ` # lang ... ` from ` in ` ;; (lang-read-syntax ctx-params-example in))) # : repeat 100 ;; #:use-errortrace? #t) ;; ) ;; See, -exp-lib/at-exp/lang/reader.rkt#L15 ;; (define-values ;; (surface-read surface-read-syntax surface-get-info) ;; (make-meta-reader ;; 'surface-lang ;; "language path" ;; lang-reader-module-paths ;; s-reader TODO ... ) ) ;; Tests (module+ test (require (submod "desugar.rkt" test) (submod "meta.rkt" test) (submod "simply-typed.rkt" test) (submod "ownership.rkt" test))) ;; Bibliography ;; ;; @InProceedings{CPN98, author = { and and } , ;; title = {Ownership Types for Flexible Alias Protection}, booktitle = { Proceedings of the 1998 { ACM } { SIGPLAN } Conference on Object - Oriented Programming Systems , Languages { \ & } Applications { ( OOPSLA } ' 98 ) , Vancouver , British Columbia , Canada , October 18 - 22 , 1998 . } , pages = { 48 - -64 } , year = { 1998 } , ;; url = {}, ;; doi = {10.1145/286936.286947} ;; } ;; ;; @InProceedings{FKF98, author = { and and ;; Felleisen}, title = { Classes and } , booktitle = { { POPL } ' 98 , Proceedings of the 25th { ACM } ;; {SIGPLAN-SIGACT} Symposium on Principles of Programming Languages , San Diego , CA , USA , January 19 - 21 , 1998 } , ;; year = 1998, pages = { 171 - -183 } , doi = { 10.1145/268946.268961 } , ;; url = {}, ;; }
null
https://raw.githubusercontent.com/rcherrueau/APE/8b5302709000bd043b64d46d55642acb34ce5ba7/racket/CPN98/lang.rkt
racket
,-,-,-. `,| | | ,-. . . ,-. ,-. . . ,-. ,-. | ; | . ,-| | | | ,-| | | | | | ' `-' `-^ `-^ `-' `-^ `-^ `-' `-' Ownership Types Checker. Naming conventions: - XS (with an uppercase "S" at the end) is a syntax list of syntax objects, e.g., #'(a b c 1 v) - Xs (with a small "s" at the end) is a list of syntax objects, - t^ is the ownership scheme of t Phases: - Desugaring phase (ir>) :: Transforms the surface syntax into an Intermediate Representation. - Meta phase (M>) :: Collects meta information for later use and checks no duplicate class/field/def names according to [FKF98] (see Bibliography). - Simple type checking (?>) :: Type checks the program for simple types ("simple" as in simply typed λ calculus, i.e., no ownership). Based on [FKF98] (see Bibliography). - Ownership type checking (Θ>) :: Type checks the program for ownership types. Based on [CPN98] (see Bibliography). Global: - meta:CS is the set of defined ownership scheme - meta:DS is the map of definitions with return ownership type as value Reader Check program, return program in intermediate representation and its meta values. Log final AST Execution #,prog Profiling lang: Remove compiled directory. Then run with > racket -l errortrace -t lang.rkt (module+ main (require profile) (define ctx-params-example (bytes->path #"/home/rfish/prog/APE/racket/CPN98/examples/ctx-params-example.rkt")) (profile (call-with-input-file ctx-params-example (λ (in) ; Strip ` # lang ... ` from ` in ` (lang-read-syntax ctx-params-example in))) #:use-errortrace? #t) ) See, -exp-lib/at-exp/lang/reader.rkt#L15 (define-values (surface-read surface-read-syntax surface-get-info) (make-meta-reader 'surface-lang "language path" lang-reader-module-paths s-reader Tests Bibliography @InProceedings{CPN98, title = {Ownership Types for Flexible Alias Protection}, url = {}, doi = {10.1145/286936.286947} } @InProceedings{FKF98, Felleisen}, {SIGPLAN-SIGACT} Symposium on Principles of year = 1998, url = {}, }
#lang racket/base - X , Y , FOO ( ie , uppercase variables ) and ` stx ' are syntax objects e.g. , ( list # ' a # ' b # ' c # ' 1 # ' v ) - meta : FS is the map of fields with ownership type field as value (require "utils.rkt" "check.rkt") (provide (rename-out [lang-read read] [lang-read-syntax read-syntax])) (define (lang-read in) (syntax->datum (lang-read-syntax #f in))) (define (lang-read-syntax source-name in) (define-values (prog-ir meta:CS meta:FS meta:DS) (check (port->lines-stx source-name in))) (log-sclang-debug (stx->string prog-ir #:newline? #f)) #`(module cpn98-lang racket/base (void))) # : repeat 100 TODO ... ) ) (module+ test (require (submod "desugar.rkt" test) (submod "meta.rkt" test) (submod "simply-typed.rkt" test) (submod "ownership.rkt" test))) author = { and and } , booktitle = { Proceedings of the 1998 { ACM } { SIGPLAN } Conference on Object - Oriented Programming Systems , Languages { \ & } Applications { ( OOPSLA } ' 98 ) , Vancouver , British Columbia , Canada , October 18 - 22 , 1998 . } , pages = { 48 - -64 } , year = { 1998 } , author = { and and title = { Classes and } , booktitle = { { POPL } ' 98 , Proceedings of the 25th { ACM } Programming Languages , San Diego , CA , USA , January 19 - 21 , 1998 } , pages = { 171 - -183 } , doi = { 10.1145/268946.268961 } ,
b3ac498a2fdd406e5890bda870157b009332e26058d73dd9eac8ebdc9e61d234
rowangithub/DOrder
selectionsort.ml
let rec getmin xs : int = match xs with | x::xs' -> ( match xs' with | [] -> x | y::ys -> let m = getmin xs' in if (x < m) then x else m) let rec rem_min m xs = match xs with | x :: xs -> if (x = m) then xs else x :: (rem_min m xs) let rec selection_sort xs = match xs with | [] -> [] | x::xs' -> let m = getmin xs in m::(selection_sort (rem_min m xs)) let main () = selection_sort [3; 2; 4; 5; 7; 6] let _ = main ()
null
https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/tests/reachability/selectionsort.ml
ocaml
let rec getmin xs : int = match xs with | x::xs' -> ( match xs' with | [] -> x | y::ys -> let m = getmin xs' in if (x < m) then x else m) let rec rem_min m xs = match xs with | x :: xs -> if (x = m) then xs else x :: (rem_min m xs) let rec selection_sort xs = match xs with | [] -> [] | x::xs' -> let m = getmin xs in m::(selection_sort (rem_min m xs)) let main () = selection_sort [3; 2; 4; 5; 7; 6] let _ = main ()
7a5abe5f165f3d775e1926fa516ac7ba24c8d3321c721e90a36b90c2621ea6cf
xh4/web-toolkit
encode.lisp
(in-package :uri-test) (in-suite :uri-test) (test percent-encode (is (equal nil (uri::percent-encode nil))) (is (equal "%E2%9D%A4" (uri::percent-encode "❤"))) (is (equal "%E7%88%B1" (uri::percent-encode "爱"))) (is (equal "%61%62%63" (uri::percent-encode "abc"))) (is (equal "abc" (uri::percent-encode "abc" :reserve 'uri::alpha-p))) (is (equal "abc%31%32%33" (uri::percent-encode "abc123" :reserve 'uri::alpha-p))) (is (equal "%20" (uri::percent-encode " "))))
null
https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/test/uri/encode.lisp
lisp
(in-package :uri-test) (in-suite :uri-test) (test percent-encode (is (equal nil (uri::percent-encode nil))) (is (equal "%E2%9D%A4" (uri::percent-encode "❤"))) (is (equal "%E7%88%B1" (uri::percent-encode "爱"))) (is (equal "%61%62%63" (uri::percent-encode "abc"))) (is (equal "abc" (uri::percent-encode "abc" :reserve 'uri::alpha-p))) (is (equal "abc%31%32%33" (uri::percent-encode "abc123" :reserve 'uri::alpha-p))) (is (equal "%20" (uri::percent-encode " "))))
17a90db58c9d584b21363f72156e4824a498f06a166610a7b2d9fff1f8d5a9b2
Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library
PaymentFlowsPrivatePaymentMethodsAlipayDetails.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 PaymentFlowsPrivatePaymentMethodsAlipayDetails module StripeAPI.Types.PaymentFlowsPrivatePaymentMethodsAlipayDetails 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.payment_flows_private_payment_methods_alipay_details@ in the specification. data PaymentFlowsPrivatePaymentMethodsAlipayDetails = PaymentFlowsPrivatePaymentMethodsAlipayDetails | buyer_id : Uniquely identifies this particular Alipay account . You can use this attribute to check whether two Alipay accounts are the same . -- -- Constraints: -- * Maximum length of 5000 paymentFlowsPrivatePaymentMethodsAlipayDetailsBuyerId :: (GHC.Maybe.Maybe Data.Text.Internal.Text), | fingerprint : Uniquely identifies this particular Alipay account . You can use this attribute to check whether two Alipay accounts are the same . -- -- Constraints: -- * Maximum length of 5000 paymentFlowsPrivatePaymentMethodsAlipayDetailsFingerprint :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), | : Transaction ID of this particular Alipay transaction . -- -- Constraints: -- * Maximum length of 5000 paymentFlowsPrivatePaymentMethodsAlipayDetailsTransactionId :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)) } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON PaymentFlowsPrivatePaymentMethodsAlipayDetails where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("buyer_id" Data.Aeson.Types.ToJSON..=)) (paymentFlowsPrivatePaymentMethodsAlipayDetailsBuyerId obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("fingerprint" Data.Aeson.Types.ToJSON..=)) (paymentFlowsPrivatePaymentMethodsAlipayDetailsFingerprint obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("transaction_id" Data.Aeson.Types.ToJSON..=)) (paymentFlowsPrivatePaymentMethodsAlipayDetailsTransactionId 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.. ("buyer_id" Data.Aeson.Types.ToJSON..=)) (paymentFlowsPrivatePaymentMethodsAlipayDetailsBuyerId obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("fingerprint" Data.Aeson.Types.ToJSON..=)) (paymentFlowsPrivatePaymentMethodsAlipayDetailsFingerprint obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("transaction_id" Data.Aeson.Types.ToJSON..=)) (paymentFlowsPrivatePaymentMethodsAlipayDetailsTransactionId obj) : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON PaymentFlowsPrivatePaymentMethodsAlipayDetails where parseJSON = Data.Aeson.Types.FromJSON.withObject "PaymentFlowsPrivatePaymentMethodsAlipayDetails" (\obj -> ((GHC.Base.pure PaymentFlowsPrivatePaymentMethodsAlipayDetails GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "buyer_id")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "fingerprint")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "transaction_id")) -- | Create a new 'PaymentFlowsPrivatePaymentMethodsAlipayDetails' with all required fields. mkPaymentFlowsPrivatePaymentMethodsAlipayDetails :: PaymentFlowsPrivatePaymentMethodsAlipayDetails mkPaymentFlowsPrivatePaymentMethodsAlipayDetails = PaymentFlowsPrivatePaymentMethodsAlipayDetails { paymentFlowsPrivatePaymentMethodsAlipayDetailsBuyerId = GHC.Maybe.Nothing, paymentFlowsPrivatePaymentMethodsAlipayDetailsFingerprint = GHC.Maybe.Nothing, paymentFlowsPrivatePaymentMethodsAlipayDetailsTransactionId = GHC.Maybe.Nothing }
null
https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Types/PaymentFlowsPrivatePaymentMethodsAlipayDetails.hs
haskell
# LANGUAGE MultiWayIf # # LANGUAGE OverloadedStrings # | Contains the types generated from the schema PaymentFlowsPrivatePaymentMethodsAlipayDetails | Defines the object schema located at @components.schemas.payment_flows_private_payment_methods_alipay_details@ in the specification. Constraints: Constraints: Constraints: | Create a new 'PaymentFlowsPrivatePaymentMethodsAlipayDetails' with all required fields.
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . module StripeAPI.Types.PaymentFlowsPrivatePaymentMethodsAlipayDetails 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 data PaymentFlowsPrivatePaymentMethodsAlipayDetails = PaymentFlowsPrivatePaymentMethodsAlipayDetails | buyer_id : Uniquely identifies this particular Alipay account . You can use this attribute to check whether two Alipay accounts are the same . * Maximum length of 5000 paymentFlowsPrivatePaymentMethodsAlipayDetailsBuyerId :: (GHC.Maybe.Maybe Data.Text.Internal.Text), | fingerprint : Uniquely identifies this particular Alipay account . You can use this attribute to check whether two Alipay accounts are the same . * Maximum length of 5000 paymentFlowsPrivatePaymentMethodsAlipayDetailsFingerprint :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), | : Transaction ID of this particular Alipay transaction . * Maximum length of 5000 paymentFlowsPrivatePaymentMethodsAlipayDetailsTransactionId :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)) } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON PaymentFlowsPrivatePaymentMethodsAlipayDetails where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("buyer_id" Data.Aeson.Types.ToJSON..=)) (paymentFlowsPrivatePaymentMethodsAlipayDetailsBuyerId obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("fingerprint" Data.Aeson.Types.ToJSON..=)) (paymentFlowsPrivatePaymentMethodsAlipayDetailsFingerprint obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("transaction_id" Data.Aeson.Types.ToJSON..=)) (paymentFlowsPrivatePaymentMethodsAlipayDetailsTransactionId 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.. ("buyer_id" Data.Aeson.Types.ToJSON..=)) (paymentFlowsPrivatePaymentMethodsAlipayDetailsBuyerId obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("fingerprint" Data.Aeson.Types.ToJSON..=)) (paymentFlowsPrivatePaymentMethodsAlipayDetailsFingerprint obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("transaction_id" Data.Aeson.Types.ToJSON..=)) (paymentFlowsPrivatePaymentMethodsAlipayDetailsTransactionId obj) : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON PaymentFlowsPrivatePaymentMethodsAlipayDetails where parseJSON = Data.Aeson.Types.FromJSON.withObject "PaymentFlowsPrivatePaymentMethodsAlipayDetails" (\obj -> ((GHC.Base.pure PaymentFlowsPrivatePaymentMethodsAlipayDetails GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "buyer_id")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "fingerprint")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "transaction_id")) mkPaymentFlowsPrivatePaymentMethodsAlipayDetails :: PaymentFlowsPrivatePaymentMethodsAlipayDetails mkPaymentFlowsPrivatePaymentMethodsAlipayDetails = PaymentFlowsPrivatePaymentMethodsAlipayDetails { paymentFlowsPrivatePaymentMethodsAlipayDetailsBuyerId = GHC.Maybe.Nothing, paymentFlowsPrivatePaymentMethodsAlipayDetailsFingerprint = GHC.Maybe.Nothing, paymentFlowsPrivatePaymentMethodsAlipayDetailsTransactionId = GHC.Maybe.Nothing }
d70b4e7c85ad3241105c13df7f1df1b8dc58d814ffe0150b159ddc58fe3c6846
metaocaml/ber-metaocaml
build_path_prefix_map.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet , INRIA Saclay (* *) Copyright 2017 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. *) (* *) (**************************************************************************) (** Rewrite paths for reproducible builds {b Warning:} this module is unstable and part of {{!Compiler_libs}compiler-libs}. *) type path = string type path_prefix = string type error_message = string val encode_prefix : path_prefix -> string val decode_prefix : string -> (path_prefix, error_message) result type pair = { target: path_prefix; source : path_prefix } val encode_pair : pair -> string val decode_pair : string -> (pair, error_message) result type map = pair option list val encode_map : map -> string val decode_map : string -> (map, error_message) result val rewrite_opt : map -> path -> path option (** [rewrite_opt map path] tries to find a source in [map] that is a prefix of the input [path]. If it succeeds, it replaces this prefix with the corresponding target. If it fails, it just returns [None]. *) val rewrite : map -> path -> path
null
https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/utils/build_path_prefix_map.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. ************************************************************************ * Rewrite paths for reproducible builds {b Warning:} this module is unstable and part of {{!Compiler_libs}compiler-libs}. * [rewrite_opt map path] tries to find a source in [map] that is a prefix of the input [path]. If it succeeds, it replaces this prefix with the corresponding target. If it fails, it just returns [None].
, projet , INRIA Saclay Copyright 2017 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the type path = string type path_prefix = string type error_message = string val encode_prefix : path_prefix -> string val decode_prefix : string -> (path_prefix, error_message) result type pair = { target: path_prefix; source : path_prefix } val encode_pair : pair -> string val decode_pair : string -> (pair, error_message) result type map = pair option list val encode_map : map -> string val decode_map : string -> (map, error_message) result val rewrite_opt : map -> path -> path option val rewrite : map -> path -> path
7f35df43328a47787e7215cb547b72bf3c2703faf5882909b4c956fd698d8b4b
arielnetworks/cl-markup
markup.lisp
(in-package :cl-markup) (defmacro %escape-string-form (val) (let ((val2 (gensym))) `(let ((,val2 ,val)) (if (should-escape-p ,val2) `(escape-string ,,val2) ,val2)))) (defun %dirty-string-form (form) (cond ((consp form) (let ((res (gensym)) (s (gensym)) (r (gensym))) `(let ((,res ,form)) (if (listp ,res) (with-output-to-string (,s) (dolist (,r ,res) (if ,r (write-string ,r ,s)))) (escape-string ,res))))) ((null form) "") ((stringp form) (%escape-string-form form)) ((symbolp form) `(escape-string (ensure-string ,form))) (t (%escape-string-form (format nil "~A" form))))) (defmacro %write-strings (&rest strings) (let ((s (gensym)) (strings (map-group-if #'stringp strings (lambda (&rest args) (apply #'concatenate 'string args))))) `(if *output-stream* (progn ,@(loop for str in strings collect `(write-string ,str *output-stream*))) (with-output-to-string (,s) ,@(loop for str in strings collect `(write-string ,str ,s)))))) (defun tagp (form) (and (consp form) (keywordp (car form)))) (defun parse-tag (tag) (values (pop tag) (loop while (and tag (keywordp (car tag))) collect (pop tag) collect (pop tag)) tag)) (defun attributes->string (attr-plist) (and (consp attr-plist) (butlast (loop for (key val) on attr-plist by #'cddr append `(,(concatenate 'string (string-downcase key) "=\"") ,(%dirty-string-form val) "\"" " "))))) (defun tag->string (tag) (multiple-value-bind (name attr-plist body) (parse-tag tag) (nconc (list (format nil "<~(~A~)" name)) (let ((attr-str (attributes->string attr-plist))) (if attr-str (cons " " attr-str))) (if body (nconc (list ">") (loop for elem in body if (tagp elem) append (tag->string elem) else collect (%dirty-string-form elem)) (list (format nil "</~(~A~)>" name))) (if (or (eq *markup-language* :html) (eq *markup-language* :html5)) (list ">") (list " />")))))) (defun doctype (lang) (case lang (:xml "<?xml version=\"1.0\" encoding=\"UTF-8\"?>") (:html "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"\">") (:html5 "<!DOCTYPE html>") (:xhtml "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"-transitional.dtd\">") (t ""))) (defmacro with-doctype (lang &body body) `(prog2 (eval-when (:compile-toplevel :load-toplevel :execute) (setq *markup-language* ,lang)) (%write-strings ,(doctype lang) ,@(let ((*markup-language* lang)) (loop for b in body append (eval b)))) (eval-when (:compile-toplevel :load-toplevel :execute) (setq *markup-language* :xhtml)))) (defmacro markup (&rest tags) `(%write-strings ,@(loop for tag in tags append (tag->string tag)))) (defun markup* (&rest tags) (eval `(markup ,@tags))) (defmacro html5 (&rest tags) `(with-doctype :html5 (tag->string (cons :html ',tags)))) (defmacro html (&rest tags) `(with-doctype :html (tag->string (cons :html ',tags)))) (defmacro xhtml (&rest tags) `(with-doctype :xhtml (tag->string (cons :html ',tags)))) (defmacro xml (&rest tags) `(with-doctype :xml (loop for tag in ',tags append (tag->string tag))))
null
https://raw.githubusercontent.com/arielnetworks/cl-markup/e0eb7debf4bdff98d1f49d0f811321a6a637b390/src/markup.lisp
lisp
(in-package :cl-markup) (defmacro %escape-string-form (val) (let ((val2 (gensym))) `(let ((,val2 ,val)) (if (should-escape-p ,val2) `(escape-string ,,val2) ,val2)))) (defun %dirty-string-form (form) (cond ((consp form) (let ((res (gensym)) (s (gensym)) (r (gensym))) `(let ((,res ,form)) (if (listp ,res) (with-output-to-string (,s) (dolist (,r ,res) (if ,r (write-string ,r ,s)))) (escape-string ,res))))) ((null form) "") ((stringp form) (%escape-string-form form)) ((symbolp form) `(escape-string (ensure-string ,form))) (t (%escape-string-form (format nil "~A" form))))) (defmacro %write-strings (&rest strings) (let ((s (gensym)) (strings (map-group-if #'stringp strings (lambda (&rest args) (apply #'concatenate 'string args))))) `(if *output-stream* (progn ,@(loop for str in strings collect `(write-string ,str *output-stream*))) (with-output-to-string (,s) ,@(loop for str in strings collect `(write-string ,str ,s)))))) (defun tagp (form) (and (consp form) (keywordp (car form)))) (defun parse-tag (tag) (values (pop tag) (loop while (and tag (keywordp (car tag))) collect (pop tag) collect (pop tag)) tag)) (defun attributes->string (attr-plist) (and (consp attr-plist) (butlast (loop for (key val) on attr-plist by #'cddr append `(,(concatenate 'string (string-downcase key) "=\"") ,(%dirty-string-form val) "\"" " "))))) (defun tag->string (tag) (multiple-value-bind (name attr-plist body) (parse-tag tag) (nconc (list (format nil "<~(~A~)" name)) (let ((attr-str (attributes->string attr-plist))) (if attr-str (cons " " attr-str))) (if body (nconc (list ">") (loop for elem in body if (tagp elem) append (tag->string elem) else collect (%dirty-string-form elem)) (list (format nil "</~(~A~)>" name))) (if (or (eq *markup-language* :html) (eq *markup-language* :html5)) (list ">") (list " />")))))) (defun doctype (lang) (case lang (:xml "<?xml version=\"1.0\" encoding=\"UTF-8\"?>") (:html "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"\">") (:html5 "<!DOCTYPE html>") (:xhtml "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"-transitional.dtd\">") (t ""))) (defmacro with-doctype (lang &body body) `(prog2 (eval-when (:compile-toplevel :load-toplevel :execute) (setq *markup-language* ,lang)) (%write-strings ,(doctype lang) ,@(let ((*markup-language* lang)) (loop for b in body append (eval b)))) (eval-when (:compile-toplevel :load-toplevel :execute) (setq *markup-language* :xhtml)))) (defmacro markup (&rest tags) `(%write-strings ,@(loop for tag in tags append (tag->string tag)))) (defun markup* (&rest tags) (eval `(markup ,@tags))) (defmacro html5 (&rest tags) `(with-doctype :html5 (tag->string (cons :html ',tags)))) (defmacro html (&rest tags) `(with-doctype :html (tag->string (cons :html ',tags)))) (defmacro xhtml (&rest tags) `(with-doctype :xhtml (tag->string (cons :html ',tags)))) (defmacro xml (&rest tags) `(with-doctype :xml (loop for tag in ',tags append (tag->string tag))))
ee06a0184dadc471e8d70a82765ed47ec0aa08c003dbdf5ee9197e3fcec9dda8
racket/drracket
teaching-lang-save-file.rkt
#lang scheme/base (require scheme/file scheme/class scheme/port framework/test framework/preferences) (require tests/drracket/private/drracket-test-util) (fire-up-drracket-and-run-tests (λ () (let* ([drr-frame (wait-for-drracket-frame)] [fn (make-temporary-file "save-teaching-lang-test~a")]) (test:menu-select "File" "New Tab") (let ([definitions-text (send drr-frame get-definitions-text)] [interactions-text (send drr-frame get-interactions-text)]) (set-language-level! (list #rx"Beginning Student$")) (clear-definitions drr-frame) (queue-callback/res (λ () (send definitions-text set-filename fn) (send definitions-text insert "(define (f x) x)\n(f 1)\n"))) (test:menu-select "File" "Save Definitions") (unless (call-with-input-file fn (λ (p) (regexp-match #rx";;[^\n]*metadata" p))) (eprintf "---- saved file, cut here ----\n") (call-with-input-file fn (λ (p) (copy-port p (current-error-port)))) (eprintf "---- saved file, cut here ----\n") (error 'save-teaching-lang-file.rkt "expected the saved file to contain the word 'metadata' in a comment")) (do-execute drr-frame) (test:menu-select "File" (if (eq? (system-type) 'unix) "Close" "Close Tab")) (use-get/put-dialog (λ () (test:menu-select "File" "Open…")) fn) (do-execute drr-frame) (let ([result (fetch-output drr-frame (send interactions-text paragraph-start-position 2) (send interactions-text last-position))]) (test:menu-select "File" (if (eq? (system-type) 'unix) "Close" "Close Tab")) (delete-file fn) (unless (equal? result "1\n> ") (error 'save-teaching-lang-file.rkt "expected the program to produce 1 (followed by the prompt), got ~s" result)))))))
null
https://raw.githubusercontent.com/racket/drracket/2d7c2cded99e630a69f05fb135d1bf7543096a23/drracket-test/tests/drracket/teaching-lang-save-file.rkt
racket
#lang scheme/base (require scheme/file scheme/class scheme/port framework/test framework/preferences) (require tests/drracket/private/drracket-test-util) (fire-up-drracket-and-run-tests (λ () (let* ([drr-frame (wait-for-drracket-frame)] [fn (make-temporary-file "save-teaching-lang-test~a")]) (test:menu-select "File" "New Tab") (let ([definitions-text (send drr-frame get-definitions-text)] [interactions-text (send drr-frame get-interactions-text)]) (set-language-level! (list #rx"Beginning Student$")) (clear-definitions drr-frame) (queue-callback/res (λ () (send definitions-text set-filename fn) (send definitions-text insert "(define (f x) x)\n(f 1)\n"))) (test:menu-select "File" "Save Definitions") (unless (call-with-input-file fn (λ (p) (regexp-match #rx";;[^\n]*metadata" p))) (eprintf "---- saved file, cut here ----\n") (call-with-input-file fn (λ (p) (copy-port p (current-error-port)))) (eprintf "---- saved file, cut here ----\n") (error 'save-teaching-lang-file.rkt "expected the saved file to contain the word 'metadata' in a comment")) (do-execute drr-frame) (test:menu-select "File" (if (eq? (system-type) 'unix) "Close" "Close Tab")) (use-get/put-dialog (λ () (test:menu-select "File" "Open…")) fn) (do-execute drr-frame) (let ([result (fetch-output drr-frame (send interactions-text paragraph-start-position 2) (send interactions-text last-position))]) (test:menu-select "File" (if (eq? (system-type) 'unix) "Close" "Close Tab")) (delete-file fn) (unless (equal? result "1\n> ") (error 'save-teaching-lang-file.rkt "expected the program to produce 1 (followed by the prompt), got ~s" result)))))))
54e65834193b125745cb13cb9f552857e8ead3ee191290cc660496f42bc16efe
ayamada/copy-of-svn.tir.jp
mydbm.scm
#!/usr/local/bin/gosh ;;; coding: euc-jp ;;; -*- scheme -*- ;;; vim:set ft=scheme ts=8 sts=2 sw=2 et: $ Id$ ;;; mydbm client/server module ;;; 仕様: ;;; - keyは文字列のみ固定対応 ;;; - valueはS式のread/writeのみ固定対応? ;;; - serverはsocketで待ち受ける ;;; - 認証は、socketに接続できるか否か、のみとする ;;; 機能: ;;; - ;;; インターフェース: ;;; - (create table) ;;; - (drop table) ;;; - (exists table) ;;; - (copy table) ;;; - (read table key) - ( write table key ) ;;; - (exists table key) ;;; - (delete table key) ;;; - (lock table) ;;; - (lock table write) ;;; - (lock table read) ;;; - (unlock table) ;;; - (unlock) ;;; - (fold table proc knil) ;;; - (for-each table proc) ;;; - (map table proc) ;;; - (flush table) ;;; - (flush&lock table) ToDo : dbmの仕様を満たす事 (define-module tir.mydbm (use srfi-2) ; and-let* (use dbm) (use tir.lock) (export <mydbm-server> mydbm-server-start <mydbm-client> )) (select-module tir.mydbm) (autoload dbm.fsdbm <fsdbm>) (define-class <mydbm-server> () ( (database-dir :accessor database-dir-of :init-keyword :database-dir :init-value #f) ; 必須 (dbm-type :accessor dbm-type-of :init-keyword :dbm-type :init-form <fsdbm>) ;; 以下のようなリストを指定する。 ;; '(unix "/tmp/hoge.sock" [:reuse-addr? flag]) ;; '(inet port-number [:reuse-addr? flag]) ;; '(tcp server-addr port-number [:reuse-addr? flag]) ; 独自拡張。 (socket-spec :accessor socket-spec-of :init-keyword :socket-spec :init-value #f) ; 指定必須 ;; 内部変数用スロット (database-table :accessor database-table-of :init-value (make-hash-table 'eq)) )) (define-method initialize ((self <mydbm-server>) initargs) (next-method) (unless (database-dir-of self) (error "this class must be need to :database-dir")) (unless (socket-spec-of self) (error "this class must be need to :socket-spec")) ) ;;; ---- (define *lockfile* "mydbm.lock") (define-method hoge ((self <mydbm-server>)) #f) ;;; ---- (provide "tir/mydbm")
null
https://raw.githubusercontent.com/ayamada/copy-of-svn.tir.jp/101cd00d595ee7bb96348df54f49707295e9e263/Gauche-tir/branches/Gauche-tir01/trunk/tir/mydbm.scm
scheme
coding: euc-jp -*- scheme -*- vim:set ft=scheme ts=8 sts=2 sw=2 et: mydbm client/server module 仕様: - keyは文字列のみ固定対応 - valueはS式のread/writeのみ固定対応? - serverはsocketで待ち受ける - 認証は、socketに接続できるか否か、のみとする 機能: - インターフェース: - (create table) - (drop table) - (exists table) - (copy table) - (read table key) - (exists table key) - (delete table key) - (lock table) - (lock table write) - (lock table read) - (unlock table) - (unlock) - (fold table proc knil) - (for-each table proc) - (map table proc) - (flush table) - (flush&lock table) and-let* 必須 以下のようなリストを指定する。 '(unix "/tmp/hoge.sock" [:reuse-addr? flag]) '(inet port-number [:reuse-addr? flag]) '(tcp server-addr port-number [:reuse-addr? flag]) ; 独自拡張。 指定必須 内部変数用スロット ---- ----
#!/usr/local/bin/gosh $ Id$ - ( write table key ) ToDo : dbmの仕様を満たす事 (define-module tir.mydbm (use dbm) (use tir.lock) (export <mydbm-server> mydbm-server-start <mydbm-client> )) (select-module tir.mydbm) (autoload dbm.fsdbm <fsdbm>) (define-class <mydbm-server> () ( (database-dir :accessor database-dir-of :init-keyword :database-dir (dbm-type :accessor dbm-type-of :init-keyword :dbm-type :init-form <fsdbm>) (socket-spec :accessor socket-spec-of :init-keyword :socket-spec (database-table :accessor database-table-of :init-value (make-hash-table 'eq)) )) (define-method initialize ((self <mydbm-server>) initargs) (next-method) (unless (database-dir-of self) (error "this class must be need to :database-dir")) (unless (socket-spec-of self) (error "this class must be need to :socket-spec")) ) (define *lockfile* "mydbm.lock") (define-method hoge ((self <mydbm-server>)) #f) (provide "tir/mydbm")
ad428f94df6048855058c12a94de117f015a73425e84f7f17dde1da4bfed26de
clojerl/clojerl
erlang_List_SUITE.erl
-module(erlang_List_SUITE). -include("clojerl.hrl"). -include("clj_test_utils.hrl"). -export([ all/0 , init_per_suite/1 , end_per_suite/1 ]). -export([ new/1 , count/1 , str/1 , is_sequential/1 , get/1 , hash/1 , seq/1 , equiv/1 , cons/1 , stack/1 , to_clj/1 , reduce/1 , complete_coverage/1 ]). -clojure(true). -spec all() -> [atom()]. all() -> clj_test_utils:all(?MODULE). -spec init_per_suite(config()) -> config(). init_per_suite(Config) -> clj_test_utils:init_per_suite(Config). -spec end_per_suite(config()) -> config(). end_per_suite(Config) -> Config. %%------------------------------------------------------------------------------ %% Test Cases %%------------------------------------------------------------------------------ -spec new(config()) -> result(). new(_Config) -> List = [1, 2, 3], [1, 2, 3] = clj_rt:seq(List), List2 = [], ?NIL = clj_rt:seq(List2), {comments, ""}. -spec count(config()) -> result(). count(_Config) -> List = [1, 2, 3], 3 = clj_rt:count(List), List2 = [], 0 = clj_rt:count(List2), {comments, ""}. -spec str(config()) -> result(). str(_Config) -> <<"#erl(1 2 3)">> = clj_rt:str([1, 2, 3]), <<"">> = clj_rt:str([]), <<"foo">> = clj_rt:str("foo"), {comments, ""}. -spec is_sequential(config()) -> result(). is_sequential(_Config) -> List = [1, 2, 3], true = clj_rt:'sequential?'(List), {comments, ""}. -spec get(config()) -> result(). get(_Config) -> List = [{a, 1}, {b, 2}, {c, 3}], 1 = clj_rt:get(List, a), 2 = clj_rt:get(List, b), 3 = clj_rt:get(List, c), ?NIL = clj_rt:get(List, d), 42 = clj_rt:get(List, d, 42), ?NIL = clj_rt:get([], foo), ?NIL = clj_rt:get([a, 1, ""], foo), {comments, ""}. -spec hash(config()) -> result(). hash(_Config) -> List1 = [1, 2, 3], List2 = [1, 3, 2], List3 = [1.0, 2, 3], Hash1 = 'clojerl.IHash':hash(List1), Hash2 = 'clojerl.IHash':hash(List2), Hash3 = 'clojerl.IHash':hash(List3), true = Hash1 =/= Hash2, true = Hash2 =/= Hash3, {comments, ""}. -spec seq(config()) -> result(). seq(_Config) -> List = [1, 2, 3], 1 = clj_rt:first(List), [2, 3] = clj_rt:seq(clj_rt:next(List)), [2, 3] = clj_rt:seq(clj_rt:rest(List)), List2 = [1], 1 = clj_rt:first(List2), ?NIL = clj_rt:next(List2), [] = clj_rt:to_list(clj_rt:rest(List2)), List3 = [], ?NIL = clj_rt:first(List3), ?NIL = clj_rt:next(List3), [] = clj_rt:rest(List3), {comments, ""}. -spec equiv(config()) -> result(). equiv(_Config) -> ct:comment("Check that lists with the same elements are equivalent"), List1 = [1, 2, 3], List2 = [1, 2, 3], true = clj_rt:equiv(List1, List2), ct:comment("Check that lists with the same elements are not equivalent"), List3 = [a, b, c], false = clj_rt:equiv(List1, List3), ct:comment("A erlang.List and a clojerl.List"), true = clj_rt:equiv(List1, clj_rt:list([1, 2, 3])), false = clj_rt:equiv(List1, clj_rt:list([1, 2, 3, a])), ct:comment("A erlang.List and a clojerl.Vector"), true = clj_rt:equiv(List1, clj_rt:vector([1, 2, 3])), false = clj_rt:equiv(List1, clj_rt:vector([1, 2, 3, a])), ct:comment("A erlang.List and something else"), false = clj_rt:equiv(List1, whatever), false = clj_rt:equiv(List1, #{}), ct:comment("An empty list and other stuff"), false = clj_rt:equiv([], [1, 2]), false = clj_rt:equiv([1, 2], []), {comments, ""}. -spec cons(config()) -> result(). cons(_Config) -> EmptyList = [], ct:comment("Conj an element to an empty list"), OneList = clj_rt:conj(EmptyList, 1), 1 = clj_rt:count(OneList), true = clj_rt:equiv(OneList, [1]), ct:comment("Conj an element to a list with one element"), TwoList = clj_rt:conj(OneList, 2), 2 = clj_rt:count(TwoList), true = clj_rt:equiv(TwoList, [2, 1]), {comments, ""}. -spec stack(config()) -> result(). stack(_Config) -> EmptyList = [], ?NIL = clj_rt:peek(EmptyList), EmptyList = clj_rt:pop(EmptyList), OneList = [1], 1 = clj_rt:peek(OneList), EmptyList = clj_rt:pop(OneList), TwoList = [2, 1], 2 = clj_rt:peek(TwoList), OneList = clj_rt:pop(TwoList), {comments, ""}. -spec to_clj(config()) -> result(). to_clj(_Config) -> List = [1, 2, 3], CljList = clj_rt:'erl->clj'(List, true), true = clj_rt:equiv(CljList, clj_rt:list([1, 2, 3])), EmptyList = [], EmptyCljList = clj_rt:'erl->clj'(EmptyList, false), true = clj_rt:equiv(EmptyCljList, clj_rt:list([])), {comments, ""}. -spec reduce(config()) -> result(). reduce(_Config) -> PlusFun0 = fun ([]) -> 0; ([X, Y]) -> X + Y end, PlusFun = 'clojerl.Fn':?CONSTRUCTOR(PlusFun0), EmptyList = [], 0 = 'clojerl.IReduce':reduce(EmptyList, PlusFun), 42 = 'clojerl.IReduce':reduce(EmptyList, PlusFun, 42), TenList = lists:seq(1, 10), 55 = 'clojerl.IReduce':reduce(TenList, PlusFun), 60 = 'clojerl.IReduce':reduce(TenList, PlusFun, 5), PlusMaxFun = fun (X, Y) when X < 10 -> X + Y; (X, _) -> 'clojerl.Reduced':?CONSTRUCTOR(X) end, 10 = 'clojerl.IReduce':reduce(TenList, PlusMaxFun), {comments, ""}. -spec complete_coverage(config()) -> result(). complete_coverage(_Config) -> NotEmptyList = [a, b, 2, 3], EmptyList = clj_rt:empty(NotEmptyList), EmptyList = [], ListMeta = clj_rt:with_meta(clj_rt:list([1, 2, 3]), #{a => 1}), #{a := 1} = clj_rt:meta(ListMeta), [1, 2, 3] = 'erlang.List':to_list([1, 2, 3]), {comments, ""}.
null
https://raw.githubusercontent.com/clojerl/clojerl/aa35847ca64e1c66224867ca4c31ca6de95bc898/test/erlang_List_SUITE.erl
erlang
------------------------------------------------------------------------------ Test Cases ------------------------------------------------------------------------------
-module(erlang_List_SUITE). -include("clojerl.hrl"). -include("clj_test_utils.hrl"). -export([ all/0 , init_per_suite/1 , end_per_suite/1 ]). -export([ new/1 , count/1 , str/1 , is_sequential/1 , get/1 , hash/1 , seq/1 , equiv/1 , cons/1 , stack/1 , to_clj/1 , reduce/1 , complete_coverage/1 ]). -clojure(true). -spec all() -> [atom()]. all() -> clj_test_utils:all(?MODULE). -spec init_per_suite(config()) -> config(). init_per_suite(Config) -> clj_test_utils:init_per_suite(Config). -spec end_per_suite(config()) -> config(). end_per_suite(Config) -> Config. -spec new(config()) -> result(). new(_Config) -> List = [1, 2, 3], [1, 2, 3] = clj_rt:seq(List), List2 = [], ?NIL = clj_rt:seq(List2), {comments, ""}. -spec count(config()) -> result(). count(_Config) -> List = [1, 2, 3], 3 = clj_rt:count(List), List2 = [], 0 = clj_rt:count(List2), {comments, ""}. -spec str(config()) -> result(). str(_Config) -> <<"#erl(1 2 3)">> = clj_rt:str([1, 2, 3]), <<"">> = clj_rt:str([]), <<"foo">> = clj_rt:str("foo"), {comments, ""}. -spec is_sequential(config()) -> result(). is_sequential(_Config) -> List = [1, 2, 3], true = clj_rt:'sequential?'(List), {comments, ""}. -spec get(config()) -> result(). get(_Config) -> List = [{a, 1}, {b, 2}, {c, 3}], 1 = clj_rt:get(List, a), 2 = clj_rt:get(List, b), 3 = clj_rt:get(List, c), ?NIL = clj_rt:get(List, d), 42 = clj_rt:get(List, d, 42), ?NIL = clj_rt:get([], foo), ?NIL = clj_rt:get([a, 1, ""], foo), {comments, ""}. -spec hash(config()) -> result(). hash(_Config) -> List1 = [1, 2, 3], List2 = [1, 3, 2], List3 = [1.0, 2, 3], Hash1 = 'clojerl.IHash':hash(List1), Hash2 = 'clojerl.IHash':hash(List2), Hash3 = 'clojerl.IHash':hash(List3), true = Hash1 =/= Hash2, true = Hash2 =/= Hash3, {comments, ""}. -spec seq(config()) -> result(). seq(_Config) -> List = [1, 2, 3], 1 = clj_rt:first(List), [2, 3] = clj_rt:seq(clj_rt:next(List)), [2, 3] = clj_rt:seq(clj_rt:rest(List)), List2 = [1], 1 = clj_rt:first(List2), ?NIL = clj_rt:next(List2), [] = clj_rt:to_list(clj_rt:rest(List2)), List3 = [], ?NIL = clj_rt:first(List3), ?NIL = clj_rt:next(List3), [] = clj_rt:rest(List3), {comments, ""}. -spec equiv(config()) -> result(). equiv(_Config) -> ct:comment("Check that lists with the same elements are equivalent"), List1 = [1, 2, 3], List2 = [1, 2, 3], true = clj_rt:equiv(List1, List2), ct:comment("Check that lists with the same elements are not equivalent"), List3 = [a, b, c], false = clj_rt:equiv(List1, List3), ct:comment("A erlang.List and a clojerl.List"), true = clj_rt:equiv(List1, clj_rt:list([1, 2, 3])), false = clj_rt:equiv(List1, clj_rt:list([1, 2, 3, a])), ct:comment("A erlang.List and a clojerl.Vector"), true = clj_rt:equiv(List1, clj_rt:vector([1, 2, 3])), false = clj_rt:equiv(List1, clj_rt:vector([1, 2, 3, a])), ct:comment("A erlang.List and something else"), false = clj_rt:equiv(List1, whatever), false = clj_rt:equiv(List1, #{}), ct:comment("An empty list and other stuff"), false = clj_rt:equiv([], [1, 2]), false = clj_rt:equiv([1, 2], []), {comments, ""}. -spec cons(config()) -> result(). cons(_Config) -> EmptyList = [], ct:comment("Conj an element to an empty list"), OneList = clj_rt:conj(EmptyList, 1), 1 = clj_rt:count(OneList), true = clj_rt:equiv(OneList, [1]), ct:comment("Conj an element to a list with one element"), TwoList = clj_rt:conj(OneList, 2), 2 = clj_rt:count(TwoList), true = clj_rt:equiv(TwoList, [2, 1]), {comments, ""}. -spec stack(config()) -> result(). stack(_Config) -> EmptyList = [], ?NIL = clj_rt:peek(EmptyList), EmptyList = clj_rt:pop(EmptyList), OneList = [1], 1 = clj_rt:peek(OneList), EmptyList = clj_rt:pop(OneList), TwoList = [2, 1], 2 = clj_rt:peek(TwoList), OneList = clj_rt:pop(TwoList), {comments, ""}. -spec to_clj(config()) -> result(). to_clj(_Config) -> List = [1, 2, 3], CljList = clj_rt:'erl->clj'(List, true), true = clj_rt:equiv(CljList, clj_rt:list([1, 2, 3])), EmptyList = [], EmptyCljList = clj_rt:'erl->clj'(EmptyList, false), true = clj_rt:equiv(EmptyCljList, clj_rt:list([])), {comments, ""}. -spec reduce(config()) -> result(). reduce(_Config) -> PlusFun0 = fun ([]) -> 0; ([X, Y]) -> X + Y end, PlusFun = 'clojerl.Fn':?CONSTRUCTOR(PlusFun0), EmptyList = [], 0 = 'clojerl.IReduce':reduce(EmptyList, PlusFun), 42 = 'clojerl.IReduce':reduce(EmptyList, PlusFun, 42), TenList = lists:seq(1, 10), 55 = 'clojerl.IReduce':reduce(TenList, PlusFun), 60 = 'clojerl.IReduce':reduce(TenList, PlusFun, 5), PlusMaxFun = fun (X, Y) when X < 10 -> X + Y; (X, _) -> 'clojerl.Reduced':?CONSTRUCTOR(X) end, 10 = 'clojerl.IReduce':reduce(TenList, PlusMaxFun), {comments, ""}. -spec complete_coverage(config()) -> result(). complete_coverage(_Config) -> NotEmptyList = [a, b, 2, 3], EmptyList = clj_rt:empty(NotEmptyList), EmptyList = [], ListMeta = clj_rt:with_meta(clj_rt:list([1, 2, 3]), #{a => 1}), #{a := 1} = clj_rt:meta(ListMeta), [1, 2, 3] = 'erlang.List':to_list([1, 2, 3]), {comments, ""}.
73ef09532d6003cbadda615e799ecaa14bd97006304507f2b75457fe373faa9d
skyzh/mips-simulator
Forward.hs
module Forward ( forward , ForwardInfo(..) ) where import Data.Word ( Word32 ) import Branch ( isBranchOp , isLinkOp ) import Memory ( memoryLoad , memoryStore ) import ALU ( isArithmeticOp ) data ForwardInfo = ForwardInfo Word32 Word32 Word32 Word32 Word32 Word32 Word32 Word32 Word32 Word32 forward :: ForwardInfo -> Word32 -> (Word32, Bool, Bool) forward (ForwardInfo ex_opcode ex_dest ex_val mem_opcode mem_dest mem_alu_val mem_val wb_opcode wb_dest wb_val) src | src == 0 = (0, False, False) | ex_dest == src && isArithmeticOp ex_opcode = (ex_val, True, False) | ex_dest == src && memoryLoad ex_opcode -- use after load, stall = (0, True, True) | ex_dest == src && isLinkOp ex_opcode = (ex_val, True, False) | mem_dest == src && isArithmeticOp mem_opcode = (mem_alu_val, True, False) | mem_dest == src && memoryLoad mem_opcode = (mem_val, True, False) | mem_dest == src && isLinkOp mem_opcode = (mem_alu_val, True, False) | wb_dest == src && (isArithmeticOp wb_opcode || memoryLoad wb_opcode || isLinkOp wb_opcode) = (wb_val, True, False) | otherwise = (0, False, False)
null
https://raw.githubusercontent.com/skyzh/mips-simulator/61a319ab776fa30831e75aab906c6ef22bb7755e/src/Forward.hs
haskell
use after load, stall
module Forward ( forward , ForwardInfo(..) ) where import Data.Word ( Word32 ) import Branch ( isBranchOp , isLinkOp ) import Memory ( memoryLoad , memoryStore ) import ALU ( isArithmeticOp ) data ForwardInfo = ForwardInfo Word32 Word32 Word32 Word32 Word32 Word32 Word32 Word32 Word32 Word32 forward :: ForwardInfo -> Word32 -> (Word32, Bool, Bool) forward (ForwardInfo ex_opcode ex_dest ex_val mem_opcode mem_dest mem_alu_val mem_val wb_opcode wb_dest wb_val) src | src == 0 = (0, False, False) | ex_dest == src && isArithmeticOp ex_opcode = (ex_val, True, False) = (0, True, True) | ex_dest == src && isLinkOp ex_opcode = (ex_val, True, False) | mem_dest == src && isArithmeticOp mem_opcode = (mem_alu_val, True, False) | mem_dest == src && memoryLoad mem_opcode = (mem_val, True, False) | mem_dest == src && isLinkOp mem_opcode = (mem_alu_val, True, False) | wb_dest == src && (isArithmeticOp wb_opcode || memoryLoad wb_opcode || isLinkOp wb_opcode) = (wb_val, True, False) | otherwise = (0, False, False)
5c877f3f6e53e94f3a76bf3362e82251041d312bd1043e3d632b1adec2655660
lucasdicioccio/deptrack-project
Parasite.hs
# LANGUAGE DataKinds # {-# LANGUAGE OverloadedStrings #-} module Devops.Parasite ( ParasitedHost (..) , ParasiteLogin , ControlledHost (..) , control , parasite , remoted , fileTransferred , SshFsMountedDir , sshMounted , sshFileCopy , FileTransferred ) where import Control.Applicative ((<|>)) import Data.Monoid ((<>)) import Data.String.Conversions (convertString) import Data.Text (Text) import qualified Data.Text as Text import Data.Typeable (Typeable) import System.FilePath.Posix (takeBaseName, (</>)) import Devops.Binary (Binary, binary) import Devops.Callback import Devops.Cli import Devops.Constraints (HasOS, onOS) import qualified Devops.Debian.Commands as Debian import Devops.Debian.User (homeDirPath) import Devops.Networking import Devops.Storage import Devops.Base import Devops.Utils type ParasiteLogin = Text -- | A host that we control. data ControlledHost = ControlledHost !ParasiteLogin !Remote -- | A host that we control. data ParasitedHost = ParasitedHost !FilePath !ParasiteLogin !IpNetString -- | A file transferred at a given remote path. data FileTransferred = FileTransferred !FilePath !Remote -- | Assert control on a remote. control :: ParasiteLogin -> DevOp env Remote -> DevOp env ControlledHost control login mkRemote = devop fst mkOp $ do r@(Remote ip) <- mkRemote return ((ControlledHost login r), ip) where mkOp (ControlledHost _ _, ip) = buildOp ("controlled-host: " <> ip) ("declares a host is controllable") noCheck noAction noAction noAction | A parasite reserves a binary in the homedir . -- The remote binary will take precedence in ' BinaryCall ' from ' remoted ' -- 'Continued' argument. parasite :: HasOS env => FilePath -> DevOp env ControlledHost -> DevOp env ParasitedHost parasite selfPath mkHost = track mkOp $ do (ControlledHost login _) <- mkHost let selfBinary = preExistingFile selfPath let rpath = homeDirPath login </> takeBaseName selfPath (FileTransferred _ (Remote ip)) <- fileTransferred selfBinary rpath mkHost return (ParasitedHost rpath login ip) where mkOp (ParasitedHost _ _ ip) = noop ("parasited-host: " <> ip) ("copies itself after in a parasite") | Turnup a given DevOp env at a given remote . remoted :: (HasOS env, Typeable a) => Continued env a -> env -> DevOp env ParasitedHost -> DevOp env (Remoted (Maybe a)) remoted cont env host = devop fst mkOp $ do c <- ssh let obj = eval env cont let (BinaryCall _ fArgs) = callback cont let args = fArgs (TurnUp Concurrently) (ParasitedHost rpath login ip) <- host return ((Remoted (Remote ip) obj), (rpath, login, c, args, ip)) where mkOp (_, (rpath, login, c, args, ip)) = buildOp ("remote-callback: " <> convertString (unwords args) <> " @" <> ip) ("calls itself back with `$self " <> convertString (unwords args) <>"`") noCheck (blindRun c (sshCmd rpath login ip args) "") noAction noAction sshCmd rpath login ip args = [ "-o", "StrictHostKeyChecking no" , "-o", "UserKnownHostsFile /dev/null" , "-l", Text.unpack login, Text.unpack ip , "sudo", "-E", rpath ] ++ args scp :: HasOS env => DevOp env (Binary "scp") scp = onOS "debian" Debian.scp <|> onOS "mac-os" binary ssh :: HasOS env => DevOp env (Binary "ssh") ssh = onOS "debian" Debian.ssh <|> onOS "mac-os" binary -- | A file transferred at a remote path. fileTransferred :: HasOS env => DevOp env FilePresent -> FilePath -> DevOp env ControlledHost -> DevOp env (FileTransferred) fileTransferred mkFp path mkHost = devop fst mkOp $ do c <- scp f <- mkFp (ControlledHost login r) <- mkHost return (FileTransferred path r, (f,c,login)) where mkOp (FileTransferred rpath (Remote ip), (FilePresent lpath,c,login)) = do buildOp ("remote-file: " <> Text.pack rpath <> "@" <> ip) ("file " <> Text.pack lpath <> " copied on " <> ip) noCheck (blindRun c (scpcmd lpath login ip rpath) "") noAction noAction scpcmd lpath login ip rpath = [ "-o", "StrictHostKeyChecking no" , "-o", "UserKnownHostsFile /dev/null" , lpath , Text.unpack login ++ "@" ++ Text.unpack ip ++ ":" ++ rpath ] -- Remote storage mounting. data SshFsMountedDir = SshFsMountedDir !FilePath sshMounted :: DevOp env DirectoryPresent -> DevOp env ControlledHost -> DevOp env (SshFsMountedDir) sshMounted mkPath mkHost = devop fst mkOp $ do binmount <- Debian.mount sshmount <- Debian.sshfs umount <- Debian.fusermount (DirectoryPresent path) <- mkPath host <- mkHost return (SshFsMountedDir path, (host, binmount, sshmount, umount)) where mkOp (SshFsMountedDir path, (host, binmount, sshmount, umount)) = do let (ControlledHost login (Remote ip)) = host buildOp ("ssh-fs-dir: " <> Text.pack path <> "@" <> ip) ("mount " <> ip <> " at mountpoint " <> Text.pack path) (checkBinaryExitCodeAndStdout (hasMountLine path) binmount ["-l", "-t", "fuse.sshfs"] "") (blindRun sshmount [ Text.unpack login ++ "@" ++ Text.unpack ip ++ ":" , path , "-o", "StrictHostKeyChecking=no" , "-o", "UserKnownHostsFile=/dev/null" ] "") (blindRun umount [ "-u", path ] "") noAction -- | Looks for the filepath in the list of mounts. hasMountLine :: FilePath -> String -> Bool hasMountLine path dat = elem path $ concatMap words $ lines dat sshFileCopy :: DevOp env FilePresent -> DevOp env (SshFsMountedDir) -> DevOp env (RepositoryFile, FilePresent) sshFileCopy mkLocal mkDir = do (FilePresent loc) <- mkLocal let rpath = (\(SshFsMountedDir dir) -> dir </> takeBaseName loc) <$> mkDir fileCopy rpath (mkLocal >>= (\(FilePresent local) -> localRepositoryFile local))
null
https://raw.githubusercontent.com/lucasdicioccio/deptrack-project/cd3d59a796815af8ae8db32c47b1e1cdc209ac71/deptrack-devops-recipes/src/Devops/Parasite.hs
haskell
# LANGUAGE OverloadedStrings # | A host that we control. | A host that we control. | A file transferred at a given remote path. | Assert control on a remote. 'Continued' argument. | A file transferred at a remote path. Remote storage mounting. | Looks for the filepath in the list of mounts.
# LANGUAGE DataKinds # module Devops.Parasite ( ParasitedHost (..) , ParasiteLogin , ControlledHost (..) , control , parasite , remoted , fileTransferred , SshFsMountedDir , sshMounted , sshFileCopy , FileTransferred ) where import Control.Applicative ((<|>)) import Data.Monoid ((<>)) import Data.String.Conversions (convertString) import Data.Text (Text) import qualified Data.Text as Text import Data.Typeable (Typeable) import System.FilePath.Posix (takeBaseName, (</>)) import Devops.Binary (Binary, binary) import Devops.Callback import Devops.Cli import Devops.Constraints (HasOS, onOS) import qualified Devops.Debian.Commands as Debian import Devops.Debian.User (homeDirPath) import Devops.Networking import Devops.Storage import Devops.Base import Devops.Utils type ParasiteLogin = Text data ControlledHost = ControlledHost !ParasiteLogin !Remote data ParasitedHost = ParasitedHost !FilePath !ParasiteLogin !IpNetString data FileTransferred = FileTransferred !FilePath !Remote control :: ParasiteLogin -> DevOp env Remote -> DevOp env ControlledHost control login mkRemote = devop fst mkOp $ do r@(Remote ip) <- mkRemote return ((ControlledHost login r), ip) where mkOp (ControlledHost _ _, ip) = buildOp ("controlled-host: " <> ip) ("declares a host is controllable") noCheck noAction noAction noAction | A parasite reserves a binary in the homedir . The remote binary will take precedence in ' BinaryCall ' from ' remoted ' parasite :: HasOS env => FilePath -> DevOp env ControlledHost -> DevOp env ParasitedHost parasite selfPath mkHost = track mkOp $ do (ControlledHost login _) <- mkHost let selfBinary = preExistingFile selfPath let rpath = homeDirPath login </> takeBaseName selfPath (FileTransferred _ (Remote ip)) <- fileTransferred selfBinary rpath mkHost return (ParasitedHost rpath login ip) where mkOp (ParasitedHost _ _ ip) = noop ("parasited-host: " <> ip) ("copies itself after in a parasite") | Turnup a given DevOp env at a given remote . remoted :: (HasOS env, Typeable a) => Continued env a -> env -> DevOp env ParasitedHost -> DevOp env (Remoted (Maybe a)) remoted cont env host = devop fst mkOp $ do c <- ssh let obj = eval env cont let (BinaryCall _ fArgs) = callback cont let args = fArgs (TurnUp Concurrently) (ParasitedHost rpath login ip) <- host return ((Remoted (Remote ip) obj), (rpath, login, c, args, ip)) where mkOp (_, (rpath, login, c, args, ip)) = buildOp ("remote-callback: " <> convertString (unwords args) <> " @" <> ip) ("calls itself back with `$self " <> convertString (unwords args) <>"`") noCheck (blindRun c (sshCmd rpath login ip args) "") noAction noAction sshCmd rpath login ip args = [ "-o", "StrictHostKeyChecking no" , "-o", "UserKnownHostsFile /dev/null" , "-l", Text.unpack login, Text.unpack ip , "sudo", "-E", rpath ] ++ args scp :: HasOS env => DevOp env (Binary "scp") scp = onOS "debian" Debian.scp <|> onOS "mac-os" binary ssh :: HasOS env => DevOp env (Binary "ssh") ssh = onOS "debian" Debian.ssh <|> onOS "mac-os" binary fileTransferred :: HasOS env => DevOp env FilePresent -> FilePath -> DevOp env ControlledHost -> DevOp env (FileTransferred) fileTransferred mkFp path mkHost = devop fst mkOp $ do c <- scp f <- mkFp (ControlledHost login r) <- mkHost return (FileTransferred path r, (f,c,login)) where mkOp (FileTransferred rpath (Remote ip), (FilePresent lpath,c,login)) = do buildOp ("remote-file: " <> Text.pack rpath <> "@" <> ip) ("file " <> Text.pack lpath <> " copied on " <> ip) noCheck (blindRun c (scpcmd lpath login ip rpath) "") noAction noAction scpcmd lpath login ip rpath = [ "-o", "StrictHostKeyChecking no" , "-o", "UserKnownHostsFile /dev/null" , lpath , Text.unpack login ++ "@" ++ Text.unpack ip ++ ":" ++ rpath ] data SshFsMountedDir = SshFsMountedDir !FilePath sshMounted :: DevOp env DirectoryPresent -> DevOp env ControlledHost -> DevOp env (SshFsMountedDir) sshMounted mkPath mkHost = devop fst mkOp $ do binmount <- Debian.mount sshmount <- Debian.sshfs umount <- Debian.fusermount (DirectoryPresent path) <- mkPath host <- mkHost return (SshFsMountedDir path, (host, binmount, sshmount, umount)) where mkOp (SshFsMountedDir path, (host, binmount, sshmount, umount)) = do let (ControlledHost login (Remote ip)) = host buildOp ("ssh-fs-dir: " <> Text.pack path <> "@" <> ip) ("mount " <> ip <> " at mountpoint " <> Text.pack path) (checkBinaryExitCodeAndStdout (hasMountLine path) binmount ["-l", "-t", "fuse.sshfs"] "") (blindRun sshmount [ Text.unpack login ++ "@" ++ Text.unpack ip ++ ":" , path , "-o", "StrictHostKeyChecking=no" , "-o", "UserKnownHostsFile=/dev/null" ] "") (blindRun umount [ "-u", path ] "") noAction hasMountLine :: FilePath -> String -> Bool hasMountLine path dat = elem path $ concatMap words $ lines dat sshFileCopy :: DevOp env FilePresent -> DevOp env (SshFsMountedDir) -> DevOp env (RepositoryFile, FilePresent) sshFileCopy mkLocal mkDir = do (FilePresent loc) <- mkLocal let rpath = (\(SshFsMountedDir dir) -> dir </> takeBaseName loc) <$> mkDir fileCopy rpath (mkLocal >>= (\(FilePresent local) -> localRepositoryFile local))
d6f684c87ccb29eae33ce94f3c24f64e1e4bb03e757ca75fc73060a0bd0340c8
elastic/eui-cljs
set_style_for_restricted_page_width.cljs
(ns eui.set-style-for-restricted-page-width (:require ["@elastic/eui/lib/components/page/_restrict_width.js" :as eui])) (def setStyleForRestrictedPageWidth eui/setStyleForRestrictedPageWidth) (def PAGE_MAX_WIDTH eui/PAGE_MAX_WIDTH) (def setPropsForRestrictedPageWidth eui/setPropsForRestrictedPageWidth)
null
https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/set_style_for_restricted_page_width.cljs
clojure
(ns eui.set-style-for-restricted-page-width (:require ["@elastic/eui/lib/components/page/_restrict_width.js" :as eui])) (def setStyleForRestrictedPageWidth eui/setStyleForRestrictedPageWidth) (def PAGE_MAX_WIDTH eui/PAGE_MAX_WIDTH) (def setPropsForRestrictedPageWidth eui/setPropsForRestrictedPageWidth)
a77869089610a4ce0a148337f7003ac9dc6c261993eb2628a0a6a9d19a0d62b5
flavioc/cl-hurd
file-set-translator.lisp
(in-package :hurd-translator) (defun %get-short-circuited-translator (ls) "Return a symbol denoting the short circuited translator, if that is the case." (let ((name (first ls))) (cond ((string= name +hurd-symlink+) :lnk) ((string= name +hurd-chrdev+) :chr) ((string= name +hurd-blkdev+) :blk) ((string= name +hurd-fifo+) :fifo) ((string= name +hurd-ifsock+) :sock) (t nil)))) (defun %set-short-circuited-translator (ls node user) "Runs a specific action for a short circuited translator." (let ((what (%get-short-circuited-translator ls))) (when what (case what (:lnk (when (= (length ls) 2) (create-symlink *translator* node user (second ls)))) ((:blk :chr) (when (= (length ls) 3) (let ((major (parse-integer (second ls) :junk-allowed t)) (minor (parse-integer (third ls) :junk-allowed t))) (when (and major minor) (let ((device (make-instance 'device-id :major major :minor minor))) (if (eq what :blk) (create-block *translator* node user device) (create-character *translator* node user device))))))) (:fifo (when (= (length ls) 1) (create-fifo *translator* node user))) (:sock (when (= (length ls) 1) (create-socket *translator* node user))) (otherwise nil))))) (defun %try-short-circuited-translator (passive-flags passive-list node user) (unless (flag-is-p passive-flags :force) (%set-short-circuited-translator passive-list node user))) (def-fs-interface :file-set-translator ((file port) (passive-flags fs-trans-flags) (active-flags fs-trans-flags) (killtrans-flags fsys-goaway-flags) (passive :pointer) (passivelen msg-type-number) (active port)) (with-lookup protid file (block set-translator (unless (or (flag-is-p passive-flags :set) (flag-is-p active-flags :set)) (return-from set-translator :invalid-argument)) (let ((node (get-node protid)) (user (get-user protid))) (when (and (flag-is-p active-flags :set) (not (flag-is-p active-flags :orphan))) (unless (is-owner-p node user) (return-from set-translator :permission-denied)) (when (and (box-active-p (box node)) (not (flag-is-p active-flags :excl))) (let ((control (box-fetch-control (box node)))) (multiple-value-bind (ret err) (fsys-goaway control killtrans-flags) (declare (ignore ret)) (when err (return-from set-translator err)))))) (when (and (flag-is-p passive-flags '(:set :excl)) (box-passive-p (box node))) (return-from set-translator :resource-busy)) (when (flag-is-p active-flags :set) (unless (box-set-active (box node) active (flag-is-p active-flags :excl)) (return-from set-translator :resource-busy))) (cond ((flag-is-p passive-flags :set) (let* ((passive-list (foreign-string-zero-separated-to-list passive passivelen)) (sct (%try-short-circuited-translator passive-flags passive-list node user))) (cond (sct t) (t (box-set-passive (box node) passive-list))))) ((flag-is-p active-flags :set) t))))))
null
https://raw.githubusercontent.com/flavioc/cl-hurd/982232f47d1a0ff4df5fde2edad03b9df871470a/translator/interfaces/file-set-translator.lisp
lisp
(in-package :hurd-translator) (defun %get-short-circuited-translator (ls) "Return a symbol denoting the short circuited translator, if that is the case." (let ((name (first ls))) (cond ((string= name +hurd-symlink+) :lnk) ((string= name +hurd-chrdev+) :chr) ((string= name +hurd-blkdev+) :blk) ((string= name +hurd-fifo+) :fifo) ((string= name +hurd-ifsock+) :sock) (t nil)))) (defun %set-short-circuited-translator (ls node user) "Runs a specific action for a short circuited translator." (let ((what (%get-short-circuited-translator ls))) (when what (case what (:lnk (when (= (length ls) 2) (create-symlink *translator* node user (second ls)))) ((:blk :chr) (when (= (length ls) 3) (let ((major (parse-integer (second ls) :junk-allowed t)) (minor (parse-integer (third ls) :junk-allowed t))) (when (and major minor) (let ((device (make-instance 'device-id :major major :minor minor))) (if (eq what :blk) (create-block *translator* node user device) (create-character *translator* node user device))))))) (:fifo (when (= (length ls) 1) (create-fifo *translator* node user))) (:sock (when (= (length ls) 1) (create-socket *translator* node user))) (otherwise nil))))) (defun %try-short-circuited-translator (passive-flags passive-list node user) (unless (flag-is-p passive-flags :force) (%set-short-circuited-translator passive-list node user))) (def-fs-interface :file-set-translator ((file port) (passive-flags fs-trans-flags) (active-flags fs-trans-flags) (killtrans-flags fsys-goaway-flags) (passive :pointer) (passivelen msg-type-number) (active port)) (with-lookup protid file (block set-translator (unless (or (flag-is-p passive-flags :set) (flag-is-p active-flags :set)) (return-from set-translator :invalid-argument)) (let ((node (get-node protid)) (user (get-user protid))) (when (and (flag-is-p active-flags :set) (not (flag-is-p active-flags :orphan))) (unless (is-owner-p node user) (return-from set-translator :permission-denied)) (when (and (box-active-p (box node)) (not (flag-is-p active-flags :excl))) (let ((control (box-fetch-control (box node)))) (multiple-value-bind (ret err) (fsys-goaway control killtrans-flags) (declare (ignore ret)) (when err (return-from set-translator err)))))) (when (and (flag-is-p passive-flags '(:set :excl)) (box-passive-p (box node))) (return-from set-translator :resource-busy)) (when (flag-is-p active-flags :set) (unless (box-set-active (box node) active (flag-is-p active-flags :excl)) (return-from set-translator :resource-busy))) (cond ((flag-is-p passive-flags :set) (let* ((passive-list (foreign-string-zero-separated-to-list passive passivelen)) (sct (%try-short-circuited-translator passive-flags passive-list node user))) (cond (sct t) (t (box-set-passive (box node) passive-list))))) ((flag-is-p active-flags :set) t))))))
00e6292b533e6d62ca706b68ce79e1c6d77100f6f92d666de54ef8835da39287
ckirkendall/enfocus
ring.clj
(ns enfocus.ring (:use ring.middleware.file ring.handler.dump)) (def app (wrap-file handle-dump "resources/public"))
null
https://raw.githubusercontent.com/ckirkendall/enfocus/54ee5d1ec4c1fd603d4766caac07bfc482f65abb/temp/testing/src/enfocus/ring.clj
clojure
(ns enfocus.ring (:use ring.middleware.file ring.handler.dump)) (def app (wrap-file handle-dump "resources/public"))
1badac64bdeca5453d25a24d9df407d01004a116644922dd9725f5f09663176d
r-willis/biten
bootstrap.erl
%%% -------------------------------------------------------------------------- @author < %%% @doc Bootstrap process. Uses DNS for peer discovery. %%% @end %%% -------------------------------------------------------------------------- -module(bootstrap). -behaviour(gen_server). %% API -export([start_link/0, stop/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %% Use module name for registered process -define(SERVER, ?MODULE). %%% ========================================================================== %%% API %%% ========================================================================== %% @doc Start bootstrap process and register it -spec start_link() -> pid(). start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). %% @doc Stop statistics process stop() -> gen_server:cast(?SERVER, stop). %%% ========================================================================== %%% gen_server callbacks. %%% ========================================================================== %% process state -record(state, {none}). init([]) -> gen_server:cast(?SERVER, go), {ok, #state{}}. handle_call(_Request, _From, S) -> {reply, ok, S}. handle_cast(go, S) -> IPs = get_addrs_ipv4_dns(), peerdiscovery:add([{IP, 8333} || IP <- IPs]), {stop, normal, S}; handle_cast(stop, State) -> {stop, normal, State}. handle_info(_Msg, S) -> {noreply, S}. terminate(_Reason, _State) -> ok. code_change(_oldVersion, State, _Extra) -> {ok, State}. %%% =========================================== %%% Local functions %%% =========================================== @doc Get addrs for bootstrap from DNS . get_addrs_ipv4_dns() -> L = ["bitseed.xf2.org", "dnsseed.bluematt.me", "seed.bitcoin.sipa.be", "dnsseed.bitcoin.dashjr.org" ], lists:flatten([nslookup_ipv4(A) || A <- L]). nslookup_ipv4(Addr) -> Type = a, Class = in, case inet_res:resolve(Addr, Class, Type) of {ok,Msg} -> [inet_dns:rr(RR, data) || RR <- inet_dns:msg(Msg, anlist), inet_dns:rr(RR, type) =:= Type, inet_dns:rr(RR, class) =:= Class]; {error,_} -> [] end.
null
https://raw.githubusercontent.com/r-willis/biten/75b13ea296992f8fa749646b9d7c15c5ef23d94d/apps/biten/src/bootstrap.erl
erlang
-------------------------------------------------------------------------- @doc Bootstrap process. Uses DNS for peer discovery. @end -------------------------------------------------------------------------- API gen_server callbacks Use module name for registered process ========================================================================== API ========================================================================== @doc Start bootstrap process and register it @doc Stop statistics process ========================================================================== gen_server callbacks. ========================================================================== process state =========================================== Local functions ===========================================
@author < -module(bootstrap). -behaviour(gen_server). -export([start_link/0, stop/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -spec start_link() -> pid(). start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). stop() -> gen_server:cast(?SERVER, stop). -record(state, {none}). init([]) -> gen_server:cast(?SERVER, go), {ok, #state{}}. handle_call(_Request, _From, S) -> {reply, ok, S}. handle_cast(go, S) -> IPs = get_addrs_ipv4_dns(), peerdiscovery:add([{IP, 8333} || IP <- IPs]), {stop, normal, S}; handle_cast(stop, State) -> {stop, normal, State}. handle_info(_Msg, S) -> {noreply, S}. terminate(_Reason, _State) -> ok. code_change(_oldVersion, State, _Extra) -> {ok, State}. @doc Get addrs for bootstrap from DNS . get_addrs_ipv4_dns() -> L = ["bitseed.xf2.org", "dnsseed.bluematt.me", "seed.bitcoin.sipa.be", "dnsseed.bitcoin.dashjr.org" ], lists:flatten([nslookup_ipv4(A) || A <- L]). nslookup_ipv4(Addr) -> Type = a, Class = in, case inet_res:resolve(Addr, Class, Type) of {ok,Msg} -> [inet_dns:rr(RR, data) || RR <- inet_dns:msg(Msg, anlist), inet_dns:rr(RR, type) =:= Type, inet_dns:rr(RR, class) =:= Class]; {error,_} -> [] end.
9c4bfb550fca23a6fb3c9d98f7440a9fb7b74aabd2e2b0d3f882bef3621c1f9a
xapi-project/xen-api
gen_empty_custom.ml
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) 2006-2009 Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) * Generate default implementation of the Custom actions signature (* open Api_lowlevel *) module OU = Ocaml_utils module DT = Datamodel_types module DU = Datamodel_utils module DM = Datamodel module O = Ocaml_syntax module Client = Gen_client open DT let debug_module_name = "DebugVersion" let release_module_name = "ReleaseVersion" let signature_name = "CUSTOM_ACTIONS" let forwarding_signature_name = "CUSTOM_FORWARDING" let _task_id = "task_id" Notes : 1 . Only those members derived from fields and messages from the datamodel which are marked as requiring side - effects should be present 2 . returns unit ( values always come from the database ) 1. Only those members derived from fields and messages from the datamodel which are marked as requiring side-effects should be present 2. get_field returns unit (values always come from the database) *) let operation_requires_side_effect ({msg_tag= tag; _} as msg) = ( match msg.DT.msg_force_custom (* this flag always forces msg into custom_actions.ml *) with | None -> false | Some mode -> ( if mode = RW then true (*RW=force both setters and getters into custom_actions *) { Static / Dynamic}RO = force only getters into custom_actions match msg with | {msg_tag= FromField ((Setter | Add | Remove), _); _} -> false | {msg_tag= FromObject (Make | Delete); _} -> false | _ -> true ) ) || match tag with | FromField (Setter, fld) -> fld.DT.field_has_effect | FromObject ( GetRecord | GetByUuid | GetByLabel | GetAll | GetAllRecordsWhere | GetAllRecords ) -> false | FromObject _ -> true | Custom -> msg.DT.msg_has_effect && msg.DT.msg_forward_to = None | _ -> false let make_custom_api api = Dm_api.filter (fun _ -> true) (fun _ -> true) (fun msg -> operation_requires_side_effect msg && Client.objfilter msg api) api let gen_debug_module name_override result_type_override body_override api : O.Module.t = let api = make_custom_api api in let operation (obj : obj) (x : message) = let args = Client.args_of_message obj x in (* filter out the session_id *) let args = List.filter (function O.Named ("session_id", _) -> false | _ -> true) args in let result_type = match result_type_override with | None -> ( match (x.msg_custom_marshaller, x.msg_result) with | true, _ -> "Rpc.t" | _, Some (ty, _) -> OU.alias_of_ty ty | _, None -> "unit" ) | Some t -> t in let body = match body_override with | None -> ["raise (Not_implemented \"" ^ x.msg_name ^ "\")"] | Some b -> b in O.Let.make ~name:x.msg_name ~params:(Gen_common.context_arg :: args) ~ty:result_type ~body ~doc:"" () in let obj (obj : obj) = let messages = List.filter (fun x -> not (x.DT.msg_lifecycle.state = Removed_s)) obj.messages in let fields = List.map (fun x -> O.Module.Let (operation obj x)) messages in O.Module.make ~name:(OU.ocaml_of_obj_name obj.DT.name) ~elements:fields () in O.Module.make ~name:(match name_override with None -> debug_module_name | Some n -> n) ~preamble:["exception Not_implemented of string"] ~elements: (List.map (fun x -> O.Module.Module (obj x)) (Dm_api.objects_of_api api)) () let gen_signature signature_name result_type_override api : O.Signature.t = (* debug version has full signature *) let x = O.Signature.of_module (gen_debug_module None result_type_override None api) in {x with O.Signature.name= signature_name} (** 'release' version has the same structures but none of the methods; so this will cause the compile of the server to fail unless it has provided an implementation of everything. *) let gen_release_module api : O.Module.t = let obj (obj : obj) = O.Module.make ~name:(OU.ocaml_of_obj_name obj.DT.name) ~elements:[] () in O.Module.make ~name:release_module_name ~elements: (List.map (fun x -> O.Module.Module (obj x)) (Dm_api.objects_of_api api)) ()
null
https://raw.githubusercontent.com/xapi-project/xen-api/4ec6be956b1181619e12b5cd14c70973ef85cb4d/ocaml/idl/ocaml_backend/gen_empty_custom.ml
ocaml
open Api_lowlevel this flag always forces msg into custom_actions.ml RW=force both setters and getters into custom_actions filter out the session_id debug version has full signature * 'release' version has the same structures but none of the methods; so this will cause the compile of the server to fail unless it has provided an implementation of everything.
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) 2006-2009 Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) * Generate default implementation of the Custom actions signature module OU = Ocaml_utils module DT = Datamodel_types module DU = Datamodel_utils module DM = Datamodel module O = Ocaml_syntax module Client = Gen_client open DT let debug_module_name = "DebugVersion" let release_module_name = "ReleaseVersion" let signature_name = "CUSTOM_ACTIONS" let forwarding_signature_name = "CUSTOM_FORWARDING" let _task_id = "task_id" Notes : 1 . Only those members derived from fields and messages from the datamodel which are marked as requiring side - effects should be present 2 . returns unit ( values always come from the database ) 1. Only those members derived from fields and messages from the datamodel which are marked as requiring side-effects should be present 2. get_field returns unit (values always come from the database) *) let operation_requires_side_effect ({msg_tag= tag; _} as msg) = ( match msg.DT.msg_force_custom with | None -> false | Some mode -> ( if mode = RW then { Static / Dynamic}RO = force only getters into custom_actions match msg with | {msg_tag= FromField ((Setter | Add | Remove), _); _} -> false | {msg_tag= FromObject (Make | Delete); _} -> false | _ -> true ) ) || match tag with | FromField (Setter, fld) -> fld.DT.field_has_effect | FromObject ( GetRecord | GetByUuid | GetByLabel | GetAll | GetAllRecordsWhere | GetAllRecords ) -> false | FromObject _ -> true | Custom -> msg.DT.msg_has_effect && msg.DT.msg_forward_to = None | _ -> false let make_custom_api api = Dm_api.filter (fun _ -> true) (fun _ -> true) (fun msg -> operation_requires_side_effect msg && Client.objfilter msg api) api let gen_debug_module name_override result_type_override body_override api : O.Module.t = let api = make_custom_api api in let operation (obj : obj) (x : message) = let args = Client.args_of_message obj x in let args = List.filter (function O.Named ("session_id", _) -> false | _ -> true) args in let result_type = match result_type_override with | None -> ( match (x.msg_custom_marshaller, x.msg_result) with | true, _ -> "Rpc.t" | _, Some (ty, _) -> OU.alias_of_ty ty | _, None -> "unit" ) | Some t -> t in let body = match body_override with | None -> ["raise (Not_implemented \"" ^ x.msg_name ^ "\")"] | Some b -> b in O.Let.make ~name:x.msg_name ~params:(Gen_common.context_arg :: args) ~ty:result_type ~body ~doc:"" () in let obj (obj : obj) = let messages = List.filter (fun x -> not (x.DT.msg_lifecycle.state = Removed_s)) obj.messages in let fields = List.map (fun x -> O.Module.Let (operation obj x)) messages in O.Module.make ~name:(OU.ocaml_of_obj_name obj.DT.name) ~elements:fields () in O.Module.make ~name:(match name_override with None -> debug_module_name | Some n -> n) ~preamble:["exception Not_implemented of string"] ~elements: (List.map (fun x -> O.Module.Module (obj x)) (Dm_api.objects_of_api api)) () let gen_signature signature_name result_type_override api : O.Signature.t = let x = O.Signature.of_module (gen_debug_module None result_type_override None api) in {x with O.Signature.name= signature_name} let gen_release_module api : O.Module.t = let obj (obj : obj) = O.Module.make ~name:(OU.ocaml_of_obj_name obj.DT.name) ~elements:[] () in O.Module.make ~name:release_module_name ~elements: (List.map (fun x -> O.Module.Module (obj x)) (Dm_api.objects_of_api api)) ()
38a0d60506f320efd0500201fd55479fd00d965d4fec95ce419813005f1a23ab
alezost/guix-config
os-32-to-64.scm
;; This is a simple example of an operating system declaration to move from a 32 - bit system to a 64 - bit one . See the thread ;; <-devel/2015-05/msg00392.html> ;; for details. (use-modules (gnu) (guix monads) (guix store) ((guix build utils) #:select (alist-replace)) (guix packages) (gnu packages linux) (gnu packages package-management) (gnu services base) (al guix services linux)) (define linux-libre-x86_64 (package (inherit linux-libre) (arguments `(#:system "x86_64-linux" ,@(package-arguments linux-libre))) (native-inputs (alist-replace "kconfig" (list (string-append (getenv "HOME") "/src/guix/gnu/packages/linux-libre-x86_64.conf")) (package-native-inputs linux-libre))))) (define guix-x86_64 (package (inherit guix) (arguments `(#:system "x86_64-linux" ,@(package-arguments guix))))) (define %services ;; Make sure guix-service uses 'guix-x86_64' package. (map (lambda (service) (if (eqv? 'guix (service-type-name (service-kind service))) (service guix-service-type (guix-configuration (guix guix-x86_64))) service)) %base-services)) (operating-system (host-name "host") (timezone "Europe/Moscow") (kernel linux-libre-x86_64) (bootloader (bootloader-configuration (bootloader grub-bootloader) (target "/dev/sda"))) (file-systems (cons* (file-system (device (file-system-label "guix")) (mount-point "/") (type "ext4")) %base-file-systems)) (users (list (user-account (name "al") (uid 1000) (home-directory "/home/al") (group "users") (supplementary-groups '("wheel" "audio" "video"))))) (packages (cons* iproute %base-packages)) (services (cons* (service loadkeys-service-type "dvorak") %services)))
null
https://raw.githubusercontent.com/alezost/guix-config/1fb884c7b1225a875537fe2856d3866f817d328b/system-config/os-32-to-64.scm
scheme
This is a simple example of an operating system declaration to move <-devel/2015-05/msg00392.html> for details. Make sure guix-service uses 'guix-x86_64' package.
from a 32 - bit system to a 64 - bit one . See the thread (use-modules (gnu) (guix monads) (guix store) ((guix build utils) #:select (alist-replace)) (guix packages) (gnu packages linux) (gnu packages package-management) (gnu services base) (al guix services linux)) (define linux-libre-x86_64 (package (inherit linux-libre) (arguments `(#:system "x86_64-linux" ,@(package-arguments linux-libre))) (native-inputs (alist-replace "kconfig" (list (string-append (getenv "HOME") "/src/guix/gnu/packages/linux-libre-x86_64.conf")) (package-native-inputs linux-libre))))) (define guix-x86_64 (package (inherit guix) (arguments `(#:system "x86_64-linux" ,@(package-arguments guix))))) (define %services (map (lambda (service) (if (eqv? 'guix (service-type-name (service-kind service))) (service guix-service-type (guix-configuration (guix guix-x86_64))) service)) %base-services)) (operating-system (host-name "host") (timezone "Europe/Moscow") (kernel linux-libre-x86_64) (bootloader (bootloader-configuration (bootloader grub-bootloader) (target "/dev/sda"))) (file-systems (cons* (file-system (device (file-system-label "guix")) (mount-point "/") (type "ext4")) %base-file-systems)) (users (list (user-account (name "al") (uid 1000) (home-directory "/home/al") (group "users") (supplementary-groups '("wheel" "audio" "video"))))) (packages (cons* iproute %base-packages)) (services (cons* (service loadkeys-service-type "dvorak") %services)))
7123d39ff977dd2bbd41602f6183882b4583eef4b7e5a42cc8568a8590e923f3
c4-project/c4f
replay.ml
This file is part of c4f . Copyright ( c ) 2018 - 2022 C4 Project c4 t itself is licensed under the MIT License . See the LICENSE file in the project root for more information . Parts of c4 t are based on code from the Herdtools7 project ( ) : see the LICENSE.herd file in the project root for more information . Copyright (c) 2018-2022 C4 Project c4t itself is licensed under the MIT License. See the LICENSE file in the project root for more information. Parts of c4t are based on code from the Herdtools7 project () : see the LICENSE.herd file in the project root for more information. *) open Core let run ?(state_output : Plumbing.Output.t option) (args : _ Common_cmd.Args.With_files.t) (o : C4f_common.Output.t) ~(trace_input : Plumbing.Input.t) : unit Or_error.t = Or_error.Let_syntax.( let%bind trace = C4f_fuzz.Trace.load trace_input in let aux = C4f_fuzz_run.Filter.Aux.Replay.make ~o trace in (* There's no point exposing the trace here; it'll be the same as the input one. *) let%bind {state; _} = Common_cmd.Args.With_files.run_filter (C4f_fuzz_run.Filter.run_replay ~aux) args in Plumbing.Output.with_opt state_output ~f:(fun dest -> C4f_fuzz.State.Dump.store state ~dest )) let readme () : string = C4f_utils.My_string.format_for_readme {| This command takes a C litmus test and fuzzer trace as input, applies the mutations listed in the trace to the test, and outputs the resulting modified test. |} let command : Command.t = Command.basic ~summary:"replay a fuzzing trace on a C litmus test" ~readme Command.Let_syntax.( let%map_open standard_args = Common_cmd.Args.(With_files.get Standard.get) and trace_input = flag "trace" (required Common_cmd.Args.input_type) ~doc:"FILE read a trace of completed fuzz actions to this filename" and state_output = flag "state-output" (optional Common_cmd.Args.output_type) ~doc: "FILE if given, dump a summary of the final fuzzer state to \ this filename" in fun () -> Common_cmd.Args.Standard.lift_command (Common_cmd.Args.With_files.rest standard_args) ~f:(run standard_args ~trace_input ?state_output))
null
https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/cmd_fuzz/src/replay.ml
ocaml
There's no point exposing the trace here; it'll be the same as the input one.
This file is part of c4f . Copyright ( c ) 2018 - 2022 C4 Project c4 t itself is licensed under the MIT License . See the LICENSE file in the project root for more information . Parts of c4 t are based on code from the Herdtools7 project ( ) : see the LICENSE.herd file in the project root for more information . Copyright (c) 2018-2022 C4 Project c4t itself is licensed under the MIT License. See the LICENSE file in the project root for more information. Parts of c4t are based on code from the Herdtools7 project () : see the LICENSE.herd file in the project root for more information. *) open Core let run ?(state_output : Plumbing.Output.t option) (args : _ Common_cmd.Args.With_files.t) (o : C4f_common.Output.t) ~(trace_input : Plumbing.Input.t) : unit Or_error.t = Or_error.Let_syntax.( let%bind trace = C4f_fuzz.Trace.load trace_input in let aux = C4f_fuzz_run.Filter.Aux.Replay.make ~o trace in let%bind {state; _} = Common_cmd.Args.With_files.run_filter (C4f_fuzz_run.Filter.run_replay ~aux) args in Plumbing.Output.with_opt state_output ~f:(fun dest -> C4f_fuzz.State.Dump.store state ~dest )) let readme () : string = C4f_utils.My_string.format_for_readme {| This command takes a C litmus test and fuzzer trace as input, applies the mutations listed in the trace to the test, and outputs the resulting modified test. |} let command : Command.t = Command.basic ~summary:"replay a fuzzing trace on a C litmus test" ~readme Command.Let_syntax.( let%map_open standard_args = Common_cmd.Args.(With_files.get Standard.get) and trace_input = flag "trace" (required Common_cmd.Args.input_type) ~doc:"FILE read a trace of completed fuzz actions to this filename" and state_output = flag "state-output" (optional Common_cmd.Args.output_type) ~doc: "FILE if given, dump a summary of the final fuzzer state to \ this filename" in fun () -> Common_cmd.Args.Standard.lift_command (Common_cmd.Args.With_files.rest standard_args) ~f:(run standard_args ~trace_input ?state_output))
e98d7435dda41935d1eb09dea24fcf1545d12d1d60e5b5cae53eff2439b3bf60
janestreet/bonsai
vdom_examples.ml
open! Core open! Bonsai_web (* $MDX part-begin=hello_world *) let hello_world : Vdom.Node.t = Vdom.Node.text "hello world!" (* $MDX part-end *) let () = Util.run_vdom hello_world ~id:"hello_world" (* $MDX part-begin=bulleted_list *) let bulleted_list : Vdom.Node.t = let open Vdom.Node in div [ h3 [ text "Norwegian Pancakes" ] ; ul [ li [ text "3 eggs" ] ; li [ text "2 cups of milk" ] ; li [ text "1 cup of flour" ] ] ] ;; (* $MDX part-end *) let () = Util.run_vdom bulleted_list ~id:"bulleted_list" let alert s = Js_of_ocaml.Dom_html.window##alert (Js_of_ocaml.Js.string s) (* $MDX part-begin=input_placeholder *) let input_placeholder : Vdom.Node.t = Vdom.Node.input ~attr:(Vdom.Attr.placeholder "placeholder text here") () ;; (* $MDX part-end *) let () = Util.run_vdom input_placeholder ~id:"input_placeholder" (* $MDX part-begin=css_gen *) let css_gen : Vdom.Node.t = Vdom.Node.span ~attr:(Vdom.Attr.style (Css_gen.color (`Name "red"))) [ Vdom.Node.text "this text is red" ] ;; (* $MDX part-end *) let () = Util.run_vdom css_gen ~id:"css_gen" type mouse_event = Js_of_ocaml.Dom_html.mouseEvent Js_of_ocaml.Js.t (* Running side-effects directly inside an event-handler is not ideal, but I didn't want to take a dependency on "Effect"s before introducing Events. In real code, prefer passing in an "inject_alert" function that is backed by [Effect.of_sync_fun]. That would make this component testable ([alert] is not supported in nodejs) *) (* $MDX part-begin=clicky_button *) let clicky : Vdom.Node.t = Vdom.Node.button ~attr: (Vdom.Attr.on_click (fun (_evt : mouse_event) -> alert "hello there!"; Ui_effect.Ignore)) [ Vdom.Node.text "click me!" ] ;; (* $MDX part-end *) let () = Util.run_vdom clicky ~id:"clicky_button"
null
https://raw.githubusercontent.com/janestreet/bonsai/33e9a58fc55ec12095959dc5ef4fd681021c1083/examples/bonsai_guide_code/vdom_examples.ml
ocaml
$MDX part-begin=hello_world $MDX part-end $MDX part-begin=bulleted_list $MDX part-end $MDX part-begin=input_placeholder $MDX part-end $MDX part-begin=css_gen $MDX part-end Running side-effects directly inside an event-handler is not ideal, but I didn't want to take a dependency on "Effect"s before introducing Events. In real code, prefer passing in an "inject_alert" function that is backed by [Effect.of_sync_fun]. That would make this component testable ([alert] is not supported in nodejs) $MDX part-begin=clicky_button $MDX part-end
open! Core open! Bonsai_web let hello_world : Vdom.Node.t = Vdom.Node.text "hello world!" let () = Util.run_vdom hello_world ~id:"hello_world" let bulleted_list : Vdom.Node.t = let open Vdom.Node in div [ h3 [ text "Norwegian Pancakes" ] ; ul [ li [ text "3 eggs" ] ; li [ text "2 cups of milk" ] ; li [ text "1 cup of flour" ] ] ] ;; let () = Util.run_vdom bulleted_list ~id:"bulleted_list" let alert s = Js_of_ocaml.Dom_html.window##alert (Js_of_ocaml.Js.string s) let input_placeholder : Vdom.Node.t = Vdom.Node.input ~attr:(Vdom.Attr.placeholder "placeholder text here") () ;; let () = Util.run_vdom input_placeholder ~id:"input_placeholder" let css_gen : Vdom.Node.t = Vdom.Node.span ~attr:(Vdom.Attr.style (Css_gen.color (`Name "red"))) [ Vdom.Node.text "this text is red" ] ;; let () = Util.run_vdom css_gen ~id:"css_gen" type mouse_event = Js_of_ocaml.Dom_html.mouseEvent Js_of_ocaml.Js.t let clicky : Vdom.Node.t = Vdom.Node.button ~attr: (Vdom.Attr.on_click (fun (_evt : mouse_event) -> alert "hello there!"; Ui_effect.Ignore)) [ Vdom.Node.text "click me!" ] ;; let () = Util.run_vdom clicky ~id:"clicky_button"
cd59eea1a0e95a62f943162ccc528db1fd0ea0a05b1cfb846b7834cc3002b6bc
gregtatcam/imaplet-lwt
dedup.ml
open Lwt open Imaplet open Commands open Parsemail open Server_config module MapStr = Map.Make(String) let dedup = ref MapStr.empty let () = Lwt_main.run ( let config = {srv_config with compress = false;compress_attach = false; encrypt = false } in Utils.fold_email_with_file Sys.argv.(1) (fun cnt message -> Printf.printf "message %d, size %d\n%!" cnt ((String.length message)/(1024*1024)); Ssl_.get_system_keys Server_config.srv_config >>= fun (pub,_) -> Email_parse.parse pub config message ~save_message:(fun _ _ _ _ _ -> return ()) ~save_attachment:(fun _ _ attachment -> let hash = Imap_crypto.get_hash ~hash:`Sha1 attachment in if MapStr.exists (fun k _ -> k = hash) !dedup then ( let (v,s,c) = MapStr.find hash !dedup in dedup := MapStr.add hash (v+1,s,c) !dedup; Printf.printf "found duplicate %s,%d,%d\n" hash (v+1) s ) else ( let comps = String.length (Imap_crypto.do_compress ~header:true attachment) in dedup := MapStr.add hash (1, String.length attachment,comps) !dedup ); return () ) >>= fun _ -> return (`Ok (cnt+1)) ) 1 >>= fun _ -> let (dup,total,ctotal) = MapStr.fold (fun k (cnt,size,comps) (dup,total,ctotal) -> if cnt > 1 then ( (dup+1,total+size*(cnt-1),ctotal+comps*(cnt-1)) ) else ( (dup,total,ctotal) ) ) !dedup (0,0,0) in Printf.printf "duplicate attachments: %d, size %d, compressed size %d\n%!" dup total ctotal; return () )
null
https://raw.githubusercontent.com/gregtatcam/imaplet-lwt/d7b51253e79cffa97e98ab899ed833cd7cb44bb6/test/dedup.ml
ocaml
open Lwt open Imaplet open Commands open Parsemail open Server_config module MapStr = Map.Make(String) let dedup = ref MapStr.empty let () = Lwt_main.run ( let config = {srv_config with compress = false;compress_attach = false; encrypt = false } in Utils.fold_email_with_file Sys.argv.(1) (fun cnt message -> Printf.printf "message %d, size %d\n%!" cnt ((String.length message)/(1024*1024)); Ssl_.get_system_keys Server_config.srv_config >>= fun (pub,_) -> Email_parse.parse pub config message ~save_message:(fun _ _ _ _ _ -> return ()) ~save_attachment:(fun _ _ attachment -> let hash = Imap_crypto.get_hash ~hash:`Sha1 attachment in if MapStr.exists (fun k _ -> k = hash) !dedup then ( let (v,s,c) = MapStr.find hash !dedup in dedup := MapStr.add hash (v+1,s,c) !dedup; Printf.printf "found duplicate %s,%d,%d\n" hash (v+1) s ) else ( let comps = String.length (Imap_crypto.do_compress ~header:true attachment) in dedup := MapStr.add hash (1, String.length attachment,comps) !dedup ); return () ) >>= fun _ -> return (`Ok (cnt+1)) ) 1 >>= fun _ -> let (dup,total,ctotal) = MapStr.fold (fun k (cnt,size,comps) (dup,total,ctotal) -> if cnt > 1 then ( (dup+1,total+size*(cnt-1),ctotal+comps*(cnt-1)) ) else ( (dup,total,ctotal) ) ) !dedup (0,0,0) in Printf.printf "duplicate attachments: %d, size %d, compressed size %d\n%!" dup total ctotal; return () )
f536c4d99a619e6bbe16f2bd1cef8ac6b00fdb611b3579fbc8654ac718813a8d
marijnh/Postmodern
util.lisp
-*- Mode : LISP ; Syntax : Ansi - Common - Lisp ; Base : 10 ; Package : POSTMODERN ; -*- (in-package :postmodern) (defun make-keyword (name) (values (intern (string-upcase name) "KEYWORD"))) (defun valid-sql-character-p (chr) "Returns t if chr is letter, underscore, digits or dollar sign" (or (uax-15:unicode-letter-p chr) (digit-char-p chr) (eq chr #\_) (eq chr #\$))) (defun code-char-0-p (chr) "Returns t if character has char-code 0 (generally #\Nul)" (eq chr (code-char 0))) (defun valid-sql-identifier-p (str) "Takes a string and returns it if it is a valid sql identifier. See -syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS. First test is for a quoted string, which has less restrictions. " (cond ((and (stringp str) (eq (char str 0) #\") (eq (char str (- (length str) 1)) #\") (notany #'code-char-0-p str)) str) ((and (stringp str) (or (uax-15:unicode-letter-p (char str 0)) (eq (char str 0) #\_)) (every #'valid-sql-character-p str))) (t nil))) (defun to-identifier (name) "Used to allow both strings and symbols as identifier - converts symbols to string with the S-SQL rules." (if (stringp name) name (to-sql-name name))) (defun coalesce (&rest args) "Returns the first non-NIL, non-NULL (as in :null) argument, or NIL if none are present. Useful for providing a fall-back value for the result of a query, or, when given only one argument, for transforming :nulls to NIL." (some (lambda (x) (if (eq x :null) nil x)) args)) (defun database-version () "DEPRECATED BECAUSE IT IS CONFUSING. IT IS REALLY THE POSTGRESQL SERVER VERSION NOT A DATABASE VERSION. USE POSTGRESQL-VERSION INSTEAD. Returns the version string provided by postgresql of the current postgresql server E.g. 'PostgreSQL 12.2 on x86_64-pc-linux-gnu, compiled by gcc (Arch Linux 9.3.0-1) 9.3.0, 64-bit'. If you want just the postgresql version number, use cl-postgres:get-postgresql-version." (query (:select (:version)) :single)) (defun postgresql-version () "Returns the version string provided by postgresql of the current postgresql server E.g. 'PostgreSQL 12.2 on x86_64-pc-linux-gnu, compiled by gcc (Arch Linux 9.3.0-1) 9.3.0, 64-bit'. If you want just the postgresql version number, use cl-postgres:get-postgresql-version." (query (:select (:version)) :single)) (defmacro make-list-query (relkind) "Helper macro for the functions that list tables, sequences, and views." `(sql (:order-by (:select 'relname :from 'pg-catalog.pg-class :inner-join 'pg-catalog.pg-namespace :on (:= 'relnamespace 'pg-namespace.oid) :where (:and (:= 'relkind ,relkind) (:not-in 'nspname (:set "pg_catalog" "pg_toast")) (:pg-catalog.pg-table-is-visible 'pg-class.oid))) 'relname))) (defmacro make-exists-query (relkind name) "Helper macro for the functions that check whether an object exists. Only works for public schema" `(sql (:select (:exists (:select 'relname :from 'pg_catalog.pg_class :inner-join 'pg_catalog.pg_namespace :on (:= 'pg_class.relnamespace 'pg_namespace.oid) :where (:and (:= 'pg_class.relkind ,relkind) (:= 'pg_namespace.nspname (:any* (:current_schemas "true"))) (:= 'pg_class.relname (to-identifier ,name)))))))) (defun split-fully-qualified-tablename (name) "Take a tablename of the form database.schema.table or schema.table or table and return the tablename and the schema name. The name can be a symbol or a string. Returns a list of form '(table schema database. If the tablename is not fully qualified, it will assume that the schema should be \"public\"." (destructuring-bind (table &optional schema database) (nreverse (split-sequence:split-sequence #\. (to-sql-name name) :test 'equal)) (when (not schema) (setf schema "public")) (list table schema database))) (defun postgres-array-string-to-list (str) "Takes a postgresql array in the form of a string like \"{wol=CTc/wol,a=c/wol,b=c/wol}\" and returns a lisp list like (\"wol=CTc/wol\" \"a=c/wol\" \"b=c/wol\")." (split-sequence:split-sequence #\, (subseq str 1 (- (length str) 1)))) (defun postgres-array-string-to-array (str) "Takes a postgresql array in the form of a string like \"{wol=CTc/wol,a=c/wol,b=c/wol}\" and returns a lisp array like #(\"wol=CTc/wol\" \"a=c/wol\" \"b=c/wol\")" (let* ((lst (postgres-array-string-to-list str)) (len (length lst))) (make-array len :initial-contents lst))) (defun add-comment (type name comment &optional (second-name "")) "Attempts to add a comment to a particular database object. The first parameter is a keyword for the type of database object. The second parameter is the name of the object. The third parameter is the comment itself. Some objects require an additional identifier. The names can be strings or symbols. Example usage would be: (add-comment :column 'country-locations.name \"Is what it looks like - the name of a country\".) (add-comment :column \"country_locations.name\" \"Is what it looks like - the name of a country\".) Example usage where two identifiers are required would be constraints: (add-comment :constraint 'constraint1 \"Some kind of constraint descriptions here\". 'country-locations)" (setf name (to-sql-name name)) (setf second-name (to-sql-name second-name)) (case type (:access-method (query (format nil "comment on ACCESS METHOD ~a is '~a'" name comment))) (:aggregate (query (format nil "comment on AGGREGATE ~a is '~a'" name comment))) (:cast (query (format nil "comment on CAST (~a as ~a) is '~a'" name second-name comment))) (:column (query (format nil "comment on COLUMN ~a is '~a'" name comment))) (:conversion (query (format nil "comment on CONVERSION m~a is '~a'" name comment))) (:constraint (query (format nil "comment on CONSTRAINT ~a on ~a is '~a'" name second-name comment))) (:domain-constraint (query (format nil "comment on CONSTRAINT ~a on DOMAIN ~a is '~a'" name second-name comment))) (:database (query (format nil "comment on DATABASE ~a is '~a'" name comment))) (:domain (query (format nil "comment on DOMAIN ~a is '~a'" name comment))) (:extension (query (format nil "comment on EXTENSION ~a is '~a'" name comment))) (:foreign-data-wrapper (query (format nil "comment on FOREIGN DATA WRAPPER ~a is '~a'" name comment))) (:foreign-table (query (format nil "comment on FOREIGN TABLE ~a is '~a'" name comment))) (:function (query (format nil "comment on FUNCTION ~a is '~a'" name comment))) (:index (query (format nil "comment on INDEX ~a is '~a'" name comment))) (:language (query (format nil "comment on LANGUAGE ~a is '~a'" name comment))) (:large-object (query (format nil "comment on LARGE OBJECT ~a is '~a'" name comment))) (:materialized-view (query (format nil "comment on MATERIALIZED VIEW ~a is '~a'" name comment))) (:operator (query (format nil "comment on OPERATOR ~a is '~a'" name comment))) (:operator-class (query (format nil "comment on OPERATOR CLASS ~a USING ~a is '~a'" name second-name comment))) (:operator-family (query (format nil "comment on OPERATOR FAMILY ~a USING ~a is '~a'" name second-name comment))) (:policy (query (format nil "comment on POLICY ~a on ~a is '~a'" name second-name comment))) (:procedure (query (format nil "comment on PROCEDURE ~a is '~a'" name comment))) (:role (query (format nil "comment on ROLE ~a is '~a'" name comment))) (:rule (query (format nil "comment on RULE ~a on ~a is '~a'" name second-name comment))) (:schema (query (format nil "comment on SCHEMA ~a is '~a'" name comment))) (:sequence (query (format nil "comment on SEQUENCE ~a is '~a'" name comment))) (:server (query (format nil "comment on SERVER ~a is '~a'" name comment))) (:statistics (query (format nil "comment on STATisTICS ~a is '~a'" name comment))) (:table (query (format nil "comment on TABLE ~a is '~a'" name comment))) (:tablespace (query (format nil "comment on TABLESPACE ~a is '~a'" name comment))) (:text-search-configuration (query (format nil "comment on TEXT SEARCH CONFIGURATIon ~a is '~a'" name comment))) (:text-search-dictionary (query (format nil "comment on TEXT SEARCH DICTIONARY ~a is '~a'" name comment))) (:text-search-parser (query (format nil "comment on TEXT SEARCH PARSER ~a is '~a'" name comment))) (:text-search-template (query (format nil "comment on TEXT SEARCH TEMPLATE ~a is '~a'" name comment))) (:trigger (query (format nil "comment on TRIGGER ~a on ~a is '~a'" name second-name comment))) (:type (query (format nil "comment on TYPE ~a is '~a'" name comment))) (:view (query (format nil "comment on VIEW ~a is '~a'" name comment))))) (defun find-comments (type identifier) "Returns the comments attached to a particular database object. The allowed types are :database :schema :table :columns (all the columns in a table) :column (for a single column). An example would be (find-comments :table 's2.employees) where the table employees is in the s2 schema." (ecase type (:database (get-database-comment identifier)) (:schema (get-schema-comment identifier)) (:table (get-table-comment identifier)) (:columns (get-column-comments identifier)) (:column (get-column-comment identifier)))) ;;; Databases (define-condition invalid-database-name (error) ((text :initarg :text :reader text)) (:documentation "Invalid-database-name indicates that this database does not exist in this cluster or the user does not have the permissions necessary to access this database.")) (defun database-exists-p (database) "Returns database name string if the database parameter is actually an available database" (query (:select (:exists (:select 'datname :from 'pg-database :where (:= 'datname '$1)))) (to-sql-name database) :single)) (defun list-available-collations () "Get a list of the collations available from the current database cluster. Collations are a mess as different operating systems provide different collations. We might get some sanity if Postgresql can use ICU as the default. See ." (setf *collations* (query "select collname from pg_collation"))) (defun collation-exists-p (collation) "This function does require the parameter to be a string and properly upper and lower cased." (query "select collname from pg_collation where collname = $1" collation :single)) (defun character-set-exists-p (char-support) "There is no good way that I know to determine the available character sets on a remote server so we just assume any postgresql usable set is available." (member char-support *character-sets* :test 'equalp)) (defun list-templates () "Returns a list of existing database template names." (query "select datname from pg_database where datistemplate is true")) (defun create-database (database-name &key (encoding "UTF8") (connection-limit -1) owner limit-public-access comment collation template) "Creates a basic database. Besides the obvious database-name parameter, you can also use key parameters to set encoding (defaults to UTF8), owner, connection-limit (defaults to no limit)). If limit-public-access is set to t, then only superuser roles or roles with explicit access to this database will be able to access it. If collation is set, the assumption is that template0 needs to be used rather than template1 which may contain encoding specific or locale specific data." (setf database-name (to-sql-name database-name)) (cond ((equal owner "") (setf owner (cl-postgres::connection-user *database*))) ((stringp owner) nil) (t (setf owner (cl-postgres::connection-user *database*)))) (if template (setf template (format nil "template ~a " template)) (setf template "")) (if collation (progn (setf template "template template0") (setf collation (format nil " lc_collate '~a' lc_ctype '~a'" collation collation))) (setf collation "")) (when (and (character-set-exists-p encoding) (integerp connection-limit)) (query (format nil "create database ~a owner ~a ~a encoding ~a ~a connection limit = ~a" database-name owner template encoding collation connection-limit)) (when limit-public-access (query (format nil "revoke all privileges on database ~a from public;" database-name))) (when comment (query (format nil "comment on database ~a is '~a'" database-name comment)))) (with-connection (list database-name (cl-postgres::connection-user *database*) (cl-postgres::connection-password *database*) (cl-postgres::connection-host *database*) :port (cl-postgres::connection-port *database*) :use-ssl (cl-postgres::connection-use-ssl *database*)) (when (member "pg_stat_statements" (list-available-extensions) :test #'equal) (query "CREATE EXTENSION IF NOT EXISTS pg_stat_statements;")))) (defun drop-database (database) "Drop the specified database. The database parameter can be a string or a symbol. Note: Only the owner of a database can drop a database and there cannot be any current connections to the database." (setf database (to-sql-name database)) (if (database-exists-p database) (query (format nil "drop database ~a" database)) (cerror "invalid database name provided" 'invalid-database-name))) (defun num-records-in-database () "Returns a list of lists with schema, table name and approximate number of records in the currently connected database." (query (:order-by (:select 'schemaname 'relname 'n_live_tup :from 'pg_stat_user_tables) (:desc 'n_live_tup)))) (defun current-database () "Returns the string name of the current database." (query (:select (:current-database)) :single)) (defun database-size (&optional (name nil)) "Given the name of a database, will return the name, a pretty-print string of the size of the database and the size in bytes. If a database name is not provided, it will return the result for the currently connected database." (unless name (setf name (current-database))) (first (query (:select 'datname (:pg-size-pretty (:pg-database-size 'pg-database.oid)) (:pg-database-size 'pg-database.oid) :from 'pg-database :where (:= 'datname '$1)) (to-sql-name name)))) (defun get-database-comment (&optional database-name) "Returns the comment, if any, attached to a database" (if database-name (setf database-name (to-sql-name database-name)) (setf database-name (current-database))) (query "SELECT pg_catalog.shobj_description(d.oid, 'pg_database') FROM pg_catalog.pg_database d WHERE datname = $1" database-name :single)) (defun list-databases (&key (order-by-size nil) (size t) (names-only nil)) "Returns a list of lists where each sub-list contains the name of the database, a pretty-print string of the size of that database and the size in bytes. The default order is by database name. Pass t as a parameter to :order-by-size for order by size. Setting size to nil will return just the database names in a single list ordered by name. This function excludes the template databases." (if order-by-size (setf order-by-size (sql (:desc (:pg-database-size 'pg-database.oid)))) (setf order-by-size " datname")) (cond (names-only (alexandria:flatten (query (:order-by (:select 'datname :from 'pg-database :where (:not (:like 'datname "template%"))) 'datname)))) (size (query (:order-by (:select 'datname (:pg-size-pretty (:pg-database-size 'pg-database.oid)) (:pg-database-size 'pg-database.oid) :from 'pg-database :where (:not (:like 'datname "template%"))) (:raw order-by-size)))) (t (alexandria:flatten (query (:order-by (:select 'datname :from 'pg-database :where (:not (:like 'datname "template%"))) (:raw order-by-size))))))) (defun list-database-access-rights (&optional database-name) "If the database parameter is specifed, this returns an list of lists where each sublist is a role name and whether they have access rights (T or NIL) to that particular database. If the database-name is not provided, the sublist is a database name, a role name and whether they have access rights (T or NIL)." (if database-name (progn (when (symbolp database-name) (setf database-name (to-sql-name database-name))) (query (:order-by (:select 'r.rolname (:has-database-privilege 'r.rolname 'db.datname "connect") :from (:as 'pg-roles 'r) :cross-join (:as 'pg-database 'db) :where (:and 'r.rolcanlogin 'db.datallowconn (:= 'db.datname '$1))) 'r.rolname) database-name)) (query (:order-by (:select 'db.datname 'r.rolname (:has-database-privilege 'r.rolname 'db.datname "connect") :from (:as 'pg-roles 'r) :cross-join (:as 'pg-database 'db) :where (:and 'r.rolcanlogin 'db.datallowconn (:not 'datistemplate))) 'db.datname 'r.rolname)))) (defun list-role-accessible-databases (role-name) "Returns a list of the databases to which the specified role can connect." (when (symbolp role-name) (setf role-name (to-sql-name role-name))) (when (role-exists-p role-name) (alexandria:flatten (query (:select 'datname :from 'pg-database :where (:and (:has-database-privilege '$1 'datname "CONNECT") (:not (:like 'datname "template%")))) role-name)))) Schemas (defun get-schema-comment (schema-name) "If the schema has been commented, returns that string, else nil. Must be a schema in the currently connected database." (query "select obj_description($1::regnamespace)" (to-sql-name schema-name) :single)) ;;;; See namespace.lisp ;;; Sequences (defun sequence-next (sequence) "Shortcut for getting the next value from a sequence. The sequence identifier can be either a string or a symbol, in the latter case it will be converted to a string according to S-SQL rules." (query (:select (:nextval (to-identifier sequence))) :single)) (defun create-sequence (name &key temp if-not-exists increment min-value max-value start cache) "Create a sequence. Available additional key parameters are :temp :if-not-exists :increment :min-value :max-value :start and :cache. See -createsequence.html for details on usage." (let ((query-string (concatenate 'string "CREATE " (if temp "TEMP " "") "SEQUENCE " (if if-not-exists "IF NOT EXISTS " "") (to-sql-name name) (if increment (concatenate 'string " INCREMENT BY " (format nil "~a" increment)) "") (if min-value (concatenate 'string " MINVALUE " (format nil "~a" min-value)) "") (if max-value (concatenate 'string " MAXVALUE " (format nil "~a" max-value)) "") (if start (concatenate 'string " START " (format nil "~a" start)) "") (if cache (concatenate 'string " CACHE " (format nil "~a" cache)) "")))) (query query-string))) (defun drop-sequence (name &key if-exists cascade) "Drop a sequence. Name should be quoted. Available key parameters are :if-exists and :cascade" (let ((query-string (concatenate 'string "DROP SEQUENCE " (if if-exists "IF EXISTS " "") (to-sql-name name) (if cascade " CASCADE" "")))) (query query-string))) (defun list-sequences (&optional strings-p) "Return a list of the sequences in a database. Turn them into keywords if strings-p is not true." (let ((result (query (make-list-query "S") :column))) (if strings-p result (mapcar 'from-sql-name result)))) (defun sequence-exists-p (sequence) "Tests whether a sequence with the given name exists. The name can be either a string or a symbol." (query (make-exists-query "S" (to-sql-name sequence)) :single)) Tablespaces (defun list-tablespaces () "Lists the tablespaces in the currently connected database. What are tablespace you ask? Per the Postgresql documentation -ag-tablespaces.html: Tablespaces in PostgreSQL allow database administrators to define locations in the file system where the files representing database objects can be stored. Once created, a tablespace can be referred to by name when creating database objects. By using tablespaces, an administrator can control the disk layout of a PostgreSQL installation. This is useful in at least two ways. First, if the partition or volume on which the cluster was initialized runs out of space and cannot be extended, a tablespace can be created on a different partition and used until the system can be reconfigured. Second, tablespaces allow an administrator to use knowledge of the usage pattern of database objects to optimize performance. For example, an index which is very heavily used can be placed on a very fast, highly available disk, such as an expensive solid state device. At the same time a table storing archived data which is rarely used or not performance critical could be stored on a less expensive, slower disk system." (alexandria:flatten (query (:order-by (:select (:as 'spcname 'name) :from 'pg_tablespace) 'spcname)))) ;;;; Types (defun list-available-types () "List the available data types in the connected postgresql version, It returns a list of lists, each sublist containing the oid (object identifier number) and the name of the data types. E.g. (21 \"smallint\")" (query (:select 'oid (:as (:format-type :oid :NULL) 'typename) :from 'pg-type :where (:= 'typtype "b")))) ;;; Tables (define-condition inconsistent-schema-name (error) ((text :initarg :text :reader text))) (defun table-schema-names (table-name schema-name) "Helper function to allow for fully qualified table names and non-qualified tables names that just exist in public schema or in a separately stated schema in the second parameter. Will thrown an error if the table-name is fully qualified and has a schema name different than the specified schema name." (let ((split-name (split-fully-qualified-tablename table-name))) (setf table-name (first split-name)) (cond ((and schema-name (not (string= (second split-name) "public")) (not (string= (second split-name) (to-sql-name schema-name)))) (error 'inconsistent-schema-name :text (format nil "You have specified a schema name ~a and an inconsistent schema name in a fully qualified table name ~a" schema-name (second split-name)))) ((not schema-name) (setf schema-name (second split-name))) (t (setf schema-name (to-sql-name schema-name)))) (values table-name schema-name))) ;;; create table can only be done either using a deftable approach or s-sql (defun get-table-comment (table-name &optional schema-name) "Retrieves the comment, if any attached to the table." (multiple-value-bind (tn sn) (table-schema-names table-name schema-name) (query (format nil "select obj_description($1::regclass)") (concatenate 'string sn "." tn) :single))) (defun get-all-table-comments () "Returns a list of lists, each list showing the schema, table and comment of all tables with comments." (query "select pg_namespace.nspname as schema, relname as table, description from pg_description inner join pg_class on objoid = oid inner join pg_namespace on pg_namespace.oid = pg_class.relnamespace where relkind = 'r'")) (defun get-table-oid (table-name &optional schema-name) "Retrieves the oid identifier for a particular table from postgresql. Works for tables in all schemas." (multiple-value-bind (tn sn) (table-schema-names table-name schema-name) (query (:select 'pg-class.oid :from 'pg-class :inner-join 'pg-namespace :on (:= 'pg-namespace.oid 'pg-class.relnamespace) :where (:and (:= 'pg-class.relname '$1) (:= 'pg-namespace.nspname '$2))) tn sn :single))) (defun table-description (table-name &optional schema-name) "Returns a list of the fields in the named table. Each field is represented by a list of three elements: the field name, the type, and a boolean indicating whether the field may be NULL. Table can be either a string or quoted. Table-names can be fully qualified with the schema or not. If the table-name is not fully qualified and a schema name is not provided, the table will be assumed to be in the public schema." (multiple-value-bind (tn sn) (table-schema-names table-name schema-name) (mapcar #'butlast (query (:order-by (:select 'attname 'typname (:not 'attnotnull) 'attnum :distinct :from 'pg-attribute :inner-join 'pg-type :on (:= 'pg-type.oid 'atttypid) :inner-join 'pg-class :on (:and (:= 'pg-class.oid 'attrelid) (:= 'pg-class.relname '$1)) :inner-join 'pg-namespace :on (:= 'pg-namespace.oid 'pg-class.relnamespace) :where (:and (:> 'attnum 0) (:= 'pg-namespace.nspname '$2))) 'attnum) tn sn)))) (defun table-description-plus (table-name &optional schema-name) "Returns more table info than table-description. It defaults to returning column-name, data-type, character-maximum-length, modifier, whether it is not-null and the default value. Table can be either a string or quoted. Table-names can be fully qualified with the schema or not. If the table-name is not fully qualified and a schema name is not provided, the table will be assumed to be in the public schema." (multiple-value-bind (tn sn) (table-schema-names table-name schema-name) (mapcar #'butlast (query (:order-by (:select (:as 'a.attname 'column-name) (:as 'tn.typname 'data-type) (:as 'a.attlen 'character-maximum-length) (:as 'a.atttypmod 'modifier) (:as 'a.attnotnull 'notnull) (:as 'a.atthasdef 'hasdefault) (:as 'a.attnum 'ordinal-position) :distinct :from (:as 'pg-attribute 'a) :inner-join (:as 'pg-type 'tn) :on (:= 'tn.oid 'a.atttypid) :inner-join 'pg-class :on (:and (:= 'pg-class.oid 'attrelid) (:= 'pg-class.relname '$1)) :inner-join 'pg-namespace :on (:= 'pg-namespace.oid 'pg-class.relnamespace) :where (:and (:> 'attnum 0) (:= 'pg-namespace.nspname '$2))) 'ordinal-position) tn sn)))) (defun table-parameter-helper (version>11 version>10 char-max-length data-type-length has-default default-value not-null numeric-precision numeric-scale storage primary primary-key-name unique unique-key-name fkey fkey-name fkey-col-id fkey-table fkey-local-col-id identity generated collation col-comments locally-defined inheritance-count stat-collection) (let ((param-list (list "t.typname AS data_type_name" "f.attname as column_name"))) (when char-max-length (push " CASE WHEN f.atttypmod >= 0 AND t.typname <> 'numeric' THEN (f.atttypmod - 4) --first 4 bytes are for storing actual length of data END AS character_maximum_length" param-list)) (when data-type-length (push " f.attlen as data_type_length " param-list)) (when has-default (push " case when f.atthasdef then f.atthasdef else null end as has_default" param-list)) (when default-value (push " CASE WHEN f.atthasdef = 't' THEN pg_get_expr(d.adbin, d.adrelid) END AS default_value " param-list)) (when not-null (push "case when f.attnotnull then f.attnotnull else null end as not_null " param-list)) (when numeric-precision (push " CASE WHEN t.typname = 'numeric' THEN (((f.atttypmod - 4) >> 16) & 65535) END AS numeric_precision " param-list)) (when numeric-scale (push " CASE WHEN t.typname = 'numeric' THEN ((f.atttypmod - 4)& 65535 ) END AS numeric_scale " param-list)) (when storage (push " CASE WHEN f.attstorage ='p' THEN 'plain' WHEN f.attstorage ='m' THEN 'main' WHEN f.attstorage ='e' THEN 'external' WHEN f.attstorage ='x' THEN 'extended' END as storage " param-list)) (when primary (push " CASE WHEN p.contype = 'p' THEN 'Primary' ELSE '' END AS primary " param-list)) (when primary-key-name (push " CASE WHEN p.contype = 'p' THEN p.conname END AS primary_key_name " param-list)) (when unique (push " CASE WHEN p.contype = 'u' THEN True ELSE null END AS unique " param-list)) (when unique-key-name (push " CASE WHEN p.contype = 'u' THEN p.conname END AS unique_key_name " param-list)) (when fkey (push " CASE WHEN p.contype = 'f' THEN True ELSE NULL END AS fkey " param-list)) (when fkey-name (push " CASE WHEN p.contype = 'f' THEN p.conname END AS fkey_name " param-list)) (when fkey-col-id (push " CASE WHEN p.contype = 'f' THEN p.confkey END AS fkey_col_id " param-list)) (when fkey-table (push " CASE WHEN p.contype = 'f' THEN g.relname END AS fkey_table " param-list)) (when fkey-local-col-id (push " CASE WHEN p.contype = 'f' THEN p.conkey END AS fkey_local_col_id " param-list)) (when (and identity version>10) (push " case when f.attidentity ='a' then 'generated always' when f.attidentity = 'd' then 'generated by default' else null end as identity " param-list)) (when (and generated version>11) (push " case when f.attgenerated ='s' then 'stored' else null end as generated " param-list)) (when collation (push " (select c.collname from pg_catalog.pg_collation as c, pg_catalog.pg_type t where c.oid = f.attcollation and t.oid = f.atttypid and f.attcollation <> t.typcollation) AS collation " param-list)) (when col-comments (push " pg_catalog.col_description(f.attrelid, f.attnum) as col_comments " param-list)) (when locally-defined (push " case when f.attislocal then true else null end as locally_defined " param-list)) (when inheritance-count (push " f.attinhcount inheritance_count " param-list)) (when stat-collection (push " CASE WHEN f.attstattarget=-1 THEN NULL ELSE f.attstattarget END AS stat_collection " param-list)) (format nil "~{~a~^, ~}" (nreverse param-list)))) (defun table-description-menu (table-name &key (char-max-length t) (data-type-length t) (has-default t) (default-value t) (not-null t) (numeric-precision t) (numeric-scale t) (storage t) (primary t) (primary-key-name t) (unique t) (unique-key-name t) (fkey t) (fkey-name t) (fkey-col-id t) (fkey-table t) (fkey-local-col-id t) (identity t) (generated t) (collation t) (col-comments t) (locally-defined t) (inheritance-count t) (stat-collection t)) "Takes a fully qualified table name which can be either a string or a symbol. Returns three values. 1. A list of plists of each row's parameters. This will always include :column-name and :data-type-name but all other parameters can be set or unset and are set by default (set to t). 2. The comment string attached to the table itself (if any). 3. A list of the check constraints applied to the rows in the table. See documentation for list-check-constraints for an example. The available keyword parameters are: - char-max-length (Typically used for something like a varchar and shows the maximum length) - data-type-length (For a fixed-size type, typlen is the number of bytes in the internal representation of the type. But for a variable-length type, typlen is negative. -1 indicates a “varlena” type (one that has a length word), -2 indicates a null-terminated C string.) - has-default (value T if this column has a default value and :NULL if not) - default-value (value is the default value as string. A default of 9.99 will still be a string) - not-null (value is T if the column must have a value or :NULL otherwise) - numeric-precision (value is the total number of digits for a numeric type if that precision was specified) - numeric-scale (value is the number of digits in the fraction part of a numeric type if that scale was specified) - storage (value is the storage setting for a column. Result can be plain, extended, main or external) - primary (value is T if the column is the primary key for the table, :NULL otherwise) - primary-key-name (value is the name of the primary-key itself, not the column, if the column is the primary key for the table, :NULL otherwise) - unique (value is T if the column is subject to a unique key, :NULL otherwise) - unique-key-name (value is the name of the unique-key itself, not the column, applied to the column, :NULL otherwise) - fkey (value is T if the column is a foreign key, :NULL otherwise) - fkey-name (value is the name of the foreign key, :NULL otherwise) - fkey-col-id (value is the column id of the foreign table used as the foreign key. Probably easier to use the Postmodern function list-foreign-keys if you are looking for the name of the columns) - fkey-table (value is the name of the foreign table, :NULL otherwise) - fkey-local-col-id (value is the column id of this column. Probably easier to use the Postmodern function list-foreign-keys if you are looking for the name of the columns involved in the foreign key) - identity (if the column is an identity column, the values can be 'generated always' or 'generated by default'. Otherwise :NULL) - generated (columns can be generated, if this column is generated and stored on disk, the value will be 'stored', otherwise :NULL) - collation (columns with collations which are not the default collation for the database will show that collation here, otherwise :NULL) - col-comments (value is any comment that has been applied to the column, :NULL otherwise) - locally-defined (value is T if locally defined. It might be both locally defined and inherited) - inheritance-count (the number of direct ancestors this column has inherited) - stat-collection (stat-collection returns the value of attstattarget which controls the level of detail of statistics accumulated for this column by ANALYZE. A zero value indicates that no statistics should be collected. A negative value says to use the system default statistics target. The exact meaning of positive values is data type-dependent. For scalar data types, attstattarget is both the target number of most common values to collect, and the target number of histogram bins to create. Attstorage is normally a copy of pg_type.typstorage of this column's type. For TOAST-able data types, this can be altered after column creation to control storage policy.)" (let* ((version>11 (cl-postgres:postgresql-version-at-least "12.0" pomo:*database*)) (version>10 (cl-postgres:postgresql-version-at-least "11.0" pomo:*database*))) (destructuring-bind (table schema database) (pomo:split-fully-qualified-tablename table-name) (declare (ignore database)) (setf schema (to-sql-name schema)) (setf table (to-sql-name table)) (when (and (pomo:schema-exists-p schema) (pomo:table-exists-p (concatenate 'string schema "." table))) (let ((overall-description (get-table-comment table schema)) (constraint-checks (list-check-constraints table-name)) (col-descriptions (query (format nil "SELECT ~a FROM pg_attribute f JOIN pg_class c ON c.oid = f.attrelid JOIN pg_type t ON t.oid = f.atttypid LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum LEFT JOIN pg_namespace n ON n.oid = c.relnamespace LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey) LEFT JOIN pg_class AS g ON p.confrelid = g.oid WHERE c.relkind = 'r'::char AND f.attisdropped = false AND n.nspname = $1 -- Replace with Schema name AND c.relname = $2 -- Replace with table name AND f.attnum > 0 ORDER BY f.attnum" (table-parameter-helper version>11 version>10 char-max-length data-type-length has-default default-value not-null numeric-precision numeric-scale storage primary primary-key-name unique unique-key-name fkey fkey-name fkey-col-id fkey-table fkey-local-col-id identity generated collation col-comments locally-defined inheritance-count stat-collection)) schema table :plists))) (values col-descriptions overall-description constraint-checks)))))) (defun list-all-tables (&optional (fully-qualified-names-only nil)) "If fully-qualified-names-only is set to t, returns all schema.table names other than pg_catalog or the information_schema. Otherwise returns the following info: schema-name, table-name, table-owner, tablespace, hasindexes, hasrules, hastriggers and rowsecurity" (if fully-qualified-names-only (alexandria:flatten (query "select schemaname ||'.'|| tablename as name from pg_catalog.pg_tables where schemaname != 'pg_catalog' and schemaname != 'information_schema' order by name")) (query "select * from pg_catalog.pg_tables where schemaname != 'pg_catalog' and schemaname != 'information_schema' order by schemaname, tablename"))) (defun list-tables-in-schema (&optional (schema-name "public") (strings-p nil)) "Returns a list of tables in a particular schema, defaulting to public. If schema-name is :all or \"all\", it will return all the non-system tables in the database in fully qualified form: e.g. 'public.test_table'. If string-p is t, the names will be returned as strings with underscores converted to hyphens." (let ((result (cond ((or (equal schema-name "all") (eq schema-name :all)) (query "select table_schema||'.'||table_name from information_schema.tables where table_schema not in ('pg_catalog', 'information_schema') order by table_schema, table_name")) (t (query "((SELECT table_name FROM information_schema.tables WHERE (table_schema = $1)) ORDER BY table_name)" (to-sql-name schema-name)))))) (setf result (alexandria:flatten result)) (if strings-p (mapcar (lambda (x) (substitute #\- #\_ x)) result) result))) (defun list-tables (&optional (strings-p nil)) "DEPRECATED FOR LIST-ALL-TABLES. Return a list of the tables in the public schema of a database. By default the table names are returned as keywords. They will be returned as lowercase strings if strings-p is true." (let ((result (query (make-list-query "r") :column))) (if strings-p result (mapcar 'from-sql-name result)))) (defun table-exists-p (table-name &optional schema-name) "Check whether a table exists in a particular schema. Defaults to the search path. Takes either a string or a symbol for the table name. The table-name can be fully qualified in the form of schema.table-name or database.schema.table-name. If the schema is specified either in a qualified table-name or in the optional schema-name parameter, we look directly to the information schema tables. Otherwise we use the search path which can be controlled by being within a with-schema form." (multiple-value-bind (tn sn) (table-schema-names table-name schema-name) (query (:select (:exists (:select 'table-name :from 'information-schema.tables :where (:and (:= 'table-schema '$1) (:= 'table-name '$2))))) sn tn :single))) (defun drop-table (table-name &key if-exists cascade) "Drop a table. Available additional key parameters are :if-exists and :cascade." (when (table-exists-p table-name) (let ((query-string (concatenate 'string "DROP " "TABLE " (if if-exists "IF EXISTS " "") (to-sql-name table-name) (if cascade " CASCADE" "")))) (query query-string)))) (defun rename-table (old-name new-name) "Rename a table. Parameters can be strings or symbols. If you are renaming a table using a fully qualified schema.table-name, you do not need to specify the schema in the new-name. You cannot use this function to move tables from one schema to another." (let* ((new-table-name (first (split-fully-qualified-tablename new-name))) (old-table-name (split-fully-qualified-tablename old-name)) (fully-qualified-new-table-name (if (not (string= (second old-table-name) "public")) (concatenate 'string (second old-table-name) "." new-table-name) new-name))) (setf old-name (to-sql-name old-name)) (query (format nil "alter table if exists ~a rename to ~a" old-name new-table-name)) (table-exists-p fully-qualified-new-table-name))) (defun list-table-sizes (&key (schema "public") (order-by-size nil) (size t)) "Returns a list of lists (table-name, size in 8k pages) of tables in the current database. Providing a name to the schema parameter will return just the information for tables in that schema. It defaults to just the tables in the public schema. Setting schema to nil will return all tables, indexes etc in the database in descending order of size. This would include system tables, so there are a lot more than you would expect. If :size is set to nil, it returns only a flat list of table names. Setting order-by-size to t will return the result in order of size instead of by table name." (setf schema (to-sql-name schema)) (if order-by-size (setf order-by-size (sql (:desc 'relpages))) (setf order-by-size " relname")) (cond ((and size schema) (query (:order-by (:select 'relname 'relpages :from 'pg_class :where (:in 'relname (:set (:select 'table-name :from 'information-schema.tables :where (:= 'table-schema '$1))))) (:raw order-by-size)) schema)) (size (query (:order-by (:select 'relname 'relpages :from 'pg_class) (:raw order-by-size)))) (schema (query (:order-by (:select 'relname :from 'pg_class :where (:in 'relname (:set (:select 'table-name :from 'information-schema.tables :where (:= 'table-schema '$1))))) 'relname) schema)) (t (alexandria:flatten (query (:order-by (:select 'relname :from 'pg_class) 'relname)))))) (defun table-size (table-name) "Return the size of a given postgresql table in k or m. Table-name can be either a string or quoted." (query (:select (:pg_size_pretty (:pg_total_relation_size '$1))) :single (to-sql-name table-name))) ;; Columns (defun get-column-comments (fully-qualified-table-name) "Retrieves a list of lists of column names and comments, if any, from a table. Each sublist will be in the form of (column-name comment-string)" (query "SELECT a.attname, pg_catalog.col_description(a.attrelid, a.attnum) FROM pg_catalog.pg_attribute a WHERE a.attrelid = $1 AND a.attnum > 0 AND NOT a.attisdropped and pg_catalog.col_description(a.attrelid, a.attnum) is not null ORDER BY a.attnum;" (get-table-oid fully-qualified-table-name))) (defun get-column-comment (qualified-column-name) "Retrieves a string which is the comment applied to a particular column in a table in the currently connected database. The parameter can be in the form of table.column, schema.table.column or database.schema.table.colum." (let* ((split-name (split-sequence:split-sequence #\. (to-sql-name qualified-column-name) :test 'equal)) (col-name (car (last split-name))) (qualified-table-name (format nil "~{~a~^.~}" (butlast split-name))) (table-oid (get-table-oid qualified-table-name))) (when table-oid (cadar (query "SELECT a.attname, pg_catalog.col_description(a.attrelid, a.attnum) FROM pg_catalog.pg_attribute a WHERE a.attrelid = $1 AND a.attnum > 0 AND NOT a.attisdropped AND a.attname = $2 and pg_catalog.col_description(a.attrelid, a.attnum) is not null ORDER BY a.attnum;" table-oid col-name))))) (defun list-columns (table-name) "Returns a list of strings of just the column names in a table. Pulls info from the postmodern table-description function rather than directly. The table-name can be a string or quoted. Any table-name that is not fully qualified with the schema will be assumed to be in the public schema." (when (table-exists-p table-name) (loop for x in (table-description table-name) collect (first x)))) (defun list-columns-with-types (table-name) "Returns a list of (name type) lists for the fields of a table. Returns a list of strings of just the column names and their sql data types in a table. Pulls info from the postmodern table-description function rather than directly. The table-name can be a string or quoted. Any table-name that is not fully qualified with the schema will be assumed to be in the public schema." (when (table-exists-p table-name) (loop for x in (table-description table-name) collect (list (first x) (second x))))) (defun column-exists-p (table-name column-name &optional schema-name) "Determine if a particular column exists. Table name and column-name can be either strings or symbols. If the optional schema name is not given or the table-name is not fully qualified with a schema name, the schema will be assumed to be the public schema. Returns t or nil." (multiple-value-bind (tn sn) (table-schema-names table-name schema-name) (query (:select (:exists (:select (:as 'a.attname 'column-name) :distinct :from (:as 'pg-attribute 'a) :inner-join 'pg-class :on (:and (:= 'pg-class.oid 'attrelid) (:= 'pg-class.relname tn)) :inner-join 'pg-namespace :on (:= 'pg-namespace.oid 'pg-class.relnamespace) :where (:and (:> 'attnum 0) (:= 'pg-namespace.nspname '$1) (:= '$2 'a.attname))))) :single sn (to-sql-name column-name)))) (defun rename-column (table old-name new-name) "Rename a column in a table. Parameters can be strings or symbols. If the table is not in the public schema, it needs to be fully qualified - e.g. schema.table.column Returns t if successful." (setf table (to-sql-name table)) (setf old-name (to-sql-name old-name)) (setf new-name (to-sql-name new-name)) (query (format nil "alter table ~a rename column ~a to ~a" table old-name new-name)) (column-exists-p table new-name)) ;;; Views (defun list-views (&optional strings-p) "Returns list of the user defined views in the current database. When strings-p is T, the names will be returned as strings, otherwise as keywords." (let ((result (query (make-list-query "v") :column))) (if strings-p result (mapcar 'from-sql-name result)))) (defun view-exists-p (view) "Tests whether a view with the given name exists. Takes either a string or a symbol for the view name." (query (make-exists-query "v" view) :single)) (defun describe-views (&optional (schema "public")) "Describe the current views in the specified schema. Includes the select statements used to create the view. Takes an optional schema name but defaults to public schema." (setf schema (to-sql-name schema)) (query (:order-by (:select 'c.oid 'c.xmin 'c.relname (:as (:pg_get_userbyid 'c.relowner) 'viewowner) 'c.relacl 'description (:as (:pg_get-viewdef 'c.oid 't) 'code) :from (:as 'pg_class 'c) :left-join (:as 'pg_description 'des) :on (:and (:= 'des.objoid 'c.oid) (:= 0 'des.objsubid)) :left-join (:as 'pg_catalog.pg_namespace 'n) :on (:= 'n.oid 'c.relnamespace) :where (:and (:or (:and 'c.relhasrules (:exists (:select 'r.rulename :from (:as 'pg_rewrite 'r) :where (:and (:= 'r.ev_class 'c.oid) (:= (:bpchar 'r.ev_type) (:type "I" bpchar)))))) (:= 'c.relkind (:type "v" char))) (:= 'n.nspname '$1))) 'relname) schema)) ;;;; Functions (defun list-database-functions () "Returns a list of the functions in the database from the information_schema." (query (:select 'routine-name :from 'information-schema.routines :where (:and (:not-in 'specific-schema (:set "pg_catalog" "information-schema")) (:!= 'type-udt-name "trigger"))))) ;;;; Indices (defun index-exists-p (index-name) "Tests whether an index with the given name exists. The name can be either a string or a symbol." (query (make-exists-query "i" (to-sql-name index-name)) :single)) (defun create-index (name &key unique if-not-exists concurrently on using fields) "Create an index. Slightly less sophisticated than the query version because it does not have a where clause capability." (let ((query-string (concatenate 'string "CREATE " (if unique "UNIQUE " "") "INDEX " (if concurrently "CONCURRENTLY " "") (if if-not-exists "IF NOT EXISTS " "") (to-sql-name name) " ON " (to-sql-name on) " " (if using (to-sql-name using) "") " (" (format nil "~{ ~a~^, ~}" (mapcar #'to-sql-name fields)) ") "))) (query query-string))) (defun drop-index (name &key concurrently if-exists cascade) "Drop an index. Available keys are :concurrently, :if-exists, and :cascade." (let ((query-string (concatenate 'string "DROP " "INDEX " (if concurrently "CONCURRENTLY " "") (if if-exists "IF EXISTS " "") (to-sql-name name) (if cascade " CASCADE" "")))) (query query-string))) (defun list-indices (&optional strings-p) "Return a list of the indexs in a database. Turn them into keywords if strings-p is not true." (let ((result (query (make-list-query "i") :column))) (if strings-p result (mapcar 'from-sql-name result)))) (defun list-table-indices (table-name &optional strings-p) "List the index names and the related columns in a single table. Each index will be in a separate sublist." (when (table-exists-p (to-sql-name table-name)) (let ((result (query (:order-by (:select (:as 'i.relname 'index-name) (:as 'a.attname 'column-name) :from (:as 'pg-class 't1) (:as 'pg-class 'i) (:as 'pg-index 'ix) (:as 'pg-attribute 'a) :where (:and (:= 't1.oid 'ix.indrelid) (:= 'i.oid 'ix.indexrelid) (:= 'a.attrelid 't1.oid) (:= 'a.attnum (:any* 'ix.indkey)) (:= 't1.relkind "r") (:= 't1.relname '$1))) 'i.relname) (to-sql-name table-name)))) (if strings-p result (loop for x in result collect (mapcar 'from-sql-name x)))))) (defun list-indexed-column-and-attributes (table-name) "List the indexed columns and their attributes in a table. Includes primary key." (setf table-name (to-sql-name table-name)) (when (table-exists-p table-name) (query (:select 'pg_attribute.attname (:format_type 'pg_attribute.atttypid 'pg_attribute.atttypmod) :from 'pg_index 'pg_class 'pg_attribute :where (:and (:= 'pg_class.oid (:type '$1 :regclass)) (:= 'indrelid 'pg_class.oid) (:= 'pg_attribute.attrelid 'pg_class.oid) (:= 'pg_attribute.attnum (:any* 'pg_index.indkey)))) table-name))) (defun list-index-definitions (table-name) "Returns a list of the definitions used to create the current indexes for the table." (setf table-name (to-sql-name table-name)) (when (table-exists-p table-name) (query (:select (:pg_get_indexdef 'indexrelid) :from 'pg_index :where (:= 'indrelid (:type '$1 :regclass))) table-name))) ;;;; Keys (defun find-primary-key-info (table &optional (just-key nil)) "Returns a list of sublists where the sublist contains two strings. If a table primary key consists of only one column, such as 'id' there will be a single sublist where the first string is the name of the column and the second string is the string name for the datatype for that column. If the primary key for the table consists of more than one column, there will be a sublist for each column subpart of the key. The sublists will be in the order they are used in the key, not in the order they appear in the table. If just-key is set to t, the list being returned will contain just the column names in the primary key as string names with no sublists. If the table is not in the public schema, provide the fully qualified table name e.g. schema-name.table-name." (when (symbolp table) (setf table (s-sql:to-sql-name table))) (let ((info (query (:order-by (:select 'a.attname (:format-type 'a.atttypid 'a.atttypmod) :from (:as 'pg-attribute 'a) :inner-join (:as (:select '* (:as (:generate-subscripts 'indkey 1) 'indkey-subscript) :from 'pg-index) 'i) :on (:and 'i.indisprimary (:= 'i.indrelid 'a.attrelid) (:= 'a.attnum (:[] 'i.indkey 'i.indkey-subscript))) :where (:= 'a.attrelid (:type '$1 regclass))) 'i.indkey-subscript) table))) (if just-key (loop for x in info collect (first x)) info))) (defun list-foreign-keys (table &optional (schema "public")) "Returns a list of sublists of foreign key info in the form of '((constraint-name local-table local-table-column foreign-table-name foreign-column-name))" (setf table (to-sql-name table)) (setf schema (to-sql-name schema)) (query (:select (:as 'conname 'constraint-name) table (:as 'att2.attname 'local-column) (:as 'cl.relname 'foreign-table-name) (:as 'att.attname 'foreign-table-column) :from (:as (:select (:as (:unnest 'con1.conkey) 'parent) (:as (:unnest 'con1.confkey) 'child) 'con1.confrelid 'con1.conrelid 'con1.conname :from (:as 'pg-class 'cl) :inner-join (:as 'pg-namespace 'ns) :on (:= 'cl.relnamespace 'ns.oid) :inner-join (:as 'pg-constraint 'con1) :on (:= 'con1.conrelid 'cl.oid) :where (:and (:= 'cl.relname '$1) (:= 'ns.nspname '$2) (:= 'con1.contype "f"))) 'con) :inner-join (:as 'pg-attribute 'att) :on (:and (:= 'att.attrelid 'con.confrelid) (:= 'att.attnum 'con.child)) :inner-join (:as 'pg-class 'cl) :on (:= 'cl.oid 'con.confrelid) :inner-join (:as 'pg-attribute 'att2) :on (:and (:= 'att2.attrelid 'con.conrelid) (:= 'att2.attnum 'con.parent))) table schema)) ;;;; Constraints (defun list-unique-or-primary-constraints (table-name &optional (strings-p)) "List constraints on a table. Table-name can be either a string or quoted. Turns constraints into keywords if strings-p is not true." (setf table-name (to-sql-name table-name)) (when (table-exists-p table-name) (let ((result (query (:select 'relname :from 'pg-class :where (:in 'oid (:select 'indexrelid :from 'pg-index 'pg-class :where (:and (:= 'pg-class.relname '$1) (:= 'pg-class.oid 'pg-index.indrelid) (:or (:= 'indisunique "t") (:= 'indisprimary "t")))))) table-name))) (if strings-p result (loop for x in result collect (mapcar 'from-sql-name x)))))) (defun list-check-constraints (table-name) "Takes a fully qualified table name and returns a list of lists of check constraints where each sublist has the form of (check-constraint-name check). See postmodern doc for example" (query "SELECT r.conname, pg_catalog.pg_get_constraintdef(r.oid, true) FROM pg_catalog.pg_constraint r WHERE r.conrelid = $1 AND r.contype = 'c' ORDER BY 1;" (get-table-oid table-name))) (defun list-all-constraints (table-name &optional (strings-p)) "Uses information_schema to list all the constraints in a table. Table-name can be either a string or quoted. Turns constraints into keywords if strings-p is not true." (setf table-name (to-sql-name table-name)) (when (table-exists-p table-name) (let ((result (query (:select 'constraint-name 'constraint-type :from 'information-schema.table-constraints :where (:= 'table-name '$1)) table-name))) (if strings-p result (loop for x in result collect (mapcar 'from-sql-name x)))))) (defun describe-constraint (table-name constraint-name) "Return a list of alists of the descriptions a particular constraint given the table-name and the constraint name using the information_schema table." (setf table-name (to-sql-name table-name)) (when (table-exists-p table-name) (first (query (:select 'tc.constraint-name 'tc.constraint-type 'tc.table-name 'kcu.column-name 'tc.is-deferrable 'tc.initially-deferred (:as 'rc.match-option 'match-type) (:as 'rc.update-rule 'on-update) (:as 'rc.delete-rule 'on-delete) (:as 'ccu.table-name 'references-table) (:as 'ccu.column-name 'references-field) :from (:as 'information-schema.table-constraints 'tc) :left-join (:as 'information-schema.key-column-usage 'kcu) :on (:and (:= 'tc.constraint-catalog 'kcu.constraint-catalog) (:= 'tc.constraint-schema 'kcu.constraint-schema) (:= 'tc.constraint-name 'kcu.constraint-name)) :left-join (:as 'information-schema.referential-constraints 'rc) :on (:and (:= 'tc.constraint-catalog 'rc.constraint-catalog) (:= 'tc.constraint-schema 'rc.constraint-schema) (:= 'tc.constraint-name 'rc.constraint-name)) :left-join (:as 'information-schema.constraint-column-usage 'ccu) :on (:and (:= 'rc.unique-constraint-catalog 'ccu.constraint-catalog) (:= 'rc.unique-constraint-schema 'ccu.constraint-schema) (:= 'rc.unique-constraint-name 'ccu.constraint-name)) :where (:and (:= 'tc.table-name '$1) (:= 'tc.constraint-name (to-sql-name constraint-name)))) table-name :alists)))) (defun describe-foreign-key-constraints () "Generates a list of lists of information on the foreign key constraints where each row returned is in the form of (constraint-name 631066 table-name table-column 631061 foreign-table-name foreign-table-column)" (query (:order-by (:select 'conname (:as 'conrelid 'table) (:as 'pgc.relname 'tabname) (:as 'a.attname 'columns) (:as 'confrelid 'foreign-table) (:as 'pgf.relname 'ftabname) (:as 'af.attname 'fcolumn) :from (:as 'pg_attribute 'af) (:as 'pg_attribute 'a) (:as 'pg_class 'pgc) (:as 'pg_class 'pgf) (:as (:select 'conname 'conrelid 'confrelid (:as (:[] 'conkey 'i) 'conkey) (:as (:[] 'confkey 'i) 'confkey) :from (:as (:select 'conname 'conrelid 'confrelid 'conkey 'confkey (:as (:generate-series '1 (:array-upper 'conkey 1)) 'i) :from 'pg_constraint :where (:= 'contype "f" )) 'ss)) 'ss2) :where (:and (:= 'af.attnum 'confkey) (:= 'af.attrelid 'confrelid) (:= 'a.attnum 'conkey) (:= 'a.attrelid 'conrelid) (:= 'pgf.relfilenode 'confrelid) (:= 'pgc.relfilenode 'conrelid))) 'ftabname 'fcolumn 'tabname 'columns))) ;;;; Triggers (defun describe-triggers () "List detailed information on the triggers from the information_schema table." (query (:select '* :from 'information-schema.triggers :where (:not-in 'trigger-schema (:set "pg_catalog" "information_schema"))))) (defun list-triggers (&optional table-name) "List distinct trigger names from the information_schema table. Table-name can be either quoted or string. (A trigger is a specification that the database should automatically execute a particular function whenever a certain type of operation is performed. Triggers can be attached to tables (partitioned or not), views, and foreign tables. See -definition.html)" (if table-name (progn (setf table-name (to-sql-name table-name)) (when (table-exists-p table-name) (alexandria:flatten (query (:order-by (:select (:as 'trg.tgname 'trigger-name) :from (:as 'pg-trigger 'trg) (:as 'pg-class 'tbl) :where (:and (:= 'trg.tgrelid 'tbl.oid) (:= 'tbl.relname '$1))) 'trigger-name) table-name)))) (alexandria:flatten (query (:order-by (:select 'trigger-name :distinct :from 'information-schema.triggers :where (:not-in 'trigger-schema (:set "pg-catalog" "information-schema"))) 'trigger-name))))) (defun list-detailed-triggers () "DEPRECATED FOR DESCRIBE-TRIGGERS.List detailed information on the triggers from the information_schema table." (query (:select '* :from 'information-schema.triggers :where (:not-in 'trigger-schema (:set "pg_catalog" "information_schema"))))) ;;;; Misc that need to be reorganized (defun change-toplevel-database (new-database user password host) "Just changes the database assuming you are using a toplevel connection. Recommended only for development work. Returns the name of the newly connected database as a string." (disconnect-toplevel) (connect-toplevel (to-sql-name new-database) user password host) (current-database)) (defun list-connections () "List the current postgresql connections to the currently connected database. It does this by returningo info from pg_stat_activity on open connections." (query (:select '* :from 'pg-stat-activity))) (defun list-available-extensions () "List the postgresql extensions which are available in the system to the currently connected database. The extensions may or may not be installed." (alexandria:flatten (query (:order-by (:select 'name :from 'pg-available-extensions) 'name)))) (defun list-installed-extensions () "List the postgresql extensions which are installed in the currently connected database." (alexandria:flatten (query (:order-by (:select 'extname :from 'pg-extension) 'extname)))) (defun load-uuid-extension () "Loads the Postgresql uuid-ossp contrib module. Once loaded, you can call uuid generation functions such as uuid_generate_v4 within a query. E.g. (query \"select uuid_generate_v4()\") See Postgresql documentation at -ossp.html" (query "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"")) (defun generate-uuid () "This gets a uuid (version 4) generated by Postgresql. If the uuid-ossp module is not loaded, it will load it first. This is probably not something you want to use because it is potentially two calls to Postgresql to get a uuid when you could do it in a single call within a query when you are getting other information." (unless (member "uuid-ossp" (list-installed-extensions) :test #'equal) (load-uuid-extension)) (query "select uuid_generate_v4()" :single)) (defun replace-non-alphanumeric-chars (str &optional (replacement #\_)) "Takes a string and a replacement char and replaces any character which is not alphanumeric or an asterisk with a specified character - by default an underscore and returns the modified string." (let ((str1 str)) (with-output-to-string (*standard-output*) (loop :for ch :of-type character :across str1 :do (if (or (eq ch #\*) (alphanumericp ch)) (write-char ch) (write-char replacement)))))) (defun copy-from-csv (tablename filename &key (delimiter 'comma) (header-p nil) (database (when *database* (cl-postgres::connection-db *database*))) (user (when *database* (cl-postgres::connection-user *database*))) (password (when *database* (cl-postgres::connection-password *database*))) (host (if *database* (cl-postgres::connection-host *database*) "localhost")) (port (if *database* (cl-postgres::connection-port *database*) 5432))) "Runs the psql copy command against a file. Assuming you are already connected to the desired database and the *database* global variable is set to that, then the mMinimum parameters required are the postgresql table-name and the file name including its absolute path. The delimiter parameter should be either 'comma or 'tab. Set the header-p parameter t if the first line of the csv file is a header that should not get imported into the database table. The table name can be either a string or quoted symbol." (setf tablename (to-sql-name tablename)) (uiop:run-program (format nil "psql postgresql://~a:~a@~a:~a/~a -c \"\\copy ~a from '~a' delimiter ~a csv ~a;\"" user password host port database tablename filename (case delimiter (comma "','") (tab "E'\t'")) (if header-p "HEADER" "")) :output :string))
null
https://raw.githubusercontent.com/marijnh/Postmodern/d8c57ef277240535353cee3c478bee34dba2ff1b/postmodern/util.lisp
lisp
Syntax : Ansi - Common - Lisp ; Base : 10 ; Package : POSTMODERN ; -*- Databases See namespace.lisp Sequences Types Tables create table can only be done either using a deftable approach or s-sql Columns " " Views Functions Indices Keys Constraints " Triggers Misc that need to be reorganized \""
(in-package :postmodern) (defun make-keyword (name) (values (intern (string-upcase name) "KEYWORD"))) (defun valid-sql-character-p (chr) "Returns t if chr is letter, underscore, digits or dollar sign" (or (uax-15:unicode-letter-p chr) (digit-char-p chr) (eq chr #\_) (eq chr #\$))) (defun code-char-0-p (chr) "Returns t if character has char-code 0 (generally #\Nul)" (eq chr (code-char 0))) (defun valid-sql-identifier-p (str) "Takes a string and returns it if it is a valid sql identifier. See -syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS. First test is for a quoted string, which has less restrictions. " (cond ((and (stringp str) (eq (char str 0) #\") (eq (char str (- (length str) 1)) #\") (notany #'code-char-0-p str)) str) ((and (stringp str) (or (uax-15:unicode-letter-p (char str 0)) (eq (char str 0) #\_)) (every #'valid-sql-character-p str))) (t nil))) (defun to-identifier (name) "Used to allow both strings and symbols as identifier - converts symbols to string with the S-SQL rules." (if (stringp name) name (to-sql-name name))) (defun coalesce (&rest args) "Returns the first non-NIL, non-NULL (as in :null) argument, or NIL if none are present. Useful for providing a fall-back value for the result of a query, or, when given only one argument, for transforming :nulls to NIL." (some (lambda (x) (if (eq x :null) nil x)) args)) (defun database-version () "DEPRECATED BECAUSE IT IS CONFUSING. IT IS REALLY THE POSTGRESQL SERVER VERSION NOT A DATABASE VERSION. USE POSTGRESQL-VERSION INSTEAD. Returns the version string provided by postgresql of the current postgresql server E.g. 'PostgreSQL 12.2 on x86_64-pc-linux-gnu, compiled by gcc (Arch Linux 9.3.0-1) 9.3.0, 64-bit'. If you want just the postgresql version number, use cl-postgres:get-postgresql-version." (query (:select (:version)) :single)) (defun postgresql-version () "Returns the version string provided by postgresql of the current postgresql server E.g. 'PostgreSQL 12.2 on x86_64-pc-linux-gnu, compiled by gcc (Arch Linux 9.3.0-1) 9.3.0, 64-bit'. If you want just the postgresql version number, use cl-postgres:get-postgresql-version." (query (:select (:version)) :single)) (defmacro make-list-query (relkind) "Helper macro for the functions that list tables, sequences, and views." `(sql (:order-by (:select 'relname :from 'pg-catalog.pg-class :inner-join 'pg-catalog.pg-namespace :on (:= 'relnamespace 'pg-namespace.oid) :where (:and (:= 'relkind ,relkind) (:not-in 'nspname (:set "pg_catalog" "pg_toast")) (:pg-catalog.pg-table-is-visible 'pg-class.oid))) 'relname))) (defmacro make-exists-query (relkind name) "Helper macro for the functions that check whether an object exists. Only works for public schema" `(sql (:select (:exists (:select 'relname :from 'pg_catalog.pg_class :inner-join 'pg_catalog.pg_namespace :on (:= 'pg_class.relnamespace 'pg_namespace.oid) :where (:and (:= 'pg_class.relkind ,relkind) (:= 'pg_namespace.nspname (:any* (:current_schemas "true"))) (:= 'pg_class.relname (to-identifier ,name)))))))) (defun split-fully-qualified-tablename (name) "Take a tablename of the form database.schema.table or schema.table or table and return the tablename and the schema name. The name can be a symbol or a string. Returns a list of form '(table schema database. If the tablename is not fully qualified, it will assume that the schema should be \"public\"." (destructuring-bind (table &optional schema database) (nreverse (split-sequence:split-sequence #\. (to-sql-name name) :test 'equal)) (when (not schema) (setf schema "public")) (list table schema database))) (defun postgres-array-string-to-list (str) "Takes a postgresql array in the form of a string like \"{wol=CTc/wol,a=c/wol,b=c/wol}\" and returns a lisp list like (\"wol=CTc/wol\" \"a=c/wol\" \"b=c/wol\")." (split-sequence:split-sequence #\, (subseq str 1 (- (length str) 1)))) (defun postgres-array-string-to-array (str) "Takes a postgresql array in the form of a string like \"{wol=CTc/wol,a=c/wol,b=c/wol}\" and returns a lisp array like #(\"wol=CTc/wol\" \"a=c/wol\" \"b=c/wol\")" (let* ((lst (postgres-array-string-to-list str)) (len (length lst))) (make-array len :initial-contents lst))) (defun add-comment (type name comment &optional (second-name "")) "Attempts to add a comment to a particular database object. The first parameter is a keyword for the type of database object. The second parameter is the name of the object. The third parameter is the comment itself. Some objects require an additional identifier. The names can be strings or symbols. Example usage would be: (add-comment :column 'country-locations.name \"Is what it looks like - the name of a country\".) (add-comment :column \"country_locations.name\" \"Is what it looks like - the name of a country\".) Example usage where two identifiers are required would be constraints: (add-comment :constraint 'constraint1 \"Some kind of constraint descriptions here\". 'country-locations)" (setf name (to-sql-name name)) (setf second-name (to-sql-name second-name)) (case type (:access-method (query (format nil "comment on ACCESS METHOD ~a is '~a'" name comment))) (:aggregate (query (format nil "comment on AGGREGATE ~a is '~a'" name comment))) (:cast (query (format nil "comment on CAST (~a as ~a) is '~a'" name second-name comment))) (:column (query (format nil "comment on COLUMN ~a is '~a'" name comment))) (:conversion (query (format nil "comment on CONVERSION m~a is '~a'" name comment))) (:constraint (query (format nil "comment on CONSTRAINT ~a on ~a is '~a'" name second-name comment))) (:domain-constraint (query (format nil "comment on CONSTRAINT ~a on DOMAIN ~a is '~a'" name second-name comment))) (:database (query (format nil "comment on DATABASE ~a is '~a'" name comment))) (:domain (query (format nil "comment on DOMAIN ~a is '~a'" name comment))) (:extension (query (format nil "comment on EXTENSION ~a is '~a'" name comment))) (:foreign-data-wrapper (query (format nil "comment on FOREIGN DATA WRAPPER ~a is '~a'" name comment))) (:foreign-table (query (format nil "comment on FOREIGN TABLE ~a is '~a'" name comment))) (:function (query (format nil "comment on FUNCTION ~a is '~a'" name comment))) (:index (query (format nil "comment on INDEX ~a is '~a'" name comment))) (:language (query (format nil "comment on LANGUAGE ~a is '~a'" name comment))) (:large-object (query (format nil "comment on LARGE OBJECT ~a is '~a'" name comment))) (:materialized-view (query (format nil "comment on MATERIALIZED VIEW ~a is '~a'" name comment))) (:operator (query (format nil "comment on OPERATOR ~a is '~a'" name comment))) (:operator-class (query (format nil "comment on OPERATOR CLASS ~a USING ~a is '~a'" name second-name comment))) (:operator-family (query (format nil "comment on OPERATOR FAMILY ~a USING ~a is '~a'" name second-name comment))) (:policy (query (format nil "comment on POLICY ~a on ~a is '~a'" name second-name comment))) (:procedure (query (format nil "comment on PROCEDURE ~a is '~a'" name comment))) (:role (query (format nil "comment on ROLE ~a is '~a'" name comment))) (:rule (query (format nil "comment on RULE ~a on ~a is '~a'" name second-name comment))) (:schema (query (format nil "comment on SCHEMA ~a is '~a'" name comment))) (:sequence (query (format nil "comment on SEQUENCE ~a is '~a'" name comment))) (:server (query (format nil "comment on SERVER ~a is '~a'" name comment))) (:statistics (query (format nil "comment on STATisTICS ~a is '~a'" name comment))) (:table (query (format nil "comment on TABLE ~a is '~a'" name comment))) (:tablespace (query (format nil "comment on TABLESPACE ~a is '~a'" name comment))) (:text-search-configuration (query (format nil "comment on TEXT SEARCH CONFIGURATIon ~a is '~a'" name comment))) (:text-search-dictionary (query (format nil "comment on TEXT SEARCH DICTIONARY ~a is '~a'" name comment))) (:text-search-parser (query (format nil "comment on TEXT SEARCH PARSER ~a is '~a'" name comment))) (:text-search-template (query (format nil "comment on TEXT SEARCH TEMPLATE ~a is '~a'" name comment))) (:trigger (query (format nil "comment on TRIGGER ~a on ~a is '~a'" name second-name comment))) (:type (query (format nil "comment on TYPE ~a is '~a'" name comment))) (:view (query (format nil "comment on VIEW ~a is '~a'" name comment))))) (defun find-comments (type identifier) "Returns the comments attached to a particular database object. The allowed types are :database :schema :table :columns (all the columns in a table) :column (for a single column). An example would be (find-comments :table 's2.employees) where the table employees is in the s2 schema." (ecase type (:database (get-database-comment identifier)) (:schema (get-schema-comment identifier)) (:table (get-table-comment identifier)) (:columns (get-column-comments identifier)) (:column (get-column-comment identifier)))) (define-condition invalid-database-name (error) ((text :initarg :text :reader text)) (:documentation "Invalid-database-name indicates that this database does not exist in this cluster or the user does not have the permissions necessary to access this database.")) (defun database-exists-p (database) "Returns database name string if the database parameter is actually an available database" (query (:select (:exists (:select 'datname :from 'pg-database :where (:= 'datname '$1)))) (to-sql-name database) :single)) (defun list-available-collations () "Get a list of the collations available from the current database cluster. Collations are a mess as different operating systems provide different collations. We might get some sanity if Postgresql can use ICU as the default. See ." (setf *collations* (query "select collname from pg_collation"))) (defun collation-exists-p (collation) "This function does require the parameter to be a string and properly upper and lower cased." (query "select collname from pg_collation where collname = $1" collation :single)) (defun character-set-exists-p (char-support) "There is no good way that I know to determine the available character sets on a remote server so we just assume any postgresql usable set is available." (member char-support *character-sets* :test 'equalp)) (defun list-templates () "Returns a list of existing database template names." (query "select datname from pg_database where datistemplate is true")) (defun create-database (database-name &key (encoding "UTF8") (connection-limit -1) owner limit-public-access comment collation template) "Creates a basic database. Besides the obvious database-name parameter, you can also use key parameters to set encoding (defaults to UTF8), owner, connection-limit (defaults to no limit)). If limit-public-access is set to t, then only superuser roles or roles with explicit access to this database will be able to access it. If collation is set, the assumption is that template0 needs to be used rather than template1 which may contain encoding specific or locale specific data." (setf database-name (to-sql-name database-name)) (cond ((equal owner "") (setf owner (cl-postgres::connection-user *database*))) ((stringp owner) nil) (t (setf owner (cl-postgres::connection-user *database*)))) (if template (setf template (format nil "template ~a " template)) (setf template "")) (if collation (progn (setf template "template template0") (setf collation (format nil " lc_collate '~a' lc_ctype '~a'" collation collation))) (setf collation "")) (when (and (character-set-exists-p encoding) (integerp connection-limit)) (query (format nil "create database ~a owner ~a ~a encoding ~a ~a connection limit = ~a" database-name owner template encoding collation connection-limit)) (when limit-public-access (query (format nil "revoke all privileges on database ~a from public;" database-name))) (when comment (query (format nil "comment on database ~a is '~a'" database-name comment)))) (with-connection (list database-name (cl-postgres::connection-user *database*) (cl-postgres::connection-password *database*) (cl-postgres::connection-host *database*) :port (cl-postgres::connection-port *database*) :use-ssl (cl-postgres::connection-use-ssl *database*)) (when (member "pg_stat_statements" (list-available-extensions) :test #'equal) (query "CREATE EXTENSION IF NOT EXISTS pg_stat_statements;")))) (defun drop-database (database) "Drop the specified database. The database parameter can be a string or a symbol. Note: Only the owner of a database can drop a database and there cannot be any current connections to the database." (setf database (to-sql-name database)) (if (database-exists-p database) (query (format nil "drop database ~a" database)) (cerror "invalid database name provided" 'invalid-database-name))) (defun num-records-in-database () "Returns a list of lists with schema, table name and approximate number of records in the currently connected database." (query (:order-by (:select 'schemaname 'relname 'n_live_tup :from 'pg_stat_user_tables) (:desc 'n_live_tup)))) (defun current-database () "Returns the string name of the current database." (query (:select (:current-database)) :single)) (defun database-size (&optional (name nil)) "Given the name of a database, will return the name, a pretty-print string of the size of the database and the size in bytes. If a database name is not provided, it will return the result for the currently connected database." (unless name (setf name (current-database))) (first (query (:select 'datname (:pg-size-pretty (:pg-database-size 'pg-database.oid)) (:pg-database-size 'pg-database.oid) :from 'pg-database :where (:= 'datname '$1)) (to-sql-name name)))) (defun get-database-comment (&optional database-name) "Returns the comment, if any, attached to a database" (if database-name (setf database-name (to-sql-name database-name)) (setf database-name (current-database))) (query "SELECT pg_catalog.shobj_description(d.oid, 'pg_database') FROM pg_catalog.pg_database d WHERE datname = $1" database-name :single)) (defun list-databases (&key (order-by-size nil) (size t) (names-only nil)) "Returns a list of lists where each sub-list contains the name of the database, a pretty-print string of the size of that database and the size in bytes. The default order is by database name. Pass t as a parameter to :order-by-size for order by size. Setting size to nil will return just the database names in a single list ordered by name. This function excludes the template databases." (if order-by-size (setf order-by-size (sql (:desc (:pg-database-size 'pg-database.oid)))) (setf order-by-size " datname")) (cond (names-only (alexandria:flatten (query (:order-by (:select 'datname :from 'pg-database :where (:not (:like 'datname "template%"))) 'datname)))) (size (query (:order-by (:select 'datname (:pg-size-pretty (:pg-database-size 'pg-database.oid)) (:pg-database-size 'pg-database.oid) :from 'pg-database :where (:not (:like 'datname "template%"))) (:raw order-by-size)))) (t (alexandria:flatten (query (:order-by (:select 'datname :from 'pg-database :where (:not (:like 'datname "template%"))) (:raw order-by-size))))))) (defun list-database-access-rights (&optional database-name) "If the database parameter is specifed, this returns an list of lists where each sublist is a role name and whether they have access rights (T or NIL) to that particular database. If the database-name is not provided, the sublist is a database name, a role name and whether they have access rights (T or NIL)." (if database-name (progn (when (symbolp database-name) (setf database-name (to-sql-name database-name))) (query (:order-by (:select 'r.rolname (:has-database-privilege 'r.rolname 'db.datname "connect") :from (:as 'pg-roles 'r) :cross-join (:as 'pg-database 'db) :where (:and 'r.rolcanlogin 'db.datallowconn (:= 'db.datname '$1))) 'r.rolname) database-name)) (query (:order-by (:select 'db.datname 'r.rolname (:has-database-privilege 'r.rolname 'db.datname "connect") :from (:as 'pg-roles 'r) :cross-join (:as 'pg-database 'db) :where (:and 'r.rolcanlogin 'db.datallowconn (:not 'datistemplate))) 'db.datname 'r.rolname)))) (defun list-role-accessible-databases (role-name) "Returns a list of the databases to which the specified role can connect." (when (symbolp role-name) (setf role-name (to-sql-name role-name))) (when (role-exists-p role-name) (alexandria:flatten (query (:select 'datname :from 'pg-database :where (:and (:has-database-privilege '$1 'datname "CONNECT") (:not (:like 'datname "template%")))) role-name)))) Schemas (defun get-schema-comment (schema-name) "If the schema has been commented, returns that string, else nil. Must be a schema in the currently connected database." (query "select obj_description($1::regnamespace)" (to-sql-name schema-name) :single)) (defun sequence-next (sequence) "Shortcut for getting the next value from a sequence. The sequence identifier can be either a string or a symbol, in the latter case it will be converted to a string according to S-SQL rules." (query (:select (:nextval (to-identifier sequence))) :single)) (defun create-sequence (name &key temp if-not-exists increment min-value max-value start cache) "Create a sequence. Available additional key parameters are :temp :if-not-exists :increment :min-value :max-value :start and :cache. See -createsequence.html for details on usage." (let ((query-string (concatenate 'string "CREATE " (if temp "TEMP " "") "SEQUENCE " (if if-not-exists "IF NOT EXISTS " "") (to-sql-name name) (if increment (concatenate 'string " INCREMENT BY " (format nil "~a" increment)) "") (if min-value (concatenate 'string " MINVALUE " (format nil "~a" min-value)) "") (if max-value (concatenate 'string " MAXVALUE " (format nil "~a" max-value)) "") (if start (concatenate 'string " START " (format nil "~a" start)) "") (if cache (concatenate 'string " CACHE " (format nil "~a" cache)) "")))) (query query-string))) (defun drop-sequence (name &key if-exists cascade) "Drop a sequence. Name should be quoted. Available key parameters are :if-exists and :cascade" (let ((query-string (concatenate 'string "DROP SEQUENCE " (if if-exists "IF EXISTS " "") (to-sql-name name) (if cascade " CASCADE" "")))) (query query-string))) (defun list-sequences (&optional strings-p) "Return a list of the sequences in a database. Turn them into keywords if strings-p is not true." (let ((result (query (make-list-query "S") :column))) (if strings-p result (mapcar 'from-sql-name result)))) (defun sequence-exists-p (sequence) "Tests whether a sequence with the given name exists. The name can be either a string or a symbol." (query (make-exists-query "S" (to-sql-name sequence)) :single)) Tablespaces (defun list-tablespaces () "Lists the tablespaces in the currently connected database. What are tablespace you ask? Per the Postgresql documentation -ag-tablespaces.html: Tablespaces in PostgreSQL allow database administrators to define locations in the file system where the files representing database objects can be stored. Once created, a tablespace can be referred to by name when creating database objects. By using tablespaces, an administrator can control the disk layout of a PostgreSQL installation. This is useful in at least two ways. First, if the partition or volume on which the cluster was initialized runs out of space and cannot be extended, a tablespace can be created on a different partition and used until the system can be reconfigured. Second, tablespaces allow an administrator to use knowledge of the usage pattern of database objects to optimize performance. For example, an index which is very heavily used can be placed on a very fast, highly available disk, such as an expensive solid state device. At the same time a table storing archived data which is rarely used or not performance critical could be stored on a less expensive, slower disk system." (alexandria:flatten (query (:order-by (:select (:as 'spcname 'name) :from 'pg_tablespace) 'spcname)))) (defun list-available-types () "List the available data types in the connected postgresql version, It returns a list of lists, each sublist containing the oid (object identifier number) and the name of the data types. E.g. (21 \"smallint\")" (query (:select 'oid (:as (:format-type :oid :NULL) 'typename) :from 'pg-type :where (:= 'typtype "b")))) (define-condition inconsistent-schema-name (error) ((text :initarg :text :reader text))) (defun table-schema-names (table-name schema-name) "Helper function to allow for fully qualified table names and non-qualified tables names that just exist in public schema or in a separately stated schema in the second parameter. Will thrown an error if the table-name is fully qualified and has a schema name different than the specified schema name." (let ((split-name (split-fully-qualified-tablename table-name))) (setf table-name (first split-name)) (cond ((and schema-name (not (string= (second split-name) "public")) (not (string= (second split-name) (to-sql-name schema-name)))) (error 'inconsistent-schema-name :text (format nil "You have specified a schema name ~a and an inconsistent schema name in a fully qualified table name ~a" schema-name (second split-name)))) ((not schema-name) (setf schema-name (second split-name))) (t (setf schema-name (to-sql-name schema-name)))) (values table-name schema-name))) (defun get-table-comment (table-name &optional schema-name) "Retrieves the comment, if any attached to the table." (multiple-value-bind (tn sn) (table-schema-names table-name schema-name) (query (format nil "select obj_description($1::regclass)") (concatenate 'string sn "." tn) :single))) (defun get-all-table-comments () "Returns a list of lists, each list showing the schema, table and comment of all tables with comments." (query "select pg_namespace.nspname as schema, relname as table, description from pg_description inner join pg_class on objoid = oid inner join pg_namespace on pg_namespace.oid = pg_class.relnamespace where relkind = 'r'")) (defun get-table-oid (table-name &optional schema-name) "Retrieves the oid identifier for a particular table from postgresql. Works for tables in all schemas." (multiple-value-bind (tn sn) (table-schema-names table-name schema-name) (query (:select 'pg-class.oid :from 'pg-class :inner-join 'pg-namespace :on (:= 'pg-namespace.oid 'pg-class.relnamespace) :where (:and (:= 'pg-class.relname '$1) (:= 'pg-namespace.nspname '$2))) tn sn :single))) (defun table-description (table-name &optional schema-name) "Returns a list of the fields in the named table. Each field is represented by a list of three elements: the field name, the type, and a boolean indicating whether the field may be NULL. Table can be either a string or quoted. Table-names can be fully qualified with the schema or not. If the table-name is not fully qualified and a schema name is not provided, the table will be assumed to be in the public schema." (multiple-value-bind (tn sn) (table-schema-names table-name schema-name) (mapcar #'butlast (query (:order-by (:select 'attname 'typname (:not 'attnotnull) 'attnum :distinct :from 'pg-attribute :inner-join 'pg-type :on (:= 'pg-type.oid 'atttypid) :inner-join 'pg-class :on (:and (:= 'pg-class.oid 'attrelid) (:= 'pg-class.relname '$1)) :inner-join 'pg-namespace :on (:= 'pg-namespace.oid 'pg-class.relnamespace) :where (:and (:> 'attnum 0) (:= 'pg-namespace.nspname '$2))) 'attnum) tn sn)))) (defun table-description-plus (table-name &optional schema-name) "Returns more table info than table-description. It defaults to returning column-name, data-type, character-maximum-length, modifier, whether it is not-null and the default value. Table can be either a string or quoted. Table-names can be fully qualified with the schema or not. If the table-name is not fully qualified and a schema name is not provided, the table will be assumed to be in the public schema." (multiple-value-bind (tn sn) (table-schema-names table-name schema-name) (mapcar #'butlast (query (:order-by (:select (:as 'a.attname 'column-name) (:as 'tn.typname 'data-type) (:as 'a.attlen 'character-maximum-length) (:as 'a.atttypmod 'modifier) (:as 'a.attnotnull 'notnull) (:as 'a.atthasdef 'hasdefault) (:as 'a.attnum 'ordinal-position) :distinct :from (:as 'pg-attribute 'a) :inner-join (:as 'pg-type 'tn) :on (:= 'tn.oid 'a.atttypid) :inner-join 'pg-class :on (:and (:= 'pg-class.oid 'attrelid) (:= 'pg-class.relname '$1)) :inner-join 'pg-namespace :on (:= 'pg-namespace.oid 'pg-class.relnamespace) :where (:and (:> 'attnum 0) (:= 'pg-namespace.nspname '$2))) 'ordinal-position) tn sn)))) (defun table-parameter-helper (version>11 version>10 char-max-length data-type-length has-default default-value not-null numeric-precision numeric-scale storage primary primary-key-name unique unique-key-name fkey fkey-name fkey-col-id fkey-table fkey-local-col-id identity generated collation col-comments locally-defined inheritance-count stat-collection) (let ((param-list (list "t.typname AS data_type_name" "f.attname as column_name"))) (when char-max-length (push " CASE WHEN f.atttypmod >= 0 AND t.typname <> 'numeric' THEN (f.atttypmod - 4) --first 4 bytes are for storing actual length of data END AS character_maximum_length" param-list)) (when data-type-length (push " f.attlen as data_type_length " param-list)) (when has-default (push " case when f.atthasdef then f.atthasdef else null end as has_default" param-list)) (when default-value (push " CASE WHEN f.atthasdef = 't' THEN pg_get_expr(d.adbin, d.adrelid) END AS default_value " param-list)) (when not-null (push "case when f.attnotnull then f.attnotnull else null end as not_null " param-list)) (when numeric-precision (push " CASE WHEN t.typname = 'numeric' THEN (((f.atttypmod - 4) >> 16) & 65535) END AS numeric_precision " param-list)) (when numeric-scale (push " CASE WHEN t.typname = 'numeric' THEN ((f.atttypmod - 4)& 65535 ) END AS numeric_scale " param-list)) (when storage (push " CASE WHEN f.attstorage ='p' THEN 'plain' WHEN f.attstorage ='m' THEN 'main' WHEN f.attstorage ='e' THEN 'external' WHEN f.attstorage ='x' THEN 'extended' END as storage " param-list)) (when primary (push " CASE WHEN p.contype = 'p' THEN 'Primary' ELSE '' END AS primary " param-list)) (when primary-key-name (push " CASE WHEN p.contype = 'p' THEN p.conname END AS primary_key_name " param-list)) (when unique (push " CASE WHEN p.contype = 'u' THEN True ELSE null END AS unique " param-list)) (when unique-key-name (push " CASE WHEN p.contype = 'u' THEN p.conname END AS unique_key_name " param-list)) (when fkey (push " CASE WHEN p.contype = 'f' THEN True ELSE NULL END AS fkey " param-list)) (when fkey-name (push " CASE WHEN p.contype = 'f' THEN p.conname END AS fkey_name " param-list)) (when fkey-col-id (push " CASE WHEN p.contype = 'f' THEN p.confkey END AS fkey_col_id " param-list)) (when fkey-table (push " CASE WHEN p.contype = 'f' THEN g.relname END AS fkey_table " param-list)) (when fkey-local-col-id (push " CASE WHEN p.contype = 'f' THEN p.conkey END AS fkey_local_col_id " param-list)) (when (and identity version>10) (push " case when f.attidentity ='a' then 'generated always' when f.attidentity = 'd' then 'generated by default' else null end as identity " param-list)) (when (and generated version>11) (push " case when f.attgenerated ='s' then 'stored' else null end as generated " param-list)) (when collation (push " (select c.collname from pg_catalog.pg_collation as c, pg_catalog.pg_type t where c.oid = f.attcollation and t.oid = f.atttypid and f.attcollation <> t.typcollation) AS collation " param-list)) (when col-comments (push " pg_catalog.col_description(f.attrelid, f.attnum) as col_comments " param-list)) (when locally-defined (push " case when f.attislocal then true else null end as locally_defined " param-list)) (when inheritance-count (push " f.attinhcount inheritance_count " param-list)) (when stat-collection (push " CASE WHEN f.attstattarget=-1 THEN NULL ELSE f.attstattarget END AS stat_collection " param-list)) (format nil "~{~a~^, ~}" (nreverse param-list)))) (defun table-description-menu (table-name &key (char-max-length t) (data-type-length t) (has-default t) (default-value t) (not-null t) (numeric-precision t) (numeric-scale t) (storage t) (primary t) (primary-key-name t) (unique t) (unique-key-name t) (fkey t) (fkey-name t) (fkey-col-id t) (fkey-table t) (fkey-local-col-id t) (identity t) (generated t) (collation t) (col-comments t) (locally-defined t) (inheritance-count t) (stat-collection t)) "Takes a fully qualified table name which can be either a string or a symbol. Returns three values. 1. A list of plists of each row's parameters. This will always include :column-name and :data-type-name but all other parameters can be set or unset and are set by default (set to t). 2. The comment string attached to the table itself (if any). 3. A list of the check constraints applied to the rows in the table. See documentation for list-check-constraints for an example. The available keyword parameters are: - char-max-length (Typically used for something like a varchar and shows the maximum length) - data-type-length (For a fixed-size type, typlen is the number of bytes in the internal representation of the type. But for a variable-length type, typlen is negative. -1 indicates a “varlena” type (one that has a length word), -2 indicates a null-terminated C string.) - has-default (value T if this column has a default value and :NULL if not) - default-value (value is the default value as string. A default of 9.99 will still be a string) - not-null (value is T if the column must have a value or :NULL otherwise) - numeric-precision (value is the total number of digits for a numeric type if that precision was specified) - numeric-scale (value is the number of digits in the fraction part of a numeric type if that scale was specified) - storage (value is the storage setting for a column. Result can be plain, extended, main or external) - primary (value is T if the column is the primary key for the table, :NULL otherwise) - primary-key-name (value is the name of the primary-key itself, not the column, if the column is the primary key for the table, :NULL otherwise) - unique (value is T if the column is subject to a unique key, :NULL otherwise) - unique-key-name (value is the name of the unique-key itself, not the column, applied to the column, :NULL otherwise) - fkey (value is T if the column is a foreign key, :NULL otherwise) - fkey-name (value is the name of the foreign key, :NULL otherwise) - fkey-col-id (value is the column id of the foreign table used as the foreign key. Probably easier to use the Postmodern function list-foreign-keys if you are looking for the name of the columns) - fkey-table (value is the name of the foreign table, :NULL otherwise) - fkey-local-col-id (value is the column id of this column. Probably easier to use the Postmodern function list-foreign-keys if you are looking for the name of the columns involved in the foreign key) - identity (if the column is an identity column, the values can be 'generated always' or 'generated by default'. Otherwise :NULL) - generated (columns can be generated, if this column is generated and stored on disk, the value will be 'stored', otherwise :NULL) - collation (columns with collations which are not the default collation for the database will show that collation here, otherwise :NULL) - col-comments (value is any comment that has been applied to the column, :NULL otherwise) - locally-defined (value is T if locally defined. It might be both locally defined and inherited) - inheritance-count (the number of direct ancestors this column has inherited) - stat-collection (stat-collection returns the value of attstattarget which controls the level of detail of statistics accumulated for this column by ANALYZE. A zero value indicates that no statistics should be collected. A negative value says to use the system default statistics target. The exact meaning of positive values is data type-dependent. For scalar data types, attstattarget is both the target number of most common values to collect, and the target number of histogram bins to create. Attstorage is normally a copy of pg_type.typstorage of this column's type. For TOAST-able data types, this can be altered after column creation to control storage policy.)" (let* ((version>11 (cl-postgres:postgresql-version-at-least "12.0" pomo:*database*)) (version>10 (cl-postgres:postgresql-version-at-least "11.0" pomo:*database*))) (destructuring-bind (table schema database) (pomo:split-fully-qualified-tablename table-name) (declare (ignore database)) (setf schema (to-sql-name schema)) (setf table (to-sql-name table)) (when (and (pomo:schema-exists-p schema) (pomo:table-exists-p (concatenate 'string schema "." table))) (let ((overall-description (get-table-comment table schema)) (constraint-checks (list-check-constraints table-name)) (col-descriptions (query (format nil "SELECT ~a FROM pg_attribute f JOIN pg_class c ON c.oid = f.attrelid JOIN pg_type t ON t.oid = f.atttypid LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum LEFT JOIN pg_namespace n ON n.oid = c.relnamespace LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey) LEFT JOIN pg_class AS g ON p.confrelid = g.oid WHERE c.relkind = 'r'::char AND f.attisdropped = false AND n.nspname = $1 -- Replace with Schema name AND c.relname = $2 -- Replace with table name AND f.attnum > 0 ORDER BY f.attnum" (table-parameter-helper version>11 version>10 char-max-length data-type-length has-default default-value not-null numeric-precision numeric-scale storage primary primary-key-name unique unique-key-name fkey fkey-name fkey-col-id fkey-table fkey-local-col-id identity generated collation col-comments locally-defined inheritance-count stat-collection)) schema table :plists))) (values col-descriptions overall-description constraint-checks)))))) (defun list-all-tables (&optional (fully-qualified-names-only nil)) "If fully-qualified-names-only is set to t, returns all schema.table names other than pg_catalog or the information_schema. Otherwise returns the following info: schema-name, table-name, table-owner, tablespace, hasindexes, hasrules, hastriggers and rowsecurity" (if fully-qualified-names-only (alexandria:flatten (query "select schemaname ||'.'|| tablename as name from pg_catalog.pg_tables where schemaname != 'pg_catalog' and schemaname != 'information_schema' order by name")) (query "select * from pg_catalog.pg_tables where schemaname != 'pg_catalog' and schemaname != 'information_schema' order by schemaname, tablename"))) (defun list-tables-in-schema (&optional (schema-name "public") (strings-p nil)) "Returns a list of tables in a particular schema, defaulting to public. If schema-name is :all or \"all\", it will return all the non-system tables in the database in fully qualified form: e.g. 'public.test_table'. If string-p is t, the names will be returned as strings with underscores converted to hyphens." (let ((result (cond ((or (equal schema-name "all") (eq schema-name :all)) (query "select table_schema||'.'||table_name from information_schema.tables where table_schema not in ('pg_catalog', 'information_schema') order by table_schema, table_name")) (t (query "((SELECT table_name FROM information_schema.tables WHERE (table_schema = $1)) ORDER BY table_name)" (to-sql-name schema-name)))))) (setf result (alexandria:flatten result)) (if strings-p (mapcar (lambda (x) (substitute #\- #\_ x)) result) result))) (defun list-tables (&optional (strings-p nil)) "DEPRECATED FOR LIST-ALL-TABLES. Return a list of the tables in the public schema of a database. By default the table names are returned as keywords. They will be returned as lowercase strings if strings-p is true." (let ((result (query (make-list-query "r") :column))) (if strings-p result (mapcar 'from-sql-name result)))) (defun table-exists-p (table-name &optional schema-name) "Check whether a table exists in a particular schema. Defaults to the search path. Takes either a string or a symbol for the table name. The table-name can be fully qualified in the form of schema.table-name or database.schema.table-name. If the schema is specified either in a qualified table-name or in the optional schema-name parameter, we look directly to the information schema tables. Otherwise we use the search path which can be controlled by being within a with-schema form." (multiple-value-bind (tn sn) (table-schema-names table-name schema-name) (query (:select (:exists (:select 'table-name :from 'information-schema.tables :where (:and (:= 'table-schema '$1) (:= 'table-name '$2))))) sn tn :single))) (defun drop-table (table-name &key if-exists cascade) "Drop a table. Available additional key parameters are :if-exists and :cascade." (when (table-exists-p table-name) (let ((query-string (concatenate 'string "DROP " "TABLE " (if if-exists "IF EXISTS " "") (to-sql-name table-name) (if cascade " CASCADE" "")))) (query query-string)))) (defun rename-table (old-name new-name) "Rename a table. Parameters can be strings or symbols. If you are renaming a table using a fully qualified schema.table-name, you do not need to specify the schema in the new-name. You cannot use this function to move tables from one schema to another." (let* ((new-table-name (first (split-fully-qualified-tablename new-name))) (old-table-name (split-fully-qualified-tablename old-name)) (fully-qualified-new-table-name (if (not (string= (second old-table-name) "public")) (concatenate 'string (second old-table-name) "." new-table-name) new-name))) (setf old-name (to-sql-name old-name)) (query (format nil "alter table if exists ~a rename to ~a" old-name new-table-name)) (table-exists-p fully-qualified-new-table-name))) (defun list-table-sizes (&key (schema "public") (order-by-size nil) (size t)) "Returns a list of lists (table-name, size in 8k pages) of tables in the current database. Providing a name to the schema parameter will return just the information for tables in that schema. It defaults to just the tables in the public schema. Setting schema to nil will return all tables, indexes etc in the database in descending order of size. This would include system tables, so there are a lot more than you would expect. If :size is set to nil, it returns only a flat list of table names. Setting order-by-size to t will return the result in order of size instead of by table name." (setf schema (to-sql-name schema)) (if order-by-size (setf order-by-size (sql (:desc 'relpages))) (setf order-by-size " relname")) (cond ((and size schema) (query (:order-by (:select 'relname 'relpages :from 'pg_class :where (:in 'relname (:set (:select 'table-name :from 'information-schema.tables :where (:= 'table-schema '$1))))) (:raw order-by-size)) schema)) (size (query (:order-by (:select 'relname 'relpages :from 'pg_class) (:raw order-by-size)))) (schema (query (:order-by (:select 'relname :from 'pg_class :where (:in 'relname (:set (:select 'table-name :from 'information-schema.tables :where (:= 'table-schema '$1))))) 'relname) schema)) (t (alexandria:flatten (query (:order-by (:select 'relname :from 'pg_class) 'relname)))))) (defun table-size (table-name) "Return the size of a given postgresql table in k or m. Table-name can be either a string or quoted." (query (:select (:pg_size_pretty (:pg_total_relation_size '$1))) :single (to-sql-name table-name))) (defun get-column-comments (fully-qualified-table-name) "Retrieves a list of lists of column names and comments, if any, from a table. Each sublist will be in the form of (column-name comment-string)" (query "SELECT a.attname, pg_catalog.col_description(a.attrelid, a.attnum) FROM pg_catalog.pg_attribute a WHERE a.attrelid = $1 AND a.attnum > 0 AND NOT a.attisdropped and pg_catalog.col_description(a.attrelid, a.attnum) is not null (get-table-oid fully-qualified-table-name))) (defun get-column-comment (qualified-column-name) "Retrieves a string which is the comment applied to a particular column in a table in the currently connected database. The parameter can be in the form of table.column, schema.table.column or database.schema.table.colum." (let* ((split-name (split-sequence:split-sequence #\. (to-sql-name qualified-column-name) :test 'equal)) (col-name (car (last split-name))) (qualified-table-name (format nil "~{~a~^.~}" (butlast split-name))) (table-oid (get-table-oid qualified-table-name))) (when table-oid (cadar (query "SELECT a.attname, pg_catalog.col_description(a.attrelid, a.attnum) FROM pg_catalog.pg_attribute a WHERE a.attrelid = $1 AND a.attnum > 0 AND NOT a.attisdropped AND a.attname = $2 and pg_catalog.col_description(a.attrelid, a.attnum) is not null table-oid col-name))))) (defun list-columns (table-name) "Returns a list of strings of just the column names in a table. Pulls info from the postmodern table-description function rather than directly. The table-name can be a string or quoted. Any table-name that is not fully qualified with the schema will be assumed to be in the public schema." (when (table-exists-p table-name) (loop for x in (table-description table-name) collect (first x)))) (defun list-columns-with-types (table-name) "Returns a list of (name type) lists for the fields of a table. Returns a list of strings of just the column names and their sql data types in a table. Pulls info from the postmodern table-description function rather than directly. The table-name can be a string or quoted. Any table-name that is not fully qualified with the schema will be assumed to be in the public schema." (when (table-exists-p table-name) (loop for x in (table-description table-name) collect (list (first x) (second x))))) (defun column-exists-p (table-name column-name &optional schema-name) "Determine if a particular column exists. Table name and column-name can be either strings or symbols. If the optional schema name is not given or the table-name is not fully qualified with a schema name, the schema will be assumed to be the public schema. Returns t or nil." (multiple-value-bind (tn sn) (table-schema-names table-name schema-name) (query (:select (:exists (:select (:as 'a.attname 'column-name) :distinct :from (:as 'pg-attribute 'a) :inner-join 'pg-class :on (:and (:= 'pg-class.oid 'attrelid) (:= 'pg-class.relname tn)) :inner-join 'pg-namespace :on (:= 'pg-namespace.oid 'pg-class.relnamespace) :where (:and (:> 'attnum 0) (:= 'pg-namespace.nspname '$1) (:= '$2 'a.attname))))) :single sn (to-sql-name column-name)))) (defun rename-column (table old-name new-name) "Rename a column in a table. Parameters can be strings or symbols. If the table is not in the public schema, it needs to be fully qualified - e.g. schema.table.column Returns t if successful." (setf table (to-sql-name table)) (setf old-name (to-sql-name old-name)) (setf new-name (to-sql-name new-name)) (query (format nil "alter table ~a rename column ~a to ~a" table old-name new-name)) (column-exists-p table new-name)) (defun list-views (&optional strings-p) "Returns list of the user defined views in the current database. When strings-p is T, the names will be returned as strings, otherwise as keywords." (let ((result (query (make-list-query "v") :column))) (if strings-p result (mapcar 'from-sql-name result)))) (defun view-exists-p (view) "Tests whether a view with the given name exists. Takes either a string or a symbol for the view name." (query (make-exists-query "v" view) :single)) (defun describe-views (&optional (schema "public")) "Describe the current views in the specified schema. Includes the select statements used to create the view. Takes an optional schema name but defaults to public schema." (setf schema (to-sql-name schema)) (query (:order-by (:select 'c.oid 'c.xmin 'c.relname (:as (:pg_get_userbyid 'c.relowner) 'viewowner) 'c.relacl 'description (:as (:pg_get-viewdef 'c.oid 't) 'code) :from (:as 'pg_class 'c) :left-join (:as 'pg_description 'des) :on (:and (:= 'des.objoid 'c.oid) (:= 0 'des.objsubid)) :left-join (:as 'pg_catalog.pg_namespace 'n) :on (:= 'n.oid 'c.relnamespace) :where (:and (:or (:and 'c.relhasrules (:exists (:select 'r.rulename :from (:as 'pg_rewrite 'r) :where (:and (:= 'r.ev_class 'c.oid) (:= (:bpchar 'r.ev_type) (:type "I" bpchar)))))) (:= 'c.relkind (:type "v" char))) (:= 'n.nspname '$1))) 'relname) schema)) (defun list-database-functions () "Returns a list of the functions in the database from the information_schema." (query (:select 'routine-name :from 'information-schema.routines :where (:and (:not-in 'specific-schema (:set "pg_catalog" "information-schema")) (:!= 'type-udt-name "trigger"))))) (defun index-exists-p (index-name) "Tests whether an index with the given name exists. The name can be either a string or a symbol." (query (make-exists-query "i" (to-sql-name index-name)) :single)) (defun create-index (name &key unique if-not-exists concurrently on using fields) "Create an index. Slightly less sophisticated than the query version because it does not have a where clause capability." (let ((query-string (concatenate 'string "CREATE " (if unique "UNIQUE " "") "INDEX " (if concurrently "CONCURRENTLY " "") (if if-not-exists "IF NOT EXISTS " "") (to-sql-name name) " ON " (to-sql-name on) " " (if using (to-sql-name using) "") " (" (format nil "~{ ~a~^, ~}" (mapcar #'to-sql-name fields)) ") "))) (query query-string))) (defun drop-index (name &key concurrently if-exists cascade) "Drop an index. Available keys are :concurrently, :if-exists, and :cascade." (let ((query-string (concatenate 'string "DROP " "INDEX " (if concurrently "CONCURRENTLY " "") (if if-exists "IF EXISTS " "") (to-sql-name name) (if cascade " CASCADE" "")))) (query query-string))) (defun list-indices (&optional strings-p) "Return a list of the indexs in a database. Turn them into keywords if strings-p is not true." (let ((result (query (make-list-query "i") :column))) (if strings-p result (mapcar 'from-sql-name result)))) (defun list-table-indices (table-name &optional strings-p) "List the index names and the related columns in a single table. Each index will be in a separate sublist." (when (table-exists-p (to-sql-name table-name)) (let ((result (query (:order-by (:select (:as 'i.relname 'index-name) (:as 'a.attname 'column-name) :from (:as 'pg-class 't1) (:as 'pg-class 'i) (:as 'pg-index 'ix) (:as 'pg-attribute 'a) :where (:and (:= 't1.oid 'ix.indrelid) (:= 'i.oid 'ix.indexrelid) (:= 'a.attrelid 't1.oid) (:= 'a.attnum (:any* 'ix.indkey)) (:= 't1.relkind "r") (:= 't1.relname '$1))) 'i.relname) (to-sql-name table-name)))) (if strings-p result (loop for x in result collect (mapcar 'from-sql-name x)))))) (defun list-indexed-column-and-attributes (table-name) "List the indexed columns and their attributes in a table. Includes primary key." (setf table-name (to-sql-name table-name)) (when (table-exists-p table-name) (query (:select 'pg_attribute.attname (:format_type 'pg_attribute.atttypid 'pg_attribute.atttypmod) :from 'pg_index 'pg_class 'pg_attribute :where (:and (:= 'pg_class.oid (:type '$1 :regclass)) (:= 'indrelid 'pg_class.oid) (:= 'pg_attribute.attrelid 'pg_class.oid) (:= 'pg_attribute.attnum (:any* 'pg_index.indkey)))) table-name))) (defun list-index-definitions (table-name) "Returns a list of the definitions used to create the current indexes for the table." (setf table-name (to-sql-name table-name)) (when (table-exists-p table-name) (query (:select (:pg_get_indexdef 'indexrelid) :from 'pg_index :where (:= 'indrelid (:type '$1 :regclass))) table-name))) (defun find-primary-key-info (table &optional (just-key nil)) "Returns a list of sublists where the sublist contains two strings. If a table primary key consists of only one column, such as 'id' there will be a single sublist where the first string is the name of the column and the second string is the string name for the datatype for that column. If the primary key for the table consists of more than one column, there will be a sublist for each column subpart of the key. The sublists will be in the order they are used in the key, not in the order they appear in the table. If just-key is set to t, the list being returned will contain just the column names in the primary key as string names with no sublists. If the table is not in the public schema, provide the fully qualified table name e.g. schema-name.table-name." (when (symbolp table) (setf table (s-sql:to-sql-name table))) (let ((info (query (:order-by (:select 'a.attname (:format-type 'a.atttypid 'a.atttypmod) :from (:as 'pg-attribute 'a) :inner-join (:as (:select '* (:as (:generate-subscripts 'indkey 1) 'indkey-subscript) :from 'pg-index) 'i) :on (:and 'i.indisprimary (:= 'i.indrelid 'a.attrelid) (:= 'a.attnum (:[] 'i.indkey 'i.indkey-subscript))) :where (:= 'a.attrelid (:type '$1 regclass))) 'i.indkey-subscript) table))) (if just-key (loop for x in info collect (first x)) info))) (defun list-foreign-keys (table &optional (schema "public")) "Returns a list of sublists of foreign key info in the form of '((constraint-name local-table local-table-column foreign-table-name foreign-column-name))" (setf table (to-sql-name table)) (setf schema (to-sql-name schema)) (query (:select (:as 'conname 'constraint-name) table (:as 'att2.attname 'local-column) (:as 'cl.relname 'foreign-table-name) (:as 'att.attname 'foreign-table-column) :from (:as (:select (:as (:unnest 'con1.conkey) 'parent) (:as (:unnest 'con1.confkey) 'child) 'con1.confrelid 'con1.conrelid 'con1.conname :from (:as 'pg-class 'cl) :inner-join (:as 'pg-namespace 'ns) :on (:= 'cl.relnamespace 'ns.oid) :inner-join (:as 'pg-constraint 'con1) :on (:= 'con1.conrelid 'cl.oid) :where (:and (:= 'cl.relname '$1) (:= 'ns.nspname '$2) (:= 'con1.contype "f"))) 'con) :inner-join (:as 'pg-attribute 'att) :on (:and (:= 'att.attrelid 'con.confrelid) (:= 'att.attnum 'con.child)) :inner-join (:as 'pg-class 'cl) :on (:= 'cl.oid 'con.confrelid) :inner-join (:as 'pg-attribute 'att2) :on (:and (:= 'att2.attrelid 'con.conrelid) (:= 'att2.attnum 'con.parent))) table schema)) (defun list-unique-or-primary-constraints (table-name &optional (strings-p)) "List constraints on a table. Table-name can be either a string or quoted. Turns constraints into keywords if strings-p is not true." (setf table-name (to-sql-name table-name)) (when (table-exists-p table-name) (let ((result (query (:select 'relname :from 'pg-class :where (:in 'oid (:select 'indexrelid :from 'pg-index 'pg-class :where (:and (:= 'pg-class.relname '$1) (:= 'pg-class.oid 'pg-index.indrelid) (:or (:= 'indisunique "t") (:= 'indisprimary "t")))))) table-name))) (if strings-p result (loop for x in result collect (mapcar 'from-sql-name x)))))) (defun list-check-constraints (table-name) "Takes a fully qualified table name and returns a list of lists of check constraints where each sublist has the form of (check-constraint-name check). See postmodern doc for example" (query "SELECT r.conname, pg_catalog.pg_get_constraintdef(r.oid, true) FROM pg_catalog.pg_constraint r WHERE r.conrelid = $1 AND r.contype = 'c' (get-table-oid table-name))) (defun list-all-constraints (table-name &optional (strings-p)) "Uses information_schema to list all the constraints in a table. Table-name can be either a string or quoted. Turns constraints into keywords if strings-p is not true." (setf table-name (to-sql-name table-name)) (when (table-exists-p table-name) (let ((result (query (:select 'constraint-name 'constraint-type :from 'information-schema.table-constraints :where (:= 'table-name '$1)) table-name))) (if strings-p result (loop for x in result collect (mapcar 'from-sql-name x)))))) (defun describe-constraint (table-name constraint-name) "Return a list of alists of the descriptions a particular constraint given the table-name and the constraint name using the information_schema table." (setf table-name (to-sql-name table-name)) (when (table-exists-p table-name) (first (query (:select 'tc.constraint-name 'tc.constraint-type 'tc.table-name 'kcu.column-name 'tc.is-deferrable 'tc.initially-deferred (:as 'rc.match-option 'match-type) (:as 'rc.update-rule 'on-update) (:as 'rc.delete-rule 'on-delete) (:as 'ccu.table-name 'references-table) (:as 'ccu.column-name 'references-field) :from (:as 'information-schema.table-constraints 'tc) :left-join (:as 'information-schema.key-column-usage 'kcu) :on (:and (:= 'tc.constraint-catalog 'kcu.constraint-catalog) (:= 'tc.constraint-schema 'kcu.constraint-schema) (:= 'tc.constraint-name 'kcu.constraint-name)) :left-join (:as 'information-schema.referential-constraints 'rc) :on (:and (:= 'tc.constraint-catalog 'rc.constraint-catalog) (:= 'tc.constraint-schema 'rc.constraint-schema) (:= 'tc.constraint-name 'rc.constraint-name)) :left-join (:as 'information-schema.constraint-column-usage 'ccu) :on (:and (:= 'rc.unique-constraint-catalog 'ccu.constraint-catalog) (:= 'rc.unique-constraint-schema 'ccu.constraint-schema) (:= 'rc.unique-constraint-name 'ccu.constraint-name)) :where (:and (:= 'tc.table-name '$1) (:= 'tc.constraint-name (to-sql-name constraint-name)))) table-name :alists)))) (defun describe-foreign-key-constraints () "Generates a list of lists of information on the foreign key constraints where each row returned is in the form of (constraint-name 631066 table-name table-column 631061 foreign-table-name foreign-table-column)" (query (:order-by (:select 'conname (:as 'conrelid 'table) (:as 'pgc.relname 'tabname) (:as 'a.attname 'columns) (:as 'confrelid 'foreign-table) (:as 'pgf.relname 'ftabname) (:as 'af.attname 'fcolumn) :from (:as 'pg_attribute 'af) (:as 'pg_attribute 'a) (:as 'pg_class 'pgc) (:as 'pg_class 'pgf) (:as (:select 'conname 'conrelid 'confrelid (:as (:[] 'conkey 'i) 'conkey) (:as (:[] 'confkey 'i) 'confkey) :from (:as (:select 'conname 'conrelid 'confrelid 'conkey 'confkey (:as (:generate-series '1 (:array-upper 'conkey 1)) 'i) :from 'pg_constraint :where (:= 'contype "f" )) 'ss)) 'ss2) :where (:and (:= 'af.attnum 'confkey) (:= 'af.attrelid 'confrelid) (:= 'a.attnum 'conkey) (:= 'a.attrelid 'conrelid) (:= 'pgf.relfilenode 'confrelid) (:= 'pgc.relfilenode 'conrelid))) 'ftabname 'fcolumn 'tabname 'columns))) (defun describe-triggers () "List detailed information on the triggers from the information_schema table." (query (:select '* :from 'information-schema.triggers :where (:not-in 'trigger-schema (:set "pg_catalog" "information_schema"))))) (defun list-triggers (&optional table-name) "List distinct trigger names from the information_schema table. Table-name can be either quoted or string. (A trigger is a specification that the database should automatically execute a particular function whenever a certain type of operation is performed. Triggers can be attached to tables (partitioned or not), views, and foreign tables. See -definition.html)" (if table-name (progn (setf table-name (to-sql-name table-name)) (when (table-exists-p table-name) (alexandria:flatten (query (:order-by (:select (:as 'trg.tgname 'trigger-name) :from (:as 'pg-trigger 'trg) (:as 'pg-class 'tbl) :where (:and (:= 'trg.tgrelid 'tbl.oid) (:= 'tbl.relname '$1))) 'trigger-name) table-name)))) (alexandria:flatten (query (:order-by (:select 'trigger-name :distinct :from 'information-schema.triggers :where (:not-in 'trigger-schema (:set "pg-catalog" "information-schema"))) 'trigger-name))))) (defun list-detailed-triggers () "DEPRECATED FOR DESCRIBE-TRIGGERS.List detailed information on the triggers from the information_schema table." (query (:select '* :from 'information-schema.triggers :where (:not-in 'trigger-schema (:set "pg_catalog" "information_schema"))))) (defun change-toplevel-database (new-database user password host) "Just changes the database assuming you are using a toplevel connection. Recommended only for development work. Returns the name of the newly connected database as a string." (disconnect-toplevel) (connect-toplevel (to-sql-name new-database) user password host) (current-database)) (defun list-connections () "List the current postgresql connections to the currently connected database. It does this by returningo info from pg_stat_activity on open connections." (query (:select '* :from 'pg-stat-activity))) (defun list-available-extensions () "List the postgresql extensions which are available in the system to the currently connected database. The extensions may or may not be installed." (alexandria:flatten (query (:order-by (:select 'name :from 'pg-available-extensions) 'name)))) (defun list-installed-extensions () "List the postgresql extensions which are installed in the currently connected database." (alexandria:flatten (query (:order-by (:select 'extname :from 'pg-extension) 'extname)))) (defun load-uuid-extension () "Loads the Postgresql uuid-ossp contrib module. Once loaded, you can call uuid generation functions such as uuid_generate_v4 within a query. E.g. (query \"select uuid_generate_v4()\") See Postgresql documentation at -ossp.html" (query "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"")) (defun generate-uuid () "This gets a uuid (version 4) generated by Postgresql. If the uuid-ossp module is not loaded, it will load it first. This is probably not something you want to use because it is potentially two calls to Postgresql to get a uuid when you could do it in a single call within a query when you are getting other information." (unless (member "uuid-ossp" (list-installed-extensions) :test #'equal) (load-uuid-extension)) (query "select uuid_generate_v4()" :single)) (defun replace-non-alphanumeric-chars (str &optional (replacement #\_)) "Takes a string and a replacement char and replaces any character which is not alphanumeric or an asterisk with a specified character - by default an underscore and returns the modified string." (let ((str1 str)) (with-output-to-string (*standard-output*) (loop :for ch :of-type character :across str1 :do (if (or (eq ch #\*) (alphanumericp ch)) (write-char ch) (write-char replacement)))))) (defun copy-from-csv (tablename filename &key (delimiter 'comma) (header-p nil) (database (when *database* (cl-postgres::connection-db *database*))) (user (when *database* (cl-postgres::connection-user *database*))) (password (when *database* (cl-postgres::connection-password *database*))) (host (if *database* (cl-postgres::connection-host *database*) "localhost")) (port (if *database* (cl-postgres::connection-port *database*) 5432))) "Runs the psql copy command against a file. Assuming you are already connected to the desired database and the *database* global variable is set to that, then the mMinimum parameters required are the postgresql table-name and the file name including its absolute path. The delimiter parameter should be either 'comma or 'tab. Set the header-p parameter t if the first line of the csv file is a header that should not get imported into the database table. The table name can be either a string or quoted symbol." (setf tablename (to-sql-name tablename)) (uiop:run-program user password host port database tablename filename (case delimiter (comma "','") (tab "E'\t'")) (if header-p "HEADER" "")) :output :string))
603c5c466eab8c4667a5bb2a6e1cc98b4390e6bd32f5984be4012f05f1cded95
ntoronto/pict3d
untyped-pict3d-canvas.rkt
#lang racket/base (require racket/gui/base racket/match racket/list racket/draw racket/class racket/async-channel racket/math typed/opengl "../gl.rkt" "../utils.rkt" "parameters.rkt" "pict3d-struct.rkt" "pict3d-draw.rkt" ) (provide pict3d-canvas%) ;; =================================================================================================== ;; Rendering threads (struct render-command (pict3d width height z-near z-far fov background ambient auto-camera ack-channel) #:transparent) (define (render cmd canvas) (define-values (_ cpu real gc) (time-apply (λ () (match-define (render-command pict width height z-near z-far fov background ambient auto-camera ack-channel) cmd) (with-gl-context (send canvas get-managed-gl-context) (draw-pict3ds (list pict) #:width width #:height height #:camera auto-camera #:z-near z-near #:z-far z-far #:fov fov #:background background #:ambient ambient #:bitmap? #f) (gl-swap-buffers)) Send an ACK if the other side is waiting for one (when ack-channel (channel-put ack-channel #t))) empty)) (log-pict3d-debug "<canvas> heap size: ~a cpu time: ~a real time: ~a gc time: ~a" (real->decimal-string (/ (current-memory-use) (* 1024 1024)) 2) cpu real gc)) (: make - canvas - render - thread ( - > ( Instance Pict3D - Canvas% ) ( Async - Channelof render - command ) Thread ) ) (define (make-canvas-render-thread canvas ch) ;(: render-thread-loop (-> Void)) (define (render-thread-loop) ;; Wait for a scene and view matrix ;(: cmd render-command) (define cmd (let ([cmd (async-channel-get ch)]) Empty the queue looking for the lastest one (let loop ([cmd cmd]) (define new-cmd (async-channel-try-get ch)) (if new-cmd (loop new-cmd) cmd)))) (render cmd canvas) (render-thread-loop)) (thread render-thread-loop)) ;; =================================================================================================== ;; Scene canvas ;(: pict3d-canvas% Pict3D-Canvas%) (define pict3d-canvas% (class canvas% (init parent [style '()] [label #f] [enabled #t] [vert-margin 0] [horiz-margin 0] [min-width #f] [min-height #f] [stretchable-width #t] [stretchable-height #t]) (init-field [pict3d empty-pict3d]) (define legacy? (current-pict3d-legacy?)) (define check-version? (current-pict3d-check-version?)) (define config (new gl-config%)) (send config set-legacy? legacy?) (super-new [parent parent] [style (list* 'gl 'no-autoclear style)] [paint-callback void] [label label] [gl-config config] [enabled enabled] [vert-margin vert-margin] [horiz-margin horiz-margin] [min-width min-width] [min-height min-height] [stretchable-width stretchable-width] [stretchable-height stretchable-height]) (define async-updates? #f) (define/public (set-async-updates? async?) (set! async-updates? async?)) (: render - queue ( Async - Channel render - command ) ) (define render-queue (make-async-channel)) ;(: render-thread Thread) (define render-thread (make-canvas-render-thread this render-queue)) ;(: get-gl-window-size (-> (Values Index Index))) (define (get-gl-window-size) (define-values (w h) (send (send this get-dc) get-size)) (values (exact-ceiling w) (exact-ceiling h))) (define z-near (current-pict3d-z-near)) (define z-far (current-pict3d-z-far)) (define fov (current-pict3d-fov)) (define background (current-pict3d-background)) (define ambient (current-pict3d-ambient)) (define auto-camera (current-pict3d-auto-camera)) (define (do-render new-pict width height z-near z-far fov background ambient auto-camera async?) (define ack-channel (if async? #f (make-channel))) (async-channel-put render-queue (render-command new-pict width height z-near z-far fov background ambient auto-camera ack-channel)) (when ack-channel (channel-get ack-channel))) (define/public (set-pict3d new-pict) (set! pict3d new-pict) (define-values (width height) (get-gl-window-size)) (set! z-near (current-pict3d-z-near)) (set! z-far (current-pict3d-z-far)) (set! fov (current-pict3d-fov)) (set! background (current-pict3d-background)) (set! ambient (current-pict3d-ambient)) (set! auto-camera (current-pict3d-auto-camera)) (do-render new-pict width height z-near z-far fov background ambient auto-camera async-updates?)) (define/public (get-pict3d) pict3d) ;(: managed-ctxt (U #f GL-Context)) (define managed-ctxt #f) ;(: get-managed-gl-context (-> GL-Context)) (define/public (get-managed-gl-context) (define mctxt managed-ctxt) (cond [mctxt mctxt] [else (define ctxt (send (send this get-dc) get-gl-context)) (cond [(or (not ctxt) (not (send ctxt ok?))) (log-pict3d-warning "<canvas> could not get canvas OpenGL context (legacy? = ~a)" legacy?) (error 'pict3d-canvas% "could not get canvas OpenGL context (legacy? = ~a)" legacy?)] [(or (not check-version?) (send ctxt call-as-current (λ () (gl-version-at-least? 30)))) (define version (send ctxt call-as-current gl-version)) (log-pict3d-info "<canvas> got canvas OpenGL ~a context (legacy? = ~a)" version legacy?) (let ([mctxt (managed-gl-context ctxt)]) (set! managed-ctxt mctxt) mctxt)] [else (define version (send ctxt call-as-current gl-version)) (log-pict3d-warning "<canvas> got canvas OpenGL ~a context (legacy? = ~a)" version legacy?) (error 'pict3d-canvas% "could not get at least an OpenGL 30 context (legacy? = ~a)" legacy?)])])) (define/override (on-paint) (define-values (width height) (get-gl-window-size)) (do-render pict3d width height z-near z-far fov background ambient auto-camera #t) (super on-paint)) ))
null
https://raw.githubusercontent.com/ntoronto/pict3d/09283c9d930c63b6a6a3f2caa43e029222091bdb/pict3d/private/gui/untyped-pict3d-canvas.rkt
racket
=================================================================================================== Rendering threads (: render-thread-loop (-> Void)) Wait for a scene and view matrix (: cmd render-command) =================================================================================================== Scene canvas (: pict3d-canvas% Pict3D-Canvas%) (: render-thread Thread) (: get-gl-window-size (-> (Values Index Index))) (: managed-ctxt (U #f GL-Context)) (: get-managed-gl-context (-> GL-Context))
#lang racket/base (require racket/gui/base racket/match racket/list racket/draw racket/class racket/async-channel racket/math typed/opengl "../gl.rkt" "../utils.rkt" "parameters.rkt" "pict3d-struct.rkt" "pict3d-draw.rkt" ) (provide pict3d-canvas%) (struct render-command (pict3d width height z-near z-far fov background ambient auto-camera ack-channel) #:transparent) (define (render cmd canvas) (define-values (_ cpu real gc) (time-apply (λ () (match-define (render-command pict width height z-near z-far fov background ambient auto-camera ack-channel) cmd) (with-gl-context (send canvas get-managed-gl-context) (draw-pict3ds (list pict) #:width width #:height height #:camera auto-camera #:z-near z-near #:z-far z-far #:fov fov #:background background #:ambient ambient #:bitmap? #f) (gl-swap-buffers)) Send an ACK if the other side is waiting for one (when ack-channel (channel-put ack-channel #t))) empty)) (log-pict3d-debug "<canvas> heap size: ~a cpu time: ~a real time: ~a gc time: ~a" (real->decimal-string (/ (current-memory-use) (* 1024 1024)) 2) cpu real gc)) (: make - canvas - render - thread ( - > ( Instance Pict3D - Canvas% ) ( Async - Channelof render - command ) Thread ) ) (define (make-canvas-render-thread canvas ch) (define (render-thread-loop) (define cmd (let ([cmd (async-channel-get ch)]) Empty the queue looking for the lastest one (let loop ([cmd cmd]) (define new-cmd (async-channel-try-get ch)) (if new-cmd (loop new-cmd) cmd)))) (render cmd canvas) (render-thread-loop)) (thread render-thread-loop)) (define pict3d-canvas% (class canvas% (init parent [style '()] [label #f] [enabled #t] [vert-margin 0] [horiz-margin 0] [min-width #f] [min-height #f] [stretchable-width #t] [stretchable-height #t]) (init-field [pict3d empty-pict3d]) (define legacy? (current-pict3d-legacy?)) (define check-version? (current-pict3d-check-version?)) (define config (new gl-config%)) (send config set-legacy? legacy?) (super-new [parent parent] [style (list* 'gl 'no-autoclear style)] [paint-callback void] [label label] [gl-config config] [enabled enabled] [vert-margin vert-margin] [horiz-margin horiz-margin] [min-width min-width] [min-height min-height] [stretchable-width stretchable-width] [stretchable-height stretchable-height]) (define async-updates? #f) (define/public (set-async-updates? async?) (set! async-updates? async?)) (: render - queue ( Async - Channel render - command ) ) (define render-queue (make-async-channel)) (define render-thread (make-canvas-render-thread this render-queue)) (define (get-gl-window-size) (define-values (w h) (send (send this get-dc) get-size)) (values (exact-ceiling w) (exact-ceiling h))) (define z-near (current-pict3d-z-near)) (define z-far (current-pict3d-z-far)) (define fov (current-pict3d-fov)) (define background (current-pict3d-background)) (define ambient (current-pict3d-ambient)) (define auto-camera (current-pict3d-auto-camera)) (define (do-render new-pict width height z-near z-far fov background ambient auto-camera async?) (define ack-channel (if async? #f (make-channel))) (async-channel-put render-queue (render-command new-pict width height z-near z-far fov background ambient auto-camera ack-channel)) (when ack-channel (channel-get ack-channel))) (define/public (set-pict3d new-pict) (set! pict3d new-pict) (define-values (width height) (get-gl-window-size)) (set! z-near (current-pict3d-z-near)) (set! z-far (current-pict3d-z-far)) (set! fov (current-pict3d-fov)) (set! background (current-pict3d-background)) (set! ambient (current-pict3d-ambient)) (set! auto-camera (current-pict3d-auto-camera)) (do-render new-pict width height z-near z-far fov background ambient auto-camera async-updates?)) (define/public (get-pict3d) pict3d) (define managed-ctxt #f) (define/public (get-managed-gl-context) (define mctxt managed-ctxt) (cond [mctxt mctxt] [else (define ctxt (send (send this get-dc) get-gl-context)) (cond [(or (not ctxt) (not (send ctxt ok?))) (log-pict3d-warning "<canvas> could not get canvas OpenGL context (legacy? = ~a)" legacy?) (error 'pict3d-canvas% "could not get canvas OpenGL context (legacy? = ~a)" legacy?)] [(or (not check-version?) (send ctxt call-as-current (λ () (gl-version-at-least? 30)))) (define version (send ctxt call-as-current gl-version)) (log-pict3d-info "<canvas> got canvas OpenGL ~a context (legacy? = ~a)" version legacy?) (let ([mctxt (managed-gl-context ctxt)]) (set! managed-ctxt mctxt) mctxt)] [else (define version (send ctxt call-as-current gl-version)) (log-pict3d-warning "<canvas> got canvas OpenGL ~a context (legacy? = ~a)" version legacy?) (error 'pict3d-canvas% "could not get at least an OpenGL 30 context (legacy? = ~a)" legacy?)])])) (define/override (on-paint) (define-values (width height) (get-gl-window-size)) (do-render pict3d width height z-near z-far fov background ambient auto-camera #t) (super on-paint)) ))
acbddc6bcf2e83e0004f8b34f47baa5ca0d371be60b73f83d2e7eb9c2bc688cc
xsc/claro
chain.cljc
(ns claro.data.ops.chain (:require [claro.data.protocols :as p] [claro.data.tree [blocking-composition :refer [->BlockingComposition]] [composition :as composition :refer [->ResolvableComposition]] [leaf :refer [->ResolvableLeaf]]] [claro.data.tree :refer [wrap-tree]])) ;; ## Resolved Node (deftype ResolvedComposition [value f] p/ResolvableTree (wrapped? [_] true) (processable? [_] false) (resolvables* [_] (throw (IllegalStateException. "'ResolvedComposition' should never be inspected. This is a bug."))) (unwrap-tree [_] (f (p/unwrap-tree value)))) ;; ## Chains (defn- chain-resolvable-when [value predicate f] (when (p/resolvable? value) (->ResolvableComposition (->ResolvableLeaf value) predicate f))) (defn- chain-tree-when [value predicate f] (let [tree (wrap-tree value) value' (composition/match-value tree predicate ::none)] (if (= value' ::none) (->ResolvableComposition tree predicate f) (->ResolvedComposition value' f)))) (defn chain-when "Apply the given function to the (potentially not fully-resolved) value once `predicate` is fulfilled." [value predicate f] (let [f' (comp wrap-tree f)] (or (chain-resolvable-when value predicate f') (chain-tree-when value predicate f')))) (defn chain-blocking* "Apply the given function once `value` is fully resolved. `f` is not allowed to introduce any futher resolvables, or has to wrap the result using `wrap-tree`." [value f] (if (p/resolvable? value) (->BlockingComposition (->ResolvableLeaf value) f) (let [tree (wrap-tree value)] (if (p/resolved? tree) (->ResolvedComposition tree f) (->BlockingComposition tree f))))) (defn chain-blocking "Apply the given function once `value` is fully resolved." [value f] (chain-blocking* value (comp wrap-tree f))) (defn chain-eager "Apply the given function once the value is no longer a `Resolvable` or wrapped." [value f] (chain-when value nil f))
null
https://raw.githubusercontent.com/xsc/claro/16db75b7a775a14f3b656362e8ee4f65dd8b0d49/src/claro/data/ops/chain.cljc
clojure
## Resolved Node ## Chains
(ns claro.data.ops.chain (:require [claro.data.protocols :as p] [claro.data.tree [blocking-composition :refer [->BlockingComposition]] [composition :as composition :refer [->ResolvableComposition]] [leaf :refer [->ResolvableLeaf]]] [claro.data.tree :refer [wrap-tree]])) (deftype ResolvedComposition [value f] p/ResolvableTree (wrapped? [_] true) (processable? [_] false) (resolvables* [_] (throw (IllegalStateException. "'ResolvedComposition' should never be inspected. This is a bug."))) (unwrap-tree [_] (f (p/unwrap-tree value)))) (defn- chain-resolvable-when [value predicate f] (when (p/resolvable? value) (->ResolvableComposition (->ResolvableLeaf value) predicate f))) (defn- chain-tree-when [value predicate f] (let [tree (wrap-tree value) value' (composition/match-value tree predicate ::none)] (if (= value' ::none) (->ResolvableComposition tree predicate f) (->ResolvedComposition value' f)))) (defn chain-when "Apply the given function to the (potentially not fully-resolved) value once `predicate` is fulfilled." [value predicate f] (let [f' (comp wrap-tree f)] (or (chain-resolvable-when value predicate f') (chain-tree-when value predicate f')))) (defn chain-blocking* "Apply the given function once `value` is fully resolved. `f` is not allowed to introduce any futher resolvables, or has to wrap the result using `wrap-tree`." [value f] (if (p/resolvable? value) (->BlockingComposition (->ResolvableLeaf value) f) (let [tree (wrap-tree value)] (if (p/resolved? tree) (->ResolvedComposition tree f) (->BlockingComposition tree f))))) (defn chain-blocking "Apply the given function once `value` is fully resolved." [value f] (chain-blocking* value (comp wrap-tree f))) (defn chain-eager "Apply the given function once the value is no longer a `Resolvable` or wrapped." [value f] (chain-when value nil f))
721543921f4f12758b3d196e40e20532f5c58a3cac8ac4e6de4ff20764743c96
metabase/metabase
util.cljc
(ns metabase.mbql.util "Utilitiy functions for working with MBQL queries." (:refer-clojure :exclude [replace]) #?@ (:clj [(:require [clojure.string :as str] [metabase.mbql.predicates :as mbql.preds] [metabase.mbql.schema :as mbql.s] [metabase.mbql.schema.helpers :as schema.helpers] [metabase.mbql.util.match :as mbql.match] [metabase.models.dispatch :as models.dispatch] [metabase.shared.util.i18n :as i18n] [metabase.util.i18n] [metabase.util.log :as log] [potemkin :as p] [schema.core :as s])] :cljs [(:require [clojure.string :as str] [metabase.mbql.predicates :as mbql.preds] [metabase.mbql.schema :as mbql.s] [metabase.mbql.schema.helpers :as schema.helpers] [metabase.mbql.util.match :as mbql.match] [metabase.shared.util.i18n :as i18n] [schema.core :as s])])) (defn qualified-name "Like `name`, but if `x` is a namespace-qualified keyword, returns that a string including the namespace." [x] (if (and (keyword? x) (namespace x)) (str (namespace x) "/" (name x)) (name x))) (s/defn normalize-token :- s/Keyword "Convert a string or keyword in various cases (`lisp-case`, `snake_case`, or `SCREAMING_SNAKE_CASE`) to a lisp-cased keyword." [token :- schema.helpers/KeywordOrString] #_{:clj-kondo/ignore [:discouraged-var]} (-> (qualified-name token) str/lower-case (str/replace #"_" "-") keyword)) (defn mbql-clause? "True if `x` is an MBQL clause (a sequence with a keyword as its first arg). (Since this is used by the code in `normalize` this handles pre-normalized clauses as well.)" [x] (and (sequential? x) (not (map-entry? x)) (keyword? (first x)))) (defn is-clause? "If `x` an MBQL clause, and an instance of clauses defined by keyword(s) `k-or-ks`? (is-clause? :count [:count 10]) ; -> true (is-clause? #{:+ :- :* :/} [:+ 10 20]) ; -> true" [k-or-ks x] (and (mbql-clause? x) (if (coll? k-or-ks) ((set k-or-ks) (first x)) (= k-or-ks (first x))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Functions for manipulating queries | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- combine-compound-filters-of-type [compound-type subclauses] (mapcat #(mbql.match/match-one % [(_ :guard (partial = compound-type)) & args] args _ [&match]) subclauses)) (defn simplify-compound-filter "Simplify compound `:and`, `:or`, and `:not` compound filters, combining or eliminating them where possible. This also fixes theoretically disallowed compound filters like `:and` with only a single subclause, and eliminates `nils` and duplicate subclauses from the clauses." [filter-clause] (mbql.match/replace filter-clause seq? (recur (vec &match)) ;; if this an an empty filter, toss it nil nil [& (_ :guard (partial every? nil?))] nil [] nil [(:or :and :or)] nil if the COMPOUND clause contains any nils , toss them [(clause-name :guard #{:and :or}) & (args :guard (partial some nil?))] (recur (apply vector clause-name (filterv some? args))) Rewrite a ` : not ` over ` : and ` using de Morgan 's law [:not [:and & args]] (recur (apply vector :or (map #(vector :not %) args))) Rewrite a ` : not ` over ` : or ` using de Morgan 's law [:not [:or & args]] (recur (apply vector :and (map #(vector :not %) args))) for ` and ` or ` not ` compound filters with only one subclase , just unnest the subclause [(:or :and :or) arg] (recur arg) ;; for `and` and `not` compound filters with subclauses of the same type pull up any compounds of the same type ;; e.g. [:and :a [:and b c]] ; -> [:and a b c] [:and & (args :guard (partial some (partial is-clause? :and)))] (recur (apply vector :and (combine-compound-filters-of-type :and args))) [:or & (args :guard (partial some (partial is-clause? :or)))] (recur (apply vector :or (combine-compound-filters-of-type :or args))) ;; for `and` or `or` clauses with duplicate args, remove the duplicates and recur [(clause :guard #{:and :or}) & (args :guard #(not (apply distinct? %)))] (recur (apply vector clause (distinct args))) ;; for `not` that wraps another `not`, eliminate both [:not [:not arg]] (recur arg) :else filter-clause)) (s/defn combine-filter-clauses :- mbql.s/Filter "Combine two filter clauses into a single clause in a way that minimizes slapping a bunch of `:and`s together if possible." [filter-clause & more-filter-clauses] (simplify-compound-filter (cons :and (cons filter-clause more-filter-clauses)))) (s/defn add-filter-clause-to-inner-query :- mbql.s/MBQLQuery "Add a additional filter clause to an *inner* MBQL query, merging with the existing filter clause with `:and` if needed." [inner-query :- mbql.s/MBQLQuery new-clause :- (s/maybe mbql.s/Filter)] (if-not new-clause inner-query (update inner-query :filter combine-filter-clauses new-clause))) (s/defn add-filter-clause :- mbql.s/Query "Add an additional filter clause to an `outer-query`. If `new-clause` is `nil` this is a no-op." [outer-query :- mbql.s/Query new-clause :- (s/maybe mbql.s/Filter)] (update outer-query :query add-filter-clause-to-inner-query new-clause)) (defn desugar-inside "Rewrite `:inside` filter clauses as a pair of `:between` clauses." [m] (mbql.match/replace m [:inside lat-field lon-field lat-max lon-min lat-min lon-max] [:and [:between lat-field lat-min lat-max] [:between lon-field lon-min lon-max]])) (defn desugar-is-null-and-not-null "Rewrite `:is-null` and `:not-null` filter clauses as simpler `:=` and `:!=`, respectively." [m] (mbql.match/replace m [:is-null field] [:= field nil] [:not-null field] [:!= field nil])) (defn desugar-is-empty-and-not-empty "Rewrite `:is-empty` and `:not-empty` filter clauses as simpler `:=` and `:!=`, respectively." [m] (mbql.match/replace m [:is-empty field] [:or [:= field nil] [:= field ""]] [:not-empty field] [:and [:!= field nil] [:!= field ""]])) (defn- replace-field-or-expression "Replace a field or expression inside :time-interval" [m unit] (mbql.match/replace m [:field id-or-name opts] [:field id-or-name (assoc opts :temporal-unit unit)] [:expression expression-name] [:expression expression-name])) (defn desugar-time-interval "Rewrite `:time-interval` filter clauses as simpler ones like `:=` or `:between`." [m] (mbql.match/replace m [:time-interval field-or-expression n unit] (recur [:time-interval field-or-expression n unit nil]) ;; replace current/last/next with corresponding value of n and recur [:time-interval field-or-expression :current unit options] (recur [:time-interval field-or-expression 0 unit options]) [:time-interval field-or-expression :last unit options] (recur [:time-interval field-or-expression -1 unit options]) [:time-interval field-or-expression :next unit options] (recur [:time-interval field-or-expression 1 unit options]) [:time-interval field-or-expression (n :guard #{-1}) unit (_ :guard :include-current)] [:between (replace-field-or-expression field-or-expression unit) [:relative-datetime n unit] [:relative-datetime 0 unit]] [:time-interval field-or-expression (n :guard #{1}) unit (_ :guard :include-current)] [:between (replace-field-or-expression field-or-expression unit) [:relative-datetime 0 unit] [:relative-datetime n unit]] [:time-interval field-or-expression (n :guard #{-1 0 1}) unit _] [:= (replace-field-or-expression field-or-expression unit) [:relative-datetime n unit]] [:time-interval field-or-expression (n :guard neg?) unit (_ :guard :include-current)] [:between (replace-field-or-expression field-or-expression unit) [:relative-datetime n unit] [:relative-datetime 0 unit]] [:time-interval field-or-expression (n :guard neg?) unit _] [:between (replace-field-or-expression field-or-expression unit) [:relative-datetime n unit] [:relative-datetime -1 unit]] [:time-interval field-or-expression n unit (_ :guard :include-current)] [:between (replace-field-or-expression field-or-expression unit) [:relative-datetime 0 unit] [:relative-datetime n unit]] [:time-interval field-or-expression n unit _] [:between (replace-field-or-expression field-or-expression unit) [:relative-datetime 1 unit] [:relative-datetime n unit]])) (defn desugar-does-not-contain "Rewrite `:does-not-contain` filter clauses as simpler `:not` clauses." [m] (mbql.match/replace m [:does-not-contain & args] [:not (into [:contains] args)])) (defn desugar-equals-and-not-equals-with-extra-args "`:=` and `!=` clauses with more than 2 args automatically get rewritten as compound filters. [:= field x y] -> [:or [:= field x] [:= field y]] [:!= field x y] -> [:and [:!= field x] [:!= field y]]" [m] (mbql.match/replace m [:= field x y & more] (apply vector :or (for [x (concat [x y] more)] [:= field x])) [:!= field x y & more] (apply vector :and (for [x (concat [x y] more)] [:!= field x])))) (defn desugar-current-relative-datetime "Replace `relative-datetime` clauses like `[:relative-datetime :current]` with `[:relative-datetime 0 <unit>]`. `<unit>` is inferred from the `:field` the clause is being compared to (if any), otherwise falls back to `default.`" [m] (mbql.match/replace m [clause field & (args :guard (partial some (partial = [:relative-datetime :current])))] (let [temporal-unit (or (mbql.match/match-one field [:field _ {:temporal-unit temporal-unit}] temporal-unit) :default)] (into [clause field] (mbql.match/replace args [:relative-datetime :current] [:relative-datetime 0 temporal-unit]))))) (def temporal-extract-ops->unit "Mapping from the sugar syntax to extract datetime to the unit." {[:get-year nil] :year-of-era [:get-quarter nil] :quarter-of-year [:get-month nil] :month-of-year ;; default get-week mode is iso [:get-week nil] :week-of-year-iso [:get-week :iso] :week-of-year-iso [:get-week :us] :week-of-year-us [:get-week :instance] :week-of-year-instance [:get-day nil] :day-of-month [:get-day-of-week nil] :day-of-week [:get-hour nil] :hour-of-day [:get-minute nil] :minute-of-hour [:get-second nil] :second-of-minute}) (def ^:private temporal-extract-ops (->> (keys temporal-extract-ops->unit) (map first) set)) (defn desugar-temporal-extract "Replace datetime extractions clauses like `[:get-year field]` with `[:temporal-extract field :year]`." [m] (mbql.match/replace m [(op :guard temporal-extract-ops) field & args] [:temporal-extract field (temporal-extract-ops->unit [op (first args)])])) (defn- desugar-divide-with-extra-args [expression] (mbql.match/replace expression [:/ x y z & more] (recur (into [:/ [:/ x y]] (cons z more))))) (s/defn desugar-expression :- mbql.s/FieldOrExpressionDef "Rewrite various 'syntactic sugar' expressions like `:/` with more than two args into something simpler for drivers to compile." [expression :- mbql.s/FieldOrExpressionDef] (-> expression desugar-divide-with-extra-args)) (defn- maybe-desugar-expression [clause] (cond-> clause (mbql.preds/FieldOrExpressionDef? clause) desugar-expression)) (s/defn desugar-filter-clause :- mbql.s/Filter "Rewrite various 'syntatic sugar' filter clauses like `:time-interval` and `:inside` as simpler, logically equivalent clauses. This can be used to simplify the number of filter clauses that need to be supported by anything that needs to enumerate all the possible filter types (such as driver query processor implementations, or the implementation `negate-filter-clause` below.)" [filter-clause :- mbql.s/Filter] (-> filter-clause desugar-current-relative-datetime desugar-equals-and-not-equals-with-extra-args desugar-does-not-contain desugar-time-interval desugar-is-null-and-not-null desugar-is-empty-and-not-empty desugar-inside simplify-compound-filter desugar-temporal-extract maybe-desugar-expression)) (defmulti ^:private negate* first) (defmethod negate* :not [[_ subclause]] subclause) (defmethod negate* :and [[_ & subclauses]] (into [:or] (map negate* subclauses))) (defmethod negate* :or [[_ & subclauses]] (into [:and] (map negate* subclauses))) (defmethod negate* := [[_ field value]] [:!= field value]) (defmethod negate* :!= [[_ field value]] [:= field value]) (defmethod negate* :> [[_ field value]] [:<= field value]) (defmethod negate* :< [[_ field value]] [:>= field value]) (defmethod negate* :>= [[_ field value]] [:< field value]) (defmethod negate* :<= [[_ field value]] [:> field value]) (defmethod negate* :between [[_ field min max]] [:or [:< field min] [:> field max]]) (defmethod negate* :contains [clause] [:not clause]) (defmethod negate* :starts-with [clause] [:not clause]) (defmethod negate* :ends-with [clause] [:not clause]) (s/defn negate-filter-clause :- mbql.s/Filter "Return the logical compliment of an MBQL filter clause, generally without using `:not` (except for the string filter clause types). Useful for generating highly optimized filter clauses and for drivers that do not support top-level `:not` filter clauses." [filter-clause :- mbql.s/Filter] (-> filter-clause desugar-filter-clause negate* simplify-compound-filter)) (s/defn query->source-table-id :- (s/maybe schema.helpers/IntGreaterThanZero) "Return the source Table ID associated with `query`, if applicable; handles nested queries as well. If `query` is `nil`, returns `nil`. Throws an Exception when it encounters a unresolved source query (i.e., the `:source-table \"card__id\"` form), because it cannot return an accurate result for a query that has not yet been preprocessed." {:arglists '([outer-query])} [{{source-table-id :source-table, source-query :source-query} :query, query-type :type, :as query}] (cond ;; for native queries, there's no source table to resolve (not= query-type :query) nil ;; for MBQL queries with a *native* source query, it's the same story (and (nil? source-table-id) source-query (:native source-query)) nil ;; for MBQL queries with an MBQL source query, recurse on the source query and try again (and (nil? source-table-id) source-query) (recur (assoc query :query source-query)) ;; if ID is a `card__id` form that can only mean we haven't preprocessed the query and resolved the source query. ;; This is almost certainly an accident, so throw an Exception so we can make the proper fixes ((every-pred string? (partial re-matches mbql.s/source-table-card-id-regex)) source-table-id) (throw (ex-info (i18n/tru "Error: query''s source query has not been resolved. You probably need to `preprocess` the query first.") {})) ;; otherwise resolve the source Table :else source-table-id)) (s/defn join->source-table-id :- (s/maybe schema.helpers/IntGreaterThanZero) "Like `query->source-table-id`, but for a join." [join] (query->source-table-id {:type :query, :query join})) (s/defn add-order-by-clause :- mbql.s/MBQLQuery "Add a new `:order-by` clause to an MBQL `inner-query`. If the new order-by clause references a Field that is already being used in another order-by clause, this function does nothing." [inner-query :- mbql.s/MBQLQuery, [_ [_ id-or-name :as _field], :as order-by-clause] :- mbql.s/OrderBy] (let [existing-fields (set (for [[_ [_ id-or-name]] (:order-by inner-query)] id-or-name))] (if (existing-fields id-or-name) Field already referenced , nothing to do inner-query ;; otherwise add new clause at the end (update inner-query :order-by (comp vec distinct conj) order-by-clause)))) (defn dispatch-by-clause-name-or-class "Dispatch function perfect for use with multimethods that dispatch off elements of an MBQL query. If `x` is an MBQL clause, dispatches off the clause name; otherwise dispatches off `x`'s class." ([x] #?(:clj (if (mbql-clause? x) (first x) (or (metabase.models.dispatch/model x) (type x))) :cljs (if (mbql-clause? x) (first x) (type x)))) ([x _] (dispatch-by-clause-name-or-class x))) (s/defn expression-with-name :- mbql.s/FieldOrExpressionDef "Return the `Expression` referenced by a given `expression-name`." [inner-query expression-name :- (s/cond-pre s/Keyword schema.helpers/NonBlankString)] (let [allowed-names [(qualified-name expression-name) (keyword expression-name)]] (loop [{:keys [expressions source-query]} inner-query, found #{}] (or ;; look for either string or keyword version of `expression-name` in `expressions` (some (partial get expressions) allowed-names) ;; otherwise, if we have a source query recursively look in that (do we allow that??) (let [found (into found (keys expressions))] (if source-query (recur source-query found) ;; failing that throw an Exception with detailed info about what we tried and what the actual expressions ;; were (throw (ex-info (i18n/tru "No expression named ''{0}''" (qualified-name expression-name)) {:type :invalid-query :expression-name expression-name :tried allowed-names :found found})))))))) (s/defn aggregation-at-index :- mbql.s/Aggregation "Fetch the aggregation at index. This is intended to power aggregate field references (e.g. [:aggregation 0]). This also handles nested queries, which could be potentially ambiguous if multiple levels had aggregations. To support nested queries, you'll need to keep tract of how many `:source-query`s deep you've traveled; pass in this number to as optional arg `nesting-level` to make sure you reference aggregations at the right level of nesting." ([query index] (aggregation-at-index query index 0)) ([query :- mbql.s/Query index :- schema.helpers/IntGreaterThanOrEqualToZero nesting-level :- schema.helpers/IntGreaterThanOrEqualToZero] (if (zero? nesting-level) (or (nth (get-in query [:query :aggregation]) index) (throw (ex-info (i18n/tru "No aggregation at index: {0}" index) {:index index}))) ;; keep recursing deeper into the query until we get to the same level the aggregation reference was defined at (recur {:query (get-in query [:query :source-query])} index (dec nesting-level))))) (defn ga-id? "Is this ID (presumably of a Metric or Segment) a GA one?" [id] (boolean (when ((some-fn string? keyword?) id) (re-find #"^ga(id)?:" (name id))))) (defn ga-metric-or-segment? "Is this metric or segment clause not a Metabase Metric or Segment, but rather a GA one? E.g. something like `[:metric ga:users]`. We want to ignore those because they're not the same thing at all as MB Metrics/Segments and don't correspond to objects in our application DB." [[_ id]] (ga-id? id)) (defn temporal-field? "Is `field` used to record something date or time related, i.e. does `field` have a base type or semantic type that derives from `:type/Temporal`?" [field] (or (isa? (:base_type field) :type/Temporal) (isa? (:semantic_type field) :type/Temporal))) (defn time-field? "Is `field` used to record a time of day (e.g. hour/minute/second), but not the date itself? i.e. does `field` have a base type or semantic type that derives from `:type/Time`?" [field] (or (isa? (:base_type field) :type/Time) (isa? (:semantic_type field) :type/Time))) (defn temporal-but-not-time-field? "Does `field` have a base type or semantic type that derives from `:type/Temporal`, but not `:type/Time`? (i.e., is Field a Date or DateTime?)" [field] (and (temporal-field? field) (not (time-field? field)))) ;;; --------------------------------- Unique names & transforming ags to have names ---------------------------------- (defn unique-name-generator "Return a function that can be used to uniquify string names. Function maintains an internal counter that will suffix any names passed to it as needed so all results will be unique. (let [unique-name (unique-name-generator)] [(unique-name \"A\") (unique-name \"B\") (unique-name \"A\")]) ;; -> [\"A\" \"B\" \"A_2\"] By default, unique aliases are generated for each unique `[id original-name]` key pair. By default, a unique `id` is generated for every call, meaning repeated calls to [[unique-name-generator]] with the same `original-name` will return different unique aliases. If idempotence is desired, the function returned by the generator also has a 2 airity version with the signature (unique-name-fn id original-name) for example: (let [unique-name (unique-name-generator)] [(unique-name :x \"A\") (unique-name :x \"B\") (unique-name :x \"A\") (unique-name :y \"A\")]) ;; -> [\"A\" \"B\" \"A\" \"A_2\"] Finally, [[unique-name-generator]] accepts the following options to further customize behavior: ### `:name-key-fn` Generated aliases are unique by the value of `[id (name-key-fn original-name)]`; the default is `identity`, so by default aliases are unique by `[id name-key-fn]`. Specify something custom here if you want to make the unique aliases unique by some other value, for example to make them unique without regards to case: (let [f (unique-name-generator :name-key-fn str/lower-case)] [(f \"x\") (f \"X\") (f \"X\")]) - > [ \"x\ " \"X_2\ " \"X_3\ " ] This is useful for databases that treat column aliases as case-insensitive (see #19618 for some examples of this). ### `:unique-alias-fn` The function used to generate a potentially-unique alias given an original alias and unique suffix with the signature (unique-alias-fn original suffix) By default, combines them like `original_suffix`, but you can supply a custom function if you need to change this behavior: (let [f (unique-name-generator :unique-alias-fn (fn [x y] (format \"%s~~%s\" y x)))] [(f \"x\") (f \"x\")]) - > [ \"x\ " \"2~~x\ " ] This is useful if you need to constrain the generated suffix in some way, for example by limiting its length or escaping characters disallowed in a column alias. Values generated by this function are recursively checked for uniqueness, and will keep trying values a unique value is generated; for this reason the function *must* return a unique value for every unique input. Use caution when limiting the length of the identifier generated (consider appending a hash in cases like these)." [& {:keys [name-key-fn unique-alias-fn] :or {name-key-fn identity unique-alias-fn (fn [original suffix] (str original \_ suffix))}}] (let [id+original->unique (atom {}) ; map of [id original-alias] -> unique-alias original->count (atom {})] ; map of original-alias -> count (fn generate-name ([alias] (generate-name (gensym) alias)) ([id original] (let [name-key (name-key-fn original)] (or ;; if we already have generated an alias for this key (e.g. `[id original]`), return it as-is. (@id+original->unique [id name-key]) ;; otherwise generate a new unique alias. see if we 're the first to try to use this candidate alias . Update the usage count in ` original->count ` (let [total-count (get (swap! original->count update name-key (fnil inc 0)) name-key)] (if (= total-count 1) if we are the first to do it , record it in ` id+original->unique ` and return it . (do (swap! id+original->unique assoc [id name-key] original) original) ;; otherwise prefix the alias by the current total count (e.g. `id` becomes `id_2`) and recur. If `id_2` is unused , it will get returned . Otherwise we 'll recursively try ` id_2_2 ` , and so forth . (let [candidate (unique-alias-fn original (str total-count))] ;; double-check that `unique-alias-fn` isn't doing something silly like truncating the generated alias ;; to aggressively or forgetting to include the `suffix` -- otherwise we could end up with an infinite ;; loop (assert (not= candidate original) (str "unique-alias-fn must return a different string than its input. Input: " (pr-str candidate))) (recur id candidate)))))))))) (s/defn uniquify-names :- (s/constrained [s/Str] distinct? "sequence of unique strings") "Make the names in a sequence of string names unique by adding suffixes such as `_2`. (uniquify-names [\"count\" \"sum\" \"count\" \"count_2\"]) ;; -> [\"count\" \"sum\" \"count_2\" \"count_2_2\"]" [names :- [s/Str]] (map (unique-name-generator) names)) (def ^:private NamedAggregation (s/constrained mbql.s/aggregation-options #(:name (nth % 2)) "`:aggregation-options` with a `:name`")) (def ^:private UniquelyNamedAggregations (s/constrained [NamedAggregation] (fn [clauses] (apply distinct? (for [[_ _ {ag-name :name}] clauses] ag-name))) "sequence of named aggregations with unique names")) (s/defn uniquify-named-aggregations :- UniquelyNamedAggregations "Make the names of a sequence of named aggregations unique by adding suffixes such as `_2`." [named-aggregations :- [NamedAggregation]] (let [unique-names (uniquify-names (for [[_ _wrapped-ag {ag-name :name}] named-aggregations] ag-name))] (map (fn [[_ wrapped-ag options] unique-name] [:aggregation-options wrapped-ag (assoc options :name unique-name)]) named-aggregations unique-names))) (s/defn pre-alias-aggregations :- [NamedAggregation] "Wrap every aggregation clause in an `:aggregation-options` clause, using the name returned by `(aggregation->name-fn ag-clause)` as names for any clauses that do not already have a `:name` in `:aggregation-options`. (pre-alias-aggregations annotate/aggregation-name [[:count] [:count] [:aggregation-options [:sum [:field 1 nil] {:name \"Sum-41\"}]]) ;; -> [[:aggregation-options [:count] {:name \"count\"}] [:aggregation-options [:count] {:name \"count\"}] [:aggregation-options [:sum [:field 1 nil]] {:name \"Sum-41\"}]] Most often, `aggregation->name-fn` will be something like `annotate/aggregation-name`, but for purposes of keeping the `metabase.mbql` module seperate from the `metabase.query-processor` code we'll let you pass that in yourself." {:style/indent 1} [aggregation->name-fn :- (s/pred fn?), aggregations :- [mbql.s/Aggregation]] (mbql.match/replace aggregations [:aggregation-options _ (_ :guard :name)] &match [:aggregation-options wrapped-ag options] [:aggregation-options wrapped-ag (assoc options :name (aggregation->name-fn wrapped-ag))] [(_ :guard keyword?) & _] [:aggregation-options &match {:name (aggregation->name-fn &match)}])) (s/defn pre-alias-and-uniquify-aggregations :- UniquelyNamedAggregations "Wrap every aggregation clause in a `:named` clause with a unique name. Combines `pre-alias-aggregations` with `uniquify-named-aggregations`." {:style/indent 1} [aggregation->name-fn :- (s/pred fn?), aggregations :- [mbql.s/Aggregation]] (-> (pre-alias-aggregations aggregation->name-fn aggregations) uniquify-named-aggregations)) (defn query->max-rows-limit "Calculate the absolute maximum number of results that should be returned by this query (MBQL or native), useful for doing the equivalent of java.sql.Statement statement = ...; statement.setMaxRows(<max-rows-limit>). to ensure the DB cursor or equivalent doesn't fetch more rows than will be consumed. This is calculated as follows: * If query is `MBQL` and has a `:limit` or `:page` clause, returns appropriate number * If query has `:constraints` with `:max-results-bare-rows` or `:max-results`, returns the appropriate number * `:max-results-bare-rows` is returned if set and Query does not have any aggregations * `:max-results` is returned otherwise * If none of the above are set, returns `nil`. In this case, you should use something like the Metabase QP's `max-rows-limit`" [{{:keys [max-results max-results-bare-rows]} :constraints {limit :limit, aggregations :aggregation, {:keys [items]} :page} :query query-type :type}] (let [safe-min (fn [& args] (when-let [args (seq (filter some? args))] (reduce min args))) mbql-limit (when (= query-type :query) (safe-min items limit)) constraints-limit (or (when-not aggregations max-results-bare-rows) max-results)] (safe-min mbql-limit constraints-limit))) (defn- remove-empty [x] (cond (map? x) (not-empty (into {} (for [[k v] x :let [v (remove-empty v)] :when (some? v)] [k v]))) (sequential? x) (not-empty (into (empty x) (filter some? (map remove-empty x)))) :else x)) (s/defn update-field-options :- mbql.s/FieldOrAggregationReference "Like [[clojure.core/update]], but for the options in a `:field`, `:expression`, or `:aggregation` clause." {:arglists '([field-or-ag-ref-or-expression-ref f & args])} [[clause-type id-or-name opts] :- mbql.s/FieldOrAggregationReference f & args] (let [opts (not-empty (remove-empty (apply f opts args)))] ;; `:field` clauses should have a `nil` options map if there are no options. `:aggregation` and `:expression` ;; should get the arg removed if it's `nil` or empty. (For now. In the future we may change this if we make the 3 - arg versions the " official " normalized versions . ) (cond opts [clause-type id-or-name opts] (= clause-type :field) [clause-type id-or-name nil] :else [clause-type id-or-name]))) (defn assoc-field-options "Like [[clojure.core/assoc]], but for the options in a `:field`, `:expression`, or `:aggregation` clause." [clause & kvs] (apply update-field-options clause assoc kvs)) (defn with-temporal-unit "Set the `:temporal-unit` of a `:field` clause to `unit`." [[_ _ {:keys [base-type]} :as clause] unit] ;; it doesn't make sense to call this on an `:expression` or `:aggregation`. (assert (is-clause? :field clause)) (if (or (not base-type) (mbql.s/valid-temporal-unit-for-base-type? base-type unit)) (assoc-field-options clause :temporal-unit unit) #_{:clj-kondo/ignore [:redundant-do]} ; The linter detects that this is redundant in CLJS and warns for it. (do #?(:clj (log/warn (metabase.util.i18n/trs "{0} is not a valid temporal unit for {1}; not adding to clause {2}" unit base-type (pr-str clause)))) clause))) (defn remove-namespaced-options "Update a `:field`, `:expression` reference, or `:aggregation` reference clause by removing all namespaced keys in the options map. This is mainly for clause equality comparison purposes -- in current usage namespaced keys are used by individual pieces of middleware or driver implementations for tracking little bits of information that should not be considered relevant when comparing clauses for equality." [field-or-ref] (update-field-options field-or-ref (partial into {} (remove (fn [[k _]] (when (keyword? k) (namespace k))))))) #?(:clj (p/import-vars [mbql.match match match-one replace replace-in]))
null
https://raw.githubusercontent.com/metabase/metabase/9ac7f26ed92ea0dff3474c0f887040549d2d85ad/shared/src/metabase/mbql/util.cljc
clojure
-> true -> true" +----------------------------------------------------------------------------------------------------------------+ | Functions for manipulating queries | +----------------------------------------------------------------------------------------------------------------+ if this an an empty filter, toss it for `and` and `not` compound filters with subclauses of the same type pull up any compounds of the same type e.g. [:and :a [:and b c]] ; -> [:and a b c] for `and` or `or` clauses with duplicate args, remove the duplicates and recur for `not` that wraps another `not`, eliminate both replace current/last/next with corresponding value of n and recur default get-week mode is iso handles nested queries as well. If `query` is for native queries, there's no source table to resolve for MBQL queries with a *native* source query, it's the same story for MBQL queries with an MBQL source query, recurse on the source query and try again if ID is a `card__id` form that can only mean we haven't preprocessed the query and resolved the source query. This is almost certainly an accident, so throw an Exception so we can make the proper fixes otherwise resolve the source Table otherwise add new clause at the end otherwise dispatches off `x`'s class." look for either string or keyword version of `expression-name` in `expressions` otherwise, if we have a source query recursively look in that (do we allow that??) failing that throw an Exception with detailed info about what we tried and what the actual expressions were pass in this keep recursing deeper into the query until we get to the same level the aggregation reference was defined at --------------------------------- Unique names & transforming ags to have names ---------------------------------- -> [\"A\" \"B\" \"A_2\"] -> [\"A\" \"B\" \"A\" \"A_2\"] the default is `identity`, so by for this reason the function *must* return a unique value for every unique input. Use caution when map of [id original-alias] -> unique-alias map of original-alias -> count if we already have generated an alias for this key (e.g. `[id original]`), return it as-is. otherwise generate a new unique alias. otherwise prefix the alias by the current total count (e.g. `id` becomes `id_2`) and recur. If `id_2` double-check that `unique-alias-fn` isn't doing something silly like truncating the generated alias to aggressively or forgetting to include the `suffix` -- otherwise we could end up with an infinite loop -> [\"count\" \"sum\" \"count_2\" \"count_2_2\"]" -> [[:aggregation-options [:count] {:name \"count\"}] `:field` clauses should have a `nil` options map if there are no options. `:aggregation` and `:expression` should get the arg removed if it's `nil` or empty. (For now. In the future we may change this if we make the it doesn't make sense to call this on an `:expression` or `:aggregation`. The linter detects that this is redundant in CLJS and warns for it.
(ns metabase.mbql.util "Utilitiy functions for working with MBQL queries." (:refer-clojure :exclude [replace]) #?@ (:clj [(:require [clojure.string :as str] [metabase.mbql.predicates :as mbql.preds] [metabase.mbql.schema :as mbql.s] [metabase.mbql.schema.helpers :as schema.helpers] [metabase.mbql.util.match :as mbql.match] [metabase.models.dispatch :as models.dispatch] [metabase.shared.util.i18n :as i18n] [metabase.util.i18n] [metabase.util.log :as log] [potemkin :as p] [schema.core :as s])] :cljs [(:require [clojure.string :as str] [metabase.mbql.predicates :as mbql.preds] [metabase.mbql.schema :as mbql.s] [metabase.mbql.schema.helpers :as schema.helpers] [metabase.mbql.util.match :as mbql.match] [metabase.shared.util.i18n :as i18n] [schema.core :as s])])) (defn qualified-name "Like `name`, but if `x` is a namespace-qualified keyword, returns that a string including the namespace." [x] (if (and (keyword? x) (namespace x)) (str (namespace x) "/" (name x)) (name x))) (s/defn normalize-token :- s/Keyword "Convert a string or keyword in various cases (`lisp-case`, `snake_case`, or `SCREAMING_SNAKE_CASE`) to a lisp-cased keyword." [token :- schema.helpers/KeywordOrString] #_{:clj-kondo/ignore [:discouraged-var]} (-> (qualified-name token) str/lower-case (str/replace #"_" "-") keyword)) (defn mbql-clause? "True if `x` is an MBQL clause (a sequence with a keyword as its first arg). (Since this is used by the code in `normalize` this handles pre-normalized clauses as well.)" [x] (and (sequential? x) (not (map-entry? x)) (keyword? (first x)))) (defn is-clause? "If `x` an MBQL clause, and an instance of clauses defined by keyword(s) `k-or-ks`? [k-or-ks x] (and (mbql-clause? x) (if (coll? k-or-ks) ((set k-or-ks) (first x)) (= k-or-ks (first x))))) (defn- combine-compound-filters-of-type [compound-type subclauses] (mapcat #(mbql.match/match-one % [(_ :guard (partial = compound-type)) & args] args _ [&match]) subclauses)) (defn simplify-compound-filter "Simplify compound `:and`, `:or`, and `:not` compound filters, combining or eliminating them where possible. This also fixes theoretically disallowed compound filters like `:and` with only a single subclause, and eliminates `nils` and duplicate subclauses from the clauses." [filter-clause] (mbql.match/replace filter-clause seq? (recur (vec &match)) nil nil [& (_ :guard (partial every? nil?))] nil [] nil [(:or :and :or)] nil if the COMPOUND clause contains any nils , toss them [(clause-name :guard #{:and :or}) & (args :guard (partial some nil?))] (recur (apply vector clause-name (filterv some? args))) Rewrite a ` : not ` over ` : and ` using de Morgan 's law [:not [:and & args]] (recur (apply vector :or (map #(vector :not %) args))) Rewrite a ` : not ` over ` : or ` using de Morgan 's law [:not [:or & args]] (recur (apply vector :and (map #(vector :not %) args))) for ` and ` or ` not ` compound filters with only one subclase , just unnest the subclause [(:or :and :or) arg] (recur arg) [:and & (args :guard (partial some (partial is-clause? :and)))] (recur (apply vector :and (combine-compound-filters-of-type :and args))) [:or & (args :guard (partial some (partial is-clause? :or)))] (recur (apply vector :or (combine-compound-filters-of-type :or args))) [(clause :guard #{:and :or}) & (args :guard #(not (apply distinct? %)))] (recur (apply vector clause (distinct args))) [:not [:not arg]] (recur arg) :else filter-clause)) (s/defn combine-filter-clauses :- mbql.s/Filter "Combine two filter clauses into a single clause in a way that minimizes slapping a bunch of `:and`s together if possible." [filter-clause & more-filter-clauses] (simplify-compound-filter (cons :and (cons filter-clause more-filter-clauses)))) (s/defn add-filter-clause-to-inner-query :- mbql.s/MBQLQuery "Add a additional filter clause to an *inner* MBQL query, merging with the existing filter clause with `:and` if needed." [inner-query :- mbql.s/MBQLQuery new-clause :- (s/maybe mbql.s/Filter)] (if-not new-clause inner-query (update inner-query :filter combine-filter-clauses new-clause))) (s/defn add-filter-clause :- mbql.s/Query "Add an additional filter clause to an `outer-query`. If `new-clause` is `nil` this is a no-op." [outer-query :- mbql.s/Query new-clause :- (s/maybe mbql.s/Filter)] (update outer-query :query add-filter-clause-to-inner-query new-clause)) (defn desugar-inside "Rewrite `:inside` filter clauses as a pair of `:between` clauses." [m] (mbql.match/replace m [:inside lat-field lon-field lat-max lon-min lat-min lon-max] [:and [:between lat-field lat-min lat-max] [:between lon-field lon-min lon-max]])) (defn desugar-is-null-and-not-null "Rewrite `:is-null` and `:not-null` filter clauses as simpler `:=` and `:!=`, respectively." [m] (mbql.match/replace m [:is-null field] [:= field nil] [:not-null field] [:!= field nil])) (defn desugar-is-empty-and-not-empty "Rewrite `:is-empty` and `:not-empty` filter clauses as simpler `:=` and `:!=`, respectively." [m] (mbql.match/replace m [:is-empty field] [:or [:= field nil] [:= field ""]] [:not-empty field] [:and [:!= field nil] [:!= field ""]])) (defn- replace-field-or-expression "Replace a field or expression inside :time-interval" [m unit] (mbql.match/replace m [:field id-or-name opts] [:field id-or-name (assoc opts :temporal-unit unit)] [:expression expression-name] [:expression expression-name])) (defn desugar-time-interval "Rewrite `:time-interval` filter clauses as simpler ones like `:=` or `:between`." [m] (mbql.match/replace m [:time-interval field-or-expression n unit] (recur [:time-interval field-or-expression n unit nil]) [:time-interval field-or-expression :current unit options] (recur [:time-interval field-or-expression 0 unit options]) [:time-interval field-or-expression :last unit options] (recur [:time-interval field-or-expression -1 unit options]) [:time-interval field-or-expression :next unit options] (recur [:time-interval field-or-expression 1 unit options]) [:time-interval field-or-expression (n :guard #{-1}) unit (_ :guard :include-current)] [:between (replace-field-or-expression field-or-expression unit) [:relative-datetime n unit] [:relative-datetime 0 unit]] [:time-interval field-or-expression (n :guard #{1}) unit (_ :guard :include-current)] [:between (replace-field-or-expression field-or-expression unit) [:relative-datetime 0 unit] [:relative-datetime n unit]] [:time-interval field-or-expression (n :guard #{-1 0 1}) unit _] [:= (replace-field-or-expression field-or-expression unit) [:relative-datetime n unit]] [:time-interval field-or-expression (n :guard neg?) unit (_ :guard :include-current)] [:between (replace-field-or-expression field-or-expression unit) [:relative-datetime n unit] [:relative-datetime 0 unit]] [:time-interval field-or-expression (n :guard neg?) unit _] [:between (replace-field-or-expression field-or-expression unit) [:relative-datetime n unit] [:relative-datetime -1 unit]] [:time-interval field-or-expression n unit (_ :guard :include-current)] [:between (replace-field-or-expression field-or-expression unit) [:relative-datetime 0 unit] [:relative-datetime n unit]] [:time-interval field-or-expression n unit _] [:between (replace-field-or-expression field-or-expression unit) [:relative-datetime 1 unit] [:relative-datetime n unit]])) (defn desugar-does-not-contain "Rewrite `:does-not-contain` filter clauses as simpler `:not` clauses." [m] (mbql.match/replace m [:does-not-contain & args] [:not (into [:contains] args)])) (defn desugar-equals-and-not-equals-with-extra-args "`:=` and `!=` clauses with more than 2 args automatically get rewritten as compound filters. [:= field x y] -> [:or [:= field x] [:= field y]] [:!= field x y] -> [:and [:!= field x] [:!= field y]]" [m] (mbql.match/replace m [:= field x y & more] (apply vector :or (for [x (concat [x y] more)] [:= field x])) [:!= field x y & more] (apply vector :and (for [x (concat [x y] more)] [:!= field x])))) (defn desugar-current-relative-datetime "Replace `relative-datetime` clauses like `[:relative-datetime :current]` with `[:relative-datetime 0 <unit>]`. `<unit>` is inferred from the `:field` the clause is being compared to (if any), otherwise falls back to `default.`" [m] (mbql.match/replace m [clause field & (args :guard (partial some (partial = [:relative-datetime :current])))] (let [temporal-unit (or (mbql.match/match-one field [:field _ {:temporal-unit temporal-unit}] temporal-unit) :default)] (into [clause field] (mbql.match/replace args [:relative-datetime :current] [:relative-datetime 0 temporal-unit]))))) (def temporal-extract-ops->unit "Mapping from the sugar syntax to extract datetime to the unit." {[:get-year nil] :year-of-era [:get-quarter nil] :quarter-of-year [:get-month nil] :month-of-year [:get-week nil] :week-of-year-iso [:get-week :iso] :week-of-year-iso [:get-week :us] :week-of-year-us [:get-week :instance] :week-of-year-instance [:get-day nil] :day-of-month [:get-day-of-week nil] :day-of-week [:get-hour nil] :hour-of-day [:get-minute nil] :minute-of-hour [:get-second nil] :second-of-minute}) (def ^:private temporal-extract-ops (->> (keys temporal-extract-ops->unit) (map first) set)) (defn desugar-temporal-extract "Replace datetime extractions clauses like `[:get-year field]` with `[:temporal-extract field :year]`." [m] (mbql.match/replace m [(op :guard temporal-extract-ops) field & args] [:temporal-extract field (temporal-extract-ops->unit [op (first args)])])) (defn- desugar-divide-with-extra-args [expression] (mbql.match/replace expression [:/ x y z & more] (recur (into [:/ [:/ x y]] (cons z more))))) (s/defn desugar-expression :- mbql.s/FieldOrExpressionDef "Rewrite various 'syntactic sugar' expressions like `:/` with more than two args into something simpler for drivers to compile." [expression :- mbql.s/FieldOrExpressionDef] (-> expression desugar-divide-with-extra-args)) (defn- maybe-desugar-expression [clause] (cond-> clause (mbql.preds/FieldOrExpressionDef? clause) desugar-expression)) (s/defn desugar-filter-clause :- mbql.s/Filter "Rewrite various 'syntatic sugar' filter clauses like `:time-interval` and `:inside` as simpler, logically equivalent clauses. This can be used to simplify the number of filter clauses that need to be supported by anything that needs to enumerate all the possible filter types (such as driver query processor implementations, or the implementation `negate-filter-clause` below.)" [filter-clause :- mbql.s/Filter] (-> filter-clause desugar-current-relative-datetime desugar-equals-and-not-equals-with-extra-args desugar-does-not-contain desugar-time-interval desugar-is-null-and-not-null desugar-is-empty-and-not-empty desugar-inside simplify-compound-filter desugar-temporal-extract maybe-desugar-expression)) (defmulti ^:private negate* first) (defmethod negate* :not [[_ subclause]] subclause) (defmethod negate* :and [[_ & subclauses]] (into [:or] (map negate* subclauses))) (defmethod negate* :or [[_ & subclauses]] (into [:and] (map negate* subclauses))) (defmethod negate* := [[_ field value]] [:!= field value]) (defmethod negate* :!= [[_ field value]] [:= field value]) (defmethod negate* :> [[_ field value]] [:<= field value]) (defmethod negate* :< [[_ field value]] [:>= field value]) (defmethod negate* :>= [[_ field value]] [:< field value]) (defmethod negate* :<= [[_ field value]] [:> field value]) (defmethod negate* :between [[_ field min max]] [:or [:< field min] [:> field max]]) (defmethod negate* :contains [clause] [:not clause]) (defmethod negate* :starts-with [clause] [:not clause]) (defmethod negate* :ends-with [clause] [:not clause]) (s/defn negate-filter-clause :- mbql.s/Filter "Return the logical compliment of an MBQL filter clause, generally without using `:not` (except for the string filter clause types). Useful for generating highly optimized filter clauses and for drivers that do not support top-level `:not` filter clauses." [filter-clause :- mbql.s/Filter] (-> filter-clause desugar-filter-clause negate* simplify-compound-filter)) (s/defn query->source-table-id :- (s/maybe schema.helpers/IntGreaterThanZero) `nil`, returns `nil`. Throws an Exception when it encounters a unresolved source query (i.e., the `:source-table \"card__id\"` form), because it cannot return an accurate result for a query that has not yet been preprocessed." {:arglists '([outer-query])} [{{source-table-id :source-table, source-query :source-query} :query, query-type :type, :as query}] (cond (not= query-type :query) nil (and (nil? source-table-id) source-query (:native source-query)) nil (and (nil? source-table-id) source-query) (recur (assoc query :query source-query)) ((every-pred string? (partial re-matches mbql.s/source-table-card-id-regex)) source-table-id) (throw (ex-info (i18n/tru "Error: query''s source query has not been resolved. You probably need to `preprocess` the query first.") {})) :else source-table-id)) (s/defn join->source-table-id :- (s/maybe schema.helpers/IntGreaterThanZero) "Like `query->source-table-id`, but for a join." [join] (query->source-table-id {:type :query, :query join})) (s/defn add-order-by-clause :- mbql.s/MBQLQuery "Add a new `:order-by` clause to an MBQL `inner-query`. If the new order-by clause references a Field that is already being used in another order-by clause, this function does nothing." [inner-query :- mbql.s/MBQLQuery, [_ [_ id-or-name :as _field], :as order-by-clause] :- mbql.s/OrderBy] (let [existing-fields (set (for [[_ [_ id-or-name]] (:order-by inner-query)] id-or-name))] (if (existing-fields id-or-name) Field already referenced , nothing to do inner-query (update inner-query :order-by (comp vec distinct conj) order-by-clause)))) (defn dispatch-by-clause-name-or-class "Dispatch function perfect for use with multimethods that dispatch off elements of an MBQL query. If `x` is an MBQL ([x] #?(:clj (if (mbql-clause? x) (first x) (or (metabase.models.dispatch/model x) (type x))) :cljs (if (mbql-clause? x) (first x) (type x)))) ([x _] (dispatch-by-clause-name-or-class x))) (s/defn expression-with-name :- mbql.s/FieldOrExpressionDef "Return the `Expression` referenced by a given `expression-name`." [inner-query expression-name :- (s/cond-pre s/Keyword schema.helpers/NonBlankString)] (let [allowed-names [(qualified-name expression-name) (keyword expression-name)]] (loop [{:keys [expressions source-query]} inner-query, found #{}] (or (some (partial get expressions) allowed-names) (let [found (into found (keys expressions))] (if source-query (recur source-query found) (throw (ex-info (i18n/tru "No expression named ''{0}''" (qualified-name expression-name)) {:type :invalid-query :expression-name expression-name :tried allowed-names :found found})))))))) (s/defn aggregation-at-index :- mbql.s/Aggregation "Fetch the aggregation at index. This is intended to power aggregate field references (e.g. [:aggregation 0]). This also handles nested queries, which could be potentially ambiguous if multiple levels had aggregations. To number to as optional arg `nesting-level` to make sure you reference aggregations at the right level of nesting." ([query index] (aggregation-at-index query index 0)) ([query :- mbql.s/Query index :- schema.helpers/IntGreaterThanOrEqualToZero nesting-level :- schema.helpers/IntGreaterThanOrEqualToZero] (if (zero? nesting-level) (or (nth (get-in query [:query :aggregation]) index) (throw (ex-info (i18n/tru "No aggregation at index: {0}" index) {:index index}))) (recur {:query (get-in query [:query :source-query])} index (dec nesting-level))))) (defn ga-id? "Is this ID (presumably of a Metric or Segment) a GA one?" [id] (boolean (when ((some-fn string? keyword?) id) (re-find #"^ga(id)?:" (name id))))) (defn ga-metric-or-segment? "Is this metric or segment clause not a Metabase Metric or Segment, but rather a GA one? E.g. something like `[:metric ga:users]`. We want to ignore those because they're not the same thing at all as MB Metrics/Segments and don't correspond to objects in our application DB." [[_ id]] (ga-id? id)) (defn temporal-field? "Is `field` used to record something date or time related, i.e. does `field` have a base type or semantic type that derives from `:type/Temporal`?" [field] (or (isa? (:base_type field) :type/Temporal) (isa? (:semantic_type field) :type/Temporal))) (defn time-field? "Is `field` used to record a time of day (e.g. hour/minute/second), but not the date itself? i.e. does `field` have a base type or semantic type that derives from `:type/Time`?" [field] (or (isa? (:base_type field) :type/Time) (isa? (:semantic_type field) :type/Time))) (defn temporal-but-not-time-field? "Does `field` have a base type or semantic type that derives from `:type/Temporal`, but not `:type/Time`? (i.e., is Field a Date or DateTime?)" [field] (and (temporal-field? field) (not (time-field? field)))) (defn unique-name-generator "Return a function that can be used to uniquify string names. Function maintains an internal counter that will suffix any names passed to it as needed so all results will be unique. (let [unique-name (unique-name-generator)] [(unique-name \"A\") (unique-name \"B\") (unique-name \"A\")]) By default, unique aliases are generated for each unique `[id original-name]` key pair. By default, a unique `id` is generated for every call, meaning repeated calls to [[unique-name-generator]] with the same `original-name` will return different unique aliases. If idempotence is desired, the function returned by the generator also has a 2 airity version with the signature (unique-name-fn id original-name) for example: (let [unique-name (unique-name-generator)] [(unique-name :x \"A\") (unique-name :x \"B\") (unique-name :x \"A\") (unique-name :y \"A\")]) Finally, [[unique-name-generator]] accepts the following options to further customize behavior: ### `:name-key-fn` default aliases are unique by `[id name-key-fn]`. Specify something custom here if you want to make the unique aliases unique by some other value, for example to make them unique without regards to case: (let [f (unique-name-generator :name-key-fn str/lower-case)] [(f \"x\") (f \"X\") (f \"X\")]) - > [ \"x\ " \"X_2\ " \"X_3\ " ] This is useful for databases that treat column aliases as case-insensitive (see #19618 for some examples of this). ### `:unique-alias-fn` The function used to generate a potentially-unique alias given an original alias and unique suffix with the signature (unique-alias-fn original suffix) By default, combines them like `original_suffix`, but you can supply a custom function if you need to change this behavior: (let [f (unique-name-generator :unique-alias-fn (fn [x y] (format \"%s~~%s\" y x)))] [(f \"x\") (f \"x\")]) - > [ \"x\ " \"2~~x\ " ] This is useful if you need to constrain the generated suffix in some way, for example by limiting its length or escaping characters disallowed in a column alias. Values generated by this function are recursively checked for uniqueness, and will keep trying values a unique value limiting the length of the identifier generated (consider appending a hash in cases like these)." [& {:keys [name-key-fn unique-alias-fn] :or {name-key-fn identity unique-alias-fn (fn [original suffix] (str original \_ suffix))}}] (fn generate-name ([alias] (generate-name (gensym) alias)) ([id original] (let [name-key (name-key-fn original)] (or (@id+original->unique [id name-key]) see if we 're the first to try to use this candidate alias . Update the usage count in ` original->count ` (let [total-count (get (swap! original->count update name-key (fnil inc 0)) name-key)] (if (= total-count 1) if we are the first to do it , record it in ` id+original->unique ` and return it . (do (swap! id+original->unique assoc [id name-key] original) original) is unused , it will get returned . Otherwise we 'll recursively try ` id_2_2 ` , and so forth . (let [candidate (unique-alias-fn original (str total-count))] (assert (not= candidate original) (str "unique-alias-fn must return a different string than its input. Input: " (pr-str candidate))) (recur id candidate)))))))))) (s/defn uniquify-names :- (s/constrained [s/Str] distinct? "sequence of unique strings") "Make the names in a sequence of string names unique by adding suffixes such as `_2`. (uniquify-names [\"count\" \"sum\" \"count\" \"count_2\"]) [names :- [s/Str]] (map (unique-name-generator) names)) (def ^:private NamedAggregation (s/constrained mbql.s/aggregation-options #(:name (nth % 2)) "`:aggregation-options` with a `:name`")) (def ^:private UniquelyNamedAggregations (s/constrained [NamedAggregation] (fn [clauses] (apply distinct? (for [[_ _ {ag-name :name}] clauses] ag-name))) "sequence of named aggregations with unique names")) (s/defn uniquify-named-aggregations :- UniquelyNamedAggregations "Make the names of a sequence of named aggregations unique by adding suffixes such as `_2`." [named-aggregations :- [NamedAggregation]] (let [unique-names (uniquify-names (for [[_ _wrapped-ag {ag-name :name}] named-aggregations] ag-name))] (map (fn [[_ wrapped-ag options] unique-name] [:aggregation-options wrapped-ag (assoc options :name unique-name)]) named-aggregations unique-names))) (s/defn pre-alias-aggregations :- [NamedAggregation] "Wrap every aggregation clause in an `:aggregation-options` clause, using the name returned by `(aggregation->name-fn ag-clause)` as names for any clauses that do not already have a `:name` in `:aggregation-options`. (pre-alias-aggregations annotate/aggregation-name [[:count] [:count] [:aggregation-options [:sum [:field 1 nil] {:name \"Sum-41\"}]]) [:aggregation-options [:count] {:name \"count\"}] [:aggregation-options [:sum [:field 1 nil]] {:name \"Sum-41\"}]] Most often, `aggregation->name-fn` will be something like `annotate/aggregation-name`, but for purposes of keeping the `metabase.mbql` module seperate from the `metabase.query-processor` code we'll let you pass that in yourself." {:style/indent 1} [aggregation->name-fn :- (s/pred fn?), aggregations :- [mbql.s/Aggregation]] (mbql.match/replace aggregations [:aggregation-options _ (_ :guard :name)] &match [:aggregation-options wrapped-ag options] [:aggregation-options wrapped-ag (assoc options :name (aggregation->name-fn wrapped-ag))] [(_ :guard keyword?) & _] [:aggregation-options &match {:name (aggregation->name-fn &match)}])) (s/defn pre-alias-and-uniquify-aggregations :- UniquelyNamedAggregations "Wrap every aggregation clause in a `:named` clause with a unique name. Combines `pre-alias-aggregations` with `uniquify-named-aggregations`." {:style/indent 1} [aggregation->name-fn :- (s/pred fn?), aggregations :- [mbql.s/Aggregation]] (-> (pre-alias-aggregations aggregation->name-fn aggregations) uniquify-named-aggregations)) (defn query->max-rows-limit "Calculate the absolute maximum number of results that should be returned by this query (MBQL or native), useful for doing the equivalent of statement.setMaxRows(<max-rows-limit>). to ensure the DB cursor or equivalent doesn't fetch more rows than will be consumed. This is calculated as follows: * If query is `MBQL` and has a `:limit` or `:page` clause, returns appropriate number * If query has `:constraints` with `:max-results-bare-rows` or `:max-results`, returns the appropriate number * `:max-results-bare-rows` is returned if set and Query does not have any aggregations * `:max-results` is returned otherwise * If none of the above are set, returns `nil`. In this case, you should use something like the Metabase QP's `max-rows-limit`" [{{:keys [max-results max-results-bare-rows]} :constraints {limit :limit, aggregations :aggregation, {:keys [items]} :page} :query query-type :type}] (let [safe-min (fn [& args] (when-let [args (seq (filter some? args))] (reduce min args))) mbql-limit (when (= query-type :query) (safe-min items limit)) constraints-limit (or (when-not aggregations max-results-bare-rows) max-results)] (safe-min mbql-limit constraints-limit))) (defn- remove-empty [x] (cond (map? x) (not-empty (into {} (for [[k v] x :let [v (remove-empty v)] :when (some? v)] [k v]))) (sequential? x) (not-empty (into (empty x) (filter some? (map remove-empty x)))) :else x)) (s/defn update-field-options :- mbql.s/FieldOrAggregationReference "Like [[clojure.core/update]], but for the options in a `:field`, `:expression`, or `:aggregation` clause." {:arglists '([field-or-ag-ref-or-expression-ref f & args])} [[clause-type id-or-name opts] :- mbql.s/FieldOrAggregationReference f & args] (let [opts (not-empty (remove-empty (apply f opts args)))] 3 - arg versions the " official " normalized versions . ) (cond opts [clause-type id-or-name opts] (= clause-type :field) [clause-type id-or-name nil] :else [clause-type id-or-name]))) (defn assoc-field-options "Like [[clojure.core/assoc]], but for the options in a `:field`, `:expression`, or `:aggregation` clause." [clause & kvs] (apply update-field-options clause assoc kvs)) (defn with-temporal-unit "Set the `:temporal-unit` of a `:field` clause to `unit`." [[_ _ {:keys [base-type]} :as clause] unit] (assert (is-clause? :field clause)) (if (or (not base-type) (mbql.s/valid-temporal-unit-for-base-type? base-type unit)) (assoc-field-options clause :temporal-unit unit) (do #?(:clj (log/warn (metabase.util.i18n/trs "{0} is not a valid temporal unit for {1}; not adding to clause {2}" unit base-type (pr-str clause)))) clause))) (defn remove-namespaced-options "Update a `:field`, `:expression` reference, or `:aggregation` reference clause by removing all namespaced keys in the options map. This is mainly for clause equality comparison purposes -- in current usage namespaced keys are used by individual pieces of middleware or driver implementations for tracking little bits of information that should not be considered relevant when comparing clauses for equality." [field-or-ref] (update-field-options field-or-ref (partial into {} (remove (fn [[k _]] (when (keyword? k) (namespace k))))))) #?(:clj (p/import-vars [mbql.match match match-one replace replace-in]))
80262035cbe1695cad7c00893184c08c3786df61a4c08915ea401ed45be4f555
iconnect/api-tools
JSON.hs
{-# LANGUAGE BangPatterns #-} module Data.Binary.Serialise.CBOR.JSON ( cborToJson, jsonToCbor, encodeJSON, decodeJSON, ) where import Data.API.JSON.Compat import qualified Data.Aeson as JSON import qualified Data.Scientific as Scientific import qualified Data.Vector as Vec import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import qualified Data.Text.Lazy as Text.Lazy import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Base64 as Base64 import qualified Data . ByteString . Base64.URL as Base64url import qualified Data.ByteString.Base16 as Base16 import Codec.Serialise.Decoding import Codec.Serialise.Encoding import Codec.CBOR.Term as CBOR import Codec.Serialise import Control.Applicative import Prelude instance Serialise JSON.Value where encode = encodeJSON decode = decodeJSON encodeJSON :: JSON.Value -> Encoding encodeJSON = encode . jsonToCbor decodeJSON :: Decoder s JSON.Value decodeJSON = cborToJson <$> decode -- Most of the types in CBOR have direct analogs in JSON. However, some -- do not, and someone implementing a CBOR-to-JSON converter has to -- consider what to do in those cases. The following non-normative -- advice deals with these by converting them to a single substitute -- value, such as a JSON null. cborToJson :: CBOR.Term -> JSON.Value o An integer ( major type 0 or 1 ) becomes a JSON number . We modify this advice by only converting numbers in the range -2 ^ 53 .. 2 ^ 53 and otherwise handling them like big nums cborToJson (CBOR.TInt n) = cborToJson (CBOR.TInteger (fromIntegral n)) o A byte string ( major type 2 ) that is not embedded in a tag that -- specifies a proposed encoding is encoded in base64url without -- padding and becomes a JSON string. cborToJson (CBOR.TBytes bs) = JSON.String (base64url bs) cborToJson (CBOR.TBytesI bs) = JSON.String (base64url (LBS.toStrict bs)) o A UTF-8 string ( major type 3 ) becomes a JSON string . Note that JSON requires escaping certain characters ( RFC 4627 , Section 2.5 ): quotation mark ( U+0022 ) , reverse solidus ( U+005C ) , and the " C0 control characters " ( U+0000 through U+001F ) . All other characters -- are copied unchanged into the JSON UTF-8 string. cborToJson (CBOR.TString s) = JSON.String s -- aeson will escape correctly cborToJson (CBOR.TStringI s) = JSON.String (Text.Lazy.toStrict s) o An array ( major type 4 ) becomes a JSON array . cborToJson (TList vs) = JSON.Array (Vec.fromList (map cborToJson vs)) o A map ( major type 5 ) becomes a JSON object . This is possible directly only if all keys are UTF-8 strings . A converter might also convert other keys into UTF-8 strings ( such as by converting -- integers into strings containing their decimal representation); -- however, doing so introduces a danger of key collision. cborToJson (TMap kvs) = JSON.object [ (textToKey (cborToJsonString k), cborToJson v) | (k, v) <- kvs ] o False ( major type 7 , additional information 20 ) becomes a JSON false . o True ( major type 7 , additional information 21 ) becomes a JSON true . -- o Null ( major type 7 , additional information 22 ) becomes a JSON null . cborToJson (TBool b) = JSON.Bool b cborToJson TNull = JSON.Null o A floating - point value ( major type 7 , additional information 25 through 27 ) becomes a JSON number if it is finite ( that is , it can be represented in a JSON number ) ; if the value is non - finite ( NaN , or positive or negative Infinity ) , it is represented by the -- substitute value. cborToJson (THalf f) | isNaN f || isInfinite f = JSON.Null | otherwise = JSON.Number (Scientific.fromFloatDigits f) cborToJson (TFloat f) | isNaN f || isInfinite f = JSON.Null | otherwise = JSON.Number (Scientific.fromFloatDigits f) cborToJson (TDouble f) | isNaN f || isInfinite f = JSON.Null | otherwise = JSON.Number (Scientific.fromFloatDigits f) o Any other simple value ( major type 7 , any additional information -- value not yet discussed) is represented by the substitute value. cborToJson (TSimple _) = JSON.Null o A bignum ( major type 6 , tag value 2 or 3 ) is represented by -- encoding its byte string in base64url without padding and becomes a JSON string . For tag value 3 ( negative bignum ) , a " ~ " ( ASCII -- tilde) is inserted before the base-encoded value. (The conversion -- to a binary blob instead of a number is to prevent a likely -- numeric overflow for the JSON decoder.) NOTE We ignore this advice and just use ' JSON.Number ' . cborToJson (TInteger n) = JSON.Number (fromInteger n) o A byte string with an encoding hint ( major type 6 , tag value 21 through 23 ) is encoded as described and becomes a JSON string . cborToJson (TTagged 21 (CBOR.TBytes bs)) = JSON.String (base64url bs) cborToJson (TTagged 22 (CBOR.TBytes bs)) = JSON.String (base64 bs) cborToJson (TTagged 23 (CBOR.TBytes bs)) = JSON.String (base16 bs) o For all other tags ( major type 6 , any other tag value ) , the -- embedded CBOR item is represented as a JSON value; the tag value -- is ignored. cborToJson (TTagged _tag term) = cborToJson term -- o Indefinite-length items are made definite before conversion. cborToJson (TListI kvs) = cborToJson (TList kvs) cborToJson (TMapI kvs) = cborToJson (TMap kvs) -- used just for converting CBOR terms to JSON map keys -- TODO: partial cborToJsonString :: CBOR.Term -> Text.Text cborToJsonString (TInt n) = Text.pack (show n) cborToJsonString (TInteger n) = Text.pack (show n) cborToJsonString (TString s) = s cborToJsonString (TStringI s) = Text.Lazy.toStrict s cborToJsonString (TBytes bs) = base64url bs cborToJsonString (TBytesI bs) = base64url (LBS.toStrict bs) -- TODO not strictly following the spec - this uses padding, spec says -- we shouldn't TODO moreover , api - tools uses base64 rather than base64url ! base64url :: ByteString -> Text base64url = base64 -- Text.decodeLatin1 . Base64url.encode base64 :: ByteString -> Text base64 = Text.decodeLatin1 . Base64.encode base16 :: ByteString -> Text base16 = Text.decodeLatin1 . Base16.encode jsonToCbor :: JSON.Value -> CBOR.Term jsonToCbor (JSON.Object kvs) = CBOR.TMap [ (CBOR.TString k, jsonToCbor v) | (k, v) <- objectToList kvs ] jsonToCbor (JSON.Array vs) = CBOR.TList [ jsonToCbor v | v <- Vec.toList vs ] jsonToCbor (JSON.String str) = CBOR.TString str jsonToCbor (JSON.Number n) = case Scientific.floatingOrInteger n of Left d -> CBOR.TDouble d Right i | i >= fromIntegral (minBound :: Int) && i <= fromIntegral (maxBound :: Int) -> CBOR.TInt (fromIntegral i) | otherwise -> CBOR.TInteger i jsonToCbor (JSON.Bool b) = CBOR.TBool b jsonToCbor JSON.Null = CBOR.TNull
null
https://raw.githubusercontent.com/iconnect/api-tools/77a8cd4c11b6e1df078e57c8a0c48b8fef3e26e4/src/Data/Binary/Serialise/CBOR/JSON.hs
haskell
# LANGUAGE BangPatterns # Most of the types in CBOR have direct analogs in JSON. However, some do not, and someone implementing a CBOR-to-JSON converter has to consider what to do in those cases. The following non-normative advice deals with these by converting them to a single substitute value, such as a JSON null. specifies a proposed encoding is encoded in base64url without padding and becomes a JSON string. are copied unchanged into the JSON UTF-8 string. aeson will escape correctly integers into strings containing their decimal representation); however, doing so introduces a danger of key collision. substitute value. value not yet discussed) is represented by the substitute value. encoding its byte string in base64url without padding and becomes tilde) is inserted before the base-encoded value. (The conversion to a binary blob instead of a number is to prevent a likely numeric overflow for the JSON decoder.) embedded CBOR item is represented as a JSON value; the tag value is ignored. o Indefinite-length items are made definite before conversion. used just for converting CBOR terms to JSON map keys TODO: partial TODO not strictly following the spec - this uses padding, spec says we shouldn't Text.decodeLatin1 . Base64url.encode
module Data.Binary.Serialise.CBOR.JSON ( cborToJson, jsonToCbor, encodeJSON, decodeJSON, ) where import Data.API.JSON.Compat import qualified Data.Aeson as JSON import qualified Data.Scientific as Scientific import qualified Data.Vector as Vec import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import qualified Data.Text.Lazy as Text.Lazy import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Base64 as Base64 import qualified Data . ByteString . Base64.URL as Base64url import qualified Data.ByteString.Base16 as Base16 import Codec.Serialise.Decoding import Codec.Serialise.Encoding import Codec.CBOR.Term as CBOR import Codec.Serialise import Control.Applicative import Prelude instance Serialise JSON.Value where encode = encodeJSON decode = decodeJSON encodeJSON :: JSON.Value -> Encoding encodeJSON = encode . jsonToCbor decodeJSON :: Decoder s JSON.Value decodeJSON = cborToJson <$> decode cborToJson :: CBOR.Term -> JSON.Value o An integer ( major type 0 or 1 ) becomes a JSON number . We modify this advice by only converting numbers in the range -2 ^ 53 .. 2 ^ 53 and otherwise handling them like big nums cborToJson (CBOR.TInt n) = cborToJson (CBOR.TInteger (fromIntegral n)) o A byte string ( major type 2 ) that is not embedded in a tag that cborToJson (CBOR.TBytes bs) = JSON.String (base64url bs) cborToJson (CBOR.TBytesI bs) = JSON.String (base64url (LBS.toStrict bs)) o A UTF-8 string ( major type 3 ) becomes a JSON string . Note that JSON requires escaping certain characters ( RFC 4627 , Section 2.5 ): quotation mark ( U+0022 ) , reverse solidus ( U+005C ) , and the " C0 control characters " ( U+0000 through U+001F ) . All other characters cborToJson (CBOR.TStringI s) = JSON.String (Text.Lazy.toStrict s) o An array ( major type 4 ) becomes a JSON array . cborToJson (TList vs) = JSON.Array (Vec.fromList (map cborToJson vs)) o A map ( major type 5 ) becomes a JSON object . This is possible directly only if all keys are UTF-8 strings . A converter might also convert other keys into UTF-8 strings ( such as by converting cborToJson (TMap kvs) = JSON.object [ (textToKey (cborToJsonString k), cborToJson v) | (k, v) <- kvs ] o False ( major type 7 , additional information 20 ) becomes a JSON false . o True ( major type 7 , additional information 21 ) becomes a JSON true . o Null ( major type 7 , additional information 22 ) becomes a JSON null . cborToJson (TBool b) = JSON.Bool b cborToJson TNull = JSON.Null o A floating - point value ( major type 7 , additional information 25 through 27 ) becomes a JSON number if it is finite ( that is , it can be represented in a JSON number ) ; if the value is non - finite ( NaN , or positive or negative Infinity ) , it is represented by the cborToJson (THalf f) | isNaN f || isInfinite f = JSON.Null | otherwise = JSON.Number (Scientific.fromFloatDigits f) cborToJson (TFloat f) | isNaN f || isInfinite f = JSON.Null | otherwise = JSON.Number (Scientific.fromFloatDigits f) cborToJson (TDouble f) | isNaN f || isInfinite f = JSON.Null | otherwise = JSON.Number (Scientific.fromFloatDigits f) o Any other simple value ( major type 7 , any additional information cborToJson (TSimple _) = JSON.Null o A bignum ( major type 6 , tag value 2 or 3 ) is represented by a JSON string . For tag value 3 ( negative bignum ) , a " ~ " ( ASCII NOTE We ignore this advice and just use ' JSON.Number ' . cborToJson (TInteger n) = JSON.Number (fromInteger n) o A byte string with an encoding hint ( major type 6 , tag value 21 through 23 ) is encoded as described and becomes a JSON string . cborToJson (TTagged 21 (CBOR.TBytes bs)) = JSON.String (base64url bs) cborToJson (TTagged 22 (CBOR.TBytes bs)) = JSON.String (base64 bs) cborToJson (TTagged 23 (CBOR.TBytes bs)) = JSON.String (base16 bs) o For all other tags ( major type 6 , any other tag value ) , the cborToJson (TTagged _tag term) = cborToJson term cborToJson (TListI kvs) = cborToJson (TList kvs) cborToJson (TMapI kvs) = cborToJson (TMap kvs) cborToJsonString :: CBOR.Term -> Text.Text cborToJsonString (TInt n) = Text.pack (show n) cborToJsonString (TInteger n) = Text.pack (show n) cborToJsonString (TString s) = s cborToJsonString (TStringI s) = Text.Lazy.toStrict s cborToJsonString (TBytes bs) = base64url bs cborToJsonString (TBytesI bs) = base64url (LBS.toStrict bs) TODO moreover , api - tools uses base64 rather than base64url ! base64url :: ByteString -> Text base64 :: ByteString -> Text base64 = Text.decodeLatin1 . Base64.encode base16 :: ByteString -> Text base16 = Text.decodeLatin1 . Base16.encode jsonToCbor :: JSON.Value -> CBOR.Term jsonToCbor (JSON.Object kvs) = CBOR.TMap [ (CBOR.TString k, jsonToCbor v) | (k, v) <- objectToList kvs ] jsonToCbor (JSON.Array vs) = CBOR.TList [ jsonToCbor v | v <- Vec.toList vs ] jsonToCbor (JSON.String str) = CBOR.TString str jsonToCbor (JSON.Number n) = case Scientific.floatingOrInteger n of Left d -> CBOR.TDouble d Right i | i >= fromIntegral (minBound :: Int) && i <= fromIntegral (maxBound :: Int) -> CBOR.TInt (fromIntegral i) | otherwise -> CBOR.TInteger i jsonToCbor (JSON.Bool b) = CBOR.TBool b jsonToCbor JSON.Null = CBOR.TNull
d7af51968991b137ade31fd7e73371b052ccf50e62743c69f4885e2d13c0080a
gleber/exat
aclscan.erl
%% %% aclscan.erl %% - New acl scanner %% %% ---------------------------------------------------------------------- %% eXAT , an erlang eXperimental Agent Tool Copyright ( C ) 2005 - 07 ( ) %% %% This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% You should have received a copy of the GNU General Public License %% along with this program. If not, see </> %% %% -module(aclscan). -export([scan/1]). scan([], _Acc, Tokens) -> lists:reverse(Tokens); scan([$( | L], [], Tokens) -> scan(L, [], ["(" | Tokens]); scan([$( | L], Acc, Tokens) -> scan(L, [], ["(", lists:reverse(Acc) | Tokens]); scan([$) | L], [], Tokens) -> scan(L, [], [")" | Tokens]); scan([$) | L], Acc, Tokens) -> scan(L, [], [")", lists:reverse(Acc) | Tokens]); scan([$: | L], [], Tokens) -> scan(L, [], [":" | Tokens]); scan([$: | L], Acc, Tokens) -> scan(L, [], [":", lists:reverse(Acc) | Tokens]); scan([$" | L], Acc, Tokens) -> [Data, Tail] = toquote(L), scan(Tail, [], [Data, lists:reverse(Acc) | Tokens]); scan([$\s | L], Acc, Tokens) -> scan(L, [], [lists:reverse(Acc) | Tokens]); scan([$\\, H | L], Acc, Tokens) -> scan(L, [H | Acc], Tokens); scan([H | L], Acc, Tokens) -> scan(L, [H | Acc], Tokens). toquote([]) -> [[], []]; toquote([$" | T]) -> [[], T]; toquote([$\\, H | T]) -> [Data, Tail] = toquote(T), [[H | Data], Tail]; toquote([H | T]) -> [Data, Tail] = toquote(T), [[H | Data], Tail]. remove_empty([]) -> []; remove_empty([[] | T]) -> remove_empty(T); remove_empty([H | T]) -> [H | remove_empty(T)]. scan(Message) -> remove_empty(scan(Message, [], [])).
null
https://raw.githubusercontent.com/gleber/exat/a7ccf4807a321934d9a69fada59103f580d7fcce/src/aclscan.erl
erlang
aclscan.erl - New acl scanner ---------------------------------------------------------------------- This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program. If not, see </>
eXAT , an erlang eXperimental Agent Tool Copyright ( C ) 2005 - 07 ( ) 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 -module(aclscan). -export([scan/1]). scan([], _Acc, Tokens) -> lists:reverse(Tokens); scan([$( | L], [], Tokens) -> scan(L, [], ["(" | Tokens]); scan([$( | L], Acc, Tokens) -> scan(L, [], ["(", lists:reverse(Acc) | Tokens]); scan([$) | L], [], Tokens) -> scan(L, [], [")" | Tokens]); scan([$) | L], Acc, Tokens) -> scan(L, [], [")", lists:reverse(Acc) | Tokens]); scan([$: | L], [], Tokens) -> scan(L, [], [":" | Tokens]); scan([$: | L], Acc, Tokens) -> scan(L, [], [":", lists:reverse(Acc) | Tokens]); scan([$" | L], Acc, Tokens) -> [Data, Tail] = toquote(L), scan(Tail, [], [Data, lists:reverse(Acc) | Tokens]); scan([$\s | L], Acc, Tokens) -> scan(L, [], [lists:reverse(Acc) | Tokens]); scan([$\\, H | L], Acc, Tokens) -> scan(L, [H | Acc], Tokens); scan([H | L], Acc, Tokens) -> scan(L, [H | Acc], Tokens). toquote([]) -> [[], []]; toquote([$" | T]) -> [[], T]; toquote([$\\, H | T]) -> [Data, Tail] = toquote(T), [[H | Data], Tail]; toquote([H | T]) -> [Data, Tail] = toquote(T), [[H | Data], Tail]. remove_empty([]) -> []; remove_empty([[] | T]) -> remove_empty(T); remove_empty([H | T]) -> [H | remove_empty(T)]. scan(Message) -> remove_empty(scan(Message, [], [])).
57556996ec8716f78f52dba2ec692ff73e05518c8b0ac1480f829a96e31b903d
micahasmith/crypto-watch
gdax_history_recorder.clj
(ns crypto.systems.gdax-history-recorder (:require [crypto.infra.config :refer [get-config]] [crypto.infra.helpers :refer :all] [crypto.infra.redis :refer [redis*]] [crypto.infra.rolling-log :refer [roll!]] [crypto.services.gdax :as gdax] [crypto.data.gdax-redis :as gdax-redis] [mount.core :as mount :refer [defstate]] [fileape.core :as ape] [taoensso.timbre :as timbre :refer [info warn error]] [clojure.core.async :as a] [cheshire.core :as json] ) (:import (java.io File DataOutputStream) (org.apache.commons.compress.compressors.bzip2 BZip2CompressorInputStream) )) (defn -start! [] (log-errors (let [history-dir (get-dir-or-root (get-config :history-dir) "/logs-history/") prods (gdax-redis/get-last-products) gdax-output-chan (a/chan) gdax-output-mult (a/mult gdax-output-chan) json-encoding-xf (comp (map json/encode)) history-writer-chan (a/chan 1024 json-encoding-xf) gdax-websocket-shutdown-chan (a/chan) gdax-book-3-shutdown-chan (a/chan) ;; send gdax output into the log writer _ (a/tap gdax-output-mult history-writer-chan) ;; kick off the history-writer history-log (roll! history-dir (str "gdax-history-" (now-string) ".json") history-writer-chan)] ;; kick off the service (info "starting websocket for " prods) (gdax/listen! prods gdax-websocket-shutdown-chan gdax-output-chan) (gdax/watch-books-3! prods gdax-book-3-shutdown-chan history-writer-chan) ;; return a map of closeable/disposable things {:history-log history-log :gdax-output-chan gdax-output-chan :gdax-websocket-shutdown-chan gdax-websocket-shutdown-chan :gdax-book-3-shutdown-chan gdax-book-3-shutdown-chan :history-writer-chan history-writer-chan}))) (defn -shutdown! [sys] (log-errors (supressed-with warn (-> sys :gdax-book-3-shutdown-chan (a/close!))) (supressed-with warn (-> sys :gdax-websocket-shutdown-chan (a/close!))) (supressed-with warn (-> sys :gdax-output-chan (a/close!))) (supressed-with warn (-> sys :history-writer-chan (a/close!))) (supressed-with warn (-> sys :history-log (ape/close))))) (defn subscribe-to-changes! [] (let [{on-next :on-next, shutdown-chan :shutdown-chan} (gdax-redis/on-latest-product-change) system (atom nil) shutdown (a/chan)] (a/go-loop [msg (a/alt! on-next :refresh shutdown :shutting-down)] (info "gdax subscriptions" msg) (condp = msg :refresh (let [had-success? (try (let [next-system (-start!) wait 1 sec so that the next system can spin up _ (a/<! (a/timeout 1000))] (-shutdown! @system) (reset! system next-system) ;; return that we had success true) (catch Exception e (do (error e "during msg" msg) false)))] (if had-success? (do (info "restart due to new prods SUCCESS") (recur (a/alt! on-next :refresh shutdown :shutting-down))) (do (warn "restart due to new prods FAIL") (recur msg)))) :shutting-down (do (supressed-with warn (a/close! shutdown)) (-> @system -shutdown!)))) ;; return fn that is the closer (fn [] (supressed-with warn (a/close! shutdown-chan)) (supressed-with warn (a/close! shutdown))))) (defstate sys :start (subscribe-to-changes!) :stop (sys)) (def sys-set #{#'crypto.infra.redis/connection #'crypto.systems.gdax-history-recorder/sys}) ;(def a (-start!)) ( -shutdown ! a )
null
https://raw.githubusercontent.com/micahasmith/crypto-watch/265d03148a018e422513a6daee67cf6e58ac12bf/crypto/src/crypto/systems/gdax_history_recorder.clj
clojure
send gdax output into the log writer kick off the history-writer kick off the service return a map of closeable/disposable things return that we had success return fn that is the closer (def a (-start!))
(ns crypto.systems.gdax-history-recorder (:require [crypto.infra.config :refer [get-config]] [crypto.infra.helpers :refer :all] [crypto.infra.redis :refer [redis*]] [crypto.infra.rolling-log :refer [roll!]] [crypto.services.gdax :as gdax] [crypto.data.gdax-redis :as gdax-redis] [mount.core :as mount :refer [defstate]] [fileape.core :as ape] [taoensso.timbre :as timbre :refer [info warn error]] [clojure.core.async :as a] [cheshire.core :as json] ) (:import (java.io File DataOutputStream) (org.apache.commons.compress.compressors.bzip2 BZip2CompressorInputStream) )) (defn -start! [] (log-errors (let [history-dir (get-dir-or-root (get-config :history-dir) "/logs-history/") prods (gdax-redis/get-last-products) gdax-output-chan (a/chan) gdax-output-mult (a/mult gdax-output-chan) json-encoding-xf (comp (map json/encode)) history-writer-chan (a/chan 1024 json-encoding-xf) gdax-websocket-shutdown-chan (a/chan) gdax-book-3-shutdown-chan (a/chan) _ (a/tap gdax-output-mult history-writer-chan) history-log (roll! history-dir (str "gdax-history-" (now-string) ".json") history-writer-chan)] (info "starting websocket for " prods) (gdax/listen! prods gdax-websocket-shutdown-chan gdax-output-chan) (gdax/watch-books-3! prods gdax-book-3-shutdown-chan history-writer-chan) {:history-log history-log :gdax-output-chan gdax-output-chan :gdax-websocket-shutdown-chan gdax-websocket-shutdown-chan :gdax-book-3-shutdown-chan gdax-book-3-shutdown-chan :history-writer-chan history-writer-chan}))) (defn -shutdown! [sys] (log-errors (supressed-with warn (-> sys :gdax-book-3-shutdown-chan (a/close!))) (supressed-with warn (-> sys :gdax-websocket-shutdown-chan (a/close!))) (supressed-with warn (-> sys :gdax-output-chan (a/close!))) (supressed-with warn (-> sys :history-writer-chan (a/close!))) (supressed-with warn (-> sys :history-log (ape/close))))) (defn subscribe-to-changes! [] (let [{on-next :on-next, shutdown-chan :shutdown-chan} (gdax-redis/on-latest-product-change) system (atom nil) shutdown (a/chan)] (a/go-loop [msg (a/alt! on-next :refresh shutdown :shutting-down)] (info "gdax subscriptions" msg) (condp = msg :refresh (let [had-success? (try (let [next-system (-start!) wait 1 sec so that the next system can spin up _ (a/<! (a/timeout 1000))] (-shutdown! @system) (reset! system next-system) true) (catch Exception e (do (error e "during msg" msg) false)))] (if had-success? (do (info "restart due to new prods SUCCESS") (recur (a/alt! on-next :refresh shutdown :shutting-down))) (do (warn "restart due to new prods FAIL") (recur msg)))) :shutting-down (do (supressed-with warn (a/close! shutdown)) (-> @system -shutdown!)))) (fn [] (supressed-with warn (a/close! shutdown-chan)) (supressed-with warn (a/close! shutdown))))) (defstate sys :start (subscribe-to-changes!) :stop (sys)) (def sys-set #{#'crypto.infra.redis/connection #'crypto.systems.gdax-history-recorder/sys}) ( -shutdown ! a )
a5d6cb633e2b90aa6473f5a438d23bd2df40dc78a2841ba4d3ff369b1aefffd6
barrel-db/rebar3_elixir_compile
rebar3_elixir_compile_resource.erl
-module(rebar3_elixir_compile_resource). -behaviour(rebar_resource). -define(DEFAULT_CDN_SITE, ""). -define(CDN_TARBALL_LOCATION, "/tarballs"). -export([lock/2 ,download/3 ,needs_update/2 ,make_vsn/1]). lock(_Dir, {elixir, Name, Vsn}) -> {elixir, rebar3_elixir_compile_util:to_binary(Name), rebar3_elixir_compile_util:to_binary(Vsn)}. download(Dir, {elixir, Name, _Vsn} = Pkg, State) -> {ok, Config} = file:consult(filename:join([rebar_dir:root_dir(State), "rebar.config"])), {deps, Deps} = lists:keyfind(deps, 1 , Config), case is_dep_there(Deps, Name, rebar_dir:deps_dir(State)) of false -> fetch_and_compile(State, Dir, Pkg); true -> rebar3_elixir_compile_util:maybe_copy_dir(rebar3_elixir_compile_util:fetch_mix_app_from_dep(State, Name), Dir, false), rebar3_elixir_compile_util:maybe_copy_dir(filename:join([rebar_dir:deps_dir(State), Name]), Dir, false) end, {ok, true}. is_dep_there(Deps, Name, Dir) -> InConfig = lists:filter(fun ({D, _}) -> rebar3_elixir_compile_util:to_binary(D) == rebar3_elixir_compile_util:to_binary(Name); (_) -> false end, Deps), InDir = filelib:is_dir(filename:join([Dir, Name, "ebin"])), case {InConfig, InDir} of {[], true} -> true; {_, true} -> false; {[], false} -> true; {_, false} -> false end. needs_update(Dir, {elixir, _Name, Vsn}) -> rebar_api:console("Checking for update, ~p", _Name), [AppInfo] = rebar_app_discover:find_apps([Dir], all), case rebar_app_info:original_vsn(AppInfo) =:= ec_cnv:to_list(Vsn) of true -> false; false -> true end. make_vsn(_) -> {error, "Replacing version of type elixir not supported."}. fetch_and_compile(State, Dir, {elixir, Name, _Vsn} = Pkg) -> CDN = cdn(State), fetch(Pkg, CDN), State1 = rebar3_elixir_compile_util:add_elixir(State), State2 = rebar_state:set(State1, libs_target_dir, default), BaseDir = filename:join(rebar_dir:root_dir(State2), "_elixir_build/"), BaseDirState = rebar_state:set(State2, elixir_base_dir, BaseDir), Env = rebar_state:get(BaseDirState, mix_env), AppDir = filename:join(BaseDir, Name), rebar3_elixir_compile_util:compile_libs(BaseDirState), LibsDir = rebar3_elixir_compile_util:libs_dir(AppDir, Env), rebar3_elixir_compile_util:transfer_libs(rebar_state:set(BaseDirState, libs_target_dir, Dir), [Name], LibsDir). cdn(State) -> Opts = rebar_state:get(State, elixir_opts, []), CDNSite = proplists:get_value(cdn, Opts, ?DEFAULT_CDN_SITE), CDNSite ++ ?CDN_TARBALL_LOCATION. fetch({elixir, Name_, Vsn_}, CDN) -> Dir = filename:join([filename:absname("_elixir_build"), Name_]), Name = rebar3_elixir_compile_util:to_binary(Name_), Vsn = rebar3_elixir_compile_util:to_binary(Vsn_), case filelib:is_dir(Dir) of false -> Config = #{ http_adapter => hex_http_httpc, http_adapter_config => #{profile => default}, http_user_agent_fragment => user_agent(), repo_url => list_to_binary(CDN) }, case hex_repo:get_tarball(Config, Name, Vsn) of {ok, Binary, _} -> {ok, Contents} = extract(Binary), ok = erl_tar:extract({binary, Contents}, [{cwd, Dir}, compressed]); _ -> rebar_api:console("Error: Unable to fetch package ~p ~p~n", [Name, Vsn]) end; true -> rebar_api:console("Dependency ~s already exists~n", [Name]) end. extract(Binary) -> {ok, Files} = erl_tar:extract({binary, Binary}, [memory]), {"contents.tar.gz", Contents} = lists:keyfind("contents.tar.gz", 1, Files), {ok, Contents}. user_agent() -> AppName = rebar3_elixir_compile, AppVsn = case lists:keyfind(AppName, 1, application:loaded_applications()) of {_, _, Ver} -> Ver; false -> "unknown" end, list_to_binary([atom_to_list(AppName), "/", AppVsn, " (httpc)"]).
null
https://raw.githubusercontent.com/barrel-db/rebar3_elixir_compile/2bc219a9feaa77362523808096f226de805857e8/src/rebar3_elixir_compile_resource.erl
erlang
-module(rebar3_elixir_compile_resource). -behaviour(rebar_resource). -define(DEFAULT_CDN_SITE, ""). -define(CDN_TARBALL_LOCATION, "/tarballs"). -export([lock/2 ,download/3 ,needs_update/2 ,make_vsn/1]). lock(_Dir, {elixir, Name, Vsn}) -> {elixir, rebar3_elixir_compile_util:to_binary(Name), rebar3_elixir_compile_util:to_binary(Vsn)}. download(Dir, {elixir, Name, _Vsn} = Pkg, State) -> {ok, Config} = file:consult(filename:join([rebar_dir:root_dir(State), "rebar.config"])), {deps, Deps} = lists:keyfind(deps, 1 , Config), case is_dep_there(Deps, Name, rebar_dir:deps_dir(State)) of false -> fetch_and_compile(State, Dir, Pkg); true -> rebar3_elixir_compile_util:maybe_copy_dir(rebar3_elixir_compile_util:fetch_mix_app_from_dep(State, Name), Dir, false), rebar3_elixir_compile_util:maybe_copy_dir(filename:join([rebar_dir:deps_dir(State), Name]), Dir, false) end, {ok, true}. is_dep_there(Deps, Name, Dir) -> InConfig = lists:filter(fun ({D, _}) -> rebar3_elixir_compile_util:to_binary(D) == rebar3_elixir_compile_util:to_binary(Name); (_) -> false end, Deps), InDir = filelib:is_dir(filename:join([Dir, Name, "ebin"])), case {InConfig, InDir} of {[], true} -> true; {_, true} -> false; {[], false} -> true; {_, false} -> false end. needs_update(Dir, {elixir, _Name, Vsn}) -> rebar_api:console("Checking for update, ~p", _Name), [AppInfo] = rebar_app_discover:find_apps([Dir], all), case rebar_app_info:original_vsn(AppInfo) =:= ec_cnv:to_list(Vsn) of true -> false; false -> true end. make_vsn(_) -> {error, "Replacing version of type elixir not supported."}. fetch_and_compile(State, Dir, {elixir, Name, _Vsn} = Pkg) -> CDN = cdn(State), fetch(Pkg, CDN), State1 = rebar3_elixir_compile_util:add_elixir(State), State2 = rebar_state:set(State1, libs_target_dir, default), BaseDir = filename:join(rebar_dir:root_dir(State2), "_elixir_build/"), BaseDirState = rebar_state:set(State2, elixir_base_dir, BaseDir), Env = rebar_state:get(BaseDirState, mix_env), AppDir = filename:join(BaseDir, Name), rebar3_elixir_compile_util:compile_libs(BaseDirState), LibsDir = rebar3_elixir_compile_util:libs_dir(AppDir, Env), rebar3_elixir_compile_util:transfer_libs(rebar_state:set(BaseDirState, libs_target_dir, Dir), [Name], LibsDir). cdn(State) -> Opts = rebar_state:get(State, elixir_opts, []), CDNSite = proplists:get_value(cdn, Opts, ?DEFAULT_CDN_SITE), CDNSite ++ ?CDN_TARBALL_LOCATION. fetch({elixir, Name_, Vsn_}, CDN) -> Dir = filename:join([filename:absname("_elixir_build"), Name_]), Name = rebar3_elixir_compile_util:to_binary(Name_), Vsn = rebar3_elixir_compile_util:to_binary(Vsn_), case filelib:is_dir(Dir) of false -> Config = #{ http_adapter => hex_http_httpc, http_adapter_config => #{profile => default}, http_user_agent_fragment => user_agent(), repo_url => list_to_binary(CDN) }, case hex_repo:get_tarball(Config, Name, Vsn) of {ok, Binary, _} -> {ok, Contents} = extract(Binary), ok = erl_tar:extract({binary, Contents}, [{cwd, Dir}, compressed]); _ -> rebar_api:console("Error: Unable to fetch package ~p ~p~n", [Name, Vsn]) end; true -> rebar_api:console("Dependency ~s already exists~n", [Name]) end. extract(Binary) -> {ok, Files} = erl_tar:extract({binary, Binary}, [memory]), {"contents.tar.gz", Contents} = lists:keyfind("contents.tar.gz", 1, Files), {ok, Contents}. user_agent() -> AppName = rebar3_elixir_compile, AppVsn = case lists:keyfind(AppName, 1, application:loaded_applications()) of {_, _, Ver} -> Ver; false -> "unknown" end, list_to_binary([atom_to_list(AppName), "/", AppVsn, " (httpc)"]).
d8ffc294eae2e7c3f7862d419dcca98acedc592667b2893628c090a9ec69be0d
wdhowe/clojure-snippets
comparisons.clj
(ns clojure.examples.comparisons (:gen-class)) (defn do-compare [] (println "Equality:" (= 7 7)) (println "Not Equality:" (not= 7 7)) (println "Less than:" (< 7 8)) (println "Greater than:" (> 7 8)) (println "And op:" (and true false)) (println "Or op:" (or true false)) (println "Not op:" (not false))) (do-compare)
null
https://raw.githubusercontent.com/wdhowe/clojure-snippets/0c3247ce99a563312b549d03f080b8cf449b541d/basic_syntax/comparisons.clj
clojure
(ns clojure.examples.comparisons (:gen-class)) (defn do-compare [] (println "Equality:" (= 7 7)) (println "Not Equality:" (not= 7 7)) (println "Less than:" (< 7 8)) (println "Greater than:" (> 7 8)) (println "And op:" (and true false)) (println "Or op:" (or true false)) (println "Not op:" (not false))) (do-compare)
3d212212c6d4f356acce2f142f3d738092a6f10f24680d66a2ca8b6676edfb30
coq/coq
autorewrite.ml
(************************************************************************) (* * 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 Equality open Names open Pp open Constr open CErrors open Util open Mod_subst open Locus (* Rewriting rules *) type rew_rule = { rew_id : KerName.t; rew_lemma : constr; rew_type: types; rew_pat: constr; rew_ctx: Univ.ContextSet.t; rew_l2r: bool; rew_tac: Genarg.glob_generic_argument option } module RewRule = struct type t = rew_rule let rew_lemma r = (r.rew_ctx, r.rew_lemma) let rew_l2r r = r.rew_l2r let rew_tac r = r.rew_tac end module HintIdent = struct type t = rew_rule let compare r1 r2 = KerName.compare r1.rew_id r2.rew_id let constr_of t = t.rew_pat end Representation / approximation of terms to use in the dnet : * * - no meta or evar ( use [ ' a pattern ] for that ) * * - [ Rel]s and [ Sort]s are not taken into account ( that 's why we need * a second pass of linear filterin on the results - it 's not a perfect * term indexing structure ) * * - no meta or evar (use ['a pattern] for that) * * - [Rel]s and [Sort]s are not taken into account (that's why we need * a second pass of linear filterin on the results - it's not a perfect * term indexing structure) *) module DTerm = struct type 't t = | DRel | DSort | DRef of GlobRef.t | DProd | DLet | DLambda | DApp | DCase of case_info | DFix of int array * int | DCoFix of int | DInt of Uint63.t | DFloat of Float64.t | DArray let compare_ci ci1 ci2 = let c = Ind.CanOrd.compare ci1.ci_ind ci2.ci_ind in if c = 0 then let c = Int.compare ci1.ci_npar ci2.ci_npar in if c = 0 then let c = Array.compare Int.compare ci1.ci_cstr_ndecls ci2.ci_cstr_ndecls in if c = 0 then Array.compare Int.compare ci1.ci_cstr_nargs ci2.ci_cstr_nargs else c else c else c let compare t1 t2 = match t1, t2 with | DRel, DRel -> 0 | DRel, _ -> -1 | _, DRel -> 1 | DSort, DSort -> 0 | DSort, _ -> -1 | _, DSort -> 1 | DRef gr1, DRef gr2 -> GlobRef.CanOrd.compare gr1 gr2 | DRef _, _ -> -1 | _, DRef _ -> 1 | DProd, DProd -> 0 | DProd, _ -> -1 | _, DProd -> 1 | DLet, DLet -> 0 | DLet, _ -> -1 | _, DLet -> 1 | DLambda, DLambda | DApp, DApp -> 0 | DLambda, _ -> -1 | _, DLambda -> 1 | DApp, _ -> -1 | _, DApp -> 1 | DCase ci1, DCase ci2 -> compare_ci ci1 ci2 | DCase _, _ -> -1 | _, DCase _ -> 1 | DFix (i1, j1), DFix (i2, j2) -> let c = Int.compare j1 j2 in if c = 0 then Array.compare Int.compare i1 i2 else c | DFix _, _ -> -1 | _, DFix _ -> 1 | DCoFix i1, DCoFix i2 -> Int.compare i1 i2 | DCoFix _, _ -> -1 | _, DCoFix _ -> 1 | DInt i1, DInt i2 -> Uint63.compare i1 i2 | DInt _, _ -> -1 | _, DInt _ -> 1 | DFloat f1, DFloat f2 -> Float64.total_compare f1 f2 | DFloat _, _ -> -1 | _, DFloat _ -> 1 | DArray, DArray -> 1 end (* * Terms discrimination nets * Uses the general dnet datatype on DTerm.t * (here you can restart reading) *) module HintDN : sig type t type ident = HintIdent.t val empty : t * [ add c i dn ] adds the binding [ ( c , i ) ] to [ dn ] . [ c ] can be a closed term or a pattern ( with untyped ) . No Metas accepted closed term or a pattern (with untyped Evars). No Metas accepted *) val add : constr -> ident -> t -> t (* * High-level primitives describing specific search problems *) (** [search_pattern dn c] returns all terms/patterns in dn matching/matched by c *) val search_pattern : Environ.env -> t -> constr -> ident list (** [find_all dn] returns all idents contained in dn *) val find_all : t -> ident list end = struct module Ident = HintIdent module PTerm = struct type t = unit DTerm.t let compare = DTerm.compare end module TDnet = Dn.Make(PTerm)(Ident) type t = TDnet.t type ident = HintIdent.t open DTerm open TDnet let pat_of_constr c : (unit DTerm.t * Constr.t list) option = let open GlobRef in let rec pat_of_constr c = match Constr.kind c with | Rel _ -> Some (DRel, []) | Sort _ -> Some (DSort, []) | Var i -> Some (DRef (VarRef i), []) | Const (c,u) -> Some (DRef (ConstRef c), []) | Ind (i,u) -> Some (DRef (IndRef i), []) | Construct (c,u)-> Some (DRef (ConstructRef c), []) | Meta _ -> assert false | Evar (i,_) -> None | Case (ci,u1,pms1,c1,_iv,c2,ca) -> let f_ctx (_, p) = p in Some (DCase(ci), [f_ctx c1; c2] @ Array.map_to_list f_ctx ca) | Fix ((ia,i),(_,ta,ca)) -> Some (DFix(ia,i), Array.to_list ta @ Array.to_list ca) | CoFix (i,(_,ta,ca)) -> Some (DCoFix(i), Array.to_list ta @ Array.to_list ca) | Cast (c,_,_) -> pat_of_constr c | Lambda (_,t,c) -> Some (DLambda, [t; c]) | Prod (_, t, u) -> Some (DProd, [t; u]) | LetIn (_, c, t, u) -> Some (DLet, [c; t; u]) | App (f,ca) -> let len = Array.length ca in let a = ca.(len - 1) in let ca = Array.sub ca 0 (len - 1) in Some (DApp, [mkApp (f, ca); a]) | Proj (p,c) -> pat_of_constr (mkApp (mkConst (Projection.constant p), [|c|])) | Int i -> Some (DInt i, []) | Float f -> Some (DFloat f, []) | Array (_u,t,def,ty) -> Some (DArray, Array.to_list t @ [def ; ty]) in pat_of_constr c (* * Basic primitives *) let empty = TDnet.empty let add (c:constr) (id:Ident.t) (dn:t) = (* We used to consider the types of the product as well, but since the dnet is only computing an approximation rectified by [filtering] we do not anymore. *) let (ctx, c) = Term.decompose_prod_decls c in let c = TDnet.pattern pat_of_constr c in TDnet.add dn c id ... tn ] ) - > ( [ c , t1, ... ,tn-1],tn ) App(c,[|| ] ) - > ( [ ] , c ) App(c,[||]) -> ([],c) *) let split_app sigma c = match EConstr.kind sigma c with App(c,l) -> let len = Array.length l in if Int.equal len 0 then ([],c) else let last = Array.get l (len-1) in let prev = Array.sub l 0 (len-1) in c::(Array.to_list prev), last | _ -> assert false exception CannotFilter let filtering env sigma ctx cv_pb c1 c2 = let open EConstr in let open Vars in let evm = ref Evar.Map.empty in let define cv_pb e1 ev c1 = try let (e2,c2) = Evar.Map.find ev !evm in let shift = e1 - e2 in if Termops.constr_cmp env sigma cv_pb c1 (lift shift c2) then () else raise CannotFilter with Not_found -> evm := Evar.Map.add ev (e1,c1) !evm in let rec aux ctx cv_pb c1 c2 = match EConstr.kind sigma c1, EConstr.kind sigma c2 with | App _, App _ -> let ((p1,l1),(p2,l2)) = (split_app sigma c1),(split_app sigma c2) in let () = aux ctx cv_pb l1 l2 in begin match p1, p2 with | [], [] -> () | (h1 :: p1), (h2 :: p2) -> aux ctx cv_pb (applist (h1, p1)) (applist (h2, p2)) | _ -> assert false end | Prod (n,t1,c1), Prod (_,t2,c2) -> aux ctx cv_pb t1 t2; aux (ctx + 1) cv_pb c1 c2 | _, Evar (ev,_) -> define cv_pb ctx ev c1 | Evar (ev,_), _ -> define cv_pb ctx ev c2 | _ -> if Termops.compare_constr_univ env sigma (fun pb c1 c2 -> aux ctx pb c1 c2; true) cv_pb c1 c2 then () else raise CannotFilter (* TODO: le reste des binders *) in try let () = aux ctx cv_pb c1 c2 in true with CannotFilter -> false let align_prod_letin sigma c a = let (lc,_) = EConstr.decompose_prod_decls sigma c in let (l,a) = EConstr.decompose_prod_decls sigma a in let lc = List.length lc in let n = List.length l in if n < lc then invalid_arg "align_prod_letin"; let l1 = CList.firstn lc l in n - lc, EConstr.it_mkProd_or_LetIn a l1 let decomp pat = match pat_of_constr pat with | None -> Dn.Everything | Some (lbl, args) -> Dn.Label (lbl, args) let search_pattern env dn cpat = let _dctx, dpat = Term.decompose_prod_decls cpat in let whole_c = EConstr.of_constr cpat in List.fold_left (fun acc id -> let c_id = EConstr.of_constr @@ Ident.constr_of id in let (ctx,wc) = FIXME with Invalid_argument _ -> 0, c_id in if filtering env Evd.empty ctx Reduction.CUMUL whole_c wc then id :: acc else acc ) (TDnet.lookup dn decomp dpat) [] let find_all dn = TDnet.lookup dn (fun () -> Everything) () end type rewrite_db = { rdb_hintdn : HintDN.t; rdb_order : int KNmap.t; rdb_maxuid : int; } let empty_rewrite_db = { rdb_hintdn = HintDN.empty; rdb_order = KNmap.empty; rdb_maxuid = 0; } (* Summary and Object declaration *) let rewtab = Summary.ref (String.Map.empty : rewrite_db String.Map.t) ~name:"autorewrite" let raw_find_base bas = String.Map.find bas !rewtab let find_base bas = try raw_find_base bas with Not_found -> user_err (str "Rewriting base " ++ str bas ++ str " does not exist.") let find_rewrites bas = let db = find_base bas in let sort r1 r2 = Int.compare (KNmap.find r2.rew_id db.rdb_order) (KNmap.find r1.rew_id db.rdb_order) in List.sort sort (HintDN.find_all db.rdb_hintdn) let find_matches env bas pat = let base = find_base bas in let res = HintDN.search_pattern env base.rdb_hintdn pat in let sort r1 r2 = Int.compare (KNmap.find r2.rew_id base.rdb_order) (KNmap.find r1.rew_id base.rdb_order) in List.sort sort res let print_rewrite_hintdb bas = let env = Global.env () in let sigma = Evd.from_env env in (str "Database " ++ str bas ++ fnl () ++ prlist_with_sep fnl (fun h -> str (if h.rew_l2r then "rewrite -> " else "rewrite <- ") ++ Printer.pr_lconstr_env env sigma h.rew_lemma ++ str " of type " ++ Printer.pr_lconstr_env env sigma h.rew_type ++ Option.cata (fun tac -> str " then use tactic " ++ Pputils.pr_glb_generic env sigma tac) (mt ()) h.rew_tac) (find_rewrites bas)) type raw_rew_rule = (constr Univ.in_universe_context_set * bool * Genarg.raw_generic_argument option) CAst.t let tclMAP_rev f args = List.fold_left (fun accu arg -> Tacticals.tclTHEN accu (f arg)) (Proofview.tclUNIT ()) args Applies all the rules of one base let one_base where conds tac_main bas = let lrul = find_rewrites bas in let rewrite dir c tac = let c = (EConstr.of_constr c, Tactypes.NoBindings) in general_rewrite ~where ~l2r:dir AllOccurrences ~freeze:true ~dep:false ~with_evars:false ~tac:(tac, conds) c in let try_rewrite h tc = Proofview.Goal.enter begin fun gl -> let sigma = Proofview.Goal.sigma gl in let subst, ctx' = UnivGen.fresh_universe_context_set_instance h.rew_ctx in let c' = Vars.subst_univs_level_constr subst h.rew_lemma in let sigma = Evd.merge_context_set Evd.univ_flexible sigma ctx' in Proofview.tclTHEN (Proofview.Unsafe.tclEVARS sigma) (rewrite h.rew_l2r c' tc) end in let open Proofview.Notations in Proofview.tclProofInfo [@ocaml.warning "-3"] >>= fun (_name, poly) -> let eval h = let tac = match h.rew_tac with | None -> Proofview.tclUNIT () | Some (Genarg.GenArg (Genarg.Glbwit wit, tac)) -> let ist = { Geninterp.lfun = Id.Map.empty ; poly ; extra = Geninterp.TacStore.empty } in Ftactic.run (Geninterp.interp wit ist tac) (fun _ -> Proofview.tclUNIT ()) in Tacticals.tclREPEAT_MAIN (Tacticals.tclTHENFIRST (try_rewrite h tac) tac_main) in let lrul = tclMAP_rev eval lrul in Tacticals.tclREPEAT_MAIN (Proofview.tclPROGRESS lrul) The AutoRewrite tactic let autorewrite ?(conds=Naive) tac_main lbas = Tacticals.tclREPEAT_MAIN (Proofview.tclPROGRESS (tclMAP_rev (fun bas -> (one_base None conds tac_main bas)) lbas)) let autorewrite_multi_in ?(conds=Naive) idl tac_main lbas = Proofview.Goal.enter begin fun gl -> (* let's check at once if id exists (to raise the appropriate error) *) let _ = List.map (fun id -> Tacmach.pf_get_hyp id gl) idl in Tacticals.tclMAP (fun id -> Tacticals.tclREPEAT_MAIN (Proofview.tclPROGRESS (tclMAP_rev (fun bas -> (one_base (Some id) conds tac_main bas)) lbas))) idl end let autorewrite_in ?(conds=Naive) id = autorewrite_multi_in ~conds [id] let gen_auto_multi_rewrite conds tac_main lbas cl = let try_do_hyps treat_id l = autorewrite_multi_in ~conds (List.map treat_id l) tac_main lbas in let concl_tac = (if cl.concl_occs != NoOccurrences then autorewrite ~conds tac_main lbas else Proofview.tclUNIT ()) in if not (Locusops.is_all_occurrences cl.concl_occs) && cl.concl_occs != NoOccurrences then let info = Exninfo.reify () in Tacticals.tclZEROMSG ~info (str"The \"at\" syntax isn't available yet for the autorewrite tactic.") else match cl.onhyps with | Some [] -> concl_tac | Some l -> Tacticals.tclTHENFIRST concl_tac (try_do_hyps (fun ((_,id),_) -> id) l) | None -> let hyp_tac = (* try to rewrite in all hypothesis (except maybe the rewritten one) *) Proofview.Goal.enter begin fun gl -> let ids = Tacmach.pf_ids_of_hyps gl in try_do_hyps (fun id -> id) ids end in Tacticals.tclTHENFIRST concl_tac hyp_tac let auto_multi_rewrite ?(conds=Naive) lems cl = Proofview.wrap_exceptions (fun () -> gen_auto_multi_rewrite conds (Proofview.tclUNIT()) lems cl) (* Same hack as auto hints: we generate an essentially unique identifier for rewrite hints. *) let fresh_key = let id = Summary.ref ~name:"REWHINT-COUNTER" 0 in fun () -> let cur = incr id; !id in let lbl = Id.of_string ("_" ^ string_of_int cur) in let kn = Lib.make_kn lbl in let (mp, _) = KerName.repr kn in We embed the full path of the kernel name in the label so that the identifier should be unique . This ensures that including two modules together wo n't confuse the corresponding labels . the identifier should be unique. This ensures that including two modules together won't confuse the corresponding labels. *) let lbl = Id.of_string_soft (Printf.sprintf "%s#%i" (ModPath.to_string mp) cur) in KerName.make mp (Label.of_id lbl) let auto_multi_rewrite_with ?(conds=Naive) tac_main lbas cl = let onconcl = match cl.Locus.concl_occs with NoOccurrences -> false | _ -> true in match onconcl,cl.Locus.onhyps with | false,Some [_] | true,Some [] | false,Some [] -> autorewrite with .... in clause using tac n'est sur que si clause represente soit le but soit UNE hypothese si clause represente soit le but soit UNE hypothese *) Proofview.wrap_exceptions (fun () -> gen_auto_multi_rewrite conds tac_main lbas cl) | _ -> let info = Exninfo.reify () in Tacticals.tclZEROMSG ~info (strbrk "autorewrite .. in .. using can only be used either with a unique hypothesis or on the conclusion.") (* Functions necessary to the library object declaration *) let cache_hintrewrite (rbase,lrl) = let base = try raw_find_base rbase with Not_found -> empty_rewrite_db in let fold accu r = { rdb_hintdn = HintDN.add r.rew_pat r accu.rdb_hintdn; rdb_order = KNmap.add r.rew_id accu.rdb_maxuid accu.rdb_order; rdb_maxuid = accu.rdb_maxuid + 1; } in let base = List.fold_left fold base lrl in rewtab := String.Map.add rbase base !rewtab let subst_hintrewrite (subst,(rbase,list as node)) = let subst_hint subst hint = let id' = subst_kn subst hint.rew_id in let cst' = subst_mps subst hint.rew_lemma in let typ' = subst_mps subst hint.rew_type in let pat' = subst_mps subst hint.rew_pat in let t' = Option.Smart.map (Genintern.generic_substitute subst) hint.rew_tac in if hint.rew_id == id' && hint.rew_lemma == cst' && hint.rew_type == typ' && hint.rew_tac == t' && hint.rew_pat == pat' then hint else { hint with rew_lemma = cst'; rew_type = typ'; rew_pat = pat'; rew_tac = t' } in let list' = List.Smart.map (fun h -> subst_hint subst h) list in if list' == list then node else (rbase,list') (* Declaration of the Hint Rewrite library object *) let inGlobalHintRewrite : string * rew_rule list -> Libobject.obj = let open Libobject in declare_object @@ superglobal_object_nodischarge "HINT_REWRITE_GLOBAL" ~cache:cache_hintrewrite ~subst:(Some subst_hintrewrite) let inExportHintRewrite : string * rew_rule list -> Libobject.obj = let open Libobject in declare_object @@ global_object_nodischarge ~cat:Hints.hint_cat "HINT_REWRITE_EXPORT" ~cache:cache_hintrewrite ~subst:(Some subst_hintrewrite) type hypinfo = { hyp_ty : EConstr.types; hyp_pat : EConstr.constr; } let decompose_applied_relation env sigma c ctype left2right = let find_rel ty = (* FIXME: this is nonsense, we generate evars and then we drop the corresponding evarmap. This sometimes works because [Term_dnet] performs evar surgery via [Termops.filtering]. *) let sigma, ty = EClause.make_evar_clause env sigma ty in let (_, args) = Termops.decompose_app_vect sigma ty.EClause.cl_concl in let len = Array.length args in if 2 <= len then let c1 = args.(len - 2) in let c2 = args.(len - 1) in Some (if left2right then c1 else c2) else None in match find_rel ctype with | Some c -> Some { hyp_pat = c; hyp_ty = ctype } | None -> let ctx,t' = Reductionops.hnf_decompose_prod_decls env sigma ctype in (* Search for underlying eq *) let ctype = EConstr.it_mkProd_or_LetIn t' ctx in match find_rel ctype with | Some c -> Some { hyp_pat = c; hyp_ty = ctype } | None -> None let find_applied_relation ?loc env sigma c left2right = let ctype = Retyping.get_type_of env sigma (EConstr.of_constr c) in match decompose_applied_relation env sigma c ctype left2right with | Some c -> c | None -> user_err ?loc (str"The type" ++ spc () ++ Printer.pr_econstr_env env sigma ctype ++ spc () ++ str"of this term does not end with an applied relation.") let default_hint_rewrite_locality () = if Global.sections_are_opened () then Hints.Local else Hints.Export (* To add rewriting rules to a base *) let add_rew_rules ~locality base lrul = let env = Global.env () in let sigma = Evd.from_env env in let ist = Genintern.empty_glob_sign (Global.env ()) in let intern tac = snd (Genintern.generic_intern ist tac) in let map {CAst.loc;v=((c,ctx),b,t)} = let sigma = Evd.merge_context_set Evd.univ_rigid sigma ctx in let info = find_applied_relation ?loc env sigma c b in let pat = EConstr.Unsafe.to_constr info.hyp_pat in let uid = fresh_key () in { rew_id = uid; rew_lemma = c; rew_type = EConstr.Unsafe.to_constr info.hyp_ty; rew_pat = pat; rew_ctx = ctx; rew_l2r = b; rew_tac = Option.map intern t } in let lrul = List.map map lrul in let open Hints in match locality with | Local -> cache_hintrewrite (base,lrul) | SuperGlobal -> let () = if Global.sections_are_opened () then CErrors.user_err Pp.(str "This command does not support the global attribute in sections."); in Lib.add_leaf (inGlobalHintRewrite (base,lrul)) | Export -> let () = if Global.sections_are_opened () then CErrors.user_err Pp.(str "This command does not support the export attribute in sections."); in Lib.add_leaf (inExportHintRewrite (base,lrul))
null
https://raw.githubusercontent.com/coq/coq/c1bf187bdd7a7b660692a97e0a36c6bf1acd0647/tactics/autorewrite.ml
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) ********************************************************************** Rewriting rules * Terms discrimination nets * Uses the general dnet datatype on DTerm.t * (here you can restart reading) * High-level primitives describing specific search problems * [search_pattern dn c] returns all terms/patterns in dn matching/matched by c * [find_all dn] returns all idents contained in dn * Basic primitives We used to consider the types of the product as well, but since the dnet is only computing an approximation rectified by [filtering] we do not anymore. TODO: le reste des binders Summary and Object declaration let's check at once if id exists (to raise the appropriate error) try to rewrite in all hypothesis (except maybe the rewritten one) Same hack as auto hints: we generate an essentially unique identifier for rewrite hints. Functions necessary to the library object declaration Declaration of the Hint Rewrite library object FIXME: this is nonsense, we generate evars and then we drop the corresponding evarmap. This sometimes works because [Term_dnet] performs evar surgery via [Termops.filtering]. Search for underlying eq To add rewriting rules to a base
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 Equality open Names open Pp open Constr open CErrors open Util open Mod_subst open Locus type rew_rule = { rew_id : KerName.t; rew_lemma : constr; rew_type: types; rew_pat: constr; rew_ctx: Univ.ContextSet.t; rew_l2r: bool; rew_tac: Genarg.glob_generic_argument option } module RewRule = struct type t = rew_rule let rew_lemma r = (r.rew_ctx, r.rew_lemma) let rew_l2r r = r.rew_l2r let rew_tac r = r.rew_tac end module HintIdent = struct type t = rew_rule let compare r1 r2 = KerName.compare r1.rew_id r2.rew_id let constr_of t = t.rew_pat end Representation / approximation of terms to use in the dnet : * * - no meta or evar ( use [ ' a pattern ] for that ) * * - [ Rel]s and [ Sort]s are not taken into account ( that 's why we need * a second pass of linear filterin on the results - it 's not a perfect * term indexing structure ) * * - no meta or evar (use ['a pattern] for that) * * - [Rel]s and [Sort]s are not taken into account (that's why we need * a second pass of linear filterin on the results - it's not a perfect * term indexing structure) *) module DTerm = struct type 't t = | DRel | DSort | DRef of GlobRef.t | DProd | DLet | DLambda | DApp | DCase of case_info | DFix of int array * int | DCoFix of int | DInt of Uint63.t | DFloat of Float64.t | DArray let compare_ci ci1 ci2 = let c = Ind.CanOrd.compare ci1.ci_ind ci2.ci_ind in if c = 0 then let c = Int.compare ci1.ci_npar ci2.ci_npar in if c = 0 then let c = Array.compare Int.compare ci1.ci_cstr_ndecls ci2.ci_cstr_ndecls in if c = 0 then Array.compare Int.compare ci1.ci_cstr_nargs ci2.ci_cstr_nargs else c else c else c let compare t1 t2 = match t1, t2 with | DRel, DRel -> 0 | DRel, _ -> -1 | _, DRel -> 1 | DSort, DSort -> 0 | DSort, _ -> -1 | _, DSort -> 1 | DRef gr1, DRef gr2 -> GlobRef.CanOrd.compare gr1 gr2 | DRef _, _ -> -1 | _, DRef _ -> 1 | DProd, DProd -> 0 | DProd, _ -> -1 | _, DProd -> 1 | DLet, DLet -> 0 | DLet, _ -> -1 | _, DLet -> 1 | DLambda, DLambda | DApp, DApp -> 0 | DLambda, _ -> -1 | _, DLambda -> 1 | DApp, _ -> -1 | _, DApp -> 1 | DCase ci1, DCase ci2 -> compare_ci ci1 ci2 | DCase _, _ -> -1 | _, DCase _ -> 1 | DFix (i1, j1), DFix (i2, j2) -> let c = Int.compare j1 j2 in if c = 0 then Array.compare Int.compare i1 i2 else c | DFix _, _ -> -1 | _, DFix _ -> 1 | DCoFix i1, DCoFix i2 -> Int.compare i1 i2 | DCoFix _, _ -> -1 | _, DCoFix _ -> 1 | DInt i1, DInt i2 -> Uint63.compare i1 i2 | DInt _, _ -> -1 | _, DInt _ -> 1 | DFloat f1, DFloat f2 -> Float64.total_compare f1 f2 | DFloat _, _ -> -1 | _, DFloat _ -> 1 | DArray, DArray -> 1 end module HintDN : sig type t type ident = HintIdent.t val empty : t * [ add c i dn ] adds the binding [ ( c , i ) ] to [ dn ] . [ c ] can be a closed term or a pattern ( with untyped ) . No Metas accepted closed term or a pattern (with untyped Evars). No Metas accepted *) val add : constr -> ident -> t -> t val search_pattern : Environ.env -> t -> constr -> ident list val find_all : t -> ident list end = struct module Ident = HintIdent module PTerm = struct type t = unit DTerm.t let compare = DTerm.compare end module TDnet = Dn.Make(PTerm)(Ident) type t = TDnet.t type ident = HintIdent.t open DTerm open TDnet let pat_of_constr c : (unit DTerm.t * Constr.t list) option = let open GlobRef in let rec pat_of_constr c = match Constr.kind c with | Rel _ -> Some (DRel, []) | Sort _ -> Some (DSort, []) | Var i -> Some (DRef (VarRef i), []) | Const (c,u) -> Some (DRef (ConstRef c), []) | Ind (i,u) -> Some (DRef (IndRef i), []) | Construct (c,u)-> Some (DRef (ConstructRef c), []) | Meta _ -> assert false | Evar (i,_) -> None | Case (ci,u1,pms1,c1,_iv,c2,ca) -> let f_ctx (_, p) = p in Some (DCase(ci), [f_ctx c1; c2] @ Array.map_to_list f_ctx ca) | Fix ((ia,i),(_,ta,ca)) -> Some (DFix(ia,i), Array.to_list ta @ Array.to_list ca) | CoFix (i,(_,ta,ca)) -> Some (DCoFix(i), Array.to_list ta @ Array.to_list ca) | Cast (c,_,_) -> pat_of_constr c | Lambda (_,t,c) -> Some (DLambda, [t; c]) | Prod (_, t, u) -> Some (DProd, [t; u]) | LetIn (_, c, t, u) -> Some (DLet, [c; t; u]) | App (f,ca) -> let len = Array.length ca in let a = ca.(len - 1) in let ca = Array.sub ca 0 (len - 1) in Some (DApp, [mkApp (f, ca); a]) | Proj (p,c) -> pat_of_constr (mkApp (mkConst (Projection.constant p), [|c|])) | Int i -> Some (DInt i, []) | Float f -> Some (DFloat f, []) | Array (_u,t,def,ty) -> Some (DArray, Array.to_list t @ [def ; ty]) in pat_of_constr c let empty = TDnet.empty let add (c:constr) (id:Ident.t) (dn:t) = let (ctx, c) = Term.decompose_prod_decls c in let c = TDnet.pattern pat_of_constr c in TDnet.add dn c id ... tn ] ) - > ( [ c , t1, ... ,tn-1],tn ) App(c,[|| ] ) - > ( [ ] , c ) App(c,[||]) -> ([],c) *) let split_app sigma c = match EConstr.kind sigma c with App(c,l) -> let len = Array.length l in if Int.equal len 0 then ([],c) else let last = Array.get l (len-1) in let prev = Array.sub l 0 (len-1) in c::(Array.to_list prev), last | _ -> assert false exception CannotFilter let filtering env sigma ctx cv_pb c1 c2 = let open EConstr in let open Vars in let evm = ref Evar.Map.empty in let define cv_pb e1 ev c1 = try let (e2,c2) = Evar.Map.find ev !evm in let shift = e1 - e2 in if Termops.constr_cmp env sigma cv_pb c1 (lift shift c2) then () else raise CannotFilter with Not_found -> evm := Evar.Map.add ev (e1,c1) !evm in let rec aux ctx cv_pb c1 c2 = match EConstr.kind sigma c1, EConstr.kind sigma c2 with | App _, App _ -> let ((p1,l1),(p2,l2)) = (split_app sigma c1),(split_app sigma c2) in let () = aux ctx cv_pb l1 l2 in begin match p1, p2 with | [], [] -> () | (h1 :: p1), (h2 :: p2) -> aux ctx cv_pb (applist (h1, p1)) (applist (h2, p2)) | _ -> assert false end | Prod (n,t1,c1), Prod (_,t2,c2) -> aux ctx cv_pb t1 t2; aux (ctx + 1) cv_pb c1 c2 | _, Evar (ev,_) -> define cv_pb ctx ev c1 | Evar (ev,_), _ -> define cv_pb ctx ev c2 | _ -> if Termops.compare_constr_univ env sigma (fun pb c1 c2 -> aux ctx pb c1 c2; true) cv_pb c1 c2 then () else raise CannotFilter in try let () = aux ctx cv_pb c1 c2 in true with CannotFilter -> false let align_prod_letin sigma c a = let (lc,_) = EConstr.decompose_prod_decls sigma c in let (l,a) = EConstr.decompose_prod_decls sigma a in let lc = List.length lc in let n = List.length l in if n < lc then invalid_arg "align_prod_letin"; let l1 = CList.firstn lc l in n - lc, EConstr.it_mkProd_or_LetIn a l1 let decomp pat = match pat_of_constr pat with | None -> Dn.Everything | Some (lbl, args) -> Dn.Label (lbl, args) let search_pattern env dn cpat = let _dctx, dpat = Term.decompose_prod_decls cpat in let whole_c = EConstr.of_constr cpat in List.fold_left (fun acc id -> let c_id = EConstr.of_constr @@ Ident.constr_of id in let (ctx,wc) = FIXME with Invalid_argument _ -> 0, c_id in if filtering env Evd.empty ctx Reduction.CUMUL whole_c wc then id :: acc else acc ) (TDnet.lookup dn decomp dpat) [] let find_all dn = TDnet.lookup dn (fun () -> Everything) () end type rewrite_db = { rdb_hintdn : HintDN.t; rdb_order : int KNmap.t; rdb_maxuid : int; } let empty_rewrite_db = { rdb_hintdn = HintDN.empty; rdb_order = KNmap.empty; rdb_maxuid = 0; } let rewtab = Summary.ref (String.Map.empty : rewrite_db String.Map.t) ~name:"autorewrite" let raw_find_base bas = String.Map.find bas !rewtab let find_base bas = try raw_find_base bas with Not_found -> user_err (str "Rewriting base " ++ str bas ++ str " does not exist.") let find_rewrites bas = let db = find_base bas in let sort r1 r2 = Int.compare (KNmap.find r2.rew_id db.rdb_order) (KNmap.find r1.rew_id db.rdb_order) in List.sort sort (HintDN.find_all db.rdb_hintdn) let find_matches env bas pat = let base = find_base bas in let res = HintDN.search_pattern env base.rdb_hintdn pat in let sort r1 r2 = Int.compare (KNmap.find r2.rew_id base.rdb_order) (KNmap.find r1.rew_id base.rdb_order) in List.sort sort res let print_rewrite_hintdb bas = let env = Global.env () in let sigma = Evd.from_env env in (str "Database " ++ str bas ++ fnl () ++ prlist_with_sep fnl (fun h -> str (if h.rew_l2r then "rewrite -> " else "rewrite <- ") ++ Printer.pr_lconstr_env env sigma h.rew_lemma ++ str " of type " ++ Printer.pr_lconstr_env env sigma h.rew_type ++ Option.cata (fun tac -> str " then use tactic " ++ Pputils.pr_glb_generic env sigma tac) (mt ()) h.rew_tac) (find_rewrites bas)) type raw_rew_rule = (constr Univ.in_universe_context_set * bool * Genarg.raw_generic_argument option) CAst.t let tclMAP_rev f args = List.fold_left (fun accu arg -> Tacticals.tclTHEN accu (f arg)) (Proofview.tclUNIT ()) args Applies all the rules of one base let one_base where conds tac_main bas = let lrul = find_rewrites bas in let rewrite dir c tac = let c = (EConstr.of_constr c, Tactypes.NoBindings) in general_rewrite ~where ~l2r:dir AllOccurrences ~freeze:true ~dep:false ~with_evars:false ~tac:(tac, conds) c in let try_rewrite h tc = Proofview.Goal.enter begin fun gl -> let sigma = Proofview.Goal.sigma gl in let subst, ctx' = UnivGen.fresh_universe_context_set_instance h.rew_ctx in let c' = Vars.subst_univs_level_constr subst h.rew_lemma in let sigma = Evd.merge_context_set Evd.univ_flexible sigma ctx' in Proofview.tclTHEN (Proofview.Unsafe.tclEVARS sigma) (rewrite h.rew_l2r c' tc) end in let open Proofview.Notations in Proofview.tclProofInfo [@ocaml.warning "-3"] >>= fun (_name, poly) -> let eval h = let tac = match h.rew_tac with | None -> Proofview.tclUNIT () | Some (Genarg.GenArg (Genarg.Glbwit wit, tac)) -> let ist = { Geninterp.lfun = Id.Map.empty ; poly ; extra = Geninterp.TacStore.empty } in Ftactic.run (Geninterp.interp wit ist tac) (fun _ -> Proofview.tclUNIT ()) in Tacticals.tclREPEAT_MAIN (Tacticals.tclTHENFIRST (try_rewrite h tac) tac_main) in let lrul = tclMAP_rev eval lrul in Tacticals.tclREPEAT_MAIN (Proofview.tclPROGRESS lrul) The AutoRewrite tactic let autorewrite ?(conds=Naive) tac_main lbas = Tacticals.tclREPEAT_MAIN (Proofview.tclPROGRESS (tclMAP_rev (fun bas -> (one_base None conds tac_main bas)) lbas)) let autorewrite_multi_in ?(conds=Naive) idl tac_main lbas = Proofview.Goal.enter begin fun gl -> let _ = List.map (fun id -> Tacmach.pf_get_hyp id gl) idl in Tacticals.tclMAP (fun id -> Tacticals.tclREPEAT_MAIN (Proofview.tclPROGRESS (tclMAP_rev (fun bas -> (one_base (Some id) conds tac_main bas)) lbas))) idl end let autorewrite_in ?(conds=Naive) id = autorewrite_multi_in ~conds [id] let gen_auto_multi_rewrite conds tac_main lbas cl = let try_do_hyps treat_id l = autorewrite_multi_in ~conds (List.map treat_id l) tac_main lbas in let concl_tac = (if cl.concl_occs != NoOccurrences then autorewrite ~conds tac_main lbas else Proofview.tclUNIT ()) in if not (Locusops.is_all_occurrences cl.concl_occs) && cl.concl_occs != NoOccurrences then let info = Exninfo.reify () in Tacticals.tclZEROMSG ~info (str"The \"at\" syntax isn't available yet for the autorewrite tactic.") else match cl.onhyps with | Some [] -> concl_tac | Some l -> Tacticals.tclTHENFIRST concl_tac (try_do_hyps (fun ((_,id),_) -> id) l) | None -> let hyp_tac = Proofview.Goal.enter begin fun gl -> let ids = Tacmach.pf_ids_of_hyps gl in try_do_hyps (fun id -> id) ids end in Tacticals.tclTHENFIRST concl_tac hyp_tac let auto_multi_rewrite ?(conds=Naive) lems cl = Proofview.wrap_exceptions (fun () -> gen_auto_multi_rewrite conds (Proofview.tclUNIT()) lems cl) let fresh_key = let id = Summary.ref ~name:"REWHINT-COUNTER" 0 in fun () -> let cur = incr id; !id in let lbl = Id.of_string ("_" ^ string_of_int cur) in let kn = Lib.make_kn lbl in let (mp, _) = KerName.repr kn in We embed the full path of the kernel name in the label so that the identifier should be unique . This ensures that including two modules together wo n't confuse the corresponding labels . the identifier should be unique. This ensures that including two modules together won't confuse the corresponding labels. *) let lbl = Id.of_string_soft (Printf.sprintf "%s#%i" (ModPath.to_string mp) cur) in KerName.make mp (Label.of_id lbl) let auto_multi_rewrite_with ?(conds=Naive) tac_main lbas cl = let onconcl = match cl.Locus.concl_occs with NoOccurrences -> false | _ -> true in match onconcl,cl.Locus.onhyps with | false,Some [_] | true,Some [] | false,Some [] -> autorewrite with .... in clause using tac n'est sur que si clause represente soit le but soit UNE hypothese si clause represente soit le but soit UNE hypothese *) Proofview.wrap_exceptions (fun () -> gen_auto_multi_rewrite conds tac_main lbas cl) | _ -> let info = Exninfo.reify () in Tacticals.tclZEROMSG ~info (strbrk "autorewrite .. in .. using can only be used either with a unique hypothesis or on the conclusion.") let cache_hintrewrite (rbase,lrl) = let base = try raw_find_base rbase with Not_found -> empty_rewrite_db in let fold accu r = { rdb_hintdn = HintDN.add r.rew_pat r accu.rdb_hintdn; rdb_order = KNmap.add r.rew_id accu.rdb_maxuid accu.rdb_order; rdb_maxuid = accu.rdb_maxuid + 1; } in let base = List.fold_left fold base lrl in rewtab := String.Map.add rbase base !rewtab let subst_hintrewrite (subst,(rbase,list as node)) = let subst_hint subst hint = let id' = subst_kn subst hint.rew_id in let cst' = subst_mps subst hint.rew_lemma in let typ' = subst_mps subst hint.rew_type in let pat' = subst_mps subst hint.rew_pat in let t' = Option.Smart.map (Genintern.generic_substitute subst) hint.rew_tac in if hint.rew_id == id' && hint.rew_lemma == cst' && hint.rew_type == typ' && hint.rew_tac == t' && hint.rew_pat == pat' then hint else { hint with rew_lemma = cst'; rew_type = typ'; rew_pat = pat'; rew_tac = t' } in let list' = List.Smart.map (fun h -> subst_hint subst h) list in if list' == list then node else (rbase,list') let inGlobalHintRewrite : string * rew_rule list -> Libobject.obj = let open Libobject in declare_object @@ superglobal_object_nodischarge "HINT_REWRITE_GLOBAL" ~cache:cache_hintrewrite ~subst:(Some subst_hintrewrite) let inExportHintRewrite : string * rew_rule list -> Libobject.obj = let open Libobject in declare_object @@ global_object_nodischarge ~cat:Hints.hint_cat "HINT_REWRITE_EXPORT" ~cache:cache_hintrewrite ~subst:(Some subst_hintrewrite) type hypinfo = { hyp_ty : EConstr.types; hyp_pat : EConstr.constr; } let decompose_applied_relation env sigma c ctype left2right = let find_rel ty = let sigma, ty = EClause.make_evar_clause env sigma ty in let (_, args) = Termops.decompose_app_vect sigma ty.EClause.cl_concl in let len = Array.length args in if 2 <= len then let c1 = args.(len - 2) in let c2 = args.(len - 1) in Some (if left2right then c1 else c2) else None in match find_rel ctype with | Some c -> Some { hyp_pat = c; hyp_ty = ctype } | None -> let ctype = EConstr.it_mkProd_or_LetIn t' ctx in match find_rel ctype with | Some c -> Some { hyp_pat = c; hyp_ty = ctype } | None -> None let find_applied_relation ?loc env sigma c left2right = let ctype = Retyping.get_type_of env sigma (EConstr.of_constr c) in match decompose_applied_relation env sigma c ctype left2right with | Some c -> c | None -> user_err ?loc (str"The type" ++ spc () ++ Printer.pr_econstr_env env sigma ctype ++ spc () ++ str"of this term does not end with an applied relation.") let default_hint_rewrite_locality () = if Global.sections_are_opened () then Hints.Local else Hints.Export let add_rew_rules ~locality base lrul = let env = Global.env () in let sigma = Evd.from_env env in let ist = Genintern.empty_glob_sign (Global.env ()) in let intern tac = snd (Genintern.generic_intern ist tac) in let map {CAst.loc;v=((c,ctx),b,t)} = let sigma = Evd.merge_context_set Evd.univ_rigid sigma ctx in let info = find_applied_relation ?loc env sigma c b in let pat = EConstr.Unsafe.to_constr info.hyp_pat in let uid = fresh_key () in { rew_id = uid; rew_lemma = c; rew_type = EConstr.Unsafe.to_constr info.hyp_ty; rew_pat = pat; rew_ctx = ctx; rew_l2r = b; rew_tac = Option.map intern t } in let lrul = List.map map lrul in let open Hints in match locality with | Local -> cache_hintrewrite (base,lrul) | SuperGlobal -> let () = if Global.sections_are_opened () then CErrors.user_err Pp.(str "This command does not support the global attribute in sections."); in Lib.add_leaf (inGlobalHintRewrite (base,lrul)) | Export -> let () = if Global.sections_are_opened () then CErrors.user_err Pp.(str "This command does not support the export attribute in sections."); in Lib.add_leaf (inExportHintRewrite (base,lrul))
0edc263f6457361cde39429805a05a4cfb327ec68d8eecfc7d513b4610902fd8
engstrand-config/guix-dotfiles
documents.scm
(define-module (engstrand features documents) #:use-module (guix gexp) #:use-module (rde features) #:use-module (rde features predicates) #:use-module (gnu packages pdf) #:use-module (gnu services) #:use-module (guix packages) #:use-module (gnu home services) #:use-module (gnu packages tex) #:use-module (gnu packages python-xyz) #:use-module (engstrand utils) #:use-module (engstrand packages documents) #:export ( feature-zathura feature-sioyek feature-latex)) NOTE : zathura plugins uses the ZATHURA_PLUGINS_PATH environment variable ;; for linking to installed plugins. Therefore, you will need to restart ;; the session after installing for the plugin to be loaded correctly. (define* (feature-zathura #:key (default-reader? #f) (zathura-pdf-plugin zathura-pdf-mupdf)) "Setup zathura, a minimal document viewer." (ensure-pred boolean? default-reader?) (ensure-pred package? zathura-pdf-plugin) (define (get-home-services config) "Return a list of system services required by zathura" (list (when default-reader? (simple-service 'set-zathura-environment-variable home-environment-variables-service-type `(("READER" . ,(file-append zathura "/bin/zathura"))))) (simple-service 'add-zathura-home-packages-to-profile home-profile-service-type (list zathura zathura-pdf-plugin)))) (feature (name 'zathura) (home-services-getter get-home-services))) (define* (feature-sioyek #:key (default-reader? #f)) "Setup zathura, a minimal document viewer." (ensure-pred boolean? default-reader?) (define (get-home-services config) "Return a list of system services required by sioyek" (define package (if (get-value 'wayland config) sioyek/wayland sioyek)) (list (when default-reader? (simple-service 'set-sioyek-environment-variable home-environment-variables-service-type `(("READER" . ,(file-append package "/bin/sioyek"))))) (simple-service 'add-sioyek-home-packages-to-profile home-profile-service-type (list package)))) (feature (name 'sioyek) (home-services-getter get-home-services))) (define* (feature-latex) (define (get-home-services config) (list (simple-service 'add-latex-home-packages-to-profile home-profile-service-type (list texlive texlive-latex-base python-pygments)))) (feature (name 'latex) (home-services-getter get-home-services)))
null
https://raw.githubusercontent.com/engstrand-config/guix-dotfiles/1b17ea2732baea38b9ed19a3c18eed850acd175c/engstrand/features/documents.scm
scheme
for linking to installed plugins. Therefore, you will need to restart the session after installing for the plugin to be loaded correctly.
(define-module (engstrand features documents) #:use-module (guix gexp) #:use-module (rde features) #:use-module (rde features predicates) #:use-module (gnu packages pdf) #:use-module (gnu services) #:use-module (guix packages) #:use-module (gnu home services) #:use-module (gnu packages tex) #:use-module (gnu packages python-xyz) #:use-module (engstrand utils) #:use-module (engstrand packages documents) #:export ( feature-zathura feature-sioyek feature-latex)) NOTE : zathura plugins uses the ZATHURA_PLUGINS_PATH environment variable (define* (feature-zathura #:key (default-reader? #f) (zathura-pdf-plugin zathura-pdf-mupdf)) "Setup zathura, a minimal document viewer." (ensure-pred boolean? default-reader?) (ensure-pred package? zathura-pdf-plugin) (define (get-home-services config) "Return a list of system services required by zathura" (list (when default-reader? (simple-service 'set-zathura-environment-variable home-environment-variables-service-type `(("READER" . ,(file-append zathura "/bin/zathura"))))) (simple-service 'add-zathura-home-packages-to-profile home-profile-service-type (list zathura zathura-pdf-plugin)))) (feature (name 'zathura) (home-services-getter get-home-services))) (define* (feature-sioyek #:key (default-reader? #f)) "Setup zathura, a minimal document viewer." (ensure-pred boolean? default-reader?) (define (get-home-services config) "Return a list of system services required by sioyek" (define package (if (get-value 'wayland config) sioyek/wayland sioyek)) (list (when default-reader? (simple-service 'set-sioyek-environment-variable home-environment-variables-service-type `(("READER" . ,(file-append package "/bin/sioyek"))))) (simple-service 'add-sioyek-home-packages-to-profile home-profile-service-type (list package)))) (feature (name 'sioyek) (home-services-getter get-home-services))) (define* (feature-latex) (define (get-home-services config) (list (simple-service 'add-latex-home-packages-to-profile home-profile-service-type (list texlive texlive-latex-base python-pygments)))) (feature (name 'latex) (home-services-getter get-home-services)))
e2f3dc1aa7a51699f4e42773ef6fcf442c8e08fb253fbeef410292445f5e89c3
racket/racket7
struct.rkt
#lang racket/base (require "private/custom-write.rkt" racket/contract/base) (provide (contract-out [make-constructor-style-printer (-> (-> any/c (or/c symbol? string?)) (-> any/c sequence?) (-> any/c output-port? (or/c #t #f 0 1) void?))]) struct->list) (define dummy-value (box 'dummy)) ;; struct->list : struct? ;; #:on-opaque (or/c 'error 'return-false 'skip) - > ( listof any / c ) (define (struct->list s #:on-opaque [on-opaque 'error]) (define error-on-opaque? (eq? on-opaque 'error)) (let ([vec (struct->vector s dummy-value)]) ;; go through vector backwards, don't traverse 0 (struct name) (let loop ([index (sub1 (vector-length vec))] [elems null] [any-opaque? #f]) (cond [(positive? index) (let ([elem (vector-ref vec index)]) (cond [(eq? elem dummy-value) (when error-on-opaque? (raise-type-error 'struct->list "non-opaque struct" s)) (loop (sub1 index) elems #t)] [else (loop (sub1 index) (cons elem elems) any-opaque?)]))] [else (cond [(and any-opaque? (eq? on-opaque 'return-false)) #f] [else elems])]))))
null
https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/collects/racket/struct.rkt
racket
struct->list : struct? #:on-opaque (or/c 'error 'return-false 'skip) go through vector backwards, don't traverse 0 (struct name)
#lang racket/base (require "private/custom-write.rkt" racket/contract/base) (provide (contract-out [make-constructor-style-printer (-> (-> any/c (or/c symbol? string?)) (-> any/c sequence?) (-> any/c output-port? (or/c #t #f 0 1) void?))]) struct->list) (define dummy-value (box 'dummy)) - > ( listof any / c ) (define (struct->list s #:on-opaque [on-opaque 'error]) (define error-on-opaque? (eq? on-opaque 'error)) (let ([vec (struct->vector s dummy-value)]) (let loop ([index (sub1 (vector-length vec))] [elems null] [any-opaque? #f]) (cond [(positive? index) (let ([elem (vector-ref vec index)]) (cond [(eq? elem dummy-value) (when error-on-opaque? (raise-type-error 'struct->list "non-opaque struct" s)) (loop (sub1 index) elems #t)] [else (loop (sub1 index) (cons elem elems) any-opaque?)]))] [else (cond [(and any-opaque? (eq? on-opaque 'return-false)) #f] [else elems])]))))
c698d57281db9436de2edc49f78092e6df28680aaa40aa7c7d553efd7c2d1240
simmone/racket-simple-xlsx
date-read-and-write-test.rkt
#lang racket (require rackunit/text-ui rackunit) (require racket/date) (require "../../../main.rkt") (require racket/runtime-path) (define-runtime-path date_write_file "date_write.xlsx") (define-runtime-path date_read_and_write_file "date_read_and_write.xlsx") (define test-writer (test-suite "test-writer" (test-case "test-date" (dynamic-wind (lambda () (void)) (lambda () (write-xlsx date_write_file (lambda () (add-data-sheet "Sheet1" (list (list (seconds->date (find-seconds 0 0 0 17 9 2018 #f)) (seconds->date (find-seconds 0 0 0 17 9 2018 #f)) (seconds->date (find-seconds 0 0 0 17 9 2018 #f)) (seconds->date (find-seconds 0 0 0 17 9 2018 #f)) (seconds->date (find-seconds 0 0 0 17 9 2018 #f))) )) (with-sheet (lambda () (set-row-range-date-style "1" "yyyy-mm-dd") (set-col-range-width "1-5" 30) )) )) (read-xlsx date_write_file (lambda () (check-equal? (get-sheet-name-list) '("Sheet1")) (with-sheet-ref 0 (lambda () (check-equal? (get-row 1) '(43360 43360 43360 43360 43360)))))) (read-and-write-xlsx date_write_file date_read_and_write_file (lambda () (check-equal? (get-sheet-name-list) '("Sheet1")) (with-sheet-ref 0 (lambda () (check-equal? (get-row 1) '(43360 43360 43360 43360 43360)) (set-row-range-date-style "1" "yyyy/mm/dd") (set-row-range-alignment-style "1" "center" "center") )) )) ) (lambda () ;; (void) (delete-file date_write_file) (delete-file date_read_and_write_file) ) )) )) (run-tests test-writer)
null
https://raw.githubusercontent.com/simmone/racket-simple-xlsx/e0ac3190b6700b0ee1dd80ed91a8f4318533d012/simple-xlsx/tests/write-and-read/date/date-read-and-write-test.rkt
racket
(void)
#lang racket (require rackunit/text-ui rackunit) (require racket/date) (require "../../../main.rkt") (require racket/runtime-path) (define-runtime-path date_write_file "date_write.xlsx") (define-runtime-path date_read_and_write_file "date_read_and_write.xlsx") (define test-writer (test-suite "test-writer" (test-case "test-date" (dynamic-wind (lambda () (void)) (lambda () (write-xlsx date_write_file (lambda () (add-data-sheet "Sheet1" (list (list (seconds->date (find-seconds 0 0 0 17 9 2018 #f)) (seconds->date (find-seconds 0 0 0 17 9 2018 #f)) (seconds->date (find-seconds 0 0 0 17 9 2018 #f)) (seconds->date (find-seconds 0 0 0 17 9 2018 #f)) (seconds->date (find-seconds 0 0 0 17 9 2018 #f))) )) (with-sheet (lambda () (set-row-range-date-style "1" "yyyy-mm-dd") (set-col-range-width "1-5" 30) )) )) (read-xlsx date_write_file (lambda () (check-equal? (get-sheet-name-list) '("Sheet1")) (with-sheet-ref 0 (lambda () (check-equal? (get-row 1) '(43360 43360 43360 43360 43360)))))) (read-and-write-xlsx date_write_file date_read_and_write_file (lambda () (check-equal? (get-sheet-name-list) '("Sheet1")) (with-sheet-ref 0 (lambda () (check-equal? (get-row 1) '(43360 43360 43360 43360 43360)) (set-row-range-date-style "1" "yyyy/mm/dd") (set-row-range-alignment-style "1" "center" "center") )) )) ) (lambda () (delete-file date_write_file) (delete-file date_read_and_write_file) ) )) )) (run-tests test-writer)
9d6b6522bdbb6978dbbb6b0d2dcf41a7c96d2c6913f18b3fe8e1566c6c29246d
hypernumbers/hypernumbers
hnfuns_bootstrap.erl
@author ( C ) 2012 - 2014 , Hypernumbers Ltd %%% @doc Make Bootstrap components available %%% %%% @end Created : 19 May 2012 by %%%------------------------------------------------------------------- %%% %%% LICENSE %%% %%% 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 version 3 %%% %%% 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(hnfuns_bootstrap). -export([ 'breadcrumbs.'/1, 'small.goto.zdropdown'/1, 'large.goto.zdropdown'/1, 'small.goto.dropdown'/1, 'large.goto.dropdown'/1, 'small.buttonbar.'/1, 'large.buttonbar.'/1, 'small.goto.button'/1, 'large.goto.button'/1 ]). -include("spriki.hrl"). -include("errvals.hrl"). -define(SEP," <span class='divider'>/</span> "). 'breadcrumbs.'([W]) -> [W2] = typechecks:std_ints([W]), Path = get(path), HTML = breadcrumbs2(Path), Resize = #resize{width = W2, height = 2}, Preview = "Breadcrumbs", CSS = ["/bootstrap/css/bootstrap.css", "/bootstrap/css/helper.css"], Incs = #incs{css = CSS}, #spec_val{val = HTML, sp_incs = Incs, preview = Preview, resize = Resize}. breadcrumbs2(Path) -> Trail = trail2(lists:reverse(Path), []), "<ul class='breadcrumb'>" ++ Trail ++ "</ul>". trail2([], Acc) -> Trail2 = ["<a href='/'>home</a>" | Acc], "<li>" ++ string:join(Trail2, ?SEP) ++ "</li>"; trail2([H | T] = L, Acc) -> Path = "/" ++ string:join(lists:reverse(L), "/") ++ "/", NewAcc = " <a class='crumb' href='" ++ Path ++ "'>" ++ H ++ "</a>", trail2(T, [NewAcc | Acc]). 'small.goto.zdropdown'([Text, Colour, ZQuery]) -> 'small.goto.zdropdown'([Text, Colour, ZQuery, 0]); 'small.goto.zdropdown'([Text, Colour, ZQuery, Style]) -> zdropdown(1, 1, Text, Colour, ZQuery, Style, "btn-small hn-btn-small"). 'large.goto.zdropdown'([Text, Colour, ZQuery]) -> 'large.goto.zdropdown'([Text, Colour, ZQuery, 0]); 'large.goto.zdropdown'([Text, Colour, ZQuery, Style]) -> zdropdown(2, 2, Text, Colour, ZQuery, Style, "btn-large hn-btn-large"). zdropdown(W, H, Text, Colour, ZQuery, Style, Button) -> [Text2] = typechecks:throw_std_strs([Text]), [C2] = typechecks:throw_std_ints([Colour]), C3 = bootstrap_utils:get_colour(C2), [S2] = typechecks:throw_std_ints([Style]), S3 = case S2 of 0 -> vals; 1 -> paths; _ -> ?ERR_VAL end, ZQuery2 = get_z(fun make_links/2, ZQuery, S3), HTML = "<a class='btn " ++ Button ++ " dropdown-toggle " ++ C3 ++ "' " ++ "data-toggle='dropdown' href='#'>" ++ Text2 ++ "<span class='caret'></span>" ++ "</a>" ++ ZQuery2, Resize = #resize{width = W, height = H}, Preview = "Dropdown: " ++ contact_utils:rightsize(Text2, 30), JS = ["/bootstrap/js/bootstrap.js", "/bootstrap/js/helper.js"], Reload = ["HN.BootstrapHelper.reload();"], CSS = ["/bootstrap/css/bootstrap.css", "/bootstrap/css/helper.css"], Incs = #incs{js = JS, js_reload = Reload, css = CSS}, #spec_val{val = lists:flatten(HTML), sp_incs = Incs, resize = Resize, preview = Preview}. 'small.goto.dropdown'([Text, Colour | Rest]) -> dropdown(1, 1, Text, Colour, Rest, "btn-small hn-btn-small"). 'large.goto.dropdown'([Text, Colour | Rest]) -> dropdown(2, 2, Text, Colour, Rest, "btn-large hn-btn-large"). dropdown(W, H, Text, Colour, Rest, Button) -> [Text2] = typechecks:throw_std_strs([Text]), [C2] = typechecks:throw_std_ints([Colour]), C3 = bootstrap_utils:get_colour(C2), Rest2 = typechecks:throw_std_strs(Rest), Drop = make_dropdown(Rest2, []), HTML = "<a class='btn " ++ Button ++ " dropdown-toggle " ++ C3 ++ "' " ++ "data-toggle='dropdown' href='#'>" ++ Text2 ++ "<span class='caret'></span>" ++ "</a>" ++ Drop, Preview = "Dropdown: " ++ contact_utils:rightsize(Text2, 30), Resize = #resize{width = W, height = H}, JS = ["/bootstrap/js/bootstrap.js", "/bootstrap/js/helper.js"], Reload = ["HN.BootstrapHelper.reload();"], CSS = ["/bootstrap/css/bootstrap.css", "/bootstrap/css/helper.css"], Incs = #incs{js = JS, js_reload = Reload, css = CSS}, #spec_val{val = lists:flatten(HTML), resize = Resize, sp_incs = Incs, preview = Preview}. 'small.goto.button'([Link, Text]) -> 'small.goto.button'([Link, Text, 0]); 'small.goto.button'([Link, Text, Colour]) -> button("btn-small hn-btn-small", "Small", 1, 2, Link, Text, Colour). 'large.goto.button'([Link, Text]) -> 'large.goto.button'([Link, Text, 0]); 'large.goto.button'([Link, Text, Colour]) -> button("btn-large hn-btn-large", "Large", 2, 2, Link, Text, Colour). 'small.buttonbar.'([W | Rest]) -> buttonbar("btn-small", "Small", W, 2, Rest). 'large.buttonbar.'([W | Rest]) -> buttonbar("btn-large", "Large", W, 3, Rest). button(Class, Size, W, H, Link, Text, Colour) -> [W2, H2] = typechecks:throw_std_ints([W, H]), [Link2, Text2] = typechecks:std_strs([Link, Text]), [C2] = typechecks:std_ints([Colour]), C3 = bootstrap_utils:get_colour(C2), [Btn] = make_buttons([Link2, Text2], Class ++ " " ++ C3, []), Resize = #resize{width = W2, height = H2}, Preview = Size ++ " Menu Buttons: " ++ Text2, JS = ["/bootstrap/js/bootstrap.js", "/bootstrap/js/helper.js"], Reload = ["HN.BootstrapHelper.reload();"], CSS = ["/bootstrap/css/bootstrap.css", "/bootstrap/css/helper.css"], Incs = #incs{js = JS, js_reload = Reload, css = CSS}, #spec_val{val = Btn, resize = Resize, sp_incs = Incs, preview = Preview}. buttonbar(Class, Size, W, H, Rest) -> [W2, H2] = typechecks:std_ints([W, H]), Rest2 = typechecks:throw_std_strs(Rest), Btns = make_buttons(Rest2, Class, []), HTML = lists:flatten("<div class='btn-group'>" ++ Btns ++ "</div>"), Resize = #resize{width = W2, height = H2}, Preview = Size ++ " Menu Buttons: " ++ get_titles(Rest2, []), JS = ["/bootstrap/js/bootstrap.js", "/bootstrap/js/helper.js"], Reload = ["HN.BootstrapHelper.reload();"], CSS = ["/bootstrap/css/bootstrap.css", "/bootstrap/css/helper.css"], Incs = #incs{js = JS, js_reload = Reload, css = CSS}, #spec_val{val = HTML, sp_incs = Incs, resize = Resize, preview = Preview}. % will throw an error if odd length list passed in get_titles([], Acc) -> lists:flatten(string:join(lists:reverse(Acc), " ")); get_titles([_, T | R], Acc) -> get_titles(R, [T | Acc]). % will throw an error if odd length list passed in make_dropdown([], Acc) -> "<ul class='dropdown-menu'>" ++ lists:reverse(Acc) ++ "</ul>"; make_dropdown([Link, Text | Rest], Acc) -> NewAcc = "<li><a " ++ "href='" ++ Link ++ "'>" ++ Text ++ "</a></li>", make_dropdown(Rest, [NewAcc | Acc]). % will throw an error if odd length list passed in make_buttons([], _Class, Acc) -> lists:reverse(Acc); make_buttons([Link, Text | Rest], Class, Acc) -> C = case Class of [] -> "btn"; _ -> "btn " end, NewAcc = "<a class='" ++ C ++ Class ++ "' " ++ "href='" ++ Link ++ "'>" ++ Text ++ "</a>", make_buttons(Rest, Class, [NewAcc | Acc]). get_z(Fun, Z, Style) -> case muin_collect:col([Z], [fetch, fetch_z_debug, blank_as_str], [return_errors]) of [{zeds, Matches, _, []}] -> Fun(Matches, Style); [{zeds, _, _, [H | _]}] -> {error, _, {errval, Err}} = H, Err end. make_links(List, paths) -> make_paths(List, []); make_links(List, vals) -> make_vals(List, []). make_paths([], Acc) -> "<ul class='dropdown-menu'>" ++ lists:flatten(lists:reverse(Acc)) ++ "</ul>"; make_paths([{{Path, _Cell}, _Val} | T], Acc) -> P2 = hn_util:list_to_path(Path), NewAcc = "<li><a href='" ++ P2 ++ "'>" ++ P2 ++ "</a></li>", make_paths(T, [NewAcc | Acc]). make_vals([], Acc) -> "<ul class='dropdown-menu'>" ++ lists:flatten(lists:reverse(Acc)) ++ "</ul>"; make_vals([{{Path, _Cell}, Val} | T], Acc) -> P2 = hn_util:list_to_path(Path), Val2 = case Val of blank -> "blank"; _ -> tconv:to_s(Val) end, NewAcc = "<li><a href='" ++ P2 ++ "'>" ++ Val2 ++ "</a></li>", make_vals(T, [NewAcc | Acc]).
null
https://raw.githubusercontent.com/hypernumbers/hypernumbers/281319f60c0ac60fb009ee6d1e4826f4f2d51c4e/lib/formula_engine-1.0/src/hnfuns_bootstrap.erl
erlang
@doc Make Bootstrap components available @end ------------------------------------------------------------------- LICENSE This program is free software: you can redistribute it and/or modify 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. along with this program. If not, see </>. ------------------------------------------------------------------- will throw an error if odd length list passed in will throw an error if odd length list passed in will throw an error if odd length list passed in
@author ( C ) 2012 - 2014 , Hypernumbers Ltd Created : 19 May 2012 by it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 You should have received a copy of the GNU Affero General Public License -module(hnfuns_bootstrap). -export([ 'breadcrumbs.'/1, 'small.goto.zdropdown'/1, 'large.goto.zdropdown'/1, 'small.goto.dropdown'/1, 'large.goto.dropdown'/1, 'small.buttonbar.'/1, 'large.buttonbar.'/1, 'small.goto.button'/1, 'large.goto.button'/1 ]). -include("spriki.hrl"). -include("errvals.hrl"). -define(SEP," <span class='divider'>/</span> "). 'breadcrumbs.'([W]) -> [W2] = typechecks:std_ints([W]), Path = get(path), HTML = breadcrumbs2(Path), Resize = #resize{width = W2, height = 2}, Preview = "Breadcrumbs", CSS = ["/bootstrap/css/bootstrap.css", "/bootstrap/css/helper.css"], Incs = #incs{css = CSS}, #spec_val{val = HTML, sp_incs = Incs, preview = Preview, resize = Resize}. breadcrumbs2(Path) -> Trail = trail2(lists:reverse(Path), []), "<ul class='breadcrumb'>" ++ Trail ++ "</ul>". trail2([], Acc) -> Trail2 = ["<a href='/'>home</a>" | Acc], "<li>" ++ string:join(Trail2, ?SEP) ++ "</li>"; trail2([H | T] = L, Acc) -> Path = "/" ++ string:join(lists:reverse(L), "/") ++ "/", NewAcc = " <a class='crumb' href='" ++ Path ++ "'>" ++ H ++ "</a>", trail2(T, [NewAcc | Acc]). 'small.goto.zdropdown'([Text, Colour, ZQuery]) -> 'small.goto.zdropdown'([Text, Colour, ZQuery, 0]); 'small.goto.zdropdown'([Text, Colour, ZQuery, Style]) -> zdropdown(1, 1, Text, Colour, ZQuery, Style, "btn-small hn-btn-small"). 'large.goto.zdropdown'([Text, Colour, ZQuery]) -> 'large.goto.zdropdown'([Text, Colour, ZQuery, 0]); 'large.goto.zdropdown'([Text, Colour, ZQuery, Style]) -> zdropdown(2, 2, Text, Colour, ZQuery, Style, "btn-large hn-btn-large"). zdropdown(W, H, Text, Colour, ZQuery, Style, Button) -> [Text2] = typechecks:throw_std_strs([Text]), [C2] = typechecks:throw_std_ints([Colour]), C3 = bootstrap_utils:get_colour(C2), [S2] = typechecks:throw_std_ints([Style]), S3 = case S2 of 0 -> vals; 1 -> paths; _ -> ?ERR_VAL end, ZQuery2 = get_z(fun make_links/2, ZQuery, S3), HTML = "<a class='btn " ++ Button ++ " dropdown-toggle " ++ C3 ++ "' " ++ "data-toggle='dropdown' href='#'>" ++ Text2 ++ "<span class='caret'></span>" ++ "</a>" ++ ZQuery2, Resize = #resize{width = W, height = H}, Preview = "Dropdown: " ++ contact_utils:rightsize(Text2, 30), JS = ["/bootstrap/js/bootstrap.js", "/bootstrap/js/helper.js"], Reload = ["HN.BootstrapHelper.reload();"], CSS = ["/bootstrap/css/bootstrap.css", "/bootstrap/css/helper.css"], Incs = #incs{js = JS, js_reload = Reload, css = CSS}, #spec_val{val = lists:flatten(HTML), sp_incs = Incs, resize = Resize, preview = Preview}. 'small.goto.dropdown'([Text, Colour | Rest]) -> dropdown(1, 1, Text, Colour, Rest, "btn-small hn-btn-small"). 'large.goto.dropdown'([Text, Colour | Rest]) -> dropdown(2, 2, Text, Colour, Rest, "btn-large hn-btn-large"). dropdown(W, H, Text, Colour, Rest, Button) -> [Text2] = typechecks:throw_std_strs([Text]), [C2] = typechecks:throw_std_ints([Colour]), C3 = bootstrap_utils:get_colour(C2), Rest2 = typechecks:throw_std_strs(Rest), Drop = make_dropdown(Rest2, []), HTML = "<a class='btn " ++ Button ++ " dropdown-toggle " ++ C3 ++ "' " ++ "data-toggle='dropdown' href='#'>" ++ Text2 ++ "<span class='caret'></span>" ++ "</a>" ++ Drop, Preview = "Dropdown: " ++ contact_utils:rightsize(Text2, 30), Resize = #resize{width = W, height = H}, JS = ["/bootstrap/js/bootstrap.js", "/bootstrap/js/helper.js"], Reload = ["HN.BootstrapHelper.reload();"], CSS = ["/bootstrap/css/bootstrap.css", "/bootstrap/css/helper.css"], Incs = #incs{js = JS, js_reload = Reload, css = CSS}, #spec_val{val = lists:flatten(HTML), resize = Resize, sp_incs = Incs, preview = Preview}. 'small.goto.button'([Link, Text]) -> 'small.goto.button'([Link, Text, 0]); 'small.goto.button'([Link, Text, Colour]) -> button("btn-small hn-btn-small", "Small", 1, 2, Link, Text, Colour). 'large.goto.button'([Link, Text]) -> 'large.goto.button'([Link, Text, 0]); 'large.goto.button'([Link, Text, Colour]) -> button("btn-large hn-btn-large", "Large", 2, 2, Link, Text, Colour). 'small.buttonbar.'([W | Rest]) -> buttonbar("btn-small", "Small", W, 2, Rest). 'large.buttonbar.'([W | Rest]) -> buttonbar("btn-large", "Large", W, 3, Rest). button(Class, Size, W, H, Link, Text, Colour) -> [W2, H2] = typechecks:throw_std_ints([W, H]), [Link2, Text2] = typechecks:std_strs([Link, Text]), [C2] = typechecks:std_ints([Colour]), C3 = bootstrap_utils:get_colour(C2), [Btn] = make_buttons([Link2, Text2], Class ++ " " ++ C3, []), Resize = #resize{width = W2, height = H2}, Preview = Size ++ " Menu Buttons: " ++ Text2, JS = ["/bootstrap/js/bootstrap.js", "/bootstrap/js/helper.js"], Reload = ["HN.BootstrapHelper.reload();"], CSS = ["/bootstrap/css/bootstrap.css", "/bootstrap/css/helper.css"], Incs = #incs{js = JS, js_reload = Reload, css = CSS}, #spec_val{val = Btn, resize = Resize, sp_incs = Incs, preview = Preview}. buttonbar(Class, Size, W, H, Rest) -> [W2, H2] = typechecks:std_ints([W, H]), Rest2 = typechecks:throw_std_strs(Rest), Btns = make_buttons(Rest2, Class, []), HTML = lists:flatten("<div class='btn-group'>" ++ Btns ++ "</div>"), Resize = #resize{width = W2, height = H2}, Preview = Size ++ " Menu Buttons: " ++ get_titles(Rest2, []), JS = ["/bootstrap/js/bootstrap.js", "/bootstrap/js/helper.js"], Reload = ["HN.BootstrapHelper.reload();"], CSS = ["/bootstrap/css/bootstrap.css", "/bootstrap/css/helper.css"], Incs = #incs{js = JS, js_reload = Reload, css = CSS}, #spec_val{val = HTML, sp_incs = Incs, resize = Resize, preview = Preview}. get_titles([], Acc) -> lists:flatten(string:join(lists:reverse(Acc), " ")); get_titles([_, T | R], Acc) -> get_titles(R, [T | Acc]). make_dropdown([], Acc) -> "<ul class='dropdown-menu'>" ++ lists:reverse(Acc) ++ "</ul>"; make_dropdown([Link, Text | Rest], Acc) -> NewAcc = "<li><a " ++ "href='" ++ Link ++ "'>" ++ Text ++ "</a></li>", make_dropdown(Rest, [NewAcc | Acc]). make_buttons([], _Class, Acc) -> lists:reverse(Acc); make_buttons([Link, Text | Rest], Class, Acc) -> C = case Class of [] -> "btn"; _ -> "btn " end, NewAcc = "<a class='" ++ C ++ Class ++ "' " ++ "href='" ++ Link ++ "'>" ++ Text ++ "</a>", make_buttons(Rest, Class, [NewAcc | Acc]). get_z(Fun, Z, Style) -> case muin_collect:col([Z], [fetch, fetch_z_debug, blank_as_str], [return_errors]) of [{zeds, Matches, _, []}] -> Fun(Matches, Style); [{zeds, _, _, [H | _]}] -> {error, _, {errval, Err}} = H, Err end. make_links(List, paths) -> make_paths(List, []); make_links(List, vals) -> make_vals(List, []). make_paths([], Acc) -> "<ul class='dropdown-menu'>" ++ lists:flatten(lists:reverse(Acc)) ++ "</ul>"; make_paths([{{Path, _Cell}, _Val} | T], Acc) -> P2 = hn_util:list_to_path(Path), NewAcc = "<li><a href='" ++ P2 ++ "'>" ++ P2 ++ "</a></li>", make_paths(T, [NewAcc | Acc]). make_vals([], Acc) -> "<ul class='dropdown-menu'>" ++ lists:flatten(lists:reverse(Acc)) ++ "</ul>"; make_vals([{{Path, _Cell}, Val} | T], Acc) -> P2 = hn_util:list_to_path(Path), Val2 = case Val of blank -> "blank"; _ -> tconv:to_s(Val) end, NewAcc = "<li><a href='" ++ P2 ++ "'>" ++ Val2 ++ "</a></li>", make_vals(T, [NewAcc | Acc]).
8d5c78d3f567b0c3b932c1681e04fa243839f460b4b731c3aab88bb2f2efb3ac
gothinkster/clojurescript-keechma-realworld-example-app
user_actions.cljs
(ns app.controllers.guest.user-actions (:require [keechma.next.controller :as ctrl] [keechma.next.controllers.pipelines :as pipelines] [keechma.pipelines.core :refer-macros [pipeline!]] [keechma.next.controllers.router :as router])) (derive :guest/user-actions ::pipelines/controller) (def redirect-to-register (pipeline! [_ {:keys [], :as ctrl}] (router/redirect! ctrl :router {:page "register"}))) (def pipelines {:toggle-favorite redirect-to-register, :toggle-follow redirect-to-register}) (defmethod ctrl/prep :guest/user-actions [ctrl] (pipelines/register ctrl pipelines))
null
https://raw.githubusercontent.com/gothinkster/clojurescript-keechma-realworld-example-app/f6d32f8eea5439b0b33df1afb89da6d27b7da66b/src/app/controllers/guest/user_actions.cljs
clojure
(ns app.controllers.guest.user-actions (:require [keechma.next.controller :as ctrl] [keechma.next.controllers.pipelines :as pipelines] [keechma.pipelines.core :refer-macros [pipeline!]] [keechma.next.controllers.router :as router])) (derive :guest/user-actions ::pipelines/controller) (def redirect-to-register (pipeline! [_ {:keys [], :as ctrl}] (router/redirect! ctrl :router {:page "register"}))) (def pipelines {:toggle-favorite redirect-to-register, :toggle-follow redirect-to-register}) (defmethod ctrl/prep :guest/user-actions [ctrl] (pipelines/register ctrl pipelines))
86a49b2228491fce4a161a076521fbb70be892fab2477f5c1f3ae27578073c0b
malcolmreynolds/GSLL
dilogarithm.lisp
Regression test DILOGARITHM for GSLL , automatically generated (in-package :gsl) (LISP-UNIT:DEFINE-TEST DILOGARITHM (LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 1.6449340668482264d0 7.304974700020789d-16) (MULTIPLE-VALUE-LIST (DILOGARITHM 1.0d0))) (LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST #C(-0.20561675835602822d0 0.915965594177219d0) #C(2.100180226255977d-15 7.618282373747058d-16)) (MULTIPLE-VALUE-LIST (DILOGARITHM #C(0.0d0 1.0d0)))))
null
https://raw.githubusercontent.com/malcolmreynolds/GSLL/2f722f12f1d08e1b9550a46e2a22adba8e1e52c4/tests/dilogarithm.lisp
lisp
Regression test DILOGARITHM for GSLL , automatically generated (in-package :gsl) (LISP-UNIT:DEFINE-TEST DILOGARITHM (LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 1.6449340668482264d0 7.304974700020789d-16) (MULTIPLE-VALUE-LIST (DILOGARITHM 1.0d0))) (LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST #C(-0.20561675835602822d0 0.915965594177219d0) #C(2.100180226255977d-15 7.618282373747058d-16)) (MULTIPLE-VALUE-LIST (DILOGARITHM #C(0.0d0 1.0d0)))))
30584248d6d48717392bb1d3b6dcf4324adf429b405a12a6f92921b00f0d4ae3
clj-commons/cljss
user.clj
(ns user (:require [figwheel-sidecar.repl-api :as f])) (defn start! [id] (f/start-figwheel! id) (f/cljs-repl)) (defn stop! [] (f/stop-figwheel!))
null
https://raw.githubusercontent.com/clj-commons/cljss/d2856688cf650babe518c798cf20e6bdb4227bb7/example/dev/user.clj
clojure
(ns user (:require [figwheel-sidecar.repl-api :as f])) (defn start! [id] (f/start-figwheel! id) (f/cljs-repl)) (defn stop! [] (f/stop-figwheel!))
b6b10d7e6a7ea03e7ae553a2efc8e671a2e6f2a3b88b3b83a0bc4befeb699209
projectcs13/sensor-cloud
vstreams_tests.erl
@author %% [www.csproj13.student.it.uu.se] %% @version 1.0 [ Copyright information ] %% %% @doc == datapoints_tests == %% This module contains several tests to test %% the virtual streams functionality. %% %% @end -module(vstreams_tests). -include_lib("eunit/include/eunit.hrl"). -define(WEBMACHINE_URL, api_help:get_webmachine_url()). -define(STREAMS_URL, ?WEBMACHINE_URL ++ "/streams/"). -define(VSTREAMS_URL, ?WEBMACHINE_URL ++ "/vstreams/"). -define(VSDATAPOINTS_URL, ?WEBMACHINE_URL ++ "/data/"). -define(TEST_VALUE, "1"). -define(INDEX, "sensorcloud"). %% @doc %% Function: init_test/0 %% Purpose: Used to start the inets to be able to do HTTP requests %% Returns: ok | {error, term()} %% %% Side effects: Start inets %% @end -spec init_test() -> ok | {error, term()}. init_test() -> inets:start(). %% @doc %% Function: post_test/0 %% Purpose: Test a post request %% Returns: ok | {error, term()} %% %% @end -spec post_test() -> ok | {error, term()}. post_test() -> {ok, {{_Version, 200, _ReasonPhrase}, _Headers, Body1}} = httpc:request(post, {?WEBMACHINE_URL++"/users", [],"application/json", "{\"username\" : \"vstreamuser\"}"}, [], []), UserId = lib_json:get_field(Body1,"_id"), api_help:refresh(), {ok, {{_Version2, 200, _ReasonPhrase2}, _Headers2, Body2}} = post_request(?STREAMS_URL, "application/json", "{ \"name\" : \"teststream1\", \"user_id\" : \"" ++ lib_json:to_string(UserId) ++ "\" }"), Streamid1 = lib_json:get_field(Body2, "_id"), api_help:refresh(), {ok, {{_Version3, 200, _ReasonPhrase3}, _Headers3, Body3}} = post_request(?STREAMS_URL, "application/json", "{ \"name\" : \"teststream2\", \"user_id\" : \"" ++ lib_json:to_string(UserId) ++ "\" }"), Streamid2 = lib_json:get_field(Body3, "_id"), api_help:refresh(), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid1) ++ "/data", "application/json", "{ \"value\":1}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid1) ++ "/data", "application/json", "{ \"value\":1}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid1) ++ "/data", "application/json", "{ \"value\":1}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid1) ++ "/data", "application/json", "{ \"value\":1}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid1) ++ "/data", "application/json", "{ \"value\":1}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid2) ++ "/data", "application/json", "{ \"value\":2}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid2) ++ "/data", "application/json", "{ \"value\":2}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid2) ++ "/data", "application/json", "{ \"value\":2}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid2) ++ "/data", "application/json", "{ \"value\":2}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid2) ++ "/data", "application/json", "{ \"value\":2}"), api_help:refresh(), Response3 = post_request(?VSTREAMS_URL, "application/json", "{\"user_id\" : \"" ++ lib_json:to_string(UserId) ++ "\", \"name\" : \"post_testvstream1\", \"description\" : \"test\", \"streams_involved\" : [\"" ++ lib_json:to_string(Streamid1) ++ "\", \"" ++ lib_json:to_string(Streamid2) ++ "\"], \"timestampfrom\" : \"now-1h\", \"function\" : [\"mean\", \"1s\"]}"), check_returned_code(Response3, 200), api_help:refresh(). %% @doc %% Function: get_vstream_test/0 %% Purpose: Test the get_stream function by doing some HTTP requests %% Returns: ok | {error, term()} %% %% Side effects: creates a document in elasticsearch %% @end -spec get_vstream_test() -> ok | {error, term()}. get_vstream_test() -> {ok, {{_Version1, 200, _ReasonPhrase1}, _Headers1, Body1}} = httpc:request(post, {?WEBMACHINE_URL++"/vstreams/_search",[],"application/json", "{\"query\":{\"term\" : { \"name\" : \"post_testvstream1\"}}}"}, [], []), StreamId = lib_json:get_field(Body1,"hits[0].id"), {ok, {{_Version2, 200, _ReasonPhrase2}, _Headers2, Body2}} = httpc:request(get, {?WEBMACHINE_URL++"/vstreams/" ++ lib_json:to_string(StreamId), []}, [], []) . %% @doc %% Function: put_vstream_test/0 %% Purpose: Test the put_vstream function by doing some HTTP requests %% Returns: ok | {error, term()} %% Side effects : creates 2 document in elasticsearch and updates them %% @end -spec put_vstream_test() -> ok | {error, term()}. put_vstream_test() -> {ok, {{_Version1, 200, _ReasonPhrase1}, _Headers1, Body1}} = httpc:request(post, {?WEBMACHINE_URL++"/vstreams/_search",[],"application/json", "{\"query\":{\"term\" : { \"name\" : \"post_testvstream1\"}}}"}, [], []), StreamId = lib_json:get_field(Body1,"hits[0].id"), {ok, {{_Version2, 200, _ReasonPhrase2}, _Headers2, Body2}} = httpc:request(put, {?WEBMACHINE_URL++"/vstreams/" ++ lib_json:to_string(StreamId), [], "application/json", "{\n\"name\" : \"updated_testvstream1\"}"}, [], []), api_help:refresh(), {ok, {{_Version3, 200, _ReasonPhrase3}, _Headers3, Body3}} = httpc:request(post, {?WEBMACHINE_URL++"/vstreams/_search",[],"application/json", "{\"query\":{\"term\" : { \"name\" : \"post_testvstream1\"}}}"}, [], []), ?assertEqual(length(lib_json:get_field(lib_json:to_string(Body3), "hits")), 0), {ok, {{_Version4, 200, _ReasonPhrase4}, _Headers4, Body4}} = httpc:request(post, {?WEBMACHINE_URL++"/vstreams/_search",[],"application/json", "{\"query\":{\"term\" : { \"name\" : \"updated_testvstream1\"}}}"}, [], []), ?assertEqual(length(lib_json:get_field(lib_json:to_string(Body4), "hits")), 1) . %% @doc %% Function: delete_vstream_test/0 %% Purpose: Test the delete_vstream function by doing some HTTP requests %% Returns: ok | {error, term()} %% Side effects : creates 2 document in elasticsearch and deletes them %% @end -spec delete_vstream_test() -> ok | {error, term()}. delete_vstream_test() -> %delete vstream, make sure there are no vsdatapoints left {ok, {{_Version1, 200, _ReasonPhrase1}, _Headers1, Body1}} = httpc:request(post, {?WEBMACHINE_URL++"/vstreams/_search",[],"application/json", "{\"query\":{\"term\" : { \"name\" : \"updated_testvstream1\"}}}"}, [], []), StreamId = lib_json:get_field(Body1,"hits[0].id"), {ok, {{_Version2, 200, _ReasonPhrase2}, _Headers2, Body2}} = httpc:request(delete, {?WEBMACHINE_URL++"/vstreams/" ++ lib_json:to_string(StreamId), []}, [], []), api_help:refresh(), {ok, {{_Version3, 200, _ReasonPhrase3}, _Headers3, Body3}} = httpc:request(post, {?WEBMACHINE_URL++"/vstreams/_search",[],"application/json", "{\"query\":{\"term\" : { \"name\" : \"updated_testvstream1\"}}}"}, [], []), ?assertEqual(length(lib_json:get_field(lib_json:to_string(Body3), "hits")), 0), {ok, {{_Version3, 200, _ReasonPhrase4}, _Headers4, Body4}} = httpc:request(get, {?WEBMACHINE_URL++"/vstreams/" ++ lib_json:to_string(StreamId) ++ "/data/_search", []}, [], []), ?assertEqual(length(lib_json:get_field(lib_json:to_string(Body4), "data")), 0), api_help:refresh(), {ok, {{_Version6, 200, _ReasonPhrase6}, _Headers6, Body6}} = httpc:request(delete, {?WEBMACHINE_URL++"/users/vstreamuser", []}, [], []) . %% @doc %% Checks if the Response has the correct http return code %% @end -spec check_returned_code(string(), integer()) -> ok. check_returned_code(Response, Code) -> {ok, Rest} = Response, {Header,_,_} = Rest, ?assertMatch({_, Code, _}, Header). post_request(URL, ContentType, Body) -> request(post, {URL, [], ContentType, Body}). get_request(URL) -> request(get, {URL, []}). request(Method, Request) -> httpc:request(Method, Request, [], []).
null
https://raw.githubusercontent.com/projectcs13/sensor-cloud/0302bd74b2e62fddbd832fb4c7a27b9c62852b90/test/vstreams_tests.erl
erlang
[www.csproj13.student.it.uu.se] @version 1.0 @doc == datapoints_tests == This module contains several tests to test the virtual streams functionality. @end @doc Function: init_test/0 Purpose: Used to start the inets to be able to do HTTP requests Returns: ok | {error, term()} Side effects: Start inets @end @doc Function: post_test/0 Purpose: Test a post request Returns: ok | {error, term()} @end @doc Function: get_vstream_test/0 Purpose: Test the get_stream function by doing some HTTP requests Returns: ok | {error, term()} Side effects: creates a document in elasticsearch @end @doc Function: put_vstream_test/0 Purpose: Test the put_vstream function by doing some HTTP requests Returns: ok | {error, term()} @end @doc Function: delete_vstream_test/0 Purpose: Test the delete_vstream function by doing some HTTP requests Returns: ok | {error, term()} @end delete vstream, make sure there are no vsdatapoints left @doc Checks if the Response has the correct http return code @end
@author [ Copyright information ] -module(vstreams_tests). -include_lib("eunit/include/eunit.hrl"). -define(WEBMACHINE_URL, api_help:get_webmachine_url()). -define(STREAMS_URL, ?WEBMACHINE_URL ++ "/streams/"). -define(VSTREAMS_URL, ?WEBMACHINE_URL ++ "/vstreams/"). -define(VSDATAPOINTS_URL, ?WEBMACHINE_URL ++ "/data/"). -define(TEST_VALUE, "1"). -define(INDEX, "sensorcloud"). -spec init_test() -> ok | {error, term()}. init_test() -> inets:start(). -spec post_test() -> ok | {error, term()}. post_test() -> {ok, {{_Version, 200, _ReasonPhrase}, _Headers, Body1}} = httpc:request(post, {?WEBMACHINE_URL++"/users", [],"application/json", "{\"username\" : \"vstreamuser\"}"}, [], []), UserId = lib_json:get_field(Body1,"_id"), api_help:refresh(), {ok, {{_Version2, 200, _ReasonPhrase2}, _Headers2, Body2}} = post_request(?STREAMS_URL, "application/json", "{ \"name\" : \"teststream1\", \"user_id\" : \"" ++ lib_json:to_string(UserId) ++ "\" }"), Streamid1 = lib_json:get_field(Body2, "_id"), api_help:refresh(), {ok, {{_Version3, 200, _ReasonPhrase3}, _Headers3, Body3}} = post_request(?STREAMS_URL, "application/json", "{ \"name\" : \"teststream2\", \"user_id\" : \"" ++ lib_json:to_string(UserId) ++ "\" }"), Streamid2 = lib_json:get_field(Body3, "_id"), api_help:refresh(), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid1) ++ "/data", "application/json", "{ \"value\":1}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid1) ++ "/data", "application/json", "{ \"value\":1}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid1) ++ "/data", "application/json", "{ \"value\":1}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid1) ++ "/data", "application/json", "{ \"value\":1}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid1) ++ "/data", "application/json", "{ \"value\":1}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid2) ++ "/data", "application/json", "{ \"value\":2}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid2) ++ "/data", "application/json", "{ \"value\":2}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid2) ++ "/data", "application/json", "{ \"value\":2}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid2) ++ "/data", "application/json", "{ \"value\":2}"), post_request(?STREAMS_URL ++ lib_json:to_string(Streamid2) ++ "/data", "application/json", "{ \"value\":2}"), api_help:refresh(), Response3 = post_request(?VSTREAMS_URL, "application/json", "{\"user_id\" : \"" ++ lib_json:to_string(UserId) ++ "\", \"name\" : \"post_testvstream1\", \"description\" : \"test\", \"streams_involved\" : [\"" ++ lib_json:to_string(Streamid1) ++ "\", \"" ++ lib_json:to_string(Streamid2) ++ "\"], \"timestampfrom\" : \"now-1h\", \"function\" : [\"mean\", \"1s\"]}"), check_returned_code(Response3, 200), api_help:refresh(). -spec get_vstream_test() -> ok | {error, term()}. get_vstream_test() -> {ok, {{_Version1, 200, _ReasonPhrase1}, _Headers1, Body1}} = httpc:request(post, {?WEBMACHINE_URL++"/vstreams/_search",[],"application/json", "{\"query\":{\"term\" : { \"name\" : \"post_testvstream1\"}}}"}, [], []), StreamId = lib_json:get_field(Body1,"hits[0].id"), {ok, {{_Version2, 200, _ReasonPhrase2}, _Headers2, Body2}} = httpc:request(get, {?WEBMACHINE_URL++"/vstreams/" ++ lib_json:to_string(StreamId), []}, [], []) . Side effects : creates 2 document in elasticsearch and updates them -spec put_vstream_test() -> ok | {error, term()}. put_vstream_test() -> {ok, {{_Version1, 200, _ReasonPhrase1}, _Headers1, Body1}} = httpc:request(post, {?WEBMACHINE_URL++"/vstreams/_search",[],"application/json", "{\"query\":{\"term\" : { \"name\" : \"post_testvstream1\"}}}"}, [], []), StreamId = lib_json:get_field(Body1,"hits[0].id"), {ok, {{_Version2, 200, _ReasonPhrase2}, _Headers2, Body2}} = httpc:request(put, {?WEBMACHINE_URL++"/vstreams/" ++ lib_json:to_string(StreamId), [], "application/json", "{\n\"name\" : \"updated_testvstream1\"}"}, [], []), api_help:refresh(), {ok, {{_Version3, 200, _ReasonPhrase3}, _Headers3, Body3}} = httpc:request(post, {?WEBMACHINE_URL++"/vstreams/_search",[],"application/json", "{\"query\":{\"term\" : { \"name\" : \"post_testvstream1\"}}}"}, [], []), ?assertEqual(length(lib_json:get_field(lib_json:to_string(Body3), "hits")), 0), {ok, {{_Version4, 200, _ReasonPhrase4}, _Headers4, Body4}} = httpc:request(post, {?WEBMACHINE_URL++"/vstreams/_search",[],"application/json", "{\"query\":{\"term\" : { \"name\" : \"updated_testvstream1\"}}}"}, [], []), ?assertEqual(length(lib_json:get_field(lib_json:to_string(Body4), "hits")), 1) . Side effects : creates 2 document in elasticsearch and deletes them -spec delete_vstream_test() -> ok | {error, term()}. delete_vstream_test() -> {ok, {{_Version1, 200, _ReasonPhrase1}, _Headers1, Body1}} = httpc:request(post, {?WEBMACHINE_URL++"/vstreams/_search",[],"application/json", "{\"query\":{\"term\" : { \"name\" : \"updated_testvstream1\"}}}"}, [], []), StreamId = lib_json:get_field(Body1,"hits[0].id"), {ok, {{_Version2, 200, _ReasonPhrase2}, _Headers2, Body2}} = httpc:request(delete, {?WEBMACHINE_URL++"/vstreams/" ++ lib_json:to_string(StreamId), []}, [], []), api_help:refresh(), {ok, {{_Version3, 200, _ReasonPhrase3}, _Headers3, Body3}} = httpc:request(post, {?WEBMACHINE_URL++"/vstreams/_search",[],"application/json", "{\"query\":{\"term\" : { \"name\" : \"updated_testvstream1\"}}}"}, [], []), ?assertEqual(length(lib_json:get_field(lib_json:to_string(Body3), "hits")), 0), {ok, {{_Version3, 200, _ReasonPhrase4}, _Headers4, Body4}} = httpc:request(get, {?WEBMACHINE_URL++"/vstreams/" ++ lib_json:to_string(StreamId) ++ "/data/_search", []}, [], []), ?assertEqual(length(lib_json:get_field(lib_json:to_string(Body4), "data")), 0), api_help:refresh(), {ok, {{_Version6, 200, _ReasonPhrase6}, _Headers6, Body6}} = httpc:request(delete, {?WEBMACHINE_URL++"/users/vstreamuser", []}, [], []) . -spec check_returned_code(string(), integer()) -> ok. check_returned_code(Response, Code) -> {ok, Rest} = Response, {Header,_,_} = Rest, ?assertMatch({_, Code, _}, Header). post_request(URL, ContentType, Body) -> request(post, {URL, [], ContentType, Body}). get_request(URL) -> request(get, {URL, []}). request(Method, Request) -> httpc:request(Method, Request, [], []).
7486cf6f5821019d1d8406b96f1ea6367ac4cb226528cac7b32f90812e338b9f
stchang/macrotypes
rackunit-typechecking.rkt
#lang racket/base (require (for-syntax rackunit syntax/srcloc racket/pretty racket/string racket/port) rackunit macrotypes/typecheck-core (only-in macrotypes/typecheck infer+erase)) (provide check-type typecheck-fail check-not-type check-props check-runtime-exn check-equal/rand typecheck-fail/toplvl typecheck-fail/definitions print-type (rename-out [typecheck-fail check-stx-err])) (begin-for-syntax (define (add-esc s) (string-append "\\" s)) (define escs (map add-esc '("(" ")" "[" "]" "+" "*"))) (define (replace-brackets str) (regexp-replace* "\\]" (regexp-replace* "\\[" str "(") ")")) (define (add-escs str) (replace-brackets (foldl (lambda (c s) (regexp-replace* c s (add-esc c))) str escs))) (define (expected tys #:given [givens ""] #:note [note ""]) (string-append note ".*Expected.+argument\\(s\\) with type\\(s\\).+" (add-escs tys) ".*Given:.*" (string-join (map add-escs (string-split givens ", ")) ".*")))) (define-syntax (check-type stx) (syntax-parse stx #:datum-literals (⇒ ->) ;; duplicate code to avoid redundant expansions [(_ e tag:id τ-expected (~or ⇒ ->) v) #:with τ-expected+ ((current-type-eval) #'τ-expected) #:with (e+ τ) (infer+erase #'(add-expected e τ-expected+) #:tag (stx->datum #'tag)) #:fail-unless (typecheck? #'τ #'τ-expected+) (format "Expression ~a [loc ~a:~a] has type ~a, expected ~a" (syntax->datum #'e) (syntax-line #'e) (syntax-column #'e) (type->str #'τ) (type->str #'τ-expected)) (syntax/loc stx (check-equal? e+ (add-expected v τ-expected+)))] [(_ e tag:id τ-expected) #:with τ-expected+ ((current-type-eval) #'τ-expected) #:with (e+ τ) (infer+erase #'(add-expected e τ-expected+) #:tag (stx->datum #'tag)) #:fail-unless (typecheck? #'τ #'τ-expected+) (format "Expression ~a [loc ~a:~a] has type ~a, expected ~a" (syntax->datum #'e) (syntax-line #'e) (syntax-column #'e) (type->str #'τ) (type->str #'τ-expected)) ;; count this test case in the test count (syntax/loc stx (check-true #t))])) ;; for checking properties other than types (define-syntax (check-props stx) (syntax-parse stx #:datum-literals (: ⇒ ->) [(_ prop e : v (~optional (~seq (~or ⇒ ->) v2) #:defaults ([v2 #'e]))) #:with e+ (expand/stop #'e) #:with props (or (syntax-property #'e+ (syntax->datum #'prop)) #'()) #:fail-unless (equal? (syntax->datum #'v) (syntax->datum #'props)) (format "Expression ~a [loc ~a:~a:~a] does not have prop ~a, actual: ~a" (syntax->datum #'e) (syntax-line #'e) (syntax-column #'e) (syntax-position #'e) (syntax->datum #'v) (syntax->datum #'props)) (syntax/loc stx (check-equal? e v2))])) (define-syntax (check-not-type stx) (syntax-parse stx #:datum-literals (:) [(_ e : not-τ) #:with (_ τ) (infer+erase #'e) #:fail-when (typecheck? #'τ ((current-type-eval) #'not-τ)) (format "(~a:~a) Expression ~a has type ~a; should not typecheck with ~a" (syntax-line stx) (syntax-column stx) (syntax->datum #'e) (type->str #'τ) (type->str #'not-τ)) ;; count this test case in the test count (syntax/loc stx (check-true #t))])) (define-syntax (typecheck-fail stx) (syntax-parse stx #:datum-literals (:) [(_ e (~or (~optional (~seq #:with-msg msg-pat) #:defaults ([msg-pat #'""])) (~optional (~seq #:verb-msg vmsg) #:defaults ([vmsg #'""])))) #:with msg:str (if (attribute msg-pat) (eval-syntax (datum->stx #'h (stx->datum #'msg-pat))) (eval-syntax (datum->stx #'h `(add-escs ,(stx->datum #'vmsg))))) #:when (with-check-info* (list (make-check-expected (syntax-e #'msg)) (make-check-expression (syntax->datum stx)) (make-check-location (build-source-location-list stx)) (make-check-name 'typecheck-fail) (make-check-params (list (syntax->datum #'e) (syntax-e #'msg)))) (let ([err-str (open-output-string)]) (λ () (check-exn (λ (ex) (and (or (exn:fail? ex) (exn:test:check? ex)) ; check err msg matches (regexp-match? (syntax-e #'msg) (string-append (get-output-string err-str) (exn-message ex))))) (λ () (parameterize ([current-error-port err-str]) ; swallow stderr (expand/df #'e))))))) ;; count this test case in the test count (syntax/loc stx (check-true #t))])) (define-syntax typecheck-fail/definitions (syntax-parser [(_ [def ...] . kws) (syntax/loc this-syntax (typecheck-fail (let () def ... (void)) . kws))])) (define-syntax typecheck-fail/toplvl (syntax-parser [(_ def . kws) (syntax/loc this-syntax (typecheck-fail/definitions [def] . kws))])) (define-syntax (check-runtime-exn stx) (syntax-parse stx [(_ e) #:with e- (expand/stop #'e) (syntax/loc stx (check-exn exn:fail? (lambda () e-)))])) (define-simple-macro (check-equal/rand f (~optional (~seq #:process p) #:defaults ([p #'(lambda (x) x)]))) #:with f* (format-id #'f "~a*" #'f) #:with out (syntax/loc this-syntax (check-equal/rand-fn f f* p)) out) (define-check (check-equal/rand-fn f f* process) (for ([i 100000]) (let ([ks (for/list ([n (procedure-arity f)]) (random 4294967087))]) (with-check-info (['f f] ['inputs ks]) (check-equal? (apply f (map process ks)) (apply f* (map process ks))))))) (define-syntax (print-type stx) (syntax-parse stx [(_ e (~optional (~seq #:tag tag:id) #:defaults ([tag #':])) (~optional (~and #:raw raw?))) #:with (_ τ) (infer+erase #'e #:tag (stx->datum #'tag)) #:do [(if (attribute raw?) (pretty-print (stx->datum #'τ)) (displayln (type->str #'τ)))] #'(void)]))
null
https://raw.githubusercontent.com/stchang/macrotypes/05ec31f2e1fe0ddd653211e041e06c6c8071ffa6/rackunit-macrotypes-lib/rackunit/rackunit-typechecking.rkt
racket
duplicate code to avoid redundant expansions count this test case in the test count for checking properties other than types count this test case in the test count check err msg matches swallow stderr count this test case in the test count
#lang racket/base (require (for-syntax rackunit syntax/srcloc racket/pretty racket/string racket/port) rackunit macrotypes/typecheck-core (only-in macrotypes/typecheck infer+erase)) (provide check-type typecheck-fail check-not-type check-props check-runtime-exn check-equal/rand typecheck-fail/toplvl typecheck-fail/definitions print-type (rename-out [typecheck-fail check-stx-err])) (begin-for-syntax (define (add-esc s) (string-append "\\" s)) (define escs (map add-esc '("(" ")" "[" "]" "+" "*"))) (define (replace-brackets str) (regexp-replace* "\\]" (regexp-replace* "\\[" str "(") ")")) (define (add-escs str) (replace-brackets (foldl (lambda (c s) (regexp-replace* c s (add-esc c))) str escs))) (define (expected tys #:given [givens ""] #:note [note ""]) (string-append note ".*Expected.+argument\\(s\\) with type\\(s\\).+" (add-escs tys) ".*Given:.*" (string-join (map add-escs (string-split givens ", ")) ".*")))) (define-syntax (check-type stx) (syntax-parse stx #:datum-literals (⇒ ->) [(_ e tag:id τ-expected (~or ⇒ ->) v) #:with τ-expected+ ((current-type-eval) #'τ-expected) #:with (e+ τ) (infer+erase #'(add-expected e τ-expected+) #:tag (stx->datum #'tag)) #:fail-unless (typecheck? #'τ #'τ-expected+) (format "Expression ~a [loc ~a:~a] has type ~a, expected ~a" (syntax->datum #'e) (syntax-line #'e) (syntax-column #'e) (type->str #'τ) (type->str #'τ-expected)) (syntax/loc stx (check-equal? e+ (add-expected v τ-expected+)))] [(_ e tag:id τ-expected) #:with τ-expected+ ((current-type-eval) #'τ-expected) #:with (e+ τ) (infer+erase #'(add-expected e τ-expected+) #:tag (stx->datum #'tag)) #:fail-unless (typecheck? #'τ #'τ-expected+) (format "Expression ~a [loc ~a:~a] has type ~a, expected ~a" (syntax->datum #'e) (syntax-line #'e) (syntax-column #'e) (type->str #'τ) (type->str #'τ-expected)) (syntax/loc stx (check-true #t))])) (define-syntax (check-props stx) (syntax-parse stx #:datum-literals (: ⇒ ->) [(_ prop e : v (~optional (~seq (~or ⇒ ->) v2) #:defaults ([v2 #'e]))) #:with e+ (expand/stop #'e) #:with props (or (syntax-property #'e+ (syntax->datum #'prop)) #'()) #:fail-unless (equal? (syntax->datum #'v) (syntax->datum #'props)) (format "Expression ~a [loc ~a:~a:~a] does not have prop ~a, actual: ~a" (syntax->datum #'e) (syntax-line #'e) (syntax-column #'e) (syntax-position #'e) (syntax->datum #'v) (syntax->datum #'props)) (syntax/loc stx (check-equal? e v2))])) (define-syntax (check-not-type stx) (syntax-parse stx #:datum-literals (:) [(_ e : not-τ) #:with (_ τ) (infer+erase #'e) #:fail-when (typecheck? #'τ ((current-type-eval) #'not-τ)) (format "(~a:~a) Expression ~a has type ~a; should not typecheck with ~a" (syntax-line stx) (syntax-column stx) (syntax->datum #'e) (type->str #'τ) (type->str #'not-τ)) (syntax/loc stx (check-true #t))])) (define-syntax (typecheck-fail stx) (syntax-parse stx #:datum-literals (:) [(_ e (~or (~optional (~seq #:with-msg msg-pat) #:defaults ([msg-pat #'""])) (~optional (~seq #:verb-msg vmsg) #:defaults ([vmsg #'""])))) #:with msg:str (if (attribute msg-pat) (eval-syntax (datum->stx #'h (stx->datum #'msg-pat))) (eval-syntax (datum->stx #'h `(add-escs ,(stx->datum #'vmsg))))) #:when (with-check-info* (list (make-check-expected (syntax-e #'msg)) (make-check-expression (syntax->datum stx)) (make-check-location (build-source-location-list stx)) (make-check-name 'typecheck-fail) (make-check-params (list (syntax->datum #'e) (syntax-e #'msg)))) (let ([err-str (open-output-string)]) (λ () (check-exn (λ (ex) (and (or (exn:fail? ex) (exn:test:check? ex)) (regexp-match? (syntax-e #'msg) (string-append (get-output-string err-str) (exn-message ex))))) (λ () (expand/df #'e))))))) (syntax/loc stx (check-true #t))])) (define-syntax typecheck-fail/definitions (syntax-parser [(_ [def ...] . kws) (syntax/loc this-syntax (typecheck-fail (let () def ... (void)) . kws))])) (define-syntax typecheck-fail/toplvl (syntax-parser [(_ def . kws) (syntax/loc this-syntax (typecheck-fail/definitions [def] . kws))])) (define-syntax (check-runtime-exn stx) (syntax-parse stx [(_ e) #:with e- (expand/stop #'e) (syntax/loc stx (check-exn exn:fail? (lambda () e-)))])) (define-simple-macro (check-equal/rand f (~optional (~seq #:process p) #:defaults ([p #'(lambda (x) x)]))) #:with f* (format-id #'f "~a*" #'f) #:with out (syntax/loc this-syntax (check-equal/rand-fn f f* p)) out) (define-check (check-equal/rand-fn f f* process) (for ([i 100000]) (let ([ks (for/list ([n (procedure-arity f)]) (random 4294967087))]) (with-check-info (['f f] ['inputs ks]) (check-equal? (apply f (map process ks)) (apply f* (map process ks))))))) (define-syntax (print-type stx) (syntax-parse stx [(_ e (~optional (~seq #:tag tag:id) #:defaults ([tag #':])) (~optional (~and #:raw raw?))) #:with (_ τ) (infer+erase #'e #:tag (stx->datum #'tag)) #:do [(if (attribute raw?) (pretty-print (stx->datum #'τ)) (displayln (type->str #'τ)))] #'(void)]))
b301ae1020c4e58e39b01add8127f80b6943227eaccb0e70000e99b62a7233f3
dongcarl/guix
shellutils.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2016 < > Copyright © 2016 , 2017 < > Copyright © 2016 < > Copyright © 2017 < > Copyright © 2018 , 2020 < > Copyright © 2018 < > Copyright © 2019 < > Copyright © 2020 < > Copyright © 2020 aecepoglu < > Copyright © 2020 < > Copyright © 2021 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages shellutils) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix utils) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix git-download) #:use-module (guix build-system gnu) #:use-module (guix build-system go) #:use-module (guix build-system python) #:use-module (gnu packages autotools) #:use-module (gnu packages base) #:use-module (gnu packages bison) #:use-module (gnu packages flex) #:use-module (gnu packages golang) #:use-module (gnu packages ncurses) #:use-module (gnu packages pkg-config) #:use-module (gnu packages python) #:use-module (gnu packages readline) #:use-module (gnu packages ruby) #:use-module (gnu packages shells) #:use-module (gnu packages tmux)) (define-public boxes (package (name "boxes") (version "1.3") (source (origin (method git-fetch) (uri (git-reference (url "-boxes/boxes") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "0b12rsynrmkldlwcb62drk33kk0aqwbj10mq5y5x3hjf626gjwsi")))) (build-system gnu-build-system) (arguments `(#:test-target "test" #:make-flags (list (string-append "GLOBALCONF=" (assoc-ref %outputs "out") "/etc/boxes-config")) #:phases (modify-phases %standard-phases (delete 'configure) (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let ((dest (assoc-ref outputs "out"))) (for-each (lambda (x) (install-file (car x) (string-append dest "/" (cdr x)))) '(("src/boxes" . "bin") ("doc/boxes.1" . "share/man/man1") ("boxes-config" . "etc/"))) #t)))))) (native-inputs `(("flex" ,flex) ("bison" ,bison))) (synopsis "Command line ASCII boxes") (description "This command-line filter program draws ASCII-art boxes around your input text.") (home-page "") (license license:gpl2))) (define-public zsh-autosuggestions (package (name "zsh-autosuggestions") (version "0.7.0") (source (origin (method git-fetch) (uri (git-reference (url "-users/zsh-autosuggestions") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "1g3pij5qn2j7v7jjac2a63lxd97mcsgw6xq6k5p7835q9fjiid98")))) (build-system gnu-build-system) (native-inputs `(("ruby" ,ruby) ("ruby-byebug" ,ruby-byebug) ("ruby-pry" ,ruby-pry) ("ruby-rspec" ,ruby-rspec) ("ruby-rspec-wait" ,ruby-rspec-wait) ("tmux" ,tmux) ("zsh" ,zsh))) (arguments '(#:phases (modify-phases %standard-phases (add-after 'unpack 'patch-tests (lambda _ Failing tests since tmux-3.2a (delete-file "spec/options/buffer_max_size_spec.rb"))) (delete 'configure) (replace 'check ; Tests use ruby's bundler; instead execute rspec directly. (lambda _ (setenv "TMUX_TMPDIR" (getenv "TMPDIR")) (setenv "SHELL" (which "zsh")) (invoke "rspec"))) (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (zsh-plugins (string-append out "/share/zsh/plugins/zsh-autosuggestions"))) (invoke "make" "all") (install-file "zsh-autosuggestions.zsh" zsh-plugins) #t)))))) (home-page "-users/zsh-autosuggestions") (synopsis "Fish-like autosuggestions for zsh") (description "Fish-like fast/unobtrusive autosuggestions for zsh. It suggests commands as you type.") (license license:expat))) (define-public sh-z (package (name "sh-z") (version "1.11") (source (origin (method git-fetch) (uri (git-reference (url "") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "13zbgkj6y0qhvn5jpkrqbd4jjxjr789k228iwma5hjfh1nx7ghyb")))) (build-system gnu-build-system) (arguments `(#:tests? #f ; No tests provided #:phases (modify-phases %standard-phases (delete 'configure) (delete 'build) (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (man (string-append out "/share/man/man1")) (bin (string-append out "/bin"))) (install-file "z.sh" bin) (chmod (string-append bin "/z.sh") #o755) (install-file "z.1" man) #t)))))) (synopsis "Jump about directories") (description "Tracks your most used directories, based on ``frecency''. After a short learning phase, z will take you to the most ``frecent'' directory that matches all of the regexes given on the command line in order.") (home-page "") (license license:expat))) (define-public envstore (package (name "envstore") (version "2.1") (source (origin (method url-fetch) (uri (string-append "/" name "/" name "-" version ".tar.bz2")) (sha256 (base32 "1x97lxad80m5blhdfanl5v2qzjwcgbij2i23701bn8mpyxsrqszi")))) (build-system gnu-build-system) (arguments `(#:test-target "test" #:make-flags (list "CC=gcc" (string-append "PREFIX=" (assoc-ref %outputs "out"))) #:phases (modify-phases %standard-phases (delete 'configure)))) (home-page "/") (synopsis "Save and restore environment variables") (description "Envstore is a program for sharing environment variables between various shells or commands.") (license license:wtfpl2))) (define-public trash-cli (package (name "trash-cli") (version "0.17.1.14") (source (origin (method url-fetch) (uri (pypi-uri "trash-cli" version)) (sha256 (base32 "01q0cl04ljf214z6s3g256gsxx3pqsgaf6ac1zh0vrq5bnhnr85h")))) (build-system python-build-system) (arguments `(#:python ,python-2 #:tests? #f ; no tests #:phases (modify-phases %standard-phases (add-before 'build 'patch-path-constants (lambda* (#:key inputs #:allow-other-keys) (let ((libc (assoc-ref inputs "libc")) (coreutils (assoc-ref inputs "coreutils"))) (substitute* "trashcli/list_mount_points.py" (("\"/lib/libc.so.6\".*") (string-append "\"" libc "/lib/libc.so.6\"\n")) (("\"df\"") (string-append "\"" coreutils "/bin/df\""))))))))) (inputs `(("coreutils" ,coreutils))) (home-page "-cli") (synopsis "Trash can management tool") (description "trash-cli is a command line utility for interacting with the FreeDesktop.org trash can used by GNOME, KDE, XFCE, and other common desktop environments. It can move files to the trash, and remove or list files that are already there.") (license license:gpl2+))) (define-public direnv (package (name "direnv") (version "2.15.2") (source (origin (method git-fetch) (uri (git-reference (url "") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "1y18619pmhfl0vrf4w0h75ybkkwgi9wcb7d9kv4n8drg1xp4aw4w")))) (build-system go-build-system) (arguments '(#:import-path "github.com/direnv/direnv" #:phases (modify-phases %standard-phases (add-after 'unpack 'delete-vendor (lambda _ ;; Using a snippet causes issues with the name of the directory, ;; so delete the extra source code here. (delete-file-recursively "src/github.com/direnv/direnv/vendor") #t)) (add-after 'install 'install-manpages (lambda* (#:key outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (man (string-append out "/share/man/man1"))) (mkdir-p man) (with-directory-excursion "src/github.com/direnv/direnv" (install-file "man/direnv.1" man) (install-file "man/direnv-stdlib.1" man) (install-file "man/direnv.toml.1" man))))) (replace 'check (lambda* (#:key tests? #:allow-other-keys) (when tests? (setenv "HOME" "/tmp") (with-directory-excursion "src/github.com/direnv/direnv" ;; The following file needs to be writable so it can be ;; modified by the testsuite. (make-file-writable "test/scenarios/base/.envrc") (invoke "make" "test") ;; Clean up from the tests, especially so that the extra ;; direnv executable that's generated is removed. (invoke "make" "clean"))) #t))))) (native-inputs `(("go-github-com-burntsushi-toml" ,go-github-com-burntsushi-toml) ("go-github-com-direnv-go-dotenv" ,go-github-com-direnv-go-dotenv) ("which" ,which))) (home-page "/") (synopsis "Environment switcher for the shell") (description "direnv can hook into the bash, zsh, tcsh, and fish shells to load or unload environment variables depending on the current directory. This allows project-specific environment variables without using @file{~/.profile}. Before each prompt, direnv checks for the existence of a @file{.envrc} file in the current and parent directories. This file is then used to alter the environment variables of the current shell.") (license license:expat))) (define-public fzy (package (name "fzy") (version "1.0") (source (origin (method git-fetch) (uri (git-reference (url "") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1gkzdvj73f71388jvym47075l9zw61v6l8wdv2lnc0mns6dxig0k")))) (build-system gnu-build-system) (arguments '(#:make-flags (list "CC=gcc" (string-append "PREFIX=" (assoc-ref %outputs "out"))) #:phases (modify-phases %standard-phases (delete 'configure)))) (home-page "") (synopsis "Fast fuzzy text selector for the terminal with an advanced scoring algorithm") (description "Most other fuzzy matchers sort based on the length of a match. fzy tries to find the result the user intended. It does this by favouring matches on consecutive letters and starts of words. This allows matching using acronyms or different parts of the path. fzy is designed to be used both as an editor plugin and on the command line. Rather than clearing the screen, fzy displays its interface directly below the current cursor position, scrolling the screen if necessary.") (license license:expat))) (define-public hstr (package (name "hstr") (version "2.3") (source (origin (method git-fetch) (uri (git-reference (url "") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1chmfdi1dwg3sarzd01nqa82g65q7wdr6hrnj96l75vikwsg986y")))) (build-system gnu-build-system) (arguments `(#:phases (modify-phases %standard-phases (add-before 'build 'adjust-ncurses-includes (lambda* (#:key make-flags outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out"))) (substitute* "src/include/hstr_curses.h" (("ncursesw\\/curses.h") "ncurses.h")) (substitute* "src/include/hstr.h" (("ncursesw\\/curses.h") "ncurses.h"))) #t))))) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("pkg-config" ,pkg-config))) (inputs `(("ncurses" ,ncurses) ("readline" ,readline))) (synopsis "Navigate and search command history with shell history suggest box") (description "HSTR (HiSToRy) is a command-line utility that brings improved Bash and Zsh command completion from the history. It aims to make completion easier and more efficient than with @kbd{Ctrl-R}. It allows you to easily view, navigate, and search your command history with suggestion boxes. HSTR can also manage your command history (for instance you can remove commands that are obsolete or contain a piece of sensitive information) or bookmark your favourite commands.") (home-page "") (license license:asl2.0))) (define-public shell-functools (package (name "shell-functools") (version "0.3.0") (source (origin (method git-fetch) (uri (git-reference (url "-functools") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "0d6zzg7cxfrzwzh1wmpj7q85kz33sak6ac59ncsm6dlbin12h0hi")))) (build-system python-build-system) (home-page "-functools/") (synopsis "Functional programming tools for the shell") (description "This package provides higher order functions like map, filter, foldl, sort_by and take_while as simple command-line tools. Following the UNIX philosophy, these commands are designed to be composed via pipes. A large collection of functions such as basename, replace, contains or is_dir are provided as arguments to these commands.") (license license:expat)))
null
https://raw.githubusercontent.com/dongcarl/guix/d2b30db788f1743f9f8738cb1de977b77748567f/gnu/packages/shellutils.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Tests use ruby's bundler; instead execute rspec directly. No tests provided no tests Using a snippet causes issues with the name of the directory, so delete the extra source code here. The following file needs to be writable so it can be modified by the testsuite. Clean up from the tests, especially so that the extra direnv executable that's generated is removed.
Copyright © 2016 < > Copyright © 2016 , 2017 < > Copyright © 2016 < > Copyright © 2017 < > Copyright © 2018 , 2020 < > Copyright © 2018 < > Copyright © 2019 < > Copyright © 2020 < > Copyright © 2020 aecepoglu < > Copyright © 2020 < > Copyright © 2021 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages shellutils) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix utils) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix git-download) #:use-module (guix build-system gnu) #:use-module (guix build-system go) #:use-module (guix build-system python) #:use-module (gnu packages autotools) #:use-module (gnu packages base) #:use-module (gnu packages bison) #:use-module (gnu packages flex) #:use-module (gnu packages golang) #:use-module (gnu packages ncurses) #:use-module (gnu packages pkg-config) #:use-module (gnu packages python) #:use-module (gnu packages readline) #:use-module (gnu packages ruby) #:use-module (gnu packages shells) #:use-module (gnu packages tmux)) (define-public boxes (package (name "boxes") (version "1.3") (source (origin (method git-fetch) (uri (git-reference (url "-boxes/boxes") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "0b12rsynrmkldlwcb62drk33kk0aqwbj10mq5y5x3hjf626gjwsi")))) (build-system gnu-build-system) (arguments `(#:test-target "test" #:make-flags (list (string-append "GLOBALCONF=" (assoc-ref %outputs "out") "/etc/boxes-config")) #:phases (modify-phases %standard-phases (delete 'configure) (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let ((dest (assoc-ref outputs "out"))) (for-each (lambda (x) (install-file (car x) (string-append dest "/" (cdr x)))) '(("src/boxes" . "bin") ("doc/boxes.1" . "share/man/man1") ("boxes-config" . "etc/"))) #t)))))) (native-inputs `(("flex" ,flex) ("bison" ,bison))) (synopsis "Command line ASCII boxes") (description "This command-line filter program draws ASCII-art boxes around your input text.") (home-page "") (license license:gpl2))) (define-public zsh-autosuggestions (package (name "zsh-autosuggestions") (version "0.7.0") (source (origin (method git-fetch) (uri (git-reference (url "-users/zsh-autosuggestions") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "1g3pij5qn2j7v7jjac2a63lxd97mcsgw6xq6k5p7835q9fjiid98")))) (build-system gnu-build-system) (native-inputs `(("ruby" ,ruby) ("ruby-byebug" ,ruby-byebug) ("ruby-pry" ,ruby-pry) ("ruby-rspec" ,ruby-rspec) ("ruby-rspec-wait" ,ruby-rspec-wait) ("tmux" ,tmux) ("zsh" ,zsh))) (arguments '(#:phases (modify-phases %standard-phases (add-after 'unpack 'patch-tests (lambda _ Failing tests since tmux-3.2a (delete-file "spec/options/buffer_max_size_spec.rb"))) (delete 'configure) (lambda _ (setenv "TMUX_TMPDIR" (getenv "TMPDIR")) (setenv "SHELL" (which "zsh")) (invoke "rspec"))) (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (zsh-plugins (string-append out "/share/zsh/plugins/zsh-autosuggestions"))) (invoke "make" "all") (install-file "zsh-autosuggestions.zsh" zsh-plugins) #t)))))) (home-page "-users/zsh-autosuggestions") (synopsis "Fish-like autosuggestions for zsh") (description "Fish-like fast/unobtrusive autosuggestions for zsh. It suggests commands as you type.") (license license:expat))) (define-public sh-z (package (name "sh-z") (version "1.11") (source (origin (method git-fetch) (uri (git-reference (url "") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "13zbgkj6y0qhvn5jpkrqbd4jjxjr789k228iwma5hjfh1nx7ghyb")))) (build-system gnu-build-system) (arguments #:phases (modify-phases %standard-phases (delete 'configure) (delete 'build) (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (man (string-append out "/share/man/man1")) (bin (string-append out "/bin"))) (install-file "z.sh" bin) (chmod (string-append bin "/z.sh") #o755) (install-file "z.1" man) #t)))))) (synopsis "Jump about directories") (description "Tracks your most used directories, based on ``frecency''. After a short learning phase, z will take you to the most ``frecent'' directory that matches all of the regexes given on the command line in order.") (home-page "") (license license:expat))) (define-public envstore (package (name "envstore") (version "2.1") (source (origin (method url-fetch) (uri (string-append "/" name "/" name "-" version ".tar.bz2")) (sha256 (base32 "1x97lxad80m5blhdfanl5v2qzjwcgbij2i23701bn8mpyxsrqszi")))) (build-system gnu-build-system) (arguments `(#:test-target "test" #:make-flags (list "CC=gcc" (string-append "PREFIX=" (assoc-ref %outputs "out"))) #:phases (modify-phases %standard-phases (delete 'configure)))) (home-page "/") (synopsis "Save and restore environment variables") (description "Envstore is a program for sharing environment variables between various shells or commands.") (license license:wtfpl2))) (define-public trash-cli (package (name "trash-cli") (version "0.17.1.14") (source (origin (method url-fetch) (uri (pypi-uri "trash-cli" version)) (sha256 (base32 "01q0cl04ljf214z6s3g256gsxx3pqsgaf6ac1zh0vrq5bnhnr85h")))) (build-system python-build-system) (arguments `(#:python ,python-2 #:phases (modify-phases %standard-phases (add-before 'build 'patch-path-constants (lambda* (#:key inputs #:allow-other-keys) (let ((libc (assoc-ref inputs "libc")) (coreutils (assoc-ref inputs "coreutils"))) (substitute* "trashcli/list_mount_points.py" (("\"/lib/libc.so.6\".*") (string-append "\"" libc "/lib/libc.so.6\"\n")) (("\"df\"") (string-append "\"" coreutils "/bin/df\""))))))))) (inputs `(("coreutils" ,coreutils))) (home-page "-cli") (synopsis "Trash can management tool") (description "trash-cli is a command line utility for interacting with the FreeDesktop.org trash can used by GNOME, KDE, XFCE, and other common desktop environments. It can move files to the trash, and remove or list files that are already there.") (license license:gpl2+))) (define-public direnv (package (name "direnv") (version "2.15.2") (source (origin (method git-fetch) (uri (git-reference (url "") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "1y18619pmhfl0vrf4w0h75ybkkwgi9wcb7d9kv4n8drg1xp4aw4w")))) (build-system go-build-system) (arguments '(#:import-path "github.com/direnv/direnv" #:phases (modify-phases %standard-phases (add-after 'unpack 'delete-vendor (lambda _ (delete-file-recursively "src/github.com/direnv/direnv/vendor") #t)) (add-after 'install 'install-manpages (lambda* (#:key outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (man (string-append out "/share/man/man1"))) (mkdir-p man) (with-directory-excursion "src/github.com/direnv/direnv" (install-file "man/direnv.1" man) (install-file "man/direnv-stdlib.1" man) (install-file "man/direnv.toml.1" man))))) (replace 'check (lambda* (#:key tests? #:allow-other-keys) (when tests? (setenv "HOME" "/tmp") (with-directory-excursion "src/github.com/direnv/direnv" (make-file-writable "test/scenarios/base/.envrc") (invoke "make" "test") (invoke "make" "clean"))) #t))))) (native-inputs `(("go-github-com-burntsushi-toml" ,go-github-com-burntsushi-toml) ("go-github-com-direnv-go-dotenv" ,go-github-com-direnv-go-dotenv) ("which" ,which))) (home-page "/") (synopsis "Environment switcher for the shell") (description "direnv can hook into the bash, zsh, tcsh, and fish shells to load or unload environment variables depending on the current directory. This allows project-specific environment variables without using @file{~/.profile}. Before each prompt, direnv checks for the existence of a @file{.envrc} file in the current and parent directories. This file is then used to alter the environment variables of the current shell.") (license license:expat))) (define-public fzy (package (name "fzy") (version "1.0") (source (origin (method git-fetch) (uri (git-reference (url "") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1gkzdvj73f71388jvym47075l9zw61v6l8wdv2lnc0mns6dxig0k")))) (build-system gnu-build-system) (arguments '(#:make-flags (list "CC=gcc" (string-append "PREFIX=" (assoc-ref %outputs "out"))) #:phases (modify-phases %standard-phases (delete 'configure)))) (home-page "") (synopsis "Fast fuzzy text selector for the terminal with an advanced scoring algorithm") (description "Most other fuzzy matchers sort based on the length of a match. fzy tries to find the result the user intended. It does this by favouring matches on consecutive letters and starts of words. This allows matching using acronyms or different parts of the path. fzy is designed to be used both as an editor plugin and on the command line. Rather than clearing the screen, fzy displays its interface directly below the current cursor position, scrolling the screen if necessary.") (license license:expat))) (define-public hstr (package (name "hstr") (version "2.3") (source (origin (method git-fetch) (uri (git-reference (url "") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1chmfdi1dwg3sarzd01nqa82g65q7wdr6hrnj96l75vikwsg986y")))) (build-system gnu-build-system) (arguments `(#:phases (modify-phases %standard-phases (add-before 'build 'adjust-ncurses-includes (lambda* (#:key make-flags outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out"))) (substitute* "src/include/hstr_curses.h" (("ncursesw\\/curses.h") "ncurses.h")) (substitute* "src/include/hstr.h" (("ncursesw\\/curses.h") "ncurses.h"))) #t))))) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("pkg-config" ,pkg-config))) (inputs `(("ncurses" ,ncurses) ("readline" ,readline))) (synopsis "Navigate and search command history with shell history suggest box") (description "HSTR (HiSToRy) is a command-line utility that brings improved Bash and Zsh command completion from the history. It aims to make completion easier and more efficient than with @kbd{Ctrl-R}. It allows you to easily view, navigate, and search your command history with suggestion boxes. HSTR can also manage your command history (for instance you can remove commands that are obsolete or contain a piece of sensitive information) or bookmark your favourite commands.") (home-page "") (license license:asl2.0))) (define-public shell-functools (package (name "shell-functools") (version "0.3.0") (source (origin (method git-fetch) (uri (git-reference (url "-functools") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "0d6zzg7cxfrzwzh1wmpj7q85kz33sak6ac59ncsm6dlbin12h0hi")))) (build-system python-build-system) (home-page "-functools/") (synopsis "Functional programming tools for the shell") (description "This package provides higher order functions like map, filter, foldl, sort_by and take_while as simple command-line tools. Following the UNIX philosophy, these commands are designed to be composed via pipes. A large collection of functions such as basename, replace, contains or is_dir are provided as arguments to these commands.") (license license:expat)))
e91344f0c17ea527bc092a52ef14e8e21f713b8457330bc3705f7dcdd3a9abba
jordanthayer/ocaml-search
optimistic_search.ml
(** Optimistic Search *) type 'a node = { mutable fp : float; h : float; mutable g : float; mutable ppos : int; mutable fpos: int; mutable dpos: int; data : 'a; } let ordered_f a b = (** are nodes [a] and [b] in order of increasing f? *) let af = a.g +. a.h and bf = b.g +. b.h in af < bf || (af = bf && a.g >= b.g) let ordered_p a b = * are [ a ] and [ b ] in best first order let af = a.g +. a.h and bf = b.g +. b.h in (a.fp < b.fp) || ((a.fp = b.fp) && af < bf) || ((a.fp = b.fp && af = bf && a.g >= b.g)) let better_p a b = (** is [a] a better solution than [b] *) (a.g +. a.h) <= (b.g +. b.h) let get_f_pos a = (** returns the f position of node a *) a.fpos let get_d_pos a = (** returns the delayed position of node [a] *) a.dpos let get_pq_pos a = (** returns the open position of node [a] *) a.ppos let set_f_pos a i = (** sets the cleanup position of node [a] to [i] *) a.fpos <- i let set_pq_pos a i = (** sets the open position of node [a] to [i] *) a.ppos <- i let set_d_pos a i = (** sets the delay position of node [a] to [i] *) a.dpos <- i let wrap f = (** takes a function [f] meant for domain nodes and makes it so that it can be applied to search nodes *) (fun n -> f n.data) let unwrap_sol s = (** Takes a search space solution and converts it into a domain space solution *) match s with Limit.Incumbent (q,n) -> if q = 0. then None else Some (n.data, n.g) | _ -> None let make_expand expand h weight = (** takes the [expand] function from the domain and returns a search space expand function *) let make_child = (fun (n, g) -> let h = h n in { fp = g +. (weight *. h); h = h; g = g; fpos = Dpq.no_position; ppos = Dpq.no_position; dpos = Dpq.no_position; data = n;}) in (fun parent -> List.map make_child (expand parent.data parent.g)) let get_node fq pq i bound = (** Returns the next node to be expanded *) let fn = Dpq.peek_first fq and incumbent = i.Limit.incumbent in match incumbent with Limit.Nothing -> raise Optimistic_framework.NoIncumbent | Limit.Incumbent(qual,inc) -> if ((fn.g +. fn.h) *. bound) >= (inc.g +. inc.h) then raise Optimistic_framework.Done; let fpn = Dpq.peek_first pq in if fpn.fp < (inc.g +. inc.h) then (Dpq.remove pq fpn.ppos; Dpq.remove fq fpn.fpos; fpn) else (let trf = fn.fpos and trp = fn.ppos in Dpq.remove fq trf; Dpq.remove pq trp; fn) (***************************************************************************) let make_interface sface wt = Search_interface.make ~node_expand:(make_expand sface.Search_interface.domain_expand sface.Search_interface.h wt) ~key:(wrap sface.Search_interface.key) ~goal_p:(wrap sface.Search_interface.goal_p) ~halt_on:sface.Search_interface.halt_on ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals sface.Search_interface.domain { fp = neg_infinity; h = neg_infinity; g = 0.; ppos = Dpq.no_position; fpos = Dpq.no_position; dpos = Dpq.no_position; data = sface.Search_interface.initial} better_p (Limit.make_default_logger (fun n -> n.h +. n.g) (wrap sface.Search_interface.get_sol_length)) let no_dups sface args = (** Performs optimistic search in domains with few or no duplicates *) let bound = Search_args.get_float "Optimistic_search.no_dups" args 0 and wt = Search_args.get_float "Optimistic_search.no_dups" args 1 in let wt = (bound -. 1.) *. wt +. 1. in let search_interface = make_interface sface wt in Limit.unwrap_sol5 unwrap_sol (Optimistic_framework.no_dups search_interface get_node ordered_p bound better_p ordered_f set_pq_pos set_f_pos) let dups sface args = (** Performs optimistic search in domains with duplicates *) let bound = Search_args.get_float "Optimistic_search.dups" args 0 and wt = Search_args.get_float "Optimistic_search.dups" args 1 in let wt = (bound -. 1.) *. wt +. 1. in let search_interface = make_interface sface wt in Limit.unwrap_sol6 unwrap_sol (Optimistic_framework.dups search_interface get_node ordered_p bound better_p ordered_f set_pq_pos set_f_pos get_pq_pos get_f_pos) let delay_dups sface args = * Performs optimistic search in domains with duplicates . Duplicate states are only considered for expansion during the cleanup phase are only considered for expansion during the cleanup phase*) let bound = Search_args.get_float "Optimistic_search.delay_dups" args 0 and wt = Search_args.get_float "Optimistic_search.delay_dups" args 1 in let wt = (bound -. 1.) *. wt +. 1. in let search_interface = make_interface sface wt in Limit.unwrap_sol6 unwrap_sol (Optimistic_framework.delay search_interface get_node ordered_p bound better_p ordered_f set_pq_pos set_d_pos set_f_pos get_pq_pos get_d_pos get_f_pos) EOF
null
https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/search/optimistic/optimistic_search.ml
ocaml
* Optimistic Search * are nodes [a] and [b] in order of increasing f? * is [a] a better solution than [b] * returns the f position of node a * returns the delayed position of node [a] * returns the open position of node [a] * sets the cleanup position of node [a] to [i] * sets the open position of node [a] to [i] * sets the delay position of node [a] to [i] * takes a function [f] meant for domain nodes and makes it so that it can be applied to search nodes * Takes a search space solution and converts it into a domain space solution * takes the [expand] function from the domain and returns a search space expand function * Returns the next node to be expanded ************************************************************************* * Performs optimistic search in domains with few or no duplicates * Performs optimistic search in domains with duplicates
type 'a node = { mutable fp : float; h : float; mutable g : float; mutable ppos : int; mutable fpos: int; mutable dpos: int; data : 'a; } let ordered_f a b = let af = a.g +. a.h and bf = b.g +. b.h in af < bf || (af = bf && a.g >= b.g) let ordered_p a b = * are [ a ] and [ b ] in best first order let af = a.g +. a.h and bf = b.g +. b.h in (a.fp < b.fp) || ((a.fp = b.fp) && af < bf) || ((a.fp = b.fp && af = bf && a.g >= b.g)) let better_p a b = (a.g +. a.h) <= (b.g +. b.h) let get_f_pos a = a.fpos let get_d_pos a = a.dpos let get_pq_pos a = a.ppos let set_f_pos a i = a.fpos <- i let set_pq_pos a i = a.ppos <- i let set_d_pos a i = a.dpos <- i let wrap f = (fun n -> f n.data) let unwrap_sol s = match s with Limit.Incumbent (q,n) -> if q = 0. then None else Some (n.data, n.g) | _ -> None let make_expand expand h weight = let make_child = (fun (n, g) -> let h = h n in { fp = g +. (weight *. h); h = h; g = g; fpos = Dpq.no_position; ppos = Dpq.no_position; dpos = Dpq.no_position; data = n;}) in (fun parent -> List.map make_child (expand parent.data parent.g)) let get_node fq pq i bound = let fn = Dpq.peek_first fq and incumbent = i.Limit.incumbent in match incumbent with Limit.Nothing -> raise Optimistic_framework.NoIncumbent | Limit.Incumbent(qual,inc) -> if ((fn.g +. fn.h) *. bound) >= (inc.g +. inc.h) then raise Optimistic_framework.Done; let fpn = Dpq.peek_first pq in if fpn.fp < (inc.g +. inc.h) then (Dpq.remove pq fpn.ppos; Dpq.remove fq fpn.fpos; fpn) else (let trf = fn.fpos and trp = fn.ppos in Dpq.remove fq trf; Dpq.remove pq trp; fn) let make_interface sface wt = Search_interface.make ~node_expand:(make_expand sface.Search_interface.domain_expand sface.Search_interface.h wt) ~key:(wrap sface.Search_interface.key) ~goal_p:(wrap sface.Search_interface.goal_p) ~halt_on:sface.Search_interface.halt_on ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals sface.Search_interface.domain { fp = neg_infinity; h = neg_infinity; g = 0.; ppos = Dpq.no_position; fpos = Dpq.no_position; dpos = Dpq.no_position; data = sface.Search_interface.initial} better_p (Limit.make_default_logger (fun n -> n.h +. n.g) (wrap sface.Search_interface.get_sol_length)) let no_dups sface args = let bound = Search_args.get_float "Optimistic_search.no_dups" args 0 and wt = Search_args.get_float "Optimistic_search.no_dups" args 1 in let wt = (bound -. 1.) *. wt +. 1. in let search_interface = make_interface sface wt in Limit.unwrap_sol5 unwrap_sol (Optimistic_framework.no_dups search_interface get_node ordered_p bound better_p ordered_f set_pq_pos set_f_pos) let dups sface args = let bound = Search_args.get_float "Optimistic_search.dups" args 0 and wt = Search_args.get_float "Optimistic_search.dups" args 1 in let wt = (bound -. 1.) *. wt +. 1. in let search_interface = make_interface sface wt in Limit.unwrap_sol6 unwrap_sol (Optimistic_framework.dups search_interface get_node ordered_p bound better_p ordered_f set_pq_pos set_f_pos get_pq_pos get_f_pos) let delay_dups sface args = * Performs optimistic search in domains with duplicates . Duplicate states are only considered for expansion during the cleanup phase are only considered for expansion during the cleanup phase*) let bound = Search_args.get_float "Optimistic_search.delay_dups" args 0 and wt = Search_args.get_float "Optimistic_search.delay_dups" args 1 in let wt = (bound -. 1.) *. wt +. 1. in let search_interface = make_interface sface wt in Limit.unwrap_sol6 unwrap_sol (Optimistic_framework.delay search_interface get_node ordered_p bound better_p ordered_f set_pq_pos set_d_pos set_f_pos get_pq_pos get_d_pos get_f_pos) EOF
97d16aa63697ef80c2f1f24c40817606583c6dd8b021f34fd3cba26a887a0a6d
anmonteiro/ocaml-h2
h2_async.ml
---------------------------------------------------------------------------- * Copyright ( c ) 2018 Inhabited Type LLC . * Copyright ( c ) 2019 - 2020 . * * All rights reserved . * * Redistribution and use in source and binary forms , with or without * modification , are permitted provided that the following conditions * are met : * * 1 . Redistributions of source code must retain the above copyright * notice , this list of conditions and the following disclaimer . * * 2 . Redistributions in binary form must reproduce the above copyright * notice , this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution . * * 3 . Neither the name of the author nor the names of his contributors * may be used to endorse or promote products derived from this software * without specific prior written permission . * * THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ` ` AS IS '' AND ANY EXPRESS * OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED . IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL * DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , * STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE . * --------------------------------------------------------------------------- * Copyright (c) 2018 Inhabited Type LLC. * Copyright (c) 2019-2020 Antonio N. Monteiro. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the author nor the names of his contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*) open Async open H2 module Server = struct type 'a socket = ([ `Active ], ([< Socket.Address.t ] as 'a)) Socket.t let create_connection_handler ?(config = H2.Config.default) ~request_handler ~error_handler client_addr socket = let connection = H2.Server_connection.create ~config ~error_handler:(error_handler client_addr) (request_handler client_addr) in Gluten_async.Server.create_connection_handler ~read_buffer_size:config.read_buffer_size ~protocol:(module H2.Server_connection) connection client_addr socket module SSL = struct let create_connection_handler ?(config = H2.Config.default) ~request_handler ~error_handler client_addr socket = let connection = H2.Server_connection.create ~config ~error_handler:(error_handler client_addr) (request_handler client_addr) in Gluten_async.Server.SSL.create_connection_handler ~read_buffer_size:config.read_buffer_size ~protocol:(module H2.Server_connection) connection client_addr socket let create_connection_handler_with_default ~certfile ~keyfile ?config ~request_handler ~error_handler = let make_ssl_server = Gluten_async.Server.SSL.create_default ~alpn_protocols:[ "h2" ] ~certfile ~keyfile in fun client_addr socket -> make_ssl_server client_addr socket >>= fun ssl_server -> create_connection_handler ?config ~request_handler ~error_handler client_addr ssl_server end end module Client = struct module Client_runtime = Gluten_async.Client type 'a socket = 'a Client_runtime.socket type 'a runtime = 'a Client_runtime.t type 'a t = { connection : Client_connection.t ; runtime : 'a runtime } let create_connection ?(config = Config.default) ?push_handler ~error_handler socket = let connection = Client_connection.create ~config ?push_handler ~error_handler () in Client_runtime.create ~read_buffer_size:config.read_buffer_size ~protocol:(module Client_connection) connection socket >>| fun runtime -> { runtime; connection } let request t = Client_connection.request t.connection let ping t = Client_connection.ping t.connection let shutdown t = Client_runtime.shutdown t.runtime let is_closed t = Client_runtime.is_closed t.runtime module SSL = struct module Client_runtime = Gluten_async.Client.SSL type 'a socket = 'a Client_runtime.socket type 'a runtime = 'a Client_runtime.t type 'a t = { connection : Client_connection.t ; runtime : 'a runtime } let create_connection ?(config = Config.default) ?push_handler ~error_handler socket = let connection = Client_connection.create ~config ?push_handler ~error_handler () in Client_runtime.create ~read_buffer_size:config.read_buffer_size ~protocol:(module Client_connection) connection socket >>| fun runtime -> { runtime; connection } let create_connection_with_default ?(config = Config.default) ?push_handler ~error_handler socket = Client_runtime.create_default ~alpn_protocols:[ "http/1.1" ] socket >>= fun ssl_client -> create_connection ~config ?push_handler ~error_handler ssl_client let request t = Client_connection.request t.connection let ping t = Client_connection.ping t.connection let shutdown t = Client_runtime.shutdown t.runtime let is_closed t = Client_runtime.is_closed t.runtime end module TLS = struct module Client_runtime = Gluten_async.Client.TLS type 'a socket = 'a Client_runtime.socket type 'a runtime = 'a Client_runtime.t type 'a t = { connection : Client_connection.t ; runtime : 'a runtime } let create_connection ?(config = Config.default) ?push_handler ~error_handler socket = let connection = Client_connection.create ~config ?push_handler ~error_handler () in Client_runtime.create ~read_buffer_size:config.read_buffer_size ~protocol:(module Client_connection) connection socket >>| fun runtime -> { runtime; connection } let create_connection_with_default ?(config = Config.default) ?push_handler ~error_handler socket where_to_connect = Client_runtime.create_default ~alpn_protocols:[ "http/1.1" ] socket where_to_connect >>= fun tls_client -> create_connection ~config ?push_handler ~error_handler tls_client let request t = Client_connection.request t.connection let ping t = Client_connection.ping t.connection let shutdown t = Client_runtime.shutdown t.runtime let is_closed t = Client_runtime.is_closed t.runtime end end
null
https://raw.githubusercontent.com/anmonteiro/ocaml-h2/5a71d3acbfb081024b1412eb2f867cfd4db9d10e/async/h2_async.ml
ocaml
---------------------------------------------------------------------------- * Copyright ( c ) 2018 Inhabited Type LLC . * Copyright ( c ) 2019 - 2020 . * * All rights reserved . * * Redistribution and use in source and binary forms , with or without * modification , are permitted provided that the following conditions * are met : * * 1 . Redistributions of source code must retain the above copyright * notice , this list of conditions and the following disclaimer . * * 2 . Redistributions in binary form must reproduce the above copyright * notice , this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution . * * 3 . Neither the name of the author nor the names of his contributors * may be used to endorse or promote products derived from this software * without specific prior written permission . * * THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ` ` AS IS '' AND ANY EXPRESS * OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED . IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL * DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , * STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE . * --------------------------------------------------------------------------- * Copyright (c) 2018 Inhabited Type LLC. * Copyright (c) 2019-2020 Antonio N. Monteiro. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the author nor the names of his contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*) open Async open H2 module Server = struct type 'a socket = ([ `Active ], ([< Socket.Address.t ] as 'a)) Socket.t let create_connection_handler ?(config = H2.Config.default) ~request_handler ~error_handler client_addr socket = let connection = H2.Server_connection.create ~config ~error_handler:(error_handler client_addr) (request_handler client_addr) in Gluten_async.Server.create_connection_handler ~read_buffer_size:config.read_buffer_size ~protocol:(module H2.Server_connection) connection client_addr socket module SSL = struct let create_connection_handler ?(config = H2.Config.default) ~request_handler ~error_handler client_addr socket = let connection = H2.Server_connection.create ~config ~error_handler:(error_handler client_addr) (request_handler client_addr) in Gluten_async.Server.SSL.create_connection_handler ~read_buffer_size:config.read_buffer_size ~protocol:(module H2.Server_connection) connection client_addr socket let create_connection_handler_with_default ~certfile ~keyfile ?config ~request_handler ~error_handler = let make_ssl_server = Gluten_async.Server.SSL.create_default ~alpn_protocols:[ "h2" ] ~certfile ~keyfile in fun client_addr socket -> make_ssl_server client_addr socket >>= fun ssl_server -> create_connection_handler ?config ~request_handler ~error_handler client_addr ssl_server end end module Client = struct module Client_runtime = Gluten_async.Client type 'a socket = 'a Client_runtime.socket type 'a runtime = 'a Client_runtime.t type 'a t = { connection : Client_connection.t ; runtime : 'a runtime } let create_connection ?(config = Config.default) ?push_handler ~error_handler socket = let connection = Client_connection.create ~config ?push_handler ~error_handler () in Client_runtime.create ~read_buffer_size:config.read_buffer_size ~protocol:(module Client_connection) connection socket >>| fun runtime -> { runtime; connection } let request t = Client_connection.request t.connection let ping t = Client_connection.ping t.connection let shutdown t = Client_runtime.shutdown t.runtime let is_closed t = Client_runtime.is_closed t.runtime module SSL = struct module Client_runtime = Gluten_async.Client.SSL type 'a socket = 'a Client_runtime.socket type 'a runtime = 'a Client_runtime.t type 'a t = { connection : Client_connection.t ; runtime : 'a runtime } let create_connection ?(config = Config.default) ?push_handler ~error_handler socket = let connection = Client_connection.create ~config ?push_handler ~error_handler () in Client_runtime.create ~read_buffer_size:config.read_buffer_size ~protocol:(module Client_connection) connection socket >>| fun runtime -> { runtime; connection } let create_connection_with_default ?(config = Config.default) ?push_handler ~error_handler socket = Client_runtime.create_default ~alpn_protocols:[ "http/1.1" ] socket >>= fun ssl_client -> create_connection ~config ?push_handler ~error_handler ssl_client let request t = Client_connection.request t.connection let ping t = Client_connection.ping t.connection let shutdown t = Client_runtime.shutdown t.runtime let is_closed t = Client_runtime.is_closed t.runtime end module TLS = struct module Client_runtime = Gluten_async.Client.TLS type 'a socket = 'a Client_runtime.socket type 'a runtime = 'a Client_runtime.t type 'a t = { connection : Client_connection.t ; runtime : 'a runtime } let create_connection ?(config = Config.default) ?push_handler ~error_handler socket = let connection = Client_connection.create ~config ?push_handler ~error_handler () in Client_runtime.create ~read_buffer_size:config.read_buffer_size ~protocol:(module Client_connection) connection socket >>| fun runtime -> { runtime; connection } let create_connection_with_default ?(config = Config.default) ?push_handler ~error_handler socket where_to_connect = Client_runtime.create_default ~alpn_protocols:[ "http/1.1" ] socket where_to_connect >>= fun tls_client -> create_connection ~config ?push_handler ~error_handler tls_client let request t = Client_connection.request t.connection let ping t = Client_connection.ping t.connection let shutdown t = Client_runtime.shutdown t.runtime let is_closed t = Client_runtime.is_closed t.runtime end end
35427e3226ac8e58cbedeae0eddf1f026a0134643e2a9620d72d250fdf7cc451
deedy/Custom-Scheme-Interpreter
eval.ml
open Ast open Heap open Util let rec eval (ast : expr) (env : env) : value = match ast with | Int_e n -> Int n | Str_e s -> Str s | Bool_e b -> Bool b | Def_e _ -> runtime "define may occur at top level only" | Defrec_e _ -> runtime "definerec may occur at top level only" | Nil_e -> Nil | Id_e id -> (match (lookup id env) with | None -> Nil | Some v -> v) | Cons_e (x, y) -> Cons ((eval x env),(eval y env)) | Let_e (x, e1, e2) -> let newenv=(bind x (eval e1 env) env) in (eval e2 newenv) | Letrec_e (x, e1, e2) -> let newenv = (bind x (Undef) env) in update x (eval e1 newenv) newenv; (eval e2 newenv) | If_e (b, e1, e2) -> (match (eval b env) with | Bool bee -> if (bee) then (eval e1 env) else (eval e2 env) | _ -> runtime "No bool case matched for if") | Apply_e (e1, es) -> let foo acc ele = apply acc (eval ele env) in let res = List.fold_left foo (eval e1 env) es in (match res with | Closure(Fun_e(xs,e),env) -> (match xs with | [] -> eval e env | _ -> res) | _ -> runtime "No closure match 2") | Fun_e (xs, e) -> Closure (Fun_e(xs,e),env) | Binop_e (op, e1, e2) -> apply_binop op (eval e1 env) (eval e2 env) | Unop_e (op, e) -> apply_unop op (eval e env) | Delayed_e (ex) -> Closure (ex,env); | Forced_e (del_expr) -> let res = (eval del_expr env) in match res with | Closure(a,b) -> eval a b | _ -> res and apply (f : value) (v : value) : value = (match f with | Closure(Fun_e(xs,e),env) -> (match xs with | [] -> eval e env | idhd::idtl -> let newenv = bind idhd v env in Closure(Fun_e(idtl,e),newenv) ) | _ -> runtime "No closure match") and apply_binop (op : op) (v1 : value) (v2 : value) : value = match op with Plus -> (match (v1, v2) with (Int m, Int n) -> Int (m + n) | _ -> runtime "applying + to non-integer") | Minus -> (match (v1, v2) with (Int m, Int n) -> Int (m - n) | _ -> runtime "applying - to non-integer") | Mul -> (match (v1, v2) with (Int m, Int n) -> Int (m * n) | _ -> runtime "applying * to non-integer") | Div -> (match (v1, v2) with (Int m, Int n) -> Int (m / n) | _ -> runtime "applying / to non-integer") | Mod -> (match (v1, v2) with (Int m, Int n) -> Int (m mod n) | _ -> runtime "applying % to non-integer") | Eq -> (match (v1, v2) with (Int m, Int n) -> Bool (m = n) | (Str m, Str n) -> Bool (m = n) | (Bool m, Bool n) -> Bool (m = n) | _ -> runtime "inappropriate comparison with =") | Neq -> (match (v1, v2) with (Int m, Int n) -> Bool (m <> n) | (Str m, Str n) -> Bool (m <> n) | (Bool m, Bool n) -> Bool (m <> n) | _ -> runtime "inappropriate comparison with !=") | Lt -> (match (v1, v2) with (Int m, Int n) -> Bool (m < n) | (Str m, Str n) -> Bool (m < n) | (Bool m, Bool n) -> Bool (m < n) | _ -> runtime "inappropriate comparison with <") | Leq -> (match (v1, v2) with (Int m, Int n) -> Bool (m <= n) | (Str m, Str n) -> Bool (m <= n) | (Bool m, Bool n) -> Bool (m <= n) | _ -> runtime "inappropriate comparison with <=") | Gt -> (match (v1, v2) with (Int m, Int n) -> Bool (m > n) | (Str m, Str n) -> Bool (m > n) | (Bool m, Bool n) -> Bool (m > n) | _ -> runtime "inappropriate comparison with >") | Geq -> (match (v1, v2) with (Int m, Int n) -> Bool (m >= n) | (Str m, Str n) -> Bool (m >= n) | (Bool m, Bool n) -> Bool (m >= n) | _ -> runtime "inappropriate comparison with >=") | And -> (match (v1, v2) with (Bool m, Bool n) -> Bool (m && n) | _ -> runtime "applying & to non-boolean") | Or -> (match (v1, v2) with (Bool m, Bool n) -> Bool (m || n) | _ -> runtime "applying | to non-boolean") | _ -> runtime "not a binary operator" and apply_unop (op : op) (v : value) : value = match op with | Minus -> (match v with Int n -> Int (-n) | _ -> runtime "applying - to non-integer") | Not -> (match v with Bool b -> Bool (not b) | _ -> runtime "applying ~ to non-boolean") | Car -> (match v with Cons (x, y) -> x | _ -> runtime "inappropriate argument for car") | Cdr -> (match v with Cons (x, y) -> y | _ -> runtime "inappropriate argument for cdr") | Null -> (match v with Cons (x, y) -> Bool false | Nil -> Bool true | _ -> runtime "inappropriate argument for null") | Load -> runtime "load may only occur at top level" | _ -> runtime "not a unary operator"
null
https://raw.githubusercontent.com/deedy/Custom-Scheme-Interpreter/ad49612f809e54eb48f5a3af3428022856574b77/eval.ml
ocaml
open Ast open Heap open Util let rec eval (ast : expr) (env : env) : value = match ast with | Int_e n -> Int n | Str_e s -> Str s | Bool_e b -> Bool b | Def_e _ -> runtime "define may occur at top level only" | Defrec_e _ -> runtime "definerec may occur at top level only" | Nil_e -> Nil | Id_e id -> (match (lookup id env) with | None -> Nil | Some v -> v) | Cons_e (x, y) -> Cons ((eval x env),(eval y env)) | Let_e (x, e1, e2) -> let newenv=(bind x (eval e1 env) env) in (eval e2 newenv) | Letrec_e (x, e1, e2) -> let newenv = (bind x (Undef) env) in update x (eval e1 newenv) newenv; (eval e2 newenv) | If_e (b, e1, e2) -> (match (eval b env) with | Bool bee -> if (bee) then (eval e1 env) else (eval e2 env) | _ -> runtime "No bool case matched for if") | Apply_e (e1, es) -> let foo acc ele = apply acc (eval ele env) in let res = List.fold_left foo (eval e1 env) es in (match res with | Closure(Fun_e(xs,e),env) -> (match xs with | [] -> eval e env | _ -> res) | _ -> runtime "No closure match 2") | Fun_e (xs, e) -> Closure (Fun_e(xs,e),env) | Binop_e (op, e1, e2) -> apply_binop op (eval e1 env) (eval e2 env) | Unop_e (op, e) -> apply_unop op (eval e env) | Delayed_e (ex) -> Closure (ex,env); | Forced_e (del_expr) -> let res = (eval del_expr env) in match res with | Closure(a,b) -> eval a b | _ -> res and apply (f : value) (v : value) : value = (match f with | Closure(Fun_e(xs,e),env) -> (match xs with | [] -> eval e env | idhd::idtl -> let newenv = bind idhd v env in Closure(Fun_e(idtl,e),newenv) ) | _ -> runtime "No closure match") and apply_binop (op : op) (v1 : value) (v2 : value) : value = match op with Plus -> (match (v1, v2) with (Int m, Int n) -> Int (m + n) | _ -> runtime "applying + to non-integer") | Minus -> (match (v1, v2) with (Int m, Int n) -> Int (m - n) | _ -> runtime "applying - to non-integer") | Mul -> (match (v1, v2) with (Int m, Int n) -> Int (m * n) | _ -> runtime "applying * to non-integer") | Div -> (match (v1, v2) with (Int m, Int n) -> Int (m / n) | _ -> runtime "applying / to non-integer") | Mod -> (match (v1, v2) with (Int m, Int n) -> Int (m mod n) | _ -> runtime "applying % to non-integer") | Eq -> (match (v1, v2) with (Int m, Int n) -> Bool (m = n) | (Str m, Str n) -> Bool (m = n) | (Bool m, Bool n) -> Bool (m = n) | _ -> runtime "inappropriate comparison with =") | Neq -> (match (v1, v2) with (Int m, Int n) -> Bool (m <> n) | (Str m, Str n) -> Bool (m <> n) | (Bool m, Bool n) -> Bool (m <> n) | _ -> runtime "inappropriate comparison with !=") | Lt -> (match (v1, v2) with (Int m, Int n) -> Bool (m < n) | (Str m, Str n) -> Bool (m < n) | (Bool m, Bool n) -> Bool (m < n) | _ -> runtime "inappropriate comparison with <") | Leq -> (match (v1, v2) with (Int m, Int n) -> Bool (m <= n) | (Str m, Str n) -> Bool (m <= n) | (Bool m, Bool n) -> Bool (m <= n) | _ -> runtime "inappropriate comparison with <=") | Gt -> (match (v1, v2) with (Int m, Int n) -> Bool (m > n) | (Str m, Str n) -> Bool (m > n) | (Bool m, Bool n) -> Bool (m > n) | _ -> runtime "inappropriate comparison with >") | Geq -> (match (v1, v2) with (Int m, Int n) -> Bool (m >= n) | (Str m, Str n) -> Bool (m >= n) | (Bool m, Bool n) -> Bool (m >= n) | _ -> runtime "inappropriate comparison with >=") | And -> (match (v1, v2) with (Bool m, Bool n) -> Bool (m && n) | _ -> runtime "applying & to non-boolean") | Or -> (match (v1, v2) with (Bool m, Bool n) -> Bool (m || n) | _ -> runtime "applying | to non-boolean") | _ -> runtime "not a binary operator" and apply_unop (op : op) (v : value) : value = match op with | Minus -> (match v with Int n -> Int (-n) | _ -> runtime "applying - to non-integer") | Not -> (match v with Bool b -> Bool (not b) | _ -> runtime "applying ~ to non-boolean") | Car -> (match v with Cons (x, y) -> x | _ -> runtime "inappropriate argument for car") | Cdr -> (match v with Cons (x, y) -> y | _ -> runtime "inappropriate argument for cdr") | Null -> (match v with Cons (x, y) -> Bool false | Nil -> Bool true | _ -> runtime "inappropriate argument for null") | Load -> runtime "load may only occur at top level" | _ -> runtime "not a unary operator"
6f43a5c0cbc46d8829b95c64da5f3f04eb54ecdc3c7fcbafe5a39b10f57dd5a6
returntocorp/semgrep
ruby_log.ml
open Format type pos = Lexing.position type ctx = | Ctx_Empty | Ctx_Pos of pos * ctx | Ctx_Msg of string * ctx | Ctx_Merge of ctx * ctx let empty = Ctx_Empty let loc pos ctx = Ctx_Pos (pos, ctx) let of_loc pos = loc pos Ctx_Empty let of_tok _x = raise Common.Todo let msg str ctx = Ctx_Msg (str, ctx) let of_msg str = msg str Ctx_Empty let merge c1 c2 = Ctx_Merge (c1, c2) let rec exists msg pos = function | Ctx_Empty -> false | Ctx_Msg (msg', Ctx_Pos (pos', rest)) -> if msg = msg' && pos = pos' then true else exists msg pos rest | Ctx_Pos (_, rest) | Ctx_Msg (_, rest) -> exists msg pos rest | Ctx_Merge (c1, c2) -> exists msg pos c1 || exists msg pos c2 let rec append c1 c2 = match c1 with | Ctx_Empty -> c2 | Ctx_Msg (msg, Ctx_Pos (pos, rest)) -> if exists msg pos c2 then append rest c2 else Ctx_Msg (msg, Ctx_Pos (pos, append rest c2)) | Ctx_Pos (p, ctx) -> Ctx_Pos (p, append ctx c2) | Ctx_Msg (s, ctx) -> Ctx_Msg (s, append ctx c2) | Ctx_Merge _ -> Ctx_Merge (c1, c2) let kfsprintf f fmt = let b = Buffer.create 127 in let ppf = Format.formatter_of_buffer b in Format.pp_set_margin ppf (*(Format.pp_get_margin std_formatter ())*) 80; Format.kfprintf (fun ppf -> Format.pp_print_flush ppf (); f (Buffer.contents b)) ppf fmt let in_ctx ctx ?pos fmt = match pos with | None -> kfsprintf (fun msg -> Ctx_Msg (msg, ctx)) fmt | Some p -> kfsprintf (fun msg -> Ctx_Msg (msg, Ctx_Pos (p, ctx))) fmt let format_pos ppf pos = fprintf ppf "%s:%d " (*Filename.basename*) pos.Lexing.pos_fname pos.Lexing.pos_lnum let lvl _i = (*conf.debug_level >= i*) true let stderr_ppf = formatter_of_out_channel stderr (* let fake_ppf = make_formatter (fun s pos len -> ()) (fun () -> ()) *) let dup_tbl = Hashtbl.create 12373 (* prime *) let rec format_ctx ppf ctx = let rec work ppf = function | Ctx_Empty -> () | Ctx_Pos (pos, Ctx_Empty) -> fprintf ppf "at %a" format_pos pos | Ctx_Msg (msg, Ctx_Pos (pos, Ctx_Empty)) -> fprintf ppf "@[<v 0>in %s@,at %a@]" msg format_pos pos | Ctx_Msg (msg, Ctx_Empty) -> fprintf ppf "in %s" msg | Ctx_Pos (pos, ctx) -> fprintf ppf "at %a@," format_pos pos; work ppf ctx | Ctx_Msg (msg, Ctx_Pos (pos, ctx)) -> fprintf ppf "in %s@,at %a@," msg format_pos pos; work ppf ctx | Ctx_Msg (msg, ctx) -> fprintf ppf "in %s@," msg; work ppf ctx | Ctx_Merge (ctx1, ctx2) -> fprintf ppf "@[<v 0>@[<v 0>in MERGING@, %a@]@,@[<v 0>AND@, %a@]@]" format_ctx ctx2 format_ctx ctx1 in fprintf ppf "@[<v>%a@]" work ctx let output_header cont code fmt = kfsprintf cont ("@[<v 2>[%s] " ^^ fmt ^^ "@]") code let output_msg_ctx ppf msg ctx = fprintf ppf "@[<v 0>%s@, @[<v>%a@]@]@\n@.%!" msg format_ctx ctx let show b no_dup ctx code fmt = output_header (fun msg -> if b then let buf = Buffer.create 127 in let ppf = Format.formatter_of_buffer buf in let () = output_msg_ctx ppf msg ctx in if no_dup then let full_msg = Buffer.contents buf in if Hashtbl.mem dup_tbl full_msg then () else ( Hashtbl.add dup_tbl full_msg (); pp_print_string stderr_ppf full_msg) else Buffer.output_buffer stderr buf) code fmt let flush () = Format.pp_print_flush stderr_ppf () let () = at_exit flush let fixme ?(ctx = Ctx_Empty) fmt = show true (*conf.no_dup_errors*) true ctx "FIXME" fmt let debug ?pos fmt = match pos with | None -> show (lvl 10) false Ctx_Empty "DEBUG" fmt | Some p -> show (lvl 10) false (of_loc p) "DEBUG" fmt let note ?(ctx = Ctx_Empty) fmt = show (lvl 10) false ctx "NOTE" fmt let warn ?(ctx = Ctx_Empty) fmt = show (lvl 1) false ctx "WARNING" fmt let show_raise ctx code fmt = let fail m = conf.error_raises_exc Format.pp_print_flush stderr_ppf (); failwith m in output_header fail code fmt let err ?(ctx = Ctx_Empty) fmt = conf.error_raises_exc else show true (*conf.no_dup_errors*) true ctx "ERROR" fmt let fatal ctx fmt = (*conf.print_error_ctx <- true;*) show_raise ctx "FATAL" fmt
null
https://raw.githubusercontent.com/returntocorp/semgrep/00f1e67bbb80f00e29db3381288fc00398b6868a/languages/ruby/dyp/ruby_log.ml
ocaml
(Format.pp_get_margin std_formatter ()) Filename.basename conf.debug_level >= i let fake_ppf = make_formatter (fun s pos len -> ()) (fun () -> ()) prime conf.no_dup_errors conf.no_dup_errors conf.print_error_ctx <- true;
open Format type pos = Lexing.position type ctx = | Ctx_Empty | Ctx_Pos of pos * ctx | Ctx_Msg of string * ctx | Ctx_Merge of ctx * ctx let empty = Ctx_Empty let loc pos ctx = Ctx_Pos (pos, ctx) let of_loc pos = loc pos Ctx_Empty let of_tok _x = raise Common.Todo let msg str ctx = Ctx_Msg (str, ctx) let of_msg str = msg str Ctx_Empty let merge c1 c2 = Ctx_Merge (c1, c2) let rec exists msg pos = function | Ctx_Empty -> false | Ctx_Msg (msg', Ctx_Pos (pos', rest)) -> if msg = msg' && pos = pos' then true else exists msg pos rest | Ctx_Pos (_, rest) | Ctx_Msg (_, rest) -> exists msg pos rest | Ctx_Merge (c1, c2) -> exists msg pos c1 || exists msg pos c2 let rec append c1 c2 = match c1 with | Ctx_Empty -> c2 | Ctx_Msg (msg, Ctx_Pos (pos, rest)) -> if exists msg pos c2 then append rest c2 else Ctx_Msg (msg, Ctx_Pos (pos, append rest c2)) | Ctx_Pos (p, ctx) -> Ctx_Pos (p, append ctx c2) | Ctx_Msg (s, ctx) -> Ctx_Msg (s, append ctx c2) | Ctx_Merge _ -> Ctx_Merge (c1, c2) let kfsprintf f fmt = let b = Buffer.create 127 in let ppf = Format.formatter_of_buffer b in Format.kfprintf (fun ppf -> Format.pp_print_flush ppf (); f (Buffer.contents b)) ppf fmt let in_ctx ctx ?pos fmt = match pos with | None -> kfsprintf (fun msg -> Ctx_Msg (msg, ctx)) fmt | Some p -> kfsprintf (fun msg -> Ctx_Msg (msg, Ctx_Pos (p, ctx))) fmt let format_pos ppf pos = pos.Lexing.pos_lnum let stderr_ppf = formatter_of_out_channel stderr let rec format_ctx ppf ctx = let rec work ppf = function | Ctx_Empty -> () | Ctx_Pos (pos, Ctx_Empty) -> fprintf ppf "at %a" format_pos pos | Ctx_Msg (msg, Ctx_Pos (pos, Ctx_Empty)) -> fprintf ppf "@[<v 0>in %s@,at %a@]" msg format_pos pos | Ctx_Msg (msg, Ctx_Empty) -> fprintf ppf "in %s" msg | Ctx_Pos (pos, ctx) -> fprintf ppf "at %a@," format_pos pos; work ppf ctx | Ctx_Msg (msg, Ctx_Pos (pos, ctx)) -> fprintf ppf "in %s@,at %a@," msg format_pos pos; work ppf ctx | Ctx_Msg (msg, ctx) -> fprintf ppf "in %s@," msg; work ppf ctx | Ctx_Merge (ctx1, ctx2) -> fprintf ppf "@[<v 0>@[<v 0>in MERGING@, %a@]@,@[<v 0>AND@, %a@]@]" format_ctx ctx2 format_ctx ctx1 in fprintf ppf "@[<v>%a@]" work ctx let output_header cont code fmt = kfsprintf cont ("@[<v 2>[%s] " ^^ fmt ^^ "@]") code let output_msg_ctx ppf msg ctx = fprintf ppf "@[<v 0>%s@, @[<v>%a@]@]@\n@.%!" msg format_ctx ctx let show b no_dup ctx code fmt = output_header (fun msg -> if b then let buf = Buffer.create 127 in let ppf = Format.formatter_of_buffer buf in let () = output_msg_ctx ppf msg ctx in if no_dup then let full_msg = Buffer.contents buf in if Hashtbl.mem dup_tbl full_msg then () else ( Hashtbl.add dup_tbl full_msg (); pp_print_string stderr_ppf full_msg) else Buffer.output_buffer stderr buf) code fmt let flush () = Format.pp_print_flush stderr_ppf () let () = at_exit flush let fixme ?(ctx = Ctx_Empty) fmt = let debug ?pos fmt = match pos with | None -> show (lvl 10) false Ctx_Empty "DEBUG" fmt | Some p -> show (lvl 10) false (of_loc p) "DEBUG" fmt let note ?(ctx = Ctx_Empty) fmt = show (lvl 10) false ctx "NOTE" fmt let warn ?(ctx = Ctx_Empty) fmt = show (lvl 1) false ctx "WARNING" fmt let show_raise ctx code fmt = let fail m = conf.error_raises_exc Format.pp_print_flush stderr_ppf (); failwith m in output_header fail code fmt let err ?(ctx = Ctx_Empty) fmt = conf.error_raises_exc let fatal ctx fmt = show_raise ctx "FATAL" fmt
1c3f995d223696de6b652a16b3d9bc886417038edeb36e07f6d319b7fe05bcb8
cronokirby/haze
TieredList.hs
| Description : Contains functions and utilities for TieredLists Description: Contains functions and utilities for TieredLists -} module Data.TieredList ( TieredList , makeTieredList , tieredSingleton , popTiered ) where import Relude -- | Represents a list of tiers of equal priority newtype TieredList a = TieredList [[a]] deriving (Eq, Show) -- | Make a Tiered list from a list of tiers makeTieredList :: [[a]] -> TieredList a makeTieredList = TieredList -- | Make a tiered list with a single item tieredSingleton :: a -> TieredList a tieredSingleton a = makeTieredList [[a]] {- | Pop off the highest priority element from a tiered list. Returns Nothing if the list is null -} popTiered :: TieredList a -> Maybe (a, TieredList a) popTiered (TieredList [] ) = Nothing popTiered (TieredList ([] : rest)) = popTiered (TieredList rest) popTiered (TieredList ((x : xs) : rest)) = Just (x, TieredList (xs : rest))
null
https://raw.githubusercontent.com/cronokirby/haze/3cfbc9de8d923a541429f4a5cb1eb4151d5aea08/src/Data/TieredList.hs
haskell
| Represents a list of tiers of equal priority | Make a Tiered list from a list of tiers | Make a tiered list with a single item | Pop off the highest priority element from a tiered list. Returns Nothing if the list is null
| Description : Contains functions and utilities for TieredLists Description: Contains functions and utilities for TieredLists -} module Data.TieredList ( TieredList , makeTieredList , tieredSingleton , popTiered ) where import Relude newtype TieredList a = TieredList [[a]] deriving (Eq, Show) makeTieredList :: [[a]] -> TieredList a makeTieredList = TieredList tieredSingleton :: a -> TieredList a tieredSingleton a = makeTieredList [[a]] popTiered :: TieredList a -> Maybe (a, TieredList a) popTiered (TieredList [] ) = Nothing popTiered (TieredList ([] : rest)) = popTiered (TieredList rest) popTiered (TieredList ((x : xs) : rest)) = Just (x, TieredList (xs : rest))
50ab8c90ff0d3e89249ae57cc5ea2e028e8b58dd8883c17cb8c5a7ba452b77b2
ocaml/dune
vcs_tests.ml
open Stdune open Dune_engine open Fiber.O open! Dune_tests_common module Config = Dune_util.Config let () = init () let printf = Printf.printf let temp_dir = lazy (Path.of_string "vcs-tests") let () = at_exit (fun () -> Path.rm_rf (Lazy.force temp_dir)) (* When hg is not available, we test with git twice indeed. This is because many people don't have hg installed. *) let has_hg = match Lazy.force Vcs.hg with | (_ : Path.t) -> true | exception _ -> false let run (vcs : Vcs.t) args = let prog, prog_str, real_args = match vcs.kind with | Git -> (Vcs.git, "git", args) | Hg -> ( if has_hg then (Vcs.hg, "hg", args) else ( Vcs.git , "hg" , match args with | [ "tag"; s; "-u"; _ ] -> [ "tag"; "-a"; s; "-m"; s ] | [ "commit"; "-m"; msg; "-u"; _ ] -> [ "commit"; "-m"; msg ] | _ -> args )) in printf "$ %s\n" (List.map (prog_str :: args) ~f:String.quote_for_shell |> String.concat ~sep:" "); Process.run Strict (Lazy.force prog) real_args ~display:Quiet ~env: One of the reasons to set GIT_DIR is to override any GIT_DIR set by the environment , which helps for example during [ git rebase --exec ] . the environment, which helps for example during [git rebase --exec]. *) Env.add Env.initial ~var:"GIT_DIR" ~value:(Filename.concat (Path.to_absolute_filename vcs.root) ".git")) ~dir:vcs.root ~stdout_to:(Process.Io.file Config.dev_null Process.Io.Out) type action = | Init | Add of string | Write of string * string | Commit | Tag of string | Describe of string let run_action (vcs : Vcs.t) action = match action with | Init -> run vcs [ "init"; "-q" ] | Add fn -> run vcs [ "add"; fn ] | Commit -> ( match vcs.kind with | Git -> run vcs [ "commit"; "-m"; "commit message" ] | Hg -> run vcs [ "commit"; "-m"; "commit message"; "-u"; "toto" ]) | Write (fn, s) -> printf "$ echo %S > %s\n" s fn; Io.write_file (Path.relative (Lazy.force temp_dir) fn) s; Fiber.return () | Describe expected -> printf "$ %s describe [...]\n" (match vcs.kind with | Git -> "git" | Hg -> "hg"); Memo.reset (Memo.Invalidation.clear_caches ~reason:Test); let vcs = match vcs.kind with | Hg when not has_hg -> { vcs with kind = Git } | _ -> vcs in let+ s = Memo.run (Vcs.describe vcs) in let s = Option.value s ~default:"n/a" in let processed = String.split s ~on:'-' |> List.map ~f:(fun s -> match s with | "" | "dirty" -> s | s when String.length s = 1 && String.for_all s ~f:(function | '0' .. '9' -> true | _ -> false) -> s | _ when String.for_all s ~f:(function | '0' .. '9' | 'a' .. 'z' -> true | _ -> false) -> "<commit-id>" | _ -> s) |> String.concat ~sep:"-" in printf "%s\n" processed; if processed <> expected then printf "Expected: %s\nOriginal: %s\n" expected s; printf "\n" | Tag s -> ( match vcs.kind with | Git -> run vcs [ "tag"; "-a"; s; "-m"; s ] | Hg -> run vcs [ "tag"; s; "-u"; "toto" ]) let run kind script = let (lazy temp_dir) = temp_dir in Path.rm_rf temp_dir; Path.mkdir_p temp_dir; let vcs = { Vcs.kind; root = temp_dir } in Dune_engine.Clflags.display := Short; let config = { Scheduler.Config.concurrency = 1 ; stats = None ; insignificant_changes = `React ; signal_watcher = `No } in Scheduler.Run.go ~on_event:(fun _ _ -> ()) config (fun () -> Fiber.sequential_iter script ~f:(run_action vcs)) let script = [ Init ; Write ("a", "-") ; Add "a" ; Commit ; Describe "<commit-id>" ; Write ("b", "-") ; Add "b" ; Describe "<commit-id>-dirty" ; Commit ; Describe "<commit-id>" ; Tag "1.0" ; Describe "1.0" ; Write ("c", "-") ; Add "c" ; Describe "1.0-dirty" ; Commit ; Describe "1.0-1-<commit-id>" ; Write ("d", "-") ; Add "d" ; Describe "1.0-1-<commit-id>-dirty" ; Commit ; Describe "1.0-2-<commit-id>" ] let%expect_test _ = run Git script; [%expect {| $ git init -q $ echo "-" > a $ git add a $ git commit -m 'commit message' $ git describe [...] <commit-id> $ echo "-" > b $ git add b $ git describe [...] <commit-id>-dirty $ git commit -m 'commit message' $ git describe [...] <commit-id> $ git tag -a 1.0 -m 1.0 $ git describe [...] 1.0 $ echo "-" > c $ git add c $ git describe [...] 1.0-dirty $ git commit -m 'commit message' $ git describe [...] 1.0-1-<commit-id> $ echo "-" > d $ git add d $ git describe [...] 1.0-1-<commit-id>-dirty $ git commit -m 'commit message' $ git describe [...] 1.0-2-<commit-id> |}] let%expect_test _ = run Hg script; [%expect {| $ hg init -q $ echo "-" > a $ hg add a $ hg commit -m 'commit message' -u toto $ hg describe [...] <commit-id> $ echo "-" > b $ hg add b $ hg describe [...] <commit-id>-dirty $ hg commit -m 'commit message' -u toto $ hg describe [...] <commit-id> $ hg tag 1.0 -u toto $ hg describe [...] 1.0 $ echo "-" > c $ hg add c $ hg describe [...] 1.0-dirty $ hg commit -m 'commit message' -u toto $ hg describe [...] 1.0-1-<commit-id> $ echo "-" > d $ hg add d $ hg describe [...] 1.0-1-<commit-id>-dirty $ hg commit -m 'commit message' -u toto $ hg describe [...] 1.0-2-<commit-id> |}]
null
https://raw.githubusercontent.com/ocaml/dune/5463cd87c573c28c71d513fbecd8cb17dbdb27b7/test/expect-tests/vcs_tests.ml
ocaml
When hg is not available, we test with git twice indeed. This is because many people don't have hg installed.
open Stdune open Dune_engine open Fiber.O open! Dune_tests_common module Config = Dune_util.Config let () = init () let printf = Printf.printf let temp_dir = lazy (Path.of_string "vcs-tests") let () = at_exit (fun () -> Path.rm_rf (Lazy.force temp_dir)) let has_hg = match Lazy.force Vcs.hg with | (_ : Path.t) -> true | exception _ -> false let run (vcs : Vcs.t) args = let prog, prog_str, real_args = match vcs.kind with | Git -> (Vcs.git, "git", args) | Hg -> ( if has_hg then (Vcs.hg, "hg", args) else ( Vcs.git , "hg" , match args with | [ "tag"; s; "-u"; _ ] -> [ "tag"; "-a"; s; "-m"; s ] | [ "commit"; "-m"; msg; "-u"; _ ] -> [ "commit"; "-m"; msg ] | _ -> args )) in printf "$ %s\n" (List.map (prog_str :: args) ~f:String.quote_for_shell |> String.concat ~sep:" "); Process.run Strict (Lazy.force prog) real_args ~display:Quiet ~env: One of the reasons to set GIT_DIR is to override any GIT_DIR set by the environment , which helps for example during [ git rebase --exec ] . the environment, which helps for example during [git rebase --exec]. *) Env.add Env.initial ~var:"GIT_DIR" ~value:(Filename.concat (Path.to_absolute_filename vcs.root) ".git")) ~dir:vcs.root ~stdout_to:(Process.Io.file Config.dev_null Process.Io.Out) type action = | Init | Add of string | Write of string * string | Commit | Tag of string | Describe of string let run_action (vcs : Vcs.t) action = match action with | Init -> run vcs [ "init"; "-q" ] | Add fn -> run vcs [ "add"; fn ] | Commit -> ( match vcs.kind with | Git -> run vcs [ "commit"; "-m"; "commit message" ] | Hg -> run vcs [ "commit"; "-m"; "commit message"; "-u"; "toto" ]) | Write (fn, s) -> printf "$ echo %S > %s\n" s fn; Io.write_file (Path.relative (Lazy.force temp_dir) fn) s; Fiber.return () | Describe expected -> printf "$ %s describe [...]\n" (match vcs.kind with | Git -> "git" | Hg -> "hg"); Memo.reset (Memo.Invalidation.clear_caches ~reason:Test); let vcs = match vcs.kind with | Hg when not has_hg -> { vcs with kind = Git } | _ -> vcs in let+ s = Memo.run (Vcs.describe vcs) in let s = Option.value s ~default:"n/a" in let processed = String.split s ~on:'-' |> List.map ~f:(fun s -> match s with | "" | "dirty" -> s | s when String.length s = 1 && String.for_all s ~f:(function | '0' .. '9' -> true | _ -> false) -> s | _ when String.for_all s ~f:(function | '0' .. '9' | 'a' .. 'z' -> true | _ -> false) -> "<commit-id>" | _ -> s) |> String.concat ~sep:"-" in printf "%s\n" processed; if processed <> expected then printf "Expected: %s\nOriginal: %s\n" expected s; printf "\n" | Tag s -> ( match vcs.kind with | Git -> run vcs [ "tag"; "-a"; s; "-m"; s ] | Hg -> run vcs [ "tag"; s; "-u"; "toto" ]) let run kind script = let (lazy temp_dir) = temp_dir in Path.rm_rf temp_dir; Path.mkdir_p temp_dir; let vcs = { Vcs.kind; root = temp_dir } in Dune_engine.Clflags.display := Short; let config = { Scheduler.Config.concurrency = 1 ; stats = None ; insignificant_changes = `React ; signal_watcher = `No } in Scheduler.Run.go ~on_event:(fun _ _ -> ()) config (fun () -> Fiber.sequential_iter script ~f:(run_action vcs)) let script = [ Init ; Write ("a", "-") ; Add "a" ; Commit ; Describe "<commit-id>" ; Write ("b", "-") ; Add "b" ; Describe "<commit-id>-dirty" ; Commit ; Describe "<commit-id>" ; Tag "1.0" ; Describe "1.0" ; Write ("c", "-") ; Add "c" ; Describe "1.0-dirty" ; Commit ; Describe "1.0-1-<commit-id>" ; Write ("d", "-") ; Add "d" ; Describe "1.0-1-<commit-id>-dirty" ; Commit ; Describe "1.0-2-<commit-id>" ] let%expect_test _ = run Git script; [%expect {| $ git init -q $ echo "-" > a $ git add a $ git commit -m 'commit message' $ git describe [...] <commit-id> $ echo "-" > b $ git add b $ git describe [...] <commit-id>-dirty $ git commit -m 'commit message' $ git describe [...] <commit-id> $ git tag -a 1.0 -m 1.0 $ git describe [...] 1.0 $ echo "-" > c $ git add c $ git describe [...] 1.0-dirty $ git commit -m 'commit message' $ git describe [...] 1.0-1-<commit-id> $ echo "-" > d $ git add d $ git describe [...] 1.0-1-<commit-id>-dirty $ git commit -m 'commit message' $ git describe [...] 1.0-2-<commit-id> |}] let%expect_test _ = run Hg script; [%expect {| $ hg init -q $ echo "-" > a $ hg add a $ hg commit -m 'commit message' -u toto $ hg describe [...] <commit-id> $ echo "-" > b $ hg add b $ hg describe [...] <commit-id>-dirty $ hg commit -m 'commit message' -u toto $ hg describe [...] <commit-id> $ hg tag 1.0 -u toto $ hg describe [...] 1.0 $ echo "-" > c $ hg add c $ hg describe [...] 1.0-dirty $ hg commit -m 'commit message' -u toto $ hg describe [...] 1.0-1-<commit-id> $ echo "-" > d $ hg add d $ hg describe [...] 1.0-1-<commit-id>-dirty $ hg commit -m 'commit message' -u toto $ hg describe [...] 1.0-2-<commit-id> |}]
09f7b6b6626cb9ccdba82f7252788a9f1d90d4e86488f81bfa2ea5b29df5d7ac
Phaetec/pogo-cruncher
views.cljs
(ns cruncher.utils.views "Reusable components, which use twitter bootstrap to reduce redundancy." (:require [om.next :as om :refer-macros [defui]] [om.dom :as dom :include-macros true] [goog.dom :as gdom] [cruncher.utils.lib :as lib])) (defn commit-component-state "Set local state of view, parse the value of the target of val." [this key val] (cond (= (type val) js/Event) (om/update-state! this assoc key (.. val -target -value)) (= (type val) js/String) (om/update-state! this assoc key val) :else (om/update-state! this assoc key (.. val -target -value)))) ;;;; Table stuff (defn sortable-table-header "Sort list of pokemon by given key." [key & str] (dom/th #js {:className "pointer" :onClick #(lib/sort-pokemon! key)} str)) (defn td-two-lines "Create a td element with a black heading and a lighter second element." [black grey] (dom/td nil black (dom/br nil) (dom/span #js {:className "text-muted"} grey))) (defn td-center "Create normal td element with centered content." [& content] (dom/td #js {:className "text-center"} content)) ;;;; Bootstrap (defn button "Create dom element of a bootstrap primary button." ([fn not-empty? str btn-class] (dom/button #js {:className (clojure.string/join " " ["btn" btn-class]) :onClick fn :disabled (or (lib/loading?) (lib/progress?) (not not-empty?)) :react-key (lib/get-unique-key)} str))) (defn button-primary "Create primary button in bootstrap style." ([fn not-empty? str] (button fn not-empty? str "btn-primary")) ([fn str] (button-primary fn true str))) (defn button-default "Create default button in bootstrap style." ([fn not-empty? str] (button fn not-empty? str "btn-default")) ([fn str] (button-default fn true str))) (defn fa-icon "Wrapper for font-awesome icons." ([class] (dom/i #js {:react-key (lib/get-unique-key) :className (str "fa " class)})) ([class f] (dom/i #js {:react-key (lib/get-unique-key) :className (str "pointer fa " class) :onClick f}))) (defn panel-wrapper "Wrap content into bootstrap's panel class." [content] (dom/div #js {:className "panel panel-default"} (dom/div #js {:className "panel-body"} content))) (defn safe-html "Creates DOM element with interpreted HTML." [string] (dom/span #js {:dangerouslySetInnerHTML #js {:__html string}})) ;;;; Selections (defn get-selected-pokemon "Returns all selected Pokemon." [] (vec (map #(.. % -value) (filter #(.. % -checked) (gdom/getElementsByClass "poketable-checkbox"))))) (defn selected-pokemon? "Returns true if some Pokemon were selected in the DOM." [] (pos? (count (get-selected-pokemon)))) ;;;; UIs (defui Loader ; "Spinning icon to indicate if there is data being transferred." Object (render [this] (when (or (lib/loading?) (lib/progress?)) (dom/div #js {:style #js {:paddingTop "2em"}} (fa-icon "fa-circle-o-notch fa-spin fa-fw") " Loading...")))) (def loader (om/factory Loader)) (defui LoggedIn Object (render [this] (if (lib/logged-in?) (let [{:keys [player]} (om/props this)] (dom/div nil (dom/div nil (:name player) " Level " (:level player)) (dom/div nil (:stardust player) (dom/img #js {:src "img/stardust_vector.png" :className "currency_image" :title "Dust"}) (:pokecoins player) (dom/img #js {:src "img/pokecoin.png" :className "currency_image" :title "Coins"})) (dom/a #js {:href "javascript:void(0)" :onClick #(lib/logged-in! false)} (fa-icon "fa-sign-out") " Logout"))) (dom/div nil (dom/a #js {:href "javascript:void(0)" :onClick #(lib/change-view! :login)} (fa-icon "fa-sign-in") " Login"))))) (def login-indicator (om/factory LoggedIn)) (defui BackToTop Object (render [this] (dom/div #js {:className (str "scrolltop") :onClick #(.scroll js/window 0 0)} (dom/div #js {:className "scroll icon"} (fa-icon "fa-angle-up"))))) (def back-to-top (om/factory BackToTop))
null
https://raw.githubusercontent.com/Phaetec/pogo-cruncher/a93bd16cc4d118d2ec57c2a641bd1b11be0d133d/frontend/src/cruncher/utils/views.cljs
clojure
Table stuff Bootstrap Selections UIs "Spinning icon to indicate if there is data being transferred."
(ns cruncher.utils.views "Reusable components, which use twitter bootstrap to reduce redundancy." (:require [om.next :as om :refer-macros [defui]] [om.dom :as dom :include-macros true] [goog.dom :as gdom] [cruncher.utils.lib :as lib])) (defn commit-component-state "Set local state of view, parse the value of the target of val." [this key val] (cond (= (type val) js/Event) (om/update-state! this assoc key (.. val -target -value)) (= (type val) js/String) (om/update-state! this assoc key val) :else (om/update-state! this assoc key (.. val -target -value)))) (defn sortable-table-header "Sort list of pokemon by given key." [key & str] (dom/th #js {:className "pointer" :onClick #(lib/sort-pokemon! key)} str)) (defn td-two-lines "Create a td element with a black heading and a lighter second element." [black grey] (dom/td nil black (dom/br nil) (dom/span #js {:className "text-muted"} grey))) (defn td-center "Create normal td element with centered content." [& content] (dom/td #js {:className "text-center"} content)) (defn button "Create dom element of a bootstrap primary button." ([fn not-empty? str btn-class] (dom/button #js {:className (clojure.string/join " " ["btn" btn-class]) :onClick fn :disabled (or (lib/loading?) (lib/progress?) (not not-empty?)) :react-key (lib/get-unique-key)} str))) (defn button-primary "Create primary button in bootstrap style." ([fn not-empty? str] (button fn not-empty? str "btn-primary")) ([fn str] (button-primary fn true str))) (defn button-default "Create default button in bootstrap style." ([fn not-empty? str] (button fn not-empty? str "btn-default")) ([fn str] (button-default fn true str))) (defn fa-icon "Wrapper for font-awesome icons." ([class] (dom/i #js {:react-key (lib/get-unique-key) :className (str "fa " class)})) ([class f] (dom/i #js {:react-key (lib/get-unique-key) :className (str "pointer fa " class) :onClick f}))) (defn panel-wrapper "Wrap content into bootstrap's panel class." [content] (dom/div #js {:className "panel panel-default"} (dom/div #js {:className "panel-body"} content))) (defn safe-html "Creates DOM element with interpreted HTML." [string] (dom/span #js {:dangerouslySetInnerHTML #js {:__html string}})) (defn get-selected-pokemon "Returns all selected Pokemon." [] (vec (map #(.. % -value) (filter #(.. % -checked) (gdom/getElementsByClass "poketable-checkbox"))))) (defn selected-pokemon? "Returns true if some Pokemon were selected in the DOM." [] (pos? (count (get-selected-pokemon)))) (defui Loader Object (render [this] (when (or (lib/loading?) (lib/progress?)) (dom/div #js {:style #js {:paddingTop "2em"}} (fa-icon "fa-circle-o-notch fa-spin fa-fw") " Loading...")))) (def loader (om/factory Loader)) (defui LoggedIn Object (render [this] (if (lib/logged-in?) (let [{:keys [player]} (om/props this)] (dom/div nil (dom/div nil (:name player) " Level " (:level player)) (dom/div nil (:stardust player) (dom/img #js {:src "img/stardust_vector.png" :className "currency_image" :title "Dust"}) (:pokecoins player) (dom/img #js {:src "img/pokecoin.png" :className "currency_image" :title "Coins"})) (dom/a #js {:href "javascript:void(0)" :onClick #(lib/logged-in! false)} (fa-icon "fa-sign-out") " Logout"))) (dom/div nil (dom/a #js {:href "javascript:void(0)" :onClick #(lib/change-view! :login)} (fa-icon "fa-sign-in") " Login"))))) (def login-indicator (om/factory LoggedIn)) (defui BackToTop Object (render [this] (dom/div #js {:className (str "scrolltop") :onClick #(.scroll js/window 0 0)} (dom/div #js {:className "scroll icon"} (fa-icon "fa-angle-up"))))) (def back-to-top (om/factory BackToTop))
1053afb70f5dcb7c19dc4d3fbcc475807d9001b9f60bf5269630198394997540
jeffa5/mirage-xmpp
performance.ml
open Cmdliner let run_python_stats file = let%lwt () = Lwt_io.printl @@ "PYTHON: Running stats on file: " ^ file in let%lwt _ = Lwt_unix.system @@ "python test/performance/stats.py --save " ^ file in Lwt_io.printl "PYTHON: Finished stats" ;; let run_command_with_output command = let command = Lwt_process.shell command in let process = Lwt_process.open_process_in command in let rec get_lines () = match%lwt Lwt_io.read_line_opt process#stdout with | Some l -> let%lwt lines_after = get_lines () in Lwt.return ((string_of_float (Unix.gettimeofday ()) ^ " " ^ l) :: lines_after) | None -> Lwt.return_nil in get_lines () ;; let get_cpu_mem_docker container_name = let command = "docker stats --no-stream " ^ container_name ^ " | sed -n '2p' | awk '{gsub(/%/, \"\", $3); gsub(/%/, \"\", $7); printf \"%s \ %s\", $3, $7}'" in run_command_with_output command ;; let tsung file server_name = let tsung_command = Lwt_process.shell "tsung -f test/performance/tsung.xml start" in let tsung_process = Lwt_process.open_process_in tsung_command in let rec tsung_get_lines () = match%lwt Lwt_io.read_line_opt tsung_process#stdout with | Some l -> let%lwt () = Lwt_io.printl @@ "TSUNG: " ^ l in let%lwt lines_after = tsung_get_lines () in Lwt.return (l :: lines_after) | None -> Lwt.return_nil in let tsung_lines = ref [] in Lwt.async (fun () -> let%lwt tsung_output = tsung_get_lines () in tsung_lines := tsung_output; Lwt.return_unit ); let cpumem_lines = ref [] in let rec main_loop () = match tsung_process#state with | Running -> let%lwt logged_lines = get_cpu_mem_docker server_name in cpumem_lines := !cpumem_lines @ logged_lines; let%lwt () = Lwt_unix.sleep 1. in main_loop () | Exited _ -> Lwt.return_unit in let%lwt () = main_loop () in match%lwt tsung_process#status with | Unix.WEXITED 0 -> (* get the log file location *) let dump_time, dump_file = match List.filter (fun line -> Astring.String.is_prefix ~affix:"Log directory is:" line) !tsung_lines with | [line] -> (match Astring.String.cut ~sep:"/" line with | Some (_, path) -> ( (match Astring.String.cut ~rev:true ~sep:"/" path with | Some (_, datetime) -> datetime | None -> "") , "/" ^ path ^ "/tsung.dump" ) | None -> "", "") | _ -> "", "" in (* separate the input file to the name of the xml file *) let config_name = match Astring.String.cut ~rev:true ~sep:"/" file with | Some (_, filename) -> (* remove the file extension *) (match Astring.String.cut ~rev:true ~sep:"." filename with | Some (fname, _) -> fname | None -> filename) | None -> file in (* copy the dump file to a new location with servername, xml file and time to identify it: servername-xmlfile-time.dump *) let results_dir = "test/performance/results/" ^ String.concat "-" [server_name; config_name; dump_time] in let%lwt () = try%lwt Lwt_unix.mkdir "test/performance/results" 0o755 with Unix.Unix_error _ -> Lwt.return_unit in let%lwt () = try%lwt Lwt_unix.mkdir results_dir 0o755 with Unix.Unix_error _ -> Lwt.return_unit in let%lwt cpumem_file = Lwt_io.open_file ~mode:Output (results_dir ^ "/cpumem") in let%lwt () = Lwt_list.iter_s (fun line -> Lwt_io.write_line cpumem_file line) !cpumem_lines in let%lwt () = Lwt_io.close cpumem_file in let copied_dump = results_dir ^ "/dump" in let%lwt () = Lwt_unix.rename dump_file copied_dump in let%lwt () = Lwt_io.printl "TSUNG: Finished Tsung" in Lwt.return results_dir | _ -> Lwt.return "" ;; let test_docker image volume server_name file = let command = Lwt_process.shell @@ "docker run --rm --name " ^ server_name ^ " " ^ (if volume <> "" then "-v " ^ volume else "") ^ " -p 5222:5222 " ^ image in let%lwt () = Lwt_io.printl "DOCKER: Starting container" in let process = Lwt_process.open_process_in command in let rec get_lines () = match%lwt Lwt_io.read_line_opt process#stdout with | Some l -> let%lwt () = Lwt_io.printl @@ "DOCKER: " ^ l in get_lines () | None -> Lwt.return_unit in Lwt.async get_lines; let%lwt () = Lwt_unix.sleep 20. in let%lwt results_dir = tsung file server_name in let%lwt () = Lwt_io.printl "DOCKER: Stopping container" in let%lwt _ = Lwt_unix.system @@ "docker stop " ^ server_name in Lwt.return results_dir ;; let test_none server_name file = tsung file server_name type server = | Mirage | Ejabberd | Tigase | Prosody | None let server_to_string = function | Mirage -> "mirage" | Ejabberd -> "ejabberd" | Tigase -> "tigase" | Prosody -> "prosody" | None -> "none" ;; let mirage = "jeffas/mirage-xmpp" let ejabberd = "ejabberd/ecs" let tigase = "dictcp/tigase" let prosody = "prosody/prosody" let performance servers files load_duration load_duration_unit load_arrivalrate load_arrivalrate_unit = Lwt_main.run (let%lwt () = Lwt_io.printl @@ "Servers: " ^ String.concat ", " (List.map (fun server -> server_to_string server) servers) in let%lwt () = Lwt_io.printl @@ "Files: " ^ String.concat ", " files in let%lwt () = Lwt_io.printl @@ "Load duration: " ^ string_of_int load_duration ^ " " ^ load_duration_unit in let%lwt () = Lwt_io.printl @@ "Load arrivalrate: " ^ string_of_int load_arrivalrate ^ " per " ^ load_arrivalrate_unit in let files_length = List.length files in let run test_fn = Lwt_list.iteri_s (fun i file -> let%lwt () = Templates.make_template file load_duration load_duration_unit load_arrivalrate load_arrivalrate_unit in let%lwt results_dir = test_fn file in let%lwt () = run_python_stats results_dir in if i + 1 <> files_length then Lwt_unix.sleep 30. else Lwt.return_unit ) files in Lwt_list.iter_s (fun server -> match server with | Mirage -> run @@ test_docker mirage "" @@ server_to_string Mirage | Ejabberd -> run @@ test_docker ejabberd "$(pwd)/docker/ejabberd/ejabberd.yml:/home/ejabberd/conf/ejabberd.yml" @@ server_to_string Ejabberd | Tigase -> run @@ test_docker tigase "$(pwd)/docker/tigase/init.properties:/opt/tigase-server/etc/init.properties" @@ server_to_string Tigase | Prosody -> run @@ test_docker prosody "$(pwd)/docker/prosody/prosody.cfg.lua:/etc/prosody/prosody.cfg.lua" @@ server_to_string Prosody | None -> run @@ test_none @@ server_to_string None ) servers) ;; (* Command line parsing *) let servers = let doc = "Run performance tests against the MirageOS unikernel" in let mirage = Mirage, Arg.info ["m"; "mirage"] ~doc in let doc = "Run performance tests against the Ejabberd server" in let ejabberd = Ejabberd, Arg.info ["e"; "ejabberd"] ~doc in let doc = "Run performance tests against the Tigase server" in let tigase = Tigase, Arg.info ["t"; "tigase"] ~doc in let doc = "Run performance tests against the Prosody server" in let prosody = Prosody, Arg.info ["p"; "prosody"] ~doc in let doc = "No automated server creation, just run tsung" in let none = None, Arg.info ["n"; "none"] ~doc in Arg.(value & vflag_all [] [mirage; ejabberd; tigase; prosody; none]) ;; let files = let doc = "The xml files to run tsung with." in Arg.(value & pos_all file [] & info [] ~doc) ;; let load_duration = let doc = "The duration to run the tests for" in Arg.(value & opt int 1 & info ["ld"; "load-duration"] ~doc) ;; let load_duration_unit = let doc = "The unit (minute or second) for the load duration." in Arg.(value & opt string "minute" & info ["ldu"; "load-duration-unit"] ~doc) ;; let load_arrivalrate = let doc = "The arrivalrate of the users for the scenario." in Arg.(value & opt int 10 & info ["la"; "load-arrivalrate"] ~doc) ;; let load_arrivalrate_unit = let doc = "The unit (minute or second) for the arrivalrate of users." in Arg.(value & opt string "second" & info ["lau"; "load-arrivalrate-unit"] ~doc) ;; let cmd = let doc = "Run performance tests against a given target." in ( Term.( const performance $ servers $ files $ load_duration $ load_duration_unit $ load_arrivalrate $ load_arrivalrate_unit) , Term.info "performance" ~doc ~exits:Term.default_exits ) ;; let info = let doc = "Run the performance tests against a given target." in Term.info "performance" ~doc ~exits:Term.default_exits ;; let () = Term.exit @@ Term.eval cmd
null
https://raw.githubusercontent.com/jeffa5/mirage-xmpp/df3dafecba9081880809d8649ed0727b9f6a9dc7/test/performance/performance.ml
ocaml
get the log file location separate the input file to the name of the xml file remove the file extension copy the dump file to a new location with servername, xml file and time to identify it: servername-xmlfile-time.dump Command line parsing
open Cmdliner let run_python_stats file = let%lwt () = Lwt_io.printl @@ "PYTHON: Running stats on file: " ^ file in let%lwt _ = Lwt_unix.system @@ "python test/performance/stats.py --save " ^ file in Lwt_io.printl "PYTHON: Finished stats" ;; let run_command_with_output command = let command = Lwt_process.shell command in let process = Lwt_process.open_process_in command in let rec get_lines () = match%lwt Lwt_io.read_line_opt process#stdout with | Some l -> let%lwt lines_after = get_lines () in Lwt.return ((string_of_float (Unix.gettimeofday ()) ^ " " ^ l) :: lines_after) | None -> Lwt.return_nil in get_lines () ;; let get_cpu_mem_docker container_name = let command = "docker stats --no-stream " ^ container_name ^ " | sed -n '2p' | awk '{gsub(/%/, \"\", $3); gsub(/%/, \"\", $7); printf \"%s \ %s\", $3, $7}'" in run_command_with_output command ;; let tsung file server_name = let tsung_command = Lwt_process.shell "tsung -f test/performance/tsung.xml start" in let tsung_process = Lwt_process.open_process_in tsung_command in let rec tsung_get_lines () = match%lwt Lwt_io.read_line_opt tsung_process#stdout with | Some l -> let%lwt () = Lwt_io.printl @@ "TSUNG: " ^ l in let%lwt lines_after = tsung_get_lines () in Lwt.return (l :: lines_after) | None -> Lwt.return_nil in let tsung_lines = ref [] in Lwt.async (fun () -> let%lwt tsung_output = tsung_get_lines () in tsung_lines := tsung_output; Lwt.return_unit ); let cpumem_lines = ref [] in let rec main_loop () = match tsung_process#state with | Running -> let%lwt logged_lines = get_cpu_mem_docker server_name in cpumem_lines := !cpumem_lines @ logged_lines; let%lwt () = Lwt_unix.sleep 1. in main_loop () | Exited _ -> Lwt.return_unit in let%lwt () = main_loop () in match%lwt tsung_process#status with | Unix.WEXITED 0 -> let dump_time, dump_file = match List.filter (fun line -> Astring.String.is_prefix ~affix:"Log directory is:" line) !tsung_lines with | [line] -> (match Astring.String.cut ~sep:"/" line with | Some (_, path) -> ( (match Astring.String.cut ~rev:true ~sep:"/" path with | Some (_, datetime) -> datetime | None -> "") , "/" ^ path ^ "/tsung.dump" ) | None -> "", "") | _ -> "", "" in let config_name = match Astring.String.cut ~rev:true ~sep:"/" file with | Some (_, filename) -> (match Astring.String.cut ~rev:true ~sep:"." filename with | Some (fname, _) -> fname | None -> filename) | None -> file in let results_dir = "test/performance/results/" ^ String.concat "-" [server_name; config_name; dump_time] in let%lwt () = try%lwt Lwt_unix.mkdir "test/performance/results" 0o755 with Unix.Unix_error _ -> Lwt.return_unit in let%lwt () = try%lwt Lwt_unix.mkdir results_dir 0o755 with Unix.Unix_error _ -> Lwt.return_unit in let%lwt cpumem_file = Lwt_io.open_file ~mode:Output (results_dir ^ "/cpumem") in let%lwt () = Lwt_list.iter_s (fun line -> Lwt_io.write_line cpumem_file line) !cpumem_lines in let%lwt () = Lwt_io.close cpumem_file in let copied_dump = results_dir ^ "/dump" in let%lwt () = Lwt_unix.rename dump_file copied_dump in let%lwt () = Lwt_io.printl "TSUNG: Finished Tsung" in Lwt.return results_dir | _ -> Lwt.return "" ;; let test_docker image volume server_name file = let command = Lwt_process.shell @@ "docker run --rm --name " ^ server_name ^ " " ^ (if volume <> "" then "-v " ^ volume else "") ^ " -p 5222:5222 " ^ image in let%lwt () = Lwt_io.printl "DOCKER: Starting container" in let process = Lwt_process.open_process_in command in let rec get_lines () = match%lwt Lwt_io.read_line_opt process#stdout with | Some l -> let%lwt () = Lwt_io.printl @@ "DOCKER: " ^ l in get_lines () | None -> Lwt.return_unit in Lwt.async get_lines; let%lwt () = Lwt_unix.sleep 20. in let%lwt results_dir = tsung file server_name in let%lwt () = Lwt_io.printl "DOCKER: Stopping container" in let%lwt _ = Lwt_unix.system @@ "docker stop " ^ server_name in Lwt.return results_dir ;; let test_none server_name file = tsung file server_name type server = | Mirage | Ejabberd | Tigase | Prosody | None let server_to_string = function | Mirage -> "mirage" | Ejabberd -> "ejabberd" | Tigase -> "tigase" | Prosody -> "prosody" | None -> "none" ;; let mirage = "jeffas/mirage-xmpp" let ejabberd = "ejabberd/ecs" let tigase = "dictcp/tigase" let prosody = "prosody/prosody" let performance servers files load_duration load_duration_unit load_arrivalrate load_arrivalrate_unit = Lwt_main.run (let%lwt () = Lwt_io.printl @@ "Servers: " ^ String.concat ", " (List.map (fun server -> server_to_string server) servers) in let%lwt () = Lwt_io.printl @@ "Files: " ^ String.concat ", " files in let%lwt () = Lwt_io.printl @@ "Load duration: " ^ string_of_int load_duration ^ " " ^ load_duration_unit in let%lwt () = Lwt_io.printl @@ "Load arrivalrate: " ^ string_of_int load_arrivalrate ^ " per " ^ load_arrivalrate_unit in let files_length = List.length files in let run test_fn = Lwt_list.iteri_s (fun i file -> let%lwt () = Templates.make_template file load_duration load_duration_unit load_arrivalrate load_arrivalrate_unit in let%lwt results_dir = test_fn file in let%lwt () = run_python_stats results_dir in if i + 1 <> files_length then Lwt_unix.sleep 30. else Lwt.return_unit ) files in Lwt_list.iter_s (fun server -> match server with | Mirage -> run @@ test_docker mirage "" @@ server_to_string Mirage | Ejabberd -> run @@ test_docker ejabberd "$(pwd)/docker/ejabberd/ejabberd.yml:/home/ejabberd/conf/ejabberd.yml" @@ server_to_string Ejabberd | Tigase -> run @@ test_docker tigase "$(pwd)/docker/tigase/init.properties:/opt/tigase-server/etc/init.properties" @@ server_to_string Tigase | Prosody -> run @@ test_docker prosody "$(pwd)/docker/prosody/prosody.cfg.lua:/etc/prosody/prosody.cfg.lua" @@ server_to_string Prosody | None -> run @@ test_none @@ server_to_string None ) servers) ;; let servers = let doc = "Run performance tests against the MirageOS unikernel" in let mirage = Mirage, Arg.info ["m"; "mirage"] ~doc in let doc = "Run performance tests against the Ejabberd server" in let ejabberd = Ejabberd, Arg.info ["e"; "ejabberd"] ~doc in let doc = "Run performance tests against the Tigase server" in let tigase = Tigase, Arg.info ["t"; "tigase"] ~doc in let doc = "Run performance tests against the Prosody server" in let prosody = Prosody, Arg.info ["p"; "prosody"] ~doc in let doc = "No automated server creation, just run tsung" in let none = None, Arg.info ["n"; "none"] ~doc in Arg.(value & vflag_all [] [mirage; ejabberd; tigase; prosody; none]) ;; let files = let doc = "The xml files to run tsung with." in Arg.(value & pos_all file [] & info [] ~doc) ;; let load_duration = let doc = "The duration to run the tests for" in Arg.(value & opt int 1 & info ["ld"; "load-duration"] ~doc) ;; let load_duration_unit = let doc = "The unit (minute or second) for the load duration." in Arg.(value & opt string "minute" & info ["ldu"; "load-duration-unit"] ~doc) ;; let load_arrivalrate = let doc = "The arrivalrate of the users for the scenario." in Arg.(value & opt int 10 & info ["la"; "load-arrivalrate"] ~doc) ;; let load_arrivalrate_unit = let doc = "The unit (minute or second) for the arrivalrate of users." in Arg.(value & opt string "second" & info ["lau"; "load-arrivalrate-unit"] ~doc) ;; let cmd = let doc = "Run performance tests against a given target." in ( Term.( const performance $ servers $ files $ load_duration $ load_duration_unit $ load_arrivalrate $ load_arrivalrate_unit) , Term.info "performance" ~doc ~exits:Term.default_exits ) ;; let info = let doc = "Run the performance tests against a given target." in Term.info "performance" ~doc ~exits:Term.default_exits ;; let () = Term.exit @@ Term.eval cmd
2efcbe664a06e22c63892eca1b228d9ea4fb207aa11cc953ca809818ceb81461
jeffshrager/biobike
process-interface.lisp
;;; -*- mode: Lisp; Syntax: Common-Lisp; Package: wb; -*- (in-package :wb) ;;; +=========================================================================+ | Copyright ( c ) 2002 , 2003 , 2004 JP , , | ;;; | | ;;; | 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. | ;;; +=========================================================================+ Nonportable stuff . Only does something useful in Allegro currently , but should ' work ' by being a noop in Lispworks . XXX could the SBCL mp be used here ? -mas 9/22/04 (defmacro with-timeout-limit ((limit &rest timeout-forms) &body body) (declare (ignorable limit timeout-forms)) #+:allegro `(mp:with-timeout (,limit ,@timeout-forms) ,@body) #-:allegro `(progn ,@body) ) (defmacro run-function-as-process (name-or-options function &rest function-args) (declare (ignorable name-or-options function function-args)) #+:allegro `(mp:process-run-function ,name-or-options ,function ,@function-args) #-:allegro `(error "RUN-FUNCTION-AS-PROCESS needs to be implemented") ) (defun my-current-process () #+:allegro mp:*current-process* #-:allegro nil ) (defun all-the-processes () #+:allegro (copy-list mp:*all-processes*) #-:allegro nil ) (defvar *spp* 0) (defun set-process-priority (value &optional (p (my-current-process))) (declare (ignorable value p)) #+:allegro (progn (incf *spp*) (setf (mp:process-priority p) value)) #-:allegro nil ) (defun get-process-priority (&optional (p (my-current-process))) (declare (ignorable p)) #+:allegro (mp:process-priority p) #-:allegro 0 ) (defun set-process-quantum (value &optional (p (my-current-process))) (declare (ignorable value p)) #+:allegro (setf (mp:process-quantum p) value) #-:allegro nil ) (defun get-process-quantum (&optional (p (my-current-process))) (declare (ignorable p)) #+:allegro (mp:process-quantum p) #-:allegro 1.0 ) (defun get-process-name (&optional (p (my-current-process))) (declare (ignorable p)) #+:allegro (mp:process-name p) #-:allegro "" ) (defun get-process-cpu (&optional (p (my-current-process))) (declare (ignorable p)) #+:allegro (mp:process-cpu-msec-used p) #-:allegro 0 ) (defun kill-process (&optional (p (my-current-process))) (declare (ignorable p)) #+:allegro (mp:process-kill p) #-:allegro nil) An Allegro process has a property list . Use that to mark a process ;; with a PDL structure. (defun my-process-property-list (&optional (p (my-current-process))) (declare (ignorable p)) #+:allegro (let ((plist (mp:process-property-list p))) (when (null plist) (setf (mp:process-property-list p) (list :nil nil))) (mp:process-property-list p)) #-:allegro nil ) (defun add-process-property (property value &optional (p (my-current-process))) (declare (ignorable property value p)) #+:allegro (setf (getf (mp:process-property-list p) property) value) #-:allegro nil ) (defun clear-process-property (property &optional (p (my-current-process))) (declare (ignorable property p)) #+:allegro (setf (getf (mp:process-property-list p) property) nil) #-:allegro nil )
null
https://raw.githubusercontent.com/jeffshrager/biobike/5313ec1fe8e82c21430d645e848ecc0386436f57/BioLisp/Portability/process-interface.lisp
lisp
-*- mode: Lisp; Syntax: Common-Lisp; Package: wb; -*- +=========================================================================+ | | | Permission is hereby granted, free of charge, to any person obtaining | | a copy of this software and associated documentation files (the | | without limitation the rights to use, copy, modify, merge, publish, | | the following conditions: | | | | The above copyright notice and this permission notice shall be included | | | | 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 | | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE | | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | +=========================================================================+ with a PDL structure.
(in-package :wb) | Copyright ( c ) 2002 , 2003 , 2004 JP , , | | " Software " ) , to deal in the Software without restriction , including | | distribute , sublicense , and/or sell copies of the Software , and to | | permit persons to whom the Software is furnished to do so , subject to | | in all copies or substantial portions of the Software . | | THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , | | CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , | Nonportable stuff . Only does something useful in Allegro currently , but should ' work ' by being a noop in Lispworks . XXX could the SBCL mp be used here ? -mas 9/22/04 (defmacro with-timeout-limit ((limit &rest timeout-forms) &body body) (declare (ignorable limit timeout-forms)) #+:allegro `(mp:with-timeout (,limit ,@timeout-forms) ,@body) #-:allegro `(progn ,@body) ) (defmacro run-function-as-process (name-or-options function &rest function-args) (declare (ignorable name-or-options function function-args)) #+:allegro `(mp:process-run-function ,name-or-options ,function ,@function-args) #-:allegro `(error "RUN-FUNCTION-AS-PROCESS needs to be implemented") ) (defun my-current-process () #+:allegro mp:*current-process* #-:allegro nil ) (defun all-the-processes () #+:allegro (copy-list mp:*all-processes*) #-:allegro nil ) (defvar *spp* 0) (defun set-process-priority (value &optional (p (my-current-process))) (declare (ignorable value p)) #+:allegro (progn (incf *spp*) (setf (mp:process-priority p) value)) #-:allegro nil ) (defun get-process-priority (&optional (p (my-current-process))) (declare (ignorable p)) #+:allegro (mp:process-priority p) #-:allegro 0 ) (defun set-process-quantum (value &optional (p (my-current-process))) (declare (ignorable value p)) #+:allegro (setf (mp:process-quantum p) value) #-:allegro nil ) (defun get-process-quantum (&optional (p (my-current-process))) (declare (ignorable p)) #+:allegro (mp:process-quantum p) #-:allegro 1.0 ) (defun get-process-name (&optional (p (my-current-process))) (declare (ignorable p)) #+:allegro (mp:process-name p) #-:allegro "" ) (defun get-process-cpu (&optional (p (my-current-process))) (declare (ignorable p)) #+:allegro (mp:process-cpu-msec-used p) #-:allegro 0 ) (defun kill-process (&optional (p (my-current-process))) (declare (ignorable p)) #+:allegro (mp:process-kill p) #-:allegro nil) An Allegro process has a property list . Use that to mark a process (defun my-process-property-list (&optional (p (my-current-process))) (declare (ignorable p)) #+:allegro (let ((plist (mp:process-property-list p))) (when (null plist) (setf (mp:process-property-list p) (list :nil nil))) (mp:process-property-list p)) #-:allegro nil ) (defun add-process-property (property value &optional (p (my-current-process))) (declare (ignorable property value p)) #+:allegro (setf (getf (mp:process-property-list p) property) value) #-:allegro nil ) (defun clear-process-property (property &optional (p (my-current-process))) (declare (ignorable property p)) #+:allegro (setf (getf (mp:process-property-list p) property) nil) #-:allegro nil )
7e2f0e786dc97f3c4103211ca1e9b1122c3d370d7b7a2534d1f4908bc90566f9
bgusach/exercises-htdp2e
ex-183.rkt
#lang htdp/bsl+ (require test-engine/racket-tests) (check-expect (cons "a" (list 0 #false)) (list "a" 0 #false) ) (check-expect (cons "a" (list 0 #false)) (cons "a" (cons 0 (cons #false '()))) ) (check-expect (list (cons 1 (cons 13 '()))) (list (list 1 13)) ) (check-expect (list (cons 1 (cons 13 '()))) (cons (cons 1 (cons 13 '())) '()) ) (check-expect (cons (list 1 (list 13 '())) '()) (list (list 1 (list 13 '()))) ) (check-expect (cons (list 1 (list 13 '())) '()) (cons (cons 1 (cons (cons 13 (cons '() '() )) '() )) '() )) (test)
null
https://raw.githubusercontent.com/bgusach/exercises-htdp2e/c4fd33f28fb0427862a2777a1fde8bf6432a7690/2-arbitrarily-large-data/ex-183.rkt
racket
#lang htdp/bsl+ (require test-engine/racket-tests) (check-expect (cons "a" (list 0 #false)) (list "a" 0 #false) ) (check-expect (cons "a" (list 0 #false)) (cons "a" (cons 0 (cons #false '()))) ) (check-expect (list (cons 1 (cons 13 '()))) (list (list 1 13)) ) (check-expect (list (cons 1 (cons 13 '()))) (cons (cons 1 (cons 13 '())) '()) ) (check-expect (cons (list 1 (list 13 '())) '()) (list (list 1 (list 13 '()))) ) (check-expect (cons (list 1 (list 13 '())) '()) (cons (cons 1 (cons (cons 13 (cons '() '() )) '() )) '() )) (test)
4a40c957b406d7c249bfbef2149e9d8d822f424c2ca80c61a4db07e6e81dd8e3
astrolin/ephemeris-api
project.clj
(defproject ephemeris-api "0.0.1-SNAPSHOT" :description "Ephemeris HTTP API" due to lein - immutant :dependencies [[org.clojure/clojure "1.10.1"] [ephemeris "0.0.1"] [prismatic/schema "1.1.12"] [pedestal-api "0.3.4" :exclusions [prismatic/schema]] [io.pedestal/pedestal.service "0.5.7"] [io.pedestal/pedestal.jetty "0.5.7"] ;; for dev [io.pedestal/pedestal.immutant "0.5.7"] ;; for prod [ch.qos.logback/logback-classic "1.2.3" :exclusions [org.slf4j/slf4j-api]] [org.slf4j/jul-to-slf4j "1.7.30"] [org.slf4j/jcl-over-slf4j "1.7.30"] [org.slf4j/log4j-over-slf4j "1.7.30"] [org.clojure/tools.logging "1.0.0"] [jarohen/nomad "0.9.1"] [environ "1.1.0"] [stencil "0.5.0"]] :plugins [[lein-environ "1.1.0"]] :env {:ever :project/version ;; ephemeris-api v[ersion] :base "/api/"} ;; keep the trailing / :source-paths ["src"] :resource-paths ["resources"] :global-vars {*warn-on-reflection* false} :profiles {:dev {:source-paths ["dev" "src"] :jvm-opts ["-Dnomad.env=dev" "--illegal-access=debug"] :dependencies [[ns-tracker "0.4.0"] [proto-repl "0.3.1"] [martian-test "0.1.11"] [midje "1.9.9"] [midje-notifier "0.3.0"]] :plugins [[lein-midje "3.2.2"] [lein-ancient "0.6.15"] [lein-immutant "2.1.0"]] :sass {:source "resources/sass" :target "resources/public/css"} :immutant {:nrepl-port 0 :nrepl-interface :management} 5 minutes :init-ns dev}} :repl {:ultra {:repl {:sort-keys false :map-coll-separator :line}}} :uberjar {:main ephemeris-api.server :aot :all}} :immutant {:init pedestal-immutant.server/initialize :resolve-dependencies true :context-path "/" :war {:name "ephemeris-api"}} :aliases {"test" ["midje"] "autotest" ["midje" ":autotest"] "uberwar" ["immutant" "war"]} :main ^:skip-aot ephemeris-api.server :target-path "target/" :pom-location "target/" :uberjar-name "server.jar" :deploy-branches ["master"])
null
https://raw.githubusercontent.com/astrolin/ephemeris-api/f910c4e2e3dbfc62799fad4e3af5684eb3ba9016/project.clj
clojure
for dev for prod ephemeris-api v[ersion] keep the trailing /
(defproject ephemeris-api "0.0.1-SNAPSHOT" :description "Ephemeris HTTP API" due to lein - immutant :dependencies [[org.clojure/clojure "1.10.1"] [ephemeris "0.0.1"] [prismatic/schema "1.1.12"] [pedestal-api "0.3.4" :exclusions [prismatic/schema]] [io.pedestal/pedestal.service "0.5.7"] [ch.qos.logback/logback-classic "1.2.3" :exclusions [org.slf4j/slf4j-api]] [org.slf4j/jul-to-slf4j "1.7.30"] [org.slf4j/jcl-over-slf4j "1.7.30"] [org.slf4j/log4j-over-slf4j "1.7.30"] [org.clojure/tools.logging "1.0.0"] [jarohen/nomad "0.9.1"] [environ "1.1.0"] [stencil "0.5.0"]] :plugins [[lein-environ "1.1.0"]] :source-paths ["src"] :resource-paths ["resources"] :global-vars {*warn-on-reflection* false} :profiles {:dev {:source-paths ["dev" "src"] :jvm-opts ["-Dnomad.env=dev" "--illegal-access=debug"] :dependencies [[ns-tracker "0.4.0"] [proto-repl "0.3.1"] [martian-test "0.1.11"] [midje "1.9.9"] [midje-notifier "0.3.0"]] :plugins [[lein-midje "3.2.2"] [lein-ancient "0.6.15"] [lein-immutant "2.1.0"]] :sass {:source "resources/sass" :target "resources/public/css"} :immutant {:nrepl-port 0 :nrepl-interface :management} 5 minutes :init-ns dev}} :repl {:ultra {:repl {:sort-keys false :map-coll-separator :line}}} :uberjar {:main ephemeris-api.server :aot :all}} :immutant {:init pedestal-immutant.server/initialize :resolve-dependencies true :context-path "/" :war {:name "ephemeris-api"}} :aliases {"test" ["midje"] "autotest" ["midje" ":autotest"] "uberwar" ["immutant" "war"]} :main ^:skip-aot ephemeris-api.server :target-path "target/" :pom-location "target/" :uberjar-name "server.jar" :deploy-branches ["master"])
59d4b275ae59620d59ad6b2a02df2245e35fff09635849a45d1270ba54b38dd5
wireapp/wire-server
Roles.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 API.Roles where import API.Util import Bilge hiding (timeout) import Bilge.Assert import Control.Lens (view) import Data.Aeson hiding (json) import Data.ByteString.Conversion (toByteString') import Data.Domain import Data.Id import Data.List1 import qualified Data.List1 as List1 import Data.Qualified import qualified Data.Set as Set import Data.Singletons import Federator.MockServer import Imports import Network.Wai.Utilities.Error import Test.Tasty import Test.Tasty.Cannon (TimeoutUnit (..), (#)) import qualified Test.Tasty.Cannon as WS import Test.Tasty.HUnit import TestHelpers import TestSetup import Wire.API.Conversation import Wire.API.Conversation.Action import Wire.API.Conversation.Role import Wire.API.Event.Conversation import qualified Wire.API.Federation.API.Galley as F import Wire.API.Federation.Component import Wire.API.Internal.Notification (Notification (..)) tests :: IO TestSetup -> TestTree tests s = testGroup "Conversation roles" [ test s "conversation roles admin (and downgrade)" handleConversationRoleAdmin, test s "conversation roles member (and upgrade)" handleConversationRoleMember, test s "conversation role update with remote users present" roleUpdateWithRemotes, test s "conversation access update with remote users present" accessUpdateWithRemotes, test s "conversation role update of remote member" roleUpdateRemoteMember, test s "get all conversation roles" testAllConversationRoles, test s "access role update with v2" testAccessRoleUpdateV2, test s "test access roles of new conversations" testConversationAccessRole ] testAllConversationRoles :: TestM () testAllConversationRoles = do alice <- randomUser bob <- randomUser chuck <- randomUser connectUsers alice (list1 bob [chuck]) let role = roleNameWireAdmin c <- decodeConvId <$> postConvWithRole alice [bob] (Just "gossip") [] Nothing Nothing role g <- viewGalley get ( g . paths ["conversations", toByteString' c, "roles"] . zUser alice ) !!! do const 200 === statusCode const (Right (ConversationRolesList [convRoleWireAdmin, convRoleWireMember])) === responseJsonEither handleConversationRoleAdmin :: TestM () handleConversationRoleAdmin = do localDomain <- viewFederationDomain c <- view tsCannon (alice, qalice) <- randomUserTuple (bob, qbob) <- randomUserTuple (chuck, qchuck) <- randomUserTuple (eve, qeve) <- randomUserTuple (jack, qjack) <- randomUserTuple connectUsers alice (list1 bob [chuck, eve, jack]) connectUsers eve (singleton bob) connectUsers bob (singleton jack) let role = roleNameWireAdmin cid <- WS.bracketR3 c alice bob chuck $ \(wsA, wsB, wsC) -> do rsp <- postConvWithRole alice [bob, chuck] (Just "gossip") [] Nothing Nothing role void $ assertConvWithRole rsp RegularConv alice qalice [qbob, qchuck] (Just "gossip") Nothing role let cid = decodeConvId rsp qcid = Qualified cid localDomain -- Make sure everyone gets the correct event postMembersWithRole alice (pure qeve) qcid role !!! const 200 === statusCode void . liftIO $ WS.assertMatchN (5 # Second) [wsA, wsB, wsC] $ wsAssertMemberJoinWithRole qcid qalice [qeve] role -- Add a member to help out with testing postMembersWithRole alice (pure qjack) qcid roleNameWireMember !!! const 200 === statusCode void . liftIO $ WS.assertMatchN (5 # Second) [wsA, wsB, wsC] $ wsAssertMemberJoinWithRole qcid qalice [qjack] roleNameWireMember pure cid Added as a wire_admin and do the checks wireAdminChecks cid alice bob jack -- Demote bob and run the member checks WS.bracketR3 c alice bob chuck $ \(wsA, wsB, wsC) -> do let updateDown = OtherMemberUpdate (Just roleNameWireMember) qcid = Qualified cid localDomain putOtherMember alice bob updateDown cid !!! assertActionSucceeded void . liftIO . WS.assertMatchN (5 # Second) [wsA, wsB, wsC] $ do wsAssertMemberUpdateWithRole qcid qalice bob roleNameWireMember wireMemberChecks cid bob alice jack handleConversationRoleMember :: TestM () handleConversationRoleMember = do localDomain <- viewFederationDomain c <- view tsCannon (alice, qalice) <- randomUserTuple (bob, qbob) <- randomUserTuple (chuck, qchuck) <- randomUserTuple eve <- randomUser let qeve = Qualified eve localDomain jack <- randomUser connectUsers alice (list1 bob [chuck, eve]) connectUsers bob (singleton chuck) connectUsers eve (list1 bob [jack]) let role = roleNameWireMember cid <- WS.bracketR3 c alice bob chuck $ \(wsA, wsB, wsC) -> do rsp <- postConvWithRole alice [bob, chuck] (Just "gossip") [] Nothing Nothing role void $ assertConvWithRole rsp RegularConv alice qalice [qbob, qchuck] (Just "gossip") Nothing role let cid = decodeConvId rsp qcid = Qualified cid localDomain -- Make sure everyone gets the correct event postMembersWithRole alice (pure qeve) qcid role !!! const 200 === statusCode void . liftIO $ WS.assertMatchN (5 # Second) [wsA, wsB, wsC] $ wsAssertMemberJoinWithRole qcid qalice [qeve] role pure cid Added as a wire_member and do the checks wireMemberChecks cid bob alice chuck -- Let's promote bob WS.bracketR3 c alice bob chuck $ \(wsA, wsB, wsC) -> do let qcid = Qualified cid localDomain let updateUp = OtherMemberUpdate (Just roleNameWireAdmin) can not update , member only putOtherMember chuck bob updateUp cid !!! assertActionDenied putOtherMember alice bob updateUp cid !!! assertActionSucceeded void . liftIO . WS.assertMatchN (5 # Second) [wsA, wsB, wsC] $ do wsAssertMemberUpdateWithRole qcid qalice bob roleNameWireAdmin wireAdminChecks cid bob alice chuck roleUpdateRemoteMember :: TestM () roleUpdateRemoteMember = do c <- view tsCannon let remoteDomain = Domain "alice.example.com" qalice <- Qualified <$> randomId <*> pure remoteDomain qbob <- randomQualifiedUser qcharlie <- Qualified <$> randomId <*> pure remoteDomain let bob = qUnqualified qbob traverse_ (connectWithRemoteUser bob) [qalice, qcharlie] resp <- postConvWithRemoteUsers bob Nothing defNewProteusConv {newConvQualifiedUsers = [qalice, qcharlie]} let qconv = decodeQualifiedConvId resp WS.bracketR c bob $ \wsB -> do (_, requests) <- withTempMockFederator' (mockReply ()) $ putOtherMemberQualified bob qcharlie (OtherMemberUpdate (Just roleNameWireMember)) qconv !!! const 200 === statusCode req <- assertOne requests let mu = MemberUpdateData { misTarget = qcharlie, misOtrMutedStatus = Nothing, misOtrMutedRef = Nothing, misOtrArchived = Nothing, misOtrArchivedRef = Nothing, misHidden = Nothing, misHiddenRef = Nothing, misConvRoleName = Just roleNameWireMember } liftIO $ do frTargetDomain req @?= remoteDomain frComponent req @?= Galley frRPC req @?= "on-conversation-updated" Right cu <- pure . eitherDecode . frBody $ req F.cuConvId cu @?= qUnqualified qconv F.cuAction cu @?= SomeConversationAction (sing @'ConversationMemberUpdateTag) (ConversationMemberUpdate qcharlie (OtherMemberUpdate (Just roleNameWireMember))) sort (F.cuAlreadyPresentUsers cu) @?= sort [qUnqualified qalice, qUnqualified qcharlie] liftIO . WS.assertMatch_ (5 # Second) wsB $ \n -> do let e = List1.head (WS.unpackPayload n) ntfTransient n @?= False evtConv e @?= qconv evtType e @?= MemberStateUpdate evtFrom e @?= qbob evtData e @?= EdMemberUpdate mu conv <- responseJsonError =<< getConvQualified bob qconv <!! const 200 === statusCode let charlieAsMember = find (\m -> omQualifiedId m == qcharlie) (cmOthers (cnvMembers conv)) liftIO $ charlieAsMember @=? Just OtherMember { omQualifiedId = qcharlie, omService = Nothing, omConvRoleName = roleNameWireMember } roleUpdateWithRemotes :: TestM () roleUpdateWithRemotes = do c <- view tsCannon let remoteDomain = Domain "alice.example.com" qalice <- Qualified <$> randomId <*> pure remoteDomain qbob <- randomQualifiedUser qcharlie <- randomQualifiedUser let bob = qUnqualified qbob charlie = qUnqualified qcharlie connectUsers bob (singleton charlie) connectWithRemoteUser bob qalice resp <- postConvWithRemoteUsers bob Nothing defNewProteusConv {newConvQualifiedUsers = [qalice, qcharlie]} let qconv = decodeQualifiedConvId resp WS.bracketR2 c bob charlie $ \(wsB, wsC) -> do (_, requests) <- withTempMockFederator' (mockReply ()) $ putOtherMemberQualified bob qcharlie (OtherMemberUpdate (Just roleNameWireAdmin)) qconv !!! const 200 === statusCode req <- assertOne requests let mu = MemberUpdateData { misTarget = qcharlie, misOtrMutedStatus = Nothing, misOtrMutedRef = Nothing, misOtrArchived = Nothing, misOtrArchivedRef = Nothing, misHidden = Nothing, misHiddenRef = Nothing, misConvRoleName = Just roleNameWireAdmin } liftIO $ do frTargetDomain req @?= remoteDomain frComponent req @?= Galley frRPC req @?= "on-conversation-updated" Right cu <- pure . eitherDecode . frBody $ req F.cuConvId cu @?= qUnqualified qconv F.cuAction cu @?= SomeConversationAction (sing @'ConversationMemberUpdateTag) (ConversationMemberUpdate qcharlie (OtherMemberUpdate (Just roleNameWireAdmin))) F.cuAlreadyPresentUsers cu @?= [qUnqualified qalice] liftIO . WS.assertMatchN_ (5 # Second) [wsB, wsC] $ \n -> do let e = List1.head (WS.unpackPayload n) ntfTransient n @?= False evtConv e @?= qconv evtType e @?= MemberStateUpdate evtFrom e @?= qbob evtData e @?= EdMemberUpdate mu accessUpdateWithRemotes :: TestM () accessUpdateWithRemotes = do c <- view tsCannon let remoteDomain = Domain "alice.example.com" qalice <- Qualified <$> randomId <*> pure remoteDomain qbob <- randomQualifiedUser qcharlie <- randomQualifiedUser let bob = qUnqualified qbob charlie = qUnqualified qcharlie connectUsers bob (singleton charlie) connectWithRemoteUser bob qalice resp <- postConvWithRemoteUsers bob Nothing defNewProteusConv {newConvQualifiedUsers = [qalice, qcharlie]} let qconv = decodeQualifiedConvId resp let access = ConversationAccessData (Set.singleton CodeAccess) (Set.fromList [TeamMemberAccessRole, NonTeamMemberAccessRole, GuestAccessRole, ServiceAccessRole]) WS.bracketR2 c bob charlie $ \(wsB, wsC) -> do (_, requests) <- withTempMockFederator' (mockReply ()) $ putQualifiedAccessUpdate bob qconv access !!! const 200 === statusCode req <- assertOne requests liftIO $ do frTargetDomain req @?= remoteDomain frComponent req @?= Galley frRPC req @?= "on-conversation-updated" Right cu <- pure . eitherDecode . frBody $ req F.cuConvId cu @?= qUnqualified qconv F.cuAction cu @?= SomeConversationAction (sing @'ConversationAccessDataTag) access F.cuAlreadyPresentUsers cu @?= [qUnqualified qalice] liftIO . WS.assertMatchN_ (5 # Second) [wsB, wsC] $ \n -> do let e = List1.head (WS.unpackPayload n) ntfTransient n @?= False evtConv e @?= qconv evtType e @?= ConvAccessUpdate evtFrom e @?= qbob evtData e @?= EdConvAccessUpdate access -- | Given an admin, another admin and a member run all -- the necessary checks targeting the admin wireAdminChecks :: ConvId -> UserId -> UserId -> UserId -> TestM () wireAdminChecks cid admin otherAdmin mem = do localDomain <- viewFederationDomain let role = roleNameWireAdmin let qcid = Qualified cid localDomain qadmin = Qualified admin localDomain qotherAdmin = Qualified otherAdmin localDomain qmem = Qualified mem localDomain (other, qother) <- randomUserTuple connectUsers admin (singleton other) -- Admins can perform all operations on the conversation; creator is not relevant -- Add members postMembers admin (pure qother) qcid !!! assertActionSucceeded -- Remove members, regardless of who they are forM_ [qotherAdmin, qmem] $ \victim -> do deleteMemberQualified admin victim qcid !!! assertActionSucceeded postMembersWithRole admin (pure victim) qcid role !!! assertActionSucceeded -- Modify the conversation name void $ putConversationName admin cid "gossip++" !!! assertActionSucceeded -- Modify other members roles forM_ [otherAdmin, mem] $ \victim -> do let updateDown = OtherMemberUpdate (Just roleNameWireMember) putOtherMember admin victim updateDown cid !!! assertActionSucceeded let updateUp = OtherMemberUpdate (Just roleNameWireAdmin) putOtherMember admin victim updateUp cid !!! assertActionSucceeded -- Updates for message timer, receipt mode or access putMessageTimerUpdate admin cid (ConversationMessageTimerUpdate $ Just 1000) !!! assertActionSucceeded putMessageTimerUpdate admin cid (ConversationMessageTimerUpdate $ Just 2000) !!! assertActionSucceeded putReceiptMode admin cid (ReceiptMode 0) !!! assertActionSucceeded putReceiptMode admin cid (ReceiptMode 1) !!! assertActionSucceeded let nonActivatedAccess = ConversationAccessData (Set.singleton CodeAccess) (Set.fromList [TeamMemberAccessRole, NonTeamMemberAccessRole, GuestAccessRole, ServiceAccessRole]) putQualifiedAccessUpdate admin qcid nonActivatedAccess !!! assertActionSucceeded let activatedAccess = ConversationAccessData (Set.singleton InviteAccess) (Set.fromList [TeamMemberAccessRole, NonTeamMemberAccessRole, GuestAccessRole, ServiceAccessRole]) putQualifiedAccessUpdate admin qcid activatedAccess !!! assertActionSucceeded -- Update your own member state let memUpdate = memberUpdate {mupOtrArchive = Just True} putMember admin memUpdate qcid !!! assertActionSucceeded -- You can also leave a conversation deleteMemberQualified admin qadmin qcid !!! assertActionSucceeded -- Readding the user postMembersWithRole otherAdmin (pure qadmin) qcid role !!! const 200 === statusCode -- | Given a member, admin and otherMem, run all the necessary checks -- targeting mem wireMemberChecks :: ConvId -> UserId -> UserId -> UserId -> TestM () wireMemberChecks cid mem admin otherMem = do localDomain <- viewFederationDomain let role = roleNameWireMember qcid = Qualified cid localDomain (other, qother) <- randomUserTuple let qmem = Qualified mem localDomain connectUsers mem (singleton other) -- Members cannot perform pretty much any action on the conversation -- Cannot add members, regardless of their role postMembers mem (pure qother) qcid !!! assertActionDenied -- Cannot remove members, regardless of who they are forM_ ((`Qualified` localDomain) <$> [admin, otherMem]) $ \victim -> deleteMemberQualified mem victim qcid !!! assertActionDenied -- Cannot modify the conversation name void $ putConversationName mem cid "gossip++" !!! assertActionDenied -- Cannot modify other members roles forM_ [admin, otherMem] $ \victim -> do let update = OtherMemberUpdate (Just roleNameWireMember) putOtherMember mem victim update cid !!! assertActionDenied -- Make sure you cannot elevate your own role let sneakyOtherMemberUpdate = OtherMemberUpdate (Just roleNameWireAdmin) putOtherMember mem mem sneakyOtherMemberUpdate cid !!! do const 403 === statusCode const (Just "invalid-op") === fmap label . responseJsonUnsafe -- No updates for message timer, receipt mode or access putMessageTimerUpdate mem cid (ConversationMessageTimerUpdate Nothing) !!! assertActionDenied putReceiptMode mem cid (ReceiptMode 0) !!! assertActionDenied let nonActivatedAccess = ConversationAccessData (Set.singleton CodeAccess) (Set.fromList [TeamMemberAccessRole, NonTeamMemberAccessRole, GuestAccessRole, ServiceAccessRole]) putQualifiedAccessUpdate mem qcid nonActivatedAccess !!! assertActionDenied -- Finally, you can still do the following actions: -- Update your own member state let memUpdate = memberUpdate {mupOtrArchive = Just True} putMember mem memUpdate qcid !!! assertActionSucceeded -- Last option is to leave a conversation deleteMemberQualified mem qmem qcid !!! assertActionSucceeded -- Let's readd the user to make tests easier postMembersWithRole admin (pure qmem) qcid role !!! const 200 === statusCode -- create a conversation and check that the access roles match testConversationAccessRole :: TestM () testConversationAccessRole = do [alice, bob] <- createAndConnectUsers (replicate 2 Nothing) let nc = defNewProteusConv { newConvQualifiedUsers = [bob], newConvAccessRoles = Just (Set.singleton TeamMemberAccessRole) } conv <- responseJsonError =<< postConvQualified (qUnqualified alice) Nothing nc <!! const 201 === statusCode liftIO $ cnvAccessRoles conv @?= Set.singleton TeamMemberAccessRole testAccessRoleUpdateV2 :: TestM () testAccessRoleUpdateV2 = do g <- view tsUnversionedGalley [alice, bob] <- createAndConnectUsers (replicate 2 Nothing) conv <- responseJsonError =<< postConvQualified (qUnqualified alice) Nothing defNewProteusConv { newConvQualifiedUsers = [bob] } <!! const 201 === statusCode let qcnv = cnvQualifiedId conv -- Using v2 qualified endpoint put ( g . paths [ "v2", "conversations", toByteString' (qDomain qcnv), toByteString' (qUnqualified qcnv), "access" ] . zUser (qUnqualified alice) . zConn "conn" . json ( object [ "access" .= ["invite" :: Text], "access_role_v2" .= ["guest" :: Text] ] ) ) !!! const 200 === statusCode -- Using v2 unqualified endpoint put ( g . paths [ "v2", "conversations", toByteString' (qUnqualified qcnv), "access" ] . zUser (qUnqualified alice) . zConn "conn" . json ( object [ "access" .= ["invite" :: Text], "access_role_v2" .= ["guest" :: Text] ] ) ) !!! const 204 === statusCode -------------------------------------------------------------------------------- Utilities assertActionSucceeded :: HasCallStack => Assertions () assertActionSucceeded = const 200 === statusCode assertActionDenied :: HasCallStack => Assertions () assertActionDenied = do const 403 === statusCode const (Just "action-denied") === fmap label . responseJsonUnsafe
null
https://raw.githubusercontent.com/wireapp/wire-server/7f6a2903f2435736b9a498a853a48c3c5abdfb8d/services/galley/test/integration/API/Roles.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 </>. Make sure everyone gets the correct event Add a member to help out with testing Demote bob and run the member checks Make sure everyone gets the correct event Let's promote bob | Given an admin, another admin and a member run all the necessary checks targeting the admin Admins can perform all operations on the conversation; creator is not relevant Add members Remove members, regardless of who they are Modify the conversation name Modify other members roles Updates for message timer, receipt mode or access Update your own member state You can also leave a conversation Readding the user | Given a member, admin and otherMem, run all the necessary checks targeting mem Members cannot perform pretty much any action on the conversation Cannot add members, regardless of their role Cannot remove members, regardless of who they are Cannot modify the conversation name Cannot modify other members roles Make sure you cannot elevate your own role No updates for message timer, receipt mode or access Finally, you can still do the following actions: Update your own member state Last option is to leave a conversation Let's readd the user to make tests easier create a conversation and check that the access roles match Using v2 qualified endpoint Using v2 unqualified endpoint ------------------------------------------------------------------------------
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 API.Roles where import API.Util import Bilge hiding (timeout) import Bilge.Assert import Control.Lens (view) import Data.Aeson hiding (json) import Data.ByteString.Conversion (toByteString') import Data.Domain import Data.Id import Data.List1 import qualified Data.List1 as List1 import Data.Qualified import qualified Data.Set as Set import Data.Singletons import Federator.MockServer import Imports import Network.Wai.Utilities.Error import Test.Tasty import Test.Tasty.Cannon (TimeoutUnit (..), (#)) import qualified Test.Tasty.Cannon as WS import Test.Tasty.HUnit import TestHelpers import TestSetup import Wire.API.Conversation import Wire.API.Conversation.Action import Wire.API.Conversation.Role import Wire.API.Event.Conversation import qualified Wire.API.Federation.API.Galley as F import Wire.API.Federation.Component import Wire.API.Internal.Notification (Notification (..)) tests :: IO TestSetup -> TestTree tests s = testGroup "Conversation roles" [ test s "conversation roles admin (and downgrade)" handleConversationRoleAdmin, test s "conversation roles member (and upgrade)" handleConversationRoleMember, test s "conversation role update with remote users present" roleUpdateWithRemotes, test s "conversation access update with remote users present" accessUpdateWithRemotes, test s "conversation role update of remote member" roleUpdateRemoteMember, test s "get all conversation roles" testAllConversationRoles, test s "access role update with v2" testAccessRoleUpdateV2, test s "test access roles of new conversations" testConversationAccessRole ] testAllConversationRoles :: TestM () testAllConversationRoles = do alice <- randomUser bob <- randomUser chuck <- randomUser connectUsers alice (list1 bob [chuck]) let role = roleNameWireAdmin c <- decodeConvId <$> postConvWithRole alice [bob] (Just "gossip") [] Nothing Nothing role g <- viewGalley get ( g . paths ["conversations", toByteString' c, "roles"] . zUser alice ) !!! do const 200 === statusCode const (Right (ConversationRolesList [convRoleWireAdmin, convRoleWireMember])) === responseJsonEither handleConversationRoleAdmin :: TestM () handleConversationRoleAdmin = do localDomain <- viewFederationDomain c <- view tsCannon (alice, qalice) <- randomUserTuple (bob, qbob) <- randomUserTuple (chuck, qchuck) <- randomUserTuple (eve, qeve) <- randomUserTuple (jack, qjack) <- randomUserTuple connectUsers alice (list1 bob [chuck, eve, jack]) connectUsers eve (singleton bob) connectUsers bob (singleton jack) let role = roleNameWireAdmin cid <- WS.bracketR3 c alice bob chuck $ \(wsA, wsB, wsC) -> do rsp <- postConvWithRole alice [bob, chuck] (Just "gossip") [] Nothing Nothing role void $ assertConvWithRole rsp RegularConv alice qalice [qbob, qchuck] (Just "gossip") Nothing role let cid = decodeConvId rsp qcid = Qualified cid localDomain postMembersWithRole alice (pure qeve) qcid role !!! const 200 === statusCode void . liftIO $ WS.assertMatchN (5 # Second) [wsA, wsB, wsC] $ wsAssertMemberJoinWithRole qcid qalice [qeve] role postMembersWithRole alice (pure qjack) qcid roleNameWireMember !!! const 200 === statusCode void . liftIO $ WS.assertMatchN (5 # Second) [wsA, wsB, wsC] $ wsAssertMemberJoinWithRole qcid qalice [qjack] roleNameWireMember pure cid Added as a wire_admin and do the checks wireAdminChecks cid alice bob jack WS.bracketR3 c alice bob chuck $ \(wsA, wsB, wsC) -> do let updateDown = OtherMemberUpdate (Just roleNameWireMember) qcid = Qualified cid localDomain putOtherMember alice bob updateDown cid !!! assertActionSucceeded void . liftIO . WS.assertMatchN (5 # Second) [wsA, wsB, wsC] $ do wsAssertMemberUpdateWithRole qcid qalice bob roleNameWireMember wireMemberChecks cid bob alice jack handleConversationRoleMember :: TestM () handleConversationRoleMember = do localDomain <- viewFederationDomain c <- view tsCannon (alice, qalice) <- randomUserTuple (bob, qbob) <- randomUserTuple (chuck, qchuck) <- randomUserTuple eve <- randomUser let qeve = Qualified eve localDomain jack <- randomUser connectUsers alice (list1 bob [chuck, eve]) connectUsers bob (singleton chuck) connectUsers eve (list1 bob [jack]) let role = roleNameWireMember cid <- WS.bracketR3 c alice bob chuck $ \(wsA, wsB, wsC) -> do rsp <- postConvWithRole alice [bob, chuck] (Just "gossip") [] Nothing Nothing role void $ assertConvWithRole rsp RegularConv alice qalice [qbob, qchuck] (Just "gossip") Nothing role let cid = decodeConvId rsp qcid = Qualified cid localDomain postMembersWithRole alice (pure qeve) qcid role !!! const 200 === statusCode void . liftIO $ WS.assertMatchN (5 # Second) [wsA, wsB, wsC] $ wsAssertMemberJoinWithRole qcid qalice [qeve] role pure cid Added as a wire_member and do the checks wireMemberChecks cid bob alice chuck WS.bracketR3 c alice bob chuck $ \(wsA, wsB, wsC) -> do let qcid = Qualified cid localDomain let updateUp = OtherMemberUpdate (Just roleNameWireAdmin) can not update , member only putOtherMember chuck bob updateUp cid !!! assertActionDenied putOtherMember alice bob updateUp cid !!! assertActionSucceeded void . liftIO . WS.assertMatchN (5 # Second) [wsA, wsB, wsC] $ do wsAssertMemberUpdateWithRole qcid qalice bob roleNameWireAdmin wireAdminChecks cid bob alice chuck roleUpdateRemoteMember :: TestM () roleUpdateRemoteMember = do c <- view tsCannon let remoteDomain = Domain "alice.example.com" qalice <- Qualified <$> randomId <*> pure remoteDomain qbob <- randomQualifiedUser qcharlie <- Qualified <$> randomId <*> pure remoteDomain let bob = qUnqualified qbob traverse_ (connectWithRemoteUser bob) [qalice, qcharlie] resp <- postConvWithRemoteUsers bob Nothing defNewProteusConv {newConvQualifiedUsers = [qalice, qcharlie]} let qconv = decodeQualifiedConvId resp WS.bracketR c bob $ \wsB -> do (_, requests) <- withTempMockFederator' (mockReply ()) $ putOtherMemberQualified bob qcharlie (OtherMemberUpdate (Just roleNameWireMember)) qconv !!! const 200 === statusCode req <- assertOne requests let mu = MemberUpdateData { misTarget = qcharlie, misOtrMutedStatus = Nothing, misOtrMutedRef = Nothing, misOtrArchived = Nothing, misOtrArchivedRef = Nothing, misHidden = Nothing, misHiddenRef = Nothing, misConvRoleName = Just roleNameWireMember } liftIO $ do frTargetDomain req @?= remoteDomain frComponent req @?= Galley frRPC req @?= "on-conversation-updated" Right cu <- pure . eitherDecode . frBody $ req F.cuConvId cu @?= qUnqualified qconv F.cuAction cu @?= SomeConversationAction (sing @'ConversationMemberUpdateTag) (ConversationMemberUpdate qcharlie (OtherMemberUpdate (Just roleNameWireMember))) sort (F.cuAlreadyPresentUsers cu) @?= sort [qUnqualified qalice, qUnqualified qcharlie] liftIO . WS.assertMatch_ (5 # Second) wsB $ \n -> do let e = List1.head (WS.unpackPayload n) ntfTransient n @?= False evtConv e @?= qconv evtType e @?= MemberStateUpdate evtFrom e @?= qbob evtData e @?= EdMemberUpdate mu conv <- responseJsonError =<< getConvQualified bob qconv <!! const 200 === statusCode let charlieAsMember = find (\m -> omQualifiedId m == qcharlie) (cmOthers (cnvMembers conv)) liftIO $ charlieAsMember @=? Just OtherMember { omQualifiedId = qcharlie, omService = Nothing, omConvRoleName = roleNameWireMember } roleUpdateWithRemotes :: TestM () roleUpdateWithRemotes = do c <- view tsCannon let remoteDomain = Domain "alice.example.com" qalice <- Qualified <$> randomId <*> pure remoteDomain qbob <- randomQualifiedUser qcharlie <- randomQualifiedUser let bob = qUnqualified qbob charlie = qUnqualified qcharlie connectUsers bob (singleton charlie) connectWithRemoteUser bob qalice resp <- postConvWithRemoteUsers bob Nothing defNewProteusConv {newConvQualifiedUsers = [qalice, qcharlie]} let qconv = decodeQualifiedConvId resp WS.bracketR2 c bob charlie $ \(wsB, wsC) -> do (_, requests) <- withTempMockFederator' (mockReply ()) $ putOtherMemberQualified bob qcharlie (OtherMemberUpdate (Just roleNameWireAdmin)) qconv !!! const 200 === statusCode req <- assertOne requests let mu = MemberUpdateData { misTarget = qcharlie, misOtrMutedStatus = Nothing, misOtrMutedRef = Nothing, misOtrArchived = Nothing, misOtrArchivedRef = Nothing, misHidden = Nothing, misHiddenRef = Nothing, misConvRoleName = Just roleNameWireAdmin } liftIO $ do frTargetDomain req @?= remoteDomain frComponent req @?= Galley frRPC req @?= "on-conversation-updated" Right cu <- pure . eitherDecode . frBody $ req F.cuConvId cu @?= qUnqualified qconv F.cuAction cu @?= SomeConversationAction (sing @'ConversationMemberUpdateTag) (ConversationMemberUpdate qcharlie (OtherMemberUpdate (Just roleNameWireAdmin))) F.cuAlreadyPresentUsers cu @?= [qUnqualified qalice] liftIO . WS.assertMatchN_ (5 # Second) [wsB, wsC] $ \n -> do let e = List1.head (WS.unpackPayload n) ntfTransient n @?= False evtConv e @?= qconv evtType e @?= MemberStateUpdate evtFrom e @?= qbob evtData e @?= EdMemberUpdate mu accessUpdateWithRemotes :: TestM () accessUpdateWithRemotes = do c <- view tsCannon let remoteDomain = Domain "alice.example.com" qalice <- Qualified <$> randomId <*> pure remoteDomain qbob <- randomQualifiedUser qcharlie <- randomQualifiedUser let bob = qUnqualified qbob charlie = qUnqualified qcharlie connectUsers bob (singleton charlie) connectWithRemoteUser bob qalice resp <- postConvWithRemoteUsers bob Nothing defNewProteusConv {newConvQualifiedUsers = [qalice, qcharlie]} let qconv = decodeQualifiedConvId resp let access = ConversationAccessData (Set.singleton CodeAccess) (Set.fromList [TeamMemberAccessRole, NonTeamMemberAccessRole, GuestAccessRole, ServiceAccessRole]) WS.bracketR2 c bob charlie $ \(wsB, wsC) -> do (_, requests) <- withTempMockFederator' (mockReply ()) $ putQualifiedAccessUpdate bob qconv access !!! const 200 === statusCode req <- assertOne requests liftIO $ do frTargetDomain req @?= remoteDomain frComponent req @?= Galley frRPC req @?= "on-conversation-updated" Right cu <- pure . eitherDecode . frBody $ req F.cuConvId cu @?= qUnqualified qconv F.cuAction cu @?= SomeConversationAction (sing @'ConversationAccessDataTag) access F.cuAlreadyPresentUsers cu @?= [qUnqualified qalice] liftIO . WS.assertMatchN_ (5 # Second) [wsB, wsC] $ \n -> do let e = List1.head (WS.unpackPayload n) ntfTransient n @?= False evtConv e @?= qconv evtType e @?= ConvAccessUpdate evtFrom e @?= qbob evtData e @?= EdConvAccessUpdate access wireAdminChecks :: ConvId -> UserId -> UserId -> UserId -> TestM () wireAdminChecks cid admin otherAdmin mem = do localDomain <- viewFederationDomain let role = roleNameWireAdmin let qcid = Qualified cid localDomain qadmin = Qualified admin localDomain qotherAdmin = Qualified otherAdmin localDomain qmem = Qualified mem localDomain (other, qother) <- randomUserTuple connectUsers admin (singleton other) postMembers admin (pure qother) qcid !!! assertActionSucceeded forM_ [qotherAdmin, qmem] $ \victim -> do deleteMemberQualified admin victim qcid !!! assertActionSucceeded postMembersWithRole admin (pure victim) qcid role !!! assertActionSucceeded void $ putConversationName admin cid "gossip++" !!! assertActionSucceeded forM_ [otherAdmin, mem] $ \victim -> do let updateDown = OtherMemberUpdate (Just roleNameWireMember) putOtherMember admin victim updateDown cid !!! assertActionSucceeded let updateUp = OtherMemberUpdate (Just roleNameWireAdmin) putOtherMember admin victim updateUp cid !!! assertActionSucceeded putMessageTimerUpdate admin cid (ConversationMessageTimerUpdate $ Just 1000) !!! assertActionSucceeded putMessageTimerUpdate admin cid (ConversationMessageTimerUpdate $ Just 2000) !!! assertActionSucceeded putReceiptMode admin cid (ReceiptMode 0) !!! assertActionSucceeded putReceiptMode admin cid (ReceiptMode 1) !!! assertActionSucceeded let nonActivatedAccess = ConversationAccessData (Set.singleton CodeAccess) (Set.fromList [TeamMemberAccessRole, NonTeamMemberAccessRole, GuestAccessRole, ServiceAccessRole]) putQualifiedAccessUpdate admin qcid nonActivatedAccess !!! assertActionSucceeded let activatedAccess = ConversationAccessData (Set.singleton InviteAccess) (Set.fromList [TeamMemberAccessRole, NonTeamMemberAccessRole, GuestAccessRole, ServiceAccessRole]) putQualifiedAccessUpdate admin qcid activatedAccess !!! assertActionSucceeded let memUpdate = memberUpdate {mupOtrArchive = Just True} putMember admin memUpdate qcid !!! assertActionSucceeded deleteMemberQualified admin qadmin qcid !!! assertActionSucceeded postMembersWithRole otherAdmin (pure qadmin) qcid role !!! const 200 === statusCode wireMemberChecks :: ConvId -> UserId -> UserId -> UserId -> TestM () wireMemberChecks cid mem admin otherMem = do localDomain <- viewFederationDomain let role = roleNameWireMember qcid = Qualified cid localDomain (other, qother) <- randomUserTuple let qmem = Qualified mem localDomain connectUsers mem (singleton other) postMembers mem (pure qother) qcid !!! assertActionDenied forM_ ((`Qualified` localDomain) <$> [admin, otherMem]) $ \victim -> deleteMemberQualified mem victim qcid !!! assertActionDenied void $ putConversationName mem cid "gossip++" !!! assertActionDenied forM_ [admin, otherMem] $ \victim -> do let update = OtherMemberUpdate (Just roleNameWireMember) putOtherMember mem victim update cid !!! assertActionDenied let sneakyOtherMemberUpdate = OtherMemberUpdate (Just roleNameWireAdmin) putOtherMember mem mem sneakyOtherMemberUpdate cid !!! do const 403 === statusCode const (Just "invalid-op") === fmap label . responseJsonUnsafe putMessageTimerUpdate mem cid (ConversationMessageTimerUpdate Nothing) !!! assertActionDenied putReceiptMode mem cid (ReceiptMode 0) !!! assertActionDenied let nonActivatedAccess = ConversationAccessData (Set.singleton CodeAccess) (Set.fromList [TeamMemberAccessRole, NonTeamMemberAccessRole, GuestAccessRole, ServiceAccessRole]) putQualifiedAccessUpdate mem qcid nonActivatedAccess !!! assertActionDenied let memUpdate = memberUpdate {mupOtrArchive = Just True} putMember mem memUpdate qcid !!! assertActionSucceeded deleteMemberQualified mem qmem qcid !!! assertActionSucceeded postMembersWithRole admin (pure qmem) qcid role !!! const 200 === statusCode testConversationAccessRole :: TestM () testConversationAccessRole = do [alice, bob] <- createAndConnectUsers (replicate 2 Nothing) let nc = defNewProteusConv { newConvQualifiedUsers = [bob], newConvAccessRoles = Just (Set.singleton TeamMemberAccessRole) } conv <- responseJsonError =<< postConvQualified (qUnqualified alice) Nothing nc <!! const 201 === statusCode liftIO $ cnvAccessRoles conv @?= Set.singleton TeamMemberAccessRole testAccessRoleUpdateV2 :: TestM () testAccessRoleUpdateV2 = do g <- view tsUnversionedGalley [alice, bob] <- createAndConnectUsers (replicate 2 Nothing) conv <- responseJsonError =<< postConvQualified (qUnqualified alice) Nothing defNewProteusConv { newConvQualifiedUsers = [bob] } <!! const 201 === statusCode let qcnv = cnvQualifiedId conv put ( g . paths [ "v2", "conversations", toByteString' (qDomain qcnv), toByteString' (qUnqualified qcnv), "access" ] . zUser (qUnqualified alice) . zConn "conn" . json ( object [ "access" .= ["invite" :: Text], "access_role_v2" .= ["guest" :: Text] ] ) ) !!! const 200 === statusCode put ( g . paths [ "v2", "conversations", toByteString' (qUnqualified qcnv), "access" ] . zUser (qUnqualified alice) . zConn "conn" . json ( object [ "access" .= ["invite" :: Text], "access_role_v2" .= ["guest" :: Text] ] ) ) !!! const 204 === statusCode Utilities assertActionSucceeded :: HasCallStack => Assertions () assertActionSucceeded = const 200 === statusCode assertActionDenied :: HasCallStack => Assertions () assertActionDenied = do const 403 === statusCode const (Just "action-denied") === fmap label . responseJsonUnsafe
44f59cbc92fab2fcd627e965640925231f94a35df7d1effea256073f6c7059ca
jabber-at/ejabberd
example_tests.erl
%%%------------------------------------------------------------------- Author : < > Created : 16 Nov 2016 by < > %%% %%% ejabberd , Copyright ( C ) 2002 - 2017 ProcessOne %%% %%% 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. , 51 Franklin Street , Fifth Floor , Boston , USA . %%% %%%---------------------------------------------------------------------- -module(example_tests). %% API -compile(export_all). -import(suite, []). -include("suite.hrl"). %%%=================================================================== %%% API %%%=================================================================== %%%=================================================================== %%% Single user tests %%%=================================================================== single_cases() -> {example_single, [sequence], [single_test(foo)]}. foo(Config) -> Config. %%%=================================================================== %%% Master-slave tests %%%=================================================================== master_slave_cases() -> {example_master_slave, [sequence], [master_slave_test(foo)]}. foo_master(Config) -> Config. foo_slave(Config) -> Config. %%%=================================================================== Internal functions %%%=================================================================== single_test(T) -> list_to_atom("example_" ++ atom_to_list(T)). master_slave_test(T) -> {list_to_atom("example_" ++ atom_to_list(T)), [parallel], [list_to_atom("example_" ++ atom_to_list(T) ++ "_master"), list_to_atom("example_" ++ atom_to_list(T) ++ "_slave")]}.
null
https://raw.githubusercontent.com/jabber-at/ejabberd/7bfec36856eaa4df21b26e879d3ba90285bad1aa/test/example_tests.erl
erlang
------------------------------------------------------------------- This program is free software; you can redistribute it and/or 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. ---------------------------------------------------------------------- API =================================================================== API =================================================================== =================================================================== Single user tests =================================================================== =================================================================== Master-slave tests =================================================================== =================================================================== ===================================================================
Author : < > Created : 16 Nov 2016 by < > ejabberd , Copyright ( C ) 2002 - 2017 ProcessOne modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the 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. , 51 Franklin Street , Fifth Floor , Boston , USA . -module(example_tests). -compile(export_all). -import(suite, []). -include("suite.hrl"). single_cases() -> {example_single, [sequence], [single_test(foo)]}. foo(Config) -> Config. master_slave_cases() -> {example_master_slave, [sequence], [master_slave_test(foo)]}. foo_master(Config) -> Config. foo_slave(Config) -> Config. Internal functions single_test(T) -> list_to_atom("example_" ++ atom_to_list(T)). master_slave_test(T) -> {list_to_atom("example_" ++ atom_to_list(T)), [parallel], [list_to_atom("example_" ++ atom_to_list(T) ++ "_master"), list_to_atom("example_" ++ atom_to_list(T) ++ "_slave")]}.
c3ee8c6f02f69d0009289fcfa59766dcd01ea607baa59151310c4e73ad4d99f3
seereason/logic-classes
Meson.hs
# LANGUAGE FlexibleContexts , OverloadedStrings , RankNTypes , ScopedTypeVariables , TypeFamilies # # OPTIONS_GHC -Wall # module Harrison.Meson where import Control.Applicative.Error (Failing(..)) import qualified Data.Map as Map import qualified Data.Set as Set import FOL (pApp) import Formulas ((.&.), (.=>.), (.|.)) import FOL (exists, for_all) import Formulas ((.~.)) import Skolem (HasSkolem(..)) import FOL (IsTerm(vt, fApp)) import FOL (generalize) import Prop (list_conj) import Meson(meson) import Skolem (MyFormula, simpdnf') import Skolem (runSkolem, askolemize) import Data.String (IsString(fromString)) import Prelude hiding (negate) import Test.HUnit (Test(TestCase, TestLabel, TestList), assertEqual) import Tableaux (Depth(Depth)) import Common (render) import Harrison.Resolution (dpExampleFm) tests :: Test tests = TestLabel "Data.Logic.Tests.Harrison.Meson" $ TestList [test01, test02] -- ------------------------------------------------------------------------- -- Example. -- ------------------------------------------------------------------------- test01 :: Test test01 = TestLabel "Data.Logic.Tests.Harrison.Meson" $ TestCase $ assertEqual "meson dp example (p. 220)" expected input where input = runSkolem (meson (Just (Depth 10)) (dpExampleFm :: MyFormula)) expected = Set.singleton ( Success ( ( Map.empty , 0 , 0 ) , 8) Success ((Map.fromList [(fromString "_0",vt' "_6"), (fromString "_1",vt' "_2"), (fromString "_10",fApp (toSkolem "z") [vt' "_6",vt' "_7"]), (fromString "_11",fApp (toSkolem "z") [vt' "_6",vt' "_7"]), (fromString "_12",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_13",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_14",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_15",fApp (toSkolem "z") [vt' "_12",vt' "_13"]), (fromString "_16",fApp (toSkolem "z") [vt' "_12",vt' "_13"]), (fromString "_17",fApp (toSkolem "z") [vt' "_12",vt' "_13"]), (fromString "_3",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_4",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_5",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_7",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_8",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_9",fApp (toSkolem "z") [vt' "_6",vt' "_7"])],0,18),Depth 8) ) vt' = vt . fromString test02 :: Test test02 = TestLabel "Data.Logic.Tests.Harrison.Meson" $ TestList [TestCase (assertEqual "meson dp example, step 1 (p. 220)" (render (exists "x" (exists "y" (for_all "z" (((f [x,y]) .=>. ((f [y,z]) .&. (f [z,z]))) .&. (((f [x,y]) .&. (g [x,y])) .=>. ((g [x,z]) .&. (g [z,z])))))))) (render dpExampleFm)), TestCase (assertEqual "meson dp example, step 2 (p. 220)" (render (exists "x" (exists "y" (for_all "z" (((f [x,y]) .=>. ((f [y,z]) .&. (f [z,z]))) .&. (((f [x,y]) .&. (g [x,y])) .=>. ((g [x,z]) .&. (g [z,z])))))))) (render (generalize dpExampleFm))), TestCase (assertEqual "meson dp example, step 3 (p. 220)" (render ((.~.)(exists "x" (exists "y" (for_all "z" (((f [x,y]) .=>. ((f [y,z]) .&. (f [z,z]))) .&. (((f [x,y]) .&. (g [x,y])) .=>. ((g [x,z]) .&. (g [z,z]))))))) :: MyFormula)) (render ((.~.) (generalize dpExampleFm)))), TestCase (assertEqual "meson dp example, step 4 (p. 220)" (render (for_all "x" . for_all "y" $ f[x,y] .&. ((.~.)(f[y, sk1[x, y]]) .|. ((.~.)(f[sk1[x,y], sk1[x, y]]))) .|. (f[x,y] .&. g[x,y]) .&. (((.~.)(g[x,sk1[x,y]])) .|. ((.~.)(g[sk1[x,y], sk1[x,y]]))))) (render (runSkolem (askolemize ((.~.) (generalize dpExampleFm))) :: MyFormula))), TestCase (assertEqual "meson dp example, step 5 (p. 220)" (Set.map (Set.map render) (Set.fromList [Set.fromList [for_all "x" . for_all "y" $ f[x,y] .&. ((.~.)(f[y, sk1[x, y]]) .|. ((.~.)(f[sk1[x,y], sk1[x, y]]))) .|. (f[x,y] .&. g[x,y]) .&. (((.~.)(g[x,sk1[x,y]])) .|. ((.~.)(g[sk1[x,y], sk1[x,y]])))]])) [ [ < < forall x y. F(x , y ) /\ ( ~F(y , f_z(x , y ) ) \/ ~F(f_z(x , y),f_z(x , y ) ) ) \/ ( F(x , y ) /\ G(x , y ) ) /\ ( ~G(x , f_z(x , y ) ) \/ ~G(f_z(x , y),f_z(x , y ) ) ) > > ] ] [[<<forall x y. F(x,y) /\ (~F(y,f_z(x,y)) \/ ~F(f_z(x,y),f_z(x,y))) \/ (F(x,y) /\ G(x,y)) /\ (~G(x,f_z(x,y)) \/ ~G(f_z(x,y),f_z(x,y))) >>]] -} (Set.map (Set.map render) (simpdnf' (runSkolem (askolemize ((.~.) (generalize dpExampleFm))) :: MyFormula)))), TestCase (assertEqual "meson dp example, step 6 (p. 220)" (Set.map render (Set.fromList [for_all "x" . for_all "y" $ f[x,y] .&. ((.~.)(f[y, sk1[x, y]]) .|. ((.~.)(f[sk1[x,y], sk1[x, y]]))) .|. (f[x,y] .&. g[x,y]) .&. (((.~.)(g[x,sk1[x,y]])) .|. ((.~.)(g[sk1[x,y], sk1[x,y]])))])) [ < < forall x y. F(x , y ) /\ ( ~F(y , f_z(x , y ) ) \/ ~F(f_z(x , y),f_z(x , y ) ) ) \/ ( F(x , y ) /\ G(x , y ) ) /\ ( ~G(x , f_z(x , y ) ) \/ ~G(f_z(x , y),f_z(x , y ) ) ) > > ] [<<forall x y. F(x,y) /\ (~F(y,f_z(x,y)) \/ ~F(f_z(x,y),f_z(x,y))) \/ (F(x,y) /\ G(x,y)) /\ (~G(x,f_z(x,y)) \/ ~G(f_z(x,y),f_z(x,y)))>>] -} (Set.map render ((Set.map list_conj (simpdnf' (runSkolem (askolemize ((.~.) (generalize dpExampleFm)))))) :: Set.Set MyFormula)))] where f = pApp "F" g = pApp "G" sk1 = fApp (toSkolem "z") x = vt "x" y = vt "y" z = vt "z" askolemize ( simpdnf ( generalize dpExampleFm ) ) - > < < forall x y. F(x , y ) /\ ( ~F(y , f_z(x , y ) ) \/ ~F(f_z(x , y ) , f_z(x , y ) ) ) \/ ( F(x , y ) /\ G(x , y ) ) /\ ( ~G(x , f_z(x , y ) ) \/ ~G(f_z(x , y),f_z(x , y ) ) ) > > askolemize (simpdnf (generalize dpExampleFm)) -> <<forall x y. F(x,y) /\ (~F(y,f_z(x,y)) \/ ~F(f_z(x,y), f_z(x,y))) \/ (F(x,y) /\ G(x,y)) /\ (~G(x,f_z(x,y)) \/ ~G(f_z(x,y),f_z(x,y)))>> -}
null
https://raw.githubusercontent.com/seereason/logic-classes/819059218027c3ee77bd2ef3a873fcca230d54b4/Tests/Harrison/Meson.hs
haskell
------------------------------------------------------------------------- Example. -------------------------------------------------------------------------
# LANGUAGE FlexibleContexts , OverloadedStrings , RankNTypes , ScopedTypeVariables , TypeFamilies # # OPTIONS_GHC -Wall # module Harrison.Meson where import Control.Applicative.Error (Failing(..)) import qualified Data.Map as Map import qualified Data.Set as Set import FOL (pApp) import Formulas ((.&.), (.=>.), (.|.)) import FOL (exists, for_all) import Formulas ((.~.)) import Skolem (HasSkolem(..)) import FOL (IsTerm(vt, fApp)) import FOL (generalize) import Prop (list_conj) import Meson(meson) import Skolem (MyFormula, simpdnf') import Skolem (runSkolem, askolemize) import Data.String (IsString(fromString)) import Prelude hiding (negate) import Test.HUnit (Test(TestCase, TestLabel, TestList), assertEqual) import Tableaux (Depth(Depth)) import Common (render) import Harrison.Resolution (dpExampleFm) tests :: Test tests = TestLabel "Data.Logic.Tests.Harrison.Meson" $ TestList [test01, test02] test01 :: Test test01 = TestLabel "Data.Logic.Tests.Harrison.Meson" $ TestCase $ assertEqual "meson dp example (p. 220)" expected input where input = runSkolem (meson (Just (Depth 10)) (dpExampleFm :: MyFormula)) expected = Set.singleton ( Success ( ( Map.empty , 0 , 0 ) , 8) Success ((Map.fromList [(fromString "_0",vt' "_6"), (fromString "_1",vt' "_2"), (fromString "_10",fApp (toSkolem "z") [vt' "_6",vt' "_7"]), (fromString "_11",fApp (toSkolem "z") [vt' "_6",vt' "_7"]), (fromString "_12",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_13",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_14",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_15",fApp (toSkolem "z") [vt' "_12",vt' "_13"]), (fromString "_16",fApp (toSkolem "z") [vt' "_12",vt' "_13"]), (fromString "_17",fApp (toSkolem "z") [vt' "_12",vt' "_13"]), (fromString "_3",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_4",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_5",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_7",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_8",fApp (toSkolem "z") [vt' "_0",vt' "_1"]), (fromString "_9",fApp (toSkolem "z") [vt' "_6",vt' "_7"])],0,18),Depth 8) ) vt' = vt . fromString test02 :: Test test02 = TestLabel "Data.Logic.Tests.Harrison.Meson" $ TestList [TestCase (assertEqual "meson dp example, step 1 (p. 220)" (render (exists "x" (exists "y" (for_all "z" (((f [x,y]) .=>. ((f [y,z]) .&. (f [z,z]))) .&. (((f [x,y]) .&. (g [x,y])) .=>. ((g [x,z]) .&. (g [z,z])))))))) (render dpExampleFm)), TestCase (assertEqual "meson dp example, step 2 (p. 220)" (render (exists "x" (exists "y" (for_all "z" (((f [x,y]) .=>. ((f [y,z]) .&. (f [z,z]))) .&. (((f [x,y]) .&. (g [x,y])) .=>. ((g [x,z]) .&. (g [z,z])))))))) (render (generalize dpExampleFm))), TestCase (assertEqual "meson dp example, step 3 (p. 220)" (render ((.~.)(exists "x" (exists "y" (for_all "z" (((f [x,y]) .=>. ((f [y,z]) .&. (f [z,z]))) .&. (((f [x,y]) .&. (g [x,y])) .=>. ((g [x,z]) .&. (g [z,z]))))))) :: MyFormula)) (render ((.~.) (generalize dpExampleFm)))), TestCase (assertEqual "meson dp example, step 4 (p. 220)" (render (for_all "x" . for_all "y" $ f[x,y] .&. ((.~.)(f[y, sk1[x, y]]) .|. ((.~.)(f[sk1[x,y], sk1[x, y]]))) .|. (f[x,y] .&. g[x,y]) .&. (((.~.)(g[x,sk1[x,y]])) .|. ((.~.)(g[sk1[x,y], sk1[x,y]]))))) (render (runSkolem (askolemize ((.~.) (generalize dpExampleFm))) :: MyFormula))), TestCase (assertEqual "meson dp example, step 5 (p. 220)" (Set.map (Set.map render) (Set.fromList [Set.fromList [for_all "x" . for_all "y" $ f[x,y] .&. ((.~.)(f[y, sk1[x, y]]) .|. ((.~.)(f[sk1[x,y], sk1[x, y]]))) .|. (f[x,y] .&. g[x,y]) .&. (((.~.)(g[x,sk1[x,y]])) .|. ((.~.)(g[sk1[x,y], sk1[x,y]])))]])) [ [ < < forall x y. F(x , y ) /\ ( ~F(y , f_z(x , y ) ) \/ ~F(f_z(x , y),f_z(x , y ) ) ) \/ ( F(x , y ) /\ G(x , y ) ) /\ ( ~G(x , f_z(x , y ) ) \/ ~G(f_z(x , y),f_z(x , y ) ) ) > > ] ] [[<<forall x y. F(x,y) /\ (~F(y,f_z(x,y)) \/ ~F(f_z(x,y),f_z(x,y))) \/ (F(x,y) /\ G(x,y)) /\ (~G(x,f_z(x,y)) \/ ~G(f_z(x,y),f_z(x,y))) >>]] -} (Set.map (Set.map render) (simpdnf' (runSkolem (askolemize ((.~.) (generalize dpExampleFm))) :: MyFormula)))), TestCase (assertEqual "meson dp example, step 6 (p. 220)" (Set.map render (Set.fromList [for_all "x" . for_all "y" $ f[x,y] .&. ((.~.)(f[y, sk1[x, y]]) .|. ((.~.)(f[sk1[x,y], sk1[x, y]]))) .|. (f[x,y] .&. g[x,y]) .&. (((.~.)(g[x,sk1[x,y]])) .|. ((.~.)(g[sk1[x,y], sk1[x,y]])))])) [ < < forall x y. F(x , y ) /\ ( ~F(y , f_z(x , y ) ) \/ ~F(f_z(x , y),f_z(x , y ) ) ) \/ ( F(x , y ) /\ G(x , y ) ) /\ ( ~G(x , f_z(x , y ) ) \/ ~G(f_z(x , y),f_z(x , y ) ) ) > > ] [<<forall x y. F(x,y) /\ (~F(y,f_z(x,y)) \/ ~F(f_z(x,y),f_z(x,y))) \/ (F(x,y) /\ G(x,y)) /\ (~G(x,f_z(x,y)) \/ ~G(f_z(x,y),f_z(x,y)))>>] -} (Set.map render ((Set.map list_conj (simpdnf' (runSkolem (askolemize ((.~.) (generalize dpExampleFm)))))) :: Set.Set MyFormula)))] where f = pApp "F" g = pApp "G" sk1 = fApp (toSkolem "z") x = vt "x" y = vt "y" z = vt "z" askolemize ( simpdnf ( generalize dpExampleFm ) ) - > < < forall x y. F(x , y ) /\ ( ~F(y , f_z(x , y ) ) \/ ~F(f_z(x , y ) , f_z(x , y ) ) ) \/ ( F(x , y ) /\ G(x , y ) ) /\ ( ~G(x , f_z(x , y ) ) \/ ~G(f_z(x , y),f_z(x , y ) ) ) > > askolemize (simpdnf (generalize dpExampleFm)) -> <<forall x y. F(x,y) /\ (~F(y,f_z(x,y)) \/ ~F(f_z(x,y), f_z(x,y))) \/ (F(x,y) /\ G(x,y)) /\ (~G(x,f_z(x,y)) \/ ~G(f_z(x,y),f_z(x,y)))>> -}
d0084c3a9cb10e0fb3c9133284ec82c7f90b19d3443456e27d63337130c472f9
TrueBoxGuy/Iocularia
Scope.hs
| Module : Transpiler . Scope Description : Scope helper functions License : Apache License 2.0 Stability : experimental Contains helpers for differentiating the behaviour conversions have on bound and unbound variables . Furthermore , this module enables for inlined variables . Module : Transpiler.Scope Description : Scope helper functions License : Apache License 2.0 Stability : experimental Contains helpers for differentiating the behaviour conversions have on bound and unbound variables. Furthermore, this module enables for inlined variables. -} module Transpiler.Scope where import qualified Lambda.Lambda as L import Lambda.Combinators import Data.Bool import Data.Foldable import Data.List import Data.Monoid -- | Term that can refer to either the global scope or a bound variable. data ScopeTerm t = Inner t -- ^ Inner scope, referring to the term instantiated by a lambda at a certain depth. | Global -- ^ The global scope, which contains all variables that aren't inlined. | Adds depth to all bound variables so that an expression can be wrapped in a @'L.Lambda'@ and still be valid . addDepth :: Integral a => a -> L.Expr (ScopeTerm a) -> L.Expr (ScopeTerm a) addDepth d = L.termReplacer depthAdder 0 where depthAdder _ Global = L.Term Global depthAdder _ (Inner d1) = L.Term (Inner (d1 + d)) -- | Converts an expression containing only bound variables to a scoped expression. toScopeTerm :: L.Expr a -> L.Expr (ScopeTerm a) toScopeTerm = L.termReplacer (pure (L.Term . Inner)) 0 | Converts an expression containing scoped terms to one containing only scoped variables , with the assumption that the global scope is at depth 0 . toTerm :: Integral a => L.Expr (ScopeTerm a) -> L.Expr a toTerm = L.termReplacer (pure globaliser) 0 where globaliser (Inner t) = L.Term t globaliser Global = L.Term 0 | Accesses the nth term of a partition of length l , by passing in @'truthAccessor'@ and @'falseAccessor'@ -- to access binary partitions of this partition. accessIndex :: Integral a => L.Expr (ScopeTerm a) -- ^ The partition that access is being done on. -> a -- ^ The length of this partition. -> a -- ^ The term that needs to be accessed in this partition. -> L.Expr (ScopeTerm a) -- ^ Expression which accesses this term. accessIndex a 1 _ = a accessIndex a l n = newExpression where midpoint = until (>= l) (*2) 2 `div` 2 newExpression = bool (accessIndex (L.App a (toScopeTerm truthAccessor)) midpoint n) (accessIndex (L.App a (toScopeTerm falseAccessor)) (l - midpoint) (n - midpoint)) (n >= midpoint) | Accesses a global variable from the global scope : see @'accessIndex'@ for an in detail explanation of how this works . makeGlobalAccessor :: Integral a => [String] -> String -> Maybe (L.Expr (ScopeTerm a)) makeGlobalAccessor terms access = accessIndex (L.Term Global) (fromIntegral $ length terms) . fromIntegral <$> findIndex (== access) terms | Accesses main , but outside of the : this enables a program to be run . accessMain :: Integral a => [String] -> (L.Expr (ScopeTerm a)) -> Maybe (L.Expr (ScopeTerm a)) accessMain terms a = accessIndex a (fromIntegral $ length terms) . fromIntegral <$> findIndex (== "main") terms -- | Accesses a bound variable: as the bound term refers to a term at a higer level, the length of bound terms should not be -- added to this accessor. makeBoundAccessor :: Integral a => [String] -> String -> Maybe (L.Expr (ScopeTerm a)) makeBoundAccessor terms access = L.Term . Inner . fromIntegral <$> findIndex (== access) terms -- | Accesses any variable: bound variables; global variables; inlined variables. makeAccessor :: Integral a => [String] -- ^ The list of bound variable names. -> [String] -- ^ The list of global variable names. -> (String -> Either String (L.Expr (ScopeTerm a))) -- ^ A function giving inlined expressions. -> String -- ^ The variable wanting to be accessed. -> Either String (L.Expr (ScopeTerm a)) -- ^ The final expression that accesses the variable. makeAccessor bound global inliner = fmap lambdaDepth . inliner <> maybeAccessors where lambdaDepth = addDepth (fromIntegral . length $ bound) maybeAccessors name = maybe (Left (name <> " not found")) Right (asum . sequence [makeBoundAccessor bound, fmap lambdaDepth . makeGlobalAccessor global] $ name) -- | Identifies variables that can be inlined from a list of their dependencies. identifyInlineable :: [(String, [String], a)] -- ^ A list containing tuples of, in order: variable name; dependencies; expressions. -> [(String, a)] -- ^ A list containing tuples of, in order: inlineable variable names; expressions. identifyInlineable list = bool (inlineable ++ identifyInlineable rest) [] (null inlineable) where dependencies (a, b, c) = b inlineable = (\(a, b, c) -> (a, c)) <$> filter (getAll . inlinePredicate) list inlinePredicate = mconcat (fmap All <$> [null . dependencies, (/= "main") . (\(a, b, c) -> a)]) names = fst <$> inlineable rest = (\(a, b, c) -> (a, filter (flip notElem names) b, c)) <$> filter (not . null . dependencies) list
null
https://raw.githubusercontent.com/TrueBoxGuy/Iocularia/5def65d2d21c33c5c09462a2015a64848f6f4f41/src/Transpiler/Scope.hs
haskell
| Term that can refer to either the global scope or a bound variable. ^ Inner scope, referring to the term instantiated by a lambda at a certain depth. ^ The global scope, which contains all variables that aren't inlined. | Converts an expression containing only bound variables to a scoped expression. to access binary partitions of this partition. ^ The partition that access is being done on. ^ The length of this partition. ^ The term that needs to be accessed in this partition. ^ Expression which accesses this term. | Accesses a bound variable: as the bound term refers to a term at a higer level, the length of bound terms should not be added to this accessor. | Accesses any variable: bound variables; global variables; inlined variables. ^ The list of bound variable names. ^ The list of global variable names. ^ A function giving inlined expressions. ^ The variable wanting to be accessed. ^ The final expression that accesses the variable. | Identifies variables that can be inlined from a list of their dependencies. ^ A list containing tuples of, in order: variable name; dependencies; expressions. ^ A list containing tuples of, in order: inlineable variable names; expressions.
| Module : Transpiler . Scope Description : Scope helper functions License : Apache License 2.0 Stability : experimental Contains helpers for differentiating the behaviour conversions have on bound and unbound variables . Furthermore , this module enables for inlined variables . Module : Transpiler.Scope Description : Scope helper functions License : Apache License 2.0 Stability : experimental Contains helpers for differentiating the behaviour conversions have on bound and unbound variables. Furthermore, this module enables for inlined variables. -} module Transpiler.Scope where import qualified Lambda.Lambda as L import Lambda.Combinators import Data.Bool import Data.Foldable import Data.List import Data.Monoid data ScopeTerm t | Adds depth to all bound variables so that an expression can be wrapped in a @'L.Lambda'@ and still be valid . addDepth :: Integral a => a -> L.Expr (ScopeTerm a) -> L.Expr (ScopeTerm a) addDepth d = L.termReplacer depthAdder 0 where depthAdder _ Global = L.Term Global depthAdder _ (Inner d1) = L.Term (Inner (d1 + d)) toScopeTerm :: L.Expr a -> L.Expr (ScopeTerm a) toScopeTerm = L.termReplacer (pure (L.Term . Inner)) 0 | Converts an expression containing scoped terms to one containing only scoped variables , with the assumption that the global scope is at depth 0 . toTerm :: Integral a => L.Expr (ScopeTerm a) -> L.Expr a toTerm = L.termReplacer (pure globaliser) 0 where globaliser (Inner t) = L.Term t globaliser Global = L.Term 0 | Accesses the nth term of a partition of length l , by passing in @'truthAccessor'@ and @'falseAccessor'@ accessIndex :: Integral a accessIndex a 1 _ = a accessIndex a l n = newExpression where midpoint = until (>= l) (*2) 2 `div` 2 newExpression = bool (accessIndex (L.App a (toScopeTerm truthAccessor)) midpoint n) (accessIndex (L.App a (toScopeTerm falseAccessor)) (l - midpoint) (n - midpoint)) (n >= midpoint) | Accesses a global variable from the global scope : see @'accessIndex'@ for an in detail explanation of how this works . makeGlobalAccessor :: Integral a => [String] -> String -> Maybe (L.Expr (ScopeTerm a)) makeGlobalAccessor terms access = accessIndex (L.Term Global) (fromIntegral $ length terms) . fromIntegral <$> findIndex (== access) terms | Accesses main , but outside of the : this enables a program to be run . accessMain :: Integral a => [String] -> (L.Expr (ScopeTerm a)) -> Maybe (L.Expr (ScopeTerm a)) accessMain terms a = accessIndex a (fromIntegral $ length terms) . fromIntegral <$> findIndex (== "main") terms makeBoundAccessor :: Integral a => [String] -> String -> Maybe (L.Expr (ScopeTerm a)) makeBoundAccessor terms access = L.Term . Inner . fromIntegral <$> findIndex (== access) terms makeAccessor :: Integral a makeAccessor bound global inliner = fmap lambdaDepth . inliner <> maybeAccessors where lambdaDepth = addDepth (fromIntegral . length $ bound) maybeAccessors name = maybe (Left (name <> " not found")) Right (asum . sequence [makeBoundAccessor bound, fmap lambdaDepth . makeGlobalAccessor global] $ name) identifyInlineable identifyInlineable list = bool (inlineable ++ identifyInlineable rest) [] (null inlineable) where dependencies (a, b, c) = b inlineable = (\(a, b, c) -> (a, c)) <$> filter (getAll . inlinePredicate) list inlinePredicate = mconcat (fmap All <$> [null . dependencies, (/= "main") . (\(a, b, c) -> a)]) names = fst <$> inlineable rest = (\(a, b, c) -> (a, filter (flip notElem names) b, c)) <$> filter (not . null . dependencies) list
47bd3c10006220cecccb69a457f7f0acb5e7711a0569176c985a7c8ff48050cb
mattdw/stemmers
core.clj
(ns stemmers.test.core (:use [stemmers.core] :reload) (:use [clojure.test])) (deftest basic-tokenise (is (= (tokenise "nothing ever happens") ["nothing" "ever" "happens"]))) (deftest default-stem (is (= (stems "the hungry dog hungrily jumped over the angry moon with a hunger, jumping with anger.") ["hungri" "dog" "hungrili" "jump" "over" "angri" "moon" "with" "hunger" "jump" "with" "anger"])))
null
https://raw.githubusercontent.com/mattdw/stemmers/7a29b412352ebb604058b357ba332a8b53d0565f/test/stemmers/test/core.clj
clojure
(ns stemmers.test.core (:use [stemmers.core] :reload) (:use [clojure.test])) (deftest basic-tokenise (is (= (tokenise "nothing ever happens") ["nothing" "ever" "happens"]))) (deftest default-stem (is (= (stems "the hungry dog hungrily jumped over the angry moon with a hunger, jumping with anger.") ["hungri" "dog" "hungrili" "jump" "over" "angri" "moon" "with" "hunger" "jump" "with" "anger"])))
6e50d59ed450deabb8164591167d5921e0e417bd1e5db1dec7262e7c633fdb9a
zenspider/schemers
exercise.4.60.scm
#!/usr/bin/env csi -s (require rackunit) (require-library logic-eval) (import logic-eval) (initialize-data-base microshaft-data-base) Exercise 4.60 ;; By giving the query ;; ( lives - near ? person ( Hacker ) ) ;; is able to find people who live near her , with ;; whom she can ride to work. On the other hand, when she tries to ;; find all pairs of people who live near each other by querying ;; ;; (lives-near ?person-1 ?person-2) ;; ;; she notices that each pair of people who live near each other is ;; listed twice; for example, ;; ( lives - near ( Hacker ) ( ) ) ( lives - near ( ) ( Hacker ) ) ;; ;; Why does this happen? Is there a way to find a list of people who ;; live near each other, in which each pair appears only once? ;; Explain. ;; A: Simple, the lives-near query is commutative. if A lives near B, ;; then B lives near A. Since the query engine tests every ;; combination, it makes sense you'd get both. (define (list<? l1 l2) (or (null? l1) (string<? (symbol->string (car l1)) (symbol->string (car l2))) (and (string=? (symbol->string (car l1)) (symbol->string (car l2))) (list<? (cdr l1) (cdr l2))))) (assert! '(rule (lives-near2 ?person-1 ?person-2) (and (address ?person-1 (?town . ?rest-1)) (address ?person-2 (?town . ?rest-2)) (not (same ?person-1 ?person-2)) (lisp-value list<? ?person-1 ?person-2)))) (test '((lives-near (Aull DeWitt) (Reasoner Louis)) (lives-near (Aull DeWitt) (Bitdiddle Ben)) (lives-near (Reasoner Louis) (Aull DeWitt)) (lives-near (Reasoner Louis) (Bitdiddle Ben)) (lives-near (Hacker Alyssa P) (Fect Cy D)) (lives-near (Fect Cy D) (Hacker Alyssa P)) (lives-near (Bitdiddle Ben) (Aull DeWitt)) (lives-near (Bitdiddle Ben) (Reasoner Louis))) (all-of '(lives-near ?a ?b))) (test '((lives-near2 (Aull DeWitt) (Reasoner Louis)) (lives-near2 (Aull DeWitt) (Bitdiddle Ben)) (lives-near2 (Fect Cy D) (Hacker Alyssa P)) (lives-near2 (Bitdiddle Ben) (Reasoner Louis))) (all-of '(lives-near2 ?a ?b)))
null
https://raw.githubusercontent.com/zenspider/schemers/2939ca553ac79013a4c3aaaec812c1bad3933b16/sicp/ch_4/exercise.4.60.scm
scheme
By giving the query whom she can ride to work. On the other hand, when she tries to find all pairs of people who live near each other by querying (lives-near ?person-1 ?person-2) she notices that each pair of people who live near each other is listed twice; for example, Why does this happen? Is there a way to find a list of people who live near each other, in which each pair appears only once? Explain. A: Simple, the lives-near query is commutative. if A lives near B, then B lives near A. Since the query engine tests every combination, it makes sense you'd get both.
#!/usr/bin/env csi -s (require rackunit) (require-library logic-eval) (import logic-eval) (initialize-data-base microshaft-data-base) Exercise 4.60 ( lives - near ? person ( Hacker ) ) is able to find people who live near her , with ( lives - near ( Hacker ) ( ) ) ( lives - near ( ) ( Hacker ) ) (define (list<? l1 l2) (or (null? l1) (string<? (symbol->string (car l1)) (symbol->string (car l2))) (and (string=? (symbol->string (car l1)) (symbol->string (car l2))) (list<? (cdr l1) (cdr l2))))) (assert! '(rule (lives-near2 ?person-1 ?person-2) (and (address ?person-1 (?town . ?rest-1)) (address ?person-2 (?town . ?rest-2)) (not (same ?person-1 ?person-2)) (lisp-value list<? ?person-1 ?person-2)))) (test '((lives-near (Aull DeWitt) (Reasoner Louis)) (lives-near (Aull DeWitt) (Bitdiddle Ben)) (lives-near (Reasoner Louis) (Aull DeWitt)) (lives-near (Reasoner Louis) (Bitdiddle Ben)) (lives-near (Hacker Alyssa P) (Fect Cy D)) (lives-near (Fect Cy D) (Hacker Alyssa P)) (lives-near (Bitdiddle Ben) (Aull DeWitt)) (lives-near (Bitdiddle Ben) (Reasoner Louis))) (all-of '(lives-near ?a ?b))) (test '((lives-near2 (Aull DeWitt) (Reasoner Louis)) (lives-near2 (Aull DeWitt) (Bitdiddle Ben)) (lives-near2 (Fect Cy D) (Hacker Alyssa P)) (lives-near2 (Bitdiddle Ben) (Reasoner Louis))) (all-of '(lives-near2 ?a ?b)))
ef2a9028a3d75e75fcb80561b273e950b66f29f382f48c8e23ff3ef7e2bdc3b3
AeneasVerif/aeneas
Utils.ml
include Charon.Utils
null
https://raw.githubusercontent.com/AeneasVerif/aeneas/d8d661d02cf0068753ae3963156896492dfde50a/compiler/Utils.ml
ocaml
include Charon.Utils
6ee0447b46de8e5a0813ec3742a52cc0f00b6319f8e810b52e117b0c447fd64b
clojure-interop/java-jdk
BasicCheckBoxUI.clj
(ns javax.swing.plaf.basic.BasicCheckBoxUI "CheckboxUI implementation for BasicCheckboxUI Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeans™ has been added to the java.beans package. Please see XMLEncoder." (:refer-clojure :only [require comment defn ->]) (:import [javax.swing.plaf.basic BasicCheckBoxUI])) (defn ->basic-check-box-ui "Constructor." (^BasicCheckBoxUI [] (new BasicCheckBoxUI ))) (defn *create-ui "b - `javax.swing.JComponent` returns: `javax.swing.plaf.ComponentUI`" (^javax.swing.plaf.ComponentUI [^javax.swing.JComponent b] (BasicCheckBoxUI/createUI b))) (defn get-property-prefix "returns: `java.lang.String`" (^java.lang.String [^BasicCheckBoxUI this] (-> this (.getPropertyPrefix))))
null
https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.swing/src/javax/swing/plaf/basic/BasicCheckBoxUI.clj
clojure
(ns javax.swing.plaf.basic.BasicCheckBoxUI "CheckboxUI implementation for BasicCheckboxUI Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeans™ has been added to the java.beans package. Please see XMLEncoder." (:refer-clojure :only [require comment defn ->]) (:import [javax.swing.plaf.basic BasicCheckBoxUI])) (defn ->basic-check-box-ui "Constructor." (^BasicCheckBoxUI [] (new BasicCheckBoxUI ))) (defn *create-ui "b - `javax.swing.JComponent` returns: `javax.swing.plaf.ComponentUI`" (^javax.swing.plaf.ComponentUI [^javax.swing.JComponent b] (BasicCheckBoxUI/createUI b))) (defn get-property-prefix "returns: `java.lang.String`" (^java.lang.String [^BasicCheckBoxUI this] (-> this (.getPropertyPrefix))))
fda619ad70cdcef252c8b2d0197294a0b007ab47d833429e492f6e5b35615162
lambdabot/lambdabot
Instances.hs
| A module to output the instances of a typeclass . Some sample input\/output : > > @instances Monad > [ ] , ArrowMonad a , WriterT w m , , ReaderT r m , Reader r , > StateT s m , State s , RWST r w s m , RWS r w s , ErrorT e m , Either e , , Cont r , Maybe , ST s , IO > > > @instances Show > Float , Double , Integer , ST s a , [ a ] , ( a , b , c , d ) , ( a , b , c ) , ( a , b ) , > ( ) , Ordering , Maybe a , Int , Either a b , , > > > @instances - importing Text . Html Data . Tree Show > Float , Double , Tree a , HtmlTable , HtmlAttr , Html , , Integer , > ST s a , [ a ] , ( a , b , c , d ) , ( a , b , c ) , ( a , b ) , ( ) , Ordering , Maybe a , > Int Some sample input\/output: > lambdabot> @instances Monad > [], ArrowMonad a, WriterT w m, Writer w, ReaderT r m, Reader r, > StateT s m, State s, RWST r w s m, RWS r w s, ErrorT e m, Either e, > ContT r m, Cont r, Maybe, ST s, IO > > lambdabot> @instances Show > Float, Double, Integer, ST s a, [a], (a, b, c, d), (a, b, c), (a, b), > (), Ordering, Maybe a, Int, Either a b, Char, Bool > > lambdabot> @instances-importing Text.Html Data.Tree Show > Float, Double, Tree a, HtmlTable, HtmlAttr, Html, HotLink, Integer, > ST s a, [a], (a, b, c, d), (a, b, c), (a, b), (), Ordering, Maybe a, > Int -} module Lambdabot.Plugin.Haskell.Instances (instancesPlugin) where import Text.ParserCombinators.Parsec import Lambdabot.Config.Haskell import Lambdabot.Plugin import Lambdabot.Util import Lambdabot.Plugin.Haskell.Eval (findL_hs) import Control.Applicative ((*>)) import Control.Monad import Data.Char import Data.List import Data.List.Split import Data.Maybe import System.FilePath import System.Process import Text.Regex.TDFA type Instance = String type ClassName = String type ModuleName = String instancesPlugin :: Module () instancesPlugin = newModule { moduleCmds = return [ (command "instances") { help = say "instances <typeclass>. Fetch the instances of a typeclass." , process = fetchInstances >=> say } , (command "instances-importing") { help = say $ "instances-importing [<module> [<module> [<module...]]] <typeclass>. " ++ "Fetch the instances of a typeclass, importing specified modules first." , process = fetchInstancesImporting >=> say } ] } -- | Nice little combinator used to throw away error messages from an Either -- and just keep a Maybe indicating the success of the computation. eitherToMaybe :: Either a b -> Maybe b eitherToMaybe = either (const Nothing) Just -- * Parsing -- -- | Parse an instance declaration. Sample inputs: -- > instance [ ] -- > instance (Monoid w) => Monad (Writer w) > instance ( State s ) -- instanceP :: ClassName -> CharParser st Instance instanceP cls = string "instance " *> (try constrained <|> unconstrained) *> skipMany space *> anyChar `manyTill` end where constrained = noneOf "=" `manyTill` string ("=> " ++ cls) unconstrained = string cls -- break on the "imported from" comment or a newline. end = void (try (string "--")) <|> eof -- | Wrapper for the instance parser. parseInstance :: ClassName -> String -> Maybe Instance parseInstance cls = fmap (strip isSpace) . eitherToMaybe . parse (instanceP cls) "GHCi output" -- | Split the input into a list of the instances, then run each instance -- through the parser. Collect successes. getInstances :: String -> ClassName -> [Instance] getInstances s cls ca n't trust those dodgy folk in # haskell = ["Couldn't find class `"++cls++"'. Try @instances-importing"] | otherwise = sort $ mapMaybe doParse (tail splut) where classFound = s =~ ("class.*" ++ cls ++ ".*where") splut = splitOn "instance" s -- splut being the past participle -- of 'to split', obviously. :) notOperator = all (\c -> or [ isAlpha c, isSpace c, c `elem` "()" ]) unbracket str | head str == '(' && last str == ')' && all (/=',') str && notOperator str && str /= "()" = init $ tail str | otherwise = str doParse = fmap unbracket . parseInstance cls . ("instance"++) -- * Delegation; interface with GHCi -- -- | The standard modules we ask GHCi to load. stdMdls :: [ModuleName] stdMdls = controls where monads = map ("Monad."++) [ "Cont", "Error", "Fix", "Reader", "RWS", "ST", "State", "Trans", "Writer" ] controls = map ("Control." ++) $ monads ++ ["Arrow"] -- | Main processing function for \@instances. Takes a class name and -- return a list of lines to output (which will actually only be one). fetchInstances :: MonadLB m => ClassName -> m String fetchInstances cls = fetchInstances' cls stdMdls -- | Main processing function for \@instances-importing. Takes the args, which -- are words'd. The all but the last argument are taken to be the modules to -- import, and the last is the typeclass whose instances we want to print. fetchInstancesImporting :: MonadLB m => String -> m String fetchInstancesImporting args = fetchInstances' cls mdls where args' = words args cls = last args' mdls = nub $ init args' ++ stdMdls -- | Interface with GHCi to get the input for the parser, then send it through -- the parser. fetchInstances' :: MonadLB m => String -> [ModuleName] -> m String fetchInstances' cls mdls = do load <- findL_hs let s = unlines $ map unwords [ [":l", load] , ":m" : "+" : mdls , [":i", cls] ] ghci <- getConfig ghciBinary (_, out, err) <- io $ readProcessWithExitCode ghci ["-ignore-dot-ghci","-fglasgow-exts"] s let is = getInstances out cls return $ if null is then err else intercalate ", " is
null
https://raw.githubusercontent.com/lambdabot/lambdabot/de01f362c7a8fc6f85c37e604168dcccb1283a0e/lambdabot-haskell-plugins/src/Lambdabot/Plugin/Haskell/Instances.hs
haskell
| Nice little combinator used to throw away error messages from an Either and just keep a Maybe indicating the success of the computation. * Parsing | Parse an instance declaration. Sample inputs: > instance (Monoid w) => Monad (Writer w) break on the "imported from" comment or a newline. | Wrapper for the instance parser. | Split the input into a list of the instances, then run each instance through the parser. Collect successes. splut being the past participle of 'to split', obviously. :) * Delegation; interface with GHCi | The standard modules we ask GHCi to load. | Main processing function for \@instances. Takes a class name and return a list of lines to output (which will actually only be one). | Main processing function for \@instances-importing. Takes the args, which are words'd. The all but the last argument are taken to be the modules to import, and the last is the typeclass whose instances we want to print. | Interface with GHCi to get the input for the parser, then send it through the parser.
| A module to output the instances of a typeclass . Some sample input\/output : > > @instances Monad > [ ] , ArrowMonad a , WriterT w m , , ReaderT r m , Reader r , > StateT s m , State s , RWST r w s m , RWS r w s , ErrorT e m , Either e , , Cont r , Maybe , ST s , IO > > > @instances Show > Float , Double , Integer , ST s a , [ a ] , ( a , b , c , d ) , ( a , b , c ) , ( a , b ) , > ( ) , Ordering , Maybe a , Int , Either a b , , > > > @instances - importing Text . Html Data . Tree Show > Float , Double , Tree a , HtmlTable , HtmlAttr , Html , , Integer , > ST s a , [ a ] , ( a , b , c , d ) , ( a , b , c ) , ( a , b ) , ( ) , Ordering , Maybe a , > Int Some sample input\/output: > lambdabot> @instances Monad > [], ArrowMonad a, WriterT w m, Writer w, ReaderT r m, Reader r, > StateT s m, State s, RWST r w s m, RWS r w s, ErrorT e m, Either e, > ContT r m, Cont r, Maybe, ST s, IO > > lambdabot> @instances Show > Float, Double, Integer, ST s a, [a], (a, b, c, d), (a, b, c), (a, b), > (), Ordering, Maybe a, Int, Either a b, Char, Bool > > lambdabot> @instances-importing Text.Html Data.Tree Show > Float, Double, Tree a, HtmlTable, HtmlAttr, Html, HotLink, Integer, > ST s a, [a], (a, b, c, d), (a, b, c), (a, b), (), Ordering, Maybe a, > Int -} module Lambdabot.Plugin.Haskell.Instances (instancesPlugin) where import Text.ParserCombinators.Parsec import Lambdabot.Config.Haskell import Lambdabot.Plugin import Lambdabot.Util import Lambdabot.Plugin.Haskell.Eval (findL_hs) import Control.Applicative ((*>)) import Control.Monad import Data.Char import Data.List import Data.List.Split import Data.Maybe import System.FilePath import System.Process import Text.Regex.TDFA type Instance = String type ClassName = String type ModuleName = String instancesPlugin :: Module () instancesPlugin = newModule { moduleCmds = return [ (command "instances") { help = say "instances <typeclass>. Fetch the instances of a typeclass." , process = fetchInstances >=> say } , (command "instances-importing") { help = say $ "instances-importing [<module> [<module> [<module...]]] <typeclass>. " ++ "Fetch the instances of a typeclass, importing specified modules first." , process = fetchInstancesImporting >=> say } ] } eitherToMaybe :: Either a b -> Maybe b eitherToMaybe = either (const Nothing) Just > instance [ ] > instance ( State s ) instanceP :: ClassName -> CharParser st Instance instanceP cls = string "instance " *> (try constrained <|> unconstrained) *> skipMany space *> anyChar `manyTill` end where constrained = noneOf "=" `manyTill` string ("=> " ++ cls) unconstrained = string cls end = void (try (string "--")) <|> eof parseInstance :: ClassName -> String -> Maybe Instance parseInstance cls = fmap (strip isSpace) . eitherToMaybe . parse (instanceP cls) "GHCi output" getInstances :: String -> ClassName -> [Instance] getInstances s cls ca n't trust those dodgy folk in # haskell = ["Couldn't find class `"++cls++"'. Try @instances-importing"] | otherwise = sort $ mapMaybe doParse (tail splut) where classFound = s =~ ("class.*" ++ cls ++ ".*where") notOperator = all (\c -> or [ isAlpha c, isSpace c, c `elem` "()" ]) unbracket str | head str == '(' && last str == ')' && all (/=',') str && notOperator str && str /= "()" = init $ tail str | otherwise = str doParse = fmap unbracket . parseInstance cls . ("instance"++) stdMdls :: [ModuleName] stdMdls = controls where monads = map ("Monad."++) [ "Cont", "Error", "Fix", "Reader", "RWS", "ST", "State", "Trans", "Writer" ] controls = map ("Control." ++) $ monads ++ ["Arrow"] fetchInstances :: MonadLB m => ClassName -> m String fetchInstances cls = fetchInstances' cls stdMdls fetchInstancesImporting :: MonadLB m => String -> m String fetchInstancesImporting args = fetchInstances' cls mdls where args' = words args cls = last args' mdls = nub $ init args' ++ stdMdls fetchInstances' :: MonadLB m => String -> [ModuleName] -> m String fetchInstances' cls mdls = do load <- findL_hs let s = unlines $ map unwords [ [":l", load] , ":m" : "+" : mdls , [":i", cls] ] ghci <- getConfig ghciBinary (_, out, err) <- io $ readProcessWithExitCode ghci ["-ignore-dot-ghci","-fglasgow-exts"] s let is = getInstances out cls return $ if null is then err else intercalate ", " is
96697d55c23e32b4528f33c532fec35627e5838a231f9fecef7041c8f6c4a055
bazurbat/chicken-scheme
makedist.scm
;;;; makedist.scm - Make distribution tarballs (use srfi-69 irregex srfi-1 setup-api) (define *release* #f) (define *help* #f) (define BUILDVERSION (with-input-from-file "buildversion" read)) (define *platform* (let ((sv (symbol->string (software-version)))) (cond ((irregex-match ".*bsd" sv) "bsd") (else (case (build-platform) ((mingw32) (if (equal? (get-environment-variable "MSYSTEM") "MINGW32") "mingw-msys" "mingw32")) ((msvc) "msvc") (else sv)))))) (define *make* (cond ((string=? "bsd" *platform*) "gmake") ((string=? "mingw32" *platform*) "mingw32-make") (else "make"))) (define (prefix dir . files) (if (null? files) (pathname-directory dir) (let ((files2 (map (cut make-pathname dir <>) (normalize files)))) (if (or (pair? (cdr files)) (pair? (car files))) files2 (car files2) ) ) ) ) (define (normalize fs) (delete-duplicates (map ->string (if (pair? fs) (flatten fs) (list fs) ) ) equal?) ) (define (release full?) (let* ((files (read-lines "distribution/manifest")) (distname (conc "chicken-" BUILDVERSION)) (distfiles (map (cut prefix distname <>) files)) (tgz (conc distname ".tar.gz"))) (run (rm -fr ,distname ,tgz)) (create-directory distname) (for-each (lambda (d) (let ((d (make-pathname distname d))) (unless (file-exists? d) (print "creating " d) (create-directory d 'with-parents)))) (delete-duplicates (filter-map prefix files) string=?)) (let ((missing (foldl (lambda (missing f) (cond ((file-exists? f) (run (cp -p ,(qs f) ,(qs (make-pathname distname f)))) missing) (else (cons f missing)))) '() files))) (unless (null? missing) (warning "files missing" missing) ) ) (run (tar cfz ,(conc distname ".tar.gz") ,distname)) (run (rm -fr ,distname)) ) ) (define (usage) (print "usage: makedist [-release] [-make PROGRAM] [--platform=PLATFORM] MAKEOPTION ...") (exit)) (define *makeargs* (let loop ((args (command-line-arguments))) (if (null? args) '() (let ((arg (car args))) (cond ((string=? "-release" arg) (set! *release* #t) (loop (cdr args))) ((string=? "-make" arg) (set! *make* (cadr args)) (loop (cddr args))) ((string=? "-help" arg) (usage)) ((string=? "-platform" arg) (set! *platform* (cadr args)) (loop (cddr args))) (else (cons arg (loop (cdr args))))))))) (run (,*make* -f ,(conc "Makefile." *platform*) distfiles ,@*makeargs*)) (release *release*)
null
https://raw.githubusercontent.com/bazurbat/chicken-scheme/f0c9d1fd8b68eb322e320e65ec40b0bf7d1b41dc/scripts/makedist.scm
scheme
makedist.scm - Make distribution tarballs
(use srfi-69 irregex srfi-1 setup-api) (define *release* #f) (define *help* #f) (define BUILDVERSION (with-input-from-file "buildversion" read)) (define *platform* (let ((sv (symbol->string (software-version)))) (cond ((irregex-match ".*bsd" sv) "bsd") (else (case (build-platform) ((mingw32) (if (equal? (get-environment-variable "MSYSTEM") "MINGW32") "mingw-msys" "mingw32")) ((msvc) "msvc") (else sv)))))) (define *make* (cond ((string=? "bsd" *platform*) "gmake") ((string=? "mingw32" *platform*) "mingw32-make") (else "make"))) (define (prefix dir . files) (if (null? files) (pathname-directory dir) (let ((files2 (map (cut make-pathname dir <>) (normalize files)))) (if (or (pair? (cdr files)) (pair? (car files))) files2 (car files2) ) ) ) ) (define (normalize fs) (delete-duplicates (map ->string (if (pair? fs) (flatten fs) (list fs) ) ) equal?) ) (define (release full?) (let* ((files (read-lines "distribution/manifest")) (distname (conc "chicken-" BUILDVERSION)) (distfiles (map (cut prefix distname <>) files)) (tgz (conc distname ".tar.gz"))) (run (rm -fr ,distname ,tgz)) (create-directory distname) (for-each (lambda (d) (let ((d (make-pathname distname d))) (unless (file-exists? d) (print "creating " d) (create-directory d 'with-parents)))) (delete-duplicates (filter-map prefix files) string=?)) (let ((missing (foldl (lambda (missing f) (cond ((file-exists? f) (run (cp -p ,(qs f) ,(qs (make-pathname distname f)))) missing) (else (cons f missing)))) '() files))) (unless (null? missing) (warning "files missing" missing) ) ) (run (tar cfz ,(conc distname ".tar.gz") ,distname)) (run (rm -fr ,distname)) ) ) (define (usage) (print "usage: makedist [-release] [-make PROGRAM] [--platform=PLATFORM] MAKEOPTION ...") (exit)) (define *makeargs* (let loop ((args (command-line-arguments))) (if (null? args) '() (let ((arg (car args))) (cond ((string=? "-release" arg) (set! *release* #t) (loop (cdr args))) ((string=? "-make" arg) (set! *make* (cadr args)) (loop (cddr args))) ((string=? "-help" arg) (usage)) ((string=? "-platform" arg) (set! *platform* (cadr args)) (loop (cddr args))) (else (cons arg (loop (cdr args))))))))) (run (,*make* -f ,(conc "Makefile." *platform*) distfiles ,@*makeargs*)) (release *release*)
3758920734913feaa71228a90ad96bd0335ce45deb2e92dbcaad089e8616e406
jvf/scalaris
rr_recon_stats.erl
2011 - 2012 Zuse Institute Berlin 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. @author < > %% @doc Replica Repair Reconciliation Statistics %% @end %% @version $Id$ -module(rr_recon_stats). -author(''). -vsn('$Id$'). -include("scalaris.hrl"). -include("record_helpers.hrl"). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Exported functions and types %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -export([new/1, new/2, inc/2, set/2, get/2, print/1]). -export_type([stats/0, status/0]). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Types %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -type status() :: wait | abort | finish. -record(rr_recon_stats, { session_id = ?required(rr_recon_stats, session_id) :: rrepair:session_id(), tree_size = {0,0,0} :: merkle_tree:mt_size(), tree_nodesCompared = 0 :: non_neg_integer(), tree_compareSkipped= 0 :: non_neg_integer(), tree_leavesSynced = 0 :: non_neg_integer(), p1e_phase1 = 0.0 :: float(), p1e_phase2 = 0.0 :: float(), in us in us rs_expected = 0 :: non_neg_integer(), %number of resolve expected requests status = wait :: status() }). -type stats() :: #rr_recon_stats{}. -type field_list1() :: [{tree_size, merkle_tree:mt_size()} | {tree_nodesCompared, non_neg_integer()} | {tree_compareSkipped, non_neg_integer()} | {tree_leavesSynced, non_neg_integer()} | {build_time, non_neg_integer()} | {recon_time, non_neg_integer()} | {rs_expected, non_neg_integer()}]. -type field_list2() :: [{status, status()} | {p1e_phase1, float()} | {p1e_phase2, float()}] | field_list1(). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% API Functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec new(rrepair:session_id()) -> stats(). new(SID) -> ?DBG_ASSERT(SID =/= null), #rr_recon_stats{session_id = SID}. -spec new(rrepair:session_id(), field_list2()) -> stats(). new(SID, KVList) -> set(KVList, #rr_recon_stats{session_id = SID}). % @doc increases the record field with name key by value -spec inc(field_list1(), Old::stats()) -> New::stats(). inc([], Stats) -> Stats; inc([{K, V} | L], Stats) -> NS = case K of tree_size -> {OldIn, OldLn, OldIt} = Stats#rr_recon_stats.tree_size, {IncIn, IncLn, IncIt} = V, X = {OldIn + IncIn, OldLn + IncLn, OldIt + IncIt}, Stats#rr_recon_stats{tree_size = X}; tree_nodesCompared -> X = V + Stats#rr_recon_stats.tree_nodesCompared, Stats#rr_recon_stats {tree_nodesCompared = X}; tree_leavesSynced -> X = V + Stats#rr_recon_stats.tree_leavesSynced, Stats#rr_recon_stats{tree_leavesSynced = X}; tree_compareSkipped -> X = V + Stats#rr_recon_stats.tree_compareSkipped, Stats#rr_recon_stats{tree_compareSkipped = X}; build_time -> X = V + Stats#rr_recon_stats.build_time, Stats#rr_recon_stats{build_time = X}; recon_time -> X = V + Stats#rr_recon_stats.recon_time, Stats#rr_recon_stats{recon_time = X}; rs_expected -> X = V + Stats#rr_recon_stats.rs_expected, Stats#rr_recon_stats{rs_expected = X} end, inc(L, NS). % @doc sets the value of record field with name of key to the given value -spec set(field_list2(), Old::stats()) -> New::stats(). set([], Stats) -> Stats; set([{K, V} | L], Stats) -> NS = case K of tree_size -> Stats#rr_recon_stats{tree_size = V}; tree_nodesCompared -> Stats#rr_recon_stats{tree_nodesCompared = V}; tree_leavesSynced -> Stats#rr_recon_stats{tree_leavesSynced = V}; tree_compareSkipped -> Stats#rr_recon_stats{tree_compareSkipped = V}; p1e_phase1 -> Stats#rr_recon_stats{p1e_phase1 = V}; p1e_phase2 -> Stats#rr_recon_stats{p1e_phase2 = V}; build_time -> Stats#rr_recon_stats{build_time = V}; recon_time -> Stats#rr_recon_stats{recon_time = V}; rs_expected -> Stats#rr_recon_stats{rs_expected = V}; status -> Stats#rr_recon_stats{status = V} end, set(L, NS). -spec get(session_id, stats()) -> rrepair:session_id(); (tree_size, stats()) -> merkle_tree:mt_size(); (tree_nodesCompared, stats()) -> non_neg_integer(); (tree_compareSkipped, stats())-> non_neg_integer(); (tree_leavesSynced, stats()) -> non_neg_integer(); (p1e_phase1 | p1e_phase2 | p1e_total, stats()) -> float(); (build_time, stats()) -> non_neg_integer(); (recon_time, stats()) -> non_neg_integer(); (rs_expected, stats()) -> non_neg_integer(); (status, stats()) -> status(). get(session_id , #rr_recon_stats{session_id = X}) -> X; get(tree_size , #rr_recon_stats{tree_size = X}) -> X; get(tree_nodesCompared , #rr_recon_stats{tree_nodesCompared = X}) -> X; get(tree_leavesSynced , #rr_recon_stats{tree_leavesSynced = X}) -> X; get(tree_compareSkipped, #rr_recon_stats{tree_compareSkipped = X}) -> X; get(p1e_phase1 , #rr_recon_stats{p1e_phase1 = X}) -> X; get(p1e_phase2 , #rr_recon_stats{p1e_phase2 = X}) -> X; get(build_time , #rr_recon_stats{build_time = X}) -> X; get(recon_time , #rr_recon_stats{recon_time = X}) -> X; get(rs_expected , #rr_recon_stats{rs_expected = X}) -> X; get(status , #rr_recon_stats{status = X}) -> X; get(p1e_total , #rr_recon_stats{p1e_phase1 = P1E_p1, p1e_phase2 = P1E_p2}) -> 1 - (1 - P1E_p1) * (1 - P1E_p2). -spec print(stats()) -> [any()]. print(Stats) -> StatsL = tl(erlang:tuple_to_list(Stats)), FieldNames = record_info(fields, rr_recon_stats), [rr_recon_stats, lists:zip(FieldNames, StatsL)].
null
https://raw.githubusercontent.com/jvf/scalaris/c069f44cf149ea6c69e24bdb08714bda242e7ee0/src/rrepair/rr_recon_stats.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. @doc Replica Repair Reconciliation Statistics @end @version $Id$ Exported functions and types Types number of resolve expected requests API Functions @doc increases the record field with name key by value @doc sets the value of record field with name of key to the given value
2011 - 2012 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author < > -module(rr_recon_stats). -author(''). -vsn('$Id$'). -include("scalaris.hrl"). -include("record_helpers.hrl"). -export([new/1, new/2, inc/2, set/2, get/2, print/1]). -export_type([stats/0, status/0]). -type status() :: wait | abort | finish. -record(rr_recon_stats, { session_id = ?required(rr_recon_stats, session_id) :: rrepair:session_id(), tree_size = {0,0,0} :: merkle_tree:mt_size(), tree_nodesCompared = 0 :: non_neg_integer(), tree_compareSkipped= 0 :: non_neg_integer(), tree_leavesSynced = 0 :: non_neg_integer(), p1e_phase1 = 0.0 :: float(), p1e_phase2 = 0.0 :: float(), in us in us status = wait :: status() }). -type stats() :: #rr_recon_stats{}. -type field_list1() :: [{tree_size, merkle_tree:mt_size()} | {tree_nodesCompared, non_neg_integer()} | {tree_compareSkipped, non_neg_integer()} | {tree_leavesSynced, non_neg_integer()} | {build_time, non_neg_integer()} | {recon_time, non_neg_integer()} | {rs_expected, non_neg_integer()}]. -type field_list2() :: [{status, status()} | {p1e_phase1, float()} | {p1e_phase2, float()}] | field_list1(). -spec new(rrepair:session_id()) -> stats(). new(SID) -> ?DBG_ASSERT(SID =/= null), #rr_recon_stats{session_id = SID}. -spec new(rrepair:session_id(), field_list2()) -> stats(). new(SID, KVList) -> set(KVList, #rr_recon_stats{session_id = SID}). -spec inc(field_list1(), Old::stats()) -> New::stats(). inc([], Stats) -> Stats; inc([{K, V} | L], Stats) -> NS = case K of tree_size -> {OldIn, OldLn, OldIt} = Stats#rr_recon_stats.tree_size, {IncIn, IncLn, IncIt} = V, X = {OldIn + IncIn, OldLn + IncLn, OldIt + IncIt}, Stats#rr_recon_stats{tree_size = X}; tree_nodesCompared -> X = V + Stats#rr_recon_stats.tree_nodesCompared, Stats#rr_recon_stats {tree_nodesCompared = X}; tree_leavesSynced -> X = V + Stats#rr_recon_stats.tree_leavesSynced, Stats#rr_recon_stats{tree_leavesSynced = X}; tree_compareSkipped -> X = V + Stats#rr_recon_stats.tree_compareSkipped, Stats#rr_recon_stats{tree_compareSkipped = X}; build_time -> X = V + Stats#rr_recon_stats.build_time, Stats#rr_recon_stats{build_time = X}; recon_time -> X = V + Stats#rr_recon_stats.recon_time, Stats#rr_recon_stats{recon_time = X}; rs_expected -> X = V + Stats#rr_recon_stats.rs_expected, Stats#rr_recon_stats{rs_expected = X} end, inc(L, NS). -spec set(field_list2(), Old::stats()) -> New::stats(). set([], Stats) -> Stats; set([{K, V} | L], Stats) -> NS = case K of tree_size -> Stats#rr_recon_stats{tree_size = V}; tree_nodesCompared -> Stats#rr_recon_stats{tree_nodesCompared = V}; tree_leavesSynced -> Stats#rr_recon_stats{tree_leavesSynced = V}; tree_compareSkipped -> Stats#rr_recon_stats{tree_compareSkipped = V}; p1e_phase1 -> Stats#rr_recon_stats{p1e_phase1 = V}; p1e_phase2 -> Stats#rr_recon_stats{p1e_phase2 = V}; build_time -> Stats#rr_recon_stats{build_time = V}; recon_time -> Stats#rr_recon_stats{recon_time = V}; rs_expected -> Stats#rr_recon_stats{rs_expected = V}; status -> Stats#rr_recon_stats{status = V} end, set(L, NS). -spec get(session_id, stats()) -> rrepair:session_id(); (tree_size, stats()) -> merkle_tree:mt_size(); (tree_nodesCompared, stats()) -> non_neg_integer(); (tree_compareSkipped, stats())-> non_neg_integer(); (tree_leavesSynced, stats()) -> non_neg_integer(); (p1e_phase1 | p1e_phase2 | p1e_total, stats()) -> float(); (build_time, stats()) -> non_neg_integer(); (recon_time, stats()) -> non_neg_integer(); (rs_expected, stats()) -> non_neg_integer(); (status, stats()) -> status(). get(session_id , #rr_recon_stats{session_id = X}) -> X; get(tree_size , #rr_recon_stats{tree_size = X}) -> X; get(tree_nodesCompared , #rr_recon_stats{tree_nodesCompared = X}) -> X; get(tree_leavesSynced , #rr_recon_stats{tree_leavesSynced = X}) -> X; get(tree_compareSkipped, #rr_recon_stats{tree_compareSkipped = X}) -> X; get(p1e_phase1 , #rr_recon_stats{p1e_phase1 = X}) -> X; get(p1e_phase2 , #rr_recon_stats{p1e_phase2 = X}) -> X; get(build_time , #rr_recon_stats{build_time = X}) -> X; get(recon_time , #rr_recon_stats{recon_time = X}) -> X; get(rs_expected , #rr_recon_stats{rs_expected = X}) -> X; get(status , #rr_recon_stats{status = X}) -> X; get(p1e_total , #rr_recon_stats{p1e_phase1 = P1E_p1, p1e_phase2 = P1E_p2}) -> 1 - (1 - P1E_p1) * (1 - P1E_p2). -spec print(stats()) -> [any()]. print(Stats) -> StatsL = tl(erlang:tuple_to_list(Stats)), FieldNames = record_info(fields, rr_recon_stats), [rr_recon_stats, lists:zip(FieldNames, StatsL)].
4fc6375d27ffced53faa8dd81f16962967b00a6f08ddc7c96abd97ba85339f46
facebook/flow
checkedSet.ml
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) Disjoint sets of checked files ( files which we not only parse but also merge ) * * Lazy mode : * Focused files - files which the user cares about . * Dependent files - files which directly or transitively depend on focused files * Dependency files - files on which Focused or Dependent files directly or transitively depend * * Non - lazy mode : * Focused files - Every checked file * Dependent files - Empty * Dependency files - Empty * * Lazy mode: * Focused files - files which the user cares about. * Dependent files - files which directly or transitively depend on focused files * Dependency files - files on which Focused or Dependent files directly or transitively depend * * Non-lazy mode: * Focused files - Every checked file * Dependent files - Empty * Dependency files - Empty *) open Utils_js (* A file foo.js can be focused, a dependent, and a dependency all at the same time. However, in * CheckedSet.t, we just keep track of its most important role. A focused file is more important * than a dependent file, which is more important than a dependency file *) type kind = | Focused | Dependent | Dependency type t = kind FilenameMap.t (* This uses polymorphic compare. Use caution if `kind` becomes a more complex type. *) let debug_equal = FilenameMap.equal ( = ) let combine a b = match (a, b) with | (Focused, _) | (_, Focused) -> Focused | (Dependent, _) | (_, Dependent) -> Dependent | _ -> Dependency let empty = FilenameMap.empty let is_empty = FilenameMap.is_empty let of_focused_list = List.fold_left (fun acc f -> FilenameMap.add f Focused acc) empty let cardinal = FilenameMap.cardinal let mem = FilenameMap.mem let add = let add_all files kind checked = Base.Option.value_map files ~f:(fun files -> FilenameSet.fold (fun f checked -> FilenameMap.add ~combine f kind checked) files checked) ~default:checked in fun ?focused ?dependents ?dependencies checked -> checked |> add_all focused Focused |> add_all dependents Dependent |> add_all dependencies Dependency let remove set_to_remove = FilenameMap.filter (fun k _ -> not (FilenameSet.mem k set_to_remove)) let fold f acc checked = FilenameMap.fold (fun k _ acc -> f acc k) checked acc let union = FilenameMap.union ~combine:(fun _ a b -> Some (combine a b)) (** [diff a b] removes from [a] every key which exists in [b] and which has an equal or higher kind in [b] than it does in [a], where Focused > Dependent > Dependency. So {[ diff { A: Focused, B: Focused, C: Dependency, D: Dependent } { A: Focused, B: Dependent, C: Dependent} = { B: Focused, D: Dependent } ]} *) let diff a b = FilenameMap.filter (fun k kind1 -> let kind2 = FilenameMap.find_opt k b in match (kind1, kind2) with | (_, None) -> true (* Key doesn't exist in b, so keep k around *) | (_, Some Focused) -> false (* Focused removes anything *) | (Focused, _) -> true (* Focused survives anything except Focused *) | (_, Some Dependent) -> false (* Dependent removes anything except Focused *) | (Dependent, Some Dependency) -> true (* Dependent survives Dependency *) | (Dependency, Some Dependency) -> false) (* Dependency removes Dependency *) a let filter ~f checked = FilenameMap.filter f checked let filter_into_set ~f checked = FilenameMap.fold (fun key kind acc -> if f kind then FilenameSet.add key acc else acc) checked FilenameSet.empty let partition ~(f : File_key.t -> kind -> bool) (checked : t) : t * t = FilenameMap.partition f checked let count ~f checked = FilenameMap.fold (fun _key kind acc -> if f kind then acc + 1 else acc) checked 0 Gives you a FilenameSet of all the checked files let all = filter_into_set ~f:(fun _ -> true) let is_focused kind = kind = Focused let is_dependent kind = kind = Dependent let is_dependency kind = kind = Dependency Gives you a FilenameSet of all the focused files let focused = filter_into_set ~f:is_focused let focused_cardinal = count ~f:is_focused Gives you a FilenameSet of all the dependent files let dependents = filter_into_set ~f:is_dependent let dependents_cardinal = count ~f:is_dependent Gives you a FilenameSet of all the dependency files let dependencies = filter_into_set ~f:is_dependency let dependencies_cardinal = count ~f:is_dependency let mem_kind ~f fn t = match FilenameMap.find_opt fn t with | Some kind -> f kind | None -> false let mem_focused = mem_kind ~f:is_focused let mem_dependent = mem_kind ~f:is_dependent let mem_dependency = mem_kind ~f:is_dependency (* Helper function for debugging *) let debug_to_string ?limit = let string_of_set set = let files = Utils_js.FilenameSet.elements set |> Base.List.map ~f:(fun f -> spf "\"%s\"" (File_key.to_string f)) in let files = match limit with | None -> files | Some n -> ListUtils.first_upto_n n (fun t -> Some (spf "[shown %d/%d]" n t)) files in String.concat "\n" files in fun checked -> Printf.sprintf "Focused:\n%s\nDependents:\n%s\nDependencies:\n%s" (checked |> focused |> string_of_set) (checked |> dependents |> string_of_set) (checked |> dependencies |> string_of_set) let debug_counts_to_string checked = let (focused, dependents, dependencies) = FilenameMap.fold (fun _ kind (focused, dependents, dependencies) -> match kind with | Focused -> (focused + 1, dependents, dependencies) | Dependent -> (focused, dependents + 1, dependencies) | Dependency -> (focused, dependents, dependencies + 1)) checked (0, 0, 0) in Printf.sprintf "Focused: %d, Dependents: %d, Dependencies: %d" focused dependents dependencies
null
https://raw.githubusercontent.com/facebook/flow/741104e69c43057ebd32804dd6bcc1b5e97548ea/src/common/utils/checked_set/checkedSet.ml
ocaml
A file foo.js can be focused, a dependent, and a dependency all at the same time. However, in * CheckedSet.t, we just keep track of its most important role. A focused file is more important * than a dependent file, which is more important than a dependency file This uses polymorphic compare. Use caution if `kind` becomes a more complex type. * [diff a b] removes from [a] every key which exists in [b] and which has an equal or higher kind in [b] than it does in [a], where Focused > Dependent > Dependency. So {[ diff { A: Focused, B: Focused, C: Dependency, D: Dependent } { A: Focused, B: Dependent, C: Dependent} = { B: Focused, D: Dependent } ]} Key doesn't exist in b, so keep k around Focused removes anything Focused survives anything except Focused Dependent removes anything except Focused Dependent survives Dependency Dependency removes Dependency Helper function for debugging
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) Disjoint sets of checked files ( files which we not only parse but also merge ) * * Lazy mode : * Focused files - files which the user cares about . * Dependent files - files which directly or transitively depend on focused files * Dependency files - files on which Focused or Dependent files directly or transitively depend * * Non - lazy mode : * Focused files - Every checked file * Dependent files - Empty * Dependency files - Empty * * Lazy mode: * Focused files - files which the user cares about. * Dependent files - files which directly or transitively depend on focused files * Dependency files - files on which Focused or Dependent files directly or transitively depend * * Non-lazy mode: * Focused files - Every checked file * Dependent files - Empty * Dependency files - Empty *) open Utils_js type kind = | Focused | Dependent | Dependency type t = kind FilenameMap.t let debug_equal = FilenameMap.equal ( = ) let combine a b = match (a, b) with | (Focused, _) | (_, Focused) -> Focused | (Dependent, _) | (_, Dependent) -> Dependent | _ -> Dependency let empty = FilenameMap.empty let is_empty = FilenameMap.is_empty let of_focused_list = List.fold_left (fun acc f -> FilenameMap.add f Focused acc) empty let cardinal = FilenameMap.cardinal let mem = FilenameMap.mem let add = let add_all files kind checked = Base.Option.value_map files ~f:(fun files -> FilenameSet.fold (fun f checked -> FilenameMap.add ~combine f kind checked) files checked) ~default:checked in fun ?focused ?dependents ?dependencies checked -> checked |> add_all focused Focused |> add_all dependents Dependent |> add_all dependencies Dependency let remove set_to_remove = FilenameMap.filter (fun k _ -> not (FilenameSet.mem k set_to_remove)) let fold f acc checked = FilenameMap.fold (fun k _ acc -> f acc k) checked acc let union = FilenameMap.union ~combine:(fun _ a b -> Some (combine a b)) let diff a b = FilenameMap.filter (fun k kind1 -> let kind2 = FilenameMap.find_opt k b in match (kind1, kind2) with | (Dependency, Some Dependency) -> false) a let filter ~f checked = FilenameMap.filter f checked let filter_into_set ~f checked = FilenameMap.fold (fun key kind acc -> if f kind then FilenameSet.add key acc else acc) checked FilenameSet.empty let partition ~(f : File_key.t -> kind -> bool) (checked : t) : t * t = FilenameMap.partition f checked let count ~f checked = FilenameMap.fold (fun _key kind acc -> if f kind then acc + 1 else acc) checked 0 Gives you a FilenameSet of all the checked files let all = filter_into_set ~f:(fun _ -> true) let is_focused kind = kind = Focused let is_dependent kind = kind = Dependent let is_dependency kind = kind = Dependency Gives you a FilenameSet of all the focused files let focused = filter_into_set ~f:is_focused let focused_cardinal = count ~f:is_focused Gives you a FilenameSet of all the dependent files let dependents = filter_into_set ~f:is_dependent let dependents_cardinal = count ~f:is_dependent Gives you a FilenameSet of all the dependency files let dependencies = filter_into_set ~f:is_dependency let dependencies_cardinal = count ~f:is_dependency let mem_kind ~f fn t = match FilenameMap.find_opt fn t with | Some kind -> f kind | None -> false let mem_focused = mem_kind ~f:is_focused let mem_dependent = mem_kind ~f:is_dependent let mem_dependency = mem_kind ~f:is_dependency let debug_to_string ?limit = let string_of_set set = let files = Utils_js.FilenameSet.elements set |> Base.List.map ~f:(fun f -> spf "\"%s\"" (File_key.to_string f)) in let files = match limit with | None -> files | Some n -> ListUtils.first_upto_n n (fun t -> Some (spf "[shown %d/%d]" n t)) files in String.concat "\n" files in fun checked -> Printf.sprintf "Focused:\n%s\nDependents:\n%s\nDependencies:\n%s" (checked |> focused |> string_of_set) (checked |> dependents |> string_of_set) (checked |> dependencies |> string_of_set) let debug_counts_to_string checked = let (focused, dependents, dependencies) = FilenameMap.fold (fun _ kind (focused, dependents, dependencies) -> match kind with | Focused -> (focused + 1, dependents, dependencies) | Dependent -> (focused, dependents + 1, dependencies) | Dependency -> (focused, dependents, dependencies + 1)) checked (0, 0, 0) in Printf.sprintf "Focused: %d, Dependents: %d, Dependencies: %d" focused dependents dependencies
99a4bc3179a046486c3c38ebf1bdd0c1b6c03d8ce641cd6a9f729a7114b44bff
ktakashi/sagittarius-scheme
convert.scm
-*- mode : scheme ; coding : utf-8 -*- ;;; ;;; text/markdown/convert.scm - Converter for parsed markdown ;;; Copyright ( c ) 2010 - 2015 < > ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; #!nounbound (library (text markdown convert) (export markdown-sexp->sxml markdown-sexp->string) (import (rnrs) (match) (sagittarius) (sagittarius control) ;; for push (srfi :1 lists) (srfi :13 strings) (srfi :26 cut) (text sxml serializer) (text sxml tools)) ;; or should we make <ast> from the beginning? ;; ;; structure of input sexp ;; :doc ;; - :blockquote ;; - :verbatim ;; - :note ;; - :reference ;; - :line ;; - :header ;; - :ordered-list ;; - :bullet-list ;; - :paragraph ;; - :plain ;; ;; - :html-block - not yet ;; ;; - :style-block - not yet First we need to collect : reference to make link work properly and check ;; the validity. Second convert to sxml ( shtml ) ;; style keyword arguments must be alist with these structure keyword and ;; detail keywords (ex :inline) to specify its style. (define (markdown-sexp->sxml sexp :key (style #f) ;; for the top most (class #f) (no-reference #t) (no-notes #f) :allow-other-keys attributes) ;; under the :doc (define (collect-reference&notes sexp) (let loop ((sexp sexp) (acc '()) (ref '()) (notes '())) (cond ((null? sexp) (values (reverse! acc) ref notes)) ((and (pair? (car sexp)) (keyword? (caar sexp))) (case (caar sexp) ((:header :blockquote :line :html-block :verbatim :ordered-list :bullet-list :paragraph :plain) (loop (cdr sexp) (cons (car sexp) acc) ref notes)) ((:reference) (loop (cdr sexp) acc (cons (car sexp) ref) notes)) ((:note) (loop (cdr sexp) acc ref (cons (car sexp) notes))) (else (assertion-violation 'markdown-sexp->sxml "invalid keyword in the given list" (caar sexp) sexp)))) (else ;; invalid list (assertion-violation 'markdown-sexp->sxml "invalid markdown list" sexp))))) (define (alist->attr alist) (let loop ((alist alist) (r '())) (cond ((null? alist) (reverse! r)) ((and (string? (caar alist)) (string? (cdar alist))) (loop (cdr alist) (cons (list (string->symbol (caar alist)) (cdar alist)) r))) (else (assertion-violation 'markdown-sexp->sxml "invalid html attribute, must be alist of strings" alist))))) (unless (and (pair? sexp) (eq? (car sexp) :doc)) (assertion-violation 'markdown-sexp->sxml "invalid keyword in the given list" (car sexp) sexp)) (let-values (((sexp refs notes) (collect-reference&notes (cdr sexp)))) (define (lookup-reference ref) (cond ((assoc ref refs) => cdr) (else (assertion-violation 'markdown-sexp->sxml "invalid reference" ref sexp)))) (define (get-attribute key) (cond ((get-keyword key attributes #f) => (cut append '(@) <>)) (else '(@)))) (define note-prefix "fnref_") (define sup-prefix "fn_") (define note-refs '()) (define (find-note ref) (let loop ((notes notes)) (if (null? notes) '("") (let ((note (car notes))) (if (string=? (cadr (cadr note)) ref) (cddr note) (loop (cdr notes))))))) (define (detail->sxml sexp) (define (strip note) (let loop ((note note) (r '())) (if (null? note) (string-concatenate (reverse! r)) (let ((e (car note))) (cond ((string? e) (loop (cdr note) (cons e r))) ((eq? e :eol) (loop (cdr note) (cons "\n" r))) (else (case (car e) ((:label :code) (loop (cdr note) (cons (cadr e) r))) ((:link) (loop (cdr note) (cons (cadr (cadr e)) r))) ((:emph :strong) (loop (cdr note) (cons (strip (cdr e)) r))) ;; ignore (else (loop (cdr note) r))))))))) inlines ;; :eol ;; :link : emph ;; :strong ;; :image ;; :link ;; :note-ref TODO attribute (let loop ((sexp sexp) (acc '())) (define (gen-sup count ref note) `(sub (@ (id ,(string-append note-prefix ref))) (a (@ (href ,(string-append "#" sup-prefix ref)) (title ,(strip note))) ,(number->string (+ count 1))))) (match sexp (() (reverse! acc)) ;; :label is sort of special we just need its content (((:label str ...) . rest) (loop rest (cons `(span (@) ,@(detail->sxml str)) acc))) : image can be 2 pattern , one is with link ;; otherone is just a label. (((:image (:link (:label label ...) source title)) . rest) (loop rest (cons `(img (@ (src ,(string-trim-both source)) (alt ,(strip label)) (title ,title))) acc))) (((:image (:label label ...)) . rest) (loop rest (cons (apply string-append "!" label) acc))) (((:link (:label label ...) source title) . rest) (loop rest (cons `(a (@ (href ,(string-trim-both source)) (title ,(if (string-null? title) (strip label) title))) ,@(detail->sxml label)) acc))) (((:code code) . rest) (loop rest (cons `(code ,code) acc))) (((:emph code maybe ...) . rest) (loop rest (cons `(em (@) ,code ,@(detail->sxml maybe)) acc))) (((:strong code maybe ...) . rest) (loop rest (cons `(strong (@) ,code ,@(detail->sxml maybe)) acc))) (((:strike code maybe ...) . rest) (loop rest (cons `(del (@) ,code ,@(detail->sxml maybe)) acc))) ((:eol . rest) ;; this emits a bit cleaner HTML. (if (null? rest) (loop rest acc) (loop rest (cons "\n" acc)))) (((:item item ...) . rest) (loop rest (cons `(li ,(get-attribute :item) ,@(detail->sxml item)) acc))) (((:note-ref ref) . rest) (let ((count (length note-refs)) (note (find-note ref))) (push! note-refs (cons ref count)) (loop rest (cons (gen-sup count ref note) acc)))) (((:note note ...) . rest) (let ((count (length note-refs)) (ref (symbol->string (gensym)))) (push! note-refs (cons ref count)) (push! notes (cons ref note)) (loop rest (cons (gen-sup count ref note) acc)))) (((? string? s) . rest) ;; explicitly add newline (loop rest (cons s acc))) ;; HTML entity ((('& entity) . rest) (loop rest (cons (car sexp) acc))) (_ (assertion-violation 'markdown-sexp->sxml "invalid inline sexp form" sexp))))) (define (gen-notes notes) (define (format-notes notes) (map (lambda (note) (cons (cadr (cadr note)) (cddr note))) notes)) (define (order-notes notes) (list-sort (lambda (note-a note-b) (let ((a (assoc (car note-a) note-refs)) (b (assoc (car note-b) note-refs))) (< (cdr b) (cdr a)))) notes)) (define (gen notes) (fold (lambda (note acc) (let ((ref (car note)) (content (cdr note))) (cons `(li ,(append (get-attribute :note) `((id ,(string-append sup-prefix ref)))) ,@(detail->sxml content) (a (@ (href ,(string-append "#" note-prefix ref))) ".")) acc))) '() notes)) (if no-notes '() (let ((notes (gen (order-notes (format-notes notes))))) (if (null? notes) notes `((ol (@ (id "notes")) ,(get-attribute :notes) ,@notes)))))) (define (gen-reference refs) (define (gen refs) (fold (lambda (ref acc) (match ref ((:reference (:label label) source title) (cons `(div ,(get-attribute :reference) ,(string-append "[" label "]: " source " '" title "'")) acc)) (_ acc))) '() refs)) (if no-reference '() (let ((refs (gen refs))) (if (null? refs) '() `((div ,(append (get-attribute :references) '((id "references"))) ,@refs)))))) TODO refactor (define (rec sexp in-html?) (let loop ((sexp sexp) (acc '())) ;; TODO add style (match sexp (() (if in-html? (reverse! acc) `(div (@ ,@(let ((s style) (c class)) (cond ((and s c) `((style ,s) (class ,c))) (s `((style ,s))) (c `((class ,c))) (else '())))) ,@(reverse! acc) ,@(gen-reference refs) ,@(gen-notes notes)))) (((:header (? keyword? type) . content) . rest) (loop (cdr sexp) (cons `(,(keyword->symbol type) ,(let ((try (get-attribute type))) (if (null? try) (get-attribute :header) try)) ,@(detail->sxml content)) acc))) (((:blockquote . content) . rest) (loop rest (cons `(blockquote ,(get-attribute :blockquote) ,@(detail->sxml content)) acc))) (((:line) . rest) (loop (cdr sexp) (cons `(hr ,(get-attribute :line)) acc))) (((:html-block content) . rest) assume it 's SXML style (loop rest (cons content acc))) (((:paragraph . content) . rest) (loop rest (cons `(p ,(get-attribute :paragraph) ,@(detail->sxml content)) acc))) ;; should we handle plain the same as paragraph? (((:plain . content) . rest) (loop rest (cons `(p ,(get-attribute :plain) ,@(detail->sxml content)) acc))) (((:bullet-list . items) . rest) (loop rest (cons `(ul ,(get-attribute :bullet-list) ,@(detail->sxml items)) acc))) (((:ordered-list . items) . rest) (loop rest (cons `(ol ,(get-attribute :ordered-list) ,@(detail->sxml items)) acc))) (((:verbatim . code) . rest) ;; we need special treat for this (loop rest (cons `(pre ,(get-attribute :verbatim) ,@code) acc))) ;; for block html's content (((? string? text) . rest) (loop rest (cons text acc))) (_ (assertion-violation 'markdown-sexp->sxml "invalid block sexp form" sexp)) ))) (rec sexp #f) )) (define (markdown-sexp->string sexp :key (no-indent #f) :allow-other-keys opts) (let ((sxml (apply markdown-sexp->sxml sexp opts))) (if no-indent (srl:sxml->html-noindent sxml) (srl:sxml->html sxml)))) )
null
https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/f3fe8ea86ec4f760af45d9ac055163b9146677f7/sitelib/text/markdown/convert.scm
scheme
coding : utf-8 -*- text/markdown/convert.scm - Converter for parsed markdown Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. for push or should we make <ast> from the beginning? structure of input sexp :doc - :blockquote - :verbatim - :note - :reference - :line - :header - :ordered-list - :bullet-list - :paragraph - :plain ;; - :html-block - not yet ;; - :style-block - not yet the validity. style keyword arguments must be alist with these structure keyword and detail keywords (ex :inline) to specify its style. for the top most under the :doc invalid list ignore :eol :link :strong :image :link :note-ref :label is sort of special we just need its content otherone is just a label. this emits a bit cleaner HTML. explicitly add newline HTML entity TODO add style should we handle plain the same as paragraph? we need special treat for this for block html's content
Copyright ( c ) 2010 - 2015 < > " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING #!nounbound (library (text markdown convert) (export markdown-sexp->sxml markdown-sexp->string) (import (rnrs) (match) (sagittarius) (srfi :1 lists) (srfi :13 strings) (srfi :26 cut) (text sxml serializer) (text sxml tools)) First we need to collect : reference to make link work properly and check Second convert to sxml ( shtml ) (class #f) (no-reference #t) (no-notes #f) :allow-other-keys attributes) (define (collect-reference&notes sexp) (let loop ((sexp sexp) (acc '()) (ref '()) (notes '())) (cond ((null? sexp) (values (reverse! acc) ref notes)) ((and (pair? (car sexp)) (keyword? (caar sexp))) (case (caar sexp) ((:header :blockquote :line :html-block :verbatim :ordered-list :bullet-list :paragraph :plain) (loop (cdr sexp) (cons (car sexp) acc) ref notes)) ((:reference) (loop (cdr sexp) acc (cons (car sexp) ref) notes)) ((:note) (loop (cdr sexp) acc ref (cons (car sexp) notes))) (else (assertion-violation 'markdown-sexp->sxml "invalid keyword in the given list" (caar sexp) sexp)))) (else (assertion-violation 'markdown-sexp->sxml "invalid markdown list" sexp))))) (define (alist->attr alist) (let loop ((alist alist) (r '())) (cond ((null? alist) (reverse! r)) ((and (string? (caar alist)) (string? (cdar alist))) (loop (cdr alist) (cons (list (string->symbol (caar alist)) (cdar alist)) r))) (else (assertion-violation 'markdown-sexp->sxml "invalid html attribute, must be alist of strings" alist))))) (unless (and (pair? sexp) (eq? (car sexp) :doc)) (assertion-violation 'markdown-sexp->sxml "invalid keyword in the given list" (car sexp) sexp)) (let-values (((sexp refs notes) (collect-reference&notes (cdr sexp)))) (define (lookup-reference ref) (cond ((assoc ref refs) => cdr) (else (assertion-violation 'markdown-sexp->sxml "invalid reference" ref sexp)))) (define (get-attribute key) (cond ((get-keyword key attributes #f) => (cut append '(@) <>)) (else '(@)))) (define note-prefix "fnref_") (define sup-prefix "fn_") (define note-refs '()) (define (find-note ref) (let loop ((notes notes)) (if (null? notes) '("") (let ((note (car notes))) (if (string=? (cadr (cadr note)) ref) (cddr note) (loop (cdr notes))))))) (define (detail->sxml sexp) (define (strip note) (let loop ((note note) (r '())) (if (null? note) (string-concatenate (reverse! r)) (let ((e (car note))) (cond ((string? e) (loop (cdr note) (cons e r))) ((eq? e :eol) (loop (cdr note) (cons "\n" r))) (else (case (car e) ((:label :code) (loop (cdr note) (cons (cadr e) r))) ((:link) (loop (cdr note) (cons (cadr (cadr e)) r))) ((:emph :strong) (loop (cdr note) (cons (strip (cdr e)) r))) (else (loop (cdr note) r))))))))) inlines : emph TODO attribute (let loop ((sexp sexp) (acc '())) (define (gen-sup count ref note) `(sub (@ (id ,(string-append note-prefix ref))) (a (@ (href ,(string-append "#" sup-prefix ref)) (title ,(strip note))) ,(number->string (+ count 1))))) (match sexp (() (reverse! acc)) (((:label str ...) . rest) (loop rest (cons `(span (@) ,@(detail->sxml str)) acc))) : image can be 2 pattern , one is with link (((:image (:link (:label label ...) source title)) . rest) (loop rest (cons `(img (@ (src ,(string-trim-both source)) (alt ,(strip label)) (title ,title))) acc))) (((:image (:label label ...)) . rest) (loop rest (cons (apply string-append "!" label) acc))) (((:link (:label label ...) source title) . rest) (loop rest (cons `(a (@ (href ,(string-trim-both source)) (title ,(if (string-null? title) (strip label) title))) ,@(detail->sxml label)) acc))) (((:code code) . rest) (loop rest (cons `(code ,code) acc))) (((:emph code maybe ...) . rest) (loop rest (cons `(em (@) ,code ,@(detail->sxml maybe)) acc))) (((:strong code maybe ...) . rest) (loop rest (cons `(strong (@) ,code ,@(detail->sxml maybe)) acc))) (((:strike code maybe ...) . rest) (loop rest (cons `(del (@) ,code ,@(detail->sxml maybe)) acc))) ((:eol . rest) (if (null? rest) (loop rest acc) (loop rest (cons "\n" acc)))) (((:item item ...) . rest) (loop rest (cons `(li ,(get-attribute :item) ,@(detail->sxml item)) acc))) (((:note-ref ref) . rest) (let ((count (length note-refs)) (note (find-note ref))) (push! note-refs (cons ref count)) (loop rest (cons (gen-sup count ref note) acc)))) (((:note note ...) . rest) (let ((count (length note-refs)) (ref (symbol->string (gensym)))) (push! note-refs (cons ref count)) (push! notes (cons ref note)) (loop rest (cons (gen-sup count ref note) acc)))) (((? string? s) . rest) (loop rest (cons s acc))) ((('& entity) . rest) (loop rest (cons (car sexp) acc))) (_ (assertion-violation 'markdown-sexp->sxml "invalid inline sexp form" sexp))))) (define (gen-notes notes) (define (format-notes notes) (map (lambda (note) (cons (cadr (cadr note)) (cddr note))) notes)) (define (order-notes notes) (list-sort (lambda (note-a note-b) (let ((a (assoc (car note-a) note-refs)) (b (assoc (car note-b) note-refs))) (< (cdr b) (cdr a)))) notes)) (define (gen notes) (fold (lambda (note acc) (let ((ref (car note)) (content (cdr note))) (cons `(li ,(append (get-attribute :note) `((id ,(string-append sup-prefix ref)))) ,@(detail->sxml content) (a (@ (href ,(string-append "#" note-prefix ref))) ".")) acc))) '() notes)) (if no-notes '() (let ((notes (gen (order-notes (format-notes notes))))) (if (null? notes) notes `((ol (@ (id "notes")) ,(get-attribute :notes) ,@notes)))))) (define (gen-reference refs) (define (gen refs) (fold (lambda (ref acc) (match ref ((:reference (:label label) source title) (cons `(div ,(get-attribute :reference) ,(string-append "[" label "]: " source " '" title "'")) acc)) (_ acc))) '() refs)) (if no-reference '() (let ((refs (gen refs))) (if (null? refs) '() `((div ,(append (get-attribute :references) '((id "references"))) ,@refs)))))) TODO refactor (define (rec sexp in-html?) (let loop ((sexp sexp) (acc '())) (match sexp (() (if in-html? (reverse! acc) `(div (@ ,@(let ((s style) (c class)) (cond ((and s c) `((style ,s) (class ,c))) (s `((style ,s))) (c `((class ,c))) (else '())))) ,@(reverse! acc) ,@(gen-reference refs) ,@(gen-notes notes)))) (((:header (? keyword? type) . content) . rest) (loop (cdr sexp) (cons `(,(keyword->symbol type) ,(let ((try (get-attribute type))) (if (null? try) (get-attribute :header) try)) ,@(detail->sxml content)) acc))) (((:blockquote . content) . rest) (loop rest (cons `(blockquote ,(get-attribute :blockquote) ,@(detail->sxml content)) acc))) (((:line) . rest) (loop (cdr sexp) (cons `(hr ,(get-attribute :line)) acc))) (((:html-block content) . rest) assume it 's SXML style (loop rest (cons content acc))) (((:paragraph . content) . rest) (loop rest (cons `(p ,(get-attribute :paragraph) ,@(detail->sxml content)) acc))) (((:plain . content) . rest) (loop rest (cons `(p ,(get-attribute :plain) ,@(detail->sxml content)) acc))) (((:bullet-list . items) . rest) (loop rest (cons `(ul ,(get-attribute :bullet-list) ,@(detail->sxml items)) acc))) (((:ordered-list . items) . rest) (loop rest (cons `(ol ,(get-attribute :ordered-list) ,@(detail->sxml items)) acc))) (((:verbatim . code) . rest) (loop rest (cons `(pre ,(get-attribute :verbatim) ,@code) acc))) (((? string? text) . rest) (loop rest (cons text acc))) (_ (assertion-violation 'markdown-sexp->sxml "invalid block sexp form" sexp)) ))) (rec sexp #f) )) (define (markdown-sexp->string sexp :key (no-indent #f) :allow-other-keys opts) (let ((sxml (apply markdown-sexp->sxml sexp opts))) (if no-indent (srl:sxml->html-noindent sxml) (srl:sxml->html sxml)))) )
2ddcdf3e0ade4a2268bf00b73482dc57a365d61cd631da8c4443121c34b0f873
nklein/Woolly
label.lisp
(in-package #:woolly) (sheeple:defproto =label= (=widget=) (label)) (sheeple:defreply sheeple:init-object :after ((ll =label=) &key label &allow-other-keys) (set? (label ll) label))
null
https://raw.githubusercontent.com/nklein/Woolly/f18b5d5dc28b04e6a194757d7ebc1f03bb6ebd4d/woolly/label.lisp
lisp
(in-package #:woolly) (sheeple:defproto =label= (=widget=) (label)) (sheeple:defreply sheeple:init-object :after ((ll =label=) &key label &allow-other-keys) (set? (label ll) label))
9b75a65863a5b488901d5d70e07e35419c76e425d156005949914256e937f3b0
narkisr-deprecated/core
physical.clj
(ns re-core.test.physical "Physical instance creation" (:import clojure.lang.ExceptionInfo) (:require physical.provider [flatland.useful.map :refer (dissoc-in*)] [re-core.fixtures.core :refer (with-m?)] [re-core.model :refer (vconstruct)] [re-core.fixtures.data :refer (redis-physical)]) (:use midje.sweet)) (fact "basic physical machine instance creation" (vconstruct redis-physical) => truthy (vconstruct (dissoc-in* redis-physical [:physical :mac])) => (throws ExceptionInfo (with-m? {:interface {:mac "must be present"}})))
null
https://raw.githubusercontent.com/narkisr-deprecated/core/85b4a768ef4b3a4eae86695bce36d270dd51dbae/test/re_core/test/physical.clj
clojure
(ns re-core.test.physical "Physical instance creation" (:import clojure.lang.ExceptionInfo) (:require physical.provider [flatland.useful.map :refer (dissoc-in*)] [re-core.fixtures.core :refer (with-m?)] [re-core.model :refer (vconstruct)] [re-core.fixtures.data :refer (redis-physical)]) (:use midje.sweet)) (fact "basic physical machine instance creation" (vconstruct redis-physical) => truthy (vconstruct (dissoc-in* redis-physical [:physical :mac])) => (throws ExceptionInfo (with-m? {:interface {:mac "must be present"}})))
b381c180c558c80304dbaf56ce7599febab0daa2491a988dfccc567f877a514c
binghe/fm-plugin-tools
deliver.lisp
-*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*- $ Header : /usr / local / cvsrep / regex - plugin / deliver.lisp , v 1.10 2008/01/08 01:09:25 edi Exp $ Copyright ( c ) 2006 - 2008 , Dr. and Dr. . All rights reserved . ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; This is an abridged version of the delivery script that comes with ;;; FM-PLUGIN-TOOLS. (in-package :cl-user) (defvar *asdf-system* :fm-plugin-regex "The ASDF system which contains the code for the plug-in. It should depend on FM-PLUGIN-TOOLS.") (defvar *deliver-level* 5 "Delivery level for the delivered DLL.") (defvar *template* (merge-pathnames "RegexPlugIn.fmplugin/" *load-pathname*)) ;;; Use the "original" delivery script for the rest of the work. ;;; (Adapt the path to match your local setup. Also, don't forget to ;;; adapt the paths in the delivery file referenced below as well!) (defvar *deliver-script* (merge-pathnames "../deliver.lisp" *load-pathname*)) (load *deliver-script*)
null
https://raw.githubusercontent.com/binghe/fm-plugin-tools/ddb970a38b9a6fb44e9fb49a3ef74a4d17ac8738/regex-plugin/deliver.lisp
lisp
Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This is an abridged version of the delivery script that comes with FM-PLUGIN-TOOLS. Use the "original" delivery script for the rest of the work. (Adapt the path to match your local setup. Also, don't forget to adapt the paths in the delivery file referenced below as well!)
$ Header : /usr / local / cvsrep / regex - plugin / deliver.lisp , v 1.10 2008/01/08 01:09:25 edi Exp $ Copyright ( c ) 2006 - 2008 , Dr. and Dr. . All rights reserved . OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , (in-package :cl-user) (defvar *asdf-system* :fm-plugin-regex "The ASDF system which contains the code for the plug-in. It should depend on FM-PLUGIN-TOOLS.") (defvar *deliver-level* 5 "Delivery level for the delivered DLL.") (defvar *template* (merge-pathnames "RegexPlugIn.fmplugin/" *load-pathname*)) (defvar *deliver-script* (merge-pathnames "../deliver.lisp" *load-pathname*)) (load *deliver-script*)
c6cd10a94960192c7445b441a373bbc9ee87c00cb2b0815d02d4c6a06138fdc8
ninenines/cowboy
charsets_provided_empty_h.erl
%% This module has a text and non-text media type, %% but provides no charset. All requests will result in a 406 not acceptable . -module(charsets_provided_empty_h). -export([init/2]). -export([content_types_provided/2]). -export([charsets_provided/2]). -export([get_text_plain/2]). -export([get_application_json/2]). init(Req, Opts) -> {cowboy_rest, Req, Opts}. content_types_provided(Req, State) -> {[ {{<<"text">>, <<"plain">>, []}, get_text_plain}, {{<<"application">>, <<"json">>, []}, get_application_json} ], Req, State}. charsets_provided(Req, State) -> {[], Req, State}. get_text_plain(Req, State) -> {<<"This is REST!">>, Req, State}. get_application_json(Req, State) -> {<<"{\"hello\": \"rest\"}">>, Req, State}.
null
https://raw.githubusercontent.com/ninenines/cowboy/8795233c57f1f472781a22ffbf186ce38cc5b049/test/handlers/charsets_provided_empty_h.erl
erlang
This module has a text and non-text media type, but provides no charset. All requests will result
in a 406 not acceptable . -module(charsets_provided_empty_h). -export([init/2]). -export([content_types_provided/2]). -export([charsets_provided/2]). -export([get_text_plain/2]). -export([get_application_json/2]). init(Req, Opts) -> {cowboy_rest, Req, Opts}. content_types_provided(Req, State) -> {[ {{<<"text">>, <<"plain">>, []}, get_text_plain}, {{<<"application">>, <<"json">>, []}, get_application_json} ], Req, State}. charsets_provided(Req, State) -> {[], Req, State}. get_text_plain(Req, State) -> {<<"This is REST!">>, Req, State}. get_application_json(Req, State) -> {<<"{\"hello\": \"rest\"}">>, Req, State}.
6f7015683d2e135724fbcddc0070588856c1d99995cbc3e123ce12dc3a519783
expipiplus1/vulkan
OpenXR.hs
{-# language CPP #-} No documentation found for Chapter " OpenXR " module OpenXR ( module OpenXR.CStruct , module OpenXR.Core10 , module OpenXR.Extensions , module OpenXR.NamedType , module OpenXR.Version ) where import OpenXR.CStruct import OpenXR.Core10 import OpenXR.Extensions import OpenXR.NamedType import OpenXR.Version
null
https://raw.githubusercontent.com/expipiplus1/vulkan/b1e33d1031779b4740c279c68879d05aee371659/openxr/src/OpenXR.hs
haskell
# language CPP #
No documentation found for Chapter " OpenXR " module OpenXR ( module OpenXR.CStruct , module OpenXR.Core10 , module OpenXR.Extensions , module OpenXR.NamedType , module OpenXR.Version ) where import OpenXR.CStruct import OpenXR.Core10 import OpenXR.Extensions import OpenXR.NamedType import OpenXR.Version
2080965e7053be067a88696e2d044401b686f991373675ce1da5e3c02a1b532d
gsakkas/rite
0138.ml
IteG (BopG EmptyG EmptyG) (SeqG EmptyG EmptyG) (AppG [EmptyG]) if sumList (digitsOfInt n) < 9 then (1 :: x; additivePersistence (sumList (digitsOfInt n))) else sumList x
null
https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/data/sp14_min/clusters/0138.ml
ocaml
IteG (BopG EmptyG EmptyG) (SeqG EmptyG EmptyG) (AppG [EmptyG]) if sumList (digitsOfInt n) < 9 then (1 :: x; additivePersistence (sumList (digitsOfInt n))) else sumList x
de9e220eef9f4ac8913c99c004bd64a21e5adb37c4821bf46bebaabf32a0f380
awslabs/s2n-bignum
bignum_mod_n384.ml
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved . * SPDX - License - Identifier : Apache-2.0 OR ISC * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 OR ISC *) (* ========================================================================= *) Reduction modulo n_384 , the order of the NIST curve P-384 (* ========================================================================= *) (**** print_literal_from_elf "x86/p384/bignum_mod_n384.o";; ****) let bignum_mod_n384_mc = define_assert_from_elf "bignum_mod_n384_mc" "x86/p384/bignum_mod_n384.o" [ 0x53; (* PUSH (% rbx) *) 0x41; 0x54; (* PUSH (% r12) *) 0x41; 0x55; (* PUSH (% r13) *) 0x41; 0x56; (* PUSH (% r14) *) CMP ( % rsi ) ( Imm8 ( word 6 ) ) 0x0f; 0x82; 0x7b; 0x01; 0x00; 0x00; JB ( Imm32 ( word 379 ) ) SUB ( % rsi ) ( Imm8 ( word 6 ) ) 0x4c; 0x8b; 0x6c; 0xf2; 0x28; MOV ( % r13 ) ( ( % % % % ( rdx,3,rsi,&40 ) ) ) 0x4c; 0x8b; 0x64; 0xf2; 0x20; MOV ( % r12 ) ( ( % % % % ( rdx,3,rsi,&32 ) ) ) 0x4c; 0x8b; 0x5c; 0xf2; 0x18; MOV ( % r11 ) ( ( % % % % ( rdx,3,rsi,&24 ) ) ) 0x4c; 0x8b; 0x54; 0xf2; 0x10; MOV ( % r10 ) ( ( % % % % ( ) ) ) 0x4c; 0x8b; 0x4c; 0xf2; 0x08; MOV ( % r9 ) ( ( % % % % ( rdx,3,rsi,&8 ) ) ) MOV ( % r8 ) ( ( % % % ( rdx,3,rsi ) ) ) MOV ( % rcx ) ( % rdx ) 0x48; 0xb8; 0x8d; 0xd6; 0x3a; 0x33; 0x95; 0xe6; 0x13; 0x13; MOV ( % rax ) ( Imm64 ( word 1374695839762142861 ) ) 0x48; 0xbb; 0x85; 0x58; 0x4f; 0xb7; 0x4d; 0xf2; 0xe5; 0xa7; MOV ( % rbx ) ( Imm64 ( word 12098342389602539653 ) ) 0x48; 0xba; 0x20; 0xd2; 0xc8; 0x0b; 0x7e; 0xb2; 0x9c; 0x38; MOV ( % rdx ) ( Imm64 ( word 4079331616924160544 ) ) 0x49; 0x01; 0xc0; (* ADD (% r8) (% rax) *) 0x49; 0x11; 0xd9; (* ADC (% r9) (% rbx) *) 0x49; 0x11; 0xd2; (* ADC (% r10) (% rdx) *) 0x49; 0x83; 0xd3; 0x00; (* ADC (% r11) (Imm8 (word 0)) *) 0x49; 0x83; 0xd4; 0x00; (* ADC (% r12) (Imm8 (word 0)) *) 0x49; 0x83; 0xd5; 0x00; (* ADC (% r13) (Imm8 (word 0)) *) SBB ( % r14 ) ( % r14 ) 0x49; 0xf7; 0xd6; (* NOT (% r14) *) 0x4c; 0x21; 0xf0; (* AND (% rax) (% r14) *) 0x4c; 0x21; 0xf3; (* AND (% rbx) (% r14) *) 0x4c; 0x21; 0xf2; (* AND (% rdx) (% r14) *) 0x49; 0x29; 0xc0; (* SUB (% r8) (% rax) *) SBB ( % r9 ) ( % rbx ) SBB ( % r10 ) ( % rdx ) SBB ( % r11 ) ( Imm8 ( word 0 ) ) SBB ( % r12 ) ( Imm8 ( word 0 ) ) SBB ( % r13 ) ( Imm8 ( word 0 ) ) 0x48; 0x85; 0xf6; (* TEST (% rsi) (% rsi) *) 0x0f; 0x84; 0xd8; 0x00; 0x00; 0x00; JE ( Imm32 ( word 216 ) ) 0xba; 0x01; 0x00; 0x00; 0x00; MOV ( % edx ) ( Imm32 ( word 1 ) ) 0x4c; 0x01; 0xea; (* ADD (% rdx) (% r13) *) SBB ( % r14 ) ( % r14 ) OR ( % rdx ) ( % r14 ) 0x4c; 0x8b; 0x74; 0xf1; 0xf8; MOV ( % r14 ) ( ( % % % % ( rcx,3,rsi,-- & 8) ) ) 0x49; 0x29; 0xd5; (* SUB (% r13) (% rdx) *) 0x48; 0x31; 0xc0; (* XOR (% rax) (% rax) *) 0x48; 0xb8; 0x8d; 0xd6; 0x3a; 0x33; 0x95; 0xe6; 0x13; 0x13; MOV ( % rax ) ( Imm64 ( word 1374695839762142861 ) ) 0xc4; 0xe2; 0xfb; 0xf6; 0xd8; MULX4 ( % rbx,% rax ) ( % rdx,% rax ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xf0; (* ADCX (% r14) (% rax) *) 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xc3; ADOX ( % r8 ) ( % rbx ) 0x48; 0xb8; 0x85; 0x58; 0x4f; 0xb7; 0x4d; 0xf2; 0xe5; 0xa7; MOV ( % rax ) ( Imm64 ( word 12098342389602539653 ) ) 0xc4; 0xe2; 0xfb; 0xf6; 0xd8; MULX4 ( % rbx,% rax ) ( % rdx,% rax ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xc0; (* ADCX (% r8) (% rax) *) 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xcb; ADOX ( % r9 ) ( % rbx ) 0x48; 0xb8; 0x20; 0xd2; 0xc8; 0x0b; 0x7e; 0xb2; 0x9c; 0x38; MOV ( % rax ) ( Imm64 ( word 4079331616924160544 ) ) 0xc4; 0xe2; 0xfb; 0xf6; 0xd8; MULX4 ( % rbx,% rax ) ( % rdx,% rax ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xc8; (* ADCX (% r9) (% rax) *) 0xb8; 0x00; 0x00; 0x00; 0x00; MOV ( % eax ) ( Imm32 ( word 0 ) ) 0xf3; 0x48; 0x0f; 0x38; 0xf6; 0xd8; ADOX ( % rbx ) ( % rax ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xd3; (* ADCX (% r10) (% rbx) *) 0x49; 0x83; 0xd3; 0x00; (* ADC (% r11) (Imm8 (word 0)) *) 0x49; 0x83; 0xd4; 0x00; (* ADC (% r12) (Imm8 (word 0)) *) 0x49; 0x83; 0xd5; 0x00; (* ADC (% r13) (Imm8 (word 0)) *) 0x48; 0xb8; 0x8d; 0xd6; 0x3a; 0x33; 0x95; 0xe6; 0x13; 0x13; MOV ( % rax ) ( Imm64 ( word 1374695839762142861 ) ) 0x4c; 0x21; 0xe8; (* AND (% rax) (% r13) *) 0x48; 0xbb; 0x85; 0x58; 0x4f; 0xb7; 0x4d; 0xf2; 0xe5; 0xa7; MOV ( % rbx ) ( Imm64 ( word 12098342389602539653 ) ) 0x4c; 0x21; 0xeb; (* AND (% rbx) (% r13) *) 0x48; 0xba; 0x20; 0xd2; 0xc8; 0x0b; 0x7e; 0xb2; 0x9c; 0x38; MOV ( % rdx ) ( Imm64 ( word 4079331616924160544 ) ) 0x4c; 0x21; 0xea; (* AND (% rdx) (% r13) *) 0x49; 0x29; 0xc6; (* SUB (% r14) (% rax) *) SBB ( % r8 ) ( % rbx ) SBB ( % r9 ) ( % rdx ) SBB ( % r10 ) ( Imm8 ( word 0 ) ) SBB ( % r11 ) ( Imm8 ( word 0 ) ) SBB ( % r12 ) ( Imm8 ( word 0 ) ) MOV ( % r13 ) ( % r12 ) MOV ( % r12 ) ( % r11 ) MOV ( % r11 ) ( % r10 ) MOV ( % r10 ) ( % r9 ) MOV ( % r9 ) ( % r8 ) MOV ( % r8 ) ( % r14 ) DEC ( % rsi ) 0x0f; 0x85; 0x28; 0xff; 0xff; 0xff; JNE ( Imm32 ( word 4294967080 ) ) MOV ( ( % % ( rdi,0 ) ) ) ( % r8 ) MOV ( ( % % ( rdi,8 ) ) ) ( % r9 ) MOV ( ( % % ( rdi,16 ) ) ) ( % r10 ) MOV ( ( % % ( ) ) ) ( % r11 ) MOV ( ( % % ( rdi,32 ) ) ) ( % r12 ) MOV ( ( % % ( rdi,40 ) ) ) ( % r13 ) 0x41; 0x5e; (* POP (% r14) *) 0x41; 0x5d; (* POP (% r13) *) 0x41; 0x5c; (* POP (% r12) *) 0x5b; (* POP (% rbx) *) RET 0x4d; 0x31; 0xc0; (* XOR (% r8) (% r8) *) 0x4d; 0x31; 0xc9; (* XOR (% r9) (% r9) *) 0x4d; 0x31; 0xd2; (* XOR (% r10) (% r10) *) 0x4d; 0x31; 0xdb; (* XOR (% r11) (% r11) *) 0x4d; 0x31; 0xe4; (* XOR (% r12) (% r12) *) 0x4d; 0x31; 0xed; (* XOR (% r13) (% r13) *) 0x48; 0x85; 0xf6; (* TEST (% rsi) (% rsi) *) JE ( Imm8 ( word 202 ) ) MOV ( % r8 ) ( ( % % ( rdx,0 ) ) ) DEC ( % rsi ) JE ( Imm8 ( word 194 ) ) MOV ( % r9 ) ( ( % % ( rdx,8 ) ) ) DEC ( % rsi ) JE ( Imm8 ( word 185 ) ) MOV ( % r10 ) ( ( % % ( rdx,16 ) ) ) DEC ( % rsi ) JE ( Imm8 ( word 176 ) ) MOV ( % r11 ) ( ( % % ( rdx,24 ) ) ) DEC ( % rsi ) JE ( Imm8 ( word 167 ) ) MOV ( % r12 ) ( ( % % ( ) ) ) JMP ( Imm8 ( word 161 ) ) ];; let BIGNUM_MOD_N384_EXEC = X86_MK_EXEC_RULE bignum_mod_n384_mc;; (* ------------------------------------------------------------------------- *) Common tactic for slightly different standard and Windows variants . (* ------------------------------------------------------------------------- *) let n_384 = new_definition `n_384 = 39402006196394479212279040100143613805079739270465446667946905279627659399113263569398956308152294913554433653942643`;; let n384longredlemma = prove (`!n. n < 2 EXP 64 * n_384 ==> let q = MIN (n DIV 2 EXP 384 + 1) (2 EXP 64 - 1) in q < 2 EXP 64 /\ q * n_384 <= n + n_384 /\ n < q * n_384 + n_384`, CONV_TAC(TOP_DEPTH_CONV let_CONV) THEN REWRITE_TAC[n_384] THEN ARITH_TAC);; let tac execth offset = X_GEN_TAC `z:int64` THEN W64_GEN_TAC `k:num` THEN MAP_EVERY X_GEN_TAC [`x:int64`; `n:num`; `pc:num`] THEN REWRITE_TAC[NONOVERLAPPING_CLAUSES] THEN REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS] THEN DISCH_TAC THEN BIGNUM_TERMRANGE_TAC `k:num` `n:num` THEN * * Case split over the k < 6 case , which is a different path * * ASM_CASES_TAC `k < 6` THENL [SUBGOAL_THEN `n MOD n_384 = n` SUBST1_TAC THENL [MATCH_MP_TAC MOD_LT THEN TRANS_TAC LTE_TRANS `2 EXP (64 * k)` THEN ASM_REWRITE_TAC[] THEN TRANS_TAC LE_TRANS `2 EXP (64 * 5)` THEN ASM_REWRITE_TAC[LE_EXP; n_384] THEN CONV_TAC NUM_REDUCE_CONV THEN ASM_ARITH_TAC; ALL_TAC] THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN BIGNUM_DIGITIZE_TAC "n_" `read(memory :> bytes(x,8 * 6)) s0` THEN FIRST_X_ASSUM(MP_TAC o MATCH_MP (ARITH_RULE `k < 6 ==> k = 0 \/ k = 1 \/ k = 2 \/ k = 3 \/ k = 4 \/ k = 5`)) THEN DISCH_THEN(REPEAT_TCL DISJ_CASES_THEN SUBST_ALL_TAC) THEN EXPAND_TAC "n" THEN CONV_TAC(ONCE_DEPTH_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THENL [X86_STEPS_TAC execth (1--16); X86_STEPS_TAC execth (1--19); X86_STEPS_TAC execth (1--22); X86_STEPS_TAC execth (1--25); X86_STEPS_TAC execth (1--28); X86_STEPS_TAC execth (1--30)] THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_0] THEN ARITH_TAC; FIRST_ASSUM(ASSUME_TAC o GEN_REWRITE_RULE I [NOT_LT])] THEN * * Initial 6 - digit modulus * * ENSURES_SEQUENCE_TAC (offset 0x8c) `\s. bignum_from_memory(x,k) s = n /\ read RDI s = z /\ read RCX s = x /\ read RSI s = word(k - 6) /\ bignum_of_wordlist[read R8 s; read R9 s; read R10 s; read R11 s; read R12 s; read R13 s] = (highdigits n (k - 6)) MOD n_384` THEN CONJ_TAC THENL [ABBREV_TAC `j = k - 6` THEN VAL_INT64_TAC `j:num` THEN SUBGOAL_THEN `word_sub (word k) (word 6):int64 = word j` ASSUME_TAC THENL [SUBST1_TAC(SYM(ASSUME `k - 6 = j`)) THEN REWRITE_TAC[WORD_SUB] THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN EXPAND_TAC "n" THEN REWRITE_TAC[highdigits] THEN REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; BIGNUM_FROM_MEMORY_DIV] THEN ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN SUBST1_TAC(SYM(ASSUME `k - 6 = j`)) THEN ASM_SIMP_TAC[ARITH_RULE `6 <= k ==> k - (k - 6) = 6`] THEN ABBREV_TAC `m = bignum_from_memory(word_add x (word (8 * j)),6) s0` THEN SUBGOAL_THEN `m < 2 EXP (64 * 6)` ASSUME_TAC THENL [EXPAND_TAC "m" THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BOUND]; ALL_TAC] THEN RULE_ASSUM_TAC(CONV_RULE(ONCE_DEPTH_CONV BIGNUM_EXPAND_CONV)) THEN BIGNUM_DIGITIZE_TAC "m_" `read (memory :> bytes (word_add x (word(8 * j)),8 * 6)) s0` THEN X86_ACCSTEPS_TAC execth (1--19) (1--19) THEN SUBGOAL_THEN `carry_s19 <=> n_384 <= m` SUBST_ALL_TAC THENL [MATCH_MP_TAC FLAG_FROM_CARRY_LE THEN EXISTS_TAC `384` THEN EXPAND_TAC "m" THEN REWRITE_TAC[n_384; GSYM REAL_OF_NUM_ADD] THEN REWRITE_TAC[GSYM REAL_OF_NUM_MUL; GSYM REAL_OF_NUM_POW] THEN ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[]; ALL_TAC] THEN X86_STEPS_TAC execth (20--24) THEN X86_ACCSTEPS_TAC execth (25--30) (25--30) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[bignum_of_wordlist; ADD_CLAUSES; MULT_CLAUSES] THEN ASM_REWRITE_TAC[] THEN DISCARD_STATE_TAC "s30" THEN W(MP_TAC o PART_MATCH (lhand o rand) MOD_CASES o rand o snd) THEN ANTS_TAC THENL [TRANS_TAC LTE_TRANS `2 EXP (64 * 6)` THEN ASM_REWRITE_TAC[n_384] THEN CONV_TAC NUM_REDUCE_CONV; DISCH_THEN SUBST1_TAC] THEN REWRITE_TAC[GSYM NOT_LE; COND_SWAP] THEN REWRITE_TAC[GSYM REAL_OF_NUM_EQ; GSYM REAL_OF_NUM_ADD] THEN ONCE_REWRITE_TAC[COND_RAND] THEN SIMP_TAC[GSYM REAL_OF_NUM_SUB] THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN REWRITE_TAC[REAL_OF_NUM_LE] THEN MATCH_MP_TAC EQUAL_FROM_CONGRUENT_REAL THEN MAP_EVERY EXISTS_TAC [`384`; `&0:real`] THEN ASM_REWRITE_TAC[] THEN CONJ_TAC THENL [BOUNDER_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [UNDISCH_TAC `m < 2 EXP (64 * 6)` THEN REWRITE_TAC[n_384] THEN POP_ASSUM_LIST(K ALL_TAC) THEN CONV_TAC NUM_REDUCE_CONV THEN REWRITE_TAC[GSYM REAL_OF_NUM_LE; GSYM REAL_OF_NUM_LT] THEN REAL_ARITH_TAC; ALL_TAC] THEN CONJ_TAC THENL [REAL_INTEGER_TAC; ALL_TAC] THEN EXPAND_TAC "m" THEN REWRITE_TAC[GSYM REAL_OF_NUM_ADD] THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[GSYM REAL_OF_NUM_MUL; GSYM REAL_OF_NUM_POW] THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN REWRITE_TAC[REAL_BITVAL_NOT; n_384] THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REWRITE_TAC[WORD_AND_MASK] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN CONV_TAC WORD_REDUCE_CONV THEN REAL_INTEGER_TAC; ALL_TAC] THEN * * Finish off the k = 6 case which is now just the writeback * * FIRST_ASSUM(DISJ_CASES_THEN2 SUBST_ALL_TAC ASSUME_TAC o MATCH_MP (ARITH_RULE `6 <= k ==> k = 6 \/ 6 < k`)) THENL [GHOST_INTRO_TAC `d0:int64` `read R8` THEN GHOST_INTRO_TAC `d1:int64` `read R9` THEN GHOST_INTRO_TAC `d2:int64` `read R10` THEN GHOST_INTRO_TAC `d3:int64` `read R11` THEN GHOST_INTRO_TAC `d4:int64` `read R12` THEN GHOST_INTRO_TAC `d5:int64` `read R13` THEN REWRITE_TAC[SUB_REFL; HIGHDIGITS_0] THEN ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC execth (1--8) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC RAND_CONV [SYM th]) THEN REWRITE_TAC[bignum_of_wordlist] THEN CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN ARITH_TAC; ALL_TAC] THEN SUBGOAL_THEN `0 < k - 6 /\ ~(k - 6 = 0)` STRIP_ASSUME_TAC THENL [SIMPLE_ARITH_TAC; ALL_TAC] THEN (*** Setup of loop invariant ***) ENSURES_WHILE_PDOWN_TAC `k - 6` (offset 0x95) (offset 0x167) `\i s. (bignum_from_memory(x,k) s = n /\ read RDI s = z /\ read RCX s = x /\ read RSI s = word i /\ bignum_of_wordlist[read R8 s; read R9 s; read R10 s; read R11 s; read R12 s; read R13 s] = (highdigits n i) MOD n_384) /\ (read ZF s <=> i = 0)` THEN ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL [VAL_INT64_TAC `k - 6` THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC execth (1--2) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[]; ALL_TAC; (*** Main loop invariant ***) X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC execth [1] THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[]; GHOST_INTRO_TAC `d0:int64` `read R8` THEN GHOST_INTRO_TAC `d1:int64` `read R9` THEN GHOST_INTRO_TAC `d2:int64` `read R10` THEN GHOST_INTRO_TAC `d3:int64` `read R11` THEN GHOST_INTRO_TAC `d4:int64` `read R12` THEN GHOST_INTRO_TAC `d5:int64` `read R13` THEN REWRITE_TAC[SUB_REFL; HIGHDIGITS_0] THEN ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC execth (1--7) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC RAND_CONV [SYM th]) THEN REWRITE_TAC[bignum_of_wordlist] THEN CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN ARITH_TAC] THEN (*** Mathematics of main loop with decomposition and quotient estimate ***) X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN GHOST_INTRO_TAC `m1:int64` `read R8` THEN GHOST_INTRO_TAC `m2:int64` `read R9` THEN GHOST_INTRO_TAC `m3:int64` `read R10` THEN GHOST_INTRO_TAC `m4:int64` `read R11` THEN GHOST_INTRO_TAC `m5:int64` `read R12` THEN GHOST_INTRO_TAC `m6:int64` `read R13` THEN GLOBALIZE_PRECONDITION_TAC THEN ASM_REWRITE_TAC[] THEN ABBREV_TAC `m0:int64 = word(bigdigit n i)` THEN ABBREV_TAC `m = bignum_of_wordlist[m0; m1; m2; m3; m4; m5; m6]` THEN SUBGOAL_THEN `m < 2 EXP 64 * n_384` ASSUME_TAC THENL [EXPAND_TAC "m" THEN ONCE_REWRITE_TAC[bignum_of_wordlist] THEN MP_TAC(SPEC `m0:int64` VAL_BOUND_64) THEN ASM_REWRITE_TAC[n_384] THEN ARITH_TAC; ALL_TAC] THEN SUBGOAL_THEN `highdigits n i MOD n_384 = m MOD n_384` SUBST1_TAC THENL [ONCE_REWRITE_TAC[HIGHDIGITS_STEP] THEN EXPAND_TAC "m" THEN ONCE_REWRITE_TAC[bignum_of_wordlist] THEN EXPAND_TAC "m0" THEN SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN ASM_REWRITE_TAC[] THEN CONV_TAC MOD_DOWN_CONV THEN AP_THM_TAC THEN AP_TERM_TAC THEN ARITH_TAC; ALL_TAC] THEN MP_TAC(SPEC `m:num` n384longredlemma) THEN ASM_REWRITE_TAC[] THEN LET_TAC THEN STRIP_TAC THEN (*** The computation of the quotient estimate q ***) ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN X86_ACCSTEPS_TAC execth [2] (1--2) THEN SUBGOAL_THEN `2 EXP 64 * bitval(read CF s2) + val(read RDX s2) = m DIV 2 EXP 384 + 1` MP_TAC THENL [EXPAND_TAC "m" THEN CONV_TAC(ONCE_DEPTH_CONV BIGNUM_OF_WORDLIST_DIV_CONV) THEN ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN REAL_ARITH_TAC; ASM_REWRITE_TAC[] THEN DISCH_TAC] THEN X86_STEPS_TAC execth (3--4) THEN FIRST_X_ASSUM(MP_TAC o SPEC `word q:int64` o MATCH_MP (MESON[] `!q. read RDX s = q' ==> q' = q ==> read RDX s = q`)) THEN ANTS_TAC THENL [EXPAND_TAC "q" THEN FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC (RAND_CONV o RAND_CONV o LAND_CONV) [SYM th]) THEN POP_ASSUM_LIST(K ALL_TAC) THEN REWRITE_TAC[WORD_OR_MASK] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN SIMP_TAC[VAL_BOUND_64; WORD_VAL; ARITH_RULE `n < 2 EXP 64 ==> MIN n (2 EXP 64 - 1) = n`] THEN REWRITE_TAC[ARITH_RULE `MIN (2 EXP 64 + a) (2 EXP 64 - 1) = 2 EXP 64 - 1`] THEN CONV_TAC NUM_REDUCE_CONV THEN CONV_TAC WORD_REDUCE_CONV; DISCH_TAC THEN VAL_INT64_TAC `q:num`] THEN (*** The next digit in the current state ***) VAL_INT64_TAC `i + 1` THEN ASSUME_TAC(SPEC `i:num` WORD_INDEX_WRAP) THEN SUBGOAL_THEN `i:num < k` ASSUME_TAC THENL [SIMPLE_ARITH_TAC; ALL_TAC] THEN MP_TAC(SPECL [`k:num`; `x:int64`; `s4:x86state`; `i:num`] BIGDIGIT_BIGNUM_FROM_MEMORY) THEN ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN DISCH_THEN(MP_TAC o AP_TERM `word:num->int64` o SYM) THEN ASM_REWRITE_TAC[WORD_VAL] THEN DISCH_TAC THEN (*** A bit of fiddle to make the accumulation tactics work ***) ABBREV_TAC `w:int64 = word q` THEN UNDISCH_THEN `val(w:int64) = q` (SUBST_ALL_TAC o SYM) THEN ACCUMULATOR_POP_ASSUM_LIST(K ALL_TAC o end_itlist CONJ) THEN (*** Subtraction of q * n_384 ***) X86_ACCSTEPS_TAC execth (5--24) (5--24) THEN SUBGOAL_THEN `sum_s24:int64 = word_neg(word(bitval(m < val(w:int64) * n_384))) /\ &(bignum_of_wordlist [sum_s10; sum_s14; sum_s18; sum_s21; sum_s22; sum_s23]) = if m < val w * n_384 then &m - &(val w * n_384) + &2 pow 384 else &m - &(val w * n_384)` STRIP_ASSUME_TAC THENL [MATCH_MP_TAC MASK_AND_VALUE_FROM_CARRY_LT THEN CONJ_TAC THENL [MAP_EVERY UNDISCH_TAC [`val(w:int64) * n_384 <= m + n_384`; `m < val(w:int64) * n_384 + n_384`] THEN REWRITE_TAC[n_384; GSYM REAL_OF_NUM_CLAUSES] THEN REAL_ARITH_TAC; ASM_REWRITE_TAC[bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES]] THEN CONJ_TAC THENL [BOUNDER_TAC[]; CONV_TAC(ONCE_DEPTH_CONV NUM_ADD_CONV)] THEN ASM_REWRITE_TAC[] THEN EXPAND_TAC "m" THEN REWRITE_TAC[bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES; n_384] THEN ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN CONV_TAC(RAND_CONV REAL_POLY_CONV) THEN REPEAT(MATCH_MP_TAC INTEGER_ADD THEN CONJ_TAC) THEN TRY REAL_INTEGER_TAC THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_INTEGER_TAC; ACCUMULATOR_POP_ASSUM_LIST(K ALL_TAC)] THEN (*** Final correction ***) X86_ACCSTEPS_TAC execth (31--36) (25--43) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL [CONV_TAC WORD_RULE; DISCH_THEN SUBST1_TAC] THEN ASM_REWRITE_TAC[] THEN CONV_TAC SYM_CONV THEN MATCH_MP_TAC MOD_UNIQ_BALANCED_REAL THEN MAP_EVERY EXISTS_TAC [`val(w:int64)`; `384`] THEN ASM_REWRITE_TAC[] THEN ABBREV_TAC `b <=> m < val(w:int64) * n_384` THEN REWRITE_TAC[REAL_ARITH `m - s - (w - b) * n:real = (m - w * n) + (b * n - s)`] THEN FIRST_ASSUM(MP_TAC o MATCH_MP (MESON[REAL_ADD_RID] `x = (if p then y + z else y) ==> x = y + (if p then z else &0)`)) THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist; n_384] THEN GEN_REWRITE_TAC LAND_CONV [REAL_ARITH `x:real = y + z <=> y = x - z`] THEN DISCH_THEN SUBST1_TAC THEN CONJ_TAC THENL [ARITH_TAC; ALL_TAC] THEN REWRITE_TAC[bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN CONJ_TAC THENL [BOUNDER_TAC[]; ALL_TAC] THEN ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN POP_ASSUM_LIST(K ALL_TAC) THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN CONV_TAC WORD_REDUCE_CONV THEN REAL_INTEGER_TAC;; (* ------------------------------------------------------------------------- *) Correctness of standard ABI version . (* ------------------------------------------------------------------------- *) let BIGNUM_MOD_N384_CORRECT = time prove (`!z k x n pc. nonoverlapping (word pc,0x1cc) (z,48) ==> ensures x86 (\s. bytes_loaded s (word pc) bignum_mod_n384_mc /\ read RIP s = word(pc + 0x7) /\ C_ARGUMENTS [z; k; x] s /\ bignum_from_memory (x,val k) s = n) (\s. read RIP s = word (pc + 0x184) /\ bignum_from_memory (z,6) s = n MOD n_384) (MAYCHANGE [RIP; RSI; RAX; RDX; RCX; RBX; R8; R9; R10; R11; R12; R13; R14] ,, MAYCHANGE SOME_FLAGS ,, MAYCHANGE [memory :> bignum(z,6)])`, tac BIGNUM_MOD_N384_EXEC (curry mk_comb `(+) (pc:num)` o mk_small_numeral));; let BIGNUM_MOD_N384_SUBROUTINE_CORRECT = time prove (`!z k x n pc stackpointer returnaddress. nonoverlapping (word_sub stackpointer (word 32),40) (z,48) /\ ALL (nonoverlapping (word_sub stackpointer (word 32),32)) [(word pc,0x1cc); (x, 8 * val k)] /\ nonoverlapping (word pc,0x1cc) (z,48) ==> ensures x86 (\s. bytes_loaded s (word pc) bignum_mod_n384_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ C_ARGUMENTS [z; k; x] s /\ bignum_from_memory (x,val k) s = n) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ bignum_from_memory (z,6) s = n MOD n_384) (MAYCHANGE [RIP; RSP; RSI; RAX; RDX; RCX; R8; R9; R10; R11] ,, MAYCHANGE SOME_FLAGS ,, MAYCHANGE [memory :> bignum(z,6); memory :> bytes(word_sub stackpointer (word 32),32)])`, X86_ADD_RETURN_STACK_TAC BIGNUM_MOD_N384_EXEC BIGNUM_MOD_N384_CORRECT `[RBX; R12; R13; R14]` 32);; (* ------------------------------------------------------------------------- *) (* Correctness of Windows ABI version. *) (* ------------------------------------------------------------------------- *) let windows_bignum_mod_n384_mc = define_from_elf "windows_bignum_mod_n384_mc" "x86/p384/bignum_mod_n384.obj";; let WINDOWS_BIGNUM_MOD_N384_CORRECT = time prove (`!z k x n pc. nonoverlapping (word pc,0x1d9) (z,48) ==> ensures x86 (\s. bytes_loaded s (word pc) windows_bignum_mod_n384_mc /\ read RIP s = word(pc + 0x12) /\ C_ARGUMENTS [z; k; x] s /\ bignum_from_memory (x,val k) s = n) (\s. read RIP s = word (pc + 0x18f) /\ bignum_from_memory (z,6) s = n MOD n_384) (MAYCHANGE [RIP; RSI; RAX; RDX; RCX; RBX; R8; R9; R10; R11; R12; R13; R14] ,, MAYCHANGE SOME_FLAGS ,, MAYCHANGE [memory :> bignum(z,6)])`, tac (X86_MK_EXEC_RULE windows_bignum_mod_n384_mc) (curry mk_comb `(+) (pc:num)` o mk_small_numeral o (fun n -> n + 11)));; let WINDOWS_BIGNUM_MOD_N384_SUBROUTINE_CORRECT = time prove (`!z k x n pc stackpointer returnaddress. nonoverlapping (word_sub stackpointer (word 48),56) (z,48) /\ ALL (nonoverlapping (word_sub stackpointer (word 48),48)) [(word pc,0x1d9); (x, 8 * val k)] /\ nonoverlapping (word pc,0x1d9) (z,48) ==> ensures x86 (\s. bytes_loaded s (word pc) windows_bignum_mod_n384_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ WINDOWS_C_ARGUMENTS [z; k; x] s /\ bignum_from_memory (x,val k) s = n) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ bignum_from_memory (z,6) s = n MOD n_384) (MAYCHANGE [RIP; RSP; RAX; RDX; RCX; R8; R9; R10; R11] ,, MAYCHANGE SOME_FLAGS ,, MAYCHANGE [memory :> bignum(z,6); memory :> bytes(word_sub stackpointer (word 48),48)])`, GEN_X86_ADD_RETURN_STACK_TAC (X86_MK_EXEC_RULE windows_bignum_mod_n384_mc) WINDOWS_BIGNUM_MOD_N384_CORRECT `[RDI; RSI; RBX; R12; R13; R14]` 48 (9,7));;
null
https://raw.githubusercontent.com/awslabs/s2n-bignum/824c15f908d7a343af1b2f378cfedd36e880bdde/x86/proofs/bignum_mod_n384.ml
ocaml
========================================================================= ========================================================================= *** print_literal_from_elf "x86/p384/bignum_mod_n384.o";; *** PUSH (% rbx) PUSH (% r12) PUSH (% r13) PUSH (% r14) ADD (% r8) (% rax) ADC (% r9) (% rbx) ADC (% r10) (% rdx) ADC (% r11) (Imm8 (word 0)) ADC (% r12) (Imm8 (word 0)) ADC (% r13) (Imm8 (word 0)) NOT (% r14) AND (% rax) (% r14) AND (% rbx) (% r14) AND (% rdx) (% r14) SUB (% r8) (% rax) TEST (% rsi) (% rsi) ADD (% rdx) (% r13) SUB (% r13) (% rdx) XOR (% rax) (% rax) ADCX (% r14) (% rax) ADCX (% r8) (% rax) ADCX (% r9) (% rax) ADCX (% r10) (% rbx) ADC (% r11) (Imm8 (word 0)) ADC (% r12) (Imm8 (word 0)) ADC (% r13) (Imm8 (word 0)) AND (% rax) (% r13) AND (% rbx) (% r13) AND (% rdx) (% r13) SUB (% r14) (% rax) POP (% r14) POP (% r13) POP (% r12) POP (% rbx) XOR (% r8) (% r8) XOR (% r9) (% r9) XOR (% r10) (% r10) XOR (% r11) (% r11) XOR (% r12) (% r12) XOR (% r13) (% r13) TEST (% rsi) (% rsi) ------------------------------------------------------------------------- ------------------------------------------------------------------------- ** Setup of loop invariant ** ** Main loop invariant ** ** Mathematics of main loop with decomposition and quotient estimate ** ** The computation of the quotient estimate q ** ** The next digit in the current state ** ** A bit of fiddle to make the accumulation tactics work ** ** Subtraction of q * n_384 ** ** Final correction ** ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- Correctness of Windows ABI version. -------------------------------------------------------------------------
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved . * SPDX - License - Identifier : Apache-2.0 OR ISC * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 OR ISC *) Reduction modulo n_384 , the order of the NIST curve P-384 let bignum_mod_n384_mc = define_assert_from_elf "bignum_mod_n384_mc" "x86/p384/bignum_mod_n384.o" [ CMP ( % rsi ) ( Imm8 ( word 6 ) ) 0x0f; 0x82; 0x7b; 0x01; 0x00; 0x00; JB ( Imm32 ( word 379 ) ) SUB ( % rsi ) ( Imm8 ( word 6 ) ) 0x4c; 0x8b; 0x6c; 0xf2; 0x28; MOV ( % r13 ) ( ( % % % % ( rdx,3,rsi,&40 ) ) ) 0x4c; 0x8b; 0x64; 0xf2; 0x20; MOV ( % r12 ) ( ( % % % % ( rdx,3,rsi,&32 ) ) ) 0x4c; 0x8b; 0x5c; 0xf2; 0x18; MOV ( % r11 ) ( ( % % % % ( rdx,3,rsi,&24 ) ) ) 0x4c; 0x8b; 0x54; 0xf2; 0x10; MOV ( % r10 ) ( ( % % % % ( ) ) ) 0x4c; 0x8b; 0x4c; 0xf2; 0x08; MOV ( % r9 ) ( ( % % % % ( rdx,3,rsi,&8 ) ) ) MOV ( % r8 ) ( ( % % % ( rdx,3,rsi ) ) ) MOV ( % rcx ) ( % rdx ) 0x48; 0xb8; 0x8d; 0xd6; 0x3a; 0x33; 0x95; 0xe6; 0x13; 0x13; MOV ( % rax ) ( Imm64 ( word 1374695839762142861 ) ) 0x48; 0xbb; 0x85; 0x58; 0x4f; 0xb7; 0x4d; 0xf2; 0xe5; 0xa7; MOV ( % rbx ) ( Imm64 ( word 12098342389602539653 ) ) 0x48; 0xba; 0x20; 0xd2; 0xc8; 0x0b; 0x7e; 0xb2; 0x9c; 0x38; MOV ( % rdx ) ( Imm64 ( word 4079331616924160544 ) ) SBB ( % r14 ) ( % r14 ) SBB ( % r9 ) ( % rbx ) SBB ( % r10 ) ( % rdx ) SBB ( % r11 ) ( Imm8 ( word 0 ) ) SBB ( % r12 ) ( Imm8 ( word 0 ) ) SBB ( % r13 ) ( Imm8 ( word 0 ) ) 0x0f; 0x84; 0xd8; 0x00; 0x00; 0x00; JE ( Imm32 ( word 216 ) ) 0xba; 0x01; 0x00; 0x00; 0x00; MOV ( % edx ) ( Imm32 ( word 1 ) ) SBB ( % r14 ) ( % r14 ) OR ( % rdx ) ( % r14 ) 0x4c; 0x8b; 0x74; 0xf1; 0xf8; MOV ( % r14 ) ( ( % % % % ( rcx,3,rsi,-- & 8) ) ) 0x48; 0xb8; 0x8d; 0xd6; 0x3a; 0x33; 0x95; 0xe6; 0x13; 0x13; MOV ( % rax ) ( Imm64 ( word 1374695839762142861 ) ) 0xc4; 0xe2; 0xfb; 0xf6; 0xd8; MULX4 ( % rbx,% rax ) ( % rdx,% rax ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xf0; 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xc3; ADOX ( % r8 ) ( % rbx ) 0x48; 0xb8; 0x85; 0x58; 0x4f; 0xb7; 0x4d; 0xf2; 0xe5; 0xa7; MOV ( % rax ) ( Imm64 ( word 12098342389602539653 ) ) 0xc4; 0xe2; 0xfb; 0xf6; 0xd8; MULX4 ( % rbx,% rax ) ( % rdx,% rax ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xc0; 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xcb; ADOX ( % r9 ) ( % rbx ) 0x48; 0xb8; 0x20; 0xd2; 0xc8; 0x0b; 0x7e; 0xb2; 0x9c; 0x38; MOV ( % rax ) ( Imm64 ( word 4079331616924160544 ) ) 0xc4; 0xe2; 0xfb; 0xf6; 0xd8; MULX4 ( % rbx,% rax ) ( % rdx,% rax ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xc8; 0xb8; 0x00; 0x00; 0x00; 0x00; MOV ( % eax ) ( Imm32 ( word 0 ) ) 0xf3; 0x48; 0x0f; 0x38; 0xf6; 0xd8; ADOX ( % rbx ) ( % rax ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xd3; 0x48; 0xb8; 0x8d; 0xd6; 0x3a; 0x33; 0x95; 0xe6; 0x13; 0x13; MOV ( % rax ) ( Imm64 ( word 1374695839762142861 ) ) 0x48; 0xbb; 0x85; 0x58; 0x4f; 0xb7; 0x4d; 0xf2; 0xe5; 0xa7; MOV ( % rbx ) ( Imm64 ( word 12098342389602539653 ) ) 0x48; 0xba; 0x20; 0xd2; 0xc8; 0x0b; 0x7e; 0xb2; 0x9c; 0x38; MOV ( % rdx ) ( Imm64 ( word 4079331616924160544 ) ) SBB ( % r8 ) ( % rbx ) SBB ( % r9 ) ( % rdx ) SBB ( % r10 ) ( Imm8 ( word 0 ) ) SBB ( % r11 ) ( Imm8 ( word 0 ) ) SBB ( % r12 ) ( Imm8 ( word 0 ) ) MOV ( % r13 ) ( % r12 ) MOV ( % r12 ) ( % r11 ) MOV ( % r11 ) ( % r10 ) MOV ( % r10 ) ( % r9 ) MOV ( % r9 ) ( % r8 ) MOV ( % r8 ) ( % r14 ) DEC ( % rsi ) 0x0f; 0x85; 0x28; 0xff; 0xff; 0xff; JNE ( Imm32 ( word 4294967080 ) ) MOV ( ( % % ( rdi,0 ) ) ) ( % r8 ) MOV ( ( % % ( rdi,8 ) ) ) ( % r9 ) MOV ( ( % % ( rdi,16 ) ) ) ( % r10 ) MOV ( ( % % ( ) ) ) ( % r11 ) MOV ( ( % % ( rdi,32 ) ) ) ( % r12 ) MOV ( ( % % ( rdi,40 ) ) ) ( % r13 ) RET JE ( Imm8 ( word 202 ) ) MOV ( % r8 ) ( ( % % ( rdx,0 ) ) ) DEC ( % rsi ) JE ( Imm8 ( word 194 ) ) MOV ( % r9 ) ( ( % % ( rdx,8 ) ) ) DEC ( % rsi ) JE ( Imm8 ( word 185 ) ) MOV ( % r10 ) ( ( % % ( rdx,16 ) ) ) DEC ( % rsi ) JE ( Imm8 ( word 176 ) ) MOV ( % r11 ) ( ( % % ( rdx,24 ) ) ) DEC ( % rsi ) JE ( Imm8 ( word 167 ) ) MOV ( % r12 ) ( ( % % ( ) ) ) JMP ( Imm8 ( word 161 ) ) ];; let BIGNUM_MOD_N384_EXEC = X86_MK_EXEC_RULE bignum_mod_n384_mc;; Common tactic for slightly different standard and Windows variants . let n_384 = new_definition `n_384 = 39402006196394479212279040100143613805079739270465446667946905279627659399113263569398956308152294913554433653942643`;; let n384longredlemma = prove (`!n. n < 2 EXP 64 * n_384 ==> let q = MIN (n DIV 2 EXP 384 + 1) (2 EXP 64 - 1) in q < 2 EXP 64 /\ q * n_384 <= n + n_384 /\ n < q * n_384 + n_384`, CONV_TAC(TOP_DEPTH_CONV let_CONV) THEN REWRITE_TAC[n_384] THEN ARITH_TAC);; let tac execth offset = X_GEN_TAC `z:int64` THEN W64_GEN_TAC `k:num` THEN MAP_EVERY X_GEN_TAC [`x:int64`; `n:num`; `pc:num`] THEN REWRITE_TAC[NONOVERLAPPING_CLAUSES] THEN REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS] THEN DISCH_TAC THEN BIGNUM_TERMRANGE_TAC `k:num` `n:num` THEN * * Case split over the k < 6 case , which is a different path * * ASM_CASES_TAC `k < 6` THENL [SUBGOAL_THEN `n MOD n_384 = n` SUBST1_TAC THENL [MATCH_MP_TAC MOD_LT THEN TRANS_TAC LTE_TRANS `2 EXP (64 * k)` THEN ASM_REWRITE_TAC[] THEN TRANS_TAC LE_TRANS `2 EXP (64 * 5)` THEN ASM_REWRITE_TAC[LE_EXP; n_384] THEN CONV_TAC NUM_REDUCE_CONV THEN ASM_ARITH_TAC; ALL_TAC] THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN BIGNUM_DIGITIZE_TAC "n_" `read(memory :> bytes(x,8 * 6)) s0` THEN FIRST_X_ASSUM(MP_TAC o MATCH_MP (ARITH_RULE `k < 6 ==> k = 0 \/ k = 1 \/ k = 2 \/ k = 3 \/ k = 4 \/ k = 5`)) THEN DISCH_THEN(REPEAT_TCL DISJ_CASES_THEN SUBST_ALL_TAC) THEN EXPAND_TAC "n" THEN CONV_TAC(ONCE_DEPTH_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THENL [X86_STEPS_TAC execth (1--16); X86_STEPS_TAC execth (1--19); X86_STEPS_TAC execth (1--22); X86_STEPS_TAC execth (1--25); X86_STEPS_TAC execth (1--28); X86_STEPS_TAC execth (1--30)] THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_0] THEN ARITH_TAC; FIRST_ASSUM(ASSUME_TAC o GEN_REWRITE_RULE I [NOT_LT])] THEN * * Initial 6 - digit modulus * * ENSURES_SEQUENCE_TAC (offset 0x8c) `\s. bignum_from_memory(x,k) s = n /\ read RDI s = z /\ read RCX s = x /\ read RSI s = word(k - 6) /\ bignum_of_wordlist[read R8 s; read R9 s; read R10 s; read R11 s; read R12 s; read R13 s] = (highdigits n (k - 6)) MOD n_384` THEN CONJ_TAC THENL [ABBREV_TAC `j = k - 6` THEN VAL_INT64_TAC `j:num` THEN SUBGOAL_THEN `word_sub (word k) (word 6):int64 = word j` ASSUME_TAC THENL [SUBST1_TAC(SYM(ASSUME `k - 6 = j`)) THEN REWRITE_TAC[WORD_SUB] THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN EXPAND_TAC "n" THEN REWRITE_TAC[highdigits] THEN REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; BIGNUM_FROM_MEMORY_DIV] THEN ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN SUBST1_TAC(SYM(ASSUME `k - 6 = j`)) THEN ASM_SIMP_TAC[ARITH_RULE `6 <= k ==> k - (k - 6) = 6`] THEN ABBREV_TAC `m = bignum_from_memory(word_add x (word (8 * j)),6) s0` THEN SUBGOAL_THEN `m < 2 EXP (64 * 6)` ASSUME_TAC THENL [EXPAND_TAC "m" THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BOUND]; ALL_TAC] THEN RULE_ASSUM_TAC(CONV_RULE(ONCE_DEPTH_CONV BIGNUM_EXPAND_CONV)) THEN BIGNUM_DIGITIZE_TAC "m_" `read (memory :> bytes (word_add x (word(8 * j)),8 * 6)) s0` THEN X86_ACCSTEPS_TAC execth (1--19) (1--19) THEN SUBGOAL_THEN `carry_s19 <=> n_384 <= m` SUBST_ALL_TAC THENL [MATCH_MP_TAC FLAG_FROM_CARRY_LE THEN EXISTS_TAC `384` THEN EXPAND_TAC "m" THEN REWRITE_TAC[n_384; GSYM REAL_OF_NUM_ADD] THEN REWRITE_TAC[GSYM REAL_OF_NUM_MUL; GSYM REAL_OF_NUM_POW] THEN ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[]; ALL_TAC] THEN X86_STEPS_TAC execth (20--24) THEN X86_ACCSTEPS_TAC execth (25--30) (25--30) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[bignum_of_wordlist; ADD_CLAUSES; MULT_CLAUSES] THEN ASM_REWRITE_TAC[] THEN DISCARD_STATE_TAC "s30" THEN W(MP_TAC o PART_MATCH (lhand o rand) MOD_CASES o rand o snd) THEN ANTS_TAC THENL [TRANS_TAC LTE_TRANS `2 EXP (64 * 6)` THEN ASM_REWRITE_TAC[n_384] THEN CONV_TAC NUM_REDUCE_CONV; DISCH_THEN SUBST1_TAC] THEN REWRITE_TAC[GSYM NOT_LE; COND_SWAP] THEN REWRITE_TAC[GSYM REAL_OF_NUM_EQ; GSYM REAL_OF_NUM_ADD] THEN ONCE_REWRITE_TAC[COND_RAND] THEN SIMP_TAC[GSYM REAL_OF_NUM_SUB] THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN REWRITE_TAC[REAL_OF_NUM_LE] THEN MATCH_MP_TAC EQUAL_FROM_CONGRUENT_REAL THEN MAP_EVERY EXISTS_TAC [`384`; `&0:real`] THEN ASM_REWRITE_TAC[] THEN CONJ_TAC THENL [BOUNDER_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [UNDISCH_TAC `m < 2 EXP (64 * 6)` THEN REWRITE_TAC[n_384] THEN POP_ASSUM_LIST(K ALL_TAC) THEN CONV_TAC NUM_REDUCE_CONV THEN REWRITE_TAC[GSYM REAL_OF_NUM_LE; GSYM REAL_OF_NUM_LT] THEN REAL_ARITH_TAC; ALL_TAC] THEN CONJ_TAC THENL [REAL_INTEGER_TAC; ALL_TAC] THEN EXPAND_TAC "m" THEN REWRITE_TAC[GSYM REAL_OF_NUM_ADD] THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[GSYM REAL_OF_NUM_MUL; GSYM REAL_OF_NUM_POW] THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN REWRITE_TAC[REAL_BITVAL_NOT; n_384] THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REWRITE_TAC[WORD_AND_MASK] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN CONV_TAC WORD_REDUCE_CONV THEN REAL_INTEGER_TAC; ALL_TAC] THEN * * Finish off the k = 6 case which is now just the writeback * * FIRST_ASSUM(DISJ_CASES_THEN2 SUBST_ALL_TAC ASSUME_TAC o MATCH_MP (ARITH_RULE `6 <= k ==> k = 6 \/ 6 < k`)) THENL [GHOST_INTRO_TAC `d0:int64` `read R8` THEN GHOST_INTRO_TAC `d1:int64` `read R9` THEN GHOST_INTRO_TAC `d2:int64` `read R10` THEN GHOST_INTRO_TAC `d3:int64` `read R11` THEN GHOST_INTRO_TAC `d4:int64` `read R12` THEN GHOST_INTRO_TAC `d5:int64` `read R13` THEN REWRITE_TAC[SUB_REFL; HIGHDIGITS_0] THEN ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC execth (1--8) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC RAND_CONV [SYM th]) THEN REWRITE_TAC[bignum_of_wordlist] THEN CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN ARITH_TAC; ALL_TAC] THEN SUBGOAL_THEN `0 < k - 6 /\ ~(k - 6 = 0)` STRIP_ASSUME_TAC THENL [SIMPLE_ARITH_TAC; ALL_TAC] THEN ENSURES_WHILE_PDOWN_TAC `k - 6` (offset 0x95) (offset 0x167) `\i s. (bignum_from_memory(x,k) s = n /\ read RDI s = z /\ read RCX s = x /\ read RSI s = word i /\ bignum_of_wordlist[read R8 s; read R9 s; read R10 s; read R11 s; read R12 s; read R13 s] = (highdigits n i) MOD n_384) /\ (read ZF s <=> i = 0)` THEN ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL [VAL_INT64_TAC `k - 6` THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC execth (1--2) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[]; X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC execth [1] THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[]; GHOST_INTRO_TAC `d0:int64` `read R8` THEN GHOST_INTRO_TAC `d1:int64` `read R9` THEN GHOST_INTRO_TAC `d2:int64` `read R10` THEN GHOST_INTRO_TAC `d3:int64` `read R11` THEN GHOST_INTRO_TAC `d4:int64` `read R12` THEN GHOST_INTRO_TAC `d5:int64` `read R13` THEN REWRITE_TAC[SUB_REFL; HIGHDIGITS_0] THEN ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC execth (1--7) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC RAND_CONV [SYM th]) THEN REWRITE_TAC[bignum_of_wordlist] THEN CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN ARITH_TAC] THEN X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN GHOST_INTRO_TAC `m1:int64` `read R8` THEN GHOST_INTRO_TAC `m2:int64` `read R9` THEN GHOST_INTRO_TAC `m3:int64` `read R10` THEN GHOST_INTRO_TAC `m4:int64` `read R11` THEN GHOST_INTRO_TAC `m5:int64` `read R12` THEN GHOST_INTRO_TAC `m6:int64` `read R13` THEN GLOBALIZE_PRECONDITION_TAC THEN ASM_REWRITE_TAC[] THEN ABBREV_TAC `m0:int64 = word(bigdigit n i)` THEN ABBREV_TAC `m = bignum_of_wordlist[m0; m1; m2; m3; m4; m5; m6]` THEN SUBGOAL_THEN `m < 2 EXP 64 * n_384` ASSUME_TAC THENL [EXPAND_TAC "m" THEN ONCE_REWRITE_TAC[bignum_of_wordlist] THEN MP_TAC(SPEC `m0:int64` VAL_BOUND_64) THEN ASM_REWRITE_TAC[n_384] THEN ARITH_TAC; ALL_TAC] THEN SUBGOAL_THEN `highdigits n i MOD n_384 = m MOD n_384` SUBST1_TAC THENL [ONCE_REWRITE_TAC[HIGHDIGITS_STEP] THEN EXPAND_TAC "m" THEN ONCE_REWRITE_TAC[bignum_of_wordlist] THEN EXPAND_TAC "m0" THEN SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN ASM_REWRITE_TAC[] THEN CONV_TAC MOD_DOWN_CONV THEN AP_THM_TAC THEN AP_TERM_TAC THEN ARITH_TAC; ALL_TAC] THEN MP_TAC(SPEC `m:num` n384longredlemma) THEN ASM_REWRITE_TAC[] THEN LET_TAC THEN STRIP_TAC THEN ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN X86_ACCSTEPS_TAC execth [2] (1--2) THEN SUBGOAL_THEN `2 EXP 64 * bitval(read CF s2) + val(read RDX s2) = m DIV 2 EXP 384 + 1` MP_TAC THENL [EXPAND_TAC "m" THEN CONV_TAC(ONCE_DEPTH_CONV BIGNUM_OF_WORDLIST_DIV_CONV) THEN ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN REAL_ARITH_TAC; ASM_REWRITE_TAC[] THEN DISCH_TAC] THEN X86_STEPS_TAC execth (3--4) THEN FIRST_X_ASSUM(MP_TAC o SPEC `word q:int64` o MATCH_MP (MESON[] `!q. read RDX s = q' ==> q' = q ==> read RDX s = q`)) THEN ANTS_TAC THENL [EXPAND_TAC "q" THEN FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC (RAND_CONV o RAND_CONV o LAND_CONV) [SYM th]) THEN POP_ASSUM_LIST(K ALL_TAC) THEN REWRITE_TAC[WORD_OR_MASK] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN SIMP_TAC[VAL_BOUND_64; WORD_VAL; ARITH_RULE `n < 2 EXP 64 ==> MIN n (2 EXP 64 - 1) = n`] THEN REWRITE_TAC[ARITH_RULE `MIN (2 EXP 64 + a) (2 EXP 64 - 1) = 2 EXP 64 - 1`] THEN CONV_TAC NUM_REDUCE_CONV THEN CONV_TAC WORD_REDUCE_CONV; DISCH_TAC THEN VAL_INT64_TAC `q:num`] THEN VAL_INT64_TAC `i + 1` THEN ASSUME_TAC(SPEC `i:num` WORD_INDEX_WRAP) THEN SUBGOAL_THEN `i:num < k` ASSUME_TAC THENL [SIMPLE_ARITH_TAC; ALL_TAC] THEN MP_TAC(SPECL [`k:num`; `x:int64`; `s4:x86state`; `i:num`] BIGDIGIT_BIGNUM_FROM_MEMORY) THEN ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN DISCH_THEN(MP_TAC o AP_TERM `word:num->int64` o SYM) THEN ASM_REWRITE_TAC[WORD_VAL] THEN DISCH_TAC THEN ABBREV_TAC `w:int64 = word q` THEN UNDISCH_THEN `val(w:int64) = q` (SUBST_ALL_TAC o SYM) THEN ACCUMULATOR_POP_ASSUM_LIST(K ALL_TAC o end_itlist CONJ) THEN X86_ACCSTEPS_TAC execth (5--24) (5--24) THEN SUBGOAL_THEN `sum_s24:int64 = word_neg(word(bitval(m < val(w:int64) * n_384))) /\ &(bignum_of_wordlist [sum_s10; sum_s14; sum_s18; sum_s21; sum_s22; sum_s23]) = if m < val w * n_384 then &m - &(val w * n_384) + &2 pow 384 else &m - &(val w * n_384)` STRIP_ASSUME_TAC THENL [MATCH_MP_TAC MASK_AND_VALUE_FROM_CARRY_LT THEN CONJ_TAC THENL [MAP_EVERY UNDISCH_TAC [`val(w:int64) * n_384 <= m + n_384`; `m < val(w:int64) * n_384 + n_384`] THEN REWRITE_TAC[n_384; GSYM REAL_OF_NUM_CLAUSES] THEN REAL_ARITH_TAC; ASM_REWRITE_TAC[bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES]] THEN CONJ_TAC THENL [BOUNDER_TAC[]; CONV_TAC(ONCE_DEPTH_CONV NUM_ADD_CONV)] THEN ASM_REWRITE_TAC[] THEN EXPAND_TAC "m" THEN REWRITE_TAC[bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES; n_384] THEN ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN CONV_TAC(RAND_CONV REAL_POLY_CONV) THEN REPEAT(MATCH_MP_TAC INTEGER_ADD THEN CONJ_TAC) THEN TRY REAL_INTEGER_TAC THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_INTEGER_TAC; ACCUMULATOR_POP_ASSUM_LIST(K ALL_TAC)] THEN X86_ACCSTEPS_TAC execth (31--36) (25--43) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL [CONV_TAC WORD_RULE; DISCH_THEN SUBST1_TAC] THEN ASM_REWRITE_TAC[] THEN CONV_TAC SYM_CONV THEN MATCH_MP_TAC MOD_UNIQ_BALANCED_REAL THEN MAP_EVERY EXISTS_TAC [`val(w:int64)`; `384`] THEN ASM_REWRITE_TAC[] THEN ABBREV_TAC `b <=> m < val(w:int64) * n_384` THEN REWRITE_TAC[REAL_ARITH `m - s - (w - b) * n:real = (m - w * n) + (b * n - s)`] THEN FIRST_ASSUM(MP_TAC o MATCH_MP (MESON[REAL_ADD_RID] `x = (if p then y + z else y) ==> x = y + (if p then z else &0)`)) THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist; n_384] THEN GEN_REWRITE_TAC LAND_CONV [REAL_ARITH `x:real = y + z <=> y = x - z`] THEN DISCH_THEN SUBST1_TAC THEN CONJ_TAC THENL [ARITH_TAC; ALL_TAC] THEN REWRITE_TAC[bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN CONJ_TAC THENL [BOUNDER_TAC[]; ALL_TAC] THEN ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN POP_ASSUM_LIST(K ALL_TAC) THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN CONV_TAC WORD_REDUCE_CONV THEN REAL_INTEGER_TAC;; Correctness of standard ABI version . let BIGNUM_MOD_N384_CORRECT = time prove (`!z k x n pc. nonoverlapping (word pc,0x1cc) (z,48) ==> ensures x86 (\s. bytes_loaded s (word pc) bignum_mod_n384_mc /\ read RIP s = word(pc + 0x7) /\ C_ARGUMENTS [z; k; x] s /\ bignum_from_memory (x,val k) s = n) (\s. read RIP s = word (pc + 0x184) /\ bignum_from_memory (z,6) s = n MOD n_384) (MAYCHANGE [RIP; RSI; RAX; RDX; RCX; RBX; R8; R9; R10; R11; R12; R13; R14] ,, MAYCHANGE SOME_FLAGS ,, MAYCHANGE [memory :> bignum(z,6)])`, tac BIGNUM_MOD_N384_EXEC (curry mk_comb `(+) (pc:num)` o mk_small_numeral));; let BIGNUM_MOD_N384_SUBROUTINE_CORRECT = time prove (`!z k x n pc stackpointer returnaddress. nonoverlapping (word_sub stackpointer (word 32),40) (z,48) /\ ALL (nonoverlapping (word_sub stackpointer (word 32),32)) [(word pc,0x1cc); (x, 8 * val k)] /\ nonoverlapping (word pc,0x1cc) (z,48) ==> ensures x86 (\s. bytes_loaded s (word pc) bignum_mod_n384_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ C_ARGUMENTS [z; k; x] s /\ bignum_from_memory (x,val k) s = n) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ bignum_from_memory (z,6) s = n MOD n_384) (MAYCHANGE [RIP; RSP; RSI; RAX; RDX; RCX; R8; R9; R10; R11] ,, MAYCHANGE SOME_FLAGS ,, MAYCHANGE [memory :> bignum(z,6); memory :> bytes(word_sub stackpointer (word 32),32)])`, X86_ADD_RETURN_STACK_TAC BIGNUM_MOD_N384_EXEC BIGNUM_MOD_N384_CORRECT `[RBX; R12; R13; R14]` 32);; let windows_bignum_mod_n384_mc = define_from_elf "windows_bignum_mod_n384_mc" "x86/p384/bignum_mod_n384.obj";; let WINDOWS_BIGNUM_MOD_N384_CORRECT = time prove (`!z k x n pc. nonoverlapping (word pc,0x1d9) (z,48) ==> ensures x86 (\s. bytes_loaded s (word pc) windows_bignum_mod_n384_mc /\ read RIP s = word(pc + 0x12) /\ C_ARGUMENTS [z; k; x] s /\ bignum_from_memory (x,val k) s = n) (\s. read RIP s = word (pc + 0x18f) /\ bignum_from_memory (z,6) s = n MOD n_384) (MAYCHANGE [RIP; RSI; RAX; RDX; RCX; RBX; R8; R9; R10; R11; R12; R13; R14] ,, MAYCHANGE SOME_FLAGS ,, MAYCHANGE [memory :> bignum(z,6)])`, tac (X86_MK_EXEC_RULE windows_bignum_mod_n384_mc) (curry mk_comb `(+) (pc:num)` o mk_small_numeral o (fun n -> n + 11)));; let WINDOWS_BIGNUM_MOD_N384_SUBROUTINE_CORRECT = time prove (`!z k x n pc stackpointer returnaddress. nonoverlapping (word_sub stackpointer (word 48),56) (z,48) /\ ALL (nonoverlapping (word_sub stackpointer (word 48),48)) [(word pc,0x1d9); (x, 8 * val k)] /\ nonoverlapping (word pc,0x1d9) (z,48) ==> ensures x86 (\s. bytes_loaded s (word pc) windows_bignum_mod_n384_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ WINDOWS_C_ARGUMENTS [z; k; x] s /\ bignum_from_memory (x,val k) s = n) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ bignum_from_memory (z,6) s = n MOD n_384) (MAYCHANGE [RIP; RSP; RAX; RDX; RCX; R8; R9; R10; R11] ,, MAYCHANGE SOME_FLAGS ,, MAYCHANGE [memory :> bignum(z,6); memory :> bytes(word_sub stackpointer (word 48),48)])`, GEN_X86_ADD_RETURN_STACK_TAC (X86_MK_EXEC_RULE windows_bignum_mod_n384_mc) WINDOWS_BIGNUM_MOD_N384_CORRECT `[RDI; RSI; RBX; R12; R13; R14]` 48 (9,7));;
5d202e33436637ddc8302892693cb7fcc7c5f1f14349fef4940ebb2bf0063df9
realworldocaml/book
main.mli
open Import * Tie the knot between [ ] and [ Dune_rules ] . val init : stats:Dune_stats.t option -> sandboxing_preference:Sandbox_mode.t list -> cache_config:Dune_cache.Config.t -> cache_debug_flags:Dune_engine.Cache_debug_flags.t -> unit type build_system = { conf : Dune_load.conf ; contexts : Context.t list ; scontexts : Super_context.t Context_name.Map.t } val get : unit -> build_system Memo.t val find_context_exn : build_system -> name:Context_name.t -> Context.t val find_scontext_exn : build_system -> name:Context_name.t -> Super_context.t
null
https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/dune_/src/dune_rules/main.mli
ocaml
open Import * Tie the knot between [ ] and [ Dune_rules ] . val init : stats:Dune_stats.t option -> sandboxing_preference:Sandbox_mode.t list -> cache_config:Dune_cache.Config.t -> cache_debug_flags:Dune_engine.Cache_debug_flags.t -> unit type build_system = { conf : Dune_load.conf ; contexts : Context.t list ; scontexts : Super_context.t Context_name.Map.t } val get : unit -> build_system Memo.t val find_context_exn : build_system -> name:Context_name.t -> Context.t val find_scontext_exn : build_system -> name:Context_name.t -> Super_context.t
bbc48777a35271dfe9ab6aafa23604b0b3a2d700ce6451d77021ecc7d2b52917
capn-freako/Haskell_ML
Classifiable.hs
-- Class of types amenable to classification, via machine learning. -- Original author : < > Original date : March 1 , 2018 -- Copyright ( c ) 2018 ; all rights reserved World wide . -- -- Note: This code originally came into being, as part of a code clean- up , which started at ' v0.5.0 ' of the Haskell_ML repository . # OPTIONS_GHC -Wall # {-# OPTIONS_GHC -Wno-unused-top-binds #-} # LANGUAGE AllowAmbiguousTypes # # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # | Module : Haskell_ML.Classify . Classifiable Description : A class of types amenable to classification , via machine learning . Copyright : ( c ) , 2018 License : BSD-3 Maintainer : Stability : experimental Portability : ? Module : Haskell_ML.Classify.Classifiable Description : A class of types amenable to classification, via machine learning. Copyright : (c) David Banas, 2018 License : BSD-3 Maintainer : Stability : experimental Portability : ? -} module Haskell_ML.Classify.Classifiable where import GHC.TypeLits import Control.Arrow ((&&&), second) import Data.Attoparsec.Text hiding (take) import Data.Foldable (minimum, maximum) import qualified Data.Text as T import qualified Data.Vector.Sized as VS type V = VS.Vector -- | Class of types amenable to classification, via machine learning. class Classifiable t where type Card t :: Nat type NAtt t :: Nat data Attr t :: * type Sample t :: * type Sample t = (Attr t, t) type AttrVec t :: * type AttrVec t = V (NAtt t) Double type TypeVec t :: * type TypeVec t = V (Card t) Double filtPreds :: V (Card t) (t -> Bool) sampleParser :: Parser (Attr t, t) attrToVec :: Attr t -> V (NAtt t) Double typeToVec :: t -> TypeVec t -- | Read a list of samples from the named file. -- -- Note: Can throw error! readClassifiableData :: Classifiable t => String -> IO [(Attr t, t)] readClassifiableData fname = do ls <- T.lines . T.pack <$> readFile fname return $ f <$> ls where f l = case parseOnly sampleParser l of Left msg -> error msg Right x -> x -- | Split a list of samples into classes and convert to vector form. splitClassifiableData :: (Classifiable t, KnownNat (NAtt t)) => [(AttrVec t, t)] -> V (Card t) [(AttrVec t, TypeVec t)] splitClassifiableData samps = VS.map (\q -> map (second typeToVec) $ filter (q . snd) samps) filtPreds | Rescale all attribute values to fall in [ 0,1 ] . mkAttrsUniform :: KnownNat n => [V n Double] -> [V n Double] mkAttrsUniform [] = [] mkAttrsUniform vs = map (VS.zipWith (*) scales . flip (VS.zipWith (-)) mins) vs where minMaxV = getAttrRanges vs scales = VS.map (\ (mn, mx) -> if mx == mn then 0 else 1 / (mx - mn)) minMaxV mins = VS.map fst minMaxV -- | Find the extremes in a list of attribute vectors. getAttrRanges :: (Traversable g, Applicative f, Ord a) => g (f a) -> f (a,a) getAttrRanges = fmap (minimum &&& maximum) . sequenceA
null
https://raw.githubusercontent.com/capn-freako/Haskell_ML/bfba2aacd700db875a9de3aae88214cfc3171e3a/src/Haskell_ML/Classify/Classifiable.hs
haskell
Class of types amenable to classification, via machine learning. Note: This code originally came into being, as part of a code clean- # OPTIONS_GHC -Wno-unused-top-binds # | Class of types amenable to classification, via machine learning. | Read a list of samples from the named file. Note: Can throw error! | Split a list of samples into classes and convert to vector form. | Find the extremes in a list of attribute vectors.
Original author : < > Original date : March 1 , 2018 Copyright ( c ) 2018 ; all rights reserved World wide . up , which started at ' v0.5.0 ' of the Haskell_ML repository . # OPTIONS_GHC -Wall # # LANGUAGE AllowAmbiguousTypes # # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # | Module : Haskell_ML.Classify . Classifiable Description : A class of types amenable to classification , via machine learning . Copyright : ( c ) , 2018 License : BSD-3 Maintainer : Stability : experimental Portability : ? Module : Haskell_ML.Classify.Classifiable Description : A class of types amenable to classification, via machine learning. Copyright : (c) David Banas, 2018 License : BSD-3 Maintainer : Stability : experimental Portability : ? -} module Haskell_ML.Classify.Classifiable where import GHC.TypeLits import Control.Arrow ((&&&), second) import Data.Attoparsec.Text hiding (take) import Data.Foldable (minimum, maximum) import qualified Data.Text as T import qualified Data.Vector.Sized as VS type V = VS.Vector class Classifiable t where type Card t :: Nat type NAtt t :: Nat data Attr t :: * type Sample t :: * type Sample t = (Attr t, t) type AttrVec t :: * type AttrVec t = V (NAtt t) Double type TypeVec t :: * type TypeVec t = V (Card t) Double filtPreds :: V (Card t) (t -> Bool) sampleParser :: Parser (Attr t, t) attrToVec :: Attr t -> V (NAtt t) Double typeToVec :: t -> TypeVec t readClassifiableData :: Classifiable t => String -> IO [(Attr t, t)] readClassifiableData fname = do ls <- T.lines . T.pack <$> readFile fname return $ f <$> ls where f l = case parseOnly sampleParser l of Left msg -> error msg Right x -> x splitClassifiableData :: (Classifiable t, KnownNat (NAtt t)) => [(AttrVec t, t)] -> V (Card t) [(AttrVec t, TypeVec t)] splitClassifiableData samps = VS.map (\q -> map (second typeToVec) $ filter (q . snd) samps) filtPreds | Rescale all attribute values to fall in [ 0,1 ] . mkAttrsUniform :: KnownNat n => [V n Double] -> [V n Double] mkAttrsUniform [] = [] mkAttrsUniform vs = map (VS.zipWith (*) scales . flip (VS.zipWith (-)) mins) vs where minMaxV = getAttrRanges vs scales = VS.map (\ (mn, mx) -> if mx == mn then 0 else 1 / (mx - mn)) minMaxV mins = VS.map fst minMaxV getAttrRanges :: (Traversable g, Applicative f, Ord a) => g (f a) -> f (a,a) getAttrRanges = fmap (minimum &&& maximum) . sequenceA
a0114dffaee5503334b554dc8fdd781cd6de57e1c380567f35fb9924745b5668
Clozure/ccl-tests
ccase.lsp
;-*- Mode: Lisp -*- Author : Created : Fri Oct 18 21:06:45 2002 ;;;; Contains: Tests of CCASE (in-package :cl-test) (deftest ccase.1 (let ((x 'b)) (ccase x (a 1) (b 2) (c 3))) 2) (deftest ccase.2 (signals-type-error x 1 (ccase x)) t) (deftest ccase.3 (signals-type-error x 1 (ccase x (a 1) (b 2) (c 3))) t) ;;; It is legal to use T or OTHERWISE as key designators ;;; in CCASE forms. They have no special meaning here. (deftest ccase.4 (signals-type-error x 1 (ccase x (t nil))) t) (deftest ccase.5 (signals-type-error x 1 (ccase x (otherwise nil))) t) (deftest ccase.6 (let ((x 'b)) (ccase x ((a z) 1) ((y b w) 2) ((b c) 3))) 2) (deftest ccase.7 (let ((x 'z)) (ccase x ((a b c) 1) ((d e) 2) ((f z g) 3))) 3) (deftest ccase.8 (let ((x (1+ most-positive-fixnum))) (ccase x (#.(1+ most-positive-fixnum) 'a))) a) (deftest ccase.9 (signals-type-error x nil (ccase x (nil 'a))) t) (deftest ccase.10 (let (x) (ccase x ((nil) 'a))) a) (deftest ccase.11 (let ((x 'a)) (ccase x (b 0) (a (values 1 2 3)) (c nil))) 1 2 3) (deftest ccase.12 (signals-type-error x t (ccase x (a 10))) t) (deftest ccase.13 (let ((x t)) (ccase x ((t) 10) (t 20))) 10) (deftest ccase.14 (let ((x (list 'a 'b))) (eval `(let ((y (quote ,x))) (ccase y ((,x) 1) (a 2))))) 1) (deftest ccase.15 (signals-type-error x 'otherwise (ccase x ((t) 10))) t) (deftest ccase.16 (signals-type-error x t (ccase x ((otherwise) 10))) t) (deftest ccase.17 (signals-type-error x 'a (ccase x (b 0) (c 1) (otherwise 2))) t) (deftest ccase.19 (signals-type-error x 'a (ccase x (b 0) (c 1) ((t) 2))) t) (deftest ccase.20 (let ((x #\a)) (ccase x ((#\b #\c) 10) ((#\d #\e #\A) 20) (() 30) ((#\z #\a #\y) 40))) 40) (deftest ccase.21 (let ((x 1)) (ccase x (1 (values)) (2 'a)))) (deftest ccase.23 (let ((x 1)) (ccase x (1 (values 'a 'b 'c)))) a b c) ;;; Show that the key expression is evaluated only once. (deftest ccase.25 (let ((a (vector 'a 'b 'c 'd 'e)) (i 1)) (values (ccase (aref a (incf i)) (a 1) (b 2) (c 3) (d 4)) i)) 3 2) Repeated keys are allowed ( all but the first are ignored ) (deftest ccase.26 (let ((x 'b)) (ccase x ((a b c) 10) (b 20))) 10) (deftest ccase.27 (let ((x 'b)) (ccase x (b 20) ((a b c) 10))) 20) (deftest ccase.28 (let ((x 'b)) (ccase x (b 20) (b 10) (d 0))) 20) There are implicit progns (deftest ccase.29 (let ((x nil) (y 2)) (values (ccase y (1 (setq x 'a) 'w) (2 (setq x 'b) 'y) (3 (setq x 'c) 'z)) x)) y b) (deftest ccase.30 (let ((x 'a)) (ccase x (a))) nil) (deftest ccase.31 (handler-bind ((type-error #'(lambda (c) (store-value 7 c)))) (let ((x 0)) (ccase x (1 :bad) (7 :good) (2 nil)))) :good) ;;; No implicit tagbody (deftest ccase.32 (block done (tagbody (let ((x 'a)) (ccase x (a (go 10) 10 (return-from done 'bad)))) 10 (return-from done 'good))) good) ;;; Test that explicit calls to macroexpand in subforms ;;; are done in the correct environment (deftest ccase.33 (let ((x :b)) (macrolet ((%m (z) z)) (ccase (expand-in-current-env (%m x)) (:a :bad1) (:b :good) (:c :bad2)))) :good) ;;; (deftest ccase.error.1 ;;; (signals-error (ccase) program-error) ;;; t) (deftest ccase.error.1 (signals-error (funcall (macro-function 'ccase)) program-error) t) (deftest ccase.error.2 (signals-error (funcall (macro-function 'ccase) '(ccase t)) program-error) t) (deftest ccase.error.3 (signals-error (funcall (macro-function 'ccase) '(ccase t) nil nil) program-error) t)
null
https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/ccase.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests of CCASE It is legal to use T or OTHERWISE as key designators in CCASE forms. They have no special meaning here. Show that the key expression is evaluated only once. No implicit tagbody Test that explicit calls to macroexpand in subforms are done in the correct environment (deftest ccase.error.1 (signals-error (ccase) program-error) t)
Author : Created : Fri Oct 18 21:06:45 2002 (in-package :cl-test) (deftest ccase.1 (let ((x 'b)) (ccase x (a 1) (b 2) (c 3))) 2) (deftest ccase.2 (signals-type-error x 1 (ccase x)) t) (deftest ccase.3 (signals-type-error x 1 (ccase x (a 1) (b 2) (c 3))) t) (deftest ccase.4 (signals-type-error x 1 (ccase x (t nil))) t) (deftest ccase.5 (signals-type-error x 1 (ccase x (otherwise nil))) t) (deftest ccase.6 (let ((x 'b)) (ccase x ((a z) 1) ((y b w) 2) ((b c) 3))) 2) (deftest ccase.7 (let ((x 'z)) (ccase x ((a b c) 1) ((d e) 2) ((f z g) 3))) 3) (deftest ccase.8 (let ((x (1+ most-positive-fixnum))) (ccase x (#.(1+ most-positive-fixnum) 'a))) a) (deftest ccase.9 (signals-type-error x nil (ccase x (nil 'a))) t) (deftest ccase.10 (let (x) (ccase x ((nil) 'a))) a) (deftest ccase.11 (let ((x 'a)) (ccase x (b 0) (a (values 1 2 3)) (c nil))) 1 2 3) (deftest ccase.12 (signals-type-error x t (ccase x (a 10))) t) (deftest ccase.13 (let ((x t)) (ccase x ((t) 10) (t 20))) 10) (deftest ccase.14 (let ((x (list 'a 'b))) (eval `(let ((y (quote ,x))) (ccase y ((,x) 1) (a 2))))) 1) (deftest ccase.15 (signals-type-error x 'otherwise (ccase x ((t) 10))) t) (deftest ccase.16 (signals-type-error x t (ccase x ((otherwise) 10))) t) (deftest ccase.17 (signals-type-error x 'a (ccase x (b 0) (c 1) (otherwise 2))) t) (deftest ccase.19 (signals-type-error x 'a (ccase x (b 0) (c 1) ((t) 2))) t) (deftest ccase.20 (let ((x #\a)) (ccase x ((#\b #\c) 10) ((#\d #\e #\A) 20) (() 30) ((#\z #\a #\y) 40))) 40) (deftest ccase.21 (let ((x 1)) (ccase x (1 (values)) (2 'a)))) (deftest ccase.23 (let ((x 1)) (ccase x (1 (values 'a 'b 'c)))) a b c) (deftest ccase.25 (let ((a (vector 'a 'b 'c 'd 'e)) (i 1)) (values (ccase (aref a (incf i)) (a 1) (b 2) (c 3) (d 4)) i)) 3 2) Repeated keys are allowed ( all but the first are ignored ) (deftest ccase.26 (let ((x 'b)) (ccase x ((a b c) 10) (b 20))) 10) (deftest ccase.27 (let ((x 'b)) (ccase x (b 20) ((a b c) 10))) 20) (deftest ccase.28 (let ((x 'b)) (ccase x (b 20) (b 10) (d 0))) 20) There are implicit progns (deftest ccase.29 (let ((x nil) (y 2)) (values (ccase y (1 (setq x 'a) 'w) (2 (setq x 'b) 'y) (3 (setq x 'c) 'z)) x)) y b) (deftest ccase.30 (let ((x 'a)) (ccase x (a))) nil) (deftest ccase.31 (handler-bind ((type-error #'(lambda (c) (store-value 7 c)))) (let ((x 0)) (ccase x (1 :bad) (7 :good) (2 nil)))) :good) (deftest ccase.32 (block done (tagbody (let ((x 'a)) (ccase x (a (go 10) 10 (return-from done 'bad)))) 10 (return-from done 'good))) good) (deftest ccase.33 (let ((x :b)) (macrolet ((%m (z) z)) (ccase (expand-in-current-env (%m x)) (:a :bad1) (:b :good) (:c :bad2)))) :good) (deftest ccase.error.1 (signals-error (funcall (macro-function 'ccase)) program-error) t) (deftest ccase.error.2 (signals-error (funcall (macro-function 'ccase) '(ccase t)) program-error) t) (deftest ccase.error.3 (signals-error (funcall (macro-function 'ccase) '(ccase t) nil nil) program-error) t)
4336b9fb9a93c73e6e66f58e855ef280ed9619b198805eba628f3f08ac67dbb0
seckcoder/iu_c311
interp.rkt
#lang racket (require eopl/datatype "parser.rkt" "../base/utils.rkt" "../types/type.rkt" "../types/store.rkt" "env.rkt") (define-datatype proc proc? (closure (vars (list-of symbol?)) (body expression?) (env environment?)) ) (define apply-proc (lambda (rator rands) (cases proc rator (closure (vars body env) (let ((new-env (extend-envs vars (newrefs rands) env))) (>val (interp body new-env)))) ))) (define extend-envs-recursively (lambda (p-names proc-exps env) (let* ((proc-refs (mapn (lambda (i) (newref i)) (length proc-exps))) (new-env (extend-envs p-names proc-refs env))) (for-each (lambda (proc-ref proc) (setref! proc-ref proc)) proc-refs (map (lambda (proc) (>val (interp proc env))) proc-exps)) new-env))) (define >val car) (define >env cadr) (define (interp-multi-exps exps env) (foldl (lambda (exp acc) (interp exp (>env acc))) (list (void) env) exps)) (define (interp exp env) (cases expression exp (const-exp (cst) `(,cst ,env)) (var-exp (var) `(,(deref (apply-env env var)) ,env)) (quote-exp (sexp) `(,sexp ,env)) (op-exp (op rand-exps) `(,(apply-base-ns op (map (lambda (exp) (>val (interp exp env))) rand-exps)) ,env)) (call-exp (rator-exp rand-exps) (match (map (lambda (exp) (>val (interp exp env))) (cons rator-exp rand-exps)) [(list rator rands ...) `(,(apply-proc rator rands) ,env)])) (if-exp (test then else) (if (interp test env) `(,(>val (interp then env)) env) `(,(>val (interp else env)) env))) (lambda-exp (vars body) `(,(closure vars body env) ,env)) (compound-exp (exps) (interp-multi-exps exps env)) (letrec-exp (p-names procs body) (let ((new-env (extend-envs-recursively p-names procs env))) `(,(>val (interp body new-env)) ,env))) (set-exp (var val) (list (setref! (apply-env env var) (>val (interp val env))) env)) (define-exp (var val) (list (void) (extend-env var (newref (>val (interp val env))) env))) (module-exp (mname vars types bodies) (match (interp-multi-exps bodies env) [(list _ new-env) (list (void) (extend-env mname (newref (mod vars new-env)) env))])) (import-exp (mname) (list (void) (import-mod mname env))) )) (define mod list) (define (mod-bindings m) (match m [(list vars env) (list vars (map (lambda (var) (apply-env env var)) vars))])) ; import mod mname and return a new env (define (import-mod mname env) (let ((mod (deref (apply-env env mname)))) (match (mod-bindings mod) [(list vars refs) (extend-envs (map (lambda (var) (sym-append mname ': var)) vars) refs env)]))) (define (initial-env) (empty-env)) (define (test-prog exp) (initialize-store!) (>val (interp (parse exp) (initial-env)))) (module+ test (check = (test-prog '(begin (define a 3) (module m1 (sig (u int) (f ((int) int))) (body ; module variable. (define u a) (set! u 4) (define f (lambda (v) (+ u v))) ; this expression has no effect on the whole module (let ((v a)) (define f (lambda (v) (* u v))) (f v)) (define g (lambda () u)) )) (import m1) (module m2 (sig (v int) (f ((int) int))) (body (define v a) (define f (lambda (v) (* v v))))) (set! m1:u 5) (import m2) (+ (m1:f m1:u) (m2:f m2:v)) )) 19))
null
https://raw.githubusercontent.com/seckcoder/iu_c311/a1215983b6ab08df32058ef1e089cb294419e567/racket/module/interp.rkt
racket
import mod mname and return a new env module variable. this expression has no effect on the whole module
#lang racket (require eopl/datatype "parser.rkt" "../base/utils.rkt" "../types/type.rkt" "../types/store.rkt" "env.rkt") (define-datatype proc proc? (closure (vars (list-of symbol?)) (body expression?) (env environment?)) ) (define apply-proc (lambda (rator rands) (cases proc rator (closure (vars body env) (let ((new-env (extend-envs vars (newrefs rands) env))) (>val (interp body new-env)))) ))) (define extend-envs-recursively (lambda (p-names proc-exps env) (let* ((proc-refs (mapn (lambda (i) (newref i)) (length proc-exps))) (new-env (extend-envs p-names proc-refs env))) (for-each (lambda (proc-ref proc) (setref! proc-ref proc)) proc-refs (map (lambda (proc) (>val (interp proc env))) proc-exps)) new-env))) (define >val car) (define >env cadr) (define (interp-multi-exps exps env) (foldl (lambda (exp acc) (interp exp (>env acc))) (list (void) env) exps)) (define (interp exp env) (cases expression exp (const-exp (cst) `(,cst ,env)) (var-exp (var) `(,(deref (apply-env env var)) ,env)) (quote-exp (sexp) `(,sexp ,env)) (op-exp (op rand-exps) `(,(apply-base-ns op (map (lambda (exp) (>val (interp exp env))) rand-exps)) ,env)) (call-exp (rator-exp rand-exps) (match (map (lambda (exp) (>val (interp exp env))) (cons rator-exp rand-exps)) [(list rator rands ...) `(,(apply-proc rator rands) ,env)])) (if-exp (test then else) (if (interp test env) `(,(>val (interp then env)) env) `(,(>val (interp else env)) env))) (lambda-exp (vars body) `(,(closure vars body env) ,env)) (compound-exp (exps) (interp-multi-exps exps env)) (letrec-exp (p-names procs body) (let ((new-env (extend-envs-recursively p-names procs env))) `(,(>val (interp body new-env)) ,env))) (set-exp (var val) (list (setref! (apply-env env var) (>val (interp val env))) env)) (define-exp (var val) (list (void) (extend-env var (newref (>val (interp val env))) env))) (module-exp (mname vars types bodies) (match (interp-multi-exps bodies env) [(list _ new-env) (list (void) (extend-env mname (newref (mod vars new-env)) env))])) (import-exp (mname) (list (void) (import-mod mname env))) )) (define mod list) (define (mod-bindings m) (match m [(list vars env) (list vars (map (lambda (var) (apply-env env var)) vars))])) (define (import-mod mname env) (let ((mod (deref (apply-env env mname)))) (match (mod-bindings mod) [(list vars refs) (extend-envs (map (lambda (var) (sym-append mname ': var)) vars) refs env)]))) (define (initial-env) (empty-env)) (define (test-prog exp) (initialize-store!) (>val (interp (parse exp) (initial-env)))) (module+ test (check = (test-prog '(begin (define a 3) (module m1 (sig (u int) (f ((int) int))) (body (define u a) (set! u 4) (define f (lambda (v) (+ u v))) (let ((v a)) (define f (lambda (v) (* u v))) (f v)) (define g (lambda () u)) )) (import m1) (module m2 (sig (v int) (f ((int) int))) (body (define v a) (define f (lambda (v) (* v v))))) (set! m1:u 5) (import m2) (+ (m1:f m1:u) (m2:f m2:v)) )) 19))
dcd1e1ed4c5cc0dc4864f3ef390aaeb3ac5bbe3b18a639a664dd54610234ad36
hoplon/hoplon
svg.cljs
(ns hoplon.svg (:refer-clojure :exclude [symbol filter mask set use]) (:require [hoplon.core :refer [parse-args do!]])) (defmethod do! :xlink/default [elem kw val] (let [xlink ""] (.setAttributeNS elem xlink (name kw) val))) (derive :xlink/type :xlink/default) (derive :xlink/href :xlink/default) (derive :xlink/role :xlink/default) (derive :xlink/arcrole :xlink/default) (derive :xlink/title :xlink/default) (derive :xlink/show :xlink/default) (derive :xlink/actuate :xlink/default) (derive :xlink/label :xlink/default) (derive :xlink/from :xlink/default) (derive :xlink/to :xlink/default) (defn mksvg [tag] (fn [& args] (let [[attr kids] (parse-args args) xmlns "" elem (.createElementNS js/document xmlns tag)] (elem attr kids)))) (def a (mksvg "a")) (def altGlyph (mksvg "altGlyph")) (def altGlyphDef (mksvg "altGlyphDef")) (def altGlyphItem (mksvg "altGlyphItem")) (def animate (mksvg "animate")) (def animateColor (mksvg "animateColor")) (def animateMotion (mksvg "animateMotion")) (def animateTransform (mksvg "animateTransform")) (def circle (mksvg "circle")) (def clipPath (mksvg "clipPath")) (def color-profile (mksvg "color-profile")) (def cursor (mksvg "cursor")) (def defs (mksvg "defs")) (def desc (mksvg "desc")) (def ellipse (mksvg "ellipse")) (def feBlend (mksvg "feBlend")) (def feColorMatrix (mksvg "feColorMatrix")) (def feComponentTransfer (mksvg "feComponentTransfer")) (def feComposite (mksvg "feComposite")) (def feConvolveMatrix (mksvg "feConvolveMatrix")) (def feDiffuseLighting (mksvg "feDiffuseLighting")) (def feDisplacementMap (mksvg "feDisplacementMap")) (def feDistantLight (mksvg "feDistantLight")) (def feFlood (mksvg "feFlood")) (def feFuncA (mksvg "feFuncA")) (def feFuncB (mksvg "feFuncB")) (def feFuncG (mksvg "feFuncG")) (def feFuncR (mksvg "feFuncR")) (def feGaussianBlur (mksvg "feGaussianBlur")) (def feImage (mksvg "feImage")) (def feMerge (mksvg "feMerge")) (def feMergeNode (mksvg "feMergeNode")) (def feMorphology (mksvg "feMorphology")) (def feOffset (mksvg "feOffset")) (def fePointLight (mksvg "fePointLight")) (def feSpecularLighting (mksvg "feSpecularLighting")) (def feSpotLight (mksvg "feSpotLight")) (def feTile (mksvg "feTile")) (def feTurbulence (mksvg "feTurbulence")) (def filter (mksvg "filter")) (def font (mksvg "font")) (def font-face (mksvg "font-face")) (def font-face-format (mksvg "font-face-format")) (def font-face-name (mksvg "font-face-name")) (def font-face-src (mksvg "font-face-src")) (def font-face-uri (mksvg "font-face-uri")) (def foreignObject (mksvg "foreignObject")) (def g (mksvg "g")) (def glyph (mksvg "glyph")) (def glyphRef (mksvg "glyphRef")) (def hkern (mksvg "hkern")) (def image (mksvg "image")) (def line (mksvg "line")) (def linearGradient (mksvg "linearGradient")) (def marker (mksvg "marker")) (def mask (mksvg "mask")) (def metadata (mksvg "metadata")) (def missing-glyph (mksvg "missing-glyph")) (def mpath (mksvg "mpath")) (def path (mksvg "path")) (def pattern (mksvg "pattern")) (def polygon (mksvg "polygon")) (def polyline (mksvg "polyline")) (def radialGradient (mksvg "radialGradient")) (def rect (mksvg "rect")) (def script (mksvg "script")) (def set (mksvg "set")) (def stop (mksvg "stop")) (def style (mksvg "style")) (def svg (mksvg "svg")) (def switch (mksvg "switch")) (def symbol (mksvg "symbol")) (def text (mksvg "text")) (def textPath (mksvg "textPath")) (def title (mksvg "title")) (def tref (mksvg "tref")) (def tspan (mksvg "tspan")) (def use (mksvg "use")) (def view (mksvg "view")) (def vkern (mksvg "vkern"))
null
https://raw.githubusercontent.com/hoplon/hoplon/2f886d10d942e72e4565dfbb997487e90c8d5e3a/src/hoplon/svg.cljs
clojure
(ns hoplon.svg (:refer-clojure :exclude [symbol filter mask set use]) (:require [hoplon.core :refer [parse-args do!]])) (defmethod do! :xlink/default [elem kw val] (let [xlink ""] (.setAttributeNS elem xlink (name kw) val))) (derive :xlink/type :xlink/default) (derive :xlink/href :xlink/default) (derive :xlink/role :xlink/default) (derive :xlink/arcrole :xlink/default) (derive :xlink/title :xlink/default) (derive :xlink/show :xlink/default) (derive :xlink/actuate :xlink/default) (derive :xlink/label :xlink/default) (derive :xlink/from :xlink/default) (derive :xlink/to :xlink/default) (defn mksvg [tag] (fn [& args] (let [[attr kids] (parse-args args) xmlns "" elem (.createElementNS js/document xmlns tag)] (elem attr kids)))) (def a (mksvg "a")) (def altGlyph (mksvg "altGlyph")) (def altGlyphDef (mksvg "altGlyphDef")) (def altGlyphItem (mksvg "altGlyphItem")) (def animate (mksvg "animate")) (def animateColor (mksvg "animateColor")) (def animateMotion (mksvg "animateMotion")) (def animateTransform (mksvg "animateTransform")) (def circle (mksvg "circle")) (def clipPath (mksvg "clipPath")) (def color-profile (mksvg "color-profile")) (def cursor (mksvg "cursor")) (def defs (mksvg "defs")) (def desc (mksvg "desc")) (def ellipse (mksvg "ellipse")) (def feBlend (mksvg "feBlend")) (def feColorMatrix (mksvg "feColorMatrix")) (def feComponentTransfer (mksvg "feComponentTransfer")) (def feComposite (mksvg "feComposite")) (def feConvolveMatrix (mksvg "feConvolveMatrix")) (def feDiffuseLighting (mksvg "feDiffuseLighting")) (def feDisplacementMap (mksvg "feDisplacementMap")) (def feDistantLight (mksvg "feDistantLight")) (def feFlood (mksvg "feFlood")) (def feFuncA (mksvg "feFuncA")) (def feFuncB (mksvg "feFuncB")) (def feFuncG (mksvg "feFuncG")) (def feFuncR (mksvg "feFuncR")) (def feGaussianBlur (mksvg "feGaussianBlur")) (def feImage (mksvg "feImage")) (def feMerge (mksvg "feMerge")) (def feMergeNode (mksvg "feMergeNode")) (def feMorphology (mksvg "feMorphology")) (def feOffset (mksvg "feOffset")) (def fePointLight (mksvg "fePointLight")) (def feSpecularLighting (mksvg "feSpecularLighting")) (def feSpotLight (mksvg "feSpotLight")) (def feTile (mksvg "feTile")) (def feTurbulence (mksvg "feTurbulence")) (def filter (mksvg "filter")) (def font (mksvg "font")) (def font-face (mksvg "font-face")) (def font-face-format (mksvg "font-face-format")) (def font-face-name (mksvg "font-face-name")) (def font-face-src (mksvg "font-face-src")) (def font-face-uri (mksvg "font-face-uri")) (def foreignObject (mksvg "foreignObject")) (def g (mksvg "g")) (def glyph (mksvg "glyph")) (def glyphRef (mksvg "glyphRef")) (def hkern (mksvg "hkern")) (def image (mksvg "image")) (def line (mksvg "line")) (def linearGradient (mksvg "linearGradient")) (def marker (mksvg "marker")) (def mask (mksvg "mask")) (def metadata (mksvg "metadata")) (def missing-glyph (mksvg "missing-glyph")) (def mpath (mksvg "mpath")) (def path (mksvg "path")) (def pattern (mksvg "pattern")) (def polygon (mksvg "polygon")) (def polyline (mksvg "polyline")) (def radialGradient (mksvg "radialGradient")) (def rect (mksvg "rect")) (def script (mksvg "script")) (def set (mksvg "set")) (def stop (mksvg "stop")) (def style (mksvg "style")) (def svg (mksvg "svg")) (def switch (mksvg "switch")) (def symbol (mksvg "symbol")) (def text (mksvg "text")) (def textPath (mksvg "textPath")) (def title (mksvg "title")) (def tref (mksvg "tref")) (def tspan (mksvg "tspan")) (def use (mksvg "use")) (def view (mksvg "view")) (def vkern (mksvg "vkern"))
f55c138b15a2e840d44fb15fef4bc13a2c58819cf69d0627d515e5b4c40b2116
finnishtransportagency/harja
erilliskustannus.cljc
(ns harja.domain.erilliskustannus "Erilliskustannuksiin (lähinnä bonuksiin) liittyvien asioiden domain määritykset:" (:require [clojure.spec.alpha :as s] [harja.domain.muokkaustiedot :as m] [harja.domain.tierekisteri :as tr] [harja.domain.organisaatio :as o] #?@(:clj [[harja.kyselyt.specql-db :refer [define-tables]]] :cljs [[specql.impl.registry]])) #?(:cljs (:require-macros [harja.kyselyt.specql-db :refer [define-tables]]))) (define-tables ["erilliskustannus" ::erilliskustannus harja.domain.muokkaustiedot/muokkaustiedot harja.domain.muokkaustiedot/poistettu?-sarake])
null
https://raw.githubusercontent.com/finnishtransportagency/harja/302b08738881a33ba3f66118db55647f3951f193/src/cljc/harja/domain/erilliskustannus.cljc
clojure
(ns harja.domain.erilliskustannus "Erilliskustannuksiin (lähinnä bonuksiin) liittyvien asioiden domain määritykset:" (:require [clojure.spec.alpha :as s] [harja.domain.muokkaustiedot :as m] [harja.domain.tierekisteri :as tr] [harja.domain.organisaatio :as o] #?@(:clj [[harja.kyselyt.specql-db :refer [define-tables]]] :cljs [[specql.impl.registry]])) #?(:cljs (:require-macros [harja.kyselyt.specql-db :refer [define-tables]]))) (define-tables ["erilliskustannus" ::erilliskustannus harja.domain.muokkaustiedot/muokkaustiedot harja.domain.muokkaustiedot/poistettu?-sarake])
3a297d87d45bf80227f37de278fef583a0231fa3ecf354401aaf82dd3a65ed49
shentufoundation/deepsea
LowValues.ml
open Integers type coq_val = | Vunit | Vint of Int256.int | Vhash of coq_val | Vhash2 of coq_val * coq_val
null
https://raw.githubusercontent.com/shentufoundation/deepsea/970576a97c8992655ed2f173f576502d73b827e1/src/backend/extraction/LowValues.ml
ocaml
open Integers type coq_val = | Vunit | Vint of Int256.int | Vhash of coq_val | Vhash2 of coq_val * coq_val
82ac901d50e460f146ddbf6c2f953d104268e12076ef0cb83c174299963eb3c3
UU-ComputerScience/uhc
sum.hs
data Bool = False | True data ''[]'' a = a : [a] | ''[]'' foreign import ccall "primAddInt" (+) :: Int -> Int -> Int foreign import ccall "primGtInt" (>) :: Int -> Int -> Bool upto m n | m > n = [] | True = m : upto (m + 1) n sum [] = 0 sum (n:ns) = n + sum ns main = sum (upto 1 10)
null
https://raw.githubusercontent.com/UU-ComputerScience/uhc/f2b94a90d26e2093d84044b3832a9a3e3c36b129/EHC/test/grinc/sum.hs
haskell
data Bool = False | True data ''[]'' a = a : [a] | ''[]'' foreign import ccall "primAddInt" (+) :: Int -> Int -> Int foreign import ccall "primGtInt" (>) :: Int -> Int -> Bool upto m n | m > n = [] | True = m : upto (m + 1) n sum [] = 0 sum (n:ns) = n + sum ns main = sum (upto 1 10)
6bc47ef36fdd9b100cf6fa60545a09e76cc14dbdb7ac1ea672d4107d6d44525f
Perry961002/SICP
HeapSort.scm
(define (MaxHeapify heap root len) (define (Left i) (+ (* i 2) 1)) (define (Right i) (* (+ i 1) 2)) (let ((left (Left root)) (right (Right root)) (largest root)) (begin (if (and (<= left len) (> (vector-ref heap left) (vector-ref heap root))) (set! largest left)) (if (and (<= right len) (> (vector-ref heap right) (vector-ref heap largest))) (set! largest right)) (if (not (= largest root)) (let ((head (vector-ref heap root))) (begin (vector-set! heap root (vector-ref heap largest)) (vector-set! heap largest head) (MaxHeapify heap largest len))))))) 对向量heap自底向上建大根堆 (define (BuildMaxHeap heap) (define (build-iter i) (if (>= i 0) (begin (MaxHeapify heap i (- (vector-length heap) 1)) (build-iter (- i 1))))) (build-iter (- (div (vector-length heap) 2) 1))) 堆排序 (define (HeapSort heap) (define (sort-iter i) (if (>= i 1) (let ((max (vector-ref heap 0))) (begin (vector-set! heap 0 (vector-ref heap i)) (vector-set! heap i max) (MaxHeapify heap 0 (- i 1)) (sort-iter (- i 1)))))) (BuildMaxHeap heap) (sort-iter (- (vector-length heap) 1)) heap) : (define heap (vector 1 5 7 8 9 6 3 4 5 1 0 89 45 15 20 17 895 1 4 56 287 45 369 45 98 92 37 15 620 784 562 15 37 66)) # ( 0 1 1 1 3 4 4 5 5 6 7 8 9 15 15 15 17 20 37 37 45 45 45 56 66 89 92 98 287 369 562 620 784 895 )
null
https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/little%20practice/HeapSort.scm
scheme
(define (MaxHeapify heap root len) (define (Left i) (+ (* i 2) 1)) (define (Right i) (* (+ i 1) 2)) (let ((left (Left root)) (right (Right root)) (largest root)) (begin (if (and (<= left len) (> (vector-ref heap left) (vector-ref heap root))) (set! largest left)) (if (and (<= right len) (> (vector-ref heap right) (vector-ref heap largest))) (set! largest right)) (if (not (= largest root)) (let ((head (vector-ref heap root))) (begin (vector-set! heap root (vector-ref heap largest)) (vector-set! heap largest head) (MaxHeapify heap largest len))))))) 对向量heap自底向上建大根堆 (define (BuildMaxHeap heap) (define (build-iter i) (if (>= i 0) (begin (MaxHeapify heap i (- (vector-length heap) 1)) (build-iter (- i 1))))) (build-iter (- (div (vector-length heap) 2) 1))) 堆排序 (define (HeapSort heap) (define (sort-iter i) (if (>= i 1) (let ((max (vector-ref heap 0))) (begin (vector-set! heap 0 (vector-ref heap i)) (vector-set! heap i max) (MaxHeapify heap 0 (- i 1)) (sort-iter (- i 1)))))) (BuildMaxHeap heap) (sort-iter (- (vector-length heap) 1)) heap) : (define heap (vector 1 5 7 8 9 6 3 4 5 1 0 89 45 15 20 17 895 1 4 56 287 45 369 45 98 92 37 15 620 784 562 15 37 66)) # ( 0 1 1 1 3 4 4 5 5 6 7 8 9 15 15 15 17 20 37 37 45 45 45 56 66 89 92 98 287 369 562 620 784 895 )
03386230590543d4b815f73d4b69b2ffd23962fb2a4adbfc3c32b22ffdbdb7f8
elnewfie/lslforge
Error.hs
We encountered problem that LSLForge process hung up when start up . I knew it was caused by difference of ' fail ' for Either monad behavier between base version prior 4.3 and later . Prior 4.3 , fail returns Left e , but later throws exception . Language . Lsl . Internal . Util.lookupM is called in 3 monads , Maybe , Either and WorldE , using to search various things . In a case to search module name from library list given by Eclipse , -- lookupM calls fail when module name not found, it 's ok on GHC 6.10.4 because it same to Left , but GHC using base 4.3 or later ( including 8.0.2 ) throws exception and cause LSLForge process to error - exit . I copied Error class from GHC library to reproduce old ' fail ' method . By module Control.Monad.Outdated.Error ( Error(..), ErrorList(..) ) where import Control.Monad.Fail(MonadFail(..)) This class was copied from Control . Monad . Trans . Error -- which will be removed from standard library. -- But we still need this class for fail on Either monad. class Error e where noMsg :: e noMsg = strMsg "" strMsg :: String -> e strMsg _ = noMsg instance ErrorList a => Error [a] where strMsg = listMsg class ErrorList a where listMsg :: String -> [a] instance ErrorList Char where listMsg = id -- This is core to reproduce old Either fail. instance Error e => MonadFail (Either e) where fail s = Left $ strMsg s
null
https://raw.githubusercontent.com/elnewfie/lslforge/27eb84231c53fffba6bdb0db67bde81c1c12dbb9/lslforge/haskell/src/Control/Monad/Outdated/Error.hs
haskell
lookupM calls fail when module name not found, which will be removed from standard library. But we still need this class for fail on Either monad. This is core to reproduce old Either fail.
We encountered problem that LSLForge process hung up when start up . I knew it was caused by difference of ' fail ' for Either monad behavier between base version prior 4.3 and later . Prior 4.3 , fail returns Left e , but later throws exception . Language . Lsl . Internal . Util.lookupM is called in 3 monads , Maybe , Either and WorldE , using to search various things . In a case to search module name from library list given by Eclipse , it 's ok on GHC 6.10.4 because it same to Left , but GHC using base 4.3 or later ( including 8.0.2 ) throws exception and cause LSLForge process to error - exit . I copied Error class from GHC library to reproduce old ' fail ' method . By module Control.Monad.Outdated.Error ( Error(..), ErrorList(..) ) where import Control.Monad.Fail(MonadFail(..)) This class was copied from Control . Monad . Trans . Error class Error e where noMsg :: e noMsg = strMsg "" strMsg :: String -> e strMsg _ = noMsg instance ErrorList a => Error [a] where strMsg = listMsg class ErrorList a where listMsg :: String -> [a] instance ErrorList Char where listMsg = id instance Error e => MonadFail (Either e) where fail s = Left $ strMsg s
5ed1e6c48f06d4e9ca4ba3603f9f9663f71a3648ff33554fb19f18198a4c3166
rm-hull/project-euler
binomial.clj
(ns util.binomial) (def pascals-triangle (let [seed 1N] (letfn [(next-row [xs] (cons seed (map (partial apply +) (partition-all 2 1 xs)))) (rows-seq [xs] (lazy-seq (cons xs (rows-seq (next-row xs)))))] (rows-seq (list seed))))) (defn choose "The number of ways of picking k unordered outcomes from n possibilities." [n k] (if (>= n k) (-> pascals-triangle (nth n) (nth k))))
null
https://raw.githubusercontent.com/rm-hull/project-euler/04e689e87a1844cfd83229bb4628051e3ac6a325/src/util/binomial.clj
clojure
(ns util.binomial) (def pascals-triangle (let [seed 1N] (letfn [(next-row [xs] (cons seed (map (partial apply +) (partition-all 2 1 xs)))) (rows-seq [xs] (lazy-seq (cons xs (rows-seq (next-row xs)))))] (rows-seq (list seed))))) (defn choose "The number of ways of picking k unordered outcomes from n possibilities." [n k] (if (>= n k) (-> pascals-triangle (nth n) (nth k))))
48f11c91a2de5faf18de84078b1e97ff44e42a8f6bc38f740abd8e64ee64f51c
troydm/edda
ParserTest.hs
{-# LANGUAGE OverloadedStrings #-} module EDDA.Schema.ParserTest where import Test.HUnit import Data.Maybe (fromJust,isJust) import Data.Aeson import Data.Aeson.Types import qualified Data.ByteString.Char8 as C import qualified Data.HashMap.Strict as HM import Control.Monad.Trans.Reader import Data.Time.Format (formatTime) import EDDA.Schema.CommodityV2 (parseCommodity) import EDDA.Schema.Util import EDDA.Schema.Parser import EDDA.Types import EDDA.Test.Util test1 :: Test test1 = TestCase $ do let timestamp = "{ \"timestamp\" : \"2016-08-11T20:06:54-05:00\" }" let v = fromJust $ (decodeStrict' timestamp :: Maybe Value) let d = getTimestamp v "timestamp" assertBool "timestamp not parsed" (isJust d) let dt = fromJust d assertEqual "date" "2016-08-12 01:06:54 UTC" (show dt) test2 :: Test test2 = TestCase $ do let timestamp = "{ \"timestamp\" : \"2016-08-11T20:6:54-05:00\" }" let v = fromJust $ (decodeStrict' timestamp :: Maybe Value) let d = getTimestamp v "timestamp" assertBool "timestamp not parsed" (isJust d) let dt = fromJust d assertEqual "date" "2016-08-12 01:06:54 UTC" (show dt) parserTests = [TestLabel "parser timestamp 1 test" test1, TestLabel "parser timestamp 2 test" test2]
null
https://raw.githubusercontent.com/troydm/edda/710856d5bc3bf70c1061c50ae159107ca51c15f0/test/EDDA/Schema/ParserTest.hs
haskell
# LANGUAGE OverloadedStrings #
module EDDA.Schema.ParserTest where import Test.HUnit import Data.Maybe (fromJust,isJust) import Data.Aeson import Data.Aeson.Types import qualified Data.ByteString.Char8 as C import qualified Data.HashMap.Strict as HM import Control.Monad.Trans.Reader import Data.Time.Format (formatTime) import EDDA.Schema.CommodityV2 (parseCommodity) import EDDA.Schema.Util import EDDA.Schema.Parser import EDDA.Types import EDDA.Test.Util test1 :: Test test1 = TestCase $ do let timestamp = "{ \"timestamp\" : \"2016-08-11T20:06:54-05:00\" }" let v = fromJust $ (decodeStrict' timestamp :: Maybe Value) let d = getTimestamp v "timestamp" assertBool "timestamp not parsed" (isJust d) let dt = fromJust d assertEqual "date" "2016-08-12 01:06:54 UTC" (show dt) test2 :: Test test2 = TestCase $ do let timestamp = "{ \"timestamp\" : \"2016-08-11T20:6:54-05:00\" }" let v = fromJust $ (decodeStrict' timestamp :: Maybe Value) let d = getTimestamp v "timestamp" assertBool "timestamp not parsed" (isJust d) let dt = fromJust d assertEqual "date" "2016-08-12 01:06:54 UTC" (show dt) parserTests = [TestLabel "parser timestamp 1 test" test1, TestLabel "parser timestamp 2 test" test2]
528bfcf6cad9fd54f7caa659ff0dd221210aa7a873fd977090155ae36092a96a
sheyll/mediabus
SyncStream.hs
-- | A module for removing and creating sequence numbers and time stamps for -- 'Stream's. -- It 's sometimes helpful to explicity use a ' SyncStream ' instead of a ' Stream ' . -- -- For example, for a library function that consumes 'Frame's and doesn't regard -- the sequence numbers and time stamps, such that the function does not handle -- any gaps and/or out of order packages or discrepancies in the time stamps -- and frame durations. -- When the library author chooses ' SyncStream ' , the library users then know , -- that the library function relies on a synchronized stream. module Data.MediaBus.Media.SyncStream ( SyncStream, assumeSynchronized, setSequenceNumberAndTimestamp, ) where import Data.MediaBus.Basics.Series (Series (Next, Start)) import Data.MediaBus.Basics.Ticks ( CanBeTicks, HasDuration (getDurationTicks), Ticks, ) import Data.MediaBus.Media.Stream ( Frame (MkFrame), FrameCtx (MkFrameCtx), Stream (MkStream), ) -- | A 'Stream' without sequence numbers and time stamps is called a ' SyncStream ' , which is the abbreviation of /synchronous stream/ , because -- when the sequence numbers and time stamps of a 'Stream', and by extension of a ' Frame ' and ' FrameCtx ' , are always @()@ , the ' Frame 's of a ' Stream ' can -- be assumed to be (perfectly) synchronous. type SyncStream streamId streamStartPayload payload = Stream streamId () () streamStartPayload payload | Convert a ' Stream ' to a ' SyncStream ' by simply /forgetting/ the sequence -- numbers and timestamps of the input. This expresses the assumption that the -- 'Frame's are either perfectly lined sequential or that this doesn't matter -- at all. assumeSynchronized :: Stream streamId s t streamStartPayload payload -> SyncStream streamId streamStartPayload payload assumeSynchronized (MkStream (Start (MkFrameCtx i _ _ p))) = MkStream (Start (MkFrameCtx i () () p)) assumeSynchronized (MkStream (Next (MkFrame _ _ payload))) = MkStream (Next (MkFrame () () payload)) -- | Set sequence numbers and timestamps. Increment the sequence numbers starting from @0@ for every frame . Start the timestamp at @0@ and add the ' Frame ' duration of the ' Next ' -- frame in the stream. This function has the signature required to turn it into a ' State ' monad . setSequenceNumberAndTimestamp :: (Num sequenceNumber, CanBeTicks rate timestamp, HasDuration payload) => SyncStream streamId streamStartPayload payload -> (sequenceNumber, Ticks rate timestamp) -> ( Stream streamId sequenceNumber (Ticks rate timestamp) streamStartPayload payload, (sequenceNumber, Ticks rate timestamp) ) setSequenceNumberAndTimestamp (MkStream (Next (MkFrame _t _s !c))) (nextS, nextT) = ( MkStream (Next (MkFrame nextT nextS c)), (nextS + 1, nextT + getDurationTicks c) ) setSequenceNumberAndTimestamp (MkStream (Start (MkFrameCtx i _t _s p))) (nextS, nextT) = (MkStream (Start (MkFrameCtx i nextT nextS p)), (nextS, nextT))
null
https://raw.githubusercontent.com/sheyll/mediabus/351272b2bb26a1bde7b0ffda6ceabc623ede2b14/src/Data/MediaBus/Media/SyncStream.hs
haskell
| A module for removing and creating sequence numbers and time stamps for 'Stream's. For example, for a library function that consumes 'Frame's and doesn't regard the sequence numbers and time stamps, such that the function does not handle any gaps and/or out of order packages or discrepancies in the time stamps and frame durations. that the library function relies on a synchronized stream. | A 'Stream' without sequence numbers and time stamps is called a when the sequence numbers and time stamps of a 'Stream', and by extension of be assumed to be (perfectly) synchronous. numbers and timestamps of the input. This expresses the assumption that the 'Frame's are either perfectly lined sequential or that this doesn't matter at all. | Set sequence numbers and timestamps. frame in the stream.
It 's sometimes helpful to explicity use a ' SyncStream ' instead of a ' Stream ' . When the library author chooses ' SyncStream ' , the library users then know , module Data.MediaBus.Media.SyncStream ( SyncStream, assumeSynchronized, setSequenceNumberAndTimestamp, ) where import Data.MediaBus.Basics.Series (Series (Next, Start)) import Data.MediaBus.Basics.Ticks ( CanBeTicks, HasDuration (getDurationTicks), Ticks, ) import Data.MediaBus.Media.Stream ( Frame (MkFrame), FrameCtx (MkFrameCtx), Stream (MkStream), ) ' SyncStream ' , which is the abbreviation of /synchronous stream/ , because a ' Frame ' and ' FrameCtx ' , are always @()@ , the ' Frame 's of a ' Stream ' can type SyncStream streamId streamStartPayload payload = Stream streamId () () streamStartPayload payload | Convert a ' Stream ' to a ' SyncStream ' by simply /forgetting/ the sequence assumeSynchronized :: Stream streamId s t streamStartPayload payload -> SyncStream streamId streamStartPayload payload assumeSynchronized (MkStream (Start (MkFrameCtx i _ _ p))) = MkStream (Start (MkFrameCtx i () () p)) assumeSynchronized (MkStream (Next (MkFrame _ _ payload))) = MkStream (Next (MkFrame () () payload)) Increment the sequence numbers starting from @0@ for every frame . Start the timestamp at @0@ and add the ' Frame ' duration of the ' Next ' This function has the signature required to turn it into a ' State ' monad . setSequenceNumberAndTimestamp :: (Num sequenceNumber, CanBeTicks rate timestamp, HasDuration payload) => SyncStream streamId streamStartPayload payload -> (sequenceNumber, Ticks rate timestamp) -> ( Stream streamId sequenceNumber (Ticks rate timestamp) streamStartPayload payload, (sequenceNumber, Ticks rate timestamp) ) setSequenceNumberAndTimestamp (MkStream (Next (MkFrame _t _s !c))) (nextS, nextT) = ( MkStream (Next (MkFrame nextT nextS c)), (nextS + 1, nextT + getDurationTicks c) ) setSequenceNumberAndTimestamp (MkStream (Start (MkFrameCtx i _t _s p))) (nextS, nextT) = (MkStream (Start (MkFrameCtx i nextT nextS p)), (nextS, nextT))
bc5e3567fbad510ee95a20d6fc98a949247c8c1f87be7e579e9131e13c1a9f12
EligiusSantori/L2Apf
attack_start.scm
(module system racket/base (require "../../packet.scm") (provide game-server-packet/attack-start) (define (game-server-packet/attack-start buffer) (let ((s (open-input-bytes buffer))) (list (cons 'id (read-byte s)) (cons 'object-id (read-int32 #f s)) ) ) ) )
null
https://raw.githubusercontent.com/EligiusSantori/L2Apf/30ffe0828e8a401f58d39984efd862c8aeab8c30/packet/game/server/attack_start.scm
scheme
(module system racket/base (require "../../packet.scm") (provide game-server-packet/attack-start) (define (game-server-packet/attack-start buffer) (let ((s (open-input-bytes buffer))) (list (cons 'id (read-byte s)) (cons 'object-id (read-int32 #f s)) ) ) ) )
8ceecc832d4aee00f7cf85ff72e38aa3bcec5bacfb9e9277ce9524c703c75b38
dalaing/little-languages
Eval.hs
| Copyright : ( c ) , 2016 License : : Stability : experimental Portability : non - portable Copyright : (c) Dave Laing, 2016 License : BSD3 Maintainer : Stability : experimental Portability : non-portable -} module Test.Term.Eval ( evalTests ) where -- from 'base' import Data.List (group) import Data.Maybe (mapMaybe) -- from 'tasty' import Test.Tasty (TestTree, testGroup) -- from 'tasty-quickcheck' import Test.Tasty.QuickCheck (testProperty) -- from 'QuickCheck' import Test.QuickCheck (Property, (===), (==>)) -- local import Term (size) import Term.Eval.BigStep (bigStepRules, eval) import Term.Eval.SmallStep (canStep, eval, isNormalForm, smallStep, smallStepRules) import Term.Eval.Value (isValue, valueRules) import Term.Gen (AnyTerm(..)) evalTests :: TestTree evalTests = testGroup "eval" [ testProperty "every value is a normal form" propValueNormal , testProperty "every normal form is a value" propNormalValue , testProperty "small step is determinate" propSmallDeterminate , testProperty "small steps decrease term sizes" propSmallShrinks , testProperty "small step rules are unique" propSmallUnique , testProperty "big step rules are unique" propBigUnique , testProperty "small step and big step agree" propSmallBig ] propValueNormal :: AnyTerm -> Property propValueNormal (AnyTerm tm) = isValue tm ==> isNormalForm tm propNormalValue :: AnyTerm -> Property propNormalValue (AnyTerm tm) = isNormalForm tm ==> isValue tm - either isValue , or there are 1 or more steps we can take that have the same result propSmallDeterminate :: AnyTerm -> Property propSmallDeterminate (AnyTerm tm) = canStep tm ==> let distinctResults = length . group . mapMaybe ($ tm) $ smallStepRules in distinctResults === 1 propSmallShrinks :: AnyTerm -> Bool propSmallShrinks (AnyTerm tm) = case smallStep tm of Nothing -> True Just tm' -> size tm' < size tm propSmallUnique :: AnyTerm -> Property propSmallUnique (AnyTerm tm) = let matches = length . mapMaybe ($ tm) $ valueRules ++ smallStepRules in matches === 1 propBigUnique :: AnyTerm -> Property propBigUnique (AnyTerm tm) = let matches = length . mapMaybe ($ tm) $ bigStepRules in matches === 1 propSmallBig :: AnyTerm -> Property propSmallBig (AnyTerm tm) = Term.Eval.SmallStep.eval tm === Term.Eval.BigStep.eval tm
null
https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/i/tests/Test/Term/Eval.hs
haskell
from 'base' from 'tasty' from 'tasty-quickcheck' from 'QuickCheck' local
| Copyright : ( c ) , 2016 License : : Stability : experimental Portability : non - portable Copyright : (c) Dave Laing, 2016 License : BSD3 Maintainer : Stability : experimental Portability : non-portable -} module Test.Term.Eval ( evalTests ) where import Data.List (group) import Data.Maybe (mapMaybe) import Test.Tasty (TestTree, testGroup) import Test.Tasty.QuickCheck (testProperty) import Test.QuickCheck (Property, (===), (==>)) import Term (size) import Term.Eval.BigStep (bigStepRules, eval) import Term.Eval.SmallStep (canStep, eval, isNormalForm, smallStep, smallStepRules) import Term.Eval.Value (isValue, valueRules) import Term.Gen (AnyTerm(..)) evalTests :: TestTree evalTests = testGroup "eval" [ testProperty "every value is a normal form" propValueNormal , testProperty "every normal form is a value" propNormalValue , testProperty "small step is determinate" propSmallDeterminate , testProperty "small steps decrease term sizes" propSmallShrinks , testProperty "small step rules are unique" propSmallUnique , testProperty "big step rules are unique" propBigUnique , testProperty "small step and big step agree" propSmallBig ] propValueNormal :: AnyTerm -> Property propValueNormal (AnyTerm tm) = isValue tm ==> isNormalForm tm propNormalValue :: AnyTerm -> Property propNormalValue (AnyTerm tm) = isNormalForm tm ==> isValue tm - either isValue , or there are 1 or more steps we can take that have the same result propSmallDeterminate :: AnyTerm -> Property propSmallDeterminate (AnyTerm tm) = canStep tm ==> let distinctResults = length . group . mapMaybe ($ tm) $ smallStepRules in distinctResults === 1 propSmallShrinks :: AnyTerm -> Bool propSmallShrinks (AnyTerm tm) = case smallStep tm of Nothing -> True Just tm' -> size tm' < size tm propSmallUnique :: AnyTerm -> Property propSmallUnique (AnyTerm tm) = let matches = length . mapMaybe ($ tm) $ valueRules ++ smallStepRules in matches === 1 propBigUnique :: AnyTerm -> Property propBigUnique (AnyTerm tm) = let matches = length . mapMaybe ($ tm) $ bigStepRules in matches === 1 propSmallBig :: AnyTerm -> Property propSmallBig (AnyTerm tm) = Term.Eval.SmallStep.eval tm === Term.Eval.BigStep.eval tm
6ca3fb00f9335e132a96d27e399d0237c4075bd88a65d7cf83588c0f760fbf8b
roman/servant-playground
DevelMain.hs
# OPTIONS_GHC -Wno - deprecations # {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE NoImplicitPrelude # module DevelMain where import RIO import App.Component (buildApp) import App.Component.Logger (logComponentEvents) import Control.Monad.Component.Development (ComponentEvent(..), runComponentDevel) main :: IO () main = do tmpLogOptions <- logOptionsHandle stdout True withReloadableLogFunc tmpLogOptions $ \(logFunc, reloadLogOptions) -> runComponentDevel (logComponentEvents logFunc) "servant-playground" (buildApp logFunc reloadLogOptions) (\app -> runRIO app $ logInfo "Application Started")
null
https://raw.githubusercontent.com/roman/servant-playground/37639f20c01306fb1a59050f7996f6779a627a1f/app/DevelMain.hs
haskell
# LANGUAGE NamedFieldPuns # # LANGUAGE OverloadedStrings #
# OPTIONS_GHC -Wno - deprecations # # LANGUAGE NoImplicitPrelude # module DevelMain where import RIO import App.Component (buildApp) import App.Component.Logger (logComponentEvents) import Control.Monad.Component.Development (ComponentEvent(..), runComponentDevel) main :: IO () main = do tmpLogOptions <- logOptionsHandle stdout True withReloadableLogFunc tmpLogOptions $ \(logFunc, reloadLogOptions) -> runComponentDevel (logComponentEvents logFunc) "servant-playground" (buildApp logFunc reloadLogOptions) (\app -> runRIO app $ logInfo "Application Started")
6a7aef964df0a028a6af7c4725769d73176c025d98984ea8795e27330386812b
alexanderwasey/stupid-computer
Listcomp.hs
module Listcomp where import Prelude hiding (map, take) map :: (a -> b) -> [a] -> [b] map f (x:xs) = (f x) : (map f xs) map _ [] = [] square :: Integer -> Integer square x = x*x doublelarge :: [Integer] -> [Integer] doublelarge xs = [x * 2 | x <- xs, x > 3] take :: Integer -> [a] -> [a] take 0 _ = [] take n (x:xs) = x : (take (n-1) xs) take _ [] = []
null
https://raw.githubusercontent.com/alexanderwasey/stupid-computer/a485d2f33a4b8d58128a74b9003b9eadffe42702/examples/Listcomp.hs
haskell
module Listcomp where import Prelude hiding (map, take) map :: (a -> b) -> [a] -> [b] map f (x:xs) = (f x) : (map f xs) map _ [] = [] square :: Integer -> Integer square x = x*x doublelarge :: [Integer] -> [Integer] doublelarge xs = [x * 2 | x <- xs, x > 3] take :: Integer -> [a] -> [a] take 0 _ = [] take n (x:xs) = x : (take (n-1) xs) take _ [] = []
551e8573c7ac2326ef92945242c930f9735d66a13be0307a77580973baa6fc5c
clojure-goes-fast/clj-memory-meter
core.clj
(ns clj-memory-meter.core (:require [clojure.java.io :as io]) (:import java.io.File java.lang.management.ManagementFactory java.net.URLClassLoader)) Agent unpacking (def ^:private jamm-jar-name "jamm-0.4.0-unsafe.jar") (defn- unpack-jamm-from-resource [] (let [dest (File/createTempFile "jamm" ".jar")] (io/copy (io/input-stream (io/resource jamm-jar-name)) dest) (.getAbsolutePath dest))) (defonce ^:private extracted-jamm-jar (unpack-jamm-from-resource)) ;;;; Agent loading (defn- tools-jar-url [] (let [file (io/file (System/getProperty "java.home")) file (if (.equalsIgnoreCase (.getName file) "jre") (.getParentFile file) file) file (io/file file "lib" "tools.jar")] (io/as-url file))) (defn- add-url-to-classloader-reflective "This is needed for cases when there is no DynamicClassLoader in the classloader chain (i.e., the env is not a REPL). Note that this will throw warning on Java 11 and stops working after Java 17." [^URLClassLoader loader, url] (doto (.getDeclaredMethod URLClassLoader "addURL" (into-array Class [java.net.URL])) (.setAccessible true) (.invoke loader (object-array [url])))) (defn- get-classloader "Find the uppermost DynamicClassLoader in the chain. However, if the immediate context classloader is not a DynamicClassLoader, it means we are not run in the REPL environment, and have to use reflection to patch this classloader. Return a tuple of [classloader is-it-dynamic?]." [] (let [dynamic-cl? #(#{"clojure.lang.DynamicClassLoader" "boot.AddableClassLoader"} (.getName (class %))) ctx-loader (.getContextClassLoader (Thread/currentThread))] (if (dynamic-cl? ctx-loader) ;; The chain starts with a dynamic classloader, walk the chain up to find ;; the uppermost one. (loop [loader ctx-loader] (let [parent (.getParent loader)] (if (dynamic-cl? parent) (recur parent) [loader true]))) ;; Otherwise, return the immediate classloader and tell it's not dynamic. [ctx-loader false]))) (def ^:private tools-jar-classloader (delay (let [tools-jar (tools-jar-url) [loader dynamic?] (get-classloader)] (if dynamic? (.addURL loader tools-jar) (add-url-to-classloader-reflective loader tools-jar)) loader))) (defn- ^Class get-virtualmachine-class [] In JDK9 + , the class is already present , no extra steps required . (or (try (resolve 'com.sun.tools.attach.VirtualMachine) (catch ClassNotFoundException _)) In earlier JDKs , load tools.jar and get the class from there . (Class/forName "com.sun.tools.attach.VirtualMachine" false @tools-jar-classloader))) (defmacro ^:private get-self-pid* "This macro expands into proper way of obtaining self PID on JDK9+, and digs into internals on JDK8." [] (if (and (try (resolve 'java.lang.ProcessHandle) (catch ClassNotFoundException _)) ( java.lang . ProcessHandle / current ) does n't work before 1.10.0 because of a Clojure bug . (>= (compare (mapv *clojure-version* [:major :minor]) [1 10]) 0)) `(.pid (java.lang.ProcessHandle/current)) `(let [runtime# (ManagementFactory/getRuntimeMXBean) jvm# (.get (doto (.getDeclaredField (class runtime#) "jvm") (.setAccessible true)) runtime#)] (.invoke (doto (.getDeclaredMethod (class jvm#) "getProcessId" (into-array Class [])) (.setAccessible true)) jvm# (object-array []))))) (defn- get-self-pid "Returns the process ID of the current JVM process." [] (get-self-pid*)) #_(get-self-pid) (defn- mk-vm [pid] (let [vm-class (get-virtualmachine-class) method (.getDeclaredMethod vm-class "attach" (into-array Class [String]))] (.invoke method nil (object-array [(str pid)])))) (defmacro ^:private load-agent-and-detach "Call `VirtualMachine.loadAgent` and `VirtualMachine.detach` for the given agent jar. This macro expands to either reflective or non-reflective call, depending whether VirtualMachine class is available at compile time (on JDK9+)." [vm agent-jar] (let [vm-sym (if (try (resolve 'com.sun.tools.attach.VirtualMachine) (catch ClassNotFoundException _)) (with-meta (gensym "vm") {:tag 'com.sun.tools.attach.VirtualMachine}) (gensym "vm"))] `(let [~vm-sym ~vm] (do (.loadAgent ~vm-sym ~agent-jar) (.detach ~vm-sym))))) (def ^:private jamm-agent-loaded (delay (load-agent-and-detach (mk-vm (get-self-pid)) extracted-jamm-jar) true)) ;;;; Public API (defn meter-builder [] @jamm-agent-loaded (let [mm-class (Class/forName "org.github.jamm.MemoryMeter") builder (.getDeclaredMethod mm-class "builder" (into-array Class []))] (.invoke builder nil (object-array 0)))) (def ^:private memory-meter (delay (.build (meter-builder)))) (defn- convert-to-human-readable "Taken from -byte-size-to-human-readable-format.html." [bytes] (let [unit 1024] (if (< bytes unit) (str bytes " B") (let [exp (int (/ (Math/log bytes) (Math/log unit))) pre (nth "KMGTPE" (dec exp))] (format "%.1f %siB" (/ bytes (Math/pow unit exp)) pre))))) #_(convert-to-human-readable 512) #_(convert-to-human-readable 10e8) (defn measure "Measure the memory usage of the `object`. Return a human-readable string. :debug - if true, print the object layout tree to stdout. Can also be set to a number to limit the nesting level being printed. :shallow - if true, count only the object header and its fields, don't follow object references :bytes - if true, return a number of bytes instead of a string :meter - custom org.github.jamm.MemoryMeter object" [object & {:keys [debug shallow bytes meter]}] (let [m (or meter @memory-meter) m (cond (integer? debug) (.enableDebug m debug) debug (.enableDebug m) :else m) byte-count (if shallow (.measure m object) (.measureDeep m object))] (if bytes byte-count (convert-to-human-readable byte-count)))) #_(measure (vec (repeat 100 "hello")) :debug true) #_(measure (object-array (repeatedly 1000 (fn [] (String. "foobarbaz")))) :bytes true)
null
https://raw.githubusercontent.com/clojure-goes-fast/clj-memory-meter/14358428fe5dafd50ed316db60cb319b63830139/src/clj_memory_meter/core.clj
clojure
Agent loading The chain starts with a dynamic classloader, walk the chain up to find the uppermost one. Otherwise, return the immediate classloader and tell it's not dynamic. Public API
(ns clj-memory-meter.core (:require [clojure.java.io :as io]) (:import java.io.File java.lang.management.ManagementFactory java.net.URLClassLoader)) Agent unpacking (def ^:private jamm-jar-name "jamm-0.4.0-unsafe.jar") (defn- unpack-jamm-from-resource [] (let [dest (File/createTempFile "jamm" ".jar")] (io/copy (io/input-stream (io/resource jamm-jar-name)) dest) (.getAbsolutePath dest))) (defonce ^:private extracted-jamm-jar (unpack-jamm-from-resource)) (defn- tools-jar-url [] (let [file (io/file (System/getProperty "java.home")) file (if (.equalsIgnoreCase (.getName file) "jre") (.getParentFile file) file) file (io/file file "lib" "tools.jar")] (io/as-url file))) (defn- add-url-to-classloader-reflective "This is needed for cases when there is no DynamicClassLoader in the classloader chain (i.e., the env is not a REPL). Note that this will throw warning on Java 11 and stops working after Java 17." [^URLClassLoader loader, url] (doto (.getDeclaredMethod URLClassLoader "addURL" (into-array Class [java.net.URL])) (.setAccessible true) (.invoke loader (object-array [url])))) (defn- get-classloader "Find the uppermost DynamicClassLoader in the chain. However, if the immediate context classloader is not a DynamicClassLoader, it means we are not run in the REPL environment, and have to use reflection to patch this classloader. Return a tuple of [classloader is-it-dynamic?]." [] (let [dynamic-cl? #(#{"clojure.lang.DynamicClassLoader" "boot.AddableClassLoader"} (.getName (class %))) ctx-loader (.getContextClassLoader (Thread/currentThread))] (if (dynamic-cl? ctx-loader) (loop [loader ctx-loader] (let [parent (.getParent loader)] (if (dynamic-cl? parent) (recur parent) [loader true]))) [ctx-loader false]))) (def ^:private tools-jar-classloader (delay (let [tools-jar (tools-jar-url) [loader dynamic?] (get-classloader)] (if dynamic? (.addURL loader tools-jar) (add-url-to-classloader-reflective loader tools-jar)) loader))) (defn- ^Class get-virtualmachine-class [] In JDK9 + , the class is already present , no extra steps required . (or (try (resolve 'com.sun.tools.attach.VirtualMachine) (catch ClassNotFoundException _)) In earlier JDKs , load tools.jar and get the class from there . (Class/forName "com.sun.tools.attach.VirtualMachine" false @tools-jar-classloader))) (defmacro ^:private get-self-pid* "This macro expands into proper way of obtaining self PID on JDK9+, and digs into internals on JDK8." [] (if (and (try (resolve 'java.lang.ProcessHandle) (catch ClassNotFoundException _)) ( java.lang . ProcessHandle / current ) does n't work before 1.10.0 because of a Clojure bug . (>= (compare (mapv *clojure-version* [:major :minor]) [1 10]) 0)) `(.pid (java.lang.ProcessHandle/current)) `(let [runtime# (ManagementFactory/getRuntimeMXBean) jvm# (.get (doto (.getDeclaredField (class runtime#) "jvm") (.setAccessible true)) runtime#)] (.invoke (doto (.getDeclaredMethod (class jvm#) "getProcessId" (into-array Class [])) (.setAccessible true)) jvm# (object-array []))))) (defn- get-self-pid "Returns the process ID of the current JVM process." [] (get-self-pid*)) #_(get-self-pid) (defn- mk-vm [pid] (let [vm-class (get-virtualmachine-class) method (.getDeclaredMethod vm-class "attach" (into-array Class [String]))] (.invoke method nil (object-array [(str pid)])))) (defmacro ^:private load-agent-and-detach "Call `VirtualMachine.loadAgent` and `VirtualMachine.detach` for the given agent jar. This macro expands to either reflective or non-reflective call, depending whether VirtualMachine class is available at compile time (on JDK9+)." [vm agent-jar] (let [vm-sym (if (try (resolve 'com.sun.tools.attach.VirtualMachine) (catch ClassNotFoundException _)) (with-meta (gensym "vm") {:tag 'com.sun.tools.attach.VirtualMachine}) (gensym "vm"))] `(let [~vm-sym ~vm] (do (.loadAgent ~vm-sym ~agent-jar) (.detach ~vm-sym))))) (def ^:private jamm-agent-loaded (delay (load-agent-and-detach (mk-vm (get-self-pid)) extracted-jamm-jar) true)) (defn meter-builder [] @jamm-agent-loaded (let [mm-class (Class/forName "org.github.jamm.MemoryMeter") builder (.getDeclaredMethod mm-class "builder" (into-array Class []))] (.invoke builder nil (object-array 0)))) (def ^:private memory-meter (delay (.build (meter-builder)))) (defn- convert-to-human-readable "Taken from -byte-size-to-human-readable-format.html." [bytes] (let [unit 1024] (if (< bytes unit) (str bytes " B") (let [exp (int (/ (Math/log bytes) (Math/log unit))) pre (nth "KMGTPE" (dec exp))] (format "%.1f %siB" (/ bytes (Math/pow unit exp)) pre))))) #_(convert-to-human-readable 512) #_(convert-to-human-readable 10e8) (defn measure "Measure the memory usage of the `object`. Return a human-readable string. :debug - if true, print the object layout tree to stdout. Can also be set to a number to limit the nesting level being printed. :shallow - if true, count only the object header and its fields, don't follow object references :bytes - if true, return a number of bytes instead of a string :meter - custom org.github.jamm.MemoryMeter object" [object & {:keys [debug shallow bytes meter]}] (let [m (or meter @memory-meter) m (cond (integer? debug) (.enableDebug m debug) debug (.enableDebug m) :else m) byte-count (if shallow (.measure m object) (.measureDeep m object))] (if bytes byte-count (convert-to-human-readable byte-count)))) #_(measure (vec (repeat 100 "hello")) :debug true) #_(measure (object-array (repeatedly 1000 (fn [] (String. "foobarbaz")))) :bytes true)
db01a5f95d2e36c4dcb1adba3a1e67848c0e229c941eb6f63d990765ea6e8bad
TyOverby/mono
test_async_quickcheck.ml
open! Core open! Async let trials = 5 let examples = [ "Example 1"; "Example 2"; "Example 3" ] let generator = Quickcheck.Generator.return "Generated value" let%expect_test "[~examples] are tested first" = let%bind () = Async_quickcheck.async_test ~trials ~examples generator ~f:(fun string -> print_endline string; return ()) in [%expect {| Example 1 Example 2 Example 3 Generated value Generated value Generated value Generated value Generated value |}]; return () ;; let%expect_test "[test] and [async_test] handle [~examples] the same" = let%bind () = Async_quickcheck.async_test ~trials ~examples generator ~f:(fun string -> print_endline string; return ()) in let async_test_output = Expect_test_helpers_base.expect_test_output [%here] in Async_quickcheck.test ~trials ~examples generator ~f:print_endline; let test_output = Expect_test_helpers_base.expect_test_output [%here] in Expect_test_helpers_base.require_equal [%here] (module String) async_test_output test_output; return () ;;
null
https://raw.githubusercontent.com/TyOverby/mono/5ce4569fc6edf6564d29d37b66d455549df1e497/vendor/janestreet-async/async_quickcheck/test/test_async_quickcheck.ml
ocaml
open! Core open! Async let trials = 5 let examples = [ "Example 1"; "Example 2"; "Example 3" ] let generator = Quickcheck.Generator.return "Generated value" let%expect_test "[~examples] are tested first" = let%bind () = Async_quickcheck.async_test ~trials ~examples generator ~f:(fun string -> print_endline string; return ()) in [%expect {| Example 1 Example 2 Example 3 Generated value Generated value Generated value Generated value Generated value |}]; return () ;; let%expect_test "[test] and [async_test] handle [~examples] the same" = let%bind () = Async_quickcheck.async_test ~trials ~examples generator ~f:(fun string -> print_endline string; return ()) in let async_test_output = Expect_test_helpers_base.expect_test_output [%here] in Async_quickcheck.test ~trials ~examples generator ~f:print_endline; let test_output = Expect_test_helpers_base.expect_test_output [%here] in Expect_test_helpers_base.require_equal [%here] (module String) async_test_output test_output; return () ;;
68a3e4d0babe1c4d11c7154df79320f421b766c43bb15133a68ab01cf492810a
facebook/flow
serverEnv.ml
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) (*****************************************************************************) The " static " environment , initialized first and then does n't change (*****************************************************************************) type genv = { options: Options.t; workers: MultiWorkerLwt.worker list option; } (*****************************************************************************) (* The environment constantly maintained by the server *) (*****************************************************************************) (* Do not change these to contain `Loc.t`s. Because these errors are stored between rechecks, it * is critical that they contain `ALoc.t`s, so that we can update the concrete locations when we * render the errors, without having to retypecheck the files that generated those errors. *) type errors = { (* errors are stored in a map from file path to error set, so that the errors from checking particular files can be cleared during recheck. *) local_errors: Flow_error.ErrorSet.t Utils_js.FilenameMap.t; (* duplicate providers found during commit_modules are stored separately so they can be cleared easily *) duplicate_providers: (File_key.t * File_key.t Nel.t) SMap.t; (* errors encountered during merge have to be stored separately so dependencies can be cleared during merge. *) merge_errors: Flow_error.ErrorSet.t Utils_js.FilenameMap.t; (* warnings are stored in a map from file path to error set, so that the warnings from checking particular files can be cleared during recheck. *) warnings: Flow_error.ErrorSet.t Utils_js.FilenameMap.t; (* error suppressions in the code *) suppressions: Error_suppressions.t; } type collated_errors = { collated_errorset: Errors.ConcreteLocPrintableErrorSet.t; collated_warning_map: Errors.ConcreteLocPrintableErrorSet.t Utils_js.FilenameMap.t; collated_suppressed_errors: (Loc.t Errors.printable_error * Loc_collections.LocSet.t) list; } type env = { * All the files that we at least parse ( includes libs ) . dependency_info: Dependency_info.t; checked_files: CheckedSet.t; (** All the current files we typecheck. *) package_json_files: Utils_js.FilenameSet.t; (** package.json files *) ordered_libs: string list; (** The lib files, in their merge order *) libs: SSet.t; (** The lib files as a set *) unparsed: Utils_js.FilenameSet.t; (** The files which didn't parse (skipped or errored) *) errors: errors; coverage: Coverage_response.file_coverage Utils_js.FilenameMap.t; collated_errors: collated_errors option ref; connections: Persistent_connection.t; exports: Export_search.t; }
null
https://raw.githubusercontent.com/facebook/flow/8d9850a82f1e3094aed7e46acab5c2b120d10a31/src/server/env/serverEnv.ml
ocaml
*************************************************************************** *************************************************************************** *************************************************************************** The environment constantly maintained by the server *************************************************************************** Do not change these to contain `Loc.t`s. Because these errors are stored between rechecks, it * is critical that they contain `ALoc.t`s, so that we can update the concrete locations when we * render the errors, without having to retypecheck the files that generated those errors. errors are stored in a map from file path to error set, so that the errors from checking particular files can be cleared during recheck. duplicate providers found during commit_modules are stored separately so they can be cleared easily errors encountered during merge have to be stored separately so dependencies can be cleared during merge. warnings are stored in a map from file path to error set, so that the warnings from checking particular files can be cleared during recheck. error suppressions in the code * All the current files we typecheck. * package.json files * The lib files, in their merge order * The lib files as a set * The files which didn't parse (skipped or errored)
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) The " static " environment , initialized first and then does n't change type genv = { options: Options.t; workers: MultiWorkerLwt.worker list option; } type errors = { local_errors: Flow_error.ErrorSet.t Utils_js.FilenameMap.t; duplicate_providers: (File_key.t * File_key.t Nel.t) SMap.t; merge_errors: Flow_error.ErrorSet.t Utils_js.FilenameMap.t; warnings: Flow_error.ErrorSet.t Utils_js.FilenameMap.t; suppressions: Error_suppressions.t; } type collated_errors = { collated_errorset: Errors.ConcreteLocPrintableErrorSet.t; collated_warning_map: Errors.ConcreteLocPrintableErrorSet.t Utils_js.FilenameMap.t; collated_suppressed_errors: (Loc.t Errors.printable_error * Loc_collections.LocSet.t) list; } type env = { * All the files that we at least parse ( includes libs ) . dependency_info: Dependency_info.t; errors: errors; coverage: Coverage_response.file_coverage Utils_js.FilenameMap.t; collated_errors: collated_errors option ref; connections: Persistent_connection.t; exports: Export_search.t; }
e0ad28a8aece5a5db848e805de92e5389f4fc03c3e542d4c7c152ef652ee6458
RefactoringTools/HaRe
Nested.expected.hs
module AddOneParameter.Nested(sumSquares,sumSquares_y) where {- add parameter 'y' to 'sumSquares'. 'sumSquares_y_1' to be added to the export list -} sumSquares y (x:xs) = sq x + (sumSquares y) xs + foo xs where foo a = (sumSquares y) a + 1 sumSquares y [] = 0 sumSquares_y = undefined sq x = x ^ pow pow =2
null
https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/test/testdata/AddOneParameter/Nested.expected.hs
haskell
add parameter 'y' to 'sumSquares'. 'sumSquares_y_1' to be added to the export list
module AddOneParameter.Nested(sumSquares,sumSquares_y) where sumSquares y (x:xs) = sq x + (sumSquares y) xs + foo xs where foo a = (sumSquares y) a + 1 sumSquares y [] = 0 sumSquares_y = undefined sq x = x ^ pow pow =2
5d095358482783e73c6f9c020e2b72a375a8abc1eff9cd212be951677cb20588
slyrus/mcclim-old
demodemo.lisp
;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: CLIM-DEMO; -*- ;;; -------------------------------------------------------------------------------------- ;;; Title: The demo demo Created : 2002 - 02 - 11 Author : < > ;;; License: LGPL (See file COPYING for details). ;;; -------------------------------------------------------------------------------------- ( c ) copyright 2002 by ;;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . ;;; ;;; This library is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details . ;;; You should have received a copy of the GNU Library General Public ;;; License along with this library; if not, write to the Free Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 USA . (in-package :clim-demo) (defun make-demo-button (title demo-frame-class) (make-pane 'push-button :label title :activate-callback (let ((frame nil)) (lambda (&rest ignore) (declare (ignore ignore)) (cond ((null frame) ;; I broke this logic, sorry.. -Hefner (setq frame (run-frame-top-level (make-application-frame demo-frame-class :calling-frame *application-frame*)))) (t #+nil (destroy-frame frame))))))) (define-application-frame demodemo () () (:menu-bar nil) (:layouts (default (vertically (:equalize-width t) spacing (: thickness 10 ) (labelling (:label "McCLIM Demos" :text-style (make-text-style :sans-serif :roman :huge) :align-x :center))) spacing (: thickness 10 ) (horizontally () ;; '+fill+ (labelling (:label "Demos") (vertically (:equalize-width t) (make-demo-button "CLIM-Fig" 'clim-fig) (make-demo-button "Calculator" 'calculator) (make-demo-button "Method Browser" 'method-browser) (make-demo-button "Address Book" 'address-book) (make-demo-button "Puzzle" 'puzzle) (make-demo-button "Logic Cube" 'logic-cube) (make-demo-button "Gadget Test" 'gadget-test) (make-demo-button "Drag and Drop" 'dragndrop) ( make - demo - button " Colorslider " ' colorslider ) (make-demo-button "D&D Translator" 'drag-test) (make-demo-button "Draggable Graph" 'draggable-graph-demo) (make-demo-button "Image viewer" 'image-viewer) (make-pane 'push-button :label "Font Selector" :activate-callback (lambda (&rest ignore) (declare (ignore ignore)) (format *trace-output* "~&You chose: ~A~%" (select-font)))) (make-demo-button "Tab Layout" 'tabdemo:tabdemo))) (labelling (:label "Tests") (vertically (:equalize-width t) (make-demo-button "Label Test" 'label-test) (make-demo-button "Table Test" 'table-test) (make-demo-button "Scroll Test" 'Scroll-test) (make-demo-button "List Test" 'list-test) (make-demo-button "HBOX Test" 'hbox-test) (make-demo-button "Text Size Test" 'text-size-test) (make-demo-button "Goatee Test" 'goatee::goatee-test) (make-demo-button "Drawing Benchmark" 'drawing-benchmark) (make-demo-button "Border Styles Test" 'bordered-output) (make-demo-button "Misc. Tests" 'misc-tests))))))))) (defun demodemo () #+nil (loop for port in climi::*all-ports* do (destroy-port port)) (run-frame-top-level (make-application-frame 'demodemo))) (define-application-frame hbox-test () () (:layouts (default (horizontally (:background climi::*3d-normal-color*) 30 (make-pane 'push-button :label "Okay" :width '(50 :mm)) '+fill+ (make-pane 'push-button :label "Cancel") '+fill+ (make-pane 'push-button :label "Help") 5 ) ))) (define-application-frame table-test () () (:layouts (default (tabling (:background +red+) (list (make-pane 'push-button :label "Last Name" :max-height +fill+) : fill+ (list (make-pane 'push-button :label "C 1 0") (make-pane 'push-button :label "C 1 1")) ) ))) (defun make-test-label (ax ay) (labelling (:label "Some Label" :align-x ax :label-alignment ay :foreground +WHITE+ :background +PALETURQUOISE4+ :text-style (make-text-style :sans-serif :roman :normal)) (make-pane 'push-button :label (format nil "~S" (list ax ay)) :text-style (make-text-style :sans-serif :roman :normal) :max-width 1000 :max-height 1000))) (defun make-test-label2 (ax ay) (labelling (:label (format nil "~(~S~)" (list ax ay)) :align-x ax :label-alignment ay :foreground +WHITE+ :background +PALETURQUOISE4+ :text-style (make-text-style :sans-serif :roman :normal)) #+nil (make-pane 'push-button :label :text-style (make-text-style :sans-serif :roman :normal) :max-width 1000 :max-height 1000))) (define-application-frame label-test () () (:layouts (default ( scrolling (: width 400 : height 200 : max - width 1000 : max - height 2000 ) (vertically (:equalize-width t : width 400 ; ; : height 800 :max-width 2000 :max-height 2000) 10 (labelling (:label "CLIM Label Tests" :align-x :center :text-style (make-text-style :sans-serif :roman :huge))) 10 (9/10 (horizontally (:equalize-height t) (1/2 (labelling (:label "Labels with content") (vertically (:equalize-width t) (make-test-label :left :top) 5 (make-test-label :center :top) 5 (make-test-label :right :top) 5 (make-test-label :left :bottom) 5 (make-test-label :center :bottom) 5 (make-test-label :right :bottom)))) (1/2 (labelling (:label "Labels w/o content") (vertically (:equalize-width t) (make-test-label2 :left :top) 5 (make-test-label2 :center :top) 5 (make-test-label2 :right :top) 5 (make-test-label2 :left :bottom) 5 (make-test-label2 :center :bottom) 5 (make-test-label2 :right :bottom)))))))))) (defclass foo-pane (basic-pane permanent-medium-sheet-output-mixin) ()) (defmethod compose-space ((pane foo-pane) &key width height) (declare (ignore width height)) (make-space-requirement :width 800 :height 1e3)) (defmethod repaint-sheet ((pane foo-pane) region) (draw-line* pane 50 50 200 50) (multiple-value-bind (x1 y1 x2 y2) (bounding-rectangle* region) (let ((k 20)) (loop for y from (* k (floor (- y1 10) k)) below (+ y2 10) by k do (draw-text* pane (format nil "~D" y) 20 y))))) (defmethod dispatch-repaint ((foo-pane foo-pane) region) (repaint-sheet foo-pane region)) (defmethod handle-event ((pane foo-pane) (event window-repaint-event)) (repaint-sheet pane (window-event-region event))) (define-application-frame scroll-test () () (:layouts (defaults (scrolling (:width 400 :height 400) (make-pane 'foo-pane))))) (define-application-frame list-test () () (:panes (substring :text-field :value "INTER") (result-list (make-pane 'list-pane :value 'clim:region-intersection :items (apropos-list "INTER" :clim t) :presentation-type-key (constantly 'list-test-symbol) :name-key (lambda (x) (format nil "~(~S~)" x)))) (interactor :interactor :height 200)) (:layouts (defaults (labelling (:label "Matching symbols" :text-style (make-text-style :sans-serif :roman :normal)) (vertically () (scrolling (:height 200) result-list) (horizontally () substring (make-pane 'push-button :label "Update" :activate-callback 'update-list-test)) interactor))))) (define-presentation-type list-test-symbol ()) (define-list-test-command com-describe-symbol ((sym 'list-test-symbol :gesture :select)) Let 's print only three lines , we do n't have space for more . (with-input-from-string (s (with-output-to-string (s) (describe sym s))) (dotimes (x 3) (write-line (read-line s nil "") *standard-input*)))) (defun update-list-test (pane) (declare (ignore pane)) (setf (list-pane-items (find-pane-named *application-frame* 'result-list)) (apropos-list (gadget-value (find-pane-named *application-frame* 'substring)) :clim t))) (format t "~&;; try (CLIM-DEMO::DEMODEMO)~%")
null
https://raw.githubusercontent.com/slyrus/mcclim-old/354cdf73c1a4c70e619ccd7d390cb2f416b21c1a/Examples/demodemo.lisp
lisp
-*- Mode: Lisp; Syntax: Common-Lisp; Package: CLIM-DEMO; -*- -------------------------------------------------------------------------------------- Title: The demo demo License: LGPL (See file COPYING for details). -------------------------------------------------------------------------------------- This library is free software; you can redistribute it and/or either This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU License along with this library; if not, write to the I broke this logic, sorry.. -Hefner '+fill+ ; : height 800
Created : 2002 - 02 - 11 Author : < > ( c ) copyright 2002 by modify it under the terms of the GNU Library General Public version 2 of the License , or ( at your option ) any later version . Library General Public License for more details . You should have received a copy of the GNU Library General Public Free Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 USA . (in-package :clim-demo) (defun make-demo-button (title demo-frame-class) (make-pane 'push-button :label title :activate-callback (let ((frame nil)) (lambda (&rest ignore) (declare (ignore ignore)) (setq frame (run-frame-top-level (make-application-frame demo-frame-class :calling-frame *application-frame*)))) (t #+nil (destroy-frame frame))))))) (define-application-frame demodemo () () (:menu-bar nil) (:layouts (default (vertically (:equalize-width t) spacing (: thickness 10 ) (labelling (:label "McCLIM Demos" :text-style (make-text-style :sans-serif :roman :huge) :align-x :center))) spacing (: thickness 10 ) (horizontally () (labelling (:label "Demos") (vertically (:equalize-width t) (make-demo-button "CLIM-Fig" 'clim-fig) (make-demo-button "Calculator" 'calculator) (make-demo-button "Method Browser" 'method-browser) (make-demo-button "Address Book" 'address-book) (make-demo-button "Puzzle" 'puzzle) (make-demo-button "Logic Cube" 'logic-cube) (make-demo-button "Gadget Test" 'gadget-test) (make-demo-button "Drag and Drop" 'dragndrop) ( make - demo - button " Colorslider " ' colorslider ) (make-demo-button "D&D Translator" 'drag-test) (make-demo-button "Draggable Graph" 'draggable-graph-demo) (make-demo-button "Image viewer" 'image-viewer) (make-pane 'push-button :label "Font Selector" :activate-callback (lambda (&rest ignore) (declare (ignore ignore)) (format *trace-output* "~&You chose: ~A~%" (select-font)))) (make-demo-button "Tab Layout" 'tabdemo:tabdemo))) (labelling (:label "Tests") (vertically (:equalize-width t) (make-demo-button "Label Test" 'label-test) (make-demo-button "Table Test" 'table-test) (make-demo-button "Scroll Test" 'Scroll-test) (make-demo-button "List Test" 'list-test) (make-demo-button "HBOX Test" 'hbox-test) (make-demo-button "Text Size Test" 'text-size-test) (make-demo-button "Goatee Test" 'goatee::goatee-test) (make-demo-button "Drawing Benchmark" 'drawing-benchmark) (make-demo-button "Border Styles Test" 'bordered-output) (make-demo-button "Misc. Tests" 'misc-tests))))))))) (defun demodemo () #+nil (loop for port in climi::*all-ports* do (destroy-port port)) (run-frame-top-level (make-application-frame 'demodemo))) (define-application-frame hbox-test () () (:layouts (default (horizontally (:background climi::*3d-normal-color*) 30 (make-pane 'push-button :label "Okay" :width '(50 :mm)) '+fill+ (make-pane 'push-button :label "Cancel") '+fill+ (make-pane 'push-button :label "Help") 5 ) ))) (define-application-frame table-test () () (:layouts (default (tabling (:background +red+) (list (make-pane 'push-button :label "Last Name" :max-height +fill+) : fill+ (list (make-pane 'push-button :label "C 1 0") (make-pane 'push-button :label "C 1 1")) ) ))) (defun make-test-label (ax ay) (labelling (:label "Some Label" :align-x ax :label-alignment ay :foreground +WHITE+ :background +PALETURQUOISE4+ :text-style (make-text-style :sans-serif :roman :normal)) (make-pane 'push-button :label (format nil "~S" (list ax ay)) :text-style (make-text-style :sans-serif :roman :normal) :max-width 1000 :max-height 1000))) (defun make-test-label2 (ax ay) (labelling (:label (format nil "~(~S~)" (list ax ay)) :align-x ax :label-alignment ay :foreground +WHITE+ :background +PALETURQUOISE4+ :text-style (make-text-style :sans-serif :roman :normal)) #+nil (make-pane 'push-button :label :text-style (make-text-style :sans-serif :roman :normal) :max-width 1000 :max-height 1000))) (define-application-frame label-test () () (:layouts (default ( scrolling (: width 400 : height 200 : max - width 1000 : max - height 2000 ) (vertically (:equalize-width t :max-width 2000 :max-height 2000) 10 (labelling (:label "CLIM Label Tests" :align-x :center :text-style (make-text-style :sans-serif :roman :huge))) 10 (9/10 (horizontally (:equalize-height t) (1/2 (labelling (:label "Labels with content") (vertically (:equalize-width t) (make-test-label :left :top) 5 (make-test-label :center :top) 5 (make-test-label :right :top) 5 (make-test-label :left :bottom) 5 (make-test-label :center :bottom) 5 (make-test-label :right :bottom)))) (1/2 (labelling (:label "Labels w/o content") (vertically (:equalize-width t) (make-test-label2 :left :top) 5 (make-test-label2 :center :top) 5 (make-test-label2 :right :top) 5 (make-test-label2 :left :bottom) 5 (make-test-label2 :center :bottom) 5 (make-test-label2 :right :bottom)))))))))) (defclass foo-pane (basic-pane permanent-medium-sheet-output-mixin) ()) (defmethod compose-space ((pane foo-pane) &key width height) (declare (ignore width height)) (make-space-requirement :width 800 :height 1e3)) (defmethod repaint-sheet ((pane foo-pane) region) (draw-line* pane 50 50 200 50) (multiple-value-bind (x1 y1 x2 y2) (bounding-rectangle* region) (let ((k 20)) (loop for y from (* k (floor (- y1 10) k)) below (+ y2 10) by k do (draw-text* pane (format nil "~D" y) 20 y))))) (defmethod dispatch-repaint ((foo-pane foo-pane) region) (repaint-sheet foo-pane region)) (defmethod handle-event ((pane foo-pane) (event window-repaint-event)) (repaint-sheet pane (window-event-region event))) (define-application-frame scroll-test () () (:layouts (defaults (scrolling (:width 400 :height 400) (make-pane 'foo-pane))))) (define-application-frame list-test () () (:panes (substring :text-field :value "INTER") (result-list (make-pane 'list-pane :value 'clim:region-intersection :items (apropos-list "INTER" :clim t) :presentation-type-key (constantly 'list-test-symbol) :name-key (lambda (x) (format nil "~(~S~)" x)))) (interactor :interactor :height 200)) (:layouts (defaults (labelling (:label "Matching symbols" :text-style (make-text-style :sans-serif :roman :normal)) (vertically () (scrolling (:height 200) result-list) (horizontally () substring (make-pane 'push-button :label "Update" :activate-callback 'update-list-test)) interactor))))) (define-presentation-type list-test-symbol ()) (define-list-test-command com-describe-symbol ((sym 'list-test-symbol :gesture :select)) Let 's print only three lines , we do n't have space for more . (with-input-from-string (s (with-output-to-string (s) (describe sym s))) (dotimes (x 3) (write-line (read-line s nil "") *standard-input*)))) (defun update-list-test (pane) (declare (ignore pane)) (setf (list-pane-items (find-pane-named *application-frame* 'result-list)) (apropos-list (gadget-value (find-pane-named *application-frame* 'substring)) :clim t))) (format t "~&;; try (CLIM-DEMO::DEMODEMO)~%")
ffd20baf73a2d3fda3c061434bd984fd52f4702e91e426942073cbf252209732
maximedenes/native-coq
reserve.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) (* Reserved names *) open Errors open Util open Pp open Names open Nameops open Summary open Libobject open Lib open Topconstr open Libnames type key = | RefKey of global_reference | Oth let reserve_table = ref Idmap.empty let reserve_revtable = ref Gmapl.empty let aconstr_key = function (* Rem: AApp(ARef ref,[]) stands for @ref *) | AApp (ARef ref,args) -> RefKey(canonical_gr ref), Some (List.length args) | AList (_,_,AApp (ARef ref,args),_,_) | ABinderList (_,_,AApp (ARef ref,args),_) -> RefKey (canonical_gr ref), Some (List.length args) | ARef ref -> RefKey(canonical_gr ref), None | _ -> Oth, None let cache_reserved_type (_,(id,t)) = let key = fst (aconstr_key t) in reserve_table := Idmap.add id t !reserve_table; reserve_revtable := Gmapl.add key (t,id) !reserve_revtable let in_reserved : identifier * aconstr -> obj = declare_object {(default_object "RESERVED-TYPE") with cache_function = cache_reserved_type } let freeze_reserved () = (!reserve_table,!reserve_revtable) let unfreeze_reserved (r,rr) = reserve_table := r; reserve_revtable := rr let init_reserved () = reserve_table := Idmap.empty; reserve_revtable := Gmapl.empty let _ = Summary.declare_summary "reserved-type" { Summary.freeze_function = freeze_reserved; Summary.unfreeze_function = unfreeze_reserved; Summary.init_function = init_reserved } let declare_reserved_type_binding (loc,id) t = if id <> root_of_id id then user_err_loc(loc,"declare_reserved_type", (pr_id id ++ str " is not reservable: it must have no trailing digits, quote, or _")); begin try let _ = Idmap.find id !reserve_table in user_err_loc(loc,"declare_reserved_type", (pr_id id++str" is already bound to a type")) with Not_found -> () end; add_anonymous_leaf (in_reserved (id,t)) let declare_reserved_type idl t = List.iter (fun id -> declare_reserved_type_binding id t) (List.rev idl) let find_reserved_type id = Idmap.find (root_of_id id) !reserve_table let constr_key c = try RefKey (canonical_gr (global_of_constr (fst (Term.decompose_app c)))) with Not_found -> Oth let revert_reserved_type t = try let l = Gmapl.find (constr_key t) !reserve_revtable in let t = Detyping.detype false [] [] t in list_try_find (fun (pat,id) -> try let _ = match_aconstr false t ([],pat) in Name id with No_match -> failwith "") l with Not_found | Failure _ -> Anonymous let _ = Namegen.set_reserved_typed_name revert_reserved_type open Glob_term let anonymize_if_reserved na t = match na with | Name id as na -> (try if not !Flags.raw_print & (try aconstr_of_glob_constr [] [] t = find_reserved_type id with UserError _ -> false) then GHole (dummy_loc,Evd.BinderType na) else t with Not_found -> t) | Anonymous -> t
null
https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/interp/reserve.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** Reserved names Rem: AApp(ARef ref,[]) stands for @ref
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Errors open Util open Pp open Names open Nameops open Summary open Libobject open Lib open Topconstr open Libnames type key = | RefKey of global_reference | Oth let reserve_table = ref Idmap.empty let reserve_revtable = ref Gmapl.empty | AApp (ARef ref,args) -> RefKey(canonical_gr ref), Some (List.length args) | AList (_,_,AApp (ARef ref,args),_,_) | ABinderList (_,_,AApp (ARef ref,args),_) -> RefKey (canonical_gr ref), Some (List.length args) | ARef ref -> RefKey(canonical_gr ref), None | _ -> Oth, None let cache_reserved_type (_,(id,t)) = let key = fst (aconstr_key t) in reserve_table := Idmap.add id t !reserve_table; reserve_revtable := Gmapl.add key (t,id) !reserve_revtable let in_reserved : identifier * aconstr -> obj = declare_object {(default_object "RESERVED-TYPE") with cache_function = cache_reserved_type } let freeze_reserved () = (!reserve_table,!reserve_revtable) let unfreeze_reserved (r,rr) = reserve_table := r; reserve_revtable := rr let init_reserved () = reserve_table := Idmap.empty; reserve_revtable := Gmapl.empty let _ = Summary.declare_summary "reserved-type" { Summary.freeze_function = freeze_reserved; Summary.unfreeze_function = unfreeze_reserved; Summary.init_function = init_reserved } let declare_reserved_type_binding (loc,id) t = if id <> root_of_id id then user_err_loc(loc,"declare_reserved_type", (pr_id id ++ str " is not reservable: it must have no trailing digits, quote, or _")); begin try let _ = Idmap.find id !reserve_table in user_err_loc(loc,"declare_reserved_type", (pr_id id++str" is already bound to a type")) with Not_found -> () end; add_anonymous_leaf (in_reserved (id,t)) let declare_reserved_type idl t = List.iter (fun id -> declare_reserved_type_binding id t) (List.rev idl) let find_reserved_type id = Idmap.find (root_of_id id) !reserve_table let constr_key c = try RefKey (canonical_gr (global_of_constr (fst (Term.decompose_app c)))) with Not_found -> Oth let revert_reserved_type t = try let l = Gmapl.find (constr_key t) !reserve_revtable in let t = Detyping.detype false [] [] t in list_try_find (fun (pat,id) -> try let _ = match_aconstr false t ([],pat) in Name id with No_match -> failwith "") l with Not_found | Failure _ -> Anonymous let _ = Namegen.set_reserved_typed_name revert_reserved_type open Glob_term let anonymize_if_reserved na t = match na with | Name id as na -> (try if not !Flags.raw_print & (try aconstr_of_glob_constr [] [] t = find_reserved_type id with UserError _ -> false) then GHole (dummy_loc,Evd.BinderType na) else t with Not_found -> t) | Anonymous -> t
85ed083c3763a053f2666040d719b0a4a2f2a686e7bda67c0b6587dec87de228
seanomlor/programming-in-haskell
voting.hs
import Data.List type Vote = String votes :: [Vote] votes = ["Red", "Blue", "Green", "Blue", "Blue", "Red"] --count :: Eq a => a -> [a] -> Int count :: Vote -> [Vote] -> Int count x = length . filter (== x) -- rmdups [ 1 , 5 , 5 , 3 , 2 , 1 ] 1 : filter ( /= 1 ) ( rmdups [ 5 , 5 , 3 , 2 , 1 ] ) rmdups [ 5 , 5 , 3 , 2 , 1 ] 5 : filter ( /= 5 ) ( rmdups [ 5 , 3 , 2 , 1 ] ) rmdups [ 5 , 3 , 2 , 1 ] 5 : filter ( /= 5 ) ( rmdups [ 3 , 2 , 1 ] ) rmdups [ 3 , 2 , 1 ] 3 : filter ( /= 3 ) ( rmdups [ 2 , 1 ] ) rmdups [ 2 , 1 ] 2 : filter ( /= 2 ) ( rmdups [ 1 ] ) rmdups [ 1 ] 1 : filter ( /= 1 ) ( rmdups [ ] ) -- rmdups [] -- [] -- -- rmdups :: Eq a => [a] -> [a] rmdups :: [Vote] -> [Vote] rmdups [] = [] rmdups (x:xs) = x : filter (/= x) (rmdups xs) -- -- example: -- > result votes [ ( 1 , " Green " ) , ( 2 , " Red " ) , ( 3 , " Blue " ) ] -- result : : a = > [ a ] - > [ ( Int , a ) ] result :: [Vote] -> [(Int, Vote)] result vs = sort [(count v vs, v) | v <- rmdups vs] winner :: [Vote] -> Vote winner = snd . last . result -- runoff voting ballots :: [[Vote]] ballots = [ ["Red", "Green"] , ["Blue"] , ["Green", "Red", "Blue"] , ["Blue", "Green", "Red"] , ["Green"] ] rmempty :: [[Vote]] -> [[Vote]] rmempty = filter (/= []) elim :: Vote -> [[Vote]] -> [[Vote]] elim x = map (filter (/= x)) -- -- rank ballots -- ["Red", "Blue", "Green"] -- rank :: [[Vote]] -> [Vote] rank = map snd . result . map head winner' :: [[Vote]] -> Vote winner' bs = case rank (rmempty bs) of [] -> "unknown rank" [c] -> c (c:_) -> winner' (elim c bs)
null
https://raw.githubusercontent.com/seanomlor/programming-in-haskell/e05142e6709eeba2e95cf86f376a32c9e629df88/07-higher-order-functions/voting.hs
haskell
count :: Eq a => a -> [a] -> Int rmdups [] [] rmdups :: Eq a => [a] -> [a] example: > result votes runoff voting rank ballots ["Red", "Blue", "Green"]
import Data.List type Vote = String votes :: [Vote] votes = ["Red", "Blue", "Green", "Blue", "Blue", "Red"] count :: Vote -> [Vote] -> Int count x = length . filter (== x) rmdups [ 1 , 5 , 5 , 3 , 2 , 1 ] 1 : filter ( /= 1 ) ( rmdups [ 5 , 5 , 3 , 2 , 1 ] ) rmdups [ 5 , 5 , 3 , 2 , 1 ] 5 : filter ( /= 5 ) ( rmdups [ 5 , 3 , 2 , 1 ] ) rmdups [ 5 , 3 , 2 , 1 ] 5 : filter ( /= 5 ) ( rmdups [ 3 , 2 , 1 ] ) rmdups [ 3 , 2 , 1 ] 3 : filter ( /= 3 ) ( rmdups [ 2 , 1 ] ) rmdups [ 2 , 1 ] 2 : filter ( /= 2 ) ( rmdups [ 1 ] ) rmdups [ 1 ] 1 : filter ( /= 1 ) ( rmdups [ ] ) rmdups :: [Vote] -> [Vote] rmdups [] = [] rmdups (x:xs) = x : filter (/= x) (rmdups xs) [ ( 1 , " Green " ) , ( 2 , " Red " ) , ( 3 , " Blue " ) ] result : : a = > [ a ] - > [ ( Int , a ) ] result :: [Vote] -> [(Int, Vote)] result vs = sort [(count v vs, v) | v <- rmdups vs] winner :: [Vote] -> Vote winner = snd . last . result ballots :: [[Vote]] ballots = [ ["Red", "Green"] , ["Blue"] , ["Green", "Red", "Blue"] , ["Blue", "Green", "Red"] , ["Green"] ] rmempty :: [[Vote]] -> [[Vote]] rmempty = filter (/= []) elim :: Vote -> [[Vote]] -> [[Vote]] elim x = map (filter (/= x)) rank :: [[Vote]] -> [Vote] rank = map snd . result . map head winner' :: [[Vote]] -> Vote winner' bs = case rank (rmempty bs) of [] -> "unknown rank" [c] -> c (c:_) -> winner' (elim c bs)
d9e7bbe197224642e288c56722dc1b4ea3d085a6f7d2deeaf08e31307b1a701d
haskell-lisp/yale-haskell
xlibclx.scm
xlibclx.scm -- Lisp support for Haskell / CLX interface ;; general (define-syntax (nth-value n form) (cond ((eqv? n 0) `(values ,form)) ((number? n) (let ((temps '())) (dotimes (i n) (declare (ignorable i)) (push (gensym) temps)) `(multiple-value-bind ,(reverse temps) ,form (declare (ignore ,@(reverse (cdr temps)))) ,(car temps)))) (else `(lisp:nth ,n (lisp:multiple-value-list ,form))) )) (define-local-syntax (keywordify string) `(lisp:intern ,string (lisp:find-package "KEYWORD"))) (define-local-syntax (xlibify string) `(lisp:intern ,string (lisp:find-package "XLIB"))) ;;; This is stuff to support slots that consist of a keyword/value ;;; pair. Note that the value is always unboxed. (define-syntax (make-keyword key value) `(cons ,key ,value)) (define-syntax (is-keyword? x key) `(eq? (car ,x) ,key)) (define-syntax (keyword-key x) `(car ,x)) (define-syntax (keyword-val x) `(cdr ,x)) (define-syntax (define-keyword-constructor name) (let* ((name-str (symbol->string name)) (key (keywordify name-str)) (is-name (string->symbol (string-append "IS-" name-str))) (mk-name (string->symbol (string-append "MK-" name-str)))) `(begin (define (,mk-name x) (make-keyword ,key x)) (define (,is-name x) (is-keyword? x ,key))) )) (define-syntax (define-event-slot-finder slot) (let* ((slot-str (symbol->string slot)) (slot-key (keywordify slot-str)) (fun (string->symbol (string-append "X-EVENT-" slot-str)))) `(define (,fun event) (lookup-event-slot (cdr event) ,slot-key)))) (define (lookup-event-slot event key) (if (null? event) (error "non-existent event slot: ~A" key) (if (eq? key (car event)) (cadr event) (lookup-event-slot (cddr event) key)))) (define-syntax (define-attribute-setter entity attribute) (let* ((entity-attr (string-append (symbol->string entity) "-" (symbol->string attribute))) (fun-name (string->symbol (string-append "X-SET-" entity-attr))) (xfun-name (xlibify entity-attr))) `(define (,fun-name ,entity ,attribute) (setf (,xfun-name ,entity) ,attribute)))) (define-syntax (make-h-tuple . args) (let ((nargs (map (lambda (arg) `(box ,arg)) args))) `(make-tuple ,@nargs))) type XError (define (cons-xerror x) (declare (ignore x)) (error "can't construct XError")) (define (x-error-string c) (make-haskell-string (format '#f "~A" c))) ;;; The forces here are necessary because the thing being funcalled ;;; returns a data structure of type (IO a), and we need to do ;;; an IO a -> a transformation. #+lucid (define (x-handle-error handler body) (lisp:catch 'x-error-handle (lcl:handler-bind ((lisp:error (mk-handler handler))) (force (funcall body (box 'state)))))) #+(or cmu allegro lispworks) (define (x-handle-error handler body) (lisp:catch 'x-error-handle (lisp:handler-bind ((lisp:error (mk-handler handler))) (force (funcall body (box 'state)))))) #+akcl (define (x-handle-error handler body) (error "AKCL does not support HANDLER-BIND!")) (define (mk-handler handler) (lambda (c) (lisp:throw 'x-error-handle (force (funcall handler (box c) (box 'state)))))) for type (define (not-null? x) (not (null? x))) For Bitmap , Pixarray , KeysymTable (define (array2->haskell-list a) (let* ((dims (lisp:array-dimensions a)) (i1max (car dims)) (i2max (cadr dims))) (declare (type fixnum i1max i2max)) (do ((i1 (the fixnum (1- i1max)) (the fixnum (1- i1))) (outer '())) ((< i1 0) outer) (declare (type fixnum i1)) (setf outer (cons (box (do ((i2 (the fixnum (1- i2max)) (the fixnum (1- i2))) (inner '())) ((< i2 0) inner) (declare (type fixnum i2)) (setf inner (cons (box (lisp:aref a i1 i2)) (box inner))))) (box outer)))) )) ;; Bitmap (define (mk-bitmap ll) (let ((l (haskell-list->list #'haskell-list->list/identity ll))) (lisp:make-array `(,(length l) , (length (car l))) :element-type 'lisp:bit :initial-contents l))) (define (sel-bitmap l) (array2->haskell-list l)) ;; XKeysymTable (define (mk-keysym-table ll) (let ((l (haskell-list->list #'haskell-list->list/identity ll))) (lisp:make-array `(,(length l) , (length (car l))) :element-type 'xlib:card32 :initial-contents l))) (define (sel-keysym-table l) (array2->haskell-list l)) ;; XPixarray (define (mk-pixarray ll) (let ((l (haskell-list->list #'haskell-list->list/identity ll))) (let* ((max-num (find-max l)) (pix-type (cond ((<= max-num 1) 'lisp:bit) ((<= max-num 15) '(lisp:unsigned-byte 4)) ((<= max-num 255) 'xlib:card8) ((<= max-num 65535) 'xlib:card16) (else 'xlib:card32)))) (declare (type integer max-num)) (lisp:make-array `(,(length l) , (length (car l))) :element-type pix-type :initial-contents l)))) (define (find-max l) (let ((max 0)) (dolist (ll l) (dolist (lll ll) (when (> (the integer lll) (the integer max)) (setf max lll)))) max)) (define (sel-pixarray l) (array2->haskell-list l)) ;;; Can't use mumble vector primitives on arrays of specialized types! (define (array1->haskell-list a) (declare (type lisp:vector a)) (let ((imax (lisp:length a))) (declare (type fixnum imax)) (do ((i (the fixnum (1- imax)) (the fixnum (1- i))) (result '())) ((< i 0) result) (declare (type fixnum i)) (setf result (cons (box (lisp:aref a i)) (box result)))))) ;; BitVec (define (mk-bitvec ll) (let ((l (haskell-list->list/identity ll))) (lisp:make-array `(,(length l)) :element-type 'lisp:bit :initial-contents l))) (define (sel-bitvec l) (array1->haskell-list l)) ByteVec (define (mk-bytevec ll) (let ((l (haskell-list->list/identity ll))) (lisp:make-array `(,(length l)) :element-type 'xlib:card8 :initial-contents l))) (define (sel-bytevec l) (array1->haskell-list l)) ;; XAtom (define (mk-atom name) (keywordify (haskell-string->string name))) (define (sel-atom atom) (make-haskell-string (symbol->string atom))) ;; XProperty ;;; watch out for name conflict with :property keyword stuff (define (mk-xproperty d ty f) (list (haskell-list->list/identity d) ty f)) (define (sel-xproperty-data p) (list->haskell-list/identity (car p))) (define (sel-xproperty-type p) (cadr p)) (define (sel-xproperty-format p) (caddr p)) (define (mk-event type slots) (cons type (slots->keywords (haskell-list->list/identity slots)))) (define (sel-event-type event) (car event)) (define (sel-event-slots event) (list->haskell-list/identity (keywords->slots (car event) (cdr event) event))) ;; XEventSlot (define-keyword-constructor window) (define-keyword-constructor event-window) (define-keyword-constructor code) (define-keyword-constructor pos) (define-keyword-constructor state) (define-keyword-constructor time) (define-keyword-constructor root) (define-keyword-constructor root-pos) (define-keyword-constructor child) (define-keyword-constructor same-screen-p) (define-keyword-constructor hint-p) (define-keyword-constructor mode) (define-keyword-constructor kind) (define-keyword-constructor focus-p) (define-keyword-constructor keymap) (define-keyword-constructor request) (define-keyword-constructor start) (define-keyword-constructor count) (define-keyword-constructor rect) (define-keyword-constructor drawable) (define-keyword-constructor graph-fun) (define-keyword-constructor place) (define-keyword-constructor border-width) (define-keyword-constructor above-sibling) (define-keyword-constructor override-redirect-p) (define-keyword-constructor parent) (define-keyword-constructor configure-p) (define-keyword-constructor visibility) (define-keyword-constructor new-p) (define-keyword-constructor installed-p) (define-keyword-constructor stack-mode) (define-keyword-constructor value-mask) (define-keyword-constructor size) (define-keyword-constructor message) (define-keyword-constructor property-state) (define-keyword-constructor atom) (define-keyword-constructor selection) (define-keyword-constructor target) (define-keyword-constructor property) (define-keyword-constructor requestor) (define-event-slot-finder window) (define-event-slot-finder event-window) (define-event-slot-finder code) (define-event-slot-finder x) (define-event-slot-finder y) (define-event-slot-finder state) (define-event-slot-finder time) (define-event-slot-finder root) (define-event-slot-finder root-x) (define-event-slot-finder root-y) (define-event-slot-finder child) (define-event-slot-finder same-screen-p) (define-event-slot-finder hint-p) (define-event-slot-finder mode) (define-event-slot-finder kind) (define-event-slot-finder focus-p) (define-event-slot-finder keymap) (define-event-slot-finder request) (define-event-slot-finder start) (define-event-slot-finder count) (define-event-slot-finder width) (define-event-slot-finder height) (define-event-slot-finder drawable) (define-event-slot-finder major) (define-event-slot-finder minor) (define-event-slot-finder place) (define-event-slot-finder border-width) (define-event-slot-finder above-sibling) (define-event-slot-finder override-redirect-p) (define-event-slot-finder parent) (define-event-slot-finder configure-p) (define-event-slot-finder new-p) (define-event-slot-finder installed-p) (define-event-slot-finder stack-mode) (define-event-slot-finder value-mask) (define-event-slot-finder data) (define-event-slot-finder type) (define-event-slot-finder format) (define-event-slot-finder atom) (define-event-slot-finder selection) (define-event-slot-finder target) (define-event-slot-finder property) (define-event-slot-finder requestor) (define (x-event-pos event) (mk-xpoint (x-event-x event) (x-event-y event))) (define (x-event-root-pos event) (mk-xpoint (x-event-root-x event) (x-event-root-y event))) (define (x-event-size event) (mk-xsize (x-event-width event) (x-event-height event))) (define (x-event-rect event) (mk-xrect (x-event-x event) (x-event-y event) (x-event-width event) (x-event-height event))) (define (x-event-graph-fun event) (cons (x-event-major event) (x-event-minor event))) (define (x-event-message event) (list (sequence->list (x-event-data event)) (x-event-type event) (x-event-format event))) (define (x-make-event-mask keys) (apply (function xlib:make-event-mask) (haskell-list->list/identity keys))) (define (x-event-mask-key-list mask) (list->haskell-list/identity (xlib:make-event-keys mask))) XStateMask (define (x-make-state-mask keys) (apply (function xlib:make-state-mask) (haskell-list->list/identity keys))) (define (x-state-mask-key-list mask) (list->haskell-list/identity (xlib:make-state-keys mask))) (define-keyword-constructor background) (define-keyword-constructor foreground) (define-keyword-constructor event-mask) (define-keyword-constructor depth) (define-keyword-constructor border-width) (define-keyword-constructor class) (define-keyword-constructor visual) (define-keyword-constructor border) (define-keyword-constructor backing-store) (define-keyword-constructor backing-planes) (define-keyword-constructor backing-pixel) (define-keyword-constructor save-under) (define-keyword-constructor do-not-propagate-mask) (define-keyword-constructor override-redirect) (define-keyword-constructor colormap) (define-keyword-constructor cursor) (define-keyword-constructor arc-mode) (define-keyword-constructor cap-style) (define-keyword-constructor clip-mask) (define-keyword-constructor clip-origin) (define-keyword-constructor dash-offset) (define-keyword-constructor dashes) (define-keyword-constructor exposures) (define-keyword-constructor fill-rule) (define-keyword-constructor fill-style) (define-keyword-constructor font) (define-keyword-constructor function) (define-keyword-constructor join-style) (define-keyword-constructor line-style) (define-keyword-constructor line-width) (define-keyword-constructor plane-mask) (define-keyword-constructor stipple) (define-keyword-constructor subwindow-mode) (define-keyword-constructor tile) (define-keyword-constructor tile-origin) (define-keyword-constructor bit-lsb-first-p) (define-keyword-constructor bits-per-pixel) (define-keyword-constructor blue-mask) (define-keyword-constructor byte-lsb-first-p) (define-keyword-constructor bytes-per-line) (define-keyword-constructor data) (define-keyword-constructor format) (define-keyword-constructor green-mask) (define-keyword-constructor size) (define-keyword-constructor name) (define-keyword-constructor red-mask) (define-keyword-constructor hot-spot) (define-keyword-constructor owner-p) (define-keyword-constructor sync-pointer-p) (define-keyword-constructor sync-keyboard-p) (define-keyword-constructor confine-to) ;; XClipMask (define (not-pixmap-and-list-p x) (and (pair? x) (not (xlib:pixmap-p x)))) (define (mk-clip-mask-rects rects) (rects->point-seq (haskell-list->list/identity rects))) (define (sel-clip-mask-rects point-seq) (list->haskell-list/identity (point-seq->rects point-seq))) XPoint (define (mk-xpoint x y) (cons x y)) (define (xpoint-x x) (car x)) (define (xpoint-y x) (cdr x)) XSize (define (mk-xsize x y) (cons x y)) (define (xsize-w x) (car x)) (define (xsize-h x) (cdr x)) XRect (define (mk-xrect x y w h) (vector x y w h)) (define (xrect-x x) (vector-ref x 0)) (define (xrect-y x) (vector-ref x 1)) (define (xrect-w x) (vector-ref x 2)) (define (xrect-h x) (vector-ref x 3)) XArc (define (mk-xarc x y w h a1 a2) (vector x y w h a1 a2)) (define (xarc-x x) (vector-ref x 0)) (define (xarc-y x) (vector-ref x 1)) (define (xarc-w x) (vector-ref x 2)) (define (xarc-h x) (vector-ref x 3)) (define (xarc-a1 x) (vector-ref x 4)) (define (xarc-a2 x) (vector-ref x 5)) BitmapFormat (define (mk-bitmap-format u p l) (xlib::make-bitmap-format :unit u :pad p :lsb-first-p l)) PixmapFormat (define (mk-pixmap-format u p l) (xlib::make-pixmap-format :depth u :bits-per-pixel p :scanline-pad l)) ;; XVisualInfo (define (mk-xvisual-info id cl rm gm bm bs es) (xlib::make-visual-info :id id :class cl :red-mask rm :green-mask gm :blue-mask bm :bits-per-rgb bs :colormap-entries es)) ;; XFillContent (define (is-fill-pixel x) (not (or (xlib:pixmap-p x) (symbol? x)))) ;; XBackingStore ;; XImageData (define (bitmap-list-p x) (pair? x)) (define (pixarray-p x) (and (not (pair? x)) (eq? (lisp:array-rank x) 2))) (define (bytevec-p x) (and (not (pair? x)) (eq? (lisp:array-rank x) 1))) XColor (define (mk-color r g b) (xlib:make-color :red r :green g :blue b)) (define (x-print x) (print x)) (define (x-set-event-mask-key mask key-sym) (lisp:logior mask (xlib:make-event-mask key-sym))) (define (x-clear-event-mask-key mask key-sym) (lisp:logand mask (lisp:lognot (xlib:make-event-mask key-sym)))) (define (x-test-event-mask-key mask key-sym) (if (eqv? 0 (lisp:logand mask (xlib:make-event-mask key-sym))) '#f '#t)) (define (x-set-state-mask-key mask key-sym) (lisp:logior mask (xlib:make-state-mask key-sym))) (define (x-clear-state-mask-key mask key-sym) (lisp:logand mask (lisp:lognot (xlib:make-state-mask key-sym)))) (define (x-test-state-mask-key mask key-sym) (if (eqv? 0 (lisp:logand mask (xlib:make-state-mask key-sym))) '#f '#t)) ;;; Display is a string of the format name:d.s ignore s ; if d is omitted , default it to zero . (define (x-open-display display) (let* ((end (string-length display)) (colon (or (string-position #\: display 0 end) end)) (dot (or (string-position #\. display colon end) end))) (declare (type fixnum end colon dot)) (xlib:open-display (substring display 0 colon) :display (if (eqv? colon dot) 0 (string->number (substring display (1+ colon) dot)))))) (define (x-set-display-error-handler display error-fun) (declare (ignore display error-fun)) (error "not implemented")) (define (x-set-display-after-function display after-fun) (declare (ignore display after-fun)) (error "not implemented")) (define (x-screen-depths screen) (let ((depths (xlib:screen-depths screen))) (map (lambda (l) (make-h-tuple (car l) (list->haskell-list/identity (cdr l)))) depths))) (define (x-screen-size screen) (mk-xsize (xlib:screen-width screen) (xlib:screen-height screen))) (define (x-screen-mmsize screen) (mk-xsize (xlib:screen-width-in-millimeters screen) (xlib:screen-height-in-millimeters screen))) (define (x-create-window parent rect attrs) (apply (function XLIB:CREATE-WINDOW) `(:parent ,parent :x ,(xrect-x rect) :y ,(xrect-y rect) :width ,(xrect-w rect) :height ,(xrect-h rect) ,@(attrs->keywords attrs)))) (define-attribute-setter drawable border-width) (define (x-drawable-size drawable) (mk-xsize (xlib:drawable-width drawable) (xlib:drawable-height drawable))) (define (x-drawable-resize drawable size) (setf (xlib:drawable-width drawable) (xsize-w size)) (setf (xlib:drawable-height drawable) (xsize-h size))) (define (x-window-pos window) (mk-xpoint (xlib:drawable-x window) (xlib:drawable-y window))) (define (x-window-move window point) (setf (xlib:drawable-x window) (xpoint-x point)) (setf (xlib:drawable-y window) (xpoint-y point))) (define-attribute-setter window background) (define-attribute-setter window backing-pixel) (define-attribute-setter window backing-planes) (define-attribute-setter window backing-store) (define-attribute-setter window bit-gravity) (define-attribute-setter window border) (define-attribute-setter window colormap) (define (x-set-window-cursor window cursor) (let ((val (if (null? cursor) :none cursor))) (setf (xlib:window-cursor window) val))) (define-attribute-setter window do-not-propagate-mask) (define-attribute-setter window event-mask) (define-attribute-setter window gravity) (define-attribute-setter window override-redirect) (define-attribute-setter window priority) (define-attribute-setter window save-under) (define (x-query-tree window) (multiple-value-bind (children parent root) (xlib:query-tree window) (make-h-tuple (list->haskell-list/identity children) parent root))) (define (x-reparent-window window parent point) (xlib:reparent-window window parent (xpoint-x point) (xpoint-y point))) (define (x-translate-coordinates source point dest) (xlib:translate-coordinates source (xpoint-x point) (xpoint-y point) dest)) (define (x-create-pixmap size depth drawable) (xlib:create-pixmap :width (xsize-w size) :height (xsize-h size) :depth depth :drawable drawable)) (define (x-create-gcontext drawable attrs) (apply (function XLIB:CREATE-GCONTEXT) `(:drawable ,drawable ,@(attrs->keywords attrs)))) (define (x-update-gcontext gcontext attrs) (do ((keys (attrs->keywords attrs) (cddr keys))) ((null? keys)) (x-update-gcontext-attr gcontext (car keys) (cadr keys)))) (define (x-update-gcontext-attr gcontext key attr) (case key (:arc-mode (setf (xlib:gcontext-arc-mode gcontext) attr)) (:background (setf (xlib:gcontext-background gcontext) attr)) (:cap-style (setf (xlib:gcontext-cap-style gcontext) attr)) (:fill-style (setf (xlib:gcontext-fill-style gcontext) attr)) (:clip-mask (setf (xlib:gcontext-clip-mask gcontext) attr)) (:clip-x (setf (xlib:gcontext-clip-x gcontext) attr)) (:clip-y (setf (xlib:gcontext-clip-y gcontext) attr)) (:dash-offset (setf (xlib:gcontext-dash-offset gcontext) attr)) (:dashes (setf (xlib:gcontext-dashes gcontext) attr)) (:exposures (setf (xlib:gcontext-exposures gcontext) attr)) (:fill-rule (setf (xlib:gcontext-fill-rule gcontext) attr)) (:font (setf (xlib:gcontext-font gcontext) attr)) (:foreground (setf (xlib:gcontext-foreground gcontext) attr)) (: function ( setf ( : gcontext - function gcontext ) attr ) ) (:join-style (setf (xlib:gcontext-join-style gcontext) attr)) (:line-style (setf (xlib:gcontext-line-style gcontext) attr)) (: line - width ( setf ( : gcontext - line - width gcontext ) attr ) ) (: plane - mask ( setf ( : gcontext - plane - mask gcontext ) attr ) ) (: stipple ( setf ( : gcontext - stipple gcontext ) attr ) ) (:subwindow-mode (setf (xlib:gcontext-subwindow-mode gcontext) attr)) (: tile ( setf ( : gcontext - tile gcontext ) attr ) ) (: ( setf ( : gcontext ) attr ) ) (: ( setf ( : gcontext - ts - y gcontext ) attr ) ) (else (format '#t "Graphics context attribute ~A is not settable.~%" key)))) (define (x-query-best-stipple dsize drawable) (multiple-value-bind (w h) (xlib:query-best-stipple (xsize-w dsize) (xsize-h dsize) drawable) (mk-xsize w h))) (define (x-query-best-tile dsize drawable) (multiple-value-bind (w h) (xlib:query-best-tile (xsize-w dsize) (xsize-h dsize) drawable) (mk-xsize w h))) (define (x-clear-area window rect exposures-p) (xlib:clear-area window :x (xrect-x rect) :y (xrect-y rect) :width (xrect-w rect) :height (xrect-h rect) :exposures-p exposures-p)) (define (x-copy-area src gcontext rect dest point) (xlib:copy-area src gcontext (xrect-x rect) (xrect-y rect) (xrect-w rect) (xrect-h rect) dest (xpoint-x point) (xpoint-y point))) (define (x-copy-plane src gcontext plane rect dest point) (xlib:copy-plane src gcontext plane (xrect-x rect) (xrect-y rect) (xrect-w rect) (xrect-h rect) dest (xpoint-x point) (xpoint-y point))) (define (x-draw-point drawable gcontext point) (xlib:draw-point drawable gcontext (xpoint-x point) (xpoint-y point))) (define (x-draw-points drawable gcontext points) (xlib:draw-points drawable gcontext (points->point-seq points))) (define (points->point-seq points) (if (null? points) '() (let ((point (car points))) (lisp:list* (xpoint-x point) (xpoint-y point) (points->point-seq (cdr points)))))) (define (segments->point-seq segments) (if (null? segments) '() (let* ((first-pair (car segments)) (point-1 (force (tuple-select 2 0 first-pair))) (point-2 (force (tuple-select 2 1 first-pair)))) (lisp:list* (xpoint-x point-1) (xpoint-y point-1) (xpoint-x point-2) (xpoint-y point-2) (segments->point-seq (cdr segments)))))) (define (rects->point-seq rects) (if (null? rects) '() (let ((rect (car rects))) (lisp:list* (xrect-x rect) (xrect-y rect) (xrect-w rect) (xrect-h rect) (rects->point-seq (cdr rects)))))) (define (point-seq->rects point-seq) (if (null? point-seq) '() (cons (mk-xrect (car point-seq) (cadr point-seq) (caddr point-seq) (cadddr point-seq)) (point-seq->rects (cddddr point-seq))))) (define (arcs->point-seq arcs) (if (null? arcs) '() (let ((arc (car arcs))) (lisp:list* (xarc-x arc) (xarc-y arc) (xarc-w arc) (xarc-h arc) (xarc-a1 arc) (xarc-a2 arc) (arcs->point-seq (cdr arcs)))))) (define (x-draw-line drawable gcontext point-1 point-2) (xlib:draw-line drawable gcontext (xpoint-x point-1) (xpoint-y point-1) (xpoint-x point-2) (xpoint-y point-2))) (define (x-draw-lines drawable gcontext points fill-p) (xlib:draw-lines drawable gcontext (points->point-seq points) :fill-p fill-p)) (define (x-draw-segments drawable gcontext segments) (xlib:draw-segments drawable gcontext (segments->point-seq segments))) (define (x-draw-rectangle drawable gcontext rect fill-p) (xlib:draw-rectangle drawable gcontext (xrect-x rect) (xrect-y rect) (xrect-w rect) (xrect-h rect) fill-p)) (define (x-draw-rectangles drawable gcontext rects fill-p) (xlib:draw-rectangles drawable gcontext (rects->point-seq rects) fill-p)) (define (x-draw-arc drawable gcontext arc fill-p) (xlib:draw-arc drawable gcontext (xarc-x arc) (xarc-y arc) (xarc-w arc) (xarc-h arc) (xarc-a1 arc) (xarc-a2 arc) fill-p)) (define (x-draw-arcs drawable gcontext arcs fill-p) (xlib:draw-arcs drawable gcontext (arcs->point-seq arcs) fill-p)) (define (x-draw-glyph drawable gcontext point element) (nth-value 1 (xlib:draw-glyph drawable gcontext (xpoint-x point) (xpoint-y point) element))) (define (x-draw-glyphs drawable gcontext point element) (nth-value 1 (xlib:draw-glyphs drawable gcontext (xpoint-x point) (xpoint-y point) element))) (define (x-draw-image-glyph drawable gcontext point element) (nth-value 1 (xlib:draw-image-glyph drawable gcontext (xpoint-x point) (xpoint-y point) element))) (define (x-draw-image-glyphs drawable gcontext point element) (nth-value 1 (xlib:draw-image-glyphs drawable gcontext (xpoint-x point) (xpoint-y point) element))) (define (x-image-size image) (mk-xsize (xlib:image-width image) (xlib:image-height image))) (define (x-image-name image) (let ((lisp-name (xlib:image-name image))) (cond ((null? lisp-name) "") ((symbol? lisp-name) (symbol->string lisp-name)) (else lisp-name)))) (define-attribute-setter image name) (define (x-image-hot-spot image) (mk-xpoint (xlib:image-x-hot image) (xlib:image-y-hot image))) (define (x-set-image-hot-spot image point) (setf (xlib:image-x-hot image) (xpoint-x point)) (setf (xlib:image-y-hot image) (xpoint-y point))) (define-attribute-setter image xy-bitmap-list) (define-attribute-setter image z-bits-per-pixel) (define-attribute-setter image z-pixarray) (define (x-create-image attrs) (apply (function xlib:create-image) (attrs->keywords attrs))) (define (x-copy-image image rect type) (xlib:copy-image image :x (xrect-x rect) :y (xrect-y rect) :width (xrect-w rect) :height (xrect-h rect) :result-type type)) (define (x-get-image drawable rect pmask format type) (xlib:get-image drawable :x (xrect-x rect) :y (xrect-y rect) :width (xrect-w rect) :height (xrect-h rect) :plane-mask pmask :format format :result-type type)) (define (x-put-image drawable gcontext image point rect) (xlib:put-image drawable gcontext image :src-x (xpoint-x point) :src-y (xpoint-y point) :x (xrect-x rect) :y (xrect-y rect) :width (xrect-w rect) :height (xrect-h rect))) (define (x-get-raw-image drawable rect pmask format) (xlib:get-raw-image drawable :x (xrect-x rect) :y (xrect-y rect) :width (xrect-w rect) :height (xrect-h rect) :plane-mask pmask :format format)) (define (x-put-raw-image drawable gcontext data depth rect left-pad format) (xlib:put-raw-image drawable gcontext data :depth depth :x (xrect-x rect) :y (xrect-y rect) :width (xrect-w rect) :height (xrect-h rect) :left-pad left-pad :format format)) (define (x-font-name font) (let ((lisp-name (xlib:font-name font))) (cond ((null? lisp-name) "") ((symbol? lisp-name) (symbol->string lisp-name)) (else lisp-name)))) (define (x-alloc-color colormap color) (multiple-value-bind (pixel screen-color exact-color) (xlib:alloc-color colormap color) (make-h-tuple pixel screen-color exact-color))) (define (x-alloc-color-cells colormap colors planes contiguous-p) (multiple-value-bind (pixels mask) (xlib:alloc-color-cells colormap colors :planes planes :contiguous-p contiguous-p) (make-h-tuple (list->haskell-list/identity pixels) (list->haskell-list/identity mask)))) (define (x-alloc-color-planes colormap colors reds greens blues contiguous-p) (multiple-value-bind (pixels red-mask green-mask blue-mask) (xlib:alloc-color-planes colormap colors :reds reds :greens greens :blues blues :contiguous-p contiguous-p) (make-h-tuple (list->haskell-list/identity pixels) red-mask green-mask blue-mask))) (define (x-lookup-color colormap name) (multiple-value-bind (screen-color exact-color) (xlib:lookup-color colormap name) (make-h-tuple screen-color exact-color))) (define (unzip l) (if (null? l) '() (let ((h (car l))) (lisp:list* (force (tuple-select 2 0 h)) (force (tuple-select 2 1 h)) (unzip (cdr l)))))) (define (x-store-colors colormap pixel-colors) (xlib:store-colors colormap (unzip pixel-colors))) (define (x-create-cursor source mask point foreground background) (apply (function xlib:create-cursor) `(:source ,source ,@(if mask `(:mask ,mask) '()) :x ,(xpoint-x point) :y ,(xpoint-y point) :foreground ,foreground :background ,background))) (define (x-create-glyph-cursor src mask foreground background) (apply (function xlib:create-glyph-cursor) `(:source-font ,(force (tuple-select 2 0 src)) :source-char ,(integer->char (force (tuple-select 2 1 src))) ,@(if mask `(:mask-font ,(force (tuple-select 2 0 mask)) :mask-char ,(integer->char (force (tuple-select 2 1 mask)))) '()) :foreground ,foreground :background ,background))) (define (x-query-best-cursor size display) (multiple-value-bind (w h) (xlib:query-best-cursor (xsize-w size) (xsize-h size) display) (mk-xsize w h))) (define (x-change-property window property content) (xlib:change-property window property (car content) (cadr content) (caddr content))) (define (x-get-property window property) (lisp:multiple-value-bind (data type format) (xlib:get-property window property) (list (sequence->list data) type format))) (define (x-convert-selection selection type requestor property time) (apply (function xlib:convert-selection) `(,selection ,type ,requestor ,property ,@(if time `(,time) '())))) (define (x-set-selection-owner display selection time owner) (if time (setf (xlib:selection-owner display selection time) owner) (setf (xlib:selection-owner display selection) owner))) (define (sequence->list seq) (if (list? seq) seq (do ((i (1- (lisp:length seq)) (1- i)) (res '() (cons (lisp:elt seq i) res))) ((< i 0) res)))) (define *this-event* '()) (define (translate-event lisp:&rest event-slots lisp:&key event-key lisp:&allow-other-keys) (setf *this-event* (cons event-key event-slots)) '#t) (define (x-get-event display) (xlib:process-event display :handler #'translate-event :force-output-p '#t) *this-event*) (define (x-queue-event display event append-p) (apply (function xlib:queue-event) `(,display ,(car event) ,@(cdr event) :append-p ,append-p))) (define (x-event-listen display) (let ((res (xlib:event-listen display))) (if (null? res) 0 res))) (define (x-send-event window event mask) (apply (function xlib:send-event) `(,window ,(car event) ,mask ,@(cdr event)))) (define (x-global-pointer-position display) (multiple-value-bind (x y) (xlib:global-pointer-position display) (mk-xpoint x y))) (define (x-pointer-position window) (multiple-value-bind (x y same) (xlib:pointer-position window) (if same (mk-xpoint x y) '()))) (define (x-motion-events window start stop) (do ((npos '() (cons (mk-xpoint (car pos) (cadr pos)) npos)) (pos (xlib:motion-events window :start start :stop stop) (cdddr pos))) ((null? pos) (nreverse npos)))) (define (x-warp-pointer dest-win point) (xlib:warp-pointer dest-win (xpoint-x point) (xpoint-y point))) (define (x-set-input-focus display focus revert-to time) (apply (function xlib:set-input-focus) `(,display ,focus ,revert-to ,@(if time `(,time) '())))) (define (x-input-focus display) (multiple-value-bind (focus revert-to) (xlib:input-focus display) (make-h-tuple focus revert-to))) (define (x-grab-pointer window event-mask attrs time) (apply (function xlib:grab-pointer) `(,window ,event-mask ,@(attrs->keywords attrs) ,@(if time `(:time ,time) '())))) (define (x-ungrab-pointer display time) (if time (xlib:ungrab-pointer display :time time) (xlib:ungrab-pointer display))) (define (x-change-active-pointer-grab display event-mask attrs time) (apply (function xlib:change-active-pointer-grab) `(,display ,event-mask ,@(attrs->keywords attrs) ,@(if time `(,time) '())))) (define (x-grab-button window button event-mask state-mask attrs) (apply (function xlib:grab-button) `(,window ,button ,event-mask :modifiers ,state-mask ,@(attrs->keywords attrs)))) (define (x-ungrab-button window button modifiers) (xlib:ungrab-button window button :modifiers modifiers)) (define (x-grab-keyboard window attrs time) (apply (function xlib:grab-keyboard) `(,window ,@(attrs->keywords attrs) ,@(if time `(:time ,time) '())))) (define (x-ungrab-keyboard display time) (if time (xlib:ungrab-keyboard display :time time) (xlib:ungrab-keyboard display))) (define (x-grab-key window key state-mask attrs) (apply (function xlib:grab-key) `(,window ,key :modifiers ,state-mask ,@(attrs->keywords attrs)))) (define (x-ungrab-key window key modifiers) (xlib:ungrab-button window key :modifiers modifiers)) (define (x-set-pointer-acceleration display val) (xlib:change-pointer-control display :acceleration val)) (define (x-set-pointer-threshold display val) (xlib:change-pointer-control display :threshold val)) (define (x-pointer-acceleration display) (lisp:coerce (nth-value 0 (xlib:pointer-control display)) 'lisp:single-float)) (define (x-pointer-threshold display) (lisp:coerce (nth-value 1 (xlib:pointer-control display)) 'lisp:single-float)) (define-attribute-setter pointer mapping) (define (x-set-keyboard-key-click-percent display v) (xlib:change-keyboard-control display :key-click-percent v)) (define (x-set-keyboard-bell-percent display v) (xlib:change-keyboard-control display :bell-percent v)) (define (x-set-keyboard-bell-pitch display v) (xlib:change-keyboard-control display :bell-pitch v)) (define (x-set-keyboard-bell-duration display v) (xlib:change-keyboard-control display :bell-duration v)) Yes , leds are really counted from 1 rather than 0 . (define (x-set-keyboard-led display v) (declare (type integer v)) (do ((led 1 (1+ led)) (vv v (lisp:ash vv -1))) ((> led 32)) (declare (type fixnum led) (type integer vv)) (xlib:change-keyboard-control display :led led :led-mode (if (lisp:logand vv 1) :on :off)))) (define (x-set-keyboard-auto-repeat-mode display v) (do ((key 0 (1+ key))) ((>= key (lisp:length v))) (declare (type fixnum key)) (xlib:change-keyboard-control display :key key :auto-repeat-mode (if (eqv? (the fixnum (lisp:aref v key)) 1) :on :off) ))) (define (x-keyboard-key-click-percent display) (nth-value 0 (xlib:keyboard-control display))) (define (x-keyboard-bell-percent display) (nth-value 1 (xlib:keyboard-control display))) (define (x-keyboard-bell-pitch display) (nth-value 2 (xlib:keyboard-control display))) (define (x-keyboard-bell-duration display) (nth-value 3 (xlib:keyboard-control display))) (define (x-keyboard-led display) (nth-value 4 (xlib:keyboard-control display))) (define (x-keyboard-auto-repeat-mode display) (nth-value 6 (xlib:keyboard-control display))) (define (x-modifier-mapping display) (lisp:multiple-value-list (xlib:modifier-mapping display))) (define (x-set-modifier-mapping display l) (let ((l1 (cddddr l))) (xlib:set-modifier-mapping display :shift (car l) :lock (cadr l) :control (caddr l) :mod1 (cadddr l) :mod2 (car l1) :mod3 (cadr l1) :mod4 (caddr l1) :mod5 (cadddr l1)))) (define (x-keysym-character display keysym state) (let ((res (xlib:keysym->character display keysym state))) (if (char? res) (char->integer res) '()))) (define (x-keycode-character display keycode state) (let ((res (xlib:keycode->character display keycode state))) (if (char? res) (char->integer res) '()))) (define-attribute-setter close-down mode) (define-attribute-setter access control) (define (x-screen-saver display) (lisp:multiple-value-list (xlib:screen-saver display))) (define (x-set-screen-saver display ss) (xlib:set-screen-saver display (car ss) (cadr ss) (caddr ss) (cadddr ss))) (define (slots->keywords slots) (if (null slots) '() `(,@(slot->keyword (car slots)) ,@(slots->keywords (cdr slots))))) (define (slot->keyword slot) (let* ((tag (keyword-key slot)) (val (keyword-val slot))) (case tag (:pos `(:x ,(xpoint-x val) :y ,(xpoint-y val))) (:root-pos `(:root-x ,(xpoint-x val) :root-y ,(xpoint-y val))) (:size `(:width ,(xsize-w val) :height ,(xsize-h val))) (:rect `(:x ,(xrect-x val) :y ,(xrect-y val) :width ,(xrect-w val) :height ,(xrect-h val))) (:graph-fun `(:major ,(car val) :minor ,(cdr val))) (:visibility `(:state ,val)) (:property-state `(:state ,val)) (:message `(:data ,(car val) :type ,(cadr val) :format ,(caddr val))) (else `(,tag ,val))))) (define (keywords->slots type keywords event) (let* ((slots (keywords->slots1 type keywords)) (has-root-xy (memq type '(:key-press :key-release :button-press :button-release :motion-notify :enter-notify :leave-notify))) (has-xy (or has-root-xy (memq type '(:gravity-notify :reparent-notify)))) (has-graph-fun (memq type '(:graphics-exposure :no-exposure))) (has-rect (memq type '(:exposure :graphics-exposure :configure-notify :create-notify :configure-request))) (has-size (memq type '(:resize-request))) (has-message (memq type '(:client-message)))) (when has-xy (push (make-keyword :pos (x-event-pos event)) slots)) (when has-root-xy (push (make-keyword :root-pos (x-event-root-pos event)) slots)) (when has-graph-fun (push (make-keyword :graph-fun (x-event-graph-fun event)) slots)) (when has-rect (push (make-keyword :rect (x-event-rect event)) slots)) (when has-size (push (make-keyword :size (x-event-size event)) slots)) (when has-message (push (make-keyword :message (x-event-message event)) slots)) slots)) (define (keywords->slots1 type keywords) (if (null? keywords) '() (if (memq (car keywords) '(:x :y :width :height :root-x :root-y :major :minor :type :data :format)) (keywords->slots1 type (cddr keywords)) (cons (keyword->slot type (car keywords) (cadr keywords)) (keywords->slots1 type (cddr keywords)))))) (define (keyword->slot type slot val) (if (eq? slot :state) (case type (:property-state (make-keyword :property-state val)) (:visibility (make-keyword :visibility val)) (else (make-keyword :state val))) (make-keyword slot val))) (define (attrs->keywords attrs) (if (null attrs) '() (nconc (attr->keyword (car attrs)) (attrs->keywords (cdr attrs))))) (define (attr->keyword attr) (let* ((tag (keyword-key attr)) (val (keyword-val attr))) (case tag (:clip-origin `(:clip-x ,(xpoint-x val) :clip-y ,(xpoint-y val))) (:dashes `(,tag ,(haskell-list->list/identity val))) (:tile-origin `(:ts-x ,(xpoint-x val) :ts-y ,(xpoint-y val))) (:size `(:width ,(xsize-w val) :height ,(xsize-h val))) (:name `(:name ,(haskell-string->string val))) (:hot-spot `(:x-hot ,(xpoint-x val) :y-hot ,(xpoint-y val))) (else `(,tag ,val))))) (define (x-mutable-array-create inits) (list->vector inits)) (define (x-mutable-array-lookup a i) (vector-ref a i)) (define (x-mutable-array-update a i x) (setf (vector-ref a i) x)) (define (x-mutable-array-length a) (vector-length a)) (define (get-time-zone) (nth-value 8 (lisp:get-decoded-time))) (define (decode-time time zone) (multiple-value-bind (sec min hour date mon year week ds-p) (if zone (lisp:decode-universal-time time zone) (lisp:decode-universal-time time)) (make-h-tuple (list->haskell-list/identity (list sec min hour date mon year week)) ds-p))) (define (encode-time time zone) (apply (function lisp:encode-universal-time) (if (null? zone) time (append time (list zone))))) (define (get-run-time) (/ (lisp:coerce (lisp:get-internal-run-time) 'lisp:single-float) (lisp:coerce lisp:internal-time-units-per-second 'lisp:single-float))) (define (get-elapsed-time) (/ (lisp:coerce (lisp:get-internal-real-time) 'lisp:single-float) (lisp:coerce lisp:internal-time-units-per-second 'lisp:single-float))) (define (prim.thenio---1 x fn) (lambda (state) (declare (ignore state)) (let ((res (funcall x (box 'state)))) (format '#t "~A~%" res) (funcall fn res (box 'state))))) (define-attribute-setter wm name) (define-attribute-setter wm icon-name)
null
https://raw.githubusercontent.com/haskell-lisp/yale-haskell/4e987026148fe65c323afbc93cd560c07bf06b3f/progs/lib/X11/xlibclx.scm
scheme
general This is stuff to support slots that consist of a keyword/value pair. Note that the value is always unboxed. The forces here are necessary because the thing being funcalled returns a data structure of type (IO a), and we need to do an IO a -> a transformation. Bitmap XKeysymTable XPixarray Can't use mumble vector primitives on arrays of specialized types! BitVec XAtom XProperty watch out for name conflict with :property keyword stuff XEventSlot XClipMask XVisualInfo XFillContent XBackingStore XImageData Display is a string of the format name:d.s if d is omitted , default it to zero .
xlibclx.scm -- Lisp support for Haskell / CLX interface (define-syntax (nth-value n form) (cond ((eqv? n 0) `(values ,form)) ((number? n) (let ((temps '())) (dotimes (i n) (declare (ignorable i)) (push (gensym) temps)) `(multiple-value-bind ,(reverse temps) ,form (declare (ignore ,@(reverse (cdr temps)))) ,(car temps)))) (else `(lisp:nth ,n (lisp:multiple-value-list ,form))) )) (define-local-syntax (keywordify string) `(lisp:intern ,string (lisp:find-package "KEYWORD"))) (define-local-syntax (xlibify string) `(lisp:intern ,string (lisp:find-package "XLIB"))) (define-syntax (make-keyword key value) `(cons ,key ,value)) (define-syntax (is-keyword? x key) `(eq? (car ,x) ,key)) (define-syntax (keyword-key x) `(car ,x)) (define-syntax (keyword-val x) `(cdr ,x)) (define-syntax (define-keyword-constructor name) (let* ((name-str (symbol->string name)) (key (keywordify name-str)) (is-name (string->symbol (string-append "IS-" name-str))) (mk-name (string->symbol (string-append "MK-" name-str)))) `(begin (define (,mk-name x) (make-keyword ,key x)) (define (,is-name x) (is-keyword? x ,key))) )) (define-syntax (define-event-slot-finder slot) (let* ((slot-str (symbol->string slot)) (slot-key (keywordify slot-str)) (fun (string->symbol (string-append "X-EVENT-" slot-str)))) `(define (,fun event) (lookup-event-slot (cdr event) ,slot-key)))) (define (lookup-event-slot event key) (if (null? event) (error "non-existent event slot: ~A" key) (if (eq? key (car event)) (cadr event) (lookup-event-slot (cddr event) key)))) (define-syntax (define-attribute-setter entity attribute) (let* ((entity-attr (string-append (symbol->string entity) "-" (symbol->string attribute))) (fun-name (string->symbol (string-append "X-SET-" entity-attr))) (xfun-name (xlibify entity-attr))) `(define (,fun-name ,entity ,attribute) (setf (,xfun-name ,entity) ,attribute)))) (define-syntax (make-h-tuple . args) (let ((nargs (map (lambda (arg) `(box ,arg)) args))) `(make-tuple ,@nargs))) type XError (define (cons-xerror x) (declare (ignore x)) (error "can't construct XError")) (define (x-error-string c) (make-haskell-string (format '#f "~A" c))) #+lucid (define (x-handle-error handler body) (lisp:catch 'x-error-handle (lcl:handler-bind ((lisp:error (mk-handler handler))) (force (funcall body (box 'state)))))) #+(or cmu allegro lispworks) (define (x-handle-error handler body) (lisp:catch 'x-error-handle (lisp:handler-bind ((lisp:error (mk-handler handler))) (force (funcall body (box 'state)))))) #+akcl (define (x-handle-error handler body) (error "AKCL does not support HANDLER-BIND!")) (define (mk-handler handler) (lambda (c) (lisp:throw 'x-error-handle (force (funcall handler (box c) (box 'state)))))) for type (define (not-null? x) (not (null? x))) For Bitmap , Pixarray , KeysymTable (define (array2->haskell-list a) (let* ((dims (lisp:array-dimensions a)) (i1max (car dims)) (i2max (cadr dims))) (declare (type fixnum i1max i2max)) (do ((i1 (the fixnum (1- i1max)) (the fixnum (1- i1))) (outer '())) ((< i1 0) outer) (declare (type fixnum i1)) (setf outer (cons (box (do ((i2 (the fixnum (1- i2max)) (the fixnum (1- i2))) (inner '())) ((< i2 0) inner) (declare (type fixnum i2)) (setf inner (cons (box (lisp:aref a i1 i2)) (box inner))))) (box outer)))) )) (define (mk-bitmap ll) (let ((l (haskell-list->list #'haskell-list->list/identity ll))) (lisp:make-array `(,(length l) , (length (car l))) :element-type 'lisp:bit :initial-contents l))) (define (sel-bitmap l) (array2->haskell-list l)) (define (mk-keysym-table ll) (let ((l (haskell-list->list #'haskell-list->list/identity ll))) (lisp:make-array `(,(length l) , (length (car l))) :element-type 'xlib:card32 :initial-contents l))) (define (sel-keysym-table l) (array2->haskell-list l)) (define (mk-pixarray ll) (let ((l (haskell-list->list #'haskell-list->list/identity ll))) (let* ((max-num (find-max l)) (pix-type (cond ((<= max-num 1) 'lisp:bit) ((<= max-num 15) '(lisp:unsigned-byte 4)) ((<= max-num 255) 'xlib:card8) ((<= max-num 65535) 'xlib:card16) (else 'xlib:card32)))) (declare (type integer max-num)) (lisp:make-array `(,(length l) , (length (car l))) :element-type pix-type :initial-contents l)))) (define (find-max l) (let ((max 0)) (dolist (ll l) (dolist (lll ll) (when (> (the integer lll) (the integer max)) (setf max lll)))) max)) (define (sel-pixarray l) (array2->haskell-list l)) (define (array1->haskell-list a) (declare (type lisp:vector a)) (let ((imax (lisp:length a))) (declare (type fixnum imax)) (do ((i (the fixnum (1- imax)) (the fixnum (1- i))) (result '())) ((< i 0) result) (declare (type fixnum i)) (setf result (cons (box (lisp:aref a i)) (box result)))))) (define (mk-bitvec ll) (let ((l (haskell-list->list/identity ll))) (lisp:make-array `(,(length l)) :element-type 'lisp:bit :initial-contents l))) (define (sel-bitvec l) (array1->haskell-list l)) ByteVec (define (mk-bytevec ll) (let ((l (haskell-list->list/identity ll))) (lisp:make-array `(,(length l)) :element-type 'xlib:card8 :initial-contents l))) (define (sel-bytevec l) (array1->haskell-list l)) (define (mk-atom name) (keywordify (haskell-string->string name))) (define (sel-atom atom) (make-haskell-string (symbol->string atom))) (define (mk-xproperty d ty f) (list (haskell-list->list/identity d) ty f)) (define (sel-xproperty-data p) (list->haskell-list/identity (car p))) (define (sel-xproperty-type p) (cadr p)) (define (sel-xproperty-format p) (caddr p)) (define (mk-event type slots) (cons type (slots->keywords (haskell-list->list/identity slots)))) (define (sel-event-type event) (car event)) (define (sel-event-slots event) (list->haskell-list/identity (keywords->slots (car event) (cdr event) event))) (define-keyword-constructor window) (define-keyword-constructor event-window) (define-keyword-constructor code) (define-keyword-constructor pos) (define-keyword-constructor state) (define-keyword-constructor time) (define-keyword-constructor root) (define-keyword-constructor root-pos) (define-keyword-constructor child) (define-keyword-constructor same-screen-p) (define-keyword-constructor hint-p) (define-keyword-constructor mode) (define-keyword-constructor kind) (define-keyword-constructor focus-p) (define-keyword-constructor keymap) (define-keyword-constructor request) (define-keyword-constructor start) (define-keyword-constructor count) (define-keyword-constructor rect) (define-keyword-constructor drawable) (define-keyword-constructor graph-fun) (define-keyword-constructor place) (define-keyword-constructor border-width) (define-keyword-constructor above-sibling) (define-keyword-constructor override-redirect-p) (define-keyword-constructor parent) (define-keyword-constructor configure-p) (define-keyword-constructor visibility) (define-keyword-constructor new-p) (define-keyword-constructor installed-p) (define-keyword-constructor stack-mode) (define-keyword-constructor value-mask) (define-keyword-constructor size) (define-keyword-constructor message) (define-keyword-constructor property-state) (define-keyword-constructor atom) (define-keyword-constructor selection) (define-keyword-constructor target) (define-keyword-constructor property) (define-keyword-constructor requestor) (define-event-slot-finder window) (define-event-slot-finder event-window) (define-event-slot-finder code) (define-event-slot-finder x) (define-event-slot-finder y) (define-event-slot-finder state) (define-event-slot-finder time) (define-event-slot-finder root) (define-event-slot-finder root-x) (define-event-slot-finder root-y) (define-event-slot-finder child) (define-event-slot-finder same-screen-p) (define-event-slot-finder hint-p) (define-event-slot-finder mode) (define-event-slot-finder kind) (define-event-slot-finder focus-p) (define-event-slot-finder keymap) (define-event-slot-finder request) (define-event-slot-finder start) (define-event-slot-finder count) (define-event-slot-finder width) (define-event-slot-finder height) (define-event-slot-finder drawable) (define-event-slot-finder major) (define-event-slot-finder minor) (define-event-slot-finder place) (define-event-slot-finder border-width) (define-event-slot-finder above-sibling) (define-event-slot-finder override-redirect-p) (define-event-slot-finder parent) (define-event-slot-finder configure-p) (define-event-slot-finder new-p) (define-event-slot-finder installed-p) (define-event-slot-finder stack-mode) (define-event-slot-finder value-mask) (define-event-slot-finder data) (define-event-slot-finder type) (define-event-slot-finder format) (define-event-slot-finder atom) (define-event-slot-finder selection) (define-event-slot-finder target) (define-event-slot-finder property) (define-event-slot-finder requestor) (define (x-event-pos event) (mk-xpoint (x-event-x event) (x-event-y event))) (define (x-event-root-pos event) (mk-xpoint (x-event-root-x event) (x-event-root-y event))) (define (x-event-size event) (mk-xsize (x-event-width event) (x-event-height event))) (define (x-event-rect event) (mk-xrect (x-event-x event) (x-event-y event) (x-event-width event) (x-event-height event))) (define (x-event-graph-fun event) (cons (x-event-major event) (x-event-minor event))) (define (x-event-message event) (list (sequence->list (x-event-data event)) (x-event-type event) (x-event-format event))) (define (x-make-event-mask keys) (apply (function xlib:make-event-mask) (haskell-list->list/identity keys))) (define (x-event-mask-key-list mask) (list->haskell-list/identity (xlib:make-event-keys mask))) XStateMask (define (x-make-state-mask keys) (apply (function xlib:make-state-mask) (haskell-list->list/identity keys))) (define (x-state-mask-key-list mask) (list->haskell-list/identity (xlib:make-state-keys mask))) (define-keyword-constructor background) (define-keyword-constructor foreground) (define-keyword-constructor event-mask) (define-keyword-constructor depth) (define-keyword-constructor border-width) (define-keyword-constructor class) (define-keyword-constructor visual) (define-keyword-constructor border) (define-keyword-constructor backing-store) (define-keyword-constructor backing-planes) (define-keyword-constructor backing-pixel) (define-keyword-constructor save-under) (define-keyword-constructor do-not-propagate-mask) (define-keyword-constructor override-redirect) (define-keyword-constructor colormap) (define-keyword-constructor cursor) (define-keyword-constructor arc-mode) (define-keyword-constructor cap-style) (define-keyword-constructor clip-mask) (define-keyword-constructor clip-origin) (define-keyword-constructor dash-offset) (define-keyword-constructor dashes) (define-keyword-constructor exposures) (define-keyword-constructor fill-rule) (define-keyword-constructor fill-style) (define-keyword-constructor font) (define-keyword-constructor function) (define-keyword-constructor join-style) (define-keyword-constructor line-style) (define-keyword-constructor line-width) (define-keyword-constructor plane-mask) (define-keyword-constructor stipple) (define-keyword-constructor subwindow-mode) (define-keyword-constructor tile) (define-keyword-constructor tile-origin) (define-keyword-constructor bit-lsb-first-p) (define-keyword-constructor bits-per-pixel) (define-keyword-constructor blue-mask) (define-keyword-constructor byte-lsb-first-p) (define-keyword-constructor bytes-per-line) (define-keyword-constructor data) (define-keyword-constructor format) (define-keyword-constructor green-mask) (define-keyword-constructor size) (define-keyword-constructor name) (define-keyword-constructor red-mask) (define-keyword-constructor hot-spot) (define-keyword-constructor owner-p) (define-keyword-constructor sync-pointer-p) (define-keyword-constructor sync-keyboard-p) (define-keyword-constructor confine-to) (define (not-pixmap-and-list-p x) (and (pair? x) (not (xlib:pixmap-p x)))) (define (mk-clip-mask-rects rects) (rects->point-seq (haskell-list->list/identity rects))) (define (sel-clip-mask-rects point-seq) (list->haskell-list/identity (point-seq->rects point-seq))) XPoint (define (mk-xpoint x y) (cons x y)) (define (xpoint-x x) (car x)) (define (xpoint-y x) (cdr x)) XSize (define (mk-xsize x y) (cons x y)) (define (xsize-w x) (car x)) (define (xsize-h x) (cdr x)) XRect (define (mk-xrect x y w h) (vector x y w h)) (define (xrect-x x) (vector-ref x 0)) (define (xrect-y x) (vector-ref x 1)) (define (xrect-w x) (vector-ref x 2)) (define (xrect-h x) (vector-ref x 3)) XArc (define (mk-xarc x y w h a1 a2) (vector x y w h a1 a2)) (define (xarc-x x) (vector-ref x 0)) (define (xarc-y x) (vector-ref x 1)) (define (xarc-w x) (vector-ref x 2)) (define (xarc-h x) (vector-ref x 3)) (define (xarc-a1 x) (vector-ref x 4)) (define (xarc-a2 x) (vector-ref x 5)) BitmapFormat (define (mk-bitmap-format u p l) (xlib::make-bitmap-format :unit u :pad p :lsb-first-p l)) PixmapFormat (define (mk-pixmap-format u p l) (xlib::make-pixmap-format :depth u :bits-per-pixel p :scanline-pad l)) (define (mk-xvisual-info id cl rm gm bm bs es) (xlib::make-visual-info :id id :class cl :red-mask rm :green-mask gm :blue-mask bm :bits-per-rgb bs :colormap-entries es)) (define (is-fill-pixel x) (not (or (xlib:pixmap-p x) (symbol? x)))) (define (bitmap-list-p x) (pair? x)) (define (pixarray-p x) (and (not (pair? x)) (eq? (lisp:array-rank x) 2))) (define (bytevec-p x) (and (not (pair? x)) (eq? (lisp:array-rank x) 1))) XColor (define (mk-color r g b) (xlib:make-color :red r :green g :blue b)) (define (x-print x) (print x)) (define (x-set-event-mask-key mask key-sym) (lisp:logior mask (xlib:make-event-mask key-sym))) (define (x-clear-event-mask-key mask key-sym) (lisp:logand mask (lisp:lognot (xlib:make-event-mask key-sym)))) (define (x-test-event-mask-key mask key-sym) (if (eqv? 0 (lisp:logand mask (xlib:make-event-mask key-sym))) '#f '#t)) (define (x-set-state-mask-key mask key-sym) (lisp:logior mask (xlib:make-state-mask key-sym))) (define (x-clear-state-mask-key mask key-sym) (lisp:logand mask (lisp:lognot (xlib:make-state-mask key-sym)))) (define (x-test-state-mask-key mask key-sym) (if (eqv? 0 (lisp:logand mask (xlib:make-state-mask key-sym))) '#f '#t)) (define (x-open-display display) (let* ((end (string-length display)) (colon (or (string-position #\: display 0 end) end)) (dot (or (string-position #\. display colon end) end))) (declare (type fixnum end colon dot)) (xlib:open-display (substring display 0 colon) :display (if (eqv? colon dot) 0 (string->number (substring display (1+ colon) dot)))))) (define (x-set-display-error-handler display error-fun) (declare (ignore display error-fun)) (error "not implemented")) (define (x-set-display-after-function display after-fun) (declare (ignore display after-fun)) (error "not implemented")) (define (x-screen-depths screen) (let ((depths (xlib:screen-depths screen))) (map (lambda (l) (make-h-tuple (car l) (list->haskell-list/identity (cdr l)))) depths))) (define (x-screen-size screen) (mk-xsize (xlib:screen-width screen) (xlib:screen-height screen))) (define (x-screen-mmsize screen) (mk-xsize (xlib:screen-width-in-millimeters screen) (xlib:screen-height-in-millimeters screen))) (define (x-create-window parent rect attrs) (apply (function XLIB:CREATE-WINDOW) `(:parent ,parent :x ,(xrect-x rect) :y ,(xrect-y rect) :width ,(xrect-w rect) :height ,(xrect-h rect) ,@(attrs->keywords attrs)))) (define-attribute-setter drawable border-width) (define (x-drawable-size drawable) (mk-xsize (xlib:drawable-width drawable) (xlib:drawable-height drawable))) (define (x-drawable-resize drawable size) (setf (xlib:drawable-width drawable) (xsize-w size)) (setf (xlib:drawable-height drawable) (xsize-h size))) (define (x-window-pos window) (mk-xpoint (xlib:drawable-x window) (xlib:drawable-y window))) (define (x-window-move window point) (setf (xlib:drawable-x window) (xpoint-x point)) (setf (xlib:drawable-y window) (xpoint-y point))) (define-attribute-setter window background) (define-attribute-setter window backing-pixel) (define-attribute-setter window backing-planes) (define-attribute-setter window backing-store) (define-attribute-setter window bit-gravity) (define-attribute-setter window border) (define-attribute-setter window colormap) (define (x-set-window-cursor window cursor) (let ((val (if (null? cursor) :none cursor))) (setf (xlib:window-cursor window) val))) (define-attribute-setter window do-not-propagate-mask) (define-attribute-setter window event-mask) (define-attribute-setter window gravity) (define-attribute-setter window override-redirect) (define-attribute-setter window priority) (define-attribute-setter window save-under) (define (x-query-tree window) (multiple-value-bind (children parent root) (xlib:query-tree window) (make-h-tuple (list->haskell-list/identity children) parent root))) (define (x-reparent-window window parent point) (xlib:reparent-window window parent (xpoint-x point) (xpoint-y point))) (define (x-translate-coordinates source point dest) (xlib:translate-coordinates source (xpoint-x point) (xpoint-y point) dest)) (define (x-create-pixmap size depth drawable) (xlib:create-pixmap :width (xsize-w size) :height (xsize-h size) :depth depth :drawable drawable)) (define (x-create-gcontext drawable attrs) (apply (function XLIB:CREATE-GCONTEXT) `(:drawable ,drawable ,@(attrs->keywords attrs)))) (define (x-update-gcontext gcontext attrs) (do ((keys (attrs->keywords attrs) (cddr keys))) ((null? keys)) (x-update-gcontext-attr gcontext (car keys) (cadr keys)))) (define (x-update-gcontext-attr gcontext key attr) (case key (:arc-mode (setf (xlib:gcontext-arc-mode gcontext) attr)) (:background (setf (xlib:gcontext-background gcontext) attr)) (:cap-style (setf (xlib:gcontext-cap-style gcontext) attr)) (:fill-style (setf (xlib:gcontext-fill-style gcontext) attr)) (:clip-mask (setf (xlib:gcontext-clip-mask gcontext) attr)) (:clip-x (setf (xlib:gcontext-clip-x gcontext) attr)) (:clip-y (setf (xlib:gcontext-clip-y gcontext) attr)) (:dash-offset (setf (xlib:gcontext-dash-offset gcontext) attr)) (:dashes (setf (xlib:gcontext-dashes gcontext) attr)) (:exposures (setf (xlib:gcontext-exposures gcontext) attr)) (:fill-rule (setf (xlib:gcontext-fill-rule gcontext) attr)) (:font (setf (xlib:gcontext-font gcontext) attr)) (:foreground (setf (xlib:gcontext-foreground gcontext) attr)) (: function ( setf ( : gcontext - function gcontext ) attr ) ) (:join-style (setf (xlib:gcontext-join-style gcontext) attr)) (:line-style (setf (xlib:gcontext-line-style gcontext) attr)) (: line - width ( setf ( : gcontext - line - width gcontext ) attr ) ) (: plane - mask ( setf ( : gcontext - plane - mask gcontext ) attr ) ) (: stipple ( setf ( : gcontext - stipple gcontext ) attr ) ) (:subwindow-mode (setf (xlib:gcontext-subwindow-mode gcontext) attr)) (: tile ( setf ( : gcontext - tile gcontext ) attr ) ) (: ( setf ( : gcontext ) attr ) ) (: ( setf ( : gcontext - ts - y gcontext ) attr ) ) (else (format '#t "Graphics context attribute ~A is not settable.~%" key)))) (define (x-query-best-stipple dsize drawable) (multiple-value-bind (w h) (xlib:query-best-stipple (xsize-w dsize) (xsize-h dsize) drawable) (mk-xsize w h))) (define (x-query-best-tile dsize drawable) (multiple-value-bind (w h) (xlib:query-best-tile (xsize-w dsize) (xsize-h dsize) drawable) (mk-xsize w h))) (define (x-clear-area window rect exposures-p) (xlib:clear-area window :x (xrect-x rect) :y (xrect-y rect) :width (xrect-w rect) :height (xrect-h rect) :exposures-p exposures-p)) (define (x-copy-area src gcontext rect dest point) (xlib:copy-area src gcontext (xrect-x rect) (xrect-y rect) (xrect-w rect) (xrect-h rect) dest (xpoint-x point) (xpoint-y point))) (define (x-copy-plane src gcontext plane rect dest point) (xlib:copy-plane src gcontext plane (xrect-x rect) (xrect-y rect) (xrect-w rect) (xrect-h rect) dest (xpoint-x point) (xpoint-y point))) (define (x-draw-point drawable gcontext point) (xlib:draw-point drawable gcontext (xpoint-x point) (xpoint-y point))) (define (x-draw-points drawable gcontext points) (xlib:draw-points drawable gcontext (points->point-seq points))) (define (points->point-seq points) (if (null? points) '() (let ((point (car points))) (lisp:list* (xpoint-x point) (xpoint-y point) (points->point-seq (cdr points)))))) (define (segments->point-seq segments) (if (null? segments) '() (let* ((first-pair (car segments)) (point-1 (force (tuple-select 2 0 first-pair))) (point-2 (force (tuple-select 2 1 first-pair)))) (lisp:list* (xpoint-x point-1) (xpoint-y point-1) (xpoint-x point-2) (xpoint-y point-2) (segments->point-seq (cdr segments)))))) (define (rects->point-seq rects) (if (null? rects) '() (let ((rect (car rects))) (lisp:list* (xrect-x rect) (xrect-y rect) (xrect-w rect) (xrect-h rect) (rects->point-seq (cdr rects)))))) (define (point-seq->rects point-seq) (if (null? point-seq) '() (cons (mk-xrect (car point-seq) (cadr point-seq) (caddr point-seq) (cadddr point-seq)) (point-seq->rects (cddddr point-seq))))) (define (arcs->point-seq arcs) (if (null? arcs) '() (let ((arc (car arcs))) (lisp:list* (xarc-x arc) (xarc-y arc) (xarc-w arc) (xarc-h arc) (xarc-a1 arc) (xarc-a2 arc) (arcs->point-seq (cdr arcs)))))) (define (x-draw-line drawable gcontext point-1 point-2) (xlib:draw-line drawable gcontext (xpoint-x point-1) (xpoint-y point-1) (xpoint-x point-2) (xpoint-y point-2))) (define (x-draw-lines drawable gcontext points fill-p) (xlib:draw-lines drawable gcontext (points->point-seq points) :fill-p fill-p)) (define (x-draw-segments drawable gcontext segments) (xlib:draw-segments drawable gcontext (segments->point-seq segments))) (define (x-draw-rectangle drawable gcontext rect fill-p) (xlib:draw-rectangle drawable gcontext (xrect-x rect) (xrect-y rect) (xrect-w rect) (xrect-h rect) fill-p)) (define (x-draw-rectangles drawable gcontext rects fill-p) (xlib:draw-rectangles drawable gcontext (rects->point-seq rects) fill-p)) (define (x-draw-arc drawable gcontext arc fill-p) (xlib:draw-arc drawable gcontext (xarc-x arc) (xarc-y arc) (xarc-w arc) (xarc-h arc) (xarc-a1 arc) (xarc-a2 arc) fill-p)) (define (x-draw-arcs drawable gcontext arcs fill-p) (xlib:draw-arcs drawable gcontext (arcs->point-seq arcs) fill-p)) (define (x-draw-glyph drawable gcontext point element) (nth-value 1 (xlib:draw-glyph drawable gcontext (xpoint-x point) (xpoint-y point) element))) (define (x-draw-glyphs drawable gcontext point element) (nth-value 1 (xlib:draw-glyphs drawable gcontext (xpoint-x point) (xpoint-y point) element))) (define (x-draw-image-glyph drawable gcontext point element) (nth-value 1 (xlib:draw-image-glyph drawable gcontext (xpoint-x point) (xpoint-y point) element))) (define (x-draw-image-glyphs drawable gcontext point element) (nth-value 1 (xlib:draw-image-glyphs drawable gcontext (xpoint-x point) (xpoint-y point) element))) (define (x-image-size image) (mk-xsize (xlib:image-width image) (xlib:image-height image))) (define (x-image-name image) (let ((lisp-name (xlib:image-name image))) (cond ((null? lisp-name) "") ((symbol? lisp-name) (symbol->string lisp-name)) (else lisp-name)))) (define-attribute-setter image name) (define (x-image-hot-spot image) (mk-xpoint (xlib:image-x-hot image) (xlib:image-y-hot image))) (define (x-set-image-hot-spot image point) (setf (xlib:image-x-hot image) (xpoint-x point)) (setf (xlib:image-y-hot image) (xpoint-y point))) (define-attribute-setter image xy-bitmap-list) (define-attribute-setter image z-bits-per-pixel) (define-attribute-setter image z-pixarray) (define (x-create-image attrs) (apply (function xlib:create-image) (attrs->keywords attrs))) (define (x-copy-image image rect type) (xlib:copy-image image :x (xrect-x rect) :y (xrect-y rect) :width (xrect-w rect) :height (xrect-h rect) :result-type type)) (define (x-get-image drawable rect pmask format type) (xlib:get-image drawable :x (xrect-x rect) :y (xrect-y rect) :width (xrect-w rect) :height (xrect-h rect) :plane-mask pmask :format format :result-type type)) (define (x-put-image drawable gcontext image point rect) (xlib:put-image drawable gcontext image :src-x (xpoint-x point) :src-y (xpoint-y point) :x (xrect-x rect) :y (xrect-y rect) :width (xrect-w rect) :height (xrect-h rect))) (define (x-get-raw-image drawable rect pmask format) (xlib:get-raw-image drawable :x (xrect-x rect) :y (xrect-y rect) :width (xrect-w rect) :height (xrect-h rect) :plane-mask pmask :format format)) (define (x-put-raw-image drawable gcontext data depth rect left-pad format) (xlib:put-raw-image drawable gcontext data :depth depth :x (xrect-x rect) :y (xrect-y rect) :width (xrect-w rect) :height (xrect-h rect) :left-pad left-pad :format format)) (define (x-font-name font) (let ((lisp-name (xlib:font-name font))) (cond ((null? lisp-name) "") ((symbol? lisp-name) (symbol->string lisp-name)) (else lisp-name)))) (define (x-alloc-color colormap color) (multiple-value-bind (pixel screen-color exact-color) (xlib:alloc-color colormap color) (make-h-tuple pixel screen-color exact-color))) (define (x-alloc-color-cells colormap colors planes contiguous-p) (multiple-value-bind (pixels mask) (xlib:alloc-color-cells colormap colors :planes planes :contiguous-p contiguous-p) (make-h-tuple (list->haskell-list/identity pixels) (list->haskell-list/identity mask)))) (define (x-alloc-color-planes colormap colors reds greens blues contiguous-p) (multiple-value-bind (pixels red-mask green-mask blue-mask) (xlib:alloc-color-planes colormap colors :reds reds :greens greens :blues blues :contiguous-p contiguous-p) (make-h-tuple (list->haskell-list/identity pixels) red-mask green-mask blue-mask))) (define (x-lookup-color colormap name) (multiple-value-bind (screen-color exact-color) (xlib:lookup-color colormap name) (make-h-tuple screen-color exact-color))) (define (unzip l) (if (null? l) '() (let ((h (car l))) (lisp:list* (force (tuple-select 2 0 h)) (force (tuple-select 2 1 h)) (unzip (cdr l)))))) (define (x-store-colors colormap pixel-colors) (xlib:store-colors colormap (unzip pixel-colors))) (define (x-create-cursor source mask point foreground background) (apply (function xlib:create-cursor) `(:source ,source ,@(if mask `(:mask ,mask) '()) :x ,(xpoint-x point) :y ,(xpoint-y point) :foreground ,foreground :background ,background))) (define (x-create-glyph-cursor src mask foreground background) (apply (function xlib:create-glyph-cursor) `(:source-font ,(force (tuple-select 2 0 src)) :source-char ,(integer->char (force (tuple-select 2 1 src))) ,@(if mask `(:mask-font ,(force (tuple-select 2 0 mask)) :mask-char ,(integer->char (force (tuple-select 2 1 mask)))) '()) :foreground ,foreground :background ,background))) (define (x-query-best-cursor size display) (multiple-value-bind (w h) (xlib:query-best-cursor (xsize-w size) (xsize-h size) display) (mk-xsize w h))) (define (x-change-property window property content) (xlib:change-property window property (car content) (cadr content) (caddr content))) (define (x-get-property window property) (lisp:multiple-value-bind (data type format) (xlib:get-property window property) (list (sequence->list data) type format))) (define (x-convert-selection selection type requestor property time) (apply (function xlib:convert-selection) `(,selection ,type ,requestor ,property ,@(if time `(,time) '())))) (define (x-set-selection-owner display selection time owner) (if time (setf (xlib:selection-owner display selection time) owner) (setf (xlib:selection-owner display selection) owner))) (define (sequence->list seq) (if (list? seq) seq (do ((i (1- (lisp:length seq)) (1- i)) (res '() (cons (lisp:elt seq i) res))) ((< i 0) res)))) (define *this-event* '()) (define (translate-event lisp:&rest event-slots lisp:&key event-key lisp:&allow-other-keys) (setf *this-event* (cons event-key event-slots)) '#t) (define (x-get-event display) (xlib:process-event display :handler #'translate-event :force-output-p '#t) *this-event*) (define (x-queue-event display event append-p) (apply (function xlib:queue-event) `(,display ,(car event) ,@(cdr event) :append-p ,append-p))) (define (x-event-listen display) (let ((res (xlib:event-listen display))) (if (null? res) 0 res))) (define (x-send-event window event mask) (apply (function xlib:send-event) `(,window ,(car event) ,mask ,@(cdr event)))) (define (x-global-pointer-position display) (multiple-value-bind (x y) (xlib:global-pointer-position display) (mk-xpoint x y))) (define (x-pointer-position window) (multiple-value-bind (x y same) (xlib:pointer-position window) (if same (mk-xpoint x y) '()))) (define (x-motion-events window start stop) (do ((npos '() (cons (mk-xpoint (car pos) (cadr pos)) npos)) (pos (xlib:motion-events window :start start :stop stop) (cdddr pos))) ((null? pos) (nreverse npos)))) (define (x-warp-pointer dest-win point) (xlib:warp-pointer dest-win (xpoint-x point) (xpoint-y point))) (define (x-set-input-focus display focus revert-to time) (apply (function xlib:set-input-focus) `(,display ,focus ,revert-to ,@(if time `(,time) '())))) (define (x-input-focus display) (multiple-value-bind (focus revert-to) (xlib:input-focus display) (make-h-tuple focus revert-to))) (define (x-grab-pointer window event-mask attrs time) (apply (function xlib:grab-pointer) `(,window ,event-mask ,@(attrs->keywords attrs) ,@(if time `(:time ,time) '())))) (define (x-ungrab-pointer display time) (if time (xlib:ungrab-pointer display :time time) (xlib:ungrab-pointer display))) (define (x-change-active-pointer-grab display event-mask attrs time) (apply (function xlib:change-active-pointer-grab) `(,display ,event-mask ,@(attrs->keywords attrs) ,@(if time `(,time) '())))) (define (x-grab-button window button event-mask state-mask attrs) (apply (function xlib:grab-button) `(,window ,button ,event-mask :modifiers ,state-mask ,@(attrs->keywords attrs)))) (define (x-ungrab-button window button modifiers) (xlib:ungrab-button window button :modifiers modifiers)) (define (x-grab-keyboard window attrs time) (apply (function xlib:grab-keyboard) `(,window ,@(attrs->keywords attrs) ,@(if time `(:time ,time) '())))) (define (x-ungrab-keyboard display time) (if time (xlib:ungrab-keyboard display :time time) (xlib:ungrab-keyboard display))) (define (x-grab-key window key state-mask attrs) (apply (function xlib:grab-key) `(,window ,key :modifiers ,state-mask ,@(attrs->keywords attrs)))) (define (x-ungrab-key window key modifiers) (xlib:ungrab-button window key :modifiers modifiers)) (define (x-set-pointer-acceleration display val) (xlib:change-pointer-control display :acceleration val)) (define (x-set-pointer-threshold display val) (xlib:change-pointer-control display :threshold val)) (define (x-pointer-acceleration display) (lisp:coerce (nth-value 0 (xlib:pointer-control display)) 'lisp:single-float)) (define (x-pointer-threshold display) (lisp:coerce (nth-value 1 (xlib:pointer-control display)) 'lisp:single-float)) (define-attribute-setter pointer mapping) (define (x-set-keyboard-key-click-percent display v) (xlib:change-keyboard-control display :key-click-percent v)) (define (x-set-keyboard-bell-percent display v) (xlib:change-keyboard-control display :bell-percent v)) (define (x-set-keyboard-bell-pitch display v) (xlib:change-keyboard-control display :bell-pitch v)) (define (x-set-keyboard-bell-duration display v) (xlib:change-keyboard-control display :bell-duration v)) Yes , leds are really counted from 1 rather than 0 . (define (x-set-keyboard-led display v) (declare (type integer v)) (do ((led 1 (1+ led)) (vv v (lisp:ash vv -1))) ((> led 32)) (declare (type fixnum led) (type integer vv)) (xlib:change-keyboard-control display :led led :led-mode (if (lisp:logand vv 1) :on :off)))) (define (x-set-keyboard-auto-repeat-mode display v) (do ((key 0 (1+ key))) ((>= key (lisp:length v))) (declare (type fixnum key)) (xlib:change-keyboard-control display :key key :auto-repeat-mode (if (eqv? (the fixnum (lisp:aref v key)) 1) :on :off) ))) (define (x-keyboard-key-click-percent display) (nth-value 0 (xlib:keyboard-control display))) (define (x-keyboard-bell-percent display) (nth-value 1 (xlib:keyboard-control display))) (define (x-keyboard-bell-pitch display) (nth-value 2 (xlib:keyboard-control display))) (define (x-keyboard-bell-duration display) (nth-value 3 (xlib:keyboard-control display))) (define (x-keyboard-led display) (nth-value 4 (xlib:keyboard-control display))) (define (x-keyboard-auto-repeat-mode display) (nth-value 6 (xlib:keyboard-control display))) (define (x-modifier-mapping display) (lisp:multiple-value-list (xlib:modifier-mapping display))) (define (x-set-modifier-mapping display l) (let ((l1 (cddddr l))) (xlib:set-modifier-mapping display :shift (car l) :lock (cadr l) :control (caddr l) :mod1 (cadddr l) :mod2 (car l1) :mod3 (cadr l1) :mod4 (caddr l1) :mod5 (cadddr l1)))) (define (x-keysym-character display keysym state) (let ((res (xlib:keysym->character display keysym state))) (if (char? res) (char->integer res) '()))) (define (x-keycode-character display keycode state) (let ((res (xlib:keycode->character display keycode state))) (if (char? res) (char->integer res) '()))) (define-attribute-setter close-down mode) (define-attribute-setter access control) (define (x-screen-saver display) (lisp:multiple-value-list (xlib:screen-saver display))) (define (x-set-screen-saver display ss) (xlib:set-screen-saver display (car ss) (cadr ss) (caddr ss) (cadddr ss))) (define (slots->keywords slots) (if (null slots) '() `(,@(slot->keyword (car slots)) ,@(slots->keywords (cdr slots))))) (define (slot->keyword slot) (let* ((tag (keyword-key slot)) (val (keyword-val slot))) (case tag (:pos `(:x ,(xpoint-x val) :y ,(xpoint-y val))) (:root-pos `(:root-x ,(xpoint-x val) :root-y ,(xpoint-y val))) (:size `(:width ,(xsize-w val) :height ,(xsize-h val))) (:rect `(:x ,(xrect-x val) :y ,(xrect-y val) :width ,(xrect-w val) :height ,(xrect-h val))) (:graph-fun `(:major ,(car val) :minor ,(cdr val))) (:visibility `(:state ,val)) (:property-state `(:state ,val)) (:message `(:data ,(car val) :type ,(cadr val) :format ,(caddr val))) (else `(,tag ,val))))) (define (keywords->slots type keywords event) (let* ((slots (keywords->slots1 type keywords)) (has-root-xy (memq type '(:key-press :key-release :button-press :button-release :motion-notify :enter-notify :leave-notify))) (has-xy (or has-root-xy (memq type '(:gravity-notify :reparent-notify)))) (has-graph-fun (memq type '(:graphics-exposure :no-exposure))) (has-rect (memq type '(:exposure :graphics-exposure :configure-notify :create-notify :configure-request))) (has-size (memq type '(:resize-request))) (has-message (memq type '(:client-message)))) (when has-xy (push (make-keyword :pos (x-event-pos event)) slots)) (when has-root-xy (push (make-keyword :root-pos (x-event-root-pos event)) slots)) (when has-graph-fun (push (make-keyword :graph-fun (x-event-graph-fun event)) slots)) (when has-rect (push (make-keyword :rect (x-event-rect event)) slots)) (when has-size (push (make-keyword :size (x-event-size event)) slots)) (when has-message (push (make-keyword :message (x-event-message event)) slots)) slots)) (define (keywords->slots1 type keywords) (if (null? keywords) '() (if (memq (car keywords) '(:x :y :width :height :root-x :root-y :major :minor :type :data :format)) (keywords->slots1 type (cddr keywords)) (cons (keyword->slot type (car keywords) (cadr keywords)) (keywords->slots1 type (cddr keywords)))))) (define (keyword->slot type slot val) (if (eq? slot :state) (case type (:property-state (make-keyword :property-state val)) (:visibility (make-keyword :visibility val)) (else (make-keyword :state val))) (make-keyword slot val))) (define (attrs->keywords attrs) (if (null attrs) '() (nconc (attr->keyword (car attrs)) (attrs->keywords (cdr attrs))))) (define (attr->keyword attr) (let* ((tag (keyword-key attr)) (val (keyword-val attr))) (case tag (:clip-origin `(:clip-x ,(xpoint-x val) :clip-y ,(xpoint-y val))) (:dashes `(,tag ,(haskell-list->list/identity val))) (:tile-origin `(:ts-x ,(xpoint-x val) :ts-y ,(xpoint-y val))) (:size `(:width ,(xsize-w val) :height ,(xsize-h val))) (:name `(:name ,(haskell-string->string val))) (:hot-spot `(:x-hot ,(xpoint-x val) :y-hot ,(xpoint-y val))) (else `(,tag ,val))))) (define (x-mutable-array-create inits) (list->vector inits)) (define (x-mutable-array-lookup a i) (vector-ref a i)) (define (x-mutable-array-update a i x) (setf (vector-ref a i) x)) (define (x-mutable-array-length a) (vector-length a)) (define (get-time-zone) (nth-value 8 (lisp:get-decoded-time))) (define (decode-time time zone) (multiple-value-bind (sec min hour date mon year week ds-p) (if zone (lisp:decode-universal-time time zone) (lisp:decode-universal-time time)) (make-h-tuple (list->haskell-list/identity (list sec min hour date mon year week)) ds-p))) (define (encode-time time zone) (apply (function lisp:encode-universal-time) (if (null? zone) time (append time (list zone))))) (define (get-run-time) (/ (lisp:coerce (lisp:get-internal-run-time) 'lisp:single-float) (lisp:coerce lisp:internal-time-units-per-second 'lisp:single-float))) (define (get-elapsed-time) (/ (lisp:coerce (lisp:get-internal-real-time) 'lisp:single-float) (lisp:coerce lisp:internal-time-units-per-second 'lisp:single-float))) (define (prim.thenio---1 x fn) (lambda (state) (declare (ignore state)) (let ((res (funcall x (box 'state)))) (format '#t "~A~%" res) (funcall fn res (box 'state))))) (define-attribute-setter wm name) (define-attribute-setter wm icon-name)