_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 |
|---|---|---|---|---|---|---|---|---|
aaac49b26b0c9048acc0dc4e1647b8720e6a446253118e20fdaf53cbabf00e0a | andrejbauer/plzoo | machine.ml | * A simple machine with a program , RAM , program counter and a stack pointer . The program
is an array of instructions . The stack grows downwards . Arithmetical and boolean
operations operate on the stack .
is an array of instructions. The stack grows downwards. Arithmetical and boolean
operations operate on the stack. *)
(** The machine instructions. *)
type instruction =
| NOOP (* no operation *)
| SET of int (* pop from stack and store in the given location *)
| GET of int (* push from given location onto stack *)
| PUSH of int (* push integer constant onto stack *)
| ADD (* addition *)
| SUB (* subtraction *)
| MUL (* multiplication *)
| DIV (* division *)
| MOD (* remainder *)
| EQ (* equal *)
| LT (* less than *)
| AND (* conjunction *)
| OR (* disjunction *)
| NOT (* negation *)
| JMP of int (* relative jump *)
relative jump if zero on the stack
| PRINT (* pop from stack and print *)
(** Print an instruction. *)
let print_instruction instr ppf =
match instr with
| NOOP -> Format.fprintf ppf "NOOP"
| SET k -> Format.fprintf ppf "SET %d" k
| GET k -> Format.fprintf ppf "GET %d" k
| PUSH k -> Format.fprintf ppf "PUSH %d" k
| ADD -> Format.fprintf ppf "ADD"
| SUB -> Format.fprintf ppf "SUB"
| MUL -> Format.fprintf ppf "MUL"
| DIV -> Format.fprintf ppf "DIV"
| MOD -> Format.fprintf ppf "MOD"
| AND -> Format.fprintf ppf "AND"
| EQ -> Format.fprintf ppf "EQ"
| LT -> Format.fprintf ppf "LT"
| OR -> Format.fprintf ppf "OR"
| NOT -> Format.fprintf ppf "NOT"
| JMP k -> Format.fprintf ppf "JMP %d" k
| JMPZ k -> Format.fprintf ppf "JMPZ %d" k
| PRINT -> Format.fprintf ppf "PRINT"
(** Machine errors *)
type error =
| Illegal_address
| Illegal_instruction
| Zero_division
(** Print a machine error *)
let print_error err ppf =
match err with
| Illegal_address -> Format.fprintf ppf "illegal address"
| Illegal_instruction -> Format.fprintf ppf "illegal instruction"
| Zero_division -> Format.fprintf ppf "division by zero"
exception Error of error
(** Signal a machine error *)
let runtime_error err = raise (Error err)
(** Print the program *)
let print_code code ppf =
Array.iteri (fun k instr -> Format.fprintf ppf "%03d %t@\n" k (print_instruction instr)) code
(** The state of the machine *)
type state = {
code : instruction array ; (* program *)
ram : int array ; (* random-access memory *)
mutable pc : int ; (* program counter *)
mutable sp : int (* stack pointer *)
}
* Initialize the state with give program and RAM size
let make code ram_size =
{
code = code ;
ram = Array.init ram_size (fun _ -> 0) ;
pc = 0 ;
sp = ram_size - 1
}
(** In state [s], read from memory location [k] *)
let read s k =
try
s.ram.(k)
with
| Invalid_argument _ -> runtime_error Illegal_address
(** In state [s], write [x] to memory location [k] *)
let write s k x =
try
s.ram.(k) <- x
with
| Invalid_argument _ -> runtime_error Illegal_address
(** In given state [s], pop from the stack *)
let pop s =
let x = read s s.sp in
s.sp <- s.sp + 1 ;
x
(** In given state [s], push [x] onto the stack *)
let push s x =
s.sp <- s.sp - 1 ;
write s s.sp x
(** Execute a command in the given state. *)
let exec s =
match s.code.(s.pc) with
| NOOP -> ()
| SET k ->
let a = pop s in
write s k a
| GET k ->
let a = read s k in
push s a
| PUSH x ->
push s x
| ADD ->
let y = pop s in
let x = pop s in
push s (x + y)
| SUB ->
let y = pop s in
let x = pop s in
push s (x - y)
| MUL ->
let y = pop s in
let x = pop s in
push s (x * y)
| DIV ->
let y = pop s in
let x = pop s in
if y <> 0 then push s (x / y) else runtime_error Zero_division
| MOD ->
let y = pop s in
let x = pop s in
if y <> 0 then push s (x mod y) else runtime_error Zero_division
| EQ ->
let y = pop s in
let x = pop s in
if x = y then push s 1 else push s 0
| LT ->
let y = pop s in
let x = pop s in
if x < y then push s 1 else push s 0
| AND ->
let b = pop s in
let a = pop s in
if a <> 0 && b <> 0 then push s 1 else push s 0
| OR ->
let b = pop s in
let a = pop s in
if a <> 0 || b <> 0 then push s 1 else push s 0
| NOT ->
let a = pop s in
if a <> 0 then push s 0 else push s 1
| JMP k ->
s.pc <- s.pc + k
| JMPZ k ->
let a = pop s in
if a = 0 then s.pc <- s.pc + k
| PRINT ->
let a = pop s in
Format.printf "%d@." a
(** In given state [s], run the program. *)
let run s =
while s.pc < Array.length s.code do
exec s ;
s.pc <- s.pc + 1
done
| null | https://raw.githubusercontent.com/andrejbauer/plzoo/ae6041c65baf1eebf65a60617819efeb8dcd3420/src/comm/machine.ml | ocaml | * The machine instructions.
no operation
pop from stack and store in the given location
push from given location onto stack
push integer constant onto stack
addition
subtraction
multiplication
division
remainder
equal
less than
conjunction
disjunction
negation
relative jump
pop from stack and print
* Print an instruction.
* Machine errors
* Print a machine error
* Signal a machine error
* Print the program
* The state of the machine
program
random-access memory
program counter
stack pointer
* In state [s], read from memory location [k]
* In state [s], write [x] to memory location [k]
* In given state [s], pop from the stack
* In given state [s], push [x] onto the stack
* Execute a command in the given state.
* In given state [s], run the program. | * A simple machine with a program , RAM , program counter and a stack pointer . The program
is an array of instructions . The stack grows downwards . Arithmetical and boolean
operations operate on the stack .
is an array of instructions. The stack grows downwards. Arithmetical and boolean
operations operate on the stack. *)
type instruction =
relative jump if zero on the stack
let print_instruction instr ppf =
match instr with
| NOOP -> Format.fprintf ppf "NOOP"
| SET k -> Format.fprintf ppf "SET %d" k
| GET k -> Format.fprintf ppf "GET %d" k
| PUSH k -> Format.fprintf ppf "PUSH %d" k
| ADD -> Format.fprintf ppf "ADD"
| SUB -> Format.fprintf ppf "SUB"
| MUL -> Format.fprintf ppf "MUL"
| DIV -> Format.fprintf ppf "DIV"
| MOD -> Format.fprintf ppf "MOD"
| AND -> Format.fprintf ppf "AND"
| EQ -> Format.fprintf ppf "EQ"
| LT -> Format.fprintf ppf "LT"
| OR -> Format.fprintf ppf "OR"
| NOT -> Format.fprintf ppf "NOT"
| JMP k -> Format.fprintf ppf "JMP %d" k
| JMPZ k -> Format.fprintf ppf "JMPZ %d" k
| PRINT -> Format.fprintf ppf "PRINT"
type error =
| Illegal_address
| Illegal_instruction
| Zero_division
let print_error err ppf =
match err with
| Illegal_address -> Format.fprintf ppf "illegal address"
| Illegal_instruction -> Format.fprintf ppf "illegal instruction"
| Zero_division -> Format.fprintf ppf "division by zero"
exception Error of error
let runtime_error err = raise (Error err)
let print_code code ppf =
Array.iteri (fun k instr -> Format.fprintf ppf "%03d %t@\n" k (print_instruction instr)) code
type state = {
}
* Initialize the state with give program and RAM size
let make code ram_size =
{
code = code ;
ram = Array.init ram_size (fun _ -> 0) ;
pc = 0 ;
sp = ram_size - 1
}
let read s k =
try
s.ram.(k)
with
| Invalid_argument _ -> runtime_error Illegal_address
let write s k x =
try
s.ram.(k) <- x
with
| Invalid_argument _ -> runtime_error Illegal_address
let pop s =
let x = read s s.sp in
s.sp <- s.sp + 1 ;
x
let push s x =
s.sp <- s.sp - 1 ;
write s s.sp x
let exec s =
match s.code.(s.pc) with
| NOOP -> ()
| SET k ->
let a = pop s in
write s k a
| GET k ->
let a = read s k in
push s a
| PUSH x ->
push s x
| ADD ->
let y = pop s in
let x = pop s in
push s (x + y)
| SUB ->
let y = pop s in
let x = pop s in
push s (x - y)
| MUL ->
let y = pop s in
let x = pop s in
push s (x * y)
| DIV ->
let y = pop s in
let x = pop s in
if y <> 0 then push s (x / y) else runtime_error Zero_division
| MOD ->
let y = pop s in
let x = pop s in
if y <> 0 then push s (x mod y) else runtime_error Zero_division
| EQ ->
let y = pop s in
let x = pop s in
if x = y then push s 1 else push s 0
| LT ->
let y = pop s in
let x = pop s in
if x < y then push s 1 else push s 0
| AND ->
let b = pop s in
let a = pop s in
if a <> 0 && b <> 0 then push s 1 else push s 0
| OR ->
let b = pop s in
let a = pop s in
if a <> 0 || b <> 0 then push s 1 else push s 0
| NOT ->
let a = pop s in
if a <> 0 then push s 0 else push s 1
| JMP k ->
s.pc <- s.pc + k
| JMPZ k ->
let a = pop s in
if a = 0 then s.pc <- s.pc + k
| PRINT ->
let a = pop s in
Format.printf "%d@." a
let run s =
while s.pc < Array.length s.code do
exec s ;
s.pc <- s.pc + 1
done
|
b45b76667426a33fdbc0591b815e71de9f63dde590526317b2c2ea5272858ac1 | exoscale/clojure-kubernetes-client | v1_stateful_set_update_strategy.clj | (ns clojure-kubernetes-client.specs.v1-stateful-set-update-strategy
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
[clojure-kubernetes-client.specs.v1-rolling-update-stateful-set-strategy :refer :all]
)
(:import (java.io File)))
(declare v1-stateful-set-update-strategy-data v1-stateful-set-update-strategy)
(def v1-stateful-set-update-strategy-data
{
(ds/opt :rollingUpdate) v1-rolling-update-stateful-set-strategy
(ds/opt :type) string?
})
(def v1-stateful-set-update-strategy
(ds/spec
{:name ::v1-stateful-set-update-strategy
:spec v1-stateful-set-update-strategy-data}))
| null | https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/v1_stateful_set_update_strategy.clj | clojure | (ns clojure-kubernetes-client.specs.v1-stateful-set-update-strategy
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
[clojure-kubernetes-client.specs.v1-rolling-update-stateful-set-strategy :refer :all]
)
(:import (java.io File)))
(declare v1-stateful-set-update-strategy-data v1-stateful-set-update-strategy)
(def v1-stateful-set-update-strategy-data
{
(ds/opt :rollingUpdate) v1-rolling-update-stateful-set-strategy
(ds/opt :type) string?
})
(def v1-stateful-set-update-strategy
(ds/spec
{:name ::v1-stateful-set-update-strategy
:spec v1-stateful-set-update-strategy-data}))
| |
210efc6a178cdc577b6c786a3c7a3309876d1de4a5561109c5c482fdfdd7241f | janestreet/sexp | main_to_csv.ml | open Core
open Sexp_app
let myprotect f x =
try Some (f x) with
| _ -> None
;;
let main ~two_pass_processing ~view_atoms_as_strings ~delimiter:sep =
let sexps =
let channel = Lexing.from_channel In_channel.stdin in
Lazy_list.build ~seed:() ~f:(fun () ->
match myprotect Sexp.scan_sexp channel with
| None -> None
| Some sexp -> Some (sexp, ()))
in
Csv_file.write
Out_channel.stdout
(To_csv.csv_of_sexp ~two_pass_processing ~view_atoms_as_strings sexps)
~sep
;;
let command =
Command.basic
~summary:"converts a list of record s-expressions into CSV format"
~readme:(fun () ->
{|
Example
COMMAND
sexp to-csv <INPUT >OUTPUT
INPUT
((foo a) (bar 2) (baz 8))
((foo b) (bar 3) (baz 88))
((foo c) (bar 4) (baz 888))
OUTPUT
foo,bar,baz
a,2,8
b,3,88
c,4,888
|})
(let%map_open.Command view_atoms_as_sexps =
flag
"atoms-as-sexps"
no_arg
~doc:
" when the extracted CSV value is an atom, dump it as a string rather than as \
an s-expression (Note: this causes atoms with embedded whitespace to show up \
triple-quoted)"
and two_pass_processing =
flag
"two-pass-processing"
no_arg
~doc:
" Uses one pass the gather all columns names for the header and a second to \
generate the rows. This ensures that no data will be discarded from any \
record, but requires more memory. Without this option, the header is \
generated solely by the first record. Any field not found in the first \
record---but found in later records---will be dropped."
and delimiter =
flag
"delimiter"
(optional_with_default ',' char)
~doc:(sprintf "CHAR use this delimiter instead of ','")
in
fun () ->
main
~delimiter
~two_pass_processing
~view_atoms_as_strings:(not view_atoms_as_sexps))
;;
| null | https://raw.githubusercontent.com/janestreet/sexp/2414e8f11fadff4a33fff87bd79fb614ee7642f3/bin/main_to_csv.ml | ocaml | open Core
open Sexp_app
let myprotect f x =
try Some (f x) with
| _ -> None
;;
let main ~two_pass_processing ~view_atoms_as_strings ~delimiter:sep =
let sexps =
let channel = Lexing.from_channel In_channel.stdin in
Lazy_list.build ~seed:() ~f:(fun () ->
match myprotect Sexp.scan_sexp channel with
| None -> None
| Some sexp -> Some (sexp, ()))
in
Csv_file.write
Out_channel.stdout
(To_csv.csv_of_sexp ~two_pass_processing ~view_atoms_as_strings sexps)
~sep
;;
let command =
Command.basic
~summary:"converts a list of record s-expressions into CSV format"
~readme:(fun () ->
{|
Example
COMMAND
sexp to-csv <INPUT >OUTPUT
INPUT
((foo a) (bar 2) (baz 8))
((foo b) (bar 3) (baz 88))
((foo c) (bar 4) (baz 888))
OUTPUT
foo,bar,baz
a,2,8
b,3,88
c,4,888
|})
(let%map_open.Command view_atoms_as_sexps =
flag
"atoms-as-sexps"
no_arg
~doc:
" when the extracted CSV value is an atom, dump it as a string rather than as \
an s-expression (Note: this causes atoms with embedded whitespace to show up \
triple-quoted)"
and two_pass_processing =
flag
"two-pass-processing"
no_arg
~doc:
" Uses one pass the gather all columns names for the header and a second to \
generate the rows. This ensures that no data will be discarded from any \
record, but requires more memory. Without this option, the header is \
generated solely by the first record. Any field not found in the first \
record---but found in later records---will be dropped."
and delimiter =
flag
"delimiter"
(optional_with_default ',' char)
~doc:(sprintf "CHAR use this delimiter instead of ','")
in
fun () ->
main
~delimiter
~two_pass_processing
~view_atoms_as_strings:(not view_atoms_as_sexps))
;;
| |
3611a195151e16ef327749f1efbf676a52517a8c0d2a5401f7a69259bc7d4de4 | mmontone/gestalt | dlist.lisp | (in-package :dlist)
(defstruct (dlist
(:print-function print-dlist))
head
tail)
(defun print-dlist (dlist stream &rest args)
(declare (ignore args))
(print-unreadable-object (dlist stream :identity t :type t)
(format stream "~A" (dlist-elements dlist))))
(defstruct (dlink
(:print-function print-dlink))
content
prev
next)
(defun print-dlink (dlink stream &rest args)
(declare (ignore args))
(print-unreadable-object (dlink stream :type t :identity t)
(format stream "~A" (dlink-content dlink))))
(defun insert-between (dlist before after data)
"Insert a fresh link containing DATA after existing link BEFORE if not nil and before existing link AFTER if not nil"
(let ((new-link (make-dlink :content data :prev before :next after)))
(if (null before)
(setf (dlist-head dlist) new-link)
(setf (dlink-next before) new-link))
(if (null after)
(setf (dlist-tail dlist) new-link)
(setf (dlink-prev after) new-link))
new-link))
(defun insert-before (dlist dlink data)
"Insert a fresh link containing DATA before existing link DLINK"
(insert-between dlist (dlink-prev dlink) dlink data))
(defun insert-after (dlist dlink data)
"Insert a fresh link containing DATA after existing link DLINK"
(insert-between dlist dlink (dlink-next dlink) data))
(defun insert-head (dlist data)
"Insert a fresh link containing DATA at the head of DLIST"
(insert-between dlist nil (dlist-head dlist) data))
(defun insert-tail (dlist data)
"Insert a fresh link containing DATA at the tail of DLIST"
(insert-between dlist (dlist-tail dlist) nil data))
(defun remove-link (dlist dlink)
"Remove link DLINK from DLIST and return its content"
(let ((before (dlink-prev dlink))
(after (dlink-next dlink)))
(if (null before)
(setf (dlist-head dlist) after)
(setf (dlink-next before) after))
(if (null after)
(setf (dlist-tail dlist) before)
(setf (dlink-prev after) before)))
dlist)
(defun dlist-elements (dlist)
"Returns the elements of DLIST as a list"
(labels ((extract-values (dlink acc)
(if (null dlink)
acc
(extract-values (dlink-next dlink) (cons (dlink-content dlink) acc)))))
(reverse (extract-values (dlist-head dlist) nil))))
(defmacro do-dlist ((var dlist &optional result) &rest body)
`(progn
(map-dlist (lambda (,var)
,@body)
,dlist)
,result))
(defun map-dlist (function dlist)
(mapcar function (dlist-elements dlist)))
(defun reduce-dlist (function dlist &key (initial-value nil ivp))
(if ivp
(reduce function (dlist-elements dlist)
:initial-value initial-value)
(reduce function (dlist-elements dlist))))
(defun null-dlist (dlist)
(equalp (length-dlist dlist) 0))
(defun length-dlist (dlist)
(length (dlist-elements dlist)))
(defun dlist-position (dlink dlist)
(loop with position = 0
for dlist-dlink = (dlist-head dlist) then (dlink-next dlist-dlink)
while (not (null dlist-dlink))
if (eql dlink dlist-dlink)
do (return-from dlist-position position)
else do (incf position))
nil) | null | https://raw.githubusercontent.com/mmontone/gestalt/fd019c0ca03b4efc73b9ddd3db1e3ed211233428/deps/util/dlist.lisp | lisp | (in-package :dlist)
(defstruct (dlist
(:print-function print-dlist))
head
tail)
(defun print-dlist (dlist stream &rest args)
(declare (ignore args))
(print-unreadable-object (dlist stream :identity t :type t)
(format stream "~A" (dlist-elements dlist))))
(defstruct (dlink
(:print-function print-dlink))
content
prev
next)
(defun print-dlink (dlink stream &rest args)
(declare (ignore args))
(print-unreadable-object (dlink stream :type t :identity t)
(format stream "~A" (dlink-content dlink))))
(defun insert-between (dlist before after data)
"Insert a fresh link containing DATA after existing link BEFORE if not nil and before existing link AFTER if not nil"
(let ((new-link (make-dlink :content data :prev before :next after)))
(if (null before)
(setf (dlist-head dlist) new-link)
(setf (dlink-next before) new-link))
(if (null after)
(setf (dlist-tail dlist) new-link)
(setf (dlink-prev after) new-link))
new-link))
(defun insert-before (dlist dlink data)
"Insert a fresh link containing DATA before existing link DLINK"
(insert-between dlist (dlink-prev dlink) dlink data))
(defun insert-after (dlist dlink data)
"Insert a fresh link containing DATA after existing link DLINK"
(insert-between dlist dlink (dlink-next dlink) data))
(defun insert-head (dlist data)
"Insert a fresh link containing DATA at the head of DLIST"
(insert-between dlist nil (dlist-head dlist) data))
(defun insert-tail (dlist data)
"Insert a fresh link containing DATA at the tail of DLIST"
(insert-between dlist (dlist-tail dlist) nil data))
(defun remove-link (dlist dlink)
"Remove link DLINK from DLIST and return its content"
(let ((before (dlink-prev dlink))
(after (dlink-next dlink)))
(if (null before)
(setf (dlist-head dlist) after)
(setf (dlink-next before) after))
(if (null after)
(setf (dlist-tail dlist) before)
(setf (dlink-prev after) before)))
dlist)
(defun dlist-elements (dlist)
"Returns the elements of DLIST as a list"
(labels ((extract-values (dlink acc)
(if (null dlink)
acc
(extract-values (dlink-next dlink) (cons (dlink-content dlink) acc)))))
(reverse (extract-values (dlist-head dlist) nil))))
(defmacro do-dlist ((var dlist &optional result) &rest body)
`(progn
(map-dlist (lambda (,var)
,@body)
,dlist)
,result))
(defun map-dlist (function dlist)
(mapcar function (dlist-elements dlist)))
(defun reduce-dlist (function dlist &key (initial-value nil ivp))
(if ivp
(reduce function (dlist-elements dlist)
:initial-value initial-value)
(reduce function (dlist-elements dlist))))
(defun null-dlist (dlist)
(equalp (length-dlist dlist) 0))
(defun length-dlist (dlist)
(length (dlist-elements dlist)))
(defun dlist-position (dlink dlist)
(loop with position = 0
for dlist-dlink = (dlist-head dlist) then (dlink-next dlist-dlink)
while (not (null dlist-dlink))
if (eql dlink dlist-dlink)
do (return-from dlist-position position)
else do (incf position))
nil) | |
f69d577a297e26cf2b6df785645c683ba96a002970eef1f420f9cf6e842095c8 | aphyr/mastodon-utils | project.clj | (defproject com.aphyr/mastodon-utils "0.1.0-SNAPSHOT"
:description "Utilities for working with Mastodon"
:url "-utils"
:license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0"
:url "-2.0/"}
:dependencies [[cheshire "5.11.0"]
[clj-http "3.12.3"]
[dom-top "1.0.8"]
[org.clojure/clojure "1.11.0"]
[org.clojure/tools.cli "1.0.214"]
[org.clojure/tools.logging "1.2.4"]
[slingshot "0.12.2"]]
:repl-options {:init-ns com.aphyr.mastodon-utils})
| null | https://raw.githubusercontent.com/aphyr/mastodon-utils/0c9a4557d1c5bd205b570f9f37a4b2078e5c79c8/project.clj | clojure | (defproject com.aphyr/mastodon-utils "0.1.0-SNAPSHOT"
:description "Utilities for working with Mastodon"
:url "-utils"
:license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0"
:url "-2.0/"}
:dependencies [[cheshire "5.11.0"]
[clj-http "3.12.3"]
[dom-top "1.0.8"]
[org.clojure/clojure "1.11.0"]
[org.clojure/tools.cli "1.0.214"]
[org.clojure/tools.logging "1.2.4"]
[slingshot "0.12.2"]]
:repl-options {:init-ns com.aphyr.mastodon-utils})
| |
318ac07605c04841ddde81f120327487ef0629803da0a92024f559cceed51795 | lgandersen/edgedns | edge_core_sup.erl | %%%
Copyright ( c ) 2016 . All rights reserved .
%%% Use of this source code is governed by a BSD-style
%%% license that can be found in the LICENSE file.
%%%
-module(edge_core_sup).
-behaviour(supervisor).
%% API.
-export([start_link/0]).
%% Supervisor callbacks.
-export([init/1]).
%% From supervisor.
-type start_link_err() :: {already_started, pid()} | shutdown | term().
-type start_link_ret() :: {ok, pid()} | ignore | {error, start_link_err()}.
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).
-spec start_link() -> start_link_ret().
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
@private
init([]) ->
{ok, {{one_for_one, 10, 10}, [
?CHILD(edge_core_udp_listener, worker),
?CHILD(edge_core_traffic_logger, worker),
?CHILD(edge_core_traffic_monitor, worker)
]}}.
| null | https://raw.githubusercontent.com/lgandersen/edgedns/6f1d414eed5ec412b934d3a82a694597fdee4649/apps/edge_core/src/edge_core_sup.erl | erlang |
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
API.
Supervisor callbacks.
From supervisor. | Copyright ( c ) 2016 . All rights reserved .
-module(edge_core_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-type start_link_err() :: {already_started, pid()} | shutdown | term().
-type start_link_ret() :: {ok, pid()} | ignore | {error, start_link_err()}.
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).
-spec start_link() -> start_link_ret().
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
@private
init([]) ->
{ok, {{one_for_one, 10, 10}, [
?CHILD(edge_core_udp_listener, worker),
?CHILD(edge_core_traffic_logger, worker),
?CHILD(edge_core_traffic_monitor, worker)
]}}.
|
506848849a6bf52a9de1042f17dab86dc0fbae1f7da3bbaf6d62454cb6975c3e | GaloisInc/ivory | Prim.hs | # LANGUAGE DataKinds #
# LANGUAGE TypeOperators #
--
-- Prim.hs --- I/O register primitives.
--
Copyright ( C ) 2013 , Galois , Inc.
All Rights Reserved .
--
module Ivory.HW.Prim where
import Ivory.Language
hw_moduledef :: ModuleDef
hw_moduledef = do
incl ioRegReadU8
incl ioRegWriteU8
incl ioRegReadU16
incl ioRegWriteU16
incl ioRegReadU32
incl ioRegWriteU32
class IvoryBits a => IvoryIOReg a where
ioRegSize :: a -> Integer
ioRegRead :: Def ('[Uint32] ':-> a)
ioRegWrite :: Def ('[Uint32, a] ':-> ())
ioRegReadU8 :: Def ('[Uint32] ':-> Uint8)
ioRegReadU8 = importProc "ivory_hw_io_read_u8" "ivory_hw_prim.h"
ioRegWriteU8 :: Def ('[Uint32, Uint8] ':-> ())
ioRegWriteU8 = importProc "ivory_hw_io_write_u8" "ivory_hw_prim.h"
instance IvoryIOReg Uint8 where
ioRegSize _ = 1
ioRegRead = ioRegReadU8
ioRegWrite = ioRegWriteU8
ioRegReadU16 :: Def ('[Uint32] ':-> Uint16)
ioRegReadU16 = importProc "ivory_hw_io_read_u16" "ivory_hw_prim.h"
ioRegWriteU16 :: Def ('[Uint32, Uint16] ':-> ())
ioRegWriteU16 = importProc "ivory_hw_io_write_u16" "ivory_hw_prim.h"
instance IvoryIOReg Uint16 where
ioRegSize _ = 2
ioRegRead = ioRegReadU16
ioRegWrite = ioRegWriteU16
ioRegReadU32 :: Def ('[Uint32] ':-> Uint32)
ioRegReadU32 = importProc "ivory_hw_io_read_u32" "ivory_hw_prim.h"
ioRegWriteU32 :: Def ('[Uint32, Uint32] ':-> ())
ioRegWriteU32 = importProc "ivory_hw_io_write_u32" "ivory_hw_prim.h"
instance IvoryIOReg Uint32 where
ioRegSize _ = 4
ioRegRead = ioRegReadU32
ioRegWrite = ioRegWriteU32
| null | https://raw.githubusercontent.com/GaloisInc/ivory/53a0795b4fbeb0b7da0f6cdaccdde18849a78cd6/ivory-hw/src/Ivory/HW/Prim.hs | haskell |
Prim.hs --- I/O register primitives.
| # LANGUAGE DataKinds #
# LANGUAGE TypeOperators #
Copyright ( C ) 2013 , Galois , Inc.
All Rights Reserved .
module Ivory.HW.Prim where
import Ivory.Language
hw_moduledef :: ModuleDef
hw_moduledef = do
incl ioRegReadU8
incl ioRegWriteU8
incl ioRegReadU16
incl ioRegWriteU16
incl ioRegReadU32
incl ioRegWriteU32
class IvoryBits a => IvoryIOReg a where
ioRegSize :: a -> Integer
ioRegRead :: Def ('[Uint32] ':-> a)
ioRegWrite :: Def ('[Uint32, a] ':-> ())
ioRegReadU8 :: Def ('[Uint32] ':-> Uint8)
ioRegReadU8 = importProc "ivory_hw_io_read_u8" "ivory_hw_prim.h"
ioRegWriteU8 :: Def ('[Uint32, Uint8] ':-> ())
ioRegWriteU8 = importProc "ivory_hw_io_write_u8" "ivory_hw_prim.h"
instance IvoryIOReg Uint8 where
ioRegSize _ = 1
ioRegRead = ioRegReadU8
ioRegWrite = ioRegWriteU8
ioRegReadU16 :: Def ('[Uint32] ':-> Uint16)
ioRegReadU16 = importProc "ivory_hw_io_read_u16" "ivory_hw_prim.h"
ioRegWriteU16 :: Def ('[Uint32, Uint16] ':-> ())
ioRegWriteU16 = importProc "ivory_hw_io_write_u16" "ivory_hw_prim.h"
instance IvoryIOReg Uint16 where
ioRegSize _ = 2
ioRegRead = ioRegReadU16
ioRegWrite = ioRegWriteU16
ioRegReadU32 :: Def ('[Uint32] ':-> Uint32)
ioRegReadU32 = importProc "ivory_hw_io_read_u32" "ivory_hw_prim.h"
ioRegWriteU32 :: Def ('[Uint32, Uint32] ':-> ())
ioRegWriteU32 = importProc "ivory_hw_io_write_u32" "ivory_hw_prim.h"
instance IvoryIOReg Uint32 where
ioRegSize _ = 4
ioRegRead = ioRegReadU32
ioRegWrite = ioRegWriteU32
|
6bff187811c071108a16a839f1de497eba8cd33c12c936042e34d22710c45ad9 | keechma/keechma-pipelines | core.cljs | (ns keechma.pipelines.core
(:refer-clojure :exclude [swap! reset!])
(:require [keechma.pipelines.runtime :as runtime])
(:require-macros [keechma.pipelines.core :refer [pipeline!]]))
(def make-pipeline runtime/make-pipeline)
(def start! runtime/start!)
(def stop! runtime/stop!)
(def has-pipeline? runtime/has-pipeline?)
(def invoke runtime/invoke)
(def in-pipeline? runtime/in-pipeline?)
(def get-active runtime/get-active)
(def cancel runtime/cancel)
(def cancel-all runtime/cancel-all)
(def break runtime/break)
(def break-all runtime/break-all)
(def get-ident runtime/get-ident)
(def get-args runtime/get-args)
(defn set-queue
"Explicitly set the queue name. Second argument can be a function in which case, it will be called with the pipeline arguments and should return a queue name"
[pipeline queue]
(assoc-in pipeline [:config :queue-name] queue))
(defn use-existing
"If there is an in flight pipeline started with the same arguments, return its promise instead of starting a new one. It can be combined with any other concurrency behavior (`restartable`, `dropping`, `enqueued` and `keep-latest`)"
[pipeline]
(assoc-in pipeline [:config :use-existing] true))
(defn restartable
"Cancel any running pipelines and start a new one"
([pipeline] (restartable pipeline 1))
([pipeline max-concurrency]
(assoc-in pipeline [:config :concurrency] {:behavior :restartable :max max-concurrency})))
(defn enqueued
"Enqueue requests and execute them sequentially"
([pipeline] (enqueued pipeline 1))
([pipeline max-concurrency]
(assoc-in pipeline [:config :concurrency] {:behavior :enqueued :max max-concurrency})))
(defn dropping
"Drop new request while another one is running"
([pipeline] (dropping pipeline 1))
([pipeline max-concurrency]
(assoc-in pipeline [:config :concurrency] {:behavior :dropping :max max-concurrency})))
(defn keep-latest
"Drop all intermediate requests, enqueue the last one"
([pipeline] (keep-latest pipeline 1))
([pipeline max-concurrency]
(assoc-in pipeline [:config :concurrency] {:behavior :keep-latest :max max-concurrency})))
(defn cancel-on-shutdown
"Should the pipeline be cancelled when the runtime is shut down"
([pipeline] (cancel-on-shutdown pipeline true))
([pipeline should-cancel]
(assoc-in pipeline [:config :cancel-on-shutdown] should-cancel)))
(defn detached
([pipeline] (detached pipeline true))
([pipeline is-detached]
(assoc-in pipeline [:config :is-detached] is-detached)))
(defn muted [pipeline]
(pipeline! [value _]
(let [value' value]
(pipeline! [_ _]
pipeline
value'))))
(defn swap!
"swap! that can be used inside pipeline! - returns nil so it doesn't change the current value"
[& args]
(apply clojure.core/swap! args)
nil)
(defn reset!
"reset! that can be used inside pipeline! - returns nil so it doesn't change the current value"
[& args]
(apply clojure.core/reset! args)
nil) | null | https://raw.githubusercontent.com/keechma/keechma-pipelines/09ae26e5f435401e420c3869dec8e77da74ef7d0/src/keechma/pipelines/core.cljs | clojure | (ns keechma.pipelines.core
(:refer-clojure :exclude [swap! reset!])
(:require [keechma.pipelines.runtime :as runtime])
(:require-macros [keechma.pipelines.core :refer [pipeline!]]))
(def make-pipeline runtime/make-pipeline)
(def start! runtime/start!)
(def stop! runtime/stop!)
(def has-pipeline? runtime/has-pipeline?)
(def invoke runtime/invoke)
(def in-pipeline? runtime/in-pipeline?)
(def get-active runtime/get-active)
(def cancel runtime/cancel)
(def cancel-all runtime/cancel-all)
(def break runtime/break)
(def break-all runtime/break-all)
(def get-ident runtime/get-ident)
(def get-args runtime/get-args)
(defn set-queue
"Explicitly set the queue name. Second argument can be a function in which case, it will be called with the pipeline arguments and should return a queue name"
[pipeline queue]
(assoc-in pipeline [:config :queue-name] queue))
(defn use-existing
"If there is an in flight pipeline started with the same arguments, return its promise instead of starting a new one. It can be combined with any other concurrency behavior (`restartable`, `dropping`, `enqueued` and `keep-latest`)"
[pipeline]
(assoc-in pipeline [:config :use-existing] true))
(defn restartable
"Cancel any running pipelines and start a new one"
([pipeline] (restartable pipeline 1))
([pipeline max-concurrency]
(assoc-in pipeline [:config :concurrency] {:behavior :restartable :max max-concurrency})))
(defn enqueued
"Enqueue requests and execute them sequentially"
([pipeline] (enqueued pipeline 1))
([pipeline max-concurrency]
(assoc-in pipeline [:config :concurrency] {:behavior :enqueued :max max-concurrency})))
(defn dropping
"Drop new request while another one is running"
([pipeline] (dropping pipeline 1))
([pipeline max-concurrency]
(assoc-in pipeline [:config :concurrency] {:behavior :dropping :max max-concurrency})))
(defn keep-latest
"Drop all intermediate requests, enqueue the last one"
([pipeline] (keep-latest pipeline 1))
([pipeline max-concurrency]
(assoc-in pipeline [:config :concurrency] {:behavior :keep-latest :max max-concurrency})))
(defn cancel-on-shutdown
"Should the pipeline be cancelled when the runtime is shut down"
([pipeline] (cancel-on-shutdown pipeline true))
([pipeline should-cancel]
(assoc-in pipeline [:config :cancel-on-shutdown] should-cancel)))
(defn detached
([pipeline] (detached pipeline true))
([pipeline is-detached]
(assoc-in pipeline [:config :is-detached] is-detached)))
(defn muted [pipeline]
(pipeline! [value _]
(let [value' value]
(pipeline! [_ _]
pipeline
value'))))
(defn swap!
"swap! that can be used inside pipeline! - returns nil so it doesn't change the current value"
[& args]
(apply clojure.core/swap! args)
nil)
(defn reset!
"reset! that can be used inside pipeline! - returns nil so it doesn't change the current value"
[& args]
(apply clojure.core/reset! args)
nil) | |
9ed1d1ae0d5261b9abe4fc5f0a4f5b4575c3949734e1979b69d5c99ad075fc76 | georgjz/raylib-gambit-scheme | raylib-consts.scm |
; ▄████████ ▄██████▄ ███▄▄▄▄ ▄████████ ███
; ███ ███ ███ ███ ███▀▀▀██▄ ███ ███ ▀█████████▄
█ █ █ █ ▀ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ ▀ ▀ █ █ █ ▀ ▀ █ █
; ███ ███ ███ ███ ███ ███ ███ ▀
; ███ ███ ███ ███ ███ ▀███████████ ███
; ███ █▄ ███ ███ ███ ███ ███ ███
; ███ ███ ███ ███ ███ ███ ▄█ ███ ███
; ████████▀ ▀██████▀ ▀█ █▀ ▄████████▀ ▄████▀
;;;-----------------------------------------------------------------------------
These are the constants and enums defined in .
;;;-----------------------------------------------------------------------------
;;; BUG: No Android buttons defined
;;; FIXME: Add gamepad buttons
(define KEY_APOSTROPHE 39)
(define KEY_COMMA 44)
(define KEY_MINUS 45)
(define KEY_PERIOD 46)
(define KEY_SLASH 47)
(define KEY_ZERO 48)
(define KEY_ONE 49)
(define KEY_TWO 50)
(define KEY_THREE 51)
(define KEY_FOUR 52)
(define KEY_FIVE 53)
(define KEY_SIX 54)
(define KEY_SEVEN 55)
(define KEY_EIGHT 56)
(define KEY_NINE 57)
(define KEY_SEMICOLON 59)
(define KEY_EQUAL 61)
(define KEY_A 65)
(define KEY_B 66)
(define KEY_C 67)
(define KEY_D 68)
(define KEY_E 69)
(define KEY_F 70)
(define KEY_G 71)
(define KEY_H 72)
(define KEY_I 73)
(define KEY_J 74)
(define KEY_K 75)
(define KEY_L 76)
(define KEY_M 77)
(define KEY_N 78)
(define KEY_O 79)
(define KEY_P 80)
(define KEY_Q 81)
(define KEY_R 82)
(define KEY_S 83)
(define KEY_T 84)
(define KEY_U 85)
(define KEY_V 86)
(define KEY_W 87)
(define KEY_X 88)
(define KEY_Y 89)
(define KEY_Z 90)
(define KEY_SPACE 32)
(define KEY_ESCAPE 256)
(define KEY_ENTER 257)
(define KEY_TAB 258)
(define KEY_BACKSPACE 259)
(define KEY_INSERT 260)
(define KEY_DELETE 261)
(define KEY_RIGHT 262)
(define KEY_LEFT 263)
(define KEY_DOWN 264)
(define KEY_UP 265)
(define KEY_PAGE_UP 266)
(define KEY_PAGE_DOWN 267)
(define KEY_HOME 268)
(define KEY_END 269)
(define KEY_CAPS_LOCK 280)
(define KEY_SCROLL_LOCK 281)
(define KEY_NUM_LOCK 282)
(define KEY_PRINT_SCREEN 283)
(define KEY_PAUSE 284)
(define KEY_F1 290)
(define KEY_F2 291)
(define KEY_F3 292)
(define KEY_F4 293)
(define KEY_F5 294)
(define KEY_F6 295)
(define KEY_F7 296)
(define KEY_F8 297)
(define KEY_F9 298)
(define KEY_F10 299)
(define KEY_F11 300)
(define KEY_F12 301)
(define KEY_LEFT_SHIFT 340)
(define KEY_LEFT_CONTROL 341)
(define KEY_LEFT_ALT 342)
(define KEY_LEFT_SUPER 343)
(define KEY_RIGHT_SHIFT 344)
(define KEY_RIGHT_CONTROL 345)
(define KEY_RIGHT_ALT 346)
(define KEY_RIGHT_SUPER 347)
(define KEY_KB_MENU 348)
(define KEY_LEFT_BRACKET 91)
(define KEY_BACKSLASH 92)
(define KEY_RIGHT_BRACKET 93)
(define KEY_GRAVE 96)
(define KEY_KP_0 320)
(define KEY_KP_1 321)
(define KEY_KP_2 322)
(define KEY_KP_3 323)
(define KEY_KP_4 324)
(define KEY_KP_5 325)
(define KEY_KP_6 326)
(define KEY_KP_7 327)
(define KEY_KP_8 328)
(define KEY_KP_9 329)
(define KEY_KP_DECIMAL 330)
(define KEY_KP_DIVIDE 331)
(define KEY_KP_MULTIPLY 332)
(define KEY_KP_SUBTRACT 333)
(define KEY_KP_ADD 334)
(define KEY_KP_ENTER 335)
(define KEY_KP_EQUAL 336)
(define MOUSE_LEFT_BUTTON 0)
(define MOUSE_RIGHT_BUTTON 1)
(define MOUSE_MIDDLE_BUTTON 2)
(define GAMEPAD_PLAYER1 0)
(define GAMEPAD_PLAYER2 1)
(define GAMEPAD_PLAYER3 2)
(define GAMEPAD_PLAYER4 3)
(define FLAG_RESERVED 1)
(define FLAG_FULLSCREEN_MODE 2)
(define FLAG_WINDOW_RESIZABLE 4)
(define FLAG_WINDOW_UNDECORATED 8)
(define FLAG_WINDOW_TRANSPARENT 16)
(define FLAG_WINDOW_HIDDEN 128)
(define FLAG_WINDOW_ALWAYS_RUN 256)
(define FLAG_MSAA_4X_HINT 32)
(define FLAG_VSYNC_HINT 64)
| null | https://raw.githubusercontent.com/georgjz/raylib-gambit-scheme/df7ea6db54a3196d13c66dac4909c64cea6e5a88/src/raylibbinding/raylib-consts.scm | scheme | ▄████████ ▄██████▄ ███▄▄▄▄ ▄████████ ███
███ ███ ███ ███ ███▀▀▀██▄ ███ ███ ▀█████████▄
███ ███ ███ ███ ███ ███ ███ ▀
███ ███ ███ ███ ███ ▀███████████ ███
███ █▄ ███ ███ ███ ███ ███ ███
███ ███ ███ ███ ███ ███ ▄█ ███ ███
████████▀ ▀██████▀ ▀█ █▀ ▄████████▀ ▄████▀
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
BUG: No Android buttons defined
FIXME: Add gamepad buttons |
█ █ █ █ ▀ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ ▀ ▀ █ █ █ ▀ ▀ █ █
These are the constants and enums defined in .
(define KEY_APOSTROPHE 39)
(define KEY_COMMA 44)
(define KEY_MINUS 45)
(define KEY_PERIOD 46)
(define KEY_SLASH 47)
(define KEY_ZERO 48)
(define KEY_ONE 49)
(define KEY_TWO 50)
(define KEY_THREE 51)
(define KEY_FOUR 52)
(define KEY_FIVE 53)
(define KEY_SIX 54)
(define KEY_SEVEN 55)
(define KEY_EIGHT 56)
(define KEY_NINE 57)
(define KEY_SEMICOLON 59)
(define KEY_EQUAL 61)
(define KEY_A 65)
(define KEY_B 66)
(define KEY_C 67)
(define KEY_D 68)
(define KEY_E 69)
(define KEY_F 70)
(define KEY_G 71)
(define KEY_H 72)
(define KEY_I 73)
(define KEY_J 74)
(define KEY_K 75)
(define KEY_L 76)
(define KEY_M 77)
(define KEY_N 78)
(define KEY_O 79)
(define KEY_P 80)
(define KEY_Q 81)
(define KEY_R 82)
(define KEY_S 83)
(define KEY_T 84)
(define KEY_U 85)
(define KEY_V 86)
(define KEY_W 87)
(define KEY_X 88)
(define KEY_Y 89)
(define KEY_Z 90)
(define KEY_SPACE 32)
(define KEY_ESCAPE 256)
(define KEY_ENTER 257)
(define KEY_TAB 258)
(define KEY_BACKSPACE 259)
(define KEY_INSERT 260)
(define KEY_DELETE 261)
(define KEY_RIGHT 262)
(define KEY_LEFT 263)
(define KEY_DOWN 264)
(define KEY_UP 265)
(define KEY_PAGE_UP 266)
(define KEY_PAGE_DOWN 267)
(define KEY_HOME 268)
(define KEY_END 269)
(define KEY_CAPS_LOCK 280)
(define KEY_SCROLL_LOCK 281)
(define KEY_NUM_LOCK 282)
(define KEY_PRINT_SCREEN 283)
(define KEY_PAUSE 284)
(define KEY_F1 290)
(define KEY_F2 291)
(define KEY_F3 292)
(define KEY_F4 293)
(define KEY_F5 294)
(define KEY_F6 295)
(define KEY_F7 296)
(define KEY_F8 297)
(define KEY_F9 298)
(define KEY_F10 299)
(define KEY_F11 300)
(define KEY_F12 301)
(define KEY_LEFT_SHIFT 340)
(define KEY_LEFT_CONTROL 341)
(define KEY_LEFT_ALT 342)
(define KEY_LEFT_SUPER 343)
(define KEY_RIGHT_SHIFT 344)
(define KEY_RIGHT_CONTROL 345)
(define KEY_RIGHT_ALT 346)
(define KEY_RIGHT_SUPER 347)
(define KEY_KB_MENU 348)
(define KEY_LEFT_BRACKET 91)
(define KEY_BACKSLASH 92)
(define KEY_RIGHT_BRACKET 93)
(define KEY_GRAVE 96)
(define KEY_KP_0 320)
(define KEY_KP_1 321)
(define KEY_KP_2 322)
(define KEY_KP_3 323)
(define KEY_KP_4 324)
(define KEY_KP_5 325)
(define KEY_KP_6 326)
(define KEY_KP_7 327)
(define KEY_KP_8 328)
(define KEY_KP_9 329)
(define KEY_KP_DECIMAL 330)
(define KEY_KP_DIVIDE 331)
(define KEY_KP_MULTIPLY 332)
(define KEY_KP_SUBTRACT 333)
(define KEY_KP_ADD 334)
(define KEY_KP_ENTER 335)
(define KEY_KP_EQUAL 336)
(define MOUSE_LEFT_BUTTON 0)
(define MOUSE_RIGHT_BUTTON 1)
(define MOUSE_MIDDLE_BUTTON 2)
(define GAMEPAD_PLAYER1 0)
(define GAMEPAD_PLAYER2 1)
(define GAMEPAD_PLAYER3 2)
(define GAMEPAD_PLAYER4 3)
(define FLAG_RESERVED 1)
(define FLAG_FULLSCREEN_MODE 2)
(define FLAG_WINDOW_RESIZABLE 4)
(define FLAG_WINDOW_UNDECORATED 8)
(define FLAG_WINDOW_TRANSPARENT 16)
(define FLAG_WINDOW_HIDDEN 128)
(define FLAG_WINDOW_ALWAYS_RUN 256)
(define FLAG_MSAA_4X_HINT 32)
(define FLAG_VSYNC_HINT 64)
|
eb67122c4b4af519eb9b67b61d1185325f4e3c5b84474e3f036f68befee35323 | kupl/LearnML | original.ml | exception Problem
type aexp =
| Const of int
| Var of string
| Power of (string * int)
| Times of aexp list
| Sum of aexp list
let rec diff ((e : aexp), (x : string)) : aexp =
match e with
| Const _ -> Const 0
| Var y -> if x = y then Const 1 else Const 0
| Power (y, n) ->
if x = y then Times [ Const n; Power (y, n - 1) ] else Const 0
| Times l -> (
match l with
| [] -> raise Problem
| [ a ] -> raise Problem
| [ a1; a2 ] ->
Sum [ Times [ diff (a1, x); a2 ]; Times [ a1; diff (a2, x) ] ]
| hd :: tl ->
Sum
[
Times [ diff (hd, x); Times tl ]; Times [ hd; diff (Times tl, x) ];
] )
| Sum l -> (
match l with
| [] -> raise Problem
| [ a ] -> raise Problem
| [ a1; a2 ] -> Sum [ diff (a1, x); diff (a2, x) ]
| hd :: tl -> Sum [ diff (hd, x); diff (Sum tl, x) ] )
| null | https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/diff/sub126/original.ml | ocaml | exception Problem
type aexp =
| Const of int
| Var of string
| Power of (string * int)
| Times of aexp list
| Sum of aexp list
let rec diff ((e : aexp), (x : string)) : aexp =
match e with
| Const _ -> Const 0
| Var y -> if x = y then Const 1 else Const 0
| Power (y, n) ->
if x = y then Times [ Const n; Power (y, n - 1) ] else Const 0
| Times l -> (
match l with
| [] -> raise Problem
| [ a ] -> raise Problem
| [ a1; a2 ] ->
Sum [ Times [ diff (a1, x); a2 ]; Times [ a1; diff (a2, x) ] ]
| hd :: tl ->
Sum
[
Times [ diff (hd, x); Times tl ]; Times [ hd; diff (Times tl, x) ];
] )
| Sum l -> (
match l with
| [] -> raise Problem
| [ a ] -> raise Problem
| [ a1; a2 ] -> Sum [ diff (a1, x); diff (a2, x) ]
| hd :: tl -> Sum [ diff (hd, x); diff (Sum tl, x) ] )
| |
22ab3d56089c0a3ec199780d311d0849f8d625fe4e0dfbc1fa3b465bd579e205 | tiensonqin/lymchat-exp | storage.cljs | (ns lymchat.storage
(:refer-clojure :exclude [update])
(:require [lymchat.core-async-storage :as s]
[re-frame.core :refer [dispatch]]
[cljs.core.async :refer [<!]]
[re-frame.db :refer [app-db]]
[lymchat.util :as util]
[cljs-time.core :as t]
[cljs-time.coerce :as tc])
(:require-macros [cljs.core.async.macros :refer [go]]))
;; all reads from memory, synchronous
;; all writes to both memory (synchronous) and storage (asynchronous)
(defn development?
[]
(true? js/__DEV__))
(def get-item s/get-item)
(def set-item s/set-item)
(def remove-item s/remove-item)
(defn kv-set
[k v]
(set-item k v)
(swap! app-db (fn [db]
(assoc db k v))))
(defn kv-get
[k]
(get @app-db k))
(defn transform
[table handler]
(go
(let [[err v] (<! (get-item table))]
(if (nil? err)
(set-item table (handler v))
(throw v)))))
(defn create
[table record]
(when (and table record)
(transform table
(fn [col]
(-> (vec col)
(conj record)
(distinct)
(vec))))))
(defn update
[table record]
(when (and table record)
(transform table
(fn [col]
(vec
(doall
(map
(fn [x]
(if (= (:id x) (:id record))
(merge x record)
x))
col)))))))
(defn batch-create
[table records]
(when (and table records)
(transform table
(fn [col]
(->
(concat col records)
(distinct)
(vec))))))
(defn delete
[table id]
(transform table
(fn [col]
(-> (remove #(= (:id %) id) col)
(vec)))))
(defn set-latest-message-id
[id]
(set-item :latest-message-id id))
(defn delete-records-by-fk-id
[records-table fk fk-value]
(transform records-table
(fn [col]
(-> (remove #(= (get % fk) fk-value) col)
(vec)))))
(defn delete-conversation
[conversation-id]
;; delete messages
(delete-records-by-fk-id :messages :conversation_id conversation-id)
;; delete conversation
(delete :conversations conversation-id))
(defn get-col
[k]
(get @app-db k))
(defn get-by-fk
[table fk fk-value]
(->> (get-col table)
(filter #(= fk-value (get % fk)))
(first)))
(defn get-by-id
[table id]
(get-by-fk table :id id))
(defn get-channel-by-id
[id]
(->> (get-in @app-db [:current-user :channels])
(filter #(= (str id) (str (get % :id))))
(first)))
(defn get-channel-members-count
[channel-id]
(-> (get-by-id :channels channel-id)
(:members_count)))
(defn get-largest-conversation-id
[]
(let [id (->> (get-col :conversations)
(sort :id)
(last)
(:id))]
(if (nil? id)
0
id)))
(defn me
[]
(:current-user @app-db))
(defn get-count
[table]
(->> (get-col table)
(count)))
(defn get-latest-message-id
[]
(:latest-message-id @app-db))
(defn get-conversations
[]
(some->>
(get-col :conversations)
(distinct)
(sort :last_message_at)
(reverse)))
(defn get-invites
[]
(get-col :invites))
(defn invite-exists?
[user]
(some? (get-by-id :invites (:id user))))
(defn get-contacts
[]
(get-col :contacts))
(defn get-contacts-count
[]
(get-count :contacts))
(defn get-contacts-ids
[]
(map :id (get-contacts)))
(defn friend?
[id]
(contains? (set (get-contacts-ids)) id))
(defn get-user-by-id
[id]
(if id
(let [me (me)]
(if (= id (:id me))
me
(get-by-id :contacts id)))))
(defn conversaction-exists?
[id]
(some #(and (= id (:to %))
(false? (:is_channel %)))
(get-conversations)))
(defn conversation-exists?
[id]
(some #(and (= id (:to %))
(false? (:is_channel %)))
(get-conversations)))
(defn channel-conversation-exists?
[id]
(some #(and (= id (:to %))
(true? (:is_channel %)))
(get-conversations)))
(defn create-conversation
([to msg msg-created-at]
(create-conversation to msg msg-created-at nil))
([to msg msg-created-at contact]
(when-not (conversation-exists? to)
(let [largest-id (get-largest-conversation-id)
contact (if contact contact (get-by-id :contacts to))]
(when contact
(let [new-id (inc largest-id)
conversation {:id new-id
:to to
:user_id (:id contact)
:name (:name contact)
:avatar (:avatar contact)
:last_message msg
:last_message_at msg-created-at}]
(create :conversations conversation)
(dispatch [:new-conversation conversation])
new-id))))))
(defn update-conversations
[m]
(js/setTimeout
(fn [] (update :conversations m))
50))
(defn get-conversation-id-by-to
[to]
(when-let [conversation (get-by-fk :conversations :to to)]
(:id conversation)))
(defn msg-convert
[me-id msg]
(when msg
(let [body (:body msg)
ret {:_id (:id msg)
:createdAt (:created_at msg)
:user {:_id (:user_id msg)
:_username (:username msg)
:_avatar (:avatar msg)
:_timezone (:timezone msg)
:_language (:language msg)
:_name (:name msg)}
:is_delivered (:is_delivered msg)}]
(if (util/photo-message? body)
(assoc ret :image (util/real-photo-url body))
(assoc ret :text body)))))
(defn ->user
[msg]
{:id (:_id msg)
:username (:_username msg)
:avatar (:_avatar msg)
:timezone (:_timezone msg)
:language (:_language msg)
:name (:_name msg)})
(defn wrap-conversation-id
([msg]
(wrap-conversation-id msg :user_id nil))
([msg k]
(wrap-conversation-id msg k nil))
([{:keys [body created_at] :as msg} k contact]
(let [cid (get-conversation-id-by-to (get msg k))
cid (if cid cid (create-conversation (get msg k) body created_at contact))]
(assoc msg :conversation_id cid))))
(defn get-conversation-messages
[current-user-id current-callee n]
(if-let [conversation-id (get-conversation-id-by-to current-callee)]
(->> (get-col :messages)
(filter #(= conversation-id (:conversation_id %)))
(sort :created_at)
(reverse)
(take n)
(mapv (partial msg-convert current-user-id)))
[]))
(defn get-groups-messages
[]
(some->>
(get-col :group-messages)
(group-by :channel_id)))
(defn delete-channel-old-messages
[channel-id message-id]
(transform :messages
(fn [col]
(->> col
(remove #(and (= (:channel_id %) channel-id)
(< (:id %) message-id)))
(vec)))))
(defn load-earlier-messages
[current-user-id current-callee last-msg-id n]
(if-let [conversation-id (get-conversation-id-by-to current-callee)]
(->> (get-col :messages)
(filter #(and (= (:conversation_id %) conversation-id)
(< (:id %) last-msg-id)))
(sort :created_at)
(reverse)
(take n)
(mapv (partial msg-convert current-user-id)))
[]))
(defn batch-insert-messages
[messages]
(when-let [messages (doall (map #(wrap-conversation-id % :user_id) messages))]
(let [conversations (group-by :conversation_id messages)]
(doseq [[id msgs] conversations]
(let [message (last msgs)]
(update :conversations {:id id
:last_message (:body message)
:last_message_at (:created_at message)}))))
;; update conversation
(batch-create :messages messages)))
(defn create-channel-conversation
[channel-id message]
(when-not (channel-conversation-exists? channel-id)
(let [channel (get-by-id :channels channel-id)
{:keys [user_id name username avatar body created_at]} message
largest-id (get-largest-conversation-id)
new-conversation {:id (inc largest-id)
:is_channel true
:message_id (:id message)
:to channel-id
:user_id user_id
:name name
:username name
:avatar avatar
:last_message body
:last_message_at (if created_at (tc/to-date created_at))
:is_read true}]
(create :conversations new-conversation)
(dispatch [:new-conversation new-conversation]))))
(defn delete-channel-conversation
[channel-id]
;; TODO delete messages
(transform :conversations
(fn [col]
(-> (remove #(and (= (:to %) channel-id)
(true? (:is_channel %))) col)
(vec)))))
(defn join-channel
[channel]
(transform :current-user
(fn [user]
(clojure.core/update user :channels conj channel))))
(defn leave-channel
[channel-id]
(transform :current-user
(fn [user]
(clojure.core/update user
:channels
(fn [xs]
(remove #(= (str channel-id) (str (:id %)))
xs)))))
(delete-channel-conversation channel-id))
;; debug
(defn debug
[command & args]
(go
(prn "Result: "
(<! (apply command args)))))
(defn query
([table]
(query table identity))
([table handler]
(go
(let [[err v] (<! (get-item table))]
(when (development?) (prn {:table table
:error err
:val v}))
(if (nil? err)
(set-item table (handler v))
(throw v))))))
(defonce lym-channel
{:need_invite false,
:block false,
:is_private false,
:locale "english",
:purpose nil,
:name "Lymchat",
:type "lymchat",
:members_count 0,
:id "10000000-3c59-4887-995b-cf275db86343",
:picture nil,
:user_id "10000000-3c59-4887-995b-cf275db86343",
:created_at #inst "2016-08-17T13:59:52.604000000-00:00"})
| null | https://raw.githubusercontent.com/tiensonqin/lymchat-exp/425a0738b11632119be08b5a59f12244f5df1575/src/lymchat/storage.cljs | clojure | all reads from memory, synchronous
all writes to both memory (synchronous) and storage (asynchronous)
delete messages
delete conversation
update conversation
TODO delete messages
debug | (ns lymchat.storage
(:refer-clojure :exclude [update])
(:require [lymchat.core-async-storage :as s]
[re-frame.core :refer [dispatch]]
[cljs.core.async :refer [<!]]
[re-frame.db :refer [app-db]]
[lymchat.util :as util]
[cljs-time.core :as t]
[cljs-time.coerce :as tc])
(:require-macros [cljs.core.async.macros :refer [go]]))
(defn development?
[]
(true? js/__DEV__))
(def get-item s/get-item)
(def set-item s/set-item)
(def remove-item s/remove-item)
(defn kv-set
[k v]
(set-item k v)
(swap! app-db (fn [db]
(assoc db k v))))
(defn kv-get
[k]
(get @app-db k))
(defn transform
[table handler]
(go
(let [[err v] (<! (get-item table))]
(if (nil? err)
(set-item table (handler v))
(throw v)))))
(defn create
[table record]
(when (and table record)
(transform table
(fn [col]
(-> (vec col)
(conj record)
(distinct)
(vec))))))
(defn update
[table record]
(when (and table record)
(transform table
(fn [col]
(vec
(doall
(map
(fn [x]
(if (= (:id x) (:id record))
(merge x record)
x))
col)))))))
(defn batch-create
[table records]
(when (and table records)
(transform table
(fn [col]
(->
(concat col records)
(distinct)
(vec))))))
(defn delete
[table id]
(transform table
(fn [col]
(-> (remove #(= (:id %) id) col)
(vec)))))
(defn set-latest-message-id
[id]
(set-item :latest-message-id id))
(defn delete-records-by-fk-id
[records-table fk fk-value]
(transform records-table
(fn [col]
(-> (remove #(= (get % fk) fk-value) col)
(vec)))))
(defn delete-conversation
[conversation-id]
(delete-records-by-fk-id :messages :conversation_id conversation-id)
(delete :conversations conversation-id))
(defn get-col
[k]
(get @app-db k))
(defn get-by-fk
[table fk fk-value]
(->> (get-col table)
(filter #(= fk-value (get % fk)))
(first)))
(defn get-by-id
[table id]
(get-by-fk table :id id))
(defn get-channel-by-id
[id]
(->> (get-in @app-db [:current-user :channels])
(filter #(= (str id) (str (get % :id))))
(first)))
(defn get-channel-members-count
[channel-id]
(-> (get-by-id :channels channel-id)
(:members_count)))
(defn get-largest-conversation-id
[]
(let [id (->> (get-col :conversations)
(sort :id)
(last)
(:id))]
(if (nil? id)
0
id)))
(defn me
[]
(:current-user @app-db))
(defn get-count
[table]
(->> (get-col table)
(count)))
(defn get-latest-message-id
[]
(:latest-message-id @app-db))
(defn get-conversations
[]
(some->>
(get-col :conversations)
(distinct)
(sort :last_message_at)
(reverse)))
(defn get-invites
[]
(get-col :invites))
(defn invite-exists?
[user]
(some? (get-by-id :invites (:id user))))
(defn get-contacts
[]
(get-col :contacts))
(defn get-contacts-count
[]
(get-count :contacts))
(defn get-contacts-ids
[]
(map :id (get-contacts)))
(defn friend?
[id]
(contains? (set (get-contacts-ids)) id))
(defn get-user-by-id
[id]
(if id
(let [me (me)]
(if (= id (:id me))
me
(get-by-id :contacts id)))))
(defn conversaction-exists?
[id]
(some #(and (= id (:to %))
(false? (:is_channel %)))
(get-conversations)))
(defn conversation-exists?
[id]
(some #(and (= id (:to %))
(false? (:is_channel %)))
(get-conversations)))
(defn channel-conversation-exists?
[id]
(some #(and (= id (:to %))
(true? (:is_channel %)))
(get-conversations)))
(defn create-conversation
([to msg msg-created-at]
(create-conversation to msg msg-created-at nil))
([to msg msg-created-at contact]
(when-not (conversation-exists? to)
(let [largest-id (get-largest-conversation-id)
contact (if contact contact (get-by-id :contacts to))]
(when contact
(let [new-id (inc largest-id)
conversation {:id new-id
:to to
:user_id (:id contact)
:name (:name contact)
:avatar (:avatar contact)
:last_message msg
:last_message_at msg-created-at}]
(create :conversations conversation)
(dispatch [:new-conversation conversation])
new-id))))))
(defn update-conversations
[m]
(js/setTimeout
(fn [] (update :conversations m))
50))
(defn get-conversation-id-by-to
[to]
(when-let [conversation (get-by-fk :conversations :to to)]
(:id conversation)))
(defn msg-convert
[me-id msg]
(when msg
(let [body (:body msg)
ret {:_id (:id msg)
:createdAt (:created_at msg)
:user {:_id (:user_id msg)
:_username (:username msg)
:_avatar (:avatar msg)
:_timezone (:timezone msg)
:_language (:language msg)
:_name (:name msg)}
:is_delivered (:is_delivered msg)}]
(if (util/photo-message? body)
(assoc ret :image (util/real-photo-url body))
(assoc ret :text body)))))
(defn ->user
[msg]
{:id (:_id msg)
:username (:_username msg)
:avatar (:_avatar msg)
:timezone (:_timezone msg)
:language (:_language msg)
:name (:_name msg)})
(defn wrap-conversation-id
([msg]
(wrap-conversation-id msg :user_id nil))
([msg k]
(wrap-conversation-id msg k nil))
([{:keys [body created_at] :as msg} k contact]
(let [cid (get-conversation-id-by-to (get msg k))
cid (if cid cid (create-conversation (get msg k) body created_at contact))]
(assoc msg :conversation_id cid))))
(defn get-conversation-messages
[current-user-id current-callee n]
(if-let [conversation-id (get-conversation-id-by-to current-callee)]
(->> (get-col :messages)
(filter #(= conversation-id (:conversation_id %)))
(sort :created_at)
(reverse)
(take n)
(mapv (partial msg-convert current-user-id)))
[]))
(defn get-groups-messages
[]
(some->>
(get-col :group-messages)
(group-by :channel_id)))
(defn delete-channel-old-messages
[channel-id message-id]
(transform :messages
(fn [col]
(->> col
(remove #(and (= (:channel_id %) channel-id)
(< (:id %) message-id)))
(vec)))))
(defn load-earlier-messages
[current-user-id current-callee last-msg-id n]
(if-let [conversation-id (get-conversation-id-by-to current-callee)]
(->> (get-col :messages)
(filter #(and (= (:conversation_id %) conversation-id)
(< (:id %) last-msg-id)))
(sort :created_at)
(reverse)
(take n)
(mapv (partial msg-convert current-user-id)))
[]))
(defn batch-insert-messages
[messages]
(when-let [messages (doall (map #(wrap-conversation-id % :user_id) messages))]
(let [conversations (group-by :conversation_id messages)]
(doseq [[id msgs] conversations]
(let [message (last msgs)]
(update :conversations {:id id
:last_message (:body message)
:last_message_at (:created_at message)}))))
(batch-create :messages messages)))
(defn create-channel-conversation
[channel-id message]
(when-not (channel-conversation-exists? channel-id)
(let [channel (get-by-id :channels channel-id)
{:keys [user_id name username avatar body created_at]} message
largest-id (get-largest-conversation-id)
new-conversation {:id (inc largest-id)
:is_channel true
:message_id (:id message)
:to channel-id
:user_id user_id
:name name
:username name
:avatar avatar
:last_message body
:last_message_at (if created_at (tc/to-date created_at))
:is_read true}]
(create :conversations new-conversation)
(dispatch [:new-conversation new-conversation]))))
(defn delete-channel-conversation
[channel-id]
(transform :conversations
(fn [col]
(-> (remove #(and (= (:to %) channel-id)
(true? (:is_channel %))) col)
(vec)))))
(defn join-channel
[channel]
(transform :current-user
(fn [user]
(clojure.core/update user :channels conj channel))))
(defn leave-channel
[channel-id]
(transform :current-user
(fn [user]
(clojure.core/update user
:channels
(fn [xs]
(remove #(= (str channel-id) (str (:id %)))
xs)))))
(delete-channel-conversation channel-id))
(defn debug
[command & args]
(go
(prn "Result: "
(<! (apply command args)))))
(defn query
([table]
(query table identity))
([table handler]
(go
(let [[err v] (<! (get-item table))]
(when (development?) (prn {:table table
:error err
:val v}))
(if (nil? err)
(set-item table (handler v))
(throw v))))))
(defonce lym-channel
{:need_invite false,
:block false,
:is_private false,
:locale "english",
:purpose nil,
:name "Lymchat",
:type "lymchat",
:members_count 0,
:id "10000000-3c59-4887-995b-cf275db86343",
:picture nil,
:user_id "10000000-3c59-4887-995b-cf275db86343",
:created_at #inst "2016-08-17T13:59:52.604000000-00:00"})
|
5ef3b93d5e95a2452944b8cbed1e110636fc6a207cba93642094b3e431584cf5 | knightsc/sandbox_profiles | sbpl.scm | Sandbox Profile Language stub
;;; This stub is loaded before the sandbox profile is evaluated. When version
is called , the SBPL prelude and the appropriate SBPL version library are
;;; loaded. Combined with functions defined in the scheme interpreter by
;;; sbpl_parser.c, these implement the profile language.
(define (version n)
(case n
(( 1) (%version-1))
(else (error "unsupported version" n)))
(set! version
(lambda (o)
(if (not (= n o))
(error "only one version may be specified")))))
(define (%finalize)
(error "no version specified"))
| null | https://raw.githubusercontent.com/knightsc/sandbox_profiles/9eb25aecbf1e6e77cba64ead53e0dc31ee97c48d/sbpl.scm | scheme | This stub is loaded before the sandbox profile is evaluated. When version
loaded. Combined with functions defined in the scheme interpreter by
sbpl_parser.c, these implement the profile language. | Sandbox Profile Language stub
is called , the SBPL prelude and the appropriate SBPL version library are
(define (version n)
(case n
(( 1) (%version-1))
(else (error "unsupported version" n)))
(set! version
(lambda (o)
(if (not (= n o))
(error "only one version may be specified")))))
(define (%finalize)
(error "no version specified"))
|
88338d935f9128863a2e221e4e5c68308eacf079d4f2976cec8900931dc00de8 | Decentralized-Pictures/T4L3NT | mockup.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , 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. *)
(* *)
(*****************************************************************************)
open Protocol.Alpha_context
(* ------------------------------------------------------------------------- *)
(* Mockup protocol parameters *)
(** Protocol constants overriding logic. *)
module Protocol_constants_overrides = struct
(** Equivalent of [Constants.parametric] with additionally [chain_id] and [timestamp] but each field is wrapped in an [option].
[Some] is an override, [None] means "Use the default value".
*)
type t = {
preserved_cycles : int option;
blocks_per_cycle : int32 option;
blocks_per_commitment : int32 option;
blocks_per_roll_snapshot : int32 option;
blocks_per_voting_period : int32 option;
time_between_blocks : Period.t list option;
minimal_block_delay : Period.t option;
endorsers_per_block : int option;
hard_gas_limit_per_operation : Gas.Arith.integral option;
hard_gas_limit_per_block : Gas.Arith.integral option;
proof_of_work_threshold : int64 option;
tokens_per_roll : Tez.t option;
michelson_maximum_type_size : int option;
seed_nonce_revelation_tip : Tez.t option;
origination_size : int option;
block_security_deposit : Tez.t option;
endorsement_security_deposit : Tez.t option;
baking_reward_per_endorsement : Tez.t list option;
endorsement_reward : Tez.t list option;
cost_per_byte : Tez.t option;
hard_storage_limit_per_operation : Z.t option;
quorum_min : int32 option;
quorum_max : int32 option;
min_proposal_quorum : int32 option;
initial_endorsers : int option;
delay_per_missing_endorsement : Period.t option;
liquidity_baking_subsidy : Tez.t option;
liquidity_baking_sunset_level : int32 option;
liquidity_baking_escape_ema_threshold : int32 option;
(* Additional, "bastard" parameters (they are not protocol constants but partially treated the same way). *)
chain_id : Chain_id.t option;
timestamp : Time.Protocol.t option;
}
(** Shamefully copied from [Constants_repr.parametric_encoding] and adapted ([opt] instead of [req]). *)
let encoding : t Data_encoding.t =
let open Data_encoding in
conv
(fun c ->
( ( c.preserved_cycles,
c.blocks_per_cycle,
c.blocks_per_commitment,
c.blocks_per_roll_snapshot,
c.blocks_per_voting_period,
c.time_between_blocks,
c.endorsers_per_block,
c.hard_gas_limit_per_operation,
c.hard_gas_limit_per_block,
c.proof_of_work_threshold ),
( ( c.tokens_per_roll,
c.michelson_maximum_type_size,
c.seed_nonce_revelation_tip,
c.origination_size,
c.block_security_deposit,
c.endorsement_security_deposit,
c.baking_reward_per_endorsement,
c.endorsement_reward,
c.cost_per_byte,
c.hard_storage_limit_per_operation ),
( ( c.quorum_min,
c.quorum_max,
c.min_proposal_quorum,
c.initial_endorsers,
c.delay_per_missing_endorsement,
c.minimal_block_delay,
c.liquidity_baking_subsidy,
c.liquidity_baking_sunset_level,
c.liquidity_baking_escape_ema_threshold ),
(c.chain_id, c.timestamp) ) ) ))
(fun ( ( preserved_cycles,
blocks_per_cycle,
blocks_per_commitment,
blocks_per_roll_snapshot,
blocks_per_voting_period,
time_between_blocks,
endorsers_per_block,
hard_gas_limit_per_operation,
hard_gas_limit_per_block,
proof_of_work_threshold ),
( ( tokens_per_roll,
michelson_maximum_type_size,
seed_nonce_revelation_tip,
origination_size,
block_security_deposit,
endorsement_security_deposit,
baking_reward_per_endorsement,
endorsement_reward,
cost_per_byte,
hard_storage_limit_per_operation ),
( ( quorum_min,
quorum_max,
min_proposal_quorum,
initial_endorsers,
delay_per_missing_endorsement,
minimal_block_delay,
liquidity_baking_subsidy,
liquidity_baking_sunset_level,
liquidity_baking_escape_ema_threshold ),
(chain_id, timestamp) ) ) ) ->
{
preserved_cycles;
blocks_per_cycle;
blocks_per_commitment;
blocks_per_roll_snapshot;
blocks_per_voting_period;
time_between_blocks;
endorsers_per_block;
hard_gas_limit_per_operation;
hard_gas_limit_per_block;
proof_of_work_threshold;
tokens_per_roll;
michelson_maximum_type_size;
seed_nonce_revelation_tip;
origination_size;
block_security_deposit;
endorsement_security_deposit;
baking_reward_per_endorsement;
endorsement_reward;
cost_per_byte;
hard_storage_limit_per_operation;
quorum_min;
quorum_max;
min_proposal_quorum;
initial_endorsers;
delay_per_missing_endorsement;
minimal_block_delay;
liquidity_baking_subsidy;
liquidity_baking_sunset_level;
liquidity_baking_escape_ema_threshold;
chain_id;
timestamp;
})
(merge_objs
(obj10
(opt "preserved_cycles" uint8)
(opt "blocks_per_cycle" int32)
(opt "blocks_per_commitment" int32)
(opt "blocks_per_roll_snapshot" int32)
(opt "blocks_per_voting_period" int32)
(opt "time_between_blocks" (list Period.encoding))
(opt "endorsers_per_block" uint16)
(opt "hard_gas_limit_per_operation" Gas.Arith.z_integral_encoding)
(opt "hard_gas_limit_per_block" Gas.Arith.z_integral_encoding)
(opt "proof_of_work_threshold" int64))
(merge_objs
(obj10
(opt "tokens_per_roll" Tez.encoding)
(opt "michelson_maximum_type_size" uint16)
(opt "seed_nonce_revelation_tip" Tez.encoding)
(opt "origination_size" int31)
(opt "block_security_deposit" Tez.encoding)
(opt "endorsement_security_deposit" Tez.encoding)
(opt "baking_reward_per_endorsement" (list Tez.encoding))
(opt "endorsement_reward" (list Tez.encoding))
(opt "cost_per_byte" Tez.encoding)
(opt "hard_storage_limit_per_operation" z))
(merge_objs
(obj9
(opt "quorum_min" int32)
(opt "quorum_max" int32)
(opt "min_proposal_quorum" int32)
(opt "initial_endorsers" uint16)
(opt "delay_per_missing_endorsement" Period.encoding)
(opt "minimal_block_delay" Period.encoding)
(opt "liquidity_baking_subsidy" Tez.encoding)
(opt "liquidity_baking_sunset_level" int32)
(opt "liquidity_baking_escape_ema_threshold" int32))
(obj2
(opt "chain_id" Chain_id.encoding)
(opt "initial_timestamp" Time.Protocol.encoding)))))
let default_value (cctxt : Tezos_client_base.Client_context.full) :
t tzresult Lwt.t =
let cpctxt = new Protocol_client_context.wrap_full cctxt in
Protocol.Constants_services.all cpctxt (cpctxt#chain, cpctxt#block)
>>=? fun {parametric; _} ->
let to_chain_id_opt = function `Hash c -> Some c | _ -> None in
Shell_services.Blocks.Header.shell_header
cpctxt
~chain:cpctxt#chain
~block:cpctxt#block
()
>>=? fun header ->
return
{
preserved_cycles = Some parametric.preserved_cycles;
blocks_per_cycle = Some parametric.blocks_per_cycle;
blocks_per_commitment = Some parametric.blocks_per_commitment;
blocks_per_roll_snapshot = Some parametric.blocks_per_roll_snapshot;
blocks_per_voting_period = Some parametric.blocks_per_voting_period;
time_between_blocks = Some parametric.time_between_blocks;
minimal_block_delay = Some parametric.minimal_block_delay;
endorsers_per_block = Some parametric.endorsers_per_block;
hard_gas_limit_per_operation =
Some parametric.hard_gas_limit_per_operation;
hard_gas_limit_per_block = Some parametric.hard_gas_limit_per_block;
proof_of_work_threshold = Some parametric.proof_of_work_threshold;
tokens_per_roll = Some parametric.tokens_per_roll;
michelson_maximum_type_size =
Some parametric.michelson_maximum_type_size;
seed_nonce_revelation_tip = Some parametric.seed_nonce_revelation_tip;
origination_size = Some parametric.origination_size;
block_security_deposit = Some parametric.block_security_deposit;
endorsement_security_deposit =
Some parametric.endorsement_security_deposit;
baking_reward_per_endorsement =
Some parametric.baking_reward_per_endorsement;
endorsement_reward = Some parametric.endorsement_reward;
cost_per_byte = Some parametric.cost_per_byte;
hard_storage_limit_per_operation =
Some parametric.hard_storage_limit_per_operation;
quorum_min = Some parametric.quorum_min;
quorum_max = Some parametric.quorum_max;
min_proposal_quorum = Some parametric.min_proposal_quorum;
initial_endorsers = Some parametric.initial_endorsers;
delay_per_missing_endorsement =
Some parametric.delay_per_missing_endorsement;
liquidity_baking_subsidy = Some parametric.liquidity_baking_subsidy;
liquidity_baking_sunset_level =
Some parametric.liquidity_baking_sunset_level;
liquidity_baking_escape_ema_threshold =
Some parametric.liquidity_baking_escape_ema_threshold;
(* Bastard, additional parameters. *)
chain_id = to_chain_id_opt cpctxt#chain;
timestamp = Some header.timestamp;
}
let no_overrides : t =
{
preserved_cycles = None;
blocks_per_cycle = None;
blocks_per_commitment = None;
blocks_per_roll_snapshot = None;
blocks_per_voting_period = None;
time_between_blocks = None;
minimal_block_delay = None;
endorsers_per_block = None;
hard_gas_limit_per_operation = None;
hard_gas_limit_per_block = None;
proof_of_work_threshold = None;
tokens_per_roll = None;
michelson_maximum_type_size = None;
seed_nonce_revelation_tip = None;
origination_size = None;
block_security_deposit = None;
endorsement_security_deposit = None;
baking_reward_per_endorsement = None;
endorsement_reward = None;
cost_per_byte = None;
hard_storage_limit_per_operation = None;
quorum_min = None;
quorum_max = None;
min_proposal_quorum = None;
initial_endorsers = None;
delay_per_missing_endorsement = None;
liquidity_baking_subsidy = None;
liquidity_baking_sunset_level = None;
liquidity_baking_escape_ema_threshold = None;
chain_id = None;
timestamp = None;
}
(** Existential wrapper to support heterogeneous lists/maps. *)
type field =
| O : {
name : string;
override_value : 'a option;
pp : Format.formatter -> 'a -> unit;
}
-> field
let field_pp ppf (O {name; override_value; pp; _}) =
match override_value with
| None -> ()
| Some value -> Format.fprintf ppf "@[<h>%s: %a@]" name pp value
let apply_overrides (cctxt : Tezos_client_base.Client_context.printer) (o : t)
(c : Constants.parametric) : Constants.parametric tzresult Lwt.t =
let open Format in
let pp_print_int32 ppf i = fprintf ppf "%li" i in
let pp_print_int64 ppf i = fprintf ppf "%Li" i in
let fields : field list =
[
O
{
name = "preserved_cycles";
override_value = o.preserved_cycles;
pp = pp_print_int;
};
O
{
name = "blocks_per_cycle";
override_value = o.blocks_per_cycle;
pp = pp_print_int32;
};
O
{
name = "blocks_per_commitment";
override_value = o.blocks_per_commitment;
pp = pp_print_int32;
};
O
{
name = "blocks_per_roll_snapshot";
override_value = o.blocks_per_roll_snapshot;
pp = pp_print_int32;
};
O
{
name = "blocks_per_voting_period";
override_value = o.blocks_per_voting_period;
pp = pp_print_int32;
};
O
{
name = "time_between_blocks";
override_value = o.time_between_blocks;
pp = pp_print_list Period.pp;
};
O
{
name = "minimal_block_delay";
override_value = o.minimal_block_delay;
pp = Period.pp;
};
O
{
name = "endorsers_per_block";
override_value = o.endorsers_per_block;
pp = pp_print_int;
};
O
{
name = "hard_gas_limit_per_operation";
override_value = o.hard_gas_limit_per_operation;
pp = Gas.Arith.pp_integral;
};
O
{
name = "hard_gas_limit_per_block";
override_value = o.hard_gas_limit_per_block;
pp = Gas.Arith.pp_integral;
};
O
{
name = "proof_of_work_threshold";
override_value = o.proof_of_work_threshold;
pp = pp_print_int64;
};
O
{
name = "tokens_per_roll";
override_value = o.tokens_per_roll;
pp = Tez.pp;
};
O
{
name = "michelson_maximum_type_size";
override_value = o.michelson_maximum_type_size;
pp = pp_print_int;
};
O
{
name = "seed_nonce_revelation_tip";
override_value = o.seed_nonce_revelation_tip;
pp = Tez.pp;
};
O
{
name = "origination_size";
override_value = o.origination_size;
pp = pp_print_int;
};
O
{
name = "block_security_deposit";
override_value = o.block_security_deposit;
pp = Tez.pp;
};
O
{
name = "endorsement_security_deposit";
override_value = o.endorsement_security_deposit;
pp = Tez.pp;
};
O
{
name = "baking_reward_per_endorsement";
override_value = o.baking_reward_per_endorsement;
pp = pp_print_list Tez.pp;
};
O
{
name = "endorsement_reward";
override_value = o.endorsement_reward;
pp = pp_print_list Tez.pp;
};
O
{
name = "cost_per_byte";
override_value = o.cost_per_byte;
pp = Tez.pp;
};
O
{
name = "hard_storage_limit_per_operation";
override_value = o.hard_storage_limit_per_operation;
pp = Z.pp_print;
};
O
{
name = "quorum_min";
override_value = o.quorum_min;
pp = pp_print_int32;
};
O
{
name = "quorum_max";
override_value = o.quorum_max;
pp = pp_print_int32;
};
O
{
name = "min_proposal_quorum";
override_value = o.min_proposal_quorum;
pp = pp_print_int32;
};
O
{
name = "initial_endorsers";
override_value = o.initial_endorsers;
pp = pp_print_int;
};
O
{
name = "delay_per_missing_endorsement";
override_value = o.delay_per_missing_endorsement;
pp = Period.pp;
};
O
{
name = "liquidity_baking_subsidy";
override_value = o.liquidity_baking_subsidy;
pp = Tez.pp;
};
O
{
name = "liquidity_baking_sunset_level";
override_value = o.liquidity_baking_sunset_level;
pp = pp_print_int32;
};
O
{
name = "liquidity_baking_escape_ema_threshold";
override_value = o.liquidity_baking_escape_ema_threshold;
pp = pp_print_int32;
};
O {name = "chain_id"; override_value = o.chain_id; pp = Chain_id.pp};
O
{
name = "timestamp";
override_value = o.timestamp;
pp = Time.Protocol.pp_hum;
};
]
in
let fields_with_override =
fields
|> List.filter (fun (O {override_value; _}) ->
Option.is_some override_value)
in
(if fields_with_override <> [] then
cctxt#message
"@[<v>mockup client uses protocol overrides:@,%a@]@?"
(pp_print_list field_pp)
fields_with_override
else Lwt.return_unit)
>>= fun () ->
return
({
preserved_cycles =
Option.value ~default:c.preserved_cycles o.preserved_cycles;
blocks_per_cycle =
Option.value ~default:c.blocks_per_cycle o.blocks_per_cycle;
blocks_per_commitment =
Option.value ~default:c.blocks_per_commitment o.blocks_per_commitment;
blocks_per_roll_snapshot =
Option.value
~default:c.blocks_per_roll_snapshot
o.blocks_per_roll_snapshot;
blocks_per_voting_period =
Option.value
~default:c.blocks_per_voting_period
o.blocks_per_voting_period;
time_between_blocks =
Option.value ~default:c.time_between_blocks o.time_between_blocks;
minimal_block_delay =
Option.value ~default:c.minimal_block_delay o.minimal_block_delay;
endorsers_per_block =
Option.value ~default:c.endorsers_per_block o.endorsers_per_block;
hard_gas_limit_per_operation =
Option.value
~default:c.hard_gas_limit_per_operation
o.hard_gas_limit_per_operation;
hard_gas_limit_per_block =
Option.value
~default:c.hard_gas_limit_per_block
o.hard_gas_limit_per_block;
proof_of_work_threshold =
Option.value
~default:c.proof_of_work_threshold
o.proof_of_work_threshold;
tokens_per_roll =
Option.value ~default:c.tokens_per_roll o.tokens_per_roll;
michelson_maximum_type_size =
Option.value
~default:c.michelson_maximum_type_size
o.michelson_maximum_type_size;
seed_nonce_revelation_tip =
Option.value
~default:c.seed_nonce_revelation_tip
o.seed_nonce_revelation_tip;
origination_size =
Option.value ~default:c.origination_size o.origination_size;
block_security_deposit =
Option.value
~default:c.block_security_deposit
o.block_security_deposit;
endorsement_security_deposit =
Option.value
~default:c.endorsement_security_deposit
o.endorsement_security_deposit;
baking_reward_per_endorsement =
Option.value
~default:c.baking_reward_per_endorsement
o.baking_reward_per_endorsement;
endorsement_reward =
Option.value ~default:c.endorsement_reward o.endorsement_reward;
cost_per_byte = Option.value ~default:c.cost_per_byte o.cost_per_byte;
hard_storage_limit_per_operation =
Option.value
~default:c.hard_storage_limit_per_operation
o.hard_storage_limit_per_operation;
quorum_min = Option.value ~default:c.quorum_min o.quorum_min;
quorum_max = Option.value ~default:c.quorum_max o.quorum_max;
min_proposal_quorum =
Option.value ~default:c.min_proposal_quorum o.min_proposal_quorum;
initial_endorsers =
Option.value ~default:c.initial_endorsers o.initial_endorsers;
delay_per_missing_endorsement =
Option.value
~default:c.delay_per_missing_endorsement
o.delay_per_missing_endorsement;
liquidity_baking_subsidy =
Option.value
~default:c.liquidity_baking_subsidy
o.liquidity_baking_subsidy;
liquidity_baking_sunset_level =
Option.value
~default:c.liquidity_baking_sunset_level
o.liquidity_baking_sunset_level;
liquidity_baking_escape_ema_threshold =
Option.value
~default:c.liquidity_baking_escape_ema_threshold
o.liquidity_baking_escape_ema_threshold
(* Notice that the chain_id and the timestamp are not used here as they are not protocol constants... *);
}
: Constants.parametric)
end
module Parsed_account = struct
type t = {name : string; sk_uri : Client_keys.sk_uri; amount : Tez.t}
let pp ppf account =
let open Format in
let format_amount ppf value = fprintf ppf "amount:%a" Tez.pp value in
fprintf
ppf
"@[<v>name:%s@,sk_uri:%s@,%a@]"
account.name
(Uri.to_string (account.sk_uri :> Uri.t))
format_amount
account.amount
let encoding =
let open Data_encoding in
conv
(fun p -> (p.name, p.sk_uri, p.amount))
(fun (name, sk_uri, amount) -> {name; sk_uri; amount})
(obj3
(req "name" string)
(req "sk_uri" Client_keys.Secret_key.encoding)
(req "amount" Tez.encoding))
let to_bootstrap_account repr =
Tezos_client_base.Client_keys.neuterize repr.sk_uri >>=? fun pk_uri ->
Tezos_client_base.Client_keys.public_key pk_uri >>=? fun public_key ->
let public_key_hash = Signature.Public_key.hash public_key in
return
Parameters.
{public_key_hash; public_key = Some public_key; amount = repr.amount}
let default_to_json (cctxt : Tezos_client_base.Client_context.full) :
string tzresult Lwt.t =
let rpc_context = new Protocol_client_context.wrap_full cctxt in
let wallet = (cctxt :> Client_context.wallet) in
let parsed_account_reprs = ref [] in
let errors = ref [] in
Client_keys.list_keys wallet >>=? fun all_keys ->
List.iter_s
(function
| (name, pkh, _pk_opt, Some sk_uri) -> (
let contract = Contract.implicit_contract pkh in
Client_proto_context.get_balance
rpc_context
~chain:cctxt#chain
~block:cctxt#block
contract
>>= fun tz_balance ->
match tz_balance with
| Ok balance -> (
let tez_repr = Tez.of_mutez @@ Tez.to_mutez balance in
match tez_repr with
| None ->
(* we're reading the wallet, it's content MUST be valid *)
assert false
| Some amount ->
parsed_account_reprs :=
{name; sk_uri; amount} :: !parsed_account_reprs ;
Lwt.return_unit)
| Error err ->
errors := err :: !errors ;
Lwt.return_unit)
| _ -> Lwt.return_unit)
all_keys
>>= fun () ->
match !errors with
| [] ->
let json =
Data_encoding.Json.construct
(Data_encoding.list encoding)
!parsed_account_reprs
in
return @@ Data_encoding.Json.to_string json
| errs -> Lwt.return_error @@ List.concat errs
end
module Bootstrap_account = struct
let encoding : Parameters.bootstrap_account Data_encoding.t =
let open Data_encoding in
let open Parameters in
conv
(fun {public_key_hash; public_key; amount} ->
(public_key_hash, public_key, amount))
(fun (public_key_hash, public_key, amount) ->
{public_key_hash; public_key; amount})
(obj3
(req "public_key_hash" Signature.Public_key_hash.encoding)
(opt "public_key" Signature.Public_key.encoding)
(req "amount" Tez.encoding))
end
module Bootstrap_contract = struct
let encoding : Parameters.bootstrap_contract Data_encoding.t =
let open Data_encoding in
let open Parameters in
conv
(fun {delegate; amount; script} -> (delegate, amount, script))
(fun (delegate, amount, script) -> {delegate; amount; script})
(obj3
(req "delegate" Signature.Public_key_hash.encoding)
(req "amount" Tez.encoding)
(req "script" Script.encoding))
end
module Protocol_parameters = struct
type t = {
initial_timestamp : Time.Protocol.t;
bootstrap_accounts : Parameters.bootstrap_account list;
bootstrap_contracts : Parameters.bootstrap_contract list;
constants : Constants.parametric;
}
let encoding : t Data_encoding.t =
let open Data_encoding in
conv
(fun p ->
( p.initial_timestamp,
p.bootstrap_accounts,
p.bootstrap_contracts,
p.constants ))
(fun ( initial_timestamp,
bootstrap_accounts,
bootstrap_contracts,
constants ) ->
{initial_timestamp; bootstrap_accounts; bootstrap_contracts; constants})
(obj4
(req "initial_timestamp" Time.Protocol.encoding)
(req "bootstrap_accounts" (list Bootstrap_account.encoding))
(req "bootstrap_contracts" (list Bootstrap_contract.encoding))
(req "constants" Constants.parametric_encoding))
let default_value : t =
let parameters =
Default_parameters.parameters_of_constants
Default_parameters.constants_sandbox
in
{
initial_timestamp = Time.Protocol.epoch;
bootstrap_accounts = parameters.bootstrap_accounts;
bootstrap_contracts = parameters.bootstrap_contracts;
constants = parameters.constants;
}
end
(* This encoding extends [Protocol_constants_overrides.encoding] to allow
reading json files as produced by lib_parameters. Sadly, this require
copying partially [bootstrap_account_encoding], which is not exposed
in parameters_repr.ml. *)
let lib_parameters_json_encoding =
let bootstrap_account_encoding =
let open Data_encoding in
conv
(function
| {Parameters.public_key; amount; _} -> (
match public_key with
| None -> assert false
| Some pk -> (pk, amount)))
(fun (pk, amount) ->
{
Parameters.public_key = Some pk;
public_key_hash = Signature.Public_key.hash pk;
amount;
})
(tup2 Signature.Public_key.encoding Tez.encoding)
in
Data_encoding.(
merge_objs
(obj2
(opt "bootstrap_accounts" (list bootstrap_account_encoding))
(opt "commitments" (list Commitment.encoding)))
Protocol_constants_overrides.encoding)
(* ------------------------------------------------------------------------- *)
(* Blocks *)
type block = {
hash : Block_hash.t;
header : Block_header.t;
operations : Operation.packed list;
context : Protocol.Environment.Context.t;
}
module Forge = struct
let default_proof_of_work_nonce =
Bytes.create Constants.proof_of_work_nonce_size
let make_shell ~level ~predecessor ~timestamp ~fitness ~operations_hash =
Tezos_base.Block_header.
{
level;
predecessor;
timestamp;
fitness;
operations_hash;
proto_level = 0;
validation_passes = 0;
context = Context_hash.zero;
}
end
(* ------------------------------------------------------------------------- *)
(* RPC context *)
let initial_context (header : Block_header.shell_header)
({bootstrap_accounts; bootstrap_contracts; constants; _} :
Protocol_parameters.t) =
let parameters =
Default_parameters.parameters_of_constants
~bootstrap_accounts
~bootstrap_contracts
~with_commitments:false
constants
in
let json = Default_parameters.json_of_parameters parameters in
let proto_params =
Data_encoding.Binary.to_bytes_exn Data_encoding.json json
in
Tezos_protocol_environment.Context.(
let empty = Memory_context.empty in
add empty ["version"] (Bytes.of_string "genesis") >>= fun ctxt ->
add ctxt ["protocol_parameters"] proto_params)
>>= fun ctxt ->
Protocol.Main.init ctxt header >|= Protocol.Environment.wrap_tzresult
>>=? fun {context; _} -> return context
let mem_init :
cctxt:Tezos_client_base.Client_context.printer ->
parameters:Protocol_parameters.t ->
constants_overrides_json:Data_encoding.json option ->
bootstrap_accounts_json:Data_encoding.json option ->
Tezos_mockup_registration.Registration.mockup_context tzresult Lwt.t =
fun ~cctxt ~parameters ~constants_overrides_json ~bootstrap_accounts_json ->
let hash =
Block_hash.of_b58check_exn
"BLockGenesisGenesisGenesisGenesisGenesisCCCCCeZiLHU"
in
Need to read this file before since timestamp modification may be in
there
there *)
(match constants_overrides_json with
| None -> return Protocol_constants_overrides.no_overrides
| Some json -> (
match Data_encoding.Json.destruct lib_parameters_json_encoding json with
| (_, x) -> return x
| exception error ->
failwith
"cannot read protocol constants overrides: %a"
(Data_encoding.Json.print_error ?print_unknown:None)
error))
>>=? fun protocol_overrides ->
let default = parameters.initial_timestamp in
let timestamp = Option.value ~default protocol_overrides.timestamp in
(if not @@ Time.Protocol.equal default timestamp then
cctxt#message "@[<h>initial_timestamp: %a@]" Time.Protocol.pp_hum timestamp
else Lwt.return_unit)
>>= fun () ->
let shell_header =
Forge.make_shell
~level:0l
~predecessor:hash
~timestamp
~fitness:(Fitness.from_int64 0L)
~operations_hash:Operation_list_list_hash.zero
in
Protocol_constants_overrides.apply_overrides
cctxt
protocol_overrides
parameters.constants
>>=? fun protocol_custom ->
(match bootstrap_accounts_json with
| None -> return None
| Some json -> (
match
Data_encoding.Json.destruct
(Data_encoding.list Parsed_account.encoding)
json
with
| accounts ->
cctxt#message "@[<h>mockup client uses custom bootstrap accounts:@]"
>>= fun () ->
let open Format in
cctxt#message
"@[%a@]"
(pp_print_list
~pp_sep:(fun ppf () -> fprintf ppf ";@ ")
Parsed_account.pp)
accounts
>>= fun () ->
List.map_es Parsed_account.to_bootstrap_account accounts
>>=? fun bootstrap_accounts -> return (Some bootstrap_accounts)
| exception error ->
failwith
"cannot read definitions of bootstrap accounts: %a"
(Data_encoding.Json.print_error ?print_unknown:None)
error))
>>=? fun bootstrap_accounts_custom ->
initial_context
shell_header
{
parameters with
bootstrap_accounts =
Option.value
~default:parameters.bootstrap_accounts
bootstrap_accounts_custom;
constants = protocol_custom;
}
>>=? fun context ->
let chain_id =
Tezos_mockup_registration.Mockup_args.Chain_id.choose
~from_config_file:protocol_overrides.chain_id
in
return
Tezos_mockup_registration.Registration_intf.
{
chain = chain_id;
rpc_context =
Tezos_protocol_environment.
{block_hash = hash; block_header = shell_header; context};
protocol_data = Bytes.empty;
}
let migrate :
Tezos_mockup_registration.Registration.mockup_context ->
Tezos_mockup_registration.Registration.mockup_context tzresult Lwt.t =
fun {chain; rpc_context; protocol_data} ->
let Tezos_protocol_environment.{block_hash; context; block_header} =
rpc_context
in
Protocol.Main.init context block_header >|= Protocol.Environment.wrap_tzresult
>>=? fun {context; _} ->
let rpc_context =
Tezos_protocol_environment.{block_hash; block_header; context}
in
return
Tezos_mockup_registration.Registration_intf.
{chain; rpc_context; protocol_data}
(* ------------------------------------------------------------------------- *)
(* Register mockup *)
let () =
let open Tezos_mockup_registration.Registration in
let module Mockup : MOCKUP = struct
type parameters = Protocol_parameters.t
type protocol_constants = Protocol_constants_overrides.t
let parameters_encoding = Protocol_parameters.encoding
let default_parameters = Protocol_parameters.default_value
let protocol_constants_encoding = Protocol_constants_overrides.encoding
let default_protocol_constants = Protocol_constants_overrides.default_value
let default_bootstrap_accounts = Parsed_account.default_to_json
let protocol_hash = Protocol.hash
module Protocol = Protocol_client_context.Lifted_protocol
module Block_services = Protocol_client_context.Alpha_block_services
let directory = Plugin.RPC.rpc_services
let init = mem_init
let migrate = migrate
end in
register_mockup_environment (module Mockup)
| null | https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/proto_010_PtGRANAD/lib_client/mockup.ml | ocaml | ***************************************************************************
Open Source License
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 all copies or substantial portions of the Software.
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.
***************************************************************************
-------------------------------------------------------------------------
Mockup protocol parameters
* Protocol constants overriding logic.
* Equivalent of [Constants.parametric] with additionally [chain_id] and [timestamp] but each field is wrapped in an [option].
[Some] is an override, [None] means "Use the default value".
Additional, "bastard" parameters (they are not protocol constants but partially treated the same way).
* Shamefully copied from [Constants_repr.parametric_encoding] and adapted ([opt] instead of [req]).
Bastard, additional parameters.
* Existential wrapper to support heterogeneous lists/maps.
Notice that the chain_id and the timestamp are not used here as they are not protocol constants...
we're reading the wallet, it's content MUST be valid
This encoding extends [Protocol_constants_overrides.encoding] to allow
reading json files as produced by lib_parameters. Sadly, this require
copying partially [bootstrap_account_encoding], which is not exposed
in parameters_repr.ml.
-------------------------------------------------------------------------
Blocks
-------------------------------------------------------------------------
RPC context
-------------------------------------------------------------------------
Register mockup | Copyright ( c ) 2018 Dynamic Ledger Solutions , 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
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Protocol.Alpha_context
module Protocol_constants_overrides = struct
type t = {
preserved_cycles : int option;
blocks_per_cycle : int32 option;
blocks_per_commitment : int32 option;
blocks_per_roll_snapshot : int32 option;
blocks_per_voting_period : int32 option;
time_between_blocks : Period.t list option;
minimal_block_delay : Period.t option;
endorsers_per_block : int option;
hard_gas_limit_per_operation : Gas.Arith.integral option;
hard_gas_limit_per_block : Gas.Arith.integral option;
proof_of_work_threshold : int64 option;
tokens_per_roll : Tez.t option;
michelson_maximum_type_size : int option;
seed_nonce_revelation_tip : Tez.t option;
origination_size : int option;
block_security_deposit : Tez.t option;
endorsement_security_deposit : Tez.t option;
baking_reward_per_endorsement : Tez.t list option;
endorsement_reward : Tez.t list option;
cost_per_byte : Tez.t option;
hard_storage_limit_per_operation : Z.t option;
quorum_min : int32 option;
quorum_max : int32 option;
min_proposal_quorum : int32 option;
initial_endorsers : int option;
delay_per_missing_endorsement : Period.t option;
liquidity_baking_subsidy : Tez.t option;
liquidity_baking_sunset_level : int32 option;
liquidity_baking_escape_ema_threshold : int32 option;
chain_id : Chain_id.t option;
timestamp : Time.Protocol.t option;
}
let encoding : t Data_encoding.t =
let open Data_encoding in
conv
(fun c ->
( ( c.preserved_cycles,
c.blocks_per_cycle,
c.blocks_per_commitment,
c.blocks_per_roll_snapshot,
c.blocks_per_voting_period,
c.time_between_blocks,
c.endorsers_per_block,
c.hard_gas_limit_per_operation,
c.hard_gas_limit_per_block,
c.proof_of_work_threshold ),
( ( c.tokens_per_roll,
c.michelson_maximum_type_size,
c.seed_nonce_revelation_tip,
c.origination_size,
c.block_security_deposit,
c.endorsement_security_deposit,
c.baking_reward_per_endorsement,
c.endorsement_reward,
c.cost_per_byte,
c.hard_storage_limit_per_operation ),
( ( c.quorum_min,
c.quorum_max,
c.min_proposal_quorum,
c.initial_endorsers,
c.delay_per_missing_endorsement,
c.minimal_block_delay,
c.liquidity_baking_subsidy,
c.liquidity_baking_sunset_level,
c.liquidity_baking_escape_ema_threshold ),
(c.chain_id, c.timestamp) ) ) ))
(fun ( ( preserved_cycles,
blocks_per_cycle,
blocks_per_commitment,
blocks_per_roll_snapshot,
blocks_per_voting_period,
time_between_blocks,
endorsers_per_block,
hard_gas_limit_per_operation,
hard_gas_limit_per_block,
proof_of_work_threshold ),
( ( tokens_per_roll,
michelson_maximum_type_size,
seed_nonce_revelation_tip,
origination_size,
block_security_deposit,
endorsement_security_deposit,
baking_reward_per_endorsement,
endorsement_reward,
cost_per_byte,
hard_storage_limit_per_operation ),
( ( quorum_min,
quorum_max,
min_proposal_quorum,
initial_endorsers,
delay_per_missing_endorsement,
minimal_block_delay,
liquidity_baking_subsidy,
liquidity_baking_sunset_level,
liquidity_baking_escape_ema_threshold ),
(chain_id, timestamp) ) ) ) ->
{
preserved_cycles;
blocks_per_cycle;
blocks_per_commitment;
blocks_per_roll_snapshot;
blocks_per_voting_period;
time_between_blocks;
endorsers_per_block;
hard_gas_limit_per_operation;
hard_gas_limit_per_block;
proof_of_work_threshold;
tokens_per_roll;
michelson_maximum_type_size;
seed_nonce_revelation_tip;
origination_size;
block_security_deposit;
endorsement_security_deposit;
baking_reward_per_endorsement;
endorsement_reward;
cost_per_byte;
hard_storage_limit_per_operation;
quorum_min;
quorum_max;
min_proposal_quorum;
initial_endorsers;
delay_per_missing_endorsement;
minimal_block_delay;
liquidity_baking_subsidy;
liquidity_baking_sunset_level;
liquidity_baking_escape_ema_threshold;
chain_id;
timestamp;
})
(merge_objs
(obj10
(opt "preserved_cycles" uint8)
(opt "blocks_per_cycle" int32)
(opt "blocks_per_commitment" int32)
(opt "blocks_per_roll_snapshot" int32)
(opt "blocks_per_voting_period" int32)
(opt "time_between_blocks" (list Period.encoding))
(opt "endorsers_per_block" uint16)
(opt "hard_gas_limit_per_operation" Gas.Arith.z_integral_encoding)
(opt "hard_gas_limit_per_block" Gas.Arith.z_integral_encoding)
(opt "proof_of_work_threshold" int64))
(merge_objs
(obj10
(opt "tokens_per_roll" Tez.encoding)
(opt "michelson_maximum_type_size" uint16)
(opt "seed_nonce_revelation_tip" Tez.encoding)
(opt "origination_size" int31)
(opt "block_security_deposit" Tez.encoding)
(opt "endorsement_security_deposit" Tez.encoding)
(opt "baking_reward_per_endorsement" (list Tez.encoding))
(opt "endorsement_reward" (list Tez.encoding))
(opt "cost_per_byte" Tez.encoding)
(opt "hard_storage_limit_per_operation" z))
(merge_objs
(obj9
(opt "quorum_min" int32)
(opt "quorum_max" int32)
(opt "min_proposal_quorum" int32)
(opt "initial_endorsers" uint16)
(opt "delay_per_missing_endorsement" Period.encoding)
(opt "minimal_block_delay" Period.encoding)
(opt "liquidity_baking_subsidy" Tez.encoding)
(opt "liquidity_baking_sunset_level" int32)
(opt "liquidity_baking_escape_ema_threshold" int32))
(obj2
(opt "chain_id" Chain_id.encoding)
(opt "initial_timestamp" Time.Protocol.encoding)))))
let default_value (cctxt : Tezos_client_base.Client_context.full) :
t tzresult Lwt.t =
let cpctxt = new Protocol_client_context.wrap_full cctxt in
Protocol.Constants_services.all cpctxt (cpctxt#chain, cpctxt#block)
>>=? fun {parametric; _} ->
let to_chain_id_opt = function `Hash c -> Some c | _ -> None in
Shell_services.Blocks.Header.shell_header
cpctxt
~chain:cpctxt#chain
~block:cpctxt#block
()
>>=? fun header ->
return
{
preserved_cycles = Some parametric.preserved_cycles;
blocks_per_cycle = Some parametric.blocks_per_cycle;
blocks_per_commitment = Some parametric.blocks_per_commitment;
blocks_per_roll_snapshot = Some parametric.blocks_per_roll_snapshot;
blocks_per_voting_period = Some parametric.blocks_per_voting_period;
time_between_blocks = Some parametric.time_between_blocks;
minimal_block_delay = Some parametric.minimal_block_delay;
endorsers_per_block = Some parametric.endorsers_per_block;
hard_gas_limit_per_operation =
Some parametric.hard_gas_limit_per_operation;
hard_gas_limit_per_block = Some parametric.hard_gas_limit_per_block;
proof_of_work_threshold = Some parametric.proof_of_work_threshold;
tokens_per_roll = Some parametric.tokens_per_roll;
michelson_maximum_type_size =
Some parametric.michelson_maximum_type_size;
seed_nonce_revelation_tip = Some parametric.seed_nonce_revelation_tip;
origination_size = Some parametric.origination_size;
block_security_deposit = Some parametric.block_security_deposit;
endorsement_security_deposit =
Some parametric.endorsement_security_deposit;
baking_reward_per_endorsement =
Some parametric.baking_reward_per_endorsement;
endorsement_reward = Some parametric.endorsement_reward;
cost_per_byte = Some parametric.cost_per_byte;
hard_storage_limit_per_operation =
Some parametric.hard_storage_limit_per_operation;
quorum_min = Some parametric.quorum_min;
quorum_max = Some parametric.quorum_max;
min_proposal_quorum = Some parametric.min_proposal_quorum;
initial_endorsers = Some parametric.initial_endorsers;
delay_per_missing_endorsement =
Some parametric.delay_per_missing_endorsement;
liquidity_baking_subsidy = Some parametric.liquidity_baking_subsidy;
liquidity_baking_sunset_level =
Some parametric.liquidity_baking_sunset_level;
liquidity_baking_escape_ema_threshold =
Some parametric.liquidity_baking_escape_ema_threshold;
chain_id = to_chain_id_opt cpctxt#chain;
timestamp = Some header.timestamp;
}
let no_overrides : t =
{
preserved_cycles = None;
blocks_per_cycle = None;
blocks_per_commitment = None;
blocks_per_roll_snapshot = None;
blocks_per_voting_period = None;
time_between_blocks = None;
minimal_block_delay = None;
endorsers_per_block = None;
hard_gas_limit_per_operation = None;
hard_gas_limit_per_block = None;
proof_of_work_threshold = None;
tokens_per_roll = None;
michelson_maximum_type_size = None;
seed_nonce_revelation_tip = None;
origination_size = None;
block_security_deposit = None;
endorsement_security_deposit = None;
baking_reward_per_endorsement = None;
endorsement_reward = None;
cost_per_byte = None;
hard_storage_limit_per_operation = None;
quorum_min = None;
quorum_max = None;
min_proposal_quorum = None;
initial_endorsers = None;
delay_per_missing_endorsement = None;
liquidity_baking_subsidy = None;
liquidity_baking_sunset_level = None;
liquidity_baking_escape_ema_threshold = None;
chain_id = None;
timestamp = None;
}
type field =
| O : {
name : string;
override_value : 'a option;
pp : Format.formatter -> 'a -> unit;
}
-> field
let field_pp ppf (O {name; override_value; pp; _}) =
match override_value with
| None -> ()
| Some value -> Format.fprintf ppf "@[<h>%s: %a@]" name pp value
let apply_overrides (cctxt : Tezos_client_base.Client_context.printer) (o : t)
(c : Constants.parametric) : Constants.parametric tzresult Lwt.t =
let open Format in
let pp_print_int32 ppf i = fprintf ppf "%li" i in
let pp_print_int64 ppf i = fprintf ppf "%Li" i in
let fields : field list =
[
O
{
name = "preserved_cycles";
override_value = o.preserved_cycles;
pp = pp_print_int;
};
O
{
name = "blocks_per_cycle";
override_value = o.blocks_per_cycle;
pp = pp_print_int32;
};
O
{
name = "blocks_per_commitment";
override_value = o.blocks_per_commitment;
pp = pp_print_int32;
};
O
{
name = "blocks_per_roll_snapshot";
override_value = o.blocks_per_roll_snapshot;
pp = pp_print_int32;
};
O
{
name = "blocks_per_voting_period";
override_value = o.blocks_per_voting_period;
pp = pp_print_int32;
};
O
{
name = "time_between_blocks";
override_value = o.time_between_blocks;
pp = pp_print_list Period.pp;
};
O
{
name = "minimal_block_delay";
override_value = o.minimal_block_delay;
pp = Period.pp;
};
O
{
name = "endorsers_per_block";
override_value = o.endorsers_per_block;
pp = pp_print_int;
};
O
{
name = "hard_gas_limit_per_operation";
override_value = o.hard_gas_limit_per_operation;
pp = Gas.Arith.pp_integral;
};
O
{
name = "hard_gas_limit_per_block";
override_value = o.hard_gas_limit_per_block;
pp = Gas.Arith.pp_integral;
};
O
{
name = "proof_of_work_threshold";
override_value = o.proof_of_work_threshold;
pp = pp_print_int64;
};
O
{
name = "tokens_per_roll";
override_value = o.tokens_per_roll;
pp = Tez.pp;
};
O
{
name = "michelson_maximum_type_size";
override_value = o.michelson_maximum_type_size;
pp = pp_print_int;
};
O
{
name = "seed_nonce_revelation_tip";
override_value = o.seed_nonce_revelation_tip;
pp = Tez.pp;
};
O
{
name = "origination_size";
override_value = o.origination_size;
pp = pp_print_int;
};
O
{
name = "block_security_deposit";
override_value = o.block_security_deposit;
pp = Tez.pp;
};
O
{
name = "endorsement_security_deposit";
override_value = o.endorsement_security_deposit;
pp = Tez.pp;
};
O
{
name = "baking_reward_per_endorsement";
override_value = o.baking_reward_per_endorsement;
pp = pp_print_list Tez.pp;
};
O
{
name = "endorsement_reward";
override_value = o.endorsement_reward;
pp = pp_print_list Tez.pp;
};
O
{
name = "cost_per_byte";
override_value = o.cost_per_byte;
pp = Tez.pp;
};
O
{
name = "hard_storage_limit_per_operation";
override_value = o.hard_storage_limit_per_operation;
pp = Z.pp_print;
};
O
{
name = "quorum_min";
override_value = o.quorum_min;
pp = pp_print_int32;
};
O
{
name = "quorum_max";
override_value = o.quorum_max;
pp = pp_print_int32;
};
O
{
name = "min_proposal_quorum";
override_value = o.min_proposal_quorum;
pp = pp_print_int32;
};
O
{
name = "initial_endorsers";
override_value = o.initial_endorsers;
pp = pp_print_int;
};
O
{
name = "delay_per_missing_endorsement";
override_value = o.delay_per_missing_endorsement;
pp = Period.pp;
};
O
{
name = "liquidity_baking_subsidy";
override_value = o.liquidity_baking_subsidy;
pp = Tez.pp;
};
O
{
name = "liquidity_baking_sunset_level";
override_value = o.liquidity_baking_sunset_level;
pp = pp_print_int32;
};
O
{
name = "liquidity_baking_escape_ema_threshold";
override_value = o.liquidity_baking_escape_ema_threshold;
pp = pp_print_int32;
};
O {name = "chain_id"; override_value = o.chain_id; pp = Chain_id.pp};
O
{
name = "timestamp";
override_value = o.timestamp;
pp = Time.Protocol.pp_hum;
};
]
in
let fields_with_override =
fields
|> List.filter (fun (O {override_value; _}) ->
Option.is_some override_value)
in
(if fields_with_override <> [] then
cctxt#message
"@[<v>mockup client uses protocol overrides:@,%a@]@?"
(pp_print_list field_pp)
fields_with_override
else Lwt.return_unit)
>>= fun () ->
return
({
preserved_cycles =
Option.value ~default:c.preserved_cycles o.preserved_cycles;
blocks_per_cycle =
Option.value ~default:c.blocks_per_cycle o.blocks_per_cycle;
blocks_per_commitment =
Option.value ~default:c.blocks_per_commitment o.blocks_per_commitment;
blocks_per_roll_snapshot =
Option.value
~default:c.blocks_per_roll_snapshot
o.blocks_per_roll_snapshot;
blocks_per_voting_period =
Option.value
~default:c.blocks_per_voting_period
o.blocks_per_voting_period;
time_between_blocks =
Option.value ~default:c.time_between_blocks o.time_between_blocks;
minimal_block_delay =
Option.value ~default:c.minimal_block_delay o.minimal_block_delay;
endorsers_per_block =
Option.value ~default:c.endorsers_per_block o.endorsers_per_block;
hard_gas_limit_per_operation =
Option.value
~default:c.hard_gas_limit_per_operation
o.hard_gas_limit_per_operation;
hard_gas_limit_per_block =
Option.value
~default:c.hard_gas_limit_per_block
o.hard_gas_limit_per_block;
proof_of_work_threshold =
Option.value
~default:c.proof_of_work_threshold
o.proof_of_work_threshold;
tokens_per_roll =
Option.value ~default:c.tokens_per_roll o.tokens_per_roll;
michelson_maximum_type_size =
Option.value
~default:c.michelson_maximum_type_size
o.michelson_maximum_type_size;
seed_nonce_revelation_tip =
Option.value
~default:c.seed_nonce_revelation_tip
o.seed_nonce_revelation_tip;
origination_size =
Option.value ~default:c.origination_size o.origination_size;
block_security_deposit =
Option.value
~default:c.block_security_deposit
o.block_security_deposit;
endorsement_security_deposit =
Option.value
~default:c.endorsement_security_deposit
o.endorsement_security_deposit;
baking_reward_per_endorsement =
Option.value
~default:c.baking_reward_per_endorsement
o.baking_reward_per_endorsement;
endorsement_reward =
Option.value ~default:c.endorsement_reward o.endorsement_reward;
cost_per_byte = Option.value ~default:c.cost_per_byte o.cost_per_byte;
hard_storage_limit_per_operation =
Option.value
~default:c.hard_storage_limit_per_operation
o.hard_storage_limit_per_operation;
quorum_min = Option.value ~default:c.quorum_min o.quorum_min;
quorum_max = Option.value ~default:c.quorum_max o.quorum_max;
min_proposal_quorum =
Option.value ~default:c.min_proposal_quorum o.min_proposal_quorum;
initial_endorsers =
Option.value ~default:c.initial_endorsers o.initial_endorsers;
delay_per_missing_endorsement =
Option.value
~default:c.delay_per_missing_endorsement
o.delay_per_missing_endorsement;
liquidity_baking_subsidy =
Option.value
~default:c.liquidity_baking_subsidy
o.liquidity_baking_subsidy;
liquidity_baking_sunset_level =
Option.value
~default:c.liquidity_baking_sunset_level
o.liquidity_baking_sunset_level;
liquidity_baking_escape_ema_threshold =
Option.value
~default:c.liquidity_baking_escape_ema_threshold
o.liquidity_baking_escape_ema_threshold
}
: Constants.parametric)
end
module Parsed_account = struct
type t = {name : string; sk_uri : Client_keys.sk_uri; amount : Tez.t}
let pp ppf account =
let open Format in
let format_amount ppf value = fprintf ppf "amount:%a" Tez.pp value in
fprintf
ppf
"@[<v>name:%s@,sk_uri:%s@,%a@]"
account.name
(Uri.to_string (account.sk_uri :> Uri.t))
format_amount
account.amount
let encoding =
let open Data_encoding in
conv
(fun p -> (p.name, p.sk_uri, p.amount))
(fun (name, sk_uri, amount) -> {name; sk_uri; amount})
(obj3
(req "name" string)
(req "sk_uri" Client_keys.Secret_key.encoding)
(req "amount" Tez.encoding))
let to_bootstrap_account repr =
Tezos_client_base.Client_keys.neuterize repr.sk_uri >>=? fun pk_uri ->
Tezos_client_base.Client_keys.public_key pk_uri >>=? fun public_key ->
let public_key_hash = Signature.Public_key.hash public_key in
return
Parameters.
{public_key_hash; public_key = Some public_key; amount = repr.amount}
let default_to_json (cctxt : Tezos_client_base.Client_context.full) :
string tzresult Lwt.t =
let rpc_context = new Protocol_client_context.wrap_full cctxt in
let wallet = (cctxt :> Client_context.wallet) in
let parsed_account_reprs = ref [] in
let errors = ref [] in
Client_keys.list_keys wallet >>=? fun all_keys ->
List.iter_s
(function
| (name, pkh, _pk_opt, Some sk_uri) -> (
let contract = Contract.implicit_contract pkh in
Client_proto_context.get_balance
rpc_context
~chain:cctxt#chain
~block:cctxt#block
contract
>>= fun tz_balance ->
match tz_balance with
| Ok balance -> (
let tez_repr = Tez.of_mutez @@ Tez.to_mutez balance in
match tez_repr with
| None ->
assert false
| Some amount ->
parsed_account_reprs :=
{name; sk_uri; amount} :: !parsed_account_reprs ;
Lwt.return_unit)
| Error err ->
errors := err :: !errors ;
Lwt.return_unit)
| _ -> Lwt.return_unit)
all_keys
>>= fun () ->
match !errors with
| [] ->
let json =
Data_encoding.Json.construct
(Data_encoding.list encoding)
!parsed_account_reprs
in
return @@ Data_encoding.Json.to_string json
| errs -> Lwt.return_error @@ List.concat errs
end
module Bootstrap_account = struct
let encoding : Parameters.bootstrap_account Data_encoding.t =
let open Data_encoding in
let open Parameters in
conv
(fun {public_key_hash; public_key; amount} ->
(public_key_hash, public_key, amount))
(fun (public_key_hash, public_key, amount) ->
{public_key_hash; public_key; amount})
(obj3
(req "public_key_hash" Signature.Public_key_hash.encoding)
(opt "public_key" Signature.Public_key.encoding)
(req "amount" Tez.encoding))
end
module Bootstrap_contract = struct
let encoding : Parameters.bootstrap_contract Data_encoding.t =
let open Data_encoding in
let open Parameters in
conv
(fun {delegate; amount; script} -> (delegate, amount, script))
(fun (delegate, amount, script) -> {delegate; amount; script})
(obj3
(req "delegate" Signature.Public_key_hash.encoding)
(req "amount" Tez.encoding)
(req "script" Script.encoding))
end
module Protocol_parameters = struct
type t = {
initial_timestamp : Time.Protocol.t;
bootstrap_accounts : Parameters.bootstrap_account list;
bootstrap_contracts : Parameters.bootstrap_contract list;
constants : Constants.parametric;
}
let encoding : t Data_encoding.t =
let open Data_encoding in
conv
(fun p ->
( p.initial_timestamp,
p.bootstrap_accounts,
p.bootstrap_contracts,
p.constants ))
(fun ( initial_timestamp,
bootstrap_accounts,
bootstrap_contracts,
constants ) ->
{initial_timestamp; bootstrap_accounts; bootstrap_contracts; constants})
(obj4
(req "initial_timestamp" Time.Protocol.encoding)
(req "bootstrap_accounts" (list Bootstrap_account.encoding))
(req "bootstrap_contracts" (list Bootstrap_contract.encoding))
(req "constants" Constants.parametric_encoding))
let default_value : t =
let parameters =
Default_parameters.parameters_of_constants
Default_parameters.constants_sandbox
in
{
initial_timestamp = Time.Protocol.epoch;
bootstrap_accounts = parameters.bootstrap_accounts;
bootstrap_contracts = parameters.bootstrap_contracts;
constants = parameters.constants;
}
end
let lib_parameters_json_encoding =
let bootstrap_account_encoding =
let open Data_encoding in
conv
(function
| {Parameters.public_key; amount; _} -> (
match public_key with
| None -> assert false
| Some pk -> (pk, amount)))
(fun (pk, amount) ->
{
Parameters.public_key = Some pk;
public_key_hash = Signature.Public_key.hash pk;
amount;
})
(tup2 Signature.Public_key.encoding Tez.encoding)
in
Data_encoding.(
merge_objs
(obj2
(opt "bootstrap_accounts" (list bootstrap_account_encoding))
(opt "commitments" (list Commitment.encoding)))
Protocol_constants_overrides.encoding)
type block = {
hash : Block_hash.t;
header : Block_header.t;
operations : Operation.packed list;
context : Protocol.Environment.Context.t;
}
module Forge = struct
let default_proof_of_work_nonce =
Bytes.create Constants.proof_of_work_nonce_size
let make_shell ~level ~predecessor ~timestamp ~fitness ~operations_hash =
Tezos_base.Block_header.
{
level;
predecessor;
timestamp;
fitness;
operations_hash;
proto_level = 0;
validation_passes = 0;
context = Context_hash.zero;
}
end
let initial_context (header : Block_header.shell_header)
({bootstrap_accounts; bootstrap_contracts; constants; _} :
Protocol_parameters.t) =
let parameters =
Default_parameters.parameters_of_constants
~bootstrap_accounts
~bootstrap_contracts
~with_commitments:false
constants
in
let json = Default_parameters.json_of_parameters parameters in
let proto_params =
Data_encoding.Binary.to_bytes_exn Data_encoding.json json
in
Tezos_protocol_environment.Context.(
let empty = Memory_context.empty in
add empty ["version"] (Bytes.of_string "genesis") >>= fun ctxt ->
add ctxt ["protocol_parameters"] proto_params)
>>= fun ctxt ->
Protocol.Main.init ctxt header >|= Protocol.Environment.wrap_tzresult
>>=? fun {context; _} -> return context
let mem_init :
cctxt:Tezos_client_base.Client_context.printer ->
parameters:Protocol_parameters.t ->
constants_overrides_json:Data_encoding.json option ->
bootstrap_accounts_json:Data_encoding.json option ->
Tezos_mockup_registration.Registration.mockup_context tzresult Lwt.t =
fun ~cctxt ~parameters ~constants_overrides_json ~bootstrap_accounts_json ->
let hash =
Block_hash.of_b58check_exn
"BLockGenesisGenesisGenesisGenesisGenesisCCCCCeZiLHU"
in
Need to read this file before since timestamp modification may be in
there
there *)
(match constants_overrides_json with
| None -> return Protocol_constants_overrides.no_overrides
| Some json -> (
match Data_encoding.Json.destruct lib_parameters_json_encoding json with
| (_, x) -> return x
| exception error ->
failwith
"cannot read protocol constants overrides: %a"
(Data_encoding.Json.print_error ?print_unknown:None)
error))
>>=? fun protocol_overrides ->
let default = parameters.initial_timestamp in
let timestamp = Option.value ~default protocol_overrides.timestamp in
(if not @@ Time.Protocol.equal default timestamp then
cctxt#message "@[<h>initial_timestamp: %a@]" Time.Protocol.pp_hum timestamp
else Lwt.return_unit)
>>= fun () ->
let shell_header =
Forge.make_shell
~level:0l
~predecessor:hash
~timestamp
~fitness:(Fitness.from_int64 0L)
~operations_hash:Operation_list_list_hash.zero
in
Protocol_constants_overrides.apply_overrides
cctxt
protocol_overrides
parameters.constants
>>=? fun protocol_custom ->
(match bootstrap_accounts_json with
| None -> return None
| Some json -> (
match
Data_encoding.Json.destruct
(Data_encoding.list Parsed_account.encoding)
json
with
| accounts ->
cctxt#message "@[<h>mockup client uses custom bootstrap accounts:@]"
>>= fun () ->
let open Format in
cctxt#message
"@[%a@]"
(pp_print_list
~pp_sep:(fun ppf () -> fprintf ppf ";@ ")
Parsed_account.pp)
accounts
>>= fun () ->
List.map_es Parsed_account.to_bootstrap_account accounts
>>=? fun bootstrap_accounts -> return (Some bootstrap_accounts)
| exception error ->
failwith
"cannot read definitions of bootstrap accounts: %a"
(Data_encoding.Json.print_error ?print_unknown:None)
error))
>>=? fun bootstrap_accounts_custom ->
initial_context
shell_header
{
parameters with
bootstrap_accounts =
Option.value
~default:parameters.bootstrap_accounts
bootstrap_accounts_custom;
constants = protocol_custom;
}
>>=? fun context ->
let chain_id =
Tezos_mockup_registration.Mockup_args.Chain_id.choose
~from_config_file:protocol_overrides.chain_id
in
return
Tezos_mockup_registration.Registration_intf.
{
chain = chain_id;
rpc_context =
Tezos_protocol_environment.
{block_hash = hash; block_header = shell_header; context};
protocol_data = Bytes.empty;
}
let migrate :
Tezos_mockup_registration.Registration.mockup_context ->
Tezos_mockup_registration.Registration.mockup_context tzresult Lwt.t =
fun {chain; rpc_context; protocol_data} ->
let Tezos_protocol_environment.{block_hash; context; block_header} =
rpc_context
in
Protocol.Main.init context block_header >|= Protocol.Environment.wrap_tzresult
>>=? fun {context; _} ->
let rpc_context =
Tezos_protocol_environment.{block_hash; block_header; context}
in
return
Tezos_mockup_registration.Registration_intf.
{chain; rpc_context; protocol_data}
let () =
let open Tezos_mockup_registration.Registration in
let module Mockup : MOCKUP = struct
type parameters = Protocol_parameters.t
type protocol_constants = Protocol_constants_overrides.t
let parameters_encoding = Protocol_parameters.encoding
let default_parameters = Protocol_parameters.default_value
let protocol_constants_encoding = Protocol_constants_overrides.encoding
let default_protocol_constants = Protocol_constants_overrides.default_value
let default_bootstrap_accounts = Parsed_account.default_to_json
let protocol_hash = Protocol.hash
module Protocol = Protocol_client_context.Lifted_protocol
module Block_services = Protocol_client_context.Alpha_block_services
let directory = Plugin.RPC.rpc_services
let init = mem_init
let migrate = migrate
end in
register_mockup_environment (module Mockup)
|
f86e4b2f73720b5d25cf74a7e1d83c50d1404e877c59cd42c86ed484e08d0d04 | tisnik/clojure-examples | project.clj | ;
( C ) Copyright 2020
;
; All rights reserved. This program and the accompanying materials
; are made available under the terms of the Eclipse Public License v1.0
; which accompanies this distribution, and is available at
-v10.html
;
; Contributors:
;
(defproject kafka-repl "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0"
:url "-2.0/"}
:dependencies [[org.clojure/clojure "1.10.1"]
[fundingcircle/jackdaw "0.7.6"]]
:plugins [[lein-kibit "0.1.8"]
[test2junit "1.1.0"]
[lein-marginalia "0.9.1"]]
:main ^:skip-aot kafka-repl.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all
:jvm-opts ["-Dclojure.compiler.direct-linking=true"]}})
| null | https://raw.githubusercontent.com/tisnik/clojure-examples/0e8ea0e19bd2c2672bbfd63db7c9efb73c816654/kafka-repl/project.clj | clojure |
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
Contributors:
| ( C ) Copyright 2020
-v10.html
(defproject kafka-repl "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0"
:url "-2.0/"}
:dependencies [[org.clojure/clojure "1.10.1"]
[fundingcircle/jackdaw "0.7.6"]]
:plugins [[lein-kibit "0.1.8"]
[test2junit "1.1.0"]
[lein-marginalia "0.9.1"]]
:main ^:skip-aot kafka-repl.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all
:jvm-opts ["-Dclojure.compiler.direct-linking=true"]}})
|
4593521b04966f17d3da8199dfd0148e45dc6fe12967716540421ea7eb2d8b09 | mlesniak/game | Main.hs | | Simulation of balls using the Chipmunk library .
--
, ball and border are the important functions ; and probably
the call to step in line 63 .
--
module Main where
import Control.Concurrent
import Control.Monad
import Graphics.UI.GLUT hiding (position, Position, scale)
import Physics.Hipmunk hiding (Position)
import Statistics
import System.Random (randomRIO)
import Unsafe.Coerce (unsafeCoerce)
import Window
main :: IO ()
main = do
-- Physics intialization.
initChipmunk
space <- newSpace
gravity space $= Vector 0 (-1)
-- Enabling performance information display.
fpsStat <- newFPS
-- Create outside borders.
let borders = [ ((0.01, 0.00), (1.29, 0.00)),
((0.01, 0.00), (0.01, 1.00)),
((1.29, 0.00), (1.29, 1.00)) ]
mapM_ (border space) borders
Drag'n'Drop support . We store the object ( actually , its shape ) clicked
-- here until the user is finished (by releasing the mouse button).
drag <- newMVar Nothing
dragpos <- newMVar Nothing
Container for all balls .
let numNew = 10
balls <- newMVar []
The WindowConfig type is special for the underlying graphics system and
-- provides handlers for frame drawing, key and mouse events. It's not
-- important for the physic simulation.
let wc = WindowConfig {
-- The FrameHandler is called for every frame, i.e. fps times per
second .
frameHandler = FrameHandler $ do
let fps' = fps wc
drawHelp
-- Handle Drag'n'Drop. I'm pretty sure this is not the best
-- solution, but it works for now.
v <- readMVar drag
case v of
Nothing -> return ()
Just (b,p) -> do
-- Reset velocity. Should we reset to the known velocity
-- before the DnD?
moldp <- takeMVar dragpos
putMVar dragpos (Just p)
let vel = case moldp of
Nothing -> Vector 0 0
Just oldp -> scale (p-oldp) fps'
velocity b $= vel
position b $= p
-- Draw borders in red.
color $ Color3 1 0 (0 :: GLdouble)
renderPrimitive Lines $
forM_ borders $ \(s, e) -> do
toVertex s
toVertex e
-- Draw balls with their particular color.
bs <- readMVar balls
forM_ bs $ \(b, c, r) -> do
Vector x y <- get $ position (body b)
circle (x, y) r c
-- Draw fps statistics, if enabled and calculate new position.
drawFPS fpsStat (Just $ "Objects: " ++ show (length bs))
-- Physics-wise, this is the important step in the simulation which
-- recalculates the new positions of our objects.
step space (1.0/fps')
-- Key handling.
, keyHandler = Just $ KeyHandler $ \key state _ ->
when (state == Down) $
case key of
Char 'c' -> clearSpace space balls
Char 'b' -> replicateM_ numNew (newBall space balls)
SpecialKey KeyLeft -> gravity space $= Vector (-0.7) (-0.7)
SpecialKey KeyDown -> gravity space $= Vector (-0.0) (-1)
SpecialKey KeyRight-> gravity space $= Vector ( 0.7) (-0.7)
SpecialKey KeyUp-> gravity space $= Vector 0 0.1
Char 'v' -> newBigBall space balls
Char 'f' -> toggleFPS fpsStat
Char '\27' -> leaveMainLoop
_ -> return ()
, mouseHandler = Just $ MouseHandler (clickBall space drag)
, motionHandler = Just $ MotionHandler (moveBall drag)
, title = "Ball simulation with Chipmunk in Haskell"
, size = Size 640 480
, fps = 30
}
windowLoop wc
-- Object creation and removal, the important physics stuff --
-- Storing the balls, i.e. their shape, color and radius.
type Balls = MVar [(Shape, Color3 GLdouble, Double)]
-- | Create an unmovable and blocking border.
border :: Space -> ((Double, Double), (Double, Double)) -> IO ()
border space ((x1,y1), (x2,y2)) = do
ground <- newBody infinity infinity
gshape <- newShape ground (LineSegment (Vector x1 y1) (Vector x2 y2) 0.01)
(Vector 0.0 0.0)
position ground $= Vector 0.0 0.00
elasticity gshape $= 0.5
friction gshape $= 0.8
spaceAdd space (Static gshape)
| Create a new ball with random velocity , position around 0.6 on the x - axis
newBall :: Space -> Balls -> IO ()
newBall space balls = do
x <- randomRIO (0.5, 0.7) :: IO CpFloat
maxRadius <- randomRIO (0.01, 0.03) :: IO Double
rad <- randomRIO (0.001, maxRadius) :: IO Double
vel <- randomPoint (-0.8, 0.8)
ball space balls 100 (x, 0.7) vel rad
-- | Creates a new heavy ball.
newBigBall :: Space -> Balls -> IO ()
newBigBall space balls = ball space balls 100000 (0.65, 0.95) (0,0) 0.05
-- | Creates a new ball with the given properties and add it to the space.
--
-- Physics-wise, this (and border above) are the important functions for
-- simulating physically correct ball behaviour.
ball :: Space -> Balls -> Mass -> (CpFloat, CpFloat) -> (CpFloat, CpFloat)
-> Double -> IO ()
ball space balls m pos vel rad = do
-- Body.
c <- randomColor
b <- newBody m infinity
position b $= uncurry Vector pos
velocity b $= uncurry Vector vel
spaceAdd space b
-- Shape.
bshape <- newShape b (Circle $ unsafeCoerce rad) (Vector 0 0)
elasticity bshape $= 0.9
friction bshape $= 0.1
spaceAdd space bshape
modifyMVar_ balls (\k -> return $ (bshape, c, rad):k)
-- | Empties the space.
clearSpace :: Space -> MVar [(Shape, t, t1)] -> IO ()
clearSpace space balls = do
as <- takeMVar balls
mapM_ (\(k,_,_) -> spaceRemove space k) as
mapM_ (\(sh,_,_) -> spaceRemove space (body sh)) as
putMVar balls []
Drag'n'Drop support --
moveBall :: MVar (Maybe (Body, Vector)) -> Position -> IO ()
moveBall mv (Position pos) = do
v <- takeMVar mv
case v of
Nothing -> putMVar mv Nothing
Just (b,_) -> putMVar mv $ Just (b, p2v pos)
where p2v (x,y) = Vector (unsafeCoerce x) (unsafeCoerce y)
clickBall :: Space -> MVar (Maybe (Body, Vector)) -> MouseButton -> Position
-> IO ()
clickBall space mv _ (Position pos) = do
v <- takeMVar mv
case v of
Nothing -> do
shs <- spaceQueryList space (p2v pos) (-1) 0
if null shs
then putMVar mv Nothing
else do
let b = body (head shs)
putMVar mv (Just (b, p2v pos))
-- Something is already dragged, user has released the button.
Just _ -> putMVar mv Nothing
where p2v (x,y) = Vector (unsafeCoerce x) (unsafeCoerce y)
-- Helper functions --
-- | Draws a circle in the given color with a black border.
circle :: (CpFloat, CpFloat) -> CpFloat -> Color3 GLdouble -> IO ()
circle (x,y) r c = preservingMatrix $ do
let poly = 24
ang p = p * 2 * pi / poly
pos = map (\p -> (x+cos(ang p)*r, y + sin(ang p)*r)) [1,2..poly]
color c
renderPrimitive Graphics.UI.GLUT.Polygon $
mapM_ (toVertex . conv) pos
color $ Color3 0 0 (0 :: GLdouble)
renderPrimitive Graphics.UI.GLUT.LineLoop $
mapM_ (toVertex . conv) pos
where conv :: (CpFloat, CpFloat) -> (GLdouble, GLdouble)
conv (a,b) = (unsafeCoerce a, unsafeCoerce b)
-- | Returns a random point in the given range.
--
Returns the point in coordinates .
randomPoint :: (Double, Double) -> IO (CpFloat, CpFloat)
randomPoint (l, r) = do
Double = = CpFloat in .
x1 <- unsafeCoerce `liftM` (randomRIO (l, r) :: IO Double)
x2 <- unsafeCoerce `liftM` (randomRIO (l, r) :: IO Double)
return (x1, x2)
-- | Returns a random color.
randomColor :: IO (Color3 GLdouble)
randomColor = do
c1 <- rndC
c2 <- rndC
c3 <- rndC
return (Color3 c1 c2 c3)
where rndC :: IO GLdouble
rndC = unsafeCoerce `liftM` (randomRIO (0, 1) :: IO Double)
drawHelp :: IO ()
drawHelp = do
color $ Color3 0 0 (0 :: GLdouble)
text (0.9, 0.97) [
"Keys:"
, "b Spawn 10 balls"
, "v Spawn 1 big ball"
, "Arrows Gravity direction"
, "c clear box"
, "f Toggle FPS graph"
, "Escape Quit"
, ""
, "Drag'n'Drop possible." ]
| null | https://raw.githubusercontent.com/mlesniak/game/63847b04b6fafdef0a805351f47e4bada85e8b40/Main.hs | haskell |
Physics intialization.
Enabling performance information display.
Create outside borders.
here until the user is finished (by releasing the mouse button).
provides handlers for frame drawing, key and mouse events. It's not
important for the physic simulation.
The FrameHandler is called for every frame, i.e. fps times per
Handle Drag'n'Drop. I'm pretty sure this is not the best
solution, but it works for now.
Reset velocity. Should we reset to the known velocity
before the DnD?
Draw borders in red.
Draw balls with their particular color.
Draw fps statistics, if enabled and calculate new position.
Physics-wise, this is the important step in the simulation which
recalculates the new positions of our objects.
Key handling.
Object creation and removal, the important physics stuff --
Storing the balls, i.e. their shape, color and radius.
| Create an unmovable and blocking border.
| Creates a new heavy ball.
| Creates a new ball with the given properties and add it to the space.
Physics-wise, this (and border above) are the important functions for
simulating physically correct ball behaviour.
Body.
Shape.
| Empties the space.
Something is already dragged, user has released the button.
Helper functions --
| Draws a circle in the given color with a black border.
| Returns a random point in the given range.
| Returns a random color. | | Simulation of balls using the Chipmunk library .
, ball and border are the important functions ; and probably
the call to step in line 63 .
module Main where
import Control.Concurrent
import Control.Monad
import Graphics.UI.GLUT hiding (position, Position, scale)
import Physics.Hipmunk hiding (Position)
import Statistics
import System.Random (randomRIO)
import Unsafe.Coerce (unsafeCoerce)
import Window
main :: IO ()
main = do
initChipmunk
space <- newSpace
gravity space $= Vector 0 (-1)
fpsStat <- newFPS
let borders = [ ((0.01, 0.00), (1.29, 0.00)),
((0.01, 0.00), (0.01, 1.00)),
((1.29, 0.00), (1.29, 1.00)) ]
mapM_ (border space) borders
Drag'n'Drop support . We store the object ( actually , its shape ) clicked
drag <- newMVar Nothing
dragpos <- newMVar Nothing
Container for all balls .
let numNew = 10
balls <- newMVar []
The WindowConfig type is special for the underlying graphics system and
let wc = WindowConfig {
second .
frameHandler = FrameHandler $ do
let fps' = fps wc
drawHelp
v <- readMVar drag
case v of
Nothing -> return ()
Just (b,p) -> do
moldp <- takeMVar dragpos
putMVar dragpos (Just p)
let vel = case moldp of
Nothing -> Vector 0 0
Just oldp -> scale (p-oldp) fps'
velocity b $= vel
position b $= p
color $ Color3 1 0 (0 :: GLdouble)
renderPrimitive Lines $
forM_ borders $ \(s, e) -> do
toVertex s
toVertex e
bs <- readMVar balls
forM_ bs $ \(b, c, r) -> do
Vector x y <- get $ position (body b)
circle (x, y) r c
drawFPS fpsStat (Just $ "Objects: " ++ show (length bs))
step space (1.0/fps')
, keyHandler = Just $ KeyHandler $ \key state _ ->
when (state == Down) $
case key of
Char 'c' -> clearSpace space balls
Char 'b' -> replicateM_ numNew (newBall space balls)
SpecialKey KeyLeft -> gravity space $= Vector (-0.7) (-0.7)
SpecialKey KeyDown -> gravity space $= Vector (-0.0) (-1)
SpecialKey KeyRight-> gravity space $= Vector ( 0.7) (-0.7)
SpecialKey KeyUp-> gravity space $= Vector 0 0.1
Char 'v' -> newBigBall space balls
Char 'f' -> toggleFPS fpsStat
Char '\27' -> leaveMainLoop
_ -> return ()
, mouseHandler = Just $ MouseHandler (clickBall space drag)
, motionHandler = Just $ MotionHandler (moveBall drag)
, title = "Ball simulation with Chipmunk in Haskell"
, size = Size 640 480
, fps = 30
}
windowLoop wc
type Balls = MVar [(Shape, Color3 GLdouble, Double)]
border :: Space -> ((Double, Double), (Double, Double)) -> IO ()
border space ((x1,y1), (x2,y2)) = do
ground <- newBody infinity infinity
gshape <- newShape ground (LineSegment (Vector x1 y1) (Vector x2 y2) 0.01)
(Vector 0.0 0.0)
position ground $= Vector 0.0 0.00
elasticity gshape $= 0.5
friction gshape $= 0.8
spaceAdd space (Static gshape)
| Create a new ball with random velocity , position around 0.6 on the x - axis
newBall :: Space -> Balls -> IO ()
newBall space balls = do
x <- randomRIO (0.5, 0.7) :: IO CpFloat
maxRadius <- randomRIO (0.01, 0.03) :: IO Double
rad <- randomRIO (0.001, maxRadius) :: IO Double
vel <- randomPoint (-0.8, 0.8)
ball space balls 100 (x, 0.7) vel rad
newBigBall :: Space -> Balls -> IO ()
newBigBall space balls = ball space balls 100000 (0.65, 0.95) (0,0) 0.05
ball :: Space -> Balls -> Mass -> (CpFloat, CpFloat) -> (CpFloat, CpFloat)
-> Double -> IO ()
ball space balls m pos vel rad = do
c <- randomColor
b <- newBody m infinity
position b $= uncurry Vector pos
velocity b $= uncurry Vector vel
spaceAdd space b
bshape <- newShape b (Circle $ unsafeCoerce rad) (Vector 0 0)
elasticity bshape $= 0.9
friction bshape $= 0.1
spaceAdd space bshape
modifyMVar_ balls (\k -> return $ (bshape, c, rad):k)
clearSpace :: Space -> MVar [(Shape, t, t1)] -> IO ()
clearSpace space balls = do
as <- takeMVar balls
mapM_ (\(k,_,_) -> spaceRemove space k) as
mapM_ (\(sh,_,_) -> spaceRemove space (body sh)) as
putMVar balls []
moveBall :: MVar (Maybe (Body, Vector)) -> Position -> IO ()
moveBall mv (Position pos) = do
v <- takeMVar mv
case v of
Nothing -> putMVar mv Nothing
Just (b,_) -> putMVar mv $ Just (b, p2v pos)
where p2v (x,y) = Vector (unsafeCoerce x) (unsafeCoerce y)
clickBall :: Space -> MVar (Maybe (Body, Vector)) -> MouseButton -> Position
-> IO ()
clickBall space mv _ (Position pos) = do
v <- takeMVar mv
case v of
Nothing -> do
shs <- spaceQueryList space (p2v pos) (-1) 0
if null shs
then putMVar mv Nothing
else do
let b = body (head shs)
putMVar mv (Just (b, p2v pos))
Just _ -> putMVar mv Nothing
where p2v (x,y) = Vector (unsafeCoerce x) (unsafeCoerce y)
circle :: (CpFloat, CpFloat) -> CpFloat -> Color3 GLdouble -> IO ()
circle (x,y) r c = preservingMatrix $ do
let poly = 24
ang p = p * 2 * pi / poly
pos = map (\p -> (x+cos(ang p)*r, y + sin(ang p)*r)) [1,2..poly]
color c
renderPrimitive Graphics.UI.GLUT.Polygon $
mapM_ (toVertex . conv) pos
color $ Color3 0 0 (0 :: GLdouble)
renderPrimitive Graphics.UI.GLUT.LineLoop $
mapM_ (toVertex . conv) pos
where conv :: (CpFloat, CpFloat) -> (GLdouble, GLdouble)
conv (a,b) = (unsafeCoerce a, unsafeCoerce b)
Returns the point in coordinates .
randomPoint :: (Double, Double) -> IO (CpFloat, CpFloat)
randomPoint (l, r) = do
Double = = CpFloat in .
x1 <- unsafeCoerce `liftM` (randomRIO (l, r) :: IO Double)
x2 <- unsafeCoerce `liftM` (randomRIO (l, r) :: IO Double)
return (x1, x2)
randomColor :: IO (Color3 GLdouble)
randomColor = do
c1 <- rndC
c2 <- rndC
c3 <- rndC
return (Color3 c1 c2 c3)
where rndC :: IO GLdouble
rndC = unsafeCoerce `liftM` (randomRIO (0, 1) :: IO Double)
drawHelp :: IO ()
drawHelp = do
color $ Color3 0 0 (0 :: GLdouble)
text (0.9, 0.97) [
"Keys:"
, "b Spawn 10 balls"
, "v Spawn 1 big ball"
, "Arrows Gravity direction"
, "c clear box"
, "f Toggle FPS graph"
, "Escape Quit"
, ""
, "Drag'n'Drop possible." ]
|
9ab7a46bdbff0bcfef83dbd8a748d13fd2c36205df3097b4b2c3c62277ccd33b | kaznum/programming_in_ocaml_exercise | gui.ml | open Tk
open MySupport
open Board
let c_height = 1
let c_width = 2
let defcol = `White
let pushcol = `Blue
let selcol = `Color "#ffdfdf"
let color_of_state = function
Pressed -> pushcol
| NotPressed -> defcol
let relief_of_state = function
Pressed -> `Sunken
| NotPressed -> `Ridge
let toggle = function
Pressed -> NotPressed
| NotPressed -> Pressed
let rec string_of_spec sep = function
[] -> ""
| [i] -> string_of_int i
| i::rest -> (string_of_int i) ^ sep ^ string_of_spec sep rest
(* 操作 *)
let focus label _ = Label.configure label ~background:selcol
let unfocus label st _ =
Label.configure label ~background:(color_of_state !st)
let pressed label st _ =
st := toggle !st;
Label.configure label ~relief:(relief_of_state !st) ~background:(color_of_state !st)
1マスをクリア
let clear label st _ =
st := NotPressed;
Label.configure label
~relief:(relief_of_state !st)
~background:(color_of_state NotPressed)
(* 全マスをクリア *)
let clear_all cells states =
List.iter2
(fun (_::c_row) st_row ->
List.iter2 (fun c_row st_row -> clear c_row st_row ()) c_row st_row) cells states
(* quit *)
let quit () = closeTk(); exit 0
(* 正誤をlabelに表示 *)
let check h_spec v_spec body label () =
if is_solved h_spec v_spec body
then Label.configure label ~text:"正解!" ~foreground:`Red
else Label.configure label ~text:"残念..." ~foreground:`Blue
(* widget作成 *)
(* 1行を作成 *)
let rec make_cells ?(width=c_width) ?(height=c_height) parent = function
[] -> []
| c::rest ->
let label =
Label.create parent ~width ~height ~relief:`Ridge
~background:(color_of_state !c) in
bind ~events:[`Enter] ~action:(focus label) label;
bind ~events:[`Leave] ~action:(unfocus label c) label;
bind ~events:[`ButtonPress] ~action:(pressed label c) label;
label :: make_cells ~width ~height parent rest
(* 縦方向のラベルのリスト *)
let make_vspec ?(spwidth=c_width) ~spheight speclist parent =
List.map
(fun s ->
Label.create parent ~width:spwidth ~height:spheight ~text:s ~anchor:`S ~relief:`Groove)
(List.map (string_of_spec "\n") speclist)
(* 横方向のラベルとマス目のリスト *)
let make_row ~spwidth ?(height=c_height) ?(width=c_width) spec parent cell_list =
let s = string_of_spec " " spec in
Label.create parent ~width:spwidth ~height ~text:s ~anchor:`E ~relief:`Groove :: (make_cells ~height ~width parent cell_list)
let make_board { width=width;
height=height;
h_spec=h_spec;
v_spec=v_spec;
body=body} b_clear b_check parent =
(* 幅と高さの計算 *)
let spwidth = max (max_list (List.map List.length h_spec) * 2) 10 in
let spheight = max (max_list (List.map List.length v_spec)) 4 in
let f1 = Frame.create parent in
let corner = Label.create ~width:spwidth ~height:spheight f1 in
let reset_corner _ =
Label.configure corner
~relief:`Raised ~text:"お絵かき\nロジック" ~foreground:`Black in
reset_corner ();
bind ~events:[`ButtonPress] ~action:reset_corner corner;
Button.configure b_check ~command:(check h_spec v_spec body corner);
let row0 = corner::make_vspec v_spec ~spheight f1 in
pack row0 ~side:`Left ~anchor:`S;
let frame_rows = make_list height (fun () -> Frame.create parent) in
pack (f1 :: frame_rows) ~side:`Top;
let rows = map3 (make_row ~spwidth) h_spec frame_rows body in
List.iter (pack ~side:`Left) rows;
Button.configure b_clear ~command:(fun () -> clear_all rows body)
(* main *)
let () =
if Array.length Sys.argv = 1 then failwith "Usage: ilogic filename"
else
begin
let top = openTk() in
let fr_board = Frame.create top in
let fr_buttons = Frame.create top in
pack [fr_board; fr_buttons] ~side:`Left ~fill:`Y;
let b_check = Button.create ~text:"解答チェック" fr_buttons in
let b_clear = Button.create ~text:"やり直し" fr_buttons in
let b_quit = Button.create ~text:"終了" ~command:quit fr_buttons in
pack [b_check; b_clear; b_quit] ~side:`Top ~fill:`X;
let board = Input.input_board (Sys.argv.(1)) in
make_board board b_clear b_check fr_board;
Wm.title_set top "お絵かきロジック";
mainLoop()
end
| null | https://raw.githubusercontent.com/kaznum/programming_in_ocaml_exercise/6f6a5d62a7a87a1c93561db88f08ae4e445b7d4e/ch16/gui.ml | ocaml | 操作
全マスをクリア
quit
正誤をlabelに表示
widget作成
1行を作成
縦方向のラベルのリスト
横方向のラベルとマス目のリスト
幅と高さの計算
main | open Tk
open MySupport
open Board
let c_height = 1
let c_width = 2
let defcol = `White
let pushcol = `Blue
let selcol = `Color "#ffdfdf"
let color_of_state = function
Pressed -> pushcol
| NotPressed -> defcol
let relief_of_state = function
Pressed -> `Sunken
| NotPressed -> `Ridge
let toggle = function
Pressed -> NotPressed
| NotPressed -> Pressed
let rec string_of_spec sep = function
[] -> ""
| [i] -> string_of_int i
| i::rest -> (string_of_int i) ^ sep ^ string_of_spec sep rest
let focus label _ = Label.configure label ~background:selcol
let unfocus label st _ =
Label.configure label ~background:(color_of_state !st)
let pressed label st _ =
st := toggle !st;
Label.configure label ~relief:(relief_of_state !st) ~background:(color_of_state !st)
1マスをクリア
let clear label st _ =
st := NotPressed;
Label.configure label
~relief:(relief_of_state !st)
~background:(color_of_state NotPressed)
let clear_all cells states =
List.iter2
(fun (_::c_row) st_row ->
List.iter2 (fun c_row st_row -> clear c_row st_row ()) c_row st_row) cells states
let quit () = closeTk(); exit 0
let check h_spec v_spec body label () =
if is_solved h_spec v_spec body
then Label.configure label ~text:"正解!" ~foreground:`Red
else Label.configure label ~text:"残念..." ~foreground:`Blue
let rec make_cells ?(width=c_width) ?(height=c_height) parent = function
[] -> []
| c::rest ->
let label =
Label.create parent ~width ~height ~relief:`Ridge
~background:(color_of_state !c) in
bind ~events:[`Enter] ~action:(focus label) label;
bind ~events:[`Leave] ~action:(unfocus label c) label;
bind ~events:[`ButtonPress] ~action:(pressed label c) label;
label :: make_cells ~width ~height parent rest
let make_vspec ?(spwidth=c_width) ~spheight speclist parent =
List.map
(fun s ->
Label.create parent ~width:spwidth ~height:spheight ~text:s ~anchor:`S ~relief:`Groove)
(List.map (string_of_spec "\n") speclist)
let make_row ~spwidth ?(height=c_height) ?(width=c_width) spec parent cell_list =
let s = string_of_spec " " spec in
Label.create parent ~width:spwidth ~height ~text:s ~anchor:`E ~relief:`Groove :: (make_cells ~height ~width parent cell_list)
let make_board { width=width;
height=height;
h_spec=h_spec;
v_spec=v_spec;
body=body} b_clear b_check parent =
let spwidth = max (max_list (List.map List.length h_spec) * 2) 10 in
let spheight = max (max_list (List.map List.length v_spec)) 4 in
let f1 = Frame.create parent in
let corner = Label.create ~width:spwidth ~height:spheight f1 in
let reset_corner _ =
Label.configure corner
~relief:`Raised ~text:"お絵かき\nロジック" ~foreground:`Black in
reset_corner ();
bind ~events:[`ButtonPress] ~action:reset_corner corner;
Button.configure b_check ~command:(check h_spec v_spec body corner);
let row0 = corner::make_vspec v_spec ~spheight f1 in
pack row0 ~side:`Left ~anchor:`S;
let frame_rows = make_list height (fun () -> Frame.create parent) in
pack (f1 :: frame_rows) ~side:`Top;
let rows = map3 (make_row ~spwidth) h_spec frame_rows body in
List.iter (pack ~side:`Left) rows;
Button.configure b_clear ~command:(fun () -> clear_all rows body)
let () =
if Array.length Sys.argv = 1 then failwith "Usage: ilogic filename"
else
begin
let top = openTk() in
let fr_board = Frame.create top in
let fr_buttons = Frame.create top in
pack [fr_board; fr_buttons] ~side:`Left ~fill:`Y;
let b_check = Button.create ~text:"解答チェック" fr_buttons in
let b_clear = Button.create ~text:"やり直し" fr_buttons in
let b_quit = Button.create ~text:"終了" ~command:quit fr_buttons in
pack [b_check; b_clear; b_quit] ~side:`Top ~fill:`X;
let board = Input.input_board (Sys.argv.(1)) in
make_board board b_clear b_check fr_board;
Wm.title_set top "お絵かきロジック";
mainLoop()
end
|
a18dce8d73b5ab3ea7bb6627816e957eba8354a71e04bb6ccc53b44ad4660f0f | zwizwa/staapl | piklab.rkt | #lang racket/base
(require (lib "process.rkt")) ;; system
Interface to piklab - prog
(provide (all-defined-out))
(define piklab-firmware (make-parameter "/home/tom/firmware/icd2"))
(define piklab-device (make-parameter "18F1220"))
(define piklab-port (make-parameter "usb"))
(define piklab-self-powered (make-parameter "false"))
(define piklab-misc (make-parameter "-p icd2 --quiet")) ;; --debug
(define (piklab-prog-cmd command-string)
(let ((cmd
(format "piklab-prog ~a -t ~a --target-self-powered ~a --firmware-dir ~a -d ~a ~a"
(piklab-misc)
(piklab-port)
(piklab-self-powered)
(piklab-firmware)
(piklab-device)
command-string)))
(display cmd) (newline)
(void
(or (system cmd)
(error 'piklab-prog-error)))))
(define (piklab-prog-program filename)
(piklab-prog-cmd (format "-c program ~a" filename)))
(define (piklab-prog-run)
(piklab-prog-cmd "-c run"))
(define (piklab-prog filename)
(piklab-prog-program filename)
(piklab-prog-run)) | null | https://raw.githubusercontent.com/zwizwa/staapl/e30e6ae6ac45de7141b97ad3cebf9b5a51bcda52/port/piklab.rkt | racket | system
--debug | #lang racket/base
Interface to piklab - prog
(provide (all-defined-out))
(define piklab-firmware (make-parameter "/home/tom/firmware/icd2"))
(define piklab-device (make-parameter "18F1220"))
(define piklab-port (make-parameter "usb"))
(define piklab-self-powered (make-parameter "false"))
(define (piklab-prog-cmd command-string)
(let ((cmd
(format "piklab-prog ~a -t ~a --target-self-powered ~a --firmware-dir ~a -d ~a ~a"
(piklab-misc)
(piklab-port)
(piklab-self-powered)
(piklab-firmware)
(piklab-device)
command-string)))
(display cmd) (newline)
(void
(or (system cmd)
(error 'piklab-prog-error)))))
(define (piklab-prog-program filename)
(piklab-prog-cmd (format "-c program ~a" filename)))
(define (piklab-prog-run)
(piklab-prog-cmd "-c run"))
(define (piklab-prog filename)
(piklab-prog-program filename)
(piklab-prog-run)) |
ba32291a0f38ff0f04ae9b57eb29f71e5034695bf3103362dbc1973832db65fd | rorra/rorracasts_erlang | dynamic.erl | -module(dynamic).
-behaviour(supervisor).
%% API
-export([start_link/0, add_child/1, remove_child/1]).
%% Supervisor callbacks
-export([init/1]).
-define(SERVER, ?MODULE).
%%%===================================================================
%%% API functions
%%%===================================================================
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
add_child(Nombre) ->
Child = #{id => Nombre,
start => {info, start_link, [Nombre]},
restart => permanent,
shutdown => 5000,
type => worker,
modules => [info]},
supervisor:start_child(?SERVER, Child).
remove_child(Nombre) ->
supervisor:terminate_child(?SERVER, Nombre),
supervisor:delete_child(?SERVER, Nombre).
%%%===================================================================
%%% Supervisor callbacks
%%%===================================================================
init([]) ->
SupFlags = #{strategy => one_for_one,
intensity => 1,
period => 5},
AChild = #{id => marcos,
start => {info, start_link, [marcos]},
restart => permanent,
shutdown => 5000,
type => worker,
modules => [info]},
BChild = #{id => juan,
start => {info, start_link, [juan]},
restart => temporary,
shutdown => 5000,
type => worker,
modules => [info]},
CChild = #{id => pedro,
start => {info, start_link, [pedro]},
restart => transient,
shutdown => 5000,
type => worker,
modules => [info]},
{ok, {SupFlags, [AChild, BChild, CChild]}}.
%%%===================================================================
Internal functions
%%%===================================================================
| null | https://raw.githubusercontent.com/rorra/rorracasts_erlang/399b88475b69a21e7e17f72089d38b917a4eb01b/028-otp-application/src/dynamic.erl | erlang | API
Supervisor callbacks
===================================================================
API functions
===================================================================
===================================================================
Supervisor callbacks
===================================================================
===================================================================
=================================================================== | -module(dynamic).
-behaviour(supervisor).
-export([start_link/0, add_child/1, remove_child/1]).
-export([init/1]).
-define(SERVER, ?MODULE).
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
add_child(Nombre) ->
Child = #{id => Nombre,
start => {info, start_link, [Nombre]},
restart => permanent,
shutdown => 5000,
type => worker,
modules => [info]},
supervisor:start_child(?SERVER, Child).
remove_child(Nombre) ->
supervisor:terminate_child(?SERVER, Nombre),
supervisor:delete_child(?SERVER, Nombre).
init([]) ->
SupFlags = #{strategy => one_for_one,
intensity => 1,
period => 5},
AChild = #{id => marcos,
start => {info, start_link, [marcos]},
restart => permanent,
shutdown => 5000,
type => worker,
modules => [info]},
BChild = #{id => juan,
start => {info, start_link, [juan]},
restart => temporary,
shutdown => 5000,
type => worker,
modules => [info]},
CChild = #{id => pedro,
start => {info, start_link, [pedro]},
restart => transient,
shutdown => 5000,
type => worker,
modules => [info]},
{ok, {SupFlags, [AChild, BChild, CChild]}}.
Internal functions
|
936864dfcbc94f173a7f314b3e37a0507fbda89cf6dee033119915865ff44f87 | borkdude/jet | patches.clj | (ns jet.patches
"Don't load this namespace unless you're building a native image."
(:require [com.rpl.specter.impl]
[jet.specter :as js]))
;; (alter-var-root #'eval (constantly nil))
;; (alter-var-root #'require (constantly nil))
;; (alter-var-root #'resolve (constantly nil))
;; (alter-var-root #'requiring-resolve (constantly nil))
;; Note, when using direct linking we need to patch more vars than this
(alter-var-root #'com.rpl.specter.impl/closed-code (constantly js/closed-code))
(println "Patches applied")
| null | https://raw.githubusercontent.com/borkdude/jet/9bad90e1d9e0714b5c842cbb1247f716b98d4431/src/jet/patches.clj | clojure | (alter-var-root #'eval (constantly nil))
(alter-var-root #'require (constantly nil))
(alter-var-root #'resolve (constantly nil))
(alter-var-root #'requiring-resolve (constantly nil))
Note, when using direct linking we need to patch more vars than this | (ns jet.patches
"Don't load this namespace unless you're building a native image."
(:require [com.rpl.specter.impl]
[jet.specter :as js]))
(alter-var-root #'com.rpl.specter.impl/closed-code (constantly js/closed-code))
(println "Patches applied")
|
b84500117ed257590c63afd5017a0fbe8bd2848bf00dba7cef5332938713af04 | erlangonrails/devdb | exmpp_client_muc.erl | Copyright ProcessOne 2006 - 2010 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
@author >
@doc Helper functions for generating MUC related stanzas .
%% Very incomplete, now it only generates kick and ban stanzas.
-module(exmpp_client_muc).
-include("exmpp.hrl").
-export([kick/2,
kick/3,
kick/4,
ban/2,
ban/3,
ban/4,
get_banlist/1,
get_banlist/2,
update_banlist/2,
update_banlist/3
]).
-type(ban_item() :: {exmpp_jid:jid(), outcast | none | binary()} | {exmpp_jid:jid(), outcast | none | binary(), binary() | string()}).
-spec kick(Room :: exmpp_jid:jid(), Nick :: string() | binary()) -> #xmlel{}.
kick(Room, Nick) ->
kick(?NS_JABBER_CLIENT, Room, Nick).
-spec kick(NS :: atom() | string(), Room :: exmpp_jid:jid(), Nick :: string() | binary()) -> #xmlel{}.
kick(NS, Room, Nick) ->
kick(NS, Room, Nick, <<>>).
-spec kick(NS :: atom() | string(), Room :: exmpp_jid:jid(), Nick :: string() | binary(), Reason :: string() | binary()) -> #xmlel{}.
kick(NS, Room, Nick, Reason) ->
exmpp_stanza:set_recipient(
exmpp_iq:set(NS,
exmpp_xml:element(?NS_MUC_ADMIN, 'query', [],
[exmpp_xml:element(?NS_MUC_ADMIN, 'item', [?XMLATTR('nick', Nick), ?XMLATTR('role', <<"none">>)],
[exmpp_xml:element(?NS_MUC_ADMIN, 'reason', [], [?XMLCDATA(Reason)])])])), Room).
-spec ban(Room :: exmpp_jid:jid(), JID :: exmpp_jid:jid() ) -> #xmlel{}.
ban(Room, JID) ->
ban(?NS_JABBER_CLIENT, Room, JID).
-spec ban(NS :: atom() | string(), Room :: exmpp_jid:jid(), JID :: exmpp_jid:jid()) -> #xmlel{}.
ban(NS, Room, JID) ->
ban(NS, Room, JID, <<>>).
-spec ban(NS :: atom() | string(), Room :: exmpp_jid:jid(), JID :: exmpp_jid:jid(), Reason :: string() | binary()) -> #xmlel{}.
ban(NS, Room, JID, Reason) ->
update_banlist(NS, Room, [{JID, outcast, Reason}]).
-spec get_banlist(Room :: exmpp_jid:jid()) -> #xmlel{}.
get_banlist(Room) ->
get_banlist(?NS_JABBER_CLIENT, Room).
-spec get_banlist(NS :: atom() | string(), Room :: exmpp_jid:jid()) -> #xmlel{}.
get_banlist(NS, Room) ->
exmpp_stanza:set_recipient(
exmpp_iq:get(NS,
exmpp_xml:element(?NS_MUC_ADMIN, 'query', [],
[exmpp_xml:element(?NS_MUC_ADMIN, 'item', [?XMLATTR('affiliation', <<"outcast">>)], [])])), Room ).
-spec update_banlist(Room :: exmpp_jid:jid(), BanList :: [ban_item()]) -> #xmlel{}.
update_banlist(Room, BanList) ->
update_banlist(?NS_JABBER_CLIENT, Room, BanList).
-spec update_banlist(NS :: atom() | string(), Room :: exmpp_jid:jid(), BanList :: [ban_item()]) -> #xmlel{}.
update_banlist(NS, Room, BanList) ->
exmpp_stanza:set_recipient(
exmpp_iq:set(NS,
exmpp_xml:element(?NS_MUC_ADMIN, 'query', [], [ban_to_item(Ban) || Ban <- BanList])), Room).
ban_to_item({JID, Affiliation}) ->
ban_to_item({JID, Affiliation, <<>>});
ban_to_item({JID, Affiliation, Reason}) ->
exmpp_xml:element(?NS_MUC_ADMIN, 'item', [?XMLATTR('jid', exmpp_jid:to_binary(JID)), ?XMLATTR('affiliation', affiliation_to_binary(Affiliation))],
[exmpp_xml:element(?NS_MUC_ADMIN, 'reason', [], [?XMLCDATA(Reason)])]).
affiliation_to_binary(outcast) -> <<"outcast">>;
affiliation_to_binary(none) -> <<"none">>;
affiliation_to_binary(A) when is_binary(A) -> A.
| null | https://raw.githubusercontent.com/erlangonrails/devdb/0e7eaa6bd810ec3892bfc3d933439560620d0941/dev/exmpp-0.9.5/src/client/exmpp_client_muc.erl | erlang |
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
Very incomplete, now it only generates kick and ban stanzas. | Copyright ProcessOne 2006 - 2010 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
@author >
@doc Helper functions for generating MUC related stanzas .
-module(exmpp_client_muc).
-include("exmpp.hrl").
-export([kick/2,
kick/3,
kick/4,
ban/2,
ban/3,
ban/4,
get_banlist/1,
get_banlist/2,
update_banlist/2,
update_banlist/3
]).
-type(ban_item() :: {exmpp_jid:jid(), outcast | none | binary()} | {exmpp_jid:jid(), outcast | none | binary(), binary() | string()}).
-spec kick(Room :: exmpp_jid:jid(), Nick :: string() | binary()) -> #xmlel{}.
kick(Room, Nick) ->
kick(?NS_JABBER_CLIENT, Room, Nick).
-spec kick(NS :: atom() | string(), Room :: exmpp_jid:jid(), Nick :: string() | binary()) -> #xmlel{}.
kick(NS, Room, Nick) ->
kick(NS, Room, Nick, <<>>).
-spec kick(NS :: atom() | string(), Room :: exmpp_jid:jid(), Nick :: string() | binary(), Reason :: string() | binary()) -> #xmlel{}.
kick(NS, Room, Nick, Reason) ->
exmpp_stanza:set_recipient(
exmpp_iq:set(NS,
exmpp_xml:element(?NS_MUC_ADMIN, 'query', [],
[exmpp_xml:element(?NS_MUC_ADMIN, 'item', [?XMLATTR('nick', Nick), ?XMLATTR('role', <<"none">>)],
[exmpp_xml:element(?NS_MUC_ADMIN, 'reason', [], [?XMLCDATA(Reason)])])])), Room).
-spec ban(Room :: exmpp_jid:jid(), JID :: exmpp_jid:jid() ) -> #xmlel{}.
ban(Room, JID) ->
ban(?NS_JABBER_CLIENT, Room, JID).
-spec ban(NS :: atom() | string(), Room :: exmpp_jid:jid(), JID :: exmpp_jid:jid()) -> #xmlel{}.
ban(NS, Room, JID) ->
ban(NS, Room, JID, <<>>).
-spec ban(NS :: atom() | string(), Room :: exmpp_jid:jid(), JID :: exmpp_jid:jid(), Reason :: string() | binary()) -> #xmlel{}.
ban(NS, Room, JID, Reason) ->
update_banlist(NS, Room, [{JID, outcast, Reason}]).
-spec get_banlist(Room :: exmpp_jid:jid()) -> #xmlel{}.
get_banlist(Room) ->
get_banlist(?NS_JABBER_CLIENT, Room).
-spec get_banlist(NS :: atom() | string(), Room :: exmpp_jid:jid()) -> #xmlel{}.
get_banlist(NS, Room) ->
exmpp_stanza:set_recipient(
exmpp_iq:get(NS,
exmpp_xml:element(?NS_MUC_ADMIN, 'query', [],
[exmpp_xml:element(?NS_MUC_ADMIN, 'item', [?XMLATTR('affiliation', <<"outcast">>)], [])])), Room ).
-spec update_banlist(Room :: exmpp_jid:jid(), BanList :: [ban_item()]) -> #xmlel{}.
update_banlist(Room, BanList) ->
update_banlist(?NS_JABBER_CLIENT, Room, BanList).
-spec update_banlist(NS :: atom() | string(), Room :: exmpp_jid:jid(), BanList :: [ban_item()]) -> #xmlel{}.
update_banlist(NS, Room, BanList) ->
exmpp_stanza:set_recipient(
exmpp_iq:set(NS,
exmpp_xml:element(?NS_MUC_ADMIN, 'query', [], [ban_to_item(Ban) || Ban <- BanList])), Room).
ban_to_item({JID, Affiliation}) ->
ban_to_item({JID, Affiliation, <<>>});
ban_to_item({JID, Affiliation, Reason}) ->
exmpp_xml:element(?NS_MUC_ADMIN, 'item', [?XMLATTR('jid', exmpp_jid:to_binary(JID)), ?XMLATTR('affiliation', affiliation_to_binary(Affiliation))],
[exmpp_xml:element(?NS_MUC_ADMIN, 'reason', [], [?XMLCDATA(Reason)])]).
affiliation_to_binary(outcast) -> <<"outcast">>;
affiliation_to_binary(none) -> <<"none">>;
affiliation_to_binary(A) when is_binary(A) -> A.
|
fd7d94b3ce3c0071baff8be549f1db9d62a02a14e15c86a05c5a9f2bdbfa6530 | rudymatela/express | show.hs | Copyright ( c ) 2017 - 2021 .
-- Distributed under the 3-Clause BSD licence (see the file LICENSE).
import Test
import Data.Express.Utils.List
main :: IO ()
main = mainTest tests 5040
tests :: Int -> [Bool]
tests n =
[ True
-- showing expressions
, show zero == "0 :: Int"
, show two == "2 :: Int"
, show minusOne == "-1 :: Int"
, show (one -+- two -*- three) == "1 + 2 * 3 :: Int"
, show ((one -+- two) -*- three) == "(1 + 2) * 3 :: Int"
, show plus == "(+) :: Int -> Int -> Int"
, show times == "(*) :: Int -> Int -> Int"
, show (plus :$ one) == "(1 +) :: Int -> Int"
, show (times :$ (minusOne -+- two)) == "(((-1) + 2) *) :: Int -> Int"
, show ffE == "f :: Int -> Int"
, show (ff xx) == "f x :: Int"
, show (var "f" (undefined :: Int -> Int -> Int)) == "f :: Int -> Int -> Int"
, show (var "f" (undefined :: Int -> Int -> Int) :$ one) == "f 1 :: Int -> Int"
, show (var "f" (undefined :: Int -> Int -> Int) :$ one :$ two) == "f 1 2 :: Int"
, show (var "`f`" (undefined :: Int -> Int -> Int)) == "f :: Int -> Int -> Int"
, show (var "`f`" (undefined :: Int -> Int -> Int) :$ one) == "(1 `f`) :: Int -> Int"
, show (var "`f`" (undefined :: Int -> Int -> Int) :$ one :$ two) == "1 `f` 2 :: Int"
, show (one -?- two) == "1 ? 2 :: Int"
, show (value "`compare`" (compare :: Int->Int->Ordering) :$ one) == "(1 `compare`) :: Int -> Ordering"
, show (value "`compare`" (compare :: Int->Int->Ordering) :$ one :$ two) == "1 `compare` 2 :: Ordering"
, holds n $ show . mapVars (\(Value ('_':s) d) -> Value (if null s then "_" else s) d) === show
, show emptyString == "\"\" :: [Char]"
, show (space -:- emptyString) == "\" \" :: [Char]"
, show (space -:- ccs) == "' ':cs :: [Char]"
, show (ae -:- bee -:- emptyString) == "\"ab\" :: [Char]"
, show (ae -:- bee -:- ccs) == "'a':'b':cs :: [Char]"
, show (ae -:- space -:- bee -:- lineBreak -:- emptyString) == "\"a b\\n\" :: [Char]"
, show (cc -:- space -:- dd -:- lineBreak -:- emptyString) == "c:' ':d:\"\\n\" :: [Char]"
, show (cc -:- space -:- dd -:- lineBreak -:- ccs) == "c:' ':d:'\\n':cs :: [Char]"
, show (cc -:- ae -:- bee -:- emptyString) == "c:\"ab\" :: [Char]"
, show (cc -:- ae -:- bee -:- space -:- ae -:- bee -:- emptyString) == "c:\"ab ab\" :: [Char]"
, show one == "1 :: Int"
, show (minusOne) == "-1 :: Int"
, show (one -+- one) == "1 + 1 :: Int"
, show (minusOne -+- minusOne) == "(-1) + (-1) :: Int"
, show (zero -|- one) == "(0,1) :: (Int,Int)"
, show (minusOne -|- minusOne) == "(-1,-1) :: (Int,Int)"
, show (triple zero one two) == "(0,1,2) :: (Int,Int,Int)"
, show (quadruple minusOne zero one two) == "(-1,0,1,2) :: (Int,Int,Int,Int)"
, show (quintuple minusOne zero one two three) == "(-1,0,1,2,3) :: (Int,Int,Int,Int,Int)"
, show (sixtuple minusTwo minusOne zero one two three) == "(-2,-1,0,1,2,3) :: (Int,Int,Int,Int,Int,Int)"
, show (one -:- nil) == "[1] :: [Int]"
, show (zero -:- one -:- nil) == "[0,1] :: [Int]"
, show (minusOne -:- nil) == "[-1] :: [Int]"
, show (minusOne -:- minusTwo -:- nil) == "[-1,-2] :: [Int]"
, show (xx -:- minusTwo -:- yy -:- nil) == "[x,-2,y] :: [Int]"
, show (xx -:- minusTwo -:- yy -:- xxs) == "x:(-2):y:xs :: [Int]"
, show (ffE -$- zero) == "f $ 0 :: Int"
, show (ggE -$- xx) == "g $ x :: Int"
, show (ffE -$- minusOne) == "f $ (-1) :: Int"
, holds n $ \e -> showExpr e `isPrefixOf` show e
, show (if' pp xx yy) == "(if p then x else y) :: Int"
, show (if' false zero one) == "(if False then 0 else 1) :: Int"
, show (if' true two three) == "(if True then 2 else 3) :: Int"
, show (if' pp false true) == "(if p then False else True) :: Bool"
, show (not' (if' pp false true)) == "not (if p then False else True) :: Bool"
, show (if' pp xx yy -*- zz) == "(if p then x else y) * z :: Int"
, show (zz -*- if' pp xx yy) == "z * (if p then x else y) :: Int"
, show (if' pp false true -||- if' qq true false)
== "(if p then False else True) || (if q then True else False) :: Bool"
, show (if' (null' xxs) zero (head' xxs -+- value "sum" (sum :: [Int] -> Int) :$ tail' xxs))
== "(if null xs then 0 else head xs + sum (tail xs)) :: Int"
, show (if' (xx -<- yy) (ff xx) (yy -*- zz)) == "(if x < y then f x else y * z) :: Int"
, show (caseBool pp xx yy) == "(case p of False -> x; True -> y) :: Int"
, show (caseBool false zero one) == "(case False of False -> 0; True -> 1) :: Int"
, show (caseBool true two three) == "(case True of False -> 2; True -> 3) :: Int"
, show (caseBool pp false true) == "(case p of False -> False; True -> True) :: Bool"
, show (not' (caseBool pp false true)) == "not (case p of False -> False; True -> True) :: Bool"
, show (caseBool pp xx yy -*- zz) == "(case p of False -> x; True -> y) * z :: Int"
, show (zz -*- caseBool pp xx yy) == "z * (case p of False -> x; True -> y) :: Int"
, showExpr (if' pp xx yy) == "if p then x else y"
, showExpr (if' false zero one) == "if False then 0 else 1"
, showExpr (if' true two three) == "if True then 2 else 3"
, showExpr (if' pp false true) == "if p then False else True"
, showExpr (if' (xx -<- yy) (ff xx) (yy -*- zz)) == "if x < y then f x else y * z"
, showExpr (caseBool pp xx yy) == "case p of False -> x; True -> y"
, showExpr (caseBool false zero one) == "case False of False -> 0; True -> 1"
, showExpr (caseBool true two three) == "case True of False -> 2; True -> 3"
, showExpr (caseBool pp false true) == "case p of False -> False; True -> True"
, showExpr (caseBool pp true false) == "case p of False -> True; True -> False"
, show (caseOrdering (compare' xx yy) xx zz yy) == "(case compare x y of LT -> x; EQ -> z; GT -> y) :: Int"
, show (caseOrdering (val LT) zero one two) == "(case LT of LT -> 0; EQ -> 1; GT -> 2) :: Int"
, show (caseOrdering (val GT) three four five) == "(case GT of LT -> 3; EQ -> 4; GT -> 5) :: Int"
, show (caseOrdering (compare' xx yy) (ff xx) zz (yy -+- zz)) == "(case compare x y of LT -> f x; EQ -> z; GT -> y + z) :: Int"
, showExpr (caseOrdering (compare' xx yy) xx zz yy) == "case compare x y of LT -> x; EQ -> z; GT -> y"
, showExpr (caseOrdering (val LT) zero one two) == "case LT of LT -> 0; EQ -> 1; GT -> 2"
, showExpr (caseOrdering (val GT) three four five) == "case GT of LT -> 3; EQ -> 4; GT -> 5"
, showExpr (caseOrdering (compare' xx yy) (ff xx) zz (yy -+- zz)) == "case compare x y of LT -> f x; EQ -> z; GT -> y + z"
-- showing holes --
, show (hole (undefined :: Int -> Int) :$ one) == "_ 1 :: Int"
, show (hole (undefined :: Int -> Int) :$ xx) == "_ x :: Int"
, show (hole (undefined :: Int -> Int -> Int) :$ one :$ xx) == "_ 1 x :: Int"
, show (hole (undefined :: Int -> Int -> Int) :$ i_ :$ i_) == "_ _ _ :: Int"
-- A type --
, show (hole (undefined :: A)) == "_ :: A"
, show (val (0 :: A)) == "0 :: A"
, show (val (1 :: A)) == "1 :: A"
, show (val (2 :: A)) == "2 :: A"
, show (var "x" (undefined :: A)) == "x :: A"
, show (value "id" (id :: A -> A) :$ var "x" (undefined :: A)) == "id x :: A"
-- B type --
, show (hole (undefined :: B)) == "_ :: B"
, show (val (0 :: B)) == "0 :: B"
, show (val (1 :: B)) == "1 :: B"
, show (val (2 :: B)) == "2 :: B"
, show (var "x" (undefined :: B)) == "x :: B"
, show (value "id" (id :: B -> B) :$ var "x" (undefined :: B)) == "id x :: B"
-- [A] type --
, show (hole (undefined :: [A])) == "_ :: [A]"
, show (val ([0] :: [A])) == "[0] :: [A]"
, show (val ([3,1] :: [A])) == "[3,1] :: [A]"
, show (val ([0,1,2] :: [A])) == "[0,1,2] :: [A]"
, show (var "xs" (undefined :: [A])) == "xs :: [A]"
, show (value "id" (id :: [A] -> [A]) :$ var "xs" (undefined :: [A])) == "id xs :: [A]"
]
| null | https://raw.githubusercontent.com/rudymatela/express/d19d34b1cfd65089465d10fc8d2c7e4e6c45fa0d/test/show.hs | haskell | Distributed under the 3-Clause BSD licence (see the file LICENSE).
showing expressions
showing holes --
A type --
B type --
[A] type -- | Copyright ( c ) 2017 - 2021 .
import Test
import Data.Express.Utils.List
main :: IO ()
main = mainTest tests 5040
tests :: Int -> [Bool]
tests n =
[ True
, show zero == "0 :: Int"
, show two == "2 :: Int"
, show minusOne == "-1 :: Int"
, show (one -+- two -*- three) == "1 + 2 * 3 :: Int"
, show ((one -+- two) -*- three) == "(1 + 2) * 3 :: Int"
, show plus == "(+) :: Int -> Int -> Int"
, show times == "(*) :: Int -> Int -> Int"
, show (plus :$ one) == "(1 +) :: Int -> Int"
, show (times :$ (minusOne -+- two)) == "(((-1) + 2) *) :: Int -> Int"
, show ffE == "f :: Int -> Int"
, show (ff xx) == "f x :: Int"
, show (var "f" (undefined :: Int -> Int -> Int)) == "f :: Int -> Int -> Int"
, show (var "f" (undefined :: Int -> Int -> Int) :$ one) == "f 1 :: Int -> Int"
, show (var "f" (undefined :: Int -> Int -> Int) :$ one :$ two) == "f 1 2 :: Int"
, show (var "`f`" (undefined :: Int -> Int -> Int)) == "f :: Int -> Int -> Int"
, show (var "`f`" (undefined :: Int -> Int -> Int) :$ one) == "(1 `f`) :: Int -> Int"
, show (var "`f`" (undefined :: Int -> Int -> Int) :$ one :$ two) == "1 `f` 2 :: Int"
, show (one -?- two) == "1 ? 2 :: Int"
, show (value "`compare`" (compare :: Int->Int->Ordering) :$ one) == "(1 `compare`) :: Int -> Ordering"
, show (value "`compare`" (compare :: Int->Int->Ordering) :$ one :$ two) == "1 `compare` 2 :: Ordering"
, holds n $ show . mapVars (\(Value ('_':s) d) -> Value (if null s then "_" else s) d) === show
, show emptyString == "\"\" :: [Char]"
, show (space -:- emptyString) == "\" \" :: [Char]"
, show (space -:- ccs) == "' ':cs :: [Char]"
, show (ae -:- bee -:- emptyString) == "\"ab\" :: [Char]"
, show (ae -:- bee -:- ccs) == "'a':'b':cs :: [Char]"
, show (ae -:- space -:- bee -:- lineBreak -:- emptyString) == "\"a b\\n\" :: [Char]"
, show (cc -:- space -:- dd -:- lineBreak -:- emptyString) == "c:' ':d:\"\\n\" :: [Char]"
, show (cc -:- space -:- dd -:- lineBreak -:- ccs) == "c:' ':d:'\\n':cs :: [Char]"
, show (cc -:- ae -:- bee -:- emptyString) == "c:\"ab\" :: [Char]"
, show (cc -:- ae -:- bee -:- space -:- ae -:- bee -:- emptyString) == "c:\"ab ab\" :: [Char]"
, show one == "1 :: Int"
, show (minusOne) == "-1 :: Int"
, show (one -+- one) == "1 + 1 :: Int"
, show (minusOne -+- minusOne) == "(-1) + (-1) :: Int"
, show (zero -|- one) == "(0,1) :: (Int,Int)"
, show (minusOne -|- minusOne) == "(-1,-1) :: (Int,Int)"
, show (triple zero one two) == "(0,1,2) :: (Int,Int,Int)"
, show (quadruple minusOne zero one two) == "(-1,0,1,2) :: (Int,Int,Int,Int)"
, show (quintuple minusOne zero one two three) == "(-1,0,1,2,3) :: (Int,Int,Int,Int,Int)"
, show (sixtuple minusTwo minusOne zero one two three) == "(-2,-1,0,1,2,3) :: (Int,Int,Int,Int,Int,Int)"
, show (one -:- nil) == "[1] :: [Int]"
, show (zero -:- one -:- nil) == "[0,1] :: [Int]"
, show (minusOne -:- nil) == "[-1] :: [Int]"
, show (minusOne -:- minusTwo -:- nil) == "[-1,-2] :: [Int]"
, show (xx -:- minusTwo -:- yy -:- nil) == "[x,-2,y] :: [Int]"
, show (xx -:- minusTwo -:- yy -:- xxs) == "x:(-2):y:xs :: [Int]"
, show (ffE -$- zero) == "f $ 0 :: Int"
, show (ggE -$- xx) == "g $ x :: Int"
, show (ffE -$- minusOne) == "f $ (-1) :: Int"
, holds n $ \e -> showExpr e `isPrefixOf` show e
, show (if' pp xx yy) == "(if p then x else y) :: Int"
, show (if' false zero one) == "(if False then 0 else 1) :: Int"
, show (if' true two three) == "(if True then 2 else 3) :: Int"
, show (if' pp false true) == "(if p then False else True) :: Bool"
, show (not' (if' pp false true)) == "not (if p then False else True) :: Bool"
, show (if' pp xx yy -*- zz) == "(if p then x else y) * z :: Int"
, show (zz -*- if' pp xx yy) == "z * (if p then x else y) :: Int"
, show (if' pp false true -||- if' qq true false)
== "(if p then False else True) || (if q then True else False) :: Bool"
, show (if' (null' xxs) zero (head' xxs -+- value "sum" (sum :: [Int] -> Int) :$ tail' xxs))
== "(if null xs then 0 else head xs + sum (tail xs)) :: Int"
, show (if' (xx -<- yy) (ff xx) (yy -*- zz)) == "(if x < y then f x else y * z) :: Int"
, show (caseBool pp xx yy) == "(case p of False -> x; True -> y) :: Int"
, show (caseBool false zero one) == "(case False of False -> 0; True -> 1) :: Int"
, show (caseBool true two three) == "(case True of False -> 2; True -> 3) :: Int"
, show (caseBool pp false true) == "(case p of False -> False; True -> True) :: Bool"
, show (not' (caseBool pp false true)) == "not (case p of False -> False; True -> True) :: Bool"
, show (caseBool pp xx yy -*- zz) == "(case p of False -> x; True -> y) * z :: Int"
, show (zz -*- caseBool pp xx yy) == "z * (case p of False -> x; True -> y) :: Int"
, showExpr (if' pp xx yy) == "if p then x else y"
, showExpr (if' false zero one) == "if False then 0 else 1"
, showExpr (if' true two three) == "if True then 2 else 3"
, showExpr (if' pp false true) == "if p then False else True"
, showExpr (if' (xx -<- yy) (ff xx) (yy -*- zz)) == "if x < y then f x else y * z"
, showExpr (caseBool pp xx yy) == "case p of False -> x; True -> y"
, showExpr (caseBool false zero one) == "case False of False -> 0; True -> 1"
, showExpr (caseBool true two three) == "case True of False -> 2; True -> 3"
, showExpr (caseBool pp false true) == "case p of False -> False; True -> True"
, showExpr (caseBool pp true false) == "case p of False -> True; True -> False"
, show (caseOrdering (compare' xx yy) xx zz yy) == "(case compare x y of LT -> x; EQ -> z; GT -> y) :: Int"
, show (caseOrdering (val LT) zero one two) == "(case LT of LT -> 0; EQ -> 1; GT -> 2) :: Int"
, show (caseOrdering (val GT) three four five) == "(case GT of LT -> 3; EQ -> 4; GT -> 5) :: Int"
, show (caseOrdering (compare' xx yy) (ff xx) zz (yy -+- zz)) == "(case compare x y of LT -> f x; EQ -> z; GT -> y + z) :: Int"
, showExpr (caseOrdering (compare' xx yy) xx zz yy) == "case compare x y of LT -> x; EQ -> z; GT -> y"
, showExpr (caseOrdering (val LT) zero one two) == "case LT of LT -> 0; EQ -> 1; GT -> 2"
, showExpr (caseOrdering (val GT) three four five) == "case GT of LT -> 3; EQ -> 4; GT -> 5"
, showExpr (caseOrdering (compare' xx yy) (ff xx) zz (yy -+- zz)) == "case compare x y of LT -> f x; EQ -> z; GT -> y + z"
, show (hole (undefined :: Int -> Int) :$ one) == "_ 1 :: Int"
, show (hole (undefined :: Int -> Int) :$ xx) == "_ x :: Int"
, show (hole (undefined :: Int -> Int -> Int) :$ one :$ xx) == "_ 1 x :: Int"
, show (hole (undefined :: Int -> Int -> Int) :$ i_ :$ i_) == "_ _ _ :: Int"
, show (hole (undefined :: A)) == "_ :: A"
, show (val (0 :: A)) == "0 :: A"
, show (val (1 :: A)) == "1 :: A"
, show (val (2 :: A)) == "2 :: A"
, show (var "x" (undefined :: A)) == "x :: A"
, show (value "id" (id :: A -> A) :$ var "x" (undefined :: A)) == "id x :: A"
, show (hole (undefined :: B)) == "_ :: B"
, show (val (0 :: B)) == "0 :: B"
, show (val (1 :: B)) == "1 :: B"
, show (val (2 :: B)) == "2 :: B"
, show (var "x" (undefined :: B)) == "x :: B"
, show (value "id" (id :: B -> B) :$ var "x" (undefined :: B)) == "id x :: B"
, show (hole (undefined :: [A])) == "_ :: [A]"
, show (val ([0] :: [A])) == "[0] :: [A]"
, show (val ([3,1] :: [A])) == "[3,1] :: [A]"
, show (val ([0,1,2] :: [A])) == "[0,1,2] :: [A]"
, show (var "xs" (undefined :: [A])) == "xs :: [A]"
, show (value "id" (id :: [A] -> [A]) :$ var "xs" (undefined :: [A])) == "id xs :: [A]"
]
|
e0a7f2e2f15f3236572efdd033e4cd8575b48915d7092abd3a5a20e3a9e6229f | brendanhay/gogol | DropDatabase.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . . Projects . Instances . Databases . DropDatabase
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
Drops ( aka deletes ) a Cloud Spanner database . Completed backups for the database will be retained according to their @expire_time@. Note : Cloud Spanner might continue to accept requests for a few seconds after the database has been deleted .
--
/See:/ < / Cloud Spanner API Reference > for @spanner.projects.instances.databases.dropDatabase@.
module Gogol.Spanner.Projects.Instances.Databases.DropDatabase
( -- * Resource
SpannerProjectsInstancesDatabasesDropDatabaseResource,
-- ** Constructing a Request
SpannerProjectsInstancesDatabasesDropDatabase (..),
newSpannerProjectsInstancesDatabasesDropDatabase,
)
where
import qualified Gogol.Prelude as Core
import Gogol.Spanner.Types
-- | A resource alias for @spanner.projects.instances.databases.dropDatabase@ method which the
-- 'SpannerProjectsInstancesDatabasesDropDatabase' request conforms to.
type SpannerProjectsInstancesDatabasesDropDatabaseResource =
"v1"
Core.:> Core.Capture "database" Core.Text
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Delete '[Core.JSON] Empty
| Drops ( aka deletes ) a Cloud Spanner database . Completed backups for the database will be retained according to their @expire_time@. Note : Cloud Spanner might continue to accept requests for a few seconds after the database has been deleted .
--
-- /See:/ 'newSpannerProjectsInstancesDatabasesDropDatabase' smart constructor.
data SpannerProjectsInstancesDatabasesDropDatabase = SpannerProjectsInstancesDatabasesDropDatabase
{ -- | V1 error format.
xgafv :: (Core.Maybe Xgafv),
-- | OAuth access token.
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
-- | Required. The database to be dropped.
database :: Core.Text,
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'SpannerProjectsInstancesDatabasesDropDatabase' with the minimum fields required to make a request.
newSpannerProjectsInstancesDatabasesDropDatabase ::
-- | Required. The database to be dropped. See 'database'.
Core.Text ->
SpannerProjectsInstancesDatabasesDropDatabase
newSpannerProjectsInstancesDatabasesDropDatabase database =
SpannerProjectsInstancesDatabasesDropDatabase
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
database = database,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
SpannerProjectsInstancesDatabasesDropDatabase
where
type
Rs SpannerProjectsInstancesDatabasesDropDatabase =
Empty
type
Scopes
SpannerProjectsInstancesDatabasesDropDatabase =
'[CloudPlatform'FullControl, Spanner'Admin]
requestClient
SpannerProjectsInstancesDatabasesDropDatabase {..} =
go
database
xgafv
accessToken
callback
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
spannerService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy
SpannerProjectsInstancesDatabasesDropDatabaseResource
)
Core.mempty
| null | https://raw.githubusercontent.com/brendanhay/gogol/fffd4d98a1996d0ffd4cf64545c5e8af9c976cda/lib/services/gogol-spanner/gen/Gogol/Spanner/Projects/Instances/Databases/DropDatabase.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
* Resource
** Constructing a Request
| A resource alias for @spanner.projects.instances.databases.dropDatabase@ method which the
'SpannerProjectsInstancesDatabasesDropDatabase' request conforms to.
/See:/ 'newSpannerProjectsInstancesDatabasesDropDatabase' smart constructor.
| V1 error format.
| OAuth access token.
| Required. The database to be dropped.
| Upload protocol for media (e.g. \"raw\", \"multipart\").
| Creates a value of 'SpannerProjectsInstancesDatabasesDropDatabase' with the minimum fields required to make a request.
| Required. The database to be dropped. See 'database'. | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . . Projects . Instances . Databases . DropDatabase
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
Drops ( aka deletes ) a Cloud Spanner database . Completed backups for the database will be retained according to their @expire_time@. Note : Cloud Spanner might continue to accept requests for a few seconds after the database has been deleted .
/See:/ < / Cloud Spanner API Reference > for @spanner.projects.instances.databases.dropDatabase@.
module Gogol.Spanner.Projects.Instances.Databases.DropDatabase
SpannerProjectsInstancesDatabasesDropDatabaseResource,
SpannerProjectsInstancesDatabasesDropDatabase (..),
newSpannerProjectsInstancesDatabasesDropDatabase,
)
where
import qualified Gogol.Prelude as Core
import Gogol.Spanner.Types
type SpannerProjectsInstancesDatabasesDropDatabaseResource =
"v1"
Core.:> Core.Capture "database" Core.Text
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Delete '[Core.JSON] Empty
| Drops ( aka deletes ) a Cloud Spanner database . Completed backups for the database will be retained according to their @expire_time@. Note : Cloud Spanner might continue to accept requests for a few seconds after the database has been deleted .
data SpannerProjectsInstancesDatabasesDropDatabase = SpannerProjectsInstancesDatabasesDropDatabase
xgafv :: (Core.Maybe Xgafv),
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
database :: Core.Text,
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newSpannerProjectsInstancesDatabasesDropDatabase ::
Core.Text ->
SpannerProjectsInstancesDatabasesDropDatabase
newSpannerProjectsInstancesDatabasesDropDatabase database =
SpannerProjectsInstancesDatabasesDropDatabase
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
database = database,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
SpannerProjectsInstancesDatabasesDropDatabase
where
type
Rs SpannerProjectsInstancesDatabasesDropDatabase =
Empty
type
Scopes
SpannerProjectsInstancesDatabasesDropDatabase =
'[CloudPlatform'FullControl, Spanner'Admin]
requestClient
SpannerProjectsInstancesDatabasesDropDatabase {..} =
go
database
xgafv
accessToken
callback
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
spannerService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy
SpannerProjectsInstancesDatabasesDropDatabaseResource
)
Core.mempty
|
9ef250d6f9faaa66069a2dba0160de77bad5e49d834d2d9be29280d8793055b5 | herbelin/coq-hh | environ.ml | open Util
open Names
open Univ
open Term
open Declarations
type globals = {
env_constants : constant_body Cmap_env.t;
env_inductives : mutual_inductive_body Mindmap_env.t;
env_inductives_eq : kernel_name KNmap.t;
env_modules : module_body MPmap.t;
env_modtypes : module_type_body MPmap.t}
type stratification = {
env_universes : universes;
env_engagement : engagement option
}
type env = {
env_globals : globals;
env_named_context : named_context;
env_rel_context : rel_context;
env_stratification : stratification;
env_imports : Digest.t MPmap.t }
let empty_env = {
env_globals =
{ env_constants = Cmap_env.empty;
env_inductives = Mindmap_env.empty;
env_inductives_eq = KNmap.empty;
env_modules = MPmap.empty;
env_modtypes = MPmap.empty};
env_named_context = [];
env_rel_context = [];
env_stratification =
{ env_universes = Univ.initial_universes;
env_engagement = None};
env_imports = MPmap.empty }
let engagement env = env.env_stratification.env_engagement
let universes env = env.env_stratification.env_universes
let named_context env = env.env_named_context
let rel_context env = env.env_rel_context
let set_engagement c env =
match env.env_stratification.env_engagement with
| Some c' -> if c=c' then env else error "Incompatible engagement"
| None ->
{ env with env_stratification =
{ env.env_stratification with env_engagement = Some c } }
Digests
let add_digest env dp digest =
{ env with env_imports = MPmap.add (MPfile dp) digest env.env_imports }
let lookup_digest env dp =
MPmap.find (MPfile dp) env.env_imports
(* Rel context *)
let lookup_rel n env =
let rec lookup_rel n sign =
match n, sign with
| 1, decl :: _ -> decl
| n, _ :: sign -> lookup_rel (n-1) sign
| _, [] -> raise Not_found in
lookup_rel n env.env_rel_context
let push_rel d env =
{ env with
env_rel_context = d :: env.env_rel_context }
let push_rel_context ctxt x = fold_rel_context push_rel ctxt ~init:x
let push_rec_types (lna,typarray,_) env =
let ctxt = array_map2_i (fun i na t -> (na, None, lift i t)) lna typarray in
Array.fold_left (fun e assum -> push_rel assum e) env ctxt
(* Named context *)
let push_named d env =
if not ( env.env_rel_context = [ ] ) then raise ( ASSERT env.env_rel_context ) ;
assert ( env.env_rel_context = [ ] ) ;
assert (env.env_rel_context = []); *)
{ env with
env_named_context = d :: env.env_named_context }
let lookup_named id env =
let rec lookup_named id = function
| (id',_,_ as decl) :: _ when id=id' -> decl
| _ :: sign -> lookup_named id sign
| [] -> raise Not_found in
lookup_named id env.env_named_context
(* A local const is evaluable if it is defined *)
let named_type id env =
let (_,_,t) = lookup_named id env in t
Universe constraints
let add_constraints c env =
if c == Constraint.empty then
env
else
let s = env.env_stratification in
{ env with env_stratification =
{ s with env_universes = merge_constraints c s.env_universes } }
(* Global constants *)
let lookup_constant kn env =
Cmap_env.find kn env.env_globals.env_constants
let add_constant kn cs env =
let new_constants =
Cmap_env.add kn cs env.env_globals.env_constants in
let new_globals =
{ env.env_globals with
env_constants = new_constants } in
{ env with env_globals = new_globals }
type const_evaluation_result = NoBody | Opaque
exception NotEvaluableConst of const_evaluation_result
let constant_value env kn =
let cb = lookup_constant kn env in
if cb.const_opaque then raise (NotEvaluableConst Opaque);
match cb.const_body with
| Some l_body -> force_constr l_body
| None -> raise (NotEvaluableConst NoBody)
(* A global const is evaluable if it is defined and not opaque *)
let evaluable_constant cst env =
try let _ = constant_value env cst in true
with Not_found | NotEvaluableConst _ -> false
(* Mutual Inductives *)
let scrape_mind env kn=
try
KNmap.find kn env.env_globals.env_inductives_eq
with
Not_found -> kn
let mind_equiv env (kn1,i1) (kn2,i2) =
i1 = i2 &&
scrape_mind env (user_mind kn1) = scrape_mind env (user_mind kn2)
let lookup_mind kn env =
Mindmap_env.find kn env.env_globals.env_inductives
let add_mind kn mib env =
let new_inds = Mindmap_env.add kn mib env.env_globals.env_inductives in
let kn1,kn2 = user_mind kn,canonical_mind kn in
let new_inds_eq = if kn1=kn2 then
env.env_globals.env_inductives_eq
else
KNmap.add kn1 kn2 env.env_globals.env_inductives_eq in
let new_globals =
{ env.env_globals with
env_inductives = new_inds;
env_inductives_eq = new_inds_eq} in
{ env with env_globals = new_globals }
(* Modules *)
let add_modtype ln mtb env =
let new_modtypes = MPmap.add ln mtb env.env_globals.env_modtypes in
let new_globals =
{ env.env_globals with
env_modtypes = new_modtypes } in
{ env with env_globals = new_globals }
let shallow_add_module mp mb env =
let new_mods = MPmap.add mp mb env.env_globals.env_modules in
let new_globals =
{ env.env_globals with
env_modules = new_mods } in
{ env with env_globals = new_globals }
let lookup_module mp env =
MPmap.find mp env.env_globals.env_modules
let lookup_modtype ln env =
MPmap.find ln env.env_globals.env_modtypes
| null | https://raw.githubusercontent.com/herbelin/coq-hh/296d03d5049fea661e8bdbaf305ed4bf6d2001d2/checker/environ.ml | ocaml | Rel context
Named context
A local const is evaluable if it is defined
Global constants
A global const is evaluable if it is defined and not opaque
Mutual Inductives
Modules | open Util
open Names
open Univ
open Term
open Declarations
type globals = {
env_constants : constant_body Cmap_env.t;
env_inductives : mutual_inductive_body Mindmap_env.t;
env_inductives_eq : kernel_name KNmap.t;
env_modules : module_body MPmap.t;
env_modtypes : module_type_body MPmap.t}
type stratification = {
env_universes : universes;
env_engagement : engagement option
}
type env = {
env_globals : globals;
env_named_context : named_context;
env_rel_context : rel_context;
env_stratification : stratification;
env_imports : Digest.t MPmap.t }
let empty_env = {
env_globals =
{ env_constants = Cmap_env.empty;
env_inductives = Mindmap_env.empty;
env_inductives_eq = KNmap.empty;
env_modules = MPmap.empty;
env_modtypes = MPmap.empty};
env_named_context = [];
env_rel_context = [];
env_stratification =
{ env_universes = Univ.initial_universes;
env_engagement = None};
env_imports = MPmap.empty }
let engagement env = env.env_stratification.env_engagement
let universes env = env.env_stratification.env_universes
let named_context env = env.env_named_context
let rel_context env = env.env_rel_context
let set_engagement c env =
match env.env_stratification.env_engagement with
| Some c' -> if c=c' then env else error "Incompatible engagement"
| None ->
{ env with env_stratification =
{ env.env_stratification with env_engagement = Some c } }
Digests
let add_digest env dp digest =
{ env with env_imports = MPmap.add (MPfile dp) digest env.env_imports }
let lookup_digest env dp =
MPmap.find (MPfile dp) env.env_imports
let lookup_rel n env =
let rec lookup_rel n sign =
match n, sign with
| 1, decl :: _ -> decl
| n, _ :: sign -> lookup_rel (n-1) sign
| _, [] -> raise Not_found in
lookup_rel n env.env_rel_context
let push_rel d env =
{ env with
env_rel_context = d :: env.env_rel_context }
let push_rel_context ctxt x = fold_rel_context push_rel ctxt ~init:x
let push_rec_types (lna,typarray,_) env =
let ctxt = array_map2_i (fun i na t -> (na, None, lift i t)) lna typarray in
Array.fold_left (fun e assum -> push_rel assum e) env ctxt
let push_named d env =
if not ( env.env_rel_context = [ ] ) then raise ( ASSERT env.env_rel_context ) ;
assert ( env.env_rel_context = [ ] ) ;
assert (env.env_rel_context = []); *)
{ env with
env_named_context = d :: env.env_named_context }
let lookup_named id env =
let rec lookup_named id = function
| (id',_,_ as decl) :: _ when id=id' -> decl
| _ :: sign -> lookup_named id sign
| [] -> raise Not_found in
lookup_named id env.env_named_context
let named_type id env =
let (_,_,t) = lookup_named id env in t
Universe constraints
let add_constraints c env =
if c == Constraint.empty then
env
else
let s = env.env_stratification in
{ env with env_stratification =
{ s with env_universes = merge_constraints c s.env_universes } }
let lookup_constant kn env =
Cmap_env.find kn env.env_globals.env_constants
let add_constant kn cs env =
let new_constants =
Cmap_env.add kn cs env.env_globals.env_constants in
let new_globals =
{ env.env_globals with
env_constants = new_constants } in
{ env with env_globals = new_globals }
type const_evaluation_result = NoBody | Opaque
exception NotEvaluableConst of const_evaluation_result
let constant_value env kn =
let cb = lookup_constant kn env in
if cb.const_opaque then raise (NotEvaluableConst Opaque);
match cb.const_body with
| Some l_body -> force_constr l_body
| None -> raise (NotEvaluableConst NoBody)
let evaluable_constant cst env =
try let _ = constant_value env cst in true
with Not_found | NotEvaluableConst _ -> false
let scrape_mind env kn=
try
KNmap.find kn env.env_globals.env_inductives_eq
with
Not_found -> kn
let mind_equiv env (kn1,i1) (kn2,i2) =
i1 = i2 &&
scrape_mind env (user_mind kn1) = scrape_mind env (user_mind kn2)
let lookup_mind kn env =
Mindmap_env.find kn env.env_globals.env_inductives
let add_mind kn mib env =
let new_inds = Mindmap_env.add kn mib env.env_globals.env_inductives in
let kn1,kn2 = user_mind kn,canonical_mind kn in
let new_inds_eq = if kn1=kn2 then
env.env_globals.env_inductives_eq
else
KNmap.add kn1 kn2 env.env_globals.env_inductives_eq in
let new_globals =
{ env.env_globals with
env_inductives = new_inds;
env_inductives_eq = new_inds_eq} in
{ env with env_globals = new_globals }
let add_modtype ln mtb env =
let new_modtypes = MPmap.add ln mtb env.env_globals.env_modtypes in
let new_globals =
{ env.env_globals with
env_modtypes = new_modtypes } in
{ env with env_globals = new_globals }
let shallow_add_module mp mb env =
let new_mods = MPmap.add mp mb env.env_globals.env_modules in
let new_globals =
{ env.env_globals with
env_modules = new_mods } in
{ env with env_globals = new_globals }
let lookup_module mp env =
MPmap.find mp env.env_globals.env_modules
let lookup_modtype ln env =
MPmap.find ln env.env_globals.env_modtypes
|
475b8adecb80074ecb5f7cf65e4f2b949c5afb48364fc917530787e01d70fd53 | racket/web-server | mime-types-test.rkt | #lang racket/base
(require rackunit
(only-in mzlib/file make-temporary-file)
racket/runtime-path
racket/path
web-server/http
web-server/private/mime-types)
(provide mime-types-tests)
(define test-file (make-temporary-file))
(with-output-to-file test-file
(lambda ()
(printf #<<END
video/mp4 mp4
video/mpeg mpeg mpg mpe
END
))
#:exists 'replace)
(define default-web-root
(path-only
(collection-file-path "default-web-root/configuration-table.rkt" "web-server")))
(define mime-types-tests
(test-suite
"MIME Types"
(test-case
"Distribution mime.types parses"
(check-not-false (read-mime-types (build-path default-web-root "mime.types"))))
(test-case
"Test file parses"
(check-not-false (read-mime-types test-file)))
(test-case
"Default mime-type given"
(check-equal? ((make-path->mime-type test-file) (build-path "test.html")) #f))
(test-case
"MIME type resolves (single in file)"
(check-equal? ((make-path->mime-type test-file) (build-path "test.mp4")) #"video/mp4"))
(test-case
"MIME type resolves (multiple in file)"
(check-equal? ((make-path->mime-type test-file) (build-path "test.mpeg")) #"video/mpeg"))
(test-case
"MIME type resolves (multiple in file)"
(check-equal? ((make-path->mime-type test-file) (build-path "test.mpg")) #"video/mpeg"))
(test-case
"MIME type resolves (multiple in file)"
(check-equal? ((make-path->mime-type test-file) (build-path "test.mpe")) #"video/mpeg"))))
| null | https://raw.githubusercontent.com/racket/web-server/f718800b5b3f407f7935adf85dfa663c4bba1651/web-server-test/tests/web-server/private/mime-types-test.rkt | racket | #lang racket/base
(require rackunit
(only-in mzlib/file make-temporary-file)
racket/runtime-path
racket/path
web-server/http
web-server/private/mime-types)
(provide mime-types-tests)
(define test-file (make-temporary-file))
(with-output-to-file test-file
(lambda ()
(printf #<<END
video/mp4 mp4
video/mpeg mpeg mpg mpe
END
))
#:exists 'replace)
(define default-web-root
(path-only
(collection-file-path "default-web-root/configuration-table.rkt" "web-server")))
(define mime-types-tests
(test-suite
"MIME Types"
(test-case
"Distribution mime.types parses"
(check-not-false (read-mime-types (build-path default-web-root "mime.types"))))
(test-case
"Test file parses"
(check-not-false (read-mime-types test-file)))
(test-case
"Default mime-type given"
(check-equal? ((make-path->mime-type test-file) (build-path "test.html")) #f))
(test-case
"MIME type resolves (single in file)"
(check-equal? ((make-path->mime-type test-file) (build-path "test.mp4")) #"video/mp4"))
(test-case
"MIME type resolves (multiple in file)"
(check-equal? ((make-path->mime-type test-file) (build-path "test.mpeg")) #"video/mpeg"))
(test-case
"MIME type resolves (multiple in file)"
(check-equal? ((make-path->mime-type test-file) (build-path "test.mpg")) #"video/mpeg"))
(test-case
"MIME type resolves (multiple in file)"
(check-equal? ((make-path->mime-type test-file) (build-path "test.mpe")) #"video/mpeg"))))
| |
9d0ceb839271dc8c7ac24e309f8f81ad62d88b8a3d9f760054a8b5c27e8f2ed4 | cardmagic/lucash | netconst.scm | Magic Numbers for Networking
Copyright ( c ) 1994 by . See file COPYING .
;;; magic numbers not from header file
;;; but from man page
;;; why can't unix make up its mind
(define shutdown/receives 0)
(define shutdown/sends 1)
(define shutdown/sends+receives 2)
;;;-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
;;; BELOW THIS POINT ARE BITS FROM:
;;; <sys/socket.h>
;;; <sys/un.h>
;;; <netinet/in.h>
;;; <netinet/tcp.h>
;;; <netdb.h>
;;;-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
ADDRESS FAMILIES -- < sys / socket.h >
(define address-family/unspecified 0) ; unspecified
(define address-family/unix 1) ; local to host (pipes, portals)
internetwork : UDP , TCP , etc .
;;; SOCKET TYPES -- <sys/socket.h>
(define socket-type/stream 2) ; stream socket
(define socket-type/datagram 1) ; datagram socket
(define socket-type/raw 3) ; raw-protocol interface
( define socket - type / rdm 4 ) ; reliably - delivered message
;;(define socket-type/seqpacket 5) ; sequenced packet stream
PROTOCOL FAMILIES -- < sys / socket.h >
(define protocol-family/unspecified 0) ; unspecified
(define protocol-family/unix 1) ; local to host (pipes, portals)
internetwork : UDP , TCP , etc .
;;; Well know addresses -- <netinet/in.h>
(define internet-address/any #x00000000)
(define internet-address/loopback #x7f000001)
(define internet-address/broadcast #xffffffff) ; must be masked
;;; errors from host lookup -- <netdb.h>
(define herror/host-not-found 1) ;Authoritative Answer Host not found
(define herror/try-again 2) ;Non-Authoritive Host not found, or SERVERFAIL
Non recoverable errors , FORMERR , REFUSED , NOTIMP
(define herror/no-data 4) ;Valid name, no data record of requested type
no address , look for MX record
flags for send / recv -- < sys / socket.h >
(define message/out-of-band 1) ; process out-of-band data
(define message/peek 2) ; peek at incoming message
(define message/dont-route 4) ; send without using routing tables
protocol level for socket options -- < sys / socket.h >
(define level/socket #xffff) ; SOL_SOCKET: options for socket level
socket options -- < sys / socket.h >
(define socket/debug #x0001) ; turn on debugging info recording
(define socket/accept-connect #x0002) ; socket has had listen()
(define socket/reuse-address #x0004) ; allow local address reuse
(define socket/keep-alive #x0008) ; keep connections alive
(define socket/dont-route #x0010) ; just use interface addresses
permit sending of broadcast msgs
(define socket/use-loop-back #x0040) ; bypass hardware when possible
(define socket/linger #x0080) ; linger on close if data present
leave received OOB data in line
(define socket/reuse-port #x020) ; allow local address,port reuse
;(define socket/use-privileged #x4000) ; allocate from privileged port area
( define socket / cant - signal # x8000 ) ; prevent SIGPIPE on SS_CANTSENDMORE
(define socket/send-buffer #x1001) ; send buffer size
(define socket/receive-buffer #x1002) ; receive buffer size
(define socket/send-low-water #x1003) ; send low-water mark
(define socket/receive-low-water #x1004) ; receive low-water mark
(define socket/send-timeout #x1005) ; send timeout
(define socket/receive-timeout #x1006) ; receive timeout
(define socket/error #x1007) ; get error status and clear
(define socket/type #x1008) ; get socket type
;;; ip options -- <netinet/in.h>
(define ip/options 1) ; set/get IP per-packet options
(define ip/include-header 7) ; int; header is included with data (raw)
(define ip/type-of-service 8) ; int; ip type of service and precedence
(define ip/time-to-live 9) ; set/get IP time-to-live value
;;; tcp options -- <netinet/tcp.h>
(define tcp/no-delay #x01) ; don't delay send to coalesce packets
(define tcp/max-segment #x02) ; set maximum segment size
;;; -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
;;; OPTION SETS FOR SOCKET-OPTION AND SET-SOCKET-OPTION
Boolean Options
(define options/boolean
(list socket/debug
socket/accept-connect
socket/reuse-address
socket/keep-alive
socket/dont-route
socket/broadcast
socket/use-loop-back
socket/oob-inline
; socket/use-privileged
; socket/cant-signal
ip/include-header
tcp/no-delay))
;;; Integer Options
(define options/value
(list socket/send-buffer
socket/receive-buffer
socket/send-low-water
socket/receive-low-water
socket/error
socket/type
ip/type-of-service
ip/time-to-live
tcp/max-segment))
# f or Positive Integer
(define options/linger
(list socket/linger))
;;; Real Number
(define options/timeout
(list socket/send-timeout
socket/receive-timeout))
| null | https://raw.githubusercontent.com/cardmagic/lucash/0452d410430d12140c14948f7f583624f819cdad/reference/scsh-0.6.6/scsh/irix/netconst.scm | scheme | magic numbers not from header file
but from man page
why can't unix make up its mind
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
BELOW THIS POINT ARE BITS FROM:
<sys/socket.h>
<sys/un.h>
<netinet/in.h>
<netinet/tcp.h>
<netdb.h>
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
unspecified
local to host (pipes, portals)
SOCKET TYPES -- <sys/socket.h>
stream socket
datagram socket
raw-protocol interface
reliably - delivered message
(define socket-type/seqpacket 5) ; sequenced packet stream
unspecified
local to host (pipes, portals)
Well know addresses -- <netinet/in.h>
must be masked
errors from host lookup -- <netdb.h>
Authoritative Answer Host not found
Non-Authoritive Host not found, or SERVERFAIL
Valid name, no data record of requested type
process out-of-band data
peek at incoming message
send without using routing tables
SOL_SOCKET: options for socket level
turn on debugging info recording
socket has had listen()
allow local address reuse
keep connections alive
just use interface addresses
bypass hardware when possible
linger on close if data present
allow local address,port reuse
(define socket/use-privileged #x4000) ; allocate from privileged port area
prevent SIGPIPE on SS_CANTSENDMORE
send buffer size
receive buffer size
send low-water mark
receive low-water mark
send timeout
receive timeout
get error status and clear
get socket type
ip options -- <netinet/in.h>
set/get IP per-packet options
int; header is included with data (raw)
int; ip type of service and precedence
set/get IP time-to-live value
tcp options -- <netinet/tcp.h>
don't delay send to coalesce packets
set maximum segment size
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
OPTION SETS FOR SOCKET-OPTION AND SET-SOCKET-OPTION
socket/use-privileged
socket/cant-signal
Integer Options
Real Number | Magic Numbers for Networking
Copyright ( c ) 1994 by . See file COPYING .
(define shutdown/receives 0)
(define shutdown/sends 1)
(define shutdown/sends+receives 2)
ADDRESS FAMILIES -- < sys / socket.h >
internetwork : UDP , TCP , etc .
PROTOCOL FAMILIES -- < sys / socket.h >
internetwork : UDP , TCP , etc .
(define internet-address/any #x00000000)
(define internet-address/loopback #x7f000001)
Non recoverable errors , FORMERR , REFUSED , NOTIMP
no address , look for MX record
flags for send / recv -- < sys / socket.h >
protocol level for socket options -- < sys / socket.h >
socket options -- < sys / socket.h >
permit sending of broadcast msgs
leave received OOB data in line
Boolean Options
(define options/boolean
(list socket/debug
socket/accept-connect
socket/reuse-address
socket/keep-alive
socket/dont-route
socket/broadcast
socket/use-loop-back
socket/oob-inline
ip/include-header
tcp/no-delay))
(define options/value
(list socket/send-buffer
socket/receive-buffer
socket/send-low-water
socket/receive-low-water
socket/error
socket/type
ip/type-of-service
ip/time-to-live
tcp/max-segment))
# f or Positive Integer
(define options/linger
(list socket/linger))
(define options/timeout
(list socket/send-timeout
socket/receive-timeout))
|
6942bed7a79a74a351df32859e3c243c779392d509a02a61d1db03550f3e95a4 | abdulapopoola/SICPBook | Ex2.17.scm | #lang planet neil/sicp
(define (last-pair list1)
(if (null? (cdr list1))
list1
(last-pair (cdr list1))))
(last-pair (list 23 72 149 34))
| null | https://raw.githubusercontent.com/abdulapopoola/SICPBook/c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a/Chapter%202/2.2/Ex2.17.scm | scheme | #lang planet neil/sicp
(define (last-pair list1)
(if (null? (cdr list1))
list1
(last-pair (cdr list1))))
(last-pair (list 23 72 149 34))
| |
41b9f89cc014c1edbe0e7c911ea564f0abf8ba73d43eb672d246afa6d9bd4880 | boxuk/finder | opts.clj |
(ns ^{:doc "This namespace deals with the query options like order, limit and offset"}
finder.opts
(:require [clojure.string :as string]))
(defn- ^{:doc "Destructures a name/value vector and returns a single order clause as
a string. ie. 'name desc'"}
to-order-clause [[col dir]]
(format "%s %s" (name col)
(name dir)))
(defn- ^{:doc "Takes an order by column, or series of columns and builds the order by
statement as a string to return."}
get-order [order]
(let [orders (if (map? order) order
(hash-map order :desc))]
(str " order by "
(string/join ", "
(map to-order-clause orders)))))
(defn- ^{:doc "Checks the options data to see if an option is present, and if it is
then passes it to its handler function, returning the result."}
to-option [opts [opt func]]
(if-let [data (get opts opt)]
(func data) ""))
;; Public
;; ------
(defn ^{:doc "Takes the 'options' map of information about ordering, limit and offset. Then returns
a string for those parts of the SQL query, in the correct order."}
get-options [opts]
(let [clause #(format " %s %d" %1 %2)]
(string/join ""
(map (partial to-option opts)
{:order get-order
:limit (partial clause "limit")
:offset (partial clause "offset")}))))
| null | https://raw.githubusercontent.com/boxuk/finder/1d5e7d6de7a85e1bdb37e5b8e6b9636454ccb9c6/src/finder/opts.clj | clojure | Public
------ |
(ns ^{:doc "This namespace deals with the query options like order, limit and offset"}
finder.opts
(:require [clojure.string :as string]))
(defn- ^{:doc "Destructures a name/value vector and returns a single order clause as
a string. ie. 'name desc'"}
to-order-clause [[col dir]]
(format "%s %s" (name col)
(name dir)))
(defn- ^{:doc "Takes an order by column, or series of columns and builds the order by
statement as a string to return."}
get-order [order]
(let [orders (if (map? order) order
(hash-map order :desc))]
(str " order by "
(string/join ", "
(map to-order-clause orders)))))
(defn- ^{:doc "Checks the options data to see if an option is present, and if it is
then passes it to its handler function, returning the result."}
to-option [opts [opt func]]
(if-let [data (get opts opt)]
(func data) ""))
(defn ^{:doc "Takes the 'options' map of information about ordering, limit and offset. Then returns
a string for those parts of the SQL query, in the correct order."}
get-options [opts]
(let [clause #(format " %s %d" %1 %2)]
(string/join ""
(map (partial to-option opts)
{:order get-order
:limit (partial clause "limit")
:offset (partial clause "offset")}))))
|
8a44718a6867f08e6579cd7a6ba02698e1e0572ac90d51d9e466e25e0e8ee3c0 | janestreet/incr_map | map_operations.ml | open Core
open Import
module Without_stabilize = struct
type ('key, 'data) t =
[ `Add of 'key * 'data [@quickcheck.weight 10.]
| `Remove of 'key [@quickcheck.weight 4.]
]
[@@deriving quickcheck, sexp_of]
let apply t map =
match t with
| `Add (key, data) -> Map.set map ~key ~data
| `Remove key -> Map.remove map key
;;
let apply_nested t ~inner_map_comparator map =
match t with
| `Add (key, nested_operations) ->
Map.update map key ~f:(fun inner_map ->
List.fold
nested_operations
~init:(Option.value inner_map ~default:(Map.empty inner_map_comparator))
~f:(fun inner_map t -> apply t inner_map))
| `Remove key -> Map.remove map key
;;
let add ~key ~data = `Add (key, data)
let remove key = `Remove key
end
type ('key, 'data) t =
[ `Stabilize
| ('key, 'data) Without_stabilize.t
]
[@@deriving sexp_of]
let add = Without_stabilize.add
let remove = Without_stabilize.remove
let stabilize = `Stabilize
let int_key_gen ~keys_size =
let open Quickcheck.Generator.Let_syntax in
let%bind keys =
let%bind len =
match keys_size with
| Some n -> return n
| None -> Int.gen_incl 5 150
in
List.gen_with_length len Int.quickcheck_generator
>>| List.dedup_and_sort ~compare:Int.compare
in
Quickcheck.Generator.of_list keys
;;
let quickcheck_generator_with_stabilize ~key_gen ?operations data_gen =
let open Quickcheck.Generator.Let_syntax in
let elt_gen =
Quickcheck.Generator.weighted_union
[ 1., return `Stabilize
; 14., Without_stabilize.quickcheck_generator key_gen data_gen
]
in
match operations with
| None -> List.quickcheck_generator elt_gen
| Some len -> List.gen_with_length len elt_gen
;;
let quickcheck_generator ?keys_size ?operations data_gen =
quickcheck_generator_with_stabilize
~key_gen:(int_key_gen ~keys_size)
?operations
data_gen
;;
let tuple_key_quickcheck_generator ?(keys_size = 12) ?operations data_gen =
quickcheck_generator_with_stabilize
~key_gen:
(Quickcheck.Generator.both
(int_key_gen ~keys_size:(Some keys_size))
(int_key_gen ~keys_size:(Some keys_size)))
?operations
data_gen
;;
let inner_map_generator ~keys_size ~operations data_gen =
let elt_gen =
Without_stabilize.quickcheck_generator (int_key_gen ~keys_size) data_gen
in
match operations with
| None -> List.quickcheck_generator elt_gen
| Some len -> List.gen_with_length len elt_gen
;;
let nested_quickcheck_generator
?outer_map_keys_size
?outer_map_operations
?inner_map_keys_size
?inner_map_operations
data_gen
=
quickcheck_generator
?keys_size:outer_map_keys_size
?operations:outer_map_operations
(inner_map_generator
~keys_size:inner_map_keys_size
~operations:inner_map_operations
data_gen)
;;
let run_operations_general ~apply operations ~into:var ~after_stabilize =
let init = Incr.Var.latest_value var in
List.fold operations ~init ~f:(fun map oper ->
match oper with
| #Without_stabilize.t as without_stabilize -> apply without_stabilize map
| `Stabilize ->
Incr.Var.set var map;
Incr.stabilize ();
after_stabilize ();
map)
|> ignore
;;
let run_operations operations ~into ~after_stabilize =
run_operations_general ~apply:Without_stabilize.apply operations ~into ~after_stabilize
;;
let nested_run_operations operations ~inner_map_comparator ~into ~after_stabilize =
run_operations_general
~apply:(Without_stabilize.apply_nested ~inner_map_comparator)
operations
~into
~after_stabilize
;;
| null | https://raw.githubusercontent.com/janestreet/incr_map/b56e7d8b1299d77790e3bc72e2aeeca74afd04fe/test/map_operations.ml | ocaml | open Core
open Import
module Without_stabilize = struct
type ('key, 'data) t =
[ `Add of 'key * 'data [@quickcheck.weight 10.]
| `Remove of 'key [@quickcheck.weight 4.]
]
[@@deriving quickcheck, sexp_of]
let apply t map =
match t with
| `Add (key, data) -> Map.set map ~key ~data
| `Remove key -> Map.remove map key
;;
let apply_nested t ~inner_map_comparator map =
match t with
| `Add (key, nested_operations) ->
Map.update map key ~f:(fun inner_map ->
List.fold
nested_operations
~init:(Option.value inner_map ~default:(Map.empty inner_map_comparator))
~f:(fun inner_map t -> apply t inner_map))
| `Remove key -> Map.remove map key
;;
let add ~key ~data = `Add (key, data)
let remove key = `Remove key
end
type ('key, 'data) t =
[ `Stabilize
| ('key, 'data) Without_stabilize.t
]
[@@deriving sexp_of]
let add = Without_stabilize.add
let remove = Without_stabilize.remove
let stabilize = `Stabilize
let int_key_gen ~keys_size =
let open Quickcheck.Generator.Let_syntax in
let%bind keys =
let%bind len =
match keys_size with
| Some n -> return n
| None -> Int.gen_incl 5 150
in
List.gen_with_length len Int.quickcheck_generator
>>| List.dedup_and_sort ~compare:Int.compare
in
Quickcheck.Generator.of_list keys
;;
let quickcheck_generator_with_stabilize ~key_gen ?operations data_gen =
let open Quickcheck.Generator.Let_syntax in
let elt_gen =
Quickcheck.Generator.weighted_union
[ 1., return `Stabilize
; 14., Without_stabilize.quickcheck_generator key_gen data_gen
]
in
match operations with
| None -> List.quickcheck_generator elt_gen
| Some len -> List.gen_with_length len elt_gen
;;
let quickcheck_generator ?keys_size ?operations data_gen =
quickcheck_generator_with_stabilize
~key_gen:(int_key_gen ~keys_size)
?operations
data_gen
;;
let tuple_key_quickcheck_generator ?(keys_size = 12) ?operations data_gen =
quickcheck_generator_with_stabilize
~key_gen:
(Quickcheck.Generator.both
(int_key_gen ~keys_size:(Some keys_size))
(int_key_gen ~keys_size:(Some keys_size)))
?operations
data_gen
;;
let inner_map_generator ~keys_size ~operations data_gen =
let elt_gen =
Without_stabilize.quickcheck_generator (int_key_gen ~keys_size) data_gen
in
match operations with
| None -> List.quickcheck_generator elt_gen
| Some len -> List.gen_with_length len elt_gen
;;
let nested_quickcheck_generator
?outer_map_keys_size
?outer_map_operations
?inner_map_keys_size
?inner_map_operations
data_gen
=
quickcheck_generator
?keys_size:outer_map_keys_size
?operations:outer_map_operations
(inner_map_generator
~keys_size:inner_map_keys_size
~operations:inner_map_operations
data_gen)
;;
let run_operations_general ~apply operations ~into:var ~after_stabilize =
let init = Incr.Var.latest_value var in
List.fold operations ~init ~f:(fun map oper ->
match oper with
| #Without_stabilize.t as without_stabilize -> apply without_stabilize map
| `Stabilize ->
Incr.Var.set var map;
Incr.stabilize ();
after_stabilize ();
map)
|> ignore
;;
let run_operations operations ~into ~after_stabilize =
run_operations_general ~apply:Without_stabilize.apply operations ~into ~after_stabilize
;;
let nested_run_operations operations ~inner_map_comparator ~into ~after_stabilize =
run_operations_general
~apply:(Without_stabilize.apply_nested ~inner_map_comparator)
operations
~into
~after_stabilize
;;
| |
76175de4865c48d4a7278853065ebaf040abb96d9aa6d206c39245cf66919ec2 | monadbobo/ocaml-core | heap.mli | * Min - heap implementation , adapted from CLR .
* { 6 Exceptions }
(** Raised when [top] or [pop] is called on an empty heap. *)
exception Empty
(** {6 Types} *)
(** Type of heaps *)
type 'el t
(** Type of heap elements (they can be efficiently removed) *)
type 'el heap_el
* { 6 Functions on heap elements }
(** [heap_el_is_valid heap_el] @return [true] iff heap element is member
of a heap. *)
val heap_el_is_valid : 'el heap_el -> bool
(** [heap_el_get_el heap_el] @return the element associated with the heap
element. *)
val heap_el_get_el : 'el heap_el -> 'el
* { 6 Information on heap values }
(** [length heap] @return the length (number of elements) of [heap]. *)
val length : 'el t -> int
(** [is_empty heap] @return [true] iff [heap] does not contain any
elements. *)
val is_empty : 'el t -> bool
(** [get_cmp heap] @return the ordering function used by [heap]. *)
val get_cmp : 'el t -> ('el -> 'el -> int)
* { 6 Heap creation }
(** [create ?min_size cmp] @return a fresh heap that can store [min_size]
elements without reallocations, using ordering function [cmp].
If [cmp x y < 0] (i.e. x < y), then [x] will be on "top" of [y] in the heap.
That is, Heap.pop will remove [x] before [y].
*)
val create : ?min_size : int -> ('el -> 'el -> int) -> 'el t
(** [of_array ?min_size cmp ar] @return a fresh heap that can store
[min_size] elements without reallocations, using ordering function
[cmp], and initialize it with the elements of [ar]. *)
val of_array : ?min_size : int -> ('el -> 'el -> int) -> 'el array -> 'el t
(** [copy heap] @return a copy of [heap]. *)
val copy : 'el t -> 'el t
* { 6 Search functions }
(** [mem heap el] @return [true] iff [el] is member of [heap].
Requires linear time in worst case. *)
val mem : 'el t -> 'el -> bool
(** [heap_el_mem heap heap_el] @return [true] iff [heap_el] is member of
[heap]. Requires constant time only. *)
val heap_el_mem : 'el t -> 'el heap_el -> bool
(** [find_heap_el_exn heap el] @return the heap element associated with
element [el] in [heap].
@raise Not_found if [el] could not be found. *)
val find_heap_el_exn : 'el t -> 'el -> 'el heap_el
* { 6 Non - destructive heap accessors }
(** [top heap] @return [Some top_element] of [heap] without
changing it, or [None] if [heap] is empty. *)
val top : 'el t -> 'el option
(** [top_exn heap] @return the top element of [heap] without changing it.
@raise Empty if [heap] is empty. *)
val top_exn : 'el t -> 'el
(** [top_heap_el heap] @return [Some top_heap_el] of [heap] without
changing it, or [None] if [heap] is empty. *)
val top_heap_el : 'el t -> 'el heap_el option
(** [top_heap_el_exn heap] @return the top heap element of [heap]
without changing it. @raise Empty if [heap] is empty. *)
val top_heap_el_exn : 'el t -> 'el heap_el
(** [iter heap ~f] iterate over [heap] with function [f]. The elements
are passed in an unspecified order. *)
val iter : 'a t -> f:('a -> unit) -> unit
* { 6 Destructive heap accessors }
(** [pop heap] @return [Some top_element] of [heap], removing it,
or [None] if [heap] is empty. *)
val pop : 'el t -> 'el option
(** [pop_exn heap] @return the top element of [heap], removing it.
@raise Empty if [heap] is empty. *)
val pop_exn : 'el t -> 'el
* [ pop_heap_el heap ] @return [ Some top_heap_element ] , removing
it , or [ None ] if [ heap ] is empty .
it, or [None] if [heap] is empty. *)
val pop_heap_el : 'el t -> 'el heap_el option
(** [pop_heap_el_exn heap] @return the top heap element of [heap],
removing it. @raise Empty if [heap] is empty. *)
val pop_heap_el_exn : 'el t -> 'el heap_el
(** [cond_pop heap cond] @return [Some top_element] of [heap] if it
fills condition [cond], removing it, or [None] in any other case. *)
val cond_pop : 'el t -> ('el -> bool) -> 'el option
(** [cond_pop_heap_el heap cond] @return [Some top_heap_element] of
[heap] if the associated element fills condition [cond], removing it,
or [None] in any other case. *)
val cond_pop_heap_el : 'el t -> ('el -> bool) -> 'el heap_el option
(** [push heap el] pushes element [el] on [heap]. @return the heap
element associated with the newly inserted element. *)
val push : 'el t -> 'el -> 'el heap_el
(** [push_heap_el heap heap_el] pushes [heap_el] on [heap].
@raise Failure if [heap_el] is already member of some heap. *)
val push_heap_el : 'el t -> 'el heap_el -> unit
(** [remove heap_el] removes [heap_el] from its associated heap.
@raise Failure if [heap_el] is not member of any heap. *)
val remove : 'el heap_el -> unit
* [ update heap_el el ] updates [ heap_el ] with element [ el ] in its
associated heap .
@raise Failure if [ heap_el ] is not member of any heap .
associated heap.
@raise Failure if [heap_el] is not member of any heap. *)
val update : 'el heap_el -> 'el -> unit
* { 6 For testing only . }
(** [check_heap_property h] asserts that [h] has the heap property: that all
nodes are less than their children by [h]'s comparison function. *)
val check_heap_property : 'el t -> bool
| null | https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/lib/heap.mli | ocaml | * Raised when [top] or [pop] is called on an empty heap.
* {6 Types}
* Type of heaps
* Type of heap elements (they can be efficiently removed)
* [heap_el_is_valid heap_el] @return [true] iff heap element is member
of a heap.
* [heap_el_get_el heap_el] @return the element associated with the heap
element.
* [length heap] @return the length (number of elements) of [heap].
* [is_empty heap] @return [true] iff [heap] does not contain any
elements.
* [get_cmp heap] @return the ordering function used by [heap].
* [create ?min_size cmp] @return a fresh heap that can store [min_size]
elements without reallocations, using ordering function [cmp].
If [cmp x y < 0] (i.e. x < y), then [x] will be on "top" of [y] in the heap.
That is, Heap.pop will remove [x] before [y].
* [of_array ?min_size cmp ar] @return a fresh heap that can store
[min_size] elements without reallocations, using ordering function
[cmp], and initialize it with the elements of [ar].
* [copy heap] @return a copy of [heap].
* [mem heap el] @return [true] iff [el] is member of [heap].
Requires linear time in worst case.
* [heap_el_mem heap heap_el] @return [true] iff [heap_el] is member of
[heap]. Requires constant time only.
* [find_heap_el_exn heap el] @return the heap element associated with
element [el] in [heap].
@raise Not_found if [el] could not be found.
* [top heap] @return [Some top_element] of [heap] without
changing it, or [None] if [heap] is empty.
* [top_exn heap] @return the top element of [heap] without changing it.
@raise Empty if [heap] is empty.
* [top_heap_el heap] @return [Some top_heap_el] of [heap] without
changing it, or [None] if [heap] is empty.
* [top_heap_el_exn heap] @return the top heap element of [heap]
without changing it. @raise Empty if [heap] is empty.
* [iter heap ~f] iterate over [heap] with function [f]. The elements
are passed in an unspecified order.
* [pop heap] @return [Some top_element] of [heap], removing it,
or [None] if [heap] is empty.
* [pop_exn heap] @return the top element of [heap], removing it.
@raise Empty if [heap] is empty.
* [pop_heap_el_exn heap] @return the top heap element of [heap],
removing it. @raise Empty if [heap] is empty.
* [cond_pop heap cond] @return [Some top_element] of [heap] if it
fills condition [cond], removing it, or [None] in any other case.
* [cond_pop_heap_el heap cond] @return [Some top_heap_element] of
[heap] if the associated element fills condition [cond], removing it,
or [None] in any other case.
* [push heap el] pushes element [el] on [heap]. @return the heap
element associated with the newly inserted element.
* [push_heap_el heap heap_el] pushes [heap_el] on [heap].
@raise Failure if [heap_el] is already member of some heap.
* [remove heap_el] removes [heap_el] from its associated heap.
@raise Failure if [heap_el] is not member of any heap.
* [check_heap_property h] asserts that [h] has the heap property: that all
nodes are less than their children by [h]'s comparison function. | * Min - heap implementation , adapted from CLR .
* { 6 Exceptions }
exception Empty
type 'el t
type 'el heap_el
* { 6 Functions on heap elements }
val heap_el_is_valid : 'el heap_el -> bool
val heap_el_get_el : 'el heap_el -> 'el
* { 6 Information on heap values }
val length : 'el t -> int
val is_empty : 'el t -> bool
val get_cmp : 'el t -> ('el -> 'el -> int)
* { 6 Heap creation }
val create : ?min_size : int -> ('el -> 'el -> int) -> 'el t
val of_array : ?min_size : int -> ('el -> 'el -> int) -> 'el array -> 'el t
val copy : 'el t -> 'el t
* { 6 Search functions }
val mem : 'el t -> 'el -> bool
val heap_el_mem : 'el t -> 'el heap_el -> bool
val find_heap_el_exn : 'el t -> 'el -> 'el heap_el
* { 6 Non - destructive heap accessors }
val top : 'el t -> 'el option
val top_exn : 'el t -> 'el
val top_heap_el : 'el t -> 'el heap_el option
val top_heap_el_exn : 'el t -> 'el heap_el
val iter : 'a t -> f:('a -> unit) -> unit
* { 6 Destructive heap accessors }
val pop : 'el t -> 'el option
val pop_exn : 'el t -> 'el
* [ pop_heap_el heap ] @return [ Some top_heap_element ] , removing
it , or [ None ] if [ heap ] is empty .
it, or [None] if [heap] is empty. *)
val pop_heap_el : 'el t -> 'el heap_el option
val pop_heap_el_exn : 'el t -> 'el heap_el
val cond_pop : 'el t -> ('el -> bool) -> 'el option
val cond_pop_heap_el : 'el t -> ('el -> bool) -> 'el heap_el option
val push : 'el t -> 'el -> 'el heap_el
val push_heap_el : 'el t -> 'el heap_el -> unit
val remove : 'el heap_el -> unit
* [ update heap_el el ] updates [ heap_el ] with element [ el ] in its
associated heap .
@raise Failure if [ heap_el ] is not member of any heap .
associated heap.
@raise Failure if [heap_el] is not member of any heap. *)
val update : 'el heap_el -> 'el -> unit
* { 6 For testing only . }
val check_heap_property : 'el t -> bool
|
0f81287845d4a64d2f4e082fce79fd10560bd02e565778e7bd71d92c1eca72bc | samoht/dog | dog_watch.ml |
* Copyright ( c ) 2015 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2015 Thomas Gazagnaire <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Dog_misc
open Lwt.Infix
let chdir dir = Unix.handle_unix_error Unix.chdir dir
let in_dir dir fn =
let reset_cwd =
let cwd = Unix.handle_unix_error Unix.getcwd () in
fun () -> chdir cwd in
chdir dir;
try
let r = fn () in
reset_cwd ();
r
with e ->
reset_cwd ();
raise e
let (/) x y = x @ [y]
let list kind dir =
in_dir dir (fun () ->
let d = Sys.readdir (Sys.getcwd ()) in
let d = Array.to_list d in
List.filter kind d
)
let files =
list (fun f -> try not (Sys.is_directory f) with Sys_error _ -> true)
let directories =
list (fun f -> try Sys.is_directory f with Sys_error _ -> false)
let rec_files ?(keep=fun _ -> true) root =
let rec aux accu dir =
let path = Dog_misc.path (root :: dir) in
let d =
directories path
|> List.filter keep
|> List.map ((/) dir)
in
let f =
files path
|> List.filter keep
|> List.map ((/) dir)
in
List.fold_left aux (f @ accu) d in
aux [] []
let read_file p =
let file = Dog_misc.path p in
let ic = open_in file in
let len = in_channel_length ic in
let buf = Bytes.create len in
really_input ic buf 0 len;
close_in ic;
Bytes.to_string buf
module View = Irmin.View(Store)
let pretty_diff (f, d) =
let file = path f in
let diff = match d with
| `Added _ -> "+"
| `Updated _ -> "*"
| `Removed _ -> "-"
in
Printf.sprintf "%s /%s" diff file
let pretty_diffs name diff =
let changes = String.concat "\n" @@ List.map pretty_diff diff in
Printf.sprintf "Changes from %s:\n\n%s" name changes
let update_files name t files =
View.empty () >>= fun view ->
Lwt_list.iter_s (fun path ->
View.update view path (read_file path)
) files
>>= fun () ->
View.of_path (t "view") [] >>= fun view0 ->
View.diff view0 view >>= function
| [] -> Lwt.return `Up_to_date
| files ->
let changes = pretty_diffs name files in
View.update_path (t changes) [] view >|= fun () ->
`Needs_update
let keep = function ".git" -> false | _ -> true
let start_msg () =
Printf.sprintf "%s\n%dn" (timestamp ()) (Unix.getpid ())
let cmd ~root ?(interval=1.) ?(once=false) name remote =
let head = Git.Reference.of_raw ("refs/heads/" ^ name) in
let config = Irmin_git.config ~root ~bare:false ~head () in
Store.Repo.create config >>= fun repo ->
Store.of_branch_id task name repo >>= fun t ->
Store.update (t "Initial commit") [".init"] (start_msg ()) >>= fun () ->
let rec aux () =
let files = rec_files ~keep root in
begin update_files name t files >>= function
| `Up_to_date -> Lwt.return_unit
| `Needs_update -> git_push ~root ~branch:name remote
end >>= fun () ->
if once then Lwt.return_unit
else Lwt_unix.sleep interval >>= aux
in
aux ()
| null | https://raw.githubusercontent.com/samoht/dog/6472e52615d704073e51290b6eeadea61f2535be/src/dog_watch.ml | ocaml |
* Copyright ( c ) 2015 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2015 Thomas Gazagnaire <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Dog_misc
open Lwt.Infix
let chdir dir = Unix.handle_unix_error Unix.chdir dir
let in_dir dir fn =
let reset_cwd =
let cwd = Unix.handle_unix_error Unix.getcwd () in
fun () -> chdir cwd in
chdir dir;
try
let r = fn () in
reset_cwd ();
r
with e ->
reset_cwd ();
raise e
let (/) x y = x @ [y]
let list kind dir =
in_dir dir (fun () ->
let d = Sys.readdir (Sys.getcwd ()) in
let d = Array.to_list d in
List.filter kind d
)
let files =
list (fun f -> try not (Sys.is_directory f) with Sys_error _ -> true)
let directories =
list (fun f -> try Sys.is_directory f with Sys_error _ -> false)
let rec_files ?(keep=fun _ -> true) root =
let rec aux accu dir =
let path = Dog_misc.path (root :: dir) in
let d =
directories path
|> List.filter keep
|> List.map ((/) dir)
in
let f =
files path
|> List.filter keep
|> List.map ((/) dir)
in
List.fold_left aux (f @ accu) d in
aux [] []
let read_file p =
let file = Dog_misc.path p in
let ic = open_in file in
let len = in_channel_length ic in
let buf = Bytes.create len in
really_input ic buf 0 len;
close_in ic;
Bytes.to_string buf
module View = Irmin.View(Store)
let pretty_diff (f, d) =
let file = path f in
let diff = match d with
| `Added _ -> "+"
| `Updated _ -> "*"
| `Removed _ -> "-"
in
Printf.sprintf "%s /%s" diff file
let pretty_diffs name diff =
let changes = String.concat "\n" @@ List.map pretty_diff diff in
Printf.sprintf "Changes from %s:\n\n%s" name changes
let update_files name t files =
View.empty () >>= fun view ->
Lwt_list.iter_s (fun path ->
View.update view path (read_file path)
) files
>>= fun () ->
View.of_path (t "view") [] >>= fun view0 ->
View.diff view0 view >>= function
| [] -> Lwt.return `Up_to_date
| files ->
let changes = pretty_diffs name files in
View.update_path (t changes) [] view >|= fun () ->
`Needs_update
let keep = function ".git" -> false | _ -> true
let start_msg () =
Printf.sprintf "%s\n%dn" (timestamp ()) (Unix.getpid ())
let cmd ~root ?(interval=1.) ?(once=false) name remote =
let head = Git.Reference.of_raw ("refs/heads/" ^ name) in
let config = Irmin_git.config ~root ~bare:false ~head () in
Store.Repo.create config >>= fun repo ->
Store.of_branch_id task name repo >>= fun t ->
Store.update (t "Initial commit") [".init"] (start_msg ()) >>= fun () ->
let rec aux () =
let files = rec_files ~keep root in
begin update_files name t files >>= function
| `Up_to_date -> Lwt.return_unit
| `Needs_update -> git_push ~root ~branch:name remote
end >>= fun () ->
if once then Lwt.return_unit
else Lwt_unix.sleep interval >>= aux
in
aux ()
| |
8b86c94a5e2f9e457c42a6c1a00eaf263791ea60eeff2376b11c589f5c20d69b | cljfx/cljfx | list_view.clj | (ns cljfx.ext.list-view
(:require [cljfx.lifecycle :as lifecycle]
[cljfx.ext.multiple-selection-model :as ext.multiple-selection-model])
(:import [javafx.scene.control ListView]))
(set! *warn-on-reflection* true)
(def with-selection-props
"Extension lifecycle providing selection-related props to list-view component
Supported keys:
- `:desc` (required) - component description whose instance has to be a ListView
- `:props` (optional) - map of selection-related props:
- `:selection-mode` - either `:single` or `:multiple`
- selection, one of:
- `:selected-index` - int
- `:selected-item` - value from `:items` prop
- `:selected-indices` - coll of ints, prefer this when selection mode is `:multiple`
- `:selected-items` - coll of values from `:items` prop, prefer this when selection
mode is `:multiple`
- selection change listener, one of:
- `:on-selected-index-changed` - will receive int
- `:on-selected-item-changed` - will receive selected value
- `:on-selected-indices-changed` - will receive vector of ints
- `:on-selected-items-changed` - will receive vector of selected items"
(ext.multiple-selection-model/make-with-props
lifecycle/dynamic
#(.getSelectionModel ^ListView %)
lifecycle/scalar
:single))
| null | https://raw.githubusercontent.com/cljfx/cljfx/ec3c34e619b2408026b9f2e2ff8665bebf70bf56/src/cljfx/ext/list_view.clj | clojure | (ns cljfx.ext.list-view
(:require [cljfx.lifecycle :as lifecycle]
[cljfx.ext.multiple-selection-model :as ext.multiple-selection-model])
(:import [javafx.scene.control ListView]))
(set! *warn-on-reflection* true)
(def with-selection-props
"Extension lifecycle providing selection-related props to list-view component
Supported keys:
- `:desc` (required) - component description whose instance has to be a ListView
- `:props` (optional) - map of selection-related props:
- `:selection-mode` - either `:single` or `:multiple`
- selection, one of:
- `:selected-index` - int
- `:selected-item` - value from `:items` prop
- `:selected-indices` - coll of ints, prefer this when selection mode is `:multiple`
- `:selected-items` - coll of values from `:items` prop, prefer this when selection
mode is `:multiple`
- selection change listener, one of:
- `:on-selected-index-changed` - will receive int
- `:on-selected-item-changed` - will receive selected value
- `:on-selected-indices-changed` - will receive vector of ints
- `:on-selected-items-changed` - will receive vector of selected items"
(ext.multiple-selection-model/make-with-props
lifecycle/dynamic
#(.getSelectionModel ^ListView %)
lifecycle/scalar
:single))
| |
6ae52fa88ce36ebea33c31fe42e85fe2d675a93fd88b4cf0729881a4cceb6640 | tolitius/obiwan | dev.clj | (ns dev
(:require [clj-http.client :as http]
[jsonista.core :as json]
[clojure.string :as s]
[clojure.java.io :as io]
[clojure.repl :refer :all]
[clojure.pprint :refer [pprint]]
[yang.lang :as y]
[spec :as rspec]
[obiwan.core :as redis]
[obiwan.tools :as t]
[obiwan.search.core :as search]))
(def spec (rspec/slurp-redis-spec))
(defn ns-fns [nspace]
(let [raw (-> nspace symbol ns-publics)]
(->> (for [[k v] raw]
[(keyword k) v])
(into {}))))
;;TODO: add as a hook on building a jar
(defn add-redis-docs [nspace]
(doseq [[fname path] (ns-fns nspace)]
(when-let [doc (fname spec)]
(alter-meta! path
assoc-in [:doc :redis-doc] doc))))
(comment
;; repl
(require '[obiwan.core :as redis]
'[obiwan.tools :as t]
'[obiwan.search.command.create :as cc]
'[obiwan.search.command.search :as cs]
'[obiwan.search.command.core :as cmd])
(require '[obiwan.core :as redis]
'[obiwan.search.core :as search])
;; search core
(def conn (redis/create-pool))
(search/ft-create conn "solar-system"
{:prefix ["solar:planet:" "solar:planet:moon:"]
:schema [#:text{:name "nick" :sortable? true}
#:text{:name "age" :no-index? true}
#:numeric{:name "mass" :sortable? true}]})
(redis/hmset conn "solar:planet:earth" {"nick" "the blue planet" "age" "4.543 billion years" "mass" "5974000000000000000000000"})
(redis/hmset conn "solar:planet:mars" {"nick" "the red planet" "age" "4.603 billion years" "mass" "639000000000000000000000"})
(redis/hmset conn "solar:planet:pluto" {"nick" "tombaugh regio" "age" "4.5 billion years" "mass" "13090000000000000000000"})
(redis/hmset conn "solar:planet:moon:charon" {"planet" "pluto" "nick" "char" "age" "4.5 billion years" "mass" "1586000000000000000000"})
(search/ft-search conn "solar-system"
"@nick:re*")
;; aggregate shtuff
(search/ft-create conn "website-visits"
{:prefix ["stats:visit:"]
:schema [#:text{:name "url" :sortable? true}
#:numeric{:name "timestamp" :sortable? true}
#:tag{:name "country" :sortable? true}
#:text{:name "user_id" :sortable? true :no-index? true}]})
(def visits
[{"url" "/2008/11/19/zx-spectrum-child/"
"timestamp" "1631965013"
"country" "Ukraine"
"user_id" "tolitius"}
{"url" "/2017/01/10/hubble-space-mission-securely-configured/"
"timestamp" "1631963013"
"country" "China"
"user_id" "hashcn"}
{"url" "/2013/10/29/s1631982013728cala-where-ingenuity-lies/"
"timestamp" "1631964013"
"country" "USA"
"user_id" "unclejohn"}
{"url" "/2013/10/22/l1631982013728imited-async/"
"timestamp" "1631965013"
"country" "USA"
"user_id" "tolitius"}
{"url" "/2013/05/31/d1631982013728atomic-can-simple-be-also-fast/"
"timestamp" "1631967013"
"country" "Ukraine"
"user_id" "vvz"}
{"url" "/2012/05/08/s1631982013728cala-fun-with-canbuildfrom/"
"timestamp" "1631968013"
"country" "USA"
"user_id" "tolitius"}
{"url" "/2017/04/09/h1631982013728azelcast-keep-your-cluster-close-but-cache-closer/"
"timestamp" "1631961014"
"country" "China"
"user_id" "bruce"}])
(map-indexed (fn [idx visit]
(redis/hset conn
(str "stats:visit:dotkam.com:" idx)
visit))
visits)
(search/ft-aggregate conn "website-visits" "*" [{:apply {:expr "upper(@country)"
:as "country"}}
{:group {:by ["@country"]
:reduce [{:fn "COUNT_DISTINCT"
:fields ["@user_id"]
:as "num_users"}]}}])
{ : found 3 ,
;; :results
[ { " country " " USA " , " num_users " " 2 " }
{ " country " " CHINA " , " num_users " " 2 " }
;; {"country" "UKRAINE", "num_users" "2"}]}
(search/ft-aggregate conn "website-visits" "*" [{:apply {:expr "@timestamp - (@timestamp % 3600)"
:as "hour"}}
{:group {:by ["@hour"]
:reduce [{:fn "COUNT_DISTINCT"
:fields ["@user_id"]
:as "num_users"}]}}
{:apply {:expr "timefmt(@hour)"
:as "datatime"}}])
{ : found 3 ,
;; :results
[ { " num_users " " 3 " ,
" hour " " 1631962800 " ,
" datatime " " 2021 - 09 - 18T11:00:00Z " } ; ; 11:00
;; {"num_users" "1",
" hour " " 1631959200 " ,
" datatime " " 2021 - 09 - 18T10:00:00Z " } ; ; 10:00
{ " num_users " " 2 " ,
" hour " " 1631966400 " ,
" datatime " " 2021 - 09 - 18T12:00:00Z " } ] } ; ; 12:00
(search/ft-aggregate conn "website-visits" "*" [{:apply {:expr "@timestamp - (@timestamp % 3600)"
:as "hour"}}
{:group {:by ["@hour"]
:reduce [{:fn "COUNT_DISTINCT"
:fields ["@user_id"]
:as "num_users"}]}}
{:sort {:by {"@hour" :desc}}}
{:apply {:expr "timefmt(@hour)"
:as "datatime"}}])
{ : found 3 ,
;; :results
[ { " num_users " " 2 " ,
" hour " " 1631966400 " ,
" datatime " " 2021 - 09 - 18T12:00:00Z " } ; ; 12:00
{ " num_users " " 3 " ,
" hour " " 1631962800 " ,
" datatime " " 2021 - 09 - 18T11:00:00Z " } ; ; 11:00
;; {"num_users" "1",
" hour " " 1631959200 " ,
" datatime " " 2021 - 09 - 18T10:00:00Z " } ] } ; ; 10:00
;; suggestions
(search/ft-sugadd conn "songs" "Don't Stop Me Now" 1 {:payload "Queen"})
(search/ft-sugadd conn "songs" "Rock You Like A Hurricane" 1 {:payload "Scorpions"})
(search/ft-sugadd conn "songs" "Fortunate Son" 1 {:payload "Creedence Clearwater Revival"})
(search/ft-sugadd conn "songs" "Thunderstruck" 1 {:payload "AC/DC"})
(search/ft-sugadd conn "songs" "All Along the Watchtower" 1 {:payload "Jimmy"})
(search/ft-sugadd conn "songs" "Enter Sandman" 1 {:payload "Metallica"})
(search/ft-sugadd conn "songs" "Free Bird" 1 {:payload "Lynyrd Skynyrd"})
(search/ft-sugadd conn "songs" "Immigrant Song" 1 {:payload "Led Zeppelin"})
(search/ft-sugadd conn "songs" "Smells Like Teen Spirit" 1 {:payload "Nirvana"})
(search/ft-sugadd conn "songs""Purple Haze" 1 {:payload "Jimmy"})
(pprint (search/ft-sugget conn "songs" "mm" {:fuzzy? true :max 42}))
)
| null | https://raw.githubusercontent.com/tolitius/obiwan/623d6d55b15151bbe637422c023572d83f9a57a5/dev/dev.clj | clojure | TODO: add as a hook on building a jar
repl
search core
aggregate shtuff
:results
{"country" "UKRAINE", "num_users" "2"}]}
:results
; 11:00
{"num_users" "1",
; 10:00
; 12:00
:results
; 12:00
; 11:00
{"num_users" "1",
; 10:00
suggestions | (ns dev
(:require [clj-http.client :as http]
[jsonista.core :as json]
[clojure.string :as s]
[clojure.java.io :as io]
[clojure.repl :refer :all]
[clojure.pprint :refer [pprint]]
[yang.lang :as y]
[spec :as rspec]
[obiwan.core :as redis]
[obiwan.tools :as t]
[obiwan.search.core :as search]))
(def spec (rspec/slurp-redis-spec))
(defn ns-fns [nspace]
(let [raw (-> nspace symbol ns-publics)]
(->> (for [[k v] raw]
[(keyword k) v])
(into {}))))
(defn add-redis-docs [nspace]
(doseq [[fname path] (ns-fns nspace)]
(when-let [doc (fname spec)]
(alter-meta! path
assoc-in [:doc :redis-doc] doc))))
(comment
(require '[obiwan.core :as redis]
'[obiwan.tools :as t]
'[obiwan.search.command.create :as cc]
'[obiwan.search.command.search :as cs]
'[obiwan.search.command.core :as cmd])
(require '[obiwan.core :as redis]
'[obiwan.search.core :as search])
(def conn (redis/create-pool))
(search/ft-create conn "solar-system"
{:prefix ["solar:planet:" "solar:planet:moon:"]
:schema [#:text{:name "nick" :sortable? true}
#:text{:name "age" :no-index? true}
#:numeric{:name "mass" :sortable? true}]})
(redis/hmset conn "solar:planet:earth" {"nick" "the blue planet" "age" "4.543 billion years" "mass" "5974000000000000000000000"})
(redis/hmset conn "solar:planet:mars" {"nick" "the red planet" "age" "4.603 billion years" "mass" "639000000000000000000000"})
(redis/hmset conn "solar:planet:pluto" {"nick" "tombaugh regio" "age" "4.5 billion years" "mass" "13090000000000000000000"})
(redis/hmset conn "solar:planet:moon:charon" {"planet" "pluto" "nick" "char" "age" "4.5 billion years" "mass" "1586000000000000000000"})
(search/ft-search conn "solar-system"
"@nick:re*")
(search/ft-create conn "website-visits"
{:prefix ["stats:visit:"]
:schema [#:text{:name "url" :sortable? true}
#:numeric{:name "timestamp" :sortable? true}
#:tag{:name "country" :sortable? true}
#:text{:name "user_id" :sortable? true :no-index? true}]})
(def visits
[{"url" "/2008/11/19/zx-spectrum-child/"
"timestamp" "1631965013"
"country" "Ukraine"
"user_id" "tolitius"}
{"url" "/2017/01/10/hubble-space-mission-securely-configured/"
"timestamp" "1631963013"
"country" "China"
"user_id" "hashcn"}
{"url" "/2013/10/29/s1631982013728cala-where-ingenuity-lies/"
"timestamp" "1631964013"
"country" "USA"
"user_id" "unclejohn"}
{"url" "/2013/10/22/l1631982013728imited-async/"
"timestamp" "1631965013"
"country" "USA"
"user_id" "tolitius"}
{"url" "/2013/05/31/d1631982013728atomic-can-simple-be-also-fast/"
"timestamp" "1631967013"
"country" "Ukraine"
"user_id" "vvz"}
{"url" "/2012/05/08/s1631982013728cala-fun-with-canbuildfrom/"
"timestamp" "1631968013"
"country" "USA"
"user_id" "tolitius"}
{"url" "/2017/04/09/h1631982013728azelcast-keep-your-cluster-close-but-cache-closer/"
"timestamp" "1631961014"
"country" "China"
"user_id" "bruce"}])
(map-indexed (fn [idx visit]
(redis/hset conn
(str "stats:visit:dotkam.com:" idx)
visit))
visits)
(search/ft-aggregate conn "website-visits" "*" [{:apply {:expr "upper(@country)"
:as "country"}}
{:group {:by ["@country"]
:reduce [{:fn "COUNT_DISTINCT"
:fields ["@user_id"]
:as "num_users"}]}}])
{ : found 3 ,
[ { " country " " USA " , " num_users " " 2 " }
{ " country " " CHINA " , " num_users " " 2 " }
(search/ft-aggregate conn "website-visits" "*" [{:apply {:expr "@timestamp - (@timestamp % 3600)"
:as "hour"}}
{:group {:by ["@hour"]
:reduce [{:fn "COUNT_DISTINCT"
:fields ["@user_id"]
:as "num_users"}]}}
{:apply {:expr "timefmt(@hour)"
:as "datatime"}}])
{ : found 3 ,
[ { " num_users " " 3 " ,
" hour " " 1631962800 " ,
" hour " " 1631959200 " ,
{ " num_users " " 2 " ,
" hour " " 1631966400 " ,
(search/ft-aggregate conn "website-visits" "*" [{:apply {:expr "@timestamp - (@timestamp % 3600)"
:as "hour"}}
{:group {:by ["@hour"]
:reduce [{:fn "COUNT_DISTINCT"
:fields ["@user_id"]
:as "num_users"}]}}
{:sort {:by {"@hour" :desc}}}
{:apply {:expr "timefmt(@hour)"
:as "datatime"}}])
{ : found 3 ,
[ { " num_users " " 2 " ,
" hour " " 1631966400 " ,
{ " num_users " " 3 " ,
" hour " " 1631962800 " ,
" hour " " 1631959200 " ,
(search/ft-sugadd conn "songs" "Don't Stop Me Now" 1 {:payload "Queen"})
(search/ft-sugadd conn "songs" "Rock You Like A Hurricane" 1 {:payload "Scorpions"})
(search/ft-sugadd conn "songs" "Fortunate Son" 1 {:payload "Creedence Clearwater Revival"})
(search/ft-sugadd conn "songs" "Thunderstruck" 1 {:payload "AC/DC"})
(search/ft-sugadd conn "songs" "All Along the Watchtower" 1 {:payload "Jimmy"})
(search/ft-sugadd conn "songs" "Enter Sandman" 1 {:payload "Metallica"})
(search/ft-sugadd conn "songs" "Free Bird" 1 {:payload "Lynyrd Skynyrd"})
(search/ft-sugadd conn "songs" "Immigrant Song" 1 {:payload "Led Zeppelin"})
(search/ft-sugadd conn "songs" "Smells Like Teen Spirit" 1 {:payload "Nirvana"})
(search/ft-sugadd conn "songs""Purple Haze" 1 {:payload "Jimmy"})
(pprint (search/ft-sugget conn "songs" "mm" {:fuzzy? true :max 42}))
)
|
a5189e93391e4c986457e72ad14532d135bf0541c7f602a244663d5b8e7277d1 | ConsenSysMesh/Fae | TX.hs | |
Module : Blockchain . Fae . Internal . TX
Description : Transaction interpreter
Copyright : ( c ) , 2017 - 2018
License : MIT
Maintainer :
Stability : experimental
This module provides the function that interprets transactions given as
source code . The interpreter enables the following extensions globally ;
this is the set of extensions I consider to be both generally harmless and
indispensable :
- BangPatterns
- DeriveDataTypeable
- DeriveGeneric
- FlexibleContexts
- FlexibleInstances
- FunctionalDependencies
- GeneralizedNewtypeDeriving
- LambdaCase
- MultiParamTypeClasses
- MultiWayIf
- NamedFieldPuns
- OverloadedStrings
- PatternGuards
- RecordWildCards
- StandaloneDeriving
- TupleSections
- TypeApplications
- TypeFamilies
Module: Blockchain.Fae.Internal.TX
Description: Transaction interpreter
Copyright: (c) Ryan Reich, 2017-2018
License: MIT
Maintainer:
Stability: experimental
This module provides the function that interprets transactions given as
source code. The interpreter enables the following extensions globally;
this is the set of extensions I consider to be both generally harmless and
indispensable:
- BangPatterns
- DeriveDataTypeable
- DeriveGeneric
- FlexibleContexts
- FlexibleInstances
- FunctionalDependencies
- GeneralizedNewtypeDeriving
- LambdaCase
- MultiParamTypeClasses
- MultiWayIf
- NamedFieldPuns
- OverloadedStrings
- PatternGuards
- RecordWildCards
- StandaloneDeriving
- TupleSections
- TypeApplications
- TypeFamilies
-}
module Blockchain.Fae.Internal.TX where
import Blockchain.Fae.Internal.Contract
import Blockchain.Fae.Internal.Crypto
import Blockchain.Fae.Internal.Exceptions
import Blockchain.Fae.Internal.IDs
import Blockchain.Fae.Internal.Storage
import Blockchain.Fae.Internal.Transaction
import Control.DeepSeq
import Control.Monad.State
import Data.ByteString (ByteString)
import Data.Functor.Identity
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Proxy
import Data.Typeable
import GHC.Generics
import Language.Haskell.Interpreter hiding (set,get)
import qualified Language.Haskell.Interpreter as Int (set,get)
import Language.Haskell.Interpreter.Unsafe as Int
import System.Environment
import System.FilePath
-- * Types
-- | This is the data type that identifies a transaction in a block; the
-- actual transaction function is only known at the time of interpretation.
data TX =
TX
{
isReward :: Bool,
txID :: TransactionID,
txMaterials :: InputMaterials,
inputs :: [Input],
pubKeys :: Signers,
fallback :: [String]
}
deriving (Generic)
-- | Helpful for printing strings without the surrounding quotes.
newtype UnquotedString = UnquotedString String
-- | Helpful for eliminating a 'Data.ByteString' dependency in the
-- 'interpretImportedValue' interpreter.
newtype WrappedByteString =
WrappedByteString { getWrappedByteString :: ByteString }
-- | Monad for interpreting Fae transactions
type FaeInterpretT m = InterpreterT (FaeStorageT m)
{- Instances -}
-- | Default instance
instance Serialize TX
-- | Default instance
instance Digestible TX
-- | Default instance
instance NFData TX
-- | Prints a string without the quotes
instance Show UnquotedString where
show (UnquotedString s) = s
-- | -
instance (Monad m) => MonadState Storage (FaeInterpretT m) where
state = lift . state
put = lift . put
get = lift get
-- * Functions
-- | Interprets a transaction, looking it up as a module named after its
-- transaction ID. We set up the module search path carefully so that this
-- transaction can effectively import both its own other modules, and those
-- of other transactions. Now that we dynamically link @faeServer@, the
load - up time for the first transaction is pretty short ; subsequent
-- transactions are faster still.
interpretTX ::
(Typeable m, MonadMask m, MonadIO m) =>
TX -> FaeInterpretT m ()
interpretTX TX{..} = do
faeInterpret [txModule] expr $ \f -> f txMaterials inputs txID pubKeys isReward
where
txModule = mkTXModuleName txID
-- Contrary to comments in the @hint@ documentation, the directory
@" . "@ is /not/ always included in the search path .
expr = unwords
[
"runTransaction",
"body",
show $ UnquotedString <$> fallback
]
-- | This has to be interpreted because, even though all the information is
-- known /to the sender/ of the value to be imported, it can only be
-- transmitted textually, and therefore has to be re-parsed into a valid
-- type. The modules necessary for expressing this type are carried in
-- 'neededModules'; they must be present for the recipient, but the
-- corresponding transactions, if any, need not have been fully evaluated.
interpretImportedValue ::
(Typeable m, MonadMask m, MonadIO m) => ExportData -> FaeInterpretT m ()
interpretImportedValue ExportData{..} =
faeInterpret neededModules runString $
\f -> f (WrappedByteString exportedValue) exportedCID exportStatus
where
runString = unwords
[
"addImportedValue",
".",
"importValueThrow @(" ++ exportValType ++ ")"
]
-- | A top-level function (so that it can be in scope in the interpreter of
-- 'interpretImportedValue') to handle failed imports.
importValueThrow ::
forall a m.
(Exportable a, MonadState Escrows m) => WrappedByteString -> m a
importValueThrow (WrappedByteString bs) =
fromMaybe (throw $ CantImport bs rep) <$> liftEscrowState (importValue bs)
where rep = typeRep $ Proxy @a
-- | The inner interpretation function that appropriately loads modules,
-- sets imports, and uses the result both for 'interpretTX' and
-- 'interpretImportedValue'.
faeInterpret ::
(Typeable m, MonadMask m, MonadIO m, Typeable a) =>
[String] ->
String ->
(a -> FaeStorage b) ->
FaeInterpretT m b
faeInterpret moduleNames runString apply = handle fixGHCErrors $ do
-- We don't have to, and in fact must not, call `loadModules` on
-- a package module that isn't to be interpreted.
loadModules $ filter isTXModule moduleNames
setImports imports
act <- interpret runString infer
liftFaeStorage $ apply act
where
imports =
"Blockchain.Fae.Internal" :
"Prelude" :
filter (not . isInternalModule) moduleNames
isTXModule = isPrefixOf "Blockchain.Fae.Transactions.TX"
isInternalModule = isPrefixOf "Blockchain.Fae.Internal"
fixGHCErrors (WontCompile []) = throw $ InterpretException "Compilation error"
fixGHCErrors (WontCompile (ghcE : _)) =
throw $ InterpretException $ errMsg ghcE
fixGHCErrors (UnknownError e) = throw $ InterpretException e
fixGHCErrors (NotAllowed e) = throw $ InterpretException e
fixGHCErrors (GhcException e) = throw $ InterpretException e
liftFaeStorage = lift . mapStateT (return . runIdentity) . getFaeStorage
-- | Runs the interpreter.
runFaeInterpret :: (MonadMask m, MonadIO m) => FaeInterpretT m a -> m a
runFaeInterpret x = do
ghcLibdirM <- liftIO $ lookupEnv "GHC_LIBDIR"
fmap (either throw id) . runStorageT . run ghcLibdirM args $ Int.set opts >> x
where
run = maybe
unsafeRunInterpreterWithArgs
(flip unsafeRunInterpreterWithArgsLibdir)
args =
-- We error on orphan instances because the import/export
-- capability relies on the 'ContractName' instance being in scope
-- whenever the name itself is.
"-Werror=orphans" :
-- For some reason, this makes the interpreter hang. Unfortunate, as it
-- rather weakens the trust situation not to have it.
-- "-distrust-all" :
"-fpackage-trust" : map ("-trust " ++) trustedPackages
opts =
[
installedModulesInScope := False,
languageExtensions :=
[
BangPatterns,
DeriveDataTypeable,
DeriveGeneric,
FlexibleContexts,
FlexibleInstances,
FunctionalDependencies,
LambdaCase,
MultiParamTypeClasses,
MultiWayIf,
NamedFieldPuns,
OverloadedStrings,
PatternGuards,
RecordWildCards,
Safe,
StandaloneDeriving,
TupleSections,
TypeApplications,
TypeFamilies
]
]
trustedPackages =
[
"array",
"base",
-- "binary",
"bytestring",
-- "cereal",
"containers",
"fae",
"filepath",
"transformers",
"pretty"
]
-- | Identifierizes a transaction ID. On the off chance that an identifier
-- (in some context) cannot begin with a number, we add an alphabetic
-- prefix.
mkTXIDName :: TransactionID -> String
mkTXIDName = ("TX" ++) . show
-- | Defines the Fae runtime module hierarchy.
mkTXPathParts :: TransactionID -> [String]
mkTXPathParts txID = ["Blockchain", "Fae", "Transactions", mkTXIDName txID]
-- | Collapses the transaction path parts into a dot-separated hierarchical
-- module name.
mkTXModuleName :: TransactionID -> String
mkTXModuleName = intercalate "." . mkTXPathParts
| null | https://raw.githubusercontent.com/ConsenSysMesh/Fae/3ff023f70fa403e9cef80045907e415ccd88d7e8/src/Blockchain/Fae/Internal/TX.hs | haskell | * Types
| This is the data type that identifies a transaction in a block; the
actual transaction function is only known at the time of interpretation.
| Helpful for printing strings without the surrounding quotes.
| Helpful for eliminating a 'Data.ByteString' dependency in the
'interpretImportedValue' interpreter.
| Monad for interpreting Fae transactions
Instances
| Default instance
| Default instance
| Default instance
| Prints a string without the quotes
| -
* Functions
| Interprets a transaction, looking it up as a module named after its
transaction ID. We set up the module search path carefully so that this
transaction can effectively import both its own other modules, and those
of other transactions. Now that we dynamically link @faeServer@, the
transactions are faster still.
Contrary to comments in the @hint@ documentation, the directory
| This has to be interpreted because, even though all the information is
known /to the sender/ of the value to be imported, it can only be
transmitted textually, and therefore has to be re-parsed into a valid
type. The modules necessary for expressing this type are carried in
'neededModules'; they must be present for the recipient, but the
corresponding transactions, if any, need not have been fully evaluated.
| A top-level function (so that it can be in scope in the interpreter of
'interpretImportedValue') to handle failed imports.
| The inner interpretation function that appropriately loads modules,
sets imports, and uses the result both for 'interpretTX' and
'interpretImportedValue'.
We don't have to, and in fact must not, call `loadModules` on
a package module that isn't to be interpreted.
| Runs the interpreter.
We error on orphan instances because the import/export
capability relies on the 'ContractName' instance being in scope
whenever the name itself is.
For some reason, this makes the interpreter hang. Unfortunate, as it
rather weakens the trust situation not to have it.
"-distrust-all" :
"binary",
"cereal",
| Identifierizes a transaction ID. On the off chance that an identifier
(in some context) cannot begin with a number, we add an alphabetic
prefix.
| Defines the Fae runtime module hierarchy.
| Collapses the transaction path parts into a dot-separated hierarchical
module name. | |
Module : Blockchain . Fae . Internal . TX
Description : Transaction interpreter
Copyright : ( c ) , 2017 - 2018
License : MIT
Maintainer :
Stability : experimental
This module provides the function that interprets transactions given as
source code . The interpreter enables the following extensions globally ;
this is the set of extensions I consider to be both generally harmless and
indispensable :
- BangPatterns
- DeriveDataTypeable
- DeriveGeneric
- FlexibleContexts
- FlexibleInstances
- FunctionalDependencies
- GeneralizedNewtypeDeriving
- LambdaCase
- MultiParamTypeClasses
- MultiWayIf
- NamedFieldPuns
- OverloadedStrings
- PatternGuards
- RecordWildCards
- StandaloneDeriving
- TupleSections
- TypeApplications
- TypeFamilies
Module: Blockchain.Fae.Internal.TX
Description: Transaction interpreter
Copyright: (c) Ryan Reich, 2017-2018
License: MIT
Maintainer:
Stability: experimental
This module provides the function that interprets transactions given as
source code. The interpreter enables the following extensions globally;
this is the set of extensions I consider to be both generally harmless and
indispensable:
- BangPatterns
- DeriveDataTypeable
- DeriveGeneric
- FlexibleContexts
- FlexibleInstances
- FunctionalDependencies
- GeneralizedNewtypeDeriving
- LambdaCase
- MultiParamTypeClasses
- MultiWayIf
- NamedFieldPuns
- OverloadedStrings
- PatternGuards
- RecordWildCards
- StandaloneDeriving
- TupleSections
- TypeApplications
- TypeFamilies
-}
module Blockchain.Fae.Internal.TX where
import Blockchain.Fae.Internal.Contract
import Blockchain.Fae.Internal.Crypto
import Blockchain.Fae.Internal.Exceptions
import Blockchain.Fae.Internal.IDs
import Blockchain.Fae.Internal.Storage
import Blockchain.Fae.Internal.Transaction
import Control.DeepSeq
import Control.Monad.State
import Data.ByteString (ByteString)
import Data.Functor.Identity
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Proxy
import Data.Typeable
import GHC.Generics
import Language.Haskell.Interpreter hiding (set,get)
import qualified Language.Haskell.Interpreter as Int (set,get)
import Language.Haskell.Interpreter.Unsafe as Int
import System.Environment
import System.FilePath
data TX =
TX
{
isReward :: Bool,
txID :: TransactionID,
txMaterials :: InputMaterials,
inputs :: [Input],
pubKeys :: Signers,
fallback :: [String]
}
deriving (Generic)
newtype UnquotedString = UnquotedString String
newtype WrappedByteString =
WrappedByteString { getWrappedByteString :: ByteString }
type FaeInterpretT m = InterpreterT (FaeStorageT m)
instance Serialize TX
instance Digestible TX
instance NFData TX
instance Show UnquotedString where
show (UnquotedString s) = s
instance (Monad m) => MonadState Storage (FaeInterpretT m) where
state = lift . state
put = lift . put
get = lift get
load - up time for the first transaction is pretty short ; subsequent
interpretTX ::
(Typeable m, MonadMask m, MonadIO m) =>
TX -> FaeInterpretT m ()
interpretTX TX{..} = do
faeInterpret [txModule] expr $ \f -> f txMaterials inputs txID pubKeys isReward
where
txModule = mkTXModuleName txID
@" . "@ is /not/ always included in the search path .
expr = unwords
[
"runTransaction",
"body",
show $ UnquotedString <$> fallback
]
interpretImportedValue ::
(Typeable m, MonadMask m, MonadIO m) => ExportData -> FaeInterpretT m ()
interpretImportedValue ExportData{..} =
faeInterpret neededModules runString $
\f -> f (WrappedByteString exportedValue) exportedCID exportStatus
where
runString = unwords
[
"addImportedValue",
".",
"importValueThrow @(" ++ exportValType ++ ")"
]
importValueThrow ::
forall a m.
(Exportable a, MonadState Escrows m) => WrappedByteString -> m a
importValueThrow (WrappedByteString bs) =
fromMaybe (throw $ CantImport bs rep) <$> liftEscrowState (importValue bs)
where rep = typeRep $ Proxy @a
faeInterpret ::
(Typeable m, MonadMask m, MonadIO m, Typeable a) =>
[String] ->
String ->
(a -> FaeStorage b) ->
FaeInterpretT m b
faeInterpret moduleNames runString apply = handle fixGHCErrors $ do
loadModules $ filter isTXModule moduleNames
setImports imports
act <- interpret runString infer
liftFaeStorage $ apply act
where
imports =
"Blockchain.Fae.Internal" :
"Prelude" :
filter (not . isInternalModule) moduleNames
isTXModule = isPrefixOf "Blockchain.Fae.Transactions.TX"
isInternalModule = isPrefixOf "Blockchain.Fae.Internal"
fixGHCErrors (WontCompile []) = throw $ InterpretException "Compilation error"
fixGHCErrors (WontCompile (ghcE : _)) =
throw $ InterpretException $ errMsg ghcE
fixGHCErrors (UnknownError e) = throw $ InterpretException e
fixGHCErrors (NotAllowed e) = throw $ InterpretException e
fixGHCErrors (GhcException e) = throw $ InterpretException e
liftFaeStorage = lift . mapStateT (return . runIdentity) . getFaeStorage
runFaeInterpret :: (MonadMask m, MonadIO m) => FaeInterpretT m a -> m a
runFaeInterpret x = do
ghcLibdirM <- liftIO $ lookupEnv "GHC_LIBDIR"
fmap (either throw id) . runStorageT . run ghcLibdirM args $ Int.set opts >> x
where
run = maybe
unsafeRunInterpreterWithArgs
(flip unsafeRunInterpreterWithArgsLibdir)
args =
"-Werror=orphans" :
"-fpackage-trust" : map ("-trust " ++) trustedPackages
opts =
[
installedModulesInScope := False,
languageExtensions :=
[
BangPatterns,
DeriveDataTypeable,
DeriveGeneric,
FlexibleContexts,
FlexibleInstances,
FunctionalDependencies,
LambdaCase,
MultiParamTypeClasses,
MultiWayIf,
NamedFieldPuns,
OverloadedStrings,
PatternGuards,
RecordWildCards,
Safe,
StandaloneDeriving,
TupleSections,
TypeApplications,
TypeFamilies
]
]
trustedPackages =
[
"array",
"base",
"bytestring",
"containers",
"fae",
"filepath",
"transformers",
"pretty"
]
mkTXIDName :: TransactionID -> String
mkTXIDName = ("TX" ++) . show
mkTXPathParts :: TransactionID -> [String]
mkTXPathParts txID = ["Blockchain", "Fae", "Transactions", mkTXIDName txID]
mkTXModuleName :: TransactionID -> String
mkTXModuleName = intercalate "." . mkTXPathParts
|
c82699c3676cdacd77035c2af919010b42ca6e3772acb9e4788bcc49dccacd38 | gfour/gic | addsx.hs | result :: Int
result = f sq 10 ;
sq :: Int -> Int
sq c = c * c ;
add :: Int -> Int -> Int
add a b = a + b ;
f :: (Int -> Int) -> Int -> Int
f s x = if (x <= 0) then s x else f (add (s x)) (x-1)
| null | https://raw.githubusercontent.com/gfour/gic/d5f2e506b31a1a28e02ca54af9610b3d8d618e9a/Examples/Data/addsx.hs | haskell | result :: Int
result = f sq 10 ;
sq :: Int -> Int
sq c = c * c ;
add :: Int -> Int -> Int
add a b = a + b ;
f :: (Int -> Int) -> Int -> Int
f s x = if (x <= 0) then s x else f (add (s x)) (x-1)
| |
411b8a82446abb836ff8477fab7723465333b2ea9ac3293f5a43b43d84b0401b | rtoy/cmucl | boot17.lisp | ;; Boot file for adding *runtime-features*
(in-package :sys)
(defvar *runtime-features* nil) | null | https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/bootfiles/18e/boot17.lisp | lisp | Boot file for adding *runtime-features* | (in-package :sys)
(defvar *runtime-features* nil) |
1beb0012e21c297f1c9dbbafd612b777ff227f5135f41f91d2c96961f1938c1a | oxidizing/sihl | email_mariadb.ml | let services =
[ Sihl.Database.Migration.MariaDb.register []
; Sihl_email.Template.MariaDb.register ()
; Sihl_email.Smtp.register ()
]
;;
module Test = Email.Make (Sihl_email.Smtp) (Sihl_email.Template.MariaDb)
let () =
Sihl.Configuration.read_string "DATABASE_URL_TEST_MARIADB"
|> Option.value ~default:"mariadb:password@127.0.0.1:3306/dev"
|> Unix.putenv "DATABASE_URL";
Unix.putenv "SIHL_ENV" "test";
Logs.set_level (Sihl.Log.get_log_level ());
Logs.set_reporter (Sihl.Log.cli_reporter ());
Lwt_main.run
(let%lwt _ = Sihl.Container.start_services services in
let%lwt () = Sihl.Database.Migration.MariaDb.run_all () in
Alcotest_lwt.run "mariadb" Test.suite)
;;
| null | https://raw.githubusercontent.com/oxidizing/sihl/439d60b7af290070be0237ffe4dfb7d34aceb4e0/sihl-email/test/email_mariadb.ml | ocaml | let services =
[ Sihl.Database.Migration.MariaDb.register []
; Sihl_email.Template.MariaDb.register ()
; Sihl_email.Smtp.register ()
]
;;
module Test = Email.Make (Sihl_email.Smtp) (Sihl_email.Template.MariaDb)
let () =
Sihl.Configuration.read_string "DATABASE_URL_TEST_MARIADB"
|> Option.value ~default:"mariadb:password@127.0.0.1:3306/dev"
|> Unix.putenv "DATABASE_URL";
Unix.putenv "SIHL_ENV" "test";
Logs.set_level (Sihl.Log.get_log_level ());
Logs.set_reporter (Sihl.Log.cli_reporter ());
Lwt_main.run
(let%lwt _ = Sihl.Container.start_services services in
let%lwt () = Sihl.Database.Migration.MariaDb.run_all () in
Alcotest_lwt.run "mariadb" Test.suite)
;;
| |
c0532689ad2119c0bda3535adc3f87c293bf657ff37fc624b578dd1093e35ad7 | yzhs/ocamlllvm | pparse.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ Id$
open Format
exception Error
(* Optionally preprocess a source file *)
let preprocess sourcefile =
match !Clflags.preprocessor with
None -> sourcefile
| Some pp ->
let tmpfile = Filename.temp_file "camlpp" "" in
let comm = Printf.sprintf "%s %s > %s"
pp (Filename.quote sourcefile) tmpfile
in
if Ccomp.command comm <> 0 then begin
Misc.remove_file tmpfile;
raise Error;
end;
tmpfile
let remove_preprocessed inputfile =
match !Clflags.preprocessor with
None -> ()
| Some _ -> Misc.remove_file inputfile
let remove_preprocessed_if_ast inputfile =
match !Clflags.preprocessor with
None -> ()
| Some _ ->
if inputfile <> !Location.input_name then Misc.remove_file inputfile
Parse a file or get a dumped syntax tree in it
exception Outdated_version
let file ppf inputfile parse_fun ast_magic =
let ic = open_in_bin inputfile in
let is_ast_file =
try
let buffer = String.create (String.length ast_magic) in
really_input ic buffer 0 (String.length ast_magic);
if buffer = ast_magic then true
else if String.sub buffer 0 9 = String.sub ast_magic 0 9 then
raise Outdated_version
else false
with
Outdated_version ->
Misc.fatal_error "Ocaml and preprocessor have incompatible versions"
| _ -> false
in
let ast =
try
if is_ast_file then begin
if !Clflags.fast then
fprintf ppf "@[Warning: %s@]@."
"option -unsafe used with a preprocessor returning a syntax tree";
Location.input_name := input_value ic;
input_value ic
end else begin
seek_in ic 0;
Location.input_name := inputfile;
let lexbuf = Lexing.from_channel ic in
Location.init lexbuf inputfile;
parse_fun lexbuf
end
with x -> close_in ic; raise x
in
close_in ic;
ast
| null | https://raw.githubusercontent.com/yzhs/ocamlllvm/45cbf449d81f2ef9d234968e49a4305aaa39ace2/src/driver/pparse.ml | ocaml | *********************************************************************
Objective Caml
*********************************************************************
Optionally preprocess a source file | , projet Cristal , INRIA Rocquencourt
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ Id$
open Format
exception Error
let preprocess sourcefile =
match !Clflags.preprocessor with
None -> sourcefile
| Some pp ->
let tmpfile = Filename.temp_file "camlpp" "" in
let comm = Printf.sprintf "%s %s > %s"
pp (Filename.quote sourcefile) tmpfile
in
if Ccomp.command comm <> 0 then begin
Misc.remove_file tmpfile;
raise Error;
end;
tmpfile
let remove_preprocessed inputfile =
match !Clflags.preprocessor with
None -> ()
| Some _ -> Misc.remove_file inputfile
let remove_preprocessed_if_ast inputfile =
match !Clflags.preprocessor with
None -> ()
| Some _ ->
if inputfile <> !Location.input_name then Misc.remove_file inputfile
Parse a file or get a dumped syntax tree in it
exception Outdated_version
let file ppf inputfile parse_fun ast_magic =
let ic = open_in_bin inputfile in
let is_ast_file =
try
let buffer = String.create (String.length ast_magic) in
really_input ic buffer 0 (String.length ast_magic);
if buffer = ast_magic then true
else if String.sub buffer 0 9 = String.sub ast_magic 0 9 then
raise Outdated_version
else false
with
Outdated_version ->
Misc.fatal_error "Ocaml and preprocessor have incompatible versions"
| _ -> false
in
let ast =
try
if is_ast_file then begin
if !Clflags.fast then
fprintf ppf "@[Warning: %s@]@."
"option -unsafe used with a preprocessor returning a syntax tree";
Location.input_name := input_value ic;
input_value ic
end else begin
seek_in ic 0;
Location.input_name := inputfile;
let lexbuf = Lexing.from_channel ic in
Location.init lexbuf inputfile;
parse_fun lexbuf
end
with x -> close_in ic; raise x
in
close_in ic;
ast
|
f1ce2d00d9552f03ea3dc5a014be7eb76317db24f2dc1fdad20f851e3741732e | txyyss/Project-Euler | Euler086.hs | A spider , S , sits in one corner of a cuboid room , measuring 6 by 5
by 3 , and a fly , F , sits in the opposite corner . By travelling on
-- the surfaces of the room the shortest "straight line" distance from
S to F is 10 and the path is shown on the diagram .
However , there are up to three " shortest " path candidates for any
given cuboid and the shortest route does n't always have integer
-- length.
-- By considering all cuboid rooms with integer dimensions, up to a
maximum size of M by M by M , there are exactly 2060 cuboids for
-- which the shortest route has integer length when M=100, and this is
the least value of M for which the number of solutions first
exceeds two thousand ; the number of solutions is 1975 when M=99 .
Find the least value of M such that the number of solutions first
exceeds one million .
module Euler086 where
import Data.List
import Data.Maybe
isSquare :: Integer -> Bool
isSquare n = n == r * r
where r = helper n
helper m = fst . head . dropWhile (\(a,b) -> a + 1 /= b && a /= b) $ iterate (\(_,x) -> (x, (x + div m x) `div` 2)) (2, 1)
perfectUnder :: Integer -> Integer
perfectUnder c = sum $ map (\n-> min (n-1) c + 1 + n `div` 2 - n) [n | n<-[2..c * 2], isSquare (n * n + c * c)]
numOfIntPaths = scanl (+) 0 $ map perfectUnder [1..]
result086 = fromJust $ findIndex (> 1000000) numOfIntPaths
| null | https://raw.githubusercontent.com/txyyss/Project-Euler/d2f41dad429013868445c1c9c1c270b951550ee9/Euler086.hs | haskell | the surfaces of the room the shortest "straight line" distance from
length.
By considering all cuboid rooms with integer dimensions, up to a
which the shortest route has integer length when M=100, and this is | A spider , S , sits in one corner of a cuboid room , measuring 6 by 5
by 3 , and a fly , F , sits in the opposite corner . By travelling on
S to F is 10 and the path is shown on the diagram .
However , there are up to three " shortest " path candidates for any
given cuboid and the shortest route does n't always have integer
maximum size of M by M by M , there are exactly 2060 cuboids for
the least value of M for which the number of solutions first
exceeds two thousand ; the number of solutions is 1975 when M=99 .
Find the least value of M such that the number of solutions first
exceeds one million .
module Euler086 where
import Data.List
import Data.Maybe
isSquare :: Integer -> Bool
isSquare n = n == r * r
where r = helper n
helper m = fst . head . dropWhile (\(a,b) -> a + 1 /= b && a /= b) $ iterate (\(_,x) -> (x, (x + div m x) `div` 2)) (2, 1)
perfectUnder :: Integer -> Integer
perfectUnder c = sum $ map (\n-> min (n-1) c + 1 + n `div` 2 - n) [n | n<-[2..c * 2], isSquare (n * n + c * c)]
numOfIntPaths = scanl (+) 0 $ map perfectUnder [1..]
result086 = fromJust $ findIndex (> 1000000) numOfIntPaths
|
000e33af12c64863d82275e9469d88322f5c4f7b9e7eda92adac998dedb3266e | mbutterick/beautiful-racket | main.rkt | #lang br/quicklang
(require brag/support "grammar.rkt" xml)
(provide (all-from-out br/quicklang) (all-defined-out) xexpr?)
(module+ reader
(provide read-syntax))
(define-lex-abbrev xml-reserved
(:or "<" "/>" "</" ">" "<!--" "-->" "=" "\""))
(define tokenize
(lexer
[(:+ whitespace) (token 'SP " ")]
["&" (token 'AMP "&")]
["<" (token 'LT "<")]
[">" (token 'GT ">")]
[xml-reserved lexeme]
[(:or alphabetic numeric) (token 'ALPHANUMERIC lexeme)]
[any-char (token 'OTHER lexeme)]))
(define (top . contents) `(root ,@contents))
(define (content . xs) xs)
(define-cases tagged-element
[(_ id attrs) (list id attrs)]
[(_ id attrs contents id-end)
(unless (eq? id id-end)
(raise-argument-error 'tagged-element "matched tags" (list id id-end)))
(list* id attrs contents)])
(define (attrs . attr-list) attr-list)
(define (attr id value) (list id value))
(define (string . strs) (string-join strs ""))
(define (identifier . strs)
(string->symbol (apply string strs)))
(define (read-syntax src ip)
(define parse-tree (parse (λ () (tokenize ip))))
(strip-context
(with-syntax ([PT parse-tree])
#'(module mel xmlish-demo
(println PT)
(displayln (if (xexpr? PT)
"YES, it's an X-expression"
"NO, it's not an X-expression")))))) | null | https://raw.githubusercontent.com/mbutterick/beautiful-racket/f0e2cb5b325733b3f9cbd554cc7d2bb236af9ee9/beautiful-racket-demo/xmlish-demo/main.rkt | racket | #lang br/quicklang
(require brag/support "grammar.rkt" xml)
(provide (all-from-out br/quicklang) (all-defined-out) xexpr?)
(module+ reader
(provide read-syntax))
(define-lex-abbrev xml-reserved
(:or "<" "/>" "</" ">" "<!--" "-->" "=" "\""))
(define tokenize
(lexer
[(:+ whitespace) (token 'SP " ")]
["&" (token 'AMP "&")]
["<" (token 'LT "<")]
[">" (token 'GT ">")]
[xml-reserved lexeme]
[(:or alphabetic numeric) (token 'ALPHANUMERIC lexeme)]
[any-char (token 'OTHER lexeme)]))
(define (top . contents) `(root ,@contents))
(define (content . xs) xs)
(define-cases tagged-element
[(_ id attrs) (list id attrs)]
[(_ id attrs contents id-end)
(unless (eq? id id-end)
(raise-argument-error 'tagged-element "matched tags" (list id id-end)))
(list* id attrs contents)])
(define (attrs . attr-list) attr-list)
(define (attr id value) (list id value))
(define (string . strs) (string-join strs ""))
(define (identifier . strs)
(string->symbol (apply string strs)))
(define (read-syntax src ip)
(define parse-tree (parse (λ () (tokenize ip))))
(strip-context
(with-syntax ([PT parse-tree])
#'(module mel xmlish-demo
(println PT)
(displayln (if (xexpr? PT)
"YES, it's an X-expression"
"NO, it's not an X-expression")))))) | |
4d40c0452bf315bc1f1785688a0b8eb1f731b50399806cbfc7748454032e709d | jherrlin/guitar-theory-training | scales.cljs | (ns v2.se.jherrlin.music-theory.webapp.scales
(:require
[clojure.set :as set]
[clojure.string :as str]
[re-frame.core :as re-frame]
[reitit.frontend.easy :as rfe]
[se.jherrlin.music-theory :as music-theory]
[v2.se.jherrlin.music-theory.definitions :as definitions]
[v2.se.jherrlin.music-theory.intervals :as intervals]
[v2.se.jherrlin.music-theory.utils
:refer [fformat]
:as utils]))
(def events-
[{:n ::scale}
{:n ::tone-or-interval
:s (fn [db [n']] (get db n' :tone))}])
(doseq [{:keys [n s e]} events-]
(re-frame/reg-sub n (or s (fn [db [n']] (get db n'))))
(re-frame/reg-event-db n (or e (fn [db [_ e]] (assoc db n e)))))
(defn scales-view []
(let [tuning-name @(re-frame/subscribe [:tuning-name])
tuning-tones @(re-frame/subscribe [:tuning-tones])
nr-of-frets @(re-frame/subscribe [:nr-of-frets])
scale @(re-frame/subscribe [::scale])
key-of @(re-frame/subscribe [:key-of])
tone-or-interval @(re-frame/subscribe [::tone-or-interval])]
(when (and scale key-of)
(let [{intervals :scale/intervals
indexes :scale/indexes}
(get @definitions/scales-atom scale)
tones ((utils/juxt-indexes-and-intervals indexes intervals)
(utils/rotate-until #(% key-of) utils/all-tones))]
[:div
;; Links to keys
[:div
(for [{key-of' :key-of
:keys [url-name title]}
(->> (music-theory/find-root-p :a)
(map (fn [x] {:key-of x
:url-name (-> x name str/lower-case (str/replace "#" "sharp"))
:title (-> x name str/capitalize)})))]
^{:key url-name}
[:div {:style {:margin-right "10px" :display "inline"}}
[:a {:href (rfe/href :v3/scale {:scale scale :key-of key-of' :instrument tuning-name})}
[:button
{:disabled (= key-of' key-of)}
title]]])]
[:br]
;; Links to scales
[:div
(for [{title :scale/title
id :scale/id}
(->> @definitions/scales-atom
vals
(sort-by :scale/order))]
^{:key (str title "-scale")}
[:div {:style {:margin-right "10px" :display "inline"}}
[:a {:href (rfe/href :v3/scale {:scale id :key-of key-of :instrument tuning-name})}
[:button
{:disabled (= scale id)}
title]]])]
;; Highlight tones
[:div {:style {:margin-top "1em"
:display "flex"
:align-items "center"}}
(for [{:keys [tone match?]}
(let [tones-set (set tones)]
(->> utils/all-tones
(utils/rotate-until #(% key-of))
(map (fn [tone]
(cond-> {:tone tone}
(seq (set/intersection tones-set tone))
(assoc :match? true))))))]
^{:key (str tone "somekey")}
[:div {:style {:width "4.5em"
:font-size "0.9em"}}
(for [t' (sort-by (fn [x]
(let [x (str x)]
(cond
(and (= (count x) 3) (str/includes? x "#"))
1
(= (count x) 3)
2
:else 0))) tone)]
^{:key (str tone t')}
[:div {:style {:margin-top "0em"}}
[:div
{:style {:color (if-not match? "grey")
:font-weight (if match? "bold")}}
(-> t' name str/capitalize)]])])]
;; Scale name
(let [{title :scale/title}
(get @definitions/scales-atom scale)]
[:div {:style {:margin-top "1em"}}
[:h2 (str (-> key-of name str/capitalize) " - " (-> title str/capitalize))]])
[:br]
;; Intervals
[:pre {:style {:overflow-x "auto"}}
(->> (map
(fn [interval index]
(str (fformat "%8s" interval) " -> " (-> index name str/capitalize)))
intervals
((utils/juxt-indexes-and-intervals indexes intervals)
(utils/rotate-until #(% key-of) definitions/all-tones)))
(str/join "\n")
(apply str)
(str "Interval -> Tone\n"))]
;; Scale on fretboard
[:button
{:on-click
#(re-frame/dispatch
[::tone-or-interval
(if (= tone-or-interval :tone)
:interval
:tone)])}
(str
"Show as "
(if (= tone-or-interval :tone)
"intervals"
"tones"))]
[:code
[:pre {:style {:overflow-x "auto"}}
(utils/fretboard-str
(utils/fretboard-strings
utils/rotate-until
utils/all-tones
tuning-tones
nr-of-frets)
(if (= tone-or-interval :tone)
(partial
utils/fretboard-tone-str-chord-f tones)
(partial
utils/fretboard-tone-str-chord-f-2
(mapv vector tones intervals))))]]
(let [scale-patterns
(->> @definitions/scale-patterns-atom
(vals)
(filter (comp #{scale} :scale-pattern/scale))
(filter (comp #{tuning-tones} :scale-pattern/tuning))
(sort-by :scale-pattern/order))]
(when (seq scale-patterns)
[:<>
[:h3 "Patterns"]
[:div
(for [{id :scale-pattern/id
pattern :scale-pattern/pattern}
scale-patterns]
^{:key (-> id name)}
[:div {:style {:margin-top "2em"}}
[:pre {:style {:overflow-x "auto"}}
(utils/fretboard-str
(utils/find-pattern
definitions/all-tones
intervals/intervals-map-by-function
(utils/fretboard-strings
utils/rotate-until
definitions/all-tones
tuning-tones
nr-of-frets)
key-of
pattern)
(if (= tone-or-interval :tone)
utils/fretboard-tone-str-pattern-f
utils/fretboard-interval-f))]])]]))
;; Chords to scale
[:h3 "Chords to scale"]
(for [{chord-title :chord/title
chord-id :chord/id}
(let [{scale-indexes :scale/indexes}
(get @definitions/scales-atom scale)]
(->> @definitions/chords-atom
(vals)
(sort-by :chord/order)
(filter (fn [{:chord/keys [indexes]}]
(set/subset? (set indexes) (set scale-indexes))))))]
^{:key (str chord-title)}
[:div {:style {:margin-right "10px" :display "inline"}}
[:a {:href (rfe/href :v3/chord {:chord-name chord-id :key-of key-of :instrument tuning-name})}
[:button chord-title]]])]))))
(def routes
[["/v2/scale/:scale/:key-of"
{:name :v2/scale
:view [scales-view]
:controllers
[{:parameters {:path [:scale :key-of]}
:start (fn [{{:keys [scale key-of]} :path}]
(let [scale' (keyword scale)
key-of' (keyword key-of)]
(js/console.log "Entering scale v2:" scale key-of)
(re-frame/dispatch [:push-state
:v3/scale
{:key-of key-of'
:scale scale'
:instrument @(re-frame/subscribe [:tuning-name])}])))
:stop (fn [& params] (js/console.log "Leaving scale v2"))}]}]
["/v3/:instrument/scale/:scale/:key-of"
{:name :v3/scale
:view [scales-view]
:controllers
[{:parameters {:path [:scale :key-of :instrument]}
:start (fn [{{:keys [scale key-of instrument]} :path}]
(let [scale' (keyword scale)
key-of' (keyword key-of)]
(js/console.log "Entering scale v3:" scale key-of)
(re-frame/dispatch [::scale scale'])
(re-frame/dispatch [:key-of key-of'])
(re-frame/dispatch [:tuning-name (keyword instrument)])))
:stop (fn [& params] (js/console.log "Leaving scale v3"))}]}]])
| null | https://raw.githubusercontent.com/jherrlin/guitar-theory-training/e97fa342c061954799f26aeb680fc721efd3017e/src/v2/se/jherrlin/music_theory/webapp/scales.cljs | clojure | Links to keys
Links to scales
Highlight tones
Scale name
Intervals
Scale on fretboard
Chords to scale | (ns v2.se.jherrlin.music-theory.webapp.scales
(:require
[clojure.set :as set]
[clojure.string :as str]
[re-frame.core :as re-frame]
[reitit.frontend.easy :as rfe]
[se.jherrlin.music-theory :as music-theory]
[v2.se.jherrlin.music-theory.definitions :as definitions]
[v2.se.jherrlin.music-theory.intervals :as intervals]
[v2.se.jherrlin.music-theory.utils
:refer [fformat]
:as utils]))
(def events-
[{:n ::scale}
{:n ::tone-or-interval
:s (fn [db [n']] (get db n' :tone))}])
(doseq [{:keys [n s e]} events-]
(re-frame/reg-sub n (or s (fn [db [n']] (get db n'))))
(re-frame/reg-event-db n (or e (fn [db [_ e]] (assoc db n e)))))
(defn scales-view []
(let [tuning-name @(re-frame/subscribe [:tuning-name])
tuning-tones @(re-frame/subscribe [:tuning-tones])
nr-of-frets @(re-frame/subscribe [:nr-of-frets])
scale @(re-frame/subscribe [::scale])
key-of @(re-frame/subscribe [:key-of])
tone-or-interval @(re-frame/subscribe [::tone-or-interval])]
(when (and scale key-of)
(let [{intervals :scale/intervals
indexes :scale/indexes}
(get @definitions/scales-atom scale)
tones ((utils/juxt-indexes-and-intervals indexes intervals)
(utils/rotate-until #(% key-of) utils/all-tones))]
[:div
[:div
(for [{key-of' :key-of
:keys [url-name title]}
(->> (music-theory/find-root-p :a)
(map (fn [x] {:key-of x
:url-name (-> x name str/lower-case (str/replace "#" "sharp"))
:title (-> x name str/capitalize)})))]
^{:key url-name}
[:div {:style {:margin-right "10px" :display "inline"}}
[:a {:href (rfe/href :v3/scale {:scale scale :key-of key-of' :instrument tuning-name})}
[:button
{:disabled (= key-of' key-of)}
title]]])]
[:br]
[:div
(for [{title :scale/title
id :scale/id}
(->> @definitions/scales-atom
vals
(sort-by :scale/order))]
^{:key (str title "-scale")}
[:div {:style {:margin-right "10px" :display "inline"}}
[:a {:href (rfe/href :v3/scale {:scale id :key-of key-of :instrument tuning-name})}
[:button
{:disabled (= scale id)}
title]]])]
[:div {:style {:margin-top "1em"
:display "flex"
:align-items "center"}}
(for [{:keys [tone match?]}
(let [tones-set (set tones)]
(->> utils/all-tones
(utils/rotate-until #(% key-of))
(map (fn [tone]
(cond-> {:tone tone}
(seq (set/intersection tones-set tone))
(assoc :match? true))))))]
^{:key (str tone "somekey")}
[:div {:style {:width "4.5em"
:font-size "0.9em"}}
(for [t' (sort-by (fn [x]
(let [x (str x)]
(cond
(and (= (count x) 3) (str/includes? x "#"))
1
(= (count x) 3)
2
:else 0))) tone)]
^{:key (str tone t')}
[:div {:style {:margin-top "0em"}}
[:div
{:style {:color (if-not match? "grey")
:font-weight (if match? "bold")}}
(-> t' name str/capitalize)]])])]
(let [{title :scale/title}
(get @definitions/scales-atom scale)]
[:div {:style {:margin-top "1em"}}
[:h2 (str (-> key-of name str/capitalize) " - " (-> title str/capitalize))]])
[:br]
[:pre {:style {:overflow-x "auto"}}
(->> (map
(fn [interval index]
(str (fformat "%8s" interval) " -> " (-> index name str/capitalize)))
intervals
((utils/juxt-indexes-and-intervals indexes intervals)
(utils/rotate-until #(% key-of) definitions/all-tones)))
(str/join "\n")
(apply str)
(str "Interval -> Tone\n"))]
[:button
{:on-click
#(re-frame/dispatch
[::tone-or-interval
(if (= tone-or-interval :tone)
:interval
:tone)])}
(str
"Show as "
(if (= tone-or-interval :tone)
"intervals"
"tones"))]
[:code
[:pre {:style {:overflow-x "auto"}}
(utils/fretboard-str
(utils/fretboard-strings
utils/rotate-until
utils/all-tones
tuning-tones
nr-of-frets)
(if (= tone-or-interval :tone)
(partial
utils/fretboard-tone-str-chord-f tones)
(partial
utils/fretboard-tone-str-chord-f-2
(mapv vector tones intervals))))]]
(let [scale-patterns
(->> @definitions/scale-patterns-atom
(vals)
(filter (comp #{scale} :scale-pattern/scale))
(filter (comp #{tuning-tones} :scale-pattern/tuning))
(sort-by :scale-pattern/order))]
(when (seq scale-patterns)
[:<>
[:h3 "Patterns"]
[:div
(for [{id :scale-pattern/id
pattern :scale-pattern/pattern}
scale-patterns]
^{:key (-> id name)}
[:div {:style {:margin-top "2em"}}
[:pre {:style {:overflow-x "auto"}}
(utils/fretboard-str
(utils/find-pattern
definitions/all-tones
intervals/intervals-map-by-function
(utils/fretboard-strings
utils/rotate-until
definitions/all-tones
tuning-tones
nr-of-frets)
key-of
pattern)
(if (= tone-or-interval :tone)
utils/fretboard-tone-str-pattern-f
utils/fretboard-interval-f))]])]]))
[:h3 "Chords to scale"]
(for [{chord-title :chord/title
chord-id :chord/id}
(let [{scale-indexes :scale/indexes}
(get @definitions/scales-atom scale)]
(->> @definitions/chords-atom
(vals)
(sort-by :chord/order)
(filter (fn [{:chord/keys [indexes]}]
(set/subset? (set indexes) (set scale-indexes))))))]
^{:key (str chord-title)}
[:div {:style {:margin-right "10px" :display "inline"}}
[:a {:href (rfe/href :v3/chord {:chord-name chord-id :key-of key-of :instrument tuning-name})}
[:button chord-title]]])]))))
(def routes
[["/v2/scale/:scale/:key-of"
{:name :v2/scale
:view [scales-view]
:controllers
[{:parameters {:path [:scale :key-of]}
:start (fn [{{:keys [scale key-of]} :path}]
(let [scale' (keyword scale)
key-of' (keyword key-of)]
(js/console.log "Entering scale v2:" scale key-of)
(re-frame/dispatch [:push-state
:v3/scale
{:key-of key-of'
:scale scale'
:instrument @(re-frame/subscribe [:tuning-name])}])))
:stop (fn [& params] (js/console.log "Leaving scale v2"))}]}]
["/v3/:instrument/scale/:scale/:key-of"
{:name :v3/scale
:view [scales-view]
:controllers
[{:parameters {:path [:scale :key-of :instrument]}
:start (fn [{{:keys [scale key-of instrument]} :path}]
(let [scale' (keyword scale)
key-of' (keyword key-of)]
(js/console.log "Entering scale v3:" scale key-of)
(re-frame/dispatch [::scale scale'])
(re-frame/dispatch [:key-of key-of'])
(re-frame/dispatch [:tuning-name (keyword instrument)])))
:stop (fn [& params] (js/console.log "Leaving scale v3"))}]}]])
|
db0131987c4884ae37eda87b83ce10ef469fb4b1dea70e0170477eedb07f9b30 | dalaing/little-languages | Value.hs | module Term.Eval.Value where
import Data.Foldable (asum)
import Term
valueTmInt :: Term
-> Maybe Term
valueTmInt (TmInt i) =
Just $ TmInt i
valueTmInt _ =
Nothing
valueRules :: [Term -> Maybe Term]
valueRules =
[valueTmInt]
value :: Term
-> Maybe Term
value tm =
asum .
map ($ tm) $
valueRules
| null | https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/old/unityped/i/src/Term/Eval/Value.hs | haskell | module Term.Eval.Value where
import Data.Foldable (asum)
import Term
valueTmInt :: Term
-> Maybe Term
valueTmInt (TmInt i) =
Just $ TmInt i
valueTmInt _ =
Nothing
valueRules :: [Term -> Maybe Term]
valueRules =
[valueTmInt]
value :: Term
-> Maybe Term
value tm =
asum .
map ($ tm) $
valueRules
| |
5306a0b55b3f6c86b444ffabe90048b4ceace970a629f7744d6e2c1bb66954ee | discus-lang/ddc | Initialize.hs |
-- | Adding code to initialise the runtime system.
module DDC.Core.Salt.Transform.Initialize
(initializeModule)
where
import DDC.Core.Salt.Compounds
import DDC.Core.Salt.Runtime
import DDC.Core.Salt.Name
import DDC.Core.Module
import DDC.Core.Exp.Annot
import Data.List
---------------------------------------------------------------------------------------------------
| If this it the Main module , then insert a main function for the posix
-- entry point that initialises the runtime system and calls the real main function.
--
Returns Nothing if this is the Main module , but there is no main function .
--
initializeModule
:: Config
-> Module a Name
-> Maybe (Module a Name)
initializeModule config mm@ModuleCore{}
| isMainModule mm
= case initRuntimeTopX config (moduleBody mm) of
Nothing
-> Nothing
Just x'
-> Just $ mm
{ moduleExportValues = patchMainExports (moduleExportValues mm)
, moduleBody = x'}
| otherwise
= Just mm
---------------------------------------------------------------------------------------------------
-- | Patch the list of export definitions to export our wrapper instead
-- of the original main function.
patchMainExports
:: [(Name, ExportValue Name (Type Name))]
-> [(Name, ExportValue Name (Type Name))]
patchMainExports xx
= case xx of
[] -> []
(x : xs)
| (NameVar "main", ExportValueLocal mn n _ mArity) <- x
-> (NameVar "main", ExportValueLocal mn n tPosixMain mArity) : xs
| otherwise
-> x : patchMainExports xs
-- | Type of the POSIX main function.
tPosixMain :: Type Name
tPosixMain
= tNat `tFun` tAddr `tFun` tInt
---------------------------------------------------------------------------------------------------
| Takes the top - level let - bindings of amodule
-- and add code to initialise the runtime system.
initRuntimeTopX :: Config -> Exp a Name -> Maybe (Exp a Name)
initRuntimeTopX config xx
| XLet a (LRec bxs) x2 <- xx
, Just (bMainOrig, xMainOrig) <- find (isMainBind . fst) bxs
, bxs_cut <- filter (not . isMainBind . fst) bxs
, BName _ tMainOrig <- bMainOrig
= let
Rename the old main function to ' _ main$discus '
bMainOrig' = BName (NameVar "_main$discus") $ tMainOrig
-- The new entry point of the program is called 'main'.
bMainEntry = BName (NameVar "main") $ tPosixMain
xMainEntry = makeMainEntryX config a
in Just $ XLet a
(LRec $ bxs_cut
++ [ (bMainOrig', xMainOrig)
, (bMainEntry, xMainEntry)])
x2
-- This was supposed to be the main Module,
-- but there was no 'main' function for the program entry point.
| otherwise
= Nothing
-- | Check whether this is the bind for the 'main' function.
isMainBind :: Bind Name -> Bool
isMainBind bb
= case bb of
(BName (NameVar "main") _) -> True
_ -> False
-- | Make the posix main function,
-- which is the entry point to the executable.
makeMainEntryX :: Config -> a -> Exp a Name
makeMainEntryX config a
= let xU = xAllocBoxed a rTop 0 (xWord a 0 32) (xNat a 0)
-- TODO: info table index.
in XLam a (BName (NameVar "argc") tNat)
$ XLam a (BName (NameVar "argv") tAddr)
Initialize the runtime system .
$ XLLet a (BNone tUnit)
(xddcInit a (configHeapSize config)
(XVar a (UName (NameVar "argc")))
(XVar a (UName (NameVar "argv"))))
-- Call the user level main function.
$ XLLet a (BNone (tBot kData))
(xApps a (XVar a (UName (NameVar "_main$discus"))) [RTerm xU])
-- Shut down the runtime system.
$ XLLet a (BNone tVoid)
(xddcExit a 0)
-- Inner dummy expression.
$ xInt a 0
| null | https://raw.githubusercontent.com/discus-lang/ddc/2baa1b4e2d43b6b02135257677671a83cb7384ac/src/s1/ddc-core-salt/DDC/Core/Salt/Transform/Initialize.hs | haskell | | Adding code to initialise the runtime system.
-------------------------------------------------------------------------------------------------
entry point that initialises the runtime system and calls the real main function.
-------------------------------------------------------------------------------------------------
| Patch the list of export definitions to export our wrapper instead
of the original main function.
| Type of the POSIX main function.
-------------------------------------------------------------------------------------------------
and add code to initialise the runtime system.
The new entry point of the program is called 'main'.
This was supposed to be the main Module,
but there was no 'main' function for the program entry point.
| Check whether this is the bind for the 'main' function.
| Make the posix main function,
which is the entry point to the executable.
TODO: info table index.
Call the user level main function.
Shut down the runtime system.
Inner dummy expression. |
module DDC.Core.Salt.Transform.Initialize
(initializeModule)
where
import DDC.Core.Salt.Compounds
import DDC.Core.Salt.Runtime
import DDC.Core.Salt.Name
import DDC.Core.Module
import DDC.Core.Exp.Annot
import Data.List
| If this it the Main module , then insert a main function for the posix
Returns Nothing if this is the Main module , but there is no main function .
initializeModule
:: Config
-> Module a Name
-> Maybe (Module a Name)
initializeModule config mm@ModuleCore{}
| isMainModule mm
= case initRuntimeTopX config (moduleBody mm) of
Nothing
-> Nothing
Just x'
-> Just $ mm
{ moduleExportValues = patchMainExports (moduleExportValues mm)
, moduleBody = x'}
| otherwise
= Just mm
patchMainExports
:: [(Name, ExportValue Name (Type Name))]
-> [(Name, ExportValue Name (Type Name))]
patchMainExports xx
= case xx of
[] -> []
(x : xs)
| (NameVar "main", ExportValueLocal mn n _ mArity) <- x
-> (NameVar "main", ExportValueLocal mn n tPosixMain mArity) : xs
| otherwise
-> x : patchMainExports xs
tPosixMain :: Type Name
tPosixMain
= tNat `tFun` tAddr `tFun` tInt
| Takes the top - level let - bindings of amodule
initRuntimeTopX :: Config -> Exp a Name -> Maybe (Exp a Name)
initRuntimeTopX config xx
| XLet a (LRec bxs) x2 <- xx
, Just (bMainOrig, xMainOrig) <- find (isMainBind . fst) bxs
, bxs_cut <- filter (not . isMainBind . fst) bxs
, BName _ tMainOrig <- bMainOrig
= let
Rename the old main function to ' _ main$discus '
bMainOrig' = BName (NameVar "_main$discus") $ tMainOrig
bMainEntry = BName (NameVar "main") $ tPosixMain
xMainEntry = makeMainEntryX config a
in Just $ XLet a
(LRec $ bxs_cut
++ [ (bMainOrig', xMainOrig)
, (bMainEntry, xMainEntry)])
x2
| otherwise
= Nothing
isMainBind :: Bind Name -> Bool
isMainBind bb
= case bb of
(BName (NameVar "main") _) -> True
_ -> False
makeMainEntryX :: Config -> a -> Exp a Name
makeMainEntryX config a
= let xU = xAllocBoxed a rTop 0 (xWord a 0 32) (xNat a 0)
in XLam a (BName (NameVar "argc") tNat)
$ XLam a (BName (NameVar "argv") tAddr)
Initialize the runtime system .
$ XLLet a (BNone tUnit)
(xddcInit a (configHeapSize config)
(XVar a (UName (NameVar "argc")))
(XVar a (UName (NameVar "argv"))))
$ XLLet a (BNone (tBot kData))
(xApps a (XVar a (UName (NameVar "_main$discus"))) [RTerm xU])
$ XLLet a (BNone tVoid)
(xddcExit a 0)
$ xInt a 0
|
187163bb34533cd3685e8060b8a87c47ca835757d6c3e9e0c15ad8235add79d9 | lambdabot/IOSpec | Echo.hs | Note that the Prelude and Test . IOSpec . Teletype both export
functions called and . To begin with , we hide the
-- definitions in the prelude and work with the pure specification.
import Prelude hiding (getChar, putChar)
import qualified Prelude (putStrLn)
import qualified Data.Stream as Stream
import Test.IOSpec hiding (putStrLn)
import Test.QuickCheck
import Data.Char (ord)
-- The echo function, as we have always known it
echo :: IOSpec Teletype ()
echo = getChar >>= putChar >> echo
-- It should echo any character entered at the teletype. This is
-- the behaviour we would expect echo to have. The Output data type
is defined in Test . IOSpec . Teletype and represents the observable
-- behaviour of a teletype interaction.
copy :: Effect ()
copy = ReadChar (\x -> Print x copy)
An auxiliary function that takes the first n elements printed to
-- the teletype.
takeOutput :: Int -> Effect () -> String
takeOutput 0 _ = ""
takeOutput (n + 1) (Print c xs) = c : takeOutput n xs
takeOutput _ _ = error "Echo.takeOutput"
-- withInput runs an Effect, passing the argument stream of
characters as the characters entered to stdin . Any effects left
-- over will be either Print statements, or a final Done result.
withInput :: Stream.Stream Char -> Effect a -> Effect a
withInput stdin (Done x) = Done x
withInput stdin (Print c e) = Print c (withInput stdin e)
withInput stdin (ReadChar f) = withInput (Stream.tail stdin)
(f (Stream.head stdin))
We can use QuickCheck to test if our echo function meets the
-- desired specification: that is that for every input the user
enters , every finite prefix of runTT echo input and copy input is
-- the same.
echoProp :: Stream.Stream Char -> Property
echoProp input =
forAll (choose (1,10000)) $ \n ->
takeOutput n (withInput input (evalIOSpec echo singleThreaded))
== takeOutput n (withInput input copy)
main = do
Prelude.putStrLn "Testing echo..."
quickCheck echoProp
-- Once we are satisfied with our definition of echo, we can change
our imports . Rather than importing Test . IOSpec . Teletype , we
import the " real " getChar and , as defined in the Prelude . | null | https://raw.githubusercontent.com/lambdabot/IOSpec/76235f77942ab7672f70fca4b9e133ef667606a4/examples/Echo.hs | haskell | definitions in the prelude and work with the pure specification.
The echo function, as we have always known it
It should echo any character entered at the teletype. This is
the behaviour we would expect echo to have. The Output data type
behaviour of a teletype interaction.
the teletype.
withInput runs an Effect, passing the argument stream of
over will be either Print statements, or a final Done result.
desired specification: that is that for every input the user
the same.
Once we are satisfied with our definition of echo, we can change | Note that the Prelude and Test . IOSpec . Teletype both export
functions called and . To begin with , we hide the
import Prelude hiding (getChar, putChar)
import qualified Prelude (putStrLn)
import qualified Data.Stream as Stream
import Test.IOSpec hiding (putStrLn)
import Test.QuickCheck
import Data.Char (ord)
echo :: IOSpec Teletype ()
echo = getChar >>= putChar >> echo
is defined in Test . IOSpec . Teletype and represents the observable
copy :: Effect ()
copy = ReadChar (\x -> Print x copy)
An auxiliary function that takes the first n elements printed to
takeOutput :: Int -> Effect () -> String
takeOutput 0 _ = ""
takeOutput (n + 1) (Print c xs) = c : takeOutput n xs
takeOutput _ _ = error "Echo.takeOutput"
characters as the characters entered to stdin . Any effects left
withInput :: Stream.Stream Char -> Effect a -> Effect a
withInput stdin (Done x) = Done x
withInput stdin (Print c e) = Print c (withInput stdin e)
withInput stdin (ReadChar f) = withInput (Stream.tail stdin)
(f (Stream.head stdin))
We can use QuickCheck to test if our echo function meets the
enters , every finite prefix of runTT echo input and copy input is
echoProp :: Stream.Stream Char -> Property
echoProp input =
forAll (choose (1,10000)) $ \n ->
takeOutput n (withInput input (evalIOSpec echo singleThreaded))
== takeOutput n (withInput input copy)
main = do
Prelude.putStrLn "Testing echo..."
quickCheck echoProp
our imports . Rather than importing Test . IOSpec . Teletype , we
import the " real " getChar and , as defined in the Prelude . |
f7d1dbe53d09c5dca87d05e730b45fc90e3ab0fbdfb8efc83ba69817a9f1cd58 | lilyball/projecteuler-ocaml | prob5.ml | open Misc
open Big_int
module Int = struct
type t = int
let compare = compare
end
module IntMap = Map.Make(Int)
let prime_factor_map n =
let factors = List.map int_of_big_int (prime_factors (big_int_of_int n)) in
let mapincr map key =
IntMap.add key (try succ (IntMap.find key map) with Not_found -> 1) map in
List.fold_left mapincr IntMap.empty factors
let print_int_map map =
print_string " [ [ " ;
let is_first = ref true in
IntMap.iter ( fun k v - > if not ! is_first then print_string " ; " ; is_first : = false ; Printf.printf " % d : % d " k v ) map ;
print_string " ] ] "
let print_int_map_endline map =
print_int_map map ;
print_newline ( )
print_string "[[";
let is_first = ref true in
IntMap.iter (fun k v -> if not !is_first then print_string "; "; is_first := false; Printf.printf "%d: %d" k v) map;
print_string "]]"
let print_int_map_endline map =
print_int_map map;
print_newline () *)
let map_to_list map =
let repeat i n =
let rec repeat_aux i n acc =
if n <= 0 then acc
else repeat_aux i (pred n) (i :: acc) in
repeat_aux i n [] in
List.rev (IntMap.fold (fun k v l -> (repeat k v) @ l) map [])
let list_product l =
List.fold_left ( * ) 1 l
let map_merge a b =
let map_find i map = try IntMap.find i map with Not_found -> 0 in
let elt_merge k v map = IntMap.add k (max v (map_find k b)) map in
IntMap.fold elt_merge a b
let _ =
let mmap = ref IntMap.empty in
for i = 1 to 20 do
mmap := map_merge !mmap (prime_factor_map i)
done;
print_int (list_product (map_to_list !mmap)); print_newline ()
| null | https://raw.githubusercontent.com/lilyball/projecteuler-ocaml/a88ed8355b565ad0726cfcac4916d2b80512da7a/prob5.ml | ocaml | open Misc
open Big_int
module Int = struct
type t = int
let compare = compare
end
module IntMap = Map.Make(Int)
let prime_factor_map n =
let factors = List.map int_of_big_int (prime_factors (big_int_of_int n)) in
let mapincr map key =
IntMap.add key (try succ (IntMap.find key map) with Not_found -> 1) map in
List.fold_left mapincr IntMap.empty factors
let print_int_map map =
print_string " [ [ " ;
let is_first = ref true in
IntMap.iter ( fun k v - > if not ! is_first then print_string " ; " ; is_first : = false ; Printf.printf " % d : % d " k v ) map ;
print_string " ] ] "
let print_int_map_endline map =
print_int_map map ;
print_newline ( )
print_string "[[";
let is_first = ref true in
IntMap.iter (fun k v -> if not !is_first then print_string "; "; is_first := false; Printf.printf "%d: %d" k v) map;
print_string "]]"
let print_int_map_endline map =
print_int_map map;
print_newline () *)
let map_to_list map =
let repeat i n =
let rec repeat_aux i n acc =
if n <= 0 then acc
else repeat_aux i (pred n) (i :: acc) in
repeat_aux i n [] in
List.rev (IntMap.fold (fun k v l -> (repeat k v) @ l) map [])
let list_product l =
List.fold_left ( * ) 1 l
let map_merge a b =
let map_find i map = try IntMap.find i map with Not_found -> 0 in
let elt_merge k v map = IntMap.add k (max v (map_find k b)) map in
IntMap.fold elt_merge a b
let _ =
let mmap = ref IntMap.empty in
for i = 1 to 20 do
mmap := map_merge !mmap (prime_factor_map i)
done;
print_int (list_product (map_to_list !mmap)); print_newline ()
| |
456b7c2b72040810cb34ef4274ee1c097cb9ee101260b5048baece3f04ad9746 | noprompt/meander | epsilon.cljc | (ns ^:no-doc meander.syntax.specs.epsilon
#?(:clj
(:require [clojure.spec.alpha :as s]
[clojure.spec.gen.alpha :as s.gen]
[meander.util.epsilon :as m.util])
:cljs
(:require [cljs.spec.alpha :as s]
[cljs.spec.gen.alpha :as s.gen]
[meander.util.epsilon :as m.util])))
;; Every AST node has, at least, the key `:tag`, the value of which is
;; a `keyword?`.
(s/def :meander.syntax.epsilon.node/tag
keyword?)
;; Some nodes may have an `::original-form` key, the value of which is
;; `any?`. This key is populated by forms which have been expanded
;; during `parse` and then subsequently parsed into an AST node.
(s/def :meander.syntax.epsilon.node/original-form
any?)
(s/def :meander.syntax.epsilon/node
(s/keys :req-un [:meander.syntax.epsilon.node/tag]
:opt [:meander.syntax.epsilon.node/original-form]))
;; ---------------------------------------------------------------------
Data specs
;; Any
;; ---
(defn any-symbol?
"`true` if `x` is a `simple-symbol?` the name of which begins with
\"_\"."
[x]
(and (simple-symbol? x) (m.util/re-matches? #"_.*" (name x))))
(s/def :meander.syntax.epsilon/any-symbol
(s/with-gen
(s/conformer
(fn [x]
(if (any-symbol? x)
x
:clojure.spec.alpha/invalid))
identity)
(fn []
(s.gen/fmap
(fn [sym]
(symbol (str "_" (name sym))))
(s.gen/symbol)))))
(s/def :meander.syntax.epsilon.node.any/tag
#{:any})
(s/def :meander.syntax.epsilon.node.any/symbol
:meander.syntax.epsilon/any-symbol)
(s/def :meander.syntax.epsilon.node/any
(s/keys :req-un [:meander.syntax.epsilon.node.any/tag
:meander.syntax.epsilon.node.any/symbol]))
;; Logic variable
;; --------------
(defn logic-variable-symbol?
"true if `x` is in the form of a logic variable i.e. a simple symbol
with a name beginning with \\?."
[x]
(and (simple-symbol? x) (m.util/re-matches? #"\?.+" (name x))))
(s/fdef logic-variable-symbol?
:args (s/cat :x any?)
:ret boolean?)
(s/def :meander.syntax.epsilon/logic-variable-symbol
(s/with-gen
(s/conformer
(fn [x]
(if (logic-variable-symbol? x)
x
:clojure.spec.alpha/invalid))
identity)
(fn []
(s.gen/fmap
(fn [x]
(symbol (str \? (name x))))
(s/gen simple-symbol?)))))
(s/def :meander.syntax.epsilon.node.lvr/tag
#{:lvr})
(s/def :meander.syntax.epsilon.node.lvr/symbol
:meander.syntax.epsilon/logic-variable-symbol)
(s/def :meander.syntax.epsilon.node/lvr
(s/keys :req-un [:meander.syntax.epsilon.node.lvr/tag
:meander.syntax.epsilon.node.lvr/symbol]))
;; Memory variable
;; ---------------
(defn memory-variable-symbol?
"true if x is in the form of a memory variable i.e. a simple symbol
with a name beginning with \\!."
[x]
(and (simple-symbol? x) (m.util/re-matches? #"!.+" (name x))))
(s/def :meander.syntax.epsilon/memory-variable
(s/with-gen
(s/conformer
(fn [x]
(if (memory-variable-symbol? x)
x
:clojure.spec.alpha/invalid))
identity)
(fn []
(s.gen/fmap
(fn [x]
(symbol (str \! (name x))))
(s/gen simple-symbol?)))))
(s/def :meander.syntax.epsilon.node.mvr/tag
#{:mvr})
(s/def :meander.syntax.epsilon.node.mvr/symbol
:meander.syntax.epsilon/memory-variable)
(s/def :meander.syntax.epsilon.node/mvr
(s/keys :req-un [:meander.syntax.epsilon.node.mvr/tag
:meander.syntax.epsilon.node.mvr/symbol]))
;; Mutable variable
;; ---------------
(defn mutable-variable-symbol?
"true if x is in the form of a memory variable i.e. a simple symbol
with a name beginning with \\!."
[x]
(and (simple-symbol? x) (m.util/re-matches? #"\*.+" (name x))))
(s/def :meander.syntax.epsilon/mutable-variable
(s/with-gen
(s/conformer
(fn [x]
(if (mutable-variable-symbol? x)
x
:clojure.spec.alpha/invalid))
identity)
(fn []
(s.gen/fmap
(fn [x]
(symbol (str \* (name x))))
(s/gen simple-symbol?)))))
(s/def :meander.syntax.epsilon.node.mut/tag
#{:mut})
(s/def :meander.syntax.epsilon.node.mut/symbol
:meander.syntax.epsilon/mutable-variable)
(s/def :meander.syntax.epsilon.node/mut
(s/keys :req-un [:meander.syntax.epsilon.node.mut/tag
:meander.syntax.epsilon.node.mut/symbol]))
;; Reference
;; ---------
(defn reference-symbol?
[x]
(and (simple-symbol? x) (m.util/re-matches? #"%.+" (name x))))
(s/def :meander.syntax.epsilon/reference-symbol
(s/with-gen
(s/conformer
(fn [x]
(if (reference-symbol? x)
x
:clojure.spec.alpha/invalid))
identity)
(fn []
(s.gen/fmap
(fn [x]
(symbol (str \% (name x))))
(s/gen simple-symbol?)))))
(s/def :meander.syntax.epsilon.node.ref/tag
#{:ref})
(s/def :meander.syntax.epsilon.node.ref/symbol
:meander.syntax.epsilon/reference-symbol)
(s/def :meander.syntax.epsilon.node/ref
(s/keys :req-un [:meander.syntax.epsilon.node.ref/symbol
:meander.syntax.epsilon.node.ref/tag]))
(s/def :meander.syntax.epsilon.node.with/tag
#{:wth})
(s/def :meander.syntax.epsilon.node.with.binding/ref
:meander.syntax.epsilon.node/ref)
(s/def :meander.syntax.epsilon.node.with.binding/pattern
:meander.syntax.epsilon/node)
(s/def :meander.syntax.epsilon.node.with/binding
(s/keys :req-un [:meander.syntax.epsilon.node.with.binding/pattern
:meander.syntax.epsilon.node.with.binding/ref]))
(s/def :meander.syntax.epsilon.node.with/bindings
(s/coll-of :meander.syntax.epsilon.node.with/binding
:kind sequential?))
(s/def :meander.syntax.epsilon.node.with/body
(s/nilable :meander.syntax.epsilon/node))
(s/def :meander.syntax.epsilon.node/with
(s/keys :req-un [:meander.syntax.epsilon.node.with/tag
:meander.syntax.epsilon.node.with/bindings]
:opt-un [:meander.syntax.epsilon.node.with/body]))
(s/def :meander.syntax.epsilon.node.partition/left
:meander.syntax.epsilon/node)
(s/def :meander.syntax.epsilon.node.partition/right
:meander.syntax.epsilon/node)
(s/def :meander.syntax.epsilon.node.partition/right
:meander.syntax.epsilon/node)
(s/def :meander.syntax.epsilon.node/partition
(s/keys :req-un [:meander.syntax.epsilon.node.partition/left
:meander.syntax.epsilon.node.partition/right]
:opt-un [:meander.syntax.epsilon.node.partition/as]))
(s/def :meander.syntax.epsilon/expander-registry
(s/map-of symbol? (s/or :fn fn? :var var?)))
(s/def :meander.syntax.epsilon/parser-registry
(s/map-of symbol? (s/or :fn fn? :var var?)))
(s/def :meander.syntax.epsilon/env
(s/keys :req [:meander.syntax.epsilon/expander-registry
:meander.syntax.epsilon/parser-registry]
:opt [:meander.syntax.epsilon/phase]))
(s/def :meander.syntax.epsilon/ref-map
(s/map-of :meander.syntax.epsilon.node/ref
:meander.syntax.epsilon/node))
;; ---------------------------------------------------------------------
;; Fn specs
#_
(s/fdef meander.syntax.epsilon/children
:args (s/cat :node :meander.syntax.epsilon/node)
:ret (s/coll-of :meander.syntax.epsilon/node
:kind sequential?))
#_
(s/fdef meander.syntax.epsilon/min-length
:args (s/cat :node :meander.syntax.epsilon/node)
:ret (s/or :nat nat-int?
:inf #{##Inf}))
(s/fdef meander.syntax.epsilon/min-length?
:args (s/cat :x any?)
:ret boolean?)
#_
(s/fdef meander.syntax.epsilon/max-length
:args (s/cat :node :meander.syntax.epsilon/node)
:ret (s/or :nat nat-int?
:inf #{##Inf}))
(s/fdef meander.syntax.epsilon/max-length?
:args (s/cat :x any?)
:ret boolean?)
(s/fdef meander.syntax.epsilon/variable-length?
:args (s/cat :node :meander.syntax.epsilon/node)
:ret boolean?)
(s/fdef meander.syntax.epsilon/ground?
:args (s/cat :node :meander.syntax.epsilon/node)
:ret boolean?)
(s/fdef meander.syntax.epsilon/search?
:args (s/cat :node :meander.syntax.epsilon/node)
:ret boolean?)
(s/fdef meander.syntax.epsilon/references
:args (s/cat :node :meander.syntax.epsilon/node)
:ret (s/coll-of :meander.syntax.epsilon.node/ref
:kind set?
:into #{}))
(s/fdef meander.syntax.epsilon/resolve-expander
:args (s/cat :sym symbol?
:env :meander.syntax.epsilon/env)
:ret (s/or :fn fn?
:nil nil?))
(s/fdef meander.syntax.epsilon/expand-form
:args (s/cat :form any?
:env :meander.syntax.epsilon/env)
:ret any?)
(s/fdef meander.syntax.epsilon/resolver-parser
:args (s/cat :sym symbol?
:env :meander.syntax.epsilon/env)
:ret (s/alt :fn fn?
:nil nil?))
(s/fdef meander.syntax.epsilon/parse-all
:args (s/cat :forms (s/nilable (s/coll-of any? :kind sequential?))
:env :meander.syntax.epsilon/env)
:ret (s/coll-of :meander.syntax.epsilon/node
:kind sequential?))
(s/fdef meander.syntax.epsilon/parse
:args (s/alt :a1 (s/cat :form any?)
:a2 (s/cat :form any?
:env :meander.syntax.epsilon/env))
:ret :meander.syntax.epsilon/node)
(s/fdef meander.syntax.epsilon/make-ref-map
:args (s/cat :node :meander.syntax.epsilon/node)
:ret :meander.syntax.epsilon/ref-map)
(s/fdef meander.syntax.epsilon/substitute-refs
:args (s/alt :a1 (s/cat :node :meander.syntax.epsilon/node)
:a2 (s/cat :node :meander.syntax.epsilon/node
:ref-map :meander.syntax.epsilon/ref-map))
:ret :meander.syntax.epsilon/node)
(s/fdef meander.syntax.epsilon/partition-nodes
:args (s/cat :node :meander.syntax.epsilon.node/partition))
(s/fdef meander.syntax.epsilon/tag
:args (s/cat :node :meander.syntax.epsilon/node))
(s/fdef meander.syntax.epsilon/variables
:args (s/cat :node :meander.syntax.epsilon/node))
(s/fdef meander.syntax.epsilon/memory-variables
:args (s/cat :node :meander.syntax.epsilon/node))
(s/fdef meander.syntax.epsilon/logic-variables
:args (s/cat :node :meander.syntax.epsilon/node))
(s/fdef meander.syntax.epsilon/mutable-variables
:args (s/cat :node :meander.syntax.epsilon/node))
(s/def ::local-name
(s/and simple-symbol? (fn [x] (not (= x '&)))))
(s/def ::binding-form
(s/or :local-symbol ::local-name
:seq-destructure ::seq-binding-form
:map-destructure ::map-binding-form))
;; sequential destructuring
(s/def ::seq-binding-form
(s/and vector?
(s/cat :forms (s/* ::binding-form)
:rest-forms (s/? (s/cat :ampersand #{'&} :form ::binding-form))
:as-form (s/? (s/cat :as #{:as} :as-sym ::local-name)))))
;; map destructuring
(s/def ::keys (s/coll-of ident? :kind vector?))
(s/def ::syms (s/coll-of symbol? :kind vector?))
(s/def ::strs (s/coll-of simple-symbol? :kind vector?))
(s/def ::or (s/map-of simple-symbol? any?))
(s/def ::as ::local-name)
(s/def ::map-special-binding
(s/keys :opt-un [::as ::or ::keys ::syms ::strs]))
(s/def ::map-binding (s/tuple ::binding-form any?))
(s/def ::ns-keys
(s/tuple (s/and qualified-keyword?
(fn [k] (contains? #{"keys" "syms"} (name k))))
(s/coll-of simple-symbol? :kind vector?)))
(s/def ::map-bindings
(s/every (s/or :map-binding ::map-binding
:qualified-keys-or-syms ::ns-keys
:special-binding (s/tuple #{:as :or :keys :syms :strs} any?))
:kind map?))
(s/def ::map-binding-form
(s/merge ::map-bindings ::map-special-binding))
(s/def ::param-list
(s/and vector?
(s/cat :params (s/* ::binding-form)
:var-params (s/? (s/cat :ampersand #{'&} :var-form ::binding-form)))))
(s/def ::params+body
(s/cat :params ::param-list
:body (s/alt :prepost+body (s/cat :prepost map?
:body (s/+ any?))
:body (s/* any?))))
(s/def ::defsyntax-args
(s/cat :fn-name simple-symbol?
:docstring (s/? string?)
:meta (s/? map?)
:fn-tail (s/alt :arity-1 ::params+body
:arity-n (s/cat :bodies (s/+ (s/spec ::params+body))
:attr-map (s/? map?)))))
(s/fdef meander.syntax.epsilon/defsyntax
:args ::defsyntax-args)
| null | https://raw.githubusercontent.com/noprompt/meander/8c0e9457befea5eee71a94a6d8726ed5916875dc/src/meander/syntax/specs/epsilon.cljc | clojure | Every AST node has, at least, the key `:tag`, the value of which is
a `keyword?`.
Some nodes may have an `::original-form` key, the value of which is
`any?`. This key is populated by forms which have been expanded
during `parse` and then subsequently parsed into an AST node.
---------------------------------------------------------------------
Any
---
Logic variable
--------------
Memory variable
---------------
Mutable variable
---------------
Reference
---------
---------------------------------------------------------------------
Fn specs
sequential destructuring
map destructuring | (ns ^:no-doc meander.syntax.specs.epsilon
#?(:clj
(:require [clojure.spec.alpha :as s]
[clojure.spec.gen.alpha :as s.gen]
[meander.util.epsilon :as m.util])
:cljs
(:require [cljs.spec.alpha :as s]
[cljs.spec.gen.alpha :as s.gen]
[meander.util.epsilon :as m.util])))
(s/def :meander.syntax.epsilon.node/tag
keyword?)
(s/def :meander.syntax.epsilon.node/original-form
any?)
(s/def :meander.syntax.epsilon/node
(s/keys :req-un [:meander.syntax.epsilon.node/tag]
:opt [:meander.syntax.epsilon.node/original-form]))
Data specs
(defn any-symbol?
"`true` if `x` is a `simple-symbol?` the name of which begins with
\"_\"."
[x]
(and (simple-symbol? x) (m.util/re-matches? #"_.*" (name x))))
(s/def :meander.syntax.epsilon/any-symbol
(s/with-gen
(s/conformer
(fn [x]
(if (any-symbol? x)
x
:clojure.spec.alpha/invalid))
identity)
(fn []
(s.gen/fmap
(fn [sym]
(symbol (str "_" (name sym))))
(s.gen/symbol)))))
(s/def :meander.syntax.epsilon.node.any/tag
#{:any})
(s/def :meander.syntax.epsilon.node.any/symbol
:meander.syntax.epsilon/any-symbol)
(s/def :meander.syntax.epsilon.node/any
(s/keys :req-un [:meander.syntax.epsilon.node.any/tag
:meander.syntax.epsilon.node.any/symbol]))
(defn logic-variable-symbol?
"true if `x` is in the form of a logic variable i.e. a simple symbol
with a name beginning with \\?."
[x]
(and (simple-symbol? x) (m.util/re-matches? #"\?.+" (name x))))
(s/fdef logic-variable-symbol?
:args (s/cat :x any?)
:ret boolean?)
(s/def :meander.syntax.epsilon/logic-variable-symbol
(s/with-gen
(s/conformer
(fn [x]
(if (logic-variable-symbol? x)
x
:clojure.spec.alpha/invalid))
identity)
(fn []
(s.gen/fmap
(fn [x]
(symbol (str \? (name x))))
(s/gen simple-symbol?)))))
(s/def :meander.syntax.epsilon.node.lvr/tag
#{:lvr})
(s/def :meander.syntax.epsilon.node.lvr/symbol
:meander.syntax.epsilon/logic-variable-symbol)
(s/def :meander.syntax.epsilon.node/lvr
(s/keys :req-un [:meander.syntax.epsilon.node.lvr/tag
:meander.syntax.epsilon.node.lvr/symbol]))
(defn memory-variable-symbol?
"true if x is in the form of a memory variable i.e. a simple symbol
with a name beginning with \\!."
[x]
(and (simple-symbol? x) (m.util/re-matches? #"!.+" (name x))))
(s/def :meander.syntax.epsilon/memory-variable
(s/with-gen
(s/conformer
(fn [x]
(if (memory-variable-symbol? x)
x
:clojure.spec.alpha/invalid))
identity)
(fn []
(s.gen/fmap
(fn [x]
(symbol (str \! (name x))))
(s/gen simple-symbol?)))))
(s/def :meander.syntax.epsilon.node.mvr/tag
#{:mvr})
(s/def :meander.syntax.epsilon.node.mvr/symbol
:meander.syntax.epsilon/memory-variable)
(s/def :meander.syntax.epsilon.node/mvr
(s/keys :req-un [:meander.syntax.epsilon.node.mvr/tag
:meander.syntax.epsilon.node.mvr/symbol]))
(defn mutable-variable-symbol?
"true if x is in the form of a memory variable i.e. a simple symbol
with a name beginning with \\!."
[x]
(and (simple-symbol? x) (m.util/re-matches? #"\*.+" (name x))))
(s/def :meander.syntax.epsilon/mutable-variable
(s/with-gen
(s/conformer
(fn [x]
(if (mutable-variable-symbol? x)
x
:clojure.spec.alpha/invalid))
identity)
(fn []
(s.gen/fmap
(fn [x]
(symbol (str \* (name x))))
(s/gen simple-symbol?)))))
(s/def :meander.syntax.epsilon.node.mut/tag
#{:mut})
(s/def :meander.syntax.epsilon.node.mut/symbol
:meander.syntax.epsilon/mutable-variable)
(s/def :meander.syntax.epsilon.node/mut
(s/keys :req-un [:meander.syntax.epsilon.node.mut/tag
:meander.syntax.epsilon.node.mut/symbol]))
(defn reference-symbol?
[x]
(and (simple-symbol? x) (m.util/re-matches? #"%.+" (name x))))
(s/def :meander.syntax.epsilon/reference-symbol
(s/with-gen
(s/conformer
(fn [x]
(if (reference-symbol? x)
x
:clojure.spec.alpha/invalid))
identity)
(fn []
(s.gen/fmap
(fn [x]
(symbol (str \% (name x))))
(s/gen simple-symbol?)))))
(s/def :meander.syntax.epsilon.node.ref/tag
#{:ref})
(s/def :meander.syntax.epsilon.node.ref/symbol
:meander.syntax.epsilon/reference-symbol)
(s/def :meander.syntax.epsilon.node/ref
(s/keys :req-un [:meander.syntax.epsilon.node.ref/symbol
:meander.syntax.epsilon.node.ref/tag]))
(s/def :meander.syntax.epsilon.node.with/tag
#{:wth})
(s/def :meander.syntax.epsilon.node.with.binding/ref
:meander.syntax.epsilon.node/ref)
(s/def :meander.syntax.epsilon.node.with.binding/pattern
:meander.syntax.epsilon/node)
(s/def :meander.syntax.epsilon.node.with/binding
(s/keys :req-un [:meander.syntax.epsilon.node.with.binding/pattern
:meander.syntax.epsilon.node.with.binding/ref]))
(s/def :meander.syntax.epsilon.node.with/bindings
(s/coll-of :meander.syntax.epsilon.node.with/binding
:kind sequential?))
(s/def :meander.syntax.epsilon.node.with/body
(s/nilable :meander.syntax.epsilon/node))
(s/def :meander.syntax.epsilon.node/with
(s/keys :req-un [:meander.syntax.epsilon.node.with/tag
:meander.syntax.epsilon.node.with/bindings]
:opt-un [:meander.syntax.epsilon.node.with/body]))
(s/def :meander.syntax.epsilon.node.partition/left
:meander.syntax.epsilon/node)
(s/def :meander.syntax.epsilon.node.partition/right
:meander.syntax.epsilon/node)
(s/def :meander.syntax.epsilon.node.partition/right
:meander.syntax.epsilon/node)
(s/def :meander.syntax.epsilon.node/partition
(s/keys :req-un [:meander.syntax.epsilon.node.partition/left
:meander.syntax.epsilon.node.partition/right]
:opt-un [:meander.syntax.epsilon.node.partition/as]))
(s/def :meander.syntax.epsilon/expander-registry
(s/map-of symbol? (s/or :fn fn? :var var?)))
(s/def :meander.syntax.epsilon/parser-registry
(s/map-of symbol? (s/or :fn fn? :var var?)))
(s/def :meander.syntax.epsilon/env
(s/keys :req [:meander.syntax.epsilon/expander-registry
:meander.syntax.epsilon/parser-registry]
:opt [:meander.syntax.epsilon/phase]))
(s/def :meander.syntax.epsilon/ref-map
(s/map-of :meander.syntax.epsilon.node/ref
:meander.syntax.epsilon/node))
#_
(s/fdef meander.syntax.epsilon/children
:args (s/cat :node :meander.syntax.epsilon/node)
:ret (s/coll-of :meander.syntax.epsilon/node
:kind sequential?))
#_
(s/fdef meander.syntax.epsilon/min-length
:args (s/cat :node :meander.syntax.epsilon/node)
:ret (s/or :nat nat-int?
:inf #{##Inf}))
(s/fdef meander.syntax.epsilon/min-length?
:args (s/cat :x any?)
:ret boolean?)
#_
(s/fdef meander.syntax.epsilon/max-length
:args (s/cat :node :meander.syntax.epsilon/node)
:ret (s/or :nat nat-int?
:inf #{##Inf}))
(s/fdef meander.syntax.epsilon/max-length?
:args (s/cat :x any?)
:ret boolean?)
(s/fdef meander.syntax.epsilon/variable-length?
:args (s/cat :node :meander.syntax.epsilon/node)
:ret boolean?)
(s/fdef meander.syntax.epsilon/ground?
:args (s/cat :node :meander.syntax.epsilon/node)
:ret boolean?)
(s/fdef meander.syntax.epsilon/search?
:args (s/cat :node :meander.syntax.epsilon/node)
:ret boolean?)
(s/fdef meander.syntax.epsilon/references
:args (s/cat :node :meander.syntax.epsilon/node)
:ret (s/coll-of :meander.syntax.epsilon.node/ref
:kind set?
:into #{}))
(s/fdef meander.syntax.epsilon/resolve-expander
:args (s/cat :sym symbol?
:env :meander.syntax.epsilon/env)
:ret (s/or :fn fn?
:nil nil?))
(s/fdef meander.syntax.epsilon/expand-form
:args (s/cat :form any?
:env :meander.syntax.epsilon/env)
:ret any?)
(s/fdef meander.syntax.epsilon/resolver-parser
:args (s/cat :sym symbol?
:env :meander.syntax.epsilon/env)
:ret (s/alt :fn fn?
:nil nil?))
(s/fdef meander.syntax.epsilon/parse-all
:args (s/cat :forms (s/nilable (s/coll-of any? :kind sequential?))
:env :meander.syntax.epsilon/env)
:ret (s/coll-of :meander.syntax.epsilon/node
:kind sequential?))
(s/fdef meander.syntax.epsilon/parse
:args (s/alt :a1 (s/cat :form any?)
:a2 (s/cat :form any?
:env :meander.syntax.epsilon/env))
:ret :meander.syntax.epsilon/node)
(s/fdef meander.syntax.epsilon/make-ref-map
:args (s/cat :node :meander.syntax.epsilon/node)
:ret :meander.syntax.epsilon/ref-map)
(s/fdef meander.syntax.epsilon/substitute-refs
:args (s/alt :a1 (s/cat :node :meander.syntax.epsilon/node)
:a2 (s/cat :node :meander.syntax.epsilon/node
:ref-map :meander.syntax.epsilon/ref-map))
:ret :meander.syntax.epsilon/node)
(s/fdef meander.syntax.epsilon/partition-nodes
:args (s/cat :node :meander.syntax.epsilon.node/partition))
(s/fdef meander.syntax.epsilon/tag
:args (s/cat :node :meander.syntax.epsilon/node))
(s/fdef meander.syntax.epsilon/variables
:args (s/cat :node :meander.syntax.epsilon/node))
(s/fdef meander.syntax.epsilon/memory-variables
:args (s/cat :node :meander.syntax.epsilon/node))
(s/fdef meander.syntax.epsilon/logic-variables
:args (s/cat :node :meander.syntax.epsilon/node))
(s/fdef meander.syntax.epsilon/mutable-variables
:args (s/cat :node :meander.syntax.epsilon/node))
(s/def ::local-name
(s/and simple-symbol? (fn [x] (not (= x '&)))))
(s/def ::binding-form
(s/or :local-symbol ::local-name
:seq-destructure ::seq-binding-form
:map-destructure ::map-binding-form))
(s/def ::seq-binding-form
(s/and vector?
(s/cat :forms (s/* ::binding-form)
:rest-forms (s/? (s/cat :ampersand #{'&} :form ::binding-form))
:as-form (s/? (s/cat :as #{:as} :as-sym ::local-name)))))
(s/def ::keys (s/coll-of ident? :kind vector?))
(s/def ::syms (s/coll-of symbol? :kind vector?))
(s/def ::strs (s/coll-of simple-symbol? :kind vector?))
(s/def ::or (s/map-of simple-symbol? any?))
(s/def ::as ::local-name)
(s/def ::map-special-binding
(s/keys :opt-un [::as ::or ::keys ::syms ::strs]))
(s/def ::map-binding (s/tuple ::binding-form any?))
(s/def ::ns-keys
(s/tuple (s/and qualified-keyword?
(fn [k] (contains? #{"keys" "syms"} (name k))))
(s/coll-of simple-symbol? :kind vector?)))
(s/def ::map-bindings
(s/every (s/or :map-binding ::map-binding
:qualified-keys-or-syms ::ns-keys
:special-binding (s/tuple #{:as :or :keys :syms :strs} any?))
:kind map?))
(s/def ::map-binding-form
(s/merge ::map-bindings ::map-special-binding))
(s/def ::param-list
(s/and vector?
(s/cat :params (s/* ::binding-form)
:var-params (s/? (s/cat :ampersand #{'&} :var-form ::binding-form)))))
(s/def ::params+body
(s/cat :params ::param-list
:body (s/alt :prepost+body (s/cat :prepost map?
:body (s/+ any?))
:body (s/* any?))))
(s/def ::defsyntax-args
(s/cat :fn-name simple-symbol?
:docstring (s/? string?)
:meta (s/? map?)
:fn-tail (s/alt :arity-1 ::params+body
:arity-n (s/cat :bodies (s/+ (s/spec ::params+body))
:attr-map (s/? map?)))))
(s/fdef meander.syntax.epsilon/defsyntax
:args ::defsyntax-args)
|
1ddccf8327ac4637164571776f9560979a7e5d839601df4560f88dc682e3ed02 | fpco/ide-backend | PrettyPrint.hs | -----------------------------------------------------------------------------
-- |
Module : Distribution . PackageDescription . PrettyPrint
Copyright : 2010
-- License : BSD3
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- Pretty printing for cabal files
--
-----------------------------------------------------------------------------
module Distribution.PackageDescription.PrettyPrint (
writeGenericPackageDescription,
showGenericPackageDescription,
) where
import Data.Monoid (Monoid(mempty))
import Distribution.PackageDescription
( Benchmark(..), BenchmarkInterface(..), benchmarkType
, TestSuite(..), TestSuiteInterface(..), testType
, SourceRepo(..),
customFieldsBI, CondTree(..), Condition(..),
FlagName(..), ConfVar(..), Executable(..), Library(..),
Flag(..), PackageDescription(..),
GenericPackageDescription(..))
import Text.PrettyPrint
(hsep, comma, punctuate, parens, char, nest, empty,
isEmpty, ($$), (<+>), colon, (<>), text, vcat, ($+$), Doc, render)
import Distribution.Simple.Utils (writeUTF8File)
import Distribution.ParseUtils (showFreeText, FieldDescr(..), indentWith, ppField, ppFields)
import Distribution.PackageDescription.Parse (pkgDescrFieldDescrs,binfoFieldDescrs,libFieldDescrs,
sourceRepoFieldDescrs,flagFieldDescrs)
import Distribution.Package (Dependency(..))
import Distribution.Text (Text(..))
import Data.Maybe (isJust, fromJust, isNothing)
-- | Recompile with false for regression testing
simplifiedPrinting :: Bool
simplifiedPrinting = False
-- | Writes a .cabal file from a generic package description
writeGenericPackageDescription :: FilePath -> GenericPackageDescription -> IO ()
writeGenericPackageDescription fpath pkg = writeUTF8File fpath (showGenericPackageDescription pkg)
-- | Writes a generic package description to a string
showGenericPackageDescription :: GenericPackageDescription -> String
showGenericPackageDescription = render . ppGenericPackageDescription
ppGenericPackageDescription :: GenericPackageDescription -> Doc
ppGenericPackageDescription gpd =
ppPackageDescription (packageDescription gpd)
$+$ ppGenPackageFlags (genPackageFlags gpd)
$+$ ppLibrary (condLibrary gpd)
$+$ ppExecutables (condExecutables gpd)
$+$ ppTestSuites (condTestSuites gpd)
$+$ ppBenchmarks (condBenchmarks gpd)
ppPackageDescription :: PackageDescription -> Doc
ppPackageDescription pd = ppFields pkgDescrFieldDescrs pd
$+$ ppCustomFields (customFieldsPD pd)
$+$ ppSourceRepos (sourceRepos pd)
ppSourceRepos :: [SourceRepo] -> Doc
ppSourceRepos [] = empty
ppSourceRepos (hd:tl) = ppSourceRepo hd $+$ ppSourceRepos tl
ppSourceRepo :: SourceRepo -> Doc
ppSourceRepo repo =
emptyLine $ text "source-repository" <+> disp (repoKind repo) $+$
(nest indentWith (ppFields sourceRepoFieldDescrs' repo))
where
sourceRepoFieldDescrs' = [fd | fd <- sourceRepoFieldDescrs, fieldName fd /= "kind"]
-- TODO: this is a temporary hack. Ideally, fields containing default values
would be filtered out when the @FieldDescr a@ list is generated .
ppFieldsFiltered :: [(String, String)] -> [FieldDescr a] -> a -> Doc
ppFieldsFiltered removable fields x = ppFields (filter nondefault fields) x
where
nondefault (FieldDescr name getter _) =
maybe True (render (getter x) /=) (lookup name removable)
binfoDefaults :: [(String, String)]
binfoDefaults = [("buildable", "True")]
libDefaults :: [(String, String)]
libDefaults = ("exposed", "True") : binfoDefaults
flagDefaults :: [(String, String)]
flagDefaults = [("default", "True"), ("manual", "False")]
ppDiffFields :: [FieldDescr a] -> a -> a -> Doc
ppDiffFields fields x y =
vcat [ ppField name (getter x)
| FieldDescr name getter _ <- fields
, render (getter x) /= render (getter y)
]
ppCustomFields :: [(String,String)] -> Doc
ppCustomFields flds = vcat [ppCustomField f | f <- flds]
ppCustomField :: (String,String) -> Doc
ppCustomField (name,val) = text name <> colon <+> showFreeText val
ppGenPackageFlags :: [Flag] -> Doc
ppGenPackageFlags flds = vcat [ppFlag f | f <- flds]
ppFlag :: Flag -> Doc
ppFlag flag@(MkFlag name _ _ _) =
emptyLine $ text "flag" <+> ppFlagName name $+$ nest indentWith fields
where
fields = ppFieldsFiltered flagDefaults flagFieldDescrs flag
ppLibrary :: (Maybe (CondTree ConfVar [Dependency] Library)) -> Doc
ppLibrary Nothing = empty
ppLibrary (Just condTree) =
emptyLine $ text "library" $+$ nest indentWith (ppCondTree condTree Nothing ppLib)
where
ppLib lib Nothing = ppFieldsFiltered libDefaults libFieldDescrs lib
$$ ppCustomFields (customFieldsBI (libBuildInfo lib))
ppLib lib (Just plib) = ppDiffFields libFieldDescrs lib plib
$$ ppCustomFields (customFieldsBI (libBuildInfo lib))
ppExecutables :: [(String, CondTree ConfVar [Dependency] Executable)] -> Doc
ppExecutables exes =
vcat [emptyLine $ text ("executable " ++ n)
$+$ nest indentWith (ppCondTree condTree Nothing ppExe)| (n,condTree) <- exes]
where
ppExe (Executable _ modulePath' buildInfo') Nothing =
(if modulePath' == "" then empty else text "main-is:" <+> text modulePath')
$+$ ppFieldsFiltered binfoDefaults binfoFieldDescrs buildInfo'
$+$ ppCustomFields (customFieldsBI buildInfo')
ppExe (Executable _ modulePath' buildInfo')
(Just (Executable _ modulePath2 buildInfo2)) =
(if modulePath' == "" || modulePath' == modulePath2
then empty else text "main-is:" <+> text modulePath')
$+$ ppDiffFields binfoFieldDescrs buildInfo' buildInfo2
$+$ ppCustomFields (customFieldsBI buildInfo')
ppTestSuites :: [(String, CondTree ConfVar [Dependency] TestSuite)] -> Doc
ppTestSuites suites =
emptyLine $ vcat [ text ("test-suite " ++ n)
$+$ nest indentWith (ppCondTree condTree Nothing ppTestSuite)
| (n,condTree) <- suites]
where
ppTestSuite testsuite Nothing =
maybe empty (\t -> text "type:" <+> disp t)
maybeTestType
$+$ maybe empty (\f -> text "main-is:" <+> text f)
(testSuiteMainIs testsuite)
$+$ maybe empty (\m -> text "test-module:" <+> disp m)
(testSuiteModule testsuite)
$+$ ppFieldsFiltered binfoDefaults binfoFieldDescrs (testBuildInfo testsuite)
$+$ ppCustomFields (customFieldsBI (testBuildInfo testsuite))
where
maybeTestType | testInterface testsuite == mempty = Nothing
| otherwise = Just (testType testsuite)
ppTestSuite (TestSuite _ _ buildInfo' _)
(Just (TestSuite _ _ buildInfo2 _)) =
ppDiffFields binfoFieldDescrs buildInfo' buildInfo2
$+$ ppCustomFields (customFieldsBI buildInfo')
testSuiteMainIs test = case testInterface test of
TestSuiteExeV10 _ f -> Just f
_ -> Nothing
testSuiteModule test = case testInterface test of
TestSuiteLibV09 _ m -> Just m
_ -> Nothing
ppBenchmarks :: [(String, CondTree ConfVar [Dependency] Benchmark)] -> Doc
ppBenchmarks suites =
emptyLine $ vcat [ text ("benchmark " ++ n)
$+$ nest indentWith (ppCondTree condTree Nothing ppBenchmark)
| (n,condTree) <- suites]
where
ppBenchmark benchmark Nothing =
maybe empty (\t -> text "type:" <+> disp t)
maybeBenchmarkType
$+$ maybe empty (\f -> text "main-is:" <+> text f)
(benchmarkMainIs benchmark)
$+$ ppFieldsFiltered binfoDefaults binfoFieldDescrs (benchmarkBuildInfo benchmark)
$+$ ppCustomFields (customFieldsBI (benchmarkBuildInfo benchmark))
where
maybeBenchmarkType | benchmarkInterface benchmark == mempty = Nothing
| otherwise = Just (benchmarkType benchmark)
ppBenchmark (Benchmark _ _ buildInfo' _)
(Just (Benchmark _ _ buildInfo2 _)) =
ppDiffFields binfoFieldDescrs buildInfo' buildInfo2
$+$ ppCustomFields (customFieldsBI buildInfo')
benchmarkMainIs benchmark = case benchmarkInterface benchmark of
BenchmarkExeV10 _ f -> Just f
_ -> Nothing
ppCondition :: Condition ConfVar -> Doc
ppCondition (Var x) = ppConfVar x
ppCondition (Lit b) = text (show b)
ppCondition (CNot c) = char '!' <> (ppCondition c)
ppCondition (COr c1 c2) = parens (hsep [ppCondition c1, text "||"
<+> ppCondition c2])
ppCondition (CAnd c1 c2) = parens (hsep [ppCondition c1, text "&&"
<+> ppCondition c2])
ppConfVar :: ConfVar -> Doc
ppConfVar (OS os) = text "os" <> parens (disp os)
ppConfVar (Arch arch) = text "arch" <> parens (disp arch)
ppConfVar (Flag name) = text "flag" <> parens (ppFlagName name)
ppConfVar (Impl c v) = text "impl" <> parens (disp c <+> disp v)
ppFlagName :: FlagName -> Doc
ppFlagName (FlagName name) = text name
ppCondTree :: CondTree ConfVar [Dependency] a -> Maybe a -> (a -> Maybe a -> Doc) -> Doc
ppCondTree ct@(CondNode it deps ifs) mbIt ppIt =
let res = ppDeps deps
$+$ (vcat $ map ppIf ifs)
$+$ ppIt it mbIt
in if isJust mbIt && isEmpty res
then ppCondTree ct Nothing ppIt
else res
where
-- TODO: this ends up printing trailing spaces when combined with nest.
ppIf (c,thenTree,mElseTree) =
((emptyLine $ text "if" <+> ppCondition c) $$
nest indentWith (ppCondTree thenTree
(if simplifiedPrinting then (Just it) else Nothing) ppIt))
$+$ (if isNothing mElseTree
then empty
else text "else"
$$ nest indentWith (ppCondTree (fromJust mElseTree)
(if simplifiedPrinting then (Just it) else Nothing) ppIt))
ppDeps :: [Dependency] -> Doc
ppDeps [] = empty
ppDeps deps =
text "build-depends:" $+$ nest indentWith (vcat (punctuate comma (map disp deps)))
emptyLine :: Doc -> Doc
emptyLine d = text "" $+$ d
| null | https://raw.githubusercontent.com/fpco/ide-backend/860636f2d0e872e9481569236bce690637e0016e/ide-backend/TestSuite/inputs/Cabal-1.22.0.0/Distribution/PackageDescription/PrettyPrint.hs | haskell | ---------------------------------------------------------------------------
|
License : BSD3
Maintainer :
Stability : provisional
Portability : portable
Pretty printing for cabal files
---------------------------------------------------------------------------
| Recompile with false for regression testing
| Writes a .cabal file from a generic package description
| Writes a generic package description to a string
TODO: this is a temporary hack. Ideally, fields containing default values
TODO: this ends up printing trailing spaces when combined with nest. | Module : Distribution . PackageDescription . PrettyPrint
Copyright : 2010
module Distribution.PackageDescription.PrettyPrint (
writeGenericPackageDescription,
showGenericPackageDescription,
) where
import Data.Monoid (Monoid(mempty))
import Distribution.PackageDescription
( Benchmark(..), BenchmarkInterface(..), benchmarkType
, TestSuite(..), TestSuiteInterface(..), testType
, SourceRepo(..),
customFieldsBI, CondTree(..), Condition(..),
FlagName(..), ConfVar(..), Executable(..), Library(..),
Flag(..), PackageDescription(..),
GenericPackageDescription(..))
import Text.PrettyPrint
(hsep, comma, punctuate, parens, char, nest, empty,
isEmpty, ($$), (<+>), colon, (<>), text, vcat, ($+$), Doc, render)
import Distribution.Simple.Utils (writeUTF8File)
import Distribution.ParseUtils (showFreeText, FieldDescr(..), indentWith, ppField, ppFields)
import Distribution.PackageDescription.Parse (pkgDescrFieldDescrs,binfoFieldDescrs,libFieldDescrs,
sourceRepoFieldDescrs,flagFieldDescrs)
import Distribution.Package (Dependency(..))
import Distribution.Text (Text(..))
import Data.Maybe (isJust, fromJust, isNothing)
simplifiedPrinting :: Bool
simplifiedPrinting = False
writeGenericPackageDescription :: FilePath -> GenericPackageDescription -> IO ()
writeGenericPackageDescription fpath pkg = writeUTF8File fpath (showGenericPackageDescription pkg)
showGenericPackageDescription :: GenericPackageDescription -> String
showGenericPackageDescription = render . ppGenericPackageDescription
ppGenericPackageDescription :: GenericPackageDescription -> Doc
ppGenericPackageDescription gpd =
ppPackageDescription (packageDescription gpd)
$+$ ppGenPackageFlags (genPackageFlags gpd)
$+$ ppLibrary (condLibrary gpd)
$+$ ppExecutables (condExecutables gpd)
$+$ ppTestSuites (condTestSuites gpd)
$+$ ppBenchmarks (condBenchmarks gpd)
ppPackageDescription :: PackageDescription -> Doc
ppPackageDescription pd = ppFields pkgDescrFieldDescrs pd
$+$ ppCustomFields (customFieldsPD pd)
$+$ ppSourceRepos (sourceRepos pd)
ppSourceRepos :: [SourceRepo] -> Doc
ppSourceRepos [] = empty
ppSourceRepos (hd:tl) = ppSourceRepo hd $+$ ppSourceRepos tl
ppSourceRepo :: SourceRepo -> Doc
ppSourceRepo repo =
emptyLine $ text "source-repository" <+> disp (repoKind repo) $+$
(nest indentWith (ppFields sourceRepoFieldDescrs' repo))
where
sourceRepoFieldDescrs' = [fd | fd <- sourceRepoFieldDescrs, fieldName fd /= "kind"]
would be filtered out when the @FieldDescr a@ list is generated .
ppFieldsFiltered :: [(String, String)] -> [FieldDescr a] -> a -> Doc
ppFieldsFiltered removable fields x = ppFields (filter nondefault fields) x
where
nondefault (FieldDescr name getter _) =
maybe True (render (getter x) /=) (lookup name removable)
binfoDefaults :: [(String, String)]
binfoDefaults = [("buildable", "True")]
libDefaults :: [(String, String)]
libDefaults = ("exposed", "True") : binfoDefaults
flagDefaults :: [(String, String)]
flagDefaults = [("default", "True"), ("manual", "False")]
ppDiffFields :: [FieldDescr a] -> a -> a -> Doc
ppDiffFields fields x y =
vcat [ ppField name (getter x)
| FieldDescr name getter _ <- fields
, render (getter x) /= render (getter y)
]
ppCustomFields :: [(String,String)] -> Doc
ppCustomFields flds = vcat [ppCustomField f | f <- flds]
ppCustomField :: (String,String) -> Doc
ppCustomField (name,val) = text name <> colon <+> showFreeText val
ppGenPackageFlags :: [Flag] -> Doc
ppGenPackageFlags flds = vcat [ppFlag f | f <- flds]
ppFlag :: Flag -> Doc
ppFlag flag@(MkFlag name _ _ _) =
emptyLine $ text "flag" <+> ppFlagName name $+$ nest indentWith fields
where
fields = ppFieldsFiltered flagDefaults flagFieldDescrs flag
ppLibrary :: (Maybe (CondTree ConfVar [Dependency] Library)) -> Doc
ppLibrary Nothing = empty
ppLibrary (Just condTree) =
emptyLine $ text "library" $+$ nest indentWith (ppCondTree condTree Nothing ppLib)
where
ppLib lib Nothing = ppFieldsFiltered libDefaults libFieldDescrs lib
$$ ppCustomFields (customFieldsBI (libBuildInfo lib))
ppLib lib (Just plib) = ppDiffFields libFieldDescrs lib plib
$$ ppCustomFields (customFieldsBI (libBuildInfo lib))
ppExecutables :: [(String, CondTree ConfVar [Dependency] Executable)] -> Doc
ppExecutables exes =
vcat [emptyLine $ text ("executable " ++ n)
$+$ nest indentWith (ppCondTree condTree Nothing ppExe)| (n,condTree) <- exes]
where
ppExe (Executable _ modulePath' buildInfo') Nothing =
(if modulePath' == "" then empty else text "main-is:" <+> text modulePath')
$+$ ppFieldsFiltered binfoDefaults binfoFieldDescrs buildInfo'
$+$ ppCustomFields (customFieldsBI buildInfo')
ppExe (Executable _ modulePath' buildInfo')
(Just (Executable _ modulePath2 buildInfo2)) =
(if modulePath' == "" || modulePath' == modulePath2
then empty else text "main-is:" <+> text modulePath')
$+$ ppDiffFields binfoFieldDescrs buildInfo' buildInfo2
$+$ ppCustomFields (customFieldsBI buildInfo')
ppTestSuites :: [(String, CondTree ConfVar [Dependency] TestSuite)] -> Doc
ppTestSuites suites =
emptyLine $ vcat [ text ("test-suite " ++ n)
$+$ nest indentWith (ppCondTree condTree Nothing ppTestSuite)
| (n,condTree) <- suites]
where
ppTestSuite testsuite Nothing =
maybe empty (\t -> text "type:" <+> disp t)
maybeTestType
$+$ maybe empty (\f -> text "main-is:" <+> text f)
(testSuiteMainIs testsuite)
$+$ maybe empty (\m -> text "test-module:" <+> disp m)
(testSuiteModule testsuite)
$+$ ppFieldsFiltered binfoDefaults binfoFieldDescrs (testBuildInfo testsuite)
$+$ ppCustomFields (customFieldsBI (testBuildInfo testsuite))
where
maybeTestType | testInterface testsuite == mempty = Nothing
| otherwise = Just (testType testsuite)
ppTestSuite (TestSuite _ _ buildInfo' _)
(Just (TestSuite _ _ buildInfo2 _)) =
ppDiffFields binfoFieldDescrs buildInfo' buildInfo2
$+$ ppCustomFields (customFieldsBI buildInfo')
testSuiteMainIs test = case testInterface test of
TestSuiteExeV10 _ f -> Just f
_ -> Nothing
testSuiteModule test = case testInterface test of
TestSuiteLibV09 _ m -> Just m
_ -> Nothing
ppBenchmarks :: [(String, CondTree ConfVar [Dependency] Benchmark)] -> Doc
ppBenchmarks suites =
emptyLine $ vcat [ text ("benchmark " ++ n)
$+$ nest indentWith (ppCondTree condTree Nothing ppBenchmark)
| (n,condTree) <- suites]
where
ppBenchmark benchmark Nothing =
maybe empty (\t -> text "type:" <+> disp t)
maybeBenchmarkType
$+$ maybe empty (\f -> text "main-is:" <+> text f)
(benchmarkMainIs benchmark)
$+$ ppFieldsFiltered binfoDefaults binfoFieldDescrs (benchmarkBuildInfo benchmark)
$+$ ppCustomFields (customFieldsBI (benchmarkBuildInfo benchmark))
where
maybeBenchmarkType | benchmarkInterface benchmark == mempty = Nothing
| otherwise = Just (benchmarkType benchmark)
ppBenchmark (Benchmark _ _ buildInfo' _)
(Just (Benchmark _ _ buildInfo2 _)) =
ppDiffFields binfoFieldDescrs buildInfo' buildInfo2
$+$ ppCustomFields (customFieldsBI buildInfo')
benchmarkMainIs benchmark = case benchmarkInterface benchmark of
BenchmarkExeV10 _ f -> Just f
_ -> Nothing
ppCondition :: Condition ConfVar -> Doc
ppCondition (Var x) = ppConfVar x
ppCondition (Lit b) = text (show b)
ppCondition (CNot c) = char '!' <> (ppCondition c)
ppCondition (COr c1 c2) = parens (hsep [ppCondition c1, text "||"
<+> ppCondition c2])
ppCondition (CAnd c1 c2) = parens (hsep [ppCondition c1, text "&&"
<+> ppCondition c2])
ppConfVar :: ConfVar -> Doc
ppConfVar (OS os) = text "os" <> parens (disp os)
ppConfVar (Arch arch) = text "arch" <> parens (disp arch)
ppConfVar (Flag name) = text "flag" <> parens (ppFlagName name)
ppConfVar (Impl c v) = text "impl" <> parens (disp c <+> disp v)
ppFlagName :: FlagName -> Doc
ppFlagName (FlagName name) = text name
ppCondTree :: CondTree ConfVar [Dependency] a -> Maybe a -> (a -> Maybe a -> Doc) -> Doc
ppCondTree ct@(CondNode it deps ifs) mbIt ppIt =
let res = ppDeps deps
$+$ (vcat $ map ppIf ifs)
$+$ ppIt it mbIt
in if isJust mbIt && isEmpty res
then ppCondTree ct Nothing ppIt
else res
where
ppIf (c,thenTree,mElseTree) =
((emptyLine $ text "if" <+> ppCondition c) $$
nest indentWith (ppCondTree thenTree
(if simplifiedPrinting then (Just it) else Nothing) ppIt))
$+$ (if isNothing mElseTree
then empty
else text "else"
$$ nest indentWith (ppCondTree (fromJust mElseTree)
(if simplifiedPrinting then (Just it) else Nothing) ppIt))
ppDeps :: [Dependency] -> Doc
ppDeps [] = empty
ppDeps deps =
text "build-depends:" $+$ nest indentWith (vcat (punctuate comma (map disp deps)))
emptyLine :: Doc -> Doc
emptyLine d = text "" $+$ d
|
613371890b727e3cff03a250fd5108e7611b683429f0eeedd14fbf9f4e172bbc | ghc/nofib | Csg.hs |
- ( The Solid Modeller , written in Haskell )
-
- Copyright 1990,1991,1992,1993 Duncan Sinclair
-
- Permissiom to use , copy , modify , and distribute this software for any
- purpose and without fee is hereby granted , provided that the above
- copyright notice and this permission notice appear in all copies , and
- that my name not be used in advertising or publicity pertaining to this
- software without specific , written prior permission . I makes no
- representations about the suitability of this software for any purpose .
- It is provided ` ` as is '' without express or implied warranty .
-
- Duncan Sinclair 1993 .
-
- CSG evaluation engine .
-
- Fulsom (The Solid Modeller, written in Haskell)
-
- Copyright 1990,1991,1992,1993 Duncan Sinclair
-
- Permissiom to use, copy, modify, and distribute this software for any
- purpose and without fee is hereby granted, provided that the above
- copyright notice and this permission notice appear in all copies, and
- that my name not be used in advertising or publicity pertaining to this
- software without specific, written prior permission. I makes no
- representations about the suitability of this software for any purpose.
- It is provided ``as is'' without express or implied warranty.
-
- Duncan Sinclair 1993.
-
- CSG evaluation engine.
-
-}
module Csg(calc) where
import Matrix
import Types
import Interval
-- no is returned when there is "no" change to the csg.
no = error ("Evaluated dead csg.")
calc :: Csg -> Calc
calc (Func f) rgb xyz = f rgb xyz
calc (Matrix a mat) rgb xyz
= (ans,newc,newr,prune)
where
newc = if prune then (if b then newc' else newc'') else (no)
(newc',b) = if prune then (reduceM newc'' mat) else (no)
xyz' = mat4x1 mat xyz
(ans,newc'',newr,prune) = calc a rgb xyz'
calc (Object X) rgb (x,y,z) = (x,no,rgb,False)
calc (Object Y) rgb (x,y,z) = (y,no,rgb,False)
calc (Object Z) rgb (x,y,z) = (z,no,rgb,False)
calc (Object (Plane a b c d)) rgb xyz
= (ans,(no),rgb,False)
where
ans = dorow (a,b,c,d) xyz
calc (Object (Sphere a b c r)) rgb xyz
= (ans,newc,rgb,True)
where
(ans,_,_,_) = calc newc rgb xyz
newc = Func f
f rgb zyx = (sphere zyx,no,rgb,False)
sphere :: (R3 BI) -> BI
sphere (x,y,z) = sqr (x-a') + sqr (y-b') + sqr (z-c') - sqr r'
a' = realToFrac a ; b' = realToFrac b ; c' = realToFrac c
r' = realToFrac r
calc (Object (Cube a b c r)) rgb xyz
= (ans,newc',rgb,bool)
where
newc'' = if bool then newc else newc'
(ans,newc,_,bool) = calc newc' rgb xyz
newc' = Inter xx (Inter yy zz)
xx = Inter x1 x2
yy = Inter y1 y2
zz = Inter z1 z2
x1 = Object (Plane ( 1) 0 0 (-(a+r)))
y1 = Object (Plane 0 ( 1) 0 (-(b+r)))
z1 = Object (Plane 0 0 ( 1) (-(c+r)))
x2 = Object (Plane (-1) 0 0 ( (a-r)))
y2 = Object (Plane 0 (-1) 0 ( (b-r)))
z2 = Object (Plane 0 0 (-1) ( (c-r)))
calc (Union a b) rgb xyz
= (min an1 an2,newc,newr,bool)
where
(an1,c1,rgb1,b1) = calc a rgb xyz
(an2,c2,rgb2,b2) = calc b rgb xyz
bool = b1 || b2
ca = if b1 then c1 else a
cb = if b2 then c2 else b
newr | an1 < an2 = rgb1
| an1 > an2 = rgb2
| otherwise = rgb
newc | an1 < an2 = ca
| an1 > an2 = cb
| not bool = (no)
| otherwise = Union ca cb
calc (Inter a b) rgb xyz
= (max an1 an2,newc,newr,bool)
where
(an1,c1,rgb1,b1) = calc a rgb xyz
(an2,c2,rgb2,b2) = calc b rgb xyz
bool = b1 || b2
ca = if b1 then c1 else a
cb = if b2 then c2 else b
newr | an1 > an2 = rgb1
| an1 < an2 = rgb2
| otherwise = rgb
newc | an1 > an2 = ca
| an1 < an2 = cb
| not bool = (no)
| otherwise = Inter ca cb
calc (Comp a) rgb xyz
= (ans,newc'',newr,True)
where
(ans,newc,newr,b) = calc newc' rgb xyz
newc'' = if b then newc else newc'
newc' = Matrix a mat
mat = (m1,m2,m3)
m1 = (-1, 0, 0, 0)
m2 = ( 0,-1, 0, 0)
m3 = ( 0, 0,-1, 0)
calc (Colour c a) rgb xyz
= (ans,newc,c,bool)
where
newc = if bool then (Colour c newc') else (no)
(ans,newc',_,bool) = calc a c xyz
calc (Sub a b) rgb xyz
= (ans,newc'',newr,True)
where
newc' = (a `Inter` (Comp b))
newc'' = if bool then newc else newc'
(ans,newc,newr,bool) = calc newc' rgb xyz
calc (Geom a (Trans h w d)) rgb xyz
= (ans,newc'',newr,True)
where
(ans,newc,newr,b) = calc newc' rgb xyz
newc'' = if b then newc else newc'
newc' = Matrix a mat
mat = (m1,m2,m3)
m1 = ( 1, 0, 0, h)
m2 = ( 0, 1, 0, w)
m3 = ( 0, 0, 1, d)
calc (Geom a (Scale h w d)) rgb xyz
= (ans,newc'',newr,True)
where
(ans,newc,newr,b) = calc newc' rgb xyz
newc'' = if b then newc else newc'
newc' = Matrix a mat
mat = (m1,m2,m3)
m1 = ( h, 0, 0, 0)
m2 = ( 0, w, 0, 0)
m3 = ( 0, 0, d, 0)
calc (Geom a (RotX rad)) rgb xyz
= (ans,newc'',newr,True)
where
(ans,newc,newr,b) = calc newc' rgb xyz
newc'' = if b then newc else newc'
newc' = Matrix a mat
mat = (m1,m2,m3)
c = cos rad
s = sin rad
m1 = ( 1, 0, 0, 0)
m2 = ( 0, c,-s, 0)
m3 = ( 0, s, c, 0)
calc (Geom a (RotY rad)) rgb xyz
= (ans,newc'',newr,True)
where
(ans,newc,newr,b) = calc newc' rgb xyz
newc'' = if b then newc else newc'
newc' = Matrix a mat
mat = (m1,m2,m3)
c = cos rad
s = sin rad
m1 = ( c, 0, s, 0)
m2 = ( 0, 1, 0, 0)
m3 = (-s, 0, c, 0)
calc (Geom a (RotZ rad)) rgb xyz
= (ans,newc'',newr,True)
where
(ans,newc,newr,b) = calc newc' rgb xyz
newc'' = if b then newc else newc'
newc' = Matrix a mat
mat = (m1,m2,m3)
c = cos rad
s = sin rad
m1 = ( c, s, 0, 0)
m2 = (-s, c, 0, 0)
m3 = ( 0, 0, 1, 0)
-- conflate matrices together and into planes planes...
reduceM (Object X) mata
= case (mat1x4 (1,0,0,0) mata) of
(x,y,z,w) -> (Object (Plane x y z w),True)
reduceM (Object Y) mata
= case (mat1x4 (0,1,0,0) mata) of
(x,y,z,w) -> (Object (Plane x y z w),True)
reduceM (Object Z) mata
= case (mat1x4 (0,0,1,0) mata) of
(x,y,z,w) -> (Object (Plane x y z w),True)
reduceM (Object (Plane a b c d)) mata
= case (mat1x4 (a,b,c,d) mata) of
(x,y,z,w) -> (Object (Plane x y z w),True)
reduceM (Matrix b matb) mata
= case (mat4x4 mata matb) of
matc -> (Matrix b matc,True)
reduceM _ _ = (no,False)
| null | https://raw.githubusercontent.com/ghc/nofib/f34b90b5a6ce46284693119a06d1133908b11856/gc/fulsom/Csg.hs | haskell | no is returned when there is "no" change to the csg.
conflate matrices together and into planes planes... |
- ( The Solid Modeller , written in Haskell )
-
- Copyright 1990,1991,1992,1993 Duncan Sinclair
-
- Permissiom to use , copy , modify , and distribute this software for any
- purpose and without fee is hereby granted , provided that the above
- copyright notice and this permission notice appear in all copies , and
- that my name not be used in advertising or publicity pertaining to this
- software without specific , written prior permission . I makes no
- representations about the suitability of this software for any purpose .
- It is provided ` ` as is '' without express or implied warranty .
-
- Duncan Sinclair 1993 .
-
- CSG evaluation engine .
-
- Fulsom (The Solid Modeller, written in Haskell)
-
- Copyright 1990,1991,1992,1993 Duncan Sinclair
-
- Permissiom to use, copy, modify, and distribute this software for any
- purpose and without fee is hereby granted, provided that the above
- copyright notice and this permission notice appear in all copies, and
- that my name not be used in advertising or publicity pertaining to this
- software without specific, written prior permission. I makes no
- representations about the suitability of this software for any purpose.
- It is provided ``as is'' without express or implied warranty.
-
- Duncan Sinclair 1993.
-
- CSG evaluation engine.
-
-}
module Csg(calc) where
import Matrix
import Types
import Interval
no = error ("Evaluated dead csg.")
calc :: Csg -> Calc
calc (Func f) rgb xyz = f rgb xyz
calc (Matrix a mat) rgb xyz
= (ans,newc,newr,prune)
where
newc = if prune then (if b then newc' else newc'') else (no)
(newc',b) = if prune then (reduceM newc'' mat) else (no)
xyz' = mat4x1 mat xyz
(ans,newc'',newr,prune) = calc a rgb xyz'
calc (Object X) rgb (x,y,z) = (x,no,rgb,False)
calc (Object Y) rgb (x,y,z) = (y,no,rgb,False)
calc (Object Z) rgb (x,y,z) = (z,no,rgb,False)
calc (Object (Plane a b c d)) rgb xyz
= (ans,(no),rgb,False)
where
ans = dorow (a,b,c,d) xyz
calc (Object (Sphere a b c r)) rgb xyz
= (ans,newc,rgb,True)
where
(ans,_,_,_) = calc newc rgb xyz
newc = Func f
f rgb zyx = (sphere zyx,no,rgb,False)
sphere :: (R3 BI) -> BI
sphere (x,y,z) = sqr (x-a') + sqr (y-b') + sqr (z-c') - sqr r'
a' = realToFrac a ; b' = realToFrac b ; c' = realToFrac c
r' = realToFrac r
calc (Object (Cube a b c r)) rgb xyz
= (ans,newc',rgb,bool)
where
newc'' = if bool then newc else newc'
(ans,newc,_,bool) = calc newc' rgb xyz
newc' = Inter xx (Inter yy zz)
xx = Inter x1 x2
yy = Inter y1 y2
zz = Inter z1 z2
x1 = Object (Plane ( 1) 0 0 (-(a+r)))
y1 = Object (Plane 0 ( 1) 0 (-(b+r)))
z1 = Object (Plane 0 0 ( 1) (-(c+r)))
x2 = Object (Plane (-1) 0 0 ( (a-r)))
y2 = Object (Plane 0 (-1) 0 ( (b-r)))
z2 = Object (Plane 0 0 (-1) ( (c-r)))
calc (Union a b) rgb xyz
= (min an1 an2,newc,newr,bool)
where
(an1,c1,rgb1,b1) = calc a rgb xyz
(an2,c2,rgb2,b2) = calc b rgb xyz
bool = b1 || b2
ca = if b1 then c1 else a
cb = if b2 then c2 else b
newr | an1 < an2 = rgb1
| an1 > an2 = rgb2
| otherwise = rgb
newc | an1 < an2 = ca
| an1 > an2 = cb
| not bool = (no)
| otherwise = Union ca cb
calc (Inter a b) rgb xyz
= (max an1 an2,newc,newr,bool)
where
(an1,c1,rgb1,b1) = calc a rgb xyz
(an2,c2,rgb2,b2) = calc b rgb xyz
bool = b1 || b2
ca = if b1 then c1 else a
cb = if b2 then c2 else b
newr | an1 > an2 = rgb1
| an1 < an2 = rgb2
| otherwise = rgb
newc | an1 > an2 = ca
| an1 < an2 = cb
| not bool = (no)
| otherwise = Inter ca cb
calc (Comp a) rgb xyz
= (ans,newc'',newr,True)
where
(ans,newc,newr,b) = calc newc' rgb xyz
newc'' = if b then newc else newc'
newc' = Matrix a mat
mat = (m1,m2,m3)
m1 = (-1, 0, 0, 0)
m2 = ( 0,-1, 0, 0)
m3 = ( 0, 0,-1, 0)
calc (Colour c a) rgb xyz
= (ans,newc,c,bool)
where
newc = if bool then (Colour c newc') else (no)
(ans,newc',_,bool) = calc a c xyz
calc (Sub a b) rgb xyz
= (ans,newc'',newr,True)
where
newc' = (a `Inter` (Comp b))
newc'' = if bool then newc else newc'
(ans,newc,newr,bool) = calc newc' rgb xyz
calc (Geom a (Trans h w d)) rgb xyz
= (ans,newc'',newr,True)
where
(ans,newc,newr,b) = calc newc' rgb xyz
newc'' = if b then newc else newc'
newc' = Matrix a mat
mat = (m1,m2,m3)
m1 = ( 1, 0, 0, h)
m2 = ( 0, 1, 0, w)
m3 = ( 0, 0, 1, d)
calc (Geom a (Scale h w d)) rgb xyz
= (ans,newc'',newr,True)
where
(ans,newc,newr,b) = calc newc' rgb xyz
newc'' = if b then newc else newc'
newc' = Matrix a mat
mat = (m1,m2,m3)
m1 = ( h, 0, 0, 0)
m2 = ( 0, w, 0, 0)
m3 = ( 0, 0, d, 0)
calc (Geom a (RotX rad)) rgb xyz
= (ans,newc'',newr,True)
where
(ans,newc,newr,b) = calc newc' rgb xyz
newc'' = if b then newc else newc'
newc' = Matrix a mat
mat = (m1,m2,m3)
c = cos rad
s = sin rad
m1 = ( 1, 0, 0, 0)
m2 = ( 0, c,-s, 0)
m3 = ( 0, s, c, 0)
calc (Geom a (RotY rad)) rgb xyz
= (ans,newc'',newr,True)
where
(ans,newc,newr,b) = calc newc' rgb xyz
newc'' = if b then newc else newc'
newc' = Matrix a mat
mat = (m1,m2,m3)
c = cos rad
s = sin rad
m1 = ( c, 0, s, 0)
m2 = ( 0, 1, 0, 0)
m3 = (-s, 0, c, 0)
calc (Geom a (RotZ rad)) rgb xyz
= (ans,newc'',newr,True)
where
(ans,newc,newr,b) = calc newc' rgb xyz
newc'' = if b then newc else newc'
newc' = Matrix a mat
mat = (m1,m2,m3)
c = cos rad
s = sin rad
m1 = ( c, s, 0, 0)
m2 = (-s, c, 0, 0)
m3 = ( 0, 0, 1, 0)
reduceM (Object X) mata
= case (mat1x4 (1,0,0,0) mata) of
(x,y,z,w) -> (Object (Plane x y z w),True)
reduceM (Object Y) mata
= case (mat1x4 (0,1,0,0) mata) of
(x,y,z,w) -> (Object (Plane x y z w),True)
reduceM (Object Z) mata
= case (mat1x4 (0,0,1,0) mata) of
(x,y,z,w) -> (Object (Plane x y z w),True)
reduceM (Object (Plane a b c d)) mata
= case (mat1x4 (a,b,c,d) mata) of
(x,y,z,w) -> (Object (Plane x y z w),True)
reduceM (Matrix b matb) mata
= case (mat4x4 mata matb) of
matc -> (Matrix b matc,True)
reduceM _ _ = (no,False)
|
87832b9a77670e392314d3ac276b9b72f9542c945d097e4ea0dc24fc62b32734 | igorhvr/bedlam | srfi-89-code.scm | ;------------------------------------------------------------------------------
Macro expander for define * .
(define-macro (define* pattern . body)
(if (pair? pattern)
`(define ,(car pattern)
(lambda* ,(cdr pattern) ,@body))
`(define ,pattern ,@body)))
Macro expander for lambda * .
(define-macro (lambda* formals . body)
;------------------------------------------------------------------------------
; Procedures needed at expansion time.
(define (parse-formals formals)
(define (variable? x) (symbol? x))
(define (required-positional? x)
(variable? x))
(define (optional-positional? x)
(and (pair? x)
(pair? (cdr x))
(null? (cddr x))
(variable? (car x))))
(define (required-named? x)
(and (pair? x)
(pair? (cdr x))
(null? (cddr x))
(keyword? (car x))
(variable? (cadr x))))
(define (optional-named? x)
(and (pair? x)
(pair? (cdr x))
(pair? (cddr x))
(null? (cdddr x))
(keyword? (car x))
(variable? (cadr x))))
(define (named? x)
(or (required-named? x)
(optional-named? x)))
(define (duplicates? lst)
(cond ((null? lst)
#f)
((memq (car lst) (cdr lst))
#t)
(else
(duplicates? (cdr lst)))))
(define (parse-positional-section lst cont)
(let loop1 ((lst lst) (rev-reqs '()))
(if (and (pair? lst)
(required-positional? (car lst)))
(loop1 (cdr lst) (cons (car lst) rev-reqs))
(let loop2 ((lst lst) (rev-opts '()))
(if (and (pair? lst)
(optional-positional? (car lst)))
(loop2 (cdr lst) (cons (car lst) rev-opts))
(cont lst (cons (reverse rev-reqs) (reverse rev-opts))))))))
(define (parse-named-section lst cont)
(let loop ((lst lst) (rev-named '()))
(if (and (pair? lst)
(named? (car lst)))
(loop (cdr lst) (cons (car lst) rev-named))
(cont lst (reverse rev-named)))))
(define (parse-rest lst
positional-before-named?
positional-reqs/opts
named)
(if (null? lst)
(parse-end positional-before-named?
positional-reqs/opts
named
#f)
(if (variable? lst)
(parse-end positional-before-named?
positional-reqs/opts
named
lst)
(error "syntax error in formal parameter list"))))
(define (parse-end positional-before-named?
positional-reqs/opts
named
rest)
(let ((positional-reqs (car positional-reqs/opts))
(positional-opts (cdr positional-reqs/opts)))
(let ((vars
(append positional-reqs
(map car positional-opts)
(map cadr named)
(if rest (list rest) '())))
(keys
(map car named)))
(cond ((duplicates? vars)
(error "duplicate variable in formal parameter list"))
((duplicates? keys)
(error "duplicate keyword in formal parameter list"))
(else
(list positional-before-named?
positional-reqs
positional-opts
named
rest))))))
(define (parse lst)
(if (and (pair? lst)
(named? (car lst)))
(parse-named-section
lst
(lambda (lst named)
(parse-positional-section
lst
(lambda (lst positional-reqs/opts)
(parse-rest lst
#f
positional-reqs/opts
named)))))
(parse-positional-section
lst
(lambda (lst positional-reqs/opts)
(parse-named-section
lst
(lambda (lst named)
(parse-rest lst
#t
positional-reqs/opts
named)))))))
(parse formals))
(define (expand-lambda* formals body)
(define (range lo hi)
(if (< lo hi)
(cons lo (range (+ lo 1) hi))
'()))
(define (expand positional-before-named?
positional-reqs
positional-opts
named
rest)
direct R5RS equivalent
`(lambda ,(append positional-reqs (or rest '())) ,@body)
(let ()
(define utility-fns
`(,@(if (or positional-before-named?
(null? positional-reqs))
`()
`(($req
(lambda ()
(if (pair? $args)
(let ((arg (car $args)))
(set! $args (cdr $args))
arg)
(error "too few actual parameters"))))))
,@(if (null? positional-opts)
`()
`(($opt
(lambda (default)
(if (pair? $args)
(let ((arg (car $args)))
(set! $args (cdr $args))
arg)
(default))))))))
(define positional-bindings
`(,@(if positional-before-named?
`()
(map (lambda (x)
`(,x ($req)))
positional-reqs))
,@(map (lambda (x)
`(,(car x) ($opt (lambda () ,(cadr x)))))
positional-opts)))
(define named-bindings
(if (null? named)
`()
`(($key-values
(vector ,@(map (lambda (x) `$undefined)
named)))
($args
($process-keys
$args
',(make-perfect-hash-table
(map (lambda (x i)
(cons (car x) i))
named
(range 0 (length named))))
$key-values))
,@(map (lambda (x i)
`(,(cadr x)
,(if (null? (cddr x))
`($req-key $key-values ,i)
`($opt-key $key-values ,i (lambda ()
,(caddr x))))))
named
(range 0 (length named))))))
(define rest-binding
(if (not rest)
`(($args (or (null? $args)
(error "too many actual parameters"))))
`((,rest $args))))
(let ((bindings
(append (if positional-before-named?
(append utility-fns
positional-bindings
named-bindings)
(append named-bindings
utility-fns
positional-bindings))
rest-binding)))
`(lambda ,(append (if positional-before-named?
positional-reqs
'())
'$args)
(let* ,bindings
,@body))))))
(apply expand (parse-formals formals)))
(define (make-perfect-hash-table alist)
; "alist" is a list of pairs of the form "(keyword . value)"
; The result is a perfect hash-table represented as a vector of
; length 2*N, where N is the hash modulus. If the keyword K is in
; the hash-table it is at index
;
X = ( * 2 ( $ hash - keyword K N ) )
;
; and the associated value is at index X+1.
(let loop1 ((n (length alist)))
(let ((v (make-vector (* 2 n) #f)))
(let loop2 ((lst alist))
(if (pair? lst)
(let* ((key-val (car lst))
(key (car key-val)))
(let ((x (* 2 ($hash-keyword key n))))
(if (vector-ref v x)
(loop1 (+ n 1))
(begin
(vector-set! v x key)
(vector-set! v (+ x 1) (cdr key-val))
(loop2 (cdr lst))))))
v)))))
(define ($hash-keyword key n)
(let ((str (keyword->string key)))
(let loop ((h 0) (i 0))
(if (< i (string-length str))
(loop (modulo (+ (* h 65536) (char->integer (string-ref str i)))
n)
(+ i 1))
h))))
(expand-lambda* formals body))
;------------------------------------------------------------------------------
; Procedures needed at run time (called by the expanded code):
; Perfect hash-tables with keyword keys.
(define ($hash-keyword key n)
(let ((str (keyword->string key)))
(let loop ((h 0) (i 0))
(if (< i (string-length str))
(loop (modulo (+ (* h 65536) (char->integer (string-ref str i)))
n)
(+ i 1))
h))))
(define ($perfect-hash-table-lookup table key)
(let* ((n (quotient (vector-length table) 2))
(x (* 2 ($hash-keyword key n))))
(and (eq? (vector-ref table x) key)
(vector-ref table (+ x 1)))))
; Handling of named parameters.
(define $undefined (list 'undefined))
(define ($req-key key-values i)
(let ((val (vector-ref key-values i)))
(if (eq? val $undefined)
(error "a required named parameter was not provided")
val)))
(define ($opt-key key-values i default)
(let ((val (vector-ref key-values i)))
(if (eq? val $undefined)
(default)
val)))
(define ($process-keys args key-hash-table key-values)
(let loop ((args args))
(if (null? args)
args
(let ((k (car args)))
(if (not (keyword? k))
args
(let ((i ($perfect-hash-table-lookup key-hash-table k)))
(if (not i)
(error "unknown parameter keyword" k)
(if (null? (cdr args))
(error "a value was expected after keyword" k)
(begin
(if (eq? (vector-ref key-values i) $undefined)
(vector-set! key-values i (cadr args))
(error "duplicate parameter" k))
(loop (cddr args)))))))))))
;------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/igorhvr/bedlam/b62e0d047105bb0473bdb47c58b23f6ca0f79a4e/iasylum/srfi-89-code.scm | scheme | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
Procedures needed at expansion time.
"alist" is a list of pairs of the form "(keyword . value)"
The result is a perfect hash-table represented as a vector of
length 2*N, where N is the hash modulus. If the keyword K is in
the hash-table it is at index
and the associated value is at index X+1.
------------------------------------------------------------------------------
Procedures needed at run time (called by the expanded code):
Perfect hash-tables with keyword keys.
Handling of named parameters.
------------------------------------------------------------------------------ |
Macro expander for define * .
(define-macro (define* pattern . body)
(if (pair? pattern)
`(define ,(car pattern)
(lambda* ,(cdr pattern) ,@body))
`(define ,pattern ,@body)))
Macro expander for lambda * .
(define-macro (lambda* formals . body)
(define (parse-formals formals)
(define (variable? x) (symbol? x))
(define (required-positional? x)
(variable? x))
(define (optional-positional? x)
(and (pair? x)
(pair? (cdr x))
(null? (cddr x))
(variable? (car x))))
(define (required-named? x)
(and (pair? x)
(pair? (cdr x))
(null? (cddr x))
(keyword? (car x))
(variable? (cadr x))))
(define (optional-named? x)
(and (pair? x)
(pair? (cdr x))
(pair? (cddr x))
(null? (cdddr x))
(keyword? (car x))
(variable? (cadr x))))
(define (named? x)
(or (required-named? x)
(optional-named? x)))
(define (duplicates? lst)
(cond ((null? lst)
#f)
((memq (car lst) (cdr lst))
#t)
(else
(duplicates? (cdr lst)))))
(define (parse-positional-section lst cont)
(let loop1 ((lst lst) (rev-reqs '()))
(if (and (pair? lst)
(required-positional? (car lst)))
(loop1 (cdr lst) (cons (car lst) rev-reqs))
(let loop2 ((lst lst) (rev-opts '()))
(if (and (pair? lst)
(optional-positional? (car lst)))
(loop2 (cdr lst) (cons (car lst) rev-opts))
(cont lst (cons (reverse rev-reqs) (reverse rev-opts))))))))
(define (parse-named-section lst cont)
(let loop ((lst lst) (rev-named '()))
(if (and (pair? lst)
(named? (car lst)))
(loop (cdr lst) (cons (car lst) rev-named))
(cont lst (reverse rev-named)))))
(define (parse-rest lst
positional-before-named?
positional-reqs/opts
named)
(if (null? lst)
(parse-end positional-before-named?
positional-reqs/opts
named
#f)
(if (variable? lst)
(parse-end positional-before-named?
positional-reqs/opts
named
lst)
(error "syntax error in formal parameter list"))))
(define (parse-end positional-before-named?
positional-reqs/opts
named
rest)
(let ((positional-reqs (car positional-reqs/opts))
(positional-opts (cdr positional-reqs/opts)))
(let ((vars
(append positional-reqs
(map car positional-opts)
(map cadr named)
(if rest (list rest) '())))
(keys
(map car named)))
(cond ((duplicates? vars)
(error "duplicate variable in formal parameter list"))
((duplicates? keys)
(error "duplicate keyword in formal parameter list"))
(else
(list positional-before-named?
positional-reqs
positional-opts
named
rest))))))
(define (parse lst)
(if (and (pair? lst)
(named? (car lst)))
(parse-named-section
lst
(lambda (lst named)
(parse-positional-section
lst
(lambda (lst positional-reqs/opts)
(parse-rest lst
#f
positional-reqs/opts
named)))))
(parse-positional-section
lst
(lambda (lst positional-reqs/opts)
(parse-named-section
lst
(lambda (lst named)
(parse-rest lst
#t
positional-reqs/opts
named)))))))
(parse formals))
(define (expand-lambda* formals body)
(define (range lo hi)
(if (< lo hi)
(cons lo (range (+ lo 1) hi))
'()))
(define (expand positional-before-named?
positional-reqs
positional-opts
named
rest)
direct R5RS equivalent
`(lambda ,(append positional-reqs (or rest '())) ,@body)
(let ()
(define utility-fns
`(,@(if (or positional-before-named?
(null? positional-reqs))
`()
`(($req
(lambda ()
(if (pair? $args)
(let ((arg (car $args)))
(set! $args (cdr $args))
arg)
(error "too few actual parameters"))))))
,@(if (null? positional-opts)
`()
`(($opt
(lambda (default)
(if (pair? $args)
(let ((arg (car $args)))
(set! $args (cdr $args))
arg)
(default))))))))
(define positional-bindings
`(,@(if positional-before-named?
`()
(map (lambda (x)
`(,x ($req)))
positional-reqs))
,@(map (lambda (x)
`(,(car x) ($opt (lambda () ,(cadr x)))))
positional-opts)))
(define named-bindings
(if (null? named)
`()
`(($key-values
(vector ,@(map (lambda (x) `$undefined)
named)))
($args
($process-keys
$args
',(make-perfect-hash-table
(map (lambda (x i)
(cons (car x) i))
named
(range 0 (length named))))
$key-values))
,@(map (lambda (x i)
`(,(cadr x)
,(if (null? (cddr x))
`($req-key $key-values ,i)
`($opt-key $key-values ,i (lambda ()
,(caddr x))))))
named
(range 0 (length named))))))
(define rest-binding
(if (not rest)
`(($args (or (null? $args)
(error "too many actual parameters"))))
`((,rest $args))))
(let ((bindings
(append (if positional-before-named?
(append utility-fns
positional-bindings
named-bindings)
(append named-bindings
utility-fns
positional-bindings))
rest-binding)))
`(lambda ,(append (if positional-before-named?
positional-reqs
'())
'$args)
(let* ,bindings
,@body))))))
(apply expand (parse-formals formals)))
(define (make-perfect-hash-table alist)
X = ( * 2 ( $ hash - keyword K N ) )
(let loop1 ((n (length alist)))
(let ((v (make-vector (* 2 n) #f)))
(let loop2 ((lst alist))
(if (pair? lst)
(let* ((key-val (car lst))
(key (car key-val)))
(let ((x (* 2 ($hash-keyword key n))))
(if (vector-ref v x)
(loop1 (+ n 1))
(begin
(vector-set! v x key)
(vector-set! v (+ x 1) (cdr key-val))
(loop2 (cdr lst))))))
v)))))
(define ($hash-keyword key n)
(let ((str (keyword->string key)))
(let loop ((h 0) (i 0))
(if (< i (string-length str))
(loop (modulo (+ (* h 65536) (char->integer (string-ref str i)))
n)
(+ i 1))
h))))
(expand-lambda* formals body))
(define ($hash-keyword key n)
(let ((str (keyword->string key)))
(let loop ((h 0) (i 0))
(if (< i (string-length str))
(loop (modulo (+ (* h 65536) (char->integer (string-ref str i)))
n)
(+ i 1))
h))))
(define ($perfect-hash-table-lookup table key)
(let* ((n (quotient (vector-length table) 2))
(x (* 2 ($hash-keyword key n))))
(and (eq? (vector-ref table x) key)
(vector-ref table (+ x 1)))))
(define $undefined (list 'undefined))
(define ($req-key key-values i)
(let ((val (vector-ref key-values i)))
(if (eq? val $undefined)
(error "a required named parameter was not provided")
val)))
(define ($opt-key key-values i default)
(let ((val (vector-ref key-values i)))
(if (eq? val $undefined)
(default)
val)))
(define ($process-keys args key-hash-table key-values)
(let loop ((args args))
(if (null? args)
args
(let ((k (car args)))
(if (not (keyword? k))
args
(let ((i ($perfect-hash-table-lookup key-hash-table k)))
(if (not i)
(error "unknown parameter keyword" k)
(if (null? (cdr args))
(error "a value was expected after keyword" k)
(begin
(if (eq? (vector-ref key-values i) $undefined)
(vector-set! key-values i (cadr args))
(error "duplicate parameter" k))
(loop (cddr args)))))))))))
|
9cc1ef9d33d2d0c9db8facafdb178fe12603c51cde231c89b2427d0595544de9 | onaio/milia | organization.cljc | (ns milia.api.organization
(:refer-clojure :exclude [update])
(:require [milia.api.http :refer [parse-http]]
[milia.utils.remote :refer [make-url]]
#?(:cljs [cljs.core.async :refer [put!]])))
(def internal-members-team-name "members")
(def owners-team-name "Owners")
(def editor-role "editor")
(defn all
"List all the organizations belonging to the account making the request.
When a username is provided, return only those organizations shared by both
the account making the request and the user associated with the username."
[& [username]]
(let [url (make-url (if username
(str "orgs.json?shared_with=" username)
"orgs.json"))]
(parse-http :get url)))
(defn create [data]
(let [url (make-url "orgs.json")]
(parse-http :post url :http-options {:form-params data}
:suppress-4xx-exceptions? true
:as-map? true)))
(defn profile
[org-name & {:keys [no-cache?]}]
(when (seq org-name)
(let [url (make-url "orgs" (str org-name ".json"))]
(parse-http :get url :no-cache? no-cache?))))
(defn retrieve-org-metadata
[username]
(:metadata (profile username)))
(defn can-user-create-project-under-organization?
"Return whether a user can create projects within an organization"
[username-to-check organization]
(let [role
(->> organization
:users
(filter #(= (:user %) username-to-check))
first
:role)]
(or (= role "manager")
(= role "owner"))))
(defn get-organizations-where-user-can-create-projects
[username-to-check]
(filter #(can-user-create-project-under-organization?
username-to-check %) (all)))
(defn teams-all
"Return all the teams for an organization."
([]
(teams-all nil))
([organization-name]
(let [base-url (make-url "teams.json")
url (if organization-name
(str base-url "?org=" organization-name)
base-url)]
(parse-http :get url))))
(defn teams
"Return the teams for an organization, removing 'members' team that is used
internall by the API to store non-team based org members."
[org-name]
(let [teams (teams-all)]
(remove #(or (= internal-members-team-name (:name %))
(not= org-name (:organization %))) teams)))
(defn team-info [org-name team-id]
(let [url (make-url "teams" org-name (str team-id ".json"))]
(parse-http :get url)))
(defn team-members [team-id]
(let [url (make-url "teams" team-id "members.json")]
(parse-http :get url)))
(defn create-team
"Add a team to an organization"
[params]
(let [url (make-url "teams.json")]
(parse-http :post url :http-options {:form-params params})))
(defn add-team-member
"Add a user to a team"
[org-name team-id user]
(let [url (make-url "teams" org-name team-id "members.json")]
(parse-http :post url :http-options {:form-params user})))
(defn members [org-name]
(let [url (make-url "orgs" org-name "members.json")]
(parse-http :get url)))
(defn add-member
"Add a user to an organization"
([org-name member]
(add-member org-name member nil))
([org-name member role]
(let [url (make-url "orgs" org-name "members.json")
assigned-role (or role editor-role)]
(parse-http :post
url
:http-options
#?(:clj {:form-params {:username member
:role assigned-role}
:content-type :json})
#?(:cljs {:json-params {:username member
:role assigned-role}})
:suppress-4xx-exceptions? true
:as-map? true))))
(defn change-org-member-role
"Change the role of an organization member"
[member org-name event-chan]
(let [data {:username (:username member)
:role (:role member)}]
(parse-http :put
(make-url "orgs" org-name "members.json")
:callback
#?(:clj nil
:cljs #(put! event-chan {:updated-member member}))
:http-options
#?(:clj {:form-params data
:content-type :json})
#?(:cljs {:json-params data})
:as-map? true)))
(defn remove-member
"Remove a user from an organization or organization team"
([org-name member]
(remove-member org-name member nil))
([org-name member team-id]
(let [url (if team-id
(make-url "teams" org-name team-id "members.json")
(make-url "orgs" org-name "members.json"))]
(parse-http :delete url
:http-options {:query-params {:username member}}))))
(defn single-owner?
"Is the user the only member of the Owners team."
([team members]
(and (= owners-team-name (:name team))
(= 1 (count members)))))
(defn single-owner-member?
"Is user only members in org with owner role?"
[org-name]
(let [org (profile org-name)
users (:users org)
owner-roles (filter #(= "owner" %) (map :role users))]
(= (count owner-roles) 1)))
(defn update
"update organization profile"
[params]
(let [org-name (:org params)
url (make-url "orgs" (str org-name ".json"))
params (dissoc params :org)]
(when (seq org-name)
(parse-http
:patch
url
:http-options
#?(:clj {:form-params params
:content-type :json})
#?(:cljs {:json-params params})
:as-map? true))))
(defn get-team
"Returns an Organizaion team given the team name."
[org-name team-name]
(let [url (make-url (str "teams.json?org=" org-name))
teams (parse-http :get url :suppress-4xx-exceptions? true)]
(first (remove #(not= team-name (:name %)) teams))))
(defn share-team
"Changes default_role permissions on a project for a team"
[team-id data]
(let [url (make-url "teams" team-id "share.json")]
(parse-http :post url
:http-options
#?(:clj {:form-params data
:content-type :json})
#?(:cljs {:json-params data})
:as-map? true)))
| null | https://raw.githubusercontent.com/onaio/milia/718ac4d2952417d1db845bf17ea54663ac7fa6a8/src/milia/api/organization.cljc | clojure | (ns milia.api.organization
(:refer-clojure :exclude [update])
(:require [milia.api.http :refer [parse-http]]
[milia.utils.remote :refer [make-url]]
#?(:cljs [cljs.core.async :refer [put!]])))
(def internal-members-team-name "members")
(def owners-team-name "Owners")
(def editor-role "editor")
(defn all
"List all the organizations belonging to the account making the request.
When a username is provided, return only those organizations shared by both
the account making the request and the user associated with the username."
[& [username]]
(let [url (make-url (if username
(str "orgs.json?shared_with=" username)
"orgs.json"))]
(parse-http :get url)))
(defn create [data]
(let [url (make-url "orgs.json")]
(parse-http :post url :http-options {:form-params data}
:suppress-4xx-exceptions? true
:as-map? true)))
(defn profile
[org-name & {:keys [no-cache?]}]
(when (seq org-name)
(let [url (make-url "orgs" (str org-name ".json"))]
(parse-http :get url :no-cache? no-cache?))))
(defn retrieve-org-metadata
[username]
(:metadata (profile username)))
(defn can-user-create-project-under-organization?
"Return whether a user can create projects within an organization"
[username-to-check organization]
(let [role
(->> organization
:users
(filter #(= (:user %) username-to-check))
first
:role)]
(or (= role "manager")
(= role "owner"))))
(defn get-organizations-where-user-can-create-projects
[username-to-check]
(filter #(can-user-create-project-under-organization?
username-to-check %) (all)))
(defn teams-all
"Return all the teams for an organization."
([]
(teams-all nil))
([organization-name]
(let [base-url (make-url "teams.json")
url (if organization-name
(str base-url "?org=" organization-name)
base-url)]
(parse-http :get url))))
(defn teams
"Return the teams for an organization, removing 'members' team that is used
internall by the API to store non-team based org members."
[org-name]
(let [teams (teams-all)]
(remove #(or (= internal-members-team-name (:name %))
(not= org-name (:organization %))) teams)))
(defn team-info [org-name team-id]
(let [url (make-url "teams" org-name (str team-id ".json"))]
(parse-http :get url)))
(defn team-members [team-id]
(let [url (make-url "teams" team-id "members.json")]
(parse-http :get url)))
(defn create-team
"Add a team to an organization"
[params]
(let [url (make-url "teams.json")]
(parse-http :post url :http-options {:form-params params})))
(defn add-team-member
"Add a user to a team"
[org-name team-id user]
(let [url (make-url "teams" org-name team-id "members.json")]
(parse-http :post url :http-options {:form-params user})))
(defn members [org-name]
(let [url (make-url "orgs" org-name "members.json")]
(parse-http :get url)))
(defn add-member
"Add a user to an organization"
([org-name member]
(add-member org-name member nil))
([org-name member role]
(let [url (make-url "orgs" org-name "members.json")
assigned-role (or role editor-role)]
(parse-http :post
url
:http-options
#?(:clj {:form-params {:username member
:role assigned-role}
:content-type :json})
#?(:cljs {:json-params {:username member
:role assigned-role}})
:suppress-4xx-exceptions? true
:as-map? true))))
(defn change-org-member-role
"Change the role of an organization member"
[member org-name event-chan]
(let [data {:username (:username member)
:role (:role member)}]
(parse-http :put
(make-url "orgs" org-name "members.json")
:callback
#?(:clj nil
:cljs #(put! event-chan {:updated-member member}))
:http-options
#?(:clj {:form-params data
:content-type :json})
#?(:cljs {:json-params data})
:as-map? true)))
(defn remove-member
"Remove a user from an organization or organization team"
([org-name member]
(remove-member org-name member nil))
([org-name member team-id]
(let [url (if team-id
(make-url "teams" org-name team-id "members.json")
(make-url "orgs" org-name "members.json"))]
(parse-http :delete url
:http-options {:query-params {:username member}}))))
(defn single-owner?
"Is the user the only member of the Owners team."
([team members]
(and (= owners-team-name (:name team))
(= 1 (count members)))))
(defn single-owner-member?
"Is user only members in org with owner role?"
[org-name]
(let [org (profile org-name)
users (:users org)
owner-roles (filter #(= "owner" %) (map :role users))]
(= (count owner-roles) 1)))
(defn update
"update organization profile"
[params]
(let [org-name (:org params)
url (make-url "orgs" (str org-name ".json"))
params (dissoc params :org)]
(when (seq org-name)
(parse-http
:patch
url
:http-options
#?(:clj {:form-params params
:content-type :json})
#?(:cljs {:json-params params})
:as-map? true))))
(defn get-team
"Returns an Organizaion team given the team name."
[org-name team-name]
(let [url (make-url (str "teams.json?org=" org-name))
teams (parse-http :get url :suppress-4xx-exceptions? true)]
(first (remove #(not= team-name (:name %)) teams))))
(defn share-team
"Changes default_role permissions on a project for a team"
[team-id data]
(let [url (make-url "teams" team-id "share.json")]
(parse-http :post url
:http-options
#?(:clj {:form-params data
:content-type :json})
#?(:cljs {:json-params data})
:as-map? true)))
| |
5b6539c40ecbfd9c7a1bdf2f96558cc88ab77e27e0ce9d6b4acee082f152e900 | mage2tv/magento-cache-clean | fingerprint_file.cljs | (ns magento.fingerprint-file
(:require [file.system :as fs]
[clojure.string :as string]))
(defn windowsify [path]
(string/replace path "/" "\\\\"))
(defn path-pattern [path-pattern]
(re-pattern (cond-> path-pattern
(fs/win?) windowsify)))
(defn- match-name? [path-pattern file]
(and (string? file) (re-find path-pattern file)))
(defn- file-fingerprint-fn [name-pattern]
(fn [file]
(match-name? name-pattern file)))
(defn- filenames->fingerprint-fns [type filenames]
(reduce (fn [acc filename]
(assoc acc (file-fingerprint-fn (path-pattern filename)) type)) {} filenames))
(defn- config-filetypes []
(let [res ["/etc(?:/[^/]+|)/di\\.xml$"
"/etc/widget\\.xml$"
"/etc/product_types\\.xml$"
"/etc/product_options\\.xml$"
"/etc/payment\\.xml$"
"/etc/search_request\\.xml$"
"/etc/config\\.xml$"
"/etc/indexer\\.xml$"]]
(filenames->fingerprint-fns ::config res)))
(defn- layout-filetypes []
(let [res ["/layout/.+\\.xml$"
"/ui_component/.+\\.xml$" ;; because of htmlContent blocks
"/page_layout/.+\\.xml$"]]
(filenames->fingerprint-fns ::layout res)))
(defn- translation-filetypes []
(let [res ["/i18n/.+\\.csv$"]]
(filenames->fingerprint-fns ::translation res)))
(defn- template-filetypes []
(let [res ["/templates/.+\\.phtml$"
"/etc/view\\.xml$"
"/theme\\.xml$"
"/Block/.+\\.php"]]
(assoc (filenames->fingerprint-fns ::template res)
(fn [file]
(when-let [header (fs/head file)]
(string/includes? header "Magento\\Framework\\View\\Element\\Block\\ArgumentInterface")))
::template)))
(defn- menu-filetypes []
(let [res ["/etc/adminhtml/menu\\.xml$"]]
(filenames->fingerprint-fns ::menu res)))
(defn- full-page-cache-only-filetypes []
(let [res ["/etc/frontend/sections\\.xml$" ;; section names list in head
"/view/(?:base|frontend|adminhtml)/requirejs-config\\.js$"
"/etc/csp_whitelist\\.xml$"
"/etc/schema.graphqls$"]]
(filenames->fingerprint-fns ::fpc res)))
(defn- svg-file-types []
(let [res ["\\.svg$"]]
(filenames->fingerprint-fns ::svg res)))
(def file->type
(merge (config-filetypes)
(layout-filetypes)
(translation-filetypes)
(template-filetypes)
(menu-filetypes)
(full-page-cache-only-filetypes)
(svg-file-types)))
(defn- make-ui-component->ids-fn
"Return a matcher fn where the returned cache id contains part of the file name."
[]
(let [ui-comp-pattern (path-pattern "/ui_component/(.+)\\.xml$")]
(fn [file]
(when-let [m (re-find ui-comp-pattern file)]
[(str "ui_component_configuration_data_" (second m))]))))
(defn- make-page-builder-component->ids-fn
"Return a matcher fn where the returned cache id contains part of the file name."
[]
(let [page-builder-content-type-pattern (path-pattern "/view/adminhtml/pagebuilder/content_type/(.*)\\.xml")]
(fn [file]
(when-let [m (re-find page-builder-content-type-pattern file)]
["pagebuilder_config" (str "content_type_" (second m))]))))
(defn- make-file->ids
"Configure the mapping of file name regex to cache-id's to be cleaned on
changes. It would also be possible to clear the complete config cache type
for these, but this more granular approach should allow for faster cache
rebuild times. If there are problems add them to config-filetypes above."
[]
(let [res [["/etc/adminhtml/system.*\\.xml$" ["adminhtml__backend_system_configuration_structure"]]
["/etc/queue\\.xml$" ["message_queue_config_cache"]]
["/etc/queue_consumer\\.xml$" ["message_queue_consumer_config_cache"]]
["/etc/queue_publisher\\.xml$" ["message_queue_publisher_config_cache"]]
["/etc/queue_topology\\.xml$" ["message_queue_topology_config_cache"]]
["/etc/crontab\\.xml$" ["crontab_config_cache"]]
["/hyva_checkout\\.xml$" ["checkout_config_cache" "hyva_checkout_config_cache"]]
["/etc/events\\.xml" ["global__event_config_cache"]]
["/etc/frontend/events\\.xml$" ["frontend__event_config_cache"]]
["/etc/adminhtml/events\\.xml$" ["adminhtml__event_config_cache"]]
["/etc/webapi_rest/events\\.xml$" ["webapi_rest__event_config_cache"]]
["/etc/webapi_soap/events\\.xml$" ["webapi_soap__event_config_cache"]]
["/etc/graphql/events\\.xml$" ["graphql__event_config_cache"]]
["/etc/crontab/events\\.xml$" ["crontab__event_config_cache"]]
["/etc/frontend/sections\\.xml$" ["sections_invalidation_config"]]
["/etc/email_templates\\.xml$" ["email_templates"]]
["/etc/webapi\\.xml" ["webapi_config"]]
["/etc/schema.graphqls" ["magento_framework_graphqlschemastitching_config_data"]]
["/etc/catalog_attributes\\.xml" ["catalog_attributes"]]
["/etc/sales\\.xml" ["sales_totals_config_cache"]]
["/etc/extension_attributes\\.xml" ["extension_attributes_config"]]
["/etc/acl\\.xml$" ["provider_acl_resources_cache"]]
["/etc/frontend/routes\\.xml$" ["frontend::RoutesConfig"]]
["/etc/adminhtml/routes\\.xml$" ["adminhtml::RoutesConfig"]]
["/etc/csp_whitelist\\.xml" ["global::csp_whitelist_config"
"frontend::csp_whitelist_config"
"adminhtml::csp_whitelist_config"
"webapi_rest::csp_whitelist_config"
"webapi_soap::csp_whitelist_config"
"graphql::csp_whitelist_config"]]]
id-fns (map (fn [[pattern-string ids]]
(let [re (path-pattern pattern-string)]
(fn [file]
#_(prn pattern-string)
(when (match-name? re file) ids)))) res)]
(apply some-fn (conj id-fns (make-ui-component->ids-fn) (make-page-builder-component->ids-fn)))))
(def file->ids (make-file->ids))
| null | https://raw.githubusercontent.com/mage2tv/magento-cache-clean/cb494a37c694617854c372811106f14e9b71e631/src/magento/fingerprint_file.cljs | clojure | because of htmlContent blocks
section names list in head | (ns magento.fingerprint-file
(:require [file.system :as fs]
[clojure.string :as string]))
(defn windowsify [path]
(string/replace path "/" "\\\\"))
(defn path-pattern [path-pattern]
(re-pattern (cond-> path-pattern
(fs/win?) windowsify)))
(defn- match-name? [path-pattern file]
(and (string? file) (re-find path-pattern file)))
(defn- file-fingerprint-fn [name-pattern]
(fn [file]
(match-name? name-pattern file)))
(defn- filenames->fingerprint-fns [type filenames]
(reduce (fn [acc filename]
(assoc acc (file-fingerprint-fn (path-pattern filename)) type)) {} filenames))
(defn- config-filetypes []
(let [res ["/etc(?:/[^/]+|)/di\\.xml$"
"/etc/widget\\.xml$"
"/etc/product_types\\.xml$"
"/etc/product_options\\.xml$"
"/etc/payment\\.xml$"
"/etc/search_request\\.xml$"
"/etc/config\\.xml$"
"/etc/indexer\\.xml$"]]
(filenames->fingerprint-fns ::config res)))
(defn- layout-filetypes []
(let [res ["/layout/.+\\.xml$"
"/page_layout/.+\\.xml$"]]
(filenames->fingerprint-fns ::layout res)))
(defn- translation-filetypes []
(let [res ["/i18n/.+\\.csv$"]]
(filenames->fingerprint-fns ::translation res)))
(defn- template-filetypes []
(let [res ["/templates/.+\\.phtml$"
"/etc/view\\.xml$"
"/theme\\.xml$"
"/Block/.+\\.php"]]
(assoc (filenames->fingerprint-fns ::template res)
(fn [file]
(when-let [header (fs/head file)]
(string/includes? header "Magento\\Framework\\View\\Element\\Block\\ArgumentInterface")))
::template)))
(defn- menu-filetypes []
(let [res ["/etc/adminhtml/menu\\.xml$"]]
(filenames->fingerprint-fns ::menu res)))
(defn- full-page-cache-only-filetypes []
"/view/(?:base|frontend|adminhtml)/requirejs-config\\.js$"
"/etc/csp_whitelist\\.xml$"
"/etc/schema.graphqls$"]]
(filenames->fingerprint-fns ::fpc res)))
(defn- svg-file-types []
(let [res ["\\.svg$"]]
(filenames->fingerprint-fns ::svg res)))
(def file->type
(merge (config-filetypes)
(layout-filetypes)
(translation-filetypes)
(template-filetypes)
(menu-filetypes)
(full-page-cache-only-filetypes)
(svg-file-types)))
(defn- make-ui-component->ids-fn
"Return a matcher fn where the returned cache id contains part of the file name."
[]
(let [ui-comp-pattern (path-pattern "/ui_component/(.+)\\.xml$")]
(fn [file]
(when-let [m (re-find ui-comp-pattern file)]
[(str "ui_component_configuration_data_" (second m))]))))
(defn- make-page-builder-component->ids-fn
"Return a matcher fn where the returned cache id contains part of the file name."
[]
(let [page-builder-content-type-pattern (path-pattern "/view/adminhtml/pagebuilder/content_type/(.*)\\.xml")]
(fn [file]
(when-let [m (re-find page-builder-content-type-pattern file)]
["pagebuilder_config" (str "content_type_" (second m))]))))
(defn- make-file->ids
"Configure the mapping of file name regex to cache-id's to be cleaned on
changes. It would also be possible to clear the complete config cache type
for these, but this more granular approach should allow for faster cache
rebuild times. If there are problems add them to config-filetypes above."
[]
(let [res [["/etc/adminhtml/system.*\\.xml$" ["adminhtml__backend_system_configuration_structure"]]
["/etc/queue\\.xml$" ["message_queue_config_cache"]]
["/etc/queue_consumer\\.xml$" ["message_queue_consumer_config_cache"]]
["/etc/queue_publisher\\.xml$" ["message_queue_publisher_config_cache"]]
["/etc/queue_topology\\.xml$" ["message_queue_topology_config_cache"]]
["/etc/crontab\\.xml$" ["crontab_config_cache"]]
["/hyva_checkout\\.xml$" ["checkout_config_cache" "hyva_checkout_config_cache"]]
["/etc/events\\.xml" ["global__event_config_cache"]]
["/etc/frontend/events\\.xml$" ["frontend__event_config_cache"]]
["/etc/adminhtml/events\\.xml$" ["adminhtml__event_config_cache"]]
["/etc/webapi_rest/events\\.xml$" ["webapi_rest__event_config_cache"]]
["/etc/webapi_soap/events\\.xml$" ["webapi_soap__event_config_cache"]]
["/etc/graphql/events\\.xml$" ["graphql__event_config_cache"]]
["/etc/crontab/events\\.xml$" ["crontab__event_config_cache"]]
["/etc/frontend/sections\\.xml$" ["sections_invalidation_config"]]
["/etc/email_templates\\.xml$" ["email_templates"]]
["/etc/webapi\\.xml" ["webapi_config"]]
["/etc/schema.graphqls" ["magento_framework_graphqlschemastitching_config_data"]]
["/etc/catalog_attributes\\.xml" ["catalog_attributes"]]
["/etc/sales\\.xml" ["sales_totals_config_cache"]]
["/etc/extension_attributes\\.xml" ["extension_attributes_config"]]
["/etc/acl\\.xml$" ["provider_acl_resources_cache"]]
["/etc/frontend/routes\\.xml$" ["frontend::RoutesConfig"]]
["/etc/adminhtml/routes\\.xml$" ["adminhtml::RoutesConfig"]]
["/etc/csp_whitelist\\.xml" ["global::csp_whitelist_config"
"frontend::csp_whitelist_config"
"adminhtml::csp_whitelist_config"
"webapi_rest::csp_whitelist_config"
"webapi_soap::csp_whitelist_config"
"graphql::csp_whitelist_config"]]]
id-fns (map (fn [[pattern-string ids]]
(let [re (path-pattern pattern-string)]
(fn [file]
#_(prn pattern-string)
(when (match-name? re file) ids)))) res)]
(apply some-fn (conj id-fns (make-ui-component->ids-fn) (make-page-builder-component->ids-fn)))))
(def file->ids (make-file->ids))
|
1eac6b9b3e02f21ce3cd4c0238427afc5fcb0f9f31fde531478fb5e9bdcd65e6 | zack-bitcoin/verkle | fq.erl | -module(fq).
-export([
det_pow/2,
mul/2,
add/2,
neg/1,
sub/2, %inverse/1,
inv/1,
square/1,
pow/2,
short_pow/2,
encode/1, decode/1,
encode_extended/1, decode_extended/1,
setup/1,
test/1,
ctest/1,
reverse_bytes/1,
prime/0,
sqrt/1,
e_double/1,
e_add/2,
%e_mul/2,
e_mul1/2,
e_mul2/2,
e_zero/0,
eq/2,
batch_inverse/1,
e_simplify_batch/1,
pow_/2,
e_neg/1,
gen_point/0,
gen_point/1,
extended2extended_niels/1,
extended_niels2extended/1,
is_zero/1,
extended2affine/1,
affine2extended/1,
to_affine_batch/1,
hash_point/1,
compress/1,
decompress/1
]).
-on_load(init/0).
-record(extended_point, {u, v, z, t1, t2}).
-record(extended_niels_point,
{v_plus_u, v_minus_u, t2d, z}).
% -(121665/121666)
37095705934669439343138083508754565189542113879843219016388785533085940283555
-define(D,
<<250,233,71,223,254,139,237,128,115,41,198,175,
119,135,161,16,144,134,24,188,7,146,147,229,38,
197,159,114,90,43,130,44>>).
2 * D
%16295367250680780974490674513165176452449235426866156013048779062215315747161
-define(D2,
<<244,211,143,190,253,23,219,1,231,82,140,95,239,
14,67,33,32,13,49,120,15,36,39,203,77,138,63,
229,180,86,4,89>>).
init() ->
ok = erlang:load_nif("./ebin/fq", 0),
setup(0),
ok.
setup(_) ->
%defined in C.
ok.
%This is the finite field on top of BLS12-381
is implemented on this curve .
%uses montgomery notation for faster modular multiplication.
binaries store bytes in reverse order in comparison to normal erlang binaries . This way when we pass the binaries to C , the bytes are already in order to fit into bigger registers .
-define(q,
57896044618658097711785492504343953926634992332820282019728792003956564819949
).
-define(i2 , ) .
-define(i2, <<19:256/little>>).
< < 255,255,255,255,0,0,0,0,1,164,1,0,253,91,66,172 ,
250,39,94,246,247,39,198,204,183,130,98,214,172 ,
88,18,12 > > ) .
2 ^ 256
-define(r, 115792089237316195423570985008687907853269984665640564039457584007913129639936).
2 ^ 256 rem q
-define(r1, 38).
%r*r rem q
-define(r2, 1444).
%r*r*r rem q
-define(r3, 54872).
1 / r rem q
-define(ir, 10665060850805439052171011777115991512801182798151104582581619579676209308938).
-define(encode_one, <<38:256/little>>).
< < 254,255,255,255,1,0,0,0,2,72,3,0,250,183,132,88 ,
245,79,188,236,239,79,140,153,111,5,197,172,89 ,
177,36,24 > > ) .
-define(encode_zero, <<0:256>>).
prime() -> ?q.
%todo. binary:encode_unsigned(X, little) is probably faster.
reverse_bytes(<<X:256>>) -> <<X:256/little>>.
%reverse_bytes(X) ->
% reverse_bytes(X, <<>>).
reverse_bytes(<<A , B / binary > > , R ) - >
, < < A , R / binary > > ) ;
%reverse_bytes(<<>>, R) -> R.
encode(0) -> <<0:256>>;
encode(1) -> <<38:256/little>>;
encode(A) when ((A < ?q) and (A > -1)) ->
mul(<<A:256/little>>,
<<?r2:256/little>>).
decode(C) ->
X = mul(C, (<<1:256/little>>)),
<<Y:256/little>> = X,
Y.
encode_extended(
#extended_point{
u = U, v = V, z = Z, t1 = T1, t2 = T2
}) ->
Ue = encode(U),
Ve = encode(V),
Ze = encode(Z),
T1e = encode(T1),
T2e = encode(T2),
<<Ue/binary, Ve/binary, Ze/binary,
T1e/binary, T2e/binary>>.
decode_extended(<<U2:256, V2:256, Z2:256,
T12:256, T22:256>>) ->
#extended_point{
u = decode(<<U2:256>>),
v = decode(<<V2:256>>),
z = decode(<<Z2:256>>),
t1 = decode(<<T12:256>>),
t2 = decode(<<T22:256>>)}.
encode_extended_niels(
#extended_niels_point{
v_plus_u = VPU,
v_minus_u = VMU,
t2d = T2D,
z = Z}) ->
VPUe = encode(VPU),
VMUe = encode(VMU),
T2De = encode(T2D),
Ze = encode(Z),
<<VPUe/binary, VMUe/binary, T2De/binary,
Ze/binary>>.
decode_extended_niels(
<<VPU:256, VMU:256, T2D:256, Z:256>>) ->
#extended_niels_point
{v_plus_u = decode(<<VPU:256>>),
v_minus_u = decode(<<VMU:256>>),
t2d = decode(<<T2D:256>>),
z = decode(<<Z:256>>)}.
hash_point(<<U:256>>) ->
fr:encode(U);
hash_point(<<U:256, _:256>>) ->
fr:encode(U);
hash_point(X = <<U:(256*5)>>) ->
hash_point(extended2affine(X)).
sqrt(A) ->
when prime mod 8 = 5
%
%v = (2*a) ^ ((p-5)/8)
i = 2*a*v*v
%r = +-av(i-1)
T = encode(2),
V = pow_(mul(T, A), (?q - 5) div 8),
AV = mul(A, V),
I = mul(mul(T, AV), V),
R = mul(AV, sub(I, ?encode_one)),
%{neg(R), R, T, V, AV, I}.
{neg(R), R}.
det_pow(_, 0) -> 1;
det_pow(X, 1) -> X;
det_pow(X, N) when ((N rem 2) == 0) and (N>0) ->
det_pow(X*X, N div 2);
det_pow(X, N) when (N > 0) -> X * det_pow(X, N-1).
pow_(X, Y) when is_integer(Y) ->
pow(X, reverse_bytes(<<Y:256>>)).
%these functions are defined in c.
add(_, _) -> ok.
neg(_) -> ok.
sub(_, _) -> ok.
mul(_, _) -> ok.
square(_) -> ok.
inv(X) -> encode(ff:inverse(decode(X), ?q)).
pow(_, _) -> ok.
short_pow(_, _) -> ok.
e_double(_) -> ok.
e_add(_extended, _niels) -> ok.
unused , accepts a 8 byte exponent as an integer .
e_mul1(_, _) ->
input 2 is a 32 byte integer as a little endian binary .
ok.
e_mul2(Fq, Fr) ->
%the exponent is montgomery encoded.
case fr:decode(Fr) of
0 -> e_zero();
R2 ->
%R3 = fr:reverse_bytes(<<R2:256>>),
e_mul1(Fq, <<R2:256/little>>)
end.
e_neg(<<U:256, VZ:512, T1:256, T2:256>>) ->
%neg U and T1
NU = neg(<<U:256>>),
NT1 = neg(<<T1:256>>),
<<NU/binary, VZ:512, NT1/binary, T2:256>>.
pis([], _) -> [];
pis([H|T], A) ->
X = mul(H, A),
[X|pis(T, X)].
batch_inverse(Vs) ->
[ v16 , v15 , v14 , v13 , v12 , v1 ]
%AllI = encode(ff:inverse(decode(All), ?q)),%i16
AllI = inv(All),
VI = lists:map(
fun(V) -> mul(AllI, V) end,
[ i6 , i56 , i46 , i36 , i26 ]
[ v16 , v26 , v36 , v46 , v56 , v6 ]
[ v26 , v36 , v46 , v56 , v6 , 1 ]
[ i16 , i26 , i36 , i46 , i56 , i6 ]
lists:zipwith(fun(A, B) ->
mul(A, B)
end, V4, VI2).
e_simplify_batch([]) -> [];
e_simplify_batch(Es) ->
Zs = lists:map(fun(<<_:512, Z:256, _:512>>) ->
<<Z:256>> end, Es),
false = (decode(hd(Zs)) == 0),
IZs = batch_inverse(Zs),
lists:zipwith(fun(E, IZ) ->
simplify(E, IZ)
end, Es, IZs).
simplify(<<U:256, V:256, _/binary>>, IZ) ->
U2 = mul(<<U:256>>, IZ),
V2 = mul(<<V:256>>, IZ),
<<U2/binary, V2/binary, (?encode_one)/binary,
U2/binary, V2/binary>>.
extended2affine(E) ->
[E2] = e_simplify_batch([E]),
<<A:256, B:256, _:(256*3)>> = E2,
<<A:256, B:256>>.
to_affine_batch(L) ->
L2 = e_simplify_batch(L),
lists:map(fun(<<U:256, V:256, _:(256*3)>>) ->
<<U:256, V:256>>
end, L2).
eq(A, B) ->
jubjub:eq(
decode_extended(A),
decode_extended(B)).
e_zero() ->
A = #extended_point
{u = 0, v = 1, z = 1, t1 = 0, t2 = 0},
encode_extended(A).
is_zero(
<<U:256, V:256, Z:256, _:256, _:256>>
) ->
(U == 0) and (V == Z);
is_zero(
<<VPU:256, VMU:256, T2D:256, Z:256>>
) ->
(VPU == VMU) and (VPU == Z).
extended2extended_niels([]) -> [];
extended2extended_niels([H|T]) ->
[extended2extended_niels(H)|
extended2extended_niels(T)];
extended2extended_niels(
A = <<U:256, V:256, Z:256, T1:256, T2:256>>
) ->
% B = is_zero(A),
% if
% B ->
% <<(encode(1))/binary,
% (encode(1))/binary,
% (encode(0))/binary,
% (encode(1))/binary>>;
% true ->
T3 = mul(<<T1:256>>, <<T2:256>>),
VPU = add(<<U:256>>, <<V:256>>),
VMU = sub(<<V:256>>, <<U:256>>),
T2D = mul(T3, ?D2),
<<VPU/binary, VMU/binary,
T2D/binary, Z:256>>.
% end.
extended_niels2extended([]) -> [];
extended_niels2extended([H|T]) ->
[extended_niels2extended(H)|
extended_niels2extended(T)];
extended_niels2extended(
N = <<VPU:256, VMU:256, T2D:256, Z:256>>
) ->
e_add(e_zero(), N).
affine2extended(
<<U:256, V:256>>) ->
Z = ?encode_one,
<<U:256, V:256, Z/binary, U:256, V:256>>.
-define(sub3(A, B),
if
B>A -> A + ?q - B;
true -> A - B
end).
ctest(_) ->
ok.
gen_point() ->
<<X0:256>> = crypto:strong_rand_bytes(32),
X = X0 rem ?q,
G = gen_point(encode(X), 2, 2),
true = is_on_curve(G),
G.
gen_point(U, 0, S) ->
io:fwrite("next U\n"),
gen_point(add(U, 1), S, S);
gen_point(Us, _, _) when is_list(Us) ->
UUs = lists:map(fun(X) -> mul(X, X) end, Us),
DUUs = lists:map(fun(X) -> sub(encode(1),
mul(?D, X))
end, UUs),
Bs = batch_inverse(DUUs),
VVs = lists:zipwith(
fun(B, UU) ->
mul(add(encode(1), UU), B)
end, Bs, UUs),
lists:zipwith(
fun(U, VV) ->
gen_point(U, 20, 20, VV)
end, Us, VVs);
gen_point(U, Tries, S) ->
UU = mul(U, U),
DUU = mul(?D, UU),
B = inv(sub(encode(1), DUU)),
T = add(encode(1), UU),
VV = mul(T, B),
gen_point(U, Tries, S, VV).
gen_point(U, _, S, VV) ->
case sqrt(VV) of
error ->
gen_point(add(U, encode(1)), S, S);
{V1, V2} ->
A = <<U/binary, V1/binary>>,
A2 = <<U/binary, V2/binary>>,
G = affine2extended(A),
%Prime = is_prime_order(G),
OnCurve = is_on_curve(A),
%io:fwrite(is_on_curve(A)),
if
not(OnCurve) -> gen_point(add(U, encode(1)), S, S);
%not(Prime) -> A;
true -> <<U/binary, V2/binary>>
end
end.
G = : affine2extended (
: gen_point ( ) ) ,
% encode_extended(G).
gen_point(X) ->
gen_point(X, 20, 20).
% fq:encode_extended(
: affine2extended (
: gen_point(X ) ) ) .
decompress_points(Us)
when is_list(Us) ->
UU = U*U ,
DUU = 1 - ( D * UU )
%B = inverse(DUU)
%VV = (UU+1) * B
%V = sqrt(VV)
V = ) / ( 1 - ( D * UU ) ) )
UUs = lists:map(fun(X) -> mul(X, X) end, Us),
DUUs = lists:map(
fun(X) ->
sub(?encode_one, mul(?D, X))
end, UUs),
Bs = batch_inverse(DUUs),
VVs = lists:zipwith(
fun(B, UU) ->
mul(add(?encode_one, UU), B)
end, Bs, UUs),
lists:zipwith(
fun(U, VV) ->
decompress_point2(U, VV)
end, Us, VVs).
decompress_point2(U, VV) ->
%without prime_order 372.
prime order 200 .
0.000350
error ->
error;
{V1, V2} ->
A = <<U/binary, V1/binary>>,%affine
A2 = <<U/binary, V2/binary>>,%affine
G = affine2extended(A),
B = is_on_curve(A),%this is the slow line. Is there no faster way to know? TODO.
%B = is_prime_order(G),%this is the slow line. Is there no faster way to know? TODO.
OnCurve = is_on_curve(A ) , TODO
if
B -> A;
true -> A2
end
end.
is_on_curve(<<U:256, V:256>>) ->
U2 = mul(<<U:256>>, <<U:256>>),
V2 = mul(<<V:256>>, <<V:256>>),
UV2 = mul(U2, V2),
(sub(V2, U2) ==
add(?encode_one, mul(?D, UV2))).
is_prime_order(E) ->
is_torsion_free(E) and not(identity(E)).
is_torsion_free(E) ->
%S = 6554484396890773809930967563523245729705921265872317281365359162392183254199,
%fr modulus.
R = 7237005577332262213973186563042994240857116359379907606001950938285454250989,
E2 = e_mul1(E, <<R:256/little>>),
%eq(encode(0), E2).
identity(E2).
identity(<<U:256, V:256, Z:256, Ts:512>>) ->
(U == 0) and (V == Z).
compress(L) when is_list(L) ->
L2 = to_affine_batch(L),
lists:map(fun(<<A:256, _:256>>)->
<<A:256>> end, L2).
decompress(<<A:256>>) ->
hd(decompress([<<A:256>>]));
%decompress(<<A:256>>) ->
% gen_point(decode(<<A:256>>));
decompress(L) when is_list(L) ->
L2 = decompress_points(L),
lists:map(fun(X) -> affine2extended(X) end,
L2).
points_list(Many) ->
G = jubjub:affine2extended(
jubjub:gen_point()),
G1 = jubjub:multiply(4327409, G),
points_list2(Many, G1).
points_list2(0, _) -> [];
points_list2(N, G) ->
E = encode_extended(G),
[{G, E}|
points_list2(
N-1, jubjub:multiply(9320472034, G))].
range(N, N) -> [N];
range(A, B) when (A < B) ->
[A|range(A+1, B)].
test(2) ->
io:fwrite("subtract test\n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
<<B0:256>> = crypto:strong_rand_bytes(32),
A1 = A0 rem ?q,
B1 = B0 rem ?q,
A = encode(A1),
B = encode(B1),
S = decode(sub(A, B)),
S = ((A1 - B1) + ?q) rem ?q,
success;
test(3) ->
io:fwrite("encode decode test\n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
%A1 = A0 rem ?q,
A1 = 2,
A = encode(A1),
A1 = decode(A);
%A = inverse(inverse(A));
test(5) ->
%testing addition.
io:fwrite("addition test\n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
<<B0:256>> = crypto:strong_rand_bytes(32),
A0 = 5 ,
= 7 ,
A1 = A0 rem ?q,
B1 = B0 rem ?q,
A = encode(A1),
B = encode(B1),
S = decode(add(A, B)),
S = (A1 + B1) rem ?q,
success;
test(6) ->
%testing multiplication.
io:fwrite("multiply test \n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
<<B0:256>> = crypto:strong_rand_bytes(32),
A0 = 2 ,
= 3 ,
A1 = A0 rem ?q,
B1 = B0 rem ?q,
A = encode(A1),
B = encode(B1),
S3 = (A1 * B1) rem ?q,
S3 = decode(mul(A, B)),
success;
test(8) ->
io:fwrite("more accurate multiplication speed test.\n"),
Many = 100000,
R = lists:map(fun(_) ->
<<A0:256>> = crypto:strong_rand_bytes(32),
<<B0:256>> = crypto:strong_rand_bytes(32),
{A0 rem ?q,
B0 rem ?q}
end, range(0, Many)),
R2 = lists:map(fun({X, Y}) ->
{encode(X),
encode(Y)}
end, R),
T1 = erlang:timestamp(),
lists:foldl(fun({X, Y}, _) ->
(X*Y) rem ?q,
0
end, 0, R),
T2 = erlang:timestamp(),
lists:foldl(fun({X, Y}, _) ->
mul(X, Y),
0
end, 0, R2),
T3 = erlang:timestamp(),
%erl sub
lists:foldl(fun({X, Y}, _) ->
if
(X >= Y) -> X - Y;
true -> ?q - Y + X
end,
0
end, 0, R),
T4 = erlang:timestamp(),
%c sub
lists:foldl(fun({X, Y}, _) ->
sub(X, Y)
end, 0, R2),
T5 = erlang:timestamp(),
%erl add
lists:foldl(fun({X, Y}, _) ->
C = X+Y,
if
(C > ?q) -> C - ?q;
true -> C
end,
0
end, 0, R),
T6 = erlang:timestamp(),
%c add
lists:foldl(fun({X, Y}, _) ->
add(X, Y),
0
end, 0, R2),
T7 = erlang:timestamp(),
lists:foldl(fun(_, _) -> 0 end, 0, R2),
T8 = erlang:timestamp(),
Empty = timer:now_diff(T8, T7),
MERL = timer:now_diff(T2, T1),
MC = timer:now_diff(T3, T2),
SERL = timer:now_diff(T4, T3),
SC = timer:now_diff(T5, T4),
AERL = timer:now_diff(T6, T5),
AC = timer:now_diff(T7, T6),
{{empty, Empty/Many},
{mul, {erl, (MERL - Empty)/Many},
{c, (MC - Empty)/Many}},
{sub, {erl, (SERL - Empty)/Many},
{c, (SC - Empty)/Many}},
{add, {erl, (AERL - Empty)/Many},
{c, (AC - Empty)/Many}}};
test(10) ->
io:fwrite("square test\n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
A0 = 3 ,
A = A0 rem ?q,
S1 = decode(square(encode(A))),
S2 = (A*A rem ?q),
B = S1 == S2,
{B, S1, S2};
test(11) ->
io:fwrite("inverse test\n"),
%fails.
<<A0:256>> = crypto:strong_rand_bytes(32),
A = A0 rem ?q,
A1 = encode(A),
IA = inv(A1),
A1 = inv(IA),
A = decode(A1),
%A = decode(inv(inv(encode(A)))),
%IA = decode(inv(encode(A))),
{A, IA};
test(12) ->
io:fwrite("inverse speed test\n"),
Many = 1000,
R = range(0, Many),
R2 = lists:map(
fun(_) ->
<<N0:256>> =
crypto:strong_rand_bytes(
32),
N0 rem ?q
end, R),
R3 = lists:map(
fun(X) -> encode(X) end, R2),
T1 = erlang:timestamp(),
lists:map(fun(I) -> inv(I) end, R3),
T2 = erlang:timestamp(),
lists:map(fun(I) ->
basics:inverse(I, ?q)
end, R2),
T3 = erlang:timestamp(),
{{c, timer:now_diff(T2, T1)/Many},
{erl, timer:now_diff(T3, T2)/Many}};
test(13) ->
io:fwrite("jubjub double test\n"),
P0 = jubjub:affine2extended(
jubjub:gen_point()),
B = encode_extended(P0),
P = decode_extended(e_double(B)),
P = decode_extended(e_double(B)),
P2 = jubjub:double(P0),
P2b = decode_extended(
extended_niels2extended(
extended2extended_niels(
encode_extended(P2)))),
P2c = jubjub:extended_niels2extended(
jubjub:extended2extended_niels(P2)),
P0 = jubjub:extended_niels2extended(
jubjub:extended2extended_niels(P0)),
true = jubjub:is_on_curve(
jubjub:extended2affine(P0)),
true = jubjub:is_on_curve(
jubjub:extended2affine(P2)),
true = jubjub:eq(P, P2),
true = jubjub:eq(P2, P2c),
true = jubjub:eq(P2, P2b),
success;
test(14) ->
io:fwrite("jubjub double speed test\n"),
Many = 10000,
R = range(0, Many),
R2 = points_list(Many),
io:fwrite("made points\n"),
T1 = erlang:timestamp(),
lists:foldl(fun({P, _}, _) ->
jubjub:double(jubjub:double(jubjub:double(P)))
end, 0, R2),
T2 = erlang:timestamp(),
lists:foldl(fun({_, P}, _) ->
e_double(e_double(e_double(P)))
end, 0, R2),
T3 = erlang:timestamp(),
{{erl, timer:now_diff(T2, T1)/Many/3},
{c, timer:now_diff(T3, T2)/Many/3}};
test(15) ->
io:fwrite("jubjub add\n"),
E0 = jubjub:affine2extended(
jubjub:gen_point()),
E = encode_extended(E0),
E0 = decode_extended(E),
N0 = jubjub:affine_niels2extended_niels(
jubjub:affine2affine_niels(
jubjub:gen_point())),
N = encode_extended_niels(N0),
E3 = jubjub:add(E0, N0),
E2 = decode_extended(e_add(E, N)),
E2 = decode_extended(e_add(E, N)),
N2 = extended2extended_niels(e_add(E, N)),
E4 = decode_extended(e_add(E, N2)),
true = jubjub:eq(E2, E3),
true = jubjub:is_on_curve(
jubjub:extended2affine(E2)),
true = jubjub:is_on_curve(
jubjub:extended2affine(E3)),
true = jubjub:is_on_curve(
jubjub:extended2affine(E4)),
success;
test(16) ->
io:fwrite("jubjub add speed\n"),
Many = 10000,
R = range(0, Many),
R2 = points_list(Many),
N0 = jubjub:affine_niels2extended_niels(
jubjub:affine2affine_niels(
jubjub:gen_point())),
N = encode_extended_niels(N0),
T1 = erlang:timestamp(),
lists:foldl(fun({P, _}, _) ->
jubjub:add(P, N0)
end, 0, R2),
T2 = erlang:timestamp(),
lists:foldl(fun({_, P}, _) ->
e_add(P, N)
end, 0, R2),
T3 = erlang:timestamp(),
{{erl, timer:now_diff(T2, T1)/Many},
{c, timer:now_diff(T3, T2)/Many}};
test(17) ->
io:fwrite("test pow\n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
A0 = 2 ,
A = A0 rem ?q,
<<B0:256>> = crypto:strong_rand_bytes(32),
= 2 ,
B = B0 rem ?q,
AE = encode(A),
New = decode(pow(AE,
reverse_bytes(<<B:256>>))),
AE = encode(A),
Old = basics:rlpow(A, B, ?q),
New = Old,
success;
test(18) ->
io:fwrite("test pow speed\n"),
Many = 100,
R = range(0, Many),
R2 = lists:map(
fun(_) ->
<<A0:256>> = crypto:strong_rand_bytes(32),
<<B0:256>> = crypto:strong_rand_bytes(32),
A = A0 rem ?q,
B = B0 rem ?q,
Ae = encode(A),
Be = reverse_bytes(<<B:256>>),
{A, B, Ae, Be}
end, R),
T1 = erlang:timestamp(),
lists:foldl(fun({A, B, _, _}, _) ->
basics:rlpow(A, B, ?q)
end, 0, R2),
T2 = erlang:timestamp(),
lists:foldl(fun({_, _, A, B}, _) ->
pow(A, B)
end, 0, R2),
T3 = erlang:timestamp(),
{{erl, timer:now_diff(T2, T1)/Many},
{c, timer:now_diff(T3, T2)/Many}};
test(19) ->
io:fwrite("test short_pow\n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
A = A0 rem ?q,
<<B:16>> = crypto:strong_rand_bytes(2),
C = decode(short_pow(encode(A), B)),
D = basics:rlpow(A, B, ?q),
C = D,
%{A, B, C},
success;
test(20) ->
io:fwrite("test neg\n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
A = A0 rem ?q,
NA = ?q - A,
NA = decode(neg(encode(A)));
test(21) ->
io:fwrite("testing elliptic multiplication\n"),
N0 = jubjub:affine_niels2extended_niels(
jubjub:affine2affine_niels(
jubjub:gen_point())),
N = encode_extended_niels(N0),
<<B:64>> = crypto:strong_rand_bytes(8),
B = 2 ,
%B = B0 rem ?q,
%Be = reverse_bytes(<<B:64>>),
%size(e_mul(N, Be)).
<<One:256>> = encode(1),
Me = e_mul(N, B),
M = jubjub:multiply(B, N0),
M2 = decode_extended(Me),
: eq(M , M2 ) ,
true = jubjub:eq(M, M2),
success;
test(22) ->
io:fwrite("elliptic multiplication speed test \n\n"),
Many = 1000,
R = range(0, Many),
R1 = points_list(Many),
R2 = lists:map(
fun({P, _}) ->
N0 = jubjub:extended2extended_niels(P),
N = encode_extended_niels(N0),
<<B:64>> = crypto:strong_rand_bytes(8),
{N0, N, B} end, R1),
T1 = erlang:timestamp(),
lists:foldl(fun({N0, _, B}, _) ->
jubjub:multiply(B, N0)
end, 0, R2),
T2 = erlang:timestamp(),
lists:foldl(fun({_, N, B}, _) ->
e_mul(N, B)
end, 0, R2),
T3 = erlang:timestamp(),
{{erl, timer:now_diff(T2, T1)/Many},
{c, timer:now_diff(T3, T2)/Many}};
test(23) ->
io:fwrite("testing long elliptic multiplication\n"),
N0 = jubjub:affine_niels2extended_niels(
jubjub:affine2affine_niels(
jubjub:gen_point())),
N = encode_extended_niels(N0),
<<B:256>> = crypto:strong_rand_bytes(32),
B = 18446744073709551615 ,
<<One:256>> = encode(1),
Me = e_mul1(N, reverse_bytes(<<B:256>>)),
M = jubjub:multiply(B, N0),
M2 = decode_extended(Me),
true = jubjub:eq(M, M2),
success;
test(24) ->
TODO
G = gen_point(),
GN = extended2extended_niels(G),
G2 = extended_niels2extended(GN),
true = eq(G, G2),
success;
test(25) ->
%check that both simplifies don't change the order.
Gs = [gen_point(),
gen_point(),
gen_point()],
G2s = lists:map(fun(X) -> e_double(X) end,
Gs),
G2simp = e_simplify_batch(G2s),
[true, true, true] =
lists:zipwith(fun(A, B) -> eq(A, B) end,
G2s, G2simp),
E = secp256k1:make(),
G = fun() ->
secp256k1:to_jacob(
secp256k1:gen_point(E))
end,
Ps = [G(), G(), G()],
Ps = secp256k1:simplify_Zs_batch(Ps),
success;
test(26) ->
io:fwrite("testing elliptic zero point\n"),
Z0 = e_zero(),
Z1 = e_double(Z0),
Z2 = e_add(Z0, extended2extended_niels(Z1)),
Z3 = extended_niels2extended(
extended2extended_niels(Z2)),
true = is_zero(Z0),
true = is_zero(Z1),
true = is_zero(Z2),
true = is_zero(Z3),
true = is_zero(extended2extended_niels(Z0)),
true = is_zero(extended2extended_niels(Z1)),
true = is_zero(extended2extended_niels(Z2)),
true = is_zero(extended2extended_niels(Z3)),
true = is_zero(e_mul2(extended2extended_niels(gen_point()), fr:encode(0))),
success;
test(27) ->
io:fwrite("encode decode speed test\n"),
Many = 100000,
R = range(0, Many),
R2 = lists:map(fun(X) -> encode(X) end, R),
T1 = erlang:timestamp(),
lists:foldl(fun(X, _) ->
encode(X),
0
end, 0, R),
T2 = erlang:timestamp(),
lists:foldl(fun(X, _) ->
decode(X),
0
end, 0, R2),
T3 = erlang:timestamp(),
{
{encode, (timer:now_diff(T2, T1)/Many)},
{decode, (timer:now_diff(T3, T2)/Many)}
};
test(28) ->
io:fwrite("testing e_add with niels/extended niels\n"),
G = gen_point(),
H = gen_point(),
HE = extended2extended_niels(H),
R1 = e_add(G, H),
R2 = e_add(G, HE),
eq(R1, R2);
test(29) ->
io:fwrite("testing e_add error that returns a broken point.\n"),
G = gen_point(),
Z = e_zero(),
Z1 = extended_niels2extended(
extended2extended_niels(Z)),
Bad = encode_extended(%this is the bad point.
{extended_point, 0,0,1,0,0}),
{
decode_extended(Z1),
decode_extended(e_mul2(G, fr:encode(0))),
decode_extended(e_add(G, Bad)),
decode_extended_niels(
extended2extended_niels(Bad)),
decode_extended(
extended_niels2extended(
extended2extended_niels(Bad))),
decode_extended(e_add(G, extended2extended_niels(Bad)))
};
test(30) ->
io:fwrite("testing compressing a point to 32 bytes"),
X = gen_point(),
X2 = e_add(X, X),
[<<A:256>>] = compress([X2]),
X3 = decompress(<<A:256>>),
Aff = extended2affine(X2),
Aff = extended2affine(X3),
ok;
test(31) ->
%decompressing in batches.
X = [gen_point(), gen_point()],
C = compress(X),
D = decompress(C),
C = compress(D),
D2 = decompress_points(C),
D3 = lists:map(fun(X) ->
affine2extended(X) end,
D2),
C = compress(D3),
{D3, D};
test(32) ->
%compression/decompression speed test.
Many = 300,
Range = range(0, Many),
Points = lists:map(
fun(X) ->
e_double(e_double(gen_point())) end,
Range),
T1 = erlang:timestamp(),
C = compress(Points),
T2 = erlang:timestamp(),
{ ok , _ PID } = : start ( ) ,
: trace([start , { procs , all } ] ) ,
decompress(C),
: ] ) ,
: profile ( ) ,
: analyse ( ) ,
: stop ( ) ,
T3 = erlang:timestamp(),
{{compress, (timer:now_diff(T2, T1)/Many)},
{decompress, (timer:now_diff(T3, T2)/Many)}}.
| null | https://raw.githubusercontent.com/zack-bitcoin/verkle/46bf69f17170a71829f9243faea06ee42f224687/src/crypto/fq.erl | erlang | inverse/1,
e_mul/2,
-(121665/121666)
16295367250680780974490674513165176452449235426866156013048779062215315747161
defined in C.
This is the finite field on top of BLS12-381
uses montgomery notation for faster modular multiplication.
r*r rem q
r*r*r rem q
todo. binary:encode_unsigned(X, little) is probably faster.
reverse_bytes(X) ->
reverse_bytes(X, <<>>).
reverse_bytes(<<>>, R) -> R.
v = (2*a) ^ ((p-5)/8)
r = +-av(i-1)
{neg(R), R, T, V, AV, I}.
these functions are defined in c.
the exponent is montgomery encoded.
R3 = fr:reverse_bytes(<<R2:256>>),
neg U and T1
AllI = encode(ff:inverse(decode(All), ?q)),%i16
B = is_zero(A),
if
B ->
<<(encode(1))/binary,
(encode(1))/binary,
(encode(0))/binary,
(encode(1))/binary>>;
true ->
end.
Prime = is_prime_order(G),
io:fwrite(is_on_curve(A)),
not(Prime) -> A;
encode_extended(G).
fq:encode_extended(
B = inverse(DUU)
VV = (UU+1) * B
V = sqrt(VV)
without prime_order 372.
affine
affine
this is the slow line. Is there no faster way to know? TODO.
B = is_prime_order(G),%this is the slow line. Is there no faster way to know? TODO.
S = 6554484396890773809930967563523245729705921265872317281365359162392183254199,
fr modulus.
eq(encode(0), E2).
decompress(<<A:256>>) ->
gen_point(decode(<<A:256>>));
A1 = A0 rem ?q,
A = inverse(inverse(A));
testing addition.
testing multiplication.
erl sub
c sub
erl add
c add
fails.
A = decode(inv(inv(encode(A)))),
IA = decode(inv(encode(A))),
{A, B, C},
B = B0 rem ?q,
Be = reverse_bytes(<<B:64>>),
size(e_mul(N, Be)).
check that both simplifies don't change the order.
this is the bad point.
decompressing in batches.
compression/decompression speed test. | -module(fq).
-export([
det_pow/2,
mul/2,
add/2,
neg/1,
inv/1,
square/1,
pow/2,
short_pow/2,
encode/1, decode/1,
encode_extended/1, decode_extended/1,
setup/1,
test/1,
ctest/1,
reverse_bytes/1,
prime/0,
sqrt/1,
e_double/1,
e_add/2,
e_mul1/2,
e_mul2/2,
e_zero/0,
eq/2,
batch_inverse/1,
e_simplify_batch/1,
pow_/2,
e_neg/1,
gen_point/0,
gen_point/1,
extended2extended_niels/1,
extended_niels2extended/1,
is_zero/1,
extended2affine/1,
affine2extended/1,
to_affine_batch/1,
hash_point/1,
compress/1,
decompress/1
]).
-on_load(init/0).
-record(extended_point, {u, v, z, t1, t2}).
-record(extended_niels_point,
{v_plus_u, v_minus_u, t2d, z}).
37095705934669439343138083508754565189542113879843219016388785533085940283555
-define(D,
<<250,233,71,223,254,139,237,128,115,41,198,175,
119,135,161,16,144,134,24,188,7,146,147,229,38,
197,159,114,90,43,130,44>>).
2 * D
-define(D2,
<<244,211,143,190,253,23,219,1,231,82,140,95,239,
14,67,33,32,13,49,120,15,36,39,203,77,138,63,
229,180,86,4,89>>).
init() ->
ok = erlang:load_nif("./ebin/fq", 0),
setup(0),
ok.
setup(_) ->
ok.
is implemented on this curve .
binaries store bytes in reverse order in comparison to normal erlang binaries . This way when we pass the binaries to C , the bytes are already in order to fit into bigger registers .
-define(q,
57896044618658097711785492504343953926634992332820282019728792003956564819949
).
-define(i2 , ) .
-define(i2, <<19:256/little>>).
< < 255,255,255,255,0,0,0,0,1,164,1,0,253,91,66,172 ,
250,39,94,246,247,39,198,204,183,130,98,214,172 ,
88,18,12 > > ) .
2 ^ 256
-define(r, 115792089237316195423570985008687907853269984665640564039457584007913129639936).
2 ^ 256 rem q
-define(r1, 38).
-define(r2, 1444).
-define(r3, 54872).
1 / r rem q
-define(ir, 10665060850805439052171011777115991512801182798151104582581619579676209308938).
-define(encode_one, <<38:256/little>>).
< < 254,255,255,255,1,0,0,0,2,72,3,0,250,183,132,88 ,
245,79,188,236,239,79,140,153,111,5,197,172,89 ,
177,36,24 > > ) .
-define(encode_zero, <<0:256>>).
prime() -> ?q.
reverse_bytes(<<X:256>>) -> <<X:256/little>>.
reverse_bytes(<<A , B / binary > > , R ) - >
, < < A , R / binary > > ) ;
encode(0) -> <<0:256>>;
encode(1) -> <<38:256/little>>;
encode(A) when ((A < ?q) and (A > -1)) ->
mul(<<A:256/little>>,
<<?r2:256/little>>).
decode(C) ->
X = mul(C, (<<1:256/little>>)),
<<Y:256/little>> = X,
Y.
encode_extended(
#extended_point{
u = U, v = V, z = Z, t1 = T1, t2 = T2
}) ->
Ue = encode(U),
Ve = encode(V),
Ze = encode(Z),
T1e = encode(T1),
T2e = encode(T2),
<<Ue/binary, Ve/binary, Ze/binary,
T1e/binary, T2e/binary>>.
decode_extended(<<U2:256, V2:256, Z2:256,
T12:256, T22:256>>) ->
#extended_point{
u = decode(<<U2:256>>),
v = decode(<<V2:256>>),
z = decode(<<Z2:256>>),
t1 = decode(<<T12:256>>),
t2 = decode(<<T22:256>>)}.
encode_extended_niels(
#extended_niels_point{
v_plus_u = VPU,
v_minus_u = VMU,
t2d = T2D,
z = Z}) ->
VPUe = encode(VPU),
VMUe = encode(VMU),
T2De = encode(T2D),
Ze = encode(Z),
<<VPUe/binary, VMUe/binary, T2De/binary,
Ze/binary>>.
decode_extended_niels(
<<VPU:256, VMU:256, T2D:256, Z:256>>) ->
#extended_niels_point
{v_plus_u = decode(<<VPU:256>>),
v_minus_u = decode(<<VMU:256>>),
t2d = decode(<<T2D:256>>),
z = decode(<<Z:256>>)}.
hash_point(<<U:256>>) ->
fr:encode(U);
hash_point(<<U:256, _:256>>) ->
fr:encode(U);
hash_point(X = <<U:(256*5)>>) ->
hash_point(extended2affine(X)).
sqrt(A) ->
when prime mod 8 = 5
i = 2*a*v*v
T = encode(2),
V = pow_(mul(T, A), (?q - 5) div 8),
AV = mul(A, V),
I = mul(mul(T, AV), V),
R = mul(AV, sub(I, ?encode_one)),
{neg(R), R}.
det_pow(_, 0) -> 1;
det_pow(X, 1) -> X;
det_pow(X, N) when ((N rem 2) == 0) and (N>0) ->
det_pow(X*X, N div 2);
det_pow(X, N) when (N > 0) -> X * det_pow(X, N-1).
pow_(X, Y) when is_integer(Y) ->
pow(X, reverse_bytes(<<Y:256>>)).
add(_, _) -> ok.
neg(_) -> ok.
sub(_, _) -> ok.
mul(_, _) -> ok.
square(_) -> ok.
inv(X) -> encode(ff:inverse(decode(X), ?q)).
pow(_, _) -> ok.
short_pow(_, _) -> ok.
e_double(_) -> ok.
e_add(_extended, _niels) -> ok.
unused , accepts a 8 byte exponent as an integer .
e_mul1(_, _) ->
input 2 is a 32 byte integer as a little endian binary .
ok.
e_mul2(Fq, Fr) ->
case fr:decode(Fr) of
0 -> e_zero();
R2 ->
e_mul1(Fq, <<R2:256/little>>)
end.
e_neg(<<U:256, VZ:512, T1:256, T2:256>>) ->
NU = neg(<<U:256>>),
NT1 = neg(<<T1:256>>),
<<NU/binary, VZ:512, NT1/binary, T2:256>>.
pis([], _) -> [];
pis([H|T], A) ->
X = mul(H, A),
[X|pis(T, X)].
batch_inverse(Vs) ->
[ v16 , v15 , v14 , v13 , v12 , v1 ]
AllI = inv(All),
VI = lists:map(
fun(V) -> mul(AllI, V) end,
[ i6 , i56 , i46 , i36 , i26 ]
[ v16 , v26 , v36 , v46 , v56 , v6 ]
[ v26 , v36 , v46 , v56 , v6 , 1 ]
[ i16 , i26 , i36 , i46 , i56 , i6 ]
lists:zipwith(fun(A, B) ->
mul(A, B)
end, V4, VI2).
e_simplify_batch([]) -> [];
e_simplify_batch(Es) ->
Zs = lists:map(fun(<<_:512, Z:256, _:512>>) ->
<<Z:256>> end, Es),
false = (decode(hd(Zs)) == 0),
IZs = batch_inverse(Zs),
lists:zipwith(fun(E, IZ) ->
simplify(E, IZ)
end, Es, IZs).
simplify(<<U:256, V:256, _/binary>>, IZ) ->
U2 = mul(<<U:256>>, IZ),
V2 = mul(<<V:256>>, IZ),
<<U2/binary, V2/binary, (?encode_one)/binary,
U2/binary, V2/binary>>.
extended2affine(E) ->
[E2] = e_simplify_batch([E]),
<<A:256, B:256, _:(256*3)>> = E2,
<<A:256, B:256>>.
to_affine_batch(L) ->
L2 = e_simplify_batch(L),
lists:map(fun(<<U:256, V:256, _:(256*3)>>) ->
<<U:256, V:256>>
end, L2).
eq(A, B) ->
jubjub:eq(
decode_extended(A),
decode_extended(B)).
e_zero() ->
A = #extended_point
{u = 0, v = 1, z = 1, t1 = 0, t2 = 0},
encode_extended(A).
is_zero(
<<U:256, V:256, Z:256, _:256, _:256>>
) ->
(U == 0) and (V == Z);
is_zero(
<<VPU:256, VMU:256, T2D:256, Z:256>>
) ->
(VPU == VMU) and (VPU == Z).
extended2extended_niels([]) -> [];
extended2extended_niels([H|T]) ->
[extended2extended_niels(H)|
extended2extended_niels(T)];
extended2extended_niels(
A = <<U:256, V:256, Z:256, T1:256, T2:256>>
) ->
T3 = mul(<<T1:256>>, <<T2:256>>),
VPU = add(<<U:256>>, <<V:256>>),
VMU = sub(<<V:256>>, <<U:256>>),
T2D = mul(T3, ?D2),
<<VPU/binary, VMU/binary,
T2D/binary, Z:256>>.
extended_niels2extended([]) -> [];
extended_niels2extended([H|T]) ->
[extended_niels2extended(H)|
extended_niels2extended(T)];
extended_niels2extended(
N = <<VPU:256, VMU:256, T2D:256, Z:256>>
) ->
e_add(e_zero(), N).
affine2extended(
<<U:256, V:256>>) ->
Z = ?encode_one,
<<U:256, V:256, Z/binary, U:256, V:256>>.
-define(sub3(A, B),
if
B>A -> A + ?q - B;
true -> A - B
end).
ctest(_) ->
ok.
gen_point() ->
<<X0:256>> = crypto:strong_rand_bytes(32),
X = X0 rem ?q,
G = gen_point(encode(X), 2, 2),
true = is_on_curve(G),
G.
gen_point(U, 0, S) ->
io:fwrite("next U\n"),
gen_point(add(U, 1), S, S);
gen_point(Us, _, _) when is_list(Us) ->
UUs = lists:map(fun(X) -> mul(X, X) end, Us),
DUUs = lists:map(fun(X) -> sub(encode(1),
mul(?D, X))
end, UUs),
Bs = batch_inverse(DUUs),
VVs = lists:zipwith(
fun(B, UU) ->
mul(add(encode(1), UU), B)
end, Bs, UUs),
lists:zipwith(
fun(U, VV) ->
gen_point(U, 20, 20, VV)
end, Us, VVs);
gen_point(U, Tries, S) ->
UU = mul(U, U),
DUU = mul(?D, UU),
B = inv(sub(encode(1), DUU)),
T = add(encode(1), UU),
VV = mul(T, B),
gen_point(U, Tries, S, VV).
gen_point(U, _, S, VV) ->
case sqrt(VV) of
error ->
gen_point(add(U, encode(1)), S, S);
{V1, V2} ->
A = <<U/binary, V1/binary>>,
A2 = <<U/binary, V2/binary>>,
G = affine2extended(A),
OnCurve = is_on_curve(A),
if
not(OnCurve) -> gen_point(add(U, encode(1)), S, S);
true -> <<U/binary, V2/binary>>
end
end.
G = : affine2extended (
: gen_point ( ) ) ,
gen_point(X) ->
gen_point(X, 20, 20).
: affine2extended (
: gen_point(X ) ) ) .
decompress_points(Us)
when is_list(Us) ->
UU = U*U ,
DUU = 1 - ( D * UU )
V = ) / ( 1 - ( D * UU ) ) )
UUs = lists:map(fun(X) -> mul(X, X) end, Us),
DUUs = lists:map(
fun(X) ->
sub(?encode_one, mul(?D, X))
end, UUs),
Bs = batch_inverse(DUUs),
VVs = lists:zipwith(
fun(B, UU) ->
mul(add(?encode_one, UU), B)
end, Bs, UUs),
lists:zipwith(
fun(U, VV) ->
decompress_point2(U, VV)
end, Us, VVs).
decompress_point2(U, VV) ->
prime order 200 .
0.000350
error ->
error;
{V1, V2} ->
G = affine2extended(A),
OnCurve = is_on_curve(A ) , TODO
if
B -> A;
true -> A2
end
end.
is_on_curve(<<U:256, V:256>>) ->
U2 = mul(<<U:256>>, <<U:256>>),
V2 = mul(<<V:256>>, <<V:256>>),
UV2 = mul(U2, V2),
(sub(V2, U2) ==
add(?encode_one, mul(?D, UV2))).
is_prime_order(E) ->
is_torsion_free(E) and not(identity(E)).
is_torsion_free(E) ->
R = 7237005577332262213973186563042994240857116359379907606001950938285454250989,
E2 = e_mul1(E, <<R:256/little>>),
identity(E2).
identity(<<U:256, V:256, Z:256, Ts:512>>) ->
(U == 0) and (V == Z).
compress(L) when is_list(L) ->
L2 = to_affine_batch(L),
lists:map(fun(<<A:256, _:256>>)->
<<A:256>> end, L2).
decompress(<<A:256>>) ->
hd(decompress([<<A:256>>]));
decompress(L) when is_list(L) ->
L2 = decompress_points(L),
lists:map(fun(X) -> affine2extended(X) end,
L2).
points_list(Many) ->
G = jubjub:affine2extended(
jubjub:gen_point()),
G1 = jubjub:multiply(4327409, G),
points_list2(Many, G1).
points_list2(0, _) -> [];
points_list2(N, G) ->
E = encode_extended(G),
[{G, E}|
points_list2(
N-1, jubjub:multiply(9320472034, G))].
range(N, N) -> [N];
range(A, B) when (A < B) ->
[A|range(A+1, B)].
test(2) ->
io:fwrite("subtract test\n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
<<B0:256>> = crypto:strong_rand_bytes(32),
A1 = A0 rem ?q,
B1 = B0 rem ?q,
A = encode(A1),
B = encode(B1),
S = decode(sub(A, B)),
S = ((A1 - B1) + ?q) rem ?q,
success;
test(3) ->
io:fwrite("encode decode test\n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
A1 = 2,
A = encode(A1),
A1 = decode(A);
test(5) ->
io:fwrite("addition test\n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
<<B0:256>> = crypto:strong_rand_bytes(32),
A0 = 5 ,
= 7 ,
A1 = A0 rem ?q,
B1 = B0 rem ?q,
A = encode(A1),
B = encode(B1),
S = decode(add(A, B)),
S = (A1 + B1) rem ?q,
success;
test(6) ->
io:fwrite("multiply test \n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
<<B0:256>> = crypto:strong_rand_bytes(32),
A0 = 2 ,
= 3 ,
A1 = A0 rem ?q,
B1 = B0 rem ?q,
A = encode(A1),
B = encode(B1),
S3 = (A1 * B1) rem ?q,
S3 = decode(mul(A, B)),
success;
test(8) ->
io:fwrite("more accurate multiplication speed test.\n"),
Many = 100000,
R = lists:map(fun(_) ->
<<A0:256>> = crypto:strong_rand_bytes(32),
<<B0:256>> = crypto:strong_rand_bytes(32),
{A0 rem ?q,
B0 rem ?q}
end, range(0, Many)),
R2 = lists:map(fun({X, Y}) ->
{encode(X),
encode(Y)}
end, R),
T1 = erlang:timestamp(),
lists:foldl(fun({X, Y}, _) ->
(X*Y) rem ?q,
0
end, 0, R),
T2 = erlang:timestamp(),
lists:foldl(fun({X, Y}, _) ->
mul(X, Y),
0
end, 0, R2),
T3 = erlang:timestamp(),
lists:foldl(fun({X, Y}, _) ->
if
(X >= Y) -> X - Y;
true -> ?q - Y + X
end,
0
end, 0, R),
T4 = erlang:timestamp(),
lists:foldl(fun({X, Y}, _) ->
sub(X, Y)
end, 0, R2),
T5 = erlang:timestamp(),
lists:foldl(fun({X, Y}, _) ->
C = X+Y,
if
(C > ?q) -> C - ?q;
true -> C
end,
0
end, 0, R),
T6 = erlang:timestamp(),
lists:foldl(fun({X, Y}, _) ->
add(X, Y),
0
end, 0, R2),
T7 = erlang:timestamp(),
lists:foldl(fun(_, _) -> 0 end, 0, R2),
T8 = erlang:timestamp(),
Empty = timer:now_diff(T8, T7),
MERL = timer:now_diff(T2, T1),
MC = timer:now_diff(T3, T2),
SERL = timer:now_diff(T4, T3),
SC = timer:now_diff(T5, T4),
AERL = timer:now_diff(T6, T5),
AC = timer:now_diff(T7, T6),
{{empty, Empty/Many},
{mul, {erl, (MERL - Empty)/Many},
{c, (MC - Empty)/Many}},
{sub, {erl, (SERL - Empty)/Many},
{c, (SC - Empty)/Many}},
{add, {erl, (AERL - Empty)/Many},
{c, (AC - Empty)/Many}}};
test(10) ->
io:fwrite("square test\n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
A0 = 3 ,
A = A0 rem ?q,
S1 = decode(square(encode(A))),
S2 = (A*A rem ?q),
B = S1 == S2,
{B, S1, S2};
test(11) ->
io:fwrite("inverse test\n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
A = A0 rem ?q,
A1 = encode(A),
IA = inv(A1),
A1 = inv(IA),
A = decode(A1),
{A, IA};
test(12) ->
io:fwrite("inverse speed test\n"),
Many = 1000,
R = range(0, Many),
R2 = lists:map(
fun(_) ->
<<N0:256>> =
crypto:strong_rand_bytes(
32),
N0 rem ?q
end, R),
R3 = lists:map(
fun(X) -> encode(X) end, R2),
T1 = erlang:timestamp(),
lists:map(fun(I) -> inv(I) end, R3),
T2 = erlang:timestamp(),
lists:map(fun(I) ->
basics:inverse(I, ?q)
end, R2),
T3 = erlang:timestamp(),
{{c, timer:now_diff(T2, T1)/Many},
{erl, timer:now_diff(T3, T2)/Many}};
test(13) ->
io:fwrite("jubjub double test\n"),
P0 = jubjub:affine2extended(
jubjub:gen_point()),
B = encode_extended(P0),
P = decode_extended(e_double(B)),
P = decode_extended(e_double(B)),
P2 = jubjub:double(P0),
P2b = decode_extended(
extended_niels2extended(
extended2extended_niels(
encode_extended(P2)))),
P2c = jubjub:extended_niels2extended(
jubjub:extended2extended_niels(P2)),
P0 = jubjub:extended_niels2extended(
jubjub:extended2extended_niels(P0)),
true = jubjub:is_on_curve(
jubjub:extended2affine(P0)),
true = jubjub:is_on_curve(
jubjub:extended2affine(P2)),
true = jubjub:eq(P, P2),
true = jubjub:eq(P2, P2c),
true = jubjub:eq(P2, P2b),
success;
test(14) ->
io:fwrite("jubjub double speed test\n"),
Many = 10000,
R = range(0, Many),
R2 = points_list(Many),
io:fwrite("made points\n"),
T1 = erlang:timestamp(),
lists:foldl(fun({P, _}, _) ->
jubjub:double(jubjub:double(jubjub:double(P)))
end, 0, R2),
T2 = erlang:timestamp(),
lists:foldl(fun({_, P}, _) ->
e_double(e_double(e_double(P)))
end, 0, R2),
T3 = erlang:timestamp(),
{{erl, timer:now_diff(T2, T1)/Many/3},
{c, timer:now_diff(T3, T2)/Many/3}};
test(15) ->
io:fwrite("jubjub add\n"),
E0 = jubjub:affine2extended(
jubjub:gen_point()),
E = encode_extended(E0),
E0 = decode_extended(E),
N0 = jubjub:affine_niels2extended_niels(
jubjub:affine2affine_niels(
jubjub:gen_point())),
N = encode_extended_niels(N0),
E3 = jubjub:add(E0, N0),
E2 = decode_extended(e_add(E, N)),
E2 = decode_extended(e_add(E, N)),
N2 = extended2extended_niels(e_add(E, N)),
E4 = decode_extended(e_add(E, N2)),
true = jubjub:eq(E2, E3),
true = jubjub:is_on_curve(
jubjub:extended2affine(E2)),
true = jubjub:is_on_curve(
jubjub:extended2affine(E3)),
true = jubjub:is_on_curve(
jubjub:extended2affine(E4)),
success;
test(16) ->
io:fwrite("jubjub add speed\n"),
Many = 10000,
R = range(0, Many),
R2 = points_list(Many),
N0 = jubjub:affine_niels2extended_niels(
jubjub:affine2affine_niels(
jubjub:gen_point())),
N = encode_extended_niels(N0),
T1 = erlang:timestamp(),
lists:foldl(fun({P, _}, _) ->
jubjub:add(P, N0)
end, 0, R2),
T2 = erlang:timestamp(),
lists:foldl(fun({_, P}, _) ->
e_add(P, N)
end, 0, R2),
T3 = erlang:timestamp(),
{{erl, timer:now_diff(T2, T1)/Many},
{c, timer:now_diff(T3, T2)/Many}};
test(17) ->
io:fwrite("test pow\n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
A0 = 2 ,
A = A0 rem ?q,
<<B0:256>> = crypto:strong_rand_bytes(32),
= 2 ,
B = B0 rem ?q,
AE = encode(A),
New = decode(pow(AE,
reverse_bytes(<<B:256>>))),
AE = encode(A),
Old = basics:rlpow(A, B, ?q),
New = Old,
success;
test(18) ->
io:fwrite("test pow speed\n"),
Many = 100,
R = range(0, Many),
R2 = lists:map(
fun(_) ->
<<A0:256>> = crypto:strong_rand_bytes(32),
<<B0:256>> = crypto:strong_rand_bytes(32),
A = A0 rem ?q,
B = B0 rem ?q,
Ae = encode(A),
Be = reverse_bytes(<<B:256>>),
{A, B, Ae, Be}
end, R),
T1 = erlang:timestamp(),
lists:foldl(fun({A, B, _, _}, _) ->
basics:rlpow(A, B, ?q)
end, 0, R2),
T2 = erlang:timestamp(),
lists:foldl(fun({_, _, A, B}, _) ->
pow(A, B)
end, 0, R2),
T3 = erlang:timestamp(),
{{erl, timer:now_diff(T2, T1)/Many},
{c, timer:now_diff(T3, T2)/Many}};
test(19) ->
io:fwrite("test short_pow\n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
A = A0 rem ?q,
<<B:16>> = crypto:strong_rand_bytes(2),
C = decode(short_pow(encode(A), B)),
D = basics:rlpow(A, B, ?q),
C = D,
success;
test(20) ->
io:fwrite("test neg\n"),
<<A0:256>> = crypto:strong_rand_bytes(32),
A = A0 rem ?q,
NA = ?q - A,
NA = decode(neg(encode(A)));
test(21) ->
io:fwrite("testing elliptic multiplication\n"),
N0 = jubjub:affine_niels2extended_niels(
jubjub:affine2affine_niels(
jubjub:gen_point())),
N = encode_extended_niels(N0),
<<B:64>> = crypto:strong_rand_bytes(8),
B = 2 ,
<<One:256>> = encode(1),
Me = e_mul(N, B),
M = jubjub:multiply(B, N0),
M2 = decode_extended(Me),
: eq(M , M2 ) ,
true = jubjub:eq(M, M2),
success;
test(22) ->
io:fwrite("elliptic multiplication speed test \n\n"),
Many = 1000,
R = range(0, Many),
R1 = points_list(Many),
R2 = lists:map(
fun({P, _}) ->
N0 = jubjub:extended2extended_niels(P),
N = encode_extended_niels(N0),
<<B:64>> = crypto:strong_rand_bytes(8),
{N0, N, B} end, R1),
T1 = erlang:timestamp(),
lists:foldl(fun({N0, _, B}, _) ->
jubjub:multiply(B, N0)
end, 0, R2),
T2 = erlang:timestamp(),
lists:foldl(fun({_, N, B}, _) ->
e_mul(N, B)
end, 0, R2),
T3 = erlang:timestamp(),
{{erl, timer:now_diff(T2, T1)/Many},
{c, timer:now_diff(T3, T2)/Many}};
test(23) ->
io:fwrite("testing long elliptic multiplication\n"),
N0 = jubjub:affine_niels2extended_niels(
jubjub:affine2affine_niels(
jubjub:gen_point())),
N = encode_extended_niels(N0),
<<B:256>> = crypto:strong_rand_bytes(32),
B = 18446744073709551615 ,
<<One:256>> = encode(1),
Me = e_mul1(N, reverse_bytes(<<B:256>>)),
M = jubjub:multiply(B, N0),
M2 = decode_extended(Me),
true = jubjub:eq(M, M2),
success;
test(24) ->
TODO
G = gen_point(),
GN = extended2extended_niels(G),
G2 = extended_niels2extended(GN),
true = eq(G, G2),
success;
test(25) ->
Gs = [gen_point(),
gen_point(),
gen_point()],
G2s = lists:map(fun(X) -> e_double(X) end,
Gs),
G2simp = e_simplify_batch(G2s),
[true, true, true] =
lists:zipwith(fun(A, B) -> eq(A, B) end,
G2s, G2simp),
E = secp256k1:make(),
G = fun() ->
secp256k1:to_jacob(
secp256k1:gen_point(E))
end,
Ps = [G(), G(), G()],
Ps = secp256k1:simplify_Zs_batch(Ps),
success;
test(26) ->
io:fwrite("testing elliptic zero point\n"),
Z0 = e_zero(),
Z1 = e_double(Z0),
Z2 = e_add(Z0, extended2extended_niels(Z1)),
Z3 = extended_niels2extended(
extended2extended_niels(Z2)),
true = is_zero(Z0),
true = is_zero(Z1),
true = is_zero(Z2),
true = is_zero(Z3),
true = is_zero(extended2extended_niels(Z0)),
true = is_zero(extended2extended_niels(Z1)),
true = is_zero(extended2extended_niels(Z2)),
true = is_zero(extended2extended_niels(Z3)),
true = is_zero(e_mul2(extended2extended_niels(gen_point()), fr:encode(0))),
success;
test(27) ->
io:fwrite("encode decode speed test\n"),
Many = 100000,
R = range(0, Many),
R2 = lists:map(fun(X) -> encode(X) end, R),
T1 = erlang:timestamp(),
lists:foldl(fun(X, _) ->
encode(X),
0
end, 0, R),
T2 = erlang:timestamp(),
lists:foldl(fun(X, _) ->
decode(X),
0
end, 0, R2),
T3 = erlang:timestamp(),
{
{encode, (timer:now_diff(T2, T1)/Many)},
{decode, (timer:now_diff(T3, T2)/Many)}
};
test(28) ->
io:fwrite("testing e_add with niels/extended niels\n"),
G = gen_point(),
H = gen_point(),
HE = extended2extended_niels(H),
R1 = e_add(G, H),
R2 = e_add(G, HE),
eq(R1, R2);
test(29) ->
io:fwrite("testing e_add error that returns a broken point.\n"),
G = gen_point(),
Z = e_zero(),
Z1 = extended_niels2extended(
extended2extended_niels(Z)),
{extended_point, 0,0,1,0,0}),
{
decode_extended(Z1),
decode_extended(e_mul2(G, fr:encode(0))),
decode_extended(e_add(G, Bad)),
decode_extended_niels(
extended2extended_niels(Bad)),
decode_extended(
extended_niels2extended(
extended2extended_niels(Bad))),
decode_extended(e_add(G, extended2extended_niels(Bad)))
};
test(30) ->
io:fwrite("testing compressing a point to 32 bytes"),
X = gen_point(),
X2 = e_add(X, X),
[<<A:256>>] = compress([X2]),
X3 = decompress(<<A:256>>),
Aff = extended2affine(X2),
Aff = extended2affine(X3),
ok;
test(31) ->
X = [gen_point(), gen_point()],
C = compress(X),
D = decompress(C),
C = compress(D),
D2 = decompress_points(C),
D3 = lists:map(fun(X) ->
affine2extended(X) end,
D2),
C = compress(D3),
{D3, D};
test(32) ->
Many = 300,
Range = range(0, Many),
Points = lists:map(
fun(X) ->
e_double(e_double(gen_point())) end,
Range),
T1 = erlang:timestamp(),
C = compress(Points),
T2 = erlang:timestamp(),
{ ok , _ PID } = : start ( ) ,
: trace([start , { procs , all } ] ) ,
decompress(C),
: ] ) ,
: profile ( ) ,
: analyse ( ) ,
: stop ( ) ,
T3 = erlang:timestamp(),
{{compress, (timer:now_diff(T2, T1)/Many)},
{decompress, (timer:now_diff(T3, T2)/Many)}}.
|
3f348b086cf496409a429761067eac7a7dae3ec81e7629bc79b022e238852134 | juxt/apex | http_test.clj | Copyright © 2020 , JUXT LTD .
(ns juxt.apex.http.http-test
(:require
[ring.mock.request :refer [request]]
[juxt.apex.alpha.http.core :as http]
[clojure.test :refer [deftest is]]
[juxt.apex.alpha.http.header-names :refer [wrap-headers-normalize-case]]))
(comment
(let [h (->
(http/handler
(reify
http/ResourceLocator
(locate-resource [_ uri]
(when (= (.getPath uri) "/hello.txt")
{:apex.http/content "Hello World!"}))
http/OkResponse
(send-ok-response
[_ resource response request respond raise]
(respond
(conj response [:body (:apex.http/content resource)])))))
wrap-headers-normalize-case)]
(h (request :get "/hello.txt"))))
| null | https://raw.githubusercontent.com/juxt/apex/cb4c0016d817ebb03d4f84e572ca71edd84ed79d/modules/http/test/juxt/apex/http/http_test.clj | clojure | Copyright © 2020 , JUXT LTD .
(ns juxt.apex.http.http-test
(:require
[ring.mock.request :refer [request]]
[juxt.apex.alpha.http.core :as http]
[clojure.test :refer [deftest is]]
[juxt.apex.alpha.http.header-names :refer [wrap-headers-normalize-case]]))
(comment
(let [h (->
(http/handler
(reify
http/ResourceLocator
(locate-resource [_ uri]
(when (= (.getPath uri) "/hello.txt")
{:apex.http/content "Hello World!"}))
http/OkResponse
(send-ok-response
[_ resource response request respond raise]
(respond
(conj response [:body (:apex.http/content resource)])))))
wrap-headers-normalize-case)]
(h (request :get "/hello.txt"))))
| |
f35766817ed66cb56970e35815483b17798e53cfd587b339b0964292b170f648 | tlehman/sicp-exercises | ex-1.20.scm | Exercise 1.20 : The process that a procedure generates is of course
; dependent on the rules used by the interpreter.
;
; As an example, consider the iterative gcd procedure:
;(define (remainder a b) `(remainder ,a ,b))
(define (gcd a b)
(if (and (number? b) (= b 0))
a
`(gcd ,b (remainder ,a ,b))))
; In normal order evaluation, use the substitution method to illustrate the execution of:
(gcd 206 40)
(gcd 40 (remainder 206 40))
(gcd (remainder 206 40) (remainder 40 (remainder 206 40)))
(gcd (remainder 40 (remainder 206 40))
(remainder (remainder 206 40) (remainder 40 (remainder 206 40))))
(gcd (remainder (remainder 206 40) (remainder 40 (remainder 206 40)))
(remainder (remainder 40 (remainder 206 40))
(remainder (remainder 206 40) (remainder 40 (remainder 206 40)))))
2
remainder is called 11 times using normal - order evaluation
; Do the same for applicative order evaluation, compare the number of
; times remainder is called.
(gcd 206 40)
(gcd 40 6)
(gcd 6 4)
(gcd 4 2)
(gcd 2 0)
2
remainder is called 5 times using normal - order evaluation
| null | https://raw.githubusercontent.com/tlehman/sicp-exercises/57151ec07d09a98318e91c83b6eacaa49361d156/ex-1.20.scm | scheme | dependent on the rules used by the interpreter.
As an example, consider the iterative gcd procedure:
(define (remainder a b) `(remainder ,a ,b))
In normal order evaluation, use the substitution method to illustrate the execution of:
Do the same for applicative order evaluation, compare the number of
times remainder is called. | Exercise 1.20 : The process that a procedure generates is of course
(define (gcd a b)
(if (and (number? b) (= b 0))
a
`(gcd ,b (remainder ,a ,b))))
(gcd 206 40)
(gcd 40 (remainder 206 40))
(gcd (remainder 206 40) (remainder 40 (remainder 206 40)))
(gcd (remainder 40 (remainder 206 40))
(remainder (remainder 206 40) (remainder 40 (remainder 206 40))))
(gcd (remainder (remainder 206 40) (remainder 40 (remainder 206 40)))
(remainder (remainder 40 (remainder 206 40))
(remainder (remainder 206 40) (remainder 40 (remainder 206 40)))))
2
remainder is called 11 times using normal - order evaluation
(gcd 206 40)
(gcd 40 6)
(gcd 6 4)
(gcd 4 2)
(gcd 2 0)
2
remainder is called 5 times using normal - order evaluation
|
d3b437c1ba278d597c971214faf3eea63c44ab03c3725d4034d3a4731f123105 | lpw25/ocaml-typed-effects | stackoverflow.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
let rec f x =
if not (x = 0 || x = 10000 || x = 20000)
then 1 + f (x + 1)
else
try
1 + f (x + 1)
with Stack_overflow ->
print_string "x = "; print_int x; print_newline();
raise Stack_overflow
let _ =
try
ignore(f 0)
with Stack_overflow ->
print_string "Stack overflow caught"; print_newline()
let rec sum n = if n = 0 then 0 else n + sum (n-1)
let _ =
print_string "sum(1..100000) = ";
print_int (sum 100000);
print_newline()
| null | https://raw.githubusercontent.com/lpw25/ocaml-typed-effects/79ea08b285c1fd9caf3f5a4d2aa112877f882bea/testsuite/tests/runtime-errors/stackoverflow.ml | ocaml | *********************************************************************
OCaml
********************************************************************* | , projet Cristal , INRIA Rocquencourt
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
let rec f x =
if not (x = 0 || x = 10000 || x = 20000)
then 1 + f (x + 1)
else
try
1 + f (x + 1)
with Stack_overflow ->
print_string "x = "; print_int x; print_newline();
raise Stack_overflow
let _ =
try
ignore(f 0)
with Stack_overflow ->
print_string "Stack overflow caught"; print_newline()
let rec sum n = if n = 0 then 0 else n + sum (n-1)
let _ =
print_string "sum(1..100000) = ";
print_int (sum 100000);
print_newline()
|
4b67ab743a697f576e98244ed45c51da07601f5fd6d1d881cd56149ee454b16e | processone/ejabberd | ejabberd_regexp.erl | %%%----------------------------------------------------------------------
%%% File : ejabberd_regexp.erl
Author :
%%% Purpose : Frontend to Re OTP module
Created : 8 Dec 2011 by
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2023 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_regexp).
-export([run/2, split/2, replace/3, greplace/3, sh_to_awk/1]).
-spec run(binary(), binary()) -> match | nomatch | {error, any()}.
run(String, Regexp) ->
re:run(String, Regexp, [{capture, none}, unicode]).
-spec split(binary(), binary()) -> [binary()].
split(String, Regexp) ->
re:split(String, Regexp, [{return, binary}]).
-spec replace(binary(), binary(), binary()) -> binary().
replace(String, Regexp, New) ->
re:replace(String, Regexp, New, [{return, binary}]).
-spec greplace(binary(), binary(), binary()) -> binary().
greplace(String, Regexp, New) ->
re:replace(String, Regexp, New, [global, {return, binary}]).
This code was copied and adapted from xmerl_regexp.erl
-spec sh_to_awk(binary()) -> binary().
sh_to_awk(Sh) ->
iolist_to_binary([<<"^(">>, sh_to_awk_1(Sh)]). %Fix the beginning
sh_to_awk_1(<<"*", Sh/binary>>) -> %This matches any string
[<<".*">>, sh_to_awk_1(Sh)];
sh_to_awk_1(<<"?", Sh/binary>>) -> %This matches any character
[$., sh_to_awk_1(Sh)];
sh_to_awk_1(<<"[^]", Sh/binary>>) -> %This takes careful handling
[<<"\\^">>, sh_to_awk_1(Sh)];
%% Must move '^' to end.
sh_to_awk_1(<<"[^", Sh/binary>>) ->
[$[, sh_to_awk_2(Sh, true)];
sh_to_awk_1(<<"[!", Sh/binary>>) ->
[<<"[^">>, sh_to_awk_2(Sh, false)];
sh_to_awk_1(<<"[", Sh/binary>>) ->
[$[, sh_to_awk_2(Sh, false)];
sh_to_awk_1(<<C:8, Sh/binary>>) -> %% Unspecialise everything else which is not an escape character.
case sh_special_char(C) of
true -> [$\\,C|sh_to_awk_1(Sh)];
false -> [C|sh_to_awk_1(Sh)]
end;
sh_to_awk_1(<<>>) ->
<<")$">>. %Fix the end
sh_to_awk_2(<<"]", Sh/binary>>, UpArrow) ->
[$]|sh_to_awk_3(Sh, UpArrow)];
sh_to_awk_2(Sh, UpArrow) ->
sh_to_awk_3(Sh, UpArrow).
sh_to_awk_3(<<"]", Sh/binary>>, true) ->
[<<"^]">>, sh_to_awk_1(Sh)];
sh_to_awk_3(<<"]", Sh/binary>>, false) ->
[$]|sh_to_awk_1(Sh)];
sh_to_awk_3(<<C:8, Sh/binary>>, UpArrow) ->
[C|sh_to_awk_3(Sh, UpArrow)];
sh_to_awk_3(<<>>, true) ->
[$^|sh_to_awk_1(<<>>)];
sh_to_awk_3(<<>>, false) ->
sh_to_awk_1(<<>>).
%% Test if a character is a special character.
-spec sh_special_char(char()) -> boolean().
sh_special_char($|) -> true;
sh_special_char($*) -> true;
sh_special_char($+) -> true;
sh_special_char($?) -> true;
sh_special_char($() -> true;
sh_special_char($)) -> true;
sh_special_char($\\) -> true;
sh_special_char($^) -> true;
sh_special_char($$) -> true;
sh_special_char($.) -> true;
sh_special_char($[) -> true;
sh_special_char($]) -> true;
sh_special_char($") -> true;
sh_special_char(_C) -> false.
| null | https://raw.githubusercontent.com/processone/ejabberd/c103182bc7e5b8a8ab123ce02d1959a54e939480/src/ejabberd_regexp.erl | erlang | ----------------------------------------------------------------------
File : ejabberd_regexp.erl
Purpose : Frontend to Re OTP module
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.
----------------------------------------------------------------------
Fix the beginning
This matches any string
This matches any character
This takes careful handling
Must move '^' to end.
Unspecialise everything else which is not an escape character.
Fix the end
Test if a character is a special character. | Author :
Created : 8 Dec 2011 by
ejabberd , Copyright ( C ) 2002 - 2023 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_regexp).
-export([run/2, split/2, replace/3, greplace/3, sh_to_awk/1]).
-spec run(binary(), binary()) -> match | nomatch | {error, any()}.
run(String, Regexp) ->
re:run(String, Regexp, [{capture, none}, unicode]).
-spec split(binary(), binary()) -> [binary()].
split(String, Regexp) ->
re:split(String, Regexp, [{return, binary}]).
-spec replace(binary(), binary(), binary()) -> binary().
replace(String, Regexp, New) ->
re:replace(String, Regexp, New, [{return, binary}]).
-spec greplace(binary(), binary(), binary()) -> binary().
greplace(String, Regexp, New) ->
re:replace(String, Regexp, New, [global, {return, binary}]).
This code was copied and adapted from xmerl_regexp.erl
-spec sh_to_awk(binary()) -> binary().
sh_to_awk(Sh) ->
[<<".*">>, sh_to_awk_1(Sh)];
[$., sh_to_awk_1(Sh)];
[<<"\\^">>, sh_to_awk_1(Sh)];
sh_to_awk_1(<<"[^", Sh/binary>>) ->
[$[, sh_to_awk_2(Sh, true)];
sh_to_awk_1(<<"[!", Sh/binary>>) ->
[<<"[^">>, sh_to_awk_2(Sh, false)];
sh_to_awk_1(<<"[", Sh/binary>>) ->
[$[, sh_to_awk_2(Sh, false)];
case sh_special_char(C) of
true -> [$\\,C|sh_to_awk_1(Sh)];
false -> [C|sh_to_awk_1(Sh)]
end;
sh_to_awk_1(<<>>) ->
sh_to_awk_2(<<"]", Sh/binary>>, UpArrow) ->
[$]|sh_to_awk_3(Sh, UpArrow)];
sh_to_awk_2(Sh, UpArrow) ->
sh_to_awk_3(Sh, UpArrow).
sh_to_awk_3(<<"]", Sh/binary>>, true) ->
[<<"^]">>, sh_to_awk_1(Sh)];
sh_to_awk_3(<<"]", Sh/binary>>, false) ->
[$]|sh_to_awk_1(Sh)];
sh_to_awk_3(<<C:8, Sh/binary>>, UpArrow) ->
[C|sh_to_awk_3(Sh, UpArrow)];
sh_to_awk_3(<<>>, true) ->
[$^|sh_to_awk_1(<<>>)];
sh_to_awk_3(<<>>, false) ->
sh_to_awk_1(<<>>).
-spec sh_special_char(char()) -> boolean().
sh_special_char($|) -> true;
sh_special_char($*) -> true;
sh_special_char($+) -> true;
sh_special_char($?) -> true;
sh_special_char($() -> true;
sh_special_char($)) -> true;
sh_special_char($\\) -> true;
sh_special_char($^) -> true;
sh_special_char($$) -> true;
sh_special_char($.) -> true;
sh_special_char($[) -> true;
sh_special_char($]) -> true;
sh_special_char($") -> true;
sh_special_char(_C) -> false.
|
e69e2eace1dc0e398dce979dc8e4c52e15ad30d5e32ba7f464a839a1ded8ca1d | logseq/logseq | graph_parser_test.cljs | (ns logseq.graph-parser-test
(:require [cljs.test :refer [deftest testing is are]]
[clojure.string :as string]
[logseq.graph-parser :as graph-parser]
[logseq.db :as ldb]
[logseq.db.default :as default-db]
[logseq.graph-parser.block :as gp-block]
[logseq.graph-parser.property :as gp-property]
[datascript.core :as d]))
(def foo-edn
"Example exported whiteboard page as an edn exportable."
'{:blocks
({:block/content "foo content a",
:block/format :markdown
:block/parent {:block/uuid #uuid "16c90195-6a03-4b3f-839d-095a496d9acd"}},
{:block/content "foo content b",
:block/format :markdown
:block/parent {:block/uuid #uuid "16c90195-6a03-4b3f-839d-095a496d9acd"}}),
:pages
({:block/format :markdown,
:block/name "foo"
:block/original-name "Foo"
:block/uuid #uuid "16c90195-6a03-4b3f-839d-095a496d9acd"
:block/properties {:title "my whiteboard foo"}})})
(def foo-conflict-edn
"Example exported whiteboard page as an edn exportable."
'{:blocks
({:block/content "foo content a",
:block/format :markdown},
{:block/content "foo content b",
:block/format :markdown}),
:pages
({:block/format :markdown,
:block/name "foo conflicted"
:block/original-name "Foo conflicted"
:block/uuid #uuid "16c90195-6a03-4b3f-839d-095a496d9acd"})})
(def bar-edn
"Example exported whiteboard page as an edn exportable."
'{:blocks
({:block/content "foo content a",
:block/format :markdown
:block/parent {:block/uuid #uuid "71515b7d-b5fc-496b-b6bf-c58004a34ee3"
:block/name "foo"}},
{:block/content "foo content b",
:block/format :markdown
:block/parent {:block/uuid #uuid "71515b7d-b5fc-496b-b6bf-c58004a34ee3"
:block/name "foo"}}),
:pages
({:block/format :markdown,
:block/name "bar"
:block/original-name "Bar"
:block/uuid #uuid "71515b7d-b5fc-496b-b6bf-c58004a34ee3"})})
(deftest parse-file
(testing "id properties"
(let [conn (ldb/start-conn)]
(graph-parser/parse-file conn "foo.md" "- id:: 628953c1-8d75-49fe-a648-f4c612109098" {})
(is (= [{:id "628953c1-8d75-49fe-a648-f4c612109098"}]
(->> (d/q '[:find (pull ?b [*])
:in $
:where [?b :block/content] [(missing? $ ?b :block/name)]]
@conn)
(map first)
(map :block/properties)))
"id as text has correct :block/properties")))
(testing "unexpected failure during block extraction"
(let [conn (ldb/start-conn)
deleted-page (atom nil)]
(with-redefs [gp-block/with-pre-block-if-exists (fn stub-failure [& _args]
(throw (js/Error "Testing unexpected failure")))]
(try
(graph-parser/parse-file conn "foo.md" "- id:: 628953c1-8d75-49fe-a648-f4c612109098"
{:delete-blocks-fn (fn [_db page _file _uuids]
(reset! deleted-page page))})
(catch :default _)))
(is (= nil @deleted-page)
"Page should not be deleted when there is unexpected failure")))
(testing "parsing whiteboard page"
(let [conn (ldb/start-conn)]
(graph-parser/parse-file conn "/whiteboards/foo.edn" (pr-str foo-edn) {})
(let [blocks (d/q '[:find (pull ?b [* {:block/page
[:block/name
:block/original-name
:block/type
{:block/file
[:file/path]}]}])
:in $
:where [?b :block/content] [(missing? $ ?b :block/name)]]
@conn)
parent (:block/page (ffirst blocks))]
(is (= {:block/name "foo"
:block/original-name "Foo"
:block/type "whiteboard"
:block/file {:file/path "/whiteboards/foo.edn"}}
parent)
"parsed block in the whiteboard page has correct parent page"))))
(testing "Loading whiteboard pages that same block/uuid should throw an error."
(let [conn (ldb/start-conn)]
(graph-parser/parse-file conn "/whiteboards/foo.edn" (pr-str foo-edn) {})
(is (thrown-with-msg?
js/Error
#"Conflicting upserts"
(graph-parser/parse-file conn "/whiteboards/foo-conflict.edn" (pr-str foo-conflict-edn) {})))))
(testing "Loading whiteboard pages should ignore the :block/name property inside :block/parent."
(let [conn (ldb/start-conn)]
(graph-parser/parse-file conn "/whiteboards/foo.edn" (pr-str foo-edn) {})
(graph-parser/parse-file conn "/whiteboards/bar.edn" (pr-str bar-edn) {})
(let [pages (d/q '[:find ?name
:in $
:where
[?b :block/name ?name]
[?b :block/type "whiteboard"]]
@conn)]
(is (= pages #{["foo"] ["bar"]}))))))
(defn- test-property-order [num-properties]
(let [conn (ldb/start-conn)
properties (mapv #(keyword (str "p" %)) (range 0 num-properties))
text (->> properties
(map #(str (name %) ":: " (name %) "-value"))
(string/join "\n"))
;; Test page properties and block properties
body (str text "\n- " text)
_ (graph-parser/parse-file conn "foo.md" body {})
properties-orders (->> (d/q '[:find (pull ?b [*])
:in $
:where [?b :block/content] [(missing? $ ?b :block/name)]]
@conn)
(map first)
(map :block/properties-order))]
(is (every? vector? properties-orders)
"Order is persisted as a vec to avoid edn serialization quirks")
(is (= [properties properties] properties-orders)
"Property order")))
(deftest properties-order
(testing "Sort order and persistence of a few properties"
(test-property-order 4))
(testing "Sort order and persistence of 10 properties"
(test-property-order 10)))
(deftest quoted-property-values
(let [conn (ldb/start-conn)
_ (graph-parser/parse-file conn
"foo.md"
"- desc:: \"#foo is not a ref\""
{:extract-options {:user-config {}}})
block (->> (d/q '[:find (pull ?b [* {:block/refs [*]}])
:in $
:where [?b :block/properties]]
@conn)
(map first)
first)]
(is (= {:desc "\"#foo is not a ref\""}
(:block/properties block))
"Quoted value is unparsed")
(is (= ["desc"]
(map :block/original-name (:block/refs block)))
"No refs from property value")))
(deftest non-string-property-values
(let [conn (ldb/start-conn)]
(graph-parser/parse-file conn
"lythe-of-heaven.md"
"rating:: 8\nrecommend:: true\narchive:: false"
{})
(is (= {:rating 8 :recommend true :archive false}
(->> (d/q '[:find (pull ?b [*])
:in $
:where [?b :block/properties]]
@conn)
(map (comp :block/properties first))
first)))))
(deftest linkable-built-in-properties
(let [conn (ldb/start-conn)
_ (graph-parser/parse-file conn
"lol.md"
(str "alias:: 233\ntags:: fun, facts"
"\n- "
"alias:: 666\ntags:: block, facts")
{})
page-block (->> (d/q '[:find (pull ?b [:block/properties {:block/alias [:block/name]} {:block/tags [:block/name]}])
:in $
:where [?b :block/name "lol"]]
@conn)
(map first)
first)
block (->> (d/q '[:find (pull ?b [:block/properties])
:in $
:where
[?b :block/properties]
[(missing? $ ?b :block/pre-block?)]
[(missing? $ ?b :block/name)]]
@conn)
(map first)
first)]
(is (= {:block/alias [{:block/name "233"}]
:block/tags [{:block/name "fun"} {:block/name "facts"}]
:block/properties {:alias #{"233"} :tags #{"fun" "facts"}}}
page-block)
"page properties, alias and tags are correct")
(is (every? set? (vals (:block/properties page-block)))
"Linked built-in property values as sets provides for easier transforms")
(is (= {:block/properties {:alias #{"666"} :tags #{"block" "facts"}}}
block)
"block properties are correct")))
(defn- property-relationships-test
"Runs tests on page properties and block properties. file-properties is what is
visible in a file and db-properties is what is pulled out from the db"
[file-properties db-properties user-config]
(let [conn (ldb/start-conn)
page-content (gp-property/->block-content file-properties)
;; Create Block properties from given page ones
block-property-transform (fn [m] (update-keys m #(keyword (str "block-" (name %)))))
block-file-properties (block-property-transform file-properties)
block-content (gp-property/->block-content block-file-properties)
_ (graph-parser/parse-file conn
"property-relationships.md"
(str page-content "\n- " block-content)
{:extract-options {:user-config user-config}})
pages (->> (d/q '[:find (pull ?b [* :block/properties])
:in $
:where [?b :block/name] [?b :block/properties]]
@conn)
(map first))
_ (assert (= 1 (count pages)))
blocks (->> (d/q '[:find (pull ?b [:block/pre-block?
:block/properties
:block/properties-text-values
{:block/refs [:block/original-name]}])
:in $
:where [?b :block/properties] [(missing? $ ?b :block/name)]]
@conn)
(map first)
(map (fn [m] (update m :block/refs #(map :block/original-name %)))))
block-db-properties (block-property-transform db-properties)]
(testing "Page properties"
(is (= db-properties (:block/properties (first pages)))
"page has expected properties")
(is (= file-properties (:block/properties-text-values (first pages)))
"page has expected full text of properties"))
(testing "Pre-block and block properties"
(is (= [true nil] (map :block/pre-block? blocks))
"page has 2 blocks, one of which is a pre-block")
(is (= [db-properties block-db-properties]
(map :block/properties blocks))
"pre-block/page and block have expected properties")
(is (= [file-properties block-file-properties]
(map :block/properties-text-values blocks))
"pre-block/page and block have expected full text of properties")
;; has expected refs
(are [db-props refs]
(= (->> (vals db-props)
;; ignore string values
(mapcat #(if (coll? %) % []))
(concat (map name (keys db-props)))
set)
(set refs))
; pre-block/page has expected refs
db-properties (first (map :block/refs blocks))
;; block has expected refs
block-db-properties (second (map :block/refs blocks))))))
(deftest property-relationships
(let [properties {:single-link "[[bar]]"
:multi-link "[[Logseq]] is the fastest #triples #[[text editor]]"
:desc "This is a multiple sentence description. It has one [[link]]"
:comma-prop "one, two,three"}]
(property-relationships-test
properties
{:single-link #{"bar"}
:multi-link #{"Logseq" "triples" "text editor"}
:desc #{"link"}
:comma-prop "one, two,three"}
{})))
(deftest invalid-properties
(let [conn (ldb/start-conn)
properties {"foo" "valid"
"[[foo]]" "invalid"
"some,prop" "invalid"
"#blarg" "invalid"}
body (str (gp-property/->block-content properties)
"\n- " (gp-property/->block-content properties))]
(graph-parser/parse-file conn "foo.md" body {})
(is (= [{:block/properties {:foo "valid"}
:block/invalid-properties #{"[[foo]]" "some,prop" "#blarg"}}]
(->> (d/q '[:find (pull ?b [*])
:in $
:where
[?b :block/properties]
[(missing? $ ?b :block/pre-block?)]
[(missing? $ ?b :block/name)]]
@conn)
(map first)
(map #(select-keys % [:block/properties :block/invalid-properties]))))
"Has correct (in)valid block properties")
(is (= [{:block/properties {:foo "valid"}
:block/invalid-properties #{"[[foo]]" "some,prop" "#blarg"}}]
(->> (d/q '[:find (pull ?b [*])
:in $
:where [?b :block/properties] [?b :block/name]]
@conn)
(map first)
(map #(select-keys % [:block/properties :block/invalid-properties]))))
"Has correct (in)valid page properties")))
(deftest correct-page-names-created
(testing "from title"
(let [conn (ldb/start-conn)
built-in-pages (set (map string/lower-case default-db/built-in-pages-names))]
(graph-parser/parse-file conn
"foo.md"
"title:: core.async"
{})
(is (= #{"core.async"}
(->> (d/q '[:find (pull ?b [*])
:in $
:where [?b :block/name]]
@conn)
(map (comp :block/name first))
(remove built-in-pages)
set)))))
(testing "from cased org title"
(let [conn (ldb/start-conn)
built-in-pages (set default-db/built-in-pages-names)]
(graph-parser/parse-file conn
"foo.org"
":PROPERTIES:
:ID: 72289d9a-eb2f-427b-ad97-b605a4b8c59b
:END:
#+tItLe: Well parsed!"
{})
(is (= #{"Well parsed!"}
(->> (d/q '[:find (pull ?b [*])
:in $
:where [?b :block/name]]
@conn)
(map (comp :block/original-name first))
(remove built-in-pages)
set)))))
(testing "for file and web uris"
(let [conn (ldb/start-conn)
built-in-pages (set (map string/lower-case default-db/built-in-pages-names))]
(graph-parser/parse-file conn
"foo.md"
(str "- [Filename.txt](file:/test/Filename.txt)\n"
"- [example]()")
{})
(is (= #{"foo"}
(->> (d/q '[:find (pull ?b [*])
:in $
:where [?b :block/name]]
@conn)
(map (comp :block/name first))
(remove built-in-pages)
set))))))
(deftest duplicated-ids
(testing "duplicated block ids in same file"
(let [conn (ldb/start-conn)
extract-block-ids (atom #{})
parse-opts {:extract-options {:extract-block-ids extract-block-ids}}
block-id #uuid "63f199bc-c737-459f-983d-84acfcda14fe"]
(graph-parser/parse-file conn
"foo.md"
"- foo
id:: 63f199bc-c737-459f-983d-84acfcda14fe
- bar
id:: 63f199bc-c737-459f-983d-84acfcda14fe
"
parse-opts)
(let [blocks (:block/_parent (d/entity @conn [:block/name "foo"]))]
(is (= 2 (count blocks)))
(is (= 1 (count (filter #(= (:block/uuid %) block-id) blocks)))))))
(testing "duplicated block ids in multiple files"
(let [conn (ldb/start-conn)
extract-block-ids (atom #{})
parse-opts {:extract-options {:extract-block-ids extract-block-ids}}
block-id #uuid "63f199bc-c737-459f-983d-84acfcda14fe"]
(graph-parser/parse-file conn
"foo.md"
"- foo
id:: 63f199bc-c737-459f-983d-84acfcda14fe
bar
- test"
parse-opts)
(graph-parser/parse-file conn
"bar.md"
"- bar
id:: 63f199bc-c737-459f-983d-84acfcda14fe
bar
- test
"
parse-opts)
(is (= "foo"
(-> (d/entity @conn [:block/uuid block-id])
:block/page
:block/name)))
(let [bar-block (first (:block/_parent (d/entity @conn [:block/name "bar"])))]
(is (some? (:block/uuid bar-block)))
(is (not= (:block/uuid bar-block) block-id))))))
| null | https://raw.githubusercontent.com/logseq/logseq/a4a5758afcb59436301f704b88638153ff1352aa/deps/graph-parser/test/logseq/graph_parser_test.cljs | clojure | Test page properties and block properties
Create Block properties from given page ones
has expected refs
ignore string values
pre-block/page has expected refs
block has expected refs | (ns logseq.graph-parser-test
(:require [cljs.test :refer [deftest testing is are]]
[clojure.string :as string]
[logseq.graph-parser :as graph-parser]
[logseq.db :as ldb]
[logseq.db.default :as default-db]
[logseq.graph-parser.block :as gp-block]
[logseq.graph-parser.property :as gp-property]
[datascript.core :as d]))
(def foo-edn
"Example exported whiteboard page as an edn exportable."
'{:blocks
({:block/content "foo content a",
:block/format :markdown
:block/parent {:block/uuid #uuid "16c90195-6a03-4b3f-839d-095a496d9acd"}},
{:block/content "foo content b",
:block/format :markdown
:block/parent {:block/uuid #uuid "16c90195-6a03-4b3f-839d-095a496d9acd"}}),
:pages
({:block/format :markdown,
:block/name "foo"
:block/original-name "Foo"
:block/uuid #uuid "16c90195-6a03-4b3f-839d-095a496d9acd"
:block/properties {:title "my whiteboard foo"}})})
(def foo-conflict-edn
"Example exported whiteboard page as an edn exportable."
'{:blocks
({:block/content "foo content a",
:block/format :markdown},
{:block/content "foo content b",
:block/format :markdown}),
:pages
({:block/format :markdown,
:block/name "foo conflicted"
:block/original-name "Foo conflicted"
:block/uuid #uuid "16c90195-6a03-4b3f-839d-095a496d9acd"})})
(def bar-edn
"Example exported whiteboard page as an edn exportable."
'{:blocks
({:block/content "foo content a",
:block/format :markdown
:block/parent {:block/uuid #uuid "71515b7d-b5fc-496b-b6bf-c58004a34ee3"
:block/name "foo"}},
{:block/content "foo content b",
:block/format :markdown
:block/parent {:block/uuid #uuid "71515b7d-b5fc-496b-b6bf-c58004a34ee3"
:block/name "foo"}}),
:pages
({:block/format :markdown,
:block/name "bar"
:block/original-name "Bar"
:block/uuid #uuid "71515b7d-b5fc-496b-b6bf-c58004a34ee3"})})
(deftest parse-file
(testing "id properties"
(let [conn (ldb/start-conn)]
(graph-parser/parse-file conn "foo.md" "- id:: 628953c1-8d75-49fe-a648-f4c612109098" {})
(is (= [{:id "628953c1-8d75-49fe-a648-f4c612109098"}]
(->> (d/q '[:find (pull ?b [*])
:in $
:where [?b :block/content] [(missing? $ ?b :block/name)]]
@conn)
(map first)
(map :block/properties)))
"id as text has correct :block/properties")))
(testing "unexpected failure during block extraction"
(let [conn (ldb/start-conn)
deleted-page (atom nil)]
(with-redefs [gp-block/with-pre-block-if-exists (fn stub-failure [& _args]
(throw (js/Error "Testing unexpected failure")))]
(try
(graph-parser/parse-file conn "foo.md" "- id:: 628953c1-8d75-49fe-a648-f4c612109098"
{:delete-blocks-fn (fn [_db page _file _uuids]
(reset! deleted-page page))})
(catch :default _)))
(is (= nil @deleted-page)
"Page should not be deleted when there is unexpected failure")))
(testing "parsing whiteboard page"
(let [conn (ldb/start-conn)]
(graph-parser/parse-file conn "/whiteboards/foo.edn" (pr-str foo-edn) {})
(let [blocks (d/q '[:find (pull ?b [* {:block/page
[:block/name
:block/original-name
:block/type
{:block/file
[:file/path]}]}])
:in $
:where [?b :block/content] [(missing? $ ?b :block/name)]]
@conn)
parent (:block/page (ffirst blocks))]
(is (= {:block/name "foo"
:block/original-name "Foo"
:block/type "whiteboard"
:block/file {:file/path "/whiteboards/foo.edn"}}
parent)
"parsed block in the whiteboard page has correct parent page"))))
(testing "Loading whiteboard pages that same block/uuid should throw an error."
(let [conn (ldb/start-conn)]
(graph-parser/parse-file conn "/whiteboards/foo.edn" (pr-str foo-edn) {})
(is (thrown-with-msg?
js/Error
#"Conflicting upserts"
(graph-parser/parse-file conn "/whiteboards/foo-conflict.edn" (pr-str foo-conflict-edn) {})))))
(testing "Loading whiteboard pages should ignore the :block/name property inside :block/parent."
(let [conn (ldb/start-conn)]
(graph-parser/parse-file conn "/whiteboards/foo.edn" (pr-str foo-edn) {})
(graph-parser/parse-file conn "/whiteboards/bar.edn" (pr-str bar-edn) {})
(let [pages (d/q '[:find ?name
:in $
:where
[?b :block/name ?name]
[?b :block/type "whiteboard"]]
@conn)]
(is (= pages #{["foo"] ["bar"]}))))))
(defn- test-property-order [num-properties]
(let [conn (ldb/start-conn)
properties (mapv #(keyword (str "p" %)) (range 0 num-properties))
text (->> properties
(map #(str (name %) ":: " (name %) "-value"))
(string/join "\n"))
body (str text "\n- " text)
_ (graph-parser/parse-file conn "foo.md" body {})
properties-orders (->> (d/q '[:find (pull ?b [*])
:in $
:where [?b :block/content] [(missing? $ ?b :block/name)]]
@conn)
(map first)
(map :block/properties-order))]
(is (every? vector? properties-orders)
"Order is persisted as a vec to avoid edn serialization quirks")
(is (= [properties properties] properties-orders)
"Property order")))
(deftest properties-order
(testing "Sort order and persistence of a few properties"
(test-property-order 4))
(testing "Sort order and persistence of 10 properties"
(test-property-order 10)))
(deftest quoted-property-values
(let [conn (ldb/start-conn)
_ (graph-parser/parse-file conn
"foo.md"
"- desc:: \"#foo is not a ref\""
{:extract-options {:user-config {}}})
block (->> (d/q '[:find (pull ?b [* {:block/refs [*]}])
:in $
:where [?b :block/properties]]
@conn)
(map first)
first)]
(is (= {:desc "\"#foo is not a ref\""}
(:block/properties block))
"Quoted value is unparsed")
(is (= ["desc"]
(map :block/original-name (:block/refs block)))
"No refs from property value")))
(deftest non-string-property-values
(let [conn (ldb/start-conn)]
(graph-parser/parse-file conn
"lythe-of-heaven.md"
"rating:: 8\nrecommend:: true\narchive:: false"
{})
(is (= {:rating 8 :recommend true :archive false}
(->> (d/q '[:find (pull ?b [*])
:in $
:where [?b :block/properties]]
@conn)
(map (comp :block/properties first))
first)))))
(deftest linkable-built-in-properties
(let [conn (ldb/start-conn)
_ (graph-parser/parse-file conn
"lol.md"
(str "alias:: 233\ntags:: fun, facts"
"\n- "
"alias:: 666\ntags:: block, facts")
{})
page-block (->> (d/q '[:find (pull ?b [:block/properties {:block/alias [:block/name]} {:block/tags [:block/name]}])
:in $
:where [?b :block/name "lol"]]
@conn)
(map first)
first)
block (->> (d/q '[:find (pull ?b [:block/properties])
:in $
:where
[?b :block/properties]
[(missing? $ ?b :block/pre-block?)]
[(missing? $ ?b :block/name)]]
@conn)
(map first)
first)]
(is (= {:block/alias [{:block/name "233"}]
:block/tags [{:block/name "fun"} {:block/name "facts"}]
:block/properties {:alias #{"233"} :tags #{"fun" "facts"}}}
page-block)
"page properties, alias and tags are correct")
(is (every? set? (vals (:block/properties page-block)))
"Linked built-in property values as sets provides for easier transforms")
(is (= {:block/properties {:alias #{"666"} :tags #{"block" "facts"}}}
block)
"block properties are correct")))
(defn- property-relationships-test
"Runs tests on page properties and block properties. file-properties is what is
visible in a file and db-properties is what is pulled out from the db"
[file-properties db-properties user-config]
(let [conn (ldb/start-conn)
page-content (gp-property/->block-content file-properties)
block-property-transform (fn [m] (update-keys m #(keyword (str "block-" (name %)))))
block-file-properties (block-property-transform file-properties)
block-content (gp-property/->block-content block-file-properties)
_ (graph-parser/parse-file conn
"property-relationships.md"
(str page-content "\n- " block-content)
{:extract-options {:user-config user-config}})
pages (->> (d/q '[:find (pull ?b [* :block/properties])
:in $
:where [?b :block/name] [?b :block/properties]]
@conn)
(map first))
_ (assert (= 1 (count pages)))
blocks (->> (d/q '[:find (pull ?b [:block/pre-block?
:block/properties
:block/properties-text-values
{:block/refs [:block/original-name]}])
:in $
:where [?b :block/properties] [(missing? $ ?b :block/name)]]
@conn)
(map first)
(map (fn [m] (update m :block/refs #(map :block/original-name %)))))
block-db-properties (block-property-transform db-properties)]
(testing "Page properties"
(is (= db-properties (:block/properties (first pages)))
"page has expected properties")
(is (= file-properties (:block/properties-text-values (first pages)))
"page has expected full text of properties"))
(testing "Pre-block and block properties"
(is (= [true nil] (map :block/pre-block? blocks))
"page has 2 blocks, one of which is a pre-block")
(is (= [db-properties block-db-properties]
(map :block/properties blocks))
"pre-block/page and block have expected properties")
(is (= [file-properties block-file-properties]
(map :block/properties-text-values blocks))
"pre-block/page and block have expected full text of properties")
(are [db-props refs]
(= (->> (vals db-props)
(mapcat #(if (coll? %) % []))
(concat (map name (keys db-props)))
set)
(set refs))
db-properties (first (map :block/refs blocks))
block-db-properties (second (map :block/refs blocks))))))
(deftest property-relationships
(let [properties {:single-link "[[bar]]"
:multi-link "[[Logseq]] is the fastest #triples #[[text editor]]"
:desc "This is a multiple sentence description. It has one [[link]]"
:comma-prop "one, two,three"}]
(property-relationships-test
properties
{:single-link #{"bar"}
:multi-link #{"Logseq" "triples" "text editor"}
:desc #{"link"}
:comma-prop "one, two,three"}
{})))
(deftest invalid-properties
(let [conn (ldb/start-conn)
properties {"foo" "valid"
"[[foo]]" "invalid"
"some,prop" "invalid"
"#blarg" "invalid"}
body (str (gp-property/->block-content properties)
"\n- " (gp-property/->block-content properties))]
(graph-parser/parse-file conn "foo.md" body {})
(is (= [{:block/properties {:foo "valid"}
:block/invalid-properties #{"[[foo]]" "some,prop" "#blarg"}}]
(->> (d/q '[:find (pull ?b [*])
:in $
:where
[?b :block/properties]
[(missing? $ ?b :block/pre-block?)]
[(missing? $ ?b :block/name)]]
@conn)
(map first)
(map #(select-keys % [:block/properties :block/invalid-properties]))))
"Has correct (in)valid block properties")
(is (= [{:block/properties {:foo "valid"}
:block/invalid-properties #{"[[foo]]" "some,prop" "#blarg"}}]
(->> (d/q '[:find (pull ?b [*])
:in $
:where [?b :block/properties] [?b :block/name]]
@conn)
(map first)
(map #(select-keys % [:block/properties :block/invalid-properties]))))
"Has correct (in)valid page properties")))
(deftest correct-page-names-created
(testing "from title"
(let [conn (ldb/start-conn)
built-in-pages (set (map string/lower-case default-db/built-in-pages-names))]
(graph-parser/parse-file conn
"foo.md"
"title:: core.async"
{})
(is (= #{"core.async"}
(->> (d/q '[:find (pull ?b [*])
:in $
:where [?b :block/name]]
@conn)
(map (comp :block/name first))
(remove built-in-pages)
set)))))
(testing "from cased org title"
(let [conn (ldb/start-conn)
built-in-pages (set default-db/built-in-pages-names)]
(graph-parser/parse-file conn
"foo.org"
":PROPERTIES:
:ID: 72289d9a-eb2f-427b-ad97-b605a4b8c59b
:END:
#+tItLe: Well parsed!"
{})
(is (= #{"Well parsed!"}
(->> (d/q '[:find (pull ?b [*])
:in $
:where [?b :block/name]]
@conn)
(map (comp :block/original-name first))
(remove built-in-pages)
set)))))
(testing "for file and web uris"
(let [conn (ldb/start-conn)
built-in-pages (set (map string/lower-case default-db/built-in-pages-names))]
(graph-parser/parse-file conn
"foo.md"
(str "- [Filename.txt](file:/test/Filename.txt)\n"
"- [example]()")
{})
(is (= #{"foo"}
(->> (d/q '[:find (pull ?b [*])
:in $
:where [?b :block/name]]
@conn)
(map (comp :block/name first))
(remove built-in-pages)
set))))))
(deftest duplicated-ids
(testing "duplicated block ids in same file"
(let [conn (ldb/start-conn)
extract-block-ids (atom #{})
parse-opts {:extract-options {:extract-block-ids extract-block-ids}}
block-id #uuid "63f199bc-c737-459f-983d-84acfcda14fe"]
(graph-parser/parse-file conn
"foo.md"
"- foo
id:: 63f199bc-c737-459f-983d-84acfcda14fe
- bar
id:: 63f199bc-c737-459f-983d-84acfcda14fe
"
parse-opts)
(let [blocks (:block/_parent (d/entity @conn [:block/name "foo"]))]
(is (= 2 (count blocks)))
(is (= 1 (count (filter #(= (:block/uuid %) block-id) blocks)))))))
(testing "duplicated block ids in multiple files"
(let [conn (ldb/start-conn)
extract-block-ids (atom #{})
parse-opts {:extract-options {:extract-block-ids extract-block-ids}}
block-id #uuid "63f199bc-c737-459f-983d-84acfcda14fe"]
(graph-parser/parse-file conn
"foo.md"
"- foo
id:: 63f199bc-c737-459f-983d-84acfcda14fe
bar
- test"
parse-opts)
(graph-parser/parse-file conn
"bar.md"
"- bar
id:: 63f199bc-c737-459f-983d-84acfcda14fe
bar
- test
"
parse-opts)
(is (= "foo"
(-> (d/entity @conn [:block/uuid block-id])
:block/page
:block/name)))
(let [bar-block (first (:block/_parent (d/entity @conn [:block/name "bar"])))]
(is (some? (:block/uuid bar-block)))
(is (not= (:block/uuid bar-block) block-id))))))
|
3299ea8f2bed05bc05a48075b86693f003b090344d8235958c2686c0c0e46ebd | ghc/testsuite | T7545.hs | # LANGUAGE RankNTypes , InstanceSigs #
module T7545 where
class C a where
f :: a -> b
instance C (a -> b) where
f :: x
f = undefined
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_fail/T7545.hs | haskell | # LANGUAGE RankNTypes , InstanceSigs #
module T7545 where
class C a where
f :: a -> b
instance C (a -> b) where
f :: x
f = undefined
| |
328da2445096abe3a7fc8bbbebfb72d8ab849d902d99b3434ff43b7981ad7a60 | minoki/pandoc-aozora-ruby | TextCompat.hs | # LANGUAGE TypeFamilies #
module TextCompat where
import Data.String
import qualified Data.Text as T
class TextLike s where
toString :: s -> String
instance a ~ Char => TextLike [a] where
toString = id
instance TextLike T.Text where
toString = T.unpack
| null | https://raw.githubusercontent.com/minoki/pandoc-aozora-ruby/b33e8121b6ce211fd4dc1d792ac78d01ce4fa300/src/TextCompat.hs | haskell | # LANGUAGE TypeFamilies #
module TextCompat where
import Data.String
import qualified Data.Text as T
class TextLike s where
toString :: s -> String
instance a ~ Char => TextLike [a] where
toString = id
instance TextLike T.Text where
toString = T.unpack
| |
371eab3a777b10557f21e4f1d97d196157f4ce6bea67208e34b0f3f54098cfd5 | ha-mo-we/Racer | owlapi-synonyms.lisp | (in-package owlapi)
;;;
;;;----------------------------------------------
Automatically Generated
Version : 2.0 , Build : 2013 - 03 - 07
Date : March 07 2013 , 13:05
;;;----------------------------------------------
;;;
(progn
(owlapi-defun (owlapi-write-xml-ontology-file)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-writeXMLOntologyFile| common-lisp-user::args))
(owlapi-defun (owlapi-write-ontology-file)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-writeOntologyFile| common-lisp-user::args))
(owlapi-defun (owlapi-write-functional-ontology-file)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-writeFunctionalOntologyFile|
common-lisp-user::args))
(owlapi-defun (owlapi-uses-simplified-protocol)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-usesSimplifiedProtocol| common-lisp-user::args))
(owlapi-defun (owlapi-uses-incremental-updates)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-usesIncrementalUpdates| common-lisp-user::args))
(owlapi-defun (owlapi-unload-ontology) (&rest common-lisp-user::args)
(apply #'|OWLAPI-unloadOntology| common-lisp-user::args))
(owlapi-defun (owlapi-unload-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-unloadOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-unload-axioms) (&rest common-lisp-user::args)
(apply #'|OWLAPI-unloadAxioms| common-lisp-user::args))
(owlapi-defun (owlapi-unload-axiom) (&rest common-lisp-user::args)
(apply #'|OWLAPI-unloadAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-store-image) (&rest common-lisp-user::args)
(apply #'|OWLAPI-storeImage| common-lisp-user::args))
(owlapi-defun (owlapi-sleep) (&rest common-lisp-user::args)
(apply #'|OWLAPI-sleep| common-lisp-user::args))
(owlapi-defun (owlapi-set-return-policy)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-setReturnPolicy| common-lisp-user::args))
(owlapi-defun (owlapi-set-progress-range)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-setProgressRange| common-lisp-user::args))
(owlapi-defun (owlapi-set-progress) (&rest common-lisp-user::args)
(apply #'|OWLAPI-setProgress| common-lisp-user::args))
(owlapi-defun (owlapi-set-current-reasoner)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-setCurrentReasoner| common-lisp-user::args))
(owlapi-defun (owlapi-set-axiom-counter)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-setAxiomCounter| common-lisp-user::args))
(owlapi-defun (owlapi-set-auto-declare-data-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-setAutoDeclareDataProperties|
common-lisp-user::args))
(owlapi-defun (owlapi-save-ontology) (&rest common-lisp-user::args)
(apply #'|OWLAPI-saveOntology| common-lisp-user::args))
(owlapi-defun (owlapi-restore-image) (&rest common-lisp-user::args)
(apply #'|OWLAPI-restoreImage| common-lisp-user::args))
(owlapi-defun (owlapi-reset-axiom-counter)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-resetAxiomCounter| common-lisp-user::args))
(owlapi-defun (owlapi-remove-prefix) (&rest common-lisp-user::args)
(apply #'|OWLAPI-removePrefix| common-lisp-user::args))
(owlapi-defun (owlapi-reload-loaded-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-reloadLoadedOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-register-referenced-entities)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-registerReferencedEntities|
common-lisp-user::args))
(owlapi-defun (owlapi-register-object) (&rest common-lisp-user::args)
(apply #'|OWLAPI-registerObject| common-lisp-user::args))
(owlapi-defun (owlapi-register-last-answer)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-registerLastAnswer| common-lisp-user::args))
(owlapi-defun (owlapi-register-declared-entities)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-registerDeclaredEntities| common-lisp-user::args))
(owlapi-defun (owlapi-realize) (&rest common-lisp-user::args)
(apply #'|OWLAPI-realize| common-lisp-user::args))
(owlapi-defun (owlapi-read-xml-ontology-file)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-readXMLOntologyFile| common-lisp-user::args))
(owlapi-defun (owlapi-read-xml-ontology-document)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-readXMLOntologyDocument| common-lisp-user::args))
(owlapi-defun (owlapi-read-ontology) (&rest common-lisp-user::args)
(apply #'|OWLAPI-readOntology| common-lisp-user::args))
(owlapi-defun (owlapi-read-functional-ontology-file)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-readFunctionalOntologyFile|
common-lisp-user::args))
(owlapi-defun (owlapi-read-functional-ontology-document)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-readFunctionalOntologyDocument|
common-lisp-user::args))
(owlapi-defun (owlapi-parse-native) (&rest common-lisp-user::args)
(apply #'|OWLAPI-parseNative| common-lisp-user::args))
(owlapi-defun (owlapi-parse) (&rest common-lisp-user::args)
(apply #'|OWLAPI-parse| common-lisp-user::args))
(owlapi-defun (owlapi-next-axiom-use-id)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-nextAxiomUseID| common-lisp-user::args))
(owlapi-defun (owlapi-new-reasoner1) (&rest common-lisp-user::args)
(apply #'|OWLAPI-newReasoner1| common-lisp-user::args))
(owlapi-defun (owlapi-new-reasoner) (&rest common-lisp-user::args)
(apply #'|OWLAPI-newReasoner| common-lisp-user::args))
(owlapi-defun (owlapi-new-ontology) (&rest common-lisp-user::args)
(apply #'|OWLAPI-newOntology| common-lisp-user::args))
(owlapi-defun (owlapi-merge-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-mergeOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-manually-apply-changes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-manuallyApplyChanges| common-lisp-user::args))
(owlapi-defun (owlapi-load-ontology) (&rest common-lisp-user::args)
(apply #'|OWLAPI-loadOntology| common-lisp-user::args))
(owlapi-defun (owlapi-load-ontologies) (&rest common-lisp-user::args)
(apply #'|OWLAPI-loadOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-load-axioms) (&rest common-lisp-user::args)
(apply #'|OWLAPI-loadAxioms| common-lisp-user::args))
(owlapi-defun (owlapi-load-axiom) (&rest common-lisp-user::args)
(apply #'|OWLAPI-loadAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-keep-annotations)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-keepAnnotations| common-lisp-user::args))
(owlapi-defun (owlapi-is-transitive) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isTransitive| common-lisp-user::args))
(owlapi-defun (owlapi-is-symmetric) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isSymmetric| common-lisp-user::args))
(owlapi-defun (owlapi-is-sub-class-of) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isSubClassOf| common-lisp-user::args))
(owlapi-defun (owlapi-is-satisfiable) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isSatisfiable| common-lisp-user::args))
(owlapi-defun (owlapi-is-same-individual)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isSameIndividual| common-lisp-user::args))
(owlapi-defun (owlapi-is-reflexive) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isReflexive| common-lisp-user::args))
(owlapi-defun (owlapi-is-realised) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isRealised| common-lisp-user::args))
(owlapi-defun (owlapi-is-irreflexive) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isIrreflexive| common-lisp-user::args))
(owlapi-defun (owlapi-is-inverse-functional)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isInverseFunctional| common-lisp-user::args))
(owlapi-defun (owlapi-is-functional) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isFunctional| common-lisp-user::args))
(owlapi-defun (owlapi-is-equivalent-class)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isEquivalentClass| common-lisp-user::args))
(owlapi-defun (owlapi-is-entailed) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isEntailed| common-lisp-user::args))
(owlapi-defun (owlapi-is-different-individual)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isDifferentIndividual| common-lisp-user::args))
(owlapi-defun (owlapi-is-defined-object-property)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isDefinedObjectProperty| common-lisp-user::args))
(owlapi-defun (owlapi-is-defined-individual)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isDefinedIndividual| common-lisp-user::args))
(owlapi-defun (owlapi-is-defined-data-property)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isDefinedDataProperty| common-lisp-user::args))
(owlapi-defun (owlapi-is-defined-class)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isDefinedClass| common-lisp-user::args))
(owlapi-defun (owlapi-is-consistent) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isConsistent| common-lisp-user::args))
(owlapi-defun (owlapi-is-classified) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isClassified| common-lisp-user::args))
(owlapi-defun (owlapi-is-class) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isClass| common-lisp-user::args))
(owlapi-defun (owlapi-is-asymmetric) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isAsymmetric| common-lisp-user::args))
(owlapi-defun (owlapi-init) (&rest common-lisp-user::args)
(apply #'|OWLAPI-init| common-lisp-user::args))
(owlapi-defun (owlapi-ignore-declarations)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-ignoreDeclarations| common-lisp-user::args))
(owlapi-defun (owlapi-ignore-annotations)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-ignoreAnnotations| common-lisp-user::args))
(owlapi-defun (owlapi-has-type) (&rest common-lisp-user::args)
(apply #'|OWLAPI-hasType| common-lisp-user::args))
(owlapi-defun (owlapi-has-object-property-relationship)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-hasObjectPropertyRelationship|
common-lisp-user::args))
(owlapi-defun (owlapi-has-data-property-relationship)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-hasDataPropertyRelationship|
common-lisp-user::args))
(owlapi-defun (owlapi-get-types) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getTypes| common-lisp-user::args))
(owlapi-defun (owlapi-get-super-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getSuperProperties| common-lisp-user::args))
(owlapi-defun (owlapi-get-super-classes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getSuperClasses| common-lisp-user::args))
(owlapi-defun (owlapi-get-sub-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getSubProperties| common-lisp-user::args))
(owlapi-defun (owlapi-get-sub-classes) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getSubClasses| common-lisp-user::args))
(owlapi-defun (owlapi-get-same-individuals)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getSameIndividuals| common-lisp-user::args))
(owlapi-defun (owlapi-get-related-values)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getRelatedValues| common-lisp-user::args))
(owlapi-defun (owlapi-get-related-individuals)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getRelatedIndividuals| common-lisp-user::args))
(owlapi-defun (owlapi-get-reasoners) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getReasoners| common-lisp-user::args))
(owlapi-defun (owlapi-get-ranges) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getRanges| common-lisp-user::args))
(owlapi-defun (owlapi-get-prefixes) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getPrefixes| common-lisp-user::args))
(owlapi-defun (owlapi-get-ontologies) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-get-object-property-values)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getObjectPropertyValues| common-lisp-user::args))
(owlapi-defun (owlapi-get-object-property-relationships)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getObjectPropertyRelationships|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-transitive-object-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLTransitiveObjectPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-symmetric-object-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLSymmetricObjectPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-sub-class-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLSubClassAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-sub-annotation-property-of-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLSubAnnotationPropertyOfAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-sub-annotation-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLSubAnnotationPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-same-individuals-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLSameIndividualsAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-reflexive-object-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLReflexiveObjectPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-really-implicit-declaration-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLReallyImplicitDeclarationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-prefix-declaration-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLPrefixDeclarationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-ontology-version-declaration-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLOntologyVersionDeclarationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-ontology-annotation-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLOntologyAnnotationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-object-sub-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLObjectSubPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-object-property-range-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLObjectPropertyRangeAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-object-property-domain-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLObjectPropertyDomainAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-object-property-chain-sub-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLObjectPropertyChainSubPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-object-property-assertion-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLObjectPropertyAssertionAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-negative-object-property-assertion-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLNegativeObjectPropertyAssertionAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-negative-data-property-assertion-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLNegativeDataPropertyAssertionAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-irreflexive-object-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLIrreflexiveObjectPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-inverse-object-properties-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLInverseObjectPropertiesAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-inverse-functional-object-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLInverseFunctionalObjectPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-imports-declaration-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLImportsDeclarationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-implicit-declaration-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLImplicitDeclarationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-has-key-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLHasKeyAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-functional-object-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLFunctionalObjectPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-functional-data-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLFunctionalDataPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-equivalent-object-properties-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLEquivalentObjectPropertiesAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-equivalent-data-properties-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLEquivalentDataPropertiesAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-equivalent-classes-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLEquivalentClassesAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-entity-annotation-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLEntityAnnotationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-disjoint-union-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDisjointUnionAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-disjoint-object-properties-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDisjointObjectPropertiesAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-disjoint-data-properties-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDisjointDataPropertiesAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-disjoint-classes-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDisjointClassesAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-different-individuals-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDifferentIndividualsAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-declaration-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDeclarationAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-datatype-definition-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDatatypeDefinitionAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-data-sub-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDataSubPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-data-property-range-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDataPropertyRangeAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-data-property-domain-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDataPropertyDomainAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-data-property-assertion-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDataPropertyAssertionAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-class-assertion-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLClassAssertionAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-axiom-annotation-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLAxiomAnnotationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-asymmetric-object-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLAsymmetricObjectPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-annotation-property-range-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLAnnotationPropertyRangeAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-annotation-property-domain-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLAnnotationPropertyDomainAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-annotation-assertion-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLAnnotationAssertionAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-loaded-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getLoadedOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-get-inverse-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getInverseProperties| common-lisp-user::args))
(owlapi-defun (owlapi-get-instances) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getInstances| common-lisp-user::args))
(owlapi-defun (owlapi-get-individuals) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getIndividuals| common-lisp-user::args))
(owlapi-defun (owlapi-get-inconsistent-classes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getInconsistentClasses| common-lisp-user::args))
(owlapi-defun (owlapi-get-equivalent-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getEquivalentProperties| common-lisp-user::args))
(owlapi-defun (owlapi-get-equivalent-classes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getEquivalentClasses| common-lisp-user::args))
(owlapi-defun (owlapi-get-domains) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getDomains| common-lisp-user::args))
(owlapi-defun (owlapi-get-disjoint-object-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDisjointObjectProperties|
common-lisp-user::args))
(owlapi-defun (owlapi-get-disjoint-data-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDisjointDataProperties|
common-lisp-user::args))
(owlapi-defun (owlapi-get-disjoint-classes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDisjointClasses| common-lisp-user::args))
(owlapi-defun (owlapi-get-different-individuals)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDifferentIndividuals| common-lisp-user::args))
(owlapi-defun (owlapi-get-descendant-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDescendantProperties| common-lisp-user::args))
(owlapi-defun (owlapi-get-descendant-classes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDescendantClasses| common-lisp-user::args))
(owlapi-defun (owlapi-get-data-property-values)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDataPropertyValues| common-lisp-user::args))
(owlapi-defun (owlapi-get-data-property-relationships)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDataPropertyRelationships|
common-lisp-user::args))
(owlapi-defun (owlapi-get-current-reasoner)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getCurrentReasoner| common-lisp-user::args))
(owlapi-defun (owlapi-get-changes) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getChanges| common-lisp-user::args))
(owlapi-defun (owlapi-get-axioms-per-ontology)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAxiomsPerOntology| common-lisp-user::args))
(owlapi-defun (owlapi-get-axioms-of-type-in)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAxiomsOfTypeIn| common-lisp-user::args))
(owlapi-defun (owlapi-get-axioms-of-type)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAxiomsOfType| common-lisp-user::args))
(owlapi-defun (owlapi-get-axioms-in) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getAxiomsIn| common-lisp-user::args))
(owlapi-defun (owlapi-get-axioms) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getAxioms| common-lisp-user::args))
(owlapi-defun (owlapi-get-axiom-counter)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAxiomCounter| common-lisp-user::args))
(owlapi-defun (owlapi-get-auto-ontology)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAutoOntology| common-lisp-user::args))
(owlapi-defun (owlapi-get-auto-declare-data-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAutoDeclareDataProperties|
common-lisp-user::args))
(owlapi-defun (owlapi-get-annotation-axioms-for-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAnnotationAxiomsForAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-ancestor-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAncestorProperties| common-lisp-user::args))
(owlapi-defun (owlapi-get-ancestor-classes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAncestorClasses| common-lisp-user::args))
(owlapi-defun (owlapi-get-all-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAllOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-find-object-from-id)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-findObjectFromID| common-lisp-user::args))
(owlapi-defun (owlapi-find-id-from-object)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-findIDFromObject| common-lisp-user::args))
(owlapi-defun (owlapi-export-reasoner) (&rest common-lisp-user::args)
(apply #'|OWLAPI-exportReasoner| common-lisp-user::args))
(owlapi-defun (owlapi-export-ontology) (&rest common-lisp-user::args)
(apply #'|OWLAPI-exportOntology| common-lisp-user::args))
(owlapi-defun (owlapi-enable-transient-axiom-mode)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-enableTransientAxiomMode| common-lisp-user::args))
(owlapi-defun (owlapi-enable-simplified-protocol)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-enableSimplifiedProtocol| common-lisp-user::args))
(owlapi-defun (owlapi-enable-memory-saving-mode)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-enableMemorySavingMode| common-lisp-user::args))
(owlapi-defun (owlapi-enable-lookup-mode)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-enableLookupMode| common-lisp-user::args))
(owlapi-defun (owlapi-enable-incremental-updates)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-enableIncrementalUpdates| common-lisp-user::args))
(owlapi-defun (owlapi-dont-register-referenced-entities)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-dontRegisterReferencedEntities|
common-lisp-user::args))
(owlapi-defun (owlapi-dont-register-declared-entities)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-dontRegisterDeclaredEntities|
common-lisp-user::args))
(owlapi-defun (owlapi-dispose-reasoner)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disposeReasoner| common-lisp-user::args))
(owlapi-defun (owlapi-dispose-ontology)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disposeOntology| common-lisp-user::args))
(owlapi-defun (owlapi-dispose-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disposeOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-dispose-axioms) (&rest common-lisp-user::args)
(apply #'|OWLAPI-disposeAxioms| common-lisp-user::args))
(owlapi-defun (owlapi-dispose-axiom) (&rest common-lisp-user::args)
(apply #'|OWLAPI-disposeAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-dispose) (&rest common-lisp-user::args)
(apply #'|OWLAPI-dispose| common-lisp-user::args))
(owlapi-defun (owlapi-disable-transient-axiom-mode)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disableTransientAxiomMode|
common-lisp-user::args))
(owlapi-defun (owlapi-disable-simplified-protocol)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disableSimplifiedProtocol|
common-lisp-user::args))
(owlapi-defun (owlapi-disable-memory-saving-mode)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disableMemorySavingMode| common-lisp-user::args))
(owlapi-defun (owlapi-disable-lookup-mode)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disableLookupMode| common-lisp-user::args))
(owlapi-defun (owlapi-disable-incremental-updates)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disableIncrementalUpdates|
common-lisp-user::args))
(owlapi-defun (owlapi-disable-auto-mode)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disableAutoMode| common-lisp-user::args))
(owlapi-defun (owlapi-describe-reasoners)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-describeReasoners| common-lisp-user::args))
(owlapi-defun (owlapi-describe-reasoner)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-describeReasoner| common-lisp-user::args))
(owlapi-defun (owlapi-describe-ontology)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-describeOntology| common-lisp-user::args))
(owlapi-defun (owlapi-describe-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-describeOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-contains) (&rest common-lisp-user::args)
(apply #'|OWLAPI-contains| common-lisp-user::args))
(owlapi-defun (owlapi-consider-declarations)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-considerDeclarations| common-lisp-user::args))
(owlapi-defun (owlapi-clear-registry) (&rest common-lisp-user::args)
(apply #'|OWLAPI-clearRegistry| common-lisp-user::args))
(owlapi-defun (owlapi-clear-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-clearOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-clear-changes) (&rest common-lisp-user::args)
(apply #'|OWLAPI-clearChanges| common-lisp-user::args))
(owlapi-defun (owlapi-classify) (&rest common-lisp-user::args)
(apply #'|OWLAPI-classify| common-lisp-user::args))
(owlapi-defun (owlapi-batch-synchronize)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-batchSynchronize| common-lisp-user::args))
(owlapi-defun (owlapi-auto-remove-axioms-from)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-autoRemoveAxiomsFrom| common-lisp-user::args))
(owlapi-defun (owlapi-auto-batch-remove-axioms-from)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-autoBatchRemoveAxiomsFrom|
common-lisp-user::args))
(owlapi-defun (owlapi-auto-batch-add-axioms-to)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-autoBatchAddAxiomsTo| common-lisp-user::args))
(owlapi-defun (owlapi-auto-apply-changes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-autoApplyChanges| common-lisp-user::args))
(owlapi-defun (owlapi-auto-add-axioms-to)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-autoAddAxiomsTo| common-lisp-user::args))
(owlapi-defun (owlapi-apply-changes) (&rest common-lisp-user::args)
(apply #'|OWLAPI-applyChanges| common-lisp-user::args))
(owlapi-defun (owlapi-advance-progress)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-advanceProgress| common-lisp-user::args))
(owlapi-defun (owlapi-add-prefix) (&rest common-lisp-user::args)
(apply #'|OWLAPI-addPrefix| common-lisp-user::args))
(owlapi-defun (owlapi-abort) (&rest common-lisp-user::args)
(apply #'|OWLAPI-abort| common-lisp-user::args))
(owlapi-defun (owlapi-set-ontology-uri)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-SetOntologyURI| common-lisp-user::args))
(owlapi-defun (owlapi-remove-axioms) (&rest common-lisp-user::args)
(apply #'|OWLAPI-RemoveAxioms| common-lisp-user::args))
(owlapi-defun (owlapi-remove-axiom) (&rest common-lisp-user::args)
(apply #'|OWLAPI-RemoveAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-id-to-axiom) (&rest common-lisp-user::args)
(apply #'|OWLAPI-IDToAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-axiom-to-id) (&rest common-lisp-user::args)
(apply #'|OWLAPI-AxiomToID| common-lisp-user::args))
(owlapi-defun (owlapi-axiom-loaded?) (&rest common-lisp-user::args)
(apply #'|OWLAPI-AxiomLoaded?| common-lisp-user::args))
(owlapi-defun (owlapi-add-axioms) (&rest common-lisp-user::args)
(apply #'|OWLAPI-AddAxioms| common-lisp-user::args))
(owlapi-defun (owlapi-add-axiom) (&rest common-lisp-user::args)
(apply #'|OWLAPI-AddAxiom| common-lisp-user::args))) | null | https://raw.githubusercontent.com/ha-mo-we/Racer/d690841d10015c7a75b1ded393fcf0a33092c4de/source/owlapi-synonyms.lisp | lisp |
----------------------------------------------
----------------------------------------------
| (in-package owlapi)
Automatically Generated
Version : 2.0 , Build : 2013 - 03 - 07
Date : March 07 2013 , 13:05
(progn
(owlapi-defun (owlapi-write-xml-ontology-file)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-writeXMLOntologyFile| common-lisp-user::args))
(owlapi-defun (owlapi-write-ontology-file)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-writeOntologyFile| common-lisp-user::args))
(owlapi-defun (owlapi-write-functional-ontology-file)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-writeFunctionalOntologyFile|
common-lisp-user::args))
(owlapi-defun (owlapi-uses-simplified-protocol)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-usesSimplifiedProtocol| common-lisp-user::args))
(owlapi-defun (owlapi-uses-incremental-updates)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-usesIncrementalUpdates| common-lisp-user::args))
(owlapi-defun (owlapi-unload-ontology) (&rest common-lisp-user::args)
(apply #'|OWLAPI-unloadOntology| common-lisp-user::args))
(owlapi-defun (owlapi-unload-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-unloadOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-unload-axioms) (&rest common-lisp-user::args)
(apply #'|OWLAPI-unloadAxioms| common-lisp-user::args))
(owlapi-defun (owlapi-unload-axiom) (&rest common-lisp-user::args)
(apply #'|OWLAPI-unloadAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-store-image) (&rest common-lisp-user::args)
(apply #'|OWLAPI-storeImage| common-lisp-user::args))
(owlapi-defun (owlapi-sleep) (&rest common-lisp-user::args)
(apply #'|OWLAPI-sleep| common-lisp-user::args))
(owlapi-defun (owlapi-set-return-policy)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-setReturnPolicy| common-lisp-user::args))
(owlapi-defun (owlapi-set-progress-range)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-setProgressRange| common-lisp-user::args))
(owlapi-defun (owlapi-set-progress) (&rest common-lisp-user::args)
(apply #'|OWLAPI-setProgress| common-lisp-user::args))
(owlapi-defun (owlapi-set-current-reasoner)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-setCurrentReasoner| common-lisp-user::args))
(owlapi-defun (owlapi-set-axiom-counter)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-setAxiomCounter| common-lisp-user::args))
(owlapi-defun (owlapi-set-auto-declare-data-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-setAutoDeclareDataProperties|
common-lisp-user::args))
(owlapi-defun (owlapi-save-ontology) (&rest common-lisp-user::args)
(apply #'|OWLAPI-saveOntology| common-lisp-user::args))
(owlapi-defun (owlapi-restore-image) (&rest common-lisp-user::args)
(apply #'|OWLAPI-restoreImage| common-lisp-user::args))
(owlapi-defun (owlapi-reset-axiom-counter)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-resetAxiomCounter| common-lisp-user::args))
(owlapi-defun (owlapi-remove-prefix) (&rest common-lisp-user::args)
(apply #'|OWLAPI-removePrefix| common-lisp-user::args))
(owlapi-defun (owlapi-reload-loaded-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-reloadLoadedOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-register-referenced-entities)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-registerReferencedEntities|
common-lisp-user::args))
(owlapi-defun (owlapi-register-object) (&rest common-lisp-user::args)
(apply #'|OWLAPI-registerObject| common-lisp-user::args))
(owlapi-defun (owlapi-register-last-answer)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-registerLastAnswer| common-lisp-user::args))
(owlapi-defun (owlapi-register-declared-entities)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-registerDeclaredEntities| common-lisp-user::args))
(owlapi-defun (owlapi-realize) (&rest common-lisp-user::args)
(apply #'|OWLAPI-realize| common-lisp-user::args))
(owlapi-defun (owlapi-read-xml-ontology-file)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-readXMLOntologyFile| common-lisp-user::args))
(owlapi-defun (owlapi-read-xml-ontology-document)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-readXMLOntologyDocument| common-lisp-user::args))
(owlapi-defun (owlapi-read-ontology) (&rest common-lisp-user::args)
(apply #'|OWLAPI-readOntology| common-lisp-user::args))
(owlapi-defun (owlapi-read-functional-ontology-file)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-readFunctionalOntologyFile|
common-lisp-user::args))
(owlapi-defun (owlapi-read-functional-ontology-document)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-readFunctionalOntologyDocument|
common-lisp-user::args))
(owlapi-defun (owlapi-parse-native) (&rest common-lisp-user::args)
(apply #'|OWLAPI-parseNative| common-lisp-user::args))
(owlapi-defun (owlapi-parse) (&rest common-lisp-user::args)
(apply #'|OWLAPI-parse| common-lisp-user::args))
(owlapi-defun (owlapi-next-axiom-use-id)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-nextAxiomUseID| common-lisp-user::args))
(owlapi-defun (owlapi-new-reasoner1) (&rest common-lisp-user::args)
(apply #'|OWLAPI-newReasoner1| common-lisp-user::args))
(owlapi-defun (owlapi-new-reasoner) (&rest common-lisp-user::args)
(apply #'|OWLAPI-newReasoner| common-lisp-user::args))
(owlapi-defun (owlapi-new-ontology) (&rest common-lisp-user::args)
(apply #'|OWLAPI-newOntology| common-lisp-user::args))
(owlapi-defun (owlapi-merge-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-mergeOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-manually-apply-changes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-manuallyApplyChanges| common-lisp-user::args))
(owlapi-defun (owlapi-load-ontology) (&rest common-lisp-user::args)
(apply #'|OWLAPI-loadOntology| common-lisp-user::args))
(owlapi-defun (owlapi-load-ontologies) (&rest common-lisp-user::args)
(apply #'|OWLAPI-loadOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-load-axioms) (&rest common-lisp-user::args)
(apply #'|OWLAPI-loadAxioms| common-lisp-user::args))
(owlapi-defun (owlapi-load-axiom) (&rest common-lisp-user::args)
(apply #'|OWLAPI-loadAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-keep-annotations)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-keepAnnotations| common-lisp-user::args))
(owlapi-defun (owlapi-is-transitive) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isTransitive| common-lisp-user::args))
(owlapi-defun (owlapi-is-symmetric) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isSymmetric| common-lisp-user::args))
(owlapi-defun (owlapi-is-sub-class-of) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isSubClassOf| common-lisp-user::args))
(owlapi-defun (owlapi-is-satisfiable) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isSatisfiable| common-lisp-user::args))
(owlapi-defun (owlapi-is-same-individual)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isSameIndividual| common-lisp-user::args))
(owlapi-defun (owlapi-is-reflexive) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isReflexive| common-lisp-user::args))
(owlapi-defun (owlapi-is-realised) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isRealised| common-lisp-user::args))
(owlapi-defun (owlapi-is-irreflexive) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isIrreflexive| common-lisp-user::args))
(owlapi-defun (owlapi-is-inverse-functional)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isInverseFunctional| common-lisp-user::args))
(owlapi-defun (owlapi-is-functional) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isFunctional| common-lisp-user::args))
(owlapi-defun (owlapi-is-equivalent-class)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isEquivalentClass| common-lisp-user::args))
(owlapi-defun (owlapi-is-entailed) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isEntailed| common-lisp-user::args))
(owlapi-defun (owlapi-is-different-individual)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isDifferentIndividual| common-lisp-user::args))
(owlapi-defun (owlapi-is-defined-object-property)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isDefinedObjectProperty| common-lisp-user::args))
(owlapi-defun (owlapi-is-defined-individual)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isDefinedIndividual| common-lisp-user::args))
(owlapi-defun (owlapi-is-defined-data-property)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isDefinedDataProperty| common-lisp-user::args))
(owlapi-defun (owlapi-is-defined-class)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-isDefinedClass| common-lisp-user::args))
(owlapi-defun (owlapi-is-consistent) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isConsistent| common-lisp-user::args))
(owlapi-defun (owlapi-is-classified) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isClassified| common-lisp-user::args))
(owlapi-defun (owlapi-is-class) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isClass| common-lisp-user::args))
(owlapi-defun (owlapi-is-asymmetric) (&rest common-lisp-user::args)
(apply #'|OWLAPI-isAsymmetric| common-lisp-user::args))
(owlapi-defun (owlapi-init) (&rest common-lisp-user::args)
(apply #'|OWLAPI-init| common-lisp-user::args))
(owlapi-defun (owlapi-ignore-declarations)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-ignoreDeclarations| common-lisp-user::args))
(owlapi-defun (owlapi-ignore-annotations)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-ignoreAnnotations| common-lisp-user::args))
(owlapi-defun (owlapi-has-type) (&rest common-lisp-user::args)
(apply #'|OWLAPI-hasType| common-lisp-user::args))
(owlapi-defun (owlapi-has-object-property-relationship)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-hasObjectPropertyRelationship|
common-lisp-user::args))
(owlapi-defun (owlapi-has-data-property-relationship)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-hasDataPropertyRelationship|
common-lisp-user::args))
(owlapi-defun (owlapi-get-types) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getTypes| common-lisp-user::args))
(owlapi-defun (owlapi-get-super-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getSuperProperties| common-lisp-user::args))
(owlapi-defun (owlapi-get-super-classes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getSuperClasses| common-lisp-user::args))
(owlapi-defun (owlapi-get-sub-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getSubProperties| common-lisp-user::args))
(owlapi-defun (owlapi-get-sub-classes) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getSubClasses| common-lisp-user::args))
(owlapi-defun (owlapi-get-same-individuals)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getSameIndividuals| common-lisp-user::args))
(owlapi-defun (owlapi-get-related-values)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getRelatedValues| common-lisp-user::args))
(owlapi-defun (owlapi-get-related-individuals)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getRelatedIndividuals| common-lisp-user::args))
(owlapi-defun (owlapi-get-reasoners) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getReasoners| common-lisp-user::args))
(owlapi-defun (owlapi-get-ranges) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getRanges| common-lisp-user::args))
(owlapi-defun (owlapi-get-prefixes) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getPrefixes| common-lisp-user::args))
(owlapi-defun (owlapi-get-ontologies) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-get-object-property-values)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getObjectPropertyValues| common-lisp-user::args))
(owlapi-defun (owlapi-get-object-property-relationships)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getObjectPropertyRelationships|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-transitive-object-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLTransitiveObjectPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-symmetric-object-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLSymmetricObjectPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-sub-class-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLSubClassAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-sub-annotation-property-of-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLSubAnnotationPropertyOfAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-sub-annotation-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLSubAnnotationPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-same-individuals-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLSameIndividualsAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-reflexive-object-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLReflexiveObjectPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-really-implicit-declaration-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLReallyImplicitDeclarationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-prefix-declaration-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLPrefixDeclarationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-ontology-version-declaration-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLOntologyVersionDeclarationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-ontology-annotation-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLOntologyAnnotationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-object-sub-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLObjectSubPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-object-property-range-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLObjectPropertyRangeAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-object-property-domain-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLObjectPropertyDomainAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-object-property-chain-sub-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLObjectPropertyChainSubPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-object-property-assertion-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLObjectPropertyAssertionAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-negative-object-property-assertion-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLNegativeObjectPropertyAssertionAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-negative-data-property-assertion-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLNegativeDataPropertyAssertionAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-irreflexive-object-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLIrreflexiveObjectPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-inverse-object-properties-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLInverseObjectPropertiesAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-inverse-functional-object-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLInverseFunctionalObjectPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-imports-declaration-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLImportsDeclarationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-implicit-declaration-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLImplicitDeclarationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-has-key-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLHasKeyAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-functional-object-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLFunctionalObjectPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-functional-data-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLFunctionalDataPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-equivalent-object-properties-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLEquivalentObjectPropertiesAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-equivalent-data-properties-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLEquivalentDataPropertiesAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-equivalent-classes-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLEquivalentClassesAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-entity-annotation-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLEntityAnnotationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-disjoint-union-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDisjointUnionAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-disjoint-object-properties-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDisjointObjectPropertiesAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-disjoint-data-properties-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDisjointDataPropertiesAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-disjoint-classes-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDisjointClassesAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-different-individuals-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDifferentIndividualsAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-declaration-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDeclarationAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-datatype-definition-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDatatypeDefinitionAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-data-sub-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDataSubPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-data-property-range-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDataPropertyRangeAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-data-property-domain-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDataPropertyDomainAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-data-property-assertion-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLDataPropertyAssertionAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-class-assertion-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLClassAssertionAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-axiom-annotation-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLAxiomAnnotationAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-asymmetric-object-property-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLAsymmetricObjectPropertyAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-annotation-property-range-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLAnnotationPropertyRangeAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-annotation-property-domain-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLAnnotationPropertyDomainAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-owl-annotation-assertion-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getOWLAnnotationAssertionAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-loaded-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getLoadedOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-get-inverse-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getInverseProperties| common-lisp-user::args))
(owlapi-defun (owlapi-get-instances) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getInstances| common-lisp-user::args))
(owlapi-defun (owlapi-get-individuals) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getIndividuals| common-lisp-user::args))
(owlapi-defun (owlapi-get-inconsistent-classes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getInconsistentClasses| common-lisp-user::args))
(owlapi-defun (owlapi-get-equivalent-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getEquivalentProperties| common-lisp-user::args))
(owlapi-defun (owlapi-get-equivalent-classes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getEquivalentClasses| common-lisp-user::args))
(owlapi-defun (owlapi-get-domains) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getDomains| common-lisp-user::args))
(owlapi-defun (owlapi-get-disjoint-object-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDisjointObjectProperties|
common-lisp-user::args))
(owlapi-defun (owlapi-get-disjoint-data-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDisjointDataProperties|
common-lisp-user::args))
(owlapi-defun (owlapi-get-disjoint-classes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDisjointClasses| common-lisp-user::args))
(owlapi-defun (owlapi-get-different-individuals)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDifferentIndividuals| common-lisp-user::args))
(owlapi-defun (owlapi-get-descendant-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDescendantProperties| common-lisp-user::args))
(owlapi-defun (owlapi-get-descendant-classes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDescendantClasses| common-lisp-user::args))
(owlapi-defun (owlapi-get-data-property-values)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDataPropertyValues| common-lisp-user::args))
(owlapi-defun (owlapi-get-data-property-relationships)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getDataPropertyRelationships|
common-lisp-user::args))
(owlapi-defun (owlapi-get-current-reasoner)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getCurrentReasoner| common-lisp-user::args))
(owlapi-defun (owlapi-get-changes) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getChanges| common-lisp-user::args))
(owlapi-defun (owlapi-get-axioms-per-ontology)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAxiomsPerOntology| common-lisp-user::args))
(owlapi-defun (owlapi-get-axioms-of-type-in)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAxiomsOfTypeIn| common-lisp-user::args))
(owlapi-defun (owlapi-get-axioms-of-type)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAxiomsOfType| common-lisp-user::args))
(owlapi-defun (owlapi-get-axioms-in) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getAxiomsIn| common-lisp-user::args))
(owlapi-defun (owlapi-get-axioms) (&rest common-lisp-user::args)
(apply #'|OWLAPI-getAxioms| common-lisp-user::args))
(owlapi-defun (owlapi-get-axiom-counter)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAxiomCounter| common-lisp-user::args))
(owlapi-defun (owlapi-get-auto-ontology)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAutoOntology| common-lisp-user::args))
(owlapi-defun (owlapi-get-auto-declare-data-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAutoDeclareDataProperties|
common-lisp-user::args))
(owlapi-defun (owlapi-get-annotation-axioms-for-axiom)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAnnotationAxiomsForAxiom|
common-lisp-user::args))
(owlapi-defun (owlapi-get-ancestor-properties)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAncestorProperties| common-lisp-user::args))
(owlapi-defun (owlapi-get-ancestor-classes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAncestorClasses| common-lisp-user::args))
(owlapi-defun (owlapi-get-all-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-getAllOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-find-object-from-id)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-findObjectFromID| common-lisp-user::args))
(owlapi-defun (owlapi-find-id-from-object)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-findIDFromObject| common-lisp-user::args))
(owlapi-defun (owlapi-export-reasoner) (&rest common-lisp-user::args)
(apply #'|OWLAPI-exportReasoner| common-lisp-user::args))
(owlapi-defun (owlapi-export-ontology) (&rest common-lisp-user::args)
(apply #'|OWLAPI-exportOntology| common-lisp-user::args))
(owlapi-defun (owlapi-enable-transient-axiom-mode)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-enableTransientAxiomMode| common-lisp-user::args))
(owlapi-defun (owlapi-enable-simplified-protocol)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-enableSimplifiedProtocol| common-lisp-user::args))
(owlapi-defun (owlapi-enable-memory-saving-mode)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-enableMemorySavingMode| common-lisp-user::args))
(owlapi-defun (owlapi-enable-lookup-mode)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-enableLookupMode| common-lisp-user::args))
(owlapi-defun (owlapi-enable-incremental-updates)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-enableIncrementalUpdates| common-lisp-user::args))
(owlapi-defun (owlapi-dont-register-referenced-entities)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-dontRegisterReferencedEntities|
common-lisp-user::args))
(owlapi-defun (owlapi-dont-register-declared-entities)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-dontRegisterDeclaredEntities|
common-lisp-user::args))
(owlapi-defun (owlapi-dispose-reasoner)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disposeReasoner| common-lisp-user::args))
(owlapi-defun (owlapi-dispose-ontology)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disposeOntology| common-lisp-user::args))
(owlapi-defun (owlapi-dispose-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disposeOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-dispose-axioms) (&rest common-lisp-user::args)
(apply #'|OWLAPI-disposeAxioms| common-lisp-user::args))
(owlapi-defun (owlapi-dispose-axiom) (&rest common-lisp-user::args)
(apply #'|OWLAPI-disposeAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-dispose) (&rest common-lisp-user::args)
(apply #'|OWLAPI-dispose| common-lisp-user::args))
(owlapi-defun (owlapi-disable-transient-axiom-mode)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disableTransientAxiomMode|
common-lisp-user::args))
(owlapi-defun (owlapi-disable-simplified-protocol)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disableSimplifiedProtocol|
common-lisp-user::args))
(owlapi-defun (owlapi-disable-memory-saving-mode)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disableMemorySavingMode| common-lisp-user::args))
(owlapi-defun (owlapi-disable-lookup-mode)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disableLookupMode| common-lisp-user::args))
(owlapi-defun (owlapi-disable-incremental-updates)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disableIncrementalUpdates|
common-lisp-user::args))
(owlapi-defun (owlapi-disable-auto-mode)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-disableAutoMode| common-lisp-user::args))
(owlapi-defun (owlapi-describe-reasoners)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-describeReasoners| common-lisp-user::args))
(owlapi-defun (owlapi-describe-reasoner)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-describeReasoner| common-lisp-user::args))
(owlapi-defun (owlapi-describe-ontology)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-describeOntology| common-lisp-user::args))
(owlapi-defun (owlapi-describe-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-describeOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-contains) (&rest common-lisp-user::args)
(apply #'|OWLAPI-contains| common-lisp-user::args))
(owlapi-defun (owlapi-consider-declarations)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-considerDeclarations| common-lisp-user::args))
(owlapi-defun (owlapi-clear-registry) (&rest common-lisp-user::args)
(apply #'|OWLAPI-clearRegistry| common-lisp-user::args))
(owlapi-defun (owlapi-clear-ontologies)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-clearOntologies| common-lisp-user::args))
(owlapi-defun (owlapi-clear-changes) (&rest common-lisp-user::args)
(apply #'|OWLAPI-clearChanges| common-lisp-user::args))
(owlapi-defun (owlapi-classify) (&rest common-lisp-user::args)
(apply #'|OWLAPI-classify| common-lisp-user::args))
(owlapi-defun (owlapi-batch-synchronize)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-batchSynchronize| common-lisp-user::args))
(owlapi-defun (owlapi-auto-remove-axioms-from)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-autoRemoveAxiomsFrom| common-lisp-user::args))
(owlapi-defun (owlapi-auto-batch-remove-axioms-from)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-autoBatchRemoveAxiomsFrom|
common-lisp-user::args))
(owlapi-defun (owlapi-auto-batch-add-axioms-to)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-autoBatchAddAxiomsTo| common-lisp-user::args))
(owlapi-defun (owlapi-auto-apply-changes)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-autoApplyChanges| common-lisp-user::args))
(owlapi-defun (owlapi-auto-add-axioms-to)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-autoAddAxiomsTo| common-lisp-user::args))
(owlapi-defun (owlapi-apply-changes) (&rest common-lisp-user::args)
(apply #'|OWLAPI-applyChanges| common-lisp-user::args))
(owlapi-defun (owlapi-advance-progress)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-advanceProgress| common-lisp-user::args))
(owlapi-defun (owlapi-add-prefix) (&rest common-lisp-user::args)
(apply #'|OWLAPI-addPrefix| common-lisp-user::args))
(owlapi-defun (owlapi-abort) (&rest common-lisp-user::args)
(apply #'|OWLAPI-abort| common-lisp-user::args))
(owlapi-defun (owlapi-set-ontology-uri)
(&rest common-lisp-user::args)
(apply #'|OWLAPI-SetOntologyURI| common-lisp-user::args))
(owlapi-defun (owlapi-remove-axioms) (&rest common-lisp-user::args)
(apply #'|OWLAPI-RemoveAxioms| common-lisp-user::args))
(owlapi-defun (owlapi-remove-axiom) (&rest common-lisp-user::args)
(apply #'|OWLAPI-RemoveAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-id-to-axiom) (&rest common-lisp-user::args)
(apply #'|OWLAPI-IDToAxiom| common-lisp-user::args))
(owlapi-defun (owlapi-axiom-to-id) (&rest common-lisp-user::args)
(apply #'|OWLAPI-AxiomToID| common-lisp-user::args))
(owlapi-defun (owlapi-axiom-loaded?) (&rest common-lisp-user::args)
(apply #'|OWLAPI-AxiomLoaded?| common-lisp-user::args))
(owlapi-defun (owlapi-add-axioms) (&rest common-lisp-user::args)
(apply #'|OWLAPI-AddAxioms| common-lisp-user::args))
(owlapi-defun (owlapi-add-axiom) (&rest common-lisp-user::args)
(apply #'|OWLAPI-AddAxiom| common-lisp-user::args))) |
b2ca53a36723f38e67513bdc9d5d92ce35482d52f6e9c4d964205d7598fd4bbb | well-typed/generics-sop | SOP.hs | # LANGUAGE PolyKinds , UndecidableInstances #
# OPTIONS_GHC -fno - warn - unused - binds #
| Main module of @sop - core@
module Data.SOP (
-- * n-ary datatypes
NP(..)
, NS(..)
, SOP(..)
, unSOP
, POP(..)
, unPOP
-- * Combinators
-- ** Constructing products
, HPure(..)
* * products
, hd
, tl
, Projection
, projections
, shiftProjection
-- ** Application
, type (-.->)(..)
, fn
, fn_2
, fn_3
, fn_4
, Prod
, HAp(..)
-- ** Lifting / mapping
, hliftA
, hliftA2
, hliftA3
, hcliftA
, hcliftA2
, hcliftA3
, hmap
, hzipWith
, hzipWith3
, hcmap
, hczipWith
, hczipWith3
-- ** Constructing sums
, Injection
, injections
, shift
, shiftInjection
, UnProd
, HApInjs(..)
, apInjs_NP -- deprecated export
, apInjs_POP -- deprecated export
* *
, unZ
, HIndex(..)
* * Dealing with @'All ' c@
, hcliftA'
, hcliftA2'
, hcliftA3'
-- ** Comparison
, compare_NS
, ccompare_NS
, compare_SOP
, ccompare_SOP
-- ** Collapsing
, CollapseTo
, HCollapse(..)
-- ** Folding and sequencing
, HTraverse_(..)
, hcfoldMap
, hcfor_
, HSequence(..)
, hsequence
, hsequenceK
, hctraverse
, hcfor
-- ** Expanding sums to products
, HExpand(..)
-- ** Transformation of index lists and coercions
, HTrans(..)
, hfromI
, htoI
-- ** Partial operations
, fromList
-- * Utilities
-- ** Basic functors
, K(..)
, unK
, I(..)
, unI
, (:.:)(..)
, unComp
-- *** Mapping functions
, mapII
, mapIK
, mapKI
, mapKK
, mapIII
, mapIIK
, mapIKI
, mapIKK
, mapKII
, mapKIK
, mapKKI
, mapKKK
-- ** Mapping constraints
, All
, All2
, cpara_SList
, ccase_SList
, AllZip
, AllZip2
, AllN
, AllZipN
-- ** Other constraints
, Compose
, And
, Top
, LiftedCoercible
, SameShapeAs
-- ** Singletons
, SList(..)
, SListI
, SListI2
, sList
, para_SList
, case_SList
-- *** Shape of type-level lists
, Shape(..)
, shape
, lengthSList
-- ** Re-exports
Workaround for lack of MIN_TOOL_VERSION macro in Cabal 1.18 , see :
-- -typed/generics-sop/issues/3
#ifndef MIN_TOOL_VERSION_haddock
#define MIN_TOOL_VERSION_haddock(x,y,z) 0
#endif
#if !(defined(__HADDOCK_VERSION__)) || MIN_TOOL_VERSION_haddock(2,14,0)
hidden from old versions , because it triggers an internal error
#endif
) where
import Data.Proxy (Proxy(..))
import Data.SOP.BasicFunctors
import Data.SOP.Classes
import Data.SOP.Constraint
import Data.SOP.NP
import Data.SOP.NS
import Data.SOP.Sing
| null | https://raw.githubusercontent.com/well-typed/generics-sop/39a3badb10e11efc4f907db557f998412ffc1b2a/sop-core/src/Data/SOP.hs | haskell | * n-ary datatypes
* Combinators
** Constructing products
** Application
** Lifting / mapping
** Constructing sums
deprecated export
deprecated export
** Comparison
** Collapsing
** Folding and sequencing
** Expanding sums to products
** Transformation of index lists and coercions
** Partial operations
* Utilities
** Basic functors
*** Mapping functions
** Mapping constraints
** Other constraints
** Singletons
*** Shape of type-level lists
** Re-exports
-typed/generics-sop/issues/3 | # LANGUAGE PolyKinds , UndecidableInstances #
# OPTIONS_GHC -fno - warn - unused - binds #
| Main module of @sop - core@
module Data.SOP (
NP(..)
, NS(..)
, SOP(..)
, unSOP
, POP(..)
, unPOP
, HPure(..)
* * products
, hd
, tl
, Projection
, projections
, shiftProjection
, type (-.->)(..)
, fn
, fn_2
, fn_3
, fn_4
, Prod
, HAp(..)
, hliftA
, hliftA2
, hliftA3
, hcliftA
, hcliftA2
, hcliftA3
, hmap
, hzipWith
, hzipWith3
, hcmap
, hczipWith
, hczipWith3
, Injection
, injections
, shift
, shiftInjection
, UnProd
, HApInjs(..)
* *
, unZ
, HIndex(..)
* * Dealing with @'All ' c@
, hcliftA'
, hcliftA2'
, hcliftA3'
, compare_NS
, ccompare_NS
, compare_SOP
, ccompare_SOP
, CollapseTo
, HCollapse(..)
, HTraverse_(..)
, hcfoldMap
, hcfor_
, HSequence(..)
, hsequence
, hsequenceK
, hctraverse
, hcfor
, HExpand(..)
, HTrans(..)
, hfromI
, htoI
, fromList
, K(..)
, unK
, I(..)
, unI
, (:.:)(..)
, unComp
, mapII
, mapIK
, mapKI
, mapKK
, mapIII
, mapIIK
, mapIKI
, mapIKK
, mapKII
, mapKIK
, mapKKI
, mapKKK
, All
, All2
, cpara_SList
, ccase_SList
, AllZip
, AllZip2
, AllN
, AllZipN
, Compose
, And
, Top
, LiftedCoercible
, SameShapeAs
, SList(..)
, SListI
, SListI2
, sList
, para_SList
, case_SList
, Shape(..)
, shape
, lengthSList
Workaround for lack of MIN_TOOL_VERSION macro in Cabal 1.18 , see :
#ifndef MIN_TOOL_VERSION_haddock
#define MIN_TOOL_VERSION_haddock(x,y,z) 0
#endif
#if !(defined(__HADDOCK_VERSION__)) || MIN_TOOL_VERSION_haddock(2,14,0)
hidden from old versions , because it triggers an internal error
#endif
) where
import Data.Proxy (Proxy(..))
import Data.SOP.BasicFunctors
import Data.SOP.Classes
import Data.SOP.Constraint
import Data.SOP.NP
import Data.SOP.NS
import Data.SOP.Sing
|
530681e8930da7272beb91f65ee2c473e62c8027b9bcba1b6e730d366ba2c70f | exoscale/pithos | system.clj | (ns io.pithos.system)
(defprotocol SystemDescriptor
(regions [this])
(bucketstore [this])
(keystore [this])
(reporters [this])
(service [this])
(service-uri [this]))
(defn system-descriptor
[config]
(reify
SystemDescriptor
(regions [this] (:regions config))
(bucketstore [this] (:bucketstore config))
(keystore [this] (:keystore config))
(reporters [this] (:reporters config))
(service [this] (:service config))
(service-uri [this] (get-in config [:options :service-uri]))
clojure.lang.ILookup
(valAt [this k] (get config k))
(valAt [this k default] (or (get config k) default))))
| null | https://raw.githubusercontent.com/exoscale/pithos/54790f00fbfd330c6196d42e5408385028d5e029/src/io/pithos/system.clj | clojure | (ns io.pithos.system)
(defprotocol SystemDescriptor
(regions [this])
(bucketstore [this])
(keystore [this])
(reporters [this])
(service [this])
(service-uri [this]))
(defn system-descriptor
[config]
(reify
SystemDescriptor
(regions [this] (:regions config))
(bucketstore [this] (:bucketstore config))
(keystore [this] (:keystore config))
(reporters [this] (:reporters config))
(service [this] (:service config))
(service-uri [this] (get-in config [:options :service-uri]))
clojure.lang.ILookup
(valAt [this k] (get config k))
(valAt [this k default] (or (get config k) default))))
| |
eb6f87e1159071b69b37593edbbccea4d2ffbc4e8d579d1233968b7a880c9e53 | brownplt/LambdaS5 | components.ml | (**************************************************************************)
(* *)
: a generic graph library for OCaml
Copyright ( C ) 2004 - 2010
, and
(* *)
(* This software is free software; you can redistribute it and/or *)
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
(* described in file LICENSE. *)
(* *)
(* This software 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. *)
(* *)
(**************************************************************************)
$ I d : components.ml , v 1.9 2004 - 10 - 22 14:42:06 signoles Exp $
open Util
module type G = sig
type t
module V : Sig.COMPARABLE
val iter_vertex : (V.t -> unit) -> t -> unit
val iter_succ : (V.t -> unit) -> t -> V.t -> unit
end
module Make(G: G) = struct
module H = Hashtbl.Make(G.V)
module S = Set.Make(G.V)
let scc g =
let root = H.create 997 in
let hashcomp = H.create 997 in
let stack = ref [] in
let numdfs = ref 0 in
let numcomp = ref 0 in
let rec pop x c = function
| (y, w) :: l when y > x ->
H.add hashcomp w !numcomp;
pop x (S.add w c) l
| l -> c,l
in
let rec visit v =
if not (H.mem root v) then
begin
let n = incr numdfs; !numdfs in
H.add root v n;
G.iter_succ
(fun w ->
visit w;
if not (H.mem hashcomp w) then
H.replace root v (min (H.find root v) (H.find root w)))
g v;
if H.find root v = n then
(H.add hashcomp v !numcomp;
let comp,s = pop n (S.add v S.empty) !stack in
stack:= s;
incr numcomp)
else stack := (n,v)::!stack;
end
in
G.iter_vertex visit g;
(!numcomp,(fun v -> H.find hashcomp v))
let scc_array g =
let n,f = scc g in
let t = Array.make n [] in
G.iter_vertex
(fun v -> let i = f v in t.(i) <- v::t.(i)) g;
t
let scc_list g =
let _,scc = scc g in
let tbl = Hashtbl.create 97 in
G.iter_vertex
(fun v ->
let n = scc v in
try
let l = Hashtbl.find tbl n in
l := v :: !l
with Not_found ->
Hashtbl.add tbl n (ref [ v ]))
g;
Hashtbl.fold (fun _ v l -> !v :: l) tbl []
end
| null | https://raw.githubusercontent.com/brownplt/LambdaS5/f0bf5c7baf1daa4ead4e398ba7d430bedb7de9cf/src/ocamlgraph-1.8.1/src/components.ml | ocaml | ************************************************************************
This software is free software; you can redistribute it and/or
described in file LICENSE.
This software 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.
************************************************************************ | : a generic graph library for OCaml
Copyright ( C ) 2004 - 2010
, and
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
$ I d : components.ml , v 1.9 2004 - 10 - 22 14:42:06 signoles Exp $
open Util
module type G = sig
type t
module V : Sig.COMPARABLE
val iter_vertex : (V.t -> unit) -> t -> unit
val iter_succ : (V.t -> unit) -> t -> V.t -> unit
end
module Make(G: G) = struct
module H = Hashtbl.Make(G.V)
module S = Set.Make(G.V)
let scc g =
let root = H.create 997 in
let hashcomp = H.create 997 in
let stack = ref [] in
let numdfs = ref 0 in
let numcomp = ref 0 in
let rec pop x c = function
| (y, w) :: l when y > x ->
H.add hashcomp w !numcomp;
pop x (S.add w c) l
| l -> c,l
in
let rec visit v =
if not (H.mem root v) then
begin
let n = incr numdfs; !numdfs in
H.add root v n;
G.iter_succ
(fun w ->
visit w;
if not (H.mem hashcomp w) then
H.replace root v (min (H.find root v) (H.find root w)))
g v;
if H.find root v = n then
(H.add hashcomp v !numcomp;
let comp,s = pop n (S.add v S.empty) !stack in
stack:= s;
incr numcomp)
else stack := (n,v)::!stack;
end
in
G.iter_vertex visit g;
(!numcomp,(fun v -> H.find hashcomp v))
let scc_array g =
let n,f = scc g in
let t = Array.make n [] in
G.iter_vertex
(fun v -> let i = f v in t.(i) <- v::t.(i)) g;
t
let scc_list g =
let _,scc = scc g in
let tbl = Hashtbl.create 97 in
G.iter_vertex
(fun v ->
let n = scc v in
try
let l = Hashtbl.find tbl n in
l := v :: !l
with Not_found ->
Hashtbl.add tbl n (ref [ v ]))
g;
Hashtbl.fold (fun _ v l -> !v :: l) tbl []
end
|
5c0050656c78ee48e63794fab8dcdd3adda16f238f126fa5b93e0b26ed2bf338 | input-output-hk/ouroboros-network | TestEnv.hs | {-# LANGUAGE LambdaCase #-}
# LANGUAGE RecordWildCards #
| A @tasty@ command - line option for enabling nightly tests
module Test.Util.TestEnv (
TestEnv (..)
, askTestEnv
, defaultMainWithTestEnv
, defaultTestEnvConfig
) where
import Data.Proxy (Proxy (..))
import Options.Applicative (metavar)
import Test.Tasty
import Test.Tasty.Ingredients
import Test.Tasty.Options
import Test.Tasty.QuickCheck
-- | 'defaultMain' extended with 'iohkTestEnvIngredient'
defaultMainWithTestEnv :: TestEnvConfig -> TestTree -> IO ()
defaultMainWithTestEnv testConfig testTree =
defaultMainWithIngredients (testEnvIngredient : defaultIngredients) $ withTestEnv testConfig testTree
where
testEnvIngredient :: Ingredient
testEnvIngredient = includingOptions [Option (Proxy :: Proxy TestEnv)]
-- | Set the appropriate options for the test environment
withTestEnv :: TestEnvConfig -> TestTree -> TestTree
withTestEnv TestEnvConfig{..} testTree = askOption $ \case
Nightly -> localOption (QuickCheckTests nightly) testTree
CI -> localOption (QuickCheckTests ci) testTree
Dev -> localOption (QuickCheckTests dev) testTree
| Query and adjust options for ` TestEnv `
askTestEnv :: (TestEnv -> TestTree) -> TestTree
askTestEnv = askOption
-- | Test configurations for test environment
data TestEnvConfig = TestEnvConfig { nightly :: Int, ci :: Int, dev :: Int }
-- | Default set of tests for each environment
defaultTestEnvConfig :: TestEnvConfig
defaultTestEnvConfig = TestEnvConfig { nightly = 100000, ci = 10000, dev = 100 }
-- | An 'Option' that indicates the environment in which to run tests.
data TestEnv = Nightly | CI | Dev
safeReadTestEnv :: String -> Maybe TestEnv
safeReadTestEnv "nightly" = Just Nightly
safeReadTestEnv "ci" = Just CI
safeReadTestEnv "dev" = Just Dev
safeReadTestEnv _ = Nothing
instance IsOption TestEnv where
defaultValue = Dev
parseValue = safeReadTestEnv
optionName = pure "test-env"
optionHelp = pure "Enable a test mode. \
\ The 'dev' env sets the default number of quickcheck tests to 100, \
\ 'nightly' env sets it to 100_000 quickcheck tests, and \
\ 'ci' env sets it to 10_000 quickcheck tests. \
\ Individual tests are adjusted to run a number of tests proportional to the value above depending \
\ on the time it takes to run them."
-- Set of choices for test environment
optionCLParser = mkOptionCLParser $ metavar "nightly|ci|dev"
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/31f2d871d2655b48a81c69f0f7365c08e10eb0df/ouroboros-consensus-test/src/Test/Util/TestEnv.hs | haskell | # LANGUAGE LambdaCase #
| 'defaultMain' extended with 'iohkTestEnvIngredient'
| Set the appropriate options for the test environment
| Test configurations for test environment
| Default set of tests for each environment
| An 'Option' that indicates the environment in which to run tests.
Set of choices for test environment | # LANGUAGE RecordWildCards #
| A @tasty@ command - line option for enabling nightly tests
module Test.Util.TestEnv (
TestEnv (..)
, askTestEnv
, defaultMainWithTestEnv
, defaultTestEnvConfig
) where
import Data.Proxy (Proxy (..))
import Options.Applicative (metavar)
import Test.Tasty
import Test.Tasty.Ingredients
import Test.Tasty.Options
import Test.Tasty.QuickCheck
defaultMainWithTestEnv :: TestEnvConfig -> TestTree -> IO ()
defaultMainWithTestEnv testConfig testTree =
defaultMainWithIngredients (testEnvIngredient : defaultIngredients) $ withTestEnv testConfig testTree
where
testEnvIngredient :: Ingredient
testEnvIngredient = includingOptions [Option (Proxy :: Proxy TestEnv)]
withTestEnv :: TestEnvConfig -> TestTree -> TestTree
withTestEnv TestEnvConfig{..} testTree = askOption $ \case
Nightly -> localOption (QuickCheckTests nightly) testTree
CI -> localOption (QuickCheckTests ci) testTree
Dev -> localOption (QuickCheckTests dev) testTree
| Query and adjust options for ` TestEnv `
askTestEnv :: (TestEnv -> TestTree) -> TestTree
askTestEnv = askOption
data TestEnvConfig = TestEnvConfig { nightly :: Int, ci :: Int, dev :: Int }
defaultTestEnvConfig :: TestEnvConfig
defaultTestEnvConfig = TestEnvConfig { nightly = 100000, ci = 10000, dev = 100 }
data TestEnv = Nightly | CI | Dev
safeReadTestEnv :: String -> Maybe TestEnv
safeReadTestEnv "nightly" = Just Nightly
safeReadTestEnv "ci" = Just CI
safeReadTestEnv "dev" = Just Dev
safeReadTestEnv _ = Nothing
instance IsOption TestEnv where
defaultValue = Dev
parseValue = safeReadTestEnv
optionName = pure "test-env"
optionHelp = pure "Enable a test mode. \
\ The 'dev' env sets the default number of quickcheck tests to 100, \
\ 'nightly' env sets it to 100_000 quickcheck tests, and \
\ 'ci' env sets it to 10_000 quickcheck tests. \
\ Individual tests are adjusted to run a number of tests proportional to the value above depending \
\ on the time it takes to run them."
optionCLParser = mkOptionCLParser $ metavar "nightly|ci|dev"
|
7ff19b7185cb9fb572dfb96b323caab9e2814c76391d13427a7b45898bbf79fa | manuel-serrano/hop | source_map.scm | ;*=====================================================================*/
* serrano / prgm / project / hop/3.0.x / scheme2js / source_map.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Fri Jul 26 17:18:45 2013 * /
* Last change : Fri Jul 11 09:17:57 2014 ( serrano ) * /
* Copyright : 2013 - 14 * /
;* ------------------------------------------------------------- */
;* JavaScript source map generation */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module source-map
(import config
nodes
dump-node
srfi0
export-desc
module-system
walk
allocate-names
base64-vlq)
(export (generate-source-map ::Module ::bstring ::bstring ::output-port)))
;*---------------------------------------------------------------------*/
;* source-map-version ... */
;*---------------------------------------------------------------------*/
(define (source-map-version) 3)
;*---------------------------------------------------------------------*/
;* generate-source-map ... */
;*---------------------------------------------------------------------*/
(define (generate-source-map tree in-file out-file p)
(with-handler
(lambda (e)
(exception-notify e)
#f)
(let ((nametable (make-hashtable))
(sourcetable (make-hashtable 4)))
(display "{\n" p)
(fprintf p " \"version\": ~a,\n" (source-map-version))
(fprintf p " \"file\": \"~a\",\n" in-file)
(display " \"mappings\": \"" p)
(generate-source-map-mappings tree nametable sourcetable in-file out-file p)
(display "\",\n" p)
(display " \"sources\": " p)
(generate-source-map-names sourcetable p)
(display ",\n" p)
(display " \"names\": " p)
(generate-source-map-names nametable p)
(display "\n}\n" p)
(hashtable-map sourcetable (lambda (k v) k)))))
;*---------------------------------------------------------------------*/
;* generate-source-map-mappings ... */
;*---------------------------------------------------------------------*/
(define (generate-source-map-mappings tree::Module
nametable sourcetable
src-file::bstring dst-file::bstring
p::output-port)
(let ((res (cons #f '())))
;; generate the segments fro the ast
(segments tree #f res nametable sourcetable)
(let ((segs (sort (lambda (s1 s2) (<fx (car s1) (car s2))) (cdr res)))
(src-linetables (make-vector (hashtable-size sourcetable)))
(dst-linetable (load-file-line-table dst-file)))
;; feed the source file lines table
(hashtable-for-each sourcetable
(lambda (k v)
(vector-set! src-linetables v (load-file-line-table k))))
(let ((pdstline 0)
(pdstcol 0)
(psrcline 0)
(psrccol 0)
(pnindex 0)
(pfindex 0))
(let loop ((segs segs)
(pseg #f))
(when (pair? segs)
(let* ((seg (car segs))
(pos (car seg))
(loc (cadr seg))
(file (hashtable-get sourcetable (cadr loc)))
(src-linetable (vector-ref src-linetables file)))
(multiple-value-bind (dstline dstbeg dstend)
(linetable-find dst-linetable pdstline pos dst-file)
(multiple-value-bind (srcline srcbeg srcend)
(linetable-find src-linetable psrcline (caddr loc) src-file)
(let ((srccol (-fx (caddr loc) srcbeg))
(dstcol (-fx pos dstbeg)))
1 . zero - based starting colum
(if (or (not pseg) (>fx dstline pdstline))
(begin
;; write as many semi-coma as we have skipped lines
(when (>fx dstline pdstline)
(display (make-string (-fx dstline pdstline) #\;) p)
(set! pdstline dstline))
(display (base64-vlq-encode dstcol) p)
reset the dst colume counter
(set! pdstcol dstcol))
(begin
(display "," p)
(display (base64-vlq-encode (-fx dstcol pdstcol)) p)
(set! pdstcol dstcol)))
2 . zero - based index into the sources list
(let* ((path (cadr loc))
(findex (hashtable-get sourcetable path)))
(display (base64-vlq-encode (-fx findex pfindex)) p)
(set! pfindex findex))
3 . zero - based staring line in the src
(display (base64-vlq-encode (-fx srcline psrcline)) p)
(set! psrcline srcline)
4 . zero - based starting colum of the line
(display (base64-vlq-encode (-fx srccol psrccol)) p)
(set! psrccol srccol)
5 . the names
(when (pair? (cddr seg))
(let* ((name (caddr seg))
(nindex (hashtable-get nametable name)))
(display (base64-vlq-encode (-fx nindex pnindex)) p)
(set! pnindex nindex)))
(let* ((file (cadr loc))
(findex (hashtable-get sourcetable file)))
(loop (cdr segs) (car segs)))))))))))))
;*---------------------------------------------------------------------*/
;* linetable-find ... */
;* ------------------------------------------------------------- */
;* Find the line containing the position. Returns the line number */
;* and the column number. */
;*---------------------------------------------------------------------*/
(define (linetable-find table fromline pos file)
(let ((len (vector-length table)))
(let loop ((i fromline))
(if (<fx i len)
(let* ((line (vector-ref table i))
(b (car line))
(e (cdr line)))
(cond
((<fx pos b)
(linetable-find table 0 pos file))
((>=fx e pos)
(values i b e))
(else
(loop (+fx i 1)))))
(linetable-find table 0 pos file)))))
;*---------------------------------------------------------------------*/
;* segments ::Node ... */
;*---------------------------------------------------------------------*/
(define-nmethod (Node.segments res nametable sourcetable)
(with-access::Node this (dstposition location)
(when (and dstposition location)
(let ((segment (list dstposition location)))
(set-cdr! res (cons segment (cdr res))))
(let* ((file (cadr location))
(f (hashtable-get sourcetable (cadr location))))
(unless f
(let ((n (hashtable-size sourcetable)))
(hashtable-put! sourcetable file n)))))
(default-walk this res nametable sourcetable)))
;*---------------------------------------------------------------------*/
;* segments ::Ref ... */
;*---------------------------------------------------------------------*/
(define-nmethod (Ref.segments res nametable sourcetable)
(with-access::Ref this (var dstposition location)
(with-access::Var var (id)
(when (and dstposition location)
(let ((segment (list dstposition location id)))
(set-cdr! res (cons segment (cdr res))))
(let* ((file (cadr location))
(f (hashtable-get sourcetable (cadr location))))
(unless f
(let ((n (hashtable-size sourcetable)))
(hashtable-put! sourcetable file n)))))
(let ((o (hashtable-get nametable id)))
(unless o
(let ((n (hashtable-size nametable)))
(hashtable-put! nametable id n)))))))
;*---------------------------------------------------------------------*/
;* generate-source-map-names ... */
;*---------------------------------------------------------------------*/
(define (generate-source-map-names nametable p::output-port)
(display "[" p)
(let ((names (sort (lambda (e1 e2) (<fx (cdr e1) (cdr e2)))
(hashtable-map nametable cons) )))
(if (null? names)
(display "]" p)
(let loop ((names names))
(if (null? (cdr names))
(begin
(display "\"" p)
(display (caar names) p)
(display "\"]" p))
(begin
(display "\"" p)
(display (caar names) p)
(display "\"," p)
(loop (cdr names))))))))
;*---------------------------------------------------------------------*/
;* load-file-line-table ... */
;* ------------------------------------------------------------- */
;* Read all the lines of a file and store the start indices */
;* in a table. */
;*---------------------------------------------------------------------*/
(define (load-file-line-table file::bstring)
(call-with-input-file file
(lambda (p)
(let loop ((lines '())
(i 0))
(let ((line (read-line p)))
(if (eof-object? line)
(list->vector (reverse! lines))
(let ((j (input-port-position p)))
(loop (cons (cons i j) lines) j))))))))
| null | https://raw.githubusercontent.com/manuel-serrano/hop/481cb10478286796addd2ec9ee29c95db27aa390/scheme2js/source_map.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* JavaScript source map generation */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* source-map-version ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* generate-source-map ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* generate-source-map-mappings ... */
*---------------------------------------------------------------------*/
generate the segments fro the ast
feed the source file lines table
write as many semi-coma as we have skipped lines
) p)
*---------------------------------------------------------------------*/
* linetable-find ... */
* ------------------------------------------------------------- */
* Find the line containing the position. Returns the line number */
* and the column number. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* segments ::Node ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* segments ::Ref ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* generate-source-map-names ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* load-file-line-table ... */
* ------------------------------------------------------------- */
* Read all the lines of a file and store the start indices */
* in a table. */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / hop/3.0.x / scheme2js / source_map.scm * /
* Author : * /
* Creation : Fri Jul 26 17:18:45 2013 * /
* Last change : Fri Jul 11 09:17:57 2014 ( serrano ) * /
* Copyright : 2013 - 14 * /
(module source-map
(import config
nodes
dump-node
srfi0
export-desc
module-system
walk
allocate-names
base64-vlq)
(export (generate-source-map ::Module ::bstring ::bstring ::output-port)))
(define (source-map-version) 3)
(define (generate-source-map tree in-file out-file p)
(with-handler
(lambda (e)
(exception-notify e)
#f)
(let ((nametable (make-hashtable))
(sourcetable (make-hashtable 4)))
(display "{\n" p)
(fprintf p " \"version\": ~a,\n" (source-map-version))
(fprintf p " \"file\": \"~a\",\n" in-file)
(display " \"mappings\": \"" p)
(generate-source-map-mappings tree nametable sourcetable in-file out-file p)
(display "\",\n" p)
(display " \"sources\": " p)
(generate-source-map-names sourcetable p)
(display ",\n" p)
(display " \"names\": " p)
(generate-source-map-names nametable p)
(display "\n}\n" p)
(hashtable-map sourcetable (lambda (k v) k)))))
(define (generate-source-map-mappings tree::Module
nametable sourcetable
src-file::bstring dst-file::bstring
p::output-port)
(let ((res (cons #f '())))
(segments tree #f res nametable sourcetable)
(let ((segs (sort (lambda (s1 s2) (<fx (car s1) (car s2))) (cdr res)))
(src-linetables (make-vector (hashtable-size sourcetable)))
(dst-linetable (load-file-line-table dst-file)))
(hashtable-for-each sourcetable
(lambda (k v)
(vector-set! src-linetables v (load-file-line-table k))))
(let ((pdstline 0)
(pdstcol 0)
(psrcline 0)
(psrccol 0)
(pnindex 0)
(pfindex 0))
(let loop ((segs segs)
(pseg #f))
(when (pair? segs)
(let* ((seg (car segs))
(pos (car seg))
(loc (cadr seg))
(file (hashtable-get sourcetable (cadr loc)))
(src-linetable (vector-ref src-linetables file)))
(multiple-value-bind (dstline dstbeg dstend)
(linetable-find dst-linetable pdstline pos dst-file)
(multiple-value-bind (srcline srcbeg srcend)
(linetable-find src-linetable psrcline (caddr loc) src-file)
(let ((srccol (-fx (caddr loc) srcbeg))
(dstcol (-fx pos dstbeg)))
1 . zero - based starting colum
(if (or (not pseg) (>fx dstline pdstline))
(begin
(when (>fx dstline pdstline)
(set! pdstline dstline))
(display (base64-vlq-encode dstcol) p)
reset the dst colume counter
(set! pdstcol dstcol))
(begin
(display "," p)
(display (base64-vlq-encode (-fx dstcol pdstcol)) p)
(set! pdstcol dstcol)))
2 . zero - based index into the sources list
(let* ((path (cadr loc))
(findex (hashtable-get sourcetable path)))
(display (base64-vlq-encode (-fx findex pfindex)) p)
(set! pfindex findex))
3 . zero - based staring line in the src
(display (base64-vlq-encode (-fx srcline psrcline)) p)
(set! psrcline srcline)
4 . zero - based starting colum of the line
(display (base64-vlq-encode (-fx srccol psrccol)) p)
(set! psrccol srccol)
5 . the names
(when (pair? (cddr seg))
(let* ((name (caddr seg))
(nindex (hashtable-get nametable name)))
(display (base64-vlq-encode (-fx nindex pnindex)) p)
(set! pnindex nindex)))
(let* ((file (cadr loc))
(findex (hashtable-get sourcetable file)))
(loop (cdr segs) (car segs)))))))))))))
(define (linetable-find table fromline pos file)
(let ((len (vector-length table)))
(let loop ((i fromline))
(if (<fx i len)
(let* ((line (vector-ref table i))
(b (car line))
(e (cdr line)))
(cond
((<fx pos b)
(linetable-find table 0 pos file))
((>=fx e pos)
(values i b e))
(else
(loop (+fx i 1)))))
(linetable-find table 0 pos file)))))
(define-nmethod (Node.segments res nametable sourcetable)
(with-access::Node this (dstposition location)
(when (and dstposition location)
(let ((segment (list dstposition location)))
(set-cdr! res (cons segment (cdr res))))
(let* ((file (cadr location))
(f (hashtable-get sourcetable (cadr location))))
(unless f
(let ((n (hashtable-size sourcetable)))
(hashtable-put! sourcetable file n)))))
(default-walk this res nametable sourcetable)))
(define-nmethod (Ref.segments res nametable sourcetable)
(with-access::Ref this (var dstposition location)
(with-access::Var var (id)
(when (and dstposition location)
(let ((segment (list dstposition location id)))
(set-cdr! res (cons segment (cdr res))))
(let* ((file (cadr location))
(f (hashtable-get sourcetable (cadr location))))
(unless f
(let ((n (hashtable-size sourcetable)))
(hashtable-put! sourcetable file n)))))
(let ((o (hashtable-get nametable id)))
(unless o
(let ((n (hashtable-size nametable)))
(hashtable-put! nametable id n)))))))
(define (generate-source-map-names nametable p::output-port)
(display "[" p)
(let ((names (sort (lambda (e1 e2) (<fx (cdr e1) (cdr e2)))
(hashtable-map nametable cons) )))
(if (null? names)
(display "]" p)
(let loop ((names names))
(if (null? (cdr names))
(begin
(display "\"" p)
(display (caar names) p)
(display "\"]" p))
(begin
(display "\"" p)
(display (caar names) p)
(display "\"," p)
(loop (cdr names))))))))
(define (load-file-line-table file::bstring)
(call-with-input-file file
(lambda (p)
(let loop ((lines '())
(i 0))
(let ((line (read-line p)))
(if (eof-object? line)
(list->vector (reverse! lines))
(let ((j (input-port-position p)))
(loop (cons (cons i j) lines) j))))))))
|
9757583313de566f2a06a13e47395528345258a5b2f026e885adbfada15aaff5 | ovotech/clj-gcp | core_test.clj | (ns clj-gcp.integration.pub-sub.core-test
(:require [cheshire.core :as json]
[clj-gcp.pub-sub.utils :as mqu]
[clj-gcp.pub-sub.admin :as sut-admin]
[clj-gcp.pub-sub.core :as sut]
[clj-gcp.test-utils :as tu]
[clojure.string :as string]
[clojure.test :refer :all]
[iapetos.core :as prometheus])
(:import java.util.UUID))
(defn gcp-project-id [] (System/getenv "GCP_PROJECT_ID"))
(defn uuid [] (str (UUID/randomUUID)))
(defn with-random-topic+subscription
[project-id f]
(let [topic-id (str "DELETE-ME.topic." (uuid))
sub-id (str "DELETE-ME.subscription." (uuid))]
(sut-admin/create-topic project-id topic-id)
(sut-admin/create-subscription project-id topic-id sub-id 0)
(try (is (sut-admin/get-subscription project-id sub-id))
(f topic-id sub-id)
(finally (sut-admin/delete-subscription project-id sub-id)
(sut-admin/delete-topic project-id topic-id)))))
(defn see-req!
"Small utility to hook in the debugger."
[seen-reqs req]
(swap! seen-reqs conj req))
(defn with-subscriber
[seen-reqs f]
(with-random-topic+subscription (gcp-project-id)
(fn [topic-id sub-id]
(let [opts {:project-id (gcp-project-id)
:topic-id topic-id
:subscription-id sub-id
:handler (fn [msgs]
(doseq [msg msgs]
(see-req! seen-reqs msg))
(map #(assoc % :ok? true) msgs))
:metrics-registry
(-> (prometheus/collector-registry)
(prometheus/register
(prometheus/counter
:clj-gcp.pub-sub.core/message-count
{:description "life-cycle of pub-sub msgs",
:labels [:state]})))}
_ (tu/is-valid ::sut/subscriber.opts opts)
stop-subscriber (sut/start-subscriber opts)]
(f topic-id sub-id stop-subscriber)))))
(deftest ^:integration subscriber-test
(let [seen-msgs (atom [])]
(with-subscriber seen-msgs
(fn [topic-id subscription-id stop-subscriber]
(testing "getting messages"
(let [msg1 (json/generate-string {:a "A" :b "B"})
msg2 (json/generate-string {:a "A2" :b "B2"})]
(mqu/pubsub-publish msg1 {"eventType" "SOME_TYPE"} (gcp-project-id) topic-id)
(mqu/pubsub-publish msg2 {"eventType" "SOME_OTHER_TYPE"} (gcp-project-id) topic-id)
(tu/is-eventually (= 2 (count @seen-msgs))
:timeout 20000)
no guarantees on ordering with PubSub ( so using a set to check messages arrived )
(let [actual @seen-msgs
without-ack-id (map #(dissoc % :pubsub/ack-id) actual)
wo-ack-set (set without-ack-id)]
ack - ids are generate by GCP so just check they are added to the incoming message
(is (every? #(not (string/blank? (:pubsub/ack-id %))) actual))
(is (wo-ack-set
{:a "A"
:b "B"
:pubsub/attributes {:eventType "SOME_TYPE"}}))
(is (wo-ack-set
{:a "A2"
:b "B2"
:pubsub/attributes {:eventType "SOME_OTHER_TYPE"}})))
(stop-subscriber)))))))
| null | https://raw.githubusercontent.com/ovotech/clj-gcp/1a82e9c9711a21995141e102e7ef81e9e77dc739/test/clj_gcp/integration/pub_sub/core_test.clj | clojure | (ns clj-gcp.integration.pub-sub.core-test
(:require [cheshire.core :as json]
[clj-gcp.pub-sub.utils :as mqu]
[clj-gcp.pub-sub.admin :as sut-admin]
[clj-gcp.pub-sub.core :as sut]
[clj-gcp.test-utils :as tu]
[clojure.string :as string]
[clojure.test :refer :all]
[iapetos.core :as prometheus])
(:import java.util.UUID))
(defn gcp-project-id [] (System/getenv "GCP_PROJECT_ID"))
(defn uuid [] (str (UUID/randomUUID)))
(defn with-random-topic+subscription
[project-id f]
(let [topic-id (str "DELETE-ME.topic." (uuid))
sub-id (str "DELETE-ME.subscription." (uuid))]
(sut-admin/create-topic project-id topic-id)
(sut-admin/create-subscription project-id topic-id sub-id 0)
(try (is (sut-admin/get-subscription project-id sub-id))
(f topic-id sub-id)
(finally (sut-admin/delete-subscription project-id sub-id)
(sut-admin/delete-topic project-id topic-id)))))
(defn see-req!
"Small utility to hook in the debugger."
[seen-reqs req]
(swap! seen-reqs conj req))
(defn with-subscriber
[seen-reqs f]
(with-random-topic+subscription (gcp-project-id)
(fn [topic-id sub-id]
(let [opts {:project-id (gcp-project-id)
:topic-id topic-id
:subscription-id sub-id
:handler (fn [msgs]
(doseq [msg msgs]
(see-req! seen-reqs msg))
(map #(assoc % :ok? true) msgs))
:metrics-registry
(-> (prometheus/collector-registry)
(prometheus/register
(prometheus/counter
:clj-gcp.pub-sub.core/message-count
{:description "life-cycle of pub-sub msgs",
:labels [:state]})))}
_ (tu/is-valid ::sut/subscriber.opts opts)
stop-subscriber (sut/start-subscriber opts)]
(f topic-id sub-id stop-subscriber)))))
(deftest ^:integration subscriber-test
(let [seen-msgs (atom [])]
(with-subscriber seen-msgs
(fn [topic-id subscription-id stop-subscriber]
(testing "getting messages"
(let [msg1 (json/generate-string {:a "A" :b "B"})
msg2 (json/generate-string {:a "A2" :b "B2"})]
(mqu/pubsub-publish msg1 {"eventType" "SOME_TYPE"} (gcp-project-id) topic-id)
(mqu/pubsub-publish msg2 {"eventType" "SOME_OTHER_TYPE"} (gcp-project-id) topic-id)
(tu/is-eventually (= 2 (count @seen-msgs))
:timeout 20000)
no guarantees on ordering with PubSub ( so using a set to check messages arrived )
(let [actual @seen-msgs
without-ack-id (map #(dissoc % :pubsub/ack-id) actual)
wo-ack-set (set without-ack-id)]
ack - ids are generate by GCP so just check they are added to the incoming message
(is (every? #(not (string/blank? (:pubsub/ack-id %))) actual))
(is (wo-ack-set
{:a "A"
:b "B"
:pubsub/attributes {:eventType "SOME_TYPE"}}))
(is (wo-ack-set
{:a "A2"
:b "B2"
:pubsub/attributes {:eventType "SOME_OTHER_TYPE"}})))
(stop-subscriber)))))))
| |
4d4ef745e84d412aefbc92000ff11da73e28714ac33d7ab4680645b5ff57fed7 | adamwalker/clash-riscv | Replacement.hs | {-# LANGUAGE ScopedTypeVariables, GADTs #-}
module Cache.Replacement where
import Clash.Prelude
import Cache.PseudoLRUTree
type ReplacementFunc dom indexBits ways
= Signal dom (BitVector indexBits) --Index being looked up in the current cycle
-> Signal dom Bool --Hit in next cycle
-> Signal dom (Index ways) --Way that was hit (if any) in the next cycle
-> Signal dom (Index ways) --Way to replace in the current cycle
randomReplacement :: HiddenClockReset dom gated sync => ReplacementFunc dom indexBits 2
randomReplacement _ _ _ = bitCoerce <$> toReplace
where
toReplace = register False $ not <$> toReplace
pseudoLRUReplacement
:: forall dom sync gated indexBits numWaysLog. (HiddenClockReset dom gated sync, KnownNat indexBits, KnownNat numWaysLog, 1 <= numWaysLog)
=> ReplacementFunc dom indexBits (2 ^ numWaysLog)
pseudoLRUReplacement index valid way = bitCoerce . getOldestWay <$> readResult
where
readResult :: Signal dom (Vec ((2 ^ numWaysLog) - 1) Bool)
readResult = readNew (blockRamPow2 (repeat (repeat False))) (unpack <$> index) write
lastIdx = register 0 index
write :: Signal dom (Maybe (Unsigned indexBits, Vec ((2 ^ numWaysLog) - 1) Bool))
write = mux valid (func <$> lastIdx <*> readResult <*> way) (pure Nothing)
where
func index readResult way = Just (unpack index, updateWay (bitCoerce way) readResult)
| null | https://raw.githubusercontent.com/adamwalker/clash-riscv/84a90731a07c3427695b4926d7159f9e9902c1a1/src/Cache/Replacement.hs | haskell | # LANGUAGE ScopedTypeVariables, GADTs #
Index being looked up in the current cycle
Hit in next cycle
Way that was hit (if any) in the next cycle
Way to replace in the current cycle |
module Cache.Replacement where
import Clash.Prelude
import Cache.PseudoLRUTree
type ReplacementFunc dom indexBits ways
randomReplacement :: HiddenClockReset dom gated sync => ReplacementFunc dom indexBits 2
randomReplacement _ _ _ = bitCoerce <$> toReplace
where
toReplace = register False $ not <$> toReplace
pseudoLRUReplacement
:: forall dom sync gated indexBits numWaysLog. (HiddenClockReset dom gated sync, KnownNat indexBits, KnownNat numWaysLog, 1 <= numWaysLog)
=> ReplacementFunc dom indexBits (2 ^ numWaysLog)
pseudoLRUReplacement index valid way = bitCoerce . getOldestWay <$> readResult
where
readResult :: Signal dom (Vec ((2 ^ numWaysLog) - 1) Bool)
readResult = readNew (blockRamPow2 (repeat (repeat False))) (unpack <$> index) write
lastIdx = register 0 index
write :: Signal dom (Maybe (Unsigned indexBits, Vec ((2 ^ numWaysLog) - 1) Bool))
write = mux valid (func <$> lastIdx <*> readResult <*> way) (pure Nothing)
where
func index readResult way = Just (unpack index, updateWay (bitCoerce way) readResult)
|
92a8d05079543bc7a49bfdaebda7710355aeb6fa5f0dcb4842422308d9f434f0 | ekoontz/dag-unify | project.clj | (defproject dag_unify "1.11.1-SNAPSHOT"
:description "Unification of Directed Acyclic Graphs"
:url "-unify"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.11.1"]
[org.clojure/tools.logging "1.2.4"]])
| null | https://raw.githubusercontent.com/ekoontz/dag-unify/a2b4642032a308d37518fa41479a0d6c2956acc7/project.clj | clojure | (defproject dag_unify "1.11.1-SNAPSHOT"
:description "Unification of Directed Acyclic Graphs"
:url "-unify"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.11.1"]
[org.clojure/tools.logging "1.2.4"]])
| |
7eeef03ca2a7ee108af33e13be3b11522ef848903b5e26600070c15e0129ad11 | uwplse/rake | visitor.rkt | #lang rosette/safe
(require
rosette/lib/destruct
rake/halide/ir/types)
(provide (rename-out [visit halide:visit]))
;; Infer the length of vector generated by the expression
(define (visit expr handler)
(destruct expr
;; Abstract expressions
[(abstr-halide-expr orig-expr abstr-vals) (handler (abstr-halide-expr orig-expr (visit abstr-vals handler)))]
;; Constructors
[(x32 sca) (handler (x32 (visit sca handler)))]
[(x64 sca) (handler (x64 (visit sca handler)))]
[(x128 sca) (handler (x128 (visit sca handler)))]
[(x256 sca) (handler (x256 (visit sca handler)))]
[(x512 sca) (handler (x512 (visit sca handler)))]
[(ramp base stride len) (handler (ramp (visit base handler) (visit stride handler) (visit len handler)))]
[(load buf idxs alignment) (handler (load (visit buf handler) (visit idxs handler) (visit alignment handler)))]
[(load-sca buf idx) (handler (load-sca (visit buf handler) (visit idx handler)))]
;; Type Casts
[(uint8x1 sca) (handler (uint8x1 (visit sca handler)))]
[(uint16x1 sca) (handler (uint16x1 (visit sca handler)))]
[(uint32x1 sca) (handler (uint32x1 (visit sca handler)))]
[(uint64x1 sca) (handler (uint64x1 (visit sca handler)))]
[(int8x1 sca) (handler (int8x1 (visit sca handler)))]
[(int16x1 sca) (handler (int16x1 (visit sca handler)))]
[(int32x1 sca) (handler (int32x1 (visit sca handler)))]
[(int64x1 sca) (handler (int64x1 (visit sca handler)))]
[(uint1x32 vec) (handler (uint1x32 (visit vec handler)))]
[(uint1x64 vec) (handler (uint1x64 (visit vec handler)))]
[(uint1x128 vec) (handler (uint1x128 (visit vec handler)))]
[(uint1x256 vec) (handler (uint1x256 (visit vec handler)))]
[(uint1x512 vec) (handler (uint1x512 (visit vec handler)))]
[(uint8x32 vec) (handler (uint8x32 (visit vec handler)))]
[(uint16x32 vec) (handler (uint16x32 (visit vec handler)))]
[(uint32x32 vec) (handler (uint32x32 (visit vec handler)))]
[(uint64x32 vec) (handler (uint64x32 (visit vec handler)))]
[(int8x32 vec) (handler (int8x32 (visit vec handler)))]
[(int16x32 vec) (handler (int16x32 (visit vec handler)))]
[(int32x32 vec) (handler (int32x32 (visit vec handler)))]
[(int64x32 vec) (handler (int64x32 (visit vec handler)))]
[(uint8x64 vec) (handler (uint8x64 (visit vec handler)))]
[(uint16x64 vec) (handler (uint16x64 (visit vec handler)))]
[(uint32x64 vec) (handler (uint32x64 (visit vec handler)))]
[(uint64x64 vec) (handler (uint64x64 (visit vec handler)))]
[(int8x64 vec) (handler (int8x64 (visit vec handler)))]
[(int16x64 vec) (handler (int16x64 (visit vec handler)))]
[(int32x64 vec) (handler (int32x64 (visit vec handler)))]
[(int64x64 vec) (handler (int64x64 (visit vec handler)))]
[(uint8x128 vec) (handler (uint8x128 (visit vec handler)))]
[(uint16x128 vec) (handler (uint16x128 (visit vec handler)))]
[(uint32x128 vec) (handler (uint32x128 (visit vec handler)))]
[(uint64x128 vec) (handler (uint64x128 (visit vec handler)))]
[(int8x128 vec) (handler (int8x128 (visit vec handler)))]
[(int16x128 vec) (handler (int16x128 (visit vec handler)))]
[(int32x128 vec) (handler (int32x128 (visit vec handler)))]
[(int64x128 vec) (handler (int64x128 (visit vec handler)))]
[(uint8x256 vec) (handler (uint8x256 (visit vec handler)))]
[(uint16x256 vec) (handler (uint16x256 (visit vec handler)))]
[(uint32x256 vec) (handler (uint32x256 (visit vec handler)))]
[(uint64x256 vec) (handler (uint64x256 (visit vec handler)))]
[(int8x256 vec) (handler (int8x256 (visit vec handler)))]
[(int16x256 vec) (handler (int16x256 (visit vec handler)))]
[(int32x256 vec) (handler (int32x256 (visit vec handler)))]
[(int64x256 vec) (handler (int64x256 (visit vec handler)))]
[(uint8x512 vec) (handler (uint8x512 (visit vec handler)))]
[(uint16x512 vec) (handler (uint16x512 (visit vec handler)))]
[(uint32x512 vec) (handler (uint32x512 (visit vec handler)))]
[(uint64x512 vec) (handler (uint64x512 (visit vec handler)))]
[(int8x512 vec) (handler (int8x512 (visit vec handler)))]
[(int16x512 vec) (handler (int16x512 (visit vec handler)))]
[(int32x512 vec) (handler (int32x512 (visit vec handler)))]
[(int64x512 vec) (handler (int64x512 (visit vec handler)))]
Operations
[(vec-add v1 v2) (handler (vec-add (visit v1 handler) (visit v2 handler)))]
[(vec-sub v1 v2) (handler (vec-sub (visit v1 handler) (visit v2 handler)))]
[(vec-mul v1 v2) (handler (vec-mul (visit v1 handler) (visit v2 handler)))]
[(vec-div v1 v2) (handler (vec-div (visit v1 handler) (visit v2 handler)))]
[(vec-mod v1 v2) (handler (vec-mod (visit v1 handler) (visit v2 handler)))]
[(vec-min v1 v2) (handler (vec-min (visit v1 handler) (visit v2 handler)))]
[(vec-max v1 v2) (handler (vec-max (visit v1 handler) (visit v2 handler)))]
[(vec-shl v1 v2) (handler (vec-shl (visit v1 handler) (visit v2 handler)))]
[(vec-shr v1 v2) (handler (vec-shr (visit v1 handler) (visit v2 handler)))]
[(vec-absd v1 v2) (handler (vec-absd (visit v1 handler) (visit v2 handler)))]
[(vec-abs v1) (handler (vec-abs (visit v1 handler)))]
[(vec-clz v1) (handler (vec-clz (visit v1 handler)))]
[(vec-lt v1 v2) (handler (vec-lt (visit v1 handler) (visit v2 handler)))]
[(vec-eq v1 v2) (handler (vec-eq (visit v1 handler) (visit v2 handler)))]
[(vec-le v1 v2) (handler (vec-le (visit v1 handler) (visit v2 handler)))]
[(vec-if v1 v2 v3) (handler (vec-if (visit v1 handler) (visit v2 handler) (visit v3 handler)))]
[(vec-bwand v1 v2) (handler (vec-bwand (visit v1 handler) (visit v2 handler)))]
[(vector_reduce op width vec) (handler (vector_reduce op width (visit vec handler)))]
;; Shuffles
[(vec-broadcast n vec) (handler (vec-broadcast n (visit vec handler)))]
[(slice_vectors vec base stride len) (handler (slice_vectors (visit vec handler) (visit base handler) (visit stride handler) (visit len handler)))]
[(concat_vectors v1 v2) (handler (concat_vectors (visit v1 handler) (visit v2 handler)))]
[(interleave v1 v2) (handler (interleave (visit v1 handler) (visit v2 handler)))]
[(interleave4 v1 v2 v3 v4) (handler (interleave4 (visit v1 handler) (visit v2 handler) (visit v3 handler) (visit v4 handler)))]
[(dynamic_shuffle vec idxs st end) (handler (slice_vectors (visit vec handler) (visit idxs handler) (visit st handler) (visit end handler)))]
;; Base case
[_ (handler expr)])) | null | https://raw.githubusercontent.com/uwplse/rake/0fb9b46ae8ac64f95a4c0e89060ffdb043229a5b/rake/halide/ir/visitor.rkt | racket | Infer the length of vector generated by the expression
Abstract expressions
Constructors
Type Casts
Shuffles
Base case | #lang rosette/safe
(require
rosette/lib/destruct
rake/halide/ir/types)
(provide (rename-out [visit halide:visit]))
(define (visit expr handler)
(destruct expr
[(abstr-halide-expr orig-expr abstr-vals) (handler (abstr-halide-expr orig-expr (visit abstr-vals handler)))]
[(x32 sca) (handler (x32 (visit sca handler)))]
[(x64 sca) (handler (x64 (visit sca handler)))]
[(x128 sca) (handler (x128 (visit sca handler)))]
[(x256 sca) (handler (x256 (visit sca handler)))]
[(x512 sca) (handler (x512 (visit sca handler)))]
[(ramp base stride len) (handler (ramp (visit base handler) (visit stride handler) (visit len handler)))]
[(load buf idxs alignment) (handler (load (visit buf handler) (visit idxs handler) (visit alignment handler)))]
[(load-sca buf idx) (handler (load-sca (visit buf handler) (visit idx handler)))]
[(uint8x1 sca) (handler (uint8x1 (visit sca handler)))]
[(uint16x1 sca) (handler (uint16x1 (visit sca handler)))]
[(uint32x1 sca) (handler (uint32x1 (visit sca handler)))]
[(uint64x1 sca) (handler (uint64x1 (visit sca handler)))]
[(int8x1 sca) (handler (int8x1 (visit sca handler)))]
[(int16x1 sca) (handler (int16x1 (visit sca handler)))]
[(int32x1 sca) (handler (int32x1 (visit sca handler)))]
[(int64x1 sca) (handler (int64x1 (visit sca handler)))]
[(uint1x32 vec) (handler (uint1x32 (visit vec handler)))]
[(uint1x64 vec) (handler (uint1x64 (visit vec handler)))]
[(uint1x128 vec) (handler (uint1x128 (visit vec handler)))]
[(uint1x256 vec) (handler (uint1x256 (visit vec handler)))]
[(uint1x512 vec) (handler (uint1x512 (visit vec handler)))]
[(uint8x32 vec) (handler (uint8x32 (visit vec handler)))]
[(uint16x32 vec) (handler (uint16x32 (visit vec handler)))]
[(uint32x32 vec) (handler (uint32x32 (visit vec handler)))]
[(uint64x32 vec) (handler (uint64x32 (visit vec handler)))]
[(int8x32 vec) (handler (int8x32 (visit vec handler)))]
[(int16x32 vec) (handler (int16x32 (visit vec handler)))]
[(int32x32 vec) (handler (int32x32 (visit vec handler)))]
[(int64x32 vec) (handler (int64x32 (visit vec handler)))]
[(uint8x64 vec) (handler (uint8x64 (visit vec handler)))]
[(uint16x64 vec) (handler (uint16x64 (visit vec handler)))]
[(uint32x64 vec) (handler (uint32x64 (visit vec handler)))]
[(uint64x64 vec) (handler (uint64x64 (visit vec handler)))]
[(int8x64 vec) (handler (int8x64 (visit vec handler)))]
[(int16x64 vec) (handler (int16x64 (visit vec handler)))]
[(int32x64 vec) (handler (int32x64 (visit vec handler)))]
[(int64x64 vec) (handler (int64x64 (visit vec handler)))]
[(uint8x128 vec) (handler (uint8x128 (visit vec handler)))]
[(uint16x128 vec) (handler (uint16x128 (visit vec handler)))]
[(uint32x128 vec) (handler (uint32x128 (visit vec handler)))]
[(uint64x128 vec) (handler (uint64x128 (visit vec handler)))]
[(int8x128 vec) (handler (int8x128 (visit vec handler)))]
[(int16x128 vec) (handler (int16x128 (visit vec handler)))]
[(int32x128 vec) (handler (int32x128 (visit vec handler)))]
[(int64x128 vec) (handler (int64x128 (visit vec handler)))]
[(uint8x256 vec) (handler (uint8x256 (visit vec handler)))]
[(uint16x256 vec) (handler (uint16x256 (visit vec handler)))]
[(uint32x256 vec) (handler (uint32x256 (visit vec handler)))]
[(uint64x256 vec) (handler (uint64x256 (visit vec handler)))]
[(int8x256 vec) (handler (int8x256 (visit vec handler)))]
[(int16x256 vec) (handler (int16x256 (visit vec handler)))]
[(int32x256 vec) (handler (int32x256 (visit vec handler)))]
[(int64x256 vec) (handler (int64x256 (visit vec handler)))]
[(uint8x512 vec) (handler (uint8x512 (visit vec handler)))]
[(uint16x512 vec) (handler (uint16x512 (visit vec handler)))]
[(uint32x512 vec) (handler (uint32x512 (visit vec handler)))]
[(uint64x512 vec) (handler (uint64x512 (visit vec handler)))]
[(int8x512 vec) (handler (int8x512 (visit vec handler)))]
[(int16x512 vec) (handler (int16x512 (visit vec handler)))]
[(int32x512 vec) (handler (int32x512 (visit vec handler)))]
[(int64x512 vec) (handler (int64x512 (visit vec handler)))]
Operations
[(vec-add v1 v2) (handler (vec-add (visit v1 handler) (visit v2 handler)))]
[(vec-sub v1 v2) (handler (vec-sub (visit v1 handler) (visit v2 handler)))]
[(vec-mul v1 v2) (handler (vec-mul (visit v1 handler) (visit v2 handler)))]
[(vec-div v1 v2) (handler (vec-div (visit v1 handler) (visit v2 handler)))]
[(vec-mod v1 v2) (handler (vec-mod (visit v1 handler) (visit v2 handler)))]
[(vec-min v1 v2) (handler (vec-min (visit v1 handler) (visit v2 handler)))]
[(vec-max v1 v2) (handler (vec-max (visit v1 handler) (visit v2 handler)))]
[(vec-shl v1 v2) (handler (vec-shl (visit v1 handler) (visit v2 handler)))]
[(vec-shr v1 v2) (handler (vec-shr (visit v1 handler) (visit v2 handler)))]
[(vec-absd v1 v2) (handler (vec-absd (visit v1 handler) (visit v2 handler)))]
[(vec-abs v1) (handler (vec-abs (visit v1 handler)))]
[(vec-clz v1) (handler (vec-clz (visit v1 handler)))]
[(vec-lt v1 v2) (handler (vec-lt (visit v1 handler) (visit v2 handler)))]
[(vec-eq v1 v2) (handler (vec-eq (visit v1 handler) (visit v2 handler)))]
[(vec-le v1 v2) (handler (vec-le (visit v1 handler) (visit v2 handler)))]
[(vec-if v1 v2 v3) (handler (vec-if (visit v1 handler) (visit v2 handler) (visit v3 handler)))]
[(vec-bwand v1 v2) (handler (vec-bwand (visit v1 handler) (visit v2 handler)))]
[(vector_reduce op width vec) (handler (vector_reduce op width (visit vec handler)))]
[(vec-broadcast n vec) (handler (vec-broadcast n (visit vec handler)))]
[(slice_vectors vec base stride len) (handler (slice_vectors (visit vec handler) (visit base handler) (visit stride handler) (visit len handler)))]
[(concat_vectors v1 v2) (handler (concat_vectors (visit v1 handler) (visit v2 handler)))]
[(interleave v1 v2) (handler (interleave (visit v1 handler) (visit v2 handler)))]
[(interleave4 v1 v2 v3 v4) (handler (interleave4 (visit v1 handler) (visit v2 handler) (visit v3 handler) (visit v4 handler)))]
[(dynamic_shuffle vec idxs st end) (handler (slice_vectors (visit vec handler) (visit idxs handler) (visit st handler) (visit end handler)))]
[_ (handler expr)])) |
5facfae67fe1f258244fbaa2cf40a22c14e26d94d69eb106e62974c69778b553 | alexandroid000/improv | Listener.hs | module Listener (main) where
import Ros.Node
import Lens.Family (view)
import qualified Ros.Std_msgs.String as S
showMsg :: S.String -> IO ()
showMsg = putStrLn . ("I heard " ++) . view S._data
main = runNode "listener" $ runHandler showMsg =<< subscribe "chatter"
| null | https://raw.githubusercontent.com/alexandroid000/improv/ef0f4a6a5f99a9c7ff3d25f50529417aba9f757c/roshask/Examples/PubSub/src/Listener.hs | haskell | module Listener (main) where
import Ros.Node
import Lens.Family (view)
import qualified Ros.Std_msgs.String as S
showMsg :: S.String -> IO ()
showMsg = putStrLn . ("I heard " ++) . view S._data
main = runNode "listener" $ runHandler showMsg =<< subscribe "chatter"
| |
4b98ef95a17d83593ab1d3195b4251d92cd586b2f3787d3abde14f7e64f45a02 | abhimanyuma/Academic-Material | Diff.hs | module Diff where
import Root
import Sim
eval (F "diff" [a,V b]) = diff a (V b)
--Basic rules
diff (C _) (V _) = C 0
diff (V a) (V b) = if a==b then C 1
else C 0
diff (F f [C _]) (V _) = C 0
diff (F "sin" [V a]) (V b) = if a==b then F "cos" [V a]
else C 0
diff (F "cos" [V a]) (V b) = if a==b then F "-" [C 0, F "sin" [V a] ]
else C 0
diff (F "tan" [V a]) (V b) = if a==b then F "^" [F "sec" [V a] , C 2]
else C 0
diff (F "cosec" [V a]) (V b) = if a==b then F "-" [C 0 ,F "*" [F "cot" [V a] , F "cosec" [V a]]]
else C 0
diff (F "sec" [V a]) (V b) = if a==b then F "*" [F "tan" [V a] , F "sec" [V a]]
else C 0
diff (F "cot" [V a]) (V b) = if a==b then F "-" [C 0, F "^" [F "cosec" [V a] , C 2]]
else C 0
diff (F "ln" [V a]) (V b) = if a==b then F "/" [C 1, V a]
else C 0
diff (F "^" [(V a) , (C y)] ) (V b) = if a==b then F "*" [(C y) , ( F "^" [(V "x") , (C (y-1))] )]
else C 0
diff (F "^" [(C y), (V a)] ) (V b) = if a==b then F "*" [(C (log y)) , F "^" [C y, V a] ] else C 0
diff (F "sinh" [V a]) (V b)= if a==b then F "cosh" [V a]
else C 0
diff (F "cosh" [V a]) (V b)= if a==b then F "sinh" [V a]
else C 0
diff (F "tanh" [V a]) (V b)= if a==b then F "^" [F "sech" [V a], C 2]
else C 0
diff (F "coth" [V a]) (V b)= if a==b then F "-" [C 0, F "^" [F "cosech" [V a], C 2]]
else C 0
diff (F "cosech" [V a]) (V b)= if a==b then F "-" [C 0, F "*" [F "cosech" [V a], F "coth" [V a]]]
else C 0
diff (F "sech" [V a]) (V b)= if a==b then F "-" [C 0, F "*" [F "tanh" [V a], F "sech" [V a]]]
else C 0
diff (F "invsin" [V a]) (V b) = if a==b then F "/" [C 1, F "^" [F "-" [C 1, F "^" [V a, C 2]],C 0.5] ]
else C 0
diff (F "invcos" [V a]) (V b) = if a==b then F "/" [(C (-1)), F "^" [F "-" [C 1, F "^" [V a, C 2]],C 0.5] ]
else C 0
diff (F "invtan" [V a]) (V b) = if a==b then F "/" [C 1, F "+" [C 1, F "^" [V a, C 2]] ]
else C 0
diff (F "invsinh" [V a]) (V b) = if a==b then F "/" [C 1, F "^" [F "+" [C 1, F "^" [V a, C 2]],C 0.5] ]
else C 0
diff (F "invcosh" [V a]) (V b) = if a==b then F "/" [(C (1)), F "^" [F "-" [ (F "^" [V a, C 2]), C 1],C 0.5] ]
else C 0
diff (F "invtanh" [V a]) (V b) = if a==b then F "/" [C 1, F "-" [C 1, F "^" [V a, C 2]] ]
else C 0
diff (F "invcosech" [V a]) (V b) = if a==b then F "/" [(C (-1)), F "^" [F "+" [C 1, F "^" [V a, C 2]],C 0.5] ]
else C 0
diff (F "invcoth" [V a]) (V b) = if a==b then F "/" [C 1, F "-" [C 1, F "^" [V a, C 2]] ]
else C 0
--diff (F "invsech" [V a]) (V b)
-- The fog rule
diff (F f [F g xs]) (V a) = F "*" [ t , (diff (F g xs) (V a)) ]
where t = substitute (diff (F f [V a]) (V a) ) (V a) (F g xs)
--The Chain Rule
diff (F "-" [x]) t= F "-" [ diff x t]
diff (F "+" [x,y]) t = F "+" [ diff x t, diff y t]
diff (F "-" [x,y]) t= F "-" [ diff x t, diff y t]
diff (F "*" [x,y]) t= F "+" [ F "*" [diff x t ,y] , F "*" [diff y t,x] ]
diff (F "/" [x,y]) t= F "/" [F "-" [ F "*" [diff x t ,y] , F "*" [diff y t,x] ] , F "^" [y,C 2] ]
diff (F "^" [x,y]) t = F "*" [F "^" [x,y], diff (F "*" [x, F "ln" [y] ] ) t ]
dif a = diff a (V "x")
substitute (C c) (V a) (eq) = C c
substitute (V c) (V a) (eq) = if c == a then eq
else V c
substitute (F f xs) (V a) (eq) = F f (fmap (\x -> substitute x (V a) (eq)) xs)
interspase [ ] = [ ]
interspase ( x : xs ) = x++ ( interspase xs )
instance Functor Equation where
fmap f ( C s ) = C ( f s )
fmap f (
interspase [] = []
interspase (x:xs) = x++ (interspase xs )
instance Functor Equation where
fmap f (C s) = C (f s)
fmap f (
-}
{-
diff (F "cos" [a]) (V a) = F "-" [F "sin" [a]]
diff (F "tan" [a]) (V a) = F "sec2" [a]
diff (F "cot" [a]) (V a) = F "cosec2" [a]
-}
--
diff ( BinOp " . " a b ) =
--diffy [a,(F "." []), b] = [ a, (F "." []) , diff b , (F "+" []) , b , (F "." []) , diff a]
diff ( F f [ F g xs ] ) ( V a ) = F " * " [ t , ( diff ( F g xs ) ( V a ) ) ]
where t = case ( diff ( F f [ V a ] ) ( V a ) ) of
( F h [ V a ] ) - > ( F h [ F g xs ] )
( F h [ F h ' x ] ) - > ( F h [ F h ' [ F g xs ] ] ) -- for handling unary opertors
( F h [ C b , V a ] ) - > ( F h [ C b , F g xs ] )
diff (F f [F g xs]) (V a) = F "*" [ t , (diff (F g xs) (V a)) ]
where t = case (diff (F f [V a]) (V a) ) of
(F h [V a]) -> (F h [F g xs])
(F h [F h' x] ) -> ( F h [ F h' [F g xs] ] ) -- for handling unary opertors
(F h [C b, V a]) -> (F h [C b ,F g xs])
-}
| null | https://raw.githubusercontent.com/abhimanyuma/Academic-Material/6badf113084c20d0d9259fc08a71e56528b168e4/Functional%20Programming/Project%20-%20Madskell/src/Diff.hs | haskell | Basic rules
diff (F "invsech" [V a]) (V b)
The fog rule
The Chain Rule
diff (F "cos" [a]) (V a) = F "-" [F "sin" [a]]
diff (F "tan" [a]) (V a) = F "sec2" [a]
diff (F "cot" [a]) (V a) = F "cosec2" [a]
diffy [a,(F "." []), b] = [ a, (F "." []) , diff b , (F "+" []) , b , (F "." []) , diff a]
for handling unary opertors
for handling unary opertors
| module Diff where
import Root
import Sim
eval (F "diff" [a,V b]) = diff a (V b)
diff (C _) (V _) = C 0
diff (V a) (V b) = if a==b then C 1
else C 0
diff (F f [C _]) (V _) = C 0
diff (F "sin" [V a]) (V b) = if a==b then F "cos" [V a]
else C 0
diff (F "cos" [V a]) (V b) = if a==b then F "-" [C 0, F "sin" [V a] ]
else C 0
diff (F "tan" [V a]) (V b) = if a==b then F "^" [F "sec" [V a] , C 2]
else C 0
diff (F "cosec" [V a]) (V b) = if a==b then F "-" [C 0 ,F "*" [F "cot" [V a] , F "cosec" [V a]]]
else C 0
diff (F "sec" [V a]) (V b) = if a==b then F "*" [F "tan" [V a] , F "sec" [V a]]
else C 0
diff (F "cot" [V a]) (V b) = if a==b then F "-" [C 0, F "^" [F "cosec" [V a] , C 2]]
else C 0
diff (F "ln" [V a]) (V b) = if a==b then F "/" [C 1, V a]
else C 0
diff (F "^" [(V a) , (C y)] ) (V b) = if a==b then F "*" [(C y) , ( F "^" [(V "x") , (C (y-1))] )]
else C 0
diff (F "^" [(C y), (V a)] ) (V b) = if a==b then F "*" [(C (log y)) , F "^" [C y, V a] ] else C 0
diff (F "sinh" [V a]) (V b)= if a==b then F "cosh" [V a]
else C 0
diff (F "cosh" [V a]) (V b)= if a==b then F "sinh" [V a]
else C 0
diff (F "tanh" [V a]) (V b)= if a==b then F "^" [F "sech" [V a], C 2]
else C 0
diff (F "coth" [V a]) (V b)= if a==b then F "-" [C 0, F "^" [F "cosech" [V a], C 2]]
else C 0
diff (F "cosech" [V a]) (V b)= if a==b then F "-" [C 0, F "*" [F "cosech" [V a], F "coth" [V a]]]
else C 0
diff (F "sech" [V a]) (V b)= if a==b then F "-" [C 0, F "*" [F "tanh" [V a], F "sech" [V a]]]
else C 0
diff (F "invsin" [V a]) (V b) = if a==b then F "/" [C 1, F "^" [F "-" [C 1, F "^" [V a, C 2]],C 0.5] ]
else C 0
diff (F "invcos" [V a]) (V b) = if a==b then F "/" [(C (-1)), F "^" [F "-" [C 1, F "^" [V a, C 2]],C 0.5] ]
else C 0
diff (F "invtan" [V a]) (V b) = if a==b then F "/" [C 1, F "+" [C 1, F "^" [V a, C 2]] ]
else C 0
diff (F "invsinh" [V a]) (V b) = if a==b then F "/" [C 1, F "^" [F "+" [C 1, F "^" [V a, C 2]],C 0.5] ]
else C 0
diff (F "invcosh" [V a]) (V b) = if a==b then F "/" [(C (1)), F "^" [F "-" [ (F "^" [V a, C 2]), C 1],C 0.5] ]
else C 0
diff (F "invtanh" [V a]) (V b) = if a==b then F "/" [C 1, F "-" [C 1, F "^" [V a, C 2]] ]
else C 0
diff (F "invcosech" [V a]) (V b) = if a==b then F "/" [(C (-1)), F "^" [F "+" [C 1, F "^" [V a, C 2]],C 0.5] ]
else C 0
diff (F "invcoth" [V a]) (V b) = if a==b then F "/" [C 1, F "-" [C 1, F "^" [V a, C 2]] ]
else C 0
diff (F f [F g xs]) (V a) = F "*" [ t , (diff (F g xs) (V a)) ]
where t = substitute (diff (F f [V a]) (V a) ) (V a) (F g xs)
diff (F "-" [x]) t= F "-" [ diff x t]
diff (F "+" [x,y]) t = F "+" [ diff x t, diff y t]
diff (F "-" [x,y]) t= F "-" [ diff x t, diff y t]
diff (F "*" [x,y]) t= F "+" [ F "*" [diff x t ,y] , F "*" [diff y t,x] ]
diff (F "/" [x,y]) t= F "/" [F "-" [ F "*" [diff x t ,y] , F "*" [diff y t,x] ] , F "^" [y,C 2] ]
diff (F "^" [x,y]) t = F "*" [F "^" [x,y], diff (F "*" [x, F "ln" [y] ] ) t ]
dif a = diff a (V "x")
substitute (C c) (V a) (eq) = C c
substitute (V c) (V a) (eq) = if c == a then eq
else V c
substitute (F f xs) (V a) (eq) = F f (fmap (\x -> substitute x (V a) (eq)) xs)
interspase [ ] = [ ]
interspase ( x : xs ) = x++ ( interspase xs )
instance Functor Equation where
fmap f ( C s ) = C ( f s )
fmap f (
interspase [] = []
interspase (x:xs) = x++ (interspase xs )
instance Functor Equation where
fmap f (C s) = C (f s)
fmap f (
-}
diff ( BinOp " . " a b ) =
diff ( F f [ F g xs ] ) ( V a ) = F " * " [ t , ( diff ( F g xs ) ( V a ) ) ]
where t = case ( diff ( F f [ V a ] ) ( V a ) ) of
( F h [ V a ] ) - > ( F h [ F g xs ] )
( F h [ C b , V a ] ) - > ( F h [ C b , F g xs ] )
diff (F f [F g xs]) (V a) = F "*" [ t , (diff (F g xs) (V a)) ]
where t = case (diff (F f [V a]) (V a) ) of
(F h [V a]) -> (F h [F g xs])
(F h [C b, V a]) -> (F h [C b ,F g xs])
-}
|
c00805bc495dd2c7ed7248a92076ffc0f8979745dc861780851c9afeec08c39d | Reisen/pixel | GenerateTypes.hs | module Commands.GenerateTypes
( commandGenerateTypes
, generateTypes
) where
import Protolude
import Commands.Types ( Options(..), GenerateTypesOptions(..) )
import Data.Text as T ( lines, isInfixOf, unlines, replace )
import Data.Text.IO ( writeFile )
import Options.Applicative ( Parser
, Mod
, CommandFields
, command
, help
, info
, long
, metavar
, progDesc
, strOption
)
import Pixel.API ( API )
import Servant.JS ( jsForAPI )
import Servant.JS.Axios ( AxiosOptions(..), defAxiosOptions, axios )
--------------------------------------------------------------------------------
generateTypes :: GenerateTypesOptions -> IO ()
generateTypes (GenerateTypesOptions folder) = do
-- Drop Header Lines (HACK: We don't really want headers ever)
writeFile (toS folder) $ lines generatedAPI
& filter (not . isInfixOf "headers: {")
& map (T.replace "var " "export const ")
& unlines
& ("import { axios } from 'axios';\n" <>)
where
generatedAPI = jsForAPI (Proxy :: Proxy API) $ axios defAxiosOptions
{ withCredentials = True
}
--------------------------------------------------------------------------------
-- Define primitives used for optparse
commandGenerateTypes :: Mod CommandFields Options
commandGenerateTypes = command "generate-types"
(info parseOptions
(progDesc "Generate TypeScript definitions for API."))
parseOptions :: Parser Options
parseOptions = GenerateTypes <$>
( GenerateTypesOptions
<$> folderOption
)
folderOption :: Parser Text
folderOption = strOption
( long "file"
<> help "File to write TypeScript definitions into."
<> metavar "FILE"
)
| null | https://raw.githubusercontent.com/Reisen/pixel/9096cc2c5b909049cdca6d14856ffc1fc99d81b5/src/app/Commands/GenerateTypes.hs | haskell | ------------------------------------------------------------------------------
Drop Header Lines (HACK: We don't really want headers ever)
------------------------------------------------------------------------------
Define primitives used for optparse | module Commands.GenerateTypes
( commandGenerateTypes
, generateTypes
) where
import Protolude
import Commands.Types ( Options(..), GenerateTypesOptions(..) )
import Data.Text as T ( lines, isInfixOf, unlines, replace )
import Data.Text.IO ( writeFile )
import Options.Applicative ( Parser
, Mod
, CommandFields
, command
, help
, info
, long
, metavar
, progDesc
, strOption
)
import Pixel.API ( API )
import Servant.JS ( jsForAPI )
import Servant.JS.Axios ( AxiosOptions(..), defAxiosOptions, axios )
generateTypes :: GenerateTypesOptions -> IO ()
generateTypes (GenerateTypesOptions folder) = do
writeFile (toS folder) $ lines generatedAPI
& filter (not . isInfixOf "headers: {")
& map (T.replace "var " "export const ")
& unlines
& ("import { axios } from 'axios';\n" <>)
where
generatedAPI = jsForAPI (Proxy :: Proxy API) $ axios defAxiosOptions
{ withCredentials = True
}
commandGenerateTypes :: Mod CommandFields Options
commandGenerateTypes = command "generate-types"
(info parseOptions
(progDesc "Generate TypeScript definitions for API."))
parseOptions :: Parser Options
parseOptions = GenerateTypes <$>
( GenerateTypesOptions
<$> folderOption
)
folderOption :: Parser Text
folderOption = strOption
( long "file"
<> help "File to write TypeScript definitions into."
<> metavar "FILE"
)
|
0ca4874c251c748719befcb99fd4f5057ad6981a09912bf18771ab0862e6a259 | VERIMAG-Polyhedra/VPL | DomainFunctors.mli | open ASAtomicCond
open ASCond
open ASTerm
open BinInt
open BinNums
open CstrC
open Datatypes
open Debugging
open DomainInterfaces
open FMapPositive
open ImpureConfig
open Itv
open LinTerm
open LinearizeBackend
open MSetPositive
open NumC
open PredTrans
open ProgVar
open Ring_polynom_AddOn
open String0
open ZNone
open ZNoneItv
type __ = Obj.t
module MakeFull :
functor (N:NumSig) ->
functor (Cond:sig
module Term :
sig
module Annot :
sig
type topLevelAnnot = TopLevelAnnot.topLevelAnnot =
| OLD
| AFFINE
| INTERV
| STATIC
| SKIP_ORACLE
val topLevelAnnot_rect :
'a1 -> 'a1 -> 'a1 -> 'a1 -> 'a1 -> topLevelAnnot -> 'a1
val topLevelAnnot_rec :
'a1 -> 'a1 -> 'a1 -> 'a1 -> 'a1 -> topLevelAnnot -> 'a1
type t = topLevelAnnot
val pr : topLevelAnnot -> char list
end
type term =
| Var of PVar.t
| Cte of N.t
| Add of term * term
| Opp of term
| Mul of term * term
| Annot of Annot.topLevelAnnot * term
val term_rect :
(PVar.t -> 'a1) -> (N.t -> 'a1) -> (term -> 'a1 -> term -> 'a1 -> 'a1)
-> (term -> 'a1 -> 'a1) -> (term -> 'a1 -> term -> 'a1 -> 'a1) ->
(Annot.topLevelAnnot -> term -> 'a1 -> 'a1) -> term -> 'a1
val term_rec :
(PVar.t -> 'a1) -> (N.t -> 'a1) -> (term -> 'a1 -> term -> 'a1 -> 'a1)
-> (term -> 'a1 -> 'a1) -> (term -> 'a1 -> term -> 'a1 -> 'a1) ->
(Annot.topLevelAnnot -> term -> 'a1 -> 'a1) -> term -> 'a1
type t = term
val eval : term -> N.t Mem.t -> N.t
val mdBound : term -> PVar.t -> PVar.t
val fold_variables : term -> (PVar.t -> 'a1 -> 'a1) -> 'a1 -> 'a1
val map : term -> PVar.t Mem.t -> term
val pseudoIsZero : term -> bool
val smartScalAdd1 : N.t -> term -> term
val smartScalAdd : N.t -> term -> term
val smartAdd : term -> term -> term
val smartOpp : term -> term
val smartScalMul1 : N.t -> term -> term
val smartScalMul : N.t -> term -> term
val smartMul : term -> term -> term
val smartAnnot : Annot.topLevelAnnot -> term -> term
val import_acc : (PVar.t*N.t) list -> term -> term
val import : (PVar.t*N.t) list -> term
val coq_Old : term -> term
val xeval : term -> N.t Mem.t -> N.t Mem.t -> N.t
val xmap : term -> PVar.t Mem.t -> PVar.t Mem.t -> term
val isCte : term -> bool
val annotAFFINEx : term -> term
val annotAFFINE_rec : term -> term option
val annotAFFINE : term -> term
val matchCte : term -> N.t option
val pr : term -> char list
end
type cond =
| Basic of bool
| Atom of cmpG * Term.term * Term.term
| BinL of binl * cond * cond
| Not of cond
val cond_rect :
(bool -> 'a1) -> (cmpG -> Term.term -> Term.term -> 'a1) -> (binl -> cond
-> 'a1 -> cond -> 'a1 -> 'a1) -> (cond -> 'a1 -> 'a1) -> cond -> 'a1
val cond_rec :
(bool -> 'a1) -> (cmpG -> Term.term -> Term.term -> 'a1) -> (binl -> cond
-> 'a1 -> cond -> 'a1 -> 'a1) -> (cond -> 'a1 -> 'a1) -> cond -> 'a1
type t = cond
val sat_dec : t -> N.t Mem.t -> bool
val xsat_dec : t -> N.t Mem.t -> N.t Mem.t -> bool
val mdBound : cond -> positive -> positive
val map : cond -> PVar.t Mem.t -> cond
val xmap : cond -> PVar.t Mem.t -> PVar.t Mem.t -> cond
val dual : cmpG -> Term.term -> Term.term -> t
val nnf : t -> t
val nnfNot : t -> t
end) ->
functor (I:sig
type t
end) ->
functor (AtomC:sig
type atomicCond = { cmpOp : cmpG; right : Cond.Term.t }
val cmpOp : atomicCond -> cmpG
val right : atomicCond -> Cond.Term.t
type t = atomicCond
val make : Cond.Term.term -> cmpG -> Cond.Term.term -> t
end) ->
functor (D:sig
type t
val isIncl : t -> t -> bool Core.Base.imp
val top : t
val join : t -> t -> t Core.Base.imp
val widen : t -> t -> t Core.Base.imp
val bottom : t
val isBottom : t -> bool Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
end) ->
functor (AtomD:sig
val assume : AtomC.t -> D.t -> D.t Core.Base.imp
end) ->
functor (R:sig
val rename : PVar.t -> PVar.t -> D.t -> D.t Core.Base.imp
end) ->
functor (DI:sig
val getItvMode : mode -> Cond.Term.t -> D.t -> I.t Core.Base.imp
end) ->
functor (DP:sig
val pr : D.t -> char list
val to_string : (PVar.t -> char list) -> D.t -> char list
type rep
val backend_rep :
D.t -> (rep*((PVar.t -> PVar.t)*(PVar.t -> PVar.t))) option
val meet : D.t -> D.t -> D.t Core.Base.imp
end) ->
sig
module Dom :
sig
type t = D.t
val isIncl : t -> t -> bool Core.Base.imp
val top : t
val join : t -> t -> t Core.Base.imp
val widen : t -> t -> t Core.Base.imp
val bottom : t
val isBottom : t -> bool Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
val skipBottom : D.t -> D.t Core.Base.imp -> D.t Core.Base.imp
val assumeRec : Cond.t -> D.t -> D.t Core.Base.imp
val assume : Cond.cond -> D.t -> D.t Core.Base.imp
module Naive :
sig
val coq_assert : Cond.cond -> t -> bool Core.Base.imp
end
val assertRec : Cond.t -> t -> bool Core.Base.imp
val coq_assert : Cond.t -> t -> bool Core.Base.imp
end
val encode : bool -> positive -> positive
val decode : positive -> positive
val encodeE : PositiveSet.t -> positive -> positive
val encodeO : PositiveSet.t -> positive -> positive
val decodeIn : PositiveSet.t -> N.t Mem.t -> N.t Mem.t -> positive -> N.t
val switch : PositiveSet.t -> positive -> PositiveSet.t
type assignDomain = { pol : Dom.t; renaming : PositiveSet.t }
val pol : assignDomain -> Dom.t
val renaming : assignDomain -> PositiveSet.t
type t = assignDomain
val top : t
val bottom : t
val isBottom : t -> bool Core.Base.imp
val assume : Cond.cond -> t -> t Core.Base.imp
val coq_assert : Cond.cond -> t -> bool Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
val guassignAux : positive -> Cond.cond -> t -> t Core.Base.imp
val guassign : PVar.t -> Cond.cond -> t -> t Core.Base.imp
val assign : positive -> Cond.Term.term -> t -> t Core.Base.imp
val nop : PVar.t -> assignDomain -> t Core.Base.imp
val switchAll : PositiveSet.t -> t -> t Core.Base.imp
val isIncl : t -> t -> bool Core.Base.imp
val join : t -> t -> t Core.Base.imp
val widen : t -> t -> t Core.Base.imp
val rename :
positive -> positive -> assignDomain -> assignDomain Core.Base.imp
val getItvMode : mode -> Cond.Term.t -> t -> I.t Core.Base.imp
val pr : t -> char list
val to_string : (PVar.t -> char list) -> t -> char list
type rep = DP.rep
val backend_rep :
t -> (DP.rep*((PVar.t -> positive)*(positive -> PVar.t))) option
val meet : t -> t -> t Core.Base.imp
end
module MakeZ :
functor (D:sig
type t
val isIncl : t -> t -> bool Core.Base.imp
val top : t
val join : t -> t -> t Core.Base.imp
val widen : t -> t -> t Core.Base.imp
val bottom : t
val isBottom : t -> bool Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
end) ->
functor (QCstrD:sig
val assume : Cstr.t -> D.t -> D.t Core.Base.imp
end) ->
functor (QItvD:sig
val getItvMode : mode -> QAffTerm.t -> D.t -> QItv.t Core.Base.imp
end) ->
functor (R:sig
val rename : PVar.t -> PVar.t -> D.t -> D.t Core.Base.imp
end) ->
functor (DP:sig
val pr : D.t -> char list
val to_string : (PVar.t -> char list) -> D.t -> char list
type rep
val backend_rep :
D.t -> (rep*((PVar.t -> PVar.t)*(PVar.t -> PVar.t))) option
val meet : D.t -> D.t -> D.t Core.Base.imp
end) ->
sig
module BasicD :
sig
type t = D.t
val isIncl : D.t -> D.t -> bool Core.Base.imp
val top : D.t
val bottom : t
val isBottom : t -> bool Core.Base.imp
val widen : D.t -> D.t -> D.t Core.Base.imp
val join : D.t -> D.t -> D.t Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
val rename : PVar.t -> PVar.t -> t -> t Core.Base.imp
val pr : t -> char list
val to_string : (PVar.t -> char list) -> D.t -> char list
type rep = DP.rep
val backend_rep :
D.t -> (DP.rep*((PVar.t -> PVar.t)*(PVar.t -> PVar.t))) option
val meet : D.t -> D.t -> D.t Core.Base.imp
end
module ZNItvD :
sig
val getItvMode :
mode -> BasicZTerm.term -> BasicD.t -> ZNItv.itv Core.Base.imp
end
module CstrD :
sig
val assume : ZtoQCstr.t -> BasicD.t -> BasicD.t Core.Base.imp
end
module AtomicD :
sig
type t = D.t
val isIncl : D.t -> D.t -> bool Core.Base.imp
val top : D.t
val bottom : t
val isBottom : t -> bool Core.Base.imp
val widen : D.t -> D.t -> D.t Core.Base.imp
val join : D.t -> D.t -> D.t Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
val rename : PVar.t -> PVar.t -> t -> t Core.Base.imp
val pr : t -> char list
val to_string : (PVar.t -> char list) -> D.t -> char list
type rep = DP.rep
val backend_rep :
D.t -> (DP.rep*((PVar.t -> PVar.t)*(PVar.t -> PVar.t))) option
val meet : D.t -> D.t -> D.t Core.Base.imp
val affAssumeLe : ZAffTerm.t -> BasicD.t -> BasicD.t Core.Base.imp
val affAssumeLt : ZAffTerm.affTerm -> BasicD.t -> BasicD.t Core.Base.imp
val affAssumeGt : ZAffTerm.affTerm -> BasicD.t -> BasicD.t Core.Base.imp
val affAssume : cmpG -> ZAffTerm.t -> BasicD.t -> BasicD.t Core.Base.imp
val add_variable :
BasicD.t -> PVar.t -> ZNItv.t PositiveMap.t -> ZNItv.t PositiveMap.t
Core.Base.imp
val get_variables :
BasicD.t -> ZTerm.term -> ZNItv.t PositiveMap.t Core.Base.imp
val mitv_find : ZNItv.t PositiveMap.t -> PositiveMap.key -> ZNItv.t
val intervalize :
(PVar.t -> ZNItv.t) -> bool -> mode -> ZTerm.term -> BasicD.t ->
ZNItv.t Core.Base.imp
module G :
sig
type cdac =
BasicD.t -> BasicD.t Core.Base.imp
(* singleton inductive, whose constructor was raw_build_cdac *)
val impl : cdac -> BasicD.t -> BasicD.t Core.Base.imp
val build_cdac :
(BasicD.t -> BasicD.t Core.Base.imp) -> (ZNum.t Mem.t -> ZNum.t Mem.t
MPP_Definitions.coq_MPP) -> cdac
val spec : cdac -> ZNum.t Mem.t -> ZNum.t Mem.t MPP_Definitions.coq_MPP
val cast :
cdac -> (ZNum.t Mem.t -> ZNum.t Mem.t MPP_Definitions.coq_MPP) -> cdac
val skip : cdac
val fail : char list -> cdac
val seq : cdac -> cdac -> cdac
val join : cdac -> cdac -> cdac
val loop : cdac -> (BasicD.t -> BasicD.t Core.Base.imp) -> cdac
val skip_info : char list
val coq_try : 'a1 option -> ('a1 -> cdac) -> cdac
val bind :
(BasicD.t -> 'a1 Core.Base.imp) -> ('a1 -> cdac) -> __ -> cdac
end
val gAffAssumeLe : ZAffTerm.t -> G.cdac
val gAffAssumeLt : ZAffTerm.affTerm -> G.cdac
val gAffAssumeGt : ZAffTerm.affTerm -> G.cdac
val gIntervalize :
(PVar.t -> ZNItv.t) -> bool -> mode -> ZTerm.term -> (ZNItv.t ->
G.cdac) -> G.cdac
val intervalizeG :
(PVar.t -> ZNItv.t) -> bool -> mode -> ZTerm.t -> (NAItv.itv -> G.cdac)
-> G.cdac
val castAFFINE_error : char list
val castAFFINE : BasicZTerm.term -> (ZAffTerm.t -> G.cdac) -> G.cdac
val caseSign :
BasicZTerm.term -> (ZAffTerm.t -> G.cdac) -> (ZAffTerm.t -> G.cdac) ->
G.cdac
val linearizeMul :
(PVar.t -> ZNItv.t) -> bool -> mode -> ZTerm.term -> ZTerm.term ->
(NAItv.itv -> G.cdac) -> G.cdac
val linearizeG :
(PVar.t -> ZNItv.t) -> bool -> mode -> ZTerm.term -> (NAItv.itv ->
G.cdac) -> G.cdac
val linearizeGX :
(PVar.t -> ZNItv.t) -> bool -> mode -> ZTerm.term -> (NAItv.itv ->
G.cdac) -> G.cdac
val assumeOpCPS :
(PVar.t -> ZNItv.t) -> bool -> cmpG -> ZTerm.term -> ZAffTerm.affTerm
-> G.cdac
val assumeOpAnnot :
(PVar.t -> ZNItv.t) -> bool -> cmpG -> ZTerm.term -> ZAffTerm.affTerm
-> G.cdac
module ZPeq :
sig
module M1 :
sig
val toPExpr : ZTerm.term -> coq_PExpr
end
module M2 :
sig
val toPExpr : ZTerm.term -> coq_PExpr
end
val pomial_eq : ZTerm.t -> ZTerm.t -> bool
end
val test_eq : ZTerm.t -> ZTerm.t -> ZTerm.t
val skip_oracle : ZTerm.t -> bool
val assumeOpFromOracle :
(PVar.t -> ZNItv.t) -> bool -> linearizeContext -> cmpG -> ZTerm.t ->
ZAffTerm.affTerm -> G.cdac
val assumeOp2 :
(PVar.t -> ZNItv.t) -> bool -> linearizeContext -> cmpG -> ZTerm.term
-> ZAffTerm.affTerm -> G.cdac
val assumeOp :
bool -> cmpG -> ZTerm.t -> ZAffTerm.t -> ZTerm.t -> BasicD.t ->
BasicD.t Core.Base.imp
val assume : ZAtomicCond.t -> BasicD.t -> BasicD.t Core.Base.imp
val getItvMode : mode -> ZTerm.term -> BasicD.t -> ZNItv.t Core.Base.imp
end
module Dom :
sig
type t = AtomicD.t
val isIncl : t -> t -> bool Core.Base.imp
val top : t
val join : t -> t -> t Core.Base.imp
val widen : t -> t -> t Core.Base.imp
val bottom : t
val isBottom : t -> bool Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
val skipBottom :
AtomicD.t -> AtomicD.t Core.Base.imp -> AtomicD.t Core.Base.imp
val assumeRec : ZCond.t -> AtomicD.t -> AtomicD.t Core.Base.imp
val assume : ZCond.cond -> AtomicD.t -> AtomicD.t Core.Base.imp
module Naive :
sig
val coq_assert : ZCond.cond -> t -> bool Core.Base.imp
end
val assertRec : ZCond.t -> t -> bool Core.Base.imp
val coq_assert : ZCond.t -> t -> bool Core.Base.imp
end
val encode : bool -> positive -> positive
val decode : positive -> positive
val encodeE : PositiveSet.t -> positive -> positive
val encodeO : PositiveSet.t -> positive -> positive
val decodeIn :
PositiveSet.t -> ZNum.t Mem.t -> ZNum.t Mem.t -> positive -> ZNum.t
val switch : PositiveSet.t -> positive -> PositiveSet.t
type assignDomain = { pol : Dom.t; renaming : PositiveSet.t }
val pol : assignDomain -> Dom.t
val renaming : assignDomain -> PositiveSet.t
type t = assignDomain
val top : t
val bottom : t
val isBottom : t -> bool Core.Base.imp
val assume : ZCond.cond -> t -> t Core.Base.imp
val coq_assert : ZCond.cond -> t -> bool Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
val guassignAux : positive -> ZCond.cond -> t -> t Core.Base.imp
val guassign : PVar.t -> ZCond.cond -> t -> t Core.Base.imp
val assign : positive -> ZCond.Term.term -> t -> t Core.Base.imp
val nop : PVar.t -> assignDomain -> t Core.Base.imp
val switchAll : PositiveSet.t -> t -> t Core.Base.imp
val isIncl : t -> t -> bool Core.Base.imp
val join : t -> t -> t Core.Base.imp
val widen : t -> t -> t Core.Base.imp
val rename :
positive -> positive -> assignDomain -> assignDomain Core.Base.imp
val getItvMode : mode -> ZCond.Term.t -> t -> ZNItv.t Core.Base.imp
val pr : t -> char list
val to_string : (PVar.t -> char list) -> t -> char list
type rep = AtomicD.rep
val backend_rep :
t -> (AtomicD.rep*((PVar.t -> positive)*(positive -> PVar.t))) option
val meet : t -> t -> t Core.Base.imp
end
| null | https://raw.githubusercontent.com/VERIMAG-Polyhedra/VPL/cd78d6e7d120508fd5a694bdb01300477e5646f8/ocaml/extracted/DomainFunctors.mli | ocaml | singleton inductive, whose constructor was raw_build_cdac | open ASAtomicCond
open ASCond
open ASTerm
open BinInt
open BinNums
open CstrC
open Datatypes
open Debugging
open DomainInterfaces
open FMapPositive
open ImpureConfig
open Itv
open LinTerm
open LinearizeBackend
open MSetPositive
open NumC
open PredTrans
open ProgVar
open Ring_polynom_AddOn
open String0
open ZNone
open ZNoneItv
type __ = Obj.t
module MakeFull :
functor (N:NumSig) ->
functor (Cond:sig
module Term :
sig
module Annot :
sig
type topLevelAnnot = TopLevelAnnot.topLevelAnnot =
| OLD
| AFFINE
| INTERV
| STATIC
| SKIP_ORACLE
val topLevelAnnot_rect :
'a1 -> 'a1 -> 'a1 -> 'a1 -> 'a1 -> topLevelAnnot -> 'a1
val topLevelAnnot_rec :
'a1 -> 'a1 -> 'a1 -> 'a1 -> 'a1 -> topLevelAnnot -> 'a1
type t = topLevelAnnot
val pr : topLevelAnnot -> char list
end
type term =
| Var of PVar.t
| Cte of N.t
| Add of term * term
| Opp of term
| Mul of term * term
| Annot of Annot.topLevelAnnot * term
val term_rect :
(PVar.t -> 'a1) -> (N.t -> 'a1) -> (term -> 'a1 -> term -> 'a1 -> 'a1)
-> (term -> 'a1 -> 'a1) -> (term -> 'a1 -> term -> 'a1 -> 'a1) ->
(Annot.topLevelAnnot -> term -> 'a1 -> 'a1) -> term -> 'a1
val term_rec :
(PVar.t -> 'a1) -> (N.t -> 'a1) -> (term -> 'a1 -> term -> 'a1 -> 'a1)
-> (term -> 'a1 -> 'a1) -> (term -> 'a1 -> term -> 'a1 -> 'a1) ->
(Annot.topLevelAnnot -> term -> 'a1 -> 'a1) -> term -> 'a1
type t = term
val eval : term -> N.t Mem.t -> N.t
val mdBound : term -> PVar.t -> PVar.t
val fold_variables : term -> (PVar.t -> 'a1 -> 'a1) -> 'a1 -> 'a1
val map : term -> PVar.t Mem.t -> term
val pseudoIsZero : term -> bool
val smartScalAdd1 : N.t -> term -> term
val smartScalAdd : N.t -> term -> term
val smartAdd : term -> term -> term
val smartOpp : term -> term
val smartScalMul1 : N.t -> term -> term
val smartScalMul : N.t -> term -> term
val smartMul : term -> term -> term
val smartAnnot : Annot.topLevelAnnot -> term -> term
val import_acc : (PVar.t*N.t) list -> term -> term
val import : (PVar.t*N.t) list -> term
val coq_Old : term -> term
val xeval : term -> N.t Mem.t -> N.t Mem.t -> N.t
val xmap : term -> PVar.t Mem.t -> PVar.t Mem.t -> term
val isCte : term -> bool
val annotAFFINEx : term -> term
val annotAFFINE_rec : term -> term option
val annotAFFINE : term -> term
val matchCte : term -> N.t option
val pr : term -> char list
end
type cond =
| Basic of bool
| Atom of cmpG * Term.term * Term.term
| BinL of binl * cond * cond
| Not of cond
val cond_rect :
(bool -> 'a1) -> (cmpG -> Term.term -> Term.term -> 'a1) -> (binl -> cond
-> 'a1 -> cond -> 'a1 -> 'a1) -> (cond -> 'a1 -> 'a1) -> cond -> 'a1
val cond_rec :
(bool -> 'a1) -> (cmpG -> Term.term -> Term.term -> 'a1) -> (binl -> cond
-> 'a1 -> cond -> 'a1 -> 'a1) -> (cond -> 'a1 -> 'a1) -> cond -> 'a1
type t = cond
val sat_dec : t -> N.t Mem.t -> bool
val xsat_dec : t -> N.t Mem.t -> N.t Mem.t -> bool
val mdBound : cond -> positive -> positive
val map : cond -> PVar.t Mem.t -> cond
val xmap : cond -> PVar.t Mem.t -> PVar.t Mem.t -> cond
val dual : cmpG -> Term.term -> Term.term -> t
val nnf : t -> t
val nnfNot : t -> t
end) ->
functor (I:sig
type t
end) ->
functor (AtomC:sig
type atomicCond = { cmpOp : cmpG; right : Cond.Term.t }
val cmpOp : atomicCond -> cmpG
val right : atomicCond -> Cond.Term.t
type t = atomicCond
val make : Cond.Term.term -> cmpG -> Cond.Term.term -> t
end) ->
functor (D:sig
type t
val isIncl : t -> t -> bool Core.Base.imp
val top : t
val join : t -> t -> t Core.Base.imp
val widen : t -> t -> t Core.Base.imp
val bottom : t
val isBottom : t -> bool Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
end) ->
functor (AtomD:sig
val assume : AtomC.t -> D.t -> D.t Core.Base.imp
end) ->
functor (R:sig
val rename : PVar.t -> PVar.t -> D.t -> D.t Core.Base.imp
end) ->
functor (DI:sig
val getItvMode : mode -> Cond.Term.t -> D.t -> I.t Core.Base.imp
end) ->
functor (DP:sig
val pr : D.t -> char list
val to_string : (PVar.t -> char list) -> D.t -> char list
type rep
val backend_rep :
D.t -> (rep*((PVar.t -> PVar.t)*(PVar.t -> PVar.t))) option
val meet : D.t -> D.t -> D.t Core.Base.imp
end) ->
sig
module Dom :
sig
type t = D.t
val isIncl : t -> t -> bool Core.Base.imp
val top : t
val join : t -> t -> t Core.Base.imp
val widen : t -> t -> t Core.Base.imp
val bottom : t
val isBottom : t -> bool Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
val skipBottom : D.t -> D.t Core.Base.imp -> D.t Core.Base.imp
val assumeRec : Cond.t -> D.t -> D.t Core.Base.imp
val assume : Cond.cond -> D.t -> D.t Core.Base.imp
module Naive :
sig
val coq_assert : Cond.cond -> t -> bool Core.Base.imp
end
val assertRec : Cond.t -> t -> bool Core.Base.imp
val coq_assert : Cond.t -> t -> bool Core.Base.imp
end
val encode : bool -> positive -> positive
val decode : positive -> positive
val encodeE : PositiveSet.t -> positive -> positive
val encodeO : PositiveSet.t -> positive -> positive
val decodeIn : PositiveSet.t -> N.t Mem.t -> N.t Mem.t -> positive -> N.t
val switch : PositiveSet.t -> positive -> PositiveSet.t
type assignDomain = { pol : Dom.t; renaming : PositiveSet.t }
val pol : assignDomain -> Dom.t
val renaming : assignDomain -> PositiveSet.t
type t = assignDomain
val top : t
val bottom : t
val isBottom : t -> bool Core.Base.imp
val assume : Cond.cond -> t -> t Core.Base.imp
val coq_assert : Cond.cond -> t -> bool Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
val guassignAux : positive -> Cond.cond -> t -> t Core.Base.imp
val guassign : PVar.t -> Cond.cond -> t -> t Core.Base.imp
val assign : positive -> Cond.Term.term -> t -> t Core.Base.imp
val nop : PVar.t -> assignDomain -> t Core.Base.imp
val switchAll : PositiveSet.t -> t -> t Core.Base.imp
val isIncl : t -> t -> bool Core.Base.imp
val join : t -> t -> t Core.Base.imp
val widen : t -> t -> t Core.Base.imp
val rename :
positive -> positive -> assignDomain -> assignDomain Core.Base.imp
val getItvMode : mode -> Cond.Term.t -> t -> I.t Core.Base.imp
val pr : t -> char list
val to_string : (PVar.t -> char list) -> t -> char list
type rep = DP.rep
val backend_rep :
t -> (DP.rep*((PVar.t -> positive)*(positive -> PVar.t))) option
val meet : t -> t -> t Core.Base.imp
end
module MakeZ :
functor (D:sig
type t
val isIncl : t -> t -> bool Core.Base.imp
val top : t
val join : t -> t -> t Core.Base.imp
val widen : t -> t -> t Core.Base.imp
val bottom : t
val isBottom : t -> bool Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
end) ->
functor (QCstrD:sig
val assume : Cstr.t -> D.t -> D.t Core.Base.imp
end) ->
functor (QItvD:sig
val getItvMode : mode -> QAffTerm.t -> D.t -> QItv.t Core.Base.imp
end) ->
functor (R:sig
val rename : PVar.t -> PVar.t -> D.t -> D.t Core.Base.imp
end) ->
functor (DP:sig
val pr : D.t -> char list
val to_string : (PVar.t -> char list) -> D.t -> char list
type rep
val backend_rep :
D.t -> (rep*((PVar.t -> PVar.t)*(PVar.t -> PVar.t))) option
val meet : D.t -> D.t -> D.t Core.Base.imp
end) ->
sig
module BasicD :
sig
type t = D.t
val isIncl : D.t -> D.t -> bool Core.Base.imp
val top : D.t
val bottom : t
val isBottom : t -> bool Core.Base.imp
val widen : D.t -> D.t -> D.t Core.Base.imp
val join : D.t -> D.t -> D.t Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
val rename : PVar.t -> PVar.t -> t -> t Core.Base.imp
val pr : t -> char list
val to_string : (PVar.t -> char list) -> D.t -> char list
type rep = DP.rep
val backend_rep :
D.t -> (DP.rep*((PVar.t -> PVar.t)*(PVar.t -> PVar.t))) option
val meet : D.t -> D.t -> D.t Core.Base.imp
end
module ZNItvD :
sig
val getItvMode :
mode -> BasicZTerm.term -> BasicD.t -> ZNItv.itv Core.Base.imp
end
module CstrD :
sig
val assume : ZtoQCstr.t -> BasicD.t -> BasicD.t Core.Base.imp
end
module AtomicD :
sig
type t = D.t
val isIncl : D.t -> D.t -> bool Core.Base.imp
val top : D.t
val bottom : t
val isBottom : t -> bool Core.Base.imp
val widen : D.t -> D.t -> D.t Core.Base.imp
val join : D.t -> D.t -> D.t Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
val rename : PVar.t -> PVar.t -> t -> t Core.Base.imp
val pr : t -> char list
val to_string : (PVar.t -> char list) -> D.t -> char list
type rep = DP.rep
val backend_rep :
D.t -> (DP.rep*((PVar.t -> PVar.t)*(PVar.t -> PVar.t))) option
val meet : D.t -> D.t -> D.t Core.Base.imp
val affAssumeLe : ZAffTerm.t -> BasicD.t -> BasicD.t Core.Base.imp
val affAssumeLt : ZAffTerm.affTerm -> BasicD.t -> BasicD.t Core.Base.imp
val affAssumeGt : ZAffTerm.affTerm -> BasicD.t -> BasicD.t Core.Base.imp
val affAssume : cmpG -> ZAffTerm.t -> BasicD.t -> BasicD.t Core.Base.imp
val add_variable :
BasicD.t -> PVar.t -> ZNItv.t PositiveMap.t -> ZNItv.t PositiveMap.t
Core.Base.imp
val get_variables :
BasicD.t -> ZTerm.term -> ZNItv.t PositiveMap.t Core.Base.imp
val mitv_find : ZNItv.t PositiveMap.t -> PositiveMap.key -> ZNItv.t
val intervalize :
(PVar.t -> ZNItv.t) -> bool -> mode -> ZTerm.term -> BasicD.t ->
ZNItv.t Core.Base.imp
module G :
sig
type cdac =
BasicD.t -> BasicD.t Core.Base.imp
val impl : cdac -> BasicD.t -> BasicD.t Core.Base.imp
val build_cdac :
(BasicD.t -> BasicD.t Core.Base.imp) -> (ZNum.t Mem.t -> ZNum.t Mem.t
MPP_Definitions.coq_MPP) -> cdac
val spec : cdac -> ZNum.t Mem.t -> ZNum.t Mem.t MPP_Definitions.coq_MPP
val cast :
cdac -> (ZNum.t Mem.t -> ZNum.t Mem.t MPP_Definitions.coq_MPP) -> cdac
val skip : cdac
val fail : char list -> cdac
val seq : cdac -> cdac -> cdac
val join : cdac -> cdac -> cdac
val loop : cdac -> (BasicD.t -> BasicD.t Core.Base.imp) -> cdac
val skip_info : char list
val coq_try : 'a1 option -> ('a1 -> cdac) -> cdac
val bind :
(BasicD.t -> 'a1 Core.Base.imp) -> ('a1 -> cdac) -> __ -> cdac
end
val gAffAssumeLe : ZAffTerm.t -> G.cdac
val gAffAssumeLt : ZAffTerm.affTerm -> G.cdac
val gAffAssumeGt : ZAffTerm.affTerm -> G.cdac
val gIntervalize :
(PVar.t -> ZNItv.t) -> bool -> mode -> ZTerm.term -> (ZNItv.t ->
G.cdac) -> G.cdac
val intervalizeG :
(PVar.t -> ZNItv.t) -> bool -> mode -> ZTerm.t -> (NAItv.itv -> G.cdac)
-> G.cdac
val castAFFINE_error : char list
val castAFFINE : BasicZTerm.term -> (ZAffTerm.t -> G.cdac) -> G.cdac
val caseSign :
BasicZTerm.term -> (ZAffTerm.t -> G.cdac) -> (ZAffTerm.t -> G.cdac) ->
G.cdac
val linearizeMul :
(PVar.t -> ZNItv.t) -> bool -> mode -> ZTerm.term -> ZTerm.term ->
(NAItv.itv -> G.cdac) -> G.cdac
val linearizeG :
(PVar.t -> ZNItv.t) -> bool -> mode -> ZTerm.term -> (NAItv.itv ->
G.cdac) -> G.cdac
val linearizeGX :
(PVar.t -> ZNItv.t) -> bool -> mode -> ZTerm.term -> (NAItv.itv ->
G.cdac) -> G.cdac
val assumeOpCPS :
(PVar.t -> ZNItv.t) -> bool -> cmpG -> ZTerm.term -> ZAffTerm.affTerm
-> G.cdac
val assumeOpAnnot :
(PVar.t -> ZNItv.t) -> bool -> cmpG -> ZTerm.term -> ZAffTerm.affTerm
-> G.cdac
module ZPeq :
sig
module M1 :
sig
val toPExpr : ZTerm.term -> coq_PExpr
end
module M2 :
sig
val toPExpr : ZTerm.term -> coq_PExpr
end
val pomial_eq : ZTerm.t -> ZTerm.t -> bool
end
val test_eq : ZTerm.t -> ZTerm.t -> ZTerm.t
val skip_oracle : ZTerm.t -> bool
val assumeOpFromOracle :
(PVar.t -> ZNItv.t) -> bool -> linearizeContext -> cmpG -> ZTerm.t ->
ZAffTerm.affTerm -> G.cdac
val assumeOp2 :
(PVar.t -> ZNItv.t) -> bool -> linearizeContext -> cmpG -> ZTerm.term
-> ZAffTerm.affTerm -> G.cdac
val assumeOp :
bool -> cmpG -> ZTerm.t -> ZAffTerm.t -> ZTerm.t -> BasicD.t ->
BasicD.t Core.Base.imp
val assume : ZAtomicCond.t -> BasicD.t -> BasicD.t Core.Base.imp
val getItvMode : mode -> ZTerm.term -> BasicD.t -> ZNItv.t Core.Base.imp
end
module Dom :
sig
type t = AtomicD.t
val isIncl : t -> t -> bool Core.Base.imp
val top : t
val join : t -> t -> t Core.Base.imp
val widen : t -> t -> t Core.Base.imp
val bottom : t
val isBottom : t -> bool Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
val skipBottom :
AtomicD.t -> AtomicD.t Core.Base.imp -> AtomicD.t Core.Base.imp
val assumeRec : ZCond.t -> AtomicD.t -> AtomicD.t Core.Base.imp
val assume : ZCond.cond -> AtomicD.t -> AtomicD.t Core.Base.imp
module Naive :
sig
val coq_assert : ZCond.cond -> t -> bool Core.Base.imp
end
val assertRec : ZCond.t -> t -> bool Core.Base.imp
val coq_assert : ZCond.t -> t -> bool Core.Base.imp
end
val encode : bool -> positive -> positive
val decode : positive -> positive
val encodeE : PositiveSet.t -> positive -> positive
val encodeO : PositiveSet.t -> positive -> positive
val decodeIn :
PositiveSet.t -> ZNum.t Mem.t -> ZNum.t Mem.t -> positive -> ZNum.t
val switch : PositiveSet.t -> positive -> PositiveSet.t
type assignDomain = { pol : Dom.t; renaming : PositiveSet.t }
val pol : assignDomain -> Dom.t
val renaming : assignDomain -> PositiveSet.t
type t = assignDomain
val top : t
val bottom : t
val isBottom : t -> bool Core.Base.imp
val assume : ZCond.cond -> t -> t Core.Base.imp
val coq_assert : ZCond.cond -> t -> bool Core.Base.imp
val project : t -> PVar.t -> t Core.Base.imp
val guassignAux : positive -> ZCond.cond -> t -> t Core.Base.imp
val guassign : PVar.t -> ZCond.cond -> t -> t Core.Base.imp
val assign : positive -> ZCond.Term.term -> t -> t Core.Base.imp
val nop : PVar.t -> assignDomain -> t Core.Base.imp
val switchAll : PositiveSet.t -> t -> t Core.Base.imp
val isIncl : t -> t -> bool Core.Base.imp
val join : t -> t -> t Core.Base.imp
val widen : t -> t -> t Core.Base.imp
val rename :
positive -> positive -> assignDomain -> assignDomain Core.Base.imp
val getItvMode : mode -> ZCond.Term.t -> t -> ZNItv.t Core.Base.imp
val pr : t -> char list
val to_string : (PVar.t -> char list) -> t -> char list
type rep = AtomicD.rep
val backend_rep :
t -> (AtomicD.rep*((PVar.t -> positive)*(positive -> PVar.t))) option
val meet : t -> t -> t Core.Base.imp
end
|
8921bad95b1a8473cab0f7a1fd3a19d8f548ab14799598ded8afb3bd4260f837 | obsidiansystems/dependent-map | Typeable.hs | # LANGUAGE Trustworthy #
module Data.Dependent.Map.Typeable where
import Data.Dependent.Map.Internal
import Data.Typeable
instance (Typeable1 k, Typeable1 f) => Typeable (DMap k f) where
typeOf ds = mkTyConApp dMapCon [typeOfK, typeOfF]
where
typeOfK = typeOf1 $ (undefined :: DMap k f -> k a) ds
typeOfF = typeOf1 $ (undefined :: DMap k f -> f a) ds
dMapCon = mkTyCon3 "dependent-map" "Data.Dependent.Map" "DMap"
| null | https://raw.githubusercontent.com/obsidiansystems/dependent-map/26677886eced970d661a5a7356ba4fe221c0324c/src/Data/Dependent/Map/Typeable.hs | haskell | # LANGUAGE Trustworthy #
module Data.Dependent.Map.Typeable where
import Data.Dependent.Map.Internal
import Data.Typeable
instance (Typeable1 k, Typeable1 f) => Typeable (DMap k f) where
typeOf ds = mkTyConApp dMapCon [typeOfK, typeOfF]
where
typeOfK = typeOf1 $ (undefined :: DMap k f -> k a) ds
typeOfF = typeOf1 $ (undefined :: DMap k f -> f a) ds
dMapCon = mkTyCon3 "dependent-map" "Data.Dependent.Map" "DMap"
| |
5aa23491a82258a91c287159ba189133a0fb286dd52fa0e2992d89ed83dd1d97 | DaveWM/willa | experiment.clj | (ns willa.experiment
(:require [loom.graph :as l]
[loom.alg :as lalg]
[willa.core :as w]
[clojure.math.combinatorics :as combo]
[willa.utils :as wu])
(:import (org.apache.kafka.streams.kstream JoinWindows TimeWindows SessionWindows)))
(defn join-kstream-results [left-results right-results ^JoinWindows window {:keys [left-join right-join join-fn]
:or {join-fn vector}}]
(let [before-ms (.beforeMs window)
after-ms (.afterMs window)
joined-results (->> (combo/cartesian-product left-results right-results)
(filter (fn [[r1 r2]]
(and (= (:key r1) (:key r2))
(<= (- (:timestamp r1) before-ms) (:timestamp r2))
(<= (:timestamp r2) (+ (:timestamp r1) after-ms)))))
(map (fn [[l r]]
{:key (:key l)
:timestamp (max (:timestamp l) (or (:timestamp r) 0))
:value (join-fn (:value l) (:value r))})))
left-unjoined-results (->> left-results
(map (fn [result] (update result :value cons [nil]))))
right-unjoined-results (->> right-results
(map (fn [result] (update result :value #(-> [nil %])))))]
(cond->> joined-results
left-join (concat left-unjoined-results)
right-join (concat right-unjoined-results)
true (group-by (juxt :timestamp :key))
true (mapcat (fn [[t rs]]
(if (< 1 (count rs))
(remove (fn [result] (some nil? (:value result))) rs)
rs))))))
(defn join-ktable-results [left-results right-results {:keys [left-join right-join join-fn]
:or {join-fn vector}}]
(let [sorted-left-results (sort-by :timestamp left-results)
sorted-right-results (sort-by :timestamp right-results)
left-joined (->> left-results
(map (fn [result]
[result
(->> sorted-right-results
(filter #(and (<= (:timestamp %) (:timestamp result))
(= (:key %) (:key result))))
last)])))
right-joined (->> right-results
(map (fn [result]
[(->> sorted-left-results
(filter #(and (<= (:timestamp %) (:timestamp result))
(= (:key %) (:key result))))
last)
result])))]
(->> (concat left-joined right-joined)
(filter (fn [[l r]]
(and (or (not left-join) (some? l))
(or (not right-join) (some? r)))))
(map (fn [[l r]]
{:key (:key (or l r))
:value (join-fn (:value l) (:value r))
:timestamp ((fnil max 0 0) (:timestamp l) (:timestamp r))})))))
(defn join-kstream-ktable-results [kstream-results ktable-results {:keys [left-join right-join join-fn]
:or {join-fn vector}}]
(let [sorted-right-results (sort-by :timestamp ktable-results)
left-joined (->> kstream-results
(map (fn [result]
[result
(->> sorted-right-results
(filter #(and (<= (:timestamp %) (:timestamp result))
(= (:key %) (:key result))))
last)])))]
(->> left-joined
(filter (fn [[l r]]
(and (or (not left-join) (some? l))
(or (not right-join) (some? r)))))
(map (fn [[l r]]
{:key (:key (or l r))
:value (join-fn (:value l) (:value r))
:timestamp ((fnil max 0 0) (:timestamp l) (:timestamp r))})))))
(defmulti join-entities* (fn [join-config entity other join-fn]
[(::w/join-type join-config) (::w/entity-type entity) (::w/entity-type other)]))
(defmethod join-entities* [:inner :kstream :kstream] [join-config entity other join-fn]
(assoc entity ::output
(join-kstream-results (::output entity) (::output other) (::w/window join-config) {:left-join false
:right-join false
:join-fn join-fn})))
(defmethod join-entities* [:left :kstream :kstream] [join-config entity other join-fn]
(assoc entity ::output
(join-kstream-results (::output entity) (::output other) (::w/window join-config) {:left-join true
:right-join false
:join-fn join-fn})))
(defmethod join-entities* [:outer :kstream :kstream] [join-config entity other join-fn]
(assoc entity ::output
(join-kstream-results (::output entity) (::output other) (::w/window join-config) {:left-join true
:right-join true
:join-fn join-fn})))
(defmethod join-entities* [:merge :kstream :kstream] [_ entity other _]
(update entity ::output concat (::output other)))
(defmethod join-entities* [:inner :ktable :ktable] [_ entity other join-fn]
(assoc entity ::output (join-ktable-results (::output entity) (::output other) {:left-join true
:right-join true
:join-fn join-fn})))
(defmethod join-entities* [:left :ktable :ktable] [_ entity other join-fn]
(assoc entity ::output (join-ktable-results (::output entity) (::output other) {:left-join true
:right-join false
:join-fn join-fn})))
(defmethod join-entities* [:outer :ktable :ktable] [_ entity other join-fn]
(assoc entity ::output (join-ktable-results (::output entity) (::output other) {:left-join false
:right-join false
:join-fn join-fn})))
(defmethod join-entities* [:inner :kstream :ktable] [_ entity other join-fn]
(assoc entity ::output (join-kstream-ktable-results (::output entity) (::output other) {:left-join true
:right-join true
:join-fn join-fn})))
(defmethod join-entities* [:left :kstream :ktable] [_ entity other join-fn]
(assoc entity ::output (join-kstream-ktable-results (::output entity) (::output other) {:left-join true
:right-join false
:join-fn join-fn})))
(defn ->joinable [entity]
(if (= :topic (::w/entity-type entity))
;; treat topics as streams
(assoc entity ::w/entity-type :kstream)
entity))
(defn join-entities
([_ entity] entity)
([join-config entity other]
(join-entities* join-config entity other vector))
([join-config entity o1 o2 & others]
(apply join-entities
join-config
(join-entities* join-config (join-entities join-config entity o1) o2 (fn [vs v] (conj vs v)))
others)))
(defmulti determine-windows (fn [window records]
(type window)))
(defmethod determine-windows TimeWindows [^TimeWindows window records]
(let [[earliest-timestamp latest-timestamp] (->> records
(sort-by :timestamp)
(map :timestamp)
((juxt first last)))
window-start (- earliest-timestamp (mod earliest-timestamp (.advanceMs window)))
window-end (+ latest-timestamp (- (.advanceMs window) (mod latest-timestamp (.-advanceMs window))))]
(->> (range window-start window-end (.advanceMs window))
(map (fn [from]
{:from from
:to (dec (+ from (.sizeMs window)))})))))
(defmethod determine-windows SessionWindows [^SessionWindows window records]
(loop [windows []
rs records]
(if (empty? rs)
windows
(let [[rs-in-window other-rs] (->> rs
(partition-all 2 1)
(split-with (fn [[x y]]
(or (not y)
(<= (- (:timestamp y)
(:timestamp x))
(.inactivityGap window))))))
[from to] (->> rs-in-window
(flatten)
(map :timestamp)
((juxt first last)))]
(recur (conj windows {:from from :to (dec (+ to (.inactivityGap window)))})
(map first (rest other-rs)))))))
(defn records-in-window [window records]
(->> records
(filter #(<= (:from window) (:timestamp %) (:to window)))))
(defmulti get-output (fn [entity parents entities joins]
(::w/entity-type entity)))
(defmethod get-output :topic [entity parents entities joins]
(when parents
(let [[join-order join-config] (w/get-join joins parents)
joined-entity (apply join-entities
(or join-config {::w/join-type :merge})
(map (comp ->joinable entities) (or join-order (vec parents))))]
(::output joined-entity))))
(defmethod get-output :kstream [entity parents entities joins]
(let [[join-order join-config] (w/get-join joins parents)
joined-entity (apply join-entities
(or join-config {::w/join-type :merge})
(map (comp ->joinable entities) (or join-order (vec parents))))
xform (get entity ::w/xform (map identity))]
(->> (for [r (::output joined-entity)]
(into []
(comp (map (juxt :key :value))
xform
(map (fn [[k v]] (merge r {:key k :value v}))))
[r]))
(mapcat identity))))
(defmethod get-output :ktable [entity parents entities joins]
(let [[join-order join-config] (w/get-join joins parents)
joined-entity (apply join-entities
(or join-config {::w/join-type :merge})
(map (comp ->joinable entities) (or join-order (vec parents))))]
(cond->> (::output joined-entity)
true (sort-by :timestamp)
(::w/group-by-fn entity) (group-by (fn [r]
((::w/group-by-fn entity) ((juxt :key :value) r))))
(::w/window entity) (mapcat (fn [[g rs]]
(for [w (determine-windows (::w/window entity) rs)]
[^:windowed [g w] (records-in-window w rs)])))
(::w/aggregate-adder-fn entity) (mapcat (fn [[g rs]]
(->> (reductions (fn [acc r]
(assoc r
:key (if (:windowed (meta g)) (first g) g)
:value ((::w/aggregate-adder-fn entity) (:value acc) [g (:value r)])))
{:value (::w/aggregate-initial-value entity)}
rs)
(drop 1)))))))
(defn run-experiment [{:keys [workflow entities joins] :as topology} entity->records]
(let [g (wu/->graph workflow)
initial-entities (->> entities
(map (fn [[k v]] [k (assoc v ::output (get entity->records k))]))
(into {}))]
(assoc topology :entities
(->> g
(lalg/topsort)
(map (juxt identity (partial l/predecessors g)))
(reduce (fn [processed-entities [node parents]]
(update processed-entities node
(fn [entity]
(update entity ::output concat (->> (get-output entity parents processed-entities joins)
(sort-by :timestamp))))))
initial-entities)))))
(defn results-only [experiment-results]
(->> experiment-results
:entities
(map (fn [[k v]]
[k (::output v)]))
(into {})))
(comment
(require 'willa.viz)
(def workflow [[:input-topic :stream]
[:secondary-input-topic :table]
[:stream :output-topic]
[:table :output-topic]])
(def joins {[:stream :table] {::w/join-type :left}})
(def experiment-topology
(run-experiment {:workflow workflow
:entities {:input-topic {::w/entity-type :topic}
:secondary-input-topic {::w/entity-type :topic}
:stream {::w/entity-type :kstream}
:table {::w/entity-type :ktable}
:output-topic {::w/entity-type :topic}}
:joins joins}
{:input-topic [{:key "key"
:value 1
:timestamp 1000}]
:secondary-input-topic [{:key "key"
:value 2
:timestamp 1100}]}))
(results-only experiment-topology)
(willa.viz/view-topology experiment-topology)
)
| null | https://raw.githubusercontent.com/DaveWM/willa/7d927e2f012b147a5810ba36c07683c4459f5f22/src/willa/experiment.clj | clojure | treat topics as streams | (ns willa.experiment
(:require [loom.graph :as l]
[loom.alg :as lalg]
[willa.core :as w]
[clojure.math.combinatorics :as combo]
[willa.utils :as wu])
(:import (org.apache.kafka.streams.kstream JoinWindows TimeWindows SessionWindows)))
(defn join-kstream-results [left-results right-results ^JoinWindows window {:keys [left-join right-join join-fn]
:or {join-fn vector}}]
(let [before-ms (.beforeMs window)
after-ms (.afterMs window)
joined-results (->> (combo/cartesian-product left-results right-results)
(filter (fn [[r1 r2]]
(and (= (:key r1) (:key r2))
(<= (- (:timestamp r1) before-ms) (:timestamp r2))
(<= (:timestamp r2) (+ (:timestamp r1) after-ms)))))
(map (fn [[l r]]
{:key (:key l)
:timestamp (max (:timestamp l) (or (:timestamp r) 0))
:value (join-fn (:value l) (:value r))})))
left-unjoined-results (->> left-results
(map (fn [result] (update result :value cons [nil]))))
right-unjoined-results (->> right-results
(map (fn [result] (update result :value #(-> [nil %])))))]
(cond->> joined-results
left-join (concat left-unjoined-results)
right-join (concat right-unjoined-results)
true (group-by (juxt :timestamp :key))
true (mapcat (fn [[t rs]]
(if (< 1 (count rs))
(remove (fn [result] (some nil? (:value result))) rs)
rs))))))
(defn join-ktable-results [left-results right-results {:keys [left-join right-join join-fn]
:or {join-fn vector}}]
(let [sorted-left-results (sort-by :timestamp left-results)
sorted-right-results (sort-by :timestamp right-results)
left-joined (->> left-results
(map (fn [result]
[result
(->> sorted-right-results
(filter #(and (<= (:timestamp %) (:timestamp result))
(= (:key %) (:key result))))
last)])))
right-joined (->> right-results
(map (fn [result]
[(->> sorted-left-results
(filter #(and (<= (:timestamp %) (:timestamp result))
(= (:key %) (:key result))))
last)
result])))]
(->> (concat left-joined right-joined)
(filter (fn [[l r]]
(and (or (not left-join) (some? l))
(or (not right-join) (some? r)))))
(map (fn [[l r]]
{:key (:key (or l r))
:value (join-fn (:value l) (:value r))
:timestamp ((fnil max 0 0) (:timestamp l) (:timestamp r))})))))
(defn join-kstream-ktable-results [kstream-results ktable-results {:keys [left-join right-join join-fn]
:or {join-fn vector}}]
(let [sorted-right-results (sort-by :timestamp ktable-results)
left-joined (->> kstream-results
(map (fn [result]
[result
(->> sorted-right-results
(filter #(and (<= (:timestamp %) (:timestamp result))
(= (:key %) (:key result))))
last)])))]
(->> left-joined
(filter (fn [[l r]]
(and (or (not left-join) (some? l))
(or (not right-join) (some? r)))))
(map (fn [[l r]]
{:key (:key (or l r))
:value (join-fn (:value l) (:value r))
:timestamp ((fnil max 0 0) (:timestamp l) (:timestamp r))})))))
(defmulti join-entities* (fn [join-config entity other join-fn]
[(::w/join-type join-config) (::w/entity-type entity) (::w/entity-type other)]))
(defmethod join-entities* [:inner :kstream :kstream] [join-config entity other join-fn]
(assoc entity ::output
(join-kstream-results (::output entity) (::output other) (::w/window join-config) {:left-join false
:right-join false
:join-fn join-fn})))
(defmethod join-entities* [:left :kstream :kstream] [join-config entity other join-fn]
(assoc entity ::output
(join-kstream-results (::output entity) (::output other) (::w/window join-config) {:left-join true
:right-join false
:join-fn join-fn})))
(defmethod join-entities* [:outer :kstream :kstream] [join-config entity other join-fn]
(assoc entity ::output
(join-kstream-results (::output entity) (::output other) (::w/window join-config) {:left-join true
:right-join true
:join-fn join-fn})))
(defmethod join-entities* [:merge :kstream :kstream] [_ entity other _]
(update entity ::output concat (::output other)))
(defmethod join-entities* [:inner :ktable :ktable] [_ entity other join-fn]
(assoc entity ::output (join-ktable-results (::output entity) (::output other) {:left-join true
:right-join true
:join-fn join-fn})))
(defmethod join-entities* [:left :ktable :ktable] [_ entity other join-fn]
(assoc entity ::output (join-ktable-results (::output entity) (::output other) {:left-join true
:right-join false
:join-fn join-fn})))
(defmethod join-entities* [:outer :ktable :ktable] [_ entity other join-fn]
(assoc entity ::output (join-ktable-results (::output entity) (::output other) {:left-join false
:right-join false
:join-fn join-fn})))
(defmethod join-entities* [:inner :kstream :ktable] [_ entity other join-fn]
(assoc entity ::output (join-kstream-ktable-results (::output entity) (::output other) {:left-join true
:right-join true
:join-fn join-fn})))
(defmethod join-entities* [:left :kstream :ktable] [_ entity other join-fn]
(assoc entity ::output (join-kstream-ktable-results (::output entity) (::output other) {:left-join true
:right-join false
:join-fn join-fn})))
(defn ->joinable [entity]
(if (= :topic (::w/entity-type entity))
(assoc entity ::w/entity-type :kstream)
entity))
(defn join-entities
([_ entity] entity)
([join-config entity other]
(join-entities* join-config entity other vector))
([join-config entity o1 o2 & others]
(apply join-entities
join-config
(join-entities* join-config (join-entities join-config entity o1) o2 (fn [vs v] (conj vs v)))
others)))
(defmulti determine-windows (fn [window records]
(type window)))
(defmethod determine-windows TimeWindows [^TimeWindows window records]
(let [[earliest-timestamp latest-timestamp] (->> records
(sort-by :timestamp)
(map :timestamp)
((juxt first last)))
window-start (- earliest-timestamp (mod earliest-timestamp (.advanceMs window)))
window-end (+ latest-timestamp (- (.advanceMs window) (mod latest-timestamp (.-advanceMs window))))]
(->> (range window-start window-end (.advanceMs window))
(map (fn [from]
{:from from
:to (dec (+ from (.sizeMs window)))})))))
(defmethod determine-windows SessionWindows [^SessionWindows window records]
(loop [windows []
rs records]
(if (empty? rs)
windows
(let [[rs-in-window other-rs] (->> rs
(partition-all 2 1)
(split-with (fn [[x y]]
(or (not y)
(<= (- (:timestamp y)
(:timestamp x))
(.inactivityGap window))))))
[from to] (->> rs-in-window
(flatten)
(map :timestamp)
((juxt first last)))]
(recur (conj windows {:from from :to (dec (+ to (.inactivityGap window)))})
(map first (rest other-rs)))))))
(defn records-in-window [window records]
(->> records
(filter #(<= (:from window) (:timestamp %) (:to window)))))
(defmulti get-output (fn [entity parents entities joins]
(::w/entity-type entity)))
(defmethod get-output :topic [entity parents entities joins]
(when parents
(let [[join-order join-config] (w/get-join joins parents)
joined-entity (apply join-entities
(or join-config {::w/join-type :merge})
(map (comp ->joinable entities) (or join-order (vec parents))))]
(::output joined-entity))))
(defmethod get-output :kstream [entity parents entities joins]
(let [[join-order join-config] (w/get-join joins parents)
joined-entity (apply join-entities
(or join-config {::w/join-type :merge})
(map (comp ->joinable entities) (or join-order (vec parents))))
xform (get entity ::w/xform (map identity))]
(->> (for [r (::output joined-entity)]
(into []
(comp (map (juxt :key :value))
xform
(map (fn [[k v]] (merge r {:key k :value v}))))
[r]))
(mapcat identity))))
(defmethod get-output :ktable [entity parents entities joins]
(let [[join-order join-config] (w/get-join joins parents)
joined-entity (apply join-entities
(or join-config {::w/join-type :merge})
(map (comp ->joinable entities) (or join-order (vec parents))))]
(cond->> (::output joined-entity)
true (sort-by :timestamp)
(::w/group-by-fn entity) (group-by (fn [r]
((::w/group-by-fn entity) ((juxt :key :value) r))))
(::w/window entity) (mapcat (fn [[g rs]]
(for [w (determine-windows (::w/window entity) rs)]
[^:windowed [g w] (records-in-window w rs)])))
(::w/aggregate-adder-fn entity) (mapcat (fn [[g rs]]
(->> (reductions (fn [acc r]
(assoc r
:key (if (:windowed (meta g)) (first g) g)
:value ((::w/aggregate-adder-fn entity) (:value acc) [g (:value r)])))
{:value (::w/aggregate-initial-value entity)}
rs)
(drop 1)))))))
(defn run-experiment [{:keys [workflow entities joins] :as topology} entity->records]
(let [g (wu/->graph workflow)
initial-entities (->> entities
(map (fn [[k v]] [k (assoc v ::output (get entity->records k))]))
(into {}))]
(assoc topology :entities
(->> g
(lalg/topsort)
(map (juxt identity (partial l/predecessors g)))
(reduce (fn [processed-entities [node parents]]
(update processed-entities node
(fn [entity]
(update entity ::output concat (->> (get-output entity parents processed-entities joins)
(sort-by :timestamp))))))
initial-entities)))))
(defn results-only [experiment-results]
(->> experiment-results
:entities
(map (fn [[k v]]
[k (::output v)]))
(into {})))
(comment
(require 'willa.viz)
(def workflow [[:input-topic :stream]
[:secondary-input-topic :table]
[:stream :output-topic]
[:table :output-topic]])
(def joins {[:stream :table] {::w/join-type :left}})
(def experiment-topology
(run-experiment {:workflow workflow
:entities {:input-topic {::w/entity-type :topic}
:secondary-input-topic {::w/entity-type :topic}
:stream {::w/entity-type :kstream}
:table {::w/entity-type :ktable}
:output-topic {::w/entity-type :topic}}
:joins joins}
{:input-topic [{:key "key"
:value 1
:timestamp 1000}]
:secondary-input-topic [{:key "key"
:value 2
:timestamp 1100}]}))
(results-only experiment-topology)
(willa.viz/view-topology experiment-topology)
)
|
519042fb32480d2b8de21861cc1c3f285d83a3da6518283fed5e84dc1d2d0a59 | fiddlerwoaroof/lisp-sandbox | gemini-client.lisp | (defpackage :gemini.client
(:use :cl))
(in-package :gemini.client)
(defun ssl-connection (host port)
(flexi-streams:make-flexi-stream
(comm:open-tcp-stream host port :ssl-ctx t)
:external-format :utf-8))
(defun crlf (s)
(princ #\return s)
(princ #\newline s))
(defun request (uri s)
(puri:render-uri uri s)
(crlf s))
(fw.lu:defclass+ link ()
((url :initarg :url :reader url)
(text :initarg :text :reader text))))
(defmethod print-object ((it link) s)
(print-unreadable-object (it s :type t :identity t)
(format s "target: ")
(puri:render-uri (url it) s))
(defun parse-link (base-uri line)
(let* ((raw (subseq line 2))
(raw (serapeum:trim-whitespace raw))
(split (split-sequence:split-sequence-if #'serapeum:whitespacep raw)))
(destructuring-bind (first . rest) split
(link (puri:merge-uris (puri:uri first)
base-uri)
(when rest (car rest))))))
(defun gemini (uri s)
(let* ((uri (puri:uri uri))
(buffer (make-string 1024 :element-type 'character)))
(with-open-stream (conn (ssl-connection (puri:uri-host uri) 1965))
(request uri conn)
(finish-output conn)
(loop for read = (read-sequence buffer conn)
while (= read (length buffer))
do (write-sequence buffer s)
finally (write-sequence buffer conn :end read))
uri)))
(defun gemini-byline (uri s)
(let* ((uri (puri:uri uri))
(links ()))
(with-open-stream (conn (ssl-connection (puri:uri-host uri) 1965))
(request uri conn)
(finish-output conn)
(loop with preformatted = nil
for read = (read-line conn nil)
while read
do
(write-sequence read s)
(terpri s)
when (equal read "```") do (setf preformatted (not preformatted))
when (and (not preformatted) (> (length read) 2) (equal (subseq read 0 2) "=>"))
do (push (parse-link uri read) links))
(values uri links))))
| null | https://raw.githubusercontent.com/fiddlerwoaroof/lisp-sandbox/38ff817c95af35db042faf760b477675264220d2/gemini-client.lisp | lisp | (defpackage :gemini.client
(:use :cl))
(in-package :gemini.client)
(defun ssl-connection (host port)
(flexi-streams:make-flexi-stream
(comm:open-tcp-stream host port :ssl-ctx t)
:external-format :utf-8))
(defun crlf (s)
(princ #\return s)
(princ #\newline s))
(defun request (uri s)
(puri:render-uri uri s)
(crlf s))
(fw.lu:defclass+ link ()
((url :initarg :url :reader url)
(text :initarg :text :reader text))))
(defmethod print-object ((it link) s)
(print-unreadable-object (it s :type t :identity t)
(format s "target: ")
(puri:render-uri (url it) s))
(defun parse-link (base-uri line)
(let* ((raw (subseq line 2))
(raw (serapeum:trim-whitespace raw))
(split (split-sequence:split-sequence-if #'serapeum:whitespacep raw)))
(destructuring-bind (first . rest) split
(link (puri:merge-uris (puri:uri first)
base-uri)
(when rest (car rest))))))
(defun gemini (uri s)
(let* ((uri (puri:uri uri))
(buffer (make-string 1024 :element-type 'character)))
(with-open-stream (conn (ssl-connection (puri:uri-host uri) 1965))
(request uri conn)
(finish-output conn)
(loop for read = (read-sequence buffer conn)
while (= read (length buffer))
do (write-sequence buffer s)
finally (write-sequence buffer conn :end read))
uri)))
(defun gemini-byline (uri s)
(let* ((uri (puri:uri uri))
(links ()))
(with-open-stream (conn (ssl-connection (puri:uri-host uri) 1965))
(request uri conn)
(finish-output conn)
(loop with preformatted = nil
for read = (read-line conn nil)
while read
do
(write-sequence read s)
(terpri s)
when (equal read "```") do (setf preformatted (not preformatted))
when (and (not preformatted) (> (length read) 2) (equal (subseq read 0 2) "=>"))
do (push (parse-link uri read) links))
(values uri links))))
| |
108bdd8477f164653560a2cfedbf3aa657a868666d4168bf45f89ce4a86cf3a8 | abdulapopoola/SICPBook | Ex1.32.scm | #lang planet neil/sicp
;;HELPER methods
(define (cube x) (* x x x))
(define (inc x) (+ x 1))
(define (identity x) x)
;;This is the reduce/accumulate concept from func programming
Version
(define (accumulate combiner null-value term a next b)
(if (> a b)
null-value
(accumulate combiner (combiner (term a) null-value)
term (next a) next b)))
;;RECURSIVE Version of accumulate
(define (accumulate2 combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a) (accumulate2 combiner null-value
term (next a) next b))))
;;Sum of cubes
;;Beauty of this involves passing in the cube function to the sum function
;; which in turn relies on the accumulate function to succeed
;; Sum using iterative accumulate
(define (sum term a next b)
(accumulate + 0 term a next b))
;;Sum using recursive accumulate
(define (sum2 term a next b)
(accumulate2 + 0 term a next b))
;;Examples
(define (sum-cubes a b)
(sum cube a inc b))
(sum-cubes 1 10)
(define (sum-cubes2 a b)
(sum2 cube a inc b))
(sum-cubes2 1 10)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;PRODUCT using iterative accumulate
(define (product term a next b)
(accumulate * 1 term a next b))
;PRODUCT using recursive accumulate
(define (product2 term a next b)
(accumulate2 * 1 term a next b))
;; EXAMPLES
(define (factorial n)
(product identity 1 inc n))
(factorial 5)
(define (factorial2 n)
(product2 identity 1 inc n))
(factorial 5) | null | https://raw.githubusercontent.com/abdulapopoola/SICPBook/c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a/Chapter%201/1.3/Ex1.32.scm | scheme | HELPER methods
This is the reduce/accumulate concept from func programming
RECURSIVE Version of accumulate
Sum of cubes
Beauty of this involves passing in the cube function to the sum function
which in turn relies on the accumulate function to succeed
Sum using iterative accumulate
Sum using recursive accumulate
Examples
PRODUCT using iterative accumulate
PRODUCT using recursive accumulate
EXAMPLES | #lang planet neil/sicp
(define (cube x) (* x x x))
(define (inc x) (+ x 1))
(define (identity x) x)
Version
(define (accumulate combiner null-value term a next b)
(if (> a b)
null-value
(accumulate combiner (combiner (term a) null-value)
term (next a) next b)))
(define (accumulate2 combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a) (accumulate2 combiner null-value
term (next a) next b))))
(define (sum term a next b)
(accumulate + 0 term a next b))
(define (sum2 term a next b)
(accumulate2 + 0 term a next b))
(define (sum-cubes a b)
(sum cube a inc b))
(sum-cubes 1 10)
(define (sum-cubes2 a b)
(sum2 cube a inc b))
(sum-cubes2 1 10)
(define (product term a next b)
(accumulate * 1 term a next b))
(define (product2 term a next b)
(accumulate2 * 1 term a next b))
(define (factorial n)
(product identity 1 inc n))
(factorial 5)
(define (factorial2 n)
(product2 identity 1 inc n))
(factorial 5) |
0981d95c00ba8d2f1bba542cf65c377500f2d34b5e2394054316a7818caaeaff | marick/Midje | arglists.clj | (ns ^{:doc "Parsing function argument lists"}
midje.parsing.other.arglists
(:require [midje.config :as config]
[midje.emission.levels :as levels]
[midje.parsing.util.core :refer :all]
[midje.util.exceptions :refer [user-error]]
[midje.util.pile :as pile]
[such.function-makers :as mkfn]
[such.types :as types]
[such.sequences :as seq]))
;;; Print levels (keywords)
(defn separate-print-levels [args default]
(let [[[print-level & extras] non-levels] (seq/bifurcate levels/valids args)]
(when (seq extras)
(throw (user-error "You have extra print level names or numbers.")))
(dorun (map levels/validate-level! (filter number? args)))
(if print-level
[[print-level] print-level non-levels]
[[ ] default non-levels])))
;;; Metadata filters
(defn separate-filters [args plain-argument?]
(let [[filters remainder]
(seq/bifurcate #(and (not (plain-argument? %))
((mkfn/pred:any? string? types/regex? fn? keyword?) %))
args)]
(vector filters remainder)))
;;; Keyword options with 0 or more arguments.
(defn is-flag-segment-for? [flag-predicate]
(comp boolean flag-predicate first))
(defn build-on-flag-keyword [original suffix]
(keyword (str (name original) suffix)))
TODO : Be responsible , , and break this into pieces .
Also , should use this .
(defn make-option-arglist-parser [& flag-descriptions]
(fn [arglist]
(let [all-arg-set (set (flatten flag-descriptions))
segments (partition-by all-arg-set arglist)
[[true-args] flag-segments] (split-with (complement (is-flag-segment-for? all-arg-set))
segments)
[unmentioned-keys map-with-flag-data-added]
(loop [so-far {:true-args (vec true-args)}
flag-selector (zipmap (map set flag-descriptions)
(map first flag-descriptions))
flag-segments flag-segments]
(let [[[flag] flag-args] (take 2 flag-segments)
matching-selector (first (filter #(% flag) (keys flag-selector)))]
(cond (empty? flag-segments)
[(vals flag-selector) so-far]
matching-selector
(recur (assoc so-far (build-on-flag-keyword (flag-selector matching-selector) "?") true
(build-on-flag-keyword (flag-selector matching-selector) "-args") (vec flag-args))
(dissoc flag-selector matching-selector)
(drop 2 flag-segments))
:else
(throw (Error. (str "It should be impossible for a flag-segment not to match a selector."
(pr-str flag-descriptions arglist)))))))]
(merge map-with-flag-data-added
(zipmap (map #(build-on-flag-keyword % "?") unmentioned-keys)
(repeat false))))))
| null | https://raw.githubusercontent.com/marick/Midje/2b9bcb117442d3bd2d16446b47540888d683c717/src/midje/parsing/other/arglists.clj | clojure | Print levels (keywords)
Metadata filters
Keyword options with 0 or more arguments. | (ns ^{:doc "Parsing function argument lists"}
midje.parsing.other.arglists
(:require [midje.config :as config]
[midje.emission.levels :as levels]
[midje.parsing.util.core :refer :all]
[midje.util.exceptions :refer [user-error]]
[midje.util.pile :as pile]
[such.function-makers :as mkfn]
[such.types :as types]
[such.sequences :as seq]))
(defn separate-print-levels [args default]
(let [[[print-level & extras] non-levels] (seq/bifurcate levels/valids args)]
(when (seq extras)
(throw (user-error "You have extra print level names or numbers.")))
(dorun (map levels/validate-level! (filter number? args)))
(if print-level
[[print-level] print-level non-levels]
[[ ] default non-levels])))
(defn separate-filters [args plain-argument?]
(let [[filters remainder]
(seq/bifurcate #(and (not (plain-argument? %))
((mkfn/pred:any? string? types/regex? fn? keyword?) %))
args)]
(vector filters remainder)))
(defn is-flag-segment-for? [flag-predicate]
(comp boolean flag-predicate first))
(defn build-on-flag-keyword [original suffix]
(keyword (str (name original) suffix)))
TODO : Be responsible , , and break this into pieces .
Also , should use this .
(defn make-option-arglist-parser [& flag-descriptions]
(fn [arglist]
(let [all-arg-set (set (flatten flag-descriptions))
segments (partition-by all-arg-set arglist)
[[true-args] flag-segments] (split-with (complement (is-flag-segment-for? all-arg-set))
segments)
[unmentioned-keys map-with-flag-data-added]
(loop [so-far {:true-args (vec true-args)}
flag-selector (zipmap (map set flag-descriptions)
(map first flag-descriptions))
flag-segments flag-segments]
(let [[[flag] flag-args] (take 2 flag-segments)
matching-selector (first (filter #(% flag) (keys flag-selector)))]
(cond (empty? flag-segments)
[(vals flag-selector) so-far]
matching-selector
(recur (assoc so-far (build-on-flag-keyword (flag-selector matching-selector) "?") true
(build-on-flag-keyword (flag-selector matching-selector) "-args") (vec flag-args))
(dissoc flag-selector matching-selector)
(drop 2 flag-segments))
:else
(throw (Error. (str "It should be impossible for a flag-segment not to match a selector."
(pr-str flag-descriptions arglist)))))))]
(merge map-with-flag-data-added
(zipmap (map #(build-on-flag-keyword % "?") unmentioned-keys)
(repeat false))))))
|
cef2119e64e7809f7a4cebf5f7e3260bf1c166b3e01a6d967e3f1308334505a1 | fjvallarino/monomer | Spacer.hs | |
Module : . Widgets . Singles . Spacer
Copyright : ( c ) 2018
License : BSD-3 - Clause ( see the LICENSE file )
Maintainer :
Stability : experimental
Portability : non - portable
Spacer is used for adding a fixed space between two widgets .
@
hstack [
label \"Username\ " ,
spacer ,
label username
]
@
Filler is used for taking all the unused space between two widgets . Useful for
alignment purposes .
@
hstack [
label " Section title " ,
filler ,
button \"Close\ " CloseSection
]
@
Both adapt to the active layout direction .
Module : Monomer.Widgets.Singles.Spacer
Copyright : (c) 2018 Francisco Vallarino
License : BSD-3-Clause (see the LICENSE file)
Maintainer :
Stability : experimental
Portability : non-portable
Spacer is used for adding a fixed space between two widgets.
@
hstack [
label \"Username\",
spacer,
label username
]
@
Filler is used for taking all the unused space between two widgets. Useful for
alignment purposes.
@
hstack [
label "Section title",
filler,
button \"Close\" CloseSection
]
@
Both adapt to the active layout direction.
-}
# LANGUAGE FlexibleContexts #
module Monomer.Widgets.Singles.Spacer (
-- * Configuration
SpacerCfg,
-- * Constructors
spacer,
spacer_,
filler,
filler_
) where
import Control.Applicative ((<|>))
import Control.Lens ((^.))
import Data.Default
import Data.Maybe
import Data.Tuple
import Monomer.Widgets.Single
import qualified Monomer.Core.Lens as L
{-|
Configuration options for spacer widget:
- 'width': the max width for spacer, the reference for filler.
- 'resizeFactor': flexibility to have more or less spaced assigned.
-}
data SpacerCfg = SpacerCfg {
_spcWidth :: Maybe Double,
_spcFactor :: Maybe Double
}
instance Default SpacerCfg where
def = SpacerCfg {
_spcWidth = Nothing,
_spcFactor = Nothing
}
instance Semigroup SpacerCfg where
(<>) s1 s2 = SpacerCfg {
_spcWidth = _spcWidth s2 <|> _spcWidth s1,
_spcFactor = _spcFactor s2 <|> _spcFactor s1
}
instance Monoid SpacerCfg where
mempty = def
instance CmbWidth SpacerCfg where
width w = def {
_spcWidth = Just w
}
instance CmbResizeFactor SpacerCfg where
resizeFactor f = def {
_spcFactor = Just f
}
-- | Creates a spacer widget.
spacer :: WidgetNode s e
spacer = spacer_ def
-- | Creates a spacer widget. Accepts config.
spacer_ :: [SpacerCfg] -> WidgetNode s e
spacer_ configs = defaultWidgetNode "spacer" widget where
config = mconcat (resizeFactor 0 : configs)
widget = makeSpacer config
-- | Creates a filler widget.
filler :: WidgetNode s e
filler = filler_ def
-- | Creates a filler widget. Accepts config.
filler_ :: [SpacerCfg] -> WidgetNode s e
filler_ configs = defaultWidgetNode "filler" widget where
config = mconcat configs
widget = makeSpacer config
makeSpacer :: SpacerCfg -> Widget s e
makeSpacer config = widget where
widget = createSingle () def {
singleGetSizeReq = getSizeReq
}
getSizeReq wenv node = sizeReq where
direction = wenv ^. L.layoutDirection
factor = fromMaybe 0.5 (_spcFactor config)
isFixed = factor < 0.01
width
| isFixed = fromMaybe 10 (_spcWidth config)
| otherwise = fromMaybe 5 (_spcWidth config)
flexSide = flexSize 5 0.5
fixedW = fixedSize width
flexW = flexSize width factor
expandW = expandSize width factor
sizeReq
| isFixed && direction == LayoutNone = (fixedW, fixedW)
| isFixed && direction == LayoutHorizontal = (fixedW, flexSide)
| isFixed = (flexSide, fixedW)
| direction == LayoutNone = (expandW, expandW)
| direction == LayoutHorizontal = (expandW, flexW)
| otherwise = (flexW, expandW)
| null | https://raw.githubusercontent.com/fjvallarino/monomer/f693af605997227f692c1d796dfba3ade7d5ad4f/src/Monomer/Widgets/Singles/Spacer.hs | haskell | * Configuration
* Constructors
|
Configuration options for spacer widget:
- 'width': the max width for spacer, the reference for filler.
- 'resizeFactor': flexibility to have more or less spaced assigned.
| Creates a spacer widget.
| Creates a spacer widget. Accepts config.
| Creates a filler widget.
| Creates a filler widget. Accepts config. | |
Module : . Widgets . Singles . Spacer
Copyright : ( c ) 2018
License : BSD-3 - Clause ( see the LICENSE file )
Maintainer :
Stability : experimental
Portability : non - portable
Spacer is used for adding a fixed space between two widgets .
@
hstack [
label \"Username\ " ,
spacer ,
label username
]
@
Filler is used for taking all the unused space between two widgets . Useful for
alignment purposes .
@
hstack [
label " Section title " ,
filler ,
button \"Close\ " CloseSection
]
@
Both adapt to the active layout direction .
Module : Monomer.Widgets.Singles.Spacer
Copyright : (c) 2018 Francisco Vallarino
License : BSD-3-Clause (see the LICENSE file)
Maintainer :
Stability : experimental
Portability : non-portable
Spacer is used for adding a fixed space between two widgets.
@
hstack [
label \"Username\",
spacer,
label username
]
@
Filler is used for taking all the unused space between two widgets. Useful for
alignment purposes.
@
hstack [
label "Section title",
filler,
button \"Close\" CloseSection
]
@
Both adapt to the active layout direction.
-}
# LANGUAGE FlexibleContexts #
module Monomer.Widgets.Singles.Spacer (
SpacerCfg,
spacer,
spacer_,
filler,
filler_
) where
import Control.Applicative ((<|>))
import Control.Lens ((^.))
import Data.Default
import Data.Maybe
import Data.Tuple
import Monomer.Widgets.Single
import qualified Monomer.Core.Lens as L
data SpacerCfg = SpacerCfg {
_spcWidth :: Maybe Double,
_spcFactor :: Maybe Double
}
instance Default SpacerCfg where
def = SpacerCfg {
_spcWidth = Nothing,
_spcFactor = Nothing
}
instance Semigroup SpacerCfg where
(<>) s1 s2 = SpacerCfg {
_spcWidth = _spcWidth s2 <|> _spcWidth s1,
_spcFactor = _spcFactor s2 <|> _spcFactor s1
}
instance Monoid SpacerCfg where
mempty = def
instance CmbWidth SpacerCfg where
width w = def {
_spcWidth = Just w
}
instance CmbResizeFactor SpacerCfg where
resizeFactor f = def {
_spcFactor = Just f
}
spacer :: WidgetNode s e
spacer = spacer_ def
spacer_ :: [SpacerCfg] -> WidgetNode s e
spacer_ configs = defaultWidgetNode "spacer" widget where
config = mconcat (resizeFactor 0 : configs)
widget = makeSpacer config
filler :: WidgetNode s e
filler = filler_ def
filler_ :: [SpacerCfg] -> WidgetNode s e
filler_ configs = defaultWidgetNode "filler" widget where
config = mconcat configs
widget = makeSpacer config
makeSpacer :: SpacerCfg -> Widget s e
makeSpacer config = widget where
widget = createSingle () def {
singleGetSizeReq = getSizeReq
}
getSizeReq wenv node = sizeReq where
direction = wenv ^. L.layoutDirection
factor = fromMaybe 0.5 (_spcFactor config)
isFixed = factor < 0.01
width
| isFixed = fromMaybe 10 (_spcWidth config)
| otherwise = fromMaybe 5 (_spcWidth config)
flexSide = flexSize 5 0.5
fixedW = fixedSize width
flexW = flexSize width factor
expandW = expandSize width factor
sizeReq
| isFixed && direction == LayoutNone = (fixedW, fixedW)
| isFixed && direction == LayoutHorizontal = (fixedW, flexSide)
| isFixed = (flexSide, fixedW)
| direction == LayoutNone = (expandW, expandW)
| direction == LayoutHorizontal = (expandW, flexW)
| otherwise = (flexW, expandW)
|
deaef015dcf1d063d279662314e88041b3984bdf54978f0598330f3c113fb99a | onaio/milia | images.cljc | (ns milia.utils.images
(:require [chimera.urls :refer [url]]
[milia.utils.remote :refer [thumbor-server]]))
(defn resize-image
"Return a URL for this image resized."
([image-url edge-px]
(resize-image image-url edge-px edge-px))
([image-url width-px height-px]
(resize-image image-url width-px height-px thumbor-server))
([image-url width-px height-px image-server-url]
(str image-server-url
(url "unsafe"
(str width-px "x" height-px) "smart" image-url))))
| null | https://raw.githubusercontent.com/onaio/milia/c68b612bd640aa2499e4ac2f907a7ef793d0820a/src/milia/utils/images.cljc | clojure | (ns milia.utils.images
(:require [chimera.urls :refer [url]]
[milia.utils.remote :refer [thumbor-server]]))
(defn resize-image
"Return a URL for this image resized."
([image-url edge-px]
(resize-image image-url edge-px edge-px))
([image-url width-px height-px]
(resize-image image-url width-px height-px thumbor-server))
([image-url width-px height-px image-server-url]
(str image-server-url
(url "unsafe"
(str width-px "x" height-px) "smart" image-url))))
| |
01df8348336d0ce0f65c51cf656ec76f9560f6275667c3878c2657a4fd8eaec5 | blindglobe/clocc | split-sequence.lisp | ;;;; SPLIT-SEQUENCE
;;;
This code was based on in
;;; <URL:>;
;;;
;;; changes include:
;;;
;;; * altering the behaviour of the :from-end keyword argument to
;;; return the subsequences in original order, for consistency with
CL : REMOVE , CL : SUBSTITUTE et al . (: from - end being non - NIL only
;;; affects the answer if :count is less than the number of
;;; subsequences, by analogy with the above-referenced functions).
;;;
;;; * changing the :maximum keyword argument to :count, by analogy
with CL : REMOVE , CL : SUBSTITUTE , and so on .
;;;
;;; * naming the function SPLIT-SEQUENCE rather than PARTITION rather
;;; than SPLIT.
;;;
;;; * adding SPLIT-SEQUENCE-IF and SPLIT-SEQUENCE-IF-NOT.
;;;
* The second return value is now an index rather than a copy of a
;;; portion of the sequence; this index is the `right' one to feed to
CL : SUBSEQ for continued processing .
;;; There's a certain amount of code duplication here, which is kept
;;; to illustrate the relationship between the SPLIT-SEQUENCE
functions and the CL : POSITION functions .
;;; Examples:
;;;
;;; * (split-sequence #\; "a;;b;c")
- > ( " a " " " " b " " c " ) , 6
;;;
;;; * (split-sequence #\; "a;;b;c" :from-end t)
- > ( " a " " " " b " " c " ) , 0
;;;
* ( split - sequence # \ ; " a;;b;c " : from - end t : count 1 )
- > ( " c " ) , 4
;;;
;;; * (split-sequence #\; "a;;b;c" :remove-empty-subseqs t)
- > ( " a " " b " " c " ) , 6
;;;
;;; * (split-sequence-if (lambda (x) (member x '(#\a #\b))) "abracadabra")
- > ( " " " " " r " " c " " d " " " " r " " " ) , 11
;;;
;;; * (split-sequence-if-not (lambda (x) (member x '(#\a #\b))) "abracadabra")
- > ( " ab " " a " " a " " ab " " a " ) , 11
;;;
* ( split - sequence # \ ; " ; oo;bar;ba ; " : start 1 : end 9 )
- > ( " oo " " bar " " b " ) , 9
(defpackage "SPLIT-SEQUENCE"
(:use "CL")
(:nicknames "PARTITION")
(:export "SPLIT-SEQUENCE" "SPLIT-SEQUENCE-IF" "SPLIT-SEQUENCE-IF-NOT"
"PARTITION" "PARTITION-IF" "PARTITION-IF-NOT")
(:documentation "The SPLIT-SEQUENCE package provides functionality for Common Lisp sequences analagous to Perl's split operator."))
(in-package "SPLIT-SEQUENCE")
(defun split-sequence (delimiter seq &key (count nil) (remove-empty-subseqs nil) (from-end nil) (start 0) (end nil) (test nil test-supplied) (test-not nil test-not-supplied) (key nil key-supplied))
"Return a list of subsequences in seq delimited by delimiter.
If :remove-empty-subseqs is NIL, empty subsequences will be included
in the result; otherwise they will be discarded. All other keywords
work analogously to those for CL:SUBSTITUTE. In particular, the
behaviour of :from-end is possibly different from other versions of
: from - end values of NIL and T are equivalent unless
:count is supplied. The second return value is an index suitable as an
argument to CL:SUBSEQ into the sequence indicating where processing
stopped."
(let ((len (length seq))
(other-keys (nconc (when test-supplied
(list :test test))
(when test-not-supplied
(list :test-not test-not))
(when key-supplied
(list :key key)))))
(unless end (setq end len))
(if from-end
(loop for right = end then left
for left = (max (or (apply #'position delimiter seq
:end right
:from-end t
other-keys)
-1)
(1- start))
unless (and (= right (1+ left))
empty subseq we do n't want
if (and count (>= nr-elts count))
;; We can't take any more. Return now.
return (values (nreverse subseqs) right)
else
collect (subseq seq (1+ left) right) into subseqs
and sum 1 into nr-elts
until (< left start)
finally (return (values (nreverse subseqs) (1+ left))))
(loop for left = start then (+ right 1)
for right = (min (or (apply #'position delimiter seq
:start left
other-keys)
len)
end)
unless (and (= right left)
empty subseq we do n't want
if (and count (>= nr-elts count))
;; We can't take any more. Return now.
return (values subseqs left)
else
collect (subseq seq left right) into subseqs
and sum 1 into nr-elts
until (>= right end)
finally (return (values subseqs right))))))
(defun split-sequence-if (predicate seq &key (count nil) (remove-empty-subseqs nil) (from-end nil) (start 0) (end nil) (key nil key-supplied))
"Return a list of subsequences in seq delimited by items satisfying
predicate.
If :remove-empty-subseqs is NIL, empty subsequences will be included
in the result; otherwise they will be discarded. All other keywords
work analogously to those for CL:SUBSTITUTE-IF. In particular, the
behaviour of :from-end is possibly different from other versions of
: from - end values of NIL and T are equivalent unless
:count is supplied. The second return value is an index suitable as an
argument to CL:SUBSEQ into the sequence indicating where processing
stopped."
(let ((len (length seq))
(other-keys (when key-supplied
(list :key key))))
(unless end (setq end len))
(if from-end
(loop for right = end then left
for left = (max (or (apply #'position-if predicate seq
:end right
:from-end t
other-keys)
-1)
(1- start))
unless (and (= right (1+ left))
empty subseq we do n't want
if (and count (>= nr-elts count))
;; We can't take any more. Return now.
return (values (nreverse subseqs) right)
else
collect (subseq seq (1+ left) right) into subseqs
and sum 1 into nr-elts
until (< left start)
finally (return (values (nreverse subseqs) (1+ left))))
(loop for left = start then (+ right 1)
for right = (min (or (apply #'position-if predicate seq
:start left
other-keys)
len)
end)
unless (and (= right left)
empty subseq we do n't want
if (and count (>= nr-elts count))
;; We can't take any more. Return now.
return (values subseqs left)
else
collect (subseq seq left right) into subseqs
and sum 1 into nr-elts
until (>= right end)
finally (return (values subseqs right))))))
(defun split-sequence-if-not (predicate seq &key (count nil) (remove-empty-subseqs nil) (from-end nil) (start 0) (end nil) (key nil key-supplied))
"Return a list of subsequences in seq delimited by items satisfying
\(CL:COMPLEMENT predicate).
If :remove-empty-subseqs is NIL, empty subsequences will be included
in the result; otherwise they will be discarded. All other keywords
work analogously to those for CL:SUBSTITUTE-IF-NOT. In particular,
the behaviour of :from-end is possibly different from other versions
: from - end values of NIL and T are equivalent unless
:count is supplied. The second return value is an index suitable as an
argument to CL:SUBSEQ into the sequence indicating where processing
stopped."
(let ((len (length seq))
(other-keys (when key-supplied
(list :key key))))
(unless end (setq end len))
(if from-end
(loop for right = end then left
for left = (max (or (apply #'position-if-not predicate seq
:end right
:from-end t
other-keys)
-1)
(1- start))
unless (and (= right (1+ left))
empty subseq we do n't want
if (and count (>= nr-elts count))
;; We can't take any more. Return now.
return (values (nreverse subseqs) right)
else
collect (subseq seq (1+ left) right) into subseqs
and sum 1 into nr-elts
until (< left start)
finally (return (values (nreverse subseqs) (1+ left))))
(loop for left = start then (+ right 1)
for right = (min (or (apply #'position-if-not predicate seq
:start left
other-keys)
len)
end)
unless (and (= right left)
empty subseq we do n't want
if (and count (>= nr-elts count))
;; We can't take any more. Return now.
return (values subseqs left)
else
collect (subseq seq left right) into subseqs
and sum 1 into nr-elts
until (>= right end)
finally (return (values subseqs right))))))
;;; clean deprecation
(defun partition (&rest args)
"PARTITION is deprecated; use SPLIT-SEQUENCE instead."
(apply #'split-sequence args))
(defun partition-if (&rest args)
"PARTITION-IF is deprecated; use SPLIT-SEQUENCE-IF instead."
(apply #'split-sequence-if args))
(defun partition-if-not (&rest args)
"PARTITION-IF-NOT is deprecated; use SPLIT-SEQUENCE-IF-NOT instead."
(apply #'split-sequence-if-not args))
(define-compiler-macro partition (&whole form &rest args)
(declare (ignore args))
(warn "PARTITION is deprecated; use SPLIT-SEQUENCE instead.")
form)
(define-compiler-macro partition-if (&whole form &rest args)
(declare (ignore args))
(warn "PARTITION-IF is deprecated; use SPLIT-SEQUENCE-IF instead.")
form)
(define-compiler-macro partition-if-not (&whole form &rest args)
(declare (ignore args))
(warn "PARTITION-IF-NOT is deprecated; use SPLIT-SEQUENCE-IF-NOT instead")
form)
(pushnew :split-sequence *features*)
| null | https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/defsystem-4/src/utilities/split-sequence.lisp | lisp | SPLIT-SEQUENCE
<URL:>;
changes include:
* altering the behaviour of the :from-end keyword argument to
return the subsequences in original order, for consistency with
affects the answer if :count is less than the number of
subsequences, by analogy with the above-referenced functions).
* changing the :maximum keyword argument to :count, by analogy
* naming the function SPLIT-SEQUENCE rather than PARTITION rather
than SPLIT.
* adding SPLIT-SEQUENCE-IF and SPLIT-SEQUENCE-IF-NOT.
portion of the sequence; this index is the `right' one to feed to
There's a certain amount of code duplication here, which is kept
to illustrate the relationship between the SPLIT-SEQUENCE
Examples:
* (split-sequence #\; "a;;b;c")
* (split-sequence #\; "a;;b;c" :from-end t)
" a;;b;c " : from - end t : count 1 )
* (split-sequence #\; "a;;b;c" :remove-empty-subseqs t)
* (split-sequence-if (lambda (x) (member x '(#\a #\b))) "abracadabra")
* (split-sequence-if-not (lambda (x) (member x '(#\a #\b))) "abracadabra")
" ; oo;bar;ba ; " : start 1 : end 9 )
otherwise they will be discarded. All other keywords
We can't take any more. Return now.
We can't take any more. Return now.
otherwise they will be discarded. All other keywords
We can't take any more. Return now.
We can't take any more. Return now.
otherwise they will be discarded. All other keywords
We can't take any more. Return now.
We can't take any more. Return now.
clean deprecation | This code was based on in
CL : REMOVE , CL : SUBSTITUTE et al . (: from - end being non - NIL only
with CL : REMOVE , CL : SUBSTITUTE , and so on .
* The second return value is now an index rather than a copy of a
CL : SUBSEQ for continued processing .
functions and the CL : POSITION functions .
- > ( " a " " " " b " " c " ) , 6
- > ( " a " " " " b " " c " ) , 0
- > ( " c " ) , 4
- > ( " a " " b " " c " ) , 6
- > ( " " " " " r " " c " " d " " " " r " " " ) , 11
- > ( " ab " " a " " a " " ab " " a " ) , 11
- > ( " oo " " bar " " b " ) , 9
(defpackage "SPLIT-SEQUENCE"
(:use "CL")
(:nicknames "PARTITION")
(:export "SPLIT-SEQUENCE" "SPLIT-SEQUENCE-IF" "SPLIT-SEQUENCE-IF-NOT"
"PARTITION" "PARTITION-IF" "PARTITION-IF-NOT")
(:documentation "The SPLIT-SEQUENCE package provides functionality for Common Lisp sequences analagous to Perl's split operator."))
(in-package "SPLIT-SEQUENCE")
(defun split-sequence (delimiter seq &key (count nil) (remove-empty-subseqs nil) (from-end nil) (start 0) (end nil) (test nil test-supplied) (test-not nil test-not-supplied) (key nil key-supplied))
"Return a list of subsequences in seq delimited by delimiter.
If :remove-empty-subseqs is NIL, empty subsequences will be included
work analogously to those for CL:SUBSTITUTE. In particular, the
behaviour of :from-end is possibly different from other versions of
: from - end values of NIL and T are equivalent unless
:count is supplied. The second return value is an index suitable as an
argument to CL:SUBSEQ into the sequence indicating where processing
stopped."
(let ((len (length seq))
(other-keys (nconc (when test-supplied
(list :test test))
(when test-not-supplied
(list :test-not test-not))
(when key-supplied
(list :key key)))))
(unless end (setq end len))
(if from-end
(loop for right = end then left
for left = (max (or (apply #'position delimiter seq
:end right
:from-end t
other-keys)
-1)
(1- start))
unless (and (= right (1+ left))
empty subseq we do n't want
if (and count (>= nr-elts count))
return (values (nreverse subseqs) right)
else
collect (subseq seq (1+ left) right) into subseqs
and sum 1 into nr-elts
until (< left start)
finally (return (values (nreverse subseqs) (1+ left))))
(loop for left = start then (+ right 1)
for right = (min (or (apply #'position delimiter seq
:start left
other-keys)
len)
end)
unless (and (= right left)
empty subseq we do n't want
if (and count (>= nr-elts count))
return (values subseqs left)
else
collect (subseq seq left right) into subseqs
and sum 1 into nr-elts
until (>= right end)
finally (return (values subseqs right))))))
(defun split-sequence-if (predicate seq &key (count nil) (remove-empty-subseqs nil) (from-end nil) (start 0) (end nil) (key nil key-supplied))
"Return a list of subsequences in seq delimited by items satisfying
predicate.
If :remove-empty-subseqs is NIL, empty subsequences will be included
work analogously to those for CL:SUBSTITUTE-IF. In particular, the
behaviour of :from-end is possibly different from other versions of
: from - end values of NIL and T are equivalent unless
:count is supplied. The second return value is an index suitable as an
argument to CL:SUBSEQ into the sequence indicating where processing
stopped."
(let ((len (length seq))
(other-keys (when key-supplied
(list :key key))))
(unless end (setq end len))
(if from-end
(loop for right = end then left
for left = (max (or (apply #'position-if predicate seq
:end right
:from-end t
other-keys)
-1)
(1- start))
unless (and (= right (1+ left))
empty subseq we do n't want
if (and count (>= nr-elts count))
return (values (nreverse subseqs) right)
else
collect (subseq seq (1+ left) right) into subseqs
and sum 1 into nr-elts
until (< left start)
finally (return (values (nreverse subseqs) (1+ left))))
(loop for left = start then (+ right 1)
for right = (min (or (apply #'position-if predicate seq
:start left
other-keys)
len)
end)
unless (and (= right left)
empty subseq we do n't want
if (and count (>= nr-elts count))
return (values subseqs left)
else
collect (subseq seq left right) into subseqs
and sum 1 into nr-elts
until (>= right end)
finally (return (values subseqs right))))))
(defun split-sequence-if-not (predicate seq &key (count nil) (remove-empty-subseqs nil) (from-end nil) (start 0) (end nil) (key nil key-supplied))
"Return a list of subsequences in seq delimited by items satisfying
\(CL:COMPLEMENT predicate).
If :remove-empty-subseqs is NIL, empty subsequences will be included
work analogously to those for CL:SUBSTITUTE-IF-NOT. In particular,
the behaviour of :from-end is possibly different from other versions
: from - end values of NIL and T are equivalent unless
:count is supplied. The second return value is an index suitable as an
argument to CL:SUBSEQ into the sequence indicating where processing
stopped."
(let ((len (length seq))
(other-keys (when key-supplied
(list :key key))))
(unless end (setq end len))
(if from-end
(loop for right = end then left
for left = (max (or (apply #'position-if-not predicate seq
:end right
:from-end t
other-keys)
-1)
(1- start))
unless (and (= right (1+ left))
empty subseq we do n't want
if (and count (>= nr-elts count))
return (values (nreverse subseqs) right)
else
collect (subseq seq (1+ left) right) into subseqs
and sum 1 into nr-elts
until (< left start)
finally (return (values (nreverse subseqs) (1+ left))))
(loop for left = start then (+ right 1)
for right = (min (or (apply #'position-if-not predicate seq
:start left
other-keys)
len)
end)
unless (and (= right left)
empty subseq we do n't want
if (and count (>= nr-elts count))
return (values subseqs left)
else
collect (subseq seq left right) into subseqs
and sum 1 into nr-elts
until (>= right end)
finally (return (values subseqs right))))))
(defun partition (&rest args)
"PARTITION is deprecated; use SPLIT-SEQUENCE instead."
(apply #'split-sequence args))
(defun partition-if (&rest args)
"PARTITION-IF is deprecated; use SPLIT-SEQUENCE-IF instead."
(apply #'split-sequence-if args))
(defun partition-if-not (&rest args)
"PARTITION-IF-NOT is deprecated; use SPLIT-SEQUENCE-IF-NOT instead."
(apply #'split-sequence-if-not args))
(define-compiler-macro partition (&whole form &rest args)
(declare (ignore args))
(warn "PARTITION is deprecated; use SPLIT-SEQUENCE instead.")
form)
(define-compiler-macro partition-if (&whole form &rest args)
(declare (ignore args))
(warn "PARTITION-IF is deprecated; use SPLIT-SEQUENCE-IF instead.")
form)
(define-compiler-macro partition-if-not (&whole form &rest args)
(declare (ignore args))
(warn "PARTITION-IF-NOT is deprecated; use SPLIT-SEQUENCE-IF-NOT instead")
form)
(pushnew :split-sequence *features*)
|
f8c46f24dd61a2f66b1bd865a4ddef2e0239dc6a3ce2bf79497ea5fe568b0a4b | akabe/ocaml-crf | crf_eval.ml | --- A library for conditional random field ( CRF ) in OCaml
Copyright ( C ) 2015 < >
This program is free software ; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation ; either version 3 of the License , or ( at your option ) any later
version .
This program is distributed in the hope that it will be useful , but WITHOUT
ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE . See the GNU General Public License for more
details .
You should have received a copy of the GNU General Public License along with
this program . If not , see < / > .
Copyright (C) 2015 Akinori ABE <>
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program. If not, see </>. *)
open Format
open Crf_model
type 'a key =
| Label of 'a
| Total
type 'a confusion_matrix =
{
labels : 'a array;
tbl : ('a key * 'a key, int) Hashtbl.t;
}
let confusion_matrix model igs ogs =
let labels = model.out_labels in
let tbl = Hashtbl.create 16 in
Hashtbl.add tbl (Total, Total) 0;
Array.iter (fun x ->
Hashtbl.add tbl (Label x, Total) 0;
Hashtbl.add tbl (Total, Label x) 0;
Array.iter (fun y -> Hashtbl.add tbl (Label x, Label y) 0) labels)
labels;
let incr key =
let n = Hashtbl.find tbl key in
Hashtbl.replace tbl key (succ n)
in
let aux iv ov =
match Crf_graph.get iv with
| { out_label = None; _ } -> ()
| { out_label = Some ans; _ } ->
let pred = Crf_graph.get ov in (* prediction *)
incr (Label ans, Label pred);
incr (Label ans, Total);
incr (Total, Label pred);
incr (Total, Total)
in
List.iter2 (Crf_graph.iter2 aux) igs ogs;
{ labels; tbl; }
let pp_confusion_matrix pp_out_label ppf { labels; tbl } =
let n = Array.length labels in
let pp_label ppf i =
if i <= n then pp_out_label ppf labels.(i-1)
else pp_print_string ppf "Total"
in
let pp_end_col ppf ~row:_ ~col:_ = pp_print_string ppf " | " in
let get_el i j =
let k1 = if i <= n then Label labels.(i-1) else Total in
let k2 = if j <= n then Label labels.(j-1) else Total in
Hashtbl.find tbl (k1, k2)
in
Slap.Io.pp_table ~pp_end_col ~pp_left:pp_label ~pp_head:pp_label
pp_print_int ppf (n + 1) (n + 1) get_el
let div m n = if n = 0 then None else Some (float m /. float n)
let accuracy { labels; tbl; } =
let deno = Hashtbl.find tbl (Total, Total) in
let nume = Array.fold_left
(fun acc x -> acc + Hashtbl.find tbl (Label x, Label x))
0 labels in
div nume deno
let precision { labels; tbl; } =
Array.map (fun x ->
let deno = Hashtbl.find tbl (Total, Label x) in
let nume = Hashtbl.find tbl (Label x, Label x) in
div nume deno)
labels
let recall { labels; tbl; } =
Array.map (fun x ->
let deno = Hashtbl.find tbl (Label x, Total) in
let nume = Hashtbl.find tbl (Label x, Label x) in
div nume deno)
labels
let f_score { labels; tbl; } =
Array.map (fun x ->
let denoP = Hashtbl.find tbl (Total, Label x) in
let denoR = Hashtbl.find tbl (Label x, Total) in
let nume = Hashtbl.find tbl (Label x, Label x) in
if denoP = 0 || denoR = 0 then None
else begin
let prec = float nume /. float denoP in
let recall = float nume /. float denoR in
Some (2.0 *. prec *. recall /. (prec +. recall))
end)
labels
let pp_score pp_out_label ppf cmat =
let precs = precision cmat in
let recalls = recall cmat in
let fs = f_score cmat in
let n = Array.length cmat.labels in
let pp_left ppf i = pp_out_label ppf cmat.labels.(i-1) in
let pp_head ppf i =
pp_print_string ppf [|"Precision"; "Recall"; "F-score"|].(i-1)
in
let pp_end_col ppf ~row:_ ~col:_ = pp_print_string ppf " | " in
let get_el i j = [|precs; recalls; fs|].(j-1).(i-1) in
let pp_el ppf = function
| None -> pp_print_string ppf "N/A"
| Some x -> fprintf ppf "%g" x in
Slap.Io.pp_table ~pp_end_col ~pp_left ~pp_head pp_el ppf n 3 get_el
| null | https://raw.githubusercontent.com/akabe/ocaml-crf/ced26bcce559b1eda307f7a8961ac9e52905882f/lib/crf_eval.ml | ocaml | prediction | --- A library for conditional random field ( CRF ) in OCaml
Copyright ( C ) 2015 < >
This program is free software ; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation ; either version 3 of the License , or ( at your option ) any later
version .
This program is distributed in the hope that it will be useful , but WITHOUT
ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE . See the GNU General Public License for more
details .
You should have received a copy of the GNU General Public License along with
this program . If not , see < / > .
Copyright (C) 2015 Akinori ABE <>
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program. If not, see </>. *)
open Format
open Crf_model
type 'a key =
| Label of 'a
| Total
type 'a confusion_matrix =
{
labels : 'a array;
tbl : ('a key * 'a key, int) Hashtbl.t;
}
let confusion_matrix model igs ogs =
let labels = model.out_labels in
let tbl = Hashtbl.create 16 in
Hashtbl.add tbl (Total, Total) 0;
Array.iter (fun x ->
Hashtbl.add tbl (Label x, Total) 0;
Hashtbl.add tbl (Total, Label x) 0;
Array.iter (fun y -> Hashtbl.add tbl (Label x, Label y) 0) labels)
labels;
let incr key =
let n = Hashtbl.find tbl key in
Hashtbl.replace tbl key (succ n)
in
let aux iv ov =
match Crf_graph.get iv with
| { out_label = None; _ } -> ()
| { out_label = Some ans; _ } ->
incr (Label ans, Label pred);
incr (Label ans, Total);
incr (Total, Label pred);
incr (Total, Total)
in
List.iter2 (Crf_graph.iter2 aux) igs ogs;
{ labels; tbl; }
let pp_confusion_matrix pp_out_label ppf { labels; tbl } =
let n = Array.length labels in
let pp_label ppf i =
if i <= n then pp_out_label ppf labels.(i-1)
else pp_print_string ppf "Total"
in
let pp_end_col ppf ~row:_ ~col:_ = pp_print_string ppf " | " in
let get_el i j =
let k1 = if i <= n then Label labels.(i-1) else Total in
let k2 = if j <= n then Label labels.(j-1) else Total in
Hashtbl.find tbl (k1, k2)
in
Slap.Io.pp_table ~pp_end_col ~pp_left:pp_label ~pp_head:pp_label
pp_print_int ppf (n + 1) (n + 1) get_el
let div m n = if n = 0 then None else Some (float m /. float n)
let accuracy { labels; tbl; } =
let deno = Hashtbl.find tbl (Total, Total) in
let nume = Array.fold_left
(fun acc x -> acc + Hashtbl.find tbl (Label x, Label x))
0 labels in
div nume deno
let precision { labels; tbl; } =
Array.map (fun x ->
let deno = Hashtbl.find tbl (Total, Label x) in
let nume = Hashtbl.find tbl (Label x, Label x) in
div nume deno)
labels
let recall { labels; tbl; } =
Array.map (fun x ->
let deno = Hashtbl.find tbl (Label x, Total) in
let nume = Hashtbl.find tbl (Label x, Label x) in
div nume deno)
labels
let f_score { labels; tbl; } =
Array.map (fun x ->
let denoP = Hashtbl.find tbl (Total, Label x) in
let denoR = Hashtbl.find tbl (Label x, Total) in
let nume = Hashtbl.find tbl (Label x, Label x) in
if denoP = 0 || denoR = 0 then None
else begin
let prec = float nume /. float denoP in
let recall = float nume /. float denoR in
Some (2.0 *. prec *. recall /. (prec +. recall))
end)
labels
let pp_score pp_out_label ppf cmat =
let precs = precision cmat in
let recalls = recall cmat in
let fs = f_score cmat in
let n = Array.length cmat.labels in
let pp_left ppf i = pp_out_label ppf cmat.labels.(i-1) in
let pp_head ppf i =
pp_print_string ppf [|"Precision"; "Recall"; "F-score"|].(i-1)
in
let pp_end_col ppf ~row:_ ~col:_ = pp_print_string ppf " | " in
let get_el i j = [|precs; recalls; fs|].(j-1).(i-1) in
let pp_el ppf = function
| None -> pp_print_string ppf "N/A"
| Some x -> fprintf ppf "%g" x in
Slap.Io.pp_table ~pp_end_col ~pp_left ~pp_head pp_el ppf n 3 get_el
|
c4839893330a69a3c6a64cb9e5b161520eff4d88ad49301aa5b51e0ec5c71c5f | INRIA/zelus | zmatching.ml | (***********************************************************************)
(* *)
(* *)
(* Zelus, a synchronous language for hybrid systems *)
(* *)
( c ) 2020 Paris ( see the file )
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
Automatique . All rights reserved . This file is distributed under
the terms of the INRIA Non - Commercial License Agreement ( see the
(* LICENSE file). *)
(* *)
(* *********************************************************************)
A generic pattern - matching verifier based on paper at JFLA
Author : 2009
See
Implemented originally in the Lucid Synchrone compiler , V4 by A.Guatto
(** Useful functions *)
let rec repeat n a = match n with | 0 -> [] | n -> a :: (repeat (n - 1) a)
(* keep l n returns the rest l' such that l = p @ l' with p of size n *)
let rec keep l n = match (l, n) with
| (_, 0) -> invalid_arg "keep"
| (h :: _, 1) -> h
| (_ :: t, n) -> keep t (n - 1)
| _ -> invalid_arg "keep"
(* keep l n returns the prefix p of size n such that l = p @ l' *)
let rec drop l n = match (l, n) with
| (_, 0) -> invalid_arg "drop"
| (_ :: t, 1) -> t
| (h :: t, n) -> h :: (drop t (n - 1))
| _ -> invalid_arg "drop"
let rec range n m = if n > m then [] else n :: (range (n + 1) m)
(* split l into p and l' such that l = p @ l with p of size n *)
let separate n l =
let rec f acc n l = match (n, l) with
| (0, _) -> (acc, l)
| (n, h :: t) -> f (h :: acc) (n - 1) t
| _ -> assert false in
if n > List.length l
then invalid_arg "separate"
else
let (p, l) = f [] n l in
(List.rev p, l)
(* Syntax for patterns, and pretty-printers *)
(** Generic pattern, basically constructors with holes and alternation,
tagged with any type. *)
type 'a pattern =
| Pany
| Por of 'a pattern * 'a pattern
| Pconstr of 'a * 'a pattern list
and 'a patt_vec = 'a pattern list
(* Row vectors *)
and 'a patt_matrix = 'a patt_vec list
(* Module type for constructor signatures *)
(** Module type for pattern signatures. *)
module type SIG =
sig
type tag
val compare : tag -> tag -> int
val arity : tag -> int
val is_complete : tag list -> bool
val not_in : tag list -> tag
type pattern_ast
val inject : pattern_ast -> tag pattern
val eject : tag pattern -> pattern_ast
end
(* The algorithm itself, parametrized over signatures *)
module PATTERN_CHECKER = functor (S : SIG) ->
struct
module SSet =
Set.Make(struct
type t = S.tag
let compare = S.compare
end)
(* Used for signature management. *)
let uniq l = SSet.elements (List.fold_right SSet.add l SSet.empty)
(* Wrappers for S's signature functions. Well, we should switch to something
more efficient than sorting at each call. *)
let is_complete sigma = S.is_complete (uniq sigma)
let not_in sigma = S.not_in (uniq sigma)
(** Extract constructors from pattern. *)
let rec head_constrs h = match h with
| Pconstr (c, q) -> [(c, List.length q)]
| Por (l, r) -> head_constrs l @ head_constrs r
| Pany -> []
* Implementation of S(c , p ) as described in the paper 's first part .
let rec matS c ar p =
let vecS pv = match pv with
| [] -> assert false
| Pconstr (c', r') :: pv' -> if S.compare c c' = 0 then [r' @ pv'] else []
| Pany :: pv' -> [repeat ar Pany @ pv']
| Por (t1, t2) :: pv' -> matS c ar [t1 :: pv'; t2 :: pv'] in
List.concat (List.map vecS p)
* Implementation of D(p ) as described in the paper 's first part .
let rec matD p =
let vecD pv = match pv with
| Pconstr _ :: _ -> []
| Pany :: pv' -> [pv']
| Por (t1, t2) :: pv' -> matD [t1 :: pv'; t2 :: pv']
| _ -> assert false in
List.concat (List.map vecD p)
(** U(p,q) from the paper. Most important function, called by higher level
ones. Tests the usefulness of q relatively to p. *)
let rec algU p q =
match (p, q) with
| ([], _) -> true (* p has no lines *)
| (_ :: _, []) -> false (* p has no columns *)
| (h :: t, Pconstr (c, r) :: q') ->
let p' = matS c (List.length r) p in
algU p' (r @ q')
| (h :: t, Por (r1, r2) :: q') ->
algU p (r1 :: q') || algU p (r2 :: q')
| (h :: t, Pany :: q') ->
let sigma =
List.concat (List.map (fun v -> head_constrs (List.hd v)) p) in
let algU_constr (c_k, ar_k) =
let p' = matS c_k ar_k p in
algU p' (repeat ar_k Pany @ q') in
let sigma_used = List.exists algU_constr sigma in
sigma_used || (if not (is_complete (List.map fst sigma))
then algU (matD p) q' else false)
(** Type used for efficient testing of usefulness and redundancy of
pattern-matching cases. *)
type 'a trivec = { p : 'a patt_vec;
q : 'a patt_vec;
r : 'a patt_vec }
and 'a trimat = 'a trivec list
* Second de finition of S(c , p ) for tri - matrices .
let rec trimatS c arity mv =
let filter_line l = match l.p with
| Pconstr (c', t) :: p' ->
if S.compare c c' = 0 then [{ l with p = t @ p' }] else []
| Pany :: p' ->
[{ l with p = repeat arity Pany @ p' }]
| Por (t1, t2) :: p' ->
trimatS c arity [{ l with p = t1 :: p' }; { l with p = t2 :: p' }]
| _ -> assert false in
List.concat (List.map filter_line mv)
(** {i shift1 l} shifts an element from {i l.p} to {i l.q}. *)
let shift1 l = match l.p with
| p :: p' -> { l with p = p'; q = p :: l.q }
| _ -> assert false
(** {i shift2 l} shifts an element from {i l.p} to {i l.r}. *)
let shift2 l = match l.p with
| p :: p' -> { l with p = p'; r = p :: l.r }
| _ -> assert false
(** {i S.tag pattern list option} is used for results of usefulness testing
for Or(r1,r2) patterns. Some [] means that r1 and r2 are both useful,
Some [r1] (resp. Some [r2]) means that r1 (resp. r2) is useless, and
None means that both are. *)
(** The following functions implement useful shortcuts. *)
let simple_union e e' = match (e, e') with
| (Some l, Some l') -> Some (l @ l')
| (None, _) | (_, None) -> None
let union r1 r2 e' e'' = match (e', e'') with
| (Some [], Some []) -> Some []
| (None, None) -> None
| (Some [], None) -> Some [r2]
| (None, Some []) -> Some [r1]
| (Some [], Some (_ :: _)) -> e''
| (Some (_ :: _), Some []) -> e'
| (None, Some ((_ :: _) as t)) -> Some (r1 :: t)
| (Some ((_ :: _) as t), None) -> Some (r2 :: t)
| (Some ((_ :: _) as t'), Some ((_ :: _) as t'')) -> Some (t' @ t'')
(** Efficient usefulness check with special Or pattern management. *)
let rec algU' m v =
match v.p with
(* Phase one *)
| Pconstr (c, t) :: p' ->
algU' (trimatS c (List.length t) m) { v with p = t @ p' }
| Pany :: _ ->
algU' (List.map shift1 m) (shift1 v)
| Por _ :: _ ->
algU' (List.map shift2 m) (shift2 v)
| [] ->
Phase two
begin match v.r with
| [] ->
let qm = List.map (fun l -> l.q) m in
if algU qm v.q then Some [] else None
| _ :: _ ->
let rec compute_Ej j =
begin match List.nth v.r (j - 1) with
| Por (t1, t2) ->
let f l =
let r_j = keep l.r j
and r_woj = drop l.r j in
{ p = [r_j]; q = r_woj @ l.q; r = [] } in
let rv_woj = drop v.r j in
let m' = List.map f m in
let m'' =
m' @ [{ p = [t1]; q = drop v.r j @ v.q; r = [] }] in
let r1 = algU' m'
{ p = [t1]; q = rv_woj @ v.q; r = [] }
and r2 = algU' m''
{ p = [t2]; q = rv_woj @ v.q; r = [] } in
union t1 t2 r1 r2
| _ -> assert false
end in
let j_list = range 1 (List.length (List.hd m).r) in
let computed_Ej = List.map compute_Ej j_list in
List.fold_left simple_union (Some []) computed_Ej
end
(** Completely construct a non-matched pattern. If none is returned,
this matrix is exhaustive. *)
let rec algI m n = match (m, n) with
| ([], 0) -> Some []
| ([] :: _, 0) -> None
| (m, n) ->
let sigma =
List.concat (List.map (fun v -> head_constrs (List.hd v)) m) in
let sigma_c = List.map fst sigma in
let default =
if is_complete sigma_c
then None
else algI (matD m) (n - 1) in
begin match default with
| Some p ->
begin match sigma with
| [] -> Some (Pany :: p)
| _ :: _ ->
let c' = not_in sigma_c in
Some (Pconstr (c', repeat (S.arity c') Pany) :: p)
end
| None ->
let rec traverse_sigma sigma = match sigma with
| [] -> None
| (c, ar) :: sigma' ->
let res =
algI (matS c ar m) (ar + n - 1) in
begin match res with
| None -> traverse_sigma sigma'
| Some v ->
let (r, p) = separate ar v in
Some (Pconstr (c, r) :: p)
end in
traverse_sigma sigma
end
type result = { not_matched : S.pattern_ast option;
redundant_patterns : S.pattern_ast list; }
let check m =
let m' = List.map (fun v -> [S.inject v]) m in
match m' with
| [] -> invalid_arg "check"
| v :: _ ->
{ not_matched =
begin
let n = List.length v in
match algI m' n with
| None -> None
| Some [p] -> Some (S.eject p)
| _ -> assert false
end;
redundant_patterns =
begin
let make_trivec v = { p = v; q = []; r = [] } in
let make_trimat m = List.map make_trivec m in
let check_line (m, red) v =
let r = algU' (make_trimat m) (make_trivec v) in
(m @ [v], match r with
| Some [] -> red
| Some r -> List.map S.eject r @ red
| None -> List.map S.eject v @ red) in
let (_, red) = List.fold_left
check_line ([(List.hd m')], []) (List.tl m') in
red;
end }
end
| null | https://raw.githubusercontent.com/INRIA/zelus/685428574b0f9100ad5a41bbaa416cd7a2506d5e/compiler/typing/zmatching.ml | ocaml | *********************************************************************
Zelus, a synchronous language for hybrid systems
Copyright Institut National de Recherche en Informatique et en
LICENSE file).
********************************************************************
* Useful functions
keep l n returns the rest l' such that l = p @ l' with p of size n
keep l n returns the prefix p of size n such that l = p @ l'
split l into p and l' such that l = p @ l with p of size n
Syntax for patterns, and pretty-printers
* Generic pattern, basically constructors with holes and alternation,
tagged with any type.
Row vectors
Module type for constructor signatures
* Module type for pattern signatures.
The algorithm itself, parametrized over signatures
Used for signature management.
Wrappers for S's signature functions. Well, we should switch to something
more efficient than sorting at each call.
* Extract constructors from pattern.
* U(p,q) from the paper. Most important function, called by higher level
ones. Tests the usefulness of q relatively to p.
p has no lines
p has no columns
* Type used for efficient testing of usefulness and redundancy of
pattern-matching cases.
* {i shift1 l} shifts an element from {i l.p} to {i l.q}.
* {i shift2 l} shifts an element from {i l.p} to {i l.r}.
* {i S.tag pattern list option} is used for results of usefulness testing
for Or(r1,r2) patterns. Some [] means that r1 and r2 are both useful,
Some [r1] (resp. Some [r2]) means that r1 (resp. r2) is useless, and
None means that both are.
* The following functions implement useful shortcuts.
* Efficient usefulness check with special Or pattern management.
Phase one
* Completely construct a non-matched pattern. If none is returned,
this matrix is exhaustive. | ( c ) 2020 Paris ( see the file )
Automatique . All rights reserved . This file is distributed under
the terms of the INRIA Non - Commercial License Agreement ( see the
A generic pattern - matching verifier based on paper at JFLA
Author : 2009
See
Implemented originally in the Lucid Synchrone compiler , V4 by A.Guatto
let rec repeat n a = match n with | 0 -> [] | n -> a :: (repeat (n - 1) a)
let rec keep l n = match (l, n) with
| (_, 0) -> invalid_arg "keep"
| (h :: _, 1) -> h
| (_ :: t, n) -> keep t (n - 1)
| _ -> invalid_arg "keep"
let rec drop l n = match (l, n) with
| (_, 0) -> invalid_arg "drop"
| (_ :: t, 1) -> t
| (h :: t, n) -> h :: (drop t (n - 1))
| _ -> invalid_arg "drop"
let rec range n m = if n > m then [] else n :: (range (n + 1) m)
let separate n l =
let rec f acc n l = match (n, l) with
| (0, _) -> (acc, l)
| (n, h :: t) -> f (h :: acc) (n - 1) t
| _ -> assert false in
if n > List.length l
then invalid_arg "separate"
else
let (p, l) = f [] n l in
(List.rev p, l)
type 'a pattern =
| Pany
| Por of 'a pattern * 'a pattern
| Pconstr of 'a * 'a pattern list
and 'a patt_vec = 'a pattern list
and 'a patt_matrix = 'a patt_vec list
module type SIG =
sig
type tag
val compare : tag -> tag -> int
val arity : tag -> int
val is_complete : tag list -> bool
val not_in : tag list -> tag
type pattern_ast
val inject : pattern_ast -> tag pattern
val eject : tag pattern -> pattern_ast
end
module PATTERN_CHECKER = functor (S : SIG) ->
struct
module SSet =
Set.Make(struct
type t = S.tag
let compare = S.compare
end)
let uniq l = SSet.elements (List.fold_right SSet.add l SSet.empty)
let is_complete sigma = S.is_complete (uniq sigma)
let not_in sigma = S.not_in (uniq sigma)
let rec head_constrs h = match h with
| Pconstr (c, q) -> [(c, List.length q)]
| Por (l, r) -> head_constrs l @ head_constrs r
| Pany -> []
* Implementation of S(c , p ) as described in the paper 's first part .
let rec matS c ar p =
let vecS pv = match pv with
| [] -> assert false
| Pconstr (c', r') :: pv' -> if S.compare c c' = 0 then [r' @ pv'] else []
| Pany :: pv' -> [repeat ar Pany @ pv']
| Por (t1, t2) :: pv' -> matS c ar [t1 :: pv'; t2 :: pv'] in
List.concat (List.map vecS p)
* Implementation of D(p ) as described in the paper 's first part .
let rec matD p =
let vecD pv = match pv with
| Pconstr _ :: _ -> []
| Pany :: pv' -> [pv']
| Por (t1, t2) :: pv' -> matD [t1 :: pv'; t2 :: pv']
| _ -> assert false in
List.concat (List.map vecD p)
let rec algU p q =
match (p, q) with
| (h :: t, Pconstr (c, r) :: q') ->
let p' = matS c (List.length r) p in
algU p' (r @ q')
| (h :: t, Por (r1, r2) :: q') ->
algU p (r1 :: q') || algU p (r2 :: q')
| (h :: t, Pany :: q') ->
let sigma =
List.concat (List.map (fun v -> head_constrs (List.hd v)) p) in
let algU_constr (c_k, ar_k) =
let p' = matS c_k ar_k p in
algU p' (repeat ar_k Pany @ q') in
let sigma_used = List.exists algU_constr sigma in
sigma_used || (if not (is_complete (List.map fst sigma))
then algU (matD p) q' else false)
type 'a trivec = { p : 'a patt_vec;
q : 'a patt_vec;
r : 'a patt_vec }
and 'a trimat = 'a trivec list
* Second de finition of S(c , p ) for tri - matrices .
let rec trimatS c arity mv =
let filter_line l = match l.p with
| Pconstr (c', t) :: p' ->
if S.compare c c' = 0 then [{ l with p = t @ p' }] else []
| Pany :: p' ->
[{ l with p = repeat arity Pany @ p' }]
| Por (t1, t2) :: p' ->
trimatS c arity [{ l with p = t1 :: p' }; { l with p = t2 :: p' }]
| _ -> assert false in
List.concat (List.map filter_line mv)
let shift1 l = match l.p with
| p :: p' -> { l with p = p'; q = p :: l.q }
| _ -> assert false
let shift2 l = match l.p with
| p :: p' -> { l with p = p'; r = p :: l.r }
| _ -> assert false
let simple_union e e' = match (e, e') with
| (Some l, Some l') -> Some (l @ l')
| (None, _) | (_, None) -> None
let union r1 r2 e' e'' = match (e', e'') with
| (Some [], Some []) -> Some []
| (None, None) -> None
| (Some [], None) -> Some [r2]
| (None, Some []) -> Some [r1]
| (Some [], Some (_ :: _)) -> e''
| (Some (_ :: _), Some []) -> e'
| (None, Some ((_ :: _) as t)) -> Some (r1 :: t)
| (Some ((_ :: _) as t), None) -> Some (r2 :: t)
| (Some ((_ :: _) as t'), Some ((_ :: _) as t'')) -> Some (t' @ t'')
let rec algU' m v =
match v.p with
| Pconstr (c, t) :: p' ->
algU' (trimatS c (List.length t) m) { v with p = t @ p' }
| Pany :: _ ->
algU' (List.map shift1 m) (shift1 v)
| Por _ :: _ ->
algU' (List.map shift2 m) (shift2 v)
| [] ->
Phase two
begin match v.r with
| [] ->
let qm = List.map (fun l -> l.q) m in
if algU qm v.q then Some [] else None
| _ :: _ ->
let rec compute_Ej j =
begin match List.nth v.r (j - 1) with
| Por (t1, t2) ->
let f l =
let r_j = keep l.r j
and r_woj = drop l.r j in
{ p = [r_j]; q = r_woj @ l.q; r = [] } in
let rv_woj = drop v.r j in
let m' = List.map f m in
let m'' =
m' @ [{ p = [t1]; q = drop v.r j @ v.q; r = [] }] in
let r1 = algU' m'
{ p = [t1]; q = rv_woj @ v.q; r = [] }
and r2 = algU' m''
{ p = [t2]; q = rv_woj @ v.q; r = [] } in
union t1 t2 r1 r2
| _ -> assert false
end in
let j_list = range 1 (List.length (List.hd m).r) in
let computed_Ej = List.map compute_Ej j_list in
List.fold_left simple_union (Some []) computed_Ej
end
let rec algI m n = match (m, n) with
| ([], 0) -> Some []
| ([] :: _, 0) -> None
| (m, n) ->
let sigma =
List.concat (List.map (fun v -> head_constrs (List.hd v)) m) in
let sigma_c = List.map fst sigma in
let default =
if is_complete sigma_c
then None
else algI (matD m) (n - 1) in
begin match default with
| Some p ->
begin match sigma with
| [] -> Some (Pany :: p)
| _ :: _ ->
let c' = not_in sigma_c in
Some (Pconstr (c', repeat (S.arity c') Pany) :: p)
end
| None ->
let rec traverse_sigma sigma = match sigma with
| [] -> None
| (c, ar) :: sigma' ->
let res =
algI (matS c ar m) (ar + n - 1) in
begin match res with
| None -> traverse_sigma sigma'
| Some v ->
let (r, p) = separate ar v in
Some (Pconstr (c, r) :: p)
end in
traverse_sigma sigma
end
type result = { not_matched : S.pattern_ast option;
redundant_patterns : S.pattern_ast list; }
let check m =
let m' = List.map (fun v -> [S.inject v]) m in
match m' with
| [] -> invalid_arg "check"
| v :: _ ->
{ not_matched =
begin
let n = List.length v in
match algI m' n with
| None -> None
| Some [p] -> Some (S.eject p)
| _ -> assert false
end;
redundant_patterns =
begin
let make_trivec v = { p = v; q = []; r = [] } in
let make_trimat m = List.map make_trivec m in
let check_line (m, red) v =
let r = algU' (make_trimat m) (make_trivec v) in
(m @ [v], match r with
| Some [] -> red
| Some r -> List.map S.eject r @ red
| None -> List.map S.eject v @ red) in
let (_, red) = List.fold_left
check_line ([(List.hd m')], []) (List.tl m') in
red;
end }
end
|
f23b65552753a2d85abd6364bfbce482e48c885f65a28781af931bef9cbce75c | qfpl/reflex-workshop | Routing.hs | |
Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
module UI.Routing (
mkMain
) where
import Control.Monad (void)
import Control.Monad.Reader (MonadReader)
import qualified Data.Map as Map
import Reflex.Dom.Core
import Reflex.Dom.Routing.Nested
import Reflex.Dom.Routing.Writer
import Reflex.Dom.Storage.Class
import State
import Types.Interactivity
import Types.RouteFragment
import Types.Section
import UI.Section
mkMain :: ( MonadWidget t m
, RouteWriter t RouteFragment m
, HasRoute t RouteFragment m
, HasStorage t AppTags m
, MonadReader Interactivity m
)
=> [Section m]
-> m ()
-> m ()
mkMain sections d = do
let
routeMap = Map.fromList . fmap (\s -> (_sRoute s, s)) $ sections
void . withRoute $ \route ->
case route of
Just p ->
case Map.lookup p routeMap of
Just s -> mkMain (_sSubSections s) $ mkSection s
TODO replace this with an error page ?
Nothing -> tellRedirectLocally [Page "events"]
_ ->
d
| null | https://raw.githubusercontent.com/qfpl/reflex-workshop/244ef13fb4b2e884f455eccc50072e98d1668c9e/src/UI/Routing.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE GADTs # | |
Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
# LANGUAGE FlexibleContexts #
module UI.Routing (
mkMain
) where
import Control.Monad (void)
import Control.Monad.Reader (MonadReader)
import qualified Data.Map as Map
import Reflex.Dom.Core
import Reflex.Dom.Routing.Nested
import Reflex.Dom.Routing.Writer
import Reflex.Dom.Storage.Class
import State
import Types.Interactivity
import Types.RouteFragment
import Types.Section
import UI.Section
mkMain :: ( MonadWidget t m
, RouteWriter t RouteFragment m
, HasRoute t RouteFragment m
, HasStorage t AppTags m
, MonadReader Interactivity m
)
=> [Section m]
-> m ()
-> m ()
mkMain sections d = do
let
routeMap = Map.fromList . fmap (\s -> (_sRoute s, s)) $ sections
void . withRoute $ \route ->
case route of
Just p ->
case Map.lookup p routeMap of
Just s -> mkMain (_sSubSections s) $ mkSection s
TODO replace this with an error page ?
Nothing -> tellRedirectLocally [Page "events"]
_ ->
d
|
048dd0838edaca218958095df843472f6081b0a9bd89ced3b0cd1ce07dd03dfa | ygmpkk/house | HuttonMeijerWallace.hs | ----------------------------------------------------------------------------
A LIBRARY OF MONADIC PARSER COMBINATORS
29th July 1996
University of Nottingham University of Utrecht
This 1.3 script defines a library of parser combinators , and is taken
from sections 1 - 6 of our article " Monadic Parser Combinators " . Some changes
to the library have been made in the move from Gofer to :
* Do notation is used in place of monad comprehension notation ;
* The parser datatype is defined using " newtype " , to avoid the overhead
of tagging and untagging parsers with the P constructor .
------------------------------------------------------------------------------
* * Extended to allow a symbol table / state to be threaded through the monad .
* * Extended to allow a parameterised token type , rather than just strings .
* * Extended to allow error - reporting .
( Extensions : 1998 - 2000 )
-----------------------------------------------------------------------------
A LIBRARY OF MONADIC PARSER COMBINATORS
29th July 1996
Graham Hutton Erik Meijer
University of Nottingham University of Utrecht
This Haskell 1.3 script defines a library of parser combinators, and is taken
from sections 1-6 of our article "Monadic Parser Combinators". Some changes
to the library have been made in the move from Gofer to Haskell:
* Do notation is used in place of monad comprehension notation;
* The parser datatype is defined using "newtype", to avoid the overhead
of tagging and untagging parsers with the P constructor.
------------------------------------------------------------------------------
** Extended to allow a symbol table/state to be threaded through the monad.
** Extended to allow a parameterised token type, rather than just strings.
** Extended to allow error-reporting.
(Extensions: 1998-2000 )
------------------------------------------------------------------------------}
-- | This library of monadic parser combinators is based on the ones
defined by and . It has been extended by
to use an abstract token type ( no longer just a
string ) as input , and to incorporate a State Transformer monad , useful
-- for symbol tables, macros, and so on. Basic facilities for error
-- reporting have also been added.
module Text.ParserCombinators.HuttonMeijerWallace
(
-- * The parser monad
Parser(..)
-- * Primitive parser combinators
, item, papply
-- * Derived combinators
, (+++), {-sat,-} tok, nottok, many, many1
, sepby, sepby1, chainl, chainl1, chainr, chainr1, ops, bracket
-- * Error handling
, elserror
-- * State handling
, stupd, stquery, stget
-- * Re-parsing
, reparse
) where
import Char
import Monad
infixr 5 +++
--- The parser monad ---------------------------------------------------------
newtype Parser s t a = P (s -> [t] -> [(a,s,[t])])
-- ^ The parser type is parametrised on the types of the state @s@,
the input tokens @t@ , and the result value The state and
-- remaining input are threaded through the monad.
instance Functor (Parser s t) where
fmap : : ( a - > b ) - > ( s t a - > Parser s t b )
fmap f (P p) = P (\st inp -> [(f v, s, out) | (v,s,out) <- p st inp])
instance Monad (Parser s t) where
return : : a - > s t a
return v = P (\st inp -> [(v,st,inp)])
> > = : : s t a - > ( a - > Parser s t b ) - > s t b
(P p) >>= f = P (\st inp -> concat [ papply (f v) s out
| (v,s,out) <- p st inp ])
-- fail :: String -> Parser s t a
fail _ = P (\st inp -> [])
instance MonadPlus (Parser s t) where
mzero : : s t a
mzero = P (\st inp -> [])
mplus : : s t a - > s t a - > Parser s t a
(P p) `mplus` (P q) = P (\st inp -> (p st inp ++ q st inp))
--- Primitive parser combinators ---------------------------------------------
| Deliver the first remaining token .
item :: Parser s t t
item = P (\st inp -> case inp of
[] -> []
(x:xs) -> [(x,st,xs)])
| Ensure the value delivered by the parser is evaluated to WHNF .
force :: Parser s t a -> Parser s t a
force (P p) = P (\st inp -> let xs = p st inp
h = head xs in
h `seq` (h: tail xs))
| Deliver the first parse result only , eliminating any backtracking .
first :: Parser s t a -> Parser s t a
first (P p) = P (\st inp -> case p st inp of
[] -> []
(x:xs) -> [x])
-- | Apply the parser to some real input, given an initial state value.
papply :: Parser s t a -> s -> [t] -> [(a,s,[t])]
papply (P p) st inp = p st inp
--- Derived combinators ------------------------------------------------------
| A choice between parsers . Keep only the first success .
(+++) :: Parser s t a -> Parser s t a -> Parser s t a
p +++ q = first (p `mplus` q)
| Deliver the first token if it satisfies a predicate .
sat :: (t -> Bool) -> Parser s (p,t) t
sat p = do {(_,x) <- item; if p x then return x else mzero}
| Deliver the first token if it equals the argument .
tok :: Eq t => t -> Parser s (p,t) t
tok t = do {(_,x) <- item; if x==t then return t else mzero}
| Deliver the first token if it does not equal the argument .
nottok :: Eq t => [t] -> Parser s (p,t) t
nottok ts = do {(_,x) <- item; if x `notElem` ts then return x
else mzero}
| Deliver zero or more values of
many :: Parser s t a -> Parser s t [a]
many p = many1 p +++ return []
many p = force ( many1 p + + + return [ ] )
| Deliver one or more values of
many1 :: Parser s t a -> Parser s t [a]
many1 p = do {x <- p; xs <- many p; return (x:xs)}
| Deliver zero or more values of @a@ separated by 's .
sepby :: Parser s t a -> Parser s t b -> Parser s t [a]
p `sepby` sep = (p `sepby1` sep) +++ return []
| Deliver one or more values of @a@ separated by 's .
sepby1 :: Parser s t a -> Parser s t b -> Parser s t [a]
p `sepby1` sep = do {x <- p; xs <- many (do {sep; p}); return (x:xs)}
chainl :: Parser s t a -> Parser s t (a->a->a) -> a -> Parser s t a
chainl p op v = (p `chainl1` op) +++ return v
chainl1 :: Parser s t a -> Parser s t (a->a->a) -> Parser s t a
p `chainl1` op = do {x <- p; rest x}
where
rest x = do {f <- op; y <- p; rest (f x y)}
+++ return x
chainr :: Parser s t a -> Parser s t (a->a->a) -> a -> Parser s t a
chainr p op v = (p `chainr1` op) +++ return v
chainr1 :: Parser s t a -> Parser s t (a->a->a) -> Parser s t a
p `chainr1` op = do {x <- p; rest x}
where
rest x = do { f <- op
; y <- p `chainr1` op
; return (f x y)
}
+++ return x
ops :: [(Parser s t a, b)] -> Parser s t b
ops xs = foldr1 (+++) [do {p; return op} | (p,op) <- xs]
bracket :: (Show p,Show t) =>
Parser s (p,t) a -> Parser s (p,t) b ->
Parser s (p,t) c -> Parser s (p,t) b
bracket open p close = do { open
; x <- p
; close -- `elserror` "improperly matched construct";
; return x
}
--- Error handling -----------------------------------------------------------
-- | If the parser fails, halt with an error message.
elserror :: (Show p,Show t) =>
Parser s (p,t) a -> String -> Parser s (p,t) a
p `elserror` s = p +++
(P (\st inp->
case inp of
[] -> error "Parse error: unexpected EOF\n"
((p,t):_) ->
error ("Parse error in "++show p++"\n "++
s++"\n"++
" actual token found: "++show t)))
--- State handling -----------------------------------------------------------
-- | Update the internal state.
stupd :: (s->s) -> Parser s t ()
stupd f = P (\st inp-> {-let newst = f st in newst `seq`-}
[((), f st, inp)])
-- | Query the internal state.
stquery :: (s->a) -> Parser s t a
stquery f = P (\st inp-> [(f st, st, inp)])
-- | Deliver the entire internal state.
stget :: Parser s t s
stget = P (\st inp-> [(st, st, inp)])
--- Push some tokens back onto the input stream and reparse ------------------
-- | This is useful for recursively expanding macros. When the
-- user-parser recognises a macro use, it can lookup the macro
-- expansion from the parse state, lex it, and then stuff the
-- lexed expansion back down into the parser.
reparse :: [t] -> Parser s t ()
reparse ts = P (\st inp-> [((), st, ts++inp)])
------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/HaXml/src/Text/ParserCombinators/HuttonMeijerWallace.hs | haskell | --------------------------------------------------------------------------
----------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------}
| This library of monadic parser combinators is based on the ones
for symbol tables, macros, and so on. Basic facilities for error
reporting have also been added.
* The parser monad
* Primitive parser combinators
* Derived combinators
sat,
* Error handling
* State handling
* Re-parsing
- The parser monad ---------------------------------------------------------
^ The parser type is parametrised on the types of the state @s@,
remaining input are threaded through the monad.
fail :: String -> Parser s t a
- Primitive parser combinators ---------------------------------------------
| Apply the parser to some real input, given an initial state value.
- Derived combinators ------------------------------------------------------
`elserror` "improperly matched construct";
- Error handling -----------------------------------------------------------
| If the parser fails, halt with an error message.
- State handling -----------------------------------------------------------
| Update the internal state.
let newst = f st in newst `seq`
| Query the internal state.
| Deliver the entire internal state.
- Push some tokens back onto the input stream and reparse ------------------
| This is useful for recursively expanding macros. When the
user-parser recognises a macro use, it can lookup the macro
expansion from the parse state, lex it, and then stuff the
lexed expansion back down into the parser.
---------------------------------------------------------------------------- |
A LIBRARY OF MONADIC PARSER COMBINATORS
29th July 1996
University of Nottingham University of Utrecht
This 1.3 script defines a library of parser combinators , and is taken
from sections 1 - 6 of our article " Monadic Parser Combinators " . Some changes
to the library have been made in the move from Gofer to :
* Do notation is used in place of monad comprehension notation ;
* The parser datatype is defined using " newtype " , to avoid the overhead
of tagging and untagging parsers with the P constructor .
* * Extended to allow a symbol table / state to be threaded through the monad .
* * Extended to allow a parameterised token type , rather than just strings .
* * Extended to allow error - reporting .
( Extensions : 1998 - 2000 )
A LIBRARY OF MONADIC PARSER COMBINATORS
29th July 1996
Graham Hutton Erik Meijer
University of Nottingham University of Utrecht
This Haskell 1.3 script defines a library of parser combinators, and is taken
from sections 1-6 of our article "Monadic Parser Combinators". Some changes
to the library have been made in the move from Gofer to Haskell:
* Do notation is used in place of monad comprehension notation;
* The parser datatype is defined using "newtype", to avoid the overhead
of tagging and untagging parsers with the P constructor.
** Extended to allow a symbol table/state to be threaded through the monad.
** Extended to allow a parameterised token type, rather than just strings.
** Extended to allow error-reporting.
(Extensions: 1998-2000 )
defined by and . It has been extended by
to use an abstract token type ( no longer just a
string ) as input , and to incorporate a State Transformer monad , useful
module Text.ParserCombinators.HuttonMeijerWallace
(
Parser(..)
, item, papply
, sepby, sepby1, chainl, chainl1, chainr, chainr1, ops, bracket
, elserror
, stupd, stquery, stget
, reparse
) where
import Char
import Monad
infixr 5 +++
newtype Parser s t a = P (s -> [t] -> [(a,s,[t])])
the input tokens @t@ , and the result value The state and
instance Functor (Parser s t) where
fmap : : ( a - > b ) - > ( s t a - > Parser s t b )
fmap f (P p) = P (\st inp -> [(f v, s, out) | (v,s,out) <- p st inp])
instance Monad (Parser s t) where
return : : a - > s t a
return v = P (\st inp -> [(v,st,inp)])
> > = : : s t a - > ( a - > Parser s t b ) - > s t b
(P p) >>= f = P (\st inp -> concat [ papply (f v) s out
| (v,s,out) <- p st inp ])
fail _ = P (\st inp -> [])
instance MonadPlus (Parser s t) where
mzero : : s t a
mzero = P (\st inp -> [])
mplus : : s t a - > s t a - > Parser s t a
(P p) `mplus` (P q) = P (\st inp -> (p st inp ++ q st inp))
| Deliver the first remaining token .
item :: Parser s t t
item = P (\st inp -> case inp of
[] -> []
(x:xs) -> [(x,st,xs)])
| Ensure the value delivered by the parser is evaluated to WHNF .
force :: Parser s t a -> Parser s t a
force (P p) = P (\st inp -> let xs = p st inp
h = head xs in
h `seq` (h: tail xs))
| Deliver the first parse result only , eliminating any backtracking .
first :: Parser s t a -> Parser s t a
first (P p) = P (\st inp -> case p st inp of
[] -> []
(x:xs) -> [x])
papply :: Parser s t a -> s -> [t] -> [(a,s,[t])]
papply (P p) st inp = p st inp
| A choice between parsers . Keep only the first success .
(+++) :: Parser s t a -> Parser s t a -> Parser s t a
p +++ q = first (p `mplus` q)
| Deliver the first token if it satisfies a predicate .
sat :: (t -> Bool) -> Parser s (p,t) t
sat p = do {(_,x) <- item; if p x then return x else mzero}
| Deliver the first token if it equals the argument .
tok :: Eq t => t -> Parser s (p,t) t
tok t = do {(_,x) <- item; if x==t then return t else mzero}
| Deliver the first token if it does not equal the argument .
nottok :: Eq t => [t] -> Parser s (p,t) t
nottok ts = do {(_,x) <- item; if x `notElem` ts then return x
else mzero}
| Deliver zero or more values of
many :: Parser s t a -> Parser s t [a]
many p = many1 p +++ return []
many p = force ( many1 p + + + return [ ] )
| Deliver one or more values of
many1 :: Parser s t a -> Parser s t [a]
many1 p = do {x <- p; xs <- many p; return (x:xs)}
| Deliver zero or more values of @a@ separated by 's .
sepby :: Parser s t a -> Parser s t b -> Parser s t [a]
p `sepby` sep = (p `sepby1` sep) +++ return []
| Deliver one or more values of @a@ separated by 's .
sepby1 :: Parser s t a -> Parser s t b -> Parser s t [a]
p `sepby1` sep = do {x <- p; xs <- many (do {sep; p}); return (x:xs)}
chainl :: Parser s t a -> Parser s t (a->a->a) -> a -> Parser s t a
chainl p op v = (p `chainl1` op) +++ return v
chainl1 :: Parser s t a -> Parser s t (a->a->a) -> Parser s t a
p `chainl1` op = do {x <- p; rest x}
where
rest x = do {f <- op; y <- p; rest (f x y)}
+++ return x
chainr :: Parser s t a -> Parser s t (a->a->a) -> a -> Parser s t a
chainr p op v = (p `chainr1` op) +++ return v
chainr1 :: Parser s t a -> Parser s t (a->a->a) -> Parser s t a
p `chainr1` op = do {x <- p; rest x}
where
rest x = do { f <- op
; y <- p `chainr1` op
; return (f x y)
}
+++ return x
ops :: [(Parser s t a, b)] -> Parser s t b
ops xs = foldr1 (+++) [do {p; return op} | (p,op) <- xs]
bracket :: (Show p,Show t) =>
Parser s (p,t) a -> Parser s (p,t) b ->
Parser s (p,t) c -> Parser s (p,t) b
bracket open p close = do { open
; x <- p
; return x
}
elserror :: (Show p,Show t) =>
Parser s (p,t) a -> String -> Parser s (p,t) a
p `elserror` s = p +++
(P (\st inp->
case inp of
[] -> error "Parse error: unexpected EOF\n"
((p,t):_) ->
error ("Parse error in "++show p++"\n "++
s++"\n"++
" actual token found: "++show t)))
stupd :: (s->s) -> Parser s t ()
[((), f st, inp)])
stquery :: (s->a) -> Parser s t a
stquery f = P (\st inp-> [(f st, st, inp)])
stget :: Parser s t s
stget = P (\st inp-> [(st, st, inp)])
reparse :: [t] -> Parser s t ()
reparse ts = P (\st inp-> [((), st, ts++inp)])
|
abc5371b9fd0763e1ba0b431966341c3528eed3f00c70f67fd6a9548e9de36d9 | DOBRO/uef-lib | uef_crypt.erl | Copyright ( c ) 2019 - 2022 , < > . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
-module(uef_crypt).
-export([md5_hex/1]).
%%%------------------------------------------------------------------------------
%%% API
%%%------------------------------------------------------------------------------
md5_hex/1
-spec md5_hex(IoData :: iodata()) -> Binary :: binary().
%% @doc
Returns binary Binary in hexadecimal form of md5 hash of the argument IoData
%% @end
md5_hex(IoData) ->
hstr(erlang:md5(IoData)).
%%%------------------------------------------------------------------------------
%%% Internal functions
%%%------------------------------------------------------------------------------
%% hstr/1
-spec hstr(binary()) -> binary().
hstr(B) when is_binary(B) ->
T = {$0,$1,$2,$3,$4,$5,$6,$7,$8,$9,$a,$b,$c,$d,$e,$f},
<< <<(element(X bsr 4 + 1, T)), (element(X band 16#0F + 1, T))>>
|| <<X:8>> <= B >>.
| null | https://raw.githubusercontent.com/DOBRO/uef-lib/765d28837584bcfced1aae5d5f831972ec0254bb/src/uef_crypt.erl | erlang |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
------------------------------------------------------------------------------
API
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
Internal functions
------------------------------------------------------------------------------
hstr/1 | Copyright ( c ) 2019 - 2022 , < > . 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(uef_crypt).
-export([md5_hex/1]).
md5_hex/1
-spec md5_hex(IoData :: iodata()) -> Binary :: binary().
Returns binary Binary in hexadecimal form of md5 hash of the argument IoData
md5_hex(IoData) ->
hstr(erlang:md5(IoData)).
-spec hstr(binary()) -> binary().
hstr(B) when is_binary(B) ->
T = {$0,$1,$2,$3,$4,$5,$6,$7,$8,$9,$a,$b,$c,$d,$e,$f},
<< <<(element(X bsr 4 + 1, T)), (element(X band 16#0F + 1, T))>>
|| <<X:8>> <= B >>.
|
e60d58930ba37f2e6989a0d817e3202659a5355fc1d854d38163d4c6665a76e4 | simplex-chat/simplexmq | M20220101_initial.hs | # LANGUAGE QuasiQuotes #
module Simplex.Messaging.Agent.Store.SQLite.Migrations.M20220101_initial where
import Database.SQLite.Simple (Query)
import Database.SQLite.Simple.QQ (sql)
m20220101_initial :: Query
m20220101_initial =
[sql|
CREATE TABLE servers (
host TEXT NOT NULL,
port TEXT NOT NULL,
key_hash BLOB NOT NULL,
PRIMARY KEY (host, port)
) WITHOUT ROWID;
CREATE TABLE connections (
conn_id BLOB NOT NULL PRIMARY KEY,
conn_mode TEXT NOT NULL,
last_internal_msg_id INTEGER NOT NULL DEFAULT 0,
last_internal_rcv_msg_id INTEGER NOT NULL DEFAULT 0,
last_internal_snd_msg_id INTEGER NOT NULL DEFAULT 0,
last_external_snd_msg_id INTEGER NOT NULL DEFAULT 0,
last_rcv_msg_hash BLOB NOT NULL DEFAULT x'',
last_snd_msg_hash BLOB NOT NULL DEFAULT x'',
smp_agent_version INTEGER NOT NULL DEFAULT 1
) WITHOUT ROWID;
CREATE TABLE rcv_queues (
host TEXT NOT NULL,
port TEXT NOT NULL,
rcv_id BLOB NOT NULL,
conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE,
rcv_private_key BLOB NOT NULL,
rcv_dh_secret BLOB NOT NULL,
e2e_priv_key BLOB NOT NULL,
e2e_dh_secret BLOB,
snd_id BLOB NOT NULL,
snd_key BLOB,
status TEXT NOT NULL,
smp_server_version INTEGER NOT NULL DEFAULT 1,
smp_client_version INTEGER,
PRIMARY KEY (host, port, rcv_id),
FOREIGN KEY (host, port) REFERENCES servers
ON DELETE RESTRICT ON UPDATE CASCADE,
UNIQUE (host, port, snd_id)
) WITHOUT ROWID;
CREATE TABLE snd_queues (
host TEXT NOT NULL,
port TEXT NOT NULL,
snd_id BLOB NOT NULL,
conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE,
snd_private_key BLOB NOT NULL,
e2e_dh_secret BLOB NOT NULL,
status TEXT NOT NULL,
smp_server_version INTEGER NOT NULL DEFAULT 1,
smp_client_version INTEGER NOT NULL DEFAULT 1,
PRIMARY KEY (host, port, snd_id),
FOREIGN KEY (host, port) REFERENCES servers
ON DELETE RESTRICT ON UPDATE CASCADE
) WITHOUT ROWID;
CREATE TABLE messages (
conn_id BLOB NOT NULL REFERENCES connections (conn_id)
ON DELETE CASCADE,
internal_id INTEGER NOT NULL,
internal_ts TEXT NOT NULL,
internal_rcv_id INTEGER,
internal_snd_id INTEGER,
( H)ELLO , ( R)EPLY , ( D)ELETE . Should SMP confirmation be saved too ?
msg_body BLOB NOT NULL DEFAULT x'',
PRIMARY KEY (conn_id, internal_id),
FOREIGN KEY (conn_id, internal_rcv_id) REFERENCES rcv_messages
ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
FOREIGN KEY (conn_id, internal_snd_id) REFERENCES snd_messages
ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED
) WITHOUT ROWID;
CREATE TABLE rcv_messages (
conn_id BLOB NOT NULL,
internal_rcv_id INTEGER NOT NULL,
internal_id INTEGER NOT NULL,
external_snd_id INTEGER NOT NULL,
broker_id BLOB NOT NULL,
broker_ts TEXT NOT NULL,
internal_hash BLOB NOT NULL,
external_prev_snd_hash BLOB NOT NULL,
integrity BLOB NOT NULL,
PRIMARY KEY (conn_id, internal_rcv_id),
FOREIGN KEY (conn_id, internal_id) REFERENCES messages
ON DELETE CASCADE
) WITHOUT ROWID;
CREATE TABLE snd_messages (
conn_id BLOB NOT NULL,
internal_snd_id INTEGER NOT NULL,
internal_id INTEGER NOT NULL,
internal_hash BLOB NOT NULL,
previous_msg_hash BLOB NOT NULL DEFAULT x'',
PRIMARY KEY (conn_id, internal_snd_id),
FOREIGN KEY (conn_id, internal_id) REFERENCES messages
ON DELETE CASCADE
) WITHOUT ROWID;
CREATE TABLE conn_confirmations (
confirmation_id BLOB NOT NULL PRIMARY KEY,
conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE,
e2e_snd_pub_key BLOB NOT NULL,
sender_key BLOB NOT NULL,
ratchet_state BLOB NOT NULL,
sender_conn_info BLOB NOT NULL,
accepted INTEGER NOT NULL,
own_conn_info BLOB,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
) WITHOUT ROWID;
CREATE TABLE conn_invitations (
invitation_id BLOB NOT NULL PRIMARY KEY,
contact_conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE,
cr_invitation BLOB NOT NULL,
recipient_conn_info BLOB NOT NULL,
accepted INTEGER NOT NULL DEFAULT 0,
own_conn_info BLOB,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
) WITHOUT ROWID;
CREATE TABLE ratchets (
conn_id BLOB NOT NULL PRIMARY KEY REFERENCES connections
ON DELETE CASCADE,
-- x3dh keys are not saved on the sending side (the side accepting the connection)
x3dh_priv_key_1 BLOB,
x3dh_priv_key_2 BLOB,
-- ratchet is initially empty on the receiving side (the side offering the connection)
ratchet_state BLOB,
e2e_version INTEGER NOT NULL DEFAULT 1
) WITHOUT ROWID;
CREATE TABLE skipped_messages (
skipped_message_id INTEGER PRIMARY KEY,
conn_id BLOB NOT NULL REFERENCES ratchets
ON DELETE CASCADE,
header_key BLOB NOT NULL,
msg_n INTEGER NOT NULL,
msg_key BLOB NOT NULL
);
|]
| null | https://raw.githubusercontent.com/simplex-chat/simplexmq/69a5896dac4505ca2a570f080cf96167afdee535/src/Simplex/Messaging/Agent/Store/SQLite/Migrations/M20220101_initial.hs | haskell | x3dh keys are not saved on the sending side (the side accepting the connection)
ratchet is initially empty on the receiving side (the side offering the connection) | # LANGUAGE QuasiQuotes #
module Simplex.Messaging.Agent.Store.SQLite.Migrations.M20220101_initial where
import Database.SQLite.Simple (Query)
import Database.SQLite.Simple.QQ (sql)
m20220101_initial :: Query
m20220101_initial =
[sql|
CREATE TABLE servers (
host TEXT NOT NULL,
port TEXT NOT NULL,
key_hash BLOB NOT NULL,
PRIMARY KEY (host, port)
) WITHOUT ROWID;
CREATE TABLE connections (
conn_id BLOB NOT NULL PRIMARY KEY,
conn_mode TEXT NOT NULL,
last_internal_msg_id INTEGER NOT NULL DEFAULT 0,
last_internal_rcv_msg_id INTEGER NOT NULL DEFAULT 0,
last_internal_snd_msg_id INTEGER NOT NULL DEFAULT 0,
last_external_snd_msg_id INTEGER NOT NULL DEFAULT 0,
last_rcv_msg_hash BLOB NOT NULL DEFAULT x'',
last_snd_msg_hash BLOB NOT NULL DEFAULT x'',
smp_agent_version INTEGER NOT NULL DEFAULT 1
) WITHOUT ROWID;
CREATE TABLE rcv_queues (
host TEXT NOT NULL,
port TEXT NOT NULL,
rcv_id BLOB NOT NULL,
conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE,
rcv_private_key BLOB NOT NULL,
rcv_dh_secret BLOB NOT NULL,
e2e_priv_key BLOB NOT NULL,
e2e_dh_secret BLOB,
snd_id BLOB NOT NULL,
snd_key BLOB,
status TEXT NOT NULL,
smp_server_version INTEGER NOT NULL DEFAULT 1,
smp_client_version INTEGER,
PRIMARY KEY (host, port, rcv_id),
FOREIGN KEY (host, port) REFERENCES servers
ON DELETE RESTRICT ON UPDATE CASCADE,
UNIQUE (host, port, snd_id)
) WITHOUT ROWID;
CREATE TABLE snd_queues (
host TEXT NOT NULL,
port TEXT NOT NULL,
snd_id BLOB NOT NULL,
conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE,
snd_private_key BLOB NOT NULL,
e2e_dh_secret BLOB NOT NULL,
status TEXT NOT NULL,
smp_server_version INTEGER NOT NULL DEFAULT 1,
smp_client_version INTEGER NOT NULL DEFAULT 1,
PRIMARY KEY (host, port, snd_id),
FOREIGN KEY (host, port) REFERENCES servers
ON DELETE RESTRICT ON UPDATE CASCADE
) WITHOUT ROWID;
CREATE TABLE messages (
conn_id BLOB NOT NULL REFERENCES connections (conn_id)
ON DELETE CASCADE,
internal_id INTEGER NOT NULL,
internal_ts TEXT NOT NULL,
internal_rcv_id INTEGER,
internal_snd_id INTEGER,
( H)ELLO , ( R)EPLY , ( D)ELETE . Should SMP confirmation be saved too ?
msg_body BLOB NOT NULL DEFAULT x'',
PRIMARY KEY (conn_id, internal_id),
FOREIGN KEY (conn_id, internal_rcv_id) REFERENCES rcv_messages
ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
FOREIGN KEY (conn_id, internal_snd_id) REFERENCES snd_messages
ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED
) WITHOUT ROWID;
CREATE TABLE rcv_messages (
conn_id BLOB NOT NULL,
internal_rcv_id INTEGER NOT NULL,
internal_id INTEGER NOT NULL,
external_snd_id INTEGER NOT NULL,
broker_id BLOB NOT NULL,
broker_ts TEXT NOT NULL,
internal_hash BLOB NOT NULL,
external_prev_snd_hash BLOB NOT NULL,
integrity BLOB NOT NULL,
PRIMARY KEY (conn_id, internal_rcv_id),
FOREIGN KEY (conn_id, internal_id) REFERENCES messages
ON DELETE CASCADE
) WITHOUT ROWID;
CREATE TABLE snd_messages (
conn_id BLOB NOT NULL,
internal_snd_id INTEGER NOT NULL,
internal_id INTEGER NOT NULL,
internal_hash BLOB NOT NULL,
previous_msg_hash BLOB NOT NULL DEFAULT x'',
PRIMARY KEY (conn_id, internal_snd_id),
FOREIGN KEY (conn_id, internal_id) REFERENCES messages
ON DELETE CASCADE
) WITHOUT ROWID;
CREATE TABLE conn_confirmations (
confirmation_id BLOB NOT NULL PRIMARY KEY,
conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE,
e2e_snd_pub_key BLOB NOT NULL,
sender_key BLOB NOT NULL,
ratchet_state BLOB NOT NULL,
sender_conn_info BLOB NOT NULL,
accepted INTEGER NOT NULL,
own_conn_info BLOB,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
) WITHOUT ROWID;
CREATE TABLE conn_invitations (
invitation_id BLOB NOT NULL PRIMARY KEY,
contact_conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE,
cr_invitation BLOB NOT NULL,
recipient_conn_info BLOB NOT NULL,
accepted INTEGER NOT NULL DEFAULT 0,
own_conn_info BLOB,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
) WITHOUT ROWID;
CREATE TABLE ratchets (
conn_id BLOB NOT NULL PRIMARY KEY REFERENCES connections
ON DELETE CASCADE,
x3dh_priv_key_1 BLOB,
x3dh_priv_key_2 BLOB,
ratchet_state BLOB,
e2e_version INTEGER NOT NULL DEFAULT 1
) WITHOUT ROWID;
CREATE TABLE skipped_messages (
skipped_message_id INTEGER PRIMARY KEY,
conn_id BLOB NOT NULL REFERENCES ratchets
ON DELETE CASCADE,
header_key BLOB NOT NULL,
msg_n INTEGER NOT NULL,
msg_key BLOB NOT NULL
);
|]
|
3ee5ea12b13b186d79f1a06d4428b4b904c14a130d3ce62146647a43524186b3 | lspector/Clojush | median.clj | ;; median.clj
,
;;
;; Problem Source:
C. Le Goues et al . , " The ManyBugs and for Automated Repair of C Programs , "
in IEEE Transactions on Software Engineering , vol . 41 , no . 12 , pp . 1236 - 1256 , Dec. 1 2015 .
doi : 10.1109 / TSE.2015.2454513
;;
Given 3 integers , print their median .
;;
input stack has the 3 integers
(ns clojush.problems.software.median
(:use clojush.pushgp.pushgp
[clojush pushstate interpreter random util globals]
clojush.instructions.tag
clojure.math.numeric-tower
))
; Atom generators
(def median-atom-generators
(concat (list
(fn [] (- (lrand-int 201) 100))
(tag-instruction-erc [:exec :integer :boolean] 1000)
(tagged-instruction-erc 1000)
end ERCs
'in1
'in2
'in3
;;; end input instructions
)
(registered-for-stacks [:integer :boolean :exec :print])))
;; A list of data domains for the median problem. Each domain is a vector containing
a " set " of inputs and two integers representing how many cases from the set
;; should be used as training and testing cases respectively. Each "set" of
;; inputs is either a list or a function that, when called, will create a
;; random element of the set.
(def median-data-domains
[#_[(list [2 6 8] [2 8 6] [6 2 8] [6 8 2] [8 2 6] [8 6 2] ; Permutations of [2 6 8]
[-5 0 5] [-5 5 0] [0 -5 5] [0 5 -5] [5 -5 0] [5 0 -5] ; Permutations of [-5 0 5]
Two zeroes
Each input includes 3 integers in range [ -100,100 ]
[(fn [] (shuffle (conj (repeat 2 (- (lrand-int 201) 100))
Edge cases where two of three are the same
[(fn [] (repeat 3 (- (lrand-int 201) 100))) 10 100] ;; Edge cases where all are the same
])
;;Can make median test data like this:
;(test-and-train-data-from-domains median-data-domains)
; Helper function for error function
(defn median-test-cases
"Takes a sequence of inputs and gives IO test cases of the form
[[input1 input2 input3] output]."
[inputs]
(map #(vector %
(second (sort %)))
inputs))
(defn make-median-error-function-from-cases
[train-cases test-cases]
(fn the-actual-median-error-function
([individual]
(the-actual-median-error-function individual :train))
([individual data-cases] ;; data-cases should be :train or :test
(the-actual-median-error-function individual data-cases false))
([individual data-cases print-outputs]
(let [behavior (atom '())
errors (doall
(for [[[input1 input2 input3] out-int] (case data-cases
:train train-cases
:test test-cases
data-cases)]
(let [final-state (run-push (:program individual)
(->> (make-push-state)
(push-item input3 :input)
(push-item input2 :input)
(push-item input1 :input)
(push-item "" :output)))
printed-result (stack-ref :output 0 final-state)]
(when print-outputs
(println (format "Correct output: %-19s | Program output: %-19s" (str out-int) printed-result)))
; Record the behavior
(swap! behavior conj printed-result)
; Each test case is either right or wrong
(if (= printed-result (str out-int))
0
1))))]
(if (= data-cases :test)
(assoc individual :test-errors errors)
(assoc individual :behaviors @behavior :errors errors))))))
(defn get-median-train-and-test
"Returns the train and test cases."
[data-domains]
(map median-test-cases
(test-and-train-data-from-domains data-domains)))
; Define train and test cases
(def median-train-and-test-cases
(get-median-train-and-test median-data-domains))
(defn median-initial-report
[argmap]
(println "Train and test cases:")
(doseq [[i case] (map vector (range) (first median-train-and-test-cases))]
(println (format "Train Case: %3d | Input/Output: %s" i (str case))))
(doseq [[i case] (map vector (range) (second median-train-and-test-cases))]
(println (format "Test Case: %3d | Input/Output: %s" i (str case))))
(println ";;******************************"))
(defn median-report
"Custom generational report."
[best population generation error-function report-simplifications]
(let [best-test-errors (:test-errors (error-function best :test))
best-total-test-error (apply +' best-test-errors)]
(println ";;******************************")
(printf ";; -*- Median problem report - generation %s\n" generation)(flush)
(println "Test total error for best:" best-total-test-error)
(println (format "Test mean error for best: %.5f" (double (/ best-total-test-error (count best-test-errors)))))
(when (zero? (:total-error best))
(doseq [[i error] (map vector
(range)
best-test-errors)]
(println (format "Test Case %3d | Error: %s" i (str error)))))
(println ";;------------------------------")
(println "Outputs of best individual on training cases:")
(error-function best :train true)
(println ";;******************************")
)) ;; To do validation, could have this function return an altered best individual
with total - error > 0 if it had error of zero on train but not on validation
set . Would need a third category of data cases , or a defined split of training cases .
Define the argmap
(def argmap
{:error-function (make-median-error-function-from-cases (first median-train-and-test-cases)
(second median-train-and-test-cases))
:training-cases (first median-train-and-test-cases)
:atom-generators median-atom-generators
:max-points 800
:max-genome-size-in-initial-program 100
:evalpush-limit 200
:population-size 1000
:max-generations 200
:parent-selection :lexicase
:epigenetic-markers [:close]
:genetic-operator-probabilities {:alternation 0.2
:uniform-mutation 0.2
:uniform-close-mutation 0.1
[:alternation :uniform-mutation] 0.5
}
:alternation-rate 0.01
:alignment-deviation 5
:uniform-mutation-rate 0.01
:problem-specific-report median-report
:problem-specific-initial-report median-initial-report
:report-simplifications 0
:final-report-simplifications 5000
:max-error 1
})
| null | https://raw.githubusercontent.com/lspector/Clojush/685b991535607cf942ae1500557171a0739982c3/src/clojush/problems/software/median.clj | clojure | median.clj
Problem Source:
Atom generators
end input instructions
A list of data domains for the median problem. Each domain is a vector containing
should be used as training and testing cases respectively. Each "set" of
inputs is either a list or a function that, when called, will create a
random element of the set.
Permutations of [2 6 8]
Permutations of [-5 0 5]
Edge cases where all are the same
Can make median test data like this:
(test-and-train-data-from-domains median-data-domains)
Helper function for error function
data-cases should be :train or :test
Record the behavior
Each test case is either right or wrong
Define train and test cases
To do validation, could have this function return an altered best individual | ,
C. Le Goues et al . , " The ManyBugs and for Automated Repair of C Programs , "
in IEEE Transactions on Software Engineering , vol . 41 , no . 12 , pp . 1236 - 1256 , Dec. 1 2015 .
doi : 10.1109 / TSE.2015.2454513
Given 3 integers , print their median .
input stack has the 3 integers
(ns clojush.problems.software.median
(:use clojush.pushgp.pushgp
[clojush pushstate interpreter random util globals]
clojush.instructions.tag
clojure.math.numeric-tower
))
(def median-atom-generators
(concat (list
(fn [] (- (lrand-int 201) 100))
(tag-instruction-erc [:exec :integer :boolean] 1000)
(tagged-instruction-erc 1000)
end ERCs
'in1
'in2
'in3
)
(registered-for-stacks [:integer :boolean :exec :print])))
a " set " of inputs and two integers representing how many cases from the set
(def median-data-domains
Two zeroes
Each input includes 3 integers in range [ -100,100 ]
[(fn [] (shuffle (conj (repeat 2 (- (lrand-int 201) 100))
Edge cases where two of three are the same
])
(defn median-test-cases
"Takes a sequence of inputs and gives IO test cases of the form
[[input1 input2 input3] output]."
[inputs]
(map #(vector %
(second (sort %)))
inputs))
(defn make-median-error-function-from-cases
[train-cases test-cases]
(fn the-actual-median-error-function
([individual]
(the-actual-median-error-function individual :train))
(the-actual-median-error-function individual data-cases false))
([individual data-cases print-outputs]
(let [behavior (atom '())
errors (doall
(for [[[input1 input2 input3] out-int] (case data-cases
:train train-cases
:test test-cases
data-cases)]
(let [final-state (run-push (:program individual)
(->> (make-push-state)
(push-item input3 :input)
(push-item input2 :input)
(push-item input1 :input)
(push-item "" :output)))
printed-result (stack-ref :output 0 final-state)]
(when print-outputs
(println (format "Correct output: %-19s | Program output: %-19s" (str out-int) printed-result)))
(swap! behavior conj printed-result)
(if (= printed-result (str out-int))
0
1))))]
(if (= data-cases :test)
(assoc individual :test-errors errors)
(assoc individual :behaviors @behavior :errors errors))))))
(defn get-median-train-and-test
"Returns the train and test cases."
[data-domains]
(map median-test-cases
(test-and-train-data-from-domains data-domains)))
(def median-train-and-test-cases
(get-median-train-and-test median-data-domains))
(defn median-initial-report
[argmap]
(println "Train and test cases:")
(doseq [[i case] (map vector (range) (first median-train-and-test-cases))]
(println (format "Train Case: %3d | Input/Output: %s" i (str case))))
(doseq [[i case] (map vector (range) (second median-train-and-test-cases))]
(println (format "Test Case: %3d | Input/Output: %s" i (str case))))
(println ";;******************************"))
(defn median-report
"Custom generational report."
[best population generation error-function report-simplifications]
(let [best-test-errors (:test-errors (error-function best :test))
best-total-test-error (apply +' best-test-errors)]
(println ";;******************************")
(printf ";; -*- Median problem report - generation %s\n" generation)(flush)
(println "Test total error for best:" best-total-test-error)
(println (format "Test mean error for best: %.5f" (double (/ best-total-test-error (count best-test-errors)))))
(when (zero? (:total-error best))
(doseq [[i error] (map vector
(range)
best-test-errors)]
(println (format "Test Case %3d | Error: %s" i (str error)))))
(println ";;------------------------------")
(println "Outputs of best individual on training cases:")
(error-function best :train true)
(println ";;******************************")
with total - error > 0 if it had error of zero on train but not on validation
set . Would need a third category of data cases , or a defined split of training cases .
Define the argmap
(def argmap
{:error-function (make-median-error-function-from-cases (first median-train-and-test-cases)
(second median-train-and-test-cases))
:training-cases (first median-train-and-test-cases)
:atom-generators median-atom-generators
:max-points 800
:max-genome-size-in-initial-program 100
:evalpush-limit 200
:population-size 1000
:max-generations 200
:parent-selection :lexicase
:epigenetic-markers [:close]
:genetic-operator-probabilities {:alternation 0.2
:uniform-mutation 0.2
:uniform-close-mutation 0.1
[:alternation :uniform-mutation] 0.5
}
:alternation-rate 0.01
:alignment-deviation 5
:uniform-mutation-rate 0.01
:problem-specific-report median-report
:problem-specific-initial-report median-initial-report
:report-simplifications 0
:final-report-simplifications 5000
:max-error 1
})
|
c4d9ddad6ef03e7a6936bc39118d283596ed04ab826ff1c3e467146b88f6ab77 | noinia/hgeometry | SSSP.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
module SSSP (ssspMulti) where
import Control.Lens ((^.))
import Reanimate (Animation, animate, curveS, fadeOutE, fork, fromToS, mkAnimation,
mkCircle, mkGroup, mkLine, newSpriteA', newSpriteSVG, newSpriteSVG_,
overEnding, partialSvg, pathify, pauseAround, pauseAtEnd,
playThenReverseA, scene, signalA, spriteE, spriteZ, translate, wait,
withFillColorPixel, withStrokeColorPixel)
import Reanimate.Animation (Sync (SyncFreeze))
import Algorithms.Geometry.SSSP (sssp, triangulate)
import Data.Ext (core, ext)
import Geometry.Point (Point (Point2))
import Geometry.Polygon (SimplePolygon, fromPoints, outerVertex, simpleFromPoints,
toPoints)
import Geometry.Transformation
import Common
targetPolygon :: SimplePolygon () Rational
targetPolygon = scaleUniformlyBy 2 $ pAtCenter $ simpleFromPoints $ map ext
[ Point2 0 0
, Point2 1 0
, Point2 1 1, Point2 2 1, Point2 2 (-1)
, Point2 0 (-1), Point2 0 (-2)
, Point2 3 (-2), Point2 3 2, Point2 0 2 ]
_ssspSingle :: Animation
_ssspSingle = pauseAtEnd 1 $ scene $ do
newSpriteSVG_ $ ppPolygonBody grey targetPolygon
newSpriteSVG_ $ ppPolygonOutline black targetPolygon
nodes <- newSpriteSVG $ mkGroup
[ ppPolygonNodes red targetPolygon
, withFillColorPixel rootColor $ ppPolygonNode black targetPolygon 0 ]
spriteZ nodes 1
case tree of
T idx sub -> mapM_ (worker idx) sub
wait 3
where
worker origin (T target sub) = do
let Point2 oX oY = realToFrac <$> targetPolygon ^. outerVertex origin . core
Point2 tX tY = realToFrac <$> targetPolygon ^. outerVertex target . core
fork $ do
wait 0.7
dot <- fork $ newSpriteA' SyncFreeze $ animate $ \t -> mkGroup
[ translate tX tY $
withFillColorPixel pathColor $ mkCircle (fromToS 0 (nodeRadius/2) t)
]
spriteZ dot 2
spriteE dot (overEnding 0.2 fadeOutE)
l <- newSpriteA' SyncFreeze $ animate $ \t -> mkGroup
[ withStrokeColorPixel pathColor $ partialSvg t $
pathify $ mkLine (oX, oY) (tX, tY)
, translate tX tY $
withFillColorPixel pathColor $ mkCircle (fromToS 0 (nodeRadius/2) t)
]
spriteE l (overEnding 0.2 fadeOutE)
mapM_ (worker target) sub
tree = ssspTree targetPolygon
ssspMulti :: Animation
ssspMulti = mkAnimation 20 $ \t ->
let p = addPointAt t targetPolygon in
mkGroup
[ ppPolygonBody grey p
, ppPolygonOutline black p
, ppSSSP p
, ppPolygonNodes red p
, withFillColorPixel rootColor $ ppPolygonNode black p 0
]
_ssspMorph :: Animation
_ssspMorph =
playThenReverseA $ pauseAround 1 3 $ signalA (curveS 2) $ mkAnimation 2 $ \t ->
ppPolyGroup t (lerpPolygon t targetPolygon mPolygon)
where
ppPolyGroup _t p = mkGroup
withGroupOpacity ( max 0.3 ( 1 - t ) ) $
ppPolygonBody grey p
, ppPolygonOutline black p
, ppSSSP' tree p
, ppPolygonNodes black p
, withFillColorPixel rootColor $ ppPolygonNode black p 0
]
p' = fromPoints $ toPoints targetPolygon
tree = sssp (triangulate p')
mPolygon = scaleUniformlyBy 2 $ morphSSSP targetPolygon
| null | https://raw.githubusercontent.com/noinia/hgeometry/89cd3d3109ec68f877bf8e34dc34b6df337a4ec1/hgeometry-showcase/src/SSSP.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE RankNTypes # | # LANGUAGE ScopedTypeVariables #
module SSSP (ssspMulti) where
import Control.Lens ((^.))
import Reanimate (Animation, animate, curveS, fadeOutE, fork, fromToS, mkAnimation,
mkCircle, mkGroup, mkLine, newSpriteA', newSpriteSVG, newSpriteSVG_,
overEnding, partialSvg, pathify, pauseAround, pauseAtEnd,
playThenReverseA, scene, signalA, spriteE, spriteZ, translate, wait,
withFillColorPixel, withStrokeColorPixel)
import Reanimate.Animation (Sync (SyncFreeze))
import Algorithms.Geometry.SSSP (sssp, triangulate)
import Data.Ext (core, ext)
import Geometry.Point (Point (Point2))
import Geometry.Polygon (SimplePolygon, fromPoints, outerVertex, simpleFromPoints,
toPoints)
import Geometry.Transformation
import Common
targetPolygon :: SimplePolygon () Rational
targetPolygon = scaleUniformlyBy 2 $ pAtCenter $ simpleFromPoints $ map ext
[ Point2 0 0
, Point2 1 0
, Point2 1 1, Point2 2 1, Point2 2 (-1)
, Point2 0 (-1), Point2 0 (-2)
, Point2 3 (-2), Point2 3 2, Point2 0 2 ]
_ssspSingle :: Animation
_ssspSingle = pauseAtEnd 1 $ scene $ do
newSpriteSVG_ $ ppPolygonBody grey targetPolygon
newSpriteSVG_ $ ppPolygonOutline black targetPolygon
nodes <- newSpriteSVG $ mkGroup
[ ppPolygonNodes red targetPolygon
, withFillColorPixel rootColor $ ppPolygonNode black targetPolygon 0 ]
spriteZ nodes 1
case tree of
T idx sub -> mapM_ (worker idx) sub
wait 3
where
worker origin (T target sub) = do
let Point2 oX oY = realToFrac <$> targetPolygon ^. outerVertex origin . core
Point2 tX tY = realToFrac <$> targetPolygon ^. outerVertex target . core
fork $ do
wait 0.7
dot <- fork $ newSpriteA' SyncFreeze $ animate $ \t -> mkGroup
[ translate tX tY $
withFillColorPixel pathColor $ mkCircle (fromToS 0 (nodeRadius/2) t)
]
spriteZ dot 2
spriteE dot (overEnding 0.2 fadeOutE)
l <- newSpriteA' SyncFreeze $ animate $ \t -> mkGroup
[ withStrokeColorPixel pathColor $ partialSvg t $
pathify $ mkLine (oX, oY) (tX, tY)
, translate tX tY $
withFillColorPixel pathColor $ mkCircle (fromToS 0 (nodeRadius/2) t)
]
spriteE l (overEnding 0.2 fadeOutE)
mapM_ (worker target) sub
tree = ssspTree targetPolygon
ssspMulti :: Animation
ssspMulti = mkAnimation 20 $ \t ->
let p = addPointAt t targetPolygon in
mkGroup
[ ppPolygonBody grey p
, ppPolygonOutline black p
, ppSSSP p
, ppPolygonNodes red p
, withFillColorPixel rootColor $ ppPolygonNode black p 0
]
_ssspMorph :: Animation
_ssspMorph =
playThenReverseA $ pauseAround 1 3 $ signalA (curveS 2) $ mkAnimation 2 $ \t ->
ppPolyGroup t (lerpPolygon t targetPolygon mPolygon)
where
ppPolyGroup _t p = mkGroup
withGroupOpacity ( max 0.3 ( 1 - t ) ) $
ppPolygonBody grey p
, ppPolygonOutline black p
, ppSSSP' tree p
, ppPolygonNodes black p
, withFillColorPixel rootColor $ ppPolygonNode black p 0
]
p' = fromPoints $ toPoints targetPolygon
tree = sssp (triangulate p')
mPolygon = scaleUniformlyBy 2 $ morphSSSP targetPolygon
|
ef908f79a2d1afa83f1529f74c45cc566e79d427e5f833552a0ad02780ab4fb1 | bos/rwh | rms.hs | {-- snippet rootMeanSquare --}
rootMeanSquare :: [Double] -> Double
rootMeanSquare xs = sqrt (sum (map square xs) / fromIntegral (length xs))
where square x = x * x
{-- /snippet rootMeanSquare --}
rootMeanSquare_explicit xs = sqrt (meanSquare xs 0 0)
where meanSquare [] i ms = ms / fromIntegral i
meanSquare (x:xs) i ms = meanSquare xs (i+1) (ms + x**2)
{-- snippet rootMeanSquare_foldl --}
rootMeanSquare_foldl xs =
let (count, sumOfSquares) = foldl step (0,0) xs
in sqrt (sumOfSquares / fromIntegral count)
where step (cnt,sumSq) x = (cnt + 1, sumSq + x*x)
{-- /snippet rootMeanSquare_foldl --}
| null | https://raw.githubusercontent.com/bos/rwh/7fd1e467d54aef832f5476ebf5f4f6a898a895d1/examples/ch05/rms.hs | haskell | - snippet rootMeanSquare -
- /snippet rootMeanSquare -
- snippet rootMeanSquare_foldl -
- /snippet rootMeanSquare_foldl - | rootMeanSquare :: [Double] -> Double
rootMeanSquare xs = sqrt (sum (map square xs) / fromIntegral (length xs))
where square x = x * x
rootMeanSquare_explicit xs = sqrt (meanSquare xs 0 0)
where meanSquare [] i ms = ms / fromIntegral i
meanSquare (x:xs) i ms = meanSquare xs (i+1) (ms + x**2)
rootMeanSquare_foldl xs =
let (count, sumOfSquares) = foldl step (0,0) xs
in sqrt (sumOfSquares / fromIntegral count)
where step (cnt,sumSq) x = (cnt + 1, sumSq + x*x)
|
3d27ef78d31f5b34d2d27db138d87bd3c65b4c7fcf346aeb73abf39d95c1e7ef | noloop/eventbus | eventbus.lisp | (in-package #:noloop.eventbus)
(defun make-eventbus ()
"Return eventbus instance."
(make-hash-table :test 'eq))
(defun get-listener-count-of-event (eventbus event-name)
"Return length listeners of event. Return nil if event nonexistent."
(length (gethash event-name eventbus)))
(defun get-all-listeners-of-event (eventbus event-name)
"Return two values, the value: list of listeners of the event, and present-p: list is present."
(multiple-value-bind (value present-p)
(gethash event-name eventbus)
(values value present-p)))
(defun make-listener (listener-fn is-once)
"It returns a list, the first element being a listener function, and the following being a boolean saying if it is an once listener."
(list listener-fn is-once))
(defun once (eventbus event-name listener-fn)
"Add one listener to an event. The listener is removed when the event is emitted. The add-listener event is emitted before adding the new listener."
(when (gethash :add-listener eventbus)
(emit eventbus :add-listener event-name))
(setf (gethash event-name eventbus)
(push (make-listener listener-fn t) (gethash event-name eventbus)))
eventbus)
(defun on (eventbus event-name listener-fn)
"Add one listener to an event. The add-listener event is emitted before adding the new listener."
(when (gethash :add-listener eventbus)
(emit eventbus :add-listener event-name))
(setf (gethash event-name eventbus)
(push (make-listener listener-fn nil) (gethash event-name eventbus)))
eventbus)
(defun off (eventbus event-name listener-fn)
"Remove the first listener from the event listeners list."
(let ((listeners (gethash event-name eventbus)))
(setf (gethash event-name eventbus)
(delete-if #'(lambda (i)
(eq (car i) listener-fn))
listeners
:count 1))
(when (gethash :remove-listener eventbus)
(emit eventbus :remove-listener event-name))
(when (eq 0 (get-listener-count-of-event eventbus event-name))
(remhash event-name eventbus))
eventbus))
(defun emit (eventbus event-name &rest args)
"Emite an event by passing the arguments offered to the listener function. If the listener is once, then the listener is excluded from the list of listeners."
(let ((listeners (gethash event-name eventbus)))
(when listeners
(dolist (i listeners)
(let ((fn (car i)))
(when (cadr i)
(off eventbus event-name fn))
(apply fn args))))
eventbus))
(defun get-all-events-name (eventbus)
"Return one list with all name of events of the eventbus. The list returned includes add-listener and remove-listener."
(let ((keys '()))
(maphash
#'(lambda (key value)
(declare (ignore value))
(push key keys))
eventbus)
(nreverse keys)))
(defun remove-all-listeners-of-event (eventbus event-name)
"Removing all listeners from the event. Will be called the off function for each listener, so the remove-listener event is emitted correctly for each listener removed."
(let* ((listeners (gethash event-name eventbus))
(listener-fn (car (first listeners))))
(when listeners
(off eventbus event-name listener-fn)
(remove-all-listeners-of-event eventbus event-name))
eventbus))
| null | https://raw.githubusercontent.com/noloop/eventbus/92c1fa3846ba0e3cc9e6d7605d765379c8658d84/src/eventbus.lisp | lisp | (in-package #:noloop.eventbus)
(defun make-eventbus ()
"Return eventbus instance."
(make-hash-table :test 'eq))
(defun get-listener-count-of-event (eventbus event-name)
"Return length listeners of event. Return nil if event nonexistent."
(length (gethash event-name eventbus)))
(defun get-all-listeners-of-event (eventbus event-name)
"Return two values, the value: list of listeners of the event, and present-p: list is present."
(multiple-value-bind (value present-p)
(gethash event-name eventbus)
(values value present-p)))
(defun make-listener (listener-fn is-once)
"It returns a list, the first element being a listener function, and the following being a boolean saying if it is an once listener."
(list listener-fn is-once))
(defun once (eventbus event-name listener-fn)
"Add one listener to an event. The listener is removed when the event is emitted. The add-listener event is emitted before adding the new listener."
(when (gethash :add-listener eventbus)
(emit eventbus :add-listener event-name))
(setf (gethash event-name eventbus)
(push (make-listener listener-fn t) (gethash event-name eventbus)))
eventbus)
(defun on (eventbus event-name listener-fn)
"Add one listener to an event. The add-listener event is emitted before adding the new listener."
(when (gethash :add-listener eventbus)
(emit eventbus :add-listener event-name))
(setf (gethash event-name eventbus)
(push (make-listener listener-fn nil) (gethash event-name eventbus)))
eventbus)
(defun off (eventbus event-name listener-fn)
"Remove the first listener from the event listeners list."
(let ((listeners (gethash event-name eventbus)))
(setf (gethash event-name eventbus)
(delete-if #'(lambda (i)
(eq (car i) listener-fn))
listeners
:count 1))
(when (gethash :remove-listener eventbus)
(emit eventbus :remove-listener event-name))
(when (eq 0 (get-listener-count-of-event eventbus event-name))
(remhash event-name eventbus))
eventbus))
(defun emit (eventbus event-name &rest args)
"Emite an event by passing the arguments offered to the listener function. If the listener is once, then the listener is excluded from the list of listeners."
(let ((listeners (gethash event-name eventbus)))
(when listeners
(dolist (i listeners)
(let ((fn (car i)))
(when (cadr i)
(off eventbus event-name fn))
(apply fn args))))
eventbus))
(defun get-all-events-name (eventbus)
"Return one list with all name of events of the eventbus. The list returned includes add-listener and remove-listener."
(let ((keys '()))
(maphash
#'(lambda (key value)
(declare (ignore value))
(push key keys))
eventbus)
(nreverse keys)))
(defun remove-all-listeners-of-event (eventbus event-name)
"Removing all listeners from the event. Will be called the off function for each listener, so the remove-listener event is emitted correctly for each listener removed."
(let* ((listeners (gethash event-name eventbus))
(listener-fn (car (first listeners))))
(when listeners
(off eventbus event-name listener-fn)
(remove-all-listeners-of-event eventbus event-name))
eventbus))
| |
e1104ef0f82b6d4b9cd8a881e3744673e661c1f789816bdf50f2dbe49a1cb904 | qfpl/reflex-workshop | CounterText.hs | |
Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Exercises.Behaviors.Querying.CounterText (
counterTextExercise
) where
import Data.Text (Text)
import Reflex
import Exercises.Events.Filtering.FmapMaybe
import Exercises.Behaviors.Querying.Counter
counterTextExercise :: Reflex t
=> Behavior t Int
-> Behavior t Text
-> Event t ()
-> Event t ()
-> (Event t Text, Event t Int)
counterTextExercise bCount bText eAdd eReset =
(never, never)
| null | https://raw.githubusercontent.com/qfpl/reflex-workshop/244ef13fb4b2e884f455eccc50072e98d1668c9e/src/Exercises/Behaviors/Querying/CounterText.hs | haskell | |
Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Exercises.Behaviors.Querying.CounterText (
counterTextExercise
) where
import Data.Text (Text)
import Reflex
import Exercises.Events.Filtering.FmapMaybe
import Exercises.Behaviors.Querying.Counter
counterTextExercise :: Reflex t
=> Behavior t Int
-> Behavior t Text
-> Event t ()
-> Event t ()
-> (Event t Text, Event t Int)
counterTextExercise bCount bText eAdd eReset =
(never, never)
| |
85bab6db11a0285051c52998c1969f5f68533970069e5cf168bfc6260fa09ba8 | gedge-platform/gedge-platform | cuttlefish_vmargs.erl | -module(cuttlefish_vmargs).
-export([stringify/1]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
%% @doc turns a proplist into a list of strings suitable for vm.args files
-spec stringify([{any(), string()}]) -> [string()].
stringify(VMArgsProplist) ->
[ stringify_line(K, V) || {K, V} <- VMArgsProplist ].
stringify_line(K, V) when is_list(V) ->
lists:flatten(io_lib:format("~s ~s", [K, V]));
stringify_line(K, V) ->
lists:flatten(io_lib:format("~s ~w", [K, V])).
-ifdef(TEST).
stringify_test() ->
VMArgsProplist = [
{'-name', "dev1@127.0.0.1"},
{'-setcookie', 'riak'},
{'-smp', enable},
{'+W',"w"},
{'+K',"true"},
{'+A',"64"},
{'-env ERL_MAX_PORTS',"64000"},
{'-env ERL_FULLSWEEP_AFTER',"0"},
{'-env ERL_CRASH_DUMP',"./log/erl_crash.dump"},
{'-env ERL_MAX_ETS_TABLES',"256000"},
{'+P', "256000"},
{'-kernel net_ticktime', "42"}
],
VMArgs = stringify(VMArgsProplist),
Expected = [
"-name dev1@127.0.0.1",
"-setcookie riak",
"-smp enable",
"+W w",
"+K true",
"+A 64",
"-env ERL_MAX_PORTS 64000",
"-env ERL_FULLSWEEP_AFTER 0",
"-env ERL_CRASH_DUMP ./log/erl_crash.dump",
"-env ERL_MAX_ETS_TABLES 256000",
"+P 256000",
"-kernel net_ticktime 42"
],
[ ?assertEqual(E, V) || {E, V} <- lists:zip(Expected, VMArgs)],
ok.
-endif.
| null | https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/cuttlefish/src/cuttlefish_vmargs.erl | erlang | @doc turns a proplist into a list of strings suitable for vm.args files | -module(cuttlefish_vmargs).
-export([stringify/1]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-spec stringify([{any(), string()}]) -> [string()].
stringify(VMArgsProplist) ->
[ stringify_line(K, V) || {K, V} <- VMArgsProplist ].
stringify_line(K, V) when is_list(V) ->
lists:flatten(io_lib:format("~s ~s", [K, V]));
stringify_line(K, V) ->
lists:flatten(io_lib:format("~s ~w", [K, V])).
-ifdef(TEST).
stringify_test() ->
VMArgsProplist = [
{'-name', "dev1@127.0.0.1"},
{'-setcookie', 'riak'},
{'-smp', enable},
{'+W',"w"},
{'+K',"true"},
{'+A',"64"},
{'-env ERL_MAX_PORTS',"64000"},
{'-env ERL_FULLSWEEP_AFTER',"0"},
{'-env ERL_CRASH_DUMP',"./log/erl_crash.dump"},
{'-env ERL_MAX_ETS_TABLES',"256000"},
{'+P', "256000"},
{'-kernel net_ticktime', "42"}
],
VMArgs = stringify(VMArgsProplist),
Expected = [
"-name dev1@127.0.0.1",
"-setcookie riak",
"-smp enable",
"+W w",
"+K true",
"+A 64",
"-env ERL_MAX_PORTS 64000",
"-env ERL_FULLSWEEP_AFTER 0",
"-env ERL_CRASH_DUMP ./log/erl_crash.dump",
"-env ERL_MAX_ETS_TABLES 256000",
"+P 256000",
"-kernel net_ticktime 42"
],
[ ?assertEqual(E, V) || {E, V} <- lists:zip(Expected, VMArgs)],
ok.
-endif.
|
c64b01268bc30cdc1a18acc5287988729269ee6c0b71645d83a013d2e71ca5b6 | yzhs/ocamlllvm | translclass.mli | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : translclass.mli 7372 2006 - 04 - 05 02:28:13Z garrigue $
open Typedtree
open Lambda
val transl_class :
Ident.t list -> Ident.t ->
int -> string list -> class_expr -> Asttypes.virtual_flag -> lambda;;
type error = Illegal_class_expr | Tags of string * string
exception Error of Location.t * error
open Format
val report_error: formatter -> error -> unit
| null | https://raw.githubusercontent.com/yzhs/ocamlllvm/45cbf449d81f2ef9d234968e49a4305aaa39ace2/src/bytecomp/translclass.mli | ocaml | *********************************************************************
Objective Caml
********************************************************************* | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ I d : translclass.mli 7372 2006 - 04 - 05 02:28:13Z garrigue $
open Typedtree
open Lambda
val transl_class :
Ident.t list -> Ident.t ->
int -> string list -> class_expr -> Asttypes.virtual_flag -> lambda;;
type error = Illegal_class_expr | Tags of string * string
exception Error of Location.t * error
open Format
val report_error: formatter -> error -> unit
|
fb684b181262826b3fba8ff71f6ee4b7c7ea9c6dc15e949735df8acb40624815 | atolab/apero-core | ordered.ml | module type Comparable = sig
type t
val compare : t -> t -> int
val equal : t -> t -> bool
end
module Ordered = struct
module type S = sig
include Comparable
module Infix : sig
val (=) : t -> t -> bool
val (>) : t -> t -> bool
val (>=) : t -> t -> bool
val (<) : t -> t -> bool
val (<=) : t -> t -> bool
val (<>) : t -> t -> bool
end
end
module Make (C : Comparable) = struct
include C
let equal a b = (C.compare a b) = 0
module Infix = struct
let (=) = equal
let (>) a b = (C.compare a b) > 0
let (>=) a b = (C.compare a b) >= 0
let (<) a b = (C.compare a b) < 0
let (<=) a b = (C.compare a b) <= 0
let (<>) a b = (C.compare a b) <> 0
end
end
end
| null | https://raw.githubusercontent.com/atolab/apero-core/6e8b9bb8383de641396463fb4e5685b7f135755c/lib/ordered.ml | ocaml | module type Comparable = sig
type t
val compare : t -> t -> int
val equal : t -> t -> bool
end
module Ordered = struct
module type S = sig
include Comparable
module Infix : sig
val (=) : t -> t -> bool
val (>) : t -> t -> bool
val (>=) : t -> t -> bool
val (<) : t -> t -> bool
val (<=) : t -> t -> bool
val (<>) : t -> t -> bool
end
end
module Make (C : Comparable) = struct
include C
let equal a b = (C.compare a b) = 0
module Infix = struct
let (=) = equal
let (>) a b = (C.compare a b) > 0
let (>=) a b = (C.compare a b) >= 0
let (<) a b = (C.compare a b) < 0
let (<=) a b = (C.compare a b) <= 0
let (<>) a b = (C.compare a b) <> 0
end
end
end
| |
ba3e003faeae6052c776dca41d9592af52dff15280e28db8abb067fdee5a7346 | sarabander/p2pu-sicp | 2.27.scm |
(define (reverse-list lst)
(if (null? lst)
empty
(append (reverse-list (cdr lst)) (list (car lst)))))
(define (deep-reverse1 lst)
(if (pair? lst)
(append (deep-reverse1 (cdr lst))
(list (deep-reverse1 (car lst))))
lst))
(define (deep-reverse2 lst)
(if (pair? lst)
(reverse (map deep-reverse2 lst))
lst))
(define deep-reverse deep-reverse1)
' ( 4 3 2 1 )
(deep-reverse '(1 2 ((3) (4 5 6) 7 ) (8 (((9) 10) 11) 12 (13 14)) 15))
' ( 15 ( ( 14 13 ) 12 ( 11 ( 10 ( 9 ) ) ) 8) ( 7 ( 6 5 4 ) ( 3 ) ) 2 1 )
(define x (list (list 1 2) (list 3 4)))
' ( ( 3 4 ) ( 1 2 ) )
' ( ( 4 3 ) ( 2 1 ) )
| null | https://raw.githubusercontent.com/sarabander/p2pu-sicp/fbc49b67dac717da1487629fb2d7a7d86dfdbe32/2.2/2.27.scm | scheme |
(define (reverse-list lst)
(if (null? lst)
empty
(append (reverse-list (cdr lst)) (list (car lst)))))
(define (deep-reverse1 lst)
(if (pair? lst)
(append (deep-reverse1 (cdr lst))
(list (deep-reverse1 (car lst))))
lst))
(define (deep-reverse2 lst)
(if (pair? lst)
(reverse (map deep-reverse2 lst))
lst))
(define deep-reverse deep-reverse1)
' ( 4 3 2 1 )
(deep-reverse '(1 2 ((3) (4 5 6) 7 ) (8 (((9) 10) 11) 12 (13 14)) 15))
' ( 15 ( ( 14 13 ) 12 ( 11 ( 10 ( 9 ) ) ) 8) ( 7 ( 6 5 4 ) ( 3 ) ) 2 1 )
(define x (list (list 1 2) (list 3 4)))
' ( ( 3 4 ) ( 1 2 ) )
' ( ( 4 3 ) ( 2 1 ) )
| |
942b32b144d5193b9b17420dfe3120fb545a431965c6a698b9e7393ee73e81f6 | ocaml-multicore/tezos | configuration.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2022 Nomadic Labs , < >
(* *)
(* 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. *)
(* *)
(*****************************************************************************)
open Clic
open Lwt_result_syntax
type t = {base_dir : string; endpoint : Uri.t}
let default_base_dir =
Filename.concat (Sys.getenv "HOME") ".tezos-sc-rollup-client"
let default_endpoint = ":8932"
let default =
{base_dir = default_base_dir; endpoint = Uri.of_string default_endpoint}
let valid_endpoint _configuration s =
let endpoint = Uri.of_string s in
match (Uri.scheme endpoint, Uri.query endpoint, Uri.fragment endpoint) with
| (Some ("http" | "https"), [], None) -> return endpoint
| _ -> failwith "Endpoint should be of the form http[s]:port"
let endpoint_arg () =
arg
~long:"endpoint"
~short:'E'
~placeholder:"uri"
~doc:
(Printf.sprintf
"endpoint of the sc rollup node; e.g. '%s'"
default_endpoint)
@@ parameter valid_endpoint
let valid_base_dir _configuration base_dir =
if not (Sys.file_exists base_dir && Sys.is_directory base_dir) then
failwith "%s does not seem to be an existing directory" base_dir
else return base_dir
let base_dir_arg () =
arg
~long:"base-dir"
~short:'d'
~placeholder:"path"
~doc:
(Format.asprintf
"@[<v>@[<2>Tezos smart-contract rollup client data directory@,\
The directory where the Tezos smart-contract rollup client stores \
its data.@,\
If absent, its value defaults to %s@]@]@."
default_base_dir)
(parameter valid_base_dir)
let global_options () = Clic.args2 (base_dir_arg ()) (endpoint_arg ())
let make (base_dir, endpoint) =
{
base_dir = Option.value base_dir ~default:default_base_dir;
endpoint = Option.value endpoint ~default:(Uri.of_string default_endpoint);
}
let parse argv =
let* (opts, argv) =
Clic.parse_global_options (global_options ()) default argv
in
return (make opts, argv)
| null | https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_alpha/bin_sc_rollup_client/configuration.ml | ocaml | ***************************************************************************
Open Source License
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 all copies or substantial portions of the Software.
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.
*************************************************************************** | Copyright ( c ) 2022 Nomadic Labs , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Clic
open Lwt_result_syntax
type t = {base_dir : string; endpoint : Uri.t}
let default_base_dir =
Filename.concat (Sys.getenv "HOME") ".tezos-sc-rollup-client"
let default_endpoint = ":8932"
let default =
{base_dir = default_base_dir; endpoint = Uri.of_string default_endpoint}
let valid_endpoint _configuration s =
let endpoint = Uri.of_string s in
match (Uri.scheme endpoint, Uri.query endpoint, Uri.fragment endpoint) with
| (Some ("http" | "https"), [], None) -> return endpoint
| _ -> failwith "Endpoint should be of the form http[s]:port"
let endpoint_arg () =
arg
~long:"endpoint"
~short:'E'
~placeholder:"uri"
~doc:
(Printf.sprintf
"endpoint of the sc rollup node; e.g. '%s'"
default_endpoint)
@@ parameter valid_endpoint
let valid_base_dir _configuration base_dir =
if not (Sys.file_exists base_dir && Sys.is_directory base_dir) then
failwith "%s does not seem to be an existing directory" base_dir
else return base_dir
let base_dir_arg () =
arg
~long:"base-dir"
~short:'d'
~placeholder:"path"
~doc:
(Format.asprintf
"@[<v>@[<2>Tezos smart-contract rollup client data directory@,\
The directory where the Tezos smart-contract rollup client stores \
its data.@,\
If absent, its value defaults to %s@]@]@."
default_base_dir)
(parameter valid_base_dir)
let global_options () = Clic.args2 (base_dir_arg ()) (endpoint_arg ())
let make (base_dir, endpoint) =
{
base_dir = Option.value base_dir ~default:default_base_dir;
endpoint = Option.value endpoint ~default:(Uri.of_string default_endpoint);
}
let parse argv =
let* (opts, argv) =
Clic.parse_global_options (global_options ()) default argv
in
return (make opts, argv)
|
413c418cbffe12d61e4cfbad66491ff75e1d87169dde8a7bcc8498177f330665 | redbadger/karma-tracker | events_repository.clj | (ns karma-tracker.events-repository
(:require [monger.core :as mongo]
[monger.collection :as collection]
[monger.query :as q]
monger.joda-time
[clj-time.core :refer [with-time-at-start-of-day] :as t]
[clj-time.coerce :refer [to-date-time]]
[clj-time.format :as format]
[clojure.walk :refer [postwalk]]
[clojure.set :refer [rename-keys]]
[environ.core :refer [env]])
(:import [com.mongodb DB]
[org.joda.time DateTimeZone]))
(comment "Download and save events:"
(require '[karma-tracker.github :as github]
'[karma-tracker.events-repository :as repo]
'[clj-time.core :refer [now weeks ago]])
(def client (github/new-connection))
(def db (repo/connect))
(defn fetch-users [organisation]
(map :login (github/organisation-members client organisation)))
(defn fetch-events [organisation]
(mapcat (partial github/performed-events client) (fetch-users organisation)))
(repo/add db (fetch-events "redbadger"))
(repo/fetch db (-> 2 weeks ago) (now)))
(def events-collection "events")
(def date-time-format (format/formatter :date-time-no-ms))
(defn try-parse-date-time
"Attempts to parse the given value as a date-time.
Returns the value unmodified if it cannot be parsed."
[value]
(try (format/parse date-time-format value)
(catch Exception _ value)))
(defn parse-date-times
"Traverses the given data structure and parses any date-time strings found within."
[data]
(postwalk try-parse-date-time data))
(defprotocol EventsRepository
(add [_ events] "Saves events.")
(fetch [_ start finish] "Loads events that occurred within the specified time period.
start and finish are dates (not date-times)."))
(extend-type DB
EventsRepository
(add [db events]
(doseq [event events]
(collection/update db
events-collection
{:_id (event :id)}
(-> event (dissoc :id) parse-date-times)
{:upsert true})))
(fetch [db start finish]
(map #(rename-keys % {:_id :id})
(q/with-collection db events-collection
(q/find {:created_at
{"$gte" (-> start to-date-time with-time-at-start-of-day)
"$lte" (-> finish to-date-time .millisOfDay .withMaximumValue)}})
(q/sort (array-map :created_at 1))))))
(defn connect
"Connects to MongoDB and returns the database client."
([] (connect (env :mongodb-uri)))
([uri] (doto (:db (mongo/connect-via-uri uri))
(collection/ensure-index events-collection {:created_at 1}))))
(defn- get-date-interval [year month]
(let [start (t/date-time year month)
end (-> start
(t/plus (t/months 1))
(t/minus (t/days 1)))]
[start end]))
(defn get-events-for-month [db year month]
(let [[start end] (get-date-interval year month)]
(fetch db start end)))
| null | https://raw.githubusercontent.com/redbadger/karma-tracker/c5375f32f4cd0386f6bb1560d979b79bceea19e2/src/karma_tracker/events_repository.clj | clojure | (ns karma-tracker.events-repository
(:require [monger.core :as mongo]
[monger.collection :as collection]
[monger.query :as q]
monger.joda-time
[clj-time.core :refer [with-time-at-start-of-day] :as t]
[clj-time.coerce :refer [to-date-time]]
[clj-time.format :as format]
[clojure.walk :refer [postwalk]]
[clojure.set :refer [rename-keys]]
[environ.core :refer [env]])
(:import [com.mongodb DB]
[org.joda.time DateTimeZone]))
(comment "Download and save events:"
(require '[karma-tracker.github :as github]
'[karma-tracker.events-repository :as repo]
'[clj-time.core :refer [now weeks ago]])
(def client (github/new-connection))
(def db (repo/connect))
(defn fetch-users [organisation]
(map :login (github/organisation-members client organisation)))
(defn fetch-events [organisation]
(mapcat (partial github/performed-events client) (fetch-users organisation)))
(repo/add db (fetch-events "redbadger"))
(repo/fetch db (-> 2 weeks ago) (now)))
(def events-collection "events")
(def date-time-format (format/formatter :date-time-no-ms))
(defn try-parse-date-time
"Attempts to parse the given value as a date-time.
Returns the value unmodified if it cannot be parsed."
[value]
(try (format/parse date-time-format value)
(catch Exception _ value)))
(defn parse-date-times
"Traverses the given data structure and parses any date-time strings found within."
[data]
(postwalk try-parse-date-time data))
(defprotocol EventsRepository
(add [_ events] "Saves events.")
(fetch [_ start finish] "Loads events that occurred within the specified time period.
start and finish are dates (not date-times)."))
(extend-type DB
EventsRepository
(add [db events]
(doseq [event events]
(collection/update db
events-collection
{:_id (event :id)}
(-> event (dissoc :id) parse-date-times)
{:upsert true})))
(fetch [db start finish]
(map #(rename-keys % {:_id :id})
(q/with-collection db events-collection
(q/find {:created_at
{"$gte" (-> start to-date-time with-time-at-start-of-day)
"$lte" (-> finish to-date-time .millisOfDay .withMaximumValue)}})
(q/sort (array-map :created_at 1))))))
(defn connect
"Connects to MongoDB and returns the database client."
([] (connect (env :mongodb-uri)))
([uri] (doto (:db (mongo/connect-via-uri uri))
(collection/ensure-index events-collection {:created_at 1}))))
(defn- get-date-interval [year month]
(let [start (t/date-time year month)
end (-> start
(t/plus (t/months 1))
(t/minus (t/days 1)))]
[start end]))
(defn get-events-for-month [db year month]
(let [[start end] (get-date-interval year month)]
(fetch db start end)))
| |
983765d05ed2745d823da376382f32c0e7aa2e00bbab4aba3365f7a8952df256 | amnh/PCG | ParEnabledNode.hs | # LANGUAGE BangPatterns , DeriveGeneric #
module PackingPar.ParEnabledNode (ParEnabledNode (..),
(B..&.)) where
-- | imports
import Control.DeepSeq
import qualified Data.Bits as B
import Data.Either
import Data.List
import Data.Maybe
import qualified Data.Vector as V
import Data.Word
import qualified Data.Map as M
import Debug.Trace
import GHC.Generics
import Packing.CardinalityLookup
import qualified Data.Array.Accelerate as A
import qualified Data.Array.Accelerate.Interpreter as AI
-- | Define the data type:
1 ) all data is stored in vectors
2 ) bits can be packed adaptively ( based on the part of the alphabet used for each character ) or statically ( based on the overall alphabet )
3 ) All data types are words to avoid sign issues , and can be of length 16 or 64
data ParEnabledNode = EmptyPackNode |
A16 {bitsA16 :: (V.Vector Word16), parMode :: ParMode} |
S16 {bitsS16 :: (V.Vector Word16), parMode :: ParMode} |
A64 {bitsA64 :: (V.Vector Word64), parMode :: ParMode} |
S64 {bitsS64 :: (V.Vector Word64), parMode :: ParMode}
SInf { bitsSInf : : BV.BitVector , parMode : : ParMode }
deriving (Eq, Generic, Show)
data ParMode = GPU | CPU | Normal deriving (Eq, Generic, Show)
instance NFData ParEnabledNode
instance NFData BV.BV where
( \ ! _ - > ( ) ) bv
instance NFData ParMode
cpuCores = 8
gpuCores = 100
| make the cardinality table and the masks for 64 bit cardinality
-- All cardinalities except for the "infinite" type are from the stored table
cardTable :: V.Vector Int
cardTable = makeLookup
fth16, thd16, snd16, fst16 :: Word64
fth16 = (foldr (\i acc -> acc + 2^i) (0 :: Word64) ([48 .. 64] :: [Int]))
thd16 = (foldr (\i acc -> acc + 2^i) (0 :: Word64) ([32 .. 47] :: [Int]))
snd16 = (foldr (\i acc -> acc + 2^i) (0 :: Word64) ([16 .. 31] :: [Int]))
fst16 = (foldr (\i acc -> acc + 2^i) (0 :: Word64) ([0 .. 15] :: [Int]))
allSelect :: V.Vector Word64
allSelect = V.fromList [fst16, snd16, thd16, fth16]
-- | Make the instance
instance Bits ParEnabledNode where
-- | And function: throws errors for different length bits, and of any empty node returns an empty
instance B.Bits ParEnabledNode where
(.&.) node1 node2
| parMode node1 /= parMode node2 = error "Parallel modes do not match"
| (parMode node1) == GPU = gpuParTwo16 (B..&.) node1 node2
| ( parMode node1 ) = = CPU = cpuParTwo ( B .. & . )
| ( parMode node1 ) = = Normal = parTwo ( B .. & . )
| otherwise = error "Unrecognized mode error"
gpuParTwo16 :: (A.IsIntegral a, B.Bits a, A.IsNum a, A.IsScalar a, A.Elt a) => (A.Exp a-> A.Exp a-> A.Exp a) -> ParEnabledNode -> ParEnabledNode -> ParEnabledNode
gpuParTwo16 f EmptyPackNode _ = EmptyPackNode
gpuParTwo16 f _ EmptyPackNode = EmptyPackNode
gpuParTwo f ( SInf _ _ ) ( SInf _ _ ) = error " Can not GPU parallelize over a built - in bitvector "
gpuParTwo16 f (A16 inBits1 _) (A16 inBits2 _) =
let
shape = A.Z A.:. (V.length inBits1)
array1 = A.fromList shape (V.toList inBits1) -- :: A.Vector A.Word16
array2 = A.fromList shape (V.toList inBits2) -- :: A.Vector A.Word16
b | (V.length inBits1) /= (V.length inBits2) = error "Attempt to take and of bits of different lengths"
| otherwise = AI.run $ A.zipWith (f) (A.use array1) (A.use array2)
in A16 {bitsA16 = V.fromList $ A.toList b}
gpuParTwo16 f (S16 inBits1 _) (S16 inBits2 _) =
let
shape = A.Z A.:. (V.length inBits1)
array1 = A.fromList shape (V.toList inBits1) :: A.Vector A.Word16
array2 = A.fromList shape (V.toList inBits2) :: A.Vector A.Word16
b | (V.length inBits1) /= (V.length inBits2) = error "Attempt to take and of bits of different lengths"
| otherwise = AI.run $ A.zipWith (\b1 b2 ->f b1 b2) (A.use array1) (A.use array2)
in S16 {bitsS16 = V.fromList $ A.toList b}
gpuParTwo64 :: (A.Exp Word64 -> A.Exp Word64 -> A.Exp Word64) -> ParEnabledNode -> ParEnabledNode -> ParEnabledNode
gpuParTwo64 f EmptyPackNode _ = EmptyPackNode
gpuParTwo64 f _ EmptyPackNode = EmptyPackNode
gpuParTwo64 f (A64 inBits1 _) (A64 inBits2 _) =
let
shape = A.Z A.:. (V.length inBits1)
array1 = A.fromList shape (V.toList inBits1) :: A.Vector A.Word64
array2 = A.fromList shape (V.toList inBits2) :: A.Vector A.Word64
b | (V.length inBits1) /= (V.length inBits2) = error "Attempt to take and of bits of different lengths"
| otherwise = AI.run $ A.zipWith (\b1 b2 ->f b1 b2) (A.use array1) (A.use array2)
in A64 {bitsA64 = V.fromList $ A.toList b}
gpuParTwo64 f (S64 inBits1 _) (S64 inBits2 _) =
let
shape = A.Z A.:. (V.length inBits1)
array1 = A.fromList shape (V.toList inBits1) :: A.Vector A.Word64
array2 = A.fromList shape (V.toList inBits2) :: A.Vector A.Word64
b | (V.length inBits1) /= (V.length inBits2) = error "Attempt to take and of bits of different lengths"
| otherwise = AI.run $ A.zipWith (\b1 b2 ->f b1 b2) (A.use array1) (A.use array2)
in S64 {bitsS64 = V.fromList $ A.toList b}
cpuParTwo :: (a -> a -> a) -> ParEnabledNode -> ParEnabledNode -> ParEnabledNode
cpuParTwo _ _ _ = undefined
parTwo :: (a -> a -> a) -> ParEnabledNode -> ParEnabledNode -> ParEnabledNode
parTwo _ _ _ = undefined
| null | https://raw.githubusercontent.com/amnh/PCG/3a1b6bdde273ed4dc09717623986e1144b006904/prototype/PackingPar/ParEnabledNode.hs | haskell | | imports
| Define the data type:
All cardinalities except for the "infinite" type are from the stored table
| Make the instance
| And function: throws errors for different length bits, and of any empty node returns an empty
:: A.Vector A.Word16
:: A.Vector A.Word16 | # LANGUAGE BangPatterns , DeriveGeneric #
module PackingPar.ParEnabledNode (ParEnabledNode (..),
(B..&.)) where
import Control.DeepSeq
import qualified Data.Bits as B
import Data.Either
import Data.List
import Data.Maybe
import qualified Data.Vector as V
import Data.Word
import qualified Data.Map as M
import Debug.Trace
import GHC.Generics
import Packing.CardinalityLookup
import qualified Data.Array.Accelerate as A
import qualified Data.Array.Accelerate.Interpreter as AI
1 ) all data is stored in vectors
2 ) bits can be packed adaptively ( based on the part of the alphabet used for each character ) or statically ( based on the overall alphabet )
3 ) All data types are words to avoid sign issues , and can be of length 16 or 64
data ParEnabledNode = EmptyPackNode |
A16 {bitsA16 :: (V.Vector Word16), parMode :: ParMode} |
S16 {bitsS16 :: (V.Vector Word16), parMode :: ParMode} |
A64 {bitsA64 :: (V.Vector Word64), parMode :: ParMode} |
S64 {bitsS64 :: (V.Vector Word64), parMode :: ParMode}
SInf { bitsSInf : : BV.BitVector , parMode : : ParMode }
deriving (Eq, Generic, Show)
data ParMode = GPU | CPU | Normal deriving (Eq, Generic, Show)
instance NFData ParEnabledNode
instance NFData BV.BV where
( \ ! _ - > ( ) ) bv
instance NFData ParMode
cpuCores = 8
gpuCores = 100
| make the cardinality table and the masks for 64 bit cardinality
cardTable :: V.Vector Int
cardTable = makeLookup
fth16, thd16, snd16, fst16 :: Word64
fth16 = (foldr (\i acc -> acc + 2^i) (0 :: Word64) ([48 .. 64] :: [Int]))
thd16 = (foldr (\i acc -> acc + 2^i) (0 :: Word64) ([32 .. 47] :: [Int]))
snd16 = (foldr (\i acc -> acc + 2^i) (0 :: Word64) ([16 .. 31] :: [Int]))
fst16 = (foldr (\i acc -> acc + 2^i) (0 :: Word64) ([0 .. 15] :: [Int]))
allSelect :: V.Vector Word64
allSelect = V.fromList [fst16, snd16, thd16, fth16]
instance Bits ParEnabledNode where
instance B.Bits ParEnabledNode where
(.&.) node1 node2
| parMode node1 /= parMode node2 = error "Parallel modes do not match"
| (parMode node1) == GPU = gpuParTwo16 (B..&.) node1 node2
| ( parMode node1 ) = = CPU = cpuParTwo ( B .. & . )
| ( parMode node1 ) = = Normal = parTwo ( B .. & . )
| otherwise = error "Unrecognized mode error"
gpuParTwo16 :: (A.IsIntegral a, B.Bits a, A.IsNum a, A.IsScalar a, A.Elt a) => (A.Exp a-> A.Exp a-> A.Exp a) -> ParEnabledNode -> ParEnabledNode -> ParEnabledNode
gpuParTwo16 f EmptyPackNode _ = EmptyPackNode
gpuParTwo16 f _ EmptyPackNode = EmptyPackNode
gpuParTwo f ( SInf _ _ ) ( SInf _ _ ) = error " Can not GPU parallelize over a built - in bitvector "
gpuParTwo16 f (A16 inBits1 _) (A16 inBits2 _) =
let
shape = A.Z A.:. (V.length inBits1)
b | (V.length inBits1) /= (V.length inBits2) = error "Attempt to take and of bits of different lengths"
| otherwise = AI.run $ A.zipWith (f) (A.use array1) (A.use array2)
in A16 {bitsA16 = V.fromList $ A.toList b}
gpuParTwo16 f (S16 inBits1 _) (S16 inBits2 _) =
let
shape = A.Z A.:. (V.length inBits1)
array1 = A.fromList shape (V.toList inBits1) :: A.Vector A.Word16
array2 = A.fromList shape (V.toList inBits2) :: A.Vector A.Word16
b | (V.length inBits1) /= (V.length inBits2) = error "Attempt to take and of bits of different lengths"
| otherwise = AI.run $ A.zipWith (\b1 b2 ->f b1 b2) (A.use array1) (A.use array2)
in S16 {bitsS16 = V.fromList $ A.toList b}
gpuParTwo64 :: (A.Exp Word64 -> A.Exp Word64 -> A.Exp Word64) -> ParEnabledNode -> ParEnabledNode -> ParEnabledNode
gpuParTwo64 f EmptyPackNode _ = EmptyPackNode
gpuParTwo64 f _ EmptyPackNode = EmptyPackNode
gpuParTwo64 f (A64 inBits1 _) (A64 inBits2 _) =
let
shape = A.Z A.:. (V.length inBits1)
array1 = A.fromList shape (V.toList inBits1) :: A.Vector A.Word64
array2 = A.fromList shape (V.toList inBits2) :: A.Vector A.Word64
b | (V.length inBits1) /= (V.length inBits2) = error "Attempt to take and of bits of different lengths"
| otherwise = AI.run $ A.zipWith (\b1 b2 ->f b1 b2) (A.use array1) (A.use array2)
in A64 {bitsA64 = V.fromList $ A.toList b}
gpuParTwo64 f (S64 inBits1 _) (S64 inBits2 _) =
let
shape = A.Z A.:. (V.length inBits1)
array1 = A.fromList shape (V.toList inBits1) :: A.Vector A.Word64
array2 = A.fromList shape (V.toList inBits2) :: A.Vector A.Word64
b | (V.length inBits1) /= (V.length inBits2) = error "Attempt to take and of bits of different lengths"
| otherwise = AI.run $ A.zipWith (\b1 b2 ->f b1 b2) (A.use array1) (A.use array2)
in S64 {bitsS64 = V.fromList $ A.toList b}
cpuParTwo :: (a -> a -> a) -> ParEnabledNode -> ParEnabledNode -> ParEnabledNode
cpuParTwo _ _ _ = undefined
parTwo :: (a -> a -> a) -> ParEnabledNode -> ParEnabledNode -> ParEnabledNode
parTwo _ _ _ = undefined
|
32985ad974a08c2532995c4e64420a7101b1b0325da1166d25ac132f2e50b4bb | mbutterick/sugar | stub.rkt | #lang racket/base
(require (for-syntax racket/base racket/syntax))
(provide (all-defined-out))
(begin-for-syntax
(require racket/string racket/format)
(define (make-prefix caller-stx)
(string-join (map ~a (list (syntax-source caller-stx) (syntax-line caller-stx))) ":" #:after-last ":")))
(define-syntax (define-stub-stop stx)
(syntax-case stx ()
[(_ ID)
(with-syntax ([ERROR-ID (format-id stx "~a~a:not-implemented" (make-prefix stx) (syntax->datum #'ID))])
#'(define (ID . args)
(error 'ERROR-ID)))]))
(provide (rename-out [define-stub-stop define-stub]))
(define-syntax (define-stub-go stx)
(syntax-case stx ()
[(_ ID)
(with-syntax ([ERROR-ID (format-id stx "~a~a:not-implemented" (make-prefix stx) (syntax->datum #'ID))])
#'(define (ID . args)
(displayln 'ERROR-ID)))]))
(define-syntax (define-unfinished stx)
(syntax-case stx ()
[(_ (ID . ARGS) . BODY)
(with-syntax ([ID-UNFINISHED (format-id stx "~a~a:unfinished" (make-prefix stx) (syntax->datum #'ID))])
#'(define (ID . ARGS)
(begin . BODY)
(error 'ID-UNFINISHED)))]))
(define-syntax (unfinished stx)
(syntax-case stx ()
[(_)
(with-syntax ([ID-UNFINISHED (format-id stx "~a:~a:~a" (path->string (syntax-source stx)) (syntax-line stx) (syntax->datum #'unfinished))])
#'(error 'ID-UNFINISHED))])) | null | https://raw.githubusercontent.com/mbutterick/sugar/990b0b589274a36a58e27197e771500c5898b5a2/sugar/unstable/stub.rkt | racket | #lang racket/base
(require (for-syntax racket/base racket/syntax))
(provide (all-defined-out))
(begin-for-syntax
(require racket/string racket/format)
(define (make-prefix caller-stx)
(string-join (map ~a (list (syntax-source caller-stx) (syntax-line caller-stx))) ":" #:after-last ":")))
(define-syntax (define-stub-stop stx)
(syntax-case stx ()
[(_ ID)
(with-syntax ([ERROR-ID (format-id stx "~a~a:not-implemented" (make-prefix stx) (syntax->datum #'ID))])
#'(define (ID . args)
(error 'ERROR-ID)))]))
(provide (rename-out [define-stub-stop define-stub]))
(define-syntax (define-stub-go stx)
(syntax-case stx ()
[(_ ID)
(with-syntax ([ERROR-ID (format-id stx "~a~a:not-implemented" (make-prefix stx) (syntax->datum #'ID))])
#'(define (ID . args)
(displayln 'ERROR-ID)))]))
(define-syntax (define-unfinished stx)
(syntax-case stx ()
[(_ (ID . ARGS) . BODY)
(with-syntax ([ID-UNFINISHED (format-id stx "~a~a:unfinished" (make-prefix stx) (syntax->datum #'ID))])
#'(define (ID . ARGS)
(begin . BODY)
(error 'ID-UNFINISHED)))]))
(define-syntax (unfinished stx)
(syntax-case stx ()
[(_)
(with-syntax ([ID-UNFINISHED (format-id stx "~a:~a:~a" (path->string (syntax-source stx)) (syntax-line stx) (syntax->datum #'unfinished))])
#'(error 'ID-UNFINISHED))])) | |
608cfcabca4f43a50bb5e78217d2663e632d43ea4b9fddc045b01846736a7c26 | defaultxr/cl-patterns | event.lisp | ;;;; t/event.lisp - tests for `event' and related functionality.
;;; TODO:
;; FIX: add more
(in-package #:cl-patterns/tests)
(in-suite cl-patterns-tests)
(test event
"Test event functionality"
(is (= 1
(event-value (event :dur 0 :sustain 1) :sustain))
"event returns the wrong sustain when sustain is provided and dur is 0")
(is (= 0.8
(event-value (event) :sustain))
"event returns the wrong default value for sustain")
(is (= 0.5
(event-value (event :dur 0 :legato 0.5) :legato))
"event returns the wrong legato when legato is provided and dur is 0")
(is (= 0.8
(event-value (event) :legato))
"event returns the wrong default value for legato")
(is (= 1
(event-value (event) :dur))
"event returns the wrong default value for dur")
(is (eql :default
(event-value (event) :instrument))
"event returns the wrong default value for instrument")
(is (= (amp-db 0.125)
(event-value (event :amp 0.125) :db))
"event incorrectly converts amp to db")
(is (= (db-amp -7)
(event-value (event :db -7) :amp))
"event incorrectly converts db to amp")
(is (eql :freq
(cadr (multiple-value-list (event-value (event :freq 420) :midinote))))
"event-value does not provide the key it derives its value from as the second return value")
(is (eql :freq
(cadr (multiple-value-list (event-value (event :freq 420) :rate))))
"event-value does not provide the key it derives its value from as the second return value when called for :rate")
(is-true (let ((*clock* (make-clock 9/7)))
(equal (list 9/7 :tempo)
(multiple-value-list (event-value (event) :tempo))))
"event-value doesn't provide :tempo when getting the tempo from *clock*")
(is-true (= 110
(event-value (event :octave 2) :freq))
"(event :octave 2) doesn't set the correct freq"))
(test event-beat
"Test the beat key for events"
(is-true (= 5
(slot-value (event :beat 5) 'cl-patterns::%beat))
"event doesn't set the internal %beat slot correctly")
(is-true (= 2
(slot-value (combine-events
(event :beat 3)
(event :beat 2))
'cl-patterns::%beat))
"combine-events doesn't set the internal %beat slot correctly")
(is-true (= 94
(let ((ev (event)))
(setf (event-value ev :beat) 94)
(slot-value ev 'cl-patterns::%beat)))
"setting an event's :beat key incorrectly sets its %beat slot"))
(test event-equal
"Test event-equal"
(is-true (event-equal (event :dur 1) (event :dur 1))
"event-equal doesn't return true for equivalent events")
(is-false (event-equal (event :dur 1) (event :dur 1 :foo 2))
"event-equal doesn't return false for events with differing keys")
(is-true (event-equal (list (event :foo 1)) (event :foo 1))
"event-equal doesn't consider an event to be equal to a list of the same event"))
(test every-event-equal
"Test every-event-equal"
(is-true (every-event-equal
(list (event :freq 440))
(list (event :freq 440)))
"every-event-equal doesn't return true for two lists of equivalent events")
(is-false (every-event-equal
(list (event :dur 1))
(list))
"every-event-equal doesn't return false for two lists of different length"))
(test events-differing-keys
"Test `events-differing-keys'"
(is-true (equal (list :bar)
(events-differing-keys (event :foo 1 :bar 2) (event :foo 1 :bar 4) (event :foo 1 :bar 5)))
"events-differing-keys doesn't return keys whose values differ")
(is-true (equal (list :foo)
(events-differing-keys (event :foo 1 :bar 5) (event :foo 1 :bar 5) (event :bar 5)))
"events-differing-keys doesn't return keys that are missing from some events"))
(test combine-events
"Test combine-events"
(is-true (event-equal
(event :foo 1 :bar 2 :baz 3)
(combine-events (event :foo 1) (event :bar 2 :baz 3)))
"combine-events doesn't work correctly on two events")
(is-true (event-equal
(event :freq 450 :qux 69 :baz 3)
(combine-events (event :freq 450) (event :qux 69) (event :baz 3)))
"combine-events doesn't work correctly on three events")
(is-true (event-equal
(event :freq 200)
(combine-events (event :freq 200) (event)))
"combine-events doesn't work correctly for empty second event")
(is-true (event-equal
(event :qux 69)
(combine-events (event) (event :qux 69)))
"combine-events doesn't work correctly for empty first event")
(is-true (eop-p (combine-events eop (event :qux 69)))
"combine-events doesn't work correctly for nil first event")
(is-true (eop-p (combine-events (event :foo 1) eop))
"combine-events doesn't work correctly for nil second event")
(is (event-equal (event)
(copy-event (event)))
"copy-event doesn't copy an empty event")
(is (eql 2
(let ((ev1 (event))
(ev2 (event))
(ev3 (event)))
(setf (slot-value ev1 'cl-patterns::%beat) 1
(slot-value ev2 'cl-patterns::%beat) 2)
(slot-value (combine-events ev1 ev2 ev3) 'cl-patterns::%beat)))
"combine-events doesn't propagate the %beat slot")
(is (eql 2
(let ((ev1 (event))
(ev2 (event :beat 2))
(ev3 (event)))
(setf (slot-value ev1 'cl-patterns::%beat) 1
(slot-value ev3 'cl-patterns::%beat) 3)
(beat (combine-events ev1 ev2 ev3))))
"combine-events doesn't prioritize the :beat key over the %beat slot"))
(test split-event-by-lists
"Test split-event-by-lists"
(is-true (every-event-equal
(list (event :foo 1 :bar 1 :baz 3)
(event :foo 1 :bar 2 :baz 4)
(event :foo 1 :bar 1 :baz 5))
(split-event-by-lists (event :foo 1 :bar (list 1 2) :baz (list 3 4 5))))
"split-event-by-lists returns incorrect results")
(is-true (every-event-equal
(list (event :foo 1 :bar 1 :baz 3)
(event :foo 1 :bar 2 :baz 4)
(event :foo 1 :bar 1 :baz 5))
(split-event-by-lists (event :foo (list 1) :bar (list 1 2) :baz (list 3 4 5))))
"split-event-by-lists returns incorrect results if one of the event values is a list of length 1")
(is-true (equal (list 999)
(let ((event (event)))
(setf (beat event) 999)
(mapcar #'beat (split-event-by-lists event))))
"split-event-by-lists doesn't carry over the %beat slot for empty events")
(is-true (equal (list 999 999 999)
(let ((event (event :midinote (list 40 50 60))))
(setf (beat event) 999)
(mapcar #'beat (split-event-by-lists event))))
"split-event-by-lists doesn't carry over the %beat slot for events with lists"))
(test combine-events-via-lists
"Test combine-events-via-lists"
(is-true (event-equal
(event :foo 1 :bar (list 2 3) :qux 4 :baz 5)
(combine-events-via-lists (event :foo 1 :bar 2 :qux 4) (event :foo 1 :bar 3 :baz 5)))
"combine-events-via-lists returns incorrect results"))
| null | https://raw.githubusercontent.com/defaultxr/cl-patterns/e4bcdcf1dff29dcdf83de79ade4412896753a027/t/event.lisp | lisp | t/event.lisp - tests for `event' and related functionality.
TODO:
FIX: add more |
(in-package #:cl-patterns/tests)
(in-suite cl-patterns-tests)
(test event
"Test event functionality"
(is (= 1
(event-value (event :dur 0 :sustain 1) :sustain))
"event returns the wrong sustain when sustain is provided and dur is 0")
(is (= 0.8
(event-value (event) :sustain))
"event returns the wrong default value for sustain")
(is (= 0.5
(event-value (event :dur 0 :legato 0.5) :legato))
"event returns the wrong legato when legato is provided and dur is 0")
(is (= 0.8
(event-value (event) :legato))
"event returns the wrong default value for legato")
(is (= 1
(event-value (event) :dur))
"event returns the wrong default value for dur")
(is (eql :default
(event-value (event) :instrument))
"event returns the wrong default value for instrument")
(is (= (amp-db 0.125)
(event-value (event :amp 0.125) :db))
"event incorrectly converts amp to db")
(is (= (db-amp -7)
(event-value (event :db -7) :amp))
"event incorrectly converts db to amp")
(is (eql :freq
(cadr (multiple-value-list (event-value (event :freq 420) :midinote))))
"event-value does not provide the key it derives its value from as the second return value")
(is (eql :freq
(cadr (multiple-value-list (event-value (event :freq 420) :rate))))
"event-value does not provide the key it derives its value from as the second return value when called for :rate")
(is-true (let ((*clock* (make-clock 9/7)))
(equal (list 9/7 :tempo)
(multiple-value-list (event-value (event) :tempo))))
"event-value doesn't provide :tempo when getting the tempo from *clock*")
(is-true (= 110
(event-value (event :octave 2) :freq))
"(event :octave 2) doesn't set the correct freq"))
(test event-beat
"Test the beat key for events"
(is-true (= 5
(slot-value (event :beat 5) 'cl-patterns::%beat))
"event doesn't set the internal %beat slot correctly")
(is-true (= 2
(slot-value (combine-events
(event :beat 3)
(event :beat 2))
'cl-patterns::%beat))
"combine-events doesn't set the internal %beat slot correctly")
(is-true (= 94
(let ((ev (event)))
(setf (event-value ev :beat) 94)
(slot-value ev 'cl-patterns::%beat)))
"setting an event's :beat key incorrectly sets its %beat slot"))
(test event-equal
"Test event-equal"
(is-true (event-equal (event :dur 1) (event :dur 1))
"event-equal doesn't return true for equivalent events")
(is-false (event-equal (event :dur 1) (event :dur 1 :foo 2))
"event-equal doesn't return false for events with differing keys")
(is-true (event-equal (list (event :foo 1)) (event :foo 1))
"event-equal doesn't consider an event to be equal to a list of the same event"))
(test every-event-equal
"Test every-event-equal"
(is-true (every-event-equal
(list (event :freq 440))
(list (event :freq 440)))
"every-event-equal doesn't return true for two lists of equivalent events")
(is-false (every-event-equal
(list (event :dur 1))
(list))
"every-event-equal doesn't return false for two lists of different length"))
(test events-differing-keys
"Test `events-differing-keys'"
(is-true (equal (list :bar)
(events-differing-keys (event :foo 1 :bar 2) (event :foo 1 :bar 4) (event :foo 1 :bar 5)))
"events-differing-keys doesn't return keys whose values differ")
(is-true (equal (list :foo)
(events-differing-keys (event :foo 1 :bar 5) (event :foo 1 :bar 5) (event :bar 5)))
"events-differing-keys doesn't return keys that are missing from some events"))
(test combine-events
"Test combine-events"
(is-true (event-equal
(event :foo 1 :bar 2 :baz 3)
(combine-events (event :foo 1) (event :bar 2 :baz 3)))
"combine-events doesn't work correctly on two events")
(is-true (event-equal
(event :freq 450 :qux 69 :baz 3)
(combine-events (event :freq 450) (event :qux 69) (event :baz 3)))
"combine-events doesn't work correctly on three events")
(is-true (event-equal
(event :freq 200)
(combine-events (event :freq 200) (event)))
"combine-events doesn't work correctly for empty second event")
(is-true (event-equal
(event :qux 69)
(combine-events (event) (event :qux 69)))
"combine-events doesn't work correctly for empty first event")
(is-true (eop-p (combine-events eop (event :qux 69)))
"combine-events doesn't work correctly for nil first event")
(is-true (eop-p (combine-events (event :foo 1) eop))
"combine-events doesn't work correctly for nil second event")
(is (event-equal (event)
(copy-event (event)))
"copy-event doesn't copy an empty event")
(is (eql 2
(let ((ev1 (event))
(ev2 (event))
(ev3 (event)))
(setf (slot-value ev1 'cl-patterns::%beat) 1
(slot-value ev2 'cl-patterns::%beat) 2)
(slot-value (combine-events ev1 ev2 ev3) 'cl-patterns::%beat)))
"combine-events doesn't propagate the %beat slot")
(is (eql 2
(let ((ev1 (event))
(ev2 (event :beat 2))
(ev3 (event)))
(setf (slot-value ev1 'cl-patterns::%beat) 1
(slot-value ev3 'cl-patterns::%beat) 3)
(beat (combine-events ev1 ev2 ev3))))
"combine-events doesn't prioritize the :beat key over the %beat slot"))
(test split-event-by-lists
"Test split-event-by-lists"
(is-true (every-event-equal
(list (event :foo 1 :bar 1 :baz 3)
(event :foo 1 :bar 2 :baz 4)
(event :foo 1 :bar 1 :baz 5))
(split-event-by-lists (event :foo 1 :bar (list 1 2) :baz (list 3 4 5))))
"split-event-by-lists returns incorrect results")
(is-true (every-event-equal
(list (event :foo 1 :bar 1 :baz 3)
(event :foo 1 :bar 2 :baz 4)
(event :foo 1 :bar 1 :baz 5))
(split-event-by-lists (event :foo (list 1) :bar (list 1 2) :baz (list 3 4 5))))
"split-event-by-lists returns incorrect results if one of the event values is a list of length 1")
(is-true (equal (list 999)
(let ((event (event)))
(setf (beat event) 999)
(mapcar #'beat (split-event-by-lists event))))
"split-event-by-lists doesn't carry over the %beat slot for empty events")
(is-true (equal (list 999 999 999)
(let ((event (event :midinote (list 40 50 60))))
(setf (beat event) 999)
(mapcar #'beat (split-event-by-lists event))))
"split-event-by-lists doesn't carry over the %beat slot for events with lists"))
(test combine-events-via-lists
"Test combine-events-via-lists"
(is-true (event-equal
(event :foo 1 :bar (list 2 3) :qux 4 :baz 5)
(combine-events-via-lists (event :foo 1 :bar 2 :qux 4) (event :foo 1 :bar 3 :baz 5)))
"combine-events-via-lists returns incorrect results"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.