_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
07c5b05d5921cdaf24245de21bd0a1bdc1dfe903b62ad875890511a274b9844a
Bogdanp/racket-crontab
main.rkt
#lang racket/base (require "crontab.rkt" "schedule.rkt") (provide (all-from-out "crontab.rkt" "schedule.rkt"))
null
https://raw.githubusercontent.com/Bogdanp/racket-crontab/83b81b8101b69deebd35cf9f979935ca7e7cb855/crontab-lib/main.rkt
racket
#lang racket/base (require "crontab.rkt" "schedule.rkt") (provide (all-from-out "crontab.rkt" "schedule.rkt"))
2915895e97cf9835065daf751805a9e873ed311c51f999fa6e14c819031ae786
ocaml/ocamlbuild
tags.mli
(***********************************************************************) (* *) (* ocamlbuild *) (* *) , , projet Gallium , INRIA Rocquencourt (* *) Copyright 2007 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) Original author : include Signatures.TAGS
null
https://raw.githubusercontent.com/ocaml/ocamlbuild/792b7c8abdbc712c98ed7e69469ed354b87e125b/src/tags.mli
ocaml
********************************************************************* ocamlbuild the special exception on linking described in file ../LICENSE. *********************************************************************
, , projet Gallium , INRIA Rocquencourt Copyright 2007 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with Original author : include Signatures.TAGS
a4ee11aa5c0e5874fc482e77ba47c9c527e3bc859cfc154abcef6c9fcf79af21
janestreet/hardcaml
mangler.ml
open Base type t = { case_sensitive : bool ; table : (string, int) Hashtbl.t } [@@deriving sexp_of] let create ~case_sensitive = { case_sensitive ; table = Hashtbl.create (if case_sensitive then (module String) else (module String.Caseless)) } ;; let add_identifier t name = Hashtbl.add t.table ~key:name ~data:0 let add_identifiers_exn t names = List.iter names ~f:(fun name -> match add_identifier t name with | `Ok -> () | `Duplicate -> raise_s [%message "Failed to add identifier to mangler as it is already present" ~invalid_identifier:(name : string)]) ;; let find_index t = Hashtbl.find t.table let rec mangle t name = match find_index t name with | None -> Hashtbl.add_exn t.table ~key:name ~data:0; name | Some i -> Hashtbl.set t.table ~key:name ~data:(i + 1); mangle t (name ^ "_" ^ Int.to_string i) ;;
null
https://raw.githubusercontent.com/janestreet/hardcaml/4126f65f39048fef5853ba9b8d766143f678a9e4/src/mangler.ml
ocaml
open Base type t = { case_sensitive : bool ; table : (string, int) Hashtbl.t } [@@deriving sexp_of] let create ~case_sensitive = { case_sensitive ; table = Hashtbl.create (if case_sensitive then (module String) else (module String.Caseless)) } ;; let add_identifier t name = Hashtbl.add t.table ~key:name ~data:0 let add_identifiers_exn t names = List.iter names ~f:(fun name -> match add_identifier t name with | `Ok -> () | `Duplicate -> raise_s [%message "Failed to add identifier to mangler as it is already present" ~invalid_identifier:(name : string)]) ;; let find_index t = Hashtbl.find t.table let rec mangle t name = match find_index t name with | None -> Hashtbl.add_exn t.table ~key:name ~data:0; name | Some i -> Hashtbl.set t.table ~key:name ~data:(i + 1); mangle t (name ^ "_" ^ Int.to_string i) ;;
b328ff755b25111c2091ee9030892be833e251563baeeeee9f950f007202a7cb
tsloughter/kuberl
kuberl_batch_v2alpha1_api.erl
-module(kuberl_batch_v2alpha1_api). -export([create_namespaced_cron_job/3, create_namespaced_cron_job/4, delete_collection_namespaced_cron_job/2, delete_collection_namespaced_cron_job/3, delete_namespaced_cron_job/4, delete_namespaced_cron_job/5, get_api_resources/1, get_api_resources/2, list_cron_job_for_all_namespaces/1, list_cron_job_for_all_namespaces/2, list_namespaced_cron_job/2, list_namespaced_cron_job/3, patch_namespaced_cron_job/4, patch_namespaced_cron_job/5, patch_namespaced_cron_job_status/4, patch_namespaced_cron_job_status/5, read_namespaced_cron_job/3, read_namespaced_cron_job/4, read_namespaced_cron_job_status/3, read_namespaced_cron_job_status/4, replace_namespaced_cron_job/4, replace_namespaced_cron_job/5, replace_namespaced_cron_job_status/4, replace_namespaced_cron_job_status/5]). -define(BASE_URL, ""). %% @doc create a -spec create_namespaced_cron_job(ctx:ctx(), binary(), kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. create_namespaced_cron_job(Ctx, Namespace, Body) -> create_namespaced_cron_job(Ctx, Namespace, Body, #{}). -spec create_namespaced_cron_job(ctx:ctx(), binary(), kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. create_namespaced_cron_job(Ctx, Namespace, Body, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = post, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs"], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty'], _OptionalParams), Headers = [], Body1 = Body, ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). %% @doc delete collection of -spec delete_collection_namespaced_cron_job(ctx:ctx(), binary()) -> {ok, kuberl_v1_status:kuberl_v1_status(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. delete_collection_namespaced_cron_job(Ctx, Namespace) -> delete_collection_namespaced_cron_job(Ctx, Namespace, #{}). -spec delete_collection_namespaced_cron_job(ctx:ctx(), binary(), maps:map()) -> {ok, kuberl_v1_status:kuberl_v1_status(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. delete_collection_namespaced_cron_job(Ctx, Namespace, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = delete, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs"], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty', 'continue', 'fieldSelector', 'includeUninitialized', 'labelSelector', 'limit', 'resourceVersion', 'timeoutSeconds', 'watch'], _OptionalParams), Headers = [], Body1 = [], ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). %% @doc delete a -spec delete_namespaced_cron_job(ctx:ctx(), binary(), binary(), kuberl_v1_delete_options:kuberl_v1_delete_options()) -> {ok, kuberl_v1_status:kuberl_v1_status(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. delete_namespaced_cron_job(Ctx, Name, Namespace, Body) -> delete_namespaced_cron_job(Ctx, Name, Namespace, Body, #{}). -spec delete_namespaced_cron_job(ctx:ctx(), binary(), binary(), kuberl_v1_delete_options:kuberl_v1_delete_options(), maps:map()) -> {ok, kuberl_v1_status:kuberl_v1_status(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. delete_namespaced_cron_job(Ctx, Name, Namespace, Body, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = delete, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs/", Name, ""], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty', 'gracePeriodSeconds', 'orphanDependents', 'propagationPolicy'], _OptionalParams), Headers = [], Body1 = Body, ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). %% @doc %% get available resources -spec get_api_resources(ctx:ctx()) -> {ok, kuberl_v1_api_resource_list:kuberl_v1_api_resource_list(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. get_api_resources(Ctx) -> get_api_resources(Ctx, #{}). -spec get_api_resources(ctx:ctx(), maps:map()) -> {ok, kuberl_v1_api_resource_list:kuberl_v1_api_resource_list(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. get_api_resources(Ctx, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, Path = ["/apis/batch/v2alpha1/"], QS = [], Headers = [], Body1 = [], ContentTypeHeader = kuberl_utils:select_header_content_type([<<"application/json">>, <<"application/yaml">>, <<"application/vnd.kubernetes.protobuf">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). %% @doc list or watch objects of kind -spec list_cron_job_for_all_namespaces(ctx:ctx()) -> {ok, kuberl_v2alpha1_cron_job_list:kuberl_v2alpha1_cron_job_list(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. list_cron_job_for_all_namespaces(Ctx) -> list_cron_job_for_all_namespaces(Ctx, #{}). -spec list_cron_job_for_all_namespaces(ctx:ctx(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job_list:kuberl_v2alpha1_cron_job_list(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. list_cron_job_for_all_namespaces(Ctx, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, Path = ["/apis/batch/v2alpha1/cronjobs"], QS = lists:flatten([])++kuberl_utils:optional_params(['continue', 'fieldSelector', 'includeUninitialized', 'labelSelector', 'limit', 'pretty', 'resourceVersion', 'timeoutSeconds', 'watch'], _OptionalParams), Headers = [], Body1 = [], ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). %% @doc list or watch objects of kind -spec list_namespaced_cron_job(ctx:ctx(), binary()) -> {ok, kuberl_v2alpha1_cron_job_list:kuberl_v2alpha1_cron_job_list(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. list_namespaced_cron_job(Ctx, Namespace) -> list_namespaced_cron_job(Ctx, Namespace, #{}). -spec list_namespaced_cron_job(ctx:ctx(), binary(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job_list:kuberl_v2alpha1_cron_job_list(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. list_namespaced_cron_job(Ctx, Namespace, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs"], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty', 'continue', 'fieldSelector', 'includeUninitialized', 'labelSelector', 'limit', 'resourceVersion', 'timeoutSeconds', 'watch'], _OptionalParams), Headers = [], Body1 = [], ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). %% @doc partially update the specified -spec patch_namespaced_cron_job(ctx:ctx(), binary(), binary(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. patch_namespaced_cron_job(Ctx, Name, Namespace, Body) -> patch_namespaced_cron_job(Ctx, Name, Namespace, Body, #{}). -spec patch_namespaced_cron_job(ctx:ctx(), binary(), binary(), maps:map(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. patch_namespaced_cron_job(Ctx, Name, Namespace, Body, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = patch, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs/", Name, ""], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty'], _OptionalParams), Headers = [], Body1 = Body, ContentTypeHeader = kuberl_utils:select_header_content_type([<<"application/json-patch+json">>, <<"application/merge-patch+json">>, <<"application/strategic-merge-patch+json">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). %% @doc partially update status of the specified -spec patch_namespaced_cron_job_status(ctx:ctx(), binary(), binary(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. patch_namespaced_cron_job_status(Ctx, Name, Namespace, Body) -> patch_namespaced_cron_job_status(Ctx, Name, Namespace, Body, #{}). -spec patch_namespaced_cron_job_status(ctx:ctx(), binary(), binary(), maps:map(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. patch_namespaced_cron_job_status(Ctx, Name, Namespace, Body, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = patch, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs/", Name, "/status"], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty'], _OptionalParams), Headers = [], Body1 = Body, ContentTypeHeader = kuberl_utils:select_header_content_type([<<"application/json-patch+json">>, <<"application/merge-patch+json">>, <<"application/strategic-merge-patch+json">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). %% @doc read the specified -spec read_namespaced_cron_job(ctx:ctx(), binary(), binary()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. read_namespaced_cron_job(Ctx, Name, Namespace) -> read_namespaced_cron_job(Ctx, Name, Namespace, #{}). -spec read_namespaced_cron_job(ctx:ctx(), binary(), binary(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. read_namespaced_cron_job(Ctx, Name, Namespace, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs/", Name, ""], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty', 'exact', 'export'], _OptionalParams), Headers = [], Body1 = [], ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). %% @doc read status of the specified -spec read_namespaced_cron_job_status(ctx:ctx(), binary(), binary()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. read_namespaced_cron_job_status(Ctx, Name, Namespace) -> read_namespaced_cron_job_status(Ctx, Name, Namespace, #{}). -spec read_namespaced_cron_job_status(ctx:ctx(), binary(), binary(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. read_namespaced_cron_job_status(Ctx, Name, Namespace, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs/", Name, "/status"], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty'], _OptionalParams), Headers = [], Body1 = [], ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). %% @doc replace the specified -spec replace_namespaced_cron_job(ctx:ctx(), binary(), binary(), kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. replace_namespaced_cron_job(Ctx, Name, Namespace, Body) -> replace_namespaced_cron_job(Ctx, Name, Namespace, Body, #{}). -spec replace_namespaced_cron_job(ctx:ctx(), binary(), binary(), kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. replace_namespaced_cron_job(Ctx, Name, Namespace, Body, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = put, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs/", Name, ""], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty'], _OptionalParams), Headers = [], Body1 = Body, ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). %% @doc replace status of the specified -spec replace_namespaced_cron_job_status(ctx:ctx(), binary(), binary(), kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. replace_namespaced_cron_job_status(Ctx, Name, Namespace, Body) -> replace_namespaced_cron_job_status(Ctx, Name, Namespace, Body, #{}). -spec replace_namespaced_cron_job_status(ctx:ctx(), binary(), binary(), kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. replace_namespaced_cron_job_status(Ctx, Name, Namespace, Body, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = put, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs/", Name, "/status"], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty'], _OptionalParams), Headers = [], Body1 = Body, ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg).
null
https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_batch_v2alpha1_api.erl
erlang
@doc @doc @doc @doc get available resources @doc @doc @doc @doc @doc @doc @doc @doc
-module(kuberl_batch_v2alpha1_api). -export([create_namespaced_cron_job/3, create_namespaced_cron_job/4, delete_collection_namespaced_cron_job/2, delete_collection_namespaced_cron_job/3, delete_namespaced_cron_job/4, delete_namespaced_cron_job/5, get_api_resources/1, get_api_resources/2, list_cron_job_for_all_namespaces/1, list_cron_job_for_all_namespaces/2, list_namespaced_cron_job/2, list_namespaced_cron_job/3, patch_namespaced_cron_job/4, patch_namespaced_cron_job/5, patch_namespaced_cron_job_status/4, patch_namespaced_cron_job_status/5, read_namespaced_cron_job/3, read_namespaced_cron_job/4, read_namespaced_cron_job_status/3, read_namespaced_cron_job_status/4, replace_namespaced_cron_job/4, replace_namespaced_cron_job/5, replace_namespaced_cron_job_status/4, replace_namespaced_cron_job_status/5]). -define(BASE_URL, ""). create a -spec create_namespaced_cron_job(ctx:ctx(), binary(), kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. create_namespaced_cron_job(Ctx, Namespace, Body) -> create_namespaced_cron_job(Ctx, Namespace, Body, #{}). -spec create_namespaced_cron_job(ctx:ctx(), binary(), kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. create_namespaced_cron_job(Ctx, Namespace, Body, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = post, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs"], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty'], _OptionalParams), Headers = [], Body1 = Body, ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). delete collection of -spec delete_collection_namespaced_cron_job(ctx:ctx(), binary()) -> {ok, kuberl_v1_status:kuberl_v1_status(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. delete_collection_namespaced_cron_job(Ctx, Namespace) -> delete_collection_namespaced_cron_job(Ctx, Namespace, #{}). -spec delete_collection_namespaced_cron_job(ctx:ctx(), binary(), maps:map()) -> {ok, kuberl_v1_status:kuberl_v1_status(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. delete_collection_namespaced_cron_job(Ctx, Namespace, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = delete, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs"], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty', 'continue', 'fieldSelector', 'includeUninitialized', 'labelSelector', 'limit', 'resourceVersion', 'timeoutSeconds', 'watch'], _OptionalParams), Headers = [], Body1 = [], ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). delete a -spec delete_namespaced_cron_job(ctx:ctx(), binary(), binary(), kuberl_v1_delete_options:kuberl_v1_delete_options()) -> {ok, kuberl_v1_status:kuberl_v1_status(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. delete_namespaced_cron_job(Ctx, Name, Namespace, Body) -> delete_namespaced_cron_job(Ctx, Name, Namespace, Body, #{}). -spec delete_namespaced_cron_job(ctx:ctx(), binary(), binary(), kuberl_v1_delete_options:kuberl_v1_delete_options(), maps:map()) -> {ok, kuberl_v1_status:kuberl_v1_status(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. delete_namespaced_cron_job(Ctx, Name, Namespace, Body, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = delete, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs/", Name, ""], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty', 'gracePeriodSeconds', 'orphanDependents', 'propagationPolicy'], _OptionalParams), Headers = [], Body1 = Body, ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). -spec get_api_resources(ctx:ctx()) -> {ok, kuberl_v1_api_resource_list:kuberl_v1_api_resource_list(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. get_api_resources(Ctx) -> get_api_resources(Ctx, #{}). -spec get_api_resources(ctx:ctx(), maps:map()) -> {ok, kuberl_v1_api_resource_list:kuberl_v1_api_resource_list(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. get_api_resources(Ctx, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, Path = ["/apis/batch/v2alpha1/"], QS = [], Headers = [], Body1 = [], ContentTypeHeader = kuberl_utils:select_header_content_type([<<"application/json">>, <<"application/yaml">>, <<"application/vnd.kubernetes.protobuf">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). list or watch objects of kind -spec list_cron_job_for_all_namespaces(ctx:ctx()) -> {ok, kuberl_v2alpha1_cron_job_list:kuberl_v2alpha1_cron_job_list(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. list_cron_job_for_all_namespaces(Ctx) -> list_cron_job_for_all_namespaces(Ctx, #{}). -spec list_cron_job_for_all_namespaces(ctx:ctx(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job_list:kuberl_v2alpha1_cron_job_list(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. list_cron_job_for_all_namespaces(Ctx, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, Path = ["/apis/batch/v2alpha1/cronjobs"], QS = lists:flatten([])++kuberl_utils:optional_params(['continue', 'fieldSelector', 'includeUninitialized', 'labelSelector', 'limit', 'pretty', 'resourceVersion', 'timeoutSeconds', 'watch'], _OptionalParams), Headers = [], Body1 = [], ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). list or watch objects of kind -spec list_namespaced_cron_job(ctx:ctx(), binary()) -> {ok, kuberl_v2alpha1_cron_job_list:kuberl_v2alpha1_cron_job_list(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. list_namespaced_cron_job(Ctx, Namespace) -> list_namespaced_cron_job(Ctx, Namespace, #{}). -spec list_namespaced_cron_job(ctx:ctx(), binary(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job_list:kuberl_v2alpha1_cron_job_list(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. list_namespaced_cron_job(Ctx, Namespace, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs"], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty', 'continue', 'fieldSelector', 'includeUninitialized', 'labelSelector', 'limit', 'resourceVersion', 'timeoutSeconds', 'watch'], _OptionalParams), Headers = [], Body1 = [], ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). partially update the specified -spec patch_namespaced_cron_job(ctx:ctx(), binary(), binary(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. patch_namespaced_cron_job(Ctx, Name, Namespace, Body) -> patch_namespaced_cron_job(Ctx, Name, Namespace, Body, #{}). -spec patch_namespaced_cron_job(ctx:ctx(), binary(), binary(), maps:map(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. patch_namespaced_cron_job(Ctx, Name, Namespace, Body, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = patch, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs/", Name, ""], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty'], _OptionalParams), Headers = [], Body1 = Body, ContentTypeHeader = kuberl_utils:select_header_content_type([<<"application/json-patch+json">>, <<"application/merge-patch+json">>, <<"application/strategic-merge-patch+json">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). partially update status of the specified -spec patch_namespaced_cron_job_status(ctx:ctx(), binary(), binary(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. patch_namespaced_cron_job_status(Ctx, Name, Namespace, Body) -> patch_namespaced_cron_job_status(Ctx, Name, Namespace, Body, #{}). -spec patch_namespaced_cron_job_status(ctx:ctx(), binary(), binary(), maps:map(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. patch_namespaced_cron_job_status(Ctx, Name, Namespace, Body, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = patch, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs/", Name, "/status"], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty'], _OptionalParams), Headers = [], Body1 = Body, ContentTypeHeader = kuberl_utils:select_header_content_type([<<"application/json-patch+json">>, <<"application/merge-patch+json">>, <<"application/strategic-merge-patch+json">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). read the specified -spec read_namespaced_cron_job(ctx:ctx(), binary(), binary()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. read_namespaced_cron_job(Ctx, Name, Namespace) -> read_namespaced_cron_job(Ctx, Name, Namespace, #{}). -spec read_namespaced_cron_job(ctx:ctx(), binary(), binary(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. read_namespaced_cron_job(Ctx, Name, Namespace, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs/", Name, ""], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty', 'exact', 'export'], _OptionalParams), Headers = [], Body1 = [], ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). read status of the specified -spec read_namespaced_cron_job_status(ctx:ctx(), binary(), binary()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. read_namespaced_cron_job_status(Ctx, Name, Namespace) -> read_namespaced_cron_job_status(Ctx, Name, Namespace, #{}). -spec read_namespaced_cron_job_status(ctx:ctx(), binary(), binary(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. read_namespaced_cron_job_status(Ctx, Name, Namespace, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs/", Name, "/status"], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty'], _OptionalParams), Headers = [], Body1 = [], ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). replace the specified -spec replace_namespaced_cron_job(ctx:ctx(), binary(), binary(), kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. replace_namespaced_cron_job(Ctx, Name, Namespace, Body) -> replace_namespaced_cron_job(Ctx, Name, Namespace, Body, #{}). -spec replace_namespaced_cron_job(ctx:ctx(), binary(), binary(), kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. replace_namespaced_cron_job(Ctx, Name, Namespace, Body, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = put, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs/", Name, ""], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty'], _OptionalParams), Headers = [], Body1 = Body, ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg). replace status of the specified -spec replace_namespaced_cron_job_status(ctx:ctx(), binary(), binary(), kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. replace_namespaced_cron_job_status(Ctx, Name, Namespace, Body) -> replace_namespaced_cron_job_status(Ctx, Name, Namespace, Body, #{}). -spec replace_namespaced_cron_job_status(ctx:ctx(), binary(), binary(), kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), maps:map()) -> {ok, kuberl_v2alpha1_cron_job:kuberl_v2alpha1_cron_job(), kuberl_utils:response_info()} | {ok, hackney:client_ref()} | {error, term(), kuberl_utils:response_info()}. replace_namespaced_cron_job_status(Ctx, Name, Namespace, Body, Optional) -> _OptionalParams = maps:get(params, Optional, #{}), Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = put, Path = ["/apis/batch/v2alpha1/namespaces/", Namespace, "/cronjobs/", Name, "/status"], QS = lists:flatten([])++kuberl_utils:optional_params(['pretty'], _OptionalParams), Headers = [], Body1 = Body, ContentTypeHeader = kuberl_utils:select_header_content_type([<<"*/*">>]), Opts = maps:get(hackney_opts, Optional, []), kuberl_utils:request(Ctx, Method, [?BASE_URL, Path], QS, ContentTypeHeader++Headers, Body1, Opts, Cfg).
12746001d141a415a7e64047502b3ffa0a5edd48200628e4e22ff85a50977f3c
tyehle/llvm-lambda
LLSpec.hs
module LLSpec (lowLevelTests) where import qualified Data.Set as Set import Test.Tasty import Test.Tasty.HUnit import LowLevel import Parsing (parse) emitLL :: String -> Prog emitLL input = runConvert (either error id $ parse "test_input" input) Set.empty checkLowLevel :: String -> Prog -> Assertion checkLowLevel input expected = emitLL input @?= expected lowLevelTests :: TestTree lowLevelTests = testGroup "Low Level Tests" [ testCase "letrec" $ checkLowLevel "(letrec [x x] x)" (Prog [ClosureDef "_f0" "_env" ["x"] (AppClos (Ref "x") [Ref "x"])] (Let "x" (NewClos "_f0" []) (AppClos (Ref "x") [Ref "x"]))) , testCase "lambda" $ checkLowLevel "(lambda (x y) y)" (Prog [ClosureDef "_f0" "_env" ["x", "y"] (Ref "y")] (NewClos "_f0" [])) , testCase "lambda shadowing" $ checkLowLevel "(lambda (x) (lambda (x) x))" (Prog [ ClosureDef "_f0" "_env" ["x"] (NewClos "_f1" []) , ClosureDef "_f1" "_env" ["x"] (Ref "x") ] (NewClos "_f0" [])) , testCase "lambda nested reference" $ checkLowLevel "(lambda (x) (lambda (y) x))" (Prog [ ClosureDef "_f0" "_env" ["x"] (NewClos "_f1" [Ref "x"]) , ClosureDef "_f1" "_env" ["y"] (GetEnv "_env" 0) ] (NewClos "_f0" [])) , testCase "lambda double nested reference" $ checkLowLevel "(lambda (x) (lambda (y) (lambda (z) (+ x y))))" (Prog [ ClosureDef "_f0" "_env" ["x"] (NewClos "_f1" [Ref "x"]) , ClosureDef "_f1" "_env" ["y"] (NewClos "_f2" [GetEnv "_env" 0, Ref "y"]) , ClosureDef "_f2" "_env" ["z"] (Plus (GetEnv "_env" 0) (GetEnv "_env" 1)) ] (NewClos "_f0" [])) ]
null
https://raw.githubusercontent.com/tyehle/llvm-lambda/679a9e1cc1d288fc9731a6f43fc45714c455741b/test/LLSpec.hs
haskell
module LLSpec (lowLevelTests) where import qualified Data.Set as Set import Test.Tasty import Test.Tasty.HUnit import LowLevel import Parsing (parse) emitLL :: String -> Prog emitLL input = runConvert (either error id $ parse "test_input" input) Set.empty checkLowLevel :: String -> Prog -> Assertion checkLowLevel input expected = emitLL input @?= expected lowLevelTests :: TestTree lowLevelTests = testGroup "Low Level Tests" [ testCase "letrec" $ checkLowLevel "(letrec [x x] x)" (Prog [ClosureDef "_f0" "_env" ["x"] (AppClos (Ref "x") [Ref "x"])] (Let "x" (NewClos "_f0" []) (AppClos (Ref "x") [Ref "x"]))) , testCase "lambda" $ checkLowLevel "(lambda (x y) y)" (Prog [ClosureDef "_f0" "_env" ["x", "y"] (Ref "y")] (NewClos "_f0" [])) , testCase "lambda shadowing" $ checkLowLevel "(lambda (x) (lambda (x) x))" (Prog [ ClosureDef "_f0" "_env" ["x"] (NewClos "_f1" []) , ClosureDef "_f1" "_env" ["x"] (Ref "x") ] (NewClos "_f0" [])) , testCase "lambda nested reference" $ checkLowLevel "(lambda (x) (lambda (y) x))" (Prog [ ClosureDef "_f0" "_env" ["x"] (NewClos "_f1" [Ref "x"]) , ClosureDef "_f1" "_env" ["y"] (GetEnv "_env" 0) ] (NewClos "_f0" [])) , testCase "lambda double nested reference" $ checkLowLevel "(lambda (x) (lambda (y) (lambda (z) (+ x y))))" (Prog [ ClosureDef "_f0" "_env" ["x"] (NewClos "_f1" [Ref "x"]) , ClosureDef "_f1" "_env" ["y"] (NewClos "_f2" [GetEnv "_env" 0, Ref "y"]) , ClosureDef "_f2" "_env" ["z"] (Plus (GetEnv "_env" 0) (GetEnv "_env" 1)) ] (NewClos "_f0" [])) ]
19d52e74e262624563ace2db023b245a1030f2e260c7d0dd1d422f76a2f0f22d
oliyh/superlifter
lacinia.clj
(ns superlifter.lacinia (:require [superlifter.core :as s] [superlifter.api :as api] [io.pedestal.interceptor :refer [interceptor]] [com.walmartlabs.lacinia.resolve :as resolve] [promesa.core :as prom])) (defn inject-superlifter [superlifter-args] (interceptor {:name ::inject-superlifter :enter (fn [ctx] (assoc-in ctx [:request :superlifter] (s/start! superlifter-args))) :leave (fn [ctx] (update-in ctx [:request :superlifter] s/stop!))})) (defn ->lacinia-promise [sl-result] (let [l-prom (resolve/resolve-promise)] (api/unwrap #(resolve/deliver! l-prom %) (prom/catch sl-result prom/resolved)) l-prom)) (defmacro with-superlifter [ctx body] `(api/with-superlifter (get-in ~ctx [:request :superlifter]) (->lacinia-promise ~body)))
null
https://raw.githubusercontent.com/oliyh/superlifter/d0baf9538f1dac712415323a2f2a6578c181bd97/src/superlifter/lacinia.clj
clojure
(ns superlifter.lacinia (:require [superlifter.core :as s] [superlifter.api :as api] [io.pedestal.interceptor :refer [interceptor]] [com.walmartlabs.lacinia.resolve :as resolve] [promesa.core :as prom])) (defn inject-superlifter [superlifter-args] (interceptor {:name ::inject-superlifter :enter (fn [ctx] (assoc-in ctx [:request :superlifter] (s/start! superlifter-args))) :leave (fn [ctx] (update-in ctx [:request :superlifter] s/stop!))})) (defn ->lacinia-promise [sl-result] (let [l-prom (resolve/resolve-promise)] (api/unwrap #(resolve/deliver! l-prom %) (prom/catch sl-result prom/resolved)) l-prom)) (defmacro with-superlifter [ctx body] `(api/with-superlifter (get-in ~ctx [:request :superlifter]) (->lacinia-promise ~body)))
ee4d6e4a35ae0da2829ed28270ffe4b4135f663a68f0c48925645a2ebdb1db19
dhleong/wish
core.clj
(ns wish.core)
null
https://raw.githubusercontent.com/dhleong/wish/9036f9da3706bfcc1e4b4736558b6f7309f53b7b/src/clj/wish/core.clj
clojure
(ns wish.core)
1b78ff3a916243c4cf6385644b81562b391514183f2e93e647382fa034f1bf04
triffon/fp-2022-23
02-power.rkt
#lang racket (define (power base exp) (define (helper exp accum) (if (= 0 exp) accum (helper (- exp 1) (* accum base)))) (helper exp 1)) ( power 5 3 ) = ( helper 3 1 ) = ( helper 2 5 ) = ( helper 1 25 ) = ( helper 0 125 ) = 125
null
https://raw.githubusercontent.com/triffon/fp-2022-23/af48edbfc8a3697ee23bcccb3ae1ffc17c1fb7ff/exercises/inf2/02/02-power.rkt
racket
#lang racket (define (power base exp) (define (helper exp accum) (if (= 0 exp) accum (helper (- exp 1) (* accum base)))) (helper exp 1)) ( power 5 3 ) = ( helper 3 1 ) = ( helper 2 5 ) = ( helper 1 25 ) = ( helper 0 125 ) = 125
a7d0ee5ec5ea564465307bfd51c80db176b3c5162d726e78a0280c46eb3e7ee0
owickstrom/komposition
UserInterface.hs
# OPTIONS_GHC -fno - warn - unticked - promoted - constructors # {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} # LANGUAGE FlexibleContexts # {-# LANGUAGE GADTs #-} # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RankNTypes # # LANGUAGE StandaloneDeriving # {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeInType #-} {-# LANGUAGE TypeOperators #-} module Komposition.UserInterface where import Komposition.Prelude hiding ( State ) import Control.Lens import qualified Komposition.Composition.Paste as Paste import qualified Komposition.Composition.Insert as Insert import Komposition.Duration import Komposition.Focus import Komposition.KeyMap import Komposition.Library import Komposition.MediaType import Komposition.Project import Komposition.VideoSettings import Komposition.VideoSpeed import Komposition.UserInterface.WindowUserInterface data Mode = WelcomeScreenMode | NewProjectMode | TimelineMode | LibraryMode | ImportMode data SMode m where SWelcomeScreenMode ::SMode WelcomeScreenMode SNewProjectMode ::SMode NewProjectMode STimelineMode ::SMode TimelineMode SLibraryMode ::SMode LibraryMode SImportMode ::SMode ImportMode modeTitle :: SMode m -> Text modeTitle = \case SWelcomeScreenMode -> "Welcome Screen Mode" SNewProjectMode -> "New Project Mode" STimelineMode -> "Timeline Mode" SLibraryMode -> "Library Mode" SImportMode -> "Import Mode" data InsertType = InsertComposition | InsertClip (Maybe MediaType) | InsertGap (Maybe MediaType) deriving (Show, Eq, Ord) data Command (mode :: Mode) where Cancel ::Command mode Help ::Command mode FocusCommand ::FocusCommand -> Command TimelineMode JumpFocus ::Focus SequenceFocusType -> Command TimelineMode InsertCommand ::InsertType -> Insert.InsertPosition -> Command TimelineMode Split ::Command TimelineMode Join ::Command TimelineMode Delete ::Command TimelineMode Copy ::Command TimelineMode Paste ::Paste.PastePosition -> Command TimelineMode Import ::Command TimelineMode Render ::Command TimelineMode PlayOrStop ::Command TimelineMode Undo ::Command TimelineMode Redo ::Command TimelineMode SaveProject ::Command TimelineMode CloseProject ::Command TimelineMode Exit ::Command TimelineMode deriving instance Eq (Command mode) deriving instance Ord (Command mode) deriving instance Show (Command mode) commandName :: Command mode -> Text commandName = \case Cancel -> "Cancel" Help -> "Show Help" FocusCommand cmd -> case cmd of FocusUp -> "Move Focus Up" FocusDown -> "Move Focus Down" FocusLeft -> "Move Focus Left" FocusRight -> "Move Focus Right" JumpFocus _ -> "Jump Focus To" InsertCommand insertType insertPosition -> mconcat [insertTypeName insertType, " (", insertPositionName insertPosition, ")"] Split -> "Split" Join -> "Join" Delete -> "Delete" Copy -> "Copy" Paste pos -> case pos of Paste.PasteLeftOf -> "Paste Left Of" Paste.PasteRightOf -> "Paste Right Of" Import -> "Import Assets" Render -> "Render" PlayOrStop -> "Play/Stop" Undo -> "Undo" Redo -> "Redo" SaveProject -> "Save" CloseProject -> "Close" Exit -> "Exit" where insertTypeName :: InsertType -> Text insertTypeName = \case InsertClip Nothing -> "Insert Clip" InsertGap Nothing -> "Insert Gap" InsertClip (Just Video) -> "Insert Video Clip" InsertGap (Just Video) -> "Insert Video Gap" InsertClip (Just Audio) -> "Insert Audio Clip" InsertGap (Just Audio) -> "Insert Audio Gap" InsertComposition -> "Insert Composition" insertPositionName :: Insert.InsertPosition -> Text insertPositionName = \case Insert.LeftMost -> "Leftmost" Insert.LeftOf -> "Left of" Insert.RightOf -> "Right of" Insert.RightMost -> "Rightmost" data Event mode where CommandKeyMappedEvent ::Show (Command mode) => Command mode -> Event mode -- Welcome Screen CreateNewProjectClicked ::Event WelcomeScreenMode OpenExistingProjectClicked ::Event WelcomeScreenMode New Project ProjectNameChanged ::Text -> Event NewProjectMode FrameRateChanged ::FrameRate -> Event NewProjectMode ResolutionChanged ::Resolution -> Event NewProjectMode CreateClicked ::Event NewProjectMode -- Timeline ZoomLevelChanged ::ZoomLevel -> Event TimelineMode PreviewFrameExtracted ::FilePath -> Event TimelineMode FocusedClipSpeedSet ::VideoSpeed -> Event TimelineMode FocusedClipStartSet ::Duration -> Event TimelineMode FocusedClipEndSet ::Duration -> Event TimelineMode StreamingProcessFailed ::Text -> Event TimelineMode PlaybackProgress ::Double -> Event TimelineMode PlaybackRestarting ::Event TimelineMode PlaybackFinished ::Event TimelineMode -- Import ImportFileSelected ::Maybe FilePath -> Event ImportMode ImportClassifySet ::Bool -> Event ImportMode ImportDefaultVideoSpeedChanged ::VideoSpeed -> Event ImportMode ImportClicked ::Event ImportMode Library LibraryAssetsSelected ::(Show (SMediaType mt), Show (Asset mt)) => SMediaType mt -> [Asset mt] -> Event LibraryMode LibrarySelectionConfirmed ::Event LibraryMode WindowClosed ::Event mode deriving instance Show (Event mode) data ModeKeyMap where ModeKeyMap :: Ord (Command mode) => SMode mode -> KeyMap (Command mode) -> ModeKeyMap type KeyMaps = forall mode . SMode mode -> KeyMap (Event mode) newtype ZoomLevel = ZoomLevel Double deriving (Eq, Show) data Preview = PlayHttpStream Text Word Duration | PlayFile FilePath Duration | PreviewFrame FilePath deriving (Eq, Show) data TimelineViewModel = TimelineViewModel { _project :: WithHistory Project , _currentFocus :: Focus SequenceFocusType , _statusMessage :: Maybe Text , _zoomLevel :: ZoomLevel , _preview :: Maybe Preview , _playbackProgress :: Maybe Double } deriving (Eq, Show) makeLenses ''TimelineViewModel data NewProjectModel = NewProjectModel { _newProjectName :: Text , _newProjectFrameRate :: FrameRate , _newProjectResolution :: Resolution } makeLenses ''NewProjectModel data ImportFileModel = ImportFileModel { classifyValue :: Bool , classifyAvailable :: Bool , setDefaultVideoSpeed :: VideoSpeed , selectedFileMediaType :: Maybe MediaType } data SelectAssetsModel mt where SelectAssetsModel ::( Show (Asset mt) , Show (SMediaType mt) ) => { mediaType :: SMediaType mt , allAssets :: NonEmpty (Asset mt) , selectedAssets :: [Asset mt] } -> SelectAssetsModel mt class UserInterfaceMarkup markup where welcomeView :: markup TopWindow (Event WelcomeScreenMode) newProjectView :: NewProjectModel -> markup Modal (Event NewProjectMode) timelineView :: TimelineViewModel -> markup TopWindow (Event TimelineMode) libraryView :: SelectAssetsModel mediaType -> markup Modal (Event LibraryMode) importView :: ImportFileModel -> markup Modal (Event ImportMode)
null
https://raw.githubusercontent.com/owickstrom/komposition/64893d50941b90f44d77fea0dc6d30c061464cf3/src/Komposition/UserInterface.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE DataKinds # # LANGUAGE GADTs # # LANGUAGE OverloadedStrings # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # # LANGUAGE TypeInType # # LANGUAGE TypeOperators # Welcome Screen Timeline Import
# OPTIONS_GHC -fno - warn - unticked - promoted - constructors # # LANGUAGE FlexibleContexts # # LANGUAGE LambdaCase # # LANGUAGE RankNTypes # # LANGUAGE StandaloneDeriving # module Komposition.UserInterface where import Komposition.Prelude hiding ( State ) import Control.Lens import qualified Komposition.Composition.Paste as Paste import qualified Komposition.Composition.Insert as Insert import Komposition.Duration import Komposition.Focus import Komposition.KeyMap import Komposition.Library import Komposition.MediaType import Komposition.Project import Komposition.VideoSettings import Komposition.VideoSpeed import Komposition.UserInterface.WindowUserInterface data Mode = WelcomeScreenMode | NewProjectMode | TimelineMode | LibraryMode | ImportMode data SMode m where SWelcomeScreenMode ::SMode WelcomeScreenMode SNewProjectMode ::SMode NewProjectMode STimelineMode ::SMode TimelineMode SLibraryMode ::SMode LibraryMode SImportMode ::SMode ImportMode modeTitle :: SMode m -> Text modeTitle = \case SWelcomeScreenMode -> "Welcome Screen Mode" SNewProjectMode -> "New Project Mode" STimelineMode -> "Timeline Mode" SLibraryMode -> "Library Mode" SImportMode -> "Import Mode" data InsertType = InsertComposition | InsertClip (Maybe MediaType) | InsertGap (Maybe MediaType) deriving (Show, Eq, Ord) data Command (mode :: Mode) where Cancel ::Command mode Help ::Command mode FocusCommand ::FocusCommand -> Command TimelineMode JumpFocus ::Focus SequenceFocusType -> Command TimelineMode InsertCommand ::InsertType -> Insert.InsertPosition -> Command TimelineMode Split ::Command TimelineMode Join ::Command TimelineMode Delete ::Command TimelineMode Copy ::Command TimelineMode Paste ::Paste.PastePosition -> Command TimelineMode Import ::Command TimelineMode Render ::Command TimelineMode PlayOrStop ::Command TimelineMode Undo ::Command TimelineMode Redo ::Command TimelineMode SaveProject ::Command TimelineMode CloseProject ::Command TimelineMode Exit ::Command TimelineMode deriving instance Eq (Command mode) deriving instance Ord (Command mode) deriving instance Show (Command mode) commandName :: Command mode -> Text commandName = \case Cancel -> "Cancel" Help -> "Show Help" FocusCommand cmd -> case cmd of FocusUp -> "Move Focus Up" FocusDown -> "Move Focus Down" FocusLeft -> "Move Focus Left" FocusRight -> "Move Focus Right" JumpFocus _ -> "Jump Focus To" InsertCommand insertType insertPosition -> mconcat [insertTypeName insertType, " (", insertPositionName insertPosition, ")"] Split -> "Split" Join -> "Join" Delete -> "Delete" Copy -> "Copy" Paste pos -> case pos of Paste.PasteLeftOf -> "Paste Left Of" Paste.PasteRightOf -> "Paste Right Of" Import -> "Import Assets" Render -> "Render" PlayOrStop -> "Play/Stop" Undo -> "Undo" Redo -> "Redo" SaveProject -> "Save" CloseProject -> "Close" Exit -> "Exit" where insertTypeName :: InsertType -> Text insertTypeName = \case InsertClip Nothing -> "Insert Clip" InsertGap Nothing -> "Insert Gap" InsertClip (Just Video) -> "Insert Video Clip" InsertGap (Just Video) -> "Insert Video Gap" InsertClip (Just Audio) -> "Insert Audio Clip" InsertGap (Just Audio) -> "Insert Audio Gap" InsertComposition -> "Insert Composition" insertPositionName :: Insert.InsertPosition -> Text insertPositionName = \case Insert.LeftMost -> "Leftmost" Insert.LeftOf -> "Left of" Insert.RightOf -> "Right of" Insert.RightMost -> "Rightmost" data Event mode where CommandKeyMappedEvent ::Show (Command mode) => Command mode -> Event mode CreateNewProjectClicked ::Event WelcomeScreenMode OpenExistingProjectClicked ::Event WelcomeScreenMode New Project ProjectNameChanged ::Text -> Event NewProjectMode FrameRateChanged ::FrameRate -> Event NewProjectMode ResolutionChanged ::Resolution -> Event NewProjectMode CreateClicked ::Event NewProjectMode ZoomLevelChanged ::ZoomLevel -> Event TimelineMode PreviewFrameExtracted ::FilePath -> Event TimelineMode FocusedClipSpeedSet ::VideoSpeed -> Event TimelineMode FocusedClipStartSet ::Duration -> Event TimelineMode FocusedClipEndSet ::Duration -> Event TimelineMode StreamingProcessFailed ::Text -> Event TimelineMode PlaybackProgress ::Double -> Event TimelineMode PlaybackRestarting ::Event TimelineMode PlaybackFinished ::Event TimelineMode ImportFileSelected ::Maybe FilePath -> Event ImportMode ImportClassifySet ::Bool -> Event ImportMode ImportDefaultVideoSpeedChanged ::VideoSpeed -> Event ImportMode ImportClicked ::Event ImportMode Library LibraryAssetsSelected ::(Show (SMediaType mt), Show (Asset mt)) => SMediaType mt -> [Asset mt] -> Event LibraryMode LibrarySelectionConfirmed ::Event LibraryMode WindowClosed ::Event mode deriving instance Show (Event mode) data ModeKeyMap where ModeKeyMap :: Ord (Command mode) => SMode mode -> KeyMap (Command mode) -> ModeKeyMap type KeyMaps = forall mode . SMode mode -> KeyMap (Event mode) newtype ZoomLevel = ZoomLevel Double deriving (Eq, Show) data Preview = PlayHttpStream Text Word Duration | PlayFile FilePath Duration | PreviewFrame FilePath deriving (Eq, Show) data TimelineViewModel = TimelineViewModel { _project :: WithHistory Project , _currentFocus :: Focus SequenceFocusType , _statusMessage :: Maybe Text , _zoomLevel :: ZoomLevel , _preview :: Maybe Preview , _playbackProgress :: Maybe Double } deriving (Eq, Show) makeLenses ''TimelineViewModel data NewProjectModel = NewProjectModel { _newProjectName :: Text , _newProjectFrameRate :: FrameRate , _newProjectResolution :: Resolution } makeLenses ''NewProjectModel data ImportFileModel = ImportFileModel { classifyValue :: Bool , classifyAvailable :: Bool , setDefaultVideoSpeed :: VideoSpeed , selectedFileMediaType :: Maybe MediaType } data SelectAssetsModel mt where SelectAssetsModel ::( Show (Asset mt) , Show (SMediaType mt) ) => { mediaType :: SMediaType mt , allAssets :: NonEmpty (Asset mt) , selectedAssets :: [Asset mt] } -> SelectAssetsModel mt class UserInterfaceMarkup markup where welcomeView :: markup TopWindow (Event WelcomeScreenMode) newProjectView :: NewProjectModel -> markup Modal (Event NewProjectMode) timelineView :: TimelineViewModel -> markup TopWindow (Event TimelineMode) libraryView :: SelectAssetsModel mediaType -> markup Modal (Event LibraryMode) importView :: ImportFileModel -> markup Modal (Event ImportMode)
9a4c812250b0d7acc2f2a8bb4d076d9b0ef8cff75cd595eca13a50b19e5dcb4c
launchdarkly/haskell-server-sdk
Store.hs
-- | This module contains details for external store implementations. module LaunchDarkly.Server.Store ( StoreResult , FeatureKey , FeatureNamespace , PersistentDataStore (..) , SerializedItemDescriptor (..) , serializeWithPlaceholder , byteStringToVersionedData ) where import LaunchDarkly.Server.Store.Internal
null
https://raw.githubusercontent.com/launchdarkly/haskell-server-sdk/b8642084591733e620dfc5c1598409be7cc40a63/src/LaunchDarkly/Server/Store.hs
haskell
| This module contains details for external store implementations.
module LaunchDarkly.Server.Store ( StoreResult , FeatureKey , FeatureNamespace , PersistentDataStore (..) , SerializedItemDescriptor (..) , serializeWithPlaceholder , byteStringToVersionedData ) where import LaunchDarkly.Server.Store.Internal
1f6e05311d8e42e7dcbae7fda909fba707c7161b8b7b031b1d31ba26a094ef26
racket/racket7
liberal-def-ctx.rkt
#lang racket/base (provide prop:liberal-define-context (rename-out [has-liberal-define-context-property? liberal-define-context?]) make-liberal-define-context) (define-values (prop:liberal-define-context has-liberal-define-context-property? liberal-define-context-value) (make-struct-type-property 'liberal-define-context)) (struct liberal-define-context () #:transparent #:property prop:liberal-define-context #t #:constructor-name make-liberal-define-context)
null
https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/src/expander/expand/liberal-def-ctx.rkt
racket
#lang racket/base (provide prop:liberal-define-context (rename-out [has-liberal-define-context-property? liberal-define-context?]) make-liberal-define-context) (define-values (prop:liberal-define-context has-liberal-define-context-property? liberal-define-context-value) (make-struct-type-property 'liberal-define-context)) (struct liberal-define-context () #:transparent #:property prop:liberal-define-context #t #:constructor-name make-liberal-define-context)
f880c7eaa7a90c27035269fda876ef46247984cbc620cacc9ac9f9acb9be2976
Tclv/HaskellBook
LookUps.hs
module LookUps where import Control.Applicative import Data.List (elemIndex) 1 . added :: Maybe Integer added = fmap (+3) (lookup 3 $ zip [1, 2, 3] [4, 5, 6]) 2 . y :: Maybe Integer y = lookup 3 $ zip [1, 2, 3] [4, 5, 6] z :: Maybe Integer z = lookup 2 $ zip [1, 2, 3] [4, 5, 6] tupled :: Maybe (Integer, Integer) tupled = (,) <$> y <*> z 3 . x3 :: Maybe Int x3 = elemIndex 3 [1 .. 5] y3 :: Maybe Int y3 = elemIndex 4 [1 .. 5] max' :: Int -> Int -> Int max' = max maxed :: Maybe Int maxed = max' <$> x3 <*> y3 4 . xs, ys :: [Integer] xs = [1, 2, 3] ys = [4, 5, 6] x4 :: Maybe Integer x4 = lookup 3 $ zip xs ys y4 :: Maybe Integer y4 = lookup 2 $ zip xs ys summed :: Maybe Integer summed = fmap sum $ (,) <$> x4 <*> y4
null
https://raw.githubusercontent.com/Tclv/HaskellBook/78eaa5c67579526b0f00f85a10be3156bc304c14/ch17/LookUps.hs
haskell
module LookUps where import Control.Applicative import Data.List (elemIndex) 1 . added :: Maybe Integer added = fmap (+3) (lookup 3 $ zip [1, 2, 3] [4, 5, 6]) 2 . y :: Maybe Integer y = lookup 3 $ zip [1, 2, 3] [4, 5, 6] z :: Maybe Integer z = lookup 2 $ zip [1, 2, 3] [4, 5, 6] tupled :: Maybe (Integer, Integer) tupled = (,) <$> y <*> z 3 . x3 :: Maybe Int x3 = elemIndex 3 [1 .. 5] y3 :: Maybe Int y3 = elemIndex 4 [1 .. 5] max' :: Int -> Int -> Int max' = max maxed :: Maybe Int maxed = max' <$> x3 <*> y3 4 . xs, ys :: [Integer] xs = [1, 2, 3] ys = [4, 5, 6] x4 :: Maybe Integer x4 = lookup 3 $ zip xs ys y4 :: Maybe Integer y4 = lookup 2 $ zip xs ys summed :: Maybe Integer summed = fmap sum $ (,) <$> x4 <*> y4
f9626806335623b801d9d4da7b32627fe6d6fcaaae3b690e3aa0c79d6f31a507
hamler-lang/hamler
Error.erl
%%--------------------------------------------------------------------------- %% | %% Module : Error Copyright : ( c ) 2020 - 2021 EMQ Technologies Co. , Ltd. %% License : BSD-style (see the LICENSE file) %% Maintainer : , , %% Stability : experimental %% Portability : portable %% %% The Error FFI module. %% %%--------------------------------------------------------------------------- -module('Error'). -include("../Foreign.hrl"). -export([showErrorImpl/1]). -export([ throwException/1 , catchException/2 , bracket/3 , bracketOnError/3 , finally/2 , onException/2 ]). showErrorImpl(Error) -> lists:flatten(io_lib:format("~p", [Error])). throwException(Ex) -> ?IO(throw(Ex)). catchException(X, Y) -> try X() of _Z -> ?IO(_Z) catch throw:_Throw -> Y(_Throw); error:_Error -> Y(_Error); exit:_Exit -> Y(_Exit) end. bracket(Before, After, Thing) -> Resource = ?RunIO(Before), try ?EvalIO(Thing(Resource)) catch _:_ -> ?EvalIO(After(Resource)) after ?EvalIO(After(Resource)) end. bracketOnError(Before, After, Thing) -> Resource = ?RunIO(Before), try ?EvalIO(Thing(Resource)) catch _:_ -> ?EvalIO(After(Resource)) end. finally(First, Second) -> try ?EvalIO(First) catch _:_ -> ?EvalIO(Second) after ?EvalIO(Second) end. onException(First, Second) -> try ?EvalIO(First) catch _:_ -> ?EvalIO(Second) end.
null
https://raw.githubusercontent.com/hamler-lang/hamler/df22edd4d7f2ded1bdb8863f0e075e0e1e35a905/lib/System/Error.erl
erlang
--------------------------------------------------------------------------- | Module : Error License : BSD-style (see the LICENSE file) Stability : experimental Portability : portable The Error FFI module. ---------------------------------------------------------------------------
Copyright : ( c ) 2020 - 2021 EMQ Technologies Co. , Ltd. Maintainer : , , -module('Error'). -include("../Foreign.hrl"). -export([showErrorImpl/1]). -export([ throwException/1 , catchException/2 , bracket/3 , bracketOnError/3 , finally/2 , onException/2 ]). showErrorImpl(Error) -> lists:flatten(io_lib:format("~p", [Error])). throwException(Ex) -> ?IO(throw(Ex)). catchException(X, Y) -> try X() of _Z -> ?IO(_Z) catch throw:_Throw -> Y(_Throw); error:_Error -> Y(_Error); exit:_Exit -> Y(_Exit) end. bracket(Before, After, Thing) -> Resource = ?RunIO(Before), try ?EvalIO(Thing(Resource)) catch _:_ -> ?EvalIO(After(Resource)) after ?EvalIO(After(Resource)) end. bracketOnError(Before, After, Thing) -> Resource = ?RunIO(Before), try ?EvalIO(Thing(Resource)) catch _:_ -> ?EvalIO(After(Resource)) end. finally(First, Second) -> try ?EvalIO(First) catch _:_ -> ?EvalIO(Second) after ?EvalIO(Second) end. onException(First, Second) -> try ?EvalIO(First) catch _:_ -> ?EvalIO(Second) end.
ae1cc7675182bcb768755f48d600c58644218c0579362b84e2122fb529258f31
TrustInSoft/tis-interpreter
project_skeleton.mli
(**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* 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 . (* *) (* It 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. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) * This module should not be used outside of the Project library . @since Carbon-20101201 @since Carbon-20101201 *) (* ************************************************************************** *) * { 2 Logging machinery } (* ************************************************************************** *) (** @since Carbon-20101201 *) module Output : sig include Log.Messages val dkey: Log.category (** @since Fluorine-20130401 *) end (* ************************************************************************** *) * { 2 Type declaration } (* ************************************************************************** *) type t = private { pid: int; mutable name: string; mutable unique_name: string } (** @since Carbon-20101201 @plugin development guide *) type project = t (** @since Carbon-20101201 *) (* ************************************************************************** *) (** {2 Constructor} *) (* ************************************************************************** *) val dummy: t (** @since Carbon-20101201 *) (** @since Carbon-20101201 *) module Make_setter(X: sig val mem: string -> bool end) : sig val make_unique_name: string -> string * @return a fresh name from the given string according to [ X.mem ] . @since @since Nitrogen-20111001 *) val make: string -> t (** @since Carbon-20101201 *) val set_name: t -> string -> unit (** @since Carbon-20101201 *) end (* Local Variables: compile-command: "make -C ../../.." End: *)
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/libraries/project/project_skeleton.mli
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It 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. ************************************************************************ ************************************************************************** ************************************************************************** * @since Carbon-20101201 * @since Fluorine-20130401 ************************************************************************** ************************************************************************** * @since Carbon-20101201 @plugin development guide * @since Carbon-20101201 ************************************************************************** * {2 Constructor} ************************************************************************** * @since Carbon-20101201 * @since Carbon-20101201 * @since Carbon-20101201 * @since Carbon-20101201 Local Variables: compile-command: "make -C ../../.." End:
This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . * This module should not be used outside of the Project library . @since Carbon-20101201 @since Carbon-20101201 *) * { 2 Logging machinery } module Output : sig include Log.Messages val dkey: Log.category end * { 2 Type declaration } type t = private { pid: int; mutable name: string; mutable unique_name: string } type project = t val dummy: t module Make_setter(X: sig val mem: string -> bool end) : sig val make_unique_name: string -> string * @return a fresh name from the given string according to [ X.mem ] . @since @since Nitrogen-20111001 *) val make: string -> t val set_name: t -> string -> unit end
f46c81cb08257d44bf742980a616289178b221f910e7526805d0d4f1979b8c4a
harpocrates/language-rust
Literals.hs
| Module : Language . Rust . . Literals Description : Parsing literals Copyright : ( c ) , 2017 - 2018 License : BSD - style Maintainer : Stability : experimental Portability : portable Functions for parsing literals from valid literal tokens . Note the functions in this module fail badly is fed invalid ' LitTok 's ; it is expected their input is coming from and is correct . Module : Language.Rust.Parser.Literals Description : Parsing literals Copyright : (c) Alec Theriault, 2017-2018 License : BSD-style Maintainer : Stability : experimental Portability : portable Functions for parsing literals from valid literal tokens. Note the functions in this module fail badly is fed invalid 'LitTok's; it is expected their input is coming from Alex and is correct. -} module Language.Rust.Parser.Literals ( translateLit ) where import Language.Rust.Syntax.Token ( LitTok(..) ) import Language.Rust.Syntax.AST ( IntRep(..), Lit(..), StrStyle(..), Suffix(..) ) import Data.Char ( chr, digitToInt, ord, isHexDigit, isSpace ) import Data.List ( unfoldr ) import Data.Maybe ( fromMaybe ) import Data.Word ( Word8 ) import Text.Read ( readMaybe ) | Parse a valid ' LitTok ' into a ' Lit ' . translateLit :: LitTok -> Suffix -> a -> Lit a translateLit (ByteTok s) = Byte (unescapeByte' s) translateLit (CharTok s) = Char (unescapeChar' s) translateLit (FloatTok s) = Float (unescapeFloat s) translateLit (StrTok s) = Str (unfoldr (unescapeChar True) s) Cooked translateLit (StrRawTok s n) = Str s (Raw n) translateLit (ByteStrTok s) = ByteStr (unfoldr (unescapeByte True) s) Cooked translateLit (ByteStrRawTok s n) = ByteStr (map (fromIntegral . ord) s) (Raw n) translateLit (IntegerTok s) = \suf -> case (suf, unescapeInteger s) of (F32, (Dec, n)) -> Float (fromInteger n) F32 (F64, (Dec, n)) -> Float (fromInteger n) F64 (_, (rep, n)) -> Int rep n suf | Given a string of characters read from a Rust source , extract the next underlying char taking -- into account escapes and unicode. unescapeChar :: Bool -- ^ multi-line strings allowed -> String -- ^ input string -> Maybe (Char, String) unescapeChar multiline ('\\':c:cs) = case c of 'n' -> pure ('\n', cs) 'r' -> pure ('\r', cs) 't' -> pure ('\t', cs) '\\' -> pure ('\\', cs) '\'' -> pure ('\'', cs) '"' -> pure ('"', cs) '0' -> pure ('\0', cs) 'x' -> do (h,cs') <- readHex 2 cs; pure (chr h, cs') 'X' -> do (h,cs') <- readHex 2 cs; pure (chr h, cs') 'U' -> do (h,cs') <- readHex 8 cs; pure (chr h, cs') 'u' -> case cs of '{':x1:'}':cs' -> do (h,_) <- readHex 1 [x1]; pure (chr h, cs') '{':x1:x2:'}':cs' -> do (h,_) <- readHex 2 [x1,x2]; pure (chr h, cs') '{':x1:x2:x3:'}':cs' -> do (h,_) <- readHex 3 [x1,x2,x3]; pure (chr h, cs') '{':x1:x2:x3:x4:'}':cs' -> do (h,_) <- readHex 4 [x1,x2,x3,x4]; pure (chr h, cs') '{':x1:x2:x3:x4:x5:'}':cs' -> do (h,_) <- readHex 5 [x1,x2,x3,x4,x5]; pure (chr h, cs') '{':x1:x2:x3:x4:x5:x6:'}':cs' -> do (h,_) <- readHex 6 [x1,x2,x3,x4,x5,x6]; pure (chr h, cs') _ -> do (h,cs') <- readHex 4 cs; pure (chr h, cs') '\n' | multiline -> unescapeChar multiline $ dropWhile isSpace cs _ -> error "unescape char: bad escape sequence" unescapeChar _ (c:cs) = Just (c, cs) unescapeChar _ [] = fail "unescape char: empty string" | Given a string of characters read from a Rust source , extract the next underlying byte taking -- into account escapes. unescapeByte :: Bool -- ^ multi-line strings allowed -> String -- ^ input string -> Maybe (Word8, String) unescapeByte multiline ('\\':c:cs) = case c of 'n' -> pure (toEnum $ fromEnum '\n', cs) 'r' -> pure (toEnum $ fromEnum '\r', cs) 't' -> pure (toEnum $ fromEnum '\t', cs) '\\' -> pure (toEnum $ fromEnum '\\', cs) '\'' -> pure (toEnum $ fromEnum '\'', cs) '"' -> pure (toEnum $ fromEnum '"', cs) '0' -> pure (toEnum $ fromEnum '\0', cs) 'x' -> do (h,cs') <- readHex 2 cs; pure (h, cs') 'X' -> do (h,cs') <- readHex 2 cs; pure (h, cs') '\n' | multiline -> unescapeByte multiline $ dropWhile isSpace cs _ -> error "unescape byte: bad escape sequence" unescapeByte _ (c:cs) = Just (toEnum $ fromEnum c, cs) unescapeByte _ [] = fail "unescape byte: empty string" | Given a string representation of a character , parse it into a character unescapeChar' :: String -> Char unescapeChar' s = case unescapeChar False s of Just (c, "") -> c _ -> error "unescape char: bad character literal" | Given a string representation of a byte , parse it into a byte unescapeByte' :: String -> Word8 unescapeByte' s = case unescapeByte False s of Just (w8, "") -> w8 _ -> error "unescape byte: bad byte literal" | Given a string representation of an integer , parse it into a number unescapeInteger :: Num a => String -> (IntRep,a) unescapeInteger ('0':'b':cs@(_:_)) | all (`elem` "_01") cs = (Bin, numBase 2 (filter (/= '_') cs)) unescapeInteger ('0':'o':cs@(_:_)) | all (`elem` "_01234567") cs = (Oct, numBase 8 (filter (/= '_') cs)) unescapeInteger ('0':'x':cs@(_:_)) | all (`elem` "_0123456789abcdefABCDEF") cs = (Hex, numBase 16 (filter (/= '_') cs)) unescapeInteger cs@(_:_) | all (`elem` "_0123456789") cs = (Dec, numBase 10 (filter (/= '_') cs)) unescapeInteger _ = error "unescape integer: bad decimal literal" | Given a string representation of a float , parse it into a float . -- NOTE: this is a bit hacky. Eventually, we might not do this and change the internal -- representation of a float to a string (what language-c has opted to do). unescapeFloat :: String -> Double unescapeFloat cs = fromMaybe (error $ "unescape float: cannot parse float " ++ cs') (readMaybe cs') where cs' = filter (/= '_') (if last cs == '.' then cs ++ "0" else cs) -- | Try to read a hexadecimal number of the specified length off of the front of the string -- provided. If there are not enough characters to do this, or the characters don't fall in the -- right range, this fails with 'Nothing'. readHex :: Num a => Int -> String -> Maybe (a, String) readHex n cs = let digits = take n cs in if length digits == n && all isHexDigit digits then Just (numBase 16 digits, drop n cs) else Nothing -- | Convert a list of characters to the number they represent. numBase :: Num a => a -> String -> a numBase b = foldl (\n x -> fromIntegral (digitToInt x) + b * n) 0
null
https://raw.githubusercontent.com/harpocrates/language-rust/9d509c450d009cc99f1180b3f2f30247dfb1cfce/src/Language/Rust/Parser/Literals.hs
haskell
into account escapes and unicode. ^ multi-line strings allowed ^ input string into account escapes. ^ multi-line strings allowed ^ input string NOTE: this is a bit hacky. Eventually, we might not do this and change the internal representation of a float to a string (what language-c has opted to do). | Try to read a hexadecimal number of the specified length off of the front of the string provided. If there are not enough characters to do this, or the characters don't fall in the right range, this fails with 'Nothing'. | Convert a list of characters to the number they represent.
| Module : Language . Rust . . Literals Description : Parsing literals Copyright : ( c ) , 2017 - 2018 License : BSD - style Maintainer : Stability : experimental Portability : portable Functions for parsing literals from valid literal tokens . Note the functions in this module fail badly is fed invalid ' LitTok 's ; it is expected their input is coming from and is correct . Module : Language.Rust.Parser.Literals Description : Parsing literals Copyright : (c) Alec Theriault, 2017-2018 License : BSD-style Maintainer : Stability : experimental Portability : portable Functions for parsing literals from valid literal tokens. Note the functions in this module fail badly is fed invalid 'LitTok's; it is expected their input is coming from Alex and is correct. -} module Language.Rust.Parser.Literals ( translateLit ) where import Language.Rust.Syntax.Token ( LitTok(..) ) import Language.Rust.Syntax.AST ( IntRep(..), Lit(..), StrStyle(..), Suffix(..) ) import Data.Char ( chr, digitToInt, ord, isHexDigit, isSpace ) import Data.List ( unfoldr ) import Data.Maybe ( fromMaybe ) import Data.Word ( Word8 ) import Text.Read ( readMaybe ) | Parse a valid ' LitTok ' into a ' Lit ' . translateLit :: LitTok -> Suffix -> a -> Lit a translateLit (ByteTok s) = Byte (unescapeByte' s) translateLit (CharTok s) = Char (unescapeChar' s) translateLit (FloatTok s) = Float (unescapeFloat s) translateLit (StrTok s) = Str (unfoldr (unescapeChar True) s) Cooked translateLit (StrRawTok s n) = Str s (Raw n) translateLit (ByteStrTok s) = ByteStr (unfoldr (unescapeByte True) s) Cooked translateLit (ByteStrRawTok s n) = ByteStr (map (fromIntegral . ord) s) (Raw n) translateLit (IntegerTok s) = \suf -> case (suf, unescapeInteger s) of (F32, (Dec, n)) -> Float (fromInteger n) F32 (F64, (Dec, n)) -> Float (fromInteger n) F64 (_, (rep, n)) -> Int rep n suf | Given a string of characters read from a Rust source , extract the next underlying char taking -> Maybe (Char, String) unescapeChar multiline ('\\':c:cs) = case c of 'n' -> pure ('\n', cs) 'r' -> pure ('\r', cs) 't' -> pure ('\t', cs) '\\' -> pure ('\\', cs) '\'' -> pure ('\'', cs) '"' -> pure ('"', cs) '0' -> pure ('\0', cs) 'x' -> do (h,cs') <- readHex 2 cs; pure (chr h, cs') 'X' -> do (h,cs') <- readHex 2 cs; pure (chr h, cs') 'U' -> do (h,cs') <- readHex 8 cs; pure (chr h, cs') 'u' -> case cs of '{':x1:'}':cs' -> do (h,_) <- readHex 1 [x1]; pure (chr h, cs') '{':x1:x2:'}':cs' -> do (h,_) <- readHex 2 [x1,x2]; pure (chr h, cs') '{':x1:x2:x3:'}':cs' -> do (h,_) <- readHex 3 [x1,x2,x3]; pure (chr h, cs') '{':x1:x2:x3:x4:'}':cs' -> do (h,_) <- readHex 4 [x1,x2,x3,x4]; pure (chr h, cs') '{':x1:x2:x3:x4:x5:'}':cs' -> do (h,_) <- readHex 5 [x1,x2,x3,x4,x5]; pure (chr h, cs') '{':x1:x2:x3:x4:x5:x6:'}':cs' -> do (h,_) <- readHex 6 [x1,x2,x3,x4,x5,x6]; pure (chr h, cs') _ -> do (h,cs') <- readHex 4 cs; pure (chr h, cs') '\n' | multiline -> unescapeChar multiline $ dropWhile isSpace cs _ -> error "unescape char: bad escape sequence" unescapeChar _ (c:cs) = Just (c, cs) unescapeChar _ [] = fail "unescape char: empty string" | Given a string of characters read from a Rust source , extract the next underlying byte taking -> Maybe (Word8, String) unescapeByte multiline ('\\':c:cs) = case c of 'n' -> pure (toEnum $ fromEnum '\n', cs) 'r' -> pure (toEnum $ fromEnum '\r', cs) 't' -> pure (toEnum $ fromEnum '\t', cs) '\\' -> pure (toEnum $ fromEnum '\\', cs) '\'' -> pure (toEnum $ fromEnum '\'', cs) '"' -> pure (toEnum $ fromEnum '"', cs) '0' -> pure (toEnum $ fromEnum '\0', cs) 'x' -> do (h,cs') <- readHex 2 cs; pure (h, cs') 'X' -> do (h,cs') <- readHex 2 cs; pure (h, cs') '\n' | multiline -> unescapeByte multiline $ dropWhile isSpace cs _ -> error "unescape byte: bad escape sequence" unescapeByte _ (c:cs) = Just (toEnum $ fromEnum c, cs) unescapeByte _ [] = fail "unescape byte: empty string" | Given a string representation of a character , parse it into a character unescapeChar' :: String -> Char unescapeChar' s = case unescapeChar False s of Just (c, "") -> c _ -> error "unescape char: bad character literal" | Given a string representation of a byte , parse it into a byte unescapeByte' :: String -> Word8 unescapeByte' s = case unescapeByte False s of Just (w8, "") -> w8 _ -> error "unescape byte: bad byte literal" | Given a string representation of an integer , parse it into a number unescapeInteger :: Num a => String -> (IntRep,a) unescapeInteger ('0':'b':cs@(_:_)) | all (`elem` "_01") cs = (Bin, numBase 2 (filter (/= '_') cs)) unescapeInteger ('0':'o':cs@(_:_)) | all (`elem` "_01234567") cs = (Oct, numBase 8 (filter (/= '_') cs)) unescapeInteger ('0':'x':cs@(_:_)) | all (`elem` "_0123456789abcdefABCDEF") cs = (Hex, numBase 16 (filter (/= '_') cs)) unescapeInteger cs@(_:_) | all (`elem` "_0123456789") cs = (Dec, numBase 10 (filter (/= '_') cs)) unescapeInteger _ = error "unescape integer: bad decimal literal" | Given a string representation of a float , parse it into a float . unescapeFloat :: String -> Double unescapeFloat cs = fromMaybe (error $ "unescape float: cannot parse float " ++ cs') (readMaybe cs') where cs' = filter (/= '_') (if last cs == '.' then cs ++ "0" else cs) readHex :: Num a => Int -> String -> Maybe (a, String) readHex n cs = let digits = take n cs in if length digits == n && all isHexDigit digits then Just (numBase 16 digits, drop n cs) else Nothing numBase :: Num a => a -> String -> a numBase b = foldl (\n x -> fromIntegral (digitToInt x) + b * n) 0
c73ebe243b6f7299a7a870388079a8fe41f1924a65c6d2f42e4da97cf6bafddb
Shadytel/osmo_ss7
isup_codec.erl
% ITU-T Q.76x ISUPcoding / decoding ( C ) 2011 by < > % % All Rights Reserved % % 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 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 </>. % Additional Permission under GNU AGPL version 3 section 7 : % If you modify this Program , or any covered work , by linking or combining it with runtime libraries of Erlang / OTP as released by Ericsson on ( or a modified version of these % libraries), containing parts covered by the terms of the Erlang Public % License (), the licensors of this Program grant you additional permission to convey the resulting work without the need to license the runtime libraries of Erlang / OTP under the GNU Affero General Public License . Corresponding Source for a % non-source form of such a combination shall include the source code for the parts of the runtime libraries of Erlang / OTP used as well as % that of the covered work. -module(isup_codec). -author('Harald Welte <>'). -include("isup.hrl"). -export([parse_isup_msg/1, encode_isup_msg/1, parse_isup_party/2, encode_isup_party/1]). -compile(export_all). -compile({parse_transform, exprecs}). -export_records([party_number, isup_msg]). parse_isup_party(<<>>, OddEven, DigitList) -> % in case of odd number of digits, we need to cut the last case OddEven of 1 -> lists:sublist(DigitList, length(DigitList)-1); 0 -> DigitList end; parse_isup_party(BcdBin, OddEven, DigitList) -> <<Second:4, First:4, Remain/binary>> = BcdBin, NewDigits = [First, Second], parse_isup_party(Remain, OddEven, DigitList ++ NewDigits). parse_isup_party(BinBcd, OddEven) when is_binary(BinBcd) -> parse_isup_party(BinBcd, OddEven, []). % parse a single option parse_isup_opt(OptType = ?ISUP_PAR_CALLED_P_NUM, _OptLen, Content) -> % C.3.7 Called Party Number <<OddEven:1, Nature:7, Inn:1, NumPlan:3, 0:4, Remain/binary>> = Content, PhoneNum = parse_isup_party(Remain, OddEven), {OptType, #party_number{nature_of_addr_ind = Nature, internal_net_num = Inn, numbering_plan = NumPlan, phone_number = PhoneNum}}; parse_isup_opt(OptType = ?ISUP_PAR_CALLING_P_NUM, _OptLen, Content) -> % C.3.8 Calling Party Number <<OddEven:1, Nature:7, Ni:1, NumPlan:3, PresRestr:2, Screen:2, Remain/binary>> = Content, PhoneNum = parse_isup_party(Remain, OddEven), {OptType, #party_number{nature_of_addr_ind = Nature, number_incompl_ind = Ni, numbering_plan = NumPlan, present_restrict = PresRestr, screening_ind = Screen, phone_number = PhoneNum}}; parse_isup_opt(OptType = ?ISUP_PAR_CONNECTED_NUM, _OptLen, Content) -> % C.3.14 Connected Number <<OddEven:1, Nature:7, 0:1, NumPlan:3, PresRestr:2, Screen:2, Remain/binary>> = Content, PhoneNum = parse_isup_party(Remain, OddEven), {OptType, #party_number{nature_of_addr_ind = Nature, numbering_plan = NumPlan, present_restrict = PresRestr, screening_ind = Screen, phone_number = PhoneNum}}; parse_isup_opt(OptType = ?ISUP_PAR_SUBSEQ_NUM, _OptLen, Content) -> % C.3.32 Subsequent Number <<OddEven:1, 0:7, Remain/binary>> = Content, PhoneNum = parse_isup_party(Remain, OddEven), {OptType, #party_number{phone_number = PhoneNum}}; parse_isup_opt(OptType, OptLen, Content) -> {OptType, {OptLen, Content}}. % parse a Binary into a list of options parse_isup_opts(<<>>, OptList) -> % empty list OptList; parse_isup_opts(<<0>>, OptList) -> % end of options OptList; parse_isup_opts(OptBin, OptList) when is_binary(OptBin) -> <<OptType:8, OptLen:8, Content:OptLen/binary, Remain/binary>> = OptBin, NewOpt = parse_isup_opt(OptType, OptLen, Content), parse_isup_opts(Remain, OptList ++ [NewOpt]). parse_isup_opts(OptBin) -> parse_isup_opts(OptBin, []). Parse options preceeded by 1 byte OptPtr parse_isup_opts_ptr(OptBinPtr) -> OptPtr = binary:at(OptBinPtr, 0), case OptPtr of 0 -> []; _ -> OptBin = binary:part(OptBinPtr, OptPtr, byte_size(OptBinPtr)-OptPtr), parse_isup_opts(OptBin, []) end. References to ' Tabe C - xxx ' are to Annex C of Q.767 % Default case: no fixed and no variable parts, only options ANM , RLC , FOT parse_isup_msgt(M, Bin) when M == ?ISUP_MSGT_ANM; M == ?ISUP_MSGT_RLC; M == ?ISUP_MSGT_FOT -> parse_isup_opts_ptr(Bin); % Table C-5 Address complete parse_isup_msgt(?ISUP_MSGT_ACM, Bin) -> <<BackCallInd:16, Remain/binary>> = Bin, BciOpt = {backward_call_ind, BackCallInd}, Opts = parse_isup_opts_ptr(Remain), [BciOpt|Opts]; % Table C-7 Call progress parse_isup_msgt(?ISUP_MSGT_CPG, Bin) -> <<EventInf:8, Remain/binary>> = Bin, BciOpt = {event_info, EventInf}, Opts = parse_isup_opts_ptr(Remain), [BciOpt|Opts]; % Table C-9 Circuit group reset acknowledgement parse_isup_msgt(?ISUP_MSGT_GRA, Bin) -> % V: Range and status <<PtrVar:8, _Remain/binary>> = Bin, RangStsLen = binary:at(Bin, PtrVar), RangeStatus = binary:part(Bin, PtrVar+1, RangStsLen), RangeStsTuple = {?ISUP_PAR_RANGE_AND_STATUS, {RangStsLen, RangeStatus}}, [RangeStsTuple]; % Table C-11 Connect parse_isup_msgt(?ISUP_MSGT_CON, Bin) -> <<BackCallInd:16, Remain/binary>> = Bin, BciOpt = {backward_call_ind, BackCallInd}, Opts = parse_isup_opts_ptr(Remain), [BciOpt|Opts]; % Table C-12 Continuity parse_isup_msgt(?ISUP_MSGT_COT, Bin) -> <<ContInd:8>> = Bin, [{continuity_ind, ContInd}]; % Table C-16 Initial address parse_isup_msgt(?ISUP_MSGT_IAM, Bin) -> <<CINat:8, FwCallInd:16/big, CallingCat:8, TransmReq:8, VarAndOpt/binary>> = Bin, FixedOpts = [{conn_ind_nature, CINat}, {fw_call_ind, FwCallInd}, {calling_cat, CallingCat}, {transm_medium_req, TransmReq}], <<PtrVar:8, PtrOpt:8, _/binary>> = VarAndOpt, % V: Called Party Number CalledPartyLen = binary:at(VarAndOpt, PtrVar), CalledParty = binary:part(VarAndOpt, PtrVar+1, CalledPartyLen), VarOpts = [parse_isup_opt(?ISUP_PAR_CALLED_P_NUM, CalledPartyLen, CalledParty)], % Optional part case PtrOpt of 0 -> Opts = []; _ -> Remain = binary:part(VarAndOpt, 1 + PtrOpt, byte_size(VarAndOpt)-(1+PtrOpt)), Opts = parse_isup_opts(Remain) end, FixedOpts ++ VarOpts ++ Opts; % Table C-17 Release Table 26 / Q.763 : Confusion parse_isup_msgt(M, VarAndOpt) when M == ?ISUP_MSGT_REL; M == ?ISUP_MSGT_CFN -> <<PtrVar:8, PtrOpt:8, _/binary>> = VarAndOpt, % V: Cause indicators CauseIndLen = binary:at(VarAndOpt, PtrVar), CauseInd = binary:part(VarAndOpt, PtrVar+1, CauseIndLen), VarOpts = [{?ISUP_PAR_CAUSE_IND, {CauseIndLen, CauseInd}}], case PtrOpt of 0 -> Opts = []; _ -> Remain = binary:part(VarAndOpt, 1 + PtrOpt, byte_size(VarAndOpt)-(1+PtrOpt)), Opts = parse_isup_opts(Remain) end, VarOpts ++ Opts; % Table C-19 Subsequent address parse_isup_msgt(?ISUP_MSGT_SAM, VarAndOpt) -> <<PtrVar:8, PtrOpt:8, _/binary>> = VarAndOpt, % V: Subsequent number SubseqNumLen = binary:at(VarAndOpt, PtrVar), SubsetNum = binary:part(VarAndOpt, PtrVar+1, SubseqNumLen), VarOpts = [{?ISUP_PAR_SUBSEQ_NUM, {SubseqNumLen, SubsetNum}}], Remain = binary:part(VarAndOpt, 1 + PtrOpt, byte_size(VarAndOpt)-(1+PtrOpt)), Opts = parse_isup_opts(Remain), VarOpts ++ Opts; Table C-21 Suspend , Resume parse_isup_msgt(Msgt, Bin) when Msgt == ?ISUP_MSGT_RES; Msgt == ?ISUP_MSGT_SUS -> <<SuspResInd:8, Remain/binary>> = Bin, FixedOpts = [{susp_res_ind, SuspResInd}], Opts = parse_isup_opts_ptr(Remain), FixedOpts ++ Opts; Table C-23 parse_isup_msgt(M, <<>>) when M == ?ISUP_MSGT_BLO; M == ?ISUP_MSGT_BLA; M == ?ISUP_MSGT_CCR; M == ?ISUP_MSGT_RSC; M == ?ISUP_MSGT_UBL; M == ?ISUP_MSGT_UBA -> []; Table 39 / Q.763 messages for national use , fixed length 1 byte msgtype parse_isup_msgt(M, <<>>) when M == ?ISUP_MSGT_LPA; M == ?ISUP_MSGT_OLM; M == ?ISUP_MSGT_UCIC -> []; Table C-25 parse_isup_msgt(M, Bin) when M == ?ISUP_MSGT_CGB; M == ?ISUP_MSGT_CGBA; M == ?ISUP_MSGT_CGU; M == ?ISUP_MSGT_CGUA -> <<CGMsgt:8, PtrVar:8, VarBin/binary>> = Bin, FixedOpts = [{cg_supv_msgt, CGMsgt}], % V: Range and status RangStsLen = binary:at(VarBin, PtrVar-1), RangeStatus = binary:part(VarBin, PtrVar, RangStsLen), VarOpts = [{?ISUP_PAR_RANGE_AND_STATUS, {RangStsLen, RangeStatus}}], FixedOpts ++ VarOpts; Table C-26 Circuit group reset parse_isup_msgt(?ISUP_MSGT_GRS, Bin) -> <<PtrVar:8, _VarBin/binary>> = Bin, % V: Range without status RangeLen = binary:at(Bin, PtrVar), Range = binary:part(Bin, PtrVar+1, RangeLen), [{?ISUP_PAR_RANGE_AND_STATUS, {RangeLen, Range}}]. parse_isup_msg(DataBin) when is_binary(DataBin) -> <<Cic:12/little, 0:4, MsgType:8, Remain/binary>> = DataBin, Opts = parse_isup_msgt(MsgType, Remain), #isup_msg{cic = Cic, msg_type = MsgType, parameters = Opts}. encode a phone number from a list of digits into the BCD binary sequence encode_isup_party(BcdInt) when is_integer(BcdInt) -> BcdList = osmo_util:int2digit_list(BcdInt), encode_isup_party(BcdList); encode_isup_party(BcdList) when is_list(BcdList) -> encode_isup_party(BcdList, <<>>, length(BcdList)). encode_isup_party([], Bin, NumDigits) -> case NumDigits rem 2 of 1 -> {Bin, 1}; 0 -> {Bin, 0} end; encode_isup_party([First,Second|BcdList], Bin, NumDigits) -> encode_isup_party(BcdList, <<Bin/binary, Second:4, First:4>>, NumDigits); encode_isup_party([Last], Bin, NumDigits) -> encode_isup_party([], <<Bin/binary, 0:4, Last:4>>, NumDigits). % encode a single option encode_isup_par(?ISUP_PAR_CALLED_P_NUM, #party_number{nature_of_addr_ind = Nature, internal_net_num = Inn, numbering_plan = NumPlan, phone_number= PhoneNum}) -> % C.3.7 Called Party Number {PhoneBin, OddEven} = encode_isup_party(PhoneNum), <<OddEven:1, Nature:7, Inn:1, NumPlan:3, 0:4, PhoneBin/binary>>; encode_isup_par(?ISUP_PAR_CALLING_P_NUM, #party_number{nature_of_addr_ind = Nature, number_incompl_ind = Ni, numbering_plan = NumPlan, present_restrict = PresRestr, screening_ind = Screen, phone_number= PhoneNum}) -> % C.3.8 Calling Party Number {PhoneBin, OddEven} = encode_isup_party(PhoneNum), <<OddEven:1, Nature:7, Ni:1, NumPlan:3, PresRestr:2, Screen:2, PhoneBin/binary>>; encode_isup_par(?ISUP_PAR_CONNECTED_NUM, #party_number{nature_of_addr_ind = Nature, numbering_plan = NumPlan, present_restrict = PresRestr, screening_ind = Screen, phone_number = PhoneNum}) -> % C.3.14 Connected Number {PhoneBin, OddEven} = encode_isup_party(PhoneNum), <<OddEven:1, Nature:7, 0:1, NumPlan:3, PresRestr:2, Screen:2, PhoneBin/binary>>; encode_isup_par(?ISUP_PAR_SUBSEQ_NUM, #party_number{phone_number = PhoneNum}) -> % C.3.32 Subsequent Number {PhoneBin, OddEven} = encode_isup_party(PhoneNum), <<OddEven:1, 0:7, PhoneBin/binary>>; encode_isup_par(Atom, _More) when is_atom(Atom) -> <<>>; encode_isup_par(OptNum, {OptLen, Binary}) when is_binary(Binary), is_integer(OptNum), is_integer(OptLen) -> Binary. % encode a single OPTIONAL parameter (TLV type), skip all others encode_isup_optpar(ParNum, _ParBody) when is_atom(ParNum) -> <<>>; encode_isup_optpar(ParNum, ParBody) -> ParBin = encode_isup_par(ParNum, ParBody), ParLen = byte_size(ParBin), <<ParNum:8, ParLen:8, ParBin/binary>>. % recursive function to encode all optional parameters encode_isup_opts([], OutBin) -> % terminate with end-of-options, but only if we have options case OutBin of <<>> -> OutBin; _ -> <<OutBin/binary, 0:8>> end; encode_isup_opts([Opt|OptPropList], OutBin) -> {OptType, OptBody} = Opt, OptBin = encode_isup_optpar(OptType, OptBody), encode_isup_opts(OptPropList, <<OutBin/binary, OptBin/binary>>). encode_isup_opts(OptPropList) -> encode_isup_opts(OptPropList, <<>>). encode_isup_hdr(#isup_msg{msg_type = MsgType, cic = Cic}) -> <<Cic:12/little, 0:4, MsgType:8>>. % Default case: no fixed and no variable parts, only options ANM , RLC , FOT encode_isup_msgt(M, #isup_msg{parameters = Params}) when M == ?ISUP_MSGT_ANM; M == ?ISUP_MSGT_RLC; M == ?ISUP_MSGT_FOT -> OptBin = encode_isup_opts(Params), case OptBin of <<>> -> PtrOpt = 0; _ -> PtrOpt = 1 end, <<PtrOpt:8, OptBin/binary>>; % Table C-5 Address complete encode_isup_msgt(?ISUP_MSGT_ACM, #isup_msg{parameters = Params}) -> BackCallInd = proplists:get_value(backward_call_ind, Params), OptBin = encode_isup_opts(Params), case OptBin of <<>> -> PtrOpt = 0; _ -> PtrOpt = 1 end, <<BackCallInd:16, PtrOpt:8, OptBin/binary>>; % Table C-7 Call progress encode_isup_msgt(?ISUP_MSGT_CPG, #isup_msg{parameters = Params}) -> EventInf = proplists:get_value(event_info, Params), OptBin = encode_isup_opts(Params), case OptBin of <<>> -> PtrOpt = 0; _ -> PtrOpt = 1 end, <<EventInf:8, PtrOpt:8, OptBin/binary>>; % Table C-9 Circuit group reset acknowledgement encode_isup_msgt(?ISUP_MSGT_GRA, #isup_msg{parameters = Params}) -> % V: Range and status {RangStsLen, RangeStatus} = proplists:get_value(?ISUP_PAR_RANGE_AND_STATUS, Params), <<1:8, RangStsLen:8, RangeStatus/binary>>; % Table C-11 Connect encode_isup_msgt(?ISUP_MSGT_CON, #isup_msg{parameters = Params}) -> BackCallInd = proplists:get_value(backward_call_ind, Params), OptBin = encode_isup_opts(Params), case OptBin of <<>> -> PtrOpt = 0; _ -> PtrOpt = 1 end, <<BackCallInd:16, PtrOpt:8, OptBin/binary>>; % Table C-12 Continuity encode_isup_msgt(?ISUP_MSGT_COT, #isup_msg{parameters = Params}) -> ContInd = proplists:get_value(continuity_ind, Params), <<ContInd:8>>; % Table C-16 Initial address encode_isup_msgt(?ISUP_MSGT_IAM, #isup_msg{parameters = Params}) -> % Fixed part CINat = proplists:get_value(conn_ind_nature, Params), FwCallInd = proplists:get_value(fw_call_ind, Params), CallingCat = proplists:get_value(calling_cat, Params), TransmReq = proplists:get_value(transm_medium_req, Params), one byte behind the PtrOpt FixedBin = <<CINat:8, FwCallInd:16/big, CallingCat:8, TransmReq:8>>, % V: Called Party Number CalledParty = encode_isup_par(?ISUP_PAR_CALLED_P_NUM, proplists:get_value(?ISUP_PAR_CALLED_P_NUM, Params)), CalledPartyLen = byte_size(CalledParty), % Optional part Params2 = proplists:delete(?ISUP_PAR_CALLED_P_NUM, Params), OptBin = encode_isup_opts(Params2), case OptBin of <<>> -> PtrOpt = 0; 1 byte length , 1 byte start offset end, <<FixedBin/binary, PtrVar:8, PtrOpt:8, CalledPartyLen:8, CalledParty/binary, OptBin/binary>>; % Table C-17 Release encode_isup_msgt(Msgt, #isup_msg{parameters = Params}) when Msgt == ?ISUP_MSGT_REL; Msgt == ?ISUP_MSGT_CFN -> one byte behind the PtrOpt % V: Cause indicators CauseInd = encode_isup_par(?ISUP_PAR_CAUSE_IND, proplists:get_value(?ISUP_PAR_CAUSE_IND, Params)), CauseIndLen = byte_size(CauseInd), % Optional Part Params2 = proplists:delete(?ISUP_PAR_CAUSE_IND, Params), OptBin = encode_isup_opts(Params2), case OptBin of <<>> -> PtrOpt = 0; 1 byte length , 1 byte start offset end, <<PtrVar:8, PtrOpt:8, CauseIndLen:8, CauseInd/binary, OptBin/binary>>; % Table C-19 Subsequent address encode_isup_msgt(?ISUP_MSGT_SAM, #isup_msg{parameters = Params}) -> one byte behind the PtrOpt % V: Subsequent number SubseqNum = encode_isup_par(?ISUP_PAR_SUBSEQ_NUM, proplists:get_value(?ISUP_PAR_SUBSEQ_NUM, Params)), SubseqNumLen = byte_size(SubseqNum), % Optional Part Params2 = proplists:delete(?ISUP_PAR_SUBSEQ_NUM, Params), OptBin = encode_isup_opts(Params2), case OptBin of <<>> -> PtrOpt = 0; 1 byte length , 1 byte start offset end, <<PtrVar:8, PtrOpt:8, SubseqNumLen:8, SubseqNum/binary, OptBin/binary>>; Table C-21 Suspend , Resume encode_isup_msgt(Msgt, #isup_msg{parameters = Params}) when Msgt == ?ISUP_MSGT_RES; Msgt == ?ISUP_MSGT_SUS -> SuspResInd = proplists:get_value(susp_res_ind, Params), OptBin = encode_isup_opts(Params), case OptBin of <<>> -> PtrOpt = 0; _ -> PtrOpt = 1 end, <<SuspResInd:8, PtrOpt:8, OptBin/binary>>; Table C-23 encode_isup_msgt(M, #isup_msg{}) when M == ?ISUP_MSGT_BLO; M == ?ISUP_MSGT_BLA; M == ?ISUP_MSGT_CCR; M == ?ISUP_MSGT_RSC; M == ?ISUP_MSGT_UBL; M == ?ISUP_MSGT_UBA -> <<>>; Table 39 / Q.763 ( national use ) encode_isup_msgt(M, #isup_msg{}) when M == ?ISUP_MSGT_LPA; M == ?ISUP_MSGT_OLM; M == ?ISUP_MSGT_UCIC -> <<>>; Table C-25 encode_isup_msgt(M, #isup_msg{parameters = Params}) when M == ?ISUP_MSGT_CGB; M == ?ISUP_MSGT_CGBA; M == ?ISUP_MSGT_CGU; M == ?ISUP_MSGT_CGUA -> one byte behind the PtrVar CGMsgt = proplists:get_value(cg_supv_msgt, Params), % V: Range and status {RangStsLen, RangeStatus} = proplists:get_value(?ISUP_PAR_RANGE_AND_STATUS, Params), <<CGMsgt:8, PtrVar:8, RangStsLen:8, RangeStatus/binary>>; Table C-26 Circuit group reset encode_isup_msgt(?ISUP_MSGT_GRS, #isup_msg{parameters = Params}) -> one byte behind the PtrVar {RangeLen, Range} = proplists:get_value(?ISUP_PAR_RANGE_AND_STATUS, Params), % V: Range without status <<PtrVar:8, RangeLen:8, Range/binary>>. encode_isup_msg(Msg = #isup_msg{msg_type = MsgType}) -> HdrBin = encode_isup_hdr(Msg), Remain = encode_isup_msgt(MsgType, Msg), <<HdrBin/binary, Remain/binary>>.
null
https://raw.githubusercontent.com/Shadytel/osmo_ss7/eef6ce439727436febc67692c145e07847cc4c89/src/isup_codec.erl
erlang
ITU-T Q.76x ISUPcoding / decoding All Rights Reserved This program is free software; you can redistribute it and/or modify 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. along with this program. If not, see </>. libraries), containing parts covered by the terms of the Erlang Public License (), the licensors of this non-source form of such a combination shall include the source code that of the covered work. in case of odd number of digits, we need to cut the last parse a single option C.3.7 Called Party Number C.3.8 Calling Party Number C.3.14 Connected Number C.3.32 Subsequent Number parse a Binary into a list of options empty list end of options Default case: no fixed and no variable parts, only options Table C-5 Address complete Table C-7 Call progress Table C-9 Circuit group reset acknowledgement V: Range and status Table C-11 Connect Table C-12 Continuity Table C-16 Initial address V: Called Party Number Optional part Table C-17 Release V: Cause indicators Table C-19 Subsequent address V: Subsequent number V: Range and status V: Range without status encode a single option C.3.7 Called Party Number C.3.8 Calling Party Number C.3.14 Connected Number C.3.32 Subsequent Number encode a single OPTIONAL parameter (TLV type), skip all others recursive function to encode all optional parameters terminate with end-of-options, but only if we have options Default case: no fixed and no variable parts, only options Table C-5 Address complete Table C-7 Call progress Table C-9 Circuit group reset acknowledgement V: Range and status Table C-11 Connect Table C-12 Continuity Table C-16 Initial address Fixed part V: Called Party Number Optional part Table C-17 Release V: Cause indicators Optional Part Table C-19 Subsequent address V: Subsequent number Optional Part V: Range and status V: Range without status
( C ) 2011 by < > it under the terms of the GNU Affero General Public License as published by the Free Software Foundation ; either version 3 of the You should have received a copy of the GNU Affero General Public License Additional Permission under GNU AGPL version 3 section 7 : If you modify this Program , or any covered work , by linking or combining it with runtime libraries of Erlang / OTP as released by Ericsson on ( or a modified version of these Program grant you additional permission to convey the resulting work without the need to license the runtime libraries of Erlang / OTP under the GNU Affero General Public License . Corresponding Source for a for the parts of the runtime libraries of Erlang / OTP used as well as -module(isup_codec). -author('Harald Welte <>'). -include("isup.hrl"). -export([parse_isup_msg/1, encode_isup_msg/1, parse_isup_party/2, encode_isup_party/1]). -compile(export_all). -compile({parse_transform, exprecs}). -export_records([party_number, isup_msg]). parse_isup_party(<<>>, OddEven, DigitList) -> case OddEven of 1 -> lists:sublist(DigitList, length(DigitList)-1); 0 -> DigitList end; parse_isup_party(BcdBin, OddEven, DigitList) -> <<Second:4, First:4, Remain/binary>> = BcdBin, NewDigits = [First, Second], parse_isup_party(Remain, OddEven, DigitList ++ NewDigits). parse_isup_party(BinBcd, OddEven) when is_binary(BinBcd) -> parse_isup_party(BinBcd, OddEven, []). parse_isup_opt(OptType = ?ISUP_PAR_CALLED_P_NUM, _OptLen, Content) -> <<OddEven:1, Nature:7, Inn:1, NumPlan:3, 0:4, Remain/binary>> = Content, PhoneNum = parse_isup_party(Remain, OddEven), {OptType, #party_number{nature_of_addr_ind = Nature, internal_net_num = Inn, numbering_plan = NumPlan, phone_number = PhoneNum}}; parse_isup_opt(OptType = ?ISUP_PAR_CALLING_P_NUM, _OptLen, Content) -> <<OddEven:1, Nature:7, Ni:1, NumPlan:3, PresRestr:2, Screen:2, Remain/binary>> = Content, PhoneNum = parse_isup_party(Remain, OddEven), {OptType, #party_number{nature_of_addr_ind = Nature, number_incompl_ind = Ni, numbering_plan = NumPlan, present_restrict = PresRestr, screening_ind = Screen, phone_number = PhoneNum}}; parse_isup_opt(OptType = ?ISUP_PAR_CONNECTED_NUM, _OptLen, Content) -> <<OddEven:1, Nature:7, 0:1, NumPlan:3, PresRestr:2, Screen:2, Remain/binary>> = Content, PhoneNum = parse_isup_party(Remain, OddEven), {OptType, #party_number{nature_of_addr_ind = Nature, numbering_plan = NumPlan, present_restrict = PresRestr, screening_ind = Screen, phone_number = PhoneNum}}; parse_isup_opt(OptType = ?ISUP_PAR_SUBSEQ_NUM, _OptLen, Content) -> <<OddEven:1, 0:7, Remain/binary>> = Content, PhoneNum = parse_isup_party(Remain, OddEven), {OptType, #party_number{phone_number = PhoneNum}}; parse_isup_opt(OptType, OptLen, Content) -> {OptType, {OptLen, Content}}. parse_isup_opts(<<>>, OptList) -> OptList; parse_isup_opts(<<0>>, OptList) -> OptList; parse_isup_opts(OptBin, OptList) when is_binary(OptBin) -> <<OptType:8, OptLen:8, Content:OptLen/binary, Remain/binary>> = OptBin, NewOpt = parse_isup_opt(OptType, OptLen, Content), parse_isup_opts(Remain, OptList ++ [NewOpt]). parse_isup_opts(OptBin) -> parse_isup_opts(OptBin, []). Parse options preceeded by 1 byte OptPtr parse_isup_opts_ptr(OptBinPtr) -> OptPtr = binary:at(OptBinPtr, 0), case OptPtr of 0 -> []; _ -> OptBin = binary:part(OptBinPtr, OptPtr, byte_size(OptBinPtr)-OptPtr), parse_isup_opts(OptBin, []) end. References to ' Tabe C - xxx ' are to Annex C of Q.767 ANM , RLC , FOT parse_isup_msgt(M, Bin) when M == ?ISUP_MSGT_ANM; M == ?ISUP_MSGT_RLC; M == ?ISUP_MSGT_FOT -> parse_isup_opts_ptr(Bin); parse_isup_msgt(?ISUP_MSGT_ACM, Bin) -> <<BackCallInd:16, Remain/binary>> = Bin, BciOpt = {backward_call_ind, BackCallInd}, Opts = parse_isup_opts_ptr(Remain), [BciOpt|Opts]; parse_isup_msgt(?ISUP_MSGT_CPG, Bin) -> <<EventInf:8, Remain/binary>> = Bin, BciOpt = {event_info, EventInf}, Opts = parse_isup_opts_ptr(Remain), [BciOpt|Opts]; parse_isup_msgt(?ISUP_MSGT_GRA, Bin) -> <<PtrVar:8, _Remain/binary>> = Bin, RangStsLen = binary:at(Bin, PtrVar), RangeStatus = binary:part(Bin, PtrVar+1, RangStsLen), RangeStsTuple = {?ISUP_PAR_RANGE_AND_STATUS, {RangStsLen, RangeStatus}}, [RangeStsTuple]; parse_isup_msgt(?ISUP_MSGT_CON, Bin) -> <<BackCallInd:16, Remain/binary>> = Bin, BciOpt = {backward_call_ind, BackCallInd}, Opts = parse_isup_opts_ptr(Remain), [BciOpt|Opts]; parse_isup_msgt(?ISUP_MSGT_COT, Bin) -> <<ContInd:8>> = Bin, [{continuity_ind, ContInd}]; parse_isup_msgt(?ISUP_MSGT_IAM, Bin) -> <<CINat:8, FwCallInd:16/big, CallingCat:8, TransmReq:8, VarAndOpt/binary>> = Bin, FixedOpts = [{conn_ind_nature, CINat}, {fw_call_ind, FwCallInd}, {calling_cat, CallingCat}, {transm_medium_req, TransmReq}], <<PtrVar:8, PtrOpt:8, _/binary>> = VarAndOpt, CalledPartyLen = binary:at(VarAndOpt, PtrVar), CalledParty = binary:part(VarAndOpt, PtrVar+1, CalledPartyLen), VarOpts = [parse_isup_opt(?ISUP_PAR_CALLED_P_NUM, CalledPartyLen, CalledParty)], case PtrOpt of 0 -> Opts = []; _ -> Remain = binary:part(VarAndOpt, 1 + PtrOpt, byte_size(VarAndOpt)-(1+PtrOpt)), Opts = parse_isup_opts(Remain) end, FixedOpts ++ VarOpts ++ Opts; Table 26 / Q.763 : Confusion parse_isup_msgt(M, VarAndOpt) when M == ?ISUP_MSGT_REL; M == ?ISUP_MSGT_CFN -> <<PtrVar:8, PtrOpt:8, _/binary>> = VarAndOpt, CauseIndLen = binary:at(VarAndOpt, PtrVar), CauseInd = binary:part(VarAndOpt, PtrVar+1, CauseIndLen), VarOpts = [{?ISUP_PAR_CAUSE_IND, {CauseIndLen, CauseInd}}], case PtrOpt of 0 -> Opts = []; _ -> Remain = binary:part(VarAndOpt, 1 + PtrOpt, byte_size(VarAndOpt)-(1+PtrOpt)), Opts = parse_isup_opts(Remain) end, VarOpts ++ Opts; parse_isup_msgt(?ISUP_MSGT_SAM, VarAndOpt) -> <<PtrVar:8, PtrOpt:8, _/binary>> = VarAndOpt, SubseqNumLen = binary:at(VarAndOpt, PtrVar), SubsetNum = binary:part(VarAndOpt, PtrVar+1, SubseqNumLen), VarOpts = [{?ISUP_PAR_SUBSEQ_NUM, {SubseqNumLen, SubsetNum}}], Remain = binary:part(VarAndOpt, 1 + PtrOpt, byte_size(VarAndOpt)-(1+PtrOpt)), Opts = parse_isup_opts(Remain), VarOpts ++ Opts; Table C-21 Suspend , Resume parse_isup_msgt(Msgt, Bin) when Msgt == ?ISUP_MSGT_RES; Msgt == ?ISUP_MSGT_SUS -> <<SuspResInd:8, Remain/binary>> = Bin, FixedOpts = [{susp_res_ind, SuspResInd}], Opts = parse_isup_opts_ptr(Remain), FixedOpts ++ Opts; Table C-23 parse_isup_msgt(M, <<>>) when M == ?ISUP_MSGT_BLO; M == ?ISUP_MSGT_BLA; M == ?ISUP_MSGT_CCR; M == ?ISUP_MSGT_RSC; M == ?ISUP_MSGT_UBL; M == ?ISUP_MSGT_UBA -> []; Table 39 / Q.763 messages for national use , fixed length 1 byte msgtype parse_isup_msgt(M, <<>>) when M == ?ISUP_MSGT_LPA; M == ?ISUP_MSGT_OLM; M == ?ISUP_MSGT_UCIC -> []; Table C-25 parse_isup_msgt(M, Bin) when M == ?ISUP_MSGT_CGB; M == ?ISUP_MSGT_CGBA; M == ?ISUP_MSGT_CGU; M == ?ISUP_MSGT_CGUA -> <<CGMsgt:8, PtrVar:8, VarBin/binary>> = Bin, FixedOpts = [{cg_supv_msgt, CGMsgt}], RangStsLen = binary:at(VarBin, PtrVar-1), RangeStatus = binary:part(VarBin, PtrVar, RangStsLen), VarOpts = [{?ISUP_PAR_RANGE_AND_STATUS, {RangStsLen, RangeStatus}}], FixedOpts ++ VarOpts; Table C-26 Circuit group reset parse_isup_msgt(?ISUP_MSGT_GRS, Bin) -> <<PtrVar:8, _VarBin/binary>> = Bin, RangeLen = binary:at(Bin, PtrVar), Range = binary:part(Bin, PtrVar+1, RangeLen), [{?ISUP_PAR_RANGE_AND_STATUS, {RangeLen, Range}}]. parse_isup_msg(DataBin) when is_binary(DataBin) -> <<Cic:12/little, 0:4, MsgType:8, Remain/binary>> = DataBin, Opts = parse_isup_msgt(MsgType, Remain), #isup_msg{cic = Cic, msg_type = MsgType, parameters = Opts}. encode a phone number from a list of digits into the BCD binary sequence encode_isup_party(BcdInt) when is_integer(BcdInt) -> BcdList = osmo_util:int2digit_list(BcdInt), encode_isup_party(BcdList); encode_isup_party(BcdList) when is_list(BcdList) -> encode_isup_party(BcdList, <<>>, length(BcdList)). encode_isup_party([], Bin, NumDigits) -> case NumDigits rem 2 of 1 -> {Bin, 1}; 0 -> {Bin, 0} end; encode_isup_party([First,Second|BcdList], Bin, NumDigits) -> encode_isup_party(BcdList, <<Bin/binary, Second:4, First:4>>, NumDigits); encode_isup_party([Last], Bin, NumDigits) -> encode_isup_party([], <<Bin/binary, 0:4, Last:4>>, NumDigits). encode_isup_par(?ISUP_PAR_CALLED_P_NUM, #party_number{nature_of_addr_ind = Nature, internal_net_num = Inn, numbering_plan = NumPlan, phone_number= PhoneNum}) -> {PhoneBin, OddEven} = encode_isup_party(PhoneNum), <<OddEven:1, Nature:7, Inn:1, NumPlan:3, 0:4, PhoneBin/binary>>; encode_isup_par(?ISUP_PAR_CALLING_P_NUM, #party_number{nature_of_addr_ind = Nature, number_incompl_ind = Ni, numbering_plan = NumPlan, present_restrict = PresRestr, screening_ind = Screen, phone_number= PhoneNum}) -> {PhoneBin, OddEven} = encode_isup_party(PhoneNum), <<OddEven:1, Nature:7, Ni:1, NumPlan:3, PresRestr:2, Screen:2, PhoneBin/binary>>; encode_isup_par(?ISUP_PAR_CONNECTED_NUM, #party_number{nature_of_addr_ind = Nature, numbering_plan = NumPlan, present_restrict = PresRestr, screening_ind = Screen, phone_number = PhoneNum}) -> {PhoneBin, OddEven} = encode_isup_party(PhoneNum), <<OddEven:1, Nature:7, 0:1, NumPlan:3, PresRestr:2, Screen:2, PhoneBin/binary>>; encode_isup_par(?ISUP_PAR_SUBSEQ_NUM, #party_number{phone_number = PhoneNum}) -> {PhoneBin, OddEven} = encode_isup_party(PhoneNum), <<OddEven:1, 0:7, PhoneBin/binary>>; encode_isup_par(Atom, _More) when is_atom(Atom) -> <<>>; encode_isup_par(OptNum, {OptLen, Binary}) when is_binary(Binary), is_integer(OptNum), is_integer(OptLen) -> Binary. encode_isup_optpar(ParNum, _ParBody) when is_atom(ParNum) -> <<>>; encode_isup_optpar(ParNum, ParBody) -> ParBin = encode_isup_par(ParNum, ParBody), ParLen = byte_size(ParBin), <<ParNum:8, ParLen:8, ParBin/binary>>. encode_isup_opts([], OutBin) -> case OutBin of <<>> -> OutBin; _ -> <<OutBin/binary, 0:8>> end; encode_isup_opts([Opt|OptPropList], OutBin) -> {OptType, OptBody} = Opt, OptBin = encode_isup_optpar(OptType, OptBody), encode_isup_opts(OptPropList, <<OutBin/binary, OptBin/binary>>). encode_isup_opts(OptPropList) -> encode_isup_opts(OptPropList, <<>>). encode_isup_hdr(#isup_msg{msg_type = MsgType, cic = Cic}) -> <<Cic:12/little, 0:4, MsgType:8>>. ANM , RLC , FOT encode_isup_msgt(M, #isup_msg{parameters = Params}) when M == ?ISUP_MSGT_ANM; M == ?ISUP_MSGT_RLC; M == ?ISUP_MSGT_FOT -> OptBin = encode_isup_opts(Params), case OptBin of <<>> -> PtrOpt = 0; _ -> PtrOpt = 1 end, <<PtrOpt:8, OptBin/binary>>; encode_isup_msgt(?ISUP_MSGT_ACM, #isup_msg{parameters = Params}) -> BackCallInd = proplists:get_value(backward_call_ind, Params), OptBin = encode_isup_opts(Params), case OptBin of <<>> -> PtrOpt = 0; _ -> PtrOpt = 1 end, <<BackCallInd:16, PtrOpt:8, OptBin/binary>>; encode_isup_msgt(?ISUP_MSGT_CPG, #isup_msg{parameters = Params}) -> EventInf = proplists:get_value(event_info, Params), OptBin = encode_isup_opts(Params), case OptBin of <<>> -> PtrOpt = 0; _ -> PtrOpt = 1 end, <<EventInf:8, PtrOpt:8, OptBin/binary>>; encode_isup_msgt(?ISUP_MSGT_GRA, #isup_msg{parameters = Params}) -> {RangStsLen, RangeStatus} = proplists:get_value(?ISUP_PAR_RANGE_AND_STATUS, Params), <<1:8, RangStsLen:8, RangeStatus/binary>>; encode_isup_msgt(?ISUP_MSGT_CON, #isup_msg{parameters = Params}) -> BackCallInd = proplists:get_value(backward_call_ind, Params), OptBin = encode_isup_opts(Params), case OptBin of <<>> -> PtrOpt = 0; _ -> PtrOpt = 1 end, <<BackCallInd:16, PtrOpt:8, OptBin/binary>>; encode_isup_msgt(?ISUP_MSGT_COT, #isup_msg{parameters = Params}) -> ContInd = proplists:get_value(continuity_ind, Params), <<ContInd:8>>; encode_isup_msgt(?ISUP_MSGT_IAM, #isup_msg{parameters = Params}) -> CINat = proplists:get_value(conn_ind_nature, Params), FwCallInd = proplists:get_value(fw_call_ind, Params), CallingCat = proplists:get_value(calling_cat, Params), TransmReq = proplists:get_value(transm_medium_req, Params), one byte behind the PtrOpt FixedBin = <<CINat:8, FwCallInd:16/big, CallingCat:8, TransmReq:8>>, CalledParty = encode_isup_par(?ISUP_PAR_CALLED_P_NUM, proplists:get_value(?ISUP_PAR_CALLED_P_NUM, Params)), CalledPartyLen = byte_size(CalledParty), Params2 = proplists:delete(?ISUP_PAR_CALLED_P_NUM, Params), OptBin = encode_isup_opts(Params2), case OptBin of <<>> -> PtrOpt = 0; 1 byte length , 1 byte start offset end, <<FixedBin/binary, PtrVar:8, PtrOpt:8, CalledPartyLen:8, CalledParty/binary, OptBin/binary>>; encode_isup_msgt(Msgt, #isup_msg{parameters = Params}) when Msgt == ?ISUP_MSGT_REL; Msgt == ?ISUP_MSGT_CFN -> one byte behind the PtrOpt CauseInd = encode_isup_par(?ISUP_PAR_CAUSE_IND, proplists:get_value(?ISUP_PAR_CAUSE_IND, Params)), CauseIndLen = byte_size(CauseInd), Params2 = proplists:delete(?ISUP_PAR_CAUSE_IND, Params), OptBin = encode_isup_opts(Params2), case OptBin of <<>> -> PtrOpt = 0; 1 byte length , 1 byte start offset end, <<PtrVar:8, PtrOpt:8, CauseIndLen:8, CauseInd/binary, OptBin/binary>>; encode_isup_msgt(?ISUP_MSGT_SAM, #isup_msg{parameters = Params}) -> one byte behind the PtrOpt SubseqNum = encode_isup_par(?ISUP_PAR_SUBSEQ_NUM, proplists:get_value(?ISUP_PAR_SUBSEQ_NUM, Params)), SubseqNumLen = byte_size(SubseqNum), Params2 = proplists:delete(?ISUP_PAR_SUBSEQ_NUM, Params), OptBin = encode_isup_opts(Params2), case OptBin of <<>> -> PtrOpt = 0; 1 byte length , 1 byte start offset end, <<PtrVar:8, PtrOpt:8, SubseqNumLen:8, SubseqNum/binary, OptBin/binary>>; Table C-21 Suspend , Resume encode_isup_msgt(Msgt, #isup_msg{parameters = Params}) when Msgt == ?ISUP_MSGT_RES; Msgt == ?ISUP_MSGT_SUS -> SuspResInd = proplists:get_value(susp_res_ind, Params), OptBin = encode_isup_opts(Params), case OptBin of <<>> -> PtrOpt = 0; _ -> PtrOpt = 1 end, <<SuspResInd:8, PtrOpt:8, OptBin/binary>>; Table C-23 encode_isup_msgt(M, #isup_msg{}) when M == ?ISUP_MSGT_BLO; M == ?ISUP_MSGT_BLA; M == ?ISUP_MSGT_CCR; M == ?ISUP_MSGT_RSC; M == ?ISUP_MSGT_UBL; M == ?ISUP_MSGT_UBA -> <<>>; Table 39 / Q.763 ( national use ) encode_isup_msgt(M, #isup_msg{}) when M == ?ISUP_MSGT_LPA; M == ?ISUP_MSGT_OLM; M == ?ISUP_MSGT_UCIC -> <<>>; Table C-25 encode_isup_msgt(M, #isup_msg{parameters = Params}) when M == ?ISUP_MSGT_CGB; M == ?ISUP_MSGT_CGBA; M == ?ISUP_MSGT_CGU; M == ?ISUP_MSGT_CGUA -> one byte behind the PtrVar CGMsgt = proplists:get_value(cg_supv_msgt, Params), {RangStsLen, RangeStatus} = proplists:get_value(?ISUP_PAR_RANGE_AND_STATUS, Params), <<CGMsgt:8, PtrVar:8, RangStsLen:8, RangeStatus/binary>>; Table C-26 Circuit group reset encode_isup_msgt(?ISUP_MSGT_GRS, #isup_msg{parameters = Params}) -> one byte behind the PtrVar {RangeLen, Range} = proplists:get_value(?ISUP_PAR_RANGE_AND_STATUS, Params), <<PtrVar:8, RangeLen:8, Range/binary>>. encode_isup_msg(Msg = #isup_msg{msg_type = MsgType}) -> HdrBin = encode_isup_hdr(Msg), Remain = encode_isup_msgt(MsgType, Msg), <<HdrBin/binary, Remain/binary>>.
cfab83ea78c0051a242841605df21203fa58b270d495fced7e98c8a642fe4309
alexbs01/OCaml
mylist3.ml
let hd l = match l with | header::_ -> header | [] -> raise(Failure "hd") let tl l = match l with | _::tail -> tail | [] -> raise(Failure "tl") let rec append l1 l2 = if l1 = [] then l2 else (hd l1) :: (append(tl l1) l2) let rec rev = function [] -> [] | head::tail -> append (rev tail) [head] let rec remove a l = match l with [] -> l | head::tail -> if (a = head) then tail else head::(remove a tail) let rec remove_all a l = match l with [] -> [] | head::tail -> if (a = head) then (remove_all a tail) else head::(remove_all a tail) let rec ldif l1 l2 = match (l1, l2) with head1::tail1, head2::tail2 -> ldif (remove_all head2 l1) tail2 | _ -> l1;; let lprod l1 l2 = let rec aux acc = function [], _ -> rev acc | _::tail1,[] -> aux acc (tail1, l2) | head1::tail1, head2::tail2 -> aux ((head1, head2)::acc) (head1::tail1, tail2) in aux [] (l1, l2) let rec divide = function head1::head2::tail -> let l1, l2 = divide tail in head1::l1, head2::l2 | l -> l, []
null
https://raw.githubusercontent.com/alexbs01/OCaml/92a28522a8467d8ed87ef380b6175f1c21616f85/p08/mylist3.ml
ocaml
let hd l = match l with | header::_ -> header | [] -> raise(Failure "hd") let tl l = match l with | _::tail -> tail | [] -> raise(Failure "tl") let rec append l1 l2 = if l1 = [] then l2 else (hd l1) :: (append(tl l1) l2) let rec rev = function [] -> [] | head::tail -> append (rev tail) [head] let rec remove a l = match l with [] -> l | head::tail -> if (a = head) then tail else head::(remove a tail) let rec remove_all a l = match l with [] -> [] | head::tail -> if (a = head) then (remove_all a tail) else head::(remove_all a tail) let rec ldif l1 l2 = match (l1, l2) with head1::tail1, head2::tail2 -> ldif (remove_all head2 l1) tail2 | _ -> l1;; let lprod l1 l2 = let rec aux acc = function [], _ -> rev acc | _::tail1,[] -> aux acc (tail1, l2) | head1::tail1, head2::tail2 -> aux ((head1, head2)::acc) (head1::tail1, tail2) in aux [] (l1, l2) let rec divide = function head1::head2::tail -> let l1, l2 = divide tail in head1::l1, head2::l2 | l -> l, []
2a5cf1e6249871c002dd19d2b5db8a314729f5101c72de477c6595fc07690bd5
TerrorJack/ghc-alter
ioeGetFileName001.hs
-- !!! test ioeGetFileName import System.IO import System.IO.Error main = do h <- openFile "ioeGetFileName001.hs" ReadMode hSeek h SeekFromEnd 0 (hGetChar h >> return ()) `catchIOError` \e -> if isEOFError e then print (ioeGetFileName e) else putStrLn "failed."
null
https://raw.githubusercontent.com/TerrorJack/ghc-alter/db736f34095eef416b7e077f9b26fc03aa78c311/ghc-alter/boot-lib/base/tests/IO/ioeGetFileName001.hs
haskell
!!! test ioeGetFileName
import System.IO import System.IO.Error main = do h <- openFile "ioeGetFileName001.hs" ReadMode hSeek h SeekFromEnd 0 (hGetChar h >> return ()) `catchIOError` \e -> if isEOFError e then print (ioeGetFileName e) else putStrLn "failed."
348ce0bc0d5d4aa5097bdb801b549cb5f263c58974d36472ed04060c8ad66692
macourtney/Dark-Exchange
offer.clj
(ns darkexchange.model.offer (:require [clj-record.boot :as clj-record-boot] [clojure.contrib.logging :as logging] [darkexchange.model.currency :as currency] [darkexchange.model.identity :as identity-model] [darkexchange.model.payment-type :as payment-type] [darkexchange.model.user :as user]) (:use darkexchange.model.base) (:import [java.math RoundingMode] [java.util Date])) (def offer-add-listeners (atom [])) (def delete-offer-listeners (atom [])) (def update-offer-listeners (atom [])) (defn add-offer-add-listener [listener] (swap! offer-add-listeners conj listener)) (defn add-delete-offer-listener [listener] (swap! delete-offer-listeners conj listener)) (defn add-update-offer-listener [listener] (swap! update-offer-listeners conj listener)) (defn offer-add [offer] (doseq [listener @offer-add-listeners] (listener offer))) (defn offer-deleted [offer] (doseq [listener @delete-offer-listeners] (listener offer))) (defn offer-updated [offer] (doseq [listener @update-offer-listeners] (listener offer))) (clj-record.core/init-model (:associations (belongs-to user)) (:callbacks (:after-insert offer-add) (:after-destroy offer-deleted) (:after-update offer-updated))) (defn create-new-offer [offer-data] (insert (merge { :created_at (new Date) :user_id (:id (user/current-user)) } (select-keys offer-data [:has_amount :has_currency :has_payment_type :wants_amount :wants_currency :wants_payment_type :identity_id :foreign_offer_id :closed])))) (defn update-from-foreign-offer [offer-id foreign-offer] (update { :id offer-id :foreign_offer_id (:id foreign-offer) :has_amount (:wants_amount foreign-offer) :has_currency (:wants_currency foreign-offer) :has_payment_type (:wants_payment_type foreign-offer) :wants_amount (:has_amount foreign-offer) :wants_currency (:has_currency foreign-offer) :wants_payment_type (:has_payment_type foreign-offer) }) (get-record offer-id)) (defn update-or-create-offer [offer-data] (when offer-data (or (find-record (select-keys offer-data [:user_id :identity_id :foreign_offer_id])) (get-record (create-new-offer offer-data))))) (defn all-offers [] (find-records [true])) (defn open-offer? [offer] (as-boolean (not (:closed offer)))) (defn open-offers ([] (open-offers (user/current-user))) ([user] (find-records ["(closed IS NULL OR closed = 0) AND user_id = ?" (:id user)]))) (defn currency [offer currency-key] (currency/get-currency (currency-key offer))) (defn amount-str [offer amount-key currency-key] (str (amount-key offer) " " (currency/currency-str (currency offer currency-key)))) (defn payment-type [offer payment-key] (payment-type/get-payment (payment-key offer))) (defn payment-type-str [offer payment-key] (payment-type/payment-type-str (payment-type offer payment-key))) (defn has-currency [offer] (currency offer :has_currency)) (defn has-amount-str [offer] (amount-str offer :has_amount :has_currency)) (defn has-payment-type [offer] (payment-type offer :has_payment_type)) (defn has-payment-type-str [offer] (payment-type-str offer :has_payment_type)) (defn wants-currency [offer] (currency offer :wants_currency)) (defn wants-amount-str [offer] (amount-str offer :wants_amount :wants_currency)) (defn wants_payment-type [offer] (payment-type offer :wants_payment_type)) (defn wants-payment-type-str [offer] (payment-type-str offer :wants_payment_type)) (defn delete-offer [offer-id] (destroy-record { :id offer-id })) (defn search-offers [search-args] (find-by-sql ["SELECT * FROM offers WHERE (closed IS NULL OR closed = 0) AND user_id = ? AND has_currency = ? AND has_payment_type = ? AND wants_currency = ? AND wants_payment_type = ?" (:id (user/current-user)) (:i-want-currency search-args) (:i-want-payment-type search-args) (:i-have-currency search-args) (:i-have-payment-type search-args)])) (defn close-offer [offer] (when-let [local-offer (find-record { :id (:id offer) })] (when (open-offer? local-offer) (update { :id (:id offer) :closed 1 }) (get-record (:id offer))))) (defn reopen-offer [offer] (update { :id (:id offer) :closed 0 })) (defn big-decimal-divide [numerator denominator] (.divide (bigdec numerator) (bigdec denominator) 8 RoundingMode/HALF_UP)) (defn calculate-has-div-wants [offer] (big-decimal-divide (:has_amount offer) (:wants_amount offer))) (defn calculate-wants-div-has [offer] (big-decimal-divide (:wants_amount offer) (:has_amount offer))) (defn convert-to-table-offer [offer] { :id (:id offer) :i-have-amount (has-amount-str offer) :i-want-to-send-by (has-payment-type-str offer) :i-want-amount (wants-amount-str offer) :i-want-to-receive-by (wants-payment-type-str offer) :has-div-wants (calculate-has-div-wants offer) :wants-div-has (calculate-wants-div-has offer) :original-offer offer }) (defn table-open-offers [] (map convert-to-table-offer (open-offers)))
null
https://raw.githubusercontent.com/macourtney/Dark-Exchange/1654d05cda0c81585da7b8e64f9ea3e2944b27f1/src/darkexchange/model/offer.clj
clojure
(ns darkexchange.model.offer (:require [clj-record.boot :as clj-record-boot] [clojure.contrib.logging :as logging] [darkexchange.model.currency :as currency] [darkexchange.model.identity :as identity-model] [darkexchange.model.payment-type :as payment-type] [darkexchange.model.user :as user]) (:use darkexchange.model.base) (:import [java.math RoundingMode] [java.util Date])) (def offer-add-listeners (atom [])) (def delete-offer-listeners (atom [])) (def update-offer-listeners (atom [])) (defn add-offer-add-listener [listener] (swap! offer-add-listeners conj listener)) (defn add-delete-offer-listener [listener] (swap! delete-offer-listeners conj listener)) (defn add-update-offer-listener [listener] (swap! update-offer-listeners conj listener)) (defn offer-add [offer] (doseq [listener @offer-add-listeners] (listener offer))) (defn offer-deleted [offer] (doseq [listener @delete-offer-listeners] (listener offer))) (defn offer-updated [offer] (doseq [listener @update-offer-listeners] (listener offer))) (clj-record.core/init-model (:associations (belongs-to user)) (:callbacks (:after-insert offer-add) (:after-destroy offer-deleted) (:after-update offer-updated))) (defn create-new-offer [offer-data] (insert (merge { :created_at (new Date) :user_id (:id (user/current-user)) } (select-keys offer-data [:has_amount :has_currency :has_payment_type :wants_amount :wants_currency :wants_payment_type :identity_id :foreign_offer_id :closed])))) (defn update-from-foreign-offer [offer-id foreign-offer] (update { :id offer-id :foreign_offer_id (:id foreign-offer) :has_amount (:wants_amount foreign-offer) :has_currency (:wants_currency foreign-offer) :has_payment_type (:wants_payment_type foreign-offer) :wants_amount (:has_amount foreign-offer) :wants_currency (:has_currency foreign-offer) :wants_payment_type (:has_payment_type foreign-offer) }) (get-record offer-id)) (defn update-or-create-offer [offer-data] (when offer-data (or (find-record (select-keys offer-data [:user_id :identity_id :foreign_offer_id])) (get-record (create-new-offer offer-data))))) (defn all-offers [] (find-records [true])) (defn open-offer? [offer] (as-boolean (not (:closed offer)))) (defn open-offers ([] (open-offers (user/current-user))) ([user] (find-records ["(closed IS NULL OR closed = 0) AND user_id = ?" (:id user)]))) (defn currency [offer currency-key] (currency/get-currency (currency-key offer))) (defn amount-str [offer amount-key currency-key] (str (amount-key offer) " " (currency/currency-str (currency offer currency-key)))) (defn payment-type [offer payment-key] (payment-type/get-payment (payment-key offer))) (defn payment-type-str [offer payment-key] (payment-type/payment-type-str (payment-type offer payment-key))) (defn has-currency [offer] (currency offer :has_currency)) (defn has-amount-str [offer] (amount-str offer :has_amount :has_currency)) (defn has-payment-type [offer] (payment-type offer :has_payment_type)) (defn has-payment-type-str [offer] (payment-type-str offer :has_payment_type)) (defn wants-currency [offer] (currency offer :wants_currency)) (defn wants-amount-str [offer] (amount-str offer :wants_amount :wants_currency)) (defn wants_payment-type [offer] (payment-type offer :wants_payment_type)) (defn wants-payment-type-str [offer] (payment-type-str offer :wants_payment_type)) (defn delete-offer [offer-id] (destroy-record { :id offer-id })) (defn search-offers [search-args] (find-by-sql ["SELECT * FROM offers WHERE (closed IS NULL OR closed = 0) AND user_id = ? AND has_currency = ? AND has_payment_type = ? AND wants_currency = ? AND wants_payment_type = ?" (:id (user/current-user)) (:i-want-currency search-args) (:i-want-payment-type search-args) (:i-have-currency search-args) (:i-have-payment-type search-args)])) (defn close-offer [offer] (when-let [local-offer (find-record { :id (:id offer) })] (when (open-offer? local-offer) (update { :id (:id offer) :closed 1 }) (get-record (:id offer))))) (defn reopen-offer [offer] (update { :id (:id offer) :closed 0 })) (defn big-decimal-divide [numerator denominator] (.divide (bigdec numerator) (bigdec denominator) 8 RoundingMode/HALF_UP)) (defn calculate-has-div-wants [offer] (big-decimal-divide (:has_amount offer) (:wants_amount offer))) (defn calculate-wants-div-has [offer] (big-decimal-divide (:wants_amount offer) (:has_amount offer))) (defn convert-to-table-offer [offer] { :id (:id offer) :i-have-amount (has-amount-str offer) :i-want-to-send-by (has-payment-type-str offer) :i-want-amount (wants-amount-str offer) :i-want-to-receive-by (wants-payment-type-str offer) :has-div-wants (calculate-has-div-wants offer) :wants-div-has (calculate-wants-div-has offer) :original-offer offer }) (defn table-open-offers [] (map convert-to-table-offer (open-offers)))
2804f2651a52146299de6ccaab5a530e3d35e9cbfb584bb111b80b8c9cc6f053
keigoi/session-ocaml
lsession.ml
type 'a data = W of 'a type ('pre, 'post, 'a) lmonad = 'pre -> 'post * 'a type 'f lbind = 'f type ('a,'b,'ss,'tt) slot = ('ss -> 'a) * ('ss -> 'b -> 'tt) let _0 = (fun (a,_) -> a), (fun (_,ss) b -> (b,ss)) let _1 = (fun (_,(a,_)) -> a), (fun (s0,(_,ss)) b -> (s0,(b,ss))) let _2 = (fun (_,(_,(a,_))) -> a), (fun (s0,(s1,(_,ss))) b -> (s0,(s1,(b,ss)))) let _3 = (fun (_,(_,(_,(a,_)))) -> a), (fun (s0,(s1,(s2,(_,ss)))) b -> (s0,(s1,(s2,(b,ss))))) type empty = Empty type all_empty = empty * 'a as 'a let return a pre = pre, a let (>>=) f g pre = let mid, la = f pre in g la mid let (>>) f g pre = let mid, _ = f pre in g mid module type UnsafeChannel = sig type t val create : unit -> t val send : t -> 'a -> unit val receive : t -> 'a val reverse : t -> t end type req and resp type cli = req * resp and serv = resp * req module type S = sig type 'p channel val new_channel : unit -> 'p channel type ('p,'q) sess val accept : 'p channel -> ('pre, 'pre, ('p, serv) sess) lmonad val connect : 'p channel -> ('pre, 'pre, ('p, cli) sess) lmonad val close : (([`close], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, unit) lmonad val send : 'v -> (([`msg of 'r1 * 'v * 'p], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, ('p, 'r1*'r2) sess) lmonad val receive : (([`msg of 'r2 * 'v * 'p], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, 'v data * ('p, 'r1*'r2) sess) lmonad val select : (('p,'r2*'r1) sess -> ([>] as 'br)) -> (([`branch of 'r1 * 'br],'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, ('p,'r1*'r2) sess) lmonad val branch : (([`branch of 'r2 * [>] as 'br], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, 'br) lmonad val deleg_send : (('pp, 'qq) sess, empty, 'mid, 'post) slot -> (([`deleg of 'r1 * ('pp, 'qq) sess * 'p], 'r1*'r2) sess, empty, 'pre, 'mid) slot -> ('pre, 'post, ('p, 'r1*'r2) sess) lmonad val deleg_recv : (([`deleg of 'r2 * ('pp, 'qq) sess * 'p], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, ('pp,'qq) sess * ('p,'r1*'r2) sess) lmonad end module Make(U : UnsafeChannel) : S = struct type ('p,'q) sess = U.t type 'p channel = U.t Schannel.t let new_channel = Schannel.create let accept : 'p 'pre. 'p channel -> ('pre, 'pre, ('p, serv) sess) lmonad = fun ch pre -> let s = Schannel.receive ch in pre, s let connect : 'p 'pre. 'p channel -> ('pre, 'pre, ('p, cli) sess) lmonad = fun ch pre -> let s = U.create () in Schannel.send ch (U.reverse s); pre, s let close : 'pre 'r1 'r2 'post. (([`close], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, unit) lmonad = fun (_,set) pre -> set pre Empty, () let send : 'v 'r1 'p 'r2 'pre 'post. 'v -> (([`msg of 'r1 * 'v * 'p], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, ('p, 'r1*'r2) sess) lmonad = fun v (get,set) pre -> let s = get pre in U.send s v; set pre Empty, s let receive : 'r2 'v 'p 'r1 'pre 'post. (([`msg of 'r2 * 'v * 'p], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, 'v data * ('p, 'r1*'r2) sess) lmonad = fun (get,set) pre -> let s = get pre in set pre Empty, (W (U.receive s), s) let select : 'p 'r2 'r1 'pre 'post. (('p,'r2*'r1) sess -> ([>] as 'br)) -> (([`branch of 'r1 * 'br],'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, ('p,'r1*'r2) sess) lmonad = fun f (get,set) pre -> let s = get pre in U.send s (f (U.reverse s)); set pre Empty, s let branch : 'r2 'r1 'pre 'post. (([`branch of 'r2 * [>] as 'br], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, 'br) lmonad = fun (get,set) pre -> let s = get pre in set pre Empty, (U.receive s) let deleg_send : 'pp 'qq 'mid 'post 'r1 'r2 'pre. (('pp, 'qq) sess, empty, 'mid, 'post) slot -> (([`deleg of 'r1 * ('pp, 'qq) sess * 'p], 'r1*'r2) sess, empty, 'pre, 'mid) slot -> ('pre, 'post, ('p, 'r1*'r2) sess) lmonad = fun (get1,set1) (get2,set2) pre -> let s = get2 pre in let mid = set2 pre Empty in let t = get1 mid in U.send s t; set1 mid Empty, s let deleg_recv : 'r2 'p 'r1 'pre 'post 'pp 'qq. (([`deleg of 'r2 * ('pp, 'qq) sess * 'p], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, ('pp,'qq) sess * ('p,'r1*'r2) sess) lmonad = fun (get,set) pre -> let s = get pre in let t = U.receive s in set pre Empty, (t, s) end include Make(struct type t = unit Event.channel let create = Event.new_channel let send ch x = Event.sync (Event.send ch (Obj.magic x)) let receive ch = Obj.magic (Event.sync (Event.receive ch)) let reverse ch = ch end) module Syntax = struct let bind = (>>=) module Internal = struct let __return_raw v pre = pre, v let __bind_raw = fun m f pre -> match m pre with (mid,x) -> f x mid let __putval_raw = fun (_,set) v pre -> set pre v, () let __takeval_raw (get,set) pre = set pre Empty, get pre let __mkbindfun f = f let __dispose_env m pre = (>>=) (m pre) (fun (_,a) -> return (Empty, a)) end end
null
https://raw.githubusercontent.com/keigoi/session-ocaml/f365456043b349874a5ce5444d313f365d5573c6/lib/lsession.ml
ocaml
type 'a data = W of 'a type ('pre, 'post, 'a) lmonad = 'pre -> 'post * 'a type 'f lbind = 'f type ('a,'b,'ss,'tt) slot = ('ss -> 'a) * ('ss -> 'b -> 'tt) let _0 = (fun (a,_) -> a), (fun (_,ss) b -> (b,ss)) let _1 = (fun (_,(a,_)) -> a), (fun (s0,(_,ss)) b -> (s0,(b,ss))) let _2 = (fun (_,(_,(a,_))) -> a), (fun (s0,(s1,(_,ss))) b -> (s0,(s1,(b,ss)))) let _3 = (fun (_,(_,(_,(a,_)))) -> a), (fun (s0,(s1,(s2,(_,ss)))) b -> (s0,(s1,(s2,(b,ss))))) type empty = Empty type all_empty = empty * 'a as 'a let return a pre = pre, a let (>>=) f g pre = let mid, la = f pre in g la mid let (>>) f g pre = let mid, _ = f pre in g mid module type UnsafeChannel = sig type t val create : unit -> t val send : t -> 'a -> unit val receive : t -> 'a val reverse : t -> t end type req and resp type cli = req * resp and serv = resp * req module type S = sig type 'p channel val new_channel : unit -> 'p channel type ('p,'q) sess val accept : 'p channel -> ('pre, 'pre, ('p, serv) sess) lmonad val connect : 'p channel -> ('pre, 'pre, ('p, cli) sess) lmonad val close : (([`close], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, unit) lmonad val send : 'v -> (([`msg of 'r1 * 'v * 'p], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, ('p, 'r1*'r2) sess) lmonad val receive : (([`msg of 'r2 * 'v * 'p], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, 'v data * ('p, 'r1*'r2) sess) lmonad val select : (('p,'r2*'r1) sess -> ([>] as 'br)) -> (([`branch of 'r1 * 'br],'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, ('p,'r1*'r2) sess) lmonad val branch : (([`branch of 'r2 * [>] as 'br], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, 'br) lmonad val deleg_send : (('pp, 'qq) sess, empty, 'mid, 'post) slot -> (([`deleg of 'r1 * ('pp, 'qq) sess * 'p], 'r1*'r2) sess, empty, 'pre, 'mid) slot -> ('pre, 'post, ('p, 'r1*'r2) sess) lmonad val deleg_recv : (([`deleg of 'r2 * ('pp, 'qq) sess * 'p], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, ('pp,'qq) sess * ('p,'r1*'r2) sess) lmonad end module Make(U : UnsafeChannel) : S = struct type ('p,'q) sess = U.t type 'p channel = U.t Schannel.t let new_channel = Schannel.create let accept : 'p 'pre. 'p channel -> ('pre, 'pre, ('p, serv) sess) lmonad = fun ch pre -> let s = Schannel.receive ch in pre, s let connect : 'p 'pre. 'p channel -> ('pre, 'pre, ('p, cli) sess) lmonad = fun ch pre -> let s = U.create () in Schannel.send ch (U.reverse s); pre, s let close : 'pre 'r1 'r2 'post. (([`close], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, unit) lmonad = fun (_,set) pre -> set pre Empty, () let send : 'v 'r1 'p 'r2 'pre 'post. 'v -> (([`msg of 'r1 * 'v * 'p], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, ('p, 'r1*'r2) sess) lmonad = fun v (get,set) pre -> let s = get pre in U.send s v; set pre Empty, s let receive : 'r2 'v 'p 'r1 'pre 'post. (([`msg of 'r2 * 'v * 'p], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, 'v data * ('p, 'r1*'r2) sess) lmonad = fun (get,set) pre -> let s = get pre in set pre Empty, (W (U.receive s), s) let select : 'p 'r2 'r1 'pre 'post. (('p,'r2*'r1) sess -> ([>] as 'br)) -> (([`branch of 'r1 * 'br],'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, ('p,'r1*'r2) sess) lmonad = fun f (get,set) pre -> let s = get pre in U.send s (f (U.reverse s)); set pre Empty, s let branch : 'r2 'r1 'pre 'post. (([`branch of 'r2 * [>] as 'br], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, 'br) lmonad = fun (get,set) pre -> let s = get pre in set pre Empty, (U.receive s) let deleg_send : 'pp 'qq 'mid 'post 'r1 'r2 'pre. (('pp, 'qq) sess, empty, 'mid, 'post) slot -> (([`deleg of 'r1 * ('pp, 'qq) sess * 'p], 'r1*'r2) sess, empty, 'pre, 'mid) slot -> ('pre, 'post, ('p, 'r1*'r2) sess) lmonad = fun (get1,set1) (get2,set2) pre -> let s = get2 pre in let mid = set2 pre Empty in let t = get1 mid in U.send s t; set1 mid Empty, s let deleg_recv : 'r2 'p 'r1 'pre 'post 'pp 'qq. (([`deleg of 'r2 * ('pp, 'qq) sess * 'p], 'r1*'r2) sess, empty, 'pre, 'post) slot -> ('pre, 'post, ('pp,'qq) sess * ('p,'r1*'r2) sess) lmonad = fun (get,set) pre -> let s = get pre in let t = U.receive s in set pre Empty, (t, s) end include Make(struct type t = unit Event.channel let create = Event.new_channel let send ch x = Event.sync (Event.send ch (Obj.magic x)) let receive ch = Obj.magic (Event.sync (Event.receive ch)) let reverse ch = ch end) module Syntax = struct let bind = (>>=) module Internal = struct let __return_raw v pre = pre, v let __bind_raw = fun m f pre -> match m pre with (mid,x) -> f x mid let __putval_raw = fun (_,set) v pre -> set pre v, () let __takeval_raw (get,set) pre = set pre Empty, get pre let __mkbindfun f = f let __dispose_env m pre = (>>=) (m pre) (fun (_,a) -> return (Empty, a)) end end
19753d8522d49d5d9b33e037f4f35ff4502cc96ae09facfbdbe41bd66e71d140
melange-re/melange-compiler-libs
translprim.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Insertion of debugging events *) val event_before : Lambda.scoped_location -> Typedtree.expression -> Lambda.lambda -> Lambda.lambda val event_after : Lambda.scoped_location -> Typedtree.expression -> Lambda.lambda -> Lambda.lambda (* Translation of primitives *) val add_exception_ident : Ident.t -> unit val remove_exception_ident : Ident.t -> unit val clear_used_primitives : unit -> unit val get_used_primitives: unit -> Path.t list val check_primitive_arity : Location.t -> Primitive.description -> unit val transl_primitive : Lambda.scoped_location -> Primitive.description -> Env.t -> Types.type_expr -> Path.t option -> Lambda.lambda val transl_primitive_application : Lambda.scoped_location -> Primitive.description -> Env.t -> Types.type_expr -> Path.t -> Typedtree.expression option -> Lambda.lambda list -> Typedtree.expression list -> Lambda.lambda (* Errors *) type error = | Unknown_builtin_primitive of string | Wrong_arity_builtin_primitive of string exception Error of Location.t * error open Format val report_error : formatter -> error -> unit
null
https://raw.githubusercontent.com/melange-re/melange-compiler-libs/83e3017d2e7a058385f71d1d9a4c4ab52dc1c008/lambda/translprim.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. ************************************************************************ Insertion of debugging events Translation of primitives Errors
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the val event_before : Lambda.scoped_location -> Typedtree.expression -> Lambda.lambda -> Lambda.lambda val event_after : Lambda.scoped_location -> Typedtree.expression -> Lambda.lambda -> Lambda.lambda val add_exception_ident : Ident.t -> unit val remove_exception_ident : Ident.t -> unit val clear_used_primitives : unit -> unit val get_used_primitives: unit -> Path.t list val check_primitive_arity : Location.t -> Primitive.description -> unit val transl_primitive : Lambda.scoped_location -> Primitive.description -> Env.t -> Types.type_expr -> Path.t option -> Lambda.lambda val transl_primitive_application : Lambda.scoped_location -> Primitive.description -> Env.t -> Types.type_expr -> Path.t -> Typedtree.expression option -> Lambda.lambda list -> Typedtree.expression list -> Lambda.lambda type error = | Unknown_builtin_primitive of string | Wrong_arity_builtin_primitive of string exception Error of Location.t * error open Format val report_error : formatter -> error -> unit
e2a54c8e6a736af70a2da616803bff2e32df5018b7cff4ab4417b0b6c843e38f
Abhiroop/okasaki
BST.hs
module BST where data BST a = Nil | Node a (BST a) (BST a) deriving (Show, Eq) key :: BST a -> a key Nil = undefined key (Node a _ _) = a left :: BST a -> BST a left Nil = Nil left (Node _ l _) = l right :: BST a -> BST a right Nil = Nil right (Node _ _ r) = r -- | Search returning boolean search :: (Ord a) => BST a -> a -> Bool search Nil _ = False search (Node a l r) k | a == k = True | a < k = search r k | otherwise = search l k -- | Search returning the tree searchT :: (Ord a) => BST a -> a -> BST a searchT Nil _ = Nil searchT x@(Node a l r) k | a == k = x | a < k = searchT r k | otherwise = searchT l k -- | In order traversal inorder :: BST a -> [a] inorder Nil = [] inorder (Node a l r) = (inorder l) ++ [a] ++ (inorder r) -- | Preorder traversal preorder :: BST a -> [a] preorder Nil = [] preorder (Node a l r) = [a] ++ (preorder l) ++ (preorder r) -- | Postorder traversal postorder :: BST a -> [a] postorder Nil = [] postorder (Node a l r) = (postorder l) ++ (postorder r) ++ [a] -- | Minimum of a BST a treeMinimum :: BST a -> a treeMinimum Nil = undefined treeMinimum (Node a Nil _) = a treeMinimum (Node _ l _) = treeMinimum l -- | Maximum of a BST a treeMaximum :: BST a -> a treeMaximum Nil = undefined treeMaximum (Node a _ Nil ) = a treeMaximum (Node _ _ r) = treeMaximum r -- | Find predecessor of an element type Parent = BstP type LChild = BstP type RChild = BstP data BstP a = None | Node1 a (Parent a) (LChild a) (RChild a) deriving Show predecessor ::(Ord a) => BstP a -> a predecessor None = undefined predecessor (Node1 a p None _) = findPredAncestor a p predecessor (Node1 a _ l _) = treeMaximumP l treeMaximumP :: BstP a -> a treeMaximumP None = undefined treeMaximumP (Node1 a _ _ None ) = a treeMaximumP (Node1 _ _ _ r) = treeMaximumP r findPredAncestor :: (Ord a) => a -> BstP a -> a findPredAncestor k (Node1 a p l r) | (keyP r) == k = a | otherwise = findPredAncestor a p keyP :: BstP a -> a keyP None = undefined keyP (Node1 a _ _ _) = a -- | Find successor of an element -- | Insertion insert :: Ord a => a -> BST a -> BST a insert k Nil = (Node k Nil Nil) insert k (Node a l r) | (k == a) = (Node a l r) | k < a = insert k l | otherwise = insert k r -- | Deletion delete :: Ord a => a -> BST a -> BST a delete k Nil = Nil delete k x@(Node a l r) | (k < a) = delete k l | (k > a) = delete k r | (k == a) = delete' k x delete' :: (Ord a) => a -> BST a -> BST a delete' k (Node a l r) | (l == Nil) = r | (r == Nil) = l | otherwise = let (k,t) = maxAndDelete l in Node k t r -- This function finds the maximum and then deletes the node as well maxAndDelete :: (Ord a) => BST a -> (a,BST a) maxAndDelete t = let m = treeMaximum t in (m,delete m t) -- | Merging merge :: (Ord a) => BST a -> BST a -> BST a merge Nil Nil = Nil merge a Nil = a merge Nil a = a merge a b = let finalList = (inorder a) ++ (inorder b) in foldr insert Nil finalList -- | Balancing 10 / \ 8 12 / \ / \ 7 9 11 13 10 / \ 8 12 / \ / \ 7 9 11 13 -} x :: BST Integer x = (Node 10 (Node 8 (Node 7 Nil Nil) (Node 9 Nil Nil)) (Node 12 (Node 11 Nil Nil) (Node 13 Nil Nil))) y = Node 3 (Node 1 Nil Nil) (Node 2 Nil Nil)
null
https://raw.githubusercontent.com/Abhiroop/okasaki/b4e8b6261cf9c44b7b273116be3da6efde76232d/src/BST.hs
haskell
| Search returning boolean | Search returning the tree | In order traversal | Preorder traversal | Postorder traversal | Minimum of a BST a | Maximum of a BST a | Find predecessor of an element | Find successor of an element | Insertion | Deletion This function finds the maximum and then deletes the node as well | Merging | Balancing
module BST where data BST a = Nil | Node a (BST a) (BST a) deriving (Show, Eq) key :: BST a -> a key Nil = undefined key (Node a _ _) = a left :: BST a -> BST a left Nil = Nil left (Node _ l _) = l right :: BST a -> BST a right Nil = Nil right (Node _ _ r) = r search :: (Ord a) => BST a -> a -> Bool search Nil _ = False search (Node a l r) k | a == k = True | a < k = search r k | otherwise = search l k searchT :: (Ord a) => BST a -> a -> BST a searchT Nil _ = Nil searchT x@(Node a l r) k | a == k = x | a < k = searchT r k | otherwise = searchT l k inorder :: BST a -> [a] inorder Nil = [] inorder (Node a l r) = (inorder l) ++ [a] ++ (inorder r) preorder :: BST a -> [a] preorder Nil = [] preorder (Node a l r) = [a] ++ (preorder l) ++ (preorder r) postorder :: BST a -> [a] postorder Nil = [] postorder (Node a l r) = (postorder l) ++ (postorder r) ++ [a] treeMinimum :: BST a -> a treeMinimum Nil = undefined treeMinimum (Node a Nil _) = a treeMinimum (Node _ l _) = treeMinimum l treeMaximum :: BST a -> a treeMaximum Nil = undefined treeMaximum (Node a _ Nil ) = a treeMaximum (Node _ _ r) = treeMaximum r type Parent = BstP type LChild = BstP type RChild = BstP data BstP a = None | Node1 a (Parent a) (LChild a) (RChild a) deriving Show predecessor ::(Ord a) => BstP a -> a predecessor None = undefined predecessor (Node1 a p None _) = findPredAncestor a p predecessor (Node1 a _ l _) = treeMaximumP l treeMaximumP :: BstP a -> a treeMaximumP None = undefined treeMaximumP (Node1 a _ _ None ) = a treeMaximumP (Node1 _ _ _ r) = treeMaximumP r findPredAncestor :: (Ord a) => a -> BstP a -> a findPredAncestor k (Node1 a p l r) | (keyP r) == k = a | otherwise = findPredAncestor a p keyP :: BstP a -> a keyP None = undefined keyP (Node1 a _ _ _) = a insert :: Ord a => a -> BST a -> BST a insert k Nil = (Node k Nil Nil) insert k (Node a l r) | (k == a) = (Node a l r) | k < a = insert k l | otherwise = insert k r delete :: Ord a => a -> BST a -> BST a delete k Nil = Nil delete k x@(Node a l r) | (k < a) = delete k l | (k > a) = delete k r | (k == a) = delete' k x delete' :: (Ord a) => a -> BST a -> BST a delete' k (Node a l r) | (l == Nil) = r | (r == Nil) = l | otherwise = let (k,t) = maxAndDelete l in Node k t r maxAndDelete :: (Ord a) => BST a -> (a,BST a) maxAndDelete t = let m = treeMaximum t in (m,delete m t) merge :: (Ord a) => BST a -> BST a -> BST a merge Nil Nil = Nil merge a Nil = a merge Nil a = a merge a b = let finalList = (inorder a) ++ (inorder b) in foldr insert Nil finalList 10 / \ 8 12 / \ / \ 7 9 11 13 10 / \ 8 12 / \ / \ 7 9 11 13 -} x :: BST Integer x = (Node 10 (Node 8 (Node 7 Nil Nil) (Node 9 Nil Nil)) (Node 12 (Node 11 Nil Nil) (Node 13 Nil Nil))) y = Node 3 (Node 1 Nil Nil) (Node 2 Nil Nil)
b28607c4068e0068208003d8021c1b26a009487b06a292dcb11fc9579c4c6a5a
gearnode/erl-oauth2c
oauth2_error_tests.erl
Copyright ( c ) 2022 < > . Copyright ( c ) 2021 Exograd SAS . Copyright ( c ) 2020 < > . %% %% Permission to use, copy, modify, and/or distribute this software for any %% purpose with or without fee is hereby granted, provided that the above %% copyright notice and this permission notice appear in all copies. %% THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR %% IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -module(oauth2_error_tests). -include_lib("eunit/include/eunit.hrl"). parse_uri_test_() -> {ok, URIWithoutError} = uri:parse(<<"">>), {ok, URIWithError} = uri:parse(<<"">>), [?_assertEqual({ok, undefined}, oauth2c_error:parse_uri(URIWithoutError)), ?_assertMatch({ok, _}, oauth2c_error:parse_uri(URIWithError))]. parse_bin_test_() -> [?_assertMatch({error, {invalid_syntax, _}}, oauth2c_error:parse_bin(<<>>)), ?_assertMatch({error, {invalid_object, _}}, oauth2c_error:parse_bin(<<"{}">>)), ?_assertEqual({ok, #{error => <<"invalid_request">>}}, oauth2c_error:parse_bin(<<"{\"error\":\"invalid_request\"}">>)), ?_assertEqual({ok, #{error => <<"invalid_request">>, error_description => <<"Request was missing the 'redirect_uri' parameter.">>, error_uri => #{host => <<"authorization-server.com">>, path => <<"/docs/access_token">>, scheme => <<"https">>}}}, oauth2c_error:parse_bin(<<"{\"error\":\"invalid_request\",\"error_description\":\"Request was missing the 'redirect_uri' parameter.\",\"error_uri\":\"-server.com/docs/access_token\"}">>))].
null
https://raw.githubusercontent.com/gearnode/erl-oauth2c/e5c00a0e27a775790ae8b56f1d6d3617ae92d05e/test/oauth2_error_tests.erl
erlang
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Copyright ( c ) 2022 < > . Copyright ( c ) 2021 Exograd SAS . Copyright ( c ) 2020 < > . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN -module(oauth2_error_tests). -include_lib("eunit/include/eunit.hrl"). parse_uri_test_() -> {ok, URIWithoutError} = uri:parse(<<"">>), {ok, URIWithError} = uri:parse(<<"">>), [?_assertEqual({ok, undefined}, oauth2c_error:parse_uri(URIWithoutError)), ?_assertMatch({ok, _}, oauth2c_error:parse_uri(URIWithError))]. parse_bin_test_() -> [?_assertMatch({error, {invalid_syntax, _}}, oauth2c_error:parse_bin(<<>>)), ?_assertMatch({error, {invalid_object, _}}, oauth2c_error:parse_bin(<<"{}">>)), ?_assertEqual({ok, #{error => <<"invalid_request">>}}, oauth2c_error:parse_bin(<<"{\"error\":\"invalid_request\"}">>)), ?_assertEqual({ok, #{error => <<"invalid_request">>, error_description => <<"Request was missing the 'redirect_uri' parameter.">>, error_uri => #{host => <<"authorization-server.com">>, path => <<"/docs/access_token">>, scheme => <<"https">>}}}, oauth2c_error:parse_bin(<<"{\"error\":\"invalid_request\",\"error_description\":\"Request was missing the 'redirect_uri' parameter.\",\"error_uri\":\"-server.com/docs/access_token\"}">>))].
7306599846d55fe6f08c751ec24a4367d0a166c77f105c08153c077f637bd343
bobzhang/fan
gfold.ml
let sfold0 f e _entry _symbl psymb = let rec fold accu = %parser{ | a = psymb; 's -> fold (f a accu) s | -> accu } in %parser{| a = fold e -> a} let sfold1 f e _entry _symbl psymb = let rec fold accu = %parser{ | a = psymb; 's -> fold (f a accu) s | -> accu} in %parser{ | a = psymb; a = fold (f a e) -> a} let sfold0sep f e entry symbl psymb psep = let failed = function | [symb; sep] -> Gentry.symb_failed_txt entry sep symb | _ -> assert false in let rec kont accu = %parser{ | () = psep; a = psymb ?? failed symbl; 's -> kont (f a accu) s | -> accu }in %parser{ | a = psymb; 's -> kont (f a e) s | -> e } FIXME this function was never used let failed = function | [symb; sep] -> Gentry.symb_failed_txt entry sep symb | _ -> assert false in let parse_top = function FIXME context | _ -> raise Streamf.NotConsumed in let rec kont accu = %parser{ | () = psep; a = %parser{ | a = psymb -> a | a = parse_top symbl -> Obj.magic a | -> raise (Streamf.Error (failed symbl)) }; 's -> kont (f a accu) s | -> accu } in %parser{ | a = psymb; 's -> kont (f a e) s}
null
https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/main/gfold.ml
ocaml
let sfold0 f e _entry _symbl psymb = let rec fold accu = %parser{ | a = psymb; 's -> fold (f a accu) s | -> accu } in %parser{| a = fold e -> a} let sfold1 f e _entry _symbl psymb = let rec fold accu = %parser{ | a = psymb; 's -> fold (f a accu) s | -> accu} in %parser{ | a = psymb; a = fold (f a e) -> a} let sfold0sep f e entry symbl psymb psep = let failed = function | [symb; sep] -> Gentry.symb_failed_txt entry sep symb | _ -> assert false in let rec kont accu = %parser{ | () = psep; a = psymb ?? failed symbl; 's -> kont (f a accu) s | -> accu }in %parser{ | a = psymb; 's -> kont (f a e) s | -> e } FIXME this function was never used let failed = function | [symb; sep] -> Gentry.symb_failed_txt entry sep symb | _ -> assert false in let parse_top = function FIXME context | _ -> raise Streamf.NotConsumed in let rec kont accu = %parser{ | () = psep; a = %parser{ | a = psymb -> a | a = parse_top symbl -> Obj.magic a | -> raise (Streamf.Error (failed symbl)) }; 's -> kont (f a accu) s | -> accu } in %parser{ | a = psymb; 's -> kont (f a e) s}
69682de144b3ab8584d087e43aa559b6d4f04c9b4665375c33f0a427c9c54d70
cirfi/sicp-my-solutions
1.11.scm
;;; recursive (define (f1 n) (cond ((< n 3) n) (else (+ (f1 (- n 1)) (* 2 (f1 (- n 2))) (* 3 (f1 (- n 3))))))) ;;; interative (define (f2 n) (define (f2-iter i r1 r2 r3) ; r: result (cond ((= i n) r1) (else (f2-iter (+ i 1) (+ r1 (* 2 r2) (* 3 r3)) r1 r2)))) (cond ((< n 3) n) (else (f2-iter 2 2 1 0))))
null
https://raw.githubusercontent.com/cirfi/sicp-my-solutions/4b6cc17391aa2c8c033b42b076a663b23aa022de/ch1/1.11.scm
scheme
recursive interative r: result
(define (f1 n) (cond ((< n 3) n) (else (+ (f1 (- n 1)) (* 2 (f1 (- n 2))) (* 3 (f1 (- n 3))))))) (define (f2 n) (cond ((= i n) r1) (else (f2-iter (+ i 1) (+ r1 (* 2 r2) (* 3 r3)) r1 r2)))) (cond ((< n 3) n) (else (f2-iter 2 2 1 0))))
f56ad04e9f5a0afdaf8069a20e8cc7a9f9da20eb0607a8f81214fef291497f66
s-expressionists/Cleavir
condition-reporters-english.lisp
(in-package #:cleavir-bir) (defmethod acclimation:report-condition ((condition unused-variable) stream (language acclimation:english)) (let ((v (variable condition))) (format stream "The variable ~a is ~a but never used." (name v) (ecase (use-status v) ((nil) "defined") ((set) "assigned"))))) (defmethod acclimation:report-condition ((condition type-conflict) stream (language acclimation:english)) (format stream "The derived type of ~:[<nameless datum>~;~:*~a~] is ~s~%but is asserted as ~s by ~a~:[~; in ~s~]." (name (datum condition)) (derived-type condition) (asserted-type condition) (asserted-by condition) (conditions:origin condition) (cst:raw (conditions:origin condition)))) (defun group-problems (problems) ;; Group by subject. Also, put function problems before iblock problems, and ;; both before instruction problems. (let ((table (make-hash-table :test #'eq))) (dolist (problem problems) (push problem (gethash (subject problem) table))) (let ((list (loop for k being the hash-keys of table using (hash-value v) collect (list* k v)))) (sort list (lambda (s1 s2) (etypecase s1 (function t) (iblock (typep s2 'instruction)) (instruction nil))) :key #'car)))) (defmethod acclimation:report-condition ((condition verification-failed) stream (language acclimation:english)) (macrolet ((dis (thing what show-ctype) `(handler-case (let ((*standard-output* stream)) (cleavir-bir-disassembler:display ,thing :show-ctype ,show-ctype)) (error (e) (format stream ,(concatenate 'string "~&! Error while disassembling " what ":~@< ~@;~a~:>") e))))) (cleavir-bir-disassembler:with-disassembly () (dis (module condition) "module" t) (format stream "~&BIR verification failed. The IR is in an inconsistent state. This probably indicates a problem in the compiler; please report it. ~@[~%Problems pertaining to the entire module:~%~< ~@;~@{~a~%~}~:>~]" (module-problems condition)) (when (function-problems condition) (loop for (function . problems) in (function-problems condition) for grouped = (group-problems problems) do (format stream "~&Problems pertaining to function ~a:~%" function) (pprint-logical-block (stream grouped :per-line-prefix " ") (loop (pprint-exit-if-list-exhausted) (destructuring-bind (subject . problems) (pprint-pop) (if (typep subject 'instruction) (dis subject "instruction" nil) (format stream "~& ~a" subject)) (fresh-line stream) (dolist (problem problems) (apply #'format stream (problem-format-control problem) (problem-format-arguments problem)) (terpri stream)))))))))) (defmethod acclimation:report-condition ((condition verification-error) stream (language acclimation:english)) (format stream "BIR verification failed due to the verifier signaling an unexpected error. This probably indicates a problem in the compiler; please report it. Error:~%~@< ~@;~a~:>" (original-condition condition)))
null
https://raw.githubusercontent.com/s-expressionists/Cleavir/560dfb6b883d8d688872e1a37393ea2779879704/BIR/condition-reporters-english.lisp
lisp
~:*~a~] in ~s~]." Group by subject. Also, put function problems before iblock problems, and both before instruction problems. please report it. ~@{~a~%~}~:>~]" please report it. ~a~:>"
(in-package #:cleavir-bir) (defmethod acclimation:report-condition ((condition unused-variable) stream (language acclimation:english)) (let ((v (variable condition))) (format stream "The variable ~a is ~a but never used." (name v) (ecase (use-status v) ((nil) "defined") ((set) "assigned"))))) (defmethod acclimation:report-condition ((condition type-conflict) stream (language acclimation:english)) is ~s~%but is asserted as ~s (name (datum condition)) (derived-type condition) (asserted-type condition) (asserted-by condition) (conditions:origin condition) (cst:raw (conditions:origin condition)))) (defun group-problems (problems) (let ((table (make-hash-table :test #'eq))) (dolist (problem problems) (push problem (gethash (subject problem) table))) (let ((list (loop for k being the hash-keys of table using (hash-value v) collect (list* k v)))) (sort list (lambda (s1 s2) (etypecase s1 (function t) (iblock (typep s2 'instruction)) (instruction nil))) :key #'car)))) (defmethod acclimation:report-condition ((condition verification-failed) stream (language acclimation:english)) (macrolet ((dis (thing what show-ctype) `(handler-case (let ((*standard-output* stream)) (cleavir-bir-disassembler:display ,thing :show-ctype ,show-ctype)) (error (e) (format stream ,(concatenate 'string "~&! Error while disassembling " what ":~@< ~@;~a~:>") e))))) (cleavir-bir-disassembler:with-disassembly () (dis (module condition) "module" t) (format stream "~&BIR verification failed. The IR is in an inconsistent state. (module-problems condition)) (when (function-problems condition) (loop for (function . problems) in (function-problems condition) for grouped = (group-problems problems) do (format stream "~&Problems pertaining to function ~a:~%" function) (pprint-logical-block (stream grouped :per-line-prefix " ") (loop (pprint-exit-if-list-exhausted) (destructuring-bind (subject . problems) (pprint-pop) (if (typep subject 'instruction) (dis subject "instruction" nil) (format stream "~& ~a" subject)) (fresh-line stream) (dolist (problem problems) (apply #'format stream (problem-format-control problem) (problem-format-arguments problem)) (terpri stream)))))))))) (defmethod acclimation:report-condition ((condition verification-error) stream (language acclimation:english)) (format stream "BIR verification failed due to the verifier signaling an unexpected error. (original-condition condition)))
a01c38161286163f505a95f7ed0caef7ea271e8f0ba3d4df2407e93f21c148a1
toddaaro/advanced-dan
ccbang.scm
;; Why does the following run? ;; More specifically, how does x know that in the future it will point to a box? (define run (lambda () (x (call/cc (lambda (k) (set! x (lambda (h) 120)) (k 'hukarz)))))) ;; answer: evaluation-order dependent behavior
null
https://raw.githubusercontent.com/toddaaro/advanced-dan/5d6c0762d998aa37774e0414a0f37404e804b536/scheme-questions/ccbang.scm
scheme
Why does the following run? More specifically, how does x know that in the future it will point to a box? answer: evaluation-order dependent behavior
(define run (lambda () (x (call/cc (lambda (k) (set! x (lambda (h) 120)) (k 'hukarz))))))
064e02a575e0e5a816fa1670bbd11567b788ea47c88445f876766fb56afc2afd
brendanhay/terrafomo
Types.hs
-- This module was auto-generated. If it is modified, it will not be overwritten. -- | -- Module : Terrafomo.DigitalOcean.Types Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- module Terrafomo.DigitalOcean.Types where import Data . Text ( Text ) import Terrafomo -- import Formatting (Format, (%)) import Terrafomo . DigitalOcean . Lens import qualified Terrafomo . Attribute as TF import qualified Terrafomo . HCL as TF import qualified Terrafomo . Name as TF import qualified Terrafomo . Provider as TF import qualified Terrafomo . Schema as TF
null
https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/provider/terrafomo-digitalocean/src/Terrafomo/DigitalOcean/Types.hs
haskell
This module was auto-generated. If it is modified, it will not be overwritten. | Module : Terrafomo.DigitalOcean.Types Stability : auto-generated import Formatting (Format, (%))
Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Terrafomo.DigitalOcean.Types where import Data . Text ( Text ) import Terrafomo import Terrafomo . DigitalOcean . Lens import qualified Terrafomo . Attribute as TF import qualified Terrafomo . HCL as TF import qualified Terrafomo . Name as TF import qualified Terrafomo . Provider as TF import qualified Terrafomo . Schema as TF
624f3bfc30ab4b2bcf7f637b2b5d02d285847a98eaab2bdd17989baa5a3578d0
tek/ribosome
GithubActions.hs
module Ribosome.App.Templates.GithubActions where import Exon (exon) import Ribosome.App.Data (Branch (Branch), Cachix (Cachix), CachixKey (CachixKey), CachixName (CachixName), ProjectName (ProjectName), cachixName, cachixTek) cachixStep :: CachixName -> Text cachixStep (CachixName name) = [exon| - uses: cachix/cachix-action@v10 with: name: #{name} signingKey: '${{ secrets.CACHIX_SIGNING_KEY }}'|] cachixConf :: Cachix -> Text cachixConf (Cachix (CachixName name) (CachixKey key)) = [exon| extra-substituters = https://#{name}.cachix.org extra-trusted-public-keys = #{key}|] ga :: ProjectName -> Maybe Cachix -> Text -> Text -> Text -> Text ga (ProjectName name) cachix actionName push release = [exon|--- name: '#{actionName}' on: push: #{push} jobs: release: name: 'Release' runs-on: ubuntu-latest steps: - uses: actions/checkout@v2.4.0 - uses: cachix/install-nix-action@v15 with: extra_nix_config: | access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}#{cachixConf (fromMaybe cachixTek cachix)}#{foldMap (cachixStep . cachixName) cachix} - name: 'build' run: nix build .#static - uses: 'marvinpinto/action-automatic-releases@latest' name: 'create release' with: repo_token: "${{ secrets.GITHUB_TOKEN }}" #{release} files: | result/bin/#{name} |] gaLatest :: ProjectName -> Branch -> Maybe Cachix -> Text gaLatest name (Branch branch) cachix = ga name cachix "latest-release" [exon|branches: - '#{branch}'|] [exon|automatic_release_tag: 'latest' prerelease: true|] gaTags :: ProjectName -> Maybe Cachix -> Text gaTags name cachix = ga name cachix "tagged-release" [exon|tags: - '*'|] [exon|prerelease: false|]
null
https://raw.githubusercontent.com/tek/ribosome/a676b4f0085916777bfdacdcc761f82d933edb80/packages/app/lib/Ribosome/App/Templates/GithubActions.hs
haskell
-
module Ribosome.App.Templates.GithubActions where import Exon (exon) import Ribosome.App.Data (Branch (Branch), Cachix (Cachix), CachixKey (CachixKey), CachixName (CachixName), ProjectName (ProjectName), cachixName, cachixTek) cachixStep :: CachixName -> Text cachixStep (CachixName name) = [exon| - uses: cachix/cachix-action@v10 with: name: #{name} signingKey: '${{ secrets.CACHIX_SIGNING_KEY }}'|] cachixConf :: Cachix -> Text cachixConf (Cachix (CachixName name) (CachixKey key)) = [exon| extra-substituters = https://#{name}.cachix.org extra-trusted-public-keys = #{key}|] ga :: ProjectName -> Maybe Cachix -> Text -> Text -> Text -> Text ga (ProjectName name) cachix actionName push release = name: '#{actionName}' on: push: #{push} jobs: release: name: 'Release' runs-on: ubuntu-latest steps: - uses: actions/checkout@v2.4.0 - uses: cachix/install-nix-action@v15 with: extra_nix_config: | access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}#{cachixConf (fromMaybe cachixTek cachix)}#{foldMap (cachixStep . cachixName) cachix} - name: 'build' run: nix build .#static - uses: 'marvinpinto/action-automatic-releases@latest' name: 'create release' with: repo_token: "${{ secrets.GITHUB_TOKEN }}" #{release} files: | result/bin/#{name} |] gaLatest :: ProjectName -> Branch -> Maybe Cachix -> Text gaLatest name (Branch branch) cachix = ga name cachix "latest-release" [exon|branches: - '#{branch}'|] [exon|automatic_release_tag: 'latest' prerelease: true|] gaTags :: ProjectName -> Maybe Cachix -> Text gaTags name cachix = ga name cachix "tagged-release" [exon|tags: - '*'|] [exon|prerelease: false|]
1b3ee6279b520eae41db55e88e97247cb0f6c2ce9942feeb4ffb8f5d15d1b667
mythical-linux/rktfetch
shell.rkt
#!/usr/bin/env racket #lang racket/base (require "helpers/basename.rkt" ) (provide get-shell) (define (get-shell) (if (getenv "SHELL") (string-upcase (basename (getenv "SHELL"))) "N/A (shell not set)" ) )
null
https://raw.githubusercontent.com/mythical-linux/rktfetch/ba4bcd57af954a23a1799fad7e01d828754ec6d1/rktfetch/private/get/shell.rkt
racket
#!/usr/bin/env racket #lang racket/base (require "helpers/basename.rkt" ) (provide get-shell) (define (get-shell) (if (getenv "SHELL") (string-upcase (basename (getenv "SHELL"))) "N/A (shell not set)" ) )
874a2fa6d6c644c4370ca4e326bef3dde1c74c6983c99fb7d4ee6c5c3708c342
heshrobe/joshua-dist
inspector.lisp
-*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Package : CLIM - ENV ; Base : 10 ; Lowercase : Yes -*- Copyright ( c ) 1994 - 2000 , . Copyright ( c ) 2001 - 2003 , and . ;;; All rights reserved. No warranty is expressed or implied. ;;; See COPYRIGHT for full copyright and terms of use. (in-package :clim-env) ;;; Object browser ;;--- This should keep a history of inspected objects ;;--- Then there should be a menu bar item that navigates this history (define-application-frame inspector-frame (selected-object-mixin) ((object :initarg :object :initform nil :accessor inspector-object) (current-pane :initform nil)) (:command-definer define-inspector-command) (:command-table (inspector :inherit-from (activity editing lisp selected-objects) :menu (("Activity" :menu activity) ("Selections" :menu selected-objects)))) (:top-level (inspector-top-level)) (:pointer-documentation t) (:panes (upper-pane :application :background +white+ :display-after-commands nil :end-of-line-action :allow :end-of-page-action :allow) (lower-pane :application :background +white+ :display-after-commands nil :end-of-line-action :allow :end-of-page-action :allow)) (:layouts (main (vertically () (:fill (vertically () (1/2 upper-pane) (1/2 lower-pane))))))) (defmethod frame-maintain-presentation-histories ((frame inspector-frame)) t) (defmethod inspector-top-level ((frame inspector-frame)) (enable-frame frame) (inspect-object frame (inspector-object frame) :use-top-pane t) (default-frame-top-level frame)) (define-presentation-type location (&key modifier) :inherit-from 'expression) (defmethod inspect-object ((frame inspector-frame) object &key use-top-pane) (let ((stream (if use-top-pane (get-frame-pane frame 'upper-pane) (get-frame-pane frame 'lower-pane))) (*print-length* 5) (*print-level* 3)) (cond (use-top-pane (window-clear stream) (window-clear (get-frame-pane frame 'lower-pane))) (t (let* ((pane (get-frame-pane frame 'lower-pane)) (line-height (stream-line-height pane))) (multiple-value-bind (x y) (stream-cursor-position pane) (declare (ignore x)) (terpri pane) (terpri pane) (window-set-viewport-position pane 0 (- y (* 2 line-height))))) )) #+Genera (when (si:named-structure-p object) ;; Generate a list of all of the structures slots (let* ((description (get (or (and (arrayp object) (si:named-structure-symbol object)) (and (listp object) (symbolp (car object)) (car object))) 'si:defstruct-description))) (formatting-table (stream :x-spacing '(2 :character)) (loop for (slot-name . slot-description) in (si:defstruct-description-slot-alist description) as form = `(,(si:defstruct-slot-description-ref-macro-name slot-description) ',object) do (formatting-row (stream) (formatting-cell (stream :align-x :right) (format stream "~A:" slot-name)) (formatting-cell (stream :align-x :left) (present (eval form) 'location :single-box :highlighting :stream stream)))))) (return-from inspect-object)) #+Genera (when (si:instancep object) (display-standard-object (si:follow-structure-forwarding object) stream) (return-from inspect-object)) (display-object object stream))) (defmethod display-object ((object symbol) stream) (formatting-table (stream :x-spacing '(2 :character) :move-cursor t) (flet ((print-property (name reader &optional tester) (formatting-row (stream) (formatting-cell (stream) (write-string name stream)) (formatting-cell (stream) (if (or (null tester) (funcall tester object)) (present (funcall reader object) 'location :single-box :highlighting :stream stream) (with-text-face (stream :italic) (write-string "unbound" stream))))))) (declare (dynamic-extent #'print-property)) (print-property "Name:" 'symbol-name) (print-property "Value:" 'symbol-value 'boundp) (print-property "Function:" 'symbol-function 'fboundp) (print-property "Plist:" 'symbol-plist) (print-property "Package:" 'symbol-package)))) (defmethod display-object ((object cons) stream) (let ((*print-length* nil) (*print-level* 3) (*print-circle* t)) (present object 'location ;--- modifier? :single-box :highlighting :stream stream))) (defmethod display-object ((object string) stream) (present object 'location :single-box :highlighting :stream stream)) (defmethod display-object ((object vector) stream) (formatting-table (stream :x-spacing '(2 :character) :move-cursor t) (let ((index -1)) (map nil #'(lambda (elt) (formatting-row (stream) (formatting-cell (stream :align-x :right) (format stream "~D:" (incf index))) (formatting-cell (stream) ;--- modifier? (present elt 'location :stream stream)))) object)))) (defmethod display-object ((object array) stream) (let ((*print-array* t)) (present object 'location ;--- modifier? :single-box :highlighting :stream stream))) (defmethod display-object ((object hash-table) stream) (formatting-table (stream :x-spacing '(2 :character) :move-cursor t) (maphash #'(lambda (key val) (formatting-row (stream) (formatting-cell (stream :align-x :right) (format stream "~S:" key)) (formatting-cell (stream) (present val 'location :stream stream)))) object))) (defmethod display-object ((object standard-object) stream) (display-standard-object object stream)) (defmethod display-standard-object (object stream) (let* ((class (class-of object)) (slots (copy-list (append (class-instance-slots class) (class-class-slots class))))) (setq slots (sort slots #'string-lessp :key #'(lambda (s) (symbol-name (slot-definition-name s))))) (formatting-table (stream :x-spacing '(2 :character) :move-cursor t) (loop for slot in slots as slot-name = (slot-definition-name slot) do (formatting-row (stream) (formatting-cell (stream :align-x :right) (format stream "~A:" slot-name)) (formatting-cell (stream :align-x :left) (if (slot-boundp object slot-name) (let ((slot-name slot-name)) ;don't share this (flet ((modifier (new-value) (setf (slot-value object slot-name) new-value))) (present (slot-value object slot-name) `(location :modifier ,#'modifier) :single-box :highlighting :stream stream))) (with-text-face (stream :italic) (write-string "unbound" stream))))))))) #-(or Genera Lispworks Allegro) (defmethod display-object ((object structure-object) stream) (display-standard-object object stream)) #+Lispworks (defmethod display-object ((object structure-object) stream) (let* ((wrapper (clos::class-wrapper (class-of object))) (slots (copy-list (structure::dd-slots wrapper)))) (setq slots (sort slots #'string-lessp :key #'(lambda (s) (symbol-name (structure::dsd-name s))))) (formatting-table (stream :x-spacing '(2 :character) :move-cursor t) (dolist (slot slots) (formatting-row (stream) (formatting-cell (stream) (format stream "~A:" (structure::dsd-name slot))) (formatting-cell (stream) (let ((slot slot)) ;don't share this (flet ((modifier (new-value) (setf (funcall (structure::dsd-accessor slot) object) new-value))) (present (funcall (structure::dsd-accessor slot) object) `(location :modifier ,#'modifier) :single-box :highlighting :stream stream))))))))) #+Allegro (defmethod display-object ((object structure-object) stream) (let* ((type (excl::structure-ref object 0)) desc) (when (consp type) (setq type (caar type))) (setq desc (get type 'excl::%structure-definition)) (when desc (let ((slots (loop for slot in (nreverse (excl::object-instance-slot-names object)) for i upfrom 1 collect (cons slot i)))) (setq slots (sort slots #'string-lessp :key #'car)) (formatting-table (stream :x-spacing '(2 :character) :move-cursor t) (loop for (name . index) in slots doing (formatting-row (stream) (formatting-cell (stream) (format stream "~A:" name)) (formatting-cell (stream) (present (excl::structure-ref object index) 'expression :single-box :highlighting :stream stream))))))))) ;;--- Should numbers display anything special? What else? (defmethod display-object ((object t) stream) (present object 'location :single-box :highlighting :stream stream)) (define-inspector-command (com-clear :name t :menu t) () (let ((frame *application-frame*)) (window-clear (get-frame-pane frame 'lower-pane)))) (define-inspector-command (com-inspect-object :name t) ((object '((expression) :auto-activate t) :gesture :select)) (inspect-object *application-frame* object)) (define-inspector-command (com-menu-inspect-object :menu "Inspect") () (with-application-frame (frame) (let* ((stream (frame-standard-input frame)) (default (inspector-object frame)) (object (accepting-values (stream :own-window t :resynchronize-every-pass t :width 500 :height 50) (setq default (eval (accept 'expression :stream stream :default default :prompt "Expression")))))) (inspect-object frame object)))) (define-inspector-command com-modify-location ((old-value 't) (modifier 't)) (with-application-frame (frame) (let* ((stream (frame-standard-input frame)) (value old-value) (new-value (accepting-values (stream :own-window t :resynchronize-every-pass t :width 500 :height 50) (setq value (eval (accept 'expression :stream stream :default value :prompt "New value")))))) (funcall modifier (eval new-value))))) (define-presentation-to-command-translator modify-location (location com-modify-location inspector :gesture :modify :documentation "Modify this location" :tester ((presentation) (with-presentation-type-parameters (location (presentation-type presentation)) (and modifier (not (eq modifier '*)))))) (object presentation) (with-presentation-type-parameters (location (presentation-type presentation)) (list object modifier)))
null
https://raw.githubusercontent.com/heshrobe/joshua-dist/f59f06303f9fabef3e945a920cf9a26d9c2fd55e/clim-env/portable-lisp-environment/inspector.lisp
lisp
Syntax : ANSI - Common - Lisp ; Package : CLIM - ENV ; Base : 10 ; Lowercase : Yes -*- All rights reserved. No warranty is expressed or implied. See COPYRIGHT for full copyright and terms of use. Object browser --- This should keep a history of inspected objects --- Then there should be a menu bar item that navigates this history Generate a list of all of the structures slots --- modifier? --- modifier? --- modifier? don't share this don't share this --- Should numbers display anything special? What else?
Copyright ( c ) 1994 - 2000 , . Copyright ( c ) 2001 - 2003 , and . (in-package :clim-env) (define-application-frame inspector-frame (selected-object-mixin) ((object :initarg :object :initform nil :accessor inspector-object) (current-pane :initform nil)) (:command-definer define-inspector-command) (:command-table (inspector :inherit-from (activity editing lisp selected-objects) :menu (("Activity" :menu activity) ("Selections" :menu selected-objects)))) (:top-level (inspector-top-level)) (:pointer-documentation t) (:panes (upper-pane :application :background +white+ :display-after-commands nil :end-of-line-action :allow :end-of-page-action :allow) (lower-pane :application :background +white+ :display-after-commands nil :end-of-line-action :allow :end-of-page-action :allow)) (:layouts (main (vertically () (:fill (vertically () (1/2 upper-pane) (1/2 lower-pane))))))) (defmethod frame-maintain-presentation-histories ((frame inspector-frame)) t) (defmethod inspector-top-level ((frame inspector-frame)) (enable-frame frame) (inspect-object frame (inspector-object frame) :use-top-pane t) (default-frame-top-level frame)) (define-presentation-type location (&key modifier) :inherit-from 'expression) (defmethod inspect-object ((frame inspector-frame) object &key use-top-pane) (let ((stream (if use-top-pane (get-frame-pane frame 'upper-pane) (get-frame-pane frame 'lower-pane))) (*print-length* 5) (*print-level* 3)) (cond (use-top-pane (window-clear stream) (window-clear (get-frame-pane frame 'lower-pane))) (t (let* ((pane (get-frame-pane frame 'lower-pane)) (line-height (stream-line-height pane))) (multiple-value-bind (x y) (stream-cursor-position pane) (declare (ignore x)) (terpri pane) (terpri pane) (window-set-viewport-position pane 0 (- y (* 2 line-height))))) )) #+Genera (when (si:named-structure-p object) (let* ((description (get (or (and (arrayp object) (si:named-structure-symbol object)) (and (listp object) (symbolp (car object)) (car object))) 'si:defstruct-description))) (formatting-table (stream :x-spacing '(2 :character)) (loop for (slot-name . slot-description) in (si:defstruct-description-slot-alist description) as form = `(,(si:defstruct-slot-description-ref-macro-name slot-description) ',object) do (formatting-row (stream) (formatting-cell (stream :align-x :right) (format stream "~A:" slot-name)) (formatting-cell (stream :align-x :left) (present (eval form) 'location :single-box :highlighting :stream stream)))))) (return-from inspect-object)) #+Genera (when (si:instancep object) (display-standard-object (si:follow-structure-forwarding object) stream) (return-from inspect-object)) (display-object object stream))) (defmethod display-object ((object symbol) stream) (formatting-table (stream :x-spacing '(2 :character) :move-cursor t) (flet ((print-property (name reader &optional tester) (formatting-row (stream) (formatting-cell (stream) (write-string name stream)) (formatting-cell (stream) (if (or (null tester) (funcall tester object)) (present (funcall reader object) 'location :single-box :highlighting :stream stream) (with-text-face (stream :italic) (write-string "unbound" stream))))))) (declare (dynamic-extent #'print-property)) (print-property "Name:" 'symbol-name) (print-property "Value:" 'symbol-value 'boundp) (print-property "Function:" 'symbol-function 'fboundp) (print-property "Plist:" 'symbol-plist) (print-property "Package:" 'symbol-package)))) (defmethod display-object ((object cons) stream) (let ((*print-length* nil) (*print-level* 3) (*print-circle* t)) :single-box :highlighting :stream stream))) (defmethod display-object ((object string) stream) (present object 'location :single-box :highlighting :stream stream)) (defmethod display-object ((object vector) stream) (formatting-table (stream :x-spacing '(2 :character) :move-cursor t) (let ((index -1)) (map nil #'(lambda (elt) (formatting-row (stream) (formatting-cell (stream :align-x :right) (format stream "~D:" (incf index))) (present elt 'location :stream stream)))) object)))) (defmethod display-object ((object array) stream) (let ((*print-array* t)) :single-box :highlighting :stream stream))) (defmethod display-object ((object hash-table) stream) (formatting-table (stream :x-spacing '(2 :character) :move-cursor t) (maphash #'(lambda (key val) (formatting-row (stream) (formatting-cell (stream :align-x :right) (format stream "~S:" key)) (formatting-cell (stream) (present val 'location :stream stream)))) object))) (defmethod display-object ((object standard-object) stream) (display-standard-object object stream)) (defmethod display-standard-object (object stream) (let* ((class (class-of object)) (slots (copy-list (append (class-instance-slots class) (class-class-slots class))))) (setq slots (sort slots #'string-lessp :key #'(lambda (s) (symbol-name (slot-definition-name s))))) (formatting-table (stream :x-spacing '(2 :character) :move-cursor t) (loop for slot in slots as slot-name = (slot-definition-name slot) do (formatting-row (stream) (formatting-cell (stream :align-x :right) (format stream "~A:" slot-name)) (formatting-cell (stream :align-x :left) (if (slot-boundp object slot-name) (flet ((modifier (new-value) (setf (slot-value object slot-name) new-value))) (present (slot-value object slot-name) `(location :modifier ,#'modifier) :single-box :highlighting :stream stream))) (with-text-face (stream :italic) (write-string "unbound" stream))))))))) #-(or Genera Lispworks Allegro) (defmethod display-object ((object structure-object) stream) (display-standard-object object stream)) #+Lispworks (defmethod display-object ((object structure-object) stream) (let* ((wrapper (clos::class-wrapper (class-of object))) (slots (copy-list (structure::dd-slots wrapper)))) (setq slots (sort slots #'string-lessp :key #'(lambda (s) (symbol-name (structure::dsd-name s))))) (formatting-table (stream :x-spacing '(2 :character) :move-cursor t) (dolist (slot slots) (formatting-row (stream) (formatting-cell (stream) (format stream "~A:" (structure::dsd-name slot))) (formatting-cell (stream) (flet ((modifier (new-value) (setf (funcall (structure::dsd-accessor slot) object) new-value))) (present (funcall (structure::dsd-accessor slot) object) `(location :modifier ,#'modifier) :single-box :highlighting :stream stream))))))))) #+Allegro (defmethod display-object ((object structure-object) stream) (let* ((type (excl::structure-ref object 0)) desc) (when (consp type) (setq type (caar type))) (setq desc (get type 'excl::%structure-definition)) (when desc (let ((slots (loop for slot in (nreverse (excl::object-instance-slot-names object)) for i upfrom 1 collect (cons slot i)))) (setq slots (sort slots #'string-lessp :key #'car)) (formatting-table (stream :x-spacing '(2 :character) :move-cursor t) (loop for (name . index) in slots doing (formatting-row (stream) (formatting-cell (stream) (format stream "~A:" name)) (formatting-cell (stream) (present (excl::structure-ref object index) 'expression :single-box :highlighting :stream stream))))))))) (defmethod display-object ((object t) stream) (present object 'location :single-box :highlighting :stream stream)) (define-inspector-command (com-clear :name t :menu t) () (let ((frame *application-frame*)) (window-clear (get-frame-pane frame 'lower-pane)))) (define-inspector-command (com-inspect-object :name t) ((object '((expression) :auto-activate t) :gesture :select)) (inspect-object *application-frame* object)) (define-inspector-command (com-menu-inspect-object :menu "Inspect") () (with-application-frame (frame) (let* ((stream (frame-standard-input frame)) (default (inspector-object frame)) (object (accepting-values (stream :own-window t :resynchronize-every-pass t :width 500 :height 50) (setq default (eval (accept 'expression :stream stream :default default :prompt "Expression")))))) (inspect-object frame object)))) (define-inspector-command com-modify-location ((old-value 't) (modifier 't)) (with-application-frame (frame) (let* ((stream (frame-standard-input frame)) (value old-value) (new-value (accepting-values (stream :own-window t :resynchronize-every-pass t :width 500 :height 50) (setq value (eval (accept 'expression :stream stream :default value :prompt "New value")))))) (funcall modifier (eval new-value))))) (define-presentation-to-command-translator modify-location (location com-modify-location inspector :gesture :modify :documentation "Modify this location" :tester ((presentation) (with-presentation-type-parameters (location (presentation-type presentation)) (and modifier (not (eq modifier '*)))))) (object presentation) (with-presentation-type-parameters (location (presentation-type presentation)) (list object modifier)))
f29be8ce95edd8186b1854bf95e0a6290535405c3f5bbc5aaabbfd9d6501049f
tonsky/advent-of-code
day17_gui.clj
(ns advent-of-code.year2018.day17-gui (:require [advent-of-code.core :refer [cond+]] [advent-of-code.year2018.day17 :as day17] [clojure.java.io :as io] [clojure.java.math :as math] [clojure.string :as str] [clojure.set :as set] [io.github.humbleui.core :as hui] [io.github.humbleui.window :as window] [nrepl.cmdline :as nrepl]) (:import ; [advent_of_code.year2018.day17 Pos Unit Game] [java.nio.file Files Path] [java.util Arrays BitSet] [io.github.humbleui.skija Canvas Font Image Paint Rect])) (defonce *window (atom nil)) (def *map (atom (day17/parse day17/example))) (add-watch *map :redraw (fn [_ _ _ map] (window/request-frame @*window))) (defn pixel-size [ww wh mw mh] (loop [p 2] (let [cols (inc (quot (dec (* mh p)) wh))] (if (> (* cols (+ mw 1) p) ww) (dec p) (recur (inc p)))))) (defn on-paint [window ^Canvas canvas map] (.clear canvas (unchecked-int 0xFFEEEEEE)) (let [bounds (.getContentRect (window/jwm-window window)) pixel-size (pixel-size (.getWidth bounds) (.getHeight bounds) (:width map) (:height map)) cols (inc (quot (dec (* (:height map) pixel-size)) (.getWidth bounds))) rows (-> (:height map) (/ cols) (math/ceil) long)] (.translate canvas (-> (.getWidth bounds) (- (* (inc (:width map)) cols pixel-size)) (quot 2)) (-> (.getHeight bounds) (- (* rows pixel-size)) (quot 2))) (.scale canvas pixel-size pixel-size) (with-open [paint (Paint.)] (.setColor paint (unchecked-int 0xFFE9C46A)) (doseq [col (range 0 cols)] (if (< col (dec cols)) (.drawRect canvas (Rect/makeXYWH (* col (inc (:width map))) 0 (:width map) rows) paint) (.drawRect canvas (Rect/makeXYWH (* col (inc (:width map))) 0 (:width map) (inc (mod (dec (:height map)) rows))) paint))) (doseq [dy (range 0 (:height map)) dx (range 0 (:width map)) :let [y (+ dy (:ymin map)) x (+ dx (:xmin map)) val (day17/map-get map x y)]] (condp = val day17/CLAY (.setColor paint (unchecked-int 0xFF7F5539)) day17/WATER (.setColor paint (unchecked-int 0xFF023e8a)) day17/DRY (.setColor paint (unchecked-int 0xFFe6ccb2)) nil) (when (not= val day17/SAND) (let [col (quot dy rows) dx' (+ dx (* col (inc (:width map)))) dy' (mod dy rows)] (.drawRect canvas (Rect/makeXYWH dx' dy' 1 1) paint)))) (.setColor paint (unchecked-int 0xFF3A86FF)) (doseq [[x y] (:sources map) :let [dx (- x (:xmin map)) dy (- y (:ymin map)) col (quot dy rows) dx' (+ dx (* col (inc (:width map)))) dy' (mod dy rows)]] (.drawRect canvas (Rect/makeXYWH (+ dx' 0.25) (+ 0.25 dy') 0.5 0.5) paint))))) (comment (window/request-frame @*window)) (defn make-window [] (let [w (window/make {:on-close (fn [_] (reset! *window nil)) :on-paint (fn [window ^Canvas canvas] (let [layer (.save canvas)] (try (let [on-paint (resolve `on-paint) *map (resolve `*map)] (@on-paint window canvas @@*map) #_(window/request-frame window)) (catch Exception e (.printStackTrace e) (.clear canvas (unchecked-int 0xFFCC3333)))) (.restoreToCount canvas layer)))})] (window/set-title w "Reservoir Research") (.setContentSize (window/jwm-window w) 1000 1000) ; (.setWindowPosition (window/jwm-window w) 2836 632) ( .setWindowSize ( window / jwm - window w ) 1320 1520 ) ; (window/set-z-order w :floating) (window/set-visible w true) (window/request-frame w) w)) (defn -main [& args] (future (apply nrepl/-main args)) (hui/init) (reset! *window (make-window)) (hui/start)) (comment (do (set! *warn-on-reflection* true) (require 'advent-of-code.year2018.day17 :reload-all)) (hui/doui (window/close @*window)) (reset! *window (hui/doui (make-window))) (window/request-frame @*window) (.getHeight (.getWindowRect (window/jwm-window @*window))) (hui/doui (window/set-z-order @*window :normal)) (hui/doui (window/set-z-order @*window :floating)) (reset! *map (day17/parse day17/example2)) (swap! *map day17/step) (day17/part1 day17/example2 {:on-turn #(do (reset! *map %) (Thread/sleep 50))}) (day17/part1 day17/problem {:on-turn #(reset! *map %)}))
null
https://raw.githubusercontent.com/tonsky/advent-of-code/3efb9627c7c8b0d1a3690f4ec0231198a44706fb/src/advent_of_code/year2018/day17_gui.clj
clojure
[advent_of_code.year2018.day17 Pos Unit Game] (.setWindowPosition (window/jwm-window w) 2836 632) (window/set-z-order w :floating)
(ns advent-of-code.year2018.day17-gui (:require [advent-of-code.core :refer [cond+]] [advent-of-code.year2018.day17 :as day17] [clojure.java.io :as io] [clojure.java.math :as math] [clojure.string :as str] [clojure.set :as set] [io.github.humbleui.core :as hui] [io.github.humbleui.window :as window] [nrepl.cmdline :as nrepl]) (:import [java.nio.file Files Path] [java.util Arrays BitSet] [io.github.humbleui.skija Canvas Font Image Paint Rect])) (defonce *window (atom nil)) (def *map (atom (day17/parse day17/example))) (add-watch *map :redraw (fn [_ _ _ map] (window/request-frame @*window))) (defn pixel-size [ww wh mw mh] (loop [p 2] (let [cols (inc (quot (dec (* mh p)) wh))] (if (> (* cols (+ mw 1) p) ww) (dec p) (recur (inc p)))))) (defn on-paint [window ^Canvas canvas map] (.clear canvas (unchecked-int 0xFFEEEEEE)) (let [bounds (.getContentRect (window/jwm-window window)) pixel-size (pixel-size (.getWidth bounds) (.getHeight bounds) (:width map) (:height map)) cols (inc (quot (dec (* (:height map) pixel-size)) (.getWidth bounds))) rows (-> (:height map) (/ cols) (math/ceil) long)] (.translate canvas (-> (.getWidth bounds) (- (* (inc (:width map)) cols pixel-size)) (quot 2)) (-> (.getHeight bounds) (- (* rows pixel-size)) (quot 2))) (.scale canvas pixel-size pixel-size) (with-open [paint (Paint.)] (.setColor paint (unchecked-int 0xFFE9C46A)) (doseq [col (range 0 cols)] (if (< col (dec cols)) (.drawRect canvas (Rect/makeXYWH (* col (inc (:width map))) 0 (:width map) rows) paint) (.drawRect canvas (Rect/makeXYWH (* col (inc (:width map))) 0 (:width map) (inc (mod (dec (:height map)) rows))) paint))) (doseq [dy (range 0 (:height map)) dx (range 0 (:width map)) :let [y (+ dy (:ymin map)) x (+ dx (:xmin map)) val (day17/map-get map x y)]] (condp = val day17/CLAY (.setColor paint (unchecked-int 0xFF7F5539)) day17/WATER (.setColor paint (unchecked-int 0xFF023e8a)) day17/DRY (.setColor paint (unchecked-int 0xFFe6ccb2)) nil) (when (not= val day17/SAND) (let [col (quot dy rows) dx' (+ dx (* col (inc (:width map)))) dy' (mod dy rows)] (.drawRect canvas (Rect/makeXYWH dx' dy' 1 1) paint)))) (.setColor paint (unchecked-int 0xFF3A86FF)) (doseq [[x y] (:sources map) :let [dx (- x (:xmin map)) dy (- y (:ymin map)) col (quot dy rows) dx' (+ dx (* col (inc (:width map)))) dy' (mod dy rows)]] (.drawRect canvas (Rect/makeXYWH (+ dx' 0.25) (+ 0.25 dy') 0.5 0.5) paint))))) (comment (window/request-frame @*window)) (defn make-window [] (let [w (window/make {:on-close (fn [_] (reset! *window nil)) :on-paint (fn [window ^Canvas canvas] (let [layer (.save canvas)] (try (let [on-paint (resolve `on-paint) *map (resolve `*map)] (@on-paint window canvas @@*map) #_(window/request-frame window)) (catch Exception e (.printStackTrace e) (.clear canvas (unchecked-int 0xFFCC3333)))) (.restoreToCount canvas layer)))})] (window/set-title w "Reservoir Research") (.setContentSize (window/jwm-window w) 1000 1000) ( .setWindowSize ( window / jwm - window w ) 1320 1520 ) (window/set-visible w true) (window/request-frame w) w)) (defn -main [& args] (future (apply nrepl/-main args)) (hui/init) (reset! *window (make-window)) (hui/start)) (comment (do (set! *warn-on-reflection* true) (require 'advent-of-code.year2018.day17 :reload-all)) (hui/doui (window/close @*window)) (reset! *window (hui/doui (make-window))) (window/request-frame @*window) (.getHeight (.getWindowRect (window/jwm-window @*window))) (hui/doui (window/set-z-order @*window :normal)) (hui/doui (window/set-z-order @*window :floating)) (reset! *map (day17/parse day17/example2)) (swap! *map day17/step) (day17/part1 day17/example2 {:on-turn #(do (reset! *map %) (Thread/sleep 50))}) (day17/part1 day17/problem {:on-turn #(reset! *map %)}))
6298ddf10ffb1abfefca1ee275e289854790b9785a1f7efd538eff3ce3bc7908
shayne-fletcher/zen
factorion.ml
let string_of_list l = String.concat " " (List.map string_of_int l) (*[fact n] computes the factorial of the natural number [n]*) let rec factorial (n : int) : int = if n <= 1 then 1 else n * factorial (n - 1) [ digits n ] computes a list of the base 10 digits of the natural number n number n*) let digits n = let rec loop acc k = let k' = k / 10 in let rem = k mod 10 in let acc' = rem :: acc in if k' = 0 then acc' else loop acc' k' in loop [] n A factorion is a natural number that equals the sum of the factorials of its decimal digits . For example , 145 is a factorion because 1 ! + 4 ! + 5 ! = 1 + 24 + 120 = 145 . factorials of its decimal digits. For example, 145 is a factorion because 1! + 4! + 5! = 1 + 24 + 120 = 145. *) [ is_factorian n ] returns [ true ] if [ n ] is a factorian otherwise [ false ] let is_factorian n = List.fold_left (fun x y -> x + y) 0 (List.map factorial (digits n)) = n (*[range start until] computes the list of numbers from [start] up-to but not including [until]*) let range start until = let rec loop acc k = if k < start then acc else loop (k :: acc) (k - 1) in loop [] (until - 1) (*[insert n ns] adds [n] to [ns] if it isn't already there*) let insert ns n = if List.mem n ns then ns else n :: ns A number is said to be " pandigital " if it contains each of the digits from 0 to 9 ( and whose leading digit must be nonzero ) digits from 0 to 9 (and whose leading digit must be nonzero)*) let pandigital n = let (h :: ns) = digits n in let l = List.sort (Pervasives.compare) (List.fold_left insert [] (h :: ns)) in h <> 0 && (l = range 0 10) let gather ls = List.fold_left (fun acc d -> (List.filter (fun x -> x = d) ls) :: acc) [] (List.fold_left (fun ns n -> if List.mem n ns then ns else n :: ns) [] ls) let gather ls = First , compute a list of all of the distinct elements in [ ls ] . For example , if [ ls ] is the list [ ' a ' ; ' a ' ; ' b ' ; ' b ' ; ' c ' ; ' a ' ; ' b ' ; ' a ' ] , then the distinct elements form the list [ ' a ' ; ' b ' ; ' c ' ; 'd ' ] example, if [ls] is the list ['a'; 'a'; 'b'; 'b'; 'c'; 'a'; 'b'; 'a'], then the distinct elements form the list ['a'; 'b'; 'c'; 'd']*) let ds = List.fold_left insert [] ls in (*Now, we consider each distinct element in turn and for each we compute a list by filtering out the occurences of that element from [ls] and add the resulting list to the list of lists [acc]*) let f acc d = (List.filter (fun x -> x = d) ls) :: acc in List.fold_left f [] ds [ partition p ls ] computes two lists : a list of the elements in [ ls ] that satisfy [ p ] and a list of the elements in [ ls ] that do n't that satisfy [p] and a list of the elements in [ls] that don't*) let partition p ls = let rec loop (xs, ys) = function | [] -> (xs, ys) | (h :: tl) -> loop (if p h then (h :: xs, ys) else (xs, h ::ys)) tl in loop ([], []) ls (*[gather ls] produces a list of list of the distinct items of [ls] gathered together*) let gather ls = let rec loop acc = function | [] -> acc | (h :: _) as s -> let (xs, rem) = partition (fun x -> x = h) s in loop (xs :: acc) rem in loop [] ls (*[bin_count ls] produces a list of the unique elements of [ls] together with a count of their occurences*) let bin_count ls = let rec loop acc = function | [] -> acc | (h :: _) as s -> let (xs, rem) = partition (fun x -> x = h) s in loop ((h, (List.length xs)) :: acc) rem in loop [] ls (*Final versions. Forget tail recursion, go for elegance*) let rec partition (p : 'a -> bool) : 'a list -> 'a list * 'a list = function | [] -> ([], []) | (h :: tl) -> let xs, ys = partition p tl in if p h then (h :: xs, ys) else (xs, h :: ys) let rec gather : 'a list -> 'a list list = function | [] -> [] | (h :: _) as ls -> let xs, ys = partition (fun x -> x = h) ls in xs :: gather ys let rec bin_count : 'a list -> ('a * int) list = function | [] -> [] | (h :: _) as ls -> let xs, ys = partition (fun x -> x = h) ls in (h, List.length xs) :: bin_count ys
null
https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/binary_search/factorion.ml
ocaml
[fact n] computes the factorial of the natural number [n] [range start until] computes the list of numbers from [start] up-to but not including [until] [insert n ns] adds [n] to [ns] if it isn't already there Now, we consider each distinct element in turn and for each we compute a list by filtering out the occurences of that element from [ls] and add the resulting list to the list of lists [acc] [gather ls] produces a list of list of the distinct items of [ls] gathered together [bin_count ls] produces a list of the unique elements of [ls] together with a count of their occurences Final versions. Forget tail recursion, go for elegance
let string_of_list l = String.concat " " (List.map string_of_int l) let rec factorial (n : int) : int = if n <= 1 then 1 else n * factorial (n - 1) [ digits n ] computes a list of the base 10 digits of the natural number n number n*) let digits n = let rec loop acc k = let k' = k / 10 in let rem = k mod 10 in let acc' = rem :: acc in if k' = 0 then acc' else loop acc' k' in loop [] n A factorion is a natural number that equals the sum of the factorials of its decimal digits . For example , 145 is a factorion because 1 ! + 4 ! + 5 ! = 1 + 24 + 120 = 145 . factorials of its decimal digits. For example, 145 is a factorion because 1! + 4! + 5! = 1 + 24 + 120 = 145. *) [ is_factorian n ] returns [ true ] if [ n ] is a factorian otherwise [ false ] let is_factorian n = List.fold_left (fun x y -> x + y) 0 (List.map factorial (digits n)) = n let range start until = let rec loop acc k = if k < start then acc else loop (k :: acc) (k - 1) in loop [] (until - 1) let insert ns n = if List.mem n ns then ns else n :: ns A number is said to be " pandigital " if it contains each of the digits from 0 to 9 ( and whose leading digit must be nonzero ) digits from 0 to 9 (and whose leading digit must be nonzero)*) let pandigital n = let (h :: ns) = digits n in let l = List.sort (Pervasives.compare) (List.fold_left insert [] (h :: ns)) in h <> 0 && (l = range 0 10) let gather ls = List.fold_left (fun acc d -> (List.filter (fun x -> x = d) ls) :: acc) [] (List.fold_left (fun ns n -> if List.mem n ns then ns else n :: ns) [] ls) let gather ls = First , compute a list of all of the distinct elements in [ ls ] . For example , if [ ls ] is the list [ ' a ' ; ' a ' ; ' b ' ; ' b ' ; ' c ' ; ' a ' ; ' b ' ; ' a ' ] , then the distinct elements form the list [ ' a ' ; ' b ' ; ' c ' ; 'd ' ] example, if [ls] is the list ['a'; 'a'; 'b'; 'b'; 'c'; 'a'; 'b'; 'a'], then the distinct elements form the list ['a'; 'b'; 'c'; 'd']*) let ds = List.fold_left insert [] ls in let f acc d = (List.filter (fun x -> x = d) ls) :: acc in List.fold_left f [] ds [ partition p ls ] computes two lists : a list of the elements in [ ls ] that satisfy [ p ] and a list of the elements in [ ls ] that do n't that satisfy [p] and a list of the elements in [ls] that don't*) let partition p ls = let rec loop (xs, ys) = function | [] -> (xs, ys) | (h :: tl) -> loop (if p h then (h :: xs, ys) else (xs, h ::ys)) tl in loop ([], []) ls let gather ls = let rec loop acc = function | [] -> acc | (h :: _) as s -> let (xs, rem) = partition (fun x -> x = h) s in loop (xs :: acc) rem in loop [] ls let bin_count ls = let rec loop acc = function | [] -> acc | (h :: _) as s -> let (xs, rem) = partition (fun x -> x = h) s in loop ((h, (List.length xs)) :: acc) rem in loop [] ls let rec partition (p : 'a -> bool) : 'a list -> 'a list * 'a list = function | [] -> ([], []) | (h :: tl) -> let xs, ys = partition p tl in if p h then (h :: xs, ys) else (xs, h :: ys) let rec gather : 'a list -> 'a list list = function | [] -> [] | (h :: _) as ls -> let xs, ys = partition (fun x -> x = h) ls in xs :: gather ys let rec bin_count : 'a list -> ('a * int) list = function | [] -> [] | (h :: _) as ls -> let xs, ys = partition (fun x -> x = h) ls in (h, List.length xs) :: bin_count ys
b764ecad6f98057bb5df8ac3cfe43ee13bbb4012c8abdf9003281601ad747336
jabber-at/ejabberd
ejabberd_captcha.erl
%%%------------------------------------------------------------------- %%% File : ejabberd_captcha.erl Author : < > %%% Purpose : CAPTCHA processing. Created : 26 Apr 2008 by < > %%% %%% ejabberd , Copyright ( C ) 2002 - 2018 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(ejabberd_captcha). -behaviour(ejabberd_config). -protocol({xep, 158, '1.0'}). -behaviour(gen_server). %% API -export([start_link/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([create_captcha/6, build_captcha_html/2, check_captcha/2, process_reply/1, process/2, is_feature_available/0, create_captcha_x/5, opt_type/1, host_up/1, host_down/1, config_reloaded/0, process_iq/1]). -include("xmpp.hrl"). -include("logger.hrl"). -include("ejabberd_http.hrl"). -define(CAPTCHA_LIFETIME, 120000). -define(LIMIT_PERIOD, 60*1000*1000). -type image_error() :: efbig | enodata | limit | malformed_image | timeout. -record(state, {limits = treap:empty() :: treap:treap(), enabled = false :: boolean()}). -record(captcha, {id :: binary(), pid :: pid() | undefined, key :: binary(), tref :: reference(), args :: any()}). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). -spec captcha_text(undefined | binary()) -> binary(). captcha_text(Lang) -> translate:translate(Lang, <<"Enter the text you see">>). -spec mk_ocr_field(binary() | undefined, binary(), binary()) -> xdata_field(). mk_ocr_field(Lang, CID, Type) -> URI = #media_uri{type = Type, uri = <<"cid:", CID/binary>>}, #xdata_field{var = <<"ocr">>, type = 'text-single', label = captcha_text(Lang), required = true, sub_els = [#media{uri = [URI]}]}. mk_field(Type, Var, Value) -> #xdata_field{type = Type, var = Var, values = [Value]}. -spec create_captcha(binary(), jid(), jid(), binary(), any(), any()) -> {error, image_error()} | {ok, binary(), [text()], [xmlel()]}. create_captcha(SID, From, To, Lang, Limiter, Args) -> case create_image(Limiter) of {ok, Type, Key, Image} -> Id = <<(p1_rand:get_string())/binary>>, JID = jid:encode(From), CID = <<"sha1+", (str:sha(Image))/binary, "@bob.xmpp.org">>, Data = #bob_data{cid = CID, 'max-age' = 0, type = Type, data = Image}, Fs = [mk_field(hidden, <<"FORM_TYPE">>, ?NS_CAPTCHA), mk_field(hidden, <<"from">>, jid:encode(To)), mk_field(hidden, <<"challenge">>, Id), mk_field(hidden, <<"sid">>, SID), mk_ocr_field(Lang, CID, Type)], X = #xdata{type = form, fields = Fs}, Captcha = #xcaptcha{xdata = X}, BodyString = {<<"Your messages to ~s are being blocked. " "To unblock them, visit ~s">>, [JID, get_url(Id)]}, Body = xmpp:mk_text(BodyString, Lang), OOB = #oob_x{url = get_url(Id)}, Tref = erlang:send_after(?CAPTCHA_LIFETIME, ?MODULE, {remove_id, Id}), ets:insert(captcha, #captcha{id = Id, pid = self(), key = Key, tref = Tref, args = Args}), {ok, Id, Body, [OOB, Captcha, Data]}; Err -> Err end. -spec create_captcha_x(binary(), jid(), binary(), any(), xdata()) -> {ok, xdata()} | {error, image_error()}. create_captcha_x(SID, To, Lang, Limiter, #xdata{fields = Fs} = X) -> case create_image(Limiter) of {ok, Type, Key, Image} -> Id = <<(p1_rand:get_string())/binary>>, CID = <<"sha1+", (str:sha(Image))/binary, "@bob.xmpp.org">>, Data = #bob_data{cid = CID, 'max-age' = 0, type = Type, data = Image}, HelpTxt = translate:translate(Lang, <<"If you don't see the CAPTCHA image here, " "visit the web page.">>), Imageurl = get_url(<<Id/binary, "/image">>), NewFs = [mk_field(hidden, <<"FORM_TYPE">>, ?NS_CAPTCHA)|Fs] ++ [#xdata_field{type = fixed, var = <<"captcha-fallback-text">>, values = [HelpTxt]}, #xdata_field{type = hidden, var = <<"captchahidden">>, values = [<<"workaround-for-psi">>]}, #xdata_field{type = 'text-single', var = <<"captcha-fallback-url">>, label = translate:translate( Lang, <<"CAPTCHA web page">>), values = [Imageurl]}, mk_field(hidden, <<"from">>, jid:encode(To)), mk_field(hidden, <<"challenge">>, Id), mk_field(hidden, <<"sid">>, SID), mk_ocr_field(Lang, CID, Type)], Captcha = X#xdata{type = form, fields = NewFs}, Tref = erlang:send_after(?CAPTCHA_LIFETIME, ?MODULE, {remove_id, Id}), ets:insert(captcha, #captcha{id = Id, key = Key, tref = Tref}), {ok, [Captcha, Data]}; Err -> Err end. -spec build_captcha_html(binary(), binary()) -> captcha_not_found | {xmlel(), {xmlel(), xmlel(), xmlel(), xmlel()}}. build_captcha_html(Id, Lang) -> case lookup_captcha(Id) of {ok, _} -> ImgEl = #xmlel{name = <<"img">>, attrs = [{<<"src">>, get_url(<<Id/binary, "/image">>)}], children = []}, TextEl = {xmlcdata, captcha_text(Lang)}, IdEl = #xmlel{name = <<"input">>, attrs = [{<<"type">>, <<"hidden">>}, {<<"name">>, <<"id">>}, {<<"value">>, Id}], children = []}, KeyEl = #xmlel{name = <<"input">>, attrs = [{<<"type">>, <<"text">>}, {<<"name">>, <<"key">>}, {<<"size">>, <<"10">>}], children = []}, FormEl = #xmlel{name = <<"form">>, attrs = [{<<"action">>, get_url(Id)}, {<<"name">>, <<"captcha">>}, {<<"method">>, <<"POST">>}], children = [ImgEl, #xmlel{name = <<"br">>, attrs = [], children = []}, TextEl, #xmlel{name = <<"br">>, attrs = [], children = []}, IdEl, KeyEl, #xmlel{name = <<"br">>, attrs = [], children = []}, #xmlel{name = <<"input">>, attrs = [{<<"type">>, <<"submit">>}, {<<"name">>, <<"enter">>}, {<<"value">>, <<"OK">>}], children = []}]}, {FormEl, {ImgEl, TextEl, IdEl, KeyEl}}; _ -> captcha_not_found end. -spec process_reply(xmpp_element()) -> ok | {error, bad_match | not_found | malformed}. process_reply(#xdata{} = X) -> case {xmpp_util:get_xdata_values(<<"challenge">>, X), xmpp_util:get_xdata_values(<<"ocr">>, X)} of {[Id], [OCR]} -> case check_captcha(Id, OCR) of captcha_valid -> ok; captcha_non_valid -> {error, bad_match}; captcha_not_found -> {error, not_found} end; _ -> {error, malformed} end; process_reply(#xcaptcha{xdata = #xdata{} = X}) -> process_reply(X); process_reply(_) -> {error, malformed}. process_iq(#iq{type = set, lang = Lang, sub_els = [#xcaptcha{} = El]} = IQ) -> case process_reply(El) of ok -> xmpp:make_iq_result(IQ); {error, malformed} -> Txt = <<"Incorrect CAPTCHA submit">>, xmpp:make_error(IQ, xmpp:err_bad_request(Txt, Lang)); {error, _} -> Txt = <<"The CAPTCHA verification has failed">>, xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang)) end; process_iq(#iq{type = get, lang = Lang} = IQ) -> Txt = <<"Value 'get' of 'type' attribute is not allowed">>, xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang)); process_iq(#iq{lang = Lang} = IQ) -> Txt = <<"No module is handling this query">>, xmpp:make_error(IQ, xmpp:err_service_unavailable(Txt, Lang)). process(_Handlers, #request{method = 'GET', lang = Lang, path = [_, Id]}) -> case build_captcha_html(Id, Lang) of {FormEl, _} when is_tuple(FormEl) -> Form = #xmlel{name = <<"div">>, attrs = [{<<"align">>, <<"center">>}], children = [FormEl]}, ejabberd_web:make_xhtml([Form]); captcha_not_found -> ejabberd_web:error(not_found) end; process(_Handlers, #request{method = 'GET', path = [_, Id, <<"image">>], ip = IP}) -> {Addr, _Port} = IP, case lookup_captcha(Id) of {ok, #captcha{key = Key}} -> case create_image(Addr, Key) of {ok, Type, _, Img} -> {200, [{<<"Content-Type">>, Type}, {<<"Cache-Control">>, <<"no-cache">>}, {<<"Last-Modified">>, list_to_binary(httpd_util:rfc1123_date())}], Img}; {error, limit} -> ejabberd_web:error(not_allowed); _ -> ejabberd_web:error(not_found) end; _ -> ejabberd_web:error(not_found) end; process(_Handlers, #request{method = 'POST', q = Q, lang = Lang, path = [_, Id]}) -> ProvidedKey = proplists:get_value(<<"key">>, Q, none), case check_captcha(Id, ProvidedKey) of captcha_valid -> Form = #xmlel{name = <<"p">>, attrs = [], children = [{xmlcdata, translate:translate(Lang, <<"The CAPTCHA is valid.">>)}]}, ejabberd_web:make_xhtml([Form]); captcha_non_valid -> ejabberd_web:error(not_allowed); captcha_not_found -> ejabberd_web:error(not_found) end; process(_Handlers, _Request) -> ejabberd_web:error(not_found). host_up(Host) -> gen_iq_handler:add_iq_handler(ejabberd_sm, Host, ?NS_CAPTCHA, ?MODULE, process_iq). host_down(Host) -> gen_iq_handler:remove_iq_handler(ejabberd_sm, Host, ?NS_CAPTCHA). config_reloaded() -> gen_server:call(?MODULE, config_reloaded, timer:minutes(1)). init([]) -> mnesia:delete_table(captcha), ets:new(captcha, [named_table, public, {keypos, #captcha.id}]), case check_captcha_setup() of true -> register_handlers(), ejabberd_hooks:add(config_reloaded, ?MODULE, config_reloaded, 50), {ok, #state{enabled = true}}; false -> {ok, #state{enabled = false}}; {error, Reason} -> {stop, Reason} end. handle_call({is_limited, Limiter, RateLimit}, _From, State) -> NowPriority = now_priority(), CleanPriority = NowPriority + (?LIMIT_PERIOD), Limits = clean_treap(State#state.limits, CleanPriority), case treap:lookup(Limiter, Limits) of {ok, _, Rate} when Rate >= RateLimit -> {reply, true, State#state{limits = Limits}}; {ok, Priority, Rate} -> NewLimits = treap:insert(Limiter, Priority, Rate + 1, Limits), {reply, false, State#state{limits = NewLimits}}; _ -> NewLimits = treap:insert(Limiter, NowPriority, 1, Limits), {reply, false, State#state{limits = NewLimits}} end; handle_call(config_reloaded, _From, #state{enabled = Enabled} = State) -> State1 = case is_feature_available() of true when not Enabled -> case check_captcha_setup() of true -> register_handlers(), State#state{enabled = true}; _ -> State end; false when Enabled -> unregister_handlers(), State#state{enabled = false}; _ -> State end, {reply, ok, State1}; handle_call(_Request, _From, State) -> {reply, bad_request, State}. handle_cast(_Msg, State) -> {noreply, State}. handle_info({remove_id, Id}, State) -> ?DEBUG("captcha ~p timed out", [Id]), case ets:lookup(captcha, Id) of [#captcha{args = Args, pid = Pid}] -> callback(captcha_failed, Pid, Args), ets:delete(captcha, Id); _ -> ok end, {noreply, State}; handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, #state{enabled = Enabled}) -> if Enabled -> unregister_handlers(); true -> ok end, ejabberd_hooks:delete(config_reloaded, ?MODULE, config_reloaded, 50). register_handlers() -> ejabberd_hooks:add(host_up, ?MODULE, host_up, 50), ejabberd_hooks:add(host_down, ?MODULE, host_down, 50), lists:foreach(fun host_up/1, ejabberd_config:get_myhosts()). unregister_handlers() -> ejabberd_hooks:delete(host_up, ?MODULE, host_up, 50), ejabberd_hooks:delete(host_down, ?MODULE, host_down, 50), lists:foreach(fun host_down/1, ejabberd_config:get_myhosts()). code_change(_OldVsn, State, _Extra) -> {ok, State}. create_image() -> create_image(undefined). create_image(Limiter) -> Key = str:substr(p1_rand:get_string(), 1, 6), create_image(Limiter, Key). create_image(Limiter, Key) -> case is_limited(Limiter) of true -> {error, limit}; false -> do_create_image(Key) end. do_create_image(Key) -> FileName = get_prog_name(), Cmd = lists:flatten(io_lib:format("~s ~s", [FileName, Key])), case cmd(Cmd) of {ok, <<137, $P, $N, $G, $\r, $\n, 26, $\n, _/binary>> = Img} -> {ok, <<"image/png">>, Key, Img}; {ok, <<255, 216, _/binary>> = Img} -> {ok, <<"image/jpeg">>, Key, Img}; {ok, <<$G, $I, $F, $8, X, $a, _/binary>> = Img} when X == $7; X == $9 -> {ok, <<"image/gif">>, Key, Img}; {error, enodata = Reason} -> ?ERROR_MSG("Failed to process output from \"~s\". " "Maybe ImageMagick's Convert program " "is not installed.", [Cmd]), {error, Reason}; {error, Reason} -> ?ERROR_MSG("Failed to process an output from \"~s\": ~p", [Cmd, Reason]), {error, Reason}; _ -> Reason = malformed_image, ?ERROR_MSG("Failed to process an output from \"~s\": ~p", [Cmd, Reason]), {error, Reason} end. get_prog_name() -> case ejabberd_config:get_option(captcha_cmd) of undefined -> ?DEBUG("The option captcha_cmd is not configured, " "but some module wants to use the CAPTCHA " "feature.", []), false; FileName -> FileName end. get_url(Str) -> CaptchaHost = ejabberd_config:get_option(captcha_host, <<"">>), case str:tokens(CaptchaHost, <<":">>) of [Host] -> <<"http://", Host/binary, "/captcha/", Str/binary>>; [<<"http", _/binary>> = TransferProt, Host] -> <<TransferProt/binary, ":", Host/binary, "/captcha/", Str/binary>>; [Host, PortString] -> TransferProt = iolist_to_binary(atom_to_list(get_transfer_protocol(PortString))), <<TransferProt/binary, "://", Host/binary, ":", PortString/binary, "/captcha/", Str/binary>>; [TransferProt, Host, PortString] -> <<TransferProt/binary, ":", Host/binary, ":", PortString/binary, "/captcha/", Str/binary>>; _ -> <<"http://", (ejabberd_config:get_myname())/binary, "/captcha/", Str/binary>> end. get_transfer_protocol(PortString) -> PortNumber = binary_to_integer(PortString), PortListeners = get_port_listeners(PortNumber), get_captcha_transfer_protocol(PortListeners). get_port_listeners(PortNumber) -> AllListeners = ejabberd_config:get_option(listen, []), lists:filter( fun({{Port, _IP, _Transport}, _Module, _Opts}) -> Port == PortNumber end, AllListeners). get_captcha_transfer_protocol([]) -> throw(<<"The port number mentioned in captcha_host " "is not a ejabberd_http listener with " "'captcha' option. Change the port number " "or specify http:// in that option.">>); get_captcha_transfer_protocol([{_, ejabberd_http, Opts} | Listeners]) -> case proplists:get_bool(captcha, Opts) of true -> case proplists:get_bool(tls, Opts) of true -> https; false -> http end; false -> get_captcha_transfer_protocol(Listeners) end; get_captcha_transfer_protocol([_ | Listeners]) -> get_captcha_transfer_protocol(Listeners). is_limited(undefined) -> false; is_limited(Limiter) -> case ejabberd_config:get_option(captcha_limit) of undefined -> false; Int -> case catch gen_server:call(?MODULE, {is_limited, Limiter, Int}, 5000) of true -> true; false -> false; Err -> ?ERROR_MSG("Call failed: ~p", [Err]), false end end. -define(CMD_TIMEOUT, 5000). -define(MAX_FILE_SIZE, 64 * 1024). cmd(Cmd) -> Port = open_port({spawn, Cmd}, [stream, eof, binary]), TRef = erlang:start_timer(?CMD_TIMEOUT, self(), timeout), recv_data(Port, TRef, <<>>). recv_data(Port, TRef, Buf) -> receive {Port, {data, Bytes}} -> NewBuf = <<Buf/binary, Bytes/binary>>, if byte_size(NewBuf) > (?MAX_FILE_SIZE) -> return(Port, TRef, {error, efbig}); true -> recv_data(Port, TRef, NewBuf) end; {Port, {data, _}} -> return(Port, TRef, {error, efbig}); {Port, eof} when Buf /= <<>> -> return(Port, TRef, {ok, Buf}); {Port, eof} -> return(Port, TRef, {error, enodata}); {timeout, TRef, _} -> return(Port, TRef, {error, timeout}) end. return(Port, TRef, Result) -> misc:cancel_timer(TRef), catch port_close(Port), Result. is_feature_available() -> case get_prog_name() of Prog when is_binary(Prog) -> true; false -> false end. check_captcha_setup() -> case is_feature_available() of true -> case create_image() of {ok, _, _, _} -> true; Err -> ?CRITICAL_MSG("Captcha is enabled in the option captcha_cmd, " "but it can't generate images.", []), Err end; false -> false end. lookup_captcha(Id) -> case ets:lookup(captcha, Id) of [C] -> {ok, C}; _ -> {error, enoent} end. -spec check_captcha(binary(), binary()) -> captcha_not_found | captcha_valid | captcha_non_valid. check_captcha(Id, ProvidedKey) -> case ets:lookup(captcha, Id) of [#captcha{pid = Pid, args = Args, key = ValidKey, tref = Tref}] -> ets:delete(captcha, Id), misc:cancel_timer(Tref), if ValidKey == ProvidedKey -> callback(captcha_succeed, Pid, Args), captcha_valid; true -> callback(captcha_failed, Pid, Args), captcha_non_valid end; _ -> captcha_not_found end. clean_treap(Treap, CleanPriority) -> case treap:is_empty(Treap) of true -> Treap; false -> {_Key, Priority, _Value} = treap:get_root(Treap), if Priority > CleanPriority -> clean_treap(treap:delete_root(Treap), CleanPriority); true -> Treap end end. -spec callback(captcha_succeed | captcha_failed, pid(), term()) -> any(). callback(Result, _Pid, F) when is_function(F) -> F(Result); callback(Result, Pid, Args) when is_pid(Pid) -> Pid ! {Result, Args}; callback(_, _, _) -> ok. now_priority() -> -p1_time_compat:system_time(micro_seconds). -spec opt_type(atom()) -> fun((any()) -> any()) | [atom()]. opt_type(captcha_cmd) -> fun (FileName) -> F = iolist_to_binary(FileName), if F /= <<"">> -> F end end; opt_type(captcha_host) -> fun iolist_to_binary/1; opt_type(captcha_limit) -> fun (I) when is_integer(I), I > 0 -> I end; opt_type(_) -> [captcha_cmd, captcha_host, captcha_limit].
null
https://raw.githubusercontent.com/jabber-at/ejabberd/7bfec36856eaa4df21b26e879d3ba90285bad1aa/src/ejabberd_captcha.erl
erlang
------------------------------------------------------------------- File : ejabberd_captcha.erl Purpose : CAPTCHA processing. 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 gen_server callbacks
Author : < > Created : 26 Apr 2008 by < > ejabberd , Copyright ( C ) 2002 - 2018 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(ejabberd_captcha). -behaviour(ejabberd_config). -protocol({xep, 158, '1.0'}). -behaviour(gen_server). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([create_captcha/6, build_captcha_html/2, check_captcha/2, process_reply/1, process/2, is_feature_available/0, create_captcha_x/5, opt_type/1, host_up/1, host_down/1, config_reloaded/0, process_iq/1]). -include("xmpp.hrl"). -include("logger.hrl"). -include("ejabberd_http.hrl"). -define(CAPTCHA_LIFETIME, 120000). -define(LIMIT_PERIOD, 60*1000*1000). -type image_error() :: efbig | enodata | limit | malformed_image | timeout. -record(state, {limits = treap:empty() :: treap:treap(), enabled = false :: boolean()}). -record(captcha, {id :: binary(), pid :: pid() | undefined, key :: binary(), tref :: reference(), args :: any()}). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). -spec captcha_text(undefined | binary()) -> binary(). captcha_text(Lang) -> translate:translate(Lang, <<"Enter the text you see">>). -spec mk_ocr_field(binary() | undefined, binary(), binary()) -> xdata_field(). mk_ocr_field(Lang, CID, Type) -> URI = #media_uri{type = Type, uri = <<"cid:", CID/binary>>}, #xdata_field{var = <<"ocr">>, type = 'text-single', label = captcha_text(Lang), required = true, sub_els = [#media{uri = [URI]}]}. mk_field(Type, Var, Value) -> #xdata_field{type = Type, var = Var, values = [Value]}. -spec create_captcha(binary(), jid(), jid(), binary(), any(), any()) -> {error, image_error()} | {ok, binary(), [text()], [xmlel()]}. create_captcha(SID, From, To, Lang, Limiter, Args) -> case create_image(Limiter) of {ok, Type, Key, Image} -> Id = <<(p1_rand:get_string())/binary>>, JID = jid:encode(From), CID = <<"sha1+", (str:sha(Image))/binary, "@bob.xmpp.org">>, Data = #bob_data{cid = CID, 'max-age' = 0, type = Type, data = Image}, Fs = [mk_field(hidden, <<"FORM_TYPE">>, ?NS_CAPTCHA), mk_field(hidden, <<"from">>, jid:encode(To)), mk_field(hidden, <<"challenge">>, Id), mk_field(hidden, <<"sid">>, SID), mk_ocr_field(Lang, CID, Type)], X = #xdata{type = form, fields = Fs}, Captcha = #xcaptcha{xdata = X}, BodyString = {<<"Your messages to ~s are being blocked. " "To unblock them, visit ~s">>, [JID, get_url(Id)]}, Body = xmpp:mk_text(BodyString, Lang), OOB = #oob_x{url = get_url(Id)}, Tref = erlang:send_after(?CAPTCHA_LIFETIME, ?MODULE, {remove_id, Id}), ets:insert(captcha, #captcha{id = Id, pid = self(), key = Key, tref = Tref, args = Args}), {ok, Id, Body, [OOB, Captcha, Data]}; Err -> Err end. -spec create_captcha_x(binary(), jid(), binary(), any(), xdata()) -> {ok, xdata()} | {error, image_error()}. create_captcha_x(SID, To, Lang, Limiter, #xdata{fields = Fs} = X) -> case create_image(Limiter) of {ok, Type, Key, Image} -> Id = <<(p1_rand:get_string())/binary>>, CID = <<"sha1+", (str:sha(Image))/binary, "@bob.xmpp.org">>, Data = #bob_data{cid = CID, 'max-age' = 0, type = Type, data = Image}, HelpTxt = translate:translate(Lang, <<"If you don't see the CAPTCHA image here, " "visit the web page.">>), Imageurl = get_url(<<Id/binary, "/image">>), NewFs = [mk_field(hidden, <<"FORM_TYPE">>, ?NS_CAPTCHA)|Fs] ++ [#xdata_field{type = fixed, var = <<"captcha-fallback-text">>, values = [HelpTxt]}, #xdata_field{type = hidden, var = <<"captchahidden">>, values = [<<"workaround-for-psi">>]}, #xdata_field{type = 'text-single', var = <<"captcha-fallback-url">>, label = translate:translate( Lang, <<"CAPTCHA web page">>), values = [Imageurl]}, mk_field(hidden, <<"from">>, jid:encode(To)), mk_field(hidden, <<"challenge">>, Id), mk_field(hidden, <<"sid">>, SID), mk_ocr_field(Lang, CID, Type)], Captcha = X#xdata{type = form, fields = NewFs}, Tref = erlang:send_after(?CAPTCHA_LIFETIME, ?MODULE, {remove_id, Id}), ets:insert(captcha, #captcha{id = Id, key = Key, tref = Tref}), {ok, [Captcha, Data]}; Err -> Err end. -spec build_captcha_html(binary(), binary()) -> captcha_not_found | {xmlel(), {xmlel(), xmlel(), xmlel(), xmlel()}}. build_captcha_html(Id, Lang) -> case lookup_captcha(Id) of {ok, _} -> ImgEl = #xmlel{name = <<"img">>, attrs = [{<<"src">>, get_url(<<Id/binary, "/image">>)}], children = []}, TextEl = {xmlcdata, captcha_text(Lang)}, IdEl = #xmlel{name = <<"input">>, attrs = [{<<"type">>, <<"hidden">>}, {<<"name">>, <<"id">>}, {<<"value">>, Id}], children = []}, KeyEl = #xmlel{name = <<"input">>, attrs = [{<<"type">>, <<"text">>}, {<<"name">>, <<"key">>}, {<<"size">>, <<"10">>}], children = []}, FormEl = #xmlel{name = <<"form">>, attrs = [{<<"action">>, get_url(Id)}, {<<"name">>, <<"captcha">>}, {<<"method">>, <<"POST">>}], children = [ImgEl, #xmlel{name = <<"br">>, attrs = [], children = []}, TextEl, #xmlel{name = <<"br">>, attrs = [], children = []}, IdEl, KeyEl, #xmlel{name = <<"br">>, attrs = [], children = []}, #xmlel{name = <<"input">>, attrs = [{<<"type">>, <<"submit">>}, {<<"name">>, <<"enter">>}, {<<"value">>, <<"OK">>}], children = []}]}, {FormEl, {ImgEl, TextEl, IdEl, KeyEl}}; _ -> captcha_not_found end. -spec process_reply(xmpp_element()) -> ok | {error, bad_match | not_found | malformed}. process_reply(#xdata{} = X) -> case {xmpp_util:get_xdata_values(<<"challenge">>, X), xmpp_util:get_xdata_values(<<"ocr">>, X)} of {[Id], [OCR]} -> case check_captcha(Id, OCR) of captcha_valid -> ok; captcha_non_valid -> {error, bad_match}; captcha_not_found -> {error, not_found} end; _ -> {error, malformed} end; process_reply(#xcaptcha{xdata = #xdata{} = X}) -> process_reply(X); process_reply(_) -> {error, malformed}. process_iq(#iq{type = set, lang = Lang, sub_els = [#xcaptcha{} = El]} = IQ) -> case process_reply(El) of ok -> xmpp:make_iq_result(IQ); {error, malformed} -> Txt = <<"Incorrect CAPTCHA submit">>, xmpp:make_error(IQ, xmpp:err_bad_request(Txt, Lang)); {error, _} -> Txt = <<"The CAPTCHA verification has failed">>, xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang)) end; process_iq(#iq{type = get, lang = Lang} = IQ) -> Txt = <<"Value 'get' of 'type' attribute is not allowed">>, xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang)); process_iq(#iq{lang = Lang} = IQ) -> Txt = <<"No module is handling this query">>, xmpp:make_error(IQ, xmpp:err_service_unavailable(Txt, Lang)). process(_Handlers, #request{method = 'GET', lang = Lang, path = [_, Id]}) -> case build_captcha_html(Id, Lang) of {FormEl, _} when is_tuple(FormEl) -> Form = #xmlel{name = <<"div">>, attrs = [{<<"align">>, <<"center">>}], children = [FormEl]}, ejabberd_web:make_xhtml([Form]); captcha_not_found -> ejabberd_web:error(not_found) end; process(_Handlers, #request{method = 'GET', path = [_, Id, <<"image">>], ip = IP}) -> {Addr, _Port} = IP, case lookup_captcha(Id) of {ok, #captcha{key = Key}} -> case create_image(Addr, Key) of {ok, Type, _, Img} -> {200, [{<<"Content-Type">>, Type}, {<<"Cache-Control">>, <<"no-cache">>}, {<<"Last-Modified">>, list_to_binary(httpd_util:rfc1123_date())}], Img}; {error, limit} -> ejabberd_web:error(not_allowed); _ -> ejabberd_web:error(not_found) end; _ -> ejabberd_web:error(not_found) end; process(_Handlers, #request{method = 'POST', q = Q, lang = Lang, path = [_, Id]}) -> ProvidedKey = proplists:get_value(<<"key">>, Q, none), case check_captcha(Id, ProvidedKey) of captcha_valid -> Form = #xmlel{name = <<"p">>, attrs = [], children = [{xmlcdata, translate:translate(Lang, <<"The CAPTCHA is valid.">>)}]}, ejabberd_web:make_xhtml([Form]); captcha_non_valid -> ejabberd_web:error(not_allowed); captcha_not_found -> ejabberd_web:error(not_found) end; process(_Handlers, _Request) -> ejabberd_web:error(not_found). host_up(Host) -> gen_iq_handler:add_iq_handler(ejabberd_sm, Host, ?NS_CAPTCHA, ?MODULE, process_iq). host_down(Host) -> gen_iq_handler:remove_iq_handler(ejabberd_sm, Host, ?NS_CAPTCHA). config_reloaded() -> gen_server:call(?MODULE, config_reloaded, timer:minutes(1)). init([]) -> mnesia:delete_table(captcha), ets:new(captcha, [named_table, public, {keypos, #captcha.id}]), case check_captcha_setup() of true -> register_handlers(), ejabberd_hooks:add(config_reloaded, ?MODULE, config_reloaded, 50), {ok, #state{enabled = true}}; false -> {ok, #state{enabled = false}}; {error, Reason} -> {stop, Reason} end. handle_call({is_limited, Limiter, RateLimit}, _From, State) -> NowPriority = now_priority(), CleanPriority = NowPriority + (?LIMIT_PERIOD), Limits = clean_treap(State#state.limits, CleanPriority), case treap:lookup(Limiter, Limits) of {ok, _, Rate} when Rate >= RateLimit -> {reply, true, State#state{limits = Limits}}; {ok, Priority, Rate} -> NewLimits = treap:insert(Limiter, Priority, Rate + 1, Limits), {reply, false, State#state{limits = NewLimits}}; _ -> NewLimits = treap:insert(Limiter, NowPriority, 1, Limits), {reply, false, State#state{limits = NewLimits}} end; handle_call(config_reloaded, _From, #state{enabled = Enabled} = State) -> State1 = case is_feature_available() of true when not Enabled -> case check_captcha_setup() of true -> register_handlers(), State#state{enabled = true}; _ -> State end; false when Enabled -> unregister_handlers(), State#state{enabled = false}; _ -> State end, {reply, ok, State1}; handle_call(_Request, _From, State) -> {reply, bad_request, State}. handle_cast(_Msg, State) -> {noreply, State}. handle_info({remove_id, Id}, State) -> ?DEBUG("captcha ~p timed out", [Id]), case ets:lookup(captcha, Id) of [#captcha{args = Args, pid = Pid}] -> callback(captcha_failed, Pid, Args), ets:delete(captcha, Id); _ -> ok end, {noreply, State}; handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, #state{enabled = Enabled}) -> if Enabled -> unregister_handlers(); true -> ok end, ejabberd_hooks:delete(config_reloaded, ?MODULE, config_reloaded, 50). register_handlers() -> ejabberd_hooks:add(host_up, ?MODULE, host_up, 50), ejabberd_hooks:add(host_down, ?MODULE, host_down, 50), lists:foreach(fun host_up/1, ejabberd_config:get_myhosts()). unregister_handlers() -> ejabberd_hooks:delete(host_up, ?MODULE, host_up, 50), ejabberd_hooks:delete(host_down, ?MODULE, host_down, 50), lists:foreach(fun host_down/1, ejabberd_config:get_myhosts()). code_change(_OldVsn, State, _Extra) -> {ok, State}. create_image() -> create_image(undefined). create_image(Limiter) -> Key = str:substr(p1_rand:get_string(), 1, 6), create_image(Limiter, Key). create_image(Limiter, Key) -> case is_limited(Limiter) of true -> {error, limit}; false -> do_create_image(Key) end. do_create_image(Key) -> FileName = get_prog_name(), Cmd = lists:flatten(io_lib:format("~s ~s", [FileName, Key])), case cmd(Cmd) of {ok, <<137, $P, $N, $G, $\r, $\n, 26, $\n, _/binary>> = Img} -> {ok, <<"image/png">>, Key, Img}; {ok, <<255, 216, _/binary>> = Img} -> {ok, <<"image/jpeg">>, Key, Img}; {ok, <<$G, $I, $F, $8, X, $a, _/binary>> = Img} when X == $7; X == $9 -> {ok, <<"image/gif">>, Key, Img}; {error, enodata = Reason} -> ?ERROR_MSG("Failed to process output from \"~s\". " "Maybe ImageMagick's Convert program " "is not installed.", [Cmd]), {error, Reason}; {error, Reason} -> ?ERROR_MSG("Failed to process an output from \"~s\": ~p", [Cmd, Reason]), {error, Reason}; _ -> Reason = malformed_image, ?ERROR_MSG("Failed to process an output from \"~s\": ~p", [Cmd, Reason]), {error, Reason} end. get_prog_name() -> case ejabberd_config:get_option(captcha_cmd) of undefined -> ?DEBUG("The option captcha_cmd is not configured, " "but some module wants to use the CAPTCHA " "feature.", []), false; FileName -> FileName end. get_url(Str) -> CaptchaHost = ejabberd_config:get_option(captcha_host, <<"">>), case str:tokens(CaptchaHost, <<":">>) of [Host] -> <<"http://", Host/binary, "/captcha/", Str/binary>>; [<<"http", _/binary>> = TransferProt, Host] -> <<TransferProt/binary, ":", Host/binary, "/captcha/", Str/binary>>; [Host, PortString] -> TransferProt = iolist_to_binary(atom_to_list(get_transfer_protocol(PortString))), <<TransferProt/binary, "://", Host/binary, ":", PortString/binary, "/captcha/", Str/binary>>; [TransferProt, Host, PortString] -> <<TransferProt/binary, ":", Host/binary, ":", PortString/binary, "/captcha/", Str/binary>>; _ -> <<"http://", (ejabberd_config:get_myname())/binary, "/captcha/", Str/binary>> end. get_transfer_protocol(PortString) -> PortNumber = binary_to_integer(PortString), PortListeners = get_port_listeners(PortNumber), get_captcha_transfer_protocol(PortListeners). get_port_listeners(PortNumber) -> AllListeners = ejabberd_config:get_option(listen, []), lists:filter( fun({{Port, _IP, _Transport}, _Module, _Opts}) -> Port == PortNumber end, AllListeners). get_captcha_transfer_protocol([]) -> throw(<<"The port number mentioned in captcha_host " "is not a ejabberd_http listener with " "'captcha' option. Change the port number " "or specify http:// in that option.">>); get_captcha_transfer_protocol([{_, ejabberd_http, Opts} | Listeners]) -> case proplists:get_bool(captcha, Opts) of true -> case proplists:get_bool(tls, Opts) of true -> https; false -> http end; false -> get_captcha_transfer_protocol(Listeners) end; get_captcha_transfer_protocol([_ | Listeners]) -> get_captcha_transfer_protocol(Listeners). is_limited(undefined) -> false; is_limited(Limiter) -> case ejabberd_config:get_option(captcha_limit) of undefined -> false; Int -> case catch gen_server:call(?MODULE, {is_limited, Limiter, Int}, 5000) of true -> true; false -> false; Err -> ?ERROR_MSG("Call failed: ~p", [Err]), false end end. -define(CMD_TIMEOUT, 5000). -define(MAX_FILE_SIZE, 64 * 1024). cmd(Cmd) -> Port = open_port({spawn, Cmd}, [stream, eof, binary]), TRef = erlang:start_timer(?CMD_TIMEOUT, self(), timeout), recv_data(Port, TRef, <<>>). recv_data(Port, TRef, Buf) -> receive {Port, {data, Bytes}} -> NewBuf = <<Buf/binary, Bytes/binary>>, if byte_size(NewBuf) > (?MAX_FILE_SIZE) -> return(Port, TRef, {error, efbig}); true -> recv_data(Port, TRef, NewBuf) end; {Port, {data, _}} -> return(Port, TRef, {error, efbig}); {Port, eof} when Buf /= <<>> -> return(Port, TRef, {ok, Buf}); {Port, eof} -> return(Port, TRef, {error, enodata}); {timeout, TRef, _} -> return(Port, TRef, {error, timeout}) end. return(Port, TRef, Result) -> misc:cancel_timer(TRef), catch port_close(Port), Result. is_feature_available() -> case get_prog_name() of Prog when is_binary(Prog) -> true; false -> false end. check_captcha_setup() -> case is_feature_available() of true -> case create_image() of {ok, _, _, _} -> true; Err -> ?CRITICAL_MSG("Captcha is enabled in the option captcha_cmd, " "but it can't generate images.", []), Err end; false -> false end. lookup_captcha(Id) -> case ets:lookup(captcha, Id) of [C] -> {ok, C}; _ -> {error, enoent} end. -spec check_captcha(binary(), binary()) -> captcha_not_found | captcha_valid | captcha_non_valid. check_captcha(Id, ProvidedKey) -> case ets:lookup(captcha, Id) of [#captcha{pid = Pid, args = Args, key = ValidKey, tref = Tref}] -> ets:delete(captcha, Id), misc:cancel_timer(Tref), if ValidKey == ProvidedKey -> callback(captcha_succeed, Pid, Args), captcha_valid; true -> callback(captcha_failed, Pid, Args), captcha_non_valid end; _ -> captcha_not_found end. clean_treap(Treap, CleanPriority) -> case treap:is_empty(Treap) of true -> Treap; false -> {_Key, Priority, _Value} = treap:get_root(Treap), if Priority > CleanPriority -> clean_treap(treap:delete_root(Treap), CleanPriority); true -> Treap end end. -spec callback(captcha_succeed | captcha_failed, pid(), term()) -> any(). callback(Result, _Pid, F) when is_function(F) -> F(Result); callback(Result, Pid, Args) when is_pid(Pid) -> Pid ! {Result, Args}; callback(_, _, _) -> ok. now_priority() -> -p1_time_compat:system_time(micro_seconds). -spec opt_type(atom()) -> fun((any()) -> any()) | [atom()]. opt_type(captcha_cmd) -> fun (FileName) -> F = iolist_to_binary(FileName), if F /= <<"">> -> F end end; opt_type(captcha_host) -> fun iolist_to_binary/1; opt_type(captcha_limit) -> fun (I) when is_integer(I), I > 0 -> I end; opt_type(_) -> [captcha_cmd, captcha_host, captcha_limit].
945886f475db491fe93eb783e6e080f841ba3978426e9751891249d348d37b3e
takikawa/racket-ppa
decompile.rkt
#lang racket/base (require racket/linklet compiler/zo-parse compiler/zo-marshal syntax/modcollapse racket/port racket/match racket/list racket/set racket/path ffi/unsafe/vm (only-in '#%linklet compiled-position->primitive) "private/deserialize.rkt" "private/chez.rkt") (provide decompile) ;; ---------------------------------------- (define primitive-table (let ([value-names (let ([ns (make-base-empty-namespace)]) (parameterize ([current-namespace ns]) (namespace-require ''#%kernel) (namespace-require ''#%unsafe) (namespace-require ''#%flfxnum) (namespace-require ''#%extfl) (namespace-require ''#%futures) (namespace-require ''#%foreign) (namespace-require ''#%paramz) (namespace-require ''#%linklet) (for/hasheq ([name (in-list (namespace-mapped-symbols))]) (values (namespace-variable-value name #t (lambda () #f)) name))))]) (for/hash ([i (in-naturals)] #:break (not (compiled-position->primitive i))) (define v (compiled-position->primitive i)) (values i (or (hash-ref value-names v #f) `',v))))) (define (list-ref/protect l pos who) (list-ref l pos) #; (if (pos . < . (length l)) (list-ref l pos) `(OUT-OF-BOUNDS ,who ,pos ,(length l) ,l))) ;; ---------------------------------------- (define-struct glob-desc (vars)) ;; Main entry: (define (decompile top #:to-linklets? [to-linklets? #f]) (cond [(linkl-directory? top) (cond [to-linklets? (cons 'linklet-directory (apply append (for/list ([(k v) (in-hash (linkl-directory-table top))]) (list '#:name k '#:bundle (decompile v #:to-linklets? to-linklets?)))))] [else (define main (hash-ref (linkl-directory-table top) '() #f)) (cond [(and main (hash-ref (linkl-bundle-table main) 'decl #f)) (decompile-module-with-submodules top '() main)] [main (decompile-single-top main)] [else (decompile-multi-top top)])])] [(linkl-bundle? top) (cond [to-linklets? (cons 'linklet-bundle (apply append (for/list ([(k v) (in-hash (linkl-bundle-table top))]) (case (and (not to-linklets?) k) [(stx-data) (list '#:stx-data (decompile-data-linklet v))] [else (list '#:key k '#:value (decompile v #:to-linklets? to-linklets?))]))))] [else (decompile-module top)])] [(or (linkl? top) (linklet? top)) (decompile-linklet top)] [(faslable-correlated-linklet? top) (strip-correlated (faslable-correlated-linklet-expr top))] [else `(quote ,top)])) (define (decompile-module-with-submodules l-dir name-list main-l) (decompile-module main-l (lambda () (for/list ([(k l) (in-hash (linkl-directory-table l-dir))] #:when (and (list? k) (= (length k) (add1 (length name-list))) (for/and ([s1 (in-list name-list)] [s2 (in-list k)]) (eq? s1 s2)))) (decompile-module-with-submodules l-dir k l))))) (define (decompile-module l [get-nested (lambda () '())]) (define ht (linkl-bundle-table l)) (define phases (sort (for/list ([k (in-hash-keys ht)] #:when (exact-integer? k)) k) <)) (define-values (mpi-vector requires provides phase-to-link-modules) (deserialize-requires-and-provides l)) (define (phase-wrap phase l) (case phase [(0) l] [(1) `((for-syntax ,@l))] [(-1) `((for-template ,@l))] [(#f) `((for-label ,@l))] [else `((for-meta ,phase ,@l))])) `(module ,(hash-ref ht 'name 'unknown) .... (require ,@(apply append (for/list ([phase+mpis (in-list requires)]) (phase-wrap (car phase+mpis) (map collapse-module-path-index (cdr phase+mpis)))))) (provide ,@(apply append (for/list ([(phase ht) (in-hash provides)]) (phase-wrap phase (hash-keys ht))))) ,@(let loop ([phases phases] [depth 0]) (cond [(null? phases) '()] [(= depth (car phases)) (append (decompile-linklet (hash-ref ht (car phases)) #:just-body? #t) (loop (cdr phases) depth))] [else (define l (loop phases (add1 depth))) (define (convert-syntax-definition s wrap) (match s [`(let ,bindings ,body) (convert-syntax-definition body (lambda (rhs) `(let ,bindings ,rhs)))] [`(begin (.set-transformer! ',id ,rhs) ',(? void?)) `(define-syntaxes ,id ,(wrap rhs))] [`(begin (.set-transformer! ',ids ,rhss) ... ',(? void?)) `(define-syntaxes ,ids ,(wrap `(values . ,rhss)))] [_ #f])) (let loop ([l l] [accum '()]) (cond [(null? l) (if (null? accum) '() `((begin-for-syntax ,@(reverse accum))))] [(convert-syntax-definition (car l) values) => (lambda (s) (append (loop null accum) (cons s (loop (cdr l) null))))] [else (loop (cdr l) (cons (car l) accum))]))])) ,@(get-nested) ,@(let ([l (hash-ref ht 'stx-data #f)]) (if l `((begin-for-all (define (.get-syntax-literal! pos) .... ,@(decompile-data-linklet l) ....))) null)))) (define (decompile-single-top b) (define forms (let ([l (hash-ref (linkl-bundle-table b) 0 #f)]) (if l (decompile-linklet l #:just-body? #t) '(<opaque-compiled-linklet>)))) (if (= (length forms) 1) (car forms) `(begin ,@forms))) (define (decompile-multi-top ld) `(begin ,@(let loop ([i 0]) (define b (hash-ref (linkl-directory-table ld) (list (string->symbol (format "~a" i))) #f)) (define l (and b (hash-ref (linkl-bundle-table b) 0 #f))) (cond [l (append (decompile-linklet l #:just-body? #t) (loop (add1 i)))] [else null])))) (define (decompile-linklet l #:just-body? [just-body? #f]) (match l [(struct linkl (name importss import-shapess exports internals lifts source-names body max-let-depth needs-instance?)) (define closed (make-hasheq)) (define globs (glob-desc (append (list 'root) (apply append importss) exports internals lifts))) (define body-l (for/list ([form (in-list body)]) (decompile-form form globs '(#%globals) closed))) (if just-body? body-l `(linklet ,importss ,exports '(import-shapes: ,@(for/list ([imports (in-list importss)] [import-shapes (in-list import-shapess)] #:when #t [import (in-list imports)] [import-shape (in-list import-shapes)] #:when import-shape) `[,import ,import-shape])) '(source-names: ,source-names) ,@body-l))] [(struct faslable-correlated-linklet (expr name)) (match (strip-correlated expr) [`(linklet ,imports ,exports ,body-l ...) body-l])] [(? linklet?) (case (system-type 'vm) [(chez-scheme) (define-values (fmt code literals) ((vm-primitive 'linklet-fasled-code+arguments) l)) (cond [code (case fmt [(compile) (cond [(not (current-partial-fasl)) (define proc (vm-eval `(load-compiled-from-port (open-bytevector-input-port ,code) ',literals))) (decompile-chez-procedure proc)] [else (disassemble-in-description `(#(FASL #:length ,(bytes-length code) #:literals ,literals ,(vm-eval `(($primitive $describe-fasl-from-port) (open-bytevector-input-port ,code) ',literals)))))])] [(interpret) (define bytecode (vm-eval `(fasl-read (open-bytevector-input-port ,code) 'load ',literals))) (list `(#%interpret ,(unwrap-chez-interpret-jitified bytecode)))] [else '(....)])] [else `(....)])])])) (define (decompile-data-linklet l) (match l [(struct linkl (_ _ _ _ _ _ _ (list vec-def (struct def-values (_ deser-lam))) _ _)) (match deser-lam [(struct lam (_ _ _ _ _ _ _ _ _ (struct seq ((list vec-copy! _))))) (match vec-copy! [(struct application (_ (list _ _ (struct application (_ (list mpi-vector inspector bulk-binding-registry num-mutables mutable-vec num-shares share-vec mutable-fill-vec result-vec)))))) (decompile-deserialize '.mpi-vector '.inspector '.bulk-binding-registry num-mutables mutable-vec num-shares share-vec mutable-fill-vec result-vec)] [_ (decompile-linklet l)])] [_ (decompile-linklet l)])] [(struct faslable-correlated-linklet (expr name)) (match (strip-correlated expr) [`(linklet ,_ ,_ ,_ (define-values ,_ (lambda ,_ (begin (vector-copy! ,_ ,_ (let-values ([(.inspector) #f]) (let-values ([(data) '#(,mutable-vec ,share-vec ,mutable-fill-vec ,result-vec)]) (deserialize .mpi-vector .inspector .bulk-binding-registry ',num-mutables (,_ data 0) ',num-shares (,_ data 1) (,_ data 2) (,_ data 3))))) ,_)))) (decompile-deserialize '.mpi-vector '.inspector '.bulk-binding-registry num-mutables mutable-vec num-shares share-vec mutable-fill-vec result-vec)] [_ (decompile-linklet l)])] [_ (decompile-linklet l)])) (define (decompile-form form globs stack closed) (match form [(struct def-values (ids rhs)) `(define-values ,(map (lambda (tl) (match tl [(struct toplevel (depth pos const? set-const?)) (list-ref/protect (glob-desc-vars globs) pos 'def-vals)])) ids) ,(if (inline-variant? rhs) `(begin ,(list 'quote '%%inline-variant%%) ,(decompile-expr (inline-variant-inline rhs) globs stack closed) ,(decompile-expr (inline-variant-direct rhs) globs stack closed)) (decompile-expr rhs globs stack closed)))] [(struct seq (forms)) `(begin ,@(map (lambda (form) (decompile-form form globs stack closed)) forms))] [_ (decompile-expr form globs stack closed)])) (define (extract-name name) (if (symbol? name) (gensym name) (if (vector? name) (gensym (vector-ref name 0)) #f))) (define (extract-id expr) (match expr [(struct lam (name flags num-params arg-types rest? closure-map closure-types tl-map max-let-depth body)) (extract-name name)] [(struct case-lam (name lams)) (extract-name name)] [(struct closure (lam gen-id)) (extract-id lam)] [_ #f])) (define (extract-ids! body ids) (match body [(struct let-rec (procs body)) (for ([proc (in-list procs)] [delta (in-naturals)]) (when (< -1 delta (vector-length ids)) (vector-set! ids delta (extract-id proc)))) (extract-ids! body ids)] [(struct install-value (val-count pos boxes? rhs body)) (extract-ids! body ids)] [(struct boxenv (pos body)) (extract-ids! body ids)] [_ #f])) (define (decompile-tl expr globs stack closed no-check?) (match expr [(struct toplevel (depth pos const? ready?)) (let ([id (list-ref/protect (glob-desc-vars globs) pos 'toplevel)]) (cond [no-check? id] [(and (not const?) (not ready?)) `(#%checked ,id)] [ ( and const ? ready ? ) ` ( # % const , i d ) ] [ const ? ` ( # % iconst , i d ) ] [else id]))])) (define (decompile-expr expr globs stack closed) (match expr [(struct toplevel (depth pos const? ready?)) (decompile-tl expr globs stack closed #f)] [(struct varref (tl dummy constant? from-unsafe?)) `(#%variable-reference . ,(cond [(not tl) '()] [(eq? tl #t) '(<constant-local>)] [(symbol? tl) (list tl)] ; primitive [else (list (decompile-tl tl globs stack closed #t))]))] [(struct primval (id)) (hash-ref primitive-table id (lambda () (error "unknown primitive: " id)))] [(struct assign (id rhs undef-ok?)) `(set! ,(decompile-expr id globs stack closed) ,(decompile-expr rhs globs stack closed))] [(struct localref (unbox? offset clear? other-clears? type)) (let ([id (list-ref/protect stack offset 'localref)]) (let ([e (if unbox? `(#%unbox ,id) id)]) (if clear? `(#%sfs-clear ,e) e)))] [(? lam?) `(lambda . ,(decompile-lam expr globs stack closed))] [(struct case-lam (name lams)) `(case-lambda ,@(map (lambda (lam) (decompile-lam lam globs stack closed)) lams))] [(struct let-one (rhs body type unused?)) (let ([id (or (extract-id rhs) (gensym (or type (if unused? 'unused 'local))))]) `(let ([,id ,(decompile-expr rhs globs (cons id stack) closed)]) ,(decompile-expr body globs (cons id stack) closed)))] [(struct let-void (count boxes? body)) (let ([ids (make-vector count #f)]) (extract-ids! body ids) (let ([vars (for/list ([i (in-range count)] [id (in-vector ids)]) (or id (gensym (if boxes? 'localvb 'localv))))]) `(let ,(map (lambda (i) `[,i ,(if boxes? `(#%box ?) '?)]) vars) ,(decompile-expr body globs (append vars stack) closed))))] [(struct let-rec (procs body)) `(begin (#%set!-rec-values ,(for/list ([p (in-list procs)] [i (in-naturals)]) (list-ref/protect stack i 'let-rec)) ,@(map (lambda (proc) (decompile-expr proc globs stack closed)) procs)) ,(decompile-expr body globs stack closed))] [(struct install-value (count pos boxes? rhs body)) `(begin (,(if boxes? '#%set-boxes! 'set!-values) ,(for/list ([i (in-range count)]) (list-ref/protect stack (+ i pos) 'install-value)) ,(decompile-expr rhs globs stack closed)) ,(decompile-expr body globs stack closed))] [(struct boxenv (pos body)) (let ([id (list-ref/protect stack pos 'boxenv)]) `(begin (set! ,id (#%box ,id)) ,(decompile-expr body globs stack closed)))] [(struct branch (test then els)) `(if ,(decompile-expr test globs stack closed) ,(decompile-expr then globs stack closed) ,(decompile-expr els globs stack closed))] [(struct application (rator rands)) (let ([stack (append (for/list ([i (in-list rands)]) (gensym 'rand)) stack)]) (annotate-unboxed rands (annotate-inline `(,(decompile-expr rator globs stack closed) ,@(map (lambda (rand) (decompile-expr rand globs stack closed)) rands)))))] [(struct apply-values (proc args-expr)) `(#%apply-values ,(decompile-expr proc globs stack closed) ,(decompile-expr args-expr globs stack closed))] [(struct with-immed-mark (key-expr val-expr body-expr)) (let ([id (gensym 'cmval)]) `(#%call-with-immediate-continuation-mark ,(decompile-expr key-expr globs stack closed) (lambda (,id) ,(decompile-expr body-expr globs (cons id stack) closed)) ,(decompile-expr val-expr globs stack closed)))] [(struct seq (exprs)) `(begin ,@(for/list ([expr (in-list exprs)]) (decompile-expr expr globs stack closed)))] [(struct beg0 (exprs)) `(begin0 ,@(for/list ([expr (in-list exprs)]) (decompile-expr expr globs stack closed)) ;; Make sure a single expression doesn't look like tail position: ,@(if (null? (cdr exprs)) (list #f) null))] [(struct with-cont-mark (key val body)) `(with-continuation-mark ,(decompile-expr key globs stack closed) ,(decompile-expr val globs stack closed) ,(decompile-expr body globs stack closed))] [(struct closure (lam gen-id)) (if (hash-ref closed gen-id #f) gen-id (begin (hash-set! closed gen-id #t) `(#%closed ,gen-id ,(decompile-expr lam globs stack closed))))] [(? void?) (list 'void)] [_ `(quote ,expr)])) (define (decompile-lam expr globs stack closed) (match expr [(struct closure (lam gen-id)) (decompile-lam lam globs stack closed)] [(struct lam (name flags num-params arg-types rest? closure-map closure-types tl-map max-let-depth body)) (let ([vars (for/list ([i (in-range num-params)] [type (in-list arg-types)]) (gensym (format "~a~a-" (case type [(ref) "argbox"] [(val) "arg"] [else (format "arg~a" type)]) i)))] [rest-vars (if rest? (list (gensym 'rest)) null)] [captures (map (lambda (v) (list-ref/protect stack v 'lam)) (vector->list closure-map))]) `((,@vars . ,(if rest? (car rest-vars) null)) ,@(if (and name (not (null? name))) `(',name) null) ,@(if (null? flags) null `('(flags: ,@flags))) ,@(if (null? captures) null `('(captures: ,@(map (lambda (c t) (if t `(,t ,c) c)) captures closure-types) ,@(if (not tl-map) '() (list (for/list ([pos (in-list (sort (set->list tl-map) <))]) (list-ref/protect (glob-desc-vars globs) pos 'lam))))))) ,(decompile-expr body globs (append captures (append vars rest-vars)) closed)))])) (define (annotate-inline a) a) (define (annotate-unboxed args a) a) ;; ---------------------------------------- (define (decompile-deserialize mpis inspector bulk-binding-registry num-mutables mutable-vec num-shares share-vec mutable-fill-vec result-vec) ;; Names for shared values: (define shared (for/vector ([i (in-range (+ num-mutables num-shares))]) (string->symbol (format "~a:~a" (if (i . < . num-mutables) 'mutable 'shared) i)))) (define (infer-name! d i) (when (pair? d) (define new-name (case (car d) [(deserialize-scope) 'scope] [(srcloc) 'srcloc] [else #f])) (when new-name (vector-set! shared i (string->symbol (format "~a:~a" new-name i)))))) (define mutables (make-vector num-mutables #f)) ;; Make mutable shells (for/fold ([pos 0]) ([i (in-range num-mutables)]) (define-values (d next-pos) (decode-shell mutable-vec pos mpis inspector bulk-binding-registry shared)) (vector-set! mutables i d) (infer-name! d i) next-pos) Construct shared values (define shareds (make-vector num-shares #f)) (for/fold ([pos 0]) ([i (in-range num-shares)]) (define-values (d next-pos) (decode share-vec pos mpis inspector bulk-binding-registry shared)) (vector-set! shareds i d) (infer-name! d (+ i num-mutables)) next-pos) ;; Fill in mutable shells (define-values (fill-pos rev-fills) (for/fold ([pos 0] [rev-fills null]) ([i (in-range num-mutables)] [v (in-vector shared)]) (define-values (fill next-pos) (decode-fill! v mutable-fill-vec pos mpis inspector bulk-binding-registry shared)) (values next-pos (if fill (cons fill rev-fills) rev-fills)))) Construct the final result (define-values (result done-pos) (decode result-vec 0 mpis inspector bulk-binding-registry shared)) `(let (,(for/list ([i (in-range num-mutables)]) `(,(vector-ref shared i) ,(vector-ref mutables i)))) (let* (,(for/list ([i (in-range num-shares)]) `(,(vector-ref shared (+ i num-mutables)) ,(vector-ref shareds i)))) ,@(reverse rev-fills) ,result))) ;; Decode the construction of a mutable variable (define (decode-shell vec pos mpis inspector bulk-binding-registry shared) (case (vector-ref vec pos) [(#:box) (values (list 'box #f) (add1 pos))] [(#:vector) (values `(make-vector ,(vector-ref vec (add1 pos))) (+ pos 2))] [(#:hash) (values (list 'make-hasheq) (add1 pos))] [(#:hasheq) (values (list 'make-hasheq) (add1 pos))] [(#:hasheqv) (values (list 'make-hasheqv) (add1 pos))] [else (decode vec pos mpis inspector bulk-binding-registry shared)])) ;; The decoder that is used for most purposes (define (decode vec pos mpis inspector bulk-binding-registry shared) (define-syntax decodes (syntax-rules () [(_ (id ...) rhs) (decodes #:pos (add1 pos) (id ...) rhs)] [(_ #:pos pos () rhs) (values rhs pos)] [(_ #:pos pos ([#:ref id0] id ...) rhs) (let-values ([(id0 next-pos) (let ([i (vector-ref vec pos)]) (if (exact-integer? i) (values (vector-ref shared i) (add1 pos)) (decode vec pos mpis inspector bulk-binding-registry shared)))]) (decodes #:pos next-pos (id ...) rhs))] [(_ #:pos pos (id0 id ...) rhs) (let-values ([(id0 next-pos) (decode vec pos mpis inspector bulk-binding-registry shared)]) (decodes #:pos next-pos (id ...) rhs))])) (define-syntax-rule (decode* (deser id ...)) (decodes (id ...) `(deser ,id ...))) (define kw (vector-ref vec pos)) (case kw [(#:ref) (values (vector-ref shared (vector-ref vec (add1 pos))) (+ pos 2))] [(#:inspector) (values inspector (add1 pos))] [(#:bulk-binding-registry) (values bulk-binding-registry (add1 pos))] [(#:syntax #:datum->syntax) (decodes (content [#:ref context] [#:ref srcloc]) `(deserialize-syntax ,content ,context ,srcloc #f #f ,inspector))] [(#:syntax+props) (decodes (content [#:ref context] [#:ref srcloc] props tamper) `(deserialize-syntax ,content ,context ,srcloc ,props ,tamper ,inspector))] [(#:srcloc) (decode* (srcloc source line column position span))] [(#:quote) (values (vector-ref vec (add1 pos)) (+ pos 2))] [(#:mpi) (values `(vector-ref ,mpis ,(vector-ref vec (add1 pos))) (+ pos 2))] [(#:box) (decode* (box-immutable v))] [(#:cons) (decode* (cons a d))] [(#:list #:vector #:set #:seteq #:seteqv) (define len (vector-ref vec (add1 pos))) (define r (make-vector len)) (define next-pos (for/fold ([pos (+ pos 2)]) ([i (in-range len)]) (define-values (v next-pos) (decodes #:pos pos (v) v)) (vector-set! r i v) next-pos)) (values `(,(case (vector-ref vec pos) [(#:list) 'list] [(#:vector) 'vector] [(#:set) 'set] [(#:seteq) 'seteq] [(#:seteqv) 'seteqv]) ,@(vector->list r)) next-pos)] [(#:hash #:hasheq #:hasheqv #:hasheqv/phase+space) (define len (vector-ref vec (add1 pos))) (define-values (l next-pos) (for/fold ([l null] [pos (+ pos 2)]) ([i (in-range len)]) (decodes #:pos pos (k v) (list* v (if (and (eq? kw '#:hasheqv/phase+space) (pair? k)) `(phase+space ,(car k) ,(cdr k)) k) l)))) (values `(,(case (vector-ref vec pos) [(#:hash) 'hash] [(#:hasheq) 'hasheq] [(#:hasheqv #:hasheqv/phase+space) 'hasheqv]) ,@(reverse l)) next-pos)] [(#:prefab) (define-values (key next-pos) (decodes #:pos (add1 pos) (k) k)) (define len (vector-ref vec next-pos)) (define-values (r done-pos) (for/fold ([r null] [pos (add1 next-pos)]) ([i (in-range len)]) (decodes #:pos pos (v) (cons v r)))) (values `(make-prefab-struct ',key ,@(reverse r)) done-pos)] [(#:scope) (decode* (deserialize-scope))] [(#:scope+kind) (decode* (deserialize-scope kind))] [(#:multi-scope) (decode* (deserialize-multi-scope name scopes))] [(#:shifted-multi-scope) (decode* (deserialize-shifted-multi-scope phase multi-scope))] [(#:table-with-bulk-bindings) (decode* (deserialize-table-with-bulk-bindings syms bulk-bindings))] [(#:bulk-binding-at) (decode* (deserialize-bulk-binding-at scopes bulk))] [(#:representative-scope) (decode* (deserialize-representative-scope kind phase))] [(#:module-binding) (decode* (deserialize-full-module-binding module sym phase nominal-module nominal-phase nominal-sym nominal-require-phase free=id extra-inspector extra-nominal-bindings))] [(#:simple-module-binding) (decode* (deserialize-simple-module-binding module sym phase nominal-module))] [(#:local-binding) (decode* (deserialize-full-local-binding key free=id))] [(#:bulk-binding) (decode* (deserialize-bulk-binding prefix excepts mpi provide-phase-level phase-shift bulk-binding-registry))] [(#:provided) (decode* (deserialize-provided binding protected? syntax?))] [else (values `(quote ,(vector-ref vec pos)) (add1 pos))])) ;; Decode the filling of mutable values, which has its own encoding ;; variant (define (decode-fill! v vec pos mpis inspector bulk-binding-registry shared) (case (vector-ref vec pos) [(#f) (values #f (add1 pos))] [(#:set-box!) (define-values (c next-pos) (decode vec (add1 pos) mpis inspector bulk-binding-registry shared)) (values `(set-box! ,v ,c) next-pos)] [(#:set-vector!) (define len (vector-ref vec (add1 pos))) (define-values (l next-pos) (for/fold ([l null] [pos (+ pos 2)]) ([i (in-range len)]) (define-values (c next-pos) (decode vec pos mpis inspector bulk-binding-registry shared)) (values (cons `(vector-set! ,v ,i ,c) l) next-pos))) (values `(begin ,@(reverse l)) next-pos)] [(#:set-hash!) (define len (vector-ref vec (add1 pos))) (define-values (l next-pos) (for/fold ([l null] [pos (+ pos 2)]) ([i (in-range len)]) (define-values (key next-pos) (decode vec pos mpis inspector bulk-binding-registry shared)) (define-values (val done-pos) (decode vec next-pos mpis inspector bulk-binding-registry shared)) (values (cons `(hash-set! ,v ,key ,val) l) done-pos))) (values `(begin ,@(reverse l)) next-pos)] [(#:scope-fill!) (define-values (c next-pos) (decode vec (add1 pos) mpis inspector bulk-binding-registry shared)) (values `(deserialize-scope-fill! ,v ,c) next-pos)] [(#:representative-scope-fill!) (define-values (a next-pos) (decode vec (add1 pos) mpis inspector bulk-binding-registry shared)) (define-values (d done-pos) (decode vec next-pos mpis inspector bulk-binding-registry shared)) (values `(deserialize-representative-scope-fill! ,v ,a ,d) done-pos)] [else (error 'deserialize "bad fill encoding: ~v" (vector-ref vec pos))])) ;; ---------------------------------------- #; (begin (require scheme/pretty) (define (try e) (pretty-print (decompile (zo-parse (let-values ([(in out) (make-pipe)]) (write (parameterize ([current-namespace (make-base-namespace)]) (compile e)) out) (close-output-port out) in))))) (pretty-print (decompile (zo-parse (open-input-file "/home/mflatt/proj/plt/collects/tests/mzscheme/benchmarks/common/sboyer_ss.zo")))) #; (try '(lambda (q . more) (letrec ([f (lambda (x) f)]) (lambda (g) f)))))
null
https://raw.githubusercontent.com/takikawa/racket-ppa/26d6ae74a1b19258c9789b7c14c074d867a4b56b/share/pkgs/compiler-lib/compiler/decompile.rkt
racket
---------------------------------------- ---------------------------------------- Main entry: primitive Make sure a single expression doesn't look like tail position: ---------------------------------------- Names for shared values: Make mutable shells Fill in mutable shells Decode the construction of a mutable variable The decoder that is used for most purposes Decode the filling of mutable values, which has its own encoding variant ----------------------------------------
#lang racket/base (require racket/linklet compiler/zo-parse compiler/zo-marshal syntax/modcollapse racket/port racket/match racket/list racket/set racket/path ffi/unsafe/vm (only-in '#%linklet compiled-position->primitive) "private/deserialize.rkt" "private/chez.rkt") (provide decompile) (define primitive-table (let ([value-names (let ([ns (make-base-empty-namespace)]) (parameterize ([current-namespace ns]) (namespace-require ''#%kernel) (namespace-require ''#%unsafe) (namespace-require ''#%flfxnum) (namespace-require ''#%extfl) (namespace-require ''#%futures) (namespace-require ''#%foreign) (namespace-require ''#%paramz) (namespace-require ''#%linklet) (for/hasheq ([name (in-list (namespace-mapped-symbols))]) (values (namespace-variable-value name #t (lambda () #f)) name))))]) (for/hash ([i (in-naturals)] #:break (not (compiled-position->primitive i))) (define v (compiled-position->primitive i)) (values i (or (hash-ref value-names v #f) `',v))))) (define (list-ref/protect l pos who) (list-ref l pos) (if (pos . < . (length l)) (list-ref l pos) `(OUT-OF-BOUNDS ,who ,pos ,(length l) ,l))) (define-struct glob-desc (vars)) (define (decompile top #:to-linklets? [to-linklets? #f]) (cond [(linkl-directory? top) (cond [to-linklets? (cons 'linklet-directory (apply append (for/list ([(k v) (in-hash (linkl-directory-table top))]) (list '#:name k '#:bundle (decompile v #:to-linklets? to-linklets?)))))] [else (define main (hash-ref (linkl-directory-table top) '() #f)) (cond [(and main (hash-ref (linkl-bundle-table main) 'decl #f)) (decompile-module-with-submodules top '() main)] [main (decompile-single-top main)] [else (decompile-multi-top top)])])] [(linkl-bundle? top) (cond [to-linklets? (cons 'linklet-bundle (apply append (for/list ([(k v) (in-hash (linkl-bundle-table top))]) (case (and (not to-linklets?) k) [(stx-data) (list '#:stx-data (decompile-data-linklet v))] [else (list '#:key k '#:value (decompile v #:to-linklets? to-linklets?))]))))] [else (decompile-module top)])] [(or (linkl? top) (linklet? top)) (decompile-linklet top)] [(faslable-correlated-linklet? top) (strip-correlated (faslable-correlated-linklet-expr top))] [else `(quote ,top)])) (define (decompile-module-with-submodules l-dir name-list main-l) (decompile-module main-l (lambda () (for/list ([(k l) (in-hash (linkl-directory-table l-dir))] #:when (and (list? k) (= (length k) (add1 (length name-list))) (for/and ([s1 (in-list name-list)] [s2 (in-list k)]) (eq? s1 s2)))) (decompile-module-with-submodules l-dir k l))))) (define (decompile-module l [get-nested (lambda () '())]) (define ht (linkl-bundle-table l)) (define phases (sort (for/list ([k (in-hash-keys ht)] #:when (exact-integer? k)) k) <)) (define-values (mpi-vector requires provides phase-to-link-modules) (deserialize-requires-and-provides l)) (define (phase-wrap phase l) (case phase [(0) l] [(1) `((for-syntax ,@l))] [(-1) `((for-template ,@l))] [(#f) `((for-label ,@l))] [else `((for-meta ,phase ,@l))])) `(module ,(hash-ref ht 'name 'unknown) .... (require ,@(apply append (for/list ([phase+mpis (in-list requires)]) (phase-wrap (car phase+mpis) (map collapse-module-path-index (cdr phase+mpis)))))) (provide ,@(apply append (for/list ([(phase ht) (in-hash provides)]) (phase-wrap phase (hash-keys ht))))) ,@(let loop ([phases phases] [depth 0]) (cond [(null? phases) '()] [(= depth (car phases)) (append (decompile-linklet (hash-ref ht (car phases)) #:just-body? #t) (loop (cdr phases) depth))] [else (define l (loop phases (add1 depth))) (define (convert-syntax-definition s wrap) (match s [`(let ,bindings ,body) (convert-syntax-definition body (lambda (rhs) `(let ,bindings ,rhs)))] [`(begin (.set-transformer! ',id ,rhs) ',(? void?)) `(define-syntaxes ,id ,(wrap rhs))] [`(begin (.set-transformer! ',ids ,rhss) ... ',(? void?)) `(define-syntaxes ,ids ,(wrap `(values . ,rhss)))] [_ #f])) (let loop ([l l] [accum '()]) (cond [(null? l) (if (null? accum) '() `((begin-for-syntax ,@(reverse accum))))] [(convert-syntax-definition (car l) values) => (lambda (s) (append (loop null accum) (cons s (loop (cdr l) null))))] [else (loop (cdr l) (cons (car l) accum))]))])) ,@(get-nested) ,@(let ([l (hash-ref ht 'stx-data #f)]) (if l `((begin-for-all (define (.get-syntax-literal! pos) .... ,@(decompile-data-linklet l) ....))) null)))) (define (decompile-single-top b) (define forms (let ([l (hash-ref (linkl-bundle-table b) 0 #f)]) (if l (decompile-linklet l #:just-body? #t) '(<opaque-compiled-linklet>)))) (if (= (length forms) 1) (car forms) `(begin ,@forms))) (define (decompile-multi-top ld) `(begin ,@(let loop ([i 0]) (define b (hash-ref (linkl-directory-table ld) (list (string->symbol (format "~a" i))) #f)) (define l (and b (hash-ref (linkl-bundle-table b) 0 #f))) (cond [l (append (decompile-linklet l #:just-body? #t) (loop (add1 i)))] [else null])))) (define (decompile-linklet l #:just-body? [just-body? #f]) (match l [(struct linkl (name importss import-shapess exports internals lifts source-names body max-let-depth needs-instance?)) (define closed (make-hasheq)) (define globs (glob-desc (append (list 'root) (apply append importss) exports internals lifts))) (define body-l (for/list ([form (in-list body)]) (decompile-form form globs '(#%globals) closed))) (if just-body? body-l `(linklet ,importss ,exports '(import-shapes: ,@(for/list ([imports (in-list importss)] [import-shapes (in-list import-shapess)] #:when #t [import (in-list imports)] [import-shape (in-list import-shapes)] #:when import-shape) `[,import ,import-shape])) '(source-names: ,source-names) ,@body-l))] [(struct faslable-correlated-linklet (expr name)) (match (strip-correlated expr) [`(linklet ,imports ,exports ,body-l ...) body-l])] [(? linklet?) (case (system-type 'vm) [(chez-scheme) (define-values (fmt code literals) ((vm-primitive 'linklet-fasled-code+arguments) l)) (cond [code (case fmt [(compile) (cond [(not (current-partial-fasl)) (define proc (vm-eval `(load-compiled-from-port (open-bytevector-input-port ,code) ',literals))) (decompile-chez-procedure proc)] [else (disassemble-in-description `(#(FASL #:length ,(bytes-length code) #:literals ,literals ,(vm-eval `(($primitive $describe-fasl-from-port) (open-bytevector-input-port ,code) ',literals)))))])] [(interpret) (define bytecode (vm-eval `(fasl-read (open-bytevector-input-port ,code) 'load ',literals))) (list `(#%interpret ,(unwrap-chez-interpret-jitified bytecode)))] [else '(....)])] [else `(....)])])])) (define (decompile-data-linklet l) (match l [(struct linkl (_ _ _ _ _ _ _ (list vec-def (struct def-values (_ deser-lam))) _ _)) (match deser-lam [(struct lam (_ _ _ _ _ _ _ _ _ (struct seq ((list vec-copy! _))))) (match vec-copy! [(struct application (_ (list _ _ (struct application (_ (list mpi-vector inspector bulk-binding-registry num-mutables mutable-vec num-shares share-vec mutable-fill-vec result-vec)))))) (decompile-deserialize '.mpi-vector '.inspector '.bulk-binding-registry num-mutables mutable-vec num-shares share-vec mutable-fill-vec result-vec)] [_ (decompile-linklet l)])] [_ (decompile-linklet l)])] [(struct faslable-correlated-linklet (expr name)) (match (strip-correlated expr) [`(linklet ,_ ,_ ,_ (define-values ,_ (lambda ,_ (begin (vector-copy! ,_ ,_ (let-values ([(.inspector) #f]) (let-values ([(data) '#(,mutable-vec ,share-vec ,mutable-fill-vec ,result-vec)]) (deserialize .mpi-vector .inspector .bulk-binding-registry ',num-mutables (,_ data 0) ',num-shares (,_ data 1) (,_ data 2) (,_ data 3))))) ,_)))) (decompile-deserialize '.mpi-vector '.inspector '.bulk-binding-registry num-mutables mutable-vec num-shares share-vec mutable-fill-vec result-vec)] [_ (decompile-linklet l)])] [_ (decompile-linklet l)])) (define (decompile-form form globs stack closed) (match form [(struct def-values (ids rhs)) `(define-values ,(map (lambda (tl) (match tl [(struct toplevel (depth pos const? set-const?)) (list-ref/protect (glob-desc-vars globs) pos 'def-vals)])) ids) ,(if (inline-variant? rhs) `(begin ,(list 'quote '%%inline-variant%%) ,(decompile-expr (inline-variant-inline rhs) globs stack closed) ,(decompile-expr (inline-variant-direct rhs) globs stack closed)) (decompile-expr rhs globs stack closed)))] [(struct seq (forms)) `(begin ,@(map (lambda (form) (decompile-form form globs stack closed)) forms))] [_ (decompile-expr form globs stack closed)])) (define (extract-name name) (if (symbol? name) (gensym name) (if (vector? name) (gensym (vector-ref name 0)) #f))) (define (extract-id expr) (match expr [(struct lam (name flags num-params arg-types rest? closure-map closure-types tl-map max-let-depth body)) (extract-name name)] [(struct case-lam (name lams)) (extract-name name)] [(struct closure (lam gen-id)) (extract-id lam)] [_ #f])) (define (extract-ids! body ids) (match body [(struct let-rec (procs body)) (for ([proc (in-list procs)] [delta (in-naturals)]) (when (< -1 delta (vector-length ids)) (vector-set! ids delta (extract-id proc)))) (extract-ids! body ids)] [(struct install-value (val-count pos boxes? rhs body)) (extract-ids! body ids)] [(struct boxenv (pos body)) (extract-ids! body ids)] [_ #f])) (define (decompile-tl expr globs stack closed no-check?) (match expr [(struct toplevel (depth pos const? ready?)) (let ([id (list-ref/protect (glob-desc-vars globs) pos 'toplevel)]) (cond [no-check? id] [(and (not const?) (not ready?)) `(#%checked ,id)] [ ( and const ? ready ? ) ` ( # % const , i d ) ] [ const ? ` ( # % iconst , i d ) ] [else id]))])) (define (decompile-expr expr globs stack closed) (match expr [(struct toplevel (depth pos const? ready?)) (decompile-tl expr globs stack closed #f)] [(struct varref (tl dummy constant? from-unsafe?)) `(#%variable-reference . ,(cond [(not tl) '()] [(eq? tl #t) '(<constant-local>)] [else (list (decompile-tl tl globs stack closed #t))]))] [(struct primval (id)) (hash-ref primitive-table id (lambda () (error "unknown primitive: " id)))] [(struct assign (id rhs undef-ok?)) `(set! ,(decompile-expr id globs stack closed) ,(decompile-expr rhs globs stack closed))] [(struct localref (unbox? offset clear? other-clears? type)) (let ([id (list-ref/protect stack offset 'localref)]) (let ([e (if unbox? `(#%unbox ,id) id)]) (if clear? `(#%sfs-clear ,e) e)))] [(? lam?) `(lambda . ,(decompile-lam expr globs stack closed))] [(struct case-lam (name lams)) `(case-lambda ,@(map (lambda (lam) (decompile-lam lam globs stack closed)) lams))] [(struct let-one (rhs body type unused?)) (let ([id (or (extract-id rhs) (gensym (or type (if unused? 'unused 'local))))]) `(let ([,id ,(decompile-expr rhs globs (cons id stack) closed)]) ,(decompile-expr body globs (cons id stack) closed)))] [(struct let-void (count boxes? body)) (let ([ids (make-vector count #f)]) (extract-ids! body ids) (let ([vars (for/list ([i (in-range count)] [id (in-vector ids)]) (or id (gensym (if boxes? 'localvb 'localv))))]) `(let ,(map (lambda (i) `[,i ,(if boxes? `(#%box ?) '?)]) vars) ,(decompile-expr body globs (append vars stack) closed))))] [(struct let-rec (procs body)) `(begin (#%set!-rec-values ,(for/list ([p (in-list procs)] [i (in-naturals)]) (list-ref/protect stack i 'let-rec)) ,@(map (lambda (proc) (decompile-expr proc globs stack closed)) procs)) ,(decompile-expr body globs stack closed))] [(struct install-value (count pos boxes? rhs body)) `(begin (,(if boxes? '#%set-boxes! 'set!-values) ,(for/list ([i (in-range count)]) (list-ref/protect stack (+ i pos) 'install-value)) ,(decompile-expr rhs globs stack closed)) ,(decompile-expr body globs stack closed))] [(struct boxenv (pos body)) (let ([id (list-ref/protect stack pos 'boxenv)]) `(begin (set! ,id (#%box ,id)) ,(decompile-expr body globs stack closed)))] [(struct branch (test then els)) `(if ,(decompile-expr test globs stack closed) ,(decompile-expr then globs stack closed) ,(decompile-expr els globs stack closed))] [(struct application (rator rands)) (let ([stack (append (for/list ([i (in-list rands)]) (gensym 'rand)) stack)]) (annotate-unboxed rands (annotate-inline `(,(decompile-expr rator globs stack closed) ,@(map (lambda (rand) (decompile-expr rand globs stack closed)) rands)))))] [(struct apply-values (proc args-expr)) `(#%apply-values ,(decompile-expr proc globs stack closed) ,(decompile-expr args-expr globs stack closed))] [(struct with-immed-mark (key-expr val-expr body-expr)) (let ([id (gensym 'cmval)]) `(#%call-with-immediate-continuation-mark ,(decompile-expr key-expr globs stack closed) (lambda (,id) ,(decompile-expr body-expr globs (cons id stack) closed)) ,(decompile-expr val-expr globs stack closed)))] [(struct seq (exprs)) `(begin ,@(for/list ([expr (in-list exprs)]) (decompile-expr expr globs stack closed)))] [(struct beg0 (exprs)) `(begin0 ,@(for/list ([expr (in-list exprs)]) (decompile-expr expr globs stack closed)) ,@(if (null? (cdr exprs)) (list #f) null))] [(struct with-cont-mark (key val body)) `(with-continuation-mark ,(decompile-expr key globs stack closed) ,(decompile-expr val globs stack closed) ,(decompile-expr body globs stack closed))] [(struct closure (lam gen-id)) (if (hash-ref closed gen-id #f) gen-id (begin (hash-set! closed gen-id #t) `(#%closed ,gen-id ,(decompile-expr lam globs stack closed))))] [(? void?) (list 'void)] [_ `(quote ,expr)])) (define (decompile-lam expr globs stack closed) (match expr [(struct closure (lam gen-id)) (decompile-lam lam globs stack closed)] [(struct lam (name flags num-params arg-types rest? closure-map closure-types tl-map max-let-depth body)) (let ([vars (for/list ([i (in-range num-params)] [type (in-list arg-types)]) (gensym (format "~a~a-" (case type [(ref) "argbox"] [(val) "arg"] [else (format "arg~a" type)]) i)))] [rest-vars (if rest? (list (gensym 'rest)) null)] [captures (map (lambda (v) (list-ref/protect stack v 'lam)) (vector->list closure-map))]) `((,@vars . ,(if rest? (car rest-vars) null)) ,@(if (and name (not (null? name))) `(',name) null) ,@(if (null? flags) null `('(flags: ,@flags))) ,@(if (null? captures) null `('(captures: ,@(map (lambda (c t) (if t `(,t ,c) c)) captures closure-types) ,@(if (not tl-map) '() (list (for/list ([pos (in-list (sort (set->list tl-map) <))]) (list-ref/protect (glob-desc-vars globs) pos 'lam))))))) ,(decompile-expr body globs (append captures (append vars rest-vars)) closed)))])) (define (annotate-inline a) a) (define (annotate-unboxed args a) a) (define (decompile-deserialize mpis inspector bulk-binding-registry num-mutables mutable-vec num-shares share-vec mutable-fill-vec result-vec) (define shared (for/vector ([i (in-range (+ num-mutables num-shares))]) (string->symbol (format "~a:~a" (if (i . < . num-mutables) 'mutable 'shared) i)))) (define (infer-name! d i) (when (pair? d) (define new-name (case (car d) [(deserialize-scope) 'scope] [(srcloc) 'srcloc] [else #f])) (when new-name (vector-set! shared i (string->symbol (format "~a:~a" new-name i)))))) (define mutables (make-vector num-mutables #f)) (for/fold ([pos 0]) ([i (in-range num-mutables)]) (define-values (d next-pos) (decode-shell mutable-vec pos mpis inspector bulk-binding-registry shared)) (vector-set! mutables i d) (infer-name! d i) next-pos) Construct shared values (define shareds (make-vector num-shares #f)) (for/fold ([pos 0]) ([i (in-range num-shares)]) (define-values (d next-pos) (decode share-vec pos mpis inspector bulk-binding-registry shared)) (vector-set! shareds i d) (infer-name! d (+ i num-mutables)) next-pos) (define-values (fill-pos rev-fills) (for/fold ([pos 0] [rev-fills null]) ([i (in-range num-mutables)] [v (in-vector shared)]) (define-values (fill next-pos) (decode-fill! v mutable-fill-vec pos mpis inspector bulk-binding-registry shared)) (values next-pos (if fill (cons fill rev-fills) rev-fills)))) Construct the final result (define-values (result done-pos) (decode result-vec 0 mpis inspector bulk-binding-registry shared)) `(let (,(for/list ([i (in-range num-mutables)]) `(,(vector-ref shared i) ,(vector-ref mutables i)))) (let* (,(for/list ([i (in-range num-shares)]) `(,(vector-ref shared (+ i num-mutables)) ,(vector-ref shareds i)))) ,@(reverse rev-fills) ,result))) (define (decode-shell vec pos mpis inspector bulk-binding-registry shared) (case (vector-ref vec pos) [(#:box) (values (list 'box #f) (add1 pos))] [(#:vector) (values `(make-vector ,(vector-ref vec (add1 pos))) (+ pos 2))] [(#:hash) (values (list 'make-hasheq) (add1 pos))] [(#:hasheq) (values (list 'make-hasheq) (add1 pos))] [(#:hasheqv) (values (list 'make-hasheqv) (add1 pos))] [else (decode vec pos mpis inspector bulk-binding-registry shared)])) (define (decode vec pos mpis inspector bulk-binding-registry shared) (define-syntax decodes (syntax-rules () [(_ (id ...) rhs) (decodes #:pos (add1 pos) (id ...) rhs)] [(_ #:pos pos () rhs) (values rhs pos)] [(_ #:pos pos ([#:ref id0] id ...) rhs) (let-values ([(id0 next-pos) (let ([i (vector-ref vec pos)]) (if (exact-integer? i) (values (vector-ref shared i) (add1 pos)) (decode vec pos mpis inspector bulk-binding-registry shared)))]) (decodes #:pos next-pos (id ...) rhs))] [(_ #:pos pos (id0 id ...) rhs) (let-values ([(id0 next-pos) (decode vec pos mpis inspector bulk-binding-registry shared)]) (decodes #:pos next-pos (id ...) rhs))])) (define-syntax-rule (decode* (deser id ...)) (decodes (id ...) `(deser ,id ...))) (define kw (vector-ref vec pos)) (case kw [(#:ref) (values (vector-ref shared (vector-ref vec (add1 pos))) (+ pos 2))] [(#:inspector) (values inspector (add1 pos))] [(#:bulk-binding-registry) (values bulk-binding-registry (add1 pos))] [(#:syntax #:datum->syntax) (decodes (content [#:ref context] [#:ref srcloc]) `(deserialize-syntax ,content ,context ,srcloc #f #f ,inspector))] [(#:syntax+props) (decodes (content [#:ref context] [#:ref srcloc] props tamper) `(deserialize-syntax ,content ,context ,srcloc ,props ,tamper ,inspector))] [(#:srcloc) (decode* (srcloc source line column position span))] [(#:quote) (values (vector-ref vec (add1 pos)) (+ pos 2))] [(#:mpi) (values `(vector-ref ,mpis ,(vector-ref vec (add1 pos))) (+ pos 2))] [(#:box) (decode* (box-immutable v))] [(#:cons) (decode* (cons a d))] [(#:list #:vector #:set #:seteq #:seteqv) (define len (vector-ref vec (add1 pos))) (define r (make-vector len)) (define next-pos (for/fold ([pos (+ pos 2)]) ([i (in-range len)]) (define-values (v next-pos) (decodes #:pos pos (v) v)) (vector-set! r i v) next-pos)) (values `(,(case (vector-ref vec pos) [(#:list) 'list] [(#:vector) 'vector] [(#:set) 'set] [(#:seteq) 'seteq] [(#:seteqv) 'seteqv]) ,@(vector->list r)) next-pos)] [(#:hash #:hasheq #:hasheqv #:hasheqv/phase+space) (define len (vector-ref vec (add1 pos))) (define-values (l next-pos) (for/fold ([l null] [pos (+ pos 2)]) ([i (in-range len)]) (decodes #:pos pos (k v) (list* v (if (and (eq? kw '#:hasheqv/phase+space) (pair? k)) `(phase+space ,(car k) ,(cdr k)) k) l)))) (values `(,(case (vector-ref vec pos) [(#:hash) 'hash] [(#:hasheq) 'hasheq] [(#:hasheqv #:hasheqv/phase+space) 'hasheqv]) ,@(reverse l)) next-pos)] [(#:prefab) (define-values (key next-pos) (decodes #:pos (add1 pos) (k) k)) (define len (vector-ref vec next-pos)) (define-values (r done-pos) (for/fold ([r null] [pos (add1 next-pos)]) ([i (in-range len)]) (decodes #:pos pos (v) (cons v r)))) (values `(make-prefab-struct ',key ,@(reverse r)) done-pos)] [(#:scope) (decode* (deserialize-scope))] [(#:scope+kind) (decode* (deserialize-scope kind))] [(#:multi-scope) (decode* (deserialize-multi-scope name scopes))] [(#:shifted-multi-scope) (decode* (deserialize-shifted-multi-scope phase multi-scope))] [(#:table-with-bulk-bindings) (decode* (deserialize-table-with-bulk-bindings syms bulk-bindings))] [(#:bulk-binding-at) (decode* (deserialize-bulk-binding-at scopes bulk))] [(#:representative-scope) (decode* (deserialize-representative-scope kind phase))] [(#:module-binding) (decode* (deserialize-full-module-binding module sym phase nominal-module nominal-phase nominal-sym nominal-require-phase free=id extra-inspector extra-nominal-bindings))] [(#:simple-module-binding) (decode* (deserialize-simple-module-binding module sym phase nominal-module))] [(#:local-binding) (decode* (deserialize-full-local-binding key free=id))] [(#:bulk-binding) (decode* (deserialize-bulk-binding prefix excepts mpi provide-phase-level phase-shift bulk-binding-registry))] [(#:provided) (decode* (deserialize-provided binding protected? syntax?))] [else (values `(quote ,(vector-ref vec pos)) (add1 pos))])) (define (decode-fill! v vec pos mpis inspector bulk-binding-registry shared) (case (vector-ref vec pos) [(#f) (values #f (add1 pos))] [(#:set-box!) (define-values (c next-pos) (decode vec (add1 pos) mpis inspector bulk-binding-registry shared)) (values `(set-box! ,v ,c) next-pos)] [(#:set-vector!) (define len (vector-ref vec (add1 pos))) (define-values (l next-pos) (for/fold ([l null] [pos (+ pos 2)]) ([i (in-range len)]) (define-values (c next-pos) (decode vec pos mpis inspector bulk-binding-registry shared)) (values (cons `(vector-set! ,v ,i ,c) l) next-pos))) (values `(begin ,@(reverse l)) next-pos)] [(#:set-hash!) (define len (vector-ref vec (add1 pos))) (define-values (l next-pos) (for/fold ([l null] [pos (+ pos 2)]) ([i (in-range len)]) (define-values (key next-pos) (decode vec pos mpis inspector bulk-binding-registry shared)) (define-values (val done-pos) (decode vec next-pos mpis inspector bulk-binding-registry shared)) (values (cons `(hash-set! ,v ,key ,val) l) done-pos))) (values `(begin ,@(reverse l)) next-pos)] [(#:scope-fill!) (define-values (c next-pos) (decode vec (add1 pos) mpis inspector bulk-binding-registry shared)) (values `(deserialize-scope-fill! ,v ,c) next-pos)] [(#:representative-scope-fill!) (define-values (a next-pos) (decode vec (add1 pos) mpis inspector bulk-binding-registry shared)) (define-values (d done-pos) (decode vec next-pos mpis inspector bulk-binding-registry shared)) (values `(deserialize-representative-scope-fill! ,v ,a ,d) done-pos)] [else (error 'deserialize "bad fill encoding: ~v" (vector-ref vec pos))])) (begin (require scheme/pretty) (define (try e) (pretty-print (decompile (zo-parse (let-values ([(in out) (make-pipe)]) (write (parameterize ([current-namespace (make-base-namespace)]) (compile e)) out) (close-output-port out) in))))) (pretty-print (decompile (zo-parse (open-input-file "/home/mflatt/proj/plt/collects/tests/mzscheme/benchmarks/common/sboyer_ss.zo")))) (try '(lambda (q . more) (letrec ([f (lambda (x) f)]) (lambda (g) f)))))
1832813f73b0ec11fa6c69d4718ba12483ceea91c23fccc03a0e81b78e05f9a7
emillon/ocaml-noise
test_pattern.ml
open OUnit2 open Test_helpers.Infix let test_of_string = let should_be expected s ctxt = let got = Noise.Pattern.of_string s in assert_equal ~ctxt ~cmp:[%eq: (Noise.Pattern.t, string) result] ~printer:[%show: (Noise.Pattern.t, string) result] expected got in "of_string" >::: [ "N" >:= should_be (Ok N) ; "K" >:= should_be (Ok K) ; "X" >:= should_be (Ok X) ; "NN" >:= should_be (Ok NN) ; "NX" >:= should_be (Ok NX) ; "IN" >:= should_be (Ok IN) ; "XN" >:= should_be (Ok XN) ; "XX" >:= should_be (Ok XX) ; "IX" >:= should_be (Ok IX) ; "NK" >:= should_be (Ok NK) ; "IK" >:= should_be (Ok IK) ; "KN" >:= should_be (Ok KN) ; "KK" >:= should_be (Ok KK) ; "KX" >:= should_be (Ok KX) ; "XK" >:= should_be (Ok XK) ; "IKpsk1" >:= should_be (Ok IKpsk1) ; "IKpsk2" >:= should_be (Ok IKpsk2) ; "INpsk1" >:= should_be (Ok INpsk1) ; "INpsk2" >:= should_be (Ok INpsk2) ; "IXpsk2" >:= should_be (Ok IXpsk2) ; "KKpsk0" >:= should_be (Ok KKpsk0) ; "KKpsk2" >:= should_be (Ok KKpsk2) ; "KNpsk0" >:= should_be (Ok KNpsk0) ; "KNpsk2" >:= should_be (Ok KNpsk2) ; "KXpsk2" >:= should_be (Ok KXpsk2) ; "NKpsk0" >:= should_be (Ok NKpsk0) ; "NKpsk2" >:= should_be (Ok NKpsk2) ; "NNpsk0" >:= should_be (Ok NNpsk0) ; "NNpsk2" >:= should_be (Ok NNpsk2) ; "NXpsk2" >:= should_be (Ok NXpsk2) ; "XKpsk3" >:= should_be (Ok XKpsk3) ; "XNpsk3" >:= should_be (Ok XNpsk3) ; "XXpsk3" >:= should_be (Ok XXpsk3) ; "Npsk0" >:= should_be (Ok Npsk0) ; "Xpsk1" >:= should_be (Ok Xpsk1) ; "Kpsk0" >:= should_be (Ok Kpsk0) ] let suite = "Pattern" >::: [ test_of_string ]
null
https://raw.githubusercontent.com/emillon/ocaml-noise/d5a3e0f634fba1f8d948a91c70a1dad6470722b0/test/unit/test_pattern.ml
ocaml
open OUnit2 open Test_helpers.Infix let test_of_string = let should_be expected s ctxt = let got = Noise.Pattern.of_string s in assert_equal ~ctxt ~cmp:[%eq: (Noise.Pattern.t, string) result] ~printer:[%show: (Noise.Pattern.t, string) result] expected got in "of_string" >::: [ "N" >:= should_be (Ok N) ; "K" >:= should_be (Ok K) ; "X" >:= should_be (Ok X) ; "NN" >:= should_be (Ok NN) ; "NX" >:= should_be (Ok NX) ; "IN" >:= should_be (Ok IN) ; "XN" >:= should_be (Ok XN) ; "XX" >:= should_be (Ok XX) ; "IX" >:= should_be (Ok IX) ; "NK" >:= should_be (Ok NK) ; "IK" >:= should_be (Ok IK) ; "KN" >:= should_be (Ok KN) ; "KK" >:= should_be (Ok KK) ; "KX" >:= should_be (Ok KX) ; "XK" >:= should_be (Ok XK) ; "IKpsk1" >:= should_be (Ok IKpsk1) ; "IKpsk2" >:= should_be (Ok IKpsk2) ; "INpsk1" >:= should_be (Ok INpsk1) ; "INpsk2" >:= should_be (Ok INpsk2) ; "IXpsk2" >:= should_be (Ok IXpsk2) ; "KKpsk0" >:= should_be (Ok KKpsk0) ; "KKpsk2" >:= should_be (Ok KKpsk2) ; "KNpsk0" >:= should_be (Ok KNpsk0) ; "KNpsk2" >:= should_be (Ok KNpsk2) ; "KXpsk2" >:= should_be (Ok KXpsk2) ; "NKpsk0" >:= should_be (Ok NKpsk0) ; "NKpsk2" >:= should_be (Ok NKpsk2) ; "NNpsk0" >:= should_be (Ok NNpsk0) ; "NNpsk2" >:= should_be (Ok NNpsk2) ; "NXpsk2" >:= should_be (Ok NXpsk2) ; "XKpsk3" >:= should_be (Ok XKpsk3) ; "XNpsk3" >:= should_be (Ok XNpsk3) ; "XXpsk3" >:= should_be (Ok XXpsk3) ; "Npsk0" >:= should_be (Ok Npsk0) ; "Xpsk1" >:= should_be (Ok Xpsk1) ; "Kpsk0" >:= should_be (Ok Kpsk0) ] let suite = "Pattern" >::: [ test_of_string ]
8778f65f481a9723e60a3396763963936cdfad921e4451a8d240ab998995dcba
anoma/juvix
Base.hs
module Base ( module Test.Tasty, module Test.Tasty.HUnit, module Juvix.Prelude, module Base, module Juvix.Extra.Paths, module Juvix.Prelude.Env, ) where import Control.Monad.Extra as Monad import Data.Algorithm.Diff import Data.Algorithm.DiffOutput import Juvix.Extra.Paths import Juvix.Prelude import Juvix.Prelude.Env import Test.Tasty import Test.Tasty.HUnit data AssertionDescr = Single Assertion | Steps ((String -> IO ()) -> Assertion) data TestDescr = TestDescr { _testName :: String, _testRoot :: Path Abs Dir, -- | relative to root _testAssertion :: AssertionDescr } newtype WASMInfo = WASMInfo { _wasmInfoActual :: Path Abs File -> IO Text } makeLenses ''TestDescr data StdlibMode = StdlibInclude | StdlibExclude deriving stock (Show, Eq) data CompileMode = WASI StdlibMode | WASM WASMInfo mkTest :: TestDescr -> TestTree mkTest TestDescr {..} = case _testAssertion of Single assertion -> testCase _testName $ withCurrentDir _testRoot assertion Steps steps -> testCaseSteps _testName (withCurrentDir _testRoot . steps) assertEqDiffText :: String -> Text -> Text -> Assertion assertEqDiffText = assertEqDiff unpack assertEqDiff :: Eq a => (a -> String) -> String -> a -> a -> Assertion assertEqDiff show_ msg a b | a == b = return () | otherwise = do putStrLn (pack $ ppDiff (getGroupedDiff pa pb)) putStrLn "End diff" Monad.fail msg where pa = lines $ show_ a pb = lines $ show_ b assertEqDiffShow :: (Eq a, Show a) => String -> a -> a -> Assertion assertEqDiffShow = assertEqDiff show assertCmdExists :: Path Rel File -> Assertion assertCmdExists cmd = assertBool ("Command: " <> toFilePath cmd <> " is not present on $PATH") . isJust =<< findExecutable cmd
null
https://raw.githubusercontent.com/anoma/juvix/764c6faa8097066687cdb0431b17bf43a94adab1/test/Base.hs
haskell
| relative to root
module Base ( module Test.Tasty, module Test.Tasty.HUnit, module Juvix.Prelude, module Base, module Juvix.Extra.Paths, module Juvix.Prelude.Env, ) where import Control.Monad.Extra as Monad import Data.Algorithm.Diff import Data.Algorithm.DiffOutput import Juvix.Extra.Paths import Juvix.Prelude import Juvix.Prelude.Env import Test.Tasty import Test.Tasty.HUnit data AssertionDescr = Single Assertion | Steps ((String -> IO ()) -> Assertion) data TestDescr = TestDescr { _testName :: String, _testRoot :: Path Abs Dir, _testAssertion :: AssertionDescr } newtype WASMInfo = WASMInfo { _wasmInfoActual :: Path Abs File -> IO Text } makeLenses ''TestDescr data StdlibMode = StdlibInclude | StdlibExclude deriving stock (Show, Eq) data CompileMode = WASI StdlibMode | WASM WASMInfo mkTest :: TestDescr -> TestTree mkTest TestDescr {..} = case _testAssertion of Single assertion -> testCase _testName $ withCurrentDir _testRoot assertion Steps steps -> testCaseSteps _testName (withCurrentDir _testRoot . steps) assertEqDiffText :: String -> Text -> Text -> Assertion assertEqDiffText = assertEqDiff unpack assertEqDiff :: Eq a => (a -> String) -> String -> a -> a -> Assertion assertEqDiff show_ msg a b | a == b = return () | otherwise = do putStrLn (pack $ ppDiff (getGroupedDiff pa pb)) putStrLn "End diff" Monad.fail msg where pa = lines $ show_ a pb = lines $ show_ b assertEqDiffShow :: (Eq a, Show a) => String -> a -> a -> Assertion assertEqDiffShow = assertEqDiff show assertCmdExists :: Path Rel File -> Assertion assertCmdExists cmd = assertBool ("Command: " <> toFilePath cmd <> " is not present on $PATH") . isJust =<< findExecutable cmd
ff634147041fa8b8476733092312c4ccb7e516faf7d3c44c052de8801f11fe1d
cljfx/cljfx
component.clj
(ns cljfx.component "Part of a public API") (defprotocol Component "Component is an immutable description of some (possibly mutable) object" :extend-via-metadata true (instance [this] "Returns (possibly mutable) object associated with this component")) (extend-protocol Component Object (instance [this] this) nil (instance [this] this))
null
https://raw.githubusercontent.com/cljfx/cljfx/ec3c34e619b2408026b9f2e2ff8665bebf70bf56/src/cljfx/component.clj
clojure
(ns cljfx.component "Part of a public API") (defprotocol Component "Component is an immutable description of some (possibly mutable) object" :extend-via-metadata true (instance [this] "Returns (possibly mutable) object associated with this component")) (extend-protocol Component Object (instance [this] this) nil (instance [this] this))
beed1d619744a5e4af22c98135ded0dc0481d0ae1f1c3dee732eda3959978005
owickstrom/komposition
FastLogger.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} -- | A 'Log' interpreter that uses fast-logger. module Komposition.Logging.FastLogger (runFastLoggerLog) where import Komposition.Prelude hiding (Type, list, Reader, ask, runReader) import qualified Data.Text as Text import Control.Effect import Control.Effect.Reader import Control.Effect.Carrier import Control.Effect.Sum import Komposition.Logging import System.Log.FastLogger newtype FastLoggerLogIOC m a = FastLoggerLogIOC { runFastLoggerLogIOC :: m a } deriving (Functor, Applicative, Monad, MonadIO) instance (MonadIO m, Member (Lift IO) sig, Carrier sig m, Member (Reader LoggerSet) sig) => Carrier (Log :+: sig) (FastLoggerLogIOC m) where ret = pure eff = handleSum (FastLoggerLogIOC . eff . handleCoercible) $ \case WriteLog sev msg k -> k =<< do ls <- ask liftIO (pushLogStr ls ("[" <> toLogStr (Text.toUpper (show sev)) <> "] " <> toLogStr msg)) runFastLoggerLog :: (Monad m, Carrier sig m, Member (Lift IO) sig) => LoggerSet -> Eff (FastLoggerLogIOC (Eff (ReaderC LoggerSet m))) a -> m a runFastLoggerLog ls = runReader ls . runFastLoggerLogIOC . interpret
null
https://raw.githubusercontent.com/owickstrom/komposition/64893d50941b90f44d77fea0dc6d30c061464cf3/src/Komposition/Logging/FastLogger.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # | A 'Log' interpreter that uses fast-logger.
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # module Komposition.Logging.FastLogger (runFastLoggerLog) where import Komposition.Prelude hiding (Type, list, Reader, ask, runReader) import qualified Data.Text as Text import Control.Effect import Control.Effect.Reader import Control.Effect.Carrier import Control.Effect.Sum import Komposition.Logging import System.Log.FastLogger newtype FastLoggerLogIOC m a = FastLoggerLogIOC { runFastLoggerLogIOC :: m a } deriving (Functor, Applicative, Monad, MonadIO) instance (MonadIO m, Member (Lift IO) sig, Carrier sig m, Member (Reader LoggerSet) sig) => Carrier (Log :+: sig) (FastLoggerLogIOC m) where ret = pure eff = handleSum (FastLoggerLogIOC . eff . handleCoercible) $ \case WriteLog sev msg k -> k =<< do ls <- ask liftIO (pushLogStr ls ("[" <> toLogStr (Text.toUpper (show sev)) <> "] " <> toLogStr msg)) runFastLoggerLog :: (Monad m, Carrier sig m, Member (Lift IO) sig) => LoggerSet -> Eff (FastLoggerLogIOC (Eff (ReaderC LoggerSet m))) a -> m a runFastLoggerLog ls = runReader ls . runFastLoggerLogIOC . interpret
4edf773a21b10b4d043e537a6b17ce0f6b97d25a03ac24e99052ebd5d086331c
RichiH/git-repair
PosixFiles.hs
POSIX files ( and compatablity wrappers ) . - - This is like System . PosixCompat . Files , except with a fixed rename . - - Copyright 2014 < > - - License : BSD-2 - clause - - This is like System.PosixCompat.Files, except with a fixed rename. - - Copyright 2014 Joey Hess <> - - License: BSD-2-clause -} # LANGUAGE CPP # # OPTIONS_GHC -fno - warn - tabs # module Utility.PosixFiles ( module X, rename ) where import System.PosixCompat.Files as X hiding (rename) #ifndef mingw32_HOST_OS import System.Posix.Files (rename) #else import qualified System.Win32.File as Win32 #endif System.PosixCompat.Files.rename on Windows calls renameFile , - so can not rename directories . - - Instead , use Win32 moveFile , which can . It needs to be told to overwrite - any existing file . - so cannot rename directories. - - Instead, use Win32 moveFile, which can. It needs to be told to overwrite - any existing file. -} #ifdef mingw32_HOST_OS rename :: FilePath -> FilePath -> IO () rename src dest = Win32.moveFileEx src dest Win32.mOVEFILE_REPLACE_EXISTING #endif
null
https://raw.githubusercontent.com/RichiH/git-repair/c61b677e7a67a286df34c0629c52aeae9be9299a/Utility/PosixFiles.hs
haskell
POSIX files ( and compatablity wrappers ) . - - This is like System . PosixCompat . Files , except with a fixed rename . - - Copyright 2014 < > - - License : BSD-2 - clause - - This is like System.PosixCompat.Files, except with a fixed rename. - - Copyright 2014 Joey Hess <> - - License: BSD-2-clause -} # LANGUAGE CPP # # OPTIONS_GHC -fno - warn - tabs # module Utility.PosixFiles ( module X, rename ) where import System.PosixCompat.Files as X hiding (rename) #ifndef mingw32_HOST_OS import System.Posix.Files (rename) #else import qualified System.Win32.File as Win32 #endif System.PosixCompat.Files.rename on Windows calls renameFile , - so can not rename directories . - - Instead , use Win32 moveFile , which can . It needs to be told to overwrite - any existing file . - so cannot rename directories. - - Instead, use Win32 moveFile, which can. It needs to be told to overwrite - any existing file. -} #ifdef mingw32_HOST_OS rename :: FilePath -> FilePath -> IO () rename src dest = Win32.moveFileEx src dest Win32.mOVEFILE_REPLACE_EXISTING #endif
82e35c04fe83e084818f21e8d7fe328d064107f848289c1e3a9678f5babdbaa6
flavioc/cl-hurd
fsys-set-options.lisp
(in-package :hurd-translator) (def-fsys-interface :fsys-set-options ((fsys port) (reply port) (reply-type msg-type-name) (data :pointer) (data-len msg-type-number) (do-children :boolean)) (declare (ignore reply reply-type)) (when (port-exists-p fsys) (let ((new-options (get-foreign-options data data-len))) (when do-children ;; Propagate options to children translators. (let (nodes-done) (bucket-iterate (port-bucket *translator*) (lambda (port) (when (typep port 'protid) (let ((node (get-node port))) (when (and (box-active-p (box node)) (not (member node nodes-done))) (fsys-set-options (box-fetch-control (box node)) :options new-options :do-children t) (push node nodes-done)))))))) (set-options *translator* new-options)) t))
null
https://raw.githubusercontent.com/flavioc/cl-hurd/982232f47d1a0ff4df5fde2edad03b9df871470a/translator/interfaces/fsys-set-options.lisp
lisp
Propagate options to children translators.
(in-package :hurd-translator) (def-fsys-interface :fsys-set-options ((fsys port) (reply port) (reply-type msg-type-name) (data :pointer) (data-len msg-type-number) (do-children :boolean)) (declare (ignore reply reply-type)) (when (port-exists-p fsys) (let ((new-options (get-foreign-options data data-len))) (when do-children (let (nodes-done) (bucket-iterate (port-bucket *translator*) (lambda (port) (when (typep port 'protid) (let ((node (get-node port))) (when (and (box-active-p (box node)) (not (member node nodes-done))) (fsys-set-options (box-fetch-control (box node)) :options new-options :do-children t) (push node nodes-done)))))))) (set-options *translator* new-options)) t))
2d0fc62ce7feadcb5baddbfbd51f8ebb7dddd748973f239046cb787bd1cdc612
IBM/probzelus
listP.ml
* Copyright 2018 - 2020 IBM Corporation * * 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 . * Copyright 2018-2020 IBM Corporation * * 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. *) open Ztypes let map (Cnode { alloc; reset; copy; step; }) = let step state (pstate, l) = List.map (fun x -> step state (pstate, x)) l in Cnode { alloc; reset; copy; step; } let ini (Cnode { alloc; reset; copy; step; }) = let step state (pstate, n) = if n < 0 then [] else List.init n (fun x -> step state (pstate, x)) in Cnode { alloc; reset; copy; step; } let filter (Cnode { alloc; reset; copy; step; }) = let step state (pstate, l) = List.filter (fun x -> step state (pstate, x)) l in Cnode { alloc; reset; copy; step; } let iter2 (Cnode { alloc; reset; copy; step; }) = let step state (pstate, (l1, l2)) = List.iter2 (fun x y -> step state (pstate, (x, y))) l1 l2 in Cnode { alloc; reset; copy; step; }
null
https://raw.githubusercontent.com/IBM/probzelus/3bdd60e3c4010452239bfe7bc79165802e5d941b/benchmarks/mtt/mttlib/listP.ml
ocaml
* Copyright 2018 - 2020 IBM Corporation * * 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 . * Copyright 2018-2020 IBM Corporation * * 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. *) open Ztypes let map (Cnode { alloc; reset; copy; step; }) = let step state (pstate, l) = List.map (fun x -> step state (pstate, x)) l in Cnode { alloc; reset; copy; step; } let ini (Cnode { alloc; reset; copy; step; }) = let step state (pstate, n) = if n < 0 then [] else List.init n (fun x -> step state (pstate, x)) in Cnode { alloc; reset; copy; step; } let filter (Cnode { alloc; reset; copy; step; }) = let step state (pstate, l) = List.filter (fun x -> step state (pstate, x)) l in Cnode { alloc; reset; copy; step; } let iter2 (Cnode { alloc; reset; copy; step; }) = let step state (pstate, (l1, l2)) = List.iter2 (fun x y -> step state (pstate, (x, y))) l1 l2 in Cnode { alloc; reset; copy; step; }
e3043cca5a1140a9e4d5486713f93690319a0ad2c1c0681466a0e1756b582669
erlang/sourcer
sourcer_analyse.erl
-module(sourcer_analyse). -export([ analyse/1, analyse_text/1, merge/1 ]). -include("sourcer_model.hrl"). %%-define(DEBUG, true). -include("debug.hrl"). merge([]) -> #model{}; merge(L) when is_list(L) -> lists:foldl(fun merge/2, #model{}, L); merge(M) -> merge([M]). analyse_text(Text) -> TText = unicode:characters_to_list(Text), {ok, Toks, _} = sourcer_scan:string(TText), Forms = sourcer_parse:parse(Toks), analyse(Forms). analyse(Forms) -> Ms = [analyse_form(X) || X<-Forms], M0 = merge(Ms), M1 = adjust_keys(M0), M2 = adjust_defs(M1), M2. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% merge(#model{defs=D1, refs=R1}, #model{defs=D2, refs=R2}) -> D = merge_defs(lists:sort(D1 ++ D2)), R = merge_refs(lists:sort(R1 ++ R2), D), #model{ defs=D, refs=R }. - if a def exists for same , keep the earliest ; %% except macros - they can have multiple defs. merge_defs(D) -> Ds = lists:sort(D), merge_defs(Ds, []). merge_defs([], R) -> lists:reverse(R); merge_defs([E], R) -> lists:reverse([E|R]); merge_defs([E,E|T], R) -> merge_defs([E|T], R); merge_defs([E1=#def{ctx=K1},E2=#def{ctx=K2}|T], R) -> if K1 == K2 -> case {element(1, hd(K1)), length(K1)} of {macro, 1} -> merge_defs([E2|T], [E1|R]); _ -> merge_defs([merge_def(E1, E2)|T], R) end; true -> merge_defs([E2|T], [E1|R]) end. merge_def(#def{ctx=K, name_range=P1, info=M1}, #def{ctx=K, name_range=P2, info=M2}) -> P = case {P1, P2} of {none, P2} -> P2; {P1, none} -> P1; _ -> if P1<P2 -> P1; true -> P2 end end, M = maps:merge(M1, M2), #def{ctx=K, name_range=P, info=M}. %% - remove doubles %% TODO : if def and ref at same location, remove ref merge_refs(R, D) -> R1 = lists:sort(R), merge_refs(R1, D, []). merge_refs([], _, R) -> lists:reverse(R); merge_refs([E,E|T], D, R) -> merge_refs([E|T], D, R); merge_refs([E=#ref{ctx=K,range=P}|T], D, R) -> case lists:keyfind(K, #def.ctx, D) of #def{ctx=K,name_range=P} -> merge_refs(T, D, R); _ -> merge_refs(T, D, [E|R]) end. range({_,P1,_,_}, {_,P2,T2,_}) -> range(P1, P2, T2); range(P, T) when is_list(T) -> range(P, P, T). range(P1, {L2,C2}, T2) when is_list(T2) -> {P1, {L2, C2+length(T2)}}; range(P1, none, _) -> {P1, none}. range({_, P, T, _}) -> range(P, P, T). %%%%%%%%%%%%%%%%%%%% new_ctx() -> queue:new(). new_ctx(Items) when is_list(Items) -> queue:from_list(Items). push_ctx(Ctx, New) -> queue:join(Ctx, queue:from_list(New)). get_ctx(Ctx) -> queue:to_list(Ctx). %%%%%%%%%%%%%%%%%% analyse_form({define, Name, Arity, Args, Value, Comments, Pos, FullRange}) -> Key = [{macro, Name, Arity, 0}], Ctx = new_ctx(Key), Defs = [#def{ctx=Key, name_range=Pos, info=#{body=>FullRange, comments=>Comments}}], Model0 = #model{defs=Defs}, Model1 = analyse_exprs_list(Args, Ctx, Model0), merge(analyse_exprs(Value, Ctx, Model1)); analyse_form({include, Name, _Comments, Pos}) -> TODO resolve path ? Key = [{include, Name}], #model{refs=[#ref{ctx=Key, range=Pos}]}; analyse_form({include_lib, Name, _Comments, Pos}) -> TODO resolve path ? Key = [{include_lib, Name}], #model{refs=[#ref{ctx=Key, range=Pos}]}; analyse_form({attribute, _Name, _Args, _Comments}) -> #model{}; analyse_form({export_type, Args, _Comments}) -> Refs = [#ref{ctx=[{type,N,A}],range=P} || {N,A,P}<-Args], #model{refs=Refs}; analyse_form({export, Args, _Comments}) -> Refs = [#ref{ctx=[{function,N,A}],range=P} || {N,A,P}<-Args], #model{refs=Refs}; analyse_form({callback, Module, Name, Arity, Args, Body, Comments, FullRange}) -> analyse_form({spec, Module, Name, Arity, Args, Body, Comments, FullRange}); analyse_form({callback, Name, Arity, Args, Body, Comments, FullRange}) -> analyse_form({spec, Name, Arity, Args, Body, Comments, FullRange}); analyse_form({spec, Module, Name, Arity, Args, Comments, Pos, FullRange}) -> Key = [{module,Module},{function, Name, Arity}], Defs = [#def{ctx=Key, name_range=none, info=#{spec=>FullRange, spec_comments=>Comments}}], Refs = [#ref{ctx=Key, range=Pos}], Ctx = new_ctx(), analyse_type_clauses(Args, Ctx, #model{defs=Defs, refs=Refs}); analyse_form({spec, Name, Arity, Args, Comments, Pos, FullRange}) -> Key = [{function, Name, Arity}], Ctx = new_ctx(), Defs = [#def{ctx=Key, name_range=none, info=#{spec=>FullRange, spec_comments=>Comments}}], Refs = [#ref{ctx=Key, range=Pos}], analyse_type_clauses(Args, Ctx, #model{defs=Defs, refs=Refs}); analyse_form({type, Name, Arity, Args, Def, Comments, Pos, FullRange}) -> Key = [{type, Name, Arity}], Ctx = new_ctx(Key), Defs = [#def{ctx=Key, name_range=Pos, info=#{body=>FullRange, comments=>Comments}}], Model0 = #model{defs=Defs}, Model1 = merge([analyse_type(A, Ctx, Model0) || A<-Args]), Model2 = analyse_type(Def, Ctx, merge([Model0,Model1])), Model2; analyse_form({module, Name, Comments, Pos}) -> Key = [{module, Name}], Defs = [#def{ctx=Key, name_range=Pos, info=#{comments=>Comments}}], #model{defs=Defs}; analyse_form({import, Module, Funcs, _Comments}) -> Key = {module, Module}, Refs = [#ref{ctx=[Key,{function,F,A}],range=Pos} || {F,A,Pos}<-Funcs], #model{refs=Refs}; analyse_form({record, Name, Comments, Pos, Fields, FullRange}) -> Key = [{record, Name}], Ctx = new_ctx(Key), Defs = [#def{ctx=Key, name_range=Pos, info=#{body=>FullRange, comments=>Comments}}], Model0 = #model{defs=Defs}, Model1 = analyse_fields(Fields, Ctx), merge([Model0, Model1]); analyse_form({function, Name, Arity, Clauses, Comments, Pos, FullRange}) -> Key = [{function, Name, Arity}], Ctx = new_ctx(Key), Defs = [#def{ctx=Key, name_range=Pos, info=#{body=>FullRange, comments=>Comments}}], Model0 = #model{defs=Defs}, merge([Model0 | [analyse_clause(C,Ctx) || C<-Clauses]]); analyse_form({compile, _Pos, _Args, _Comments}) -> #model{}; analyse_form(X) -> throw({bad_value, X}), #model{}. analyse_clause({clause, N, Args, Guards, Body}, Ctx) -> Ctx1 = push_ctx(Ctx, [{clause, N}]), Models = [analyse_exprs(A, Ctx1) || A<-Args], M1 = merge(Models), M2 = analyse_exprs(Guards, Ctx1, M1), analyse_exprs(Body, Ctx1, M2). analyse_fields(Fields, Ctx) -> merge([analyse_field(F, Ctx) || F<-Fields]). analyse_field({field, Pos, Name, Type, DefVal}, Ctx) -> Key = get_ctx(push_ctx(Ctx,[{field, Name}])), M0 = #model{defs=[#def{ctx=Key, name_range=Pos, info=#{}}]}, M1 = analyse_type(Type, Ctx, M0), analyse_exprs(DefVal, Ctx, M1). analyse_exprs_list(none, _Ctx, Model) -> Model; analyse_exprs_list(List, Ctx, Model) -> Models = [analyse_exprs(A, Ctx) || A<-List], merge([Model|Models]). analyse_exprs(Exprs, Ctx) -> analyse_exprs(Exprs, Ctx, #model{}). has_type(Ctx) -> lists:any(fun(?k(type))->true;(_)->false end, get_ctx(Ctx)). analyse_exprs([], _Ctx, Model) -> Model; analyse_exprs(none, _Ctx, Model) -> Model; analyse_exprs([{var,_,_,Name}=H|T], Ctx, Model=#model{defs=Defs, refs=Refs}) -> Key = get_ctx(push_ctx(Ctx, [{var, Name}])), NewDefs = [#def{ctx=Key, name_range=range(H), info=#{}}|Defs], NewRefs = [#ref{ctx=Key, range=range(H)}|Refs], analyse_exprs(T, Ctx, Model#model{defs=NewDefs, refs=NewRefs}); analyse_exprs([{macro,_,Name,none}=H|T], Ctx, Model=#model{refs=Refs}) -> Index = 0, Key = [{macro, macro_name(Name), -1, Index}], NewRefs = [#ref{ctx=Key, range=range(H)}|Refs], analyse_exprs(T, Ctx, Model#model{refs=NewRefs}); analyse_exprs([{macro,_,Name,Args}=H|T], Ctx, Model=#model{refs=Refs}) -> Index = 0, Key = [{macro, macro_name(Name), macro_arity(Args), Index}], NewRefs = [#ref{ctx=Key, range=range(H)}|Refs], merge([analyse_exprs(T, Ctx, Model#model{refs=NewRefs}) | [analyse_exprs(A, Ctx, Model) || A<-Args]]); analyse_exprs([{call, ?v(Name)=F, Args} | T], Ctx, Model=#model{refs=Refs}) -> Arity = length(Args), case has_type(Ctx) of true -> NewCtx = push_ctx(Ctx, [{type, Name, Arity}]), Key = get_ctx(NewCtx), NewRefs = [#ref{ctx=Key, range=range(F)}|Refs], merge([analyse_exprs(T, Ctx, Model#model{refs=NewRefs}) | [analyse_exprs(A, Ctx, Model) || A<-Args]]); false -> Key = [{function, Name, Arity}], NewRefs = [#ref{ctx=Key, range=range(F)}|Refs], merge([analyse_exprs(T, Ctx, Model#model{refs=NewRefs}) | [analyse_exprs(A, Ctx, Model) || A<-Args]]) end; analyse_exprs([{call, ?v(Mod)=MM, ?v(Fun)=F, Args} | T], Ctx, Model=#model{refs=Refs}) -> Arity = length(Args), case has_type(Ctx) of true -> NewCtx = push_ctx(Ctx, [{type, Fun, Arity}]), Key = get_ctx(NewCtx), NewRefs = [#ref{ctx=Key, range=range(F)}|Refs], merge([analyse_exprs(T, Ctx, Model#model{refs=NewRefs}) | [analyse_exprs(A, Ctx, Model) || A<-Args]]); false -> NewRefs = case MM of {macro,_,"?MODULE",'MODULE'} -> Key1 = [{function, Fun, Arity}], Key2 = [{macro, 'MODULE', -1, 0}], [#ref{ctx=Key2, range=range(MM)},#ref{ctx=Key1, range=range(F)}|Refs]; _ -> Key = [{module, Mod}, {function, Fun, Arity}], [#ref{ctx=Key, range=range(F)}|Refs] end, merge([analyse_exprs(T, Ctx, Model#model{refs=NewRefs}) | [analyse_exprs(A, Ctx, Model) || A<-Args]]) end; analyse_exprs([{funref, ?v(Mod), ?v(Fun)=F, ?v(A)} | T], Ctx, Model=#model{refs=Refs}) -> Key = [{module, Mod}, {function, Fun, A}], NewRefs = [#ref{ctx=Key, range=range(F)}|Refs], analyse_exprs(T, Ctx, Model#model{refs=NewRefs}); analyse_exprs([{defun, '', A, Ix, Clauses, _} | T], Ctx, Model) -> NewCtx = push_ctx(Ctx, [{function, Ix, A}]), merge([analyse_exprs(T, Ctx, Model) | [analyse_clause(C, NewCtx) || C<-Clauses]]); analyse_exprs([{defun, FN, Args, _Ix, Clauses, Pos} | T], Ctx, Model=#model{defs=Defs}) -> NewCtx = push_ctx(Ctx, [{function, FN, Args}]), Key = get_ctx(NewCtx), NewDefs = [#def{ctx=Key, name_range=Pos, info=#{}}|Defs], merge([analyse_exprs(T, Ctx, Model#model{defs=NewDefs}) | [analyse_clause(C, NewCtx) || C<-Clauses]]); analyse_exprs([{record, ?v(N)=R, Fs} | T], Ctx, Model=#model{refs=Refs}) -> Key = [{record, N}], NewRefs = [#ref{ctx=Key, range=range(R)}|Refs], merge([analyse_exprs(T, Ctx, Model#model{refs=NewRefs}), analyse_fields(Fs, Ctx)]); analyse_exprs([{recfield, ?v(RN)=R, ?v(FN)=F} | T], Ctx, Model=#model{refs=Refs}) -> KeyR = [{record, RN}], KeyF = [{record, RN},{field, FN}], NewRefs = [#ref{ctx=KeyR, range=range(R)},#ref{ctx=KeyF, range=range(F)}|Refs], analyse_exprs(T, Ctx, Model#model{refs=NewRefs}); analyse_exprs([_|T], Ctx, Model) -> analyse_exprs(T, Ctx, Model). analyse_type([], _Ctx, Model) -> Model; analyse_type([{call,?v(Name)=Target,Args}|_], Ctx, Model) -> case lists:member(Name, predefined_types()) of true -> Model; _ -> Key = [{type, Name, length(Args)}], M = #model{ refs=[ #ref{ctx=Key, range=range(Target)} ] }, Model2 = [analyse_exprs(A, Ctx, Model)||A<-Args], merge([M,Model|Model2]) end; analyse_type([{call,?v(M),?v(Name)=Target,Args}|_], Ctx, Model) -> Key = [{module,M},{type, Name, length(Args)}], Model1 = #model{ refs=[ #ref{ctx=Key, range=range(Target)} ] }, Model2 = [analyse_exprs(A, Ctx, Model)||A<-Args], merge([Model1,Model|Model2]); analyse_type(L, Ctx, Model) -> analyse_exprs(L, Ctx, Model). analyse_type_clauses(Clauses, Ctx, Model) -> Fun = fun({Args,Return}) -> merge([analyse_type(Args, Ctx, Model), analyse_type(Return, Ctx, Model)]) end, merge([Fun(C) || C<-Clauses]). comments_info(Comments, Key) -> case Comments of [] -> []; _ -> [{Key, [{comments, Comments}]}] end. predefined_types() -> [ any, none, pid, port, reference, float, atom, integer, term, binary, bitstring, boolean, byte, char, nil, number, list, map, tuple, maybe_improper_list, nonempty_list, string, nonempty_string, iodata, iolist, function, module, mfa, arity, identifier, node, timeout, no_return, non_neg_integer, pos_integer, neg_integer, nonempty_maybe_improper_list, nonempty_improper_list ]. macro_arity(none) -> -1; macro_arity(L) -> length(L). macro_name("?"++Name) -> list_to_atom(Name); macro_name(X) -> X. adjust_keys(M=#model{defs=D, refs=R}) -> Fun = fun(#def{ctx=[{module,_}]})->false; (_)->true end, L = lists:dropwhile(Fun, D), case L of [#def{ctx=[{module,_}=K]}|_] -> M#model{ defs = [fix_key(E,K) || E<-D], refs = [fix_key(E,K) || E<-R] }; _ -> M end. fix_key(E=#def{ctx=KK}, K) -> E#def{ctx=fix_key(KK, K)}; fix_key(E=#ref{ctx=KK}, K) -> E#ref{ctx=fix_key(KK, K)}; fix_key(KK, K) -> case KK of [{module,_}|_] -> KK; _ -> [K|KK] end. adjust_defs(M=#model{defs=Defs}) -> D = [adjust_map(X) || X<-Defs], M#model{defs=D}. adjust_map(#def{info=M0}=E) -> M = case M0 of #{comments:=none} -> maps:remove(comments, M0); _ -> M0 end, E#def{info=M}. get_line_info(Text) -> %% we hope there are no mixed newlines Lines = binary:split(Text, [<<"\r\n">>, <<"\r">>, <<"\n">>], [global]), lists:mapfoldl( fun(X, {A, I}) -> L=size(X), {{A, L, I}, {A+L, I+1}} end, {0, 0}, Lines ). get_line_at_offset(Offset, Lines) -> L = lists:dropwhile(fun({O,_,_})-> O<Offset end, Lines), case L of [{_,_,I}|_] -> I; _ -> none end. get_line_info(none, _) -> undefined; get_line_info(Index, Lines) -> lists:nth(Index+1, Lines).
null
https://raw.githubusercontent.com/erlang/sourcer/27ea9c63998b9e694eb7b654dd05b831b989e69e/apps/sourcer/src/sourcer_analyse.erl
erlang
-define(DEBUG, true). except macros - they can have multiple defs. - remove doubles TODO : if def and ref at same location, remove ref we hope there are no mixed newlines
-module(sourcer_analyse). -export([ analyse/1, analyse_text/1, merge/1 ]). -include("sourcer_model.hrl"). -include("debug.hrl"). merge([]) -> #model{}; merge(L) when is_list(L) -> lists:foldl(fun merge/2, #model{}, L); merge(M) -> merge([M]). analyse_text(Text) -> TText = unicode:characters_to_list(Text), {ok, Toks, _} = sourcer_scan:string(TText), Forms = sourcer_parse:parse(Toks), analyse(Forms). analyse(Forms) -> Ms = [analyse_form(X) || X<-Forms], M0 = merge(Ms), M1 = adjust_keys(M0), M2 = adjust_defs(M1), M2. merge(#model{defs=D1, refs=R1}, #model{defs=D2, refs=R2}) -> D = merge_defs(lists:sort(D1 ++ D2)), R = merge_refs(lists:sort(R1 ++ R2), D), #model{ defs=D, refs=R }. - if a def exists for same , keep the earliest ; merge_defs(D) -> Ds = lists:sort(D), merge_defs(Ds, []). merge_defs([], R) -> lists:reverse(R); merge_defs([E], R) -> lists:reverse([E|R]); merge_defs([E,E|T], R) -> merge_defs([E|T], R); merge_defs([E1=#def{ctx=K1},E2=#def{ctx=K2}|T], R) -> if K1 == K2 -> case {element(1, hd(K1)), length(K1)} of {macro, 1} -> merge_defs([E2|T], [E1|R]); _ -> merge_defs([merge_def(E1, E2)|T], R) end; true -> merge_defs([E2|T], [E1|R]) end. merge_def(#def{ctx=K, name_range=P1, info=M1}, #def{ctx=K, name_range=P2, info=M2}) -> P = case {P1, P2} of {none, P2} -> P2; {P1, none} -> P1; _ -> if P1<P2 -> P1; true -> P2 end end, M = maps:merge(M1, M2), #def{ctx=K, name_range=P, info=M}. merge_refs(R, D) -> R1 = lists:sort(R), merge_refs(R1, D, []). merge_refs([], _, R) -> lists:reverse(R); merge_refs([E,E|T], D, R) -> merge_refs([E|T], D, R); merge_refs([E=#ref{ctx=K,range=P}|T], D, R) -> case lists:keyfind(K, #def.ctx, D) of #def{ctx=K,name_range=P} -> merge_refs(T, D, R); _ -> merge_refs(T, D, [E|R]) end. range({_,P1,_,_}, {_,P2,T2,_}) -> range(P1, P2, T2); range(P, T) when is_list(T) -> range(P, P, T). range(P1, {L2,C2}, T2) when is_list(T2) -> {P1, {L2, C2+length(T2)}}; range(P1, none, _) -> {P1, none}. range({_, P, T, _}) -> range(P, P, T). new_ctx() -> queue:new(). new_ctx(Items) when is_list(Items) -> queue:from_list(Items). push_ctx(Ctx, New) -> queue:join(Ctx, queue:from_list(New)). get_ctx(Ctx) -> queue:to_list(Ctx). analyse_form({define, Name, Arity, Args, Value, Comments, Pos, FullRange}) -> Key = [{macro, Name, Arity, 0}], Ctx = new_ctx(Key), Defs = [#def{ctx=Key, name_range=Pos, info=#{body=>FullRange, comments=>Comments}}], Model0 = #model{defs=Defs}, Model1 = analyse_exprs_list(Args, Ctx, Model0), merge(analyse_exprs(Value, Ctx, Model1)); analyse_form({include, Name, _Comments, Pos}) -> TODO resolve path ? Key = [{include, Name}], #model{refs=[#ref{ctx=Key, range=Pos}]}; analyse_form({include_lib, Name, _Comments, Pos}) -> TODO resolve path ? Key = [{include_lib, Name}], #model{refs=[#ref{ctx=Key, range=Pos}]}; analyse_form({attribute, _Name, _Args, _Comments}) -> #model{}; analyse_form({export_type, Args, _Comments}) -> Refs = [#ref{ctx=[{type,N,A}],range=P} || {N,A,P}<-Args], #model{refs=Refs}; analyse_form({export, Args, _Comments}) -> Refs = [#ref{ctx=[{function,N,A}],range=P} || {N,A,P}<-Args], #model{refs=Refs}; analyse_form({callback, Module, Name, Arity, Args, Body, Comments, FullRange}) -> analyse_form({spec, Module, Name, Arity, Args, Body, Comments, FullRange}); analyse_form({callback, Name, Arity, Args, Body, Comments, FullRange}) -> analyse_form({spec, Name, Arity, Args, Body, Comments, FullRange}); analyse_form({spec, Module, Name, Arity, Args, Comments, Pos, FullRange}) -> Key = [{module,Module},{function, Name, Arity}], Defs = [#def{ctx=Key, name_range=none, info=#{spec=>FullRange, spec_comments=>Comments}}], Refs = [#ref{ctx=Key, range=Pos}], Ctx = new_ctx(), analyse_type_clauses(Args, Ctx, #model{defs=Defs, refs=Refs}); analyse_form({spec, Name, Arity, Args, Comments, Pos, FullRange}) -> Key = [{function, Name, Arity}], Ctx = new_ctx(), Defs = [#def{ctx=Key, name_range=none, info=#{spec=>FullRange, spec_comments=>Comments}}], Refs = [#ref{ctx=Key, range=Pos}], analyse_type_clauses(Args, Ctx, #model{defs=Defs, refs=Refs}); analyse_form({type, Name, Arity, Args, Def, Comments, Pos, FullRange}) -> Key = [{type, Name, Arity}], Ctx = new_ctx(Key), Defs = [#def{ctx=Key, name_range=Pos, info=#{body=>FullRange, comments=>Comments}}], Model0 = #model{defs=Defs}, Model1 = merge([analyse_type(A, Ctx, Model0) || A<-Args]), Model2 = analyse_type(Def, Ctx, merge([Model0,Model1])), Model2; analyse_form({module, Name, Comments, Pos}) -> Key = [{module, Name}], Defs = [#def{ctx=Key, name_range=Pos, info=#{comments=>Comments}}], #model{defs=Defs}; analyse_form({import, Module, Funcs, _Comments}) -> Key = {module, Module}, Refs = [#ref{ctx=[Key,{function,F,A}],range=Pos} || {F,A,Pos}<-Funcs], #model{refs=Refs}; analyse_form({record, Name, Comments, Pos, Fields, FullRange}) -> Key = [{record, Name}], Ctx = new_ctx(Key), Defs = [#def{ctx=Key, name_range=Pos, info=#{body=>FullRange, comments=>Comments}}], Model0 = #model{defs=Defs}, Model1 = analyse_fields(Fields, Ctx), merge([Model0, Model1]); analyse_form({function, Name, Arity, Clauses, Comments, Pos, FullRange}) -> Key = [{function, Name, Arity}], Ctx = new_ctx(Key), Defs = [#def{ctx=Key, name_range=Pos, info=#{body=>FullRange, comments=>Comments}}], Model0 = #model{defs=Defs}, merge([Model0 | [analyse_clause(C,Ctx) || C<-Clauses]]); analyse_form({compile, _Pos, _Args, _Comments}) -> #model{}; analyse_form(X) -> throw({bad_value, X}), #model{}. analyse_clause({clause, N, Args, Guards, Body}, Ctx) -> Ctx1 = push_ctx(Ctx, [{clause, N}]), Models = [analyse_exprs(A, Ctx1) || A<-Args], M1 = merge(Models), M2 = analyse_exprs(Guards, Ctx1, M1), analyse_exprs(Body, Ctx1, M2). analyse_fields(Fields, Ctx) -> merge([analyse_field(F, Ctx) || F<-Fields]). analyse_field({field, Pos, Name, Type, DefVal}, Ctx) -> Key = get_ctx(push_ctx(Ctx,[{field, Name}])), M0 = #model{defs=[#def{ctx=Key, name_range=Pos, info=#{}}]}, M1 = analyse_type(Type, Ctx, M0), analyse_exprs(DefVal, Ctx, M1). analyse_exprs_list(none, _Ctx, Model) -> Model; analyse_exprs_list(List, Ctx, Model) -> Models = [analyse_exprs(A, Ctx) || A<-List], merge([Model|Models]). analyse_exprs(Exprs, Ctx) -> analyse_exprs(Exprs, Ctx, #model{}). has_type(Ctx) -> lists:any(fun(?k(type))->true;(_)->false end, get_ctx(Ctx)). analyse_exprs([], _Ctx, Model) -> Model; analyse_exprs(none, _Ctx, Model) -> Model; analyse_exprs([{var,_,_,Name}=H|T], Ctx, Model=#model{defs=Defs, refs=Refs}) -> Key = get_ctx(push_ctx(Ctx, [{var, Name}])), NewDefs = [#def{ctx=Key, name_range=range(H), info=#{}}|Defs], NewRefs = [#ref{ctx=Key, range=range(H)}|Refs], analyse_exprs(T, Ctx, Model#model{defs=NewDefs, refs=NewRefs}); analyse_exprs([{macro,_,Name,none}=H|T], Ctx, Model=#model{refs=Refs}) -> Index = 0, Key = [{macro, macro_name(Name), -1, Index}], NewRefs = [#ref{ctx=Key, range=range(H)}|Refs], analyse_exprs(T, Ctx, Model#model{refs=NewRefs}); analyse_exprs([{macro,_,Name,Args}=H|T], Ctx, Model=#model{refs=Refs}) -> Index = 0, Key = [{macro, macro_name(Name), macro_arity(Args), Index}], NewRefs = [#ref{ctx=Key, range=range(H)}|Refs], merge([analyse_exprs(T, Ctx, Model#model{refs=NewRefs}) | [analyse_exprs(A, Ctx, Model) || A<-Args]]); analyse_exprs([{call, ?v(Name)=F, Args} | T], Ctx, Model=#model{refs=Refs}) -> Arity = length(Args), case has_type(Ctx) of true -> NewCtx = push_ctx(Ctx, [{type, Name, Arity}]), Key = get_ctx(NewCtx), NewRefs = [#ref{ctx=Key, range=range(F)}|Refs], merge([analyse_exprs(T, Ctx, Model#model{refs=NewRefs}) | [analyse_exprs(A, Ctx, Model) || A<-Args]]); false -> Key = [{function, Name, Arity}], NewRefs = [#ref{ctx=Key, range=range(F)}|Refs], merge([analyse_exprs(T, Ctx, Model#model{refs=NewRefs}) | [analyse_exprs(A, Ctx, Model) || A<-Args]]) end; analyse_exprs([{call, ?v(Mod)=MM, ?v(Fun)=F, Args} | T], Ctx, Model=#model{refs=Refs}) -> Arity = length(Args), case has_type(Ctx) of true -> NewCtx = push_ctx(Ctx, [{type, Fun, Arity}]), Key = get_ctx(NewCtx), NewRefs = [#ref{ctx=Key, range=range(F)}|Refs], merge([analyse_exprs(T, Ctx, Model#model{refs=NewRefs}) | [analyse_exprs(A, Ctx, Model) || A<-Args]]); false -> NewRefs = case MM of {macro,_,"?MODULE",'MODULE'} -> Key1 = [{function, Fun, Arity}], Key2 = [{macro, 'MODULE', -1, 0}], [#ref{ctx=Key2, range=range(MM)},#ref{ctx=Key1, range=range(F)}|Refs]; _ -> Key = [{module, Mod}, {function, Fun, Arity}], [#ref{ctx=Key, range=range(F)}|Refs] end, merge([analyse_exprs(T, Ctx, Model#model{refs=NewRefs}) | [analyse_exprs(A, Ctx, Model) || A<-Args]]) end; analyse_exprs([{funref, ?v(Mod), ?v(Fun)=F, ?v(A)} | T], Ctx, Model=#model{refs=Refs}) -> Key = [{module, Mod}, {function, Fun, A}], NewRefs = [#ref{ctx=Key, range=range(F)}|Refs], analyse_exprs(T, Ctx, Model#model{refs=NewRefs}); analyse_exprs([{defun, '', A, Ix, Clauses, _} | T], Ctx, Model) -> NewCtx = push_ctx(Ctx, [{function, Ix, A}]), merge([analyse_exprs(T, Ctx, Model) | [analyse_clause(C, NewCtx) || C<-Clauses]]); analyse_exprs([{defun, FN, Args, _Ix, Clauses, Pos} | T], Ctx, Model=#model{defs=Defs}) -> NewCtx = push_ctx(Ctx, [{function, FN, Args}]), Key = get_ctx(NewCtx), NewDefs = [#def{ctx=Key, name_range=Pos, info=#{}}|Defs], merge([analyse_exprs(T, Ctx, Model#model{defs=NewDefs}) | [analyse_clause(C, NewCtx) || C<-Clauses]]); analyse_exprs([{record, ?v(N)=R, Fs} | T], Ctx, Model=#model{refs=Refs}) -> Key = [{record, N}], NewRefs = [#ref{ctx=Key, range=range(R)}|Refs], merge([analyse_exprs(T, Ctx, Model#model{refs=NewRefs}), analyse_fields(Fs, Ctx)]); analyse_exprs([{recfield, ?v(RN)=R, ?v(FN)=F} | T], Ctx, Model=#model{refs=Refs}) -> KeyR = [{record, RN}], KeyF = [{record, RN},{field, FN}], NewRefs = [#ref{ctx=KeyR, range=range(R)},#ref{ctx=KeyF, range=range(F)}|Refs], analyse_exprs(T, Ctx, Model#model{refs=NewRefs}); analyse_exprs([_|T], Ctx, Model) -> analyse_exprs(T, Ctx, Model). analyse_type([], _Ctx, Model) -> Model; analyse_type([{call,?v(Name)=Target,Args}|_], Ctx, Model) -> case lists:member(Name, predefined_types()) of true -> Model; _ -> Key = [{type, Name, length(Args)}], M = #model{ refs=[ #ref{ctx=Key, range=range(Target)} ] }, Model2 = [analyse_exprs(A, Ctx, Model)||A<-Args], merge([M,Model|Model2]) end; analyse_type([{call,?v(M),?v(Name)=Target,Args}|_], Ctx, Model) -> Key = [{module,M},{type, Name, length(Args)}], Model1 = #model{ refs=[ #ref{ctx=Key, range=range(Target)} ] }, Model2 = [analyse_exprs(A, Ctx, Model)||A<-Args], merge([Model1,Model|Model2]); analyse_type(L, Ctx, Model) -> analyse_exprs(L, Ctx, Model). analyse_type_clauses(Clauses, Ctx, Model) -> Fun = fun({Args,Return}) -> merge([analyse_type(Args, Ctx, Model), analyse_type(Return, Ctx, Model)]) end, merge([Fun(C) || C<-Clauses]). comments_info(Comments, Key) -> case Comments of [] -> []; _ -> [{Key, [{comments, Comments}]}] end. predefined_types() -> [ any, none, pid, port, reference, float, atom, integer, term, binary, bitstring, boolean, byte, char, nil, number, list, map, tuple, maybe_improper_list, nonempty_list, string, nonempty_string, iodata, iolist, function, module, mfa, arity, identifier, node, timeout, no_return, non_neg_integer, pos_integer, neg_integer, nonempty_maybe_improper_list, nonempty_improper_list ]. macro_arity(none) -> -1; macro_arity(L) -> length(L). macro_name("?"++Name) -> list_to_atom(Name); macro_name(X) -> X. adjust_keys(M=#model{defs=D, refs=R}) -> Fun = fun(#def{ctx=[{module,_}]})->false; (_)->true end, L = lists:dropwhile(Fun, D), case L of [#def{ctx=[{module,_}=K]}|_] -> M#model{ defs = [fix_key(E,K) || E<-D], refs = [fix_key(E,K) || E<-R] }; _ -> M end. fix_key(E=#def{ctx=KK}, K) -> E#def{ctx=fix_key(KK, K)}; fix_key(E=#ref{ctx=KK}, K) -> E#ref{ctx=fix_key(KK, K)}; fix_key(KK, K) -> case KK of [{module,_}|_] -> KK; _ -> [K|KK] end. adjust_defs(M=#model{defs=Defs}) -> D = [adjust_map(X) || X<-Defs], M#model{defs=D}. adjust_map(#def{info=M0}=E) -> M = case M0 of #{comments:=none} -> maps:remove(comments, M0); _ -> M0 end, E#def{info=M}. get_line_info(Text) -> Lines = binary:split(Text, [<<"\r\n">>, <<"\r">>, <<"\n">>], [global]), lists:mapfoldl( fun(X, {A, I}) -> L=size(X), {{A, L, I}, {A+L, I+1}} end, {0, 0}, Lines ). get_line_at_offset(Offset, Lines) -> L = lists:dropwhile(fun({O,_,_})-> O<Offset end, Lines), case L of [{_,_,I}|_] -> I; _ -> none end. get_line_info(none, _) -> undefined; get_line_info(Index, Lines) -> lists:nth(Index+1, Lines).
67ef994ecdccd83656cc37f6288e0ff432da1367d580d3d2b6d024ef7b7b01b3
stereoknife/cowbot-hs
Bless.hs
{-# LANGUAGE DeriveGeneric #-} # LANGUAGE TypeApplications # # LANGUAGE FlexibleContexts # # LANGUAGE DataKinds # module Commands.Bless where import Control.Monad.Catch (MonadThrow) import Control.Monad.IO.Class (MonadIO (liftIO)) import Data.Aeson (FromJSON, decode) import Data.Text (Text) import Data.Text.Encoding (encodeUtf8) import GHC.Generics (Generic) import Howdy.Error (HowdyException (..), report) import Network.HTTP.Simple (getResponseBody, httpJSON, parseRequest, setRequestIgnoreStatus, setRequestMethod, setRequestPath, setRequestQueryString) import Howdy.Internal.Command import Howdy.Internal.Discord data APIResponse = APIResponse { bookname :: Text , chapter :: Text , verse :: Text , text :: Text } deriving (Generic, Show) instance FromJSON APIResponse where bless :: Command bless = do defReq <- parseRequest "/" let request = setRequestPath "/api" $ setRequestMethod "GET" $ setRequestQueryString [ ("passage", Just $ encodeUtf8 "random") , ("type", Just $ encodeUtf8 "json") ] $ setRequestIgnoreStatus defReq response <- httpJSON request let r = head $ getResponseBody @[APIResponse] response send $ "**" <> bookname r <> " " <> chapter r <> ":" <> verse r <> "** " <> text r
null
https://raw.githubusercontent.com/stereoknife/cowbot-hs/50e80d6ef4b849f27692fad3a4bc2b7187848202/app/Commands/Bless.hs
haskell
# LANGUAGE DeriveGeneric #
# LANGUAGE TypeApplications # # LANGUAGE FlexibleContexts # # LANGUAGE DataKinds # module Commands.Bless where import Control.Monad.Catch (MonadThrow) import Control.Monad.IO.Class (MonadIO (liftIO)) import Data.Aeson (FromJSON, decode) import Data.Text (Text) import Data.Text.Encoding (encodeUtf8) import GHC.Generics (Generic) import Howdy.Error (HowdyException (..), report) import Network.HTTP.Simple (getResponseBody, httpJSON, parseRequest, setRequestIgnoreStatus, setRequestMethod, setRequestPath, setRequestQueryString) import Howdy.Internal.Command import Howdy.Internal.Discord data APIResponse = APIResponse { bookname :: Text , chapter :: Text , verse :: Text , text :: Text } deriving (Generic, Show) instance FromJSON APIResponse where bless :: Command bless = do defReq <- parseRequest "/" let request = setRequestPath "/api" $ setRequestMethod "GET" $ setRequestQueryString [ ("passage", Just $ encodeUtf8 "random") , ("type", Just $ encodeUtf8 "json") ] $ setRequestIgnoreStatus defReq response <- httpJSON request let r = head $ getResponseBody @[APIResponse] response send $ "**" <> bookname r <> " " <> chapter r <> ":" <> verse r <> "** " <> text r
bd5b40cd48c26f38e15dd338f88393d819b813198d809a2f033f8957e10397e6
dwayne/eopl3
ex2.26.test.rkt
#lang racket (require "../ch1/ex1.31.rkt") (require "./ex2.26.rkt") (require rackunit) (check-equal? (mark-leaves-with-red-depth (interior-node 'red (interior-node 'bar (leaf 26) (leaf 12)) (interior-node 'red (leaf 11) (interior-node 'quux (leaf 117) (leaf 14))))) (a-red-blue-subtree (red-node (blue-node (list (leaf-node 1) (leaf-node 1))) (red-node (leaf-node 2) (blue-node (list (leaf-node 2) (leaf-node 2)))))))
null
https://raw.githubusercontent.com/dwayne/eopl3/9d5fdb2a8dafac3bc48852d49cda8b83e7a825cf/solutions/02-ch2/racket/ex2.26.test.rkt
racket
#lang racket (require "../ch1/ex1.31.rkt") (require "./ex2.26.rkt") (require rackunit) (check-equal? (mark-leaves-with-red-depth (interior-node 'red (interior-node 'bar (leaf 26) (leaf 12)) (interior-node 'red (leaf 11) (interior-node 'quux (leaf 117) (leaf 14))))) (a-red-blue-subtree (red-node (blue-node (list (leaf-node 1) (leaf-node 1))) (red-node (leaf-node 2) (blue-node (list (leaf-node 2) (leaf-node 2)))))))
32d9ec0e425ef1a1955b2f93f23e6d2cca2b0666c2850958c4e464d521f54f7e
spurious/sagittarius-scheme-mirror
button.scm
-*- mode : scheme ; coding : utf-8 ; -*- ;;; ;;; win32/gui/button.scm - Win32 GUI button ;;; Copyright ( c ) 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. ;;; (library (win32 gui button) (export <win32-button> win32-button? make-win32-button ) (import (rnrs) (clos user) (win32 user) (win32 defs) (win32 kernel) (win32 gui api) (sagittarius ffi) (sagittarius object) (sagittarius control)) (define *win32-default-button-class-name* "sagittarius-default-button-class") (define-class <win32-button> (<win32-component>) ()) (define-method initialize ((b <win32-button>) initargs) (call-next-method) (let ((style (bitwise-ior (~ b 'style) BS_NOTIFY))) (unless (slot-bound? b 'class-name) (set! (~ b 'class-name) *win32-default-button-class-name*)) (set! (~ b 'style) style) (when (zero? (~ b 'window-style)) (set! (~ b 'window-style) WS_EX_STATICEDGE))) b) (define (make-win32-button . opt) (apply make <win32-button> opt)) (define (win32-button? o) (is-a? o <win32-button>)) (define-method win32-translate-notification ((b <win32-button>) code) (cond ((= code BN_CLICKED) 'click) ((= code BN_DOUBLECLICKED) 'double-click) ((= code BN_SETFOCUS) 'focus) ((= code BN_KILLFOCUS) 'blur) (else code))) (inherit-window-class "BUTTON" *win32-default-button-class-name* WM_NCCREATE) )
null
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/ext/ffi/win32/gui/button.scm
scheme
coding : utf-8 ; -*- win32/gui/button.scm - Win32 GUI button 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.
Copyright ( c ) 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 (library (win32 gui button) (export <win32-button> win32-button? make-win32-button ) (import (rnrs) (clos user) (win32 user) (win32 defs) (win32 kernel) (win32 gui api) (sagittarius ffi) (sagittarius object) (sagittarius control)) (define *win32-default-button-class-name* "sagittarius-default-button-class") (define-class <win32-button> (<win32-component>) ()) (define-method initialize ((b <win32-button>) initargs) (call-next-method) (let ((style (bitwise-ior (~ b 'style) BS_NOTIFY))) (unless (slot-bound? b 'class-name) (set! (~ b 'class-name) *win32-default-button-class-name*)) (set! (~ b 'style) style) (when (zero? (~ b 'window-style)) (set! (~ b 'window-style) WS_EX_STATICEDGE))) b) (define (make-win32-button . opt) (apply make <win32-button> opt)) (define (win32-button? o) (is-a? o <win32-button>)) (define-method win32-translate-notification ((b <win32-button>) code) (cond ((= code BN_CLICKED) 'click) ((= code BN_DOUBLECLICKED) 'double-click) ((= code BN_SETFOCUS) 'focus) ((= code BN_KILLFOCUS) 'blur) (else code))) (inherit-window-class "BUTTON" *win32-default-button-class-name* WM_NCCREATE) )
a995bed58a434b370a5b9698f246860f4184fa433e75ec08cfb8b1b8ad4c8380
juspay/atlas
Environment.hs
# OPTIONS_GHC -Wno - orphans # | Copyright 2022 Juspay Technologies Pvt Ltd 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 : Environment Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd 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 : Environment Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Environment where import Beckn.External.Encryption (EncTools) import Beckn.Sms.Config import Beckn.Storage.Esqueleto.Config import qualified Beckn.Storage.Redis.Config as T import qualified Beckn.Tools.Metrics.CoreMetrics as Metrics import Beckn.Types.App import Beckn.Types.Cache import Beckn.Types.Common import Beckn.Types.Credentials (PrivateKey) import Beckn.Types.Flow (FlowR) import Beckn.Types.Registry import Beckn.Types.SlidingWindowLimiter import Beckn.Utils.CacheRedis as Cache import Beckn.Utils.Dhall (FromDhall) import Beckn.Utils.IOLogging import qualified Beckn.Utils.Registry as Registry import Beckn.Utils.Servant.Client import Beckn.Utils.Servant.SignatureAuth import qualified Data.Text as T import EulerHS.Prelude import System.Environment (lookupEnv) data AppCfg = AppCfg { esqDBCfg :: EsqDBConfig, port :: Int, metricsPort :: Int, hostName :: Text, nwAddress :: BaseUrl, signingKey :: PrivateKey, signatureExpiry :: Seconds, migrationPath :: Maybe FilePath, autoMigrate :: Bool, coreVersion :: Text, domainVersion :: Text, loggerConfig :: LoggerConfig, graceTerminationPeriod :: Seconds, registryUrl :: BaseUrl, encTools :: EncTools, authTokenCacheExpiry :: Seconds, disableSignatureAuth :: Bool, otpSmsTemplate :: Text, smsCfg :: SmsConfig, inviteSmsTemplate :: Text, apiRateLimitOptions :: APIRateLimitOptions, driverPositionInfoExpiry :: Maybe Seconds, fcmJsonPath :: Maybe Text, fcmUrl :: BaseUrl, googleMapsUrl :: BaseUrl, googleMapsKey :: Text, defaultRadiusOfSearch :: Meters, redisCfg :: T.RedisConfig, searchRequestExpirationSeconds :: Int, httpClientOptions :: HttpClientOptions } deriving (Generic, FromDhall) data AppEnv = AppEnv { hostName :: Text, nwAddress :: BaseUrl, signingKey :: PrivateKey, signatureExpiry :: Seconds, coreVersion :: Text, domainVersion :: Text, loggerConfig :: LoggerConfig, graceTerminationPeriod :: Seconds, registryUrl :: BaseUrl, disableSignatureAuth :: Bool, esqDBEnv :: EsqDBEnv, isShuttingDown :: TMVar (), loggerEnv :: LoggerEnv, encTools :: EncTools, authTokenCacheExpiry :: Seconds, port :: Int, coreMetrics :: Metrics.CoreMetricsContainer, httpClientOptions :: HttpClientOptions, otpSmsTemplate :: Text, smsCfg :: SmsConfig, inviteSmsTemplate :: Text, apiRateLimitOptions :: APIRateLimitOptions, driverPositionInfoExpiry :: Maybe Seconds, fcmJsonPath :: Maybe Text, fcmUrl :: BaseUrl, googleMapsUrl :: BaseUrl, googleMapsKey :: Text, defaultRadiusOfSearch :: Meters, searchRequestExpirationSeconds :: Int } deriving (Generic) instance AuthenticatingEntity AppEnv where getSigningKey = (.signingKey) getSignatureExpiry = (.signatureExpiry) buildAppEnv :: AppCfg -> IO AppEnv buildAppEnv AppCfg {..} = do hostname <- map T.pack <$> lookupEnv "POD_NAME" isShuttingDown <- newEmptyTMVarIO loggerEnv <- prepareLoggerEnv loggerConfig hostname esqDBEnv <- prepareEsqDBEnv esqDBCfg loggerEnv coreMetrics <- Metrics.registerCoreMetricsContainer return AppEnv {..} releaseAppEnv :: AppEnv -> IO () releaseAppEnv AppEnv {..} = do FIXME : disconnect database ? releaseLoggerEnv loggerEnv type Env = EnvR AppEnv type FlowHandler = FlowHandlerR AppEnv type FlowServer api = FlowServerR AppEnv api type Flow = FlowR AppEnv instance Registry Flow where registryLookup = Registry.withSubscriberCache Registry.registryLookup cacheRegistryKey :: Text cacheRegistryKey = "driver-offer-bpp:registry" instance Cache Subscriber Flow where type CacheKey Subscriber = SimpleLookupRequest getKey = Cache.getKey cacheRegistryKey . lookupRequestToRedisKey setKey = Cache.setKey cacheRegistryKey . lookupRequestToRedisKey delKey = Cache.delKey cacheRegistryKey . lookupRequestToRedisKey instance CacheEx Subscriber Flow where setKeyEx ttl = Cache.setKeyEx cacheRegistryKey ttl . lookupRequestToRedisKey
null
https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/driver-offer-bpp/src/Environment.hs
haskell
# OPTIONS_GHC -Wno - orphans # | Copyright 2022 Juspay Technologies Pvt Ltd 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 : Environment Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd 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 : Environment Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Environment where import Beckn.External.Encryption (EncTools) import Beckn.Sms.Config import Beckn.Storage.Esqueleto.Config import qualified Beckn.Storage.Redis.Config as T import qualified Beckn.Tools.Metrics.CoreMetrics as Metrics import Beckn.Types.App import Beckn.Types.Cache import Beckn.Types.Common import Beckn.Types.Credentials (PrivateKey) import Beckn.Types.Flow (FlowR) import Beckn.Types.Registry import Beckn.Types.SlidingWindowLimiter import Beckn.Utils.CacheRedis as Cache import Beckn.Utils.Dhall (FromDhall) import Beckn.Utils.IOLogging import qualified Beckn.Utils.Registry as Registry import Beckn.Utils.Servant.Client import Beckn.Utils.Servant.SignatureAuth import qualified Data.Text as T import EulerHS.Prelude import System.Environment (lookupEnv) data AppCfg = AppCfg { esqDBCfg :: EsqDBConfig, port :: Int, metricsPort :: Int, hostName :: Text, nwAddress :: BaseUrl, signingKey :: PrivateKey, signatureExpiry :: Seconds, migrationPath :: Maybe FilePath, autoMigrate :: Bool, coreVersion :: Text, domainVersion :: Text, loggerConfig :: LoggerConfig, graceTerminationPeriod :: Seconds, registryUrl :: BaseUrl, encTools :: EncTools, authTokenCacheExpiry :: Seconds, disableSignatureAuth :: Bool, otpSmsTemplate :: Text, smsCfg :: SmsConfig, inviteSmsTemplate :: Text, apiRateLimitOptions :: APIRateLimitOptions, driverPositionInfoExpiry :: Maybe Seconds, fcmJsonPath :: Maybe Text, fcmUrl :: BaseUrl, googleMapsUrl :: BaseUrl, googleMapsKey :: Text, defaultRadiusOfSearch :: Meters, redisCfg :: T.RedisConfig, searchRequestExpirationSeconds :: Int, httpClientOptions :: HttpClientOptions } deriving (Generic, FromDhall) data AppEnv = AppEnv { hostName :: Text, nwAddress :: BaseUrl, signingKey :: PrivateKey, signatureExpiry :: Seconds, coreVersion :: Text, domainVersion :: Text, loggerConfig :: LoggerConfig, graceTerminationPeriod :: Seconds, registryUrl :: BaseUrl, disableSignatureAuth :: Bool, esqDBEnv :: EsqDBEnv, isShuttingDown :: TMVar (), loggerEnv :: LoggerEnv, encTools :: EncTools, authTokenCacheExpiry :: Seconds, port :: Int, coreMetrics :: Metrics.CoreMetricsContainer, httpClientOptions :: HttpClientOptions, otpSmsTemplate :: Text, smsCfg :: SmsConfig, inviteSmsTemplate :: Text, apiRateLimitOptions :: APIRateLimitOptions, driverPositionInfoExpiry :: Maybe Seconds, fcmJsonPath :: Maybe Text, fcmUrl :: BaseUrl, googleMapsUrl :: BaseUrl, googleMapsKey :: Text, defaultRadiusOfSearch :: Meters, searchRequestExpirationSeconds :: Int } deriving (Generic) instance AuthenticatingEntity AppEnv where getSigningKey = (.signingKey) getSignatureExpiry = (.signatureExpiry) buildAppEnv :: AppCfg -> IO AppEnv buildAppEnv AppCfg {..} = do hostname <- map T.pack <$> lookupEnv "POD_NAME" isShuttingDown <- newEmptyTMVarIO loggerEnv <- prepareLoggerEnv loggerConfig hostname esqDBEnv <- prepareEsqDBEnv esqDBCfg loggerEnv coreMetrics <- Metrics.registerCoreMetricsContainer return AppEnv {..} releaseAppEnv :: AppEnv -> IO () releaseAppEnv AppEnv {..} = do FIXME : disconnect database ? releaseLoggerEnv loggerEnv type Env = EnvR AppEnv type FlowHandler = FlowHandlerR AppEnv type FlowServer api = FlowServerR AppEnv api type Flow = FlowR AppEnv instance Registry Flow where registryLookup = Registry.withSubscriberCache Registry.registryLookup cacheRegistryKey :: Text cacheRegistryKey = "driver-offer-bpp:registry" instance Cache Subscriber Flow where type CacheKey Subscriber = SimpleLookupRequest getKey = Cache.getKey cacheRegistryKey . lookupRequestToRedisKey setKey = Cache.setKey cacheRegistryKey . lookupRequestToRedisKey delKey = Cache.delKey cacheRegistryKey . lookupRequestToRedisKey instance CacheEx Subscriber Flow where setKeyEx ttl = Cache.setKeyEx cacheRegistryKey ttl . lookupRequestToRedisKey
24f860c0169e1d17e31a904325639945a283569c855673f383546edd93451978
inria-parkas/sundialsml
cvsHessian_ASA_FSA.ml
* ----------------------------------------------------------------- * $ Revision : 1.2 $ * $ Date : 2010/12/01 22:57:59 $ * ----------------------------------------------------------------- * Programmer(s ): @ LLNL * ----------------------------------------------------------------- * OCaml port : , , Jun 2014 . * ----------------------------------------------------------------- * Copyright ( c ) 2002 , The Regents of the University of California . * Produced at the Lawrence Livermore National Laboratory . * All rights reserved . * For details , see the LICENSE file . * ----------------------------------------------------------------- * * Hessian through adjoint sensitivity example problem . * * [ - p1 * y1 ^ 2 - y3 ] [ 1 ] * y ' = [ - y2 ] y(0 ) = [ 1 ] * [ -p2 ^ 2 * y2 * [ 1 ] * * p1 = 1.0 * p2 = 2.0 * * 2 * / * G(p ) = | 0.5 * ( y1 ^ 2 + y2 ^ 2 + y3 ^ 2 ) dt * / * 0 * * Compute the gradient ( ASA ) and Hessian ( FSA over ASA ) of G(p ) . * * See and , SISC 26(5 ) 1725 - 1743 , 2005 . * * ----------------------------------------------------------------- * ----------------------------------------------------------------- * $Revision: 1.2 $ * $Date: 2010/12/01 22:57:59 $ * ----------------------------------------------------------------- * Programmer(s): Radu Serban @ LLNL * ----------------------------------------------------------------- * OCaml port: Timothy Bourke, Inria, Jun 2014. * ----------------------------------------------------------------- * Copyright (c) 2002, The Regents of the University of California. * Produced at the Lawrence Livermore National Laboratory. * All rights reserved. * For details, see the LICENSE file. * ----------------------------------------------------------------- * * Hessian through adjoint sensitivity example problem. * * [ - p1 * y1^2 - y3 ] [ 1 ] * y' = [ - y2 ] y(0) = [ 1 ] * [ -p2^2 * y2 * y3 ] [ 1 ] * * p1 = 1.0 * p2 = 2.0 * * 2 * / * G(p) = | 0.5 * ( y1^2 + y2^2 + y3^2 ) dt * / * 0 * * Compute the gradient (ASA) and Hessian (FSA over ASA) of G(p). * * See D.B. Ozyurt and P.I. Barton, SISC 26(5) 1725-1743, 2005. * * ----------------------------------------------------------------- *) open Sundials let compat2_3 = match Config.sundials_version with | 2,_,_ -> true | 3,_,_ -> true | _ -> false module Quad = Cvodes.Quadrature module Sens = Cvodes.Sensitivity module QuadSens = Cvodes.Sensitivity.Quadrature module Adj = Cvodes.Adjoint module QuadAdj = Cvodes.Adjoint.Quadrature let unwrap = Nvector.unwrap let printf = Printf.printf let ith (v : RealArray.t) i = v.{i - 1} let set_ith (v : RealArray.t) i e = v.{i - 1} <- e let zero = 0.0 let one = 1.0 type user_data = { mutable p1 : float; mutable p2 : float; } (* *-------------------------------------------------------------------- * FUNCTIONS CALLED BY CVODES *-------------------------------------------------------------------- *) let f data _ (y : RealArray.t) (ydot : RealArray.t) = let p1 = data.p1 and p2 = data.p2 in ydot.{0} <- -.p1*.y.{0}*.y.{0} -. y.{2}; ydot.{1} <- -.y.{1}; ydot.{2} <- -.p2*.p2*.y.{1}*.y.{2} let fQ _ _ (y : RealArray.t) (qdot : RealArray.t) = qdot.{0} <- 0.5 *. ( y.{0}*.y.{0} +. y.{1}*.y.{1} +. y.{2}*.y.{2}) let fS : user_data -> RealArray.t Sens.sensrhsfn_all = fun data { Sens.y = y } yS ySdot -> let p1 = data.p1 and p2 = data.p2 in (* 1st sensitivity RHS *) let s1 = yS.(0).{0} in let s2 = yS.(0).{1} in let s3 = yS.(0).{2} in let fys1 = -. 2.0*.p1*.y.{0} *. s1 -. s3 and fys2 = -. s2 and fys3 = -. p2*.p2*.y.{2} *. s2 -. p2*.p2*.y.{1} *. s3 in ySdot.(0).{0} <- (fys1 -. y.{0}*.y.{0}); ySdot.(0).{1} <- fys2; ySdot.(0).{2} <- fys3; 2nd sensitivity RHS let s1 = yS.(1).{0} and s2 = yS.(1).{1} and s3 = yS.(1).{2} in let fys1 = -. 2.0*.p1*.y.{0} *. s1 -. s3 and fys2 = -. s2 and fys3 = -. p2*.p2*.y.{2} *. s2 -. p2*.p2*.y.{1} *. s3 in ySdot.(1).{0} <- fys1; ySdot.(1).{1} <- fys2; ySdot.(1).{2} <- (fys3 -. 2.0*.p2*.y.{1}*.y.{2}) let fQS : user_data -> RealArray.t QuadSens.quadsensrhsfn = fun _ { QuadSens.y = y; QuadSens.s = yS } yQSdot -> (* 1st sensitivity RHS *) let s1 = yS.(0).{0} and s2 = yS.(0).{1} and s3 = yS.(0).{2} in yQSdot.(0).{0} <- y.{0}*.s1 +. y.{1}*.s2 +. y.{2}*.s3; (* 1st sensitivity RHS *) let s1 = yS.(1).{0} and s2 = yS.(1).{1} and s3 = yS.(1).{2} in yQSdot.(1).{0} <- y.{0}*.s1 +. y.{1}*.s2 +. y.{2}*.s3 let fB1 : user_data -> RealArray.t Adj.brhsfn_with_sens = fun data args yS yBdot -> let y = args.Adj.y and yB = args.Adj.yb in let p1 = data.p1 and p2 = data.p2 in sensitivity 1 and s2 = yS.(0).{1} and s3 = yS.(0).{2} in let l1 = yB.{0} (* lambda *) and l2 = yB.{1} and l3 = yB.{2} in let m1 = yB.{3} (* mu *) and m2 = yB.{4} and m3 = yB.{5} in yBdot.{0} <- 2.0*.p1*.y.{0} *. l1 -. y.{0}; yBdot.{1} <- l2 +. p2*.p2*.y.{2} *. l3 -. y.{1}; yBdot.{2} <- l1 +. p2*.p2*.y.{1} *. l3 -. y.{2}; yBdot.{3} <- 2.0*.p1*.y.{0} *. m1 +. l1 *. 2.0*.(y.{0} +. p1*.s1) -. s1; yBdot.{4} <- m2 +. p2*.p2*.y.{2} *. m3 +. l3 *. p2*.p2*.s3 -. s2; yBdot.{5} <- m1 +. p2*.p2*.y.{1} *. m3 +. l3 *. p2*.p2*.s2 -. s3 let fQB1 : user_data -> RealArray.t QuadAdj.bquadrhsfn_with_sens = fun data args yS qBdot -> let y = args.QuadAdj.y and yB = args.QuadAdj.yb in let p2 = data.p2 in sensitivity 1 and s2 = yS.(0).{1} and s3 = yS.(0).{2} in let l1 = yB.{0} (* lambda *) and l3 = yB.{2} in let m1 = yB.{3} (* mu *) and m3 = yB.{5} in qBdot.{0} <- -.y.{0}*.y.{0} *. l1; qBdot.{1} <- -.2.0*.p2*.y.{1}*.y.{2} *. l3; qBdot.{2} <- -.y.{0}*.y.{0} *. m1 -. l1 *. 2.0*.y.{0}*.s1; qBdot.{3} <- -.2.0*.p2*.y.{1}*.y.{2} *. m3 -. l3 *. 2.0*.(p2*.y.{2}*.s2 +. p2*.y.{1}*.s3) let fB2 : user_data -> RealArray.t Adj.brhsfn_with_sens = fun data args yS yBdot -> let y = args.Adj.y and yB = args.Adj.yb in let p1 = data.p1 and p2 = data.p2 in sensitivity 2 and s2 = yS.(1).{1} and s3 = yS.(1).{2} in let l1 = yB.{0} (* lambda *) and l2 = yB.{1} and l3 = yB.{2} in let m1 = yB.{3} (* mu *) and m2 = yB.{4} and m3 = yB.{5} in yBdot.{0} <- 2.0*.p1*.y.{0} *. l1 -. y.{0}; yBdot.{1} <- l2 +. p2*.p2*.y.{2} *. l3 -. y.{1}; yBdot.{2} <- l1 +. p2*.p2*.y.{1} *. l3 -. y.{2}; yBdot.{3} <- 2.0*.p1*.y.{0} *. m1 +. l1 *. 2.0*.p1*.s1 -. s1; yBdot.{4} <- m2 +. p2*.p2*.y.{2} *. m3 +. l3 *. (2.0*.p2*.y.{2} +. p2*.p2*.s3) -. s2; match Config.sundials_version with | 2,5,_ -> yBdot.{5} <- m1 +. p2*.p2*.y.{1} *. m3 +. l3 *. (2.0*.p2*.y.{2} +. p2*.p2*.s2) -. s3 | _ -> yBdot.{5} <- m1 +. p2*.p2*.y.{1} *. m3 +. l3 *. (2.0*.p2*.y.{1} +. p2*.p2*.s2) -. s3 let fQB2 : user_data -> RealArray.t QuadAdj.bquadrhsfn_with_sens = fun data args yS qBdot -> let y = args.QuadAdj.y and yB = args.QuadAdj.yb in let p2 = data.p2 in sensitivity 2 and s2 = yS.(1).{1} and s3 = yS.(1).{2} in let l1 = yB.{0} (* lambda *) and l3 = yB.{2} in let m1 = yB.{3} (* mu *) and m3 = yB.{5} in qBdot.{0} <- -.y.{0}*.y.{0} *. l1; qBdot.{1} <- -.2.0*.p2*.y.{1}*.y.{2} *. l3; qBdot.{2} <- -.y.{0}*.y.{0} *. m1 -. l1 *. 2.0*.y.{0}*.s1; qBdot.{3} <- -.2.0*.p2*.y.{1}*.y.{2} *. m3 -. l3 *. 2.0*.(p2*.y.{2}*.s2 +. p2*.y.{1}*.s3 +. y.{1}*.y.{2}) (* *-------------------------------------------------------------------- * PRIVATE FUNCTIONS *-------------------------------------------------------------------- *) let print_fwd_stats cvode_mem = let open Cvode in let { num_steps = nst; num_rhs_evals = nfe; num_lin_solv_setups = nsetups; num_err_test_fails = netf; _ } = get_integrator_stats cvode_mem in let nni, ncfn = get_nonlin_solv_stats cvode_mem and nfQe, netfQ = Quad.get_stats cvode_mem and { Sens.num_sens_evals = nfSe; Sens.num_err_test_fails = netfS; Sens.num_lin_solv_setups = nsetupsS; _ } = Sens.get_stats cvode_mem and nniS, ncfnS = if compat2_3 then Sens.get_nonlin_solv_stats cvode_mem else 0,0 and nfQSe, netfQS = QuadSens.get_stats cvode_mem in printf " Number steps: %5d\n\n" nst; printf " Function evaluations:\n"; printf " f: %5d\n fQ: %5d\n fS: %5d\n fQS: %5d\n" nfe nfQe nfSe nfQSe; printf " Error test failures:\n"; printf " netf: %5d\n netfQ: %5d\n netfS: %5d\n netfQS: %5d\n" netf netfQ netfS netfQS; printf " Linear solver setups:\n"; printf " nsetups: %5d\n nsetupsS: %5d\n" nsetups nsetupsS; printf " Nonlinear iterations:\n"; printf " nni: %5d\n" nni; if compat2_3 then printf " nniS: %5d\n" nniS; printf " Convergence failures:\n"; printf " ncfn: %5d\n" ncfn; if compat2_3 then printf " ncfnS: %5d\n" ncfnS; printf "\n" let print_bck_stats cvode_mem = let open Cvode in let { num_steps = nst; num_rhs_evals = nfe; num_lin_solv_setups = nsetups; num_err_test_fails = netf; _ } = Adj.get_integrator_stats cvode_mem in let nni, ncfn = Adj.get_nonlin_solv_stats cvode_mem and nfQe, netfQ = QuadAdj.get_stats cvode_mem in printf " Number steps: %5d\n\n" nst; printf " Function evaluations:\n"; printf " f: %5d\n fQ: %5d\n" nfe nfQe; printf " Error test failures:\n"; printf " netf: %5d\n netfQ: %5d\n" netf netfQ; printf " Linear solver setups:\n"; printf " nsetups: %5d\n" nsetups; printf " Nonlinear iterations:\n"; printf " nni: %5d\n" nni; printf " Convergence failures:\n"; printf " ncfn: %5d\n" ncfn; printf "\n" (* *-------------------------------------------------------------------- * MAIN PROGRAM *-------------------------------------------------------------------- *) let main () = let grdG_fwd = Array.make 2 0.0 in let grdG_bck = Array.make 2 0.0 in let grdG_cntr = Array.make 2 0.0 in (* User data structure *) let data = { p1 = 1.0; p2 = 2.0 } in (* Problem size, integration interval, and tolerances *) let neq = 3 in let np = 2 in let np2 = 2*np in let t0 = 0.0 in let tf = 2.0 in let reltol = 1.0e-8 in let abstol = 1.0e-8 in let abstolQ = 1.0e-8 in let abstolB = 1.0e-8 in let abstolQB = 1.0e-8 in Initializations for forward problem let y = Nvector_serial.make neq one in let ydata = unwrap y in let yQ = Nvector_serial.make 1 zero in let yS = Array.init np (fun _ -> Nvector_serial.make neq zero) in let yQS = Array.init np (fun _ -> Nvector_serial.make 1 zero) in (* Create and initialize forward problem *) let m = Matrix.dense neq in let cvode_mem = Cvode.(init BDF (SStolerances (reltol, abstol)) ~lsolver:Dls.(solver (dense y m)) (f data) t0 y) in Quad.init cvode_mem (fQ data) yQ; Quad.set_tolerances cvode_mem (Quad.SStolerances (reltol, abstolQ)); Sens.(init cvode_mem EEtolerances (Simultaneous None) (AllAtOnce (Some (fS data))) yS); Sens.set_err_con cvode_mem true; QuadSens.init cvode_mem ~fqs:(fQS data) yQS; QuadSens.set_tolerances cvode_mem (QuadSens.EEtolerances); Initialize ASA let steps = 100 in Adj.init cvode_mem steps Adj.IPolynomial; (* Forward integration *) printf "-------------------\n"; printf "Forward integration\n"; printf "-------------------\n\n"; let _, ncheck, _ = Adj.forward_normal cvode_mem tf y in ignore (Quad.get cvode_mem yQ); let g = ith (unwrap yQ) 1 in ignore (Sens.get cvode_mem yS); ignore (QuadSens.get cvode_mem yQS); printf "ncheck = %d\n" ncheck; printf "\n"; printf " y: %12.4e %12.4e %12.4e" (ith ydata 1) (ith ydata 2) (ith ydata 3); printf " G: %12.4e\n" (ith (unwrap yQ) 1); printf "\n"; printf " yS1: %12.4e %12.4e %12.4e\n" (ith (unwrap yS.(0)) 1) (ith (unwrap yS.(0)) 2) (ith (unwrap yS.(0)) 3); printf " yS2: %12.4e %12.4e %12.4e\n" (ith (unwrap yS.(1)) 1) (ith (unwrap yS.(1)) 2) (ith (unwrap yS.(1)) 3); printf "\n"; printf " dG/dp: %12.4e %12.4e\n" (ith (unwrap yQS.(0)) 1) (ith (unwrap yQS.(1)) 1); printf "\n"; printf "Final Statistics for forward pb.\n"; printf "--------------------------------\n"; print_fwd_stats cvode_mem; (* Initializations for backward problems *) let yB1 = Nvector_serial.make (2 * neq) zero in let yQB1 = Nvector_serial.make np2 zero in let yB2 = Nvector_serial.make (2 * neq) zero in let yQB2 = Nvector_serial.make np2 zero in Create and initialize backward problems ( one for each column of the Hessian ) let m = Matrix.dense (2*neq) in let cvode_memB1 = Adj.(init_backward cvode_mem Cvode.BDF (SStolerances (reltol, abstolB)) ~lsolver:Dls.(solver (dense yB1 m)) (WithSens (fB1 data)) tf yB1) in QuadAdj.(init cvode_memB1 (WithSens (fQB1 data)) yQB1); QuadAdj.(set_tolerances cvode_memB1 (SStolerances (reltol, abstolQB))); let m = Matrix.dense (2*neq) in let cvode_memB2 = Adj.(init_backward cvode_mem Cvode.BDF (SStolerances (reltol, abstolB)) ~lsolver:Dls.(solver (dense yB2 m)) (WithSens (fB2 data)) tf yB2) in QuadAdj.(init cvode_memB2 (WithSens (fQB2 data)) yQB2); QuadAdj.(set_tolerances cvode_memB2 (SStolerances (reltol, abstolB))); (* Backward integration *) printf "---------------------------------------------\n"; printf "Backward integration ... (2 adjoint problems)\n"; printf "---------------------------------------------\n\n"; Adj.backward_normal cvode_mem t0; ignore (Adj.get cvode_memB1 yB1); ignore (QuadAdj.get cvode_memB1 yQB1); ignore (Adj.get cvode_memB2 yB2); ignore (QuadAdj.get cvode_memB2 yQB2); printf " dG/dp: %12.4e %12.4e (from backward pb. 1)\n" (-.ith (unwrap yQB1) 1) (-.ith (unwrap yQB1) 2); printf " %12.4e %12.4e (from backward pb. 2)\n" (-.ith (unwrap yQB2) 1) (-.ith (unwrap yQB2) 2); printf "\n"; printf " H = d2G/dp2:\n"; printf " (1) (2)\n"; printf " %12.4e %12.4e\n" (-.ith (unwrap yQB1) 3) (-.ith (unwrap yQB2) 3); printf " %12.4e %12.4e\n" (-.ith (unwrap yQB1) 4) (-.ith (unwrap yQB2) 4); printf "\n"; printf "Final Statistics for backward pb. 1\n"; printf "-----------------------------------\n"; print_bck_stats cvode_memB1; printf "Final Statistics for backward pb. 2\n"; printf "-----------------------------------\n"; print_bck_stats cvode_memB2; (* Free CVODES memory *) (* Finite difference tests *) let dp = 1.0e-2 in printf "-----------------------\n"; printf "Finite Difference tests\n"; printf "-----------------------\n\n"; printf "del_p = %g\n\n" dp; RealArray.fill (unwrap y) one; let m = Matrix.dense neq in let cvode_mem = Cvode.(init BDF (SStolerances (reltol, abstol)) ~lsolver:Dls.(solver (dense y m)) (f data) t0 y) in RealArray.fill (unwrap yQ) zero; Quad.init cvode_mem (fQ data) yQ; Quad.(set_tolerances cvode_mem (SStolerances (reltol, abstolQ))); data.p1 <- data.p1 +. dp; ignore (Cvode.solve_normal cvode_mem tf y); ignore (Quad.get cvode_mem yQ); let gp = ith (unwrap yQ) 1 in printf "p1+ y: %12.4e %12.4e %12.4e" (ith (unwrap y) 1) (ith (unwrap y) 2) (ith (unwrap y) 3); printf " G: %12.4e\n" (ith (unwrap yQ) 1); data.p1 <- data.p1 -. 2.0*.dp; RealArray.fill (unwrap y) one; RealArray.fill (unwrap yQ) zero; Cvode.reinit cvode_mem t0 y; Quad.reinit cvode_mem yQ; ignore (Cvode.solve_normal cvode_mem tf y); ignore (Quad.get cvode_mem yQ); let gm = ith (unwrap yQ) 1 in printf "p1- y: %12.4e %12.4e %12.4e" (ith (unwrap y) 1) (ith (unwrap y) 2) (ith (unwrap y) 3); printf " G: %12.4e\n" (ith (unwrap yQ) 1); data.p1 <- data.p1 +. dp; grdG_fwd.(0) <- (gp-.g)/.dp; grdG_bck.(0) <- (g-.gm)/.dp; grdG_cntr.(0) <- (gp-.gm)/.(2.0*.dp); let h11 = (gp -. 2.0*.g +. gm) /. (dp*.dp) in data.p2 <- data.p2 +. dp; RealArray.fill (unwrap y) one; RealArray.fill (unwrap yQ) zero; Cvode.reinit cvode_mem t0 y; Quad.reinit cvode_mem yQ; ignore (Cvode.solve_normal cvode_mem tf y); ignore (Quad.get cvode_mem yQ); let gp = ith (unwrap yQ) 1 in printf "p2+ y: %12.4e %12.4e %12.4e" (ith (unwrap y) 1) (ith (unwrap y) 2) (ith (unwrap y) 3); printf " G: %12.4e\n" (ith (unwrap yQ) 1); data.p2 <- data.p2 -. 2.0*.dp; RealArray.fill (unwrap y) one; RealArray.fill (unwrap yQ) zero; Cvode.reinit cvode_mem t0 y; Quad.reinit cvode_mem yQ; ignore (Cvode.solve_normal cvode_mem tf y); ignore (Quad.get cvode_mem yQ); let gm = ith (unwrap yQ) 1 in printf "p2- y: %12.4e %12.4e %12.4e" (ith (unwrap y) 1) (ith (unwrap y) 2) (ith (unwrap y) 3); printf " G: %12.4e\n" (ith (unwrap yQ) 1); data.p2 <- data.p2 +. dp; grdG_fwd.(1) <- (gp-.g)/.dp; grdG_bck.(1) <- (g-.gm)/.dp; grdG_cntr.(1) <- (gp-.gm)/.(2.0*.dp); let h22 = (gp -. 2.0*.g +. gm) /. (dp*.dp) in printf "\n"; printf " dG/dp: %12.4e %12.4e (fwd FD)\n" grdG_fwd.(0) grdG_fwd.(1); printf " %12.4e %12.4e (bck FD)\n" grdG_bck.(0) grdG_bck.(1); printf " %12.4e %12.4e (cntr FD)\n" grdG_cntr.(0) grdG_cntr.(1); printf "\n"; printf " H(1,1): %12.4e\n" h11; printf " H(2,2): %12.4e\n" h22 (* Check environment variables for extra arguments. *) let reps = try int_of_string (Unix.getenv "NUM_REPS") with Not_found | Failure _ -> 1 let gc_at_end = try int_of_string (Unix.getenv "GC_AT_END") <> 0 with Not_found | Failure _ -> false let gc_each_rep = try int_of_string (Unix.getenv "GC_EACH_REP") <> 0 with Not_found | Failure _ -> false (* Entry point *) let _ = for _ = 1 to reps do main (); if gc_each_rep then Gc.compact () done; if gc_at_end then Gc.compact ()
null
https://raw.githubusercontent.com/inria-parkas/sundialsml/a1848318cac2e340c32ddfd42671bef07b1390db/examples/cvodes/serial/cvsHessian_ASA_FSA.ml
ocaml
*-------------------------------------------------------------------- * FUNCTIONS CALLED BY CVODES *-------------------------------------------------------------------- 1st sensitivity RHS 1st sensitivity RHS 1st sensitivity RHS lambda mu lambda mu lambda mu lambda mu *-------------------------------------------------------------------- * PRIVATE FUNCTIONS *-------------------------------------------------------------------- *-------------------------------------------------------------------- * MAIN PROGRAM *-------------------------------------------------------------------- User data structure Problem size, integration interval, and tolerances Create and initialize forward problem Forward integration Initializations for backward problems Backward integration Free CVODES memory Finite difference tests Check environment variables for extra arguments. Entry point
* ----------------------------------------------------------------- * $ Revision : 1.2 $ * $ Date : 2010/12/01 22:57:59 $ * ----------------------------------------------------------------- * Programmer(s ): @ LLNL * ----------------------------------------------------------------- * OCaml port : , , Jun 2014 . * ----------------------------------------------------------------- * Copyright ( c ) 2002 , The Regents of the University of California . * Produced at the Lawrence Livermore National Laboratory . * All rights reserved . * For details , see the LICENSE file . * ----------------------------------------------------------------- * * Hessian through adjoint sensitivity example problem . * * [ - p1 * y1 ^ 2 - y3 ] [ 1 ] * y ' = [ - y2 ] y(0 ) = [ 1 ] * [ -p2 ^ 2 * y2 * [ 1 ] * * p1 = 1.0 * p2 = 2.0 * * 2 * / * G(p ) = | 0.5 * ( y1 ^ 2 + y2 ^ 2 + y3 ^ 2 ) dt * / * 0 * * Compute the gradient ( ASA ) and Hessian ( FSA over ASA ) of G(p ) . * * See and , SISC 26(5 ) 1725 - 1743 , 2005 . * * ----------------------------------------------------------------- * ----------------------------------------------------------------- * $Revision: 1.2 $ * $Date: 2010/12/01 22:57:59 $ * ----------------------------------------------------------------- * Programmer(s): Radu Serban @ LLNL * ----------------------------------------------------------------- * OCaml port: Timothy Bourke, Inria, Jun 2014. * ----------------------------------------------------------------- * Copyright (c) 2002, The Regents of the University of California. * Produced at the Lawrence Livermore National Laboratory. * All rights reserved. * For details, see the LICENSE file. * ----------------------------------------------------------------- * * Hessian through adjoint sensitivity example problem. * * [ - p1 * y1^2 - y3 ] [ 1 ] * y' = [ - y2 ] y(0) = [ 1 ] * [ -p2^2 * y2 * y3 ] [ 1 ] * * p1 = 1.0 * p2 = 2.0 * * 2 * / * G(p) = | 0.5 * ( y1^2 + y2^2 + y3^2 ) dt * / * 0 * * Compute the gradient (ASA) and Hessian (FSA over ASA) of G(p). * * See D.B. Ozyurt and P.I. Barton, SISC 26(5) 1725-1743, 2005. * * ----------------------------------------------------------------- *) open Sundials let compat2_3 = match Config.sundials_version with | 2,_,_ -> true | 3,_,_ -> true | _ -> false module Quad = Cvodes.Quadrature module Sens = Cvodes.Sensitivity module QuadSens = Cvodes.Sensitivity.Quadrature module Adj = Cvodes.Adjoint module QuadAdj = Cvodes.Adjoint.Quadrature let unwrap = Nvector.unwrap let printf = Printf.printf let ith (v : RealArray.t) i = v.{i - 1} let set_ith (v : RealArray.t) i e = v.{i - 1} <- e let zero = 0.0 let one = 1.0 type user_data = { mutable p1 : float; mutable p2 : float; } let f data _ (y : RealArray.t) (ydot : RealArray.t) = let p1 = data.p1 and p2 = data.p2 in ydot.{0} <- -.p1*.y.{0}*.y.{0} -. y.{2}; ydot.{1} <- -.y.{1}; ydot.{2} <- -.p2*.p2*.y.{1}*.y.{2} let fQ _ _ (y : RealArray.t) (qdot : RealArray.t) = qdot.{0} <- 0.5 *. ( y.{0}*.y.{0} +. y.{1}*.y.{1} +. y.{2}*.y.{2}) let fS : user_data -> RealArray.t Sens.sensrhsfn_all = fun data { Sens.y = y } yS ySdot -> let p1 = data.p1 and p2 = data.p2 in let s1 = yS.(0).{0} in let s2 = yS.(0).{1} in let s3 = yS.(0).{2} in let fys1 = -. 2.0*.p1*.y.{0} *. s1 -. s3 and fys2 = -. s2 and fys3 = -. p2*.p2*.y.{2} *. s2 -. p2*.p2*.y.{1} *. s3 in ySdot.(0).{0} <- (fys1 -. y.{0}*.y.{0}); ySdot.(0).{1} <- fys2; ySdot.(0).{2} <- fys3; 2nd sensitivity RHS let s1 = yS.(1).{0} and s2 = yS.(1).{1} and s3 = yS.(1).{2} in let fys1 = -. 2.0*.p1*.y.{0} *. s1 -. s3 and fys2 = -. s2 and fys3 = -. p2*.p2*.y.{2} *. s2 -. p2*.p2*.y.{1} *. s3 in ySdot.(1).{0} <- fys1; ySdot.(1).{1} <- fys2; ySdot.(1).{2} <- (fys3 -. 2.0*.p2*.y.{1}*.y.{2}) let fQS : user_data -> RealArray.t QuadSens.quadsensrhsfn = fun _ { QuadSens.y = y; QuadSens.s = yS } yQSdot -> let s1 = yS.(0).{0} and s2 = yS.(0).{1} and s3 = yS.(0).{2} in yQSdot.(0).{0} <- y.{0}*.s1 +. y.{1}*.s2 +. y.{2}*.s3; let s1 = yS.(1).{0} and s2 = yS.(1).{1} and s3 = yS.(1).{2} in yQSdot.(1).{0} <- y.{0}*.s1 +. y.{1}*.s2 +. y.{2}*.s3 let fB1 : user_data -> RealArray.t Adj.brhsfn_with_sens = fun data args yS yBdot -> let y = args.Adj.y and yB = args.Adj.yb in let p1 = data.p1 and p2 = data.p2 in sensitivity 1 and s2 = yS.(0).{1} and s3 = yS.(0).{2} in and l2 = yB.{1} and l3 = yB.{2} in and m2 = yB.{4} and m3 = yB.{5} in yBdot.{0} <- 2.0*.p1*.y.{0} *. l1 -. y.{0}; yBdot.{1} <- l2 +. p2*.p2*.y.{2} *. l3 -. y.{1}; yBdot.{2} <- l1 +. p2*.p2*.y.{1} *. l3 -. y.{2}; yBdot.{3} <- 2.0*.p1*.y.{0} *. m1 +. l1 *. 2.0*.(y.{0} +. p1*.s1) -. s1; yBdot.{4} <- m2 +. p2*.p2*.y.{2} *. m3 +. l3 *. p2*.p2*.s3 -. s2; yBdot.{5} <- m1 +. p2*.p2*.y.{1} *. m3 +. l3 *. p2*.p2*.s2 -. s3 let fQB1 : user_data -> RealArray.t QuadAdj.bquadrhsfn_with_sens = fun data args yS qBdot -> let y = args.QuadAdj.y and yB = args.QuadAdj.yb in let p2 = data.p2 in sensitivity 1 and s2 = yS.(0).{1} and s3 = yS.(0).{2} in and l3 = yB.{2} in and m3 = yB.{5} in qBdot.{0} <- -.y.{0}*.y.{0} *. l1; qBdot.{1} <- -.2.0*.p2*.y.{1}*.y.{2} *. l3; qBdot.{2} <- -.y.{0}*.y.{0} *. m1 -. l1 *. 2.0*.y.{0}*.s1; qBdot.{3} <- -.2.0*.p2*.y.{1}*.y.{2} *. m3 -. l3 *. 2.0*.(p2*.y.{2}*.s2 +. p2*.y.{1}*.s3) let fB2 : user_data -> RealArray.t Adj.brhsfn_with_sens = fun data args yS yBdot -> let y = args.Adj.y and yB = args.Adj.yb in let p1 = data.p1 and p2 = data.p2 in sensitivity 2 and s2 = yS.(1).{1} and s3 = yS.(1).{2} in and l2 = yB.{1} and l3 = yB.{2} in and m2 = yB.{4} and m3 = yB.{5} in yBdot.{0} <- 2.0*.p1*.y.{0} *. l1 -. y.{0}; yBdot.{1} <- l2 +. p2*.p2*.y.{2} *. l3 -. y.{1}; yBdot.{2} <- l1 +. p2*.p2*.y.{1} *. l3 -. y.{2}; yBdot.{3} <- 2.0*.p1*.y.{0} *. m1 +. l1 *. 2.0*.p1*.s1 -. s1; yBdot.{4} <- m2 +. p2*.p2*.y.{2} *. m3 +. l3 *. (2.0*.p2*.y.{2} +. p2*.p2*.s3) -. s2; match Config.sundials_version with | 2,5,_ -> yBdot.{5} <- m1 +. p2*.p2*.y.{1} *. m3 +. l3 *. (2.0*.p2*.y.{2} +. p2*.p2*.s2) -. s3 | _ -> yBdot.{5} <- m1 +. p2*.p2*.y.{1} *. m3 +. l3 *. (2.0*.p2*.y.{1} +. p2*.p2*.s2) -. s3 let fQB2 : user_data -> RealArray.t QuadAdj.bquadrhsfn_with_sens = fun data args yS qBdot -> let y = args.QuadAdj.y and yB = args.QuadAdj.yb in let p2 = data.p2 in sensitivity 2 and s2 = yS.(1).{1} and s3 = yS.(1).{2} in and l3 = yB.{2} in and m3 = yB.{5} in qBdot.{0} <- -.y.{0}*.y.{0} *. l1; qBdot.{1} <- -.2.0*.p2*.y.{1}*.y.{2} *. l3; qBdot.{2} <- -.y.{0}*.y.{0} *. m1 -. l1 *. 2.0*.y.{0}*.s1; qBdot.{3} <- -.2.0*.p2*.y.{1}*.y.{2} *. m3 -. l3 *. 2.0*.(p2*.y.{2}*.s2 +. p2*.y.{1}*.s3 +. y.{1}*.y.{2}) let print_fwd_stats cvode_mem = let open Cvode in let { num_steps = nst; num_rhs_evals = nfe; num_lin_solv_setups = nsetups; num_err_test_fails = netf; _ } = get_integrator_stats cvode_mem in let nni, ncfn = get_nonlin_solv_stats cvode_mem and nfQe, netfQ = Quad.get_stats cvode_mem and { Sens.num_sens_evals = nfSe; Sens.num_err_test_fails = netfS; Sens.num_lin_solv_setups = nsetupsS; _ } = Sens.get_stats cvode_mem and nniS, ncfnS = if compat2_3 then Sens.get_nonlin_solv_stats cvode_mem else 0,0 and nfQSe, netfQS = QuadSens.get_stats cvode_mem in printf " Number steps: %5d\n\n" nst; printf " Function evaluations:\n"; printf " f: %5d\n fQ: %5d\n fS: %5d\n fQS: %5d\n" nfe nfQe nfSe nfQSe; printf " Error test failures:\n"; printf " netf: %5d\n netfQ: %5d\n netfS: %5d\n netfQS: %5d\n" netf netfQ netfS netfQS; printf " Linear solver setups:\n"; printf " nsetups: %5d\n nsetupsS: %5d\n" nsetups nsetupsS; printf " Nonlinear iterations:\n"; printf " nni: %5d\n" nni; if compat2_3 then printf " nniS: %5d\n" nniS; printf " Convergence failures:\n"; printf " ncfn: %5d\n" ncfn; if compat2_3 then printf " ncfnS: %5d\n" ncfnS; printf "\n" let print_bck_stats cvode_mem = let open Cvode in let { num_steps = nst; num_rhs_evals = nfe; num_lin_solv_setups = nsetups; num_err_test_fails = netf; _ } = Adj.get_integrator_stats cvode_mem in let nni, ncfn = Adj.get_nonlin_solv_stats cvode_mem and nfQe, netfQ = QuadAdj.get_stats cvode_mem in printf " Number steps: %5d\n\n" nst; printf " Function evaluations:\n"; printf " f: %5d\n fQ: %5d\n" nfe nfQe; printf " Error test failures:\n"; printf " netf: %5d\n netfQ: %5d\n" netf netfQ; printf " Linear solver setups:\n"; printf " nsetups: %5d\n" nsetups; printf " Nonlinear iterations:\n"; printf " nni: %5d\n" nni; printf " Convergence failures:\n"; printf " ncfn: %5d\n" ncfn; printf "\n" let main () = let grdG_fwd = Array.make 2 0.0 in let grdG_bck = Array.make 2 0.0 in let grdG_cntr = Array.make 2 0.0 in let data = { p1 = 1.0; p2 = 2.0 } in let neq = 3 in let np = 2 in let np2 = 2*np in let t0 = 0.0 in let tf = 2.0 in let reltol = 1.0e-8 in let abstol = 1.0e-8 in let abstolQ = 1.0e-8 in let abstolB = 1.0e-8 in let abstolQB = 1.0e-8 in Initializations for forward problem let y = Nvector_serial.make neq one in let ydata = unwrap y in let yQ = Nvector_serial.make 1 zero in let yS = Array.init np (fun _ -> Nvector_serial.make neq zero) in let yQS = Array.init np (fun _ -> Nvector_serial.make 1 zero) in let m = Matrix.dense neq in let cvode_mem = Cvode.(init BDF (SStolerances (reltol, abstol)) ~lsolver:Dls.(solver (dense y m)) (f data) t0 y) in Quad.init cvode_mem (fQ data) yQ; Quad.set_tolerances cvode_mem (Quad.SStolerances (reltol, abstolQ)); Sens.(init cvode_mem EEtolerances (Simultaneous None) (AllAtOnce (Some (fS data))) yS); Sens.set_err_con cvode_mem true; QuadSens.init cvode_mem ~fqs:(fQS data) yQS; QuadSens.set_tolerances cvode_mem (QuadSens.EEtolerances); Initialize ASA let steps = 100 in Adj.init cvode_mem steps Adj.IPolynomial; printf "-------------------\n"; printf "Forward integration\n"; printf "-------------------\n\n"; let _, ncheck, _ = Adj.forward_normal cvode_mem tf y in ignore (Quad.get cvode_mem yQ); let g = ith (unwrap yQ) 1 in ignore (Sens.get cvode_mem yS); ignore (QuadSens.get cvode_mem yQS); printf "ncheck = %d\n" ncheck; printf "\n"; printf " y: %12.4e %12.4e %12.4e" (ith ydata 1) (ith ydata 2) (ith ydata 3); printf " G: %12.4e\n" (ith (unwrap yQ) 1); printf "\n"; printf " yS1: %12.4e %12.4e %12.4e\n" (ith (unwrap yS.(0)) 1) (ith (unwrap yS.(0)) 2) (ith (unwrap yS.(0)) 3); printf " yS2: %12.4e %12.4e %12.4e\n" (ith (unwrap yS.(1)) 1) (ith (unwrap yS.(1)) 2) (ith (unwrap yS.(1)) 3); printf "\n"; printf " dG/dp: %12.4e %12.4e\n" (ith (unwrap yQS.(0)) 1) (ith (unwrap yQS.(1)) 1); printf "\n"; printf "Final Statistics for forward pb.\n"; printf "--------------------------------\n"; print_fwd_stats cvode_mem; let yB1 = Nvector_serial.make (2 * neq) zero in let yQB1 = Nvector_serial.make np2 zero in let yB2 = Nvector_serial.make (2 * neq) zero in let yQB2 = Nvector_serial.make np2 zero in Create and initialize backward problems ( one for each column of the Hessian ) let m = Matrix.dense (2*neq) in let cvode_memB1 = Adj.(init_backward cvode_mem Cvode.BDF (SStolerances (reltol, abstolB)) ~lsolver:Dls.(solver (dense yB1 m)) (WithSens (fB1 data)) tf yB1) in QuadAdj.(init cvode_memB1 (WithSens (fQB1 data)) yQB1); QuadAdj.(set_tolerances cvode_memB1 (SStolerances (reltol, abstolQB))); let m = Matrix.dense (2*neq) in let cvode_memB2 = Adj.(init_backward cvode_mem Cvode.BDF (SStolerances (reltol, abstolB)) ~lsolver:Dls.(solver (dense yB2 m)) (WithSens (fB2 data)) tf yB2) in QuadAdj.(init cvode_memB2 (WithSens (fQB2 data)) yQB2); QuadAdj.(set_tolerances cvode_memB2 (SStolerances (reltol, abstolB))); printf "---------------------------------------------\n"; printf "Backward integration ... (2 adjoint problems)\n"; printf "---------------------------------------------\n\n"; Adj.backward_normal cvode_mem t0; ignore (Adj.get cvode_memB1 yB1); ignore (QuadAdj.get cvode_memB1 yQB1); ignore (Adj.get cvode_memB2 yB2); ignore (QuadAdj.get cvode_memB2 yQB2); printf " dG/dp: %12.4e %12.4e (from backward pb. 1)\n" (-.ith (unwrap yQB1) 1) (-.ith (unwrap yQB1) 2); printf " %12.4e %12.4e (from backward pb. 2)\n" (-.ith (unwrap yQB2) 1) (-.ith (unwrap yQB2) 2); printf "\n"; printf " H = d2G/dp2:\n"; printf " (1) (2)\n"; printf " %12.4e %12.4e\n" (-.ith (unwrap yQB1) 3) (-.ith (unwrap yQB2) 3); printf " %12.4e %12.4e\n" (-.ith (unwrap yQB1) 4) (-.ith (unwrap yQB2) 4); printf "\n"; printf "Final Statistics for backward pb. 1\n"; printf "-----------------------------------\n"; print_bck_stats cvode_memB1; printf "Final Statistics for backward pb. 2\n"; printf "-----------------------------------\n"; print_bck_stats cvode_memB2; let dp = 1.0e-2 in printf "-----------------------\n"; printf "Finite Difference tests\n"; printf "-----------------------\n\n"; printf "del_p = %g\n\n" dp; RealArray.fill (unwrap y) one; let m = Matrix.dense neq in let cvode_mem = Cvode.(init BDF (SStolerances (reltol, abstol)) ~lsolver:Dls.(solver (dense y m)) (f data) t0 y) in RealArray.fill (unwrap yQ) zero; Quad.init cvode_mem (fQ data) yQ; Quad.(set_tolerances cvode_mem (SStolerances (reltol, abstolQ))); data.p1 <- data.p1 +. dp; ignore (Cvode.solve_normal cvode_mem tf y); ignore (Quad.get cvode_mem yQ); let gp = ith (unwrap yQ) 1 in printf "p1+ y: %12.4e %12.4e %12.4e" (ith (unwrap y) 1) (ith (unwrap y) 2) (ith (unwrap y) 3); printf " G: %12.4e\n" (ith (unwrap yQ) 1); data.p1 <- data.p1 -. 2.0*.dp; RealArray.fill (unwrap y) one; RealArray.fill (unwrap yQ) zero; Cvode.reinit cvode_mem t0 y; Quad.reinit cvode_mem yQ; ignore (Cvode.solve_normal cvode_mem tf y); ignore (Quad.get cvode_mem yQ); let gm = ith (unwrap yQ) 1 in printf "p1- y: %12.4e %12.4e %12.4e" (ith (unwrap y) 1) (ith (unwrap y) 2) (ith (unwrap y) 3); printf " G: %12.4e\n" (ith (unwrap yQ) 1); data.p1 <- data.p1 +. dp; grdG_fwd.(0) <- (gp-.g)/.dp; grdG_bck.(0) <- (g-.gm)/.dp; grdG_cntr.(0) <- (gp-.gm)/.(2.0*.dp); let h11 = (gp -. 2.0*.g +. gm) /. (dp*.dp) in data.p2 <- data.p2 +. dp; RealArray.fill (unwrap y) one; RealArray.fill (unwrap yQ) zero; Cvode.reinit cvode_mem t0 y; Quad.reinit cvode_mem yQ; ignore (Cvode.solve_normal cvode_mem tf y); ignore (Quad.get cvode_mem yQ); let gp = ith (unwrap yQ) 1 in printf "p2+ y: %12.4e %12.4e %12.4e" (ith (unwrap y) 1) (ith (unwrap y) 2) (ith (unwrap y) 3); printf " G: %12.4e\n" (ith (unwrap yQ) 1); data.p2 <- data.p2 -. 2.0*.dp; RealArray.fill (unwrap y) one; RealArray.fill (unwrap yQ) zero; Cvode.reinit cvode_mem t0 y; Quad.reinit cvode_mem yQ; ignore (Cvode.solve_normal cvode_mem tf y); ignore (Quad.get cvode_mem yQ); let gm = ith (unwrap yQ) 1 in printf "p2- y: %12.4e %12.4e %12.4e" (ith (unwrap y) 1) (ith (unwrap y) 2) (ith (unwrap y) 3); printf " G: %12.4e\n" (ith (unwrap yQ) 1); data.p2 <- data.p2 +. dp; grdG_fwd.(1) <- (gp-.g)/.dp; grdG_bck.(1) <- (g-.gm)/.dp; grdG_cntr.(1) <- (gp-.gm)/.(2.0*.dp); let h22 = (gp -. 2.0*.g +. gm) /. (dp*.dp) in printf "\n"; printf " dG/dp: %12.4e %12.4e (fwd FD)\n" grdG_fwd.(0) grdG_fwd.(1); printf " %12.4e %12.4e (bck FD)\n" grdG_bck.(0) grdG_bck.(1); printf " %12.4e %12.4e (cntr FD)\n" grdG_cntr.(0) grdG_cntr.(1); printf "\n"; printf " H(1,1): %12.4e\n" h11; printf " H(2,2): %12.4e\n" h22 let reps = try int_of_string (Unix.getenv "NUM_REPS") with Not_found | Failure _ -> 1 let gc_at_end = try int_of_string (Unix.getenv "GC_AT_END") <> 0 with Not_found | Failure _ -> false let gc_each_rep = try int_of_string (Unix.getenv "GC_EACH_REP") <> 0 with Not_found | Failure _ -> false let _ = for _ = 1 to reps do main (); if gc_each_rep then Gc.compact () done; if gc_at_end then Gc.compact ()
e6fd7a5381f578d78f4e5488c268ab1936e59c344abe0d156efbd4df61a04c4d
Bike/sandalphon.lambda-list
parse.lisp
(in-package #:sandalphon.lambda-list) (defun parse-lambda-list (lambda-list grammar-spec &rest initargs &key (safe t)) "Given a lambda list, initargs for it, and a grammar specification, returns a LAMBDA-LIST object. A grammar specification is a list of clause specifications. A clause specification is either a class specifier, or a list (class-specifier &key). The grammar specification is simply based on clauses earlier in the list having to occur before clauses later in the list. All clauses are considered optional. The keys and values in the list are passed unevaluated to MAKE-INSTANCE. Certain keys have special meanings to the grammar itself. These are removed before they can be passed to MAKE-INSTANCE. They are as follows: * :DATA-DESTRUCTURE indicates that a dotted list indicates this kind of clause. E.g., in parsing (foo bar . baz), if there was a &rest clause in the grammar with :DATA-DESTRUCTURE, the result would be the same as from (foo bar &rest baz). * :ANYWHERE indicates that the position of this clause in the grammar is unimportant, and that this clause can be anywhere in the lambda list, except, for bad reasons, before the first clause. This is used for &environment clauses, which cannot be before &whole. The keys are arguments to the lambda-list and clause creation that are not part of the grammar. Presently the only one is SAFE, controlling whether extra code is inserted to ensure conforming code and more helpful error messages. EXAMPLE: A lambda-list like an ordinary lambda-list but with keys having :no-value as a default if no default is explicitly given would have the grammar specification (REGULAR-CLAUSE OPTIONAL-CLAUSE REST-CLAUSE (KEY-CLAUSE :DEFAULT-DEFAULT :NO-VALUE) AUX-CLAUSE)." (%parse-lambda-list lambda-list (apply #'make-grammar grammar-spec initargs) :safe safe)) (defgeneric clause-parse (clause list lambda-list) (:documentation "Parse an entire clause. Side-effect the results into CLAUSE, and return a list with the clause consumed. For example, given (&whole foo bar baz), the &whole clause parser would return (bar baz).")) (defgeneric multiple-clause-parse (clause spec lambda-list) (:documentation "Parse an individual specifier for a multiple-clause. The return format is particular to what the particular clause class expects.")) (defun grammar-clean-keywords (list) "Takes a plist of key/values, cleans out grammar specials, and returns something that should be fine for MAKE-INSTANCE and friends. Specials are presently :DATA-DESTRUCTURE, :ANYWHERE." ;; but it's easy to add any, at least for this function (let ((to-kill '(:data-destructure :anywhere))) (loop for (key value) on list by #'cddr when (find key to-kill) collect key into kws else collect key into clean and collect value into clean finally (return (values clean kws))))) (defun make-grammar (grammar-spec &rest more-keys &key (safe t)) "Takes a grammar specification and makes it into a fresh \"grammar\", which is an internal thing passed to %parse-lambda-list that is full of clauses subject to side effects. MORE-KEYS is a plist of initialization arguments to all clauses." (declare (ignore safe)) (loop with blank = nil with anywhere = nil with data-destructure = nil for thing in grammar-spec collecting (multiple-value-bind (class cleaned kws) (if (listp thing) (multiple-value-call #'values (first thing) (grammar-clean-keywords (rest thing))) (values thing nil nil)) (let ((obj (apply #'make-instance class (append cleaned more-keys)))) (when (find :data-destructure kws) (if data-destructure (error "grammar spec ~a has multiple clauses with ~a" grammar-spec :data-destructure) (setf data-destructure t))) (when (find :anywhere kws) (if anywhere (error "grammar spec ~a has multiple clauses with ~a" grammar-spec :anywhere) (setf anywhere t))) (when (null (clause-keywords obj)) (if blank (error "grammar spec ~a has multiple clauses with no keyword" grammar-spec) (setf blank t))) (list (clause-keywords obj) obj kws))))) (defun %parse-lambda-list (llist grammar &rest initargs &key (safe t)) (declare (ignore safe)) ;; grammar format = list of (ll-keywords object keywords) ;; keywords right now being :anywhere and :data-destructure (loop with ret = (apply #'make-instance 'lambda-list :clauses (mapcar #'second grammar) initargs) with last = nil with been-anywhere = nil with working = llist do (flet ((find-clause (kw) (loop for spec in grammar do (when (member kw (first spec)) (if (find :anywhere (third spec)) (if been-anywhere (error "Multiple ~a clauses" (first spec)) (progn ;; &environment can only be after & whole . silly . (when (null last) (setf last (first grammar))) (return spec))) (if (or (null last) ;; if this spec is after ;; the last spec. (find spec (rest (member last grammar)))) ;; we're in a proper position, ;; return the spec (return (setf last spec)) ;; fail (error "~a clause in wrong position" (first spec)))))))) (etypecase working (null (loop-finish)) (symbol (let ((dd (find :data-destructure grammar :key #'third :test #'find))) (cond ((not dd) (error "Improperly dotted lambda list")) ((not (find dd (rest (member last grammar)))) (error "Dot in lambda list not allowed in this position")) (t (setf working (clause-parse dd (list working) ret)) (loop-finish))))) ((cons null) (error "Can't name a parameter NIL")) ((cons symbol) (let ((spec (find-clause (first working)))) (if spec (setf working (clause-parse (second spec) working ret)) (let ((blank (find-clause nil))) (cond (blank (setf working (clause-parse (second blank) working ret))) (t (error "Parameter ~a outside of clause" (first working)))))))) ((cons t) ; a destructure, probably (let ((blank (find-clause nil))) (cond (blank (setf working (clause-parse (second blank) working ret))) (t (error "Parameter ~a outside of clause" (first working)))))))) finally (return ret))) ;;; What follows are the parse methods for standard clauses. (defun parse-destructure (clause llist grammar-name) "Helper function for destructuring parameters. Given a clause to take initargs from, something that's maybe a lambda list, and the name of a grammar, parses." (let ((safety (clause-safe clause))) (if (symbolp llist) llist (%parse-lambda-list llist (make-grammar (symbol-value grammar-name) :safe safety) :safe safety)))) (declaim (inline make-key)) (defun make-key (symbol) "For &key parsing." (intern (symbol-name symbol) "KEYWORD")) (defmethod clause-parse ((clause singleton-clause) list llist) FIXME better errors (let ((spec (second list))) (unless (symbolp spec) (error "~a parameter is not a symbol" (clause-keywords clause))) (setf (clause-spec clause) spec) (cddr list))) (defmethod clause-parse ((clause multiple-clause) list llist) (loop with specs = nil for list on list do (let* ((thing (first list)) (res (multiple-clause-parse clause thing llist))) (cond ((null res) ; thing is not part of this clause (setf (multiple-clause-specs clause) (nreverse specs)) (return list)) (t (push res specs)))) finally (setf (multiple-clause-specs clause) (nreverse specs)))) (defmethod clause-parse ((clause optional-clause) list llist) ;; skip &optional (call-next-method clause (rest list) llist)) (defmethod clause-parse ((clause destructuring-optional-clause) list llist) ;; skip &optional (call-next-method clause (rest list) llist)) (defmethod clause-parse ((clause key-clause) list llist) ;; special due to aok (when (eq (first list) '&allow-other-keys) (error "~a without ~a" '&allow-other-keys '&key)) (loop with specs = nil for list on (rest list) do (let* ((thing (first list)) (rest (rest list))) (when (eq thing '&allow-other-keys) (setf (key-clause-aok-p clause) t (multiple-clause-specs clause) (nreverse specs)) (return rest)) (let ((res (multiple-clause-parse clause thing llist))) (cond ((null res) (setf (multiple-clause-specs clause) (nreverse specs)) (return list)) (t (push res specs))))) finally (setf (multiple-clause-specs clause) (nreverse specs)))) (defmethod clause-parse ((clause destructuring-key-clause) list llist) ;; special due to aok (when (eq (first list) '&allow-other-keys) (error "~a without ~a" '&allow-other-keys '&key)) (loop with specs = nil for list on (rest list) do (let* ((thing (first list)) (rest (rest list))) (when (eq thing '&allow-other-keys) (setf (key-clause-aok-p clause) t (multiple-clause-specs clause) (nreverse specs)) (return rest)) (let ((res (multiple-clause-parse clause thing llist))) (cond ((null res) (setf (multiple-clause-specs clause) (nreverse (cons res specs))) (return list)) (t (push res specs))))) finally (setf (multiple-clause-specs clause) (nreverse specs)))) (defmethod clause-parse ((clause aux-clause) list llist) skip & aux (call-next-method clause (rest list) llist)) (defmethod multiple-clause-parse ((clause regular-clause) spec llist) (cond ((find spec (lambda-list-keywords llist)) nil) ((symbolp spec) spec) (t (error "~a is not a suitable parameter" spec)))) (defmethod multiple-clause-parse ((clause specialized-regular-clause) spec llist) (cond ((find spec (lambda-list-keywords llist)) nil) ((symbolp spec) (list spec 't)) ((and (consp spec) (consp (cdr spec)) (null (cddr spec))) spec) (t (error "~a is not a suitable parameter" spec)))) (defmethod multiple-clause-parse ((clause destructuring-regular-clause) spec llist) (cond ((not (symbolp spec)) (parse-destructure clause spec (destructuring-clause-grammar clause))) ((find spec (lambda-list-keywords llist)) nil) (t spec))) (defmethod multiple-clause-parse ((clause optional-clause) spec llist) (cond ((find spec (lambda-list-keywords llist)) nil) ((listp spec) (destructuring-bind (var &optional (default (clause-default-default clause)) -p) spec (unless (symbolp var) (error "~a is not a valid &optional parameter name" var)) (list var default -p))) ((symbolp spec) (list spec nil nil)) (t (error "~a is not a valid &optional spec" spec)))) (defmethod multiple-clause-parse ((clause destructuring-optional-clause) spec llist) (cond ((listp spec) (destructuring-bind (var &optional (default (clause-default-default clause)) -p) spec (list (parse-destructure clause var (destructuring-clause-grammar clause)) default -p))) ((not (symbolp spec)) (error "~a is not a valid &optional spec" spec)) ((find spec (lambda-list-keywords llist)) nil) (t (list spec (clause-default-default clause) nil)))) (defmethod multiple-clause-parse ((clause key-clause) spec llist) (cond ((find spec (lambda-list-keywords llist)) nil) ((symbolp spec) (list (list (make-key spec) spec) (clause-default-default clause) nil)) ((not (listp spec)) (error "~a is not a valid &key spec" spec)) ((listp (first spec)) (destructuring-bind ((key var) &optional (default (clause-default-default clause)) -p) spec (unless (symbolp var) (error "~a is not a valid &key name" var)) (list (list key var) default -p))) (t (destructuring-bind (var &optional (default (clause-default-default clause)) -p) spec (unless (symbolp var) (error "~a is not a valid &key name" var)) (list (list (make-key var) var) default -p))))) (defmethod multiple-clause-parse ((clause destructuring-key-clause) spec llist) (cond ((find spec (lambda-list-keywords llist)) nil) ((symbolp spec) (list (list (make-key spec) spec) (clause-default-default clause) nil)) ((not (listp spec)) (error "~a is not a valid &key spec" spec)) ((listp (first spec)) (destructuring-bind ((key var) &optional (default (clause-default-default clause)) -p) spec ;; this is the only case that can actually destructure. (list (list key (parse-destructure clause var (destructuring-clause-grammar clause)) default -p)))) (t (destructuring-bind (var &optional (default (clause-default-default clause)) -p) spec (list (list (make-key var) var) default -p))))) (defmethod multiple-clause-parse ((clause aux-clause) spec llist) (cond ((find spec (lambda-list-keywords llist)) nil) ((symbolp spec) (list spec (clause-default-default clause))) ((listp spec) (destructuring-bind (var &optional (default (clause-default-default clause))) spec (list var default))) (t (error "~a is not a valid ~a parameter spec" spec '&aux))))
null
https://raw.githubusercontent.com/Bike/sandalphon.lambda-list/db240cdcf2c066e220de0b49d441cecca941f1fb/parse.lisp
lisp
but it's easy to add any, at least for this function grammar format = list of (ll-keywords object keywords) keywords right now being :anywhere and :data-destructure &environment can only be after if this spec is after the last spec. we're in a proper position, return the spec fail a destructure, probably What follows are the parse methods for standard clauses. thing is not part of this clause skip &optional skip &optional special due to aok special due to aok this is the only case that can actually destructure.
(in-package #:sandalphon.lambda-list) (defun parse-lambda-list (lambda-list grammar-spec &rest initargs &key (safe t)) "Given a lambda list, initargs for it, and a grammar specification, returns a LAMBDA-LIST object. A grammar specification is a list of clause specifications. A clause specification is either a class specifier, or a list (class-specifier &key). The grammar specification is simply based on clauses earlier in the list having to occur before clauses later in the list. All clauses are considered optional. The keys and values in the list are passed unevaluated to MAKE-INSTANCE. Certain keys have special meanings to the grammar itself. These are removed before they can be passed to MAKE-INSTANCE. They are as follows: * :DATA-DESTRUCTURE indicates that a dotted list indicates this kind of clause. E.g., in parsing (foo bar . baz), if there was a &rest clause in the grammar with :DATA-DESTRUCTURE, the result would be the same as from (foo bar &rest baz). * :ANYWHERE indicates that the position of this clause in the grammar is unimportant, and that this clause can be anywhere in the lambda list, except, for bad reasons, before the first clause. This is used for &environment clauses, which cannot be before &whole. The keys are arguments to the lambda-list and clause creation that are not part of the grammar. Presently the only one is SAFE, controlling whether extra code is inserted to ensure conforming code and more helpful error messages. EXAMPLE: A lambda-list like an ordinary lambda-list but with keys having :no-value as a default if no default is explicitly given would have the grammar specification (REGULAR-CLAUSE OPTIONAL-CLAUSE REST-CLAUSE (KEY-CLAUSE :DEFAULT-DEFAULT :NO-VALUE) AUX-CLAUSE)." (%parse-lambda-list lambda-list (apply #'make-grammar grammar-spec initargs) :safe safe)) (defgeneric clause-parse (clause list lambda-list) (:documentation "Parse an entire clause. Side-effect the results into CLAUSE, and return a list with the clause consumed. For example, given (&whole foo bar baz), the &whole clause parser would return (bar baz).")) (defgeneric multiple-clause-parse (clause spec lambda-list) (:documentation "Parse an individual specifier for a multiple-clause. The return format is particular to what the particular clause class expects.")) (defun grammar-clean-keywords (list) "Takes a plist of key/values, cleans out grammar specials, and returns something that should be fine for MAKE-INSTANCE and friends. Specials are presently :DATA-DESTRUCTURE, :ANYWHERE." (let ((to-kill '(:data-destructure :anywhere))) (loop for (key value) on list by #'cddr when (find key to-kill) collect key into kws else collect key into clean and collect value into clean finally (return (values clean kws))))) (defun make-grammar (grammar-spec &rest more-keys &key (safe t)) "Takes a grammar specification and makes it into a fresh \"grammar\", which is an internal thing passed to %parse-lambda-list that is full of clauses subject to side effects. MORE-KEYS is a plist of initialization arguments to all clauses." (declare (ignore safe)) (loop with blank = nil with anywhere = nil with data-destructure = nil for thing in grammar-spec collecting (multiple-value-bind (class cleaned kws) (if (listp thing) (multiple-value-call #'values (first thing) (grammar-clean-keywords (rest thing))) (values thing nil nil)) (let ((obj (apply #'make-instance class (append cleaned more-keys)))) (when (find :data-destructure kws) (if data-destructure (error "grammar spec ~a has multiple clauses with ~a" grammar-spec :data-destructure) (setf data-destructure t))) (when (find :anywhere kws) (if anywhere (error "grammar spec ~a has multiple clauses with ~a" grammar-spec :anywhere) (setf anywhere t))) (when (null (clause-keywords obj)) (if blank (error "grammar spec ~a has multiple clauses with no keyword" grammar-spec) (setf blank t))) (list (clause-keywords obj) obj kws))))) (defun %parse-lambda-list (llist grammar &rest initargs &key (safe t)) (declare (ignore safe)) (loop with ret = (apply #'make-instance 'lambda-list :clauses (mapcar #'second grammar) initargs) with last = nil with been-anywhere = nil with working = llist do (flet ((find-clause (kw) (loop for spec in grammar do (when (member kw (first spec)) (if (find :anywhere (third spec)) (if been-anywhere (error "Multiple ~a clauses" (first spec)) (progn & whole . silly . (when (null last) (setf last (first grammar))) (return spec))) (if (or (null last) (find spec (rest (member last grammar)))) (return (setf last spec)) (error "~a clause in wrong position" (first spec)))))))) (etypecase working (null (loop-finish)) (symbol (let ((dd (find :data-destructure grammar :key #'third :test #'find))) (cond ((not dd) (error "Improperly dotted lambda list")) ((not (find dd (rest (member last grammar)))) (error "Dot in lambda list not allowed in this position")) (t (setf working (clause-parse dd (list working) ret)) (loop-finish))))) ((cons null) (error "Can't name a parameter NIL")) ((cons symbol) (let ((spec (find-clause (first working)))) (if spec (setf working (clause-parse (second spec) working ret)) (let ((blank (find-clause nil))) (cond (blank (setf working (clause-parse (second blank) working ret))) (t (error "Parameter ~a outside of clause" (first working)))))))) (let ((blank (find-clause nil))) (cond (blank (setf working (clause-parse (second blank) working ret))) (t (error "Parameter ~a outside of clause" (first working)))))))) finally (return ret))) (defun parse-destructure (clause llist grammar-name) "Helper function for destructuring parameters. Given a clause to take initargs from, something that's maybe a lambda list, and the name of a grammar, parses." (let ((safety (clause-safe clause))) (if (symbolp llist) llist (%parse-lambda-list llist (make-grammar (symbol-value grammar-name) :safe safety) :safe safety)))) (declaim (inline make-key)) (defun make-key (symbol) "For &key parsing." (intern (symbol-name symbol) "KEYWORD")) (defmethod clause-parse ((clause singleton-clause) list llist) FIXME better errors (let ((spec (second list))) (unless (symbolp spec) (error "~a parameter is not a symbol" (clause-keywords clause))) (setf (clause-spec clause) spec) (cddr list))) (defmethod clause-parse ((clause multiple-clause) list llist) (loop with specs = nil for list on list do (let* ((thing (first list)) (res (multiple-clause-parse clause thing llist))) (setf (multiple-clause-specs clause) (nreverse specs)) (return list)) (t (push res specs)))) finally (setf (multiple-clause-specs clause) (nreverse specs)))) (defmethod clause-parse ((clause optional-clause) list llist) (call-next-method clause (rest list) llist)) (defmethod clause-parse ((clause destructuring-optional-clause) list llist) (call-next-method clause (rest list) llist)) (defmethod clause-parse ((clause key-clause) list llist) (when (eq (first list) '&allow-other-keys) (error "~a without ~a" '&allow-other-keys '&key)) (loop with specs = nil for list on (rest list) do (let* ((thing (first list)) (rest (rest list))) (when (eq thing '&allow-other-keys) (setf (key-clause-aok-p clause) t (multiple-clause-specs clause) (nreverse specs)) (return rest)) (let ((res (multiple-clause-parse clause thing llist))) (cond ((null res) (setf (multiple-clause-specs clause) (nreverse specs)) (return list)) (t (push res specs))))) finally (setf (multiple-clause-specs clause) (nreverse specs)))) (defmethod clause-parse ((clause destructuring-key-clause) list llist) (when (eq (first list) '&allow-other-keys) (error "~a without ~a" '&allow-other-keys '&key)) (loop with specs = nil for list on (rest list) do (let* ((thing (first list)) (rest (rest list))) (when (eq thing '&allow-other-keys) (setf (key-clause-aok-p clause) t (multiple-clause-specs clause) (nreverse specs)) (return rest)) (let ((res (multiple-clause-parse clause thing llist))) (cond ((null res) (setf (multiple-clause-specs clause) (nreverse (cons res specs))) (return list)) (t (push res specs))))) finally (setf (multiple-clause-specs clause) (nreverse specs)))) (defmethod clause-parse ((clause aux-clause) list llist) skip & aux (call-next-method clause (rest list) llist)) (defmethod multiple-clause-parse ((clause regular-clause) spec llist) (cond ((find spec (lambda-list-keywords llist)) nil) ((symbolp spec) spec) (t (error "~a is not a suitable parameter" spec)))) (defmethod multiple-clause-parse ((clause specialized-regular-clause) spec llist) (cond ((find spec (lambda-list-keywords llist)) nil) ((symbolp spec) (list spec 't)) ((and (consp spec) (consp (cdr spec)) (null (cddr spec))) spec) (t (error "~a is not a suitable parameter" spec)))) (defmethod multiple-clause-parse ((clause destructuring-regular-clause) spec llist) (cond ((not (symbolp spec)) (parse-destructure clause spec (destructuring-clause-grammar clause))) ((find spec (lambda-list-keywords llist)) nil) (t spec))) (defmethod multiple-clause-parse ((clause optional-clause) spec llist) (cond ((find spec (lambda-list-keywords llist)) nil) ((listp spec) (destructuring-bind (var &optional (default (clause-default-default clause)) -p) spec (unless (symbolp var) (error "~a is not a valid &optional parameter name" var)) (list var default -p))) ((symbolp spec) (list spec nil nil)) (t (error "~a is not a valid &optional spec" spec)))) (defmethod multiple-clause-parse ((clause destructuring-optional-clause) spec llist) (cond ((listp spec) (destructuring-bind (var &optional (default (clause-default-default clause)) -p) spec (list (parse-destructure clause var (destructuring-clause-grammar clause)) default -p))) ((not (symbolp spec)) (error "~a is not a valid &optional spec" spec)) ((find spec (lambda-list-keywords llist)) nil) (t (list spec (clause-default-default clause) nil)))) (defmethod multiple-clause-parse ((clause key-clause) spec llist) (cond ((find spec (lambda-list-keywords llist)) nil) ((symbolp spec) (list (list (make-key spec) spec) (clause-default-default clause) nil)) ((not (listp spec)) (error "~a is not a valid &key spec" spec)) ((listp (first spec)) (destructuring-bind ((key var) &optional (default (clause-default-default clause)) -p) spec (unless (symbolp var) (error "~a is not a valid &key name" var)) (list (list key var) default -p))) (t (destructuring-bind (var &optional (default (clause-default-default clause)) -p) spec (unless (symbolp var) (error "~a is not a valid &key name" var)) (list (list (make-key var) var) default -p))))) (defmethod multiple-clause-parse ((clause destructuring-key-clause) spec llist) (cond ((find spec (lambda-list-keywords llist)) nil) ((symbolp spec) (list (list (make-key spec) spec) (clause-default-default clause) nil)) ((not (listp spec)) (error "~a is not a valid &key spec" spec)) ((listp (first spec)) (destructuring-bind ((key var) &optional (default (clause-default-default clause)) -p) spec (list (list key (parse-destructure clause var (destructuring-clause-grammar clause)) default -p)))) (t (destructuring-bind (var &optional (default (clause-default-default clause)) -p) spec (list (list (make-key var) var) default -p))))) (defmethod multiple-clause-parse ((clause aux-clause) spec llist) (cond ((find spec (lambda-list-keywords llist)) nil) ((symbolp spec) (list spec (clause-default-default clause))) ((listp spec) (destructuring-bind (var &optional (default (clause-default-default clause))) spec (list var default))) (t (error "~a is not a valid ~a parameter spec" spec '&aux))))
ef6ceeae936829d6358cd87c3b9624b2ee02f6e919df294f7118217b56dbd3b1
jgm/gitit
Cache.hs
# LANGUAGE CPP # Copyright ( C ) 2008 < > This program is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA Copyright (C) 2008 John MacFarlane <> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- Functions for maintaining user list and session state. -} module Network.Gitit.Cache ( expireCachedFile , lookupCache , cacheContents ) where import qualified Data.ByteString as B (ByteString, readFile, writeFile) import System.FilePath import System.Directory (doesFileExist, removeFile, createDirectoryIfMissing, getModificationTime) import Data.Time.Clock (UTCTime) #if MIN_VERSION_directory(1,2,0) #else import System.Time (ClockTime(..)) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) #endif import Network.Gitit.State import Network.Gitit.Types import Control.Monad import Control.Monad.Trans (liftIO) import Text.Pandoc.UTF8 (encodePath) | Expire a cached file , identified by its filename in the filestore . -- Returns () after deleting a file from the cache, fails if no cached file. expireCachedFile :: String -> GititServerPart () expireCachedFile file = do cfg <- getConfig let target = encodePath $ cacheDir cfg </> file exists <- liftIO $ doesFileExist target when exists $ liftIO $ liftIO $ removeFile target lookupCache :: String -> GititServerPart (Maybe (UTCTime, B.ByteString)) lookupCache file = do cfg <- getConfig let target = encodePath $ cacheDir cfg </> file exists <- liftIO $ doesFileExist target if exists then liftIO $ do #if MIN_VERSION_directory(1,2,0) modtime <- getModificationTime target #else TOD secs _ <- getModificationTime target let modtime = posixSecondsToUTCTime $ fromIntegral secs #endif contents <- B.readFile target return $ Just (modtime, contents) else return Nothing cacheContents :: String -> B.ByteString -> GititServerPart () cacheContents file contents = do cfg <- getConfig let target = encodePath $ cacheDir cfg </> file let targetDir = takeDirectory target liftIO $ do createDirectoryIfMissing True targetDir B.writeFile target contents
null
https://raw.githubusercontent.com/jgm/gitit/b83bb4cd0278e1248954d009dc7ab8e97a3a8190/src/Network/Gitit/Cache.hs
haskell
Functions for maintaining user list and session state. Returns () after deleting a file from the cache, fails if no cached file.
# LANGUAGE CPP # Copyright ( C ) 2008 < > This program is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA Copyright (C) 2008 John MacFarlane <> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} module Network.Gitit.Cache ( expireCachedFile , lookupCache , cacheContents ) where import qualified Data.ByteString as B (ByteString, readFile, writeFile) import System.FilePath import System.Directory (doesFileExist, removeFile, createDirectoryIfMissing, getModificationTime) import Data.Time.Clock (UTCTime) #if MIN_VERSION_directory(1,2,0) #else import System.Time (ClockTime(..)) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) #endif import Network.Gitit.State import Network.Gitit.Types import Control.Monad import Control.Monad.Trans (liftIO) import Text.Pandoc.UTF8 (encodePath) | Expire a cached file , identified by its filename in the filestore . expireCachedFile :: String -> GititServerPart () expireCachedFile file = do cfg <- getConfig let target = encodePath $ cacheDir cfg </> file exists <- liftIO $ doesFileExist target when exists $ liftIO $ liftIO $ removeFile target lookupCache :: String -> GititServerPart (Maybe (UTCTime, B.ByteString)) lookupCache file = do cfg <- getConfig let target = encodePath $ cacheDir cfg </> file exists <- liftIO $ doesFileExist target if exists then liftIO $ do #if MIN_VERSION_directory(1,2,0) modtime <- getModificationTime target #else TOD secs _ <- getModificationTime target let modtime = posixSecondsToUTCTime $ fromIntegral secs #endif contents <- B.readFile target return $ Just (modtime, contents) else return Nothing cacheContents :: String -> B.ByteString -> GititServerPart () cacheContents file contents = do cfg <- getConfig let target = encodePath $ cacheDir cfg </> file let targetDir = takeDirectory target liftIO $ do createDirectoryIfMissing True targetDir B.writeFile target contents
523bddb15cb0c27754729e0af89297761ad5f09453f9b196b020c71eb67a4a84
goblint/analyzer
myCheck.ml
open QCheck let shrink arb = BatOption.default Shrink.nil arb.shrink module Gen = struct let sequence (gens: 'a Gen.t list): 'a list Gen.t = let open Gen in let f gen acc = acc >>= (fun xs -> gen >|= (fun x -> x :: xs)) in List.fold_right f gens (return []) end module Iter = struct let of_gen ~n gen = QCheck.Gen.generate ~n gen |> Iter.of_list let of_arbitrary ~n arb = of_gen ~n (gen arb) end module Shrink = struct let sequence (shrinks: 'a Shrink.t list) (xs: 'a list) = let open QCheck.Iter in BatList.combine xs shrinks |> BatList.fold_lefti (fun acc i (x, shrink) -> let modify_ith y = BatList.modify_at i (fun _ -> y) xs in acc <+> (shrink x >|= modify_ith) ) empty end module Arbitrary = struct let int64: int64 arbitrary = (* -cube/qcheck/blob/e2c27723bbffd85b992355f91e2e2ba7dcd04f43/src/QCheck.ml#L330-L337 *) (* only divisions are fast enough *) let shrink x yield = let y = ref x in (* try some divisors *) while !y <> 0L do y := Int64.div !y 2L; yield !y; done; (* fast path *) () in set_shrink shrink int64 let big_int: Z.t arbitrary = let shrink x yield = let y = ref x in let two_big_int = Z.of_int 2 in while not (Z.equal !y Z.zero) do y := Z.ediv !y two_big_int; yield !y; done; () in set_print Z.to_string @@ set_shrink shrink @@ QCheck.map Z.of_int64 int64 let sequence (arbs: 'a arbitrary list): 'a list arbitrary = let gens = List.map gen arbs in let shrinks = List.map shrink arbs in make ~shrink:(Shrink.sequence shrinks) (Gen.sequence gens) open GoblintCil let varinfo: Cil.varinfo arbitrary = QCheck.always (Cil.makeGlobalVar "arbVar" Cil.voidPtrType) (* S TODO: how to generate this *) end
null
https://raw.githubusercontent.com/goblint/analyzer/69d12c316e89e66d10ad655cbc4e235e4d51bc69/src/domains/myCheck.ml
ocaml
-cube/qcheck/blob/e2c27723bbffd85b992355f91e2e2ba7dcd04f43/src/QCheck.ml#L330-L337 only divisions are fast enough try some divisors fast path S TODO: how to generate this
open QCheck let shrink arb = BatOption.default Shrink.nil arb.shrink module Gen = struct let sequence (gens: 'a Gen.t list): 'a list Gen.t = let open Gen in let f gen acc = acc >>= (fun xs -> gen >|= (fun x -> x :: xs)) in List.fold_right f gens (return []) end module Iter = struct let of_gen ~n gen = QCheck.Gen.generate ~n gen |> Iter.of_list let of_arbitrary ~n arb = of_gen ~n (gen arb) end module Shrink = struct let sequence (shrinks: 'a Shrink.t list) (xs: 'a list) = let open QCheck.Iter in BatList.combine xs shrinks |> BatList.fold_lefti (fun acc i (x, shrink) -> let modify_ith y = BatList.modify_at i (fun _ -> y) xs in acc <+> (shrink x >|= modify_ith) ) empty end module Arbitrary = struct let int64: int64 arbitrary = let shrink x yield = let y = ref x in () in set_shrink shrink int64 let big_int: Z.t arbitrary = let shrink x yield = let y = ref x in let two_big_int = Z.of_int 2 in while not (Z.equal !y Z.zero) do y := Z.ediv !y two_big_int; yield !y; done; () in set_print Z.to_string @@ set_shrink shrink @@ QCheck.map Z.of_int64 int64 let sequence (arbs: 'a arbitrary list): 'a list arbitrary = let gens = List.map gen arbs in let shrinks = List.map shrink arbs in make ~shrink:(Shrink.sequence shrinks) (Gen.sequence gens) open GoblintCil end
129c3c8b8de83dcddee0755aea07ed2569d03dd3170978dcc494fe9ff26b5923
alanz/ghc-exactprint
Utils2.hs
# LANGUAGE FlexibleInstances # # LANGUAGE StandaloneDeriving # module Utils2 where import Control.Applicative (Applicative(..)) import Control.Monad (when, liftM, ap) import Control.Exception import Data.Data import Data.List import Data.Maybe import Data.Monoid import Language . Haskell . GHC.ExactPrint . Utils import Language.Haskell.GHC.ExactPrint.Types hiding (showGhc) import qualified Bag as GHC import qualified BasicTypes as GHC import qualified BooleanFormula as GHC import qualified Class as GHC import qualified CoAxiom as GHC import qualified DynFlags as GHC import qualified FastString as GHC import qualified ForeignCall as GHC import qualified GHC as GHC import qualified GHC.Paths as GHC import qualified Lexer as GHC import qualified Name as GHC import qualified NameSet as GHC import qualified Outputable as GHC import qualified RdrName as GHC import qualified SrcLoc as GHC import qualified StringBuffer as GHC import qualified UniqSet as GHC import qualified Unique as GHC import qualified Var as GHC import qualified Data.Map as Map -- --------------------------------------------------------------------- instance AnnotateP GHC.RdrName where annotateP l n = do case rdrName2String n of "[]" -> do addDeltaAnnotation GHC.AnnOpenS -- '[' nonBUG addDeltaAnnotation GHC.AnnCloseS -- ']' BUG "()" -> do addDeltaAnnotation GHC.AnnOpenP -- '(' addDeltaAnnotation GHC.AnnCloseP -- ')' "(##)" -> do addDeltaAnnotation GHC.AnnOpen -- '(#' addDeltaAnnotation GHC.AnnClose -- '#)' "[::]" -> do addDeltaAnnotation GHC.AnnOpen -- '[:' addDeltaAnnotation GHC.AnnClose -- ':]' _ -> do addDeltaAnnotation GHC.AnnType addDeltaAnnotation GHC.AnnOpenP -- '(' addDeltaAnnotationLs GHC.AnnBackquote 0 addDeltaAnnotations GHC.AnnCommaTuple -- For '(,,,)' cnt <- countAnnsAP GHC.AnnVal cntT <- countAnnsAP GHC.AnnCommaTuple cntR <- countAnnsAP GHC.AnnRarrow case cnt of 0 -> if cntT >0 || cntR >0 then return () else addDeltaAnnotationExt l GHC.AnnVal 1 -> addDeltaAnnotation GHC.AnnVal x -> error $ "annotateP.RdrName: too many AnnVal :" ++ showGhc (l,x) addDeltaAnnotation GHC.AnnTildehsh addDeltaAnnotation GHC.AnnTilde addDeltaAnnotation GHC.AnnRarrow addDeltaAnnotationLs GHC.AnnBackquote 1 addDeltaAnnotation GHC.AnnCloseP -- ')' -- temporary, for test class (Typeable ast) => AnnotateP ast where annotateP :: GHC.SrcSpan -> ast -> IO () addDeltaAnnotation = undefined addDeltaAnnotations = undefined addDeltaAnnotationLs = undefined addDeltaAnnotationExt = undefined countAnnsAP = undefined showGhc = undefined rdrName2String = undefined
null
https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc710/Utils2.hs
haskell
--------------------------------------------------------------------- '[' nonBUG ']' BUG '(' ')' '(#' '#)' '[:' ':]' '(' For '(,,,)' ')' temporary, for test
# LANGUAGE FlexibleInstances # # LANGUAGE StandaloneDeriving # module Utils2 where import Control.Applicative (Applicative(..)) import Control.Monad (when, liftM, ap) import Control.Exception import Data.Data import Data.List import Data.Maybe import Data.Monoid import Language . Haskell . GHC.ExactPrint . Utils import Language.Haskell.GHC.ExactPrint.Types hiding (showGhc) import qualified Bag as GHC import qualified BasicTypes as GHC import qualified BooleanFormula as GHC import qualified Class as GHC import qualified CoAxiom as GHC import qualified DynFlags as GHC import qualified FastString as GHC import qualified ForeignCall as GHC import qualified GHC as GHC import qualified GHC.Paths as GHC import qualified Lexer as GHC import qualified Name as GHC import qualified NameSet as GHC import qualified Outputable as GHC import qualified RdrName as GHC import qualified SrcLoc as GHC import qualified StringBuffer as GHC import qualified UniqSet as GHC import qualified Unique as GHC import qualified Var as GHC import qualified Data.Map as Map instance AnnotateP GHC.RdrName where annotateP l n = do case rdrName2String n of "[]" -> do "()" -> do "(##)" -> do "[::]" -> do _ -> do addDeltaAnnotation GHC.AnnType addDeltaAnnotationLs GHC.AnnBackquote 0 cnt <- countAnnsAP GHC.AnnVal cntT <- countAnnsAP GHC.AnnCommaTuple cntR <- countAnnsAP GHC.AnnRarrow case cnt of 0 -> if cntT >0 || cntR >0 then return () else addDeltaAnnotationExt l GHC.AnnVal 1 -> addDeltaAnnotation GHC.AnnVal x -> error $ "annotateP.RdrName: too many AnnVal :" ++ showGhc (l,x) addDeltaAnnotation GHC.AnnTildehsh addDeltaAnnotation GHC.AnnTilde addDeltaAnnotation GHC.AnnRarrow addDeltaAnnotationLs GHC.AnnBackquote 1 class (Typeable ast) => AnnotateP ast where annotateP :: GHC.SrcSpan -> ast -> IO () addDeltaAnnotation = undefined addDeltaAnnotations = undefined addDeltaAnnotationLs = undefined addDeltaAnnotationExt = undefined countAnnsAP = undefined showGhc = undefined rdrName2String = undefined
aba10752ad61e54a4513a1f7176ea06d9f6e3d4c2db312811adda9cfe2b5ee4e
lambdaisland/harvest
walkthrough.clj
(ns notebooks.walkthrough (:require [lambdaisland.harvest :as h] [lambdaisland.faker :as faker :refer [fake]] [lambdaisland.harvest.xtdb :as harvest-xt] [xtdb.api :as xt])) ;; # 🧧 Factories for Fun and Profit. 恭喜發財 Harvest is a factory library for Clojure and ClojureScript , inspired by the likes of Factory Bot ( Ruby ) and Ex Machina ( Elixir ) , but with some unique ;; features that set it apart. In this walkthrough we'll build up your ;; understanding from bottom to top. The main entry point when using Harvest is the [ [ lambdaisland.harvest/build ] ] ;; function. Build takes a _template_ or _factory_, and optionally a map of ;; options. (h/build ["hello"]) ;; `build` returns a "result map", contained a _value_, and a map of _linked ;; entities_, which in this case is empty. We'll ignore linked entities for now, ;; and instead use the `build-val` function, which returns the value directly. (h/build-val ["hello"]) ;; The argument passed to `build`/`build-val` is a _template_. Any value is a ;; valid template, when a template gets built, the following rules are applied. ;; - functions are invoked (they should take no arguments) ;; - factories build the factory template ;; - Clojure collections are traversed and built recursively ;; - other values are preserved as-is (h/build-val {:number (partial rand-int 100)}) ;; ## 🏭 Factories ;; A _factory_ combines a template, an id (qualified symbol), and optionally ;; other things like traits and hooks. ;; Let's look at a simple factory for a user, with an `:id` and `:email`. We'll ;; also use `lambdaisland.faker` to make our factory more random, while still ;; generating realistic-looking data. Consult ;; the [supported_fakers.clj]() ;; to find the appropriate fakers for your use case. (def user ^{:type :harvest/factory} {:harvest.factory/id `user :harvest.factory/template {:user/id random-uuid :user/email #(fake [:internet :email])}}) (h/build-val user) ;; Factories must have a `:type :harvest/factory` metadata, and a fully qualified ;; `:harvest.factory/id`. We recommend using the `defactory` convenience macro to set ;; up your factories. (h/defactory user2 {:user/id random-uuid :user/email #(fake [:internet :email])}) (h/build-val user2) ;; When you use `defactory` it also becomes possible to treat your factories as functions, calling them does the same thing as passing them to `build-val`. (user2) # # 🔗 Associations ;; Let's look at a more complex example where we combine multiple factories. Say we are building a Educational Management System . (defn date-of-birth [] (let [over18-epoch-days (.toEpochDay (.minusYears (java.time.LocalDate/now) 18))] (java.time.LocalDate/ofEpochDay (- over18-epoch-days (rand-int 5000))))) ;; We'll have institutions (colleges or universities): (h/defactory institution {:institution/name #(fake [:educator :university])}) ;; And students: (h/defactory student {:student/name #(fake [:name :name]) :student/date-of-birth date-of-birth}) ;; Courses have a course name, a start and end time, and are taught at a ;; specific institution. Note how we simply reference the institution factory ;; here. (h/defactory course {:course/name #(fake [:educator :course-name]) :course/start-time #(fake [:time :date-time]) :course/end-time #(fake [:time :date-time]) :course/institution institution}) ;; Finally we allow students to enroll in courses. (h/defactory enrollment {:enrollment/student student :enrollment/course course}) ;; Now when you build an "enrollment", it follows the various associations, so ;; it generates a student, course, and institution as well. (enrollment) ;; So far hopefully this all hasn't been too surprising, what we've shown so far can be done with fairly little straightforward Clojure code . Now let 's look ;; at what actually sets these factories apart. There are two sets of features that make Harvest a valuable tool , one is ;; database support, the other is allowing fine-grained declarative mechanisms ;; for generating specific shapes of data. ;; Factories are typically used in combination with a database, so you can easily ;; insert some fixture data, which you can then leverage in your tests. Harvest currently has support for XTDB , Datomic Peer ( Free or Pro ) , and relational ;; databases through next.jdbc. ;; When setting up fixture data for tests you'll find that much of it is ;; boilerplate. You might need a user, profile, or tenant to satisfy some ;; constraints, but for the test at hand it really doesn't matter which specific ;; user, profile, or tenant it is. On the other hand some things very much do ;; matter. If you are testing that discounts on a shopping cart are calculated ;; correctly, then what's in the cart and the applied discount are essential ;; inputs to the test. ;; The idea with factories is that in your tests you specify exactly and only ;; the pieces of information that are relevant to the test, and let everything ;; else be provided by the factories. To help with this there are traits, hooks, ;; and selectors. ;; Let's look at these in turn: # # Database Support I 'll use XTDB here . Since it 's schema - on - read it requires the least setup for ;; demonstration. This starts an in - memory database : ^{:nextjournal.clerk/viewer nextjournal.clerk.viewer/hide-result} (def node (xt/start-node {})) Now we can use Harvest to populate it with data : (def result (harvest-xt/create! node enrollment)) This returns a Harvest result map , just like ` f / build ` , but notice how the ;; values now have a `:xt/id`. For each database we support there is a separate ;; `create!` function which takes an implementatation-specific reference to the ;; database and a factory/template. Any entities will be inserted, and if the ;; database assigns any default values, then you'll get those back as well. For ;; instance if you have an auto-increment key in a relational database, then ;; you'll see the assigned numbers in your result. Harvest has some helpers to find specific entities in the result . This uses ;; selectors which we'll discuss later. For now what you need to know is that ;; the factory itself functions as a selector that finds all entities built by ;; that factory. (h/sel result course) (h/sel result student) ;; Notice how this enrollment is no longer a nested map, but a flat structure with UUID references , since that 's how this structure gets represented in the ;; database. (h/sel result enrollment) ;; ## Traits
null
https://raw.githubusercontent.com/lambdaisland/harvest/74a6b6e31cef0cead4d7aa970b4ee9452013155b/notebooks/walkthrough.clj
clojure
# 🧧 Factories for Fun and Profit. 恭喜發財 features that set it apart. In this walkthrough we'll build up your understanding from bottom to top. function. Build takes a _template_ or _factory_, and optionally a map of options. `build` returns a "result map", contained a _value_, and a map of _linked entities_, which in this case is empty. We'll ignore linked entities for now, and instead use the `build-val` function, which returns the value directly. The argument passed to `build`/`build-val` is a _template_. Any value is a valid template, when a template gets built, the following rules are applied. - functions are invoked (they should take no arguments) - factories build the factory template - Clojure collections are traversed and built recursively - other values are preserved as-is ## 🏭 Factories A _factory_ combines a template, an id (qualified symbol), and optionally other things like traits and hooks. Let's look at a simple factory for a user, with an `:id` and `:email`. We'll also use `lambdaisland.faker` to make our factory more random, while still generating realistic-looking data. Consult the [supported_fakers.clj]() to find the appropriate fakers for your use case. Factories must have a `:type :harvest/factory` metadata, and a fully qualified `:harvest.factory/id`. We recommend using the `defactory` convenience macro to set up your factories. When you use `defactory` it also becomes possible to treat your factories as functions, calling them does the same thing as passing them to `build-val`. Let's look at a more complex example where we combine multiple factories. Say we We'll have institutions (colleges or universities): And students: Courses have a course name, a start and end time, and are taught at a specific institution. Note how we simply reference the institution factory here. Finally we allow students to enroll in courses. Now when you build an "enrollment", it follows the various associations, so it generates a student, course, and institution as well. So far hopefully this all hasn't been too surprising, what we've shown so far at what actually sets these factories apart. database support, the other is allowing fine-grained declarative mechanisms for generating specific shapes of data. Factories are typically used in combination with a database, so you can easily insert some fixture data, which you can then leverage in your tests. Harvest databases through next.jdbc. When setting up fixture data for tests you'll find that much of it is boilerplate. You might need a user, profile, or tenant to satisfy some constraints, but for the test at hand it really doesn't matter which specific user, profile, or tenant it is. On the other hand some things very much do matter. If you are testing that discounts on a shopping cart are calculated correctly, then what's in the cart and the applied discount are essential inputs to the test. The idea with factories is that in your tests you specify exactly and only the pieces of information that are relevant to the test, and let everything else be provided by the factories. To help with this there are traits, hooks, and selectors. Let's look at these in turn: demonstration. values now have a `:xt/id`. For each database we support there is a separate `create!` function which takes an implementatation-specific reference to the database and a factory/template. Any entities will be inserted, and if the database assigns any default values, then you'll get those back as well. For instance if you have an auto-increment key in a relational database, then you'll see the assigned numbers in your result. selectors which we'll discuss later. For now what you need to know is that the factory itself functions as a selector that finds all entities built by that factory. Notice how this enrollment is no longer a nested map, but a flat structure database. ## Traits
(ns notebooks.walkthrough (:require [lambdaisland.harvest :as h] [lambdaisland.faker :as faker :refer [fake]] [lambdaisland.harvest.xtdb :as harvest-xt] [xtdb.api :as xt])) Harvest is a factory library for Clojure and ClojureScript , inspired by the likes of Factory Bot ( Ruby ) and Ex Machina ( Elixir ) , but with some unique The main entry point when using Harvest is the [ [ lambdaisland.harvest/build ] ] (h/build ["hello"]) (h/build-val ["hello"]) (h/build-val {:number (partial rand-int 100)}) (def user ^{:type :harvest/factory} {:harvest.factory/id `user :harvest.factory/template {:user/id random-uuid :user/email #(fake [:internet :email])}}) (h/build-val user) (h/defactory user2 {:user/id random-uuid :user/email #(fake [:internet :email])}) (h/build-val user2) (user2) # # 🔗 Associations are building a Educational Management System . (defn date-of-birth [] (let [over18-epoch-days (.toEpochDay (.minusYears (java.time.LocalDate/now) 18))] (java.time.LocalDate/ofEpochDay (- over18-epoch-days (rand-int 5000))))) (h/defactory institution {:institution/name #(fake [:educator :university])}) (h/defactory student {:student/name #(fake [:name :name]) :student/date-of-birth date-of-birth}) (h/defactory course {:course/name #(fake [:educator :course-name]) :course/start-time #(fake [:time :date-time]) :course/end-time #(fake [:time :date-time]) :course/institution institution}) (h/defactory enrollment {:enrollment/student student :enrollment/course course}) (enrollment) can be done with fairly little straightforward Clojure code . Now let 's look There are two sets of features that make Harvest a valuable tool , one is currently has support for XTDB , Datomic Peer ( Free or Pro ) , and relational # # Database Support I 'll use XTDB here . Since it 's schema - on - read it requires the least setup for This starts an in - memory database : ^{:nextjournal.clerk/viewer nextjournal.clerk.viewer/hide-result} (def node (xt/start-node {})) Now we can use Harvest to populate it with data : (def result (harvest-xt/create! node enrollment)) This returns a Harvest result map , just like ` f / build ` , but notice how the Harvest has some helpers to find specific entities in the result . This uses (h/sel result course) (h/sel result student) with UUID references , since that 's how this structure gets represented in the (h/sel result enrollment)
4f7c4223c1932d1aa25881b3faccc6f151e7cb8c5b77b6d9c6c02752ecfb1d9e
wdebeaum/step
vague.lisp
;;;; ;;;; W::vague ;;;; (define-words :pos W::adj :templ CENTRAL-ADJ-TEMPL :words ( (W::vague (wordfeats (W::morph (:FORMS (-er -LY)))) (SENSES ((meta-data :origin cardiac :entry-date 20080508 :change-date nil :comments LM-vocab) (lf-parent ont::not-precise-val) ) ) ) ))
null
https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/vague.lisp
lisp
W::vague
(define-words :pos W::adj :templ CENTRAL-ADJ-TEMPL :words ( (W::vague (wordfeats (W::morph (:FORMS (-er -LY)))) (SENSES ((meta-data :origin cardiac :entry-date 20080508 :change-date nil :comments LM-vocab) (lf-parent ont::not-precise-val) ) ) ) ))
3cb0287cb3a0a610f2501f1944f2529b3ff98005e39dd9b0efecaeecea02aa69
janestreet/universe
expert1.mli
(** A module internal to Incremental. Users should see {!Incremental_intf}. This module is almost the external interface of the [Expert], but defunctorized, so it's easier to use from the inside of incremental. *) module Dependency : sig type 'a t [@@deriving sexp_of] val create : ?on_change:('a -> unit) -> 'a Node.t -> 'a t val value : 'a t -> 'a end module Node : sig type 'a t [@@deriving sexp_of] val create : State.t -> ?on_observability_change:(is_now_observable:bool -> unit) -> (unit -> 'a) -> 'a t val watch : 'a t -> 'a Node.t val make_stale : _ t -> unit val invalidate : _ t -> unit val add_dependency : _ t -> _ Dependency.t -> unit val remove_dependency : _ t -> _ Dependency.t -> unit end
null
https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/incremental/src/expert1.mli
ocaml
* A module internal to Incremental. Users should see {!Incremental_intf}. This module is almost the external interface of the [Expert], but defunctorized, so it's easier to use from the inside of incremental.
module Dependency : sig type 'a t [@@deriving sexp_of] val create : ?on_change:('a -> unit) -> 'a Node.t -> 'a t val value : 'a t -> 'a end module Node : sig type 'a t [@@deriving sexp_of] val create : State.t -> ?on_observability_change:(is_now_observable:bool -> unit) -> (unit -> 'a) -> 'a t val watch : 'a t -> 'a Node.t val make_stale : _ t -> unit val invalidate : _ t -> unit val add_dependency : _ t -> _ Dependency.t -> unit val remove_dependency : _ t -> _ Dependency.t -> unit end
d0737bf4a91202af34b5c7297a8540d89153656ab49b87bb254dfed43fb9f487
walkie/academic-webpage
Main.hs
module Main where import System.Environment (getArgs,withArgs) import Hakyll import WebPage.Generate import WebPage.Generate.Marburg main = do args <- getArgs case args of "marburg" : as -> withArgs as (hakyllWith marburgConfig marburgRules) _ -> hakyllWith config rules
null
https://raw.githubusercontent.com/walkie/academic-webpage/4c86e5d5c1559cde08440427fa39bab7d91e765d/haskell/Main.hs
haskell
module Main where import System.Environment (getArgs,withArgs) import Hakyll import WebPage.Generate import WebPage.Generate.Marburg main = do args <- getArgs case args of "marburg" : as -> withArgs as (hakyllWith marburgConfig marburgRules) _ -> hakyllWith config rules
8272404502a6be8ccbbd7b1dc073074d4b038f32b37dea84e060455a1a97fae0
namin/inc
tests-1.7-req.scm
(add-tests-with-string-output "procedures" [(letrec () 12) => "12\n"] [(letrec () (let ([x 5]) (fx+ x x))) => "10\n"] [(letrec ([f (lambda () 5)]) 7) => "7\n"] [(letrec ([f (lambda () 5)]) (let ([x 12]) x)) => "12\n"] [(letrec ([f (lambda () 5)]) (f)) => "5\n"] [(letrec ([f (lambda () 5)]) (let ([x (f)]) x)) => "5\n"] [(letrec ([f (lambda () 5)]) (fx+ (f) 6)) => "11\n"] [(letrec ([f (lambda () 5)]) (fx+ 6 (f))) => "11\n"] [(letrec ([f (lambda () 5)]) (fx- 20 (f))) => "15\n"] [(letrec ([f (lambda () 5)]) (fx+ (f) (f))) => "10\n"] [(letrec ([f (lambda () (fx+ 5 7))] [g (lambda () 13)]) (fx+ (f) (g))) => "25\n"] [(letrec ([f (lambda (x) (fx+ x 12))]) (f 13)) => "25\n"] [(letrec ([f (lambda (x) (fx+ x 12))]) (f (f 10))) => "34\n"] [(letrec ([f (lambda (x) (fx+ x 12))]) (f (f (f 0)))) => "36\n"] [(letrec ([f (lambda (x y) (fx+ x y))] [g (lambda (x) (fx+ x 12))]) (f 16 (f (g 0) (fx+ 1 (g 0))))) => "41\n"] [(letrec ([f (lambda (x) (g x x))] [g (lambda (x y) (fx+ x y))]) (f 12)) => "24\n"] [(letrec ([f (lambda (x) (if (fxzero? x) 1 (fx* x (f (fxsub1 x)))))]) (f 5)) => "120\n"] [(letrec ([f (lambda (x acc) (if (fxzero? x) acc (f (fxsub1 x) (fx* acc x))))]) (f 5 1)) => "120\n"] [(letrec ([f (lambda (x) (if (fxzero? x) 0 (fx+ 1 (f (fxsub1 x)))))]) (f 200)) => "200\n"] ) (add-tests-with-string-output "more stack" [(letrec ([f (lambda (n) (if (fxzero? n) 0 (fx+ 1 (f (fxsub1 n)))))]) (f 500)) => "500\n"])
null
https://raw.githubusercontent.com/namin/inc/3f683935e290848485f8d4d165a4f727f6658d1d/src/tests-1.7-req.scm
scheme
(add-tests-with-string-output "procedures" [(letrec () 12) => "12\n"] [(letrec () (let ([x 5]) (fx+ x x))) => "10\n"] [(letrec ([f (lambda () 5)]) 7) => "7\n"] [(letrec ([f (lambda () 5)]) (let ([x 12]) x)) => "12\n"] [(letrec ([f (lambda () 5)]) (f)) => "5\n"] [(letrec ([f (lambda () 5)]) (let ([x (f)]) x)) => "5\n"] [(letrec ([f (lambda () 5)]) (fx+ (f) 6)) => "11\n"] [(letrec ([f (lambda () 5)]) (fx+ 6 (f))) => "11\n"] [(letrec ([f (lambda () 5)]) (fx- 20 (f))) => "15\n"] [(letrec ([f (lambda () 5)]) (fx+ (f) (f))) => "10\n"] [(letrec ([f (lambda () (fx+ 5 7))] [g (lambda () 13)]) (fx+ (f) (g))) => "25\n"] [(letrec ([f (lambda (x) (fx+ x 12))]) (f 13)) => "25\n"] [(letrec ([f (lambda (x) (fx+ x 12))]) (f (f 10))) => "34\n"] [(letrec ([f (lambda (x) (fx+ x 12))]) (f (f (f 0)))) => "36\n"] [(letrec ([f (lambda (x y) (fx+ x y))] [g (lambda (x) (fx+ x 12))]) (f 16 (f (g 0) (fx+ 1 (g 0))))) => "41\n"] [(letrec ([f (lambda (x) (g x x))] [g (lambda (x y) (fx+ x y))]) (f 12)) => "24\n"] [(letrec ([f (lambda (x) (if (fxzero? x) 1 (fx* x (f (fxsub1 x)))))]) (f 5)) => "120\n"] [(letrec ([f (lambda (x acc) (if (fxzero? x) acc (f (fxsub1 x) (fx* acc x))))]) (f 5 1)) => "120\n"] [(letrec ([f (lambda (x) (if (fxzero? x) 0 (fx+ 1 (f (fxsub1 x)))))]) (f 200)) => "200\n"] ) (add-tests-with-string-output "more stack" [(letrec ([f (lambda (n) (if (fxzero? n) 0 (fx+ 1 (f (fxsub1 n)))))]) (f 500)) => "500\n"])
a0b3369bdff25d73056766b1cc2397ca9378f9e06627e9532f2056e0830fe6b5
Bogdanp/racket-gui-extra
ffi.rkt
#lang racket/base (require ffi/unsafe ffi/unsafe/atomic ffi/unsafe/nsalloc ffi/unsafe/nsstring ffi/unsafe/objc mred/private/lock mred/private/wx/cocoa/types (only-in mred/private/wx/cocoa/utils as-objc-allocation as-objc-allocation-with-retain ->wxb ->wx)) (provide (all-from-out ffi/unsafe ffi/unsafe/atomic ffi/unsafe/nsalloc ffi/unsafe/nsstring ffi/unsafe/objc mred/private/lock mred/private/wx/cocoa/types) as-objc-allocation as-objc-allocation-with-retain ->wxb ->wx (all-defined-out)) (define _CGFloat (make-ctype _double (λ (v) (if (and (number? v) (exact? v)) (exact->inexact v) v)) #f)) (define-cstruct _NSPoint ([x _CGFloat] [y _CGFloat])) (define-cstruct _NSSize ([width _CGFloat] [height _CGFloat])) (define-cstruct _NSRect ([origin _NSPoint] [size _NSSize]))
null
https://raw.githubusercontent.com/Bogdanp/racket-gui-extra/0760650cc1968db396e175c042e97ca597927739/gui-extra-lib/gui/extra/private/cocoa/ffi.rkt
racket
#lang racket/base (require ffi/unsafe ffi/unsafe/atomic ffi/unsafe/nsalloc ffi/unsafe/nsstring ffi/unsafe/objc mred/private/lock mred/private/wx/cocoa/types (only-in mred/private/wx/cocoa/utils as-objc-allocation as-objc-allocation-with-retain ->wxb ->wx)) (provide (all-from-out ffi/unsafe ffi/unsafe/atomic ffi/unsafe/nsalloc ffi/unsafe/nsstring ffi/unsafe/objc mred/private/lock mred/private/wx/cocoa/types) as-objc-allocation as-objc-allocation-with-retain ->wxb ->wx (all-defined-out)) (define _CGFloat (make-ctype _double (λ (v) (if (and (number? v) (exact? v)) (exact->inexact v) v)) #f)) (define-cstruct _NSPoint ([x _CGFloat] [y _CGFloat])) (define-cstruct _NSSize ([width _CGFloat] [height _CGFloat])) (define-cstruct _NSRect ([origin _NSPoint] [size _NSSize]))
4af3b123e6001eac6470d93ec026ab076a9cddaeeb678e2c186bed398817f34f
mstksg/functor-combinators
Tensor.hs
# OPTIONS_GHC -Wno - orphans # -- | -- Module : Data.HBifunctor.Tensor Copyright : ( c ) 2019 -- License : BSD3 -- Maintainer : -- Stability : experimental -- Portability : non-portable -- -- This module provides tools for working with binary functor combinators. -- " Data . Functor . HFunctor " deals with /single/ functor combinators -- (transforming a single functor). This module provides tools for working with combinators that combine and mix two functors " together " . -- -- The binary analog of 'HFunctor' is 'HBifunctor': we can map -- a structure-transforming function over both of the transformed functors. -- -- 'Tensor' gives some extra properties of your binary functor combinator: -- associativity and identity (see docs for 'Tensor' for more details). -- The binary analog of ' Interpret ' is ' ' . If your combinator @t@ and target functor is an instance of @'MonoidIn ' t f@ , it means you -- can "interpret" out of your tensored values, and also "generate" values of @f@. -- -- @ -- 'biretract' :: (f ':+:' f) a -> f a -- 'pureT' :: 'V1' a -> f a -- -- biretract :: 'Plus' f => (f ':*:' f) a -> f a -- pureT :: Plus f => 'Proxy' a -> f a -- biretract : : ' Applicative ' f = > ' Day ' f f a - > f a -- pureT :: Applicative f => 'Identity' a -> f a -- -- biretract :: 'Monad' f => 'Comp' f f a -> f a -- pureT :: Monad f => 'Identity' a -> f a -- @ -- module Data.HBifunctor.Tensor ( -- * 'Tensor' Tensor(..) , rightIdentity , leftIdentity , sumLeftIdentity , sumRightIdentity , prodLeftIdentity , prodRightIdentity * ' ' , MonoidIn(..) , nilLB , consLB , unconsLB , retractLB , interpretLB -- ** Utility , inL , inR , outL , outR , prodOutL , prodOutR , WrapF(..) , WrapLB(..) -- * 'Matchable' , Matchable(..) , splittingNE , matchingLB ) where import Control.Applicative.Free import Control.Applicative.ListF import Control.Applicative.Step import Control.Monad.Freer.Church import Control.Monad.Trans.Compose import Control.Natural import Control.Natural.IsoF import Data.Bifunctor import Data.Coerce import Data.Data import Data.Function import Data.Functor.Apply.Free import Data.Functor.Bind import Data.Functor.Classes import Data.Functor.Contravariant import Data.Functor.Contravariant.Conclude import Data.Functor.Contravariant.Decide import Data.Functor.Contravariant.Divise import Data.Functor.Contravariant.Divisible import Data.Functor.Contravariant.Divisible.Free import Data.Functor.Contravariant.Night (Night(..), Not(..)) import Data.Functor.Day (Day(..)) import Data.Functor.Identity import Data.Functor.Invariant import Data.Functor.Invariant.Internative import Data.Functor.Invariant.Inplicative import Data.Functor.Plus import Data.Functor.Product import Data.Functor.Sum import Data.Functor.These import Data.HBifunctor import Data.HBifunctor.Associative import Data.HBifunctor.Tensor.Internal import Data.HFunctor import Data.HFunctor.Chain.Internal import Data.HFunctor.Internal import Data.HFunctor.Interpret import Data.List.NonEmpty (NonEmpty(..)) import Data.Void import GHC.Generics import qualified Data.Bifunctor.Assoc as B import qualified Data.Functor.Contravariant.Coyoneda as CCY import qualified Data.Functor.Contravariant.Day as CD import qualified Data.Functor.Contravariant.Night as N import qualified Data.Functor.Day as D import qualified Data.Functor.Invariant.Day as ID import qualified Data.Functor.Invariant.Night as IN import qualified Data.Map.NonEmpty as NEM | @f@ is isomorphic to @t f i@ : that is , @i@ is the identity of @t@ , and leaves unchanged . rightIdentity :: (Tensor t i, FunctorBy t f) => f <~> t f i rightIdentity = isoF intro1 elim1 | @g@ is isomorphic to @t i : that is , @i@ is the identity of @t@ , and leaves unchanged . leftIdentity :: (Tensor t i, FunctorBy t g) => g <~> t i g leftIdentity = isoF intro2 elim2 | ' leftIdentity ' ( ' intro1 ' and ' ' ) for ' : + : ' actually does not -- require 'Functor'. This is the more general version. sumLeftIdentity :: f <~> V1 :+: f sumLeftIdentity = isoF R1 (absurd1 !+! id) | ' rightIdentity ' ( ' intro2 ' and ' ' ) for ' : + : ' actually does not -- require 'Functor'. This is the more general version. sumRightIdentity :: f <~> f :+: V1 sumRightIdentity = isoF L1 (id !+! absurd1) | ' leftIdentity ' ( ' intro1 ' and ' ' ) for ' :* : ' actually does not -- require 'Functor'. This is the more general version. prodLeftIdentity :: f <~> Proxy :*: f prodLeftIdentity = isoF (Proxy :*:) (\case _ :*: y -> y) | ' rightIdentity ' ( ' intro2 ' and ' ' ) for ' :* : ' actually does not -- require 'Functor'. This is the more general version. prodRightIdentity :: g <~> g :*: Proxy prodRightIdentity = isoF (:*: Proxy) (\case x :*: _ -> x) -- | A poly-kinded version of 'outL' for ':*:'. prodOutL :: f :*: g ~> f prodOutL (x :*: _) = x -- | A poly-kinded version of 'outR' for ':*:'. prodOutR :: f :*: g ~> g prodOutR (_ :*: y) = y | This class effectively gives us a way to generate a value of @f a@ based on an @i a@ , for @'Tensor ' t Having this ability makes a lot -- of interesting functions possible when used with 'biretract' from -- 'SemigroupIn' that weren't possible without it: it gives us a "base -- case" for recursion in a lot of cases. -- -- Essentially, we get an @i ~> f@, 'pureT', where we can introduce an @f -- a@ as long as we have an @i a@. -- -- Formally, if we have @'Tensor' t i@, we are enriching the category of -- endofunctors with monoid structure, turning it into a monoidal category. -- Different choices of @t@ give different monoidal categories. -- A functor is known as a " monoid in the ( monoidal ) category -- of endofunctors on @t@" if we can 'biretract': -- -- @ -- t f f ~> f -- @ -- -- and also 'pureT': -- -- @ -- i ~> f -- @ -- -- This gives us a few interesting results in category theory, which you -- can stil reading about if you don't care: -- -- * /All/ functors are monoids in the monoidal category -- on ':+:' -- * The class of functors that are monoids in the monoidal -- category on ':*:' is exactly the functors that are instances of ' Plus ' . -- * The class of functors that are monoids in the monoidal category on ' Day ' is exactly the functors that are instances of ' Applicative ' . -- * The class of functors that are monoids in the monoidal -- category on 'Comp' is exactly the functors that are instances of ' ' . -- -- This is the meaning behind the common adage, "monads are just monoids -- in the category of endofunctors". It means that if you enrich the -- category of endofunctors to be monoidal with 'Comp', then the class -- of functors that are monoids in that monoidal category are exactly -- what monads are. However, the adage is a little misleading: there -- are many other ways to enrich the category of endofunctors to be -- monoidal, and 'Comp' is just one of them. Similarly, the class of -- functors that are monoids in the category of endofunctors enriched by -- 'Day' are 'Applicative'. -- -- Note that instances of this class are /intended/ to be written with @t@ and @i@ to be fixed type constructors , and to be allowed to vary -- freely: -- -- @ instance = > MonoidIn Comp Identity f -- @ -- -- Any other sort of instance and it's easy to run into problems with type -- inference. If you want to write an instance that's "polymorphic" on tensor choice , use the ' WrapHBF ' and ' WrapF ' newtype wrappers over type variables , where the third argument also uses a type constructor : -- -- @ instance ( WrapHBF t ) ( WrapF i ) ( MyFunctor t i ) -- @ -- -- This will prevent problems with overloaded instances. class (Tensor t i, SemigroupIn t f) => MonoidIn t i f where | If we have an @i@ , we can generate an @f@ based on how it interacts with -- Specialized ( and simplified ) , this type is : -- -- @ -- 'pureT' \@'Day' :: 'Applicative' f => 'Identity' a -> f a -- 'pure' pureT \@'Comp ' : : ' Monad ' f = > Identity a - > f a -- ' return ' -- pureT \@(':*:') :: 'Plus' f => 'Proxy' a -> f a -- 'zero' -- @ -- -- Note that because @t@ appears nowhere in the input or output types, -- you must always use this with explicit type application syntax (like @pureT \@Day@ ) -- Along with ' biretract ' , this function makes @f@ a monoid in the category of endofunctors with respect to tensor pureT :: i ~> f default pureT :: Interpret (ListBy t) f => i ~> f pureT = retract . reviewF (splittingLB @t) . L1 -- | An implementation of 'retract' that works for any instance of @'MonoidIn ' t i@ for @'ListBy ' t@. -- Can be useful as a default implementation if you already have ' ' -- implemented. retractLB :: forall t i f. MonoidIn t i f => ListBy t f ~> f retractLB = (pureT @t !*! biretract @t . hright (retractLB @t)) . unconsLB @t -- | An implementation of 'interpret' that works for any instance of @'MonoidIn ' t i@ for @'ListBy ' t@. -- Can be useful as a default implementation if you already have ' ' -- implemented. interpretLB :: forall t i g f. MonoidIn t i f => (g ~> f) -> ListBy t g ~> f interpretLB f = retractLB @t . hmap f | Convenient wrapper over ' intro1 ' that lets us introduce an arbitrary functor @g@ to the right of an @f@. -- -- You can think of this as an 'HBifunctor' analogue of 'inject'. inL :: forall t i f g. MonoidIn t i g => f ~> t f g inL = hright (pureT @t) . intro1 -- | Convenient wrapper over 'intro2' that lets us introduce an arbitrary functor to the right of a @g@. -- -- You can think of this as an 'HBifunctor' analogue of 'inject'. inR :: forall t i f g. MonoidIn t i f => g ~> t f g inR = hleft (pureT @t) . intro2 | Convenient wrapper over ' ' that lets us drop one of the arguments -- of a 'Tensor' for free, without requiring any extra constraints (like -- for 'binterpret'). -- -- See 'prodOutL' for a version that does not require @'Functor' f@, -- specifically for ':*:'. outL :: (Tensor t Proxy, FunctorBy t f) => t f g ~> f outL = elim1 . hright absorb | Convenient wrapper over ' ' that lets us drop one of the arguments -- of a 'Tensor' for free, without requiring any constraints (like for -- 'binterpret'). -- See ' prodOutR ' for a version that does not require @'Functor ' , -- specifically for ':*:'. outR :: (Tensor t Proxy, FunctorBy t g) => t f g ~> g outR = elim2 . hleft absorb | For some @t@ , we have the ability to " statically analyze " the @'ListBy ' t@ -- and pattern match and manipulate the structure without ever -- interpreting or retracting. These are 'Matchable'. class Tensor t i => Matchable t i where | The inverse of ' splitNE ' . A consing of to @'ListBy ' t f@ is non - empty , so it can be represented as an @'NonEmptyBy ' t f@. -- -- This is analogous to a function @'uncurry' ('Data.List.NonEmpty.:|') : : ( a , [ a ] ) - > ' Data . List . NonEmpty . NonEmpty ' a@. unsplitNE :: FunctorBy t f => t f (ListBy t f) ~> NonEmptyBy t f | " Pattern match " on an @'ListBy ' t f@ : it is either empty , or it is non - empty ( and so can be an @'NonEmptyBy ' t f@ ) . -- This is analgous to a function @'Data . List . NonEmpty.nonEmpty ' : : [ a ] - > Maybe ( ' Data . List . NonEmpty . NonEmpty ' a)@. -- -- Note that because @t@ cannot be inferred from the input or output -- type, you should use this with /-XTypeApplications/: -- -- @ -- 'matchLB' \@'Day' :: 'Ap' f a -> ('Identity' :+: 'Ap1' f) a -- @ -- -- Note that you can recursively "unroll" a 'ListBy' completely into -- a 'Data.HFunctor.Chain.Chain' by using -- 'Data.HFunctor.Chain.unrollLB'. matchLB :: FunctorBy t f => ListBy t f ~> i :+: NonEmptyBy t f | An @'NonEmptyBy ' t f@ is isomorphic to an consed with an @'ListBy ' t f@ , like how a @'Data . List . NonEmpty . NonEmpty ' a@ is isomorphic to @(a , [ a])@. splittingNE :: (Matchable t i, FunctorBy t f) => NonEmptyBy t f <~> t f (ListBy t f) splittingNE = isoF splitNE unsplitNE | An @'ListBy ' t f@ is isomorphic to either the empty case ( @i@ ) or the non - empty case ( @'NonEmptyBy ' t f@ ) , like how @[a]@ is isomorphic to @'Maybe ' ( ' Data . List . NonEmpty . NonEmpty ' a)@. matchingLB :: forall t i f. (Matchable t i, FunctorBy t f) => ListBy t f <~> i :+: NonEmptyBy t f matchingLB = isoF (matchLB @t) (nilLB @t !*! fromNE @t) instance Tensor (:*:) Proxy where type ListBy (:*:) = ListF intro1 = (:*: Proxy) intro2 = (Proxy :*:) elim1 (x :*: ~Proxy) = x elim2 (~Proxy :*: y ) = y appendLB (ListF xs :*: ListF ys) = ListF (xs ++ ys) splitNE = nonEmptyProd splittingLB = isoF to_ from_ where to_ = \case ListF [] -> L1 Proxy ListF (x:xs) -> R1 (x :*: ListF xs) from_ = \case L1 ~Proxy -> ListF [] R1 (x :*: ListF xs) -> ListF (x:xs) toListBy (x :*: y) = ListF [x, y] -- | Instances of 'Plus' are monoids in the monoidal category on -- ':*:'. instance Plus f => MonoidIn (:*:) Proxy f where pureT _ = zero instance Tensor Product Proxy where type ListBy Product = ListF intro1 = (`Pair` Proxy) intro2 = (Proxy `Pair`) elim1 (Pair x ~Proxy) = x elim2 (Pair ~Proxy y) = y appendLB (ListF xs `Pair` ListF ys) = ListF (xs ++ ys) splitNE = viewF prodProd . nonEmptyProd splittingLB = isoF to_ from_ where to_ = \case ListF [] -> L1 Proxy ListF (x:xs) -> R1 (x `Pair` ListF xs) from_ = \case L1 ~Proxy -> ListF [] R1 (x `Pair` ListF xs) -> ListF (x:xs) toListBy (Pair x y) = ListF [x, y] -- | Instances of 'Plus' are monoids in the monoidal category on -- 'Product'. instance Plus f => MonoidIn Product Proxy f where pureT _ = zero instance Tensor Day Identity where type ListBy Day = Ap intro1 = D.intro2 intro2 = D.intro1 elim1 = D.elim2 elim2 = D.elim1 appendLB (Day x y z) = z <$> x <*> y splitNE = ap1Day splittingLB = isoF to_ from_ where to_ = \case Pure x -> L1 (Identity x) Ap x xs -> R1 (Day x xs (&)) from_ = \case L1 (Identity x) -> Pure x R1 (Day x xs f) -> Ap x (flip f <$> xs) toListBy (Day x y z) = Ap x (Ap y (Pure (flip z))) -- | Instances of 'Applicative' are monoids in the monoidal category on -- the covariant 'Day'. -- -- Note that because of typeclass constraints, this requires 'Apply' as -- well as 'Applicative'. But, you can get a "local" instance of 'Apply' -- for any 'Applicative' using -- 'Data.Functor.Combinators.Unsafe.unsafeApply'. instance (Apply f, Applicative f) => MonoidIn Day Identity f where pureT = generalize | @since 0.3.0.0 instance Tensor CD.Day Proxy where type ListBy CD.Day = Div intro1 = CD.intro2 intro2 = CD.intro1 elim1 = CD.day1 elim2 = CD.day2 appendLB (CD.Day x y z) = divide z x y splitNE = go . splitNE @(:*:) . NonEmptyF . unDiv1 where go (CCY.Coyoneda f x :*: ListF xs) = CD.Day x (Div xs) (\y -> (f y, y)) splittingLB = isoF (ListF . unDiv) (Div . runListF) . splittingLB @(:*:) . isoF (hright to_) (hright from_) where to_ (CCY.Coyoneda f x :*: ListF xs) = CD.Day x (Div xs) (\y -> (f y, y)) from_ (CD.Day x (Div xs) f) = CCY.Coyoneda (fst . f) x :*: contramap (snd . f) (ListF xs) toListBy (CD.Day x y f) = Div . runListF . toListBy $ CCY.Coyoneda (fst . f) x :*: CCY.Coyoneda (snd . f) y -- | Instances of 'Divisible' are monoids in the monoidal category on -- contravariant 'CD.Day'. -- Note that because of typeclass constraints , this requires ' Divise ' as well as ' Divisible ' . But , you can get a " local " instance of ' Divise ' -- for any 'Divisible' using -- 'Data.Functor.Combinators.Unsafe.unsafeDivise'. -- @since 0.3.0.0 instance (Divise f, Divisible f) => MonoidIn CD.Day Proxy f where pureT _ = conquer instance Tensor ID.Day Identity where type ListBy ID.Day = DivAp intro1 = ID.intro2 intro2 = ID.intro1 elim1 = ID.elim2 elim2 = ID.elim1 appendLB (ID.Day (DivAp xs) (DivAp ys) f g) = DivAp $ case xs of Done (Identity x) -> invmap (f x) (snd . g) ys More (ID.Day z zs h j) -> More $ ID.Day z (unDivAp $ appendLB (ID.Day (DivAp zs) (DivAp ys) (,) id)) (\q (r, s) -> f (h q r) s) (B.assoc . first j . g) splitNE = coerce splitChain1 splittingLB = coercedF . splittingChain . coercedF toListBy = DivAp . More . hright (unDivAp . inject) instance Matchable ID.Day Identity where unsplitNE = coerce unsplitNEIDay_ matchLB = coerce matchLBIDay_ unsplitNEIDay_ :: Invariant f => ID.Day f (Chain ID.Day Identity f) ~> Chain1 ID.Day f unsplitNEIDay_ (ID.Day x xs g f) = case xs of Done (Identity r) -> Done1 $ invmap (`g` r) (fst . f) x More ys -> More1 $ ID.Day x (unsplitNEIDay_ ys) g f matchLBIDay_ :: Invariant f => Chain ID.Day Identity f ~> (Identity :+: Chain1 ID.Day f) matchLBIDay_ = \case Done x -> L1 x More xs -> R1 $ unsplitNEIDay_ xs instance Inplicative f => MonoidIn ID.Day Identity f where pureT (Identity x) = knot x instance Tensor IN.Night IN.Not where type ListBy IN.Night = DecAlt intro1 = IN.intro2 intro2 = IN.intro1 elim1 = IN.elim2 elim2 = IN.elim1 appendLB (IN.Night (DecAlt xs) (DecAlt ys) f g h) = DecAlt $ case xs of Done r -> invmap g (either (absurd . refute r) id . h) ys More (IN.Night z zs j k l) -> More $ IN.Night z (unDecAlt $ appendLB (IN.Night (DecAlt zs) (DecAlt ys) Left Right id)) (f . j) (either (f . k) g) (B.assoc . first l . h) splitNE = coerce splitChain1 splittingLB = coercedF . splittingChain . coercedF toListBy = DecAlt . More . hright (unDecAlt . inject) instance Matchable IN.Night Not where unsplitNE = coerce unsplitNEINight_ matchLB = coerce matchLBINight_ unsplitNEINight_ :: Invariant f => IN.Night f (Chain IN.Night Not f) ~> Chain1 IN.Night f unsplitNEINight_ (IN.Night x xs f g h) = case xs of Done r -> Done1 $ invmap f (either id (absurd . refute r) . h) x More ys -> More1 $ IN.Night x (unsplitNEINight_ ys) f g h matchLBINight_ :: Invariant f => Chain IN.Night Not f ~> (Not :+: Chain1 IN.Night f) matchLBINight_ = \case Done x -> L1 x More xs -> R1 $ unsplitNEINight_ xs -- | @since 0.4.0.0 instance Inplus f => MonoidIn IN.Night IN.Not f where pureT (Not x) = reject x | @since 0.3.0.0 instance Tensor Night Not where type ListBy Night = Dec intro1 = N.intro2 intro2 = N.intro1 elim1 = N.elim2 elim2 = N.elim1 appendLB (Night x y z) = decide z x y splitNE (Dec1 f x xs) = Night x xs f splittingLB = isoF to_ from_ where to_ = \case Lose f -> L1 (Not f) Choose f x xs -> R1 (Night x xs f) from_ = \case L1 (Not f) -> Lose f R1 (Night x xs f) -> Choose f x xs toListBy (Night x y z) = Choose z x (inject y) | Instances of ' Conclude ' are monoids in the monoidal category on ' Night ' . instance Conclude f => MonoidIn Night Not f where pureT (Not x) = conclude x instance Tensor (:+:) V1 where type ListBy (:+:) = Step intro1 = L1 intro2 = R1 elim1 = \case L1 x -> x R1 y -> absurd1 y elim2 = \case L1 x -> absurd1 x R1 y -> y appendLB = id !*! stepUp . R1 splitNE = stepDown splittingLB = stepping . sumLeftIdentity toListBy = \case L1 x -> Step 0 x R1 x -> Step 1 x -- | All functors are monoids in the monoidal category on ':+:'. instance MonoidIn (:+:) V1 f where pureT = absurd1 instance Tensor Sum V1 where type ListBy Sum = Step intro1 = InL intro2 = InR elim1 = \case InL x -> x InR y -> absurd1 y elim2 = \case InL x -> absurd1 x InR y -> y appendLB = id !*! stepUp . R1 splitNE = viewF sumSum . stepDown splittingLB = stepping . sumLeftIdentity . overHBifunctor id sumSum toListBy = \case InL x -> Step 0 x InR x -> Step 1 x -- | All functors are monoids in the monoidal category on 'Sum'. instance MonoidIn Sum V1 f where pureT = absurd1 instance Tensor These1 V1 where type ListBy These1 = Steps intro1 = This1 intro2 = That1 elim1 = \case This1 x -> x That1 y -> absurd1 y These1 _ y -> absurd1 y elim2 = \case This1 x -> absurd1 x That1 y -> y These1 x _ -> absurd1 x appendLB = \case This1 x -> x That1 y -> stepsUp . That1 $ y These1 x y -> x <> y splitNE = stepsDown . flaggedVal . getComposeT splittingLB = steppings . sumLeftIdentity toListBy = \case This1 x -> Steps $ NEM.singleton 0 x That1 y -> Steps $ NEM.singleton 1 y These1 x y -> Steps $ NEM.fromDistinctAscList ((0, x) :| [(1, y)]) instance Alt f => MonoidIn These1 V1 f where pureT = absurd1 instance Tensor Comp Identity where type ListBy Comp = Free intro1 = (:>>= Identity) intro2 = (Identity () :>>=) . const elim1 (x :>>= y) = runIdentity . y <$> x elim2 (x :>>= y) = y (runIdentity x) appendLB (x :>>= y) = x >>= y splitNE = free1Comp splittingLB = isoF to_ from_ where to_ :: Free f ~> Identity :+: Comp f (Free f) to_ = foldFree' (L1 . Identity) $ \y n -> R1 $ y :>>= (from_ . n) from_ :: Identity :+: Comp f (Free f) ~> Free f from_ = generalize !*! (\case x :>>= f -> liftFree x >>= f) toListBy (x :>>= y) = liftFree x >>= (inject . y) -- | Instances of 'Monad' are monoids in the monoidal category on -- 'Comp'. -- -- This instance is the "proof" that "monads are the monoids in the -- category of endofunctors (enriched with 'Comp')" -- Note that because of typeclass constraints , this requires ' Bind ' as -- well as 'Monad'. But, you can get a "local" instance of 'Apply' -- for any 'Monad' using -- 'Data.Functor.Combinators.Unsafe.unsafeBind'. instance (Bind f, Monad f) => MonoidIn Comp Identity f where pureT = generalize instance Matchable (:*:) Proxy where unsplitNE = ProdNonEmpty matchLB = fromListF instance Matchable Product Proxy where unsplitNE = ProdNonEmpty . reviewF prodProd matchLB = fromListF instance Matchable Day Identity where unsplitNE = DayAp1 matchLB = fromAp | Instances of ' Conclude ' are monoids in the monoidal category on ' Night ' . -- @since 0.3.0.0 instance Matchable CD.Day Proxy where unsplitNE (CD.Day x (Div xs) f) = Div1 . runNonEmptyF . unsplitNE $ CCY.Coyoneda (fst . f) x :*: contramap (snd . f) (ListF xs) matchLB = hright (Div1 . runNonEmptyF) . matchLB @(:*:) . ListF . unDiv | @since 0.3.0.0 instance Matchable Night Not where unsplitNE (Night x xs f) = Dec1 f x xs matchLB = \case Lose f -> L1 (Not f) Choose f x xs -> R1 (Dec1 f x xs) instance Matchable (:+:) V1 where unsplitNE = stepUp matchLB = R1 instance Matchable Sum V1 where unsplitNE = stepUp . reviewF sumSum matchLB = R1 -- We can't write this until we get an isomorphism between MF These1 and SF These1 -- instance Matchable These1 where -- unsplitNE = stepsUp -- matchLB = R1 | A newtype wrapper meant to be used to define polymorphic ' ' instances . See documentation for ' ' for more information . -- Please do not ever define an instance of ' ' " naked " on the third parameter : -- -- @ instance ( WrapHBF t ) ( WrapF i ) f -- @ -- -- As that would globally ruin everything using 'WrapHBF'. newtype WrapF f a = WrapF { unwrapF :: f a } deriving (Show, Read, Eq, Ord, Functor, Foldable, Traversable, Typeable, Generic, Data) instance Show1 f => Show1 (WrapF f) where liftShowsPrec sp sl d (WrapF x) = showsUnaryWith (liftShowsPrec sp sl) "WrapF" d x instance Eq1 f => Eq1 (WrapF f) where liftEq eq (WrapF x) (WrapF y) = liftEq eq x y instance Ord1 f => Ord1 (WrapF f) where liftCompare c (WrapF x) (WrapF y) = liftCompare c x y instance Tensor t i => Tensor (WrapHBF t) (WrapF i) where type ListBy (WrapHBF t) = ListBy t intro1 = WrapHBF . hright WrapF . intro1 intro2 = WrapHBF . hleft WrapF . intro2 elim1 = elim1 . hright unwrapF . unwrapHBF elim2 = elim2 . hleft unwrapF . unwrapHBF appendLB = appendLB . unwrapHBF splitNE = WrapHBF . splitNE splittingLB = splittingLB @t . overHBifunctor (isoF WrapF unwrapF) (isoF WrapHBF unwrapHBF) toListBy = toListBy . unwrapHBF fromNE = fromNE @t | Any @'ListBy ' t f@ is a @'SemigroupIn ' t@ and a @'MonoidIn ' t i@ , if we have @'Tensor ' t This newtype wrapper witnesses that fact . We -- require a newtype wrapper to avoid overlapping instances. newtype WrapLB t f a = WrapLB { unwrapLB :: ListBy t f a } instance Functor (ListBy t f) => Functor (WrapLB t f) where fmap f (WrapLB x) = WrapLB (fmap f x) | @since 0.3.0.0 instance Contravariant (ListBy t f) => Contravariant (WrapLB t f) where contramap f (WrapLB x) = WrapLB (contramap f x) | @since 0.3.0.0 instance Invariant (ListBy t f) => Invariant (WrapLB t f) where invmap f g (WrapLB x) = WrapLB (invmap f g x) instance (Tensor t i, FunctorBy t f, FunctorBy t (WrapLB t f)) => SemigroupIn (WrapHBF t) (WrapLB t f) where biretract = WrapLB . appendLB . hbimap unwrapLB unwrapLB . unwrapHBF binterpret f g = biretract . hbimap f g instance (Tensor t i, FunctorBy t f, FunctorBy t (WrapLB t f)) => MonoidIn (WrapHBF t) (WrapF i) (WrapLB t f) where pureT = WrapLB . nilLB @t . unwrapF
null
https://raw.githubusercontent.com/mstksg/functor-combinators/3e1ab9fc4c4fe756ba05d348cd9ba0342201c611/src/Data/HBifunctor/Tensor.hs
haskell
| Module : Data.HBifunctor.Tensor License : BSD3 Stability : experimental Portability : non-portable This module provides tools for working with binary functor combinators. (transforming a single functor). This module provides tools for working The binary analog of 'HFunctor' is 'HBifunctor': we can map a structure-transforming function over both of the transformed functors. 'Tensor' gives some extra properties of your binary functor combinator: associativity and identity (see docs for 'Tensor' for more details). can "interpret" out of your tensored values, and also "generate" values @ 'biretract' :: (f ':+:' f) a -> f a 'pureT' :: 'V1' a -> f a biretract :: 'Plus' f => (f ':*:' f) a -> f a pureT :: Plus f => 'Proxy' a -> f a pureT :: Applicative f => 'Identity' a -> f a biretract :: 'Monad' f => 'Comp' f f a -> f a pureT :: Monad f => 'Identity' a -> f a @ * 'Tensor' ** Utility * 'Matchable' require 'Functor'. This is the more general version. require 'Functor'. This is the more general version. require 'Functor'. This is the more general version. require 'Functor'. This is the more general version. | A poly-kinded version of 'outL' for ':*:'. | A poly-kinded version of 'outR' for ':*:'. of interesting functions possible when used with 'biretract' from 'SemigroupIn' that weren't possible without it: it gives us a "base case" for recursion in a lot of cases. Essentially, we get an @i ~> f@, 'pureT', where we can introduce an @f a@ as long as we have an @i a@. Formally, if we have @'Tensor' t i@, we are enriching the category of endofunctors with monoid structure, turning it into a monoidal category. Different choices of @t@ give different monoidal categories. of endofunctors on @t@" if we can 'biretract': @ t f f ~> f @ and also 'pureT': @ i ~> f @ This gives us a few interesting results in category theory, which you can stil reading about if you don't care: * /All/ functors are monoids in the monoidal category on ':+:' * The class of functors that are monoids in the monoidal category on ':*:' is exactly the functors that are instances of * The class of functors that are monoids in the monoidal * The class of functors that are monoids in the monoidal category on 'Comp' is exactly the functors that are instances of This is the meaning behind the common adage, "monads are just monoids in the category of endofunctors". It means that if you enrich the category of endofunctors to be monoidal with 'Comp', then the class of functors that are monoids in that monoidal category are exactly what monads are. However, the adage is a little misleading: there are many other ways to enrich the category of endofunctors to be monoidal, and 'Comp' is just one of them. Similarly, the class of functors that are monoids in the category of endofunctors enriched by 'Day' are 'Applicative'. Note that instances of this class are /intended/ to be written with @t@ freely: @ @ Any other sort of instance and it's easy to run into problems with type inference. If you want to write an instance that's "polymorphic" on @ @ This will prevent problems with overloaded instances. @ 'pureT' \@'Day' :: 'Applicative' f => 'Identity' a -> f a -- 'pure' ' return ' pureT \@(':*:') :: 'Plus' f => 'Proxy' a -> f a -- 'zero' @ Note that because @t@ appears nowhere in the input or output types, you must always use this with explicit type application syntax (like | An implementation of 'retract' that works for any instance of implemented. | An implementation of 'interpret' that works for any instance of implemented. You can think of this as an 'HBifunctor' analogue of 'inject'. | Convenient wrapper over 'intro2' that lets us introduce an arbitrary You can think of this as an 'HBifunctor' analogue of 'inject'. of a 'Tensor' for free, without requiring any extra constraints (like for 'binterpret'). See 'prodOutL' for a version that does not require @'Functor' f@, specifically for ':*:'. of a 'Tensor' for free, without requiring any constraints (like for 'binterpret'). specifically for ':*:'. and pattern match and manipulate the structure without ever interpreting or retracting. These are 'Matchable'. This is analogous to a function @'uncurry' ('Data.List.NonEmpty.:|') Note that because @t@ cannot be inferred from the input or output type, you should use this with /-XTypeApplications/: @ 'matchLB' \@'Day' :: 'Ap' f a -> ('Identity' :+: 'Ap1' f) a @ Note that you can recursively "unroll" a 'ListBy' completely into a 'Data.HFunctor.Chain.Chain' by using 'Data.HFunctor.Chain.unrollLB'. | Instances of 'Plus' are monoids in the monoidal category on ':*:'. | Instances of 'Plus' are monoids in the monoidal category on 'Product'. | Instances of 'Applicative' are monoids in the monoidal category on the covariant 'Day'. Note that because of typeclass constraints, this requires 'Apply' as well as 'Applicative'. But, you can get a "local" instance of 'Apply' for any 'Applicative' using 'Data.Functor.Combinators.Unsafe.unsafeApply'. | Instances of 'Divisible' are monoids in the monoidal category on contravariant 'CD.Day'. for any 'Divisible' using 'Data.Functor.Combinators.Unsafe.unsafeDivise'. | @since 0.4.0.0 | All functors are monoids in the monoidal category on ':+:'. | All functors are monoids in the monoidal category on 'Sum'. | Instances of 'Monad' are monoids in the monoidal category on 'Comp'. This instance is the "proof" that "monads are the monoids in the category of endofunctors (enriched with 'Comp')" well as 'Monad'. But, you can get a "local" instance of 'Apply' for any 'Monad' using 'Data.Functor.Combinators.Unsafe.unsafeBind'. We can't write this until we get an isomorphism between MF These1 and SF These1 instance Matchable These1 where unsplitNE = stepsUp matchLB = R1 @ @ As that would globally ruin everything using 'WrapHBF'. require a newtype wrapper to avoid overlapping instances.
# OPTIONS_GHC -Wno - orphans # Copyright : ( c ) 2019 Maintainer : " Data . Functor . HFunctor " deals with /single/ functor combinators with combinators that combine and mix two functors " together " . The binary analog of ' Interpret ' is ' ' . If your combinator @t@ and target functor is an instance of @'MonoidIn ' t f@ , it means you of @f@. biretract : : ' Applicative ' f = > ' Day ' f f a - > f a module Data.HBifunctor.Tensor ( Tensor(..) , rightIdentity , leftIdentity , sumLeftIdentity , sumRightIdentity , prodLeftIdentity , prodRightIdentity * ' ' , MonoidIn(..) , nilLB , consLB , unconsLB , retractLB , interpretLB , inL , inR , outL , outR , prodOutL , prodOutR , WrapF(..) , WrapLB(..) , Matchable(..) , splittingNE , matchingLB ) where import Control.Applicative.Free import Control.Applicative.ListF import Control.Applicative.Step import Control.Monad.Freer.Church import Control.Monad.Trans.Compose import Control.Natural import Control.Natural.IsoF import Data.Bifunctor import Data.Coerce import Data.Data import Data.Function import Data.Functor.Apply.Free import Data.Functor.Bind import Data.Functor.Classes import Data.Functor.Contravariant import Data.Functor.Contravariant.Conclude import Data.Functor.Contravariant.Decide import Data.Functor.Contravariant.Divise import Data.Functor.Contravariant.Divisible import Data.Functor.Contravariant.Divisible.Free import Data.Functor.Contravariant.Night (Night(..), Not(..)) import Data.Functor.Day (Day(..)) import Data.Functor.Identity import Data.Functor.Invariant import Data.Functor.Invariant.Internative import Data.Functor.Invariant.Inplicative import Data.Functor.Plus import Data.Functor.Product import Data.Functor.Sum import Data.Functor.These import Data.HBifunctor import Data.HBifunctor.Associative import Data.HBifunctor.Tensor.Internal import Data.HFunctor import Data.HFunctor.Chain.Internal import Data.HFunctor.Internal import Data.HFunctor.Interpret import Data.List.NonEmpty (NonEmpty(..)) import Data.Void import GHC.Generics import qualified Data.Bifunctor.Assoc as B import qualified Data.Functor.Contravariant.Coyoneda as CCY import qualified Data.Functor.Contravariant.Day as CD import qualified Data.Functor.Contravariant.Night as N import qualified Data.Functor.Day as D import qualified Data.Functor.Invariant.Day as ID import qualified Data.Functor.Invariant.Night as IN import qualified Data.Map.NonEmpty as NEM | @f@ is isomorphic to @t f i@ : that is , @i@ is the identity of @t@ , and leaves unchanged . rightIdentity :: (Tensor t i, FunctorBy t f) => f <~> t f i rightIdentity = isoF intro1 elim1 | @g@ is isomorphic to @t i : that is , @i@ is the identity of @t@ , and leaves unchanged . leftIdentity :: (Tensor t i, FunctorBy t g) => g <~> t i g leftIdentity = isoF intro2 elim2 | ' leftIdentity ' ( ' intro1 ' and ' ' ) for ' : + : ' actually does not sumLeftIdentity :: f <~> V1 :+: f sumLeftIdentity = isoF R1 (absurd1 !+! id) | ' rightIdentity ' ( ' intro2 ' and ' ' ) for ' : + : ' actually does not sumRightIdentity :: f <~> f :+: V1 sumRightIdentity = isoF L1 (id !+! absurd1) | ' leftIdentity ' ( ' intro1 ' and ' ' ) for ' :* : ' actually does not prodLeftIdentity :: f <~> Proxy :*: f prodLeftIdentity = isoF (Proxy :*:) (\case _ :*: y -> y) | ' rightIdentity ' ( ' intro2 ' and ' ' ) for ' :* : ' actually does not prodRightIdentity :: g <~> g :*: Proxy prodRightIdentity = isoF (:*: Proxy) (\case x :*: _ -> x) prodOutL :: f :*: g ~> f prodOutL (x :*: _) = x prodOutR :: f :*: g ~> g prodOutR (_ :*: y) = y | This class effectively gives us a way to generate a value of @f a@ based on an @i a@ , for @'Tensor ' t Having this ability makes a lot A functor is known as a " monoid in the ( monoidal ) category ' Plus ' . category on ' Day ' is exactly the functors that are instances of ' Applicative ' . ' ' . and @i@ to be fixed type constructors , and to be allowed to vary instance = > MonoidIn Comp Identity f tensor choice , use the ' WrapHBF ' and ' WrapF ' newtype wrappers over type variables , where the third argument also uses a type constructor : instance ( WrapHBF t ) ( WrapF i ) ( MyFunctor t i ) class (Tensor t i, SemigroupIn t f) => MonoidIn t i f where | If we have an @i@ , we can generate an @f@ based on how it interacts with Specialized ( and simplified ) , this type is : @pureT \@Day@ ) Along with ' biretract ' , this function makes @f@ a monoid in the category of endofunctors with respect to tensor pureT :: i ~> f default pureT :: Interpret (ListBy t) f => i ~> f pureT = retract . reviewF (splittingLB @t) . L1 @'MonoidIn ' t i@ for @'ListBy ' t@. Can be useful as a default implementation if you already have ' ' retractLB :: forall t i f. MonoidIn t i f => ListBy t f ~> f retractLB = (pureT @t !*! biretract @t . hright (retractLB @t)) . unconsLB @t @'MonoidIn ' t i@ for @'ListBy ' t@. Can be useful as a default implementation if you already have ' ' interpretLB :: forall t i g f. MonoidIn t i f => (g ~> f) -> ListBy t g ~> f interpretLB f = retractLB @t . hmap f | Convenient wrapper over ' intro1 ' that lets us introduce an arbitrary functor @g@ to the right of an @f@. inL :: forall t i f g. MonoidIn t i g => f ~> t f g inL = hright (pureT @t) . intro1 functor to the right of a @g@. inR :: forall t i f g. MonoidIn t i f => g ~> t f g inR = hleft (pureT @t) . intro2 | Convenient wrapper over ' ' that lets us drop one of the arguments outL :: (Tensor t Proxy, FunctorBy t f) => t f g ~> f outL = elim1 . hright absorb | Convenient wrapper over ' ' that lets us drop one of the arguments See ' prodOutR ' for a version that does not require @'Functor ' , outR :: (Tensor t Proxy, FunctorBy t g) => t f g ~> g outR = elim2 . hleft absorb | For some @t@ , we have the ability to " statically analyze " the @'ListBy ' t@ class Tensor t i => Matchable t i where | The inverse of ' splitNE ' . A consing of to @'ListBy ' t f@ is non - empty , so it can be represented as an @'NonEmptyBy ' t f@. : : ( a , [ a ] ) - > ' Data . List . NonEmpty . NonEmpty ' a@. unsplitNE :: FunctorBy t f => t f (ListBy t f) ~> NonEmptyBy t f | " Pattern match " on an @'ListBy ' t f@ : it is either empty , or it is non - empty ( and so can be an @'NonEmptyBy ' t f@ ) . This is analgous to a function @'Data . List . NonEmpty.nonEmpty ' : : [ a ] - > Maybe ( ' Data . List . NonEmpty . NonEmpty ' a)@. matchLB :: FunctorBy t f => ListBy t f ~> i :+: NonEmptyBy t f | An @'NonEmptyBy ' t f@ is isomorphic to an consed with an @'ListBy ' t f@ , like how a @'Data . List . NonEmpty . NonEmpty ' a@ is isomorphic to @(a , [ a])@. splittingNE :: (Matchable t i, FunctorBy t f) => NonEmptyBy t f <~> t f (ListBy t f) splittingNE = isoF splitNE unsplitNE | An @'ListBy ' t f@ is isomorphic to either the empty case ( @i@ ) or the non - empty case ( @'NonEmptyBy ' t f@ ) , like how @[a]@ is isomorphic to @'Maybe ' ( ' Data . List . NonEmpty . NonEmpty ' a)@. matchingLB :: forall t i f. (Matchable t i, FunctorBy t f) => ListBy t f <~> i :+: NonEmptyBy t f matchingLB = isoF (matchLB @t) (nilLB @t !*! fromNE @t) instance Tensor (:*:) Proxy where type ListBy (:*:) = ListF intro1 = (:*: Proxy) intro2 = (Proxy :*:) elim1 (x :*: ~Proxy) = x elim2 (~Proxy :*: y ) = y appendLB (ListF xs :*: ListF ys) = ListF (xs ++ ys) splitNE = nonEmptyProd splittingLB = isoF to_ from_ where to_ = \case ListF [] -> L1 Proxy ListF (x:xs) -> R1 (x :*: ListF xs) from_ = \case L1 ~Proxy -> ListF [] R1 (x :*: ListF xs) -> ListF (x:xs) toListBy (x :*: y) = ListF [x, y] instance Plus f => MonoidIn (:*:) Proxy f where pureT _ = zero instance Tensor Product Proxy where type ListBy Product = ListF intro1 = (`Pair` Proxy) intro2 = (Proxy `Pair`) elim1 (Pair x ~Proxy) = x elim2 (Pair ~Proxy y) = y appendLB (ListF xs `Pair` ListF ys) = ListF (xs ++ ys) splitNE = viewF prodProd . nonEmptyProd splittingLB = isoF to_ from_ where to_ = \case ListF [] -> L1 Proxy ListF (x:xs) -> R1 (x `Pair` ListF xs) from_ = \case L1 ~Proxy -> ListF [] R1 (x `Pair` ListF xs) -> ListF (x:xs) toListBy (Pair x y) = ListF [x, y] instance Plus f => MonoidIn Product Proxy f where pureT _ = zero instance Tensor Day Identity where type ListBy Day = Ap intro1 = D.intro2 intro2 = D.intro1 elim1 = D.elim2 elim2 = D.elim1 appendLB (Day x y z) = z <$> x <*> y splitNE = ap1Day splittingLB = isoF to_ from_ where to_ = \case Pure x -> L1 (Identity x) Ap x xs -> R1 (Day x xs (&)) from_ = \case L1 (Identity x) -> Pure x R1 (Day x xs f) -> Ap x (flip f <$> xs) toListBy (Day x y z) = Ap x (Ap y (Pure (flip z))) instance (Apply f, Applicative f) => MonoidIn Day Identity f where pureT = generalize | @since 0.3.0.0 instance Tensor CD.Day Proxy where type ListBy CD.Day = Div intro1 = CD.intro2 intro2 = CD.intro1 elim1 = CD.day1 elim2 = CD.day2 appendLB (CD.Day x y z) = divide z x y splitNE = go . splitNE @(:*:) . NonEmptyF . unDiv1 where go (CCY.Coyoneda f x :*: ListF xs) = CD.Day x (Div xs) (\y -> (f y, y)) splittingLB = isoF (ListF . unDiv) (Div . runListF) . splittingLB @(:*:) . isoF (hright to_) (hright from_) where to_ (CCY.Coyoneda f x :*: ListF xs) = CD.Day x (Div xs) (\y -> (f y, y)) from_ (CD.Day x (Div xs) f) = CCY.Coyoneda (fst . f) x :*: contramap (snd . f) (ListF xs) toListBy (CD.Day x y f) = Div . runListF . toListBy $ CCY.Coyoneda (fst . f) x :*: CCY.Coyoneda (snd . f) y Note that because of typeclass constraints , this requires ' Divise ' as well as ' Divisible ' . But , you can get a " local " instance of ' Divise ' @since 0.3.0.0 instance (Divise f, Divisible f) => MonoidIn CD.Day Proxy f where pureT _ = conquer instance Tensor ID.Day Identity where type ListBy ID.Day = DivAp intro1 = ID.intro2 intro2 = ID.intro1 elim1 = ID.elim2 elim2 = ID.elim1 appendLB (ID.Day (DivAp xs) (DivAp ys) f g) = DivAp $ case xs of Done (Identity x) -> invmap (f x) (snd . g) ys More (ID.Day z zs h j) -> More $ ID.Day z (unDivAp $ appendLB (ID.Day (DivAp zs) (DivAp ys) (,) id)) (\q (r, s) -> f (h q r) s) (B.assoc . first j . g) splitNE = coerce splitChain1 splittingLB = coercedF . splittingChain . coercedF toListBy = DivAp . More . hright (unDivAp . inject) instance Matchable ID.Day Identity where unsplitNE = coerce unsplitNEIDay_ matchLB = coerce matchLBIDay_ unsplitNEIDay_ :: Invariant f => ID.Day f (Chain ID.Day Identity f) ~> Chain1 ID.Day f unsplitNEIDay_ (ID.Day x xs g f) = case xs of Done (Identity r) -> Done1 $ invmap (`g` r) (fst . f) x More ys -> More1 $ ID.Day x (unsplitNEIDay_ ys) g f matchLBIDay_ :: Invariant f => Chain ID.Day Identity f ~> (Identity :+: Chain1 ID.Day f) matchLBIDay_ = \case Done x -> L1 x More xs -> R1 $ unsplitNEIDay_ xs instance Inplicative f => MonoidIn ID.Day Identity f where pureT (Identity x) = knot x instance Tensor IN.Night IN.Not where type ListBy IN.Night = DecAlt intro1 = IN.intro2 intro2 = IN.intro1 elim1 = IN.elim2 elim2 = IN.elim1 appendLB (IN.Night (DecAlt xs) (DecAlt ys) f g h) = DecAlt $ case xs of Done r -> invmap g (either (absurd . refute r) id . h) ys More (IN.Night z zs j k l) -> More $ IN.Night z (unDecAlt $ appendLB (IN.Night (DecAlt zs) (DecAlt ys) Left Right id)) (f . j) (either (f . k) g) (B.assoc . first l . h) splitNE = coerce splitChain1 splittingLB = coercedF . splittingChain . coercedF toListBy = DecAlt . More . hright (unDecAlt . inject) instance Matchable IN.Night Not where unsplitNE = coerce unsplitNEINight_ matchLB = coerce matchLBINight_ unsplitNEINight_ :: Invariant f => IN.Night f (Chain IN.Night Not f) ~> Chain1 IN.Night f unsplitNEINight_ (IN.Night x xs f g h) = case xs of Done r -> Done1 $ invmap f (either id (absurd . refute r) . h) x More ys -> More1 $ IN.Night x (unsplitNEINight_ ys) f g h matchLBINight_ :: Invariant f => Chain IN.Night Not f ~> (Not :+: Chain1 IN.Night f) matchLBINight_ = \case Done x -> L1 x More xs -> R1 $ unsplitNEINight_ xs instance Inplus f => MonoidIn IN.Night IN.Not f where pureT (Not x) = reject x | @since 0.3.0.0 instance Tensor Night Not where type ListBy Night = Dec intro1 = N.intro2 intro2 = N.intro1 elim1 = N.elim2 elim2 = N.elim1 appendLB (Night x y z) = decide z x y splitNE (Dec1 f x xs) = Night x xs f splittingLB = isoF to_ from_ where to_ = \case Lose f -> L1 (Not f) Choose f x xs -> R1 (Night x xs f) from_ = \case L1 (Not f) -> Lose f R1 (Night x xs f) -> Choose f x xs toListBy (Night x y z) = Choose z x (inject y) | Instances of ' Conclude ' are monoids in the monoidal category on ' Night ' . instance Conclude f => MonoidIn Night Not f where pureT (Not x) = conclude x instance Tensor (:+:) V1 where type ListBy (:+:) = Step intro1 = L1 intro2 = R1 elim1 = \case L1 x -> x R1 y -> absurd1 y elim2 = \case L1 x -> absurd1 x R1 y -> y appendLB = id !*! stepUp . R1 splitNE = stepDown splittingLB = stepping . sumLeftIdentity toListBy = \case L1 x -> Step 0 x R1 x -> Step 1 x instance MonoidIn (:+:) V1 f where pureT = absurd1 instance Tensor Sum V1 where type ListBy Sum = Step intro1 = InL intro2 = InR elim1 = \case InL x -> x InR y -> absurd1 y elim2 = \case InL x -> absurd1 x InR y -> y appendLB = id !*! stepUp . R1 splitNE = viewF sumSum . stepDown splittingLB = stepping . sumLeftIdentity . overHBifunctor id sumSum toListBy = \case InL x -> Step 0 x InR x -> Step 1 x instance MonoidIn Sum V1 f where pureT = absurd1 instance Tensor These1 V1 where type ListBy These1 = Steps intro1 = This1 intro2 = That1 elim1 = \case This1 x -> x That1 y -> absurd1 y These1 _ y -> absurd1 y elim2 = \case This1 x -> absurd1 x That1 y -> y These1 x _ -> absurd1 x appendLB = \case This1 x -> x That1 y -> stepsUp . That1 $ y These1 x y -> x <> y splitNE = stepsDown . flaggedVal . getComposeT splittingLB = steppings . sumLeftIdentity toListBy = \case This1 x -> Steps $ NEM.singleton 0 x That1 y -> Steps $ NEM.singleton 1 y These1 x y -> Steps $ NEM.fromDistinctAscList ((0, x) :| [(1, y)]) instance Alt f => MonoidIn These1 V1 f where pureT = absurd1 instance Tensor Comp Identity where type ListBy Comp = Free intro1 = (:>>= Identity) intro2 = (Identity () :>>=) . const elim1 (x :>>= y) = runIdentity . y <$> x elim2 (x :>>= y) = y (runIdentity x) appendLB (x :>>= y) = x >>= y splitNE = free1Comp splittingLB = isoF to_ from_ where to_ :: Free f ~> Identity :+: Comp f (Free f) to_ = foldFree' (L1 . Identity) $ \y n -> R1 $ y :>>= (from_ . n) from_ :: Identity :+: Comp f (Free f) ~> Free f from_ = generalize !*! (\case x :>>= f -> liftFree x >>= f) toListBy (x :>>= y) = liftFree x >>= (inject . y) Note that because of typeclass constraints , this requires ' Bind ' as instance (Bind f, Monad f) => MonoidIn Comp Identity f where pureT = generalize instance Matchable (:*:) Proxy where unsplitNE = ProdNonEmpty matchLB = fromListF instance Matchable Product Proxy where unsplitNE = ProdNonEmpty . reviewF prodProd matchLB = fromListF instance Matchable Day Identity where unsplitNE = DayAp1 matchLB = fromAp | Instances of ' Conclude ' are monoids in the monoidal category on ' Night ' . @since 0.3.0.0 instance Matchable CD.Day Proxy where unsplitNE (CD.Day x (Div xs) f) = Div1 . runNonEmptyF . unsplitNE $ CCY.Coyoneda (fst . f) x :*: contramap (snd . f) (ListF xs) matchLB = hright (Div1 . runNonEmptyF) . matchLB @(:*:) . ListF . unDiv | @since 0.3.0.0 instance Matchable Night Not where unsplitNE (Night x xs f) = Dec1 f x xs matchLB = \case Lose f -> L1 (Not f) Choose f x xs -> R1 (Dec1 f x xs) instance Matchable (:+:) V1 where unsplitNE = stepUp matchLB = R1 instance Matchable Sum V1 where unsplitNE = stepUp . reviewF sumSum matchLB = R1 | A newtype wrapper meant to be used to define polymorphic ' ' instances . See documentation for ' ' for more information . Please do not ever define an instance of ' ' " naked " on the third parameter : instance ( WrapHBF t ) ( WrapF i ) f newtype WrapF f a = WrapF { unwrapF :: f a } deriving (Show, Read, Eq, Ord, Functor, Foldable, Traversable, Typeable, Generic, Data) instance Show1 f => Show1 (WrapF f) where liftShowsPrec sp sl d (WrapF x) = showsUnaryWith (liftShowsPrec sp sl) "WrapF" d x instance Eq1 f => Eq1 (WrapF f) where liftEq eq (WrapF x) (WrapF y) = liftEq eq x y instance Ord1 f => Ord1 (WrapF f) where liftCompare c (WrapF x) (WrapF y) = liftCompare c x y instance Tensor t i => Tensor (WrapHBF t) (WrapF i) where type ListBy (WrapHBF t) = ListBy t intro1 = WrapHBF . hright WrapF . intro1 intro2 = WrapHBF . hleft WrapF . intro2 elim1 = elim1 . hright unwrapF . unwrapHBF elim2 = elim2 . hleft unwrapF . unwrapHBF appendLB = appendLB . unwrapHBF splitNE = WrapHBF . splitNE splittingLB = splittingLB @t . overHBifunctor (isoF WrapF unwrapF) (isoF WrapHBF unwrapHBF) toListBy = toListBy . unwrapHBF fromNE = fromNE @t | Any @'ListBy ' t f@ is a @'SemigroupIn ' t@ and a @'MonoidIn ' t i@ , if we have @'Tensor ' t This newtype wrapper witnesses that fact . We newtype WrapLB t f a = WrapLB { unwrapLB :: ListBy t f a } instance Functor (ListBy t f) => Functor (WrapLB t f) where fmap f (WrapLB x) = WrapLB (fmap f x) | @since 0.3.0.0 instance Contravariant (ListBy t f) => Contravariant (WrapLB t f) where contramap f (WrapLB x) = WrapLB (contramap f x) | @since 0.3.0.0 instance Invariant (ListBy t f) => Invariant (WrapLB t f) where invmap f g (WrapLB x) = WrapLB (invmap f g x) instance (Tensor t i, FunctorBy t f, FunctorBy t (WrapLB t f)) => SemigroupIn (WrapHBF t) (WrapLB t f) where biretract = WrapLB . appendLB . hbimap unwrapLB unwrapLB . unwrapHBF binterpret f g = biretract . hbimap f g instance (Tensor t i, FunctorBy t f, FunctorBy t (WrapLB t f)) => MonoidIn (WrapHBF t) (WrapF i) (WrapLB t f) where pureT = WrapLB . nilLB @t . unwrapF
c59a3e17f31d289b75ec8f2a3c5feb216e5c88f4a77a66c8cc3f4354ffe2017c
apache/couchdb-mochiweb
mochitemp.erl
@author < > @copyright 2010 Mochi Media , Inc. %% %% 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. %% @doc Create temporary files and directories. Requires crypto to be started. -module(mochitemp). -export([gettempdir/0]). -export([mkdtemp/0, mkdtemp/3]). -export([rmtempdir/1]). %% -export([mkstemp/4]). -define(SAFE_CHARS, {$a, $b, $c, $d, $e, $f, $g, $h, $i, $j, $k, $l, $m, $n, $o, $p, $q, $r, $s, $t, $u, $v, $w, $x, $y, $z, $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O, $P, $Q, $R, $S, $T, $U, $V, $W, $X, $Y, $Z, $0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $_}). -define(TMP_MAX, 10000). -include_lib("kernel/include/file.hrl"). %% TODO: An ugly wrapper over the mktemp tool with open_port and sadness? We ca n't implement this race - free in Erlang without the ability %% to issue O_CREAT|O_EXCL. I suppose we could hack something with %% mkdtemp, del_dir, open. mkstemp(Suffix , Prefix , , Options ) - > %% ok. rmtempdir(Dir) -> case file:del_dir(Dir) of {error, eexist} -> ok = rmtempdirfiles(Dir), ok = file:del_dir(Dir); ok -> ok end. rmtempdirfiles(Dir) -> {ok, Files} = file:list_dir(Dir), ok = rmtempdirfiles(Dir, Files). rmtempdirfiles(_Dir, []) -> ok; rmtempdirfiles(Dir, [Basename | Rest]) -> Path = filename:join([Dir, Basename]), case filelib:is_dir(Path) of true -> ok = rmtempdir(Path); false -> ok = file:delete(Path) end, rmtempdirfiles(Dir, Rest). mkdtemp() -> mkdtemp("", "tmp", gettempdir()). mkdtemp(Suffix, Prefix, Dir) -> mkdtemp_n(rngpath_fun(Suffix, Prefix, Dir), ?TMP_MAX). mkdtemp_n(RngPath, 1) -> make_dir(RngPath()); mkdtemp_n(RngPath, N) -> try make_dir(RngPath()) catch throw:{error, eexist} -> mkdtemp_n(RngPath, N - 1) end. make_dir(Path) -> case file:make_dir(Path) of ok -> ok; E={error, eexist} -> throw(E) end, Small window for a race condition here because is created 777 ok = file:write_file_info(Path, #file_info{mode=8#0700}), Path. rngpath_fun(Prefix, Suffix, Dir) -> fun () -> filename:join([Dir, Prefix ++ rngchars(6) ++ Suffix]) end. rngchars(0) -> ""; rngchars(N) -> [rngchar() | rngchars(N - 1)]. rngchar() -> rngchar(mochiweb_util:rand_uniform(0, tuple_size(?SAFE_CHARS))). rngchar(C) -> element(1 + C, ?SAFE_CHARS). ( ) - > string ( ) @doc Get a usable temporary directory using the first of these that is a directory : $ TMPDIR , , $ TEMP , " /tmp " , " /var / tmp " , " /usr / tmp " , " . " . gettempdir() -> gettempdir(gettempdir_checks(), fun normalize_dir/1). gettempdir_checks() -> [{fun os:getenv/1, ["TMPDIR", "TMP", "TEMP"]}, {fun gettempdir_identity/1, ["/tmp", "/var/tmp", "/usr/tmp"]}, {fun gettempdir_cwd/1, [cwd]}]. gettempdir_identity(L) -> L. gettempdir_cwd(cwd) -> {ok, L} = file:get_cwd(), L. gettempdir([{_F, []} | RestF], Normalize) -> gettempdir(RestF, Normalize); gettempdir([{F, [L | RestL]} | RestF], Normalize) -> case Normalize(F(L)) of false -> gettempdir([{F, RestL} | RestF], Normalize); Dir -> Dir end. normalize_dir(False) when False =:= false orelse False =:= "" -> Erlang does n't have an unsetenv , wtf . false; normalize_dir(L) -> Dir = filename:absname(L), case filelib:is_dir(Dir) of false -> false; true -> Dir end. %% %% Tests %% -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). pushenv(L) -> [{K, os:getenv(K)} || K <- L]. popenv(L) -> F = fun ({K, false}) -> Erlang does n't have an unsetenv , wtf . os:putenv(K, ""); ({K, V}) -> os:putenv(K, V) end, lists:foreach(F, L). gettempdir_fallback_test() -> ?assertEqual( "/", gettempdir([{fun gettempdir_identity/1, ["/--not-here--/"]}, {fun gettempdir_identity/1, ["/"]}], fun normalize_dir/1)), ?assertEqual( "/", simulate a true os : unset env gettempdir([{fun gettempdir_identity/1, [false]}, {fun gettempdir_identity/1, ["/"]}], fun normalize_dir/1)), ok. gettempdir_identity_test() -> ?assertEqual( "/", gettempdir([{fun gettempdir_identity/1, ["/"]}], fun normalize_dir/1)), ok. gettempdir_cwd_test() -> {ok, Cwd} = file:get_cwd(), ?assertEqual( normalize_dir(Cwd), gettempdir([{fun gettempdir_cwd/1, [cwd]}], fun normalize_dir/1)), ok. rngchars_test() -> crypto:start(), ?assertEqual( "", rngchars(0)), ?assertEqual( 10, length(rngchars(10))), ok. rngchar_test() -> ?assertEqual( $a, rngchar(0)), ?assertEqual( $A, rngchar(26)), ?assertEqual( $_, rngchar(62)), ok. mkdtemp_n_failonce_test() -> crypto:start(), D = mkdtemp(), Path = filename:join([D, "testdir"]), %% Toggle the existence of a dir so that it fails the first time and succeeds the second . F = fun () -> case filelib:is_dir(Path) of true -> file:del_dir(Path); false -> file:make_dir(Path) end, Path end, try Fails the first time ?assertThrow( {error, eexist}, mkdtemp_n(F, 1)), %% Reset state file:del_dir(Path), Succeeds the second time ?assertEqual( Path, mkdtemp_n(F, 2)) after rmtempdir(D) end, ok. mkdtemp_n_fail_test() -> {ok, Cwd} = file:get_cwd(), ?assertThrow( {error, eexist}, mkdtemp_n(fun () -> Cwd end, 1)), ?assertThrow( {error, eexist}, mkdtemp_n(fun () -> Cwd end, 2)), ok. make_dir_fail_test() -> {ok, Cwd} = file:get_cwd(), ?assertThrow( {error, eexist}, make_dir(Cwd)), ok. mkdtemp_test() -> crypto:start(), D = mkdtemp(), ?assertEqual( true, filelib:is_dir(D)), ?assertEqual( ok, file:del_dir(D)), ok. rmtempdir_test() -> crypto:start(), D1 = mkdtemp(), ?assertEqual( true, filelib:is_dir(D1)), ?assertEqual( ok, rmtempdir(D1)), D2 = mkdtemp(), ?assertEqual( true, filelib:is_dir(D2)), ok = file:write_file(filename:join([D2, "foo"]), <<"bytes">>), D3 = mkdtemp("suffix", "prefix", D2), ?assertEqual( true, filelib:is_dir(D3)), ok = file:write_file(filename:join([D3, "foo"]), <<"bytes">>), ?assertEqual( ok, rmtempdir(D2)), ?assertEqual( {error, enoent}, file:consult(D3)), ?assertEqual( {error, enoent}, file:consult(D2)), ok. gettempdir_env_test() -> Env = pushenv(["TMPDIR", "TEMP", "TMP"]), FalseEnv = [{"TMPDIR", false}, {"TEMP", false}, {"TMP", false}], try popenv(FalseEnv), popenv([{"TMPDIR", "/"}]), ?assertEqual( "/", os:getenv("TMPDIR")), ?assertEqual( "/", gettempdir()), {ok, Cwd} = file:get_cwd(), popenv(FalseEnv), popenv([{"TMP", Cwd}]), ?assertEqual( normalize_dir(Cwd), gettempdir()) after popenv(Env) end, ok. -endif.
null
https://raw.githubusercontent.com/apache/couchdb-mochiweb/d3c47a9e8833cd878c9227093e30a2341ee32900/src/mochitemp.erl
erlang
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @doc Create temporary files and directories. Requires crypto to be started. -export([mkstemp/4]). TODO: An ugly wrapper over the mktemp tool with open_port and sadness? to issue O_CREAT|O_EXCL. I suppose we could hack something with mkdtemp, del_dir, open. ok. Tests Toggle the existence of a dir so that it fails Reset state
@author < > @copyright 2010 Mochi Media , Inc. to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING -module(mochitemp). -export([gettempdir/0]). -export([mkdtemp/0, mkdtemp/3]). -export([rmtempdir/1]). -define(SAFE_CHARS, {$a, $b, $c, $d, $e, $f, $g, $h, $i, $j, $k, $l, $m, $n, $o, $p, $q, $r, $s, $t, $u, $v, $w, $x, $y, $z, $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O, $P, $Q, $R, $S, $T, $U, $V, $W, $X, $Y, $Z, $0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $_}). -define(TMP_MAX, 10000). -include_lib("kernel/include/file.hrl"). We ca n't implement this race - free in Erlang without the ability mkstemp(Suffix , Prefix , , Options ) - > rmtempdir(Dir) -> case file:del_dir(Dir) of {error, eexist} -> ok = rmtempdirfiles(Dir), ok = file:del_dir(Dir); ok -> ok end. rmtempdirfiles(Dir) -> {ok, Files} = file:list_dir(Dir), ok = rmtempdirfiles(Dir, Files). rmtempdirfiles(_Dir, []) -> ok; rmtempdirfiles(Dir, [Basename | Rest]) -> Path = filename:join([Dir, Basename]), case filelib:is_dir(Path) of true -> ok = rmtempdir(Path); false -> ok = file:delete(Path) end, rmtempdirfiles(Dir, Rest). mkdtemp() -> mkdtemp("", "tmp", gettempdir()). mkdtemp(Suffix, Prefix, Dir) -> mkdtemp_n(rngpath_fun(Suffix, Prefix, Dir), ?TMP_MAX). mkdtemp_n(RngPath, 1) -> make_dir(RngPath()); mkdtemp_n(RngPath, N) -> try make_dir(RngPath()) catch throw:{error, eexist} -> mkdtemp_n(RngPath, N - 1) end. make_dir(Path) -> case file:make_dir(Path) of ok -> ok; E={error, eexist} -> throw(E) end, Small window for a race condition here because is created 777 ok = file:write_file_info(Path, #file_info{mode=8#0700}), Path. rngpath_fun(Prefix, Suffix, Dir) -> fun () -> filename:join([Dir, Prefix ++ rngchars(6) ++ Suffix]) end. rngchars(0) -> ""; rngchars(N) -> [rngchar() | rngchars(N - 1)]. rngchar() -> rngchar(mochiweb_util:rand_uniform(0, tuple_size(?SAFE_CHARS))). rngchar(C) -> element(1 + C, ?SAFE_CHARS). ( ) - > string ( ) @doc Get a usable temporary directory using the first of these that is a directory : $ TMPDIR , , $ TEMP , " /tmp " , " /var / tmp " , " /usr / tmp " , " . " . gettempdir() -> gettempdir(gettempdir_checks(), fun normalize_dir/1). gettempdir_checks() -> [{fun os:getenv/1, ["TMPDIR", "TMP", "TEMP"]}, {fun gettempdir_identity/1, ["/tmp", "/var/tmp", "/usr/tmp"]}, {fun gettempdir_cwd/1, [cwd]}]. gettempdir_identity(L) -> L. gettempdir_cwd(cwd) -> {ok, L} = file:get_cwd(), L. gettempdir([{_F, []} | RestF], Normalize) -> gettempdir(RestF, Normalize); gettempdir([{F, [L | RestL]} | RestF], Normalize) -> case Normalize(F(L)) of false -> gettempdir([{F, RestL} | RestF], Normalize); Dir -> Dir end. normalize_dir(False) when False =:= false orelse False =:= "" -> Erlang does n't have an unsetenv , wtf . false; normalize_dir(L) -> Dir = filename:absname(L), case filelib:is_dir(Dir) of false -> false; true -> Dir end. -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). pushenv(L) -> [{K, os:getenv(K)} || K <- L]. popenv(L) -> F = fun ({K, false}) -> Erlang does n't have an unsetenv , wtf . os:putenv(K, ""); ({K, V}) -> os:putenv(K, V) end, lists:foreach(F, L). gettempdir_fallback_test() -> ?assertEqual( "/", gettempdir([{fun gettempdir_identity/1, ["/--not-here--/"]}, {fun gettempdir_identity/1, ["/"]}], fun normalize_dir/1)), ?assertEqual( "/", simulate a true os : unset env gettempdir([{fun gettempdir_identity/1, [false]}, {fun gettempdir_identity/1, ["/"]}], fun normalize_dir/1)), ok. gettempdir_identity_test() -> ?assertEqual( "/", gettempdir([{fun gettempdir_identity/1, ["/"]}], fun normalize_dir/1)), ok. gettempdir_cwd_test() -> {ok, Cwd} = file:get_cwd(), ?assertEqual( normalize_dir(Cwd), gettempdir([{fun gettempdir_cwd/1, [cwd]}], fun normalize_dir/1)), ok. rngchars_test() -> crypto:start(), ?assertEqual( "", rngchars(0)), ?assertEqual( 10, length(rngchars(10))), ok. rngchar_test() -> ?assertEqual( $a, rngchar(0)), ?assertEqual( $A, rngchar(26)), ?assertEqual( $_, rngchar(62)), ok. mkdtemp_n_failonce_test() -> crypto:start(), D = mkdtemp(), Path = filename:join([D, "testdir"]), the first time and succeeds the second . F = fun () -> case filelib:is_dir(Path) of true -> file:del_dir(Path); false -> file:make_dir(Path) end, Path end, try Fails the first time ?assertThrow( {error, eexist}, mkdtemp_n(F, 1)), file:del_dir(Path), Succeeds the second time ?assertEqual( Path, mkdtemp_n(F, 2)) after rmtempdir(D) end, ok. mkdtemp_n_fail_test() -> {ok, Cwd} = file:get_cwd(), ?assertThrow( {error, eexist}, mkdtemp_n(fun () -> Cwd end, 1)), ?assertThrow( {error, eexist}, mkdtemp_n(fun () -> Cwd end, 2)), ok. make_dir_fail_test() -> {ok, Cwd} = file:get_cwd(), ?assertThrow( {error, eexist}, make_dir(Cwd)), ok. mkdtemp_test() -> crypto:start(), D = mkdtemp(), ?assertEqual( true, filelib:is_dir(D)), ?assertEqual( ok, file:del_dir(D)), ok. rmtempdir_test() -> crypto:start(), D1 = mkdtemp(), ?assertEqual( true, filelib:is_dir(D1)), ?assertEqual( ok, rmtempdir(D1)), D2 = mkdtemp(), ?assertEqual( true, filelib:is_dir(D2)), ok = file:write_file(filename:join([D2, "foo"]), <<"bytes">>), D3 = mkdtemp("suffix", "prefix", D2), ?assertEqual( true, filelib:is_dir(D3)), ok = file:write_file(filename:join([D3, "foo"]), <<"bytes">>), ?assertEqual( ok, rmtempdir(D2)), ?assertEqual( {error, enoent}, file:consult(D3)), ?assertEqual( {error, enoent}, file:consult(D2)), ok. gettempdir_env_test() -> Env = pushenv(["TMPDIR", "TEMP", "TMP"]), FalseEnv = [{"TMPDIR", false}, {"TEMP", false}, {"TMP", false}], try popenv(FalseEnv), popenv([{"TMPDIR", "/"}]), ?assertEqual( "/", os:getenv("TMPDIR")), ?assertEqual( "/", gettempdir()), {ok, Cwd} = file:get_cwd(), popenv(FalseEnv), popenv([{"TMP", Cwd}]), ?assertEqual( normalize_dir(Cwd), gettempdir()) after popenv(Env) end, ok. -endif.
4ef53af7766ff6d62f51a5f02949bb1b67a60566ab97e8c64307d20514048db1
bmeurer/ocamljit2
array.ml
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) $ Id$ (* Array operations *) external length : 'a array -> int = "%array_length" external get: 'a array -> int -> 'a = "%array_safe_get" external set: 'a array -> int -> 'a -> unit = "%array_safe_set" external unsafe_get: 'a array -> int -> 'a = "%array_unsafe_get" external unsafe_set: 'a array -> int -> 'a -> unit = "%array_unsafe_set" external make: int -> 'a -> 'a array = "caml_make_vect" external create: int -> 'a -> 'a array = "caml_make_vect" let init l f = if l = 0 then [||] else let res = create l (f 0) in for i = 1 to pred l do unsafe_set res i (f i) done; res let make_matrix sx sy init = let res = create sx [||] in for x = 0 to pred sx do unsafe_set res x (create sy init) done; res let create_matrix = make_matrix let copy a = let l = length a in if l = 0 then [||] else begin let res = create l (unsafe_get a 0) in for i = 1 to pred l do unsafe_set res i (unsafe_get a i) done; res end let append a1 a2 = let l1 = length a1 and l2 = length a2 in if l1 = 0 && l2 = 0 then [||] else begin let r = create (l1 + l2) (unsafe_get (if l1 > 0 then a1 else a2) 0) in for i = 0 to l1 - 1 do unsafe_set r i (unsafe_get a1 i) done; for i = 0 to l2 - 1 do unsafe_set r (i + l1) (unsafe_get a2 i) done; r end let concat_aux init al = let rec size accu = function | [] -> accu | h::t -> size (accu + length h) t in let res = create (size 0 al) init in let rec fill pos = function | [] -> () | h::t -> for i = 0 to length h - 1 do unsafe_set res (pos + i) (unsafe_get h i); done; fill (pos + length h) t; in fill 0 al; res ;; let concat al = let rec find_init aa = match aa with | [] -> [||] | a :: rem -> if length a > 0 then concat_aux (unsafe_get a 0) aa else find_init rem in find_init al let sub a ofs len = if ofs < 0 || len < 0 || ofs > length a - len then invalid_arg "Array.sub" else if len = 0 then [||] else begin let r = create len (unsafe_get a ofs) in for i = 1 to len - 1 do unsafe_set r i (unsafe_get a (ofs + i)) done; r end let fill a ofs len v = if ofs < 0 || len < 0 || ofs > length a - len then invalid_arg "Array.fill" else for i = ofs to ofs + len - 1 do unsafe_set a i v done let blit a1 ofs1 a2 ofs2 len = if len < 0 || ofs1 < 0 || ofs1 > length a1 - len || ofs2 < 0 || ofs2 > length a2 - len then invalid_arg "Array.blit" else if ofs1 < ofs2 then (* Top-down copy *) for i = len - 1 downto 0 do unsafe_set a2 (ofs2 + i) (unsafe_get a1 (ofs1 + i)) done else (* Bottom-up copy *) for i = 0 to len - 1 do unsafe_set a2 (ofs2 + i) (unsafe_get a1 (ofs1 + i)) done let iter f a = for i = 0 to length a - 1 do f(unsafe_get a i) done let map f a = let l = length a in if l = 0 then [||] else begin let r = create l (f(unsafe_get a 0)) in for i = 1 to l - 1 do unsafe_set r i (f(unsafe_get a i)) done; r end let iteri f a = for i = 0 to length a - 1 do f i (unsafe_get a i) done let mapi f a = let l = length a in if l = 0 then [||] else begin let r = create l (f 0 (unsafe_get a 0)) in for i = 1 to l - 1 do unsafe_set r i (f i (unsafe_get a i)) done; r end let to_list a = let rec tolist i res = if i < 0 then res else tolist (i - 1) (unsafe_get a i :: res) in tolist (length a - 1) [] Can not use here because the List module depends on Array . let rec list_length accu = function | [] -> accu | h::t -> list_length (succ accu) t ;; let of_list = function [] -> [||] | hd::tl as l -> let a = create (list_length 0 l) hd in let rec fill i = function [] -> a | hd::tl -> unsafe_set a i hd; fill (i+1) tl in fill 1 tl let fold_left f x a = let r = ref x in for i = 0 to length a - 1 do r := f !r (unsafe_get a i) done; !r let fold_right f a x = let r = ref x in for i = length a - 1 downto 0 do r := f (unsafe_get a i) !r done; !r exception Bottom of int;; let sort cmp a = let maxson l i = let i31 = i+i+i+1 in let x = ref i31 in if i31+2 < l then begin if cmp (get a i31) (get a (i31+1)) < 0 then x := i31+1; if cmp (get a !x) (get a (i31+2)) < 0 then x := i31+2; !x end else if i31+1 < l && cmp (get a i31) (get a (i31+1)) < 0 then i31+1 else if i31 < l then i31 else raise (Bottom i) in let rec trickledown l i e = let j = maxson l i in if cmp (get a j) e > 0 then begin set a i (get a j); trickledown l j e; end else begin set a i e; end; in let rec trickle l i e = try trickledown l i e with Bottom i -> set a i e in let rec bubbledown l i = let j = maxson l i in set a i (get a j); bubbledown l j in let bubble l i = try bubbledown l i with Bottom i -> i in let rec trickleup i e = let father = (i - 1) / 3 in assert (i <> father); if cmp (get a father) e < 0 then begin set a i (get a father); if father > 0 then trickleup father e else set a 0 e; end else begin set a i e; end; in let l = length a in for i = (l + 1) / 3 - 1 downto 0 do trickle l i (get a i); done; for i = l - 1 downto 2 do let e = (get a i) in set a i (get a 0); trickleup (bubble i 0) e; done; if l > 1 then (let e = (get a 1) in set a 1 (get a 0); set a 0 e); ;; let cutoff = 5;; let stable_sort cmp a = let merge src1ofs src1len src2 src2ofs src2len dst dstofs = let src1r = src1ofs + src1len and src2r = src2ofs + src2len in let rec loop i1 s1 i2 s2 d = if cmp s1 s2 <= 0 then begin set dst d s1; let i1 = i1 + 1 in if i1 < src1r then loop i1 (get a i1) i2 s2 (d + 1) else blit src2 i2 dst (d + 1) (src2r - i2) end else begin set dst d s2; let i2 = i2 + 1 in if i2 < src2r then loop i1 s1 i2 (get src2 i2) (d + 1) else blit a i1 dst (d + 1) (src1r - i1) end in loop src1ofs (get a src1ofs) src2ofs (get src2 src2ofs) dstofs; in let isortto srcofs dst dstofs len = for i = 0 to len - 1 do let e = (get a (srcofs + i)) in let j = ref (dstofs + i - 1) in while (!j >= dstofs && cmp (get dst !j) e > 0) do set dst (!j + 1) (get dst !j); decr j; done; set dst (!j + 1) e; done; in let rec sortto srcofs dst dstofs len = if len <= cutoff then isortto srcofs dst dstofs len else begin let l1 = len / 2 in let l2 = len - l1 in sortto (srcofs + l1) dst (dstofs + l1) l2; sortto srcofs a (srcofs + l2) l1; merge (srcofs + l2) l1 dst (dstofs + l1) l2 dst dstofs; end; in let l = length a in if l <= cutoff then isortto 0 a 0 l else begin let l1 = l / 2 in let l2 = l - l1 in let t = make l2 (get a 0) in sortto l1 t 0 l2; sortto 0 a l2 l1; merge l2 l1 t 0 l2 a 0; end; ;; let fast_sort = stable_sort;;
null
https://raw.githubusercontent.com/bmeurer/ocamljit2/ef06db5c688c1160acc1de1f63c29473bcd0055c/stdlib/array.ml
ocaml
********************************************************************* Objective Caml the special exception on linking described in file ../LICENSE. ********************************************************************* Array operations Top-down copy Bottom-up copy
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with $ Id$ external length : 'a array -> int = "%array_length" external get: 'a array -> int -> 'a = "%array_safe_get" external set: 'a array -> int -> 'a -> unit = "%array_safe_set" external unsafe_get: 'a array -> int -> 'a = "%array_unsafe_get" external unsafe_set: 'a array -> int -> 'a -> unit = "%array_unsafe_set" external make: int -> 'a -> 'a array = "caml_make_vect" external create: int -> 'a -> 'a array = "caml_make_vect" let init l f = if l = 0 then [||] else let res = create l (f 0) in for i = 1 to pred l do unsafe_set res i (f i) done; res let make_matrix sx sy init = let res = create sx [||] in for x = 0 to pred sx do unsafe_set res x (create sy init) done; res let create_matrix = make_matrix let copy a = let l = length a in if l = 0 then [||] else begin let res = create l (unsafe_get a 0) in for i = 1 to pred l do unsafe_set res i (unsafe_get a i) done; res end let append a1 a2 = let l1 = length a1 and l2 = length a2 in if l1 = 0 && l2 = 0 then [||] else begin let r = create (l1 + l2) (unsafe_get (if l1 > 0 then a1 else a2) 0) in for i = 0 to l1 - 1 do unsafe_set r i (unsafe_get a1 i) done; for i = 0 to l2 - 1 do unsafe_set r (i + l1) (unsafe_get a2 i) done; r end let concat_aux init al = let rec size accu = function | [] -> accu | h::t -> size (accu + length h) t in let res = create (size 0 al) init in let rec fill pos = function | [] -> () | h::t -> for i = 0 to length h - 1 do unsafe_set res (pos + i) (unsafe_get h i); done; fill (pos + length h) t; in fill 0 al; res ;; let concat al = let rec find_init aa = match aa with | [] -> [||] | a :: rem -> if length a > 0 then concat_aux (unsafe_get a 0) aa else find_init rem in find_init al let sub a ofs len = if ofs < 0 || len < 0 || ofs > length a - len then invalid_arg "Array.sub" else if len = 0 then [||] else begin let r = create len (unsafe_get a ofs) in for i = 1 to len - 1 do unsafe_set r i (unsafe_get a (ofs + i)) done; r end let fill a ofs len v = if ofs < 0 || len < 0 || ofs > length a - len then invalid_arg "Array.fill" else for i = ofs to ofs + len - 1 do unsafe_set a i v done let blit a1 ofs1 a2 ofs2 len = if len < 0 || ofs1 < 0 || ofs1 > length a1 - len || ofs2 < 0 || ofs2 > length a2 - len then invalid_arg "Array.blit" else if ofs1 < ofs2 then for i = len - 1 downto 0 do unsafe_set a2 (ofs2 + i) (unsafe_get a1 (ofs1 + i)) done else for i = 0 to len - 1 do unsafe_set a2 (ofs2 + i) (unsafe_get a1 (ofs1 + i)) done let iter f a = for i = 0 to length a - 1 do f(unsafe_get a i) done let map f a = let l = length a in if l = 0 then [||] else begin let r = create l (f(unsafe_get a 0)) in for i = 1 to l - 1 do unsafe_set r i (f(unsafe_get a i)) done; r end let iteri f a = for i = 0 to length a - 1 do f i (unsafe_get a i) done let mapi f a = let l = length a in if l = 0 then [||] else begin let r = create l (f 0 (unsafe_get a 0)) in for i = 1 to l - 1 do unsafe_set r i (f i (unsafe_get a i)) done; r end let to_list a = let rec tolist i res = if i < 0 then res else tolist (i - 1) (unsafe_get a i :: res) in tolist (length a - 1) [] Can not use here because the List module depends on Array . let rec list_length accu = function | [] -> accu | h::t -> list_length (succ accu) t ;; let of_list = function [] -> [||] | hd::tl as l -> let a = create (list_length 0 l) hd in let rec fill i = function [] -> a | hd::tl -> unsafe_set a i hd; fill (i+1) tl in fill 1 tl let fold_left f x a = let r = ref x in for i = 0 to length a - 1 do r := f !r (unsafe_get a i) done; !r let fold_right f a x = let r = ref x in for i = length a - 1 downto 0 do r := f (unsafe_get a i) !r done; !r exception Bottom of int;; let sort cmp a = let maxson l i = let i31 = i+i+i+1 in let x = ref i31 in if i31+2 < l then begin if cmp (get a i31) (get a (i31+1)) < 0 then x := i31+1; if cmp (get a !x) (get a (i31+2)) < 0 then x := i31+2; !x end else if i31+1 < l && cmp (get a i31) (get a (i31+1)) < 0 then i31+1 else if i31 < l then i31 else raise (Bottom i) in let rec trickledown l i e = let j = maxson l i in if cmp (get a j) e > 0 then begin set a i (get a j); trickledown l j e; end else begin set a i e; end; in let rec trickle l i e = try trickledown l i e with Bottom i -> set a i e in let rec bubbledown l i = let j = maxson l i in set a i (get a j); bubbledown l j in let bubble l i = try bubbledown l i with Bottom i -> i in let rec trickleup i e = let father = (i - 1) / 3 in assert (i <> father); if cmp (get a father) e < 0 then begin set a i (get a father); if father > 0 then trickleup father e else set a 0 e; end else begin set a i e; end; in let l = length a in for i = (l + 1) / 3 - 1 downto 0 do trickle l i (get a i); done; for i = l - 1 downto 2 do let e = (get a i) in set a i (get a 0); trickleup (bubble i 0) e; done; if l > 1 then (let e = (get a 1) in set a 1 (get a 0); set a 0 e); ;; let cutoff = 5;; let stable_sort cmp a = let merge src1ofs src1len src2 src2ofs src2len dst dstofs = let src1r = src1ofs + src1len and src2r = src2ofs + src2len in let rec loop i1 s1 i2 s2 d = if cmp s1 s2 <= 0 then begin set dst d s1; let i1 = i1 + 1 in if i1 < src1r then loop i1 (get a i1) i2 s2 (d + 1) else blit src2 i2 dst (d + 1) (src2r - i2) end else begin set dst d s2; let i2 = i2 + 1 in if i2 < src2r then loop i1 s1 i2 (get src2 i2) (d + 1) else blit a i1 dst (d + 1) (src1r - i1) end in loop src1ofs (get a src1ofs) src2ofs (get src2 src2ofs) dstofs; in let isortto srcofs dst dstofs len = for i = 0 to len - 1 do let e = (get a (srcofs + i)) in let j = ref (dstofs + i - 1) in while (!j >= dstofs && cmp (get dst !j) e > 0) do set dst (!j + 1) (get dst !j); decr j; done; set dst (!j + 1) e; done; in let rec sortto srcofs dst dstofs len = if len <= cutoff then isortto srcofs dst dstofs len else begin let l1 = len / 2 in let l2 = len - l1 in sortto (srcofs + l1) dst (dstofs + l1) l2; sortto srcofs a (srcofs + l2) l1; merge (srcofs + l2) l1 dst (dstofs + l1) l2 dst dstofs; end; in let l = length a in if l <= cutoff then isortto 0 a 0 l else begin let l1 = l / 2 in let l2 = l - l1 in let t = make l2 (get a 0) in sortto l1 t 0 l2; sortto 0 a l2 l1; merge l2 l1 t 0 l2 a 0; end; ;; let fast_sort = stable_sort;;
a7ea3e11bd3ab0b2a7ad1518e71dd139547bb2c1da011f86e331fe9e4986cf8c
SovereignShop/codenames
game.cljs
(ns ^:figwheel-always codenames.views.game (:require [codenames.subs.game :as game-subs] [codenames.subs.session :as session-subs] [codenames.subs.stats :as stat-subs] [codenames.constants.ui-idents :as idents] [codenames.constants.ui-tabs :as tabs] [codenames.events.game :as game-events] [codenames.events.pregame :as pregame-events] [codenames.db :as db] [swig.views :as swig-view] [re-posh.core :as re-posh] [re-com.core :as com :refer [h-box v-box box button gap scroller input-text]])) (defn popover! [content label title] (re-posh/dispatch [:codenames.events.popover/show [:swig/ident idents/main-popover] {:popover/content content :popover/showing? true :popover/label label :popover/title title}])) (defn display-card [game-id {:keys [:codenames.word-card/word :codenames.word-card/position :codenames.word-card/character-card] :as card}] (let [character-card-id (:db/id character-card) player-type @(re-posh/subscribe [::game-subs/player-type game-id]) codemaster? (= player-type :codemaster) card @(re-posh/subscribe [::game-subs/character-card character-card-id]) played? (:codenames.character-card/played? card) role (:codenames.character-card/role card) word-color (if (= role :assassin) "white" "black")] [box :attr {:on-click #(re-posh/dispatch [::game-events/card-click game-id character-card-id])} :style {:text-align "center" :padding "12px" :border-radius "3px" :box-shadow (if played? "3px 3px 2px grey" "") :background-color (if (or codemaster? played?) (case role :neutral (if played? "#ff9933" "#ffb366") :blue (if played? "#0040ff" "#00bfff") :red (if played? "#990000" "#cc0000") :assassin "black") "white")} :child [:h4 {:style {:text-align :center :color (if (or codemaster? played?) "white" "black")}} word]])) (defn game-score [game-id] (let [red-remaining @(re-posh/subscribe [::game-subs/red-cards-remaining game-id]) blue-remaining @(re-posh/subscribe [::game-subs/blue-cards-remaining game-id])] [h-box :max-width "60px" :style {:width "50px"} :children [[:div {:style {:color "red" :width "20px"}} red-remaining] [:div {:style {:color "blue" :width "20px"}} blue-remaining]]])) (defn board-info [tab-id game-id cards] (let [current-team @(re-posh/subscribe [::game-subs/current-team game-id]) team-color (:codenames.team/color current-team) [winning-team winning-color] @(re-posh/subscribe [::game-subs/game-over game-id])] #_(when winning-team (re-posh/dispatch [::game-events/set-winning-team game-id winning-team])) [h-box :class "center" :gap "20px" :children [[button :on-click #(re-posh/dispatch [::pregame-events/new-round game-id]) :label "New Round"] [button :on-click #(re-posh/dispatch [::pregame-events/enter-pregame tab-id]) :label "Exit Game"] [button :label "End Turn" :on-click #(re-posh/dispatch [::game-events/end-turn game-id])] [game-score game-id] (case team-color :blue [:div {:style {:color "Blue" :width "125px"}} "Blue Team's Turn"] :red [:div {:style {:color "Red" :width "125px"}} "Red Team's Turn"] [:div (str "Error.. " current-team)]) (case winning-color :red [:div {:style {:color "red"}} "Red team wins!"] :blue [:div {:style {:color "blue"}} "Blue team wins!"] nil)]])) (defn board-grid [game-id cards] (let [cards (->> cards (sort-by :codenames.word-card/position) (partition (first db/board-dimensions)))] [:div #_{:class "center"} [:table.center {:style {:border-spacing "10px" :border-collapse "separate"}} [:tbody (for [row cards] [:tr (for [card row] [:td [display-card game-id card]])])]]])) (defn turn-handler [game-id] (let [turn @(re-posh/subscribe [::game-subs/current-turn game-id]) turn-id (:db/id turn) player-type @(re-posh/subscribe [::game-subs/player-type game-id]) codemaster? (= player-type :codemaster) submitted? (:codenames.turn/submitted? turn)] (if (and codemaster? (not submitted?)) [h-box :class "center" :children [[input-text :model (str (:codenames.turn/word turn)) :placeholder "word" :on-change #(re-posh/dispatch [::game-events/set-word turn-id %])] [input-text :model (str (:codenames.turn/number turn)) :placeholder "number" :on-change #(re-posh/dispatch [::game-events/set-number turn-id %])] [button :label "Submit" :on-click #(re-posh/dispatch [::game-events/submit-clue turn-id])]]] (when submitted? [h-box :class "center" :children [[box :child (str (:codenames.turn/word turn))] [gap :size "10px"] [box :child (str (:codenames.turn/number turn))]]])))) (defmethod swig-view/dispatch tabs/game-board [{tab-id :db/id}] (when-let [game-id @(re-posh/subscribe [::session-subs/game])] (let [cards @(re-posh/subscribe [::game-subs/word-cards game-id])] [v-box :width "100%" :children [[board-info tab-id game-id cards] [turn-handler game-id] [scroller :style {:flex "1 1 0%"} :child [board-grid game-id cards]]]]))) (defmethod swig-view/dispatch tabs/leader-board [tab] [:div "Leader Board"] #_(let [stats @(re-posh/subscribe [::stat-subs/leader-board])] [:table [:thead [:tr [:td "Name"] [:td "CM Wins"] [:td "CM Losses"] [:td "Wins"] [:td "Losses"]]] [:tbody (for [stat stats] [:tr (for [s stat] [:td (str s)])])]])) (defmethod swig-view/dispatch tabs/score-board [tab] (let [tab-id (:db/id tab) src @(re-posh/subscribe [::game-subs/get-browser-src tab-id])] [v-box :style {:flex "1 1 0%"} :children [[input-text :width "100%" :model (or (str src) "") :on-change #(re-posh/dispatch [::game-events/set-browser-src tab-id %]) :change-on-blur? true] [:iframe {:width "100%" :height "100%" :target "_parent" :allow "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" :allowfullscreen true :on-load #(let [new-src (-> % .-target .-contentWindow)] #_(when (not= new-src src) (re-posh/dispatch [::game-events/set-browser-src tab-id new-src]))) :src (or src "")}]]]))
null
https://raw.githubusercontent.com/SovereignShop/codenames/0a3d5f52b0a704341801bb7125b054a4323bcf19/src/cljs/codenames/views/game.cljs
clojure
(ns ^:figwheel-always codenames.views.game (:require [codenames.subs.game :as game-subs] [codenames.subs.session :as session-subs] [codenames.subs.stats :as stat-subs] [codenames.constants.ui-idents :as idents] [codenames.constants.ui-tabs :as tabs] [codenames.events.game :as game-events] [codenames.events.pregame :as pregame-events] [codenames.db :as db] [swig.views :as swig-view] [re-posh.core :as re-posh] [re-com.core :as com :refer [h-box v-box box button gap scroller input-text]])) (defn popover! [content label title] (re-posh/dispatch [:codenames.events.popover/show [:swig/ident idents/main-popover] {:popover/content content :popover/showing? true :popover/label label :popover/title title}])) (defn display-card [game-id {:keys [:codenames.word-card/word :codenames.word-card/position :codenames.word-card/character-card] :as card}] (let [character-card-id (:db/id character-card) player-type @(re-posh/subscribe [::game-subs/player-type game-id]) codemaster? (= player-type :codemaster) card @(re-posh/subscribe [::game-subs/character-card character-card-id]) played? (:codenames.character-card/played? card) role (:codenames.character-card/role card) word-color (if (= role :assassin) "white" "black")] [box :attr {:on-click #(re-posh/dispatch [::game-events/card-click game-id character-card-id])} :style {:text-align "center" :padding "12px" :border-radius "3px" :box-shadow (if played? "3px 3px 2px grey" "") :background-color (if (or codemaster? played?) (case role :neutral (if played? "#ff9933" "#ffb366") :blue (if played? "#0040ff" "#00bfff") :red (if played? "#990000" "#cc0000") :assassin "black") "white")} :child [:h4 {:style {:text-align :center :color (if (or codemaster? played?) "white" "black")}} word]])) (defn game-score [game-id] (let [red-remaining @(re-posh/subscribe [::game-subs/red-cards-remaining game-id]) blue-remaining @(re-posh/subscribe [::game-subs/blue-cards-remaining game-id])] [h-box :max-width "60px" :style {:width "50px"} :children [[:div {:style {:color "red" :width "20px"}} red-remaining] [:div {:style {:color "blue" :width "20px"}} blue-remaining]]])) (defn board-info [tab-id game-id cards] (let [current-team @(re-posh/subscribe [::game-subs/current-team game-id]) team-color (:codenames.team/color current-team) [winning-team winning-color] @(re-posh/subscribe [::game-subs/game-over game-id])] #_(when winning-team (re-posh/dispatch [::game-events/set-winning-team game-id winning-team])) [h-box :class "center" :gap "20px" :children [[button :on-click #(re-posh/dispatch [::pregame-events/new-round game-id]) :label "New Round"] [button :on-click #(re-posh/dispatch [::pregame-events/enter-pregame tab-id]) :label "Exit Game"] [button :label "End Turn" :on-click #(re-posh/dispatch [::game-events/end-turn game-id])] [game-score game-id] (case team-color :blue [:div {:style {:color "Blue" :width "125px"}} "Blue Team's Turn"] :red [:div {:style {:color "Red" :width "125px"}} "Red Team's Turn"] [:div (str "Error.. " current-team)]) (case winning-color :red [:div {:style {:color "red"}} "Red team wins!"] :blue [:div {:style {:color "blue"}} "Blue team wins!"] nil)]])) (defn board-grid [game-id cards] (let [cards (->> cards (sort-by :codenames.word-card/position) (partition (first db/board-dimensions)))] [:div #_{:class "center"} [:table.center {:style {:border-spacing "10px" :border-collapse "separate"}} [:tbody (for [row cards] [:tr (for [card row] [:td [display-card game-id card]])])]]])) (defn turn-handler [game-id] (let [turn @(re-posh/subscribe [::game-subs/current-turn game-id]) turn-id (:db/id turn) player-type @(re-posh/subscribe [::game-subs/player-type game-id]) codemaster? (= player-type :codemaster) submitted? (:codenames.turn/submitted? turn)] (if (and codemaster? (not submitted?)) [h-box :class "center" :children [[input-text :model (str (:codenames.turn/word turn)) :placeholder "word" :on-change #(re-posh/dispatch [::game-events/set-word turn-id %])] [input-text :model (str (:codenames.turn/number turn)) :placeholder "number" :on-change #(re-posh/dispatch [::game-events/set-number turn-id %])] [button :label "Submit" :on-click #(re-posh/dispatch [::game-events/submit-clue turn-id])]]] (when submitted? [h-box :class "center" :children [[box :child (str (:codenames.turn/word turn))] [gap :size "10px"] [box :child (str (:codenames.turn/number turn))]]])))) (defmethod swig-view/dispatch tabs/game-board [{tab-id :db/id}] (when-let [game-id @(re-posh/subscribe [::session-subs/game])] (let [cards @(re-posh/subscribe [::game-subs/word-cards game-id])] [v-box :width "100%" :children [[board-info tab-id game-id cards] [turn-handler game-id] [scroller :style {:flex "1 1 0%"} :child [board-grid game-id cards]]]]))) (defmethod swig-view/dispatch tabs/leader-board [tab] [:div "Leader Board"] #_(let [stats @(re-posh/subscribe [::stat-subs/leader-board])] [:table [:thead [:tr [:td "Name"] [:td "CM Wins"] [:td "CM Losses"] [:td "Wins"] [:td "Losses"]]] [:tbody (for [stat stats] [:tr (for [s stat] [:td (str s)])])]])) (defmethod swig-view/dispatch tabs/score-board [tab] (let [tab-id (:db/id tab) src @(re-posh/subscribe [::game-subs/get-browser-src tab-id])] [v-box :style {:flex "1 1 0%"} :children [[input-text :width "100%" :model (or (str src) "") :on-change #(re-posh/dispatch [::game-events/set-browser-src tab-id %]) :change-on-blur? true] [:iframe {:width "100%" :height "100%" :target "_parent" :allow "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" :allowfullscreen true :on-load #(let [new-src (-> % .-target .-contentWindow)] #_(when (not= new-src src) (re-posh/dispatch [::game-events/set-browser-src tab-id new-src]))) :src (or src "")}]]]))
3c797e3cf82c1e09ac880624e2c673cc0a9a56604fdc6a932e52c9b9768c7103
sbcl/sbcl
braid.lisp
;;;; bootstrapping the meta-braid ;;;; ;;;; The code in this file takes the early definitions that have been ;;;; saved up and actually builds those class objects. This work is ;;;; largely driven off of those class definitions, but the fact that ;;;; STANDARD-CLASS is the class of all metaclasses in the braid is ;;;; built into this code pretty deeply. This software is part of the SBCL system . See the README file for ;;;; more information. This software is derived from software originally released by Xerox ;;;; Corporation. Copyright and release statements follow. Later modifications ;;;; to the software are in the public domain and are provided with ;;;; absolutely no warranty. See the COPYING and CREDITS files for more ;;;; information. copyright information from original PCL sources : ;;;; Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation . ;;;; All rights reserved. ;;;; ;;;; Use and copying of this software and preparation of derivative works based ;;;; upon this software are permitted. Any distribution of this software or derivative works must comply with all applicable United States export ;;;; control laws. ;;;; This software is made available AS IS , and Xerox Corporation makes no ;;;; warranty about the software, its performance or its conformity to any ;;;; specification. (in-package "SB-PCL") (defun !bootstrap-accessor-definitions (early-p) (let ((*early-p* early-p)) (dolist (definition *!early-class-definitions*) (let ((name (ecd-class-name definition)) (meta (ecd-metaclass definition))) (unless (or (eq meta 'built-in-class) (eq meta 'system-class)) (let ((direct-slots (ecd-canonical-slots definition))) (dolist (slotd direct-slots) (let ((slot-name (getf slotd :name)) (readers (getf slotd :readers)) (writers (getf slotd :writers))) (!bootstrap-accessor-definitions1 name slot-name readers writers (ecd-source-location definition)))))))))) (defun !bootstrap-accessor-definition (class-name accessor-name slot-name type source-location) (multiple-value-bind (accessor-class make-method-function arglist specls doc) (ecase type (reader (values 'standard-reader-method #'make-std-reader-method-function (list class-name) (list class-name) "automatically generated reader method")) (writer (values 'standard-writer-method #'make-std-writer-method-function (list 'new-value class-name) (list t class-name) "automatically generated writer method"))) (let ((gf (ensure-generic-function accessor-name :lambda-list arglist))) (if (find specls (early-gf-methods gf) :key #'early-method-specializers :test 'equal) (unless (assoc accessor-name *!generic-function-fixups* :test #'equal) (update-dfun gf)) (add-method gf (make-a-method accessor-class () arglist specls (funcall make-method-function class-name slot-name) doc :slot-name slot-name :object-class class-name :method-class-function (constantly (find-class accessor-class)) 'source source-location)))))) (defun !bootstrap-accessor-definitions1 (class-name slot-name readers writers source-location) (flet ((do-reader-definition (reader) (!bootstrap-accessor-definition class-name reader slot-name 'reader source-location)) (do-writer-definition (writer) (!bootstrap-accessor-definition class-name writer slot-name 'writer source-location))) (dolist (reader readers) (do-reader-definition reader)) (dolist (writer writers) (do-writer-definition writer)))) (defun class-of (x) (declare (explicit-check)) (wrapper-class (wrapper-of x))) (defun eval-form (form) (lambda () (eval form))) (defun ensure-non-standard-class (name classoid &optional existing-class extra-data) (labels ((ensure (metaclass slots) (let ((supers (mapcar #'classoid-name (classoid-direct-superclasses classoid)))) (ensure-class-using-class existing-class name :metaclass metaclass :name name :direct-superclasses supers :direct-slots slots))) (slot-initargs-from-structure-slotd (slotd writer-fn reader-fn) (flet ((name->fun (f) (if (functionp f) f (fdefinition f)))) `(:name ,(dsd-name slotd) :defstruct-accessor-symbol ,(dsd-accessor-name slotd) :internal-reader-function ,(name->fun reader-fn) :internal-writer-function ,(name->fun writer-fn) :always-bound-p ,(dsd-always-boundp slotd) :type ,(dsd-type slotd) :initform ,(dsd-default slotd) This is nuts ! any DEFAULT might need its lexical environment , yet we EVAL in the null environment . :initfunction ,(eval-form (dsd-default slotd))))) (accessor-closures (dsd) (multiple-value-bind (reader-fn writer-fn) (sb-kernel::dsd-reader dsd nil) ;; This is for a structure class that exists only in its compile-time representation. ;; I don't see how these would get called, since you can't make an instance ;; of the structure. (list (lambda (newval object) (funcall writer-fn newval object) newval) (lambda (object) (funcall reader-fn object))))) (structure-type-slot-description-list (type) (let* ((dd (find-defstruct-description type)) (include (dd-include dd)) (all-slots (dd-slots dd))) (unless extra-data (acond ((assoc (dd-name dd) sb-kernel::*struct-accesss-fragments-delayed*) (let ((fragments (cdr it))) (dolist (dsd (dd-slots dd)) (push (list dsd (pop fragments) (pop fragments)) extra-data))) (setq sb-kernel::*struct-accesss-fragments-delayed* (delete it sb-kernel::*struct-accesss-fragments-delayed*))) (t (dolist (dsd (dd-slots dd)) (push (cons dsd (accessor-closures dsd)) extra-data))))) (multiple-value-bind (super slot-overrides) (if (consp include) (values (car include) (mapcar #'car (cdr include))) (values include nil)) (let ((included-slots (when super (dd-slots (find-defstruct-description super))))) ;; This seems like a very unclear way to do what it's doing, which is ;; collect slots of TYPE that are not in its direct ancestor, *or* ;; which have an altered definition relative to the inherited one. (loop for slot = (pop all-slots) for included-slot = (pop included-slots) while slot when (or (not included-slot) (member (dsd-name included-slot) slot-overrides :test #'eq)) collect (apply #'slot-initargs-from-structure-slotd (assoc slot extra-data))))))) (slot-initargs-from-condition-slot (slot) `(:name ,(condition-slot-name slot) :initargs ,(condition-slot-initargs slot) :readers ,(condition-slot-readers slot) :writers ,(condition-slot-writers slot) ,@(when (condition-slot-initform-p slot) (let ((initform (condition-slot-initform slot)) (initfun (condition-slot-initfunction slot))) `(:initform ',initform :initfunction ,initfun))) :allocation ,(condition-slot-allocation slot) :documentation ,(condition-slot-documentation slot)))) (cond ((structure-type-p name) (ensure 'structure-class (structure-type-slot-description-list name))) ((condition-type-p name) (ensure 'condition-class (mapcar #'slot-initargs-from-condition-slot (condition-classoid-slots classoid)))) (t (error "~@<~S is not the name of a class.~@:>" name))))) (defun ensure-deffoo-class (classoid &optional accessors) (let ((class (classoid-pcl-class classoid))) (cond (class (ensure-non-standard-class (class-name class) classoid class accessors)) ((eq 'complete **boot-state**) (ensure-non-standard-class (classoid-name classoid) classoid nil accessors))))) (defun ensure-defstruct-class (classoid) Create an association from the DSD to the reader and writer functions . (let* ((name (classoid-name classoid)) (dd (find-defstruct-description name)) (fragments sb-kernel::*struct-accesss-fragments*)) (collect ((accessors)) (dolist (dsd (dd-slots dd)) (accessors (list dsd (pop fragments) (pop fragments)))) (ensure-deffoo-class classoid (accessors))))) ;;; Prior to the normal (steady-state) defstruct hook getting installed, ;;; we just accumulate an alist of slot accessor functions keyed by ;;; the type name. After switching it over, we start calling ENSURE - CLASS - USING - CLASS . But that means if PCL is n't ready to ;;; actually create classes, we can't switch over. So we refrain from installing the DEFSTRUCT - HOOK until there are no more defstruct forms to execute within PCL itself . (pushnew 'ensure-deffoo-class sb-kernel::*define-condition-hooks*) (defun !make-class-predicate (class name source-location) (let* ((gf (ensure-generic-function name :lambda-list '(object) 'source source-location)) (mlist (if (eq **boot-state** 'complete) (early-gf-methods gf) (generic-function-methods gf)))) (unless mlist (unless (eq class *the-class-t*) (let* ((default-method-function #'constantly-nil) (default-method-initargs (list :function default-method-function 'plist '(:constant-value nil))) (default-method (make-a-method 'standard-method () (list 'object) (list *the-class-t*) default-method-initargs "class predicate default method"))) (add-method gf default-method))) (let* ((class-method-function #'constantly-t) (class-method-initargs (list :function class-method-function 'plist '(:constant-value t))) (class-method (make-a-method 'standard-method () (list 'object) (list class) class-method-initargs "class predicate class method"))) (add-method gf class-method))) gf)) (define-load-time-global *simple-stream-root-classoid* :unknown) (defun set-bitmap-and-flags (wrapper &aux (inherits (wrapper-inherits wrapper)) (flags (wrapper-flags wrapper)) (layout (wrapper-friend wrapper))) (when (eq (wrapper-classoid wrapper) *simple-stream-root-classoid*) (setq flags (logior flags +simple-stream-layout-flag+))) ;; We decide only at class finalization time whether it is funcallable. ;; Picking the right bitmap could probably be done sooner given the metaclass, but this approach avoids changing how PCL uses MAKE - LAYOUT . ;; FIXME: we should assert that this is not a STRUCTURE-OBJECT, ;; because there must not be additional ID words preceding the bitmap. ;; STANDARD-OBJECT can't generally use a fixed number of ID slots ;; because of arbitrary changes to inheritance being permissible. ;; On the other hand, we do create a new layout for each change to superclasses , so maybe it 's possible . (dovector (ancestor inherits) (when (eq ancestor #.(find-layout 'function)) (%raw-instance-set/signed-word layout (sb-kernel::type-dd-length sb-vm:layout) sb-kernel::standard-gf-primitive-obj-layout-bitmap)) (setq flags (logior (logand (logior +sequence-layout-flag+ +stream-layout-flag+ +simple-stream-layout-flag+ +file-stream-layout-flag+ +string-stream-layout-flag+) (wrapper-flags ancestor)) flags))) (setf (layout-flags (wrapper-friend wrapper)) flags)) Set the inherits from CPL , and register the layout . This actually ;;; installs the class in the Lisp type system. (defun %update-lisp-class-layout (class wrapper) ;; Protected by **world-lock** in callers. (let ((classoid (wrapper-classoid wrapper))) (unless (eq (classoid-wrapper classoid) wrapper) (set-layout-inherits wrapper (order-layout-inherits (map 'simple-vector #'class-wrapper (reverse (rest (class-precedence-list class))))) nil 0) (set-bitmap-and-flags wrapper) (register-layout wrapper :invalidate t) ;; FIXME: I don't think this should be necessary, but without it we are unable to compile ( TYPEP foo ' < class - name > ) in the ;; same file as the class is defined. If we had environments, ;; then I think the classsoid whould only be associated with the ;; name in that environment... Alternatively, fix the compiler so that TYPEP foo ' < class - name > is slow but compileable . (let ((name (class-name class))) (when (and name (symbolp name) (eq name (classoid-name classoid))) (setf (find-classoid name) classoid)))))) (!bootstrap-accessor-definitions t) (!bootstrap-accessor-definitions nil) (loop for (name . x) in (let (classoid-cells) (do-all-symbols (s classoid-cells) (let ((cell (sb-int:info :type :classoid-cell s))) (when cell (push (cons s cell) classoid-cells))))) do (when (classoid-cell-pcl-class x) (let* ((class (find-class-from-cell name x)) (layout (class-wrapper class)) (lclass (wrapper-classoid layout)) (lclass-pcl-class (classoid-pcl-class lclass)) (olclass (find-classoid name nil))) (if lclass-pcl-class (aver (eq class lclass-pcl-class)) (setf (classoid-pcl-class lclass) class)) (%update-lisp-class-layout class layout) (cond (olclass (aver (eq lclass olclass))) (t (setf (find-classoid name) lclass)))))) (setq **boot-state** 'braid) (define-condition effective-method-condition (reference-condition) ((generic-function :initarg :generic-function :reader effective-method-condition-generic-function) (method :initarg :method :initform nil :reader effective-method-condition-method) (args :initarg :args :reader effective-method-condition-args)) (:default-initargs :generic-function (missing-arg) :args (missing-arg))) (define-condition effective-method-error (error effective-method-condition) ((problem :initarg :problem :reader effective-method-error-problem)) (:default-initargs :problem (missing-arg)) (:report (lambda (condition stream) (format stream "~@<~A for the generic function ~2I~_~S ~I~_when ~ called ~@[from method ~2I~_~S~I~_~]with arguments ~ ~2I~_~S.~:>" (effective-method-error-problem condition) (effective-method-condition-generic-function condition) (effective-method-condition-method condition) (effective-method-condition-args condition))))) (define-condition no-applicable-method-error (effective-method-error) () (:default-initargs :problem "There is no applicable method" :references '((:ansi-cl :section (7 6 6))))) (defmethod no-applicable-method (generic-function &rest args) (error 'no-applicable-method-error :generic-function generic-function :args args)) (define-condition no-next-method-error (effective-method-error) () (:default-initargs :problem "There is no next method" :references '((:ansi-cl :section (7 6 6 2))))) (defmethod no-next-method ((generic-function standard-generic-function) (method standard-method) &rest args) (error 'no-next-method-error :generic-function generic-function :method method :args args)) An extension to the ANSI standard : in the presence of e.g. a ;;; :BEFORE method, it would seem that going through ;;; NO-APPLICABLE-METHOD is prohibited, as in fact there is an applicable method . -- CSR , 2002 - 11 - 15 (define-condition no-primary-method-error (effective-method-error) () (:default-initargs :problem "There is no primary method" :references '((:ansi-cl :section (7 6 6 2))))) (defmethod no-primary-method (generic-function &rest args) (error 'no-primary-method-error :generic-function generic-function :args args)) FIXME should n't this specialize on STANDARD - METHOD - COMBINATION ? (defmethod invalid-qualifiers ((gf generic-function) combin method) (let* ((qualifiers (method-qualifiers method)) (qualifier (first qualifiers)) (type-name (method-combination-type-name combin)) (why (cond ((cdr qualifiers) "has too many qualifiers") (t (aver (not (standard-method-combination-qualifier-p qualifier))) "has an invalid qualifier")))) (invalid-method-error method "~@<The method ~S on ~S ~A.~ ~@:_~@:_~ ~@(~A~) method combination requires all methods to have one of ~ and ~ : ; , ~]~ } or to have no ~ qualifier at all.~@:>" method gf why type-name +standard-method-combination-qualifiers+)))
null
https://raw.githubusercontent.com/sbcl/sbcl/cacbb24d03cbc1309447bfcd72a5cd17dd2d0e8b/src/pcl/braid.lisp
lisp
bootstrapping the meta-braid The code in this file takes the early definitions that have been saved up and actually builds those class objects. This work is largely driven off of those class definitions, but the fact that STANDARD-CLASS is the class of all metaclasses in the braid is built into this code pretty deeply. more information. Corporation. Copyright and release statements follow. Later modifications to the software are in the public domain and are provided with absolutely no warranty. See the COPYING and CREDITS files for more information. All rights reserved. Use and copying of this software and preparation of derivative works based upon this software are permitted. Any distribution of this software or control laws. warranty about the software, its performance or its conformity to any specification. This is for a structure class that exists only in its compile-time representation. I don't see how these would get called, since you can't make an instance of the structure. This seems like a very unclear way to do what it's doing, which is collect slots of TYPE that are not in its direct ancestor, *or* which have an altered definition relative to the inherited one. Prior to the normal (steady-state) defstruct hook getting installed, we just accumulate an alist of slot accessor functions keyed by the type name. After switching it over, we start calling actually create classes, we can't switch over. So we refrain We decide only at class finalization time whether it is funcallable. Picking the right bitmap could probably be done sooner given the metaclass, FIXME: we should assert that this is not a STRUCTURE-OBJECT, because there must not be additional ID words preceding the bitmap. STANDARD-OBJECT can't generally use a fixed number of ID slots because of arbitrary changes to inheritance being permissible. On the other hand, we do create a new layout for each change installs the class in the Lisp type system. Protected by **world-lock** in callers. FIXME: I don't think this should be necessary, but without it same file as the class is defined. If we had environments, then I think the classsoid whould only be associated with the name in that environment... Alternatively, fix the compiler :BEFORE method, it would seem that going through NO-APPLICABLE-METHOD is prohibited, as in fact there is an , ~]~ } or to have no ~
This software is part of the SBCL system . See the README file for This software is derived from software originally released by Xerox copyright information from original PCL sources : Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation . derivative works must comply with all applicable United States export This software is made available AS IS , and Xerox Corporation makes no (in-package "SB-PCL") (defun !bootstrap-accessor-definitions (early-p) (let ((*early-p* early-p)) (dolist (definition *!early-class-definitions*) (let ((name (ecd-class-name definition)) (meta (ecd-metaclass definition))) (unless (or (eq meta 'built-in-class) (eq meta 'system-class)) (let ((direct-slots (ecd-canonical-slots definition))) (dolist (slotd direct-slots) (let ((slot-name (getf slotd :name)) (readers (getf slotd :readers)) (writers (getf slotd :writers))) (!bootstrap-accessor-definitions1 name slot-name readers writers (ecd-source-location definition)))))))))) (defun !bootstrap-accessor-definition (class-name accessor-name slot-name type source-location) (multiple-value-bind (accessor-class make-method-function arglist specls doc) (ecase type (reader (values 'standard-reader-method #'make-std-reader-method-function (list class-name) (list class-name) "automatically generated reader method")) (writer (values 'standard-writer-method #'make-std-writer-method-function (list 'new-value class-name) (list t class-name) "automatically generated writer method"))) (let ((gf (ensure-generic-function accessor-name :lambda-list arglist))) (if (find specls (early-gf-methods gf) :key #'early-method-specializers :test 'equal) (unless (assoc accessor-name *!generic-function-fixups* :test #'equal) (update-dfun gf)) (add-method gf (make-a-method accessor-class () arglist specls (funcall make-method-function class-name slot-name) doc :slot-name slot-name :object-class class-name :method-class-function (constantly (find-class accessor-class)) 'source source-location)))))) (defun !bootstrap-accessor-definitions1 (class-name slot-name readers writers source-location) (flet ((do-reader-definition (reader) (!bootstrap-accessor-definition class-name reader slot-name 'reader source-location)) (do-writer-definition (writer) (!bootstrap-accessor-definition class-name writer slot-name 'writer source-location))) (dolist (reader readers) (do-reader-definition reader)) (dolist (writer writers) (do-writer-definition writer)))) (defun class-of (x) (declare (explicit-check)) (wrapper-class (wrapper-of x))) (defun eval-form (form) (lambda () (eval form))) (defun ensure-non-standard-class (name classoid &optional existing-class extra-data) (labels ((ensure (metaclass slots) (let ((supers (mapcar #'classoid-name (classoid-direct-superclasses classoid)))) (ensure-class-using-class existing-class name :metaclass metaclass :name name :direct-superclasses supers :direct-slots slots))) (slot-initargs-from-structure-slotd (slotd writer-fn reader-fn) (flet ((name->fun (f) (if (functionp f) f (fdefinition f)))) `(:name ,(dsd-name slotd) :defstruct-accessor-symbol ,(dsd-accessor-name slotd) :internal-reader-function ,(name->fun reader-fn) :internal-writer-function ,(name->fun writer-fn) :always-bound-p ,(dsd-always-boundp slotd) :type ,(dsd-type slotd) :initform ,(dsd-default slotd) This is nuts ! any DEFAULT might need its lexical environment , yet we EVAL in the null environment . :initfunction ,(eval-form (dsd-default slotd))))) (accessor-closures (dsd) (multiple-value-bind (reader-fn writer-fn) (sb-kernel::dsd-reader dsd nil) (list (lambda (newval object) (funcall writer-fn newval object) newval) (lambda (object) (funcall reader-fn object))))) (structure-type-slot-description-list (type) (let* ((dd (find-defstruct-description type)) (include (dd-include dd)) (all-slots (dd-slots dd))) (unless extra-data (acond ((assoc (dd-name dd) sb-kernel::*struct-accesss-fragments-delayed*) (let ((fragments (cdr it))) (dolist (dsd (dd-slots dd)) (push (list dsd (pop fragments) (pop fragments)) extra-data))) (setq sb-kernel::*struct-accesss-fragments-delayed* (delete it sb-kernel::*struct-accesss-fragments-delayed*))) (t (dolist (dsd (dd-slots dd)) (push (cons dsd (accessor-closures dsd)) extra-data))))) (multiple-value-bind (super slot-overrides) (if (consp include) (values (car include) (mapcar #'car (cdr include))) (values include nil)) (let ((included-slots (when super (dd-slots (find-defstruct-description super))))) (loop for slot = (pop all-slots) for included-slot = (pop included-slots) while slot when (or (not included-slot) (member (dsd-name included-slot) slot-overrides :test #'eq)) collect (apply #'slot-initargs-from-structure-slotd (assoc slot extra-data))))))) (slot-initargs-from-condition-slot (slot) `(:name ,(condition-slot-name slot) :initargs ,(condition-slot-initargs slot) :readers ,(condition-slot-readers slot) :writers ,(condition-slot-writers slot) ,@(when (condition-slot-initform-p slot) (let ((initform (condition-slot-initform slot)) (initfun (condition-slot-initfunction slot))) `(:initform ',initform :initfunction ,initfun))) :allocation ,(condition-slot-allocation slot) :documentation ,(condition-slot-documentation slot)))) (cond ((structure-type-p name) (ensure 'structure-class (structure-type-slot-description-list name))) ((condition-type-p name) (ensure 'condition-class (mapcar #'slot-initargs-from-condition-slot (condition-classoid-slots classoid)))) (t (error "~@<~S is not the name of a class.~@:>" name))))) (defun ensure-deffoo-class (classoid &optional accessors) (let ((class (classoid-pcl-class classoid))) (cond (class (ensure-non-standard-class (class-name class) classoid class accessors)) ((eq 'complete **boot-state**) (ensure-non-standard-class (classoid-name classoid) classoid nil accessors))))) (defun ensure-defstruct-class (classoid) Create an association from the DSD to the reader and writer functions . (let* ((name (classoid-name classoid)) (dd (find-defstruct-description name)) (fragments sb-kernel::*struct-accesss-fragments*)) (collect ((accessors)) (dolist (dsd (dd-slots dd)) (accessors (list dsd (pop fragments) (pop fragments)))) (ensure-deffoo-class classoid (accessors))))) ENSURE - CLASS - USING - CLASS . But that means if PCL is n't ready to from installing the DEFSTRUCT - HOOK until there are no more defstruct forms to execute within PCL itself . (pushnew 'ensure-deffoo-class sb-kernel::*define-condition-hooks*) (defun !make-class-predicate (class name source-location) (let* ((gf (ensure-generic-function name :lambda-list '(object) 'source source-location)) (mlist (if (eq **boot-state** 'complete) (early-gf-methods gf) (generic-function-methods gf)))) (unless mlist (unless (eq class *the-class-t*) (let* ((default-method-function #'constantly-nil) (default-method-initargs (list :function default-method-function 'plist '(:constant-value nil))) (default-method (make-a-method 'standard-method () (list 'object) (list *the-class-t*) default-method-initargs "class predicate default method"))) (add-method gf default-method))) (let* ((class-method-function #'constantly-t) (class-method-initargs (list :function class-method-function 'plist '(:constant-value t))) (class-method (make-a-method 'standard-method () (list 'object) (list class) class-method-initargs "class predicate class method"))) (add-method gf class-method))) gf)) (define-load-time-global *simple-stream-root-classoid* :unknown) (defun set-bitmap-and-flags (wrapper &aux (inherits (wrapper-inherits wrapper)) (flags (wrapper-flags wrapper)) (layout (wrapper-friend wrapper))) (when (eq (wrapper-classoid wrapper) *simple-stream-root-classoid*) (setq flags (logior flags +simple-stream-layout-flag+))) but this approach avoids changing how PCL uses MAKE - LAYOUT . to superclasses , so maybe it 's possible . (dovector (ancestor inherits) (when (eq ancestor #.(find-layout 'function)) (%raw-instance-set/signed-word layout (sb-kernel::type-dd-length sb-vm:layout) sb-kernel::standard-gf-primitive-obj-layout-bitmap)) (setq flags (logior (logand (logior +sequence-layout-flag+ +stream-layout-flag+ +simple-stream-layout-flag+ +file-stream-layout-flag+ +string-stream-layout-flag+) (wrapper-flags ancestor)) flags))) (setf (layout-flags (wrapper-friend wrapper)) flags)) Set the inherits from CPL , and register the layout . This actually (defun %update-lisp-class-layout (class wrapper) (let ((classoid (wrapper-classoid wrapper))) (unless (eq (classoid-wrapper classoid) wrapper) (set-layout-inherits wrapper (order-layout-inherits (map 'simple-vector #'class-wrapper (reverse (rest (class-precedence-list class))))) nil 0) (set-bitmap-and-flags wrapper) (register-layout wrapper :invalidate t) we are unable to compile ( TYPEP foo ' < class - name > ) in the so that TYPEP foo ' < class - name > is slow but compileable . (let ((name (class-name class))) (when (and name (symbolp name) (eq name (classoid-name classoid))) (setf (find-classoid name) classoid)))))) (!bootstrap-accessor-definitions t) (!bootstrap-accessor-definitions nil) (loop for (name . x) in (let (classoid-cells) (do-all-symbols (s classoid-cells) (let ((cell (sb-int:info :type :classoid-cell s))) (when cell (push (cons s cell) classoid-cells))))) do (when (classoid-cell-pcl-class x) (let* ((class (find-class-from-cell name x)) (layout (class-wrapper class)) (lclass (wrapper-classoid layout)) (lclass-pcl-class (classoid-pcl-class lclass)) (olclass (find-classoid name nil))) (if lclass-pcl-class (aver (eq class lclass-pcl-class)) (setf (classoid-pcl-class lclass) class)) (%update-lisp-class-layout class layout) (cond (olclass (aver (eq lclass olclass))) (t (setf (find-classoid name) lclass)))))) (setq **boot-state** 'braid) (define-condition effective-method-condition (reference-condition) ((generic-function :initarg :generic-function :reader effective-method-condition-generic-function) (method :initarg :method :initform nil :reader effective-method-condition-method) (args :initarg :args :reader effective-method-condition-args)) (:default-initargs :generic-function (missing-arg) :args (missing-arg))) (define-condition effective-method-error (error effective-method-condition) ((problem :initarg :problem :reader effective-method-error-problem)) (:default-initargs :problem (missing-arg)) (:report (lambda (condition stream) (format stream "~@<~A for the generic function ~2I~_~S ~I~_when ~ called ~@[from method ~2I~_~S~I~_~]with arguments ~ ~2I~_~S.~:>" (effective-method-error-problem condition) (effective-method-condition-generic-function condition) (effective-method-condition-method condition) (effective-method-condition-args condition))))) (define-condition no-applicable-method-error (effective-method-error) () (:default-initargs :problem "There is no applicable method" :references '((:ansi-cl :section (7 6 6))))) (defmethod no-applicable-method (generic-function &rest args) (error 'no-applicable-method-error :generic-function generic-function :args args)) (define-condition no-next-method-error (effective-method-error) () (:default-initargs :problem "There is no next method" :references '((:ansi-cl :section (7 6 6 2))))) (defmethod no-next-method ((generic-function standard-generic-function) (method standard-method) &rest args) (error 'no-next-method-error :generic-function generic-function :method method :args args)) An extension to the ANSI standard : in the presence of e.g. a applicable method . -- CSR , 2002 - 11 - 15 (define-condition no-primary-method-error (effective-method-error) () (:default-initargs :problem "There is no primary method" :references '((:ansi-cl :section (7 6 6 2))))) (defmethod no-primary-method (generic-function &rest args) (error 'no-primary-method-error :generic-function generic-function :args args)) FIXME should n't this specialize on STANDARD - METHOD - COMBINATION ? (defmethod invalid-qualifiers ((gf generic-function) combin method) (let* ((qualifiers (method-qualifiers method)) (qualifier (first qualifiers)) (type-name (method-combination-type-name combin)) (why (cond ((cdr qualifiers) "has too many qualifiers") (t (aver (not (standard-method-combination-qualifier-p qualifier))) "has an invalid qualifier")))) (invalid-method-error method "~@<The method ~S on ~S ~A.~ ~@:_~@:_~ ~@(~A~) method combination requires all methods to have one of ~ qualifier at all.~@:>" method gf why type-name +standard-method-combination-qualifiers+)))
2f5aa2b4b4d33edfd03214469a4aa3994a00de284349ceabe597451529da3c1f
ktakashi/sagittarius-scheme
ecdsa_brainpoolP224r1_sha224_p1363_test.scm
(test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 87 46 171 115 118 208 82 223 196 9 35 219 37 52 46 169 203 252 228 184 88 30 16 74 76 143 55 201 74 112 14 197 220 5 164 129 178 182 149 50 12 111 26 210 221 134 40 99 60 219 117 169 18 69 194 101) :der-encode #f :tests '(#(1 "signature malleability" #vu8(49 50 51 52 48 48) #vu8(203 104 172 151 101 199 100 23 133 223 35 126 153 81 225 66 149 129 135 154 242 99 20 96 4 137 97 211 19 156 120 36 58 110 54 225 36 213 245 225 75 76 184 117 74 189 242 15 241 165 1 213 102 106 66 143) #t ()) #(2 "Modified r or s, e.g. by adding or subtracting the order of the group" #vu8(49 50 51 52 48 48) #vu8(1 163 41 225 65 140 10 202 157 175 247 83 164 15 34 220 219 102 152 67 230 96 65 209 3 170 48 245 114 0 196 36 188 133 235 213 47 165 5 66 58 68 42 132 67 35 134 88 202 59 124 57 186 206 63 61 81 16) #f ()) #(3 "Modified r or s, e.g. by adding or subtracting the order of the group" #vu8(49 50 51 52 48 48) #vu8(12 88 136 18 192 124 2 110 164 57 12 166 220 127 26 86 59 149 52 176 123 123 168 67 161 30 49 204 196 36 188 133 235 213 47 165 5 66 58 68 42 132 67 35 134 88 202 59 124 57 186 206 63 61 81 16) #f ()) #(4 "Modified r or s, e.g. by adding or subtracting the order of the group" #vu8(49 50 51 52 48 48) #vu8(1 203 104 172 151 101 199 100 23 133 223 35 126 153 81 225 66 149 129 135 154 242 99 20 96 4 137 97 211 0 196 36 188 133 235 213 47 165 5 66 58 68 42 132 67 35 134 88 202 59 124 57 186 206 63 61 81 16) #f ()) #(5 "Modified r or s, e.g. by adding or subtracting the order of the group" #vu8(49 50 51 52 48 48) #vu8(52 151 83 104 154 56 155 232 122 32 220 129 102 174 30 189 106 126 120 101 13 156 235 159 251 118 158 45 196 36 188 133 235 213 47 165 5 66 58 68 42 132 67 35 134 88 202 59 124 57 186 206 63 61 81 16) #f ()) #(6 "Modified r or s, e.g. by adding or subtracting the order of the group" #vu8(49 50 51 52 48 48) #vu8(0 203 104 172 151 101 199 100 23 133 223 35 126 153 81 225 66 149 129 135 154 242 99 20 96 4 137 97 211 1 155 229 241 48 18 24 150 43 47 90 106 105 160 85 62 188 87 111 134 134 234 24 119 113 228 228 228 175) #f ()) #(7 "Modified r or s, e.g. by adding or subtracting the order of the group" #vu8(49 50 51 52 48 48) #vu8(0 203 104 172 151 101 199 100 23 133 223 35 126 153 81 225 66 149 129 135 154 242 99 20 96 4 137 97 211 1 196 36 188 133 235 213 47 165 5 66 58 68 42 132 67 35 134 88 202 59 124 57 186 206 63 61 81 16) #f ()) #(8 "Modified r or s, e.g. by adding or subtracting the order of the group" #vu8(49 50 51 52 48 48) #vu8(203 104 172 151 101 199 100 23 133 223 35 126 153 81 225 66 149 129 135 154 242 99 20 96 4 137 97 211 59 219 67 122 20 42 208 90 250 189 197 187 213 123 188 220 121 167 53 196 131 198 69 49 192 194 174 240) #f ()) #(9 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ("EdgeCase")) #(10 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #f ("EdgeCase")) #(11 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159) #f ("EdgeCase")) #(12 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158) #f ("EdgeCase")) #(13 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160) #f ("EdgeCase")) #(14 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255) #f ("EdgeCase")) #(15 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0) #f ("EdgeCase")) #(16 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ("EdgeCase")) #(17 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #f ("EdgeCase")) #(18 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159) #f ("EdgeCase")) #(19 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158) #f ("EdgeCase")) #(20 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160) #f ("EdgeCase")) #(21 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255) #f ("EdgeCase")) #(22 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0) #f ("EdgeCase")) #(23 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ("EdgeCase")) #(24 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #f ("EdgeCase")) #(25 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159) #f ("EdgeCase")) #(26 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158) #f ("EdgeCase")) #(27 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160) #f ("EdgeCase")) #(28 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255) #f ("EdgeCase")) #(29 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0) #f ("EdgeCase")) #(30 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ("EdgeCase")) #(31 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #f ("EdgeCase")) #(32 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159) #f ("EdgeCase")) #(33 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158) #f ("EdgeCase")) #(34 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160) #f ("EdgeCase")) #(35 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255) #f ("EdgeCase")) #(36 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0) #f ("EdgeCase")) #(37 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ("EdgeCase")) #(38 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #f ("EdgeCase")) #(39 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159) #f ("EdgeCase")) #(40 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158) #f ("EdgeCase")) #(41 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160) #f ("EdgeCase")) #(42 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255) #f ("EdgeCase")) #(43 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0) #f ("EdgeCase")) #(44 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ("EdgeCase")) #(45 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #f ("EdgeCase")) #(46 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159) #f ("EdgeCase")) #(47 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158) #f ("EdgeCase")) #(48 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160) #f ("EdgeCase")) #(49 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255) #f ("EdgeCase")) #(50 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0) #f ("EdgeCase")) #(51 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ("EdgeCase")) #(52 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #f ("EdgeCase")) #(53 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159) #f ("EdgeCase")) #(54 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158) #f ("EdgeCase")) #(55 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160) #f ("EdgeCase")) #(56 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255) #f ("EdgeCase")) #(57 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0) #f ("EdgeCase")) #(58 "Edge case for Shamir multiplication" #vu8(57 53 51 56 56) #vu8(14 126 202 178 39 111 3 92 13 199 5 32 235 213 174 60 183 183 168 242 31 165 104 126 238 146 196 98 133 168 83 50 248 200 153 181 61 67 9 27 2 230 149 107 57 24 23 225 117 168 177 244 13 202 126 0) #t ()) #(59 "special case hash" #vu8(50 50 53 52 54 50 56 57 56 52) #vu8(47 194 239 159 118 99 246 111 19 176 78 73 242 6 194 36 65 235 62 225 145 123 139 248 26 155 83 118 209 223 61 208 39 14 88 132 233 132 142 162 129 43 102 245 1 91 233 109 37 133 254 211 149 123 49 60) #t ()) #(60 "special case hash" #vu8(49 56 50 55 56 55 56 54 49 48) #vu8(198 130 88 123 244 62 12 149 78 181 139 188 254 185 77 250 200 186 212 4 153 90 194 110 142 81 255 32 146 191 16 218 16 50 76 195 34 247 156 65 45 174 211 5 178 117 252 25 147 191 58 245 35 222 214 42) #t ()) #(61 "special case hash" #vu8(49 53 49 56 56 54 49 55 48 57) #vu8(2 93 28 241 111 3 52 31 60 141 22 167 120 57 181 193 214 150 54 61 174 137 141 145 225 74 213 34 183 55 156 195 92 151 168 240 139 14 251 50 238 130 206 14 25 17 105 93 55 46 230 214 121 236 84 102) #t ()) #(62 "special case hash" #vu8(50 49 50 57 50 51 51 52 50 50) #vu8(192 201 73 224 240 248 87 24 2 234 126 2 97 124 169 37 185 93 41 10 23 79 104 109 128 187 161 212 185 102 23 60 227 241 60 165 76 205 200 162 73 254 167 46 50 96 173 62 120 84 167 49 5 29 140 3) #t ()) #(63 "special case hash" #vu8(49 50 50 49 57 55 57 48 53 57) #vu8(93 87 241 66 117 148 124 155 255 234 102 249 243 10 226 3 25 69 53 248 2 12 66 187 193 239 236 115 195 88 101 27 162 82 124 50 216 88 101 124 207 8 229 53 211 40 81 251 216 195 84 119 186 23 86 128) #t ()) #(64 "special case hash" #vu8(50 51 48 50 53 54 55 54 49 49) #vu8(19 59 177 47 16 150 152 157 200 103 216 116 246 117 253 249 233 121 117 194 226 44 113 228 79 89 191 53 101 87 238 178 181 180 241 247 200 81 132 220 198 83 133 12 52 177 195 72 13 47 50 209 86 124 37 193) #t ()) #(65 "special case hash" #vu8(49 49 48 53 56 54 56 52 55 50) #vu8(209 220 125 28 200 134 202 144 224 217 96 182 199 253 169 46 213 130 236 97 108 28 121 177 113 239 49 8 65 167 210 20 56 231 195 75 39 23 96 5 239 103 192 74 99 243 98 210 218 241 11 98 197 59 136 180) #t ()) #(66 "special case hash" #vu8(49 52 54 54 54 49 52 52 52 50) #vu8(158 195 183 180 160 241 35 81 105 182 74 32 88 77 54 185 107 183 162 189 224 13 35 22 60 195 177 191 172 50 239 59 158 148 141 150 127 150 205 8 80 120 9 227 185 160 224 147 190 62 118 184 24 51 29 213) #t ()) #(67 "special case hash" #vu8(52 52 49 57 53 54 52 50 48) #vu8(57 42 227 129 218 76 207 217 213 173 9 61 73 178 45 87 148 17 247 193 205 4 232 132 115 171 110 245 162 137 139 139 241 32 209 142 78 224 209 92 65 144 68 50 77 227 192 146 126 233 15 214 243 135 17 244) #t ()) #(68 "special case hash" #vu8(49 57 54 57 52 56 54 48 54 52) #vu8(163 123 12 200 127 109 70 32 48 48 48 215 172 74 101 114 249 76 12 244 79 10 3 92 14 89 208 124 48 199 172 216 219 158 114 1 34 8 240 141 181 56 26 30 84 250 9 140 3 20 160 154 48 88 196 33) #t ()) #(69 "special case hash" #vu8(50 50 51 53 54 55 50 56 56 51) #vu8(98 246 96 217 58 69 223 163 182 97 248 182 164 213 224 110 90 30 232 168 133 90 186 250 64 115 181 19 214 151 143 93 168 175 204 91 57 95 212 181 243 192 253 183 162 104 158 109 228 109 8 251 157 231 24 96) #t ()) #(70 "special case hash" #vu8(50 50 53 55 56 52 51 55 48 51) #vu8(97 175 154 44 162 5 3 253 98 188 60 111 132 52 153 92 108 243 3 126 182 249 255 98 19 72 207 83 9 248 246 71 19 135 105 84 141 180 96 239 221 131 35 248 202 209 138 112 113 211 208 77 106 211 61 130) #t ()) #(71 "special case hash" #vu8(57 52 52 53 48 48 57 52 54) #vu8(14 69 156 254 55 1 124 139 96 94 56 191 93 37 23 101 118 212 117 250 136 222 210 123 226 106 188 167 177 187 106 96 204 195 212 142 141 29 76 83 249 1 66 128 110 68 217 148 158 188 170 5 184 62 32 244) #t ()) #(72 "special case hash" #vu8(49 54 56 55 55 56 57 52 49 48) #vu8(208 24 72 130 189 214 250 9 153 108 47 236 243 205 38 237 134 163 206 21 152 126 6 219 133 11 139 43 207 240 114 178 124 51 249 22 129 211 233 90 71 190 192 0 204 150 197 220 145 246 142 204 194 28 163 196) #t ()) #(73 "special case hash" #vu8(51 57 51 50 54 49 50 50 56) #vu8(53 126 150 171 84 244 219 179 166 163 169 209 237 230 223 82 148 99 154 237 253 234 150 231 255 201 218 49 36 235 107 127 85 144 103 57 49 62 162 102 90 5 4 163 176 191 122 155 50 156 105 15 74 46 223 81) #t ()) #(74 "special case hash" #vu8(49 48 55 51 53 55 49 48 57 53) #vu8(11 170 247 157 82 53 227 38 142 85 67 28 189 121 0 70 194 88 30 189 63 139 144 98 123 212 107 139 131 213 111 107 86 202 147 129 177 76 168 136 40 27 72 28 248 40 233 180 59 13 65 129 8 232 45 88) #t ()) #(75 "special case hash" #vu8(54 48 56 56 55 52 55 52) #vu8(126 190 241 173 65 222 148 52 235 63 111 131 51 143 1 9 102 108 38 77 137 18 51 66 176 144 15 5 120 163 169 250 114 1 196 143 146 131 68 0 74 31 81 128 83 9 157 248 105 8 222 41 238 183 106 76) #t ()) #(76 "special case hash" #vu8(49 49 57 50 53 54 57 57 54 50) #vu8(159 32 171 239 240 175 150 93 169 197 28 153 80 124 245 249 29 117 242 63 224 43 97 21 2 150 22 124 191 111 237 138 142 247 38 242 246 98 156 78 75 80 179 194 206 20 255 67 159 233 191 230 21 120 104 212) #t ()) #(77 "special case hash" #vu8(57 48 48 55 54 48 57 51) #vu8(90 214 127 240 221 248 203 136 64 121 116 248 63 234 67 217 209 71 203 178 61 186 38 31 173 173 174 219 127 211 28 204 75 54 5 219 66 183 0 162 69 223 143 198 14 251 241 64 106 251 77 108 140 22 224 163) #t ()) #(78 "special case hash" #vu8(49 54 48 50 56 51 54 49 51 55) #vu8(64 224 189 154 47 165 168 134 120 200 92 63 77 39 226 174 45 208 70 242 154 54 57 236 47 242 81 26 22 205 73 33 92 176 5 51 253 19 154 225 211 99 29 69 251 6 213 236 209 19 138 180 108 72 164 92) #t ()) #(79 "special case hash" #vu8(50 48 56 48 50 52 53 54 55 52) #vu8(154 112 93 220 135 103 229 76 236 77 28 55 162 70 11 60 11 49 233 129 28 58 66 117 38 73 156 1 54 166 185 220 215 200 168 30 52 175 223 132 92 76 192 231 52 85 1 27 188 215 152 127 136 114 88 186) #t ()) #(80 "special case hash" #vu8(49 55 57 56 50 55 52 54 53 57) #vu8(165 26 98 91 153 86 141 0 62 75 150 230 147 19 107 167 82 33 232 229 108 154 181 233 236 104 22 238 126 32 137 24 120 85 22 205 167 207 112 135 13 216 18 232 14 143 159 27 82 72 217 25 177 255 29 6) #t ()) #(81 "special case hash" #vu8(49 49 53 53 53 55 55 55 50 48) #vu8(71 32 249 55 16 13 245 46 106 225 186 244 15 139 201 80 229 175 43 31 148 125 4 23 128 74 130 37 139 130 34 115 251 93 71 60 156 136 170 60 141 222 161 103 97 156 218 18 238 65 206 101 222 38 138 117) #t ()) #(82 "special case hash" #vu8(50 52 51 50 52 55 52 54 54 52) #vu8(61 40 29 152 182 166 118 166 237 167 87 13 123 79 154 8 233 36 199 26 253 44 182 224 98 167 235 253 132 70 228 39 71 163 82 81 142 246 142 255 5 86 149 180 118 107 220 42 216 211 250 151 188 32 43 67) #t ()) #(83 "special case hash" #vu8(50 52 49 55 50 56 50 50 55 55) #vu8(77 52 105 233 57 255 234 217 65 227 203 206 188 163 188 182 243 192 41 100 31 151 112 14 2 129 119 56 66 203 135 161 14 161 124 14 88 195 130 47 106 225 243 168 145 141 134 168 50 93 239 74 140 128 130 242) #t ()) #(84 "special case hash" #vu8(55 55 56 55 52 55 55 49) #vu8(33 229 27 121 232 85 78 34 147 124 62 91 25 131 179 119 98 89 30 33 245 112 110 92 25 130 165 12 75 205 189 35 176 164 113 219 132 209 238 62 223 118 119 187 177 67 7 236 197 225 2 49 116 236 91 140) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 160 239 125 177 190 224 174 219 90 86 52 244 243 177 184 141 151 210 160 127 128 106 113 142 254 25 1 77 174 225 4 63 158 146 156 50 215 74 176 228 238 186 38 35 241 123 162 129 182 190 135 116 91 89 246 14) :der-encode #f :tests '(#(85 "k*G has a large x-coordinate" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 219 238 223 136 75 12 41 251 205 81 217 33 45 95 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 156) #t ()) #(86 "r too large" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 254 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 156) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 58 221 164 7 186 215 245 147 232 61 125 72 79 209 76 35 221 161 127 141 70 12 34 42 167 37 117 119 205 98 68 59 43 119 2 145 246 89 4 218 207 117 255 151 95 26 102 113 135 224 228 245 12 20 136 156) :der-encode #f :tests '(#(87 "r,s are large" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 157) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 36 88 124 225 219 255 40 29 202 177 121 69 25 128 98 129 173 78 9 151 73 37 16 103 127 182 81 6 146 150 153 110 131 184 8 103 108 191 111 40 201 43 132 48 51 20 182 58 3 8 19 79 34 45 14 194) :der-encode #f :tests '(#(88 "r and s^-1 have a large Hamming weight" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 99 240 227 66 88 187 144 97 84 121 6 208 195 130 124 80 68 34 193 57 230 214 225 7 139 55 170 68) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 196 92 81 213 169 178 19 228 28 166 241 92 184 170 27 192 184 183 61 58 138 35 161 79 90 61 164 223 188 120 204 97 118 211 184 49 230 136 0 103 23 104 4 60 17 191 99 166 149 145 141 246 236 135 55 138) :der-encode #f :tests '(#(89 "r and s^-1 have a large Hamming weight" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 110 177 251 250 141 248 125 79 161 12 131 63 125 209 187 231 239 1 68 255 113 83 121 117 55 143 145 236) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 54 165 52 77 160 138 66 30 220 108 59 235 125 233 122 117 89 252 16 28 20 137 255 43 80 54 216 246 32 123 244 102 110 77 246 6 189 13 152 35 165 43 88 221 253 252 29 167 5 19 197 249 153 15 128 133) :der-encode #f :tests '(#(90 "small r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #t ()) #(91 "incorrect size of signature" #vu8(49 50 51 52 48 48) #vu8(1 1) #t ("SigSize")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 64 149 192 149 169 100 137 81 218 53 43 131 127 54 142 11 230 125 121 253 87 234 223 255 237 223 180 85 204 220 250 190 161 158 150 212 210 14 66 184 174 35 194 81 148 38 1 142 37 166 77 234 133 216 166 139) :der-encode #f :tests '(#(92 "small r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2) #t ()) #(93 "incorrect size of signature" #vu8(49 50 51 52 48 48) #vu8(1 2) #t ("SigSize")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 204 53 42 196 138 172 182 73 94 195 131 27 33 204 212 211 25 113 54 41 43 246 242 15 34 128 37 102 100 50 25 145 230 127 125 188 34 96 46 203 219 49 34 237 206 95 248 93 146 49 67 206 204 13 79 109) :der-encode #f :tests '(#(94 "small r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3) #t ()) #(95 "incorrect size of signature" #vu8(49 50 51 52 48 48) #vu8(1 3) #t ("SigSize")) #(96 "r is larger than n" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 145 72 242 156 103 248 60 112 94 239 181 156 146 149 71 117 249 12 21 226 37 218 46 153 106 188 221 29 201 219 26 161 225 82 119 196 85 93 36 17 130 57 229 63 210 240 181 231 234 128 126 179 222 30 227 80) :der-encode #f :tests '(#(97 "s is larger than n" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 186 106 38) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 155 240 69 164 58 95 20 213 228 18 238 24 31 17 29 110 83 150 17 32 83 31 60 80 202 112 30 120 190 158 185 81 70 244 242 190 150 148 153 118 167 170 73 211 21 147 167 218 46 221 144 118 82 57 140 58) :der-encode #f :tests '(#(98 "small r and s^-1" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 157 254 92 253 155 2 254 122 111 116 123 243 29 213 129 208 169 60 254 204 102 161 23 61 97 29 253 60) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 135 115 158 40 33 237 149 103 232 135 2 250 140 109 8 60 151 193 243 241 235 50 209 63 117 31 176 115 109 2 235 160 94 140 185 70 114 208 158 188 17 5 29 82 236 123 212 220 119 103 48 27 103 3 66 18) :der-encode #f :tests '(#(99 "smallish r and s^-1" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 45 155 77 52 121 82 204 67 226 53 116 139 211 177 191 161 76 146 35 74 144 38 26 204 62 144 134 129 8 1 163 103 70 188 238) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 26 81 92 190 149 123 252 7 14 76 74 117 214 253 94 124 21 177 226 85 235 66 254 173 6 201 210 99 98 82 204 13 35 67 24 57 77 247 219 101 176 165 46 6 149 60 166 194 30 201 87 116 211 158 253 201) :der-encode #f :tests '(#(100 "100-bit r and small s^-1" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 51 230 126 55 179 43 68 85 128 191 78 251 168 189 244 101 50 216 19 107 235 33 219 241 120 9 12 126 125 173 44 170 142 181 44 239 141 131 15 216) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 214 161 110 25 78 18 185 109 184 225 187 2 80 217 80 247 179 18 155 20 187 160 239 177 87 196 66 62 98 90 12 140 32 131 139 217 127 188 137 241 103 0 40 117 74 9 173 40 246 45 229 238 166 224 123 193) :der-encode #f :tests '(#(101 "small r and 100 bit s^-1" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 115 22 138 137 148 229 247 23 147 8 28 183 175 190 60 10 244 191 122 163 54 207 157 227 30 248 83 20) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 192 18 149 13 7 75 176 27 10 25 136 165 181 155 149 145 4 39 91 175 117 126 83 2 155 4 106 21 66 245 15 226 127 62 186 201 3 101 88 239 48 235 203 129 32 39 191 14 244 108 218 81 150 149 65 187) :der-encode #f :tests '(#(102 "100-bit r and s^-1" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 37 34 187 211 236 190 124 57 233 62 124 36 115 22 138 137 148 229 247 23 147 8 28 183 175 190 60 10 244 191 122 163 54 207 157 227 30 248 83 20) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 209 92 19 161 190 153 217 235 119 214 136 16 74 24 226 66 66 210 5 164 2 111 74 101 98 158 89 238 126 61 223 154 187 183 213 50 182 232 26 110 17 243 13 91 85 254 184 238 112 124 79 237 249 156 6 7) :der-encode #f :tests '(#(103 "r and s^-1 are close to n" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 31 71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 63 224 25 114 192 98 46 168 18 211 6 82 201 254 47 235 238 112 129 35 177 98 109 116 79 135 219 13 165 114 199 225 227 164 129 149 230 34 29 152 63 120 47 220 158 124 85 189 95 223 123 103 155 15 135 86) :der-encode #f :tests '(#(104 "s == 1" #vu8(49 50 51 52 48 48) #vu8(71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #t ()) #(105 "s == 0" #vu8(49 50 51 52 48 48) #vu8(71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 212 182 229 17 36 6 251 116 59 107 181 95 73 234 32 48 217 4 66 8 49 235 221 172 214 123 186 137 101 34 101 56 75 117 216 80 231 194 127 78 51 237 108 87 109 240 255 150 148 112 169 239 37 255 175 205) :der-encode #f :tests '(#(106 "point at infinity during verify" #vu8(49 50 51 52 48 48) #vu8(107 224 154 85 19 33 179 67 21 12 24 18 186 232 125 204 104 139 94 37 182 239 94 81 210 211 201 207 71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 22 194 18 157 84 185 52 121 181 106 159 245 184 62 76 117 11 180 243 62 225 231 15 56 181 68 159 45 52 204 175 121 197 28 125 255 58 127 154 5 205 21 163 150 224 207 254 37 66 28 55 233 184 14 20 137) :der-encode #f :tests '(#(107 "edge case for signature malleability" #vu8(49 50 51 52 48 48) #vu8(107 224 154 85 19 33 179 67 21 12 24 18 186 232 125 204 104 139 94 37 182 239 94 81 210 211 201 208 107 224 154 85 19 33 179 67 21 12 24 18 186 232 125 204 104 139 94 37 182 239 94 81 210 211 201 207) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 101 171 160 228 66 122 10 229 88 114 26 90 142 114 203 55 98 235 80 34 59 190 76 65 164 80 254 73 200 29 58 228 134 71 139 66 152 201 67 40 61 46 194 19 11 172 34 250 188 82 247 67 177 171 127 167) :der-encode #f :tests '(#(108 "edge case for signature malleability" #vu8(49 50 51 52 48 48) #vu8(107 224 154 85 19 33 179 67 21 12 24 18 186 232 125 204 104 139 94 37 182 239 94 81 210 211 201 208 107 224 154 85 19 33 179 67 21 12 24 18 186 232 125 204 104 139 94 37 182 239 94 81 210 211 201 208) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 85 167 176 16 6 19 250 189 149 123 66 96 8 53 198 212 46 1 224 66 82 89 59 221 227 177 114 120 135 112 138 5 171 162 249 63 26 30 30 203 112 62 201 168 238 109 96 19 161 1 211 151 1 42 140 206) :der-encode #f :tests '(#(109 "u1 == 1" #vu8(49 50 51 52 48 48) #vu8(71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138 117 59 180 0 120 147 64 129 215 189 17 62 196 155 25 239 9 209 186 51 73 134 144 81 109 77 18 44) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 26 218 84 220 1 88 97 104 13 139 178 211 17 185 14 130 219 117 170 158 130 23 185 38 17 250 3 203 132 198 17 85 17 151 41 139 50 116 135 92 185 70 134 231 88 240 161 169 103 92 11 193 87 69 26 118) :der-encode #f :tests '(#(110 "u1 == n - 1" #vu8(49 50 51 52 48 48) #vu8(71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138 98 133 128 169 173 176 38 4 82 91 30 230 177 53 225 169 199 69 2 24 36 88 44 82 56 90 129 115) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 198 123 100 41 120 83 52 166 8 221 233 73 168 171 230 65 219 211 96 30 188 225 230 117 254 113 168 229 39 210 232 114 125 196 246 24 73 53 80 187 148 1 81 188 166 130 111 113 76 91 49 133 64 56 244 77) :der-encode #f :tests '(#(111 "u2 == 1" #vu8(49 50 51 52 48 48) #vu8(71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138 71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 29 204 122 90 209 17 163 54 39 249 45 216 117 186 74 6 246 167 194 190 253 209 5 4 136 208 87 167 52 28 174 11 231 42 153 119 109 181 189 121 180 99 226 211 136 39 100 175 156 2 69 208 132 163 52 45) :der-encode #f :tests '(#(112 "u2 == n - 1" #vu8(49 50 51 52 48 48) #vu8(71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138 143 214 35 28 25 130 68 89 113 101 117 110 78 139 82 101 224 185 210 220 243 233 211 23 195 197 13 21) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 189 247 8 160 28 106 129 71 40 211 148 183 242 155 246 87 151 52 134 45 138 248 230 255 120 111 190 73 144 28 212 98 148 110 94 54 204 151 201 137 109 242 225 129 119 69 109 40 42 122 38 163 128 132 192 134) :der-encode #f :tests '(#(113 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 182 234 9 198 236 94 4 132 185 79 37 216 144 20 91 10 227 255 187 152 183 22 173 221 146 222 189 206) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 12 83 31 179 217 150 250 162 36 7 223 19 5 255 106 224 191 233 78 28 32 34 244 115 13 15 138 74 189 128 115 149 4 89 86 46 83 154 192 137 84 51 117 126 37 32 155 18 83 79 243 15 227 211 124 113) :der-encode #f :tests '(#(114 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 47 98 169 207 72 227 202 96 46 239 78 51 175 164 63 45 206 185 34 164 10 103 222 121 247 177 174 56) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 103 130 149 64 130 65 142 0 2 160 129 38 114 172 33 35 182 51 75 52 19 64 85 80 150 188 246 198 31 111 161 168 254 166 23 217 221 161 68 97 214 58 164 72 242 5 163 155 37 80 26 107 29 66 238 95) :der-encode #f :tests '(#(115 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 97 141 252 84 64 139 236 28 179 124 126 229 43 96 173 188 141 58 108 38 69 124 57 208 19 232 142 129) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 91 94 110 171 167 89 122 230 65 66 10 206 106 242 87 88 57 241 97 178 123 145 178 112 241 139 247 208 73 106 179 195 7 47 166 238 85 120 252 129 79 116 209 72 236 188 42 152 207 220 93 64 236 126 105 128) :der-encode #f :tests '(#(116 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 1 13 229 113 36 192 147 14 248 0 231 100 181 88 89 39 151 126 42 210 216 184 46 124 182 72 175 82) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 142 102 26 6 173 85 181 34 120 1 234 67 9 167 43 156 217 73 115 188 135 60 4 5 225 36 125 30 100 137 139 130 44 54 60 172 136 33 48 45 227 138 145 66 104 170 166 125 178 86 24 120 240 249 10 2) :der-encode #f :tests '(#(117 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 3 62 245 1 11 236 237 4 196 146 136 104 81 62 209 135 140 230 119 166 237 129 14 155 153 221 151 148) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 179 210 185 63 20 136 101 114 98 20 15 150 193 8 170 4 133 147 155 217 148 64 36 10 122 125 84 227 136 150 129 116 176 97 133 55 57 248 176 71 28 118 18 101 57 220 87 204 109 124 31 83 159 104 102 116) :der-encode #f :tests '(#(118 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 6 125 234 2 23 217 218 9 137 37 16 208 162 125 163 15 25 204 239 77 219 2 29 55 51 187 47 40) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 186 131 13 191 131 7 92 209 130 188 147 34 193 246 41 154 76 227 207 77 221 224 230 252 238 80 240 214 43 21 63 111 55 122 136 128 156 157 213 13 141 97 235 103 148 81 68 72 22 87 134 167 198 85 141 204) :der-encode #f :tests '(#(119 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 69 132 126 2 253 1 163 204 158 6 63 150 31 185 32 171 50 113 236 9 153 111 117 188 167 254 109 63) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 119 244 2 34 228 167 154 15 167 229 16 136 126 105 235 163 31 109 215 6 113 33 218 254 115 155 190 19 208 255 171 114 34 207 109 130 124 81 235 83 171 172 80 107 192 165 215 193 165 167 225 104 61 73 228 62) :der-encode #f :tests '(#(120 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 11 76 190 134 109 25 32 99 65 56 200 121 143 204 65 71 148 71 229 174 118 7 148 225 229 121 121 40) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 89 123 90 60 16 107 140 78 154 126 122 81 124 215 64 231 118 103 200 162 208 108 81 14 94 59 114 141 156 194 73 232 39 245 255 249 2 18 46 178 107 173 196 167 218 101 85 180 137 186 152 152 45 56 129 37) :der-encode #f :tests '(#(121 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 32 215 42 227 57 229 98 1 112 201 10 76 229 188 160 141 237 23 0 178 182 200 14 198 18 200 213 209) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 15 36 83 231 88 92 177 57 47 244 250 17 134 159 140 16 178 249 207 79 42 24 184 102 232 243 124 43 209 86 110 240 73 40 121 117 121 212 15 51 16 235 175 71 122 78 120 162 53 134 25 40 50 134 52 223) :der-encode #f :tests '(#(122 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 157 35 90 169 233 249 198 69 62 57 167 134 19 131 110 161 76 45 223 49 201 27 116 122 239 1 10 137) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 16 203 61 188 228 218 81 142 4 235 18 92 243 180 75 239 4 81 186 211 231 203 186 213 50 139 133 187 53 134 81 180 120 188 242 0 104 79 211 16 230 209 74 205 35 220 42 118 4 117 223 15 91 138 117 140) :der-encode #f :tests '(#(123 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 156 167 152 127 51 103 169 81 110 202 87 133 80 152 212 170 175 40 148 56 217 173 123 57 220 200 17 16) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 44 39 115 42 170 163 248 177 102 100 164 138 29 208 111 192 254 64 246 87 66 117 30 92 4 183 239 245 7 128 75 45 190 231 159 254 86 220 79 74 96 98 206 214 243 117 184 11 90 210 207 58 41 33 179 149) :der-encode #f :tests '(#(124 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 114 149 188 56 183 107 204 215 99 93 101 97 209 240 83 221 155 7 148 25 36 159 148 54 140 141 49 51) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 140 237 85 104 119 238 21 175 49 74 237 93 252 67 160 15 187 118 38 251 220 123 129 255 125 190 162 248 152 245 226 111 127 195 39 109 162 168 232 105 176 175 188 65 239 59 64 50 96 128 170 133 206 98 194 171) :der-encode #f :tests '(#(125 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 147 143 45 178 183 32 97 171 215 235 110 92 143 230 133 57 30 150 110 192 199 105 208 197 56 224 103 138) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 66 177 155 34 80 108 79 216 159 162 140 89 9 217 127 143 254 189 200 40 4 220 199 191 106 87 10 226 26 151 78 224 139 72 79 160 94 31 187 137 196 140 80 117 75 161 228 10 101 138 92 237 64 156 99 97) :der-encode #f :tests '(#(126 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 127 144 124 142 50 230 14 43 164 3 62 231 214 95 63 232 253 35 113 156 122 156 111 94 82 241 140 71) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 32 149 225 33 22 206 189 212 232 188 28 193 132 181 56 177 81 95 120 158 59 228 176 58 65 131 250 229 208 146 110 68 104 117 171 220 209 44 130 57 230 7 150 28 173 208 10 46 137 157 130 29 177 29 86 121) :der-encode #f :tests '(#(127 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 52 195 151 140 58 29 172 146 31 98 53 200 42 2 237 185 52 34 133 70 148 38 187 16 248 40 151 196) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 88 248 46 178 202 110 52 116 169 14 41 172 86 220 182 61 136 230 105 224 164 2 4 230 32 42 247 197 160 232 94 64 57 243 67 37 91 79 228 189 193 25 26 120 69 189 215 235 144 142 205 135 121 162 121 99) :der-encode #f :tests '(#(128 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 151 1 214 82 61 61 63 91 138 200 64 38 128 179 202 184 150 110 38 81 207 193 115 159 205 60 7 73) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 113 242 196 167 195 247 19 17 167 147 69 143 241 34 98 168 99 81 143 179 13 187 122 128 112 16 48 184 182 176 132 40 250 189 182 156 138 142 158 50 125 174 208 121 95 184 78 13 136 23 8 96 34 211 178 59) :der-encode #f :tests '(#(129 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 86 66 119 250 84 55 24 48 235 120 80 39 139 150 153 216 91 197 144 88 49 164 42 155 244 208 122 243) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 60 252 246 78 236 233 148 195 92 86 233 21 228 237 24 131 186 110 195 79 227 150 193 26 205 143 71 210 99 205 251 170 52 64 17 0 181 177 10 247 113 187 70 192 213 52 70 247 170 132 121 86 201 54 52 148) :der-encode #f :tests '(#(130 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 119 148 251 222 230 56 246 87 172 30 76 101 40 76 20 75 62 250 123 244 16 158 108 202 96 92 79 76) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 76 64 77 236 188 6 151 178 7 250 8 152 46 240 254 219 0 30 235 67 243 116 4 218 185 122 154 119 71 25 27 194 64 223 212 64 39 78 6 149 86 17 249 146 63 173 105 73 178 204 21 122 24 92 130 41) :der-encode #f :tests '(#(131 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 181 32 13 167 164 88 55 245 183 28 71 225 185 76 120 98 161 228 190 203 163 10 144 138 218 33 148 135) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 123 228 176 234 11 21 185 111 145 49 44 21 200 22 41 228 12 68 24 247 11 134 197 188 220 37 143 217 121 203 239 142 162 167 124 160 146 219 14 185 84 169 227 62 130 185 197 241 16 200 201 144 185 35 90 87) :der-encode #f :tests '(#(132 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 101 43 120 113 110 215 153 174 198 186 202 195 163 224 167 187 54 15 40 50 73 63 40 109 25 26 98 108) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 100 166 76 255 165 64 102 73 146 100 153 30 71 160 241 75 202 99 25 161 194 126 21 8 226 1 107 86 189 167 193 122 4 217 203 136 234 219 114 150 207 135 223 191 173 254 101 5 104 55 167 151 214 105 151 221) :der-encode #f :tests '(#(133 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 151 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 162) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 61 76 78 60 91 167 165 51 200 163 56 109 111 247 122 129 53 19 70 225 137 75 37 96 180 6 166 62 163 73 119 89 70 121 158 235 39 73 38 180 217 87 50 143 108 125 80 246 118 2 145 172 218 235 17 79) :der-encode #f :tests '(#(134 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 171 168 216 156 44 148 186 88 231 13 183 134 166 24 29 192 231 29 22 243 244 61 150 0 252 76 143 243) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 77 184 232 172 67 242 45 247 92 156 9 254 25 59 156 216 61 92 155 115 243 125 20 148 118 23 36 176 167 96 130 195 93 168 98 161 226 232 98 111 250 148 237 24 252 177 216 151 236 122 181 44 50 37 83 255) :der-encode #f :tests '(#(135 "point duplication during verification" #vu8(49 50 51 52 48 48) #vu8(122 242 149 230 228 120 114 82 243 76 82 122 245 98 202 39 33 74 102 246 214 219 79 210 193 18 181 100 177 208 16 247 64 98 238 170 192 206 203 44 60 44 77 40 138 87 107 246 240 160 3 71 198 165 181 98) #t ("PointDuplication")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 77 184 232 172 67 242 45 247 92 156 9 254 25 59 156 216 61 92 155 115 243 125 20 148 118 23 36 176 48 96 177 230 200 155 3 228 71 47 205 181 123 60 234 110 179 237 46 191 171 95 212 201 76 163 109 0) :der-encode #f :tests '(#(136 "duplication bug" #vu8(49 50 51 52 48 48) #vu8(122 242 149 230 228 120 114 82 243 76 82 122 245 98 202 39 33 74 102 246 214 219 79 210 193 18 181 100 177 208 16 247 64 98 238 170 192 206 203 44 60 44 77 40 138 87 107 246 240 160 3 71 198 165 181 98) #f ("PointDuplication")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 43 146 38 130 8 213 34 69 12 66 243 252 189 164 9 195 172 226 165 248 87 234 16 97 44 96 147 248 49 94 178 212 72 19 78 113 107 3 32 120 182 131 1 98 46 60 33 134 171 88 61 151 110 118 159 235) :der-encode #f :tests '(#(137 "comparison with point at infinity " #vu8(49 50 51 52 48 48) #vu8(71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138 43 38 164 34 7 167 20 129 59 158 112 7 125 246 152 184 41 209 88 219 226 198 37 186 84 84 183 31) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 77 75 213 105 61 134 221 154 96 22 186 128 109 128 49 249 77 200 226 211 60 111 88 113 160 11 100 115 42 70 98 242 149 36 236 231 84 130 139 157 130 156 10 7 36 217 189 157 40 141 33 248 126 63 177 250) :der-encode #f :tests '(#(138 "extreme value for k and edgecase s" #vu8(49 50 51 52 48 48) #vu8(51 183 228 152 188 218 26 51 230 26 103 175 86 163 109 18 223 112 50 37 93 223 94 30 198 90 86 105 71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 190 14 251 72 65 223 55 171 205 207 63 40 221 176 213 117 26 146 160 254 122 62 136 209 171 2 131 44 187 83 204 214 107 156 14 66 67 128 105 61 100 22 252 46 26 60 121 58 53 95 125 5 249 99 244 53) :der-encode #f :tests '(#(139 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(51 183 228 152 188 218 26 51 230 26 103 175 86 163 109 18 223 112 50 37 93 223 94 30 198 90 86 105 184 238 191 109 69 94 87 224 182 93 224 32 27 215 179 21 69 129 51 174 94 44 161 176 215 33 236 63) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 188 2 114 227 105 58 5 231 136 57 44 136 15 157 233 92 114 226 147 253 27 19 241 226 42 153 7 163 105 149 6 228 89 15 169 12 98 87 177 196 227 99 44 204 72 108 184 51 203 188 191 33 180 162 96 65) :der-encode #f :tests '(#(140 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(51 183 228 152 188 218 26 51 230 26 103 175 86 163 109 18 223 112 50 37 93 223 94 30 198 90 86 105 172 154 144 136 30 156 82 4 238 121 192 29 247 218 98 224 167 69 99 111 139 24 150 233 81 82 220 127) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 168 59 195 233 4 60 185 56 218 225 103 187 234 47 125 98 52 134 244 3 141 244 83 18 232 70 123 218 115 99 250 88 175 54 58 113 131 93 160 148 19 200 130 39 132 156 111 15 254 142 78 64 175 245 16 35) :der-encode #f :tests '(#(141 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(51 183 228 152 188 218 26 51 230 26 103 175 86 163 109 18 223 112 50 37 93 223 94 30 198 90 86 105 43 38 164 34 7 167 20 129 59 158 112 7 125 246 152 184 41 209 88 219 226 198 37 186 84 84 183 32) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 59 208 138 28 70 99 133 100 82 29 237 63 167 124 233 201 85 56 228 151 3 235 185 248 211 107 230 247 39 111 250 18 128 81 103 31 126 76 99 233 184 19 45 233 243 56 156 197 37 215 38 130 182 1 158 195) :der-encode #f :tests '(#(142 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(51 183 228 152 188 218 26 51 230 26 103 175 86 163 109 18 223 112 50 37 93 223 94 30 198 90 86 105 30 210 117 60 224 229 14 165 115 186 80 5 89 249 72 131 139 149 136 157 15 178 26 242 206 133 167 96) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 163 219 43 62 44 98 196 43 244 251 14 17 194 144 143 209 127 232 61 163 172 156 9 128 35 78 253 189 60 190 236 64 39 189 124 16 155 39 174 47 124 240 77 198 94 234 241 63 170 34 77 50 162 15 49 99) :der-encode #f :tests '(#(143 "extreme value for k" #vu8(49 50 51 52 48 48) #vu8(51 183 228 152 188 218 26 51 230 26 103 175 86 163 109 18 223 112 50 37 93 223 94 30 198 90 86 105 88 227 117 24 198 228 122 132 222 16 204 178 84 192 54 147 39 17 69 241 62 0 169 18 55 164 165 71) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 96 108 230 248 199 122 193 125 91 117 21 213 133 30 237 21 94 161 32 205 7 202 66 119 179 91 141 54 95 113 107 98 174 233 168 26 1 27 209 210 188 234 243 125 95 58 97 229 247 48 126 11 185 200 146 200) :der-encode #f :tests '(#(144 "extreme value for k and edgecase s" #vu8(49 50 51 52 48 48) #vu8(13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 42 255 187 130 105 203 120 131 218 218 51 80 57 69 121 145 46 247 86 168 223 107 221 125 163 93 57 142 144 33 61 147 130 179 213 251 157 222 130 114 77 56 229 103 140 23 230 16 244 23 207 230 247 239 205 145) :der-encode #f :tests '(#(145 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 184 238 191 109 69 94 87 224 182 93 224 32 27 215 179 21 69 129 51 174 94 44 161 176 215 33 236 63) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 25 205 212 78 42 51 17 58 136 69 88 231 238 14 251 65 186 254 26 220 220 249 93 246 222 106 37 17 95 66 142 233 152 163 72 86 242 172 63 111 57 199 35 123 241 249 222 35 33 117 215 71 181 205 151 254) :der-encode #f :tests '(#(146 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 172 154 144 136 30 156 82 4 238 121 192 29 247 218 98 224 167 69 99 111 139 24 150 233 81 82 220 127) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 183 47 124 26 60 133 98 203 141 233 146 94 236 4 28 204 38 54 73 198 82 71 98 185 244 88 94 227 157 247 86 218 8 209 39 74 215 45 140 172 41 58 166 13 21 12 119 19 31 159 162 140 205 255 223 160) :der-encode #f :tests '(#(147 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 43 38 164 34 7 167 20 129 59 158 112 7 125 246 152 184 41 209 88 219 226 198 37 186 84 84 183 32) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 157 55 3 179 32 91 18 60 144 58 4 70 151 50 71 193 106 136 209 3 254 169 208 77 208 42 112 43 101 24 107 119 123 87 234 222 232 21 76 2 252 224 233 92 63 6 20 104 73 155 172 61 198 2 158 140) :der-encode #f :tests '(#(148 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 30 210 117 60 224 229 14 165 115 186 80 5 89 249 72 131 139 149 136 157 15 178 26 242 206 133 167 96) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 62 165 114 80 90 72 177 190 208 133 149 61 167 212 201 99 194 197 182 173 153 119 157 157 84 186 64 18 148 71 0 116 224 37 45 161 89 160 192 208 178 248 212 194 66 203 148 186 178 194 2 12 75 45 244 153) :der-encode #f :tests '(#(149 "extreme value for k" #vu8(49 50 51 52 48 48) #vu8(13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 88 227 117 24 198 228 122 132 222 16 204 178 84 192 54 147 39 17 69 241 62 0 169 18 55 164 165 71) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 88 170 86 247 114 192 114 111 36 198 184 158 78 205 172 36 53 75 158 153 202 163 246 211 118 20 2 205) :der-encode #f :tests '(#(150 "testing point duplication" #vu8(49 50 51 52 48 48) #vu8(117 59 180 0 120 147 64 129 215 189 17 62 196 155 25 239 9 209 186 51 73 134 144 81 109 77 18 44 30 210 117 60 224 229 14 165 115 186 80 5 89 249 72 131 139 149 136 157 15 178 26 242 206 133 167 95) #f ()) #(151 "testing point duplication" #vu8(49 50 51 52 48 48) #vu8(98 133 128 169 173 176 38 4 82 91 30 230 177 53 225 169 199 69 2 24 36 88 44 82 56 90 129 115 30 210 117 60 224 229 14 165 115 186 80 5 89 249 72 131 139 149 136 157 15 178 26 242 206 133 167 95) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 127 22 221 178 179 130 244 23 5 81 119 135 39 4 43 99 123 83 104 189 205 54 147 34 8 180 190 50) :der-encode #f :tests '(#(152 "testing point duplication" #vu8(49 50 51 52 48 48) #vu8(117 59 180 0 120 147 64 129 215 189 17 62 196 155 25 239 9 209 186 51 73 134 144 81 109 77 18 44 30 210 117 60 224 229 14 165 115 186 80 5 89 249 72 131 139 149 136 157 15 178 26 242 206 133 167 95) #f ()) #(153 "testing point duplication" #vu8(49 50 51 52 48 48) #vu8(98 133 128 169 173 176 38 4 82 91 30 230 177 53 225 169 199 69 2 24 36 88 44 82 56 90 129 115 30 210 117 60 224 229 14 165 115 186 80 5 89 249 72 131 139 149 136 157 15 178 26 242 206 133 167 95) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 181 84 252 37 233 240 152 234 241 70 108 53 50 140 151 48 93 13 74 160 228 70 46 139 175 122 142 126 208 143 196 14 176 29 200 85 87 123 174 169 227 7 7 112 97 111 87 177 126 169 133 76 173 147 136 26) :der-encode #f :tests '(#(154 "pseudorandom signature" #vu8() #vu8(185 130 190 168 13 16 129 107 180 80 163 250 170 237 78 213 79 177 151 179 191 249 90 242 93 125 55 134 158 110 162 229 135 19 241 48 77 41 222 191 133 89 167 74 137 224 24 186 226 139 5 85 110 84 130 161) #t ()) #(155 "pseudorandom signature" #vu8(77 115 103) #vu8(77 171 197 254 150 43 95 138 102 129 233 74 33 101 217 182 190 25 64 242 14 39 206 183 63 196 234 125 116 110 155 186 126 251 144 252 236 194 99 194 41 161 109 128 157 53 71 194 138 38 205 113 165 42 189 197) #t ()) #(156 "pseudorandom signature" #vu8(49 50 51 52 48 48) #vu8(149 177 30 50 0 7 162 224 248 206 0 249 5 140 169 185 25 232 214 170 213 68 168 249 128 139 68 161 21 169 98 1 156 133 165 177 250 116 116 22 45 3 205 14 82 142 139 147 188 200 73 32 175 87 159 97) #t ()) #(157 "pseudorandom signature" #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #vu8(158 77 171 158 11 0 151 227 101 120 63 192 95 1 12 22 13 54 29 247 146 91 13 219 223 236 232 139 132 6 163 101 240 120 240 49 230 250 214 81 29 105 248 166 84 131 193 154 90 128 12 57 73 15 117 16) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 128 42 15 81 32 78 246 168 41 33 27 192 116 8 135 70 30 228 171 167 54 233 202 238 0 0 0 0 127 185 49 224 99 0 69 19 98 212 68 16 110 235 93 171 221 202 101 15 236 75 229 95 197 69 247 200) :der-encode #f :tests '(#(158 "x-coordinate of the public key has many trailing 0's" #vu8(77 101 115 115 97 103 101) #vu8(12 147 253 127 109 208 182 151 213 194 135 238 97 174 228 220 190 220 194 8 133 193 230 33 91 139 54 8 59 199 161 190 204 241 168 232 58 242 245 22 47 197 57 161 208 98 189 99 154 47 190 197 18 144 122 39) #t ()) #(159 "x-coordinate of the public key has many trailing 0's" #vu8(77 101 115 115 97 103 101) #vu8(158 11 98 10 47 49 58 218 117 100 99 162 41 136 175 182 87 27 59 3 10 66 133 177 133 225 204 128 195 235 160 76 66 230 77 64 40 172 171 205 203 123 46 237 27 60 251 86 11 141 125 20 251 38 172 163) #t ()) #(160 "x-coordinate of the public key has many trailing 0's" #vu8(77 101 115 115 97 103 101) #vu8(163 6 245 0 218 79 10 48 148 100 121 147 106 175 156 99 118 118 176 240 45 32 174 13 152 28 37 235 1 86 71 242 80 11 203 227 32 75 219 128 73 114 184 65 137 11 78 83 25 108 216 177 136 153 49 81) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 203 50 12 132 242 108 0 161 180 173 113 70 145 76 174 18 101 41 22 93 231 54 61 138 239 154 189 5 163 151 212 107 135 40 49 118 183 246 157 161 249 70 21 202 68 49 252 71 178 160 230 12 0 0 0 0) :der-encode #f :tests '(#(161 "y-coordinate of the public key has many trailing 0's" #vu8(77 101 115 115 97 103 101) #vu8(4 240 13 212 79 221 138 230 176 139 134 204 189 215 214 21 170 158 73 138 137 179 80 148 200 169 166 254 73 97 122 22 23 197 108 233 13 65 197 62 239 78 98 143 36 192 71 160 110 2 193 249 33 35 68 31) #t ()) #(162 "y-coordinate of the public key has many trailing 0's" #vu8(77 101 115 115 97 103 101) #vu8(18 134 246 167 55 91 246 128 81 227 27 46 50 181 246 192 152 140 145 137 121 146 86 231 206 100 226 145 82 211 193 249 231 119 242 60 23 203 200 50 208 229 168 75 182 139 19 222 191 57 56 120 209 160 100 152) #t ()) #(163 "y-coordinate of the public key has many trailing 0's" #vu8(77 101 115 115 97 103 101) #vu8(88 40 37 223 35 104 220 185 47 187 163 250 100 84 209 73 211 184 96 227 255 50 106 254 54 33 88 19 73 51 79 198 167 4 24 219 196 84 218 106 153 123 200 55 98 112 195 163 136 99 173 178 170 112 187 15) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 0 0 0 0 129 223 151 23 68 162 90 201 148 114 195 255 90 143 196 155 134 252 159 181 112 68 143 249 119 242 208 124 28 146 150 178 247 116 120 209 61 90 177 198 57 147 150 47 45 208 142 231 195 19 222 206) :der-encode #f :tests '(#(164 "x-coordinate of the public key is small" #vu8(77 101 115 115 97 103 101) #vu8(90 17 113 140 144 160 36 89 128 15 16 158 78 132 12 194 97 215 130 214 78 28 138 71 18 221 144 129 210 131 177 193 225 16 164 98 10 105 111 223 116 169 199 121 35 82 19 157 84 204 237 140 151 61 158 126) #t ()) #(165 "x-coordinate of the public key is small" #vu8(77 101 115 115 97 103 101) #vu8(213 119 242 62 89 36 20 227 81 179 146 138 89 60 93 47 137 240 199 45 245 19 191 188 101 53 186 187 27 176 157 210 53 18 74 20 224 36 105 70 242 128 69 15 21 87 105 18 174 183 53 183 60 232 40 188) #t ()) #(166 "x-coordinate of the public key is small" #vu8(77 101 115 115 97 103 101) #vu8(175 143 131 110 99 153 93 199 21 164 211 198 132 44 78 108 108 244 88 109 247 110 70 89 216 9 238 201 133 190 253 11 27 184 174 24 44 5 208 113 218 209 128 34 77 34 83 61 206 115 125 77 218 116 213 209) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 13 40 180 247 254 31 108 111 166 167 125 17 228 59 211 233 39 23 88 223 52 198 95 165 119 166 221 59 0 0 0 0 40 1 212 131 130 134 22 132 184 210 203 215 229 152 154 13 124 21 167 232 25 181 115 170) :der-encode #f :tests '(#(167 "y-coordinate of the public key is small" #vu8(77 101 115 115 97 103 101) #vu8(21 106 167 134 146 199 142 151 105 171 167 40 201 238 167 136 53 181 80 0 144 27 165 7 148 163 62 252 185 120 93 244 10 34 19 55 116 129 49 27 26 129 211 16 231 99 65 146 123 143 186 13 110 62 199 173) #t ()) #(168 "y-coordinate of the public key is small" #vu8(77 101 115 115 97 103 101) #vu8(146 116 212 106 127 250 18 153 163 114 232 33 189 137 114 141 232 62 248 124 70 175 103 4 58 99 75 2 25 228 187 236 139 3 250 119 42 54 34 191 72 147 229 129 239 173 249 210 11 214 8 6 216 38 118 182) #t ()) #(169 "y-coordinate of the public key is small" #vu8(77 101 115 115 97 103 101) #vu8(207 106 156 186 40 94 86 73 60 187 70 43 123 22 18 138 12 241 199 5 132 71 148 93 174 243 65 73 41 166 135 131 158 142 224 60 83 114 161 19 115 60 8 31 65 61 31 148 5 221 254 71 225 143 204 84) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 13 40 180 247 254 31 108 111 166 167 125 17 228 59 211 233 39 23 88 223 52 198 95 165 119 166 221 59 215 193 52 169 254 65 146 2 167 146 25 160 188 255 11 175 203 6 109 74 27 196 226 13 101 19 77 85) :der-encode #f :tests '(#(170 "y-coordinate of the public key is large" #vu8(77 101 115 115 97 103 101) #vu8(89 46 84 160 234 149 10 199 205 131 15 86 199 149 74 118 159 129 170 85 232 225 1 190 225 155 59 39 72 55 95 221 77 144 20 201 182 11 99 199 11 254 152 200 68 190 102 143 45 58 46 37 146 98 185 69) #t ()) #(171 "y-coordinate of the public key is large" #vu8(77 101 115 115 97 103 101) #vu8(30 192 239 77 91 237 175 229 8 31 122 218 227 45 180 208 170 148 111 19 10 206 218 186 226 109 144 220 98 126 129 215 235 53 143 89 232 168 99 5 39 212 232 148 109 28 173 33 150 118 24 54 217 125 149 60) #t ()) #(172 "y-coordinate of the public key is large" #vu8(77 101 115 115 97 103 101) #vu8(95 175 3 94 213 119 78 235 10 220 24 127 244 133 168 70 170 42 188 241 231 248 89 177 185 16 242 92 139 241 42 28 0 177 143 102 194 40 53 45 228 156 196 251 130 122 9 252 134 247 34 206 86 27 165 250) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 81 46 88 23 49 201 196 96 187 112 91 96 218 151 108 203 27 14 244 33 120 81 6 186 44 205 210 56 15 33 213 186 205 248 28 12 183 143 161 81 35 125 179 19 10 212 222 243 115 243 229 35 57 140 44 247) :der-encode #f :tests '(#(173 "y-coordinate of the public key has many trailing 1's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(82 178 211 105 241 141 245 99 114 175 231 254 179 132 19 242 50 180 251 156 161 108 111 111 237 198 65 137 193 177 159 19 119 115 239 50 1 205 52 28 56 30 79 148 73 204 14 108 104 138 53 29 122 96 112 178) #t ("GroupIsomorphism")) #(174 "y-coordinate of the public key has many trailing 1's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(91 136 157 40 138 170 129 103 77 50 0 110 129 39 156 87 237 86 160 53 200 120 211 226 182 135 190 195 13 166 33 213 250 152 19 38 60 127 88 248 224 21 93 111 12 51 10 86 197 148 222 252 46 189 240 160) #t ("GroupIsomorphism")) #(175 "y-coordinate of the public key has many trailing 1's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(182 248 168 1 135 24 10 173 138 92 137 107 226 20 49 70 1 161 88 95 44 203 40 188 126 142 143 1 169 12 104 193 74 103 245 213 156 236 112 220 15 71 59 92 20 1 59 5 109 18 203 192 247 21 59 29) #t ("GroupIsomorphism")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 172 85 209 179 254 212 174 224 63 163 97 93 34 90 156 186 92 2 132 65 111 186 249 167 97 53 247 98 23 168 136 57 91 206 211 73 119 168 72 35 112 213 110 188 98 170 28 168 27 195 48 244 157 74 20 29) :der-encode #f :tests '(#(176 "x-coordinate of the public key is small on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(22 212 168 80 156 155 206 44 115 248 219 75 115 37 124 126 51 244 23 38 194 92 76 100 84 107 29 204 121 186 53 169 109 35 69 173 25 79 57 16 145 32 157 252 206 215 153 23 224 77 243 182 95 68 209 235) #t ("GroupIsomorphism")) #(177 "x-coordinate of the public key is small on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(93 161 86 151 187 228 235 167 112 126 52 159 243 35 157 80 132 85 55 129 19 210 78 126 29 122 2 12 69 190 68 165 112 251 83 12 73 215 89 113 44 16 4 19 69 247 192 137 10 121 70 217 29 50 186 198) #t ("GroupIsomorphism")) #(178 "x-coordinate of the public key is small on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(193 248 212 52 121 196 242 155 25 185 178 199 181 116 112 16 73 20 64 116 108 200 0 213 190 137 176 17 129 84 52 139 124 55 240 80 77 202 43 17 89 65 247 186 88 87 50 30 174 143 100 23 91 233 203 185) #t ("GroupIsomorphism")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 139 49 159 46 208 116 162 14 196 45 134 156 127 153 189 145 70 237 130 99 41 123 254 0 79 39 197 155 18 15 150 52 61 235 128 9 62 203 118 149 194 210 165 190 153 55 162 88 114 61 120 237 0 170 30 223) :der-encode #f :tests '(#(179 "y-coordinate of the public key is small on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(135 21 129 181 0 146 87 130 17 22 14 71 13 221 170 100 13 90 45 158 34 79 175 202 135 145 6 212 190 112 253 92 117 145 163 19 15 92 42 245 54 255 255 142 114 193 98 81 116 76 151 150 143 146 23 40) #t ("GroupIsomorphism")) #(180 "y-coordinate of the public key is small on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(169 135 53 229 101 144 34 176 39 74 230 247 188 177 100 110 158 107 75 136 64 141 179 249 38 236 204 137 169 35 255 94 21 224 215 100 205 92 239 255 197 196 12 8 44 110 183 114 219 118 98 251 27 130 213 37) #t ("GroupIsomorphism")) #(181 "y-coordinate of the public key is small on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(169 107 92 36 227 61 89 0 76 243 26 174 244 74 228 199 87 158 11 91 33 154 178 93 127 28 105 10 136 192 19 120 132 124 56 65 244 158 193 72 64 226 208 35 215 185 18 181 3 242 217 138 146 59 232 201) #t ("GroupIsomorphism")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 139 49 159 46 208 116 162 14 196 45 134 156 127 153 189 145 70 237 130 99 41 123 254 0 79 39 197 155 197 177 158 117 232 87 230 124 235 76 185 143 178 255 49 201 23 103 100 255 37 157 17 8 126 30 162 32) :der-encode #f :tests '(#(182 "y-coordinate of the public key is large on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(107 87 183 58 183 195 155 86 152 84 157 213 205 212 223 115 152 24 27 85 110 124 114 131 55 94 63 134 159 89 209 134 61 111 214 1 50 71 212 230 120 161 196 252 29 137 109 198 97 250 49 251 115 195 63 0) #t ("GroupIsomorphism")) #(183 "y-coordinate of the public key is large on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(47 133 175 126 83 95 102 207 201 169 218 183 190 120 22 49 221 98 43 228 53 215 100 43 91 81 252 199 97 147 1 194 28 147 66 85 223 147 238 221 91 69 156 141 210 128 253 208 126 230 86 167 20 125 77 105) #t ("GroupIsomorphism")) #(184 "y-coordinate of the public key is large on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(152 168 169 143 204 130 248 4 168 35 204 145 7 36 55 207 216 131 34 184 103 22 134 81 127 25 120 171 106 195 232 55 118 104 91 206 206 254 186 228 115 172 7 199 113 232 59 12 90 85 126 254 131 80 32 54) #t ("GroupIsomorphism")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 197 220 81 53 240 80 169 107 187 13 33 136 81 149 180 154 87 77 81 152 186 172 75 70 2 178 27 200 181 243 139 127 230 97 0 63 174 225 183 175 103 14 22 91 250 183 11 1 137 101 232 51 41 212 5 188) :der-encode #f :tests '(#(185 "y-coordinate of the public key has many trailing 0's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(105 156 64 183 53 35 107 217 35 151 112 165 222 44 26 117 84 99 30 107 166 239 81 47 133 83 208 47 11 202 156 81 108 164 5 255 201 174 45 206 225 42 215 217 107 88 107 253 200 24 163 212 93 207 207 38) #t ("GroupIsomorphism")) #(186 "y-coordinate of the public key has many trailing 0's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(118 138 129 157 57 67 252 48 120 26 174 242 143 161 32 24 76 114 18 208 145 31 224 61 252 140 98 96 81 179 219 14 28 62 147 145 73 204 191 157 70 25 187 191 240 226 225 116 17 15 110 206 67 19 180 202) #t ("GroupIsomorphism")) #(187 "y-coordinate of the public key has many trailing 0's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(88 252 192 255 177 37 194 60 67 87 53 183 195 144 105 32 55 192 58 103 101 239 123 83 101 161 125 212 149 24 210 157 120 237 169 203 37 3 253 227 141 59 115 214 251 144 160 212 10 35 240 236 38 22 105 105) #t ("GroupIsomorphism")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 193 181 106 26 209 84 225 21 86 183 35 252 116 147 243 110 102 80 157 143 104 250 208 230 44 64 240 133 155 4 120 10 133 230 154 191 152 222 243 51 92 230 67 205 53 84 22 122 139 80 213 150 185 83 136 149) :der-encode #f :tests '(#(188 "x-coordinate of the public key has many trailing 1's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(209 147 238 10 61 66 162 58 240 24 171 144 137 107 53 213 194 80 24 123 249 251 28 202 195 100 116 140 160 146 42 204 199 86 45 1 113 9 233 29 47 131 228 139 250 60 31 162 238 4 216 70 155 233 64 51) #t ("GroupIsomorphism")) #(189 "x-coordinate of the public key has many trailing 1's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(9 116 82 29 124 231 83 222 165 209 21 111 180 217 146 204 97 64 121 235 134 119 171 54 164 7 138 79 131 116 223 186 232 208 66 154 111 186 96 251 181 210 253 85 152 86 165 215 57 243 154 162 191 29 161 201) #t ("GroupIsomorphism")) #(190 "x-coordinate of the public key has many trailing 1's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(98 95 71 60 162 209 91 183 241 45 161 35 95 144 173 203 105 237 72 24 116 108 174 46 45 178 111 230 74 184 23 246 241 185 200 196 159 104 27 237 21 104 52 111 83 236 191 172 253 82 212 94 39 171 203 176) #t ("GroupIsomorphism"))))
null
https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/8d3be98032133507b87d6c0466d60f982ebf9b15/ext/crypto/tests/testvectors/signature/ecdsa_brainpoolP224r1_sha224_p1363_test.scm
scheme
(test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 87 46 171 115 118 208 82 223 196 9 35 219 37 52 46 169 203 252 228 184 88 30 16 74 76 143 55 201 74 112 14 197 220 5 164 129 178 182 149 50 12 111 26 210 221 134 40 99 60 219 117 169 18 69 194 101) :der-encode #f :tests '(#(1 "signature malleability" #vu8(49 50 51 52 48 48) #vu8(203 104 172 151 101 199 100 23 133 223 35 126 153 81 225 66 149 129 135 154 242 99 20 96 4 137 97 211 19 156 120 36 58 110 54 225 36 213 245 225 75 76 184 117 74 189 242 15 241 165 1 213 102 106 66 143) #t ()) #(2 "Modified r or s, e.g. by adding or subtracting the order of the group" #vu8(49 50 51 52 48 48) #vu8(1 163 41 225 65 140 10 202 157 175 247 83 164 15 34 220 219 102 152 67 230 96 65 209 3 170 48 245 114 0 196 36 188 133 235 213 47 165 5 66 58 68 42 132 67 35 134 88 202 59 124 57 186 206 63 61 81 16) #f ()) #(3 "Modified r or s, e.g. by adding or subtracting the order of the group" #vu8(49 50 51 52 48 48) #vu8(12 88 136 18 192 124 2 110 164 57 12 166 220 127 26 86 59 149 52 176 123 123 168 67 161 30 49 204 196 36 188 133 235 213 47 165 5 66 58 68 42 132 67 35 134 88 202 59 124 57 186 206 63 61 81 16) #f ()) #(4 "Modified r or s, e.g. by adding or subtracting the order of the group" #vu8(49 50 51 52 48 48) #vu8(1 203 104 172 151 101 199 100 23 133 223 35 126 153 81 225 66 149 129 135 154 242 99 20 96 4 137 97 211 0 196 36 188 133 235 213 47 165 5 66 58 68 42 132 67 35 134 88 202 59 124 57 186 206 63 61 81 16) #f ()) #(5 "Modified r or s, e.g. by adding or subtracting the order of the group" #vu8(49 50 51 52 48 48) #vu8(52 151 83 104 154 56 155 232 122 32 220 129 102 174 30 189 106 126 120 101 13 156 235 159 251 118 158 45 196 36 188 133 235 213 47 165 5 66 58 68 42 132 67 35 134 88 202 59 124 57 186 206 63 61 81 16) #f ()) #(6 "Modified r or s, e.g. by adding or subtracting the order of the group" #vu8(49 50 51 52 48 48) #vu8(0 203 104 172 151 101 199 100 23 133 223 35 126 153 81 225 66 149 129 135 154 242 99 20 96 4 137 97 211 1 155 229 241 48 18 24 150 43 47 90 106 105 160 85 62 188 87 111 134 134 234 24 119 113 228 228 228 175) #f ()) #(7 "Modified r or s, e.g. by adding or subtracting the order of the group" #vu8(49 50 51 52 48 48) #vu8(0 203 104 172 151 101 199 100 23 133 223 35 126 153 81 225 66 149 129 135 154 242 99 20 96 4 137 97 211 1 196 36 188 133 235 213 47 165 5 66 58 68 42 132 67 35 134 88 202 59 124 57 186 206 63 61 81 16) #f ()) #(8 "Modified r or s, e.g. by adding or subtracting the order of the group" #vu8(49 50 51 52 48 48) #vu8(203 104 172 151 101 199 100 23 133 223 35 126 153 81 225 66 149 129 135 154 242 99 20 96 4 137 97 211 59 219 67 122 20 42 208 90 250 189 197 187 213 123 188 220 121 167 53 196 131 198 69 49 192 194 174 240) #f ()) #(9 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ("EdgeCase")) #(10 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #f ("EdgeCase")) #(11 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159) #f ("EdgeCase")) #(12 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158) #f ("EdgeCase")) #(13 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160) #f ("EdgeCase")) #(14 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255) #f ("EdgeCase")) #(15 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0) #f ("EdgeCase")) #(16 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ("EdgeCase")) #(17 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #f ("EdgeCase")) #(18 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159) #f ("EdgeCase")) #(19 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158) #f ("EdgeCase")) #(20 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160) #f ("EdgeCase")) #(21 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255) #f ("EdgeCase")) #(22 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0) #f ("EdgeCase")) #(23 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ("EdgeCase")) #(24 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #f ("EdgeCase")) #(25 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159) #f ("EdgeCase")) #(26 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158) #f ("EdgeCase")) #(27 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160) #f ("EdgeCase")) #(28 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255) #f ("EdgeCase")) #(29 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0) #f ("EdgeCase")) #(30 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ("EdgeCase")) #(31 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #f ("EdgeCase")) #(32 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159) #f ("EdgeCase")) #(33 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158) #f ("EdgeCase")) #(34 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160) #f ("EdgeCase")) #(35 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255) #f ("EdgeCase")) #(36 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0) #f ("EdgeCase")) #(37 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ("EdgeCase")) #(38 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #f ("EdgeCase")) #(39 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159) #f ("EdgeCase")) #(40 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158) #f ("EdgeCase")) #(41 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160) #f ("EdgeCase")) #(42 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255) #f ("EdgeCase")) #(43 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0) #f ("EdgeCase")) #(44 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ("EdgeCase")) #(45 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #f ("EdgeCase")) #(46 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159) #f ("EdgeCase")) #(47 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158) #f ("EdgeCase")) #(48 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160) #f ("EdgeCase")) #(49 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255) #f ("EdgeCase")) #(50 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0) #f ("EdgeCase")) #(51 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ("EdgeCase")) #(52 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #f ("EdgeCase")) #(53 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 159) #f ("EdgeCase")) #(54 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158) #f ("EdgeCase")) #(55 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160) #f ("EdgeCase")) #(56 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 255) #f ("EdgeCase")) #(57 "Signature with special case values for r and s" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0 215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 193 0) #f ("EdgeCase")) #(58 "Edge case for Shamir multiplication" #vu8(57 53 51 56 56) #vu8(14 126 202 178 39 111 3 92 13 199 5 32 235 213 174 60 183 183 168 242 31 165 104 126 238 146 196 98 133 168 83 50 248 200 153 181 61 67 9 27 2 230 149 107 57 24 23 225 117 168 177 244 13 202 126 0) #t ()) #(59 "special case hash" #vu8(50 50 53 52 54 50 56 57 56 52) #vu8(47 194 239 159 118 99 246 111 19 176 78 73 242 6 194 36 65 235 62 225 145 123 139 248 26 155 83 118 209 223 61 208 39 14 88 132 233 132 142 162 129 43 102 245 1 91 233 109 37 133 254 211 149 123 49 60) #t ()) #(60 "special case hash" #vu8(49 56 50 55 56 55 56 54 49 48) #vu8(198 130 88 123 244 62 12 149 78 181 139 188 254 185 77 250 200 186 212 4 153 90 194 110 142 81 255 32 146 191 16 218 16 50 76 195 34 247 156 65 45 174 211 5 178 117 252 25 147 191 58 245 35 222 214 42) #t ()) #(61 "special case hash" #vu8(49 53 49 56 56 54 49 55 48 57) #vu8(2 93 28 241 111 3 52 31 60 141 22 167 120 57 181 193 214 150 54 61 174 137 141 145 225 74 213 34 183 55 156 195 92 151 168 240 139 14 251 50 238 130 206 14 25 17 105 93 55 46 230 214 121 236 84 102) #t ()) #(62 "special case hash" #vu8(50 49 50 57 50 51 51 52 50 50) #vu8(192 201 73 224 240 248 87 24 2 234 126 2 97 124 169 37 185 93 41 10 23 79 104 109 128 187 161 212 185 102 23 60 227 241 60 165 76 205 200 162 73 254 167 46 50 96 173 62 120 84 167 49 5 29 140 3) #t ()) #(63 "special case hash" #vu8(49 50 50 49 57 55 57 48 53 57) #vu8(93 87 241 66 117 148 124 155 255 234 102 249 243 10 226 3 25 69 53 248 2 12 66 187 193 239 236 115 195 88 101 27 162 82 124 50 216 88 101 124 207 8 229 53 211 40 81 251 216 195 84 119 186 23 86 128) #t ()) #(64 "special case hash" #vu8(50 51 48 50 53 54 55 54 49 49) #vu8(19 59 177 47 16 150 152 157 200 103 216 116 246 117 253 249 233 121 117 194 226 44 113 228 79 89 191 53 101 87 238 178 181 180 241 247 200 81 132 220 198 83 133 12 52 177 195 72 13 47 50 209 86 124 37 193) #t ()) #(65 "special case hash" #vu8(49 49 48 53 56 54 56 52 55 50) #vu8(209 220 125 28 200 134 202 144 224 217 96 182 199 253 169 46 213 130 236 97 108 28 121 177 113 239 49 8 65 167 210 20 56 231 195 75 39 23 96 5 239 103 192 74 99 243 98 210 218 241 11 98 197 59 136 180) #t ()) #(66 "special case hash" #vu8(49 52 54 54 54 49 52 52 52 50) #vu8(158 195 183 180 160 241 35 81 105 182 74 32 88 77 54 185 107 183 162 189 224 13 35 22 60 195 177 191 172 50 239 59 158 148 141 150 127 150 205 8 80 120 9 227 185 160 224 147 190 62 118 184 24 51 29 213) #t ()) #(67 "special case hash" #vu8(52 52 49 57 53 54 52 50 48) #vu8(57 42 227 129 218 76 207 217 213 173 9 61 73 178 45 87 148 17 247 193 205 4 232 132 115 171 110 245 162 137 139 139 241 32 209 142 78 224 209 92 65 144 68 50 77 227 192 146 126 233 15 214 243 135 17 244) #t ()) #(68 "special case hash" #vu8(49 57 54 57 52 56 54 48 54 52) #vu8(163 123 12 200 127 109 70 32 48 48 48 215 172 74 101 114 249 76 12 244 79 10 3 92 14 89 208 124 48 199 172 216 219 158 114 1 34 8 240 141 181 56 26 30 84 250 9 140 3 20 160 154 48 88 196 33) #t ()) #(69 "special case hash" #vu8(50 50 51 53 54 55 50 56 56 51) #vu8(98 246 96 217 58 69 223 163 182 97 248 182 164 213 224 110 90 30 232 168 133 90 186 250 64 115 181 19 214 151 143 93 168 175 204 91 57 95 212 181 243 192 253 183 162 104 158 109 228 109 8 251 157 231 24 96) #t ()) #(70 "special case hash" #vu8(50 50 53 55 56 52 51 55 48 51) #vu8(97 175 154 44 162 5 3 253 98 188 60 111 132 52 153 92 108 243 3 126 182 249 255 98 19 72 207 83 9 248 246 71 19 135 105 84 141 180 96 239 221 131 35 248 202 209 138 112 113 211 208 77 106 211 61 130) #t ()) #(71 "special case hash" #vu8(57 52 52 53 48 48 57 52 54) #vu8(14 69 156 254 55 1 124 139 96 94 56 191 93 37 23 101 118 212 117 250 136 222 210 123 226 106 188 167 177 187 106 96 204 195 212 142 141 29 76 83 249 1 66 128 110 68 217 148 158 188 170 5 184 62 32 244) #t ()) #(72 "special case hash" #vu8(49 54 56 55 55 56 57 52 49 48) #vu8(208 24 72 130 189 214 250 9 153 108 47 236 243 205 38 237 134 163 206 21 152 126 6 219 133 11 139 43 207 240 114 178 124 51 249 22 129 211 233 90 71 190 192 0 204 150 197 220 145 246 142 204 194 28 163 196) #t ()) #(73 "special case hash" #vu8(51 57 51 50 54 49 50 50 56) #vu8(53 126 150 171 84 244 219 179 166 163 169 209 237 230 223 82 148 99 154 237 253 234 150 231 255 201 218 49 36 235 107 127 85 144 103 57 49 62 162 102 90 5 4 163 176 191 122 155 50 156 105 15 74 46 223 81) #t ()) #(74 "special case hash" #vu8(49 48 55 51 53 55 49 48 57 53) #vu8(11 170 247 157 82 53 227 38 142 85 67 28 189 121 0 70 194 88 30 189 63 139 144 98 123 212 107 139 131 213 111 107 86 202 147 129 177 76 168 136 40 27 72 28 248 40 233 180 59 13 65 129 8 232 45 88) #t ()) #(75 "special case hash" #vu8(54 48 56 56 55 52 55 52) #vu8(126 190 241 173 65 222 148 52 235 63 111 131 51 143 1 9 102 108 38 77 137 18 51 66 176 144 15 5 120 163 169 250 114 1 196 143 146 131 68 0 74 31 81 128 83 9 157 248 105 8 222 41 238 183 106 76) #t ()) #(76 "special case hash" #vu8(49 49 57 50 53 54 57 57 54 50) #vu8(159 32 171 239 240 175 150 93 169 197 28 153 80 124 245 249 29 117 242 63 224 43 97 21 2 150 22 124 191 111 237 138 142 247 38 242 246 98 156 78 75 80 179 194 206 20 255 67 159 233 191 230 21 120 104 212) #t ()) #(77 "special case hash" #vu8(57 48 48 55 54 48 57 51) #vu8(90 214 127 240 221 248 203 136 64 121 116 248 63 234 67 217 209 71 203 178 61 186 38 31 173 173 174 219 127 211 28 204 75 54 5 219 66 183 0 162 69 223 143 198 14 251 241 64 106 251 77 108 140 22 224 163) #t ()) #(78 "special case hash" #vu8(49 54 48 50 56 51 54 49 51 55) #vu8(64 224 189 154 47 165 168 134 120 200 92 63 77 39 226 174 45 208 70 242 154 54 57 236 47 242 81 26 22 205 73 33 92 176 5 51 253 19 154 225 211 99 29 69 251 6 213 236 209 19 138 180 108 72 164 92) #t ()) #(79 "special case hash" #vu8(50 48 56 48 50 52 53 54 55 52) #vu8(154 112 93 220 135 103 229 76 236 77 28 55 162 70 11 60 11 49 233 129 28 58 66 117 38 73 156 1 54 166 185 220 215 200 168 30 52 175 223 132 92 76 192 231 52 85 1 27 188 215 152 127 136 114 88 186) #t ()) #(80 "special case hash" #vu8(49 55 57 56 50 55 52 54 53 57) #vu8(165 26 98 91 153 86 141 0 62 75 150 230 147 19 107 167 82 33 232 229 108 154 181 233 236 104 22 238 126 32 137 24 120 85 22 205 167 207 112 135 13 216 18 232 14 143 159 27 82 72 217 25 177 255 29 6) #t ()) #(81 "special case hash" #vu8(49 49 53 53 53 55 55 55 50 48) #vu8(71 32 249 55 16 13 245 46 106 225 186 244 15 139 201 80 229 175 43 31 148 125 4 23 128 74 130 37 139 130 34 115 251 93 71 60 156 136 170 60 141 222 161 103 97 156 218 18 238 65 206 101 222 38 138 117) #t ()) #(82 "special case hash" #vu8(50 52 51 50 52 55 52 54 54 52) #vu8(61 40 29 152 182 166 118 166 237 167 87 13 123 79 154 8 233 36 199 26 253 44 182 224 98 167 235 253 132 70 228 39 71 163 82 81 142 246 142 255 5 86 149 180 118 107 220 42 216 211 250 151 188 32 43 67) #t ()) #(83 "special case hash" #vu8(50 52 49 55 50 56 50 50 55 55) #vu8(77 52 105 233 57 255 234 217 65 227 203 206 188 163 188 182 243 192 41 100 31 151 112 14 2 129 119 56 66 203 135 161 14 161 124 14 88 195 130 47 106 225 243 168 145 141 134 168 50 93 239 74 140 128 130 242) #t ()) #(84 "special case hash" #vu8(55 55 56 55 52 55 55 49) #vu8(33 229 27 121 232 85 78 34 147 124 62 91 25 131 179 119 98 89 30 33 245 112 110 92 25 130 165 12 75 205 189 35 176 164 113 219 132 209 238 62 223 118 119 187 177 67 7 236 197 225 2 49 116 236 91 140) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 160 239 125 177 190 224 174 219 90 86 52 244 243 177 184 141 151 210 160 127 128 106 113 142 254 25 1 77 174 225 4 63 158 146 156 50 215 74 176 228 238 186 38 35 241 123 162 129 182 190 135 116 91 89 246 14) :der-encode #f :tests '(#(85 "k*G has a large x-coordinate" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 219 238 223 136 75 12 41 251 205 81 217 33 45 95 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 156) #t ()) #(86 "r too large" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 209 215 135 176 159 7 87 151 218 137 245 126 200 192 254 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 156) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 58 221 164 7 186 215 245 147 232 61 125 72 79 209 76 35 221 161 127 141 70 12 34 42 167 37 117 119 205 98 68 59 43 119 2 145 246 89 4 218 207 117 255 151 95 26 102 113 135 224 228 245 12 20 136 156) :der-encode #f :tests '(#(87 "r,s are large" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 158 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 157) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 36 88 124 225 219 255 40 29 202 177 121 69 25 128 98 129 173 78 9 151 73 37 16 103 127 182 81 6 146 150 153 110 131 184 8 103 108 191 111 40 201 43 132 48 51 20 182 58 3 8 19 79 34 45 14 194) :der-encode #f :tests '(#(88 "r and s^-1 have a large Hamming weight" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 99 240 227 66 88 187 144 97 84 121 6 208 195 130 124 80 68 34 193 57 230 214 225 7 139 55 170 68) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 196 92 81 213 169 178 19 228 28 166 241 92 184 170 27 192 184 183 61 58 138 35 161 79 90 61 164 223 188 120 204 97 118 211 184 49 230 136 0 103 23 104 4 60 17 191 99 166 149 145 141 246 236 135 55 138) :der-encode #f :tests '(#(89 "r and s^-1 have a large Hamming weight" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 110 177 251 250 141 248 125 79 161 12 131 63 125 209 187 231 239 1 68 255 113 83 121 117 55 143 145 236) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 54 165 52 77 160 138 66 30 220 108 59 235 125 233 122 117 89 252 16 28 20 137 255 43 80 54 216 246 32 123 244 102 110 77 246 6 189 13 152 35 165 43 88 221 253 252 29 167 5 19 197 249 153 15 128 133) :der-encode #f :tests '(#(90 "small r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #t ()) #(91 "incorrect size of signature" #vu8(49 50 51 52 48 48) #vu8(1 1) #t ("SigSize")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 64 149 192 149 169 100 137 81 218 53 43 131 127 54 142 11 230 125 121 253 87 234 223 255 237 223 180 85 204 220 250 190 161 158 150 212 210 14 66 184 174 35 194 81 148 38 1 142 37 166 77 234 133 216 166 139) :der-encode #f :tests '(#(92 "small r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2) #t ()) #(93 "incorrect size of signature" #vu8(49 50 51 52 48 48) #vu8(1 2) #t ("SigSize")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 204 53 42 196 138 172 182 73 94 195 131 27 33 204 212 211 25 113 54 41 43 246 242 15 34 128 37 102 100 50 25 145 230 127 125 188 34 96 46 203 219 49 34 237 206 95 248 93 146 49 67 206 204 13 79 109) :der-encode #f :tests '(#(94 "small r and s" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3) #t ()) #(95 "incorrect size of signature" #vu8(49 50 51 52 48 48) #vu8(1 3) #t ("SigSize")) #(96 "r is larger than n" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 160 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 145 72 242 156 103 248 60 112 94 239 181 156 146 149 71 117 249 12 21 226 37 218 46 153 106 188 221 29 201 219 26 161 225 82 119 196 85 93 36 17 130 57 229 63 210 240 181 231 234 128 126 179 222 30 227 80) :der-encode #f :tests '(#(97 "s is larger than n" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 186 106 38) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 155 240 69 164 58 95 20 213 228 18 238 24 31 17 29 110 83 150 17 32 83 31 60 80 202 112 30 120 190 158 185 81 70 244 242 190 150 148 153 118 167 170 73 211 21 147 167 218 46 221 144 118 82 57 140 58) :der-encode #f :tests '(#(98 "small r and s^-1" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 157 254 92 253 155 2 254 122 111 116 123 243 29 213 129 208 169 60 254 204 102 161 23 61 97 29 253 60) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 135 115 158 40 33 237 149 103 232 135 2 250 140 109 8 60 151 193 243 241 235 50 209 63 117 31 176 115 109 2 235 160 94 140 185 70 114 208 158 188 17 5 29 82 236 123 212 220 119 103 48 27 103 3 66 18) :der-encode #f :tests '(#(99 "smallish r and s^-1" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 45 155 77 52 121 82 204 67 226 53 116 139 211 177 191 161 76 146 35 74 144 38 26 204 62 144 134 129 8 1 163 103 70 188 238) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 26 81 92 190 149 123 252 7 14 76 74 117 214 253 94 124 21 177 226 85 235 66 254 173 6 201 210 99 98 82 204 13 35 67 24 57 77 247 219 101 176 165 46 6 149 60 166 194 30 201 87 116 211 158 253 201) :der-encode #f :tests '(#(100 "100-bit r and small s^-1" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 51 230 126 55 179 43 68 85 128 191 78 251 168 189 244 101 50 216 19 107 235 33 219 241 120 9 12 126 125 173 44 170 142 181 44 239 141 131 15 216) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 214 161 110 25 78 18 185 109 184 225 187 2 80 217 80 247 179 18 155 20 187 160 239 177 87 196 66 62 98 90 12 140 32 131 139 217 127 188 137 241 103 0 40 117 74 9 173 40 246 45 229 238 166 224 123 193) :der-encode #f :tests '(#(101 "small r and 100 bit s^-1" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 115 22 138 137 148 229 247 23 147 8 28 183 175 190 60 10 244 191 122 163 54 207 157 227 30 248 83 20) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 192 18 149 13 7 75 176 27 10 25 136 165 181 155 149 145 4 39 91 175 117 126 83 2 155 4 106 21 66 245 15 226 127 62 186 201 3 101 88 239 48 235 203 129 32 39 191 14 244 108 218 81 150 149 65 187) :der-encode #f :tests '(#(102 "100-bit r and s^-1" #vu8(49 50 51 52 48 48) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 37 34 187 211 236 190 124 57 233 62 124 36 115 22 138 137 148 229 247 23 147 8 28 183 175 190 60 10 244 191 122 163 54 207 157 227 30 248 83 20) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 209 92 19 161 190 153 217 235 119 214 136 16 74 24 226 66 66 210 5 164 2 111 74 101 98 158 89 238 126 61 223 154 187 183 213 50 182 232 26 110 17 243 13 91 85 254 184 238 112 124 79 237 249 156 6 7) :der-encode #f :tests '(#(103 "r and s^-1 are close to n" #vu8(49 50 51 52 48 48) #vu8(215 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 31 71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 63 224 25 114 192 98 46 168 18 211 6 82 201 254 47 235 238 112 129 35 177 98 109 116 79 135 219 13 165 114 199 225 227 164 129 149 230 34 29 152 63 120 47 220 158 124 85 189 95 223 123 103 155 15 135 86) :der-encode #f :tests '(#(104 "s == 1" #vu8(49 50 51 52 48 48) #vu8(71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) #t ()) #(105 "s == 0" #vu8(49 50 51 52 48 48) #vu8(71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 212 182 229 17 36 6 251 116 59 107 181 95 73 234 32 48 217 4 66 8 49 235 221 172 214 123 186 137 101 34 101 56 75 117 216 80 231 194 127 78 51 237 108 87 109 240 255 150 148 112 169 239 37 255 175 205) :der-encode #f :tests '(#(106 "point at infinity during verify" #vu8(49 50 51 52 48 48) #vu8(107 224 154 85 19 33 179 67 21 12 24 18 186 232 125 204 104 139 94 37 182 239 94 81 210 211 201 207 71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 22 194 18 157 84 185 52 121 181 106 159 245 184 62 76 117 11 180 243 62 225 231 15 56 181 68 159 45 52 204 175 121 197 28 125 255 58 127 154 5 205 21 163 150 224 207 254 37 66 28 55 233 184 14 20 137) :der-encode #f :tests '(#(107 "edge case for signature malleability" #vu8(49 50 51 52 48 48) #vu8(107 224 154 85 19 33 179 67 21 12 24 18 186 232 125 204 104 139 94 37 182 239 94 81 210 211 201 208 107 224 154 85 19 33 179 67 21 12 24 18 186 232 125 204 104 139 94 37 182 239 94 81 210 211 201 207) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 101 171 160 228 66 122 10 229 88 114 26 90 142 114 203 55 98 235 80 34 59 190 76 65 164 80 254 73 200 29 58 228 134 71 139 66 152 201 67 40 61 46 194 19 11 172 34 250 188 82 247 67 177 171 127 167) :der-encode #f :tests '(#(108 "edge case for signature malleability" #vu8(49 50 51 52 48 48) #vu8(107 224 154 85 19 33 179 67 21 12 24 18 186 232 125 204 104 139 94 37 182 239 94 81 210 211 201 208 107 224 154 85 19 33 179 67 21 12 24 18 186 232 125 204 104 139 94 37 182 239 94 81 210 211 201 208) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 85 167 176 16 6 19 250 189 149 123 66 96 8 53 198 212 46 1 224 66 82 89 59 221 227 177 114 120 135 112 138 5 171 162 249 63 26 30 30 203 112 62 201 168 238 109 96 19 161 1 211 151 1 42 140 206) :der-encode #f :tests '(#(109 "u1 == 1" #vu8(49 50 51 52 48 48) #vu8(71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138 117 59 180 0 120 147 64 129 215 189 17 62 196 155 25 239 9 209 186 51 73 134 144 81 109 77 18 44) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 26 218 84 220 1 88 97 104 13 139 178 211 17 185 14 130 219 117 170 158 130 23 185 38 17 250 3 203 132 198 17 85 17 151 41 139 50 116 135 92 185 70 134 231 88 240 161 169 103 92 11 193 87 69 26 118) :der-encode #f :tests '(#(110 "u1 == n - 1" #vu8(49 50 51 52 48 48) #vu8(71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138 98 133 128 169 173 176 38 4 82 91 30 230 177 53 225 169 199 69 2 24 36 88 44 82 56 90 129 115) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 198 123 100 41 120 83 52 166 8 221 233 73 168 171 230 65 219 211 96 30 188 225 230 117 254 113 168 229 39 210 232 114 125 196 246 24 73 53 80 187 148 1 81 188 166 130 111 113 76 91 49 133 64 56 244 77) :der-encode #f :tests '(#(111 "u2 == 1" #vu8(49 50 51 52 48 48) #vu8(71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138 71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 29 204 122 90 209 17 163 54 39 249 45 216 117 186 74 6 246 167 194 190 253 209 5 4 136 208 87 167 52 28 174 11 231 42 153 119 109 181 189 121 180 99 226 211 136 39 100 175 156 2 69 208 132 163 52 45) :der-encode #f :tests '(#(112 "u2 == n - 1" #vu8(49 50 51 52 48 48) #vu8(71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138 143 214 35 28 25 130 68 89 113 101 117 110 78 139 82 101 224 185 210 220 243 233 211 23 195 197 13 21) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 189 247 8 160 28 106 129 71 40 211 148 183 242 155 246 87 151 52 134 45 138 248 230 255 120 111 190 73 144 28 212 98 148 110 94 54 204 151 201 137 109 242 225 129 119 69 109 40 42 122 38 163 128 132 192 134) :der-encode #f :tests '(#(113 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 182 234 9 198 236 94 4 132 185 79 37 216 144 20 91 10 227 255 187 152 183 22 173 221 146 222 189 206) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 12 83 31 179 217 150 250 162 36 7 223 19 5 255 106 224 191 233 78 28 32 34 244 115 13 15 138 74 189 128 115 149 4 89 86 46 83 154 192 137 84 51 117 126 37 32 155 18 83 79 243 15 227 211 124 113) :der-encode #f :tests '(#(114 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 47 98 169 207 72 227 202 96 46 239 78 51 175 164 63 45 206 185 34 164 10 103 222 121 247 177 174 56) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 103 130 149 64 130 65 142 0 2 160 129 38 114 172 33 35 182 51 75 52 19 64 85 80 150 188 246 198 31 111 161 168 254 166 23 217 221 161 68 97 214 58 164 72 242 5 163 155 37 80 26 107 29 66 238 95) :der-encode #f :tests '(#(115 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 97 141 252 84 64 139 236 28 179 124 126 229 43 96 173 188 141 58 108 38 69 124 57 208 19 232 142 129) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 91 94 110 171 167 89 122 230 65 66 10 206 106 242 87 88 57 241 97 178 123 145 178 112 241 139 247 208 73 106 179 195 7 47 166 238 85 120 252 129 79 116 209 72 236 188 42 152 207 220 93 64 236 126 105 128) :der-encode #f :tests '(#(116 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 1 13 229 113 36 192 147 14 248 0 231 100 181 88 89 39 151 126 42 210 216 184 46 124 182 72 175 82) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 142 102 26 6 173 85 181 34 120 1 234 67 9 167 43 156 217 73 115 188 135 60 4 5 225 36 125 30 100 137 139 130 44 54 60 172 136 33 48 45 227 138 145 66 104 170 166 125 178 86 24 120 240 249 10 2) :der-encode #f :tests '(#(117 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 3 62 245 1 11 236 237 4 196 146 136 104 81 62 209 135 140 230 119 166 237 129 14 155 153 221 151 148) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 179 210 185 63 20 136 101 114 98 20 15 150 193 8 170 4 133 147 155 217 148 64 36 10 122 125 84 227 136 150 129 116 176 97 133 55 57 248 176 71 28 118 18 101 57 220 87 204 109 124 31 83 159 104 102 116) :der-encode #f :tests '(#(118 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 6 125 234 2 23 217 218 9 137 37 16 208 162 125 163 15 25 204 239 77 219 2 29 55 51 187 47 40) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 186 131 13 191 131 7 92 209 130 188 147 34 193 246 41 154 76 227 207 77 221 224 230 252 238 80 240 214 43 21 63 111 55 122 136 128 156 157 213 13 141 97 235 103 148 81 68 72 22 87 134 167 198 85 141 204) :der-encode #f :tests '(#(119 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 69 132 126 2 253 1 163 204 158 6 63 150 31 185 32 171 50 113 236 9 153 111 117 188 167 254 109 63) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 119 244 2 34 228 167 154 15 167 229 16 136 126 105 235 163 31 109 215 6 113 33 218 254 115 155 190 19 208 255 171 114 34 207 109 130 124 81 235 83 171 172 80 107 192 165 215 193 165 167 225 104 61 73 228 62) :der-encode #f :tests '(#(120 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 11 76 190 134 109 25 32 99 65 56 200 121 143 204 65 71 148 71 229 174 118 7 148 225 229 121 121 40) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 89 123 90 60 16 107 140 78 154 126 122 81 124 215 64 231 118 103 200 162 208 108 81 14 94 59 114 141 156 194 73 232 39 245 255 249 2 18 46 178 107 173 196 167 218 101 85 180 137 186 152 152 45 56 129 37) :der-encode #f :tests '(#(121 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 32 215 42 227 57 229 98 1 112 201 10 76 229 188 160 141 237 23 0 178 182 200 14 198 18 200 213 209) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 15 36 83 231 88 92 177 57 47 244 250 17 134 159 140 16 178 249 207 79 42 24 184 102 232 243 124 43 209 86 110 240 73 40 121 117 121 212 15 51 16 235 175 71 122 78 120 162 53 134 25 40 50 134 52 223) :der-encode #f :tests '(#(122 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 157 35 90 169 233 249 198 69 62 57 167 134 19 131 110 161 76 45 223 49 201 27 116 122 239 1 10 137) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 16 203 61 188 228 218 81 142 4 235 18 92 243 180 75 239 4 81 186 211 231 203 186 213 50 139 133 187 53 134 81 180 120 188 242 0 104 79 211 16 230 209 74 205 35 220 42 118 4 117 223 15 91 138 117 140) :der-encode #f :tests '(#(123 "edge case for u1" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 156 167 152 127 51 103 169 81 110 202 87 133 80 152 212 170 175 40 148 56 217 173 123 57 220 200 17 16) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 44 39 115 42 170 163 248 177 102 100 164 138 29 208 111 192 254 64 246 87 66 117 30 92 4 183 239 245 7 128 75 45 190 231 159 254 86 220 79 74 96 98 206 214 243 117 184 11 90 210 207 58 41 33 179 149) :der-encode #f :tests '(#(124 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 114 149 188 56 183 107 204 215 99 93 101 97 209 240 83 221 155 7 148 25 36 159 148 54 140 141 49 51) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 140 237 85 104 119 238 21 175 49 74 237 93 252 67 160 15 187 118 38 251 220 123 129 255 125 190 162 248 152 245 226 111 127 195 39 109 162 168 232 105 176 175 188 65 239 59 64 50 96 128 170 133 206 98 194 171) :der-encode #f :tests '(#(125 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 147 143 45 178 183 32 97 171 215 235 110 92 143 230 133 57 30 150 110 192 199 105 208 197 56 224 103 138) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 66 177 155 34 80 108 79 216 159 162 140 89 9 217 127 143 254 189 200 40 4 220 199 191 106 87 10 226 26 151 78 224 139 72 79 160 94 31 187 137 196 140 80 117 75 161 228 10 101 138 92 237 64 156 99 97) :der-encode #f :tests '(#(126 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 127 144 124 142 50 230 14 43 164 3 62 231 214 95 63 232 253 35 113 156 122 156 111 94 82 241 140 71) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 32 149 225 33 22 206 189 212 232 188 28 193 132 181 56 177 81 95 120 158 59 228 176 58 65 131 250 229 208 146 110 68 104 117 171 220 209 44 130 57 230 7 150 28 173 208 10 46 137 157 130 29 177 29 86 121) :der-encode #f :tests '(#(127 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 52 195 151 140 58 29 172 146 31 98 53 200 42 2 237 185 52 34 133 70 148 38 187 16 248 40 151 196) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 88 248 46 178 202 110 52 116 169 14 41 172 86 220 182 61 136 230 105 224 164 2 4 230 32 42 247 197 160 232 94 64 57 243 67 37 91 79 228 189 193 25 26 120 69 189 215 235 144 142 205 135 121 162 121 99) :der-encode #f :tests '(#(128 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 151 1 214 82 61 61 63 91 138 200 64 38 128 179 202 184 150 110 38 81 207 193 115 159 205 60 7 73) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 113 242 196 167 195 247 19 17 167 147 69 143 241 34 98 168 99 81 143 179 13 187 122 128 112 16 48 184 182 176 132 40 250 189 182 156 138 142 158 50 125 174 208 121 95 184 78 13 136 23 8 96 34 211 178 59) :der-encode #f :tests '(#(129 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 86 66 119 250 84 55 24 48 235 120 80 39 139 150 153 216 91 197 144 88 49 164 42 155 244 208 122 243) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 60 252 246 78 236 233 148 195 92 86 233 21 228 237 24 131 186 110 195 79 227 150 193 26 205 143 71 210 99 205 251 170 52 64 17 0 181 177 10 247 113 187 70 192 213 52 70 247 170 132 121 86 201 54 52 148) :der-encode #f :tests '(#(130 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 119 148 251 222 230 56 246 87 172 30 76 101 40 76 20 75 62 250 123 244 16 158 108 202 96 92 79 76) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 76 64 77 236 188 6 151 178 7 250 8 152 46 240 254 219 0 30 235 67 243 116 4 218 185 122 154 119 71 25 27 194 64 223 212 64 39 78 6 149 86 17 249 146 63 173 105 73 178 204 21 122 24 92 130 41) :der-encode #f :tests '(#(131 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 181 32 13 167 164 88 55 245 183 28 71 225 185 76 120 98 161 228 190 203 163 10 144 138 218 33 148 135) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 123 228 176 234 11 21 185 111 145 49 44 21 200 22 41 228 12 68 24 247 11 134 197 188 220 37 143 217 121 203 239 142 162 167 124 160 146 219 14 185 84 169 227 62 130 185 197 241 16 200 201 144 185 35 90 87) :der-encode #f :tests '(#(132 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 101 43 120 113 110 215 153 174 198 186 202 195 163 224 167 187 54 15 40 50 73 63 40 109 25 26 98 108) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 100 166 76 255 165 64 102 73 146 100 153 30 71 160 241 75 202 99 25 161 194 126 21 8 226 1 107 86 189 167 193 122 4 217 203 136 234 219 114 150 207 135 223 191 173 254 101 5 104 55 167 151 214 105 151 221) :der-encode #f :tests '(#(133 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 151 193 52 170 38 67 102 134 42 24 48 37 117 208 251 152 209 22 188 75 109 222 188 163 165 167 147 162) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 61 76 78 60 91 167 165 51 200 163 56 109 111 247 122 129 53 19 70 225 137 75 37 96 180 6 166 62 163 73 119 89 70 121 158 235 39 73 38 180 217 87 50 143 108 125 80 246 118 2 145 172 218 235 17 79) :der-encode #f :tests '(#(134 "edge case for u2" #vu8(49 50 51 52 48 48) #vu8(127 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 250 171 168 216 156 44 148 186 88 231 13 183 134 166 24 29 192 231 29 22 243 244 61 150 0 252 76 143 243) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 77 184 232 172 67 242 45 247 92 156 9 254 25 59 156 216 61 92 155 115 243 125 20 148 118 23 36 176 167 96 130 195 93 168 98 161 226 232 98 111 250 148 237 24 252 177 216 151 236 122 181 44 50 37 83 255) :der-encode #f :tests '(#(135 "point duplication during verification" #vu8(49 50 51 52 48 48) #vu8(122 242 149 230 228 120 114 82 243 76 82 122 245 98 202 39 33 74 102 246 214 219 79 210 193 18 181 100 177 208 16 247 64 98 238 170 192 206 203 44 60 44 77 40 138 87 107 246 240 160 3 71 198 165 181 98) #t ("PointDuplication")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 77 184 232 172 67 242 45 247 92 156 9 254 25 59 156 216 61 92 155 115 243 125 20 148 118 23 36 176 48 96 177 230 200 155 3 228 71 47 205 181 123 60 234 110 179 237 46 191 171 95 212 201 76 163 109 0) :der-encode #f :tests '(#(136 "duplication bug" #vu8(49 50 51 52 48 48) #vu8(122 242 149 230 228 120 114 82 243 76 82 122 245 98 202 39 33 74 102 246 214 219 79 210 193 18 181 100 177 208 16 247 64 98 238 170 192 206 203 44 60 44 77 40 138 87 107 246 240 160 3 71 198 165 181 98) #f ("PointDuplication")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 43 146 38 130 8 213 34 69 12 66 243 252 189 164 9 195 172 226 165 248 87 234 16 97 44 96 147 248 49 94 178 212 72 19 78 113 107 3 32 120 182 131 1 98 46 60 33 134 171 88 61 151 110 118 159 235) :der-encode #f :tests '(#(137 "comparison with point at infinity " #vu8(49 50 51 52 48 48) #vu8(71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138 43 38 164 34 7 167 20 129 59 158 112 7 125 246 152 184 41 209 88 219 226 198 37 186 84 84 183 31) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 77 75 213 105 61 134 221 154 96 22 186 128 109 128 49 249 77 200 226 211 60 111 88 113 160 11 100 115 42 70 98 242 149 36 236 231 84 130 139 157 130 156 10 7 36 217 189 157 40 141 33 248 126 63 177 250) :der-encode #f :tests '(#(138 "extreme value for k and edgecase s" #vu8(49 50 51 52 48 48) #vu8(51 183 228 152 188 218 26 51 230 26 103 175 86 163 109 18 223 112 50 37 93 223 94 30 198 90 86 105 71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 190 14 251 72 65 223 55 171 205 207 63 40 221 176 213 117 26 146 160 254 122 62 136 209 171 2 131 44 187 83 204 214 107 156 14 66 67 128 105 61 100 22 252 46 26 60 121 58 53 95 125 5 249 99 244 53) :der-encode #f :tests '(#(139 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(51 183 228 152 188 218 26 51 230 26 103 175 86 163 109 18 223 112 50 37 93 223 94 30 198 90 86 105 184 238 191 109 69 94 87 224 182 93 224 32 27 215 179 21 69 129 51 174 94 44 161 176 215 33 236 63) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 188 2 114 227 105 58 5 231 136 57 44 136 15 157 233 92 114 226 147 253 27 19 241 226 42 153 7 163 105 149 6 228 89 15 169 12 98 87 177 196 227 99 44 204 72 108 184 51 203 188 191 33 180 162 96 65) :der-encode #f :tests '(#(140 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(51 183 228 152 188 218 26 51 230 26 103 175 86 163 109 18 223 112 50 37 93 223 94 30 198 90 86 105 172 154 144 136 30 156 82 4 238 121 192 29 247 218 98 224 167 69 99 111 139 24 150 233 81 82 220 127) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 168 59 195 233 4 60 185 56 218 225 103 187 234 47 125 98 52 134 244 3 141 244 83 18 232 70 123 218 115 99 250 88 175 54 58 113 131 93 160 148 19 200 130 39 132 156 111 15 254 142 78 64 175 245 16 35) :der-encode #f :tests '(#(141 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(51 183 228 152 188 218 26 51 230 26 103 175 86 163 109 18 223 112 50 37 93 223 94 30 198 90 86 105 43 38 164 34 7 167 20 129 59 158 112 7 125 246 152 184 41 209 88 219 226 198 37 186 84 84 183 32) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 59 208 138 28 70 99 133 100 82 29 237 63 167 124 233 201 85 56 228 151 3 235 185 248 211 107 230 247 39 111 250 18 128 81 103 31 126 76 99 233 184 19 45 233 243 56 156 197 37 215 38 130 182 1 158 195) :der-encode #f :tests '(#(142 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(51 183 228 152 188 218 26 51 230 26 103 175 86 163 109 18 223 112 50 37 93 223 94 30 198 90 86 105 30 210 117 60 224 229 14 165 115 186 80 5 89 249 72 131 139 149 136 157 15 178 26 242 206 133 167 96) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 163 219 43 62 44 98 196 43 244 251 14 17 194 144 143 209 127 232 61 163 172 156 9 128 35 78 253 189 60 190 236 64 39 189 124 16 155 39 174 47 124 240 77 198 94 234 241 63 170 34 77 50 162 15 49 99) :der-encode #f :tests '(#(143 "extreme value for k" #vu8(49 50 51 52 48 48) #vu8(51 183 228 152 188 218 26 51 230 26 103 175 86 163 109 18 223 112 50 37 93 223 94 30 198 90 86 105 88 227 117 24 198 228 122 132 222 16 204 178 84 192 54 147 39 17 69 241 62 0 169 18 55 164 165 71) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 96 108 230 248 199 122 193 125 91 117 21 213 133 30 237 21 94 161 32 205 7 202 66 119 179 91 141 54 95 113 107 98 174 233 168 26 1 27 209 210 188 234 243 125 95 58 97 229 247 48 126 11 185 200 146 200) :der-encode #f :tests '(#(144 "extreme value for k and edgecase s" #vu8(49 50 51 52 48 48) #vu8(13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 71 235 17 142 12 193 34 44 184 178 186 183 39 69 169 50 240 92 233 110 121 244 233 139 225 226 134 138) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 42 255 187 130 105 203 120 131 218 218 51 80 57 69 121 145 46 247 86 168 223 107 221 125 163 93 57 142 144 33 61 147 130 179 213 251 157 222 130 114 77 56 229 103 140 23 230 16 244 23 207 230 247 239 205 145) :der-encode #f :tests '(#(145 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 184 238 191 109 69 94 87 224 182 93 224 32 27 215 179 21 69 129 51 174 94 44 161 176 215 33 236 63) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 25 205 212 78 42 51 17 58 136 69 88 231 238 14 251 65 186 254 26 220 220 249 93 246 222 106 37 17 95 66 142 233 152 163 72 86 242 172 63 111 57 199 35 123 241 249 222 35 33 117 215 71 181 205 151 254) :der-encode #f :tests '(#(146 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 172 154 144 136 30 156 82 4 238 121 192 29 247 218 98 224 167 69 99 111 139 24 150 233 81 82 220 127) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 183 47 124 26 60 133 98 203 141 233 146 94 236 4 28 204 38 54 73 198 82 71 98 185 244 88 94 227 157 247 86 218 8 209 39 74 215 45 140 172 41 58 166 13 21 12 119 19 31 159 162 140 205 255 223 160) :der-encode #f :tests '(#(147 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 43 38 164 34 7 167 20 129 59 158 112 7 125 246 152 184 41 209 88 219 226 198 37 186 84 84 183 32) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 157 55 3 179 32 91 18 60 144 58 4 70 151 50 71 193 106 136 209 3 254 169 208 77 208 42 112 43 101 24 107 119 123 87 234 222 232 21 76 2 252 224 233 92 63 6 20 104 73 155 172 61 198 2 158 140) :der-encode #f :tests '(#(148 "extreme value for k and s^-1" #vu8(49 50 51 52 48 48) #vu8(13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 30 210 117 60 224 229 14 165 115 186 80 5 89 249 72 131 139 149 136 157 15 178 26 242 206 133 167 96) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 62 165 114 80 90 72 177 190 208 133 149 61 167 212 201 99 194 197 182 173 153 119 157 157 84 186 64 18 148 71 0 116 224 37 45 161 89 160 192 208 178 248 212 194 66 203 148 186 178 194 2 12 75 45 244 153) :der-encode #f :tests '(#(149 "extreme value for k" #vu8(49 50 51 52 48 48) #vu8(13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 88 227 117 24 198 228 122 132 222 16 204 178 84 192 54 147 39 17 69 241 62 0 169 18 55 164 165 71) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 88 170 86 247 114 192 114 111 36 198 184 158 78 205 172 36 53 75 158 153 202 163 246 211 118 20 2 205) :der-encode #f :tests '(#(150 "testing point duplication" #vu8(49 50 51 52 48 48) #vu8(117 59 180 0 120 147 64 129 215 189 17 62 196 155 25 239 9 209 186 51 73 134 144 81 109 77 18 44 30 210 117 60 224 229 14 165 115 186 80 5 89 249 72 131 139 149 136 157 15 178 26 242 206 133 167 95) #f ()) #(151 "testing point duplication" #vu8(49 50 51 52 48 48) #vu8(98 133 128 169 173 176 38 4 82 91 30 230 177 53 225 169 199 69 2 24 36 88 44 82 56 90 129 115 30 210 117 60 224 229 14 165 115 186 80 5 89 249 72 131 139 149 136 157 15 178 26 242 206 133 167 95) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 13 144 41 173 44 126 92 244 52 8 35 178 168 125 198 140 158 76 227 23 76 30 110 253 238 18 192 125 127 22 221 178 179 130 244 23 5 81 119 135 39 4 43 99 123 83 104 189 205 54 147 34 8 180 190 50) :der-encode #f :tests '(#(152 "testing point duplication" #vu8(49 50 51 52 48 48) #vu8(117 59 180 0 120 147 64 129 215 189 17 62 196 155 25 239 9 209 186 51 73 134 144 81 109 77 18 44 30 210 117 60 224 229 14 165 115 186 80 5 89 249 72 131 139 149 136 157 15 178 26 242 206 133 167 95) #f ()) #(153 "testing point duplication" #vu8(49 50 51 52 48 48) #vu8(98 133 128 169 173 176 38 4 82 91 30 230 177 53 225 169 199 69 2 24 36 88 44 82 56 90 129 115 30 210 117 60 224 229 14 165 115 186 80 5 89 249 72 131 139 149 136 157 15 178 26 242 206 133 167 95) #f ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 181 84 252 37 233 240 152 234 241 70 108 53 50 140 151 48 93 13 74 160 228 70 46 139 175 122 142 126 208 143 196 14 176 29 200 85 87 123 174 169 227 7 7 112 97 111 87 177 126 169 133 76 173 147 136 26) :der-encode #f :tests '(#(154 "pseudorandom signature" #vu8() #vu8(185 130 190 168 13 16 129 107 180 80 163 250 170 237 78 213 79 177 151 179 191 249 90 242 93 125 55 134 158 110 162 229 135 19 241 48 77 41 222 191 133 89 167 74 137 224 24 186 226 139 5 85 110 84 130 161) #t ()) #(155 "pseudorandom signature" #vu8(77 115 103) #vu8(77 171 197 254 150 43 95 138 102 129 233 74 33 101 217 182 190 25 64 242 14 39 206 183 63 196 234 125 116 110 155 186 126 251 144 252 236 194 99 194 41 161 109 128 157 53 71 194 138 38 205 113 165 42 189 197) #t ()) #(156 "pseudorandom signature" #vu8(49 50 51 52 48 48) #vu8(149 177 30 50 0 7 162 224 248 206 0 249 5 140 169 185 25 232 214 170 213 68 168 249 128 139 68 161 21 169 98 1 156 133 165 177 250 116 116 22 45 3 205 14 82 142 139 147 188 200 73 32 175 87 159 97) #t ()) #(157 "pseudorandom signature" #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #vu8(158 77 171 158 11 0 151 227 101 120 63 192 95 1 12 22 13 54 29 247 146 91 13 219 223 236 232 139 132 6 163 101 240 120 240 49 230 250 214 81 29 105 248 166 84 131 193 154 90 128 12 57 73 15 117 16) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 128 42 15 81 32 78 246 168 41 33 27 192 116 8 135 70 30 228 171 167 54 233 202 238 0 0 0 0 127 185 49 224 99 0 69 19 98 212 68 16 110 235 93 171 221 202 101 15 236 75 229 95 197 69 247 200) :der-encode #f :tests '(#(158 "x-coordinate of the public key has many trailing 0's" #vu8(77 101 115 115 97 103 101) #vu8(12 147 253 127 109 208 182 151 213 194 135 238 97 174 228 220 190 220 194 8 133 193 230 33 91 139 54 8 59 199 161 190 204 241 168 232 58 242 245 22 47 197 57 161 208 98 189 99 154 47 190 197 18 144 122 39) #t ()) #(159 "x-coordinate of the public key has many trailing 0's" #vu8(77 101 115 115 97 103 101) #vu8(158 11 98 10 47 49 58 218 117 100 99 162 41 136 175 182 87 27 59 3 10 66 133 177 133 225 204 128 195 235 160 76 66 230 77 64 40 172 171 205 203 123 46 237 27 60 251 86 11 141 125 20 251 38 172 163) #t ()) #(160 "x-coordinate of the public key has many trailing 0's" #vu8(77 101 115 115 97 103 101) #vu8(163 6 245 0 218 79 10 48 148 100 121 147 106 175 156 99 118 118 176 240 45 32 174 13 152 28 37 235 1 86 71 242 80 11 203 227 32 75 219 128 73 114 184 65 137 11 78 83 25 108 216 177 136 153 49 81) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 203 50 12 132 242 108 0 161 180 173 113 70 145 76 174 18 101 41 22 93 231 54 61 138 239 154 189 5 163 151 212 107 135 40 49 118 183 246 157 161 249 70 21 202 68 49 252 71 178 160 230 12 0 0 0 0) :der-encode #f :tests '(#(161 "y-coordinate of the public key has many trailing 0's" #vu8(77 101 115 115 97 103 101) #vu8(4 240 13 212 79 221 138 230 176 139 134 204 189 215 214 21 170 158 73 138 137 179 80 148 200 169 166 254 73 97 122 22 23 197 108 233 13 65 197 62 239 78 98 143 36 192 71 160 110 2 193 249 33 35 68 31) #t ()) #(162 "y-coordinate of the public key has many trailing 0's" #vu8(77 101 115 115 97 103 101) #vu8(18 134 246 167 55 91 246 128 81 227 27 46 50 181 246 192 152 140 145 137 121 146 86 231 206 100 226 145 82 211 193 249 231 119 242 60 23 203 200 50 208 229 168 75 182 139 19 222 191 57 56 120 209 160 100 152) #t ()) #(163 "y-coordinate of the public key has many trailing 0's" #vu8(77 101 115 115 97 103 101) #vu8(88 40 37 223 35 104 220 185 47 187 163 250 100 84 209 73 211 184 96 227 255 50 106 254 54 33 88 19 73 51 79 198 167 4 24 219 196 84 218 106 153 123 200 55 98 112 195 163 136 99 173 178 170 112 187 15) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 0 0 0 0 129 223 151 23 68 162 90 201 148 114 195 255 90 143 196 155 134 252 159 181 112 68 143 249 119 242 208 124 28 146 150 178 247 116 120 209 61 90 177 198 57 147 150 47 45 208 142 231 195 19 222 206) :der-encode #f :tests '(#(164 "x-coordinate of the public key is small" #vu8(77 101 115 115 97 103 101) #vu8(90 17 113 140 144 160 36 89 128 15 16 158 78 132 12 194 97 215 130 214 78 28 138 71 18 221 144 129 210 131 177 193 225 16 164 98 10 105 111 223 116 169 199 121 35 82 19 157 84 204 237 140 151 61 158 126) #t ()) #(165 "x-coordinate of the public key is small" #vu8(77 101 115 115 97 103 101) #vu8(213 119 242 62 89 36 20 227 81 179 146 138 89 60 93 47 137 240 199 45 245 19 191 188 101 53 186 187 27 176 157 210 53 18 74 20 224 36 105 70 242 128 69 15 21 87 105 18 174 183 53 183 60 232 40 188) #t ()) #(166 "x-coordinate of the public key is small" #vu8(77 101 115 115 97 103 101) #vu8(175 143 131 110 99 153 93 199 21 164 211 198 132 44 78 108 108 244 88 109 247 110 70 89 216 9 238 201 133 190 253 11 27 184 174 24 44 5 208 113 218 209 128 34 77 34 83 61 206 115 125 77 218 116 213 209) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 13 40 180 247 254 31 108 111 166 167 125 17 228 59 211 233 39 23 88 223 52 198 95 165 119 166 221 59 0 0 0 0 40 1 212 131 130 134 22 132 184 210 203 215 229 152 154 13 124 21 167 232 25 181 115 170) :der-encode #f :tests '(#(167 "y-coordinate of the public key is small" #vu8(77 101 115 115 97 103 101) #vu8(21 106 167 134 146 199 142 151 105 171 167 40 201 238 167 136 53 181 80 0 144 27 165 7 148 163 62 252 185 120 93 244 10 34 19 55 116 129 49 27 26 129 211 16 231 99 65 146 123 143 186 13 110 62 199 173) #t ()) #(168 "y-coordinate of the public key is small" #vu8(77 101 115 115 97 103 101) #vu8(146 116 212 106 127 250 18 153 163 114 232 33 189 137 114 141 232 62 248 124 70 175 103 4 58 99 75 2 25 228 187 236 139 3 250 119 42 54 34 191 72 147 229 129 239 173 249 210 11 214 8 6 216 38 118 182) #t ()) #(169 "y-coordinate of the public key is small" #vu8(77 101 115 115 97 103 101) #vu8(207 106 156 186 40 94 86 73 60 187 70 43 123 22 18 138 12 241 199 5 132 71 148 93 174 243 65 73 41 166 135 131 158 142 224 60 83 114 161 19 115 60 8 31 65 61 31 148 5 221 254 71 225 143 204 84) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 13 40 180 247 254 31 108 111 166 167 125 17 228 59 211 233 39 23 88 223 52 198 95 165 119 166 221 59 215 193 52 169 254 65 146 2 167 146 25 160 188 255 11 175 203 6 109 74 27 196 226 13 101 19 77 85) :der-encode #f :tests '(#(170 "y-coordinate of the public key is large" #vu8(77 101 115 115 97 103 101) #vu8(89 46 84 160 234 149 10 199 205 131 15 86 199 149 74 118 159 129 170 85 232 225 1 190 225 155 59 39 72 55 95 221 77 144 20 201 182 11 99 199 11 254 152 200 68 190 102 143 45 58 46 37 146 98 185 69) #t ()) #(171 "y-coordinate of the public key is large" #vu8(77 101 115 115 97 103 101) #vu8(30 192 239 77 91 237 175 229 8 31 122 218 227 45 180 208 170 148 111 19 10 206 218 186 226 109 144 220 98 126 129 215 235 53 143 89 232 168 99 5 39 212 232 148 109 28 173 33 150 118 24 54 217 125 149 60) #t ()) #(172 "y-coordinate of the public key is large" #vu8(77 101 115 115 97 103 101) #vu8(95 175 3 94 213 119 78 235 10 220 24 127 244 133 168 70 170 42 188 241 231 248 89 177 185 16 242 92 139 241 42 28 0 177 143 102 194 40 53 45 228 156 196 251 130 122 9 252 134 247 34 206 86 27 165 250) #t ()))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 81 46 88 23 49 201 196 96 187 112 91 96 218 151 108 203 27 14 244 33 120 81 6 186 44 205 210 56 15 33 213 186 205 248 28 12 183 143 161 81 35 125 179 19 10 212 222 243 115 243 229 35 57 140 44 247) :der-encode #f :tests '(#(173 "y-coordinate of the public key has many trailing 1's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(82 178 211 105 241 141 245 99 114 175 231 254 179 132 19 242 50 180 251 156 161 108 111 111 237 198 65 137 193 177 159 19 119 115 239 50 1 205 52 28 56 30 79 148 73 204 14 108 104 138 53 29 122 96 112 178) #t ("GroupIsomorphism")) #(174 "y-coordinate of the public key has many trailing 1's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(91 136 157 40 138 170 129 103 77 50 0 110 129 39 156 87 237 86 160 53 200 120 211 226 182 135 190 195 13 166 33 213 250 152 19 38 60 127 88 248 224 21 93 111 12 51 10 86 197 148 222 252 46 189 240 160) #t ("GroupIsomorphism")) #(175 "y-coordinate of the public key has many trailing 1's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(182 248 168 1 135 24 10 173 138 92 137 107 226 20 49 70 1 161 88 95 44 203 40 188 126 142 143 1 169 12 104 193 74 103 245 213 156 236 112 220 15 71 59 92 20 1 59 5 109 18 203 192 247 21 59 29) #t ("GroupIsomorphism")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 172 85 209 179 254 212 174 224 63 163 97 93 34 90 156 186 92 2 132 65 111 186 249 167 97 53 247 98 23 168 136 57 91 206 211 73 119 168 72 35 112 213 110 188 98 170 28 168 27 195 48 244 157 74 20 29) :der-encode #f :tests '(#(176 "x-coordinate of the public key is small on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(22 212 168 80 156 155 206 44 115 248 219 75 115 37 124 126 51 244 23 38 194 92 76 100 84 107 29 204 121 186 53 169 109 35 69 173 25 79 57 16 145 32 157 252 206 215 153 23 224 77 243 182 95 68 209 235) #t ("GroupIsomorphism")) #(177 "x-coordinate of the public key is small on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(93 161 86 151 187 228 235 167 112 126 52 159 243 35 157 80 132 85 55 129 19 210 78 126 29 122 2 12 69 190 68 165 112 251 83 12 73 215 89 113 44 16 4 19 69 247 192 137 10 121 70 217 29 50 186 198) #t ("GroupIsomorphism")) #(178 "x-coordinate of the public key is small on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(193 248 212 52 121 196 242 155 25 185 178 199 181 116 112 16 73 20 64 116 108 200 0 213 190 137 176 17 129 84 52 139 124 55 240 80 77 202 43 17 89 65 247 186 88 87 50 30 174 143 100 23 91 233 203 185) #t ("GroupIsomorphism")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 139 49 159 46 208 116 162 14 196 45 134 156 127 153 189 145 70 237 130 99 41 123 254 0 79 39 197 155 18 15 150 52 61 235 128 9 62 203 118 149 194 210 165 190 153 55 162 88 114 61 120 237 0 170 30 223) :der-encode #f :tests '(#(179 "y-coordinate of the public key is small on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(135 21 129 181 0 146 87 130 17 22 14 71 13 221 170 100 13 90 45 158 34 79 175 202 135 145 6 212 190 112 253 92 117 145 163 19 15 92 42 245 54 255 255 142 114 193 98 81 116 76 151 150 143 146 23 40) #t ("GroupIsomorphism")) #(180 "y-coordinate of the public key is small on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(169 135 53 229 101 144 34 176 39 74 230 247 188 177 100 110 158 107 75 136 64 141 179 249 38 236 204 137 169 35 255 94 21 224 215 100 205 92 239 255 197 196 12 8 44 110 183 114 219 118 98 251 27 130 213 37) #t ("GroupIsomorphism")) #(181 "y-coordinate of the public key is small on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(169 107 92 36 227 61 89 0 76 243 26 174 244 74 228 199 87 158 11 91 33 154 178 93 127 28 105 10 136 192 19 120 132 124 56 65 244 158 193 72 64 226 208 35 215 185 18 181 3 242 217 138 146 59 232 201) #t ("GroupIsomorphism")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 139 49 159 46 208 116 162 14 196 45 134 156 127 153 189 145 70 237 130 99 41 123 254 0 79 39 197 155 197 177 158 117 232 87 230 124 235 76 185 143 178 255 49 201 23 103 100 255 37 157 17 8 126 30 162 32) :der-encode #f :tests '(#(182 "y-coordinate of the public key is large on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(107 87 183 58 183 195 155 86 152 84 157 213 205 212 223 115 152 24 27 85 110 124 114 131 55 94 63 134 159 89 209 134 61 111 214 1 50 71 212 230 120 161 196 252 29 137 109 198 97 250 49 251 115 195 63 0) #t ("GroupIsomorphism")) #(183 "y-coordinate of the public key is large on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(47 133 175 126 83 95 102 207 201 169 218 183 190 120 22 49 221 98 43 228 53 215 100 43 91 81 252 199 97 147 1 194 28 147 66 85 223 147 238 221 91 69 156 141 210 128 253 208 126 230 86 167 20 125 77 105) #t ("GroupIsomorphism")) #(184 "y-coordinate of the public key is large on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(152 168 169 143 204 130 248 4 168 35 204 145 7 36 55 207 216 131 34 184 103 22 134 81 127 25 120 171 106 195 232 55 118 104 91 206 206 254 186 228 115 172 7 199 113 232 59 12 90 85 126 254 131 80 32 54) #t ("GroupIsomorphism")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 197 220 81 53 240 80 169 107 187 13 33 136 81 149 180 154 87 77 81 152 186 172 75 70 2 178 27 200 181 243 139 127 230 97 0 63 174 225 183 175 103 14 22 91 250 183 11 1 137 101 232 51 41 212 5 188) :der-encode #f :tests '(#(185 "y-coordinate of the public key has many trailing 0's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(105 156 64 183 53 35 107 217 35 151 112 165 222 44 26 117 84 99 30 107 166 239 81 47 133 83 208 47 11 202 156 81 108 164 5 255 201 174 45 206 225 42 215 217 107 88 107 253 200 24 163 212 93 207 207 38) #t ("GroupIsomorphism")) #(186 "y-coordinate of the public key has many trailing 0's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(118 138 129 157 57 67 252 48 120 26 174 242 143 161 32 24 76 114 18 208 145 31 224 61 252 140 98 96 81 179 219 14 28 62 147 145 73 204 191 157 70 25 187 191 240 226 225 116 17 15 110 206 67 19 180 202) #t ("GroupIsomorphism")) #(187 "y-coordinate of the public key has many trailing 0's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(88 252 192 255 177 37 194 60 67 87 53 183 195 144 105 32 55 192 58 103 101 239 123 83 101 161 125 212 149 24 210 157 120 237 169 203 37 3 253 227 141 59 115 214 251 144 160 212 10 35 240 236 38 22 105 105) #t ("GroupIsomorphism")))) (test-signature/testvector "ecdsa_brainpoolP224r1_sha224_p1363_test" :algorithm "ECDSA" :digest "SHA-224" :public-key #vu8(48 82 48 20 6 7 42 134 72 206 61 2 1 6 9 43 36 3 3 2 8 1 1 5 3 58 0 4 193 181 106 26 209 84 225 21 86 183 35 252 116 147 243 110 102 80 157 143 104 250 208 230 44 64 240 133 155 4 120 10 133 230 154 191 152 222 243 51 92 230 67 205 53 84 22 122 139 80 213 150 185 83 136 149) :der-encode #f :tests '(#(188 "x-coordinate of the public key has many trailing 1's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(209 147 238 10 61 66 162 58 240 24 171 144 137 107 53 213 194 80 24 123 249 251 28 202 195 100 116 140 160 146 42 204 199 86 45 1 113 9 233 29 47 131 228 139 250 60 31 162 238 4 216 70 155 233 64 51) #t ("GroupIsomorphism")) #(189 "x-coordinate of the public key has many trailing 1's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(9 116 82 29 124 231 83 222 165 209 21 111 180 217 146 204 97 64 121 235 134 119 171 54 164 7 138 79 131 116 223 186 232 208 66 154 111 186 96 251 181 210 253 85 152 86 165 215 57 243 154 162 191 29 161 201) #t ("GroupIsomorphism")) #(190 "x-coordinate of the public key has many trailing 1's on brainpoolP224t1" #vu8(77 101 115 115 97 103 101) #vu8(98 95 71 60 162 209 91 183 241 45 161 35 95 144 173 203 105 237 72 24 116 108 174 46 45 178 111 230 74 184 23 246 241 185 200 196 159 104 27 237 21 104 52 111 83 236 191 172 253 82 212 94 39 171 203 176) #t ("GroupIsomorphism"))))
d51605803abf3e30cf44d870d3384e1976ad2bb891274e7f0ceb1b5e7e98171b
footprintanalytics/footprint-web
session.clj
(ns metabase.models.session (:require [buddy.core.codecs :as codecs] [buddy.core.nonce :as nonce] [metabase.server.middleware.misc :as mw.misc] [metabase.server.request.util :as request.u] [metabase.util :as u] [schema.core :as s] [toucan.models :as models])) (s/defn ^:private random-anti-csrf-token :- #"^[0-9a-f]{32}$" [] (codecs/bytes->hex (nonce/random-bytes 16))) (models/defmodel Session :core_session) (defn- pre-update [_] (throw (RuntimeException. "You cannot update a Session."))) (defn- pre-insert [session] (cond-> session (some-> mw.misc/*request* request.u/embedded?) (assoc :anti_csrf_token (random-anti-csrf-token)))) (defn- post-insert [{anti-csrf-token :anti_csrf_token, :as session}] (let [session-type (if anti-csrf-token :full-app-embed :normal)] (assoc session :type session-type))) (u/strict-extend #_{:clj-kondo/ignore [:metabase/disallow-class-or-type-on-model]} (class Session) models/IModel (merge models/IModelDefaults {:pre-insert pre-insert :post-insert post-insert :pre-update pre-update :properties (constantly {:created-at-timestamped? true})}))
null
https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/src/metabase/models/session.clj
clojure
(ns metabase.models.session (:require [buddy.core.codecs :as codecs] [buddy.core.nonce :as nonce] [metabase.server.middleware.misc :as mw.misc] [metabase.server.request.util :as request.u] [metabase.util :as u] [schema.core :as s] [toucan.models :as models])) (s/defn ^:private random-anti-csrf-token :- #"^[0-9a-f]{32}$" [] (codecs/bytes->hex (nonce/random-bytes 16))) (models/defmodel Session :core_session) (defn- pre-update [_] (throw (RuntimeException. "You cannot update a Session."))) (defn- pre-insert [session] (cond-> session (some-> mw.misc/*request* request.u/embedded?) (assoc :anti_csrf_token (random-anti-csrf-token)))) (defn- post-insert [{anti-csrf-token :anti_csrf_token, :as session}] (let [session-type (if anti-csrf-token :full-app-embed :normal)] (assoc session :type session-type))) (u/strict-extend #_{:clj-kondo/ignore [:metabase/disallow-class-or-type-on-model]} (class Session) models/IModel (merge models/IModelDefaults {:pre-insert pre-insert :post-insert post-insert :pre-update pre-update :properties (constantly {:created-at-timestamped? true})}))
731a785113ac0f51daeac2821f2d065b02ea77f3ff91f8c48ba910ce52d16c6f
BekaValentine/SimpleFP
REPL.hs
module Record.Unification.REPL where import Control.Monad.Reader (runReaderT) import System.IO import Env import Eval import Record.Core.ConSig import Record.Core.Evaluation import Record.Core.Parser import Record.Core.Term import Record.Unification.Elaboration import Record.Unification.TypeChecking flushStr :: String -> IO () flushStr str = putStr str >> hFlush stdout readPrompt :: String -> IO String readPrompt prompt = flushStr prompt >> getLine until_ :: Monad m => (a -> Bool) -> m a -> (a -> m ()) -> m () until_ p prompt action = do result <- prompt if p result then return () else action result >> until_ p prompt action repl :: String -> IO () repl src = case loadProgram src of Left e -> flushStr ("ERROR: " ++ e ++ "\n") Right (sig,defs,ctx,i,env,ms) -> do hSetBuffering stdin LineBuffering until_ (== ":quit") (readPrompt "$> ") (evalAndPrint sig defs ctx i env ms) where loadProgram :: String -> Either String (Signature Term,Definitions,Context,Int,Environment (String,String) Term,[String]) loadProgram src = do prog <- parseProgram src ElabState sig defs ctx i _ _ ms <- runElaborator (elabProgram prog) let env = [ (x,m) | (x,m,_) <- defs ] return (sig,defs,ctx,i,env,ms) loadTerm :: Signature Term -> Definitions -> Context -> Int -> Environment (String,String) Term -> [String] -> String -> Either String Term loadTerm sig defs ctx i env ms src = do tm <- parseTerm src case runTypeChecker (infer tm) sig defs ctx i ([ (Right p,p) | (p,_) <- sig ] ++ [ (Right p,p) | (p,_,_) <- defs ]) ms of Left e -> Left e Right ((tm',_),_) -> runReaderT (eval tm') env evalAndPrint :: Signature Term -> Definitions -> Context -> Int -> Environment (String,String) Term -> [String] -> String -> IO () evalAndPrint _ _ _ _ _ _ "" = return () evalAndPrint sig defs ctx i env ms src = case loadTerm sig defs ctx i env ms src of Left e -> flushStr ("ERROR: " ++ e ++ "\n") Right v -> flushStr (show v ++ "\n") replFile :: String -> IO () replFile loc = readFile loc >>= repl
null
https://raw.githubusercontent.com/BekaValentine/SimpleFP/3cff456be9f0b99509e5cbe809be1055009b32df/src/Record/Unification/REPL.hs
haskell
module Record.Unification.REPL where import Control.Monad.Reader (runReaderT) import System.IO import Env import Eval import Record.Core.ConSig import Record.Core.Evaluation import Record.Core.Parser import Record.Core.Term import Record.Unification.Elaboration import Record.Unification.TypeChecking flushStr :: String -> IO () flushStr str = putStr str >> hFlush stdout readPrompt :: String -> IO String readPrompt prompt = flushStr prompt >> getLine until_ :: Monad m => (a -> Bool) -> m a -> (a -> m ()) -> m () until_ p prompt action = do result <- prompt if p result then return () else action result >> until_ p prompt action repl :: String -> IO () repl src = case loadProgram src of Left e -> flushStr ("ERROR: " ++ e ++ "\n") Right (sig,defs,ctx,i,env,ms) -> do hSetBuffering stdin LineBuffering until_ (== ":quit") (readPrompt "$> ") (evalAndPrint sig defs ctx i env ms) where loadProgram :: String -> Either String (Signature Term,Definitions,Context,Int,Environment (String,String) Term,[String]) loadProgram src = do prog <- parseProgram src ElabState sig defs ctx i _ _ ms <- runElaborator (elabProgram prog) let env = [ (x,m) | (x,m,_) <- defs ] return (sig,defs,ctx,i,env,ms) loadTerm :: Signature Term -> Definitions -> Context -> Int -> Environment (String,String) Term -> [String] -> String -> Either String Term loadTerm sig defs ctx i env ms src = do tm <- parseTerm src case runTypeChecker (infer tm) sig defs ctx i ([ (Right p,p) | (p,_) <- sig ] ++ [ (Right p,p) | (p,_,_) <- defs ]) ms of Left e -> Left e Right ((tm',_),_) -> runReaderT (eval tm') env evalAndPrint :: Signature Term -> Definitions -> Context -> Int -> Environment (String,String) Term -> [String] -> String -> IO () evalAndPrint _ _ _ _ _ _ "" = return () evalAndPrint sig defs ctx i env ms src = case loadTerm sig defs ctx i env ms src of Left e -> flushStr ("ERROR: " ++ e ++ "\n") Right v -> flushStr (show v ++ "\n") replFile :: String -> IO () replFile loc = readFile loc >>= repl
25da55f5a701b20db6b0183694c9cc013378937b440c46a9c7080d5a21e33753
2049foundation/clickhouse-haskell
Pool.hs
Copyright ( c ) 2020 - present , EMQX , Inc. -- All rights reserved. -- This source code is distributed under the terms of a MIT license , -- found in the LICENSE file. ------------------------------------------------------------------------------- -- This module provides implementation of Connection pool for TCP network # LANGUAGE BlockArguments # # LANGUAGE NamedFieldPuns # module Database.ClickHouseDriver.Pool ( createConnectionPool ) where import Database.ClickHouseDriver.Connection ( tcpConnect ) import Database.ClickHouseDriver.Defines ( _DEFAULT_USERNAME, _DEFAULT_HOST_NAME, _DEFAULT_PASSWORD, _DEFAULT_PORT_NAME, _DEFAULT_DATABASE, _DEFAULT_COMPRESSION_SETTING ) import Data.Pool ( createPool, Pool ) import Data.Time.Clock ( NominalDiffTime ) import Network.Socket (close) import Data.Default.Class ( Default(..) ) import Database.ClickHouseDriver.Types ( ConnParams(..), TCPConnection(TCPConnection, tcpSocket) ) -- | default connection parameters (settings) instance Default ConnParams where def = ConnParams{ username' = _DEFAULT_USERNAME ,host' = _DEFAULT_HOST_NAME ,port' = _DEFAULT_PORT_NAME ,password' = _DEFAULT_PASSWORD ,compression' = _DEFAULT_COMPRESSION_SETTING ,database' = _DEFAULT_DATABASE } -- | Create connection pool createConnectionPool :: ConnParams -- ^ parameters for basic connection. ->Int -- ^ number of stripes ->NominalDiffTime -- ^ idleTime for each resource when not using. ->Int -- ^ maximum number of resources. ->IO (Pool TCPConnection) createConnectionPool ConnParams { username', host', port', password', compression', database' } numStripes idleTime maxResources = createPool (do conn <- tcpConnect host' port' username' password' database' compression' case conn of Left err -> error err Right tcp -> return tcp ) (\TCPConnection{tcpSocket=sock}->close sock) numStripes idleTime maxResources
null
https://raw.githubusercontent.com/2049foundation/clickhouse-haskell/43a1714e344984e032b68f1c6d622d6b17721c5b/src/Database/ClickHouseDriver/Pool.hs
haskell
All rights reserved. found in the LICENSE file. ----------------------------------------------------------------------------- This module provides implementation of Connection pool for TCP network | default connection parameters (settings) | Create connection pool ^ parameters for basic connection. ^ number of stripes ^ idleTime for each resource when not using. ^ maximum number of resources.
Copyright ( c ) 2020 - present , EMQX , Inc. This source code is distributed under the terms of a MIT license , # LANGUAGE BlockArguments # # LANGUAGE NamedFieldPuns # module Database.ClickHouseDriver.Pool ( createConnectionPool ) where import Database.ClickHouseDriver.Connection ( tcpConnect ) import Database.ClickHouseDriver.Defines ( _DEFAULT_USERNAME, _DEFAULT_HOST_NAME, _DEFAULT_PASSWORD, _DEFAULT_PORT_NAME, _DEFAULT_DATABASE, _DEFAULT_COMPRESSION_SETTING ) import Data.Pool ( createPool, Pool ) import Data.Time.Clock ( NominalDiffTime ) import Network.Socket (close) import Data.Default.Class ( Default(..) ) import Database.ClickHouseDriver.Types ( ConnParams(..), TCPConnection(TCPConnection, tcpSocket) ) instance Default ConnParams where def = ConnParams{ username' = _DEFAULT_USERNAME ,host' = _DEFAULT_HOST_NAME ,port' = _DEFAULT_PORT_NAME ,password' = _DEFAULT_PASSWORD ,compression' = _DEFAULT_COMPRESSION_SETTING ,database' = _DEFAULT_DATABASE } createConnectionPool :: ConnParams ->Int ->NominalDiffTime ->Int ->IO (Pool TCPConnection) createConnectionPool ConnParams { username', host', port', password', compression', database' } numStripes idleTime maxResources = createPool (do conn <- tcpConnect host' port' username' password' database' compression' case conn of Left err -> error err Right tcp -> return tcp ) (\TCPConnection{tcpSocket=sock}->close sock) numStripes idleTime maxResources
167085600a6ce3a381835d29c7dc1b98ecd88def9d6b338573a351a9d3ec16b3
spawnfest/eep49ers
ssh_io.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2005 - 2017 . 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% %% %% %%% Description: user interaction for SSH -module(ssh_io). -export([yes_no/2, read_password/2, read_line/2, format/2]). -include("ssh.hrl"). read_line(Prompt, _Opts) -> format("~s", [listify(Prompt)]), unicode:characters_to_list(io:get_line("")). yes_no(Prompt, Opts) -> format("~s [y/n]?", [Prompt]), case trim(io:get_line("")) of "y" -> yes; "n" -> no; "Y" -> yes; "N" -> no; _ -> format("please answer y or n\n",[]), yes_no(Prompt, Opts) end. read_password(Prompt, Opts) -> format("~s", [listify(Prompt)]), case trim(io:get_password()) of "" -> read_password(Prompt, Opts); Pwd -> Pwd end. format(Fmt, Args) -> io:format(Fmt, Args). %%%================================================================ listify(A) when is_atom(A) -> atom_to_list(A); listify(L) when is_list(L) -> L; listify(B) when is_binary(B) -> binary_to_list(B). trim(Line) when is_list(Line) -> lists:reverse(trim1(lists:reverse(trim1(Line)))); trim(Line) when is_binary(Line) -> trim(unicode:characters_to_list(Line)); trim(Other) -> Other. trim1([$\s|Cs]) -> trim(Cs); trim1([$\r|Cs]) -> trim(Cs); trim1([$\n|Cs]) -> trim(Cs); trim1([$\t|Cs]) -> trim(Cs); trim1(Cs) -> Cs.
null
https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/ssh/src/ssh_io.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% Description: user interaction for SSH ================================================================
Copyright Ericsson AB 2005 - 2017 . 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(ssh_io). -export([yes_no/2, read_password/2, read_line/2, format/2]). -include("ssh.hrl"). read_line(Prompt, _Opts) -> format("~s", [listify(Prompt)]), unicode:characters_to_list(io:get_line("")). yes_no(Prompt, Opts) -> format("~s [y/n]?", [Prompt]), case trim(io:get_line("")) of "y" -> yes; "n" -> no; "Y" -> yes; "N" -> no; _ -> format("please answer y or n\n",[]), yes_no(Prompt, Opts) end. read_password(Prompt, Opts) -> format("~s", [listify(Prompt)]), case trim(io:get_password()) of "" -> read_password(Prompt, Opts); Pwd -> Pwd end. format(Fmt, Args) -> io:format(Fmt, Args). listify(A) when is_atom(A) -> atom_to_list(A); listify(L) when is_list(L) -> L; listify(B) when is_binary(B) -> binary_to_list(B). trim(Line) when is_list(Line) -> lists:reverse(trim1(lists:reverse(trim1(Line)))); trim(Line) when is_binary(Line) -> trim(unicode:characters_to_list(Line)); trim(Other) -> Other. trim1([$\s|Cs]) -> trim(Cs); trim1([$\r|Cs]) -> trim(Cs); trim1([$\n|Cs]) -> trim(Cs); trim1([$\t|Cs]) -> trim(Cs); trim1(Cs) -> Cs.
8cd3ae8c462071ce5233711cedf85869f06d07c5b436e52155f1792d2ece8b26
yi-editor/yi
IReader.hs
{-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # {-# OPTIONS_HADDOCK show-extensions #-} -- | Module : . IReader -- License : GPL-2 -- Maintainer : -- Stability : experimental -- Portability : portable -- -- This module defines a list type and operations on it; it further -- provides functions which write in and out the list. The goal is to -- make it easy for the user to store a large number of text buffers -- and cycle among them, making edits as she goes. The idea is -- inspired by \"incremental reading\", see -- <>. module Yi.IReader where import Control.Exception (SomeException, catch) import Control.Monad (join, void) import Data.Binary (Binary, decode, encodeFile) import qualified Data.ByteString.Char8 as B (ByteString, pack, readFile, unpack) import qualified Data.ByteString.Lazy.Char8 as BL (fromChunks) import Data.Default (Default, def) import Data.Sequence as S (Seq, ViewL (EmptyL, (:<)), ViewR ((:>)), empty, length, null, splitAt, viewl, viewr, (<|), (><), (|>)) import Data.Typeable (Typeable) import Yi.Buffer.HighLevel (replaceBufferContent, topB) import Yi.Buffer.Misc (elemsB, getBufferDyn, putBufferDyn) import Yi.Editor (withCurrentBuffer) import Yi.Keymap (YiM) import Yi.Paths (getConfigPath) import qualified Yi.Rope as R (fromString, toString) import Yi.Types (YiVariable) import Yi.Utils (io) -- | TODO: Why 'B.ByteString'? type Article = B.ByteString newtype ArticleDB = ADB { unADB :: Seq Article } deriving (Typeable, Binary) instance Default ArticleDB where def = ADB S.empty instance YiVariable ArticleDB | Take an ' ArticleDB ' , and return the first ' Article ' and an -- ArticleDB - *without* that article. split :: ArticleDB -> (Article, ArticleDB) split (ADB adb) = case viewl adb of EmptyL -> (B.pack "", def) (a :< b) -> (a, ADB b) | Get the first article in the list . We use the list to express relative priority ; the first is the most , the last least . We then -- just cycle through - every article gets equal time. getLatestArticle :: ArticleDB -> Article getLatestArticle = fst . split -- we only want the article | We remove the old first article , and we stick it on the end of the -- list using the presumably modified version. removeSetLast :: ArticleDB -> Article -> ArticleDB removeSetLast adb old = ADB (unADB (snd (split adb)) S.|> old) -- we move the last entry to the entry 'length `div` n'from the beginning ; so ' shift 1 ' would do nothing ( eg . the last index is 50 , 50 ` div ` 1 = = 50 , so the item would be moved to where it is ) ' shift 2 ' will move it to the middle of the list , though ; last index = 50 , then 50 ` div ` 2 will shift the item to index 25 , and so on down to 50 ` div ` 50 - the head of the list / Seq . shift :: Int -> ArticleDB -> ArticleDB shift n adb = if n < 2 || lst < 2 then adb else ADB $ (r S.|> lastentry) >< s' where lst = S.length (unADB adb) - 1 (r,s) = S.splitAt (lst `div` n) (unADB adb) (s' :> lastentry) = S.viewr s -- | Insert a new article with top priority (that is, at the front of the list). insertArticle :: ArticleDB -> Article -> ArticleDB insertArticle (ADB adb) new = ADB (new S.<| adb) | Serialize given ' ArticleDB ' out . writeDB :: ArticleDB -> YiM () writeDB adb = void $ io . join . fmap (`encodeFile` adb) $ getArticleDbFilename -- | Read in database from 'getArticleDbFilename' and then parse it -- into an 'ArticleDB'. readDB :: YiM ArticleDB readDB = io $ (getArticleDbFilename >>= r) `catch` returnDefault where r = fmap (decode . BL.fromChunks . return) . B.readFile -- We read in with strict bytestrings to guarantee the file is -- closed, and then we convert it to the lazy bytestring -- data.binary expects. This is inefficient, but alas... returnDefault (_ :: SomeException) = return def -- | Get articles.db database of locations to visit getArticleDbFilename :: IO FilePath getArticleDbFilename = getConfigPath "articles.db" | Returns the database as it exists on the disk , and the current buffer contents . Note that the gives us an empty Seq . So first we try the buffer state in the hope we can avoid a -- very expensive read from disk, and if we find nothing (that is, if -- we get an empty Seq), only then do we call 'readDB'. oldDbNewArticle :: YiM (ArticleDB, Article) oldDbNewArticle = do saveddb <- withCurrentBuffer getBufferDyn newarticle <- B.pack . R.toString <$> withCurrentBuffer elemsB if not $ S.null (unADB saveddb) then return (saveddb, newarticle) else readDB >>= \olddb -> return (olddb, newarticle) -- | Given an 'ArticleDB', dump the scheduled article into the buffer -- (replacing previous contents). setDisplayedArticle :: ArticleDB -> YiM () setDisplayedArticle newdb = do let next = getLatestArticle newdb withCurrentBuffer $ do replaceBufferContent $ R.fromString (B.unpack next) topB -- replaceBufferContents moves us to bottom? putBufferDyn newdb -- | Go to next one. This ignores the buffer, but it doesn't remove -- anything from the database. However, the ordering does change. nextArticle :: YiM () nextArticle = do (oldb,_) <- oldDbNewArticle Ignore buffer , just set the first article last let newdb = removeSetLast oldb (getLatestArticle oldb) writeDB newdb setDisplayedArticle newdb -- | Delete current article (the article as in the database), and go -- to next one. deleteAndNextArticle :: YiM () deleteAndNextArticle = do (oldb,_) <- oldDbNewArticle -- throw away changes drop 1st article EmptyL -> empty (_ :< b) -> b writeDB ndb setDisplayedArticle ndb -- | The main action. We fetch the old database, we fetch the modified -- article from the buffer, then we call the function 'updateSetLast' which removes the first article and pushes our modified article to -- the end of the list. saveAndNextArticle :: Int -> YiM () saveAndNextArticle n = do (oldb,newa) <- oldDbNewArticle let newdb = shift n $ removeSetLast oldb newa writeDB newdb setDisplayedArticle newdb -- | Assume the buffer is an entirely new article just imported this second , and save it . We do n't want to use ' updateSetLast ' since -- that will erase an article. saveAsNewArticle :: YiM () saveAsNewArticle = do oldb <- readDB -- make sure we read from disk - we aren't in iread-mode! (_,newa) <- oldDbNewArticle -- we ignore the fst - the Default is 'empty' let newdb = insertArticle oldb newa writeDB newdb
null
https://raw.githubusercontent.com/yi-editor/yi/58c239e3a77cef8f4f77e94677bd6a295f585f5f/yi-ireader/src/Yi/IReader.hs
haskell
# LANGUAGE DeriveDataTypeable # # LANGUAGE OverloadedStrings # # OPTIONS_HADDOCK show-extensions # | License : GPL-2 Maintainer : Stability : experimental Portability : portable This module defines a list type and operations on it; it further provides functions which write in and out the list. The goal is to make it easy for the user to store a large number of text buffers and cycle among them, making edits as she goes. The idea is inspired by \"incremental reading\", see <>. | TODO: Why 'B.ByteString'? ArticleDB - *without* that article. just cycle through - every article gets equal time. we only want the article list using the presumably modified version. we move the last entry to the entry 'length `div` n'from the | Insert a new article with top priority (that is, at the front of the list). | Read in database from 'getArticleDbFilename' and then parse it into an 'ArticleDB'. We read in with strict bytestrings to guarantee the file is closed, and then we convert it to the lazy bytestring data.binary expects. This is inefficient, but alas... | Get articles.db database of locations to visit very expensive read from disk, and if we find nothing (that is, if we get an empty Seq), only then do we call 'readDB'. | Given an 'ArticleDB', dump the scheduled article into the buffer (replacing previous contents). replaceBufferContents moves us to bottom? | Go to next one. This ignores the buffer, but it doesn't remove anything from the database. However, the ordering does change. | Delete current article (the article as in the database), and go to next one. throw away changes | The main action. We fetch the old database, we fetch the modified article from the buffer, then we call the function 'updateSetLast' the end of the list. | Assume the buffer is an entirely new article just imported this that will erase an article. make sure we read from disk - we aren't in iread-mode! we ignore the fst - the Default is 'empty'
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE ScopedTypeVariables # Module : . IReader module Yi.IReader where import Control.Exception (SomeException, catch) import Control.Monad (join, void) import Data.Binary (Binary, decode, encodeFile) import qualified Data.ByteString.Char8 as B (ByteString, pack, readFile, unpack) import qualified Data.ByteString.Lazy.Char8 as BL (fromChunks) import Data.Default (Default, def) import Data.Sequence as S (Seq, ViewL (EmptyL, (:<)), ViewR ((:>)), empty, length, null, splitAt, viewl, viewr, (<|), (><), (|>)) import Data.Typeable (Typeable) import Yi.Buffer.HighLevel (replaceBufferContent, topB) import Yi.Buffer.Misc (elemsB, getBufferDyn, putBufferDyn) import Yi.Editor (withCurrentBuffer) import Yi.Keymap (YiM) import Yi.Paths (getConfigPath) import qualified Yi.Rope as R (fromString, toString) import Yi.Types (YiVariable) import Yi.Utils (io) type Article = B.ByteString newtype ArticleDB = ADB { unADB :: Seq Article } deriving (Typeable, Binary) instance Default ArticleDB where def = ADB S.empty instance YiVariable ArticleDB | Take an ' ArticleDB ' , and return the first ' Article ' and an split :: ArticleDB -> (Article, ArticleDB) split (ADB adb) = case viewl adb of EmptyL -> (B.pack "", def) (a :< b) -> (a, ADB b) | Get the first article in the list . We use the list to express relative priority ; the first is the most , the last least . We then getLatestArticle :: ArticleDB -> Article | We remove the old first article , and we stick it on the end of the removeSetLast :: ArticleDB -> Article -> ArticleDB removeSetLast adb old = ADB (unADB (snd (split adb)) S.|> old) beginning ; so ' shift 1 ' would do nothing ( eg . the last index is 50 , 50 ` div ` 1 = = 50 , so the item would be moved to where it is ) ' shift 2 ' will move it to the middle of the list , though ; last index = 50 , then 50 ` div ` 2 will shift the item to index 25 , and so on down to 50 ` div ` 50 - the head of the list / Seq . shift :: Int -> ArticleDB -> ArticleDB shift n adb = if n < 2 || lst < 2 then adb else ADB $ (r S.|> lastentry) >< s' where lst = S.length (unADB adb) - 1 (r,s) = S.splitAt (lst `div` n) (unADB adb) (s' :> lastentry) = S.viewr s insertArticle :: ArticleDB -> Article -> ArticleDB insertArticle (ADB adb) new = ADB (new S.<| adb) | Serialize given ' ArticleDB ' out . writeDB :: ArticleDB -> YiM () writeDB adb = void $ io . join . fmap (`encodeFile` adb) $ getArticleDbFilename readDB :: YiM ArticleDB readDB = io $ (getArticleDbFilename >>= r) `catch` returnDefault where r = fmap (decode . BL.fromChunks . return) . B.readFile returnDefault (_ :: SomeException) = return def getArticleDbFilename :: IO FilePath getArticleDbFilename = getConfigPath "articles.db" | Returns the database as it exists on the disk , and the current buffer contents . Note that the gives us an empty Seq . So first we try the buffer state in the hope we can avoid a oldDbNewArticle :: YiM (ArticleDB, Article) oldDbNewArticle = do saveddb <- withCurrentBuffer getBufferDyn newarticle <- B.pack . R.toString <$> withCurrentBuffer elemsB if not $ S.null (unADB saveddb) then return (saveddb, newarticle) else readDB >>= \olddb -> return (olddb, newarticle) setDisplayedArticle :: ArticleDB -> YiM () setDisplayedArticle newdb = do let next = getLatestArticle newdb withCurrentBuffer $ do replaceBufferContent $ R.fromString (B.unpack next) putBufferDyn newdb nextArticle :: YiM () nextArticle = do (oldb,_) <- oldDbNewArticle Ignore buffer , just set the first article last let newdb = removeSetLast oldb (getLatestArticle oldb) writeDB newdb setDisplayedArticle newdb deleteAndNextArticle :: YiM () deleteAndNextArticle = do drop 1st article EmptyL -> empty (_ :< b) -> b writeDB ndb setDisplayedArticle ndb which removes the first article and pushes our modified article to saveAndNextArticle :: Int -> YiM () saveAndNextArticle n = do (oldb,newa) <- oldDbNewArticle let newdb = shift n $ removeSetLast oldb newa writeDB newdb setDisplayedArticle newdb second , and save it . We do n't want to use ' updateSetLast ' since saveAsNewArticle :: YiM () saveAsNewArticle = do let newdb = insertArticle oldb newa writeDB newdb
236f2489b9bbb0f956696c63f6047cd87a1066604640c2c9cebe74344fcec18b
MarchLiu/market
core.clj
(ns matcher.core) (defn foo "I don't do a whole lot." [x] (println x "Hello, World!"))
null
https://raw.githubusercontent.com/MarchLiu/market/7a7daf6c04b41e0f8494be6740da8d54785c5e77/matcher/src/matcher/core.clj
clojure
(ns matcher.core) (defn foo "I don't do a whole lot." [x] (println x "Hello, World!"))
c0b91205dc0c7521e4126424368d3ca9a8b7d7dbd2d5ea9a2009225da2ced070
jpmonettas/flow-storm-debugger
api.cljs
(ns flow-storm.api (:require [flow-storm.json-serializer :as serializer] [flow-storm.remote-websocket-client :as remote-websocket-client] [flow-storm.runtime.taps :as rt-taps] [flow-storm.runtime.events :as rt-events] [flow-storm.runtime.indexes.api :as indexes-api] [flow-storm.runtime.debuggers-api :as dbg-api] [flow-storm.runtime.values :as rt-values] [flow-storm.utils :refer [log] :as utils] [flow-storm.tracer] [hansel.instrument.runtime]) (:require-macros [flow-storm.api])) (def api-loaded? "Used for remote connections to check this ns has been loaded" true) (defn remote-connect [config] (println "About to remote-connect ClojureScript with " config) ;; connect to the remote websocket (remote-websocket-client/start-remote-websocket-client (assoc config :api-call-fn dbg-api/call-by-name)) ;; push all events thru the websocket (rt-events/subscribe! (fn [ev] (-> [:event ev] serializer/serialize remote-websocket-client/send))) (rt-values/clear-values-references) (rt-taps/setup-tap!) (println "Remote ClojureScript runtime initialized")) (defn stop [] (rt-taps/remove-tap!) (rt-events/clear-subscription!) (rt-events/clear-pending-events!) (rt-values/clear-values-references) (indexes-api/stop) (remote-websocket-client/stop-remote-websocket-client) (log "System stopped")) (defn current-stack-trace [] (rest (.split (.-stack (js/Error.)) "\n")))
null
https://raw.githubusercontent.com/jpmonettas/flow-storm-debugger/c4419e6d18a4710b12dce93111f0ad37da1722f5/src-inst/flow_storm/api.cljs
clojure
connect to the remote websocket push all events thru the websocket
(ns flow-storm.api (:require [flow-storm.json-serializer :as serializer] [flow-storm.remote-websocket-client :as remote-websocket-client] [flow-storm.runtime.taps :as rt-taps] [flow-storm.runtime.events :as rt-events] [flow-storm.runtime.indexes.api :as indexes-api] [flow-storm.runtime.debuggers-api :as dbg-api] [flow-storm.runtime.values :as rt-values] [flow-storm.utils :refer [log] :as utils] [flow-storm.tracer] [hansel.instrument.runtime]) (:require-macros [flow-storm.api])) (def api-loaded? "Used for remote connections to check this ns has been loaded" true) (defn remote-connect [config] (println "About to remote-connect ClojureScript with " config) (remote-websocket-client/start-remote-websocket-client (assoc config :api-call-fn dbg-api/call-by-name)) (rt-events/subscribe! (fn [ev] (-> [:event ev] serializer/serialize remote-websocket-client/send))) (rt-values/clear-values-references) (rt-taps/setup-tap!) (println "Remote ClojureScript runtime initialized")) (defn stop [] (rt-taps/remove-tap!) (rt-events/clear-subscription!) (rt-events/clear-pending-events!) (rt-values/clear-values-references) (indexes-api/stop) (remote-websocket-client/stop-remote-websocket-client) (log "System stopped")) (defn current-stack-trace [] (rest (.split (.-stack (js/Error.)) "\n")))
5d4aa3c09f3a45d69444110fd33c9aec3b8a394ef076798bcfc4c464379abc2f
soegaard/urlang
info.rkt
#lang info This file describes the contents of the Urlang package . ;;; The information is used by the Racket package system. The Urlang package contains multiple collections ( urlang , urlang - doc , compiler etc ) (define collection "urlang-examples") ;;; Version number (define version "1.0") ;;; Dependencies declared here will need source (define deps '()) ;;; Dependencies here can be installed as binaries (i.e. zo-files) (define build-deps '("base" "html-writing" "at-exp-lib" "rackunit-lib" "scribble-lib" "racket-doc")) (define compile-omit-paths '())
null
https://raw.githubusercontent.com/soegaard/urlang/086622e2306e72731016c7108aca3328e5082aee/urlang-examples/info.rkt
racket
The information is used by the Racket package system. Version number Dependencies declared here will need source Dependencies here can be installed as binaries (i.e. zo-files)
#lang info This file describes the contents of the Urlang package . The Urlang package contains multiple collections ( urlang , urlang - doc , compiler etc ) (define collection "urlang-examples") (define version "1.0") (define deps '()) (define build-deps '("base" "html-writing" "at-exp-lib" "rackunit-lib" "scribble-lib" "racket-doc")) (define compile-omit-paths '())
7d3256995720daacdac9379b25a51d449c56cfe5d44961da972ff7ca42fbf260
DavidAlphaFox/aihtml
aihtml_app.erl
-module(aihtml_app). -behaviour(application). -export([start/2]). -export([stop/1]). start(_Type, _Args) -> application:start(crypto), application:start(ailib), aihtml_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/DavidAlphaFox/aihtml/82c01eb4cd39ccbef5ac32c58febcec3ac49b4af/src/aihtml_app.erl
erlang
-module(aihtml_app). -behaviour(application). -export([start/2]). -export([stop/1]). start(_Type, _Args) -> application:start(crypto), application:start(ailib), aihtml_sup:start_link(). stop(_State) -> ok.
4b5fcdedc6f71ec723d0cf5bfa203bec758233bbc7c5952b5efcc67f7186c400
roman01la/virtual.list
core.cljs
(ns example.core (:require [rum.core :as rum] [goog.dom :as gdom] [sablono.core :refer-macros [html]] [virtual.list :refer [v-list]])) (rum/defc Avatar [label color] [:div {:style {:background-color color :color "#fff" :width 42 :min-width 42 :height 42 :border-radius "50%" :box-sizing "border-box" :border "2px solid #eee" :display "flex" :align-items "center" :justify-content "center" :margin "0 16px 0 4px"}} [:span {} label]]) (rum/defc InputField [label value on-change] [:div {} [:span {:style {:margin "0 8px 0 0"}} label] [:input {:value value :type "number" :on-change (comp on-change js/parseFloat #(.. % -target -value))}]]) (rum/defcs ContactsList < (rum/local {:row-height 48 :rows-count 8} ::state) [{state ::state} data] (let [{:keys [row-height rows-count]} @state max-rows-count (count data) render-row (fn [{:keys [idx scrolling?]}] (let [[n color] (nth data idx)] (html [:div {:key idx :style {:height row-height :box-sizing "border-box" :border-bottom (when (not= idx (dec max-rows-count)) "1px solid #ccc") :display "flex" :align-items "center" :padding "0 4px"}} (Avatar (inc n) color) [:div {} "Lorem Ipsum is simply dummy text of the printing and typesetting industry"]])))] [:div {:style {:width "100%" :font "normal 16px sans-serif"}} [:div {:style {:display "flex" :justify-content "space-around" :padding 8}} (InputField "Row height:" row-height #(swap! state assoc :row-height %)) (InputField "Rows count:" rows-count #(swap! state assoc :rows-count %))] [:div {:style {:border "1px solid #ccc" :border-radius 4}} (v-list {:row-height row-height :rows-count rows-count :max-rows-count max-rows-count :render-row render-row :overscan-count 2})]])) (rum/mount (ContactsList (->> (range 1000) (mapv (fn [n] [n (str "#" (.toString (rand-int 16rFFFFFF) 16))])))) (gdom/getElement "example"))
null
https://raw.githubusercontent.com/roman01la/virtual.list/90dc1b6126ccfa368864a65d9c13a0618d2b5eb6/examples/example/core.cljs
clojure
(ns example.core (:require [rum.core :as rum] [goog.dom :as gdom] [sablono.core :refer-macros [html]] [virtual.list :refer [v-list]])) (rum/defc Avatar [label color] [:div {:style {:background-color color :color "#fff" :width 42 :min-width 42 :height 42 :border-radius "50%" :box-sizing "border-box" :border "2px solid #eee" :display "flex" :align-items "center" :justify-content "center" :margin "0 16px 0 4px"}} [:span {} label]]) (rum/defc InputField [label value on-change] [:div {} [:span {:style {:margin "0 8px 0 0"}} label] [:input {:value value :type "number" :on-change (comp on-change js/parseFloat #(.. % -target -value))}]]) (rum/defcs ContactsList < (rum/local {:row-height 48 :rows-count 8} ::state) [{state ::state} data] (let [{:keys [row-height rows-count]} @state max-rows-count (count data) render-row (fn [{:keys [idx scrolling?]}] (let [[n color] (nth data idx)] (html [:div {:key idx :style {:height row-height :box-sizing "border-box" :border-bottom (when (not= idx (dec max-rows-count)) "1px solid #ccc") :display "flex" :align-items "center" :padding "0 4px"}} (Avatar (inc n) color) [:div {} "Lorem Ipsum is simply dummy text of the printing and typesetting industry"]])))] [:div {:style {:width "100%" :font "normal 16px sans-serif"}} [:div {:style {:display "flex" :justify-content "space-around" :padding 8}} (InputField "Row height:" row-height #(swap! state assoc :row-height %)) (InputField "Rows count:" rows-count #(swap! state assoc :rows-count %))] [:div {:style {:border "1px solid #ccc" :border-radius 4}} (v-list {:row-height row-height :rows-count rows-count :max-rows-count max-rows-count :render-row render-row :overscan-count 2})]])) (rum/mount (ContactsList (->> (range 1000) (mapv (fn [n] [n (str "#" (.toString (rand-int 16rFFFFFF) 16))])))) (gdom/getElement "example"))
edf296f0388065dbec70c3d473cb374adbb2694bb61a5a5898b24b891ef68a80
marick/Midje
open_protocols.clj
(ns ^{:doc "Macros for using protocols in prerequisites. The strategy for open protocols is to rewrite each function defined in the deftype/defrecord so that it checks whether its corresponding symbol is currently faked out. If so, it uses that function definition instead of continuing on with its own implementation."} midje.open-protocols (:require [midje.data.prerequisite-state :refer [implements-a-fake?]] [midje.production-mode :refer [user-desires-checking?]])) (defn- ^{:testable true } implementation? "Is this thing a protocol or a function definition?" [name-or-impl] (not (symbol? name-or-impl))) (defn- ^:testable protocol? "Is this a java interface or class (like Object) or a Clojure protocol?" [symbol] (not (instance? java.lang.Class (resolve symbol)))) (defn- rewrite-as-mockable-function [[name args & body]] `(~name ~args (if (implements-a-fake? ~name) (apply ~name ~args) (do ~@body)))) (defn- rewrite-def*-body [body] (if (user-desires-checking?) (first (reduce (fn [[revised-body working-on-protocol?] form] (if (implementation? form) (vector (conj revised-body (if working-on-protocol? (rewrite-as-mockable-function form) form)) working-on-protocol?) (vector (conj revised-body form) (protocol? form)))) [[] false] body)) body)) (defmacro deftype-openly [name fields & specs] `(deftype ~name ~fields ~@(rewrite-def*-body specs))) (defmacro defrecord-openly [name fields & specs] `(defrecord ~name ~fields ~@(rewrite-def*-body specs)))
null
https://raw.githubusercontent.com/marick/Midje/2b9bcb117442d3bd2d16446b47540888d683c717/src/midje/open_protocols.clj
clojure
(ns ^{:doc "Macros for using protocols in prerequisites. The strategy for open protocols is to rewrite each function defined in the deftype/defrecord so that it checks whether its corresponding symbol is currently faked out. If so, it uses that function definition instead of continuing on with its own implementation."} midje.open-protocols (:require [midje.data.prerequisite-state :refer [implements-a-fake?]] [midje.production-mode :refer [user-desires-checking?]])) (defn- ^{:testable true } implementation? "Is this thing a protocol or a function definition?" [name-or-impl] (not (symbol? name-or-impl))) (defn- ^:testable protocol? "Is this a java interface or class (like Object) or a Clojure protocol?" [symbol] (not (instance? java.lang.Class (resolve symbol)))) (defn- rewrite-as-mockable-function [[name args & body]] `(~name ~args (if (implements-a-fake? ~name) (apply ~name ~args) (do ~@body)))) (defn- rewrite-def*-body [body] (if (user-desires-checking?) (first (reduce (fn [[revised-body working-on-protocol?] form] (if (implementation? form) (vector (conj revised-body (if working-on-protocol? (rewrite-as-mockable-function form) form)) working-on-protocol?) (vector (conj revised-body form) (protocol? form)))) [[] false] body)) body)) (defmacro deftype-openly [name fields & specs] `(deftype ~name ~fields ~@(rewrite-def*-body specs))) (defmacro defrecord-openly [name fields & specs] `(defrecord ~name ~fields ~@(rewrite-def*-body specs)))
d1ac58d6d2056e70ace1bf42c15a6c7ee6dfb3e23b615a6ea367df974d14f2cb
serokell/importify
05-RecordWildCardUsed.hs
# LANGUAGE RecordWildCards # module RecordWildCardUsed where import Language.Haskell.Names (Symbol (Value, symbolName)) foo Value{..} = symbolName
null
https://raw.githubusercontent.com/serokell/importify/09f31d851b2152ae6ce880b81abc3554ade29f37/test/test-data/haskell-names%40records/05-RecordWildCardUsed.hs
haskell
# LANGUAGE RecordWildCards # module RecordWildCardUsed where import Language.Haskell.Names (Symbol (Value, symbolName)) foo Value{..} = symbolName
cdfe982249ea60e945b433cc76ca5a79b63726bef33ef34734b16a7e5d2464ff
valderman/selda
Types.hs
# OPTIONS_GHC -fno - warn - unused - binds # # LANGUAGE GADTs , TypeOperators , TypeFamilies , FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving , MultiParamTypeClasses # # LANGUAGE UndecidableInstances , DeriveGeneric , OverloadedStrings # # LANGUAGE CPP # -- | Basic Selda types. module Database.Selda.Types ( (:*:)(..), Head, Tup (..) , first, second, third, fourth, fifth , ColName, TableName , modColName, mkColName, mkTableName, addColSuffix, addColPrefix , fromColName, fromTableName, rawTableName, intercalateColNames ) where import Data.Dynamic ( Typeable ) import Data.String ( IsString ) import Data.Text (Text, replace, append, intercalate) import GHC.Generics (Generic) -- | Name of a database column. newtype ColName = ColName { unColName :: Text } deriving (Ord, Eq, Show, IsString) -- | Name of a database table. newtype TableName = TableName Text deriving (Ord, Eq, Show, IsString) -- | Modify the given column name using the given function. modColName :: ColName -> (Text -> Text) -> ColName modColName (ColName cn) f = ColName (f cn) -- | Add a prefix to a column name. addColPrefix :: ColName -> Text -> ColName addColPrefix (ColName cn) s = ColName $ Data.Text.append s cn -- | Add a suffix to a column name. addColSuffix :: ColName -> Text -> ColName addColSuffix (ColName cn) s = ColName $ Data.Text.append cn s -- | Convert a column name into a string, with quotes. fromColName :: ColName -> Text fromColName (ColName cn) = mconcat ["\"", escapeQuotes cn, "\""] -- | Convert column names into a string, without quotes, intercalating the given -- string. -- -- @ -- intercalateColNames "_" [ColName "a", ColName "b"] == "a_b" -- @ intercalateColNames :: Text -> [ColName] -> Text intercalateColNames inter cs = intercalate inter (escapeQuotes . unColName <$> cs) -- | Convert a table name into a string, with quotes. fromTableName :: TableName -> Text fromTableName (TableName tn) = mconcat ["\"", escapeQuotes tn, "\""] -- | Convert a table name into a string, without quotes. rawTableName :: TableName -> Text rawTableName (TableName tn) = escapeQuotes tn -- | Create a column name. mkColName :: Text -> ColName mkColName = ColName -- | Create a column name. mkTableName :: Text -> TableName mkTableName = TableName -- | Escape double quotes in an SQL identifier. escapeQuotes :: Text -> Text escapeQuotes = Data.Text.replace "\"" "\"\"" -- | An inductively defined "tuple", or heterogeneous, non-empty list. data a :*: b where (:*:) :: a -> b -> a :*: b deriving (Typeable, Generic) infixr 1 :*: instance (Show a, Show b) => Show (a :*: b) where show (a :*: b) = show a ++ " :*: " ++ show b instance (Eq a, Eq b) => Eq (a :*: b) where (a :*: b) == (a' :*: b') = a == a' && b == b' instance (Ord a, Ord b) => Ord (a :*: b) where (a :*: b) `compare` (a' :*: b') = case a `compare` a' of EQ -> b `compare` b' o -> o type family Head a where Head (a :*: b) = a Head a = a class Tup a where tupHead :: a -> Head a instance {-# OVERLAPPING #-} Tup (a :*: b) where tupHead (a :*: _) = a instance Head a ~ a => Tup a where tupHead a = a | Get the first element of an inductive tuple . first :: Tup a => a -> Head a first = tupHead | Get the second element of an inductive tuple . second :: Tup b => (a :*: b) -> Head b second (_ :*: b) = tupHead b | Get the third element of an inductive tuple . third :: Tup c => (a :*: b :*: c) -> Head c third (_ :*: _ :*: c) = tupHead c | Get the fourth element of an inductive tuple . fourth :: Tup d => (a :*: b :*: c :*: d) -> Head d fourth (_ :*: _ :*: _ :*: d) = tupHead d | Get the fifth element of an inductive tuple . fifth :: Tup e => (a :*: b :*: c :*: d :*: e) -> Head e fifth (_ :*: _ :*: _ :*: _ :*: e) = tupHead e
null
https://raw.githubusercontent.com/valderman/selda/c270f354caaa733d10b79d5c0ba05f98f56fa4b6/selda/src/Database/Selda/Types.hs
haskell
| Basic Selda types. | Name of a database column. | Name of a database table. | Modify the given column name using the given function. | Add a prefix to a column name. | Add a suffix to a column name. | Convert a column name into a string, with quotes. | Convert column names into a string, without quotes, intercalating the given string. @ intercalateColNames "_" [ColName "a", ColName "b"] == "a_b" @ | Convert a table name into a string, with quotes. | Convert a table name into a string, without quotes. | Create a column name. | Create a column name. | Escape double quotes in an SQL identifier. | An inductively defined "tuple", or heterogeneous, non-empty list. # OVERLAPPING #
# OPTIONS_GHC -fno - warn - unused - binds # # LANGUAGE GADTs , TypeOperators , TypeFamilies , FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving , MultiParamTypeClasses # # LANGUAGE UndecidableInstances , DeriveGeneric , OverloadedStrings # # LANGUAGE CPP # module Database.Selda.Types ( (:*:)(..), Head, Tup (..) , first, second, third, fourth, fifth , ColName, TableName , modColName, mkColName, mkTableName, addColSuffix, addColPrefix , fromColName, fromTableName, rawTableName, intercalateColNames ) where import Data.Dynamic ( Typeable ) import Data.String ( IsString ) import Data.Text (Text, replace, append, intercalate) import GHC.Generics (Generic) newtype ColName = ColName { unColName :: Text } deriving (Ord, Eq, Show, IsString) newtype TableName = TableName Text deriving (Ord, Eq, Show, IsString) modColName :: ColName -> (Text -> Text) -> ColName modColName (ColName cn) f = ColName (f cn) addColPrefix :: ColName -> Text -> ColName addColPrefix (ColName cn) s = ColName $ Data.Text.append s cn addColSuffix :: ColName -> Text -> ColName addColSuffix (ColName cn) s = ColName $ Data.Text.append cn s fromColName :: ColName -> Text fromColName (ColName cn) = mconcat ["\"", escapeQuotes cn, "\""] intercalateColNames :: Text -> [ColName] -> Text intercalateColNames inter cs = intercalate inter (escapeQuotes . unColName <$> cs) fromTableName :: TableName -> Text fromTableName (TableName tn) = mconcat ["\"", escapeQuotes tn, "\""] rawTableName :: TableName -> Text rawTableName (TableName tn) = escapeQuotes tn mkColName :: Text -> ColName mkColName = ColName mkTableName :: Text -> TableName mkTableName = TableName escapeQuotes :: Text -> Text escapeQuotes = Data.Text.replace "\"" "\"\"" data a :*: b where (:*:) :: a -> b -> a :*: b deriving (Typeable, Generic) infixr 1 :*: instance (Show a, Show b) => Show (a :*: b) where show (a :*: b) = show a ++ " :*: " ++ show b instance (Eq a, Eq b) => Eq (a :*: b) where (a :*: b) == (a' :*: b') = a == a' && b == b' instance (Ord a, Ord b) => Ord (a :*: b) where (a :*: b) `compare` (a' :*: b') = case a `compare` a' of EQ -> b `compare` b' o -> o type family Head a where Head (a :*: b) = a Head a = a class Tup a where tupHead :: a -> Head a tupHead (a :*: _) = a instance Head a ~ a => Tup a where tupHead a = a | Get the first element of an inductive tuple . first :: Tup a => a -> Head a first = tupHead | Get the second element of an inductive tuple . second :: Tup b => (a :*: b) -> Head b second (_ :*: b) = tupHead b | Get the third element of an inductive tuple . third :: Tup c => (a :*: b :*: c) -> Head c third (_ :*: _ :*: c) = tupHead c | Get the fourth element of an inductive tuple . fourth :: Tup d => (a :*: b :*: c :*: d) -> Head d fourth (_ :*: _ :*: _ :*: d) = tupHead d | Get the fifth element of an inductive tuple . fifth :: Tup e => (a :*: b :*: c :*: d :*: e) -> Head e fifth (_ :*: _ :*: _ :*: _ :*: e) = tupHead e
85d807611b64cca908233f24b5bb3bbd2617adad4e7ae9657671551bd5c190ea
commercialhaskell/stack
build-stack-installer.hs
{- stack script --resolver nightly-2022-11-14 --install-ghc --package nsis -} {-# LANGUAGE OverloadedStrings #-} import Data.String import System.Environment import Development.NSIS import Development.NSIS.Plugins.EnvVarUpdate Note that it is * required * to use a NSIS compiler that supports long strings , -- to avoid corrupting the user's $PATH. main :: IO () main = do [srcPath, execPath, nsiPath, stackVersionStr] <- getArgs writeFile (fromString nsiPath) $ nsis $ do _ <- constantStr "Name" "Haskell Stack" name "$Name" outFile $ fromString execPath installDir "$APPDATA/local/bin" installDirRegKey HKCU "Software/$Name" "Install_Dir" requestExecutionLevel User page Directory page Components page InstFiles unpage Components unpage InstFiles section "Install Haskell Stack" [Required] $ do setOutPath "$INSTDIR" file [OName "stack.exe"] $ fromString srcPath -- Write the installation path into the registry writeRegStr HKCU "SOFTWARE/$Name" "Install_Dir" "$INSTDIR" -- Write the uninstall keys for Windows writeRegStr HKCU "Software/Microsoft/Windows/CurrentVersion/Uninstall/$Name" "DisplayName" "$Name" writeRegStr HKCU "Software/Microsoft/Windows/CurrentVersion/Uninstall/$Name" "DisplayVersion" (str stackVersionStr) writeRegStr HKCU "Software/Microsoft/Windows/CurrentVersion/Uninstall/$Name" "UninstallString" "\"$INSTDIR/uninstall-stack.exe\"" writeRegDWORD HKCU "Software/Microsoft/Windows/CurrentVersion/Uninstall/$Name" "NoModify" 1 writeRegDWORD HKCU "Software/Microsoft/Windows/CurrentVersion/Uninstall/$Name" "NoRepair" 1 writeUninstaller "uninstall-stack.exe" section "Add to user %PATH%" [ Description "Add installation directory to user %PATH% to allow running Stack in the console." ] $ do setEnvVarPrepend HKCU "PATH" "$INSTDIR" section "Set %STACK_ROOT% to recommended default" [ Description "Set %STACK_ROOT% to C:\\sr to workaround issues with long paths." ] $ do setEnvVar HKCU "STACK_ROOT" "C:\\sr" Uninstallation sections . ( Any section prepended with " un . " is an -- uninstallation option.) section "un.stack" [] $ do deleteRegKey HKCU "Software/Microsoft/Windows/CurrentVersion/Uninstall/$Name" deleteRegKey HKCU "Software/$Name" delete [] "$INSTDIR/stack.exe" delete [] "$INSTDIR/uninstall-stack.exe" rmdir [] "$INSTDIR" -- will not remove if not empty -- The description text is not actually added to the uninstaller as of -- nsis-0.3 section "un.Install location on %PATH%" [ Description "Remove $INSTDIR from the user %PATH%. There may be other programs installed in that location." ] $ do setEnvVarRemove HKCU "PATH" "$INSTDIR" section "un.Set %STACK_ROOT% to recommended default" [ Description "Remove setting of %STACK_ROOT% to C:\\sr." ] $ do deleteEnvVar HKCU "STACK_ROOT" section "un.Compilers installed by Stack" [ Unselected , Description "Remove %LOCALAPPDATA%/Programs/stack, which contains compilers that have been installed by Stack." ] $ do rmdir [Recursive] "$LOCALAPPDATA/Programs/stack" section "un.Stack snapshots and configuration" [ Unselected , Description "Remove %APPDATA%/stack, which contains the user-defined global stack.yaml and the snapshot/compilation cache." ] $ do rmdir [Recursive] "$APPDATA/stack"
null
https://raw.githubusercontent.com/commercialhaskell/stack/dafb4cdace8603837abe9d7c344a40c04fc7824c/etc/scripts/build-stack-installer.hs
haskell
stack script --resolver nightly-2022-11-14 --install-ghc --package nsis # LANGUAGE OverloadedStrings # to avoid corrupting the user's $PATH. Write the installation path into the registry Write the uninstall keys for Windows uninstallation option.) will not remove if not empty The description text is not actually added to the uninstaller as of nsis-0.3
import Data.String import System.Environment import Development.NSIS import Development.NSIS.Plugins.EnvVarUpdate Note that it is * required * to use a NSIS compiler that supports long strings , main :: IO () main = do [srcPath, execPath, nsiPath, stackVersionStr] <- getArgs writeFile (fromString nsiPath) $ nsis $ do _ <- constantStr "Name" "Haskell Stack" name "$Name" outFile $ fromString execPath installDir "$APPDATA/local/bin" installDirRegKey HKCU "Software/$Name" "Install_Dir" requestExecutionLevel User page Directory page Components page InstFiles unpage Components unpage InstFiles section "Install Haskell Stack" [Required] $ do setOutPath "$INSTDIR" file [OName "stack.exe"] $ fromString srcPath writeRegStr HKCU "SOFTWARE/$Name" "Install_Dir" "$INSTDIR" writeRegStr HKCU "Software/Microsoft/Windows/CurrentVersion/Uninstall/$Name" "DisplayName" "$Name" writeRegStr HKCU "Software/Microsoft/Windows/CurrentVersion/Uninstall/$Name" "DisplayVersion" (str stackVersionStr) writeRegStr HKCU "Software/Microsoft/Windows/CurrentVersion/Uninstall/$Name" "UninstallString" "\"$INSTDIR/uninstall-stack.exe\"" writeRegDWORD HKCU "Software/Microsoft/Windows/CurrentVersion/Uninstall/$Name" "NoModify" 1 writeRegDWORD HKCU "Software/Microsoft/Windows/CurrentVersion/Uninstall/$Name" "NoRepair" 1 writeUninstaller "uninstall-stack.exe" section "Add to user %PATH%" [ Description "Add installation directory to user %PATH% to allow running Stack in the console." ] $ do setEnvVarPrepend HKCU "PATH" "$INSTDIR" section "Set %STACK_ROOT% to recommended default" [ Description "Set %STACK_ROOT% to C:\\sr to workaround issues with long paths." ] $ do setEnvVar HKCU "STACK_ROOT" "C:\\sr" Uninstallation sections . ( Any section prepended with " un . " is an section "un.stack" [] $ do deleteRegKey HKCU "Software/Microsoft/Windows/CurrentVersion/Uninstall/$Name" deleteRegKey HKCU "Software/$Name" delete [] "$INSTDIR/stack.exe" delete [] "$INSTDIR/uninstall-stack.exe" section "un.Install location on %PATH%" [ Description "Remove $INSTDIR from the user %PATH%. There may be other programs installed in that location." ] $ do setEnvVarRemove HKCU "PATH" "$INSTDIR" section "un.Set %STACK_ROOT% to recommended default" [ Description "Remove setting of %STACK_ROOT% to C:\\sr." ] $ do deleteEnvVar HKCU "STACK_ROOT" section "un.Compilers installed by Stack" [ Unselected , Description "Remove %LOCALAPPDATA%/Programs/stack, which contains compilers that have been installed by Stack." ] $ do rmdir [Recursive] "$LOCALAPPDATA/Programs/stack" section "un.Stack snapshots and configuration" [ Unselected , Description "Remove %APPDATA%/stack, which contains the user-defined global stack.yaml and the snapshot/compilation cache." ] $ do rmdir [Recursive] "$APPDATA/stack"
7b2eb85c591499b611c978de62c5e90fb290b2bc762dd9d25f7f9e3207cf6500
paurkedal/episql
error.mli
Copyright ( C ) 2021 - -2023 Petter A. Urkedal < > * * This library is free software ; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version , with the LGPL-3.0 Linking Exception . * * This library is distributed in the hope that it will be useful , but WITHOUT * ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library . If not , see * < / > and < > , respectively . * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version, with the LGPL-3.0 Linking Exception. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library. If not, see * </> and <>, respectively. *) type not_present = { operation: string; table: string; } [@@deriving show] type conflict = { conflict_type: [`Insert_insert | `Update_insert | `Update_delete]; conflict_table: string; } [@@deriving show] type t = [Caqti_error.t | `Conflict of conflict] [@@deriving show] val or_fail : ('a, [< t]) result -> 'a Lwt.t exception Not_present of not_present exception Conflict of conflict
null
https://raw.githubusercontent.com/paurkedal/episql/bd1cf8399af9073d39c21437d963ea4d498f2816/caqti-persist/lib/error.mli
ocaml
Copyright ( C ) 2021 - -2023 Petter A. Urkedal < > * * This library is free software ; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version , with the LGPL-3.0 Linking Exception . * * This library is distributed in the hope that it will be useful , but WITHOUT * ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library . If not , see * < / > and < > , respectively . * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version, with the LGPL-3.0 Linking Exception. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library. If not, see * </> and <>, respectively. *) type not_present = { operation: string; table: string; } [@@deriving show] type conflict = { conflict_type: [`Insert_insert | `Update_insert | `Update_delete]; conflict_table: string; } [@@deriving show] type t = [Caqti_error.t | `Conflict of conflict] [@@deriving show] val or_fail : ('a, [< t]) result -> 'a Lwt.t exception Not_present of not_present exception Conflict of conflict
49112389d93646e1453c119712ec94176e71f6d77c8dbf7e17d3d870f9bdc2fb
haroldcarr/learn-haskell-coq-ml-etc
HMF.hs
{-# OPTIONS_GHC -Wno-unused-do-bind #-} # OPTIONS_GHC -fno - warn - missing - signatures # # OPTIONS_GHC -Wno - missing - pattern - synonym - signatures # # LANGUAGE DeriveFunctor # # LANGUAGE ExistentialQuantification # {-# LANGUAGE GADTs #-} # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE TypeOperators #-} module HMF where import Common ------------------------------------------------------------------------------ import Control.Applicative import Control.Monad.Free import Data.Attoparsec.ByteString.Char8 import Data.ByteString hiding (foldr1, getLine) import Data.Functor data Ex a = forall i. Wrap (a i) -- | runtime representation of type parameter data Ty a where ListIntTy :: Ty [Int] UnitTy :: Ty () | Pairs up two type constructors . -- Ensures their parameters are equal. Pattern match on . data (a :*: b) i = a i :&: b i -- | Sig(ma) type (i.e., dependent pair) type of second component depends on value of first type Sig a b = Ex (a :*: b) pattern Sig x y = Wrap (x :&: y) data HmfCmdF a = FlushPage [Int] a | PageMisses ([Int] -> a) deriving Functor type HmfCmd = Free HmfCmdF fp :: [Int] -> HmfCmd () fp is = liftF $ FlushPage is () pm :: HmfCmd [Int] pm = liftF $ PageMisses id parseList :: Parser [Int] parseList = do char '['; t <- decimal `sepBy` char ','; char ']'; return t parseFP :: Parser (HmfCmd ()) parseFP = skipSpace >> string "flushPage" *> skipSpace *> fmap fp parseList parsePM :: Parser (HmfCmd [Int]) parsePM = skipSpace >> string "pageMisses" $> pm parseFPPM :: Parser (Sig Ty HmfCmd) parseFPPM = fmap (Sig UnitTy) parseFP <|> fmap (Sig ListIntTy) parsePM parseSeparator :: Parser Char parseSeparator = skipSpace >> char ';' parseHmfParser :: Parser (Sig Ty HmfCmd) parseHmfParser = fmap (foldr1 combine) $ parseFPPM `sepBy1` parseSeparator where combine (Sig _ val) (Sig ty acc) = Sig ty (val >> acc) combine _ _ = error "parseHmf" eatTheRest :: Parser () eatTheRest = skipWhile stuff >> endOfInput where stuff w = isSpace w || w == ';' parseHmf :: ByteString -> Result (Sig Ty HmfCmd) parseHmf = parse (parseHmfParser <* eatTheRest) ------------------------------------------------------------------------------ ioHmf :: ByteString -> Either String (IO ()) ioHmf s = do (_u, r) <- parseFully (parseHmf s) let a = ioHmfAux r return a ioHmfAux :: Sig Ty HmfCmd -> IO () ioHmfAux (Sig _ f) = do doHmf f; return () ioHmfAux _ = return () doHmf :: HmfCmd a -> IO a doHmf = foldFree $ \case FlushPage ps next -> do print ps return next PageMisses next -> do i <- read <$> getLine print [i] return $ next [i] {- :set -XOverloadedStrings let x = ioHmf "pageMisses" let x = ioHmf "flushPage [1,2]" let x = ioHmf "flushPage [1,2];pageMisses;" case x of (Right a) -> a -}
null
https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/topic/fix-free/2016-01-benjamin-hodgson-parsing-to-free-monads/HMF.hs
haskell
# OPTIONS_GHC -Wno-unused-do-bind # # LANGUAGE GADTs # # LANGUAGE OverloadedStrings # # LANGUAGE PatternSynonyms # # LANGUAGE TypeOperators # ---------------------------------------------------------------------------- | runtime representation of type parameter Ensures their parameters are equal. | Sig(ma) type (i.e., dependent pair) ---------------------------------------------------------------------------- :set -XOverloadedStrings let x = ioHmf "pageMisses" let x = ioHmf "flushPage [1,2]" let x = ioHmf "flushPage [1,2];pageMisses;" case x of (Right a) -> a
# OPTIONS_GHC -fno - warn - missing - signatures # # OPTIONS_GHC -Wno - missing - pattern - synonym - signatures # # LANGUAGE DeriveFunctor # # LANGUAGE ExistentialQuantification # # LANGUAGE LambdaCase # module HMF where import Common import Control.Applicative import Control.Monad.Free import Data.Attoparsec.ByteString.Char8 import Data.ByteString hiding (foldr1, getLine) import Data.Functor data Ex a = forall i. Wrap (a i) data Ty a where ListIntTy :: Ty [Int] UnitTy :: Ty () | Pairs up two type constructors . Pattern match on . data (a :*: b) i = a i :&: b i type of second component depends on value of first type Sig a b = Ex (a :*: b) pattern Sig x y = Wrap (x :&: y) data HmfCmdF a = FlushPage [Int] a | PageMisses ([Int] -> a) deriving Functor type HmfCmd = Free HmfCmdF fp :: [Int] -> HmfCmd () fp is = liftF $ FlushPage is () pm :: HmfCmd [Int] pm = liftF $ PageMisses id parseList :: Parser [Int] parseList = do char '['; t <- decimal `sepBy` char ','; char ']'; return t parseFP :: Parser (HmfCmd ()) parseFP = skipSpace >> string "flushPage" *> skipSpace *> fmap fp parseList parsePM :: Parser (HmfCmd [Int]) parsePM = skipSpace >> string "pageMisses" $> pm parseFPPM :: Parser (Sig Ty HmfCmd) parseFPPM = fmap (Sig UnitTy) parseFP <|> fmap (Sig ListIntTy) parsePM parseSeparator :: Parser Char parseSeparator = skipSpace >> char ';' parseHmfParser :: Parser (Sig Ty HmfCmd) parseHmfParser = fmap (foldr1 combine) $ parseFPPM `sepBy1` parseSeparator where combine (Sig _ val) (Sig ty acc) = Sig ty (val >> acc) combine _ _ = error "parseHmf" eatTheRest :: Parser () eatTheRest = skipWhile stuff >> endOfInput where stuff w = isSpace w || w == ';' parseHmf :: ByteString -> Result (Sig Ty HmfCmd) parseHmf = parse (parseHmfParser <* eatTheRest) ioHmf :: ByteString -> Either String (IO ()) ioHmf s = do (_u, r) <- parseFully (parseHmf s) let a = ioHmfAux r return a ioHmfAux :: Sig Ty HmfCmd -> IO () ioHmfAux (Sig _ f) = do doHmf f; return () ioHmfAux _ = return () doHmf :: HmfCmd a -> IO a doHmf = foldFree $ \case FlushPage ps next -> do print ps return next PageMisses next -> do i <- read <$> getLine print [i] return $ next [i]
21c244eedfb637656f4783080a0a36e563e430842cb7065e2a17e57d0441a1ce
cdepillabout/servant-checked-exceptions
EnvelopeT.hs
{-# LANGUAGE ConstraintKinds #-} # LANGUAGE DataKinds # # LANGUAGE EmptyCase # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} # LANGUAGE InstanceSigs # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PolyKinds # {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # | This example is very similar to @./Server.hs@ , but it is making use of -- 'EnvelopeT' instead of just 'Envelope'. module Main where import Control.Monad.IO.Class (MonadIO(liftIO)) import Data.Char (toLower) import Data.Proxy (Proxy(Proxy)) import Network.Wai (Application) import Network.Wai.Handler.Warp (run) import Servant (Handler, (:<|>)((:<|>)), ServerT, serve) import Servant.Checked.Exceptions ( Envelope , EnvelopeT , IsMember , pureErrEnvelope , pureSuccEnvelope , relaxEnvT , runEnvelopeT , throwErrEnvT ) import Api ( Api , BadSearchTermErr(BadSearchTermErr) , IncorrectCapitalization(IncorrectCapitalization) , SearchQuery(SearchQuery) , SearchResponse , port ) | This is our server root for the ' ServerT ' for ' Api ' . We only have two handlers , ' postStrictSearch ' and ' postLaxSearch ' . serverRoot :: ServerT Api Handler serverRoot = postStrictSearch :<|> postLaxSearch :<|> postNoErrSearch -- | This is the handler for 'Api.ApiStrictSearch'. postStrictSearch :: SearchQuery -> Handler (Envelope '[BadSearchTermErr, IncorrectCapitalization] SearchResponse) postStrictSearch query = runEnvelopeT $ do res <- checkQueryInDb query relaxEnvT $ doubleCheckCapitalization query doubleCheckCapitalizationGeneral query pure res | Check that the input ' ' is in the DB . ( The DB is just a list -- of greetings.) -- If the input ' ' is in the DB , return the string @"greeting"@. -- Otherwise, throw an envelope error 'BadSearchTermErr'. -- -- Note that this function says that it might also return an -- 'IncorrectCapitalization' error, but it doesn't actually. This is just for -- demonstration. -- Also note that our underlying here is ' Handler ' . checkQueryInDb :: SearchQuery -> EnvelopeT '[BadSearchTermErr, IncorrectCapitalization] Handler SearchResponse checkQueryInDb (SearchQuery query) = do liftIO $ putStrLn "querying DB..." let lowerQuery = fmap toLower query case lowerQuery `elem` ["hello", "goodbye", "goodnight"] of True -> pure "greeting" False -> throwErrEnvT BadSearchTermErr | Check the first letter of ' ' to make sure that it is lowercase . -- -- If it is not lowercase, throw 'IncorrectCapitalization'. -- -- Note that 'relaxEnvT' needs to be called on the result of this to use it in -- do notation with the above 'checkQueryInDb'. This is because the result of -- this is technically a different monad than the result of 'checkQueryInDb', -- because the error types are different. -- -- Also note that since we only use 'MonadIO' for this, our underlying monad is -- polymorphic. We don't specialize it to 'Handler'. doubleCheckCapitalization :: MonadIO m => SearchQuery -> EnvelopeT '[IncorrectCapitalization] m () doubleCheckCapitalization (SearchQuery []) = liftIO $ putStrLn "search query empty" doubleCheckCapitalization (SearchQuery (q:query)) = if toLower q == q then pure () else throwErrEnvT IncorrectCapitalization -- | This is just like 'doubleCheckCapitalization' above, but we use the -- 'IsMember' constraint to make this function more general. In ' postStrictSearch ' , you can see that we do n't have to call ' relaxEnvT ' when -- using this function. doubleCheckCapitalizationGeneral :: IsMember IncorrectCapitalization es => SearchQuery -> EnvelopeT es Handler () doubleCheckCapitalizationGeneral _ = throwErrEnvT IncorrectCapitalization -- | This doesn't do anything interesting. -- See ' postLaxSearch ' in @./Server.hs@ for an example using ' Envelope ' . postLaxSearch :: SearchQuery -> Handler (Envelope '[BadSearchTermErr] SearchResponse) postLaxSearch _ = pureSuccEnvelope "good" -- | This doesn't do anything interesting. -- See ' postNoErrSearch ' in @./Server.hs@ for an example using ' Envelope ' . postNoErrSearch :: SearchQuery -> Handler (Envelope '[] SearchResponse) postNoErrSearch (SearchQuery _) = pureSuccEnvelope "good" -- | Create a WAI 'Application'. app :: Application app = serve (Proxy :: Proxy Api) serverRoot -- | Run the WAI 'Application' using 'run' on the port defined by 'port'. main :: IO () main = run port app
null
https://raw.githubusercontent.com/cdepillabout/servant-checked-exceptions/8ec4e831e45e51f3404790496f036a42c7349afa/servant-checked-exceptions/example/EnvelopeT.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE GADTs # # LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # 'EnvelopeT' instead of just 'Envelope'. | This is the handler for 'Api.ApiStrictSearch'. of greetings.) Otherwise, throw an envelope error 'BadSearchTermErr'. Note that this function says that it might also return an 'IncorrectCapitalization' error, but it doesn't actually. This is just for demonstration. If it is not lowercase, throw 'IncorrectCapitalization'. Note that 'relaxEnvT' needs to be called on the result of this to use it in do notation with the above 'checkQueryInDb'. This is because the result of this is technically a different monad than the result of 'checkQueryInDb', because the error types are different. Also note that since we only use 'MonadIO' for this, our underlying monad is polymorphic. We don't specialize it to 'Handler'. | This is just like 'doubleCheckCapitalization' above, but we use the 'IsMember' constraint to make this function more general. In using this function. | This doesn't do anything interesting. | This doesn't do anything interesting. | Create a WAI 'Application'. | Run the WAI 'Application' using 'run' on the port defined by 'port'.
# LANGUAGE DataKinds # # LANGUAGE EmptyCase # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE InstanceSigs # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PolyKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # | This example is very similar to @./Server.hs@ , but it is making use of module Main where import Control.Monad.IO.Class (MonadIO(liftIO)) import Data.Char (toLower) import Data.Proxy (Proxy(Proxy)) import Network.Wai (Application) import Network.Wai.Handler.Warp (run) import Servant (Handler, (:<|>)((:<|>)), ServerT, serve) import Servant.Checked.Exceptions ( Envelope , EnvelopeT , IsMember , pureErrEnvelope , pureSuccEnvelope , relaxEnvT , runEnvelopeT , throwErrEnvT ) import Api ( Api , BadSearchTermErr(BadSearchTermErr) , IncorrectCapitalization(IncorrectCapitalization) , SearchQuery(SearchQuery) , SearchResponse , port ) | This is our server root for the ' ServerT ' for ' Api ' . We only have two handlers , ' postStrictSearch ' and ' postLaxSearch ' . serverRoot :: ServerT Api Handler serverRoot = postStrictSearch :<|> postLaxSearch :<|> postNoErrSearch postStrictSearch :: SearchQuery -> Handler (Envelope '[BadSearchTermErr, IncorrectCapitalization] SearchResponse) postStrictSearch query = runEnvelopeT $ do res <- checkQueryInDb query relaxEnvT $ doubleCheckCapitalization query doubleCheckCapitalizationGeneral query pure res | Check that the input ' ' is in the DB . ( The DB is just a list If the input ' ' is in the DB , return the string @"greeting"@. Also note that our underlying here is ' Handler ' . checkQueryInDb :: SearchQuery -> EnvelopeT '[BadSearchTermErr, IncorrectCapitalization] Handler SearchResponse checkQueryInDb (SearchQuery query) = do liftIO $ putStrLn "querying DB..." let lowerQuery = fmap toLower query case lowerQuery `elem` ["hello", "goodbye", "goodnight"] of True -> pure "greeting" False -> throwErrEnvT BadSearchTermErr | Check the first letter of ' ' to make sure that it is lowercase . doubleCheckCapitalization :: MonadIO m => SearchQuery -> EnvelopeT '[IncorrectCapitalization] m () doubleCheckCapitalization (SearchQuery []) = liftIO $ putStrLn "search query empty" doubleCheckCapitalization (SearchQuery (q:query)) = if toLower q == q then pure () else throwErrEnvT IncorrectCapitalization ' postStrictSearch ' , you can see that we do n't have to call ' relaxEnvT ' when doubleCheckCapitalizationGeneral :: IsMember IncorrectCapitalization es => SearchQuery -> EnvelopeT es Handler () doubleCheckCapitalizationGeneral _ = throwErrEnvT IncorrectCapitalization See ' postLaxSearch ' in @./Server.hs@ for an example using ' Envelope ' . postLaxSearch :: SearchQuery -> Handler (Envelope '[BadSearchTermErr] SearchResponse) postLaxSearch _ = pureSuccEnvelope "good" See ' postNoErrSearch ' in @./Server.hs@ for an example using ' Envelope ' . postNoErrSearch :: SearchQuery -> Handler (Envelope '[] SearchResponse) postNoErrSearch (SearchQuery _) = pureSuccEnvelope "good" app :: Application app = serve (Proxy :: Proxy Api) serverRoot main :: IO () main = run port app
0b549d31fcf9cfe12acbc549217e7168e5dbcaa085219a2f714e267f7b559a60
rixed/ramen
raql_value.ml
(* Manually written impostor to raql_value, converting from/to Ramen's internal * value types. *) open Stdint open DessserOCamlBackEndHelpers module Wire = Raql_value_wire.DessserGen (* Stdint types are implemented as custom blocks, therefore are slower than * ints. But we do not care as we merely represents code here, we do not run * the operators. * For NULL values we are doomed to loose the type information, at least for * constructed types, unless we always keep the type alongside the value, * which we do not want to (we want to erase types in serialization etc). So * if we are given only a NULL tuple there is no way to know its type. * Tough life. *) Refined from Raql_value because of our IP type . FIXME . type t = | VNull | VUnit | VFloat of float | VString of string | VBool of bool | VChar of char | VU8 of uint8 | VU16 of uint16 | VU24 of uint24 | VU32 of uint32 | VU40 of uint40 | VU48 of uint48 | VU56 of uint56 | VU64 of uint64 | VU128 of uint128 | VI8 of int8 | VI16 of int16 | VI24 of int24 | VI32 of int32 | VI40 of int40 | VI48 of int48 | VI56 of int56 | VI64 of int64 | VI128 of int128 | VEth of uint48 | VIpv4 of uint32 | VIpv6 of uint128 | VIp of RamenIp.t | VCidrv4 of RamenIpv4.Cidr.t | VCidrv6 of RamenIpv6.Cidr.t | VCidr of RamenIp.Cidr.t | VTup of t array | VVec of t array (* All values must have the same type *) | VArr of t array (* All values must have the same type *) (* Note: The labels are only needed for pretty printing the values. *) | VRec of (string * t) array | VMap of (t * t) array [@@ppp PPP_OCaml] (* Temporarily, convert a dessser raql_value representation into a value: *) let rec of_wire = function | Wire.VNull -> (VNull : t) | VUnit -> VUnit | VFloat x -> VFloat x | VString x -> VString x | VBool x -> VBool x | VChar x -> VChar x | VU8 x -> VU8 x | VU16 x -> VU16 x | VU24 x -> VU24 x | VU32 x -> VU32 x | VU40 x -> VU40 x | VU48 x -> VU48 x | VU56 x -> VU56 x | VU64 x -> VU64 x | VU128 x -> VU128 x | VI8 x -> VI8 x | VI16 x -> VI16 x | VI24 x -> VI24 x | VI32 x -> VI32 x | VI40 x -> VI40 x | VI48 x -> VI48 x | VI56 x -> VI56 x | VI64 x -> VI64 x | VI128 x -> VI128 x | VEth x -> VEth x | VIpv4 x -> VIpv4 x | VIpv6 x -> VIpv6 x | VIp (Ip_v4 x) -> VIp (RamenIp.V4 x) | VIp (Ip_v6 x) -> VIp (RamenIp.V6 x) | VCidrv4 { cidr4_ip ; cidr4_mask } -> VCidrv4 (cidr4_ip, cidr4_mask) | VCidrv6 { ip ; mask } -> VCidrv6 (ip, mask) | VCidr (V4 { cidr4_ip ; cidr4_mask }) -> VCidr (V4 (cidr4_ip, cidr4_mask)) | VCidr (V6 { ip ; mask }) -> VCidr (V6 (ip, mask)) | VTup x -> VTup (Array.map of_wire x) | VVec x -> VVec (Array.map of_wire x) | VArr x -> VArr (Array.map of_wire x) | VRec x -> VRec (Array.map (fun (n, v) -> n, of_wire v) x) | VMap x -> VMap (Array.map (fun (k, v) -> of_wire k, of_wire v) x) let rec to_wire = function | VNull -> Wire.VNull | VUnit -> VUnit | VFloat x -> VFloat x | VString x -> VString x | VBool x -> VBool x | VChar x -> VChar x | VU8 x -> VU8 x | VU16 x -> VU16 x | VU24 x -> VU24 x | VU32 x -> VU32 x | VU40 x -> VU40 x | VU48 x -> VU48 x | VU56 x -> VU56 x | VU64 x -> VU64 x | VU128 x -> VU128 x | VI8 x -> VI8 x | VI16 x -> VI16 x | VI24 x -> VI24 x | VI32 x -> VI32 x | VI40 x -> VI40 x | VI48 x -> VI48 x | VI56 x -> VI56 x | VI64 x -> VI64 x | VI128 x -> VI128 x | VEth x -> VEth x | VIpv4 x -> VIpv4 x | VIpv6 x -> VIpv6 x | VIp (RamenIp.V4 x) -> VIp (Ip_v4 x) | VIp (RamenIp.V6 x) -> VIp (Ip_v6 x) | VCidrv4 (cidr4_ip, cidr4_mask) -> VCidrv4 { cidr4_ip ; cidr4_mask } | VCidrv6 (ip, mask) -> VCidrv6 { ip ; mask } | VCidr (V4 (cidr4_ip, cidr4_mask)) -> VCidr (V4 { cidr4_ip ; cidr4_mask }) | VCidr (V6 (ip, mask)) -> VCidr (V6 { ip ; mask }) | VTup x -> VTup (Array.map to_wire x) | VVec x -> VVec (Array.map to_wire x) | VArr x -> VArr (Array.map to_wire x) | VRec x -> VRec (Array.map (fun (n, v) -> n, to_wire v) x) | VMap x -> VMap (Array.map (fun (k, v) -> to_wire k, to_wire v) x) module DessserGen = struct type out_t = t type t = out_t let to_row_binary_with_mask m t p = Wire.to_row_binary_with_mask m (to_wire t) p let to_row_binary t p = Wire.to_row_binary (to_wire t) p let sersize_of_row_binary_with_mask m t = Wire.sersize_of_row_binary_with_mask m (to_wire t) let sersize_of_row_binary t = Wire.sersize_of_row_binary (to_wire t) let of_row_binary p = let t, p = Wire.of_row_binary p in of_wire t, p end
null
https://raw.githubusercontent.com/rixed/ramen/7a166362f7a290d6852b2db948cc949d7bcb157c/src/raql_value.ml
ocaml
Manually written impostor to raql_value, converting from/to Ramen's internal * value types. Stdint types are implemented as custom blocks, therefore are slower than * ints. But we do not care as we merely represents code here, we do not run * the operators. * For NULL values we are doomed to loose the type information, at least for * constructed types, unless we always keep the type alongside the value, * which we do not want to (we want to erase types in serialization etc). So * if we are given only a NULL tuple there is no way to know its type. * Tough life. All values must have the same type All values must have the same type Note: The labels are only needed for pretty printing the values. Temporarily, convert a dessser raql_value representation into a value:
open Stdint open DessserOCamlBackEndHelpers module Wire = Raql_value_wire.DessserGen Refined from Raql_value because of our IP type . FIXME . type t = | VNull | VUnit | VFloat of float | VString of string | VBool of bool | VChar of char | VU8 of uint8 | VU16 of uint16 | VU24 of uint24 | VU32 of uint32 | VU40 of uint40 | VU48 of uint48 | VU56 of uint56 | VU64 of uint64 | VU128 of uint128 | VI8 of int8 | VI16 of int16 | VI24 of int24 | VI32 of int32 | VI40 of int40 | VI48 of int48 | VI56 of int56 | VI64 of int64 | VI128 of int128 | VEth of uint48 | VIpv4 of uint32 | VIpv6 of uint128 | VIp of RamenIp.t | VCidrv4 of RamenIpv4.Cidr.t | VCidrv6 of RamenIpv6.Cidr.t | VCidr of RamenIp.Cidr.t | VTup of t array | VRec of (string * t) array | VMap of (t * t) array [@@ppp PPP_OCaml] let rec of_wire = function | Wire.VNull -> (VNull : t) | VUnit -> VUnit | VFloat x -> VFloat x | VString x -> VString x | VBool x -> VBool x | VChar x -> VChar x | VU8 x -> VU8 x | VU16 x -> VU16 x | VU24 x -> VU24 x | VU32 x -> VU32 x | VU40 x -> VU40 x | VU48 x -> VU48 x | VU56 x -> VU56 x | VU64 x -> VU64 x | VU128 x -> VU128 x | VI8 x -> VI8 x | VI16 x -> VI16 x | VI24 x -> VI24 x | VI32 x -> VI32 x | VI40 x -> VI40 x | VI48 x -> VI48 x | VI56 x -> VI56 x | VI64 x -> VI64 x | VI128 x -> VI128 x | VEth x -> VEth x | VIpv4 x -> VIpv4 x | VIpv6 x -> VIpv6 x | VIp (Ip_v4 x) -> VIp (RamenIp.V4 x) | VIp (Ip_v6 x) -> VIp (RamenIp.V6 x) | VCidrv4 { cidr4_ip ; cidr4_mask } -> VCidrv4 (cidr4_ip, cidr4_mask) | VCidrv6 { ip ; mask } -> VCidrv6 (ip, mask) | VCidr (V4 { cidr4_ip ; cidr4_mask }) -> VCidr (V4 (cidr4_ip, cidr4_mask)) | VCidr (V6 { ip ; mask }) -> VCidr (V6 (ip, mask)) | VTup x -> VTup (Array.map of_wire x) | VVec x -> VVec (Array.map of_wire x) | VArr x -> VArr (Array.map of_wire x) | VRec x -> VRec (Array.map (fun (n, v) -> n, of_wire v) x) | VMap x -> VMap (Array.map (fun (k, v) -> of_wire k, of_wire v) x) let rec to_wire = function | VNull -> Wire.VNull | VUnit -> VUnit | VFloat x -> VFloat x | VString x -> VString x | VBool x -> VBool x | VChar x -> VChar x | VU8 x -> VU8 x | VU16 x -> VU16 x | VU24 x -> VU24 x | VU32 x -> VU32 x | VU40 x -> VU40 x | VU48 x -> VU48 x | VU56 x -> VU56 x | VU64 x -> VU64 x | VU128 x -> VU128 x | VI8 x -> VI8 x | VI16 x -> VI16 x | VI24 x -> VI24 x | VI32 x -> VI32 x | VI40 x -> VI40 x | VI48 x -> VI48 x | VI56 x -> VI56 x | VI64 x -> VI64 x | VI128 x -> VI128 x | VEth x -> VEth x | VIpv4 x -> VIpv4 x | VIpv6 x -> VIpv6 x | VIp (RamenIp.V4 x) -> VIp (Ip_v4 x) | VIp (RamenIp.V6 x) -> VIp (Ip_v6 x) | VCidrv4 (cidr4_ip, cidr4_mask) -> VCidrv4 { cidr4_ip ; cidr4_mask } | VCidrv6 (ip, mask) -> VCidrv6 { ip ; mask } | VCidr (V4 (cidr4_ip, cidr4_mask)) -> VCidr (V4 { cidr4_ip ; cidr4_mask }) | VCidr (V6 (ip, mask)) -> VCidr (V6 { ip ; mask }) | VTup x -> VTup (Array.map to_wire x) | VVec x -> VVec (Array.map to_wire x) | VArr x -> VArr (Array.map to_wire x) | VRec x -> VRec (Array.map (fun (n, v) -> n, to_wire v) x) | VMap x -> VMap (Array.map (fun (k, v) -> to_wire k, to_wire v) x) module DessserGen = struct type out_t = t type t = out_t let to_row_binary_with_mask m t p = Wire.to_row_binary_with_mask m (to_wire t) p let to_row_binary t p = Wire.to_row_binary (to_wire t) p let sersize_of_row_binary_with_mask m t = Wire.sersize_of_row_binary_with_mask m (to_wire t) let sersize_of_row_binary t = Wire.sersize_of_row_binary (to_wire t) let of_row_binary p = let t, p = Wire.of_row_binary p in of_wire t, p end
512fb807a8b3ab6d9fc9048dabe3fac916be7ec7de90e87ea0bc0fcf094b9f66
larcenists/larceny
16seq3.scm
(bits 16) (text (begin (nop) (nop) (seq (nop) (nop) z! (nop) (inv z!) (nop)) (nop))) 00000000 90 nop 00000001 90 nop 00000002 90 nop 00000003 90 nop 00000004 7504 jnz 0xa 00000006 90 nop 00000007 7401 jz 0xa 00000009 90 nop 0000000A 90 nop
null
https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/src/Lib/Sassy/tests/prims16/16seq3.scm
scheme
(bits 16) (text (begin (nop) (nop) (seq (nop) (nop) z! (nop) (inv z!) (nop)) (nop))) 00000000 90 nop 00000001 90 nop 00000002 90 nop 00000003 90 nop 00000004 7504 jnz 0xa 00000006 90 nop 00000007 7401 jz 0xa 00000009 90 nop 0000000A 90 nop
20ed435c890b1221636aa2d2959ca6ac6b74dbe02298367b750f72b0db8f29cb
whamtet/ctmx
config.cljc
(ns ctmx.config) (def default-param-method :simple) (defn set-param-method! [method] {:pre [(contains? #{:simple :path} method)]} #?(:clj (alter-var-root #'default-param-method (constantly method)) :cljs (set! default-param-method method))) (def render-style? true) (def render-hs? true) (def render-class? true) (def render-vals? true) (def render-commands? true) (defn set-render-style! [s] #?(:clj (alter-var-root #'render-style? (constantly s)) :cljs (set! render-style? s))) (defn set-render-hs! [s] #?(:clj (alter-var-root #'render-hs? (constantly s)) :cljs (set! render-hs? s))) (defn set-render-class! [s] #?(:clj (alter-var-root #'render-class? (constantly s)) :cljs (set! render-class? s))) (defn set-render-vals! [s] #?(:clj (alter-var-root #'render-vals? (constantly s)) :cljs (set! render-vals? s))) (defn set-render-commands! [s] #?(:clj (alter-var-root #'render-commands? (constantly s)) :cljs (set! render-commands? s)))
null
https://raw.githubusercontent.com/whamtet/ctmx/9ea5677dfe5196f8fbff88d05ea6b020169ccdc8/src/ctmx/config.cljc
clojure
(ns ctmx.config) (def default-param-method :simple) (defn set-param-method! [method] {:pre [(contains? #{:simple :path} method)]} #?(:clj (alter-var-root #'default-param-method (constantly method)) :cljs (set! default-param-method method))) (def render-style? true) (def render-hs? true) (def render-class? true) (def render-vals? true) (def render-commands? true) (defn set-render-style! [s] #?(:clj (alter-var-root #'render-style? (constantly s)) :cljs (set! render-style? s))) (defn set-render-hs! [s] #?(:clj (alter-var-root #'render-hs? (constantly s)) :cljs (set! render-hs? s))) (defn set-render-class! [s] #?(:clj (alter-var-root #'render-class? (constantly s)) :cljs (set! render-class? s))) (defn set-render-vals! [s] #?(:clj (alter-var-root #'render-vals? (constantly s)) :cljs (set! render-vals? s))) (defn set-render-commands! [s] #?(:clj (alter-var-root #'render-commands? (constantly s)) :cljs (set! render-commands? s)))
b52f213555a2ff92d3eb83a97868db2cee486deb85fd9c7a7da3ea17e252b4f7
lowasser/TrieMap
Traversable.hs
# LANGUAGE CPP , BangPatterns , ViewPatterns , FlexibleInstances # module Data.TrieMap.RadixTrie.Traversable () where import Data.TrieMap.RadixTrie.Base import Data.Functor.Immoral import Prelude hiding (foldl, foldr) #define V(f) f (VVector) (k) #define U(f) f (PVector) (Word) #define EDGE(args) (!(eView -> Edge args)) instance TrieKey k => Functor (TrieMap (VVector k)) where fmap f (Radix m) = Radix (fmap (fmap f) m) instance Functor (TrieMap (PVector Word)) where fmap f (WRadix m) = WRadix (fmap (fmap f) m) instance TrieKey k => Foldable (TrieMap (VVector k)) where foldMap f (Radix m) = foldMap (foldMap f) m foldr f z (Radix m) = foldl (foldr f) z m foldl f z (Radix m) = foldl (foldl f) z m instance Foldable (TrieMap (PVector Word)) where foldMap f (WRadix m) = foldMap (foldMap f) m foldr f z (WRadix m) = foldl (foldr f) z m foldl f z (WRadix m) = foldl (foldl f) z m instance TrieKey k => Traversable (TrieMap (VVector k)) where traverse f (Radix m) = castMap (traverse (traverse f) m) instance Traversable (TrieMap (PVector Word)) where traverse f (WRadix m) = castMap (traverse (traverse f) m) instance Label v k => Functor (Edge v k) where # SPECIALIZE instance k = > Functor ( ) ) # # SPECIALIZE instance Functor ( U(Edge ) ) # fmap f = map where map EDGE(sz ks v ts) = edge' sz ks (f <$> v) (map <$> ts) instance Label v k => Foldable (Edge v k) where # SPECIALIZE instance k = > Foldable ( ) ) # # SPECIALIZE instance Foldable ( U(Edge ) ) # foldMap f = fold where foldBranch = foldMap fold fold e = case eView e of Edge _ _ Nothing ts -> foldBranch ts Edge _ _ (Just a) ts -> f a `mappend` foldBranch ts foldr f = flip fold where foldBranch = foldr fold fold e z = case eView e of Edge _ _ Nothing ts -> foldBranch z ts Edge _ _ (Just a) ts -> a `f` foldBranch z ts foldl f = fold where foldBranch = foldl fold fold z e = case eView e of Edge _ _ Nothing ts -> foldBranch z ts Edge _ _ (Just a) ts -> foldBranch (z `f` a) ts instance Label v k => Traversable (Edge v k) where # SPECIALIZE instance k = > ( ) ) # # SPECIALIZE instance ( U(Edge ) ) # traverse f = trav where travBranch = traverse trav trav e = case eView e of Edge sz ks Nothing ts -> edge' sz ks Nothing <$> travBranch ts Edge sz ks (Just a) ts -> edge' sz ks . Just <$> f a <*> travBranch ts
null
https://raw.githubusercontent.com/lowasser/TrieMap/1ab52b8d83469974a629f2aa577a85de3f9e867a/Data/TrieMap/RadixTrie/Traversable.hs
haskell
# LANGUAGE CPP , BangPatterns , ViewPatterns , FlexibleInstances # module Data.TrieMap.RadixTrie.Traversable () where import Data.TrieMap.RadixTrie.Base import Data.Functor.Immoral import Prelude hiding (foldl, foldr) #define V(f) f (VVector) (k) #define U(f) f (PVector) (Word) #define EDGE(args) (!(eView -> Edge args)) instance TrieKey k => Functor (TrieMap (VVector k)) where fmap f (Radix m) = Radix (fmap (fmap f) m) instance Functor (TrieMap (PVector Word)) where fmap f (WRadix m) = WRadix (fmap (fmap f) m) instance TrieKey k => Foldable (TrieMap (VVector k)) where foldMap f (Radix m) = foldMap (foldMap f) m foldr f z (Radix m) = foldl (foldr f) z m foldl f z (Radix m) = foldl (foldl f) z m instance Foldable (TrieMap (PVector Word)) where foldMap f (WRadix m) = foldMap (foldMap f) m foldr f z (WRadix m) = foldl (foldr f) z m foldl f z (WRadix m) = foldl (foldl f) z m instance TrieKey k => Traversable (TrieMap (VVector k)) where traverse f (Radix m) = castMap (traverse (traverse f) m) instance Traversable (TrieMap (PVector Word)) where traverse f (WRadix m) = castMap (traverse (traverse f) m) instance Label v k => Functor (Edge v k) where # SPECIALIZE instance k = > Functor ( ) ) # # SPECIALIZE instance Functor ( U(Edge ) ) # fmap f = map where map EDGE(sz ks v ts) = edge' sz ks (f <$> v) (map <$> ts) instance Label v k => Foldable (Edge v k) where # SPECIALIZE instance k = > Foldable ( ) ) # # SPECIALIZE instance Foldable ( U(Edge ) ) # foldMap f = fold where foldBranch = foldMap fold fold e = case eView e of Edge _ _ Nothing ts -> foldBranch ts Edge _ _ (Just a) ts -> f a `mappend` foldBranch ts foldr f = flip fold where foldBranch = foldr fold fold e z = case eView e of Edge _ _ Nothing ts -> foldBranch z ts Edge _ _ (Just a) ts -> a `f` foldBranch z ts foldl f = fold where foldBranch = foldl fold fold z e = case eView e of Edge _ _ Nothing ts -> foldBranch z ts Edge _ _ (Just a) ts -> foldBranch (z `f` a) ts instance Label v k => Traversable (Edge v k) where # SPECIALIZE instance k = > ( ) ) # # SPECIALIZE instance ( U(Edge ) ) # traverse f = trav where travBranch = traverse trav trav e = case eView e of Edge sz ks Nothing ts -> edge' sz ks Nothing <$> travBranch ts Edge sz ks (Just a) ts -> edge' sz ks . Just <$> f a <*> travBranch ts
7f4c58f11004a790d559f5ad655d4e3b55bd308c1d37b06f3ecac1073b61d39d
simonmichael/hledger
unittest.hs
Run the hledger package 's unit tests using the tasty test runner ( by running the test command limited to Hledger . Cli tests ) . Run the hledger package's unit tests using the tasty test runner (by running the test command limited to Hledger.Cli tests). -} cabal missing - home - modules workaround from hledger - lib , seems not needed here -- {-# LANGUAGE PackageImports #-} -- import "hledger" Hledger.Cli (tests_Hledger_Cli) import Hledger.Cli (tests_Hledger_Cli) import System.Environment (setEnv) import Test.Tasty (defaultMain) main :: IO () main = do setEnv "TASTY_HIDE_SUCCESSES" "true" setEnv "TASTY_ANSI_TRICKS" "false" -- helps the above defaultMain tests_Hledger_Cli
null
https://raw.githubusercontent.com/simonmichael/hledger/55772cbd9b88dfbe120811f8639b5b63640dac19/hledger/test/unittest.hs
haskell
{-# LANGUAGE PackageImports #-} import "hledger" Hledger.Cli (tests_Hledger_Cli) helps the above
Run the hledger package 's unit tests using the tasty test runner ( by running the test command limited to Hledger . Cli tests ) . Run the hledger package's unit tests using the tasty test runner (by running the test command limited to Hledger.Cli tests). -} cabal missing - home - modules workaround from hledger - lib , seems not needed here import Hledger.Cli (tests_Hledger_Cli) import System.Environment (setEnv) import Test.Tasty (defaultMain) main :: IO () main = do setEnv "TASTY_HIDE_SUCCESSES" "true" defaultMain tests_Hledger_Cli
573bd64c4bdb3ce3a92cba5c143bd81a605ee33846ac8bf1a492821301031d21
raystubbs/FkCSS
render.cljc
(ns fkcss.render (:require [clojure.string :as str] [fkcss.misc :refer [panic]])) (declare ^:dynamic ^:private *context*) (def default-property-handlers "Custom property handling, includes vendor prefixing." {:margin-x (fn [v] {:props {:margin-left v :margin-right v}}) :margin-y (fn [v] {:props {:margin-top v :margin-bottom v}}) :padding-x (fn [v] {:props {:padding-left v :padding-right v}}) :padding-y (fn [v] {:props {:padding-top v :padding-bottom v}}) :border-top-radius (fn [v] {:props {:border-top-left-radius v :border-top-right-radius v}}) :border-bottom-radius (fn [v] {:props {:border-bottom-left-radius v :border-bottom-right-radius v}}) :border-right-radius (fn [v] {:props {:border-top-right-radius v :border-bottom-right-radius v}}) :border-left-radius (fn [v] {:props {:border-top-left-radius v :border-bottom-left-radius v}}) :box-shadow (fn box-shadow-handler [v] (cond (string? v) v (map? v) (let [{:keys [offset-x offset-y blur-radius spread-radius color inset?]} v] (str (when inset? "inset ") (or offset-x 0) " " (or offset-y 0) " " (when (some? blur-radius) (str blur-radius " ")) (when (some? spread-radius) (str spread-radius " ")) (or color "black"))) (seqable? v) (str/join ", " (map box-shadow-handler v)) :else (str v))) :background-clip (fn [v] {:props (case (name v) "text" {:-webkit-background-clip v} #_else {:background-clip v})}) :box-reflect (fn [v] {:props {:-webkit-box-reflext v :box-reflect v}}) :filter (fn [v] {:props {:-webkit-filter v :filter v}}) :display (fn [v] {:props (case (name v) "flex" {:wk2/display "-webkit-box" :wk/display "-webkit-flexbox" :ms/display "-ms-flexbox" :display "flex"} "grid" {:ms/display "-ms-grid" :display "grid"} #_else {:display v})}) :flex (fn [v] {:props {:-webkit-box-flex v for old syntax , otherwise collapses ( from shouldiprefix.com#flexbox ) :-webkit-flex v :-ms-flex v :flex v}}) :font-feature-settings (fn [v] {:props {:-webkit-font-feature-settings v :-moz-font-feature-settings v :font-feature-settings v}}) :hyphens (fn [v] {:props {:-webkit-hyphens v :-moz-hyphens v :-ms-hyphens v :hyphens v}}) :word-break (fn [v] {:props {:-ms-word-break v :word-break v}}) :mask-image (fn [v] {:props {:-webkit-mask-image v :mask-image v}}) :column-count (fn [v] {:props {:-webkit-column-count v :-moz-column-count v :-column-count v}}) :column-gap (fn [v] {:props {:-webkit-column-gap v :-moz-column-gap v :column-gap v}}) :column-rule (fn [v] {:props {:-webkit-column-rule v :-moz-column-rule v :column-rule v}}) :object-fit (fn [v] {:props {:-o-object-fit v :object-fit v}}) :transform (fn [v] {:props {:-webkit-transform v :-ms-transform v :transform v}}) :appearance (fn [v] {:props {:-webkit-appearance v :-moz-appearance v :appearance v}}) :font-family (fn font-family-handler [v] {:props {:font-family (cond (string? v) (if (or (str/includes? v "'") (str/includes? v "\"") (str/includes? v ",") (not (re-find #"\W" v))) v (str "'" v "'")) (sequential? v) (str/join ", " (map font-family-handler v)) :else (str v))}})}) (def default-predicates (merge {:hovered? {:selector ":hover"} :active? {:selector ":active"} :focused? {:selector ":focus"} :focus-visible? {:selector ":focus-visible"} :enabled? {:selector ":enabled"} :disabled? {:selector ":disabled"} :visited? {:selector ":visited"} :checked? {:selector ":checked"} :expanded? {:selector "[aria-expanded=\"true\"]"} :current? {:selector "[aria-current]"} :screen-tiny? {:query "@media (max-width: 480px)"} :screen-small? {:query "@media (max-width: 768px)"} :screen-large? {:query "@media (min-width: 1025px)"} :screen-huge? {:query "@media (min-width: 1200px)"} :pointer-fine? {:query "@media (pointer: fine)"} :pointer-coarse? {:query "@media (pointer: coarse)"} :pointer-none? {:query "@media (pointer: none)"} :hoverable? {:query "@media (hover: hover)"}} #?(:cljs {:touchable? {:exec (fn is-touch-device? [] (or (js-in js/window "ontouchstart") (< 0 js/navigator.maxTouchPoints) (< 0 js/navigator.msMaxTouchPoints)))}}))) (def ^:private ^:dynamic *context* {:property-handlers default-property-handlers :predicates default-predicates}) (defn- resolve-properties [props] (into {} (mapcat (fn [[prop-key prop-val]] (or (when-let [handler (get-in *context* [:property-handlers prop-key])] (:props (handler prop-val))) (when (map? prop-val) (resolve-properties (into {} (map (fn [[sub-key sub-val]] [(keyword (str (name prop-key) "-" (name sub-key))) sub-val]) prop-val)))) [[prop-key (str prop-val)]])) props))) (defn- drop-chars [s n] (subs s 0 (- (count s) n))) (defn- tag-selector-key? [k] (and (keyword? k) (let [k-name (name k)] (and (not (str/ends-with? k-name ">>")) (str/ends-with? k-name ">"))))) (defn- predicate-selector-key? [k] (and (keyword? k) (-> k name (str/ends-with? "?")))) (defn- classes-selector-key? [k] (string? k)) (defn- pseudo-el-selector-key? [k] (and (keyword? k) (-> k name (str/ends-with? ">>")))) (defn- prop-key? [k] (and (keyword? k) (not (or (tag-selector-key? k) (predicate-selector-key? k) (classes-selector-key? k) (pseudo-el-selector-key? k))))) (defn- select-style-props [style] (into {} (keep (fn [[k v :as kv]] (when (prop-key? k) kv)) style))) (defn- select-style-nested [style] (into {} (keep (fn [[k v :as kv]] (when-not (prop-key? k) kv)) style))) (defn- update-last [v f & args] (let [new-v (apply f (last v) args)] (-> v pop (conj new-v)))) (defn- resolve-selector-next [resolved-path next-selector-key] (cond (tag-selector-key? next-selector-key) (conj resolved-path {:tag (-> next-selector-key name (drop-chars 1))}) (pseudo-el-selector-key? next-selector-key) (do (when (empty? resolved-path) (panic "unnested pseudo-element selector" {:key next-selector-key})) (let [pseudo-el-name (-> next-selector-key name (drop-chars 2))] (update-last resolved-path (fn [last-selector] (when-let [parent-pseudo-el-name (:pseudo-el last-selector)] (panic "nested pseudo-selectors" {:child pseudo-el-name :parent parent-pseudo-el-name})) (assoc last-selector :pseudo-el pseudo-el-name))))) (classes-selector-key? next-selector-key) (let [classes (-> next-selector-key (str/split #"\s+") vec)] (conj resolved-path {:classes classes})) (predicate-selector-key? next-selector-key) (let [predicate (get-in *context* [:predicates next-selector-key])] (when (and (:selector predicate) (empty? resolved-path)) (panic "selector predicate not nested" {:key next-selector-key})) (if (empty? resolved-path) [{:predicates #{predicate}}] (update-last resolved-path update :predicates (fnil conj #{}) predicate))) (vector? next-selector-key) (reduce (fn [m inner-next-selector-key] (resolve-selector-next m inner-next-selector-key)) resolved-path next-selector-key))) (defn- resolve-selectors-inner [resolved-path style] (into [[resolved-path (select-style-props style)]] (mapcat (fn [[k v]] (resolve-selectors-inner (resolve-selector-next resolved-path k) v)) (select-style-nested style)))) (defn- resolve-selectors [style] (resolve-selectors-inner [] style)) (defn- resolved-path->queries [resolved-path] (->> resolved-path (mapcat :predicates) (keep :query) set)) (defn- indentation [n] (str/join (repeat (* 2 n) " "))) (defn- render-css-selectors [resolved-path] (let [selectors (->> resolved-path (map (fn [{:keys [tag classes predicates pseudo-el]}] (str tag (when (seq classes) (str "." (str/join "." classes))) (str/join (keep :selector predicates)) (when pseudo-el (str "::" pseudo-el))))) (str/join " "))] (if (str/blank? selectors) "*" selectors))) (defn- render-css-props [level props] (->> props resolve-properties (map (fn [[k v]] (str (indentation level) (name k) ": " v ";\n"))) str/join)) (defn- render-css-rule [level resolved-path props] (str (indentation level) (render-css-selectors resolved-path) " {\n" (render-css-props (inc level) props) (indentation level) "}\n")) (defn- wrapped-in-queries [level queries styles] (cond (seq queries) (str (indentation level) (first queries) " {\n" (wrapped-in-queries (inc level) (rest queries) styles) (indentation level) "}\n") :else (->> styles (map (fn [[resolved-path props]] (render-css-rule level resolved-path props))) (str/join)))) (defn- exec-predicates [resolved-path] (->> resolved-path (mapcat :predicates) (keep :exec) (reduce (fn [acc exec-fn] (and acc (exec-fn))) true))) (defn render-style [style {:keys [property-handlers predicates]}] (binding [*context* {:property-handlers (or property-handlers default-property-handlers) :predicates (or predicates default-predicates) :rendering :style}] (->> style resolve-selectors (filter #(and (seq (second %)) (exec-predicates (first %)))) (group-by (comp resolved-path->queries first)) (sort-by #(count (first %))) ; rules with queries come after to ensure correct precedence (map #(wrapped-in-queries 0 (seq (first %)) (second %))) (str/join "\n")))) (defn render-font [font-spec {:keys [property-handlers]}] (binding [*context* {:property-handlers (or property-handlers default-property-handlers) :predicates {} :rendering :font}] (->> font-spec (map (fn [font-props] (str "@font-face {\n" (render-css-props 1 font-props) "}\n"))) str/join))) (defn render-animation [animation-name animation-frames] (str "@keyframes " animation-name " {\n" (->> animation-frames (map (fn [[k props]] (str (indentation 1) (cond (number? k) (str (* 100 k) "%") (keyword? k) (name k) :else k) " {\n" (render-css-props 2 props) (indentation 1) "}\n"))) str/join) "}\n"))
null
https://raw.githubusercontent.com/raystubbs/FkCSS/c77478b0f7c664e110942b11bb6dc14f641895f9/src/fkcss/render.cljc
clojure
rules with queries come after to ensure correct precedence
(ns fkcss.render (:require [clojure.string :as str] [fkcss.misc :refer [panic]])) (declare ^:dynamic ^:private *context*) (def default-property-handlers "Custom property handling, includes vendor prefixing." {:margin-x (fn [v] {:props {:margin-left v :margin-right v}}) :margin-y (fn [v] {:props {:margin-top v :margin-bottom v}}) :padding-x (fn [v] {:props {:padding-left v :padding-right v}}) :padding-y (fn [v] {:props {:padding-top v :padding-bottom v}}) :border-top-radius (fn [v] {:props {:border-top-left-radius v :border-top-right-radius v}}) :border-bottom-radius (fn [v] {:props {:border-bottom-left-radius v :border-bottom-right-radius v}}) :border-right-radius (fn [v] {:props {:border-top-right-radius v :border-bottom-right-radius v}}) :border-left-radius (fn [v] {:props {:border-top-left-radius v :border-bottom-left-radius v}}) :box-shadow (fn box-shadow-handler [v] (cond (string? v) v (map? v) (let [{:keys [offset-x offset-y blur-radius spread-radius color inset?]} v] (str (when inset? "inset ") (or offset-x 0) " " (or offset-y 0) " " (when (some? blur-radius) (str blur-radius " ")) (when (some? spread-radius) (str spread-radius " ")) (or color "black"))) (seqable? v) (str/join ", " (map box-shadow-handler v)) :else (str v))) :background-clip (fn [v] {:props (case (name v) "text" {:-webkit-background-clip v} #_else {:background-clip v})}) :box-reflect (fn [v] {:props {:-webkit-box-reflext v :box-reflect v}}) :filter (fn [v] {:props {:-webkit-filter v :filter v}}) :display (fn [v] {:props (case (name v) "flex" {:wk2/display "-webkit-box" :wk/display "-webkit-flexbox" :ms/display "-ms-flexbox" :display "flex"} "grid" {:ms/display "-ms-grid" :display "grid"} #_else {:display v})}) :flex (fn [v] {:props {:-webkit-box-flex v for old syntax , otherwise collapses ( from shouldiprefix.com#flexbox ) :-webkit-flex v :-ms-flex v :flex v}}) :font-feature-settings (fn [v] {:props {:-webkit-font-feature-settings v :-moz-font-feature-settings v :font-feature-settings v}}) :hyphens (fn [v] {:props {:-webkit-hyphens v :-moz-hyphens v :-ms-hyphens v :hyphens v}}) :word-break (fn [v] {:props {:-ms-word-break v :word-break v}}) :mask-image (fn [v] {:props {:-webkit-mask-image v :mask-image v}}) :column-count (fn [v] {:props {:-webkit-column-count v :-moz-column-count v :-column-count v}}) :column-gap (fn [v] {:props {:-webkit-column-gap v :-moz-column-gap v :column-gap v}}) :column-rule (fn [v] {:props {:-webkit-column-rule v :-moz-column-rule v :column-rule v}}) :object-fit (fn [v] {:props {:-o-object-fit v :object-fit v}}) :transform (fn [v] {:props {:-webkit-transform v :-ms-transform v :transform v}}) :appearance (fn [v] {:props {:-webkit-appearance v :-moz-appearance v :appearance v}}) :font-family (fn font-family-handler [v] {:props {:font-family (cond (string? v) (if (or (str/includes? v "'") (str/includes? v "\"") (str/includes? v ",") (not (re-find #"\W" v))) v (str "'" v "'")) (sequential? v) (str/join ", " (map font-family-handler v)) :else (str v))}})}) (def default-predicates (merge {:hovered? {:selector ":hover"} :active? {:selector ":active"} :focused? {:selector ":focus"} :focus-visible? {:selector ":focus-visible"} :enabled? {:selector ":enabled"} :disabled? {:selector ":disabled"} :visited? {:selector ":visited"} :checked? {:selector ":checked"} :expanded? {:selector "[aria-expanded=\"true\"]"} :current? {:selector "[aria-current]"} :screen-tiny? {:query "@media (max-width: 480px)"} :screen-small? {:query "@media (max-width: 768px)"} :screen-large? {:query "@media (min-width: 1025px)"} :screen-huge? {:query "@media (min-width: 1200px)"} :pointer-fine? {:query "@media (pointer: fine)"} :pointer-coarse? {:query "@media (pointer: coarse)"} :pointer-none? {:query "@media (pointer: none)"} :hoverable? {:query "@media (hover: hover)"}} #?(:cljs {:touchable? {:exec (fn is-touch-device? [] (or (js-in js/window "ontouchstart") (< 0 js/navigator.maxTouchPoints) (< 0 js/navigator.msMaxTouchPoints)))}}))) (def ^:private ^:dynamic *context* {:property-handlers default-property-handlers :predicates default-predicates}) (defn- resolve-properties [props] (into {} (mapcat (fn [[prop-key prop-val]] (or (when-let [handler (get-in *context* [:property-handlers prop-key])] (:props (handler prop-val))) (when (map? prop-val) (resolve-properties (into {} (map (fn [[sub-key sub-val]] [(keyword (str (name prop-key) "-" (name sub-key))) sub-val]) prop-val)))) [[prop-key (str prop-val)]])) props))) (defn- drop-chars [s n] (subs s 0 (- (count s) n))) (defn- tag-selector-key? [k] (and (keyword? k) (let [k-name (name k)] (and (not (str/ends-with? k-name ">>")) (str/ends-with? k-name ">"))))) (defn- predicate-selector-key? [k] (and (keyword? k) (-> k name (str/ends-with? "?")))) (defn- classes-selector-key? [k] (string? k)) (defn- pseudo-el-selector-key? [k] (and (keyword? k) (-> k name (str/ends-with? ">>")))) (defn- prop-key? [k] (and (keyword? k) (not (or (tag-selector-key? k) (predicate-selector-key? k) (classes-selector-key? k) (pseudo-el-selector-key? k))))) (defn- select-style-props [style] (into {} (keep (fn [[k v :as kv]] (when (prop-key? k) kv)) style))) (defn- select-style-nested [style] (into {} (keep (fn [[k v :as kv]] (when-not (prop-key? k) kv)) style))) (defn- update-last [v f & args] (let [new-v (apply f (last v) args)] (-> v pop (conj new-v)))) (defn- resolve-selector-next [resolved-path next-selector-key] (cond (tag-selector-key? next-selector-key) (conj resolved-path {:tag (-> next-selector-key name (drop-chars 1))}) (pseudo-el-selector-key? next-selector-key) (do (when (empty? resolved-path) (panic "unnested pseudo-element selector" {:key next-selector-key})) (let [pseudo-el-name (-> next-selector-key name (drop-chars 2))] (update-last resolved-path (fn [last-selector] (when-let [parent-pseudo-el-name (:pseudo-el last-selector)] (panic "nested pseudo-selectors" {:child pseudo-el-name :parent parent-pseudo-el-name})) (assoc last-selector :pseudo-el pseudo-el-name))))) (classes-selector-key? next-selector-key) (let [classes (-> next-selector-key (str/split #"\s+") vec)] (conj resolved-path {:classes classes})) (predicate-selector-key? next-selector-key) (let [predicate (get-in *context* [:predicates next-selector-key])] (when (and (:selector predicate) (empty? resolved-path)) (panic "selector predicate not nested" {:key next-selector-key})) (if (empty? resolved-path) [{:predicates #{predicate}}] (update-last resolved-path update :predicates (fnil conj #{}) predicate))) (vector? next-selector-key) (reduce (fn [m inner-next-selector-key] (resolve-selector-next m inner-next-selector-key)) resolved-path next-selector-key))) (defn- resolve-selectors-inner [resolved-path style] (into [[resolved-path (select-style-props style)]] (mapcat (fn [[k v]] (resolve-selectors-inner (resolve-selector-next resolved-path k) v)) (select-style-nested style)))) (defn- resolve-selectors [style] (resolve-selectors-inner [] style)) (defn- resolved-path->queries [resolved-path] (->> resolved-path (mapcat :predicates) (keep :query) set)) (defn- indentation [n] (str/join (repeat (* 2 n) " "))) (defn- render-css-selectors [resolved-path] (let [selectors (->> resolved-path (map (fn [{:keys [tag classes predicates pseudo-el]}] (str tag (when (seq classes) (str "." (str/join "." classes))) (str/join (keep :selector predicates)) (when pseudo-el (str "::" pseudo-el))))) (str/join " "))] (if (str/blank? selectors) "*" selectors))) (defn- render-css-props [level props] (->> props resolve-properties (map (fn [[k v]] (str (indentation level) (name k) ": " v ";\n"))) str/join)) (defn- render-css-rule [level resolved-path props] (str (indentation level) (render-css-selectors resolved-path) " {\n" (render-css-props (inc level) props) (indentation level) "}\n")) (defn- wrapped-in-queries [level queries styles] (cond (seq queries) (str (indentation level) (first queries) " {\n" (wrapped-in-queries (inc level) (rest queries) styles) (indentation level) "}\n") :else (->> styles (map (fn [[resolved-path props]] (render-css-rule level resolved-path props))) (str/join)))) (defn- exec-predicates [resolved-path] (->> resolved-path (mapcat :predicates) (keep :exec) (reduce (fn [acc exec-fn] (and acc (exec-fn))) true))) (defn render-style [style {:keys [property-handlers predicates]}] (binding [*context* {:property-handlers (or property-handlers default-property-handlers) :predicates (or predicates default-predicates) :rendering :style}] (->> style resolve-selectors (filter #(and (seq (second %)) (exec-predicates (first %)))) (group-by (comp resolved-path->queries first)) (map #(wrapped-in-queries 0 (seq (first %)) (second %))) (str/join "\n")))) (defn render-font [font-spec {:keys [property-handlers]}] (binding [*context* {:property-handlers (or property-handlers default-property-handlers) :predicates {} :rendering :font}] (->> font-spec (map (fn [font-props] (str "@font-face {\n" (render-css-props 1 font-props) "}\n"))) str/join))) (defn render-animation [animation-name animation-frames] (str "@keyframes " animation-name " {\n" (->> animation-frames (map (fn [[k props]] (str (indentation 1) (cond (number? k) (str (* 100 k) "%") (keyword? k) (name k) :else k) " {\n" (render-css-props 2 props) (indentation 1) "}\n"))) str/join) "}\n"))
1172d8e6a4ec53aad2758301c8ec0bcbb9192474ac675e514414498d8e70aa40
pichi/epexercises
db.erl
-module(db). -export([new/0, destroy/1, write/3, delete/2, read/2, match/2]). -export([test/0]). % db:new() ⇒ Db. % db:destroy(Db) ⇒ ok. % db:write(Key, Element, Db) ⇒ NewDb. db : delete(Key , Db ) ⇒ NewDb . db : read(Key , Db ) ⇒{ok , Element } | { error , instance } . db : match(Element , Db ) ⇒ [ Key1 , ... , KeyN ] . new() -> []. destroy(X) when is_list(X) -> ok. write(Key, Element, Db) -> [{Key, Element}|lists:keydelete(Key, 1, Db)]. delete(Key, Db) -> lists:keydelete(Key, 1, Db). read(Key, Db) -> read(lists:keyfind(Key, 1, Db)). read(false) -> {error, instance}; read({_, Element}) -> {ok, Element}. match(Element, Db) -> [Key || {Key, X}<-Db, X=:=Element]. test() -> [] = Db = db:new(), [{francesco,london}] = Db1 = db:write(francesco, london, Db), [{lelle,stockholm},{francesco,london}] = Db2 = db:write(lelle, stockholm, Db1), {ok,london} = db:read(francesco, Db2), [{joern,stockholm},{lelle,stockholm},{francesco,london}] = Db3 = db:write(joern, stockholm, Db2), {error,instance}= db:read(ola, Db3), [joern,lelle] = db:match(stockholm, Db3), [{joern,stockholm},{francesco,london}] = Db4 = db:delete(lelle, Db3), [{francesco,prague},{joern,stockholm}] = db:write(francesco, prague, Db4), [joern] = db:match(stockholm, Db4), ok.
null
https://raw.githubusercontent.com/pichi/epexercises/d6383ad334bd6cf684b16225bffd33d6c3d2746f/Exercise3-7/db.erl
erlang
db:new() ⇒ Db. db:destroy(Db) ⇒ ok. db:write(Key, Element, Db) ⇒ NewDb.
-module(db). -export([new/0, destroy/1, write/3, delete/2, read/2, match/2]). -export([test/0]). db : delete(Key , Db ) ⇒ NewDb . db : read(Key , Db ) ⇒{ok , Element } | { error , instance } . db : match(Element , Db ) ⇒ [ Key1 , ... , KeyN ] . new() -> []. destroy(X) when is_list(X) -> ok. write(Key, Element, Db) -> [{Key, Element}|lists:keydelete(Key, 1, Db)]. delete(Key, Db) -> lists:keydelete(Key, 1, Db). read(Key, Db) -> read(lists:keyfind(Key, 1, Db)). read(false) -> {error, instance}; read({_, Element}) -> {ok, Element}. match(Element, Db) -> [Key || {Key, X}<-Db, X=:=Element]. test() -> [] = Db = db:new(), [{francesco,london}] = Db1 = db:write(francesco, london, Db), [{lelle,stockholm},{francesco,london}] = Db2 = db:write(lelle, stockholm, Db1), {ok,london} = db:read(francesco, Db2), [{joern,stockholm},{lelle,stockholm},{francesco,london}] = Db3 = db:write(joern, stockholm, Db2), {error,instance}= db:read(ola, Db3), [joern,lelle] = db:match(stockholm, Db3), [{joern,stockholm},{francesco,london}] = Db4 = db:delete(lelle, Db3), [{francesco,prague},{joern,stockholm}] = db:write(francesco, prague, Db4), [joern] = db:match(stockholm, Db4), ok.
fc6fbf3acecfd8d72c033c798a02f212ca140e4102c2135523266b4acf2d2e85
TyGuS/hoogle_plus
GHCCheckerSpec.hs
module HooglePlus.GHCCheckerSpec (spec) where import HooglePlus.GHCChecker import Synquid.Parser import Synquid.Pretty () -- Instances import Types.Type import Types.Program import Synquid.Type import Synquid.Logic import Database.Util import Test.Hspec import Text.Pretty.Simple import Text.Parsec.Pos import Control.Monad.State import Text.Parsec.Indent import qualified Data.Map as Map import Data.Either doParseType tyStr = flip evalState (initialPos "goal") $ runIndentParserT parseTypeMbTypeclasses () "" tyStr anyTy program = Program{typeOf=AnyT, content=program} separateFunctions : : String - > ( [ RType ] , RType ) separateFunctions query = let res = either (\left -> error $ show left) id $ doParseType query in allBaseTypes res spec :: Spec spec = do describe "parseStrictnessSig" $ do it "plucks out the strictness signatures" $ do let sig = unlines [ "foo :: forall a b. a -> a -> (a -> b) -> a" , "[LclIdX," , "Arity=3," , "Str=<S,1*U><L,A><L,A>," , "Unf=Unf{Src=<vanilla>, TopLvl=True, Value=True, ConLike=True," , " WorkFree=True, Expandable=True," , " Guidance=ALWAYS_IF(arity=3,unsat_ok=True,boring_ok=True)}]" , "foo" , " = \\ (@ a)" , " (@ b)" , " (arg0 [Dmd=<S,1*U>] :: a)" , " _ [Occ=Dead, Dmd=<L,A>]" , " _ [Occ=Dead, Dmd=<L,A>] ->" , " arg0" ] let expected = "<S,1*U><L,A><L,A>" let result = parseStrictnessSig sig result `shouldBe` expected it "plucks out the strictness signatures, example 2" $ do let sig = unlines [ "foo :: forall a. a -> [a] -> [a]" , "[LclIdX," , "Arity=2," , "Str=<L,U><L,U>m2," , "Unf=Unf{Src=<vanilla>, TopLvl=True, Value=True, ConLike=True," , " WorkFree=True, Expandable=True," , " Guidance=ALWAYS_IF(arity=3,unsat_ok=True,boring_ok=True)}]" , "foo" ] let expected = "<L,U><L,U>" let result = parseStrictnessSig sig result `shouldBe` expected describe "checkStrictness'" $ do it "should accpt a fully used lambda" $ do let tyclassCount = 0 let lambdaExpr = "(\\x -> \\y -> (:) x y)" let typeExpr = "a -> [a] -> [a]" let modules = ["Prelude"] result <- checkStrictness' tyclassCount lambdaExpr typeExpr modules result `shouldBe` True it "should reject a partially used lambda" $ do let tyclassCount = 0 let lambdaExpr = "(\\x -> \\y -> x)" let typeExpr = "a -> b -> a" let modules = ["Prelude"] result <- checkStrictness' tyclassCount lambdaExpr typeExpr modules result `shouldBe` False
null
https://raw.githubusercontent.com/TyGuS/hoogle_plus/d02a1466d98f872e78ddb2fb612cb67d4bd0ca18/test/HooglePlus/GHCCheckerSpec.hs
haskell
Instances
module HooglePlus.GHCCheckerSpec (spec) where import HooglePlus.GHCChecker import Synquid.Parser import Types.Type import Types.Program import Synquid.Type import Synquid.Logic import Database.Util import Test.Hspec import Text.Pretty.Simple import Text.Parsec.Pos import Control.Monad.State import Text.Parsec.Indent import qualified Data.Map as Map import Data.Either doParseType tyStr = flip evalState (initialPos "goal") $ runIndentParserT parseTypeMbTypeclasses () "" tyStr anyTy program = Program{typeOf=AnyT, content=program} separateFunctions : : String - > ( [ RType ] , RType ) separateFunctions query = let res = either (\left -> error $ show left) id $ doParseType query in allBaseTypes res spec :: Spec spec = do describe "parseStrictnessSig" $ do it "plucks out the strictness signatures" $ do let sig = unlines [ "foo :: forall a b. a -> a -> (a -> b) -> a" , "[LclIdX," , "Arity=3," , "Str=<S,1*U><L,A><L,A>," , "Unf=Unf{Src=<vanilla>, TopLvl=True, Value=True, ConLike=True," , " WorkFree=True, Expandable=True," , " Guidance=ALWAYS_IF(arity=3,unsat_ok=True,boring_ok=True)}]" , "foo" , " = \\ (@ a)" , " (@ b)" , " (arg0 [Dmd=<S,1*U>] :: a)" , " _ [Occ=Dead, Dmd=<L,A>]" , " _ [Occ=Dead, Dmd=<L,A>] ->" , " arg0" ] let expected = "<S,1*U><L,A><L,A>" let result = parseStrictnessSig sig result `shouldBe` expected it "plucks out the strictness signatures, example 2" $ do let sig = unlines [ "foo :: forall a. a -> [a] -> [a]" , "[LclIdX," , "Arity=2," , "Str=<L,U><L,U>m2," , "Unf=Unf{Src=<vanilla>, TopLvl=True, Value=True, ConLike=True," , " WorkFree=True, Expandable=True," , " Guidance=ALWAYS_IF(arity=3,unsat_ok=True,boring_ok=True)}]" , "foo" ] let expected = "<L,U><L,U>" let result = parseStrictnessSig sig result `shouldBe` expected describe "checkStrictness'" $ do it "should accpt a fully used lambda" $ do let tyclassCount = 0 let lambdaExpr = "(\\x -> \\y -> (:) x y)" let typeExpr = "a -> [a] -> [a]" let modules = ["Prelude"] result <- checkStrictness' tyclassCount lambdaExpr typeExpr modules result `shouldBe` True it "should reject a partially used lambda" $ do let tyclassCount = 0 let lambdaExpr = "(\\x -> \\y -> x)" let typeExpr = "a -> b -> a" let modules = ["Prelude"] result <- checkStrictness' tyclassCount lambdaExpr typeExpr modules result `shouldBe` False
ec78f49e1795d661efc1eef10369b7b54033bc00a3d658d3f3c2369e12519d80
themattchan/haskell-tiger
Gensym.hs
# LANGUAGE DeriveFunctor , GeneralizedNewtypeDeriving , FlexibleContexts , FlexibleInstances , MultiParamTypeClasses , FunctionalDependencies # FlexibleInstances, MultiParamTypeClasses, FunctionalDependencies #-} module Language.Tiger.Gensym do NOT export genzero and , Gensym(..) , , GensymT(..) , runGensymT ) where import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Monad.Trans.State (StateT(..), evalStateT) import Control.Monad.State.Class class Fresh s where genzero :: s gennext :: s -> s instance Fresh Int where genzero = 0 gennext = (+1) newtype GensymT s m a = GensymT { unGensymT :: StateT s m a } deriving (Functor, Applicative, Monad, MonadTrans, MonadIO) instance = > MonadState s ( GensymT s m ) where -- state = GensymT . state -- class Gensym s m where : : m s class (Fresh s, Monad m) => Gensym s m | m -> s where gensym :: m s instance (Fresh s, Monad m) => Gensym s (GensymT s m) where gensym = GensymT $ do s <- get modify gennext return s runGensymT :: (Fresh s, Monad m) => GensymT s m a -> m a runGensymT = flip evalStateT genzero . unGensymT
null
https://raw.githubusercontent.com/themattchan/haskell-tiger/cdf439a45e51783b3d2023c261426abdd7cd1067/src/Language/Tiger/Gensym.hs
haskell
state = GensymT . state class Gensym s m where
# LANGUAGE DeriveFunctor , GeneralizedNewtypeDeriving , FlexibleContexts , FlexibleInstances , MultiParamTypeClasses , FunctionalDependencies # FlexibleInstances, MultiParamTypeClasses, FunctionalDependencies #-} module Language.Tiger.Gensym do NOT export genzero and , Gensym(..) , , GensymT(..) , runGensymT ) where import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Monad.Trans.State (StateT(..), evalStateT) import Control.Monad.State.Class class Fresh s where genzero :: s gennext :: s -> s instance Fresh Int where genzero = 0 gennext = (+1) newtype GensymT s m a = GensymT { unGensymT :: StateT s m a } deriving (Functor, Applicative, Monad, MonadTrans, MonadIO) instance = > MonadState s ( GensymT s m ) where : : m s class (Fresh s, Monad m) => Gensym s m | m -> s where gensym :: m s instance (Fresh s, Monad m) => Gensym s (GensymT s m) where gensym = GensymT $ do s <- get modify gennext return s runGensymT :: (Fresh s, Monad m) => GensymT s m a -> m a runGensymT = flip evalStateT genzero . unGensymT
595379351630fc885fb0204e2816a2eac035188626a57e978dac9648a03cc1f3
MinaProtocol/mina
sgn.ml
[%%import "/src/config.mlh"] open Core_kernel open Snark_params.Tick [%%versioned module Stable = struct module V1 = struct type t = Sgn_type.Sgn.Stable.V1.t = Pos | Neg [@@deriving sexp, hash, compare, equal, yojson] let to_latest = Fn.id end end] let gen = Quickcheck.Generator.map Bool.quickcheck_generator ~f:(fun b -> if b then Pos else Neg ) let negate = function Pos -> Neg | Neg -> Pos let neg_one = Field.(negate one) let to_field = function Pos -> Field.one | Neg -> neg_one let of_field_exn x = if Field.equal x Field.one then Pos else if Field.equal x neg_one then Neg else failwith "Sgn.of_field: Expected positive or negative 1" [%%ifdef consensus_mechanism] type var = Field.Var.t let typ : (var, t) Typ.t = let open Typ in Typ { check = (fun x -> assert_r1cs x x (Field.Var.constant Field.one)) ; var_to_fields = (fun t -> ([| t |], ())) ; var_of_fields = (fun (ts, ()) -> ts.(0)) ; value_to_fields = (fun t -> ([| to_field t |], ())) ; value_of_fields = (fun (ts, ()) -> of_field_exn ts.(0)) ; size_in_field_elements = 1 ; constraint_system_auxiliary = (fun () -> ()) } module Checked = struct let two = Field.of_int 2 let neg_two = Field.negate two let one_half = Field.inv two let neg_one_half = Field.negate one_half let is_pos (v : var) = Boolean.Unsafe.of_cvar (let open Field.Checked in one_half * (v + Field.Var.constant Field.one)) let is_neg (v : var) = Boolean.Unsafe.of_cvar (let open Field.Checked in neg_one_half * (v - Field.Var.constant Field.one)) let pos_if_true (b : Boolean.var) = let open Field.Checked in (two * (b :> Field.Var.t)) - Field.Var.constant Field.one let neg_if_true (b : Boolean.var) = let open Field.Checked in (neg_two * (b :> Field.Var.t)) + Field.Var.constant Field.one let negate t = Field.Var.scale t neg_one let constant = Fn.compose Field.Var.constant to_field let neg = constant Neg let pos = constant Pos let if_ = Field.Checked.if_ end [%%endif]
null
https://raw.githubusercontent.com/MinaProtocol/mina/c3900e233a58127c00c26f7eb2ebf468581cbd07/src/lib/sgn/sgn.ml
ocaml
[%%import "/src/config.mlh"] open Core_kernel open Snark_params.Tick [%%versioned module Stable = struct module V1 = struct type t = Sgn_type.Sgn.Stable.V1.t = Pos | Neg [@@deriving sexp, hash, compare, equal, yojson] let to_latest = Fn.id end end] let gen = Quickcheck.Generator.map Bool.quickcheck_generator ~f:(fun b -> if b then Pos else Neg ) let negate = function Pos -> Neg | Neg -> Pos let neg_one = Field.(negate one) let to_field = function Pos -> Field.one | Neg -> neg_one let of_field_exn x = if Field.equal x Field.one then Pos else if Field.equal x neg_one then Neg else failwith "Sgn.of_field: Expected positive or negative 1" [%%ifdef consensus_mechanism] type var = Field.Var.t let typ : (var, t) Typ.t = let open Typ in Typ { check = (fun x -> assert_r1cs x x (Field.Var.constant Field.one)) ; var_to_fields = (fun t -> ([| t |], ())) ; var_of_fields = (fun (ts, ()) -> ts.(0)) ; value_to_fields = (fun t -> ([| to_field t |], ())) ; value_of_fields = (fun (ts, ()) -> of_field_exn ts.(0)) ; size_in_field_elements = 1 ; constraint_system_auxiliary = (fun () -> ()) } module Checked = struct let two = Field.of_int 2 let neg_two = Field.negate two let one_half = Field.inv two let neg_one_half = Field.negate one_half let is_pos (v : var) = Boolean.Unsafe.of_cvar (let open Field.Checked in one_half * (v + Field.Var.constant Field.one)) let is_neg (v : var) = Boolean.Unsafe.of_cvar (let open Field.Checked in neg_one_half * (v - Field.Var.constant Field.one)) let pos_if_true (b : Boolean.var) = let open Field.Checked in (two * (b :> Field.Var.t)) - Field.Var.constant Field.one let neg_if_true (b : Boolean.var) = let open Field.Checked in (neg_two * (b :> Field.Var.t)) + Field.Var.constant Field.one let negate t = Field.Var.scale t neg_one let constant = Fn.compose Field.Var.constant to_field let neg = constant Neg let pos = constant Pos let if_ = Field.Checked.if_ end [%%endif]
53a9e50a9b5aacf45fc6d0059b6d58c6c64e57e090783d29bfbe77a94bc53b72
jamesdbrock/replace-megaparsec
TestByteString.hs
# LANGUAGE FlexibleContexts # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TypeFamilies # # LANGUAGE CPP # module TestByteString ( tests ) where import Distribution.TestSuite as TestSuite import Replace.Megaparsec import Text.Megaparsec import Text.Megaparsec.Byte import Text.Megaparsec.Byte.Lexer import Data.Void import qualified Data.ByteString as B import Data.ByteString.Internal (c2w) import GHC.Word type Parser = Parsec Void B.ByteString findAllCap' :: MonadParsec e s m => m a -> m [Either (Tokens s) (Tokens s, a)] findAllCap' sep = sepCap (match sep) tests :: IO [Test] tests = return [ Test $ runParserTest "findAll upperChar" (findAllCap' (upperChar :: Parser Word8)) ("aBcD" :: B.ByteString) [Left "a", Right ("B", c2w 'B'), Left "c", Right ("D", c2w 'D')] check that sepCap can progress even when parser consumes nothing -- and succeeds. , Test $ runParserTest "zero-consumption parser" (sepCap (many (upperChar :: Parser Word8))) ("aBcD" :: B.ByteString) [Left "a", Right [c2w 'B'], Left "c", Right [c2w 'D']] , Test $ runParserTest "scinum" (sepCap scinum) ("1E3") ([Right (1,3)]) , Test $ runParserTest "getOffset" (sepCap offsetA) ("xxAxx") ([Left "xx", Right 2, Left "xx"]) , Test $ runParserTest "monad fail" (sepCap (fail "" :: Parser ())) ("xxx") ([Left "xxx"]) #if MIN_VERSION_GLASGOW_HASKELL(8,6,0,0) , Test $ runParserTest "read fail" (sepCap (return (read "a" :: Int) :: Parser Int)) ("a") ([Left "a"]) #endif , Test $ runParserTest "empty input" (sepCap (fail "" :: Parser ())) "" [] , Test $ streamEditTest "x to o" (string "x" :: Parser B.ByteString) (const "o") "x x x" "o o o" , Test $ streamEditTest "x to o inner" (string "x" :: Parser B.ByteString) (const "o") " x x x " " o o o " , Test $ streamEditTest "ordering" (string "456" :: Parser B.ByteString) (const "ABC") "123456789" "123ABC789" , Test $ streamEditTest "empty input" (match (fail "" :: Parser ())) (fst) "" "" , Test $ breakCapTest "basic" (upperChar :: Parser Word8) "aAa" (Just ("a", c2w 'A', "a")) , Test $ breakCapTest "first" (upperChar :: Parser Word8) "Aa" (Just ("", c2w 'A', "a")) , Test $ breakCapTest "last" (upperChar :: Parser Word8) "aA" (Just ("a", c2w 'A', "")) , Test $ breakCapTest "fail" (upperChar :: Parser Word8) "aaa" Nothing , Test $ breakCapTest "match" (match (upperChar :: Parser Word8)) "aAa" (Just ("a", ("A",c2w 'A'), "a")) , Test $ breakCapTest "zero-width" (lookAhead (upperChar :: Parser Word8)) "aAa" (Just ("a", c2w 'A', "Aa")) , Test $ breakCapTest "empty input" (upperChar :: Parser Word8) "" Nothing , Test $ breakCapTest "empty input zero-width" (return () :: Parser ()) "" (Just ("", (), "")) ] where runParserTest nam p input expected = TestInstance { run = do case runParser p "" input of Left e -> return (Finished $ Fail $ show e) Right output -> if (output == expected) then return (Finished Pass) else return (Finished $ Fail $ "got " <> show output <> " expected " <> show expected) , name = nam , tags = [] , options = [] , setOption = \_ _ -> Left "no options supported" } streamEditTest nam sep editor input expected = TestInstance { run = do let output = streamEdit sep editor input if (output == expected) then return (Finished Pass) else return (Finished $ TestSuite.Fail $ "got " <> show output <> " expected " <> show expected) , name = "streamEdit " ++ nam , tags = [] , options = [] , setOption = \_ _ -> Left "no options supported" } breakCapTest nam sep input expected = TestInstance { run = do let output = breakCap sep input if (output == expected) then return (Finished Pass) else return (Finished $ TestSuite.Fail $ "got " <> show output <> " expected " <> show expected) , name = "breakCap " ++ nam , tags = [] , options = [] , setOption = \_ _ -> Left "no options supported" } scinum :: Parser (Double, Integer) scinum = do -- This won't parse mantissas that contain a decimal point, -- but if we use the Text.Megaparsec.Byte.Lexer.float, then it consumes -- the "E" and the exponent. Whatever, doesn't really matter for this test. m <- (fromIntegral :: Integer -> Double) <$> decimal _ <- chunk "E" e <- decimal return (m, e) offsetA :: Parser Int offsetA = getOffset <* chunk "A"
null
https://raw.githubusercontent.com/jamesdbrock/replace-megaparsec/eeabfbdd482a22d96cee9ca2a19bf194f1d5d610/tests/TestByteString.hs
haskell
# LANGUAGE OverloadedStrings # and succeeds. This won't parse mantissas that contain a decimal point, but if we use the Text.Megaparsec.Byte.Lexer.float, then it consumes the "E" and the exponent. Whatever, doesn't really matter for this test.
# LANGUAGE FlexibleContexts # # LANGUAGE TypeFamilies # # LANGUAGE CPP # module TestByteString ( tests ) where import Distribution.TestSuite as TestSuite import Replace.Megaparsec import Text.Megaparsec import Text.Megaparsec.Byte import Text.Megaparsec.Byte.Lexer import Data.Void import qualified Data.ByteString as B import Data.ByteString.Internal (c2w) import GHC.Word type Parser = Parsec Void B.ByteString findAllCap' :: MonadParsec e s m => m a -> m [Either (Tokens s) (Tokens s, a)] findAllCap' sep = sepCap (match sep) tests :: IO [Test] tests = return [ Test $ runParserTest "findAll upperChar" (findAllCap' (upperChar :: Parser Word8)) ("aBcD" :: B.ByteString) [Left "a", Right ("B", c2w 'B'), Left "c", Right ("D", c2w 'D')] check that sepCap can progress even when parser consumes nothing , Test $ runParserTest "zero-consumption parser" (sepCap (many (upperChar :: Parser Word8))) ("aBcD" :: B.ByteString) [Left "a", Right [c2w 'B'], Left "c", Right [c2w 'D']] , Test $ runParserTest "scinum" (sepCap scinum) ("1E3") ([Right (1,3)]) , Test $ runParserTest "getOffset" (sepCap offsetA) ("xxAxx") ([Left "xx", Right 2, Left "xx"]) , Test $ runParserTest "monad fail" (sepCap (fail "" :: Parser ())) ("xxx") ([Left "xxx"]) #if MIN_VERSION_GLASGOW_HASKELL(8,6,0,0) , Test $ runParserTest "read fail" (sepCap (return (read "a" :: Int) :: Parser Int)) ("a") ([Left "a"]) #endif , Test $ runParserTest "empty input" (sepCap (fail "" :: Parser ())) "" [] , Test $ streamEditTest "x to o" (string "x" :: Parser B.ByteString) (const "o") "x x x" "o o o" , Test $ streamEditTest "x to o inner" (string "x" :: Parser B.ByteString) (const "o") " x x x " " o o o " , Test $ streamEditTest "ordering" (string "456" :: Parser B.ByteString) (const "ABC") "123456789" "123ABC789" , Test $ streamEditTest "empty input" (match (fail "" :: Parser ())) (fst) "" "" , Test $ breakCapTest "basic" (upperChar :: Parser Word8) "aAa" (Just ("a", c2w 'A', "a")) , Test $ breakCapTest "first" (upperChar :: Parser Word8) "Aa" (Just ("", c2w 'A', "a")) , Test $ breakCapTest "last" (upperChar :: Parser Word8) "aA" (Just ("a", c2w 'A', "")) , Test $ breakCapTest "fail" (upperChar :: Parser Word8) "aaa" Nothing , Test $ breakCapTest "match" (match (upperChar :: Parser Word8)) "aAa" (Just ("a", ("A",c2w 'A'), "a")) , Test $ breakCapTest "zero-width" (lookAhead (upperChar :: Parser Word8)) "aAa" (Just ("a", c2w 'A', "Aa")) , Test $ breakCapTest "empty input" (upperChar :: Parser Word8) "" Nothing , Test $ breakCapTest "empty input zero-width" (return () :: Parser ()) "" (Just ("", (), "")) ] where runParserTest nam p input expected = TestInstance { run = do case runParser p "" input of Left e -> return (Finished $ Fail $ show e) Right output -> if (output == expected) then return (Finished Pass) else return (Finished $ Fail $ "got " <> show output <> " expected " <> show expected) , name = nam , tags = [] , options = [] , setOption = \_ _ -> Left "no options supported" } streamEditTest nam sep editor input expected = TestInstance { run = do let output = streamEdit sep editor input if (output == expected) then return (Finished Pass) else return (Finished $ TestSuite.Fail $ "got " <> show output <> " expected " <> show expected) , name = "streamEdit " ++ nam , tags = [] , options = [] , setOption = \_ _ -> Left "no options supported" } breakCapTest nam sep input expected = TestInstance { run = do let output = breakCap sep input if (output == expected) then return (Finished Pass) else return (Finished $ TestSuite.Fail $ "got " <> show output <> " expected " <> show expected) , name = "breakCap " ++ nam , tags = [] , options = [] , setOption = \_ _ -> Left "no options supported" } scinum :: Parser (Double, Integer) scinum = do m <- (fromIntegral :: Integer -> Double) <$> decimal _ <- chunk "E" e <- decimal return (m, e) offsetA :: Parser Int offsetA = getOffset <* chunk "A"
96f4c423b38cff5390e262b123d82a7499a03a9f996a5e12941b65da9d88f8e4
Martoon-00/toy-compiler
Exp.hs
-- | Keeps expressions related datatypes and utils # OPTIONS_GHC -F -pgmF autoexporter #
null
https://raw.githubusercontent.com/Martoon-00/toy-compiler/a325d56c367bbb673608d283197fcd51cf5960fa/src/Toy/Exp.hs
haskell
| Keeps expressions related datatypes and utils
# OPTIONS_GHC -F -pgmF autoexporter #
e15d3b2fd4d89b6a61dc10d459af339662b04b4e91623a92caa7fb0146f1f490
ocaml/ocaml
pr6993_bad.ml
(* TEST * expect *) type (_, _) eqp = Y : ('a, 'a) eqp | N : string -> ('a, 'b) eqp let f : ('a list, 'a) eqp -> unit = function N s -> print_string s;; module rec A : sig type t = B.t list end = struct type t = B.t list end and B : sig type t val eq : (B.t list, t) eqp end = struct type t = A.t let eq = Y end;; f B.eq;; [%%expect{| type (_, _) eqp = Y : ('a, 'a) eqp | N : string -> ('a, 'b) eqp Line 2, characters 36-66: 2 | let f : ('a list, 'a) eqp -> unit = function N s -> print_string s;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: Y val f : ('a list, 'a) eqp -> unit = <fun> module rec A : sig type t = B.t list end and B : sig type t val eq : (B.t list, t) eqp end Exception: Match_failure ("", 2, 36). |}];;
null
https://raw.githubusercontent.com/ocaml/ocaml/d71ea3d089ae3c338b8b6e2fb7beb08908076c7a/testsuite/tests/typing-gadts/pr6993_bad.ml
ocaml
TEST * expect
type (_, _) eqp = Y : ('a, 'a) eqp | N : string -> ('a, 'b) eqp let f : ('a list, 'a) eqp -> unit = function N s -> print_string s;; module rec A : sig type t = B.t list end = struct type t = B.t list end and B : sig type t val eq : (B.t list, t) eqp end = struct type t = A.t let eq = Y end;; f B.eq;; [%%expect{| type (_, _) eqp = Y : ('a, 'a) eqp | N : string -> ('a, 'b) eqp Line 2, characters 36-66: 2 | let f : ('a list, 'a) eqp -> unit = function N s -> print_string s;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: Y val f : ('a list, 'a) eqp -> unit = <fun> module rec A : sig type t = B.t list end and B : sig type t val eq : (B.t list, t) eqp end Exception: Match_failure ("", 2, 36). |}];;
351bec0b5e391783623cabfa75e4690409ff3e3aad7a0de88b3072169e999bb2
appleshan/cl-http
cl-http-70-206.lisp
-*- Mode : LISP ; Syntax : Ansi - common - lisp ; Package : HTTP ; Base : 10 ; Patch - File : T -*- Patch file for CL - HTTP version 70.206 ;;; Reason: Make STANDARDIZE-LINE-BREAKS work on the lisp machine. ;;; Function ( FLAVOR : METHOD TCP::ASCII - OUTPUT - MODE SI : BUFFERED - OUTPUT - CHARACTER - STREAM ): Required for standardize line ;;; breaks to work on the lisp machine. Function ( CLOS : METHOD HTTP::STANDARDIZE - LINE - BREAKS ( FS : LMFS - PATHNAME ) : AROUND ): expunge LMFS directories . Function ( CLOS : METHOD HTTP::STANDARDIZE - LINE - BREAKS ( FS : LOGICAL - PATHNAME ) : AROUND ): Expunge LMFS directories . ;;; Function WWW-UTILS::%PATHNAME-DIRECTORY-P: - ;;; Function WWW-UTILS:PATHNAME-DIRECTORY-P: update ;;; Function HTML4.0::%NOTE-IMAGE: - ;;; Function HTML4.0::IMAGE: new ;;; Variable HTML4.0:*DTD-VERSION*: update. ;;; Function HTML4.0:DECLARE-HTML-VERSION: update. ;;; Variable HTML4.0::*STRICT-DTD*: new ;;; Function HTML4.0:WITH-HTML-DOCUMENT: new ;;; Function HTML4.0::WITH-DEPRECATION-CHECKING: new ;;; Function HTML4.0::ENUMERATING-ITEM: new ;;; Function HTML4.0::WITH-ENUMERATION: new ;;; Function HTML4.0::ENUMERATE-ITEM-LIST: new Written by , 8/23/05 18:57:00 while running on FUJI - VLM from FUJI:/usr / lib / symbolics / Plus - CL - HTTP - A - CSAIL-8 - 5.vlod with Open Genera 2.0 , Genera 8.5 , Lock Simple 437.0 , Version Control 405.0 , Compare Merge 404.0 , VC Documentation 401.0 , Logical Pathnames Translation Files NEWEST , Metering 444.0 , Metering Substrate 444.1 , Conversion Tools 436.0 , Hacks 440.0 , CLIM 72.0 , Genera CLIM 72.0 , CLX CLIM 72.0 , PostScript CLIM 72.0 , CLIM Demo 72.0 , CLIM Documentation 72.0 , Experimental Genera 8 5 Patches 1.0 , Genera 8 5 System Patches 1.40 , 8 5 Support Patches 1.0 , Genera 8 5 Metering Patches 1.0 , 8 5 , Genera 8 5 Jericho Patches 1.0 , 8 5 , Genera 8 5 , 8 5 Statice Runtime Patches 1.0 , Genera 8 5 Statice Patches 1.0 , Genera 8 5 Statice Server Patches 1.0 , Genera 8 5 Statice Documentation Patches 1.0 , 8 5 Clim Patches 1.3 , Genera 8 5 Patches 1.0 , Genera 8 5 Postscript Clim Patches 1.0 , Genera 8 5 Clx Clim Patches 1.0 , 8 5 Clim Doc Patches 1.0 , Genera 8 5 Clim Demo Patches 1.0 , 8 5 Color Patches 1.1 , Genera 8 5 Images Patches 1.0 , 8 5 Color Demo Patches 1.0 , Genera 8 5 Image Substrate Patches 1.0 , 8 5 Lock Simple Patches 1.0 , Genera 8 5 Concordia Patches 1.2 , 8 5 , Genera 8 5 C Patches 1.0 , 8 5 , Genera 8 5 Fortran Patches 1.0 , MAC 415.2 , MacIvory Support 447.0 , MacIvory Development 434.0 , Color 427.1 , Graphics Support 431.0 , Genera Extensions 16.0 , Essential Image Substrate 433.0 , Color System Documentation 10.0 , SGD Book Design 10.0 , Color Demo 422.0 , Images 431.2 , Image Substrate 440.4 , Statice Runtime 466.1 , Statice 466.0 , Statice Browser 466.0 , Statice Server 466.2 , Statice Documentation 426.0 , Symbolics Concordia 444.0 , Graphic Editor 440.0 , Graphic Editing 441.0 , Bitmap Editor 441.0 , Graphic Editing Documentation 432.0 , Postscript 436.0 , Concordia Documentation 432.0 , , , Joshua Metering 206.0 , Jericho 237.0 , C 440.0 , , 438.0 , , Lalr 1 434.0 , Context Free Grammar 439.0 , Context Free Grammar Package 439.0 , C Runtime 438.0 , Compiler Tools Package 434.0 , Compiler Tools Runtime 434.0 , C Packages 436.0 , Syntax Editor Runtime 434.0 , C Library Headers 434 , Compiler Tools Development 435.0 , Compiler Tools Debugger 434.0 , C Documentation 426.0 , Syntax Editor Support 434.0 , LL-1 support system 438.0 , Fortran 434.0 , Fortran Runtime 434.0 , Fortran Package 434.0 , , Pascal 433.0 , , Pascal Package 434.0 , , HTTP Server 70.205 , Showable Procedures 36.3 , Binary Tree 34.0 , Experimental W3 Presentation System 8.2 , CL - HTTP Server Interface 54.0 , HTTP Proxy Server 6.34 , HTTP Client Substrate 4.23 , W4 Constraint - Guide Web Walker 45.14 , HTTP Client 51.9 , Ivory Revision 5 , VLM Debugger 329 , Genera program 8.18 , DEC OSF/1 V4.0 ( Rev. 110 ) , 1728x1062 24 - bit TRUE - COLOR X Screen FUJI:1.0 with 224 Genera fonts ( The Olivetti & Oracle Research Laboratory R3323 ) , Machine serial number -2142637960 , ;;; Patch TCP hang on close when client drops connection. (from HTTP:LISPM;SERVER;TCP-PATCH-HANG-ON-CLOSE.LISP.10), ;;; Prevent reset of input buffer on tcp reset by HTTP servers. (from HTTP:LISPM;W4;RECEIVE-TCP-SEGMENT-PATCH.LISP.7), Get Xauthority pathname from user namespace object . ( from W:>jcma > fixes > xauthority - pathname.lisp.2 ) , Domain ad host patch ( from > domain - ad - host - patch.lisp.21 ) , Background dns refreshing ( from > background - dns - refreshing ) . Patch file for CL - HTTP version 70.206 Written by , 8/23/05 21:19:03 while running on FUJI - VLM from FUJI:/usr / lib / symbolics / Plus - CL - HTTP - A - CSAIL-8 - 5.vlod with Open Genera 2.0 , Genera 8.5 , Lock Simple 437.0 , Version Control 405.0 , Compare Merge 404.0 , VC Documentation 401.0 , Logical Pathnames Translation Files NEWEST , Metering 444.0 , Metering Substrate 444.1 , Conversion Tools 436.0 , Hacks 440.0 , CLIM 72.0 , Genera CLIM 72.0 , CLX CLIM 72.0 , PostScript CLIM 72.0 , CLIM Demo 72.0 , CLIM Documentation 72.0 , Experimental Genera 8 5 Patches 1.0 , Genera 8 5 System Patches 1.40 , 8 5 Support Patches 1.0 , Genera 8 5 Metering Patches 1.0 , 8 5 , Genera 8 5 Jericho Patches 1.0 , 8 5 , Genera 8 5 , 8 5 Statice Runtime Patches 1.0 , Genera 8 5 Statice Patches 1.0 , Genera 8 5 Statice Server Patches 1.0 , Genera 8 5 Statice Documentation Patches 1.0 , 8 5 Clim Patches 1.3 , Genera 8 5 Patches 1.0 , Genera 8 5 Postscript Clim Patches 1.0 , Genera 8 5 Clx Clim Patches 1.0 , 8 5 Clim Doc Patches 1.0 , Genera 8 5 Clim Demo Patches 1.0 , 8 5 Color Patches 1.1 , Genera 8 5 Images Patches 1.0 , 8 5 Color Demo Patches 1.0 , Genera 8 5 Image Substrate Patches 1.0 , 8 5 Lock Simple Patches 1.0 , Genera 8 5 Concordia Patches 1.2 , 8 5 , Genera 8 5 C Patches 1.0 , 8 5 , Genera 8 5 Fortran Patches 1.0 , MAC 415.2 , MacIvory Support 447.0 , MacIvory Development 434.0 , Color 427.1 , Graphics Support 431.0 , Genera Extensions 16.0 , Essential Image Substrate 433.0 , Color System Documentation 10.0 , SGD Book Design 10.0 , Color Demo 422.0 , Images 431.2 , Image Substrate 440.4 , Statice Runtime 466.1 , Statice 466.0 , Statice Browser 466.0 , Statice Server 466.2 , Statice Documentation 426.0 , Symbolics Concordia 444.0 , Graphic Editor 440.0 , Graphic Editing 441.0 , Bitmap Editor 441.0 , Graphic Editing Documentation 432.0 , Postscript 436.0 , Concordia Documentation 432.0 , , , Joshua Metering 206.0 , Jericho 237.0 , C 440.0 , , 438.0 , , Lalr 1 434.0 , Context Free Grammar 439.0 , Context Free Grammar Package 439.0 , C Runtime 438.0 , Compiler Tools Package 434.0 , Compiler Tools Runtime 434.0 , C Packages 436.0 , Syntax Editor Runtime 434.0 , C Library Headers 434 , Compiler Tools Development 435.0 , Compiler Tools Debugger 434.0 , C Documentation 426.0 , Syntax Editor Support 434.0 , LL-1 support system 438.0 , Fortran 434.0 , Fortran Runtime 434.0 , Fortran Package 434.0 , , Pascal 433.0 , , Pascal Package 434.0 , , HTTP Server 70.205 , Showable Procedures 36.3 , Binary Tree 34.0 , Experimental W3 Presentation System 8.2 , CL - HTTP Server Interface 54.0 , HTTP Proxy Server 6.34 , HTTP Client Substrate 4.23 , W4 Constraint - Guide Web Walker 45.14 , HTTP Client 51.9 , Ivory Revision 5 , VLM Debugger 329 , Genera program 8.18 , DEC OSF/1 V4.0 ( Rev. 110 ) , 1728x1062 24 - bit TRUE - COLOR X Screen FUJI:1.0 with 224 Genera fonts ( The Olivetti & Oracle Research Laboratory R3323 ) , Machine serial number -2142637960 , ;;; Patch TCP hang on close when client drops connection. (from HTTP:LISPM;SERVER;TCP-PATCH-HANG-ON-CLOSE.LISP.10), ;;; Prevent reset of input buffer on tcp reset by HTTP servers. (from HTTP:LISPM;W4;RECEIVE-TCP-SEGMENT-PATCH.LISP.7), Get Xauthority pathname from user namespace object . ( from W:>jcma > fixes > xauthority - pathname.lisp.2 ) , Domain ad host patch ( from > domain - ad - host - patch.lisp.21 ) , Background dns refreshing ( from > background - dns - refreshing ) . Patch file for CL - HTTP version 70.206 Written by , 8/23/05 18:59:41 while running on FUJI - VLM from FUJI:/usr / lib / symbolics / Plus - CL - HTTP - A - CSAIL-8 - 5.vlod with Open Genera 2.0 , Genera 8.5 , Lock Simple 437.0 , Version Control 405.0 , Compare Merge 404.0 , VC Documentation 401.0 , Logical Pathnames Translation Files NEWEST , Metering 444.0 , Metering Substrate 444.1 , Conversion Tools 436.0 , Hacks 440.0 , CLIM 72.0 , Genera CLIM 72.0 , CLX CLIM 72.0 , PostScript CLIM 72.0 , CLIM Demo 72.0 , CLIM Documentation 72.0 , Experimental Genera 8 5 Patches 1.0 , Genera 8 5 System Patches 1.40 , 8 5 Support Patches 1.0 , Genera 8 5 Metering Patches 1.0 , 8 5 , Genera 8 5 Jericho Patches 1.0 , 8 5 , Genera 8 5 , 8 5 Statice Runtime Patches 1.0 , Genera 8 5 Statice Patches 1.0 , Genera 8 5 Statice Server Patches 1.0 , Genera 8 5 Statice Documentation Patches 1.0 , 8 5 Clim Patches 1.3 , Genera 8 5 Patches 1.0 , Genera 8 5 Postscript Clim Patches 1.0 , Genera 8 5 Clx Clim Patches 1.0 , 8 5 Clim Doc Patches 1.0 , Genera 8 5 Clim Demo Patches 1.0 , 8 5 Color Patches 1.1 , Genera 8 5 Images Patches 1.0 , 8 5 Color Demo Patches 1.0 , Genera 8 5 Image Substrate Patches 1.0 , 8 5 Lock Simple Patches 1.0 , Genera 8 5 Concordia Patches 1.2 , 8 5 , Genera 8 5 C Patches 1.0 , 8 5 , Genera 8 5 Fortran Patches 1.0 , MAC 415.2 , MacIvory Support 447.0 , MacIvory Development 434.0 , Color 427.1 , Graphics Support 431.0 , Genera Extensions 16.0 , Essential Image Substrate 433.0 , Color System Documentation 10.0 , SGD Book Design 10.0 , Color Demo 422.0 , Images 431.2 , Image Substrate 440.4 , Statice Runtime 466.1 , Statice 466.0 , Statice Browser 466.0 , Statice Server 466.2 , Statice Documentation 426.0 , Symbolics Concordia 444.0 , Graphic Editor 440.0 , Graphic Editing 441.0 , Bitmap Editor 441.0 , Graphic Editing Documentation 432.0 , Postscript 436.0 , Concordia Documentation 432.0 , , , Joshua Metering 206.0 , Jericho 237.0 , C 440.0 , , 438.0 , , Lalr 1 434.0 , Context Free Grammar 439.0 , Context Free Grammar Package 439.0 , C Runtime 438.0 , Compiler Tools Package 434.0 , Compiler Tools Runtime 434.0 , C Packages 436.0 , Syntax Editor Runtime 434.0 , C Library Headers 434 , Compiler Tools Development 435.0 , Compiler Tools Debugger 434.0 , C Documentation 426.0 , Syntax Editor Support 434.0 , LL-1 support system 438.0 , Fortran 434.0 , Fortran Runtime 434.0 , Fortran Package 434.0 , , Pascal 433.0 , , Pascal Package 434.0 , , HTTP Server 70.205 , Showable Procedures 36.3 , Binary Tree 34.0 , Experimental W3 Presentation System 8.2 , CL - HTTP Server Interface 54.0 , HTTP Proxy Server 6.34 , HTTP Client Substrate 4.23 , W4 Constraint - Guide Web Walker 45.14 , HTTP Client 51.9 , Ivory Revision 5 , VLM Debugger 329 , Genera program 8.18 , DEC OSF/1 V4.0 ( Rev. 110 ) , 1728x1062 24 - bit TRUE - COLOR X Screen FUJI:1.0 with 224 Genera fonts ( The Olivetti & Oracle Research Laboratory R3323 ) , Machine serial number -2142637960 , ;;; Patch TCP hang on close when client drops connection. (from HTTP:LISPM;SERVER;TCP-PATCH-HANG-ON-CLOSE.LISP.10), ;;; Prevent reset of input buffer on tcp reset by HTTP servers. (from HTTP:LISPM;W4;RECEIVE-TCP-SEGMENT-PATCH.LISP.7), Get Xauthority pathname from user namespace object . ( from W:>jcma > fixes > xauthority - pathname.lisp.2 ) , Domain ad host patch ( from > domain - ad - host - patch.lisp.21 ) , Background dns refreshing ( from > background - dns - refreshing ) . (SCT:FILES-PATCHED-IN-THIS-PATCH-FILE "HTTP:LISPM;SERVER;LISPM.LISP.522" "HTTP:LISPM;SERVER;LISPM.LISP.523" "HTTP:LISPM;SERVER;LISPM.LISP.526" "HTTP:SERVER;HTML4.LISP.43" "HTTP:SERVER;HTML4.LISP.44" "HTTP:SERVER;HTML4.LISP.46" "HTTP:SERVER;HTML4.LISP.49" "HTTP:SERVER;HTML4.LISP.50") ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;LISPM.LISP.522") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: WWW-UTILS; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:fix :roman :normal);-*-") ;; Enables standardize line breaks to work on the lisp machine (scl:defmethod (tcp::ascii-output-mode si:buffered-output-character-stream) () scl:self) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;LISPM.LISP.523") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: WWW-UTILS; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:fix :roman :normal);-*-") (defmethod http::standardize-line-breaks :around ((pathname fs:lmfs-pathname) &optional standard-line-break stream) (call-next-method pathname standard-line-break stream) (if (pathname-directory-p pathname) (fs:expunge-directory pathname))) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;LISPM.LISP.523") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: WWW-UTILS; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:fix :roman :normal);-*-") (defmethod http::standardize-line-breaks :around ((pathname logical-pathname) &optional standard-line-break stream) (call-next-method pathname standard-line-break stream) (if (and (pathname-directory-p pathname) (typep (http::translated-pathname pathname) 'fs:lmfs-pathname)) (fs:expunge-directory pathname))) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;LISPM.LISP.526") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: WWW-UTILS; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:fix :roman :normal);-*-") (defun %pathname-directory-p (pathname) (let ((p (pathname pathname))) (and (null (pathname-name p)) (null (pathname-type p)) (null (pathname-version p))))) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;LISPM.LISP.526") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: WWW-UTILS; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:fix :roman :normal);-*-") (defun pathname-directory-p (pathname) (let ((path (pathname pathname))) (or (%pathname-directory-p path) (%pathname-directory-file-p path)))) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.43") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (eval-when (load eval compile) (unexport 'html3.2:image :html4.0) (shadow 'html3.2:image :html4.0) ) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.43") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (declaim (inline image)) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.43") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (define image (image-url alternative-text &key alignment accept-coordinates-at-url client-side-image-map border vertical-space horizontal-space width height description class id title style language direction events (stream *output-stream*)) (%note-image stream image-url alternative-text alignment accept-coordinates-at-url client-side-image-map border vertical-space horizontal-space width height description class id title style language direction events)) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.43") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (setf (documentation 'image 'function) "IMAGE-URL is the URL for an image and ALTERNATIVE-TEXT is the text to display when the image is not loaded. ACCEPT-COORDINATES-URL can be: * URL to which coordinates will be returned when the user clicks on the image. * T, indicating that returned coordinates should go to a search URL version of IMAGE-URL * :NO-URL, indicating not to emit an anchor for accepting the returns but to mark the IMG as a coordinate search. CLIENT-SIDE-IMAGE-MAP indicates the client side image map to use. Normally, this is a named URL (/url.html#map-name) and often, all client side image maps are served from a single url. The function WRITE-CLIENT-SIDE-IMAGE-MAP writes a client side image map from a server-side image map URL (CERN or NCSA formats). Allow browsers to layout the display before the image has loaded and thus eliminate the delay for the user otherwise incurred. WIDTH is width of the image in pixels. HEIGHT is the height of the image in pixels. DESCRIPTION provides a longer description of the image which supplements the short one in alternative-text. CLASS is the class for the element ID is an element identifier. TITLE is a string used as an element title. STYLE denotes the style sheet to use. LANGUAGE is the two-digit language code for the displayed content (see RFC 1766) DIRECTION is ht base directionality of neutral text and can be either :LEFT-TO-RIGHT or :RIGHT-TO-LEFT. EVENTS are a set of image related events. ALIGNMENT (deprecated) can be: HTML2 Arugments TOP -- align with the tallest item on the line. MIDDLE -- align with the baseline with the middle of the image. BOTTOM -- align with the baseline of the current line with the image. Text Flow Options LEFT -- float down and over to the next available space on the left margin, and subsequent text wraps around the right side of the image. RIGHT -- float down and over to the next available space on the right margin, and subsequent text wraps around the left side of the image. Semi-Random Options TEXTTOP -- align the image top with the top of the current line. ABSMIDDLE -- aling the middle of the image with the middle of the current line. ABSBOTTOM -- align the image bottom with the bottom of the current line. BORDER (deprecated) is an integer indicating the thickness of the border with which to surround the image. VERTICAL-SPACE (deprecated) is an integer indicating the amount of vertical space above and below a floating image. HORIZONTAL-SPACE (deprecated) is an integer indicating the amount of horizontal space above and below a floating image.") ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.43") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (eval-when (load) (export (intern "IMAGE" :html4.0))) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.44") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") ;;;------------------------------------------------------------------- ;;; ;;; DOCUMENT LEVEL OPERATIONS ;;; (defconstant *dtd-version* "-//W3C//DTD HTML 4.01//EN") ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.44") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (define declare-html-version (&optional (stream *output-stream*) (dtd-version :frameset)) "Declares the document type as the current HTML generation DTD. All HTML 4.0 must declare the document type definition version. DTD-VERSION can be any of: :STRICT - includes all elements that have not been deprecated and do not appear in frameset documents. :TRANSITIONAL - includes everything is the STRICT DTD plus deprecated elements and attributes. :FRAMESET - includes everything in TRANSITIONAL plus frames." (when dtd-version (%issue-command ("!DOCTYPE HTML PUBLIC" stream :fresh-line t :trailing-line t) (ecase dtd-version ((:frameset t) (fast-format stream " ~S ~S" "-//W3C//DTD HTML 4.0.1 Frameset//EN" "")) (:strict (fast-format stream " ~S ~S" *dtd-version* "")) (:transitional (fast-format stream " ~S ~S" "-//W3C//DTD HTML 4.0.1 Transitional//EN" "")))))) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.44") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") ;;;------------------------------------------------------------------- ;;; ;;; DOCUMENT LEVEL OPERATIONS ;;; (defvar *strict-dtd* nil "Non-null when generating strict HTML 4.") ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.44") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (define-macro with-html-document ((&key (stream '*output-stream*) (declare-dtd-version-p :frameset) (language nil language-supplied-p) (direction nil direction-supplied-p)) &body body) "Asserts the contents of BODY is an HTML document. DECLARE-DTD-VERSION-P will declare the version of the DTD implemented by the current generation package. This should be :STRICT whenever generation strictly conforms to the HTML version associated with the macro WITH-HTML-DOCUMENT. HTML 4.0.1 offers three DTD versions. Consequently, DECLARE-DTD-VERSION-P can be any of :FRAMESET, :TRANSITIONAL, or :STRICT. A value of T is interpreted as :FRAMESET. DECLARE-DTD-VERSION-P should always be NIL, whenever extension tags or features outside these specifications are used. LANGUAGE is the two-digit language code for the displayed content (see RFC 1766) DIRECTION is ht base directionality of neutral text and can be either :LEFT-TO-RIGHT or :RIGHT-TO-LEFT." (let* ((args `(,.(when language-supplied-p `((%write-language-argument ,stream ,language))) ,.(when direction-supplied-p `((%write-direction-argument ,stream ,direction))))) (version (ecase declare-dtd-version-p ((nil) nil) ((t :frameset) :frameset) (:transitional :transitional) (:strict :strict))) (version-declaration (ecase version ((nil) nil) (:frameset `(declare-html-version ,stream :frameset)) (:transitional `(declare-html-version ,stream :transitional)) (:strict `(declare-html-version ,stream :strict))))) (if version-declaration `(let ((*strict-dtd* (eq :strict ,version))) ,version-declaration (%with-environment ("HTML" :stream ,stream) ,(when args (cons 'progn args)) . ,body)) `(%with-environment ("HTML" :stream ,stream) ,(when args (cons 'progn args)) . ,body)))) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.46") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (defmacro %with-deprecation-checking ((function condition &optional argument value value-supplied-p format-string format-args) &body body) `(progn (when ,(if condition `(and *strict-dtd* ,condition) '*strict-dtd*) ,(cond (argument `(cerror "Continue HTML Generation" "In HTML 4.0.1, for ~S the argument, ~S, ~:[~; with value, ~S,~] is deprecated.~:[~;~&~:*~?~]" ,function ,argument ,value-supplied-p ,value ,format-string ,format-args)) (function `(cerror "Continue HTML Generation" "In HTML 4.0.1, ~S is deprecated.~:[~;~&~:*~?~]" ,function ,format-string ,format-args)) (t `(cerror "Continue HTML Generation" ,format-string ,@format-args)))) ,@body)) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.46") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (define-macro with-deprecation-checking ((function &key argument (value nil value-supplied-p) condition format-string format-args) &body body) `(%with-deprecation-checking (',function ,condition ',argument ,value ,value-supplied-p ,format-string ,@format-args) ,@body)) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.49") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (eval-when (load eval compile) (mapc #'(lambda (x) (unexport x :html4.0) (shadow x :html4.0)) '(html3.2:with-enumeration html3.2:enumerating-item html3.2:enumerate-item-list))) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.49") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (PROGN (defun enumerate-itemized-item (stream continuation icon-url type id class language direction title style events) (declare (ignore icon-url)) (%issue-command ("LI" stream :fresh-line t) (html3.2::%get-bullet-style type html3.2::*itemize-bullet-styles*) (when (or id class language direction title style events) (%write-standard-command-arguments stream id class language direction title style events))) (multiple-value-prog1 (funcall continuation stream) (fresh-line stream))) (defun enumerate-enumerated-item (stream continuation icon-url type id class language direction title style events) (declare (ignore icon-url)) (%issue-command ("LI" stream :fresh-line t) (html3.2::%get-bullet-style type html3.2::*enumerate-bullet-styles*) (when (or id class language direction title style events) (%write-standard-command-arguments stream id class language direction title style events))) (multiple-value-prog1 (funcall continuation stream) (fresh-line stream))) (defun enumerate-normal-item (stream continuation icon-url head id class language direction title style events) (declare (ignore head)) (%issue-command ("LI" stream :fresh-line t) (when (or id class language direction title style events) (%write-standard-command-arguments stream id class language direction title style events))) (when icon-url (image icon-url "o" :stream stream) (write-char #\space stream)) (funcall continuation stream) (fresh-line stream)) Does not provide standard html 4 parameters for DD -- 8/25/05 JCMa (defun enumerate-definition-item (stream continuation icon-url head id class language direction title style events) (flet ((write-dd (stream) (issue-command "DD" stream nil) (write-char #\space stream))) (declare (inline write-dd)) (fresh-line stream) (%issue-command ("DT" stream :fresh-line t) (when (or id class language direction title style events) (%write-standard-command-arguments stream id class language direction title style events))) (when icon-url (image icon-url "o" :stream stream) (write-char #\space stream)) (etypecase head (null nil) (string (write-string head stream) (write-dd stream)) (cons (dolist (item head) (write item :stream stream)) (write-dd stream)) (function (funcall head stream) (write-dd stream))) (funcall continuation stream))) ) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.49") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") Does not implement the VALUE parameter -- 8/25/05 JCMa (define-macro enumerating-item ((stream &key icon-url head type id class language direction title style events) &body body) "Enumerates an item on STREAM according to the enclosing enumeration style. BODY generates the body of the item whereas icon-url head type control the item's header. TYPE (deprecated) can be provided for the styles :ENUMERATE and :ITEMIZE to override the default bullet given by the enclosing WITH-ENUMERATION. For the style ENUMERATE, TYPE can be any of :CAPITAL-LETTERS, :SMALL-LETTERS, :LARGE-ROMAN, :SMALL-ROMAN, or :ARABIC (the default). For the style :ITEMIZE, TYPE can be any of :SOLID-DISC, :CIRCLE, or :SQUARE. HEAD specifies the heading for an item in the :DEFINITION style. Head can be a string, a list of strings or a function called on STREAM. ICON-URL is available for the styles :DEFINITION, :DIRECTORY (deprecated), and :MENU (deprecated). When provided, an image is emitted at the start of the item using the URL supplied as the value of ICON-URL. CLASS is the class for the element ID is an element identifier. TITLE is a string used as an element title. STYLE denotes the style sheet to use. LANGUAGE is the two-digit language code for the displayed content (see RFC 1766) DIRECTION is ht base directionality of neutral text and can be either :LEFT-TO-RIGHT or :RIGHT-TO-LEFT." `(flet ((continuation (,stream) ,@body)) (declare (dynamic-extent #'continuation)) (funcall *enumeration-function* ,stream #'continuation ,icon-url ,(or head type) ,id ,class ,language ,direction ,title ,style ,events))) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.49") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (defun %enumeration-style-parameters (style type) (declare (values function tag type)) (case style (:itemize (values #'enumerate-itemized-item "UL" (html3.2::%get-bullet-style type html3.2::*itemize-bullet-styles*))) (:enumerate (values #'enumerate-enumerated-item "OL" (html3.2::%get-bullet-style type html3.2::*enumerate-bullet-styles*))) (:definition (values #'enumerate-definition-item "DL")) (:directory (with-deprecation-checking (with-enumeration :argument style :value style) (values #'enumerate-normal-item "DIR"))) ((:menu :plain) (with-deprecation-checking (with-enumeration :argument style :value style) (values #'enumerate-normal-item "MENU"))) (t (error "Unknown enumeration style, ~A." style)))) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.49") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (define-macro with-enumeration ((stream enumeration-style &key compact type start id class language direction title style events) &body body) "Establishes an enumeration environment using the style, STYLE, on STREAM. Within this environment, each item is emitted by generation code executed with the ENUMERATING-ITEM macro. ENUMERATION-STYLE can be :DEFINITION, :DIRECTORY (deprecated), :ENUMERATE :ITEMIZE :MENU (deprecated). You must use the ENUMERATING-ITEM from the same package for reliable results. TYPE (deprecated) allows the default styles of enumeration to be overridden for some styles. For the style :ENUMERATE, TYPE can be any of: :CAPITAL-LETTERS, :SMALL-LETTERS, :LARGE-ROMAN, :SMALL-ROMAN, or :ARABIC (the default). For the style :ITEMIZE, TYPE can be any of :SOLID-DISC, :CIRCLE, :SQUARE COMPACT (deprecated) advises the client to render lists in a more compact style. For the :ENUMERATE style, START (deprecated) can cause the enumeration to begin at a number other than the default 1. CLASS is the class for the element ID is an element identifier. TITLE is a string used as an element title. STYLE denotes the style sheet to use. LANGUAGE is the two-digit language code for the displayed content (see RFC 1766) DIRECTION is ht base directionality of neutral text and can be either :LEFT-TO-RIGHT or :RIGHT-TO-LEFT." (flet ((enumeration-arguments (compact start type) (let ((args nil)) (cond-every (compact (push `(,compact (with-deprecation-checking (with-enumeration :argument compact) (write-string " COMPACT" ,stream))) args)) (type (push `(,type (with-deprecation-checking (with-enumeration :argument type) (fast-format stream " TYPE=~A" ,type))) args)) (start (push `(,start (with-deprecation-checking (with-enumeration :argument start) (check-type ,start integer) (fast-format ,stream " START=~D" ,start))) args))) (when args `(cond-every ,.args))))) `(multiple-value-bind (*enumeration-function* tag enumeration-type) (%enumeration-style-parameters ,enumeration-style ,type) enumeration-type ;no compiler warning (%with-environment (tag :fresh-line t :stream ,stream) (progn ,(when (or id class language direction title style events) `(%write-standard-command-arguments ,stream ,id ,class ,language ,direction ,title ,style ,events)) ,(enumeration-arguments compact start type)) ,@body)))) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.49") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (define enumerate-item-list (item-list &key (enumeration-style :itemize) type compact id class language direction title style events (stream *output-stream*)) "Enumerates the elements of ITEM-LIST in STYLE on STREAM." (with-enumeration (stream enumeration-style :compact compact :type type :id id :class class :language language :direction direction :title title :style style :events events) (dolist (item item-list) (enumerating-item (stream) (write item :stream stream :escape nil))))) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.49") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (eval-when (load) (mapc #'(lambda (x) (export (intern x :html4.0))) '("WITH-ENUMERATION" "ENUMERATING-ITEM" "ENUMERATE-ITEM-LIST"))) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.50") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") ;; html spec says to always provide alternative text (defun %note-image (stream image-url alternative-text alignment accept-coordinates-at-url client-side-image-map border vertical-space horizontal-space width height description class id title style language direction events) (flet ((write-element (stream image-url alignment alternative-text accept-coordinates-at-url events) (flet ((alignment-value (alignment) (unless (member alignment *image-alignment-values*) (error "Unknown alignment, ~S, for an image." alignment)) (symbol-name alignment)) (write-integer-arg (stream option value) (check-type value integer) (%write-command-key-arg stream option value t))) (declare (inline alignment-value write-integer-arg)) ;; Automagically insert image sizes when algorithms available. (when (and image-url (not (or width height)) http:*image-sizes-default-automatically*) (multiple-value-setq (width height) (url:image-size image-url))) (%issue-command ("IMG" stream) (cond-every (image-url (%write-command-key-arg stream "SRC" image-url)) (alignment (with-deprecation-checking (image :argument alignment) (%write-command-key-arg stream "ALIGN" (alignment-value alignment)))) (alternative-text (check-type alternative-text string) (%write-command-key-arg stream "ALT" alternative-text)) (description (check-type description string) (%write-command-key-arg stream "LONGDESC" description)) (accept-coordinates-at-url (%write-command-key-arg stream "ISMAP")) (client-side-image-map (%write-command-key-arg stream "USEMAP" (url:name-string-without-search-suffix client-side-image-map nil))) (border (with-deprecation-checking (image :argument border) (write-integer-arg stream "BORDER" border))) (vertical-space (with-deprecation-checking (image :argument vertical-space) (write-integer-arg stream "VSPACE" vertical-space))) (horizontal-space (with-deprecation-checking (image :argument horizontal-space) (write-integer-arg stream "HSPACE" horizontal-space))) (width (write-integer-arg stream "WIDTH" width)) (height (write-integer-arg stream "HEIGHT" height)) ((or id class language direction title style events) (%write-standard-command-arguments stream id class language direction title style events))))))) (let ((url-string (url:name-string-without-search-suffix image-url nil))) (declare (dynamic-extent url-string)) (case accept-coordinates-at-url ((nil :no-url) (write-element stream url-string alignment alternative-text accept-coordinates-at-url events)) (t (with-anchor-noted (:reference (if (eq accept-coordinates-at-url t) url-string (url:name-string-without-search-suffix accept-coordinates-at-url nil)) :stream stream) (write-element stream url-string alignment alternative-text accept-coordinates-at-url events)))))))
null
https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/lispm/server/patch/cl-http-70/cl-http-70-206.lisp
lisp
Syntax : Ansi - common - lisp ; Package : HTTP ; Base : 10 ; Patch - File : T -*- Reason: Make STANDARDIZE-LINE-BREAKS work on the lisp machine. breaks to work on the lisp machine. Function WWW-UTILS::%PATHNAME-DIRECTORY-P: - Function WWW-UTILS:PATHNAME-DIRECTORY-P: update Function HTML4.0::%NOTE-IMAGE: - Function HTML4.0::IMAGE: new Variable HTML4.0:*DTD-VERSION*: update. Function HTML4.0:DECLARE-HTML-VERSION: update. Variable HTML4.0::*STRICT-DTD*: new Function HTML4.0:WITH-HTML-DOCUMENT: new Function HTML4.0::WITH-DEPRECATION-CHECKING: new Function HTML4.0::ENUMERATING-ITEM: new Function HTML4.0::WITH-ENUMERATION: new Function HTML4.0::ENUMERATE-ITEM-LIST: new Patch TCP hang on close when client drops connection. (from HTTP:LISPM;SERVER;TCP-PATCH-HANG-ON-CLOSE.LISP.10), Prevent reset of input buffer on tcp reset by HTTP servers. (from HTTP:LISPM;W4;RECEIVE-TCP-SEGMENT-PATCH.LISP.7), Patch TCP hang on close when client drops connection. (from HTTP:LISPM;SERVER;TCP-PATCH-HANG-ON-CLOSE.LISP.10), Prevent reset of input buffer on tcp reset by HTTP servers. (from HTTP:LISPM;W4;RECEIVE-TCP-SEGMENT-PATCH.LISP.7), Patch TCP hang on close when client drops connection. (from HTTP:LISPM;SERVER;TCP-PATCH-HANG-ON-CLOSE.LISP.10), Prevent reset of input buffer on tcp reset by HTTP servers. (from HTTP:LISPM;W4;RECEIVE-TCP-SEGMENT-PATCH.LISP.7), ======================== Enables standardize line breaks to work on the lisp machine ======================== ======================== ======================== ======================== ======================== ======================== ======================== ======================== ======================== ======================== ------------------------------------------------------------------- DOCUMENT LEVEL OPERATIONS ======================== ======================== ------------------------------------------------------------------- DOCUMENT LEVEL OPERATIONS ======================== ======================== ======================== ======================== ======================== ======================== ======================== ======================== no compiler warning ======================== ======================== ======================== html spec says to always provide alternative text Automagically insert image sizes when algorithms available.
Patch file for CL - HTTP version 70.206 Function ( FLAVOR : METHOD TCP::ASCII - OUTPUT - MODE SI : BUFFERED - OUTPUT - CHARACTER - STREAM ): Required for standardize line Function ( CLOS : METHOD HTTP::STANDARDIZE - LINE - BREAKS ( FS : LMFS - PATHNAME ) : AROUND ): expunge LMFS directories . Function ( CLOS : METHOD HTTP::STANDARDIZE - LINE - BREAKS ( FS : LOGICAL - PATHNAME ) : AROUND ): Expunge LMFS directories . Written by , 8/23/05 18:57:00 while running on FUJI - VLM from FUJI:/usr / lib / symbolics / Plus - CL - HTTP - A - CSAIL-8 - 5.vlod with Open Genera 2.0 , Genera 8.5 , Lock Simple 437.0 , Version Control 405.0 , Compare Merge 404.0 , VC Documentation 401.0 , Logical Pathnames Translation Files NEWEST , Metering 444.0 , Metering Substrate 444.1 , Conversion Tools 436.0 , Hacks 440.0 , CLIM 72.0 , Genera CLIM 72.0 , CLX CLIM 72.0 , PostScript CLIM 72.0 , CLIM Demo 72.0 , CLIM Documentation 72.0 , Experimental Genera 8 5 Patches 1.0 , Genera 8 5 System Patches 1.40 , 8 5 Support Patches 1.0 , Genera 8 5 Metering Patches 1.0 , 8 5 , Genera 8 5 Jericho Patches 1.0 , 8 5 , Genera 8 5 , 8 5 Statice Runtime Patches 1.0 , Genera 8 5 Statice Patches 1.0 , Genera 8 5 Statice Server Patches 1.0 , Genera 8 5 Statice Documentation Patches 1.0 , 8 5 Clim Patches 1.3 , Genera 8 5 Patches 1.0 , Genera 8 5 Postscript Clim Patches 1.0 , Genera 8 5 Clx Clim Patches 1.0 , 8 5 Clim Doc Patches 1.0 , Genera 8 5 Clim Demo Patches 1.0 , 8 5 Color Patches 1.1 , Genera 8 5 Images Patches 1.0 , 8 5 Color Demo Patches 1.0 , Genera 8 5 Image Substrate Patches 1.0 , 8 5 Lock Simple Patches 1.0 , Genera 8 5 Concordia Patches 1.2 , 8 5 , Genera 8 5 C Patches 1.0 , 8 5 , Genera 8 5 Fortran Patches 1.0 , MAC 415.2 , MacIvory Support 447.0 , MacIvory Development 434.0 , Color 427.1 , Graphics Support 431.0 , Genera Extensions 16.0 , Essential Image Substrate 433.0 , Color System Documentation 10.0 , SGD Book Design 10.0 , Color Demo 422.0 , Images 431.2 , Image Substrate 440.4 , Statice Runtime 466.1 , Statice 466.0 , Statice Browser 466.0 , Statice Server 466.2 , Statice Documentation 426.0 , Symbolics Concordia 444.0 , Graphic Editor 440.0 , Graphic Editing 441.0 , Bitmap Editor 441.0 , Graphic Editing Documentation 432.0 , Postscript 436.0 , Concordia Documentation 432.0 , , , Joshua Metering 206.0 , Jericho 237.0 , C 440.0 , , 438.0 , , Lalr 1 434.0 , Context Free Grammar 439.0 , Context Free Grammar Package 439.0 , C Runtime 438.0 , Compiler Tools Package 434.0 , Compiler Tools Runtime 434.0 , C Packages 436.0 , Syntax Editor Runtime 434.0 , C Library Headers 434 , Compiler Tools Development 435.0 , Compiler Tools Debugger 434.0 , C Documentation 426.0 , Syntax Editor Support 434.0 , LL-1 support system 438.0 , Fortran 434.0 , Fortran Runtime 434.0 , Fortran Package 434.0 , , Pascal 433.0 , , Pascal Package 434.0 , , HTTP Server 70.205 , Showable Procedures 36.3 , Binary Tree 34.0 , Experimental W3 Presentation System 8.2 , CL - HTTP Server Interface 54.0 , HTTP Proxy Server 6.34 , HTTP Client Substrate 4.23 , W4 Constraint - Guide Web Walker 45.14 , HTTP Client 51.9 , Ivory Revision 5 , VLM Debugger 329 , Genera program 8.18 , DEC OSF/1 V4.0 ( Rev. 110 ) , 1728x1062 24 - bit TRUE - COLOR X Screen FUJI:1.0 with 224 Genera fonts ( The Olivetti & Oracle Research Laboratory R3323 ) , Machine serial number -2142637960 , Get Xauthority pathname from user namespace object . ( from W:>jcma > fixes > xauthority - pathname.lisp.2 ) , Domain ad host patch ( from > domain - ad - host - patch.lisp.21 ) , Background dns refreshing ( from > background - dns - refreshing ) . Patch file for CL - HTTP version 70.206 Written by , 8/23/05 21:19:03 while running on FUJI - VLM from FUJI:/usr / lib / symbolics / Plus - CL - HTTP - A - CSAIL-8 - 5.vlod with Open Genera 2.0 , Genera 8.5 , Lock Simple 437.0 , Version Control 405.0 , Compare Merge 404.0 , VC Documentation 401.0 , Logical Pathnames Translation Files NEWEST , Metering 444.0 , Metering Substrate 444.1 , Conversion Tools 436.0 , Hacks 440.0 , CLIM 72.0 , Genera CLIM 72.0 , CLX CLIM 72.0 , PostScript CLIM 72.0 , CLIM Demo 72.0 , CLIM Documentation 72.0 , Experimental Genera 8 5 Patches 1.0 , Genera 8 5 System Patches 1.40 , 8 5 Support Patches 1.0 , Genera 8 5 Metering Patches 1.0 , 8 5 , Genera 8 5 Jericho Patches 1.0 , 8 5 , Genera 8 5 , 8 5 Statice Runtime Patches 1.0 , Genera 8 5 Statice Patches 1.0 , Genera 8 5 Statice Server Patches 1.0 , Genera 8 5 Statice Documentation Patches 1.0 , 8 5 Clim Patches 1.3 , Genera 8 5 Patches 1.0 , Genera 8 5 Postscript Clim Patches 1.0 , Genera 8 5 Clx Clim Patches 1.0 , 8 5 Clim Doc Patches 1.0 , Genera 8 5 Clim Demo Patches 1.0 , 8 5 Color Patches 1.1 , Genera 8 5 Images Patches 1.0 , 8 5 Color Demo Patches 1.0 , Genera 8 5 Image Substrate Patches 1.0 , 8 5 Lock Simple Patches 1.0 , Genera 8 5 Concordia Patches 1.2 , 8 5 , Genera 8 5 C Patches 1.0 , 8 5 , Genera 8 5 Fortran Patches 1.0 , MAC 415.2 , MacIvory Support 447.0 , MacIvory Development 434.0 , Color 427.1 , Graphics Support 431.0 , Genera Extensions 16.0 , Essential Image Substrate 433.0 , Color System Documentation 10.0 , SGD Book Design 10.0 , Color Demo 422.0 , Images 431.2 , Image Substrate 440.4 , Statice Runtime 466.1 , Statice 466.0 , Statice Browser 466.0 , Statice Server 466.2 , Statice Documentation 426.0 , Symbolics Concordia 444.0 , Graphic Editor 440.0 , Graphic Editing 441.0 , Bitmap Editor 441.0 , Graphic Editing Documentation 432.0 , Postscript 436.0 , Concordia Documentation 432.0 , , , Joshua Metering 206.0 , Jericho 237.0 , C 440.0 , , 438.0 , , Lalr 1 434.0 , Context Free Grammar 439.0 , Context Free Grammar Package 439.0 , C Runtime 438.0 , Compiler Tools Package 434.0 , Compiler Tools Runtime 434.0 , C Packages 436.0 , Syntax Editor Runtime 434.0 , C Library Headers 434 , Compiler Tools Development 435.0 , Compiler Tools Debugger 434.0 , C Documentation 426.0 , Syntax Editor Support 434.0 , LL-1 support system 438.0 , Fortran 434.0 , Fortran Runtime 434.0 , Fortran Package 434.0 , , Pascal 433.0 , , Pascal Package 434.0 , , HTTP Server 70.205 , Showable Procedures 36.3 , Binary Tree 34.0 , Experimental W3 Presentation System 8.2 , CL - HTTP Server Interface 54.0 , HTTP Proxy Server 6.34 , HTTP Client Substrate 4.23 , W4 Constraint - Guide Web Walker 45.14 , HTTP Client 51.9 , Ivory Revision 5 , VLM Debugger 329 , Genera program 8.18 , DEC OSF/1 V4.0 ( Rev. 110 ) , 1728x1062 24 - bit TRUE - COLOR X Screen FUJI:1.0 with 224 Genera fonts ( The Olivetti & Oracle Research Laboratory R3323 ) , Machine serial number -2142637960 , Get Xauthority pathname from user namespace object . ( from W:>jcma > fixes > xauthority - pathname.lisp.2 ) , Domain ad host patch ( from > domain - ad - host - patch.lisp.21 ) , Background dns refreshing ( from > background - dns - refreshing ) . Patch file for CL - HTTP version 70.206 Written by , 8/23/05 18:59:41 while running on FUJI - VLM from FUJI:/usr / lib / symbolics / Plus - CL - HTTP - A - CSAIL-8 - 5.vlod with Open Genera 2.0 , Genera 8.5 , Lock Simple 437.0 , Version Control 405.0 , Compare Merge 404.0 , VC Documentation 401.0 , Logical Pathnames Translation Files NEWEST , Metering 444.0 , Metering Substrate 444.1 , Conversion Tools 436.0 , Hacks 440.0 , CLIM 72.0 , Genera CLIM 72.0 , CLX CLIM 72.0 , PostScript CLIM 72.0 , CLIM Demo 72.0 , CLIM Documentation 72.0 , Experimental Genera 8 5 Patches 1.0 , Genera 8 5 System Patches 1.40 , 8 5 Support Patches 1.0 , Genera 8 5 Metering Patches 1.0 , 8 5 , Genera 8 5 Jericho Patches 1.0 , 8 5 , Genera 8 5 , 8 5 Statice Runtime Patches 1.0 , Genera 8 5 Statice Patches 1.0 , Genera 8 5 Statice Server Patches 1.0 , Genera 8 5 Statice Documentation Patches 1.0 , 8 5 Clim Patches 1.3 , Genera 8 5 Patches 1.0 , Genera 8 5 Postscript Clim Patches 1.0 , Genera 8 5 Clx Clim Patches 1.0 , 8 5 Clim Doc Patches 1.0 , Genera 8 5 Clim Demo Patches 1.0 , 8 5 Color Patches 1.1 , Genera 8 5 Images Patches 1.0 , 8 5 Color Demo Patches 1.0 , Genera 8 5 Image Substrate Patches 1.0 , 8 5 Lock Simple Patches 1.0 , Genera 8 5 Concordia Patches 1.2 , 8 5 , Genera 8 5 C Patches 1.0 , 8 5 , Genera 8 5 Fortran Patches 1.0 , MAC 415.2 , MacIvory Support 447.0 , MacIvory Development 434.0 , Color 427.1 , Graphics Support 431.0 , Genera Extensions 16.0 , Essential Image Substrate 433.0 , Color System Documentation 10.0 , SGD Book Design 10.0 , Color Demo 422.0 , Images 431.2 , Image Substrate 440.4 , Statice Runtime 466.1 , Statice 466.0 , Statice Browser 466.0 , Statice Server 466.2 , Statice Documentation 426.0 , Symbolics Concordia 444.0 , Graphic Editor 440.0 , Graphic Editing 441.0 , Bitmap Editor 441.0 , Graphic Editing Documentation 432.0 , Postscript 436.0 , Concordia Documentation 432.0 , , , Joshua Metering 206.0 , Jericho 237.0 , C 440.0 , , 438.0 , , Lalr 1 434.0 , Context Free Grammar 439.0 , Context Free Grammar Package 439.0 , C Runtime 438.0 , Compiler Tools Package 434.0 , Compiler Tools Runtime 434.0 , C Packages 436.0 , Syntax Editor Runtime 434.0 , C Library Headers 434 , Compiler Tools Development 435.0 , Compiler Tools Debugger 434.0 , C Documentation 426.0 , Syntax Editor Support 434.0 , LL-1 support system 438.0 , Fortran 434.0 , Fortran Runtime 434.0 , Fortran Package 434.0 , , Pascal 433.0 , , Pascal Package 434.0 , , HTTP Server 70.205 , Showable Procedures 36.3 , Binary Tree 34.0 , Experimental W3 Presentation System 8.2 , CL - HTTP Server Interface 54.0 , HTTP Proxy Server 6.34 , HTTP Client Substrate 4.23 , W4 Constraint - Guide Web Walker 45.14 , HTTP Client 51.9 , Ivory Revision 5 , VLM Debugger 329 , Genera program 8.18 , DEC OSF/1 V4.0 ( Rev. 110 ) , 1728x1062 24 - bit TRUE - COLOR X Screen FUJI:1.0 with 224 Genera fonts ( The Olivetti & Oracle Research Laboratory R3323 ) , Machine serial number -2142637960 , Get Xauthority pathname from user namespace object . ( from W:>jcma > fixes > xauthority - pathname.lisp.2 ) , Domain ad host patch ( from > domain - ad - host - patch.lisp.21 ) , Background dns refreshing ( from > background - dns - refreshing ) . (SCT:FILES-PATCHED-IN-THIS-PATCH-FILE "HTTP:LISPM;SERVER;LISPM.LISP.522" "HTTP:LISPM;SERVER;LISPM.LISP.523" "HTTP:LISPM;SERVER;LISPM.LISP.526" "HTTP:SERVER;HTML4.LISP.43" "HTTP:SERVER;HTML4.LISP.44" "HTTP:SERVER;HTML4.LISP.46" "HTTP:SERVER;HTML4.LISP.49" "HTTP:SERVER;HTML4.LISP.50") (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;LISPM.LISP.522") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: WWW-UTILS; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:fix :roman :normal);-*-") (scl:defmethod (tcp::ascii-output-mode si:buffered-output-character-stream) () scl:self) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;LISPM.LISP.523") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: WWW-UTILS; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:fix :roman :normal);-*-") (defmethod http::standardize-line-breaks :around ((pathname fs:lmfs-pathname) &optional standard-line-break stream) (call-next-method pathname standard-line-break stream) (if (pathname-directory-p pathname) (fs:expunge-directory pathname))) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;LISPM.LISP.523") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: WWW-UTILS; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:fix :roman :normal);-*-") (defmethod http::standardize-line-breaks :around ((pathname logical-pathname) &optional standard-line-break stream) (call-next-method pathname standard-line-break stream) (if (and (pathname-directory-p pathname) (typep (http::translated-pathname pathname) 'fs:lmfs-pathname)) (fs:expunge-directory pathname))) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;LISPM.LISP.526") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: WWW-UTILS; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:fix :roman :normal);-*-") (defun %pathname-directory-p (pathname) (let ((p (pathname pathname))) (and (null (pathname-name p)) (null (pathname-type p)) (null (pathname-version p))))) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;LISPM.LISP.526") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: WWW-UTILS; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:fix :roman :normal);-*-") (defun pathname-directory-p (pathname) (let ((path (pathname pathname))) (or (%pathname-directory-p path) (%pathname-directory-file-p path)))) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.43") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (eval-when (load eval compile) (unexport 'html3.2:image :html4.0) (shadow 'html3.2:image :html4.0) ) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.43") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (declaim (inline image)) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.43") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (define image (image-url alternative-text &key alignment accept-coordinates-at-url client-side-image-map border vertical-space horizontal-space width height description class id title style language direction events (stream *output-stream*)) (%note-image stream image-url alternative-text alignment accept-coordinates-at-url client-side-image-map border vertical-space horizontal-space width height description class id title style language direction events)) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.43") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (setf (documentation 'image 'function) "IMAGE-URL is the URL for an image and ALTERNATIVE-TEXT is the text to display when the image is not loaded. ACCEPT-COORDINATES-URL can be: * URL to which coordinates will be returned when the user clicks on the image. * T, indicating that returned coordinates should go to a search URL version of IMAGE-URL * :NO-URL, indicating not to emit an anchor for accepting the returns but to mark the IMG as a coordinate search. CLIENT-SIDE-IMAGE-MAP indicates the client side image map to use. Normally, this is a named URL (/url.html#map-name) and often, all client side image maps are served from a single url. The function WRITE-CLIENT-SIDE-IMAGE-MAP writes a client side image map from a server-side image map URL (CERN or NCSA formats). Allow browsers to layout the display before the image has loaded and thus eliminate the delay for the user otherwise incurred. WIDTH is width of the image in pixels. HEIGHT is the height of the image in pixels. DESCRIPTION provides a longer description of the image which supplements the short one in alternative-text. CLASS is the class for the element ID is an element identifier. TITLE is a string used as an element title. STYLE denotes the style sheet to use. LANGUAGE is the two-digit language code for the displayed content (see RFC 1766) DIRECTION is ht base directionality of neutral text and can be either :LEFT-TO-RIGHT or :RIGHT-TO-LEFT. EVENTS are a set of image related events. ALIGNMENT (deprecated) can be: HTML2 Arugments TOP -- align with the tallest item on the line. MIDDLE -- align with the baseline with the middle of the image. BOTTOM -- align with the baseline of the current line with the image. Text Flow Options LEFT -- float down and over to the next available space on the left margin, and subsequent text wraps around the right side of the image. RIGHT -- float down and over to the next available space on the right margin, and subsequent text wraps around the left side of the image. Semi-Random Options TEXTTOP -- align the image top with the top of the current line. ABSMIDDLE -- aling the middle of the image with the middle of the current line. ABSBOTTOM -- align the image bottom with the bottom of the current line. BORDER (deprecated) is an integer indicating the thickness of the border with which to surround the image. VERTICAL-SPACE (deprecated) is an integer indicating the amount of vertical space above and below a floating image. HORIZONTAL-SPACE (deprecated) is an integer indicating the amount of horizontal space above and below a floating image.") (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.43") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (eval-when (load) (export (intern "IMAGE" :html4.0))) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.44") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (defconstant *dtd-version* "-//W3C//DTD HTML 4.01//EN") (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.44") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (define declare-html-version (&optional (stream *output-stream*) (dtd-version :frameset)) "Declares the document type as the current HTML generation DTD. All HTML 4.0 must declare the document type definition version. DTD-VERSION can be any of: :STRICT - includes all elements that have not been deprecated and do not appear in frameset documents. :TRANSITIONAL - includes everything is the STRICT DTD plus deprecated elements and attributes. :FRAMESET - includes everything in TRANSITIONAL plus frames." (when dtd-version (%issue-command ("!DOCTYPE HTML PUBLIC" stream :fresh-line t :trailing-line t) (ecase dtd-version ((:frameset t) (fast-format stream " ~S ~S" "-//W3C//DTD HTML 4.0.1 Frameset//EN" "")) (:strict (fast-format stream " ~S ~S" *dtd-version* "")) (:transitional (fast-format stream " ~S ~S" "-//W3C//DTD HTML 4.0.1 Transitional//EN" "")))))) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.44") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (defvar *strict-dtd* nil "Non-null when generating strict HTML 4.") (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.44") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (define-macro with-html-document ((&key (stream '*output-stream*) (declare-dtd-version-p :frameset) (language nil language-supplied-p) (direction nil direction-supplied-p)) &body body) "Asserts the contents of BODY is an HTML document. DECLARE-DTD-VERSION-P will declare the version of the DTD implemented by the current generation package. This should be :STRICT whenever generation strictly conforms to the HTML version associated with the macro WITH-HTML-DOCUMENT. HTML 4.0.1 offers three DTD versions. Consequently, DECLARE-DTD-VERSION-P can be any of :FRAMESET, :TRANSITIONAL, or :STRICT. A value of T is interpreted as :FRAMESET. DECLARE-DTD-VERSION-P should always be NIL, whenever extension tags or features outside these specifications are used. LANGUAGE is the two-digit language code for the displayed content (see RFC 1766) DIRECTION is ht base directionality of neutral text and can be either :LEFT-TO-RIGHT or :RIGHT-TO-LEFT." (let* ((args `(,.(when language-supplied-p `((%write-language-argument ,stream ,language))) ,.(when direction-supplied-p `((%write-direction-argument ,stream ,direction))))) (version (ecase declare-dtd-version-p ((nil) nil) ((t :frameset) :frameset) (:transitional :transitional) (:strict :strict))) (version-declaration (ecase version ((nil) nil) (:frameset `(declare-html-version ,stream :frameset)) (:transitional `(declare-html-version ,stream :transitional)) (:strict `(declare-html-version ,stream :strict))))) (if version-declaration `(let ((*strict-dtd* (eq :strict ,version))) ,version-declaration (%with-environment ("HTML" :stream ,stream) ,(when args (cons 'progn args)) . ,body)) `(%with-environment ("HTML" :stream ,stream) ,(when args (cons 'progn args)) . ,body)))) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.46") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (defmacro %with-deprecation-checking ((function condition &optional argument value value-supplied-p format-string format-args) &body body) `(progn (when ,(if condition `(and *strict-dtd* ,condition) '*strict-dtd*) ,(cond (argument `(cerror "Continue HTML Generation" "In HTML 4.0.1, for ~S the argument, ~S, ~:[~; with value, ~S,~] is deprecated.~:[~;~&~:*~?~]" ,function ,argument ,value-supplied-p ,value ,format-string ,format-args)) (function `(cerror "Continue HTML Generation" "In HTML 4.0.1, ~S is deprecated.~:[~;~&~:*~?~]" ,function ,format-string ,format-args)) (t `(cerror "Continue HTML Generation" ,format-string ,@format-args)))) ,@body)) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.46") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (define-macro with-deprecation-checking ((function &key argument (value nil value-supplied-p) condition format-string format-args) &body body) `(%with-deprecation-checking (',function ,condition ',argument ,value ,value-supplied-p ,format-string ,@format-args) ,@body)) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.49") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (eval-when (load eval compile) (mapc #'(lambda (x) (unexport x :html4.0) (shadow x :html4.0)) '(html3.2:with-enumeration html3.2:enumerating-item html3.2:enumerate-item-list))) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.49") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (PROGN (defun enumerate-itemized-item (stream continuation icon-url type id class language direction title style events) (declare (ignore icon-url)) (%issue-command ("LI" stream :fresh-line t) (html3.2::%get-bullet-style type html3.2::*itemize-bullet-styles*) (when (or id class language direction title style events) (%write-standard-command-arguments stream id class language direction title style events))) (multiple-value-prog1 (funcall continuation stream) (fresh-line stream))) (defun enumerate-enumerated-item (stream continuation icon-url type id class language direction title style events) (declare (ignore icon-url)) (%issue-command ("LI" stream :fresh-line t) (html3.2::%get-bullet-style type html3.2::*enumerate-bullet-styles*) (when (or id class language direction title style events) (%write-standard-command-arguments stream id class language direction title style events))) (multiple-value-prog1 (funcall continuation stream) (fresh-line stream))) (defun enumerate-normal-item (stream continuation icon-url head id class language direction title style events) (declare (ignore head)) (%issue-command ("LI" stream :fresh-line t) (when (or id class language direction title style events) (%write-standard-command-arguments stream id class language direction title style events))) (when icon-url (image icon-url "o" :stream stream) (write-char #\space stream)) (funcall continuation stream) (fresh-line stream)) Does not provide standard html 4 parameters for DD -- 8/25/05 JCMa (defun enumerate-definition-item (stream continuation icon-url head id class language direction title style events) (flet ((write-dd (stream) (issue-command "DD" stream nil) (write-char #\space stream))) (declare (inline write-dd)) (fresh-line stream) (%issue-command ("DT" stream :fresh-line t) (when (or id class language direction title style events) (%write-standard-command-arguments stream id class language direction title style events))) (when icon-url (image icon-url "o" :stream stream) (write-char #\space stream)) (etypecase head (null nil) (string (write-string head stream) (write-dd stream)) (cons (dolist (item head) (write item :stream stream)) (write-dd stream)) (function (funcall head stream) (write-dd stream))) (funcall continuation stream))) ) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.49") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") Does not implement the VALUE parameter -- 8/25/05 JCMa (define-macro enumerating-item ((stream &key icon-url head type id class language direction title style events) &body body) "Enumerates an item on STREAM according to the enclosing enumeration style. BODY generates the body of the item whereas icon-url head type control the item's header. TYPE (deprecated) can be provided for the styles :ENUMERATE and :ITEMIZE to override the default bullet given by the enclosing WITH-ENUMERATION. For the style ENUMERATE, TYPE can be any of :CAPITAL-LETTERS, :SMALL-LETTERS, :LARGE-ROMAN, :SMALL-ROMAN, or :ARABIC (the default). For the style :ITEMIZE, TYPE can be any of :SOLID-DISC, :CIRCLE, or :SQUARE. HEAD specifies the heading for an item in the :DEFINITION style. Head can be a string, a list of strings or a function called on STREAM. ICON-URL is available for the styles :DEFINITION, :DIRECTORY (deprecated), and :MENU (deprecated). When provided, an image is emitted at the start of the item using the URL supplied as the value of ICON-URL. CLASS is the class for the element ID is an element identifier. TITLE is a string used as an element title. STYLE denotes the style sheet to use. LANGUAGE is the two-digit language code for the displayed content (see RFC 1766) DIRECTION is ht base directionality of neutral text and can be either :LEFT-TO-RIGHT or :RIGHT-TO-LEFT." `(flet ((continuation (,stream) ,@body)) (declare (dynamic-extent #'continuation)) (funcall *enumeration-function* ,stream #'continuation ,icon-url ,(or head type) ,id ,class ,language ,direction ,title ,style ,events))) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.49") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (defun %enumeration-style-parameters (style type) (declare (values function tag type)) (case style (:itemize (values #'enumerate-itemized-item "UL" (html3.2::%get-bullet-style type html3.2::*itemize-bullet-styles*))) (:enumerate (values #'enumerate-enumerated-item "OL" (html3.2::%get-bullet-style type html3.2::*enumerate-bullet-styles*))) (:definition (values #'enumerate-definition-item "DL")) (:directory (with-deprecation-checking (with-enumeration :argument style :value style) (values #'enumerate-normal-item "DIR"))) ((:menu :plain) (with-deprecation-checking (with-enumeration :argument style :value style) (values #'enumerate-normal-item "MENU"))) (t (error "Unknown enumeration style, ~A." style)))) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.49") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (define-macro with-enumeration ((stream enumeration-style &key compact type start id class language direction title style events) &body body) "Establishes an enumeration environment using the style, STYLE, on STREAM. Within this environment, each item is emitted by generation code executed with the ENUMERATING-ITEM macro. ENUMERATION-STYLE can be :DEFINITION, :DIRECTORY (deprecated), :ENUMERATE :ITEMIZE :MENU (deprecated). You must use the ENUMERATING-ITEM from the same package for reliable results. TYPE (deprecated) allows the default styles of enumeration to be overridden for some styles. For the style :ENUMERATE, TYPE can be any of: :CAPITAL-LETTERS, :SMALL-LETTERS, :LARGE-ROMAN, :SMALL-ROMAN, or :ARABIC (the default). For the style :ITEMIZE, TYPE can be any of :SOLID-DISC, :CIRCLE, :SQUARE COMPACT (deprecated) advises the client to render lists in a more compact style. For the :ENUMERATE style, START (deprecated) can cause the enumeration to begin at a number other than the default 1. CLASS is the class for the element ID is an element identifier. TITLE is a string used as an element title. STYLE denotes the style sheet to use. LANGUAGE is the two-digit language code for the displayed content (see RFC 1766) DIRECTION is ht base directionality of neutral text and can be either :LEFT-TO-RIGHT or :RIGHT-TO-LEFT." (flet ((enumeration-arguments (compact start type) (let ((args nil)) (cond-every (compact (push `(,compact (with-deprecation-checking (with-enumeration :argument compact) (write-string " COMPACT" ,stream))) args)) (type (push `(,type (with-deprecation-checking (with-enumeration :argument type) (fast-format stream " TYPE=~A" ,type))) args)) (start (push `(,start (with-deprecation-checking (with-enumeration :argument start) (check-type ,start integer) (fast-format ,stream " START=~D" ,start))) args))) (when args `(cond-every ,.args))))) `(multiple-value-bind (*enumeration-function* tag enumeration-type) (%enumeration-style-parameters ,enumeration-style ,type) (%with-environment (tag :fresh-line t :stream ,stream) (progn ,(when (or id class language direction title style events) `(%write-standard-command-arguments ,stream ,id ,class ,language ,direction ,title ,style ,events)) ,(enumeration-arguments compact start type)) ,@body)))) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.49") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (define enumerate-item-list (item-list &key (enumeration-style :itemize) type compact id class language direction title style events (stream *output-stream*)) "Enumerates the elements of ITEM-LIST in STYLE on STREAM." (with-enumeration (stream enumeration-style :compact compact :type type :id id :class class :language language :direction direction :title title :style style :events events) (dolist (item item-list) (enumerating-item (stream) (write item :stream stream :escape nil))))) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.49") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (eval-when (load) (mapc #'(lambda (x) (export (intern x :html4.0))) '("WITH-ENUMERATION" "ENUMERATING-ITEM" "ENUMERATE-ITEM-LIST"))) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;HTML4.LISP.50") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: LISP; Package: html4.0; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-") (defun %note-image (stream image-url alternative-text alignment accept-coordinates-at-url client-side-image-map border vertical-space horizontal-space width height description class id title style language direction events) (flet ((write-element (stream image-url alignment alternative-text accept-coordinates-at-url events) (flet ((alignment-value (alignment) (unless (member alignment *image-alignment-values*) (error "Unknown alignment, ~S, for an image." alignment)) (symbol-name alignment)) (write-integer-arg (stream option value) (check-type value integer) (%write-command-key-arg stream option value t))) (declare (inline alignment-value write-integer-arg)) (when (and image-url (not (or width height)) http:*image-sizes-default-automatically*) (multiple-value-setq (width height) (url:image-size image-url))) (%issue-command ("IMG" stream) (cond-every (image-url (%write-command-key-arg stream "SRC" image-url)) (alignment (with-deprecation-checking (image :argument alignment) (%write-command-key-arg stream "ALIGN" (alignment-value alignment)))) (alternative-text (check-type alternative-text string) (%write-command-key-arg stream "ALT" alternative-text)) (description (check-type description string) (%write-command-key-arg stream "LONGDESC" description)) (accept-coordinates-at-url (%write-command-key-arg stream "ISMAP")) (client-side-image-map (%write-command-key-arg stream "USEMAP" (url:name-string-without-search-suffix client-side-image-map nil))) (border (with-deprecation-checking (image :argument border) (write-integer-arg stream "BORDER" border))) (vertical-space (with-deprecation-checking (image :argument vertical-space) (write-integer-arg stream "VSPACE" vertical-space))) (horizontal-space (with-deprecation-checking (image :argument horizontal-space) (write-integer-arg stream "HSPACE" horizontal-space))) (width (write-integer-arg stream "WIDTH" width)) (height (write-integer-arg stream "HEIGHT" height)) ((or id class language direction title style events) (%write-standard-command-arguments stream id class language direction title style events))))))) (let ((url-string (url:name-string-without-search-suffix image-url nil))) (declare (dynamic-extent url-string)) (case accept-coordinates-at-url ((nil :no-url) (write-element stream url-string alignment alternative-text accept-coordinates-at-url events)) (t (with-anchor-noted (:reference (if (eq accept-coordinates-at-url t) url-string (url:name-string-without-search-suffix accept-coordinates-at-url nil)) :stream stream) (write-element stream url-string alignment alternative-text accept-coordinates-at-url events)))))))
e1259fe5f4690f81ff52908d5bf6ae0a768d4755f100b91d220fabd517a85f04
nedap/formatting-stack
background.clj
(ns formatting-stack.background "This file live in a distinct source-paths so it's not affected by the Reloaded workflow, while developing formatting-stack itself.") (defonce workload (atom nil)) (defonce ^Thread ^{:doc "The runner for 'background' execution. Can be stopped via the thread interruption mechanism."} runner (let [f (fn [] (while (not (-> (Thread/currentThread) .isInterrupted)) (if-let [job @workload] (when (compare-and-set! workload job nil) (try (job) (catch Exception e (-> e .printStackTrace)) (catch AssertionError e (-> e .printStackTrace)))) (Thread/sleep 50))))] (-> f Thread. (doto (.setName (str `runner))) Important - daemonize this thread , otherwise under certain conditions it can prevent the JVM from exiting . ;; (We exercise this implicitly via `lein eastwood` in CI) (doto (.setDaemon true)) (doto .start))))
null
https://raw.githubusercontent.com/nedap/formatting-stack/c43e74d5409e9338f208457bb8928ce437381a3f/worker/formatting_stack/background.clj
clojure
(We exercise this implicitly via `lein eastwood` in CI)
(ns formatting-stack.background "This file live in a distinct source-paths so it's not affected by the Reloaded workflow, while developing formatting-stack itself.") (defonce workload (atom nil)) (defonce ^Thread ^{:doc "The runner for 'background' execution. Can be stopped via the thread interruption mechanism."} runner (let [f (fn [] (while (not (-> (Thread/currentThread) .isInterrupted)) (if-let [job @workload] (when (compare-and-set! workload job nil) (try (job) (catch Exception e (-> e .printStackTrace)) (catch AssertionError e (-> e .printStackTrace)))) (Thread/sleep 50))))] (-> f Thread. (doto (.setName (str `runner))) Important - daemonize this thread , otherwise under certain conditions it can prevent the JVM from exiting . (doto (.setDaemon true)) (doto .start))))
71916651445d88b7c8cce709742d64d81200ff793e8fbd491ec6e068f958e259
ppelleti/normalization-insensitive
bench.hs
# LANGUAGE CPP # # OPTIONS_GHC -fno - warn - orphans # module Main ( main) where import Criterion.Main ( defaultMain, bench, nf ) import qualified Data.ByteString as B ( readFile ) import qualified Data.Unicode.NormalizationInsensitive as NI ( mk ) import qualified NoClass as NC ( mk ) #if !MIN_VERSION_bytestring(0,10,0) import Control.DeepSeq ( NFData ) instance NFData ByteString #endif main :: IO () main = do bs <- B.readFile "pg2189.txt" defaultMain [ bench "no-class" $ nf (\s -> NC.mk s) bs , bench "normalization-insensitive" $ nf (\s -> NI.mk s) bs ]
null
https://raw.githubusercontent.com/ppelleti/normalization-insensitive/5f18e8a6a5261405e15fd418ca279da62f96e54e/bench/bench.hs
haskell
# LANGUAGE CPP # # OPTIONS_GHC -fno - warn - orphans # module Main ( main) where import Criterion.Main ( defaultMain, bench, nf ) import qualified Data.ByteString as B ( readFile ) import qualified Data.Unicode.NormalizationInsensitive as NI ( mk ) import qualified NoClass as NC ( mk ) #if !MIN_VERSION_bytestring(0,10,0) import Control.DeepSeq ( NFData ) instance NFData ByteString #endif main :: IO () main = do bs <- B.readFile "pg2189.txt" defaultMain [ bench "no-class" $ nf (\s -> NC.mk s) bs , bench "normalization-insensitive" $ nf (\s -> NI.mk s) bs ]
388b39d8b92e25b960f53a5b5e75f49fd59e707a350f1458f63116dc418dabbe
twosigma/waiter
process_request_test.clj
;; Copyright ( c ) Two Sigma Open Source , LLC ;; Licensed under the Apache License , Version 2.0 ( the " License " ) ; ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; -2.0 ;; ;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns waiter.process-request-test (:require [clj-time.core :as t] [clojure.core.async :as async] [clojure.string :as str] [clojure.test :refer :all] [metrics.counters :as counters] [metrics.meters :as meters] [plumbing.core :as pc] [qbits.jet.client.http :as http] [waiter.core :refer :all] [waiter.descriptor :as descriptor] [waiter.headers :as headers] [waiter.metrics :as metrics] [waiter.process-request :refer :all] [waiter.statsd :as statsd] [waiter.status-codes :refer :all] [waiter.test-helpers :refer :all] [waiter.util.async-utils :as au] [waiter.util.utils :as utils]) (:import (java.io ByteArrayOutputStream IOException) (java.net ConnectException SocketTimeoutException) (java.util.concurrent TimeoutException) (org.eclipse.jetty.client HttpClient) (org.eclipse.jetty.io EofException) (org.eclipse.jetty.websocket.api UpgradeException))) (deftest test-prepare-request-properties (let [test-cases (list {:name "test-prepare-request-properties:nil-inputs" :input {:request-properties nil :waiter-headers nil} :expected {:async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:empty-nil-inputs" :input {:request-properties {} :waiter-headers nil} :expected {:async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:nil-empty-inputs" :input {:request-properties nil :waiter-headers {}} :expected {:async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:empty-inputs" :input {:request-properties {} :waiter-headers {}} :expected {:async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:missing-timeout-header-1" :input {:request-properties {:fie "foe"} :waiter-headers {:foo "bar"}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:missing-timeout-header-2" :input {:request-properties {:fie "foe" :initial-socket-timeout-ms 100 :streaming-timeout-ms 200} :waiter-headers {:foo "bar"}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 100 :queue-timeout-ms nil :streaming-timeout-ms 200} } {:name "test-prepare-request-properties:invalid-timeout-header" :input {:request-properties {:fie "foe" :initial-socket-timeout-ms 100 :queue-timeout-ms 150 :streaming-timeout-ms nil} :waiter-headers {"timeout" "bar"}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 100 :queue-timeout-ms 150 :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:negative-timeout-header" :input {:request-properties {:fie "foe" :initial-socket-timeout-ms 100} :waiter-headers {"timeout" -50}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 100 :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:valid-timeout-header" :input {:request-properties {:fie "foe" :initial-socket-timeout-ms 100 :streaming-timeout-ms 200} :waiter-headers {"timeout" 50 "streaming-timeout" 250}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 50 :queue-timeout-ms nil :streaming-timeout-ms 250} } {:name "test-prepare-request-properties:invalid-queue-timeout-header" :input {:request-properties {:fie "foe" :queue-timeout-ms 150} :waiter-headers {"queue-timeout" "bar"}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms 150 :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:negative-queue-timeout-header" :input {:request-properties {:fie "foe" :queue-timeout-ms 150} :waiter-headers {"queue-timeout" -50}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms 150 :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:valid-queue-timeout-header" :input {:request-properties {:fie "foe" :queue-timeout-ms 150 :streaming-timeout-ms nil} :waiter-headers {"queue-timeout" 50}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms 50 :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:valid-both-timeout-headers" :input {:request-properties {:fie "foe" :initial-socket-timeout-ms 100 :queue-timeout-ms 150} :waiter-headers {"queue-timeout" 50 "timeout" 75}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 75 :queue-timeout-ms 50 :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:invalid-async-headers" :input {:request-properties {:fie "foe" :async-check-interval-ms 100 :async-request-timeout-ms 200} :waiter-headers {"async-check-interval" -50 "async-request-timeout" "foo"}} :expected {:fie "foe" :async-check-interval-ms 100 :async-request-timeout-ms 200 :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:valid-async-headers" :input {:request-properties {:fie "foe" :async-check-interval-ms 100 :async-request-timeout-ms 200} :waiter-headers {"async-check-interval" 50 "async-request-timeout" 250}} :expected {:fie "foe" :async-check-interval-ms 50 :async-request-timeout-ms 250 :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:too-large-async-request-timeout-header" :input {:request-properties {:fie "foe" :async-check-interval-ms 100 :async-request-max-timeout-ms 100000 :async-request-timeout-ms 200} :waiter-headers {"async-request-timeout" 101000}} :expected {:fie "foe" :async-check-interval-ms 100 :async-request-max-timeout-ms 100000 :async-request-timeout-ms 100000 :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:too-large-async-request-timeout-header" :input {:request-properties {:fie "foe" :async-check-interval-ms 100 :async-request-max-timeout-ms 100000 :async-request-timeout-ms 200} :waiter-headers {"async-request-timeout" 101000}} :expected {:fie "foe" :async-check-interval-ms 100 :async-request-max-timeout-ms 100000 :async-request-timeout-ms 100000 :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:empty-request-properties-with-token-defaults" :input {:request-properties {:initial-socket-timeout-ms 100 :queue-timeout-ms 150 :streaming-timeout-ms nil} :token-metadata {"queue-timeout-ms" 300000 "socket-timeout-ms" 900000 "streaming-timeout-ms" 20000} :waiter-headers nil} :expected {:async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 900000 :queue-timeout-ms 300000 :streaming-timeout-ms 20000} } {:name "test-prepare-request-properties:empty-request-properties-with-token-defaults-and-some-headers" :input {:request-properties {:initial-socket-timeout-ms 100 :queue-timeout-ms 150 :streaming-timeout-ms nil} :token-metadata {"queue-timeout-ms" 300000 "socket-timeout-ms" 900000 "streaming-timeout-ms" 20000} :waiter-headers {"queue-timeout" 50 "timeout" 75}} :expected {:async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 75 :queue-timeout-ms 50 :streaming-timeout-ms 20000} } {:name "test-prepare-request-properties:empty-request-properties-with-token-defaults-and-most-timeout-headers" :input {:request-properties {:initial-socket-timeout-ms 100 :queue-timeout-ms 150 :streaming-timeout-ms nil} :token-metadata {"queue-timeout-ms" 300000 "socket-timeout-ms" 900000 "streaming-timeout-ms" 20000} :waiter-headers {"queue-timeout" 50 "streaming-timeout" 95 "timeout" 75}} :expected {:async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 75 :queue-timeout-ms 50 :streaming-timeout-ms 95} })] (doseq [{:keys [name input expected]} test-cases] (testing (str "Test " name) (let [{:keys [request-properties token-metadata waiter-headers]} input waiter-headers' (pc/map-keys #(str headers/waiter-header-prefix %) waiter-headers) actual (prepare-request-properties request-properties waiter-headers' token-metadata)] (is (= expected actual))))))) (deftest test-prepare-grpc-compliant-request-properties (let [request-properties-base {:async-check-interval-ms 1010 :async-request-timeout-ms 1020 :initial-socket-timeout-ms 1030 :queue-timeout-ms 1040 :streaming-timeout-ms 1050}] (doseq [{:keys [backend-proto request-headers request-properties-expected token-metadata] :as test-case} [{:backend-proto "h2c" :request-headers {"x-waiter-async-check-interval" "2100" "x-waiter-async-request-timeout" "2200" "x-waiter-timeout" "2300" "x-waiter-queue-timeout" "2400" "x-waiter-streaming-timeout" "2500"} :request-properties-expected {:async-request-timeout-ms 2200 :async-check-interval-ms 2100 :initial-socket-timeout-ms 2300 :queue-timeout-ms 2400 :streaming-timeout-ms 2500}} {:backend-proto "h2c" :request-headers {} :request-properties-expected {}} {:backend-proto "h2c" :request-headers {"x-waiter-queue-timeout" "2000"} :request-properties-expected {:queue-timeout-ms 2000}} {:backend-proto "h2c" :request-headers {"grpc-timeout" "3S"} :request-properties-expected {:queue-timeout-ms 1040}} {:backend-proto "h2c" :request-headers {"grpc-timeout" "3S" "x-waiter-queue-timeout" "2000"} :request-properties-expected {:queue-timeout-ms 2000}} {:backend-proto "http" :request-headers {"content-type" "application/grpc" "grpc-timeout" "3S"} :request-properties-expected {:queue-timeout-ms 1040}} {:backend-proto "h2c" :request-headers {"content-type" "application/grpc" "grpc-timeout" "3S"} :request-properties-expected {:queue-timeout-ms 3100}} {:backend-proto "h2c" :request-headers {"content-type" "application/grpc" "grpc-timeout" "3S" "x-waiter-queue-timeout" "2000"} :request-properties-expected {:queue-timeout-ms 2000}} {:backend-proto "h2c" :request-headers {"content-type" "application/grpc" "grpc-timeout" "3S" "x-waiter-queue-timeout" "2000"} :request-properties-expected {:initial-socket-timeout-ms 900000 :queue-timeout-ms 2000 :streaming-timeout-ms 20000} :token-metadata {"queue-timeout-ms" 300000 "socket-timeout-ms" 900000 "streaming-timeout-ms" 20000}}]] (let [{:keys [passthrough-headers waiter-headers]} (headers/split-headers request-headers) request-properties-actual (prepare-grpc-compliant-request-properties request-properties-base backend-proto passthrough-headers waiter-headers token-metadata)] (is (= (merge request-properties-base request-properties-expected) request-properties-actual) (str test-case)))))) (deftest test-stream-http-response-configure-idle-timeout (let [idle-timeout-atom (atom nil) output-stream (ByteArrayOutputStream.)] (with-redefs [set-idle-timeout! (fn [in-output-stream idle-timeout-ms] (is (= output-stream in-output-stream)) (reset! idle-timeout-atom idle-timeout-ms))] (let [body (async/chan) confirm-live-connection (fn [] :nothing) request-abort-callback (fn [_] :nothing) resp-chan (async/chan) streaming-timeout-ms 100 instance-request-properties {:output-buffer-size 1000000 :streaming-timeout-ms streaming-timeout-ms} reservation-status-promise (promise) request-state-chan (async/chan) metric-group nil waiter-debug-enabled? nil service-id "service-id" abort-request-chan (async/chan) error-chan (async/chan) response {:abort-request-chan abort-request-chan, :body body, :error-chan error-chan}] (async/close! error-chan) (async/close! body) (stream-http-response response confirm-live-connection request-abort-callback false resp-chan instance-request-properties reservation-status-promise request-state-chan metric-group waiter-debug-enabled? (metrics/stream-metric-map service-id)) (loop [] (let [message (async/<!! resp-chan)] (when (function? message) (message output-stream)) (when message (recur)))) (is (= streaming-timeout-ms @idle-timeout-atom)) (is (= :success @reservation-status-promise)) (is (nil? (async/<!! request-state-chan))))))) (defn- stream-response "Calls stream-http-response with statsd/inc! redefined to simply store the count of response bytes that it gets called with, and returns these counts in a vector" [bytes skip-streaming?] (let [bytes-reported (atom [])] (with-redefs [statsd/inc! (fn [_ metric value] (when (= metric "response_bytes") (swap! bytes-reported conj value)))] (let [body (async/chan) confirm-live-connection (fn [] :nothing) request-abort-callback (fn [_] :nothing) resp-chan (async/chan) instance-request-properties {:output-buffer-size 1000000 :streaming-timeout-ms 100} reservation-status-promise (promise) request-state-chan (async/chan) metric-group nil waiter-debug-enabled? nil service-id "service-id" abort-request-chan (async/chan) error-chan (async/chan) response {:abort-request-chan abort-request-chan, :body body, :error-chan error-chan}] (async/go-loop [bytes-streamed 0] (if (= bytes-streamed bytes) (do (async/close! error-chan) (async/close! body)) (let [bytes-to-stream (min 1024 (- bytes bytes-streamed))] (async/>! body (byte-array (repeat bytes-to-stream 0))) (recur (+ bytes-streamed bytes-to-stream))))) (when skip-streaming? (Thread/sleep 100) (async/close! resp-chan)) (stream-http-response response confirm-live-connection request-abort-callback skip-streaming? resp-chan instance-request-properties reservation-status-promise request-state-chan metric-group waiter-debug-enabled? (metrics/stream-metric-map service-id)) (loop [] (let [message (async/<!! resp-chan)] (when message (recur)))))) @bytes-reported)) (deftest test-stream-http-response (testing "Streaming the response" (testing "skipping should stream no bytes" (let [bytes-reported (stream-response 2048 true)] (is (zero? (count bytes-reported))))) (testing "should throttle calls to statsd to report bytes streamed" (let [bytes-reported (stream-response 1 false)] (is (= 1 (count bytes-reported))) (is (= [1] bytes-reported))) (let [bytes-reported (stream-response (* 1024 977) false)] (is (= 1 (count bytes-reported))) (is (= [1000448] bytes-reported))) (let [bytes-reported (stream-response (-> 1024 (* 977) (inc)) false)] (is (= 2 (count bytes-reported))) (is (= [1000448 1] bytes-reported))) (let [bytes-reported (stream-response 10000000 false)] (is (= 10 (count bytes-reported))) (is (= 10000000 (reduce + bytes-reported))) (is (= [1000448 1000448 1000448 1000448 1000448 1000448 1000448 1000448 1000448 995968] bytes-reported)))))) (deftest test-extract-async-request-response-data (testing "202-missing-location-header" (is (nil? (extract-async-request-response-data {:status http-202-accepted :headers {}} ":1234/query/for/status")))) (testing "200-not-async" (is (nil? (extract-async-request-response-data {:status http-200-ok, :headers {"location" "/result/location"}} ":1234/query/for/status")))) (testing "303-not-async" (is (nil? (extract-async-request-response-data {:status http-303-see-other, :headers {"location" "/result/location"}} ":1234/query/for/status")))) (testing "404-not-async" (is (nil? (extract-async-request-response-data {:status http-404-not-found, :headers {"location" "/result/location"}} ":1234/query/for/status")))) (testing "202-absolute-location" (is (= {:location "/result/location" :query-string nil} (extract-async-request-response-data {:status http-202-accepted :headers {"location" "/result/location"}} ":1234/query/for/status")))) (testing "202-relative-location-1" (is (= {:location "/query/result/location" :query-string nil} (extract-async-request-response-data {:status http-202-accepted :headers {"location" "../result/location"}} ":1234/query/for/status")))) (testing "202-relative-location-2" (is (= {:location "/query/for/result/location" :query-string nil} (extract-async-request-response-data {:status http-202-accepted :headers {"location" "result/location"}} ":1234/query/for/status")))) (testing "202-relative-location-two-levels" (is (= {:location "/result/location" :query-string "p=q&r=s|t"} (extract-async-request-response-data {:status http-202-accepted :headers {"location" "../../result/location?p=q&r=s|t"}} ":1234/query/for/status?u=v&w=x|y|z")))) (testing "202-absolute-url-same-host-port" (is (= {:location "/retrieve/result/location" :query-string nil} (extract-async-request-response-data {:status http-202-accepted :headers {"location" ":1234/retrieve/result/location"}} ":1234/query/for/status")))) (testing "202-absolute-url-different-host" (is (nil? (extract-async-request-response-data {:status http-202-accepted :headers {"location" ":1234/retrieve/result/location"}} ":1234/query/for/status")))) (testing "202-absolute-url-different-port" (is (nil? (extract-async-request-response-data {:status http-202-accepted :headers {"location" ":5678/retrieve/result/location"}} ":1234/query/for/status"))))) (deftest test-make-request (let [instance {:service-id "test-service-id", :host "example.com", :port 8080} backend-proto "http" request {:authorization/principal "" :authorization/user "test-user" :body "body"} request-properties {:connection-timeout-ms 123456, :initial-socket-timeout-ms 654321} passthrough-headers {"accept" "text/html" "accept-charset" "ISO-8859-1,utf-8;q=0.7,*;q=0.7" "accept-language" "en-us" "accept-encoding" "gzip,deflate" "authorization" "test-user-authorization" "cache-control" "no-cache" "connection" "keep-alive" "content-length" "12341234" "content-MD5" "Q2hlY2sgSW50ZWdyaXR5IQ==" "content-type" "application/x-www-form-urlencoded" "cookie" "$Version=1; Skin=new; x-waiter-auth=foo" "date" "Tue, 15 Nov 2015 08:12:31 GMT" "expect" "100-continue" "expires" "2200-08-09" "forwarded" "for=192.0.2.43, for=198.51.100.17" "from" "" "host" "www.test-source.com" "if-match" "737060cd8c284d8af7ad3082f209582d" "if-modified-since" "Sat, 29 Oct 2015 19:43:31 GMT" "keep-alive" "300" "origin" "" "pragma" "no-cache" "proxy-authenticate" "proxy-authenticate value" "proxy-authorization" "proxy-authorization value" "proxy-connection" "keep-alive" "referer" "-referer.com" "te" "trailers, deflate" "trailers" "trailer-name-1, trailer-name-2" "transfer-encoding" "trailers, deflate" "upgrade" "HTTP/2.0, HTTPS/1.3, IRC/6.9, RTA/x11, websocket" "user-agent" "Test/App" "x-cid" "239874623hk2er7908245" "x-forwarded-for" "client1, proxy1, proxy2" "x-http-method-override" "DELETE"} end-route "/end-route" app-password "test-password"] (let [expected-endpoint ":8080/end-route" make-basic-auth-fn (fn make-basic-auth-fn [endpoint username password] (is (= expected-endpoint endpoint)) (is (= username "waiter")) (is (= app-password password)) (Object.)) service-id->password-fn (fn service-id->password-fn [service-id] (is (= "test-service-id" service-id)) app-password) http-clients {:http1-client (http/client)} http-request-mock-factory (fn [passthrough-headers request-method-fn-call-counter proto-version] (fn [^HttpClient _ request-config] (swap! request-method-fn-call-counter inc) (is (= expected-endpoint (:url request-config))) (is (= :bytes (:as request-config))) (is (:auth request-config)) (is (= "body" (:body request-config))) (is (= 654321 (:idle-timeout request-config))) (is (= (-> passthrough-headers (assoc "cookie" "$Version=1; Skin=new") (dissoc "expect" "authorization" "connection" "keep-alive" "proxy-authenticate" "proxy-authorization" "te" "trailers" "transfer-encoding" "upgrade") (merge {"x-waiter-auth-principal" "test-user" "x-waiter-authenticated-principal" ""})) (:headers request-config))) (is (= proto-version (:version request-config)))))] (testing "make-request:headers:HTTP/1.0" (let [proto-version "HTTP/1.0" request-method-fn-call-counter (atom 0)] (with-redefs [http/request (http-request-mock-factory passthrough-headers request-method-fn-call-counter proto-version)] (make-request http-clients make-basic-auth-fn service-id->password-fn instance request request-properties passthrough-headers end-route nil backend-proto proto-version) (is (= 1 @request-method-fn-call-counter))))) (testing "make-request:headers:HTTP/2.0" (let [proto-version "HTTP/2.0" request-method-fn-call-counter (atom 0)] (with-redefs [http/request (http-request-mock-factory passthrough-headers request-method-fn-call-counter proto-version)] (make-request http-clients make-basic-auth-fn service-id->password-fn instance request request-properties passthrough-headers end-route nil backend-proto proto-version) (is (= 1 @request-method-fn-call-counter))))) (testing "make-request:headers-long-content-length" (let [proto-version "HTTP/1.0" request-method-fn-call-counter (atom 0) passthrough-headers (assoc passthrough-headers "content-length" "1234123412341234") statsd-inc-call-value (promise)] (with-redefs [http/request (http-request-mock-factory passthrough-headers request-method-fn-call-counter proto-version) statsd/inc! (fn [metric-group metric value] (is (nil? metric-group)) (is (= "request_content_length" metric)) (deliver statsd-inc-call-value value))] (make-request http-clients make-basic-auth-fn service-id->password-fn instance request request-properties passthrough-headers end-route nil backend-proto proto-version) (is (= 1 @request-method-fn-call-counter)) (is (= 1234123412341234 (deref statsd-inc-call-value 0 :statsd-inc-not-called))))))))) (deftest test-wrap-suspended-service (testing "returns error for suspended app" (let [handler (wrap-suspended-service (fn [_] {:status http-200-ok})) request {:descriptor {:service-id "service-id-1" :suspended-state {:suspended true :last-updated-by "test-user" :time (t/now)}}} {:keys [status body]} (handler request)] (is (= http-503-service-unavailable status)) (is (str/includes? body "Service has been suspended")) (is (str/includes? body "test-user")))) (testing "passes apps by default" (let [handler (wrap-suspended-service (fn [_] {:status http-200-ok})) request {} {:keys [status]} (handler request)] (is (= http-200-ok status))))) (deftest test-wrap-maintenance-mode (testing "returns 503 for token in maintenance mode with custom message" (let [handler (wrap-maintenance-mode (fn [_] {:status http-200-ok})) maintenance-message "test maintenance message" request {:waiter-discovery {:token-metadata {"maintenance" {"message" maintenance-message}} :token "token" :waiter-headers {}}} {:keys [status body]} (handler request)] (is (= http-503-service-unavailable status)) (is (str/includes? body maintenance-message)))) (testing "passes apps by default" (let [handler (wrap-maintenance-mode (fn [_] {:status http-200-ok})) request {:waiter-discovery {:token-metadata {} :token "token" :waiter-headers {}}} {:keys [status]} (handler request)] (is (= http-200-ok status))))) (deftest test-wrap-maintenance-mode-acceptor (testing "returns 503 for token in maintenance mode with custom message" (let [handler (wrap-maintenance-mode-acceptor (fn [_] (is false "Not supposed to call this handler") true)) maintenance-message "test maintenance message" upgrade-response (reified-upgrade-response) request {:upgrade-response upgrade-response :waiter-discovery {:token-metadata {"maintenance" {"message" maintenance-message}} :token "token" :waiter-headers {}}} response-status (handler request)] (is (= http-503-service-unavailable response-status)) (is (= http-503-service-unavailable (.getStatusCode upgrade-response))) (is (str/includes? (.getStatusReason upgrade-response) maintenance-message)))) (testing "passes apps by default" (let [handler (wrap-maintenance-mode-acceptor (fn [_] true)) request {:waiter-discovery {:token-metadata {} :token "token" :waiter-headers {}}} success? (handler request)] (is (true? success?))))) (deftest test-wrap-too-many-requests (let [error-response-throttle {:max-delay-ms 1000 :step-delay-ms 50 :step-size-per-min 100}] (testing "returns error for too many requests" (let [service-id (str "my-service-" (System/currentTimeMillis)) counter (metrics/service-counter service-id "request-counts" "waiting-for-available-instance")] (counters/inc! counter 10) (let [handler (wrap-too-many-requests (fn [_] {:status http-200-ok}) error-response-throttle) request {:descriptor {:service-id service-id :service-description {"max-queue-length" 5}}} response (handler request) {:keys [status body]} (cond-> response (au/chan? response) (async/<!!))] (is (= http-503-service-unavailable status)) (is (str/includes? body "Max queue length")))) (let [service-id (str "my-service-" (System/currentTimeMillis)) counter (metrics/service-counter service-id "request-counts" "waiting-for-available-instance") queue-length-meter (metrics/service-meter service-id "response-rate" "error" "queue-length")] (counters/inc! counter 10) (meters/mark! queue-length-meter 1000000) (let [handler (wrap-too-many-requests (fn [_] {:status http-200-ok}) error-response-throttle) request {:descriptor {:service-id service-id :service-description {"max-queue-length" 5}}} response (handler request) {:keys [status body]} (cond-> response (au/chan? response) (async/<!!))] (is (= http-503-service-unavailable status)) (is (str/includes? body "Max queue length"))))) (testing "passes service with fewer requests" (let [service-id (str "ok-service-" (System/currentTimeMillis)) counter (metrics/service-counter service-id "request-counts" "waiting-for-available-instance")] (counters/clear! counter) (counters/inc! counter 3) (let [handler (wrap-too-many-requests (fn [_] {:status http-200-ok}) error-response-throttle) request {:descriptor {:service-id service-id :service-description {"max-queue-length" 10}}} {:keys [status]} (handler request)] (is (= http-200-ok status))))))) (deftest test-redirect-on-process-error (let [request->descriptor-fn (fn [_] (throw (ex-info "Test exception" {:type :service-description-error :issue {"run-as-user" "missing-required-key"} :x-waiter-headers {"queue-length" 100}}))) service-invocation-authorized? (constantly true) start-new-service-fn (constantly nil) fallback-state-atom (atom {}) handler (descriptor/wrap-descriptor (fn [_] {:status http-200-ok}) request->descriptor-fn service-invocation-authorized? start-new-service-fn fallback-state-atom utils/exception->response)] (testing "with-query-params" (let [request {:headers {"host" "www.example.com:1234"}, :query-string "a=b&c=d", :uri "/path"} {:keys [headers status]} (handler request)] (is (= http-303-see-other status)) (is (= "/waiter-consent/path?a=b&c=d" (get headers "location"))))) (testing "with-query-params-and-default-port" (let [request {:headers {"host" "www.example.com"}, :query-string "a=b&c=d", :uri "/path"} {:keys [headers status]} (handler request)] (is (= http-303-see-other status)) (is (= "/waiter-consent/path?a=b&c=d" (get headers "location"))))) (testing "without-query-params" (let [request {:headers {"host" "www.example.com:1234"}, :uri "/path"} {:keys [headers status]} (handler request)] (is (= http-303-see-other status)) (is (= "/waiter-consent/path" (get headers "location"))))))) (deftest test-no-redirect-on-process-error (let [request->descriptor-fn (fn [_] (throw (Exception. "Exception message"))) service-invocation-authorized? (constantly true) start-new-service-fn (constantly nil) fallback-state-atom (atom {}) handler (descriptor/wrap-descriptor (fn [_] {:status http-200-ok}) request->descriptor-fn service-invocation-authorized? start-new-service-fn fallback-state-atom utils/exception->response) request {} {:keys [body headers status]} (handler request)] (is (= http-500-internal-server-error status)) (is (nil? (get headers "location"))) (is (= "text/plain" (get headers "content-type"))) (is (str/includes? (str body) "Internal error")))) (deftest test-message-reaches-user-on-process-error (let [request->descriptor-fn (fn [_] (throw (ex-info "Error message for user" {:status http-404-not-found}))) service-invocation-authorized? (constantly true) start-new-service-fn (constantly nil) fallback-state-atom (atom {}) handler (descriptor/wrap-descriptor (fn [_] {:status http-200-ok}) request->descriptor-fn service-invocation-authorized? start-new-service-fn fallback-state-atom utils/exception->response) request {} {:keys [body headers status]} (handler request)] (is (= http-404-not-found status)) (is (= "text/plain" (get headers "content-type"))) (is (str/includes? (str body) "Error message for user")))) (deftest test-determine-priority (let [position-generator-atom (atom 100)] (is (nil? (determine-priority position-generator-atom nil))) (is (nil? (determine-priority position-generator-atom {}))) (is (nil? (determine-priority position-generator-atom {"foo" 1}))) (is (= [1 -101] (determine-priority position-generator-atom {:priority 1}))) (is (= [2 -102] (determine-priority position-generator-atom {:priority 2}))) (is (= [4 -103] (determine-priority position-generator-atom {:priority 4 :source 2}))) (is (nil? (determine-priority position-generator-atom {"priority" 1}))) (is (nil? (determine-priority position-generator-atom {:priority "1"}))) (is (= 103 @position-generator-atom)))) (deftest test-classify-error (with-redefs [utils/message name] (is (= [error-cause-generic-error "Test Exception" http-500-internal-server-error error-image-500-internal-server-error "clojure.lang.ExceptionInfo"] (classify-error "test-classify-error" (ex-info "Test Exception" {:source :test})))) (is (= [:test-error "Test Exception" http-500-internal-server-error error-image-500-internal-server-error "clojure.lang.ExceptionInfo"] (classify-error "test-classify-error" (ex-info "Test Exception" {:error-cause :test-error :source :test})))) (is (= [error-cause-generic-error "Test 401 Exception" http-401-unauthorized nil "clojure.lang.ExceptionInfo"] (classify-error "test-classify-error" (ex-info "Test 401 Exception" {:source :test :status http-401-unauthorized})))) (is (= [error-cause-generic-error "Test 400 Exception" http-400-bad-request error-image-400-bad-request "clojure.lang.ExceptionInfo"] (classify-error "test-classify-error" (ex-info "Test 400 Exception" {:source :test :status http-400-bad-request})))) (is (= [error-cause-generic-error "Test 500 Exception" http-500-internal-server-error error-image-500-internal-server-error "clojure.lang.ExceptionInfo"] (classify-error "test-classify-error" (ex-info "Test 500 Exception" {:source :test :status http-500-internal-server-error})))) (is (= [error-cause-generic-error "Test Exception" http-400-bad-request error-image-400-bad-request "clojure.lang.ExceptionInfo"] (classify-error "test-classify-error" (ex-info "Test Exception" {:source :test :status http-400-bad-request :waiter/error-image error-image-400-bad-request})))) (is (= [error-cause-instance-error "backend-request-failed" http-502-bad-gateway error-image-502-connection-failed "java.io.IOException"] (classify-error "test-classify-error" (ex-info "Test Exception" {:source :test :status http-400-bad-request} (IOException. "Test"))))) (is (= [error-cause-instance-error "backend-request-failed" http-502-bad-gateway error-image-502-connection-failed "java.io.IOException"] (classify-error "test-classify-error" (IOException. "Test")))) (is (= [error-cause-client-error "Client action means stream is no longer needed" http-400-bad-request error-image-400-bad-request "java.io.IOException"] (classify-error "test-classify-error" (ex-info "Test Exception" {:source :test :status http-400-bad-request} (IOException. "cancel_stream_error"))))) (is (= [error-cause-client-error "Client action means stream is no longer needed" http-400-bad-request error-image-400-bad-request "java.io.IOException"] (classify-error "test-classify-error" (IOException. "cancel_stream_error")))) (is (= [error-cause-generic-error "Internal error: session already closed" http-500-internal-server-error error-image-500-internal-server-error "java.lang.IllegalStateException"] (classify-error "test-classify-error" (IllegalStateException. "session closed")))) (is (= [error-cause-generic-error "invalid state" http-400-bad-request error-image-400-bad-request "java.lang.IllegalStateException"] (classify-error "test-classify-error" (IllegalStateException. "invalid state")))) (let [exception (IOException. "internal_error")] (->> (into-array StackTraceElement [(StackTraceElement. "org.eclipse.jetty.http2.client.http.HttpReceiverOverHTTP2" "onReset" "HttpReceivedOverHTTP2.java" 169) (StackTraceElement. "org.eclipse.jetty.http2.api.Stream$Listener" "onReset" "Stream.java" 177) (StackTraceElement. "org.eclipse.jetty.http2.HTTP2Stream" "notifyReset" "HTTP2Stream.java" 574)]) (.setStackTrace exception)) (is (= [error-cause-client-error "Client send invalid data to HTTP/2 backend" http-400-bad-request error-image-400-bad-request "java.io.IOException"] (classify-error "test-classify-error" exception)))) (is (= [error-cause-instance-error "backend-request-failed" http-502-bad-gateway error-image-502-connection-failed "java.io.IOException"] (classify-error "test-classify-error" (IOException. "internal_error")))) (is (= [error-cause-server-eagerly-closed "Connection eagerly closed by server" http-400-bad-request error-image-400-bad-request "java.io.IOException"] (classify-error "test-classify-error" (IOException. "no_error")))) (is (= [error-cause-client-error "Connection unexpectedly closed while streaming request" http-400-bad-request error-image-400-bad-request "org.eclipse.jetty.io.EofException"] (classify-error "test-classify-error" (ex-info "Test Exception" {:source :test :status http-400-bad-request} (EofException. "Test"))))) (is (= [error-cause-client-eagerly-closed "Connection eagerly closed by client" http-400-bad-request error-image-400-bad-request "org.eclipse.jetty.io.EofException"] (classify-error "test-classify-error" (ex-info "Test Exception" {:source :test :status http-400-bad-request} (EofException. "reset"))))) (is (= [error-cause-client-eagerly-closed "Connection eagerly closed by client" http-400-bad-request error-image-400-bad-request "org.eclipse.jetty.io.EofException"] (classify-error "test-classify-error" (EofException. "reset")))) (is (= [error-cause-instance-error "backend-request-timed-out" http-504-gateway-timeout error-image-504-gateway-timeout "java.util.concurrent.TimeoutException"] (classify-error "test-classify-error" (TimeoutException. "timeout")))) (is (= [error-cause-client-error "Timeout receiving bytes from client" http-408-request-timeout error-image-408-request-timeout "java.util.concurrent.TimeoutException"] (let [timeout-exception (TimeoutException. "timeout")] (.addSuppressed timeout-exception (Throwable. "HttpInput idle timeout")) (classify-error "test-classify-error" timeout-exception)))) (is (= [error-cause-client-error "Failed to upgrade to websocket connection" http-400-bad-request error-image-400-bad-request "org.eclipse.jetty.websocket.api.UpgradeException"] (classify-error "test-classify-error" (UpgradeException. nil http-400-bad-request "websocket upgrade failed")))) (is (= [error-cause-instance-error "backend-connect-error" http-502-bad-gateway error-image-502-connection-failed "java.net.ConnectException"] (classify-error "test-classify-error" (ConnectException. "Connection refused")))) (is (= [error-cause-instance-error "backend-connect-error" http-502-bad-gateway error-image-502-connection-failed "java.net.SocketTimeoutException"] (classify-error "test-classify-error" (SocketTimeoutException. "Connect Timeout")))) (is (= [error-cause-instance-error "backend-request-failed" http-502-bad-gateway error-image-502-connection-failed "java.net.SocketTimeoutException"] (classify-error "test-classify-error" (SocketTimeoutException. "Connection refused")))) (is (= [error-cause-instance-error "backend-request-failed" http-502-bad-gateway error-image-502-connection-failed "java.lang.Exception"] (classify-error "test-classify-error" (Exception. "Test Exception"))))))
null
https://raw.githubusercontent.com/twosigma/waiter/fa1d028f61f92c8be15ddb45cfa743b92eeb4058/waiter/test/waiter/process_request_test.clj
clojure
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright ( c ) Two Sigma Open Source , LLC distributed under the License is distributed on an " AS IS " BASIS , (ns waiter.process-request-test (:require [clj-time.core :as t] [clojure.core.async :as async] [clojure.string :as str] [clojure.test :refer :all] [metrics.counters :as counters] [metrics.meters :as meters] [plumbing.core :as pc] [qbits.jet.client.http :as http] [waiter.core :refer :all] [waiter.descriptor :as descriptor] [waiter.headers :as headers] [waiter.metrics :as metrics] [waiter.process-request :refer :all] [waiter.statsd :as statsd] [waiter.status-codes :refer :all] [waiter.test-helpers :refer :all] [waiter.util.async-utils :as au] [waiter.util.utils :as utils]) (:import (java.io ByteArrayOutputStream IOException) (java.net ConnectException SocketTimeoutException) (java.util.concurrent TimeoutException) (org.eclipse.jetty.client HttpClient) (org.eclipse.jetty.io EofException) (org.eclipse.jetty.websocket.api UpgradeException))) (deftest test-prepare-request-properties (let [test-cases (list {:name "test-prepare-request-properties:nil-inputs" :input {:request-properties nil :waiter-headers nil} :expected {:async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:empty-nil-inputs" :input {:request-properties {} :waiter-headers nil} :expected {:async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:nil-empty-inputs" :input {:request-properties nil :waiter-headers {}} :expected {:async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:empty-inputs" :input {:request-properties {} :waiter-headers {}} :expected {:async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:missing-timeout-header-1" :input {:request-properties {:fie "foe"} :waiter-headers {:foo "bar"}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:missing-timeout-header-2" :input {:request-properties {:fie "foe" :initial-socket-timeout-ms 100 :streaming-timeout-ms 200} :waiter-headers {:foo "bar"}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 100 :queue-timeout-ms nil :streaming-timeout-ms 200} } {:name "test-prepare-request-properties:invalid-timeout-header" :input {:request-properties {:fie "foe" :initial-socket-timeout-ms 100 :queue-timeout-ms 150 :streaming-timeout-ms nil} :waiter-headers {"timeout" "bar"}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 100 :queue-timeout-ms 150 :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:negative-timeout-header" :input {:request-properties {:fie "foe" :initial-socket-timeout-ms 100} :waiter-headers {"timeout" -50}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 100 :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:valid-timeout-header" :input {:request-properties {:fie "foe" :initial-socket-timeout-ms 100 :streaming-timeout-ms 200} :waiter-headers {"timeout" 50 "streaming-timeout" 250}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 50 :queue-timeout-ms nil :streaming-timeout-ms 250} } {:name "test-prepare-request-properties:invalid-queue-timeout-header" :input {:request-properties {:fie "foe" :queue-timeout-ms 150} :waiter-headers {"queue-timeout" "bar"}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms 150 :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:negative-queue-timeout-header" :input {:request-properties {:fie "foe" :queue-timeout-ms 150} :waiter-headers {"queue-timeout" -50}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms 150 :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:valid-queue-timeout-header" :input {:request-properties {:fie "foe" :queue-timeout-ms 150 :streaming-timeout-ms nil} :waiter-headers {"queue-timeout" 50}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms nil :queue-timeout-ms 50 :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:valid-both-timeout-headers" :input {:request-properties {:fie "foe" :initial-socket-timeout-ms 100 :queue-timeout-ms 150} :waiter-headers {"queue-timeout" 50 "timeout" 75}} :expected {:fie "foe" :async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 75 :queue-timeout-ms 50 :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:invalid-async-headers" :input {:request-properties {:fie "foe" :async-check-interval-ms 100 :async-request-timeout-ms 200} :waiter-headers {"async-check-interval" -50 "async-request-timeout" "foo"}} :expected {:fie "foe" :async-check-interval-ms 100 :async-request-timeout-ms 200 :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:valid-async-headers" :input {:request-properties {:fie "foe" :async-check-interval-ms 100 :async-request-timeout-ms 200} :waiter-headers {"async-check-interval" 50 "async-request-timeout" 250}} :expected {:fie "foe" :async-check-interval-ms 50 :async-request-timeout-ms 250 :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:too-large-async-request-timeout-header" :input {:request-properties {:fie "foe" :async-check-interval-ms 100 :async-request-max-timeout-ms 100000 :async-request-timeout-ms 200} :waiter-headers {"async-request-timeout" 101000}} :expected {:fie "foe" :async-check-interval-ms 100 :async-request-max-timeout-ms 100000 :async-request-timeout-ms 100000 :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:too-large-async-request-timeout-header" :input {:request-properties {:fie "foe" :async-check-interval-ms 100 :async-request-max-timeout-ms 100000 :async-request-timeout-ms 200} :waiter-headers {"async-request-timeout" 101000}} :expected {:fie "foe" :async-check-interval-ms 100 :async-request-max-timeout-ms 100000 :async-request-timeout-ms 100000 :initial-socket-timeout-ms nil :queue-timeout-ms nil :streaming-timeout-ms nil} } {:name "test-prepare-request-properties:empty-request-properties-with-token-defaults" :input {:request-properties {:initial-socket-timeout-ms 100 :queue-timeout-ms 150 :streaming-timeout-ms nil} :token-metadata {"queue-timeout-ms" 300000 "socket-timeout-ms" 900000 "streaming-timeout-ms" 20000} :waiter-headers nil} :expected {:async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 900000 :queue-timeout-ms 300000 :streaming-timeout-ms 20000} } {:name "test-prepare-request-properties:empty-request-properties-with-token-defaults-and-some-headers" :input {:request-properties {:initial-socket-timeout-ms 100 :queue-timeout-ms 150 :streaming-timeout-ms nil} :token-metadata {"queue-timeout-ms" 300000 "socket-timeout-ms" 900000 "streaming-timeout-ms" 20000} :waiter-headers {"queue-timeout" 50 "timeout" 75}} :expected {:async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 75 :queue-timeout-ms 50 :streaming-timeout-ms 20000} } {:name "test-prepare-request-properties:empty-request-properties-with-token-defaults-and-most-timeout-headers" :input {:request-properties {:initial-socket-timeout-ms 100 :queue-timeout-ms 150 :streaming-timeout-ms nil} :token-metadata {"queue-timeout-ms" 300000 "socket-timeout-ms" 900000 "streaming-timeout-ms" 20000} :waiter-headers {"queue-timeout" 50 "streaming-timeout" 95 "timeout" 75}} :expected {:async-check-interval-ms nil :async-request-timeout-ms nil :initial-socket-timeout-ms 75 :queue-timeout-ms 50 :streaming-timeout-ms 95} })] (doseq [{:keys [name input expected]} test-cases] (testing (str "Test " name) (let [{:keys [request-properties token-metadata waiter-headers]} input waiter-headers' (pc/map-keys #(str headers/waiter-header-prefix %) waiter-headers) actual (prepare-request-properties request-properties waiter-headers' token-metadata)] (is (= expected actual))))))) (deftest test-prepare-grpc-compliant-request-properties (let [request-properties-base {:async-check-interval-ms 1010 :async-request-timeout-ms 1020 :initial-socket-timeout-ms 1030 :queue-timeout-ms 1040 :streaming-timeout-ms 1050}] (doseq [{:keys [backend-proto request-headers request-properties-expected token-metadata] :as test-case} [{:backend-proto "h2c" :request-headers {"x-waiter-async-check-interval" "2100" "x-waiter-async-request-timeout" "2200" "x-waiter-timeout" "2300" "x-waiter-queue-timeout" "2400" "x-waiter-streaming-timeout" "2500"} :request-properties-expected {:async-request-timeout-ms 2200 :async-check-interval-ms 2100 :initial-socket-timeout-ms 2300 :queue-timeout-ms 2400 :streaming-timeout-ms 2500}} {:backend-proto "h2c" :request-headers {} :request-properties-expected {}} {:backend-proto "h2c" :request-headers {"x-waiter-queue-timeout" "2000"} :request-properties-expected {:queue-timeout-ms 2000}} {:backend-proto "h2c" :request-headers {"grpc-timeout" "3S"} :request-properties-expected {:queue-timeout-ms 1040}} {:backend-proto "h2c" :request-headers {"grpc-timeout" "3S" "x-waiter-queue-timeout" "2000"} :request-properties-expected {:queue-timeout-ms 2000}} {:backend-proto "http" :request-headers {"content-type" "application/grpc" "grpc-timeout" "3S"} :request-properties-expected {:queue-timeout-ms 1040}} {:backend-proto "h2c" :request-headers {"content-type" "application/grpc" "grpc-timeout" "3S"} :request-properties-expected {:queue-timeout-ms 3100}} {:backend-proto "h2c" :request-headers {"content-type" "application/grpc" "grpc-timeout" "3S" "x-waiter-queue-timeout" "2000"} :request-properties-expected {:queue-timeout-ms 2000}} {:backend-proto "h2c" :request-headers {"content-type" "application/grpc" "grpc-timeout" "3S" "x-waiter-queue-timeout" "2000"} :request-properties-expected {:initial-socket-timeout-ms 900000 :queue-timeout-ms 2000 :streaming-timeout-ms 20000} :token-metadata {"queue-timeout-ms" 300000 "socket-timeout-ms" 900000 "streaming-timeout-ms" 20000}}]] (let [{:keys [passthrough-headers waiter-headers]} (headers/split-headers request-headers) request-properties-actual (prepare-grpc-compliant-request-properties request-properties-base backend-proto passthrough-headers waiter-headers token-metadata)] (is (= (merge request-properties-base request-properties-expected) request-properties-actual) (str test-case)))))) (deftest test-stream-http-response-configure-idle-timeout (let [idle-timeout-atom (atom nil) output-stream (ByteArrayOutputStream.)] (with-redefs [set-idle-timeout! (fn [in-output-stream idle-timeout-ms] (is (= output-stream in-output-stream)) (reset! idle-timeout-atom idle-timeout-ms))] (let [body (async/chan) confirm-live-connection (fn [] :nothing) request-abort-callback (fn [_] :nothing) resp-chan (async/chan) streaming-timeout-ms 100 instance-request-properties {:output-buffer-size 1000000 :streaming-timeout-ms streaming-timeout-ms} reservation-status-promise (promise) request-state-chan (async/chan) metric-group nil waiter-debug-enabled? nil service-id "service-id" abort-request-chan (async/chan) error-chan (async/chan) response {:abort-request-chan abort-request-chan, :body body, :error-chan error-chan}] (async/close! error-chan) (async/close! body) (stream-http-response response confirm-live-connection request-abort-callback false resp-chan instance-request-properties reservation-status-promise request-state-chan metric-group waiter-debug-enabled? (metrics/stream-metric-map service-id)) (loop [] (let [message (async/<!! resp-chan)] (when (function? message) (message output-stream)) (when message (recur)))) (is (= streaming-timeout-ms @idle-timeout-atom)) (is (= :success @reservation-status-promise)) (is (nil? (async/<!! request-state-chan))))))) (defn- stream-response "Calls stream-http-response with statsd/inc! redefined to simply store the count of response bytes that it gets called with, and returns these counts in a vector" [bytes skip-streaming?] (let [bytes-reported (atom [])] (with-redefs [statsd/inc! (fn [_ metric value] (when (= metric "response_bytes") (swap! bytes-reported conj value)))] (let [body (async/chan) confirm-live-connection (fn [] :nothing) request-abort-callback (fn [_] :nothing) resp-chan (async/chan) instance-request-properties {:output-buffer-size 1000000 :streaming-timeout-ms 100} reservation-status-promise (promise) request-state-chan (async/chan) metric-group nil waiter-debug-enabled? nil service-id "service-id" abort-request-chan (async/chan) error-chan (async/chan) response {:abort-request-chan abort-request-chan, :body body, :error-chan error-chan}] (async/go-loop [bytes-streamed 0] (if (= bytes-streamed bytes) (do (async/close! error-chan) (async/close! body)) (let [bytes-to-stream (min 1024 (- bytes bytes-streamed))] (async/>! body (byte-array (repeat bytes-to-stream 0))) (recur (+ bytes-streamed bytes-to-stream))))) (when skip-streaming? (Thread/sleep 100) (async/close! resp-chan)) (stream-http-response response confirm-live-connection request-abort-callback skip-streaming? resp-chan instance-request-properties reservation-status-promise request-state-chan metric-group waiter-debug-enabled? (metrics/stream-metric-map service-id)) (loop [] (let [message (async/<!! resp-chan)] (when message (recur)))))) @bytes-reported)) (deftest test-stream-http-response (testing "Streaming the response" (testing "skipping should stream no bytes" (let [bytes-reported (stream-response 2048 true)] (is (zero? (count bytes-reported))))) (testing "should throttle calls to statsd to report bytes streamed" (let [bytes-reported (stream-response 1 false)] (is (= 1 (count bytes-reported))) (is (= [1] bytes-reported))) (let [bytes-reported (stream-response (* 1024 977) false)] (is (= 1 (count bytes-reported))) (is (= [1000448] bytes-reported))) (let [bytes-reported (stream-response (-> 1024 (* 977) (inc)) false)] (is (= 2 (count bytes-reported))) (is (= [1000448 1] bytes-reported))) (let [bytes-reported (stream-response 10000000 false)] (is (= 10 (count bytes-reported))) (is (= 10000000 (reduce + bytes-reported))) (is (= [1000448 1000448 1000448 1000448 1000448 1000448 1000448 1000448 1000448 995968] bytes-reported)))))) (deftest test-extract-async-request-response-data (testing "202-missing-location-header" (is (nil? (extract-async-request-response-data {:status http-202-accepted :headers {}} ":1234/query/for/status")))) (testing "200-not-async" (is (nil? (extract-async-request-response-data {:status http-200-ok, :headers {"location" "/result/location"}} ":1234/query/for/status")))) (testing "303-not-async" (is (nil? (extract-async-request-response-data {:status http-303-see-other, :headers {"location" "/result/location"}} ":1234/query/for/status")))) (testing "404-not-async" (is (nil? (extract-async-request-response-data {:status http-404-not-found, :headers {"location" "/result/location"}} ":1234/query/for/status")))) (testing "202-absolute-location" (is (= {:location "/result/location" :query-string nil} (extract-async-request-response-data {:status http-202-accepted :headers {"location" "/result/location"}} ":1234/query/for/status")))) (testing "202-relative-location-1" (is (= {:location "/query/result/location" :query-string nil} (extract-async-request-response-data {:status http-202-accepted :headers {"location" "../result/location"}} ":1234/query/for/status")))) (testing "202-relative-location-2" (is (= {:location "/query/for/result/location" :query-string nil} (extract-async-request-response-data {:status http-202-accepted :headers {"location" "result/location"}} ":1234/query/for/status")))) (testing "202-relative-location-two-levels" (is (= {:location "/result/location" :query-string "p=q&r=s|t"} (extract-async-request-response-data {:status http-202-accepted :headers {"location" "../../result/location?p=q&r=s|t"}} ":1234/query/for/status?u=v&w=x|y|z")))) (testing "202-absolute-url-same-host-port" (is (= {:location "/retrieve/result/location" :query-string nil} (extract-async-request-response-data {:status http-202-accepted :headers {"location" ":1234/retrieve/result/location"}} ":1234/query/for/status")))) (testing "202-absolute-url-different-host" (is (nil? (extract-async-request-response-data {:status http-202-accepted :headers {"location" ":1234/retrieve/result/location"}} ":1234/query/for/status")))) (testing "202-absolute-url-different-port" (is (nil? (extract-async-request-response-data {:status http-202-accepted :headers {"location" ":5678/retrieve/result/location"}} ":1234/query/for/status"))))) (deftest test-make-request (let [instance {:service-id "test-service-id", :host "example.com", :port 8080} backend-proto "http" request {:authorization/principal "" :authorization/user "test-user" :body "body"} request-properties {:connection-timeout-ms 123456, :initial-socket-timeout-ms 654321} passthrough-headers {"accept" "text/html" "accept-charset" "ISO-8859-1,utf-8;q=0.7,*;q=0.7" "accept-language" "en-us" "accept-encoding" "gzip,deflate" "authorization" "test-user-authorization" "cache-control" "no-cache" "connection" "keep-alive" "content-length" "12341234" "content-MD5" "Q2hlY2sgSW50ZWdyaXR5IQ==" "content-type" "application/x-www-form-urlencoded" "cookie" "$Version=1; Skin=new; x-waiter-auth=foo" "date" "Tue, 15 Nov 2015 08:12:31 GMT" "expect" "100-continue" "expires" "2200-08-09" "forwarded" "for=192.0.2.43, for=198.51.100.17" "from" "" "host" "www.test-source.com" "if-match" "737060cd8c284d8af7ad3082f209582d" "if-modified-since" "Sat, 29 Oct 2015 19:43:31 GMT" "keep-alive" "300" "origin" "" "pragma" "no-cache" "proxy-authenticate" "proxy-authenticate value" "proxy-authorization" "proxy-authorization value" "proxy-connection" "keep-alive" "referer" "-referer.com" "te" "trailers, deflate" "trailers" "trailer-name-1, trailer-name-2" "transfer-encoding" "trailers, deflate" "upgrade" "HTTP/2.0, HTTPS/1.3, IRC/6.9, RTA/x11, websocket" "user-agent" "Test/App" "x-cid" "239874623hk2er7908245" "x-forwarded-for" "client1, proxy1, proxy2" "x-http-method-override" "DELETE"} end-route "/end-route" app-password "test-password"] (let [expected-endpoint ":8080/end-route" make-basic-auth-fn (fn make-basic-auth-fn [endpoint username password] (is (= expected-endpoint endpoint)) (is (= username "waiter")) (is (= app-password password)) (Object.)) service-id->password-fn (fn service-id->password-fn [service-id] (is (= "test-service-id" service-id)) app-password) http-clients {:http1-client (http/client)} http-request-mock-factory (fn [passthrough-headers request-method-fn-call-counter proto-version] (fn [^HttpClient _ request-config] (swap! request-method-fn-call-counter inc) (is (= expected-endpoint (:url request-config))) (is (= :bytes (:as request-config))) (is (:auth request-config)) (is (= "body" (:body request-config))) (is (= 654321 (:idle-timeout request-config))) (is (= (-> passthrough-headers (assoc "cookie" "$Version=1; Skin=new") (dissoc "expect" "authorization" "connection" "keep-alive" "proxy-authenticate" "proxy-authorization" "te" "trailers" "transfer-encoding" "upgrade") (merge {"x-waiter-auth-principal" "test-user" "x-waiter-authenticated-principal" ""})) (:headers request-config))) (is (= proto-version (:version request-config)))))] (testing "make-request:headers:HTTP/1.0" (let [proto-version "HTTP/1.0" request-method-fn-call-counter (atom 0)] (with-redefs [http/request (http-request-mock-factory passthrough-headers request-method-fn-call-counter proto-version)] (make-request http-clients make-basic-auth-fn service-id->password-fn instance request request-properties passthrough-headers end-route nil backend-proto proto-version) (is (= 1 @request-method-fn-call-counter))))) (testing "make-request:headers:HTTP/2.0" (let [proto-version "HTTP/2.0" request-method-fn-call-counter (atom 0)] (with-redefs [http/request (http-request-mock-factory passthrough-headers request-method-fn-call-counter proto-version)] (make-request http-clients make-basic-auth-fn service-id->password-fn instance request request-properties passthrough-headers end-route nil backend-proto proto-version) (is (= 1 @request-method-fn-call-counter))))) (testing "make-request:headers-long-content-length" (let [proto-version "HTTP/1.0" request-method-fn-call-counter (atom 0) passthrough-headers (assoc passthrough-headers "content-length" "1234123412341234") statsd-inc-call-value (promise)] (with-redefs [http/request (http-request-mock-factory passthrough-headers request-method-fn-call-counter proto-version) statsd/inc! (fn [metric-group metric value] (is (nil? metric-group)) (is (= "request_content_length" metric)) (deliver statsd-inc-call-value value))] (make-request http-clients make-basic-auth-fn service-id->password-fn instance request request-properties passthrough-headers end-route nil backend-proto proto-version) (is (= 1 @request-method-fn-call-counter)) (is (= 1234123412341234 (deref statsd-inc-call-value 0 :statsd-inc-not-called))))))))) (deftest test-wrap-suspended-service (testing "returns error for suspended app" (let [handler (wrap-suspended-service (fn [_] {:status http-200-ok})) request {:descriptor {:service-id "service-id-1" :suspended-state {:suspended true :last-updated-by "test-user" :time (t/now)}}} {:keys [status body]} (handler request)] (is (= http-503-service-unavailable status)) (is (str/includes? body "Service has been suspended")) (is (str/includes? body "test-user")))) (testing "passes apps by default" (let [handler (wrap-suspended-service (fn [_] {:status http-200-ok})) request {} {:keys [status]} (handler request)] (is (= http-200-ok status))))) (deftest test-wrap-maintenance-mode (testing "returns 503 for token in maintenance mode with custom message" (let [handler (wrap-maintenance-mode (fn [_] {:status http-200-ok})) maintenance-message "test maintenance message" request {:waiter-discovery {:token-metadata {"maintenance" {"message" maintenance-message}} :token "token" :waiter-headers {}}} {:keys [status body]} (handler request)] (is (= http-503-service-unavailable status)) (is (str/includes? body maintenance-message)))) (testing "passes apps by default" (let [handler (wrap-maintenance-mode (fn [_] {:status http-200-ok})) request {:waiter-discovery {:token-metadata {} :token "token" :waiter-headers {}}} {:keys [status]} (handler request)] (is (= http-200-ok status))))) (deftest test-wrap-maintenance-mode-acceptor (testing "returns 503 for token in maintenance mode with custom message" (let [handler (wrap-maintenance-mode-acceptor (fn [_] (is false "Not supposed to call this handler") true)) maintenance-message "test maintenance message" upgrade-response (reified-upgrade-response) request {:upgrade-response upgrade-response :waiter-discovery {:token-metadata {"maintenance" {"message" maintenance-message}} :token "token" :waiter-headers {}}} response-status (handler request)] (is (= http-503-service-unavailable response-status)) (is (= http-503-service-unavailable (.getStatusCode upgrade-response))) (is (str/includes? (.getStatusReason upgrade-response) maintenance-message)))) (testing "passes apps by default" (let [handler (wrap-maintenance-mode-acceptor (fn [_] true)) request {:waiter-discovery {:token-metadata {} :token "token" :waiter-headers {}}} success? (handler request)] (is (true? success?))))) (deftest test-wrap-too-many-requests (let [error-response-throttle {:max-delay-ms 1000 :step-delay-ms 50 :step-size-per-min 100}] (testing "returns error for too many requests" (let [service-id (str "my-service-" (System/currentTimeMillis)) counter (metrics/service-counter service-id "request-counts" "waiting-for-available-instance")] (counters/inc! counter 10) (let [handler (wrap-too-many-requests (fn [_] {:status http-200-ok}) error-response-throttle) request {:descriptor {:service-id service-id :service-description {"max-queue-length" 5}}} response (handler request) {:keys [status body]} (cond-> response (au/chan? response) (async/<!!))] (is (= http-503-service-unavailable status)) (is (str/includes? body "Max queue length")))) (let [service-id (str "my-service-" (System/currentTimeMillis)) counter (metrics/service-counter service-id "request-counts" "waiting-for-available-instance") queue-length-meter (metrics/service-meter service-id "response-rate" "error" "queue-length")] (counters/inc! counter 10) (meters/mark! queue-length-meter 1000000) (let [handler (wrap-too-many-requests (fn [_] {:status http-200-ok}) error-response-throttle) request {:descriptor {:service-id service-id :service-description {"max-queue-length" 5}}} response (handler request) {:keys [status body]} (cond-> response (au/chan? response) (async/<!!))] (is (= http-503-service-unavailable status)) (is (str/includes? body "Max queue length"))))) (testing "passes service with fewer requests" (let [service-id (str "ok-service-" (System/currentTimeMillis)) counter (metrics/service-counter service-id "request-counts" "waiting-for-available-instance")] (counters/clear! counter) (counters/inc! counter 3) (let [handler (wrap-too-many-requests (fn [_] {:status http-200-ok}) error-response-throttle) request {:descriptor {:service-id service-id :service-description {"max-queue-length" 10}}} {:keys [status]} (handler request)] (is (= http-200-ok status))))))) (deftest test-redirect-on-process-error (let [request->descriptor-fn (fn [_] (throw (ex-info "Test exception" {:type :service-description-error :issue {"run-as-user" "missing-required-key"} :x-waiter-headers {"queue-length" 100}}))) service-invocation-authorized? (constantly true) start-new-service-fn (constantly nil) fallback-state-atom (atom {}) handler (descriptor/wrap-descriptor (fn [_] {:status http-200-ok}) request->descriptor-fn service-invocation-authorized? start-new-service-fn fallback-state-atom utils/exception->response)] (testing "with-query-params" (let [request {:headers {"host" "www.example.com:1234"}, :query-string "a=b&c=d", :uri "/path"} {:keys [headers status]} (handler request)] (is (= http-303-see-other status)) (is (= "/waiter-consent/path?a=b&c=d" (get headers "location"))))) (testing "with-query-params-and-default-port" (let [request {:headers {"host" "www.example.com"}, :query-string "a=b&c=d", :uri "/path"} {:keys [headers status]} (handler request)] (is (= http-303-see-other status)) (is (= "/waiter-consent/path?a=b&c=d" (get headers "location"))))) (testing "without-query-params" (let [request {:headers {"host" "www.example.com:1234"}, :uri "/path"} {:keys [headers status]} (handler request)] (is (= http-303-see-other status)) (is (= "/waiter-consent/path" (get headers "location"))))))) (deftest test-no-redirect-on-process-error (let [request->descriptor-fn (fn [_] (throw (Exception. "Exception message"))) service-invocation-authorized? (constantly true) start-new-service-fn (constantly nil) fallback-state-atom (atom {}) handler (descriptor/wrap-descriptor (fn [_] {:status http-200-ok}) request->descriptor-fn service-invocation-authorized? start-new-service-fn fallback-state-atom utils/exception->response) request {} {:keys [body headers status]} (handler request)] (is (= http-500-internal-server-error status)) (is (nil? (get headers "location"))) (is (= "text/plain" (get headers "content-type"))) (is (str/includes? (str body) "Internal error")))) (deftest test-message-reaches-user-on-process-error (let [request->descriptor-fn (fn [_] (throw (ex-info "Error message for user" {:status http-404-not-found}))) service-invocation-authorized? (constantly true) start-new-service-fn (constantly nil) fallback-state-atom (atom {}) handler (descriptor/wrap-descriptor (fn [_] {:status http-200-ok}) request->descriptor-fn service-invocation-authorized? start-new-service-fn fallback-state-atom utils/exception->response) request {} {:keys [body headers status]} (handler request)] (is (= http-404-not-found status)) (is (= "text/plain" (get headers "content-type"))) (is (str/includes? (str body) "Error message for user")))) (deftest test-determine-priority (let [position-generator-atom (atom 100)] (is (nil? (determine-priority position-generator-atom nil))) (is (nil? (determine-priority position-generator-atom {}))) (is (nil? (determine-priority position-generator-atom {"foo" 1}))) (is (= [1 -101] (determine-priority position-generator-atom {:priority 1}))) (is (= [2 -102] (determine-priority position-generator-atom {:priority 2}))) (is (= [4 -103] (determine-priority position-generator-atom {:priority 4 :source 2}))) (is (nil? (determine-priority position-generator-atom {"priority" 1}))) (is (nil? (determine-priority position-generator-atom {:priority "1"}))) (is (= 103 @position-generator-atom)))) (deftest test-classify-error (with-redefs [utils/message name] (is (= [error-cause-generic-error "Test Exception" http-500-internal-server-error error-image-500-internal-server-error "clojure.lang.ExceptionInfo"] (classify-error "test-classify-error" (ex-info "Test Exception" {:source :test})))) (is (= [:test-error "Test Exception" http-500-internal-server-error error-image-500-internal-server-error "clojure.lang.ExceptionInfo"] (classify-error "test-classify-error" (ex-info "Test Exception" {:error-cause :test-error :source :test})))) (is (= [error-cause-generic-error "Test 401 Exception" http-401-unauthorized nil "clojure.lang.ExceptionInfo"] (classify-error "test-classify-error" (ex-info "Test 401 Exception" {:source :test :status http-401-unauthorized})))) (is (= [error-cause-generic-error "Test 400 Exception" http-400-bad-request error-image-400-bad-request "clojure.lang.ExceptionInfo"] (classify-error "test-classify-error" (ex-info "Test 400 Exception" {:source :test :status http-400-bad-request})))) (is (= [error-cause-generic-error "Test 500 Exception" http-500-internal-server-error error-image-500-internal-server-error "clojure.lang.ExceptionInfo"] (classify-error "test-classify-error" (ex-info "Test 500 Exception" {:source :test :status http-500-internal-server-error})))) (is (= [error-cause-generic-error "Test Exception" http-400-bad-request error-image-400-bad-request "clojure.lang.ExceptionInfo"] (classify-error "test-classify-error" (ex-info "Test Exception" {:source :test :status http-400-bad-request :waiter/error-image error-image-400-bad-request})))) (is (= [error-cause-instance-error "backend-request-failed" http-502-bad-gateway error-image-502-connection-failed "java.io.IOException"] (classify-error "test-classify-error" (ex-info "Test Exception" {:source :test :status http-400-bad-request} (IOException. "Test"))))) (is (= [error-cause-instance-error "backend-request-failed" http-502-bad-gateway error-image-502-connection-failed "java.io.IOException"] (classify-error "test-classify-error" (IOException. "Test")))) (is (= [error-cause-client-error "Client action means stream is no longer needed" http-400-bad-request error-image-400-bad-request "java.io.IOException"] (classify-error "test-classify-error" (ex-info "Test Exception" {:source :test :status http-400-bad-request} (IOException. "cancel_stream_error"))))) (is (= [error-cause-client-error "Client action means stream is no longer needed" http-400-bad-request error-image-400-bad-request "java.io.IOException"] (classify-error "test-classify-error" (IOException. "cancel_stream_error")))) (is (= [error-cause-generic-error "Internal error: session already closed" http-500-internal-server-error error-image-500-internal-server-error "java.lang.IllegalStateException"] (classify-error "test-classify-error" (IllegalStateException. "session closed")))) (is (= [error-cause-generic-error "invalid state" http-400-bad-request error-image-400-bad-request "java.lang.IllegalStateException"] (classify-error "test-classify-error" (IllegalStateException. "invalid state")))) (let [exception (IOException. "internal_error")] (->> (into-array StackTraceElement [(StackTraceElement. "org.eclipse.jetty.http2.client.http.HttpReceiverOverHTTP2" "onReset" "HttpReceivedOverHTTP2.java" 169) (StackTraceElement. "org.eclipse.jetty.http2.api.Stream$Listener" "onReset" "Stream.java" 177) (StackTraceElement. "org.eclipse.jetty.http2.HTTP2Stream" "notifyReset" "HTTP2Stream.java" 574)]) (.setStackTrace exception)) (is (= [error-cause-client-error "Client send invalid data to HTTP/2 backend" http-400-bad-request error-image-400-bad-request "java.io.IOException"] (classify-error "test-classify-error" exception)))) (is (= [error-cause-instance-error "backend-request-failed" http-502-bad-gateway error-image-502-connection-failed "java.io.IOException"] (classify-error "test-classify-error" (IOException. "internal_error")))) (is (= [error-cause-server-eagerly-closed "Connection eagerly closed by server" http-400-bad-request error-image-400-bad-request "java.io.IOException"] (classify-error "test-classify-error" (IOException. "no_error")))) (is (= [error-cause-client-error "Connection unexpectedly closed while streaming request" http-400-bad-request error-image-400-bad-request "org.eclipse.jetty.io.EofException"] (classify-error "test-classify-error" (ex-info "Test Exception" {:source :test :status http-400-bad-request} (EofException. "Test"))))) (is (= [error-cause-client-eagerly-closed "Connection eagerly closed by client" http-400-bad-request error-image-400-bad-request "org.eclipse.jetty.io.EofException"] (classify-error "test-classify-error" (ex-info "Test Exception" {:source :test :status http-400-bad-request} (EofException. "reset"))))) (is (= [error-cause-client-eagerly-closed "Connection eagerly closed by client" http-400-bad-request error-image-400-bad-request "org.eclipse.jetty.io.EofException"] (classify-error "test-classify-error" (EofException. "reset")))) (is (= [error-cause-instance-error "backend-request-timed-out" http-504-gateway-timeout error-image-504-gateway-timeout "java.util.concurrent.TimeoutException"] (classify-error "test-classify-error" (TimeoutException. "timeout")))) (is (= [error-cause-client-error "Timeout receiving bytes from client" http-408-request-timeout error-image-408-request-timeout "java.util.concurrent.TimeoutException"] (let [timeout-exception (TimeoutException. "timeout")] (.addSuppressed timeout-exception (Throwable. "HttpInput idle timeout")) (classify-error "test-classify-error" timeout-exception)))) (is (= [error-cause-client-error "Failed to upgrade to websocket connection" http-400-bad-request error-image-400-bad-request "org.eclipse.jetty.websocket.api.UpgradeException"] (classify-error "test-classify-error" (UpgradeException. nil http-400-bad-request "websocket upgrade failed")))) (is (= [error-cause-instance-error "backend-connect-error" http-502-bad-gateway error-image-502-connection-failed "java.net.ConnectException"] (classify-error "test-classify-error" (ConnectException. "Connection refused")))) (is (= [error-cause-instance-error "backend-connect-error" http-502-bad-gateway error-image-502-connection-failed "java.net.SocketTimeoutException"] (classify-error "test-classify-error" (SocketTimeoutException. "Connect Timeout")))) (is (= [error-cause-instance-error "backend-request-failed" http-502-bad-gateway error-image-502-connection-failed "java.net.SocketTimeoutException"] (classify-error "test-classify-error" (SocketTimeoutException. "Connection refused")))) (is (= [error-cause-instance-error "backend-request-failed" http-502-bad-gateway error-image-502-connection-failed "java.lang.Exception"] (classify-error "test-classify-error" (Exception. "Test Exception"))))))
6251c0eab71067d37761485409102c5977db82c849d5a72453db6a0274c0bcf9
fumieval/deriving-aeson
test.hs
# LANGUAGE DerivingVia , # LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} module Main where import Data.Aeson import Deriving.Aeson import Deriving.Aeson.Stock import System.Exit (die) import qualified Data.ByteString.Lazy.Char8 as BL data User = User { userId :: Int , userName :: String , userAPIToken :: Maybe String , userType :: String } deriving Generic deriving (FromJSON, ToJSON) via CustomJSON '[ OmitNothingFields , FieldLabelModifier '[StripPrefix "user", CamelToSnake, Rename "type" "user_type"] ] User data Foo = Foo { fooFoo :: Int, fooBar :: Int } deriving Generic deriving (FromJSON, ToJSON) via Prefixed "foo" Foo testData :: [User] testData = [User 42 "Alice" Nothing "human", User 43 "Bob" (Just "xyz") "bot"] data MultipleCtorRenames = RenamedCtorOptA | RenamedCtorOptB (Maybe ()) | RenamedCtorOptC Char deriving (Eq, Generic, Show) deriving (ToJSON) via CustomJSON [ ConstructorTagModifier (Rename "RenamedCtorOptA" "nullary") , ConstructorTagModifier (Rename "RenamedCtorOptB" "twisted-bool") , ConstructorTagModifier (Rename "RenamedCtorOptC" "wrapped-char") ] MultipleCtorRenames data MultipleFieldRenames = MultipleFieldRenames { fooField1 :: Int , fooField2 :: Bool , fooField3 :: String } deriving (Eq, Generic, Show) deriving (ToJSON) via CustomJSON [ FieldLabelModifier (Rename "fooField1" "field-1") , FieldLabelModifier (Rename "fooField2" "field-2") , FieldLabelModifier (Rename "fooField3" "field-3") ] MultipleFieldRenames main = do BL.putStrLn $ encode testData BL.putStrLn $ encode $ Foo 0 1 assertEq (toJSON RenamedCtorOptA) (object [("tag", "nullary")]) "Support multiple constructor modifiers" assertEq (toJSON $ RenamedCtorOptB Nothing) (object [("tag", String "twisted-bool"), ("contents", Null)]) "Support multiple constructor modifiers" assertEq (toJSON $ RenamedCtorOptC '?') (object [("tag", String "wrapped-char"), ("contents", String "?")]) "Support multiple constructor modifiers" assertEq (toJSON $ MultipleFieldRenames 42 True "meaning of life") (object [("field-1", Number 42) ,("field-2", Bool True) ,("field-3", String "meaning of life") ]) "Support multiple field modifiers" assertEq :: (Show a, Eq a) => a -> a -> String -> IO () assertEq x y expectation | x == y = pure () | otherwise = die msg where msg = concat [expectation, " -- not fulfilled:\n\t", show x, "\n\t /= \n\t", show y]
null
https://raw.githubusercontent.com/fumieval/deriving-aeson/817b71499b6dd3174c92cbe6377f0edbdaba485b/tests/test.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE DerivingVia , # LANGUAGE DeriveGeneric # module Main where import Data.Aeson import Deriving.Aeson import Deriving.Aeson.Stock import System.Exit (die) import qualified Data.ByteString.Lazy.Char8 as BL data User = User { userId :: Int , userName :: String , userAPIToken :: Maybe String , userType :: String } deriving Generic deriving (FromJSON, ToJSON) via CustomJSON '[ OmitNothingFields , FieldLabelModifier '[StripPrefix "user", CamelToSnake, Rename "type" "user_type"] ] User data Foo = Foo { fooFoo :: Int, fooBar :: Int } deriving Generic deriving (FromJSON, ToJSON) via Prefixed "foo" Foo testData :: [User] testData = [User 42 "Alice" Nothing "human", User 43 "Bob" (Just "xyz") "bot"] data MultipleCtorRenames = RenamedCtorOptA | RenamedCtorOptB (Maybe ()) | RenamedCtorOptC Char deriving (Eq, Generic, Show) deriving (ToJSON) via CustomJSON [ ConstructorTagModifier (Rename "RenamedCtorOptA" "nullary") , ConstructorTagModifier (Rename "RenamedCtorOptB" "twisted-bool") , ConstructorTagModifier (Rename "RenamedCtorOptC" "wrapped-char") ] MultipleCtorRenames data MultipleFieldRenames = MultipleFieldRenames { fooField1 :: Int , fooField2 :: Bool , fooField3 :: String } deriving (Eq, Generic, Show) deriving (ToJSON) via CustomJSON [ FieldLabelModifier (Rename "fooField1" "field-1") , FieldLabelModifier (Rename "fooField2" "field-2") , FieldLabelModifier (Rename "fooField3" "field-3") ] MultipleFieldRenames main = do BL.putStrLn $ encode testData BL.putStrLn $ encode $ Foo 0 1 assertEq (toJSON RenamedCtorOptA) (object [("tag", "nullary")]) "Support multiple constructor modifiers" assertEq (toJSON $ RenamedCtorOptB Nothing) (object [("tag", String "twisted-bool"), ("contents", Null)]) "Support multiple constructor modifiers" assertEq (toJSON $ RenamedCtorOptC '?') (object [("tag", String "wrapped-char"), ("contents", String "?")]) "Support multiple constructor modifiers" assertEq (toJSON $ MultipleFieldRenames 42 True "meaning of life") (object [("field-1", Number 42) ,("field-2", Bool True) ,("field-3", String "meaning of life") ]) "Support multiple field modifiers" assertEq :: (Show a, Eq a) => a -> a -> String -> IO () assertEq x y expectation | x == y = pure () | otherwise = die msg where msg = concat [expectation, " -- not fulfilled:\n\t", show x, "\n\t /= \n\t", show y]
50a90012469adb6c1a906c1ebf517c2f62e53c54da230bbdced2d0dbeaf0a924
darwin/blender-clojure
pyv8.cljs
(ns bcljs.tests.suites.pyv8 (:require [cljs.test :refer-macros [deftest is testing run-tests]] [goog.object :as gobj])) (deftest symbol-property-access ; this was crashing ; (let [prop-name (.-iterator js/Symbol) pyobj (js/test.get_simple_python_sequence)] (is (= ::null (gobj/get pyobj prop-name ::null)))))
null
https://raw.githubusercontent.com/darwin/blender-clojure/bbdb5071d3f4a33ccbdb5a67818df58ae6767716/tests/e2e/src/main/bcljs/tests/suites/pyv8.cljs
clojure
this was crashing
(ns bcljs.tests.suites.pyv8 (:require [cljs.test :refer-macros [deftest is testing run-tests]] [goog.object :as gobj])) (deftest symbol-property-access (let [prop-name (.-iterator js/Symbol) pyobj (js/test.get_simple_python_sequence)] (is (= ::null (gobj/get pyobj prop-name ::null)))))